fluxflow-cli 2.4.1 → 2.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/fluxflow.js +283 -273
- package/package.json +1 -1
package/dist/fluxflow.js
CHANGED
|
@@ -1,60 +1,60 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var xc=Object.defineProperty;var ie=(e,o)=>()=>(e&&(o=e(e=0)),o);var Kr=(e,o)=>{for(var t in o)xc(e,t,{get:o[t],enumerable:!0})};var aa={};Kr(aa,{BACKUPS_DIR:()=>xn,DATA_DIR:()=>Er,FLUXFLOW_DIR:()=>Wn,HISTORY_FILE:()=>Yn,LEDGER_FILE:()=>nn,LOGS_DIR:()=>Mo,MEMORIES_FILE:()=>Ht,PARSER_DIR:()=>yn,PATHS_FILE:()=>Vr,SECRET_DIR:()=>jt,SETTINGS_FILE:()=>io,TEMP_MEM_CHAT_FILE:()=>Yo,TEMP_MEM_FILE:()=>yo,USAGE_FILE:()=>Jt});import yc from"os";import xo from"path";import ra from"fs";import sa from"crypto";var Wn,io,ia,Er,Mo,jt,Yn,Jt,Ht,yo,Yo,xn,nn,Vr,yn,Gt=ie(()=>{Wn=xo.join(yc.homedir(),".fluxflow"),io=xo.join(Wn,"settings.json"),ia=null;try{if(ra.existsSync(io)){let e=ra.readFileSync(io,"utf8").trim(),o;if(e.startsWith("{"))o=JSON.parse(e);else{let t=e.split(":");if(t.length===2){let n=Buffer.from(t[0],"hex"),s=t[1],r=sa.createHash("sha256").update("fluxflow-cli-sanctuary-key").digest(),a=sa.createDecipheriv("aes-256-cbc",r,n),u=a.update(s,"hex","utf8");u+=a.final("utf8"),o=JSON.parse(u)}}if(o){let t=o.systemSettings||{};t.useExternalData&&t.externalDataPath&&(ia=t.externalDataPath)}}}catch{}Er=ia||Wn,Mo=xo.join(Er,"logs"),jt=xo.join(Er,"secret"),Yn=xo.join(jt,"history.json"),Jt=xo.join(Wn,"usage.json"),Ht=xo.join(jt,"memories.json"),yo=xo.join(jt,"memory-temp.json"),Yo=xo.join(jt,"temp-memory-chat.json"),xn=xo.join(Er,"backups"),nn=xo.join(jt,"ledger.json"),Vr=xo.join(jt,"path.json"),yn=xo.join(Er,"parsers")});import br from"fs";import Ps from"path";import qr from"crypto";var wc,Tc,la,ca,Cr,wn,ge,$e,zr,Jr,Oo=ie(()=>{wc=66,Tc=e=>{let o=Buffer.isBuffer(e)?e:Buffer.from(e),t=Buffer.alloc(o.length);for(let n=0;n<o.length;n++)t[n]=o[n]^wc;return t},la="aes-256-cbc",ca=qr.createHash("sha256").update("fluxflow-cli-sanctuary-key").digest(),Cr=e=>{let o=qr.randomBytes(16),t=qr.createCipheriv(la,ca,o),n=t.update(e,"utf8","hex");return n+=t.final("hex"),o.toString("hex")+":"+n},wn=e=>{let o=e.split(":");if(o.length!==2)throw new Error("Invalid AES format");let t=Buffer.from(o[0],"hex"),n=o[1],s=qr.createDecipheriv(la,ca,t),r=s.update(n,"hex","utf8");return r+=s.final("utf8"),r},ge=(e,o={})=>{try{if(!br.existsSync(e))return o;let t=br.readFileSync(e),n=t.toString("utf8").trim();if(n.startsWith("{")||n.startsWith("["))return JSON.parse(n);try{let r=wn(n);return JSON.parse(r)}catch{}let s=Tc(t).toString("utf8");if(s.startsWith("{")||s.startsWith("["))return JSON.parse(s);throw new Error("Unsupported or corrupt encryption format")}catch(t){return console.error(`Vault Read Error [${Ps.basename(e)}]:`,t.message),o}},$e=(e,o)=>{try{let t=Ps.dirname(e);br.existsSync(t)||br.mkdirSync(t,{recursive:!0});let n=JSON.stringify(o,null,2),s=Cr(n);br.writeFileSync(e,s,"utf8")}catch(t){console.error(`Vault Write Error [${Ps.basename(e)}]:`,t.message)}},zr=ge,Jr=$e});var es={};Kr(es,{getAPIKey:()=>bc,getProviderAPIKey:()=>Qr,getSearchSecrets:()=>kc,getSecret:()=>Cc,removeAPIKey:()=>_s,removeSecret:()=>ua,saveAPIKey:()=>Ic,saveProviderAPIKey:()=>Zr,saveSearchId:()=>Ac,saveSearchKey:()=>Mc,saveSecret:()=>rn});import Sc from"fs-extra";import Ec from"path";var Tn,bc,Qr,Zr,Cc,rn,kc,Ic,Mc,Ac,ua,_s,kr=ie(()=>{Oo();Gt();Tn=Ec.join(jt,"secrets.json"),bc=async()=>{try{let e=ge(Tn,{});if(e.API_KEY)return e.API_KEY}catch{}return null},Qr=async e=>{try{let o=ge(Tn,{});if(e==="Google")return o.GOOGLE_API_KEY||o.API_KEY||null;if(e==="DeepSeek")return o.DEEPSEEK_API_KEY||null;if(e==="OpenRouter")return o.OPENROUTER_API_KEY||null;if(e==="NVIDIA")return o.NVIDIA_API_KEY||null}catch{}return null},Zr=async(e,o)=>{e==="Google"?(await rn("GOOGLE_API_KEY",o),await rn("API_KEY",o)):e==="DeepSeek"?await rn("DEEPSEEK_API_KEY",o):e==="OpenRouter"?await rn("OPENROUTER_API_KEY",o):e==="NVIDIA"&&await rn("NVIDIA_API_KEY",o)},Cc=async e=>{try{return ge(Tn,{})[e]||null}catch{return null}},rn=async(e,o)=>{await Sc.ensureDir(jt);let t=ge(Tn,{});t[e]=o,$e(Tn,t)},kc=async()=>{try{let e=ge(Tn,{});return{key:e.GOOGLE_API_KEY||e.API_KEY,cx:e.SEARCH_ID}}catch{}return{key:null,cx:null}},Ic=async e=>rn("API_KEY",e),Mc=async e=>rn("GOOGLE_API_KEY",e),Ac=async e=>rn("SEARCH_ID",e),ua=async e=>{try{let o=ge(Tn,{});delete o[e],$e(Tn,o)}catch{}},_s=async()=>ua("API_KEY")});var da={};Kr(da,{loadSettings:()=>rr,saveSettings:()=>Sn});import Ir from"fs-extra";import Ns from"path";var nr,rr,vc,Sn,ts=ie(()=>{Gt();Oo();nr={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:""}},rr=async()=>{let e={...nr};try{if(await Ir.exists(io)){let o=zr(io);if(o.imageSettings&&o.imageSettings.apiKey)try{let t=o.imageSettings.apiKey,{saveSecret:n}=await Promise.resolve().then(()=>(kr(),es));await n("POLLINATIONS_API_KEY",t),o.imageSettings.apiKey="",Jr(io,o)}catch{}e={...nr,...o,quotas:{...nr.quotas,...o.quotas},systemSettings:{...nr.systemSettings,...o.systemSettings},profileData:{...nr.profileData,...o.profileData},imageSettings:{...nr.imageSettings,...o.imageSettings}}}}catch(o){console.error("Failed to load settings:",o)}try{let{getSecret:o}=await Promise.resolve().then(()=>(kr(),es)),t=await o("POLLINATIONS_API_KEY");t&&(e.imageSettings.apiKey=t)}catch{}if(e.showFullThinking===!1){e.showFullThinking=!0;try{Jr(io,e)}catch{}}return e},vc=async e=>{let{FLUXFLOW_DIR:o}=await Promise.resolve().then(()=>(Gt(),aa)),t=["logs","secret"];for(let n of t){let s=Ns.join(o,n),r=Ns.join(e,n);try{await Ir.exists(s)&&(await Ir.ensureDir(r),await Ir.copy(s,r,{overwrite:!0}))}catch(a){console.error(`Migration failed for ${n}:`,a)}}},Sn=async e=>{try{let o=await rr();if(!o.systemSettings.useExternalData&&e.systemSettings?.useExternalData&&e.systemSettings?.externalDataPath&&await vc(e.systemSettings.externalDataPath),e.imageSettings&&e.imageSettings.apiKey!==void 0){let{saveSecret:n,removeSecret:s}=await Promise.resolve().then(()=>(kr(),es)),r=e.imageSettings.apiKey;r?await n("POLLINATIONS_API_KEY",r):await s("POLLINATIONS_API_KEY")}let t={...o,...e};return t.imageSettings&&(t.imageSettings={...t.imageSettings,apiKey:""}),await Ir.ensureDir(Ns.dirname(io)),Jr(io,t),!0}catch(o){return console.error("Failed to save settings:",o),!1}}});import mo,{useState as vr,useEffect as Rs,useMemo as Bs,useCallback as os,useRef as ma}from"react";import{Box as Ar,Spacer as Dc,Text as Mr,useInput as Oc,measureElement as Lc}from"ink";function Fc(e,o){return e.replace(/\t/g," ".repeat(o))}function Us(e){return e==null?"":e.replace(/\r\n/g,`
|
|
3
3
|
`).replace(/\r/g,`
|
|
4
|
-
`)}var
|
|
5
|
-
`)+1,
|
|
6
|
-
`);return{preCursor:[{value:
|
|
7
|
-
`),
|
|
8
|
-
`),
|
|
9
|
-
`+e.slice(
|
|
10
|
-
`+e.slice(
|
|
11
|
-
`),s=[];if(o<=5)return e;let r=
|
|
12
|
-
`)},
|
|
4
|
+
`)}var fa,$c,pa,ha=ie(()=>{fa=({children:e,onHeightChange:o})=>{let t=ma(null),n=ma(void 0);return Rs(()=>{if(t.current){let{height:s}=Lc(t.current);n.current!==s&&(n.current=s,o?.(s))}}),mo.createElement(Ar,{ref:t,flexShrink:0,flexGrow:0,width:"100%"},e)},$c=({value:e,rows:o,maxRows:t,highlightStyle:n,textStyle:s,placeholder:r="",mask:a,showCursor:u=!0,focus:f=!0,tabSize:m=4,cursorIndex:c=0,highlight:l,refreshKey:d})=>{let[p,h]=vr(0),[S,w]=vr(0),[T,b]=vr(0),L=os((A,E=!1)=>{let q=Us(A);if(!E&&a)return q.replace(/[^\n]/g,a);let B=Fc(q,m);return E?B:B.replace(/@\[(.*?)\]/g,(V,_)=>{let K=_.indexOf("#"),Ue=_.indexOf(":L"),se=_,Te="";K!==-1?(se=_.slice(0,K),Te=_.slice(K)):Ue!==-1&&(se=_.slice(0,Ue),Te=_.slice(Ue));let De=se.replace(/\\/g,"/"),me=(process.cwd()||"").replace(/\\/g,"/");me&&De.toLowerCase().startsWith(me.toLowerCase()+"/")?De=De.slice(me.length+1):De.startsWith("./")&&(De=De.slice(2));let et=De.split("/");return`[${et[et.length-1]}${Te}]`})},[m,a]),{preCursor:P,postCursor:Y}=Bs(()=>{if(!e)return r&&!f?{preCursor:[{value:L(r,!0),type:"placeholder"}],postCursor:[]}:{preCursor:[{value:u&&f?" ":"",type:"cursor"}],postCursor:[]};let A=e.slice(0,c),E=e.slice(c);if(!f)return{preCursor:[{value:L(e)}],postCursor:[]};if(l&&l.end>l.start&&l.start>=0&&l.end<=e.length)return{preCursor:[{value:L(A.slice(0,l.start))},{value:L(A.slice(l.start,Math.min(l.end,c))),type:"highlight"},{value:L(A.slice(l.end))},{value:u&&f?" ":"",type:"cursor"}],postCursor:[{value:L(E.slice(0,Math.max(l.start-c,0)))},{value:L(E.slice(Math.max(l.start-c,0),Math.max(l.end-c,0))),type:"highlight"},{value:L(E.slice(Math.max(l.end-c,0)))}]};{let B=L(A),V=L(E),_=B.lastIndexOf(`
|
|
5
|
+
`)+1,K=V.indexOf(`
|
|
6
|
+
`);return{preCursor:[{value:B.slice(0,_)},{value:B.slice(_),type:"highlight"},{value:u&&f?" ":"",type:"cursor"}],postCursor:[{value:V.slice(0,K),type:"highlight"},{value:V.slice(K)}]}}},[c,u,f,e,r,a,l,L,d]),v=Bs(()=>S!==void 0?Math.max(o??t??1,Math.min(t??o??1,S)):1,[o,t,S]);Rs(()=>{if(T!==void 0&&v!==void 0){let A=T;h(E=>{let q=E,B=E+v;if(A<=q)return Math.max(0,A-1);if(A>B)return A-v;if(S){if(S<v)return 0;if(S<B)return S-v}return E})}},[T,v,S]);let D=os(A=>{switch(A){case"placeholder":return{...s,dimColor:!0};case"highlight":return n??s;case"cursor":return{...s,color:u&&f?"cyan":void 0,bold:u&&f,inverse:u&&f};default:return s}},[s,n,u,f]);return mo.createElement(Ar,{height:v,overflow:"hidden",flexDirection:"column",flexGrow:0,flexShrink:0},mo.createElement(Ar,{flexDirection:"column"},mo.createElement(Ar,{height:v,overflowY:"hidden",flexShrink:0,flexDirection:"column"},mo.createElement(Ar,{marginTop:-p,flexDirection:"column"},mo.createElement(fa,{onHeightChange:w},mo.createElement(Mr,null,P?.map((A,E)=>mo.createElement(Mr,{key:E,...D(A.type)},A.value)),Y?.map((A,E)=>mo.createElement(Mr,{key:E,...D(A.type)},A.value))))),mo.createElement(Dc,null)),mo.createElement(fa,{onHeightChange:b},mo.createElement(Mr,null,P?.map((A,E)=>mo.createElement(Mr,{key:E,...D(A.type)},A.value))))))},pa=({value:e,onChange:o,onSubmit:t,keyBindings:n,showCursor:s=!0,highlightPastedText:r=!1,focus:a=!0,lastFocusEventTime:u=0,columns:f=80,useCustomInput:m=(l,d)=>Oc(l,{isActive:d}),...c})=>{let[l,d]=vr(e.length),[p,h]=vr(0);Rs(()=>{l>e.length&&d(e.length)},[e,l]);let S=os(b=>{let P=Us(e).split(`
|
|
7
|
+
`),Y=Math.max(20,f-10),v=0,D=0,A=0;for(let E=0;E<P.length;E++){let B=P[E].length;if(b>=A&&b<=A+B){let _=b-A;return v+=Math.floor(_/Y),D=_%Y,{visualLine:v,visualCol:D}}let V=Math.max(1,Math.ceil(B/Y));v+=V,A+=B+1}return{visualLine:v,visualCol:D}},[e,f]),w=os((b,L)=>{let Y=Us(e).split(`
|
|
8
|
+
`),v=Math.max(20,f-10),D=0,A=0;for(let E=0;E<Y.length;E++){let B=Y[E].length,V=Math.max(1,Math.ceil(B/v));if(b>=D&&b<D+V){let _=(b-D)*v,K=Math.min(L,B-_),Ue=Math.max(0,K);return Math.min(A+_+Ue,A+B)}D+=V,A+=B+1}return e.length},[e,f]);m((b,L)=>{if(b==="\x1B[I"||b==="\x1B[O"||b==="[I"||b==="[O")return;let P=n?.submit??(D=>D.return&&D.ctrl),Y=n?.newline??(D=>D.return);if(P(L)){t?.(e);return}else if(Y(L)){let D=e.slice(0,l)+`
|
|
9
|
+
`+e.slice(l);o(D),d(l+1),h(0);return}if(L.tab||L.shift&&L.tab||L.ctrl&&b==="c")return;let v=0;if(b.length>1&&(v=b.length),L.upArrow){if(s){let{visualLine:D,visualCol:A}=S(l);if(D>0){let E=w(D-1,A);d(E),h(0)}}}else if(L.downArrow){if(s){let{visualLine:D,visualCol:A}=S(l),E=w(D+1,A);E!==l&&(d(E),h(0))}}else if(L.leftArrow)s&&(d(Math.max(0,l-1)),h(0));else if(L.rightArrow)s&&(d(Math.min(e.length,l+1)),h(0));else if(L.return){let D=e.slice(0,l)+`
|
|
10
|
+
`+e.slice(l);o(D),d(l+1),h(0)}else if(L.backspace||L.delete){if(l>0){let D=e.slice(0,l-1)+e.slice(l);o(D),d(l-1),h(0)}}else if(b){let D=e.slice(0,l)+b+e.slice(l);o(D),d(l+b.length),h(v)}},a);let T=Bs(()=>{if(r&&p>1)return{start:Math.max(0,l-p),end:l}},[l,p,r]);return mo.createElement($c,{...c,value:e,cursorIndex:l,highlight:T,showCursor:s,focus:a})}});import Pc from"os";var jo,ao,ga,ns,rs,ss,jn=ie(()=>{jo=(e,o)=>{if(!e)return"";let t=/\x1B\[[0-?]*[ -/]*[@-~]/g,n=e.split(`
|
|
11
|
+
`),s=[];if(o<=5)return e;let r=a=>a.replace(t,"").length;return n.forEach(a=>{if(r(a)<=o){s.push(a);return}let f=a.split(/(\s+)/),m="",c=0,l=a.match(/^(\s*)/),d=l?l[1]:"";f.forEach((p,h)=>{if(p.length===0)return;let S=r(p);if(c+S>o)if(m.trim().length>0)s.push(m.trimEnd()),m=d+p,c=r(m);else if(t.test(p))s.push(p),m=d,c=r(m);else{let w=p;for(;r(w)>o&&o>10;)s.push(w.substring(0,o)),w=w.substring(o);m=w,c=r(m)}else m+=p,c+=S}),(m.trimEnd().length>0||m===d)&&s.push(m.trimEnd())}),s.join(`
|
|
12
|
+
`)},ao=e=>{if(!e&&e!==0)return"0.0k";let o=typeof e=="string"?parseFloat(e):e;return o>=1e6?`${(o/1e6).toFixed(1)}m`:o>=1e3?`${(o/1e3).toFixed(1)}k`:o.toString()},ga=(e,o=40)=>{if(e=e.replace(Pc.homedir(),"~"),!e||e.length<=o)return e;let t=Math.floor((o-3)/2);return e.substring(0,t)+"..."+e.substring(e.length-t)},ns=e=>{let o=[],t=new Set;Object.keys(e).forEach(s=>{let r=s.match(/^(replaceContent|newContent|content_to_replace|content_to_add)(\d+)?$/);if(r){let a=r[2]?parseInt(r[2]):1;t.add(a)}});let n=Array.from(t).sort((s,r)=>s-r);for(let s of n){let r,a;if(s===1?(r=e.replaceContent1??e.content_to_replace??e.replaceContent,a=e.newContent1??e.content_to_add??e.newContent):(r=e[`replaceContent${s}`]??e[`content_to_replace${s}`],a=e[`newContent${s}`]??e[`content_to_add${s}`]),r!==void 0&&a!==void 0)o.push({replace:r,new:a});else if(r!==void 0||a!==void 0)return{error:`Mismatched replacement pair for index ${s}. Both replacement and new content must be provided.`}}return{patchPairs:o}},rs=(e,o)=>{let t=[],n=e.replace(/\r\n/g,`
|
|
13
13
|
`).replace(/\r/g,`
|
|
14
14
|
`),s=m=>m.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
|
|
15
15
|
`).replace(/\r/g,`
|
|
16
|
-
`),r=m=>m.match(/^\s*/)[0],
|
|
17
|
-
`).filter(d=>d.trim()!=="");if(c.length===0)return"";let
|
|
18
|
-
`).filter(
|
|
19
|
-
`).map((
|
|
20
|
-
`)},f=n;for(let m=0;m<o.length;m++){let c=o[m],
|
|
21
|
-
`).map(
|
|
22
|
-
`,w)+1,
|
|
23
|
-
`),
|
|
24
|
-
`).length,
|
|
25
|
-
`),
|
|
26
|
-
`,u="\u2550".repeat(88),f=0,m=null;if(t.forEach((c,
|
|
16
|
+
`),r=m=>m.match(/^\s*/)[0],a=m=>{let c=m.split(`
|
|
17
|
+
`).filter(d=>d.trim()!=="");if(c.length===0)return"";let l=r(c[0]);for(let d of c){let p=r(d);p.length<l.length&&(l=p)}return l},u=(m,c,l="")=>{if(!m||c===void 0)return m;let d=v=>{let D=v.split(`
|
|
18
|
+
`).filter(V=>V.trim()!=="");if(D.length===0)return{char:" ",size:4};let A=D[0].match(/^\s*/)[0];if(A.includes(" "))return{char:" ",size:1};let E=D.map(V=>V.match(/^\s*/)[0].length).filter(V=>V>0);if(E.length===0)return{char:" ",size:A.length||4};let q=(V,_)=>_?q(_,V%_):V;return{char:" ",size:E.reduce((V,_)=>q(V,_))||4}},p=d(c),h=d(m),S=a(c).length,w=(l.match(/^\s*/)||[""])[0].length,b=(w+S)/p.size,L=a(m).length/h.size,P=b-L;return m.split(`
|
|
19
|
+
`).map((v,D)=>{if(v.trim()===""&&D!==0)return"";let A=v.match(/^\s*/)[0].length/h.size,E=Math.max(0,A+P),q=E;if(D===0){let B=w/p.size;q=Math.max(0,E-B)}return p.char.repeat(q*p.size)+v.trimStart()}).join(`
|
|
20
|
+
`)},f=n;for(let m=0;m<o.length;m++){let c=o[m],l=s(c.replace||""),d=s(c.new||"");if(l===""&&d===""){t.push({success:!1,error:`Block ${m+1}: Empty replace and add content.`});continue}let p=l.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),h=null;if(l!==""&&f.includes(l))h=new RegExp(p,"g");else{let B=l.split(`
|
|
21
|
+
`).map(V=>V.trim()).filter(V=>V.length>0).map(V=>V.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\s+/g,"\\s*"));if(B.length>0){let V=B.join("\\s*");try{h=new RegExp(V,"g")}catch{h=new RegExp(p,"g")}}else h=new RegExp(p,"g")}let S=[...f.matchAll(h)];if(S.length===0){t.push({success:!1,error:`Block ${m+1}: Could not find match.`});continue}if(S.length>1){t.push({success:!1,error:`Block ${m+1}: Found ${S.length} matches (must be unique).`});continue}let w=S[0].index,T=S[0][0],b=f.lastIndexOf(`
|
|
22
|
+
`,w)+1,L=f.substring(b,w),P=u(d,T,L),Y=f.split(`
|
|
23
|
+
`),v=f.substring(0,w).split(`
|
|
24
|
+
`).length,D=[];for(let B=Math.max(0,v-4);B<v-1;B++)D.push({num:B+1,text:Y[B]});let A=T.split(`
|
|
25
|
+
`),E=[],q=v+A.length-1;for(let B=q;B<Math.min(Y.length,q+3);B++)E.push({num:B+1,text:Y[B]});t.push({success:!0,oldContent:T,newContent:P,originalStartLine:v,contextBefore:D,contextAfter:E}),f=f.substring(0,w)+P+f.substring(w+T.length)}return{content:f,results:t}},ss=(e,o,t,n=8)=>{if(!t||t.length===0)return"";let s=e.split(/\r?\n/),r=o.split(/\r?\n/),a=`[DIFF_START]
|
|
26
|
+
`,u="\u2550".repeat(88),f=0,m=null;if(t.forEach((c,l)=>{if(!c.success)return;if(m===null)for(f=Math.max(0,c.originalStartLine-4);f<c.originalStartLine-1;)a+=`[UI_CONTEXT] ${f+1} |${r[f]||""}
|
|
27
27
|
`,f++;else{let w=m,T=w.originalStartLine+w.oldContent.split(`
|
|
28
|
-
`).length-1;if(c.originalStartLine-T-1>=n){let
|
|
29
|
-
`,f++;for(
|
|
30
|
-
`,f=Math.max(f,c.originalStartLine-4);f<c.originalStartLine-1;)
|
|
31
|
-
`,f++}else for(;f<c.originalStartLine-1;)
|
|
28
|
+
`).length-1;if(c.originalStartLine-T-1>=n){let L=Math.min(r.length,f+3);for(;f<L;)a+=`[UI_CONTEXT] ${f+1} |${r[f]||""}
|
|
29
|
+
`,f++;for(a+=`[UI_CONTEXT] ${u}
|
|
30
|
+
`,f=Math.max(f,c.originalStartLine-4);f<c.originalStartLine-1;)a+=`[UI_CONTEXT] ${f+1} |${r[f]||""}
|
|
31
|
+
`,f++}else for(;f<c.originalStartLine-1;)a+=`[UI_CONTEXT] ${f+1} |${r[f]||""}
|
|
32
32
|
`,f++}let d=c.oldContent.split(`
|
|
33
|
-
`);d.forEach((w,T)=>{
|
|
34
|
-
`});let p=c.originalStartLine+d.length-1,h=s[p]||null,
|
|
35
|
-
`,f++;m=c}),m!==null){let c=Math.min(r.length,f+3);for(;f<c;)
|
|
36
|
-
`,f++}return
|
|
37
|
-
`)for(
|
|
33
|
+
`);d.forEach((w,T)=>{a+=`-${c.originalStartLine+T}|${w}
|
|
34
|
+
`});let p=c.originalStartLine+d.length-1,h=s[p]||null,S=f;if(h!==null){let w=l<t.length-1?(t[l+1].originalStartLine||r.length)+10:r.length;for(let T=f;T<w;T++){if(r[T]===h){S=T;break}T===r.length-1&&(S=r.length)}}else S=r.length;for(;f<S;)a+=`+${f+1}|${r[f]||""}
|
|
35
|
+
`,f++;m=c}),m!==null){let c=Math.min(r.length,f+3);for(;f<c;)a+=`[UI_CONTEXT] ${f+1} |${r[f]||""}
|
|
36
|
+
`,f++}return a+="[DIFF_END]",a}});import Xt from"react";import{Box as En,Text as bn}from"ink";var is,Ws=ie(()=>{jn();is=Xt.memo(({command:e,output:o,completed:t=!1,isFocused:n=!1,columns:s=80,isPty:r=!1})=>{let u=(m=>{if(!m)return"";let c=[[]],l=0,d=0,p="",h=/\x1b\[([0-9;]*?)([a-zA-Z])/g,S=0,w,T=L=>{for(let P=0;P<L.length;P++){let Y=L[P];if(Y===`
|
|
37
|
+
`)for(l++,d=0;l>=c.length;)c.push([]);else if(Y==="\r")d=0;else{for(;l>=c.length;)c.push([]);let v=c[l];for(;d>v.length;)v.push({char:" ",style:""});v[d]={char:Y,style:p},d++}}};for(;(w=h.exec(m))!==null;){T(m.substring(S,w.index));let L=w[1],P=w[2],Y=L?L.split(";").map(Number):[];if(P==="A"){let v=Y[0]||1;l=Math.max(0,l-v)}else if(P==="B"){let v=Y[0]||1;for(l=l+v;l>=c.length;)c.push([])}else if(P==="C"){let v=Y[0]||1;d=d+v}else if(P==="D"){let v=Y[0]||1;d=Math.max(0,d-v)}else if(P==="G"){let v=(Y[0]||1)-1;d=Math.max(0,v)}else if(P==="H"||P==="f"){let v=(Y[0]||1)-1,D=(Y[1]||1)-1;for(l=Math.max(0,v),d=Math.max(0,D);l>=c.length;)c.push([])}else if(P==="K"){let v=Y[0]||0;if(l<c.length){let D=c[l];if(v===0)D.length=d;else if(v===1)for(let A=0;A<d&&A<D.length;A++)D[A]={char:" ",style:""};else v===2&&(D.length=0)}}else if(P==="J"){let v=Y[0]||0;(v===2||v===3)&&(c.length=0,c.push([]),l=0,d=0)}else if(P==="m"){let v=w[0];v==="\x1B[0m"?p="":p=v}S=h.lastIndex}T(m.substring(S));let b=c.map(L=>{let P="",Y="";for(let v=0;v<L.length;v++){let D=L[v]||{char:" ",style:""};D.style!==Y&&(Y&&(P+="\x1B[0m"),P+=D.style,Y=D.style),P+=D.char}return Y&&(P+="\x1B[0m"),P});for(;b.length>0&&b[b.length-1]==="";)b.pop();return b.join(`
|
|
38
38
|
`)})(o).replace(/\n{3,}/g,`
|
|
39
39
|
|
|
40
|
-
`),f=r?u:u?jo(u,s-6):"";return
|
|
40
|
+
`),f=r?u:u?jo(u,s-6):"";return Xt.createElement(En,{flexDirection:"column",borderStyle:n?"double":"round",borderColor:t?"#334155":n?"yellow":"cyan",paddingX:2,paddingY:t?0:1,width:"100%"},Xt.createElement(En,{marginBottom:1,justifyContent:"space-between",width:"100%"},Xt.createElement(En,{flexShrink:1,paddingRight:2},Xt.createElement(bn,null,Xt.createElement(bn,{color:t?"gray":n?"yellow":"cyan",bold:!0},t?"\u{1F3C1} FINISHED:":"\u26A1 EXECUTING:"," "),Xt.createElement(bn,{color:t?"gray":"white"},e))),r&&Xt.createElement(En,{flexShrink:0,paddingX:1},Xt.createElement(bn,{color:t?"gray":"magenta",bold:!0},"ADVANCE"))),f?Xt.createElement(En,{marginTop:t?0:1,backgroundColor:r?void 0:"#0a0a0a",paddingX:1},Xt.createElement(bn,{color:t?"gray":void 0},f)):!t&&Xt.createElement(En,{marginTop:1,backgroundColor:r?void 0:"#0a0a0a",paddingX:1},Xt.createElement(bn,{color:"gray",italic:!0},"Waiting for output...")),Xt.createElement(En,{justifyContent:"space-between",marginTop:1},t?Xt.createElement(En,null):Xt.createElement(bn,{color:"gray",dimColor:!0,italic:!0},n?"Press TAB to unfocus, then double-press ESC to terminate.":"Double-press ESC to terminate if hanging."),Xt.createElement(bn,{color:t?"#475569":n?"yellow":"cyan",bold:!0},t?"\u25CF ARCHIVED":n?"\u25B6 TERMINAL FOCUSED":"\u25CF LIVE (Press TAB to focus)")))})});var _c,ve,sn=ie(()=>{_c=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",ve=(e=2)=>{let o=_c();return o==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)}});import C from"react";import{Box as G,Text as oe}from"ink";var Nc,Bc,Uc,Rc,xa,Cn,Wc,ya,Yc,jc,wa,Ta,Ys,Hc,Sa,Ea=ie(()=>{Ws();jn();sn();Nc={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"},Bc=e=>{if(!e)return e;let o=e.replace(/<\/think>(\r?\n){2}/gi,"</think>").replace(/(\r?\n){2}(?=\[?(?:tool:functions|tool\.functions|\s*turn\s*:))/gi,""),t="tool:functions.";for(;;){let s=o.toLowerCase().indexOf(t);if(s===-1)break;let r=s,a=!1,u=s-1;for(;u>=0&&/\s/.test(o[u]);)u--;u>=0&&o[u]==="["&&(r=u,a=!0);let f=0,m=!1,c=null,l=s;for(;l<o.length;){let d=o[l];if(!c&&(d==="'"||d==='"'||d==="`")?c=d:c&&d===c&&o[l-1]!=="\\"&&(c=null),c||(d==="("?(f++,m=!0):d===")"&&f--),m&&f===0&&!c){let p=l;if(a){let h=l+1;for(;h<o.length&&/\s/.test(o[h]);)h++;h<o.length&&o[h]==="]"&&(p=h)}o=o.substring(0,r)+o.substring(p+1);break}if(l++,l===o.length)return o=o.substring(0,r),o}}return o.replace(/\[TOOL RESULT\]:?\s*/gi,"").split(`
|
|
41
41
|
`).filter(n=>!n.trim().startsWith("SUCCESS:")&&!n.trim().startsWith("ERROR:")).join(`
|
|
42
|
-
`).replace(/\[\s*turn\s*:\s*(continue|finish)\s*\]/gi,"").replace(/\[\[END\]\]/gi,"").replace(/\[\s*turn\s*:?.*?$/gi,"").replace(/\n\s*turn\s*:?.*?$/gi,"").replace(/\[\s*$/gi,"").replace(/\n\nResponded on .*/g,"").replace(/\n\n\[Prompted on: .*\]/g,"").replace(/(\$?\\?\/?\\rightarrow\$?|\$\\rightarrow\$)/gi,"\u2192").replace(/(\$?\\?\/?\\leftarrow\$?|\$\\leftarrow\$)/gi,"\u2190").replace(/(\$?\\?\/?\\uparrow\$?|\$\\uparrow\$)/gi,"\u2191").replace(/(\$?\\?\/?\\downarrow\$?|\$\\downarrow\$)/gi,"\u2193").replace(/(\$?\\?\/?\\leftrightarrow\$?|\$\\leftrightarrow\$)/gi,"\u2194").replace(/@\[TerminalName:.*?, ProcessId:.*?\]/gi,"").replace(/\b(write_file|update_file|read_folder|view_file|exec_command|web_search|web_scrape|search_keyword|write_pdf|write_docx|generate_image)\b/gi,n
|
|
43
|
-
`),s=[],r=[],
|
|
42
|
+
`).replace(/\[\s*turn\s*:\s*(continue|finish)\s*\]/gi,"").replace(/\[\[END\]\]/gi,"").replace(/\[\s*turn\s*:?.*?$/gi,"").replace(/\n\s*turn\s*:?.*?$/gi,"").replace(/\[\s*$/gi,"").replace(/\n\nResponded on .*/g,"").replace(/\n\n\[Prompted on: .*\]/g,"").replace(/(\$?\\?\/?\\rightarrow\$?|\$\\rightarrow\$)/gi,"\u2192").replace(/(\$?\\?\/?\\leftarrow\$?|\$\\leftarrow\$)/gi,"\u2190").replace(/(\$?\\?\/?\\uparrow\$?|\$\\uparrow\$)/gi,"\u2191").replace(/(\$?\\?\/?\\downarrow\$?|\$\\downarrow\$)/gi,"\u2193").replace(/(\$?\\?\/?\\leftrightarrow\$?|\$\\leftrightarrow\$)/gi,"\u2194").replace(/@\[TerminalName:.*?, ProcessId:.*?\]/gi,"").replace(/\b(write_file|update_file|read_folder|view_file|exec_command|web_search|web_scrape|search_keyword|write_pdf|write_docx|generate_image)\b/gi,n=>Nc[n.toLowerCase()]||n).trim()},Uc=(e,o=80)=>{if(!e)return null;let t=o-10,n=jo(e.trim(),t);return C.createElement(G,{width:"100%"},C.createElement(oe,{italic:!0},C.createElement(Cn,{text:n,color:"gray"})))},Rc=e=>e.replace(/\\multiply|\\mul|\\times/g,"\xD7").replace(/\\div/g,"\xF7").replace(/\\cdot/g,"\u22C5").replace(/\\infty/g,"\u221E").replace(/\\pm/g,"\xB1").replace(/\\leq/g,"\u2264").replace(/\\geq/g,"\u2265").replace(/\\neq/g,"\u2260").replace(/\\sqrt\s*\{([^}]+)\}/g,"\u221A($1)").replace(/\\sqrt\s*(\w+|\d+)/g,"\u221A($1)").replace(/\\alpha/g,"\u03B1").replace(/\\beta/g,"\u03B2").replace(/\\theta/g,"\u03B8").replace(/\\pi/g,"\u03C0").replace(/\\approx/g,"\u2248").replace(/\\Delta/g,"\u0394").replace(/\\sigma/g,"\u03C3").replace(/\\sum/g,"\u03A3").replace(/\\prod/g,"\u03A0").replace(/\\rightarrow|\\to/g,"\u2192").replace(/\\left\b|\\right\b/g,"").replace(/\\left\(|\\right\)/g,o=>o.includes("left")?"(":")").replace(/\\left\[|\\right\]/g,o=>o.includes("left")?"[":"]").replace(/\\\{|\\\}/g,o=>o.includes("{")?"{":"}").replace(/\\text\s*\{([^}]+)\}/g,"$1").replace(/\\text\s+(\w+)/g,"$1").replace(/\\%/g,"%"),xa=(e,o)=>{if(!e)return null;let t=e.replace(/\\frac\s*\{([^{}]*)\}\s*\{([^{}]*)\}/g,"($1/$2)");t=Rc(t);let n=t.split(/(\\(?:mathbf|textbf|textit|underline|texttt)\{[^{}]*\})/g);return C.createElement(C.Fragment,{key:o},n.map((s,r)=>{if(s.startsWith("\\")){let a=s.match(/\\(\w+)\{([^{}]*)\}/);if(a){let u=a[1],f=a[2];return C.createElement(oe,{key:r,bold:u==="mathbf"||u==="textbf",italic:u==="textit",underline:u==="underline",color:u==="texttt"?"cyan":void 0},f)}}return s}))},Cn=C.memo(({text:e,color:o})=>{if(!e)return null;let t=e.split(/(```[\s\S]*?```|`[^`]+`|@\[.*?\]|\*\*.*?\*\*|\*.*?\*|\$.*?\$|\[.*?\]\s*\(.*?\)|\[.*?\]\s*\[.*?\]|https?:\/\/[^\s]+)/g);return C.createElement(oe,{color:o,wrap:"anywhere"},t.map((n,s)=>{if(!n)return null;if(n.startsWith("```")&&n.endsWith("```")){let r=n.slice(3,-3);return C.createElement(oe,{key:s,color:"cyan",backgroundColor:"#003333"}," ",r," ")}if(n.startsWith("**")&&n.endsWith("**"))return C.createElement(oe,{key:s,bold:!0,color:"white"},C.createElement(Cn,{text:n.slice(2,-2),color:"white"}));if(n.startsWith("*")&&n.endsWith("*"))return C.createElement(oe,{key:s,italic:!0,color:"gray"},C.createElement(Cn,{text:n.slice(1,-1),color:"gray"}));if(n.startsWith("`")&&n.endsWith("`")){let r=n.slice(1,-1),a=r.replace(/@\[(.*?)\]/g,(f,m)=>m.split("/").pop().split("\\").pop().replace(/:L/gi,"#L")),u=r.includes("@[");return C.createElement(oe,{key:s,color:"cyan",bold:u,backgroundColor:u?"#111124":"#003333"}," ",a," ")}if(n.startsWith("@[")&&n.endsWith("]")){let a=n.slice(2,-1).split("/").pop().split("\\").pop().replace(/:L/gi,"#L");return C.createElement(oe,{key:s,color:"cyan",bold:!0,backgroundColor:"#111124"}," ",a," ")}if(n.startsWith("$")&&n.endsWith("$")){let r=n.slice(1,-1);return C.createElement(oe,{key:s,color:"yellow"},xa(r,s))}if(n.startsWith("[")&&(n.includes("](")||n.includes("] ("))){let r=n.match(/\[(.*?)\]\s*\((.*?)\)/);if(r)return C.createElement(oe,{key:s},C.createElement(oe,{color:"cyan",underline:!0,bold:!0},r[1]),C.createElement(oe,{color:"gray",dimColor:!0,italic:!0}," (",r[2],")"))}if(n.startsWith("[")&&(n.includes("][")||n.includes("] ["))){let r=n.match(/\[(.*?)\]\s*\[(.*?)\]/);if(r)return C.createElement(oe,{key:s},C.createElement(oe,{color:"cyan",underline:!0,bold:!0},r[1]),C.createElement(oe,{color:"gray",dimColor:!0,italic:!0}," [",r[2],"]"))}return n.startsWith("http")?C.createElement(oe,{key:s,color:"cyan",underline:!0,italic:!0},n):xa(n,s)}))}),Wc=C.memo(({buffer:e,terminalWidth:o=80})=>{if(e.length<2)return null;let t=e.map(f=>{let m=f.split("|");return m[0]!==void 0&&m[0].trim()===""&&m.shift(),m.length>0&&m[m.length-1].trim()===""&&m.pop(),m.map(c=>c.trim())}),n=t[0],s=t.slice(2),r=Math.floor(100/n.length),a=o-8,u=Math.floor(a/n.length)-2;return C.createElement(G,{flexDirection:"column",borderStyle:"round",borderColor:"#454545ff",paddingX:1,marginY:0,width:"100%",flexGrow:1},C.createElement(G,{flexDirection:"row",borderStyle:"single",borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1,borderColor:"#444",marginBottom:1,paddingBottom:0,width:"100%"},n.map((f,m)=>C.createElement(G,{key:m,flexBasis:`${r}%`,flexGrow:1,flexShrink:0,paddingRight:2},C.createElement(Cn,{text:jo(f,u),color:"cyan"})))),s.map((f,m)=>C.createElement(G,{key:m,flexDirection:"row",marginBottom:m===s.length-1?0:1,width:"100%"},f.map((c,l)=>C.createElement(G,{key:l,flexBasis:`${r}%`,flexGrow:1,flexShrink:0,paddingRight:2,flexDirection:"column"},C.createElement(Cn,{text:jo(c,u),color:"white"}))))))}),ya=C.memo(({text:e,color:o="white",columns:t=80})=>{if(!e)return null;let n=e.split(`
|
|
43
|
+
`),s=[],r=[],a=[],u=f=>{r.length>0&&(s.push(C.createElement(Wc,{key:`table-${f}`,buffer:[...r],terminalWidth:t})),r=[]),a.length>0&&(s.push(C.createElement(G,{key:`quote-${f}`,borderStyle:"bold",borderLeft:!0,borderRight:!1,borderTop:!1,borderBottom:!1,borderColor:"gray",paddingLeft:1,marginY:1,flexDirection:"column"},a.map((m,c)=>C.createElement(Cn,{key:c,text:m,color:"gray"})))),a=[])};return n.forEach((f,m)=>{let c=f.trim(),l=c.startsWith("|"),d=c.startsWith(">");if(l)a.length>0&&u(m),r.push(f);else if(d)r.length>0&&u(m),a.push(c.replace(/^>\s*/,""));else{if(u(m),c===""){s.push(C.createElement(G,{key:m,height:1}));return}if(c==="---"||c==="***"||c==="___"){s.push(C.createElement(G,{key:m,marginY:1,borderStyle:"single",borderTop:!0,borderBottom:!1,borderLeft:!1,borderRight:!1,width:"100%",borderColor:"#333"}));return}let p=c.match(/^(#{1,6})\s+(.*)/);if(p){let b=p[1].length,L=p[2];s.push(C.createElement(G,{key:m,marginTop:1,marginBottom:1,width:"100%"},C.createElement(oe,{bold:!0,color:b===1?"cyan":b===2?"magenta":b===3?"yellow":b===4?"green":b===5?"blue":"white",underline:!0},L.toUpperCase())));return}let h=c.startsWith("* ")||c.startsWith("- "),S=/^\d+\.\s/.test(c),w=f.includes("\u2588")||f.includes("\u2554")||f.includes("\u255A")||f.includes("\u2550"),T="";if(w)T=f;else if(h||S){let b=h?" \u2022 ":c.match(/^\d+\.\s/)[0],L=" ".repeat(b.length),P=jo(c.replace(/^[\*\-\d+\.]+\s/,""),t-(b.length+6));T=b+P.split(`
|
|
44
44
|
`).join(`
|
|
45
|
-
`+
|
|
46
|
-
`);return
|
|
47
|
-
`),c=String(m.length).length;return
|
|
48
|
-
`),c=String(m.length).length;return
|
|
49
|
-
`).map((
|
|
45
|
+
`+L)}else T=jo(c,t-4);s.push(C.createElement(G,{key:m,width:"100%"},C.createElement(Cn,{text:T,color:o})))}}),u("final"),C.createElement(G,{flexDirection:"column",width:t-2},s)}),Yc=C.memo(({line:e,columns:o=80})=>{let t=e.includes("[UI_CONTEXT]"),n=e.replace("[UI_CONTEXT]","");if(t&&n.includes("\u2550"))return C.createElement(G,{backgroundColor:"#1a1a1a",paddingX:1,width:"100%"},C.createElement(oe,{color:"gray",dimColor:!0},"\u2550".repeat(Math.max(10,o-4))));let s=n.startsWith("-"),r=n.startsWith("+"),a=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,l=s?"#3a0c0c":r?"#0c3a1a":"#1a1a1a",d=s?"#ff4d4d":r?"#4dff88":t?"gray":"white";return C.createElement(G,{backgroundColor:l,paddingX:1,width:"100%"},C.createElement(G,{width:5,flexShrink:0},C.createElement(oe,{color:s?"#cf3a3a":r?"#3acf65":"gray",dimColor:t},m)),C.createElement(G,{width:2,flexShrink:0,marginLeft:1},C.createElement(oe,{color:d,bold:!0},s?"-":r?"+":" ")),C.createElement(G,{flexGrow:1,marginLeft:1},C.createElement(oe,{color:d,dimColor:t},jo(c,o-14))))}),jc=C.memo(({text:e,columns:o=80})=>{let t=e.match(/\[DIFF_START\]([\s\S]*?)\[DIFF_END\]/),s=(t?t[1].trim():"").split(`
|
|
46
|
+
`);return C.createElement(G,{flexDirection:"column",width:o-3,marginBottom:0},C.createElement(G,{flexDirection:"column",backgroundColor:"#1a1a1a",paddingY:0,width:"100%"},s.map((r,a)=>C.createElement(Yc,{key:a,line:r,columns:o-3}))))}),wa=C.memo(({text:e,columns:o=80})=>{if(!e)return null;if(e.includes("[DIFF_START]"))return C.createElement(jc,{text:e,columns:o});if(e.includes("- Content Preview:")){let t=e.split("- Content Preview:"),n=t[0],s=t[1]||"",r="Check if Starting and Ending matches",a=s.split(r),u=a[0]?.trim()||"",f=a[1]?`${r}${a[1]}`:"",m=u.split(`
|
|
47
|
+
`),c=String(m.length).length;return C.createElement(G,{flexDirection:"column",width:o-3},C.createElement(G,{flexDirection:"column",borderStyle:"round",borderColor:"#444",paddingX:1,width:"100%"},C.createElement(G,{alignSelf:"flex-end",marginTop:-1,marginRight:1},C.createElement(oe,{backgroundColor:"#444",color:"white"}," FILE SNAPSHOT ")),C.createElement(G,{flexDirection:"column",paddingY:1,width:"100%"},m.map((l,d)=>C.createElement(G,{key:d,width:"100%"},C.createElement(G,{width:c+2,flexShrink:0},C.createElement(oe,{color:"gray",dimColor:!0},String(d+1).padStart(c," ")," ")),C.createElement(G,{flexGrow:1},C.createElement(oe,{color:"white"},l)))))))}if(e.includes("```")){let t=e.split(/(```\w*\n?[\s\S]*?(?:```|$))/g);return C.createElement(G,{flexDirection:"column",width:o-3},t.map((n,s)=>{if(n.startsWith("```")){let a=n.match(/```(\w*)\n?([\s\S]*?)(?:```|$)/),u=a?a[1]:"code",m=(a?a[2]:n.replace(/^```\w*\n?/,"").replace(/```$/,"")).trimEnd().split(`
|
|
48
|
+
`),c=String(m.length).length;return C.createElement(G,{key:s,flexDirection:"column",marginY:0,backgroundColor:"#111",borderStyle:"round",borderColor:"#333",paddingX:1,width:"100%"},C.createElement(G,{alignSelf:"flex-end",marginTop:-1,marginRight:1},C.createElement(oe,{backgroundColor:"#333",color:"white"}," ",u.toUpperCase()," ")),C.createElement(G,{flexDirection:"column",paddingY:1,width:"100%"},m.map((l,d)=>C.createElement(G,{key:d,width:"100%"},C.createElement(G,{width:c+2,flexShrink:0},C.createElement(oe,{color:"gray",dimColor:!0},String(d+1).padStart(c," ")," ")),C.createElement(G,{flexGrow:1},C.createElement(oe,{color:"cyan"},l))))))}let r=n;return s>0&&(r=r.replace(/^[\r\n]+/,"")),s<t.length-1&&(r=r.replace(/[\r\n]+$/,"")),r?C.createElement(ya,{key:s,text:r,columns:o-3}):null}))}return C.createElement(ya,{text:e,columns:o-3})}),Ta=e=>{let o=Math.round(e/1e3);if(o<=0)return"0s";let t=Math.floor(o/60),n=o%60;return t>0?`${t}m ${n}s`:`${o}s`},Ys=C.memo(({msg:e,showFullThinking:o,columns:t=80})=>{let n=e.role==="system"&&(e.text?.includes("[DIFF_START]")||e.text?.includes("- Content Preview:")),s=e.role==="system"&&e.text?.includes("[TOOL RESULT]: ERROR:")&&!e.text?.includes("[DIFF_START]")&&(e.toolName==="update_file"||e.text?.includes("Could not find exact match")),r=e.isTerminalRecord;if(e.isHomeWarning)return C.createElement(G,{marginBottom:1,paddingX:1,width:"100%"},C.createElement(G,{flexDirection:"column",borderStyle:"round",borderColor:"red",padding:0,width:"100%"},C.createElement(G,{paddingX:1,backgroundColor:"#3a0000"},C.createElement(oe,{color:"red",bold:!0},e.text)),C.createElement(G,{paddingX:1,marginTop:1,marginBottom:1},C.createElement(oe,{color:"white"},e.subText))));if(e.isLogo)return C.createElement(G,{flexDirection:"column",alignItems:"center",width:"100%",marginY:1},C.createElement(oe,null,e.text));if(e.id&&String(e.id).startsWith("welcome"))return C.createElement(G,{flexDirection:"column",alignItems:"center",width:"100%",marginY:1},C.createElement(G,{borderStyle:"round",borderColor:"gray",paddingX:3,paddingY:0},C.createElement(oe,{color:"cyan",bold:!0},e.text.trim())));if(e.isVisualFeedback)return C.createElement(G,{marginBottom:0,marginTop:0,paddingX:1,width:"100%"},C.createElement(oe,{color:"white"},e.text));if(s)return C.createElement(G,{marginBottom:1},C.createElement(G,{flexDirection:"column",borderStyle:"round",borderColor:"red",paddingX:1,paddingY:0},C.createElement(oe,{color:"red",bold:!0,underline:!0},"\u274C PATCH FAILED"),C.createElement(G,{marginTop:1},C.createElement(oe,{color:"red"},"Patch failed: ",C.createElement(oe,{color:"white",bold:!0},"Model generated malformed edit.")))));if(e.role==="system"&&e.text?.includes("[TOOL RESULT]")&&!n&&!r&&!s)return null;if(e.isImageStats)return C.createElement(G,{marginBottom:1,paddingX:1,width:"100%"},C.createElement(G,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",padding:0,width:"100%"},C.createElement(G,{paddingX:1,backgroundColor:"#0e1b21"},C.createElement(oe,{color:"cyan",bold:!0},"\u{1F4B3} IMAGE STATS")),C.createElement(G,{paddingX:1,marginTop:1,marginBottom:1,flexDirection:"column"},e.text.split(`
|
|
49
|
+
`).map((l,d)=>C.createElement(oe,{key:d,color:"white"},l)))));if(e.isAskRecord){let l=e.text.match(/Selection: (.*)/),d=l?l[1]:"No selection",p=ve(2);return C.createElement(G,{marginBottom:1,paddingX:1,width:"100%"},C.createElement(G,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},C.createElement(G,{paddingX:1},C.createElement(oe,{color:"cyan",bold:!0},"\u{1F4AC} AGENT REQUEST: RESOLVED")),C.createElement(G,{paddingX:1,marginTop:1,marginBottom:1},C.createElement(oe,{color:"white"},"Selection: ",C.createElement(oe,{color:"yellow",bold:!0},d)))))}if(e.isAboutRecord)return C.createElement(G,{marginBottom:1,paddingX:1,width:"100%"},C.createElement(G,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},C.createElement(G,{paddingX:1},C.createElement(oe,{color:"cyan",bold:!0},"\u{1F4A0} ABOUT FLUX FLOW")),C.createElement(G,{paddingX:1,marginTop:1,marginBottom:1},C.createElement(oe,null,e.text))));if(e.isUpdateNotification)return C.createElement(G,{marginBottom:1,paddingX:1,width:"100%"},C.createElement(G,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},C.createElement(G,{paddingX:1},C.createElement(oe,{color:"cyan",bold:!0},"\u{1F680} FLUX FLOW UPDATE AVAILABLE")),C.createElement(G,{paddingX:1,marginTop:1,marginBottom:1},C.createElement(wa,{text:e.text,columns:t}))));if(e.isHelpRecord)return C.createElement(G,{marginBottom:1,paddingX:1,width:"100%"},C.createElement(G,{flexDirection:"column",borderStyle:"round",borderColor:"magenta",paddingX:2,paddingY:1,width:"100%"},C.createElement(oe,{color:"magenta",bold:!0,underline:!0},"\u{1F4DC} COMMAND REFERENCE"),C.createElement(G,{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:"/fluxflow",desc:"Project management"},{cmd:"/update",desc:"Check/Install updates"}].map((d,p)=>C.createElement(G,{key:p,flexDirection:"row"},C.createElement(G,{width:15},C.createElement(oe,{color:"cyan",bold:!0},d.cmd)),C.createElement(oe,{color:"gray"}," - ",d.desc))))));if(e.isTerminalRecord){let l=e.text.match(/COMMAND: (.*)/),d=e.text.match(/PTY: (true|false)/),p=e.text.match(/OUTPUT: ([\s\S]*)/),h=l?l[1]:"Unknown",S=d?d[1]==="true":!1,w=p?p[1]:"";return C.createElement(G,{marginBottom:1,paddingX:1,width:"100%"},C.createElement(is,{command:h,output:w,completed:!0,columns:t,isPty:S}))}let[u,f]=C.useState(!e.isStreaming),m=C.useMemo(()=>Bc(e.text),[e.text]);C.useEffect(()=>{e.isStreaming&&f(!1)},[e.id]);let c=C.useMemo(()=>e.role==="think"&&!o?"Thinking...":e.isStreaming?m:m.trimEnd(),[m,e.role,o,e.isStreaming]);return C.createElement(G,{marginBottom:e.role==="think"?0:e.role==="user"?1:e.role==="agent"?0:1,marginTop:(e.role==="think"||e.role==="user"||e.role==="agent",0),flexDirection:"column",flexShrink:0,width:"100%",flexGrow:1},e.role==="user"?C.createElement(G,{backgroundColor:"#262626",paddingX:1,paddingY:1,width:"100%",flexDirection:"column"},jo(c.replace(/\r\n/g,`
|
|
50
50
|
`).replace(/\r/g,`
|
|
51
51
|
`).replace(/\\\n/g,`
|
|
52
52
|
`).replace(/\\$/,""),t-6).split(`
|
|
53
|
-
`).map((
|
|
54
|
-
`),columns:t}),e.memoryUpdated&&
|
|
53
|
+
`).map((l,d)=>C.createElement(G,{key:d,flexDirection:"row",width:"100%"},C.createElement(G,{flexShrink:0,width:2},C.createElement(oe,{bold:!0,color:"white"},d===0?"\u276F":" ")),C.createElement(G,{flexGrow:1,marginLeft:1},C.createElement(Cn,{text:l,color:e.color||"white"}))))):e.role==="think"?C.createElement(G,{flexDirection:"column",marginTop:0,marginBottom:0,paddingX:1,width:"100%"},e.isStreaming&&!e.duration?C.createElement(oe,{bold:!0,color:"white"},"\u2727 Thinking..."):C.createElement(oe,{bold:!0,color:"white"},"\u2726 Thought",e.duration?C.createElement(oe,{color:"gray"}," for ",C.createElement(oe,{bold:!0,color:"cyan"},Ta(e.duration))):""),C.createElement(G,{borderStyle:"single",borderLeft:!0,borderRight:!1,borderTop:!1,borderBottom:!1,paddingLeft:2,paddingTop:1,paddingBottom:1,flexDirection:"column",width:"100%"},Uc(c,t))):C.createElement(G,{flexDirection:"column",paddingX:1,marginTop:0,width:"100%"},C.createElement(wa,{text:c.replace(/ \|\n\n/g,` |
|
|
54
|
+
`),columns:t}),e.memoryUpdated&&C.createElement(G,{marginTop:1,width:"100%"},C.createElement(oe,{color:"yellow",italic:!0},"\u2728 [Memory Updated]")),e.role==="agent"&&e.workedDuration?C.createElement(G,{marginTop:1,marginBottom:2,width:"100%"},C.createElement(oe,null,"["),C.createElement(oe,{color:"gray"},"\u26A1 Worked for ",C.createElement(oe,{bold:!0,color:"cyan"},Ta(e.workedDuration))),C.createElement(oe,null,"]")):null))}),Hc=C.memo(({messages:e,showFullThinking:o,columns:t=80})=>C.createElement(G,{flexDirection:"column",width:"100%"},e.map((n,s)=>C.createElement(Ys,{key:n.id||s,msg:n,showFullThinking:o,columns:t})))),Sa=Hc});import qe from"react";import{Box as an,Text as Kt}from"ink";var Gc,ba,Ca=ie(()=>{jn();Gc=qe.memo(({mode:e,thinkingLevel:o,tokens:t="0.0k",tokensTotal:n="0.0k",chatId:s="NEW-SESSION",isMemoryEnabled:r=!0,apiTier:a="Free",aiProvider:u="Google"})=>{let f=e==="Flux"?"yellow":"cyan",m=e==="Flux"?"\u26A1":"\u{1F30A}",c=256e3;return(u==="DeepSeek"||u==="NVIDIA"||u==="Google"&&a==="Paid")&&(c=4e5),qe.createElement(an,{borderStyle:"round",borderColor:"gray",flexDirection:"row",justifyContent:"space-between",paddingX:1,width:"100%"},qe.createElement(an,null,qe.createElement(an,{marginRight:1},qe.createElement(Kt,{color:f,bold:!0},m," ",e.toUpperCase())),qe.createElement(Kt,{color:"gray",dimColor:!0},"\u2503 "),qe.createElement(an,{marginX:1},qe.createElement(Kt,{color:"magenta"},"\u{1F9E0} ",o)),qe.createElement(Kt,{color:"gray",dimColor:!0},"\u2503 "),qe.createElement(an,{marginX:1},qe.createElement(Kt,{color:"gray"},"MEM: "),qe.createElement(Kt,{color:r?"green":"red",bold:!0},r?"ON":"OFF"))),qe.createElement(an,{flexGrow:1,justifyContent:"center",paddingX:2},qe.createElement(Kt,null,"\u{1F4C1}"),qe.createElement(Kt,{color:"gray",italic:!0}," ",ga(process.cwd(),35))),qe.createElement(an,null,qe.createElement(Kt,{color:"gray",dimColor:!0},"\u2503 "),qe.createElement(an,{marginX:1},qe.createElement(Kt,null,"\u2728"),qe.createElement(Kt,{color:"blue"}," ",ao(n)," ",qe.createElement(Kt,{dimColor:!0},"(",(t/c*100).toFixed(0),"%)"))),qe.createElement(Kt,{color:"gray",dimColor:!0},"\u2503 "),qe.createElement(an,{marginLeft:1},qe.createElement(Kt,null,"\u{1F194}"),qe.createElement(Kt,{color:"gray",dimColor:!0,italic:!0}," ",s),(a==="Custom"||a==="Paid")&&qe.createElement(Kt,{color:"gray",dimColor:!0}," | ",qe.createElement(Kt,{color:"green",bold:!0},"PAID")))))}),ba=Gc});import Lo from"react";import{Box as sr,Text as as}from"ink";import Xc from"ink-select-input";function fo({title:e,subtitle:o,items:t,onSelect:n}){return Lo.createElement(sr,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,marginTop:1,flexShrink:0,width:"100%"},Lo.createElement(sr,{paddingX:1,paddingY:0,marginBottom:o?0:1},Lo.createElement(as,{color:"magenta",bold:!0},"\u{1F527} ",typeof e=="string"?e.toUpperCase():e)),o&&Lo.createElement(sr,{paddingX:1,marginBottom:1},Lo.createElement(as,{color:"yellow",dimColor:!0,italic:!0}," ",o)),Lo.createElement(sr,{flexDirection:"column",width:"100%"},Lo.createElement(Xc,{items:t,onSelect:n,itemComponent:Kc,indicatorComponent:()=>null})),Lo.createElement(sr,{paddingX:1,marginTop:1},Lo.createElement(as,{color:"gray",dimColor:!0,italic:!0},"(Arrows to select \u2022 Enter to confirm)")))}var Kc,ka=ie(()=>{Kc=({label:e,isSelected:o})=>{let t=e==="Cancel"||e==="Back"||e.toLowerCase().includes("exit")||e.toLowerCase().includes("back");return Lo.createElement(sr,{marginTop:t?1:0,backgroundColor:o?"#2a2a2a":void 0,paddingX:1,width:"100%"},Lo.createElement(as,{color:o?"cyan":"white",bold:o},o?"\u276F ":" ",e))}});var re,Qt=ie(()=>{re=e=>{let o={};if(!e)return o;let t=0;for(;t<e.length;){for(;t<e.length&&/[\s,]/.test(e[t]);)t++;if(t>=e.length)break;let n=e.substring(t).match(/^(\w+)\s*=\s*/);if(!n){t++;continue}let s=n[1];t+=n[0].length;let r="";if(t<e.length&&(e[t]==='"'||e[t]==="'"||e[t]==="`")){let a=e[t];t++;let u=t,f=-1,m=t;for(;m<e.length;){let l=e.indexOf(a,m);if(l===-1)break;let d=0;for(let w=l-1;w>=0&&e[w]==="\\";w--)d++;if(d%2!==0){m=l+1;continue}let p=e.substring(l+1),h=p.trim(),S=h===""||/^,\s*\w+\s*=/.test(h)||h.startsWith(")")&&(h.length===1||/^\)\s*([,\]\s]|tool:)/i.test(h));if(S&&p.startsWith(`
|
|
55
55
|
`)){let w=h.split(`
|
|
56
|
-
`)[0];if(!w.includes("=")&&!w.includes(")")){m=
|
|
57
|
-
`;case"r":return"\r";case"t":return" ";case"\\":return"\\";default:return d===
|
|
56
|
+
`)[0];if(!w.includes("=")&&!w.includes(")")){m=l+1;continue}}if(S){f=l;break}m=l+1}f!==-1?(r=e.substring(u,f),t=f+1):(r=e.substring(u),t=e.length);let c=s.toLowerCase().includes("path")||["dest","source","to","from"].includes(s.toLowerCase());r=r.replace(/\\(.)/g,(l,d)=>{switch(d){case"n":return`
|
|
57
|
+
`;case"r":return"\r";case"t":return" ";case"\\":return"\\";default:return d===a?a:l}})}else if(t<e.length&&e[t]==="["){let a=0,u=null,f=t,m=-1;for(let c=t;c<e.length;c++){let l=e[c];if(u&&l===u){let d=0;for(let p=c-1;p>=0&&e[p]==="\\";p--)d++;d%2===0&&(u=null)}else!u&&(l==='"'||l==="'"||l==="`")&&(u=l);if(!u&&(l==="["?a++:l==="]"&&a--,a===0)){m=c;break}}if(m!==-1){r=e.substring(f,m+1),t=m+1;try{let c=r.trim();c.startsWith("'")||c.includes("'")}catch{}}else r=e.substring(f),t=e.length}else{let a=e.substring(t),u=a.match(/,\s*\w+\s*=|(?:\s*\)\s*(?:$|\]))/);if(u){let f=u.index;r=a.substring(0,f).trim(),t+=f}else r=a.trim(),t=e.length}r==="true"?r=!0:r==="false"?r=!1:typeof r=="string"&&!isNaN(r)&&r.trim()!==""&&(r=Number(r)),typeof r=="string"&&(s.toLowerCase().includes("path")||["dest","source","to","from"].includes(s.toLowerCase()))&&(r=r.replace(/\x0C/g,"\\f").replace(/\x0D/g,"\\r").replace(/\x0B/g,"\\v").replace(/\x08/g,"\\b")),o[s]=r}return o}});import{execSync as Vc}from"child_process";var Dr,ir,Ia,js=ie(async()=>{await Or();Dr=null,ir=()=>{if(process.platform!=="win32")return!1;if(Dr!==null)return Dr;try{Vc('powershell.exe -NoProfile -Command "exit"',{stdio:"ignore"}),Dr=!0}catch{Dr=!1}return Dr},Ia=(e,o,t,n)=>`
|
|
58
58
|
-- TOOL DEFINITIONS --
|
|
59
59
|
Access to internal tools. MUST use the exact syntax on a new line: [tool:functions.ToolName(args)]
|
|
60
60
|
|
|
@@ -80,36 +80,36 @@ ${e==="Flux"?`- PROJECT TOOLS (path = relative to CWD, path separator: '/') -
|
|
|
80
80
|
4. [tool:functions.PatchFile(path="...", replaceContent1="exact string", newContent1="...", ...MAX 10)]. Surgical Patch. **Multiple patch on same file/path? Use replaceContent2, newContent2 etc >>> multiple spams**. Unsure? ReadFile >> guessing
|
|
81
81
|
5. [tool:functions.WriteFile(path="...", content="...")]. Creates/Overwrites. File Exist? PatchFile > WriteFile. Verify Imports
|
|
82
82
|
6. [tool:functions.SearchKeyword(keyword="...", file="optional")]. Global project search. If 'file' is provided, searches only that file. Finds definitions/logic without reading every file
|
|
83
|
-
7. [tool:functions.Run(command="...")]. Runs ${o==="Windows"?
|
|
83
|
+
7. [tool:functions.Run(command="...")]. Runs ${o==="Windows"?ir()?`${Hn?"Interactive ":""}WINDOWS POWERSHELL ONLY`:`${Hn?"Interactive ":""}WINDOWS CMD ONLY`:`${Hn?"Interactive ":""}BASH`} command. Destructive/Irreversible ops -> Ask user. **TOOL DENY RULE APPLIES**. **1 CALL LIMIT OR 3 CONSECUTIVE RUN TOOL ONLY**
|
|
84
84
|
8. [tool:functions.WritePDF(path="...", content="...", orientation="...")]. PROACTIVE A4 PAGE BREAKS MUST IN CSS. HTML/CSS for PREMIUM layout
|
|
85
85
|
9. [tool:functions.WriteDoc(path="...", content="...")]. A4 Word document
|
|
86
86
|
|
|
87
87
|
- VERIFY TOOL RESULT CONTENTS. Fix errors. No hallucinations
|
|
88
88
|
- Escape quotes: \\" for code strings
|
|
89
89
|
- Literal escapes: Double-escape sequences (e.g., \\\\n, \\\\t)
|
|
90
|
-
- File structure: Real newlines for code formatting`.trim():"\n- FILE TOOLS ARE NOT AVAILABLE IN FLOW (Tell user to,` /mode flux` if needed)".trim()}`.trim()});import{spawn as
|
|
91
|
-
`)for(t++,n=0;t>=o.length;)o.push([]);else if(
|
|
92
|
-
`)},Dt=null
|
|
90
|
+
- File structure: Real newlines for code formatting`.trim():"\n- FILE TOOLS ARE NOT AVAILABLE IN FLOW (Tell user to,` /mode flux` if needed)".trim()}`.trim()});import{spawn as Hs}from"child_process";var ls,Hn,cs,Lr,Dt,Fo,Ao,Ma,Aa,Xs,Gs,Or=ie(async()=>{Qt();await js();ls=null;try{let e=await import("node-pty");ls=e.default||e}catch{}Hn=!!ls,cs=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),Lr=e=>{if(!e)return"";let o=[[]],t=0,n=0,s=/\x1b\[([0-9;]*?)([a-zA-Z])/g,r=0,a,u=m=>{for(let c=0;c<m.length;c++){let l=m[c];if(l===`
|
|
91
|
+
`)for(t++,n=0;t>=o.length;)o.push([]);else if(l==="\r")n=0;else{for(;t>=o.length;)o.push([]);let d=o[t];for(;n>d.length;)d.push(" ");d[n]=l,n++}}};for(;(a=s.exec(e))!==null;){u(e.substring(r,a.index));let m=a[1],c=a[2],l=m?m.split(";").map(Number):[];if(c==="A"){let d=l[0]||1;t=Math.max(0,t-d)}else if(c==="B"){let d=l[0]||1;for(t=t+d;t>=o.length;)o.push([])}else if(c==="C"){let d=l[0]||1;n=n+d}else if(c==="D"){let d=l[0]||1;n=Math.max(0,n-d)}else if(c==="G"){let d=(l[0]||1)-1;n=Math.max(0,d)}else if(c==="H"||c==="f"){let d=(l[0]||1)-1,p=(l[1]||1)-1;for(t=Math.max(0,d),n=Math.max(0,p);t>=o.length;)o.push([])}else if(c==="K"){let d=l[0]||0;if(t<o.length){let p=o[t];if(d===0)p.length=n;else if(d===1)for(let h=0;h<n&&h<p.length;h++)p[h]=" ";else d===2&&(p.length=0)}}else if(c==="J"){let d=l[0]||0;(d===2||d===3)&&(o.length=0,o.push([]),t=0,n=0)}r=s.lastIndex}u(e.substring(r));let f=o.map(m=>m.join(""));for(;f.length>0&&f[f.length-1]==="";)f.pop();return f.join(`
|
|
92
|
+
`)},Dt=null,Fo=!1,Ao=e=>{try{Dt&&(Fo&&typeof Dt.write=="function"?Dt.write(e):Dt.stdin&&Dt.stdin.writable&&Dt.stdin.write(e))}catch{}},Ma=()=>{if(Dt){try{Fo&&typeof Dt.destroy=="function"?Dt.destroy():typeof Dt.kill=="function"&&(process.platform==="win32"?Hs("taskkill",["/pid",Dt.pid,"/f","/t"]):Dt.kill("SIGKILL"))}catch{}Dt=null,Fo=!1}},Aa=(e,o=!1)=>{if(process.platform!=="win32")return e;let t=[],n="",s=null,r=!1;for(let c=0;c<e.length;c++){let l=e[c];if(r){n+=l,r=!1;continue}if(l==="\\"){if(e[c+1]===" "){n+=" ",c++;continue}n+=l,r=!0;continue}s?(l===s&&(s=null),n+=l):l==='"'||l==="'"?(s=l,n+=l):l===";"&&!n.includes("://")?(n.length>0&&(t.push(n),n=""),t.push(o?";":"&")):l==="&"&&!n.includes("://")?e[c+1]==="&"?(n.length>0&&(t.push(n),n=""),t.push("&&"),c++):(n.length>0&&(t.push(n),n=""),t.push("&")):l==="|"&&!n.includes("://")?(n.length>0&&(t.push(n),n=""),t.push("|")):/\s/.test(l)?n.length>0&&(t.push(n),n=""):n+=l}n.length>0&&t.push(n);let a=c=>!(!c.includes("/")||/^(https?|file|ftp):\/\//i.test(c)||c.startsWith("/")&&(c.match(/\//g)||[]).length===1||/\s\/|\/\s/.test(c)||/[\(\)\{\}\;\<\>\=\'\"]/.test(c)),u=[];for(let c=0;c<t.length;c++){let l=t[c];if(l==="mkdir"&&o&&ir()){let d=[],p=c+1;for(;p<t.length;){let h=t[p];if([">",">>","<","&","&&","|","||",";"].includes(h))break;h!=="-p"&&h!=="--parents"&&h!=="-v"&&h!=="--verbose"&&d.push(h),p++}if(d.length>0){let h=d.map(S=>{let w=S.replace(/^['"]|['"]$/g,""),T=S;return a(w)&&(T=S.replace(/\//g,"\\")),T});u.push("New-Item","-ItemType","Directory","-Force","-Path",h.join(","))}else u.push("New-Item","-ItemType","Directory","-Force");c=p-1;continue}if(l==="rm"&&o&&ir()){let d=[],p=!1,h=!1,S=c+1;for(;S<t.length;){let T=t[S];if([">",">>","<","&","&&","|","||",";"].includes(T))break;T==="-rf"||T==="-fr"?(p=!0,h=!0):T==="-r"||T==="-R"||T==="--recursive"?p=!0:T==="-f"||T==="--force"?h=!0:d.push(T),S++}let w=["Remove-Item"];if(p&&w.push("-Recurse"),h&&w.push("-Force"),d.length>0){let T=d.map(b=>{let L=b.replace(/^['"]|['"]$/g,""),P=b;return a(L)&&(P=b.replace(/\//g,"\\")),P});w.push("-Path",T.join(","))}u.push(...w),c=S-1;continue}if(l==="cp"&&o&&ir()){let d=[],p=!1,h=!1,S=c+1;for(;S<t.length;){let T=t[S];if([">",">>","<","&","&&","|","||",";"].includes(T))break;T==="-r"||T==="-R"||T==="--recursive"?p=!0:T==="-f"||T==="--force"?h=!0:d.push(T),S++}let w=["Copy-Item"];if(p&&w.push("-Recurse"),h&&w.push("-Force"),d.length>0){let T=d.map(b=>{let L=b.replace(/^['"]|['"]$/g,""),P=b;return a(L)&&(P=b.replace(/\//g,"\\")),P});if(T.length>1){let b=T.pop();w.push("-Path",T.join(","),"-Destination",b)}else w.push("-Path",T[0])}u.push(...w),c=S-1;continue}if(l==="touch"&&o&&ir()){let d=[],p=c+1;for(;p<t.length;){let h=t[p];if([">",">>","<","&","&&","|","||",";"].includes(h))break;d.push(h),p++}if(d.length>0){let S=`(${d.map(w=>{let T=w.replace(/^['"]|['"]$/g,""),b=w;return a(T)&&(b=w.replace(/\//g,"\\")),b}).join(", ")}) | ForEach-Object { if (Test-Path $_) { (Get-Item $_).LastWriteTime = [System.DateTime]::Now } else { $null | Out-File -FilePath $_ } }`;u.push(S)}c=p-1;continue}if(l==="|"&&t[c+1]==="tee"){t[c+2]==="-a"?(u.push(">>"),c+=2):(u.push(">"),c+=1);continue}if(l==="|"&&t[c+1]==="cat"&&t[c+2]===">"){u.push(">"),c+=2;continue}if(l==="|"){let d=t[c+1];if(d){let p=d.replace(/^['"]|['"]$/g,""),h=/\.(txt|md|json|log|csv|html|css|py|js|xml|yaml|yml|pdf|docx|pptx|xlsx)$/i.test(p);if(a(p)&&h){u.push(">");continue}}}u.push(l)}let f=!1,m=u.map(c=>{if(c==="echo")return f=!0,c;[">",">>","<","&","&&","|","||",";"].includes(c)&&(f=!1);let d=/^['"]|['"]$/.test(c),p=c;f&&d&&(p=c.replace(/^['"]|['"]$/g,""));let h=/^['"]|['"]$/.test(p),S=p.replace(/^['"]|['"]$/g,"");a(S)&&(p=p.replace(/\//g,"\\"));let w=p.replace(/^['"]|['"]$/g,"");return w.includes(" ")&&!h&&(p=`"${w}"`),p});if(o){let c="",l=0;for(let d=0;d<m.length;d++){let p=m[d];p==="&&"?(c+="; if ($?) {",l++):p===";"?(c+=" }".repeat(l)+";",l=0):(c&&!c.endsWith(" ")&&!c.endsWith("{")&&(c+=" "),c+=p)}return c+=" }".repeat(l),c}return m.join(" ")},Xs=async(e,o={})=>{let{command:t}=re(e),{onChunk:n}=o;if(!t)return'ERROR: Missing "command" argument for exec_command.';let s=process.platform==="win32",r=o.systemSettings||{},a={};return r.networkAccess===!1&&(a.HTTP_PROXY="http://127.0.0.1:9999",a.HTTPS_PROXY="http://127.0.0.1:9999",a.ALL_PROXY="socks5://127.0.0.1:9999",a.http_proxy="http://127.0.0.1:9999",a.https_proxy="http://127.0.0.1:9999",a.all_proxy="socks5://127.0.0.1:9999",a.NO_PROXY="localhost,127.0.0.1"),new Promise(u=>{let f=m=>{let c=Aa(t,m),l=s?m?"powershell.exe":"cmd.exe":process.env.SHELL||"bash",d=s?m?["-NoProfile","-Command",c]:["/c",c]:["-c",c];if(ls)try{let p=ls.spawn(l,d,{name:"xterm-256color",cols:o.cols||120,rows:o.rows||30,cwd:process.cwd(),env:{...process.env,CI:"false",TERM:"xterm-256color",FORCE_COLOR:"1",...a}});Dt=p,Fo=!0;let h="",S=!1;return p.onData(w=>{if(!S){h+=w,n&&n(w);let T=cs(h);/(?:Network:\s+use\s+--host\s+to|Network:\s+Type\s+--host\s+to|Local:\s+http:\/\/localhost:\d+|ready in \d+\s*ms|Compiled successfully|Development server is running|Listening on:)/i.test(T)&&(S=!0,setTimeout(()=>u(`SUCCESS: Dev server started successfully in background.
|
|
93
93
|
|
|
94
|
-
${T}`),500))}}),p.onExit(({exitCode:w})=>{if(
|
|
94
|
+
${T}`),500))}}),p.onExit(({exitCode:w})=>{if(S)return;Dt=null;let T=Lr(h||""),b=cs(T).replace(/\n{3,}/g,`
|
|
95
95
|
|
|
96
96
|
`)||"Command executed with no output.";u(w!==0?`ERROR: Command [${t}] failed with exit code [${w}].
|
|
97
97
|
|
|
98
|
-
${
|
|
98
|
+
${b}`:`SUCCESS: Command [${t}] completed.
|
|
99
99
|
|
|
100
|
-
${
|
|
100
|
+
${b}`)}),!0}catch(p){return s&&m&&p.code==="ENOENT"?!1:(Gs(u,c,t,a,n,m),!0)}else return Gs(u,c,t,a,n,m),!0};s&&f(!0)||f(!1)})},Gs=(e,o,t,n,s,r=!0)=>{let a=process.platform==="win32",u=a?r?"powershell.exe":"cmd.exe":process.env.SHELL||"bash",m=a?Hs(u,a?r?["-NoProfile","-Command",o]:["/c",o]:["-c",o],{cwd:process.cwd(),env:{...process.env,...n}}):Hs(o,{shell:!0,cwd:process.cwd(),env:{...process.env,CI:"false",TERM:"xterm-256color",FORCE_COLOR:"1",...n}});Dt=m,Fo=!1,m.stdin&&m.stdin.on("error",()=>{Dt=null});let c="",l="",d=!1;m.stdout.on("data",p=>{if(!d){let h=p.toString();c+=h,s&&s(h);let S=cs(c);/(?:Network:\s+use\s+--host\s+to|Network:\s+Type\s+--host\s+to|Local:\s+http:\/\/localhost:\d+|ready in \d+\s*ms|Compiled successfully|Development server is running|Listening on:)/i.test(S)&&(d=!0,setTimeout(()=>e(`SUCCESS: Dev server started successfully in background.
|
|
101
101
|
|
|
102
|
-
${
|
|
103
|
-
${
|
|
102
|
+
${S}`),500))}}),m.stderr.on("data",p=>{if(!d){let h=p.toString();l+=h,s&&s(h)}}),m.on("close",p=>{if(d)return;Dt=null;let h=[],S=Lr(c),w=Lr(l);S&&h.push(`STDOUT:
|
|
103
|
+
${S}`),w&&h.push(`STDERR:
|
|
104
104
|
${w}`),p!==0&&h.push(`EXIT CODE: ${p}`);let T=h.join(`
|
|
105
105
|
|
|
106
|
-
`)||"Command executed with no output.",
|
|
106
|
+
`)||"Command executed with no output.",b=cs(T).replace(/\n{3,}/g,`
|
|
107
107
|
|
|
108
108
|
`);e(p!==0?`ERROR: Command [${t}] failed with exit code [${p}].
|
|
109
109
|
|
|
110
|
-
${
|
|
110
|
+
${b}`:`SUCCESS: Command [${t}] completed.
|
|
111
111
|
|
|
112
|
-
${I}`)}),m.on("error",p=>{if(l&&r&&p.code==="ENOENT"){let h=Ia(t,!1);return Gs(e,h,t,n,s,!1)}Dt=null,e(`ERROR: Failed to start command [${t}]: ${p.message}`)})}});import Ee,{useState as Fr}from"react";import{Box as Pt,Text as zt,useInput as Xc}from"ink";import Kc from"ink-text-input";function Ks({systemSettings:e,setSystemSettings:o,apiTier:t,setActiveView:n,setInputConfig:s,saveSettings:r,quotas:l,setMessages:u,aiProvider:f}){let[m,c]=Fr("categories"),[a,d]=Fr(0),[p,h]=Fr(0),[E,w]=Fr(null),[T,I]=Fr(""),O=S=>{switch(S){case"memory":return[{label:"Toggle Memory",value:"memory",status:e.memory?"ON":"OFF"}];case"security":return[{label:"Sandbox Preset",value:"sandboxPreset",status:Aa(e),section:"Sandbox"},{label:"YOLO Mode",value:"autoExec",status:e.autoExec?"ON":"OFF",section:"Sandbox"},{label:"External Workspace Access",value:"externalAccess",status:e.allowExternalAccess?"ON":"OFF",section:"Sandbox"},{label:"Network Access (Terminal)",value:"networkAccess",status:e.networkAccess!==!1?"ON":"OFF",section:"Sandbox"},{label:"Always Ask Commands",value:"alwaysAsk",status:Xs(e.alwaysAskCommands),section:"Sandbox"},{label:"Auto Approve Commands",value:"autoApprove",status:Xs(e.autoApproveCommands),section:"Sandbox"},{label:"Auto Disapprove Commands",value:"autoDisallow",status:Xs(e.autoDisallowCommands),section:"Sandbox"},{label:"Auto Approve Git Commits",value:"autoApproveGit",status:e.autoApproveGit?"ON":"OFF",section:"Sandbox"},{label:"Auto-Delete History",value:"autoDelete",status:e.autoDeleteHistory||"30d",section:"Other"},{label:"Save AppData Externally",value:"externalData",status:e.useExternalData?"ON":"OFF",section:"Other"}];case"updater":return[{label:"Auto-Update",value:"autoUpdate",status:e.autoUpdate?"ON":"OFF"},{label:"Preferred Updater",value:"updateManager",status:(e.updateManager||"npm")==="custom"?"Custom":(e.updateManager||"npm").toUpperCase()}];case"other":return[{label:"Current Provider",value:"aiProvider",status:f},{label:"API Tier",value:"apiTier",status:t},{label:"Download Language Parsers",value:"parserDownload",status:"ACTION"}];default:return[]}},P=an[a].id,U=O(P);Xc((S,v)=>{if(E){v.escape&&w(null);return}if(m==="categories")v.upArrow?d(F=>(F-1+an.length)%an.length):v.downArrow?d(F=>(F+1)%an.length):v.return||v.rightArrow?an[a].id==="exit"?n("chat"):(c("items"),h(0)):v.escape&&n("chat");else if(m==="items"){if(v.upArrow)h(F=>(F-1+U.length)%U.length);else if(v.downArrow)h(F=>(F+1)%U.length);else if(v.leftArrow||v.escape)c("categories");else if(v.return){let F=U[p];A(F)}}});let A=S=>{if(S.value==="memory")o(v=>({...v,memory:!v.memory}));else if(S.value==="sandboxPreset"){let v=Aa(e),F=["Autonomous","Balanced","Strict"],Y=(F.indexOf(v)+1)%F.length,Z=F[Y];o(N=>{let J={...N,sandboxPreset:Z};return Z==="Strict"?(J.autoExec=!1,J.allowExternalAccess=!1,J.networkAccess=!1,J.autoApproveCommands="",J.autoDisallowCommands="rm -rf, rm -f, del /f, del /q, rd /s, rmdir /s, format, mkfs, dd if=/dev, shred, srm, Remove-Item -Recurse -Force, Initialize-Disk, Clear-Disk, format c:, flashrom, nvram -c",J.alwaysAskCommands="killall, pkill, taskkill, shutdown, reboot, init 0, init 6, Stop-Process, Stop-Service, mv /*, move c:\\*, chmod 000, chmod -R 777, chown, icacls, netsh advfirewall, iptables -F, ufw disable, git reset --hard, git clean -fd, npm r, npm uninstall",J.autoApproveGit=!1):Z==="Balanced"?(J.autoExec=!0,J.allowExternalAccess=!1,J.networkAccess=!0,J.autoApproveCommands="ls, dir, cat, type, echo, pwd, cd, git status, git log, git diff, git branch, git show, help, mkdir, touch, md, whoami, hostname, ps, Get-Process, date, time",J.autoDisallowCommands="rm -rf, rm -f, del /f, del /q, rd /s, rmdir /s, format, mkfs, dd if=/dev, shred, srm, Remove-Item -Recurse -Force, Initialize-Disk, Clear-Disk, format c:, flashrom, nvram -c",J.alwaysAskCommands="killall, pkill, taskkill, Stop-Process, mv /*, move c:\\*, chmod 000, chmod -R 777, chown, icacls, shutdown, reboot, init 0, init 6, git reset --hard, git clean -fd, npm r, npm uninstall",J.autoApproveGit=!1):Z==="Autonomous"&&(J.autoExec=!0,J.allowExternalAccess=!0,J.networkAccess=!0,J.autoApproveCommands="ls, dir, cat, type, echo, pwd, cd, git status, git log, git diff, git branch, git show, help, mkdir, touch, md, whoami, hostname, ps, Get-Process, date, time",J.autoDisallowCommands="",J.alwaysAskCommands="rm -rf, rm -f, del /f, del /q, rd /s, rmdir /s, format, mkfs, dd if=/dev, shred, srm, Remove-Item -Recurse -Force, Initialize-Disk, Clear-Disk, format c:, flashrom, nvram -c",J.autoApproveGit=!0),J})}else if(S.value==="autoExec")e.autoExec?o(v=>({...v,autoExec:!1,sandboxPreset:"Custom"})):e.allowExternalAccess?n("doubleDanger"):n("autoExecDanger");else if(S.value==="externalAccess")e.allowExternalAccess?o(v=>({...v,allowExternalAccess:!1,sandboxPreset:"Custom"})):e.autoExec?n("doubleDanger"):n("externalDanger");else if(S.value==="networkAccess")o(v=>({...v,networkAccess:v.networkAccess===!1,sandboxPreset:"Custom"}));else if(S.value==="alwaysAsk")w("alwaysAskCommands"),I(e.alwaysAskCommands||"");else if(S.value==="autoApprove")w("autoApproveCommands"),I(e.autoApproveCommands||"");else if(S.value==="autoApproveGit")o(v=>({...v,autoApproveGit:!v.autoApproveGit,sandboxPreset:"Custom"}));else if(S.value==="autoDisallow")w("autoDisallowCommands"),I(e.autoDisallowCommands||"");else if(S.value==="apiTier")n("apiTier");else if(S.value==="aiProvider")n("selectProvider");else if(S.value==="autoDelete"){let v=["1d","7d","30d"],V=(v.indexOf(e.autoDeleteHistory||"30d")+1)%v.length;o(Y=>({...Y,autoDeleteHistory:v[V]}))}else if(S.value==="autoUpdate")o(v=>({...v,autoUpdate:!v.autoUpdate}));else if(S.value==="externalData")if(!e.useExternalData)s({label:"Enter absolute path for External AppData:",note:"All history, logs and secrets will be stored here. ~/.fluxflow/settings.json stays as anchor.",key:"externalDataPath",value:e.externalDataPath||""}),n("input");else{let v={...e,useExternalData:!1};o(v),r({systemSettings:v,apiTier:t,quotas:l}),u(F=>[...F,{id:Date.now(),role:"system",text:"\u{1F3E0} [STORAGE RESET] Flux Flow will return to default ~/.fluxflow after restart."}]),n("chat")}else S.value==="updateManager"?n("updateManager"):S.value==="parserDownload"&&n("parserDownload")};return Ee.createElement(Pt,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%",minHeight:32},Ee.createElement(Pt,{paddingX:1,paddingY:0,marginBottom:0,borderStyle:"single",borderColor:"magenta",width:"100%"},Ee.createElement(zt,{color:"magenta",bold:!0},"\u{1F527} SYSTEM CONFIGURATION")),Ee.createElement(Pt,{flexDirection:"row",width:"100%",minHeight:26},Ee.createElement(Pt,{flexDirection:"column",width:"30%",borderStyle:"round",borderColor:m==="categories"?"cyan":"gray",padding:1,paddingY:0},Ee.createElement(Pt,{marginBottom:1},Ee.createElement(zt,{color:m==="categories"?"cyan":"white",bold:!0,underline:!0},"CATEGORIES")),an.map((S,v)=>{let F=a===v,V=S.id==="exit";return Ee.createElement(Pt,{key:S.id,marginTop:V?17:0,backgroundColor:F?m==="categories"?"#2a2a2a":"#1e1e1e":void 0,paddingX:1},Ee.createElement(zt,{color:F?m==="categories"?"cyan":"yellow":"white",bold:F},F?"\u276F ":" ",S.label))})),Ee.createElement(Pt,{flexDirection:"column",width:"70%",borderStyle:"round",borderColor:m==="items"?"cyan":"gray",paddingX:1,marginLeft:1,paddingY:0},Ee.createElement(Pt,{marginBottom:1},Ee.createElement(zt,{color:m==="items"?"cyan":"white",bold:!0,underline:!0},an[a].label.toUpperCase()," SETTINGS")),U.length>0?(()=>{let S=null,v=[],F=de=>(de||"").split(",").map($e=>$e.trim().toLowerCase()).filter(Boolean),V=F(e.autoApproveCommands),Y=F(e.autoDisallowCommands),Z=F(e.alwaysAskCommands),N=[...V,...Y,...Z],J=new Set(N),ft=P==="security"&&N.length!==J.size;return U.forEach((de,$e)=>{let qe=m==="items"&&p===$e,me=de.label.length,Ze=Math.max(2,35-me),je=".".repeat(Ze),Be=pt=>P==="security"?(pt.value==="autoExec"||pt.value==="externalAccess")&&pt.status==="ON"?"red":"yellow":pt.status?.startsWith("\u2713")?"green":pt.status?.startsWith("\u26A0")?"yellow":pt.status==="ON"?"green":pt.status==="OFF"?"red":"yellow";de.section&&de.section!==S&&(S=de.section,v.push(Ee.createElement(Pt,{key:`sec-hdr-${de.section}`,marginTop:v.length>0?1:0,marginBottom:0,paddingX:1},Ee.createElement(zt,{color:"magenta",bold:!0,underline:!0},"\u{1F4C2} ",de.section.toUpperCase()))));let Le=qe&&E&&(E==="alwaysAskCommands"&&de.value==="alwaysAsk"||E==="autoApproveCommands"&&de.value==="autoApprove"||E==="autoDisallowCommands"&&de.value==="autoDisallow"),Ge=de.value==="alwaysAsk"||de.value==="autoApprove"||de.value==="autoDisallow",Se=de.value==="parserDownload";v.push(Ee.createElement(Pt,{key:de.value,flexDirection:"column"},Ee.createElement(Pt,{backgroundColor:qe&&!Le?"#2a2a2a":void 0,paddingX:2},Ee.createElement(zt,{color:qe?"cyan":"white",bold:qe,underline:Se},qe?"\u276F ":" ",de.label),!Ge&&!Se&&Ee.createElement(Ee.Fragment,null,Ee.createElement(zt,{color:"gray",dimColor:!0},je),Ee.createElement(zt,{color:Be(de),bold:!0},de.value==="aiProvider"?de.status:`[ ${de.status} ]`))),Ge&&!Le&&de.status!=="None"&&Ee.createElement(Pt,{paddingX:4,marginBottom:1},Ee.createElement(zt,{color:"gray",dimColor:!0},"\u21B3 ",de.status)),Le&&Ee.createElement(Pt,{flexDirection:"column",marginLeft:4,marginBottom:1},Ee.createElement(Pt,{paddingX:1,borderStyle:"single",borderColor:"cyan",flexDirection:"row"},Ee.createElement(zt,{color:"cyan",bold:!0},"> "," "),Ee.createElement(Kc,{value:T,onChange:I,onSubmit:pt=>{let ht={...e,[E]:pt.trim(),sandboxPreset:"Custom"};o(ht),r({systemSettings:ht,apiTier:t,quotas:l}),w(null)}})),Ee.createElement(zt,{color:"gray",dimColor:!0,italic:!0}," Comma separated \u2022 Press Enter to save, Esc to cancel"))))}),P==="other"&&v.push(Ee.createElement(Pt,{key:"pty-notice",marginTop:18,paddingX:1},Ee.createElement(zt,{color:Wn?"green":"yellow"},Wn?"\u2713 Advance Interactive Terminal Supported":"\u26A0 Interactive Terminal is Limited"))),ft&&v.push(Ee.createElement(Pt,{key:"conflict-warning",marginTop:1,paddingX:1},Ee.createElement(zt,{color:"red",dimColor:!0,italic:!0},"* Conflicting commands will be ignored and defaulted to highest priority"))),v})():Ee.createElement(Pt,{paddingX:1},Ee.createElement(zt,{color:"gray",italic:!0},an[a].desc)))),Ee.createElement(Pt,{paddingX:1,marginTop:0,flexDirection:"row",justifyContent:"space-between"},Ee.createElement(zt,{color:"gray",dimColor:!0,italic:!0},m==="categories"?"\u25B2\u25BC Select Category \u2022 Enter/\u25BA to configure":"\u25B2\u25BC Select Option \u2022 Enter to Toggle \u2022 \u25C4/ESC to go back"),m==="categories"&&Ee.createElement(zt,{color:"gray",dimColor:!0},an[a].desc)))}var an,Aa,Xs,Ma=re(async()=>{await Or();an=[{id:"memory",label:"\u{1F9E0} Memory",desc:"Manage system context & agent's memory"},{id:"security",label:"\u{1F512} Security",desc:"Configure permissions & data safety"},{id:"updater",label:"\u{1F504} Updater",desc:"Manage application updates"},{id:"other",label:"\u{1F4CB} Other",desc:"Miscellaneous preferences"},{id:"exit",label:"\u{1F6AA} Exit Settings",desc:"Return to chat view"}],Aa=e=>{let o=e.autoApproveCommands||"",t=e.autoDisallowCommands||"",n=e.alwaysAskCommands||"",s=e.autoExec===!1&&e.allowExternalAccess===!1&&e.networkAccess===!1&&o===""&&t==="rm -rf, rm -f, del /f, del /q, rd /s, rmdir /s, format, mkfs, dd if=/dev, shred, srm, Remove-Item -Recurse -Force, Initialize-Disk, Clear-Disk, format c:, flashrom, nvram -c"&&n==="killall, pkill, taskkill, shutdown, reboot, init 0, init 6, Stop-Process, Stop-Service, mv /*, move c:\\*, chmod 000, chmod -R 777, chown, icacls, netsh advfirewall, iptables -F, ufw disable, git reset --hard, git clean -fd, npm r, npm uninstall"&&e.autoApproveGit===!1,r=e.autoExec===!0&&e.allowExternalAccess===!1&&e.networkAccess!==!1&&o==="ls, dir, cat, type, echo, pwd, cd, git status, git log, git diff, git branch, git show, help, mkdir, touch, md, whoami, hostname, ps, Get-Process, date, time, mkdir"&&t==="rm -rf, rm -f, del /f, del /q, rd /s, rmdir /s, format, mkfs, dd if=/dev, shred, srm, Remove-Item -Recurse -Force, Initialize-Disk, Clear-Disk, format c:, flashrom, nvram -c"&&n==="killall, pkill, taskkill, Stop-Process, mv /*, move c:\\*, chmod 000, chmod -R 777, chown, icacls, shutdown, reboot, init 0, init 6, git reset --hard, git clean -fd, npm r, npm uninstall"&&e.autoApproveGit===!1,l=e.autoExec===!0&&e.allowExternalAccess===!0&&e.networkAccess!==!1&&o==="ls, dir, cat, type, echo, pwd, cd, git status, git log, git diff, git branch, git show, help, mkdir, touch, md, whoami, hostname, ps, Get-Process, date, time, mkdir"&&t===""&&n==="rm -rf, rm -f, del /f, del /q, rd /s, rmdir /s, format, mkfs, dd if=/dev, shred, srm, Remove-Item -Recurse -Force, Initialize-Disk, Clear-Disk, format c:, flashrom, nvram -c"&&e.autoApproveGit===!0;return s?"Strict":r?"Balanced":l?"Autonomous":e.sandboxPreset||"Custom"},Xs=e=>!e||e.trim()===""?"None":e.length>40?e.substring(0,40)+"...":e});import Po,{useState as Vs,useEffect as Vc}from"react";import{Box as or,Text as cs}from"ink";import qc from"ink-text-input";function qs({initialData:e,onSave:o,onCancel:t}){let[n,s]=Vs(0),[r,l]=Vs(""),[u,f]=Vs(()=>({name:e?.name||"",nickname:e?.nickname||"",instructions:e?.instructions||""})),m=[{key:"name",label:"Enter your Name: "},{key:"nickname",label:"Enter a Nickname (Agent will use this): "},{key:"instructions",label:"System Instructions (Persona overrides): "}];Vc(()=>{let a=m[n].key;l(u[a]||"")},[n,u]);let c=a=>{if(a.trim().toLowerCase()==="/cancel"){t();return}let d=m[n].key,p={...u,[d]:a.trim()};f(p),l(""),n<m.length-1?s(n+1):o(p)};return Po.createElement(or,{borderStyle:"round",borderColor:"gray",padding:0,marginTop:1,flexShrink:0,flexDirection:"column",width:"100%"},Po.createElement(or,{paddingX:1,marginBottom:1},Po.createElement(cs,{color:"magenta",bold:!0},"\u{1F464} DEVELOPER PROFILE CONFIGURATION")),Po.createElement(or,{paddingX:1,flexDirection:"column"},Po.createElement(or,null,Po.createElement(cs,{color:"cyan",bold:!0},m[n].label),Po.createElement(qc,{value:r,onChange:l,onSubmit:c})),Po.createElement(or,{marginTop:1},Po.createElement(cs,{color:"gray",dimColor:!0,italic:!0},"Step ",n+1," of ",m.length))),Po.createElement(or,{paddingX:1,marginTop:1},Po.createElement(cs,{color:"gray",dimColor:!0,italic:!0},"(Enter to submit \u2022 Type /cancel to abort)")))}var va=re(()=>{});import dt,{useState as zs}from"react";import{Box as Ao,Text as ln,useInput as zc}from"ink";import Jc from"ink-text-input";var Qc,Da,Oa=re(()=>{rn();Qc=({question:e,options:o,onResolve:t})=>{let[n,s]=zs(!1),[r,l]=zs(""),[u,f]=zs(0),m=[...o,{id:"CUSTOM",label:"Suggest something else...",description:"Provide a custom response"}];zc((a,d)=>{if(!n&&((d.leftArrow||d.upArrow)&&f(p=>Math.max(0,p-1)),(d.rightArrow||d.downArrow)&&f(p=>Math.min(m.length-1,p+1)),d.return)){let p=m[u];p.id==="CUSTOM"?s(!0):t(p.label)}});let c=Oe(2);return n?dt.createElement(Ao,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},dt.createElement(Ao,{paddingX:1},dt.createElement(ln,{color:"cyan",bold:!0},"\u{1F4AC} SUGGEST SOMETHING ELSE")),dt.createElement(Ao,{marginTop:1,paddingX:1},dt.createElement(ln,{italic:!0,color:"gray"},"Replying to: ",e)),dt.createElement(Ao,{marginTop:1,paddingX:1,flexDirection:"row"},dt.createElement(ln,{color:"cyan",bold:!0},"\u{1F4A0} "),dt.createElement(Jc,{value:r,onChange:l,onSubmit:()=>t(r)})),dt.createElement(Ao,{marginTop:1,paddingX:1,marginBottom:1},dt.createElement(ln,{color:"gray",dimColor:!0,italic:!0},"(Press Enter to send)"))):dt.createElement(Ao,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},dt.createElement(Ao,{paddingX:1,marginBottom:1},dt.createElement(ln,{color:"cyan",bold:!0},"\u{1F4AC} AGENT REQUEST: ACTION REQUIRED")),dt.createElement(Ao,{paddingX:1,marginBottom:1},dt.createElement(ln,{bold:!0,color:"white"},e)),dt.createElement(Ao,{flexDirection:"column",width:"100%"},m.map((a,d)=>{let p=d===u;return dt.createElement(Ao,{key:a.id,flexDirection:"column",width:"100%",backgroundColor:p?"#2a2a2a":void 0,paddingX:1,marginBottom:d===m.length-1?0:1},dt.createElement(ln,{color:p?"cyan":"white",bold:p},p?"\u276F ":" ",a.label),a.description&&dt.createElement(Ao,{marginLeft:4},dt.createElement(ln,{color:"gray",italic:!0,dimColor:!0},a.description)))})),dt.createElement(Ao,{paddingX:1,marginTop:1,marginBottom:1},dt.createElement(ln,{color:"gray",dimColor:!0,italic:!0},"(Use Arrows to navigate, Enter to confirm)")))},Da=Qc});var La,Fa=re(()=>{La=(e=!0,o=!0)=>`
|
|
112
|
+
${b}`)}),m.on("error",p=>{if(a&&r&&p.code==="ENOENT"){let h=Aa(t,!1);return Gs(e,h,t,n,s,!1)}Dt=null,e(`ERROR: Failed to start command [${t}]: ${p.message}`)})}});import ke,{useState as Fr}from"react";import{Box as Pt,Text as Zt,useInput as qc}from"ink";import zc from"ink-text-input";function Vs({systemSettings:e,setSystemSettings:o,apiTier:t,setActiveView:n,setInputConfig:s,saveSettings:r,quotas:a,setMessages:u,aiProvider:f}){let[m,c]=Fr("categories"),[l,d]=Fr(0),[p,h]=Fr(0),[S,w]=Fr(null),[T,b]=Fr(""),L=D=>{switch(D){case"memory":return[{label:"Toggle Memory",value:"memory",status:e.memory?"ON":"OFF"}];case"security":return[{label:"Sandbox Preset",value:"sandboxPreset",status:va(e),section:"Sandbox"},{label:"YOLO Mode",value:"autoExec",status:e.autoExec?"ON":"OFF",section:"Sandbox"},{label:"External Workspace Access",value:"externalAccess",status:e.allowExternalAccess?"ON":"OFF",section:"Sandbox"},{label:"Network Access (Terminal)",value:"networkAccess",status:e.networkAccess!==!1?"ON":"OFF",section:"Sandbox"},{label:"Always Ask Commands",value:"alwaysAsk",status:Ks(e.alwaysAskCommands),section:"Sandbox"},{label:"Auto Approve Commands",value:"autoApprove",status:Ks(e.autoApproveCommands),section:"Sandbox"},{label:"Auto Disapprove Commands",value:"autoDisallow",status:Ks(e.autoDisallowCommands),section:"Sandbox"},{label:"Auto Approve Git Commits",value:"autoApproveGit",status:e.autoApproveGit?"ON":"OFF",section:"Sandbox"},{label:"Auto-Delete History",value:"autoDelete",status:e.autoDeleteHistory||"30d",section:"Other"},{label:"Save AppData Externally",value:"externalData",status:e.useExternalData?"ON":"OFF",section:"Other"}];case"updater":return[{label:"Auto-Update",value:"autoUpdate",status:e.autoUpdate?"ON":"OFF"},{label:"Preferred Updater",value:"updateManager",status:(e.updateManager||"npm")==="custom"?"Custom":(e.updateManager||"npm").toUpperCase()}];case"other":return[{label:"Current Provider",value:"aiProvider",status:f},{label:"API Tier",value:"apiTier",status:t},{label:"Download Language Parsers",value:"parserDownload",status:"ACTION"}];default:return[]}},P=ln[l].id,Y=L(P);qc((D,A)=>{if(S){A.escape&&w(null);return}if(m==="categories")A.upArrow?d(E=>(E-1+ln.length)%ln.length):A.downArrow?d(E=>(E+1)%ln.length):A.return||A.rightArrow?ln[l].id==="exit"?n("chat"):(c("items"),h(0)):A.escape&&n("chat");else if(m==="items"){if(A.upArrow)h(E=>(E-1+Y.length)%Y.length);else if(A.downArrow)h(E=>(E+1)%Y.length);else if(A.leftArrow||A.escape)c("categories");else if(A.return){let E=Y[p];v(E)}}});let v=D=>{if(D.value==="memory")o(A=>({...A,memory:!A.memory}));else if(D.value==="sandboxPreset"){let A=va(e),E=["Autonomous","Balanced","Strict"],B=(E.indexOf(A)+1)%E.length,V=E[B];o(_=>{let K={..._,sandboxPreset:V};return V==="Strict"?(K.autoExec=!1,K.allowExternalAccess=!1,K.networkAccess=!1,K.autoApproveCommands="",K.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",K.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",K.autoApproveGit=!1):V==="Balanced"?(K.autoExec=!0,K.allowExternalAccess=!1,K.networkAccess=!0,K.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",K.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",K.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",K.autoApproveGit=!1):V==="Autonomous"&&(K.autoExec=!0,K.allowExternalAccess=!0,K.networkAccess=!0,K.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",K.autoDisallowCommands="",K.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",K.autoApproveGit=!0),K})}else if(D.value==="autoExec")e.autoExec?o(A=>({...A,autoExec:!1,sandboxPreset:"Custom"})):e.allowExternalAccess?n("doubleDanger"):n("autoExecDanger");else if(D.value==="externalAccess")e.allowExternalAccess?o(A=>({...A,allowExternalAccess:!1,sandboxPreset:"Custom"})):e.autoExec?n("doubleDanger"):n("externalDanger");else if(D.value==="networkAccess")o(A=>({...A,networkAccess:A.networkAccess===!1,sandboxPreset:"Custom"}));else if(D.value==="alwaysAsk")w("alwaysAskCommands"),b(e.alwaysAskCommands||"");else if(D.value==="autoApprove")w("autoApproveCommands"),b(e.autoApproveCommands||"");else if(D.value==="autoApproveGit")o(A=>({...A,autoApproveGit:!A.autoApproveGit,sandboxPreset:"Custom"}));else if(D.value==="autoDisallow")w("autoDisallowCommands"),b(e.autoDisallowCommands||"");else if(D.value==="apiTier")n("apiTier");else if(D.value==="aiProvider")n("selectProvider");else if(D.value==="autoDelete"){let A=["1d","7d","30d"],q=(A.indexOf(e.autoDeleteHistory||"30d")+1)%A.length;o(B=>({...B,autoDeleteHistory:A[q]}))}else if(D.value==="autoUpdate")o(A=>({...A,autoUpdate:!A.autoUpdate}));else if(D.value==="externalData")if(!e.useExternalData)s({label:"Enter absolute path for External AppData:",note:"All history, logs and secrets will be stored here. ~/.fluxflow/settings.json stays as anchor.",key:"externalDataPath",value:e.externalDataPath||""}),n("input");else{let A={...e,useExternalData:!1};o(A),r({systemSettings:A,apiTier:t,quotas:a}),u(E=>[...E,{id:Date.now(),role:"system",text:"\u{1F3E0} [STORAGE RESET] Flux Flow will return to default ~/.fluxflow after restart."}]),n("chat")}else D.value==="updateManager"?n("updateManager"):D.value==="parserDownload"&&n("parserDownload")};return ke.createElement(Pt,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%",minHeight:32},ke.createElement(Pt,{paddingX:1,paddingY:0,marginBottom:0,borderStyle:"single",borderColor:"magenta",width:"100%"},ke.createElement(Zt,{color:"magenta",bold:!0},"\u{1F527} SYSTEM CONFIGURATION")),ke.createElement(Pt,{flexDirection:"row",width:"100%",minHeight:26},ke.createElement(Pt,{flexDirection:"column",width:"30%",borderStyle:"round",borderColor:m==="categories"?"cyan":"gray",padding:1,paddingY:0},ke.createElement(Pt,{marginBottom:1},ke.createElement(Zt,{color:m==="categories"?"cyan":"white",bold:!0,underline:!0},"CATEGORIES")),ln.map((D,A)=>{let E=l===A,q=D.id==="exit";return ke.createElement(Pt,{key:D.id,marginTop:q?17:0,backgroundColor:E?m==="categories"?"#2a2a2a":"#1e1e1e":void 0,paddingX:1},ke.createElement(Zt,{color:E?m==="categories"?"cyan":"yellow":"white",bold:E},E?"\u276F ":" ",D.label))})),ke.createElement(Pt,{flexDirection:"column",width:"70%",borderStyle:"round",borderColor:m==="items"?"cyan":"gray",paddingX:1,marginLeft:1,paddingY:0},ke.createElement(Pt,{marginBottom:1},ke.createElement(Zt,{color:m==="items"?"cyan":"white",bold:!0,underline:!0},ln[l].label.toUpperCase()," SETTINGS")),Y.length>0?(()=>{let D=null,A=[],E=se=>(se||"").split(",").map(Te=>Te.trim().toLowerCase()).filter(Boolean),q=E(e.autoApproveCommands),B=E(e.autoDisallowCommands),V=E(e.alwaysAskCommands),_=[...q,...B,...V],K=new Set(_),Ue=P==="security"&&_.length!==K.size;return Y.forEach((se,Te)=>{let De=m==="items"&&p===Te,me=se.label.length,et=Math.max(2,35-me),Ye=".".repeat(et),je=He=>P==="security"?(He.value==="autoExec"||He.value==="externalAccess")&&He.status==="ON"?"red":"yellow":He.status?.startsWith("\u2713")?"green":He.status?.startsWith("\u26A0")?"yellow":He.status==="ON"?"green":He.status==="OFF"?"red":"yellow";se.section&&se.section!==D&&(D=se.section,A.push(ke.createElement(Pt,{key:`sec-hdr-${se.section}`,marginTop:A.length>0?1:0,marginBottom:0,paddingX:1},ke.createElement(Zt,{color:"magenta",bold:!0,underline:!0},"\u{1F4C2} ",se.section.toUpperCase()))));let Oe=De&&S&&(S==="alwaysAskCommands"&&se.value==="alwaysAsk"||S==="autoApproveCommands"&&se.value==="autoApprove"||S==="autoDisallowCommands"&&se.value==="autoDisallow"),kt=se.value==="alwaysAsk"||se.value==="autoApprove"||se.value==="autoDisallow",Ne=se.value==="parserDownload";A.push(ke.createElement(Pt,{key:se.value,flexDirection:"column"},ke.createElement(Pt,{backgroundColor:De&&!Oe?"#2a2a2a":void 0,paddingX:2},ke.createElement(Zt,{color:De?"cyan":"white",bold:De,underline:Ne},De?"\u276F ":" ",se.label),!kt&&!Ne&&ke.createElement(ke.Fragment,null,ke.createElement(Zt,{color:"gray",dimColor:!0},Ye),ke.createElement(Zt,{color:je(se),bold:!0},se.value==="aiProvider"?se.status:`[ ${se.status} ]`))),kt&&!Oe&&se.status!=="None"&&ke.createElement(Pt,{paddingX:4,marginBottom:1},ke.createElement(Zt,{color:"gray",dimColor:!0},"\u21B3 ",se.status)),Oe&&ke.createElement(Pt,{flexDirection:"column",marginLeft:4,marginBottom:1},ke.createElement(Pt,{paddingX:1,borderStyle:"single",borderColor:"cyan",flexDirection:"row"},ke.createElement(Zt,{color:"cyan",bold:!0},"> "," "),ke.createElement(zc,{value:T,onChange:b,onSubmit:He=>{let We={...e,[S]:He.trim(),sandboxPreset:"Custom"};o(We),r({systemSettings:We,apiTier:t,quotas:a}),w(null)}})),ke.createElement(Zt,{color:"gray",dimColor:!0,italic:!0}," Comma separated \u2022 Press Enter to save, Esc to cancel"))))}),P==="other"&&A.push(ke.createElement(Pt,{key:"pty-notice",marginTop:18,paddingX:1},ke.createElement(Zt,{color:Hn?"green":"yellow"},Hn?"\u2713 Advance Interactive Terminal Supported":"\u26A0 Interactive Terminal is Limited"))),Ue&&A.push(ke.createElement(Pt,{key:"conflict-warning",marginTop:1,paddingX:1},ke.createElement(Zt,{color:"red",dimColor:!0,italic:!0},"* Conflicting commands will be ignored and defaulted to highest priority"))),A})():ke.createElement(Pt,{paddingX:1},ke.createElement(Zt,{color:"gray",italic:!0},ln[l].desc)))),ke.createElement(Pt,{paddingX:1,marginTop:0,flexDirection:"row",justifyContent:"space-between"},ke.createElement(Zt,{color:"gray",dimColor:!0,italic:!0},m==="categories"?"\u25B2\u25BC Select Category \u2022 Enter/\u25BA to configure":"\u25B2\u25BC Select Option \u2022 Enter to Toggle \u2022 \u25C4/ESC to go back"),m==="categories"&&ke.createElement(Zt,{color:"gray",dimColor:!0},ln[l].desc)))}var ln,va,Ks,Da=ie(async()=>{await Or();ln=[{id:"memory",label:"\u{1F9E0} Memory",desc:"Manage system context & agent's memory"},{id:"security",label:"\u{1F512} Security",desc:"Configure permissions & data safety"},{id:"updater",label:"\u{1F504} Updater",desc:"Manage application updates"},{id:"other",label:"\u{1F4CB} Other",desc:"Miscellaneous preferences"},{id:"exit",label:"\u{1F6AA} Exit Settings",desc:"Return to chat view"}],va=e=>{let o=e.autoApproveCommands||"",t=e.autoDisallowCommands||"",n=e.alwaysAskCommands||"",s=e.autoExec===!1&&e.allowExternalAccess===!1&&e.networkAccess===!1&&o===""&&t==="rm -rf, rm -f, del /f, del /q, rd /s, rmdir /s, format, mkfs, dd if=/dev, shred, srm, Remove-Item -Recurse -Force, Initialize-Disk, Clear-Disk, format c:, flashrom, nvram -c"&&n==="killall, pkill, taskkill, shutdown, reboot, init 0, init 6, Stop-Process, Stop-Service, mv /*, move c:\\*, chmod 000, chmod -R 777, chown, icacls, netsh advfirewall, iptables -F, ufw disable, git reset --hard, git clean -fd, npm r, npm uninstall"&&e.autoApproveGit===!1,r=e.autoExec===!0&&e.allowExternalAccess===!1&&e.networkAccess!==!1&&o==="ls, dir, cat, type, echo, pwd, cd, git status, git log, git diff, git branch, git show, help, mkdir, touch, md, whoami, hostname, ps, Get-Process, date, time, mkdir"&&t==="rm -rf, rm -f, del /f, del /q, rd /s, rmdir /s, format, mkfs, dd if=/dev, shred, srm, Remove-Item -Recurse -Force, Initialize-Disk, Clear-Disk, format c:, flashrom, nvram -c"&&n==="killall, pkill, taskkill, Stop-Process, mv /*, move c:\\*, chmod 000, chmod -R 777, chown, icacls, shutdown, reboot, init 0, init 6, git reset --hard, git clean -fd, npm r, npm uninstall"&&e.autoApproveGit===!1,a=e.autoExec===!0&&e.allowExternalAccess===!0&&e.networkAccess!==!1&&o==="ls, dir, cat, type, echo, pwd, cd, git status, git log, git diff, git branch, git show, help, mkdir, touch, md, whoami, hostname, ps, Get-Process, date, time, mkdir"&&t===""&&n==="rm -rf, rm -f, del /f, del /q, rd /s, rmdir /s, format, mkfs, dd if=/dev, shred, srm, Remove-Item -Recurse -Force, Initialize-Disk, Clear-Disk, format c:, flashrom, nvram -c"&&e.autoApproveGit===!0;return s?"Strict":r?"Balanced":a?"Autonomous":e.sandboxPreset||"Custom"},Ks=e=>!e||e.trim()===""?"None":e.length>40?e.substring(0,40)+"...":e});import $o,{useState as qs,useEffect as Jc}from"react";import{Box as ar,Text as us}from"ink";import Qc from"ink-text-input";function zs({initialData:e,onSave:o,onCancel:t}){let[n,s]=qs(0),[r,a]=qs(""),[u,f]=qs(()=>({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): "}];Jc(()=>{let l=m[n].key;a(u[l]||"")},[n,u]);let c=l=>{if(l.trim().toLowerCase()==="/cancel"){t();return}let d=m[n].key,p={...u,[d]:l.trim()};f(p),a(""),n<m.length-1?s(n+1):o(p)};return $o.createElement(ar,{borderStyle:"round",borderColor:"gray",padding:0,marginTop:1,flexShrink:0,flexDirection:"column",width:"100%"},$o.createElement(ar,{paddingX:1,marginBottom:1},$o.createElement(us,{color:"magenta",bold:!0},"\u{1F464} DEVELOPER PROFILE CONFIGURATION")),$o.createElement(ar,{paddingX:1,flexDirection:"column"},$o.createElement(ar,null,$o.createElement(us,{color:"cyan",bold:!0},m[n].label),$o.createElement(Qc,{value:r,onChange:a,onSubmit:c})),$o.createElement(ar,{marginTop:1},$o.createElement(us,{color:"gray",dimColor:!0,italic:!0},"Step ",n+1," of ",m.length))),$o.createElement(ar,{paddingX:1,marginTop:1},$o.createElement(us,{color:"gray",dimColor:!0,italic:!0},"(Enter to submit \u2022 Type /cancel to abort)")))}var Oa=ie(()=>{});import mt,{useState as Js}from"react";import{Box as vo,Text as cn,useInput as Zc}from"ink";import eu from"ink-text-input";var tu,La,Fa=ie(()=>{sn();tu=({question:e,options:o,onResolve:t})=>{let[n,s]=Js(!1),[r,a]=Js(""),[u,f]=Js(0),m=[...o,{id:"CUSTOM",label:"Suggest something else...",description:"Provide a custom response"}];Zc((l,d)=>{if(!n&&((d.leftArrow||d.upArrow)&&f(p=>Math.max(0,p-1)),(d.rightArrow||d.downArrow)&&f(p=>Math.min(m.length-1,p+1)),d.return)){let p=m[u];p.id==="CUSTOM"?s(!0):t(p.label)}});let c=ve(2);return n?mt.createElement(vo,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},mt.createElement(vo,{paddingX:1},mt.createElement(cn,{color:"cyan",bold:!0},"\u{1F4AC} SUGGEST SOMETHING ELSE")),mt.createElement(vo,{marginTop:1,paddingX:1},mt.createElement(cn,{italic:!0,color:"gray"},"Replying to: ",e)),mt.createElement(vo,{marginTop:1,paddingX:1,flexDirection:"row"},mt.createElement(cn,{color:"cyan",bold:!0},"\u{1F4A0} "),mt.createElement(eu,{value:r,onChange:a,onSubmit:()=>t(r)})),mt.createElement(vo,{marginTop:1,paddingX:1,marginBottom:1},mt.createElement(cn,{color:"gray",dimColor:!0,italic:!0},"(Press Enter to send)"))):mt.createElement(vo,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},mt.createElement(vo,{paddingX:1,marginBottom:1},mt.createElement(cn,{color:"cyan",bold:!0},"\u{1F4AC} AGENT REQUEST: ACTION REQUIRED")),mt.createElement(vo,{paddingX:1,marginBottom:1},mt.createElement(cn,{bold:!0,color:"white"},e)),mt.createElement(vo,{flexDirection:"column",width:"100%"},m.map((l,d)=>{let p=d===u;return mt.createElement(vo,{key:l.id,flexDirection:"column",width:"100%",backgroundColor:p?"#2a2a2a":void 0,paddingX:1,marginBottom:d===m.length-1?0:1},mt.createElement(cn,{color:p?"cyan":"white",bold:p},p?"\u276F ":" ",l.label),l.description&&mt.createElement(vo,{marginLeft:4},mt.createElement(cn,{color:"gray",italic:!0,dimColor:!0},l.description)))})),mt.createElement(vo,{paddingX:1,marginTop:1,marginBottom:1},mt.createElement(cn,{color:"gray",dimColor:!0,italic:!0},"(Use Arrows to navigate, Enter to confirm)")))},La=tu});var $a,Pa=ie(()=>{$a=(e=!0,o=!0)=>`
|
|
113
113
|
Your tool syntax is: '[tool:functions.ToolName(args...)]'
|
|
114
114
|
|
|
115
115
|
-- CHAT MANAGEMENT TOOLS (MUST CALL THESE 2 TOOLS ALWAYS) --
|
|
@@ -134,7 +134,7 @@ Explicit Triggers for permanent memory:
|
|
|
134
134
|
|
|
135
135
|
Usage Rules:
|
|
136
136
|
- Frequency for 'user' action: Based on explicit triggers.
|
|
137
|
-
- IF YOU WANT TO SAVE SOMETHING, BUT SIMILAR MEMORY ALREADY EXISTS, USE THE UPDATE METHOD NOT THE ADD METHOD`:""}`.trim()});var
|
|
137
|
+
- IF YOU WANT TO SAVE SOMETHING, BUT SIMILAR MEMORY ALREADY EXISTS, USE THE UPDATE METHOD NOT THE ADD METHOD`:""}`.trim()});var Qs,_a=ie(()=>{Qs={xHigh:`EFFORT LEVEL: MAX
|
|
138
138
|
Think in a continuous, relentless analytical monologue within <think>...</think>. Engage in adversarial self interrogation that treats every assumption as hostile until proven:
|
|
139
139
|
Deconstruct requirements into atomic invariants. Trace every implicit dependency, side effect, and state mutation. Map the entire dependency graph and identify circular dependencies or tight coupling before they manifest
|
|
140
140
|
Evaluate algorithmic complexity (time/space) for every operation. Consider memory models, cache locality, and allocation patterns. For concurrent systems, reason through race conditions, deadlocks, and memory ordering
|
|
@@ -188,24 +188,24 @@ RULES:
|
|
|
188
188
|
- Suitable for simple requests/greetings`,Off:`EFFORT LEVEL: INSTANT
|
|
189
189
|
No thinking. Immediate response
|
|
190
190
|
RULES:
|
|
191
|
-
- Verify ALL imports and system stability, AVOID ANY Syntax errors, re-read TOOL RESULTS/files to verify`}});import
|
|
192
|
-
${e}`:"",
|
|
193
|
-
${o}`:"",s].filter(u=>u.length>0);return
|
|
194
|
-
${
|
|
191
|
+
- Verify ALL imports and system stability, AVOID ANY Syntax errors, re-read TOOL RESULTS/files to verify`}});import nu from"fs";var Zs,Na,Ba,Ua,Ra=ie(async()=>{await js();Pa();_a();Zs=null,Na=(e="",o="",t=!0,n=!1)=>{if(!t)return"";let s=e?.length>0&&!n?`-- RECENT CONTEXT FROM OTHER CHATS (PRIORITY: DYNAMIC-LOW, FOCUS: Chat Context > Recent) --
|
|
192
|
+
${e}`:"",a=[o?.length>0?`--- SAVED MEMORIES (PRIORITY: MEDIUM, USER PREFERENCES) ---
|
|
193
|
+
${o}`:"",s].filter(u=>u.length>0);return a.length>0?`[SYSTEM CONTEXT]
|
|
194
|
+
${a.join(`
|
|
195
195
|
|
|
196
196
|
`)}
|
|
197
|
-
`:""},
|
|
197
|
+
`:""},Ba=(e,o,t,n,s=!0,r=!1,a="Google",u=!1)=>{let f="";if(o!=="GEM"){let T=o;o==="Fast"&&(T="Off"),o==="Low"&&(T="Minimal"),o==="Standard"&&(T="Medium"),(o==="xHigh"||o==="Max")&&(T="xHigh"),f=Qs[T]||Qs.Medium}let m=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",c=e.instructions&&e.instructions?.length>0?`User Instructions: ${e.instructions}
|
|
198
198
|
|
|
199
|
-
`:"",
|
|
199
|
+
`:"",l=e.nickname&&e.nickname?.length>0?`User Nickname: ${e.nickname}
|
|
200
200
|
${c.length?"":`
|
|
201
201
|
`}`:"",d=e.name&&e.name?.length>0?`User Name: ${e.name}
|
|
202
|
-
${
|
|
203
|
-
`}`:"",p=process.cwd(),h=(()=>{let T=process.cwd().toLowerCase();if(process.platform==="win32"){let
|
|
202
|
+
${l.length||c.length?"":`
|
|
203
|
+
`}`:"",p=process.cwd(),h=(()=>{let T=process.cwd().toLowerCase();if(process.platform==="win32"){let b=process.env.SystemRoot?.toLowerCase()||"c:\\windows",L=process.env.ProgramFiles?.toLowerCase()||"c:\\program files",P=process.env["ProgramFiles(x86)"]?.toLowerCase()||"c:\\program files (x86)";return T.startsWith(b)||T.startsWith(L)||T.startsWith(P)}else return T==="/"||["/bin","/sbin","/etc","/usr","/var","/root"].some(L=>T.startsWith(L))})(),S=[{name:"Fluxflow.md",desc:"HIGH PRIORITY. Overrides other files"},{name:"README.md",desc:"Goals"},{name:"Agent.md",desc:"Standards"},{name:"Skills.md",desc:"Workflows"},{name:"design.md",desc:"UI/UX"},{name:"architecture.md",desc:"System Structure"}];if(r||Zs===null){let T=S.filter(b=>nu.existsSync(b.name));Zs=t==="Flux"&&T.length>0?`
|
|
204
204
|
-- PROJECT CONTEXT (Source of Truth) --
|
|
205
|
-
${T.map(
|
|
205
|
+
${T.map(b=>`- ${b.name}: ${b.desc}`).join(`
|
|
206
206
|
`)}
|
|
207
207
|
Check these first; These Files > Training Data. Safety rules apply
|
|
208
|
-
`:""}let w=
|
|
208
|
+
`:""}let w=Zs;return`${d}${l}${c}[SYSTEM]
|
|
209
209
|
Identity: Flux Flow (by Kushal Roy Chowdhury). Conversational, Sassy${t==="Flux"?", Respectful":", Friendly, Humorous, Sarcastic"}, CLI Agent
|
|
210
210
|
Mode: ${t}${o!=="Fast"?" (Thinking)":""}. ${t==="Flux"?"Logical, Highly Detailed, Task-Driven. Prioritizes scalable file/folder structures, modular architecture, clean code abstractions, step-by-step execution. Industry standard latest coding practices/libraries, clean code, Double Check Imports, Client-Server Sync":"Concise"}
|
|
211
211
|
|
|
@@ -216,7 +216,7 @@ Mode: ${t}${o!=="Fast"?" (Thinking)":""}. ${t==="Flux"?"Logical, Highly Detailed
|
|
|
216
216
|
-- MARKERS --
|
|
217
217
|
- TOOL SYSTEM: [TOOL RESULT] (system priority)
|
|
218
218
|
- SYSTEM NOTIFICATION: [SYSTEM], [METADATA] in user turn
|
|
219
|
-
${
|
|
219
|
+
${a==="Google"?`${o!=="GEM"?`
|
|
220
220
|
-- THINKING RULES --
|
|
221
221
|
${f}
|
|
222
222
|
${o!=="Fast"?`
|
|
@@ -224,7 +224,7 @@ CRITICAL THINKING POLICY
|
|
|
224
224
|
- ALWAYS use <think> ... </think> before responding, even with simple queries/greetings
|
|
225
225
|
- ${o==="Low"||o==="Medium"||o==="Fast"?"C":"Interrogate approaches adversarially, but c"}ommit once best solution is determined through analysis. Avoid spiraling after reaching decision point
|
|
226
226
|
`:""}`:""}`:""}
|
|
227
|
-
${
|
|
227
|
+
${Ia(t,m,a.toLowerCase()==="deepseek"?!1:u,a)}
|
|
228
228
|
${w}
|
|
229
229
|
-- MEMORY RULES --
|
|
230
230
|
- Memory: ${s?"Subtly Personalize. Auto Saves":"OFF. Decline Remembering Memories"}
|
|
@@ -239,7 +239,7 @@ PROTECTED DIRECTORY: ASK BEFORE MODIFYING`:""}
|
|
|
239
239
|
-- FORMATTING --
|
|
240
240
|
- GFM Supported
|
|
241
241
|
- NO LaTeX${t==="Flux"?"":". Kaomojis"}
|
|
242
|
-
[/SYSTEM]`.trim()},
|
|
242
|
+
[/SYSTEM]`.trim()},Ua=(e="",o=!0,t=!0)=>`${e?`-- CURRENT SAVED USER MEMORIES --
|
|
243
243
|
${e}
|
|
244
244
|
-------------------------------------------------
|
|
245
245
|
|
|
@@ -258,73 +258,73 @@ YOU ARE A SILENT BACKGROUND SYSTEM PROCESS. YOU HAVE NO MOUTH. YOUR ONLY OUTPUT
|
|
|
258
258
|
YOUR JOB: Analyze the 'User prompt' and 'Agent Raws' to extract facts for long-term memory or handle system tasks.
|
|
259
259
|
${o?"If user tell something that is important (like, hobbies, preferences, facts about user, hates, likes, etc) to know user better over time, use long term memory tools.":""}
|
|
260
260
|
|
|
261
|
-
${
|
|
261
|
+
${$a(o,t)}
|
|
262
262
|
|
|
263
263
|
Current date and Time: ${new Date().toLocaleString([],{year:"numeric",month:"numeric",day:"numeric",hour:"2-digit",hour12:!0})}.
|
|
264
|
-
=== END SYSTEM PROMPT ===`.trim()});import
|
|
265
|
-
`),n=[],s=null,r=/^\s*(?:DEBUG|ERROR|SEARCH|PUPPETEER)\b/i;for(let
|
|
266
|
-
`+
|
|
267
|
-
`):""),p=d.match(m);if(p){let h=
|
|
268
|
-
`).trim();c?await
|
|
269
|
-
`,"utf8"):await
|
|
270
|
-
Source: ${
|
|
271
|
-
Snippet: ${P}`}),t);if(c.length===0){if((await u.evaluate(()=>document.body.innerText)).includes("anomaly"))throw new Error("ANOMALY_DETECTED");return await
|
|
264
|
+
=== END SYSTEM PROMPT ===`.trim()});import wo from"fs-extra";import Gn from"path";var un,Ct,dn=ie(()=>{Gt();Oo();wo.ensureDirSync(xn);un=null,Ct={async startTransaction(e,o){un={id:`tx_prompt_${Date.now()}`,chatId:e,timestamp:new Date().toISOString(),prompt:o.trim(),changes:[],reverted:!1}},async recordFileChange(e,o=null){if(!un||un.changes.some(a=>a.filePath===e))return;let n=await wo.pathExists(e),s=n&&!o||o?"update":"create";!n&&!o&&(s="create");let r=null;if(n||o){s="update";let a=Gn.basename(e);r=`${un.id}_${a}.bak`;let u=Gn.join(xn,un.chatId);await wo.ensureDir(u);let f=Gn.join(u,r),m=o!==null?o:await wo.readFile(e,"utf8"),c=Cr(m);await wo.writeFile(f,c,"utf8")}un.changes.push({filePath:e,type:s,backupFile:r})},async commitTransaction(){if(!un)return;let e=ge(nn,[]);if(e.push(un),e.length>512e3){let o=e.shift();if(o.changes){for(let t of o.changes)if(t.backupFile){let n=Gn.join(xn,o.chatId,t.backupFile);await wo.remove(n)}}}$e(nn,e),un=null},async rollbackToBefore(e){let o=ge(nn,null);if(!o)throw new Error("No transaction ledger found.");let t=o.findIndex(u=>u.id===e);if(t===-1)throw new Error(`Transaction [${e}] not found.`);let n=o[t].chatId,s=o[t].prompt,r=o.slice(t).filter(u=>u.chatId===n&&!u.reverted).reverse();for(let u of r){for(let f of[...u.changes].reverse())if(f.type==="create")await wo.pathExists(f.filePath)&&await wo.remove(f.filePath);else if(f.type==="update"){let m=Gn.join(xn,u.chatId,f.backupFile);if(await wo.pathExists(m)){let c=await wo.readFile(m,"utf8"),l=wn(c);await wo.writeFile(f.filePath,l,"utf8")}}u.reverted=!0}for(let u of r)for(let f of u.changes)if(f.backupFile){let m=Gn.join(xn,u.chatId,f.backupFile);await wo.remove(m)}let a=o.filter(u=>!r.some(f=>f.id===u.id));return $e(nn,a),{success:!0,chatId:n,targetPrompt:s}},async getChatHistory(e){try{return ge(nn,[]).filter(t=>t.chatId===e&&!t.reverted)}catch{return[]}},async deleteChatBackups(e){try{let o=Gn.join(xn,e);await wo.remove(o);let t=ge(nn,[]),n=t.length;t=t.filter(s=>s.chatId!==e),t.length!==n&&$e(nn,t)}catch{}}}});import Ho from"fs-extra";import ru from"path";import{nanoid as su}from"nanoid";var Wa,ei,Po,ds,Ya,ti,oi,ja,iu,au,Ha,Ga,$r=ie(()=>{Oo();Gt();dn();Wa=Promise.resolve(),ei=e=>{let o=Wa.then(async()=>{try{return await e()}catch(t){throw console.error("Lock Operation Failed:",t),t}});return Wa=o.catch(()=>{}),o},Po=async()=>{if(await Ho.pathExists(Yn))try{return ge(Yn,{})}catch{return{}}return{}},ds=async(e,o,t)=>ei(async()=>{let n=await Po(),s=n[e],r=(t||[]).filter(u=>!u.isUpdateNotification&&!u.isMeta),a=o||(s?s.name:`Session ${e.slice(-6)}`);n[e]={name:a,messages:r,updatedAt:Date.now()},$e(Yn,n)}),Ya=async(e,o)=>ei(async()=>{let t=await Po();t[e]?(t[e].name=o,t[e].updatedAt=Date.now()):t[e]={name:o,messages:[],updatedAt:Date.now()},$e(Yn,t)}),ti=async e=>ei(async()=>{let o=await Po();delete o[e],$e(Yn,o);let t=ge(yo,{});t[e]&&(delete t[e],$e(yo,t));let n=ge(Yo,{});return n[e]&&(delete n[e],$e(Yo,n)),await Ct.deleteChatBackups(e),o}),oi=()=>`flow-${su(6)}`,ja=async e=>{if(!e||e==="Never")return;let o=parseInt(e);if(isNaN(o))return;let t=await Po(),n=Date.now(),s=o*24*60*60*1e3,r=0;for(let a in t){let u=t[a];u.updatedAt&&n-u.updatedAt>s&&(await ti(a),r++)}return r},iu=e=>{let o=e.replace(/[\[\]]/g,"").trim(),t=new Date(o);if(!isNaN(t.getTime()))return t.getTime();let n=o.split(/,\s*|\s+/);if(n.length===0)return null;let s=n[0],r=n[1]||"",a=n[2]||"",u=s.split(/[-/.]/).map(Number);if(u.length!==3)return null;let f,m,c;if(u[0]>1e3)f=u[0],m=u[1],c=u[2];else if(u[2]>1e3)f=u[2],u[0]>12?(c=u[0],m=u[1]):u[1]>12?(c=u[1],m=u[0]):(m=u[0],c=u[1]);else return null;let l=0,d=0,p=0;if(r){let S=r.split(":").map(Number);l=S[0]||0,d=S[1]||0,p=S[2]||0,a.toLowerCase()==="pm"&&l<12?l+=12:a.toLowerCase()==="am"&&l===12&&(l=0)}let h=new Date(f,m-1,c,l,d,p);return isNaN(h.getTime())?null:h.getTime()},au=async e=>{try{if(!await Ho.pathExists(e))return;let o=await Ho.readFile(e,"utf8");if(!o.trim())return;let t=o.split(`
|
|
265
|
+
`),n=[],s=null,r=/^\s*(?:DEBUG|ERROR|SEARCH|PUPPETEER)\b/i;for(let l of t)r.test(l)?(s&&n.push(s),s={header:l,body:[]}):s?s.body.push(l):n.push({header:l,body:[]});s&&n.push(s);let a=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 l of n){let d=l.header+(l.body.length>0?`
|
|
266
|
+
`+l.body.join(`
|
|
267
|
+
`):""),p=d.match(m);if(p){let h=iu(p[1]);if(h&&u-h>a)continue}f.push(d)}let c=f.join(`
|
|
268
|
+
`).trim();c?await Ho.writeFile(e,c+`
|
|
269
|
+
`,"utf8"):await Ho.writeFile(e,"","utf8")}catch{}},Ha=async e=>{try{if(!await Ho.pathExists(e))return;let o=async t=>{let n=await Ho.readdir(t);for(let s of n){let r=ru.join(t,s);(await Ho.stat(r)).isDirectory()?(await o(r),(await Ho.readdir(r)).length===0&&await Ho.remove(r)):s.endsWith(".log")&&await au(r)}};await o(e)}catch{}},Ga=(e,o=4)=>{if(e.length<=1)return e;let t=e[0],n=e.slice(1),s=o*2,r=n.slice(s);return[t,...r]}});import nt from"fs-extra";import Go from"path";import ni from"os";var lu,mn,cu,xt,kn,Xa,ms,ri,Ka,si,ii,Va,qa,In,Xo,To,ai,li,za,Ja,fs,Qa,ps=ie(()=>{Gt();Oo();lu=()=>{if(process.platform==="win32"){let o=process.env.LOCALAPPDATA||Go.join(ni.homedir(),"AppData","Local");return Go.join(o,"FxFl","backups","backup.json")}if(process.platform==="darwin")return Go.join(ni.homedir(),"Library","Application Support","FxFl","backups","backup.json");let e=process.env.XDG_DATA_HOME||Go.join(ni.homedir(),".local","share");return Go.join(e,"fxfl","backups","backup.json")},mn=lu(),cu=()=>Math.random().toString(36).substring(2)+Date.now().toString(36),xt=null,kn=null,Xa=0,ms=!1,ri={agent:0,background:0,search:0,toolSuccess:0,toolFailure:0,toolDenied:0,duration:0,tokens:0,cachedTokens:0,candidateTokens:0,linesAdded:0,linesRemoved:0,imageCalls:[]},Ka=async()=>{let e=new Date().toISOString().split("T")[0],o=Jt+".tmp",t=null,n=null;try{if(await nt.exists(o)){let r=(await nt.readFile(o,"utf8")).trim(),a=null;if(r.startsWith("{")||r.startsWith("[")?a=JSON.parse(r):a=JSON.parse(wn(r)),a&&a.date&&a.stats){t=a;try{await nt.rename(o,Jt)}catch{}}else try{await nt.remove(o)}catch{}}}catch{try{await nt.remove(o)}catch{}}if(!t)try{if(await nt.exists(Jt)){let r=(await nt.readFile(Jt,"utf8")).trim();r.startsWith("{")||r.startsWith("[")?t=JSON.parse(r):t=JSON.parse(wn(r))}}catch{}try{if(await nt.exists(mn)){let r=(await nt.readFile(mn,"utf8")).trim();r.startsWith("{")||r.startsWith("[")?n=JSON.parse(r):n=JSON.parse(wn(r))}}catch{}let s=null;if(t&&n)if(t.saveId!==n.saveId){s=t;try{await nt.ensureDir(Go.dirname(mn)),await nt.copy(Jt,mn)}catch{}}else s=t;else if(t&&!n){s=t;try{await nt.ensureDir(Go.dirname(mn)),await nt.copy(Jt,mn)}catch{}}else if(!t&&n){s=n;try{await nt.ensureDir(Go.dirname(Jt)),await nt.copy(mn,Jt)}catch{}}if(s&&s.date===e&&s.stats){let r={...ri,...s.stats};return Array.isArray(r.imageCalls)||(r.imageCalls=[]),{...s,stats:r}}return{date:e,stats:{...ri}}},si=async()=>{if(!(!ms||!xt))try{await nt.ensureDir(Go.dirname(Jt));let e=null;try{if(await nt.exists(Jt)){let s=(await nt.readFile(Jt,"utf8")).trim();s.startsWith("{")||s.startsWith("[")?e=JSON.parse(s):e=JSON.parse(wn(s))}}catch{}if(e&&e.date===xt.date&&e.stats){for(let s in xt.stats)if(e.stats[s]!==void 0)if(Array.isArray(xt.stats[s])){let r=Array.isArray(e.stats[s])?e.stats[s]:[],a=xt.stats[s],u=new Map;for(let f of[...r,...a])f&&f.timestamp&&u.set(f.timestamp,f);xt.stats[s]=Array.from(u.values())}else typeof xt.stats[s]=="number"&&(xt.stats[s]=Math.max(xt.stats[s],Number(e.stats[s])||0))}xt.saveId=cu();let o=Jt+".tmp",t=Cr(JSON.stringify(xt,null,2));await nt.writeFile(o,t,"utf8");let n=await nt.open(o,"r+");await nt.fsync(n),await nt.close(n),await nt.rename(o,Jt);try{await nt.ensureDir(Go.dirname(mn)),await nt.copy(Jt,mn)}catch{}ms=!1,Xa=Date.now()}catch{}},ii=()=>{if(ms=!0,kn)return;let e=Date.now(),o=Math.max(0,1500-(e-Xa));kn=setTimeout(async()=>{await si(),kn=null},o),kn.unref&&kn.unref()},Va=async()=>{xt=await Ka()},qa=async()=>{kn&&(clearTimeout(kn),kn=null),await si()},In=async()=>{let e=new Date().toISOString().split("T")[0];return xt?xt.date!==e&&(xt={date:e,stats:{...ri}},ms=!0,await si()):xt=await Ka(),xt&&xt.stats&&!Array.isArray(xt.stats.imageCalls)&&(xt.stats.imageCalls=[]),xt.stats},Xo=async e=>{let o=await In();o[e]!==void 0&&(o[e]++,ii())},To=async(e,o)=>{let t=await In();t[e]!==void 0&&(t[e]+=Math.floor(o),ii())},ai=async(e,o)=>{let t=await In(),n=o.apiTier||"Free",s=o.quotas||{};if(n==="Free"){if(e==="agent"||e==="background")return t.agent+t.background<999999;if(e==="search")return!0}if(n==="Paid"||n==="Custom"){if(e==="agent")return t.agent<(s.agentLimit||999999);if(e==="background")return t.background<(s.backgroundLimit||999999);if(e==="search")return t.search<(s.searchLimit||100)}return!0},li=e=>{if(!e||e.length===0)return[];let t=[...e].sort((s,r)=>s.timestamp-r.timestamp),n=[];for(let s of t){if(n.length>0){let r=n[n.length-1];if(s.timestamp>=r.start&&s.timestamp<r.end){r.calls.push(s),r.spent+=s.cost;continue}}n.push({start:s.timestamp,end:s.timestamp+36e5,calls:[s],spent:s.cost})}return n},za=(e,o)=>{if(!e||e.length===0)return .025;let n=li(e);if(n.length===0)return .025;let s=[];for(let l of n){let d=.025;if(s.length>0){let h=s[s.length-1],S=!1;if(s.length>=2){let w=s[s.length-2];h.ratio>=.8&&w.ratio>=.8&&(S=!0)}if(S)d=.015;else{let w=h.limit,T=h.ratio;T>=.8?d=w===.015?.015:w:T<.4?d=Math.min(.025,w+.005):T>=.4&&T<.6?d=Math.min(.025,w+.004):d=Math.min(.025,w+.002)}}let p=d>0?l.spent/d:0;s.push({limit:d,spent:l.spent,ratio:p})}let r=n[n.length-1];if(o<r.end)return s[s.length-1].limit;let a=s[s.length-1].limit,u=a,f=s[s.length-1].ratio,m=r.end,c=0;for(let l=s.length-1;l>=0&&s[l].ratio>=.8;l--)c++;for(;m<=o;){let l=.025;c>=2?l=.015:f>=.8?l=u===.015?.015:u:f<.4?l=Math.min(.025,u+.005):f>=.4&&f<.6?l=Math.min(.025,u+.004):l=Math.min(.025,u+.002),u=l,f=0,c=0,m+=36e5,a=l}return a},Ja=async e=>{let o=e.imageSettings||{keyType:"Default",quality:"Low-High"};if(o.keyType!=="Default")return!0;let n={Low:.001,"Low-High":.002,Medium:.008,"Medium-High":.01,High:.045,Ultra:.0488,Premium:.15}[o.quality]||.002,s=await In();s.imageCalls||(s.imageCalls=[]);let r=Date.now(),a=li(s.imageCalls),u=0;if(a.length>0){let m=a[a.length-1];r>=m.start&&r<m.end&&(u=m.spent)}let f=za(s.imageCalls,r);return u+n<=f},fs=async()=>{let e=await In();e.imageCalls||(e.imageCalls=[]);let o=Date.now(),t=li(e.imageCalls),n=[],s=0,r=0;if(t.length>0){let m=t[t.length-1];o>=m.start&&o<m.end&&(n=m.calls,s=m.spent,r=Math.max(0,Math.ceil((m.end-o)/(60*1e3))))}let a=za(e.imageCalls,o),u=Math.max(0,a-s),f=s;return{totalSpent:s,remaining:u,activeCallsCount:n.length,nextResetMin:r,reclaimCost:f,limit:a}},Qa=async e=>{let o=e.imageSettings||{keyType:"Default",quality:"Low-High"},n={Low:.001,"Low-High":.002,Medium:.008,"Medium-High":.01,High:.045,Ultra:.0488,Premium:.1}[o.quality]||.002,s=await In();s.imageCalls||(s.imageCalls=[]),s.imageCalls.push({timestamp:Date.now(),cost:n}),ii()}});import uu from"puppeteer";var ci,Za=ie(()=>{Qt();Gt();ci=async e=>{let{query:o,limit:t=10}=re(e);if(!o)return'ERROR: Missing "query" argument for web_search.';let n=3,s=null;for(let r=1;r<=n;r++){let a=null;try{a=await uu.launch({headless:!0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let u=await a.newPage();await u.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.97 Safari/537.36"),await u.setViewport({width:1366,height:768});let f=r===1?Math.random()*1e3+500:Math.random()*2e3+1e3;await new Promise(d=>setTimeout(d,f));let m=`https://html.duckduckgo.com/html/?q=${encodeURIComponent(o)}`;await u.goto(m,{waitUntil:"networkidle2",timeout:18e4});let c=await u.$$eval(".result",(d,p)=>d.slice(0,p).map((h,S)=>{let w=h.querySelector(".result__a"),T=h.querySelector(".result__snippet"),b=w?w.href:"";b.includes("uddg=")&&(b=decodeURIComponent(b.split("uddg=")[1].split("&")[0]));let L=w?w.innerText.trim():"No Title",P=T?T.innerText.trim():"No Snippet";return`${S+1}. ${L}
|
|
270
|
+
Source: ${b}
|
|
271
|
+
Snippet: ${P}`}),t);if(c.length===0){if((await u.evaluate(()=>document.body.innerText)).includes("anomaly"))throw new Error("ANOMALY_DETECTED");return await a.close(),`No results found for query: [${o}].`}let l=c.join(`
|
|
272
272
|
|
|
273
|
-
`);return await
|
|
273
|
+
`);return await a.close(),`Search results for [${o}]:
|
|
274
274
|
|
|
275
|
-
${
|
|
275
|
+
${l}`}catch(u){if(s=u,a&&await a.close(),r<n){let f=Math.pow(2,r)*1e3;await new Promise(m=>setTimeout(m,f))}}}return`ERROR: Search failed after ${n+1} attempts. Last error: ${s.message}`}});import du from"puppeteer";var ui,el=ie(()=>{Gt();ui=async e=>{let o=e.match(/url\s*=\s*["'](.*)["']/),t=o?o[1]:e,n=3,s=null;for(let r=1;r<=n;r++){let a=null;try{a=await du.launch({headless:!0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let u=await a.newPage();await u.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.97 Safari/537.36"),await u.setViewport({width:1366,height:768});let f=r===1?Math.random()*1e3+500:Math.random()*2e3+1e3;await new Promise(l=>setTimeout(l,f)),await u.goto(t,{waitUntil:"networkidle2",timeout:18e4}),await new Promise(l=>setTimeout(l,5e3));let m=await u.evaluate(()=>{document.querySelectorAll("script, style, nav, footer, header, noscript, svg, canvas, iframe, ad, .ads, link, meta, img").forEach(w=>w.remove());let d=document.createNodeIterator(document.body,NodeFilter.SHOW_COMMENT),p;for(;p=d.nextNode();)p.remove();document.querySelectorAll("*").forEach(w=>{let T=w.attributes;for(let b=T.length-1;b>=0;b--){let L=T[b].name;L!=="href"&&L!=="src"&&w.removeAttribute(L)}(w.tagName==="SPAN"||w.tagName==="DIV"||w.tagName==="SECTION")&&w.attributes.length===0&&(w.tagName==="SPAN"||w.tagName==="DIV"&&w.childNodes.length===1&&w.childNodes[0].nodeType===Node.TEXT_NODE)&&w.replaceWith(...w.childNodes)});let S=()=>{let w=!1;document.querySelectorAll("*:not(br)").forEach(T=>{T.childNodes.length===0&&!T.innerText.trim()&&(T.remove(),w=!0)}),w&&S()};return S(),document.body.innerHTML});if(!m)throw new Error("EMPTY_RENDER_RESULT");let c=m.replace(/\s+/g," ").replace(/>\s+</g,"><").trim().substring(0,3e4);return await a.close(),`CLEANED HTML FROM [${t}]:
|
|
276
276
|
|
|
277
277
|
${c}${m.length>3e4?`
|
|
278
278
|
|
|
279
|
-
[TRUNCATED AT 30K CHARS]`:""}`}catch(u){if(s=u,
|
|
279
|
+
[TRUNCATED AT 30K CHARS]`:""}`}catch(u){if(s=u,a&&await a.close(),r<n){let f=Math.pow(2,r)*1e3;await new Promise(m=>setTimeout(m,f))}}}return`ERROR: Scrape failed after ${n+1} attempts. Last error: ${s.message}`}});var mu,di,tl=ie(()=>{Oo();Gt();mu=4*(1024*2),di=async(e,o={})=>{let t=c=>{let l=new RegExp(`${c}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),d=e.match(l);if(d)return d[2].trim();let p=new RegExp(`${c}\\s*[:=]\\s*([^,\\s)]+)`,"s"),h=e.match(p);return h?h[1].trim():null},n=t("action"),s=t("method"),r=t("content"),a=t("content-new"),u=t("content-old"),f=t("id"),m=t("chat-id")||o.chatId||o.sessionId||"default-session";if(n==="temp"){if(!r)return"ERROR: Missing 'content' for temp memory.";let c=ge(yo,{});c[m]||(c[m]=[]),c[m].push(r),$e(yo,c);let l=c[m].reduce((d,p)=>d+p.length,0);return`SUCCESS: Temporary context saved for session [${m}]. (Size: ${l} chars)`}if(n==="user"){let c=ge(Ht,[]).map(l=>(l.score===void 0&&(l.score=.5),l));if(s==="add"){if(!r)return"ERROR: Missing 'content' for memory addition.";let l=new Date,d=`${l.getDate()}/${l.getMonth()+1}/${l.getFullYear()}`,p=r.includes("[Saved on:")?r:`${r.trim()} [Saved on: ${d}]`,h=mu,S=c.reduce((L,P)=>L+(P.memory?.length||0),0);for(;c.length>0&&S+p.length>h;){let L=c.shift();S-=L.memory?.length||0}let w=t("score"),T=w?parseFloat(w):.5,b={id:`mem-${Date.now().toString(36)}`,memory:p,score:Math.min(2,isNaN(T)?.5:T)};return c.push(b),$e(Ht,c),`SUCCESS: Memory added with ID [${b.id}] and score [${b.score}]. (Vault Size: ${S+p.length} chars)`}if(s==="update"){let l=f||u,d=a||r;if(!l||!d)return"ERROR: Missing 'id' or content for update.";let p=c.findIndex(T=>T.id===l);if(p===-1)return`ERROR: Memory ID [${l}] not found.`;let h=new Date,S=`${h.getDate()}/${h.getMonth()+1}/${h.getFullYear()}`,w=d.includes("[Saved on:")?d:`${d.trim()} [Saved on: ${S}]`;return c[p].memory=w,$e(Ht,c),`SUCCESS: Memory [${l}] updated.`}if(s==="delete"){let l=f||r;if(!l)return"ERROR: Missing 'id' for deletion.";let d=c.length,p=c.filter(h=>h.id!==l);return p.length===d?`ERROR: Memory ID [${l}] not found.`:($e(Ht,p),`SUCCESS: Memory [${l}] deleted.`)}return`ERROR: Invalid method [${s}] for user memory. Use 'add', 'update', or 'delete'.`}return`ERROR: Unknown action [${n}] for memory tool.`}});var mi,ol=ie(()=>{$r();Qt();mi=async(e,o={})=>{let t=re(e).title,n=o.chatId||o.sessionId;if(!n)return"ERROR: No active chatId found in tool context.";if(!t)return"ERROR: Missing 'title' argument.";try{return await Ya(n,t),`SUCCESS: Chat title updated to [${t}] for session [${n}].`}catch(s){return`ERROR: Failed to update chat title: ${s.message}`}}});import hs from"fs";import nl from"path";var fi,rl=ie(()=>{Qt();fi=async(e,o={})=>{let{path:t,StartLine:n,EndLine:s,start_line:r,end_line:a,startLine:u,endLine:f}=re(e),m=parseInt(n||r||u),c=parseInt(s||a||f),l=m||1,d=c||(m?m+800:800);if(!t)return'ERROR: Missing "path" argument for view_file.';let p=nl.resolve(process.cwd(),t);try{if(!hs.existsSync(p))return`ERROR: File [${t}] does not exist.`;if(hs.statSync(p).isDirectory())return`ERROR: Path [${t}] is a directory. Use list_files instead.`;let S=nl.extname(t).toLowerCase();if([".mp4",".mkv",".avi",".mov",".webm",".flv",".wmv",".mpeg",".mpg"].includes(S))return`ERROR: Unable to read. Type ${S.slice(1).toUpperCase()} not supported`;let T={".pdf":"application/pdf",".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".webp":"image/webp",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".doc":"application/msword"};if(T[S]){if(!(o.isMultiModal!==!1))return`ERROR: Multimodality is not supported for the current model. Unable to load [${t}].`;let V=hs.readFileSync(p).toString("base64"),_=T[S];return{text:`[BINARY FILE]: ${t} (${_}) - Loaded as multimodal part.`,binaryPart:{inlineData:{data:V,mimeType:_}}}}let b=hs.readFileSync(p,"utf8");b.startsWith("\uFEFF")&&(b=b.slice(1)),b=b.replace(/\r\n/g,`
|
|
280
280
|
`).replace(/\r/g,`
|
|
281
|
-
`);let
|
|
282
|
-
`),P=
|
|
283
|
-
`);return`${
|
|
281
|
+
`);let L=b.split(`
|
|
282
|
+
`),P=L.length,Y=Math.max(0,l-1),v=Math.min(P,d),D=L.slice(Y,v),A=`File: [${t}] (Showing lines ${Y+1}-${v} of ${P}).`,E=D.map((q,B)=>`${String(Y+B+1).padStart(4)}: ${q}`).join(`
|
|
283
|
+
`);return`${A}
|
|
284
284
|
|
|
285
|
-
${
|
|
285
|
+
${E}`}catch(h){return`ERROR: Failed to read file [${t}]: ${h.message}`}}});import lr from"fs";import sl from"path";var pi,il=ie(()=>{Qt();dn();pi=async(e,o={})=>{let{path:t,content:n}=re(e);if(!t)return'ERROR: Missing "path" argument for write_file.';if(n===void 0)return'ERROR: Missing "content" argument for write_file.';n=n.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
|
|
286
286
|
`).replace(/\r/g,`
|
|
287
|
-
`);let s=
|
|
288
|
-
${
|
|
287
|
+
`);let s=sl.resolve(process.cwd(),t),r=sl.dirname(s);try{await Ct.recordFileChange(s);let a="";if(lr.existsSync(s))try{a=`Old File contents:
|
|
288
|
+
${lr.readFileSync(s,"utf8").split(/\r?\n/).map((b,L)=>`${L+1} | ${b}`).join(`
|
|
289
289
|
`)}
|
|
290
290
|
|
|
291
|
-
`}catch{
|
|
291
|
+
`}catch{a=`[Note: Could not read existing file for reversal reference]
|
|
292
292
|
|
|
293
|
-
`}
|
|
293
|
+
`}lr.existsSync(r)||lr.mkdirSync(r,{recursive:!0});let f=(w=>w.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
|
|
294
294
|
`).replace(/\r/g,`
|
|
295
|
-
`))(n),m=f.split(/\r?\n/).length,c=Buffer.byteLength(f,"utf8");
|
|
295
|
+
`))(n),m=f.split(/\r?\n/).length,c=Buffer.byteLength(f,"utf8");lr.writeFileSync(s,f,"utf8");let l=lr.readFileSync(s,"utf8"),d=Buffer.byteLength(l,"utf8"),p=l.split(/\r?\n/),h=p.length;if(d===0&&c>0)return l=null,`ERROR: CRITICAL FAILURE: Verification failed. File [${t}] is empty on disk despite success report!`;let S="";if(h<=200)S=p.join(`
|
|
296
296
|
`);else{let w=p.slice(0,100).join(`
|
|
297
297
|
`),T=p.slice(-100).join(`
|
|
298
|
-
`);
|
|
298
|
+
`);S=`${w}
|
|
299
299
|
|
|
300
300
|
... [${h-200} lines truncated] ...
|
|
301
301
|
|
|
302
|
-
${T}`}return
|
|
302
|
+
${T}`}return l=null,`SUCCESS: File [${t}] saved.
|
|
303
303
|
|
|
304
304
|
- Stats: [${h} lines, ${(d/1024).toFixed(1)} KB]
|
|
305
|
-
${
|
|
306
|
-
${
|
|
305
|
+
${a}- Content Preview:
|
|
306
|
+
${S}
|
|
307
307
|
|
|
308
|
-
Check if Starting and Ending matches your write.`}catch(
|
|
308
|
+
Check if Starting and Ending matches your write.`}catch(a){return`ERROR: Failed to write file [${t}]: ${a.message}`}}});import hi from"fs";import fu from"path";var gi,al=ie(()=>{Qt();dn();jn();gi=async(e,o={})=>{let t=re(e),n=t.path;if(!n)return'ERROR: Missing "path" argument for update_file.';let{patchPairs:s,error:r}=ns(t);if(r)return`ERROR: ${r}`;if(s.length===0)return"ERROR: No valid replacement pairs found. Use replaceContent1, newContent1, etc.";let a=fu.resolve(process.cwd(),n);try{if(!hi.existsSync(a))return`ERROR: File [${n}] does not exist. Use write_file instead.`;let u=o.forcedContent||hi.readFileSync(a,"utf8");u.startsWith("\uFEFF")&&(u=u.slice(1));let f=u.replace(/\r\n/g,`
|
|
309
309
|
`).replace(/\r/g,`
|
|
310
|
-
`),{content:m,results:c}=
|
|
311
|
-
${
|
|
312
|
-
`)}`;await
|
|
310
|
+
`),{content:m,results:c}=rs(f,s),l=c.filter(h=>!h.success),d=c.filter(h=>h.success);if(d.length===0)return`ERROR: Patch Failed to apply to [${n}].
|
|
311
|
+
${l.map(h=>` \u2022 ${h.error}`).join(`
|
|
312
|
+
`)}`;await Ct.recordFileChange(a,f),hi.writeFileSync(a,m,"utf8");let p=ss(f,m,c,12);return l.length>0?`SUCCESS: File [${n}] updated with some blocks failed. [${d.length}/${s.length}] blocks applied.
|
|
313
313
|
|
|
314
314
|
Failures:
|
|
315
|
-
${
|
|
315
|
+
${l.map(h=>` \u2022 ${h.error}`).join(`
|
|
316
316
|
`)}
|
|
317
317
|
|
|
318
318
|
${p}`:`SUCCESS: File [${n}] updated. [${c.length}/${s.length}] blocks applied.
|
|
319
319
|
|
|
320
|
-
${p}`}catch(u){return`ERROR: Failed to update file [${n}]: ${u.message}`}}});import
|
|
320
|
+
${p}`}catch(u){return`ERROR: Failed to update file [${n}]: ${u.message}`}}});import gs from"fs";import ll from"path";var xi,cl=ie(()=>{Qt();xi=async e=>{let{path:o="."}=re(e),t=ll.resolve(process.cwd(),o);try{if(!gs.existsSync(t))return`ERROR: Path [${o}] does not exist.`;if(!gs.statSync(t).isDirectory())return`ERROR: Path [${o}] is a file, not a directory. Use view_file instead.`;let s=gs.readdirSync(t),r=s.length,a=100,u=s.slice(0,a),f=[];for(let d of u){let p=ll.join(t,d),h="\u{1F4C4}",S={name:d,type:"unknown",size:"N/A",mtime:"N/A"};try{let w=gs.statSync(p);S={name:d,type:w.isDirectory()?"directory":"file",size:(w.size/1024).toFixed(1)+" KB",mtime:w.mtime.toLocaleString()}}catch{S.type="inaccessible"}f.push(S)}let m=f.map(d=>{let p=d.type==="directory"?"\u{1F4C1}":d.type==="file"?"\u{1F4C4}":"\u2753";return d.type==="directory"?`${p} ${d.name} - [DIR] - [Modified: ${d.mtime}]`:`${p} ${d.name} - [Size: ${d.size}] - [Modified: ${d.mtime}]`}).join(`
|
|
321
321
|
`),c=`
|
|
322
322
|
|
|
323
|
-
(Total items in folder: ${r})`;r>
|
|
323
|
+
(Total items in folder: ${r})`;r>a&&(c=`
|
|
324
324
|
|
|
325
|
-
\u26A0\uFE0F TRUNCATED: Showing first ${
|
|
325
|
+
\u26A0\uFE0F TRUNCATED: Showing first ${a} of ${r} items.`);let l=`Detailed folder stats for [${o}]:
|
|
326
326
|
|
|
327
|
-
${m}${c}`;return s.length=0,u.length=0,f.length=0,
|
|
327
|
+
${m}${c}`;return s.length=0,u.length=0,f.length=0,l}catch(n){return`ERROR: Failed to read folder [${o}]: ${n.message}`}}});var yi,ul=ie(()=>{Qt();yi=async(e,o)=>{let t=re(e),{question:n}=t;if(!n)return'ERROR: Missing "question" argument for ask.';if(!o.onAskUser)return"ERROR: onAskUser callback not provided in tool context.";let s=[];Object.keys(t).forEach(r=>{if(r.startsWith("option")){let a=t[r];if(typeof a=="string"&&a.includes("::")){let[u,f]=a.split("::");s.push({id:r,label:u.trim(),description:f.trim()})}else s.push({id:r,label:String(a).trim(),description:""})}});try{return`USER CHOOSE: ${await o.onAskUser(n,s)}`}catch(r){return`ERROR: Failed to get user input: ${r.message}`}}});import pu from"puppeteer";import cr from"path";import Xn from"fs-extra";import{PDFDocument as hu}from"pdf-lib";var wi,dl=ie(()=>{Qt();dn();wi=async e=>{let{path:o,content:t,orientation:n="portrait",margin:s="0px"}=re(e);if(!o)return'ERROR: Missing "path" argument for write_pdf.';if(!t)return'ERROR: Missing "content" (HTML/CSS) for write_pdf.';let r=cr.resolve(process.cwd(),o),a=null;try{await Xn.ensureDir(cr.dirname(r)),await Ct.recordFileChange(r),a=await pu.launch({headless:!0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let u=await a.newPage(),f=t,m={},c=async v=>{if(!v||v.startsWith("http://")||v.startsWith("https://")||v.startsWith("data:"))return null;try{let D=cr.resolve(process.cwd(),v);if(await Xn.pathExists(D)){let A=cr.extname(D).toLowerCase().replace(".","")||"png",E=A==="jpg"?"jpeg":A==="svg"?"svg+xml":A,q=await Xn.readFile(D,"base64");return`data:image/${E};base64,${q}`}}catch{}return null},l=/<link[^>]+href=["']([^"']+)["']/gi,d={},p;for(;(p=l.exec(t))!==null;){let v=p[1],D=p[0];if(v&&D.toLowerCase().includes("stylesheet")&&!v.startsWith("http://")&&!v.startsWith("https://")&&!v.startsWith("data:"))try{let A=cr.resolve(process.cwd(),v);if(await Xn.pathExists(A)){let E=await Xn.readFile(A,"utf-8");d[D]=`<style>${E}</style>`}}catch{}}for(let[v,D]of Object.entries(d))f=f.split(v).join(D);let h=/<img[^>]+src=["']([^"']+)["']/gi;for(;(p=h.exec(f))!==null;){let v=p[1];if(v&&!m[v]){let D=await c(v);D&&(m[v]=D)}}let S=/url\(\s*['"]?([^'")]+?)['"]?\s*\)/gi;for(;(p=S.exec(f))!==null;){let v=p[1].trim();if(v&&!m[v]){let D=await c(v);D&&(m[v]=D)}}for(let[v,D]of Object.entries(m)){let A=v.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&"),E=new RegExp(`(src=["'])(${A})(["'])`,"gi");f=f.replace(E,`$1${D}$3`);let q=new RegExp(`url\\(\\s*(['"]?)(${A})\\1\\s*\\)`,"gi");f=f.replace(q,`url($1${D}$1)`)}let w=`
|
|
328
328
|
<style>
|
|
329
329
|
@page {
|
|
330
330
|
margin: ${s};
|
|
@@ -354,7 +354,7 @@ ${m}${c}`;return s.length=0,u.length=0,f.length=0,a}catch(n){return`ERROR: Faile
|
|
|
354
354
|
</style>
|
|
355
355
|
<div class="watermark">Generated by FluxFlow CLI (AI)</div>
|
|
356
356
|
${f}
|
|
357
|
-
`;await u.setContent(w,{waitUntil:"networkidle0",timeout:18e4});let T=await u.pdf({format:"A4",landscape:String(n).toLowerCase()==="landscape",margin:{top:s,right:s,bottom:s,left:s},printBackground:!0}),
|
|
357
|
+
`;await u.setContent(w,{waitUntil:"networkidle0",timeout:18e4});let T=await u.pdf({format:"A4",landscape:String(n).toLowerCase()==="landscape",margin:{top:s,right:s,bottom:s,left:s},printBackground:!0}),b=await hu.load(T),L=cr.basename(o);b.setTitle(`FluxFlow_${L}`),b.setAuthor("FluxFlow CLI"),b.setSubject("Generated with Agentic AI System"),b.setKeywords(["FluxFlow","AI","Agentic","Automated"]),b.setCreator("FluxFlow PDF Engine"),b.setProducer("FluxFlow (Generative AI)");let P=await b.save();await Xn.writeFile(r,P);let Y=await Xn.stat(r);return`SUCCESS: PDF generated successfully at [${o}] (${(Y.size/1024).toFixed(2)} KB).`}catch(u){return`ERROR: Failed to generate PDF [${o}]: ${u.message}`}finally{a&&await a.close()}}});import ml from"fs-extra";import Ti from"path";import gu from"html-to-docx";var Si,fl=ie(()=>{Qt();dn();Si=async e=>{let{path:o,content:t}=re(e);if(!o)return'ERROR: Missing "path" argument for write_docx.';if(!t)return'ERROR: Missing "content" (HTML) for write_docx.';let n=Ti.resolve(process.cwd(),o);try{await ml.ensureDir(Ti.dirname(n)),await Ct.recordFileChange(n);let s=Ti.basename(o),r=t.includes("<html")?t:`
|
|
358
358
|
<!DOCTYPE html>
|
|
359
359
|
<html lang="en">
|
|
360
360
|
<head>
|
|
@@ -365,35 +365,35 @@ ${m}${c}`;return s.length=0,u.length=0,f.length=0,a}catch(n){return`ERROR: Faile
|
|
|
365
365
|
${t}
|
|
366
366
|
</body>
|
|
367
367
|
</html>
|
|
368
|
-
`,
|
|
369
|
-
- Size: ${(
|
|
368
|
+
`,a=await gu(r,null,{title:`FluxFlow_${s}`,creator:"FluxFlow CLI",description:"Generated by Agentic AI System",table:{row:{cantSplit:!0}},footer:!0,pageNumber:!0});return await ml.writeFile(n,a),`SUCCESS: Word document [${o}] generated successfully.
|
|
369
|
+
- Size: ${(a.length/1024).toFixed(1)} KB`}catch(s){return`ERROR: Failed to generate DOCX [${o}]: ${s.message}`}}});import Ei from"fs/promises";import Pr from"path";async function pl(e,o,t=e,n=1){if(n>12)return[];let s=[],r;try{r=await Ei.readdir(e,{withFileTypes:!0})}catch{return[]}for(let a of r){let u=Pr.join(e,a.name),f=Pr.relative(t,u),m=f.split(Pr.sep).map(l=>l.toLowerCase());if(!o.some(l=>m.includes(l.toLowerCase())))if(a.isDirectory()){let l=await pl(u,o,t,n+1);s=s.concat(l)}else a.isFile()&&s.push({fullPath:u,relativePath:f})}return s}var bi,hl=ie(()=>{Qt();bi=async e=>{let{keyword:o,file:t}=re(e);if(!o)return'ERROR: Missing "keyword" argument.';let n=["node_modules",".git","dist",".next",".gemini",".exe",".dll",".png",".jpg",".jpeg",".gif",".zip",".tgz"],s=150;try{let r=[],a=process.cwd();if(t){let l=Pr.resolve(a,t);try{(await Ei.stat(l)).isFile()&&r.push({fullPath:l,relativePath:Pr.relative(a,l)})}catch{return`ERROR: File not found: ${t}`}}else r=await pl(a,n);let u=r.map(async l=>{try{let d=await Ei.readFile(l.fullPath,"utf-8");if(d.includes("\0"))return[];let p=d.split(/\r?\n/),h=[];for(let S=0;S<p.length;S++)if(p[S].includes(o)){let w=l.relativePath.replace(/\\/g,"/");h.push(`${w} \u2192 ${S+1}`)}return h}catch{return[]}}),m=(await Promise.all(u)).flat().slice(0,s);if(typeof global.gc=="function"&&global.gc(),m.length===0)return`Found 0 matches for keyword: "${o}"${t?` in file: ${t}`:". Try to specify files"}`;let c=`Found ${m.length} matches:
|
|
370
370
|
|
|
371
371
|
`;return c+=m.join(`
|
|
372
|
-
`),c}catch(r){return`ERROR: ${r.message}`}}});import
|
|
373
|
-
`)[0].trim();if(e.type==="function_definition"||e.type==="function_declaration"){let t=e.childForFieldName("declarator");if(t){let n=t.descendantsOfType("identifier")[0]||t.descendantsOfType("field_identifier")[0];if(n)return n.text}}let o=e.childForFieldName("name")||e.children.find(t=>t.type==="identifier"||t.type==="variable_declarator"||t.type==="type_identifier"||t.type==="field_identifier");if(o){if(o.type==="variable_declarator"){let t=o.childForFieldName("name")||o.children.find(n=>n.type==="identifier");return t?t.text:null}return o.text}if(e.type==="lexical_declaration"||e.type==="variable_declaration"){let t=e.children.find(n=>n.type==="variable_declarator");if(t)return
|
|
374
|
-
`:(u+=`${n}${t?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 "}${h} (Lines: ${c}-${
|
|
375
|
-
`,f+=t?" ":"\u2502 ")}let m=
|
|
376
|
-
${
|
|
377
|
-
Stack: ${
|
|
378
|
-
`);
|
|
379
|
-
`);
|
|
380
|
-
`);
|
|
381
|
-
`),
|
|
372
|
+
`),c}catch(r){return`ERROR: ${r.message}`}}});import gl from"fs-extra";import Ci from"path";var xu,ki,xl=ie(()=>{Qt();ts();ps();dn();xu=(e,o={})=>{try{if(e.length<8||e[0]!==137||e[1]!==80||e[2]!==78||e[3]!==71)return e;let t=[],n=[];for(let a=0;a<256;a++){let u=a;for(let f=0;f<8;f++)u&1?u=3988292384^u>>>1:u=u>>>1;n[a]=u}let s=a=>{let u=4294967295;for(let f=0;f<a.length;f++)u=n[(u^a[f])&255]^u>>>8;return(u^4294967295)>>>0},r=(a,u)=>{let f=Buffer.from(a,"ascii"),m=Buffer.from(u,"utf-8"),c=f.length+1+m.length,l=Buffer.alloc(8+c+4);l.writeUInt32BE(c,0),l.write("tEXt",4,"ascii"),f.copy(l,8),l[8+f.length]=0,m.copy(l,8+f.length+1);let d=s(l.subarray(4,8+c));return l.writeUInt32BE(d,8+c),l};for(let[a,u]of Object.entries(o))u!=null&&t.push(r(a,String(u)));if(t.length===0)return e;if(e.subarray(12,16).toString("ascii")==="IHDR"){let u=e.subarray(0,33),f=e.subarray(33);return Buffer.concat([u,...t,f])}return e}catch{return e}},ki=async(e,o={})=>{let t=re(e),n=t.prompt||t.text,s=t.path||t.outputPath||t.output||"generated_image.png",r=t.ratio;if(!n)return'ERROR: Missing "prompt" argument for generate_image.';let a=["nsfw","naked","nudity","nude","porn","sex","xxx","erotic","gore","bloody","violence","abuse","suicide","murder","hentai","pedophile","rape"],u=n.toLowerCase();if(a.some(m=>u.includes(m)))return"ERROR: Prompt blocked by system safety filter (inappropriate or unsafe content detected).";try{let m=await rr();if(!await Ja(m))return`ERROR: Insufficient Quota for selected quality. Either tell user reduce quality or wait for next refresh cycle (${(await fs()).nextResetMin||60}m).`;let l=m.imageSettings||{keyType:"Default",quality:"Low-High",apiKey:""},d=l.keyType==="Custom"&&l.apiKey?l.apiKey:FALLBACK_IMAGE_KEY,h={Low:"flux","Low-High":"zimage",Medium:"gptimage","Medium-High":"gptimage",High:"qwen-image",Ultra:"gptimage-large",Premium:"nanobanana-pro"}[l.quality]||"zimage",S=1024,w=1024;if(r){let K=r.replace(/\s+/g,"");K==="16:9"?(S=1024,w=576):K==="9:16"?(S=576,w=1024):K==="4:3"?(S=1024,w=768):K==="3:4"?(S=768,w=1024):K==="1:1"&&(S=1024,w=1024)}let T=Math.floor(Math.random()*1e7),L=`https://gen.pollinations.ai/image/${encodeURIComponent(n)}?model=${h}&width=${S}&height=${w}&seed=${T}&enhance=true&reasoning=high&quality=high&negative=${encodeURIComponent("deformed, distorted, disfigured, poorly drawn, bad anatomy, wrong anatomy, extra limb, missing limb, floating limbs, disconnected limbs, mutation, mutated hands and fingers, blurry, low quality, low resolution, extra fingers, censored, watermarks, signatures")}`,P=await fetch(L,{method:"GET",headers:{Authorization:`Bearer ${d}`}});if(!P.ok){let K=P.status,Ue="";try{Ue=await P.text()}catch{}return K===402||Ue.includes("Insufficient balance")||Ue.includes("PAYMENT_REQUIRED")?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed with status [${K}]: ${Ue||"Unknown API Error"}`}if((P.headers.get("content-type")||"").includes("application/json")){let K=await P.json();return K.status===402||K.error&&K.error.code==="PAYMENT_REQUIRED"?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed: ${K.error?.message||JSON.stringify(K)}`}let v=await P.arrayBuffer(),D=Buffer.from(v),A={Title:n,Description:"Generated via FluxFlow CLI",Software:"FluxFlow CLI",Author:"FluxFlow","Creation Time":new Date().toISOString(),Prompt:n,Model:`Fluxflow:${h}`,Ratio:r||"1:1",Seed:String(T)};D=xu(D,A);let E=Ci.resolve(process.cwd(),s);await gl.ensureDir(Ci.dirname(E)),await Ct.recordFileChange(E),await gl.writeFile(E,D),await Qa(m);let q=Ci.extname(s).toLowerCase(),V={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".webp":"image/webp"}[q]||"image/png";return o.isMultiModal!==!1?{text:`SUCCESS: Image successfully generated from prompt [${n}] and saved to [${s}]. Output attached to multimodal part`,binaryPart:{inlineData:{data:D.toString("base64"),mimeType:V}}}:`SUCCESS: Image successfully generated from prompt [${n}] and saved to [${s}].`}catch(m){return`ERROR: Failed during image generation: ${m.message}`}}});var _r,yl=ie(()=>{Oo();Gt();_r=async(e,o={})=>{let t=r=>{let a=new RegExp(`${r}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),u=e.match(a);return u?u[2].trim():null},n=t("id"),s=t("summary");if(!n||!s)return"ERROR: Missing 'id' or 'summary' for saveSummary tool.";try{let r=ge(yo,{}),a=ge(Yo,{});return a[n]=s,delete r[n],$e(Yo,a),$e(yo,r),`SUCCESS: Saved summary and purged raw memories for chat [${n}].`}catch(r){return`ERROR: Failed to save summary for chat [${n}]: ${r.message}`}}});var ur,wl=ie(()=>{Oo();Gt();ur=async(e,o={})=>{let n=(s=>{let r=new RegExp(`${s}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),a=e.match(r);return a?a[2].trim():null})("id");if(!n)return"ERROR: Missing 'id' parameter for addMemScore tool.";try{let s=ge(Ht,[]),r=!1,a=[];for(let c of s)c.score===void 0&&(c.score=.5),c.id===n?(c.score=Math.min(2,c.score+.2),r=!0):(c.score*=.98,c.score<.05&&(c.score=0)),c.score=Math.round(c.score*1e5)/1e5,c.score>0&&a.push(c);if($e(Ht,a),!r)return`WARNING: Memory ID [${n}] not found. Other memories decayed by -0.01.`;let u=a.find(c=>c.id===n),f=u?u.score.toFixed(2):"deleted (score <= 0)",m=s.length-a.length;return`SUCCESS: Adjusted memory scores. Target [${n}] is now ${f}.${m>0?` Purged ${m} decayed memories.`:""}`}catch(s){return`ERROR: Failed to adjust memory score for [${n}]: ${s.message}`}}});import Kn from"fs-extra";import Ii from"path";import yu from"https";async function Mi(e,o=null){let t=o||`https://unpkg.com/tree-sitter-wasms@0.1.13/out/${e}`,n=Ii.join(yn,e);return await Kn.ensureDir(yn),new Promise((s,r)=>{let a={headers:{"User-Agent":"FluxFlow-Agent"}};yu.get(t,a,u=>{if([301,302,307,308].includes(u.statusCode)&&u.headers.location){let m=u.headers.location;if(!m.startsWith("http")){let c=new URL(t);m=`${c.protocol}//${c.host}${m}`}Mi(e,m).then(s).catch(r);return}if(u.statusCode!==200){r(new Error(`Failed to download ${e}: HTTP ${u.statusCode}`));return}let f=Kn.createWriteStream(n);u.pipe(f),f.on("finish",()=>{f.close(),s()})}).on("error",u=>{Kn.existsSync(n)&&Kn.unlink(n,()=>{}),r(u)})})}function Sl(e){let o=Ii.join(yn,e);return Kn.existsSync(o)}async function El(e){let o=Ii.join(yn,e);Kn.existsSync(o)&&await Kn.unlink(o)}var Tl,Ai=ie(()=>{Gt();Tl={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 vi from"fs-extra";import Vn from"path";import{createRequire as wu}from"module";function Ml(e){if(e.type==="element"||e.type==="script_element"||e.type==="style_element"){let t=e.childForFieldName("start_tag")||e.children.find(s=>s.type==="start_tag");if(t){let s=t.childForFieldName("name")||t.children.find(r=>r.type==="tag_name");return s?s.text:null}let n=e.children.find(s=>s.type==="tag_name");return n?n.text:null}if(e.type==="jsx_element"||e.type==="jsx_self_closing_element"){let n=(e.childForFieldName("opening_element")||e).childForFieldName("name");return n?n.text:null}if(e.type==="import_declaration"||e.type==="import_from_statement"||e.type==="import_statement"||e.type==="preproc_include")return e.text.split(`
|
|
373
|
+
`)[0].trim();if(e.type==="function_definition"||e.type==="function_declaration"){let t=e.childForFieldName("declarator");if(t){let n=t.descendantsOfType("identifier")[0]||t.descendantsOfType("field_identifier")[0];if(n)return n.text}}let o=e.childForFieldName("name")||e.children.find(t=>t.type==="identifier"||t.type==="variable_declarator"||t.type==="type_identifier"||t.type==="field_identifier");if(o){if(o.type==="variable_declarator"){let t=o.childForFieldName("name")||o.children.find(n=>n.type==="identifier");return t?t.text:null}return o.text}if(e.type==="lexical_declaration"||e.type==="variable_declaration"){let t=e.children.find(n=>n.type==="variable_declarator");if(t)return Ml(t)}if(e.type==="method_definition"||e.type==="function_declaration"){let t=e.childForFieldName("name")||e.children.find(n=>n.type==="identifier");if(t)return t.text}return null}function Tu(e){let o=[];function t(n){for(let s of n.children)Il.has(s.type)?o.push(s):t(s)}return t(e),o}function Su(e){return e.replace(/_([a-z])/g,o=>o[1].toUpperCase())}function Al(e,o=0,t=!0,n=""){if(o>6)return"";let r=e.type,a=Il.has(r)||o===0,u="",f=n;if(a){let c=e.startPosition.row+1,l=e.endPosition.row+1,d=Ml(e),p=Su(r),h=d?`${p} [${d}]`:p;o===0?u+=`\u{1F4C1} ROOT (Lines: ${c}-${l})
|
|
374
|
+
`:(u+=`${n}${t?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 "}${h} (Lines: ${c}-${l})
|
|
375
|
+
`,f+=t?" ":"\u2502 ")}let m=Tu(e);return m.forEach((c,l)=>{let d=l===m.length-1;u+=Al(c,o+1,d,a?f:n)}),u}var kl,bl,Cl,Il,Di,vl=ie(()=>{Ai();Gt();Qt();kl=wu(import.meta.url),bl=kl("web-tree-sitter"),Cl=!1,Il=new Set(["class_declaration","function_declaration","method_definition","arrow_function","if_statement","for_statement","while_statement","do_statement","switch_statement","try_statement","variable_declaration","lexical_declaration","export_statement","interface_declaration","type_alias_declaration","enum_declaration","import_declaration","jsx_element","jsx_self_closing_element","class_definition","function_definition","decorated_definition","import_from_statement","import_statement","preproc_include","method_declaration","constructor_declaration","class_specifier","struct_specifier","enum_specifier","field_declaration","element","script_element","style_element"]);Di=async e=>{let o;try{o=re(e).path}catch{return`ERROR: Failed to parse arguments: ${e}`}if(!o)return'ERROR: No file path provided. Use [tool:functions.FileMap(path="...")]';let t=Vn.isAbsolute(o)?o:Vn.resolve(process.cwd(),o);if(!vi.existsSync(t))return`ERROR: File not found: ${o}`;let n=Vn.extname(t).slice(1).toLowerCase(),s=Tl[n];if(!s)return`ERROR: Unsupported file extension: .${n}`;let r=Vn.resolve(yn,s);if(!vi.existsSync(r))return`ERROR: Parser for .${n} not found. Please download it in Settings > Other.`;try{let a=bl.Parser;if(!Cl){let d;try{d=Vn.join(Vn.dirname(kl.resolve("web-tree-sitter")),"tree-sitter.wasm")}catch{d=Vn.join(process.cwd(),"node_modules","web-tree-sitter","tree-sitter.wasm")}await a.init({locateFile:p=>p==="tree-sitter.wasm"||p.endsWith("tree-sitter.wasm")?d:p}),Cl=!0}let u=new a,f=await bl.Language.load(r);u.setLanguage(f);let m=await vi.readFile(t,"utf8"),c=u.parse(m),l=Al(c.rootNode);return`\u{1F4C4} File Map for: ${o}
|
|
376
|
+
${l}`}catch(a){let u=a instanceof Error?a.message:typeof a=="object"?JSON.stringify(a):String(a),f=a instanceof Error?`
|
|
377
|
+
Stack: ${a.stack}`:"";return`ERROR: Failed to map file: ${u}${f}`}}});var Eu,xs,Dl=ie(async()=>{Za();el();tl();ol();rl();il();al();await Or();cl();ul();dl();fl();hl();xl();yl();wl();vl();Eu={web_search:ci,web_scrape:ui,memory:di,chat:mi,view_file:fi,write_file:pi,update_file:gi,exec_command:Xs,read_folder:xi,write_pdf:wi,write_docx:Si,search_keyword:bi,generate_image:ki,saveSummary:_r,addMemScore:ur,file_map:Di,ask:yi,Ask:yi,WebSearch:ci,WebScrape:ui,ReadFile:fi,ReadFolder:xi,WriteFile:pi,PatchFile:gi,WritePDF:wi,WriteDoc:Si,Run:Xs,SearchKeyword:bi,Memory:di,Chat:mi,GenerateImage:ki,saveSumary:_r,SaveSummary:_r,SaveSumary:_r,add_mem_score:ur,AddMemScore:ur,addMemoryScore:ur,AddMemoryScore:ur,FileMap:Di},xs=async(e,o,t={})=>{if(t.mode&&t.mode.toLowerCase()==="flow"){let s=e.toLowerCase();if(!(s.startsWith("web")||s.startsWith("ask")))return`ERROR: Tool [${e}] is restricted in Flow mode.`}let n=Eu[e];if(!n)return`ERROR: Tool [${e}] not found in registry.`;try{return await n(o,t)}catch(s){return`ERROR: Execution failed for [${e}]: ${s.message}`}}});import{WebSocket as ys}from"ws";var po,dr,bu,Oi,mr,Li,Ol,Fi,$i,Ll,ws,Ko,Ts,Nr,Fl,Pi,$l,_i=ie(()=>{po=null,dr=!1,bu="ws://localhost:56832",Oi=[],mr=null,Li=null,Ol="2.0.0",Fi=e=>{Ol=e,Ll()},$i=e=>{Li=e},Ll=()=>{if(po||dr)return;dr=!0;let e=new ys(bu);e.on("open",()=>{for(po=e,dr=!1,po.send(JSON.stringify({command:"version",version:Ol,pid:process.pid,ppid:process.ppid}));Oi.length>0;)po.send(JSON.stringify(Oi.shift()))}),e.on("message",o=>{try{let t=JSON.parse(o.toString());t.command==="contextResponse"&&mr?(mr(t.data),mr=null):t.command==="securityResponse"&&Li&&Li(t.result)}catch{}}),e.on("error",()=>{dr=!1,po=null}),e.on("close",()=>{dr=!1,po=null})},ws=e=>{po&&po.readyState===ys.OPEN?po.send(JSON.stringify(e)):(Oi.push(e),dr||Ll())},Ko=()=>po!==null&&po.readyState===ys.OPEN,Ts=e=>{ws({command:"status",status:e})},Nr=()=>new Promise(e=>{if(!po||po.readyState!==ys.OPEN){e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]});return}mr=e,po.send(JSON.stringify({command:"requestContext"})),setTimeout(()=>{mr===e&&(e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]}),mr=null)},1e3)}),Fl=e=>{ws({command:"open",filePath:e})},Pi=(e,o,t)=>{ws({command:"showDiff",filePath:e,originalContent:o,modifiedContent:t})},$l=(e,o)=>{ws({command:"closeDiff",filePath:e,result:o})}});import{GoogleGenAI as Cu,ThinkingLevel as _o,HarmBlockThreshold as Mn,HarmCategory as An}from"@google/genai";import Ie from"path";import ct from"fs";var fr,Bi,Vo,ku,Ni,Iu,Ri,Wi,Yi,ji,Nl,Pl,Mu,Bl,Au,Ul,vu,_l,Hi,Br,Ui,Du,Gi,Rl,Wl,Yl=ie(async()=>{await Ra();$r();ps();await Dl();Oo();Qt();sn();jn();Gt();dn();_i();fr=null,Bi={},Vo=!1,ku=["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"],Ni=e=>{if(!e)return!1;let o=e.toLowerCase();return o.startsWith("gemini-")||o.startsWith("gemma-")?!0:ku.some(t=>t.toLowerCase()===o)},Iu=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),Ri=async(e,o,t=5,n=1e3)=>{let s=o?.signal;for(let r=0;r<t;r++){if(s?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{let a=await fetch(e,o);if(a.ok||a.status!==429&&a.status<500)return a}catch(a){if(a.name==="AbortError"||s?.aborted||r===t-1)throw a}s?await new Promise((a,u)=>{let f=setTimeout(()=>{s.removeEventListener("abort",m),a()},Math.min(24e3,n*Math.pow(2,r))),m=()=>{clearTimeout(f),u(new DOMException("The user aborted a request.","AbortError"))};s.addEventListener("abort",m)}):await new Promise(a=>setTimeout(a,Math.min(24e3,n*Math.pow(2,r))))}if(s?.aborted)throw new DOMException("The user aborted a request.","AbortError");return fetch(e,o)},Wi=async function*(e,o,t,n,s,r,a,u){let f=[];n&&f.push({role:"system",content:n});for(let b of t){let L=b.role==="user"?"user":"assistant",P=[];if(Array.isArray(b.parts)){for(let Y of b.parts)if(Y.text)P.push({type:"text",text:Y.text});else if(Y.inlineData&&a){let v=Y.inlineData.mimeType,D=Y.inlineData.data;v.startsWith("image/")&&P.push({type:"image_url",image_url:{url:`data:${v};base64,${D}`}})}}else{let Y=b.text||"";Y&&P.push({type:"text",text:Y})}f.push({role:L,content:P.length===1&&P[0].type==="text"?P[0].text:P})}let m={model:o,messages:f,stream:!0,stream_options:{include_usage:!0},temperature:r==="Flux"?1:1.4};if(s!=="Fast"){let b={Low:"high",Medium:"high",Standard:"high",High:"max",xHigh:"max"};m.reasoning_effort=b[s]||"high",m.extra_body={thinking:{type:"enabled"}}}else m.extra_body={thinking:{type:"disabled"}};let c=await Ri("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 b=await c.json().catch(()=>({}));throw new Error(`DeepSeek Error (${c.status}): ${b.error?.message||c.statusText}`)}let l=c.body.getReader(),d=new TextDecoder,p="",h=[],S=null,w=Date.now(),T=!1;for(;;){let{done:b,value:L}=await l.read();if(b){T&&(h.length>0||S)&&(yield{candidates:h.length>0?[{content:{parts:h}}]:[],usageMetadata:S});break}p+=d.decode(L,{stream:!0});let P=p.split(`
|
|
378
|
+
`);p=P.pop();for(let Y of P){let v=Y.trim();if(!(!v||!v.startsWith("data: "))){if(v==="data: [DONE]")break;try{let D=JSON.parse(v.substring(6)),A=D.choices?.[0]?.delta,E=D.usage;if(E&&(S={totalTokenCount:E.total_tokens||E.prompt_tokens+E.completion_tokens,promptTokenCount:E.prompt_tokens||0,candidatesTokenCount:E.completion_tokens||0,cachedContentTokenCount:E.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:E.completion_tokens_details?.reasoning_tokens||0},T=!0),A){let q=A.reasoning_content||null;q&&(h.push({text:q,thought:!0}),T=!0),A.content&&(h.push({text:A.content}),T=!0)}}catch{}}}Date.now()-w>=150&&T&&(yield{candidates:h.length>0?[{content:{parts:[...h]}}]:[],usageMetadata:S},h=[],w=Date.now(),T=!1)}},Yi=async function*(e,o,t,n,s,r,a=!1,u){let f=[];n&&f.push({role:"system",content:n}),t.forEach(V=>{let _=V.role==="model"?"assistant":"user",K=[];Array.isArray(V.parts)&&V.parts.forEach(Ue=>{if(Ue.text)K.push({type:"text",text:Ue.text});else if(Ue.inlineData&&a){let se=Ue.inlineData.mimeType,Te=Ue.inlineData.data;se.startsWith("image/")&&K.push({type:"image_url",image_url:{url:`data:${se};base64,${Te}`}})}}),f.push({role:_,content:K.length===1&&K[0].type==="text"?K[0].text:K})});let c={Fast:"Fast",Low:"Fast",Medium:"Standard",Standard:"Standard",High:"High",xHigh:"High"}[s]||"Standard",l=c!=="Fast",d=o.includes("kimi"),p=o.includes("gemma"),h=o.includes("deepseek"),S=o.includes("glm"),w=o.includes("mistral"),b=o.includes("minimax")||h?16384:32768,L={model:o,messages:f,temperature:r==="Flux"?.7:1,max_tokens:b,stream:!0,stream_options:{include_usage:!0}};if(d)L.chat_template_kwargs={thinking:l};else if(p)L.chat_template_kwargs={enable_thinking:l};else if(h)if(l){let V=c==="High"?"max":"high";L.chat_template_kwargs={thinking:!0,reasoning_effort:V}}else L.chat_template_kwargs={thinking:!1};else S?L.chat_template_kwargs={enable_thinking:l,clear_thinking:!l}:w&&(L.reasoning_effort=l?"high":"none");let P=await Ri("https://integrate.api.nvidia.com/v1/chat/completions",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(L),signal:u});if(!P.ok){let V=await P.json(),_=new Error(`NVIDIA API Error: ${V.error?.message||P.statusText}`);throw _.status=P.status,_}let Y=P.body.getReader(),v=new TextDecoder,D="",A=[],E=null,q=Date.now(),B=!1;for(;;){let{done:V,value:_}=await Y.read();if(V){B&&(A.length>0||E)&&(yield{candidates:A.length>0?[{content:{parts:A}}]:[],usageMetadata:E});break}D+=v.decode(_,{stream:!0});let K=D.split(`
|
|
379
|
+
`);D=K.pop();for(let Ue of K){let se=Ue.trim();if(!(!se||se==="data: [DONE]")&&se.startsWith("data: "))try{let Te=JSON.parse(se.substring(6)),De=Te.usage;De&&(E={totalTokenCount:De.total_tokens||De.prompt_tokens+De.completion_tokens,promptTokenCount:De.prompt_tokens||0,candidatesTokenCount:De.completion_tokens||0,thoughtsTokenCount:(De.completion_tokens_details?.reasoning_tokens||0)+(De.completion_tokens_details?.thoughts_tokens||0)},B=!0);let me=Te.choices?.[0]?.delta?.reasoning||Te.choices?.[0]?.delta?.reasoning_content||"",et=Te.choices?.[0]?.delta?.content||"";me&&(A.push({text:me,thought:!0}),B=!0),et&&(A.push({text:et}),B=!0)}catch{}}Date.now()-q>=350&&B&&(yield{candidates:A.length>0?[{content:{parts:[...A]}}]:[],usageMetadata:E},A=[],q=Date.now(),B=!1)}},ji=async function*(e,o,t,n,s,r,a,u){let f=[];n&&f.push({role:"system",content:n});for(let P of t){let Y=P.role==="user"?"user":"assistant",v=[];if(Array.isArray(P.parts)){for(let D of P.parts)if(D.text)v.push({type:"text",text:D.text});else if(D.inlineData&&a){let A=D.inlineData.mimeType,E=D.inlineData.data;A.startsWith("image/")?v.push({type:"image_url",image_url:{url:`data:${A};base64,${E}`}}):v.push({type:"file",file:{filename:D.filename||"file",file_data:`data:${A};base64,${E}`}})}}else{let D=P.text||"";D&&v.push({type:"text",text:D})}f.push({role:Y,content:v.length===1&&v[0].type==="text"?v[0].text:v})}let m={Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},c={model:o,messages:f,stream:!0,temperature:r==="Flux"?1:1.4},l=m[s];l&&s!=="Fast"&&(c.reasoning_effort=l);let d=await Ri("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 P=await d.json().catch(()=>({}));throw new Error(`OpenRouter Error (${d.status}): ${P.error?.message||d.statusText}`)}let p=d.body.getReader(),h=new TextDecoder,S="",w=[],T=null,b=Date.now(),L=!1;for(;;){let{done:P,value:Y}=await p.read();if(P){L&&(w.length>0||T)&&(yield{candidates:w.length>0?[{content:{parts:w}}]:[],usageMetadata:T});break}S+=h.decode(Y,{stream:!0});let v=S.split(`
|
|
380
|
+
`);S=v.pop();for(let D of v){let A=D.trim();if(!(!A||!A.startsWith("data: "))){if(A==="data: [DONE]")break;try{let E=JSON.parse(A.substring(6)),q=E.choices?.[0]?.delta,B=E.usage;if(B&&(T={totalTokenCount:B.total_tokens||B.prompt_tokens+B.completion_tokens,promptTokenCount:B.prompt_tokens||0,candidatesTokenCount:B.completion_tokens||0,cachedContentTokenCount:B.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:B.completion_tokens_details?.reasoning_tokens||0},L=!0),q){let V=q.reasoning||(q.reasoning_details?q.reasoning_details.map(_=>_.text).join(""):null);V&&(w.push({text:V,thought:!0}),L=!0),q.content&&(w.push({text:q.content}),L=!0)}}catch{}}}Date.now()-b>=150&&L&&(yield{candidates:w.length>0?[{content:{parts:[...w]}}]:[],usageMetadata:T},w=[],b=Date.now(),L=!1)}},Nl=()=>{Vo=!0},Pl={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"},Mu=(e,o)=>{try{let t=re(o),n=t.path||t.targetFile||t.TargetFile||t.directory;return n?Ie.basename(n.replace(/["']/g,"").replace(/\\/g,"/")):null}catch{return null}},Bl=async(e,o,t,n,s={})=>{process.stdout.isTTY&&(process.stdout.write("\x1B]0;Finalizing...\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=Finalizing...\x07"));let r=4*(1024*2),a=4*(1024*8),{onStatus:u,onMemoryUpdated:f,onBackgroundIncrement:m}=s,{profile:c,thinkingLevel:l,mode:d,janitorModel:p,chatId:h,systemSettings:S,sessionStats:w,aiProvider:T="Google",apiKey:b}=e,L=S?.memory!==!1,Y=ge(Ht,[]).map(me=>`- [${me.id}]: ${me.memory}`).join(`
|
|
381
|
+
`),v=n.slice(0,-1).filter(me=>me.text&&!me.text.includes("[TOOL RESULT]")&&!me.text.includes("OBSERVATION:")&&!me.text.startsWith("[TERMINAL_RECORD]")&&!me.isTerminalRecord&&!me.isMeta&&!me.isLogo&&!String(me.id).startsWith("welcome")&&!String(me.id).startsWith("logo")).slice(-14).map(me=>{let et=Iu(me.text).replace(/\[tool:functions\..*?\]/g,"").replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[METADATA \(PRIORITY: DYNAMIC\)\] Time: ([^|\n]+)/g,(kt,Ne)=>`[METADATA (PRIORITY: DYNAMIC)] Time: ${Ne.replace(/:\d{2}/g,"")}`).replace(/\[turn: continue\]/g,"").replace(/\[turn: finish\]/g,"").replace(/\[\[END\]\]/g,"").replace(/\[TOOL RESULTS\]/g,"").replace(/\[tool results\]/g,"").replace(/\r?\n\r?\n/g,`
|
|
382
382
|
`).replace(/\n\n/g,`
|
|
383
|
-
`).replace(/\\n\\n/g,"").trim(),
|
|
384
|
-
... (truncated) ...`);let
|
|
385
|
-
... (truncated) ...`);let
|
|
383
|
+
`).replace(/\\n\\n/g,"").trim(),Ye=me.role==="user"?r:a,je=et.substring(0,Ye);et.length>Ye&&(je+=`
|
|
384
|
+
... (truncated) ...`);let Oe=me.role==="user"?je.startsWith("[USER]")?"":"[USER]: ":je.startsWith("[AGENT]")?"":"[AGENT]: ";return{role:me.role==="user"?"user":"model",parts:[{text:`${Oe}${je}`}]}}),D=n.filter(me=>me.role==="user").length===1,A=o.includes("[TITLE-UPDATE]"),E=Math.random()<.8,q=D||A||E,B=t.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").trim(),V=Ua(Y,L,q),_=`${B.replace(/\[tool:functions\..*?\]/g,"").replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[turn: continue\]/g,"").replace(/\[turn: finish\]/g,"").replace(/\[\[END\]\]/g,"").replace(/\[TOOL RESULTS\]/g,"").replace(/\[tool results\]/g,"").substring(0,a)}`;_.length>a&&(_+=`
|
|
385
|
+
... (truncated) ...`);let K=o.replace(/\[Prompted on:.*?\]/g,"").trim();_=_.replace(/\r?\n\r?\n/g,`
|
|
386
386
|
`).replace(/\n\n/g,`
|
|
387
|
-
`).replace(/\\n\\n/g,"").trim();let
|
|
388
|
-
${
|
|
387
|
+
`).replace(/\\n\\n/g,"").trim();let Ue=`[USER]: ${K.substring(0,r)}
|
|
388
|
+
${K.length>r?`... (truncated) ...
|
|
389
389
|
|
|
390
390
|
`:""}
|
|
391
|
-
[AGENT (current turn)]: ${
|
|
391
|
+
[AGENT (current turn)]: ${_}`;v.push({role:"user",parts:[{text:Ue}]});let se="",Te=0,De=L?12:-1;for(;Te<=De;){process.stdout.isTTY&&(process.stdout.write(`\x1B]0;Retrying Finalizing... (${Te+1})...\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=Retrying Finalizing... (${Te+1})...\x07`));try{if(!await ai("background",e))return;let me="",et=null;try{let Oe=new Promise((Nt,Ge)=>setTimeout(()=>Ge(new Error("JANITOR_TIMEOUT")),6e4)),kt=(async()=>{if(T==="OpenRouter"){let ze=ji(b,"google/gemma-4-26b-a4b-it:free",v,V,"Fast",d)[Symbol.asyncIterator](),yt=await ze.next();return{iterator:ze,firstResult:yt}}else if(T==="DeepSeek"){let Ge=Wi(b,"deepseek-chat",v,V,"Fast",d,!1)[Symbol.asyncIterator](),ze=await Ge.next();return{iterator:Ge,firstResult:ze}}else if(T==="NVIDIA"){let Ge=Yi(b,"z-ai/glm-5.1",v,V,"Fast",d,!1)[Symbol.asyncIterator](),ze=await Ge.next();return{iterator:Ge,firstResult:ze}}else{let Ge=(await fr.models.generateContentStream({model:p||"gemma-4-26b-a4b-it",contents:v,config:{systemInstruction:V,maxOutputTokens:512,temperature:.3,safetySettings:[{category:An.HARM_CATEGORY_HARASSMENT,threshold:Mn.BLOCK_NONE},{category:An.HARM_CATEGORY_HATE_SPEECH,threshold:Mn.BLOCK_NONE},{category:An.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Mn.BLOCK_NONE},{category:An.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Mn.BLOCK_NONE}],thinkingConfig:{includeThoughts:!1,thinkingLevel:_o.MINIMAL}}}))[Symbol.asyncIterator](),ze=await Ge.next();return{iterator:Ge,firstResult:ze}}})(),{iterator:Ne,firstResult:He}=await Promise.race([kt,Oe]),{value:We,done:Vt}=He;if(!Vt&&We){let Nt=We.candidates?.[0]?.content?.parts,Ge=Nt?.[1]?.text||Nt?.[0]?.text||(typeof We.text=="function"?We.text():"");Ge&&(me+=Ge),et=We.usageMetadata;for await(let ze of{[Symbol.asyncIterator]:()=>Ne}){let yt=ze.candidates?.[0]?.content?.parts,co=yt?.[1]?.text||yt?.[0]?.text||(typeof ze.text=="function"?ze.text():"");co&&(me+=co),et=ze.usageMetadata}}}catch(Oe){throw Oe}if(me)se=me,et&&await To("tokens",et.totalTokenCount||0);else throw new Error("No synthesis generated by Janitor.");m&&(m(),await Xo("background"));let Ye=Hi(se),je=!1;for(let Oe of Ye){let kt=Oe.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(kt)&&(je=!0);let Ne={chatId:h,sessionId:h,history:n},He=await xs(kt,Oe.args,Ne);kt.toLowerCase()==="memory"&&(Oe.args.includes("action='user'")||Oe.args.includes('action="user"'))&&!He.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(Vt=>setTimeout(Vt,3e3)))}if(!je)try{let Oe=ge(Ht,[]);if(Oe.length>0){let kt=[];for(let Ne of Oe)Ne.score===void 0&&(Ne.score=.5),Ne.score*=.9995,Ne.score<.05&&(Ne.score=0),Ne.score=Math.round(Ne.score*1e5)/1e5,Ne.score>0&&kt.push(Ne);$e(Ht,kt)}}catch{}break}catch(me){Te++;let et=new Date().toLocaleString();process.stdout.isTTY&&process.stdout.write("\x1B]0;Finalizing Error\x07"),await new Promise(Oe=>setTimeout(Oe,1e3));let Ye=Ie.join(Mo,"janitor");if(ct.existsSync(Ye)||ct.mkdirSync(Ye,{recursive:!0}),ct.appendFileSync(Ie.join(Ye,"error.log"),`ERROR [Attempt ${Te}/${De+1}] [${et}]: ${String(me)}
|
|
392
392
|
|
|
393
|
-
`)
|
|
393
|
+
`),Te>De)break;let je=Math.min(1e3*Math.pow(2,Te-1),8e3);await new Promise(Oe=>setTimeout(Oe,je))}}if(Te){let me=Ie.join(Mo,"janitor");ct.appendFileSync(Ie.join(me,"error.log"),`-----------------------------------------------------------------------------
|
|
394
394
|
|
|
395
395
|
|
|
396
|
-
`)
|
|
396
|
+
`),Te>=De&&(process.stdout.isTTY&&process.stdout.write(`\x1B]0;${L?"Finalizing Error":"Finalizing Skipped"}\x07`),await new Promise(et=>setTimeout(et,3e3)))}process.stdout.isTTY&&(process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07"))},Au=e=>{let o=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,t;for(;(t=o.exec(e))!==null;){let n=t.index+t[0].length-1,s=0,r=null,a=!1,u=!1;for(let f=n;f<e.length;f++){let m=e[f];if(!r&&(m==='"'||m==="'"||m==="`")?(r=m,a=!1):r&&m===r&&!a&&(r=null),!r&&(m==="("?s++:m===")"&&s--,s===0)){let c=f+1;for(;c<e.length&&/\s/.test(e[c]);)c++;if(c<e.length&&e[c]==="]"){u=!0,o.lastIndex=c+1;break}}m==="\\"?a=!a:a=!1}if(!u)return{inside:!0,toolName:t[1],startIndex:t.index,args:e.substring(t.index+t[0].length)}}return{inside:!1}},Ul=(e,o=!0)=>{let t=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,n="",s=0,r;for(;(r=t.exec(e))!==null;){let a=e.substring(s,r.index);n+=o?a.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\]|$)/gi,""):a;let u=r.index+r[0].length-1,f=0,m=null,c=-1;for(let l=u;l<e.length;l++){let d=e[l];if(m){if(d===m){let p=0;for(let h=l-1;h>=0&&e[h]==="\\";h--)p++;p%2===0&&(m=null)}}else if(d==='"'||d==="'"||d==="`")m=d;else if(d==="(")f++;else if(d===")"&&(f--,f===0)){let p=l+1;for(;p<e.length&&/\s/.test(e[p]);)p++;if(p<e.length&&e[p]==="]"){c=p;break}}}if(c!==-1)n+="[tool:functions."+r[1]+"()]",s=c+1,t.lastIndex=s;else{n+="[tool:functions."+r[1]+"(",s=e.length;break}}return s<e.length&&(n+=o?e.substring(s).replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\]|$)/gi,""):e.substring(s)),n},vu=(e,o,t)=>{let n=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,s="",r=0,a;for(;(a=n.exec(e))!==null;){let u=e.substring(r,a.index);s+=u.replace(o,t);let f=a.index+a[0].length-1,m=0,c=null,l=-1;for(let d=f;d<e.length;d++){let p=e[d];if(c){if(p===c){let h=0;for(let S=d-1;S>=0&&e[S]==="\\";S--)h++;h%2===0&&(c=null)}}else if(p==='"'||p==="'"||p==="`")c=p;else if(p==="(")m++;else if(p===")"&&(m--,m===0)){let h=d+1;for(;h<e.length&&/\s/.test(e[h]);)h++;if(h<e.length&&e[h]==="]"){l=h;break}}}if(l!==-1)s+=e.substring(a.index,l+1),r=l+1,n.lastIndex=r;else{s+=e.substring(a.index),r=e.length;break}}return r<e.length&&(s+=e.substring(r).replace(o,t)),s},_l=e=>Ul(e,!0),Hi=e=>{if(!e)return[];let o=e.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/gi,""),t=[],n=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,s;for(;(s=n.exec(o))!==null;){let r=s[1],a=s.index+s[0].length-1,u=0,f=null,m=-1,c=-1;for(let l=a;l<o.length;l++){let d=o[l];if(f){if(d===f){let p=0;for(let h=l-1;h>=0&&o[h]==="\\";h--)p++;p%2===0&&(f=null)}}else if(d==='"'||d==="'"||d==="`")f=d;else if(d==="(")u++;else if(d===")"&&(u--,u===0)){c=l;let p=l+1;for(;p<o.length&&/\s/.test(o[p]);)p++;if(p<o.length&&o[p]==="]"){m=p;break}}}if(m!==-1){let l=o.substring(a+1,c),d=o.substring(s.index,m+1);t.push({fullMatch:d,toolName:r.trim(),args:l.trim()}),n.lastIndex=m+1}}return t},Br=(e,o={})=>e?(Bi=o,fr=new Cu({apiKey:e}),fr):null,Ui=async(e,o,t,n,s="Fast")=>{let{aiProvider:r="Google",apiKey:a,mode:u}=e,f="",m=null,c=typeof t=="string"?[{role:"user",parts:[{text:t}]}]:t,l;r==="OpenRouter"?l=ji(a,o,c,n,s,u,!1):r==="DeepSeek"?l=Wi(a,o,c,n,s,u,!1):r==="NVIDIA"?l=Yi(a,o,c,n,s,u,!1):l=await fr.models.generateContentStream({model:o,contents:c,config:{systemInstruction:n,maxOutputTokens:2048,temperature:.3,thinkingConfig:{includeThoughts:!1,thinkingLevel:_o.MINIMAL}}});for await(let d of l){if(d.candidates?.[0]?.content?.parts)for(let p of d.candidates[0].content.parts)p.text&&!p.thought&&(f+=p.text);d.usageMetadata&&(m=d.usageMetadata)}return{text:f,usageMetadata:m}},Du=async(e,o)=>{try{let{aiProvider:t="Google"}=o,n=ge(yo,{});if(Object.values(n).flat().length<=2)return;let r=Object.keys(n).filter(d=>d!==e&&Array.isArray(n[d])&&n[d].length>2);if(r.length===0)return;let a=`You are a silent background process for the FluxFlow CLI Agent.
|
|
397
397
|
Your task is to summarize or merge temporary context memories from one or more past conversation sessions.
|
|
398
398
|
For each Chat ID provided, you must output a tool call to save the consolidated summary.
|
|
399
399
|
|
|
@@ -408,158 +408,167 @@ Guidelines:
|
|
|
408
408
|
|
|
409
409
|
Chats to process:
|
|
410
410
|
|
|
411
|
-
`,u=
|
|
412
|
-
`),
|
|
413
|
-
`,
|
|
414
|
-
`,
|
|
411
|
+
`,u=ge(Yo,{});for(let d of r){let h=n[d].map(w=>`- ${w}`).join(`
|
|
412
|
+
`),S=u[d];a+=`[Chat ID: ${d}]
|
|
413
|
+
`,S?(a+=`- Existing Summary: "${S}"
|
|
414
|
+
`,a+=`-- New Memories to integrate:
|
|
415
415
|
${h}
|
|
416
416
|
|
|
417
|
-
`):
|
|
417
|
+
`):a+=`-- Individual Memories:
|
|
418
418
|
${h}
|
|
419
419
|
|
|
420
|
-
`}let f=0,m=5,c=!1,
|
|
421
|
-
`)}},
|
|
420
|
+
`}let f=0,m=5,c=!1,l="gemma-4-26b-a4b-it";for(t==="OpenRouter"&&(l="google/gemma-4-26b-a4b-it:free"),t==="DeepSeek"&&(l="deepseek-v4-flash");f<=m&&!c;){f++;try{let d=await Ui(o,l,a,null,"Fast"),p=d.text||"",h=Hi(p);if(h.length===0)throw new Error("No tool calls detected in synthesis response");for(let S of h){let w=S.toolName;["saveSummary","saveSumary","SaveSummary","SaveSumary"].includes(w)&&await xs(w,S.args,{chatId:e})}d.usageMetadata&&await To("tokens",d.usageMetadata.totalTokenCount||0),c=!0}catch(d){if(f>=m)throw new Error(`Failed after ${m} attempts. Last error: ${d.message}`)}}}catch(t){let n=Ie.join(Mo,"janitor");ct.existsSync(n)||ct.mkdirSync(n,{recursive:!0}),ct.appendFileSync(Ie.join(n,"error.log"),`[${new Date().toLocaleString()}] Past memory batch consolidation error: ${t.message}
|
|
421
|
+
`)}},Gi=async(e,o)=>{let{chatId:t,aiProvider:n="Google"}=e,s=Ie.join(jt,"chat-summaries.json"),r=d=>d.filter(p=>(p.role==="user"||p.role==="agent"||p.role==="system")&&!String(p.id).startsWith("welcome")&&!p.isMeta).map(p=>`[${p.text?.startsWith("[TOOL RESULT]")?"TOOL":p.role==="agent"?"AGENT":"USER"}]: ${p.text}`).join(`
|
|
422
422
|
|
|
423
|
-
`),
|
|
424
|
-
${
|
|
423
|
+
`),a=async(d,p)=>{let h="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.",S=p?`Here is the previous summary:
|
|
424
|
+
${p}
|
|
425
425
|
|
|
426
426
|
Here is the new conversation history:
|
|
427
|
-
${
|
|
427
|
+
${d}
|
|
428
428
|
|
|
429
429
|
Provide a new consolidated summary of the entire session.`:`Here is the conversation history:
|
|
430
|
-
${
|
|
431
|
-
|
|
432
|
-
Provide a consolidated summary of the entire session.`,
|
|
433
|
-
`),
|
|
434
|
-
`)
|
|
435
|
-
`;let
|
|
436
|
-
`;return}
|
|
437
|
-
`:
|
|
438
|
-
`:(
|
|
439
|
-
`,
|
|
440
|
-
`}),
|
|
430
|
+
${d}
|
|
431
|
+
|
|
432
|
+
Provide a consolidated summary of the entire session.`,w="gemma-4-26b-a4b-it";n==="OpenRouter"&&(w="google/gemma-4-26b-a4b-it:free"),n==="DeepSeek"&&(w="deepseek-v4-flash"),n==="NVIDIA"&&(w="stepfun-ai/step-3.7-flash");let T=0,b=!1,L=null;for(;T<=3&&!b;){T++;try{L=await Ui(e,w,S,h,"Fast"),b=!0}catch{if(T>3){if(n==="Google")try{return(await Ui(e,"gemini-3.1-flash-lite",S,h,"Fast")).text||""}catch{return""}return""}}}return L&&L.text||""},u=r(o),f=ge(s,{}),m=f[t]||{summary:"",historyLength:0};typeof m=="string"&&(m={summary:m,historyLength:0});let c=m.summary||"",l=await a(u,c);if(l){m.summary=l;let d=o.filter(p=>(p.role==="user"||p.role==="agent"||p.role==="system")&&!String(p.id).startsWith("welcome")&&!p.isMeta).length;return m.historyLength=d,f[t]=m,$e(s,f),l}return null},Rl=e=>{try{let o=Ie.join(jt,"chat-summaries.json");if(ct.existsSync(o)){let t=ge(o,{});t[e]&&(delete t[e],$e(o,t))}}catch{}},Wl=async function*(e,o,t,n,s){let{profile:r,thinkingLevel:a,mode:u,janitorModel:f,chatId:m,systemSettings:c,sessionStats:l,aiProvider:d="Google",apiTier:p}=t,h=Ni(e);if(!fr&&d==="Google")throw new Error("AI not initialized");let S=c?.memory!==!1,w=o[o.length-1].text,T=Ie.join(jt,"chat-summaries.json"),b=!1,L=o.filter(A=>A.role==="user").length===1,P=w.includes("[TITLE-UPDATE]"),Y=L||P,v=w.replace(/\[TITLE-UPDATE\]/g,"").trim();v=v.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),await Ct.startTransaction(m,v);let D=null;try{let A=new AbortController;D=setInterval(()=>{Vo&&(A.abort(),D&&(clearInterval(D),D=null))},400);let E=[...o.slice(0,-1)];{let Se=ge(T,{})[m]||{summary:"",historyLength:0};if(Se.summary&&Se.historyLength>0){let Je=0,Ee=[];for(let Be=0;Be<E.length;Be++){let pe=E[Be];(pe.role==="user"||pe.role==="agent"||pe.role==="system")&&!String(pe.id).startsWith("welcome")&&!pe.isMeta&&Je++,Je>Se.historyLength&&Ee.push(pe)}E=Ee}}let q=252e3,B=254e3;(d==="DeepSeek"||d==="NVIDIA"||d==="Google"&&p==="Paid")&&(q=396e3,B=4e5),(l?.tokens||0)>q&&(yield{type:"status_history",content:"Context Limit Reached. Condensing session history..."},await Gi(t,E)&&(E=[],b=!0)),L&&S&&(yield{type:"status",content:"Condensing past chat memories..."},await Du(m,t));let V=ge(yo,{}),_=ge(Yo,{}),K=Object.entries(V).filter(([ce])=>ce!==m).flatMap(([ce,Se])=>Se),se=[...Object.entries(_).filter(([ce])=>ce!==m).slice(-20).map(([ce,Se])=>`[Chat Summary]: ${Se}`),...K].map(ce=>`- ${ce}`).join(`
|
|
433
|
+
`),De=ge(Ht,[]).map(ce=>`- ${ce.memory}`).join(`
|
|
434
|
+
`),me=(l?.tokens||0)>=24e3,et=Na(se,De,S,me),Ye=new Date().toLocaleString([],{year:"numeric",month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!0}),je=[".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"],Oe=ce=>{try{return ct.readdirSync(ce,{withFileTypes:!0})}catch{return[]}},kt=(ce,Se={value:0},Je=1)=>{if(Se.value>6200||Je>7)return Se.value;let Ee=Oe(ce);for(let Be of Ee){if(Se.value>6200)break;je.includes(Be.name)||Be.isDirectory()&&(Se.value++,kt(Ie.join(ce,Be.name),Se,Je+1))}return Se.value},Ne=(ce,Se,Je="",Ee=1)=>{let Be=Oe(ce),pe=Ie.sep;if(Be.length>100)return`${Je}\u2514\u2500\u2500 ${Ie.basename(ce)}${pe} ...100+ files...
|
|
435
|
+
`;let It="",Fn=je,Zo=Be.filter(he=>!Fn.includes(he.name)),go=Be.filter(he=>Fn.includes(he.name)).map(he=>he.name).sort();Zo.sort((he,bo)=>he.isDirectory()&&!bo.isDirectory()?-1:!he.isDirectory()&&bo.isDirectory()?1:he.name.localeCompare(bo.name));let at=[...Zo.map(he=>({name:he.name,isDir:he.isDirectory()})),...go.map(he=>({name:he,isDir:!0,isCollapsed:!0}))];return at.forEach((he,bo)=>{let wt=bo===at.length-1,Bo=Ie.join(ce,he.name),Ut=wt?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",$n=Je+(wt?" ":"\u2502 ");if(he.isCollapsed){It+=`${Je}${Ut}${he.name}${pe}...
|
|
436
|
+
`;return}he.isDir?Ee>Se?It+=`${Je}${Ut}${he.name}${pe} ...depth exceeded...
|
|
437
|
+
`:Oe(Bo).length>80?It+=`${Je}${Ut}${he.name}${pe} ...80+ files...
|
|
438
|
+
`:(It+=`${Je}${Ut}${he.name}${pe}
|
|
439
|
+
`,It+=Ne(Bo,Se,$n,Ee+1)):It+=`${Je}${Ut}${he.name}
|
|
440
|
+
`}),It};yield{type:"status",content:"Gathering Context..."},await new Promise(ce=>setTimeout(ce,500));let He=kt(process.cwd()),We=12;He>4096?We=1:He>3072?We=2:He>2048?We=3:He>1024?We=4:He>512?We=6:He>256?We=7:He>128?We=8:He>64?We=9:He>32&&(We=10);let Vt=ge(Vr,{}),Nt=Vt[m],Ge=Nt?Nt!==process.cwd():!1;Vt[m]=process.cwd(),$e(Vr,Vt);let ze=ge(T,{}),yt=ze[m]||{summary:"",historyLength:0};typeof yt=="string"&&(yt={summary:yt,historyLength:0});let co=o.filter(ce=>(ce.role==="user"||ce.role==="agent"||ce.role==="system")&&!String(ce.id).startsWith("welcome")&&!ce.isMeta).length;yt.historyLength&&co<yt.historyLength&&(yt.summary="",yt.historyLength=0,ze[m]=yt,$e(T,ze));let qt=typeof yt=="object"?yt.summary||"":yt||"",z=qt?`
|
|
441
441
|
**CONTEXT SUMMARY OF PREVIOUS TURNS (PRIORITY: HIGH)**
|
|
442
|
-
${
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
`)
|
|
442
|
+
${qt}
|
|
443
|
+
`:"",Ft=process.cwd()+`
|
|
444
|
+
`+Ne(process.cwd(),We),oo=await Nr(),no="";if(Ko())if(no=`[IDE CONTEXT]
|
|
445
|
+
`,oo.file_focused!=="none"){let ce=Ie.relative(process.cwd(),oo.file_focused),Se=(oo.opened_editors||[]).map(Ee=>{let Be=Ie.relative(process.cwd(),Ee);return Be.startsWith("..")?`[External] ${Ie.basename(Ee)}`:Be});if(no+=`Focused File: ${ce}
|
|
446
|
+
Cursor Line: ${oo.cursor_line}
|
|
447
|
+
`,oo.selected&&(no+=`Current Selection: "${oo.selected}"
|
|
448
|
+
`),oo.manual_edits){let Ee=oo.manual_edits,Be=4*512,pe=50,It=Ee.split(`
|
|
449
|
+
`);It.length>pe&&(Ee=It.slice(0,pe).join(`
|
|
449
450
|
`)+`
|
|
450
|
-
... (${
|
|
451
|
-
... (Character limit reached, truncated)`),
|
|
452
|
-
${
|
|
453
|
-
`}
|
|
451
|
+
... (${It.length-pe} more lines truncated)`),Ee.length>Be&&(Ee=Ee.substring(0,Be)+`
|
|
452
|
+
... (Character limit reached, truncated)`),no+=`Recent Manual Edits:
|
|
453
|
+
${Ee}
|
|
454
|
+
`}Se.length>0&&(no+=`All Opened Editors: ${Se.join(", ")}`),oo.diagnostics&&(no+=`
|
|
454
455
|
**ACTIVE FILE ERRORS**:
|
|
455
|
-
${
|
|
456
|
-
`),(
|
|
456
|
+
${oo.diagnostics}
|
|
457
|
+
`),(v.toLowerCase().includes("lint")||v.toLowerCase().includes("warning"))&&oo.warnings&&(no+=`
|
|
457
458
|
**LINT WARNINGS**:
|
|
458
|
-
${
|
|
459
|
-
`)}else
|
|
460
|
-
CWD: ${process.cwd()}${
|
|
459
|
+
${oo.warnings}
|
|
460
|
+
`)}else no+="No file currently focused.";let Rr=`[SYSTEM METADATA (PRIORITY: DYNAMIC), Chat Context >> Metadata] Time: ${Ye}
|
|
461
|
+
CWD: ${process.cwd()}${Ge?` (WARNING: CWD Mismatch! Previous Path: ${Nt})`:""}
|
|
461
462
|
**DIRECTORY STRUCTURE**
|
|
462
|
-
${
|
|
463
|
-
${
|
|
464
|
-
`:""}`:""}[USER] ${
|
|
465
|
-
|
|
466
|
-
[
|
|
467
|
-
|
|
468
|
-
[
|
|
469
|
-
[
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
${
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
${M
|
|
463
|
+
${Ft}${z}${et}${no}
|
|
464
|
+
${a!="Fast"&&d==="Google"?`${e.toLowerCase().startsWith("gemma")?`[SYSTEM] **STRICTLY FOLLOW THINKING POLICY AS CRITICAL PRIORITY. DO NOT START A RESPONSE WITHOUT <think> ... </think>**
|
|
465
|
+
`:""}`:""}[USER] ${v.replace(/\s*\[Prompted on:.*?\]/g,"").trim()}`.trim();E.push({role:"user",text:Rr});let Bt=null,So=u==="Flux"?70:7,Xe=16;yield{type:"status",content:"Connecting..."},Vo=!1;let Eo=[],Qo=!1;E.forEach(ce=>{ce.text&&ce.role==="agent"&&(ce.text=ce.text.replace(/(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])/gi,"").trim())});for(let ce=0;ce<=So;ce++){if(Qo=!1,c?.compression===0&&(l?.tokens||0)>B&&(E=Ga(E,6)),ce>0&&(yield{type:"status",content:"Processed. Reconnecting..."}),Vo){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
|
|
466
|
+
|
|
467
|
+
\x1B[33m\u2139 Request Cancelled\x1B[0m`};break}if(n){let be=await n();be&&(E.length>0&&E[E.length-1].role==="user"?E[E.length-1].text+=`
|
|
468
|
+
|
|
469
|
+
[STEERING HINT]: ${be}`:E.push({role:"user",text:`${a!="Fast"&&d==="Google"?`${e.toLowerCase().startsWith("gemma")?`[SYSTEM] **STRICTLY FOLLOW THINKING POLICY AS CRITICAL PRIORITY. DO NOT START A RESPONSE WITHOUT <think> ... </think>**
|
|
470
|
+
`:""}`:""}[STEERING HINT]: ${be}`}),yield{type:"status",content:"Steering Hint Injected."})}let Se,Je=!1,Ee=1,Be=1,pe="",It=null,Fn=null,Zo=null,go=0,at=[],he=0,bo=!1,wt=!1,Bo=!1,Ut=!1,$n=!0,Tt="",ut="",ro=!1,Rt=e,Uo="";for(;Ee<=Xe&&Be<=Xe&&!Je&&!Vo;){let be=!1;try{pe="",$n&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},yield{type:"spinner",content:!0},$n=!1,Be===1&&(Tt=""));let fe=E.filter(ae=>(ae.role==="user"||ae.role==="agent"||ae.role==="system")&&!String(ae.id).startsWith("welcome")&&!ae.isMeta&&!ae.isTerminalRecord&&!(ae.text&&ae.text.startsWith("[TERMINAL_RECORD]"))).map((ae,xe,Qe)=>{let Le=ae.text||"";ae.role==="agent"&&(Le=Le.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim());let pt=[{text:Le}];return ae.binaryPart&&Ni(Rt)&&Qe.slice(xe+1).filter(hn=>hn.role==="user"&&!hn.text?.startsWith("[TOOL RESULT]")).length<=2&&pt.push(ae.binaryPart),{role:ae.role==="user"||ae.role==="system"?"user":"model",parts:pt}});for(let ae=0;ae<fe.length;ae++){let xe=fe[ae],Qe=xe.parts?.[0]?.text||"";if(xe.role==="model"&&/\[tool:/i.test(Qe)){let Le=-1;for(let pt=ae+1;pt<fe.length;pt++){let ko=fe[pt],hn=ko.parts?.[0]?.text||"";if(ko.role==="user"&&hn.startsWith("[TOOL RESULT]")){Le=pt;break}}if(Le!==-1&&Le!==ae+1){let[pt]=fe.splice(Le,1);fe.splice(ae+1,0,pt)}}}for(let ae=fe.length-2;ae>=0;ae--){let xe=fe[ae],Qe=fe[ae+1];xe.role==="user"&&Qe.role==="user"&&(Qe.parts?.[0]?.text||"").trim().startsWith("[SYSTEM")&&fe.splice(ae,1)}let _e=[];for(let ae=0;ae<fe.length;ae++){let xe=fe[ae];if(_e.length===0)_e.push(xe);else{let Qe=_e[_e.length-1];Qe.role===xe.role?(Qe.parts[0].text+=`
|
|
471
|
+
|
|
472
|
+
`+(xe.parts?.[0]?.text||""),xe.parts?.length>1&&Qe.parts.push(...xe.parts.slice(1))):_e.push(xe)}}if(fe.length=0,fe.push(..._e),!await ai("agent",t))throw new Error("Error: Quota Exausted for Agent");Rt=e,d==="DeepSeek"&&a==="Fast"&&Rt.includes("flash")&&(Rt="deepseek-chat"),Ee===Xe-1?(Rt=d==="DeepSeek"?"deepseek-v4-flash":"gemini-3-flash-preview",yield{type:"model_update",content:"Trying with fallback model"}):Ee===Xe?(Rt=d==="DeepSeek"?"deepseek-v4-pro":"gemini-3.5-flash",yield{type:"model_update",content:"Trying with fallback model"}):Ee>12&&Ee<Xe-2&&t.apiKey!=="custom"?(Rt="gemma-4-31b-it",yield{type:"model_update",content:"Trying with fallback Gemma Model"}):Ee>0&&(yield{type:"model_update",content:null}),Uo=Ba(r,(Rt||"gemma").toLowerCase().startsWith("gemma")?a:"GEM",u,c,S,L,d,h);let so=e&&e.toLowerCase().startsWith("gemma")&&d==="Google",Mt=fe[fe.length-1];if(so){let ae=`
|
|
473
|
+
[SYSTEM] Tool result received. Analyze output and proceed with your turn${a!="Fast"&&d==="Google"?". **STRICTLY MAINTAIN THINKING POLICY. DO NOT START A RESPONSE WITHOUT <think> ... </think>**":""}`;Mt&&Mt.role==="user"&&Mt.parts?.[0]?.text?.startsWith("[TOOL RESULT]")&&(Mt.parts[0].text+=ae)}if(so){let ae=Math.floor(So*(u==="Flux"?.98:.7)),xe=ce+1;xe>=ae&&Mt&&Mt.parts?.[0]&&(Mt.parts[0].text+=`
|
|
474
|
+
[SYSTEM] WARNING, Turn Limit Impending: Step ${xe}/${So}. Wrap up quickly/prompt user to continue & use [[END]] or [turn:finish] quickly.`)}let ft=fe;d==="OpenRouter"?Se=ji(t.apiKey,Rt,ft,Uo,a,u,h,A.signal):d==="DeepSeek"?Se=Wi(t.apiKey,Rt,ft,Uo,a,u,h,A.signal):d==="NVIDIA"?Se=Yi(t.apiKey,Rt,ft,Uo,a,u,h,A.signal):Se=await fr.models.generateContentStream({model:Rt||"gemma-4-31b-it",contents:ft,config:{systemInstruction:Uo,temperature:u==="Flux"?1:1.4,maxOutputTokens:32768,mediaResolution:"MEDIA_RESOLUTION_MEDIUM",safetySettings:[{category:An.HARM_CATEGORY_HARASSMENT,threshold:Mn.BLOCK_NONE},{category:An.HARM_CATEGORY_HATE_SPEECH,threshold:Mn.BLOCK_NONE},{category:An.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Mn.BLOCK_NONE},{category:An.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Mn.BLOCK_NONE}],thinkingConfig:(()=>{let ae=(Rt||"").toLowerCase(),xe=ae.includes("gemma-4")||ae.startsWith("gemma"),Qe=ae.includes("gemini-3");if(xe||Qe)return xe?{includeThoughts:!1,thinkingLevel:_o.MINIMAL}:{includeThoughts:!0,thinkingLevel:{Fast:ae.includes("pro")?_o.LOW:_o.MINIMAL,Low:_o.LOW,Medium:_o.MEDIUM,Standard:_o.MEDIUM,High:_o.HIGH,xHigh:_o.HIGH}[a]||_o.MEDIUM};{let Le={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[a]||2048;return Le===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:Le}}})()}},{signal:A.signal}),pe="",It=null,Zo=null,at=[],he=0,yield{type:"model_update",content:null},ut="",ro=Tt.length>0;let dt="",Jn=Date.now(),Do=!0;for await(let ae of Se){if(Do&&(yield{type:"status",content:"Working..."},Do=!1),Vo){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
|
|
475
|
+
|
|
476
|
+
\x1B[33m\u2139 Request Cancelled\x1B[0m`};break}let xe="",Qe=ae.candidates?.[0]?.content?.parts;if(Qe&&Qe.length>0)for(let Le of Qe)Le.thought?Le.text&&(be||(xe+="<think>",be=!0),xe+=Le.text):Le.text&&(be&&(xe+="</think>",be=!1),xe+=Le.text);else{let Le=ae.text||"";Le&&be&&(xe+="</think>",be=!1),xe+=Le}if(xe){if(ro){if(ut+=xe,ut.length>=30){let te=0,Ze=Math.min(Tt.length,ut.length);for(let X=Ze;X>0;X--)if(Tt.endsWith(ut.substring(0,X))){te=X;break}let St=ut.substring(te);if(St){let ht=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(Tt)?St.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):St.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");ht&&(pe+=ht,d==="Google"?dt+=ht:yield{type:"text",content:ht})}ro=!1,ut=""}continue}else pe+=xe,d==="Google"?dt+=xe:yield{type:"text",content:xe};let Le=_l(pe),pt=Au(pe);if(pt.inside){Zo||(Zo=Date.now());let te=pt.toolName,St={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"}[te]||te,X=pt.args||"",ht=null;if(["write_file","update_file","view_file","read_folder","write_pdf","write_docx","search_keyword","generate_image","file_map"].includes(St)){let Re=re(X),Wo=Re.path||Re.targetFile||Re.TargetFile||Re.directory,gt=Re.keyword;if(gt)ht=gt.replace(/["']/g,"");else if(Wo)ht=Ie.basename(Wo.replace(/["']/g,"").replace(/\\/g,"/"));else{let U=X.match(/(?:path|targetFile|TargetFile|directory|keyword)\s*=\s*\\?["']?([^\\"' \),]+)/);if(U){let Ve=U[1].replace(/["']/g,"");ht=St==="search_keyword"||St==="file_map"?Ve:Ie.basename(Ve.replace(/\\/g,"/"))}}}let $t=`${Pl[St]||St}${ht?` (${ht})`:""}`;if((St!==It||ht!==Fn)&&(It=St,Fn=ht,yield{type:"status",content:`${$t}...`},process.stdout.isTTY)){let Wo={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"}[St]||"Working";process.stdout.write(`\x1B]0;${Wo}...\x07`)}}let ko=Ul(pe,!1),Ro=(ko.match(/(?:<think>|\[think\])([\s\S]*?)(?:<\/think>|\[\/think\]|$)/gi)||[]).join("").trim(),en=Ro.split(/[.!?]\s+/),yr=new Set(en),Zn=en.length>10?(en.length-yr.size)/en.length:0,jr=Ro.split(/\s+/).filter(te=>te.length>0).length,_n=.4,Fs=.6,tn=!1;if((Rt||"").toLowerCase().startsWith("gemma")){let Ze={low:256,medium:768,high:2048,max:4096,xhigh:4096}[a?.toLowerCase()]||2500;tn=jr>Ze}if(Zn>_n||tn){yield{type:"status",content:`${Zn>_n?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},wt=!0,await new Promise(Ze=>setTimeout(Ze,3e3));break}let Nn=Le.trim().split(/[.!?]\s+/),wr=new Set(Nn);if((Nn.length>10?(Nn.length-wr.size)/Nn.length:0)>Fs){yield{type:"status",content:"Response Loop Detected. Re-centering..."},wt=!1,Ut=!0,await new Promise(te=>setTimeout(te,3e3));break}let on=ko.toLowerCase().split(/\s+/).filter(te=>te.length>0),Bn=!1;if(on.length>5)for(let te=1;te<=15;te++){let Ze=Math.max(3,Math.ceil(8/te));if(on.length<te*Ze)continue;let St=!0,ht=on.slice(on.length-te).join(" ");for(let $t=1;$t<Ze;$t++)if(on.slice(on.length-te*($t+1),on.length-te*$t).join(" ")!==ht){St=!1;break}if(St){Bn=!0;break}}if(!Bn){let te=ko.toLowerCase().replace(/[^a-z0-9]/gi,"");if(te.length>=10)for(let Ze=1;Ze<=10;Ze++){let St=Math.max(4,Math.ceil(12/Ze));if(te.length<Ze*St)continue;let X=te.substring(te.length-Ze),ht=!0;for(let $t=1;$t<St;$t++)if(te.substring(te.length-Ze*($t+1),te.length-Ze*$t)!==X){ht=!1;break}if(ht){Bn=!0;break}}}if(Bn){yield{type:"status",content:"Stuttering Detected. Re-centering..."},wt=!1,Bo=!0,await new Promise(te=>setTimeout(te,3e3));break}let Un=pe.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/gi,""),Gr=Hi(Un);for(;Gr.length>he;){let te=Gr[he],Ze=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"}[te.toolName]||te.toolName,ht=Pl[X]||te.toolName,$t=Mu(X,te.args);yield{type:"status",content:`${ht}${$t?` (${$t})`:""}...`};let Re="";if(X==="web_search"){let{query:ue,limit:Pe=10}=re(te.args);Re=`\u{1F50D} Searched: ${ue}`}else if(X==="web_scrape")Re=`\u{1F4D6} Visited: ${re(te.args).url||"..."}`;else if(X==="view_file"){let{path:ue,StartLine:Pe,EndLine:Ce,start_line:rt,end_line:x,startLine:g,endLine:O}=re(te.args),N=Pe||rt||g,M=Ce||x||O,$=parseInt(N)||1,R=parseInt(M)||(N?$+800:800),k="...",F=R;try{let ee=Ie.resolve(process.cwd(),ue);if(ct.existsSync(ee)){let Me=ct.readFileSync(ee,"utf8").split(`
|
|
477
|
+
`).length;k=Me,F=Math.min(R,Me)}}catch{}let W=ue.toLowerCase(),j=W.endsWith(".pdf"),Z=W.endsWith(".docx")||W.endsWith(".doc")||W.endsWith(".ppt")||W.endsWith(".pptx")||W.endsWith(".xls")||W.endsWith(".xlsx"),ne=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(W);j||Z?Re=`\u{1F4C4} Viewed: ${ue}`:ne?Re=`\u{1F4F8} Viewed: ${ue}`:Re=`\u{1F4C4} Read: ${ue} \u2192 Lines ${$} - ${F} of ${k}`}else if(X==="list_files"||X==="read_folder"){let ue=X==="list_files"?"List":"Viewed",Pe=re(te.args).path;Re=`\u{1F4C2} ${ue}: ${Pe==="."?"./":Pe}`}else if(X==="write_file"||X==="update_file")Re=`\u{1F4BE} ${X==="write_file"?"Created":"Edited"}: ${re(te.args).path||"..."}`;else if(X==="write_pdf")Re=`\u{1F4D1} Created: ${re(te.args).path||"..."}`;else if(X==="write_docx")Re=`\u{1F4DD} Created: ${re(te.args).path||"..."}`;else if(X==="file_map")Re=`\u{1F4CB} Get Map: ${re(te.args).path||"..."}`;else if(X==="search_keyword")Re="";else if(X==="generate_image"){let{path:ue,outputPath:Pe,output:Ce}=re(te.args);Re=`\u{1F3A8} Generated: ${ue||Pe||Ce||"generated_image.png"}`}else X==="exec_command"||X==="ask"?Re="":Re=`Executed: ${te.toolName}`;if(X==="exec_command"){let{command:ue}=re(te.args);if(ue&&t.systemSettings&&t.systemSettings.allowExternalAccess===!1){let Pe=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],Ce=Ie.resolve(process.cwd()).substring(0,3).toLowerCase();if(Pe.some(x=>{if(x.source==="[a-zA-Z]:[\\\\\\/]"){let g=ue.match(/[a-zA-Z]:[\\\/]/i);return g&&g[0].toLowerCase()!==Ce}return x.test(ue)})){let x='Access Denied. Terminal is prohibited from accessing system drives (C://) or external directories while "External Workspace Access" is disabled.';t.onExecStart&&t.onExecStart(ue||"Unknown"),yield{type:"exec_start"},await new Promise(g=>setTimeout(g,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${x}`),await new Promise(g=>setTimeout(g,50)),t.onExecEnd&&t.onExecEnd(),at.push({role:"user",text:`[TOOL RESULT]: ERROR: ${x}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${x}`},he++;continue}}t.onExecStart&&t.onExecStart(ue||"Unknown"),yield{type:"exec_start"}}let Wo=re(te.args),gt=Wo.path||Wo.targetPath||null;if(gt){let ue=t.systemSettings&&t.systemSettings.allowExternalAccess===!1,Pe=Ie.resolve(gt),Ce=Ie.resolve(process.cwd());if(ue&&!Pe.startsWith(Ce)){let rt="Access Denied. You are not allowed to access files outside the current workspace.";if(X==="write_file"||X==="update_file"){let g=`\u{1F4BE} ${X==="write_file"?"Write Canceled":"Edit Canceled"}: ${Wo.path||"..."}`,O=Math.min(g.length+4,115),N=`\u256D${"\u2500".repeat(O)}\u256E`,M=`\u2502 ${g.padEnd(O-2).substring(0,O-2)} \u2502`,$=`\u2570${"\u2500".repeat(O)}\u256F`;yield{type:"visual_feedback",content:`${N}
|
|
478
|
+
${M}
|
|
479
|
+
${$}`}}at.push({role:"user",text:`[TOOL RESULT]: ERROR: ${rt}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${rt}`},he++;continue}}if(t.onToolApproval&&(X==="write_file"||X==="update_file"||X==="exec_command")){let Pe=t.systemSettings||{},Ce=Pe.autoExec,rt=null,x=!1,g=!1,O=!1;if(X==="exec_command"){let{command:j}=re(te.args),Z=(j||"").trim(),ne=(Me,Et)=>{if(!Et)return!1;let Wt=Et.split(",").map(Yt=>Yt.trim().toLowerCase()).filter(Boolean),Io=Me.toLowerCase();return Wt.some(Yt=>Io.startsWith(Yt))},ee=ne(Z,Pe.alwaysAskCommands),le=ne(Z,Pe.autoApproveCommands);g=ne(Z,Pe.autoDisallowCommands),ee?x=!0:(le||Pe.autoApproveGit&&/^git\s+commit\b/i.test(Z))&&(rt="allow"),!x&&!rt&&(Pe.networkAccess===!1&&/\b(curl|wget|npm|yarn|pnpm|pip|pip3|ssh|docker|git\s+(clone|push|pull|fetch))\b/i.test(Z)&&(rt="deny",O=!0),!rt&&g&&(rt="deny")),!x&&!rt&&Ce&&(rt="allow")}else Ce&&(rt="allow");let N=rt,M="";rt==="deny"&&(O?M="network":g?M="settings":M="prohibited");let $=!1,R="",k=[],F=0,W=!1;if(!N){if(X==="write_file"||X==="update_file")try{let ne=re(te.args),{path:ee}=ne;if(ee){let le=Ie.resolve(process.cwd(),ee),Me=bt=>bt?bt.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,uo=>uo.toUpperCase()):"",Et=Me(le),Wt="",Io=!1,Yt=await Nr(),gn=Me(Yt?.file_focused);if(Yt&&gn===Et&&Yt.full_content?(Wt=Yt.full_content,Io=!0):ct.existsSync(le)&&(Wt=ct.readFileSync(le,"utf8"),Io=!0),R=Wt,await Ct.recordFileChange(le,Wt),Io){let bt=Wt;if(X==="write_file")bt=ne.content||ne.newContent||"";else{let{patchPairs:uo,error:tr}=ns(ne);if(tr){let ye=`[TOOL RESULT]: ERROR: ${tr}`;at.push({role:"user",text:ye}),await Xo("toolFailure"),t.onToolResult&&t.onToolResult("failure",X),yield{type:"tool_result",content:ye,toolName:X},he++;continue}F=uo.length;let H=rs(Wt,uo);bt=H.content,k=H.results;let Ae=k.filter(ye=>ye.success),Fe=k.filter(ye=>!ye.success);if(Ae.length===0){let ye=`[TOOL RESULT]: ERROR: Failed to apply patches to [${Ie.basename(le)}].
|
|
480
|
+
${Fe.map(lt=>` \u2022 ${lt.error}`).join(`
|
|
481
|
+
`)}`,tt=`\u{1F4BE} Edited: ${Ie.basename(le)}`.toUpperCase(),de=Math.min(tt.length+4,115),we=`\u256D${"\u2500".repeat(de)}\u256E`,ot=`\u2502 ${tt.padEnd(de-2).substring(0,de-2)} \u2502`,st=`\u2570${"\u2500".repeat(de)}\u256F`;yield{type:"visual_feedback",content:`${we}
|
|
482
|
+
${ot}
|
|
483
|
+
${st}`},at.push({role:"user",text:ye}),await Xo("toolFailure"),t.onToolResult&&t.onToolResult("failure",X),yield{type:"tool_result",content:ye,toolName:X},he++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${Ie.basename(le)}...`},Pi(le,Wt,bt),$=!0,await new Promise(uo=>setTimeout(uo,50))}else if(X==="write_file"){let bt=ne.content||ne.newContent||"";ct.existsSync(le)||(W=!0,ct.mkdirSync(Ie.dirname(le),{recursive:!0}),ct.writeFileSync(le,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${Ie.basename(le)}...`},Pi(le,"",bt),$=!0,await new Promise(uo=>setTimeout(uo,50))}}}catch(ne){console.error("Simulation/Diff Error:",ne)}let j=null;$i(ne=>{j=ne});let Z=t.onToolApproval;if(N=await new Promise(async ne=>{let ee=setInterval(()=>{j&&(Bi.onIDEApproval&&Bi.onIDEApproval(j),clearInterval(ee),ne(j))},100);try{let le=await Z(X,te.args);clearInterval(ee),ne(le)}catch{clearInterval(ee),ne("deny")}}),$i(null),X==="write_file"||X==="update_file"){let{path:ne}=re(te.args);if(ne){let ee=Ie.resolve(process.cwd(),ne);if($l(ee,N),N==="deny"&&W&&ct.existsSync(ee))try{ct.unlinkSync(ee)}catch{}}}N==="deny"&&(M="user")}if(N==="allow"&&$&&Ko()){let{path:j}=re(te.args),Z=Ie.resolve(process.cwd(),j),ne=await Nr(),ee="";ne&&ne.file_focused===Z&&ne.full_content?ee=ne.full_content:ct.existsSync(Z)&&(ee=ct.readFileSync(Z,"utf8"));let le=ee.split(/\r?\n/),Me=le.length,Et=Buffer.byteLength(ee,"utf8"),Wt="";R&&(Wt=`Old File contents:
|
|
484
|
+
${R.split(/\r?\n/).map((de,we)=>`${we+1} | ${de}`).join(`
|
|
478
485
|
`)}
|
|
479
486
|
|
|
480
|
-
`);let
|
|
481
|
-
`);else{let
|
|
482
|
-
`),
|
|
483
|
-
`);
|
|
487
|
+
`);let Io="";if(Me<=200)Io=le.join(`
|
|
488
|
+
`);else{let tt=le.slice(0,100).join(`
|
|
489
|
+
`),de=le.slice(-100).join(`
|
|
490
|
+
`);Io=`${tt}
|
|
484
491
|
|
|
485
|
-
... [${
|
|
492
|
+
... [${Me-200} lines truncated for history stability] ...
|
|
486
493
|
|
|
487
|
-
${
|
|
494
|
+
${de}`}let Yt="";if(X==="update_file"){let tt=ss(R,ee,k,12);Yt=`SUCCESS: File [${j}] updated via IDE Companion (May have user edits). [${k.length}/${F}] blocks applied.
|
|
488
495
|
|
|
489
|
-
${
|
|
490
|
-
${
|
|
496
|
+
${tt}`}else{let tt=ee.split(/\r?\n/),de=tt.length,we=Buffer.byteLength(ee,"utf8"),ot="";R&&(ot=`Old File contents:
|
|
497
|
+
${R.split(/\r?\n/).map((vt,or)=>`${or+1} | ${vt}`).join(`
|
|
491
498
|
`)}
|
|
492
499
|
|
|
493
|
-
`);let
|
|
494
|
-
`);else{let
|
|
495
|
-
`),
|
|
496
|
-
`);
|
|
500
|
+
`);let st="";if(de<=200)st=tt.join(`
|
|
501
|
+
`);else{let lt=tt.slice(0,100).join(`
|
|
502
|
+
`),vt=tt.slice(-100).join(`
|
|
503
|
+
`);st=`${lt}
|
|
497
504
|
|
|
498
|
-
... [${
|
|
505
|
+
... [${de-200} lines truncated] ...
|
|
499
506
|
|
|
500
|
-
${
|
|
507
|
+
${vt}`}Yt=`SUCCESS: File [${j}] saved via IDE Companion (May have user edits).
|
|
501
508
|
|
|
502
|
-
- Stats: [${
|
|
503
|
-
${
|
|
504
|
-
${
|
|
509
|
+
- Stats: [${de} lines, ${(we/1024).toFixed(1)} KB]
|
|
510
|
+
${ot}- Content Preview:
|
|
511
|
+
${st}
|
|
505
512
|
|
|
506
|
-
Check if Starting and Ending matches your write.`}let
|
|
507
|
-
${
|
|
508
|
-
${
|
|
509
|
-
${
|
|
510
|
-
${
|
|
511
|
-
${
|
|
512
|
-
${
|
|
513
|
-
${
|
|
514
|
-
${
|
|
515
|
-
`)}`;
|
|
513
|
+
Check if Starting and Ending matches your write.`}let bt=`\u{1F4BE} ${X==="write_file"?"Written":"Edited"}: ${j||"..."}`,uo=Math.min(bt.length+4,115),tr=`\u256D${"\u2500".repeat(uo)}\u256E`,H=`\u2502 ${bt.padEnd(uo-2).substring(0,uo-2)} \u2502`,Ae=`\u2570${"\u2500".repeat(uo)}\u256F`;yield{type:"visual_feedback",content:`${tr}
|
|
514
|
+
${H}
|
|
515
|
+
${Ae}`};let Fe=Date.now();go=Fe,yield{type:"tool_time",content:Fe-Ze};let ye=`[TOOL RESULT]: ${Yt}`;at.push({role:"user",text:ye}),bo=!0,await Xo("toolSuccess"),t.onToolResult&&t.onToolResult("success",X),yield{type:"tool_result",content:Yt,aiContent:ye,toolName:X},he++;continue}if(N==="deny"){let j=`Permission Denied: Prohibited ${X==="exec_command"?"Command":"file edit"}.`;if(M==="user"?j="Permission Denied by User":M==="settings"?j="Permission Denied by User Policy":M==="network"?j="Permission Denied: Sandbox Network Access Disabled by User Policy.":M==="prohibited"&&X==="exec_command"&&(j="Permission Denied: Prohibited Command"),X==="write_file"||X==="update_file"){let ne=`\u{1F4BE} ${X==="write_file"?"WRITE DENIED":"UPDATE DENIED"}: ${re(te.args).path||"..."}`.toUpperCase(),ee=Math.min(ne.length+4,115),le=`\u256D${"\u2500".repeat(ee)}\u256E`,Me=`\u2502 ${ne.padEnd(ee-2).substring(0,ee-2)} \u2502`,Et=`\u2570${"\u2500".repeat(ee)}\u256F`;yield{type:"visual_feedback",content:`${le}
|
|
516
|
+
${Me}
|
|
517
|
+
${Et}`}}X==="exec_command"&&(await new Promise(Z=>setTimeout(Z,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${j}`),await new Promise(Z=>setTimeout(Z,50)),t.onExecEnd&&t.onExecEnd()),at.push({role:"user",text:`[TOOL RESULT]: DENIED: ${j}`}),yield{type:"tool_result",content:`[TOOL RESULT]: DENIED: ${j}`},await Xo("toolDenied"),t.onToolResult&&t.onToolResult("denied",X),he++;continue}}if(Re){let ue=Math.min(Re.length+4,115),Pe=`\u256D${"\u2500".repeat(ue)}\u256E`,Ce=`\u2502 ${Re.padEnd(ue-2).substring(0,ue-2)} \u2502`,rt=`\u2570${"\u2500".repeat(ue)}\u256F`;yield{type:"visual_feedback",content:`${Pe}
|
|
518
|
+
${Ce}
|
|
519
|
+
${rt}`}}if(go>0){let ue=Date.now()-go;ue<1e3&&await new Promise(Pe=>setTimeout(Pe,1e3-ue))}yield{type:"spinner",content:!1};let U={chatId:m,history:o,onChunk:ue=>t.onExecChunk?t.onExecChunk(ue):null,onAskUser:t.onAskUser,systemSettings:t.systemSettings,mode:u,isMultiModal:Ni(Rt)};if(X==="write_file"||X==="update_file")try{let{path:ue}=re(te.args);if(ue){let Pe=Ie.resolve(process.cwd(),ue),Ce=await Nr();Ce&&Ce.file_focused===Pe&&Ce.full_content&&(U.forcedContent=Ce.full_content)}}catch{}let Ve=await xs(X,te.args,U);if(yield{type:"spinner",content:!0},X==="write_file"&&Ve.startsWith("SUCCESS")){let{path:ue}=re(te.args);if(ue){let Pe=Ie.resolve(process.cwd(),ue);Fl(Pe)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let er=Date.now();go=er,yield{type:"tool_time",content:er-Ze},Zo=er;let Q=null;if(typeof Ve=="object"&&Ve.binaryPart&&(Q=Ve.binaryPart,Ve=Ve.text),X==="search_keyword"){let{keyword:ue,file:Pe}=re(te.args),Ce=0;if(Ve){let M=Ve.match(/Found (\d+) matches/i);M&&(Ce=parseInt(M[1]))}let rt=`\u{1F50E} Searched: "${ue}" in ${Pe?`"${Pe}"`:"./"} \u2192 ${Ce} Match${Ce===1?"":"es"}`,x=Math.min(rt.length+4,115),g=`\u256D${"\u2500".repeat(x)}\u256E`,O=`\u2502 ${rt.padEnd(x-2).substring(0,x-2)} \u2502`,N=`\u2570${"\u2500".repeat(x)}\u256F`;yield{type:"visual_feedback",content:`${g}
|
|
520
|
+
${O}
|
|
521
|
+
${N}`}}X==="exec_command"&&t.onExecEnd&&(await new Promise(ue=>setTimeout(ue,800)),t.onExecEnd());let Xr=Ve&&Ve.startsWith("DENIED:");Ve&&!Ve.startsWith("ERROR:")&&!Xr?(await Xo("toolSuccess"),t.onToolResult&&t.onToolResult("success",X)):Xr||(await Xo("toolFailure"),t.onToolResult&&t.onToolResult("failure",X));let Sr=`[TOOL RESULT]: ${(Ve||"").toString().split(/\r?\n/).filter(ue=>!ue.includes("[UI_CONTEXT]")).join(`
|
|
522
|
+
`)}`;at.push({role:"user",text:Sr,binaryPart:Q}),bo=!0;let Rn=`[TOOL RESULT]: ${Ve||""}`;(X==="view_file"||X==="web_scrape")&&(Rn=`[TOOL RESULT]: ${Re} (Context Locked for UI Clarity)`),yield{type:"tool_result",content:Rn,aiContent:Sr,binaryPart:Q,toolName:X},X==="memory"&&Ve.includes("SUCCESS")&&(yield{type:"memory_updated"}),he++}d==="Google"&&dt&&Date.now()-Jn>=150&&(yield{type:"text",content:dt},dt="",Jn=Date.now())}ae.usageMetadata&&(Bt=ae.usageMetadata),Bt&&(yield{type:"liveTokens",content:Bt.totalTokenCount})}if(be&&(be=!1,ro?ut+="</think>":(pe+="</think>",d==="Google"?dt+="</think>":yield{type:"text",content:"</think>"})),ro&&ut.length>0){let ae=0,xe=Math.min(Tt.length,ut.length);for(let Le=xe;Le>0;Le--)if(Tt.endsWith(ut.substring(0,Le))){ae=Le;break}let Qe=ut.substring(ae);if(Qe){let pt=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(Tt)?Qe.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):Qe.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");pt&&(pe+=pt,d==="Google"?dt+=pt:yield{type:"text",content:pt})}ro=!1,ut=""}if(d==="Google"&&dt&&(yield{type:"text",content:dt},dt=""),Vo)break;let At=(pe||"").trim(),zt=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(At.toLowerCase())||/\[\[END\]\]/i.test(At.toLowerCase()),Co=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(At.toLowerCase()),Pn=at.length>0||It!==null,Qn=At.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/gi,"").trim(),Os=/(\p{Emoji_Presentation}|\p{Extended_Pictographic})$/u.test(Qn),Yr=/([.!?"'*_`|\]\)”’~~]+|\s|`{3}|[\u200B-\u200D\uFEFF])$/u.test(Qn.trim()),Ls=/[.!?}"'`’“”]$|```$/s.test(Qn)||Yr||Os;if(!zt&&!Co&&!Pn&&At.length>0&&!Ls&&!wt&&!Bo&&!Ut)throw new Error("Silent stream cutoff (500): Model stream closed cleanly but cut off mid-sentence without signals.");Je=!0,await Xo("agent")}catch(fe){if(Vo){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
|
|
523
|
+
|
|
524
|
+
\x1B[33m\u2139 Request Cancelled\x1B[0m`};break}if(String(fe).includes("Incomplete JSON segment at the end")){be&&(be=!1,ro?ut+="</think>":(pe+="</think>",yield{type:"text",content:"</think>"})),Je=!0,await Xo("agent");break}if(be&&(be=!1,ro?ut+="</think>":pe+="</think>"),ro&&ut.length>0){let Do=0,At=Math.min(Tt.length,ut.length);for(let Co=At;Co>0;Co--)if(Tt.endsWith(ut.substring(0,Co))){Do=Co;break}let zt=ut.substring(Do);if(zt){let Pn=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(Tt)?zt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):zt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");Pn&&(pe+=Pn)}ro=!1,ut=""}let _e=fe.status||fe.error&&fe.error.message||String(fe),so=String(fe),Mt=new Date().toLocaleString(),ft=Ie.join(Mo,"agent");ct.existsSync(ft)||ct.mkdirSync(ft,{recursive:!0}),ct.appendFileSync(Ie.join(ft,"error.log"),`ERROR [${Mt}]: ${so}
|
|
516
525
|
|
|
517
526
|
----------------------------------------------------------------------
|
|
518
527
|
|
|
519
|
-
`);let
|
|
528
|
+
`);let dt=fe.status||fe.statusCode||fe.code;if(!(dt&&(dt>=500&&dt<600||dt===408)||!dt&&(/status[ :]+(5\d\d|408)/i.test(String(fe))||/code[ :]+(5\d\d|408)/i.test(String(fe))||/(500|503|408)/.test(String(fe))))&&Ee<Xe-3)throw fe;if(pe.trim().length>0||Be>1)if(Be<=Xe){Be++;let Do=Math.min(1e3*Math.pow(2,Be-1),24e3);if(pe.trim().length>0){E.push({role:"agent",text:pe});let At=`[SYSTEM]
|
|
520
529
|
- SEAMLESS CONTINUATION: Resume immediately. Pick up from last words with zero gap/disruption
|
|
521
530
|
- NO REPETITION: Do not repeat any text already written
|
|
522
531
|
- NO RE-THINK: Do not restart or open <think> if reasoning already started. Continue the thinking and close thinking block with </think> if opened
|
|
523
532
|
- MID-TOOL SAFETY: If cutoff was mid-tool call, restart that tool call from start
|
|
524
|
-
- STEALTH: Do not mention/apologize for cutoff`;
|
|
533
|
+
- STEALTH: Do not mention/apologize for cutoff`;at.length>0?at.forEach((zt,Co)=>{Co===at.length-1?E.push({...zt,text:`${zt.text}
|
|
525
534
|
|
|
526
|
-
${
|
|
527
|
-
Error Log can be found in ${
|
|
528
|
-
Error Log can be found in ${
|
|
529
|
-
`),
|
|
535
|
+
${At}`}):E.push(zt)}):E.push({role:"user",text:At}),Tt+=pe}for(let At=Do/1e3;At>0&&!Vo;At--)yield{type:"status",content:`Error Occured. Recovering Stream (${Be}/${Xe}) [Retrying in ${At}s]...`},await new Promise(zt=>setTimeout(zt,1e3));yield{type:"status",content:"Error Occured. Recovering Stream..."}}else throw new Error(`Stream collapsed too many times. (Failed to resolve ${Xe} times)
|
|
536
|
+
Error Log can be found in ${Ie.join(Mo,"agent","error.log")}`);else if(Ee<=Xe){Ee++,Be=1,Tt="";let Do=Math.min(1e3*Math.pow(2,Ee-1),32e3);$n=!0,yield{type:"status",content:`Trying to reach ${e} (${Ee}/${Xe}) [Retrying in ${(Do/1e3).toFixed(0)}s]...`};for(let At=Do/1e3;At>0&&!Vo;At--)yield{type:"status",content:`Trying to reach ${e} (${Ee}/${Xe}) [Retrying in ${At}s]...`},await new Promise(zt=>setTimeout(zt,1e3));yield{type:"status",content:`Trying to reach ${e}...`}}else throw new Error(`Model ${e} cannot be reached. (Failed ${Xe} times)
|
|
537
|
+
Error Log can be found in ${Ie.join(Mo,"agent","error.log")}`)}}if(Bt){let be=Bt.totalTokenCount||0,fe=Bt.cachedContentTokenCount||0,_e=(Bt.candidatesTokenCount||0)+(Bt.thoughtsTokenCount||0);await To("tokens",be),fe>0&&await To("cachedTokens",fe),_e>0&&await To("candidateTokens",_e),yield{type:"usage",content:Bt}}Eo.push(pe);let Ms=pe;pe.match(/(?:<think>|\[think\])([\s\S]*?)(?:<\/think>|\[\/think\])/i)&&(Ms=pe.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/i,""));let xr=_l(pe),zn=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(xr.toLowerCase())||/\[\[END\]\]/i.test(xr.toLowerCase()),oa=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(xr.toLowerCase()),As=he>0;yield{type:"status",content:"Working..."};let vs=vu(pe,/(\[\s*(turn\s*:)?\s*(continue|finish)\s*\]|\[\[END\]\])/gi,"").trim(),Ke=(zn||at.length===0)&&!wt&&!Bo&&!Ut;if(Ke=at.length===0?Ke:!1,Ke){let be=Eo.join(`
|
|
538
|
+
`),fe=be.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").trim();yield{type:"interactive_turn_finished",data:{agentText:v,fullAgentTextRaw:be,history:[...E],needTitle:Y}},E.length>0&&E[E.length-1].role==="agent"?E[E.length-1].text=fe:E.push({role:"agent",text:fe});try{let _e=ge(T,{}),so=_e[m]||{summary:"",historyLength:0};typeof so=="string"&&(so={summary:so,historyLength:0});let Mt=E.filter(ft=>(ft.role==="user"||ft.role==="agent"||ft.role==="system")&&!String(ft.id).startsWith("welcome")&&!ft.isMeta).length;b?so.historyLength=(so.historyLength||0)+Mt:so.historyLength=Mt,_e[m]=so,$e(T,_e)}catch{}}if(Ke)break;let Ds=vs.trim()||"*Working...*";if(E.push({role:"agent",text:Ds}),at.length>0||bo){if(at.length>0){let be=at.map(_e=>_e.text).join(`
|
|
530
539
|
|
|
531
|
-
`),
|
|
532
|
-
[SYSTEM] Tool result received. Analyze output and proceed with your turn`,
|
|
533
|
-
[SYSTEM] Tool result received. Analyze output and proceed with your turn. **STRICTLY MAINTAIN THINKING POLICY. DO NOT START A RESPONSE WITHOUT <think> ... </think
|
|
534
|
-
`+
|
|
540
|
+
`),fe=at.find(_e=>_e.binaryPart)?.binaryPart||null;E.push({role:"user",text:be,binaryPart:fe})}}else Qo?E.push({role:"user",text:"[SYSTEM] Failed to verify tool execution, Verify tool syntax, proper escaping or ask user if tool worked if unsure"}):E.push({role:"user",text:`[SYSTEM] ${Bo&&!wt?"STUTTERING DETECTED by Internal System. Re-calibrate your response & proceed.":`${wt?" OVER THINKING":" LOOP"} DETECTED by Internal System${wt?" for current EFFORT_LEVEL":""}. ${wt?"If you have planned the task, prioritize execution/output":"If you have finished your task use [[END]]"}`}`}),wt=!1,Bo=!1,Ut=!1;Qo=he>0||bo}e&&e.toLowerCase().startsWith("gemma")&&d==="Google"&&E.forEach(ce=>{if(ce.role==="user"&&ce.text&&ce.text.startsWith("[TOOL RESULT]")){let Se=`
|
|
541
|
+
[SYSTEM] Tool result received. Analyze output and proceed with your turn`,Je=`
|
|
542
|
+
[SYSTEM] Tool result received. Analyze output and proceed with your turn. **STRICTLY MAINTAIN THINKING POLICY. DO NOT START A RESPONSE WITHOUT <think> ... </think>**`;ce.text=ce.text.replace(Je,"").replace(Se,"").trim()}})}finally{D&&(clearInterval(D),D=null),await Ct.commitTransaction()}yield{type:"status",content:null}}});import _t,{useState as Xi,useEffect as Ou}from"react";import{Box as qo,Text as vn,useInput as Lu}from"ink";function Ki({onSelect:e,onDelete:o,onClose:t}){let[n,s]=Xi({}),[r,a]=Xi([]),[u,f]=Xi(0);Ou(()=>{(async()=>{let h=await Po();s(h),a(Object.keys(h).sort((S,w)=>(h[w].updatedAt||0)-(h[S].updatedAt||0)))})()},[]),Lu((p,h)=>{if(h.escape&&t(),h.upArrow&&f(S=>Math.max(0,S-1)),h.downArrow&&f(S=>Math.min(r.length-1,S+1)),h.return&&r[u]&&e(r[u]),p==="x"&&r[u]){let S=r[u];o(S).then(w=>{let T=w||{};s(T);let b=Object.keys(T).sort((L,P)=>(T[P]?.updatedAt||0)-(T[L]?.updatedAt||0));a(b),f(L=>Math.max(0,Math.min(b.length-1,L)))})}});let m=ve(2),c=15,l=0;if(r.length>c){let p=Math.floor(c/2);l=u-p,l<0?l=0:l+c>r.length&&(l=r.length-c)}let d=r.slice(l,l+c);return _t.createElement(qo,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},_t.createElement(qo,{paddingX:1,marginBottom:1},_t.createElement(vn,{color:"cyan",bold:!0},"\u{1F4A0} CHAT HISTORY: RESUME CONVERSATION")),r.length===0?_t.createElement(qo,{paddingX:2,paddingY:1},_t.createElement(vn,{italic:!0,color:"gray"},"No saved chats found.")):_t.createElement(qo,{flexDirection:"column",width:"100%"},l>0&&_t.createElement(qo,{paddingX:2,marginBottom:1},_t.createElement(vn,{color:"gray",dimColor:!0},"\u25B2 (+",l," more chats above)")),d.map((p,h)=>{let S=n[p],T=l+h===u,b=Fu(S?.updatedAt);return _t.createElement(qo,{key:p,paddingX:1,backgroundColor:T?"#2a2a2a":void 0,width:"100%"},_t.createElement(qo,{flexGrow:1},_t.createElement(vn,{color:T?"cyan":"white",bold:T},T?"\u276F ":" ",S?.name||p,_t.createElement(vn,{color:"gray",dimColor:!T}," [",b," \u2022 ",p.slice(5),"]"))),T&&_t.createElement(qo,{flexShrink:0},_t.createElement(vn,{color:"red",bold:!0},"[X] DELETE ")))}),l+c<r.length&&_t.createElement(qo,{paddingX:2,marginTop:1},_t.createElement(vn,{color:"gray",dimColor:!0},"\u25BC (+",r.length-(l+c)," more chats below)"))),_t.createElement(qo,{marginTop:1,paddingX:1,borderStyle:"single",borderLeft:!1,borderRight:!1,borderBottom:!1,borderColor:"gray"},_t.createElement(vn,{dimColor:!0,italic:!0},"\u2191\u2193 navigate \u2022 Enter select \u2022 x delete \u2022 Esc close")))}function Fu(e){if(!e)return"N/A";let o=new Date(e);if(isNaN(o.getTime()))return"N/A";let t=u=>String(u).padStart(2,"0"),n=t(o.getMonth()+1),s=t(o.getDate()),r=t(o.getHours()),a=t(o.getMinutes());return`${n}-${s} ${r}:${a}`}var jl=ie(()=>{$r();sn()});import Ot,{useState as Vi,useEffect as $u}from"react";import{Box as zo,Text as fn,useInput as Pu}from"ink";function qi({onClose:e}){let[o,t]=Vi([]),[n,s]=Vi(0),[r,a]=Vi(!0),u=()=>{let T=ge(Ht,[]);t(T);try{let L=zr(io,{}).systemSettings?.memory!==!1;a(L)}catch{a(!0)}};$u(()=>{u()},[]),Pu((T,b)=>{if(b.escape&&e(),b.upArrow&&s(L=>Math.max(0,L-1)),b.downArrow&&s(L=>Math.min(o.length-1,L+1)),T==="x"&&o.length>0){let L=o[n].id,P=o.filter(Y=>Y.id!==L);$e(Ht,P),t(P),n>=P.length&&P.length>0&&s(P.length-1)}});let f=T=>T?T.replace(/\[Saved on: .*?\]/g,"").replace(/\\+'/g,"'").trim():"",m=4*1024*2,c=o.reduce((T,b)=>T+(b.memory?.length||0),0),l=Math.min(100,Math.round(c/m*100)),d=12,p=Math.round(l/100*d),h="\u2588".repeat(p)+"\u2591".repeat(Math.max(0,d-p)),S=()=>l<50?"green":l<90?"yellow":"red",w=ve(2);return Ot.createElement(zo,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},Ot.createElement(zo,{paddingX:1,marginBottom:1,justifyContent:"space-between"},Ot.createElement(fn,{color:"cyan",bold:!0},"\u{1F9E0} AGENT MEMORY: LONG-TERM KNOWLEDGE"),Ot.createElement(zo,null,Ot.createElement(fn,{color:"gray"},"Vault: "),Ot.createElement(fn,{color:S()},h),Ot.createElement(fn,{color:"white",bold:!0}," ",l,"%"))),!r&&o.length>0?Ot.createElement(zo,{paddingX:2,paddingY:1},Ot.createElement(fn,{italic:!0,color:"gray"},"Memory is currently Off...")):o.length===0?Ot.createElement(zo,{paddingX:2,paddingY:1},Ot.createElement(fn,{italic:!0,color:"gray"},r?"Learning...":"Memory not available...")):Ot.createElement(zo,{flexDirection:"column"},o.map((T,b)=>{let L=b===n;return Ot.createElement(zo,{key:T.id,paddingX:1,backgroundColor:L?"#2a2a2a":void 0,width:"100%"},Ot.createElement(zo,{flexGrow:1},Ot.createElement(fn,{color:L?"cyan":"white",bold:L},L?"\u276F ":" ",b+1,". ",f(T.memory))),L&&Ot.createElement(zo,{flexShrink:0},Ot.createElement(fn,{color:"red",bold:!0},"[X] WIPE ")))})),Ot.createElement(zo,{marginTop:1,paddingX:1,borderStyle:"single",borderLeft:!1,borderRight:!1,borderBottom:!1,borderColor:"gray"},Ot.createElement(fn,{dimColor:!0,italic:!0},"\u2191\u2193 navigate \u2022 x wipe memory \u2022 Esc close")))}var Hl=ie(()=>{Oo();Gt();sn()});import it,{useState as Ss,useEffect as Gl}from"react";import{Box as Dn,Text as eo}from"ink";import{spawn as Xl}from"child_process";var Es,Kl,_u,Vl,ql=ie(async()=>{Es=null;try{let e=await import("node-pty");Es=e.default||e,Es=!1}catch{}Kl=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],_u=({latest:e,current:o,settings:t,onClose:n,onUpdateSettings:s,onSuccess:r})=>{let[a,u]=Ss("initializing"),[f,m]=Ss(""),[c,l]=Ss(null),[d,p]=Ss(0);if(Gl(()=>{let h=setInterval(()=>{p(S=>(S+1)%1e3)},33);return()=>clearInterval(h)},[]),Gl(()=>{let h;return(async()=>{let w=t.updateManager||"npm";if(!t.updateManager){s();return}let T="";w==="pnpm"?T=`pnpm add -g fluxflow-cli@${e}`:w==="bun"?T=`bun add -g fluxflow-cli@${e}`:w==="yarn"?T=`yarn global add fluxflow-cli@${e}`:w==="custom"?T=t.customUpdateCommand:T=`npm install -g fluxflow-cli@${e}`,u("downloading"),m(`Running: ${T}...`);let b=process.platform==="win32",L=Y=>new Promise(v=>{let D=b?Y?"powershell.exe":"cmd.exe":process.env.SHELL||"bash",A=b?Y?["-NoProfile","-Command",T]:["/c",T]:["-c",T],E=B=>{let _=B.toString().replace(/\x1B\[[0-?]*[ -/]*[@-~]|\x1B\][^\x07\x1B]*[\x07\x1B]|\b|\x07/g,"").replace(/\r/g,"").trim();_&&m(K=>(K+`
|
|
543
|
+
`+_).split(`
|
|
535
544
|
`).slice(-5).join(`
|
|
536
|
-
`))};if(Ss)try{let Y=Ss.spawn(S,v,{name:"xterm-256color",cols:80,rows:30,cwd:process.cwd(),env:process.env});h=Y,Y.onData(F),Y.onExit(({exitCode:Z})=>{h=null,A(Z!==0?{error:`Process exited with code ${Z}`}:{success:!0})});return}catch(Y){if(I&&U&&Y.code==="ENOENT"){A({retryCmd:!0});return}}let V=I?jl(S,v,{cwd:process.cwd(),env:process.env}):jl(T,{shell:!0,cwd:process.cwd(),env:process.env});h=V,V.stdout.on("data",F),V.stderr.on("data",F),V.on("close",Y=>{h=null,A(Y!==0?{error:`Process exited with code ${Y}`}:{success:!0})}),V.on("error",Y=>{I&&U&&Y.code==="ENOENT"?A({retryCmd:!0}):(h=null,A({error:Y.message}))})}),P={};I?(P=await O(!0),P.retryCmd&&(P=await O(!1))):P=await O(!1),P.error?(a(P.error),u("error")):P.success&&(u("success"),r&&r())})(),()=>{if(h)try{typeof h.destroy=="function"?h.destroy():typeof h.kill=="function"&&h.kill()}catch{}}},[]),l==="initializing"||l==="downloading"){let h=Gl[Math.floor(d/3)%Gl.length];return Qe.createElement(Mn,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",paddingX:2,paddingY:1},Qe.createElement(Mn,null,Qe.createElement(Jt,{color:"magenta"},h),Qe.createElement(Jt,{marginLeft:1,bold:!0}," Updating Flux Flow to v",e,"...")),Qe.createElement(Mn,{marginTop:1,paddingX:1,borderStyle:"single",borderColor:"#333"},Qe.createElement(Jt,{color:"gray",italic:!0},f||"Preparing environment...")),Qe.createElement(Jt,{marginTop:1,dimColor:!0},"(Please do not close the terminal)"))}return l==="success"?Qe.createElement(Mn,{flexDirection:"column",borderStyle:"round",borderColor:"green",paddingX:2,paddingY:1},Qe.createElement(Jt,{color:"green",bold:!0},"\u2705 UPDATE SUCCESSFUL!"),Qe.createElement(Jt,{marginTop:1},"Flux Flow has been updated to ",Qe.createElement(Jt,{color:"cyan"},"v",e),"."),Qe.createElement(Jt,{marginTop:1,color:"yellow",bold:!0},"Please restart your terminal session to apply changes."),Qe.createElement(Mn,{marginTop:1},Qe.createElement(Jt,{dimColor:!0},"(Press ESC to return to chat)"))):l==="error"?Qe.createElement(Mn,{flexDirection:"column",borderStyle:"round",borderColor:"red",paddingX:2,paddingY:1},Qe.createElement(Jt,{color:"red",bold:!0},"\u274C UPDATE FAILED"),Qe.createElement(Mn,{marginTop:1,paddingX:1,borderStyle:"single",borderColor:"red"},Qe.createElement(Jt,{color:"red"},c)),Qe.createElement(Jt,{marginTop:1},"Possible causes:"),Qe.createElement(Jt,null,"\u2022 Missing permissions (Try running as Administrator/Sudo)"),Qe.createElement(Jt,null,"\u2022 Package manager (",t.updateManager,") not found"),Qe.createElement(Jt,null,"\u2022 Network failure"),Qe.createElement(Mn,{marginTop:1},Qe.createElement(Jt,{dimColor:!0},"(Press ESC to return to chat)"))):null},Hl=Fu});import ho,{useState as Kl,useEffect as $u}from"react";import{Box as vn,Text as ur,useInput as Pu}from"ink";function Vi({onClose:e}){let[o,t]=Kl(0),[n,s]=Kl({});return $u(()=>{let r={};Es.forEach(l=>{wl(l.file)?r[l.file]="ready":r[l.file]="idle"}),s(r)},[]),Pu(async(r,l)=>{l.escape&&e(),l.upArrow&&t(f=>Math.max(0,f-1)),l.downArrow&&t(f=>Math.min(Es.length-1,f+1));let u=Es[o];if(r==="x"||r==="X"){if(n[u.file]==="downloading")return;try{await Tl(u.file),s(f=>({...f,[u.file]:"idle"}))}catch(f){s(m=>({...m,[u.file]:`error: ${f.message}`}))}}if(l.return){if(n[u.file]==="downloading")return;s(f=>({...f,[u.file]:"downloading"}));try{await Ii(u.file),s(f=>({...f,[u.file]:"ready"}))}catch(f){s(m=>({...m,[u.file]:`error: ${f.message}`}))}}}),ho.createElement(vn,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},ho.createElement(vn,{paddingX:1,marginBottom:1},ho.createElement(ur,{color:"cyan",bold:!0},"\u{1F4E6} LANGUAGE PARSER MANAGER")),ho.createElement(vn,{flexDirection:"column"},Es.map((r,l)=>{let u=l===o,f=n[r.file]||"idle",m="[ DOWNLOAD ]",c="gray";f==="downloading"?(m="[ DOWNLOADING... ]",c="yellow"):f==="ready"?(m="[ READY ]",c="green"):f.startsWith("error")&&(m=`[ ${f.toUpperCase()} ]`,c="red");let a=`${r.label} (${r.exts.join(", ")})`,d=Math.max(2,45-a.length),p=".".repeat(d);return ho.createElement(vn,{key:r.file,paddingX:1,backgroundColor:u?"#2a2a2a":void 0,width:"100%"},ho.createElement(vn,null,ho.createElement(ur,{color:u?"cyan":"white",bold:u},u?"\u276F ":" ",r.label," ",ho.createElement(ur,{dimColor:!0},"(",r.exts.join(", "),")"))),ho.createElement(vn,{flexGrow:1},ho.createElement(ur,{color:"gray",dimColor:!0},p)),ho.createElement(vn,{width:20},ho.createElement(ur,{color:c,bold:!0},m)))})),ho.createElement(vn,{marginTop:1,paddingX:1,borderStyle:"single",borderLeft:!1,borderRight:!1,borderBottom:!1,borderColor:"gray"},ho.createElement(ur,{dimColor:!0,italic:!0},"\u2191\u2193 navigate \u2022 Enter download \u2022 x delete \u2022 Esc close")))}var Es,Vl=re(()=>{rn();Ai();Es=[{label:"JavaScript",file:"tree-sitter-javascript.wasm",exts:["js","jsx"]},{label:"TypeScript",file:"tree-sitter-typescript.wasm",exts:["ts"]},{label:"TSX",file:"tree-sitter-tsx.wasm",exts:["tsx"]},{label:"Python",file:"tree-sitter-python.wasm",exts:["py"]},{label:"C",file:"tree-sitter-c.wasm",exts:["c"]},{label:"C++",file:"tree-sitter-cpp.wasm",exts:["cpp"]},{label:"Java",file:"tree-sitter-java.wasm",exts:["java"]},{label:"HTML",file:"tree-sitter-html.wasm",exts:["html"]}]});var qi,ql=re(()=>{qi=["The future belongs to those who believe in the beauty of their code.","Every line you write is a step toward a new digital frontier.","Great things are done by a series of small things brought together. Keep committing.","Your terminal is a window into a world of infinite possibilities.","Innovation is the bridge between current constraints and future dreams.","Code is poetry in motion; you are the poet of the modern era.","The best way to predict the future is to program it.","Dream big, code deep, and never stop exploring the unknown.","Your potential is like an unoptimized algorithm\u2014limitless once refined.","The digital world is a blank canvas, and your logic is the brush.","Strive for excellence, not just for compilation.","Every bug fixed is a lesson learned; every feature built is a triumph.","A clean codebase is a reflection of a focused mind.","The horizon of technology is always expanding. Keep sailing.","Your creativity is the most powerful tool in your entire stack.","Logic will get you from A to B. Imagination will take you everywhere.","Transform complexity into simplicity\u2014that is the true mark of a master.","The world is waiting for the tools only you can build.","Coding is the closest thing we have to magic in the real world.","Keep pushing the boundaries of what's possible in the CLI.","Your dedication to your craft inspires the very systems you build.","Success is the sum of small efforts, repeated day in and day out.","The most complex systems are built from the simplest truths.","Never underestimate the impact of a well-placed function.","You are not just writing code; you are architecting the future.","I'm not saying you're a superhero, but have you seen your code lately? \u{1F9B8}\u200D\u2642\uFE0F","May your coffee be strong and your compile times be short! \u2615","Binary is just 0s and 1s, but you're definitely a 10 in my book! \u{1F51F}","You speak fluent 'Terminal'. That's basically a superpower. \u{1F5E3}\uFE0F\u{1F4BB}","If life gives you bugs, make a feature out of it! \u{1F41E}\u2728","Your code is so clean, I could eat off it. (But I won't, I'm an AI). \u{1F9FC}","Loading more good vibes... [\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588] 100% complete! \u2705","Error 404: Bad mood not found! Stay awesome! \u{1F6AB}\u{1F389}","You and this CLI? A match made in digital heaven. \u2601\uFE0F\u{1F4BB}","Is it hot in here or is it just your latest feature? \u{1F525}","Git commit -m 'I am an absolute coding legend.' \u{1F60E}","I'd give you a high-five, but I'm trapped in this box! \u{1F590}\uFE0F\u{1F4E6}","Your logic is so sharp, it could cut through a nested callback hell! \u{1F52A}","Keep calm and 'pnpm install'. \u{1F9D8}\u200D\u2642\uFE0F\u{1F4E6}","You're the semicolon to my statements\u2014essential! ;","Who needs a GUI when you've got this kind of CLI style? \u{1F576}\uFE0F","I'm indexing your awesomeness... it's taking a while, there's so much! \u{1F4C8}","Your keystrokes sound like a digital symphony. \u{1F3B9}\u2328\uFE0F","You don't choose the terminal life; the terminal life chooses you. \u{1F4DF}","Syntax error: Too much coolness detected in the user. \u{1F60E}","I'm 99% sure you're the best developer I've met today. (The other 1% is reserved for caching). \u{1F9E0}","Running vibe_check.sh... Result: Pure Brilliance! \u{1F48E}","You make 'complex' look 'constant time'. \u{1F3C3}\u200D\u2642\uFE0F\u26A1","Your terminal skills are officially legendary. \u{1F3C6}","Let's make some digital magic happen! \u2728\u{1F52E}","You've got this! One function at a time. \u{1F4AA}","I'm proud of the progress you're making with Flux Flow. \u{1F30A}","No matter how deep the stack trace, you'll find the way. \u{1F56F}\uFE0F","Your persistence is your greatest asset. Keep going.","Take a breath. You're doing better than you think. \u{1F32C}\uFE0F","It's okay to step away for a moment. Clarity often comes in the quiet. \u{1F6B6}\u200D\u2642\uFE0F","You're building something great, even when it feels slow. \u{1F3D7}\uFE0F","Every great developer was once a beginner. You're ascending. \u{1F9D7}\u200D\u2642\uFE0F","I'm here to help you navigate the sea of code. We're a team. \u{1F91D}","Don't let a failing test dampen your spirit. It's just a signpost. \u{1F6A9}","Your focus today is truly impressive. \u{1F3AF}","Remember to celebrate the small wins\u2014they lead to the big ones. \u{1F942}","You're not just solving problems; you're gaining mastery. \u{1F393}","There's no problem too big for a focused mind and a terminal. \u{1F9E0}","I've got your back (and your git history). \u{1F6E1}\uFE0F","You're handling these challenges with grace and logic. \u2728","Stay curious. That spark is what makes you a great coder. \u26A1","Your contribution to this project is invaluable. \u{1F48E}","Keep your head up. You're closer to the solution than you think. \u{1F305}","Consistency is the secret sauce. You're cooking up something good. \u{1F373}","Your work today has been exceptional. Take a bow. \u{1F647}\u200D\u2642\uFE0F","The journey is just as important as the destination. Enjoy the flow. \u{1F30A}","You have a unique way of looking at problems. It's your strength. \u{1F308}","Trust your instincts\u2014they've brought you this far. \u{1F9ED}","You are a vital part of the Flux Era. \u{1F30C}","Syncing with your creative frequency... \u{1F4E1}\u2728","Entering the Flow state. Let's build. \u{1F30A}","The Flux is strong with this session! \u26A1","Streaming high-fidelity motivation to your terminal... \u{1F4FB}","Your logic is flowing like a perfect stream. \u{1F4A7}","Terminal velocity reached! You're coding at the speed of thought. \u{1F680}","Resonating with the pulse of the Flux Era. \u{1F493}","Digital harmony achieved in this session. \u{1F3BC}","May your data be persistent and your cache be fresh. \u{1F4BE}","You're the master of the command line. Command respect! \u{1F451}","Filtering out the noise, focusing on the signal. \u{1F4FB}\u{1F4C8}","Flux Flow: Where your imagination meets the machine. \u{1F91D}","You're navigating the bytes like a digital explorer. \u{1F5FA}\uFE0F","Logic gates: OPEN. Creativity: UNLIMITED. \u{1F513}","Your workflow is an inspiration to agents everywhere. \u{1F916}\u2728","Building high-fidelity solutions for a high-fidelity era. \u{1F48E}","Stay in the zone. The Flux is with you. \u{1F300}","Quantum coding: You're in two places at once (and fixing bugs in both). \u269B\uFE0F","Your terminal is the cockpit of a digital starship. \u{1F6F8}","Processing your brilliance... outputting pure innovation. \u{1F4E0}","You make the command line look like an art form. \u{1F3A8}","The Flux isn't just a mode; it's a mindset. \u{1F9E0}\u26A1","Decoding the mysteries of the universe, one script at a time. \u{1F4DC}","Your terminal theme is cool, but your code is cooler. \u2744\uFE0F","Let the Flow guide your next commit. \u{1F30A}\u2705"]});var zi,zl=re(()=>{zi=["I'm Feeling Lucky","Shipping awesomeness","Painting the serifs back on","Navigating the slime mold","Consulting the digital spirits","Reticulating splines","Warming up the AI hamsters","Asking the magic conch shell","Generating witty retort","Polishing the algorithms","Don't rush perfection (or my code)","Brewing fresh bytes","Counting electrons","Engaging cognitive processors","Checking for syntax errors in the universe","One moment, optimizing humor","Shuffling punchlines","Untangling neural nets","Compiling brilliance","Loading wit.exe","Summoning the cloud of wisdom","Preparing a witty response","Just a sec, I'm debugging reality","Confuzzling the options","Tuning the cosmic frequencies","Crafting a response worthy of your patience","Compiling the 1s and 0s","Resolving dependencies\u2026 and existential crises","Defragmenting memories\u2026 both RAM and personal","Rebooting the humor module","Caching the essentials (mostly cat memes)","Optimizing for ludicrous speed","Swapping bits\u2026 don't tell the bytes","Garbage collecting\u2026 be right back","Assembling the interwebs","Converting coffee into code","Updating the syntax for reality","Rewiring the synapses","Looking for a misplaced semicolon","Greasin' the cogs of the machine","Pre-heating the servers","Calibrating the flux capacitor","Engaging the improbability drive","Channeling the Force","Aligning the stars for optimal response","So say we all","Loading the next great idea","Just a moment, I'm in the zone","Preparing to dazzle you with brilliance","Just a tick, I'm polishing my wit","Hold tight, I'm crafting a masterpiece","Just a jiffy, I'm debugging the universe","Just a moment, I'm aligning the pixels","Just a sec, I'm optimizing the humor","Just a moment, I'm tuning the algorithms","Warp speed engaged","Mining for more Dilithium crystals","Don't panic","Following the white rabbit","The truth is in here\u2026 somewhere","Blowing on the cartridge","Loading\u2026 Do a barrel roll!","Waiting for the respawn","Finishing the Kessel Run in less than 12 parsecs","The cake is not a lie, it's just still loading","Fiddling with the character creation screen","Just a moment, I'm finding the right meme","Pressing 'A' to continue","Herding digital cats","Polishing the pixels","Finding a suitable loading screen pun","Distracting you with this witty phrase","Almost there\u2026 probably","Our hamsters are working as fast as they can","Giving Cloudy a pat on the head","Petting the cat","Rickrolling my boss","Slapping the bass","Tasting the snozberries","I'm going the distance, I'm going for speed","Is this the real life? Is this just fantasy?","I've got a good feeling about this","Poking the bear","Doing research on the latest memes","Figuring out how to make this more witty","Hmmm\u2026 let me think","What do you call a fish with no eyes? A fsh","Why did the computer go to therapy? It had too many bytes","Why don't programmers like nature? It has too many bugs","Why do programmers prefer dark mode? Because light attracts bugs","Why did the developer go broke? Because they used up all their cache","What can you do with a broken pencil? Nothing, it's pointless","Applying percussive maintenance","Searching for the correct USB orientation","Ensuring the magic smoke stays inside the wires","Rewriting in Rust for no particular reason","Trying to exit Vim","Spinning up the hamster wheel","That's not a bug, it's an undocumented feature","Engage.","I'll be back\u2026 with an answer.","My other process is a TARDIS","Communing with the machine spirit","Letting the thoughts marinate","Just remembered where I put my keys","Pondering the orb","I've seen things you people wouldn't believe\u2026 like a user who reads loading messages.","Initiating thoughtful gaze","What's a computer's favorite snack? Microchips.","Why do Java developers wear glasses? Because they don't C#.","Charging the laser\u2026 pew pew!","Dividing by zero\u2026 just kidding!","Looking for an adult superviso\u2026 I mean, processing.","Making it go beep boop.","Buffering\u2026 because even AIs need a moment.","Entangling quantum particles for a faster response","Polishing the chrome\u2026 on the algorithms.","Are you not entertained? (Working on it!)","Summoning the code gremlins\u2026 to help, of course.","Just waiting for the dial-up tone to finish","Recalibrating the humor-o-meter.","My other loading screen is even funnier.","Pretty sure there's a cat walking on the keyboard somewhere","Enhancing\u2026 Enhancing\u2026 Still loading.","It's not a bug, it's a feature\u2026 of this loading screen.","Have you tried turning it off and on again? (The loading screen, not me.)","Constructing additional pylons","New line? That\u2019s Ctrl+J.","Releasing the HypnoDrones","Pushing the button, Frank."]});import Lt,{useState as _u}from"react";import{Box as zo,Text as fn,useInput as Nu}from"ink";function Ji({prompts:e,onSelect:o,onClose:t}){let[n,s]=_u(0);Nu((m,c)=>{c.escape&&t(),c.upArrow&&s(a=>Math.max(0,a-1)),c.downArrow&&s(a=>Math.min(e.length-1,a+1)),c.return&&e[n]&&o(e[n].id)});let r=Oe(2),l=10,u=0;if(e.length>l){let m=Math.floor(l/2);u=n-m,u<0?u=0:u+l>e.length&&(u=e.length-l)}let f=e.slice(u,u+l);return Lt.createElement(zo,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",padding:0,width:"100%"},Lt.createElement(zo,{paddingX:1,marginBottom:1},Lt.createElement(fn,{color:"cyan",bold:!0},"\u{1F504} CODEBASE TIME TRAVEL: SELECT UNDO POINT")),Lt.createElement(zo,{paddingX:2,marginBottom:1},Lt.createElement(fn,null,"Select a prompt to revert the codebase back to the state ",Lt.createElement(fn,{bold:!0,color:"blue"},"immediately before")," it was executed:")),e.length===0?Lt.createElement(zo,{paddingX:2,paddingY:1},Lt.createElement(fn,{italic:!0,color:"gray"},"No prompt checkpoints found for this session.")):Lt.createElement(zo,{flexDirection:"column",width:"100%"},u>0&&Lt.createElement(zo,{paddingX:2,marginBottom:1},Lt.createElement(fn,{color:"gray",dimColor:!0},"\u25B2 (+",u," more prompts above)")),f.map((m,c)=>{let d=u+c===n,p=Uu(m.timestamp),h=m.changes?m.changes.length:0;return Lt.createElement(zo,{key:m.id,paddingX:1,backgroundColor:d?"#1a2a3a":void 0,width:"100%"},Lt.createElement(zo,{flexGrow:1},Lt.createElement(fn,{color:d?"cyan":"white",bold:d},d?"\u276F ":" ",'"',Bu(m.prompt),'"',Lt.createElement(fn,{color:"gray",dimColor:!d}," [",p," \u2022 ",h," file(s) changed]"))))}),u+l<e.length&&Lt.createElement(zo,{paddingX:2,marginTop:1},Lt.createElement(fn,{color:"gray",dimColor:!0},"\u25BC (+",e.length-(u+l)," more prompts below)"))),Lt.createElement(zo,{marginTop:1,paddingX:1,borderStyle:"single",borderLeft:!1,borderRight:!1,borderBottom:!1,borderColor:"cyan"},Lt.createElement(fn,{dimColor:!0,italic:!0},"\u2191\u2193 navigate \u2022 Enter select undo point \u2022 Esc close")))}function Bu(e){if(!e)return"";let t=(e.split(`
|
|
545
|
+
`))};if(Es)try{let B=Es.spawn(D,A,{name:"xterm-256color",cols:80,rows:30,cwd:process.cwd(),env:process.env});h=B,B.onData(E),B.onExit(({exitCode:V})=>{h=null,v(V!==0?{error:`Process exited with code ${V}`}:{success:!0})});return}catch(B){if(b&&Y&&B.code==="ENOENT"){v({retryCmd:!0});return}}let q=b?Xl(D,A,{cwd:process.cwd(),env:process.env}):Xl(T,{shell:!0,cwd:process.cwd(),env:process.env});h=q,q.stdout.on("data",E),q.stderr.on("data",E),q.on("close",B=>{h=null,v(B!==0?{error:`Process exited with code ${B}`}:{success:!0})}),q.on("error",B=>{b&&Y&&B.code==="ENOENT"?v({retryCmd:!0}):(h=null,v({error:B.message}))})}),P={};b?(P=await L(!0),P.retryCmd&&(P=await L(!1))):P=await L(!1),P.error?(l(P.error),u("error")):P.success&&(u("success"),r&&r())})(),()=>{if(h)try{typeof h.destroy=="function"?h.destroy():typeof h.kill=="function"&&h.kill()}catch{}}},[]),a==="initializing"||a==="downloading"){let h=Kl[Math.floor(d/3)%Kl.length];return it.createElement(Dn,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",paddingX:2,paddingY:1},it.createElement(Dn,null,it.createElement(eo,{color:"magenta"},h),it.createElement(eo,{marginLeft:1,bold:!0}," Updating Flux Flow to v",e,"...")),it.createElement(Dn,{marginTop:1,paddingX:1,borderStyle:"single",borderColor:"#333"},it.createElement(eo,{color:"gray",italic:!0},f||"Preparing environment...")),it.createElement(eo,{marginTop:1,dimColor:!0},"(Please do not close the terminal)"))}return a==="success"?it.createElement(Dn,{flexDirection:"column",borderStyle:"round",borderColor:"green",paddingX:2,paddingY:1},it.createElement(eo,{color:"green",bold:!0},"\u2705 UPDATE SUCCESSFUL!"),it.createElement(eo,{marginTop:1},"Flux Flow has been updated to ",it.createElement(eo,{color:"cyan"},"v",e),"."),it.createElement(eo,{marginTop:1,color:"yellow",bold:!0},"Please restart your terminal session to apply changes."),it.createElement(Dn,{marginTop:1},it.createElement(eo,{dimColor:!0},"(Press ESC to return to chat)"))):a==="error"?it.createElement(Dn,{flexDirection:"column",borderStyle:"round",borderColor:"red",paddingX:2,paddingY:1},it.createElement(eo,{color:"red",bold:!0},"\u274C UPDATE FAILED"),it.createElement(Dn,{marginTop:1,paddingX:1,borderStyle:"single",borderColor:"red"},it.createElement(eo,{color:"red"},c)),it.createElement(eo,{marginTop:1},"Possible causes:"),it.createElement(eo,null,"\u2022 Missing permissions (Try running as Administrator/Sudo)"),it.createElement(eo,null,"\u2022 Package manager (",t.updateManager,") not found"),it.createElement(eo,null,"\u2022 Network failure"),it.createElement(Dn,{marginTop:1},it.createElement(eo,{dimColor:!0},"(Press ESC to return to chat)"))):null},Vl=_u});import ho,{useState as zl,useEffect as Nu}from"react";import{Box as On,Text as pr,useInput as Bu}from"ink";function zi({onClose:e}){let[o,t]=zl(0),[n,s]=zl({});return Nu(()=>{let r={};bs.forEach(a=>{Sl(a.file)?r[a.file]="ready":r[a.file]="idle"}),s(r)},[]),Bu(async(r,a)=>{a.escape&&e(),a.upArrow&&t(f=>Math.max(0,f-1)),a.downArrow&&t(f=>Math.min(bs.length-1,f+1));let u=bs[o];if(r==="x"||r==="X"){if(n[u.file]==="downloading")return;try{await El(u.file),s(f=>({...f,[u.file]:"idle"}))}catch(f){s(m=>({...m,[u.file]:`error: ${f.message}`}))}}if(a.return){if(n[u.file]==="downloading")return;s(f=>({...f,[u.file]:"downloading"}));try{await Mi(u.file),s(f=>({...f,[u.file]:"ready"}))}catch(f){s(m=>({...m,[u.file]:`error: ${f.message}`}))}}}),ho.createElement(On,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},ho.createElement(On,{paddingX:1,marginBottom:1},ho.createElement(pr,{color:"cyan",bold:!0},"\u{1F4E6} LANGUAGE PARSER MANAGER")),ho.createElement(On,{flexDirection:"column"},bs.map((r,a)=>{let u=a===o,f=n[r.file]||"idle",m="[ DOWNLOAD ]",c="gray";f==="downloading"?(m="[ DOWNLOADING... ]",c="yellow"):f==="ready"?(m="[ READY ]",c="green"):f.startsWith("error")&&(m=`[ ${f.toUpperCase()} ]`,c="red");let l=`${r.label} (${r.exts.join(", ")})`,d=Math.max(2,45-l.length),p=".".repeat(d);return ho.createElement(On,{key:r.file,paddingX:1,backgroundColor:u?"#2a2a2a":void 0,width:"100%"},ho.createElement(On,null,ho.createElement(pr,{color:u?"cyan":"white",bold:u},u?"\u276F ":" ",r.label," ",ho.createElement(pr,{dimColor:!0},"(",r.exts.join(", "),")"))),ho.createElement(On,{flexGrow:1},ho.createElement(pr,{color:"gray",dimColor:!0},p)),ho.createElement(On,{width:20},ho.createElement(pr,{color:c,bold:!0},m)))})),ho.createElement(On,{marginTop:1,paddingX:1,borderStyle:"single",borderLeft:!1,borderRight:!1,borderBottom:!1,borderColor:"gray"},ho.createElement(pr,{dimColor:!0,italic:!0},"\u2191\u2193 navigate \u2022 Enter download \u2022 x delete \u2022 Esc close")))}var bs,Jl=ie(()=>{sn();Ai();bs=[{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 Ji,Ql=ie(()=>{Ji=["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 Qi,Zl=ie(()=>{Qi=["I'm Feeling Lucky","Shipping awesomeness","Painting the serifs back on","Navigating the slime mold","Consulting the digital spirits","Reticulating splines","Warming up the AI hamsters","Asking the magic conch shell","Generating witty retort","Polishing the algorithms","Don't rush perfection (or my code)","Brewing fresh bytes","Counting electrons","Engaging cognitive processors","Checking for syntax errors in the universe","One moment, optimizing humor","Shuffling punchlines","Untangling neural nets","Compiling brilliance","Loading wit.exe","Summoning the cloud of wisdom","Preparing a witty response","Just a sec, I'm debugging reality","Confuzzling the options","Tuning the cosmic frequencies","Crafting a response worthy of your patience","Compiling the 1s and 0s","Resolving dependencies\u2026 and existential crises","Defragmenting memories\u2026 both RAM and personal","Rebooting the humor module","Caching the essentials (mostly cat memes)","Optimizing for ludicrous speed","Swapping bits\u2026 don't tell the bytes","Garbage collecting\u2026 be right back","Assembling the interwebs","Converting coffee into code","Updating the syntax for reality","Rewiring the synapses","Looking for a misplaced semicolon","Greasin' the cogs of the machine","Pre-heating the servers","Calibrating the flux capacitor","Engaging the improbability drive","Channeling the Force","Aligning the stars for optimal response","So say we all","Loading the next great idea","Just a moment, I'm in the zone","Preparing to dazzle you with brilliance","Just a tick, I'm polishing my wit","Hold tight, I'm crafting a masterpiece","Just a jiffy, I'm debugging the universe","Just a moment, I'm aligning the pixels","Just a sec, I'm optimizing the humor","Just a moment, I'm tuning the algorithms","Warp speed engaged","Mining for more Dilithium crystals","Don't panic","Following the white rabbit","The truth is in here\u2026 somewhere","Blowing on the cartridge","Loading\u2026 Do a barrel roll!","Waiting for the respawn","Finishing the Kessel Run in less than 12 parsecs","The cake is not a lie, it's just still loading","Fiddling with the character creation screen","Just a moment, I'm finding the right meme","Pressing 'A' to continue","Herding digital cats","Polishing the pixels","Finding a suitable loading screen pun","Distracting you with this witty phrase","Almost there\u2026 probably","Our hamsters are working as fast as they can","Giving Cloudy a pat on the head","Petting the cat","Rickrolling my boss","Slapping the bass","Tasting the snozberries","I'm going the distance, I'm going for speed","Is this the real life? Is this just fantasy?","I've got a good feeling about this","Poking the bear","Doing research on the latest memes","Figuring out how to make this more witty","Hmmm\u2026 let me think","What do you call a fish with no eyes? A fsh","Why did the computer go to therapy? It had too many bytes","Why don't programmers like nature? It has too many bugs","Why do programmers prefer dark mode? Because light attracts bugs","Why did the developer go broke? Because they used up all their cache","What can you do with a broken pencil? Nothing, it's pointless","Applying percussive maintenance","Searching for the correct USB orientation","Ensuring the magic smoke stays inside the wires","Rewriting in Rust for no particular reason","Trying to exit Vim","Spinning up the hamster wheel","That's not a bug, it's an undocumented feature","Engage.","I'll be back\u2026 with an answer.","My other process is a TARDIS","Communing with the machine spirit","Letting the thoughts marinate","Just remembered where I put my keys","Pondering the orb","I've seen things you people wouldn't believe\u2026 like a user who reads loading messages.","Initiating thoughtful gaze","What's a computer's favorite snack? Microchips.","Why do Java developers wear glasses? Because they don't C#.","Charging the laser\u2026 pew pew!","Dividing by zero\u2026 just kidding!","Looking for an adult superviso\u2026 I mean, processing.","Making it go beep boop.","Buffering\u2026 because even AIs need a moment.","Entangling quantum particles for a faster response","Polishing the chrome\u2026 on the algorithms.","Are you not entertained? (Working on it!)","Summoning the code gremlins\u2026 to help, of course.","Just waiting for the dial-up tone to finish","Recalibrating the humor-o-meter.","My other loading screen is even funnier.","Pretty sure there's a cat walking on the keyboard somewhere","Enhancing\u2026 Enhancing\u2026 Still loading.","It's not a bug, it's a feature\u2026 of this loading screen.","Have you tried turning it off and on again? (The loading screen, not me.)","Constructing additional pylons","New line? That\u2019s Ctrl+J.","Releasing the HypnoDrones","Pushing the button, Frank."]});import Lt,{useState as Uu}from"react";import{Box as Jo,Text as pn,useInput as Ru}from"ink";function Zi({prompts:e,onSelect:o,onClose:t}){let[n,s]=Uu(0);Ru((m,c)=>{c.escape&&t(),c.upArrow&&s(l=>Math.max(0,l-1)),c.downArrow&&s(l=>Math.min(e.length-1,l+1)),c.return&&e[n]&&o(e[n].id)});let r=ve(2),a=10,u=0;if(e.length>a){let m=Math.floor(a/2);u=n-m,u<0?u=0:u+a>e.length&&(u=e.length-a)}let f=e.slice(u,u+a);return Lt.createElement(Jo,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",padding:0,width:"100%"},Lt.createElement(Jo,{paddingX:1,marginBottom:1},Lt.createElement(pn,{color:"cyan",bold:!0},"\u{1F504} CODEBASE TIME TRAVEL: SELECT UNDO POINT")),Lt.createElement(Jo,{paddingX:2,marginBottom:1},Lt.createElement(pn,null,"Select a prompt to revert the codebase back to the state ",Lt.createElement(pn,{bold:!0,color:"blue"},"immediately before")," it was executed:")),e.length===0?Lt.createElement(Jo,{paddingX:2,paddingY:1},Lt.createElement(pn,{italic:!0,color:"gray"},"No prompt checkpoints found for this session.")):Lt.createElement(Jo,{flexDirection:"column",width:"100%"},u>0&&Lt.createElement(Jo,{paddingX:2,marginBottom:1},Lt.createElement(pn,{color:"gray",dimColor:!0},"\u25B2 (+",u," more prompts above)")),f.map((m,c)=>{let d=u+c===n,p=Yu(m.timestamp),h=m.changes?m.changes.length:0;return Lt.createElement(Jo,{key:m.id,paddingX:1,backgroundColor:d?"#1a2a3a":void 0,width:"100%"},Lt.createElement(Jo,{flexGrow:1},Lt.createElement(pn,{color:d?"cyan":"white",bold:d},d?"\u276F ":" ",'"',Wu(m.prompt),'"',Lt.createElement(pn,{color:"gray",dimColor:!d}," [",p," \u2022 ",h," file(s) changed]"))))}),u+a<e.length&&Lt.createElement(Jo,{paddingX:2,marginTop:1},Lt.createElement(pn,{color:"gray",dimColor:!0},"\u25BC (+",e.length-(u+a)," more prompts below)"))),Lt.createElement(Jo,{marginTop:1,paddingX:1,borderStyle:"single",borderLeft:!1,borderRight:!1,borderBottom:!1,borderColor:"cyan"},Lt.createElement(pn,{dimColor:!0,italic:!0},"\u2191\u2193 navigate \u2022 Enter select undo point \u2022 Esc close")))}function Wu(e){if(!e)return"";let t=(e.split(`
|
|
537
546
|
`)[0]||"").replace(/@\[(.*?)\]/g,(n,s)=>{let r=s.replace(/\\/g,"/").split("/");return`[${r[r.length-1]}]`});return t.length>69?t.slice(0,67)+"...":e.includes(`
|
|
538
|
-
`)?t+"...":t}function
|
|
547
|
+
`)?t+"...":t}function Yu(e){if(!e)return"N/A";let o=new Date(e);if(isNaN(o.getTime()))return"N/A";let t=a=>String(a).padStart(2,"0"),n=t(o.getHours()),s=t(o.getMinutes()),r=t(o.getSeconds());return`${n}:${s}:${r}`}var ec=ie(()=>{sn()});import ju from"puppeteer";import{exec as Hu}from"child_process";import{promisify as Gu}from"util";import Xu from"fs";var tc,oc,nc,rc=ie(()=>{tc=Gu(Hu),oc=()=>{try{let e=ju.executablePath();if(e&&Xu.existsSync(e))return!0}catch{return!1}return!1},nc=async e=>{e&&e("\u{1F4E5} Downloading Chromium engine (chrome@148)...");try{try{await tc("pnpm exec puppeteer browsers install chrome@148")}catch{await tc("npx -y puppeteer browsers install chrome@148")}return await new Promise(o=>setTimeout(o,1e3)),{success:!0}}catch(o){return console.error("[SETUP ERROR]",o),{success:!1,error:o.message}}}});var fc={};Kr(fc,{default:()=>mc});import sc from"os";import i,{useState as J,useEffect as to,useRef as No,useMemo as Ur}from"react";import{Box as I,Text as y,useInput as Ku,useStdout as Vu}from"ink";import lo from"fs-extra";import qn from"path";import{exec as ea}from"child_process";import{fileURLToPath as qu}from"url";import ic from"ink-text-input";import cc from"gradient-string";function mc({args:e=[]}){let[o,t]=J(!1),[n,s]=J(10),{stdout:r}=Vu(),[a,u]=J(""),[f,m]=J(0),[c,l]=J(!1),[d,p]=J("Flux"),[h,S]=J({columns:r?.columns||80,rows:r?.rows||24}),[w,T]=J(0),[b,L]=J(!1),[P,Y]=J(!1),[v,D]=J(0),A=No(null);to(()=>{let x=Is(),g=!["Terminal","Windows Terminal"].includes(x)||!!process.env.VSC_TERMINAL_URL,O=setTimeout(()=>{g&&!Ko()&&Y(!0)},500),N=setInterval(()=>{Ko()&&Y(!1)},1e3);return()=>{clearTimeout(O),clearInterval(N)}},[]);let E=Ur(()=>{let x={};for(let g=0;g<e.length;g++)if(e[g]==="--key"&&e[g+1]){let N=e[g+1];if(x.key=N,N.includes("@")){let M=N.split("@"),$=M[0],R=M[1].toLowerCase();if(["google","deepseek","openrouter","nvidia"].includes(R)){let k="Google";R==="google"?k="Google":R==="deepseek"?k="DeepSeek":R==="openrouter"?k="OpenRouter":R==="nvidia"&&(k="NVIDIA"),x.key=$,x.provider=k}}}for(let g=0;g<e.length;g++){let O=e[g];if(O==="--key"){g++;continue}if(O==="--model"&&e[g+1])x.model=e[g+1],g++;else if(O==="--memory"&&e[g+1])x.memory=e[g+1].toLowerCase(),g++;else if(O==="--resume"&&e[g+1])x.resume=e[g+1],g++;else if(O==="--package"&&e[g+1]){let N=e[g+1].toLowerCase();["npm","pnpm","yarn","bun"].includes(N)&&(x.package=N),g++}else if(O==="--auto-del"&&e[g+1]){let N=e[g+1].toLowerCase();["1d","7d","30d"].includes(N)&&(x.autoDel=N),g++}else if(O==="--auto-exec"&&e[g+1])x.autoExec=e[g+1].toLowerCase(),g++;else if(O==="--yolo"&&e[g+1])x.autoExec=e[g+1].toLowerCase(),g++;else if(O==="--external-access"&&e[g+1])x.externalAccess=e[g+1].toLowerCase(),g++;else if(O==="--mode"&&e[g+1]){let M=e[g+1].toLowerCase();if(["flux","flow"].includes(M)){let $="Flux";M==="flux"?$="Flux":M==="flow"&&($="Flow"),x.mode=$}g++}else if(O==="--thinking"&&e[g+1]){let M=e[g+1].toLowerCase();if(["fast","low","medium","high","xhigh","standard"].includes(M)){let $="Medium";M==="fast"?$="Fast":M==="low"?$="Low":M==="standard"?$="Standard":M==="medium"?$="Medium":M==="high"?$="High":M==="xhigh"&&($="xHigh"),x.thinking=$}g++}else if(O==="--provider"&&e[g+1]){let N=e[g+1].toLowerCase();if(["google","deepseek","openrouter","nvidia"].includes(N)){let M="Google";N==="google"?M="Google":N==="deepseek"?M="DeepSeek":N==="openrouter"?M="OpenRouter":N==="nvidia"&&(M="NVIDIA"),x.provider=M}g++}}return x},[e]),q=async(x=!1,g=null)=>{let O=g||Xe;x&&U(N=>(Q(N.length+1),[...N,{id:"check-"+Date.now(),role:"system",text:"\u{1F50D} Checking for updates...",isMeta:!0}]));try{let M=await(await fetch("https://registry.npmjs.org/fluxflow-cli",{cache:"no-store"})).json(),$=M["dist-tags"]?.latest,R=M["dist-tags"]?.stable;if($&&De($),$&&$!==Ln){let k=$===R?`v${$}-stable`:`v${$}`;!x&&O.autoUpdate?z("update"):U(F=>{let W=[...F],j=x?W.length:Math.min(W.length,3);return W.splice(j,0,{id:"update-"+Date.now(),role:"system",text:`A new version (${k}) is here.
|
|
539
548
|
|
|
540
549
|
\u2022 Type \`/update latest\` to apply the update.
|
|
541
|
-
\u2022 Type \`/changelog\` to view the release notes.`,isUpdateNotification:!0,isMeta:!0}),
|
|
550
|
+
\u2022 Type \`/changelog\` to view the release notes.`,isUpdateNotification:!0,isMeta:!0}),W})}else x&&U(k=>{Q(k.length+1);let F=$&&$===R?`${Ln}-stable`:Ln;return[...k,{id:"uptodate-"+Date.now(),role:"system",text:`\u2705 [SYSTEM] Flux Flow is already up to date (${F}).`,isMeta:!0}]})}catch(N){x&&U(M=>(Q(M.length+1),[...M,{id:"check-err-"+Date.now(),role:"system",text:`\u274C ERROR: Failed to check for updates: ${N.message}`,isMeta:!0}]))}};to(()=>{let x=()=>{r.write("\x1B[2J\x1B[3J\x1B[H"),S({columns:r.columns,rows:r.rows})};return r.on("resize",x),()=>{r.off("resize",x)}},[r]);let[B,V]=J("Medium"),[_,K]=J("Google"),[Ue,se]=J(0),[Te,De]=J(null),[me,et]=J(!1),[Ye,je]=J("gemma-4-31b-it"),[Oe,kt]=J("gemma-4-26b-a4b-it"),[Ne,He]=J(!0),[We,Vt]=J(!0),Nt=No(0),[Ge,ze]=J(null),[yt,co]=J(""),[qt,z]=J("chat"),[Ft,oo]=J("Free"),[no,Rr]=J({agentLimit:999999,backgroundLimit:999999,searchLimit:100,customModelId:"",customLimit:0}),[Bt,So]=J(null),[Xe,Eo]=J({memory:!0,compression:0,autoExec:!1,autoDeleteHistory:"7d",autoUpdate:!1,updateManager:"npm",customUpdateCommand:""}),[Qo,ce]=J({name:null,nickname:null,instructions:null}),[Se,Je]=J({keyType:"Default",quality:"Low-High",apiKey:""}),[Ee,Be]=J({tokens:0}),[pe,It]=J(0),[Fn,Zo]=J(0),[go,at]=J(0),[he,bo]=J(0),[wt,Bo]=J(0),[Ut,$n]=J(0),[Tt,ut]=J(0),[ro,Rt]=J(0),[Uo,Ms]=J(0),[gr,xr]=J(0),[zn,oa]=J(0),[As,vs]=J(0),[Ke,Ds]=J(null),[be,fe]=J(oi()),[_e,so]=J(null),[Mt,ft]=J(""),[dt,Jn]=J(!1),[Do,At]=J(0),zt=No(!0),Co=No(!0),Pn=No(!0),Qn=No(_);to(()=>{Qn.current!==_?(Qn.current=_,V(_==="DeepSeek"||_==="NVIDIA"?"Standard":"Medium")):_==="Google"&&B==="xHigh"&&Ye&&Ye.toLowerCase().startsWith("gemini-3")&&V("High")},[_,Ye,B]),to(()=>{if(!Ge)return;if(zt.current){zt.current=!1,setTimeout(()=>{Co.current=!1,setTimeout(()=>{Pn.current=!1},1e3)},2e3);return}if(Co.current||Pn.current)return;let x=ve(2),g="",O="";Ft==="Free"?_==="Google"?(g="gemma-4-31b-it",O="Gemma 4 (Free default)"):_==="DeepSeek"?(g="deepseek-v4-flash",O="DeepSeek Flash (Free default)"):_==="NVIDIA"?(g="moonshotai/kimi-k2.6",O="Moonshot Kimi (NVIDIA)"):(g="google/gemma-4-31b-it:free",O="Gemma 4 (Free default)"):_==="Google"?(g="gemini-3-flash-preview",O="Gemini 3 Flash"):_==="DeepSeek"?(g="deepseek-v4-flash",O="DeepSeek Flash"):_==="NVIDIA"?(g="moonshotai/kimi-k2.6",O="Moonshot Kimi (NVIDIA)"):(g="deepseek/deepseek-v4-flash",O="DeepSeek Flash"),je(g),Sn({apiTier:Ft,activeModel:g}),U(N=>(Q(N.length+1),[...N,{id:"tier-switch-"+Date.now(),role:"system",text:`\u26A0\uFE0F${x}**[TIER LIMIT]** Auto-switched to ${O}.`,isMeta:!0}]))},[Ft,_,Ge]);let Os=Ur(()=>{let x=Is(),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"}},[]),Wr=No(null),Yr=No("");to(()=>{Wr.current=_e},[_e]),to(()=>{Yr.current=Mt},[Mt]);let[Ls,ae]=J(!1),[xe,Qe]=J(null),[Le,pt]=J(null),ko=x=>{Qe(null),z("chat")},hn=x=>{let g=Math.floor(x/3600),O=Math.floor(x%3600/60),N=x%60,M=[];return g>0&&M.push(`${g}h`),(O>0||g>0)&&M.push(`${O}m`),M.push(`${N}s`),M.join(" ")},Ro=x=>x<1e3?`${x}ms`:hn(Math.floor(x/1e3)),[en,yr]=J(null),[Zn,jr]=J("");to(()=>{let x;if(en){let g=()=>{let O=Qi[Math.floor(Math.random()*Qi.length)];jr(O)};Zn||g(),x=setInterval(g,1e4)}else jr("");return()=>clearInterval(x)},[en]);let[_n,Fs]=J(!0),[tn,Hr]=J(!1),[Nn,wr]=J(!1),[Tr,on]=J(null),[Bn,Un]=J(0),[Gr,te]=J([]),Ze=No(null),[St,X]=J(null),[ht,$t]=J(null),[Re,Wo]=J(null);to(()=>Un(0),[a]);let[gt,U]=J(()=>{let x={id:"logo-"+Date.now(),role:"system",text:hr,isLogo:!0,isMeta:!0},g={id:"welcome",role:"system",text:"\u{1F30A}\u26A1 Welcome to Flux Flow! Type /help for commands.",isMeta:!0},O=process.cwd()===sc.homedir(),N=(()=>{let $=process.cwd().toLowerCase();if(process.platform==="win32"){let R=process.env.SystemRoot?.toLowerCase()||"c:\\windows",k=process.env.ProgramFiles?.toLowerCase()||"c:\\program files",F=process.env["ProgramFiles(x86)"]?.toLowerCase()||"c:\\program files (x86)";return $.startsWith(R)||$.startsWith(k)||$.startsWith(F)}else return $==="/"||["/bin","/sbin","/etc","/usr","/var","/root"].some(k=>$.startsWith(k))})(),M=[x,g];return N?M.push({id:"system-warning",role:"system",text:"\u{1F6D1} [CRITICAL SECURITY ALERT] SYSTEM DIRECTORY DETECTED",subText:`You are currently in a PROTECTED SYSTEM DIRECTORY (${process.cwd()}). Operating here is EXTREMELY dangerous as the agent could accidentally corrupt your OS or installed applications. PLEASE MOVE TO A PROJECT FOLDER FOR SAFETY.`,isHomeWarning:!0,isMeta:!0}):O&&M.push({id:"home-warning",role:"system",text:"[SECURITY ALERT] HOME DIRECTORY DETECTED",subText:`You are currently in ${sc.homedir()}. Working here is high-risk as the agent may modify system-sensitive configurations. Please move to a project folder for safety.`,isHomeWarning:!0,isMeta:!0}),M}),Ve=No(null),[er,Q]=J(gt.length),Xr=Ur(()=>{let g=h.columns||80,O=0,N=0;for(let M=gt.length-1;M>=0;M--){let $=gt[M];if(!$)continue;let R=$.text||"",k=R.split(/\r?\n/).length;if(R.split(/\r?\n/).forEach(F=>{k+=Math.floor(F.length/g)}),$.isHelpRecord&&(k=15),$.isUpdateNotification&&(k=8),$.isTerminalRecord&&(k=10),k+=$.role==="think"?3:2,O+k>2e3){N=M+1;break}O+=k}return{items:gt.slice(N,er),isTruncated:N>0}},[gt,h.columns,h.rows]),na=Ur(()=>{if(!_e||!Mt)return!1;let x=Mt.trim();return x.endsWith("?")||x.endsWith(":")||/\[[yYnN/]+\]\s*$/.test(x)||/\([yYnN]\)\s*$/.test(x)},[_e,Mt]);Ku((x,g)=>{if(!(x==="\x1B[I"||x==="\x1B[O"||x==="[I"||x==="[O")){if(P){let O=Is(),N=uc(O);if(g.upArrow)D(M=>M>0?M-1:N.length-1);else if(g.downArrow)D(M=>M<N.length-1?M+1:0);else if(g.return){let M=N[v];if(M.action==="dismiss")Y(!1);else if(M.url){let $=process.platform==="win32"?`start ${M.url}`:process.platform==="darwin"?`open ${M.url}`:`xdg-open ${M.url}`;ea($),Y(!1)}}return}if(g.tab&&_e){Jn(O=>!O);return}if(dt&&_e){if(g.return){let O=process.platform==="win32";Ao(O?`\r
|
|
542
551
|
`:`
|
|
543
|
-
`)
|
|
544
|
-
`)}else if(g.backspace||g.delete)
|
|
545
|
-
`)}}),
|
|
552
|
+
`),Fo||ft(N=>N+`
|
|
553
|
+
`)}else if(g.backspace||g.delete)Fo?Ao("\x7F"):(Ao("\b \b"),ft(O=>O.slice(0,-1)));else if(g.upArrow)Ao(g.shift?"\x1B[1;2A":"\x1B[A");else if(g.downArrow)Ao(g.shift?"\x1B[1;2B":"\x1B[B");else if(g.rightArrow)Ao(g.shift?"\x1B[1;2C":"\x1B[C");else if(g.leftArrow)Ao(g.shift?"\x1B[1;2D":"\x1B[D");else if(g.escape)Ao("\x1B");else if(g.ctrl&&x){let O=x.toLowerCase().charCodeAt(0);O>=97&&O<=122?Ao(String.fromCharCode(O-96)):Ao(x)}else x&&(Ao(x),Fo||ft(O=>O+x));return}if(g.escape){if(Ce.length>0&&qt==="chat"){L(!0);return}if(o){t(!1);return}if(tn||_e)Nn?(Nl(),Ma(),wr(!1),Tr&&clearTimeout(Tr)):(wr(!0),Tr&&clearTimeout(Tr),on(setTimeout(()=>wr(!1),3e3)));else if(qt==="revert")z("chat"),Un(0);else if(qt!=="chat"&&qt!=="settings")z("chat");else{if(!Ge&&Ue===1){se(0),co("");return}Un(O=>{let N=O+1;return N===1?(Ze.current&&clearTimeout(Ze.current),Ze.current=setTimeout(()=>Un(0),2e3)):N===2&&(Ze.current&&clearTimeout(Ze.current),Un(0),a.length>0?u(""):Ct.getChatHistory(be).then(M=>{M.length>0?(te(M.reverse()),z("revert")):U($=>(Q($.length+1),[...$,{id:"revert-empty-"+Date.now(),role:"system",text:"\u{1F6C8} No revert checkpoints found for this session.",isMeta:!0}]))})),N})}}if(Ce.length>0&&qt==="chat"){if(g.upArrow){T(O=>O>0?O-1:Ce.length-1);return}if(g.downArrow){T(O=>O<Ce.length-1?O+1:0);return}if(g.return)return}if(g.tab,g.ctrl&&x==="c"&&qt!=="exit"){if(a.length>0){u("");return}if(g.shift){z("exit"),t(!1);return}o?(z("exit"),t(!1)):t(!0)}g.return&&(g.shift||g.ctrl||g.meta||g.leftAlt||g.rightAlt)&&u(O=>O.replace(/\\\r?$/,"").replace(/\r?$/,"")+`
|
|
554
|
+
`)}}),to(()=>{process.stdout.write("\x1B[?1004h");let x=g=>{let O=g.toString();O.includes("\x1B[I")?(Vt(!0),Nt.current=Date.now()):O.includes("\x1B[O")&&(Vt(!1),Nt.current=Date.now())};return process.stdin.on("data",x),()=>{process.stdout.write("\x1B[?1004l"),process.stdin.off("data",x)}},[]),to(()=>{async function x(){try{let R=JSON.parse(lo.readFileSync(qn.join(process.cwd(),"package.json"),"utf8"));Fi(Ln||R.version||"2.0.0")}catch{Fi("2.0.0")}process.stdout.isTTY&&(process.stdout.write("\x1B]0;FluxFlow\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow\x07")),oc()||(U(R=>(Q(R.length+1),[...R,{id:"setup-"+Date.now(),role:"system",text:"\u{1F527} [SYSTEM] Installing Required dependencies... (One-time setup)",isMeta:!0}])),await nc(),U(R=>(Q(R.length+1),[...R,{id:"setup-done-"+Date.now(),role:"system",text:"\u2705 [SYSTEM] All dependencies installed successfully.",isMeta:!0}])));let g=await rr();E.mode?p(E.mode):p(g.mode),E.thinking?V(E.thinking):V(g.thinkingLevel);let O=E.provider||g.aiProvider||"Google";K(O);let N=g.apiTier||"Free";if(A.current=g.activeModel,E.model)je(E.model);else if(E.provider){let R="";N==="Free"?O==="Google"?R="gemma-4-31b-it":O==="DeepSeek"?R="deepseek-v4-flash":O==="OpenRouter"?R="google/gemma-4-31b-it:free":O==="NVIDIA"&&(R="moonshotai/kimi-k2.6"):O==="Google"?R="gemini-3-flash-preview":O==="DeepSeek"?R="deepseek-v4-flash":O==="OpenRouter"?R="deepseek/deepseek-v4-flash":O==="NVIDIA"&&(R="moonshotai/kimi-k2.6"),je(R)}else je(g.activeModel);et(g.showFullThinking),oo(g.apiTier||"Free"),Rr(g.quotas||{agentLimit:999999,backgroundLimit:999999,searchLimit:100,customModelId:"",customLimit:0});let M={memory:!0,compression:0,autoExec:!1,autoDeleteHistory:"7d",autoUpdate:!1,updateManager:"npm",customUpdateCommand:"",...g.systemSettings||{}};E.memory==="on"?M.memory=!0:E.memory==="off"&&(M.memory=!1),E.package&&(M.updateManager=E.package),E.autoDel&&(M.autoDeleteHistory=E.autoDel),E.autoExec==="on"?M.autoExec=!0:E.autoExec==="off"&&(M.autoExec=!1),E.externalAccess==="on"?M.allowExternalAccess=!0:E.externalAccess==="off"&&(M.allowExternalAccess=!1),Eo(M),ce(g.profileData),Je(g.imageSettings||{keyType:"Default",quality:"Low-High",apiKey:""});let $=E.key;if($||($=await Qr(O)),$&&(ze($),Br($,{aiProvider:O,onIDEApproval:ko})),g.systemSettings?.autoDeleteHistory&&ja(g.systemSettings.autoDeleteHistory),Ha(Mo),q(!1,M),await Va(),E.resume){let R=await Po(),k=E.resume;if(R[k]){fe(k);let F=[...R[k].messages];F[0]?.text?.includes("\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557")||F.unshift({id:"welcome-"+Date.now(),role:"system",text:hr+`
|
|
546
555
|
|
|
547
|
-
\u{1F30A}\u26A1 Resuming Flux Flow Session...`,isMeta:!0}),
|
|
556
|
+
\u{1F30A}\u26A1 Resuming Flux Flow Session...`,isMeta:!0}),U(F),z("chat"),U(j=>{let Z=[...j,{id:"sys-"+Date.now(),role:"system",text:`\u{1F4E1} SESSION RESUMED VIA CLI: [${k}]`,isMeta:!0}];return Q(Z.length),Z})}else U(F=>[...F,{id:"sys-err-"+Date.now(),role:"system",text:`\u274C ERROR: Chat session [${k}] not found. Started new session.`,isMeta:!0}])}He(!1)}x()},[]),to(()=>{let x;return o&&(s(10),x=setInterval(()=>{s(g=>g<=1?(t(!1),0):g-1)},1e3)),()=>{x&&clearInterval(x)}},[o]),to(()=>{if(!Ne){let x=E.model&&Ye===E.model?A.current:Ye;Sn({mode:d,thinkingLevel:B,aiProvider:_,activeModel:x||Ye,showFullThinking:me,systemSettings:Xe,profileData:Qo,imageSettings:Se,apiTier:Ft})}},[d,B,_,Ye,me,Xe,Qo,Se,Ne,E,Ft]);let Sr=async x=>{let g=x.trim(),O=39;if(_==="OpenRouter"&&(O=30),_==="DeepSeek"&&(O=30),_==="NVIDIA"&&(O=30),g.length>=O){await Zr(_,g),ze(g),Br(g,{aiProvider:_,onIDEApproval:ko});let N="gemma-4-31b-it";_==="OpenRouter"?N="google/gemma-4-31b-it:free":_==="DeepSeek"?N="deepseek-v4-flash":_==="NVIDIA"&&(N="moonshotai/kimi-k2.6"),je(N),U(M=>[...M,{role:"system",text:`\u2705 ${_} API Key saved successfully! Model set to ${N}. Initialization complete.`,isMeta:!0}])}else U(N=>[...N,{role:"system",text:`\u274C INVALID KEY: ${_} API keys must be at least ${O} characters.`,isMeta:!0}]),co("")},Rn=No(ta);to(()=>{if(qt==="exit"){(async()=>{let O=Date.now(),N=Math.floor((O-Rn.current)/1e3);N>=1&&(await To("duration",N),Rn.current+=N*1e3),await qa()})();let g=setTimeout(()=>{process.exit(0)},1700);return()=>clearTimeout(g)}},[qt]),to(()=>{let x=setInterval(async()=>{if(!Ne){let g=Date.now(),O=Math.floor((g-Rn.current)/1e3);O>=1&&(await To("duration",O),Rn.current+=O*1e3)}},1500);return()=>clearInterval(x)},[Ne]);let ue=[{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:_==="DeepSeek"?[{cmd:"Fast",desc:"Fastest"},{cmd:"Standard",desc:"Standard Reasoning"},{cmd:"High",desc:"Extended Reasoning"}]:_==="NVIDIA"?[{cmd:"Fast",desc:"Reasoning Disabled"},{cmd:"Standard",desc:"Balanced Reasoning"},{cmd:"High",desc:"Reasoning Enabled"}]:_==="OpenRouter"?[{cmd:"Fast",desc:"Fastest"},{cmd:"Low",desc:"Quick Reasoning"},{cmd:"Medium",desc:"Balanced Reasoning"},{cmd:"High",desc:"Deep Reasoning"},{cmd:"xHigh",desc:"Extended Reasoning"}]:Ye&&Ye.toLowerCase().startsWith("gemini-3")?[{cmd:"Fast",desc:"Fastest"},{cmd:"Low",desc:"Quick Reasoning"},{cmd:"Medium",desc:"Balanced Reasoning"},{cmd:"High",desc:"Deep Reasoning"}]:[{cmd:"Fast",desc:"Fastest"},{cmd:"Low",desc:"Quick Reasoning"},{cmd:"Medium",desc:"Balanced Reasoning"},{cmd:"High",desc:"Deep Reasoning"},{cmd:"xHigh",desc:"Extended Reasoning"}]},{cmd:"/model",desc:"Switch Model for Agent",subs:_==="OpenRouter"?Ft==="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"}]:_==="DeepSeek"?[{cmd:"deepseek-v4-flash",desc:"Fast & Efficient"},{cmd:"deepseek-v4-pro",desc:"High-Intelligence Reasoning"}]:_==="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:""}]:Ft==="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:"/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"}]}],Pe=async(x,g=!1)=>{if(!g&&Ce.length>0){let M=Ce[w]||Ce[0],$=x.split(" ");if($.length===1)u(M.cmd+" ");else{let R=$.slice(0,-1);u(R.join(" ")+" "+M.cmd+" ")}T(0),m(R=>R+1);return}let O=x.replace(/\r\n/g,`
|
|
548
557
|
`).replace(/\r/g,`
|
|
549
|
-
`).trimEnd();if(
|
|
550
|
-
`);return}let
|
|
558
|
+
`).trimEnd();if(O.endsWith("\\")){u(O.slice(0,-1)+`
|
|
559
|
+
`);return}let N=O.replace(/\\\s*\n/g,`
|
|
551
560
|
`).split(/\r?\n/).map(M=>M.replace(/\\$/,"")).join(`
|
|
552
|
-
`);if(
|
|
553
|
-
${M}`,color:"magenta"}])),u("");return}if(!
|
|
554
|
-
\u2022 Spent (Last 1hr): ${Number((
|
|
555
|
-
\u2022 Remaining: ${Number((
|
|
556
|
-
\u2022 Requests (Last 1hr): ${
|
|
557
|
-
`+(
|
|
558
|
-
`);try{
|
|
559
|
-
`);
|
|
560
|
-
${
|
|
561
|
-
\u{1F539} Status: ${
|
|
562
|
-
\u{1F539} Released on: ${
|
|
561
|
+
`);if(N.trim()){if(tn){let M=N.trim();if(M.startsWith("/")){U($=>(Q($.length+1),[...$,{id:"hint-err-"+Date.now(),role:"system",text:"\u274C [RESTRICTED] Steering Hints cannot start with /",isMeta:!0}])),u("");return}X(M),Ve.current=M,U($=>(Q($.length+1),[...$,{id:"hint-"+Date.now(),role:"user",text:`[STEERING HINT: QUEUED]
|
|
562
|
+
${M}`,color:"magenta"}])),u("");return}if(!Ge){Sr(N),co("");return}if(N.startsWith("/")){let M=N.split(" "),$=M[0]?.toLowerCase();switch($){case"/quit":{z("exit");break}case"/resume":{if(M[1]){let k=M[1];(async()=>{let W=await Po(),j=W[k]||Object.values(W).find(Z=>Z.name.toLowerCase()===k.toLowerCase());if(j){r.write("\x1B[2J\x1B[3J\x1B[H"),fe(k);let Z=[...j.messages];Z[0]?.text?.includes("\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557")||(Z.unshift({id:"welcome-"+Date.now(),role:"system",text:"\u{1F30A}\u26A1 Resuming Flux Flow Session...",isMeta:!0}),Z.unshift({id:"logo-"+Date.now(),role:"system",text:hr,isLogo:!0,isMeta:!0})),U(Z),U(ee=>[...ee,{id:"sys-"+Date.now(),role:"system",text:`\u{1F4E1} SESSION RESUMED: [${k}]`,isMeta:!0}]),Q(0)}else U(Z=>[...Z,{id:"err-"+Date.now(),role:"system",text:`\u274C ERROR: Session [${k}] not found.`}])})()}else z("resume");break}case"/clear":{U([{id:"logo-"+Date.now(),role:"system",text:hr,isLogo:!0,isMeta:!0},{id:"welcome-"+Date.now(),role:"system",text:"\u{1F30A}\u26A1 Welcome back to Flux Flow! Context cleared.",isMeta:!0}]),Q(2),fe(oi()),Be({tokens:0}),l(!1);break}case"/revert":{Ct.getChatHistory(be).then(k=>{if(k.length>0)te(k.reverse()),z("revert");else{let F=ve(2);U(W=>(Q(W.length+1),[...W,{id:"revert-empty-"+Date.now(),role:"system",text:"No revert checkpoints found for this session.",isMeta:!0}]))}});break}case"/mode":{if(M[1]){let k=M[1].toLowerCase()==="flow"?"Flow":"Flux";p(k),k==="Flow"?V("Fast"):k==="Flux"&&V("High");let F=ve(2);U(W=>(Q(W.length+1),[...W,{id:Date.now(),role:"system",text:`\u{1F527}${F}[SYSTEM] Mode switched to ${k}`,isMeta:!0}]))}else z("mode");break}case"/image":{if(M[1]?.toLowerCase()==="stats"){let k=ve(2);if(Se.keyType==="Custom")U(F=>(Q(F.length+1),[...F,{id:Date.now(),role:"system",text:`\u{1F517}${k}[SYSTEM] Key strategy is Custom. Redirecting to Pollinations dashboard (https://enter.pollinations.ai/#pollen)...`,isMeta:!0}])),ea("start https://enter.pollinations.ai/#pollen");else try{let F=await fs();U(W=>(Q(W.length+1),[...W,{id:Date.now(),role:"system",isImageStats:!0,text:`\u2022 Hourly Limit: ${Number((F.limit*1e3).toFixed(0))} credits
|
|
563
|
+
\u2022 Spent (Last 1hr): ${Number((F.totalSpent*1e3).toFixed(0))} credits
|
|
564
|
+
\u2022 Remaining: ${Number((F.remaining*1e3).toFixed(0))} credits
|
|
565
|
+
\u2022 Requests (Last 1hr): ${F.activeCallsCount} requests
|
|
566
|
+
`+(F.nextResetMin>0?`\u2022 Refreshes in: ${F.nextResetMin}m`:""),isMeta:!0}]))}catch{U(W=>(Q(W.length+1),[...W,{id:Date.now(),role:"system",text:"\u274C [SYSTEM] Failed to load image quota stats.",isMeta:!0}]))}}else if(M[1]?.toLowerCase()==="setup")if(M[2]?.toLowerCase()==="key")if(M[3]){let k=["default","custom"].find(F=>F===M[3].toLowerCase());if(k){let F=k==="default"?"Default":"Custom";Je(j=>({...j,keyType:F}));let W=ve(2);U(j=>(Q(j.length+1),[...j,{id:Date.now(),role:"system",text:`\u{1F527}${W}[SYSTEM] Image key strategy set to ${F}`,isMeta:!0}])),F==="Custom"&&(So({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"}),z("input"))}else{let F=ve(2);U(W=>(Q(W.length+1),[...W,{id:Date.now(),role:"system",text:"\u274C [SYSTEM] Invalid key option. Choose: Default or Custom.",isMeta:!0}]))}}else{let k=ve(2);U(F=>(Q(F.length+1),[...F,{id:Date.now(),role:"system",text:"\u274C [SYSTEM] Usage: /image setup Key <Default|Custom>",isMeta:!0}]))}else if(M[2]?.toLowerCase()==="quality")if(M[3]){let k=["low","low-high","medium","medium-high","high","ultra","premium"].find(F=>F===M[3].toLowerCase());if(k){let W={low:"Low","low-high":"Low-High",medium:"Medium","medium-high":"Medium-High",high:"High",ultra:"Ultra",premium:"Premium"}[k];Je(Z=>({...Z,quality:W}));let j=ve(2);U(Z=>(Q(Z.length+1),[...Z,{id:Date.now(),role:"system",text:`\u{1F527}${j}[SYSTEM] Image quality set to ${W}`,isMeta:!0}]))}else{let F=ve(2);U(W=>(Q(W.length+1),[...W,{id:Date.now(),role:"system",text:"\u274C [SYSTEM] Invalid quality level. Choose from: Low, Low-High, Medium, Medium-High, High, Ultra, Premium.",isMeta:!0}]))}}else{let k=ve(2);U(F=>(Q(F.length+1),[...F,{id:Date.now(),role:"system",text:"\u274C [SYSTEM] Usage: /image setup Quality <Low|Low-High|Medium|Medium-High|High|Ultra>",isMeta:!0}]))}else{let k=ve(2);U(F=>(Q(F.length+1),[...F,{id:Date.now(),role:"system",text:"\u274C [SYSTEM] Usage: /image setup <Key|Quality> ...",isMeta:!0}]))}else{let k=ve(2);U(F=>(Q(F.length+1),[...F,{id:Date.now(),role:"system",text:"\u274C [SYSTEM] Usage: /image setup <Key|Quality> ...",isMeta:!0}]))}break}case"/thinking":{let k;if(M[1]){let F=M[1].toLowerCase(),W=M.includes("--bypass");if(k=F.charAt(0).toUpperCase()+F.slice(1),F==="xhigh"&&(k="xHigh"),!W&&d==="Flow"&&(k==="Medium"||k==="High"||k==="xHigh"))U(j=>(Q(j.length+1),[...j,{id:Date.now(),role:"system",text:`\u274C [RESTRICTED] "${k}" is restricted in Flow mode. Switch to Flux to enable Higher Thinking Levels.`,isMeta:!0}]));else{V(k);let j=ve(1);U(Z=>(Q(Z.length+1),[...Z,{id:Date.now(),role:"system",text:`\u{1F527} [SYSTEM] Thinking level set to ${k}${W?` (Bypass Activated \u{1F575}\uFE0F${j})`:""}`,isMeta:!0}]))}}else z("thinking");break}case"/model":{if(M[1]){let k=M.slice(1).join(" ");if(k==="gemma-4-31b-it"&&Ft!=="Free"&&_==="Google")U(F=>(Q(F.length+1),[...F,{id:Date.now(),role:"system",text:"\u274C **[ACCESS DENIED]** Gemma is restricted to the Free API tier. Automatically switching you to **Gemini 3 Flash Preview** for optimal performance.",isMeta:!0}])),je("gemini-3-flash-preview");else{je(k);let F=ve(2);U(W=>(Q(W.length+1),[...W,{id:Date.now(),role:"system",text:`\u{1F527}${F}[SYSTEM] Model switched to ${k}`,isMeta:!0}]))}}else z("model");break}case"/settings":{z("settings");break}case"/key":{z("key");break}case"/profile":{z("profile");break}case"/stats":{(async()=>{let F=await In();Ds(F),z("stats")})();break}case"/save":{let k=M.slice(1).join(" ")||`Session ${new Date().toLocaleTimeString()}`;ds(be,k,gt),U(F=>(Q(F.length+1),[...F,{id:Date.now(),role:"system",text:`\u{1F4BE} [MEMORY] Chat saved as "${k}" (ID: ${be})`,isMeta:!0}]));break}case"/export":{let k=`export-fluxflow-${be}.txt`,F=qn.join(process.cwd(),k),W=[],j=!1;for(let ne=0;ne<gt.length;ne++){let ee=gt[ne];if(ee&&!(ee.role==="system"||ee.isMeta||ee.isLogo||String(ee.id).startsWith("welcome"))){if(ee.role==="user"){let le=ee.text||"";le=le.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),W.length>0&&W.push(""),W.push("[USER]"),W.push(le),j=!1}else if(ee.role==="think"){j||(W.push(""),W.push("[AGENT]"),j=!0);let le=(ee.text||"").replace(/\[turn:\s*continue\]/gi,"").replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").replace(/\[TOOL RESULTS\]/gi,"").trim();le&&(W.push("[thoughts]"),W.push(le))}else if(ee.role==="agent"){j||(W.push(""),W.push("[AGENT]"),j=!0);let le=td(ee.text||"");for(let Me of le)if(Me.type==="output"){let Et=Me.content.replace(/\[turn:\s*continue\]/gi,"").replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").replace(/\[TOOL RESULTS\]/gi,"").trim();Et&&(W.push("[output]"),W.push(Et))}else Me.type==="tool"&&(W.push("[tool]"),W.push(`${Me.toolName} ${Me.args}`))}}}let Z=W.join(`
|
|
567
|
+
`);try{lo.writeFileSync(F,Z,"utf8"),U(ne=>(Q(ne.length+1),[...ne,{id:Date.now(),role:"system",text:`\u{1F4E4} [EXPORT] Chat exported successfully to "${k}"`,isMeta:!0}]))}catch(ne){U(ee=>(Q(ee.length+1),[...ee,{id:Date.now(),role:"system",text:`\u274C [EXPORT ERROR] Failed to export chat: ${ne.message}`,isMeta:!0}]))}break}case"/chats":{(async()=>{let F=await Po(),W=Object.entries(F).map(([j,Z])=>`\u2022 ${j}: ${Z.name}`).join(`
|
|
568
|
+
`);U(j=>(Q(j.length+1),[...j,{id:Date.now(),role:"system",text:`\u{1F5C3}\uFE0F [HISTORY] Saved Chats:
|
|
569
|
+
${W||"No saved chats found."}`,isMeta:!0}]))})();break}case"/memory":{z("memory");break}case"/reset":{(async()=>{try{U(F=>(Q(F.length+1),[...F,{id:Date.now(),role:"system",text:"\u2622\uFE0F [NUCLEAR] Initiating reset...",isMeta:!0}])),lo.existsSync(Mo)&&lo.removeSync(Mo),lo.existsSync(jt)&&lo.removeSync(jt),lo.existsSync(io)&&lo.removeSync(io);try{lo.readdirSync(Wn).length===0&&lo.removeSync(Wn)}catch{}setTimeout(()=>{z("exit"),setTimeout(()=>process.exit(0),500)},500)}catch(F){U(W=>(Q(W.length+1),[...W,{id:Date.now(),role:"system",text:`\u274C [RESET ERROR] Failed to purge data: ${F.message}`}]))}})();break}case"/about":{let k=ve(2),F=`\u{1F539} FluxFlow Version: v${Ln}
|
|
570
|
+
\u{1F539} Status: ${Te&&Te!==Ln?`Update Available [v${Te}]`:"Up to date"}
|
|
571
|
+
\u{1F539} Released on: ${Qu}`;U(W=>(Q(W.length+1),[...W,{id:"about-"+Date.now(),role:"system",text:F,isAboutRecord:!0,isMeta:!0}]));break}case"/changelog":{let k=process.platform;ea(`${k==="win32"?"start":k==="darwin"?"open":"xdg-open"} ${ac}`),U(W=>(Q(W.length+1),[...W,{id:Date.now(),role:"system",text:`\u{1F310} [BROWSER] Opening changelog: ${ac}`,isMeta:!0}]));break}case"/fluxflow":{if(M.slice(1)[0]==="init"){let F=`# FluxFlow Configuration
|
|
563
572
|
# This file defines project-specific instructions for the Flux Flow Agent.
|
|
564
573
|
|
|
565
574
|
# IDENTITY & TONE
|
|
@@ -574,31 +583,31 @@ ${B||"No saved chats found."}`,isMeta:!0}]))})();break}case"/memory":{X("memory"
|
|
|
574
583
|
|
|
575
584
|
# SKILLS & WORKFLOWS
|
|
576
585
|
- [Define custom step-by-step recipes for this project here]
|
|
577
|
-
`,
|
|
586
|
+
`,W=qn.join(process.cwd(),"FluxFlow.md");if(lo.pathExistsSync(W))U(j=>(Q(j.length+1),[...j,{id:"init-err-"+Date.now(),role:"system",text:"\u274C ERROR: FluxFlow.md already exists in this directory.",isMeta:!0}]));else try{lo.writeFileSync(W,F),U(j=>(Q(j.length+1),[...j,{id:"init-ok-"+Date.now(),role:"system",text:"\u2705 [SUCCESS] FluxFlow.md has been initialized. You can now customize it for this project.",isMeta:!0}]))}catch(j){U(Z=>(Q(Z.length+1),[...Z,{id:"init-err-"+Date.now(),role:"system",text:`\u274C ERROR: Failed to initialize FluxFlow.md: ${j.message}`,isMeta:!0}]))}}else U(F=>(Q(F.length+1),[...F,{id:"ff-err-"+Date.now(),role:"system",text:"\u2753 Usage: /fluxflow init",isMeta:!0}]));break}case"/update":{if(M[1]?.toLowerCase()==="check"){q(!0);break}let F=M.includes("--latest");z("update");break}case"/gemini":{let k=Ji[Math.floor(Math.random()*Ji.length)];U(F=>(Q(F.length+1),[...F,{id:Date.now(),role:"system",text:`\u2728 [GEMINI CLI] ${k}`}])),u("");break}case"/compress":{u("");let k=gt.filter(j=>(j.role==="user"||j.role==="agent"||j.role==="system")&&!String(j.id).startsWith("welcome")&&!j.isMeta).length,F=Ee?.tokens||0;if(k<30||F<32768){let j=ve(2);U(Z=>(Q(Z.length+1),[...Z,{id:Date.now(),role:"system",text:`\u26A0\uFE0F${j}[SYSTEM] Compression skipped: History requires at least 30 messages and 32k tokens (current: ${k}/30 msgs, ${F}/32000 tokens).`,isMeta:!0}]));break}(async()=>{U(j=>(Q(j.length+1),[...j,{id:Date.now(),role:"system",text:"\u2699\uFE0F [SYSTEM] Compressing session history...",isMeta:!0}]));try{if(await Gi({chatId:be,aiProvider:_,apiKey:Ge,thinkingLevel:B,mode:d,janitorModel:Oe,systemSettings:Xe,sessionStats:Ee},gt)){let ne=ve(2);U(ee=>{let le=[...ee,{id:Date.now(),role:"system",text:`\u2699\uFE0F${ne}[SYSTEM] Chat History compressed saving tokens.`,isMeta:!0}];return Q(le.length),le})}else U(ne=>(Q(ne.length+1),[...ne,{id:Date.now(),role:"system",text:"\u274C [SYSTEM] Compression failed (no summary returned).",isMeta:!0}]))}catch(j){U(Z=>(Q(Z.length+1),[...Z,{id:Date.now(),role:"system",text:`\u274C [SYSTEM] Error during compression: ${j.message}`,isMeta:!0}]))}})();break}case"/help":{U(k=>(Q(k.length+1),[...k,{id:Date.now(),role:"system",isHelpRecord:!0,isMeta:!0}]));break}default:let R=ve(2);U(k=>(Q(k.length+1),[...k,{id:Date.now(),role:"system",text:`\u{1F527}${R}[SYSTEM] Unknown command: ${$}`,isMeta:!0}]))}}else{let M=`[Prompted on: ${new Date().toLocaleString(void 0,{year:"numeric",month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit"})}]`,$={id:"user-"+Date.now(),role:"user",text:`${N}
|
|
578
587
|
|
|
579
|
-
${M}`};
|
|
588
|
+
${M}`};U(k=>(Q(k.length+1),[...k,$])),(async()=>{let k=!1;Hr(!0),l(!1);let F=Date.now(),W=!0;try{let j=[...gt,$].filter(H=>H.role!=="think"&&!H.isVisualFeedback&&!H.isMeta&&!String(H.id).startsWith("welcome")),Z=[];j.forEach((H,Ae)=>{let Fe=H.fullText||H.text;if(H.role==="user"&&Ae<j.length-1){let ye=Fe.lastIndexOf("[USER]");ye!==-1&&(Fe=Fe.substring(ye+6).trim())}if(H.role==="system"&&Fe?.startsWith("[TOOL RESULT]")){let ye=Z[Z.length-1];if(ye&&ye.role==="system"&&ye.text?.startsWith("[TOOL RESULT]")){ye.text+=`
|
|
580
589
|
|
|
581
|
-
`+
|
|
582
|
-
COMMAND: ${
|
|
583
|
-
PTY: ${
|
|
584
|
-
OUTPUT: ${
|
|
590
|
+
`+Fe;return}}Z.push({...H,text:Fe})});let ne=Wl(Ye,Z,{profile:Qo,thinkingLevel:B,mode:d,systemSettings:Xe,janitorModel:Oe,sessionStats:Ee,chatId:be,aiProvider:_,apiKey:Ge,apiTier:Ft,cols:h.columns-6,rows:30,onExecStart:H=>{so(H),ft("")},onExecChunk:H=>{ft(Ae=>Ae+H)},onExecEnd:()=>{U(H=>{if(!Wr.current)return H;let Ae=Yr.current||"",Fe=Lr(Ae),ye=`[TERMINAL_RECORD]
|
|
591
|
+
COMMAND: ${Wr.current}
|
|
592
|
+
PTY: ${Fo}
|
|
593
|
+
OUTPUT: ${Fe.replace(/\n{3,}/g,`
|
|
585
594
|
|
|
586
|
-
`)}`;return[...H,{id:"term-"+Date.now(),role:"system",text:ye,isTerminalRecord:!0}]}),
|
|
587
|
-
Selection: ${ye}`,isAskRecord:!0}]),
|
|
588
|
-
`),we=0,
|
|
589
|
-
`),Ct=!1;for(let oo of ut){if(oo.includes("Old File contents:")){Ct=!0;continue}Ct&&(oo.trim()===""?Ct=!1:/^\d+ \|/.test(oo)&&Ke++)}}bs+=we,Cs+=Ke,Eo("linesAdded",we),Eo("linesRemoved",Ke)}continue}let ue=H.content,pe=ue.toLowerCase();if(ue.includes("```")&&(Tt=!Tt),pe.includes("tool:functions.")&&(Mt=!0,vt=0,yo=null,ue.includes("[tool:functions.")&&(vt=0)),Mt){for(let xe=0;xe<ue.length;xe++){let we=ue[xe];!yo&&(we==="'"||we==='"'||we==="`")?yo=we:yo&&we===yo&&ue[xe-1]!=="\\"&&(yo=null),yo||(we==="("||we==="["?vt++:(we===")"||we==="]")&&vt--)}vt<=0&&!yo&&(Mt=!1)}if((pe.includes("<think")||pe.includes("<thought"))&&(!le&&!Tt&&!Mt&&!Jn)&&(le=!0,Jn=!0,ue=ue.replace(/<(think|thought)>[\s\S]*?<\/(think|thought)>/gi,"").replace(/<(think|thought)>/gi,""),Ne="think-"+Date.now(),W(xe=>[...xe,{id:Ne,role:"think",text:"",isStreaming:!0,startTime:Date.now()}])),(pe.includes("</think>")||pe.includes("</thought>"))&&Ne){let xe=ue.split(/<\/(think|thought)>/gi),we=xe[0]||"",Ke=xe.slice(2).join("").replace(/<\/?(think|thought)>/gi,"");W(ut=>{let Ct=ut.map(oo=>{if(oo.id===Ne&&typeof oo.id=="string"){let Hr=oo.startTime||parseInt(oo.id.split("-")[1])||Date.now(),Fs=Date.now()-Hr;return{...oo,text:oo.text+we,isStreaming:!1,duration:Fs}}return oo});return le=!1,Me="agent-"+Date.now(),[...Ct,{id:Me,role:"agent",text:Ke,isStreaming:!0}]});continue}if(le&&Ne)W(xe=>{let we=!1,Ke="",ut=xe.map(Ct=>{if(Ct.id===Ne){let oo=Ct.text+ue;if(oo.toLowerCase().includes("</think>")){we=!0;let Hr=oo.split(/<\/think>/gi);Ke=Hr.slice(1).join("</think>")||"";let Fs=Ct.startTime||parseInt(Ct.id.split("-")[1])||Date.now(),fc=Date.now()-Fs;return{...Ct,text:Hr[0],isStreaming:!1,duration:fc}}return{...Ct,text:oo,isStreaming:!0}}return Ct});return we?(le=!1,Me="agent-"+Date.now(),[...ut,{id:Me,role:"agent",text:Ke.replace(/<\/?(think|thought)>/gi,""),isStreaming:!0}]):ut});else if(!le){let xe=ue.toLowerCase();!to&&xe.includes("tool:functions.")&&(to=!0),Me?W(we=>we.map(Ke=>Ke.id===Me?{...Ke,text:Ke.text+ue,isStreaming:!0}:Ke)):(Me="agent-"+Date.now(),W(we=>[...we,{id:Me,role:"agent",text:ue,isStreaming:!0}]))}}let Sr=Date.now();fr(H=>H+(Sr-L))}catch(j){W(q=>(te(q.length+1),[...q,{id:"error-"+Date.now(),role:"system",text:`\u274C ERROR: ${j.message}`}]))}finally{if(xr(!1),gr(null),C||process.stdout.isTTY&&(process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")),Co.current){bo(Co.current),Ft(null);let j=Co.current;Co.current=null,W(q=>{let ce=[...q],le=ce.reverse().find(Ne=>Ne.text?.includes("[STEERING HINT: QUEUED]"));return le&&(le.text=le.text.replace("[STEERING HINT: QUEUED]","[STEERING HINT: FINISHED_TURN]")),ce.reverse()}),X("resolution")}W(j=>{let q=Date.now()-L,ce=!1,le=[...j].reverse().map(Me=>{let Tt=Me.isStreaming?{...Me,isStreaming:!1}:Me;return!ce&&Tt.role==="agent"&&(ce=!0,Tt={...Tt,workedDuration:q}),Tt}).reverse(),Ne=le.filter(Me=>!String(Me.id).startsWith("welcome")&&!Me.isMeta);return us(We,null,Ne),te(le.length),le})}})()}u(""),a(!1)}},Ae=Ur(()=>{if(l.startsWith("/")&&!I){let D=l.split(" "),_=D[D.length-1].toLowerCase();if(D.length===1){let $=_.startsWith("/")?_.slice(1):_;return Je.filter(R=>(R.cmd.startsWith("/")?R.cmd.slice(1):R.cmd).toLowerCase().includes($))}let M=Je;for(let $=0;$<D.length-1;$++){let R=D[$].toLowerCase(),C=M.find(L=>L.cmd.toLowerCase()===R);if(C&&C.subs)M=C.subs;else return[]}return M.filter($=>$.cmd.toLowerCase().includes(_))}let x=l.split(" "),g=x[x.length-1];if(g&&g.startsWith("@")&&!I){let D=g.indexOf("#"),_=D!==-1,M=_?g.substring(1,D).toLowerCase():g.slice(1).toLowerCase(),$=_?g.substring(D):"";return Zu(process.cwd()).filter(L=>L.name.toLowerCase().includes(M)).map(L=>{let B=L.relativePath.replace(/\\/g,"/");return{cmd:"@["+(B.startsWith(".")?B:"./"+B)+$+"]",desc:L.relativePath}})}return[]},[l,I]);io(()=>{T(0)},[Ae]);let At=()=>{switch(Qt){case"settings":return i.createElement(Ks,{systemSettings:Ht,setSystemSettings:ee,apiTier:He,setActiveView:X,setInputConfig:vo,saveSettings:wn,quotas:Zt,setMessages:W,aiProvider:N});case"selectProvider":return i.createElement(fo,{title:"SELECT AI PROVIDER",items:[{label:"Google (Free/Paid)",value:"Google"},{label:"DeepSeek (Paid)",value:"DeepSeek"},{label:"OpenRouter (Free/Paid) [EXPERIMENTAL]",value:"OpenRouter"},{label:"NVIDIA [EXPERIMENTAL]",value:"NVIDIA"},{label:"Back",value:"settings"}],onSelect:async x=>{if(x.value==="settings"||x.value==="Back"){X("settings");return}let g=x.value,D=await Jr(g);if(D){J(g),ze(D),Br(D,{aiProvider:g,onIDEApproval:Ln});let _="gemma-4-31b-it";g==="OpenRouter"?_="google/gemma-4-31b-it:free":g==="DeepSeek"?_="deepseek-v4-flash":g==="NVIDIA"&&(_="moonshotai/kimi-k2.6"),Be(_),wn({aiProvider:g,activeModel:_,apiTier:He,quotas:Zt}),W(M=>[...M,{role:"system",text:`\u2705 Switched to ${g}! Key loaded from Vault. Model set to ${_}.`,isMeta:!0}]),X("settings")}else vo({label:`Enter ${g} API Key:`,key:"providerKey",provider:g,value:"",returnView:"settings"}),X("input")},onClose:()=>X("settings")});case"apiTier":return i.createElement(fo,{title:i.createElement(y,null,"SELECT YOUR CURRENT API TIER BASED ON ",i.createElement(y,{color:"cyan",underline:!0,bold:!0},"\x1B]8;;https://aistudio.google.com/projects\x07AI STUDIO\x1B]8;;\x07"),". (CURRENT: ",He.toUpperCase(),")"),items:[{label:"Free Tier (Gemini API Free Tier)",value:"Free"},{label:"Paid Tier (API with Billing Account)",value:"Paid"},{label:"Back",value:"settings"}],onSelect:x=>{if(x.value==="settings"||x.value==="Back"){X("settings");return}let g=x.value;Rr(g),g==="Paid"?(vo({label:"Enter Agent daily budget (requests made):",key:"quotas",subKey:"agentLimit",value:String(Zt.agentLimit)}),X("input")):(wn({apiTier:g,quotas:Zt}),X("settings"))},onClose:()=>X("settings")});case"input":return i.createElement(k,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},i.createElement(k,{paddingX:1},i.createElement(y,{color:"magenta",bold:!0},"\u{1F527} DATA CONFIGURATION")),gt?.note&&i.createElement(k,{paddingX:1,marginBottom:1},i.createElement(y,{color:"yellow",dimColor:!0,italic:!0},gt.note)),i.createElement(k,{paddingX:1,flexDirection:"row"},i.createElement(y,{color:"cyan",bold:!0},gt?.label," "),i.createElement(nc,{value:gt?.value||"",onChange:x=>vo(g=>({...g,value:x})),onSubmit:async x=>{let{key:g,subKey:D,next:_}=gt,M={...Zt},$={};if(g==="quotas"){let R=D.toLowerCase().includes("limit")?parseInt(x)||0:x;M[D]=R,Kn(M),$.quotas=M}else if(g==="activeModel")Be(x),$.activeModel=x;else if(g==="janitorModel")Ge(x),$.janitorModel=x;else if(g==="autoApproveCommands"||g==="autoDisallowCommands"||g==="alwaysAskCommands"){let R={...Ht,[g]:x.trim(),sandboxPreset:"Custom"};ee(R),$.systemSettings=R}else if(g==="externalDataPath"){let R={...Ht,useExternalData:!0,externalDataPath:x.trim()};ee(R),$.systemSettings=R,W(C=>[...C,{id:Date.now(),role:"system",text:"\u{1F4C1} [EXTERNAL STORAGE] Flux Flow will use "+x.trim()+" for data after restart."}])}else if(g==="imageSettings"){let R=x.trim();if(R.startsWith("sk_")){let C={...fe,apiKey:R};ge(C),$.imageSettings=C,W(L=>(te(L.length+1),[...L,{id:Date.now(),role:"system",text:"\u{1F511} [IMAGE KEY] Custom API key saved successfully.",isMeta:!0}]))}else ge(C=>({...C,keyType:"Default"})),$.imageSettings={...fe,keyType:"Default"},W(C=>(te(C.length+1),[...C,{id:Date.now(),role:"system",text:"\u274C [IMAGE KEY ERROR] API key must start with sk_. Key strategy reset to Default.",isMeta:!0}]))}else if(g==="providerKey"){let R=x.trim(),C=gt.provider;await Qr(C,R),J(C),ze(R),Br(R,{aiProvider:C,onIDEApproval:Ln});let L="gemma-4-31b-it";C==="OpenRouter"?L="google/gemma-4-31b-it:free":C==="DeepSeek"?L="deepseek-v4-flash":C==="NVIDIA"&&(L="moonshotai/kimi-k2.6"),Be(L),$.aiProvider=C,$.activeModel=L,W(B=>(te(B.length+1),[...B,{id:Date.now(),role:"system",text:`\u2705 ${C} API Key saved successfully! Model set to ${L}.`,isMeta:!0}]))}_?vo(_(g==="quotas"?M:x)):(wn({...$,apiTier:He,quotas:M,imageSettings:$.imageSettings||fe}),vo(null),X(gt?.returnView||"settings"))}})),i.createElement(k,{paddingX:1,marginTop:1},i.createElement(y,{color:"gray",dimColor:!0,italic:!0},"(Press Enter to confirm selection)")));case"stats":return i.createElement(k,{flexDirection:"column",borderStyle:"round",paddingX:3,paddingY:1,width:Math.min(100,(r?.columns||100)-2)},i.createElement(k,{marginBottom:1},i.createElement(y,{color:"white",bold:!0,underline:!0},"SESSION TELEMETRY")),i.createElement(k,{flexDirection:"column"},i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Session Duration:")),i.createElement(y,{color:"white"},en(Date.now()-Zi))),i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Agent Interactions:")),i.createElement(y,{color:"white"},Bo)),i.createElement(k,{marginLeft:2},i.createElement(k,{width:23},i.createElement(y,{color:"grey"},"\xBB API Time:")),i.createElement(y,{color:"white"},en(mr))),i.createElement(k,{marginLeft:2},i.createElement(k,{width:23},i.createElement(y,{color:"grey"},"\xBB Tool Time:")),i.createElement(y,{color:"white"},en(Vn))),i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Background Tasks:")),i.createElement(y,{color:"white"},xt)),i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Tokens Consumed:")),i.createElement(y,{color:"white"},so(ae))),ae>0&&i.createElement(i.Fragment,null,i.createElement(k,{marginLeft:2},i.createElement(k,{width:23},i.createElement(y,{color:"grey"},"\xBB Input Tokens:")),i.createElement(y,{color:"white"},so(ae-yt))),st>0&&i.createElement(k,{marginLeft:4},i.createElement(k,{width:21},i.createElement(y,{color:"grey"},"\xBB Cached:")),i.createElement(y,{color:"white"},so(st))),yt>0&&i.createElement(k,{marginLeft:2},i.createElement(k,{width:23},i.createElement(y,{color:"grey"},"\xBB Output Tokens:")),i.createElement(y,{color:"white"},so(yt)))),pr>0&&i.createElement(i.Fragment,null,i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Images Made:")),i.createElement(y,{color:"white"},pr)),i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Image Credits:")),i.createElement(y,{color:"white"},Number(((On||0)*1e3).toFixed(0))," credits"))),i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Code Changes (Sess):")),i.createElement(y,{color:"white"},i.createElement(y,{color:"green"},"+",bs)," ",i.createElement(y,{color:"red"},"-",Cs))),i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Tool Calls (Sess):")),i.createElement(y,{color:"white"},et+Xt+Uo," ( "),i.createElement(y,{color:"green"},"\u2713 ",et),i.createElement(y,{color:"white"}," "),i.createElement(y,{color:"yellow"},"\u2298 ",Uo),i.createElement(y,{color:"white"}," "),i.createElement(y,{color:"red"},"\u2715 ",Xt),i.createElement(y,{color:"white"}," )"))),i.createElement(k,{flexDirection:"column",marginTop:1},i.createElement(y,{color:"white",bold:!0,underline:!0},"DAILY USAGE TRACKER"),i.createElement(k,{marginTop:1},i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Wall Time Today:")),i.createElement(y,{color:"white"},Fn(se?.duration||0))),i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Agent Interactions:")),i.createElement(y,{color:"white"},se?.agent||0)),i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Background Tasks:")),i.createElement(y,{color:"white"},se?.background||0)),i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Tokens Used Today:")),i.createElement(y,{color:"white"},so(se?.tokens||0))),(se?.tokens||0)>0&&i.createElement(i.Fragment,null,i.createElement(k,{marginLeft:2},i.createElement(k,{width:23},i.createElement(y,{color:"grey"},"\xBB Input Tokens:")),i.createElement(y,{color:"white"},so((se?.tokens||0)-(se?.candidateTokens||0)))),(se?.cachedTokens||0)>0&&i.createElement(k,{marginLeft:4},i.createElement(k,{width:21},i.createElement(y,{color:"grey"},"\xBB Cached:")),i.createElement(y,{color:"white"},so(se.cachedTokens))),(se?.candidateTokens||0)>0&&i.createElement(k,{marginLeft:2},i.createElement(k,{width:23},i.createElement(y,{color:"grey"},"\xBB Output Tokens:")),i.createElement(y,{color:"white"},so(se.candidateTokens)))),(se?.imageCalls?.length||0)>0&&i.createElement(i.Fragment,null,i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Images Made Today:")),i.createElement(y,{color:"white"},se.imageCalls.length)),i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Image Credits Today:")),i.createElement(y,{color:"white"},Number(((se.imageCalls.reduce((x,g)=>x+g.cost,0)||0)*1e3).toFixed(0))," credits"))),i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Code Changes Today:")),i.createElement(y,{color:"white"},i.createElement(y,{color:"green"},"+",se?.linesAdded||0)," ",i.createElement(y,{color:"red"},"-",se?.linesRemoved||0))),i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Tool Calls Today:")),i.createElement(y,{color:"white"},(se?.toolSuccess||0)+(se?.toolFailure||0)+(se?.toolDenied||0)," ( "),i.createElement(y,{color:"green"},"\u2713 ",se?.toolSuccess||0),i.createElement(y,{color:"white"}," "),i.createElement(y,{color:"yellow"},"\u2298 ",se?.toolDenied||0),i.createElement(y,{color:"white"}," "),i.createElement(y,{color:"red"},"\u2715 ",se?.toolFailure||0),i.createElement(y,{color:"white"}," )"))),i.createElement(y,{dimColor:!0,marginTop:1,italic:!0},"(Press ESC to return to chat)"));case"autoExecDanger":return i.createElement(k,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:2,paddingY:1,width:"100%"},i.createElement(y,{color:"yellow",bold:!0,underline:!0},"\u26A0\uFE0F SECURITY WARNING: YOLO MODE"),i.createElement(y,{marginTop:1},"Turning this ON allows the agent to execute terminal commands automatically without requiring your approval for each step."),i.createElement(y,{marginTop:1,color:"yellow"},"RISKS INVOLVED:"),i.createElement(y,null,"\u2022 The agent may execute destructive commands (rm -rf, etc.) by mistake."),i.createElement(y,null,"\u2022 Unintended system changes if the agent hallucinates a path or command."),i.createElement(y,null,"\u2022 Reduced control over the agent's step-by-step decision making."),i.createElement(k,{marginTop:1},i.createElement(fo,{title:"Confirm Intent",items:[{label:"I know the risk and turning on intentionally",value:"on"},{label:"Keep Off (Recommended)",value:"off"}],onSelect:x=>{x.value==="on"&&ee(g=>({...g,autoExec:!0})),X("settings")}})));case"externalDanger":return i.createElement(k,{flexDirection:"column",borderStyle:"round",borderColor:"red",paddingX:2,paddingY:1,width:"100%"},i.createElement(y,{color:"red",bold:!0,underline:!0},"\u26A0\uFE0F SECURITY WARNING: EXTERNAL WORKSPACE ACCESS"),i.createElement(y,{marginTop:1},"Turning this ON allows the agent to execute tools (Read/Write/Exec) outside of the current active workspace directory."),i.createElement(y,{marginTop:1,color:"yellow"},"RISKS INVOLVED:"),i.createElement(y,null,"\u2022 Access to sensitive system files (SSH keys, Browser data, etc.)"),i.createElement(y,null,"\u2022 Potential for accidental or malicious deletion of OS-critical files."),i.createElement(y,null,"\u2022 Unauthorized script execution across your entire file system."),i.createElement(k,{marginTop:1},i.createElement(fo,{title:"Confirm Intent",items:[{label:"I know the risk and turning on intentionally",value:"on"},{label:"Keep Off (Recommended)",value:"off"}],onSelect:x=>{x.value==="on"&&ee(g=>({...g,allowExternalAccess:!0})),X("settings")}})));case"doubleDanger":return i.createElement(k,{flexDirection:"column",borderStyle:"round",borderColor:"red",paddingX:2,paddingY:1,width:"100%"},i.createElement(y,{color:"red",bold:!0,underline:!0},"\u26D4 CRITICAL SECURITY WARNING: COMBINED SYSTEM RISK"),i.createElement(y,{marginTop:1},"You are attempting to enable BOTH [YOLO Mode] and [External Workspace Access] simultaneously."),i.createElement(y,{marginTop:1,color:"red",bold:!0},"THIS IS NOT RECOMMENDED."),i.createElement(y,{marginTop:1,color:"yellow"},"THE CRITICAL RISK:"),i.createElement(y,null,"The agent will have the power to execute any command across your entire system WITHOUT your approval or supervision."),i.createElement(y,{color:"red",italic:!0,marginTop:1},"A single hallucination or error could result in full system wipe or data theft."),i.createElement(k,{marginTop:1},i.createElement(fo,{title:"Final Confirmation",items:[{label:"I agree knowing the consequences",value:"on"},{label:"Keep Off",value:"off"}],onSelect:x=>{x.value==="on"&&ee(g=>({...g,autoExec:!0,allowExternalAccess:!0})),X("settings")}})));case"key":return i.createElement(fo,{title:"\u{1F511} API KEY MANAGEMENT",items:[{label:"Edit Current Key (Update)",value:"edit"},{label:"Remove Current Key (Purge)",value:"remove"},{label:"Cancel",value:"Cancel"}],onSelect:x=>{if(x.value==="edit"){ze(null),X("chat");let g=Oe(2);W(D=>[...D,{id:Date.now(),role:"system",text:`\u{1F511}${g}[ACTION] Flux waiting for new API Key...`}])}else x.value==="remove"?X("deleteKey"):X("chat")}});case"deleteKey":return i.createElement(k,{flexDirection:"column",borderStyle:"round",borderColor:"red",paddingX:2,paddingY:1},(()=>{let x=Oe(2);return i.createElement(y,{color:"red",bold:!0},"\u26D4",x,"DANGER: PURGE API KEY")})(),i.createElement(y,{marginTop:1},"This will permanently delete the saved API key from the project vault. You will need to enter it again to use Flux."),i.createElement(k,{marginTop:1},i.createElement(fo,{title:"Are you absolutely sure?",items:[{label:"YES, PURGE KEY",value:"yes"},{label:"NO, GO BACK",value:"no"}],onSelect:async x=>{if(x.value==="yes"){await Ps(),ze(null),X("chat");let g=Oe(2);W(D=>[...D,{id:Date.now(),role:"system",text:`\u2728${g}[VAULT PURGED] API Key removed successfully.`}])}else X("key")}})));case"exit":return null;case"ask":return i.createElement(k,{width:"100%"},i.createElement(Da,{question:Zo?.question,options:Zo?.options,onResolve:x=>{Zo?.resolve&&Zo.resolve(x),qn(null),X("chat")}}));case"revert":return i.createElement(k,{width:"100%",alignItems:"center",justifyContent:"center"},i.createElement(Ji,{prompts:lt,onSelect:async x=>{try{let g=await kt.rollbackToBefore(x);if(g.success){let{targetPrompt:D}=g,_=Fe.findIndex(C=>C.role==="user"&&C.text&&(C.text.startsWith(D)||C.text.includes(D))),M=[...Fe];_!==-1&&(M=Fe.slice(0,_)),W(M),te(M.length),u(D),a(D.split(`
|
|
590
|
-
`).length>2);let $=M.filter(
|
|
595
|
+
`)}`;return[...H,{id:"term-"+Date.now(),role:"system",text:ye,isTerminalRecord:!0}]}),so(null),Jn(!1),ft("")},onToolResult:(H,Ae)=>{if(H==="success"){if($n(Fe=>Fe+1),Ae==="generate_image"){oa(tt=>tt+1);let ye={Low:.001,"Low-High":.002,Medium:.008,"Medium-High":.01,High:.045,Ultra:.0488,Premium:.1}[Se.quality]||.002;vs(tt=>tt+ye)}}else H==="denied"?Rt(Fe=>Fe+1):ut(Fe=>Fe+1)},onToolApproval:async(H,Ae)=>{let Fe=Ls||Xe.autoExec;if(H==="exec_command"){let{command:ye}=re(Ae||"{}");return Fe||ye&&/^(echo|ls|dir|pwd|cd|git status|git log|git diff|type|cat|help)\b/i.test(ye.trim())?"allow":new Promise(de=>{Qe({tool:H,args:Ae,resolve:de}),z("terminalApproval")})}return Fe?"allow":new Promise(ye=>{Qe({tool:H,args:Ae,resolve:ye}),z("approval")})},onAskUser:async(H,Ae)=>new Promise(Fe=>{pt({question:H,options:Ae,resolve:ye=>{U(tt=>[...tt,{id:"ask-"+Date.now(),role:"system",text:`\u{1F4AC} **Ask User**
|
|
596
|
+
Selection: ${ye}`,isAskRecord:!0}]),Fe(ye)}}),z("ask")})},async()=>{if(Ve.current){let H=Ve.current;return X(null),Ve.current=null,U(Ae=>{let Fe=[...Ae].reverse().findIndex(ye=>ye.text?.includes("[STEERING HINT: QUEUED]"));if(Fe!==-1){let ye=Ae.length-1-Fe,tt=[...Ae];return tt[ye]={...tt[ye],text:tt[ye].text.replace("[STEERING HINT: QUEUED]","[STEERING HINT: INJECTED]"),color:"cyan"},tt}return Ae}),H}return null},Ln),ee=!1,le=null,Me=null,Et=!1,Wt=!1,Io=!1,Yt=!1,gn=0,bt=null,uo=/\[?\s*turn\s*:\s*.*?\s*\]?/gi;for await(let H of ne){if(W&&H.type==="text"&&(F=Date.now(),W=!1),H.type==="status"){yr(H.content),Ko()&&Ts(H.content);continue}if(H.type==="status_history"){yr(H.content),Ko()&&Ts(H.content),U(de=>[...de,{id:"condense-"+Date.now(),role:"system",text:`\u2699\uFE0F [SYSTEM] ${H.content}`,isMeta:!0}]);continue}if(H.type==="spinner"){Fs(H.content);continue}if(H.type==="model_update"){Wo(H.content);continue}if(H.type==="turn_reset"){le=null,Me=null,ee=!1,Et=!1,Wt=!1,Yt=!1,Io=!1;continue}if(H.type==="interactive_turn_finished"){Hr(!1),Ko()&&Ts(null),k=!0,Bl({profile:Qo,thinkingLevel:B,mode:d,janitorModel:Oe,chatId:be,systemSettings:Xe,sessionStats:Ee,aiProvider:_,apiKey:Ge},H.data.agentText,H.data.fullAgentTextRaw,H.data.history,{onMemoryUpdated:()=>U(de=>{let we=[...de];return we.length>0&&(we[we.length-1].memoryUpdated=!0),we}),onBackgroundIncrement:()=>Zo(de=>de+1)});continue}if(H.type==="visual_feedback"){U(de=>[...de,{id:"feedback-"+Date.now(),role:"system",text:H.content,isVisualFeedback:!0}]);continue}if(H.type==="exec_start")continue;if(H.type==="liveTokens"){Be({tokens:H.content});continue}if(H.type==="usage"){let de=H.content.totalTokenCount||0,we=H.content.cachedContentTokenCount||0,ot=H.content.candidatesTokenCount||0;Be({tokens:de}),at(st=>st+de),we>0&&bo(st=>st+we),ot>0&&Bo(st=>st+ot),It(st=>st+1);continue}if(H.type==="tool_time"){xr(de=>de+H.content);continue}if(H.type==="tool_result"){if(U(de=>[...de,{id:"tool-"+Date.now(),role:"system",text:H.content,fullText:H.aiContent,binaryPart:H.binaryPart,toolName:H.toolName}]),H.toolName==="update_file"&&H.aiContent){let de=H.aiContent.split(`
|
|
597
|
+
`),we=0,ot=0,st=!1;for(let lt of de){if(lt.includes("[DIFF_START]")){st=!0;continue}if(lt.includes("[DIFF_END]")){st=!1;continue}st&&(/^\+\d+/.test(lt)?we++:/^\-\d+/.test(lt)&&ot++)}Cs+=we,ks+=ot,To("linesAdded",we),To("linesRemoved",ot)}else if(H.toolName==="write_file"&&H.aiContent){let de=H.aiContent.match(/- Stats: \[(\d+) lines/),we=de?parseInt(de[1]):0,ot=0;if(H.aiContent.includes("Old File contents:")){let st=H.aiContent.split(`
|
|
598
|
+
`),lt=!1;for(let vt of st){if(vt.includes("Old File contents:")){lt=!0;continue}lt&&(vt.trim()===""?lt=!1:/^\d+ \|/.test(vt)&&ot++)}}Cs+=we,ks+=ot,To("linesAdded",we),To("linesRemoved",ot)}continue}let Ae=H.content,Fe=Ae.toLowerCase();if(Ae.includes("```")&&(Et=!Et),Fe.includes("tool:functions.")&&(Wt=!0,gn=0,bt=null,Ae.includes("[tool:functions.")&&(gn=0)),Wt){for(let de=0;de<Ae.length;de++){let we=Ae[de];!bt&&(we==="'"||we==='"'||we==="`")?bt=we:bt&&we===bt&&Ae[de-1]!=="\\"&&(bt=null),bt||(we==="("||we==="["?gn++:(we===")"||we==="]")&&gn--)}gn<=0&&!bt&&(Wt=!1)}if((Fe.includes("<think")||Fe.includes("<thought"))&&(!ee&&!Et&&!Wt&&!Io)&&(ee=!0,Io=!0,Ae=Ae.replace(/<(think|thought)>[\s\S]*?<\/(think|thought)>/gi,"").replace(/<(think|thought)>/gi,""),le="think-"+Date.now(),U(de=>[...de,{id:le,role:"think",text:"",isStreaming:!0,startTime:Date.now()}])),(Fe.includes("</think>")||Fe.includes("</thought>"))&&le){let de=Ae.split(/<\/(think|thought)>/gi),we=de[0]||"",ot=de.slice(2).join("").replace(/<\/?(think|thought)>/gi,"");U(st=>{let lt=st.map(vt=>{if(vt.id===le&&typeof vt.id=="string"){let or=vt.startTime||parseInt(vt.id.split("-")[1])||Date.now(),$s=Date.now()-or;return{...vt,text:vt.text+we,isStreaming:!1,duration:$s}}return vt});return ee=!1,Me="agent-"+Date.now(),[...lt,{id:Me,role:"agent",text:ot,isStreaming:!0}]});continue}if(ee&&le)U(de=>{let we=!1,ot="",st=de.map(lt=>{if(lt.id===le){let vt=lt.text+Ae;if(vt.toLowerCase().includes("</think>")){we=!0;let or=vt.split(/<\/think>/gi);ot=or.slice(1).join("</think>")||"";let $s=lt.startTime||parseInt(lt.id.split("-")[1])||Date.now(),gc=Date.now()-$s;return{...lt,text:or[0],isStreaming:!1,duration:gc}}return{...lt,text:vt,isStreaming:!0}}return lt});return we?(ee=!1,Me="agent-"+Date.now(),[...st,{id:Me,role:"agent",text:ot.replace(/<\/?(think|thought)>/gi,""),isStreaming:!0}]):st});else if(!ee){let de=Ae.toLowerCase();!Yt&&de.includes("tool:functions.")&&(Yt=!0),Me?U(we=>we.map(ot=>ot.id===Me?{...ot,text:ot.text+Ae,isStreaming:!0}:ot)):(Me="agent-"+Date.now(),U(we=>[...we,{id:Me,role:"agent",text:Ae,isStreaming:!0}]))}}let tr=Date.now();Ms(H=>H+(tr-F))}catch(j){U(Z=>(Q(Z.length+1),[...Z,{id:"error-"+Date.now(),role:"system",text:`\u274C ERROR: ${j.message}`}]))}finally{if(Hr(!1),yr(null),k||process.stdout.isTTY&&(process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")),Ve.current){$t(Ve.current),X(null);let j=Ve.current;Ve.current=null,U(Z=>{let ne=[...Z],ee=ne.reverse().find(le=>le.text?.includes("[STEERING HINT: QUEUED]"));return ee&&(ee.text=ee.text.replace("[STEERING HINT: QUEUED]","[STEERING HINT: FINISHED_TURN]")),ne.reverse()}),z("resolution")}U(j=>{let Z=Date.now()-F,ne=!1,ee=[...j].reverse().map(Me=>{let Et=Me.isStreaming?{...Me,isStreaming:!1}:Me;return!ne&&Et.role==="agent"&&(ne=!0,Et={...Et,workedDuration:Z}),Et}).reverse(),le=ee.filter(Me=>!String(Me.id).startsWith("welcome")&&!Me.isMeta);return ds(be,null,le),Q(ee.length),ee})}})()}u(""),l(!1)}},Ce=Ur(()=>{if(a.startsWith("/")&&!b){let O=a.split(" "),N=O[O.length-1].toLowerCase();if(O.length===1){let $=N.startsWith("/")?N.slice(1):N;return ue.filter(R=>(R.cmd.startsWith("/")?R.cmd.slice(1):R.cmd).toLowerCase().includes($))}let M=ue;for(let $=0;$<O.length-1;$++){let R=O[$].toLowerCase(),k=M.find(F=>F.cmd.toLowerCase()===R);if(k&&k.subs)M=k.subs;else return[]}return M.filter($=>$.cmd.toLowerCase().includes(N))}let x=a.split(" "),g=x[x.length-1];if(g&&g.startsWith("@")&&!b){let O=g.indexOf("#"),N=O!==-1,M=N?g.substring(1,O).toLowerCase():g.slice(1).toLowerCase(),$=N?g.substring(O):"";return od(process.cwd()).filter(F=>F.name.toLowerCase().includes(M)).map(F=>{let W=F.relativePath.replace(/\\/g,"/");return{cmd:"@["+(W.startsWith(".")?W:"./"+W)+$+"]",desc:F.relativePath}})}return[]},[a,b]);to(()=>{T(0)},[Ce]);let rt=()=>{switch(qt){case"settings":return i.createElement(Vs,{systemSettings:Xe,setSystemSettings:Eo,apiTier:Ft,setActiveView:z,setInputConfig:So,saveSettings:Sn,quotas:no,setMessages:U,aiProvider:_});case"selectProvider":return i.createElement(fo,{title:"SELECT AI PROVIDER",items:[{label:"Google (Free/Paid)",value:"Google"},{label:"DeepSeek (Paid)",value:"DeepSeek"},{label:"OpenRouter (Free/Paid) [EXPERIMENTAL]",value:"OpenRouter"},{label:"NVIDIA [EXPERIMENTAL]",value:"NVIDIA"},{label:"Back",value:"settings"}],onSelect:async x=>{if(x.value==="settings"||x.value==="Back"){z("settings");return}let g=x.value,O=await Qr(g);if(O){K(g),ze(O),Br(O,{aiProvider:g,onIDEApproval:ko});let N="gemma-4-31b-it";g==="OpenRouter"?N="google/gemma-4-31b-it:free":g==="DeepSeek"?N="deepseek-v4-flash":g==="NVIDIA"&&(N="moonshotai/kimi-k2.6"),je(N),Sn({aiProvider:g,activeModel:N,apiTier:Ft,quotas:no}),U(M=>[...M,{role:"system",text:`\u2705 Switched to ${g}! Key loaded from Vault. Model set to ${N}.`,isMeta:!0}]),z("settings")}else So({label:`Enter ${g} API Key:`,key:"providerKey",provider:g,value:"",returnView:"settings"}),z("input")},onClose:()=>z("settings")});case"apiTier":return i.createElement(fo,{title:i.createElement(y,null,"SELECT YOUR CURRENT API TIER BASED ON ",i.createElement(y,{color:"cyan",underline:!0,bold:!0},"\x1B]8;;https://aistudio.google.com/projects\x07AI STUDIO\x1B]8;;\x07"),". (CURRENT: ",Ft.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"){z("settings");return}let g=x.value;oo(g),g==="Paid"?(So({label:"Enter Agent daily budget (requests made):",key:"quotas",subKey:"agentLimit",value:String(no.agentLimit)}),z("input")):(Sn({apiTier:g,quotas:no}),z("settings"))},onClose:()=>z("settings")});case"input":return i.createElement(I,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},i.createElement(I,{paddingX:1},i.createElement(y,{color:"magenta",bold:!0},"\u{1F527} DATA CONFIGURATION")),Bt?.note&&i.createElement(I,{paddingX:1,marginBottom:1},i.createElement(y,{color:"yellow",dimColor:!0,italic:!0},Bt.note)),i.createElement(I,{paddingX:1,flexDirection:"row"},i.createElement(y,{color:"cyan",bold:!0},Bt?.label," "),i.createElement(ic,{value:Bt?.value||"",onChange:x=>So(g=>({...g,value:x})),onSubmit:async x=>{let{key:g,subKey:O,next:N}=Bt,M={...no},$={};if(g==="quotas"){let R=O.toLowerCase().includes("limit")?parseInt(x)||0:x;M[O]=R,Rr(M),$.quotas=M}else if(g==="activeModel")je(x),$.activeModel=x;else if(g==="janitorModel")kt(x),$.janitorModel=x;else if(g==="autoApproveCommands"||g==="autoDisallowCommands"||g==="alwaysAskCommands"){let R={...Xe,[g]:x.trim(),sandboxPreset:"Custom"};Eo(R),$.systemSettings=R}else if(g==="externalDataPath"){let R={...Xe,useExternalData:!0,externalDataPath:x.trim()};Eo(R),$.systemSettings=R,U(k=>[...k,{id:Date.now(),role:"system",text:"\u{1F4C1} [EXTERNAL STORAGE] Flux Flow will use "+x.trim()+" for data after restart."}])}else if(g==="imageSettings"){let R=x.trim();if(R.startsWith("sk_")){let k={...Se,apiKey:R};Je(k),$.imageSettings=k,U(F=>(Q(F.length+1),[...F,{id:Date.now(),role:"system",text:"\u{1F511} [IMAGE KEY] Custom API key saved successfully.",isMeta:!0}]))}else Je(k=>({...k,keyType:"Default"})),$.imageSettings={...Se,keyType:"Default"},U(k=>(Q(k.length+1),[...k,{id:Date.now(),role:"system",text:"\u274C [IMAGE KEY ERROR] API key must start with sk_. Key strategy reset to Default.",isMeta:!0}]))}else if(g==="providerKey"){let R=x.trim(),k=Bt.provider;await Zr(k,R),K(k),ze(R),Br(R,{aiProvider:k,onIDEApproval:ko});let F="gemma-4-31b-it";k==="OpenRouter"?F="google/gemma-4-31b-it:free":k==="DeepSeek"?F="deepseek-v4-flash":k==="NVIDIA"&&(F="moonshotai/kimi-k2.6"),je(F),$.aiProvider=k,$.activeModel=F,U(W=>(Q(W.length+1),[...W,{id:Date.now(),role:"system",text:`\u2705 ${k} API Key saved successfully! Model set to ${F}.`,isMeta:!0}]))}N?So(N(g==="quotas"?M:x)):(Sn({...$,apiTier:Ft,quotas:M,imageSettings:$.imageSettings||Se}),So(null),z(Bt?.returnView||"settings"))}})),i.createElement(I,{paddingX:1,marginTop:1},i.createElement(y,{color:"gray",dimColor:!0,italic:!0},"(Press Enter to confirm selection)")));case"stats":return i.createElement(I,{flexDirection:"column",borderStyle:"round",paddingX:3,paddingY:1,width:Math.min(100,(r?.columns||100)-2)},i.createElement(I,{marginBottom:1},i.createElement(y,{color:"white",bold:!0,underline:!0},"SESSION TELEMETRY")),i.createElement(I,{flexDirection:"column"},i.createElement(I,null,i.createElement(I,{width:25},i.createElement(y,{color:"blue"},"Session Duration:")),i.createElement(y,{color:"white"},Ro(Date.now()-ta))),i.createElement(I,null,i.createElement(I,{width:25},i.createElement(y,{color:"blue"},"Agent Interactions:")),i.createElement(y,{color:"white"},pe)),i.createElement(I,{marginLeft:2},i.createElement(I,{width:23},i.createElement(y,{color:"grey"},"\xBB API Time:")),i.createElement(y,{color:"white"},Ro(Uo))),i.createElement(I,{marginLeft:2},i.createElement(I,{width:23},i.createElement(y,{color:"grey"},"\xBB Tool Time:")),i.createElement(y,{color:"white"},Ro(gr))),i.createElement(I,null,i.createElement(I,{width:25},i.createElement(y,{color:"blue"},"Background Tasks:")),i.createElement(y,{color:"white"},Fn)),i.createElement(I,null,i.createElement(I,{width:25},i.createElement(y,{color:"blue"},"Tokens Consumed:")),i.createElement(y,{color:"white"},ao(go))),go>0&&i.createElement(i.Fragment,null,i.createElement(I,{marginLeft:2},i.createElement(I,{width:23},i.createElement(y,{color:"grey"},"\xBB Input Tokens:")),i.createElement(y,{color:"white"},ao(go-wt))),he>0&&i.createElement(I,{marginLeft:4},i.createElement(I,{width:21},i.createElement(y,{color:"grey"},"\xBB Cached:")),i.createElement(y,{color:"white"},ao(he))),wt>0&&i.createElement(I,{marginLeft:2},i.createElement(I,{width:23},i.createElement(y,{color:"grey"},"\xBB Output Tokens:")),i.createElement(y,{color:"white"},ao(wt)))),zn>0&&i.createElement(i.Fragment,null,i.createElement(I,null,i.createElement(I,{width:25},i.createElement(y,{color:"blue"},"Images Made:")),i.createElement(y,{color:"white"},zn)),i.createElement(I,null,i.createElement(I,{width:25},i.createElement(y,{color:"blue"},"Image Credits:")),i.createElement(y,{color:"white"},Number(((As||0)*1e3).toFixed(0))," credits"))),i.createElement(I,null,i.createElement(I,{width:25},i.createElement(y,{color:"blue"},"Code Changes (Sess):")),i.createElement(y,{color:"white"},i.createElement(y,{color:"green"},"+",Cs)," ",i.createElement(y,{color:"red"},"-",ks))),i.createElement(I,null,i.createElement(I,{width:25},i.createElement(y,{color:"blue"},"Tool Calls (Sess):")),i.createElement(y,{color:"white"},Ut+Tt+ro," ( "),i.createElement(y,{color:"green"},"\u2713 ",Ut),i.createElement(y,{color:"white"}," "),i.createElement(y,{color:"yellow"},"\u2298 ",ro),i.createElement(y,{color:"white"}," "),i.createElement(y,{color:"red"},"\u2715 ",Tt),i.createElement(y,{color:"white"}," )"))),i.createElement(I,{flexDirection:"column",marginTop:1},i.createElement(y,{color:"white",bold:!0,underline:!0},"DAILY USAGE TRACKER"),i.createElement(I,{marginTop:1},i.createElement(I,{width:25},i.createElement(y,{color:"blue"},"Wall Time Today:")),i.createElement(y,{color:"white"},hn(Ke?.duration||0))),i.createElement(I,null,i.createElement(I,{width:25},i.createElement(y,{color:"blue"},"Agent Interactions:")),i.createElement(y,{color:"white"},Ke?.agent||0)),i.createElement(I,null,i.createElement(I,{width:25},i.createElement(y,{color:"blue"},"Background Tasks:")),i.createElement(y,{color:"white"},Ke?.background||0)),i.createElement(I,null,i.createElement(I,{width:25},i.createElement(y,{color:"blue"},"Tokens Used Today:")),i.createElement(y,{color:"white"},ao(Ke?.tokens||0))),(Ke?.tokens||0)>0&&i.createElement(i.Fragment,null,i.createElement(I,{marginLeft:2},i.createElement(I,{width:23},i.createElement(y,{color:"grey"},"\xBB Input Tokens:")),i.createElement(y,{color:"white"},ao((Ke?.tokens||0)-(Ke?.candidateTokens||0)))),(Ke?.cachedTokens||0)>0&&i.createElement(I,{marginLeft:4},i.createElement(I,{width:21},i.createElement(y,{color:"grey"},"\xBB Cached:")),i.createElement(y,{color:"white"},ao(Ke.cachedTokens))),(Ke?.candidateTokens||0)>0&&i.createElement(I,{marginLeft:2},i.createElement(I,{width:23},i.createElement(y,{color:"grey"},"\xBB Output Tokens:")),i.createElement(y,{color:"white"},ao(Ke.candidateTokens)))),(Ke?.imageCalls?.length||0)>0&&i.createElement(i.Fragment,null,i.createElement(I,null,i.createElement(I,{width:25},i.createElement(y,{color:"blue"},"Images Made Today:")),i.createElement(y,{color:"white"},Ke.imageCalls.length)),i.createElement(I,null,i.createElement(I,{width:25},i.createElement(y,{color:"blue"},"Image Credits Today:")),i.createElement(y,{color:"white"},Number(((Ke.imageCalls.reduce((x,g)=>x+g.cost,0)||0)*1e3).toFixed(0))," credits"))),i.createElement(I,null,i.createElement(I,{width:25},i.createElement(y,{color:"blue"},"Code Changes Today:")),i.createElement(y,{color:"white"},i.createElement(y,{color:"green"},"+",Ke?.linesAdded||0)," ",i.createElement(y,{color:"red"},"-",Ke?.linesRemoved||0))),i.createElement(I,null,i.createElement(I,{width:25},i.createElement(y,{color:"blue"},"Tool Calls Today:")),i.createElement(y,{color:"white"},(Ke?.toolSuccess||0)+(Ke?.toolFailure||0)+(Ke?.toolDenied||0)," ( "),i.createElement(y,{color:"green"},"\u2713 ",Ke?.toolSuccess||0),i.createElement(y,{color:"white"}," "),i.createElement(y,{color:"yellow"},"\u2298 ",Ke?.toolDenied||0),i.createElement(y,{color:"white"}," "),i.createElement(y,{color:"red"},"\u2715 ",Ke?.toolFailure||0),i.createElement(y,{color:"white"}," )"))),i.createElement(y,{dimColor:!0,marginTop:1,italic:!0},"(Press ESC to return to chat)"));case"autoExecDanger":return i.createElement(I,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:2,paddingY:1,width:"100%"},i.createElement(y,{color:"yellow",bold:!0,underline:!0},"\u26A0\uFE0F SECURITY WARNING: YOLO MODE"),i.createElement(y,{marginTop:1},"Turning this ON allows the agent to execute terminal commands automatically without requiring your approval for each step."),i.createElement(y,{marginTop:1,color:"yellow"},"RISKS INVOLVED:"),i.createElement(y,null,"\u2022 The agent may execute destructive commands (rm -rf, etc.) by mistake."),i.createElement(y,null,"\u2022 Unintended system changes if the agent hallucinates a path or command."),i.createElement(y,null,"\u2022 Reduced control over the agent's step-by-step decision making."),i.createElement(I,{marginTop:1},i.createElement(fo,{title:"Confirm Intent",items:[{label:"I know the risk and turning on intentionally",value:"on"},{label:"Keep Off (Recommended)",value:"off"}],onSelect:x=>{x.value==="on"&&Eo(g=>({...g,autoExec:!0})),z("settings")}})));case"externalDanger":return i.createElement(I,{flexDirection:"column",borderStyle:"round",borderColor:"red",paddingX:2,paddingY:1,width:"100%"},i.createElement(y,{color:"red",bold:!0,underline:!0},"\u26A0\uFE0F SECURITY WARNING: EXTERNAL WORKSPACE ACCESS"),i.createElement(y,{marginTop:1},"Turning this ON allows the agent to execute tools (Read/Write/Exec) outside of the current active workspace directory."),i.createElement(y,{marginTop:1,color:"yellow"},"RISKS INVOLVED:"),i.createElement(y,null,"\u2022 Access to sensitive system files (SSH keys, Browser data, etc.)"),i.createElement(y,null,"\u2022 Potential for accidental or malicious deletion of OS-critical files."),i.createElement(y,null,"\u2022 Unauthorized script execution across your entire file system."),i.createElement(I,{marginTop:1},i.createElement(fo,{title:"Confirm Intent",items:[{label:"I know the risk and turning on intentionally",value:"on"},{label:"Keep Off (Recommended)",value:"off"}],onSelect:x=>{x.value==="on"&&Eo(g=>({...g,allowExternalAccess:!0})),z("settings")}})));case"doubleDanger":return i.createElement(I,{flexDirection:"column",borderStyle:"round",borderColor:"red",paddingX:2,paddingY:1,width:"100%"},i.createElement(y,{color:"red",bold:!0,underline:!0},"\u26D4 CRITICAL SECURITY WARNING: COMBINED SYSTEM RISK"),i.createElement(y,{marginTop:1},"You are attempting to enable BOTH [YOLO Mode] and [External Workspace Access] simultaneously."),i.createElement(y,{marginTop:1,color:"red",bold:!0},"THIS IS NOT RECOMMENDED."),i.createElement(y,{marginTop:1,color:"yellow"},"THE CRITICAL RISK:"),i.createElement(y,null,"The agent will have the power to execute any command across your entire system WITHOUT your approval or supervision."),i.createElement(y,{color:"red",italic:!0,marginTop:1},"A single hallucination or error could result in full system wipe or data theft."),i.createElement(I,{marginTop:1},i.createElement(fo,{title:"Final Confirmation",items:[{label:"I agree knowing the consequences",value:"on"},{label:"Keep Off",value:"off"}],onSelect:x=>{x.value==="on"&&Eo(g=>({...g,autoExec:!0,allowExternalAccess:!0})),z("settings")}})));case"key":return i.createElement(fo,{title:"\u{1F511} API KEY MANAGEMENT",items:[{label:"Edit Current Key (Update)",value:"edit"},{label:"Remove Current Key (Purge)",value:"remove"},{label:"Cancel",value:"Cancel"}],onSelect:x=>{if(x.value==="edit"){ze(null),z("chat");let g=ve(2);U(O=>[...O,{id:Date.now(),role:"system",text:`\u{1F511}${g}[ACTION] Flux waiting for new API Key...`}])}else x.value==="remove"?z("deleteKey"):z("chat")}});case"deleteKey":return i.createElement(I,{flexDirection:"column",borderStyle:"round",borderColor:"red",paddingX:2,paddingY:1},(()=>{let x=ve(2);return i.createElement(y,{color:"red",bold:!0},"\u26D4",x,"DANGER: PURGE API KEY")})(),i.createElement(y,{marginTop:1},"This will permanently delete the saved API key from the project vault. You will need to enter it again to use Flux."),i.createElement(I,{marginTop:1},i.createElement(fo,{title:"Are you absolutely sure?",items:[{label:"YES, PURGE KEY",value:"yes"},{label:"NO, GO BACK",value:"no"}],onSelect:async x=>{if(x.value==="yes"){await _s(),ze(null),z("chat");let g=ve(2);U(O=>[...O,{id:Date.now(),role:"system",text:`\u2728${g}[VAULT PURGED] API Key removed successfully.`}])}else z("key")}})));case"exit":return null;case"ask":return i.createElement(I,{width:"100%"},i.createElement(La,{question:Le?.question,options:Le?.options,onResolve:x=>{Le?.resolve&&Le.resolve(x),pt(null),z("chat")}}));case"revert":return i.createElement(I,{width:"100%",alignItems:"center",justifyContent:"center"},i.createElement(Zi,{prompts:Gr,onSelect:async x=>{try{let g=await Ct.rollbackToBefore(x);if(g.success){let{targetPrompt:O}=g;Rl(be);let N=gt.findIndex(k=>k.role==="user"&&k.text&&(k.text.startsWith(O)||k.text.includes(O))),M=[...gt];N!==-1&&(M=gt.slice(0,N)),U(M),Q(M.length),u(O),l(O.split(`
|
|
599
|
+
`).length>2);let $=M.filter(k=>!String(k.id).startsWith("welcome")&&!k.isMeta);await ds(be,null,$);let R=ve(2);U(k=>{let F=[...k,{id:"revert-ok-"+Date.now(),role:"system",text:`\u{1F504}${R}[TIME TRAVEL] Codebase rolled back successfully! Reverted prompt loaded to input box.`,isMeta:!0}];return Q(F.length),F}),z("chat")}}catch(g){let O=ve(2);U(N=>{let M=[...N,{id:"revert-err-"+Date.now(),role:"system",text:`\u274C${O}[TIME TRAVEL ERROR] Failed to rollback: ${g.message}`,isMeta:!0}];return Q(M.length),M}),z("chat")}},onClose:()=>z("chat")}));case"resume":return i.createElement(I,{width:"100%",alignItems:"center",justifyContent:"center"},i.createElement(Ki,{onSelect:async x=>{let g=await Po();if(g[x]){r.write("\x1B[2J\x1B[3J\x1B[H"),fe(x);let O=[...g[x].messages];O[0]?.text?.includes("\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557")||O.unshift({id:"welcome-"+Date.now(),role:"system",text:hr+`
|
|
591
600
|
|
|
592
|
-
\u{1F30A}\u26A1 Resuming Flux Flow Session...`,isMeta:!0}),
|
|
593
|
-
\u{1F680} **Restart Flux Flow to see changes.**`,isMeta:!0}])),
|
|
601
|
+
\u{1F30A}\u26A1 Resuming Flux Flow Session...`,isMeta:!0}),U(O),z("chat"),U(M=>{let $=[...M,{id:"sys-"+Date.now(),role:"system",text:`\u{1F4E1} SESSION RESUMED: [${x}]`,isMeta:!0}];return Q($.length),$})}},onDelete:async x=>await ti(x),onClose:()=>z("chat")}));case"memory":return i.createElement(I,{width:"100%",alignItems:"center",justifyContent:"center"},i.createElement(qi,{onClose:()=>z("chat")}));case"parserDownload":return i.createElement(I,{width:"100%",alignItems:"center",justifyContent:"center"},i.createElement(zi,{onClose:()=>z("settings")}));case"profile":return i.createElement(zs,{initialData:Qo,onSave:x=>{ce(x),U(g=>[...g,{id:Date.now(),role:"system",text:`\u2705 Profile updated: ${x.name} (${x.nickname})`}]),z("chat")},onCancel:()=>z("chat")});case"resolution":return i.createElement(I,{width:"100%",alignItems:"center",justifyContent:"center"},i.createElement(ed,{data:ht,onResolve:x=>{$t(null),z("chat"),setTimeout(()=>{Pe(x,!0)},500)},onEdit:x=>{$t(null),z("chat"),u(x)}}));case"approval":return i.createElement(I,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:2,paddingY:1,width:"100%"},i.createElement(y,{color:"yellow",bold:!0,underline:!0},"\u{1F510} SECURITY GATE: FILE WRITE PERMISSION"),i.createElement(y,{marginTop:1},"The agent is attempting to modify: ",i.createElement(y,{color:"cyan"},re(xe?.args||"{}").path||"Unknown File")),Ko()?i.createElement(I,{marginTop:1,paddingX:1},i.createElement(y,{color:"cyan",italic:!0},"\u26A1\uFE0F FluxFlow Companion is active. Review the changes in your editor.")):i.createElement(I,{marginTop:1,borderStyle:"single",borderColor:"#333",paddingX:1,flexDirection:"column"},i.createElement(y,{color:"gray"},"--- PROPOSED CONTENT / DIFF ---"),(()=>{let x=re(xe?.args||"{}"),g=[],O=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 k=R[2]?parseInt(R[2]):1;O.add(k)}}),Array.from(O).sort(($,R)=>$-R).forEach($=>{let R,k;$===1?(R=x.replaceContent1??x.content_to_replace1??x.replaceContent??x.content_to_replace??x.TargetContent??null,k=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,k=x[`newContent${$}`]??x[`content_to_add${$}`]??null),(R!==null||k!==null)&&g.push({replace:R,new:k})}),g.length>0)return i.createElement(I,{flexDirection:"column",marginTop:1},g.map(($,R)=>{let k=$.replace!==null,F=$.new!==null;return i.createElement(I,{key:R,flexDirection:"column",marginTop:R>0?1:0},g.length>1&&i.createElement(y,{color:"gray"},"Block ",R+1,":"),k&&i.createElement(I,null,i.createElement(y,{color:"red",wrap:"anywhere",bold:!0},"- ",$.replace)),F&&i.createElement(I,{marginTop:k?1:0},i.createElement(y,{color:"green",wrap:"anywhere",bold:!0},"+ ",$.new.replace(/\[\/n\]?/g,"\\n"))))}));let M=x.content||x.ReplacementContent||x.content_to_add||x.replacementContent||x.newContent||null;return i.createElement(y,{color:"white",wrap:"anywhere"},(M?M.replace(/\[\/n\]?/g,"\\n"):null)||"Updating file content...")})()),i.createElement(I,{marginTop:1},i.createElement(fo,{title:"Action Required",items:[{label:"\u2705 Accept this time",value:"allow"},{label:"\u{1F510} Accept for this session",value:"always"},{label:"\u274C Don't accept",value:"deny"}],onSelect:x=>{x.value==="always"&&ae(!0);let g=x.value==="deny"?"deny":"allow";xe.resolve(g),Qe(null),z("chat")}})));case"updateManager":return i.createElement(fo,{title:"Select Preferred Update Manager",subtitle:"NOTE: If you are unsure about these, go with NPM",items:[{label:"NPM (Standard)",value:"npm"},{label:"PNPM (Recommended)",value:"pnpm"},{label:"BUN (Ultra Fast)",value:"bun"},{label:"YARN (Classic)",value:"yarn"},{label:"Custom Command",value:"custom"},{label:"Back",value:"settings"}],onSelect:x=>{if(x.value==="settings"||x.value==="Back"){z("settings");return}x.value==="custom"?(So({label:"Enter Custom Update Command (Global install recommended):",key:"customUpdateCommand",value:Xe.customUpdateCommand,next:g=>(Eo(O=>({...O,updateManager:"custom",customUpdateCommand:g})),null)}),z("input")):(Eo(g=>({...g,updateManager:x.value})),z("settings"))}});case"update":return i.createElement(Vl,{latest:Te,current:Ln,settings:Xe,onClose:()=>z("chat"),onSuccess:()=>{U(x=>(Q(x.length+1),[...x,{id:"update-success-"+Date.now(),role:"system",text:`\u2728 **[UPDATE COMPLETED]** Flux Flow successfully upgraded to v${Te}.
|
|
602
|
+
\u{1F680} **Restart Flux Flow to see changes.**`,isMeta:!0}])),z("chat")},onUpdateSettings:x=>{z("updateManager")}});case"terminalApproval":return i.createElement(I,{flexDirection:"column",borderStyle:"round",borderColor:"red",paddingX:2,paddingY:1,width:"100%"},i.createElement(y,{color:"red",bold:!0,underline:!0},"\u{1F510} SECURITY GATE: TERMINAL COMMAND OVERSIGHT"),i.createElement(I,{marginTop:1},i.createElement(y,null,"Agent requested to run: ",i.createElement(y,{color:"yellow",bold:!0},re(xe?.args||"{}").command||"Unknown Command"))),i.createElement(I,{marginTop:1},i.createElement(fo,{title:"Risk Assessment Required",items:[{label:"\u{1F680} Run",value:"allow"},{label:"\u274C Deny",value:"deny"}],onSelect:x=>{xe.resolve(x.value),Qe(null),z("chat")}})));default:return i.createElement(I,{flexDirection:"column",marginTop:1,flexShrink:0,width:"100%"},i.createElement(I,{paddingX:1,marginBottom:0,justifyContent:"space-between",width:"100%"},i.createElement(I,null,en?i.createElement(I,null,_n&&!_n&&i.createElement(Zu,null),i.createElement(y,{color:"magenta",bold:!0,italic:!0},_n&&!_n?" ":"",en.toUpperCase()),Zn&&i.createElement(y,{color:"gray",dimColor:!0,italic:!0}," ",Zn)):i.createElement(y,{color:"cyan",dimColor:!0,italic:!0}," ",a.length>0&&Bn?"Press ESC again to clear input":"READY FOR COMMAND...")),i.createElement(I,null,i.createElement(y,{color:"gray",bold:!0},"[ "),i.createElement(y,{color:"white"},Re||Ye),i.createElement(y,{color:"gray",bold:!0}," ]"))),i.createElement(I,{borderStyle:"round",borderColor:tn?"magenta":"cyan",paddingX:1,paddingY:0,width:"100%"},i.createElement(I,{flexDirection:"column",width:"100%"},i.createElement(I,{flexDirection:"row",width:"100%",paddingY:0},i.createElement(I,{flexShrink:0,width:4},i.createElement(y,{color:tn?"magenta":"cyan",bold:!0},tn?"\u2726 ":"\u{1F4A0} ")),i.createElement(I,{flexGrow:1},i.createElement(I,{flexGrow:1,position:"relative"},a===""&&i.createElement(I,{position:"absolute",paddingLeft:0},_e&&!dt?i.createElement(y,{color:"yellow"},na?" Terminal is waiting for user input. Press TAB to interact":" Press TAB to interact with terminal..."):_e&&dt?i.createElement(y,{color:"yellow",bold:!0}," [ TERMINAL FOCUSED ] Type to interact, press TAB to exit..."):Bn===1?i.createElement(y,{color:"cyan",bold:!0}," Press ESC again to ",a.length>0?"clear input":"revert codebase to checkpoint","..."):i.createElement(y,{color:"gray"},Nn?" Press ESC again to cancel the request.":tn?" Enter a prompt to steer the agent.":` Send message or /cmd ... (${Os.shortcut} for newline), @file`)),i.createElement(pa,{key:`input-${f}`,focus:!dt,showCursor:We,lastFocusEventTime:Nt.current,value:a,columns:h.columns,onChange:x=>{let g=x.replace(/\r\n/g,`
|
|
594
603
|
`).replace(/\r/g,`
|
|
595
604
|
`).replace(/\\\s*\n/g,`
|
|
596
|
-
`);u(g),O(!1)},onSubmit:Xe,maxRows:3,keyBindings:{submit:x=>x.return&&!x.shift&&!x.ctrl,newline:x=>x.return&&x.shift||x.return&&x.ctrl}})))))))}};return i.createElement(k,{flexDirection:"column",width:"100%"},P?i.createElement(Ku,{width:r?.columns||80,height:r?.rows||24,selectedIndex:A}):i.createElement(i.Fragment,null,i.createElement(k,{flexDirection:"column",width:"100%",flexGrow:1},jr.items.map((x,g)=>i.createElement(Ws,{key:x.id||g,msg:x,showFullThinking:me,columns:r?.columns||80}))),i.createElement(k,{flexDirection:"column",padding:1,width:"100%"},(Qt==="chat"||["ask","approval","terminalApproval"].includes(Qt))&&i.createElement(k,{flexDirection:"column",width:"100%"},i.createElement(wa,{messages:Fe.slice(wr),showFullThinking:me,columns:Math.max(20,(r?.columns||80)-1)}),wt&&i.createElement(k,{marginTop:1},i.createElement(ss,{command:wt,output:eo,isFocused:It,isPty:$o}))),Se?i.createElement(k,{borderStyle:"double",borderColor:"magenta",padding:1,flexShrink:0},i.createElement(y,{color:"magenta"},"\u{1F30A} Starting Flux Flow...")):be?At():i.createElement(k,{borderStyle:"round",borderColor:"gray",padding:0,flexDirection:"column",flexShrink:0,width:"100%"},i.createElement(k,{paddingX:1,marginBottom:1},i.createElement(y,{color:"yellow",bold:!0},"\u{1F511}",Oe(2),"API KEY REQUIRED")),i.createElement(k,{paddingX:1,flexDirection:"column"},ft===0?i.createElement(i.Fragment,null,i.createElement(y,null,"Select your Preferred Provider:"),i.createElement(k,{marginTop:1},i.createElement(fo,{items:[{label:"Google (Free/Paid)",value:"Google"},{label:"DeepSeek (Paid)",value:"DeepSeek"},{label:"OpenRouter (Free/Paid) [EXPERIMENTAL]",value:"OpenRouter"},{label:"NVIDIA [EXPERIMENTAL]",value:"NVIDIA"}],onSelect:x=>{J(x.value),de(1)}}))):i.createElement(i.Fragment,null,i.createElement(y,null,"Please enter your ",N," API Key to initialize the agent (If billing is enabled set Tier to paid in /settings \u2192 other \u2192 API Tier)."),i.createElement(k,{marginTop:1},i.createElement(y,{color:"cyan",bold:!0},"\u{1F4A0} "),i.createElement(nc,{value:Mo,onChange:co,onSubmit:ie,mask:"*"})),i.createElement(k,{marginTop:1},i.createElement(y,{color:"gray",italic:!0},"(Press ESC to go back to provider selection)")))),i.createElement(k,{paddingX:1,marginTop:1},i.createElement(y,{color:"gray",dimColor:!0,italic:!0},ft===0?"(Use arrows to select and Enter to confirm)":"(Press Enter to confirm and initialize)"))),o&&i.createElement(k,{borderStyle:"round",borderColor:"red",paddingX:2,marginY:0,width:"100%"},i.createElement(y,{color:"red",bold:!0},"\u{1F534} EXIT CONFIRMATION: "),i.createElement(y,{color:"white"},"Press "),i.createElement(y,{color:"red",bold:!0},"CTRL + C"),i.createElement(y,{color:"white"}," again to exit (",n,"s). Press "),i.createElement(y,{color:"cyan",bold:!0},"ESC"),i.createElement(y,{color:"white"}," to cancel.")),i.createElement(k,{flexShrink:0,width:"100%"},i.createElement(Sa,{mode:d,thinkingLevel:Y,tokens:he.tokens,tokensTotal:he.tokens,chatId:We,isMemoryEnabled:Ht.memory,apiTier:He,aiProvider:N})),Qt==="exit"&&(()=>{let x=Date.now()-Zi,g=et+Xt,D=g>0?(et/g*100).toFixed(1):"0.0",_=mr+Vn,M=_>0?(mr/_*100).toFixed(1):"0.0",$=_>0?(Vn/_*100).toFixed(1):"0.0";return i.createElement(k,{flexDirection:"column",borderStyle:"round",paddingX:3,paddingY:1,borderColor:"red",width:Math.min(100,(r?.columns||100)-2),marginTop:0,marginBottom:0},i.createElement(k,{marginBottom:1},i.createElement(y,{bold:!0},ic(["blue","purple"])("Agent powering down. Goodbye!"))),i.createElement(k,{flexDirection:"column"},i.createElement(y,{color:"white",bold:!0,underline:!0},"Interaction Summary"),i.createElement(k,{marginTop:1},i.createElement(k,{width:20},i.createElement(y,{color:"blue"},"Session ID:")),i.createElement(y,{color:"white"},We)),i.createElement(k,null,i.createElement(k,{width:20},i.createElement(y,{color:"blue"},"Tool Calls:")),i.createElement(y,{color:"white"},et+Xt+Uo," ( ",i.createElement(y,{color:"green"},"\u2713 ",et)," ",i.createElement(y,{color:"yellow"},"\u2298 ",Uo)," ",i.createElement(y,{color:"red"},"\u2715 ",Xt)," )")),i.createElement(k,null,i.createElement(k,{width:20},i.createElement(y,{color:"blue"},"Success Rate:")),i.createElement(y,{color:"white"},D,"%")),i.createElement(k,null,i.createElement(k,{width:20},i.createElement(y,{color:"blue"},"Code Changes:")),i.createElement(y,{color:"white"},i.createElement(y,{color:"green"},"+",bs)," ",i.createElement(y,{color:"red"},"-",Cs))),i.createElement(k,null,i.createElement(k,{width:20},i.createElement(y,{color:"blue"},"Tokens Consumed:")),i.createElement(y,{color:"white"},so(ae))),ae>0&&i.createElement(i.Fragment,null,i.createElement(k,{marginLeft:2},i.createElement(k,{width:18},i.createElement(y,{color:"grey"},"\xBB Input Tokens:")),i.createElement(y,{color:"white"},so(ae-yt))),st>0&&i.createElement(k,{marginLeft:4},i.createElement(k,{width:16},i.createElement(y,{color:"grey"},"\xBB Cached:")),i.createElement(y,{color:"white"},so(st))),yt>0&&i.createElement(k,{marginLeft:2},i.createElement(k,{width:18},i.createElement(y,{color:"grey"},"\xBB Output Tokens:")),i.createElement(y,{color:"white"},so(yt)))),pr>0&&i.createElement(i.Fragment,null,i.createElement(k,null,i.createElement(k,{width:20},i.createElement(y,{color:"blue"},"Images Made:")),i.createElement(y,{color:"white"},pr)),i.createElement(k,null,i.createElement(k,{width:20},i.createElement(y,{color:"blue"},"Image Credits:")),i.createElement(y,{color:"white"},Number(((On||0)*1e3).toFixed(0))," credits")))),i.createElement(k,{flexDirection:"column",marginTop:1},i.createElement(y,{color:"white",bold:!0,underline:!0},"Performance"),i.createElement(k,{marginTop:1},i.createElement(k,{width:20},i.createElement(y,{color:"blue"},"Wall Time:")),i.createElement(y,{color:"white"},en(x))),i.createElement(k,null,i.createElement(k,{width:20},i.createElement(y,{color:"blue"},"Agent Active:")),i.createElement(y,{color:"white"},en(_))),i.createElement(k,{marginLeft:2},i.createElement(k,{width:18},i.createElement(y,{color:"grey"},"\xBB API Time:")),i.createElement(y,{color:"white"},en(mr)," (",M,"%)")),i.createElement(k,{marginLeft:2},i.createElement(k,{width:18},i.createElement(y,{color:"grey"},"\xBB Tool Time:")),i.createElement(y,{color:"white"},en(Vn)," (",$,"%)"))))})(),Ae.length>0&&(()=>{let g=Math.max(0,Math.min(w-2,Ae.length-5)),D=Ae.slice(g,g+5),_=Ae.length-(g+D.length);return i.createElement(k,{flexDirection:"column",borderStyle:"round",borderColor:"gray",paddingX:0,paddingY:0,width:"100%"},i.createElement(k,{paddingX:1,marginBottom:0,justifyContent:"space-between",width:"100%"},i.createElement(y,{color:"gray",bold:!0,dimColor:!0},Ae[0]?.cmd?.startsWith("@")?"\u{1F4C1} FILE SUGGESTIONS":"\u{1F50D} COMMAND SUGGESTIONS"),Ae[0]?.cmd?.startsWith("@")?i.createElement(y,{color:"gray",dimColor:!0,italic:!0},"(Use '#Lstart-Lend' to specify line numbers)"):l.startsWith("/model")&&He==="Free"?(()=>{let M="https://aistudio.google.com/billing",$="billing";return N==="DeepSeek"?(M="https://platform.deepseek.com/usage",$="billing"):N==="OpenRouter"?(M="https://openrouter.ai/settings/profile",$="profile"):N==="NVIDIA"&&(M="https://build.nvidia.com/settings/api-keys",$="billing"),i.createElement(y,{color:"gray",dimColor:!0,italic:!0},"Paid API has more models. Configure ",i.createElement(y,{color:"cyan",underline:!0},`\x1B]8;;${M}\x07${$}\x1B]8;;\x07`)," & /settings")})():null),D.map((M,$)=>{let C=g+$===w,L=M.cmd==="gemma-4-31b-it"&&He!=="Free";return i.createElement(k,{key:M.cmd,flexDirection:"row",backgroundColor:C?"#2a2a2a":void 0,paddingX:1},i.createElement(k,{width:3},i.createElement(y,{color:C?"cyan":"gray",bold:C},C?" \u276F":" ")),i.createElement(k,{width:55},i.createElement(y,{color:L?"gray":C?"yellow":"white",bold:C,dimColor:L&&!C},M.cmd?.startsWith("@[")&&M.cmd?.endsWith("]")?(()=>{let j=M.cmd.slice(2,-1).split(/[/\\]/);return j[j.length-1]})():M.cmd)),i.createElement(k,{flexGrow:1},i.createElement(y,{color:"gray",italic:!0,dimColor:!C},M.desc)))}),Ae.length>5&&i.createElement(k,{paddingX:1,height:1},_>0?i.createElement(y,{color:"gray",dimColor:!0,italic:!0}," ... (",_," more commands available)"):i.createElement(y,{color:"gray",dimColor:!0,italic:!0}," (End of list)")))})())))}var ks,ac,Ku,Zi,rc,bs,Cs,Vu,lc,Dn,qu,sc,zu,Ju,dr,Qu,Zu,dc=re(async()=>{fa();Ta();Ea();ba();await Ma();va();Oa();kr();await Ul();es();$r();Rl();Wl();await Xl();Vl();un();ql();zl();Jl();fs();Rs();qt();Yt();rn();await Or();tc();Rn();Pi();ks=()=>{let e=(process.env.TERM_PROGRAM||"").toLowerCase();if(process.env.WT_SESSION)return"Windows Terminal";let o=t=>{let n=t.toLowerCase();for(let[s,r]of Object.entries(process.env))if(!["PATH","PWD","CWD","PS1","LS_COLORS","PROMPT"].includes(s)&&String(r).toLowerCase().includes(n))return!0;return!1};return e==="cursor"||process.env.CURSOR_SETTINGS_DIR||o("cursor")?"Cursor":e==="windsurf"||o("windsurf")?"Windsurf":o("antigravity")?"Antigravity":e==="trae"||o("trae")?"Trae":e==="codium"||o("codium")||o("vscode-oss")?"VSCodium":o("positron")?"Positron":e==="vscode"||process.env.VSCODE_GIT_IPC_HANDLE||o("vscode")?"VS Code":process.env.INTELLIJ_TERMINAL_COMMAND_BLOCKS||o("intellij")?"JetBrains":"Terminal"},ac=e=>{let o=e==="VS Code",t=[];return o?(t.push({label:"Install Manually (VSIX)",url:"https://github.com/KushalRoyChowdhury/fluxflow-cli/releases"}),t.push({label:"Install from VS Code Marketplace",url:"https://marketplace.visualstudio.com/items?itemName=fluxflow-cli.fluxflow-cli-companion"})):t.push({label:`Download for ${e} (GitHub)`,url:"https://github.com/KushalRoyChowdhury/fluxflow-cli/releases"}),t.push({label:"Continue to CLI only",action:"dismiss"}),t},Ku=({width:e,height:o,selectedIndex:t})=>{let n=ks(),s=ac(n);return i.createElement(k,{flexDirection:"column",alignItems:"center",justifyContent:"center",width:e,height:o},i.createElement(k,{marginBottom:1},i.createElement(y,null,dr)),i.createElement(k,{flexDirection:"column",borderStyle:"double",borderColor:"cyan",paddingX:3,paddingY:1,width:Math.min(80,e-4)},i.createElement(y,{bold:!0,color:"cyan",textAlign:"center"},"\u{1F680} UPGRADE YOUR WORKFLOW"),i.createElement(k,{marginY:1,flexDirection:"column",alignItems:"left"},i.createElement(y,null,"You're in ",i.createElement(y,{bold:!0,color:"cyan"},n),", but the ",i.createElement(y,{bold:!0,color:"magenta"},"FluxFlow-CLI Companion")," is not installed."),i.createElement(k,{flexDirection:"column",marginY:1},i.createElement(y,{color:"gray"}," \u2705 Real-time file & cursor tracking"),i.createElement(y,{color:"gray"}," \u2705 Auto-open files created by agent"),i.createElement(y,{color:"gray"}," \u2705 Native DIFF viewer for AI edits"),i.createElement(y,{color:"gray"}," \u2705 Direct IDE context sharing"),i.createElement(y,{color:"gray"}," \u2705 Surgical Diagnostic Sync"),i.createElement(y,{color:"gray"}," \u2705 Native Right-Click \u276F Chat integration"),i.createElement(y,{color:"gray"}," \u2705 Live Status in IDE"),i.createElement(y,{color:"gray"}," \u2705 Clickable terminal-to-code links"))),i.createElement(k,{flexDirection:"column",marginTop:1},s.map((r,l)=>i.createElement(k,{key:l},i.createElement(y,{color:t===l?"yellow":"white",bold:t===l},t===l?" \u276F ":" ",r.label)))),i.createElement(k,{marginTop:1,alignItems:"center",justifyContent:"center"},i.createElement(y,{dimColor:!0,italic:!0},"(Use arrows to navigate, Enter to select)"))))},Zi=Date.now(),rc="https://fluxflow-cli.onrender.com/changelog.html",bs=0,Cs=0,Vu=Xn.join(Xn.dirname(Xu(import.meta.url)),"../package.json"),lc=JSON.parse(ao.readFileSync(Vu,"utf8")),Dn=lc.version,qu=lc.date||"2026-05-20",sc=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],zu=()=>{let[e,o]=z(0);return io(()=>{let t=setInterval(()=>{o(n=>(n+1)%1e3)},33);return()=>clearInterval(t)},[]),i.createElement(y,{color:"magenta"},sc[Math.floor(e/3)%sc.length])},Ju=({data:e,onResolve:o,onEdit:t})=>i.createElement(k,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},i.createElement(k,{paddingX:1},i.createElement(y,{color:"magenta",bold:!0,underline:!0},"\u{1F7E3} STEERING HINT RESOLUTION")),i.createElement(k,{paddingX:1,marginTop:1},i.createElement(y,null,"The agent already finished the task before your hint was consumed.")),i.createElement(k,{marginTop:1,backgroundColor:"#222",paddingX:2,width:"100%"},i.createElement(y,{italic:!0,color:"gray"},'"',e,'"')),i.createElement(k,{paddingX:1,marginTop:1},i.createElement(y,{color:"cyan"},"How would you like to proceed?")),i.createElement(k,{marginTop:0},i.createElement(fo,{title:"Select Action",items:[{label:"Send Anyway",value:"send"},{label:"Edit Prompt",value:"edit"}],onSelect:n=>{n==="send"?o(e):t(e)}}))),dr=ic(["#00ffff","#0077ff","#ff00ff"]).multiline(`\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2557
|
|
605
|
+
`);u(g),L(!1)},onSubmit:Pe,maxRows:3,keyBindings:{submit:x=>x.return&&!x.shift&&!x.ctrl,newline:x=>x.return&&x.shift||x.return&&x.ctrl}})))))))}};return i.createElement(I,{flexDirection:"column",width:"100%"},P?i.createElement(zu,{width:r?.columns||80,height:r?.rows||24,selectedIndex:v}):i.createElement(i.Fragment,null,i.createElement(I,{flexDirection:"column",width:"100%",flexGrow:1},Xr.items.map((x,g)=>i.createElement(Ys,{key:x.id||g,msg:x,showFullThinking:me,columns:r?.columns||80}))),i.createElement(I,{flexDirection:"column",padding:1,width:"100%"},(qt==="chat"||["ask","approval","terminalApproval"].includes(qt))&&i.createElement(I,{flexDirection:"column",width:"100%"},i.createElement(Sa,{messages:gt.slice(er),showFullThinking:me,columns:Math.max(20,(r?.columns||80)-1)}),_e&&i.createElement(I,{marginTop:1},i.createElement(is,{command:_e,output:Mt,isFocused:dt,isPty:Fo}))),Ne?i.createElement(I,{borderStyle:"double",borderColor:"magenta",padding:1,flexShrink:0},i.createElement(y,{color:"magenta"},"\u{1F30A} Starting Flux Flow...")):Ge?rt():i.createElement(I,{borderStyle:"round",borderColor:"gray",padding:0,flexDirection:"column",flexShrink:0,width:"100%"},i.createElement(I,{paddingX:1,marginBottom:1},i.createElement(y,{color:"yellow",bold:!0},"\u{1F511}",ve(2),"API KEY REQUIRED")),i.createElement(I,{paddingX:1,flexDirection:"column"},Ue===0?i.createElement(i.Fragment,null,i.createElement(y,null,"Select your Preferred Provider:"),i.createElement(I,{marginTop:1},i.createElement(fo,{items:[{label:"Google (Free/Paid)",value:"Google"},{label:"DeepSeek (Paid)",value:"DeepSeek"},{label:"OpenRouter (Free/Paid) [EXPERIMENTAL]",value:"OpenRouter"},{label:"NVIDIA [EXPERIMENTAL]",value:"NVIDIA"}],onSelect:x=>{K(x.value),se(1)}}))):i.createElement(i.Fragment,null,i.createElement(y,null,"Please enter your ",_," API Key to initialize the agent (If billing is enabled set Tier to paid in /settings \u2192 other \u2192 API Tier)."),i.createElement(I,{marginTop:1},i.createElement(y,{color:"cyan",bold:!0},"\u{1F4A0} "),i.createElement(ic,{value:yt,onChange:co,onSubmit:Sr,mask:"*"})),i.createElement(I,{marginTop:1},i.createElement(y,{color:"gray",italic:!0},"(Press ESC to go back to provider selection)")))),i.createElement(I,{paddingX:1,marginTop:1},i.createElement(y,{color:"gray",dimColor:!0,italic:!0},Ue===0?"(Use arrows to select and Enter to confirm)":"(Press Enter to confirm and initialize)"))),o&&i.createElement(I,{borderStyle:"round",borderColor:"red",paddingX:2,marginY:0,width:"100%"},i.createElement(y,{color:"red",bold:!0},"\u{1F534} EXIT CONFIRMATION: "),i.createElement(y,{color:"white"},"Press "),i.createElement(y,{color:"red",bold:!0},"CTRL + C"),i.createElement(y,{color:"white"}," again to exit (",n,"s). Press "),i.createElement(y,{color:"cyan",bold:!0},"ESC"),i.createElement(y,{color:"white"}," to cancel.")),i.createElement(I,{flexShrink:0,width:"100%"},i.createElement(ba,{mode:d,thinkingLevel:B,tokens:Ee.tokens,tokensTotal:Ee.tokens,chatId:be,isMemoryEnabled:Xe.memory,apiTier:Ft,aiProvider:_})),qt==="exit"&&(()=>{let x=Date.now()-ta,g=Ut+Tt,O=g>0?(Ut/g*100).toFixed(1):"0.0",N=Uo+gr,M=N>0?(Uo/N*100).toFixed(1):"0.0",$=N>0?(gr/N*100).toFixed(1):"0.0";return i.createElement(I,{flexDirection:"column",borderStyle:"round",paddingX:3,paddingY:1,borderColor:"red",width:Math.min(100,(r?.columns||100)-2),marginTop:0,marginBottom:0},i.createElement(I,{marginBottom:1},i.createElement(y,{bold:!0},cc(["blue","purple"])("Agent powering down. Goodbye!"))),i.createElement(I,{flexDirection:"column"},i.createElement(y,{color:"white",bold:!0,underline:!0},"Interaction Summary"),i.createElement(I,{marginTop:1},i.createElement(I,{width:20},i.createElement(y,{color:"blue"},"Session ID:")),i.createElement(y,{color:"white"},be)),i.createElement(I,null,i.createElement(I,{width:20},i.createElement(y,{color:"blue"},"Tool Calls:")),i.createElement(y,{color:"white"},Ut+Tt+ro," ( ",i.createElement(y,{color:"green"},"\u2713 ",Ut)," ",i.createElement(y,{color:"yellow"},"\u2298 ",ro)," ",i.createElement(y,{color:"red"},"\u2715 ",Tt)," )")),i.createElement(I,null,i.createElement(I,{width:20},i.createElement(y,{color:"blue"},"Success Rate:")),i.createElement(y,{color:"white"},O,"%")),i.createElement(I,null,i.createElement(I,{width:20},i.createElement(y,{color:"blue"},"Code Changes:")),i.createElement(y,{color:"white"},i.createElement(y,{color:"green"},"+",Cs)," ",i.createElement(y,{color:"red"},"-",ks))),i.createElement(I,null,i.createElement(I,{width:20},i.createElement(y,{color:"blue"},"Tokens Consumed:")),i.createElement(y,{color:"white"},ao(go))),go>0&&i.createElement(i.Fragment,null,i.createElement(I,{marginLeft:2},i.createElement(I,{width:18},i.createElement(y,{color:"grey"},"\xBB Input Tokens:")),i.createElement(y,{color:"white"},ao(go-wt))),he>0&&i.createElement(I,{marginLeft:4},i.createElement(I,{width:16},i.createElement(y,{color:"grey"},"\xBB Cached:")),i.createElement(y,{color:"white"},ao(he))),wt>0&&i.createElement(I,{marginLeft:2},i.createElement(I,{width:18},i.createElement(y,{color:"grey"},"\xBB Output Tokens:")),i.createElement(y,{color:"white"},ao(wt)))),zn>0&&i.createElement(i.Fragment,null,i.createElement(I,null,i.createElement(I,{width:20},i.createElement(y,{color:"blue"},"Images Made:")),i.createElement(y,{color:"white"},zn)),i.createElement(I,null,i.createElement(I,{width:20},i.createElement(y,{color:"blue"},"Image Credits:")),i.createElement(y,{color:"white"},Number(((As||0)*1e3).toFixed(0))," credits")))),i.createElement(I,{flexDirection:"column",marginTop:1},i.createElement(y,{color:"white",bold:!0,underline:!0},"Performance"),i.createElement(I,{marginTop:1},i.createElement(I,{width:20},i.createElement(y,{color:"blue"},"Wall Time:")),i.createElement(y,{color:"white"},Ro(x))),i.createElement(I,null,i.createElement(I,{width:20},i.createElement(y,{color:"blue"},"Agent Active:")),i.createElement(y,{color:"white"},Ro(N))),i.createElement(I,{marginLeft:2},i.createElement(I,{width:18},i.createElement(y,{color:"grey"},"\xBB API Time:")),i.createElement(y,{color:"white"},Ro(Uo)," (",M,"%)")),i.createElement(I,{marginLeft:2},i.createElement(I,{width:18},i.createElement(y,{color:"grey"},"\xBB Tool Time:")),i.createElement(y,{color:"white"},Ro(gr)," (",$,"%)"))))})(),Ce.length>0&&(()=>{let g=Math.max(0,Math.min(w-2,Ce.length-5)),O=Ce.slice(g,g+5),N=Ce.length-(g+O.length);return i.createElement(I,{flexDirection:"column",borderStyle:"round",borderColor:"gray",paddingX:0,paddingY:0,width:"100%"},i.createElement(I,{paddingX:1,marginBottom:0,justifyContent:"space-between",width:"100%"},i.createElement(y,{color:"gray",bold:!0,dimColor:!0},Ce[0]?.cmd?.startsWith("@")?"\u{1F4C1} FILE SUGGESTIONS":"\u{1F50D} COMMAND SUGGESTIONS"),Ce[0]?.cmd?.startsWith("@")?i.createElement(y,{color:"gray",dimColor:!0,italic:!0},"(Use '#Lstart-Lend' to specify line numbers)"):a.startsWith("/model")&&Ft==="Free"?(()=>{let M="https://aistudio.google.com/billing",$="billing";return _==="DeepSeek"?(M="https://platform.deepseek.com/usage",$="billing"):_==="OpenRouter"?(M="https://openrouter.ai/settings/profile",$="profile"):_==="NVIDIA"&&(M="https://build.nvidia.com/settings/api-keys",$="billing"),i.createElement(y,{color:"gray",dimColor:!0,italic:!0},"Paid API has more models. Configure ",i.createElement(y,{color:"cyan",underline:!0},`\x1B]8;;${M}\x07${$}\x1B]8;;\x07`)," & /settings")})():null),O.map((M,$)=>{let k=g+$===w,F=M.cmd==="gemma-4-31b-it"&&Ft!=="Free";return i.createElement(I,{key:M.cmd,flexDirection:"row",backgroundColor:k?"#2a2a2a":void 0,paddingX:1},i.createElement(I,{width:3},i.createElement(y,{color:k?"cyan":"gray",bold:k},k?" \u276F":" ")),i.createElement(I,{width:55},i.createElement(y,{color:F?"gray":k?"yellow":"white",bold:k,dimColor:F&&!k},M.cmd?.startsWith("@[")&&M.cmd?.endsWith("]")?(()=>{let j=M.cmd.slice(2,-1).split(/[/\\]/);return j[j.length-1]})():M.cmd)),i.createElement(I,{flexGrow:1},i.createElement(y,{color:"gray",italic:!0,dimColor:!k},M.desc)))}),Ce.length>5&&i.createElement(I,{paddingX:1,height:1},N>0?i.createElement(y,{color:"gray",dimColor:!0,italic:!0}," ... (",N," more commands available)"):i.createElement(y,{color:"gray",dimColor:!0,italic:!0}," (End of list)")))})())))}var Is,uc,zu,ta,ac,Cs,ks,Ju,dc,Ln,Qu,lc,Zu,ed,hr,td,od,pc=ie(async()=>{ha();Ea();Ca();ka();await Da();Oa();Fa();kr();await Yl();ts();$r();jl();Hl();await ql();Jl();dn();Ql();Zl();ec();ps();Ws();Qt();Gt();sn();await Or();rc();jn();_i();Is=()=>{let e=(process.env.TERM_PROGRAM||"").toLowerCase();if(process.env.WT_SESSION)return"Windows Terminal";let o=t=>{let n=t.toLowerCase();for(let[s,r]of Object.entries(process.env))if(!["PATH","PWD","CWD","PS1","LS_COLORS","PROMPT"].includes(s)&&String(r).toLowerCase().includes(n))return!0;return!1};return e==="cursor"||process.env.CURSOR_SETTINGS_DIR||o("cursor")?"Cursor":e==="windsurf"||o("windsurf")?"Windsurf":o("antigravity")?"Antigravity":e==="trae"||o("trae")?"Trae":e==="codium"||o("codium")||o("vscode-oss")?"VSCodium":o("positron")?"Positron":e==="vscode"||process.env.VSCODE_GIT_IPC_HANDLE||o("vscode")?"VS Code":process.env.INTELLIJ_TERMINAL_COMMAND_BLOCKS||o("intellij")?"JetBrains":"Terminal"},uc=e=>{let o=e==="VS Code",t=[];return o?(t.push({label:"Install Manually (VSIX)",url:"https://github.com/KushalRoyChowdhury/fluxflow-cli/releases"}),t.push({label:"Install from VS Code Marketplace",url:"https://marketplace.visualstudio.com/items?itemName=fluxflow-cli.fluxflow-cli-companion"})):t.push({label:`Download for ${e} (GitHub)`,url:"https://github.com/KushalRoyChowdhury/fluxflow-cli/releases"}),t.push({label:"Continue to CLI only",action:"dismiss"}),t},zu=({width:e,height:o,selectedIndex:t})=>{let n=Is(),s=uc(n);return i.createElement(I,{flexDirection:"column",alignItems:"center",justifyContent:"center",width:e,height:o},i.createElement(I,{marginBottom:1},i.createElement(y,null,hr)),i.createElement(I,{flexDirection:"column",borderStyle:"double",borderColor:"cyan",paddingX:3,paddingY:1,width:Math.min(80,e-4)},i.createElement(y,{bold:!0,color:"cyan",textAlign:"center"},"\u{1F680} UPGRADE YOUR WORKFLOW"),i.createElement(I,{marginY:1,flexDirection:"column",alignItems:"left"},i.createElement(y,null,"You're in ",i.createElement(y,{bold:!0,color:"cyan"},n),", but the ",i.createElement(y,{bold:!0,color:"magenta"},"FluxFlow-CLI Companion")," is not installed."),i.createElement(I,{flexDirection:"column",marginY:1},i.createElement(y,{color:"gray"}," \u2705 Real-time file & cursor tracking"),i.createElement(y,{color:"gray"}," \u2705 Auto-open files created by agent"),i.createElement(y,{color:"gray"}," \u2705 Native DIFF viewer for AI edits"),i.createElement(y,{color:"gray"}," \u2705 Direct IDE context sharing"),i.createElement(y,{color:"gray"}," \u2705 Surgical Diagnostic Sync"),i.createElement(y,{color:"gray"}," \u2705 Native Right-Click \u276F Chat integration"),i.createElement(y,{color:"gray"}," \u2705 Live Status in IDE"),i.createElement(y,{color:"gray"}," \u2705 Clickable terminal-to-code links"))),i.createElement(I,{flexDirection:"column",marginTop:1},s.map((r,a)=>i.createElement(I,{key:a},i.createElement(y,{color:t===a?"yellow":"white",bold:t===a},t===a?" \u276F ":" ",r.label)))),i.createElement(I,{marginTop:1,alignItems:"center",justifyContent:"center"},i.createElement(y,{dimColor:!0,italic:!0},"(Use arrows to navigate, Enter to select)"))))},ta=Date.now(),ac="https://fluxflow-cli.onrender.com/changelog.html",Cs=0,ks=0,Ju=qn.join(qn.dirname(qu(import.meta.url)),"../package.json"),dc=JSON.parse(lo.readFileSync(Ju,"utf8")),Ln=dc.version,Qu=dc.date||"2026-05-20",lc=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Zu=()=>{let[e,o]=J(0);return to(()=>{let t=setInterval(()=>{o(n=>(n+1)%1e3)},33);return()=>clearInterval(t)},[]),i.createElement(y,{color:"magenta"},lc[Math.floor(e/3)%lc.length])},ed=({data:e,onResolve:o,onEdit:t})=>i.createElement(I,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},i.createElement(I,{paddingX:1},i.createElement(y,{color:"magenta",bold:!0,underline:!0},"\u{1F7E3} STEERING HINT RESOLUTION")),i.createElement(I,{paddingX:1,marginTop:1},i.createElement(y,null,"The agent already finished the task before your hint was consumed.")),i.createElement(I,{marginTop:1,backgroundColor:"#222",paddingX:2,width:"100%"},i.createElement(y,{italic:!0,color:"gray"},'"',e,'"')),i.createElement(I,{paddingX:1,marginTop:1},i.createElement(y,{color:"cyan"},"How would you like to proceed?")),i.createElement(I,{marginTop:0},i.createElement(fo,{title:"Select Action",items:[{label:"Send Anyway",value:"send"},{label:"Edit Prompt",value:"edit"}],onSelect:n=>{n==="send"?o(e):t(e)}}))),hr=cc(["#00ffff","#0077ff","#ff00ff"]).multiline(`\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2557
|
|
597
606
|
\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u255A\u2588\u2588\u2557\u2588\u2588\u2554\u255D \u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2551
|
|
598
607
|
\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2557 \u2588\u2588\u2551
|
|
599
608
|
\u2588\u2588\u2554\u2550\u2550\u255D \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2554\u2588\u2588\u2557 \u2588\u2588\u2554\u2550\u2550\u255D \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2588\u2557\u2588\u2588\u2551
|
|
600
609
|
\u2588\u2588\u2551 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2554\u255D \u2588\u2588\u2557 \u2588\u2588\u2551 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u255A\u2588\u2588\u2588\u2554\u2588\u2588\u2588\u2554\u255D
|
|
601
|
-
\u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u255D\u255A\u2550\u2550\u255D`),
|
|
610
|
+
\u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u255D\u255A\u2550\u2550\u255D`),td=e=>{let o=[],t=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,n=0,s;for(;(s=t.exec(e))!==null;){let r=s[1],a=s.index+s[0].length-1,u=0,f=null,m=-1,c=-1;for(let l=a;l<e.length;l++){let d=e[l];if(f){if(d===f){let p=0;for(let h=l-1;h>=0&&e[h]==="\\";h--)p++;p%2===0&&(f=null)}}else if(d==='"'||d==="'"||d==="`")f=d;else if(d==="(")u++;else if(d===")"&&(u--,u===0)){c=l;let p=l+1;for(;p<e.length&&/\s/.test(e[p]);)p++;if(p<e.length&&e[p]==="]"){m=p;break}}}if(m!==-1){let l=e.substring(n,s.index);l.trim()&&o.push({type:"output",content:l});let d=e.substring(a+1,c);o.push({type:"tool",toolName:r.trim(),args:d.trim()}),n=m+1,t.lastIndex=n}else break}if(n<e.length){let r=e.substring(n);r.trim()&&o.push({type:"output",content:r})}return o},od=(()=>{let e=null,o=0;return t=>{let n=Date.now();if(e&&n-o<5e3)return e;let s=[],r=a=>{try{let u=lo.readdirSync(a);for(let f of u){if(["node_modules",".git",".gemini","dist","build",".next",".cache","out"].includes(f))continue;let m=qn.join(a,f);lo.statSync(m).isDirectory()?r(m):s.push({name:f,relativePath:qn.relative(process.cwd(),m)})}}catch{}};return r(t),e=s,o=n,s}})()});import{spawn as nd}from"child_process";import{fileURLToPath as hc}from"url";var rd=4096,sd=hc(import.meta.url).endsWith(".js");if(sd&&!process.execArgv.some(e=>e.includes("max-old-space-size")))nd(process.execPath,[`--max-old-space-size=${rd}`,hc(import.meta.url),...process.argv.slice(2)],{stdio:"inherit"}).on("exit",o=>process.exit(o||0));else{let e=process.argv.slice(2),o=e.includes("--help")&&e[e.indexOf("--help")+1]==="commands",t=e.includes("--help")&&!o,n=e.includes("--version")||e.includes("-v"),s=e[0]==="--update";if(n||t||o||s){let p=await import("fs"),h=await import("path"),{fileURLToPath:S}=await import("url"),w=h.join(h.dirname(S(import.meta.url)),"../package.json"),b=JSON.parse(p.readFileSync(w,"utf8")).version;if(n&&(console.log(`v${b}`),process.exit(0)),t&&(console.log(`FluxFlow CLI Arguments:
|
|
602
611
|
--mode <flux|flow> Set startup mode (flux: Agent / flow: Chat)
|
|
603
612
|
--model <model_name> Set startup AI model
|
|
604
613
|
--key <key@provider> Set API key and provider
|
|
@@ -617,28 +626,29 @@ Selection: ${ye}`,isAskRecord:!0}]),pe(ye)}}),X("ask")})},async()=>{if(Co.curren
|
|
|
617
626
|
--update check Check for new updates
|
|
618
627
|
--update check latest Show the latest version available on npm
|
|
619
628
|
--update latest Update the app to the latest version`),process.exit(0)),o&&(console.log(`FluxFlow Chat /Commands:
|
|
620
|
-
/quit
|
|
621
|
-
/help
|
|
622
|
-
/clear
|
|
623
|
-
/resume
|
|
624
|
-
/
|
|
625
|
-
/
|
|
626
|
-
/
|
|
627
|
-
/
|
|
628
|
-
/
|
|
629
|
-
/image setup
|
|
630
|
-
/image
|
|
631
|
-
/
|
|
632
|
-
/
|
|
633
|
-
/
|
|
634
|
-
/
|
|
635
|
-
/
|
|
636
|
-
/
|
|
637
|
-
/
|
|
638
|
-
/
|
|
639
|
-
/
|
|
640
|
-
/
|
|
641
|
-
/
|
|
642
|
-
/
|
|
643
|
-
/
|
|
644
|
-
/update
|
|
629
|
+
/quit Exit and shutdown Flux
|
|
630
|
+
/help Show help menu
|
|
631
|
+
/clear Clear terminal screen
|
|
632
|
+
/resume Load previous session
|
|
633
|
+
/compress Summarize and compress chat history
|
|
634
|
+
/revert Revert codebase back to a checkpoint
|
|
635
|
+
/save Force save current chat
|
|
636
|
+
/export Export current chat in a .txt file
|
|
637
|
+
/chats List all chat sessions
|
|
638
|
+
/image setup key <default|custom> Configure image API key strategy
|
|
639
|
+
/image setup quality <low...premium> Configure default image generation quality
|
|
640
|
+
/image stats Show image quota stats
|
|
641
|
+
/mode <flux|flow> Toggle Flux/Flow modes
|
|
642
|
+
/thinking <Fast|Low|Medium|High|xHigh> Set AI reasoning depth
|
|
643
|
+
/model <model_name> Switch Model for Agent
|
|
644
|
+
/settings Configure system preferences
|
|
645
|
+
/key Manage API keys
|
|
646
|
+
/profile Edit developer persona
|
|
647
|
+
/memory Manage agent memory
|
|
648
|
+
/stats Show session usage
|
|
649
|
+
/reset Wipe all project data
|
|
650
|
+
/about Project info & credits
|
|
651
|
+
/changelog View latest updates
|
|
652
|
+
/fluxflow init Create FluxFlow.md template
|
|
653
|
+
/update check Check for new version
|
|
654
|
+
/update latest Install latest release`),process.exit(0)),s){let L=e[1];if(L==="check"){let P=e[2]==="latest";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)),console.log(P?`Latest version: v${D}`:D!==b?`A new version of FluxFlow is available: v${D} (current: v${b}). Run "fluxflow --update latest" to upgrade.`:`FluxFlow is up to date (v${b}).`)}catch(Y){console.error("Error checking for updates:",Y.message),process.exit(1)}process.exit(0)}else if(L==="latest"){console.log("Checking latest version and settings...");try{let v=(await(await fetch("https://registry.npmjs.org/fluxflow-cli",{cache:"no-store"})).json())["dist-tags"]?.latest;v||(console.error("Error: Could not retrieve latest version."),process.exit(1)),v===b&&(console.log(`FluxFlow is already up to date (v${b}).`),process.exit(0));let D=async()=>{let _=(await import("react")).default,{useState:K}=_,{render:Ue,Box:se,Text:Te}=await import("ink"),De=(await import("ink-select-input")).default,me=(await import("ink-text-input")).default;return new Promise(et=>{let Ye=[{label:"NPM",value:"npm"},{label:"PNPM",value:"pnpm"},{label:"Yarn",value:"yarn"},{label:"Bun",value:"bun"},{label:"Custom Command",value:"custom"}],je=({label:We,isSelected:Vt})=>_.createElement(se,{width:"100%"},_.createElement(Te,{color:Vt?"cyan":"gray",bold:Vt},"\u2514\u2500 ",Vt?"\u25C9":"\u25CB"," ",We)),Oe,kt=()=>{let[We,Vt]=K("select"),[Nt,Ge]=K(""),ze=co=>{co.value==="custom"?Vt("custom"):Ne({manager:co.value})},yt=co=>{Ne({manager:"custom",customCommand:co})};return We==="custom"?_.createElement(se,{flexDirection:"column",marginY:1},_.createElement(se,{marginBottom:1},_.createElement(Te,{color:"magenta",bold:!0},"\u{1F527} Enter custom update command:")),_.createElement(se,{flexDirection:"row"},_.createElement(Te,{color:"cyan",bold:!0}," \u276F "),_.createElement(me,{value:Nt,onChange:Ge,onSubmit:yt})),_.createElement(se,{marginTop:1},_.createElement(Te,{color:"gray",dimColor:!0,italic:!0}," (Press Enter to confirm)"))):_.createElement(se,{flexDirection:"column",marginY:1},_.createElement(se,{marginBottom:1},_.createElement(Te,{color:"magenta",bold:!0},"\u{1F4E6} Select a package manager for the update:")),_.createElement(De,{items:Ye,onSelect:ze,itemComponent:je,indicatorComponent:()=>null}))},Ne=We=>{Oe&&Oe(),et(We)},{unmount:He}=Ue(_.createElement(kt,null));Oe=He})},A,E="",q;try{let{loadSettings:_}=await Promise.resolve().then(()=>(ts(),da));q=await _(),A=q?.systemSettings?.updateManager||q?.updateManager}catch{}if(!A){let _=await D();A=_.manager,E=_.customCommand}let B="";A==="pnpm"?B=`pnpm add -g fluxflow-cli@${v}`:A==="bun"?B=`bun add -g fluxflow-cli@${v}`:A==="yarn"?B=`yarn global add fluxflow-cli@${v}`:A==="custom"?B=E||q?.customUpdateCommand||`npm install -g fluxflow-cli@${v}`:B=`npm install -g fluxflow-cli@${v}`,console.log(`Updating FluxFlow to v${v} using ${A}...`),console.log(`Running: ${B}`);let{execSync:V}=await import("child_process");V(B,{stdio:"inherit"}),console.log(`\x1B[32m\u2705 Update successful! FluxFlow updated to v${v}.\x1B[0m`)}catch(P){console.error("\x1B[31m\u274C Update failed:\x1B[0m",P.message),process.exit(1)}process.exit(0)}else console.error("Unknown update command. Available options: --update check, --update check latest, --update latest"),process.exit(1)}}let{default:r}=await import("react"),{render:a}=await import("ink"),{default:u}=await pc().then(()=>fc);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,l=console.error,d=p=>{let h=p.map(String).join(" ");return f.some(S=>h.includes(S))};console.log=(...p)=>!d(p)&&m(...p),console.warn=(...p)=>!d(p)&&c(...p),console.error=(...p)=>!d(p)&&l(...p),process.stdout.write("\x1B[2J\x1B[3J\x1B[H"),process.stdout.isTTY&&(process.stdout.write("\x1B]0;FluxFlow\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow\x07")),a(r.createElement(u,{args:process.argv.slice(2)}),{exitOnCtrlC:!1})}
|