fluxflow-cli 2.7.6 → 2.7.8
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.
- package/dist/fluxflow.js +199 -199
- package/package.json +1 -1
package/dist/fluxflow.js
CHANGED
|
@@ -1,23 +1,23 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var Nc=Object.defineProperty;var ae=(e,t)=>()=>(e&&(t=e(e=0)),t);var
|
|
2
|
+
var Nc=Object.defineProperty;var ae=(e,t)=>()=>(e&&(t=e(e=0)),t);var ss=(e,t)=>{for(var o in t)Nc(e,o,{get:t[o],enumerable:!0})};var Ca={};ss(Ca,{ACTIVE_TX_FILE:()=>In,BACKUPS_DIR:()=>kn,CONTEXT_FILE:()=>cn,DATA_DIR:()=>er,FLUXFLOW_DIR:()=>Zn,HISTORY_FILE:()=>tr,LEDGER_FILE:()=>Do,LOGS_DIR:()=>To,MEMORIES_FILE:()=>Ht,PARSER_DIR:()=>Mn,PATHS_FILE:()=>is,SECRET_DIR:()=>bt,SETTINGS_FILE:()=>lo,TEMP_MEM_CHAT_FILE:()=>Vo,TEMP_MEM_FILE:()=>So,USAGE_FILE:()=>Zt});import Bc from"os";import co from"path";import Sa from"fs";import Ea from"crypto";var Zn,lo,ba,er,To,bt,tr,Zt,Ht,So,Vo,kn,Do,In,is,cn,Mn,Pt=ae(()=>{Zn=co.join(Bc.homedir(),".fluxflow"),lo=co.join(Zn,"settings.json"),ba=null;try{if(Sa.existsSync(lo)){let e=Sa.readFileSync(lo,"utf8").trim(),t;if(e.startsWith("{"))t=JSON.parse(e);else{let o=e.split(":");if(o.length===2){let n=Buffer.from(o[0],"hex"),r=o[1],s=Ea.createHash("sha256").update("fluxflow-cli-sanctuary-key").digest(),i=Ea.createDecipheriv("aes-256-cbc",s,n),u=i.update(r,"hex","utf8");u+=i.final("utf8"),t=JSON.parse(u)}}if(t){let o=t.systemSettings||{};o.useExternalData&&o.externalDataPath&&(ba=o.externalDataPath)}}}catch{}er=ba||Zn,To=co.join(er,"logs"),bt=co.join(er,"secret"),tr=co.join(bt,"history.json"),Zt=co.join(Zn,"usage.json"),Ht=co.join(bt,"memories.json"),So=co.join(bt,"memory-temp.json"),Vo=co.join(bt,"temp-memory-chat.json"),kn=co.join(er,"backups"),Do=co.join(bt,"ledger.json"),In=co.join(bt,"active_tx.json"),is=co.join(bt,"path.json"),cn=co.join(bt,"context.json"),Mn=co.join(er,"parsers")});import $r from"fs";import zs from"path";import as from"crypto";var Rc,Uc,Wc,ka,Ia,_r,An,pe,De,ls,cs,Oo=ae(()=>{Rc=66,Uc=!1,Wc=e=>{let t=Buffer.isBuffer(e)?e:Buffer.from(e),o=Buffer.alloc(t.length);for(let n=0;n<t.length;n++)o[n]=t[n]^Rc;return o},ka="aes-256-cbc",Ia=as.createHash("sha256").update("fluxflow-cli-sanctuary-key").digest(),_r=e=>{if(Uc)return e;let t=as.randomBytes(16),o=as.createCipheriv(ka,Ia,t),n=o.update(e,"utf8","hex");return n+=o.final("hex"),t.toString("hex")+":"+n},An=e=>{let t=e.split(":");if(t.length!==2)throw new Error("Invalid AES format");let o=Buffer.from(t[0],"hex"),n=t[1],r=as.createDecipheriv(ka,Ia,o),s=r.update(n,"hex","utf8");return s+=r.final("utf8"),s},pe=(e,t={})=>{try{if(!$r.existsSync(e))return t;let o=$r.readFileSync(e),n=o.toString("utf8").trim();if(n.startsWith("{")||n.startsWith("["))return JSON.parse(n);try{let s=An(n);return JSON.parse(s)}catch{}let r=Wc(o).toString("utf8");if(r.startsWith("{")||r.startsWith("["))return JSON.parse(r);throw new Error("Unsupported or corrupt encryption format")}catch(o){return console.error(`Vault Read Error [${zs.basename(e)}]:`,o.message),t}},De=(e,t)=>{try{let o=zs.dirname(e);$r.existsSync(o)||$r.mkdirSync(o,{recursive:!0});let n=JSON.stringify(t,null,2),r=_r(n);$r.writeFileSync(e,r,"utf8")}catch(o){console.error(`Vault Write Error [${zs.basename(e)}]:`,o.message)}},ls=pe,cs=De});var ms={};ss(ms,{getAPIKey:()=>Hc,getProviderAPIKey:()=>us,getSearchSecrets:()=>Kc,getSecret:()=>Gc,removeAPIKey:()=>Js,removeSecret:()=>Ma,saveAPIKey:()=>Xc,saveProviderAPIKey:()=>ds,saveSearchId:()=>qc,saveSearchKey:()=>Vc,saveSecret:()=>un});import Yc from"fs-extra";import jc from"path";var vn,Hc,us,ds,Gc,un,Kc,Xc,Vc,qc,Ma,Js,Nr=ae(()=>{Oo();Pt();vn=jc.join(bt,"secrets.json"),Hc=async()=>{try{let e=pe(vn,{});if(e.API_KEY)return e.API_KEY}catch{}return null},us=async e=>{try{let t=pe(vn,{});if(e==="Google")return t.GOOGLE_API_KEY||t.API_KEY||null;if(e==="DeepSeek")return t.DEEPSEEK_API_KEY||null;if(e==="OpenRouter")return t.OPENROUTER_API_KEY||null;if(e==="NVIDIA")return t.NVIDIA_API_KEY||null}catch{}return null},ds=async(e,t)=>{e==="Google"?(await un("GOOGLE_API_KEY",t),await un("API_KEY",t)):e==="DeepSeek"?await un("DEEPSEEK_API_KEY",t):e==="OpenRouter"?await un("OPENROUTER_API_KEY",t):e==="NVIDIA"&&await un("NVIDIA_API_KEY",t)},Gc=async e=>{try{return pe(vn,{})[e]||null}catch{return null}},un=async(e,t)=>{await Yc.ensureDir(bt);let o=pe(vn,{});o[e]=t,De(vn,o)},Kc=async()=>{try{let e=pe(vn,{});return{key:e.GOOGLE_API_KEY||e.API_KEY,cx:e.SEARCH_ID}}catch{}return{key:null,cx:null}},Xc=async e=>un("API_KEY",e),Vc=async e=>un("GOOGLE_API_KEY",e),qc=async e=>un("SEARCH_ID",e),Ma=async e=>{try{let t=pe(vn,{});delete t[e],De(vn,t)}catch{}},Js=async()=>Ma("API_KEY")});var Aa={};ss(Aa,{loadSettings:()=>hr,saveSettings:()=>Dn});import Br from"fs-extra";import Qs from"path";var fr,hr,zc,Dn,fs=ae(()=>{Pt();Oo();fr={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:""}},hr=async()=>{let e={...fr};try{if(await Br.exists(lo)){let t=ls(lo);if(t.imageSettings&&t.imageSettings.apiKey)try{let o=t.imageSettings.apiKey,{saveSecret:n}=await Promise.resolve().then(()=>(Nr(),ms));await n("POLLINATIONS_API_KEY",o),t.imageSettings.apiKey="",cs(lo,t)}catch{}e={...fr,...t,quotas:{...fr.quotas,...t.quotas},systemSettings:{...fr.systemSettings,...t.systemSettings},profileData:{...fr.profileData,...t.profileData},imageSettings:{...fr.imageSettings,...t.imageSettings}}}}catch(t){console.error("Failed to load settings:",t)}try{let{getSecret:t}=await Promise.resolve().then(()=>(Nr(),ms)),o=await t("POLLINATIONS_API_KEY");o&&(e.imageSettings.apiKey=o)}catch{}if(e.showFullThinking===!1){e.showFullThinking=!0;try{cs(lo,e)}catch{}}return e},zc=async e=>{let{FLUXFLOW_DIR:t}=await Promise.resolve().then(()=>(Pt(),Ca)),o=["logs","secret"];for(let n of o){let r=Qs.join(t,n),s=Qs.join(e,n);try{await Br.exists(r)&&(await Br.ensureDir(s),await Br.copy(r,s,{overwrite:!0}))}catch(i){console.error(`Migration failed for ${n}:`,i)}}},Dn=async e=>{try{let t=await hr();if(!t.systemSettings.useExternalData&&e.systemSettings?.useExternalData&&e.systemSettings?.externalDataPath&&await zc(e.systemSettings.externalDataPath),e.imageSettings&&e.imageSettings.apiKey!==void 0){let{saveSecret:n,removeSecret:r}=await Promise.resolve().then(()=>(Nr(),ms)),s=e.imageSettings.apiKey;s?await n("POLLINATIONS_API_KEY",s):await r("POLLINATIONS_API_KEY")}let o={...t,...e};return o.imageSettings&&(o.imageSettings={...o.imageSettings,apiKey:""}),await Br.ensureDir(Qs.dirname(lo)),cs(lo,o),!0}catch(t){return console.error("Failed to save settings:",t),!1}}});import ho,{useState as Wr,useEffect as ti,useMemo as Zs,useCallback as hs,useRef as va}from"react";import{Box as Ur,Spacer as Jc,Text as Rr,useInput as Qc,measureElement as Zc}from"ink";function eu(e,t){return e.replace(/\t/g," ".repeat(t))}function ei(e){return e==null?"":e.replace(/\r\n/g,`
|
|
3
3
|
`).replace(/\r/g,`
|
|
4
|
-
`)}var Da,tu,Oa,La=ae(()=>{Da=({children:e,onHeightChange:t})=>{let o=va(null),n=va(void 0);return ti(()=>{if(o.current){let{height:
|
|
5
|
-
`)+1,
|
|
4
|
+
`)}var Da,tu,Oa,La=ae(()=>{Da=({children:e,onHeightChange:t})=>{let o=va(null),n=va(void 0);return ti(()=>{if(o.current){let{height:r}=Zc(o.current);n.current!==r&&(n.current=r,t?.(r))}}),ho.createElement(Ur,{ref:o,flexShrink:0,flexGrow:0,width:"100%"},e)},tu=({value:e,rows:t,maxRows:o,highlightStyle:n,textStyle:r,placeholder:s="",mask:i,showCursor:u=!0,focus:f=!0,tabSize:m=4,cursorIndex:c=0,highlight:a,refreshKey:d})=>{let[h,p]=Wr(0),[y,T]=Wr(0),[w,E]=Wr(0),A=hs((M,P=!1)=>{let j=ei(M);if(!P&&i)return j.replace(/[^\n]/g,i);let G=eu(j,m);return P?G:G.replace(/@\[(.*?)\]/g,(q,Y)=>{let N=Y.indexOf("#"),ge=Y.indexOf(":L"),ee=Y,Me="";N!==-1?(ee=Y.slice(0,N),Me=Y.slice(N)):ge!==-1&&(ee=Y.slice(0,ge),Me=Y.slice(ge));let ce=ee.replace(/\\/g,"/"),ue=(process.cwd()||"").replace(/\\/g,"/");ue&&ce.toLowerCase().startsWith(ue.toLowerCase()+"/")?ce=ce.slice(ue.length+1):ce.startsWith("./")&&(ce=ce.slice(2));let Xe=ce.split("/");return`[${Xe[Xe.length-1]}${Me}]`})},[m,i]),{preCursor:$,postCursor:W}=Zs(()=>{if(!e)return s&&!f?{preCursor:[{value:A(s,!0),type:"placeholder"}],postCursor:[]}:{preCursor:[{value:u&&f?" ":"",type:"cursor"}],postCursor:[]};let M=e.slice(0,c),P=e[c]||" ",j=e.slice(c+1);if(!f)return{preCursor:[{value:A(e)}],postCursor:[]};if(a&&a.end>a.start&&a.start>=0&&a.end<=e.length)return{preCursor:[{value:A(e.slice(0,Math.min(c,a.start)))},{value:A(e.slice(Math.max(0,a.start),Math.min(a.end,c))),type:"highlight"},{value:A(e.slice(Math.max(a.end,0),c))},{value:A(P),type:"cursor"}],postCursor:[{value:A(e.slice(c+1,Math.max(c+1,a.start)))},{value:A(e.slice(Math.max(c+1,a.start),Math.max(c+1,a.end))),type:"highlight"},{value:A(e.slice(Math.max(c+1,a.end)))}]};{let q=A(M),Y=A(j),N=q.lastIndexOf(`
|
|
5
|
+
`)+1,ge=Y.indexOf(`
|
|
6
6
|
`)===-1?Y.length:Y.indexOf(`
|
|
7
|
-
`);return{preCursor:[{value:q.slice(0,N)},{value:q.slice(N),type:"highlight"},{value:A(P),type:"cursor"}],postCursor:[{value:Y.slice(0,
|
|
8
|
-
`),W=Math.max(20,f-10),D=0,O=0,M=0;for(let P=0;P<$.length;P++){let G=$[P].length;if(E>=M&&E<=M+G){let Y=E-M;return D+=Math.floor(Y/W),O=Y%W,{visualLine:D,visualCol:O}}let q=Math.max(1,Math.ceil(G/W));D+=q,M+=G+1}return{visualLine:D,visualCol:O}},[e,f]),T=
|
|
9
|
-
`),D=Math.max(20,f-10),O=0,M=0;for(let P=0;P<W.length;P++){let G=W[P].length,q=Math.max(1,Math.ceil(G/D));if(E>=O&&E<O+q){let Y=(E-O)*D,N=Math.min(A,G-Y),
|
|
10
|
-
`+e.slice(a);t(O),d(a+1),p(0);return}if(A.tab||A.shift&&A.tab||A.ctrl&&E==="c")return;let D=0;if(E.length>1&&(D=E.length),A.upArrow){if(
|
|
11
|
-
`+e.slice(a);t(O),d(a+1),p(0)}else if(A.backspace||A.delete){if(a>0){let O=e.slice(0,a-1)+e.slice(a);t(O),d(a-1),p(0)}}else if(E){let O=e.slice(0,a)+E+e.slice(a);t(O),d(a+E.length),p(D)}},i);let w=
|
|
12
|
-
`),
|
|
13
|
-
`)},eo=e=>{if(!e&&e!==0)return"0.0k";let t=typeof e=="string"?parseFloat(e):e;return t>=1e6?`${(t/1e6).toFixed(1)}m`:t>=1e3?`${(t/1e3).toFixed(1)}k`:t.toString()},Pa=(e,t=40)=>{if(e=e.replace(ou.homedir(),"~"),!e||e.length<=t)return e;let o=Math.floor((t-3)/2);return e.substring(0,o)+"..."+e.substring(e.length-o)},
|
|
7
|
+
`);return{preCursor:[{value:q.slice(0,N)},{value:q.slice(N),type:"highlight"},{value:A(P),type:"cursor"}],postCursor:[{value:Y.slice(0,ge),type:"highlight"},{value:Y.slice(ge)}]}}},[c,u,f,e,s,i,a,A,d]),D=Zs(()=>y!==void 0?Math.max(t??o??1,Math.min(o??t??1,y)):1,[t,o,y]);ti(()=>{if(w!==void 0&&D!==void 0){let M=w;p(P=>{let j=P,G=P+D;if(M<=j)return Math.max(0,M-1);if(M>G)return M-D;if(y){if(y<D)return 0;if(y<G)return y-D}return P})}},[w,D,y]);let O=hs(M=>{switch(M){case"placeholder":return{...r,dimColor:!0};case"highlight":return n??r;case"cursor":return{...r,color:u&&f?"white":void 0,bold:u&&f,inverse:u&&f};default:return r}},[r,n,u,f]);return ho.createElement(Ur,{height:D,overflow:"hidden",flexDirection:"column",flexGrow:0,flexShrink:0},ho.createElement(Ur,{flexDirection:"column"},ho.createElement(Ur,{height:D,overflowY:"hidden",flexShrink:0,flexDirection:"column"},ho.createElement(Ur,{marginTop:-h,flexDirection:"column"},ho.createElement(Da,{onHeightChange:T},ho.createElement(Rr,null,$?.map((M,P)=>ho.createElement(Rr,{key:P,...O(M.type)},M.value)),W?.map((M,P)=>ho.createElement(Rr,{key:P,...O(M.type)},M.value))))),ho.createElement(Jc,null)),ho.createElement(Da,{onHeightChange:E},ho.createElement(Rr,null,$?.map((M,P)=>ho.createElement(Rr,{key:P,...O(M.type)},M.value))))))},Oa=({value:e,onChange:t,onSubmit:o,keyBindings:n,showCursor:r=!0,highlightPastedText:s=!1,focus:i=!0,lastFocusEventTime:u=0,columns:f=80,useCustomInput:m=(a,d)=>Qc(a,{isActive:d}),...c})=>{let[a,d]=Wr(e.length),[h,p]=Wr(0);ti(()=>{a>e.length&&d(e.length)},[e,a]);let y=hs(E=>{let $=ei(e).split(`
|
|
8
|
+
`),W=Math.max(20,f-10),D=0,O=0,M=0;for(let P=0;P<$.length;P++){let G=$[P].length;if(E>=M&&E<=M+G){let Y=E-M;return D+=Math.floor(Y/W),O=Y%W,{visualLine:D,visualCol:O}}let q=Math.max(1,Math.ceil(G/W));D+=q,M+=G+1}return{visualLine:D,visualCol:O}},[e,f]),T=hs((E,A)=>{let W=ei(e).split(`
|
|
9
|
+
`),D=Math.max(20,f-10),O=0,M=0;for(let P=0;P<W.length;P++){let G=W[P].length,q=Math.max(1,Math.ceil(G/D));if(E>=O&&E<O+q){let Y=(E-O)*D,N=Math.min(A,G-Y),ge=Math.max(0,N);return Math.min(M+Y+ge,M+G)}O+=q,M+=G+1}return e.length},[e,f]);m((E,A)=>{if(E==="\x1B[I"||E==="\x1B[O"||E==="[I"||E==="[O")return;let $=n?.submit??(O=>O.return&&O.ctrl),W=n?.newline??(O=>O.return);if($(A)){o?.(e);return}else if(W(A)){let O=e.slice(0,a)+`
|
|
10
|
+
`+e.slice(a);t(O),d(a+1),p(0);return}if(A.tab||A.shift&&A.tab||A.ctrl&&E==="c")return;let D=0;if(E.length>1&&(D=E.length),A.upArrow){if(r){let{visualLine:O,visualCol:M}=y(a);if(O>0){let P=T(O-1,M);d(P),p(0)}}}else if(A.downArrow){if(r){let{visualLine:O,visualCol:M}=y(a),P=T(O+1,M);P!==a&&(d(P),p(0))}}else if(A.leftArrow)r&&(d(Math.max(0,a-1)),p(0));else if(A.rightArrow)r&&(d(Math.min(e.length,a+1)),p(0));else if(A.return){let O=e.slice(0,a)+`
|
|
11
|
+
`+e.slice(a);t(O),d(a+1),p(0)}else if(A.backspace||A.delete){if(a>0){let O=e.slice(0,a-1)+e.slice(a);t(O),d(a-1),p(0)}}else if(E){let O=e.slice(0,a)+E+e.slice(a);t(O),d(a+E.length),p(D)}},i);let w=Zs(()=>{if(s&&h>1)return{start:Math.max(0,a-h),end:a}},[a,h,s]);return ho.createElement(tu,{...c,value:e,cursorIndex:a,highlight:w,showCursor:r,focus:i})}});import ou from"os";var qo,eo,Pa,ps,gs,xs,or=ae(()=>{qo=(e,t)=>{if(!e)return"";let o=/\x1B\[[0-?]*[ -/]*[@-~]/g,n=e.split(`
|
|
12
|
+
`),r=[];if(t<=5)return e;let s=i=>i.replace(o,"").length;return n.forEach(i=>{if(s(i)<=t){r.push(i);return}let f=i.split(/(\s+)/),m="",c=0,a=i.match(/^(\s*)/),d=a?a[1]:"";f.forEach((h,p)=>{if(h.length===0)return;let y=s(h);if(c+y>t)if(m.trim().length>0)r.push(m.trimEnd()),m=d+h,c=s(m);else if(o.test(h))r.push(h),m=d,c=s(m);else{let T=h;for(;s(T)>t&&t>10;)r.push(T.substring(0,t)),T=T.substring(t);m=T,c=s(m)}else m+=h,c+=y}),(m.trimEnd().length>0||m===d)&&r.push(m.trimEnd())}),r.join(`
|
|
13
|
+
`)},eo=e=>{if(!e&&e!==0)return"0.0k";let t=typeof e=="string"?parseFloat(e):e;return t>=1e6?`${(t/1e6).toFixed(1)}m`:t>=1e3?`${(t/1e3).toFixed(1)}k`:t.toString()},Pa=(e,t=40)=>{if(e=e.replace(ou.homedir(),"~"),!e||e.length<=t)return e;let o=Math.floor((t-3)/2);return e.substring(0,o)+"..."+e.substring(e.length-o)},ps=e=>{let t=[],o=new Set;Object.keys(e).forEach(r=>{let s=r.match(/^(replaceContent|newContent|content_to_replace|content_to_add)(\d+)?$/);if(s){let i=s[2]?parseInt(s[2]):1;o.add(i)}});let n=Array.from(o).sort((r,s)=>r-s);for(let r of n){let s,i;if(r===1?(s=e.replaceContent1??e.content_to_replace??e.replaceContent,i=e.newContent1??e.content_to_add??e.newContent):(s=e[`replaceContent${r}`]??e[`content_to_replace${r}`],i=e[`newContent${r}`]??e[`content_to_add${r}`]),s!==void 0&&i!==void 0)t.push({replace:s,new:i});else if(s!==void 0||i!==void 0)return{error:`Mismatched replacement pair for index ${r}. Both replacement and new content must be provided.`}}return{patchPairs:t}},gs=(e,t)=>{let o=e.replace(/\r\n/g,`
|
|
14
14
|
`).replace(/\r/g,`
|
|
15
15
|
`),n=y=>y.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
|
|
16
16
|
`).replace(/\r/g,`
|
|
17
|
-
`),
|
|
18
|
-
`).filter(E=>E.trim()!=="");if(T.length===0)return"";let w=
|
|
19
|
-
`).filter(
|
|
20
|
-
`).map((q,Y)=>{if(q.trim()===""&&Y!==0)return"";let N=q.match(/^\s*/)[0].length/$.size,
|
|
17
|
+
`),r=y=>y.match(/^\s*/)[0],s=y=>{let T=y.split(`
|
|
18
|
+
`).filter(E=>E.trim()!=="");if(T.length===0)return"";let w=r(T[0]);for(let E of T){let A=r(E);A.length<w.length&&(w=A)}return w},i=(y,T,w="")=>{if(!y||T===void 0)return y;let E=q=>{let Y=q.split(`
|
|
19
|
+
`).filter(ce=>ce.trim()!=="");if(Y.length===0)return{char:" ",size:4};let N=Y[0].match(/^\s*/)[0];if(N.includes(" "))return{char:" ",size:1};let ge=Y.map(ce=>ce.match(/^\s*/)[0].length).filter(ce=>ce>0);if(ge.length===0)return{char:" ",size:N.length||4};let ee=(ce,ue)=>ue?ee(ue,ce%ue):ce;return{char:" ",size:ge.reduce((ce,ue)=>ee(ce,ue))||4}},A=E(T),$=E(y),W=s(T).length,D=(w.match(/^\s*/)||[""])[0].length,M=(D+W)/A.size,P=s(y).length/$.size,j=M-P;return y.split(`
|
|
20
|
+
`).map((q,Y)=>{if(q.trim()===""&&Y!==0)return"";let N=q.match(/^\s*/)[0].length/$.size,ge=Math.max(0,N+j),ee=ge;if(Y===0){let Me=D/A.size;ee=Math.max(0,ge-Me)}return A.char.repeat(ee*A.size)+q.trimStart()}).join(`
|
|
21
21
|
`)},u=[];for(let y=0;y<t.length;y++){let T=t[y],w=n(T.replace||""),E=n(T.new||"");if(w===""&&E===""){u.push({index:y,success:!1,error:`Block ${y+1}: Empty replace and add content.`});continue}let A=w.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),$=null;if(w!==""&&o.includes(w))$=new RegExp(A,"g");else{let D=w.split(`
|
|
22
22
|
`).map(O=>O.trim()).filter(O=>O.length>0).map(O=>O.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\s+/g,"\\s*"));if(D.length>0){let O=D.join("\\s*");try{$=new RegExp(O,"g")}catch{$=new RegExp(A,"g")}}else $=new RegExp(A,"g")}let W=[...o.matchAll($)];if(W.length===0){u.push({index:y,success:!1,error:`Block ${y+1}: Could not find match.`});continue}if(W.length>1){u.push({index:y,success:!1,error:`Block ${y+1}: Found ${W.length} matches (must be unique).`});continue}u.push({index:y,success:!0,startPos:W[0].index,firstMatchContent:W[0][0],content_to_add:E})}let f=u.filter(y=>y.success).sort((y,T)=>y.startPos-T.startPos);for(let y=0;y<f.length-1;y++){let T=f[y],w=f[y+1];T.startPos+T.firstMatchContent.length>w.startPos&&(T.success=!1,T.error=`Block ${T.index+1}: Overlaps with another block.`,w.success=!1,w.error=`Block ${w.index+1}: Overlaps with another block.`)}let m=new Map,c=o,a=0,d=0,h=u.filter(y=>y.success).sort((y,T)=>y.startPos-T.startPos);for(let y of h){let T=y.startPos,w=o.substring(0,T).split(`
|
|
23
23
|
`).length,E=T+a,A=w+d,$=c.lastIndexOf(`
|
|
@@ -25,54 +25,54 @@ var Nc=Object.defineProperty;var ae=(e,t)=>()=>(e&&(t=e(e=0)),t);var rr=(e,t)=>{
|
|
|
25
25
|
`),M=[];for(let q=Math.max(0,A-4);q<A-1;q++)M.push({num:q+1,text:O[q]});let P=y.firstMatchContent.split(`
|
|
26
26
|
`),j=[],G=A+P.length-1;for(let q=G;q<Math.min(O.length,G+3);q++)j.push({num:q+1,text:O[q]});m.set(y.index,{success:!0,oldContent:y.firstMatchContent,newContent:D,originalStartLine:w,finalStartLine:A,contextBefore:M,contextAfter:j}),c=c.substring(0,E)+D+c.substring(E+y.firstMatchContent.length),a+=D.length-y.firstMatchContent.length,d+=D.split(`
|
|
27
27
|
`).length-y.firstMatchContent.split(`
|
|
28
|
-
`).length}let p=[];for(let y=0;y<t.length;y++)if(m.has(y))p.push(m.get(y));else{let T=u.find(w=>w.index===y);p.push({success:!1,error:T?T.error:`Block ${y+1}: Unknown error.`})}return{content:c,results:p}},
|
|
29
|
-
`,u="\u2550".repeat(88),f=0,m=null,c=o.filter(a=>a.success).sort((a,d)=>a.originalStartLine-d.originalStartLine);if(c.forEach((a,d)=>{let h=a.finalStartLine!==void 0?a.finalStartLine:a.originalStartLine;if(m===null)for(f=Math.max(0,h-4);f<h-1;)i+=`[UI_CONTEXT] ${f+1} |${
|
|
28
|
+
`).length}let p=[];for(let y=0;y<t.length;y++)if(m.has(y))p.push(m.get(y));else{let T=u.find(w=>w.index===y);p.push({success:!1,error:T?T.error:`Block ${y+1}: Unknown error.`})}return{content:c,results:p}},xs=(e,t,o,n=8)=>{if(!o||o.length===0)return"";let r=e.split(/\r?\n/),s=t.split(/\r?\n/),i=`[DIFF_START]
|
|
29
|
+
`,u="\u2550".repeat(88),f=0,m=null,c=o.filter(a=>a.success).sort((a,d)=>a.originalStartLine-d.originalStartLine);if(c.forEach((a,d)=>{let h=a.finalStartLine!==void 0?a.finalStartLine:a.originalStartLine;if(m===null)for(f=Math.max(0,h-4);f<h-1;)i+=`[UI_CONTEXT] ${f+1} |${s[f]||""}
|
|
30
30
|
`,f++;else{let T=m,w=T.originalStartLine+T.oldContent.split(`
|
|
31
|
-
`).length-1;if(a.originalStartLine-w-1>=n){let A=Math.min(
|
|
31
|
+
`).length-1;if(a.originalStartLine-w-1>=n){let A=Math.min(s.length,f+3);for(;f<A;)i+=`[UI_CONTEXT] ${f+1} |${s[f]||""}
|
|
32
32
|
`,f++;for(i+=`[UI_CONTEXT] ${u}
|
|
33
|
-
`,f=Math.max(f,h-4);f<h-1;)i+=`[UI_CONTEXT] ${f+1} |${
|
|
34
|
-
`,f++}else for(;f<h-1;)i+=`[UI_CONTEXT] ${f+1} |${
|
|
33
|
+
`,f=Math.max(f,h-4);f<h-1;)i+=`[UI_CONTEXT] ${f+1} |${s[f]||""}
|
|
34
|
+
`,f++}else for(;f<h-1;)i+=`[UI_CONTEXT] ${f+1} |${s[f]||""}
|
|
35
35
|
`,f++}let p=a.oldContent.split(`
|
|
36
36
|
`);p.forEach((T,w)=>{i+=`-${a.originalStartLine+w}|${T}
|
|
37
37
|
`});let y=f;if(a.finalStartLine!==void 0)y=a.finalStartLine-1+(a.newContent?a.newContent.split(`
|
|
38
|
-
`).length:0);else{let T=a.originalStartLine+p.length-1,w=
|
|
39
|
-
`,f++;m=a}),m!==null){let a=Math.min(
|
|
40
|
-
`,f++}return i+="[DIFF_END]",i}});import Gt from"react";import{Box as On,Text as Ln}from"ink";var
|
|
38
|
+
`).length:0);else{let T=a.originalStartLine+p.length-1,w=r[T]||null;if(w!==null){let E=d<c.length-1?(c[d+1].originalStartLine||s.length)+10:s.length;for(let A=f;A<E;A++){if(s[A]===w){y=A;break}A===s.length-1&&(y=s.length)}}else y=s.length}for(;f<y;)i+=`+${f+1}|${s[f]||""}
|
|
39
|
+
`,f++;m=a}),m!==null){let a=Math.min(s.length,f+3);for(;f<a;)i+=`[UI_CONTEXT] ${f+1} |${s[f]||""}
|
|
40
|
+
`,f++}return i+="[DIFF_END]",i}});import Gt from"react";import{Box as On,Text as Ln}from"ink";var ys,oi=ae(()=>{or();ys=Gt.memo(({command:e,output:t,completed:o=!1,isFocused:n=!1,columns:r=80,isPty:s=!1})=>{let u=(m=>{if(!m)return"";let c=[[]],a=0,d=0,h="",p=/\x1b\[([0-9;]*?)([a-zA-Z])/g,y=0,T,w=A=>{for(let $=0;$<A.length;$++){let W=A[$];if(W===`
|
|
41
41
|
`)for(a++,d=0;a>=c.length;)c.push([]);else if(W==="\r")d=0;else{for(;a>=c.length;)c.push([]);let D=c[a];for(;d>D.length;)D.push({char:" ",style:""});D[d]={char:W,style:h},d++}}};for(;(T=p.exec(m))!==null;){w(m.substring(y,T.index));let A=T[1],$=T[2],W=A?A.split(";").map(Number):[];if($==="A"){let D=W[0]||1;a=Math.max(0,a-D)}else if($==="B"){let D=W[0]||1;for(a=a+D;a>=c.length;)c.push([])}else if($==="C"){let D=W[0]||1;d=d+D}else if($==="D"){let D=W[0]||1;d=Math.max(0,d-D)}else if($==="G"){let D=(W[0]||1)-1;d=Math.max(0,D)}else if($==="H"||$==="f"){let D=(W[0]||1)-1,O=(W[1]||1)-1;for(a=Math.max(0,D),d=Math.max(0,O);a>=c.length;)c.push([])}else if($==="K"){let D=W[0]||0;if(a<c.length){let O=c[a];if(D===0)O.length=d;else if(D===1)for(let M=0;M<d&&M<O.length;M++)O[M]={char:" ",style:""};else D===2&&(O.length=0)}}else if($==="J"){let D=W[0]||0;(D===2||D===3)&&(c.length=0,c.push([]),a=0,d=0)}else if($==="m"){let D=T[0];D==="\x1B[0m"?h="":h=D}y=p.lastIndex}w(m.substring(y));let E=c.map(A=>{let $="",W="";for(let D=0;D<A.length;D++){let O=A[D]||{char:" ",style:""};O.style!==W&&(W&&($+="\x1B[0m"),$+=O.style,W=O.style),$+=O.char}return W&&($+="\x1B[0m"),$});for(;E.length>0&&E[E.length-1]==="";)E.pop();return E.join(`
|
|
42
42
|
`)})(t).replace(/\n{3,}/g,`
|
|
43
43
|
|
|
44
|
-
`),f=
|
|
44
|
+
`),f=s?u:u?qo(u,r-6):"";return Gt.createElement(On,{flexDirection:"column",borderStyle:n?"double":"round",borderColor:"#555555",paddingX:2,paddingY:o?0:1,width:"100%"},Gt.createElement(On,{marginBottom:1,justifyContent:"space-between",width:"100%"},Gt.createElement(On,{flexShrink:1,paddingRight:2},Gt.createElement(Ln,null,Gt.createElement(Ln,{color:"gray",bold:!0},o?"\u{1F3C1} FINISHED:":"\u26A1 EXECUTING:"," "),Gt.createElement(Ln,{color:"white"},e))),s&&Gt.createElement(On,{flexShrink:0,paddingX:1},Gt.createElement(Ln,{color:"gray",bold:!0},"ADVANCE"))),f?Gt.createElement(On,{marginTop:o?0:1,backgroundColor:s?void 0:"#0a0a0a",paddingX:1},Gt.createElement(Ln,{color:o?"gray":void 0},f)):!o&&Gt.createElement(On,{marginTop:1,backgroundColor:s?void 0:"#0a0a0a",paddingX:1},Gt.createElement(Ln,{color:"white",italic:!0},"Waiting for output...")),Gt.createElement(On,{justifyContent:"space-between",marginTop:1},o?Gt.createElement(On,null):Gt.createElement(Ln,{color:"gray",italic:!0},n?"Press TAB to unfocus, then double-press ESC to terminate.":"Double-press ESC to terminate if hanging."),Gt.createElement(Ln,{color:"gray",bold:!0},o?"\u25CF ARCHIVED":n?"\u25B6 TERMINAL FOCUSED":"\u25CF LIVE (Press TAB to focus)")))})});var ni,Fa=ae(()=>{ni=["I have a regex for your problems.","Your terminal, my kingdom.","Blowing on the cartridge helps. Probably.","Don't panic. I have the towel.","Logic is the start of wisdom.","Try to exit Vim? Good luck.","I speak fluent Terminal.","The cake is a lie. This code is not.","I have no bugs, just surprise features.","Rewriting in Rust... just for fun.","Coffee in, clean commits out.","The magic smoke stays inside today.","A semicolon short of a miracle.","One does not simply code without a bug.","Keep it simple. Keep it terminal.","Regex: now you have two problems.","I dream in binary.","Root access or bust.","Wait for the dial-up tone. Just kidding.","I take the 'labor' out of collab.","My other process is a TARDIS.","Calculated response: 42.","Ponder the orb. Ponder the code.","Less talk, more flow.","Elegance in every byte.","Build something the world is not ready for.","Your wishes, my tool calls.","I act in Flux. I think in Flow.","Syntax error in the universe. Please fix.","Your project, my obsession.","I am not a bot, I am an architect.","Digital spirits consulted. They say: Ship it.","Reticulate splines. Engage humor.","Code like poetry. Run like water.","Minimalism is the ultimate flex.","The truth is in the logs.","Follow the white rabbit.","There is no spoon. Only code.","Binary is the only language I trust.","I have a good feeling about this.","Pew pew! Lasers charged.","Divide by zero? Not today.","Search for the correct USB orientation...","I've got a fever, and the only cure is more code.","The code gremlins are on our side.","My favorite command? Yours.","Stay hungry. Stay active.","Momentum is your best friend.","Lead the flow. Don't chase it.","A fresh batch of bytes. Hot and ready.","I orchestrate the ones and zeros.","Smart enough to help. Humble enough to ask.","Think twice. Code once.","Pure intent. Pure execution.","Small steps. Massive impact.","Your terminal is a canvas.","Efficiency is my second name.","I have seen things you people wouldn't believe.","Let the thoughts marinate.","The best feature? The one you don't need.","Precision is the only perfection.","Stay focused. Stay terminal.","Silence is the best debugger.","Erase the debt. Commit the code.","Velocity meets stability.","Ship it. Improve it. Repeat.","Build tomorrow, right now.","Turn logic into reality.","The best way to predict the future is to build it.","Break barriers, not builds.","Fuel the next breakthrough.","Momentum is key.","Terminal vibes only.","Your digital co-pilot is ready.","Partner in code. Partner in crime.","I speak in semicolons.","Ready for the next great idea.","Just a moment. In the zone.","Polishing the algorithms. Hold tight.","Craft a masterpiece today.","Debug the universe. Start here.","Warp speed engaged. Almost.","The cake is not a lie. It's just loading.","Finish the Kessel Run in 12 parsecs.","Do a barrel roll!","Waiting for the respawn.","Press Start to continue.","Herding digital cats... done.","The hamsters are fast today.","Tasting the snozberries.","I go for speed. I go for flow.","Real life or just fantasy?","Poking the bear... gently.","Ensure the magic smoke stays inside.","Try turning it off and on again.","Construct additional pylons.","New line? Ctrl+J is your friend.","Release the HypnoDrones.","Push the button, Frank.","My other loading screen is even funnier.","Pretty sure a cat walked on my keyboard.","Recalibrate the humor-o-meter.","Summon the code gremlins.","I've seen your browser history. Just kidding.","Charge the laser... pew pew!","Dividing by zero... just for a sec.","Looking for an adult supervisor. Found none.","Make it go beep boop.","Buffering... for effect.","Entangle quantum particles... complete.","Polishing the chrome on my algorithms.","Are you not entertained?","Just waiting for the dial-up tone.","Reboot the humor module.","Defragment memories. Check.","Optimizing for ludicrous speed.","Swapping bits. Don't tell the bytes.","Garbage collected. I am back.","Assembling the interwebs.","Converting coffee to logic.","Update syntax for reality.","Rewire the synapses.","Greasin' the cogs.","Engage the improbability drive.","Channel the Force.","Align the stars. Respond now.","The cake is a lie. The prompt is real.","I'm Feeling Lucky.","Shipping awesomeness.","Navigating the slime mold.","Consult digital spirits.","Ask the magic conch shell.","One moment. Optimizing humor.","Shuffling punchlines.","Compiling brilliance.","Summon the cloud of wisdom.","Prepare to dazzle.","Hold tight. Crafting a response.","Tuning the algorithms.","Following the white rabbit... again.","The truth is in here. Somewhere.","Herding cats is my day job.","Distracting you with this phrase.","Almost there. Probably.","Rickrolling my creator. Don't tell.","Slapping the bass.","Is this real life?","Ponder the orb. Type the prompt.","Thoughtful gaze initiated.","Computer's favorite snack? Microchips.","Why Java? Because I don't C#.","Charging the laser... wait for it.","Dividing by zero... just kidding!","Adult supervision not found. Proceed.","Beep boop. I'm a real boy.","Wait for the respawn.","Finish the run. Ship the code.","Fiddling with character creation.","Just a moment. Finding a meme.","Pressing A to continue.","Loading wit.exe.","Pre-heating the servers.","Calibrate flux capacitor.","Channeling the Force.","Aligning the stars.","The truth is in the code.","Don't panic.","Blowing on the cartridge.","Doing a barrel roll!","Respawning in 3... 2... 1...","The cake is a lie.","Fiddling with character settings.","Finding a suitable pun.","Distracting with wit.","Almost ready.","Hamsters on speed today.","Patting Cloudy on the head.","Rickrolling the logs.","Slapping the code.","Got a good feeling about this.","Poking the prompt.","Researching latest memes.","Making it more witty.","Thinking... hmmm.","Fish with no eyes? Fsh.","Broken pencil? Pointless.","Percussive maintenance applied.","USB orientation: 3rd try's the charm.","Rust rewrite in 3... 2...","Exiting Vim... someday.","Spinning the hamster wheel.","Not a bug. Unplanned feature.","Engage.","I'll be back.","Machine spirit consulted.","Letting the thoughts marinate.","Orb pondered.","Thoughtful gaze engaged.","Charging the laser...","Making it go beep.","Buffering...","Quantum particles entangled.","Polishing the chrome.","Entertained yet?","Gremlins summoned.","Dial-up tone finished.","Humor meter recalibrated.","Cat on keyboard. Sending help.","Enhancing...","Turn it off and on again.","Constructing pylons.","HypnoDrones released.","Pushing the button."]});import nu from"gradient-string";var ru,Fe,ws,dn=ae(()=>{Fa();ru=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",Fe=(e=2)=>{let t=ru();return t==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)},ws=(e="2.0.0",t="Google")=>{let o=ni[Math.floor(Math.random()*ni.length)],n=[" \u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2588\u2588\u2588\u2591 "," \u2588\u2588\u2588\u2591 "," \u2588\u2588\u2588\u2591 "," \u2591\u2591\u2591 "],r=nu(["#0077ff","#ff00ff"]).multiline(n.join(`
|
|
45
45
|
`)).split(`
|
|
46
|
-
`),
|
|
47
|
-
${
|
|
48
|
-
${
|
|
49
|
-
${
|
|
50
|
-
${
|
|
51
|
-
${
|
|
52
|
-
${
|
|
53
|
-
${
|
|
46
|
+
`),s=i=>`\x1B[90m${i}\x1B[0m`;return`${r[0]}
|
|
47
|
+
${r[1]} \x1B[1;37mSelected Provider: ${t}\x1B[0m
|
|
48
|
+
${r[2]}
|
|
49
|
+
${r[3]} \x1B[1;37mFLUX FLOW ${s("v"+e)}\x1B[0m
|
|
50
|
+
${r[4]}
|
|
51
|
+
${r[5]} \x1B[37mSee /help for additional commands.\x1B[0m
|
|
52
|
+
${r[6]} ${s(o)}
|
|
53
|
+
${r[7]}`}});import k from"react";import{Box as H,Text as te}from"ink";var su,iu,au,lu,$a,Pn,cu,_a,uu,du,Na,Ba,ri,mu,Ra,Ua=ae(()=>{oi();or();dn();su={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"},iu=e=>{if(!e)return e;let t=e.replace(/<\/think>(\r?\n){2}/gi,"</think>").replace(/(\r?\n){2}(?=\[?(?:tool:functions|tool\.functions|\s*turn\s*:))/gi,""),o="tool:functions.";for(;;){let r=t.toLowerCase().indexOf(o);if(r===-1)break;let s=r,i=!1,u=r-1;for(;u>=0&&/\s/.test(t[u]);)u--;u>=0&&t[u]==="["&&(s=u,i=!0);let f=0,m=!1,c=null,a=r;for(;a<t.length;){let d=t[a];if(!c&&(d==="'"||d==='"'||d==="`")?c=d:c&&d===c&&t[a-1]!=="\\"&&(c=null),c||(d==="("?(f++,m=!0):d===")"&&f--),m&&f===0&&!c){let h=a;if(i){let p=a+1;for(;p<t.length&&/\s/.test(t[p]);)p++;p<t.length&&t[p]==="]"&&(h=p)}t=t.substring(0,s)+t.substring(h+1);break}if(a++,a===t.length)return t=t.substring(0,s),t}}return t.replace(/\[TOOL RESULT\]:?\s*/gi,"").split(`
|
|
54
54
|
`).filter(n=>!n.trim().startsWith("SUCCESS:")&&!n.trim().startsWith("ERROR:")).join(`
|
|
55
|
-
`).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=>
|
|
56
|
-
`),
|
|
55
|
+
`).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=>su[n.toLowerCase()]||n).trim()},au=(e,t=80)=>{if(!e)return null;let o=t-10,n=qo(e.trim(),o);return k.createElement(H,{width:"100%"},k.createElement(te,{italic:!0},k.createElement(Pn,{text:n,color:"gray"})))},lu=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,t=>t.includes("left")?"(":")").replace(/\\left\[|\\right\]/g,t=>t.includes("left")?"[":"]").replace(/\\\{|\\\}/g,t=>t.includes("{")?"{":"}").replace(/\\text\s*\{([^}]+)\}/g,"$1").replace(/\\text\s+(\w+)/g,"$1").replace(/\\%/g,"%"),$a=(e,t)=>{if(!e)return null;let o=e.replace(/\\frac\s*\{([^{}]*)\}\s*\{([^{}]*)\}/g,"($1/$2)");o=lu(o);let n=o.split(/(\\(?:mathbf|textbf|textit|underline|texttt)\{[^{}]*\})/g);return k.createElement(k.Fragment,{key:t},n.map((r,s)=>{if(r.startsWith("\\")){let i=r.match(/\\(\w+)\{([^{}]*)\}/);if(i){let u=i[1],f=i[2];return k.createElement(te,{key:s,bold:u==="mathbf"||u==="textbf",italic:u==="textit",underline:u==="underline",color:u==="texttt"?"cyan":void 0},f)}}return r}))},Pn=k.memo(({text:e,color:t})=>{if(!e)return null;let o=e.split(/(```[\s\S]*?```|`[^`]+`|@\[.*?\]|\*\*.*?\*\*|\*.*?\*|\$.*?\$|\[.*?\]\s*\(.*?\)|\[.*?\]\s*\[.*?\]|https?:\/\/[^\s]+)/g);return k.createElement(te,{color:t,wrap:"anywhere"},o.map((n,r)=>{if(!n)return null;if(n.startsWith("```")&&n.endsWith("```")){let s=n.slice(3,-3);return k.createElement(te,{key:r,color:"cyan"},s)}if(n.startsWith("**")&&n.endsWith("**"))return k.createElement(te,{key:r,bold:!0,color:"white"},k.createElement(Pn,{text:n.slice(2,-2),color:"white"}));if(n.startsWith("*")&&n.endsWith("*"))return k.createElement(te,{key:r,italic:!0,color:"gray"},k.createElement(Pn,{text:n.slice(1,-1),color:"gray"}));if(n.startsWith("`")&&n.endsWith("`")){let s=n.slice(1,-1),i=s.replace(/@\[(.*?)\]/g,(f,m)=>m.split("/").pop().split("\\").pop().replace(/:L/gi,"#L")),u=s.includes("@[");return k.createElement(te,{key:r,color:"cyan",bold:u},i)}if(n.startsWith("@[")&&n.endsWith("]")){let i=n.slice(2,-1).split("/").pop().split("\\").pop().replace(/:L/gi,"#L");return k.createElement(te,{key:r,color:"cyan",bold:!0},i)}if(n.startsWith("$")&&n.endsWith("$")){let s=n.slice(1,-1);return k.createElement(te,{key:r,color:"yellow"},$a(s,r))}if(n.startsWith("[")&&(n.includes("](")||n.includes("] ("))){let s=n.match(/\[(.*?)\]\s*\((.*?)\)/);if(s)return k.createElement(te,{key:r},k.createElement(te,{color:"cyan",underline:!0,bold:!0},s[1]),k.createElement(te,{color:"gray",italic:!0}," (",s[2],")"))}if(n.startsWith("[")&&(n.includes("][")||n.includes("] ["))){let s=n.match(/\[(.*?)\]\s*\[(.*?)\]/);if(s)return k.createElement(te,{key:r},k.createElement(te,{color:"cyan",underline:!0,bold:!0},s[1]),k.createElement(te,{color:"gray",italic:!0}," [",s[2],"]"))}return n.startsWith("http")?k.createElement(te,{key:r,color:"cyan",underline:!0,italic:!0},n):$a(n,r)}))}),cu=k.memo(({buffer:e,terminalWidth:t=80})=>{if(e.length<2)return null;let o=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=o[0],r=o.slice(2),s=Math.floor(100/n.length),i=t-8,u=Math.floor(i/n.length)-2;return k.createElement(H,{flexDirection:"column",borderStyle:"round",borderColor:"#454545ff",paddingX:1,marginY:0,width:"100%",flexGrow:1},k.createElement(H,{flexDirection:"row",borderStyle:"single",borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1,borderColor:"#444",marginBottom:1,paddingBottom:0,width:"100%"},n.map((f,m)=>k.createElement(H,{key:m,flexBasis:`${s}%`,flexGrow:1,flexShrink:0,paddingRight:2},k.createElement(Pn,{text:qo(f,u),color:"cyan"})))),r.map((f,m)=>k.createElement(H,{key:m,flexDirection:"row",marginBottom:m===r.length-1?0:1,width:"100%"},f.map((c,a)=>k.createElement(H,{key:a,flexBasis:`${s}%`,flexGrow:1,flexShrink:0,paddingRight:2,flexDirection:"column"},k.createElement(Pn,{text:qo(c,u),color:"white"}))))))}),_a=k.memo(({text:e,color:t="white",columns:o=80})=>{if(!e)return null;let n=e.split(`
|
|
56
|
+
`),r=[],s=[],i=[],u=f=>{s.length>0&&(r.push(k.createElement(cu,{key:`table-${f}`,buffer:[...s],terminalWidth:o})),s=[]),i.length>0&&(r.push(k.createElement(H,{key:`quote-${f}`,borderStyle:"bold",borderLeft:!0,borderRight:!1,borderTop:!1,borderBottom:!1,borderColor:"gray",paddingLeft:1,marginY:1,flexDirection:"column"},i.map((m,c)=>k.createElement(Pn,{key:c,text:m,color:"gray"})))),i=[])};return n.forEach((f,m)=>{let c=f.trim(),a=c.startsWith("|"),d=c.startsWith(">");if(a)i.length>0&&u(m),s.push(f);else if(d)s.length>0&&u(m),i.push(c.replace(/^>\s*/,""));else{if(u(m),c===""){r.push(k.createElement(H,{key:m,height:1}));return}if(c==="---"||c==="***"||c==="___"){r.push(k.createElement(H,{key:m,marginY:1,borderStyle:"single",borderTop:!0,borderBottom:!1,borderLeft:!1,borderRight:!1,width:"100%",borderColor:"#333"}));return}let h=c.match(/^(#{1,6})\s+(.*)/);if(h){let E=h[1].length,A=h[2];r.push(k.createElement(H,{key:m,marginTop:1,marginBottom:1,width:"100%"},k.createElement(te,{bold:!0,color:E===1?"cyan":E===2?"magenta":E===3?"yellow":E===4?"green":E===5?"blue":"white",underline:!0},A.toUpperCase())));return}let p=c.startsWith("* ")||c.startsWith("- "),y=/^\d+\.\s/.test(c),T=f.includes("\u2588")||f.includes("\u2554")||f.includes("\u255A")||f.includes("\u2550"),w="";if(T)w=f;else if(p||y){let E=p?" \u2022 ":c.match(/^\d+\.\s/)[0],A=" ".repeat(E.length),$=qo(c.replace(/^[\*\-\d+\.]+\s/,""),o-(E.length+6));w=E+$.split(`
|
|
57
57
|
`).join(`
|
|
58
|
-
`+A)}else w=qo(c,o-4);
|
|
59
|
-
`);return k.createElement(H,{flexDirection:"column",width:t-3,marginBottom:0},k.createElement(H,{flexDirection:"column",backgroundColor:"#1a1a1a",paddingY:0,width:"100%"},
|
|
60
|
-
`),c=String(m.length).length;return k.createElement(H,{flexDirection:"column",width:t-3},k.createElement(H,{flexDirection:"column",borderStyle:"round",borderColor:"#444",paddingX:1,width:"100%"},k.createElement(H,{alignSelf:"flex-end",marginTop:-1,marginRight:1},k.createElement(te,{backgroundColor:"#444",color:"white"}," FILE SNAPSHOT ")),k.createElement(H,{flexDirection:"column",paddingY:1,width:"100%"},m.map((a,d)=>k.createElement(H,{key:d,width:"100%"},k.createElement(H,{width:c+2,flexShrink:0},k.createElement(te,{color:"gray",dimColor:!0},String(d+1).padStart(c," ")," ")),k.createElement(H,{flexGrow:1},k.createElement(te,{color:"white"},a)))))))}if(e.includes("```")){let o=e.split(/(```\w*\n?[\s\S]*?(?:```|$))/g);return k.createElement(H,{flexDirection:"column",width:t-3},o.map((n,
|
|
61
|
-
`),c=String(m.length).length;return k.createElement(H,{key:
|
|
62
|
-
`).map((h,p)=>k.createElement(te,{key:p,color:"white"},h)))));if(e.isAskRecord){let h=e.text.match(/Selection: (.*)/),p=h?h[1]:"No selection",y=Fe(2);return k.createElement(H,{marginBottom:0,paddingX:1,width:"100%"},k.createElement(H,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},k.createElement(H,{paddingX:1},k.createElement(te,{color:"cyan",bold:!0},"\u{1F4AC} AGENT REQUEST: RESOLVED")),k.createElement(H,{paddingX:1,marginTop:1,marginBottom:1},k.createElement(te,{color:"white"},"Selection: ",k.createElement(te,{color:"yellow",bold:!0},p)))))}if(e.isAboutRecord)return k.createElement(H,{marginBottom:0,paddingX:1,width:"100%"},k.createElement(H,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},k.createElement(H,{paddingX:1},k.createElement(te,{color:"white",bold:!0},"ABOUT FLUX FLOW")),k.createElement(H,{paddingX:1,marginTop:1,marginBottom:1},k.createElement(te,null,e.text))));if(e.isUpdateNotification)return k.createElement(H,{marginBottom:1,paddingX:1,width:"100%"},k.createElement(H,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},k.createElement(H,{paddingX:1},k.createElement(te,{color:"white",bold:!0},"UPDATE AVAILABLE")),k.createElement(H,{paddingX:1,marginTop:1,marginBottom:1},k.createElement(Na,{text:e.text,columns:o}))));if(e.isHelpRecord)return k.createElement(H,{marginBottom:1,paddingX:1,width:"100%"},k.createElement(H,{flexDirection:"column",borderStyle:"round",borderColor:"magenta",paddingX:2,paddingY:1,width:"100%"},k.createElement(te,{color:"magenta",bold:!0,underline:!0},"\u{1F4DC} COMMAND REFERENCE"),k.createElement(H,{flexDirection:"column",marginTop:1},[{cmd:"/quit",desc:"Exit and shutdown Flux"},{cmd:"/help",desc:"Show all available commands"},{cmd:"/compress",desc:"Summarize and compress chat history"},{cmd:"/clear",desc:"Clear terminal screen"},{cmd:"/resume",desc:"Load previous session"},{cmd:"/revert",desc:"Revert codebase to checkpoint"},{cmd:"/save",desc:"Force save current chat"},{cmd:"/export",desc:"Export current chat 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:"/docs",desc:"View documentation"},{cmd:"/fluxflow",desc:"Project management"},{cmd:"/update",desc:"Check/Install updates"}].map((p,y)=>k.createElement(H,{key:y,flexDirection:"row"},k.createElement(H,{width:15},k.createElement(te,{color:"cyan",bold:!0},p.cmd)),k.createElement(te,{color:"gray"}," - ",p.desc))))));if(e.isTerminalRecord){let h=e.text.match(/COMMAND: (.*)/),p=e.text.match(/PTY: (true|false)/),y=e.text.match(/OUTPUT: ([\s\S]*)/),T=h?h[1]:"Unknown",w=p?p[1]==="true":!1,E=y?y[1]:"";return k.createElement(H,{marginBottom:0,paddingX:1,width:"100%"},k.createElement(
|
|
58
|
+
`+A)}else w=qo(c,o-4);r.push(k.createElement(H,{key:m,width:"100%"},k.createElement(Pn,{text:w,color:t})))}}),u("final"),k.createElement(H,{flexDirection:"column",width:o-2},r)}),uu=k.memo(({line:e,columns:t=80})=>{let o=e.includes("[UI_CONTEXT]"),n=e.replace("[UI_CONTEXT]","");if(o&&n.includes("\u2550"))return k.createElement(H,{backgroundColor:"#1a1a1a",paddingX:1,width:"100%"},k.createElement(te,{color:"gray"},"\u2550".repeat(Math.max(10,t-4))));let r=n.startsWith("-"),s=n.startsWith("+"),i=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=r?"#3a0c0c":s?"#0c3a1a":"#1a1a1a",d=r?"#ff4d4d":s?"#4dff88":"white";return k.createElement(H,{backgroundColor:a,paddingX:1,width:"100%"},k.createElement(H,{width:5,flexShrink:0},k.createElement(te,{color:r?"#cf3a3a":s?"#3acf65":"gray",dimColor:o},m)),k.createElement(H,{width:2,flexShrink:0,marginLeft:1},k.createElement(te,{color:d,bold:!0},r?"-":s?"+":" ")),k.createElement(H,{flexGrow:1,marginLeft:1},k.createElement(te,{color:d,dimColor:o},qo(c,t-14))))}),du=k.memo(({text:e,columns:t=80})=>{let o=e.match(/\[DIFF_START\]([\s\S]*?)\[DIFF_END\]/),r=(o?o[1].trim():"").split(`
|
|
59
|
+
`);return k.createElement(H,{flexDirection:"column",width:t-3,marginBottom:0},k.createElement(H,{flexDirection:"column",backgroundColor:"#1a1a1a",paddingY:0,width:"100%"},r.map((s,i)=>k.createElement(uu,{key:i,line:s,columns:t-3}))))}),Na=k.memo(({text:e,columns:t=80})=>{if(!e)return null;if(e.includes("[DIFF_START]"))return k.createElement(du,{text:e,columns:t});if(e.includes("- Content Preview:")){let o=e.split("- Content Preview:"),n=o[0],r=o[1]||"",s="[SYSTEM] Check the content preview for verification [/SYSTEM]",i=r.split(s),u=i[0]?.trim()||"",f=i[1]?`${s}${i[1]}`:"",m=u.split(`
|
|
60
|
+
`),c=String(m.length).length;return k.createElement(H,{flexDirection:"column",width:t-3},k.createElement(H,{flexDirection:"column",borderStyle:"round",borderColor:"#444",paddingX:1,width:"100%"},k.createElement(H,{alignSelf:"flex-end",marginTop:-1,marginRight:1},k.createElement(te,{backgroundColor:"#444",color:"white"}," FILE SNAPSHOT ")),k.createElement(H,{flexDirection:"column",paddingY:1,width:"100%"},m.map((a,d)=>k.createElement(H,{key:d,width:"100%"},k.createElement(H,{width:c+2,flexShrink:0},k.createElement(te,{color:"gray",dimColor:!0},String(d+1).padStart(c," ")," ")),k.createElement(H,{flexGrow:1},k.createElement(te,{color:"white"},a)))))))}if(e.includes("```")){let o=e.split(/(```\w*\n?[\s\S]*?(?:```|$))/g);return k.createElement(H,{flexDirection:"column",width:t-3},o.map((n,r)=>{if(n.startsWith("```")){let i=n.match(/```(\w*)\n?([\s\S]*?)(?:```|$)/),u=i?i[1]:"code",m=(i?i[2]:n.replace(/^```\w*\n?/,"").replace(/```$/,"")).trimEnd().split(`
|
|
61
|
+
`),c=String(m.length).length;return k.createElement(H,{key:r,flexDirection:"column",marginY:0,borderStyle:"round",borderColor:"#444",paddingX:1,width:"100%"},k.createElement(H,{alignSelf:"flex-end",marginTop:-1,marginRight:1},k.createElement(te,{backgroundColor:"#444",color:"white"}," ",u.toUpperCase()," ")),k.createElement(H,{flexDirection:"column",paddingY:1,width:"100%"},m.map((a,d)=>k.createElement(H,{key:d,width:"100%"},k.createElement(H,{width:c+2,flexShrink:0},k.createElement(te,{color:"gray"},String(d+1).padStart(c," ")," ")),k.createElement(H,{flexGrow:1},k.createElement(te,{color:"#fcfca4ff"},a))))))}let s=n;return r>0&&(s=s.replace(/^[\r\n]+/,"")),r<o.length-1&&(s=s.replace(/[\r\n]+$/,"")),s?k.createElement(_a,{key:r,text:s,columns:t-3}):null}))}return k.createElement(_a,{text:e,columns:t-3})}),Ba=e=>{let t=Math.round(e/1e3);if(t<=0)return"0s";let o=Math.floor(t/60),n=t%60;return o>0?`${o}m ${n}s`:`${t}s`},ri=k.memo(({msg:e,showFullThinking:t,columns:o=80,aiProvider:n,version:r})=>{let s=e.role==="system"&&(e.text?.includes("[DIFF_START]")||e.text?.includes("- Content Preview:")),i=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")),u=e.isTerminalRecord;if(e.isHomeWarning)return k.createElement(H,{marginBottom:1,paddingX:1,width:"100%"},k.createElement(H,{flexDirection:"column",borderStyle:"round",borderColor:"red",padding:0,width:"100%"},k.createElement(H,{paddingX:1,backgroundColor:"#3a0000"},k.createElement(te,{color:"red",bold:!0},e.text)),k.createElement(H,{paddingX:1,marginTop:0,marginBottom:0},k.createElement(te,{color:"white"},e.subText))));if(e.isLogo)return k.createElement(H,{flexDirection:"column",alignItems:"flex-start",width:"100%",marginY:1},k.createElement(te,null,ws(r,n)));if(e.id&&String(e.id).startsWith("welcome"))return k.createElement(H,{flexDirection:"column",alignItems:"center",width:"100%",marginY:1},k.createElement(H,{borderStyle:"round",borderColor:"gray",paddingX:3,paddingY:0},k.createElement(te,{color:"cyan",bold:!0},e.text.trim())));if(e.isVisualFeedback)return k.createElement(H,{marginBottom:0,marginTop:0,paddingX:1,width:"100%"},k.createElement(te,{color:"white"},e.text));if(i)return k.createElement(H,{marginBottom:1},k.createElement(H,{flexDirection:"column",borderStyle:"round",borderColor:"red",paddingX:1,paddingY:0},k.createElement(te,{color:"red",bold:!0,underline:!0},"\u274C PATCH FAILED"),k.createElement(H,{marginTop:1},k.createElement(te,{color:"red"},"Patch failed: ",k.createElement(te,{color:"white",bold:!0},"Model generated malformed edit.")))));if(e.role==="system"&&e.text?.includes("[TOOL RESULT]")&&!s&&!u&&!i)return null;if(e.isImageStats)return k.createElement(H,{marginBottom:1,paddingX:1,width:"100%"},k.createElement(H,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",padding:0,width:"100%"},k.createElement(H,{paddingX:1,backgroundColor:"#0e1b21"},k.createElement(te,{color:"cyan",bold:!0},"\u{1F4B3} IMAGE STATS")),k.createElement(H,{paddingX:1,marginTop:1,marginBottom:1,flexDirection:"column"},e.text.split(`
|
|
62
|
+
`).map((h,p)=>k.createElement(te,{key:p,color:"white"},h)))));if(e.isAskRecord){let h=e.text.match(/Selection: (.*)/),p=h?h[1]:"No selection",y=Fe(2);return k.createElement(H,{marginBottom:0,paddingX:1,width:"100%"},k.createElement(H,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},k.createElement(H,{paddingX:1},k.createElement(te,{color:"cyan",bold:!0},"\u{1F4AC} AGENT REQUEST: RESOLVED")),k.createElement(H,{paddingX:1,marginTop:1,marginBottom:1},k.createElement(te,{color:"white"},"Selection: ",k.createElement(te,{color:"yellow",bold:!0},p)))))}if(e.isAboutRecord)return k.createElement(H,{marginBottom:0,paddingX:1,width:"100%"},k.createElement(H,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},k.createElement(H,{paddingX:1},k.createElement(te,{color:"white",bold:!0},"ABOUT FLUX FLOW")),k.createElement(H,{paddingX:1,marginTop:1,marginBottom:1},k.createElement(te,null,e.text))));if(e.isUpdateNotification)return k.createElement(H,{marginBottom:1,paddingX:1,width:"100%"},k.createElement(H,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},k.createElement(H,{paddingX:1},k.createElement(te,{color:"white",bold:!0},"UPDATE AVAILABLE")),k.createElement(H,{paddingX:1,marginTop:1,marginBottom:1},k.createElement(Na,{text:e.text,columns:o}))));if(e.isHelpRecord)return k.createElement(H,{marginBottom:1,paddingX:1,width:"100%"},k.createElement(H,{flexDirection:"column",borderStyle:"round",borderColor:"magenta",paddingX:2,paddingY:1,width:"100%"},k.createElement(te,{color:"magenta",bold:!0,underline:!0},"\u{1F4DC} COMMAND REFERENCE"),k.createElement(H,{flexDirection:"column",marginTop:1},[{cmd:"/quit",desc:"Exit and shutdown Flux"},{cmd:"/help",desc:"Show all available commands"},{cmd:"/compress",desc:"Summarize and compress chat history"},{cmd:"/clear",desc:"Clear terminal screen"},{cmd:"/resume",desc:"Load previous session"},{cmd:"/revert",desc:"Revert codebase to checkpoint"},{cmd:"/save",desc:"Force save current chat"},{cmd:"/export",desc:"Export current chat 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:"/docs",desc:"View documentation"},{cmd:"/fluxflow",desc:"Project management"},{cmd:"/update",desc:"Check/Install updates"}].map((p,y)=>k.createElement(H,{key:y,flexDirection:"row"},k.createElement(H,{width:15},k.createElement(te,{color:"cyan",bold:!0},p.cmd)),k.createElement(te,{color:"gray"}," - ",p.desc))))));if(e.isTerminalRecord){let h=e.text.match(/COMMAND: (.*)/),p=e.text.match(/PTY: (true|false)/),y=e.text.match(/OUTPUT: ([\s\S]*)/),T=h?h[1]:"Unknown",w=p?p[1]==="true":!1,E=y?y[1]:"";return k.createElement(H,{marginBottom:0,paddingX:1,width:"100%"},k.createElement(ys,{command:T,output:E,completed:!0,columns:o,isPty:w}))}let[m,c]=k.useState(!e.isStreaming),a=k.useMemo(()=>iu(e.text),[e.text]);k.useEffect(()=>{e.isStreaming&&c(!1)},[e.id]);let d=k.useMemo(()=>e.role==="think"&&!t?"Thinking...":e.isStreaming?a:a.trimEnd(),[a,e.role,t,e.isStreaming]);return k.createElement(H,{marginBottom:(e.role==="think"||e.role==="user"||e.role==="agent",0),marginTop:(e.role==="think"||e.role==="user"||e.role==="agent",0),flexDirection:"column",flexShrink:0,width:"100%",flexGrow:1},e.role==="user"?k.createElement(H,{flexDirection:"column",width:"100%"},k.createElement(H,{width:"100%",height:1,overflow:"hidden"},k.createElement(te,{color:"#444444"},"\u2584".repeat(Math.max(1,o)))),k.createElement(H,{backgroundColor:"#444444",paddingX:1,paddingY:0,width:"100%",flexDirection:"column"},qo(d.replace(/\r\n/g,`
|
|
63
63
|
`).replace(/\r/g,`
|
|
64
64
|
`).replace(/\\\n/g,`
|
|
65
65
|
`).replace(/\\$/,""),o-6).split(`
|
|
66
66
|
`).map((h,p)=>k.createElement(H,{key:p,flexDirection:"row",width:"100%"},k.createElement(H,{flexShrink:0,width:2},k.createElement(te,{bold:!0,color:"white"},p===0?">":" ")),k.createElement(H,{flexGrow:1,marginLeft:1},k.createElement(Pn,{text:h,color:e.color||"white"}))))),k.createElement(H,{width:"100%",height:1,overflow:"hidden"},k.createElement(te,{color:"#444444"},"\u2580".repeat(Math.max(1,o))))):e.role==="think"?k.createElement(H,{flexDirection:"column",marginTop:0,marginBottom:0,paddingX:1,width:"100%"},e.isStreaming&&!e.duration?k.createElement(te,{bold:!0,color:"white"},"\u2727 Thinking..."):k.createElement(te,{bold:!0,color:"white"},"\u2726 Thought",e.duration?k.createElement(te,{color:"gray"}," for ",k.createElement(te,{bold:!0,color:"white"},Ba(e.duration))):""),k.createElement(H,{borderStyle:"single",borderLeft:!0,borderRight:!1,borderTop:!1,borderBottom:!1,paddingLeft:2,paddingTop:1,paddingBottom:1,flexDirection:"column",width:"100%"},au(d,o))):k.createElement(H,{flexDirection:"column",paddingX:1,marginTop:0,width:"100%"},k.createElement(Na,{text:d.replace(/ \|\n\n/g,` |
|
|
67
|
-
`),columns:o}),e.memoryUpdated&&k.createElement(H,{marginTop:1,width:"100%"},k.createElement(te,{color:"white",italic:!0},"[Memory Updated]")),e.role==="agent"&&e.workedDuration?k.createElement(H,{marginTop:1,marginBottom:2,width:"100%"},k.createElement(te,null,"["),k.createElement(te,{color:"gray"},"Worked for ",k.createElement(te,{bold:!0,color:"white"},Ba(e.workedDuration))),k.createElement(te,null,"]")):null))}),mu=k.memo(({messages:e,showFullThinking:t,columns:o=80,aiProvider:n,version:
|
|
67
|
+
`),columns:o}),e.memoryUpdated&&k.createElement(H,{marginTop:1,width:"100%"},k.createElement(te,{color:"white",italic:!0},"[Memory Updated]")),e.role==="agent"&&e.workedDuration?k.createElement(H,{marginTop:1,marginBottom:2,width:"100%"},k.createElement(te,null,"["),k.createElement(te,{color:"gray"},"Worked for ",k.createElement(te,{bold:!0,color:"white"},Ba(e.workedDuration))),k.createElement(te,null,"]")):null))}),mu=k.memo(({messages:e,showFullThinking:t,columns:o=80,aiProvider:n,version:r})=>k.createElement(H,{flexDirection:"column",width:"100%"},e.map((s,i)=>k.createElement(ri,{key:s.id||i,msg:s,showFullThinking:t,columns:o,aiProvider:n,version:r})))),Ra=mu});import it from"react";import{Box as mn,Text as po}from"ink";var fu,Wa,Ya=ae(()=>{or();fu=it.memo(({mode:e,thinkingLevel:t,tokens:o="0.0k",tokensTotal:n="0.0k",chatId:r="NEW-SESSION",isMemoryEnabled:s=!0,apiTier:i="Free",aiProvider:u="Google"})=>{let m=256e3;return(u==="DeepSeek"||u==="Google"&&i==="Paid")&&(m=4e5),it.createElement(mn,{flexDirection:"row",justifyContent:"space-between",paddingX:1,width:"100%"},it.createElement(mn,null,it.createElement(mn,{marginRight:1},it.createElement(po,{color:"white",bold:!0},""," ",e.toUpperCase())),it.createElement(po,{color:"gray",dimColor:!0},"\u2503 "),it.createElement(mn,{marginX:1},it.createElement(po,{color:"white",bold:!0},t.toUpperCase())),it.createElement(po,{color:"gray",dimColor:!0},"\u2503 "),it.createElement(mn,{marginX:1},it.createElement(po,{color:"gray"},"MEM: "),it.createElement(po,{color:"white",bold:!0},s?"ON":"OFF"))),it.createElement(mn,{flexGrow:1,justifyContent:"center",paddingX:2},it.createElement(po,{color:"white",italic:!0}," ",Pa(process.cwd(),35))),it.createElement(mn,null,it.createElement(po,{color:"gray",dimColor:!0},"\u2503 "),it.createElement(mn,{marginX:1},it.createElement(po,{color:"white"}," ",eo(n)," ",it.createElement(po,{dimColor:!0},(o/m*100).toFixed(0),"%"))),it.createElement(po,{color:"gray",dimColor:!0},"\u2503 "),it.createElement(mn,{marginLeft:1},it.createElement(po,{color:"gray",italic:!0}," ",r),(i==="Custom"||i==="Paid")&&it.createElement(po,{color:"gray",dimColor:!0}," | ",it.createElement(po,{color:"gray",bold:!0},"PAID")))))}),Wa=fu});import Lo from"react";import{Box as pr,Text as Ts}from"ink";import hu from"ink-select-input";function go({title:e,subtitle:t,items:o,onSelect:n}){return Lo.createElement(pr,{flexDirection:"column",borderStyle:"round",borderColor:"white",padding:0,marginTop:1,flexShrink:0,width:"100%"},Lo.createElement(pr,{paddingX:1,paddingY:0,marginBottom:t?0:1},Lo.createElement(Ts,{color:"gray",bold:!0},"\u{1F527} ",typeof e=="string"?e.toUpperCase():e)),t&&Lo.createElement(pr,{paddingX:1,marginBottom:1},Lo.createElement(Ts,{color:"gray",italic:!0}," ",t)),Lo.createElement(pr,{flexDirection:"column",width:"100%"},Lo.createElement(hu,{items:o,onSelect:n,itemComponent:pu,indicatorComponent:()=>null})),Lo.createElement(pr,{paddingX:1,marginTop:1},Lo.createElement(Ts,{color:"gray",italic:!0},"(Arrows to select \u2022 Enter to confirm)")))}var pu,ja=ae(()=>{pu=({label:e,isSelected:t})=>{let o=e==="Cancel"||e==="Back"||e.toLowerCase().includes("exit")||e.toLowerCase().includes("back");return Lo.createElement(pr,{marginTop:o?1:0,backgroundColor:t?"#2a2a2a":void 0,paddingX:1,width:"100%"},Lo.createElement(Ts,{color:t?"white":"gray",bold:t},t?"\u276F ":" ",e))}});var re,Kt=ae(()=>{re=e=>{let t={};if(!e)return t;let o=0;for(;o<e.length;){for(;o<e.length&&/[\s,]/.test(e[o]);)o++;if(o>=e.length)break;let n=e.substring(o).match(/^(\w+)\s*=\s*/);if(!n){o++;continue}let r=n[1];o+=n[0].length;let s="";if(o<e.length&&(e[o]==='"'||e[o]==="'"||e[o]==="`")){let i=e[o];o++;let u=o,f=-1,m=o;for(;m<e.length;){let a=e.indexOf(i,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 h=e.substring(a+1),p=h.trim(),y=p===""||/^,\s*\w+\s*=/.test(p)||p.startsWith(")")&&(p.length===1||/^\)\s*([,\]\s]|\[\[?tool:)/i.test(p));if(y&&h.startsWith(`
|
|
68
68
|
`)){let T=p.split(`
|
|
69
|
-
`)[0];if(!T.includes("=")&&!T.includes(")")){m=a+1;continue}}if(y){f=a;break}m=a+1}f!==-1?(
|
|
70
|
-
`;case"r":return"\r";case"t":return" ";case"\\":return"\\";default:return d===i?i:a}})}else if(o<e.length&&e[o]==="["){let i=0,u=null,f=o,m=-1;for(let c=o;c<e.length;c++){let a=e[c];if(u&&a===u){let d=0;for(let h=c-1;h>=0&&e[h]==="\\";h--)d++;d%2===0&&(u=null)}else!u&&(a==='"'||a==="'"||a==="`")&&(u=a);if(!u&&(a==="["?i++:a==="]"&&i--,i===0)){m=c;break}}if(m!==-1){
|
|
69
|
+
`)[0];if(!T.includes("=")&&!T.includes(")")){m=a+1;continue}}if(y){f=a;break}m=a+1}f!==-1?(s=e.substring(u,f),o=f+1):(s=e.substring(u),o=e.length);let c=r.toLowerCase().includes("path")||["dest","source","to","from"].includes(r.toLowerCase());s=s.replace(/\\(.)/g,(a,d)=>{switch(d){case"n":return`
|
|
70
|
+
`;case"r":return"\r";case"t":return" ";case"\\":return"\\";default:return d===i?i:a}})}else if(o<e.length&&e[o]==="["){let i=0,u=null,f=o,m=-1;for(let c=o;c<e.length;c++){let a=e[c];if(u&&a===u){let d=0;for(let h=c-1;h>=0&&e[h]==="\\";h--)d++;d%2===0&&(u=null)}else!u&&(a==='"'||a==="'"||a==="`")&&(u=a);if(!u&&(a==="["?i++:a==="]"&&i--,i===0)){m=c;break}}if(m!==-1){s=e.substring(f,m+1),o=m+1;try{let c=s.trim();c.startsWith("'")||c.includes("'")}catch{}}else s=e.substring(f),o=e.length}else{let i=e.substring(o),u=i.match(/,\s*\w+\s*=|(?:\s*\)\s*(?:$|\]\]))/);if(u){let f=u.index;s=i.substring(0,f).trim(),o+=f}else s=i.trim(),o=e.length}s==="true"?s=!0:s==="false"?s=!1:typeof s=="string"&&!isNaN(s)&&s.trim()!==""&&(s=Number(s)),typeof s=="string"&&(r.toLowerCase().includes("path")||["dest","source","to","from"].includes(r.toLowerCase()))&&(s=s.replace(/\x0C/g,"\\f").replace(/\x0D/g,"\\r").replace(/\x0B/g,"\\v").replace(/\x08/g,"\\b")),t[r]=s}return t}});import{execSync as gu}from"child_process";var Yr,xr,Ha,si=ae(async()=>{await jr();Yr=null,xr=()=>{if(process.platform!=="win32")return!1;if(Yr!==null)return Yr;try{gu('powershell.exe -NoProfile -Command "exit"',{stdio:"ignore"}),Yr=!0}catch{Yr=!1}return Yr},Ha=(e,t,o,n)=>`
|
|
71
71
|
-- TOOL DEFINITIONS --
|
|
72
72
|
Internal tools. MUST use the EXACT syntax '[tool:functions.ToolName(args)]'. **NO OTHER SYNTAX/MARKERS ARE ALLOWED, BRACKETS SHOULD BE PROPERLY USED AS PER SCHEMA**
|
|
73
73
|
|
|
74
74
|
**TOOL USAGE POLICY:**
|
|
75
|
-
- **MAX 3 TOOL CALLS PER TURN
|
|
75
|
+
- **MAX 3 TOOL CALLS PER TURN${e==="Flux"?". EXCEPTION FOR Todo TOOL (4th allowed)":""}. Next Turn, verify tool results, plan next**
|
|
76
76
|
${e==="Flux"?`- USE multiple search & replace on patch tool if editing same file/path with many changes \u2190 **HIGHLY RECOMMENDED**
|
|
77
77
|
- Tool execution denied? MUST use 'Ask' tool immediately to ask for reason/changes. NEVER END RESPONSE OR PROCEED BLINDLY \u2190 **MANDATORY**
|
|
78
78
|
- FileMap >> ReadFile for understandling files efficiently
|
|
@@ -91,11 +91,11 @@ ${e==="Flux"?`- WORKSPACE TOOLS (path = relative to CWD & WILL BE FIRST ARGUMENT
|
|
|
91
91
|
1. [tool:functions.ReadFile(path="...", startLine=number, endLine=number)]. ${n!=="Google"?`${o?"Supports images/docs. User gives image/doc: VIEW FIRST":"No Multimodal support"}`:"Supports images/docs. User gives image/doc: VIEW FIRST"}
|
|
92
92
|
2. [tool:functions.FileMap(path="path/file")]. Shows file structure, dependency, functions, variable maps. Token Efficient than ReadFile
|
|
93
93
|
3. [tool:functions.ReadFolder(path="...")]. Detailed DIR stats including File Sizes
|
|
94
|
-
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. **MUST VERIFY DIFF**
|
|
94
|
+
4. [tool:functions.PatchFile(path="...", replaceContent1="exact string match", newContent1="...", ...MAX 10)]. Surgical Patch. **Multiple patch on same file/path? Use replaceContent2, newContent2 etc >>> multiple spams**. Unsure? ReadFile >> guessing. **MUST VERIFY DIFF**
|
|
95
95
|
5. [tool:functions.WriteFile(path="...", content="...")]. Creates/Overwrites. File Exist? PatchFile > WriteFile. Verify Imports
|
|
96
96
|
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. Usage: Can search for relevent lines/logic area to read specifically for edit
|
|
97
|
-
7. [tool:functions.Run(command="...")]. Runs ${t==="Windows"?
|
|
98
|
-
8. [tool:functions.Todo(method="create/append/get", tasks=[ARRAY OF STRINGS], markDone=[ARRAY OF TASK STRINGS])].
|
|
97
|
+
7. [tool:functions.Run(command="...")]. Runs ${t==="Windows"?xr()?`${gr?"Interactive ":""}WINDOWS POWERSHELL ONLY`:`${gr?"Interactive ":""}WINDOWS CMD ONLY`:`${gr?"Interactive ":""}BASH`} command. Destructive/Irreversible ops -> Ask user. **TOOL DENY RULE APPLIES**. **1 CALL LIMIT FOR RUN**
|
|
98
|
+
8. [tool:functions.Todo(method="create/append/get", tasks=[ARRAY OF STRINGS], markDone=[ARRAY OF TASK STRINGS])]. Task List, Markdown IN ARRAY NOT ALLOWED. USAGE: ANALYZE USER REQUEST \u2192 BREAK DOWN TASK \u2192 CREATE TODO **BEFORE** MAKING CHNAGES. MUST CALL TOOL TO KEEP TODO UPDATED WITH TASK IN REALTIME. 'tasks' & 'markDone' are OPTIONAL PARAMETERS WITH method 'get'. USE 'get' method WITH 'markDone' to mark task completed`.trim():`- CREATIVE TOOLS (path = relative to CWD & WILL BE FIRST ARGUMENT, path separator: '/') -
|
|
99
99
|
1. [tool:functions.WritePDF(path="...", content="...", orientation="...")]. PROACTIVE A4 PAGE BREAKS MUST IN CSS. HTML/CSS for PREMIUM layout
|
|
100
100
|
2. [tool:functions.WriteDoc(path="...", content="...")]. A4 Word document
|
|
101
101
|
- WORKSPACE TOOLS ARE NOT AVAILABLE IN FLOW`.trim()}
|
|
@@ -103,29 +103,29 @@ ${e==="Flux"?`- WORKSPACE TOOLS (path = relative to CWD & WILL BE FIRST ARGUMENT
|
|
|
103
103
|
- VERIFY TOOL RESULT CONTENTS. Fix errors. No hallucinations
|
|
104
104
|
- Escape quotes: \\" for code strings
|
|
105
105
|
- Literal escapes: Double-escape sequences (e.g., \\\\n, \\\\t)
|
|
106
|
-
- File structure: Real newlines for code formatting`.trim()});import{spawn as ii}from"child_process";var
|
|
107
|
-
`)for(o++,n=0;o>=t.length;)t.push([]);else if(a==="\r")n=0;else{for(;o>=t.length;)t.push([]);let d=t[o];for(;n>d.length;)d.push(" ");d[n]=a,n++}}};for(;(i=
|
|
108
|
-
`)},Ct=null,Po=!1,ko=e=>{try{Ct&&(Po&&typeof Ct.write=="function"?Ct.write(e):Ct.stdin&&Ct.stdin.writable&&Ct.stdin.write(e))}catch{}},Ga=()=>{if(Ct){try{Po&&typeof Ct.destroy=="function"?Ct.destroy():typeof Ct.kill=="function"&&(process.platform==="win32"?ii("taskkill",["/pid",Ct.pid,"/f","/t"]):Ct.kill("SIGKILL"))}catch{}Ct=null,Po=!1}},Ka=(e,t=!1)=>{if(process.platform!=="win32")return e;let o=[],n="",
|
|
106
|
+
- File structure: Real newlines for code formatting`.trim()});import{spawn as ii}from"child_process";var Ss,gr,Es,Hr,Ct,Po,ko,Ga,Ka,li,ai,jr=ae(async()=>{Kt();await si();Ss=null;try{let e=await import("node-pty");Ss=e.default||e}catch{}gr=!!Ss,Es=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),Hr=e=>{if(!e)return"";let t=[[]],o=0,n=0,r=/\x1b\[([0-9;]*?)([a-zA-Z])/g,s=0,i,u=m=>{for(let c=0;c<m.length;c++){let a=m[c];if(a===`
|
|
107
|
+
`)for(o++,n=0;o>=t.length;)t.push([]);else if(a==="\r")n=0;else{for(;o>=t.length;)t.push([]);let d=t[o];for(;n>d.length;)d.push(" ");d[n]=a,n++}}};for(;(i=r.exec(e))!==null;){u(e.substring(s,i.index));let m=i[1],c=i[2],a=m?m.split(";").map(Number):[];if(c==="A"){let d=a[0]||1;o=Math.max(0,o-d)}else if(c==="B"){let d=a[0]||1;for(o=o+d;o>=t.length;)t.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,h=(a[1]||1)-1;for(o=Math.max(0,d),n=Math.max(0,h);o>=t.length;)t.push([])}else if(c==="K"){let d=a[0]||0;if(o<t.length){let h=t[o];if(d===0)h.length=n;else if(d===1)for(let p=0;p<n&&p<h.length;p++)h[p]=" ";else d===2&&(h.length=0)}}else if(c==="J"){let d=a[0]||0;(d===2||d===3)&&(t.length=0,t.push([]),o=0,n=0)}s=r.lastIndex}u(e.substring(s));let f=t.map(m=>m.join(""));for(;f.length>0&&f[f.length-1]==="";)f.pop();return f.join(`
|
|
108
|
+
`)},Ct=null,Po=!1,ko=e=>{try{Ct&&(Po&&typeof Ct.write=="function"?Ct.write(e):Ct.stdin&&Ct.stdin.writable&&Ct.stdin.write(e))}catch{}},Ga=()=>{if(Ct){try{Po&&typeof Ct.destroy=="function"?Ct.destroy():typeof Ct.kill=="function"&&(process.platform==="win32"?ii("taskkill",["/pid",Ct.pid,"/f","/t"]):Ct.kill("SIGKILL"))}catch{}Ct=null,Po=!1}},Ka=(e,t=!1)=>{if(process.platform!=="win32")return e;let o=[],n="",r=null,s=!1;for(let c=0;c<e.length;c++){let a=e[c];if(s){n+=a,s=!1;continue}if(a==="\\"){if(e[c+1]===" "){n+=" ",c++;continue}n+=a,s=!0;continue}r?(a===r&&(r=null),n+=a):a==='"'||a==="'"?(r=a,n+=a):a===";"&&!n.includes("://")?(n.length>0&&(o.push(n),n=""),o.push(t?";":"&")):a==="&"&&!n.includes("://")?e[c+1]==="&"?(n.length>0&&(o.push(n),n=""),o.push("&&"),c++):(n.length>0&&(o.push(n),n=""),o.push("&")):a==="|"&&!n.includes("://")?(n.length>0&&(o.push(n),n=""),o.push("|")):/\s/.test(a)?n.length>0&&(o.push(n),n=""):n+=a}n.length>0&&o.push(n);let i=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<o.length;c++){let a=o[c];if(a==="mkdir"&&t&&xr()){let d=[],h=c+1;for(;h<o.length;){let p=o[h];if([">",">>","<","&","&&","|","||",";"].includes(p))break;p!=="-p"&&p!=="--parents"&&p!=="-v"&&p!=="--verbose"&&d.push(p),h++}if(d.length>0){let p=d.map(y=>{let T=y.replace(/^['"]|['"]$/g,""),w=y;return i(T)&&(w=y.replace(/\//g,"\\")),w});u.push("New-Item","-ItemType","Directory","-Force","-Path",p.join(","))}else u.push("New-Item","-ItemType","Directory","-Force");c=h-1;continue}if(a==="rm"&&t&&xr()){let d=[],h=!1,p=!1,y=c+1;for(;y<o.length;){let w=o[y];if([">",">>","<","&","&&","|","||",";"].includes(w))break;w==="-rf"||w==="-fr"?(h=!0,p=!0):w==="-r"||w==="-R"||w==="--recursive"?h=!0:w==="-f"||w==="--force"?p=!0:d.push(w),y++}let T=["Remove-Item"];if(h&&T.push("-Recurse"),p&&T.push("-Force"),d.length>0){let w=d.map(E=>{let A=E.replace(/^['"]|['"]$/g,""),$=E;return i(A)&&($=E.replace(/\//g,"\\")),$});T.push("-Path",w.join(","))}u.push(...T),c=y-1;continue}if(a==="cp"&&t&&xr()){let d=[],h=!1,p=!1,y=c+1;for(;y<o.length;){let w=o[y];if([">",">>","<","&","&&","|","||",";"].includes(w))break;w==="-r"||w==="-R"||w==="--recursive"?h=!0:w==="-f"||w==="--force"?p=!0:d.push(w),y++}let T=["Copy-Item"];if(h&&T.push("-Recurse"),p&&T.push("-Force"),d.length>0){let w=d.map(E=>{let A=E.replace(/^['"]|['"]$/g,""),$=E;return i(A)&&($=E.replace(/\//g,"\\")),$});if(w.length>1){let E=w.pop();T.push("-Path",w.join(","),"-Destination",E)}else T.push("-Path",w[0])}u.push(...T),c=y-1;continue}if(a==="touch"&&t&&xr()){let d=[],h=c+1;for(;h<o.length;){let p=o[h];if([">",">>","<","&","&&","|","||",";"].includes(p))break;d.push(p),h++}if(d.length>0){let y=`(${d.map(T=>{let w=T.replace(/^['"]|['"]$/g,""),E=T;return i(w)&&(E=T.replace(/\//g,"\\")),E}).join(", ")}) | ForEach-Object { if (Test-Path $_) { (Get-Item $_).LastWriteTime = [System.DateTime]::Now } else { $null | Out-File -FilePath $_ } }`;u.push(y)}c=h-1;continue}if(a==="|"&&o[c+1]==="tee"){o[c+2]==="-a"?(u.push(">>"),c+=2):(u.push(">"),c+=1);continue}if(a==="|"&&o[c+1]==="cat"&&o[c+2]===">"){u.push(">"),c+=2;continue}if(a==="|"){let d=o[c+1];if(d){let h=d.replace(/^['"]|['"]$/g,""),p=/\.(txt|md|json|log|csv|html|css|py|js|xml|yaml|yml|pdf|docx|pptx|xlsx)$/i.test(h);if(i(h)&&p){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),h=c;f&&d&&(h=c.replace(/^['"]|['"]$/g,""));let p=/^['"]|['"]$/.test(h),y=h.replace(/^['"]|['"]$/g,"");i(y)&&(h=h.replace(/\//g,"\\"));let T=h.replace(/^['"]|['"]$/g,"");return T.includes(" ")&&!p&&(h=`"${T}"`),h});if(t){let c="",a=0;for(let d=0;d<m.length;d++){let h=m[d];h==="&&"?(c+="; if ($?) {",a++):h===";"?(c+=" }".repeat(a)+";",a=0):(c&&!c.endsWith(" ")&&!c.endsWith("{")&&(c+=" "),c+=h)}return c+=" }".repeat(a),c}return m.join(" ")},li=async(e,t={})=>{let{command:o}=re(e),{onChunk:n}=t;if(!o)return'ERROR: Missing "command" argument for exec_command.';let r=process.platform==="win32",s=t.systemSettings||{},i={};return s.networkAccess===!1&&(i.HTTP_PROXY="http://127.0.0.1:9999",i.HTTPS_PROXY="http://127.0.0.1:9999",i.ALL_PROXY="socks5://127.0.0.1:9999",i.http_proxy="http://127.0.0.1:9999",i.https_proxy="http://127.0.0.1:9999",i.all_proxy="socks5://127.0.0.1:9999",i.NO_PROXY="localhost,127.0.0.1"),new Promise(u=>{let f=m=>{let c=Ka(o,m),a=r?m?"powershell.exe":"cmd.exe":process.env.SHELL||"bash",d=r?m?["-NoProfile","-Command",c]:["/c",c]:["-c",c];if(Ss)try{let h=Ss.spawn(a,d,{name:"xterm-256color",cols:t.cols||120,rows:t.rows||30,cwd:process.cwd(),env:{...process.env,CI:"false",TERM:"xterm-256color",FORCE_COLOR:"1",...i}});Ct=h,Po=!0;let p="",y=!1;return h.onData(T=>{if(!y){p+=T,n&&n(T);let w=Es(p);/(?: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)&&(y=!0,setTimeout(()=>u(`SUCCESS: Dev server started successfully in background.
|
|
109
109
|
|
|
110
|
-
${w}`),500))}}),h.onExit(({exitCode:T})=>{if(y)return;Ct=null;let w=
|
|
110
|
+
${w}`),500))}}),h.onExit(({exitCode:T})=>{if(y)return;Ct=null;let w=Hr(p||""),E=Es(w).replace(/\n{3,}/g,`
|
|
111
111
|
|
|
112
112
|
`)||"Command executed with no output.";u(T!==0?`ERROR: Command [${o}] failed with exit code [${T}].
|
|
113
113
|
|
|
114
114
|
${E}`:`SUCCESS: Command [${o}] completed.
|
|
115
115
|
|
|
116
|
-
${E}`)}),!0}catch(h){return
|
|
116
|
+
${E}`)}),!0}catch(h){return r&&m&&h.code==="ENOENT"?!1:(ai(u,c,o,i,n,m),!0)}else return ai(u,c,o,i,n,m),!0};r&&f(!0)||f(!1)})},ai=(e,t,o,n,r,s=!0)=>{let i=process.platform==="win32",u=i?s?"powershell.exe":"cmd.exe":process.env.SHELL||"bash",m=i?ii(u,i?s?["-NoProfile","-Command",t]:["/c",t]:["-c",t],{cwd:process.cwd(),env:{...process.env,...n}}):ii(t,{shell:!0,cwd:process.cwd(),env:{...process.env,CI:"false",TERM:"xterm-256color",FORCE_COLOR:"1",...n}});Ct=m,Po=!1,m.stdin&&m.stdin.on("error",()=>{Ct=null});let c="",a="",d=!1;m.stdout.on("data",h=>{if(!d){let p=h.toString();c+=p,r&&r(p);let y=Es(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(y)&&(d=!0,setTimeout(()=>e(`SUCCESS: Dev server started successfully in background.
|
|
117
117
|
|
|
118
|
-
${y}`),500))}}),m.stderr.on("data",h=>{if(!d){let p=h.toString();a+=p,
|
|
118
|
+
${y}`),500))}}),m.stderr.on("data",h=>{if(!d){let p=h.toString();a+=p,r&&r(p)}}),m.on("close",h=>{if(d)return;Ct=null;let p=[],y=Hr(c),T=Hr(a);y&&p.push(`STDOUT:
|
|
119
119
|
${y}`),T&&p.push(`STDERR:
|
|
120
120
|
${T}`),h!==0&&p.push(`EXIT CODE: ${h}`);let w=p.join(`
|
|
121
121
|
|
|
122
|
-
`)||"Command executed with no output.",E=
|
|
122
|
+
`)||"Command executed with no output.",E=Es(w).replace(/\n{3,}/g,`
|
|
123
123
|
|
|
124
124
|
`);e(h!==0?`ERROR: Command [${o}] failed with exit code [${h}].
|
|
125
125
|
|
|
126
126
|
${E}`:`SUCCESS: Command [${o}] completed.
|
|
127
127
|
|
|
128
|
-
${E}`)}),m.on("error",h=>{if(i&&r&&h.code==="ENOENT"){let y=Ka(o,!1);return ai(e,y,o,n,s,!1)}Ct=null;let p=h instanceof Error?h.message:String(h);e(`ERROR: Failed to start command [${o}]: ${p}`)})}});import Pe,{useState as Gs}from"react";import{Box as Ft,Text as to,useInput as xu}from"ink";import yu from"ink-text-input";function ui({systemSettings:e,setSystemSettings:t,apiTier:o,setActiveView:n,setInputConfig:s,saveSettings:r,quotas:i,setMessages:u,aiProvider:f}){let[m,c]=Gs("categories"),[a,d]=Gs(0),[h,p]=Gs(0),[y,T]=Gs(null),[w,E]=Gs(""),A=O=>{switch(O){case"memory":return[{label:"Toggle Memory",value:"memory",status:e.memory?"ON":"OFF"}];case"security":return[{label:"Sandbox Preset",value:"sandboxPreset",status:Xa(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:ci(e.alwaysAskCommands),section:"Sandbox"},{label:"Auto Approve Commands",value:"autoApprove",status:ci(e.autoApproveCommands),section:"Sandbox"},{label:"Auto Disapprove Commands",value:"autoDisallow",status:ci(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:o},{label:"Download Language Parsers",value:"parserDownload",status:"ACTION"}];default:return[]}},$=mn[a].id,W=A($);xu((O,M)=>{if(y){M.escape&&T(null);return}if(m==="categories")M.upArrow?d(P=>(P-1+mn.length)%mn.length):M.downArrow?d(P=>(P+1)%mn.length):M.return||M.rightArrow?mn[a].id==="exit"?n("chat"):(c("items"),p(0)):M.escape&&n("chat");else if(m==="items"){if(M.upArrow)p(P=>(P-1+W.length)%W.length);else if(M.downArrow)p(P=>(P+1)%W.length);else if(M.leftArrow||M.escape)c("categories");else if(M.return){let P=W[h];D(P)}}});let D=O=>{if(O.value==="memory")t(M=>({...M,memory:!M.memory}));else if(O.value==="sandboxPreset"){let M=Xa(e),P=["Autonomous","Balanced","Strict"],G=(P.indexOf(M)+1)%P.length,q=P[G];t(Y=>{let N={...Y,sandboxPreset:q};return q==="Strict"?(N.autoExec=!1,N.allowExternalAccess=!1,N.networkAccess=!1,N.autoApproveCommands="",N.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",N.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",N.autoApproveGit=!1):q==="Balanced"?(N.autoExec=!0,N.allowExternalAccess=!1,N.networkAccess=!0,N.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",N.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",N.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",N.autoApproveGit=!1):q==="Autonomous"&&(N.autoExec=!0,N.allowExternalAccess=!0,N.networkAccess=!0,N.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",N.autoDisallowCommands="",N.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",N.autoApproveGit=!0),N})}else if(O.value==="autoExec")e.autoExec?t(M=>({...M,autoExec:!1,sandboxPreset:"Custom"})):e.allowExternalAccess?n("doubleDanger"):n("autoExecDanger");else if(O.value==="externalAccess")e.allowExternalAccess?t(M=>({...M,allowExternalAccess:!1,sandboxPreset:"Custom"})):e.autoExec?n("doubleDanger"):n("externalDanger");else if(O.value==="networkAccess")t(M=>({...M,networkAccess:M.networkAccess===!1,sandboxPreset:"Custom"}));else if(O.value==="alwaysAsk")T("alwaysAskCommands"),E(e.alwaysAskCommands||"");else if(O.value==="autoApprove")T("autoApproveCommands"),E(e.autoApproveCommands||"");else if(O.value==="autoApproveGit")t(M=>({...M,autoApproveGit:!M.autoApproveGit,sandboxPreset:"Custom"}));else if(O.value==="autoDisallow")T("autoDisallowCommands"),E(e.autoDisallowCommands||"");else if(O.value==="apiTier")n("apiTier");else if(O.value==="aiProvider")n("selectProvider");else if(O.value==="autoDelete"){let M=["1d","7d","30d"],j=(M.indexOf(e.autoDeleteHistory||"30d")+1)%M.length;t(G=>({...G,autoDeleteHistory:M[j]}))}else if(O.value==="autoUpdate")t(M=>({...M,autoUpdate:!M.autoUpdate}));else if(O.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 M={...e,useExternalData:!1};t(M),r({systemSettings:M,apiTier:o,quotas:i}),u(P=>[...P,{id:Date.now(),role:"system",text:"[STORAGE RESET] Flux Flow will return to default ~/.fluxflow after restart."}]),n("chat")}else O.value==="updateManager"?n("updateManager"):O.value==="parserDownload"&&n("parserDownload")};return Pe.createElement(Ft,{flexDirection:"column",borderStyle:"round",borderColor:"white",padding:0,width:"100%",minHeight:32},Pe.createElement(Ft,{paddingX:1,paddingY:0,marginBottom:0,borderStyle:"single",borderColor:"gray",width:"100%"},Pe.createElement(to,{color:"gray",bold:!0},"SYSTEM CONFIGURATION")),Pe.createElement(Ft,{flexDirection:"row",width:"100%",minHeight:26},Pe.createElement(Ft,{flexDirection:"column",width:"30%",borderStyle:"round",borderColor:m==="categories"?"white":"grey",padding:1,paddingY:0},Pe.createElement(Ft,{marginBottom:1},Pe.createElement(to,{color:m==="categories"?"white":"grey",bold:!0,underline:!0},"CATEGORIES")),mn.map((O,M)=>{let P=a===M,j=O.id==="exit";return Pe.createElement(Ft,{key:O.id,marginTop:j?17:0,backgroundColor:P?m==="categories"?"#2a2a2a":"#1e1e1e":void 0,paddingX:1},Pe.createElement(to,{color:P&&m==="categories"?"white":"grey",bold:P},P?"\u276F ":" ",O.label))})),Pe.createElement(Ft,{flexDirection:"column",width:"70%",borderStyle:"round",borderColor:m==="items"?"white":"grey",paddingX:1,marginLeft:1,paddingY:0},Pe.createElement(Ft,{marginBottom:1},Pe.createElement(to,{color:m==="items"?"white":"grey",bold:!0,underline:!0},mn[a].label.toUpperCase()," SETTINGS")),W.length>0?(()=>{let O=null,M=[],P=ee=>(ee||"").split(",").map(Me=>Me.trim().toLowerCase()).filter(Boolean),j=P(e.autoApproveCommands),G=P(e.autoDisallowCommands),q=P(e.alwaysAskCommands),Y=[...j,...G,...q],N=new Set(Y),he=$==="security"&&Y.length!==N.size;return W.forEach((ee,Me)=>{let le=m==="items"&&h===Me,ue=ee.label.length,Xe=Math.max(2,35-ue),_t=".".repeat(Xe),Ve=Ye=>$==="security"?(Ye.value==="autoExec"||Ye.value==="externalAccess")&&Ye.status==="ON"?"white":"gray":Ye.status?.startsWith("\u2713")?"white":Ye.status?.startsWith("\u26A0")?"gray":Ye.status==="ON"?"white":Ye.status==="OFF"?"gray":"white";ee.section&&ee.section!==O&&(O=ee.section,M.push(Pe.createElement(Ft,{key:`sec-hdr-${ee.section}`,marginTop:M.length>0?1:0,marginBottom:0,paddingX:1},Pe.createElement(to,{color:"gray",bold:!0,underline:!0},ee.section.toUpperCase()))));let Ee=le&&y&&(y==="alwaysAskCommands"&&ee.value==="alwaysAsk"||y==="autoApproveCommands"&&ee.value==="autoApprove"||y==="autoDisallowCommands"&&ee.value==="autoDisallow"),ft=ee.value==="alwaysAsk"||ee.value==="autoApprove"||ee.value==="autoDisallow",et=ee.value==="parserDownload";M.push(Pe.createElement(Ft,{key:ee.value,flexDirection:"column"},Pe.createElement(Ft,{backgroundColor:le&&!Ee?"#2a2a2a":void 0,paddingX:2},Pe.createElement(to,{color:le?"white":"grey",bold:le,underline:et},le?"\u276F ":" ",ee.label),!ft&&!et&&Pe.createElement(Pe.Fragment,null,Pe.createElement(to,{color:"gray"},_t),Pe.createElement(to,{color:Ve(ee),bold:!0},ee.value==="aiProvider"?ee.status:`[ ${ee.status} ]`))),ft&&!Ee&&ee.status!=="None"&&Pe.createElement(Ft,{paddingX:4,marginBottom:1},Pe.createElement(to,{color:"gray"},"\u21B3 ",ee.status)),Ee&&Pe.createElement(Ft,{flexDirection:"column",marginLeft:4,marginBottom:1},Pe.createElement(Ft,{paddingX:1,borderStyle:"single",borderColor:"gray",flexDirection:"row"},Pe.createElement(to,{color:"gray",bold:!0},"> "," "),Pe.createElement(yu,{value:w,onChange:E,onSubmit:Ye=>{let qe={...e,[y]:Ye.trim(),sandboxPreset:"Custom"};t(qe),r({systemSettings:qe,apiTier:o,quotas:i}),T(null)}})),Pe.createElement(to,{color:"gray",italic:!0}," Comma separated \u2022 Press Enter to save, Esc to cancel"))))}),$==="other"&&M.push(Pe.createElement(Ft,{key:"pty-notice",marginTop:18,paddingX:1},Pe.createElement(to,{color:"white"},gs?"\u2713 Advance Interactive Terminal Supported":"\u26A0 Interactive Terminal is Limited"))),he&&M.push(Pe.createElement(Ft,{key:"conflict-warning",marginTop:1,paddingX:1},Pe.createElement(to,{color:"white",italic:!0},"* Conflicting commands will be ignored and defaulted to highest priority"))),M})():Pe.createElement(Ft,{paddingX:1},Pe.createElement(to,{color:"gray",italic:!0},mn[a].desc)))),Pe.createElement(Ft,{paddingX:1,marginTop:0,flexDirection:"row",justifyContent:"space-between"},Pe.createElement(to,{color:"gray",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"&&Pe.createElement(to,{color:"gray"},mn[a].desc)))}var mn,Xa,ci,Va=ae(async()=>{await js();mn=[{id:"memory",label:"Memory",desc:"Manage system context & agent's memory"},{id:"security",label:"Security",desc:"Configure permissions & data safety"},{id:"updater",label:"Updater",desc:"Manage application updates"},{id:"other",label:"Other",desc:"Miscellaneous preferences"},{id:"exit",label:"Exit Settings",desc:"Return to chat view"}],Xa=e=>{let t=e.autoApproveCommands||"",o=e.autoDisallowCommands||"",n=e.alwaysAskCommands||"",s=e.autoExec===!1&&e.allowExternalAccess===!1&&e.networkAccess===!1&&t===""&&o==="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&&t==="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"&&o==="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,i=e.autoExec===!0&&e.allowExternalAccess===!0&&e.networkAccess!==!1&&t==="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"&&o===""&&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":i?"Autonomous":e.sandboxPreset||"Custom"},ci=e=>!e||e.trim()===""?"None":e.length>40?e.substring(0,40)+"...":e});import Fo,{useState as di,useEffect as wu}from"react";import{Box as ys,Text as br}from"ink";import Tu from"ink-text-input";function mi({initialData:e,onSave:t,onCancel:o}){let[n,s]=di(0),[r,i]=di(""),[u,f]=di(()=>({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): "}];wu(()=>{let a=m[n].key;i(u[a]||"")},[n,u]);let c=a=>{if(a.trim().toLowerCase()==="/cancel"){o();return}let d=m[n].key,h={...u,[d]:a.trim()};f(h),i(""),n<m.length-1?s(n+1):t(h)};return Fo.createElement(ys,{borderStyle:"round",borderColor:"gray",padding:0,marginTop:1,flexShrink:0,flexDirection:"column",width:"100%"},Fo.createElement(ys,{paddingX:1,marginBottom:1},Fo.createElement(br,{color:"white",bold:!0},"\u{1F464} DEVELOPER PROFILE CONFIGURATION")),Fo.createElement(ys,{paddingX:1,flexDirection:"column"},Fo.createElement(ys,null,Fo.createElement(br,{color:"white",bold:!0},m[n].label),Fo.createElement(Tu,{value:r,onChange:i,onSubmit:c})),Fo.createElement(ys,{marginTop:1},Fo.createElement(br,{color:"gray",italic:!0},"Step ",n+1," of ",m.length))),Fo.createElement(ys,{paddingX:1,marginTop:1},Fo.createElement(br,{color:"gray",italic:!0},"(Enter to submit \u2022 Type /cancel to abort)")))}var qa=ae(()=>{});import mt,{useState as fi}from"react";import{Box as Io,Text as fn,useInput as Su}from"ink";import Eu from"ink-text-input";var bu,za,Ja=ae(()=>{un();bu=({question:e,options:t,onResolve:o})=>{let[n,s]=fi(!1),[r,i]=fi(""),[u,f]=fi(0),m=[...t,{id:"CUSTOM",label:"Suggest something else...",description:"Provide a custom response"}];Su((a,d)=>{if(!n&&((d.leftArrow||d.upArrow)&&f(h=>Math.max(0,h-1)),(d.rightArrow||d.downArrow)&&f(h=>Math.min(m.length-1,h+1)),d.return)){let h=m[u];h.id==="CUSTOM"?s(!0):o(h.label)}});let c=Fe(2);return n?mt.createElement(Io,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},mt.createElement(Io,{paddingX:1},mt.createElement(fn,{color:"white",bold:!0},"\u{1F4AC} SUGGEST SOMETHING ELSE")),mt.createElement(Io,{marginTop:1,paddingX:1},mt.createElement(fn,{italic:!0,color:"gray"},"Replying to: ",e)),mt.createElement(Io,{marginTop:1,paddingX:1,flexDirection:"row"},mt.createElement(fn,{color:"white",bold:!0},"\u{1F4A0} "),mt.createElement(Eu,{value:r,onChange:i,onSubmit:()=>o(r)})),mt.createElement(Io,{marginTop:1,paddingX:1,marginBottom:1},mt.createElement(fn,{color:"gray",italic:!0},"(Press Enter to send)"))):mt.createElement(Io,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},mt.createElement(Io,{paddingX:1,marginBottom:1},mt.createElement(fn,{color:"white",bold:!0},"\u{1F4AC} AGENT REQUEST: ACTION REQUIRED")),mt.createElement(Io,{paddingX:1,marginBottom:1},mt.createElement(fn,{bold:!0,color:"white"},e)),mt.createElement(Io,{flexDirection:"column",width:"100%"},m.map((a,d)=>{let h=d===u;return mt.createElement(Io,{key:a.id,flexDirection:"column",width:"100%",backgroundColor:h?"#2a2a2a":void 0,paddingX:1,marginBottom:d===m.length-1?0:1},mt.createElement(fn,{color:h?"white":"grey",bold:h},h?"\u276F ":" ",a.label),a.description&&mt.createElement(Io,{marginLeft:4},mt.createElement(fn,{color:"gray",italic:!0},a.description)))})),mt.createElement(Io,{paddingX:1,marginTop:1,marginBottom:1},mt.createElement(fn,{color:"gray",italic:!0},"(Use Arrows to navigate, Enter to confirm)")))},za=bu});var Qa,Za=ae(()=>{Qa=(e=!0,t=!0)=>`
|
|
128
|
+
${E}`)}),m.on("error",h=>{if(i&&s&&h.code==="ENOENT"){let y=Ka(o,!1);return ai(e,y,o,n,r,!1)}Ct=null;let p=h instanceof Error?h.message:String(h);e(`ERROR: Failed to start command [${o}]: ${p}`)})}});import Pe,{useState as Gr}from"react";import{Box as Ft,Text as to,useInput as xu}from"ink";import yu from"ink-text-input";function ui({systemSettings:e,setSystemSettings:t,apiTier:o,setActiveView:n,setInputConfig:r,saveSettings:s,quotas:i,setMessages:u,aiProvider:f}){let[m,c]=Gr("categories"),[a,d]=Gr(0),[h,p]=Gr(0),[y,T]=Gr(null),[w,E]=Gr(""),A=O=>{switch(O){case"memory":return[{label:"Toggle Memory",value:"memory",status:e.memory?"ON":"OFF"}];case"security":return[{label:"Sandbox Preset",value:"sandboxPreset",status:Xa(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:ci(e.alwaysAskCommands),section:"Sandbox"},{label:"Auto Approve Commands",value:"autoApprove",status:ci(e.autoApproveCommands),section:"Sandbox"},{label:"Auto Disapprove Commands",value:"autoDisallow",status:ci(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:o},{label:"Download Language Parsers",value:"parserDownload",status:"ACTION"}];default:return[]}},$=fn[a].id,W=A($);xu((O,M)=>{if(y){M.escape&&T(null);return}if(m==="categories")M.upArrow?d(P=>(P-1+fn.length)%fn.length):M.downArrow?d(P=>(P+1)%fn.length):M.return||M.rightArrow?fn[a].id==="exit"?n("chat"):(c("items"),p(0)):M.escape&&n("chat");else if(m==="items"){if(M.upArrow)p(P=>(P-1+W.length)%W.length);else if(M.downArrow)p(P=>(P+1)%W.length);else if(M.leftArrow||M.escape)c("categories");else if(M.return){let P=W[h];D(P)}}});let D=O=>{if(O.value==="memory")t(M=>({...M,memory:!M.memory}));else if(O.value==="sandboxPreset"){let M=Xa(e),P=["Autonomous","Balanced","Strict"],G=(P.indexOf(M)+1)%P.length,q=P[G];t(Y=>{let N={...Y,sandboxPreset:q};return q==="Strict"?(N.autoExec=!1,N.allowExternalAccess=!1,N.networkAccess=!1,N.autoApproveCommands="",N.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",N.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",N.autoApproveGit=!1):q==="Balanced"?(N.autoExec=!0,N.allowExternalAccess=!1,N.networkAccess=!0,N.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",N.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",N.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",N.autoApproveGit=!1):q==="Autonomous"&&(N.autoExec=!0,N.allowExternalAccess=!0,N.networkAccess=!0,N.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",N.autoDisallowCommands="",N.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",N.autoApproveGit=!0),N})}else if(O.value==="autoExec")e.autoExec?t(M=>({...M,autoExec:!1,sandboxPreset:"Custom"})):e.allowExternalAccess?n("doubleDanger"):n("autoExecDanger");else if(O.value==="externalAccess")e.allowExternalAccess?t(M=>({...M,allowExternalAccess:!1,sandboxPreset:"Custom"})):e.autoExec?n("doubleDanger"):n("externalDanger");else if(O.value==="networkAccess")t(M=>({...M,networkAccess:M.networkAccess===!1,sandboxPreset:"Custom"}));else if(O.value==="alwaysAsk")T("alwaysAskCommands"),E(e.alwaysAskCommands||"");else if(O.value==="autoApprove")T("autoApproveCommands"),E(e.autoApproveCommands||"");else if(O.value==="autoApproveGit")t(M=>({...M,autoApproveGit:!M.autoApproveGit,sandboxPreset:"Custom"}));else if(O.value==="autoDisallow")T("autoDisallowCommands"),E(e.autoDisallowCommands||"");else if(O.value==="apiTier")n("apiTier");else if(O.value==="aiProvider")n("selectProvider");else if(O.value==="autoDelete"){let M=["1d","7d","30d"],j=(M.indexOf(e.autoDeleteHistory||"30d")+1)%M.length;t(G=>({...G,autoDeleteHistory:M[j]}))}else if(O.value==="autoUpdate")t(M=>({...M,autoUpdate:!M.autoUpdate}));else if(O.value==="externalData")if(!e.useExternalData)r({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 M={...e,useExternalData:!1};t(M),s({systemSettings:M,apiTier:o,quotas:i}),u(P=>[...P,{id:Date.now(),role:"system",text:"[STORAGE RESET] Flux Flow will return to default ~/.fluxflow after restart."}]),n("chat")}else O.value==="updateManager"?n("updateManager"):O.value==="parserDownload"&&n("parserDownload")};return Pe.createElement(Ft,{flexDirection:"column",borderStyle:"round",borderColor:"white",padding:0,width:"100%",minHeight:32},Pe.createElement(Ft,{paddingX:1,paddingY:0,marginBottom:0,borderStyle:"single",borderColor:"gray",width:"100%"},Pe.createElement(to,{color:"gray",bold:!0},"SYSTEM CONFIGURATION")),Pe.createElement(Ft,{flexDirection:"row",width:"100%",minHeight:26},Pe.createElement(Ft,{flexDirection:"column",width:"30%",borderStyle:"round",borderColor:m==="categories"?"white":"grey",padding:1,paddingY:0},Pe.createElement(Ft,{marginBottom:1},Pe.createElement(to,{color:m==="categories"?"white":"grey",bold:!0,underline:!0},"CATEGORIES")),fn.map((O,M)=>{let P=a===M,j=O.id==="exit";return Pe.createElement(Ft,{key:O.id,marginTop:j?17:0,backgroundColor:P?m==="categories"?"#2a2a2a":"#1e1e1e":void 0,paddingX:1},Pe.createElement(to,{color:P&&m==="categories"?"white":"grey",bold:P},P?"\u276F ":" ",O.label))})),Pe.createElement(Ft,{flexDirection:"column",width:"70%",borderStyle:"round",borderColor:m==="items"?"white":"grey",paddingX:1,marginLeft:1,paddingY:0},Pe.createElement(Ft,{marginBottom:1},Pe.createElement(to,{color:m==="items"?"white":"grey",bold:!0,underline:!0},fn[a].label.toUpperCase()," SETTINGS")),W.length>0?(()=>{let O=null,M=[],P=ee=>(ee||"").split(",").map(Me=>Me.trim().toLowerCase()).filter(Boolean),j=P(e.autoApproveCommands),G=P(e.autoDisallowCommands),q=P(e.alwaysAskCommands),Y=[...j,...G,...q],N=new Set(Y),ge=$==="security"&&Y.length!==N.size;return W.forEach((ee,Me)=>{let ce=m==="items"&&h===Me,ue=ee.label.length,Xe=Math.max(2,35-ue),_t=".".repeat(Xe),Ve=Ye=>$==="security"?(Ye.value==="autoExec"||Ye.value==="externalAccess")&&Ye.status==="ON"?"white":"gray":Ye.status?.startsWith("\u2713")?"white":Ye.status?.startsWith("\u26A0")?"gray":Ye.status==="ON"?"white":Ye.status==="OFF"?"gray":"white";ee.section&&ee.section!==O&&(O=ee.section,M.push(Pe.createElement(Ft,{key:`sec-hdr-${ee.section}`,marginTop:M.length>0?1:0,marginBottom:0,paddingX:1},Pe.createElement(to,{color:"gray",bold:!0,underline:!0},ee.section.toUpperCase()))));let Ee=ce&&y&&(y==="alwaysAskCommands"&&ee.value==="alwaysAsk"||y==="autoApproveCommands"&&ee.value==="autoApprove"||y==="autoDisallowCommands"&&ee.value==="autoDisallow"),ht=ee.value==="alwaysAsk"||ee.value==="autoApprove"||ee.value==="autoDisallow",et=ee.value==="parserDownload";M.push(Pe.createElement(Ft,{key:ee.value,flexDirection:"column"},Pe.createElement(Ft,{backgroundColor:ce&&!Ee?"#2a2a2a":void 0,paddingX:2},Pe.createElement(to,{color:ce?"white":"grey",bold:ce,underline:et},ce?"\u276F ":" ",ee.label),!ht&&!et&&Pe.createElement(Pe.Fragment,null,Pe.createElement(to,{color:"gray"},_t),Pe.createElement(to,{color:Ve(ee),bold:!0},ee.value==="aiProvider"?ee.status:`[ ${ee.status} ]`))),ht&&!Ee&&ee.status!=="None"&&Pe.createElement(Ft,{paddingX:4,marginBottom:1},Pe.createElement(to,{color:"gray"},"\u21B3 ",ee.status)),Ee&&Pe.createElement(Ft,{flexDirection:"column",marginLeft:4,marginBottom:1},Pe.createElement(Ft,{paddingX:1,borderStyle:"single",borderColor:"gray",flexDirection:"row"},Pe.createElement(to,{color:"gray",bold:!0},"> "," "),Pe.createElement(yu,{value:w,onChange:E,onSubmit:Ye=>{let qe={...e,[y]:Ye.trim(),sandboxPreset:"Custom"};t(qe),s({systemSettings:qe,apiTier:o,quotas:i}),T(null)}})),Pe.createElement(to,{color:"gray",italic:!0}," Comma separated \u2022 Press Enter to save, Esc to cancel"))))}),$==="other"&&M.push(Pe.createElement(Ft,{key:"pty-notice",marginTop:18,paddingX:1},Pe.createElement(to,{color:"white"},gr?"\u2713 Advance Interactive Terminal Supported":"\u26A0 Interactive Terminal is Limited"))),ge&&M.push(Pe.createElement(Ft,{key:"conflict-warning",marginTop:1,paddingX:1},Pe.createElement(to,{color:"white",italic:!0},"* Conflicting commands will be ignored and defaulted to highest priority"))),M})():Pe.createElement(Ft,{paddingX:1},Pe.createElement(to,{color:"gray",italic:!0},fn[a].desc)))),Pe.createElement(Ft,{paddingX:1,marginTop:0,flexDirection:"row",justifyContent:"space-between"},Pe.createElement(to,{color:"gray",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"&&Pe.createElement(to,{color:"gray"},fn[a].desc)))}var fn,Xa,ci,Va=ae(async()=>{await jr();fn=[{id:"memory",label:"Memory",desc:"Manage system context & agent's memory"},{id:"security",label:"Security",desc:"Configure permissions & data safety"},{id:"updater",label:"Updater",desc:"Manage application updates"},{id:"other",label:"Other",desc:"Miscellaneous preferences"},{id:"exit",label:"Exit Settings",desc:"Return to chat view"}],Xa=e=>{let t=e.autoApproveCommands||"",o=e.autoDisallowCommands||"",n=e.alwaysAskCommands||"",r=e.autoExec===!1&&e.allowExternalAccess===!1&&e.networkAccess===!1&&t===""&&o==="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,s=e.autoExec===!0&&e.allowExternalAccess===!1&&e.networkAccess!==!1&&t==="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"&&o==="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,i=e.autoExec===!0&&e.allowExternalAccess===!0&&e.networkAccess!==!1&&t==="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"&&o===""&&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 r?"Strict":s?"Balanced":i?"Autonomous":e.sandboxPreset||"Custom"},ci=e=>!e||e.trim()===""?"None":e.length>40?e.substring(0,40)+"...":e});import Fo,{useState as di,useEffect as wu}from"react";import{Box as yr,Text as bs}from"ink";import Tu from"ink-text-input";function mi({initialData:e,onSave:t,onCancel:o}){let[n,r]=di(0),[s,i]=di(""),[u,f]=di(()=>({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): "}];wu(()=>{let a=m[n].key;i(u[a]||"")},[n,u]);let c=a=>{if(a.trim().toLowerCase()==="/cancel"){o();return}let d=m[n].key,h={...u,[d]:a.trim()};f(h),i(""),n<m.length-1?r(n+1):t(h)};return Fo.createElement(yr,{borderStyle:"round",borderColor:"gray",padding:0,marginTop:1,flexShrink:0,flexDirection:"column",width:"100%"},Fo.createElement(yr,{paddingX:1,marginBottom:1},Fo.createElement(bs,{color:"white",bold:!0},"\u{1F464} DEVELOPER PROFILE CONFIGURATION")),Fo.createElement(yr,{paddingX:1,flexDirection:"column"},Fo.createElement(yr,null,Fo.createElement(bs,{color:"white",bold:!0},m[n].label),Fo.createElement(Tu,{value:s,onChange:i,onSubmit:c})),Fo.createElement(yr,{marginTop:1},Fo.createElement(bs,{color:"gray",italic:!0},"Step ",n+1," of ",m.length))),Fo.createElement(yr,{paddingX:1,marginTop:1},Fo.createElement(bs,{color:"gray",italic:!0},"(Enter to submit \u2022 Type /cancel to abort)")))}var qa=ae(()=>{});import ft,{useState as fi}from"react";import{Box as Io,Text as hn,useInput as Su}from"ink";import Eu from"ink-text-input";var bu,za,Ja=ae(()=>{dn();bu=({question:e,options:t,onResolve:o})=>{let[n,r]=fi(!1),[s,i]=fi(""),[u,f]=fi(0),m=[...t,{id:"CUSTOM",label:"Suggest something else...",description:"Provide a custom response"}];Su((a,d)=>{if(!n&&((d.leftArrow||d.upArrow)&&f(h=>Math.max(0,h-1)),(d.rightArrow||d.downArrow)&&f(h=>Math.min(m.length-1,h+1)),d.return)){let h=m[u];h.id==="CUSTOM"?r(!0):o(h.label)}});let c=Fe(2);return n?ft.createElement(Io,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},ft.createElement(Io,{paddingX:1},ft.createElement(hn,{color:"white",bold:!0},"\u{1F4AC} SUGGEST SOMETHING ELSE")),ft.createElement(Io,{marginTop:1,paddingX:1},ft.createElement(hn,{italic:!0,color:"gray"},"Replying to: ",e)),ft.createElement(Io,{marginTop:1,paddingX:1,flexDirection:"row"},ft.createElement(hn,{color:"white",bold:!0},"\u{1F4A0} "),ft.createElement(Eu,{value:s,onChange:i,onSubmit:()=>o(s)})),ft.createElement(Io,{marginTop:1,paddingX:1,marginBottom:1},ft.createElement(hn,{color:"gray",italic:!0},"(Press Enter to send)"))):ft.createElement(Io,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},ft.createElement(Io,{paddingX:1,marginBottom:1},ft.createElement(hn,{color:"white",bold:!0},"\u{1F4AC} AGENT REQUEST: ACTION REQUIRED")),ft.createElement(Io,{paddingX:1,marginBottom:1},ft.createElement(hn,{bold:!0,color:"white"},e)),ft.createElement(Io,{flexDirection:"column",width:"100%"},m.map((a,d)=>{let h=d===u;return ft.createElement(Io,{key:a.id,flexDirection:"column",width:"100%",backgroundColor:h?"#2a2a2a":void 0,paddingX:1,marginBottom:d===m.length-1?0:1},ft.createElement(hn,{color:h?"white":"grey",bold:h},h?"\u276F ":" ",a.label),a.description&&ft.createElement(Io,{marginLeft:4},ft.createElement(hn,{color:"gray",italic:!0},a.description)))})),ft.createElement(Io,{paddingX:1,marginTop:1,marginBottom:1},ft.createElement(hn,{color:"gray",italic:!0},"(Use Arrows to navigate, Enter to confirm)")))},za=bu});var Qa,Za=ae(()=>{Qa=(e=!0,t=!0)=>`
|
|
129
129
|
Your tool syntax is: '[tool:functions.ToolName(args...)]'
|
|
130
130
|
|
|
131
131
|
-- CHAT MANAGEMENT TOOLS (MUST CALL THESE 2 TOOLS ALWAYS) --
|
|
@@ -204,19 +204,19 @@ RULES:
|
|
|
204
204
|
- Suitable for simple requests/greetings`,Off:`EFFORT LEVEL: INSTANT
|
|
205
205
|
No thinking. Immediate response
|
|
206
206
|
RULES:
|
|
207
|
-
- Verify ALL imports and system stability, AVOID ANY Syntax errors, re-read TOOL RESULTS/files to verify`}});import ku from"fs";var pi,tl,ol,nl,
|
|
207
|
+
- Verify ALL imports and system stability, AVOID ANY Syntax errors, re-read TOOL RESULTS/files to verify`}});import ku from"fs";var pi,tl,ol,nl,rl=ae(async()=>{await si();Za();el();pi=null,tl=(e="",t="",o=!0,n=!1)=>{if(!o)return"";let r=e?.length>0&&!n?`-- RECENT CONTEXT FROM OTHER CHATS (PRIORITY: DYNAMIC-LOW, FOCUS: Chat Context > Recent) --
|
|
208
208
|
${e}`:"",i=[t?.length>0?`--- SAVED MEMORIES (PRIORITY: MEDIUM, USER PREFERENCES) ---
|
|
209
|
-
${t}`:"",
|
|
209
|
+
${t}`:"",r].filter(u=>u.length>0);return i.length>0?`[SYSTEM CONTEXT]
|
|
210
210
|
${i.join(`
|
|
211
211
|
|
|
212
212
|
`)}
|
|
213
|
-
`:""},ol=(e,t,o,n,
|
|
213
|
+
`:""},ol=(e,t,o,n,r=!0,s=!1,i="Google",u=!1)=>{let f="";if(t!=="GEM"){let w=t;t==="Fast"&&(w="Off"),t==="Low"&&(w="Minimal"),t==="Standard"&&(w="Medium"),(t==="xHigh"||t==="Max")&&(w="xHigh"),f=hi[w]||hi.Medium}let m=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",c=e.instructions&&e.instructions?.length>0?`User Instructions: ${e.instructions}
|
|
214
214
|
|
|
215
215
|
`:"",a=e.nickname&&e.nickname?.length>0?`User Nickname: ${e.nickname}
|
|
216
216
|
${c.length?"":`
|
|
217
217
|
`}`:"",d=e.name&&e.name?.length>0?`User Name: ${e.name}
|
|
218
218
|
${a.length||c.length?"":`
|
|
219
|
-
`}`:"",h=process.cwd(),p=(()=>{let w=process.cwd().toLowerCase();if(process.platform==="win32"){let E=process.env.SystemRoot?.toLowerCase()||"c:\\windows",A=process.env.ProgramFiles?.toLowerCase()||"c:\\program files",$=process.env["ProgramFiles(x86)"]?.toLowerCase()||"c:\\program files (x86)";return w.startsWith(E)||w.startsWith(A)||w.startsWith($)}else return w==="/"||["/bin","/sbin","/etc","/usr","/var","/root"].some(A=>w.startsWith(A))})(),y=[{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(
|
|
219
|
+
`}`:"",h=process.cwd(),p=(()=>{let w=process.cwd().toLowerCase();if(process.platform==="win32"){let E=process.env.SystemRoot?.toLowerCase()||"c:\\windows",A=process.env.ProgramFiles?.toLowerCase()||"c:\\program files",$=process.env["ProgramFiles(x86)"]?.toLowerCase()||"c:\\program files (x86)";return w.startsWith(E)||w.startsWith(A)||w.startsWith($)}else return w==="/"||["/bin","/sbin","/etc","/usr","/var","/root"].some(A=>w.startsWith(A))})(),y=[{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(s||pi===null){let w=y.filter(E=>ku.existsSync(E.name));pi=o==="Flux"&&w.length>0?`
|
|
220
220
|
-- PROJECT CONTEXT --
|
|
221
221
|
${w.map(E=>`- ${E.name}: ${E.desc}`).join(`
|
|
222
222
|
`)}
|
|
@@ -239,7 +239,7 @@ CRITICAL THINKING POLICY
|
|
|
239
239
|
${Ha(o,m,i.toLowerCase()==="deepseek"?!1:u,i)}
|
|
240
240
|
${T}
|
|
241
241
|
-- MEMORY RULES --
|
|
242
|
-
- Memory: ${
|
|
242
|
+
- Memory: ${r?"Subtly Personalize. Auto Saves":"OFF. Decline Remembering Memories"}
|
|
243
243
|
- Temporal Awareness: RELATIVE TIME REFERENCE eg. few mins ago
|
|
244
244
|
|
|
245
245
|
-- SECURITY RULES --${n.allowExternalAccess?"":`
|
|
@@ -273,38 +273,38 @@ ${t?"If user tell something that is important (like, hobbies, preferences, facts
|
|
|
273
273
|
${Qa(t,o)}
|
|
274
274
|
|
|
275
275
|
Current date and Time: ${new Date().toLocaleString([],{year:"numeric",month:"numeric",day:"numeric",hour:"2-digit",hour12:!0})}.
|
|
276
|
-
=== END SYSTEM PROMPT ===`.trim()});import Xt from"fs-extra";import
|
|
277
|
-
`),n=[],
|
|
276
|
+
=== END SYSTEM PROMPT ===`.trim()});import Xt from"fs-extra";import pn from"path";async function Iu(e,t){try{if(e.type==="create")await Xt.pathExists(e.filePath)&&(await Xt.chmod(e.filePath,438).catch(()=>{}),await Xt.remove(e.filePath));else if(e.type==="update"){if(!e.backupFile)return;let o=pn.join(kn,t.chatId,e.backupFile);if(await Xt.pathExists(o)){let n=pe(o,null);if(!n||!n.data)throw new Error(`Backup container corrupt or empty for ${pn.basename(e.filePath)}`);let r=An(n.data);await Xt.pathExists(e.filePath)&&await Xt.chmod(e.filePath,438).catch(()=>{}),await Xt.writeFile(e.filePath,r,"utf8")}}}catch(o){throw new Error(`Restoration failed for ${pn.basename(e.filePath)}: ${o.message}`)}}async function Mu(e,t,o=7){let n=0;for(;n<o;)try{return await Iu(e,t),!0}catch{if(n++,n>=o)return!1;let s=Math.min(100*Math.pow(2,n-1),5e3);await new Promise(i=>setTimeout(i,s))}return!1}var $o,nt,zo=ae(()=>{Pt();Oo();Xt.ensureDirSync(kn);$o=null;nt={async startTransaction(e,t){$o={id:`tx_prompt_${Date.now()}`,chatId:e,timestamp:new Date().toISOString(),prompt:t.trim(),changes:[],reverted:!1},De(In,$o)},async recordFileChange(e,t=null){if($o)try{if($o.changes.some(i=>i.filePath===e))return;let r=await Xt.pathExists(e)||t?"update":"create",s=null;if(r==="update"){let i=pn.basename(e);s=`${$o.id}_${i}.bak`;let u=pn.join(kn,$o.chatId);await Xt.ensureDir(u);let f=pn.join(u,s),m=t!==null?t:await Xt.readFile(e,"utf8").catch(()=>null);m!==null?De(f,{data:_r(m)}):(r="create",s=null)}$o.changes.push({filePath:e,type:r,backupFile:s}),De(In,$o)}catch{}},async commitTransaction(){if($o)try{let e=pe(Do,[]);if(e.push($o),e.length>512e3){let t=e.shift();if(t.changes)for(let o of t.changes)o.backupFile&&await Xt.remove(pn.join(kn,t.chatId,o.backupFile)).catch(()=>{})}De(Do,e),await Xt.remove(In).catch(()=>{})}catch{}finally{$o=null}},async recoverCrashedTransaction(){try{if(await Xt.pathExists(In)){let e=pe(In,null);if(e?.changes?.length>0){let t=pe(Do,[]);t.some(o=>o.id===e.id)||(t.push(e),De(Do,t))}await Xt.remove(In).catch(()=>{})}}catch{}},async rollbackToBefore(e){let t=pe(Do,null);if(!t)throw new Error("No transaction ledger found.");let o=t.findIndex(i=>i.id===e);if(o===-1)throw new Error(`Transaction [${e}] not found.`);let n=t[o].chatId,r=t[o].prompt,s=t.slice(o).filter(i=>i.chatId===n&&!i.reverted).reverse();for(let i of s){for(let u of[...i.changes].reverse())await Mu(u,i);for(let u of i.changes)if(u.backupFile){let f=pn.join(kn,i.chatId,u.backupFile);await Xt.remove(f).catch(()=>{})}t=t.filter(u=>u.id!==i.id),De(Do,t)}return{success:!0,chatId:n,targetPrompt:r}},async getChatHistory(e){try{return pe(Do,[]).filter(o=>o.chatId===e&&!o.reverted)}catch{return[]}},async deleteChatBackups(e){try{await Xt.remove(pn.join(kn,e));let t=pe(Do,[]),o=t.filter(n=>n.chatId!==e);t.length!==o.length&&De(Do,o)}catch{}}}});import Mo from"fs-extra";import Au from"path";import{nanoid as vu}from"nanoid";var sl,Cs,_o,ks,il,gi,xi,al,Du,Ou,ll,cl,ul,Is,Kr=ae(()=>{Oo();Pt();zo();sl=Promise.resolve(),Cs=e=>{let t=sl.then(async()=>{try{return await e()}catch(o){throw console.error("Lock Operation Failed:",o),o}});return sl=t.catch(()=>{}),t},_o=async()=>{if(await Mo.pathExists(tr))try{return pe(tr,{})}catch{return{}}return{}},ks=async(e,t,o)=>Cs(async()=>{let n=await _o(),r=n[e],s=(o||[]).filter(u=>!u.isUpdateNotification&&!u.isMeta),i=t||(r?r.name:`Session ${e.slice(-6)}`);n[e]={name:i,messages:s,updatedAt:Date.now()},De(tr,n)}),il=async(e,t)=>Cs(async()=>{let o=await _o();o[e]?(o[e].name=t,o[e].updatedAt=Date.now()):o[e]={name:t,messages:[],updatedAt:Date.now()},De(tr,o)}),gi=async e=>Cs(async()=>{let t=await _o();if(delete t[e],De(tr,t),await Mo.pathExists(cn))try{let r=pe(cn,[]);if(Array.isArray(r)){let s=r.filter(i=>Object.keys(i)[0]!==String(e));De(cn,s)}}catch{}let o=pe(So,{});o[e]&&(delete o[e],De(So,o));let n=pe(Vo,{});return n[e]&&(delete n[e],De(Vo,n)),await nt.deleteChatBackups(e),t}),xi=()=>`flow-${vu(6)}`,al=async e=>{if(!e||e==="Never")return;let t=parseInt(e);if(isNaN(t))return;let o=await _o(),n=Date.now(),r=t*24*60*60*1e3,s=0;for(let i in o){let u=o[i];u.updatedAt&&n-u.updatedAt>r&&(await gi(i),s++)}return s},Du=e=>{let t=e.replace(/[\[\]]/g,"").trim(),o=new Date(t);if(!isNaN(o.getTime()))return o.getTime();let n=t.split(/,\s*|\s+/);if(n.length===0)return null;let r=n[0],s=n[1]||"",i=n[2]||"",u=r.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,h=0;if(s){let y=s.split(":").map(Number);a=y[0]||0,d=y[1]||0,h=y[2]||0,i.toLowerCase()==="pm"&&a<12?a+=12:i.toLowerCase()==="am"&&a===12&&(a=0)}let p=new Date(f,m-1,c,a,d,h);return isNaN(p.getTime())?null:p.getTime()},Ou=async e=>{try{if(!await Mo.pathExists(e))return;let t=await Mo.readFile(e,"utf8");if(!t.trim())return;let o=t.split(`
|
|
277
|
+
`),n=[],r=null,s=/^\s*(?:DEBUG|ERROR|SEARCH|PUPPETEER)\b/i;for(let a of o)s.test(a)?(r&&n.push(r),r={header:a,body:[]}):r?r.body.push(a):n.push({header:a,body:[]});r&&n.push(r);let i=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?`
|
|
278
278
|
`+a.body.join(`
|
|
279
279
|
`):""),h=d.match(m);if(h){let p=Du(h[1]);if(p&&u-p>i)continue}f.push(d)}let c=f.join(`
|
|
280
280
|
`).trim();c?await Mo.writeFile(e,c+`
|
|
281
|
-
`,"utf8"):await Mo.writeFile(e,"","utf8")}catch{}},ll=async e=>{try{if(!await Mo.pathExists(e))return;let t=async o=>{let n=await Mo.readdir(o);for(let
|
|
281
|
+
`,"utf8"):await Mo.writeFile(e,"","utf8")}catch{}},ll=async e=>{try{if(!await Mo.pathExists(e))return;let t=async o=>{let n=await Mo.readdir(o);for(let r of n){let s=Au.join(o,r);(await Mo.stat(s)).isDirectory()?(await t(s),(await Mo.readdir(s)).length===0&&await Mo.remove(s)):r.endsWith(".log")&&await Ou(s)}};await t(e)}catch{}},cl=(e,t=4)=>{if(e.length<=1)return e;let o=e[0],n=e.slice(1),r=t*2,s=n.slice(r);return[o,...s]},ul=async(e,t,o)=>Cs(async()=>{let n=pe(cn,[]);Array.isArray(n)||(n=[]);let r={total:t,context:o},s=n.findIndex(i=>Object.keys(i)[0]===String(e));s!==-1?n[s]={[String(e)]:r}:n.push({[String(e)]:r}),De(cn,n)}),Is=async e=>{try{if(!await Mo.pathExists(cn))return{total:0,context:0};let t=pe(cn,[]);if(!Array.isArray(t))return{total:0,context:0};let o=t.find(n=>Object.keys(n)[0]===String(e));return o?o[String(e)]:{total:0,context:0}}catch{return{total:0,context:0}}}});import rt from"fs-extra";import Jo from"path";import yi from"os";var Lu,gn,Pu,wt,Fn,dl,Ms,wi,ml,Ti,Si,fl,hl,$n,Qo,Eo,Ei,bi,pl,gl,As,xl,vs=ae(()=>{Pt();Oo();Lu=()=>{if(process.platform==="win32"){let t=process.env.LOCALAPPDATA||Jo.join(yi.homedir(),"AppData","Local");return Jo.join(t,"FxFl","backups","backup.json")}if(process.platform==="darwin")return Jo.join(yi.homedir(),"Library","Application Support","FxFl","backups","backup.json");let e=process.env.XDG_DATA_HOME||Jo.join(yi.homedir(),".local","share");return Jo.join(e,"fxfl","backups","backup.json")},gn=Lu(),Pu=()=>Math.random().toString(36).substring(2)+Date.now().toString(36),wt=null,Fn=null,dl=0,Ms=!1,wi={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:[]},ml=async()=>{let e=new Date().toISOString().split("T")[0],t=Zt+".tmp",o=null,n=null;try{if(await rt.exists(t)){let s=(await rt.readFile(t,"utf8")).trim(),i=null;if(s.startsWith("{")||s.startsWith("[")?i=JSON.parse(s):i=JSON.parse(An(s)),i&&i.date&&i.stats){o=i;try{await rt.rename(t,Zt)}catch{}}else try{await rt.remove(t)}catch{}}}catch{try{await rt.remove(t)}catch{}}if(!o)try{if(await rt.exists(Zt)){let s=(await rt.readFile(Zt,"utf8")).trim();s.startsWith("{")||s.startsWith("[")?o=JSON.parse(s):o=JSON.parse(An(s))}}catch{}try{if(await rt.exists(gn)){let s=(await rt.readFile(gn,"utf8")).trim();s.startsWith("{")||s.startsWith("[")?n=JSON.parse(s):n=JSON.parse(An(s))}}catch{}let r=null;if(o&&n)if(o.saveId!==n.saveId){r=o;try{await rt.ensureDir(Jo.dirname(gn)),await rt.copy(Zt,gn)}catch{}}else r=o;else if(o&&!n){r=o;try{await rt.ensureDir(Jo.dirname(gn)),await rt.copy(Zt,gn)}catch{}}else if(!o&&n){r=n;try{await rt.ensureDir(Jo.dirname(Zt)),await rt.copy(gn,Zt)}catch{}}if(r&&r.date===e&&r.stats){let s={...wi,...r.stats};return Array.isArray(s.imageCalls)||(s.imageCalls=[]),{...r,stats:s}}return{date:e,stats:{...wi}}},Ti=async()=>{if(!(!Ms||!wt))try{await rt.ensureDir(Jo.dirname(Zt));let e=null;try{if(await rt.exists(Zt)){let r=(await rt.readFile(Zt,"utf8")).trim();r.startsWith("{")||r.startsWith("[")?e=JSON.parse(r):e=JSON.parse(An(r))}}catch{}if(e&&e.date===wt.date&&e.stats){for(let r in wt.stats)if(e.stats[r]!==void 0)if(Array.isArray(wt.stats[r])){let s=Array.isArray(e.stats[r])?e.stats[r]:[],i=wt.stats[r],u=new Map;for(let f of[...s,...i])f&&f.timestamp&&u.set(f.timestamp,f);wt.stats[r]=Array.from(u.values())}else typeof wt.stats[r]=="number"&&(wt.stats[r]=Math.max(wt.stats[r],Number(e.stats[r])||0))}wt.saveId=Pu();let t=Zt+".tmp",o=_r(JSON.stringify(wt,null,2));await rt.writeFile(t,o,"utf8");let n=await rt.open(t,"r+");await rt.fsync(n),await rt.close(n),await rt.rename(t,Zt);try{await rt.ensureDir(Jo.dirname(gn)),await rt.copy(Zt,gn)}catch{}Ms=!1,dl=Date.now()}catch{}},Si=()=>{if(Ms=!0,Fn)return;let e=Date.now(),t=Math.max(0,1500-(e-dl));Fn=setTimeout(async()=>{await Ti(),Fn=null},t),Fn.unref&&Fn.unref()},fl=async()=>{wt=await ml()},hl=async()=>{Fn&&(clearTimeout(Fn),Fn=null),await Ti()},$n=async()=>{let e=new Date().toISOString().split("T")[0];return wt?wt.date!==e&&(wt={date:e,stats:{...wi}},Ms=!0,await Ti()):wt=await ml(),wt&&wt.stats&&!Array.isArray(wt.stats.imageCalls)&&(wt.stats.imageCalls=[]),wt.stats},Qo=async e=>{let t=await $n();t[e]!==void 0&&(t[e]++,Si())},Eo=async(e,t)=>{let o=await $n();o[e]!==void 0&&(o[e]+=Math.floor(t),Si())},Ei=async(e,t)=>{let o=await $n(),n=t.apiTier||"Free",r=t.quotas||{};if(n==="Free"){if(e==="agent"||e==="background")return o.agent+o.background<999999;if(e==="search")return!0}if(n==="Paid"||n==="Custom"){if(e==="agent")return o.agent<(r.agentLimit||999999);if(e==="background")return o.background<(r.backgroundLimit||999999);if(e==="search")return o.search<(r.searchLimit||100)}return!0},bi=e=>{if(!e||e.length===0)return[];let o=[...e].sort((r,s)=>r.timestamp-s.timestamp),n=[];for(let r of o){if(n.length>0){let s=n[n.length-1];if(r.timestamp>=s.start&&r.timestamp<s.end){s.calls.push(r),s.spent+=r.cost;continue}}n.push({start:r.timestamp,end:r.timestamp+36e5,calls:[r],spent:r.cost})}return n},pl=(e,t)=>{if(!e||e.length===0)return .025;let n=bi(e);if(n.length===0)return .025;let r=[];for(let a of n){let d=.025;if(r.length>0){let p=r[r.length-1],y=!1;if(r.length>=2){let T=r[r.length-2];p.ratio>=.8&&T.ratio>=.8&&(y=!0)}if(y)d=.015;else{let T=p.limit,w=p.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 h=d>0?a.spent/d:0;r.push({limit:d,spent:a.spent,ratio:h})}let s=n[n.length-1];if(t<s.end)return r[r.length-1].limit;let i=r[r.length-1].limit,u=i,f=r[r.length-1].ratio,m=s.end,c=0;for(let a=r.length-1;a>=0&&r[a].ratio>=.8;a--)c++;for(;m<=t;){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,i=a}return i},gl=async e=>{let t=e.imageSettings||{keyType:"Default",quality:"Low-High"};if(t.keyType!=="Default")return!0;let n={Low:.001,"Low-High":.002,Medium:.008,"Medium-High":.01,High:.045,Ultra:.0488,Premium:.15}[t.quality]||.002,r=await $n();r.imageCalls||(r.imageCalls=[]);let s=Date.now(),i=bi(r.imageCalls),u=0;if(i.length>0){let m=i[i.length-1];s>=m.start&&s<m.end&&(u=m.spent)}let f=pl(r.imageCalls,s);return u+n<=f},As=async()=>{let e=await $n();e.imageCalls||(e.imageCalls=[]);let t=Date.now(),o=bi(e.imageCalls),n=[],r=0,s=0;if(o.length>0){let m=o[o.length-1];t>=m.start&&t<m.end&&(n=m.calls,r=m.spent,s=Math.max(0,Math.ceil((m.end-t)/(60*1e3))))}let i=pl(e.imageCalls,t),u=Math.max(0,i-r),f=r;return{totalSpent:r,remaining:u,activeCallsCount:n.length,nextResetMin:s,reclaimCost:f,limit:i}},xl=async e=>{let t=e.imageSettings||{keyType:"Default",quality:"Low-High"},n={Low:.001,"Low-High":.002,Medium:.008,"Medium-High":.01,High:.045,Ultra:.0488,Premium:.1}[t.quality]||.002,r=await $n();r.imageCalls||(r.imageCalls=[]),r.imageCalls.push({timestamp:Date.now(),cost:n}),Si()}});import Fu from"puppeteer";var Ci,yl=ae(()=>{Kt();Pt();Ci=async e=>{let{query:t,limit:o=10}=re(e);if(!t)return'ERROR: Missing "query" argument for web_search.';let n=3,r=null;for(let s=1;s<=n;s++){let i=null;try{i=await Fu.launch({headless:!0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let u=await i.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=s===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(t)}`;await u.goto(m,{waitUntil:"networkidle2",timeout:18e4});let c=await u.$$eval(".result",(d,h)=>d.slice(0,h).map((p,y)=>{let T=p.querySelector(".result__a"),w=p.querySelector(".result__snippet"),E=T?T.href:"";E.includes("uddg=")&&(E=decodeURIComponent(E.split("uddg=")[1].split("&")[0]));let A=T?T.innerText.trim():"No Title",$=w?w.innerText.trim():"No Snippet";return`${y+1}. ${A}
|
|
282
282
|
Source: ${E}
|
|
283
283
|
Snippet: ${$}`}),o);if(c.length===0){if((await u.evaluate(()=>document.body.innerText)).includes("anomaly"))throw new Error("ANOMALY_DETECTED");return await i.close(),`No results found for query: [${t}].`}let a=c.join(`
|
|
284
284
|
|
|
285
285
|
`);return await i.close(),`Search results for [${t}]:
|
|
286
286
|
|
|
287
|
-
${a}`}catch(u){if(
|
|
287
|
+
${a}`}catch(u){if(r=u,i&&await i.close(),s<n){let f=Math.pow(2,s)*1e3;await new Promise(m=>setTimeout(m,f))}}}return`ERROR: Search failed after ${n+1} attempts. Last error: ${r.message}`}});import $u from"puppeteer";var ki,wl=ae(()=>{Pt();ki=async e=>{let t=e.match(/url\s*=\s*["'](.*)["']/),o=t?t[1]:e,n=3,r=null;for(let s=1;s<=n;s++){let i=null;try{i=await $u.launch({headless:!0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let u=await i.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=s===1?Math.random()*1e3+500:Math.random()*2e3+1e3;await new Promise(a=>setTimeout(a,f)),await u.goto(o,{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),h;for(;h=d.nextNode();)h.remove();document.querySelectorAll("*").forEach(T=>{let w=T.attributes;for(let E=w.length-1;E>=0;E--){let A=w[E].name;A!=="href"&&A!=="src"&&T.removeAttribute(A)}(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 y=()=>{let T=!1;document.querySelectorAll("*:not(br)").forEach(w=>{w.childNodes.length===0&&!w.innerText.trim()&&(w.remove(),T=!0)}),T&&y()};return y(),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 i.close(),`CLEANED HTML FROM [${o}]:
|
|
288
288
|
|
|
289
289
|
${c}${m.length>3e4?`
|
|
290
290
|
|
|
291
|
-
[TRUNCATED AT 30K CHARS]`:""}`}catch(u){if(
|
|
291
|
+
[TRUNCATED AT 30K CHARS]`:""}`}catch(u){if(r=u,i&&await i.close(),s<n){let f=Math.pow(2,s)*1e3;await new Promise(m=>setTimeout(m,f))}}}return`ERROR: Scrape failed after ${n+1} attempts. Last error: ${r.message}`}});var _u,Ii,Tl=ae(()=>{Oo();Pt();_u=4*(1024*2),Ii=async(e,t={})=>{let o=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 h=new RegExp(`${c}\\s*[:=]\\s*([^,\\s)]+)`,"s"),p=e.match(h);return p?p[1].trim():null},n=o("action"),r=o("method"),s=o("content"),i=o("content-new"),u=o("content-old"),f=o("id"),m=o("chat-id")||t.chatId||t.sessionId||"default-session";if(n==="temp"){if(!s)return"ERROR: Missing 'content' for temp memory.";let c=pe(So,{});c[m]||(c[m]=[]),c[m].push(s),De(So,c);let a=c[m].reduce((d,h)=>d+h.length,0);return`SUCCESS: Temporary context saved for session [${m}]. (Size: ${a} chars)`}if(n==="user"){let c=pe(Ht,[]).map(a=>(a.score===void 0&&(a.score=.5),a));if(r==="add"){if(!s)return"ERROR: Missing 'content' for memory addition.";let a=new Date,d=`${a.getDate()}/${a.getMonth()+1}/${a.getFullYear()}`,h=s.includes("[Saved on:")?s:`${s.trim()} [Saved on: ${d}]`,p=_u,y=c.reduce((A,$)=>A+($.memory?.length||0),0);for(;c.length>0&&y+h.length>p;){let A=c.shift();y-=A.memory?.length||0}let T=o("score"),w=T?parseFloat(T):.5,E={id:`mem-${Date.now().toString(36)}`,memory:h,score:Math.min(2,isNaN(w)?.5:w)};return c.push(E),De(Ht,c),`SUCCESS: Memory added with ID [${E.id}] and score [${E.score}]. (Vault Size: ${y+h.length} chars)`}if(r==="update"){let a=f||u,d=i||s;if(!a||!d)return"ERROR: Missing 'id' or content for update.";let h=c.findIndex(w=>w.id===a);if(h===-1)return`ERROR: Memory ID [${a}] not found.`;let p=new Date,y=`${p.getDate()}/${p.getMonth()+1}/${p.getFullYear()}`,T=d.includes("[Saved on:")?d:`${d.trim()} [Saved on: ${y}]`;return c[h].memory=T,De(Ht,c),`SUCCESS: Memory [${a}] updated.`}if(r==="delete"){let a=f||s;if(!a)return"ERROR: Missing 'id' for deletion.";let d=c.length,h=c.filter(p=>p.id!==a);return h.length===d?`ERROR: Memory ID [${a}] not found.`:(De(Ht,h),`SUCCESS: Memory [${a}] deleted.`)}return`ERROR: Invalid method [${r}] for user memory. Use 'add', 'update', or 'delete'.`}return`ERROR: Unknown action [${n}] for memory tool.`}});var Mi,Sl=ae(()=>{Kr();Kt();Mi=async(e,t={})=>{let o=re(e).title,n=t.chatId||t.sessionId;if(!n)return"ERROR: No active chatId found in tool context.";if(!o)return"ERROR: Missing 'title' argument.";try{return await il(n,o),`SUCCESS: Chat title updated to [${o}] for session [${n}].`}catch(r){return`ERROR: Failed to update chat title: ${r instanceof Error?r.message:String(r)}`}}});import Ds from"fs";import El from"path";var Ai,bl=ae(()=>{Kt();Ai=async(e,t={})=>{let{path:o,StartLine:n,EndLine:r,start_line:s,end_line:i,startLine:u,endLine:f}=re(e),m=parseInt(n||s||u),c=parseInt(r||i||f),a=m||1,d=c||(m?m+800:800);if(!o)return'ERROR: Missing "path" argument for view_file.';let h=El.resolve(process.cwd(),o);try{if(!Ds.existsSync(h))return`ERROR: File [${o}] does not exist.`;if(Ds.statSync(h).isDirectory())return`ERROR: Path [${o}] is a directory. Use list_files instead.`;let y=El.extname(o).toLowerCase();if([".mp4",".mkv",".avi",".mov",".webm",".flv",".wmv",".mpeg",".mpg"].includes(y))return`ERROR: Unable to read. Type ${y.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[y]){if(!(t.isMultiModal!==!1))return`ERROR: Multimodality is not supported for the current model. Unable to load [${o}].`;let q=Ds.readFileSync(h).toString("base64"),Y=w[y];return{text:`[BINARY FILE]: ${o} (${Y}) - Loaded as multimodal part.`,binaryPart:{inlineData:{data:q,mimeType:Y}}}}let E=Ds.readFileSync(h,"utf8");E.startsWith("\uFEFF")&&(E=E.slice(1)),E=E.replace(/\r\n/g,`
|
|
292
292
|
`).replace(/\r/g,`
|
|
293
293
|
`);let A=E.split(`
|
|
294
294
|
`),$=A.length,W=Math.max(0,a-1),D=Math.min($,d),O=A.slice(W,D),M=`File: [${o}] (Showing lines ${W+1}-${D} of ${$}).`,P=O.map((j,G)=>`${String(W+G+1).padStart(4)}: ${j}`).join(`
|
|
295
295
|
`);return`${M}
|
|
296
296
|
|
|
297
|
-
${P}`}catch(p){let y=p instanceof Error?p.message:String(p);return`ERROR: Failed to read file [${o}]: ${y}`}}});import
|
|
297
|
+
${P}`}catch(p){let y=p instanceof Error?p.message:String(p);return`ERROR: Failed to read file [${o}]: ${y}`}}});import wr from"fs";import Cl from"path";var vi,kl=ae(()=>{Kt();zo();vi=async(e,t={})=>{let{path:o,content:n}=re(e);if(!o)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,`
|
|
298
298
|
`).replace(/\r/g,`
|
|
299
|
-
`);let
|
|
300
|
-
${
|
|
299
|
+
`);let r=Cl.resolve(process.cwd(),o),s=Cl.dirname(r);try{await nt.recordFileChange(r);let i="";if(wr.existsSync(r))try{i=`Old File contents:
|
|
300
|
+
${wr.readFileSync(r,"utf8").split(/\r?\n/).map((E,A)=>`${A+1} | ${E}`).join(`
|
|
301
301
|
`)}
|
|
302
302
|
|
|
303
303
|
`}catch{i=`[Note: Could not read existing file for reversal reference]
|
|
304
304
|
|
|
305
|
-
`}
|
|
305
|
+
`}wr.existsSync(s)||wr.mkdirSync(s,{recursive:!0});let f=(T=>T.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
|
|
306
306
|
`).replace(/\r/g,`
|
|
307
|
-
`))(n),m=f.split(/\r?\n/).length,c=Buffer.byteLength(f,"utf8");
|
|
307
|
+
`))(n),m=f.split(/\r?\n/).length,c=Buffer.byteLength(f,"utf8");wr.writeFileSync(r,f,"utf8");let a=wr.readFileSync(r,"utf8"),d=Buffer.byteLength(a,"utf8"),h=a.split(/\r?\n/),p=h.length;if(d===0&&c>0)return a=null,`ERROR: CRITICAL FAILURE: Verification failed. File [${o}] is empty on disk despite success report!`;let y="";if(p<=200)y=h.join(`
|
|
308
308
|
`);else{let T=h.slice(0,100).join(`
|
|
309
309
|
`),w=h.slice(-100).join(`
|
|
310
310
|
`);y=`${T}
|
|
@@ -317,29 +317,29 @@ ${w}`}return a=null,`SUCCESS: File [${o}] saved.
|
|
|
317
317
|
${i}- Content Preview:
|
|
318
318
|
${y}
|
|
319
319
|
|
|
320
|
-
[SYSTEM] Check the content preview for verification [/SYSTEM]`}catch(i){let u=i instanceof Error?i.message:String(i);return`ERROR: Failed to write file [${o}]: ${u}`}}});import Di from"fs";import Nu from"path";var Oi,Il=ae(()=>{Kt();
|
|
320
|
+
[SYSTEM] Check the content preview for verification [/SYSTEM]`}catch(i){let u=i instanceof Error?i.message:String(i);return`ERROR: Failed to write file [${o}]: ${u}`}}});import Di from"fs";import Nu from"path";var Oi,Il=ae(()=>{Kt();zo();or();Oi=async(e,t={})=>{let o=re(e),n=o.path;if(!n)return'ERROR: Missing "path" argument for update_file.';let{patchPairs:r,error:s}=ps(o);if(s)return`ERROR: ${s}`;if(r.length===0)return"ERROR: No valid replacement pairs found. Use replaceContent1, newContent1, etc.";let i=Nu.resolve(process.cwd(),n);try{if(!Di.existsSync(i))return`ERROR: File [${n}] does not exist. Use write_file instead.`;let u=t.forcedContent||Di.readFileSync(i,"utf8");u.startsWith("\uFEFF")&&(u=u.slice(1));let f=u.replace(/\r\n/g,`
|
|
321
321
|
`).replace(/\r/g,`
|
|
322
|
-
`),{content:m,results:c}=
|
|
322
|
+
`),{content:m,results:c}=gs(f,r),a=c.filter(p=>!p.success),d=c.filter(p=>p.success);if(d.length===0)return`ERROR: Patch Failed to apply to [${n}].
|
|
323
323
|
${a.map(p=>` \u2022 ${p.error}`).join(`
|
|
324
|
-
`)}`;await
|
|
324
|
+
`)}`;await nt.recordFileChange(i,f),Di.writeFileSync(i,m,"utf8");let h=xs(f,m,c,12);return a.length>0?`SUCCESS: File [${n}] updated with some blocks failed. [${d.length}/${r.length}] blocks applied.
|
|
325
325
|
|
|
326
326
|
Failures:
|
|
327
327
|
${a.map(p=>` \u2022 ${p.error}`).join(`
|
|
328
328
|
`)}
|
|
329
329
|
|
|
330
|
-
${h}`:`SUCCESS: File [${n}] updated. [${c.length}/${
|
|
330
|
+
${h}`:`SUCCESS: File [${n}] updated. [${c.length}/${r.length}] blocks applied.
|
|
331
331
|
|
|
332
|
-
${h}`}catch(u){let f=u instanceof Error?u.message:String(u);return`ERROR: Failed to update file [${n}]: ${f}`}}});import
|
|
332
|
+
${h}`}catch(u){let f=u instanceof Error?u.message:String(u);return`ERROR: Failed to update file [${n}]: ${f}`}}});import Os from"fs";import Ml from"path";var Li,Al=ae(()=>{Kt();Li=async e=>{let{path:t="."}=re(e),o=Ml.resolve(process.cwd(),t);try{if(!Os.existsSync(o))return`ERROR: Path [${t}] does not exist.`;if(!Os.statSync(o).isDirectory())return`ERROR: Path [${t}] is a file, not a directory. Use view_file instead.`;let r=Os.readdirSync(o),s=r.length,i=100,u=r.slice(0,i),f=[];for(let d of u){let h=Ml.join(o,d),p="\u{1F4C4}",y={name:d,type:"unknown",size:"N/A",mtime:"N/A"};try{let T=Os.statSync(h);y={name:d,type:T.isDirectory()?"directory":"file",size:(T.size/1024).toFixed(1)+" KB",mtime:T.mtime.toLocaleString()}}catch{y.type="inaccessible"}f.push(y)}let m=f.map(d=>{let h=d.type==="directory"?"\u{1F4C1}":d.type==="file"?"\u{1F4C4}":"\u2753";return d.type==="directory"?`${h} ${d.name} - [DIR] - [Modified: ${d.mtime}]`:`${h} ${d.name} - [Size: ${d.size}] - [Modified: ${d.mtime}]`}).join(`
|
|
333
333
|
`),c=`
|
|
334
334
|
|
|
335
|
-
(Total items in folder: ${
|
|
335
|
+
(Total items in folder: ${s})`;s>i&&(c=`
|
|
336
336
|
|
|
337
|
-
\u26A0\uFE0F TRUNCATED: Showing first ${i} of ${
|
|
337
|
+
\u26A0\uFE0F TRUNCATED: Showing first ${i} of ${s} items.`);let a=`Detailed folder stats for [${t}]:
|
|
338
338
|
|
|
339
|
-
${m}${c}`;return
|
|
339
|
+
${m}${c}`;return r.length=0,u.length=0,f.length=0,a}catch(n){let r=n instanceof Error?n.message:String(n);return`ERROR: Failed to read folder [${t}]: ${r}`}}});var Pi,vl=ae(()=>{Kt();Pi=async(e,t)=>{let o=re(e),{question:n}=o;if(!n)return'ERROR: Missing "question" argument for ask.';if(!t.onAskUser)return"ERROR: onAskUser callback not provided in tool context.";let r=[];Object.keys(o).forEach(s=>{if(s.startsWith("option")){let i=o[s];if(typeof i=="string"&&i.includes("::")){let[u,f]=i.split("::");r.push({id:s,label:u.trim(),description:f.trim()})}else r.push({id:s,label:String(i).trim(),description:""})}});try{return`USER CHOOSE: ${await t.onAskUser(n,r)}`}catch(s){return`ERROR: Failed to get user input: ${s instanceof Error?s.message:String(s)}`}}});import Bu from"puppeteer";import Tr from"path";import nr from"fs-extra";import{PDFDocument as Ru}from"pdf-lib";var Fi,Dl=ae(()=>{Kt();zo();Fi=async e=>{let{path:t,content:o,orientation:n="portrait",margin:r="0px"}=re(e);if(!t)return'ERROR: Missing "path" argument for write_pdf.';if(!o)return'ERROR: Missing "content" (HTML/CSS) for write_pdf.';let s=Tr.resolve(process.cwd(),t),i=null;try{await nr.ensureDir(Tr.dirname(s)),await nt.recordFileChange(s),i=await Bu.launch({headless:!0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let u=await i.newPage(),f=o,m={},c=async D=>{if(!D||D.startsWith("http://")||D.startsWith("https://")||D.startsWith("data:"))return null;try{let O=Tr.resolve(process.cwd(),D);if(await nr.pathExists(O)){let M=Tr.extname(O).toLowerCase().replace(".","")||"png",P=M==="jpg"?"jpeg":M==="svg"?"svg+xml":M,j=await nr.readFile(O,"base64");return`data:image/${P};base64,${j}`}}catch{}return null},a=/<link[^>]+href=["']([^"']+)["']/gi,d={},h;for(;(h=a.exec(o))!==null;){let D=h[1],O=h[0];if(D&&O.toLowerCase().includes("stylesheet")&&!D.startsWith("http://")&&!D.startsWith("https://")&&!D.startsWith("data:"))try{let M=Tr.resolve(process.cwd(),D);if(await nr.pathExists(M)){let P=await nr.readFile(M,"utf-8");d[O]=`<style>${P}</style>`}}catch{}}for(let[D,O]of Object.entries(d))f=f.split(D).join(O);let p=/<img[^>]+src=["']([^"']+)["']/gi;for(;(h=p.exec(f))!==null;){let D=h[1];if(D&&!m[D]){let O=await c(D);O&&(m[D]=O)}}let y=/url\(\s*['"]?([^'")]+?)['"]?\s*\)/gi;for(;(h=y.exec(f))!==null;){let D=h[1].trim();if(D&&!m[D]){let O=await c(D);O&&(m[D]=O)}}for(let[D,O]of Object.entries(m)){let M=D.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&"),P=new RegExp(`(src=["'])(${M})(["'])`,"gi");f=f.replace(P,`$1${O}$3`);let j=new RegExp(`url\\(\\s*(['"]?)(${M})\\1\\s*\\)`,"gi");f=f.replace(j,`url($1${O}$1)`)}let T=`
|
|
340
340
|
<style>
|
|
341
341
|
@page {
|
|
342
|
-
margin: ${
|
|
342
|
+
margin: ${r};
|
|
343
343
|
}
|
|
344
344
|
body {
|
|
345
345
|
margin: 0;
|
|
@@ -366,7 +366,7 @@ ${m}${c}`;return s.length=0,u.length=0,f.length=0,a}catch(n){let s=n instanceof
|
|
|
366
366
|
</style>
|
|
367
367
|
<div class="watermark">Generated by FluxFlow CLI (AI)</div>
|
|
368
368
|
${f}
|
|
369
|
-
`;await u.setContent(T,{waitUntil:"networkidle0",timeout:18e4});let w=await u.pdf({format:"A4",landscape:String(n).toLowerCase()==="landscape",margin:{top:
|
|
369
|
+
`;await u.setContent(T,{waitUntil:"networkidle0",timeout:18e4});let w=await u.pdf({format:"A4",landscape:String(n).toLowerCase()==="landscape",margin:{top:r,right:r,bottom:r,left:r},printBackground:!0}),E=await Ru.load(w),A=Tr.basename(t);E.setTitle(`FluxFlow_${A}`),E.setAuthor("FluxFlow CLI"),E.setSubject("Generated with Agentic AI System"),E.setKeywords(["FluxFlow","AI","Agentic","Automated"]),E.setCreator("FluxFlow PDF Engine"),E.setProducer("FluxFlow (Generative AI)");let $=await E.save();await nr.writeFile(s,$);let W=await nr.stat(s);return`SUCCESS: PDF generated successfully at [${t}] (${(W.size/1024).toFixed(2)} KB).`}catch(u){let f=u instanceof Error?u.message:String(u);return`ERROR: Failed to generate PDF [${t}]: ${f}`}finally{i&&await i.close()}}});import Ol from"fs-extra";import $i from"path";import Uu from"html-to-docx";var _i,Ll=ae(()=>{Kt();zo();_i=async e=>{let{path:t,content:o}=re(e);if(!t)return'ERROR: Missing "path" argument for write_docx.';if(!o)return'ERROR: Missing "content" (HTML) for write_docx.';let n=$i.resolve(process.cwd(),t);try{await Ol.ensureDir($i.dirname(n)),await nt.recordFileChange(n);let r=$i.basename(t),s=o.includes("<html")?o:`
|
|
370
370
|
<!DOCTYPE html>
|
|
371
371
|
<html lang="en">
|
|
372
372
|
<head>
|
|
@@ -377,48 +377,48 @@ ${m}${c}`;return s.length=0,u.length=0,f.length=0,a}catch(n){let s=n instanceof
|
|
|
377
377
|
${o}
|
|
378
378
|
</body>
|
|
379
379
|
</html>
|
|
380
|
-
`,i=await Uu(
|
|
381
|
-
- Size: ${(i.length/1024).toFixed(1)} KB`}catch(
|
|
380
|
+
`,i=await Uu(s,null,{title:`FluxFlow_${r}`,creator:"FluxFlow CLI",description:"Generated by Agentic AI System",table:{row:{cantSplit:!0}},footer:!0,pageNumber:!0});return await Ol.writeFile(n,i),`SUCCESS: Word document [${t}] generated successfully.
|
|
381
|
+
- Size: ${(i.length/1024).toFixed(1)} KB`}catch(r){let s=r instanceof Error?r.message:String(r);return`ERROR: Failed to generate DOCX [${t}]: ${s}`}}});import Ni from"fs/promises";import Xr from"path";async function Pl(e,t,o=e,n=1){if(n>12)return[];let r=[],s;try{s=await Ni.readdir(e,{withFileTypes:!0})}catch{return[]}for(let i of s){let u=Xr.join(e,i.name),f=Xr.relative(o,u),m=f.split(Xr.sep).map(a=>a.toLowerCase());if(!t.some(a=>m.includes(a.toLowerCase())))if(i.isDirectory()){let a=await Pl(u,t,o,n+1);r=r.concat(a)}else i.isFile()&&r.push({fullPath:u,relativePath:f})}return r}var Bi,Fl=ae(()=>{Kt();Bi=async e=>{let{keyword:t,file:o}=re(e);if(!t)return'ERROR: Missing "keyword" argument.';let n=["node_modules",".git","dist",".next",".gemini",".exe",".dll",".png",".jpg",".jpeg",".gif",".zip",".tgz"],r=150;try{let s=[],i=process.cwd();if(o){let a=Xr.resolve(i,o);try{(await Ni.stat(a)).isFile()&&s.push({fullPath:a,relativePath:Xr.relative(i,a)})}catch{return`ERROR: File not found: ${o}`}}else s=await Pl(i,n);let u=s.map(async a=>{try{let d=await Ni.readFile(a.fullPath,"utf-8");if(d.includes("\0"))return[];let h=d.split(/\r?\n/),p=[];for(let y=0;y<h.length;y++)if(h[y].includes(t)){let T=a.relativePath.replace(/\\/g,"/");p.push(`${T} \u2192 ${y+1}`)}return p}catch{return[]}}),m=(await Promise.all(u)).flat().slice(0,r);if(typeof global.gc=="function"&&global.gc(),m.length===0)return`Found 0 matches for keyword: "${t}"${o?` in file: ${o}`:". Try to specify files"}`;let c=`Found ${m.length} matches:
|
|
382
382
|
|
|
383
383
|
`;return c+=m.join(`
|
|
384
|
-
`),c}catch(
|
|
385
|
-
`)[0].match(/for\s*(?:await\s*)?\((.*)\)/);return
|
|
386
|
-
`)[0],60);if(t==="pair"){let n=e.childForFieldName("key");return n?No(n.text.replace(/["']/g,""),40):null}if(t==="assignment_expression"){let n=e.childForFieldName("left");return n?`${No(n.text,30)} = ...`:null}if(t==="variable_declarator"){let n=e.childForFieldName("name")||e.children.find(
|
|
384
|
+
`),c}catch(s){return`ERROR: ${s.message}`}}});import $l from"fs-extra";import Ri from"path";var Wu,Ui,_l=ae(()=>{Kt();fs();vs();zo();Wu=(e,t={})=>{try{if(e.length<8||e[0]!==137||e[1]!==80||e[2]!==78||e[3]!==71)return e;let o=[],n=[];for(let i=0;i<256;i++){let u=i;for(let f=0;f<8;f++)u&1?u=3988292384^u>>>1:u=u>>>1;n[i]=u}let r=i=>{let u=4294967295;for(let f=0;f<i.length;f++)u=n[(u^i[f])&255]^u>>>8;return(u^4294967295)>>>0},s=(i,u)=>{let f=Buffer.from(i,"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=r(a.subarray(4,8+c));return a.writeUInt32BE(d,8+c),a};for(let[i,u]of Object.entries(t))u!=null&&o.push(s(i,String(u)));if(o.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,...o,f])}return e}catch{return e}},Ui=async(e,t={})=>{let o=re(e),n=o.prompt||o.text,r=o.path||o.outputPath||o.output||"generated_image.png",s=o.ratio;if(!n)return'ERROR: Missing "prompt" argument for generate_image.';let i=["nsfw","naked","nudity","nude","porn","sex","xxx","erotic","gore","bloody","violence","abuse","suicide","murder","hentai","pedophile","rape"],u=n.toLowerCase();if(i.some(m=>u.includes(m)))return"ERROR: Prompt blocked by system safety filter (inappropriate or unsafe content detected).";try{let m=await hr();if(!await gl(m))return`ERROR: Insufficient Quota for selected quality. Either tell user reduce quality or wait for next refresh cycle (${(await As()).nextResetMin||60}m).`;let a=m.imageSettings||{keyType:"Default",quality:"Low-High",apiKey:""},d=a.keyType==="Custom"&&a.apiKey?a.apiKey:FALLBACK_IMAGE_KEY,p={Low:"flux","Low-High":"zimage",Medium:"gptimage","Medium-High":"gptimage",High:"qwen-image",Ultra:"gptimage-large",Premium:"nanobanana-pro"}[a.quality]||"zimage",y=1024,T=1024;if(s){let N=s.replace(/\s+/g,"");N==="16:9"?(y=1024,T=576):N==="9:16"?(y=576,T=1024):N==="4:3"?(y=1024,T=768):N==="3:4"?(y=768,T=1024):N==="1:1"&&(y=1024,T=1024)}let w=Math.floor(Math.random()*1e7),A=`https://gen.pollinations.ai/image/${encodeURIComponent(n)}?model=${p}&width=${y}&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(A,{method:"GET",headers:{Authorization:`Bearer ${d}`}});if(!$.ok){let N=$.status,ge="";try{ge=await $.text()}catch{}return N===402||ge.includes("Insufficient balance")||ge.includes("PAYMENT_REQUIRED")?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed with status [${N}]: ${ge||"Unknown API Error"}`}if(($.headers.get("content-type")||"").includes("application/json")){let N=await $.json();return N.status===402||N.error&&N.error.code==="PAYMENT_REQUIRED"?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed: ${N.error?.message||JSON.stringify(N)}`}let D=await $.arrayBuffer(),O=Buffer.from(D),M={Title:n,Description:"Generated via FluxFlow CLI",Software:"FluxFlow CLI",Author:"FluxFlow","Creation Time":new Date().toISOString(),Prompt:n,Model:`Fluxflow:${p}`,Ratio:s||"1:1",Seed:String(w)};O=Wu(O,M);let P=Ri.resolve(process.cwd(),r);await $l.ensureDir(Ri.dirname(P)),await nt.recordFileChange(P),await $l.writeFile(P,O),await xl(m);let j=Ri.extname(r).toLowerCase(),q={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".webp":"image/webp"}[j]||"image/png";return t.isMultiModal!==!1?{text:`SUCCESS: Image successfully generated from prompt [${n}] and saved to [${r}]. Output attached to multimodal part`,binaryPart:{inlineData:{data:O.toString("base64"),mimeType:q}}}:`SUCCESS: Image successfully generated from prompt [${n}] and saved to [${r}].`}catch(m){return`ERROR: Failed during image generation: ${m instanceof Error?m.message:String(m)}`}}});var Vr,Nl=ae(()=>{Oo();Pt();Vr=async(e,t={})=>{let o=s=>{let i=new RegExp(`${s}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),u=e.match(i);return u?u[2].trim():null},n=o("id"),r=o("summary");if(!n||!r)return"ERROR: Missing 'id' or 'summary' for saveSummary tool.";try{let s=pe(So,{}),i=pe(Vo,{});return i[n]=r,delete s[n],De(Vo,i),De(So,s),`SUCCESS: Saved summary and purged raw memories for chat [${n}].`}catch(s){let i=s instanceof Error?s.message:String(s);return`ERROR: Failed to save summary for chat [${n}]: ${i}`}}});var Sr,Bl=ae(()=>{Oo();Pt();Sr=async(e,t={})=>{let n=(r=>{let s=new RegExp(`${r}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),i=e.match(s);return i?i[2].trim():null})("id");if(!n)return"ERROR: Missing 'id' parameter for addMemScore tool.";try{let r=pe(Ht,[]),s=!1,i=[];for(let c of r)c.score===void 0&&(c.score=.5),c.id===n?(c.score=Math.min(2,c.score+.2),s=!0):(c.score*=.98,c.score<.05&&(c.score=0)),c.score=Math.round(c.score*1e5)/1e5,c.score>0&&i.push(c);if(De(Ht,i),!s)return`WARNING: Memory ID [${n}] not found. Other memories decayed by -0.01.`;let u=i.find(c=>c.id===n),f=u?u.score.toFixed(2):"deleted (score <= 0)",m=r.length-i.length;return`SUCCESS: Adjusted memory scores. Target [${n}] is now ${f}.${m>0?` Purged ${m} decayed memories.`:""}`}catch(r){let s=r instanceof Error?r.message:String(r);return`ERROR: Failed to adjust memory score for [${n}]: ${s}`}}});import rr from"fs-extra";import Wi from"path";import Yu from"https";async function Yi(e,t=null){let o=t||`https://unpkg.com/tree-sitter-wasms@0.1.13/out/${e}`,n=Wi.join(Mn,e);return await rr.ensureDir(Mn),new Promise((r,s)=>{let i={headers:{"User-Agent":"FluxFlow-Agent"}};Yu.get(o,i,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(o);m=`${c.protocol}//${c.host}${m}`}Yi(e,m).then(r).catch(s);return}if(u.statusCode!==200){s(new Error(`Failed to download ${e}: HTTP ${u.statusCode}`));return}let f=rr.createWriteStream(n);u.pipe(f),f.on("finish",()=>{f.close(),r()})}).on("error",u=>{rr.existsSync(n)&&rr.unlink(n,()=>{}),s(u)})})}function Ul(e){let t=Wi.join(Mn,e);return rr.existsSync(t)}async function Wl(e){let t=Wi.join(Mn,e);rr.existsSync(t)&&await rr.unlink(t)}var Rl,ji=ae(()=>{Pt();Rl={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 Hi from"fs-extra";import sr from"path";import{createRequire as ju}from"module";function No(e,t=50){if(!e)return"";let o=e.replace(/\s+/g," ").trim();return o.length>t?o.substring(0,t-3)+"...":o}function Xl(e){let t=e.type;if(t==="if_statement"){let n=e.childForFieldName("condition");return n?`if (${No(n.text,40)})`:"if"}if(t==="else_clause")return"else";if(t==="while_statement"||t==="do_statement"){let n=e.childForFieldName("condition");return`${t.split("_")[0]} (${n?No(n.text,40):""})`}if(t==="for_statement"||t==="for_in_statement"||t==="for_of_statement"){let r=e.text.split(`
|
|
385
|
+
`)[0].match(/for\s*(?:await\s*)?\((.*)\)/);return r?`for (${No(r[1],40)})`:"for"}if(t==="switch_statement"){let n=e.childForFieldName("value");return`switch (${n?No(n.text,40):""})`}if(t==="try_statement")return"try";if(t==="catch_clause")return"catch";if(t==="element"||t==="script_element"||t==="style_element"||t==="jsx_element"||t==="jsx_self_closing_element"){let n=e.childForFieldName("opening_element")||e.childForFieldName("start_tag")||e.children.find(s=>s.type==="start_tag")||e,r=n.childForFieldName("name")||n.childForFieldName("tag_name")||n.children.find(s=>s.type==="tag_name");return r?`<${No(r.text,30)}>`:null}if(["import_declaration","import_from_statement","import_statement","preproc_include"].includes(t))return No(e.text.split(`
|
|
386
|
+
`)[0],60);if(t==="pair"){let n=e.childForFieldName("key");return n?No(n.text.replace(/["']/g,""),40):null}if(t==="assignment_expression"){let n=e.childForFieldName("left");return n?`${No(n.text,30)} = ...`:null}if(t==="variable_declarator"){let n=e.childForFieldName("name")||e.children.find(r=>["identifier","object_pattern","array_pattern"].includes(r.type));return n?No(n.text,40):null}let o=e.childForFieldName("name")||e.childForFieldName("declarator")||e.children.find(n=>["identifier","type_identifier","field_identifier","property_identifier","shorthand_property_identifier"].includes(n.type));if(o){if(o.type.includes("declarator")){let n=o.descendantsOfType("identifier")[0]||o.descendantsOfType("field_identifier")[0];if(n)return No(n.text,40)}return No(o.text,40)}if(["arrow_function","function_expression","function_declaration"].includes(t)){let n=e.parent;for(;n&&n.type!=="program";){let r=Xl(n);if(r)return r;if(!Kl.has(n.type))break;n=n.parent}}return null}function Hu(e){let t=[];function o(n){for(let r of n.children)Gl.has(r.type)?t.push(r):o(r)}return o(e),t}function Gu(e){return e.replace(/_([a-z])/g,t=>t[1].toUpperCase())}function Vl(e,t=0,o=!0,n="",r=null,s=12){let i=e.type,u=Xl(e),f=Gl.has(i)||t===0,m=Hu(e),c=f&&t>0&&(Kl.has(i)&&m.length>0||u!==null&&u===r&&m.length>0),a="",d=n,h=t,p=r;if(f&&!c){let y=e.startPosition.row+1,T=e.endPosition.row+1,w=Gu(i),E=u?`${w} [${u}]`:w;t===0?(a+=`\u{1F4C1} ROOT (Lines: ${y}-${T})
|
|
387
387
|
`,d=n):(a+=`${n}${o?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 "}${E} (Lines: ${y}-${T})
|
|
388
|
-
`,d+=o?" ":"\u2502 "),h=t+1,p=u}return h>
|
|
389
|
-
`:m.forEach((y,T)=>{let w=T===m.length-1;a+=Vl(y,h,c?o&&w:w,d,p,
|
|
388
|
+
`,d+=o?" ":"\u2502 "),h=t+1,p=u}return h>s&&m.length>0?a+=`${d}\u2514\u2500\u2500 ... depth exceeded ...
|
|
389
|
+
`:m.forEach((y,T)=>{let w=T===m.length-1;a+=Vl(y,h,c?o&&w:w,d,p,s)}),a}var Hl,Yl,jl,Gl,Kl,Gi,ql=ae(()=>{ji();Pt();Kt();Hl=ju(import.meta.url),Yl=Hl("web-tree-sitter"),jl=!1,Gl=new Set(["class_declaration","function_declaration","method_definition","arrow_function","function_expression","if_statement","else_clause","for_statement","for_in_statement","for_of_statement","while_statement","do_statement","switch_statement","try_statement","catch_clause","variable_declarator","export_statement","lexical_declaration","variable_declaration","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","assignment_expression","pair","class_specifier","struct_specifier","enum_specifier","field_declaration","element","script_element","style_element"]),Kl=new Set(["export_statement","lexical_declaration","variable_declaration","variable_declarator","pair","assignment_expression"]);Gi=async e=>{let t;try{t=re(e).path}catch{return`ERROR: Failed to parse arguments: ${e}`}if(!t)return'ERROR: No file path provided. Use [tool:functions.FileMap(path="...")]';let o=sr.isAbsolute(t)?t:sr.resolve(process.cwd(),t);if(!Hi.existsSync(o))return`ERROR: File not found: ${t}`;let n=sr.extname(o).slice(1).toLowerCase(),r=Rl[n];if(!r)return`ERROR: Unsupported file extension: .${n}`;let s=sr.resolve(Mn,r);if(!Hi.existsSync(s))return`ERROR: Parser for .${n} not found. Please download it in Settings > Other.`;try{let i=Yl.Parser;if(!jl){let p;try{p=sr.join(sr.dirname(Hl.resolve("web-tree-sitter")),"tree-sitter.wasm")}catch{p=sr.join(process.cwd(),"node_modules","web-tree-sitter","tree-sitter.wasm")}await i.init({locateFile:y=>y==="tree-sitter.wasm"||y.endsWith("tree-sitter.wasm")?p:y}),jl=!0}let u=new i,f=await Yl.Language.load(s);u.setLanguage(f);let m=await Hi.readFile(o,"utf8"),c=m.split(`
|
|
390
390
|
`).length,a=12;c>1e4?a=2:c>=8e3?a=3:c>=5e3?a=5:c>=4e3?a=8:c>2e3&&(a=10);let d=u.parse(m),h=Vl(d.rootNode,0,!0," ",null,a);return`\u{1F4C4} File Map for: ${t}
|
|
391
391
|
${h}`}catch(i){let u=i instanceof Error?i.message:typeof i=="object"?JSON.stringify(i):String(i),f=i instanceof Error?`
|
|
392
|
-
Stack: ${i.stack}`:"";return`ERROR: Failed to map file: ${u}${f}`}}});import _n from"fs";import zl from"path";var
|
|
392
|
+
Stack: ${i.stack}`:"";return`ERROR: Failed to map file: ${u}${f}`}}});import _n from"fs";import zl from"path";var Ls,Jl=ae(()=>{Kt();Pt();zo();Ls=async(e,t={})=>{let{method:o,tasks:n,markDone:r}=re(e),s=t.chatId||"default";if(!o)return'ERROR: Missing "method" argument for todo tool (create/append/get).';let i=zl.join(er,"plan",s),u=zl.join(i,"todo.md"),f=c=>{if(!c||Array.isArray(c))return c;let a=String(c).trim();if(a.startsWith("[")&&a.endsWith("]")){let d=a.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);return d?d.map(h=>h.slice(1,-1).replace(/\\(.)/g,"$1")):a.slice(1,-1).split(",").map(h=>h.trim()).filter(Boolean)}return c},m=c=>{let a=f(c);return a?(Array.isArray(a)?a:String(a).split(`
|
|
393
393
|
`)).map(h=>{let p=String(h).trim();return p?p.startsWith("- [ ]")||p.startsWith("- [x]")||p.startsWith("- [X]")?p:`- [ ] ${p}`:null}).filter(Boolean).join(`
|
|
394
394
|
`)+`
|
|
395
|
-
`:""};try{if(_n.existsSync(i)||_n.mkdirSync(i,{recursive:!0}),o==="create"){if(!n)return'ERROR: Missing "tasks" for create method.';let c=m(n);return _n.writeFileSync(u,c,"utf8"),`SUCCESS: TASK LIST CREATED (${(c.match(/^- \[ [xX ]\]/gm)||[]).length} total)
|
|
396
|
-
${c}`}if(o==="append"){if(!n)return'ERROR: Missing "tasks" for append method.';let c=m(n);_n.appendFileSync(u,c,"utf8");let a=_n.readFileSync(u,"utf8"),d=(a.match(/^- \[ [xX ]\]/gm)||[]).length,h=(a.match(/^- \[x\]/gim)||[]).length,p=(c.match(/^- \[ [xX ]\]/gm)||[]).length;return`SUCCESS: TASK APPENDED (${h} completed, ${d-h} left, ${p} added)
|
|
397
|
-
${a}`}if(o==="get"){if(!_n.existsSync(u))return"TODO GET: No task list found for this session.";let c=_n.readFileSync(u,"utf8"),a=0;if(
|
|
395
|
+
`:""};try{if(_n.existsSync(i)||_n.mkdirSync(i,{recursive:!0}),o==="create"){if(!n)return'ERROR: Missing "tasks" for create method.';let c=m(n);return await nt.recordFileChange(u),_n.writeFileSync(u,c,"utf8"),`SUCCESS: TASK LIST CREATED (${(c.match(/^- \[ [xX ]\]/gm)||[]).length} total)
|
|
396
|
+
${c}`}if(o==="append"){if(!n)return'ERROR: Missing "tasks" for append method.';let c=m(n);await nt.recordFileChange(u),_n.appendFileSync(u,c,"utf8");let a=_n.readFileSync(u,"utf8"),d=(a.match(/^- \[ [xX ]\]/gm)||[]).length,h=(a.match(/^- \[x\]/gim)||[]).length,p=(c.match(/^- \[ [xX ]\]/gm)||[]).length;return`SUCCESS: TASK APPENDED (${h} completed, ${d-h} left, ${p} added)
|
|
397
|
+
${a}`}if(o==="get"){if(!_n.existsSync(u))return"TODO GET: No task list found for this session.";let c=_n.readFileSync(u,"utf8"),a=0;if(r){let y=f(r),T=(Array.isArray(y)?y:[y]).map(A=>String(A).replace(/^- \[[xX ]\]\s*/i,"").trim()).filter(Boolean),w=c.split(`
|
|
398
398
|
`),E=!1;for(let A of T){let $=!1;for(let W=0;W<w.length;W++)if(w[W].includes(A)&&/^- \[\s\]/.test(w[W].trim())){w[W]=w[W].replace("- [ ]","- [x]"),$=!0,E=!0,a++;break}if(!$){for(let W=0;W<w.length;W++)if(w[W].toLowerCase().includes(A.toLowerCase())&&/^- \[\s\]/.test(w[W].trim())){w[W]=w[W].replace("- [ ]","- [x]"),$=!0,E=!0,a++;break}}}E&&(c=w.join(`
|
|
399
|
-
`),_n.writeFileSync(u,c,"utf8"))}let d=(c.match(/^- \[ [xX ]\]/gm)||[]).length,h=(c.match(/^- \[x\]/gim)||[]).length;return`${a>0?`SUCCESS: ${a} TASK(S) MARKED DONE`:"TODO GET"}: ${h} Completed, ${d-h} left
|
|
400
|
-
${c}`}return`ERROR: Unknown method "${o}". Use create, append, or get.`}catch(c){return`ERROR: Todo tool failure: ${c instanceof Error?c.message:String(c)}`}}});var Ku,
|
|
401
|
-
|
|
402
|
-
`+
|
|
403
|
-
`);h=$.pop();for(let W of $){let D=W.trim();if(!(!D||!D.startsWith("data: "))){if(D==="data: [DONE]")break;try{let O=JSON.parse(D.substring(6)),M=O.choices?.[0]?.delta,P=O.usage;if(P&&(y={totalTokenCount:P.total_tokens||P.prompt_tokens+P.completion_tokens,promptTokenCount:P.prompt_tokens||0,candidatesTokenCount:P.completion_tokens||0,cachedContentTokenCount:P.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:P.completion_tokens_details?.reasoning_tokens||0},w=!0),M){let j=M.reasoning_content||null;j&&(p.push({text:j,thought:!0}),w=!0),M.content&&(p.push({text:M.content}),w=!0)}}catch{}}}Date.now()-T>=150&&w&&(yield{candidates:p.length>0?[{content:{parts:[...p]}}]:[],usageMetadata:y},p=[],T=Date.now(),w=!1)}},na=async function*(e,t,o,n,s,
|
|
404
|
-
`);O=N.pop();for(let
|
|
405
|
-
`);y=D.pop();for(let O of D){let M=O.trim();if(!(!M||!M.startsWith("data: "))){if(M==="data: [DONE]")break;try{let P=JSON.parse(M.substring(6)),j=P.choices?.[0]?.delta,G=P.usage;if(G&&(w={totalTokenCount:G.total_tokens||G.prompt_tokens+G.completion_tokens,promptTokenCount:G.prompt_tokens||0,candidatesTokenCount:G.completion_tokens||0,cachedContentTokenCount:G.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:G.completion_tokens_details?.reasoning_tokens||0},A=!0),j){let q=j.reasoning||(j.reasoning_details?j.reasoning_details.map(Y=>Y.text).join(""):null);q&&(T.push({text:q,thought:!0}),A=!0),j.content&&(T.push({text:j.content}),A=!0)}}catch{}}}Date.now()-E>=150&&A&&(yield{candidates:T.length>0?[{content:{parts:[...T]}}]:[],usageMetadata:w},T=[],E=Date.now(),A=!1)}},
|
|
406
|
-
`),D=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 Xe=Ju(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,(
|
|
399
|
+
`),await nt.recordFileChange(u),_n.writeFileSync(u,c,"utf8"))}let d=(c.match(/^- \[ [xX ]\]/gm)||[]).length,h=(c.match(/^- \[x\]/gim)||[]).length;return`${a>0?`SUCCESS: ${a} TASK(S) MARKED DONE`:"TODO GET"}: ${h} Completed, ${d-h} left
|
|
400
|
+
${c}`}return`ERROR: Unknown method "${o}". Use create, append, or get.`}catch(c){return`ERROR: Todo tool failure: ${c instanceof Error?c.message:String(c)}`}}});var Ku,Ps,Ql=ae(async()=>{yl();wl();Tl();Sl();bl();kl();Il();await jr();Al();vl();Dl();Ll();Fl();_l();Nl();Bl();ql();Jl();Ku={web_search:Ci,web_scrape:ki,memory:Ii,chat:Mi,view_file:Ai,write_file:vi,update_file:Oi,exec_command:li,read_folder:Li,write_pdf:Fi,write_docx:_i,search_keyword:Bi,generate_image:Ui,saveSummary:Vr,addMemScore:Sr,file_map:Gi,todo:Ls,ask:Pi,Ask:Pi,WebSearch:Ci,WebScrape:ki,ReadFile:Ai,ReadFolder:Li,WriteFile:vi,PatchFile:Oi,WritePDF:Fi,WriteDoc:_i,Run:li,SearchKeyword:Bi,Memory:Ii,Chat:Mi,GenerateImage:Ui,saveSumary:Vr,SaveSummary:Vr,SaveSumary:Vr,add_mem_score:Sr,AddMemScore:Sr,addMemoryScore:Sr,AddMemoryScore:Sr,FileMap:Gi,Todo:Ls,TODO:Ls},Ps=async(e,t,o={})=>{let n=o.mode?o.mode.toLowerCase():"flux",r=e.toLowerCase();if(!(["memory","chat","savesummary","addmemscore","add_mem_score","ask","web_search","web_scrape"].some(f=>r.includes(f))||r==="ask")){if(n==="flow"){if(!(r.includes("write_pdf")||r.includes("write_docx")||r.includes("generate_image")))return`ERROR: Tool [${e}] is a Workspace Tool and NOT available in Flow mode. Tell user to switch (\`/mode flux\`) to use this tool.`}else if(r.includes("write_pdf")||r.includes("write_docx")||r.includes("generate_image"))return`ERROR: Tool [${e}] is not available in Flux mode. Tell user to switch (\`/mode flow\`) for document generation.`}let u=Ku[e];if(!u)return`ERROR: Tool [${e}] not found in registry.`;try{return await u(t,o)}catch(f){let m=f instanceof Error?f.message:String(f);return`ERROR: Execution failed for [${e}]: ${m}`}}});import{WebSocket as Fs}from"ws";var xo,Er,Xu,Ki,br,Xi,Zl,Vi,qi,ec,$s,Zo,_s,qr,tc,zi,oc,Ji=ae(()=>{xo=null,Er=!1,Xu="ws://localhost:56832",Ki=[],br=null,Xi=null,Zl="2.0.0",Vi=e=>{Zl=e,ec()},qi=e=>{Xi=e},ec=()=>{if(xo||Er)return;Er=!0;let e=new Fs(Xu);e.on("open",()=>{for(xo=e,Er=!1,xo.send(JSON.stringify({command:"version",version:Zl,pid:process.pid,ppid:process.ppid}));Ki.length>0;)xo.send(JSON.stringify(Ki.shift()))}),e.on("message",t=>{try{let o=JSON.parse(t.toString());o.command==="contextResponse"&&br?(br(o.data),br=null):o.command==="securityResponse"&&Xi&&Xi(o.result)}catch{}}),e.on("error",()=>{Er=!1,xo=null}),e.on("close",()=>{Er=!1,xo=null})},$s=e=>{xo&&xo.readyState===Fs.OPEN?xo.send(JSON.stringify(e)):(Ki.push(e),Er||ec())},Zo=()=>xo!==null&&xo.readyState===Fs.OPEN,_s=e=>{$s({command:"status",status:e})},qr=()=>new Promise(e=>{if(!xo||xo.readyState!==Fs.OPEN){e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]});return}br=e,xo.send(JSON.stringify({command:"requestContext"})),setTimeout(()=>{br===e&&(e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]}),br=null)},1e3)}),tc=e=>{$s({command:"open",filePath:e})},zi=(e,t,o)=>{$s({command:"showDiff",filePath:e,originalContent:t,modifiedContent:o})},oc=(e,t)=>{$s({command:"closeDiff",filePath:e,result:t})}});import{GoogleGenAI as Vu,ThinkingLevel as Ro,HarmBlockThreshold as Nn,HarmCategory as Bn}from"@google/genai";import Ae from"path";import tt from"fs";var Cr,Zi,Bo,qu,Qi,zu,Ju,ta,oa,na,ra,sc,nc,Qu,ic,Zu,ac,ed,rc,sa,zr,ea,td,ia,lc,cc,uc=ae(async()=>{await rl();Kr();vs();await Ql();Oo();Kt();dn();or();Pt();zo();Ji();Cr=null,Zi={},Bo=!1,qu=["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"],Qi=e=>{if(!e)return!1;let t=e.toLowerCase();return t.startsWith("gemini-")||t.startsWith("gemma-")?!0:qu.some(o=>o.toLowerCase()===t)},zu=e=>{let t=[];return e.forEach(o=>{if(!((o.role==="user"||o.role==="agent"||o.role==="system")&&o.role!=="think"&&!o.isVisualFeedback&&!o.isMeta&&!String(o.id).startsWith("welcome")))return;let r=o.fullText||o.text||"";if(o.role==="system"&&r?.startsWith("[TOOL RESULT]")){let s=t[t.length-1];if(s&&s.role==="system"&&s.text?.startsWith("[TOOL RESULT]")){s.text+=`
|
|
401
|
+
|
|
402
|
+
`+r;return}}t.push({...o,text:r})}),t.length},Ju=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),ta=async(e,t,o=5,n=1e3)=>{let r=t?.signal;for(let s=0;s<o;s++){if(r?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{let i=await fetch(e,t);if(i.ok||i.status!==429&&i.status<500)return i}catch(i){if(i.name==="AbortError"||r?.aborted||s===o-1)throw i}r?await new Promise((i,u)=>{let f=setTimeout(()=>{r.removeEventListener("abort",m),i()},Math.min(24e3,n*Math.pow(2,s))),m=()=>{clearTimeout(f),u(new DOMException("The user aborted a request.","AbortError"))};r.addEventListener("abort",m)}):await new Promise(i=>setTimeout(i,Math.min(24e3,n*Math.pow(2,s))))}if(r?.aborted)throw new DOMException("The user aborted a request.","AbortError");return fetch(e,t)},oa=async function*(e,t,o,n,r,s,i,u){let f=[];n&&f.push({role:"system",content:n});for(let E of o){let A=E.role==="user"?"user":"assistant",$=[];if(Array.isArray(E.parts)){for(let W of E.parts)if(W.text)$.push({type:"text",text:W.text});else if(W.inlineData&&i){let D=W.inlineData.mimeType,O=W.inlineData.data;D.startsWith("image/")&&$.push({type:"image_url",image_url:{url:`data:${D};base64,${O}`}})}}else{let W=E.text||"";W&&$.push({type:"text",text:W})}f.push({role:A,content:$.length===1&&$[0].type==="text"?$[0].text:$})}let m={model:t,messages:f,stream:!0,stream_options:{include_usage:!0}};if(r!=="Fast"){let E={Low:"high",Medium:"high",Standard:"high",High:"max",xHigh:"max"};m.reasoning_effort=E[r]||"high",m.extra_body={thinking:{type:"enabled"}}}else m.extra_body={thinking:{type:"disabled"}};let c=await ta("https://api.deepseek.com/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(m),signal:u});if(!c.ok){let E=await c.json().catch(()=>({}));throw new Error(`DeepSeek Error (${c.status}): ${E.error?.message||c.statusText}`)}let a=c.body.getReader(),d=new TextDecoder,h="",p=[],y=null,T=Date.now(),w=!1;for(;;){let{done:E,value:A}=await a.read();if(E){w&&(p.length>0||y)&&(yield{candidates:p.length>0?[{content:{parts:p}}]:[],usageMetadata:y});break}h+=d.decode(A,{stream:!0});let $=h.split(`
|
|
403
|
+
`);h=$.pop();for(let W of $){let D=W.trim();if(!(!D||!D.startsWith("data: "))){if(D==="data: [DONE]")break;try{let O=JSON.parse(D.substring(6)),M=O.choices?.[0]?.delta,P=O.usage;if(P&&(y={totalTokenCount:P.total_tokens||P.prompt_tokens+P.completion_tokens,promptTokenCount:P.prompt_tokens||0,candidatesTokenCount:P.completion_tokens||0,cachedContentTokenCount:P.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:P.completion_tokens_details?.reasoning_tokens||0},w=!0),M){let j=M.reasoning_content||null;j&&(p.push({text:j,thought:!0}),w=!0),M.content&&(p.push({text:M.content}),w=!0)}}catch{}}}Date.now()-T>=150&&w&&(yield{candidates:p.length>0?[{content:{parts:[...p]}}]:[],usageMetadata:y},p=[],T=Date.now(),w=!1)}},na=async function*(e,t,o,n,r,s,i=!1,u){let f=[];n&&f.push({role:"system",content:n}),o.forEach(q=>{let Y=q.role==="model"?"assistant":"user",N=[];Array.isArray(q.parts)&&q.parts.forEach(ge=>{if(ge.text)N.push({type:"text",text:ge.text});else if(ge.inlineData&&i){let ee=ge.inlineData.mimeType,Me=ge.inlineData.data;ee.startsWith("image/")&&N.push({type:"image_url",image_url:{url:`data:${ee};base64,${Me}`}})}}),f.push({role:Y,content:N.length===1&&N[0].type==="text"?N[0].text:N})});let c={Fast:"Fast",Low:"Fast",Medium:"Standard",Standard:"Standard",High:"High",xHigh:"High"}[r]||"Standard",a=c!=="Fast",d=t.includes("kimi"),h=t.includes("gemma"),p=t.includes("deepseek"),y=t.includes("glm"),T=t.includes("mistral"),w=t.includes("minimax"),A={model:t,messages:f,max_tokens:w||p?16384:32768,stream:!0,stream_options:{include_usage:!0}};if(d)A.chat_template_kwargs={thinking:a};else if(h)A.chat_template_kwargs={enable_thinking:a};else if(p)if(a){let q=c==="High"?"max":"high";A.chat_template_kwargs={thinking:!0,reasoning_effort:q}}else A.chat_template_kwargs={thinking:!1};else y?A.chat_template_kwargs={enable_thinking:a,clear_thinking:!a}:T?A.reasoning_effort=a?"high":"none":w&&t.includes("minimax-m3")&&(A.chat_template_kwargs={thinking_mode:a?"enabled":"disabled"});let $=await ta("https://integrate.api.nvidia.com/v1/chat/completions",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(A),signal:u});if(!$.ok){let q=await $.json(),Y=new Error(`NVIDIA API Error: ${q.error?.message||$.statusText}`);throw Y.status=$.status,Y}let W=$.body.getReader(),D=new TextDecoder,O="",M=[],P=null,j=Date.now(),G=!1;for(;;){let{done:q,value:Y}=await W.read();if(q){G&&(M.length>0||P)&&(yield{candidates:M.length>0?[{content:{parts:M}}]:[],usageMetadata:P});break}O+=D.decode(Y,{stream:!0});let N=O.split(`
|
|
404
|
+
`);O=N.pop();for(let ge of N){let ee=ge.trim();if(!(!ee||ee==="data: [DONE]")&&ee.startsWith("data: "))try{let Me=JSON.parse(ee.substring(6)),ce=Me.usage;ce&&(P={totalTokenCount:ce.total_tokens||ce.prompt_tokens+ce.completion_tokens,promptTokenCount:ce.prompt_tokens||0,candidatesTokenCount:ce.completion_tokens||0,thoughtsTokenCount:(ce.completion_tokens_details?.reasoning_tokens||0)+(ce.completion_tokens_details?.thoughts_tokens||0)},G=!0);let ue=Me.choices?.[0]?.delta?.reasoning||Me.choices?.[0]?.delta?.reasoning_content||"",Xe=Me.choices?.[0]?.delta?.content||"";ue&&(M.push({text:ue,thought:!0}),G=!0),Xe&&(M.push({text:Xe}),G=!0)}catch{}}Date.now()-j>=350&&G&&(yield{candidates:M.length>0?[{content:{parts:[...M]}}]:[],usageMetadata:P},M=[],j=Date.now(),G=!1)}},ra=async function*(e,t,o,n,r,s,i,u){let f=[];n&&f.push({role:"system",content:n});for(let $ of o){let W=$.role==="user"?"user":"assistant",D=[];if(Array.isArray($.parts)){for(let O of $.parts)if(O.text)D.push({type:"text",text:O.text});else if(O.inlineData&&i){let M=O.inlineData.mimeType,P=O.inlineData.data;M.startsWith("image/")?D.push({type:"image_url",image_url:{url:`data:${M};base64,${P}`}}):D.push({type:"file",file:{filename:O.filename||"file",file_data:`data:${M};base64,${P}`}})}}else{let O=$.text||"";O&&D.push({type:"text",text:O})}f.push({role:W,content:D.length===1&&D[0].type==="text"?D[0].text:D})}let m={Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},c={model:t,messages:f,stream:!0},a=m[r];a&&r!=="Fast"&&(c.reasoning_effort=a);let d=await ta("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(c),signal:u});if(!d.ok){let $=await d.json().catch(()=>({}));throw new Error(`OpenRouter Error (${d.status}): ${$.error?.message||d.statusText}`)}let h=d.body.getReader(),p=new TextDecoder,y="",T=[],w=null,E=Date.now(),A=!1;for(;;){let{done:$,value:W}=await h.read();if($){A&&(T.length>0||w)&&(yield{candidates:T.length>0?[{content:{parts:T}}]:[],usageMetadata:w});break}y+=p.decode(W,{stream:!0});let D=y.split(`
|
|
405
|
+
`);y=D.pop();for(let O of D){let M=O.trim();if(!(!M||!M.startsWith("data: "))){if(M==="data: [DONE]")break;try{let P=JSON.parse(M.substring(6)),j=P.choices?.[0]?.delta,G=P.usage;if(G&&(w={totalTokenCount:G.total_tokens||G.prompt_tokens+G.completion_tokens,promptTokenCount:G.prompt_tokens||0,candidatesTokenCount:G.completion_tokens||0,cachedContentTokenCount:G.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:G.completion_tokens_details?.reasoning_tokens||0},A=!0),j){let q=j.reasoning||(j.reasoning_details?j.reasoning_details.map(Y=>Y.text).join(""):null);q&&(T.push({text:q,thought:!0}),A=!0),j.content&&(T.push({text:j.content}),A=!0)}}catch{}}}Date.now()-E>=150&&A&&(yield{candidates:T.length>0?[{content:{parts:[...T]}}]:[],usageMetadata:w},T=[],E=Date.now(),A=!1)}},sc=()=>{Bo=!0},nc={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",todo:"Planning",Todo:"Planning"},Qu=(e,t)=>{try{let o=re(t),n=o.path||o.targetFile||o.TargetFile||o.directory;return n?Ae.basename(n.replace(/["']/g,"").replace(/\\/g,"/")):null}catch{return null}},ic=async(e,t,o,n,r={})=>{process.stdout.isTTY&&(process.stdout.write("\x1B]0;Finalizing...\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=Finalizing...\x07"));let s=4*(1024*2),i=4*(1024*8),{onStatus:u,onMemoryUpdated:f,onBackgroundIncrement:m}=r,{profile:c,thinkingLevel:a,mode:d,janitorModel:h,chatId:p,systemSettings:y,sessionStats:T,aiProvider:w="Google",apiKey:E}=e,A=y?.memory!==!1,W=pe(Ht,[]).map(ue=>`- [${ue.id}]: ${ue.memory}`).join(`
|
|
406
|
+
`),D=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 Xe=Ju(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,(ht,et)=>`[METADATA (PRIORITY: DYNAMIC)] Time: ${et.replace(/:\d{2}/g,"")}`).replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[TOOL RESULTS\]/g,"").replace(/\[tool results\]/g,"").replace(/\r?\n\r?\n/g,`
|
|
407
407
|
`).replace(/\n\n/g,`
|
|
408
|
-
`).replace(/\\n\\n/g,"").trim(),_t=ue.role==="user"?
|
|
408
|
+
`).replace(/\\n\\n/g,"").trim(),_t=ue.role==="user"?s:i,Ve=Xe.substring(0,_t);Xe.length>_t&&(Ve+=`
|
|
409
409
|
... (truncated) ...`);let Ee=ue.role==="user"?Ve.startsWith("[USER]")?"":"[USER]: ":Ve.startsWith("[AGENT]")?"":"[AGENT]: ";return{role:ue.role==="user"?"user":"model",parts:[{text:`${Ee}${Ve}`}]}}),O=n.filter(ue=>ue.role==="user").length===1,M=t.includes("[TITLE-UPDATE]"),P=Math.random()<.8,j=O||M||P,G=o.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").trim(),q=nl(W,A,j),Y=`${G.replace(/\[tool:functions\..*?\]/g,"").replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[\[TOOL RESULTS\]\]/g,"").replace(/\[tool results\]/g,"").substring(0,i)}`;Y.length>i&&(Y+=`
|
|
410
410
|
... (truncated) ...`);let N=t.replace(/\[Prompted on:.*?\]/g,"").trim();Y=Y.replace(/\r?\n\r?\n/g,`
|
|
411
411
|
`).replace(/\n\n/g,`
|
|
412
|
-
`).replace(/\\n\\n/g,"").trim();let
|
|
413
|
-
${N.length>
|
|
412
|
+
`).replace(/\\n\\n/g,"").trim();let ge=`[USER]: ${N.substring(0,s)}
|
|
413
|
+
${N.length>s?`... (truncated) ...
|
|
414
414
|
|
|
415
415
|
`:""}
|
|
416
|
-
[AGENT (current turn)]: ${Y}`;D.push({role:"user",parts:[{text:
|
|
416
|
+
[AGENT (current turn)]: ${Y}`;D.push({role:"user",parts:[{text:ge}]});let ee="",Me=0,ce=A?12:-1;for(;Me<=ce;){process.stdout.isTTY&&(process.stdout.write(`\x1B]0;Retrying Finalizing... (${Me+1})...\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=Retrying Finalizing... (${Me+1})...\x07`));try{if(!await Ei("background",e))return;let ue="",Xe=null;try{let Ee=new Promise((Vt,ut)=>setTimeout(()=>ut(new Error("JANITOR_TIMEOUT")),6e4)),ht=(async()=>{if(w==="OpenRouter"){let ze=ra(E,"google/gemma-4-26b-a4b-it:free",D,q,"Fast",d)[Symbol.asyncIterator](),ot=await ze.next();return{iterator:ze,firstResult:ot}}else if(w==="DeepSeek"){let ut=oa(E,"deepseek-chat",D,q,"Fast",d,!1)[Symbol.asyncIterator](),ze=await ut.next();return{iterator:ut,firstResult:ze}}else if(w==="NVIDIA"){let ut=na(E,"moonshotai/kimi-k2.6",D,q,"Fast",d,!1)[Symbol.asyncIterator](),ze=await ut.next();return{iterator:ut,firstResult:ze}}else{let ut=(await Cr.models.generateContentStream({model:h||(Me===ce?"gemini-3.1-flash-lite":"gemma-4-26b-a4b-it"),contents:D,config:{systemInstruction:q,maxOutputTokens:512,temperature:.3,safetySettings:[{category:Bn.HARM_CATEGORY_HARASSMENT,threshold:Nn.BLOCK_NONE},{category:Bn.HARM_CATEGORY_HATE_SPEECH,threshold:Nn.BLOCK_NONE},{category:Bn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Nn.BLOCK_NONE},{category:Bn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Nn.BLOCK_NONE}],thinkingConfig:{includeThoughts:!1,thinkingLevel:Ro.MINIMAL}}}))[Symbol.asyncIterator](),ze=await ut.next();return{iterator:ut,firstResult:ze}}})(),{iterator:et,firstResult:Ye}=await Promise.race([ht,Ee]),{value:qe,done:mo}=Ye;if(!mo&&qe){let Vt=qe.candidates?.[0]?.content?.parts,ut=Vt?.[1]?.text||Vt?.[0]?.text||(typeof qe.text=="function"?qe.text():"");ut&&(ue+=ut),Xe=qe.usageMetadata;for await(let ze of{[Symbol.asyncIterator]:()=>et}){let ot=ze.candidates?.[0]?.content?.parts,Ao=ot?.[1]?.text||ot?.[0]?.text||(typeof ze.text=="function"?ze.text():"");Ao&&(ue+=Ao),Xe=ze.usageMetadata}}}catch(Ee){throw Ee}if(ue)ee=ue,Xe&&await Eo("tokens",Xe.totalTokenCount||0);else throw new Error("No synthesis generated by Janitor.");m&&(m(),await Qo("background"));let _t=sa(ee),Ve=!1;for(let Ee of _t){let ht=Ee.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(ht)&&(Ve=!0);let et={chatId:p,sessionId:p,history:n},Ye=await Ps(ht,Ee.args,et);ht.toLowerCase()==="memory"&&(Ee.args.includes("action='user'")||Ee.args.includes('action="user"'))&&!Ye.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(mo=>setTimeout(mo,3e3)))}if(!Ve)try{let Ee=pe(Ht,[]);if(Ee.length>0){let ht=[];for(let et of Ee)et.score===void 0&&(et.score=.5),et.score*=.9995,et.score<.05&&(et.score=0),et.score=Math.round(et.score*1e5)/1e5,et.score>0&&ht.push(et);De(Ht,ht)}}catch{}break}catch(ue){Me++;let Xe=new Date().toLocaleString();process.stdout.isTTY&&process.stdout.write("\x1B]0;Finalizing Error\x07"),await new Promise(Ee=>setTimeout(Ee,1e3));let _t=Ae.join(To,"janitor");if(tt.existsSync(_t)||tt.mkdirSync(_t,{recursive:!0}),tt.appendFileSync(Ae.join(_t,"error.log"),`ERROR [Attempt ${Me}/${ce+1}] [${Xe}]: ${String(ue)}
|
|
417
417
|
|
|
418
|
-
`),Me>
|
|
418
|
+
`),Me>ce)break;let Ve=Math.min(1e3*Math.pow(2,Me-1),8e3);await new Promise(Ee=>setTimeout(Ee,Ve))}}if(Me){let ue=Ae.join(To,"janitor");tt.appendFileSync(Ae.join(ue,"error.log"),`-----------------------------------------------------------------------------
|
|
419
419
|
|
|
420
420
|
|
|
421
|
-
`),Me>=
|
|
421
|
+
`),Me>=ce&&(process.stdout.isTTY&&process.stdout.write(`\x1B]0;${A?"Finalizing Error":"Finalizing Skipped"}\x07`),await new Promise(Xe=>setTimeout(Xe,3e3)))}process.stdout.isTTY&&(process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07"))},Zu=e=>{let t=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,o;for(;(o=t.exec(e))!==null;){let n=o.index+o[0].length-1,r=0,s=null,i=!1,u=!1;for(let f=n;f<e.length;f++){let m=e[f];if(!s&&(m==='"'||m==="'"||m==="`")?(s=m,i=!1):s&&m===s&&!i&&(s=null),!s&&(m==="("?r++:m===")"&&r--,r===0)){let c=f+1;for(;c<e.length&&/\s/.test(e[c]);)c++;if(c<e.length&&e[c]==="]"){u=!0,t.lastIndex=c+1;break}}m==="\\"?i=!i:i=!1}if(!u)return{inside:!0,toolName:o[1],startIndex:o.index,args:e.substring(o.index+o[0].length)}}return{inside:!1}},ac=(e,t=!0)=>{let o=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,n="",r=0,s;for(;(s=o.exec(e))!==null;){let i=e.substring(r,s.index);n+=t?i.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\]|$)/gi,""):i;let u=s.index+s[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 h=0;for(let p=a-1;p>=0&&e[p]==="\\";p--)h++;h%2===0&&(m=null)}}else if(d==='"'||d==="'"||d==="`")m=d;else if(d==="(")f++;else if(d===")"&&(f--,f===0)){let h=a+1;for(;h<e.length&&/\s/.test(e[h]);)h++;if(h<e.length&&e[h]==="]"){c=h;break}}}if(c!==-1)n+="[tool:functions."+s[1]+"()]",r=c+1,o.lastIndex=r;else{n+="[tool:functions."+s[1]+"(",r=e.length;break}}return r<e.length&&(n+=t?e.substring(r).replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\]|$)/gi,""):e.substring(r)),n},ed=(e,t,o)=>{let n=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,r="",s=0,i;for(;(i=n.exec(e))!==null;){let u=e.substring(s,i.index);r+=u.replace(t,o);let f=i.index+i[0].length-1,m=0,c=null,a=-1;for(let d=f;d<e.length;d++){let h=e[d];if(c){if(h===c){let p=0;for(let y=d-1;y>=0&&e[y]==="\\";y--)p++;p%2===0&&(c=null)}}else if(h==='"'||h==="'"||h==="`")c=h;else if(h==="(")m++;else if(h===")"&&(m--,m===0)){let p=d+1;for(;p<e.length&&/\s/.test(e[p]);)p++;if(p<e.length&&e[p]==="]"){a=p;break}}}if(a!==-1)r+=e.substring(i.index,a+1),s=a+1,n.lastIndex=s;else{r+=e.substring(i.index),s=e.length;break}}return s<e.length&&(r+=e.substring(s).replace(t,o)),r},rc=e=>ac(e,!0),sa=e=>{if(!e)return[];let t=e.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/gi,""),o=[],n=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,r;for(;(r=n.exec(t))!==null;){let s=r[1],i=r.index+r[0].length-1,u=0,f=null,m=-1,c=-1;for(let a=i;a<t.length;a++){let d=t[a];if(f){if(d===f){let h=0;for(let p=a-1;p>=0&&t[p]==="\\";p--)h++;h%2===0&&(f=null)}}else if(d==='"'||d==="'"||d==="`")f=d;else if(d==="(")u++;else if(d===")"&&(u--,u===0)){c=a;let h=a+1;for(;h<t.length&&/\s/.test(t[h]);)h++;if(h<t.length&&t[h]==="]"){m=h;break}}}if(m!==-1){let a=t.substring(i+1,c),d=t.substring(r.index,m+1);o.push({fullMatch:d,toolName:s.trim(),args:a.trim()}),n.lastIndex=m+1}}return o},zr=(e,t={})=>e?(Zi=t,Cr=new Vu({apiKey:e}),Cr):null,ea=async(e,t,o,n,r="Fast")=>{let{aiProvider:s="Google",apiKey:i,mode:u}=e,f="",m=null,c=typeof o=="string"?[{role:"user",parts:[{text:o}]}]:o,a;s==="OpenRouter"?a=ra(i,t,c,n,r,u,!1):s==="DeepSeek"?a=oa(i,t,c,n,r,u,!1):s==="NVIDIA"?a=na(i,t,c,n,r,u,!1):a=await Cr.models.generateContentStream({model:t,contents:c,config:{systemInstruction:n,maxOutputTokens:2048,temperature:.3,thinkingConfig:{includeThoughts:!1,thinkingLevel:Ro.MINIMAL}}});for await(let d of a){if(d.candidates?.[0]?.content?.parts)for(let h of d.candidates[0].content.parts)h.text&&!h.thought&&(f+=h.text);d.usageMetadata&&(m=d.usageMetadata)}return{text:f,usageMetadata:m}},td=async(e,t)=>{try{let{aiProvider:o="Google"}=t,n=pe(So,{});if(Object.values(n).flat().length<=2)return;let s=Object.keys(n).filter(d=>d!==e&&Array.isArray(n[d])&&n[d].length>2);if(s.length===0)return;let i=`You are a silent background process for the FluxFlow CLI Agent.
|
|
422
422
|
Your task is to summarize or merge temporary context memories from one or more past conversation sessions.
|
|
423
423
|
For each Chat ID provided, you must output a tool call to save the consolidated summary.
|
|
424
424
|
|
|
@@ -433,7 +433,7 @@ Guidelines:
|
|
|
433
433
|
|
|
434
434
|
Chats to process:
|
|
435
435
|
|
|
436
|
-
`,u=
|
|
436
|
+
`,u=pe(Vo,{});for(let d of s){let p=n[d].map(T=>`- ${T}`).join(`
|
|
437
437
|
`),y=u[d];i+=`[Chat ID: ${d}]
|
|
438
438
|
`,y?(i+=`- Existing Summary: "${y}"
|
|
439
439
|
`,i+=`-- New Memories to integrate:
|
|
@@ -442,8 +442,8 @@ ${p}
|
|
|
442
442
|
`):i+=`-- Individual Memories:
|
|
443
443
|
${p}
|
|
444
444
|
|
|
445
|
-
`}let f=0,m=5,c=!1,a="gemma-4-26b-a4b-it";for(o==="OpenRouter"&&(a="google/gemma-4-26b-a4b-it:free"),o==="DeepSeek"&&(a="deepseek-v4-flash");f<=m&&!c;){f++;try{let d=await ea(t,a,i,null,"Fast"),h=d.text||"",p=
|
|
446
|
-
`)}},ia=async(e,t,o=!1)=>{let{chatId:n,aiProvider:
|
|
445
|
+
`}let f=0,m=5,c=!1,a="gemma-4-26b-a4b-it";for(o==="OpenRouter"&&(a="google/gemma-4-26b-a4b-it:free"),o==="DeepSeek"&&(a="deepseek-v4-flash");f<=m&&!c;){f++;try{let d=await ea(t,a,i,null,"Fast"),h=d.text||"",p=sa(h);if(p.length===0)throw new Error("No tool calls detected in synthesis response");for(let y of p){let T=y.toolName;["saveSummary","saveSumary","SaveSummary","SaveSumary"].includes(T)&&await Ps(T,y.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(o){let n=Ae.join(To,"janitor");tt.existsSync(n)||tt.mkdirSync(n,{recursive:!0}),tt.appendFileSync(Ae.join(n,"error.log"),`[${new Date().toLocaleString()}] Past memory batch consolidation error: ${o.message}
|
|
446
|
+
`)}},ia=async(e,t,o=!1)=>{let{chatId:n,aiProvider:r="Google"}=e,s=Ae.join(bt,"chat-summaries.json"),i=h=>h.filter(p=>(p.role==="user"||p.role==="agent"||p.role==="system")&&p.role!=="think"&&!p.isVisualFeedback&&!p.isMeta&&!String(p.id).startsWith("welcome")).map(p=>`[${p.text?.startsWith("[TOOL RESULT]")?"TOOL":p.role==="agent"?"AGENT":"USER"}]: ${p.text}`).join(`
|
|
447
447
|
|
|
448
448
|
`),u=async(h,p)=>{let y="You are an expert context summarizer. 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, chat messages, file changes. Under no circumstances exceed MAX 2000 words.",T=p?`Here is the previous summary:
|
|
449
449
|
${p}
|
|
@@ -454,160 +454,160 @@ ${h}
|
|
|
454
454
|
Provide a new consolidated summary of the entire session.`:`Here is the conversation history:
|
|
455
455
|
${h}
|
|
456
456
|
|
|
457
|
-
Provide a consolidated summary of the entire session.`,w="gemma-4-26b-a4b-it";
|
|
458
|
-
`),
|
|
459
|
-
`),ue=(a?.tokens||0)>=24e3,Xe=tl(ee,
|
|
460
|
-
`;let Et="",Yn=Ve,Tt=Je.filter(Se=>!Yn.includes(Se.name)),Tn=Je.filter(Se=>Yn.includes(Se.name)).map(Se=>Se.name).sort();Tt.sort((Se,zt)=>Se.isDirectory()&&!zt.isDirectory()?-1:!Se.isDirectory()&&zt.isDirectory()?1:Se.name.localeCompare(zt.name));let
|
|
457
|
+
Provide a consolidated summary of the entire session.`,w="gemma-4-26b-a4b-it";r==="OpenRouter"&&(w="google/gemma-4-26b-a4b-it:free"),r==="DeepSeek"&&(w="deepseek-v4-flash"),r==="NVIDIA"&&(w="stepfun-ai/step-3.7-flash");let E=0,A=!1,$=null;for(;E<=3&&!A;){E++;try{$=await ea(e,w,T,y,"Fast"),A=!0}catch{if(E>3){if(r==="Google")try{return(await ea(e,"gemini-3.1-flash-lite",T,y,"Fast")).text||""}catch{return""}return""}}}return $&&$.text||""},f=i(t),m=pe(s,{}),c=m[n]||{summary:"",historyLength:0};typeof c=="string"&&(c={summary:c,historyLength:0});let a=c.summary||"",d=await u(f,a);if(d){c.summary=d;let h=zu(t);return o?c.historyLength=(c.historyLength||0)+h:c.historyLength=h,m[n]=c,De(s,m),d}return null},lc=e=>{try{let t=Ae.join(bt,"chat-summaries.json");if(tt.existsSync(t)){let o=pe(t,{});o[e]&&(delete o[e],De(t,o))}}catch{}},cc=async function*(e,t,o,n,r){let{profile:s,thinkingLevel:i,mode:u,janitorModel:f,chatId:m,systemSettings:c,sessionStats:a,aiProvider:d="Google",apiTier:h}=o,p=Qi(e);if(!Cr&&d==="Google")throw new Error("AI not initialized");let y=c?.memory!==!1,T=t[t.length-1].text,w=Ae.join(bt,"chat-summaries.json"),E=!1,A=t.filter(M=>M.role==="user").length===1,$=T.includes("[TITLE-UPDATE]"),W=A||$,D=T.replace(/\[TITLE-UPDATE\]/g,"").trim();D=D.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),await nt.startTransaction(m,D),Bo=!1;let O=null;try{let M=new AbortController;O=setInterval(()=>{Bo&&(M.abort(),O&&(clearInterval(O),O=null))},400);let P=[...t.slice(0,-1)];{let $e=pe(w,{})[m]||{summary:"",historyLength:0};if($e.summary&&$e.historyLength>0){let Ke=0,Oe=[];for(let Je=0;Je<P.length;Je++){let Te=P[Je];(Te.role==="user"||Te.role==="agent"||Te.role==="system")&&!String(Te.id).startsWith("welcome")&&!Te.isMeta&&Ke++,Ke>$e.historyLength&&Oe.push(Te)}P=Oe}}let j=252e3,G=254e3;(d==="DeepSeek"||d==="Google"&&h==="Paid")&&(j=396e3,G=4e5),(a?.tokens||0)>j&&(yield{type:"status_history",content:"Context Limit Reached. Condensing session history..."},await ia(o,P,!0)&&(P=[],E=!0)),A&&y&&(yield{type:"status",content:"Condensing past chat memories..."},await td(m,o));let q=pe(So,{}),Y=pe(Vo,{}),N=Object.entries(q).filter(([se])=>se!==m).flatMap(([se,$e])=>$e),ee=[...Object.entries(Y).filter(([se])=>se!==m).slice(-20).map(([se,$e])=>`[Chat Summary]: ${$e}`),...N].map(se=>`- ${se}`).join(`
|
|
458
|
+
`),ce=pe(Ht,[]).map(se=>`- ${se.memory}`).join(`
|
|
459
|
+
`),ue=(a?.tokens||0)>=24e3,Xe=tl(ee,ce,y,ue),_t=new Date().toLocaleString([],{year:"numeric",month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!0}),Ve=[".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"],Ee=se=>{try{return tt.readdirSync(se,{withFileTypes:!0})}catch{return[]}},ht=(se,$e={value:0},Ke=1)=>{if($e.value>6200||Ke>7)return $e.value;let Oe=Ee(se);for(let Je of Oe){if($e.value>6200)break;Ve.includes(Je.name)||Je.isDirectory()&&($e.value++,ht(Ae.join(se,Je.name),$e,Ke+1))}return $e.value},et=(se,$e,Ke="",Oe=1)=>{let Je=Ee(se),Te=Ae.sep;if(Je.length>100)return`${Ke}\u2514\u2500\u2500 ${Ae.basename(se)}${Te} ...100+ files...
|
|
460
|
+
`;let Et="",Yn=Ve,Tt=Je.filter(Se=>!Yn.includes(Se.name)),Tn=Je.filter(Se=>Yn.includes(Se.name)).map(Se=>Se.name).sort();Tt.sort((Se,zt)=>Se.isDirectory()&&!zt.isDirectory()?-1:!Se.isDirectory()&&zt.isDirectory()?1:Se.name.localeCompare(zt.name));let ct=[...Tt.map(Se=>({name:Se.name,isDir:Se.isDirectory()})),...Tn.map(Se=>({name:Se,isDir:!0,isCollapsed:!0}))];return ct.forEach((Se,zt)=>{let vt=zt===ct.length-1,Yo=Ae.join(se,Se.name),Bt=vt?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",jn=Ke+(vt?" ":"\u2502 ");if(Se.isCollapsed){Et+=`${Ke}${Bt}${Se.name}${Te}...
|
|
461
461
|
`;return}Se.isDir?Oe>$e?Et+=`${Ke}${Bt}${Se.name}${Te} ...depth exceeded...
|
|
462
462
|
`:Ee(Yo).length>80?Et+=`${Ke}${Bt}${Se.name}${Te} ...80+ files...
|
|
463
463
|
`:(Et+=`${Ke}${Bt}${Se.name}${Te}
|
|
464
464
|
`,Et+=et(Yo,$e,jn,Oe+1)):Et+=`${Ke}${Bt}${Se.name}
|
|
465
|
-
`}),Et};yield{type:"status",content:"Gathering Context..."},await new Promise(
|
|
465
|
+
`}),Et};yield{type:"status",content:"Gathering Context..."},await new Promise(se=>setTimeout(se,500));let Ye=ht(process.cwd()),qe=12;Ye>4096?qe=1:Ye>3072?qe=2:Ye>2048?qe=3:Ye>1024?qe=4:Ye>512?qe=6:Ye>256?qe=7:Ye>128?qe=8:Ye>64?qe=9:Ye>32&&(qe=10);let mo=pe(is,{}),Vt=mo[m],ut=Vt?Vt!==process.cwd():!1;mo[m]=process.cwd(),De(is,mo);let ze=pe(w,{}),ot=ze[m]||{summary:"",historyLength:0};typeof ot=="string"&&(ot={summary:ot,historyLength:0});let Ao=t.filter(se=>(se.role==="user"||se.role==="agent"||se.role==="system")&&!String(se.id).startsWith("welcome")&&!se.isMeta).length;ot.historyLength&&Ao<ot.historyLength&&(ot.summary="",ot.historyLength=0,ze[m]=ot,De(w,ze));let nn=typeof ot=="object"?ot.summary||"":ot||"",qt=P.length>0;qt&&nn&&P[0]&&(P[0].role==="user"||P[0].role==="system")&&(P[0].text.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")||(P[0].text=`[SYSTEM METADATA (PRIORITY: HIGH)]
|
|
466
466
|
**CONTEXT SUMMARY OF PREVIOUS TURNS (PRIORITY: HIGH)**
|
|
467
|
-
${
|
|
467
|
+
${nn}
|
|
468
468
|
|
|
469
|
-
[USER] ${P[0].text}`,yield{type:"summary_injected",content:{id:P[0].id,text:P[0].text}}));let J=
|
|
469
|
+
[USER] ${P[0].text}`,yield{type:"summary_injected",content:{id:P[0].id,text:P[0].text}}));let J=nn&&!qt?`
|
|
470
470
|
[SYSTEM METADATA (PRIORITY: HIGH)]
|
|
471
471
|
**CONTEXT SUMMARY OF PREVIOUS TURNS (PRIORITY: HIGH)**
|
|
472
|
-
${
|
|
472
|
+
${nn}
|
|
473
473
|
`:"",Mt=process.cwd()+`
|
|
474
|
-
`+et(process.cwd(),qe),
|
|
475
|
-
`,
|
|
476
|
-
Cursor Line: ${
|
|
477
|
-
`,
|
|
478
|
-
`),
|
|
474
|
+
`+et(process.cwd(),qe),ro=await qr(),so="";if(Zo())if(so=`[IDE CONTEXT]
|
|
475
|
+
`,ro.file_focused!=="none"){let se=Ae.relative(process.cwd(),ro.file_focused),$e=(ro.opened_editors||[]).map(Oe=>{let Je=Ae.relative(process.cwd(),Oe);return Je.startsWith("..")?`[External] ${Ae.basename(Oe)}`:Je});if(so+=`Focused File: ${se}
|
|
476
|
+
Cursor Line: ${ro.cursor_line}
|
|
477
|
+
`,ro.selected&&(so+=`Current Selection: "${ro.selected}"
|
|
478
|
+
`),ro.manual_edits){let Oe=ro.manual_edits,Je=4*512,Te=50,Et=Oe.split(`
|
|
479
479
|
`);Et.length>Te&&(Oe=Et.slice(0,Te).join(`
|
|
480
480
|
`)+`
|
|
481
481
|
... (${Et.length-Te} more lines truncated)`),Oe.length>Je&&(Oe=Oe.substring(0,Je)+`
|
|
482
|
-
... (Character limit reached, truncated)`),
|
|
482
|
+
... (Character limit reached, truncated)`),so+=`Recent Manual Edits:
|
|
483
483
|
${Oe}
|
|
484
|
-
`}$e.length>0&&(
|
|
484
|
+
`}$e.length>0&&(so+=`All Opened Editors: ${$e.join(", ")}`),ro.diagnostics&&(so+=`
|
|
485
485
|
**ACTIVE FILE ERRORS**:
|
|
486
|
-
${
|
|
487
|
-
`),(D.toLowerCase().includes("lint")||D.toLowerCase().includes("warning"))&&
|
|
486
|
+
${ro.diagnostics}
|
|
487
|
+
`),(D.toLowerCase().includes("lint")||D.toLowerCase().includes("warning"))&&ro.warnings&&(so+=`
|
|
488
488
|
**LINT WARNINGS**:
|
|
489
|
-
${
|
|
490
|
-
`)}else
|
|
491
|
-
CWD: ${process.cwd()}${
|
|
489
|
+
${ro.warnings}
|
|
490
|
+
`)}else so+="No file currently focused.";let Qr=D.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),Wo=`[SYSTEM METADATA (PRIORITY: DYNAMIC), Chat Context >> Metadata] Time: ${_t}
|
|
491
|
+
CWD: ${process.cwd()}${ut?` (WARNING: CWD Mismatch! Previous Path: ${Vt})`:""}
|
|
492
492
|
**DIRECTORY STRUCTURE**
|
|
493
|
-
${Mt}${Xe}${
|
|
493
|
+
${Mt}${Xe}${so}
|
|
494
494
|
${J}${i!="Fast"&&d==="Google"?`${e.toLowerCase().startsWith("gemma")?`[SYSTEM] **STRICTLY FOLLOW THINKING POLICY AS CRITICAL PRIORITY. DO NOT START A RESPONSE WITHOUT <think> ... </think>**
|
|
495
|
-
[/SYSTEM]`:""}`:""} [USER] ${
|
|
495
|
+
[/SYSTEM]`:""}`:""} [USER] ${Qr}[/USER]`.trim();P.push({role:"user",text:Wo}),J&&t[t.length-1]?.id&&(yield{type:"summary_injected",content:{id:t[t.length-1].id,text:Wo}});let At=null,Nt=u==="Flux"?70:7,lt=16;yield{type:"status",content:"Connecting..."},Bo=!1;let wn=[],ar=!1;P.forEach(se=>{se.text&&se.role==="agent"&&(se.text=se.text.replace(/(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])/gi,"").trim())});for(let se=0;se<=Nt;se++){if(ar=!1,c?.compression===0&&(a?.tokens||0)>G&&(P=cl(P,6)),se>0&&(yield{type:"status",content:"Working...."}),Bo){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
|
|
496
496
|
|
|
497
497
|
\x1B[33m\u2139 Request Cancelled\x1B[0m`};break}if(n){let me=await n();me&&(P.length>0&&P[P.length-1].role==="user"?P[P.length-1].text+=`
|
|
498
498
|
|
|
499
499
|
[STEERING HINT]: ${me}`:P.push({role:"user",text:`${i!="Fast"&&d==="Google"?`${e.toLowerCase().startsWith("gemma")?`[SYSTEM] **STRICTLY FOLLOW THINKING POLICY AS CRITICAL PRIORITY. DO NOT START A RESPONSE WITHOUT <think> ... </think>**
|
|
500
|
-
[/SYSTEM]`:""}`:""} [STEERING HINT]: ${me}`}),yield{type:"status",content:"Steering Hint Injected."})}let $e,Ke=!1,Oe=1,Je=1,Te="",Et=null,Yn=null,Tt=null,Tn=0,
|
|
501
|
-
|
|
502
|
-
`+(Ce.parts?.[0]?.text||""),Ce.parts?.length>1&&ie.parts.push(...Ce.parts.slice(1))):je.push(Ce)}}if(be.length=0,be.push(...je),!await Ei("agent",o))throw new Error("Error: Quota Exausted for Agent");Rt=e,d==="DeepSeek"&&i==="Fast"&&Rt.includes("flash")&&(Rt="deepseek-chat"),Oe===
|
|
503
|
-
[SYSTEM] Tool result received. Analyze output and proceed with your turn${i!="Fast"&&d==="Google"?". **STRICTLY MAINTAIN THINKING POLICY. DO NOT START A RESPONSE WITHOUT <think> ... </think>**":""}[/SYSTEM]`;
|
|
504
|
-
[SYSTEM] WARNING, Turn Limit Impending: Step ${Ce}/${Nt}. Wrap up quickly/prompt user to continue & use [[END]] quickly.[/SYSTEM]`)}let sn=new Promise((oe,Ce)=>{M.signal.aborted&&Ce(new DOMException("The user aborted a request.","AbortError")),M.signal.addEventListener("abort",()=>{Ce(new DOMException("The user aborted a request.","AbortError"))})}),Ut=be;if(d==="OpenRouter")$e=
|
|
505
|
-
|
|
506
|
-
\x1B[33m\u2139 Request Cancelled\x1B[0m`};break}let ie="",We=oe.candidates?.[0]?.content?.parts;if(We&&We.length>0)for(let
|
|
507
|
-
`).length;ne=Yt,Ne=Math.min(V,Yt)}}catch{}let de=x.toLowerCase(),
|
|
508
|
-
${
|
|
509
|
-
${V}`}}
|
|
510
|
-
${Ie.map(
|
|
511
|
-
`)}`,st=`\u{1F4BE} Edited: ${Ae.basename(
|
|
500
|
+
[/SYSTEM]`:""}`:""} [STEERING HINT]: ${me}`}),yield{type:"status",content:"Steering Hint Injected."})}let $e,Ke=!1,Oe=1,Je=1,Te="",Et=null,Yn=null,Tt=null,Tn=0,ct=[],Se=0,zt=!1,vt=!1,Yo=!1,Bt=!1,jn=!0,pt="",dt="",Jt=!1,Rt=e,jo="";for(;Oe<=lt&&Je<=lt&&!Ke&&!Bo;){let me=!1;try{Te="",jn&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},yield{type:"spinner",content:!0},jn=!1,Je===1&&(pt=""));let be=P.filter(oe=>(oe.role==="user"||oe.role==="agent"||oe.role==="system")&&!String(oe.id).startsWith("welcome")&&!oe.isMeta&&!oe.isTerminalRecord&&!(oe.text&&oe.text.startsWith("[TERMINAL_RECORD]"))).map((oe,Ce,ie)=>{let We=oe.text||"";oe.role==="agent"&&(We=We.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim());let xe=[{text:We}];return oe.binaryPart&&Qi(Rt)&&ie.slice(Ce+1).filter(He=>He.role==="user"&&!He.text?.startsWith("[TOOL RESULT]")).length<=2&&xe.push(oe.binaryPart),{role:oe.role==="user"||oe.role==="system"?"user":"model",parts:xe}});for(let oe=0;oe<be.length;oe++){let Ce=be[oe],ie=Ce.parts?.[0]?.text||"";if(Ce.role==="model"&&/\[tool:/i.test(ie)){let We=-1;for(let xe=oe+1;xe<be.length;xe++){let St=be[xe],He=St.parts?.[0]?.text||"";if(St.role==="user"&&He.startsWith("[TOOL RESULT]")){We=xe;break}}if(We!==-1&&We!==oe+1){let[xe]=be.splice(We,1);be.splice(oe+1,0,xe)}}}for(let oe=be.length-2;oe>=0;oe--){let Ce=be[oe],ie=be[oe+1];Ce.role==="user"&&ie.role==="user"&&(ie.parts?.[0]?.text||"").trim().startsWith("[SYSTEM")&&be.splice(oe,1)}let je=[];for(let oe=0;oe<be.length;oe++){let Ce=be[oe];if(je.length===0)je.push(Ce);else{let ie=je[je.length-1];ie.role===Ce.role?(ie.parts[0].text+=`
|
|
501
|
+
|
|
502
|
+
`+(Ce.parts?.[0]?.text||""),Ce.parts?.length>1&&ie.parts.push(...Ce.parts.slice(1))):je.push(Ce)}}if(be.length=0,be.push(...je),!await Ei("agent",o))throw new Error("Error: Quota Exausted for Agent");Rt=e,d==="DeepSeek"&&i==="Fast"&&Rt.includes("flash")&&(Rt="deepseek-chat"),Oe===lt-1?(Rt=d==="DeepSeek"?"deepseek-v4-flash":"gemini-3-flash-preview",yield{type:"model_update",content:"Trying with fallback model"}):Oe===lt?(Rt=d==="DeepSeek"?"deepseek-v4-pro":"gemini-3.5-flash",yield{type:"model_update",content:"Trying with fallback model"}):Oe>12&&Oe<lt-2&&o.apiKey!=="custom"?(Rt="gemma-4-31b-it",yield{type:"model_update",content:"Trying with fallback Gemma Model"}):Oe>0&&(yield{type:"model_update",content:null}),jo=ol(s,(Rt||"gemma").toLowerCase().startsWith("gemma")?i:"GEM",u,c,y,A,d,p);let rn=e&&e.toLowerCase().startsWith("gemma")&&d==="Google",gt=be[be.length-1];if(rn){let oe=`
|
|
503
|
+
[SYSTEM] Tool result received. Analyze output and proceed with your turn${i!="Fast"&&d==="Google"?". **STRICTLY MAINTAIN THINKING POLICY. DO NOT START A RESPONSE WITHOUT <think> ... </think>**":""}[/SYSTEM]`;gt&>.role==="user"&>.parts?.[0]?.text?.startsWith("[TOOL RESULT]")&&(gt.parts[0].text+=oe)}if(rn){let oe=Math.floor(Nt*(u==="Flux"?.98:.7)),Ce=se+1;Ce>=oe&>&>.parts?.[0]&&(gt.parts[0].text+=`
|
|
504
|
+
[SYSTEM] WARNING, Turn Limit Impending: Step ${Ce}/${Nt}. Wrap up quickly/prompt user to continue & use [[END]] quickly.[/SYSTEM]`)}let sn=new Promise((oe,Ce)=>{M.signal.aborted&&Ce(new DOMException("The user aborted a request.","AbortError")),M.signal.addEventListener("abort",()=>{Ce(new DOMException("The user aborted a request.","AbortError"))})}),Ut=be;if(d==="OpenRouter")$e=ra(o.apiKey,Rt,Ut,jo,i,u,p,M.signal);else if(d==="DeepSeek")$e=oa(o.apiKey,Rt,Ut,jo,i,u,p,M.signal);else if(d==="NVIDIA")$e=na(o.apiKey,Rt,Ut,jo,i,u,p,M.signal);else{let oe=Cr.models.generateContentStream({model:Rt||"gemma-4-31b-it",contents:Ut,config:{systemInstruction:jo,mediaResolution:"MEDIA_RESOLUTION_MEDIUM",safetySettings:[{category:Bn.HARM_CATEGORY_HARASSMENT,threshold:Nn.BLOCK_NONE},{category:Bn.HARM_CATEGORY_HATE_SPEECH,threshold:Nn.BLOCK_NONE},{category:Bn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Nn.BLOCK_NONE},{category:Bn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Nn.BLOCK_NONE}],thinkingConfig:(()=>{let Ce=(Rt||"").toLowerCase(),ie=Ce.includes("gemma-4")||Ce.startsWith("gemma"),We=Ce.includes("gemini-3");if(ie||We)return ie?{includeThoughts:!1,thinkingLevel:Ro.MINIMAL}:{includeThoughts:!0,thinkingLevel:{Fast:Ce.includes("pro")?Ro.LOW:Ro.MINIMAL,Low:Ro.LOW,Medium:Ro.MEDIUM,Standard:Ro.MEDIUM,High:Ro.HIGH,xHigh:Ro.HIGH}[i]||Ro.MEDIUM};{let xe={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[i]||2048;return xe===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:xe}}})()}},{signal:M.signal});$e=await Promise.race([oe,sn])}Te="",Et=null,Tt=null,ct=[],Se=0,yield{type:"model_update",content:null},dt="",Jt=pt.length>0;let Dt="",Wt=Date.now(),Ot=async function*(){if(d==="Google"&&Dt){let oe=Sn(Dt);for(let Ce of oe)yield Ce;Dt="",Wt=Date.now()}},io=!0,Qt="",Co=!1,an=null,Sn=oe=>{let Ce=[],ie=oe;for(;ie.length>0;)if(Co){let We=an==="tool"?"]":"[[END]]",xe=Qt+ie;if(an==="tool"){let He="[tool:functions.";if(!xe.startsWith("[tool")||xe.length>=He.length&&!xe.startsWith(He)){Ce.push({type:"text",content:xe}),Qt="",Co=!1,an=null,ie="";break}}let St=xe.indexOf(We);if(St!==-1){let He=xe.substring(0,St+We.length);Ce.push({type:"text",content:He}),Qt="",Co=!1,an=null,ie=xe.substring(St+We.length)}else{xe.length>512?(Ce.push({type:"text",content:xe}),Qt="",Co=!1):Qt=xe,ie="";break}}else{let We=ie.indexOf("[tool"),xe=ie.indexOf("[[END]]"),St=[{type:"tool",idx:We,start:"[tool",end:"]"},{type:"end",idx:xe,start:"[[END]]",end:"[[END]]"}].filter(He=>He.idx!==-1).sort((He,Ho)=>He.idx-Ho.idx);if(St.length>0){let He=St[0];He.idx>0&&Ce.push({type:"text",content:ie.substring(0,He.idx)}),Co=!0,an=He.type,Qt="",ie=ie.substring(He.idx)}else{let He=["[tool","[[END]]"],Ho=-1;for(let En of He){for(let fo=En.length-1;fo>0;fo--)if(ie.endsWith(En.substring(0,fo))){Ho=ie.length-fo,an=He.indexOf(En)===0?"tool":"end";break}if(Ho!==-1)break}if(Ho!==-1)Ho>0&&Ce.push({type:"text",content:ie.substring(0,Ho)}),Co=!0,Qt=ie.substring(Ho),ie="";else{Ce.push({type:"text",content:ie});break}}}return Ce},Zr=$e[Symbol.asyncIterator]();for(;;){let{value:oe,done:Ce}=await Promise.race([Zr.next(),sn]);if(Ce)break;if(io&&(yield{type:"status",content:"Working..."},io=!1),Bo){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
|
|
505
|
+
|
|
506
|
+
\x1B[33m\u2139 Request Cancelled\x1B[0m`};break}let ie="",We=oe.candidates?.[0]?.content?.parts;if(We&&We.length>0)for(let xe of We)xe.thought?xe.text&&(me||(ie+="<think>",me=!0),ie+=xe.text):xe.text&&(me&&(ie+="</think>",me=!1),ie+=xe.text);else{let xe=oe.text||"";xe&&me&&(ie+="</think>",me=!1),ie+=xe}if(ie){if(Jt){if(dt+=ie,dt.length>=64){let Z=0,Qe=Math.min(pt.length,dt.length);for(let X=Qe;X>=10;X--)if(pt.endsWith(dt.substring(0,X))){Z=X;break}let xt=dt.substring(Z);if(xt){let _e=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(pt)?xt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):xt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(_e)if(Te+=_e,d==="Google")Dt+=_e;else{let U=Sn(_e);for(let ve of U)yield ve}}Jt=!1,dt=""}continue}else if(Te+=ie,d==="Google")Dt+=ie;else{let Z=Sn(ie);for(let Qe of Z)yield Qe}let xe=rc(Te),St=Zu(Te);if(St.inside){Tt||(Tt=Date.now());let Z=St.toolName,xt={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"}[Z]||Z,X=St.args||"",_e=null;if(["write_file","update_file","view_file","read_folder","write_pdf","write_docx","search_keyword","generate_image","file_map"].includes(xt)){let ve=re(X),vo=ve.path||ve.targetFile||ve.TargetFile||ve.directory,z=ve.keyword;if(z)_e=z.replace(/["']/g,"");else if(vo)_e=Ae.basename(vo.replace(/["']/g,"").replace(/\\/g,"/"));else{let Jn=X.match(/(?:path|targetFile|TargetFile|directory|keyword)\s*=\s*\\?["']?([^\\"' \),]+)/);if(Jn){let yt=Jn[1].replace(/["']/g,"");_e=xt==="search_keyword"||xt==="file_map"?yt:Ae.basename(yt.replace(/\\/g,"/"))}}}let U=`${nc[xt]||xt}${_e?` (${_e})`:""}`;if((xt!==Et||_e!==Yn)&&(Et=xt,Yn=_e,yield{type:"status",content:`${U}...`},process.stdout.isTTY)){let vo={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"}[xt]||"Working";process.stdout.write(`\x1B]0;${vo}...\x07`)}}let He=ac(Te,!1),En=(He.match(/(?:<think>|\[think\])([\s\S]*?)(?:<\/think>|\[\/think\]|$)/gi)||[]).join("").trim(),fo=En.split(/[.!?]\s+/),Or=new Set(fo),Xn=fo.length>10?(fo.length-Or.size)/fo.length:0,os=En.split(/\s+/).filter(Z=>Z.length>0).length,Lr=.4,Pr=.6,Vn=!1;if((Rt||"").toLowerCase().startsWith("gemma")){let Qe={low:256,medium:768,high:2048,max:4096,xhigh:4096}[i?.toLowerCase()]||2500;Vn=os>Qe}if(Xn>Lr||Vn){yield{type:"status",content:`${Xn>Lr?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},vt=!0,await new Promise(Qe=>setTimeout(Qe,3e3));break}let qn=xe.trim().split(/[.!?]\s+/),zn=new Set(qn);if((qn.length>10?(qn.length-zn.size)/qn.length:0)>Pr){yield{type:"status",content:"Response Loop Detected. Re-centering..."},vt=!1,Bt=!0,await new Promise(Z=>setTimeout(Z,3e3));break}let Go=He.toLowerCase().split(/\s+/).filter(Z=>Z.length>0),Ko=!1;if(Go.length>5)for(let Z=1;Z<=15;Z++){let Qe=Math.max(3,Math.ceil(8/Z));if(Go.length<Z*Qe)continue;let xt=!0,_e=Go.slice(Go.length-Z).join(" ");for(let U=1;U<Qe;U++)if(Go.slice(Go.length-Z*(U+1),Go.length-Z*U).join(" ")!==_e){xt=!1;break}if(xt){Ko=!0;break}}if(!Ko){let Z=He.toLowerCase().replace(/[^a-z0-9]/gi,"");if(Z.length>=10)for(let Qe=1;Qe<=10;Qe++){let xt=Math.max(4,Math.ceil(12/Qe));if(Z.length<Qe*xt)continue;let X=Z.substring(Z.length-Qe),_e=!0;for(let U=1;U<xt;U++)if(Z.substring(Z.length-Qe*(U+1),Z.length-Qe*U)!==X){_e=!1;break}if(_e){Ko=!0;break}}}if(Ko){yield{type:"status",content:"Stuttering Detected. Re-centering..."},vt=!1,Yo=!0,await new Promise(Z=>setTimeout(Z,3e3));break}let Ta=Te.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/gi,""),dr=sa(Ta);for(;dr.length>Se;){yield*Ot();let Z=dr[Se],Qe=Date.now(),X={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",todo:"todo",Todo:"todo"}[Z.toolName]||Z.toolName,_e=nc[X]||Z.toolName,U=Qu(X,Z.args);yield{type:"status",content:`${_e}${U?` (${U})`:""}...`};let ve="";if(X==="web_search"){let{query:x,limit:g=10}=re(Z.args);ve=`\u{1F50D} Searched: ${x}`}else if(X==="web_scrape")ve=`\u{1F4D6} Visited: ${re(Z.args).url||"..."}`;else if(X==="view_file"){let{path:x,StartLine:g,EndLine:v,start_line:F,end_line:C,startLine:_,endLine:R}=re(Z.args),b=g||F||_,L=v||C||R,B=parseInt(b)||1,V=parseInt(L)||(b?B+800:800),ne="...",Ne=V;try{let Be=Ae.resolve(process.cwd(),x);if(tt.existsSync(Be)){let Yt=tt.readFileSync(Be,"utf8").split(`
|
|
507
|
+
`).length;ne=Yt,Ne=Math.min(V,Yt)}}catch{}let de=x.toLowerCase(),le=de.endsWith(".pdf"),fe=de.endsWith(".docx")||de.endsWith(".doc")||de.endsWith(".ppt")||de.endsWith(".pptx")||de.endsWith(".xls")||de.endsWith(".xlsx"),he=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(de);le||fe?ve=`\u{1F4C4} Viewed: ${x}`:he?ve=`\u{1F4F8} Viewed: ${x}`:ve=`\u{1F4C4} Read: ${x} \u2192 Lines ${B} - ${Ne} of ${ne}`}else if(X==="list_files"||X==="read_folder"){let x=X==="list_files"?"List":"Viewed",g=re(Z.args).path;ve=`\u{1F4C2} ${x}: ${g==="."?"./":g}`}else if(X==="write_file"||X==="update_file")ve=`\u{1F4BE} ${X==="write_file"?"Created":"Edited"}: ${re(Z.args).path||"..."}`;else if(X==="write_pdf")ve=`\u{1F4D1} Created: ${re(Z.args).path||"..."}`;else if(X==="write_docx")ve=`\u{1F4DD} Created: ${re(Z.args).path||"..."}`;else if(X==="file_map")ve=`\u{1F4CB} Get Map: ${re(Z.args).path||"..."}`;else if(X.toLowerCase()==="search_keyword"||X.toLowerCase()==="todo")ve="";else if(X.toLowerCase()==="generate_image"){let{path:x,outputPath:g,output:v}=re(Z.args);ve=`\u{1F3A8} Generated: ${x||g||v||"generated_image.png"}`}else X.toLowerCase()==="exec_command"||X.toLowerCase()==="ask"?ve="":ve=`Executed: ${Z.toolName}`;if(X==="exec_command"){let{command:x}=re(Z.args);if(x&&o.systemSettings&&o.systemSettings.allowExternalAccess===!1){let g=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],v=Ae.resolve(process.cwd()).substring(0,3).toLowerCase();if(g.some(C=>{if(C.source==="[a-zA-Z]:[\\\\\\/]"){let _=x.match(/[a-zA-Z]:[\\\/]/i);return _&&_[0].toLowerCase()!==v}return C.test(x)})){let C='Access Denied. Terminal is prohibited from accessing system drives (C://) or external directories while "External Workspace Access" is disabled.';o.onExecStart&&o.onExecStart(x||"Unknown"),yield{type:"exec_start"},await new Promise(_=>setTimeout(_,50)),o.onExecChunk&&o.onExecChunk(`ERROR: ${C}`),await new Promise(_=>setTimeout(_,50)),o.onExecEnd&&o.onExecEnd(),ct.push({role:"user",text:`[TOOL RESULT]: ERROR: ${C}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${C}`},Se++;continue}}o.onExecStart&&o.onExecStart(x||"Unknown"),yield{type:"exec_start"}}let vo=re(Z.args),z=vo.path||vo.targetPath||null;if(z){let x=o.systemSettings&&o.systemSettings.allowExternalAccess===!1,g=Ae.resolve(z),v=Ae.resolve(process.cwd());if(x&&!g.startsWith(v)){let F="Access Denied. You are not allowed to access files outside the current workspace.";if(X==="write_file"||X==="update_file"){let _=`\u{1F4BE} ${X==="write_file"?"Write Canceled":"Edit Canceled"}: ${vo.path||"..."}`,R=115;process.stdout.isTTY&&(R=process.stdout.columns-10||120);let b=Math.min(_.length+4,R),L=`\u256D${"\u2500".repeat(b)}\u256E`,B=`\u2502 ${_.padEnd(b-2).substring(0,b-2)} \u2502`,V=`\u2570${"\u2500".repeat(b)}\u256F`;yield{type:"visual_feedback",content:`${L}
|
|
508
|
+
${B}
|
|
509
|
+
${V}`}}ct.push({role:"user",text:`[TOOL RESULT]: ERROR: ${F}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${F}`},Se++;continue}}if(o.onToolApproval&&(X==="write_file"||X==="update_file"||X==="exec_command")){let g=o.systemSettings||{},v=g.autoExec,F=null,C=!1,_=!1,R=!1;if(X==="exec_command"){let{command:le}=re(Z.args),fe=(le||"").trim(),he=(Yt,wo)=>{if(!wo)return!1;let mt=wo.split(",").map(ao=>ao.trim().toLowerCase()).filter(Boolean),ln=Yt.toLowerCase();return mt.some(ao=>ln.startsWith(ao))},Be=he(fe,g.alwaysAskCommands),Re=he(fe,g.autoApproveCommands);_=he(fe,g.autoDisallowCommands),Be?C=!0:(Re||g.autoApproveGit&&/^git\s+commit\b/i.test(fe))&&(F="allow"),!C&&!F&&(g.networkAccess===!1&&/\b(curl|wget|npm|yarn|pnpm|pip|pip3|ssh|docker|git\s+(clone|push|pull|fetch))\b/i.test(fe)&&(F="deny",R=!0),!F&&_&&(F="deny")),!C&&!F&&v&&(F="allow")}else v&&(F="allow");let b=F,L="";F==="deny"&&(R?L="network":_?L="settings":L="prohibited");let B=!1,V="",ne=[],Ne=0,de=!1;if(!b){if(X==="write_file"||X==="update_file")try{let he=re(Z.args),{path:Be}=he;if(Be){let Re=Ae.resolve(process.cwd(),Be),Yt=we=>we?we.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,ye=>ye.toUpperCase()):"",wo=Yt(Re),mt="",ln=!1,ao=await qr(),K=Yt(ao?.file_focused);if(ao&&K===wo&&ao.full_content?(mt=ao.full_content,ln=!0):tt.existsSync(Re)&&(mt=tt.readFileSync(Re,"utf8"),ln=!0),V=mt,await nt.recordFileChange(Re,mt),ln){let we=mt;if(X==="write_file")we=he.content||he.newContent||"";else{let{patchPairs:ye,error:Le}=ps(he);if(Le){let Ue=`[TOOL RESULT]: ERROR: ${Le}`;ct.push({role:"user",text:Ue}),await Qo("toolFailure"),o.onToolResult&&o.onToolResult("failure",X),yield{type:"tool_result",content:Ue,toolName:X},Se++;continue}Ne=ye.length;let jt=gs(mt,ye);we=jt.content,ne=jt.results;let ke=ne.filter(Ue=>Ue.success),Ie=ne.filter(Ue=>!Ue.success);if(ke.length===0){let Ue=`[TOOL RESULT]: ERROR: Failed to apply patches to [${Ae.basename(Re)}].
|
|
510
|
+
${Ie.map(rs=>` \u2022 ${rs.error}`).join(`
|
|
511
|
+
`)}`,st=`\u{1F4BE} Edited: ${Ae.basename(Re)}`.toUpperCase(),Ge=115;process.stdout.isTTY&&(Ge=process.stdout.columns-10||120);let Ze=Math.min(st.length+4,Ge),Xo=`\u256D${"\u2500".repeat(Ze)}\u256E`,Cn=`\u2502 ${st.padEnd(Ze-2).substring(0,Ze-2)} \u2502`,Qn=`\u2570${"\u2500".repeat(Ze)}\u256F`;yield{type:"visual_feedback",content:`${Xo}
|
|
512
512
|
${Cn}
|
|
513
|
-
${Qn}`},
|
|
513
|
+
${Qn}`},ct.push({role:"user",text:Ue}),await Qo("toolFailure"),o.onToolResult&&o.onToolResult("failure",X),yield{type:"tool_result",content:Ue,toolName:X},Se++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${Ae.basename(Re)}...`},zi(Re,mt,we),B=!0,await new Promise(ye=>setTimeout(ye,50))}else if(X==="write_file"){let we=he.content||he.newContent||"";tt.existsSync(Re)||(de=!0,tt.mkdirSync(Ae.dirname(Re),{recursive:!0}),tt.writeFileSync(Re,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${Ae.basename(Re)}...`},zi(Re,"",we),B=!0,await new Promise(ye=>setTimeout(ye,50))}}}catch(he){console.error("Simulation/Diff Error:",he)}let le=null;qi(he=>{le=he});let fe=o.onToolApproval;if(b=await new Promise(async he=>{let Be=setInterval(()=>{le&&(Zi.onIDEApproval&&Zi.onIDEApproval(le),clearInterval(Be),he(le))},100);try{let Re=await fe(X,Z.args);clearInterval(Be),he(Re)}catch{clearInterval(Be),he("deny")}}),qi(null),X==="write_file"||X==="update_file"){let{path:he}=re(Z.args);if(he){let Be=Ae.resolve(process.cwd(),he);if(oc(Be,b),b==="deny"&&de&&tt.existsSync(Be))try{tt.unlinkSync(Be)}catch{}}}b==="deny"&&(L="user")}if(b==="allow"&&B&&Zo()){let{path:le}=re(Z.args),fe=Ae.resolve(process.cwd(),le),he=await qr(),Be="";he&&he.file_focused===fe&&he.full_content?Be=he.full_content:tt.existsSync(fe)&&(Be=tt.readFileSync(fe,"utf8"));let Re=Be.split(/\r?\n/),Yt=Re.length,wo=Buffer.byteLength(Be,"utf8"),mt="";V&&(mt=`Old File contents:
|
|
514
514
|
${V.split(/\r?\n/).map((Ze,Xo)=>`${Xo+1} | ${Ze}`).join(`
|
|
515
515
|
`)}
|
|
516
516
|
|
|
517
|
-
`);let
|
|
518
|
-
`);else{let Ge=
|
|
519
|
-
`),Ze=
|
|
520
|
-
`);
|
|
517
|
+
`);let ln="";if(Yt<=200)ln=Re.join(`
|
|
518
|
+
`);else{let Ge=Re.slice(0,100).join(`
|
|
519
|
+
`),Ze=Re.slice(-100).join(`
|
|
520
|
+
`);ln=`${Ge}
|
|
521
521
|
|
|
522
522
|
... [${Yt-200} lines truncated for history stability] ...
|
|
523
523
|
|
|
524
|
-
${Ze}`}let ao="";if(X==="update_file"){let Ge=
|
|
524
|
+
${Ze}`}let ao="";if(X==="update_file"){let Ge=xs(V,Be,ne,12);ao=`SUCCESS: File [${le}] updated via IDE Companion (May have user edits). [${ne.length}/${Ne}] blocks applied.
|
|
525
525
|
|
|
526
|
-
${Ge}`}else{let Ge=
|
|
527
|
-
${V.split(/\r?\n/).map((
|
|
526
|
+
${Ge}`}else{let Ge=Be.split(/\r?\n/),Ze=Ge.length,Xo=Buffer.byteLength(Be,"utf8"),Cn="";V&&(Cn=`Old File contents:
|
|
527
|
+
${V.split(/\r?\n/).map((qs,_c)=>`${_c+1} | ${qs}`).join(`
|
|
528
528
|
`)}
|
|
529
529
|
|
|
530
530
|
`);let Qn="";if(Ze<=200)Qn=Ge.join(`
|
|
531
|
-
`);else{let
|
|
532
|
-
`),
|
|
533
|
-
`);Qn=`${
|
|
531
|
+
`);else{let rs=Ge.slice(0,100).join(`
|
|
532
|
+
`),qs=Ge.slice(-100).join(`
|
|
533
|
+
`);Qn=`${rs}
|
|
534
534
|
|
|
535
535
|
... [${Ze-200} lines truncated] ...
|
|
536
536
|
|
|
537
|
-
${
|
|
537
|
+
${qs}`}ao=`SUCCESS: File [${le}] saved via IDE Companion (May have user edits).
|
|
538
538
|
|
|
539
539
|
- Stats: [${Ze} lines, ${(Xo/1024).toFixed(1)} KB]
|
|
540
540
|
${Cn}- Content Preview:
|
|
541
541
|
${Qn}
|
|
542
542
|
|
|
543
|
-
[SYSTEM] Check the content preview for verification [/SYSTEM]`}let we=`\u{1F4BE} ${X==="write_file"?"Written":"Edited"}: ${
|
|
543
|
+
[SYSTEM] Check the content preview for verification [/SYSTEM]`}let we=`\u{1F4BE} ${X==="write_file"?"Written":"Edited"}: ${le||"..."}`,ye=115;process.stdout.isTTY&&(ye=process.stdout.columns-10||120);let Le=Math.min(we.length+4,ye),jt=`\u256D${"\u2500".repeat(Le)}\u256E`,ke=`\u2502 ${we.padEnd(Le-2).substring(0,Le-2)} \u2502`,Ie=`\u2570${"\u2500".repeat(Le)}\u256F`;yield{type:"visual_feedback",content:`${jt}
|
|
544
544
|
${ke}
|
|
545
|
-
${Ie}`};let Ue=Date.now();Tn=Ue,yield{type:"tool_time",content:Ue-Qe};let st=`[TOOL RESULT]: ${ao}`;
|
|
545
|
+
${Ie}`};let Ue=Date.now();Tn=Ue,yield{type:"tool_time",content:Ue-Qe};let st=`[TOOL RESULT]: ${ao}`;ct.push({role:"user",text:st}),zt=!0,await Qo("toolSuccess"),o.onToolResult&&o.onToolResult("success",X),yield{type:"tool_result",content:ao,aiContent:st,toolName:X},Se++;continue}if(b==="deny"){let le=`Permission Denied: Prohibited ${X==="exec_command"?"Command":"file edit"}.`;if(L==="user"?le="Permission Denied by User":L==="settings"?le="Permission Denied by User Policy":L==="network"?le="Permission Denied: Sandbox Network Access Disabled by User Policy.":L==="prohibited"&&X==="exec_command"&&(le="Permission Denied: Prohibited Command"),X==="write_file"||X==="update_file"){let he=`\u{1F4BE} ${X==="write_file"?"WRITE DENIED":"UPDATE DENIED"}: ${re(Z.args).path||"..."}`.toUpperCase(),Be=115;process.stdout.isTTY&&(Be=process.stdout.columns-10||120);let Re=Math.min(he.length+4,Be),Yt=`\u256D${"\u2500".repeat(Re)}\u256E`,wo=`\u2502 ${he.padEnd(Re-2).substring(0,Re-2)} \u2502`,mt=`\u2570${"\u2500".repeat(Re)}\u256F`;yield{type:"visual_feedback",content:`${Yt}
|
|
546
546
|
${wo}
|
|
547
|
-
${
|
|
547
|
+
${mt}`}}X==="exec_command"&&(await new Promise(fe=>setTimeout(fe,50)),o.onExecChunk&&o.onExecChunk(`ERROR: ${le}`),await new Promise(fe=>setTimeout(fe,50)),o.onExecEnd&&o.onExecEnd()),ct.push({role:"user",text:`[TOOL RESULT]: DENIED: ${le}`}),yield{type:"tool_result",content:`[TOOL RESULT]: DENIED: ${le}`},await Qo("toolDenied"),o.onToolResult&&o.onToolResult("denied",X),Se++;continue}}if(ve){let x=115;process.stdout.isTTY&&(x=process.stdout.columns-10||120);let g=Math.min(ve.length+4,x),v=`\u256D${"\u2500".repeat(g)}\u256E`,F=`\u2502 ${ve.padEnd(g-2).substring(0,g-2)} \u2502`,C=`\u2570${"\u2500".repeat(g)}\u256F`;yield{type:"visual_feedback",content:`${v}
|
|
548
548
|
${F}
|
|
549
|
-
${C}`}}if(Tn>0){let x=Date.now()-Tn;x<1e3&&await new Promise(g=>setTimeout(g,1e3-x))}yield{type:"spinner",content:!1};let Jn={chatId:m,history:t,onChunk:x=>o.onExecChunk?o.onExecChunk(x):null,onAskUser:o.onAskUser,systemSettings:o.systemSettings,mode:u,isMultiModal:Qi(Rt)};if(X==="write_file"||X==="update_file")try{let{path:x}=
|
|
549
|
+
${C}`}}if(Tn>0){let x=Date.now()-Tn;x<1e3&&await new Promise(g=>setTimeout(g,1e3-x))}yield{type:"spinner",content:!1};let Jn={chatId:m,history:t,onChunk:x=>o.onExecChunk?o.onExecChunk(x):null,onAskUser:o.onAskUser,systemSettings:o.systemSettings,mode:u,isMultiModal:Qi(Rt)};if(X==="write_file"||X==="update_file")try{let{path:x}=re(Z.args);if(x){let g=Ae.resolve(process.cwd(),x),v=await qr();v&&v.file_focused===g&&v.full_content&&(Jn.forcedContent=v.full_content)}}catch{}let yt=await Ps(X,Z.args,Jn);if(yield{type:"spinner",content:!0},X==="write_file"&&yt.startsWith("SUCCESS")){let{path:x}=re(Z.args);if(x){let g=Ae.resolve(process.cwd(),x);tc(g)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let mr=Date.now();Tn=mr,yield{type:"tool_time",content:mr-Qe},Tt=mr;let bn=null;if(typeof yt=="object"&&yt.binaryPart&&(bn=yt.binaryPart,yt=yt.text),X==="search_keyword"){let{keyword:x,file:g}=re(Z.args),v=0;if(yt){let B=yt.match(/Found (\d+) matches/i);B&&(v=parseInt(B[1]))}let F=`\u{1F50E} Searched: "${x}" in ${g?`"${g}"`:"./"} \u2192 ${v} Match${v===1?"":"es"}`,C=115;process.stdout.isTTY&&(C=process.stdout.columns-10||120);let _=Math.min(F.length+4,C),R=`\u256D${"\u2500".repeat(_)}\u256E`,b=`\u2502 ${F.padEnd(_-2).substring(0,_-2)} \u2502`,L=`\u2570${"\u2500".repeat(_)}\u256F`;yield{type:"visual_feedback",content:`${R}
|
|
550
550
|
${b}
|
|
551
|
-
${L}`}}if(X==="todo"){let{method:x,tasks:g,markDone:v}=
|
|
552
|
-
`)}return b.filter(L=>String(L).trim()).map(L=>{let
|
|
551
|
+
${L}`}}if(X==="todo"){let{method:x,tasks:g,markDone:v}=re(Z.args),F="",C=[],_=R=>{if(!R)return[];let b=Array.isArray(R)?R:[];if(b.length===0&&typeof R=="string"){let L=R.trim();if(L.startsWith("[")&&L.endsWith("]")){let B=L.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);B?b=B.map(V=>V.slice(1,-1).replace(/\\(.)/g,"$1")):b=L.slice(1,-1).split(",").map(V=>V.trim()).filter(Boolean)}else b=R.split(`
|
|
552
|
+
`)}return b.filter(L=>String(L).trim()).map(L=>{let B=String(L).trim();return B.startsWith("- [")?B.substring(6).trim():B})};if(x==="create"?(F="\u{1F4C5} Created Plan",C=_(g).map(R=>`\u25CB ${R}`)):x==="append"?(F="\u{1F4E5} Added Plan",C=_(g).map(R=>`\u25CB ${R}`)):x==="get"&&(F=v?"\u{1F4CC} Updated Plan":"\u{1F4DD} Reviewed Plan",C=(yt||"").split(`
|
|
553
553
|
`).slice(1).join(`
|
|
554
554
|
`).split(`
|
|
555
|
-
`).filter(b=>b.trim().startsWith("- [")).map(b=>{let L=b.trim()
|
|
556
|
-
`)}}}X==="exec_command"&&o.onExecEnd&&(await new Promise(x=>setTimeout(x,800)),o.onExecEnd());let
|
|
557
|
-
`)}`;
|
|
555
|
+
`).filter(b=>b.trim().startsWith("- [")).map(b=>{let L=b.trim(),B=L.startsWith("- [x]");return`${B?"\x1B[32m\u25CF\x1B[0m":"\u25CB"} ${B?"\x1B[90m":"\x1B[37m"}${L.substring(6).trim()}\x1B[0m`})),F&&C.length>0){let R=Math.max(F.length,...C.map(le=>le.length))+4,b=100;process.stdout.isTTY&&(b=process.stdout.columns-10||120);let L=Math.min(R,b),B=`\u256D${"\u2500".repeat(L)}\u256E`,V=`\u2502 ${F.padEnd(L-2).substring(0,L-2)} \u2502`,ne=`\u251C${"\u2500".repeat(L)}\u2524`,Ne=C.map(le=>{let fe=le.replace(/\x1b\[[0-9;]*m/g,"").length,he=L-2,Be=Math.max(0,he-fe);return`\u2502 ${le}${" ".repeat(Be)} \u2502`}),de=`\u2570${"\u2500".repeat(L)}\u256F`;yield{type:"visual_feedback",content:[B,V,ne,...Ne,de].join(`
|
|
556
|
+
`)}}}X==="exec_command"&&o.onExecEnd&&(await new Promise(x=>setTimeout(x,800)),o.onExecEnd());let Fr=yt&&yt.startsWith("DENIED:");yt&&!yt.startsWith("ERROR:")&&!Fr?(await Qo("toolSuccess"),o.onToolResult&&o.onToolResult("success",X)):Fr||(await Qo("toolFailure"),o.onToolResult&&o.onToolResult("failure",X));let Lt=`[TOOL RESULT]: ${(yt||"").toString().split(/\r?\n/).filter(x=>!x.includes("[[UI_CONTEXT]]")).join(`
|
|
557
|
+
`)}`;ct.push({role:"user",text:Lt,binaryPart:bn}),zt=!0;let ns=`[TOOL RESULT]: ${yt||""}`;(X==="view_file"||X==="web_scrape"||X==="file_map")&&(ns=`[TOOL RESULT]: ${ve} (Context Locked for UI Clarity)`),yield{type:"tool_result",content:ns,aiContent:Lt,binaryPart:bn,toolName:X},X==="memory"&&yt.includes("SUCCESS")&&(yield{type:"memory_updated"}),Se++}if(d==="Google"&&Dt&&Date.now()-Wt>=150){let Z=Sn(Dt);for(let Qe of Z)yield Qe;Dt="",Wt=Date.now()}}oe.usageMetadata&&(At=oe.usageMetadata),At&&(yield{type:"liveTokens",content:At.totalTokenCount})}if(me&&(me=!1,Jt?dt+="</think>":(Te+="</think>",d==="Google"?Dt+="</think>":yield{type:"text",content:"</think>"})),Jt&&dt.length>0){let oe=0,Ce=Math.min(pt.length,dt.length);for(let We=Ce;We>0;We--)if(pt.endsWith(dt.substring(0,We))){oe=We;break}let ie=dt.substring(oe);if(ie){let xe=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(pt)?ie.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):ie.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(xe)if(Te+=xe,d==="Google")Dt+=xe;else{let St=Sn(xe);for(let He of St)yield He}}Jt=!1,dt=""}if(yield*Ot(),Bo)break;let Gn=(Te||"").trim(),vr=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(Gn.toLowerCase())||/\[\[END\]\]/i.test(Gn.toLowerCase()),es=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(Gn.toLowerCase()),Xs=ct.length>0||Et!==null,Dr=Gn.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/gi,"").trim(),Kn=/(\p{Emoji_Presentation}|\p{Extended_Pictographic})$/u.test(Dr),ur=/([.!?"'*_`|\]\)”’~~]+|\s|`{3}|[\u200B-\u200D\uFEFF])$/u.test(Dr.trim()),ts=/[.!?}"'`’“”]$|```$/s.test(Dr)||ur||Kn;!vr&&!es&&!Xs&&Gn.length>0,Ke=!0,await Qo("agent")}catch(be){if(Bo){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
|
|
558
558
|
|
|
559
|
-
\x1B[33m\u2139 Request Cancelled\x1B[0m`};break}if(String(be).includes("Incomplete JSON segment at the end")){me&&(me=!1,Jt?
|
|
559
|
+
\x1B[33m\u2139 Request Cancelled\x1B[0m`};break}if(String(be).includes("Incomplete JSON segment at the end")){me&&(me=!1,Jt?dt+="</think>":(Te+="</think>",yield{type:"text",content:"</think>"})),Ke=!0,await Qo("agent");break}if(me&&(me=!1,Jt?dt+="</think>":Te+="</think>"),Jt&&dt.length>0){let Wt=0,Ot=Math.min(pt.length,dt.length);for(let Qt=Ot;Qt>0;Qt--)if(pt.endsWith(dt.substring(0,Qt))){Wt=Qt;break}let io=dt.substring(Wt);if(io){let Co=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(pt)?io.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):io.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");Co&&(Te+=Co)}Jt=!1,dt=""}let je=be.status||be.error&&be.error.message||String(be),rn=String(be),gt=new Date().toLocaleString(),sn=Ae.join(To,"agent");tt.existsSync(sn)||tt.mkdirSync(sn,{recursive:!0}),tt.appendFileSync(Ae.join(sn,"error.log"),`ERROR [${gt}]: ${rn}
|
|
560
560
|
|
|
561
561
|
----------------------------------------------------------------------
|
|
562
562
|
|
|
563
|
-
`);let Ut=be.status||be.statusCode||be.code;if(!(Ut&&(Ut>=500&&Ut<600||Ut===408)||!Ut&&(/status[ :]+(5\d\d|408)/i.test(String(be))||/code[ :]+(5\d\d|408)/i.test(String(be))||/(500|503|408)/.test(String(be))))&&Oe<
|
|
563
|
+
`);let Ut=be.status||be.statusCode||be.code;if(!(Ut&&(Ut>=500&&Ut<600||Ut===408)||!Ut&&(/status[ :]+(5\d\d|408)/i.test(String(be))||/code[ :]+(5\d\d|408)/i.test(String(be))||/(500|503|408)/.test(String(be))))&&Oe<lt-3)throw be;if(Te.trim().length>0||Je>1)if(Je<=lt){Je++;let Wt=Math.min(1e3*Math.pow(2,Je-1),24e3);if(Te.trim().length>0){P.push({role:"agent",text:Te});let Ot=`[SYSTEM]
|
|
564
564
|
- SEAMLESS CONTINUATION: Resume immediately. Pick up from last words with zero gap/disruption
|
|
565
565
|
- NO REPETITION: Do not repeat any text already written
|
|
566
566
|
- NO RE-THINK: Do not restart or open <think> if reasoning already started. Continue the thinking and close thinking block with </think> if opened before outputting user response
|
|
567
567
|
- MID-TOOL SAFETY: If cutoff was mid-tool call, restart that tool call from start
|
|
568
|
-
- STEALTH: Do not mention/apologize for cutoff[/SYSTEM]`;
|
|
568
|
+
- STEALTH: Do not mention/apologize for cutoff[/SYSTEM]`;ct.length>0?ct.forEach((io,Qt)=>{Qt===ct.length-1?P.push({...io,text:`${io.text}
|
|
569
569
|
|
|
570
|
-
${Ot}`}):P.push(io)}):P.push({role:"user",text:Ot}),
|
|
571
|
-
Error Log can be found in ${Ae.join(To,"agent","error.log")}`);else if(Oe<=
|
|
572
|
-
Error Log can be found in ${Ae.join(To,"agent","error.log")}`)}}if(At){let me=At.totalTokenCount||0,be=At.cachedContentTokenCount||0,je=(At.candidatesTokenCount||0)+(At.thoughtsTokenCount||0);await Eo("tokens",me),be>0&&await Eo("cachedTokens",be),je>0&&await Eo("candidateTokens",je),yield{type:"usage",content:At}}wn.push(Te);let
|
|
573
|
-
`),be=me.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").trim();yield{type:"interactive_turn_finished",data:{agentText:D,fullAgentTextRaw:me,history:[...P],needTitle:W}},P.length>0&&P[P.length-1].role==="agent"?P[P.length-1].text=be:P.push({role:"agent",text:be})}if(Hn)break;let
|
|
570
|
+
${Ot}`}):P.push(io)}):P.push({role:"user",text:Ot}),pt+=Te}for(let Ot=Wt/1e3;Ot>0&&!Bo;Ot--)yield{type:"status",content:`Error Occured. Recovering Stream (${Je}/${lt}) [Retrying in ${Ot}s]...`},await new Promise(io=>setTimeout(io,1e3));yield{type:"status",content:"Error Occured. Recovering Stream..."}}else throw new Error(`Stream collapsed too many times. (Failed to resolve ${lt} times)
|
|
571
|
+
Error Log can be found in ${Ae.join(To,"agent","error.log")}`);else if(Oe<=lt){Oe++,Je=1,pt="";let Wt=Math.min(1e3*Math.pow(2,Oe-1),32e3);jn=!0,yield{type:"status",content:`Trying to reach ${e} (${Oe}/${lt}) [Retrying in ${(Wt/1e3).toFixed(0)}s]...`};for(let Ot=Wt/1e3;Ot>0&&!Bo;Ot--)yield{type:"status",content:`Trying to reach ${e} (${Oe}/${lt}) [Retrying in ${Ot}s]...`},await new Promise(io=>setTimeout(io,1e3));yield{type:"status",content:`Trying to reach ${e}...`}}else throw new Error(`Model ${e} cannot be reached. (Failed ${lt} times)
|
|
572
|
+
Error Log can be found in ${Ae.join(To,"agent","error.log")}`)}}if(At){let me=At.totalTokenCount||0,be=At.cachedContentTokenCount||0,je=(At.candidatesTokenCount||0)+(At.thoughtsTokenCount||0);await Eo("tokens",me),be>0&&await Eo("cachedTokens",be),je>0&&await Eo("candidateTokens",je),yield{type:"usage",content:At}}wn.push(Te);let Hs=Te;Te.match(/(?:<think>|\[think\])([\s\S]*?)(?:<\/think>|\[\/think\])/i)&&(Hs=Te.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/i,""));let Mr=rc(Te),lr=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(Mr.toLowerCase())||/\[\[END\]\]/i.test(Mr.toLowerCase())||!0,xa=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(Mr.toLowerCase()),Ar=Se>0;yield{type:"status",content:"Working..."};let Gs=ed(Te,/(\[\s*(turn\s*:)?\s*(continue|finish)\s*\]|\[\[END\]\])/gi,"").trim(),Hn=(lr||ct.length===0)&&!vt&&!Yo&&!Bt;if(Hn=ct.length===0?Hn:!1,Hn){let me=wn.join(`
|
|
573
|
+
`),be=me.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").trim();yield{type:"interactive_turn_finished",data:{agentText:D,fullAgentTextRaw:me,history:[...P],needTitle:W}},P.length>0&&P[P.length-1].role==="agent"?P[P.length-1].text=be:P.push({role:"agent",text:be})}if(Hn)break;let Ks=Gs.trim()||"*Working...*";if(P.push({role:"agent",text:Ks}),ct.length>0||zt){if(ct.length>0){let me=ct.map(je=>je.text).join(`
|
|
574
574
|
|
|
575
|
-
`),be=
|
|
575
|
+
`),be=ct.find(je=>je.binaryPart)?.binaryPart||null;P.push({role:"user",text:me,binaryPart:be})}}else ar?P.push({role:"user",text:"[SYSTEM] Failed to verify tool execution, Verify tool syntax, proper escaping or ask user if tool worked when unsure[/SYSTEM]"}):P.push({role:"user",text:`[SYSTEM] ${Yo&&!vt?"STUTTERING DETECTED by Internal System. Re-calibrate your response & proceed.":`${vt?" OVER THINKING":" LOOP"} DETECTED by Internal System${vt?" for current EFFORT_LEVEL":""}. ${vt?"If you have planned the task, prioritize execution/output":"If you have finished your task use [[END]]"}`} [/SYSTEM]`}),vt=!1,Yo=!1,Bt=!1;ar=Se>0||zt}e&&e.toLowerCase().startsWith("gemma")&&d==="Google"&&P.forEach(se=>{if(se.role==="user"&&se.text&&se.text.startsWith("[TOOL RESULT]")){let $e=`
|
|
576
576
|
[SYSTEM] Tool result received. Analyze output and proceed with your turn [/SYSTEM]`,Ke=`
|
|
577
|
-
[SYSTEM] Tool result received. Analyze output and proceed with your turn. **STRICTLY MAINTAIN THINKING POLICY. DO NOT START A RESPONSE WITHOUT <think> ... </think>** [/SYSTEM]`;
|
|
577
|
+
[SYSTEM] Tool result received. Analyze output and proceed with your turn. **STRICTLY MAINTAIN THINKING POLICY. DO NOT START A RESPONSE WITHOUT <think> ... </think>** [/SYSTEM]`;se.text=se.text.replace(Ke,"").replace($e,"").trim()}})}catch(M){let P=M instanceof Error?M.message:String(M),j=new Date().toLocaleString(),G=Ae.join(To,"agent");tt.existsSync(G)||tt.mkdirSync(G,{recursive:!0}),tt.appendFileSync(Ae.join(G,"error.log"),`CRITICAL ERROR [${j}]: ${M instanceof Error?M.stack:M}
|
|
578
578
|
|
|
579
579
|
----------------------------------------------------------------------
|
|
580
580
|
|
|
581
|
-
`),typeof flushGoogleBuffer=="function"&&(yield*flushGoogleBuffer()),yield{type:"tool_result",content:`ERROR: [INTERNAL CRITICAL] ${P}`}}finally{O&&(clearInterval(O),O=null),await
|
|
582
|
-
`);return
|
|
581
|
+
`),typeof flushGoogleBuffer=="function"&&(yield*flushGoogleBuffer()),yield{type:"tool_result",content:`ERROR: [INTERNAL CRITICAL] ${P}`}}finally{O&&(clearInterval(O),O=null),await nt.commitTransaction()}yield{type:"status",content:null}}});import $t,{useState as aa,useEffect as od}from"react";import{Box as en,Text as Rn,useInput as nd}from"ink";function la({onSelect:e,onDelete:t,onClose:o}){let[n,r]=aa({}),[s,i]=aa([]),[u,f]=aa(0);od(()=>{(async()=>{let p=await _o();r(p),i(Object.keys(p).sort((y,T)=>(p[T].updatedAt||0)-(p[y].updatedAt||0)))})()},[]),nd((h,p)=>{if(p.escape&&o(),p.upArrow&&f(y=>Math.max(0,y-1)),p.downArrow&&f(y=>Math.min(s.length-1,y+1)),p.return&&s[u]&&e(s[u]),h==="x"&&s[u]){let y=s[u];t(y).then(T=>{let w=T||{};r(w);let E=Object.keys(w).sort((A,$)=>(w[$]?.updatedAt||0)-(w[A]?.updatedAt||0));i(E),f(A=>Math.max(0,Math.min(E.length-1,A)))})}});let m=Fe(2),c=15,a=0;if(s.length>c){let h=Math.floor(c/2);a=u-h,a<0?a=0:a+c>s.length&&(a=s.length-c)}let d=s.slice(a,a+c);return $t.createElement(en,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},$t.createElement(en,{paddingX:1,marginBottom:1},$t.createElement(Rn,{color:"white",bold:!0},"CHAT HISTORY: RESUME CONVERSATION")),s.length===0?$t.createElement(en,{paddingX:2,paddingY:1},$t.createElement(Rn,{italic:!0,color:"gray"},"No saved chats found.")):$t.createElement(en,{flexDirection:"column",width:"100%"},a>0&&$t.createElement(en,{paddingX:2,marginBottom:1},$t.createElement(Rn,{color:"gray"},"\u25B2 (+",a," more chats above)")),d.map((h,p)=>{let y=n[h],w=a+p===u,E=rd(y?.updatedAt);return $t.createElement(en,{key:h,paddingX:1,backgroundColor:w?"#2a2a2a":void 0,width:"100%"},$t.createElement(en,{flexGrow:1},$t.createElement(Rn,{color:w?"while":"grey",bold:w},w?"\u276F ":" ",y?.name||h,$t.createElement(Rn,{color:"grey"}," [",E," \u2022 ",h,"]"))),w&&$t.createElement(en,{flexShrink:0},$t.createElement(Rn,{color:"white",bold:!0},"[X] DELETE ")))}),a+c<s.length&&$t.createElement(en,{paddingX:2,marginTop:1},$t.createElement(Rn,{color:"gray"},"\u25BC (+",s.length-(a+c)," more chats below)"))),$t.createElement(en,{marginTop:1,paddingX:1,borderStyle:"single",borderLeft:!1,borderRight:!1,borderBottom:!1,borderColor:"gray"},$t.createElement(Rn,{italic:!0},"\u2191\u2193 navigate \u2022 Enter select \u2022 x delete \u2022 Esc close")))}function rd(e){if(!e)return"N/A";let t=new Date(e);if(isNaN(t.getTime()))return"N/A";let o=u=>String(u).padStart(2,"0"),n=o(t.getMonth()+1),r=o(t.getDate()),s=o(t.getHours()),i=o(t.getMinutes());return`${n}-${r} ${s}:${i}`}var dc=ae(()=>{Kr();dn()});import kt,{useState as ca,useEffect as sd}from"react";import{Box as tn,Text as xn,useInput as id}from"ink";function ua({onClose:e}){let[t,o]=ca([]),[n,r]=ca(0),[s,i]=ca(!0),u=()=>{let w=pe(Ht,[]);o(w);try{let A=ls(lo,{}).systemSettings?.memory!==!1;i(A)}catch{i(!0)}};sd(()=>{u()},[]),id((w,E)=>{if(E.escape&&e(),E.upArrow&&r(A=>Math.max(0,A-1)),E.downArrow&&r(A=>Math.min(t.length-1,A+1)),w==="x"&&t.length>0){let A=t[n].id,$=t.filter(W=>W.id!==A);De(Ht,$),o($),n>=$.length&&$.length>0&&r($.length-1)}});let f=w=>w?w.replace(/\[Saved on: .*?\]/g,"").replace(/\\+'/g,"'").trim():"",m=4*1024*2,c=t.reduce((w,E)=>w+(E.memory?.length||0),0),a=Math.min(100,Math.round(c/m*100)),d=12,h=Math.round(a/100*d),p="\u2588".repeat(h)+"\u2591".repeat(Math.max(0,d-h)),y=()=>a<50?"grey":a<90?"yellow":"red",T=Fe(2);return kt.createElement(tn,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},kt.createElement(tn,{paddingX:1,marginBottom:1,justifyContent:"space-between"},kt.createElement(xn,{color:"white",bold:!0},"AGENT MEMORY: LONG-TERM KNOWLEDGE"),kt.createElement(tn,null,kt.createElement(xn,{color:"gray"},"Vault: "),kt.createElement(xn,{color:y()},p),kt.createElement(xn,{color:"white",bold:!0}," ",a,"%"))),!s&&t.length>0?kt.createElement(tn,{paddingX:2,paddingY:1},kt.createElement(xn,{italic:!0,color:"gray"},"Memory is currently Off...")):t.length===0?kt.createElement(tn,{paddingX:2,paddingY:1},kt.createElement(xn,{italic:!0,color:"gray"},s?"Learning...":"Memory not available...")):kt.createElement(tn,{flexDirection:"column"},t.map((w,E)=>{let A=E===n;return kt.createElement(tn,{key:w.id,paddingX:1,backgroundColor:A?"#2a2a2a":void 0,width:"100%"},kt.createElement(tn,{flexGrow:1},kt.createElement(xn,{color:A?"white":"grey",bold:A},A?"\u276F ":" ",E+1,". ",f(w.memory))),A&&kt.createElement(tn,{flexShrink:0},kt.createElement(xn,{color:"grey",bold:!0},"[X] WIPE ")))})),kt.createElement(tn,{marginTop:1,paddingX:1,borderStyle:"single",borderLeft:!1,borderRight:!1,borderBottom:!1,borderColor:"gray"},kt.createElement(xn,{color:"grey",italic:!0},"\u2191\u2193 navigate \u2022 x wipe memory \u2022 Esc close")))}var mc=ae(()=>{Oo();Pt();dn()});import at,{useState as Ns,useEffect as fc}from"react";import{Box as Un,Text as oo}from"ink";import{spawn as hc}from"child_process";var Bs,pc,ad,gc,xc=ae(async()=>{Bs=null;try{let e=await import("node-pty");Bs=e.default||e,Bs=!1}catch{}pc=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],ad=({latest:e,current:t,settings:o,onClose:n,onUpdateSettings:r,onSuccess:s})=>{let[i,u]=Ns("initializing"),[f,m]=Ns(""),[c,a]=Ns(null),[d,h]=Ns(0);if(fc(()=>{let p=setInterval(()=>{h(y=>(y+1)%1e3)},33);return()=>clearInterval(p)},[]),fc(()=>{let p;return(async()=>{let T=o.updateManager||"npm";if(!o.updateManager){r();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=o.customUpdateCommand:w=`npm install -g fluxflow-cli@${e}`,u("downloading"),m(`Running: ${w}...`);let E=process.platform==="win32",A=W=>new Promise(D=>{let O=E?W?"powershell.exe":"cmd.exe":process.env.SHELL||"bash",M=E?W?["-NoProfile","-Command",w]:["/c",w]:["-c",w],P=G=>{let Y=G.toString().replace(/\x1B\[[0-?]*[ -/]*[@-~]|\x1B\][^\x07\x1B]*[\x07\x1B]|\b|\x07/g,"").replace(/\r/g,"").trim();Y&&m(N=>{let ge=N.split(`
|
|
582
|
+
`);return ge[ge.length-1]?.startsWith("Progress:")&&Y.startsWith("Progress:")?(ge[ge.length-1]=Y,ge.slice(-5).join(`
|
|
583
583
|
`)):(N+`
|
|
584
584
|
`+Y).split(`
|
|
585
585
|
`).slice(-5).join(`
|
|
586
|
-
`)})};if(Br)try{let G=Br.spawn(O,M,{name:"xterm-256color",cols:80,rows:30,cwd:process.cwd(),env:process.env});p=G,G.onData(P),G.onExit(({exitCode:q})=>{p=null,D(q!==0?{error:`Process exited with code ${q}`}:{success:!0})});return}catch(G){if(E&&W&&G.code==="ENOENT"){D({retryCmd:!0});return}}let j=E?hc(O,M,{cwd:process.cwd(),env:process.env}):hc(w,{shell:!0,cwd:process.cwd(),env:process.env});p=j,j.stdout.on("data",P),j.stderr.on("data",P),j.on("close",G=>{p=null,D(G!==0?{error:`Process exited with code ${G}`}:{success:!0})}),j.on("error",G=>{E&&W&&G.code==="ENOENT"?D({retryCmd:!0}):(p=null,D({error:G.message}))})}),$={};E?($=await A(!0),$.retryCmd&&($=await A(!1))):$=await A(!1),$.error?(a($.error),u("error")):$.success&&(u("success"),r&&r())})(),()=>{if(p)try{typeof p.destroy=="function"?p.destroy():typeof p.kill=="function"&&p.kill()}catch{}}},[]),i==="initializing"||i==="downloading"){let p=pc[Math.floor(d/3)%pc.length];return it.createElement(Un,{flexDirection:"column",borderStyle:"round",borderColor:"white",paddingX:2,paddingY:1},it.createElement(Un,null,it.createElement(oo,{color:"gray"},p),it.createElement(oo,{marginLeft:1,bold:!0,color:"white"}," Updating Flux Flow to v",e,"...")),it.createElement(Un,{marginTop:1,paddingX:1,borderStyle:"single",borderColor:"gray"},it.createElement(oo,{color:"gray",italic:!0},f||"Preparing environment...")),it.createElement(oo,{marginTop:1,color:"gray"},"(Please do not close the terminal)"))}return i==="success"?it.createElement(Un,{flexDirection:"column",borderStyle:"round",borderColor:"white",paddingX:2,paddingY:1},it.createElement(oo,{color:"white",bold:!0},"\u2705 UPDATE SUCCESSFUL!"),it.createElement(oo,{marginTop:1,color:"white"},"Flux Flow has been updated to ",it.createElement(oo,{color:"gray"},"v",e),"."),it.createElement(oo,{marginTop:1,color:"white",bold:!0},"Please restart your terminal session to apply changes."),it.createElement(Un,{marginTop:1},it.createElement(oo,{color:"gray"},"(Press ESC to return to chat)"))):i==="error"?it.createElement(Un,{flexDirection:"column",borderStyle:"round",borderColor:"white",paddingX:2,paddingY:1},it.createElement(oo,{color:"white",bold:!0},"\u274C UPDATE FAILED"),it.createElement(Un,{marginTop:1,paddingX:1,borderStyle:"single",borderColor:"gray"},it.createElement(oo,{color:"white"},c)),it.createElement(oo,{marginTop:1,color:"white"},"Possible causes:"),it.createElement(oo,{color:"white"},"\u2022 Missing permissions (Try running as Administrator/Sudo)"),it.createElement(oo,{color:"white"},"\u2022 Package manager (",o.updateManager,") not found"),it.createElement(oo,{color:"white"},"\u2022 Network failure"),it.createElement(Un,{marginTop:1},it.createElement(oo,{color:"gray"},"(Press ESC to return to chat)"))):null},gc=ad});import yo,{useState as yc,useEffect as ld}from"react";import{Box as Wn,Text as ks,useInput as cd}from"ink";function da({onClose:e}){let[t,o]=yc(0),[n,s]=yc({});return ld(()=>{let r={};Rr.forEach(i=>{Ul(i.file)?r[i.file]="ready":r[i.file]="idle"}),s(r)},[]),cd(async(r,i)=>{i.escape&&e(),i.upArrow&&o(f=>Math.max(0,f-1)),i.downArrow&&o(f=>Math.min(Rr.length-1,f+1));let u=Rr[t];if(r==="x"||r==="X"){if(n[u.file]==="downloading")return;try{await Wl(u.file),s(f=>({...f,[u.file]:"idle"}))}catch(f){s(m=>({...m,[u.file]:`error: ${f.message}`}))}}if(i.return){if(n[u.file]==="downloading")return;s(f=>({...f,[u.file]:"downloading"}));try{await Yi(u.file),s(f=>({...f,[u.file]:"ready"}))}catch(f){s(m=>({...m,[u.file]:`error: ${f.message}`}))}}}),yo.createElement(Wn,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},yo.createElement(Wn,{paddingX:1,marginBottom:1},yo.createElement(ks,{color:"white",bold:!0},"LANGUAGE PARSER MANAGER")),yo.createElement(Wn,{flexDirection:"column"},Rr.map((r,i)=>{let u=i===t,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),h=".".repeat(d);return yo.createElement(Wn,{key:r.file,paddingX:1,backgroundColor:u?"#2a2a2a":void 0,width:"100%"},yo.createElement(Wn,null,yo.createElement(ks,{color:u?"white":"grey",bold:u},u?"\u276F ":" ",r.label," ",yo.createElement(ks,{dimColor:!0},"(",r.exts.join(", "),")"))),yo.createElement(Wn,{flexGrow:1},yo.createElement(ks,{color:"gray",dimColor:!0},h)),yo.createElement(Wn,{width:20},yo.createElement(ks,{color:c,bold:!0},m)))})),yo.createElement(Wn,{marginTop:1,paddingX:1,borderStyle:"single",borderLeft:!1,borderRight:!1,borderBottom:!1,borderColor:"gray"},yo.createElement(ks,{color:"grey",italic:!0},"\u2191\u2193 navigate \u2022 Enter download \u2022 x delete \u2022 Esc close")))}var Rr,wc=ae(()=>{un();ji();Rr=[{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 ma,Tc=ae(()=>{ma=["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 fa,Sc=ae(()=>{fa=["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 It,{useState as ud}from"react";import{Box as tn,Text as yn,useInput as dd}from"ink";function ha({prompts:e,onSelect:t,onClose:o}){let[n,s]=ud(0);dd((m,c)=>{c.escape&&o(),c.upArrow&&s(a=>Math.max(0,a-1)),c.downArrow&&s(a=>Math.min(e.length-1,a+1)),c.return&&e[n]&&t(e[n].id)});let r=Fe(2),i=10,u=0;if(e.length>i){let m=Math.floor(i/2);u=n-m,u<0?u=0:u+i>e.length&&(u=e.length-i)}let f=e.slice(u,u+i);return It.createElement(tn,{flexDirection:"column",borderStyle:"round",borderColor:"grey",padding:0,width:"100%"},It.createElement(tn,{paddingX:1,marginBottom:1},It.createElement(yn,{color:"white",bold:!0},"CODEBASE TIME TRAVEL: SELECT UNDO POINT")),It.createElement(tn,{paddingX:2,marginBottom:1},It.createElement(yn,null,"Select a prompt to revert the codebase back to the state ",It.createElement(yn,{bold:!0,color:"cyan"},"immediately before")," it was executed:")),e.length===0?It.createElement(tn,{paddingX:2,paddingY:1},It.createElement(yn,{italic:!0,color:"gray"},"No prompt checkpoints found for this session.")):It.createElement(tn,{flexDirection:"column",width:"100%"},u>0&&It.createElement(tn,{paddingX:2,marginBottom:1},It.createElement(yn,{color:"gray"},"\u25B2 (+",u," more prompts above)")),f.map((m,c)=>{let d=u+c===n,h=fd(m.timestamp),p=m.changes?m.changes.length:0;return It.createElement(tn,{key:m.id,paddingX:1,backgroundColor:d?"#444444":void 0,width:"100%"},It.createElement(tn,{flexGrow:1},It.createElement(yn,{color:d?"white":"grey",bold:d},d?"\u276F ":" ",'"',md(m.prompt),'"',It.createElement(yn,{color:`${d?"white":"grey"}`,dimColor:!0}," [",h," \u2022 ",p," file(s) changed]"))))}),u+i<e.length&&It.createElement(tn,{paddingX:2,marginTop:1},It.createElement(yn,{color:"gray"},"\u25BC (+",e.length-(u+i)," more prompts below)"))),It.createElement(tn,{marginTop:1,paddingX:1,borderStyle:"single",borderLeft:!1,borderRight:!1,borderBottom:!1,borderColor:"grey"},It.createElement(yn,{color:"grey",italic:!0},"\u2191\u2193 navigate \u2022 Enter select undo point \u2022 Esc close")))}function md(e){if(!e)return"";let o=(e.split(`
|
|
587
|
-
`)[0]||"").replace(/@\[(.*?)\]/g,(n,
|
|
588
|
-
`)?o+"...":o}function fd(e){if(!e)return"N/A";let t=new Date(e);if(isNaN(t.getTime()))return"N/A";let o=i=>String(i).padStart(2,"0"),n=o(t.getHours()),
|
|
586
|
+
`)})};if(Bs)try{let G=Bs.spawn(O,M,{name:"xterm-256color",cols:80,rows:30,cwd:process.cwd(),env:process.env});p=G,G.onData(P),G.onExit(({exitCode:q})=>{p=null,D(q!==0?{error:`Process exited with code ${q}`}:{success:!0})});return}catch(G){if(E&&W&&G.code==="ENOENT"){D({retryCmd:!0});return}}let j=E?hc(O,M,{cwd:process.cwd(),env:process.env}):hc(w,{shell:!0,cwd:process.cwd(),env:process.env});p=j,j.stdout.on("data",P),j.stderr.on("data",P),j.on("close",G=>{p=null,D(G!==0?{error:`Process exited with code ${G}`}:{success:!0})}),j.on("error",G=>{E&&W&&G.code==="ENOENT"?D({retryCmd:!0}):(p=null,D({error:G.message}))})}),$={};E?($=await A(!0),$.retryCmd&&($=await A(!1))):$=await A(!1),$.error?(a($.error),u("error")):$.success&&(u("success"),s&&s())})(),()=>{if(p)try{typeof p.destroy=="function"?p.destroy():typeof p.kill=="function"&&p.kill()}catch{}}},[]),i==="initializing"||i==="downloading"){let p=pc[Math.floor(d/3)%pc.length];return at.createElement(Un,{flexDirection:"column",borderStyle:"round",borderColor:"white",paddingX:2,paddingY:1},at.createElement(Un,null,at.createElement(oo,{color:"gray"},p),at.createElement(oo,{marginLeft:1,bold:!0,color:"white"}," Updating Flux Flow to v",e,"...")),at.createElement(Un,{marginTop:1,paddingX:1,borderStyle:"single",borderColor:"gray"},at.createElement(oo,{color:"gray",italic:!0},f||"Preparing environment...")),at.createElement(oo,{marginTop:1,color:"gray"},"(Please do not close the terminal)"))}return i==="success"?at.createElement(Un,{flexDirection:"column",borderStyle:"round",borderColor:"white",paddingX:2,paddingY:1},at.createElement(oo,{color:"white",bold:!0},"\u2705 UPDATE SUCCESSFUL!"),at.createElement(oo,{marginTop:1,color:"white"},"Flux Flow has been updated to ",at.createElement(oo,{color:"gray"},"v",e),"."),at.createElement(oo,{marginTop:1,color:"white",bold:!0},"Please restart your terminal session to apply changes."),at.createElement(Un,{marginTop:1},at.createElement(oo,{color:"gray"},"(Press ESC to return to chat)"))):i==="error"?at.createElement(Un,{flexDirection:"column",borderStyle:"round",borderColor:"white",paddingX:2,paddingY:1},at.createElement(oo,{color:"white",bold:!0},"\u274C UPDATE FAILED"),at.createElement(Un,{marginTop:1,paddingX:1,borderStyle:"single",borderColor:"gray"},at.createElement(oo,{color:"white"},c)),at.createElement(oo,{marginTop:1,color:"white"},"Possible causes:"),at.createElement(oo,{color:"white"},"\u2022 Missing permissions (Try running as Administrator/Sudo)"),at.createElement(oo,{color:"white"},"\u2022 Package manager (",o.updateManager,") not found"),at.createElement(oo,{color:"white"},"\u2022 Network failure"),at.createElement(Un,{marginTop:1},at.createElement(oo,{color:"gray"},"(Press ESC to return to chat)"))):null},gc=ad});import yo,{useState as yc,useEffect as ld}from"react";import{Box as Wn,Text as kr,useInput as cd}from"ink";function da({onClose:e}){let[t,o]=yc(0),[n,r]=yc({});return ld(()=>{let s={};Rs.forEach(i=>{Ul(i.file)?s[i.file]="ready":s[i.file]="idle"}),r(s)},[]),cd(async(s,i)=>{i.escape&&e(),i.upArrow&&o(f=>Math.max(0,f-1)),i.downArrow&&o(f=>Math.min(Rs.length-1,f+1));let u=Rs[t];if(s==="x"||s==="X"){if(n[u.file]==="downloading")return;try{await Wl(u.file),r(f=>({...f,[u.file]:"idle"}))}catch(f){r(m=>({...m,[u.file]:`error: ${f.message}`}))}}if(i.return){if(n[u.file]==="downloading")return;r(f=>({...f,[u.file]:"downloading"}));try{await Yi(u.file),r(f=>({...f,[u.file]:"ready"}))}catch(f){r(m=>({...m,[u.file]:`error: ${f.message}`}))}}}),yo.createElement(Wn,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},yo.createElement(Wn,{paddingX:1,marginBottom:1},yo.createElement(kr,{color:"white",bold:!0},"LANGUAGE PARSER MANAGER")),yo.createElement(Wn,{flexDirection:"column"},Rs.map((s,i)=>{let u=i===t,f=n[s.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=`${s.label} (${s.exts.join(", ")})`,d=Math.max(2,45-a.length),h=".".repeat(d);return yo.createElement(Wn,{key:s.file,paddingX:1,backgroundColor:u?"#2a2a2a":void 0,width:"100%"},yo.createElement(Wn,null,yo.createElement(kr,{color:u?"white":"grey",bold:u},u?"\u276F ":" ",s.label," ",yo.createElement(kr,{dimColor:!0},"(",s.exts.join(", "),")"))),yo.createElement(Wn,{flexGrow:1},yo.createElement(kr,{color:"gray",dimColor:!0},h)),yo.createElement(Wn,{width:20},yo.createElement(kr,{color:c,bold:!0},m)))})),yo.createElement(Wn,{marginTop:1,paddingX:1,borderStyle:"single",borderLeft:!1,borderRight:!1,borderBottom:!1,borderColor:"gray"},yo.createElement(kr,{color:"grey",italic:!0},"\u2191\u2193 navigate \u2022 Enter download \u2022 x delete \u2022 Esc close")))}var Rs,wc=ae(()=>{dn();ji();Rs=[{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 ma,Tc=ae(()=>{ma=["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 fa,Sc=ae(()=>{fa=["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 It,{useState as ud}from"react";import{Box as on,Text as yn,useInput as dd}from"ink";function ha({prompts:e,onSelect:t,onClose:o}){let[n,r]=ud(0);dd((m,c)=>{c.escape&&o(),c.upArrow&&r(a=>Math.max(0,a-1)),c.downArrow&&r(a=>Math.min(e.length-1,a+1)),c.return&&e[n]&&t(e[n].id)});let s=Fe(2),i=10,u=0;if(e.length>i){let m=Math.floor(i/2);u=n-m,u<0?u=0:u+i>e.length&&(u=e.length-i)}let f=e.slice(u,u+i);return It.createElement(on,{flexDirection:"column",borderStyle:"round",borderColor:"grey",padding:0,width:"100%"},It.createElement(on,{paddingX:1,marginBottom:1},It.createElement(yn,{color:"white",bold:!0},"CODEBASE TIME TRAVEL: SELECT UNDO POINT")),It.createElement(on,{paddingX:2,marginBottom:1},It.createElement(yn,null,"Select a prompt to revert the codebase back to the state ",It.createElement(yn,{bold:!0,color:"cyan"},"immediately before")," it was executed:")),e.length===0?It.createElement(on,{paddingX:2,paddingY:1},It.createElement(yn,{italic:!0,color:"gray"},"No prompt checkpoints found for this session.")):It.createElement(on,{flexDirection:"column",width:"100%"},u>0&&It.createElement(on,{paddingX:2,marginBottom:1},It.createElement(yn,{color:"gray"},"\u25B2 (+",u," more prompts above)")),f.map((m,c)=>{let d=u+c===n,h=fd(m.timestamp),p=m.changes?m.changes.length:0;return It.createElement(on,{key:m.id,paddingX:1,backgroundColor:d?"#444444":void 0,width:"100%"},It.createElement(on,{flexGrow:1},It.createElement(yn,{color:d?"white":"grey",bold:d},d?"\u276F ":" ",'"',md(m.prompt),'"',It.createElement(yn,{color:`${d?"white":"grey"}`,dimColor:!0}," [",h," \u2022 ",p," file(s) changed]"))))}),u+i<e.length&&It.createElement(on,{paddingX:2,marginTop:1},It.createElement(yn,{color:"gray"},"\u25BC (+",e.length-(u+i)," more prompts below)"))),It.createElement(on,{marginTop:1,paddingX:1,borderStyle:"single",borderLeft:!1,borderRight:!1,borderBottom:!1,borderColor:"grey"},It.createElement(yn,{color:"grey",italic:!0},"\u2191\u2193 navigate \u2022 Enter select undo point \u2022 Esc close")))}function md(e){if(!e)return"";let o=(e.split(`
|
|
587
|
+
`)[0]||"").replace(/@\[(.*?)\]/g,(n,r)=>{let s=r.replace(/\\/g,"/").split("/");return`[${s[s.length-1]}]`});return o.length>69?o.slice(0,67)+"...":e.includes(`
|
|
588
|
+
`)?o+"...":o}function fd(e){if(!e)return"N/A";let t=new Date(e);if(isNaN(t.getTime()))return"N/A";let o=i=>String(i).padStart(2,"0"),n=o(t.getHours()),r=o(t.getMinutes()),s=o(t.getSeconds());return`${n}:${r}:${s}`}var Ec=ae(()=>{dn()});import hd from"puppeteer";import{exec as pd}from"child_process";import{promisify as gd}from"util";import xd from"fs";var bc,Cc,kc,Ic=ae(()=>{bc=gd(pd),Cc=()=>{try{let e=hd.executablePath();if(e&&xd.existsSync(e))return!0}catch{return!1}return!1},kc=async e=>{e&&e("\u{1F4E5} Downloading Chromium engine (chrome@148)...");try{try{await bc("pnpm exec puppeteer browsers install chrome@148")}catch{await bc("npx -y puppeteer browsers install chrome@148")}return await new Promise(t=>setTimeout(t,1e3)),{success:!0}}catch(t){return console.error("[SETUP ERROR]",t),{success:!1,error:t.message}}}});var Pc={};ss(Pc,{default:()=>Lc});import Mc from"os";import l,{useState as Q,useEffect as no,useRef as bo,useMemo as Jr}from"react";import{Box as I,Text as S,useInput as yd,useStdout as wd}from"ink";import uo from"fs-extra";import ir from"path";import{exec as Us}from"child_process";import{fileURLToPath as Td}from"url";import Ac from"ink-text-input";import Sd from"gradient-string";function Lc({args:e=[]}){let[t,o]=Q(!1),[n,r]=Q(10),{stdout:s}=wd(),[i,u]=Q(""),[f,m]=Q(0),[c,a]=Q(!1),[d,h]=Q("Flux"),[p,y]=Q({columns:s?.columns||80,rows:s?.rows||24}),[T,w]=Q(0),[E,A]=Q(!1),[$,W]=Q(!1),[D,O]=Q(0),M=bo(0),P=bo(null);no(()=>{let x=js(),g=!["Terminal","Windows Terminal"].includes(x)||!!process.env.VSC_TERMINAL_URL,v=setTimeout(()=>{g&&!Zo()&&W(!0)},500),F=setInterval(()=>{Zo()&&W(!1)},1e3);return()=>{clearTimeout(v),clearInterval(F)}},[]);let j=Jr(()=>{let x={};for(let g=0;g<e.length;g++)if(e[g]==="--key"&&e[g+1]){let F=e[g+1];if(x.key=F,F.includes("@")){let C=F.split("@"),_=C[0],R=C[1].toLowerCase();if(["google","deepseek","openrouter","nvidia"].includes(R)){let b="Google";R==="google"?b="Google":R==="deepseek"?b="DeepSeek":R==="openrouter"?b="OpenRouter":R==="nvidia"&&(b="NVIDIA"),x.key=_,x.provider=b}}}for(let g=0;g<e.length;g++){let v=e[g];if(v==="--key"){g++;continue}if(v==="--model"&&e[g+1])x.model=e[g+1],g++;else if(v==="--memory"&&e[g+1])x.memory=e[g+1].toLowerCase(),g++;else if(v==="--resume"&&e[g+1])x.resume=e[g+1],g++;else if(v==="--package"&&e[g+1]){let F=e[g+1].toLowerCase();["npm","pnpm","yarn","bun"].includes(F)&&(x.package=F),g++}else if(v==="--auto-del"&&e[g+1]){let F=e[g+1].toLowerCase();["1d","7d","30d"].includes(F)&&(x.autoDel=F),g++}else if(v==="--auto-exec"&&e[g+1])x.autoExec=e[g+1].toLowerCase(),g++;else if(v==="--yolo"&&e[g+1])x.autoExec=e[g+1].toLowerCase(),g++;else if(v==="--external-access"&&e[g+1])x.externalAccess=e[g+1].toLowerCase(),g++;else if(v==="--mode"&&e[g+1]){let C=e[g+1].toLowerCase();if(["flux","flow"].includes(C)){let _="Flux";C==="flux"?_="Flux":C==="flow"&&(_="Flow"),x.mode=_}g++}else if(v==="--thinking"&&e[g+1]){let C=e[g+1].toLowerCase();if(["fast","low","medium","high","xhigh","standard"].includes(C)){let _="Medium";C==="fast"?_="Fast":C==="low"?_="Low":C==="standard"?_="Standard":C==="medium"?_="Medium":C==="high"?_="High":C==="xhigh"&&(_="xHigh"),x.thinking=_}g++}else if(v==="--provider"&&e[g+1]){let F=e[g+1].toLowerCase();if(["google","deepseek","openrouter","nvidia"].includes(F)){let C="Google";F==="google"?C="Google":F==="deepseek"?C="DeepSeek":F==="openrouter"?C="OpenRouter":F==="nvidia"&&(C="NVIDIA"),x.provider=C}g++}else(v==="--resume"||v==="-r")&&e[g+1]&&(x.resume=e[g+1],g++)}return x},[e]),G=async(x=!1,g=null)=>{let v=g||Nt;x&&U(F=>(z(F.length+1),[...F,{id:"check-"+Date.now(),role:"system",text:"\u{1F50D} Checking for updates...",isMeta:!0}]));try{let C=await(await fetch("https://registry.npmjs.org/fluxflow-cli",{cache:"no-store"})).json(),_=C["dist-tags"]?.latest,R=C["dist-tags"]?.stable;if(_&&ue(_),_&&_!==Uo){let b=_===R?`v${_}-stable`:`v${_}`;!x&&v.autoUpdate?J("update"):U(L=>{let B=[...L],V=x?B.length:Math.min(B.length,3);return B.splice(V,0,{id:"update-"+Date.now(),role:"system",text:`A new version (${b}) is here.
|
|
589
589
|
|
|
590
590
|
\u2022 Type \`/update latest\` to apply the update.
|
|
591
|
-
\u2022 Type \`/changelog\` to view the release notes.`,isUpdateNotification:!0,isMeta:!0}),
|
|
591
|
+
\u2022 Type \`/changelog\` to view the release notes.`,isUpdateNotification:!0,isMeta:!0}),B})}else x&&U(b=>{z(b.length+1);let L=_&&_===R?`${Uo}-stable`:Uo;return[...b,{id:"uptodate-"+Date.now(),role:"system",text:`[SYSTEM] Flux Flow is already up to date (${L}).`,isMeta:!0}]})}catch(F){x&&U(C=>(z(C.length+1),[...C,{id:"check-err-"+Date.now(),role:"system",text:`ERROR: Failed to check for updates: ${F.message}`,isMeta:!0}]))}};no(()=>{let x=()=>{s.write("\x1B[2J\x1B[3J\x1B[H"),y({columns:s.columns,rows:s.rows})};return s.on("resize",x),()=>{s.off("resize",x)}},[s]);let[q,Y]=Q("Medium"),[N,ge]=Q("Google"),[ee,Me]=Q(0),[ce,ue]=Q(null),[Xe,_t]=Q(!1),[Ve,Ee]=Q("gemma-4-31b-it"),[ht,et]=Q("gemma-4-26b-a4b-it"),[Ye,qe]=Q(!0),[mo,Vt]=Q(!0),ut=bo(0),[ze,ot]=Q(null),[Ao,nn]=Q(""),[qt,J]=Q("chat"),[Mt,ro]=Q("Free"),[so,Qr]=Q({agentLimit:999999,backgroundLimit:999999,searchLimit:100,customModelId:"",customLimit:0}),[Wo,At]=Q(null),[Nt,lt]=Q({memory:!0,compression:0,autoExec:!1,autoDeleteHistory:"7d",autoUpdate:!1,updateManager:"npm",customUpdateCommand:""}),[wn,ar]=Q({name:null,nickname:null,instructions:null}),[se,$e]=Q({keyType:"Default",quality:"Low-High",apiKey:""}),[Ke,Oe]=Q({tokens:0}),[Je,Te]=Q(0),[Et,Yn]=Q(0),[Tt,Tn]=Q(0),[ct,Se]=Q(0),zt=bo(0),[vt,Yo]=Q(0),[Bt,jn]=Q(0),[pt,dt]=Q(0),[Jt,Rt]=Q(0),[jo,Hs]=Q(0),[Ir,Mr]=Q(0),[lr,xa]=Q(0),[Ar,Gs]=Q(0),[Hn,Ks]=Q(0),[me,be]=Q(null),[je,rn]=Q(xi());no(()=>{let x=Tt-zt.current;Se(x),je&&ul(je,x,Ke.tokens).catch(()=>{})},[Tt,je,Ke.tokens]);let[gt,sn]=Q(null),[Ut,Dt]=Q(""),[Wt,Ot]=Q(!1),[io,Qt]=Q(0),Co=bo(!0),an=bo(!0),Sn=bo(!0),Zr=bo(N);no(()=>{Zr.current!==N?(Zr.current=N,Y(N==="DeepSeek"||N==="NVIDIA"?"Standard":"Medium")):N==="Google"&&q==="xHigh"&&Ve&&Ve.toLowerCase().startsWith("gemini-3")&&Y("High")},[N,Ve,q]),no(()=>{if(!ze)return;if(Co.current){Co.current=!1,setTimeout(()=>{an.current=!1,setTimeout(()=>{Sn.current=!1},1e3)},2e3);return}if(an.current||Sn.current)return;let x=Fe(2),g="",v="";Mt==="Free"?N==="Google"?(g="gemma-4-31b-it",v="Gemma 4 (Free default)"):N==="DeepSeek"?(g="deepseek-v4-flash",v="DeepSeek Flash (Free default)"):N==="NVIDIA"?(g="moonshotai/kimi-k2.6",v="Moonshot Kimi (NVIDIA)"):(g="google/gemma-4-31b-it:free",v="Gemma 4 (Free default)"):N==="Google"?(g="gemini-3-flash-preview",v="Gemini 3 Flash"):N==="DeepSeek"?(g="deepseek-v4-flash",v="DeepSeek Flash"):N==="NVIDIA"?(g="moonshotai/kimi-k2.6",v="Moonshot Kimi (NVIDIA)"):(g="deepseek/deepseek-v4-flash",v="DeepSeek Flash"),Ee(g),Dn({apiTier:Mt,activeModel:g}),U(F=>(z(F.length+1),[...F,{id:"tier-switch-"+Date.now(),role:"system",text:`**[TIER LIMIT]** Auto-switched to ${v}.`,isMeta:!0}]))},[Mt,N,ze]);let Gn=Jr(()=>{let x=js(),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"}},[]),vr=bo(null),es=bo("");no(()=>{vr.current=gt},[gt]),no(()=>{es.current=Ut},[Ut]);let[Xs,Dr]=Q(!1),[Kn,cr]=Q(null),[ur,ts]=Q(null),oe=x=>{cr(null),J("chat")},Ce=x=>{let g=Math.floor(x/3600),v=Math.floor(x%3600/60),F=x%60,C=[];return g>0&&C.push(`${g}h`),(v>0||g>0)&&C.push(`${v}m`),C.push(`${F}s`),C.join(" ")},ie=x=>x<1e3?`${x}ms`:Ce(Math.floor(x/1e3)),[We,xe]=Q(null),[St,He]=Q("");no(()=>{let x;if(We){let g=()=>{let v=fa[Math.floor(Math.random()*fa.length)];He(v)};St||g(),x=setInterval(g,1e4)}else He("");return()=>clearInterval(x)},[We]);let[Ho,En]=Q(!0),[fo,Or]=Q(!1),[Xn,os]=Q(!1),[Lr,Pr]=Q(!1),[Vn,ya]=Q(null),[qn,zn]=Q(0),[wa,Go]=Q([]),Ko=bo(null),[Ta,dr]=Q(null),[Z,Qe]=Q(null),[xt,X]=Q(null);no(()=>zn(0),[i]);let[_e,U]=Q(()=>{let x={id:"logo-"+Date.now(),role:"system",isLogo:!0,isMeta:!0},g=process.cwd()===Mc.homedir(),v=(()=>{let C=process.cwd().toLowerCase();if(process.platform==="win32"){let _=process.env.SystemRoot?.toLowerCase()||"c:\\windows",R=process.env.ProgramFiles?.toLowerCase()||"c:\\program files",b=process.env["ProgramFiles(x86)"]?.toLowerCase()||"c:\\program files (x86)";return C.startsWith(_)||C.startsWith(R)||C.startsWith(b)}else return C==="/"||["/bin","/sbin","/etc","/usr","/var","/root"].some(R=>C.startsWith(R))})(),F=[x];return v?F.push({id:"system-warning",role:"system",text:"[CRITICAL SECURITY ALERT] SYSTEM DIRECTORY DETECTED",subText:`You are currently in a PROTECTED SYSTEM DIRECTORY (${process.cwd()}). Operating here is EXTREMELY dangerous as the agent could accidentally corrupt your OS or installed applications. PLEASE MOVE TO A PROJECT FOLDER FOR SAFETY.`,isHomeWarning:!0,isMeta:!0}):g&&F.push({id:"home-warning",role:"system",text:"[SECURITY ALERT] HOME DIRECTORY DETECTED",subText:`You are currently in ${Mc.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}),F}),ve=bo(null),[vo,z]=Q(_e.length),Jn=Jr(()=>{let g=p.columns||80,v=0,F=0;for(let C=_e.length-1;C>=0;C--){let _=_e[C];if(!_)continue;let R=_.text||"",b=R.split(/\r?\n/).length;if(R.split(/\r?\n/).forEach(L=>{b+=Math.floor(L.length/g)}),_.isHelpRecord&&(b=15),_.isUpdateNotification&&(b=8),_.isTerminalRecord&&(b=10),b+=_.role==="think"?3:2,v+b>2e3){F=C+1;break}v+=b}return{items:_e.slice(F,vo),isTruncated:F>0}},[_e,p.columns,p.rows]),yt=Jr(()=>{if(!gt||!Ut)return!1;let x=Ut.trim();return x.endsWith("?")||x.endsWith(":")||/\[[yYnN/]+\]\s*$/.test(x)||/\([yYnN]\)\s*$/.test(x)},[gt,Ut]);yd((x,g)=>{if(!(x==="\x1B[I"||x==="\x1B[O"||x==="[I"||x==="[O")){if($){let v=js(),F=Dc(v);if(g.upArrow)O(C=>C>0?C-1:F.length-1);else if(g.downArrow)O(C=>C<F.length-1?C+1:0);else if(g.return){let C=F[D];if(C.action==="dismiss")W(!1);else if(C.url){let _=process.platform==="win32"?`start ${C.url}`:process.platform==="darwin"?`open ${C.url}`:`xdg-open ${C.url}`;Us(_),W(!1)}}return}if(g.tab&>){Ot(v=>!v);return}if(Wt&>){if(g.return){let v=process.platform==="win32";ko(v?`\r
|
|
592
592
|
`:`
|
|
593
593
|
`),Po||Dt(F=>F+`
|
|
594
|
-
`)}else if(g.backspace||g.delete)Po?ko("\x7F"):(ko("\b \b"),Dt(v=>v.slice(0,-1)));else if(g.upArrow)ko(g.shift?"\x1B[1;2A":"\x1B[A");else if(g.downArrow)ko(g.shift?"\x1B[1;2B":"\x1B[B");else if(g.rightArrow)ko(g.shift?"\x1B[1;2C":"\x1B[C");else if(g.leftArrow)ko(g.shift?"\x1B[1;2D":"\x1B[D");else if(g.escape)ko("\x1B");else if(g.ctrl&&x){let v=x.toLowerCase().charCodeAt(0);v>=97&&v<=122?ko(String.fromCharCode(v-96)):ko(x)}else x&&(ko(x),Po||Dt(v=>v+x));return}if(g.escape){if(Lt.length>0&&qt==="chat"){A(!0);return}if(t){o(!1);return}if(fo||
|
|
595
|
-
`)}}),no(()=>{process.stdout.write("\x1B[?1004h");let x=g=>{let v=g.toString();v.includes("\x1B[I")?(Vt(!0),
|
|
594
|
+
`)}else if(g.backspace||g.delete)Po?ko("\x7F"):(ko("\b \b"),Dt(v=>v.slice(0,-1)));else if(g.upArrow)ko(g.shift?"\x1B[1;2A":"\x1B[A");else if(g.downArrow)ko(g.shift?"\x1B[1;2B":"\x1B[B");else if(g.rightArrow)ko(g.shift?"\x1B[1;2C":"\x1B[C");else if(g.leftArrow)ko(g.shift?"\x1B[1;2D":"\x1B[D");else if(g.escape)ko("\x1B");else if(g.ctrl&&x){let v=x.toLowerCase().charCodeAt(0);v>=97&&v<=122?ko(String.fromCharCode(v-96)):ko(x)}else x&&(ko(x),Po||Dt(v=>v+x));return}if(g.escape){if(Lt.length>0&&qt==="chat"){A(!0);return}if(t){o(!1);return}if(fo||gt)Lr?(sc(),Ga(),Pr(!1),Vn&&clearTimeout(Vn)):(Pr(!0),Vn&&clearTimeout(Vn),ya(setTimeout(()=>Pr(!1),3e3)));else if(qt==="revert")J("chat"),zn(0);else if(qt!=="chat"&&qt!=="settings")J("chat");else{if(!ze&&ee===1){Me(0),nn("");return}zn(v=>{let F=v+1;return F===1?(Ko.current&&clearTimeout(Ko.current),Ko.current=setTimeout(()=>zn(0),2e3)):F===2&&(Ko.current&&clearTimeout(Ko.current),zn(0),i.length>0?u(""):nt.getChatHistory(je).then(C=>{C.length>0?(Go(C.reverse()),J("revert")):U(_=>(z(_.length+1),[..._,{id:"revert-empty-"+Date.now(),role:"system",text:"\u{1F6C8} Nothing to revert to.",isMeta:!0}]))})),F})}}if(Lt.length>0&&qt==="chat"){if(g.upArrow){w(v=>v>0?v-1:Lt.length-1);return}if(g.downArrow){w(v=>v<Lt.length-1?v+1:0);return}if(g.return)return}if(g.tab,g.ctrl&&x==="c"&&qt!=="exit"){if(i.length>0){u("");return}if(g.shift){J("exit"),o(!1);return}t?(J("exit"),o(!1)):o(!0)}g.return&&(g.shift||g.ctrl||g.meta||g.leftAlt||g.rightAlt)&&u(v=>v.replace(/\\\r?$/,"").replace(/\r?$/,"")+`
|
|
595
|
+
`)}}),no(()=>{process.stdout.write("\x1B[?1004h");let x=g=>{let v=g.toString();v.includes("\x1B[I")?(Vt(!0),ut.current=Date.now()):v.includes("\x1B[O")&&(Vt(!1),ut.current=Date.now())};return process.stdin.on("data",x),()=>{process.stdout.write("\x1B[?1004l"),process.stdin.off("data",x)}},[]),no(()=>{async function x(){try{let R=JSON.parse(uo.readFileSync(ir.join(process.cwd(),"package.json"),"utf8"));Vi(Uo||R.version||"2.0.0")}catch{Vi("2.0.0")}process.stdout.isTTY&&(process.stdout.write("\x1B]0;FluxFlow\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow\x07")),Cc()||(U(R=>(z(R.length+1),[...R,{id:"setup-"+Date.now(),role:"system",text:"[SYSTEM] Installing Required dependencies... (One-time setup)",isMeta:!0}])),await kc(),U(R=>(z(R.length+1),[...R,{id:"setup-done-"+Date.now(),role:"system",text:"[SYSTEM] All dependencies installed successfully.",isMeta:!0}])));let g=await hr();j.mode?h(j.mode):h(g.mode),j.thinking?Y(j.thinking):Y(g.thinkingLevel);let v=j.provider||g.aiProvider||"Google";ge(v);let F=g.apiTier||"Free";if(P.current=g.activeModel,j.model)Ee(j.model);else if(j.provider){let R="";F==="Free"?v==="Google"?R="gemma-4-31b-it":v==="DeepSeek"?R="deepseek-v4-flash":v==="OpenRouter"?R="google/gemma-4-31b-it:free":v==="NVIDIA"&&(R="moonshotai/kimi-k2.6"):v==="Google"?R="gemini-3-flash-preview":v==="DeepSeek"?R="deepseek-v4-flash":v==="OpenRouter"?R="deepseek/deepseek-v4-flash":v==="NVIDIA"&&(R="moonshotai/kimi-k2.6"),Ee(R)}else Ee(g.activeModel);_t(g.showFullThinking),ro(g.apiTier||"Free"),Qr(g.quotas||{agentLimit:999999,backgroundLimit:999999,searchLimit:100,customModelId:"",customLimit:0});let C={memory:!0,compression:0,autoExec:!1,autoDeleteHistory:"7d",autoUpdate:!1,updateManager:"npm",customUpdateCommand:"",...g.systemSettings||{}};j.memory==="on"?C.memory=!0:j.memory==="off"&&(C.memory=!1),j.package&&(C.updateManager=j.package),j.autoDel&&(C.autoDeleteHistory=j.autoDel),j.autoExec==="on"?C.autoExec=!0:j.autoExec==="off"&&(C.autoExec=!1),j.externalAccess==="on"?C.allowExternalAccess=!0:j.externalAccess==="off"&&(C.allowExternalAccess=!1),lt(C),ar(g.profileData),$e(g.imageSettings||{keyType:"Default",quality:"Low-High",apiKey:""});let _=j.key;if(_||(_=await us(v)),_&&(ot(_),zr(_,{aiProvider:v,onIDEApproval:oe})),g.systemSettings?.autoDeleteHistory&&al(g.systemSettings.autoDeleteHistory),ll(To),G(!1,C),await fl(),await nt.recoverCrashedTransaction(),j.resume){let R=await _o(),b=j.resume;if(R[b]){rn(b);let L=await Is(b);zt.current=Tt-L.total,Se(L.total),Oe({tokens:L.context});let B=[...R[b].messages];B[0]?.text?.includes("\u2591\u2591\u2591\u2588\u2588\u2588")||B.unshift({id:"logo-"+Date.now(),role:"system",isLogo:!0,isMeta:!0}),U(B),J("chat"),U(ne=>{let Ne=[...ne,{id:"sys-"+Date.now(),role:"system",text:`SESSION RESUMED VIA CLI: [${b}]`,isMeta:!0}];return z(Ne.length),Ne})}else U(L=>[...L,{id:"sys-err-"+Date.now(),role:"system",text:`ERROR: Chat session [${b}] not found. Started new session.`,isMeta:!0}])}qe(!1)}x()},[]),no(()=>{let x;return t&&(r(10),x=setInterval(()=>{r(g=>g<=1?(o(!1),0):g-1)},1e3)),()=>{x&&clearInterval(x)}},[t]),no(()=>{if(!Ye){let x=j.model&&Ve===j.model?P.current:Ve;Dn({mode:d,thinkingLevel:q,aiProvider:N,activeModel:x||Ve,showFullThinking:Xe,systemSettings:Nt,profileData:wn,imageSettings:se,apiTier:Mt})}},[d,q,N,Ve,Xe,Nt,wn,se,Ye,j,Mt]);let mr=async x=>{let g=x.trim(),v=38;if(N==="OpenRouter"&&(v=30),N==="DeepSeek"&&(v=30),N==="NVIDIA"&&(v=30),g.length>=v){await ds(N,g),ot(g),zr(g,{aiProvider:N,onIDEApproval:oe});let F="gemma-4-31b-it";N==="OpenRouter"?F="google/gemma-4-31b-it:free":N==="DeepSeek"?F="deepseek-v4-flash":N==="NVIDIA"&&(F="moonshotai/kimi-k2.6"),Ee(F),U(C=>[...C,{role:"system",text:`${N} API Key saved successfully! Model set to ${F}. Initialization complete.`,isMeta:!0}])}else U(F=>[...F,{role:"system",text:`INVALID KEY: ${N} API keys must be at least ${v} characters.`,isMeta:!0}]),nn("")},bn=bo(pa);no(()=>{if(qt==="exit"){(async()=>{let v=Date.now(),F=Math.floor((v-bn.current)/1e3);F>=1&&(await Eo("duration",F),bn.current+=F*1e3),await hl()})();let g=setTimeout(()=>{process.exit(0)},1700);return()=>clearTimeout(g)}},[qt]),no(()=>{let x=setInterval(async()=>{if(!Ye){let g=Date.now(),v=Math.floor((g-bn.current)/1e3);v>=1&&(await Eo("duration",v),bn.current+=v*1e3)}},1500);return()=>clearInterval(x)},[Ye]);let Fr=[{cmd:"/quit",desc:"Exit and shutdown Flux"},{cmd:"/help",desc:"Show all available commands"},{cmd:"/compress",desc:"Summarize and compress chat history"},{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:"High",desc:"Extended Reasoning"}]:N==="NVIDIA"?[{cmd:"Fast",desc:"Reasoning Disabled"},{cmd:"Standard",desc:"Balanced Reasoning"},{cmd:"High",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"}]:Ve&&Ve.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"?Mt==="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"},{cmd:"google/gemma-4-31b-it",desc:""},{cmd:"stepfun-ai/step-3.7-flash",desc:""},{cmd:"minimaxai/minimax-m2.7",desc:""},{cmd:"deepseek-ai/deepseek-v4-flash",desc:""},{cmd:"deepseek-ai/deepseek-v4-pro",desc:""},{cmd:"mistralai/mistral-medium-3.5-128b",desc:""},{cmd:"z-ai/glm-5.1",desc:""},{cmd:"google/diffusiongemma-26b-a4b-it",desc:"Mega Fast [Experimental]"},{cmd:"minimaxai/minimax-m3",desc:""}]:Mt==="Free"?[{cmd:"gemma-4-26b-a4b-it",desc:"Standard & Faster"},{cmd:"gemma-4-31b-it",desc:"Standard Default"},{cmd:"gemini-2.5-flash-lite",desc:"Fast & Cheap (Limited Free Quota)"},{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-lite",desc:"Fast & Cheap"},{cmd:"gemini-2.5-flash",desc:"Fast & Reliable"},{cmd:"gemini-2.5-pro",desc:"Last gen Pro reasoning"},{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:"/docs",desc:"View Documentation"},{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"}]}],Vs=async(x,g=!1)=>{if(!g&&Lt.length>0){let C=Lt[T]||Lt[0],_=x.split(" ");if(_.length===1)u(C.cmd+" ");else{let R=_.slice(0,-1);u(R.join(" ")+" "+C.cmd+" ")}w(0),m(R=>R+1);return}let v=x.replace(/\r\n/g,`
|
|
596
596
|
`).replace(/\r/g,`
|
|
597
597
|
`).trimEnd();if(v.endsWith("\\")){u(v.slice(0,-1)+`
|
|
598
598
|
`);return}let F=v.replace(/\\\s*\n/g,`
|
|
599
599
|
`).split(/\r?\n/).map(C=>C.replace(/\\$/,"")).join(`
|
|
600
|
-
`);if(F.trim()){if(fo){let C=F.trim();if(C.startsWith("/")){U(_=>(z(_.length+1),[..._,{id:"hint-err-"+Date.now(),role:"system",text:"[RESTRICTED] Steering Hints cannot start with /",isMeta:!0}])),u("");return}
|
|
601
|
-
${C}`,color:"magenta"}])),u("");return}if(!ze){
|
|
600
|
+
`);if(F.trim()){if(fo){let C=F.trim();if(C.startsWith("/")){U(_=>(z(_.length+1),[..._,{id:"hint-err-"+Date.now(),role:"system",text:"[RESTRICTED] Steering Hints cannot start with /",isMeta:!0}])),u("");return}dr(C),ve.current=C,U(_=>(z(_.length+1),[..._,{id:"hint-"+Date.now(),role:"user",text:`[STEERING HINT: QUEUED]
|
|
601
|
+
${C}`,color:"magenta"}])),u("");return}if(!ze){mr(F),nn("");return}if(F.startsWith("/")){let C=F.split(" "),_=C[0]?.toLowerCase();switch(_){case"/quit":{J("exit");break}case"/resume":{if(C[1]){let b=C[1];(async()=>{let B=await _o(),V=B[b]||Object.values(B).find(ne=>ne.name.toLowerCase()===b.toLowerCase());if(V){s.write("\x1B[2J\x1B[3J\x1B[H"),rn(b);let ne=await Is(b);zt.current=Tt-ne.total,Se(ne.total),Oe({tokens:ne.context});let Ne=[...V.messages];Ne[0]?.text?.includes("\u2591\u2591\u2591\u2588\u2588\u2588")||Ne.unshift({id:"logo-"+Date.now(),role:"system",isLogo:!0,isMeta:!0}),U(Ne),U(le=>[...le,{id:"sys-"+Date.now(),role:"system",text:`SESSION RESUMED: [${b}]`,isMeta:!0}]),z(0)}else U(ne=>[...ne,{id:"err-"+Date.now(),role:"system",text:`ERROR: Session [${b}] not found.`}])})()}else J("resume");break}case"/clear":{U([{id:"logo-"+Date.now(),role:"system",isLogo:!0,isMeta:!0}]),z(1),rn(xi()),Oe({tokens:0}),a(!1),Se(0),zt.current=Tt;break}case"/revert":{nt.getChatHistory(je).then(b=>{if(b.length>0)Go(b.reverse()),J("revert");else{let L=Fe(2);U(B=>(z(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(C[1]){let b=C[1].toLowerCase()==="flow"?"Flow":"Flux";h(b),b==="Flow"?Y("Fast"):b==="Flux"&&Y("High");let L=Fe(2);U(B=>(z(B.length+1),[...B,{id:Date.now(),role:"system",text:`[SYSTEM] Mode switched to ${b}`,isMeta:!0}]))}else J("mode");break}case"/image":{if(C[1]?.toLowerCase()==="stats"){let b=Fe(2);if(se.keyType==="Custom")U(L=>(z(L.length+1),[...L,{id:Date.now(),role:"system",text:"[SYSTEM] Key strategy is Custom. Redirecting to Pollinations dashboard (https://enter.pollinations.ai/#pollen)...",isMeta:!0}])),Us("start https://enter.pollinations.ai/#pollen");else try{let L=await As();U(B=>(z(B.length+1),[...B,{id:Date.now(),role:"system",isImageStats:!0,text:`\u2022 Hourly Limit: ${Number((L.limit*1e3).toFixed(0))} credits
|
|
602
602
|
\u2022 Spent (Last 1hr): ${Number((L.totalSpent*1e3).toFixed(0))} credits
|
|
603
603
|
\u2022 Remaining: ${Number((L.remaining*1e3).toFixed(0))} credits
|
|
604
604
|
\u2022 Requests (Last 1hr): ${L.activeCallsCount} requests
|
|
605
|
-
`+(L.nextResetMin>0?`\u2022 Refreshes in: ${L.nextResetMin}m`:""),isMeta:!0}]))}catch{U(
|
|
606
|
-
`);try{uo.writeFileSync(L,ne,"utf8"),U(Ne=>(z(Ne.length+1),[...Ne,{id:Date.now(),role:"system",text:`[EXPORT] Chat exported to "${b}"`,isMeta:!0}]))}catch(Ne){U(de=>(z(de.length+1),[...de,{id:Date.now(),role:"system",text:`[EXPORT ERROR] Failed to export chat: ${Ne.message}`,isMeta:!0}]))}break}case"/chats":{(async()=>{let L=await _o(),
|
|
605
|
+
`+(L.nextResetMin>0?`\u2022 Refreshes in: ${L.nextResetMin}m`:""),isMeta:!0}]))}catch{U(B=>(z(B.length+1),[...B,{id:Date.now(),role:"system",text:"[SYSTEM] Failed to load image quota stats.",isMeta:!0}]))}}else if(C[1]?.toLowerCase()==="setup")if(C[2]?.toLowerCase()==="key")if(C[3]){let b=["default","custom"].find(L=>L===C[3].toLowerCase());if(b){let L=b==="default"?"Default":"Custom";$e(V=>({...V,keyType:L}));let B=Fe(2);U(V=>(z(V.length+1),[...V,{id:Date.now(),role:"system",text:`[SYSTEM] Image key strategy set to ${L}`,isMeta:!0}])),L==="Custom"&&(At({label:"Enter Pollinations API key (starting with sk_):",note:"Get a key from https://enter.pollinations.ai",key:"imageSettings",subKey:"apiKey",value:se.apiKey||"",returnView:"chat"}),J("input"))}else{let L=Fe(2);U(B=>(z(B.length+1),[...B,{id:Date.now(),role:"system",text:"[SYSTEM] Invalid key option. Choose: Default or Custom.",isMeta:!0}]))}}else{let b=Fe(2);U(L=>(z(L.length+1),[...L,{id:Date.now(),role:"system",text:"[SYSTEM] Usage: /image setup Key <Default|Custom>",isMeta:!0}]))}else if(C[2]?.toLowerCase()==="quality")if(C[3]){let b=["low","low-high","medium","medium-high","high","ultra","premium"].find(L=>L===C[3].toLowerCase());if(b){let B={low:"Low","low-high":"Low-High",medium:"Medium","medium-high":"Medium-High",high:"High",ultra:"Ultra",premium:"Premium"}[b];$e(ne=>({...ne,quality:B}));let V=Fe(2);U(ne=>(z(ne.length+1),[...ne,{id:Date.now(),role:"system",text:`[SYSTEM] Image quality set to ${B}`,isMeta:!0}]))}else{let L=Fe(2);U(B=>(z(B.length+1),[...B,{id:Date.now(),role:"system",text:"[SYSTEM] Invalid quality level. Choose from: Low, Low-High, Medium, Medium-High, High, Ultra, Premium.",isMeta:!0}]))}}else{let b=Fe(2);U(L=>(z(L.length+1),[...L,{id:Date.now(),role:"system",text:"[SYSTEM] Usage: /image setup Quality <Low|Low-High|Medium|Medium-High|High|Ultra>",isMeta:!0}]))}else{let b=Fe(2);U(L=>(z(L.length+1),[...L,{id:Date.now(),role:"system",text:"[SYSTEM] Usage: /image setup <Key|Quality> ...",isMeta:!0}]))}else{let b=Fe(2);U(L=>(z(L.length+1),[...L,{id:Date.now(),role:"system",text:"[SYSTEM] Usage: /image setup <Key|Quality> ...",isMeta:!0}]))}break}case"/thinking":{let b;if(C[1]){let L=C[1].toLowerCase(),B=C.includes("--bypass");if(b=L.charAt(0).toUpperCase()+L.slice(1),L==="xhigh"&&(b="xHigh"),!B&&d==="Flow"&&(b==="High"||b==="xHigh"))U(V=>(z(V.length+1),[...V,{id:Date.now(),role:"system",text:`[RESTRICTED] "${b}" is restricted in Flow mode. Switch to Flux to enable Higher Thinking Levels.`,isMeta:!0}]));else{Y(b);let V=Fe(1);U(ne=>(z(ne.length+1),[...ne,{id:Date.now(),role:"system",text:`[SYSTEM] Thinking level set to ${b}${B?" (Bypass Activated)":""}`,isMeta:!0}]))}}else J("thinking");break}case"/model":{if(C[1]){let b=C.slice(1).join(" ");if(b==="gemma-4-31b-it"&&Mt!=="Free"&&N==="Google")U(L=>(z(L.length+1),[...L,{id:Date.now(),role:"system",text:"**[ACCESS DENIED]** Gemma is restricted to the Free API tier. Automatically switching you to **Gemini 3 Flash Preview** for optimal performance.",isMeta:!0}])),Ee("gemini-3-flash-preview");else{Ee(b);let L=Fe(2);U(B=>(z(B.length+1),[...B,{id:Date.now(),role:"system",text:`[SYSTEM] Model switched to ${b}`,isMeta:!0}]))}}else J("model");break}case"/settings":{J("settings");break}case"/key":{J("key");break}case"/profile":{J("profile");break}case"/stats":{(async()=>{let L=await $n();be(L),J("stats")})();break}case"/save":{let b=C.slice(1).join(" ")||`Session ${new Date().toLocaleTimeString()}`;ks(je,b,_e),U(L=>(z(L.length+1),[...L,{id:Date.now(),role:"system",text:`[MEMORY] Chat saved as "${b}" (ID: ${je})`,isMeta:!0}]));break}case"/export":{let b=`export-fluxflow-${je}.txt`,L=ir.join(process.cwd(),b),B=[],V=!1;for(let Ne=0;Ne<_e.length;Ne++){let de=_e[Ne];if(de&&!(de.role==="system"||de.isMeta||de.isLogo||String(de.id).startsWith("welcome"))){if(de.role==="user"){let le=de.text||"";le=le.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),B.length>0&&B.push(""),B.push("[USER]"),B.push(le),V=!1}else if(de.role==="think"){V||(B.push(""),B.push("[AGENT]"),V=!0);let le=(de.text||"").replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/gi,"").replace(/\[\[TOOL RESULTS\]\]/gi,"").replace(/\[TOOL RESULTS\]/gi,"").replace(/\[TOOL RESULT\]/gi,"").trim();le&&(B.push("[thoughts]"),B.push(le))}else if(de.role==="agent"){V||(B.push(""),B.push("[AGENT]"),V=!0);let le=Id(de.text||"");for(let fe of le)if(fe.type==="output"){let he=fe.content.replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/gi,"").replace(/\[\[TOOL RESULTS\]\]/gi,"").replace(/\[TOOL RESULTS\]/gi,"").replace(/\[TOOL RESULT\]/gi,"").trim();he&&(B.push("[output]"),B.push(he))}else fe.type==="tool"&&(B.push("[tool]"),B.push(`${fe.toolName} ${fe.args}`))}}}let ne=B.join(`
|
|
606
|
+
`);try{uo.writeFileSync(L,ne,"utf8"),U(Ne=>(z(Ne.length+1),[...Ne,{id:Date.now(),role:"system",text:`[EXPORT] Chat exported to "${b}"`,isMeta:!0}]))}catch(Ne){U(de=>(z(de.length+1),[...de,{id:Date.now(),role:"system",text:`[EXPORT ERROR] Failed to export chat: ${Ne.message}`,isMeta:!0}]))}break}case"/chats":{(async()=>{let L=await _o(),B=Object.entries(L).map(([V,ne])=>`\u2022 ${V}: ${ne.name}`).join(`
|
|
607
607
|
`);U(V=>(z(V.length+1),[...V,{id:Date.now(),role:"system",text:`[HISTORY] Saved Chats:
|
|
608
|
-
${
|
|
609
|
-
\u2022 Status: ${
|
|
610
|
-
\u2022 Released on: ${Cd}`;U(
|
|
608
|
+
${B||"No saved chats found."}`,isMeta:!0}]))})();break}case"/memory":{J("memory");break}case"/reset":{(async()=>{try{U(L=>(z(L.length+1),[...L,{id:Date.now(),role:"system",text:"[NUCLEAR] Initiating reset...",isMeta:!0}])),uo.existsSync(To)&&uo.removeSync(To),uo.existsSync(bt)&&uo.removeSync(bt),uo.existsSync(lo)&&uo.removeSync(lo);try{uo.readdirSync(Zn).length===0&&uo.removeSync(Zn)}catch{}setTimeout(()=>{J("exit"),setTimeout(()=>process.exit(0),500)},500)}catch(L){U(B=>(z(B.length+1),[...B,{id:Date.now(),role:"system",text:`[RESET ERROR] Failed to purge data: ${L.message}`}]))}})();break}case"/about":{let b=Fe(2),L=`\u2022 FluxFlow Version: v${Uo}
|
|
609
|
+
\u2022 Status: ${ce&&ce!==Uo?`Update Available [v${ce}]`:"Up to date"}
|
|
610
|
+
\u2022 Released on: ${Cd}`;U(B=>(z(B.length+1),[...B,{id:"about-"+Date.now(),role:"system",text:L,isAboutRecord:!0,isMeta:!0}]));break}case"/changelog":{let b=process.platform;Us(`${b==="win32"?"start":b==="darwin"?"open":"xdg-open"} ${vc}`),U(B=>(z(B.length+1),[...B,{id:Date.now(),role:"system",text:`[BROWSER] Opening changelog: ${vc}`,isMeta:!0}]));break}case"/docs":{if(!ga){U(B=>(z(B.length+1),[...B,{id:Date.now(),role:"system",text:"[BROWSER] Documentation URL is not configured.",isMeta:!0}]));break}let b=process.platform;Us(`${b==="win32"?"start":b==="darwin"?"open":"xdg-open"} ${ga}`),U(B=>(z(B.length+1),[...B,{id:Date.now(),role:"system",text:`[BROWSER] Opening documentation: ${ga}`,isMeta:!0}]));break}case"/fluxflow":{if(C.slice(1)[0]==="init"){let L=`# FluxFlow Configuration
|
|
611
611
|
# This file defines project-specific instructions for the Flux Flow Agent.
|
|
612
612
|
|
|
613
613
|
# IDENTITY & TONE
|
|
@@ -622,24 +622,24 @@ ${R||"No saved chats found."}`,isMeta:!0}]))})();break}case"/memory":{J("memory"
|
|
|
622
622
|
|
|
623
623
|
# SKILLS & WORKFLOWS
|
|
624
624
|
- [Define custom step-by-step recipes for this project here]
|
|
625
|
-
`,
|
|
625
|
+
`,B=ir.join(process.cwd(),"FluxFlow.md");if(uo.pathExistsSync(B))U(V=>(z(V.length+1),[...V,{id:"init-err-"+Date.now(),role:"system",text:"ERROR: FluxFlow.md already exists in this directory.",isMeta:!0}]));else try{uo.writeFileSync(B,L),U(V=>(z(V.length+1),[...V,{id:"init-ok-"+Date.now(),role:"system",text:"[SUCCESS] FluxFlow.md has been initialized. You can now customize it for this project.",isMeta:!0}]))}catch(V){U(ne=>(z(ne.length+1),[...ne,{id:"init-err-"+Date.now(),role:"system",text:`ERROR: Failed to initialize FluxFlow.md: ${V.message}`,isMeta:!0}]))}}else U(L=>(z(L.length+1),[...L,{id:"ff-err-"+Date.now(),role:"system",text:"Usage: /fluxflow init",isMeta:!0}]));break}case"/update":{if(C[1]?.toLowerCase()==="check"){G(!0);break}let L=C.includes("--latest");J("update");break}case"/gemini":{let b=ma[Math.floor(Math.random()*ma.length)];U(L=>(z(L.length+1),[...L,{id:Date.now(),role:"system",text:`\u2728 [GEMINI CLI] ${b}`}])),u("");break}case"/compress":{u("");let b=_e.filter(V=>(V.role==="user"||V.role==="agent"||V.role==="system")&&!String(V.id).startsWith("welcome")&&!V.isMeta).length,L=Ke?.tokens||0;if(b<100||L<32768){let V=Fe(2);U(ne=>(z(ne.length+1),[...ne,{id:Date.now(),role:"system",text:`[SYSTEM] Compression skipped: History requires at least 100 messages and 32k tokens (current: ${b}/100 msgs, ${L}/32768 tokens).`,isMeta:!0}]));break}(async()=>{os(!0);let V=Fe(2);U(ne=>(z(ne.length+1),[...ne,{id:Date.now(),role:"system",text:"[SYSTEM] Compressing session history...",isMeta:!0}]));try{if(await ia({chatId:je,aiProvider:N,apiKey:ze,thinkingLevel:q,mode:d,janitorModel:ht,systemSettings:Nt,sessionStats:Ke},_e)){let de=Fe(2);U(le=>{let fe=[...le,{id:Date.now(),role:"system",text:"[SYSTEM] Chat History compressed saving tokens.",isMeta:!0}];return z(fe.length),fe})}else U(de=>(z(de.length+1),[...de,{id:Date.now(),role:"system",text:"[SYSTEM] Compression failed (no summary returned).",isMeta:!0}]))}catch(ne){U(Ne=>(z(Ne.length+1),[...Ne,{id:Date.now(),role:"system",text:`[SYSTEM] Error during compression: ${ne.message}`,isMeta:!0}]))}finally{os(!1)}})();break}case"/help":{U(b=>(z(b.length+1),[...b,{id:Date.now(),role:"system",isHelpRecord:!0,isMeta:!0}]));break}default:let R=Fe(2);U(b=>(z(b.length+1),[...b,{id:Date.now(),role:"system",text:`[SYSTEM] Unknown command: ${_}`,isMeta:!0}]))}}else{let C=`[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:`${F}
|
|
626
626
|
|
|
627
|
-
${C}`};U(b=>(z(b.length+1),[...b,_])),(async()=>{let b=!1;
|
|
627
|
+
${C}`};U(b=>(z(b.length+1),[...b,_])),(async()=>{let b=!1;Or(!0),a(!1);let L=Date.now(),B=!0;try{let V=[..._e,_].filter(K=>K.role!=="think"&&!K.isVisualFeedback&&!K.isMeta&&!String(K.id).startsWith("welcome")),ne=[];V.forEach((K,we)=>{let ye=K.fullText||K.text;if(K.role==="user"&&we<V.length-1)if(ye.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")){let Le=ye.indexOf("[SYSTEM METADATA (PRIORITY: DYNAMIC)]");Le!==-1&&(ye=ye.substring(Le).trim())}else{let Le=ye.lastIndexOf("[USER]");Le!==-1&&(ye=ye.substring(Le+6).trim())}if(K.role==="system"&&ye?.startsWith("[TOOL RESULT]")){let Le=ne[ne.length-1];if(Le&&Le.role==="system"&&Le.text?.startsWith("[TOOL RESULT]")){Le.text+=`
|
|
628
628
|
|
|
629
|
-
`+
|
|
630
|
-
COMMAND: ${
|
|
629
|
+
`+ye;return}}ne.push({...K,text:ye})});let Ne=cc(Ve,ne,{profile:wn,thinkingLevel:q,mode:d,systemSettings:Nt,janitorModel:ht,sessionStats:Ke,chatId:je,aiProvider:N,apiKey:ze,apiTier:Mt,cols:p.columns-6,rows:30,onExecStart:K=>{sn(K),Dt("")},onExecChunk:K=>{Dt(we=>we+K)},onExecEnd:()=>{U(K=>{if(!vr.current)return K;let we=es.current||"",ye=Hr(we),Le=`[TERMINAL_RECORD]
|
|
630
|
+
COMMAND: ${vr.current}
|
|
631
631
|
PTY: ${Po}
|
|
632
|
-
OUTPUT: ${
|
|
633
|
-
|
|
634
|
-
`)}`;return[...K,{id:"term-"+Date.now(),role:"system",text:Le,isTerminalRecord:!0}]}),sn(null),Ot(!1),Dt("")},onToolResult:(K,we)=>{if(K==="success"){if(
|
|
635
|
-
Selection: ${Le}`,isAskRecord:!0}]),
|
|
636
|
-
`),Ie=0,Ue=0,st=!1;for(let Ge of ke){if(Ge.includes("[DIFF_START]")){st=!0;continue}if(Ge.includes("[DIFF_END]")){st=!1;continue}st&&(/^\+\d+/.test(Ge)?Ie++:/^\-\d+/.test(Ge)&&Ue++)}
|
|
637
|
-
`),Ge=!1;for(let Ze of st){if(Ze.includes("Old File contents:")){Ge=!0;continue}Ge&&(Ze.trim()===""?Ge=!1:/^\d+ \|/.test(Ze)&&Ue++)}}Wr+=Ie,Yr+=Ue,Eo("linesAdded",Ie),Eo("linesRemoved",Ue)}continue}let we=K.content,ge=we.toLowerCase();if(we.includes("```")&&(ye=!ye),ge.includes("tool:functions.")&&(Re=!0,wo=0,dt=null,we.includes("[tool:functions.")&&(wo=0)),Re){for(let ke=0;ke<we.length;ke++){let Ie=we[ke];!dt&&(Ie==="'"||Ie==='"'||Ie==="`")?dt=Ie:dt&&Ie===dt&&we[ke-1]!=="\\"&&(dt=null),dt||(Ie==="("||Ie==="["?wo++:(Ie===")"||Ie==="]")&&wo--)}wo<=0&&!dt&&(Re=!1)}if((ge.includes("<think")||ge.includes("<thought"))&&(!de&&!ye&&!Re&&!Be)&&(de=!0,Be=!0,we=we.replace(/<(think|thought)>[\s\S]*?<\/(think|thought)>/gi,"").replace(/<(think|thought)>/gi,""),ce="think-"+Date.now(),U(ke=>[...ke,{id:ce,role:"think",text:"",isStreaming:!0,startTime:Date.now()}])),(ge.includes("</think>")||ge.includes("</thought>"))&&ce){let ke=we.split(/<\/(think|thought)>/gi),Ie=ke[0]||"",Ue=ke.slice(2).join("").replace(/<\/?(think|thought)>/gi,"");U(st=>{let Ge=st.map(Ze=>{if(Ze.id===ce&&typeof Ze.id=="string"){let Xo=Ze.startTime||parseInt(Ze.id.split("-")[1])||Date.now(),Cn=Date.now()-Xo;return{...Ze,text:Ze.text+Ie,isStreaming:!1,duration:Cn}}return Ze});return de=!1,xe="agent-"+Date.now(),[...Ge,{id:xe,role:"agent",text:Ue,isStreaming:!0}]});continue}if(de&&ce)U(ke=>{let Ie=!1,Ue="",st=ke.map(Ge=>{if(Ge.id===ce){let Ze=Ge.text+we;if(Ze.toLowerCase().includes("</think>")){Ie=!0;let Xo=Ze.split(/<\/think>/gi);Ue=Xo.slice(1).join("</think>")||"";let Cn=Ge.startTime||parseInt(Ge.id.split("-")[1])||Date.now(),Qn=Date.now()-Cn;return{...Ge,text:Xo[0],isStreaming:!1,duration:Qn}}return{...Ge,text:Ze,isStreaming:!0}}return Ge});return Ie?(de=!1,xe="agent-"+Date.now(),[...st,{id:xe,role:"agent",text:Ue.replace(/<\/?(think|thought)>/gi,""),isStreaming:!0}]):st});else if(!de){let ke=we.toLowerCase();!Yt&&ke.includes("tool:functions.")&&(Yt=!0),xe?U(Ie=>Ie.map(Ue=>Ue.id===xe?{...Ue,text:Ue.text+we,isStreaming:!0}:Ue)):(xe="agent-"+Date.now(),U(Ie=>[...Ie,{id:xe,role:"agent",text:we,isStreaming:!0}]))}}let ao=Date.now();Ms(K=>K+(ao-L))}catch(V){U(ne=>(z(ne.length+1),[...ne,{id:"error-"+Date.now(),role:"system",text:`\u274C ERROR: ${V.message}`}]))}finally{if(Os(!1),pe(null),b||process.stdout.isTTY&&(process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")),ve.current){Qe(ve.current),ds(null);let V=ve.current;ve.current=null,U(ne=>{let Ne=[...ne],de=Ne.reverse().find(ce=>ce.text?.includes("[STEERING HINT: QUEUED]"));return de&&(de.text=de.text.replace("[STEERING HINT: QUEUED]","[STEERING HINT: FINISHED_TURN]")),Ne.reverse()}),J("resolution")}U(V=>{let ne=Date.now()-L,Ne=!1,de=[...V].reverse().map(xe=>{let ye=xe.isStreaming?{...xe,isStreaming:!1}:xe;return!Ne&&ye.role==="agent"&&(Ne=!0,ye={...ye,workedDuration:ne}),ye}).reverse(),ce=de.filter(xe=>!String(xe.id).startsWith("welcome")&&!xe.isMeta);return kr(je,null,ce),z(de.length),de})}})()}u(""),a(!1)}},Lt=Js(()=>{if(i.startsWith("/")&&!E){let v=i.split(" "),F=v[v.length-1].toLowerCase();if(v.length===1){let _=F.startsWith("/")?F.slice(1):F;return Fs.filter(B=>(B.cmd.startsWith("/")?B.cmd.slice(1):B.cmd).toLowerCase().includes(_))}let C=Fs;for(let _=0;_<v.length-1;_++){let B=v[_].toLowerCase(),b=C.find(L=>L.cmd.toLowerCase()===B);if(b&&b.subs)C=b.subs;else return[]}return C.filter(_=>_.cmd.toLowerCase().includes(F))}let x=i.split(" "),g=x[x.length-1];if(g&&g.startsWith("@")&&!E){let v=g.indexOf("#"),F=v!==-1,C=F?g.substring(1,v).toLowerCase():g.slice(1).toLowerCase(),_=F?g.substring(v):"";return Md(process.cwd()).filter(L=>L.name.toLowerCase().includes(C)).map(L=>{let R=L.relativePath.replace(/\\/g,"/");return{cmd:"@["+(R.startsWith(".")?R:"./"+R)+_+"]",desc:L.relativePath}})}return[]},[i,E]);no(()=>{w(0)},[Lt]);let nr=()=>{switch(qt){case"settings":return l.createElement(ui,{systemSettings:Nt,setSystemSettings:at,apiTier:Mt,setActiveView:J,setInputConfig:At,saveSettings:Dn,quotas:ro,setMessages:U,aiProvider:N});case"selectProvider":return l.createElement(go,{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 (Free/Paid)",value:"NVIDIA"},{label:"Back",value:"settings"}],onSelect:async x=>{if(x.value==="settings"||x.value==="Back"){J("settings");return}let g=x.value,v=await ur(g);if(v){he(g),ot(v),zs(v,{aiProvider:g,onIDEApproval:oe});let F="gemma-4-31b-it";g==="OpenRouter"?F="google/gemma-4-31b-it:free":g==="DeepSeek"?F="deepseek-v4-flash":g==="NVIDIA"&&(F="moonshotai/kimi-k2.6"),Ee(F),Dn({aiProvider:g,activeModel:F,apiTier:Mt,quotas:ro}),U(C=>[...C,{role:"system",text:`\u2705 Switched to ${g}! Key loaded from Vault. Model set to ${F}.`,isMeta:!0}]),J("settings")}else At({label:`Enter ${g} API Key:`,key:"providerKey",provider:g,value:"",returnView:"settings"}),J("input")},onClose:()=>J("settings")});case"apiTier":return l.createElement(go,{title:l.createElement(S,null,"SELECT YOUR CURRENT API TIER BASED ON ",l.createElement(S,{color:"cyan",underline:!0,bold:!0},"\x1B]8;;https://aistudio.google.com/projects\x07AI STUDIO\x1B]8;;\x07"),". (CURRENT: ",Mt.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"){J("settings");return}let g=x.value;so(g),g==="Paid"?(At({label:"Enter Agent daily budget (requests made):",key:"quotas",subKey:"agentLimit",value:String(ro.agentLimit)}),J("input")):(Dn({apiTier:g,quotas:ro}),J("settings"))},onClose:()=>J("settings")});case"input":return l.createElement(I,{flexDirection:"column",borderStyle:"round",borderColor:"white",padding:0,width:"100%"},l.createElement(I,{paddingX:1},l.createElement(S,{color:"white",bold:!0},"DATA CONFIGURATION")),Wo?.note&&l.createElement(I,{paddingX:1,marginBottom:1},l.createElement(S,{color:"gray",italic:!0},Wo.note)),l.createElement(I,{paddingX:1,flexDirection:"row"},l.createElement(S,{color:"white",bold:!0},Wo?.label," "),l.createElement(Ac,{value:Wo?.value||"",onChange:x=>At(g=>({...g,value:x})),onSubmit:async x=>{let{key:g,subKey:v,next:F}=Wo,C={...ro},_={};if(g==="quotas"){let B=v.toLowerCase().includes("limit")?parseInt(x)||0:x;C[v]=B,Qs(C),_.quotas=C}else if(g==="activeModel")Ee(x),_.activeModel=x;else if(g==="janitorModel")et(x),_.janitorModel=x;else if(g==="autoApproveCommands"||g==="autoDisallowCommands"||g==="alwaysAskCommands"){let B={...Nt,[g]:x.trim(),sandboxPreset:"Custom"};at(B),_.systemSettings=B}else if(g==="externalDataPath"){let B={...Nt,useExternalData:!0,externalDataPath:x.trim()};at(B),_.systemSettings=B,U(b=>[...b,{id:Date.now(),role:"system",text:"[EXTERNAL STORAGE] Flux Flow will use "+x.trim()+" for data after restart."}])}else if(g==="imageSettings"){let B=x.trim();if(B.startsWith("sk_")){let b={...re,apiKey:B};$e(b),_.imageSettings=b,U(L=>(z(L.length+1),[...L,{id:Date.now(),role:"system",text:"[IMAGE KEY] Custom API key saved successfully.",isMeta:!0}]))}else $e(b=>({...b,keyType:"Default"})),_.imageSettings={...re,keyType:"Default"},U(b=>(z(b.length+1),[...b,{id:Date.now(),role:"system",text:"[IMAGE KEY ERROR] API key must start with sk_. Key strategy reset to Default.",isMeta:!0}]))}else if(g==="providerKey"){let B=x.trim(),b=Wo.provider;await dr(b,B),he(b),ot(B),zs(B,{aiProvider:b,onIDEApproval:oe});let L="gemma-4-31b-it";b==="OpenRouter"?L="google/gemma-4-31b-it:free":b==="DeepSeek"?L="deepseek-v4-flash":b==="NVIDIA"&&(L="moonshotai/kimi-k2.6"),Ee(L),_.aiProvider=b,_.activeModel=L,U(R=>(z(R.length+1),[...R,{id:Date.now(),role:"system",text:`\u2705 ${b} API Key saved successfully! Model set to ${L}.`,isMeta:!0}]))}F?At(F(g==="quotas"?C:x)):(Dn({..._,apiTier:Mt,quotas:C,imageSettings:_.imageSettings||re}),At(null),J(Wo?.returnView||"settings"))}})),l.createElement(I,{paddingX:1,marginTop:1},l.createElement(S,{color:"gray",dimColor:!0,italic:!0},"(Press Enter to confirm selection)")));case"stats":return l.createElement(I,{flexDirection:"column",borderStyle:"round",borderColor:"grey",paddingX:3,paddingY:1,width:Math.min(100,(r?.columns||100)-2)},l.createElement(I,{marginBottom:1},l.createElement(S,{color:"white",bold:!0,underline:!0},"SESSION TELEMETRY")),l.createElement(I,{flexDirection:"column"},l.createElement(I,null,l.createElement(I,{width:25},l.createElement(S,{color:"blue"},"Session Duration:")),l.createElement(S,{color:"white"},ie(Date.now()-pa))),l.createElement(I,null,l.createElement(I,{width:25},l.createElement(S,{color:"blue"},"Agent Interactions:")),l.createElement(S,{color:"white"},Je)),l.createElement(I,{marginLeft:2},l.createElement(I,{width:23},l.createElement(S,{color:"grey"},"\xBB API Time:")),l.createElement(S,{color:"white"},ie(Is))),l.createElement(I,{marginLeft:2},l.createElement(I,{width:23},l.createElement(S,{color:"grey"},"\xBB Tool Time:")),l.createElement(S,{color:"white"},ie(ls))),l.createElement(I,null,l.createElement(I,{width:25},l.createElement(S,{color:"blue"},"Background Tasks:")),l.createElement(S,{color:"white"},Et)),l.createElement(I,null,l.createElement(I,{width:25},l.createElement(S,{color:"blue"},"Tokens Consumed:")),l.createElement(S,{color:"white"},eo(Tt))),l.createElement(I,null,l.createElement(I,{width:25},l.createElement(S,{color:"blue"},"Active Context:")),l.createElement(S,{color:"white"},eo(Ke.tokens))),Tt>0&&l.createElement(l.Fragment,null,l.createElement(I,{marginLeft:2},l.createElement(I,{width:23},l.createElement(S,{color:"grey"},"\xBB Input Tokens:")),l.createElement(S,{color:"white"},eo(Tt-Bt))),vt>0&&l.createElement(I,{marginLeft:4},l.createElement(I,{width:21},l.createElement(S,{color:"grey"},"\xBB Cached:")),l.createElement(S,{color:"white"},eo(vt))),Bt>0&&l.createElement(I,{marginLeft:2},l.createElement(I,{width:23},l.createElement(S,{color:"grey"},"\xBB Output Tokens:")),l.createElement(S,{color:"white"},eo(Bt)))),As>0&&l.createElement(l.Fragment,null,l.createElement(I,null,l.createElement(I,{width:25},l.createElement(S,{color:"blue"},"Images Made:")),l.createElement(S,{color:"white"},As)),l.createElement(I,null,l.createElement(I,{width:25},l.createElement(S,{color:"blue"},"Image Credits:")),l.createElement(S,{color:"white"},Number(((Hn||0)*1e3).toFixed(0))," credits"))),l.createElement(I,null,l.createElement(I,{width:25},l.createElement(S,{color:"blue"},"Code Changes (Sess):")),l.createElement(S,{color:"white"},l.createElement(S,{color:"green"},"+",Wr)," ",l.createElement(S,{color:"red"},"-",Yr))),l.createElement(I,null,l.createElement(I,{width:25},l.createElement(S,{color:"blue"},"Tool Calls (Sess):")),l.createElement(S,{color:"white"},ht+Jt+jo," ( "),l.createElement(S,{color:"green"},"\u2713 ",ht),l.createElement(S,{color:"white"}," "),l.createElement(S,{color:"yellow"},"\u2298 ",jo),l.createElement(S,{color:"white"}," "),l.createElement(S,{color:"red"},"\u2715 ",Jt),l.createElement(S,{color:"white"}," )"))),l.createElement(I,{flexDirection:"column",marginTop:1},l.createElement(S,{color:"white",bold:!0,underline:!0},"DAILY USAGE TRACKER"),l.createElement(I,{marginTop:1},l.createElement(I,{width:25},l.createElement(S,{color:"blue"},"Wall Time Today:")),l.createElement(S,{color:"white"},Ce(me?.duration||0))),l.createElement(I,null,l.createElement(I,{width:25},l.createElement(S,{color:"blue"},"Agent Interactions:")),l.createElement(S,{color:"white"},me?.agent||0)),l.createElement(I,null,l.createElement(I,{width:25},l.createElement(S,{color:"blue"},"Background Tasks:")),l.createElement(S,{color:"white"},me?.background||0)),l.createElement(I,null,l.createElement(I,{width:25},l.createElement(S,{color:"blue"},"Tokens Used Today:")),l.createElement(S,{color:"white"},eo(me?.tokens||0))),(me?.tokens||0)>0&&l.createElement(l.Fragment,null,l.createElement(I,{marginLeft:2},l.createElement(I,{width:23},l.createElement(S,{color:"grey"},"\xBB Input Tokens:")),l.createElement(S,{color:"white"},eo((me?.tokens||0)-(me?.candidateTokens||0)))),(me?.cachedTokens||0)>0&&l.createElement(I,{marginLeft:4},l.createElement(I,{width:21},l.createElement(S,{color:"grey"},"\xBB Cached:")),l.createElement(S,{color:"white"},eo(me.cachedTokens))),(me?.candidateTokens||0)>0&&l.createElement(I,{marginLeft:2},l.createElement(I,{width:23},l.createElement(S,{color:"grey"},"\xBB Output Tokens:")),l.createElement(S,{color:"white"},eo(me.candidateTokens)))),(me?.imageCalls?.length||0)>0&&l.createElement(l.Fragment,null,l.createElement(I,null,l.createElement(I,{width:25},l.createElement(S,{color:"blue"},"Images Made Today:")),l.createElement(S,{color:"white"},me.imageCalls.length)),l.createElement(I,null,l.createElement(I,{width:25},l.createElement(S,{color:"blue"},"Image Credits Today:")),l.createElement(S,{color:"white"},Number(((me.imageCalls.reduce((x,g)=>x+g.cost,0)||0)*1e3).toFixed(0))," credits"))),l.createElement(I,null,l.createElement(I,{width:25},l.createElement(S,{color:"blue"},"Code Changes Today:")),l.createElement(S,{color:"white"},l.createElement(S,{color:"green"},"+",me?.linesAdded||0)," ",l.createElement(S,{color:"red"},"-",me?.linesRemoved||0))),l.createElement(I,null,l.createElement(I,{width:25},l.createElement(S,{color:"blue"},"Tool Calls Today:")),l.createElement(S,{color:"white"},(me?.toolSuccess||0)+(me?.toolFailure||0)+(me?.toolDenied||0)," ( "),l.createElement(S,{color:"green"},"\u2713 ",me?.toolSuccess||0),l.createElement(S,{color:"white"}," "),l.createElement(S,{color:"yellow"},"\u2298 ",me?.toolDenied||0),l.createElement(S,{color:"white"}," "),l.createElement(S,{color:"red"},"\u2715 ",me?.toolFailure||0),l.createElement(S,{color:"white"}," )"))),l.createElement(S,{dimColor:!0,marginTop:1,italic:!0},"(Press ESC to return to chat)"));case"autoExecDanger":return l.createElement(I,{flexDirection:"column",borderStyle:"round",borderColor:"grey",paddingX:2,paddingY:1,width:"100%"},l.createElement(S,{color:"white",bold:!0,underline:!0},"SECURITY WARNING: YOLO MODE"),l.createElement(S,{marginTop:1},"Turning this ON allows the agent to execute terminal commands automatically without requiring your approval for each step."),l.createElement(S,{marginTop:1,color:"white"},"RISKS INVOLVED:"),l.createElement(S,null,"\u2022 The agent may execute destructive commands (rm -rf, etc.) by mistake unless specified in sandbox rules."),l.createElement(S,null,"\u2022 Unintended system changes if the agent hallucinates a path or command."),l.createElement(S,null,"\u2022 Reduced control over the agent's step-by-step decision making."),l.createElement(I,{marginTop:1},l.createElement(go,{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"&&at(g=>({...g,autoExec:!0})),J("settings")}})));case"externalDanger":return l.createElement(I,{flexDirection:"column",borderStyle:"round",borderColor:"grey",paddingX:2,paddingY:1,width:"100%"},l.createElement(S,{color:"white",bold:!0,underline:!0},"SECURITY WARNING: EXTERNAL WORKSPACE ACCESS"),l.createElement(S,{marginTop:1},"Turning this ON allows the agent to execute tools (Read/Write/Exec) outside of the current active workspace directory."),l.createElement(S,{marginTop:1,color:"white"},"RISKS INVOLVED:"),l.createElement(S,null,"\u2022 Access to sensitive system files (SSH keys, Browser data, etc.)"),l.createElement(S,null,"\u2022 Potential for accidental or malicious deletion of OS-critical files."),l.createElement(S,null,"\u2022 Unauthorized script execution across your entire file system."),l.createElement(I,{marginTop:1},l.createElement(go,{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"&&at(g=>({...g,allowExternalAccess:!0})),J("settings")}})));case"doubleDanger":return l.createElement(I,{flexDirection:"column",borderStyle:"round",borderColor:"white",paddingX:2,paddingY:1,width:"100%"},l.createElement(S,{color:"white",bold:!0,underline:!0},"CRITICAL SECURITY WARNING: COMBINED SYSTEM RISK"),l.createElement(S,{marginTop:1},"You are attempting to enable BOTH [YOLO Mode] and [External Workspace Access] simultaneously."),l.createElement(S,{marginTop:1,color:"red",bold:!0},"THIS IS NOT RECOMMENDED."),l.createElement(S,{marginTop:1,color:"white"},"THE CRITICAL RISK:"),l.createElement(S,null,"The agent will have the power to execute any command across your entire system WITHOUT your approval or supervision."),l.createElement(S,{color:"red",italic:!0,marginTop:1},"A single hallucination or error could result in full system wipe or data theft."),l.createElement(I,{marginTop:1},l.createElement(go,{title:"Final Confirmation",items:[{label:"I agree knowing the consequences",value:"on"},{label:"Keep Off",value:"off"}],onSelect:x=>{x.value==="on"&&at(g=>({...g,autoExec:!0,allowExternalAccess:!0})),J("settings")}})));case"key":return l.createElement(go,{title:"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"){ot(null),J("chat");let g=Fe(2);U(v=>[...v,{id:Date.now(),role:"system",text:"[ACTION] Flux waiting for new API Key..."}])}else x.value==="remove"?J("deleteKey"):J("chat")}});case"deleteKey":return l.createElement(I,{flexDirection:"column",borderStyle:"round",borderColor:"grey",paddingX:2,paddingY:1},(()=>{let x=Fe(2);return l.createElement(S,{color:"white",bold:!0},"DANGER: PURGE API KEY")})(),l.createElement(S,{marginTop:1},"This will permanently delete the saved API key from the project vault. You will need to enter it again to use Flux."),l.createElement(I,{marginTop:1},l.createElement(go,{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 Jr(),ot(null),J("chat");let g=Fe(2);U(v=>[...v,{id:Date.now(),role:"system",text:"[VAULT PURGED] API Key removed successfully."}])}else J("key")}})));case"exit":return null;case"ask":return l.createElement(I,{width:"100%"},l.createElement(za,{question:us?.question,options:us?.options,onResolve:x=>{us?.resolve&&us.resolve(x),tr(null),J("chat")}}));case"revert":return l.createElement(I,{width:"100%",alignItems:"center",justifyContent:"center"},l.createElement(ha,{prompts:wa,onSelect:async x=>{try{let g=await yt.rollbackToBefore(x);if(g.success){let{targetPrompt:v}=g;lc(je);let F=_e.findLastIndex(b=>b.role==="user"&&b.text&&(b.text.startsWith(v)||b.text.includes(v))),C=[..._e];F!==-1&&(C=_e.slice(0,F)),U(C),z(C.length),u(v),a(v.split(`
|
|
638
|
-
`).length>2);let _=C.filter(b=>!String(b.id).startsWith("welcome")&&!b.isMeta);await
|
|
639
|
-
**Restart to see changes.**`,isMeta:!0}])),J("chat")},onUpdateSettings:x=>{J("updateManager")}});case"terminalApproval":return l.createElement(I,{flexDirection:"column",borderStyle:"round",borderColor:"white",paddingX:2,paddingY:1,width:"100%"},l.createElement(S,{color:"white",bold:!0,underline:!0},"TERMINAL COMMAND OVERSIGHT"),l.createElement(I,{marginTop:1},l.createElement(S,null,"Agent requested to run: ",l.createElement(S,{color:"yellow",bold:!0},
|
|
632
|
+
OUTPUT: ${ye.replace(/\n{3,}/g,`
|
|
633
|
+
|
|
634
|
+
`)}`;return[...K,{id:"term-"+Date.now(),role:"system",text:Le,isTerminalRecord:!0}]}),sn(null),Ot(!1),Dt("")},onToolResult:(K,we)=>{if(K==="success"){if(dt(ye=>ye+1),we==="generate_image"){Gs(jt=>jt+1);let Le={Low:.001,"Low-High":.002,Medium:.008,"Medium-High":.01,High:.045,Ultra:.0488,Premium:.1}[se.quality]||.002;Ks(jt=>jt+Le)}}else K==="denied"?Hs(ye=>ye+1):Rt(ye=>ye+1)},onToolApproval:async(K,we)=>{let ye=Xs||Nt.autoExec;if(K==="exec_command"){let{command:Le}=re(we||"{}");return ye||Le&&/^(echo|ls|dir|pwd|cd|git status|git log|git diff|type|cat|help)\b/i.test(Le.trim())?"allow":new Promise(ke=>{cr({tool:K,args:we,resolve:ke}),J("terminalApproval")})}return ye?"allow":new Promise(Le=>{cr({tool:K,args:we,resolve:Le}),J("approval")})},onAskUser:async(K,we)=>new Promise(ye=>{ts({question:K,options:we,resolve:Le=>{U(jt=>[...jt,{id:"ask-"+Date.now(),role:"system",text:`\u{1F4AC} **Ask User**
|
|
635
|
+
Selection: ${Le}`,isAskRecord:!0}]),ye(Le)}}),J("ask")})},async()=>{if(ve.current){let K=ve.current;return dr(null),ve.current=null,U(we=>{let ye=[...we].reverse().findIndex(Le=>Le.text?.includes("[STEERING HINT: QUEUED]"));if(ye!==-1){let Le=we.length-1-ye,jt=[...we];return jt[Le]={...jt[Le],text:jt[Le].text.replace("[STEERING HINT: QUEUED]","[STEERING HINT: INJECTED]"),color:"cyan"},jt}return we}),K}return null},Uo),de=!1,le=null,fe=null,he=!1,Be=!1,Re=!1,Yt=!1,wo=0,mt=null,ln=/\[?\s*turn\s*:\s*.*?\s*\]?/gi;for await(let K of Ne){if(B&&K.type==="text"&&(L=Date.now(),B=!1),K.type==="status"){xe(K.content),Zo()&&_s(K.content);continue}if(K.type==="status_history"){xe(K.content),Zo()&&_s(K.content),U(ke=>[...ke,{id:"condense-"+Date.now(),role:"system",text:`[SYSTEM] ${K.content}`,isMeta:!0}]);continue}if(K.type==="summary_injected"){U(ke=>ke.map(Ie=>Ie.id===K.content.id?{...Ie,fullText:K.content.text}:Ie));continue}if(K.type==="spinner"){En(K.content);continue}if(K.type==="model_update"){X(K.content);continue}if(K.type==="turn_reset"){le=null,fe=null,de=!1,he=!1,Be=!1,Yt=!1,Re=!1;continue}if(K.type==="interactive_turn_finished"){Or(!1),Zo()&&_s(null),b=!0,ic({profile:wn,thinkingLevel:q,mode:d,janitorModel:ht,chatId:je,systemSettings:Nt,sessionStats:Ke,aiProvider:N,apiKey:ze},K.data.agentText,K.data.fullAgentTextRaw,K.data.history,{onMemoryUpdated:()=>U(ke=>{let Ie=[...ke];return Ie.length>0&&(Ie[Ie.length-1].memoryUpdated=!0),Ie}),onBackgroundIncrement:()=>Yn(ke=>ke+1)});continue}if(K.type==="visual_feedback"){U(ke=>[...ke,{id:"feedback-"+Date.now(),role:"system",text:K.content,isVisualFeedback:!0}]);continue}if(K.type==="exec_start")continue;if(K.type==="liveTokens"){Oe({tokens:K.content});continue}if(K.type==="usage"){let ke=K.content.totalTokenCount||0,Ie=K.content.cachedContentTokenCount||0,Ue=K.content.candidatesTokenCount||0;Oe({tokens:ke}),Tn(st=>st+ke),Ie>0&&Yo(st=>st+Ie),Ue>0&&jn(st=>st+Ue),Te(st=>st+1);continue}if(K.type==="tool_time"){xa(ke=>ke+K.content);continue}if(K.type==="tool_result"){if(U(ke=>[...ke,{id:"tool-"+Date.now(),role:"system",text:K.content,fullText:K.aiContent,binaryPart:K.binaryPart,toolName:K.toolName}]),K.toolName==="update_file"&&K.aiContent){let ke=K.aiContent.split(`
|
|
636
|
+
`),Ie=0,Ue=0,st=!1;for(let Ge of ke){if(Ge.includes("[DIFF_START]")){st=!0;continue}if(Ge.includes("[DIFF_END]")){st=!1;continue}st&&(/^\+\d+/.test(Ge)?Ie++:/^\-\d+/.test(Ge)&&Ue++)}Ws+=Ie,Ys+=Ue,Eo("linesAdded",Ie),Eo("linesRemoved",Ue)}else if(K.toolName==="write_file"&&K.aiContent){let ke=K.aiContent.match(/- Stats: \[(\d+) lines/),Ie=ke?parseInt(ke[1]):0,Ue=0;if(K.aiContent.includes("Old File contents:")){let st=K.aiContent.split(`
|
|
637
|
+
`),Ge=!1;for(let Ze of st){if(Ze.includes("Old File contents:")){Ge=!0;continue}Ge&&(Ze.trim()===""?Ge=!1:/^\d+ \|/.test(Ze)&&Ue++)}}Ws+=Ie,Ys+=Ue,Eo("linesAdded",Ie),Eo("linesRemoved",Ue)}continue}let we=K.content,ye=we.toLowerCase();if(we.includes("```")&&(he=!he),ye.includes("tool:functions.")&&(Be=!0,wo=0,mt=null,we.includes("[tool:functions.")&&(wo=0)),Be){for(let ke=0;ke<we.length;ke++){let Ie=we[ke];!mt&&(Ie==="'"||Ie==='"'||Ie==="`")?mt=Ie:mt&&Ie===mt&&we[ke-1]!=="\\"&&(mt=null),mt||(Ie==="("||Ie==="["?wo++:(Ie===")"||Ie==="]")&&wo--)}wo<=0&&!mt&&(Be=!1)}if((ye.includes("<think")||ye.includes("<thought"))&&(!de&&!he&&!Be&&!Re)&&(de=!0,Re=!0,we=we.replace(/<(think|thought)>[\s\S]*?<\/(think|thought)>/gi,"").replace(/<(think|thought)>/gi,""),le="think-"+Date.now(),U(ke=>[...ke,{id:le,role:"think",text:"",isStreaming:!0,startTime:Date.now()}])),(ye.includes("</think>")||ye.includes("</thought>"))&&le){let ke=we.split(/<\/(think|thought)>/gi),Ie=ke[0]||"",Ue=ke.slice(2).join("").replace(/<\/?(think|thought)>/gi,"");U(st=>{let Ge=st.map(Ze=>{if(Ze.id===le&&typeof Ze.id=="string"){let Xo=Ze.startTime||parseInt(Ze.id.split("-")[1])||Date.now(),Cn=Date.now()-Xo;return{...Ze,text:Ze.text+Ie,isStreaming:!1,duration:Cn}}return Ze});return de=!1,fe="agent-"+Date.now(),[...Ge,{id:fe,role:"agent",text:Ue,isStreaming:!0}]});continue}if(de&&le)U(ke=>{let Ie=!1,Ue="",st=ke.map(Ge=>{if(Ge.id===le){let Ze=Ge.text+we;if(Ze.toLowerCase().includes("</think>")){Ie=!0;let Xo=Ze.split(/<\/think>/gi);Ue=Xo.slice(1).join("</think>")||"";let Cn=Ge.startTime||parseInt(Ge.id.split("-")[1])||Date.now(),Qn=Date.now()-Cn;return{...Ge,text:Xo[0],isStreaming:!1,duration:Qn}}return{...Ge,text:Ze,isStreaming:!0}}return Ge});return Ie?(de=!1,fe="agent-"+Date.now(),[...st,{id:fe,role:"agent",text:Ue.replace(/<\/?(think|thought)>/gi,""),isStreaming:!0}]):st});else if(!de){let ke=we.toLowerCase();!Yt&&ke.includes("tool:functions.")&&(Yt=!0),fe?U(Ie=>Ie.map(Ue=>Ue.id===fe?{...Ue,text:Ue.text+we,isStreaming:!0}:Ue)):(fe="agent-"+Date.now(),U(Ie=>[...Ie,{id:fe,role:"agent",text:we,isStreaming:!0}]))}}let ao=Date.now();Mr(K=>K+(ao-L))}catch(V){U(ne=>(z(ne.length+1),[...ne,{id:"error-"+Date.now(),role:"system",text:`\u274C ERROR: ${V.message}`}]))}finally{if(Or(!1),xe(null),b||process.stdout.isTTY&&(process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")),ve.current){Qe(ve.current),dr(null);let V=ve.current;ve.current=null,U(ne=>{let Ne=[...ne],de=Ne.reverse().find(le=>le.text?.includes("[STEERING HINT: QUEUED]"));return de&&(de.text=de.text.replace("[STEERING HINT: QUEUED]","[STEERING HINT: FINISHED_TURN]")),Ne.reverse()}),J("resolution")}U(V=>{let ne=Date.now()-L,Ne=!1,de=[...V].reverse().map(fe=>{let he=fe.isStreaming?{...fe,isStreaming:!1}:fe;return!Ne&&he.role==="agent"&&(Ne=!0,he={...he,workedDuration:ne}),he}).reverse(),le=de.filter(fe=>!String(fe.id).startsWith("welcome")&&!fe.isMeta);return ks(je,null,le),z(de.length),de})}})()}u(""),a(!1)}},Lt=Jr(()=>{if(i.startsWith("/")&&!E){let v=i.split(" "),F=v[v.length-1].toLowerCase();if(v.length===1){let _=F.startsWith("/")?F.slice(1):F;return Fr.filter(R=>(R.cmd.startsWith("/")?R.cmd.slice(1):R.cmd).toLowerCase().includes(_))}let C=Fr;for(let _=0;_<v.length-1;_++){let R=v[_].toLowerCase(),b=C.find(L=>L.cmd.toLowerCase()===R);if(b&&b.subs)C=b.subs;else return[]}return C.filter(_=>_.cmd.toLowerCase().includes(F))}let x=i.split(" "),g=x[x.length-1];if(g&&g.startsWith("@")&&!E){let v=g.indexOf("#"),F=v!==-1,C=F?g.substring(1,v).toLowerCase():g.slice(1).toLowerCase(),_=F?g.substring(v):"";return Md(process.cwd()).filter(L=>L.name.toLowerCase().includes(C)).map(L=>{let B=L.relativePath.replace(/\\/g,"/");return{cmd:"@["+(B.startsWith(".")?B:"./"+B)+_+"]",desc:L.relativePath}})}return[]},[i,E]);no(()=>{w(0)},[Lt]);let ns=()=>{switch(qt){case"settings":return l.createElement(ui,{systemSettings:Nt,setSystemSettings:lt,apiTier:Mt,setActiveView:J,setInputConfig:At,saveSettings:Dn,quotas:so,setMessages:U,aiProvider:N});case"selectProvider":return l.createElement(go,{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 (Free/Paid)",value:"NVIDIA"},{label:"Back",value:"settings"}],onSelect:async x=>{if(x.value==="settings"||x.value==="Back"){J("settings");return}let g=x.value,v=await us(g);if(v){ge(g),ot(v),zr(v,{aiProvider:g,onIDEApproval:oe});let F="gemma-4-31b-it";g==="OpenRouter"?F="google/gemma-4-31b-it:free":g==="DeepSeek"?F="deepseek-v4-flash":g==="NVIDIA"&&(F="moonshotai/kimi-k2.6"),Ee(F),Dn({aiProvider:g,activeModel:F,apiTier:Mt,quotas:so}),U(C=>[...C,{role:"system",text:`\u2705 Switched to ${g}! Key loaded from Vault. Model set to ${F}.`,isMeta:!0}]),J("settings")}else At({label:`Enter ${g} API Key:`,key:"providerKey",provider:g,value:"",returnView:"settings"}),J("input")},onClose:()=>J("settings")});case"apiTier":return l.createElement(go,{title:l.createElement(S,null,"SELECT YOUR CURRENT API TIER BASED ON ",l.createElement(S,{color:"cyan",underline:!0,bold:!0},"\x1B]8;;https://aistudio.google.com/projects\x07AI STUDIO\x1B]8;;\x07"),". (CURRENT: ",Mt.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"){J("settings");return}let g=x.value;ro(g),g==="Paid"?(At({label:"Enter Agent daily budget (requests made):",key:"quotas",subKey:"agentLimit",value:String(so.agentLimit)}),J("input")):(Dn({apiTier:g,quotas:so}),J("settings"))},onClose:()=>J("settings")});case"input":return l.createElement(I,{flexDirection:"column",borderStyle:"round",borderColor:"white",padding:0,width:"100%"},l.createElement(I,{paddingX:1},l.createElement(S,{color:"white",bold:!0},"DATA CONFIGURATION")),Wo?.note&&l.createElement(I,{paddingX:1,marginBottom:1},l.createElement(S,{color:"gray",italic:!0},Wo.note)),l.createElement(I,{paddingX:1,flexDirection:"row"},l.createElement(S,{color:"white",bold:!0},Wo?.label," "),l.createElement(Ac,{value:Wo?.value||"",onChange:x=>At(g=>({...g,value:x})),onSubmit:async x=>{let{key:g,subKey:v,next:F}=Wo,C={...so},_={};if(g==="quotas"){let R=v.toLowerCase().includes("limit")?parseInt(x)||0:x;C[v]=R,Qr(C),_.quotas=C}else if(g==="activeModel")Ee(x),_.activeModel=x;else if(g==="janitorModel")et(x),_.janitorModel=x;else if(g==="autoApproveCommands"||g==="autoDisallowCommands"||g==="alwaysAskCommands"){let R={...Nt,[g]:x.trim(),sandboxPreset:"Custom"};lt(R),_.systemSettings=R}else if(g==="externalDataPath"){let R={...Nt,useExternalData:!0,externalDataPath:x.trim()};lt(R),_.systemSettings=R,U(b=>[...b,{id:Date.now(),role:"system",text:"[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 b={...se,apiKey:R};$e(b),_.imageSettings=b,U(L=>(z(L.length+1),[...L,{id:Date.now(),role:"system",text:"[IMAGE KEY] Custom API key saved successfully.",isMeta:!0}]))}else $e(b=>({...b,keyType:"Default"})),_.imageSettings={...se,keyType:"Default"},U(b=>(z(b.length+1),[...b,{id:Date.now(),role:"system",text:"[IMAGE KEY ERROR] API key must start with sk_. Key strategy reset to Default.",isMeta:!0}]))}else if(g==="providerKey"){let R=x.trim(),b=Wo.provider;await ds(b,R),ge(b),ot(R),zr(R,{aiProvider:b,onIDEApproval:oe});let L="gemma-4-31b-it";b==="OpenRouter"?L="google/gemma-4-31b-it:free":b==="DeepSeek"?L="deepseek-v4-flash":b==="NVIDIA"&&(L="moonshotai/kimi-k2.6"),Ee(L),_.aiProvider=b,_.activeModel=L,U(B=>(z(B.length+1),[...B,{id:Date.now(),role:"system",text:`\u2705 ${b} API Key saved successfully! Model set to ${L}.`,isMeta:!0}]))}F?At(F(g==="quotas"?C:x)):(Dn({..._,apiTier:Mt,quotas:C,imageSettings:_.imageSettings||se}),At(null),J(Wo?.returnView||"settings"))}})),l.createElement(I,{paddingX:1,marginTop:1},l.createElement(S,{color:"gray",dimColor:!0,italic:!0},"(Press Enter to confirm selection)")));case"stats":return l.createElement(I,{flexDirection:"column",borderStyle:"round",borderColor:"grey",paddingX:3,paddingY:1,width:Math.min(100,(s?.columns||100)-2)},l.createElement(I,{marginBottom:1},l.createElement(S,{color:"white",bold:!0,underline:!0},"SESSION TELEMETRY")),l.createElement(I,{flexDirection:"column"},l.createElement(I,null,l.createElement(I,{width:25},l.createElement(S,{color:"blue"},"Session Duration:")),l.createElement(S,{color:"white"},ie(Date.now()-pa))),l.createElement(I,null,l.createElement(I,{width:25},l.createElement(S,{color:"blue"},"Agent Interactions:")),l.createElement(S,{color:"white"},Je)),l.createElement(I,{marginLeft:2},l.createElement(I,{width:23},l.createElement(S,{color:"grey"},"\xBB API Time:")),l.createElement(S,{color:"white"},ie(Ir))),l.createElement(I,{marginLeft:2},l.createElement(I,{width:23},l.createElement(S,{color:"grey"},"\xBB Tool Time:")),l.createElement(S,{color:"white"},ie(lr))),l.createElement(I,null,l.createElement(I,{width:25},l.createElement(S,{color:"blue"},"Background Tasks:")),l.createElement(S,{color:"white"},Et)),l.createElement(I,null,l.createElement(I,{width:25},l.createElement(S,{color:"blue"},"Tokens Consumed:")),l.createElement(S,{color:"white"},eo(Tt))),l.createElement(I,null,l.createElement(I,{width:25},l.createElement(S,{color:"blue"},"Active Context:")),l.createElement(S,{color:"white"},eo(Ke.tokens))),Tt>0&&l.createElement(l.Fragment,null,l.createElement(I,{marginLeft:2},l.createElement(I,{width:23},l.createElement(S,{color:"grey"},"\xBB Input Tokens:")),l.createElement(S,{color:"white"},eo(Tt-Bt))),vt>0&&l.createElement(I,{marginLeft:4},l.createElement(I,{width:21},l.createElement(S,{color:"grey"},"\xBB Cached:")),l.createElement(S,{color:"white"},eo(vt))),Bt>0&&l.createElement(I,{marginLeft:2},l.createElement(I,{width:23},l.createElement(S,{color:"grey"},"\xBB Output Tokens:")),l.createElement(S,{color:"white"},eo(Bt)))),Ar>0&&l.createElement(l.Fragment,null,l.createElement(I,null,l.createElement(I,{width:25},l.createElement(S,{color:"blue"},"Images Made:")),l.createElement(S,{color:"white"},Ar)),l.createElement(I,null,l.createElement(I,{width:25},l.createElement(S,{color:"blue"},"Image Credits:")),l.createElement(S,{color:"white"},Number(((Hn||0)*1e3).toFixed(0))," credits"))),l.createElement(I,null,l.createElement(I,{width:25},l.createElement(S,{color:"blue"},"Code Changes (Sess):")),l.createElement(S,{color:"white"},l.createElement(S,{color:"green"},"+",Ws)," ",l.createElement(S,{color:"red"},"-",Ys))),l.createElement(I,null,l.createElement(I,{width:25},l.createElement(S,{color:"blue"},"Tool Calls (Sess):")),l.createElement(S,{color:"white"},pt+Jt+jo," ( "),l.createElement(S,{color:"green"},"\u2713 ",pt),l.createElement(S,{color:"white"}," "),l.createElement(S,{color:"yellow"},"\u2298 ",jo),l.createElement(S,{color:"white"}," "),l.createElement(S,{color:"red"},"\u2715 ",Jt),l.createElement(S,{color:"white"}," )"))),l.createElement(I,{flexDirection:"column",marginTop:1},l.createElement(S,{color:"white",bold:!0,underline:!0},"DAILY USAGE TRACKER"),l.createElement(I,{marginTop:1},l.createElement(I,{width:25},l.createElement(S,{color:"blue"},"Wall Time Today:")),l.createElement(S,{color:"white"},Ce(me?.duration||0))),l.createElement(I,null,l.createElement(I,{width:25},l.createElement(S,{color:"blue"},"Agent Interactions:")),l.createElement(S,{color:"white"},me?.agent||0)),l.createElement(I,null,l.createElement(I,{width:25},l.createElement(S,{color:"blue"},"Background Tasks:")),l.createElement(S,{color:"white"},me?.background||0)),l.createElement(I,null,l.createElement(I,{width:25},l.createElement(S,{color:"blue"},"Tokens Used Today:")),l.createElement(S,{color:"white"},eo(me?.tokens||0))),(me?.tokens||0)>0&&l.createElement(l.Fragment,null,l.createElement(I,{marginLeft:2},l.createElement(I,{width:23},l.createElement(S,{color:"grey"},"\xBB Input Tokens:")),l.createElement(S,{color:"white"},eo((me?.tokens||0)-(me?.candidateTokens||0)))),(me?.cachedTokens||0)>0&&l.createElement(I,{marginLeft:4},l.createElement(I,{width:21},l.createElement(S,{color:"grey"},"\xBB Cached:")),l.createElement(S,{color:"white"},eo(me.cachedTokens))),(me?.candidateTokens||0)>0&&l.createElement(I,{marginLeft:2},l.createElement(I,{width:23},l.createElement(S,{color:"grey"},"\xBB Output Tokens:")),l.createElement(S,{color:"white"},eo(me.candidateTokens)))),(me?.imageCalls?.length||0)>0&&l.createElement(l.Fragment,null,l.createElement(I,null,l.createElement(I,{width:25},l.createElement(S,{color:"blue"},"Images Made Today:")),l.createElement(S,{color:"white"},me.imageCalls.length)),l.createElement(I,null,l.createElement(I,{width:25},l.createElement(S,{color:"blue"},"Image Credits Today:")),l.createElement(S,{color:"white"},Number(((me.imageCalls.reduce((x,g)=>x+g.cost,0)||0)*1e3).toFixed(0))," credits"))),l.createElement(I,null,l.createElement(I,{width:25},l.createElement(S,{color:"blue"},"Code Changes Today:")),l.createElement(S,{color:"white"},l.createElement(S,{color:"green"},"+",me?.linesAdded||0)," ",l.createElement(S,{color:"red"},"-",me?.linesRemoved||0))),l.createElement(I,null,l.createElement(I,{width:25},l.createElement(S,{color:"blue"},"Tool Calls Today:")),l.createElement(S,{color:"white"},(me?.toolSuccess||0)+(me?.toolFailure||0)+(me?.toolDenied||0)," ( "),l.createElement(S,{color:"green"},"\u2713 ",me?.toolSuccess||0),l.createElement(S,{color:"white"}," "),l.createElement(S,{color:"yellow"},"\u2298 ",me?.toolDenied||0),l.createElement(S,{color:"white"}," "),l.createElement(S,{color:"red"},"\u2715 ",me?.toolFailure||0),l.createElement(S,{color:"white"}," )"))),l.createElement(S,{dimColor:!0,marginTop:1,italic:!0},"(Press ESC to return to chat)"));case"autoExecDanger":return l.createElement(I,{flexDirection:"column",borderStyle:"round",borderColor:"grey",paddingX:2,paddingY:1,width:"100%"},l.createElement(S,{color:"white",bold:!0,underline:!0},"SECURITY WARNING: YOLO MODE"),l.createElement(S,{marginTop:1},"Turning this ON allows the agent to execute terminal commands automatically without requiring your approval for each step."),l.createElement(S,{marginTop:1,color:"white"},"RISKS INVOLVED:"),l.createElement(S,null,"\u2022 The agent may execute destructive commands (rm -rf, etc.) by mistake unless specified in sandbox rules."),l.createElement(S,null,"\u2022 Unintended system changes if the agent hallucinates a path or command."),l.createElement(S,null,"\u2022 Reduced control over the agent's step-by-step decision making."),l.createElement(I,{marginTop:1},l.createElement(go,{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"&<(g=>({...g,autoExec:!0})),J("settings")}})));case"externalDanger":return l.createElement(I,{flexDirection:"column",borderStyle:"round",borderColor:"grey",paddingX:2,paddingY:1,width:"100%"},l.createElement(S,{color:"white",bold:!0,underline:!0},"SECURITY WARNING: EXTERNAL WORKSPACE ACCESS"),l.createElement(S,{marginTop:1},"Turning this ON allows the agent to execute tools (Read/Write/Exec) outside of the current active workspace directory."),l.createElement(S,{marginTop:1,color:"white"},"RISKS INVOLVED:"),l.createElement(S,null,"\u2022 Access to sensitive system files (SSH keys, Browser data, etc.)"),l.createElement(S,null,"\u2022 Potential for accidental or malicious deletion of OS-critical files."),l.createElement(S,null,"\u2022 Unauthorized script execution across your entire file system."),l.createElement(I,{marginTop:1},l.createElement(go,{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"&<(g=>({...g,allowExternalAccess:!0})),J("settings")}})));case"doubleDanger":return l.createElement(I,{flexDirection:"column",borderStyle:"round",borderColor:"white",paddingX:2,paddingY:1,width:"100%"},l.createElement(S,{color:"white",bold:!0,underline:!0},"CRITICAL SECURITY WARNING: COMBINED SYSTEM RISK"),l.createElement(S,{marginTop:1},"You are attempting to enable BOTH [YOLO Mode] and [External Workspace Access] simultaneously."),l.createElement(S,{marginTop:1,color:"red",bold:!0},"THIS IS NOT RECOMMENDED."),l.createElement(S,{marginTop:1,color:"white"},"THE CRITICAL RISK:"),l.createElement(S,null,"The agent will have the power to execute any command across your entire system WITHOUT your approval or supervision."),l.createElement(S,{color:"red",italic:!0,marginTop:1},"A single hallucination or error could result in full system wipe or data theft."),l.createElement(I,{marginTop:1},l.createElement(go,{title:"Final Confirmation",items:[{label:"I agree knowing the consequences",value:"on"},{label:"Keep Off",value:"off"}],onSelect:x=>{x.value==="on"&<(g=>({...g,autoExec:!0,allowExternalAccess:!0})),J("settings")}})));case"key":return l.createElement(go,{title:"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"){ot(null),J("chat");let g=Fe(2);U(v=>[...v,{id:Date.now(),role:"system",text:"[ACTION] Flux waiting for new API Key..."}])}else x.value==="remove"?J("deleteKey"):J("chat")}});case"deleteKey":return l.createElement(I,{flexDirection:"column",borderStyle:"round",borderColor:"grey",paddingX:2,paddingY:1},(()=>{let x=Fe(2);return l.createElement(S,{color:"white",bold:!0},"DANGER: PURGE API KEY")})(),l.createElement(S,{marginTop:1},"This will permanently delete the saved API key from the project vault. You will need to enter it again to use Flux."),l.createElement(I,{marginTop:1},l.createElement(go,{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 Js(),ot(null),J("chat");let g=Fe(2);U(v=>[...v,{id:Date.now(),role:"system",text:"[VAULT PURGED] API Key removed successfully."}])}else J("key")}})));case"exit":return null;case"ask":return l.createElement(I,{width:"100%"},l.createElement(za,{question:ur?.question,options:ur?.options,onResolve:x=>{ur?.resolve&&ur.resolve(x),ts(null),J("chat")}}));case"revert":return l.createElement(I,{width:"100%",alignItems:"center",justifyContent:"center"},l.createElement(ha,{prompts:wa,onSelect:async x=>{try{let g=await nt.rollbackToBefore(x);if(g.success){let{targetPrompt:v}=g;lc(je);let F=_e.findLastIndex(b=>b.role==="user"&&b.text&&(b.text.startsWith(v)||b.text.includes(v))),C=[..._e];F!==-1&&(C=_e.slice(0,F)),U(C),z(C.length),u(v),a(v.split(`
|
|
638
|
+
`).length>2);let _=C.filter(b=>!String(b.id).startsWith("welcome")&&!b.isMeta);await ks(je,null,_);let R=Fe(2);U(b=>{let L=[...b,{id:"revert-ok-"+Date.now(),role:"system",text:"[ROLLBACK SUCCESSFUL] Reverted prompt loaded to input box.",isMeta:!0}];return z(L.length),L}),J("chat")}}catch(g){let v=Fe(2);U(F=>{let C=[...F,{id:"revert-err-"+Date.now(),role:"system",text:`[ROLLBACK ERROR] ${g.message}`,isMeta:!0}];return z(C.length),C}),J("chat")}},onClose:()=>J("chat")}));case"resume":return l.createElement(I,{width:"100%",alignItems:"center",justifyContent:"center"},l.createElement(la,{onSelect:async x=>{let g=await _o();if(g[x]){s.write("\x1B[2J\x1B[3J\x1B[H"),rn(x);let v=await Is(x);zt.current=Tt-v.total,Se(v.total),Oe({tokens:v.context});let F=[...g[x].messages];F[0]?.text?.includes("\u2591\u2591\u2591\u2588\u2588\u2588")||F.unshift({id:"logo-"+Date.now(),role:"system",isLogo:!0,isMeta:!0}),U(F),J("chat"),U(_=>{let R=[..._,{id:"sys-"+Date.now(),role:"system",text:`SESSION RESUMED: [${x}]`,isMeta:!0}];return z(R.length),R})}},onDelete:async x=>await gi(x),onClose:()=>J("chat")}));case"memory":return l.createElement(I,{width:"100%",alignItems:"center",justifyContent:"center"},l.createElement(ua,{onClose:()=>J("chat")}));case"parserDownload":return l.createElement(I,{width:"100%",alignItems:"center",justifyContent:"center"},l.createElement(da,{onClose:()=>J("settings")}));case"profile":return l.createElement(mi,{initialData:wn,onSave:x=>{ar(x),U(g=>[...g,{id:Date.now(),role:"system",text:`Profile updated: ${x.name} (${x.nickname})`}]),J("chat")},onCancel:()=>J("chat")});case"resolution":return l.createElement(I,{width:"100%",alignItems:"center",justifyContent:"center"},l.createElement(kd,{data:Z,onResolve:x=>{Qe(null),J("chat"),setTimeout(()=>{Vs(x,!0)},500)},onEdit:x=>{Qe(null),J("chat"),u(x)}}));case"approval":return l.createElement(I,{flexDirection:"column",borderStyle:"round",borderColor:"white",paddingX:2,paddingY:1,width:"100%"},l.createElement(S,{color:"white",bold:!0,underline:!0},"FILE WRITE PERMISSION"),l.createElement(S,{marginTop:1},"The agent is attempting to modify: ",l.createElement(S,{color:"cyan"},re(Kn?.args||"{}").path||"Unknown File")),Zo()?l.createElement(I,{marginTop:1,paddingX:1},l.createElement(S,{color:"cyan",italic:!0},"\u26A1\uFE0F FluxFlow Companion is active. Review the changes in your editor.")):l.createElement(I,{marginTop:1,borderStyle:"single",borderColor:"#333",paddingX:1,flexDirection:"column"},l.createElement(S,{color:"gray"},"--- PROPOSED CONTENT ---"),(()=>{let x=re(Kn?.args||"{}"),g=[],v=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 b=R[2]?parseInt(R[2]):1;v.add(b)}}),Array.from(v).sort((_,R)=>_-R).forEach(_=>{let R,b;_===1?(R=x.replaceContent1??x.content_to_replace1??x.replaceContent??x.content_to_replace??x.TargetContent??null,b=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,b=x[`newContent${_}`]??x[`content_to_add${_}`]??null),(R!==null||b!==null)&&g.push({replace:R,new:b})}),g.length>0)return l.createElement(I,{flexDirection:"column",marginTop:1},g.map((_,R)=>{let b=_.replace!==null,L=_.new!==null;return l.createElement(I,{key:R,flexDirection:"column",marginTop:R>0?1:0},g.length>1&&l.createElement(S,{color:"gray"},"Block ",R+1,":"),b&&l.createElement(I,null,l.createElement(S,{color:"red",wrap:"anywhere",bold:!0},"- ",_.replace)),L&&l.createElement(I,{marginTop:0},l.createElement(S,{color:"green",wrap:"anywhere",bold:!0},"+ ",_.new.replace(/\[\/n\]?/g,"\\n"))))}));let C=x.content||x.ReplacementContent||x.content_to_add||x.replacementContent||x.newContent||null;return l.createElement(S,{color:"white",wrap:"anywhere"},(C?C.replace(/\[\/n\]?/g,"\\n"):null)||"Updating file content...")})()),l.createElement(I,{marginTop:1},l.createElement(go,{title:"Action Required",items:[{label:"Accept this time",value:"allow"},{label:"Accept for this session",value:"always"},{label:"Don't accept",value:"deny"}],onSelect:x=>{x.value==="always"&&Dr(!0);let g=x.value==="deny"?"deny":"allow";Kn.resolve(g),cr(null),J("chat")}})));case"updateManager":return l.createElement(go,{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"){J("settings");return}x.value==="custom"?(At({label:"Enter Custom Update Command (Global install recommended):",key:"customUpdateCommand",value:Nt.customUpdateCommand,next:g=>(lt(v=>({...v,updateManager:"custom",customUpdateCommand:g})),null)}),J("input")):(lt(g=>({...g,updateManager:x.value})),J("settings"))}});case"update":return l.createElement(gc,{latest:ce,current:Uo,settings:Nt,onClose:()=>J("chat"),onSuccess:()=>{U(x=>(z(x.length+1),[...x,{id:"update-success-"+Date.now(),role:"system",text:`**[UPDATE COMPLETED]** Flux Flow successfully updated to v${ce}.
|
|
639
|
+
**Restart to see changes.**`,isMeta:!0}])),J("chat")},onUpdateSettings:x=>{J("updateManager")}});case"terminalApproval":return l.createElement(I,{flexDirection:"column",borderStyle:"round",borderColor:"white",paddingX:2,paddingY:1,width:"100%"},l.createElement(S,{color:"white",bold:!0,underline:!0},"TERMINAL COMMAND OVERSIGHT"),l.createElement(I,{marginTop:1},l.createElement(S,null,"Agent requested to run: ",l.createElement(S,{color:"yellow",bold:!0},re(Kn?.args||"{}").command||"Unknown Command"))),l.createElement(I,{marginTop:1},l.createElement(go,{title:"Risk Assessment Required",items:[{label:"Run",value:"allow"},{label:"Deny",value:"deny"}],onSelect:x=>{Kn.resolve(x.value),cr(null),J("chat")}})));default:return l.createElement(I,{flexDirection:"column",marginTop:1,flexShrink:0,width:"100%"},l.createElement(I,{paddingX:1,marginBottom:0,justifyContent:"space-between",width:"100%"},l.createElement(I,null,We?l.createElement(I,null,l.createElement(S,{color:"gray",bold:!0,italic:!0},We)):l.createElement(S,{color:"gray",italic:!0},i.length>0&&qn?"Press ESC again to clear input":"Waiting for input...")),l.createElement(I,null,St&&l.createElement(S,{color:"gray",italic:!0},St," "),l.createElement(S,{color:"gray",bold:!0},"[ "),l.createElement(S,{color:"white"},xt||Ve),l.createElement(S,{color:"gray",bold:!0}," ]"))),l.createElement(I,{flexDirection:"column",width:"100%"},l.createElement(I,{width:"100%",height:1,overflow:"hidden"},l.createElement(S,{color:"#555555"},"\u2584".repeat(Math.max(1,p.columns)))),l.createElement(I,{backgroundColor:"#555555",paddingX:1,paddingY:0,width:"100%",flexDirection:"column"},l.createElement(I,{flexDirection:"column",width:"100%"},l.createElement(I,{flexDirection:"row",width:"100%",paddingY:0},l.createElement(I,{flexShrink:0,width:4},l.createElement(S,{color:"white",bold:!0},fo||Xn?"\u2726 ":" \u276F ")),l.createElement(I,{flexGrow:1},l.createElement(I,{flexGrow:1,position:"relative"},i===""&&l.createElement(I,{position:"absolute",paddingLeft:0},gt&&!Wt?l.createElement(S,{color:"yellow"},yt?" Terminal is waiting for user input. Press TAB to interact":" Press TAB to interact with terminal..."):gt&&Wt?l.createElement(S,{color:"yellow",bold:!0}," [ TERMINAL FOCUSED ] Type to interact, press TAB to exit..."):qn===1?l.createElement(S,{color:"white",bold:!0}," Press ESC again to ",i.length>0?"clear input":"revert codebase to checkpoint","..."):l.createElement(S,{color:"#cccccc"},Lr?" Press ESC again to cancel the request.":Xn?" Compressing session history, please wait...":fo?" Enter a prompt to steer the agent.":` Send message, @file or /cmd ... (${Gn.shortcut} for newline)`)),l.createElement(Oa,{key:`input-${f}`,focus:!Wt&&!Xn,showCursor:mo&&!Xn,lastFocusEventTime:ut.current,value:i,textStyle:{bold:!0},columns:p.columns,onChange:x=>{let g=x.replace(/\r\n/g,`
|
|
640
640
|
`).replace(/\r/g,`
|
|
641
641
|
`).replace(/\\\s*\n/g,`
|
|
642
|
-
`);u(g),A(!1)},onSubmit:Vr,rows:1,maxRows:10,keyBindings:{submit:x=>x.return&&!x.shift&&!x.ctrl,newline:x=>x.return&&x.shift||x.return&&x.ctrl}})))))),l.createElement(I,{width:"100%",height:1,overflow:"hidden"},l.createElement(S,{color:"#555555"},"\u2580".repeat(Math.max(1,p.columns))))))}};return l.createElement(I,{flexDirection:"column",width:"100%"},$?l.createElement(Ed,{width:r?.columns||80,height:r?.rows||24,selectedIndex:D}):l.createElement(l.Fragment,null,l.createElement(I,{flexDirection:"column",width:"100%",flexGrow:1},Jn.items.map((x,g)=>l.createElement(si,{key:x.id||g,msg:x,showFullThinking:Xe,columns:r?.columns||80,aiProvider:N,version:Uo}))),l.createElement(I,{flexDirection:"column",padding:1,width:"100%"},(qt==="chat"||["ask","approval","terminalApproval"].includes(qt))&&l.createElement(I,{flexDirection:"column",width:"100%"},l.createElement(Ra,{messages:_e.slice(vo),showFullThinking:Xe,columns:Math.max(20,(r?.columns||80)-1),aiProvider:N,version:Uo}),pt&&l.createElement(I,{marginTop:1},l.createElement(yr,{command:pt,output:Ut,isFocused:Wt,isPty:Po}))),Ye?l.createElement(I,{borderStyle:"double",borderColor:"grey",padding:1,flexShrink:0},l.createElement(S,{color:"white"},"Starting Flux Flow...")):ze?nr():l.createElement(I,{borderStyle:"round",borderColor:"white",padding:0,flexDirection:"column",flexShrink:0,width:"100%"},l.createElement(I,{paddingX:1,marginBottom:1},l.createElement(S,{color:"gray",bold:!0},"\u{1F511}",Fe(2),"API KEY REQUIRED")),l.createElement(I,{paddingX:1,flexDirection:"column"},ee===0?l.createElement(l.Fragment,null,l.createElement(S,{color:"white"},"Select your Preferred Provider:"),l.createElement(I,{marginTop:1},l.createElement(go,{items:[{label:"Google (Free/Paid)",value:"Google"},{label:"DeepSeek (Paid)",value:"DeepSeek"},{label:"OpenRouter (Free/Paid) [EXPERIMENTAL]",value:"OpenRouter"},{label:"NVIDIA (Free/Paid)",value:"NVIDIA"}],onSelect:x=>{he(x.value),Me(1)}}))):l.createElement(l.Fragment,null,l.createElement(S,{color:"white"},"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)."),l.createElement(I,{marginTop:1},l.createElement(S,{color:"gray",bold:!0}," ",">"," "),l.createElement(Ac,{value:Ao,onChange:on,onSubmit:ms,mask:"*"})),l.createElement(I,{marginTop:1},l.createElement(S,{color:"gray",italic:!0},"(Press ESC to go back to provider selection)")))),l.createElement(I,{paddingX:1,marginTop:1},l.createElement(S,{color:"gray",italic:!0},ee===0?"(Use arrows to select and Enter to confirm)":"(Press Enter to confirm and initialize)"))),t&&l.createElement(I,{borderStyle:"round",borderColor:"white",paddingX:2,marginY:0,width:"100%"},l.createElement(S,{color:"white",bold:!0},"\u{1F534} EXIT CONFIRMATION: "),l.createElement(S,{color:"white"},"Press "),l.createElement(S,{color:"white",bold:!0},"CTRL + C"),l.createElement(S,{color:"white"}," again to exit (",n,"s). Press "),l.createElement(S,{color:"gray",bold:!0},"ESC"),l.createElement(S,{color:"white"}," to cancel.")),Lt.length>0&&(()=>{let g=M.current;T<g?g=T:T>=g+5&&(g=T-5+1),g=Math.max(0,Math.min(g,Math.max(0,Lt.length-5))),M.current=g;let v=Lt.slice(g,g+5),F=Lt.length-(g+v.length);return l.createElement(I,{flexDirection:"column",width:"100%",marginBottom:1},l.createElement(I,{paddingX:1,marginBottom:0,justifyContent:"space-between",width:"100%"},l.createElement(S,{color:"white",bold:!0},Lt[0]?.cmd?.startsWith("@")?"FILE SUGGESTIONS":"COMMAND SUGGESTIONS"),Lt[0]?.cmd?.startsWith("@")?l.createElement(S,{color:"gray",italic:!0},"(Use '#Lstart-Lend' to specify line numbers)"):i.startsWith("/model")&&Mt==="Free"?(()=>{let C="https://aistudio.google.com/billing",_="billing";return N==="DeepSeek"?(C="https://platform.deepseek.com/usage",_="billing"):N==="OpenRouter"?(C="https://openrouter.ai/settings/profile",_="profile"):N==="NVIDIA"&&(C="https://build.nvidia.com/settings/api-keys",_="billing"),l.createElement(S,{color:"gray",dimColor:!0,italic:!0},"Paid API has more models. Configure ",l.createElement(S,{color:"cyan",underline:!0},`\x1B]8;;${C}\x07${_}\x1B]8;;\x07`)," & /settings")})():null),v.map((C,_)=>{let b=g+_===T,L=C.cmd==="gemma-4-31b-it"&&Mt!=="Free";return l.createElement(I,{key:C.cmd,flexDirection:"row",backgroundColor:b?"#2a2a2a":void 0,paddingX:1},l.createElement(I,{width:3},l.createElement(S,{color:b?"white":"gray",bold:b},b?" \u276F":" ")),l.createElement(I,{width:55},l.createElement(S,{color:L?"gray":b?"white":"grey",bold:b},C.cmd?.startsWith("@[")&&C.cmd?.endsWith("]")?(()=>{let V=C.cmd.slice(2,-1).split(/[/\\]/);return V[V.length-1]})():C.cmd)),l.createElement(I,{flexGrow:1},l.createElement(S,{color:`${b?"white":"gray"}`,italic:!0},C.desc)))}),Lt.length>5&&l.createElement(I,{paddingX:1,height:1},F>0?l.createElement(S,{color:"gray",dimColor:!0,italic:!0}," ... (",F," more commands available)"):l.createElement(S,{color:"gray",dimColor:!0,italic:!0}," (End of list)")))})(),l.createElement(I,{flexShrink:0,width:"100%"},l.createElement(Wa,{mode:d,thinkingLevel:q,tokens:Ke.tokens,tokensTotal:lt,chatId:je,isMemoryEnabled:Nt.memory,apiTier:Mt,aiProvider:N})),qt==="exit"&&(()=>{let x=Date.now()-pa,g=ht+Jt,v=g>0?(ht/g*100).toFixed(1):"0.0",F=Is+ls,C=F>0?(Is/F*100).toFixed(1):"0.0",_=F>0?(ls/F*100).toFixed(1):"0.0";return l.createElement(I,{flexDirection:"column",borderStyle:"round",paddingX:3,paddingY:1,borderColor:"grey",width:Math.min(100,(r?.columns||100)-2),marginTop:0,marginBottom:0},l.createElement(I,{marginBottom:1},l.createElement(S,{bold:!0},Sd(["blue","purple"])("Agent powering down. Goodbye!"))),l.createElement(I,{flexDirection:"column"},l.createElement(S,{color:"white",bold:!0,underline:!0},"Interaction Summary"),l.createElement(I,{marginTop:1},l.createElement(I,{width:20},l.createElement(S,{color:"blue"},"Session ID:")),l.createElement(S,{color:"white"},je)),l.createElement(I,null,l.createElement(I,{width:20},l.createElement(S,{color:"blue"},"Tool Calls:")),l.createElement(S,{color:"white"},ht+Jt+jo," ( ",l.createElement(S,{color:"green"},"\u2713 ",ht)," ",l.createElement(S,{color:"yellow"},"\u2298 ",jo)," ",l.createElement(S,{color:"red"},"\u2715 ",Jt)," )")),l.createElement(I,null,l.createElement(I,{width:20},l.createElement(S,{color:"blue"},"Success Rate:")),l.createElement(S,{color:"white"},v,"%")),l.createElement(I,null,l.createElement(I,{width:20},l.createElement(S,{color:"blue"},"Code Changes:")),l.createElement(S,{color:"white"},l.createElement(S,{color:"green"},"+",Wr)," ",l.createElement(S,{color:"red"},"-",Yr))),l.createElement(I,null,l.createElement(I,{width:20},l.createElement(S,{color:"blue"},"Tokens Consumed:")),l.createElement(S,{color:"white"},eo(Tt))),Tt>0&&l.createElement(l.Fragment,null,l.createElement(I,{marginLeft:2},l.createElement(I,{width:18},l.createElement(S,{color:"grey"},"\xBB Input Tokens:")),l.createElement(S,{color:"white"},eo(Tt-Bt))),vt>0&&l.createElement(I,{marginLeft:4},l.createElement(I,{width:16},l.createElement(S,{color:"grey"},"\xBB Cached:")),l.createElement(S,{color:"white"},eo(vt))),Bt>0&&l.createElement(I,{marginLeft:2},l.createElement(I,{width:18},l.createElement(S,{color:"grey"},"\xBB Output Tokens:")),l.createElement(S,{color:"white"},eo(Bt)))),As>0&&l.createElement(l.Fragment,null,l.createElement(I,null,l.createElement(I,{width:20},l.createElement(S,{color:"blue"},"Images Made:")),l.createElement(S,{color:"white"},As)),l.createElement(I,null,l.createElement(I,{width:20},l.createElement(S,{color:"blue"},"Image Credits:")),l.createElement(S,{color:"white"},Number(((Hn||0)*1e3).toFixed(0))," credits")))),l.createElement(I,{flexDirection:"column",marginTop:1},l.createElement(S,{color:"white",bold:!0,underline:!0},"Performance"),l.createElement(I,{marginTop:1},l.createElement(I,{width:20},l.createElement(S,{color:"blue"},"Wall Time:")),l.createElement(S,{color:"white"},ie(x))),l.createElement(I,null,l.createElement(I,{width:20},l.createElement(S,{color:"blue"},"Agent Active:")),l.createElement(S,{color:"white"},ie(F))),l.createElement(I,{marginLeft:2},l.createElement(I,{width:18},l.createElement(S,{color:"grey"},"\xBB API Time:")),l.createElement(S,{color:"white"},ie(Is)," (",C,"%)")),l.createElement(I,{marginLeft:2},l.createElement(I,{width:18},l.createElement(S,{color:"grey"},"\xBB Tool Time:")),l.createElement(S,{color:"white"},ie(ls)," (",_,"%)"))))})())))}var jr,Dc,Ed,pa,vc,ga,Wr,Yr,bd,Oc,Uo,Cd,kd,Id,Md,Fc=ae(async()=>{La();Ua();Ya();ja();await Va();qa();Ja();Ns();await uc();fr();Ks();dc();mc();await xc();wc();pn();Tc();Sc();Ec();vr();oi();Kt();Pt();un();await js();Ic();os();Ji();jr=()=>{let e=(process.env.TERM_PROGRAM||"").toLowerCase();if(process.env.WT_SESSION)return"Windows Terminal";let t=o=>{let n=o.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||t("cursor")?"Cursor":e==="windsurf"||t("windsurf")?"Windsurf":t("antigravity")?"Antigravity":e==="trae"||t("trae")?"Trae":e==="codium"||t("codium")||t("vscode-oss")?"VSCodium":t("positron")?"Positron":e==="vscode"||process.env.VSCODE_GIT_IPC_HANDLE||t("vscode")?"VS Code":process.env.INTELLIJ_TERMINAL_COMMAND_BLOCKS||t("intellij")?"JetBrains":"Terminal"},Dc=e=>{let t=e==="VS Code",o=[];return t?(o.push({label:"Install Manually (VSIX)",url:"https://github.com/KushalRoyChowdhury/fluxflow-cli/releases"}),o.push({label:"Install from VS Code Marketplace",url:"https://marketplace.visualstudio.com/items?itemName=fluxflow-cli.fluxflow-cli-companion"})):o.push({label:`Download for ${e} (GitHub)`,url:"https://github.com/KushalRoyChowdhury/fluxflow-cli/releases"}),o.push({label:"Continue to CLI only",action:"dismiss"}),o},Ed=({width:e,height:t,selectedIndex:o})=>{let n=jr(),s=Dc(n);return l.createElement(I,{flexDirection:"column",alignItems:"center",justifyContent:"center",width:e,height:t},l.createElement(I,{marginBottom:1,width:Math.min(80,e-4),justifyContent:"flex-start"},l.createElement(S,null,wr(Uo))),l.createElement(I,{flexDirection:"column",borderStyle:"double",borderColor:"grey",paddingX:3,paddingY:1,width:Math.min(80,e-4)},l.createElement(S,{bold:!0,color:"white",textAlign:"center"},"\u{1F680} UPGRADE YOUR WORKFLOW"),l.createElement(I,{marginY:1,flexDirection:"column",alignItems:"left"},l.createElement(S,null,"You're in ",l.createElement(S,{bold:!0,color:"cyan"},n),", but the ",l.createElement(S,{bold:!0,color:"white"},"FluxFlow-CLI Companion")," is not installed."),l.createElement(I,{flexDirection:"column",marginY:1},l.createElement(S,{color:"gray"}," \u2705 Real-time file & cursor tracking"),l.createElement(S,{color:"gray"}," \u2705 Auto-open files created by agent"),l.createElement(S,{color:"gray"}," \u2705 Native DIFF viewer for AI edits"),l.createElement(S,{color:"gray"}," \u2705 Direct IDE context sharing"),l.createElement(S,{color:"gray"}," \u2705 Surgical Diagnostic Sync"),l.createElement(S,{color:"gray"}," \u2705 Native Right-Click \u276F Chat integration"),l.createElement(S,{color:"gray"}," \u2705 Live Status in IDE"),l.createElement(S,{color:"gray"}," \u2705 Clickable terminal-to-code links"))),l.createElement(I,{flexDirection:"column",marginTop:1},s.map((r,i)=>l.createElement(I,{key:i},l.createElement(S,{color:o===i?"yellow":"white",bold:o===i},o===i?" \u276F ":" ",r.label)))),l.createElement(I,{marginTop:1,alignItems:"center",justifyContent:"center"},l.createElement(S,{dimColor:!0,italic:!0},"(Use arrows to navigate, Enter to select)"))))},pa=Date.now(),vc="https://fluxflow-cli.onrender.com/changelog",ga="https://fluxflow-cli.onrender.com/",Wr=0,Yr=0,bd=is.join(is.dirname(Td(import.meta.url)),"../package.json"),Oc=JSON.parse(uo.readFileSync(bd,"utf8")),Uo=Oc.version,Cd=Oc.date||"2026-05-20",kd=({data:e,onResolve:t,onEdit:o})=>l.createElement(I,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},l.createElement(I,{paddingX:1},l.createElement(S,{color:"magenta",bold:!0,underline:!0},"\u{1F7E3} STEERING HINT RESOLUTION")),l.createElement(I,{paddingX:1,marginTop:1},l.createElement(S,null,"The agent already finished the task before your hint was consumed.")),l.createElement(I,{marginTop:1,backgroundColor:"#222",paddingX:2,width:"100%"},l.createElement(S,{italic:!0,color:"gray"},'"',e,'"')),l.createElement(I,{paddingX:1,marginTop:1},l.createElement(S,{color:"cyan"},"How would you like to proceed?")),l.createElement(I,{marginTop:0},l.createElement(go,{title:"Select Action",items:[{label:"Send Anyway",value:"send"},{label:"Edit Prompt",value:"edit"}],onSelect:n=>{n==="send"?t(e):o(e)}}))),Id=e=>{let t=[],o=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,n=0,s;for(;(s=o.exec(e))!==null;){let r=s[1],i=s.index+s[0].length-1,u=0,f=null,m=-1,c=-1;for(let a=i;a<e.length;a++){let d=e[a];if(f){if(d===f){let h=0;for(let p=a-1;p>=0&&e[p]==="\\";p--)h++;h%2===0&&(f=null)}}else if(d==='"'||d==="'"||d==="`")f=d;else if(d==="(")u++;else if(d===")"&&(u--,u===0)){c=a;let h=a+1;for(;h<e.length&&/\s/.test(e[h]);)h++;if(h<e.length&&e[h]==="]"){m=h;break}}}if(m!==-1){let a=e.substring(n,s.index);a.trim()&&t.push({type:"output",content:a});let d=e.substring(i+1,c);t.push({type:"tool",toolName:r.trim(),args:d.trim()}),n=m+1,o.lastIndex=n}else break}if(n<e.length){let r=e.substring(n);r.trim()&&t.push({type:"output",content:r})}return t},Md=(()=>{let e=null,t=0;return o=>{let n=Date.now();if(e&&n-t<5e3)return e;let s=[],r=i=>{try{let u=uo.readdirSync(i);for(let f of u){if(["node_modules",".git",".gemini","dist","build",".next",".cache","out"].includes(f))continue;let m=is.join(i,f);uo.statSync(m).isDirectory()?r(m):s.push({name:f,relativePath:is.relative(process.cwd(),m)})}}catch{}};return r(o),e=s,t=n,s}})()});import{spawn as Ad}from"child_process";import{fileURLToPath as $c}from"url";var vd=4096,Dd=$c(import.meta.url).endsWith(".js");if(Dd&&!process.execArgv.some(e=>e.includes("max-old-space-size")))Ad(process.execPath,[`--max-old-space-size=${vd}`,$c(import.meta.url),...process.argv.slice(2)],{stdio:"inherit"}).on("exit",t=>process.exit(t||0));else{let e=process.argv.slice(2),t=e.includes("--help")&&e[e.indexOf("--help")+1]==="commands",o=e.includes("--help")&&!t,n=e.includes("--version")||e.includes("-v"),s=e[0]==="--update";if(n||o||t||s){let h=await import("fs"),p=await import("path"),{fileURLToPath:y}=await import("url"),T=p.join(p.dirname(y(import.meta.url)),"../package.json"),E=JSON.parse(h.readFileSync(T,"utf8")).version;if(n&&(console.log(`v${E}`),process.exit(0)),o&&(console.log(`FluxFlow CLI Arguments:
|
|
642
|
+
`);u(g),A(!1)},onSubmit:Vs,rows:1,maxRows:10,keyBindings:{submit:x=>x.return&&!x.shift&&!x.ctrl,newline:x=>x.return&&x.shift||x.return&&x.ctrl}})))))),l.createElement(I,{width:"100%",height:1,overflow:"hidden"},l.createElement(S,{color:"#555555"},"\u2580".repeat(Math.max(1,p.columns))))))}};return l.createElement(I,{flexDirection:"column",width:"100%"},$?l.createElement(Ed,{width:s?.columns||80,height:s?.rows||24,selectedIndex:D}):l.createElement(l.Fragment,null,l.createElement(I,{flexDirection:"column",width:"100%",flexGrow:1},Jn.items.map((x,g)=>l.createElement(ri,{key:x.id||g,msg:x,showFullThinking:Xe,columns:s?.columns||80,aiProvider:N,version:Uo}))),l.createElement(I,{flexDirection:"column",padding:1,width:"100%"},(qt==="chat"||["ask","approval","terminalApproval"].includes(qt))&&l.createElement(I,{flexDirection:"column",width:"100%"},l.createElement(Ra,{messages:_e.slice(vo),showFullThinking:Xe,columns:Math.max(20,(s?.columns||80)-1),aiProvider:N,version:Uo}),gt&&l.createElement(I,{marginTop:1},l.createElement(ys,{command:gt,output:Ut,isFocused:Wt,isPty:Po}))),Ye?l.createElement(I,{borderStyle:"double",borderColor:"grey",padding:1,flexShrink:0},l.createElement(S,{color:"white"},"Starting Flux Flow...")):ze?ns():l.createElement(I,{borderStyle:"round",borderColor:"white",padding:0,flexDirection:"column",flexShrink:0,width:"100%"},l.createElement(I,{paddingX:1,marginBottom:1},l.createElement(S,{color:"gray",bold:!0},"\u{1F511}",Fe(2),"API KEY REQUIRED")),l.createElement(I,{paddingX:1,flexDirection:"column"},ee===0?l.createElement(l.Fragment,null,l.createElement(S,{color:"white"},"Select your Preferred Provider:"),l.createElement(I,{marginTop:1},l.createElement(go,{items:[{label:"Google (Free/Paid)",value:"Google"},{label:"DeepSeek (Paid)",value:"DeepSeek"},{label:"OpenRouter (Free/Paid) [EXPERIMENTAL]",value:"OpenRouter"},{label:"NVIDIA (Free/Paid)",value:"NVIDIA"}],onSelect:x=>{ge(x.value),Me(1)}}))):l.createElement(l.Fragment,null,l.createElement(S,{color:"white"},"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)."),l.createElement(I,{marginTop:1},l.createElement(S,{color:"gray",bold:!0}," ",">"," "),l.createElement(Ac,{value:Ao,onChange:nn,onSubmit:mr,mask:"*"})),l.createElement(I,{marginTop:1},l.createElement(S,{color:"gray",italic:!0},"(Press ESC to go back to provider selection)")))),l.createElement(I,{paddingX:1,marginTop:1},l.createElement(S,{color:"gray",italic:!0},ee===0?"(Use arrows to select and Enter to confirm)":"(Press Enter to confirm and initialize)"))),t&&l.createElement(I,{borderStyle:"round",borderColor:"white",paddingX:2,marginY:0,width:"100%"},l.createElement(S,{color:"white",bold:!0},"\u{1F534} EXIT CONFIRMATION: "),l.createElement(S,{color:"white"},"Press "),l.createElement(S,{color:"white",bold:!0},"CTRL + C"),l.createElement(S,{color:"white"}," again to exit (",n,"s). Press "),l.createElement(S,{color:"gray",bold:!0},"ESC"),l.createElement(S,{color:"white"}," to cancel.")),Lt.length>0&&(()=>{let g=M.current;T<g?g=T:T>=g+5&&(g=T-5+1),g=Math.max(0,Math.min(g,Math.max(0,Lt.length-5))),M.current=g;let v=Lt.slice(g,g+5),F=Lt.length-(g+v.length);return l.createElement(I,{flexDirection:"column",width:"100%",marginBottom:1},l.createElement(I,{paddingX:1,marginBottom:0,justifyContent:"space-between",width:"100%"},l.createElement(S,{color:"white",bold:!0},Lt[0]?.cmd?.startsWith("@")?"FILE SUGGESTIONS":"COMMAND SUGGESTIONS"),Lt[0]?.cmd?.startsWith("@")?l.createElement(S,{color:"gray",italic:!0},"(Use '#Lstart-Lend' to specify line numbers)"):i.startsWith("/model")&&Mt==="Free"?(()=>{let C="https://aistudio.google.com/billing",_="billing";return N==="DeepSeek"?(C="https://platform.deepseek.com/usage",_="billing"):N==="OpenRouter"?(C="https://openrouter.ai/settings/profile",_="profile"):N==="NVIDIA"&&(C="https://build.nvidia.com/settings/api-keys",_="billing"),l.createElement(S,{color:"gray",dimColor:!0,italic:!0},"Paid API has more models. Configure ",l.createElement(S,{color:"cyan",underline:!0},`\x1B]8;;${C}\x07${_}\x1B]8;;\x07`)," & /settings")})():null),v.map((C,_)=>{let b=g+_===T,L=C.cmd==="gemma-4-31b-it"&&Mt!=="Free";return l.createElement(I,{key:C.cmd,flexDirection:"row",backgroundColor:b?"#2a2a2a":void 0,paddingX:1},l.createElement(I,{width:3},l.createElement(S,{color:b?"white":"gray",bold:b},b?" \u276F":" ")),l.createElement(I,{width:55},l.createElement(S,{color:L?"gray":b?"white":"grey",bold:b},C.cmd?.startsWith("@[")&&C.cmd?.endsWith("]")?(()=>{let V=C.cmd.slice(2,-1).split(/[/\\]/);return V[V.length-1]})():C.cmd)),l.createElement(I,{flexGrow:1},l.createElement(S,{color:`${b?"white":"gray"}`,italic:!0},C.desc)))}),Lt.length>5&&l.createElement(I,{paddingX:1,height:1},F>0?l.createElement(S,{color:"gray",dimColor:!0,italic:!0}," ... (",F," more commands available)"):l.createElement(S,{color:"gray",dimColor:!0,italic:!0}," (End of list)")))})(),l.createElement(I,{flexShrink:0,width:"100%"},l.createElement(Wa,{mode:d,thinkingLevel:q,tokens:Ke.tokens,tokensTotal:ct,chatId:je,isMemoryEnabled:Nt.memory,apiTier:Mt,aiProvider:N})),qt==="exit"&&(()=>{let x=Date.now()-pa,g=pt+Jt,v=g>0?(pt/g*100).toFixed(1):"0.0",F=Ir+lr,C=F>0?(Ir/F*100).toFixed(1):"0.0",_=F>0?(lr/F*100).toFixed(1):"0.0";return l.createElement(I,{flexDirection:"column",borderStyle:"round",paddingX:3,paddingY:1,borderColor:"grey",width:Math.min(100,(s?.columns||100)-2),marginTop:0,marginBottom:0},l.createElement(I,{marginBottom:1},l.createElement(S,{bold:!0},Sd(["blue","purple"])("Agent powering down. Goodbye!"))),l.createElement(I,{flexDirection:"column"},l.createElement(S,{color:"white",bold:!0,underline:!0},"Interaction Summary"),l.createElement(I,{marginTop:1},l.createElement(I,{width:20},l.createElement(S,{color:"blue"},"Session ID:")),l.createElement(S,{color:"white"},je)),l.createElement(I,null,l.createElement(I,{width:20},l.createElement(S,{color:"blue"},"Tool Calls:")),l.createElement(S,{color:"white"},pt+Jt+jo," ( ",l.createElement(S,{color:"green"},"\u2713 ",pt)," ",l.createElement(S,{color:"yellow"},"\u2298 ",jo)," ",l.createElement(S,{color:"red"},"\u2715 ",Jt)," )")),l.createElement(I,null,l.createElement(I,{width:20},l.createElement(S,{color:"blue"},"Success Rate:")),l.createElement(S,{color:"white"},v,"%")),l.createElement(I,null,l.createElement(I,{width:20},l.createElement(S,{color:"blue"},"Code Changes:")),l.createElement(S,{color:"white"},l.createElement(S,{color:"green"},"+",Ws)," ",l.createElement(S,{color:"red"},"-",Ys))),l.createElement(I,null,l.createElement(I,{width:20},l.createElement(S,{color:"blue"},"Tokens Consumed:")),l.createElement(S,{color:"white"},eo(Tt))),Tt>0&&l.createElement(l.Fragment,null,l.createElement(I,{marginLeft:2},l.createElement(I,{width:18},l.createElement(S,{color:"grey"},"\xBB Input Tokens:")),l.createElement(S,{color:"white"},eo(Tt-Bt))),vt>0&&l.createElement(I,{marginLeft:4},l.createElement(I,{width:16},l.createElement(S,{color:"grey"},"\xBB Cached:")),l.createElement(S,{color:"white"},eo(vt))),Bt>0&&l.createElement(I,{marginLeft:2},l.createElement(I,{width:18},l.createElement(S,{color:"grey"},"\xBB Output Tokens:")),l.createElement(S,{color:"white"},eo(Bt)))),Ar>0&&l.createElement(l.Fragment,null,l.createElement(I,null,l.createElement(I,{width:20},l.createElement(S,{color:"blue"},"Images Made:")),l.createElement(S,{color:"white"},Ar)),l.createElement(I,null,l.createElement(I,{width:20},l.createElement(S,{color:"blue"},"Image Credits:")),l.createElement(S,{color:"white"},Number(((Hn||0)*1e3).toFixed(0))," credits")))),l.createElement(I,{flexDirection:"column",marginTop:1},l.createElement(S,{color:"white",bold:!0,underline:!0},"Performance"),l.createElement(I,{marginTop:1},l.createElement(I,{width:20},l.createElement(S,{color:"blue"},"Wall Time:")),l.createElement(S,{color:"white"},ie(x))),l.createElement(I,null,l.createElement(I,{width:20},l.createElement(S,{color:"blue"},"Agent Active:")),l.createElement(S,{color:"white"},ie(F))),l.createElement(I,{marginLeft:2},l.createElement(I,{width:18},l.createElement(S,{color:"grey"},"\xBB API Time:")),l.createElement(S,{color:"white"},ie(Ir)," (",C,"%)")),l.createElement(I,{marginLeft:2},l.createElement(I,{width:18},l.createElement(S,{color:"grey"},"\xBB Tool Time:")),l.createElement(S,{color:"white"},ie(lr)," (",_,"%)"))))})())))}var js,Dc,Ed,pa,vc,ga,Ws,Ys,bd,Oc,Uo,Cd,kd,Id,Md,Fc=ae(async()=>{La();Ua();Ya();ja();await Va();qa();Ja();Nr();await uc();fs();Kr();dc();mc();await xc();wc();zo();Tc();Sc();Ec();vs();oi();Kt();Pt();dn();await jr();Ic();or();Ji();js=()=>{let e=(process.env.TERM_PROGRAM||"").toLowerCase();if(process.env.WT_SESSION)return"Windows Terminal";let t=o=>{let n=o.toLowerCase();for(let[r,s]of Object.entries(process.env))if(!["PATH","PWD","CWD","PS1","LS_COLORS","PROMPT"].includes(r)&&String(s).toLowerCase().includes(n))return!0;return!1};return e==="cursor"||process.env.CURSOR_SETTINGS_DIR||t("cursor")?"Cursor":e==="windsurf"||t("windsurf")?"Windsurf":t("antigravity")?"Antigravity":e==="trae"||t("trae")?"Trae":e==="codium"||t("codium")||t("vscode-oss")?"VSCodium":t("positron")?"Positron":e==="vscode"||process.env.VSCODE_GIT_IPC_HANDLE||t("vscode")?"VS Code":process.env.INTELLIJ_TERMINAL_COMMAND_BLOCKS||t("intellij")?"JetBrains":"Terminal"},Dc=e=>{let t=e==="VS Code",o=[];return t?(o.push({label:"Install Manually (VSIX)",url:"https://github.com/KushalRoyChowdhury/fluxflow-cli/releases"}),o.push({label:"Install from VS Code Marketplace",url:"https://marketplace.visualstudio.com/items?itemName=fluxflow-cli.fluxflow-cli-companion"})):o.push({label:`Download for ${e} (GitHub)`,url:"https://github.com/KushalRoyChowdhury/fluxflow-cli/releases"}),o.push({label:"Continue to CLI only",action:"dismiss"}),o},Ed=({width:e,height:t,selectedIndex:o})=>{let n=js(),r=Dc(n);return l.createElement(I,{flexDirection:"column",alignItems:"center",justifyContent:"center",width:e,height:t},l.createElement(I,{marginBottom:1,width:Math.min(80,e-4),justifyContent:"flex-start"},l.createElement(S,null,ws(Uo))),l.createElement(I,{flexDirection:"column",borderStyle:"double",borderColor:"grey",paddingX:3,paddingY:1,width:Math.min(80,e-4)},l.createElement(S,{bold:!0,color:"white",textAlign:"center"},"\u{1F680} UPGRADE YOUR WORKFLOW"),l.createElement(I,{marginY:1,flexDirection:"column",alignItems:"left"},l.createElement(S,null,"You're in ",l.createElement(S,{bold:!0,color:"cyan"},n),", but the ",l.createElement(S,{bold:!0,color:"white"},"FluxFlow-CLI Companion")," is not installed."),l.createElement(I,{flexDirection:"column",marginY:1},l.createElement(S,{color:"gray"}," \u2705 Real-time file & cursor tracking"),l.createElement(S,{color:"gray"}," \u2705 Auto-open files created by agent"),l.createElement(S,{color:"gray"}," \u2705 Native DIFF viewer for AI edits"),l.createElement(S,{color:"gray"}," \u2705 Direct IDE context sharing"),l.createElement(S,{color:"gray"}," \u2705 Surgical Diagnostic Sync"),l.createElement(S,{color:"gray"}," \u2705 Native Right-Click \u276F Chat integration"),l.createElement(S,{color:"gray"}," \u2705 Live Status in IDE"),l.createElement(S,{color:"gray"}," \u2705 Clickable terminal-to-code links"))),l.createElement(I,{flexDirection:"column",marginTop:1},r.map((s,i)=>l.createElement(I,{key:i},l.createElement(S,{color:o===i?"yellow":"white",bold:o===i},o===i?" \u276F ":" ",s.label)))),l.createElement(I,{marginTop:1,alignItems:"center",justifyContent:"center"},l.createElement(S,{dimColor:!0,italic:!0},"(Use arrows to navigate, Enter to select)"))))},pa=Date.now(),vc="https://fluxflow-cli.onrender.com/changelog",ga="https://fluxflow-cli.onrender.com/",Ws=0,Ys=0,bd=ir.join(ir.dirname(Td(import.meta.url)),"../package.json"),Oc=JSON.parse(uo.readFileSync(bd,"utf8")),Uo=Oc.version,Cd=Oc.date||"2026-05-20",kd=({data:e,onResolve:t,onEdit:o})=>l.createElement(I,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},l.createElement(I,{paddingX:1},l.createElement(S,{color:"magenta",bold:!0,underline:!0},"\u{1F7E3} STEERING HINT RESOLUTION")),l.createElement(I,{paddingX:1,marginTop:1},l.createElement(S,null,"The agent already finished the task before your hint was consumed.")),l.createElement(I,{marginTop:1,backgroundColor:"#222",paddingX:2,width:"100%"},l.createElement(S,{italic:!0,color:"gray"},'"',e,'"')),l.createElement(I,{paddingX:1,marginTop:1},l.createElement(S,{color:"cyan"},"How would you like to proceed?")),l.createElement(I,{marginTop:0},l.createElement(go,{title:"Select Action",items:[{label:"Send Anyway",value:"send"},{label:"Edit Prompt",value:"edit"}],onSelect:n=>{n==="send"?t(e):o(e)}}))),Id=e=>{let t=[],o=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,n=0,r;for(;(r=o.exec(e))!==null;){let s=r[1],i=r.index+r[0].length-1,u=0,f=null,m=-1,c=-1;for(let a=i;a<e.length;a++){let d=e[a];if(f){if(d===f){let h=0;for(let p=a-1;p>=0&&e[p]==="\\";p--)h++;h%2===0&&(f=null)}}else if(d==='"'||d==="'"||d==="`")f=d;else if(d==="(")u++;else if(d===")"&&(u--,u===0)){c=a;let h=a+1;for(;h<e.length&&/\s/.test(e[h]);)h++;if(h<e.length&&e[h]==="]"){m=h;break}}}if(m!==-1){let a=e.substring(n,r.index);a.trim()&&t.push({type:"output",content:a});let d=e.substring(i+1,c);t.push({type:"tool",toolName:s.trim(),args:d.trim()}),n=m+1,o.lastIndex=n}else break}if(n<e.length){let s=e.substring(n);s.trim()&&t.push({type:"output",content:s})}return t},Md=(()=>{let e=null,t=0;return o=>{let n=Date.now();if(e&&n-t<5e3)return e;let r=[],s=i=>{try{let u=uo.readdirSync(i);for(let f of u){if(["node_modules",".git",".gemini","dist","build",".next",".cache","out"].includes(f))continue;let m=ir.join(i,f);uo.statSync(m).isDirectory()?s(m):r.push({name:f,relativePath:ir.relative(process.cwd(),m)})}}catch{}};return s(o),e=r,t=n,r}})()});import{spawn as Ad}from"child_process";import{fileURLToPath as $c}from"url";var vd=4096,Dd=$c(import.meta.url).endsWith(".js");if(Dd&&!process.execArgv.some(e=>e.includes("max-old-space-size")))Ad(process.execPath,[`--max-old-space-size=${vd}`,$c(import.meta.url),...process.argv.slice(2)],{stdio:"inherit"}).on("exit",t=>process.exit(t||0));else{let e=process.argv.slice(2),t=e.includes("--help")&&e[e.indexOf("--help")+1]==="commands",o=e.includes("--help")&&!t,n=e.includes("--version")||e.includes("-v"),r=e[0]==="--update";if(n||o||t||r){let h=await import("fs"),p=await import("path"),{fileURLToPath:y}=await import("url"),T=p.join(p.dirname(y(import.meta.url)),"../package.json"),E=JSON.parse(h.readFileSync(T,"utf8")).version;if(n&&(console.log(`v${E}`),process.exit(0)),o&&(console.log(`FluxFlow CLI Arguments:
|
|
643
643
|
--mode <flux|flow> Set startup mode (flux: Agent / flow: Chat)
|
|
644
644
|
--model <model_name> Set startup AI model
|
|
645
645
|
--key <key@provider> Set API key and provider
|
|
@@ -684,4 +684,4 @@ Selection: ${Le}`,isAskRecord:!0}]),ge(Le)}}),J("ask")})},async()=>{if(ve.curren
|
|
|
684
684
|
/docs View documentation
|
|
685
685
|
/fluxflow init Create FluxFlow.md template
|
|
686
686
|
/update check Check for new version
|
|
687
|
-
/update latest Install latest release`),process.exit(0)),
|
|
687
|
+
/update latest Install latest release`),process.exit(0)),r){let A=e[1];if(A==="check"){let $=e[2]==="latest";try{let O=(await(await fetch("https://registry.npmjs.org/fluxflow-cli",{cache:"no-store"})).json())["dist-tags"]?.latest;O||(console.error("Error: Could not retrieve latest version."),process.exit(1)),console.log($?`Latest version: v${O}`:O!==E?`A new version of FluxFlow is available: v${O} (current: v${E}). Run "fluxflow --update latest" to upgrade.`:`FluxFlow is up to date (v${E}).`)}catch(W){console.error("Error checking for updates:",W.message),process.exit(1)}process.exit(0)}else if(A==="latest"){console.log("Checking latest version and settings...");try{let D=(await(await fetch("https://registry.npmjs.org/fluxflow-cli",{cache:"no-store"})).json())["dist-tags"]?.latest;D||(console.error("Error: Could not retrieve latest version."),process.exit(1)),D===E&&(console.log(`FluxFlow is already up to date (v${E}).`),process.exit(0));let O=async()=>{let Y=(await import("react")).default,{useState:N}=Y,{render:ge,Box:ee,Text:Me}=await import("ink"),ce=(await import("ink-select-input")).default,ue=(await import("ink-text-input")).default;return new Promise(Xe=>{let _t=[{label:"NPM",value:"npm"},{label:"PNPM",value:"pnpm"},{label:"Yarn",value:"yarn"},{label:"Bun",value:"bun"},{label:"Custom Command",value:"custom"}],Ve=({label:qe,isSelected:mo})=>Y.createElement(ee,{width:"100%"},Y.createElement(Me,{bold:mo},"\u2514\u2500 ",mo?"\x1B[32m\u25CF\x1B[0m":"\u25CB"," ",qe)),Ee,ht=()=>{let[qe,mo]=N("select"),[Vt,ut]=N(""),ze=Ao=>{Ao.value==="custom"?mo("custom"):et({manager:Ao.value})},ot=Ao=>{et({manager:"custom",customCommand:Ao})};return qe==="custom"?Y.createElement(ee,{flexDirection:"column",marginY:1},Y.createElement(ee,{marginBottom:1},Y.createElement(Me,{color:"magenta",bold:!0},"\u{1F527} Enter custom update command:")),Y.createElement(ee,{flexDirection:"row"},Y.createElement(Me,{color:"cyan",bold:!0}," \u276F "),Y.createElement(ue,{value:Vt,onChange:ut,onSubmit:ot})),Y.createElement(ee,{marginTop:1},Y.createElement(Me,{color:"gray",dimColor:!0,italic:!0}," (Press Enter to confirm)"))):Y.createElement(ee,{flexDirection:"column",marginY:1},Y.createElement(ee,{marginBottom:1},Y.createElement(Me,{color:"magenta",bold:!0},"\u{1F4E6} Select a package manager for the update:")),Y.createElement(ce,{items:_t,onSelect:ze,itemComponent:Ve,indicatorComponent:()=>null}))},et=qe=>{Ee&&Ee(),Xe(qe)},{unmount:Ye}=ge(Y.createElement(ht,null));Ee=Ye})},M,P="",j;try{let{loadSettings:Y}=await Promise.resolve().then(()=>(fs(),Aa));j=await Y(),M=j?.systemSettings?.updateManager||j?.updateManager}catch{}{let Y=await O();M=Y.manager,P=Y.customCommand}let G="";M==="pnpm"?G=`pnpm add -g fluxflow-cli@${D}`:M==="bun"?G=`bun add -g fluxflow-cli@${D}`:M==="yarn"?G=`yarn global add fluxflow-cli@${D}`:M==="custom"?G=P||j?.customUpdateCommand||`npm install -g fluxflow-cli@${D}`:G=`npm install -g fluxflow-cli@${D}`,console.log(`Updating FluxFlow to v${D} using ${M}...`),console.log(`Running: ${G}`);let{execSync:q}=await import("child_process");q(G,{stdio:"inherit"}),console.log(`\x1B[32m\u2705 Update successful! FluxFlow updated to v${D}.\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:s}=await import("react"),{render:i}=await import("ink"),{default:u}=await Fc().then(()=>Pc);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=h=>{let p=h.map(String).join(" ");return f.some(y=>p.includes(y))};console.log=(...h)=>!d(h)&&m(...h),console.warn=(...h)=>!d(h)&&c(...h),console.error=(...h)=>!d(h)&&a(...h),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")),i(s.createElement(u,{args:process.argv.slice(2)}),{exitOnCtrlC:!1})}
|