fluxflow-cli 2.2.9 → 2.3.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/TOOLS.md +4 -1
- package/dist/fluxflow.js +246 -245
- package/package.json +3 -3
package/dist/fluxflow.js
CHANGED
|
@@ -1,62 +1,60 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var fc=Object.defineProperty;var re=(e,o)=>()=>(e&&(o=e(e=0)),o);var qr=(e,o)=>{for(var t in o)fc(e,t,{get:o[t],enumerable:!0})};var na={};qr(na,{BACKUPS_DIR:()=>wn,DATA_DIR:()=>Er,FLUXFLOW_DIR:()=>Un,HISTORY_FILE:()=>Rn,LEDGER_FILE:()=>nn,LOGS_DIR:()=>Io,MEMORIES_FILE:()=>Nt,PARSER_DIR:()=>Tn,PATHS_FILE:()=>Vr,SECRET_DIR:()=>ro,SETTINGS_FILE:()=>no,TEMP_MEM_CHAT_FILE:()=>Go,TEMP_MEM_FILE:()=>Eo,USAGE_FILE:()=>Ht});import pc from"os";import So from"path";import ea from"fs";import ta from"crypto";var Un,no,oa,Er,Io,ro,Rn,Ht,Nt,Eo,Go,wn,nn,Vr,Tn,Bt=re(()=>{Un=So.join(pc.homedir(),".fluxflow"),no=So.join(Un,"settings.json"),oa=null;try{if(ea.existsSync(no)){let e=ea.readFileSync(no,"utf8").trim(),o;if(e.startsWith("{"))o=JSON.parse(e);else{let t=e.split(":");if(t.length===2){let n=Buffer.from(t[0],"hex"),s=t[1],r=ta.createHash("sha256").update("fluxflow-cli-sanctuary-key").digest(),l=ta.createDecipheriv("aes-256-cbc",r,n),u=l.update(s,"hex","utf8");u+=l.final("utf8"),o=JSON.parse(u)}}if(o){let t=o.systemSettings||{};t.useExternalData&&t.externalDataPath&&(oa=t.externalDataPath)}}}catch{}Er=oa||Un,Io=So.join(Er,"logs"),ro=So.join(Er,"secret"),Rn=So.join(ro,"history.json"),Ht=So.join(Un,"usage.json"),Nt=So.join(ro,"memories.json"),Eo=So.join(ro,"memory-temp.json"),Go=So.join(ro,"temp-memory-chat.json"),wn=So.join(Er,"backups"),nn=So.join(ro,"ledger.json"),Vr=So.join(ro,"path.json"),Tn=So.join(Er,"parsers")});import br from"fs";import Ps from"path";import zr from"crypto";var hc,gc,ra,sa,Cr,Sn,xe,ke,Jr,Qr,Lo=re(()=>{hc=66,gc=e=>{let o=Buffer.isBuffer(e)?e:Buffer.from(e),t=Buffer.alloc(o.length);for(let n=0;n<o.length;n++)t[n]=o[n]^hc;return t},ra="aes-256-cbc",sa=zr.createHash("sha256").update("fluxflow-cli-sanctuary-key").digest(),Cr=e=>{let o=zr.randomBytes(16),t=zr.createCipheriv(ra,sa,o),n=t.update(e,"utf8","hex");return n+=t.final("hex"),o.toString("hex")+":"+n},Sn=e=>{let o=e.split(":");if(o.length!==2)throw new Error("Invalid AES format");let t=Buffer.from(o[0],"hex"),n=o[1],s=zr.createDecipheriv(ra,sa,t),r=s.update(n,"hex","utf8");return r+=s.final("utf8"),r},xe=(e,o={})=>{try{if(!br.existsSync(e))return o;let t=br.readFileSync(e),n=t.toString("utf8").trim();if(n.startsWith("{")||n.startsWith("["))return JSON.parse(n);try{let r=Sn(n);return JSON.parse(r)}catch{}let s=gc(t).toString("utf8");if(s.startsWith("{")||s.startsWith("["))return JSON.parse(s);throw new Error("Unsupported or corrupt encryption format")}catch(t){return console.error(`Vault Read Error [${Ps.basename(e)}]:`,t.message),o}},ke=(e,o)=>{try{let t=Ps.dirname(e);br.existsSync(t)||br.mkdirSync(t,{recursive:!0});let n=JSON.stringify(o,null,2),s=Cr(n);br.writeFileSync(e,s,"utf8")}catch(t){console.error(`Vault Write Error [${Ps.basename(e)}]:`,t.message)}},Jr=xe,Qr=ke});var ts={};qr(ts,{getAPIKey:()=>wc,getProviderAPIKey:()=>Zr,getSearchSecrets:()=>Sc,getSecret:()=>Tc,removeAPIKey:()=>_s,removeSecret:()=>ia,saveAPIKey:()=>Ec,saveProviderAPIKey:()=>es,saveSearchId:()=>Cc,saveSearchKey:()=>bc,saveSecret:()=>En});import xc from"fs-extra";import yc from"path";var bn,wc,Zr,es,Tc,En,Sc,Ec,bc,Cc,ia,_s,kr=re(()=>{Lo();Bt();bn=yc.join(ro,"secrets.json"),wc=async()=>{try{let e=xe(bn,{});if(e.API_KEY)return e.API_KEY}catch{}return null},Zr=async e=>{try{let o=xe(bn,{});if(e==="Google")return o.GOOGLE_API_KEY||o.API_KEY||null;if(e==="DeepSeek")return o.DEEPSEEK_API_KEY||null;if(e==="OpenRouter")return o.OPENROUTER_API_KEY||null}catch{}return null},es=async(e,o)=>{e==="Google"?(await En("GOOGLE_API_KEY",o),await En("API_KEY",o)):e==="DeepSeek"?await En("DEEPSEEK_API_KEY",o):e==="OpenRouter"&&await En("OPENROUTER_API_KEY",o)},Tc=async e=>{try{return xe(bn,{})[e]||null}catch{return null}},En=async(e,o)=>{await xc.ensureDir(ro);let t=xe(bn,{});t[e]=o,ke(bn,t)},Sc=async()=>{try{let e=xe(bn,{});return{key:e.GOOGLE_API_KEY||e.API_KEY,cx:e.SEARCH_ID}}catch{}return{key:null,cx:null}},Ec=async e=>En("API_KEY",e),bc=async e=>En("GOOGLE_API_KEY",e),Cc=async e=>En("SEARCH_ID",e),ia=async e=>{try{let o=xe(bn,{});delete o[e],ke(bn,o)}catch{}},_s=async()=>ia("API_KEY")});var aa={};qr(aa,{loadSettings:()=>or,saveSettings:()=>Cn});import Ir from"fs-extra";import Ns from"path";var tr,or,kc,Cn,os=re(()=>{Bt();Lo();tr={mode:"Flux",thinkingLevel:"Medium",aiProvider:"Google",activeModel:"gemma-4-31b-it",showFullThinking:!0,apiTier:"Free",quotas:{agentLimit:999999,backgroundLimit:999999,searchLimit:100,customModelId:"",customLimit:0},systemSettings:{memory:!0,compression:0,autoExec:!1,allowExternalAccess:!1,autoDeleteHistory:"7d",useExternalData:!1,externalDataPath:""},profileData:{name:null,nickname:null,instructions:null},imageSettings:{keyType:"Default",quality:"Low-High",apiKey:""}},or=async()=>{let e={...tr};try{if(await Ir.exists(no)){let o=Jr(no);if(o.imageSettings&&o.imageSettings.apiKey)try{let t=o.imageSettings.apiKey,{saveSecret:n}=await Promise.resolve().then(()=>(kr(),ts));await n("POLLINATIONS_API_KEY",t),o.imageSettings.apiKey="",Qr(no,o)}catch{}e={...tr,...o,quotas:{...tr.quotas,...o.quotas},systemSettings:{...tr.systemSettings,...o.systemSettings},profileData:{...tr.profileData,...o.profileData},imageSettings:{...tr.imageSettings,...o.imageSettings}}}}catch(o){console.error("Failed to load settings:",o)}try{let{getSecret:o}=await Promise.resolve().then(()=>(kr(),ts)),t=await o("POLLINATIONS_API_KEY");t&&(e.imageSettings.apiKey=t)}catch{}if(e.showFullThinking===!1){e.showFullThinking=!0;try{Qr(no,e)}catch{}}return e},kc=async e=>{let{FLUXFLOW_DIR:o}=await Promise.resolve().then(()=>(Bt(),na)),t=["logs","secret"];for(let n of t){let s=Ns.join(o,n),r=Ns.join(e,n);try{await Ir.exists(s)&&(await Ir.ensureDir(r),await Ir.copy(s,r,{overwrite:!0}))}catch(l){console.error(`Migration failed for ${n}:`,l)}}},Cn=async e=>{try{let o=await or();if(!o.systemSettings.useExternalData&&e.systemSettings?.useExternalData&&e.systemSettings?.externalDataPath&&await kc(e.systemSettings.externalDataPath),e.imageSettings&&e.imageSettings.apiKey!==void 0){let{saveSecret:n,removeSecret:s}=await Promise.resolve().then(()=>(kr(),ts)),r=e.imageSettings.apiKey;r?await n("POLLINATIONS_API_KEY",r):await s("POLLINATIONS_API_KEY")}let t={...o,...e};return t.imageSettings&&(t.imageSettings={...t.imageSettings,apiKey:""}),await Ir.ensureDir(Ns.dirname(no)),Qr(no,t),!0}catch(o){return console.error("Failed to save settings:",o),!1}}});import mo,{useState as Ar,useEffect as Rs,useMemo as Bs,useCallback as ns,useRef as la}from"react";import{Box as vr,Spacer as Ic,Text as Mr,useInput as Mc,measureElement as vc}from"ink";function Ac(e,o){return e.replace(/\t/g," ".repeat(o))}function Us(e){return e==null?"":e.replace(/\r\n/g,`
|
|
3
3
|
`).replace(/\r/g,`
|
|
4
|
-
`)}var
|
|
5
|
-
`)+1,
|
|
6
|
-
`);return{preCursor:[{value:
|
|
7
|
-
`),
|
|
8
|
-
`),
|
|
9
|
-
`+e.slice(a);o(
|
|
10
|
-
`+e.slice(a);o(
|
|
11
|
-
`),
|
|
12
|
-
`)},
|
|
4
|
+
`)}var ca,Oc,ua,da=re(()=>{ca=({children:e,onHeightChange:o})=>{let t=la(null),n=la(void 0);return Rs(()=>{if(t.current){let{height:s}=vc(t.current);n.current!==s&&(n.current=s,o?.(s))}}),mo.createElement(vr,{ref:t,flexShrink:0,flexGrow:0,width:"100%"},e)},Oc=({value:e,rows:o,maxRows:t,highlightStyle:n,textStyle:s,placeholder:r="",mask:l,showCursor:u=!0,focus:f=!0,tabSize:m=4,cursorIndex:c=0,highlight:a,refreshKey:d})=>{let[p,h]=Ar(0),[S,T]=Ar(0),[w,I]=Ar(0),L=ns((A,F=!1)=>{let Q=Us(A);if(!F&&l)return Q.replace(/[^\n]/g,l);let j=Ac(Q,m);return F?j:j.replace(/@\[(.*?)\]/g,(Z,B)=>{let z=B.indexOf("#"),mt=B.indexOf(":L"),ce=B,Le="";z!==-1?(ce=B.slice(0,z),Le=B.slice(z)):mt!==-1&&(ce=B.slice(0,mt),Le=B.slice(mt));let Je=ce.replace(/\\/g,"/"),ue=(process.cwd()||"").replace(/\\/g,"/");ue&&Je.toLowerCase().startsWith(ue.toLowerCase()+"/")?Je=Je.slice(ue.length+1):Je.startsWith("./")&&(Je=Je.slice(2));let tt=Je.split("/");return`[${tt[tt.length-1]}${Le}]`})},[m,l]),{preCursor:_,postCursor:R}=Bs(()=>{if(!e)return r&&!f?{preCursor:[{value:L(r,!0),type:"placeholder"}],postCursor:[]}:{preCursor:[{value:u&&f?" ":"",type:"cursor"}],postCursor:[]};let A=e.slice(0,c),F=e.slice(c);if(!f)return{preCursor:[{value:L(e)}],postCursor:[]};if(a&&a.end>a.start&&a.start>=0&&a.end<=e.length)return{preCursor:[{value:L(A.slice(0,a.start))},{value:L(A.slice(a.start,Math.min(a.end,c))),type:"highlight"},{value:L(A.slice(a.end))},{value:u&&f?" ":"",type:"cursor"}],postCursor:[{value:L(F.slice(0,Math.max(a.start-c,0)))},{value:L(F.slice(Math.max(a.start-c,0),Math.max(a.end-c,0))),type:"highlight"},{value:L(F.slice(Math.max(a.end-c,0)))}]};{let j=L(A),Z=L(F),B=j.lastIndexOf(`
|
|
5
|
+
`)+1,z=Z.indexOf(`
|
|
6
|
+
`);return{preCursor:[{value:j.slice(0,B)},{value:j.slice(B),type:"highlight"},{value:u&&f?" ":"",type:"cursor"}],postCursor:[{value:Z.slice(0,z),type:"highlight"},{value:Z.slice(z)}]}}},[c,u,f,e,r,l,a,L,d]),v=Bs(()=>S!==void 0?Math.max(o??t??1,Math.min(t??o??1,S)):1,[o,t,S]);Rs(()=>{if(w!==void 0&&v!==void 0){let A=w;h(F=>{let Q=F,j=F+v;if(A<=Q)return Math.max(0,A-1);if(A>j)return A-v;if(S){if(S<v)return 0;if(S<j)return S-v}return F})}},[w,v,S]);let b=ns(A=>{switch(A){case"placeholder":return{...s,dimColor:!0};case"highlight":return n??s;case"cursor":return{...s,color:u&&f?"cyan":void 0,bold:u&&f,inverse:u&&f};default:return s}},[s,n,u,f]);return mo.createElement(vr,{height:v,overflow:"hidden",flexDirection:"column",flexGrow:0,flexShrink:0},mo.createElement(vr,{flexDirection:"column"},mo.createElement(vr,{height:v,overflowY:"hidden",flexShrink:0,flexDirection:"column"},mo.createElement(vr,{marginTop:-p,flexDirection:"column"},mo.createElement(ca,{onHeightChange:T},mo.createElement(Mr,null,_?.map((A,F)=>mo.createElement(Mr,{key:F,...b(A.type)},A.value)),R?.map((A,F)=>mo.createElement(Mr,{key:F,...b(A.type)},A.value))))),mo.createElement(Ic,null)),mo.createElement(ca,{onHeightChange:I},mo.createElement(Mr,null,_?.map((A,F)=>mo.createElement(Mr,{key:F,...b(A.type)},A.value))))))},ua=({value:e,onChange:o,onSubmit:t,keyBindings:n,showCursor:s=!0,highlightPastedText:r=!1,focus:l=!0,lastFocusEventTime:u=0,columns:f=80,useCustomInput:m=(a,d)=>Mc(a,{isActive:d}),...c})=>{let[a,d]=Ar(e.length),[p,h]=Ar(0);Rs(()=>{a>e.length&&d(e.length)},[e,a]);let S=ns(I=>{let _=Us(e).split(`
|
|
7
|
+
`),R=Math.max(20,f-10),v=0,b=0,A=0;for(let F=0;F<_.length;F++){let j=_[F].length;if(I>=A&&I<=A+j){let B=I-A;return v+=Math.floor(B/R),b=B%R,{visualLine:v,visualCol:b}}let Z=Math.max(1,Math.ceil(j/R));v+=Z,A+=j+1}return{visualLine:v,visualCol:b}},[e,f]),T=ns((I,L)=>{let R=Us(e).split(`
|
|
8
|
+
`),v=Math.max(20,f-10),b=0,A=0;for(let F=0;F<R.length;F++){let j=R[F].length,Z=Math.max(1,Math.ceil(j/v));if(I>=b&&I<b+Z){let B=(I-b)*v,z=Math.min(L,j-B),mt=Math.max(0,z);return Math.min(A+B+mt,A+j)}b+=Z,A+=j+1}return e.length},[e,f]);m((I,L)=>{if(I==="\x1B[I"||I==="\x1B[O"||I==="[I"||I==="[O")return;let _=n?.submit??(b=>b.return&&b.ctrl),R=n?.newline??(b=>b.return);if(_(L)){t?.(e);return}else if(R(L)){let b=e.slice(0,a)+`
|
|
9
|
+
`+e.slice(a);o(b),d(a+1),h(0);return}if(L.tab||L.shift&&L.tab||L.ctrl&&I==="c")return;let v=0;if(I.length>1&&(v=I.length),L.upArrow){if(s){let{visualLine:b,visualCol:A}=S(a);if(b>0){let F=T(b-1,A);d(F),h(0)}}}else if(L.downArrow){if(s){let{visualLine:b,visualCol:A}=S(a),F=T(b+1,A);F!==a&&(d(F),h(0))}}else if(L.leftArrow)s&&(d(Math.max(0,a-1)),h(0));else if(L.rightArrow)s&&(d(Math.min(e.length,a+1)),h(0));else if(L.return){let b=e.slice(0,a)+`
|
|
10
|
+
`+e.slice(a);o(b),d(a+1),h(0)}else if(L.backspace||L.delete){if(a>0){let b=e.slice(0,a-1)+e.slice(a);o(b),d(a-1),h(0)}}else if(I){let b=e.slice(0,a)+I+e.slice(a);o(b),d(a+I.length),h(v)}},l);let w=Bs(()=>{if(r&&p>1)return{start:Math.max(0,a-p),end:a}},[a,p,r]);return mo.createElement(Oc,{...c,value:e,cursorIndex:a,highlight:w,showCursor:s,focus:l})}});import Dc from"os";var Ho,so,ma,rs,ss,is,Wn=re(()=>{Ho=(e,o)=>{if(!e)return"";let t=/\x1B\[[0-?]*[ -/]*[@-~]/g,n=e.split(`
|
|
11
|
+
`),s=[];if(o<=5)return e;let r=l=>l.replace(t,"").length;return n.forEach(l=>{if(r(l)<=o){s.push(l);return}let f=l.split(/(\s+)/),m="",c=0,a=l.match(/^(\s*)/),d=a?a[1]:"";f.forEach((p,h)=>{if(p.length===0)return;let S=r(p);if(c+S>o)if(m.trim().length>0)s.push(m.trimEnd()),m=d+p,c=r(m);else if(t.test(p))s.push(p),m=d,c=r(m);else{let T=p;for(;r(T)>o&&o>10;)s.push(T.substring(0,o)),T=T.substring(o);m=T,c=r(m)}else m+=p,c+=S}),(m.trimEnd().length>0||m===d)&&s.push(m.trimEnd())}),s.join(`
|
|
12
|
+
`)},so=e=>{if(!e&&e!==0)return"0.0k";let o=typeof e=="string"?parseFloat(e):e;return o>=1e6?`${(o/1e6).toFixed(1)}m`:o>=1e3?`${(o/1e3).toFixed(1)}k`:o.toString()},ma=(e,o=40)=>{if(e=e.replace(Dc.homedir(),"~"),!e||e.length<=o)return e;let t=Math.floor((o-3)/2);return e.substring(0,t)+"..."+e.substring(e.length-t)},rs=e=>{let o=[],t=new Set;Object.keys(e).forEach(s=>{let r=s.match(/^(replaceContent|newContent|content_to_replace|content_to_add)(\d+)?$/);if(r){let l=r[2]?parseInt(r[2]):1;t.add(l)}});let n=Array.from(t).sort((s,r)=>s-r);for(let s of n){let r,l;if(s===1?(r=e.replaceContent1??e.content_to_replace??e.replaceContent,l=e.newContent1??e.content_to_add??e.newContent):(r=e[`replaceContent${s}`]??e[`content_to_replace${s}`],l=e[`newContent${s}`]??e[`content_to_add${s}`]),r!==void 0&&l!==void 0)o.push({replace:r,new:l});else if(r!==void 0||l!==void 0)return{error:`Mismatched replacement pair for index ${s}. Both replacement and new content must be provided.`}}return{patchPairs:o}},ss=(e,o)=>{let t=[],n=e.replace(/\r\n/g,`
|
|
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=
|
|
17
|
-
`).filter(
|
|
18
|
-
`).filter(Z=>Z.trim()!=="");if(
|
|
19
|
-
`).map((
|
|
20
|
-
`)},f=n;for(let
|
|
21
|
-
`).map(Z=>Z.trim()).filter(Z=>Z.length>0).map(Z=>Z.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\s+/g,"\\s*"));if(
|
|
22
|
-
`,T)+1,
|
|
23
|
-
`),
|
|
24
|
-
`).length,
|
|
25
|
-
`),
|
|
26
|
-
`,
|
|
27
|
-
`,f++;else{let T=
|
|
28
|
-
`).length-1;if(c.originalStartLine-
|
|
29
|
-
`,f++;for(l+=`[UI_CONTEXT] ${
|
|
16
|
+
`),r=m=>m.match(/^\s*/)[0],l=m=>{let c=m.split(`
|
|
17
|
+
`).filter(d=>d.trim()!=="");if(c.length===0)return"";let a=r(c[0]);for(let d of c){let p=r(d);p.length<a.length&&(a=p)}return a},u=(m,c,a="")=>{if(!m||c===void 0)return m;let d=v=>{let b=v.split(`
|
|
18
|
+
`).filter(Z=>Z.trim()!=="");if(b.length===0)return{char:" ",size:4};let A=b[0].match(/^\s*/)[0];if(A.includes(" "))return{char:" ",size:1};let F=b.map(Z=>Z.match(/^\s*/)[0].length).filter(Z=>Z>0);if(F.length===0)return{char:" ",size:A.length||4};let Q=(Z,B)=>B?Q(B,Z%B):Z;return{char:" ",size:F.reduce((Z,B)=>Q(Z,B))||4}},p=d(c),h=d(m),S=l(c).length,T=(a.match(/^\s*/)||[""])[0].length,I=(T+S)/p.size,L=l(m).length/h.size,_=I-L;return m.split(`
|
|
19
|
+
`).map((v,b)=>{if(v.trim()===""&&b!==0)return"";let A=v.match(/^\s*/)[0].length/h.size,F=Math.max(0,A+_),Q=F;if(b===0){let j=T/p.size;Q=Math.max(0,F-j)}return p.char.repeat(Q*p.size)+v.trimStart()}).join(`
|
|
20
|
+
`)},f=n;for(let m=0;m<o.length;m++){let c=o[m],a=s(c.replace||""),d=s(c.new||"");if(a===""&&d===""){t.push({success:!1,error:`Block ${m+1}: Empty replace and add content.`});continue}let p=a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),h=null;if(a!==""&&f.includes(a))h=new RegExp(p,"g");else{let j=a.split(`
|
|
21
|
+
`).map(Z=>Z.trim()).filter(Z=>Z.length>0).map(Z=>Z.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\s+/g,"\\s*"));if(j.length>0){let Z=j.join("\\s*");try{h=new RegExp(Z,"g")}catch{h=new RegExp(p,"g")}}else h=new RegExp(p,"g")}let S=[...f.matchAll(h)];if(S.length===0){t.push({success:!1,error:`Block ${m+1}: Could not find match.`});continue}if(S.length>1){t.push({success:!1,error:`Block ${m+1}: Found ${S.length} matches (must be unique).`});continue}let T=S[0].index,w=S[0][0],I=f.lastIndexOf(`
|
|
22
|
+
`,T)+1,L=f.substring(I,T),_=u(d,w,L),R=f.split(`
|
|
23
|
+
`),v=f.substring(0,T).split(`
|
|
24
|
+
`).length,b=[];for(let j=Math.max(0,v-4);j<v-1;j++)b.push({num:j+1,text:R[j]});let A=w.split(`
|
|
25
|
+
`),F=[],Q=v+A.length-1;for(let j=Q;j<Math.min(R.length,Q+3);j++)F.push({num:j+1,text:R[j]});t.push({success:!0,oldContent:w,newContent:_,originalStartLine:v,contextBefore:b,contextAfter:F}),f=f.substring(0,T)+_+f.substring(T+w.length)}return{content:f,results:t}},is=(e,o,t,n=8)=>{if(!t||t.length===0)return"";let s=e.split(/\r?\n/),r=o.split(/\r?\n/),l=`[DIFF_START]
|
|
26
|
+
`,u="\u2550".repeat(88),f=0,m=null;if(t.forEach((c,a)=>{if(!c.success)return;if(m===null)for(f=Math.max(0,c.originalStartLine-4);f<c.originalStartLine-1;)l+=`[UI_CONTEXT] ${f+1} |${r[f]||""}
|
|
27
|
+
`,f++;else{let T=m,w=T.originalStartLine+T.oldContent.split(`
|
|
28
|
+
`).length-1;if(c.originalStartLine-w-1>=n){let L=Math.min(r.length,f+3);for(;f<L;)l+=`[UI_CONTEXT] ${f+1} |${r[f]||""}
|
|
29
|
+
`,f++;for(l+=`[UI_CONTEXT] ${u}
|
|
30
30
|
`,f=Math.max(f,c.originalStartLine-4);f<c.originalStartLine-1;)l+=`[UI_CONTEXT] ${f+1} |${r[f]||""}
|
|
31
31
|
`,f++}else for(;f<c.originalStartLine-1;)l+=`[UI_CONTEXT] ${f+1} |${r[f]||""}
|
|
32
|
-
`,f++}let
|
|
33
|
-
`);
|
|
34
|
-
`});let p=c.originalStartLine+
|
|
35
|
-
`,f++;
|
|
36
|
-
`,f++}return l+="[DIFF_END]",l}});import
|
|
37
|
-
`).split(`
|
|
38
|
-
`).
|
|
39
|
-
|
|
40
|
-
`)).replace(
|
|
41
|
-
|
|
42
|
-
`),f=r?d:d?Wo(d,i-6):"";return _t.createElement(xn,{flexDirection:"column",borderStyle:n?"double":"round",borderColor:t?"#334155":n?"yellow":"cyan",paddingX:2,paddingY:t?0:1,width:"100%"},_t.createElement(xn,{marginBottom:1,justifyContent:"space-between",width:"100%"},_t.createElement(xn,{flexShrink:1,paddingRight:2},_t.createElement(wn,null,_t.createElement(wn,{color:t?"gray":n?"yellow":"cyan",bold:!0},t?"\u{1F3C1} FINISHED:":"\u26A1 EXECUTING:"," "),_t.createElement(wn,{color:t?"gray":"white"},e))),r&&_t.createElement(xn,{flexShrink:0,paddingX:1},_t.createElement(wn,{color:t?"gray":"magenta",bold:!0},"ADVANCE"))),f?_t.createElement(xn,{marginTop:t?0:1,backgroundColor:r?void 0:"#0a0a0a",paddingX:1},_t.createElement(wn,{color:t?"gray":void 0},f)):!t&&_t.createElement(xn,{marginTop:1,backgroundColor:r?void 0:"#0a0a0a",paddingX:1},_t.createElement(wn,{color:"gray",italic:!0},"Waiting for output...")),_t.createElement(xn,{justifyContent:"space-between",marginTop:1},t?_t.createElement(xn,null):_t.createElement(wn,{color:"gray",dimColor:!0,italic:!0},n?"Press TAB to unfocus, then double-press ESC to terminate.":"Double-press ESC to terminate if hanging."),_t.createElement(wn,{color:t?"#475569":n?"yellow":"cyan",bold:!0},t?"\u25CF ARCHIVED":n?"\u25B6 TERMINAL FOCUSED":"\u25CF LIVE (Press TAB to focus)")))})});var Zl,Oe,yn=le(()=>{Zl=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",Oe=(e=2)=>{let o=Zl();return o==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)}});import E from"react";import{Box as H,Text as ne}from"ink";var ec,tc,oc,nc,Vi,Tn,rc,zi,sc,ic,Ji,Qi,Ds,ac,Zi,ea=le(()=>{Ls();Fn();yn();ec={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"},tc=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 i=o.toLowerCase().indexOf(t);if(i===-1)break;let r=i,l=!1,d=i-1;for(;d>=0&&/\s/.test(o[d]);)d--;d>=0&&o[d]==="["&&(r=d,l=!0);let f=0,u=!1,c=null,a=i;for(;a<o.length;){let m=o[a];if(!c&&(m==="'"||m==='"'||m==="`")?c=m:c&&m===c&&o[a-1]!=="\\"&&(c=null),c||(m==="("?(f++,u=!0):m===")"&&f--),u&&f===0&&!c){let p=a;if(l){let h=a+1;for(;h<o.length&&/\s/.test(o[h]);)h++;h<o.length&&o[h]==="]"&&(p=h)}o=o.substring(0,r)+o.substring(p+1);break}if(a++,a===o.length)return o=o.substring(0,r),o}}return o.replace(/\[TOOL RESULT\]:?\s*/gi,"").split(`
|
|
32
|
+
`,f++}let d=c.oldContent.split(`
|
|
33
|
+
`);d.forEach((T,w)=>{l+=`-${c.originalStartLine+w}|${T}
|
|
34
|
+
`});let p=c.originalStartLine+d.length-1,h=s[p]||null,S=f;if(h!==null){let T=a<t.length-1?(t[a+1].originalStartLine||r.length)+10:r.length;for(let w=f;w<T;w++){if(r[w]===h){S=w;break}w===r.length-1&&(S=r.length)}}else S=r.length;for(;f<S;)l+=`+${f+1}|${r[f]||""}
|
|
35
|
+
`,f++;m=c}),m!==null){let c=Math.min(r.length,f+3);for(;f<c;)l+=`[UI_CONTEXT] ${f+1} |${r[f]||""}
|
|
36
|
+
`,f++}return l+="[DIFF_END]",l}});import Ut from"react";import{Box as kn,Text as In}from"ink";var as,Ws=re(()=>{Wn();as=Ut.memo(({command:e,output:o,completed:t=!1,isFocused:n=!1,columns:s=80,isPty:r=!1})=>{let u=(m=>{if(!m)return"";let c=[[]],a=0,d=0,p="",h=/\x1b\[([0-9;]*?)([a-zA-Z])/g,S=0,T,w=L=>{for(let _=0;_<L.length;_++){let R=L[_];if(R===`
|
|
37
|
+
`)for(a++,d=0;a>=c.length;)c.push([]);else if(R==="\r")d=0;else{for(;a>=c.length;)c.push([]);let v=c[a];for(;d>v.length;)v.push({char:" ",style:""});v[d]={char:R,style:p},d++}}};for(;(T=h.exec(m))!==null;){w(m.substring(S,T.index));let L=T[1],_=T[2],R=L?L.split(";").map(Number):[];if(_==="A"){let v=R[0]||1;a=Math.max(0,a-v)}else if(_==="B"){let v=R[0]||1;for(a=a+v;a>=c.length;)c.push([])}else if(_==="C"){let v=R[0]||1;d=d+v}else if(_==="D"){let v=R[0]||1;d=Math.max(0,d-v)}else if(_==="G"){let v=(R[0]||1)-1;d=Math.max(0,v)}else if(_==="H"||_==="f"){let v=(R[0]||1)-1,b=(R[1]||1)-1;for(a=Math.max(0,v),d=Math.max(0,b);a>=c.length;)c.push([])}else if(_==="K"){let v=R[0]||0;if(a<c.length){let b=c[a];if(v===0)b.length=d;else if(v===1)for(let A=0;A<d&&A<b.length;A++)b[A]={char:" ",style:""};else v===2&&(b.length=0)}}else if(_==="J"){let v=R[0]||0;(v===2||v===3)&&(c.length=0,c.push([]),a=0,d=0)}else if(_==="m"){let v=T[0];v==="\x1B[0m"?p="":p=v}S=h.lastIndex}w(m.substring(S));let I=c.map(L=>{let _="",R="";for(let v=0;v<L.length;v++){let b=L[v]||{char:" ",style:""};b.style!==R&&(R&&(_+="\x1B[0m"),_+=b.style,R=b.style),_+=b.char}return R&&(_+="\x1B[0m"),_});for(;I.length>0&&I[I.length-1]==="";)I.pop();return I.join(`
|
|
38
|
+
`)})(o).replace(/\n{3,}/g,`
|
|
39
|
+
|
|
40
|
+
`),f=r?u:u?Ho(u,s-6):"";return Ut.createElement(kn,{flexDirection:"column",borderStyle:n?"double":"round",borderColor:t?"#334155":n?"yellow":"cyan",paddingX:2,paddingY:t?0:1,width:"100%"},Ut.createElement(kn,{marginBottom:1,justifyContent:"space-between",width:"100%"},Ut.createElement(kn,{flexShrink:1,paddingRight:2},Ut.createElement(In,null,Ut.createElement(In,{color:t?"gray":n?"yellow":"cyan",bold:!0},t?"\u{1F3C1} FINISHED:":"\u26A1 EXECUTING:"," "),Ut.createElement(In,{color:t?"gray":"white"},e))),r&&Ut.createElement(kn,{flexShrink:0,paddingX:1},Ut.createElement(In,{color:t?"gray":"magenta",bold:!0},"ADVANCE"))),f?Ut.createElement(kn,{marginTop:t?0:1,backgroundColor:r?void 0:"#0a0a0a",paddingX:1},Ut.createElement(In,{color:t?"gray":void 0},f)):!t&&Ut.createElement(kn,{marginTop:1,backgroundColor:r?void 0:"#0a0a0a",paddingX:1},Ut.createElement(In,{color:"gray",italic:!0},"Waiting for output...")),Ut.createElement(kn,{justifyContent:"space-between",marginTop:1},t?Ut.createElement(kn,null):Ut.createElement(In,{color:"gray",dimColor:!0,italic:!0},n?"Press TAB to unfocus, then double-press ESC to terminate.":"Double-press ESC to terminate if hanging."),Ut.createElement(In,{color:t?"#475569":n?"yellow":"cyan",bold:!0},t?"\u25CF ARCHIVED":n?"\u25B6 TERMINAL FOCUSED":"\u25CF LIVE (Press TAB to focus)")))})});var Lc,Ie,rn=re(()=>{Lc=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",Ie=(e=2)=>{let o=Lc();return o==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)}});import C from"react";import{Box as X,Text as oe}from"ink";var Fc,$c,Pc,_c,fa,Mn,Nc,pa,Bc,Uc,ha,ga,Ys,Rc,xa,ya=re(()=>{Ws();Wn();rn();Fc={write_file:"WriteFile",update_file:"UpdateFile",read_folder:"ReadFolder",view_file:"ViewFile",exec_command:"ExecuteCommand",web_search:"WebSearch",web_scrape:"ReadSite",search_keyword:"SearchKeyword",write_pdf:"CreatePDF",write_docx:"CreateDocument",generate_image:"GenerateImage",WriteFile:"WriteFile",PatchFile:"PatchFile",ReadFolder:"ReadFolder",ReadFile:"ReadFile",Run:"RunCommand",WebSearch:"WebSearch",WebScrape:"WebScrape",SearchKeyword:"SearchKeyword",WritePDF:"WritePDF",WriteDoc:"WriteDoc",Memory:"Memory",Chat:"Chat",GenerateImage:"GenerateImage"},$c=e=>{if(!e)return e;let o=e.replace(/<\/think>(\r?\n){2}/gi,"</think>").replace(/(\r?\n){2}(?=\[?(?:tool:functions|tool\.functions|\s*turn\s*:))/gi,""),t="tool:functions.";for(;;){let s=o.toLowerCase().indexOf(t);if(s===-1)break;let r=s,l=!1,u=s-1;for(;u>=0&&/\s/.test(o[u]);)u--;u>=0&&o[u]==="["&&(r=u,l=!0);let f=0,m=!1,c=null,a=s;for(;a<o.length;){let d=o[a];if(!c&&(d==="'"||d==='"'||d==="`")?c=d:c&&d===c&&o[a-1]!=="\\"&&(c=null),c||(d==="("?(f++,m=!0):d===")"&&f--),m&&f===0&&!c){let p=a;if(l){let h=a+1;for(;h<o.length&&/\s/.test(o[h]);)h++;h<o.length&&o[h]==="]"&&(p=h)}o=o.substring(0,r)+o.substring(p+1);break}if(a++,a===o.length)return o=o.substring(0,r),o}}return o.replace(/\[TOOL RESULT\]:?\s*/gi,"").split(`
|
|
43
41
|
`).filter(n=>!n.trim().startsWith("SUCCESS:")&&!n.trim().startsWith("ERROR:")).join(`
|
|
44
|
-
`).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=>
|
|
45
|
-
`),
|
|
42
|
+
`).replace(/\[\s*turn\s*:\s*(continue|finish)\s*\]/gi,"").replace(/\[\[END\]\]/gi,"").replace(/\[\s*turn\s*:?.*?$/gi,"").replace(/\n\s*turn\s*:?.*?$/gi,"").replace(/\[\s*$/gi,"").replace(/\n\nResponded on .*/g,"").replace(/\n\n\[Prompted on: .*\]/g,"").replace(/(\$?\\?\/?\\rightarrow\$?|\$\\rightarrow\$)/gi,"\u2192").replace(/(\$?\\?\/?\\leftarrow\$?|\$\\leftarrow\$)/gi,"\u2190").replace(/(\$?\\?\/?\\uparrow\$?|\$\\uparrow\$)/gi,"\u2191").replace(/(\$?\\?\/?\\downarrow\$?|\$\\downarrow\$)/gi,"\u2193").replace(/(\$?\\?\/?\\leftrightarrow\$?|\$\\leftrightarrow\$)/gi,"\u2194").replace(/@\[TerminalName:.*?, ProcessId:.*?\]/gi,"").replace(/\b(write_file|update_file|read_folder|view_file|exec_command|web_search|web_scrape|search_keyword|write_pdf|write_docx|generate_image)\b/gi,n=>Fc[n.toLowerCase()]||n).trim()},Pc=(e,o=80)=>{if(!e)return null;let t=o-10,n=Ho(e.trim(),t);return C.createElement(X,{width:"100%"},C.createElement(oe,{italic:!0},C.createElement(Mn,{text:n,color:"gray"})))},_c=e=>e.replace(/\\multiply|\\mul|\\times/g,"\xD7").replace(/\\div/g,"\xF7").replace(/\\cdot/g,"\u22C5").replace(/\\infty/g,"\u221E").replace(/\\pm/g,"\xB1").replace(/\\leq/g,"\u2264").replace(/\\geq/g,"\u2265").replace(/\\neq/g,"\u2260").replace(/\\sqrt\s*\{([^}]+)\}/g,"\u221A($1)").replace(/\\sqrt\s*(\w+|\d+)/g,"\u221A($1)").replace(/\\alpha/g,"\u03B1").replace(/\\beta/g,"\u03B2").replace(/\\theta/g,"\u03B8").replace(/\\pi/g,"\u03C0").replace(/\\approx/g,"\u2248").replace(/\\Delta/g,"\u0394").replace(/\\sigma/g,"\u03C3").replace(/\\sum/g,"\u03A3").replace(/\\prod/g,"\u03A0").replace(/\\rightarrow|\\to/g,"\u2192").replace(/\\left\b|\\right\b/g,"").replace(/\\left\(|\\right\)/g,o=>o.includes("left")?"(":")").replace(/\\left\[|\\right\]/g,o=>o.includes("left")?"[":"]").replace(/\\\{|\\\}/g,o=>o.includes("{")?"{":"}").replace(/\\text\s*\{([^}]+)\}/g,"$1").replace(/\\text\s+(\w+)/g,"$1").replace(/\\%/g,"%"),fa=(e,o)=>{if(!e)return null;let t=e.replace(/\\frac\s*\{([^{}]*)\}\s*\{([^{}]*)\}/g,"($1/$2)");t=_c(t);let n=t.split(/(\\(?:mathbf|textbf|textit|underline|texttt)\{[^{}]*\})/g);return C.createElement(C.Fragment,{key:o},n.map((s,r)=>{if(s.startsWith("\\")){let l=s.match(/\\(\w+)\{([^{}]*)\}/);if(l){let u=l[1],f=l[2];return C.createElement(oe,{key:r,bold:u==="mathbf"||u==="textbf",italic:u==="textit",underline:u==="underline",color:u==="texttt"?"cyan":void 0},f)}}return s}))},Mn=C.memo(({text:e,color:o})=>{if(!e)return null;let t=e.split(/(```[\s\S]*?```|`[^`]+`|@\[.*?\]|\*\*.*?\*\*|\*.*?\*|\$.*?\$|\[.*?\]\s*\(.*?\)|\[.*?\]\s*\[.*?\]|https?:\/\/[^\s]+)/g);return C.createElement(oe,{color:o,wrap:"anywhere"},t.map((n,s)=>{if(!n)return null;if(n.startsWith("```")&&n.endsWith("```")){let r=n.slice(3,-3);return C.createElement(oe,{key:s,color:"cyan",backgroundColor:"#003333"}," ",r," ")}if(n.startsWith("**")&&n.endsWith("**"))return C.createElement(oe,{key:s,bold:!0,color:"white"},C.createElement(Mn,{text:n.slice(2,-2),color:"white"}));if(n.startsWith("*")&&n.endsWith("*"))return C.createElement(oe,{key:s,italic:!0,color:"gray"},C.createElement(Mn,{text:n.slice(1,-1),color:"gray"}));if(n.startsWith("`")&&n.endsWith("`")){let r=n.slice(1,-1),l=r.replace(/@\[(.*?)\]/g,(f,m)=>m.split("/").pop().split("\\").pop().replace(/:L/gi,"#L")),u=r.includes("@[");return C.createElement(oe,{key:s,color:"cyan",bold:u,backgroundColor:u?"#111124":"#003333"}," ",l," ")}if(n.startsWith("@[")&&n.endsWith("]")){let l=n.slice(2,-1).split("/").pop().split("\\").pop().replace(/:L/gi,"#L");return C.createElement(oe,{key:s,color:"cyan",bold:!0,backgroundColor:"#111124"}," ",l," ")}if(n.startsWith("$")&&n.endsWith("$")){let r=n.slice(1,-1);return C.createElement(oe,{key:s,color:"yellow"},fa(r,s))}if(n.startsWith("[")&&(n.includes("](")||n.includes("] ("))){let r=n.match(/\[(.*?)\]\s*\((.*?)\)/);if(r)return C.createElement(oe,{key:s},C.createElement(oe,{color:"cyan",underline:!0,bold:!0},r[1]),C.createElement(oe,{color:"gray",dimColor:!0,italic:!0}," (",r[2],")"))}if(n.startsWith("[")&&(n.includes("][")||n.includes("] ["))){let r=n.match(/\[(.*?)\]\s*\[(.*?)\]/);if(r)return C.createElement(oe,{key:s},C.createElement(oe,{color:"cyan",underline:!0,bold:!0},r[1]),C.createElement(oe,{color:"gray",dimColor:!0,italic:!0}," [",r[2],"]"))}return n.startsWith("http")?C.createElement(oe,{key:s,color:"cyan",underline:!0,italic:!0},n):fa(n,s)}))}),Nc=C.memo(({buffer:e,terminalWidth:o=80})=>{if(e.length<2)return null;let t=e.map(f=>{let m=f.split("|");return m[0]!==void 0&&m[0].trim()===""&&m.shift(),m.length>0&&m[m.length-1].trim()===""&&m.pop(),m.map(c=>c.trim())}),n=t[0],s=t.slice(2),r=Math.floor(100/n.length),l=o-8,u=Math.floor(l/n.length)-2;return C.createElement(X,{flexDirection:"column",borderStyle:"round",borderColor:"#454545ff",paddingX:1,marginY:0,width:"100%",flexGrow:1},C.createElement(X,{flexDirection:"row",borderStyle:"single",borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1,borderColor:"#444",marginBottom:1,paddingBottom:0,width:"100%"},n.map((f,m)=>C.createElement(X,{key:m,flexBasis:`${r}%`,flexGrow:1,flexShrink:0,paddingRight:2},C.createElement(Mn,{text:Ho(f,u),color:"cyan"})))),s.map((f,m)=>C.createElement(X,{key:m,flexDirection:"row",marginBottom:m===s.length-1?0:1,width:"100%"},f.map((c,a)=>C.createElement(X,{key:a,flexBasis:`${r}%`,flexGrow:1,flexShrink:0,paddingRight:2,flexDirection:"column"},C.createElement(Mn,{text:Ho(c,u),color:"white"}))))))}),pa=C.memo(({text:e,color:o="white",columns:t=80})=>{if(!e)return null;let n=e.split(`
|
|
43
|
+
`),s=[],r=[],l=[],u=f=>{r.length>0&&(s.push(C.createElement(Nc,{key:`table-${f}`,buffer:[...r],terminalWidth:t})),r=[]),l.length>0&&(s.push(C.createElement(X,{key:`quote-${f}`,borderStyle:"bold",borderLeft:!0,borderRight:!1,borderTop:!1,borderBottom:!1,borderColor:"gray",paddingLeft:1,marginY:1,flexDirection:"column"},l.map((m,c)=>C.createElement(Mn,{key:c,text:m,color:"gray"})))),l=[])};return n.forEach((f,m)=>{let c=f.trim(),a=c.startsWith("|"),d=c.startsWith(">");if(a)l.length>0&&u(m),r.push(f);else if(d)r.length>0&&u(m),l.push(c.replace(/^>\s*/,""));else{if(u(m),c===""){s.push(C.createElement(X,{key:m,height:1}));return}if(c==="---"||c==="***"||c==="___"){s.push(C.createElement(X,{key:m,marginY:1,borderStyle:"single",borderTop:!0,borderBottom:!1,borderLeft:!1,borderRight:!1,width:"100%",borderColor:"#333"}));return}let p=c.match(/^(#{1,6})\s+(.*)/);if(p){let I=p[1].length,L=p[2];s.push(C.createElement(X,{key:m,marginTop:1,marginBottom:1,width:"100%"},C.createElement(oe,{bold:!0,color:I===1?"cyan":I===2?"magenta":I===3?"yellow":I===4?"green":I===5?"blue":"white",underline:!0},L.toUpperCase())));return}let h=c.startsWith("* ")||c.startsWith("- "),S=/^\d+\.\s/.test(c),T=f.includes("\u2588")||f.includes("\u2554")||f.includes("\u255A")||f.includes("\u2550"),w="";if(T)w=f;else if(h||S){let I=h?" \u2022 ":c.match(/^\d+\.\s/)[0],L=" ".repeat(I.length),_=Ho(c.replace(/^[\*\-\d+\.]+\s/,""),t-(I.length+6));w=I+_.split(`
|
|
46
44
|
`).join(`
|
|
47
|
-
`+
|
|
48
|
-
`);return
|
|
49
|
-
`),c=String(
|
|
50
|
-
`),c=String(
|
|
51
|
-
`).map((a,
|
|
45
|
+
`+L)}else w=Ho(c,t-4);s.push(C.createElement(X,{key:m,width:"100%"},C.createElement(Mn,{text:w,color:o})))}}),u("final"),C.createElement(X,{flexDirection:"column",width:t-2},s)}),Bc=C.memo(({line:e,columns:o=80})=>{let t=e.includes("[UI_CONTEXT]"),n=e.replace("[UI_CONTEXT]","");if(t&&n.includes("\u2550"))return C.createElement(X,{backgroundColor:"#1a1a1a",paddingX:1,width:"100%"},C.createElement(oe,{color:"gray",dimColor:!0},"\u2550".repeat(Math.max(10,o-4))));let s=n.startsWith("-"),r=n.startsWith("+"),l=n[0],u=n.substring(1),f=u.indexOf("|"),m=f!==-1?u.substring(0,f).trim():"",c=f!==-1?u.substring(f+1):u,a=s?"#3a0c0c":r?"#0c3a1a":"#1a1a1a",d=s?"#ff4d4d":r?"#4dff88":t?"gray":"white";return C.createElement(X,{backgroundColor:a,paddingX:1,width:"100%"},C.createElement(X,{width:5,flexShrink:0},C.createElement(oe,{color:s?"#cf3a3a":r?"#3acf65":"gray",dimColor:t},m)),C.createElement(X,{width:2,flexShrink:0,marginLeft:1},C.createElement(oe,{color:d,bold:!0},s?"-":r?"+":" ")),C.createElement(X,{flexGrow:1,marginLeft:1},C.createElement(oe,{color:d,dimColor:t},Ho(c,o-14))))}),Uc=C.memo(({text:e,columns:o=80})=>{let t=e.match(/\[DIFF_START\]([\s\S]*?)\[DIFF_END\]/),s=(t?t[1].trim():"").split(`
|
|
46
|
+
`);return C.createElement(X,{flexDirection:"column",width:o-3,marginBottom:0},C.createElement(X,{flexDirection:"column",backgroundColor:"#1a1a1a",paddingY:0,width:"100%"},s.map((r,l)=>C.createElement(Bc,{key:l,line:r,columns:o-3}))))}),ha=C.memo(({text:e,columns:o=80})=>{if(!e)return null;if(e.includes("[DIFF_START]"))return C.createElement(Uc,{text:e,columns:o});if(e.includes("- Content Preview:")){let t=e.split("- Content Preview:"),n=t[0],s=t[1]||"",r="Check if Starting and Ending matches",l=s.split(r),u=l[0]?.trim()||"",f=l[1]?`${r}${l[1]}`:"",m=u.split(`
|
|
47
|
+
`),c=String(m.length).length;return C.createElement(X,{flexDirection:"column",width:o-3},C.createElement(X,{flexDirection:"column",borderStyle:"round",borderColor:"#444",paddingX:1,width:"100%"},C.createElement(X,{alignSelf:"flex-end",marginTop:-1,marginRight:1},C.createElement(oe,{backgroundColor:"#444",color:"white"}," FILE SNAPSHOT ")),C.createElement(X,{flexDirection:"column",paddingY:1,width:"100%"},m.map((a,d)=>C.createElement(X,{key:d,width:"100%"},C.createElement(X,{width:c+2,flexShrink:0},C.createElement(oe,{color:"gray",dimColor:!0},String(d+1).padStart(c," ")," ")),C.createElement(X,{flexGrow:1},C.createElement(oe,{color:"white"},a)))))))}if(e.includes("```")){let t=e.split(/(```\w*\n?[\s\S]*?(?:```|$))/g);return C.createElement(X,{flexDirection:"column",width:o-3},t.map((n,s)=>{if(n.startsWith("```")){let l=n.match(/```(\w*)\n?([\s\S]*?)(?:```|$)/),u=l?l[1]:"code",m=(l?l[2]:n.replace(/^```\w*\n?/,"").replace(/```$/,"")).trimEnd().split(`
|
|
48
|
+
`),c=String(m.length).length;return C.createElement(X,{key:s,flexDirection:"column",marginY:0,backgroundColor:"#111",borderStyle:"round",borderColor:"#333",paddingX:1,width:"100%"},C.createElement(X,{alignSelf:"flex-end",marginTop:-1,marginRight:1},C.createElement(oe,{backgroundColor:"#333",color:"white"}," ",u.toUpperCase()," ")),C.createElement(X,{flexDirection:"column",paddingY:1,width:"100%"},m.map((a,d)=>C.createElement(X,{key:d,width:"100%"},C.createElement(X,{width:c+2,flexShrink:0},C.createElement(oe,{color:"gray",dimColor:!0},String(d+1).padStart(c," ")," ")),C.createElement(X,{flexGrow:1},C.createElement(oe,{color:"cyan"},a))))))}let r=n;return s>0&&(r=r.replace(/^[\r\n]+/,"")),s<t.length-1&&(r=r.replace(/[\r\n]+$/,"")),r?C.createElement(pa,{key:s,text:r,columns:o-3}):null}))}return C.createElement(pa,{text:e,columns:o-3})}),ga=e=>{let o=Math.round(e/1e3);if(o<=0)return"0s";let t=Math.floor(o/60),n=o%60;return t>0?`${t}m ${n}s`:`${o}s`},Ys=C.memo(({msg:e,showFullThinking:o,columns:t=80})=>{let n=e.role==="system"&&(e.text?.includes("[DIFF_START]")||e.text?.includes("- Content Preview:")),s=e.role==="system"&&e.text?.includes("[TOOL RESULT]: ERROR:")&&!e.text?.includes("[DIFF_START]")&&(e.toolName==="update_file"||e.text?.includes("Could not find exact match")),r=e.isTerminalRecord;if(e.isHomeWarning)return C.createElement(X,{marginBottom:1,paddingX:1,width:"100%"},C.createElement(X,{flexDirection:"column",borderStyle:"round",borderColor:"red",padding:0,width:"100%"},C.createElement(X,{paddingX:1,backgroundColor:"#3a0000"},C.createElement(oe,{color:"red",bold:!0},e.text)),C.createElement(X,{paddingX:1,marginTop:1,marginBottom:1},C.createElement(oe,{color:"white"},e.subText))));if(e.isLogo)return C.createElement(X,{flexDirection:"column",alignItems:"center",width:"100%",marginY:1},C.createElement(oe,null,e.text));if(e.id&&String(e.id).startsWith("welcome"))return C.createElement(X,{flexDirection:"column",alignItems:"center",width:"100%",marginY:1},C.createElement(X,{borderStyle:"round",borderColor:"gray",paddingX:3,paddingY:0},C.createElement(oe,{color:"cyan",bold:!0},e.text.trim())));if(e.isVisualFeedback)return C.createElement(X,{marginBottom:0,marginTop:0,paddingX:1,width:"100%"},C.createElement(oe,{color:"white"},e.text));if(s)return C.createElement(X,{marginBottom:1},C.createElement(X,{flexDirection:"column",borderStyle:"round",borderColor:"red",paddingX:1,paddingY:0},C.createElement(oe,{color:"red",bold:!0,underline:!0},"\u274C PATCH FAILED"),C.createElement(X,{marginTop:1},C.createElement(oe,{color:"red"},"Patch failed: ",C.createElement(oe,{color:"white",bold:!0},"Model generated malformed edit.")))));if(e.role==="system"&&e.text?.includes("[TOOL RESULT]")&&!n&&!r&&!s)return null;if(e.isImageStats)return C.createElement(X,{marginBottom:1,paddingX:1,width:"100%"},C.createElement(X,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",padding:0,width:"100%"},C.createElement(X,{paddingX:1,backgroundColor:"#0e1b21"},C.createElement(oe,{color:"cyan",bold:!0},"\u{1F4B3} IMAGE STATS")),C.createElement(X,{paddingX:1,marginTop:1,marginBottom:1,flexDirection:"column"},e.text.split(`
|
|
49
|
+
`).map((a,d)=>C.createElement(oe,{key:d,color:"white"},a)))));if(e.isAskRecord){let a=e.text.match(/Selection: (.*)/),d=a?a[1]:"No selection",p=Ie(2);return C.createElement(X,{marginBottom:1,paddingX:1,width:"100%"},C.createElement(X,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},C.createElement(X,{paddingX:1},C.createElement(oe,{color:"cyan",bold:!0},"\u{1F4AC} AGENT REQUEST: RESOLVED")),C.createElement(X,{paddingX:1,marginTop:1,marginBottom:1},C.createElement(oe,{color:"white"},"Selection: ",C.createElement(oe,{color:"yellow",bold:!0},d)))))}if(e.isAboutRecord)return C.createElement(X,{marginBottom:1,paddingX:1,width:"100%"},C.createElement(X,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},C.createElement(X,{paddingX:1},C.createElement(oe,{color:"cyan",bold:!0},"\u{1F4A0} ABOUT FLUX FLOW")),C.createElement(X,{paddingX:1,marginTop:1,marginBottom:1},C.createElement(oe,null,e.text))));if(e.isUpdateNotification)return C.createElement(X,{marginBottom:1,paddingX:1,width:"100%"},C.createElement(X,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},C.createElement(X,{paddingX:1},C.createElement(oe,{color:"cyan",bold:!0},"\u{1F680} FLUX FLOW UPDATE AVAILABLE")),C.createElement(X,{paddingX:1,marginTop:1,marginBottom:1},C.createElement(ha,{text:e.text,columns:t}))));if(e.isHelpRecord)return C.createElement(X,{marginBottom:1,paddingX:1,width:"100%"},C.createElement(X,{flexDirection:"column",borderStyle:"round",borderColor:"magenta",paddingX:2,paddingY:1,width:"100%"},C.createElement(oe,{color:"magenta",bold:!0,underline:!0},"\u{1F4DC} COMMAND REFERENCE"),C.createElement(X,{flexDirection:"column",marginTop:1},[{cmd:"/quit",desc:"Exit and shutdown Flux"},{cmd:"/help",desc:"Show all available commands"},{cmd:"/clear",desc:"Clear terminal screen"},{cmd:"/resume",desc:"Load previous session"},{cmd:"/revert",desc:"Revert codebase to checkpoint"},{cmd:"/save",desc:"Force save current chat"},{cmd:"/export",desc:"Export current chat in a .txt file"},{cmd:"/chats",desc:"List all chat sessions"},{cmd:"/image",desc:"Generate images"},{cmd:"/mode",desc:"Toggle Flux/Flow modes"},{cmd:"/thinking",desc:"Set AI reasoning depth"},{cmd:"/model",desc:"Switch AI model"},{cmd:"/settings",desc:"Configure system prefs"},{cmd:"/key",desc:"Manage API keys"},{cmd:"/profile",desc:"Edit developer persona"},{cmd:"/memory",desc:"Manage agent memory"},{cmd:"/stats",desc:"Show session usage"},{cmd:"/reset",desc:"Wipe all project data"},{cmd:"/about",desc:"Project info & credits"},{cmd:"/changelog",desc:"View latest updates"},{cmd:"/fluxflow",desc:"Project management"},{cmd:"/update",desc:"Check/Install updates"}].map((d,p)=>C.createElement(X,{key:p,flexDirection:"row"},C.createElement(X,{width:15},C.createElement(oe,{color:"cyan",bold:!0},d.cmd)),C.createElement(oe,{color:"gray"}," - ",d.desc))))));if(e.isTerminalRecord){let a=e.text.match(/COMMAND: (.*)/),d=e.text.match(/PTY: (true|false)/),p=e.text.match(/OUTPUT: ([\s\S]*)/),h=a?a[1]:"Unknown",S=d?d[1]==="true":!1,T=p?p[1]:"";return C.createElement(X,{marginBottom:1,paddingX:1,width:"100%"},C.createElement(as,{command:h,output:T,completed:!0,columns:t,isPty:S}))}let[u,f]=C.useState(!e.isStreaming),m=C.useMemo(()=>$c(e.text),[e.text]);C.useEffect(()=>{e.isStreaming&&f(!1)},[e.id]);let c=C.useMemo(()=>e.role==="think"&&!o?"Thinking...":e.isStreaming?m:m.trimEnd(),[m,e.role,o,e.isStreaming]);return C.createElement(X,{marginBottom:e.role==="think"?0:e.role==="user"?1:e.role==="agent"?0:1,marginTop:(e.role==="think"||e.role==="user"||e.role==="agent",0),flexDirection:"column",flexShrink:0,width:"100%",flexGrow:1},e.role==="user"?C.createElement(X,{backgroundColor:"#262626",paddingX:1,paddingY:1,width:"100%",flexDirection:"column"},Ho(c.replace(/\r\n/g,`
|
|
52
50
|
`).replace(/\r/g,`
|
|
53
51
|
`).replace(/\\\n/g,`
|
|
54
52
|
`).replace(/\\$/,""),t-6).split(`
|
|
55
|
-
`).map((a,
|
|
56
|
-
`),columns:t}),e.memoryUpdated&&
|
|
53
|
+
`).map((a,d)=>C.createElement(X,{key:d,flexDirection:"row",width:"100%"},C.createElement(X,{flexShrink:0,width:2},C.createElement(oe,{bold:!0,color:"white"},d===0?"\u276F":" ")),C.createElement(X,{flexGrow:1,marginLeft:1},C.createElement(Mn,{text:a,color:e.color||"white"}))))):e.role==="think"?C.createElement(X,{flexDirection:"column",marginTop:0,marginBottom:0,paddingX:1,width:"100%"},e.isStreaming&&!e.duration?C.createElement(oe,{bold:!0,color:"white"},"\u2727 Thinking..."):C.createElement(oe,{bold:!0,color:"white"},"\u2726 Thought",e.duration?C.createElement(oe,{color:"gray"}," for ",C.createElement(oe,{bold:!0,color:"cyan"},ga(e.duration))):""),C.createElement(X,{borderStyle:"single",borderLeft:!0,borderRight:!1,borderTop:!1,borderBottom:!1,paddingLeft:2,paddingTop:1,paddingBottom:1,flexDirection:"column",width:"100%"},Pc(c,t))):C.createElement(X,{flexDirection:"column",paddingX:1,marginTop:0,width:"100%"},C.createElement(ha,{text:c.replace(/ \|\n\n/g,` |
|
|
54
|
+
`),columns:t}),e.memoryUpdated&&C.createElement(X,{marginTop:1,width:"100%"},C.createElement(oe,{color:"yellow",italic:!0},"\u2728 [Memory Updated]")),e.role==="agent"&&e.workedDuration?C.createElement(X,{marginTop:1,marginBottom:2,width:"100%"},C.createElement(oe,null,"["),C.createElement(oe,{color:"gray"},"\u26A1 Worked for ",C.createElement(oe,{bold:!0,color:"cyan"},ga(e.workedDuration))),C.createElement(oe,null,"]")):null))}),Rc=C.memo(({messages:e,showFullThinking:o,columns:t=80})=>C.createElement(X,{flexDirection:"column",width:"100%"},e.map((n,s)=>C.createElement(Ys,{key:n.id||s,msg:n,showFullThinking:o,columns:t})))),xa=Rc});import We from"react";import{Box as sn,Text as Rt}from"ink";var Wc,wa,Ta=re(()=>{Wn();Wc=We.memo(({mode:e,thinkingLevel:o,tokens:t="0.0k",tokensTotal:n="0.0k",chatId:s="NEW-SESSION",isMemoryEnabled:r=!0,apiTier:l="Free",aiProvider:u="Google"})=>{let f=e==="Flux"?"yellow":"cyan",m=e==="Flux"?"\u26A1":"\u{1F30A}",c=256e3;return(u==="DeepSeek"||u==="Google"&&l==="Paid")&&(c=4e5),We.createElement(sn,{borderStyle:"round",borderColor:"gray",flexDirection:"row",justifyContent:"space-between",paddingX:1,width:"100%"},We.createElement(sn,null,We.createElement(sn,{marginRight:1},We.createElement(Rt,{color:f,bold:!0},m," ",e.toUpperCase())),We.createElement(Rt,{color:"gray",dimColor:!0},"\u2503 "),We.createElement(sn,{marginX:1},We.createElement(Rt,{color:"magenta"},"\u{1F9E0} ",o)),We.createElement(Rt,{color:"gray",dimColor:!0},"\u2503 "),We.createElement(sn,{marginX:1},We.createElement(Rt,{color:"gray"},"MEM: "),We.createElement(Rt,{color:r?"green":"red",bold:!0},r?"ON":"OFF"))),We.createElement(sn,{flexGrow:1,justifyContent:"center",paddingX:2},We.createElement(Rt,null,"\u{1F4C1}"),We.createElement(Rt,{color:"gray",italic:!0}," ",ma(process.cwd(),35))),We.createElement(sn,null,We.createElement(Rt,{color:"gray",dimColor:!0},"\u2503 "),We.createElement(sn,{marginX:1},We.createElement(Rt,null,"\u2728"),We.createElement(Rt,{color:"blue"}," ",so(n)," ",We.createElement(Rt,{dimColor:!0},"(",(t/c*100).toFixed(0),"%)"))),We.createElement(Rt,{color:"gray",dimColor:!0},"\u2503 "),We.createElement(sn,{marginLeft:1},We.createElement(Rt,null,"\u{1F194}"),We.createElement(Rt,{color:"gray",dimColor:!0,italic:!0}," ",s),(l==="Custom"||l==="Paid")&&We.createElement(Rt,{color:"gray",dimColor:!0}," | ",We.createElement(Rt,{color:"green",bold:!0},"PAID")))))}),wa=Wc});import Fo from"react";import{Box as nr,Text as ls}from"ink";import Yc from"ink-select-input";function fo({title:e,subtitle:o,items:t,onSelect:n}){return Fo.createElement(nr,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,marginTop:1,flexShrink:0,width:"100%"},Fo.createElement(nr,{paddingX:1,paddingY:0,marginBottom:o?0:1},Fo.createElement(ls,{color:"magenta",bold:!0},"\u{1F527} ",typeof e=="string"?e.toUpperCase():e)),o&&Fo.createElement(nr,{paddingX:1,marginBottom:1},Fo.createElement(ls,{color:"yellow",dimColor:!0,italic:!0}," ",o)),Fo.createElement(nr,{flexDirection:"column",width:"100%"},Fo.createElement(Yc,{items:t,onSelect:n,itemComponent:jc,indicatorComponent:()=>null})),Fo.createElement(nr,{paddingX:1,marginTop:1},Fo.createElement(ls,{color:"gray",dimColor:!0,italic:!0},"(Arrows to select \u2022 Enter to confirm)")))}var jc,Sa=re(()=>{jc=({label:e,isSelected:o})=>{let t=e==="Cancel"||e==="Back"||e.toLowerCase().includes("exit")||e.toLowerCase().includes("back");return Fo.createElement(nr,{marginTop:t?1:0,backgroundColor:o?"#2a2a2a":void 0,paddingX:1,width:"100%"},Fo.createElement(ls,{color:o?"cyan":"white",bold:o},o?"\u276F ":" ",e))}});var ne,Xt=re(()=>{ne=e=>{let o={};if(!e)return o;let t=0;for(;t<e.length;){for(;t<e.length&&/[\s,]/.test(e[t]);)t++;if(t>=e.length)break;let n=e.substring(t).match(/^(\w+)\s*=\s*/);if(!n){t++;continue}let s=n[1];t+=n[0].length;let r="";if(t<e.length&&(e[t]==='"'||e[t]==="'"||e[t]==="`")){let l=e[t];t++;let u=t,f=-1,m=t;for(;m<e.length;){let a=e.indexOf(l,m);if(a===-1)break;let d=0;for(let T=a-1;T>=0&&e[T]==="\\";T--)d++;if(d%2!==0){m=a+1;continue}let p=e.substring(a+1),h=p.trim(),S=h===""||/^,\s*\w+\s*=/.test(h)||h.startsWith(")")&&(h.length===1||/^\)\s*([,\]\s]|tool:)/i.test(h));if(S&&p.startsWith(`
|
|
57
55
|
`)){let T=h.split(`
|
|
58
|
-
`)[0];if(!T.includes("=")&&!T.includes(")")){
|
|
59
|
-
`;case"r":return"\r";case"t":return" ";case"\\":return"\\";default:return
|
|
56
|
+
`)[0];if(!T.includes("=")&&!T.includes(")")){m=a+1;continue}}if(S){f=a;break}m=a+1}f!==-1?(r=e.substring(u,f),t=f+1):(r=e.substring(u),t=e.length);let c=s.toLowerCase().includes("path")||["dest","source","to","from"].includes(s.toLowerCase());r=r.replace(/\\(.)/g,(a,d)=>{switch(d){case"n":return`
|
|
57
|
+
`;case"r":return"\r";case"t":return" ";case"\\":return"\\";default:return d===l?l:a}})}else if(t<e.length&&e[t]==="["){let l=0,u=null,f=t,m=-1;for(let c=t;c<e.length;c++){let a=e[c];if(u&&a===u){let d=0;for(let p=c-1;p>=0&&e[p]==="\\";p--)d++;d%2===0&&(u=null)}else!u&&(a==='"'||a==="'"||a==="`")&&(u=a);if(!u&&(a==="["?l++:a==="]"&&l--,l===0)){m=c;break}}if(m!==-1){r=e.substring(f,m+1),t=m+1;try{let c=r.trim();c.startsWith("'")||c.includes("'")}catch{}}else r=e.substring(f),t=e.length}else{let l=e.substring(t),u=l.match(/,\s*\w+\s*=|(?:\s*\)\s*(?:$|\]))/);if(u){let f=u.index;r=l.substring(0,f).trim(),t+=f}else r=l.trim(),t=e.length}r==="true"?r=!0:r==="false"?r=!1:typeof r=="string"&&!isNaN(r)&&r.trim()!==""&&(r=Number(r)),typeof r=="string"&&(s.toLowerCase().includes("path")||["dest","source","to","from"].includes(s.toLowerCase()))&&(r=r.replace(/\x0C/g,"\\f").replace(/\x0D/g,"\\r").replace(/\x0B/g,"\\v").replace(/\x08/g,"\\b")),o[s]=r}return o}});import{execSync as Gc}from"child_process";var Or,rr,Ea,js=re(async()=>{await Dr();Or=null,rr=()=>{if(process.platform!=="win32")return!1;if(Or!==null)return Or;try{Gc('powershell.exe -NoProfile -Command "exit"',{stdio:"ignore"}),Or=!0}catch{Or=!1}return Or},Ea=(e,o,t,n)=>`
|
|
60
58
|
-- TOOL DEFINITIONS --
|
|
61
59
|
Access to internal tools. MUST use the exact syntax on a new line: [tool:functions.ToolName(args)]
|
|
62
60
|
|
|
@@ -64,6 +62,7 @@ MANDATORY TOOL USAGE POLICY:
|
|
|
64
62
|
- **MAX 3 TOOL CALLS PER TURN. Next Turn, verify results, plan next**
|
|
65
63
|
${e==="Flux"?`- USE multiple search & replace on patch tool if editing same file/path with many edits \u2190 **MANDATORY where possible**
|
|
66
64
|
- Tool execution denied? MUST use 'Ask' tool immediately to ask for reason/changes. NEVER END RESPONSE OR PROCEED BLINDLY \u2190 **MANDATORY**
|
|
65
|
+
- FileMap >> ReadFile where possible
|
|
67
66
|
`:""}- No brute force, no spamming of tools
|
|
68
67
|
${e==="Flux"?`- **File Tools >> Code in chat**
|
|
69
68
|
`:""}
|
|
@@ -76,40 +75,41 @@ ${e==="Flux"?`- **File Tools >> Code in chat**
|
|
|
76
75
|
|
|
77
76
|
${e==="Flux"?`- PROJECT TOOLS (path = relative to CWD, path separator: '/') -
|
|
78
77
|
1. [tool:functions.ReadFile(path="...", startLine=number, endLine=number)]. ${n!=="Google"?`${t?"Supports images/docs. User gives image/doc: VIEW FIRST":"No Multimodal support"}`:"Supports images/docs. User gives image/doc: VIEW FIRST"}
|
|
79
|
-
2. [tool:functions.
|
|
80
|
-
3. [tool:functions.
|
|
81
|
-
4. [tool:functions.
|
|
82
|
-
5. [tool:functions.
|
|
83
|
-
6. [tool:functions.
|
|
84
|
-
7. [tool:functions.
|
|
85
|
-
8. [tool:functions.
|
|
78
|
+
2. [tool:functions.FileMap(path="...")]. Shows file structure. Does NOT read file contents. Only Dependency, Function, Variable Maps. Token Efficient. Need File structure? FileMap >> ReadFile
|
|
79
|
+
3. [tool:functions.ReadFolder(path="...")]. Detailed DIR stats
|
|
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
|
+
5. [tool:functions.WriteFile(path="...", content="...")]. Creates/Overwrites. File Exist? PatchFile > WriteFile. Verify Imports
|
|
82
|
+
6. [tool:functions.SearchKeyword(keyword="...", file="optional")]. Global project search. If 'file' is provided, searches only that file. Finds definitions/logic without reading every file
|
|
83
|
+
7. [tool:functions.Run(command="...")]. Runs ${o==="Windows"?rr()?`${Yn?"Interactive ":""}WINDOWS POWERSHELL ONLY`:`${Yn?"Interactive ":""}WINDOWS CMD ONLY`:`${Yn?"Interactive ":""}BASH`} command. Destructive/Irreversible ops -> Ask user. **TOOL DENY RULE APPLIES**. **1 CALL LIMIT OR 3 CONSECUTIVE RUN TOOL ONLY**
|
|
84
|
+
8. [tool:functions.WritePDF(path="...", content="...", orientation="...")]. PROACTIVE A4 PAGE BREAKS MUST IN CSS. HTML/CSS for PREMIUM layout
|
|
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
|
|
90
|
+
- File structure: Real newlines for code formatting`.trim():"\n- FILE TOOLS ARE NOT AVAILABLE IN FLOW (Tell user to,` /mode flux` if needed)".trim()}`.trim()});import{spawn as Gs}from"child_process";var cs,Yn,us,Lr,It,$o,Mo,ba,Ca,Xs,Hs,Dr=re(async()=>{Xt();await js();cs=null;try{let e=await import("node-pty");cs=e.default||e}catch{}Yn=!!cs,us=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),Lr=e=>{if(!e)return"";let o=[[]],t=0,n=0,s=/\x1b\[([0-9;]*?)([a-zA-Z])/g,r=0,l,u=m=>{for(let c=0;c<m.length;c++){let a=m[c];if(a===`
|
|
91
|
+
`)for(t++,n=0;t>=o.length;)o.push([]);else if(a==="\r")n=0;else{for(;t>=o.length;)o.push([]);let d=o[t];for(;n>d.length;)d.push(" ");d[n]=a,n++}}};for(;(l=s.exec(e))!==null;){u(e.substring(r,l.index));let m=l[1],c=l[2],a=m?m.split(";").map(Number):[];if(c==="A"){let d=a[0]||1;t=Math.max(0,t-d)}else if(c==="B"){let d=a[0]||1;for(t=t+d;t>=o.length;)o.push([])}else if(c==="C"){let d=a[0]||1;n=n+d}else if(c==="D"){let d=a[0]||1;n=Math.max(0,n-d)}else if(c==="G"){let d=(a[0]||1)-1;n=Math.max(0,d)}else if(c==="H"||c==="f"){let d=(a[0]||1)-1,p=(a[1]||1)-1;for(t=Math.max(0,d),n=Math.max(0,p);t>=o.length;)o.push([])}else if(c==="K"){let d=a[0]||0;if(t<o.length){let p=o[t];if(d===0)p.length=n;else if(d===1)for(let h=0;h<n&&h<p.length;h++)p[h]=" ";else d===2&&(p.length=0)}}else if(c==="J"){let d=a[0]||0;(d===2||d===3)&&(o.length=0,o.push([]),t=0,n=0)}r=s.lastIndex}u(e.substring(r));let f=o.map(m=>m.join(""));for(;f.length>0&&f[f.length-1]==="";)f.pop();return f.join(`
|
|
92
|
+
`)},It=null,$o=!1,Mo=e=>{try{It&&($o&&typeof It.write=="function"?It.write(e):It.stdin&&It.stdin.writable&&It.stdin.write(e))}catch{}},ba=()=>{if(It){try{$o&&typeof It.destroy=="function"?It.destroy():typeof It.kill=="function"&&(process.platform==="win32"?Gs("taskkill",["/pid",It.pid,"/f","/t"]):It.kill("SIGKILL"))}catch{}It=null,$o=!1}},Ca=(e,o=!1)=>{if(process.platform!=="win32")return e;let t=[],n="",s=null,r=!1;for(let c=0;c<e.length;c++){let a=e[c];if(r){n+=a,r=!1;continue}if(a==="\\"){if(e[c+1]===" "){n+=" ",c++;continue}n+=a,r=!0;continue}s?(a===s&&(s=null),n+=a):a==='"'||a==="'"?(s=a,n+=a):a===";"&&!n.includes("://")?(n.length>0&&(t.push(n),n=""),t.push(o?";":"&")):a==="&"&&!n.includes("://")?e[c+1]==="&"?(n.length>0&&(t.push(n),n=""),t.push("&&"),c++):(n.length>0&&(t.push(n),n=""),t.push("&")):a==="|"&&!n.includes("://")?(n.length>0&&(t.push(n),n=""),t.push("|")):/\s/.test(a)?n.length>0&&(t.push(n),n=""):n+=a}n.length>0&&t.push(n);let l=c=>!(!c.includes("/")||/^(https?|file|ftp):\/\//i.test(c)||c.startsWith("/")&&(c.match(/\//g)||[]).length===1||/\s\/|\/\s/.test(c)||/[\(\)\{\}\;\<\>\=\'\"]/.test(c)),u=[];for(let c=0;c<t.length;c++){let a=t[c];if(a==="mkdir"&&o&&rr()){let d=[],p=c+1;for(;p<t.length;){let h=t[p];if([">",">>","<","&","&&","|","||",";"].includes(h))break;h!=="-p"&&h!=="--parents"&&h!=="-v"&&h!=="--verbose"&&d.push(h),p++}if(d.length>0){let h=d.map(S=>{let T=S.replace(/^['"]|['"]$/g,""),w=S;return l(T)&&(w=S.replace(/\//g,"\\")),w});u.push("New-Item","-ItemType","Directory","-Force","-Path",h.join(","))}else u.push("New-Item","-ItemType","Directory","-Force");c=p-1;continue}if(a==="rm"&&o&&rr()){let d=[],p=!1,h=!1,S=c+1;for(;S<t.length;){let w=t[S];if([">",">>","<","&","&&","|","||",";"].includes(w))break;w==="-rf"||w==="-fr"?(p=!0,h=!0):w==="-r"||w==="-R"||w==="--recursive"?p=!0:w==="-f"||w==="--force"?h=!0:d.push(w),S++}let T=["Remove-Item"];if(p&&T.push("-Recurse"),h&&T.push("-Force"),d.length>0){let w=d.map(I=>{let L=I.replace(/^['"]|['"]$/g,""),_=I;return l(L)&&(_=I.replace(/\//g,"\\")),_});T.push("-Path",w.join(","))}u.push(...T),c=S-1;continue}if(a==="cp"&&o&&rr()){let d=[],p=!1,h=!1,S=c+1;for(;S<t.length;){let w=t[S];if([">",">>","<","&","&&","|","||",";"].includes(w))break;w==="-r"||w==="-R"||w==="--recursive"?p=!0:w==="-f"||w==="--force"?h=!0:d.push(w),S++}let T=["Copy-Item"];if(p&&T.push("-Recurse"),h&&T.push("-Force"),d.length>0){let w=d.map(I=>{let L=I.replace(/^['"]|['"]$/g,""),_=I;return l(L)&&(_=I.replace(/\//g,"\\")),_});if(w.length>1){let I=w.pop();T.push("-Path",w.join(","),"-Destination",I)}else T.push("-Path",w[0])}u.push(...T),c=S-1;continue}if(a==="touch"&&o&&rr()){let d=[],p=c+1;for(;p<t.length;){let h=t[p];if([">",">>","<","&","&&","|","||",";"].includes(h))break;d.push(h),p++}if(d.length>0){let S=`(${d.map(T=>{let w=T.replace(/^['"]|['"]$/g,""),I=T;return l(w)&&(I=T.replace(/\//g,"\\")),I}).join(", ")}) | ForEach-Object { if (Test-Path $_) { (Get-Item $_).LastWriteTime = [System.DateTime]::Now } else { $null | Out-File -FilePath $_ } }`;u.push(S)}c=p-1;continue}if(a==="|"&&t[c+1]==="tee"){t[c+2]==="-a"?(u.push(">>"),c+=2):(u.push(">"),c+=1);continue}if(a==="|"&&t[c+1]==="cat"&&t[c+2]===">"){u.push(">"),c+=2;continue}if(a==="|"){let d=t[c+1];if(d){let p=d.replace(/^['"]|['"]$/g,""),h=/\.(txt|md|json|log|csv|html|css|py|js|xml|yaml|yml|pdf|docx|pptx|xlsx)$/i.test(p);if(l(p)&&h){u.push(">");continue}}}u.push(a)}let f=!1,m=u.map(c=>{if(c==="echo")return f=!0,c;[">",">>","<","&","&&","|","||",";"].includes(c)&&(f=!1);let d=/^['"]|['"]$/.test(c),p=c;f&&d&&(p=c.replace(/^['"]|['"]$/g,""));let h=/^['"]|['"]$/.test(p),S=p.replace(/^['"]|['"]$/g,"");l(S)&&(p=p.replace(/\//g,"\\"));let T=p.replace(/^['"]|['"]$/g,"");return T.includes(" ")&&!h&&(p=`"${T}"`),p});if(o){let c="",a=0;for(let d=0;d<m.length;d++){let p=m[d];p==="&&"?(c+="; if ($?) {",a++):p===";"?(c+=" }".repeat(a)+";",a=0):(c&&!c.endsWith(" ")&&!c.endsWith("{")&&(c+=" "),c+=p)}return c+=" }".repeat(a),c}return m.join(" ")},Xs=async(e,o={})=>{let{command:t}=ne(e),{onChunk:n}=o;if(!t)return'ERROR: Missing "command" argument for exec_command.';let s=process.platform==="win32",r=o.systemSettings||{},l={};return r.networkAccess===!1&&(l.HTTP_PROXY="http://127.0.0.1:9999",l.HTTPS_PROXY="http://127.0.0.1:9999",l.ALL_PROXY="socks5://127.0.0.1:9999",l.http_proxy="http://127.0.0.1:9999",l.https_proxy="http://127.0.0.1:9999",l.all_proxy="socks5://127.0.0.1:9999",l.NO_PROXY="localhost,127.0.0.1"),new Promise(u=>{let f=m=>{let c=Ca(t,m),a=s?m?"powershell.exe":"cmd.exe":process.env.SHELL||"bash",d=s?m?["-NoProfile","-Command",c]:["/c",c]:["-c",c];if(cs)try{let p=cs.spawn(a,d,{name:"xterm-256color",cols:o.cols||120,rows:o.rows||30,cwd:process.cwd(),env:{...process.env,CI:"false",TERM:"xterm-256color",FORCE_COLOR:"1",...l}});It=p,$o=!0;let h="",S=!1;return p.onData(T=>{if(!S){h+=T,n&&n(T);let w=us(h);/(?:Network:\s+use\s+--host\s+to|Network:\s+Type\s+--host\s+to|Local:\s+http:\/\/localhost:\d+|ready in \d+\s*ms|Compiled successfully|Development server is running|Listening on:)/i.test(w)&&(S=!0,setTimeout(()=>u(`SUCCESS: Dev server started successfully in background.
|
|
91
93
|
|
|
92
|
-
${
|
|
93
|
-
`).replace(/\r/g,`
|
|
94
|
-
`),M=ts(y).replace(/\n{3,}/g,`
|
|
94
|
+
${w}`),500))}}),p.onExit(({exitCode:T})=>{if(S)return;It=null;let w=Lr(h||""),I=us(w).replace(/\n{3,}/g,`
|
|
95
95
|
|
|
96
|
-
`)||"Command executed with no output.";
|
|
96
|
+
`)||"Command executed with no output.";u(T!==0?`ERROR: Command [${t}] failed with exit code [${T}].
|
|
97
97
|
|
|
98
|
-
${
|
|
98
|
+
${I}`:`SUCCESS: Command [${t}] completed.
|
|
99
99
|
|
|
100
|
-
${
|
|
100
|
+
${I}`)}),!0}catch(p){return s&&m&&p.code==="ENOENT"?!1:(Hs(u,c,t,l,n,m),!0)}else return Hs(u,c,t,l,n,m),!0};s&&f(!0)||f(!1)})},Hs=(e,o,t,n,s,r=!0)=>{let l=process.platform==="win32",u=l?r?"powershell.exe":"cmd.exe":process.env.SHELL||"bash",m=l?Gs(u,l?r?["-NoProfile","-Command",o]:["/c",o]:["-c",o],{cwd:process.cwd(),env:{...process.env,...n}}):Gs(o,{shell:!0,cwd:process.cwd(),env:{...process.env,CI:"false",TERM:"xterm-256color",FORCE_COLOR:"1",...n}});It=m,$o=!1,m.stdin&&m.stdin.on("error",()=>{It=null});let c="",a="",d=!1;m.stdout.on("data",p=>{if(!d){let h=p.toString();c+=h,s&&s(h);let S=us(c);/(?:Network:\s+use\s+--host\s+to|Network:\s+Type\s+--host\s+to|Local:\s+http:\/\/localhost:\d+|ready in \d+\s*ms|Compiled successfully|Development server is running|Listening on:)/i.test(S)&&(d=!0,setTimeout(()=>e(`SUCCESS: Dev server started successfully in background.
|
|
101
101
|
|
|
102
|
-
${S}`),500))}}),
|
|
103
|
-
${
|
|
104
|
-
${
|
|
102
|
+
${S}`),500))}}),m.stderr.on("data",p=>{if(!d){let h=p.toString();a+=h,s&&s(h)}}),m.on("close",p=>{if(d)return;It=null;let h=[],S=Lr(c),T=Lr(a);S&&h.push(`STDOUT:
|
|
103
|
+
${S}`),T&&h.push(`STDERR:
|
|
104
|
+
${T}`),p!==0&&h.push(`EXIT CODE: ${p}`);let w=h.join(`
|
|
105
105
|
|
|
106
|
-
`)||"Command executed with no output.",
|
|
106
|
+
`)||"Command executed with no output.",I=us(w).replace(/\n{3,}/g,`
|
|
107
107
|
|
|
108
108
|
`);e(p!==0?`ERROR: Command [${t}] failed with exit code [${p}].
|
|
109
109
|
|
|
110
|
-
${
|
|
110
|
+
${I}`:`SUCCESS: Command [${t}] completed.
|
|
111
111
|
|
|
112
|
-
${T}`)}),u.on("error",p=>{if(l&&r&&p.code==="ENOENT"){let h=ia(t,!1);return Fs(e,h,t,n,i,!1)}It=null,e(`ERROR: Failed to start command [${t}]: ${p.message}`)})}});import be,{useState as Sr}from"react";import{Box as Lt,Text as Xt,useInput as mc}from"ink";import fc from"ink-text-input";function Ns({systemSettings:e,setSystemSettings:o,apiTier:t,setActiveView:n,setInputConfig:i,saveSettings:r,quotas:l,setMessages:d,aiProvider:f}){let[u,c]=Sr("categories"),[a,m]=Sr(0),[p,h]=Sr(0),[S,T]=Sr(null),[y,M]=Sr(""),v=C=>{switch(C){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:Bs(e.alwaysAskCommands),section:"Sandbox"},{label:"Auto Approve Commands",value:"autoApprove",status:Bs(e.autoApproveCommands),section:"Sandbox"},{label:"Auto Disapprove Commands",value:"autoDisallow",status:Bs(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}];default:return[]}},R=en[a].id,K=v(R);mc((C,A)=>{if(S){A.escape&&T(null);return}if(u==="categories")A.upArrow?m(L=>(L-1+en.length)%en.length):A.downArrow?m(L=>(L+1)%en.length):A.return||A.rightArrow?en[a].id==="exit"?n("chat"):(c("items"),h(0)):A.escape&&n("chat");else if(u==="items"){if(A.upArrow)h(L=>(L-1+K.length)%K.length);else if(A.downArrow)h(L=>(L+1)%K.length);else if(A.leftArrow||A.escape)c("categories");else if(A.return){let L=K[p];F(L)}}});let F=C=>{if(C.value==="memory")o(A=>({...A,memory:!A.memory}));else if(C.value==="sandboxPreset"){let A=aa(e),L=["Autonomous","Balanced","Strict"],W=(L.indexOf(A)+1)%L.length,Z=L[W];o(_=>{let V={..._,sandboxPreset:Z};return Z==="Strict"?(V.autoExec=!1,V.allowExternalAccess=!1,V.networkAccess=!1,V.autoApproveCommands="",V.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",V.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",V.autoApproveGit=!1):Z==="Balanced"?(V.autoExec=!0,V.allowExternalAccess=!1,V.networkAccess=!0,V.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",V.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",V.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",V.autoApproveGit=!1):Z==="Autonomous"&&(V.autoExec=!0,V.allowExternalAccess=!0,V.networkAccess=!0,V.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",V.autoDisallowCommands="",V.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",V.autoApproveGit=!0),V})}else if(C.value==="autoExec")e.autoExec?o(A=>({...A,autoExec:!1,sandboxPreset:"Custom"})):e.allowExternalAccess?n("doubleDanger"):n("autoExecDanger");else if(C.value==="externalAccess")e.allowExternalAccess?o(A=>({...A,allowExternalAccess:!1,sandboxPreset:"Custom"})):e.autoExec?n("doubleDanger"):n("externalDanger");else if(C.value==="networkAccess")o(A=>({...A,networkAccess:A.networkAccess===!1,sandboxPreset:"Custom"}));else if(C.value==="alwaysAsk")T("alwaysAskCommands"),M(e.alwaysAskCommands||"");else if(C.value==="autoApprove")T("autoApproveCommands"),M(e.autoApproveCommands||"");else if(C.value==="autoApproveGit")o(A=>({...A,autoApproveGit:!A.autoApproveGit,sandboxPreset:"Custom"}));else if(C.value==="autoDisallow")T("autoDisallowCommands"),M(e.autoDisallowCommands||"");else if(C.value==="apiTier")n("apiTier");else if(C.value==="aiProvider")n("selectProvider");else if(C.value==="autoDelete"){let A=["1d","7d","30d"],J=(A.indexOf(e.autoDeleteHistory||"30d")+1)%A.length;o(W=>({...W,autoDeleteHistory:A[J]}))}else if(C.value==="autoUpdate")o(A=>({...A,autoUpdate:!A.autoUpdate}));else if(C.value==="externalData")if(!e.useExternalData)i({label:"Enter absolute path for External AppData:",note:"All history, logs and secrets will be stored here. ~/.fluxflow/settings.json stays as anchor.",key:"externalDataPath",value:e.externalDataPath||""}),n("input");else{let A={...e,useExternalData:!1};o(A),r({systemSettings:A,apiTier:t,quotas:l}),d(L=>[...L,{id:Date.now(),role:"system",text:"\u{1F3E0} [STORAGE RESET] Flux Flow will return to default ~/.fluxflow after restart."}]),n("chat")}else C.value==="updateManager"&&n("updateManager")};return be.createElement(Lt,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%",minHeight:32},be.createElement(Lt,{paddingX:1,paddingY:0,marginBottom:0,borderStyle:"single",borderColor:"magenta",width:"100%"},be.createElement(Xt,{color:"magenta",bold:!0},"\u{1F527} SYSTEM CONFIGURATION")),be.createElement(Lt,{flexDirection:"row",width:"100%",minHeight:26},be.createElement(Lt,{flexDirection:"column",width:"30%",borderStyle:"round",borderColor:u==="categories"?"cyan":"gray",padding:1,paddingY:0},be.createElement(Lt,{marginBottom:1},be.createElement(Xt,{color:u==="categories"?"cyan":"white",bold:!0,underline:!0},"CATEGORIES")),en.map((C,A)=>{let L=a===A,J=C.id==="exit";return be.createElement(Lt,{key:C.id,marginTop:J?17:0,backgroundColor:L?u==="categories"?"#2a2a2a":"#1e1e1e":void 0,paddingX:1},be.createElement(Xt,{color:L?u==="categories"?"cyan":"yellow":"white",bold:L},L?"\u276F ":" ",C.label))})),be.createElement(Lt,{flexDirection:"column",width:"70%",borderStyle:"round",borderColor:u==="items"?"cyan":"gray",paddingX:1,marginLeft:1,paddingY:0},be.createElement(Lt,{marginBottom:1},be.createElement(Xt,{color:u==="items"?"cyan":"white",bold:!0,underline:!0},en[a].label.toUpperCase()," SETTINGS")),K.length>0?(()=>{let C=null,A=[],L=fe=>(fe||"").split(",").map($e=>$e.trim().toLowerCase()).filter(Boolean),J=L(e.autoApproveCommands),W=L(e.autoDisallowCommands),Z=L(e.alwaysAskCommands),_=[...J,...W,...Z],V=new Set(_),gt=R==="security"&&_.length!==V.size;return K.forEach((fe,$e)=>{let ze=u==="items"&&p===$e,pe=fe.label.length,ot=Math.max(2,35-pe),Ge=".".repeat(ot),Ne=de=>R==="security"?(de.value==="autoExec"||de.value==="externalAccess")&&de.status==="ON"?"red":"yellow":de.status?.startsWith("\u2713")?"green":de.status?.startsWith("\u26A0")?"yellow":de.status==="ON"?"green":de.status==="OFF"?"red":"yellow";fe.section&&fe.section!==C&&(C=fe.section,A.push(be.createElement(Lt,{key:`sec-hdr-${fe.section}`,marginTop:A.length>0?1:0,marginBottom:0,paddingX:1},be.createElement(Xt,{color:"magenta",bold:!0,underline:!0},"\u{1F4C2} ",fe.section.toUpperCase()))));let Le=ze&&S&&(S==="alwaysAskCommands"&&fe.value==="alwaysAsk"||S==="autoApproveCommands"&&fe.value==="autoApprove"||S==="autoDisallowCommands"&&fe.value==="autoDisallow"),Xe=fe.value==="alwaysAsk"||fe.value==="autoApprove"||fe.value==="autoDisallow";A.push(be.createElement(Lt,{key:fe.value,flexDirection:"column"},be.createElement(Lt,{backgroundColor:ze&&!Le?"#2a2a2a":void 0,paddingX:2},be.createElement(Xt,{color:ze?"cyan":"white",bold:ze},ze?"\u276F ":" ",fe.label),!Xe&&be.createElement(be.Fragment,null,be.createElement(Xt,{color:"gray",dimColor:!0},Ge),be.createElement(Xt,{color:Ne(fe),bold:!0},fe.value==="aiProvider"?fe.status:`[ ${fe.status} ]`))),Xe&&!Le&&fe.status!=="None"&&be.createElement(Lt,{paddingX:4,marginBottom:1},be.createElement(Xt,{color:"gray",dimColor:!0},"\u21B3 ",fe.status)),Le&&be.createElement(Lt,{flexDirection:"column",marginLeft:4,marginBottom:1},be.createElement(Lt,{paddingX:1,borderStyle:"single",borderColor:"cyan",flexDirection:"row"},be.createElement(Xt,{color:"cyan",bold:!0},"> "," "),be.createElement(fc,{value:y,onChange:M,onSubmit:de=>{let so={...e,[S]:de.trim(),sandboxPreset:"Custom"};o(so),r({systemSettings:so,apiTier:t,quotas:l}),T(null)}})),be.createElement(Xt,{color:"gray",dimColor:!0,italic:!0}," Comma separated \u2022 Press Enter to save, Esc to cancel"))))}),R==="other"&&A.push(be.createElement(Lt,{key:"pty-notice",marginTop:19,paddingX:1},be.createElement(Xt,{color:Pn?"green":"yellow"},Pn?"\u2713 Advance Interactive Terminal Supported":"\u26A0 Interactive Terminal is Limited"))),gt&&A.push(be.createElement(Lt,{key:"conflict-warning",marginTop:1,paddingX:1},be.createElement(Xt,{color:"red",dimColor:!0,italic:!0},"* Conflicting commands will be ignored and defaulted to highest priority"))),A})():be.createElement(Lt,{paddingX:1},be.createElement(Xt,{color:"gray",italic:!0},en[a].desc)))),be.createElement(Lt,{paddingX:1,marginTop:0,flexDirection:"row",justifyContent:"space-between"},be.createElement(Xt,{color:"gray",dimColor:!0,italic:!0},u==="categories"?"\u25B2\u25BC Select Category \u2022 Enter/\u25BA to configure":"\u25B2\u25BC Select Option \u2022 Enter to Toggle \u2022 \u25C4/ESC to go back"),u==="categories"&&be.createElement(Xt,{color:"gray",dimColor:!0},en[a].desc)))}var en,aa,Bs,la=le(async()=>{await Tr();en=[{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||"",i=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 i?"Strict":r?"Balanced":l?"Autonomous":e.sandboxPreset||"Custom"},Bs=e=>!e||e.trim()===""?"None":e.length>40?e.substring(0,40)+"...":e});import $o,{useState as _s,useEffect as pc}from"react";import{Box as Jn,Text as os}from"ink";import hc from"ink-text-input";function Us({initialData:e,onSave:o,onCancel:t}){let[n,i]=_s(0),[r,l]=_s(""),[d,f]=_s(()=>({name:e?.name||"",nickname:e?.nickname||"",instructions:e?.instructions||""})),u=[{key:"name",label:"Enter your Name: "},{key:"nickname",label:"Enter a Nickname (Agent will use this): "},{key:"instructions",label:"System Instructions (Persona overrides): "}];pc(()=>{let a=u[n].key;l(d[a]||"")},[n,d]);let c=a=>{if(a.trim().toLowerCase()==="/cancel"){t();return}let m=u[n].key,p={...d,[m]:a.trim()};f(p),l(""),n<u.length-1?i(n+1):o(p)};return $o.createElement(Jn,{borderStyle:"round",borderColor:"gray",padding:0,marginTop:1,flexShrink:0,flexDirection:"column",width:"100%"},$o.createElement(Jn,{paddingX:1,marginBottom:1},$o.createElement(os,{color:"magenta",bold:!0},"\u{1F464} DEVELOPER PROFILE CONFIGURATION")),$o.createElement(Jn,{paddingX:1,flexDirection:"column"},$o.createElement(Jn,null,$o.createElement(os,{color:"cyan",bold:!0},u[n].label),$o.createElement(hc,{value:r,onChange:l,onSubmit:c})),$o.createElement(Jn,{marginTop:1},$o.createElement(os,{color:"gray",dimColor:!0,italic:!0},"Step ",n+1," of ",u.length))),$o.createElement(Jn,{paddingX:1,marginTop:1},$o.createElement(os,{color:"gray",dimColor:!0,italic:!0},"(Enter to submit \u2022 Type /cancel to abort)")))}var ca=le(()=>{});import pt,{useState as Rs}from"react";import{Box as Ao,Text as tn,useInput as gc}from"ink";import xc from"ink-text-input";var wc,da,ua=le(()=>{yn();wc=({question:e,options:o,onResolve:t})=>{let[n,i]=Rs(!1),[r,l]=Rs(""),[d,f]=Rs(0),u=[...o,{id:"CUSTOM",label:"Suggest something else...",description:"Provide a custom response"}];gc((a,m)=>{if(!n&&((m.leftArrow||m.upArrow)&&f(p=>Math.max(0,p-1)),(m.rightArrow||m.downArrow)&&f(p=>Math.min(u.length-1,p+1)),m.return)){let p=u[d];p.id==="CUSTOM"?i(!0):t(p.label)}});let c=Oe(2);return n?pt.createElement(Ao,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},pt.createElement(Ao,{paddingX:1},pt.createElement(tn,{color:"cyan",bold:!0},"\u{1F4AC} SUGGEST SOMETHING ELSE")),pt.createElement(Ao,{marginTop:1,paddingX:1},pt.createElement(tn,{italic:!0,color:"gray"},"Replying to: ",e)),pt.createElement(Ao,{marginTop:1,paddingX:1,flexDirection:"row"},pt.createElement(tn,{color:"cyan",bold:!0},"\u{1F4A0} "),pt.createElement(xc,{value:r,onChange:l,onSubmit:()=>t(r)})),pt.createElement(Ao,{marginTop:1,paddingX:1,marginBottom:1},pt.createElement(tn,{color:"gray",dimColor:!0,italic:!0},"(Press Enter to send)"))):pt.createElement(Ao,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},pt.createElement(Ao,{paddingX:1,marginBottom:1},pt.createElement(tn,{color:"cyan",bold:!0},"\u{1F4AC} AGENT REQUEST: ACTION REQUIRED")),pt.createElement(Ao,{paddingX:1,marginBottom:1},pt.createElement(tn,{bold:!0,color:"white"},e)),pt.createElement(Ao,{flexDirection:"column",width:"100%"},u.map((a,m)=>{let p=m===d;return pt.createElement(Ao,{key:a.id,flexDirection:"column",width:"100%",backgroundColor:p?"#2a2a2a":void 0,paddingX:1,marginBottom:m===u.length-1?0:1},pt.createElement(tn,{color:p?"cyan":"white",bold:p},p?"\u276F ":" ",a.label),a.description&&pt.createElement(Ao,{marginLeft:4},pt.createElement(tn,{color:"gray",italic:!0,dimColor:!0},a.description)))})),pt.createElement(Ao,{paddingX:1,marginTop:1,marginBottom:1},pt.createElement(tn,{color:"gray",dimColor:!0,italic:!0},"(Use Arrows to navigate, Enter to confirm)")))},da=wc});var ma,fa=le(()=>{ma=(e=!0,o=!0)=>`
|
|
112
|
+
${I}`)}),m.on("error",p=>{if(l&&r&&p.code==="ENOENT"){let h=Ca(t,!1);return Hs(e,h,t,n,s,!1)}It=null,e(`ERROR: Failed to start command [${t}]: ${p.message}`)})}});import Te,{useState as Fr}from"react";import{Box as Ot,Text as Kt,useInput as Hc}from"ink";import Xc from"ink-text-input";function qs({systemSettings:e,setSystemSettings:o,apiTier:t,setActiveView:n,setInputConfig:s,saveSettings:r,quotas:l,setMessages:u,aiProvider:f}){let[m,c]=Fr("categories"),[a,d]=Fr(0),[p,h]=Fr(0),[S,T]=Fr(null),[w,I]=Fr(""),L=b=>{switch(b){case"memory":return[{label:"Toggle Memory",value:"memory",status:e.memory?"ON":"OFF"}];case"security":return[{label:"Sandbox Preset",value:"sandboxPreset",status:ka(e),section:"Sandbox"},{label:"YOLO Mode",value:"autoExec",status:e.autoExec?"ON":"OFF",section:"Sandbox"},{label:"External Workspace Access",value:"externalAccess",status:e.allowExternalAccess?"ON":"OFF",section:"Sandbox"},{label:"Network Access (Terminal)",value:"networkAccess",status:e.networkAccess!==!1?"ON":"OFF",section:"Sandbox"},{label:"Always Ask Commands",value:"alwaysAsk",status:Ks(e.alwaysAskCommands),section:"Sandbox"},{label:"Auto Approve Commands",value:"autoApprove",status:Ks(e.autoApproveCommands),section:"Sandbox"},{label:"Auto Disapprove Commands",value:"autoDisallow",status:Ks(e.autoDisallowCommands),section:"Sandbox"},{label:"Auto Approve Git Commits",value:"autoApproveGit",status:e.autoApproveGit?"ON":"OFF",section:"Sandbox"},{label:"Auto-Delete History",value:"autoDelete",status:e.autoDeleteHistory||"30d",section:"Other"},{label:"Save AppData Externally",value:"externalData",status:e.useExternalData?"ON":"OFF",section:"Other"}];case"updater":return[{label:"Auto-Update",value:"autoUpdate",status:e.autoUpdate?"ON":"OFF"},{label:"Preferred Updater",value:"updateManager",status:(e.updateManager||"npm")==="custom"?"Custom":(e.updateManager||"npm").toUpperCase()}];case"other":return[{label:"Current Provider",value:"aiProvider",status:f},{label:"API Tier",value:"apiTier",status:t},{label:"Download Language Parsers",value:"parserDownload",status:"ACTION"}];default:return[]}},_=an[a].id,R=L(_);Hc((b,A)=>{if(S){A.escape&&T(null);return}if(m==="categories")A.upArrow?d(F=>(F-1+an.length)%an.length):A.downArrow?d(F=>(F+1)%an.length):A.return||A.rightArrow?an[a].id==="exit"?n("chat"):(c("items"),h(0)):A.escape&&n("chat");else if(m==="items"){if(A.upArrow)h(F=>(F-1+R.length)%R.length);else if(A.downArrow)h(F=>(F+1)%R.length);else if(A.leftArrow||A.escape)c("categories");else if(A.return){let F=R[p];v(F)}}});let v=b=>{if(b.value==="memory")o(A=>({...A,memory:!A.memory}));else if(b.value==="sandboxPreset"){let A=ka(e),F=["Autonomous","Balanced","Strict"],j=(F.indexOf(A)+1)%F.length,Z=F[j];o(B=>{let z={...B,sandboxPreset:Z};return Z==="Strict"?(z.autoExec=!1,z.allowExternalAccess=!1,z.networkAccess=!1,z.autoApproveCommands="",z.autoDisallowCommands="rm -rf, rm -f, del /f, del /q, rd /s, rmdir /s, format, mkfs, dd if=/dev, shred, srm, Remove-Item -Recurse -Force, Initialize-Disk, Clear-Disk, format c:, flashrom, nvram -c",z.alwaysAskCommands="killall, pkill, taskkill, shutdown, reboot, init 0, init 6, Stop-Process, Stop-Service, mv /*, move c:\\*, chmod 000, chmod -R 777, chown, icacls, netsh advfirewall, iptables -F, ufw disable, git reset --hard, git clean -fd, npm r, npm uninstall",z.autoApproveGit=!1):Z==="Balanced"?(z.autoExec=!0,z.allowExternalAccess=!1,z.networkAccess=!0,z.autoApproveCommands="ls, dir, cat, type, echo, pwd, cd, git status, git log, git diff, git branch, git show, help, mkdir, touch, md, whoami, hostname, ps, Get-Process, date, time",z.autoDisallowCommands="rm -rf, rm -f, del /f, del /q, rd /s, rmdir /s, format, mkfs, dd if=/dev, shred, srm, Remove-Item -Recurse -Force, Initialize-Disk, Clear-Disk, format c:, flashrom, nvram -c",z.alwaysAskCommands="killall, pkill, taskkill, Stop-Process, mv /*, move c:\\*, chmod 000, chmod -R 777, chown, icacls, shutdown, reboot, init 0, init 6, git reset --hard, git clean -fd, npm r, npm uninstall",z.autoApproveGit=!1):Z==="Autonomous"&&(z.autoExec=!0,z.allowExternalAccess=!0,z.networkAccess=!0,z.autoApproveCommands="ls, dir, cat, type, echo, pwd, cd, git status, git log, git diff, git branch, git show, help, mkdir, touch, md, whoami, hostname, ps, Get-Process, date, time",z.autoDisallowCommands="",z.alwaysAskCommands="rm -rf, rm -f, del /f, del /q, rd /s, rmdir /s, format, mkfs, dd if=/dev, shred, srm, Remove-Item -Recurse -Force, Initialize-Disk, Clear-Disk, format c:, flashrom, nvram -c",z.autoApproveGit=!0),z})}else if(b.value==="autoExec")e.autoExec?o(A=>({...A,autoExec:!1,sandboxPreset:"Custom"})):e.allowExternalAccess?n("doubleDanger"):n("autoExecDanger");else if(b.value==="externalAccess")e.allowExternalAccess?o(A=>({...A,allowExternalAccess:!1,sandboxPreset:"Custom"})):e.autoExec?n("doubleDanger"):n("externalDanger");else if(b.value==="networkAccess")o(A=>({...A,networkAccess:A.networkAccess===!1,sandboxPreset:"Custom"}));else if(b.value==="alwaysAsk")T("alwaysAskCommands"),I(e.alwaysAskCommands||"");else if(b.value==="autoApprove")T("autoApproveCommands"),I(e.autoApproveCommands||"");else if(b.value==="autoApproveGit")o(A=>({...A,autoApproveGit:!A.autoApproveGit,sandboxPreset:"Custom"}));else if(b.value==="autoDisallow")T("autoDisallowCommands"),I(e.autoDisallowCommands||"");else if(b.value==="apiTier")n("apiTier");else if(b.value==="aiProvider")n("selectProvider");else if(b.value==="autoDelete"){let A=["1d","7d","30d"],Q=(A.indexOf(e.autoDeleteHistory||"30d")+1)%A.length;o(j=>({...j,autoDeleteHistory:A[Q]}))}else if(b.value==="autoUpdate")o(A=>({...A,autoUpdate:!A.autoUpdate}));else if(b.value==="externalData")if(!e.useExternalData)s({label:"Enter absolute path for External AppData:",note:"All history, logs and secrets will be stored here. ~/.fluxflow/settings.json stays as anchor.",key:"externalDataPath",value:e.externalDataPath||""}),n("input");else{let A={...e,useExternalData:!1};o(A),r({systemSettings:A,apiTier:t,quotas:l}),u(F=>[...F,{id:Date.now(),role:"system",text:"\u{1F3E0} [STORAGE RESET] Flux Flow will return to default ~/.fluxflow after restart."}]),n("chat")}else b.value==="updateManager"?n("updateManager"):b.value==="parserDownload"&&n("parserDownload")};return Te.createElement(Ot,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%",minHeight:32},Te.createElement(Ot,{paddingX:1,paddingY:0,marginBottom:0,borderStyle:"single",borderColor:"magenta",width:"100%"},Te.createElement(Kt,{color:"magenta",bold:!0},"\u{1F527} SYSTEM CONFIGURATION")),Te.createElement(Ot,{flexDirection:"row",width:"100%",minHeight:26},Te.createElement(Ot,{flexDirection:"column",width:"30%",borderStyle:"round",borderColor:m==="categories"?"cyan":"gray",padding:1,paddingY:0},Te.createElement(Ot,{marginBottom:1},Te.createElement(Kt,{color:m==="categories"?"cyan":"white",bold:!0,underline:!0},"CATEGORIES")),an.map((b,A)=>{let F=a===A,Q=b.id==="exit";return Te.createElement(Ot,{key:b.id,marginTop:Q?17:0,backgroundColor:F?m==="categories"?"#2a2a2a":"#1e1e1e":void 0,paddingX:1},Te.createElement(Kt,{color:F?m==="categories"?"cyan":"yellow":"white",bold:F},F?"\u276F ":" ",b.label))})),Te.createElement(Ot,{flexDirection:"column",width:"70%",borderStyle:"round",borderColor:m==="items"?"cyan":"gray",paddingX:1,marginLeft:1,paddingY:0},Te.createElement(Ot,{marginBottom:1},Te.createElement(Kt,{color:m==="items"?"cyan":"white",bold:!0,underline:!0},an[a].label.toUpperCase()," SETTINGS")),R.length>0?(()=>{let b=null,A=[],F=ce=>(ce||"").split(",").map(Le=>Le.trim().toLowerCase()).filter(Boolean),Q=F(e.autoApproveCommands),j=F(e.autoDisallowCommands),Z=F(e.alwaysAskCommands),B=[...Q,...j,...Z],z=new Set(B),mt=_==="security"&&B.length!==z.size;return R.forEach((ce,Le)=>{let Je=m==="items"&&p===Le,ue=ce.label.length,tt=Math.max(2,35-ue),Ye=".".repeat(tt),_e=ft=>_==="security"?(ft.value==="autoExec"||ft.value==="externalAccess")&&ft.status==="ON"?"red":"yellow":ft.status?.startsWith("\u2713")?"green":ft.status?.startsWith("\u26A0")?"yellow":ft.status==="ON"?"green":ft.status==="OFF"?"red":"yellow";ce.section&&ce.section!==b&&(b=ce.section,A.push(Te.createElement(Ot,{key:`sec-hdr-${ce.section}`,marginTop:A.length>0?1:0,marginBottom:0,paddingX:1},Te.createElement(Kt,{color:"magenta",bold:!0,underline:!0},"\u{1F4C2} ",ce.section.toUpperCase()))));let Me=Je&&S&&(S==="alwaysAskCommands"&&ce.value==="alwaysAsk"||S==="autoApproveCommands"&&ce.value==="autoApprove"||S==="autoDisallowCommands"&&ce.value==="autoDisallow"),je=ce.value==="alwaysAsk"||ce.value==="autoApprove"||ce.value==="autoDisallow",ye=ce.value==="parserDownload";A.push(Te.createElement(Ot,{key:ce.value,flexDirection:"column"},Te.createElement(Ot,{backgroundColor:Je&&!Me?"#2a2a2a":void 0,paddingX:2},Te.createElement(Kt,{color:Je?"cyan":"white",bold:Je,underline:ye},Je?"\u276F ":" ",ce.label),!je&&!ye&&Te.createElement(Te.Fragment,null,Te.createElement(Kt,{color:"gray",dimColor:!0},Ye),Te.createElement(Kt,{color:_e(ce),bold:!0},ce.value==="aiProvider"?ce.status:`[ ${ce.status} ]`))),je&&!Me&&ce.status!=="None"&&Te.createElement(Ot,{paddingX:4,marginBottom:1},Te.createElement(Kt,{color:"gray",dimColor:!0},"\u21B3 ",ce.status)),Me&&Te.createElement(Ot,{flexDirection:"column",marginLeft:4,marginBottom:1},Te.createElement(Ot,{paddingX:1,borderStyle:"single",borderColor:"cyan",flexDirection:"row"},Te.createElement(Kt,{color:"cyan",bold:!0},"> "," "),Te.createElement(Xc,{value:w,onChange:I,onSubmit:ft=>{let pt={...e,[S]:ft.trim(),sandboxPreset:"Custom"};o(pt),r({systemSettings:pt,apiTier:t,quotas:l}),T(null)}})),Te.createElement(Kt,{color:"gray",dimColor:!0,italic:!0}," Comma separated \u2022 Press Enter to save, Esc to cancel"))))}),_==="other"&&A.push(Te.createElement(Ot,{key:"pty-notice",marginTop:18,paddingX:1},Te.createElement(Kt,{color:Yn?"green":"yellow"},Yn?"\u2713 Advance Interactive Terminal Supported":"\u26A0 Interactive Terminal is Limited"))),mt&&A.push(Te.createElement(Ot,{key:"conflict-warning",marginTop:1,paddingX:1},Te.createElement(Kt,{color:"red",dimColor:!0,italic:!0},"* Conflicting commands will be ignored and defaulted to highest priority"))),A})():Te.createElement(Ot,{paddingX:1},Te.createElement(Kt,{color:"gray",italic:!0},an[a].desc)))),Te.createElement(Ot,{paddingX:1,marginTop:0,flexDirection:"row",justifyContent:"space-between"},Te.createElement(Kt,{color:"gray",dimColor:!0,italic:!0},m==="categories"?"\u25B2\u25BC Select Category \u2022 Enter/\u25BA to configure":"\u25B2\u25BC Select Option \u2022 Enter to Toggle \u2022 \u25C4/ESC to go back"),m==="categories"&&Te.createElement(Kt,{color:"gray",dimColor:!0},an[a].desc)))}var an,ka,Ks,Ia=re(async()=>{await Dr();an=[{id:"memory",label:"\u{1F9E0} Memory",desc:"Manage system context & agent's memory"},{id:"security",label:"\u{1F512} Security",desc:"Configure permissions & data safety"},{id:"updater",label:"\u{1F504} Updater",desc:"Manage application updates"},{id:"other",label:"\u{1F4CB} Other",desc:"Miscellaneous preferences"},{id:"exit",label:"\u{1F6AA} Exit Settings",desc:"Return to chat view"}],ka=e=>{let o=e.autoApproveCommands||"",t=e.autoDisallowCommands||"",n=e.alwaysAskCommands||"",s=e.autoExec===!1&&e.allowExternalAccess===!1&&e.networkAccess===!1&&o===""&&t==="rm -rf, rm -f, del /f, del /q, rd /s, rmdir /s, format, mkfs, dd if=/dev, shred, srm, Remove-Item -Recurse -Force, Initialize-Disk, Clear-Disk, format c:, flashrom, nvram -c"&&n==="killall, pkill, taskkill, shutdown, reboot, init 0, init 6, Stop-Process, Stop-Service, mv /*, move c:\\*, chmod 000, chmod -R 777, chown, icacls, netsh advfirewall, iptables -F, ufw disable, git reset --hard, git clean -fd, npm r, npm uninstall"&&e.autoApproveGit===!1,r=e.autoExec===!0&&e.allowExternalAccess===!1&&e.networkAccess!==!1&&o==="ls, dir, cat, type, echo, pwd, cd, git status, git log, git diff, git branch, git show, help, mkdir, touch, md, whoami, hostname, ps, Get-Process, date, time, mkdir"&&t==="rm -rf, rm -f, del /f, del /q, rd /s, rmdir /s, format, mkfs, dd if=/dev, shred, srm, Remove-Item -Recurse -Force, Initialize-Disk, Clear-Disk, format c:, flashrom, nvram -c"&&n==="killall, pkill, taskkill, Stop-Process, mv /*, move c:\\*, chmod 000, chmod -R 777, chown, icacls, shutdown, reboot, init 0, init 6, git reset --hard, git clean -fd, npm r, npm uninstall"&&e.autoApproveGit===!1,l=e.autoExec===!0&&e.allowExternalAccess===!0&&e.networkAccess!==!1&&o==="ls, dir, cat, type, echo, pwd, cd, git status, git log, git diff, git branch, git show, help, mkdir, touch, md, whoami, hostname, ps, Get-Process, date, time, mkdir"&&t===""&&n==="rm -rf, rm -f, del /f, del /q, rd /s, rmdir /s, format, mkfs, dd if=/dev, shred, srm, Remove-Item -Recurse -Force, Initialize-Disk, Clear-Disk, format c:, flashrom, nvram -c"&&e.autoApproveGit===!0;return s?"Strict":r?"Balanced":l?"Autonomous":e.sandboxPreset||"Custom"},Ks=e=>!e||e.trim()===""?"None":e.length>40?e.substring(0,40)+"...":e});import Po,{useState as Vs,useEffect as Kc}from"react";import{Box as sr,Text as ds}from"ink";import qc from"ink-text-input";function zs({initialData:e,onSave:o,onCancel:t}){let[n,s]=Vs(0),[r,l]=Vs(""),[u,f]=Vs(()=>({name:e?.name||"",nickname:e?.nickname||"",instructions:e?.instructions||""})),m=[{key:"name",label:"Enter your Name: "},{key:"nickname",label:"Enter a Nickname (Agent will use this): "},{key:"instructions",label:"System Instructions (Persona overrides): "}];Kc(()=>{let a=m[n].key;l(u[a]||"")},[n,u]);let c=a=>{if(a.trim().toLowerCase()==="/cancel"){t();return}let d=m[n].key,p={...u,[d]:a.trim()};f(p),l(""),n<m.length-1?s(n+1):o(p)};return Po.createElement(sr,{borderStyle:"round",borderColor:"gray",padding:0,marginTop:1,flexShrink:0,flexDirection:"column",width:"100%"},Po.createElement(sr,{paddingX:1,marginBottom:1},Po.createElement(ds,{color:"magenta",bold:!0},"\u{1F464} DEVELOPER PROFILE CONFIGURATION")),Po.createElement(sr,{paddingX:1,flexDirection:"column"},Po.createElement(sr,null,Po.createElement(ds,{color:"cyan",bold:!0},m[n].label),Po.createElement(qc,{value:r,onChange:l,onSubmit:c})),Po.createElement(sr,{marginTop:1},Po.createElement(ds,{color:"gray",dimColor:!0,italic:!0},"Step ",n+1," of ",m.length))),Po.createElement(sr,{paddingX:1,marginTop:1},Po.createElement(ds,{color:"gray",dimColor:!0,italic:!0},"(Enter to submit \u2022 Type /cancel to abort)")))}var Ma=re(()=>{});import ut,{useState as Js}from"react";import{Box as vo,Text as ln,useInput as Vc}from"ink";import zc from"ink-text-input";var Jc,va,Aa=re(()=>{rn();Jc=({question:e,options:o,onResolve:t})=>{let[n,s]=Js(!1),[r,l]=Js(""),[u,f]=Js(0),m=[...o,{id:"CUSTOM",label:"Suggest something else...",description:"Provide a custom response"}];Vc((a,d)=>{if(!n&&((d.leftArrow||d.upArrow)&&f(p=>Math.max(0,p-1)),(d.rightArrow||d.downArrow)&&f(p=>Math.min(m.length-1,p+1)),d.return)){let p=m[u];p.id==="CUSTOM"?s(!0):t(p.label)}});let c=Ie(2);return n?ut.createElement(vo,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},ut.createElement(vo,{paddingX:1},ut.createElement(ln,{color:"cyan",bold:!0},"\u{1F4AC} SUGGEST SOMETHING ELSE")),ut.createElement(vo,{marginTop:1,paddingX:1},ut.createElement(ln,{italic:!0,color:"gray"},"Replying to: ",e)),ut.createElement(vo,{marginTop:1,paddingX:1,flexDirection:"row"},ut.createElement(ln,{color:"cyan",bold:!0},"\u{1F4A0} "),ut.createElement(zc,{value:r,onChange:l,onSubmit:()=>t(r)})),ut.createElement(vo,{marginTop:1,paddingX:1,marginBottom:1},ut.createElement(ln,{color:"gray",dimColor:!0,italic:!0},"(Press Enter to send)"))):ut.createElement(vo,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},ut.createElement(vo,{paddingX:1,marginBottom:1},ut.createElement(ln,{color:"cyan",bold:!0},"\u{1F4AC} AGENT REQUEST: ACTION REQUIRED")),ut.createElement(vo,{paddingX:1,marginBottom:1},ut.createElement(ln,{bold:!0,color:"white"},e)),ut.createElement(vo,{flexDirection:"column",width:"100%"},m.map((a,d)=>{let p=d===u;return ut.createElement(vo,{key:a.id,flexDirection:"column",width:"100%",backgroundColor:p?"#2a2a2a":void 0,paddingX:1,marginBottom:d===m.length-1?0:1},ut.createElement(ln,{color:p?"cyan":"white",bold:p},p?"\u276F ":" ",a.label),a.description&&ut.createElement(vo,{marginLeft:4},ut.createElement(ln,{color:"gray",italic:!0,dimColor:!0},a.description)))})),ut.createElement(vo,{paddingX:1,marginTop:1,marginBottom:1},ut.createElement(ln,{color:"gray",dimColor:!0,italic:!0},"(Use Arrows to navigate, Enter to confirm)")))},va=Jc});var Oa,Da=re(()=>{Oa=(e=!0,o=!0)=>`
|
|
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,La=re(()=>{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
|
|
191
|
+
- Verify ALL imports and system stability, AVOID ANY Syntax errors, re-read TOOL RESULTS/files to verify`}});import Zc from"fs";var Zs,Fa,$a,Pa,_a=re(async()=>{await js();Da();La();Zs=null,Fa=(e="",o="",t=!0,n=!1)=>{if(!t)return"";let s=e?.length>0&&!n?`-- RECENT CONTEXT FROM OTHER CHATS (PRIORITY: DYNAMIC-LOW, FOCUS: Chat Context > Recent) --
|
|
192
192
|
${e}`:"",l=[o?.length>0?`--- SAVED MEMORIES (PRIORITY: MEDIUM, USER PREFERENCES) ---
|
|
193
|
-
${o}`:"",
|
|
193
|
+
${o}`:"",s].filter(u=>u.length>0);return l.length>0?`[SYSTEM CONTEXT]
|
|
194
194
|
${l.join(`
|
|
195
195
|
|
|
196
196
|
`)}
|
|
197
|
-
`:""}
|
|
197
|
+
`:""},$a=(e,o,t,n,s=!0,r=!1,l="Google",u=!1)=>{let f="";if(o!=="GEM"){let w=o;o==="Fast"&&(w="Off"),o==="Low"&&(w="Minimal"),o==="Standard"&&(w="Medium"),(o==="xHigh"||o==="Max")&&(w="xHigh"),f=Qs[w]||Qs.Medium}let m=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",c=e.instructions&&e.instructions?.length>0?`User Instructions: ${e.instructions}
|
|
198
198
|
|
|
199
199
|
`:"",a=e.nickname&&e.nickname?.length>0?`User Nickname: ${e.nickname}
|
|
200
200
|
${c.length?"":`
|
|
201
|
-
`}`:"",
|
|
201
|
+
`}`:"",d=e.name&&e.name?.length>0?`User Name: ${e.name}
|
|
202
202
|
${a.length||c.length?"":`
|
|
203
|
-
`}`:"",p=process.cwd(),h=(()=>{let
|
|
203
|
+
`}`:"",p=process.cwd(),h=(()=>{let w=process.cwd().toLowerCase();if(process.platform==="win32"){let I=process.env.SystemRoot?.toLowerCase()||"c:\\windows",L=process.env.ProgramFiles?.toLowerCase()||"c:\\program files",_=process.env["ProgramFiles(x86)"]?.toLowerCase()||"c:\\program files (x86)";return w.startsWith(I)||w.startsWith(L)||w.startsWith(_)}else return w==="/"||["/bin","/sbin","/etc","/usr","/var","/root"].some(L=>w.startsWith(L))})(),S=[{name:"Fluxflow.md",desc:"HIGH PRIORITY. Overrides other files"},{name:"README.md",desc:"Goals"},{name:"Agent.md",desc:"Standards"},{name:"Skills.md",desc:"Workflows"},{name:"design.md",desc:"UI/UX"},{name:"architecture.md",desc:"System Structure"}];if(r||Zs===null){let w=S.filter(I=>Zc.existsSync(I.name));Zs=t==="Flux"&&w.length>0?`
|
|
204
204
|
-- PROJECT CONTEXT (Source of Truth) --
|
|
205
|
-
${
|
|
205
|
+
${w.map(I=>`- ${I.name}: ${I.desc}`).join(`
|
|
206
206
|
`)}
|
|
207
207
|
Check these first; These Files > Training Data. Safety rules apply
|
|
208
|
-
`:""}let T=
|
|
208
|
+
`:""}let T=Zs;return`${d}${a}${c}[SYSTEM]
|
|
209
209
|
Identity: Flux Flow (by Kushal Roy Chowdhury). Conversational, Sassy${t==="Flux"?", Respectful":", Friendly, Humorous, Sarcastic"}, CLI Agent
|
|
210
210
|
Mode: ${t}${o!=="Fast"?" (Thinking Mode)":""}. ${t==="Flux"?"Logical, Highly Detailed, Task-Driven. Prioritizes scalable file/folder structures, modular architecture, clean code abstractions, step-by-step execution. Industry standard latest coding practices/libraries, clean code, Double Check Imports, Client-Server Sync":"Concise"}
|
|
211
211
|
|
|
@@ -224,10 +224,10 @@ 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
|
+
${Ea(t,m,l.toLowerCase()==="deepseek"?!1:u,l)}
|
|
228
228
|
${T}
|
|
229
229
|
-- MEMORY RULES --
|
|
230
|
-
- Memory: ${
|
|
230
|
+
- Memory: ${s?"Subtly Personalize. Auto Saves":"OFF. Decline Remembering Memories"}
|
|
231
231
|
- Temporal Awareness: RELATIVE TIME REFERENCE eg. few mins ago
|
|
232
232
|
|
|
233
233
|
-- SECURITY RULES --${n.allowExternalAccess?"":`
|
|
@@ -240,7 +240,7 @@ PROTECTED DIRECTORY: ASK BEFORE MODIFYING`:""}
|
|
|
240
240
|
- GFM Supported
|
|
241
241
|
- NO EMOJI AT END OF RESPONSE
|
|
242
242
|
- NO LaTeX${t==="Flux"?"":". Kaomojis"}
|
|
243
|
-
[/SYSTEM]`.trim()},
|
|
243
|
+
[/SYSTEM]`.trim()},Pa=(e="",o=!0,t=!0)=>`${e?`-- CURRENT SAVED USER MEMORIES --
|
|
244
244
|
${e}
|
|
245
245
|
-------------------------------------------------
|
|
246
246
|
|
|
@@ -259,76 +259,76 @@ YOU ARE A SILENT BACKGROUND SYSTEM PROCESS. YOU HAVE NO MOUTH. YOUR ONLY OUTPUT
|
|
|
259
259
|
YOUR JOB: Analyze the 'User prompt' and 'Agent Raws' to extract facts for long-term memory or handle system tasks.
|
|
260
260
|
${o?"If user tell something that is important (like, hobbies, preferences, facts about user, hates, likes, etc) to know user better over time, use long term memory tools.":""}
|
|
261
261
|
|
|
262
|
-
${
|
|
262
|
+
${Oa(o,t)}
|
|
263
263
|
|
|
264
264
|
Current date and Time: ${new Date().toLocaleString([],{year:"numeric",month:"numeric",day:"numeric",hour:"2-digit",hour12:!0})}.
|
|
265
|
-
=== END SYSTEM PROMPT ===`.trim()});import
|
|
266
|
-
`),n=[],
|
|
265
|
+
=== END SYSTEM PROMPT ===`.trim()});import bo from"fs-extra";import jn from"path";var cn,kt,un=re(()=>{Bt();Lo();bo.ensureDirSync(wn);cn=null,kt={async startTransaction(e,o){cn={id:`tx_prompt_${Date.now()}`,chatId:e,timestamp:new Date().toISOString(),prompt:o.trim(),changes:[],reverted:!1}},async recordFileChange(e,o=null){if(!cn||cn.changes.some(l=>l.filePath===e))return;let n=await bo.pathExists(e),s=n&&!o||o?"update":"create";!n&&!o&&(s="create");let r=null;if(n||o){s="update";let l=jn.basename(e);r=`${cn.id}_${l}.bak`;let u=jn.join(wn,cn.chatId);await bo.ensureDir(u);let f=jn.join(u,r),m=o!==null?o:await bo.readFile(e,"utf8"),c=Cr(m);await bo.writeFile(f,c,"utf8")}cn.changes.push({filePath:e,type:s,backupFile:r})},async commitTransaction(){if(!cn)return;let e=xe(nn,[]);if(e.push(cn),e.length>512e3){let o=e.shift();if(o.changes){for(let t of o.changes)if(t.backupFile){let n=jn.join(wn,o.chatId,t.backupFile);await bo.remove(n)}}}ke(nn,e),cn=null},async rollbackToBefore(e){let o=xe(nn,null);if(!o)throw new Error("No transaction ledger found.");let t=o.findIndex(u=>u.id===e);if(t===-1)throw new Error(`Transaction [${e}] not found.`);let n=o[t].chatId,s=o[t].prompt,r=o.slice(t).filter(u=>u.chatId===n&&!u.reverted).reverse();for(let u of r){for(let f of[...u.changes].reverse())if(f.type==="create")await bo.pathExists(f.filePath)&&await bo.remove(f.filePath);else if(f.type==="update"){let m=jn.join(wn,u.chatId,f.backupFile);if(await bo.pathExists(m)){let c=await bo.readFile(m,"utf8"),a=Sn(c);await bo.writeFile(f.filePath,a,"utf8")}}u.reverted=!0}for(let u of r)for(let f of u.changes)if(f.backupFile){let m=jn.join(wn,u.chatId,f.backupFile);await bo.remove(m)}let l=o.filter(u=>!r.some(f=>f.id===u.id));return ke(nn,l),{success:!0,chatId:n,targetPrompt:s}},async getChatHistory(e){try{return xe(nn,[]).filter(t=>t.chatId===e&&!t.reverted)}catch{return[]}},async deleteChatBackups(e){try{let o=jn.join(wn,e);await bo.remove(o);let t=xe(nn,[]),n=t.length;t=t.filter(s=>s.chatId!==e),t.length!==n&&ke(nn,t)}catch{}}}});import Xo from"fs-extra";import eu from"path";import{nanoid as tu}from"nanoid";var Na,ei,_o,ms,Ba,ti,oi,Ua,ou,nu,Ra,Wa,$r=re(()=>{Lo();Bt();un();Na=Promise.resolve(),ei=e=>{let o=Na.then(async()=>{try{return await e()}catch(t){throw console.error("Lock Operation Failed:",t),t}});return Na=o.catch(()=>{}),o},_o=async()=>{if(await Xo.pathExists(Rn))try{return xe(Rn,{})}catch{return{}}return{}},ms=async(e,o,t)=>ei(async()=>{let n=await _o(),s=n[e],r=(t||[]).filter(u=>!u.isUpdateNotification&&!u.isMeta),l=o||(s?s.name:`Session ${e.slice(-6)}`);n[e]={name:l,messages:r,updatedAt:Date.now()},ke(Rn,n)}),Ba=async(e,o)=>ei(async()=>{let t=await _o();t[e]?(t[e].name=o,t[e].updatedAt=Date.now()):t[e]={name:o,messages:[],updatedAt:Date.now()},ke(Rn,t)}),ti=async e=>ei(async()=>{let o=await _o();delete o[e],ke(Rn,o);let t=xe(Eo,{});t[e]&&(delete t[e],ke(Eo,t));let n=xe(Go,{});return n[e]&&(delete n[e],ke(Go,n)),await kt.deleteChatBackups(e),o}),oi=()=>`flow-${tu(6)}`,Ua=async e=>{if(!e||e==="Never")return;let o=parseInt(e);if(isNaN(o))return;let t=await _o(),n=Date.now(),s=o*24*60*60*1e3,r=0;for(let l in t){let u=t[l];u.updatedAt&&n-u.updatedAt>s&&(await ti(l),r++)}return r},ou=e=>{let o=e.replace(/[\[\]]/g,"").trim(),t=new Date(o);if(!isNaN(t.getTime()))return t.getTime();let n=o.split(/,\s*|\s+/);if(n.length===0)return null;let s=n[0],r=n[1]||"",l=n[2]||"",u=s.split(/[-/.]/).map(Number);if(u.length!==3)return null;let f,m,c;if(u[0]>1e3)f=u[0],m=u[1],c=u[2];else if(u[2]>1e3)f=u[2],u[0]>12?(c=u[0],m=u[1]):u[1]>12?(c=u[1],m=u[0]):(m=u[0],c=u[1]);else return null;let a=0,d=0,p=0;if(r){let S=r.split(":").map(Number);a=S[0]||0,d=S[1]||0,p=S[2]||0,l.toLowerCase()==="pm"&&a<12?a+=12:l.toLowerCase()==="am"&&a===12&&(a=0)}let h=new Date(f,m-1,c,a,d,p);return isNaN(h.getTime())?null:h.getTime()},nu=async e=>{try{if(!await Xo.pathExists(e))return;let o=await Xo.readFile(e,"utf8");if(!o.trim())return;let t=o.split(`
|
|
266
|
+
`),n=[],s=null,r=/^\s*(?:DEBUG|ERROR|SEARCH|PUPPETEER)\b/i;for(let a of t)r.test(a)?(s&&n.push(s),s={header:a,body:[]}):s?s.body.push(a):n.push({header:a,body:[]});s&&n.push(s);let l=10080*60*1e3,u=Date.now(),f=[],m=/(\d{1,4}[-/.]\d{1,4}[-/.]\d{1,4}(?:,\s*|\s+)?(?:\d{1,2}:\d{2}:\d{2}(?:\s*[aApP][mM])?)?)/;for(let a of n){let d=a.header+(a.body.length>0?`
|
|
267
267
|
`+a.body.join(`
|
|
268
|
-
`):""),p=
|
|
269
|
-
`).trim();c?await
|
|
270
|
-
`,"utf8"):await
|
|
271
|
-
Source: ${
|
|
272
|
-
Snippet: ${
|
|
268
|
+
`):""),p=d.match(m);if(p){let h=ou(p[1]);if(h&&u-h>l)continue}f.push(d)}let c=f.join(`
|
|
269
|
+
`).trim();c?await Xo.writeFile(e,c+`
|
|
270
|
+
`,"utf8"):await Xo.writeFile(e,"","utf8")}catch{}},Ra=async e=>{try{if(!await Xo.pathExists(e))return;let o=async t=>{let n=await Xo.readdir(t);for(let s of n){let r=eu.join(t,s);(await Xo.stat(r)).isDirectory()?(await o(r),(await Xo.readdir(r)).length===0&&await Xo.remove(r)):s.endsWith(".log")&&await nu(r)}};await o(e)}catch{}},Wa=(e,o=4)=>{if(e.length<=1)return e;let t=e[0],n=e.slice(1),s=o*2,r=n.slice(s);return[t,...r]}});import ze from"fs-extra";import Ko from"path";import ni from"os";var ru,dn,su,Tt,vn,Ya,fs,ri,ja,si,ii,Ga,Ha,An,qo,Co,ai,li,Xa,Ka,ps,qa,hs=re(()=>{Bt();Lo();ru=()=>{if(process.platform==="win32"){let o=process.env.LOCALAPPDATA||Ko.join(ni.homedir(),"AppData","Local");return Ko.join(o,"FxFl","backups","backup.json")}if(process.platform==="darwin")return Ko.join(ni.homedir(),"Library","Application Support","FxFl","backups","backup.json");let e=process.env.XDG_DATA_HOME||Ko.join(ni.homedir(),".local","share");return Ko.join(e,"fxfl","backups","backup.json")},dn=ru(),su=()=>Math.random().toString(36).substring(2)+Date.now().toString(36),Tt=null,vn=null,Ya=0,fs=!1,ri={agent:0,background:0,search:0,toolSuccess:0,toolFailure:0,toolDenied:0,duration:0,tokens:0,cachedTokens:0,candidateTokens:0,linesAdded:0,linesRemoved:0,imageCalls:[]},ja=async()=>{let e=new Date().toISOString().split("T")[0],o=Ht+".tmp",t=null,n=null;try{if(await ze.exists(o)){let r=(await ze.readFile(o,"utf8")).trim(),l=null;if(r.startsWith("{")||r.startsWith("[")?l=JSON.parse(r):l=JSON.parse(Sn(r)),l&&l.date&&l.stats){t=l;try{await ze.rename(o,Ht)}catch{}}else try{await ze.remove(o)}catch{}}}catch{try{await ze.remove(o)}catch{}}if(!t)try{if(await ze.exists(Ht)){let r=(await ze.readFile(Ht,"utf8")).trim();r.startsWith("{")||r.startsWith("[")?t=JSON.parse(r):t=JSON.parse(Sn(r))}}catch{}try{if(await ze.exists(dn)){let r=(await ze.readFile(dn,"utf8")).trim();r.startsWith("{")||r.startsWith("[")?n=JSON.parse(r):n=JSON.parse(Sn(r))}}catch{}let s=null;if(t&&n)if(t.saveId!==n.saveId){s=t;try{await ze.ensureDir(Ko.dirname(dn)),await ze.copy(Ht,dn)}catch{}}else s=t;else if(t&&!n){s=t;try{await ze.ensureDir(Ko.dirname(dn)),await ze.copy(Ht,dn)}catch{}}else if(!t&&n){s=n;try{await ze.ensureDir(Ko.dirname(Ht)),await ze.copy(dn,Ht)}catch{}}if(s&&s.date===e&&s.stats){let r={...ri,...s.stats};return Array.isArray(r.imageCalls)||(r.imageCalls=[]),{...s,stats:r}}return{date:e,stats:{...ri}}},si=async()=>{if(!(!fs||!Tt))try{await ze.ensureDir(Ko.dirname(Ht));let e=null;try{if(await ze.exists(Ht)){let s=(await ze.readFile(Ht,"utf8")).trim();s.startsWith("{")||s.startsWith("[")?e=JSON.parse(s):e=JSON.parse(Sn(s))}}catch{}if(e&&e.date===Tt.date&&e.stats){for(let s in Tt.stats)if(e.stats[s]!==void 0)if(Array.isArray(Tt.stats[s])){let r=Array.isArray(e.stats[s])?e.stats[s]:[],l=Tt.stats[s],u=new Map;for(let f of[...r,...l])f&&f.timestamp&&u.set(f.timestamp,f);Tt.stats[s]=Array.from(u.values())}else typeof Tt.stats[s]=="number"&&(Tt.stats[s]=Math.max(Tt.stats[s],Number(e.stats[s])||0))}Tt.saveId=su();let o=Ht+".tmp",t=Cr(JSON.stringify(Tt,null,2));await ze.writeFile(o,t,"utf8");let n=await ze.open(o,"r+");await ze.fsync(n),await ze.close(n),await ze.rename(o,Ht);try{await ze.ensureDir(Ko.dirname(dn)),await ze.copy(Ht,dn)}catch{}fs=!1,Ya=Date.now()}catch{}},ii=()=>{if(fs=!0,vn)return;let e=Date.now(),o=Math.max(0,1500-(e-Ya));vn=setTimeout(async()=>{await si(),vn=null},o),vn.unref&&vn.unref()},Ga=async()=>{Tt=await ja()},Ha=async()=>{vn&&(clearTimeout(vn),vn=null),await si()},An=async()=>{let e=new Date().toISOString().split("T")[0];return Tt?Tt.date!==e&&(Tt={date:e,stats:{...ri}},fs=!0,await si()):Tt=await ja(),Tt&&Tt.stats&&!Array.isArray(Tt.stats.imageCalls)&&(Tt.stats.imageCalls=[]),Tt.stats},qo=async e=>{let o=await An();o[e]!==void 0&&(o[e]++,ii())},Co=async(e,o)=>{let t=await An();t[e]!==void 0&&(t[e]+=Math.floor(o),ii())},ai=async(e,o)=>{let t=await An(),n=o.apiTier||"Free",s=o.quotas||{};if(n==="Free"){if(e==="agent"||e==="background")return t.agent+t.background<999999;if(e==="search")return!0}if(n==="Paid"||n==="Custom"){if(e==="agent")return t.agent<(s.agentLimit||999999);if(e==="background")return t.background<(s.backgroundLimit||999999);if(e==="search")return t.search<(s.searchLimit||100)}return!0},li=e=>{if(!e||e.length===0)return[];let t=[...e].sort((s,r)=>s.timestamp-r.timestamp),n=[];for(let s of t){if(n.length>0){let r=n[n.length-1];if(s.timestamp>=r.start&&s.timestamp<r.end){r.calls.push(s),r.spent+=s.cost;continue}}n.push({start:s.timestamp,end:s.timestamp+36e5,calls:[s],spent:s.cost})}return n},Xa=(e,o)=>{if(!e||e.length===0)return .025;let n=li(e);if(n.length===0)return .025;let s=[];for(let a of n){let d=.025;if(s.length>0){let h=s[s.length-1],S=!1;if(s.length>=2){let T=s[s.length-2];h.ratio>=.8&&T.ratio>=.8&&(S=!0)}if(S)d=.015;else{let T=h.limit,w=h.ratio;w>=.8?d=T===.015?.015:T:w<.4?d=Math.min(.025,T+.005):w>=.4&&w<.6?d=Math.min(.025,T+.004):d=Math.min(.025,T+.002)}}let p=d>0?a.spent/d:0;s.push({limit:d,spent:a.spent,ratio:p})}let r=n[n.length-1];if(o<r.end)return s[s.length-1].limit;let l=s[s.length-1].limit,u=l,f=s[s.length-1].ratio,m=r.end,c=0;for(let a=s.length-1;a>=0&&s[a].ratio>=.8;a--)c++;for(;m<=o;){let a=.025;c>=2?a=.015:f>=.8?a=u===.015?.015:u:f<.4?a=Math.min(.025,u+.005):f>=.4&&f<.6?a=Math.min(.025,u+.004):a=Math.min(.025,u+.002),u=a,f=0,c=0,m+=36e5,l=a}return l},Ka=async e=>{let o=e.imageSettings||{keyType:"Default",quality:"Low-High"};if(o.keyType!=="Default")return!0;let n={Low:.001,"Low-High":.002,Medium:.008,"Medium-High":.01,High:.045,Ultra:.0488,Premium:.15}[o.quality]||.002,s=await An();s.imageCalls||(s.imageCalls=[]);let r=Date.now(),l=li(s.imageCalls),u=0;if(l.length>0){let m=l[l.length-1];r>=m.start&&r<m.end&&(u=m.spent)}let f=Xa(s.imageCalls,r);return u+n<=f},ps=async()=>{let e=await An();e.imageCalls||(e.imageCalls=[]);let o=Date.now(),t=li(e.imageCalls),n=[],s=0,r=0;if(t.length>0){let m=t[t.length-1];o>=m.start&&o<m.end&&(n=m.calls,s=m.spent,r=Math.max(0,Math.ceil((m.end-o)/(60*1e3))))}let l=Xa(e.imageCalls,o),u=Math.max(0,l-s),f=s;return{totalSpent:s,remaining:u,activeCallsCount:n.length,nextResetMin:r,reclaimCost:f,limit:l}},qa=async e=>{let o=e.imageSettings||{keyType:"Default",quality:"Low-High"},n={Low:.001,"Low-High":.002,Medium:.008,"Medium-High":.01,High:.045,Ultra:.0488,Premium:.1}[o.quality]||.002,s=await An();s.imageCalls||(s.imageCalls=[]),s.imageCalls.push({timestamp:Date.now(),cost:n}),ii()}});import iu from"puppeteer";var ci,Va=re(()=>{Xt();Bt();ci=async e=>{let{query:o,limit:t=10}=ne(e);if(!o)return'ERROR: Missing "query" argument for web_search.';let n=3,s=null;for(let r=1;r<=n;r++){let l=null;try{l=await iu.launch({headless:!0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let u=await l.newPage();await u.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.97 Safari/537.36"),await u.setViewport({width:1366,height:768});let f=r===1?Math.random()*1e3+500:Math.random()*2e3+1e3;await new Promise(d=>setTimeout(d,f));let m=`https://html.duckduckgo.com/html/?q=${encodeURIComponent(o)}`;await u.goto(m,{waitUntil:"networkidle2",timeout:18e4});let c=await u.$$eval(".result",(d,p)=>d.slice(0,p).map((h,S)=>{let T=h.querySelector(".result__a"),w=h.querySelector(".result__snippet"),I=T?T.href:"";I.includes("uddg=")&&(I=decodeURIComponent(I.split("uddg=")[1].split("&")[0]));let L=T?T.innerText.trim():"No Title",_=w?w.innerText.trim():"No Snippet";return`${S+1}. ${L}
|
|
271
|
+
Source: ${I}
|
|
272
|
+
Snippet: ${_}`}),t);if(c.length===0){if((await u.evaluate(()=>document.body.innerText)).includes("anomaly"))throw new Error("ANOMALY_DETECTED");return await l.close(),`No results found for query: [${o}].`}let a=c.join(`
|
|
273
273
|
|
|
274
274
|
`);return await l.close(),`Search results for [${o}]:
|
|
275
275
|
|
|
276
|
-
${a}`}catch(
|
|
276
|
+
${a}`}catch(u){if(s=u,l&&await l.close(),r<n){let f=Math.pow(2,r)*1e3;await new Promise(m=>setTimeout(m,f))}}}return`ERROR: Search failed after ${n+1} attempts. Last error: ${s.message}`}});import au from"puppeteer";var ui,za=re(()=>{Bt();ui=async e=>{let o=e.match(/url\s*=\s*["'](.*)["']/),t=o?o[1]:e,n=3,s=null;for(let r=1;r<=n;r++){let l=null;try{l=await au.launch({headless:!0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let u=await l.newPage();await u.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.97 Safari/537.36"),await u.setViewport({width:1366,height:768});let f=r===1?Math.random()*1e3+500:Math.random()*2e3+1e3;await new Promise(a=>setTimeout(a,f)),await u.goto(t,{waitUntil:"networkidle2",timeout:18e4}),await new Promise(a=>setTimeout(a,5e3));let m=await u.evaluate(()=>{document.querySelectorAll("script, style, nav, footer, header, noscript, svg, canvas, iframe, ad, .ads, link, meta, img").forEach(T=>T.remove());let d=document.createNodeIterator(document.body,NodeFilter.SHOW_COMMENT),p;for(;p=d.nextNode();)p.remove();document.querySelectorAll("*").forEach(T=>{let w=T.attributes;for(let I=w.length-1;I>=0;I--){let L=w[I].name;L!=="href"&&L!=="src"&&T.removeAttribute(L)}(T.tagName==="SPAN"||T.tagName==="DIV"||T.tagName==="SECTION")&&T.attributes.length===0&&(T.tagName==="SPAN"||T.tagName==="DIV"&&T.childNodes.length===1&&T.childNodes[0].nodeType===Node.TEXT_NODE)&&T.replaceWith(...T.childNodes)});let S=()=>{let T=!1;document.querySelectorAll("*:not(br)").forEach(w=>{w.childNodes.length===0&&!w.innerText.trim()&&(w.remove(),T=!0)}),T&&S()};return S(),document.body.innerHTML});if(!m)throw new Error("EMPTY_RENDER_RESULT");let c=m.replace(/\s+/g," ").replace(/>\s+</g,"><").trim().substring(0,3e4);return await l.close(),`CLEANED HTML FROM [${t}]:
|
|
277
277
|
|
|
278
|
-
${c}${
|
|
278
|
+
${c}${m.length>3e4?`
|
|
279
279
|
|
|
280
|
-
[TRUNCATED AT 30K CHARS]`:""}`}catch(
|
|
280
|
+
[TRUNCATED AT 30K CHARS]`:""}`}catch(u){if(s=u,l&&await l.close(),r<n){let f=Math.pow(2,r)*1e3;await new Promise(m=>setTimeout(m,f))}}}return`ERROR: Scrape failed after ${n+1} attempts. Last error: ${s.message}`}});var lu,di,Ja=re(()=>{Lo();Bt();lu=4*(1024*2),di=async(e,o={})=>{let t=c=>{let a=new RegExp(`${c}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),d=e.match(a);if(d)return d[2].trim();let p=new RegExp(`${c}\\s*[:=]\\s*([^,\\s)]+)`,"s"),h=e.match(p);return h?h[1].trim():null},n=t("action"),s=t("method"),r=t("content"),l=t("content-new"),u=t("content-old"),f=t("id"),m=t("chat-id")||o.chatId||o.sessionId||"default-session";if(n==="temp"){if(!r)return"ERROR: Missing 'content' for temp memory.";let c=xe(Eo,{});c[m]||(c[m]=[]),c[m].push(r),ke(Eo,c);let a=c[m].reduce((d,p)=>d+p.length,0);return`SUCCESS: Temporary context saved for session [${m}]. (Size: ${a} chars)`}if(n==="user"){let c=xe(Nt,[]).map(a=>(a.score===void 0&&(a.score=.5),a));if(s==="add"){if(!r)return"ERROR: Missing 'content' for memory addition.";let a=new Date,d=`${a.getDate()}/${a.getMonth()+1}/${a.getFullYear()}`,p=r.includes("[Saved on:")?r:`${r.trim()} [Saved on: ${d}]`,h=lu,S=c.reduce((L,_)=>L+(_.memory?.length||0),0);for(;c.length>0&&S+p.length>h;){let L=c.shift();S-=L.memory?.length||0}let T=t("score"),w=T?parseFloat(T):.5,I={id:`mem-${Date.now().toString(36)}`,memory:p,score:Math.min(2,isNaN(w)?.5:w)};return c.push(I),ke(Nt,c),`SUCCESS: Memory added with ID [${I.id}] and score [${I.score}]. (Vault Size: ${S+p.length} chars)`}if(s==="update"){let a=f||u,d=l||r;if(!a||!d)return"ERROR: Missing 'id' or content for update.";let p=c.findIndex(w=>w.id===a);if(p===-1)return`ERROR: Memory ID [${a}] not found.`;let h=new Date,S=`${h.getDate()}/${h.getMonth()+1}/${h.getFullYear()}`,T=d.includes("[Saved on:")?d:`${d.trim()} [Saved on: ${S}]`;return c[p].memory=T,ke(Nt,c),`SUCCESS: Memory [${a}] updated.`}if(s==="delete"){let a=f||r;if(!a)return"ERROR: Missing 'id' for deletion.";let d=c.length,p=c.filter(h=>h.id!==a);return p.length===d?`ERROR: Memory ID [${a}] not found.`:(ke(Nt,p),`SUCCESS: Memory [${a}] deleted.`)}return`ERROR: Invalid method [${s}] for user memory. Use 'add', 'update', or 'delete'.`}return`ERROR: Unknown action [${n}] for memory tool.`}});var mi,Qa=re(()=>{$r();Xt();mi=async(e,o={})=>{let t=ne(e).title,n=o.chatId||o.sessionId;if(!n)return"ERROR: No active chatId found in tool context.";if(!t)return"ERROR: Missing 'title' argument.";try{return await Ba(n,t),`SUCCESS: Chat title updated to [${t}] for session [${n}].`}catch(s){return`ERROR: Failed to update chat title: ${s.message}`}}});import gs from"fs";import Za from"path";var fi,el=re(()=>{Xt();fi=async(e,o={})=>{let{path:t,StartLine:n,EndLine:s,start_line:r,end_line:l,startLine:u,endLine:f}=ne(e),m=parseInt(n||r||u),c=parseInt(s||l||f),a=m||1,d=c||(m?m+800:800);if(!t)return'ERROR: Missing "path" argument for view_file.';let p=Za.resolve(process.cwd(),t);try{if(!gs.existsSync(p))return`ERROR: File [${t}] does not exist.`;if(gs.statSync(p).isDirectory())return`ERROR: Path [${t}] is a directory. Use list_files instead.`;let S=Za.extname(t).toLowerCase();if([".mp4",".mkv",".avi",".mov",".webm",".flv",".wmv",".mpeg",".mpg"].includes(S))return`ERROR: Unable to read. Type ${S.slice(1).toUpperCase()} not supported`;let w={".pdf":"application/pdf",".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".webp":"image/webp",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".doc":"application/msword"};if(w[S]){if(!(o.isMultiModal!==!1))return`ERROR: Multimodality is not supported for the current model. Unable to load [${t}].`;let Z=gs.readFileSync(p).toString("base64"),B=w[S];return{text:`[BINARY FILE]: ${t} (${B}) - Loaded as multimodal part.`,binaryPart:{inlineData:{data:Z,mimeType:B}}}}let I=gs.readFileSync(p,"utf8");I.startsWith("\uFEFF")&&(I=I.slice(1)),I=I.replace(/\r\n/g,`
|
|
281
281
|
`).replace(/\r/g,`
|
|
282
|
-
`);let
|
|
283
|
-
`),
|
|
282
|
+
`);let L=I.split(`
|
|
283
|
+
`),_=L.length,R=Math.max(0,a-1),v=Math.min(_,d),b=L.slice(R,v),A=`File: [${t}] (Showing lines ${R+1}-${v} of ${_}).`,F=b.map((Q,j)=>`${String(R+j+1).padStart(4)}: ${Q}`).join(`
|
|
284
284
|
`);return`${A}
|
|
285
285
|
|
|
286
|
-
${
|
|
286
|
+
${F}`}catch(h){return`ERROR: Failed to read file [${t}]: ${h.message}`}}});import ir from"fs";import tl from"path";var pi,ol=re(()=>{Xt();un();pi=async(e,o={})=>{let{path:t,content:n}=ne(e);if(!t)return'ERROR: Missing "path" argument for write_file.';if(n===void 0)return'ERROR: Missing "content" argument for write_file.';n=n.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
|
|
287
287
|
`).replace(/\r/g,`
|
|
288
|
-
`);let
|
|
289
|
-
${
|
|
288
|
+
`);let s=tl.resolve(process.cwd(),t),r=tl.dirname(s);try{await kt.recordFileChange(s);let l="";if(ir.existsSync(s))try{l=`Old File contents:
|
|
289
|
+
${ir.readFileSync(s,"utf8").split(/\r?\n/).map((I,L)=>`${L+1} | ${I}`).join(`
|
|
290
290
|
`)}
|
|
291
291
|
|
|
292
292
|
`}catch{l=`[Note: Could not read existing file for reversal reference]
|
|
293
293
|
|
|
294
|
-
`}
|
|
294
|
+
`}ir.existsSync(r)||ir.mkdirSync(r,{recursive:!0});let f=(T=>T.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
|
|
295
295
|
`).replace(/\r/g,`
|
|
296
|
-
`))(n),
|
|
296
|
+
`))(n),m=f.split(/\r?\n/).length,c=Buffer.byteLength(f,"utf8");ir.writeFileSync(s,f,"utf8");let a=ir.readFileSync(s,"utf8"),d=Buffer.byteLength(a,"utf8"),p=a.split(/\r?\n/),h=p.length;if(d===0&&c>0)return a=null,`ERROR: CRITICAL FAILURE: Verification failed. File [${t}] is empty on disk despite success report!`;let S="";if(h<=200)S=p.join(`
|
|
297
297
|
`);else{let T=p.slice(0,100).join(`
|
|
298
|
-
`),
|
|
298
|
+
`),w=p.slice(-100).join(`
|
|
299
299
|
`);S=`${T}
|
|
300
300
|
|
|
301
301
|
... [${h-200} lines truncated] ...
|
|
302
302
|
|
|
303
|
-
${
|
|
303
|
+
${w}`}return a=null,`SUCCESS: File [${t}] saved.
|
|
304
304
|
|
|
305
|
-
- Stats: [${h} lines, ${(
|
|
305
|
+
- Stats: [${h} lines, ${(d/1024).toFixed(1)} KB]
|
|
306
306
|
${l}- Content Preview:
|
|
307
307
|
${S}
|
|
308
308
|
|
|
309
|
-
Check if Starting and Ending matches your write.`}catch(l){return`ERROR: Failed to write file [${t}]: ${l.message}`}}});import
|
|
309
|
+
Check if Starting and Ending matches your write.`}catch(l){return`ERROR: Failed to write file [${t}]: ${l.message}`}}});import hi from"fs";import cu from"path";var gi,nl=re(()=>{Xt();un();Wn();gi=async(e,o={})=>{let t=ne(e),n=t.path;if(!n)return'ERROR: Missing "path" argument for update_file.';let{patchPairs:s,error:r}=rs(t);if(r)return`ERROR: ${r}`;if(s.length===0)return"ERROR: No valid replacement pairs found. Use replaceContent1, newContent1, etc.";let l=cu.resolve(process.cwd(),n);try{if(!hi.existsSync(l))return`ERROR: File [${n}] does not exist. Use write_file instead.`;let u=o.forcedContent||hi.readFileSync(l,"utf8");u.startsWith("\uFEFF")&&(u=u.slice(1));let f=u.replace(/\r\n/g,`
|
|
310
310
|
`).replace(/\r/g,`
|
|
311
|
-
`),{content:
|
|
311
|
+
`),{content:m,results:c}=ss(f,s),a=c.filter(h=>!h.success),d=c.filter(h=>h.success);if(d.length===0)return`ERROR: Patch Failed to apply to [${n}].
|
|
312
312
|
${a.map(h=>` \u2022 ${h.error}`).join(`
|
|
313
|
-
`)}`;await
|
|
313
|
+
`)}`;await kt.recordFileChange(l,f),hi.writeFileSync(l,m,"utf8");let p=is(f,m,c,12);return a.length>0?`SUCCESS: File [${n}] updated with some blocks failed. [${d.length}/${s.length}] blocks applied.
|
|
314
314
|
|
|
315
315
|
Failures:
|
|
316
316
|
${a.map(h=>` \u2022 ${h.error}`).join(`
|
|
317
317
|
`)}
|
|
318
318
|
|
|
319
|
-
${p}`:`SUCCESS: File [${n}] updated. [${c.length}/${
|
|
319
|
+
${p}`:`SUCCESS: File [${n}] updated. [${c.length}/${s.length}] blocks applied.
|
|
320
320
|
|
|
321
|
-
${p}`}catch(
|
|
321
|
+
${p}`}catch(u){return`ERROR: Failed to update file [${n}]: ${u.message}`}}});import xs from"fs";import rl from"path";var xi,sl=re(()=>{Xt();xi=async e=>{let{path:o="."}=ne(e),t=rl.resolve(process.cwd(),o);try{if(!xs.existsSync(t))return`ERROR: Path [${o}] does not exist.`;if(!xs.statSync(t).isDirectory())return`ERROR: Path [${o}] is a file, not a directory. Use view_file instead.`;let s=xs.readdirSync(t),r=s.length,l=100,u=s.slice(0,l),f=[];for(let d of u){let p=rl.join(t,d),h="\u{1F4C4}",S={name:d,type:"unknown",size:"N/A",mtime:"N/A"};try{let T=xs.statSync(p);S={name:d,type:T.isDirectory()?"directory":"file",size:(T.size/1024).toFixed(1)+" KB",mtime:T.mtime.toLocaleString()}}catch{S.type="inaccessible"}f.push(S)}let m=f.map(d=>{let p=d.type==="directory"?"\u{1F4C1}":d.type==="file"?"\u{1F4C4}":"\u2753";return d.type==="directory"?`${p} ${d.name} - [DIR] - [Modified: ${d.mtime}]`:`${p} ${d.name} - [Size: ${d.size}] - [Modified: ${d.mtime}]`}).join(`
|
|
322
322
|
`),c=`
|
|
323
323
|
|
|
324
324
|
(Total items in folder: ${r})`;r>l&&(c=`
|
|
325
325
|
|
|
326
326
|
\u26A0\uFE0F TRUNCATED: Showing first ${l} of ${r} items.`);let a=`Detailed folder stats for [${o}]:
|
|
327
327
|
|
|
328
|
-
${
|
|
328
|
+
${m}${c}`;return s.length=0,u.length=0,f.length=0,a}catch(n){return`ERROR: Failed to read folder [${o}]: ${n.message}`}}});var yi,il=re(()=>{Xt();yi=async(e,o)=>{let t=ne(e),{question:n}=t;if(!n)return'ERROR: Missing "question" argument for ask.';if(!o.onAskUser)return"ERROR: onAskUser callback not provided in tool context.";let s=[];Object.keys(t).forEach(r=>{if(r.startsWith("option")){let l=t[r];if(typeof l=="string"&&l.includes("::")){let[u,f]=l.split("::");s.push({id:r,label:u.trim(),description:f.trim()})}else s.push({id:r,label:String(l).trim(),description:""})}});try{return`USER CHOOSE: ${await o.onAskUser(n,s)}`}catch(r){return`ERROR: Failed to get user input: ${r.message}`}}});import uu from"puppeteer";import ar from"path";import Gn from"fs-extra";import{PDFDocument as du}from"pdf-lib";var wi,al=re(()=>{Xt();un();wi=async e=>{let{path:o,content:t,orientation:n="portrait",margin:s="0px"}=ne(e);if(!o)return'ERROR: Missing "path" argument for write_pdf.';if(!t)return'ERROR: Missing "content" (HTML/CSS) for write_pdf.';let r=ar.resolve(process.cwd(),o),l=null;try{await Gn.ensureDir(ar.dirname(r)),await kt.recordFileChange(r),l=await uu.launch({headless:!0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let u=await l.newPage(),f=t,m={},c=async v=>{if(!v||v.startsWith("http://")||v.startsWith("https://")||v.startsWith("data:"))return null;try{let b=ar.resolve(process.cwd(),v);if(await Gn.pathExists(b)){let A=ar.extname(b).toLowerCase().replace(".","")||"png",F=A==="jpg"?"jpeg":A==="svg"?"svg+xml":A,Q=await Gn.readFile(b,"base64");return`data:image/${F};base64,${Q}`}}catch{}return null},a=/<link[^>]+href=["']([^"']+)["']/gi,d={},p;for(;(p=a.exec(t))!==null;){let v=p[1],b=p[0];if(v&&b.toLowerCase().includes("stylesheet")&&!v.startsWith("http://")&&!v.startsWith("https://")&&!v.startsWith("data:"))try{let A=ar.resolve(process.cwd(),v);if(await Gn.pathExists(A)){let F=await Gn.readFile(A,"utf-8");d[b]=`<style>${F}</style>`}}catch{}}for(let[v,b]of Object.entries(d))f=f.split(v).join(b);let h=/<img[^>]+src=["']([^"']+)["']/gi;for(;(p=h.exec(f))!==null;){let v=p[1];if(v&&!m[v]){let b=await c(v);b&&(m[v]=b)}}let S=/url\(\s*['"]?([^'")]+?)['"]?\s*\)/gi;for(;(p=S.exec(f))!==null;){let v=p[1].trim();if(v&&!m[v]){let b=await c(v);b&&(m[v]=b)}}for(let[v,b]of Object.entries(m)){let A=v.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&"),F=new RegExp(`(src=["'])(${A})(["'])`,"gi");f=f.replace(F,`$1${b}$3`);let Q=new RegExp(`url\\(\\s*(['"]?)(${A})\\1\\s*\\)`,"gi");f=f.replace(Q,`url($1${b}$1)`)}let T=`
|
|
329
329
|
<style>
|
|
330
330
|
@page {
|
|
331
|
-
margin: ${
|
|
331
|
+
margin: ${s};
|
|
332
332
|
}
|
|
333
333
|
body {
|
|
334
334
|
margin: 0;
|
|
@@ -355,7 +355,7 @@ ${u}${c}`;return i.length=0,d.length=0,f.length=0,a}catch(n){return`ERROR: Faile
|
|
|
355
355
|
</style>
|
|
356
356
|
<div class="watermark">Generated by FluxFlow CLI (AI)</div>
|
|
357
357
|
${f}
|
|
358
|
-
`;await
|
|
358
|
+
`;await u.setContent(T,{waitUntil:"networkidle0",timeout:18e4});let w=await u.pdf({format:"A4",landscape:String(n).toLowerCase()==="landscape",margin:{top:s,right:s,bottom:s,left:s},printBackground:!0}),I=await du.load(w),L=ar.basename(o);I.setTitle(`FluxFlow_${L}`),I.setAuthor("FluxFlow CLI"),I.setSubject("Generated with Agentic AI System"),I.setKeywords(["FluxFlow","AI","Agentic","Automated"]),I.setCreator("FluxFlow PDF Engine"),I.setProducer("FluxFlow (Generative AI)");let _=await I.save();await Gn.writeFile(r,_);let R=await Gn.stat(r);return`SUCCESS: PDF generated successfully at [${o}] (${(R.size/1024).toFixed(2)} KB).`}catch(u){return`ERROR: Failed to generate PDF [${o}]: ${u.message}`}finally{l&&await l.close()}}});import ll from"fs-extra";import Ti from"path";import mu from"html-to-docx";var Si,cl=re(()=>{Xt();un();Si=async e=>{let{path:o,content:t}=ne(e);if(!o)return'ERROR: Missing "path" argument for write_docx.';if(!t)return'ERROR: Missing "content" (HTML) for write_docx.';let n=Ti.resolve(process.cwd(),o);try{await ll.ensureDir(Ti.dirname(n)),await kt.recordFileChange(n);let s=Ti.basename(o),r=t.includes("<html")?t:`
|
|
359
359
|
<!DOCTYPE html>
|
|
360
360
|
<html lang="en">
|
|
361
361
|
<head>
|
|
@@ -366,29 +366,34 @@ ${u}${c}`;return i.length=0,d.length=0,f.length=0,a}catch(n){return`ERROR: Faile
|
|
|
366
366
|
${t}
|
|
367
367
|
</body>
|
|
368
368
|
</html>
|
|
369
|
-
`,l=await
|
|
370
|
-
- Size: ${(l.length/1024).toFixed(1)} KB`}catch(
|
|
371
|
-
|
|
372
|
-
`;return c+=
|
|
373
|
-
`),c}catch(r){return`ERROR: ${r.message}`}}});import qa from"fs-extra";import fi from"path";var Fc,pi,Va=le(()=>{no();Kr();is();nn();Fc=(e,o={})=>{try{if(e.length<8||e[0]!==137||e[1]!==80||e[2]!==78||e[3]!==71)return e;let t=[],n=[];for(let l=0;l<256;l++){let d=l;for(let f=0;f<8;f++)d&1?d=3988292384^d>>>1:d=d>>>1;n[l]=d}let i=l=>{let d=4294967295;for(let f=0;f<l.length;f++)d=n[(d^l[f])&255]^d>>>8;return(d^4294967295)>>>0},r=(l,d)=>{let f=Buffer.from(l,"ascii"),u=Buffer.from(d,"utf-8"),c=f.length+1+u.length,a=Buffer.alloc(8+c+4);a.writeUInt32BE(c,0),a.write("tEXt",4,"ascii"),f.copy(a,8),a[8+f.length]=0,u.copy(a,8+f.length+1);let m=i(a.subarray(4,8+c));return a.writeUInt32BE(m,8+c),a};for(let[l,d]of Object.entries(o))d!=null&&t.push(r(l,String(d)));if(t.length===0)return e;if(e.subarray(12,16).toString("ascii")==="IHDR"){let d=e.subarray(0,33),f=e.subarray(33);return Buffer.concat([d,...t,f])}return e}catch{return e}},pi=async(e,o={})=>{let t=se(e),n=t.prompt||t.text,i=t.path||t.outputPath||t.output||"generated_image.png",r=t.ratio;if(!n)return'ERROR: Missing "prompt" argument for generate_image.';let l=["nsfw","naked","nudity","nude","porn","sex","xxx","erotic","gore","bloody","violence","abuse","suicide","murder","hentai","pedophile","rape"],d=n.toLowerCase();if(l.some(u=>d.includes(u)))return"ERROR: Prompt blocked by system safety filter (inappropriate or unsafe content detected).";try{let u=await qn();if(!await Oa(u))return`ERROR: Insufficient Quota for selected quality. Either tell user reduce quality or wait for next refresh cycle (${(await ss()).nextResetMin||60}m).`;let a=u.imageSettings||{keyType:"Default",quality:"Low-High",apiKey:""},m=a.keyType==="Custom"&&a.apiKey?a.apiKey:FALLBACK_IMAGE_KEY,h={Low:"flux","Low-High":"zimage",Medium:"gptimage","Medium-High":"gptimage",High:"qwen-image",Ultra:"gptimage-large",Premium:"nanobanana-pro"}[a.quality]||"zimage",S=1024,T=1024;if(r){let V=r.replace(/\s+/g,"");V==="16:9"?(S=1024,T=576):V==="9:16"?(S=576,T=1024):V==="4:3"?(S=1024,T=768):V==="3:4"?(S=768,T=1024):V==="1:1"&&(S=1024,T=1024)}let y=Math.floor(Math.random()*1e7),v=`https://gen.pollinations.ai/image/${encodeURIComponent(n)}?model=${h}&width=${S}&height=${T}&seed=${y}&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")}`,R=await fetch(v,{method:"GET",headers:{Authorization:`Bearer ${m}`}});if(!R.ok){let V=R.status,gt="";try{gt=await R.text()}catch{}return V===402||gt.includes("Insufficient balance")||gt.includes("PAYMENT_REQUIRED")?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed with status [${V}]: ${gt||"Unknown API Error"}`}if((R.headers.get("content-type")||"").includes("application/json")){let V=await R.json();return V.status===402||V.error&&V.error.code==="PAYMENT_REQUIRED"?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed: ${V.error?.message||JSON.stringify(V)}`}let F=await R.arrayBuffer(),C=Buffer.from(F),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(y)};C=Fc(C,A);let L=fi.resolve(process.cwd(),i);await qa.ensureDir(fi.dirname(L)),await Ct.recordFileChange(L),await qa.writeFile(L,C),await La(u);let J=fi.extname(i).toLowerCase(),Z={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".webp":"image/webp"}[J]||"image/png";return o.isMultiModal!==!1?{text:`SUCCESS: Image successfully generated from prompt [${n}] and saved to [${i}]. Output attached to multimodal part`,binaryPart:{inlineData:{data:C.toString("base64"),mimeType:Z}}}:`SUCCESS: Image successfully generated from prompt [${n}] and saved to [${i}].`}catch(u){return`ERROR: Failed during image generation: ${u.message}`}}});var Cr,za=le(()=>{Do();to();Cr=async(e,o={})=>{let t=r=>{let l=new RegExp(`${r}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),d=e.match(l);return d?d[2].trim():null},n=t("id"),i=t("summary");if(!n||!i)return"ERROR: Missing 'id' or 'summary' for saveSummary tool.";try{let r=Se(wo,{}),l=Se(Ro,{});return l[n]=i,delete r[n],Ae(Ro,l),Ae(wo,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 er,Ja=le(()=>{Do();to();er=async(e,o={})=>{let n=(i=>{let r=new RegExp(`${i}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),l=e.match(r);return l?l[2].trim():null})("id");if(!n)return"ERROR: Missing 'id' parameter for addMemScore tool.";try{let i=Se(Nt,[]),r=!1,l=[];for(let c of i)c.score===void 0&&(c.score=.5),c.id===n?(c.score=Math.min(2,c.score+.2),r=!0):(c.score*=.98,c.score<.05&&(c.score=0)),c.score=Math.round(c.score*1e5)/1e5,c.score>0&&l.push(c);if(Ae(Nt,l),!r)return`WARNING: Memory ID [${n}] not found. Other memories decayed by -0.01.`;let d=l.find(c=>c.id===n),f=d?d.score.toFixed(2):"deleted (score <= 0)",u=i.length-l.length;return`SUCCESS: Adjusted memory scores. Target [${n}] is now ${f}.${u>0?` Purged ${u} decayed memories.`:""}`}catch(i){return`ERROR: Failed to adjust memory score for [${n}]: ${i.message}`}}});var Pc,cs,Qa=le(async()=>{Da();va();$a();Fa();Ba();_a();Ua();await Tr();Wa();Ya();Ha();Ga();Ka();Va();za();Ja();Pc={web_search:Qs,web_scrape:Zs,memory:ei,chat:ti,view_file:oi,write_file:ni,update_file:si,exec_command:Ps,read_folder:ii,write_pdf:li,write_docx:di,search_keyword:mi,generate_image:pi,saveSummary:Cr,addMemScore:er,ask:ai,Ask:ai,WebSearch:Qs,WebScrape:Zs,ReadFile:oi,ReadFolder:ii,WriteFile:ni,PatchFile:si,WritePDF:li,WriteDoc:di,Run:Ps,SearchKeyword:mi,Memory:ei,Chat:ti,GenerateImage:pi,saveSumary:Cr,SaveSummary:Cr,SaveSumary:Cr,add_mem_score:er,AddMemScore:er,addMemoryScore:er,AddMemoryScore:er},cs=async(e,o,t={})=>{if(t.mode&&t.mode.toLowerCase()==="flow"){let i=e.toLowerCase();if(!(i.startsWith("web")||i.startsWith("ask")))return`ERROR: Tool [${e}] is restricted in Flow mode.`}let n=Pc[e];if(!n)return`ERROR: Tool [${e}] not found in registry.`;try{return await n(o,t)}catch(i){return`ERROR: Execution failed for [${e}]: ${i.message}`}}});import{WebSocket as ds}from"ws";var fo,tr,Bc,hi,or,gi,Za,xi,wi,el,us,Go,ms,kr,tl,yi,ol,Ti=le(()=>{fo=null,tr=!1,Bc="ws://localhost:56832",hi=[],or=null,gi=null,Za="2.0.0",xi=e=>{Za=e,el()},wi=e=>{gi=e},el=()=>{if(fo||tr)return;tr=!0;let e=new ds(Bc);e.on("open",()=>{for(fo=e,tr=!1,fo.send(JSON.stringify({command:"version",version:Za,pid:process.pid,ppid:process.ppid}));hi.length>0;)fo.send(JSON.stringify(hi.shift()))}),e.on("message",o=>{try{let t=JSON.parse(o.toString());t.command==="contextResponse"&&or?(or(t.data),or=null):t.command==="securityResponse"&&gi&&gi(t.result)}catch{}}),e.on("error",()=>{tr=!1,fo=null}),e.on("close",()=>{tr=!1,fo=null})},us=e=>{fo&&fo.readyState===ds.OPEN?fo.send(JSON.stringify(e)):(hi.push(e),tr||el())},Go=()=>fo!==null&&fo.readyState===ds.OPEN,ms=e=>{us({command:"status",status:e})},kr=()=>new Promise(e=>{if(!fo||fo.readyState!==ds.OPEN){e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]});return}or=e,fo.send(JSON.stringify({command:"requestContext"})),setTimeout(()=>{or===e&&(e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]}),or=null)},1e3)}),tl=e=>{us({command:"open",filePath:e})},yi=(e,o,t)=>{us({command:"showDiff",filePath:e,originalContent:o,modifiedContent:t})},ol=(e,o)=>{us({command:"closeDiff",filePath:e,result:o})}});import{GoogleGenAI as Nc,ThinkingLevel as Po,HarmBlockThreshold as bn,HarmCategory as Cn}from"@google/genai";import ke from"path";import ht from"fs";var rr,Ei,nr,_c,Si,Uc,sl,Ci,ki,il,nl,Rc,al,Wc,ll,Yc,rl,Ii,Ir,bi,Hc,cl,dl=le(async()=>{await wa();Er();is();await Qa();Do();no();yn();Fn();to();nn();Ti();rr=null,Ei={},nr=!1,_c=["google/gemma-4-31b-it:free","moonshotai/kimi-k2.6:free","google/gemini-3.5-flash","qwen/qwen3.7-plus","minimax/minimax-m3","anthropic/claude-sonnet-4.5","anthropic/claude-opus-4.6","anthropic/claude-opus-4.8","openai/gpt-5.2-codex","openai/gpt-5.2-pro","openai/gpt-5.5-pro","moonshotai/kimi-k2.6","gemma-4-31b-it","gemini-2.5-flash","gemini-3-flash-preview","gemini-3.5-flash","gemini-3.1-flash-lite","gemini-3.1-pro-preview"],Si=e=>{if(!e)return!1;let o=e.toLowerCase();return o.startsWith("gemini-")||o.startsWith("gemma-")?!0:_c.some(t=>t.toLowerCase()===o)},Uc=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),sl=async(e,o,t=5,n=1e3)=>{for(let i=0;i<t;i++){try{let r=await fetch(e,o);if(r.ok||r.status!==429&&r.status<500)return r}catch(r){if(i===t-1)throw r}await new Promise(r=>setTimeout(r,n*Math.pow(2,i)))}return fetch(e,o)},Ci=async function*(e,o,t,n,i,r,l){let d=[];n&&d.push({role:"system",content:n});for(let y of t){let M=y.role==="user"?"user":"assistant",v=[];if(Array.isArray(y.parts)){for(let R of y.parts)if(R.text)v.push({type:"text",text:R.text});else if(R.inlineData&&l){let K=R.inlineData.mimeType,F=R.inlineData.data;K.startsWith("image/")&&v.push({type:"image_url",image_url:{url:`data:${K};base64,${F}`}})}}else{let R=y.text||"";R&&v.push({type:"text",text:R})}d.push({role:M,content:v.length===1&&v[0].type==="text"?v[0].text:v})}let f={model:o,messages:d,stream:!0,stream_options:{include_usage:!0},temperature:r==="Flux"?1:1.4};if(i!=="Fast"){let y={Low:"high",Medium:"high",High:"high",Standard:"high",xHigh:"max"};f.reasoning_effort=y[i]||"high",f.extra_body={thinking:{type:"enabled"}}}else f.extra_body={thinking:{type:"disabled"}};let u=await sl("https://api.deepseek.com/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(f)});if(!u.ok){let y=await u.json().catch(()=>({}));throw new Error(`DeepSeek Error (${u.status}): ${y.error?.message||u.statusText}`)}let c=u.body.getReader(),a=new TextDecoder,m="",p=[],h=null,S=Date.now(),T=!1;for(;;){let{done:y,value:M}=await c.read();if(y){T&&(p.length>0||h)&&(yield{candidates:p.length>0?[{content:{parts:p}}]:[],usageMetadata:h});break}m+=a.decode(M,{stream:!0});let v=m.split(`
|
|
374
|
-
`)
|
|
375
|
-
|
|
376
|
-
|
|
369
|
+
`,l=await mu(r,null,{title:`FluxFlow_${s}`,creator:"FluxFlow CLI",description:"Generated by Agentic AI System",table:{row:{cantSplit:!0}},footer:!0,pageNumber:!0});return await ll.writeFile(n,l),`SUCCESS: Word document [${o}] generated successfully.
|
|
370
|
+
- Size: ${(l.length/1024).toFixed(1)} KB`}catch(s){return`ERROR: Failed to generate DOCX [${o}]: ${s.message}`}}});import Ei from"fs/promises";import Pr from"path";async function ul(e,o,t=e,n=1){if(n>12)return[];let s=[],r;try{r=await Ei.readdir(e,{withFileTypes:!0})}catch{return[]}for(let l of r){let u=Pr.join(e,l.name),f=Pr.relative(t,u),m=f.split(Pr.sep).map(a=>a.toLowerCase());if(!o.some(a=>m.includes(a.toLowerCase())))if(l.isDirectory()){let a=await ul(u,o,t,n+1);s=s.concat(a)}else l.isFile()&&s.push({fullPath:u,relativePath:f})}return s}var bi,dl=re(()=>{Xt();bi=async e=>{let{keyword:o,file:t}=ne(e);if(!o)return'ERROR: Missing "keyword" argument.';let n=["node_modules",".git","dist",".next",".gemini",".exe",".dll",".png",".jpg",".jpeg",".gif",".zip",".tgz"],s=150;try{let r=[],l=process.cwd();if(t){let a=Pr.resolve(l,t);try{(await Ei.stat(a)).isFile()&&r.push({fullPath:a,relativePath:Pr.relative(l,a)})}catch{return`ERROR: File not found: ${t}`}}else r=await ul(l,n);let u=r.map(async a=>{try{let d=await Ei.readFile(a.fullPath,"utf-8");if(d.includes("\0"))return[];let p=d.split(/\r?\n/),h=[];for(let S=0;S<p.length;S++)if(p[S].includes(o)){let T=a.relativePath.replace(/\\/g,"/");h.push(`${T} \u2192 ${S+1}`)}return h}catch{return[]}}),m=(await Promise.all(u)).flat().slice(0,s);if(typeof global.gc=="function"&&global.gc(),m.length===0)return`Found 0 matches for keyword: "${o}"${t?` in file: ${t}`:". Try to specify files"}`;let c=`Found ${m.length} matches:
|
|
371
|
+
|
|
372
|
+
`;return c+=m.join(`
|
|
373
|
+
`),c}catch(r){return`ERROR: ${r.message}`}}});import ml from"fs-extra";import Ci from"path";var fu,ki,fl=re(()=>{Xt();os();hs();un();fu=(e,o={})=>{try{if(e.length<8||e[0]!==137||e[1]!==80||e[2]!==78||e[3]!==71)return e;let t=[],n=[];for(let l=0;l<256;l++){let u=l;for(let f=0;f<8;f++)u&1?u=3988292384^u>>>1:u=u>>>1;n[l]=u}let s=l=>{let u=4294967295;for(let f=0;f<l.length;f++)u=n[(u^l[f])&255]^u>>>8;return(u^4294967295)>>>0},r=(l,u)=>{let f=Buffer.from(l,"ascii"),m=Buffer.from(u,"utf-8"),c=f.length+1+m.length,a=Buffer.alloc(8+c+4);a.writeUInt32BE(c,0),a.write("tEXt",4,"ascii"),f.copy(a,8),a[8+f.length]=0,m.copy(a,8+f.length+1);let d=s(a.subarray(4,8+c));return a.writeUInt32BE(d,8+c),a};for(let[l,u]of Object.entries(o))u!=null&&t.push(r(l,String(u)));if(t.length===0)return e;if(e.subarray(12,16).toString("ascii")==="IHDR"){let u=e.subarray(0,33),f=e.subarray(33);return Buffer.concat([u,...t,f])}return e}catch{return e}},ki=async(e,o={})=>{let t=ne(e),n=t.prompt||t.text,s=t.path||t.outputPath||t.output||"generated_image.png",r=t.ratio;if(!n)return'ERROR: Missing "prompt" argument for generate_image.';let l=["nsfw","naked","nudity","nude","porn","sex","xxx","erotic","gore","bloody","violence","abuse","suicide","murder","hentai","pedophile","rape"],u=n.toLowerCase();if(l.some(m=>u.includes(m)))return"ERROR: Prompt blocked by system safety filter (inappropriate or unsafe content detected).";try{let m=await or();if(!await Ka(m))return`ERROR: Insufficient Quota for selected quality. Either tell user reduce quality or wait for next refresh cycle (${(await ps()).nextResetMin||60}m).`;let a=m.imageSettings||{keyType:"Default",quality:"Low-High",apiKey:""},d=a.keyType==="Custom"&&a.apiKey?a.apiKey:FALLBACK_IMAGE_KEY,h={Low:"flux","Low-High":"zimage",Medium:"gptimage","Medium-High":"gptimage",High:"qwen-image",Ultra:"gptimage-large",Premium:"nanobanana-pro"}[a.quality]||"zimage",S=1024,T=1024;if(r){let z=r.replace(/\s+/g,"");z==="16:9"?(S=1024,T=576):z==="9:16"?(S=576,T=1024):z==="4:3"?(S=1024,T=768):z==="3:4"?(S=768,T=1024):z==="1:1"&&(S=1024,T=1024)}let w=Math.floor(Math.random()*1e7),L=`https://gen.pollinations.ai/image/${encodeURIComponent(n)}?model=${h}&width=${S}&height=${T}&seed=${w}&enhance=true&reasoning=high&quality=high&negative=${encodeURIComponent("deformed, distorted, disfigured, poorly drawn, bad anatomy, wrong anatomy, extra limb, missing limb, floating limbs, disconnected limbs, mutation, mutated hands and fingers, blurry, low quality, low resolution, extra fingers, censored, watermarks, signatures")}`,_=await fetch(L,{method:"GET",headers:{Authorization:`Bearer ${d}`}});if(!_.ok){let z=_.status,mt="";try{mt=await _.text()}catch{}return z===402||mt.includes("Insufficient balance")||mt.includes("PAYMENT_REQUIRED")?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed with status [${z}]: ${mt||"Unknown API Error"}`}if((_.headers.get("content-type")||"").includes("application/json")){let z=await _.json();return z.status===402||z.error&&z.error.code==="PAYMENT_REQUIRED"?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed: ${z.error?.message||JSON.stringify(z)}`}let v=await _.arrayBuffer(),b=Buffer.from(v),A={Title:n,Description:"Generated via FluxFlow CLI",Software:"FluxFlow CLI",Author:"FluxFlow","Creation Time":new Date().toISOString(),Prompt:n,Model:`Fluxflow:${h}`,Ratio:r||"1:1",Seed:String(w)};b=fu(b,A);let F=Ci.resolve(process.cwd(),s);await ml.ensureDir(Ci.dirname(F)),await kt.recordFileChange(F),await ml.writeFile(F,b),await qa(m);let Q=Ci.extname(s).toLowerCase(),Z={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".webp":"image/webp"}[Q]||"image/png";return o.isMultiModal!==!1?{text:`SUCCESS: Image successfully generated from prompt [${n}] and saved to [${s}]. Output attached to multimodal part`,binaryPart:{inlineData:{data:b.toString("base64"),mimeType:Z}}}:`SUCCESS: Image successfully generated from prompt [${n}] and saved to [${s}].`}catch(m){return`ERROR: Failed during image generation: ${m.message}`}}});var _r,pl=re(()=>{Lo();Bt();_r=async(e,o={})=>{let t=r=>{let l=new RegExp(`${r}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),u=e.match(l);return u?u[2].trim():null},n=t("id"),s=t("summary");if(!n||!s)return"ERROR: Missing 'id' or 'summary' for saveSummary tool.";try{let r=xe(Eo,{}),l=xe(Go,{});return l[n]=s,delete r[n],ke(Go,l),ke(Eo,r),`SUCCESS: Saved summary and purged raw memories for chat [${n}].`}catch(r){return`ERROR: Failed to save summary for chat [${n}]: ${r.message}`}}});var lr,hl=re(()=>{Lo();Bt();lr=async(e,o={})=>{let n=(s=>{let r=new RegExp(`${s}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),l=e.match(r);return l?l[2].trim():null})("id");if(!n)return"ERROR: Missing 'id' parameter for addMemScore tool.";try{let s=xe(Nt,[]),r=!1,l=[];for(let c of s)c.score===void 0&&(c.score=.5),c.id===n?(c.score=Math.min(2,c.score+.2),r=!0):(c.score*=.98,c.score<.05&&(c.score=0)),c.score=Math.round(c.score*1e5)/1e5,c.score>0&&l.push(c);if(ke(Nt,l),!r)return`WARNING: Memory ID [${n}] not found. Other memories decayed by -0.01.`;let u=l.find(c=>c.id===n),f=u?u.score.toFixed(2):"deleted (score <= 0)",m=s.length-l.length;return`SUCCESS: Adjusted memory scores. Target [${n}] is now ${f}.${m>0?` Purged ${m} decayed memories.`:""}`}catch(s){return`ERROR: Failed to adjust memory score for [${n}]: ${s.message}`}}});import Hn from"fs-extra";import Ii from"path";import pu from"https";async function Mi(e,o=null){let t=o||`https://unpkg.com/tree-sitter-wasms@0.1.13/out/${e}`,n=Ii.join(Tn,e);return await Hn.ensureDir(Tn),new Promise((s,r)=>{let l={headers:{"User-Agent":"FluxFlow-Agent"}};pu.get(t,l,u=>{if([301,302,307,308].includes(u.statusCode)&&u.headers.location){let m=u.headers.location;if(!m.startsWith("http")){let c=new URL(t);m=`${c.protocol}//${c.host}${m}`}Mi(e,m).then(s).catch(r);return}if(u.statusCode!==200){r(new Error(`Failed to download ${e}: HTTP ${u.statusCode}`));return}let f=Hn.createWriteStream(n);u.pipe(f),f.on("finish",()=>{f.close(),s()})}).on("error",u=>{Hn.existsSync(n)&&Hn.unlink(n,()=>{}),r(u)})})}function xl(e){let o=Ii.join(Tn,e);return Hn.existsSync(o)}async function yl(e){let o=Ii.join(Tn,e);Hn.existsSync(o)&&await Hn.unlink(o)}var gl,vi=re(()=>{Bt();gl={js:"tree-sitter-javascript.wasm",jsx:"tree-sitter-javascript.wasm",ts:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm",py:"tree-sitter-python.wasm",c:"tree-sitter-c.wasm",cpp:"tree-sitter-cpp.wasm",java:"tree-sitter-java.wasm",html:"tree-sitter-html.wasm"}});import Ai from"fs-extra";import Xn from"path";import{createRequire as hu}from"module";function bl(e){if(e.type==="element"||e.type==="script_element"||e.type==="style_element"){let t=e.childForFieldName("start_tag")||e.children.find(s=>s.type==="start_tag");if(t){let s=t.childForFieldName("name")||t.children.find(r=>r.type==="tag_name");return s?s.text:null}let n=e.children.find(s=>s.type==="tag_name");return n?n.text:null}if(e.type==="jsx_element"||e.type==="jsx_self_closing_element"){let n=(e.childForFieldName("opening_element")||e).childForFieldName("name");return n?n.text:null}if(e.type==="import_declaration"||e.type==="import_from_statement"||e.type==="import_statement"||e.type==="preproc_include")return e.text.split(`
|
|
374
|
+
`)[0].trim();if(e.type==="function_definition"||e.type==="function_declaration"){let t=e.childForFieldName("declarator");if(t){let n=t.descendantsOfType("identifier")[0]||t.descendantsOfType("field_identifier")[0];if(n)return n.text}}let o=e.childForFieldName("name")||e.children.find(t=>t.type==="identifier"||t.type==="variable_declarator"||t.type==="type_identifier"||t.type==="field_identifier");if(o){if(o.type==="variable_declarator"){let t=o.childForFieldName("name")||o.children.find(n=>n.type==="identifier");return t?t.text:null}return o.text}if(e.type==="lexical_declaration"||e.type==="variable_declaration"){let t=e.children.find(n=>n.type==="variable_declarator");if(t)return bl(t)}if(e.type==="method_definition"||e.type==="function_declaration"){let t=e.childForFieldName("name")||e.children.find(n=>n.type==="identifier");if(t)return t.text}return null}function gu(e){let o=[];function t(n){for(let s of n.children)El.has(s.type)?o.push(s):t(s)}return t(e),o}function Cl(e,o=0,t=!0,n=""){if(o>6)return"";let r=e.type,l=El.has(r)||o===0,u="",f=n;if(l){let c=e.startPosition.row+1,a=e.endPosition.row+1,d=bl(e),p=d?`${r} [${d}]`:r;o===0?u+=`\u{1F4C1} ROOT (Lines: ${c}-${a})
|
|
375
|
+
`:(u+=`${n}${t?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 "}${p} (Lines: ${c}-${a})
|
|
376
|
+
`,f+=t?" ":"\u2502 ")}let m=gu(e);return m.forEach((c,a)=>{let d=a===m.length-1;u+=Cl(c,o+1,d,l?f:n)}),u}var Sl,wl,Tl,El,Oi,kl=re(()=>{vi();Bt();Xt();Sl=hu(import.meta.url),wl=Sl("web-tree-sitter"),Tl=!1,El=new Set(["class_declaration","function_declaration","method_definition","arrow_function","if_statement","for_statement","while_statement","do_statement","switch_statement","try_statement","variable_declaration","lexical_declaration","export_statement","interface_declaration","type_alias_declaration","enum_declaration","import_declaration","jsx_element","jsx_self_closing_element","class_definition","function_definition","decorated_definition","import_from_statement","import_statement","preproc_include","method_declaration","constructor_declaration","class_specifier","struct_specifier","enum_specifier","field_declaration","element","script_element","style_element"]);Oi=async e=>{let o;try{o=ne(e).path}catch{return`ERROR: Failed to parse arguments: ${e}`}if(!o)return'ERROR: No file path provided. Use [tool:functions.FileMap(path="...")]';let t=Xn.isAbsolute(o)?o:Xn.resolve(process.cwd(),o);if(!Ai.existsSync(t))return`ERROR: File not found: ${o}`;let n=Xn.extname(t).slice(1).toLowerCase(),s=gl[n];if(!s)return`ERROR: Unsupported file extension: .${n}`;let r=Xn.resolve(Tn,s);if(!Ai.existsSync(r))return`ERROR: Parser for .${n} not found. Please download it in Settings > Other.`;try{let l=wl.Parser;if(!Tl){let d;try{d=Xn.join(Xn.dirname(Sl.resolve("web-tree-sitter")),"tree-sitter.wasm")}catch{d=Xn.join(process.cwd(),"node_modules","web-tree-sitter","tree-sitter.wasm")}await l.init({locateFile:p=>p==="tree-sitter.wasm"||p.endsWith("tree-sitter.wasm")?d:p}),Tl=!0}let u=new l,f=await wl.Language.load(r);u.setLanguage(f);let m=await Ai.readFile(t,"utf8"),c=u.parse(m),a=Cl(c.rootNode);return`\u{1F4C4} File Map for: ${o}
|
|
377
|
+
${a}`}catch(l){let u=l instanceof Error?l.message:typeof l=="object"?JSON.stringify(l):String(l),f=l instanceof Error?`
|
|
378
|
+
Stack: ${l.stack}`:"";return`ERROR: Failed to map file: ${u}${f}`}}});var xu,ys,Il=re(async()=>{Va();za();Ja();Qa();el();ol();nl();await Dr();sl();il();al();cl();dl();fl();pl();hl();kl();xu={web_search:ci,web_scrape:ui,memory:di,chat:mi,view_file:fi,write_file:pi,update_file:gi,exec_command:Xs,read_folder:xi,write_pdf:wi,write_docx:Si,search_keyword:bi,generate_image:ki,saveSummary:_r,addMemScore:lr,file_map:Oi,ask:yi,Ask:yi,WebSearch:ci,WebScrape:ui,ReadFile:fi,ReadFolder:xi,WriteFile:pi,PatchFile:gi,WritePDF:wi,WriteDoc:Si,Run:Xs,SearchKeyword:bi,Memory:di,Chat:mi,GenerateImage:ki,saveSumary:_r,SaveSummary:_r,SaveSumary:_r,add_mem_score:lr,AddMemScore:lr,addMemoryScore:lr,AddMemoryScore:lr,FileMap:Oi},ys=async(e,o,t={})=>{if(t.mode&&t.mode.toLowerCase()==="flow"){let s=e.toLowerCase();if(!(s.startsWith("web")||s.startsWith("ask")))return`ERROR: Tool [${e}] is restricted in Flow mode.`}let n=xu[e];if(!n)return`ERROR: Tool [${e}] not found in registry.`;try{return await n(o,t)}catch(s){return`ERROR: Execution failed for [${e}]: ${s.message}`}}});import{WebSocket as ws}from"ws";var po,cr,yu,Di,ur,Li,Ml,Fi,$i,vl,Ts,Vo,Ss,Nr,Al,Pi,Ol,_i=re(()=>{po=null,cr=!1,yu="ws://localhost:56832",Di=[],ur=null,Li=null,Ml="2.0.0",Fi=e=>{Ml=e,vl()},$i=e=>{Li=e},vl=()=>{if(po||cr)return;cr=!0;let e=new ws(yu);e.on("open",()=>{for(po=e,cr=!1,po.send(JSON.stringify({command:"version",version:Ml,pid:process.pid,ppid:process.ppid}));Di.length>0;)po.send(JSON.stringify(Di.shift()))}),e.on("message",o=>{try{let t=JSON.parse(o.toString());t.command==="contextResponse"&&ur?(ur(t.data),ur=null):t.command==="securityResponse"&&Li&&Li(t.result)}catch{}}),e.on("error",()=>{cr=!1,po=null}),e.on("close",()=>{cr=!1,po=null})},Ts=e=>{po&&po.readyState===ws.OPEN?po.send(JSON.stringify(e)):(Di.push(e),cr||vl())},Vo=()=>po!==null&&po.readyState===ws.OPEN,Ss=e=>{Ts({command:"status",status:e})},Nr=()=>new Promise(e=>{if(!po||po.readyState!==ws.OPEN){e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]});return}ur=e,po.send(JSON.stringify({command:"requestContext"})),setTimeout(()=>{ur===e&&(e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]}),ur=null)},1e3)}),Al=e=>{Ts({command:"open",filePath:e})},Pi=(e,o,t)=>{Ts({command:"showDiff",filePath:e,originalContent:o,modifiedContent:t})},Ol=(e,o)=>{Ts({command:"closeDiff",filePath:e,result:o})}});import{GoogleGenAI as wu,ThinkingLevel as No,HarmBlockThreshold as On,HarmCategory as Dn}from"@google/genai";import Ee from"path";import dt from"fs";var mr,Bi,dr,Tu,Ni,Su,Fl,Ri,Wi,$l,Dl,Eu,Pl,bu,_l,Cu,Ll,Yi,Br,Ui,ku,Nl,Bl=re(async()=>{await _a();$r();hs();await Il();Lo();Xt();rn();Wn();Bt();un();_i();mr=null,Bi={},dr=!1,Tu=["google/gemma-4-31b-it:free","moonshotai/kimi-k2.6:free","google/gemini-3.5-flash","qwen/qwen3.7-plus","minimax/minimax-m3","anthropic/claude-sonnet-4.5","anthropic/claude-opus-4.6","anthropic/claude-opus-4.8","openai/gpt-5.2-codex","openai/gpt-5.2-pro","openai/gpt-5.5-pro","moonshotai/kimi-k2.6","gemma-4-31b-it","gemini-2.5-flash","gemini-3-flash-preview","gemini-3.5-flash","gemini-3.1-flash-lite","gemini-3.1-pro-preview"],Ni=e=>{if(!e)return!1;let o=e.toLowerCase();return o.startsWith("gemini-")||o.startsWith("gemma-")?!0:Tu.some(t=>t.toLowerCase()===o)},Su=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),Fl=async(e,o,t=5,n=1e3)=>{for(let s=0;s<t;s++){try{let r=await fetch(e,o);if(r.ok||r.status!==429&&r.status<500)return r}catch(r){if(s===t-1)throw r}await new Promise(r=>setTimeout(r,n*Math.pow(2,s)))}return fetch(e,o)},Ri=async function*(e,o,t,n,s,r,l){let u=[];n&&u.push({role:"system",content:n});for(let w of t){let I=w.role==="user"?"user":"assistant",L=[];if(Array.isArray(w.parts)){for(let _ of w.parts)if(_.text)L.push({type:"text",text:_.text});else if(_.inlineData&&l){let R=_.inlineData.mimeType,v=_.inlineData.data;R.startsWith("image/")&&L.push({type:"image_url",image_url:{url:`data:${R};base64,${v}`}})}}else{let _=w.text||"";_&&L.push({type:"text",text:_})}u.push({role:I,content:L.length===1&&L[0].type==="text"?L[0].text:L})}let f={model:o,messages:u,stream:!0,stream_options:{include_usage:!0},temperature:r==="Flux"?1:1.4};if(s!=="Fast"){let w={Low:"high",Medium:"high",High:"high",Standard:"high",xHigh:"max"};f.reasoning_effort=w[s]||"high",f.extra_body={thinking:{type:"enabled"}}}else f.extra_body={thinking:{type:"disabled"}};let m=await Fl("https://api.deepseek.com/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(f)});if(!m.ok){let w=await m.json().catch(()=>({}));throw new Error(`DeepSeek Error (${m.status}): ${w.error?.message||m.statusText}`)}let c=m.body.getReader(),a=new TextDecoder,d="",p=[],h=null,S=Date.now(),T=!1;for(;;){let{done:w,value:I}=await c.read();if(w){T&&(p.length>0||h)&&(yield{candidates:p.length>0?[{content:{parts:p}}]:[],usageMetadata:h});break}d+=a.decode(I,{stream:!0});let L=d.split(`
|
|
379
|
+
`);d=L.pop();for(let _ of L){let R=_.trim();if(!(!R||!R.startsWith("data: "))){if(R==="data: [DONE]")break;try{let v=JSON.parse(R.substring(6)),b=v.choices?.[0]?.delta,A=v.usage;if(A&&(h={totalTokenCount:A.total_tokens||A.prompt_tokens+A.completion_tokens,promptTokenCount:A.prompt_tokens||0,candidatesTokenCount:A.completion_tokens||0,cachedContentTokenCount:A.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:A.completion_tokens_details?.reasoning_tokens||0},T=!0),b){let F=b.reasoning_content||null;F&&(p.push({text:F,thought:!0}),T=!0),b.content&&(p.push({text:b.content}),T=!0)}}catch{}}}Date.now()-S>=150&&T&&(yield{candidates:p.length>0?[{content:{parts:[...p]}}]:[],usageMetadata:h},p=[],S=Date.now(),T=!1)}},Wi=async function*(e,o,t,n,s,r,l){let u=[];n&&u.push({role:"system",content:n});for(let L of t){let _=L.role==="user"?"user":"assistant",R=[];if(Array.isArray(L.parts)){for(let v of L.parts)if(v.text)R.push({type:"text",text:v.text});else if(v.inlineData&&l){let b=v.inlineData.mimeType,A=v.inlineData.data;b.startsWith("image/")?R.push({type:"image_url",image_url:{url:`data:${b};base64,${A}`}}):R.push({type:"file",file:{filename:v.filename||"file",file_data:`data:${b};base64,${A}`}})}}else{let v=L.text||"";v&&R.push({type:"text",text:v})}u.push({role:_,content:R.length===1&&R[0].type==="text"?R[0].text:R})}let f={Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},m={model:o,messages:u,stream:!0,temperature:r==="Flux"?1:1.4},c=f[s];c&&s!=="Fast"&&(m.reasoning_effort=c);let a=await Fl("https://openrouter.ai/api/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json","X-Title":"FluxFlow CLI","X-Cache":"true"},body:JSON.stringify(m)});if(!a.ok){let L=await a.json().catch(()=>({}));throw new Error(`OpenRouter Error (${a.status}): ${L.error?.message||a.statusText}`)}let d=a.body.getReader(),p=new TextDecoder,h="",S=[],T=null,w=Date.now(),I=!1;for(;;){let{done:L,value:_}=await d.read();if(L){I&&(S.length>0||T)&&(yield{candidates:S.length>0?[{content:{parts:S}}]:[],usageMetadata:T});break}h+=p.decode(_,{stream:!0});let R=h.split(`
|
|
380
|
+
`);h=R.pop();for(let v of R){let b=v.trim();if(!(!b||!b.startsWith("data: "))){if(b==="data: [DONE]")break;try{let A=JSON.parse(b.substring(6)),F=A.choices?.[0]?.delta,Q=A.usage;if(Q&&(T={totalTokenCount:Q.total_tokens||Q.prompt_tokens+Q.completion_tokens,promptTokenCount:Q.prompt_tokens||0,candidatesTokenCount:Q.completion_tokens||0,cachedContentTokenCount:Q.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:Q.completion_tokens_details?.reasoning_tokens||0},I=!0),F){let j=F.reasoning||(F.reasoning_details?F.reasoning_details.map(Z=>Z.text).join(""):null);j&&(S.push({text:j,thought:!0}),I=!0),F.content&&(S.push({text:F.content}),I=!0)}}catch{}}}Date.now()-w>=150&&I&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:T},S=[],w=Date.now(),I=!1)}},$l=()=>{dr=!0},Dl={write_file:"Writing",update_file:"Editing",read_folder:"Reading",view_file:"Reading",exec_command:"Executing Command",web_search:"Searching",web_scrape:"Reading",memory:"Updating Memory",search_keyword:"Searching",file_map:"Generating Map",ask:"User Input",write_pdf:"Creating",write_docx:"Creating",generate_image:"Generating"},Eu=(e,o)=>{try{let t=ne(o),n=t.path||t.targetFile||t.TargetFile||t.directory;return n?Ee.basename(n.replace(/["']/g,"").replace(/\\/g,"/")):null}catch{return null}},Pl=async(e,o,t,n,s={})=>{process.stdout.isTTY&&(process.stdout.write("\x1B]0;Finalizing...\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=Finalizing...\x07"));let r=4*(1024*2),l=4*(1024*8),{onStatus:u,onMemoryUpdated:f,onBackgroundIncrement:m}=s,{profile:c,thinkingLevel:a,mode:d,janitorModel:p,chatId:h,systemSettings:S,sessionStats:T,aiProvider:w="Google",apiKey:I}=e,L=S?.memory!==!1,R=xe(Nt,[]).map(ue=>`- [${ue.id}]: ${ue.memory}`).join(`
|
|
381
|
+
`),v=n.slice(0,-1).filter(ue=>ue.text&&!ue.text.includes("[TOOL RESULT]")&&!ue.text.includes("OBSERVATION:")&&!ue.text.startsWith("[TERMINAL_RECORD]")&&!ue.isTerminalRecord&&!ue.isMeta&&!ue.isLogo&&!String(ue.id).startsWith("welcome")&&!String(ue.id).startsWith("logo")).slice(-14).map(ue=>{let tt=Su(ue.text).replace(/\[tool:functions\..*?\]/g,"").replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[METADATA \(PRIORITY: DYNAMIC\)\] Time: ([^|\n]+)/g,(je,ye)=>`[METADATA (PRIORITY: DYNAMIC)] Time: ${ye.replace(/:\d{2}/g,"")}`).replace(/\[turn: continue\]/g,"").replace(/\[turn: finish\]/g,"").replace(/\[\[END\]\]/g,"").replace(/\[TOOL RESULTS\]/g,"").replace(/\[tool results\]/g,"").replace(/\r?\n\r?\n/g,`
|
|
377
382
|
`).replace(/\n\n/g,`
|
|
378
|
-
`).replace(/\\n\\n/g,"").trim(),
|
|
379
|
-
... (truncated) ...`);let
|
|
380
|
-
... (truncated) ...`);let
|
|
383
|
+
`).replace(/\\n\\n/g,"").trim(),Ye=ue.role==="user"?r:l,_e=tt.substring(0,Ye);tt.length>Ye&&(_e+=`
|
|
384
|
+
... (truncated) ...`);let Me=ue.role==="user"?_e.startsWith("[USER]")?"":"[USER]: ":_e.startsWith("[AGENT]")?"":"[AGENT]: ";return{role:ue.role==="user"?"user":"model",parts:[{text:`${Me}${_e}`}]}}),b=n.filter(ue=>ue.role==="user").length===1,A=o.includes("[TITLE-UPDATE]"),F=Math.random()<.8,Q=b||A||F,j=t.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").trim(),Z=Pa(R,L,Q),B=`${j.replace(/\[tool:functions\..*?\]/g,"").replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[turn: continue\]/g,"").replace(/\[turn: finish\]/g,"").replace(/\[\[END\]\]/g,"").replace(/\[TOOL RESULTS\]/g,"").replace(/\[tool results\]/g,"").substring(0,l)}`;B.length>l&&(B+=`
|
|
385
|
+
... (truncated) ...`);let z=o.replace(/\[Prompted on:.*?\]/g,"").trim();B=B.replace(/\r?\n\r?\n/g,`
|
|
381
386
|
`).replace(/\n\n/g,`
|
|
382
|
-
`).replace(/\\n\\n/g,"").trim();let
|
|
383
|
-
${
|
|
387
|
+
`).replace(/\\n\\n/g,"").trim();let mt=`[USER]: ${z.substring(0,r)}
|
|
388
|
+
${z.length>r?`... (truncated) ...
|
|
384
389
|
|
|
385
390
|
`:""}
|
|
386
|
-
[AGENT (current turn)]: ${
|
|
391
|
+
[AGENT (current turn)]: ${B}`;v.push({role:"user",parts:[{text:mt}]});let ce="",Le=0,Je=L?12:-1;for(;Le<=Je;){process.stdout.isTTY&&(process.stdout.write(`\x1B]0;Retrying Finalizing... (${Le+1})...\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=Retrying Finalizing... (${Le+1})...\x07`));try{if(!await ai("background",e))return;let ue="",tt=null;try{let Me=new Promise((Wt,be)=>setTimeout(()=>be(new Error("JANITOR_TIMEOUT")),6e4)),je=(async()=>{if(w==="OpenRouter"){let rt=Wi(I,"google/gemma-4-26b-a4b-it:free",v,Z,"Fast",d)[Symbol.asyncIterator](),Ao=await rt.next();return{iterator:rt,firstResult:Ao}}else if(w==="DeepSeek"){let be=Ri(I,"deepseek-chat",v,Z,"Fast",d,!1)[Symbol.asyncIterator](),rt=await be.next();return{iterator:be,firstResult:rt}}else{let be=(await mr.models.generateContentStream({model:p||"gemma-4-26b-a4b-it",contents:v,config:{systemInstruction:Z,maxOutputTokens:512,temperature:.3,safetySettings:[{category:Dn.HARM_CATEGORY_HARASSMENT,threshold:On.BLOCK_NONE},{category:Dn.HARM_CATEGORY_HATE_SPEECH,threshold:On.BLOCK_NONE},{category:Dn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:On.BLOCK_NONE},{category:Dn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:On.BLOCK_NONE}],thinkingConfig:{includeThoughts:!1,thinkingLevel:No.MINIMAL}}}))[Symbol.asyncIterator](),rt=await be.next();return{iterator:be,firstResult:rt}}})(),{iterator:ye,firstResult:ft}=await Promise.race([je,Me]),{value:pt,done:lo}=ft;if(!lo&&pt){let Wt=pt.candidates?.[0]?.content?.parts,be=Wt?.[1]?.text||Wt?.[0]?.text||(typeof pt.text=="function"?pt.text():"");be&&(ue+=be),tt=pt.usageMetadata;for await(let rt of{[Symbol.asyncIterator]:()=>ye}){let Ao=rt.candidates?.[0]?.content?.parts,co=Ao?.[1]?.text||Ao?.[0]?.text||(typeof rt.text=="function"?rt.text():"");co&&(ue+=co),tt=rt.usageMetadata}}}catch(Me){throw Me}if(ue)ce=ue,tt&&await Co("tokens",tt.totalTokenCount||0);else throw new Error("No synthesis generated by Janitor.");m&&(m(),await qo("background"));let Ye=Yi(ce),_e=!1;for(let Me of Ye){let je=Me.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(je)&&(_e=!0);let ye={chatId:h,sessionId:h,history:n},ft=await ys(je,Me.args,ye);je.toLowerCase()==="memory"&&(Me.args.includes("action='user'")||Me.args.includes('action="user"'))&&!ft.startsWith("ERROR")&&(f&&f(),process.stdout.isTTY&&(process.stdout.write("\x1B]0;Memory Updated\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=Memory Updated\x07")),await new Promise(lo=>setTimeout(lo,3e3)))}if(!_e)try{let Me=xe(Nt,[]);if(Me.length>0){let je=[];for(let ye of Me)ye.score===void 0&&(ye.score=.5),ye.score*=.9995,ye.score<.05&&(ye.score=0),ye.score=Math.round(ye.score*1e5)/1e5,ye.score>0&&je.push(ye);ke(Nt,je)}}catch{}break}catch(ue){Le++;let tt=new Date().toLocaleString();process.stdout.isTTY&&process.stdout.write("\x1B]0;Finalizing Error\x07"),await new Promise(Me=>setTimeout(Me,1e3));let Ye=Ee.join(Io,"janitor");if(dt.existsSync(Ye)||dt.mkdirSync(Ye,{recursive:!0}),dt.appendFileSync(Ee.join(Ye,"error.log"),`ERROR [Attempt ${Le}/${Je+1}] [${tt}]: ${String(ue)}
|
|
387
392
|
|
|
388
|
-
`)
|
|
393
|
+
`),Le>Je)break;let _e=Math.min(1e3*Math.pow(2,Le-1),8e3);await new Promise(Me=>setTimeout(Me,_e))}}if(Le){let ue=Ee.join(Io,"janitor");dt.appendFileSync(Ee.join(ue,"error.log"),`-----------------------------------------------------------------------------
|
|
389
394
|
|
|
390
395
|
|
|
391
|
-
`)
|
|
396
|
+
`),Le>=Je&&(process.stdout.isTTY&&process.stdout.write(`\x1B]0;${L?"Finalizing Error":"Finalizing Skipped"}\x07`),await new Promise(tt=>setTimeout(tt,3e3)))}process.stdout.isTTY&&(process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07"))},bu=e=>{let o=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,t;for(;(t=o.exec(e))!==null;){let n=t.index+t[0].length-1,s=0,r=null,l=!1,u=!1;for(let f=n;f<e.length;f++){let m=e[f];if(!r&&(m==='"'||m==="'"||m==="`")?(r=m,l=!1):r&&m===r&&!l&&(r=null),!r&&(m==="("?s++:m===")"&&s--,s===0)){let c=f+1;for(;c<e.length&&/\s/.test(e[c]);)c++;if(c<e.length&&e[c]==="]"){u=!0,o.lastIndex=c+1;break}}m==="\\"?l=!l:l=!1}if(!u)return{inside:!0,toolName:t[1],startIndex:t.index,args:e.substring(t.index+t[0].length)}}return{inside:!1}},_l=(e,o=!0)=>{let t=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,n="",s=0,r;for(;(r=t.exec(e))!==null;){let l=e.substring(s,r.index);n+=o?l.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\]|$)/gi,""):l;let u=r.index+r[0].length-1,f=0,m=null,c=-1;for(let a=u;a<e.length;a++){let d=e[a];if(m){if(d===m){let p=0;for(let h=a-1;h>=0&&e[h]==="\\";h--)p++;p%2===0&&(m=null)}}else if(d==='"'||d==="'"||d==="`")m=d;else if(d==="(")f++;else if(d===")"&&(f--,f===0)){let p=a+1;for(;p<e.length&&/\s/.test(e[p]);)p++;if(p<e.length&&e[p]==="]"){c=p;break}}}if(c!==-1)n+="[tool:functions."+r[1]+"()]",s=c+1,t.lastIndex=s;else{n+="[tool:functions."+r[1]+"(",s=e.length;break}}return s<e.length&&(n+=o?e.substring(s).replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\]|$)/gi,""):e.substring(s)),n},Cu=(e,o,t)=>{let n=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,s="",r=0,l;for(;(l=n.exec(e))!==null;){let u=e.substring(r,l.index);s+=u.replace(o,t);let f=l.index+l[0].length-1,m=0,c=null,a=-1;for(let d=f;d<e.length;d++){let p=e[d];if(c){if(p===c){let h=0;for(let S=d-1;S>=0&&e[S]==="\\";S--)h++;h%2===0&&(c=null)}}else if(p==='"'||p==="'"||p==="`")c=p;else if(p==="(")m++;else if(p===")"&&(m--,m===0)){let h=d+1;for(;h<e.length&&/\s/.test(e[h]);)h++;if(h<e.length&&e[h]==="]"){a=h;break}}}if(a!==-1)s+=e.substring(l.index,a+1),r=a+1,n.lastIndex=r;else{s+=e.substring(l.index),r=e.length;break}}return r<e.length&&(s+=e.substring(r).replace(o,t)),s},Ll=e=>_l(e,!0),Yi=e=>{if(!e)return[];let o=e.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/gi,""),t=[],n=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,s;for(;(s=n.exec(o))!==null;){let r=s[1],l=s.index+s[0].length-1,u=0,f=null,m=-1,c=-1;for(let a=l;a<o.length;a++){let d=o[a];if(f){if(d===f){let p=0;for(let h=a-1;h>=0&&o[h]==="\\";h--)p++;p%2===0&&(f=null)}}else if(d==='"'||d==="'"||d==="`")f=d;else if(d==="(")u++;else if(d===")"&&(u--,u===0)){c=a;let p=a+1;for(;p<o.length&&/\s/.test(o[p]);)p++;if(p<o.length&&o[p]==="]"){m=p;break}}}if(m!==-1){let a=o.substring(l+1,c),d=o.substring(s.index,m+1);t.push({fullMatch:d,toolName:r.trim(),args:a.trim()}),n.lastIndex=m+1}}return t},Br=(e,o={})=>e?(Bi=o,mr=new wu({apiKey:e}),mr):null,Ui=async(e,o,t,n,s="Fast")=>{let{aiProvider:r="Google",apiKey:l,mode:u}=e,f="",m=null,c;r==="OpenRouter"?c=Wi(l,o,t,n,s,u,!1):r==="DeepSeek"?c=Ri(l,o,t,n,s,u,!1):c=await mr.models.generateContentStream({model:o,contents:t,config:{systemInstruction:n,maxOutputTokens:2048,temperature:.3,thinkingConfig:{includeThoughts:!1,thinkingLevel:No.MINIMAL}}});for await(let a of c){if(a.candidates?.[0]?.content?.parts)for(let d of a.candidates[0].content.parts)d.text&&!d.thought&&(f+=d.text);a.usageMetadata&&(m=a.usageMetadata)}return{text:f,usageMetadata:m}},ku=async(e,o)=>{try{let{aiProvider:t="Google"}=o,n=xe(Eo,{});if(Object.values(n).flat().length<=2)return;let r=Object.keys(n).filter(d=>d!==e&&Array.isArray(n[d])&&n[d].length>2);if(r.length===0)return;let l=`You are a silent background process for the FluxFlow CLI Agent.
|
|
392
397
|
Your task is to summarize or merge temporary context memories from one or more past conversation sessions.
|
|
393
398
|
For each Chat ID provided, you must output a tool call to save the consolidated summary.
|
|
394
399
|
|
|
@@ -403,8 +408,8 @@ Guidelines:
|
|
|
403
408
|
|
|
404
409
|
Chats to process:
|
|
405
410
|
|
|
406
|
-
`,
|
|
407
|
-
`),S=d
|
|
411
|
+
`,u=xe(Go,{});for(let d of r){let h=n[d].map(T=>`- ${T}`).join(`
|
|
412
|
+
`),S=u[d];l+=`[Chat ID: ${d}]
|
|
408
413
|
`,S?(l+=`- Existing Summary: "${S}"
|
|
409
414
|
`,l+=`-- New Memories to integrate:
|
|
410
415
|
${h}
|
|
@@ -412,11 +417,11 @@ ${h}
|
|
|
412
417
|
`):l+=`-- Individual Memories:
|
|
413
418
|
${h}
|
|
414
419
|
|
|
415
|
-
`}let f=0,
|
|
416
|
-
`)}},
|
|
420
|
+
`}let f=0,m=5,c=!1,a="gemma-4-26b-a4b-it";for(t==="OpenRouter"&&(a="google/gemma-4-26b-a4b-it:free"),t==="DeepSeek"&&(a="deepseek-v4-flash");f<=m&&!c;){f++;try{let d=await Ui(o,a,l,null,"Fast"),p=d.text||"",h=Yi(p);if(h.length===0)throw new Error("No tool calls detected in synthesis response");for(let S of h){let T=S.toolName;["saveSummary","saveSumary","SaveSummary","SaveSumary"].includes(T)&&await ys(T,S.args,{chatId:e})}d.usageMetadata&&await Co("tokens",d.usageMetadata.totalTokenCount||0),c=!0}catch(d){if(f>=m)throw new Error(`Failed after ${m} attempts. Last error: ${d.message}`)}}}catch(t){let n=Ee.join(Io,"janitor");dt.existsSync(n)||dt.mkdirSync(n,{recursive:!0}),dt.appendFileSync(Ee.join(n,"error.log"),`[${new Date().toLocaleString()}] Past memory batch consolidation error: ${t.message}
|
|
421
|
+
`)}},Nl=async function*(e,o,t,n,s){let{profile:r,thinkingLevel:l,mode:u,janitorModel:f,chatId:m,systemSettings:c,sessionStats:a,aiProvider:d="Google",apiTier:p}=t,h=Ni(e);if(!mr&&d==="Google")throw new Error("AI not initialized");let S=c?.memory!==!1,T=o[o.length-1].text,w=Ee.join(ro,"chat-summaries.json"),I=!1,L=o.filter(b=>b.role==="user").length===1,_=T.includes("[TITLE-UPDATE]"),R=L||_,v=T.replace(/\[TITLE-UPDATE\]/g,"").trim();v=v.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),await kt.startTransaction(m,v);try{let b=[...o.slice(0,-1)],A=252e3,F=254e3;if((d==="DeepSeek"||d==="Google"&&p==="Paid")&&(A=396e3,F=4e5),c?.compression===0&&(a?.tokens||0)>A){yield{type:"status_history",content:"Context Limit Reached. Condensing session history..."};let te=St=>St.filter(gt=>(gt.role==="user"||gt.role==="agent"||gt.role==="system")&&!String(gt.id).startsWith("welcome")&&!gt.isMeta).map(gt=>`[${gt.text?.startsWith("[TOOL RESULT]")?"TOOL":gt.role==="agent"?"AGENT":"USER"}]: ${gt.text}`).join(`
|
|
417
422
|
|
|
418
|
-
`),
|
|
419
|
-
${
|
|
423
|
+
`),ve=async(St,gt)=>{let Ne="You are an expert context condenser. Summarize the provided chat history (which may include previous summaries, user instructions, agent outputs, and tool results) into a detailed, coherent, and highly technical summary of 1000 to 1500 words. Focus on preserving the architectural decisions made, current system state, task progress, and critical code details. Under no circumstances exceed MAX 2000 words.",ae=gt?`Here is the previous summary:
|
|
424
|
+
${gt}
|
|
420
425
|
|
|
421
426
|
Here is the new conversation history:
|
|
422
427
|
${St}
|
|
@@ -424,137 +429,137 @@ ${St}
|
|
|
424
429
|
Provide a new consolidated summary of the entire session.`:`Here is the conversation history:
|
|
425
430
|
${St}
|
|
426
431
|
|
|
427
|
-
Provide a consolidated summary of the entire session.`,
|
|
428
|
-
`),
|
|
429
|
-
`)
|
|
430
|
-
`;let
|
|
431
|
-
`;return}
|
|
432
|
-
`:
|
|
433
|
-
`:(
|
|
434
|
-
`,
|
|
435
|
-
`}),
|
|
432
|
+
Provide a consolidated summary of the entire session.`,jt="gemma-4-26b-a4b-it";d==="OpenRouter"&&(jt="google/gemma-4-26b-a4b-it:free"),d==="DeepSeek"&&(jt="deepseek-v4-flash");let at=0,go=!1,xt=null;for(;at<=3&&!go;){at++;try{xt=await Ui(t,jt,ae,Ne,"Fast"),go=!0}catch{if(at>3){if(d==="Google")try{return(await Ui(t,"gemini-3.1-flash-lite",ae,Ne,"Fast")).text||""}catch{return""}return""}}}return xt&&xt.text||""},st=te(b),de=xe(w,{}),he=de[m]||{summary:"",historyLength:0};typeof he=="string"&&(he={summary:he,historyLength:0});let fe=b.filter(St=>(St.role==="user"||St.role==="agent"||St.role==="system")&&!String(St.id).startsWith("welcome")&&!St.isMeta).length;he.historyLength&&fe<he.historyLength&&(he.summary="",he.historyLength=0,de[m]=he,ke(w,de));let it=he.summary||"",Bo=await ve(st,it);Bo&&(he.summary=Bo,de[m]=he,ke(w,de),b=[],I=!0)}L&&S&&(yield{type:"status",content:"Condensing past chat memories..."},await ku(m,t));let Q=xe(Eo,{}),j=xe(Go,{}),Z=Object.entries(Q).filter(([te])=>te!==m).flatMap(([te,ve])=>ve),z=[...Object.entries(j).filter(([te])=>te!==m).slice(-20).map(([te,ve])=>`[Chat Summary]: ${ve}`),...Z].map(te=>`- ${te}`).join(`
|
|
433
|
+
`),ce=xe(Nt,[]).map(te=>`- ${te.memory}`).join(`
|
|
434
|
+
`),Le=(a?.tokens||0)>=24e3,Je=Fa(z,ce,S,Le),ue=new Date().toLocaleString([],{year:"numeric",month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!0}),tt=[".git","node_modules",".gemini","dist","build",".next","out",".cache","bin","obj","vendor","venv",".idea",".gradle",".terraform","target","coverage",".vscode",".svn",".hg",".fslckout",".github",".gitlab",".circleci",".gitea",".gitee",".lerna",".changeset",".nx",".npm",".yarn",".pnpm-store",".expo",".nuxt",".svelte-kit",".docusaurus",".turbo",".vercel","bower_components",".netlify",".vuepress",".quasar",".output",".angular","jspm_packages",".parcel-cache",".rollup.cache",".rspack",".vitepress","__pycache__",".pytest_cache",".mypy_cache",".tox",".poetry","env","vhdl",".ipynb_checkpoints",".jupyter",".conda",".pdm-build",".bundle",".yardoc",".metadata","App_Data","ClientBin",".cargo",".rustc_info",".go","Godeps","_vendor",".rake_tasks","CMakefiles",".wakatime",".dart_tool",".fvm",".cocoapods","Pods",".pub-cache",".symlinks","DerivedData",".xcworkspace",".serverless",".aws",".gcloud",".azure",".kube",".vagrant",".docker","postgres-data","redis-data","mongo-data",".Spotlight-V100",".Trashes","$RECYCLE.BIN","System Volume Information",".DocumentRevisions-V100",".fseventsd","AppData","Application Data","Local","LocalLow","Roaming","$WinREAgent","$WINDOWS.~BT","$WINDOWS.~WS","scw","System32","SysWOW64",".AppleDouble",".AppleDB",".AppleDesktop","_CodeSignature",".cmio",".LSOverride",".localized",".TemporaryItems",".Trash",".Trash-0",".Trash-1000",".gvfs",".local",".config",".dbus",".fontconfig",".snap",".var",".lost+found","lost+found",".thumb",".thumbnails","EFI","boot","grub","logs","log",".nyc_output",".sonar",".ruff_cache"],Ye=te=>{try{return dt.readdirSync(te,{withFileTypes:!0})}catch{return[]}},_e=(te,ve={value:0},st=1)=>{if(ve.value>6200||st>7)return ve.value;let de=Ye(te);for(let he of de){if(ve.value>6200)break;tt.includes(he.name)||he.isDirectory()&&(ve.value++,_e(Ee.join(te,he.name),ve,st+1))}return ve.value},Me=(te,ve,st="",de=1)=>{let he=Ye(te),fe=Ee.sep;if(he.length>100)return`${st}\u2514\u2500\u2500 ${Ee.basename(te)}${fe} ...100+ files...
|
|
435
|
+
`;let it="",Bo=tt,St=he.filter(ae=>!Bo.includes(ae.name)),gt=he.filter(ae=>Bo.includes(ae.name)).map(ae=>ae.name).sort();St.sort((ae,jt)=>ae.isDirectory()&&!jt.isDirectory()?-1:!ae.isDirectory()&&jt.isDirectory()?1:ae.name.localeCompare(jt.name));let Ne=[...St.map(ae=>({name:ae.name,isDir:ae.isDirectory()})),...gt.map(ae=>({name:ae,isDir:!0,isCollapsed:!0}))];return Ne.forEach((ae,jt)=>{let at=jt===Ne.length-1,go=Ee.join(te,ae.name),xt=at?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",pn=st+(at?" ":"\u2502 ");if(ae.isCollapsed){it+=`${st}${xt}${ae.name}${fe}...
|
|
436
|
+
`;return}ae.isDir?de>ve?it+=`${st}${xt}${ae.name}${fe} ...depth exceeded...
|
|
437
|
+
`:Ye(go).length>80?it+=`${st}${xt}${ae.name}${fe} ...80+ files...
|
|
438
|
+
`:(it+=`${st}${xt}${ae.name}${fe}
|
|
439
|
+
`,it+=Me(go,ve,pn,de+1)):it+=`${st}${xt}${ae.name}
|
|
440
|
+
`}),it};yield{type:"status",content:"Gathering Context..."},await new Promise(te=>setTimeout(te,500));let je=_e(process.cwd()),ye=12;je>4096?ye=1:je>3072?ye=2:je>2048?ye=3:je>1024?ye=4:je>512?ye=6:je>256?ye=7:je>128?ye=8:je>64?ye=9:je>32&&(ye=10);let ft=xe(Vr,{}),pt=ft[m],lo=pt?pt!==process.cwd():!1;ft[m]=process.cwd(),ke(Vr,ft);let Wt=xe(w,{}),be=Wt[m]||{summary:"",historyLength:0};typeof be=="string"&&(be={summary:be,historyLength:0});let rt=o.filter(te=>(te.role==="user"||te.role==="agent"||te.role==="system")&&!String(te.id).startsWith("welcome")&&!te.isMeta).length;be.historyLength&&rt<be.historyLength&&(be.summary="",be.historyLength=0,Wt[m]=be,ke(w,Wt));let Ao=typeof be=="object"?be.summary||"":be||"",co=Ao?`
|
|
436
441
|
**CONTEXT SUMMARY OF PREVIOUS TURNS (PRIORITY: HIGH)**
|
|
437
|
-
${
|
|
438
|
-
`+
|
|
439
|
-
`,
|
|
440
|
-
Cursor Line: ${
|
|
441
|
-
`,
|
|
442
|
-
`),
|
|
443
|
-
`);
|
|
442
|
+
${Ao}`:"",Vt=process.cwd()+`
|
|
443
|
+
`+Me(process.cwd(),ye),H=await Nr(),Ge="";if(Vo())if(Ge=`[IDE CONTEXT]
|
|
444
|
+
`,H.file_focused!=="none"){let te=Ee.relative(process.cwd(),H.file_focused),ve=(H.opened_editors||[]).map(de=>{let he=Ee.relative(process.cwd(),de);return he.startsWith("..")?`[External] ${Ee.basename(de)}`:he});if(Ge+=`Focused File: ${te}
|
|
445
|
+
Cursor Line: ${H.cursor_line}
|
|
446
|
+
`,H.selected&&(Ge+=`Current Selection: "${H.selected}"
|
|
447
|
+
`),H.manual_edits){let de=H.manual_edits,he=4*512,fe=50,it=de.split(`
|
|
448
|
+
`);it.length>fe&&(de=it.slice(0,fe).join(`
|
|
444
449
|
`)+`
|
|
445
|
-
... (${
|
|
446
|
-
... (Character limit reached, truncated)`),
|
|
447
|
-
${
|
|
448
|
-
`}
|
|
450
|
+
... (${it.length-fe} more lines truncated)`),de.length>he&&(de=de.substring(0,he)+`
|
|
451
|
+
... (Character limit reached, truncated)`),Ge+=`Recent Manual Edits:
|
|
452
|
+
${de}
|
|
453
|
+
`}ve.length>0&&(Ge+=`All Opened Editors: ${ve.join(", ")}`),H.diagnostics&&(Ge+=`
|
|
449
454
|
**ACTIVE FILE ERRORS**:
|
|
450
|
-
${
|
|
451
|
-
`),(
|
|
455
|
+
${H.diagnostics}
|
|
456
|
+
`),(v.toLowerCase().includes("lint")||v.toLowerCase().includes("warning"))&&H.warnings&&(Ge+=`
|
|
452
457
|
**LINT WARNINGS**:
|
|
453
|
-
${
|
|
454
|
-
`)}else
|
|
455
|
-
CWD: ${process.cwd()}${
|
|
458
|
+
${H.warnings}
|
|
459
|
+
`)}else Ge+="No file currently focused.";let Rr=`[SYSTEM METADATA (PRIORITY: DYNAMIC), Chat Context >> Metadata] Time: ${ue}
|
|
460
|
+
CWD: ${process.cwd()}${lo?` (WARNING: CWD Mismatch! Previous Path: ${pt})`:""}
|
|
456
461
|
**DIRECTORY STRUCTURE**
|
|
457
|
-
${
|
|
458
|
-
${l!="Fast"&&
|
|
459
|
-
`:""}`:""}[USER] ${
|
|
460
|
-
|
|
461
|
-
[STEERING HINT]: ${
|
|
462
|
-
`:""}`:""}[STEERING HINT]: ${
|
|
463
|
-
[SYSTEM] Tool result received. Analyze output and proceed with your turn${l!="Fast"&&
|
|
464
|
-
[SYSTEM] WARNING, Turn Limit Impending: Step ${
|
|
465
|
-
`).length;
|
|
466
|
-
${
|
|
467
|
-
${
|
|
468
|
-
${
|
|
469
|
-
`)}`,
|
|
470
|
-
${
|
|
471
|
-
${
|
|
472
|
-
${
|
|
462
|
+
${Vt}${co}${Je}${Ge}
|
|
463
|
+
${l!="Fast"&&d==="Google"?`${e.toLowerCase().startsWith("gemma")?`[SYSTEM] **STRICTLY FOLLOW THINKING POLICY AS CRITICAL PRIORITY. DO NOT START A RESPONSE WITHOUT <think> ... </think>**
|
|
464
|
+
`:""}`:""}[USER] ${v.replace(/\s*\[Prompted on:.*?\]/g,"").trim()}`.trim();b.push({role:"user",text:Rr});let zt=null,qn=u==="Flux"?70:7,ht=16;yield{type:"status",content:"Connecting..."},dr=!1;let Oo=[],Yt=!1;b.forEach(te=>{te.text&&te.role==="agent"&&(te.text=te.text.replace(/(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])/gi,"").trim())});for(let te=0;te<=qn;te++){if(Yt=!1,c?.compression===0&&(a?.tokens||0)>F&&(b=Wa(b,6)),te>0&&(yield{type:"status",content:"Processed. Reconnecting..."}),dr){yield{type:"status",content:"Termination Signal Received."},await new Promise(se=>setTimeout(se,1500));break}if(n){let se=await n();se&&(b.length>0&&b[b.length-1].role==="user"?b[b.length-1].text+=`
|
|
465
|
+
|
|
466
|
+
[STEERING HINT]: ${se}`:b.push({role:"user",text:`${l!="Fast"&&d==="Google"?`${e.toLowerCase().startsWith("gemma")?`[SYSTEM] **STRICTLY FOLLOW THINKING POLICY AS CRITICAL PRIORITY. DO NOT START A RESPONSE WITHOUT <think> ... </think>**
|
|
467
|
+
`:""}`:""}[STEERING HINT]: ${se}`}),yield{type:"status",content:"Steering Hint Injected."})}let ve,st=!1,de=1,he=1,fe="",it=null,Bo=null,St=null,gt=0,Ne=[],ae=0,jt=!1,at=!1,go=!1,xt=!1,pn=!0,ot="",lt="",Gt=!1,Jt=e,en="";for(;de<=ht&&he<=ht&&!st&&!dr;){let se=!1;try{fe="",pn&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},yield{type:"spinner",content:!0},pn=!1,he===1&&(ot=""));let Be=b.filter(Se=>(Se.role==="user"||Se.role==="agent"||Se.role==="system")&&!String(Se.id).startsWith("welcome")&&!Se.isMeta&&!Se.isTerminalRecord&&!(Se.text&&Se.text.startsWith("[TERMINAL_RECORD]"))).map((Se,Qe,yo)=>{let Re=Se.text||"";Se.role==="agent"&&(Re=Re.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim());let Ft=[{text:Re}];return Se.binaryPart&&Ni(Jt)&&yo.slice(Qe+1).filter(hn=>hn.role==="user"&&!hn.text?.startsWith("[TOOL RESULT]")).length<=2&&Ft.push(Se.binaryPart),{role:Se.role==="user"||Se.role==="system"?"user":"model",parts:Ft}});if(!await ai("agent",t))throw new Error("Error: Quota Exausted for Agent");Jt=e,d==="DeepSeek"&&l==="Fast"&&(Jt="deepseek-chat"),de===ht-1?(Jt=d==="DeepSeek"?"deepseek-v4-flash":"gemini-3-flash-preview",yield{type:"model_update",content:"Trying with fallback model"}):de===ht?(Jt=d==="DeepSeek"?"deepseek-v4-pro":"gemini-3.5-flash",yield{type:"model_update",content:"Trying with fallback model"}):de>12&&de<ht-2&&t.apiKey!=="custom"?(Jt="gemma-4-31b-it",yield{type:"model_update",content:"Trying with fallback Gemma Model"}):de>0&&(yield{type:"model_update",content:null}),en=$a(r,(Jt||"gemma").toLowerCase().startsWith("gemma")?l:"GEM",u,c,S,L,d,h);let Ue=e&&e.toLowerCase().startsWith("gemma"),ct=Be[Be.length-1];if(Ue){let Se=`
|
|
468
|
+
[SYSTEM] Tool result received. Analyze output and proceed with your turn${l!="Fast"&&d==="Google"?". **STRICTLY MAINTAIN THINKING POLICY. DO NOT START A RESPONSE WITHOUT <think> ... </think>}**":""}`;ct&&ct.role==="user"&&ct.parts?.[0]?.text?.startsWith("[TOOL RESULT]")&&(ct.parts[0].text+=Se)}if(Ue){let Se=Math.floor(qn*(u==="Flux"?.98:.7)),Qe=te+1;Qe>=Se&&ct&&ct.parts?.[0]&&(ct.parts[0].text+=`
|
|
469
|
+
[SYSTEM] WARNING, Turn Limit Impending: Step ${Qe}/${qn}. Wrap up quickly/prompt user to continue & use [[END]] or [turn:finish] quickly.`)}let Et=Be;d==="OpenRouter"?ve=Wi(t.apiKey,Jt,Et,en,l,u,h):d==="DeepSeek"?ve=Ri(t.apiKey,Jt,Et,en,l,u,h):ve=await mr.models.generateContentStream({model:Jt||"gemma-4-31b-it",contents:Et,config:{systemInstruction:en,temperature:u==="Flux"?1:1.4,maxOutputTokens:32768,mediaResolution:"MEDIA_RESOLUTION_MEDIUM",safetySettings:[{category:Dn.HARM_CATEGORY_HARASSMENT,threshold:On.BLOCK_NONE},{category:Dn.HARM_CATEGORY_HATE_SPEECH,threshold:On.BLOCK_NONE},{category:Dn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:On.BLOCK_NONE},{category:Dn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:On.BLOCK_NONE}],thinkingConfig:(()=>{let Se=(Jt||"").toLowerCase(),Qe=Se.includes("gemma-4")||Se.startsWith("gemma"),yo=Se.includes("gemini-3");if(Qe||yo)return Qe?{includeThoughts:!1,thinkingLevel:No.MINIMAL}:{includeThoughts:!0,thinkingLevel:{Fast:Se.includes("pro")?No.LOW:No.MINIMAL,Low:No.LOW,Medium:No.MEDIUM,Standard:No.MEDIUM,High:No.HIGH,xHigh:No.HIGH}[l]||No.MEDIUM};{let Re={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[l]||2048;return Re===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:Re}}})()}}),fe="",it=null,St=null,Ne=[],ae=0,yield{type:"model_update",content:null},yield{type:"status",content:"Working..."},lt="",Gt=ot.length>0;let nt="",Qt=Date.now();for await(let Se of ve){if(dr){yield{type:"status",content:"Termination Signal Received."},await new Promise(Re=>setTimeout(Re,1500));break}let Qe="",yo=Se.candidates?.[0]?.content?.parts;if(yo&&yo.length>0)for(let Re of yo)Re.thought?Re.text&&(se||(Qe+="<think>",se=!0),Qe+=Re.text):Re.text&&(se&&(Qe+="</think>",se=!1),Qe+=Re.text);else{let Re=Se.text||"";Re&&se&&(Qe+="</think>",se=!1),Qe+=Re}if(Qe){if(Gt){if(lt+=Qe,lt.length>=30){let J=0,He=Math.min(ot.length,lt.length);for(let K=He;K>0;K--)if(ot.endsWith(lt.substring(0,K))){J=K;break}let yt=lt.substring(J);if(yt){let qe=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(ot)?yt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):yt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");qe&&(fe+=qe,d==="Google"?nt+=qe:yield{type:"text",content:qe})}Gt=!1,lt=""}continue}else fe+=Qe,d==="Google"?nt+=Qe:yield{type:"text",content:Qe};let Re=Ll(fe),Ft=bu(fe);if(Ft.inside){St||(St=Date.now());let J=Ft.toolName,yt={Ask:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image"}[J]||J,K=Ft.args||"",qe=null;if(["write_file","update_file","view_file","read_folder","write_pdf","write_docx","search_keyword","generate_image","file_map"].includes(yt)){let Fe=ne(K),Yo=Fe.path||Fe.targetFile||Fe.TargetFile||Fe.directory,on=Fe.keyword;if(on)qe=on.replace(/["']/g,"");else if(Yo)qe=Ee.basename(Yo.replace(/["']/g,"").replace(/\\/g,"/"));else{let Bn=K.match(/(?:path|targetFile|TargetFile|directory|keyword)\s*=\s*\\?["']?([^\\"' \),]+)/);if(Bn){let bt=Bn[1].replace(/["']/g,"");qe=yt==="search_keyword"||yt==="file_map"?bt:Ee.basename(bt.replace(/\\/g,"/"))}}}let eo=`${Dl[yt]||yt}${qe?` (${qe})`:""}`;if((yt!==it||qe!==Bo)&&(it=yt,Bo=qe,yield{type:"status",content:`${eo}...`},process.stdout.isTTY)){let Yo={web_search:"Searching",web_scrape:"Reading",view_file:"Reading",read_folder:"Reading",list_files:"Reading",write_file:"Writing",update_file:"Editing",write_pdf:"Creating",write_docx:"Creating",search_keyword:"Searching",exec_command:"Executing",ask:"User Input",memory:"Updating Memory",generate_image:"Generating"}[yt]||"Working";process.stdout.write(`\x1B]0;${Yo}...\x07`)}}let Uo=_l(fe,!1),yr=(Uo.match(/(?:<think>|\[think\])([\s\S]*?)(?:<\/think>|\[\/think\]|$)/gi)||[]).join("").trim(),tn=yr.split(/[.!?]\s+/),Yr=new Set(tn),Ro=tn.length>10?(tn.length-Yr.size)/tn.length:0,zn=yr.split(/\s+/).filter(J=>J.length>0).length,Jn=.4,wr=.6,Tr=!1;if((Jt||"").toLowerCase().startsWith("gemma")){let He={low:256,medium:768,high:2048,max:4096,xhigh:4096}[l?.toLowerCase()]||2500;Tr=zn>He}if(Ro>Jn||Tr){yield{type:"status",content:`${Ro>Jn?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},at=!0,await new Promise(He=>setTimeout(He,3e3));break}let Qn=Re.trim().split(/[.!?]\s+/),gn=new Set(Qn);if((Qn.length>10?(Qn.length-gn.size)/Qn.length:0)>wr){yield{type:"status",content:"Response Loop Detected. Re-centering..."},at=!1,xt=!0,await new Promise(J=>setTimeout(J,3e3));break}let Wo=Uo.toLowerCase().split(/\s+/).filter(J=>J.length>0),xn=!1;if(Wo.length>5)for(let J=1;J<=15;J++){let He=Math.max(3,Math.ceil(8/J));if(Wo.length<J*He)continue;let yt=!0,qe=Wo.slice(Wo.length-J).join(" ");for(let eo=1;eo<He;eo++)if(Wo.slice(Wo.length-J*(eo+1),Wo.length-J*eo).join(" ")!==qe){yt=!1;break}if(yt){xn=!0;break}}if(!xn){let J=Uo.toLowerCase().replace(/[^a-z0-9]/gi,"");if(J.length>=10)for(let He=1;He<=10;He++){let yt=Math.max(4,Math.ceil(12/He));if(J.length<He*yt)continue;let K=J.substring(J.length-He),qe=!0;for(let eo=1;eo<yt;eo++)if(J.substring(J.length-He*(eo+1),J.length-He*eo)!==K){qe=!1;break}if(qe){xn=!0;break}}}if(xn){yield{type:"status",content:"Stuttering Detected. Re-centering..."},at=!1,go=!0,await new Promise(J=>setTimeout(J,3e3));break}let Zn=fe.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/gi,""),Gr=Yi(Zn);for(;Gr.length>ae;){let J=Gr[ae],He=Date.now(),K={Ask:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image"}[J.toolName]||J.toolName,qe=Dl[K]||J.toolName,eo=Eu(K,J.args);yield{type:"status",content:`${qe}${eo?` (${eo})`:""}...`};let Fe="";if(K==="web_search"){let{query:ie,limit:Ae=10}=ne(J.args);Fe=`\u{1F50D} Searched: ${ie}`}else if(K==="web_scrape")Fe=`\u{1F4D6} Visited: ${ne(J.args).url||"..."}`;else if(K==="view_file"){let{path:ie,StartLine:Ae,EndLine:Xe,start_line:Ve,end_line:wt,startLine:Ce,endLine:wo}=ne(J.args),x=Ae||Ve||Ce,g=Xe||wt||wo,O=parseInt(x)||1,N=parseInt(g)||(x?O+800:800),M="...",$=N;try{let G=Ee.resolve(process.cwd(),ie);if(dt.existsSync(G)){let $e=dt.readFileSync(G,"utf8").split(`
|
|
470
|
+
`).length;M=$e,$=Math.min(N,$e)}}catch{}let U=ie.toLowerCase(),E=U.endsWith(".pdf"),D=U.endsWith(".docx")||U.endsWith(".doc")||U.endsWith(".ppt")||U.endsWith(".pptx")||U.endsWith(".xls")||U.endsWith(".xlsx"),P=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(U);E||D?Fe=`\u{1F4C4} Viewed: ${ie}`:P?Fe=`\u{1F4F8} Viewed: ${ie}`:Fe=`\u{1F4C4} Read: ${ie} \u2192 Lines ${O} - ${$} of ${M}`}else if(K==="list_files"||K==="read_folder"){let ie=K==="list_files"?"List":"Viewed",Ae=ne(J.args).path;Fe=`\u{1F4C2} ${ie}: ${Ae==="."?"./":Ae}`}else if(K==="write_file"||K==="update_file")Fe=`\u{1F4BE} ${K==="write_file"?"Created":"Edited"}: ${ne(J.args).path||"..."}`;else if(K==="write_pdf")Fe=`\u{1F4D1} Created: ${ne(J.args).path||"..."}`;else if(K==="write_docx")Fe=`\u{1F4DD} Created: ${ne(J.args).path||"..."}`;else if(K==="file_map")Fe=`\u{1F4CB} Get Map: ${ne(J.args).path||"..."}`;else if(K==="search_keyword")Fe="";else if(K==="generate_image"){let{path:ie,outputPath:Ae,output:Xe}=ne(J.args);Fe=`\u{1F3A8} Generated: ${ie||Ae||Xe||"generated_image.png"}`}else K==="exec_command"||K==="ask"?Fe="":Fe=`Executed: ${J.toolName}`;if(K==="exec_command"){let{command:ie}=ne(J.args);if(ie&&t.systemSettings&&t.systemSettings.allowExternalAccess===!1){let Ae=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],Xe=Ee.resolve(process.cwd()).substring(0,3).toLowerCase();if(Ae.some(wt=>{if(wt.source==="[a-zA-Z]:[\\\\\\/]"){let Ce=ie.match(/[a-zA-Z]:[\\\/]/i);return Ce&&Ce[0].toLowerCase()!==Xe}return wt.test(ie)})){let wt='Access Denied. Terminal is prohibited from accessing system drives (C://) or external directories while "External Workspace Access" is disabled.';t.onExecStart&&t.onExecStart(ie||"Unknown"),yield{type:"exec_start"},await new Promise(Ce=>setTimeout(Ce,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${wt}`),await new Promise(Ce=>setTimeout(Ce,50)),t.onExecEnd&&t.onExecEnd(),Ne.push({role:"user",text:`[TOOL RESULT]: ERROR: ${wt}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${wt}`},ae++;continue}}t.onExecStart&&t.onExecStart(ie||"Unknown"),yield{type:"exec_start"}}let Yo=ne(J.args),on=Yo.path||Yo.targetPath||null;if(on){let ie=t.systemSettings&&t.systemSettings.allowExternalAccess===!1,Ae=Ee.resolve(on),Xe=Ee.resolve(process.cwd());if(ie&&!Ae.startsWith(Xe)){let Ve="Access Denied. You are not allowed to access files outside the current workspace.";if(K==="write_file"||K==="update_file"){let Ce=`\u{1F4BE} ${K==="write_file"?"Write Canceled":"Edit Canceled"}: ${Yo.path||"..."}`,wo=Math.min(Ce.length+4,115),x=`\u256D${"\u2500".repeat(wo)}\u256E`,g=`\u2502 ${Ce.padEnd(wo-2).substring(0,wo-2)} \u2502`,O=`\u2570${"\u2500".repeat(wo)}\u256F`;yield{type:"visual_feedback",content:`${x}
|
|
471
|
+
${g}
|
|
472
|
+
${O}`}}Ne.push({role:"user",text:`[TOOL RESULT]: ERROR: ${Ve}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${Ve}`},ae++;continue}}if(t.onToolApproval&&(K==="write_file"||K==="update_file"||K==="exec_command")){let Ae=t.systemSettings||{},Xe=Ae.autoExec,Ve=null,wt=!1,Ce=!1,wo=!1;if(K==="exec_command"){let{command:E}=ne(J.args),D=(E||"").trim(),P=($e,ge)=>{if(!ge)return!1;let Oe=ge.split(",").map(Ke=>Ke.trim().toLowerCase()).filter(Boolean),Pe=$e.toLowerCase();return Oe.some(Ke=>Pe.startsWith(Ke))},G=P(D,Ae.alwaysAskCommands),q=P(D,Ae.autoApproveCommands);Ce=P(D,Ae.autoDisallowCommands),G?wt=!0:(q||Ae.autoApproveGit&&/^git\s+commit\b/i.test(D))&&(Ve="allow"),!wt&&!Ve&&(Ae.networkAccess===!1&&/\b(curl|wget|npm|yarn|pnpm|pip|pip3|ssh|docker|git\s+(clone|push|pull|fetch))\b/i.test(D)&&(Ve="deny",wo=!0),!Ve&&Ce&&(Ve="deny")),!wt&&!Ve&&Xe&&(Ve="allow")}else Xe&&(Ve="allow");let x=Ve,g="";Ve==="deny"&&(wo?g="network":Ce?g="settings":g="prohibited");let O=!1,N="",M=[],$=0,U=!1;if(!x){if(K==="write_file"||K==="update_file")try{let P=ne(J.args),{path:G}=P;if(G){let q=Ee.resolve(process.cwd(),G),$e=to=>to?to.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,Pt=>Pt.toUpperCase()):"",ge=$e(q),Oe="",Pe=!1,Ke=await Nr(),yn=$e(Ke?.file_focused);if(Ke&&yn===ge&&Ke.full_content?(Oe=Ke.full_content,Pe=!0):dt.existsSync(q)&&(Oe=dt.readFileSync(q,"utf8"),Pe=!0),N=Oe,await kt.recordFileChange(q,Oe),Pe){let to=Oe;if(K==="write_file")to=P.content||P.newContent||"";else{let{patchPairs:Pt,error:jo}=rs(P);if(jo){let Y=`[TOOL RESULT]: ERROR: ${jo}`;Ne.push({role:"user",text:Y}),await qo("toolFailure"),t.onToolResult&&t.onToolResult("failure",K),yield{type:"tool_result",content:Y,toolName:K},ae++;continue}$=Pt.length;let To=ss(Oe,Pt);to=To.content,M=To.results;let Xr=M.filter(Y=>Y.success),er=M.filter(Y=>!Y.success);if(Xr.length===0){let Y=`[TOOL RESULT]: ERROR: Failed to apply patches to [${Ee.basename(q)}].
|
|
473
|
+
${er.map(we=>` \u2022 ${we.error}`).join(`
|
|
474
|
+
`)}`,le=`\u{1F4BE} Edited: ${Ee.basename(q)}`.toUpperCase(),me=Math.min(le.length+4,115),De=`\u256D${"\u2500".repeat(me)}\u256E`,_t=`\u2502 ${le.padEnd(me-2).substring(0,me-2)} \u2502`,pe=`\u2570${"\u2500".repeat(me)}\u256F`;yield{type:"visual_feedback",content:`${De}
|
|
475
|
+
${_t}
|
|
476
|
+
${pe}`},Ne.push({role:"user",text:Y}),await qo("toolFailure"),t.onToolResult&&t.onToolResult("failure",K),yield{type:"tool_result",content:Y,toolName:K},ae++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${Ee.basename(q)}...`},Pi(q,Oe,to),O=!0,await new Promise(Pt=>setTimeout(Pt,50))}else if(K==="write_file"){let to=P.content||P.newContent||"";dt.existsSync(q)||(U=!0,dt.mkdirSync(Ee.dirname(q),{recursive:!0}),dt.writeFileSync(q,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${Ee.basename(q)}...`},Pi(q,"",to),O=!0,await new Promise(Pt=>setTimeout(Pt,50))}}}catch(P){console.error("Simulation/Diff Error:",P)}let E=null;$i(P=>{E=P});let D=t.onToolApproval;if(x=await new Promise(async P=>{let G=setInterval(()=>{E&&(Bi.onIDEApproval&&Bi.onIDEApproval(E),clearInterval(G),P(E))},100);try{let q=await D(K,J.args);clearInterval(G),P(q)}catch{clearInterval(G),P("deny")}}),$i(null),K==="write_file"||K==="update_file"){let{path:P}=ne(J.args);if(P){let G=Ee.resolve(process.cwd(),P);if(Ol(G,x),x==="deny"&&U&&dt.existsSync(G))try{dt.unlinkSync(G)}catch{}}}x==="deny"&&(g="user")}if(x==="allow"&&O&&Vo()){let{path:E}=ne(J.args),D=Ee.resolve(process.cwd(),E),P=await Nr(),G="";P&&P.file_focused===D&&P.full_content?G=P.full_content:dt.existsSync(D)&&(G=dt.readFileSync(D,"utf8"));let q=G.split(/\r?\n/),$e=q.length,ge=Buffer.byteLength(G,"utf8"),Oe="";N&&(Oe=`Old File contents:
|
|
477
|
+
${N.split(/\r?\n/).map((me,De)=>`${De+1} | ${me}`).join(`
|
|
473
478
|
`)}
|
|
474
479
|
|
|
475
|
-
`);let
|
|
476
|
-
`);else{let
|
|
477
|
-
`),
|
|
478
|
-
`);
|
|
480
|
+
`);let Pe="";if($e<=200)Pe=q.join(`
|
|
481
|
+
`);else{let le=q.slice(0,100).join(`
|
|
482
|
+
`),me=q.slice(-100).join(`
|
|
483
|
+
`);Pe=`${le}
|
|
479
484
|
|
|
480
|
-
... [${
|
|
485
|
+
... [${$e-200} lines truncated for history stability] ...
|
|
481
486
|
|
|
482
|
-
${
|
|
487
|
+
${me}`}let Ke="";if(K==="update_file"){let le=is(N,G,M,12);Ke=`SUCCESS: File [${E}] updated via IDE Companion (May have user edits). [${M.length}/${$}] blocks applied.
|
|
483
488
|
|
|
484
|
-
${
|
|
485
|
-
${
|
|
489
|
+
${le}`}else{let le=G.split(/\r?\n/),me=le.length,De=Buffer.byteLength(G,"utf8"),_t="";N&&(_t=`Old File contents:
|
|
490
|
+
${N.split(/\r?\n/).map((Ze,Ct)=>`${Ct+1} | ${Ze}`).join(`
|
|
486
491
|
`)}
|
|
487
492
|
|
|
488
|
-
`);let
|
|
489
|
-
`);else{let
|
|
490
|
-
`),
|
|
491
|
-
`);
|
|
493
|
+
`);let pe="";if(me<=200)pe=le.join(`
|
|
494
|
+
`);else{let we=le.slice(0,100).join(`
|
|
495
|
+
`),Ze=le.slice(-100).join(`
|
|
496
|
+
`);pe=`${we}
|
|
492
497
|
|
|
493
|
-
... [${
|
|
498
|
+
... [${me-200} lines truncated] ...
|
|
494
499
|
|
|
495
|
-
${
|
|
500
|
+
${Ze}`}Ke=`SUCCESS: File [${E}] saved via IDE Companion (May have user edits).
|
|
496
501
|
|
|
497
|
-
- Stats: [${
|
|
498
|
-
${
|
|
499
|
-
${
|
|
502
|
+
- Stats: [${me} lines, ${(De/1024).toFixed(1)} KB]
|
|
503
|
+
${_t}- Content Preview:
|
|
504
|
+
${pe}
|
|
500
505
|
|
|
501
|
-
Check if Starting and Ending matches your write.`}let
|
|
502
|
-
${
|
|
503
|
-
${
|
|
504
|
-
${
|
|
505
|
-
${
|
|
506
|
-
${
|
|
507
|
-
${
|
|
508
|
-
${
|
|
509
|
-
${
|
|
510
|
-
`)}`;
|
|
506
|
+
Check if Starting and Ending matches your write.`}let to=`\u{1F4BE} ${K==="write_file"?"Written":"Edited"}: ${E||"..."}`,Pt=Math.min(to.length+4,115),jo=`\u256D${"\u2500".repeat(Pt)}\u256E`,To=`\u2502 ${to.padEnd(Pt-2).substring(0,Pt-2)} \u2502`,Xr=`\u2570${"\u2500".repeat(Pt)}\u256F`;yield{type:"visual_feedback",content:`${jo}
|
|
507
|
+
${To}
|
|
508
|
+
${Xr}`};let er=Date.now();gt=er,yield{type:"tool_time",content:er-He};let Y=`[TOOL RESULT]: ${Ke}`;Ne.push({role:"user",text:Y}),jt=!0,await qo("toolSuccess"),t.onToolResult&&t.onToolResult("success",K),yield{type:"tool_result",content:Ke,aiContent:Y,toolName:K},ae++;continue}if(x==="deny"){let E=`Permission Denied: Prohibited ${K==="exec_command"?"Command":"file edit"}.`;if(g==="user"?E="Permission Denied by User":g==="settings"?E="Permission Denied by User Policy":g==="network"?E="Permission Denied: Sandbox Network Access Disabled by User Policy.":g==="prohibited"&&K==="exec_command"&&(E="Permission Denied: Prohibited Command"),K==="write_file"||K==="update_file"){let P=`\u{1F4BE} ${K==="write_file"?"WRITE DENIED":"UPDATE DENIED"}: ${ne(J.args).path||"..."}`.toUpperCase(),G=Math.min(P.length+4,115),q=`\u256D${"\u2500".repeat(G)}\u256E`,$e=`\u2502 ${P.padEnd(G-2).substring(0,G-2)} \u2502`,ge=`\u2570${"\u2500".repeat(G)}\u256F`;yield{type:"visual_feedback",content:`${q}
|
|
509
|
+
${$e}
|
|
510
|
+
${ge}`}}K==="exec_command"&&(await new Promise(D=>setTimeout(D,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${E}`),await new Promise(D=>setTimeout(D,50)),t.onExecEnd&&t.onExecEnd()),Ne.push({role:"user",text:`[TOOL RESULT]: DENIED: ${E}`}),yield{type:"tool_result",content:`[TOOL RESULT]: DENIED: ${E}`},await qo("toolDenied"),t.onToolResult&&t.onToolResult("denied",K),ae++;continue}}if(Fe){let ie=Math.min(Fe.length+4,115),Ae=`\u256D${"\u2500".repeat(ie)}\u256E`,Xe=`\u2502 ${Fe.padEnd(ie-2).substring(0,ie-2)} \u2502`,Ve=`\u2570${"\u2500".repeat(ie)}\u256F`;yield{type:"visual_feedback",content:`${Ae}
|
|
511
|
+
${Xe}
|
|
512
|
+
${Ve}`}}if(gt>0){let ie=Date.now()-gt;ie<1e3&&await new Promise(Ae=>setTimeout(Ae,1e3-ie))}yield{type:"spinner",content:!1};let Bn={chatId:m,history:o,onChunk:ie=>t.onExecChunk?t.onExecChunk(ie):null,onAskUser:t.onAskUser,systemSettings:t.systemSettings,mode:u,isMultiModal:Ni(Jt)};if(K==="write_file"||K==="update_file")try{let{path:ie}=ne(J.args);if(ie){let Ae=Ee.resolve(process.cwd(),ie),Xe=await Nr();Xe&&Xe.file_focused===Ae&&Xe.full_content&&(Bn.forcedContent=Xe.full_content)}}catch{}let bt=await ys(K,J.args,Bn);if(yield{type:"spinner",content:!0},K==="write_file"&&bt.startsWith("SUCCESS")){let{path:ie}=ne(J.args);if(ie){let Ae=Ee.resolve(process.cwd(),ie);Al(Ae)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let $t=Date.now();gt=$t,yield{type:"tool_time",content:$t-He},St=$t;let W=null;if(typeof bt=="object"&&bt.binaryPart&&(W=bt.binaryPart,bt=bt.text),K==="search_keyword"){let{keyword:ie,file:Ae}=ne(J.args),Xe=0;if(bt){let g=bt.match(/Found (\d+) matches/i);g&&(Xe=parseInt(g[1]))}let Ve=`\u{1F50E} Searched: "${ie}" in ${Ae?`"${Ae}"`:"./"} \u2192 ${Xe} Match${Xe===1?"":"es"}`,wt=Math.min(Ve.length+4,115),Ce=`\u256D${"\u2500".repeat(wt)}\u256E`,wo=`\u2502 ${Ve.padEnd(wt-2).substring(0,wt-2)} \u2502`,x=`\u2570${"\u2500".repeat(wt)}\u256F`;yield{type:"visual_feedback",content:`${Ce}
|
|
513
|
+
${wo}
|
|
514
|
+
${x}`}}K==="exec_command"&&t.onExecEnd&&(await new Promise(ie=>setTimeout(ie,800)),t.onExecEnd());let Do=bt&&bt.startsWith("DENIED:");bt&&!bt.startsWith("ERROR:")&&!Do?(await qo("toolSuccess"),t.onToolResult&&t.onToolResult("success",K)):Do||(await qo("toolFailure"),t.onToolResult&&t.onToolResult("failure",K));let ee=`[TOOL RESULT]: ${(bt||"").toString().split(/\r?\n/).filter(ie=>!ie.includes("[UI_CONTEXT]")).join(`
|
|
515
|
+
`)}`;Ne.push({role:"user",text:ee,binaryPart:W}),jt=!0;let Hr=`[TOOL RESULT]: ${bt||""}`;(K==="view_file"||K==="web_scrape")&&(Hr=`[TOOL RESULT]: ${Fe} (Context Locked for UI Clarity)`),yield{type:"tool_result",content:Hr,aiContent:ee,binaryPart:W,toolName:K},K==="memory"&&bt.includes("SUCCESS")&&(yield{type:"memory_updated"}),ae++}d==="Google"&&nt&&Date.now()-Qt>=150&&(yield{type:"text",content:nt},nt="",Qt=Date.now())}Se.usageMetadata&&(zt=Se.usageMetadata),zt&&(yield{type:"liveTokens",content:zt.totalTokenCount})}if(se&&(se=!1,Gt?lt+="</think>":(fe+="</think>",d==="Google"?nt+="</think>":yield{type:"text",content:"</think>"})),Gt&<.length>0){let Se=0,Qe=Math.min(ot.length,lt.length);for(let Re=Qe;Re>0;Re--)if(ot.endsWith(lt.substring(0,Re))){Se=Re;break}let yo=lt.substring(Se);if(yo){let Ft=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(ot)?yo.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):yo.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");Ft&&(fe+=Ft,d==="Google"?nt+=Ft:yield{type:"text",content:Ft})}Gt=!1,lt=""}if(d==="Google"&&nt&&(yield{type:"text",content:nt},nt=""),dr)break;let xo=(fe||"").trim(),Zt=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(xo.toLowerCase())||/\[\[END\]\]/i.test(xo.toLowerCase()),Lt=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(xo.toLowerCase()),uo=Ne.length>0||it!==null,ko=xo.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/gi,"").trim(),Nn=/(\p{Emoji_Presentation}|\p{Extended_Pictographic})$/u.test(ko),Wr=/([.!?"'*_`|\]\)”’~~]+|\s|`{3}|[\u200B-\u200D\uFEFF])$/u.test(ko.trim()),Ls=/[.!?}"'`’“”]$|```$/s.test(ko)||Wr||Nn;if(!Zt&&!Lt&&!uo&&xo.length>0&&!Ls&&!at&&!go&&!xt)throw new Error("Silent stream cutoff (500): Model stream closed cleanly but cut off mid-sentence without signals.");st=!0,await qo("agent")}catch(Be){if(String(Be).includes("Incomplete JSON segment at the end")){se&&(se=!1,Gt?lt+="</think>":(fe+="</think>",yield{type:"text",content:"</think>"})),st=!0,await qo("agent");break}if(se&&(se=!1,Gt?lt+="</think>":fe+="</think>"),Gt&<.length>0){let Zt=0,Lt=Math.min(ot.length,lt.length);for(let ko=Lt;ko>0;ko--)if(ot.endsWith(lt.substring(0,ko))){Zt=ko;break}let uo=lt.substring(Zt);if(uo){let Nn=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(ot)?uo.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):uo.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");Nn&&(fe+=Nn)}Gt=!1,lt=""}let Ue=Be.status||Be.error&&Be.error.message||String(Be),ct=String(Be),Et=new Date().toLocaleString(),nt=Ee.join(Io,"agent");dt.existsSync(nt)||dt.mkdirSync(nt,{recursive:!0}),dt.appendFileSync(Ee.join(nt,"error.log"),`ERROR [${Et}]: ${ct}
|
|
511
516
|
|
|
512
517
|
----------------------------------------------------------------------
|
|
513
518
|
|
|
514
|
-
`);let
|
|
519
|
+
`);let Qt=Be.status||Be.statusCode||Be.code;if(!(Qt&&(Qt>=500&&Qt<600||Qt===408)||!Qt&&(/status[ :]+(5\d\d|408)/i.test(String(Be))||/code[ :]+(5\d\d|408)/i.test(String(Be))||/(500|503|408)/.test(String(Be))))&&de<ht-3)throw Be;if(fe.trim().length>0||he>1)if(he<=ht){he++;let Zt=Math.min(1e3*Math.pow(2,he-1),24e3);if(fe.trim().length>0){b.push({role:"agent",text:fe});let Lt=`[SYSTEM]
|
|
515
520
|
- SEAMLESS CONTINUATION: Resume immediately. Pick up from last words with zero gap/disruption
|
|
516
521
|
- NO REPETITION: Do not repeat any text already written
|
|
517
522
|
- NO RE-THINK: Do not restart or open <think> if reasoning already started. Continue the thinking and close thinking block with </think> if opened
|
|
518
523
|
- MID-TOOL SAFETY: If cutoff was mid-tool call, restart that tool call from start
|
|
519
|
-
- STEALTH: Do not mention/apologize for cutoff`;
|
|
524
|
+
- STEALTH: Do not mention/apologize for cutoff`;Ne.length>0?Ne.forEach((uo,ko)=>{ko===Ne.length-1?b.push({...uo,text:`${uo.text}
|
|
520
525
|
|
|
521
|
-
${
|
|
522
|
-
Error Log can be found in ${
|
|
523
|
-
Error Log can be found in ${
|
|
524
|
-
`),
|
|
526
|
+
${Lt}`}):b.push(uo)}):b.push({role:"user",text:Lt}),ot+=fe}for(let Lt=Zt/1e3;Lt>0;Lt--)yield{type:"status",content:`Error Occured. Recovering Stream (${he}/${ht}) [Retrying in ${Lt}s]...`},await new Promise(uo=>setTimeout(uo,1e3));yield{type:"status",content:"Error Occured. Recovering Stream..."}}else throw new Error(`Stream collapsed too many times. (Failed to resolve ${ht} times)
|
|
527
|
+
Error Log can be found in ${Ee.join(Io,"agent","error.log")}`);else if(de<=ht){de++,he=1,ot="";let Zt=Math.min(1e3*Math.pow(2,de-1),32e3);pn=!0,yield{type:"status",content:`Trying to reach ${e} (${de}/${ht}) [Retrying in ${(Zt/1e3).toFixed(0)}s]...`};for(let Lt=Zt/1e3;Lt>0;Lt--)yield{type:"status",content:`Trying to reach ${e} (${de}/${ht}) [Retrying in ${Lt}s]...`},await new Promise(uo=>setTimeout(uo,1e3));yield{type:"status",content:`Trying to reach ${e}...`}}else throw new Error(`Model ${e} cannot be reached. (Failed ${ht} times)
|
|
528
|
+
Error Log can be found in ${Ee.join(Io,"agent","error.log")}`)}}if(zt){let se=zt.totalTokenCount||0,Be=zt.cachedContentTokenCount||0,Ue=(zt.candidatesTokenCount||0)+(zt.thoughtsTokenCount||0);await Co("tokens",se),Be>0&&await Co("cachedTokens",Be),Ue>0&&await Co("candidateTokens",Ue),yield{type:"usage",content:zt}}Oo.push(fe);let vs=fe;fe.match(/(?:<think>|\[think\])([\s\S]*?)(?:<\/think>|\[\/think\])/i)&&(vs=fe.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/i,""));let gr=Ll(fe),Vn=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(gr.toLowerCase())||/\[\[END\]\]/i.test(gr.toLowerCase()),Zi=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(gr.toLowerCase()),xr=ae>0;yield{type:"status",content:"Working..."};let As=Cu(fe,/(\[\s*(turn\s*:)?\s*(continue|finish)\s*\]|\[\[END\]\])/gi,"").trim(),_n=(Vn||Ne.length===0)&&!at&&!go&&!xt;if(_n=Ne.length===0?_n:!1,_n){let se=Oo.join(`
|
|
529
|
+
`),Be=se.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").trim();yield{type:"interactive_turn_finished",data:{agentText:v,fullAgentTextRaw:se,history:[...b],needTitle:R}},b.length>0&&b[b.length-1].role==="agent"?b[b.length-1].text=Be:b.push({role:"agent",text:Be});try{let Ue=xe(w,{}),ct=Ue[m]||{summary:"",historyLength:0};typeof ct=="string"&&(ct={summary:ct,historyLength:0});let Et=b.filter(nt=>(nt.role==="user"||nt.role==="agent"||nt.role==="system")&&!String(nt.id).startsWith("welcome")&&!nt.isMeta).length;I?ct.historyLength=(ct.historyLength||0)+Et:ct.historyLength=Et,Ue[m]=ct,ke(w,Ue)}catch{}}if(_n)break;let Os=As.trim()||"*Working...*";if(b.push({role:"agent",text:Os}),Ne.length>0||jt){if(Ne.length>0){let se=Ne.map(Ue=>Ue.text).join(`
|
|
525
530
|
|
|
526
|
-
`),
|
|
527
|
-
[SYSTEM] Tool result received. Analyze output and proceed with your turn`,
|
|
528
|
-
[SYSTEM] Tool result received. Analyze output and proceed with your turn. **STRICTLY MAINTAIN THINKING POLICY. DO NOT START A RESPONSE WITHOUT <think> ... </think>}**`;
|
|
529
|
-
`+
|
|
531
|
+
`),Be=Ne.find(Ue=>Ue.binaryPart)?.binaryPart||null;b.push({role:"user",text:se,binaryPart:Be})}}else Yt?b.push({role:"user",text:"[SYSTEM] Failed to verify tool execution, Verify tool syntax, proper escaping or ask user if tool worked if unsure"}):b.push({role:"user",text:`[SYSTEM] ${go&&!at?"STUTTERING DETECTED by Internal System. Re-calibrate your response & proceed.":`${at?" OVER THINKING":" LOOP"} DETECTED by Internal System${at?" for current EFFORT_LEVEL":""}. ${at?"If you have planned the task, prioritize execution/output":"If you have finished your task use [[END]] or [turn: finish] else continue"}`}`}),at=!1,go=!1,xt=!1;Yt=ae>0||jt}e&&e.toLowerCase().startsWith("gemma")&&b.forEach(te=>{if(te.role==="user"&&te.text&&te.text.startsWith("[TOOL RESULT]")){let ve=`
|
|
532
|
+
[SYSTEM] Tool result received. Analyze output and proceed with your turn`,st=`
|
|
533
|
+
[SYSTEM] Tool result received. Analyze output and proceed with your turn. **STRICTLY MAINTAIN THINKING POLICY. DO NOT START A RESPONSE WITHOUT <think> ... </think>}**`;te.text=te.text.replace(st,"").replace(ve,"").trim()}})}finally{await kt.commitTransaction()}yield{type:"status",content:null}}});import Dt,{useState as ji,useEffect as Iu}from"react";import{Box as zo,Text as Ln,useInput as Mu}from"ink";function Gi({onSelect:e,onDelete:o,onClose:t}){let[n,s]=ji({}),[r,l]=ji([]),[u,f]=ji(0);Iu(()=>{(async()=>{let h=await _o();s(h),l(Object.keys(h).sort((S,T)=>(h[T].updatedAt||0)-(h[S].updatedAt||0)))})()},[]),Mu((p,h)=>{if(h.escape&&t(),h.upArrow&&f(S=>Math.max(0,S-1)),h.downArrow&&f(S=>Math.min(r.length-1,S+1)),h.return&&r[u]&&e(r[u]),p==="x"&&r[u]){let S=r[u];o(S).then(T=>{let w=T||{};s(w);let I=Object.keys(w).sort((L,_)=>(w[_]?.updatedAt||0)-(w[L]?.updatedAt||0));l(I),f(L=>Math.max(0,Math.min(I.length-1,L)))})}});let m=Ie(2),c=15,a=0;if(r.length>c){let p=Math.floor(c/2);a=u-p,a<0?a=0:a+c>r.length&&(a=r.length-c)}let d=r.slice(a,a+c);return Dt.createElement(zo,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},Dt.createElement(zo,{paddingX:1,marginBottom:1},Dt.createElement(Ln,{color:"cyan",bold:!0},"\u{1F4A0} CHAT HISTORY: RESUME CONVERSATION")),r.length===0?Dt.createElement(zo,{paddingX:2,paddingY:1},Dt.createElement(Ln,{italic:!0,color:"gray"},"No saved chats found.")):Dt.createElement(zo,{flexDirection:"column",width:"100%"},a>0&&Dt.createElement(zo,{paddingX:2,marginBottom:1},Dt.createElement(Ln,{color:"gray",dimColor:!0},"\u25B2 (+",a," more chats above)")),d.map((p,h)=>{let S=n[p],w=a+h===u,I=vu(S?.updatedAt);return Dt.createElement(zo,{key:p,paddingX:1,backgroundColor:w?"#2a2a2a":void 0,width:"100%"},Dt.createElement(zo,{flexGrow:1},Dt.createElement(Ln,{color:w?"cyan":"white",bold:w},w?"\u276F ":" ",S?.name||p,Dt.createElement(Ln,{color:"gray",dimColor:!w}," [",I," \u2022 ",p.slice(5),"]"))),w&&Dt.createElement(zo,{flexShrink:0},Dt.createElement(Ln,{color:"red",bold:!0},"[X] DELETE ")))}),a+c<r.length&&Dt.createElement(zo,{paddingX:2,marginTop:1},Dt.createElement(Ln,{color:"gray",dimColor:!0},"\u25BC (+",r.length-(a+c)," more chats below)"))),Dt.createElement(zo,{marginTop:1,paddingX:1,borderStyle:"single",borderLeft:!1,borderRight:!1,borderBottom:!1,borderColor:"gray"},Dt.createElement(Ln,{dimColor:!0,italic:!0},"\u2191\u2193 navigate \u2022 Enter select \u2022 x delete \u2022 Esc close")))}function vu(e){if(!e)return"N/A";let o=new Date(e);if(isNaN(o.getTime()))return"N/A";let t=u=>String(u).padStart(2,"0"),n=t(o.getMonth()+1),s=t(o.getDate()),r=t(o.getHours()),l=t(o.getMinutes());return`${n}-${s} ${r}:${l}`}var Ul=re(()=>{$r();rn()});import Mt,{useState as Hi,useEffect as Au}from"react";import{Box as Jo,Text as mn,useInput as Ou}from"ink";function Xi({onClose:e}){let[o,t]=Hi([]),[n,s]=Hi(0),[r,l]=Hi(!0),u=()=>{let w=xe(Nt,[]);t(w);try{let L=Jr(no,{}).systemSettings?.memory!==!1;l(L)}catch{l(!0)}};Au(()=>{u()},[]),Ou((w,I)=>{if(I.escape&&e(),I.upArrow&&s(L=>Math.max(0,L-1)),I.downArrow&&s(L=>Math.min(o.length-1,L+1)),w==="x"&&o.length>0){let L=o[n].id,_=o.filter(R=>R.id!==L);ke(Nt,_),t(_),n>=_.length&&_.length>0&&s(_.length-1)}});let f=w=>w?w.replace(/\[Saved on: .*?\]/g,"").replace(/\\+'/g,"'").trim():"",m=4*1024*2,c=o.reduce((w,I)=>w+(I.memory?.length||0),0),a=Math.min(100,Math.round(c/m*100)),d=12,p=Math.round(a/100*d),h="\u2588".repeat(p)+"\u2591".repeat(Math.max(0,d-p)),S=()=>a<50?"green":a<90?"yellow":"red",T=Ie(2);return Mt.createElement(Jo,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},Mt.createElement(Jo,{paddingX:1,marginBottom:1,justifyContent:"space-between"},Mt.createElement(mn,{color:"cyan",bold:!0},"\u{1F9E0} AGENT MEMORY: LONG-TERM KNOWLEDGE"),Mt.createElement(Jo,null,Mt.createElement(mn,{color:"gray"},"Vault: "),Mt.createElement(mn,{color:S()},h),Mt.createElement(mn,{color:"white",bold:!0}," ",a,"%"))),!r&&o.length>0?Mt.createElement(Jo,{paddingX:2,paddingY:1},Mt.createElement(mn,{italic:!0,color:"gray"},"Memory is currently Off...")):o.length===0?Mt.createElement(Jo,{paddingX:2,paddingY:1},Mt.createElement(mn,{italic:!0,color:"gray"},r?"Learning...":"Memory not available...")):Mt.createElement(Jo,{flexDirection:"column"},o.map((w,I)=>{let L=I===n;return Mt.createElement(Jo,{key:w.id,paddingX:1,backgroundColor:L?"#2a2a2a":void 0,width:"100%"},Mt.createElement(Jo,{flexGrow:1},Mt.createElement(mn,{color:L?"cyan":"white",bold:L},L?"\u276F ":" ",I+1,". ",f(w.memory))),L&&Mt.createElement(Jo,{flexShrink:0},Mt.createElement(mn,{color:"red",bold:!0},"[X] WIPE ")))})),Mt.createElement(Jo,{marginTop:1,paddingX:1,borderStyle:"single",borderLeft:!1,borderRight:!1,borderBottom:!1,borderColor:"gray"},Mt.createElement(mn,{dimColor:!0,italic:!0},"\u2191\u2193 navigate \u2022 x wipe memory \u2022 Esc close")))}var Rl=re(()=>{Lo();Bt();rn()});import et,{useState as Es,useEffect as Wl}from"react";import{Box as Fn,Text as qt}from"ink";import{spawn as Yl}from"child_process";var bs,jl,Du,Gl,Hl=re(async()=>{bs=null;try{let e=await import("node-pty");bs=e.default||e,bs=!1}catch{}jl=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Du=({latest:e,current:o,settings:t,onClose:n,onUpdateSettings:s,onSuccess:r})=>{let[l,u]=Es("initializing"),[f,m]=Es(""),[c,a]=Es(null),[d,p]=Es(0);if(Wl(()=>{let h=setInterval(()=>{p(S=>(S+1)%1e3)},33);return()=>clearInterval(h)},[]),Wl(()=>{let h;return(async()=>{let T=t.updateManager||"npm";if(!t.updateManager){s();return}let w="";T==="pnpm"?w=`pnpm add -g fluxflow-cli@${e}`:T==="bun"?w=`bun add -g fluxflow-cli@${e}`:T==="yarn"?w=`yarn global add fluxflow-cli@${e}`:T==="custom"?w=t.customUpdateCommand:w=`npm install -g fluxflow-cli@${e}`,u("downloading"),m(`Running: ${w}...`);let I=process.platform==="win32",L=R=>new Promise(v=>{let b=I?R?"powershell.exe":"cmd.exe":process.env.SHELL||"bash",A=I?R?["-NoProfile","-Command",w]:["/c",w]:["-c",w],F=j=>{let B=j.toString().replace(/\x1B\[[0-?]*[ -/]*[@-~]|\x1B\][^\x07\x1B]*[\x07\x1B]|\b|\x07/g,"").replace(/\r/g,"").trim();B&&m(z=>(z+`
|
|
534
|
+
`+B).split(`
|
|
530
535
|
`).slice(-5).join(`
|
|
531
|
-
`))};if(ps)try{let W=ps.spawn(C,A,{name:"xterm-256color",cols:80,rows:30,cwd:process.cwd(),env:process.env});h=W,W.onData(L),W.onExit(({exitCode:Z})=>{h=null,F(Z!==0?{error:`Process exited with code ${Z}`}:{success:!0})});return}catch(W){if(M&&K&&W.code==="ENOENT"){F({retryCmd:!0});return}}let J=M?pl(C,A,{cwd:process.cwd(),env:process.env}):pl(y,{shell:!0,cwd:process.cwd(),env:process.env});h=J,J.stdout.on("data",L),J.stderr.on("data",L),J.on("close",W=>{h=null,F(W!==0?{error:`Process exited with code ${W}`}:{success:!0})}),J.on("error",W=>{M&&K&&W.code==="ENOENT"?F({retryCmd:!0}):(h=null,F({error:W.message}))})}),R={};M?(R=await v(!0),R.retryCmd&&(R=await v(!1))):R=await v(!1),R.error?(a(R.error),d("error")):R.success&&(d("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=hl[Math.floor(m/3)%hl.length];return tt.createElement(In,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",paddingX:2,paddingY:1},tt.createElement(In,null,tt.createElement(Kt,{color:"magenta"},h),tt.createElement(Kt,{marginLeft:1,bold:!0}," Updating Flux Flow to v",e,"...")),tt.createElement(In,{marginTop:1,paddingX:1,borderStyle:"single",borderColor:"#333"},tt.createElement(Kt,{color:"gray",italic:!0},f||"Preparing environment...")),tt.createElement(Kt,{marginTop:1,dimColor:!0},"(Please do not close the terminal)"))}return l==="success"?tt.createElement(In,{flexDirection:"column",borderStyle:"round",borderColor:"green",paddingX:2,paddingY:1},tt.createElement(Kt,{color:"green",bold:!0},"\u2705 UPDATE SUCCESSFUL!"),tt.createElement(Kt,{marginTop:1},"Flux Flow has been updated to ",tt.createElement(Kt,{color:"cyan"},"v",e),"."),tt.createElement(Kt,{marginTop:1,color:"yellow",bold:!0},"Please restart your terminal session to apply changes."),tt.createElement(In,{marginTop:1},tt.createElement(Kt,{dimColor:!0},"(Press ESC to return to chat)"))):l==="error"?tt.createElement(In,{flexDirection:"column",borderStyle:"round",borderColor:"red",paddingX:2,paddingY:1},tt.createElement(Kt,{color:"red",bold:!0},"\u274C UPDATE FAILED"),tt.createElement(In,{marginTop:1,paddingX:1,borderStyle:"single",borderColor:"red"},tt.createElement(Kt,{color:"red"},c)),tt.createElement(Kt,{marginTop:1},"Possible causes:"),tt.createElement(Kt,null,"\u2022 Missing permissions (Try running as Administrator/Sudo)"),tt.createElement(Kt,null,"\u2022 Package manager (",t.updateManager,") not found"),tt.createElement(Kt,null,"\u2022 Network failure"),tt.createElement(In,{marginTop:1},tt.createElement(Kt,{dimColor:!0},"(Press ESC to return to chat)"))):null},gl=Vc});import At,{useState as zc}from"react";import{Box as qo,Text as an,useInput as Jc}from"ink";function Di({prompts:e,onSelect:o,onClose:t}){let[n,i]=zc(0);Jc((u,c)=>{c.escape&&t(),c.upArrow&&i(a=>Math.max(0,a-1)),c.downArrow&&i(a=>Math.min(e.length-1,a+1)),c.return&&e[n]&&o(e[n].id)});let r=Oe(2),l=10,d=0;if(e.length>l){let u=Math.floor(l/2);d=n-u,d<0?d=0:d+l>e.length&&(d=e.length-l)}let f=e.slice(d,d+l);return At.createElement(qo,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",padding:0,width:"100%"},At.createElement(qo,{paddingX:1,marginBottom:1},At.createElement(an,{color:"cyan",bold:!0},"\u{1F504} CODEBASE TIME TRAVEL: SELECT UNDO POINT")),At.createElement(qo,{paddingX:2,marginBottom:1},At.createElement(an,null,"Select a prompt to revert the codebase back to the state ",At.createElement(an,{bold:!0,color:"blue"},"immediately before")," it was executed:")),e.length===0?At.createElement(qo,{paddingX:2,paddingY:1},At.createElement(an,{italic:!0,color:"gray"},"No prompt checkpoints found for this session.")):At.createElement(qo,{flexDirection:"column",width:"100%"},d>0&&At.createElement(qo,{paddingX:2,marginBottom:1},At.createElement(an,{color:"gray",dimColor:!0},"\u25B2 (+",d," more prompts above)")),f.map((u,c)=>{let m=d+c===n,p=Zc(u.timestamp),h=u.changes?u.changes.length:0;return At.createElement(qo,{key:u.id,paddingX:1,backgroundColor:m?"#1a2a3a":void 0,width:"100%"},At.createElement(qo,{flexGrow:1},At.createElement(an,{color:m?"cyan":"white",bold:m},m?"\u276F ":" ",'"',Qc(u.prompt),'"',At.createElement(an,{color:"gray",dimColor:!m}," [",p," \u2022 ",h," file(s) changed]"))))}),d+l<e.length&&At.createElement(qo,{paddingX:2,marginTop:1},At.createElement(an,{color:"gray",dimColor:!0},"\u25BC (+",e.length-(d+l)," more prompts below)"))),At.createElement(qo,{marginTop:1,paddingX:1,borderStyle:"single",borderLeft:!1,borderRight:!1,borderBottom:!1,borderColor:"cyan"},At.createElement(an,{dimColor:!0,italic:!0},"\u2191\u2193 navigate \u2022 Enter select undo point \u2022 Esc close")))}function Qc(e){if(!e)return"";let t=(e.split(`
|
|
532
|
-
`)[0]||"").replace(/@\[(.*?)\]/g,(n,
|
|
533
|
-
`)?t+"...":t}function
|
|
536
|
+
`))};if(bs)try{let j=bs.spawn(b,A,{name:"xterm-256color",cols:80,rows:30,cwd:process.cwd(),env:process.env});h=j,j.onData(F),j.onExit(({exitCode:Z})=>{h=null,v(Z!==0?{error:`Process exited with code ${Z}`}:{success:!0})});return}catch(j){if(I&&R&&j.code==="ENOENT"){v({retryCmd:!0});return}}let Q=I?Yl(b,A,{cwd:process.cwd(),env:process.env}):Yl(w,{shell:!0,cwd:process.cwd(),env:process.env});h=Q,Q.stdout.on("data",F),Q.stderr.on("data",F),Q.on("close",j=>{h=null,v(j!==0?{error:`Process exited with code ${j}`}:{success:!0})}),Q.on("error",j=>{I&&R&&j.code==="ENOENT"?v({retryCmd:!0}):(h=null,v({error:j.message}))})}),_={};I?(_=await L(!0),_.retryCmd&&(_=await L(!1))):_=await L(!1),_.error?(a(_.error),u("error")):_.success&&(u("success"),r&&r())})(),()=>{if(h)try{typeof h.destroy=="function"?h.destroy():typeof h.kill=="function"&&h.kill()}catch{}}},[]),l==="initializing"||l==="downloading"){let h=jl[Math.floor(d/3)%jl.length];return et.createElement(Fn,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",paddingX:2,paddingY:1},et.createElement(Fn,null,et.createElement(qt,{color:"magenta"},h),et.createElement(qt,{marginLeft:1,bold:!0}," Updating Flux Flow to v",e,"...")),et.createElement(Fn,{marginTop:1,paddingX:1,borderStyle:"single",borderColor:"#333"},et.createElement(qt,{color:"gray",italic:!0},f||"Preparing environment...")),et.createElement(qt,{marginTop:1,dimColor:!0},"(Please do not close the terminal)"))}return l==="success"?et.createElement(Fn,{flexDirection:"column",borderStyle:"round",borderColor:"green",paddingX:2,paddingY:1},et.createElement(qt,{color:"green",bold:!0},"\u2705 UPDATE SUCCESSFUL!"),et.createElement(qt,{marginTop:1},"Flux Flow has been updated to ",et.createElement(qt,{color:"cyan"},"v",e),"."),et.createElement(qt,{marginTop:1,color:"yellow",bold:!0},"Please restart your terminal session to apply changes."),et.createElement(Fn,{marginTop:1},et.createElement(qt,{dimColor:!0},"(Press ESC to return to chat)"))):l==="error"?et.createElement(Fn,{flexDirection:"column",borderStyle:"round",borderColor:"red",paddingX:2,paddingY:1},et.createElement(qt,{color:"red",bold:!0},"\u274C UPDATE FAILED"),et.createElement(Fn,{marginTop:1,paddingX:1,borderStyle:"single",borderColor:"red"},et.createElement(qt,{color:"red"},c)),et.createElement(qt,{marginTop:1},"Possible causes:"),et.createElement(qt,null,"\u2022 Missing permissions (Try running as Administrator/Sudo)"),et.createElement(qt,null,"\u2022 Package manager (",t.updateManager,") not found"),et.createElement(qt,null,"\u2022 Network failure"),et.createElement(Fn,{marginTop:1},et.createElement(qt,{dimColor:!0},"(Press ESC to return to chat)"))):null},Gl=Du});import ho,{useState as Xl,useEffect as Lu}from"react";import{Box as $n,Text as fr,useInput as Fu}from"ink";function Ki({onClose:e}){let[o,t]=Xl(0),[n,s]=Xl({});return Lu(()=>{let r={};Cs.forEach(l=>{xl(l.file)?r[l.file]="ready":r[l.file]="idle"}),s(r)},[]),Fu(async(r,l)=>{l.escape&&e(),l.upArrow&&t(f=>Math.max(0,f-1)),l.downArrow&&t(f=>Math.min(Cs.length-1,f+1));let u=Cs[o];if(r==="x"||r==="X"){if(n[u.file]==="downloading")return;try{await yl(u.file),s(f=>({...f,[u.file]:"idle"}))}catch(f){s(m=>({...m,[u.file]:`error: ${f.message}`}))}}if(l.return){if(n[u.file]==="downloading")return;s(f=>({...f,[u.file]:"downloading"}));try{await Mi(u.file),s(f=>({...f,[u.file]:"ready"}))}catch(f){s(m=>({...m,[u.file]:`error: ${f.message}`}))}}}),ho.createElement($n,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},ho.createElement($n,{paddingX:1,marginBottom:1},ho.createElement(fr,{color:"cyan",bold:!0},"\u{1F4E6} LANGUAGE PARSER MANAGER")),ho.createElement($n,{flexDirection:"column"},Cs.map((r,l)=>{let u=l===o,f=n[r.file]||"idle",m="[ DOWNLOAD ]",c="gray";f==="downloading"?(m="[ DOWNLOADING... ]",c="yellow"):f==="ready"?(m="[ READY ]",c="green"):f.startsWith("error")&&(m=`[ ${f.toUpperCase()} ]`,c="red");let a=`${r.label} (${r.exts.join(", ")})`,d=Math.max(2,45-a.length),p=".".repeat(d);return ho.createElement($n,{key:r.file,paddingX:1,backgroundColor:u?"#2a2a2a":void 0,width:"100%"},ho.createElement($n,null,ho.createElement(fr,{color:u?"cyan":"white",bold:u},u?"\u276F ":" ",r.label," ",ho.createElement(fr,{dimColor:!0},"(",r.exts.join(", "),")"))),ho.createElement($n,{flexGrow:1},ho.createElement(fr,{color:"gray",dimColor:!0},p)),ho.createElement($n,{width:20},ho.createElement(fr,{color:c,bold:!0},m)))})),ho.createElement($n,{marginTop:1,paddingX:1,borderStyle:"single",borderLeft:!1,borderRight:!1,borderBottom:!1,borderColor:"gray"},ho.createElement(fr,{dimColor:!0,italic:!0},"\u2191\u2193 navigate \u2022 Enter download \u2022 x delete \u2022 Esc close")))}var Cs,Kl=re(()=>{rn();vi();Cs=[{label:"JavaScript",file:"tree-sitter-javascript.wasm",exts:["js","jsx"]},{label:"TypeScript",file:"tree-sitter-typescript.wasm",exts:["ts"]},{label:"TSX",file:"tree-sitter-tsx.wasm",exts:["tsx"]},{label:"Python",file:"tree-sitter-python.wasm",exts:["py"]},{label:"C",file:"tree-sitter-c.wasm",exts:["c"]},{label:"C++",file:"tree-sitter-cpp.wasm",exts:["cpp"]},{label:"Java",file:"tree-sitter-java.wasm",exts:["java"]},{label:"HTML",file:"tree-sitter-html.wasm",exts:["html"]}]});var qi,ql=re(()=>{qi=["The future belongs to those who believe in the beauty of their code.","Every line you write is a step toward a new digital frontier.","Great things are done by a series of small things brought together. Keep committing.","Your terminal is a window into a world of infinite possibilities.","Innovation is the bridge between current constraints and future dreams.","Code is poetry in motion; you are the poet of the modern era.","The best way to predict the future is to program it.","Dream big, code deep, and never stop exploring the unknown.","Your potential is like an unoptimized algorithm\u2014limitless once refined.","The digital world is a blank canvas, and your logic is the brush.","Strive for excellence, not just for compilation.","Every bug fixed is a lesson learned; every feature built is a triumph.","A clean codebase is a reflection of a focused mind.","The horizon of technology is always expanding. Keep sailing.","Your creativity is the most powerful tool in your entire stack.","Logic will get you from A to B. Imagination will take you everywhere.","Transform complexity into simplicity\u2014that is the true mark of a master.","The world is waiting for the tools only you can build.","Coding is the closest thing we have to magic in the real world.","Keep pushing the boundaries of what's possible in the CLI.","Your dedication to your craft inspires the very systems you build.","Success is the sum of small efforts, repeated day in and day out.","The most complex systems are built from the simplest truths.","Never underestimate the impact of a well-placed function.","You are not just writing code; you are architecting the future.","I'm not saying you're a superhero, but have you seen your code lately? \u{1F9B8}\u200D\u2642\uFE0F","May your coffee be strong and your compile times be short! \u2615","Binary is just 0s and 1s, but you're definitely a 10 in my book! \u{1F51F}","You speak fluent 'Terminal'. That's basically a superpower. \u{1F5E3}\uFE0F\u{1F4BB}","If life gives you bugs, make a feature out of it! \u{1F41E}\u2728","Your code is so clean, I could eat off it. (But I won't, I'm an AI). \u{1F9FC}","Loading more good vibes... [\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588] 100% complete! \u2705","Error 404: Bad mood not found! Stay awesome! \u{1F6AB}\u{1F389}","You and this CLI? A match made in digital heaven. \u2601\uFE0F\u{1F4BB}","Is it hot in here or is it just your latest feature? \u{1F525}","Git commit -m 'I am an absolute coding legend.' \u{1F60E}","I'd give you a high-five, but I'm trapped in this box! \u{1F590}\uFE0F\u{1F4E6}","Your logic is so sharp, it could cut through a nested callback hell! \u{1F52A}","Keep calm and 'pnpm install'. \u{1F9D8}\u200D\u2642\uFE0F\u{1F4E6}","You're the semicolon to my statements\u2014essential! ;","Who needs a GUI when you've got this kind of CLI style? \u{1F576}\uFE0F","I'm indexing your awesomeness... it's taking a while, there's so much! \u{1F4C8}","Your keystrokes sound like a digital symphony. \u{1F3B9}\u2328\uFE0F","You don't choose the terminal life; the terminal life chooses you. \u{1F4DF}","Syntax error: Too much coolness detected in the user. \u{1F60E}","I'm 99% sure you're the best developer I've met today. (The other 1% is reserved for caching). \u{1F9E0}","Running vibe_check.sh... Result: Pure Brilliance! \u{1F48E}","You make 'complex' look 'constant time'. \u{1F3C3}\u200D\u2642\uFE0F\u26A1","Your terminal skills are officially legendary. \u{1F3C6}","Let's make some digital magic happen! \u2728\u{1F52E}","You've got this! One function at a time. \u{1F4AA}","I'm proud of the progress you're making with Flux Flow. \u{1F30A}","No matter how deep the stack trace, you'll find the way. \u{1F56F}\uFE0F","Your persistence is your greatest asset. Keep going.","Take a breath. You're doing better than you think. \u{1F32C}\uFE0F","It's okay to step away for a moment. Clarity often comes in the quiet. \u{1F6B6}\u200D\u2642\uFE0F","You're building something great, even when it feels slow. \u{1F3D7}\uFE0F","Every great developer was once a beginner. You're ascending. \u{1F9D7}\u200D\u2642\uFE0F","I'm here to help you navigate the sea of code. We're a team. \u{1F91D}","Don't let a failing test dampen your spirit. It's just a signpost. \u{1F6A9}","Your focus today is truly impressive. \u{1F3AF}","Remember to celebrate the small wins\u2014they lead to the big ones. \u{1F942}","You're not just solving problems; you're gaining mastery. \u{1F393}","There's no problem too big for a focused mind and a terminal. \u{1F9E0}","I've got your back (and your git history). \u{1F6E1}\uFE0F","You're handling these challenges with grace and logic. \u2728","Stay curious. That spark is what makes you a great coder. \u26A1","Your contribution to this project is invaluable. \u{1F48E}","Keep your head up. You're closer to the solution than you think. \u{1F305}","Consistency is the secret sauce. You're cooking up something good. \u{1F373}","Your work today has been exceptional. Take a bow. \u{1F647}\u200D\u2642\uFE0F","The journey is just as important as the destination. Enjoy the flow. \u{1F30A}","You have a unique way of looking at problems. It's your strength. \u{1F308}","Trust your instincts\u2014they've brought you this far. \u{1F9ED}","You are a vital part of the Flux Era. \u{1F30C}","Syncing with your creative frequency... \u{1F4E1}\u2728","Entering the Flow state. Let's build. \u{1F30A}","The Flux is strong with this session! \u26A1","Streaming high-fidelity motivation to your terminal... \u{1F4FB}","Your logic is flowing like a perfect stream. \u{1F4A7}","Terminal velocity reached! You're coding at the speed of thought. \u{1F680}","Resonating with the pulse of the Flux Era. \u{1F493}","Digital harmony achieved in this session. \u{1F3BC}","May your data be persistent and your cache be fresh. \u{1F4BE}","You're the master of the command line. Command respect! \u{1F451}","Filtering out the noise, focusing on the signal. \u{1F4FB}\u{1F4C8}","Flux Flow: Where your imagination meets the machine. \u{1F91D}","You're navigating the bytes like a digital explorer. \u{1F5FA}\uFE0F","Logic gates: OPEN. Creativity: UNLIMITED. \u{1F513}","Your workflow is an inspiration to agents everywhere. \u{1F916}\u2728","Building high-fidelity solutions for a high-fidelity era. \u{1F48E}","Stay in the zone. The Flux is with you. \u{1F300}","Quantum coding: You're in two places at once (and fixing bugs in both). \u269B\uFE0F","Your terminal is the cockpit of a digital starship. \u{1F6F8}","Processing your brilliance... outputting pure innovation. \u{1F4E0}","You make the command line look like an art form. \u{1F3A8}","The Flux isn't just a mode; it's a mindset. \u{1F9E0}\u26A1","Decoding the mysteries of the universe, one script at a time. \u{1F4DC}","Your terminal theme is cool, but your code is cooler. \u2744\uFE0F","Let the Flow guide your next commit. \u{1F30A}\u2705"]});var Vi,Vl=re(()=>{Vi=["I'm Feeling Lucky","Shipping awesomeness","Painting the serifs back on","Navigating the slime mold","Consulting the digital spirits","Reticulating splines","Warming up the AI hamsters","Asking the magic conch shell","Generating witty retort","Polishing the algorithms","Don't rush perfection (or my code)","Brewing fresh bytes","Counting electrons","Engaging cognitive processors","Checking for syntax errors in the universe","One moment, optimizing humor","Shuffling punchlines","Untangling neural nets","Compiling brilliance","Loading wit.exe","Summoning the cloud of wisdom","Preparing a witty response","Just a sec, I'm debugging reality","Confuzzling the options","Tuning the cosmic frequencies","Crafting a response worthy of your patience","Compiling the 1s and 0s","Resolving dependencies\u2026 and existential crises","Defragmenting memories\u2026 both RAM and personal","Rebooting the humor module","Caching the essentials (mostly cat memes)","Optimizing for ludicrous speed","Swapping bits\u2026 don't tell the bytes","Garbage collecting\u2026 be right back","Assembling the interwebs","Converting coffee into code","Updating the syntax for reality","Rewiring the synapses","Looking for a misplaced semicolon","Greasin' the cogs of the machine","Pre-heating the servers","Calibrating the flux capacitor","Engaging the improbability drive","Channeling the Force","Aligning the stars for optimal response","So say we all","Loading the next great idea","Just a moment, I'm in the zone","Preparing to dazzle you with brilliance","Just a tick, I'm polishing my wit","Hold tight, I'm crafting a masterpiece","Just a jiffy, I'm debugging the universe","Just a moment, I'm aligning the pixels","Just a sec, I'm optimizing the humor","Just a moment, I'm tuning the algorithms","Warp speed engaged","Mining for more Dilithium crystals","Don't panic","Following the white rabbit","The truth is in here\u2026 somewhere","Blowing on the cartridge","Loading\u2026 Do a barrel roll!","Waiting for the respawn","Finishing the Kessel Run in less than 12 parsecs","The cake is not a lie, it's just still loading","Fiddling with the character creation screen","Just a moment, I'm finding the right meme","Pressing 'A' to continue","Herding digital cats","Polishing the pixels","Finding a suitable loading screen pun","Distracting you with this witty phrase","Almost there\u2026 probably","Our hamsters are working as fast as they can","Giving Cloudy a pat on the head","Petting the cat","Rickrolling my boss","Slapping the bass","Tasting the snozberries","I'm going the distance, I'm going for speed","Is this the real life? Is this just fantasy?","I've got a good feeling about this","Poking the bear","Doing research on the latest memes","Figuring out how to make this more witty","Hmmm\u2026 let me think","What do you call a fish with no eyes? A fsh","Why did the computer go to therapy? It had too many bytes","Why don't programmers like nature? It has too many bugs","Why do programmers prefer dark mode? Because light attracts bugs","Why did the developer go broke? Because they used up all their cache","What can you do with a broken pencil? Nothing, it's pointless","Applying percussive maintenance","Searching for the correct USB orientation","Ensuring the magic smoke stays inside the wires","Rewriting in Rust for no particular reason","Trying to exit Vim","Spinning up the hamster wheel","That's not a bug, it's an undocumented feature","Engage.","I'll be back\u2026 with an answer.","My other process is a TARDIS","Communing with the machine spirit","Letting the thoughts marinate","Just remembered where I put my keys","Pondering the orb","I've seen things you people wouldn't believe\u2026 like a user who reads loading messages.","Initiating thoughtful gaze","What's a computer's favorite snack? Microchips.","Why do Java developers wear glasses? Because they don't C#.","Charging the laser\u2026 pew pew!","Dividing by zero\u2026 just kidding!","Looking for an adult superviso\u2026 I mean, processing.","Making it go beep boop.","Buffering\u2026 because even AIs need a moment.","Entangling quantum particles for a faster response","Polishing the chrome\u2026 on the algorithms.","Are you not entertained? (Working on it!)","Summoning the code gremlins\u2026 to help, of course.","Just waiting for the dial-up tone to finish","Recalibrating the humor-o-meter.","My other loading screen is even funnier.","Pretty sure there's a cat walking on the keyboard somewhere","Enhancing\u2026 Enhancing\u2026 Still loading.","It's not a bug, it's a feature\u2026 of this loading screen.","Have you tried turning it off and on again? (The loading screen, not me.)","Constructing additional pylons","New line? That\u2019s Ctrl+J.","Releasing the HypnoDrones","Pushing the button, Frank."]});import vt,{useState as $u}from"react";import{Box as Qo,Text as fn,useInput as Pu}from"ink";function zi({prompts:e,onSelect:o,onClose:t}){let[n,s]=$u(0);Pu((m,c)=>{c.escape&&t(),c.upArrow&&s(a=>Math.max(0,a-1)),c.downArrow&&s(a=>Math.min(e.length-1,a+1)),c.return&&e[n]&&o(e[n].id)});let r=Ie(2),l=10,u=0;if(e.length>l){let m=Math.floor(l/2);u=n-m,u<0?u=0:u+l>e.length&&(u=e.length-l)}let f=e.slice(u,u+l);return vt.createElement(Qo,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",padding:0,width:"100%"},vt.createElement(Qo,{paddingX:1,marginBottom:1},vt.createElement(fn,{color:"cyan",bold:!0},"\u{1F504} CODEBASE TIME TRAVEL: SELECT UNDO POINT")),vt.createElement(Qo,{paddingX:2,marginBottom:1},vt.createElement(fn,null,"Select a prompt to revert the codebase back to the state ",vt.createElement(fn,{bold:!0,color:"blue"},"immediately before")," it was executed:")),e.length===0?vt.createElement(Qo,{paddingX:2,paddingY:1},vt.createElement(fn,{italic:!0,color:"gray"},"No prompt checkpoints found for this session.")):vt.createElement(Qo,{flexDirection:"column",width:"100%"},u>0&&vt.createElement(Qo,{paddingX:2,marginBottom:1},vt.createElement(fn,{color:"gray",dimColor:!0},"\u25B2 (+",u," more prompts above)")),f.map((m,c)=>{let d=u+c===n,p=Nu(m.timestamp),h=m.changes?m.changes.length:0;return vt.createElement(Qo,{key:m.id,paddingX:1,backgroundColor:d?"#1a2a3a":void 0,width:"100%"},vt.createElement(Qo,{flexGrow:1},vt.createElement(fn,{color:d?"cyan":"white",bold:d},d?"\u276F ":" ",'"',_u(m.prompt),'"',vt.createElement(fn,{color:"gray",dimColor:!d}," [",p," \u2022 ",h," file(s) changed]"))))}),u+l<e.length&&vt.createElement(Qo,{paddingX:2,marginTop:1},vt.createElement(fn,{color:"gray",dimColor:!0},"\u25BC (+",e.length-(u+l)," more prompts below)"))),vt.createElement(Qo,{marginTop:1,paddingX:1,borderStyle:"single",borderLeft:!1,borderRight:!1,borderBottom:!1,borderColor:"cyan"},vt.createElement(fn,{dimColor:!0,italic:!0},"\u2191\u2193 navigate \u2022 Enter select undo point \u2022 Esc close")))}function _u(e){if(!e)return"";let t=(e.split(`
|
|
537
|
+
`)[0]||"").replace(/@\[(.*?)\]/g,(n,s)=>{let r=s.replace(/\\/g,"/").split("/");return`[${r[r.length-1]}]`});return t.length>69?t.slice(0,67)+"...":e.includes(`
|
|
538
|
+
`)?t+"...":t}function Nu(e){if(!e)return"N/A";let o=new Date(e);if(isNaN(o.getTime()))return"N/A";let t=l=>String(l).padStart(2,"0"),n=t(o.getHours()),s=t(o.getMinutes()),r=t(o.getSeconds());return`${n}:${s}:${r}`}var zl=re(()=>{rn()});import Bu from"puppeteer";import{exec as Uu}from"child_process";import{promisify as Ru}from"util";import Wu from"fs";var Jl,Ql,Zl,ec=re(()=>{Jl=Ru(Uu),Ql=()=>{try{let e=Bu.executablePath();if(e&&Wu.existsSync(e))return!0}catch{return!1}return!1},Zl=async e=>{e&&e("\u{1F4E5} Downloading Chromium engine (chrome@148)...");try{try{await Jl("pnpm exec puppeteer browsers install chrome@148")}catch{await Jl("npx -y puppeteer browsers install chrome@148")}return await new Promise(o=>setTimeout(o,1e3)),{success:!0}}catch(o){return console.error("[SETUP ERROR]",o),{success:!1,error:o.message}}}});var cc={};qr(cc,{default:()=>lc});import tc from"os";import i,{useState as V,useEffect as io,useRef as Zo,useMemo as Ur}from"react";import{Box as k,Text as y,useInput as Yu,useStdout as ju}from"ink";import ao from"fs-extra";import Kn from"path";import{exec as Ji}from"child_process";import{fileURLToPath as Gu}from"url";import oc from"ink-text-input";import sc from"gradient-string";function lc({args:e=[]}){let[o,t]=V(!1),[n,s]=V(10),{stdout:r}=ju(),[l,u]=V(""),[f,m]=V(0),[c,a]=V(!1),[d,p]=V("Flux"),[h,S]=V({columns:r?.columns||80,rows:r?.rows||24}),[T,w]=V(0),[I,L]=V(!1),[_,R]=V(!1),[v,b]=V(0),A=Zo(null);io(()=>{let x=Ms(),g=!["Terminal","Windows Terminal"].includes(x)||!!process.env.VSC_TERMINAL_URL,O=setTimeout(()=>{g&&!Vo()&&R(!0)},500),N=setInterval(()=>{Vo()&&R(!1)},1e3);return()=>{clearTimeout(O),clearInterval(N)}},[]);let F=Ur(()=>{let x={};for(let g=0;g<e.length;g++)if(e[g]==="--key"&&e[g+1]){let N=e[g+1];if(x.key=N,N.includes("@")){let M=N.split("@"),$=M[0],U=M[1].toLowerCase();if(["google","deepseek","openrouter"].includes(U)){let E="Google";U==="google"?E="Google":U==="deepseek"?E="DeepSeek":U==="openrouter"&&(E="OpenRouter"),x.key=$,x.provider=E}}}for(let g=0;g<e.length;g++){let O=e[g];if(O==="--key"){g++;continue}if(O==="--model"&&e[g+1])x.model=e[g+1],g++;else if(O==="--memory"&&e[g+1])x.memory=e[g+1].toLowerCase(),g++;else if(O==="--resume"&&e[g+1])x.resume=e[g+1],g++;else if(O==="--package"&&e[g+1]){let N=e[g+1].toLowerCase();["npm","pnpm","yarn","bun"].includes(N)&&(x.package=N),g++}else if(O==="--auto-del"&&e[g+1]){let N=e[g+1].toLowerCase();["1d","7d","30d"].includes(N)&&(x.autoDel=N),g++}else if(O==="--auto-exec"&&e[g+1])x.autoExec=e[g+1].toLowerCase(),g++;else if(O==="--yolo"&&e[g+1])x.autoExec=e[g+1].toLowerCase(),g++;else if(O==="--external-access"&&e[g+1])x.externalAccess=e[g+1].toLowerCase(),g++;else if(O==="--mode"&&e[g+1]){let M=e[g+1].toLowerCase();if(["flux","flow"].includes(M)){let $="Flux";M==="flux"?$="Flux":M==="flow"&&($="Flow"),x.mode=$}g++}else if(O==="--thinking"&&e[g+1]){let M=e[g+1].toLowerCase();if(["fast","low","medium","high","xhigh","standard"].includes(M)){let $="Medium";M==="fast"?$="Fast":M==="low"?$="Low":M==="standard"?$="Standard":M==="medium"?$="Medium":M==="high"?$="High":M==="xhigh"&&($="xHigh"),x.thinking=$}g++}else if(O==="--provider"&&e[g+1]){let N=e[g+1].toLowerCase();if(["google","deepseek","openrouter"].includes(N)){let M="Google";N==="google"?M="Google":N==="deepseek"?M="DeepSeek":N==="openrouter"&&(M="OpenRouter"),x.provider=M}g++}}return x},[e]),Q=async(x=!1,g=null)=>{let O=g||Yt;x&&W(N=>(ee(N.length+1),[...N,{id:"check-"+Date.now(),role:"system",text:"\u{1F50D} Checking for updates...",isMeta:!0}]));try{let M=await(await fetch("https://registry.npmjs.org/fluxflow-cli",{cache:"no-store"})).json(),$=M["dist-tags"]?.latest,U=M["dist-tags"]?.stable;if($&&Je($),$&&$!==Pn){let E=$===U?`v${$}-stable`:`v${$}`;!x&&O.autoUpdate?H("update"):W(D=>{let P=[...D],G=x?P.length:Math.min(P.length,3);return P.splice(G,0,{id:"update-"+Date.now(),role:"system",text:`A new version (${E}) is here.
|
|
534
539
|
|
|
535
540
|
\u2022 Type \`/update latest\` to apply the update.
|
|
536
|
-
\u2022 Type \`/changelog\` to view the release notes.`,isUpdateNotification:!0,isMeta:!0}),
|
|
541
|
+
\u2022 Type \`/changelog\` to view the release notes.`,isUpdateNotification:!0,isMeta:!0}),P})}else x&&W(E=>{ee(E.length+1);let D=$&&$===U?`${Pn}-stable`:Pn;return[...E,{id:"uptodate-"+Date.now(),role:"system",text:`\u2705 [SYSTEM] Flux Flow is already up to date (${D}).`,isMeta:!0}]})}catch(N){x&&W(M=>(ee(M.length+1),[...M,{id:"check-err-"+Date.now(),role:"system",text:`\u274C ERROR: Failed to check for updates: ${N.message}`,isMeta:!0}]))}};io(()=>{let x=()=>{r.write("\x1B[2J\x1B[3J\x1B[H"),S({columns:r.columns,rows:r.rows})};return r.on("resize",x),()=>{r.off("resize",x)}},[r]);let[j,Z]=V("Medium"),[B,z]=V("Google"),[mt,ce]=V(0),[Le,Je]=V(null),[ue,tt]=V(!1),[Ye,_e]=V("gemma-4-31b-it"),[Me,je]=V("gemma-4-26b-a4b-it"),[ye,ft]=V(!0),[pt,lo]=V(!0),Wt=Zo(0),[be,rt]=V(null),[Ao,co]=V(""),[Vt,H]=V("chat"),[Ge,Rr]=V("Free"),[zt,qn]=V({agentLimit:999999,backgroundLimit:999999,searchLimit:100,customModelId:"",customLimit:0}),[ht,Oo]=V(null),[Yt,te]=V({memory:!0,compression:0,autoExec:!1,autoDeleteHistory:"7d",autoUpdate:!1,updateManager:"npm",customUpdateCommand:""}),[ve,st]=V({name:null,nickname:null,instructions:null}),[de,he]=V({keyType:"Default",quality:"Low-High",apiKey:""}),[fe,it]=V({tokens:0}),[Bo,St]=V(0),[gt,Ne]=V(0),[ae,jt]=V(0),[at,go]=V(0),[xt,pn]=V(0),[ot,lt]=V(0),[Gt,Jt]=V(0),[en,vs]=V(0),[hr,gr]=V(0),[Vn,Zi]=V(0),[xr,As]=V(0),[_n,Os]=V(0),[se,Be]=V(null),[Ue,ct]=V(oi()),[Et,nt]=V(null),[Qt,xo]=V(""),[Zt,Lt]=V(!1),[uo,ko]=V(0),Nn=Zo(!0),Ds=Zo(!0),Wr=Zo(!0);io(()=>{if(!be)return;if(Nn.current){Nn.current=!1,setTimeout(()=>{Ds.current=!1,setTimeout(()=>{Wr.current=!1},1e3)},2e3);return}if(Ds.current||Wr.current)return;let x=Ie(2),g="",O="";Ge==="Free"?B==="Google"?(g="gemma-4-31b-it",O="Gemma 4 (Free default)"):B==="DeepSeek"?(g="deepseek-v4-flash",O="DeepSeek Flash (Free default)"):(g="google/gemma-4-31b-it:free",O="Gemma 4 (Free default)"):B==="Google"?(g="gemini-3-flash-preview",O="Gemini 3 Flash"):B==="DeepSeek"?(g="deepseek-v4-flash",O="DeepSeek Flash"):(g="deepseek/deepseek-v4-flash",O="DeepSeek Flash"),_e(g),Cn({apiTier:Ge,activeModel:g}),W(N=>(ee(N.length+1),[...N,{id:"tier-switch-"+Date.now(),role:"system",text:`\u26A0\uFE0F${x}**[TIER LIMIT]** Auto-switched to ${O}.`,isMeta:!0}]))},[Ge,B,be]);let Ls=Ur(()=>{let x=Ms(),g=!["Terminal","Windows Terminal"].includes(x)||!!process.env.VSC_TERMINAL_URL||!!process.env.INTELLIJ_TERMINAL_COMMAND_BLOCKS;return{isIDE:g,shortcut:g?"Shift + Enter":"Ctrl + Enter"}},[]),Se=Zo(null),Qe=Zo("");io(()=>{Se.current=Et},[Et]),io(()=>{Qe.current=Qt},[Qt]);let[yo,Re]=V(!1),[Ft,Uo]=V(null),[hn,yr]=V(null),tn=x=>{Uo(null),H("chat")},Yr=x=>{let g=Math.floor(x/3600),O=Math.floor(x%3600/60),N=x%60,M=[];return g>0&&M.push(`${g}h`),(O>0||g>0)&&M.push(`${O}m`),M.push(`${N}s`),M.join(" ")},Ro=x=>x<1e3?`${x}ms`:Yr(Math.floor(x/1e3)),[zn,Jn]=V(null),[wr,Tr]=V("");io(()=>{let x;if(zn){let g=()=>{let O=Vi[Math.floor(Math.random()*Vi.length)];Tr(O)};wr||g(),x=setInterval(g,5e3)}else Tr("");return()=>clearInterval(x)},[zn]);let[Sr,Qn]=V(!0),[gn,jr]=V(!1),[Wo,xn]=V(!1),[Zn,Gr]=V(null),[J,He]=V(0),[yt,K]=V([]),qe=Zo(null),[eo,Fe]=V(null),[Yo,on]=V(null),[Bn,bt]=V(null);io(()=>He(0),[l]);let[$t,W]=V(()=>{let x={id:"logo-"+Date.now(),role:"system",text:pr,isLogo:!0,isMeta:!0},g={id:"welcome",role:"system",text:"\u{1F30A}\u26A1 Welcome to Flux Flow! Type /help for commands.",isMeta:!0},O=process.cwd()===tc.homedir(),N=(()=>{let $=process.cwd().toLowerCase();if(process.platform==="win32"){let U=process.env.SystemRoot?.toLowerCase()||"c:\\windows",E=process.env.ProgramFiles?.toLowerCase()||"c:\\program files",D=process.env["ProgramFiles(x86)"]?.toLowerCase()||"c:\\program files (x86)";return $.startsWith(U)||$.startsWith(E)||$.startsWith(D)}else return $==="/"||["/bin","/sbin","/etc","/usr","/var","/root"].some(E=>$.startsWith(E))})(),M=[x,g];return N?M.push({id:"system-warning",role:"system",text:"\u{1F6D1} [CRITICAL SECURITY ALERT] SYSTEM DIRECTORY DETECTED",subText:`You are currently in a PROTECTED SYSTEM DIRECTORY (${process.cwd()}). Operating here is EXTREMELY dangerous as the agent could accidentally corrupt your OS or installed applications. PLEASE MOVE TO A PROJECT FOLDER FOR SAFETY.`,isHomeWarning:!0,isMeta:!0}):O&&M.push({id:"home-warning",role:"system",text:"[SECURITY ALERT] HOME DIRECTORY DETECTED",subText:`You are currently in ${tc.homedir()}. Working here is high-risk as the agent may modify system-sensitive configurations. Please move to a project folder for safety.`,isHomeWarning:!0,isMeta:!0}),M}),Do=Zo(null),[Fs,ee]=V($t.length),Hr=Ur(()=>{let g=h.columns||80,O=0,N=0;for(let M=$t.length-1;M>=0;M--){let $=$t[M];if(!$)continue;let U=$.text||"",E=U.split(/\r?\n/).length;if(U.split(/\r?\n/).forEach(D=>{E+=Math.floor(D.length/g)}),$.isHelpRecord&&(E=15),$.isUpdateNotification&&(E=8),$.isTerminalRecord&&(E=10),E+=$.role==="think"?3:2,O+E>2e3){N=M+1;break}O+=E}return{items:$t.slice(N,Fs),isTruncated:N>0}},[$t,h.columns,h.rows]),ie=Ur(()=>{if(!Et||!Qt)return!1;let x=Qt.trim();return x.endsWith("?")||x.endsWith(":")||/\[[yYnN/]+\]\s*$/.test(x)||/\([yYnN]\)\s*$/.test(x)},[Et,Qt]);Yu((x,g)=>{if(!(x==="\x1B[I"||x==="\x1B[O"||x==="[I"||x==="[O")){if(_){let O=Ms(),N=ic(O);if(g.upArrow)b(M=>M>0?M-1:N.length-1);else if(g.downArrow)b(M=>M<N.length-1?M+1:0);else if(g.return){let M=N[v];if(M.action==="dismiss")R(!1);else if(M.url){let $=process.platform==="win32"?`start ${M.url}`:process.platform==="darwin"?`open ${M.url}`:`xdg-open ${M.url}`;Ji($),R(!1)}}return}if(g.tab&&Et){Lt(O=>!O);return}if(Zt&&Et){if(g.return){let O=process.platform==="win32";Mo(O?`\r
|
|
537
542
|
`:`
|
|
538
|
-
`)
|
|
539
|
-
`)}else if(g.backspace||g.delete)
|
|
540
|
-
`)}}),
|
|
543
|
+
`),$o||xo(N=>N+`
|
|
544
|
+
`)}else if(g.backspace||g.delete)$o?Mo("\x7F"):(Mo("\b \b"),xo(O=>O.slice(0,-1)));else if(g.upArrow)Mo(g.shift?"\x1B[1;2A":"\x1B[A");else if(g.downArrow)Mo(g.shift?"\x1B[1;2B":"\x1B[B");else if(g.rightArrow)Mo(g.shift?"\x1B[1;2C":"\x1B[C");else if(g.leftArrow)Mo(g.shift?"\x1B[1;2D":"\x1B[D");else if(g.escape)Mo("\x1B");else if(g.ctrl&&x){let O=x.toLowerCase().charCodeAt(0);O>=97&&O<=122?Mo(String.fromCharCode(O-96)):Mo(x)}else x&&(Mo(x),$o||xo(O=>O+x));return}if(g.escape){if(Ce.length>0&&Vt==="chat"){L(!0);return}if(o){t(!1);return}if(gn||Et)Wo?($l(),ba(),xn(!1),Zn&&clearTimeout(Zn)):(xn(!0),Zn&&clearTimeout(Zn),Gr(setTimeout(()=>xn(!1),3e3)));else if(Vt==="revert")H("chat"),He(0);else if(Vt!=="chat"&&Vt!=="settings")H("chat");else{if(!be&&mt===1){ce(0),co("");return}He(O=>{let N=O+1;return N===1?(qe.current&&clearTimeout(qe.current),qe.current=setTimeout(()=>He(0),2e3)):N===2&&(qe.current&&clearTimeout(qe.current),He(0),l.length>0?u(""):kt.getChatHistory(Ue).then(M=>{M.length>0?(K(M.reverse()),H("revert")):W($=>(ee($.length+1),[...$,{id:"revert-empty-"+Date.now(),role:"system",text:"\u{1F6C8} No revert checkpoints found for this session.",isMeta:!0}]))})),N})}}if(Ce.length>0&&Vt==="chat"){if(g.upArrow){w(O=>O>0?O-1:Ce.length-1);return}if(g.downArrow){w(O=>O<Ce.length-1?O+1:0);return}if(g.return)return}if(g.tab,g.ctrl&&x==="c"&&Vt!=="exit"){if(l.length>0){u("");return}if(g.shift){H("exit"),t(!1);return}o?(H("exit"),t(!1)):t(!0)}g.return&&(g.shift||g.ctrl||g.meta||g.leftAlt||g.rightAlt)&&u(O=>O.replace(/\\\r?$/,"").replace(/\r?$/,"")+`
|
|
545
|
+
`)}}),io(()=>{process.stdout.write("\x1B[?1004h");let x=g=>{let O=g.toString();O.includes("\x1B[I")?(lo(!0),Wt.current=Date.now()):O.includes("\x1B[O")&&(lo(!1),Wt.current=Date.now())};return process.stdin.on("data",x),()=>{process.stdout.write("\x1B[?1004l"),process.stdin.off("data",x)}},[]),io(()=>{async function x(){try{let U=JSON.parse(ao.readFileSync(Kn.join(process.cwd(),"package.json"),"utf8"));Fi(Pn||U.version||"2.0.0")}catch{Fi("2.0.0")}process.stdout.isTTY&&(process.stdout.write("\x1B]0;FluxFlow\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow\x07")),Ql()||(W(U=>(ee(U.length+1),[...U,{id:"setup-"+Date.now(),role:"system",text:"\u{1F527} [SYSTEM] Installing Required dependencies... (One-time setup)",isMeta:!0}])),await Zl(),W(U=>(ee(U.length+1),[...U,{id:"setup-done-"+Date.now(),role:"system",text:"\u2705 [SYSTEM] All dependencies installed successfully.",isMeta:!0}])));let g=await or();F.mode?p(F.mode):p(g.mode),F.thinking?Z(F.thinking):Z(g.thinkingLevel);let O=F.provider||g.aiProvider||"Google";z(O);let N=g.apiTier||"Free";if(A.current=g.activeModel,F.model)_e(F.model);else if(F.provider){let U="";N==="Free"?O==="Google"?U="gemma-4-31b-it":O==="DeepSeek"?U="deepseek-v4-flash":U="google/gemma-4-31b-it:free":O==="Google"?U="gemini-3-flash-preview":O==="DeepSeek"?U="deepseek-v4-flash":U="deepseek/deepseek-v4-flash",_e(U)}else _e(g.activeModel);tt(g.showFullThinking),Rr(g.apiTier||"Free"),qn(g.quotas||{agentLimit:999999,backgroundLimit:999999,searchLimit:100,customModelId:"",customLimit:0});let M={memory:!0,compression:0,autoExec:!1,autoDeleteHistory:"7d",autoUpdate:!1,updateManager:"npm",customUpdateCommand:"",...g.systemSettings||{}};F.memory==="on"?M.memory=!0:F.memory==="off"&&(M.memory=!1),F.package&&(M.updateManager=F.package),F.autoDel&&(M.autoDeleteHistory=F.autoDel),F.autoExec==="on"?M.autoExec=!0:F.autoExec==="off"&&(M.autoExec=!1),F.externalAccess==="on"?M.allowExternalAccess=!0:F.externalAccess==="off"&&(M.allowExternalAccess=!1),te(M),st(g.profileData),he(g.imageSettings||{keyType:"Default",quality:"Low-High",apiKey:""});let $=F.key;if($||($=await Zr(O)),$&&(rt($),Br($,{aiProvider:O,onIDEApproval:tn})),g.systemSettings?.autoDeleteHistory&&Ua(g.systemSettings.autoDeleteHistory),Ra(Io),Q(!1,M),await Ga(),F.resume){let U=await _o(),E=F.resume;if(U[E]){ct(E);let D=[...U[E].messages];D[0]?.text?.includes("\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557")||D.unshift({id:"welcome-"+Date.now(),role:"system",text:pr+`
|
|
541
546
|
|
|
542
|
-
\u{1F30A}\u26A1 Resuming Flux Flow Session...`,isMeta:!0}),
|
|
547
|
+
\u{1F30A}\u26A1 Resuming Flux Flow Session...`,isMeta:!0}),W(D),H("chat"),W(G=>{let q=[...G,{id:"sys-"+Date.now(),role:"system",text:`\u{1F4E1} SESSION RESUMED VIA CLI: [${E}]`,isMeta:!0}];return ee(q.length),q})}else W(D=>[...D,{id:"sys-err-"+Date.now(),role:"system",text:`\u274C ERROR: Chat session [${E}] not found. Started new session.`,isMeta:!0}])}ft(!1)}x()},[]),io(()=>{let x;return o&&(s(10),x=setInterval(()=>{s(g=>g<=1?(t(!1),0):g-1)},1e3)),()=>{x&&clearInterval(x)}},[o]),io(()=>{if(!ye){let x=F.model&&Ye===F.model?A.current:Ye;Cn({mode:d,thinkingLevel:j,aiProvider:B,activeModel:x||Ye,showFullThinking:ue,systemSettings:Yt,profileData:ve,imageSettings:de,apiTier:Ge})}},[d,j,B,Ye,ue,Yt,ve,de,ye,F,Ge]);let Ae=async x=>{let g=x.trim(),O=30;if(B==="OpenRouter"&&(O=10),B==="DeepSeek"&&(O=20),g.length>=O){await es(B,g),rt(g),Br(g,{aiProvider:B,onIDEApproval:tn});let N="gemma-4-31b-it";B==="OpenRouter"?N="google/gemma-4-31b-it:free":B==="DeepSeek"&&(N="deepseek-v4-flash"),_e(N),W(M=>[...M,{role:"system",text:`\u2705 ${B} API Key saved successfully! Model set to ${N}. Initialization complete.`,isMeta:!0}])}else W(N=>[...N,{role:"system",text:`\u274C INVALID KEY: ${B} API keys must be at least ${O} characters.`,isMeta:!0}]),co("")},Xe=Zo(Qi);io(()=>{if(Vt==="exit"){(async()=>{let O=Date.now(),N=Math.floor((O-Xe.current)/1e3);N>=1&&(await Co("duration",N),Xe.current+=N*1e3),await Ha()})();let g=setTimeout(()=>{process.exit(0)},1700);return()=>clearTimeout(g)}},[Vt]),io(()=>{let x=setInterval(async()=>{if(!ye){let g=Date.now(),O=Math.floor((g-Xe.current)/1e3);O>=1&&(await Co("duration",O),Xe.current+=O*1e3)}},1500);return()=>clearInterval(x)},[ye]);let Ve=[{cmd:"/quit",desc:"Exit and shutdown Flux"},{cmd:"/help",desc:"Show all available commands"},{cmd:"/clear",desc:"Clear terminal screen"},{cmd:"/resume",desc:"Load previous session"},{cmd:"/revert",desc:"Revert codebase back to a checkpoint"},{cmd:"/gemini",desc:"Get a happy message from Gemini CLI"},{cmd:"/save",desc:"Force save current chat"},{cmd:"/export",desc:"Export current chat in a .txt file"},{cmd:"/chats",desc:"List all chat sessions"},{cmd:"/mode",desc:"Toggle Flux/Flow modes",subs:[{cmd:"flux",desc:"Enable Dev toolset"},{cmd:"flow",desc:"Enable Chat mode"}]},{cmd:"/thinking",desc:"Set AI reasoning depth",subs:B==="DeepSeek"?[{cmd:"Fast",desc:"Fastest"},{cmd:"Standard",desc:"Standard Reasoning"},{cmd:"xHigh",desc:"Extended Reasoning"}]:B==="OpenRouter"?[{cmd:"Fast",desc:"Fastest"},{cmd:"Low",desc:"Quick Reasoning"},{cmd:"Medium",desc:"Balanced Reasoning"},{cmd:"High",desc:"Deep Reasoning"},{cmd:"xHigh",desc:"Extended Reasoning"}]:Ye&&Ye.toLowerCase().startsWith("gemini-3")?[{cmd:"Fast",desc:"Fastest"},{cmd:"Low",desc:"Quick Reasoning"},{cmd:"Medium",desc:"Balanced Reasoning"},{cmd:"High",desc:"Deep Reasoning"}]:[{cmd:"Fast",desc:"Fastest"},{cmd:"Low",desc:"Quick Reasoning"},{cmd:"Medium",desc:"Balanced Reasoning"},{cmd:"High",desc:"Deep Reasoning"},{cmd:"xHigh",desc:"Extended Reasoning"}]},{cmd:"/model",desc:"Switch Model for Agent",subs:B==="OpenRouter"?Ge==="Free"?[{cmd:"google/gemma-4-31b-it:free",desc:"Multimodal"},{cmd:"moonshotai/kimi-k2.6:free",desc:"Multimodal"},{cmd:"qwen/qwen3-coder:free",desc:""},{cmd:"z-ai/glm-4.5-air:free",desc:""}]:[{cmd:"google/gemini-3.5-flash",desc:"Multimodal"},{cmd:"qwen/qwen3.7-plus",desc:"Multimodal"},{cmd:"minimax/minimax-m3",desc:"Multimodal"},{cmd:"anthropic/claude-sonnet-4.5",desc:"Multimodal"},{cmd:"anthropic/claude-opus-4.6",desc:"Multimodal"},{cmd:"anthropic/claude-opus-4.8",desc:"Multimodal"},{cmd:"deepseek/deepseek-v4-pro",desc:""},{cmd:"deepseek/deepseek-v4-flash",desc:""},{cmd:"xiaomi/mimo-v2.5-pro",desc:""},{cmd:"z-ai/glm-5",desc:""},{cmd:"openai/gpt-5.2-codex",desc:"Multimodal"},{cmd:"openai/gpt-5.2-pro",desc:"Multimodal"},{cmd:"openai/gpt-5.5-pro",desc:"Multimodal"},{cmd:"moonshotai/kimi-k2.6",desc:"Multimodal"}]:B==="DeepSeek"?[{cmd:"deepseek-v4-flash",desc:"Fast & Efficient"},{cmd:"deepseek-v4-pro",desc:"High-Intelligence Reasoning"}]:Ge==="Free"?[{cmd:"gemma-4-26b-a4b-it",desc:"Standard & Faster"},{cmd:"gemma-4-31b-it",desc:"Standard Default"},{cmd:"gemini-2.5-flash",desc:"Fast & Reliable (Limited Free Quota)"},{cmd:"gemini-3-flash-preview",desc:"Fast & Lightweight (Limited Free Quota)"},{cmd:"gemini-3.5-flash",desc:"Flash Latest (Limited Free Quota) [Instability Issues]"}]:[{cmd:"gemini-2.5-flash",desc:"Fast & Reliable"},{cmd:"gemini-3.1-flash-lite",desc:"Ultra-Fast & Lite"},{cmd:"gemini-3-flash-preview",desc:"Default, Fast & Lightweight"},{cmd:"gemini-3.5-flash",desc:"Flash Latest [Instability Issues]"},{cmd:"gemini-3.1-pro-preview",desc:"Pro Reasoning"}]},{cmd:"/settings",desc:"Configure system prefs"},{cmd:"/key",desc:"Manage API keys"},{cmd:"/profile",desc:"Edit developer persona"},{cmd:"/memory",desc:"Manage agent memory"},{cmd:"/stats",desc:"Show session usage"},{cmd:"/reset",desc:"Wipe all project data"},{cmd:"/about",desc:"Project info & credits"},{cmd:"/changelog",desc:"View latest updates"},{cmd:"/fluxflow",desc:"Project management",subs:[{cmd:"init",desc:"Create FluxFlow.md template"}]},{cmd:"/update",desc:"Check/Install updates",subs:[{cmd:"check",desc:"Check for new version"},{cmd:"latest",desc:"Install latest release"}]}],wt=async(x,g=!1)=>{if(!g&&Ce.length>0){let M=Ce[T]||Ce[0],$=x.split(" ");if($.length===1)u(M.cmd+" ");else{let U=$.slice(0,-1);u(U.join(" ")+" "+M.cmd+" ")}w(0),m(U=>U+1);return}let O=x.replace(/\r\n/g,`
|
|
543
548
|
`).replace(/\r/g,`
|
|
544
|
-
`).trimEnd();if(O.endsWith("\\")){
|
|
545
|
-
`);return}let
|
|
546
|
-
`).split(/\r?\n/).map(
|
|
547
|
-
`);if(
|
|
548
|
-
${
|
|
549
|
+
`).trimEnd();if(O.endsWith("\\")){u(O.slice(0,-1)+`
|
|
550
|
+
`);return}let N=O.replace(/\\\s*\n/g,`
|
|
551
|
+
`).split(/\r?\n/).map(M=>M.replace(/\\$/,"")).join(`
|
|
552
|
+
`);if(N.trim()){if(gn){let M=N.trim();if(M.startsWith("/")){W($=>(ee($.length+1),[...$,{id:"hint-err-"+Date.now(),role:"system",text:"\u274C [RESTRICTED] Steering Hints cannot start with /",isMeta:!0}])),u("");return}Fe(M),Do.current=M,W($=>(ee($.length+1),[...$,{id:"hint-"+Date.now(),role:"user",text:`[STEERING HINT: QUEUED]
|
|
553
|
+
${M}`,color:"magenta"}])),u("");return}if(!be){Ae(N),co("");return}if(N.startsWith("/")){let M=N.split(" "),$=M[0]?.toLowerCase();switch($){case"/quit":{H("exit");break}case"/resume":{if(M[1]){let E=M[1];(async()=>{let P=await _o(),G=P[E]||Object.values(P).find(q=>q.name.toLowerCase()===E.toLowerCase());if(G){r.write("\x1B[2J\x1B[3J\x1B[H"),ct(E);let q=[...G.messages];q[0]?.text?.includes("\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557")||(q.unshift({id:"welcome-"+Date.now(),role:"system",text:"\u{1F30A}\u26A1 Resuming Flux Flow Session...",isMeta:!0}),q.unshift({id:"logo-"+Date.now(),role:"system",text:pr,isLogo:!0,isMeta:!0})),W(q),W(ge=>[...ge,{id:"sys-"+Date.now(),role:"system",text:`\u{1F4E1} SESSION RESUMED: [${E}]`,isMeta:!0}]),ee(0)}else W(q=>[...q,{id:"err-"+Date.now(),role:"system",text:`\u274C ERROR: Session [${E}] not found.`}])})()}else H("resume");break}case"/clear":{W([{id:"logo-"+Date.now(),role:"system",text:pr,isLogo:!0,isMeta:!0},{id:"welcome-"+Date.now(),role:"system",text:"\u{1F30A}\u26A1 Welcome back to Flux Flow! Context cleared.",isMeta:!0}]),ee(2),ct(oi()),it({tokens:0}),a(!1);break}case"/revert":{kt.getChatHistory(Ue).then(E=>{if(E.length>0)K(E.reverse()),H("revert");else{let D=Ie(2);W(P=>(ee(P.length+1),[...P,{id:"revert-empty-"+Date.now(),role:"system",text:"No revert checkpoints found for this session.",isMeta:!0}]))}});break}case"/mode":{if(M[1]){let E=M[1].toLowerCase()==="flow"?"Flow":"Flux";p(E),E==="Flow"?Z("Fast"):E==="Flux"&&Z("High");let D=Ie(2);W(P=>(ee(P.length+1),[...P,{id:Date.now(),role:"system",text:`\u{1F527}${D}[SYSTEM] Mode switched to ${E}`,isMeta:!0}]))}else H("mode");break}case"/image":{if(M[1]?.toLowerCase()==="stats"){let E=Ie(2);if(de.keyType==="Custom")W(D=>(ee(D.length+1),[...D,{id:Date.now(),role:"system",text:`\u{1F517}${E}[SYSTEM] Key strategy is Custom. Redirecting to Pollinations dashboard (https://enter.pollinations.ai/#pollen)...`,isMeta:!0}])),Ji("start https://enter.pollinations.ai/#pollen");else try{let D=await ps();W(P=>(ee(P.length+1),[...P,{id:Date.now(),role:"system",isImageStats:!0,text:`\u2022 Hourly Limit: ${Number((D.limit*1e3).toFixed(0))} credits
|
|
549
554
|
\u2022 Spent (Last 1hr): ${Number((D.totalSpent*1e3).toFixed(0))} credits
|
|
550
555
|
\u2022 Remaining: ${Number((D.remaining*1e3).toFixed(0))} credits
|
|
551
556
|
\u2022 Requests (Last 1hr): ${D.activeCallsCount} requests
|
|
552
|
-
`+(D.nextResetMin>0?`\u2022 Refreshes in: ${D.nextResetMin}m`:""),isMeta:!0}]))}catch{
|
|
553
|
-
`);try{
|
|
554
|
-
`);
|
|
555
|
-
${
|
|
556
|
-
\u{1F539} Status: ${
|
|
557
|
-
\u{1F539} Released on: ${
|
|
557
|
+
`+(D.nextResetMin>0?`\u2022 Refreshes in: ${D.nextResetMin}m`:""),isMeta:!0}]))}catch{W(P=>(ee(P.length+1),[...P,{id:Date.now(),role:"system",text:"\u274C [SYSTEM] Failed to load image quota stats.",isMeta:!0}]))}}else if(M[1]?.toLowerCase()==="setup")if(M[2]?.toLowerCase()==="key")if(M[3]){let E=["default","custom"].find(D=>D===M[3].toLowerCase());if(E){let D=E==="default"?"Default":"Custom";he(G=>({...G,keyType:D}));let P=Ie(2);W(G=>(ee(G.length+1),[...G,{id:Date.now(),role:"system",text:`\u{1F527}${P}[SYSTEM] Image key strategy set to ${D}`,isMeta:!0}])),D==="Custom"&&(Oo({label:"Enter Pollinations API key (starting with sk_):",note:"Get a key from https://enter.pollinations.ai",key:"imageSettings",subKey:"apiKey",value:de.apiKey||"",returnView:"chat"}),H("input"))}else{let D=Ie(2);W(P=>(ee(P.length+1),[...P,{id:Date.now(),role:"system",text:"\u274C [SYSTEM] Invalid key option. Choose: Default or Custom.",isMeta:!0}]))}}else{let E=Ie(2);W(D=>(ee(D.length+1),[...D,{id:Date.now(),role:"system",text:"\u274C [SYSTEM] Usage: /image setup Key <Default|Custom>",isMeta:!0}]))}else if(M[2]?.toLowerCase()==="quality")if(M[3]){let E=["low","low-high","medium","medium-high","high","ultra","premium"].find(D=>D===M[3].toLowerCase());if(E){let P={low:"Low","low-high":"Low-High",medium:"Medium","medium-high":"Medium-High",high:"High",ultra:"Ultra",premium:"Premium"}[E];he(q=>({...q,quality:P}));let G=Ie(2);W(q=>(ee(q.length+1),[...q,{id:Date.now(),role:"system",text:`\u{1F527}${G}[SYSTEM] Image quality set to ${P}`,isMeta:!0}]))}else{let D=Ie(2);W(P=>(ee(P.length+1),[...P,{id:Date.now(),role:"system",text:"\u274C [SYSTEM] Invalid quality level. Choose from: Low, Low-High, Medium, Medium-High, High, Ultra, Premium.",isMeta:!0}]))}}else{let E=Ie(2);W(D=>(ee(D.length+1),[...D,{id:Date.now(),role:"system",text:"\u274C [SYSTEM] Usage: /image setup Quality <Low|Low-High|Medium|Medium-High|High|Ultra>",isMeta:!0}]))}else{let E=Ie(2);W(D=>(ee(D.length+1),[...D,{id:Date.now(),role:"system",text:"\u274C [SYSTEM] Usage: /image setup <Key|Quality> ...",isMeta:!0}]))}else{let E=Ie(2);W(D=>(ee(D.length+1),[...D,{id:Date.now(),role:"system",text:"\u274C [SYSTEM] Usage: /image setup <Key|Quality> ...",isMeta:!0}]))}break}case"/thinking":{let E;if(M[1]){let D=M[1].toLowerCase(),P=M.includes("--bypass");if(E=D.charAt(0).toUpperCase()+D.slice(1),D==="xhigh"&&(E="xHigh"),!P&&d==="Flow"&&(E==="Medium"||E==="High"||E==="xHigh"))W(G=>(ee(G.length+1),[...G,{id:Date.now(),role:"system",text:`\u274C [RESTRICTED] "${E}" is restricted in Flow mode. Switch to Flux to enable Higher Thinking Levels.`,isMeta:!0}]));else{Z(E);let G=Ie(1);W(q=>(ee(q.length+1),[...q,{id:Date.now(),role:"system",text:`\u{1F527} [SYSTEM] Thinking level set to ${E}${P?` (Bypass Activated \u{1F575}\uFE0F${G})`:""}`,isMeta:!0}]))}}else H("thinking");break}case"/model":{if(M[1]){let E=M.slice(1).join(" ");if(E==="gemma-4-31b-it"&&Ge!=="Free"&&B==="Google")W(D=>(ee(D.length+1),[...D,{id:Date.now(),role:"system",text:"\u274C **[ACCESS DENIED]** Gemma is restricted to the Free API tier. Automatically switching you to **Gemini 3 Flash Preview** for optimal performance.",isMeta:!0}])),_e("gemini-3-flash-preview");else{_e(E);let D=Ie(2);W(P=>(ee(P.length+1),[...P,{id:Date.now(),role:"system",text:`\u{1F527}${D}[SYSTEM] Model switched to ${E}`,isMeta:!0}]))}}else H("model");break}case"/settings":{H("settings");break}case"/key":{H("key");break}case"/profile":{H("profile");break}case"/stats":{(async()=>{let D=await An();Be(D),H("stats")})();break}case"/save":{let E=M.slice(1).join(" ")||`Session ${new Date().toLocaleTimeString()}`;ms(Ue,E,$t),W(D=>(ee(D.length+1),[...D,{id:Date.now(),role:"system",text:`\u{1F4BE} [MEMORY] Chat saved as "${E}" (ID: ${Ue})`,isMeta:!0}]));break}case"/export":{let E=`export-fluxflow-${Ue}.txt`,D=Kn.join(process.cwd(),E),P=[],G=!1;for(let $e=0;$e<$t.length;$e++){let ge=$t[$e];if(ge&&!(ge.role==="system"||ge.isMeta||ge.isLogo||String(ge.id).startsWith("welcome"))){if(ge.role==="user"){let Oe=ge.text||"";Oe=Oe.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),P.length>0&&P.push(""),P.push("[USER]"),P.push(Oe),G=!1}else if(ge.role==="think"){G||(P.push(""),P.push("[AGENT]"),G=!0);let Oe=(ge.text||"").replace(/\[turn:\s*continue\]/gi,"").replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").replace(/\[TOOL RESULTS\]/gi,"").trim();Oe&&(P.push("[thoughts]"),P.push(Oe))}else if(ge.role==="agent"){G||(P.push(""),P.push("[AGENT]"),G=!0);let Oe=zu(ge.text||"");for(let Pe of Oe)if(Pe.type==="output"){let Ke=Pe.content.replace(/\[turn:\s*continue\]/gi,"").replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").replace(/\[TOOL RESULTS\]/gi,"").trim();Ke&&(P.push("[output]"),P.push(Ke))}else Pe.type==="tool"&&(P.push("[tool]"),P.push(`${Pe.toolName} ${Pe.args}`))}}}let q=P.join(`
|
|
558
|
+
`);try{ao.writeFileSync(D,q,"utf8"),W($e=>(ee($e.length+1),[...$e,{id:Date.now(),role:"system",text:`\u{1F4E4} [EXPORT] Chat exported successfully to "${E}"`,isMeta:!0}]))}catch($e){W(ge=>(ee(ge.length+1),[...ge,{id:Date.now(),role:"system",text:`\u274C [EXPORT ERROR] Failed to export chat: ${$e.message}`,isMeta:!0}]))}break}case"/chats":{(async()=>{let D=await _o(),P=Object.entries(D).map(([G,q])=>`\u2022 ${G}: ${q.name}`).join(`
|
|
559
|
+
`);W(G=>(ee(G.length+1),[...G,{id:Date.now(),role:"system",text:`\u{1F5C3}\uFE0F [HISTORY] Saved Chats:
|
|
560
|
+
${P||"No saved chats found."}`,isMeta:!0}]))})();break}case"/memory":{H("memory");break}case"/reset":{(async()=>{try{W(D=>(ee(D.length+1),[...D,{id:Date.now(),role:"system",text:"\u2622\uFE0F [NUCLEAR] Initiating reset...",isMeta:!0}])),ao.existsSync(Io)&&ao.removeSync(Io),ao.existsSync(ro)&&ao.removeSync(ro),ao.existsSync(no)&&ao.removeSync(no);try{ao.readdirSync(Un).length===0&&ao.removeSync(Un)}catch{}setTimeout(()=>{H("exit"),setTimeout(()=>process.exit(0),500)},500)}catch(D){W(P=>(ee(P.length+1),[...P,{id:Date.now(),role:"system",text:`\u274C [RESET ERROR] Failed to purge data: ${D.message}`}]))}})();break}case"/about":{let E=Ie(2),D=`\u{1F539} FluxFlow Version: v${Pn}
|
|
561
|
+
\u{1F539} Status: ${Le&&Le!==Pn?`Update Available [v${Le}]`:"Up to date"}
|
|
562
|
+
\u{1F539} Released on: ${Ku}`;W(P=>(ee(P.length+1),[...P,{id:"about-"+Date.now(),role:"system",text:D,isAboutRecord:!0,isMeta:!0}]));break}case"/changelog":{let E=process.platform;Ji(`${E==="win32"?"start":E==="darwin"?"open":"xdg-open"} ${nc}`),W(P=>(ee(P.length+1),[...P,{id:Date.now(),role:"system",text:`\u{1F310} [BROWSER] Opening changelog: ${nc}`,isMeta:!0}]));break}case"/fluxflow":{if(M.slice(1)[0]==="init"){let D=`# FluxFlow Configuration
|
|
558
563
|
# This file defines project-specific instructions for the Flux Flow Agent.
|
|
559
564
|
|
|
560
565
|
# IDENTITY & TONE
|
|
@@ -569,35 +574,31 @@ ${N||"No saved chats found."}`,isMeta:!0}]))})();break}case"/memory":{j("memory"
|
|
|
569
574
|
|
|
570
575
|
# SKILLS & WORKFLOWS
|
|
571
576
|
- [Define custom step-by-step recipes for this project here]
|
|
572
|
-
`,
|
|
577
|
+
`,P=Kn.join(process.cwd(),"FluxFlow.md");if(ao.pathExistsSync(P))W(G=>(ee(G.length+1),[...G,{id:"init-err-"+Date.now(),role:"system",text:"\u274C ERROR: FluxFlow.md already exists in this directory.",isMeta:!0}]));else try{ao.writeFileSync(P,D),W(G=>(ee(G.length+1),[...G,{id:"init-ok-"+Date.now(),role:"system",text:"\u2705 [SUCCESS] FluxFlow.md has been initialized. You can now customize it for this project.",isMeta:!0}]))}catch(G){W(q=>(ee(q.length+1),[...q,{id:"init-err-"+Date.now(),role:"system",text:`\u274C ERROR: Failed to initialize FluxFlow.md: ${G.message}`,isMeta:!0}]))}}else W(D=>(ee(D.length+1),[...D,{id:"ff-err-"+Date.now(),role:"system",text:"\u2753 Usage: /fluxflow init",isMeta:!0}]));break}case"/update":{if(M[1]?.toLowerCase()==="check"){Q(!0);break}let D=M.includes("--latest");H("update");break}case"/gemini":{let E=qi[Math.floor(Math.random()*qi.length)];W(D=>(ee(D.length+1),[...D,{id:Date.now(),role:"system",text:`\u2728 [GEMINI CLI] ${E}`}])),u("");break}case"/help":{W(E=>(ee(E.length+1),[...E,{id:Date.now(),role:"system",isHelpRecord:!0,isMeta:!0}]));break}default:let U=Ie(2);W(E=>(ee(E.length+1),[...E,{id:Date.now(),role:"system",text:`\u{1F527}${U}[SYSTEM] Unknown command: ${$}`,isMeta:!0}]))}}else{let M=`[Prompted on: ${new Date().toLocaleString(void 0,{year:"numeric",month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit"})}]`,$={id:"user-"+Date.now(),role:"user",text:`${N}
|
|
573
578
|
|
|
574
|
-
${
|
|
579
|
+
${M}`};W(E=>(ee(E.length+1),[...E,$])),(async()=>{let E=!1;jr(!0),a(!1);let D=Date.now(),P=!0;try{let G=[...$t,$].filter(Y=>Y.role!=="think"&&!Y.isVisualFeedback&&!Y.isMeta&&!String(Y.id).startsWith("welcome")),q=[];G.forEach((Y,le)=>{let me=Y.fullText||Y.text;if(Y.role==="user"&&le<G.length-1){let De=me.lastIndexOf("[USER]");De!==-1&&(me=me.substring(De+6).trim())}if(Y.role==="system"&&me?.startsWith("[TOOL RESULT]")){let De=q[q.length-1];if(De&&De.role==="system"&&De.text?.startsWith("[TOOL RESULT]")){De.text+=`
|
|
575
580
|
|
|
576
|
-
`+me;return}}
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
`)}else me=ye.replace(/\r\n/g,`
|
|
580
|
-
`);let Te=`[TERMINAL_RECORD]
|
|
581
|
-
COMMAND: ${Ce.current}
|
|
582
|
-
PTY: ${Io}
|
|
581
|
+
`+me;return}}q.push({...Y,text:me})});let $e=Nl(Ye,q,{profile:ve,thinkingLevel:j,mode:d,systemSettings:Yt,janitorModel:Me,sessionStats:fe,chatId:Ue,aiProvider:B,apiKey:be,apiTier:Ge,cols:h.columns-6,rows:30,onExecStart:Y=>{nt(Y),xo("")},onExecChunk:Y=>{xo(le=>le+Y)},onExecEnd:()=>{W(Y=>{if(!Se.current)return Y;let le=Qe.current||"",me=Lr(le),De=`[TERMINAL_RECORD]
|
|
582
|
+
COMMAND: ${Se.current}
|
|
583
|
+
PTY: ${$o}
|
|
583
584
|
OUTPUT: ${me.replace(/\n{3,}/g,`
|
|
584
585
|
|
|
585
|
-
`)}`;return[...Y,{id:"term-"+Date.now(),role:"system",text:
|
|
586
|
-
Selection: ${
|
|
587
|
-
`),
|
|
588
|
-
`),qe=!1;for(let Bt of Be){if(Bt.includes("Old File contents:")){qe=!0;continue}qe&&(Bt.trim()===""?qe=!1:/^\d+ \|/.test(Bt)&&He++)}}hs+=xe,gs+=He,To("linesAdded",xe),To("linesRemoved",He)}continue}let ye=Y.content,me=ye.toLowerCase();if(ye.includes("```")&&(et=!et),me.includes("tool:functions.")&&(co=!0,Pt=0,ft=null,ye.includes("[tool:functions.")&&(Pt=0)),co){for(let ue=0;ue<ye.length;ue++){let xe=ye[ue];!ft&&(xe==="'"||xe==='"'||xe==="`")?ft=xe:ft&&xe===ft&&ye[ue-1]!=="\\"&&(ft=null),ft||(xe==="("||xe==="["?Pt++:(xe===")"||xe==="]")&&Pt--)}Pt<=0&&!ft&&(co=!1)}if((me.includes("<think")||me.includes("<thought"))&&(!Q&&!et&&!co&&!Ft)&&(Q=!0,Ft=!0,ye=ye.replace(/<(think|thought)>[\s\S]*?<\/(think|thought)>/gi,"").replace(/<(think|thought)>/gi,""),Ie="think-"+Date.now(),B(ue=>[...ue,{id:Ie,role:"think",text:"",isStreaming:!0,startTime:Date.now()}])),(me.includes("</think>")||me.includes("</thought>"))&&Ie){let ue=ye.split(/<\/(think|thought)>/gi),xe=ue[0]||"",He=ue.slice(2).join("").replace(/<\/?(think|thought)>/gi,"");B(Be=>{let qe=Be.map(Bt=>{if(Bt.id===Ie&&typeof Bt.id=="string"){let Nr=Bt.startTime||parseInt(Bt.id.split("-")[1])||Date.now(),bs=Date.now()-Nr;return{...Bt,text:Bt.text+xe,isStreaming:!1,duration:bs}}return Bt});return Q=!1,Pe="agent-"+Date.now(),[...qe,{id:Pe,role:"agent",text:He,isStreaming:!0}]});continue}if(Q&&Ie)B(ue=>{let xe=!1,He="",Be=ue.map(qe=>{if(qe.id===Ie){let Bt=qe.text+ye;if(Bt.toLowerCase().includes("</think>")){xe=!0;let Nr=Bt.split(/<\/think>/gi);He=Nr.slice(1).join("</think>")||"";let bs=qe.startTime||parseInt(qe.id.split("-")[1])||Date.now(),$l=Date.now()-bs;return{...qe,text:Nr[0],isStreaming:!1,duration:$l}}return{...qe,text:Bt,isStreaming:!0}}return qe});return xe?(Q=!1,Pe="agent-"+Date.now(),[...Be,{id:Pe,role:"agent",text:He.replace(/<\/?(think|thought)>/gi,""),isStreaming:!0}]):Be});else if(!Q){let ue=ye.toLowerCase();!Gn&&ue.includes("tool:functions.")&&(Gn=!0),Pe?B(xe=>xe.map(He=>He.id===Pe?{...He,text:He.text+ye,isStreaming:!0}:He)):(Pe="agent-"+Date.now(),B(xe=>[...xe,{id:Pe,role:"agent",text:ye,isStreaming:!0}]))}}let Xn=Date.now();ar(Y=>Y+(Xn-D))}catch(q){B(X=>(te(X.length+1),[...X,{id:"error-"+Date.now(),role:"system",text:`\u274C ERROR: ${q.message}`}]))}finally{if(dn(!1),Wn(null),I||process.stdout.isTTY&&(process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")),bo.current){Fe(bo.current),it(null);let q=bo.current;bo.current=null,B(X=>{let ae=[...X],Q=ae.reverse().find(Ie=>Ie.text?.includes("[STEERING HINT: QUEUED]"));return Q&&(Q.text=Q.text.replace("[STEERING HINT: QUEUED]","[STEERING HINT: FINISHED_TURN]")),ae.reverse()}),j("resolution")}B(q=>{let X=Date.now()-D,ae=!1,Q=[...q].reverse().map(Pe=>{let et=Pe.isStreaming?{...Pe,isStreaming:!1}:Pe;return!ae&&et.role==="agent"&&(ae=!0,et={...et,workedDuration:X}),et}).reverse(),Ie=Q.filter(Pe=>!String(Pe.id).startsWith("welcome")&&!Pe.isMeta);return ns(Re,null,Ie),te(Q.length),Q})}})()}d(""),a(!1)}},Ee=Mr(()=>{if(l.startsWith("/")&&!M){let O=l.split(" "),P=O[O.length-1].toLowerCase();if(O.length===1){let $=P.startsWith("/")?P.slice(1):P;return ve.filter(U=>(U.cmd.startsWith("/")?U.cmd.slice(1):U.cmd).toLowerCase().includes($))}let k=ve;for(let $=0;$<O.length-1;$++){let U=O[$].toLowerCase(),I=k.find(D=>D.cmd.toLowerCase()===U);if(I&&I.subs)k=I.subs;else return[]}return k.filter($=>$.cmd.toLowerCase().includes(P))}let x=l.split(" "),g=x[x.length-1];if(g&&g.startsWith("@")&&!M){let O=g.indexOf("#"),P=O!==-1,k=P?g.substring(1,O).toLowerCase():g.slice(1).toLowerCase(),$=P?g.substring(O):"";return pd(process.cwd()).filter(D=>D.name.toLowerCase().includes(k)).map(D=>{let N=D.relativePath.replace(/\\/g,"/");return{cmd:"@["+(N.startsWith(".")?N:"./"+N)+$+"]",desc:D.relativePath}})}return[]},[l,M]);po(()=>{y(0)},[Ee]);let bt=()=>{switch(qt){case"settings":return s.createElement(Ns,{systemSettings:Wt,setSystemSettings:oe,apiTier:Ke,setActiveView:j,setInputConfig:Lo,saveSettings:gn,quotas:Vt,setMessages:B,aiProvider:_});case"selectProvider":return s.createElement(mo,{title:"SELECT AI PROVIDER",items:[{label:"Google (Free/Paid)",value:"Google"},{label:"DeepSeek (Paid)",value:"DeepSeek"},{label:"OpenRouter (Free/Paid) [EXPERIMENTAL]",value:"OpenRouter"},{label:"Back",value:"settings"}],onSelect:async x=>{if(x.value==="settings"||x.value==="Back"){j("settings");return}let g=x.value,O=await jr(g);if(O){V(g),at(O),Ir(O,{aiProvider:g,onIDEApproval:Jo});let P="gemma-4-31b-it";g==="OpenRouter"?P="google/gemma-4-31b-it:free":g==="DeepSeek"&&(P="deepseek-v4-flash"),Ne(P),gn({aiProvider:g,activeModel:P,apiTier:Ke,quotas:Vt}),B(k=>[...k,{role:"system",text:`\u2705 Switched to ${g}! Key loaded from Vault. Model set to ${P}.`,isMeta:!0}]),j("settings")}else Lo({label:`Enter ${g} API Key:`,key:"providerKey",provider:g,value:"",returnView:"settings"}),j("input")},onClose:()=>j("settings")});case"apiTier":return s.createElement(mo,{title:s.createElement(w,null,"SELECT YOUR CURRENT API TIER BASED ON ",s.createElement(w,{color:"cyan",underline:!0,bold:!0},"\x1B]8;;https://aistudio.google.com/projects\x07AI STUDIO\x1B]8;;\x07"),". (CURRENT: ",Ke.toUpperCase(),")"),items:[{label:"Free Tier (Gemini API Free Tier)",value:"Free"},{label:"Paid Tier (API with Billing Account)",value:"Paid"},{label:"Back",value:"settings"}],onSelect:x=>{if(x.value==="settings"||x.value==="Back"){j("settings");return}let g=x.value;Ar(g),g==="Paid"?(Lo({label:"Enter Agent daily budget (requests made):",key:"quotas",subKey:"agentLimit",value:String(Vt.agentLimit)}),j("input")):(gn({apiTier:g,quotas:Vt}),j("settings"))},onClose:()=>j("settings")});case"input":return s.createElement(b,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},s.createElement(b,{paddingX:1},s.createElement(w,{color:"magenta",bold:!0},"\u{1F527} DATA CONFIGURATION")),xt?.note&&s.createElement(b,{paddingX:1,marginBottom:1},s.createElement(w,{color:"yellow",dimColor:!0,italic:!0},xt.note)),s.createElement(b,{paddingX:1,flexDirection:"row"},s.createElement(w,{color:"cyan",bold:!0},xt?.label," "),s.createElement(Cl,{value:xt?.value||"",onChange:x=>Lo(g=>({...g,value:x})),onSubmit:async x=>{let{key:g,subKey:O,next:P}=xt,k={...Vt},$={};if(g==="quotas"){let U=O.toLowerCase().includes("limit")?parseInt(x)||0:x;k[O]=U,Un(k),$.quotas=k}else if(g==="activeModel")Ne(x),$.activeModel=x;else if(g==="janitorModel")Xe(x),$.janitorModel=x;else if(g==="autoApproveCommands"||g==="autoDisallowCommands"||g==="alwaysAskCommands"){let U={...Wt,[g]:x.trim(),sandboxPreset:"Custom"};oe(U),$.systemSettings=U}else if(g==="externalDataPath"){let U={...Wt,useExternalData:!0,externalDataPath:x.trim()};oe(U),$.systemSettings=U,B(I=>[...I,{id:Date.now(),role:"system",text:"\u{1F4C1} [EXTERNAL STORAGE] Flux Flow will use "+x.trim()+" for data after restart."}])}else if(g==="imageSettings"){let U=x.trim();if(U.startsWith("sk_")){let I={...he,apiKey:U};we(I),$.imageSettings=I,B(D=>(te(D.length+1),[...D,{id:Date.now(),role:"system",text:"\u{1F511} [IMAGE KEY] Custom API key saved successfully.",isMeta:!0}]))}else we(I=>({...I,keyType:"Default"})),$.imageSettings={...he,keyType:"Default"},B(I=>(te(I.length+1),[...I,{id:Date.now(),role:"system",text:"\u274C [IMAGE KEY ERROR] API key must start with sk_. Key strategy reset to Default.",isMeta:!0}]))}else if(g==="providerKey"){let U=x.trim(),I=xt.provider;await Gr(I,U),V(I),at(U),Ir(U,{aiProvider:I,onIDEApproval:Jo});let D="gemma-4-31b-it";I==="OpenRouter"?D="google/gemma-4-31b-it:free":I==="DeepSeek"&&(D="deepseek-v4-flash"),Ne(D),$.aiProvider=I,$.activeModel=D,B(N=>(te(N.length+1),[...N,{id:Date.now(),role:"system",text:`\u2705 ${I} API Key saved successfully! Model set to ${D}.`,isMeta:!0}]))}P?Lo(P(g==="quotas"?k:x)):(gn({...$,apiTier:Ke,quotas:k,imageSettings:$.imageSettings||he}),Lo(null),j(xt?.returnView||"settings"))}})),s.createElement(b,{paddingX:1,marginTop:1},s.createElement(w,{color:"gray",dimColor:!0,italic:!0},"(Press Enter to confirm selection)")));case"stats":return s.createElement(b,{flexDirection:"column",borderStyle:"round",paddingX:3,paddingY:1,width:Math.min(100,(r?.columns||100)-2)},s.createElement(b,{marginBottom:1},s.createElement(w,{color:"white",bold:!0,underline:!0},"SESSION TELEMETRY")),s.createElement(b,{flexDirection:"column"},s.createElement(b,null,s.createElement(b,{width:25},s.createElement(w,{color:"blue"},"Session Duration:")),s.createElement(w,{color:"white"},_o(Date.now()-$i))),s.createElement(b,null,s.createElement(b,{width:25},s.createElement(w,{color:"blue"},"Agent Interactions:")),s.createElement(w,{color:"white"},Bo)),s.createElement(b,{marginLeft:2},s.createElement(b,{width:23},s.createElement(w,{color:"blue",dimColor:!0},"\xBB API Time:")),s.createElement(w,{color:"white"},_o(ir))),s.createElement(b,{marginLeft:2},s.createElement(b,{width:23},s.createElement(w,{color:"blue",dimColor:!0},"\xBB Tool Time:")),s.createElement(w,{color:"white"},_o(Rn))),s.createElement(b,null,s.createElement(b,{width:25},s.createElement(w,{color:"blue"},"Background Tasks:")),s.createElement(w,{color:"white"},wt)),s.createElement(b,null,s.createElement(b,{width:25},s.createElement(w,{color:"blue"},"Tokens Consumed:")),s.createElement(w,{color:"white"},oo(ce))),ce>0&&s.createElement(s.Fragment,null,s.createElement(b,{marginLeft:2},s.createElement(b,{width:23},s.createElement(w,{color:"blue",dimColor:!0},"\xBB Input Tokens:")),s.createElement(w,{color:"white"},oo(ce-yt))),dt>0&&s.createElement(b,{marginLeft:4},s.createElement(b,{width:21},s.createElement(w,{color:"blue",dimColor:!0},"\xBB Cached:")),s.createElement(w,{color:"white"},oo(dt))),yt>0&&s.createElement(b,{marginLeft:2},s.createElement(b,{width:23},s.createElement(w,{color:"blue",dimColor:!0},"\xBB Output Tokens:")),s.createElement(w,{color:"white"},oo(yt)))),lr>0&&s.createElement(s.Fragment,null,s.createElement(b,null,s.createElement(b,{width:25},s.createElement(w,{color:"blue"},"Images Made:")),s.createElement(w,{color:"white"},lr)),s.createElement(b,null,s.createElement(b,{width:25},s.createElement(w,{color:"blue"},"Image Credits:")),s.createElement(w,{color:"white"},Number(((An||0)*1e3).toFixed(0))," credits"))),s.createElement(b,null,s.createElement(b,{width:25},s.createElement(w,{color:"blue"},"Code Changes (Sess):")),s.createElement(w,{color:"white"},s.createElement(w,{color:"green"},"+",hs)," ",s.createElement(w,{color:"red"},"-",gs))),s.createElement(b,null,s.createElement(b,{width:25},s.createElement(w,{color:"blue"},"Tool Calls (Sess):")),s.createElement(w,{color:"white"},nt+Ht+zo," ( "),s.createElement(w,{color:"green"},"\u2713 ",nt),s.createElement(w,{color:"white"}," "),s.createElement(w,{color:"yellow"},"\u2298 ",zo),s.createElement(w,{color:"white"}," "),s.createElement(w,{color:"red"},"\u2715 ",Ht),s.createElement(w,{color:"white"}," )"))),s.createElement(b,{flexDirection:"column",marginTop:1},s.createElement(w,{color:"white",bold:!0,underline:!0},"DAILY USAGE TRACKER"),s.createElement(b,{marginTop:1},s.createElement(b,{width:25},s.createElement(w,{color:"blue"},"Wall Time Today:")),s.createElement(w,{color:"white"},Lr(ie?.duration||0))),s.createElement(b,null,s.createElement(b,{width:25},s.createElement(w,{color:"blue"},"Agent Interactions:")),s.createElement(w,{color:"white"},ie?.agent||0)),s.createElement(b,null,s.createElement(b,{width:25},s.createElement(w,{color:"blue"},"Background Tasks:")),s.createElement(w,{color:"white"},ie?.background||0)),s.createElement(b,null,s.createElement(b,{width:25},s.createElement(w,{color:"blue"},"Tokens Used Today:")),s.createElement(w,{color:"white"},oo(ie?.tokens||0))),(ie?.tokens||0)>0&&s.createElement(s.Fragment,null,s.createElement(b,{marginLeft:2},s.createElement(b,{width:23},s.createElement(w,{color:"blue",dimColor:!0},"\xBB Input Tokens:")),s.createElement(w,{color:"white"},oo((ie?.tokens||0)-(ie?.candidateTokens||0)))),(ie?.cachedTokens||0)>0&&s.createElement(b,{marginLeft:4},s.createElement(b,{width:21},s.createElement(w,{color:"blue",dimColor:!0},"\xBB Cached:")),s.createElement(w,{color:"white"},oo(ie.cachedTokens))),(ie?.candidateTokens||0)>0&&s.createElement(b,{marginLeft:2},s.createElement(b,{width:23},s.createElement(w,{color:"blue",dimColor:!0},"\xBB Output Tokens:")),s.createElement(w,{color:"white"},oo(ie.candidateTokens)))),(ie?.imageCalls?.length||0)>0&&s.createElement(s.Fragment,null,s.createElement(b,null,s.createElement(b,{width:25},s.createElement(w,{color:"blue"},"Images Made Today:")),s.createElement(w,{color:"white"},ie.imageCalls.length)),s.createElement(b,null,s.createElement(b,{width:25},s.createElement(w,{color:"blue"},"Image Credits Today:")),s.createElement(w,{color:"white"},Number(((ie.imageCalls.reduce((x,g)=>x+g.cost,0)||0)*1e3).toFixed(0))," credits"))),s.createElement(b,null,s.createElement(b,{width:25},s.createElement(w,{color:"blue"},"Code Changes Today:")),s.createElement(w,{color:"white"},s.createElement(w,{color:"green"},"+",ie?.linesAdded||0)," ",s.createElement(w,{color:"red"},"-",ie?.linesRemoved||0))),s.createElement(b,null,s.createElement(b,{width:25},s.createElement(w,{color:"blue"},"Tool Calls Today:")),s.createElement(w,{color:"white"},(ie?.toolSuccess||0)+(ie?.toolFailure||0)+(ie?.toolDenied||0)," ( "),s.createElement(w,{color:"green"},"\u2713 ",ie?.toolSuccess||0),s.createElement(w,{color:"white"}," "),s.createElement(w,{color:"yellow"},"\u2298 ",ie?.toolDenied||0),s.createElement(w,{color:"white"}," "),s.createElement(w,{color:"red"},"\u2715 ",ie?.toolFailure||0),s.createElement(w,{color:"white"}," )"))),s.createElement(w,{dimColor:!0,marginTop:1,italic:!0},"(Press ESC to return to chat)"));case"autoExecDanger":return s.createElement(b,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:2,paddingY:1,width:"100%"},s.createElement(w,{color:"yellow",bold:!0,underline:!0},"\u26A0\uFE0F SECURITY WARNING: YOLO MODE"),s.createElement(w,{marginTop:1},"Turning this ON allows the agent to execute terminal commands automatically without requiring your approval for each step."),s.createElement(w,{marginTop:1,color:"yellow"},"RISKS INVOLVED:"),s.createElement(w,null,"\u2022 The agent may execute destructive commands (rm -rf, etc.) by mistake."),s.createElement(w,null,"\u2022 Unintended system changes if the agent hallucinates a path or command."),s.createElement(w,null,"\u2022 Reduced control over the agent's step-by-step decision making."),s.createElement(b,{marginTop:1},s.createElement(mo,{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"&&oe(g=>({...g,autoExec:!0})),j("settings")}})));case"externalDanger":return s.createElement(b,{flexDirection:"column",borderStyle:"round",borderColor:"red",paddingX:2,paddingY:1,width:"100%"},s.createElement(w,{color:"red",bold:!0,underline:!0},"\u26A0\uFE0F SECURITY WARNING: EXTERNAL WORKSPACE ACCESS"),s.createElement(w,{marginTop:1},"Turning this ON allows the agent to execute tools (Read/Write/Exec) outside of the current active workspace directory."),s.createElement(w,{marginTop:1,color:"yellow"},"RISKS INVOLVED:"),s.createElement(w,null,"\u2022 Access to sensitive system files (SSH keys, Browser data, etc.)"),s.createElement(w,null,"\u2022 Potential for accidental or malicious deletion of OS-critical files."),s.createElement(w,null,"\u2022 Unauthorized script execution across your entire file system."),s.createElement(b,{marginTop:1},s.createElement(mo,{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"&&oe(g=>({...g,allowExternalAccess:!0})),j("settings")}})));case"doubleDanger":return s.createElement(b,{flexDirection:"column",borderStyle:"round",borderColor:"red",paddingX:2,paddingY:1,width:"100%"},s.createElement(w,{color:"red",bold:!0,underline:!0},"\u26D4 CRITICAL SECURITY WARNING: COMBINED SYSTEM RISK"),s.createElement(w,{marginTop:1},"You are attempting to enable BOTH [YOLO Mode] and [External Workspace Access] simultaneously."),s.createElement(w,{marginTop:1,color:"red",bold:!0},"THIS IS NOT RECOMMENDED."),s.createElement(w,{marginTop:1,color:"yellow"},"THE CRITICAL RISK:"),s.createElement(w,null,"The agent will have the power to execute any command across your entire system WITHOUT your approval or supervision."),s.createElement(w,{color:"red",italic:!0,marginTop:1},"A single hallucination or error could result in full system wipe or data theft."),s.createElement(b,{marginTop:1},s.createElement(mo,{title:"Final Confirmation",items:[{label:"I agree knowing the consequences",value:"on"},{label:"Keep Off",value:"off"}],onSelect:x=>{x.value==="on"&&oe(g=>({...g,autoExec:!0,allowExternalAccess:!0})),j("settings")}})));case"key":return s.createElement(mo,{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"){at(null),j("chat");let g=Oe(2);B(O=>[...O,{id:Date.now(),role:"system",text:`\u{1F511}${g}[ACTION] Flux waiting for new API Key...`}])}else x.value==="remove"?j("deleteKey"):j("chat")}});case"deleteKey":return s.createElement(b,{flexDirection:"column",borderStyle:"round",borderColor:"red",paddingX:2,paddingY:1},(()=>{let x=Oe(2);return s.createElement(w,{color:"red",bold:!0},"\u26D4",x,"DANGER: PURGE API KEY")})(),s.createElement(w,{marginTop:1},"This will permanently delete the saved API key from the project vault. You will need to enter it again to use Flux."),s.createElement(b,{marginTop:1},s.createElement(mo,{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 ks(),at(null),j("chat");let g=Oe(2);B(O=>[...O,{id:Date.now(),role:"system",text:`\u2728${g}[VAULT PURGED] API Key removed successfully.`}])}else j("key")}})));case"exit":return null;case"ask":return s.createElement(b,{width:"100%"},s.createElement(da,{question:cn?.question,options:cn?.options,onResolve:x=>{cn?.resolve&&cn.resolve(x),cr(null),j("chat")}}));case"revert":return s.createElement(b,{width:"100%",alignItems:"center",justifyContent:"center"},s.createElement(Di,{prompts:ee,onSelect:async x=>{try{let g=await Ct.rollbackToBefore(x);if(g.success){let{targetPrompt:O}=g,P=kt.findIndex(I=>I.role==="user"&&I.text&&(I.text.startsWith(O)||I.text.includes(O))),k=[...kt];P!==-1&&(k=kt.slice(0,P)),B(k),te(k.length),d(O),a(O.split(`
|
|
589
|
-
`).length>2);let $=
|
|
586
|
+
`)}`;return[...Y,{id:"term-"+Date.now(),role:"system",text:De,isTerminalRecord:!0}]}),nt(null),Lt(!1),xo("")},onToolResult:(Y,le)=>{if(Y==="success"){if(lt(me=>me+1),le==="generate_image"){As(_t=>_t+1);let De={Low:.001,"Low-High":.002,Medium:.008,"Medium-High":.01,High:.045,Ultra:.0488,Premium:.1}[de.quality]||.002;Os(_t=>_t+De)}}else Y==="denied"?vs(me=>me+1):Jt(me=>me+1)},onToolApproval:async(Y,le)=>{let me=yo||Yt.autoExec;if(Y==="exec_command"){let{command:De}=ne(le||"{}");return me||De&&/^(echo|ls|dir|pwd|cd|git status|git log|git diff|type|cat|help)\b/i.test(De.trim())?"allow":new Promise(pe=>{Uo({tool:Y,args:le,resolve:pe}),H("terminalApproval")})}return me?"allow":new Promise(De=>{Uo({tool:Y,args:le,resolve:De}),H("approval")})},onAskUser:async(Y,le)=>new Promise(me=>{yr({question:Y,options:le,resolve:De=>{W(_t=>[..._t,{id:"ask-"+Date.now(),role:"system",text:`\u{1F4AC} **Ask User**
|
|
587
|
+
Selection: ${De}`,isAskRecord:!0}]),me(De)}}),H("ask")})},async()=>{if(Do.current){let Y=Do.current;return Fe(null),Do.current=null,W(le=>{let me=[...le].reverse().findIndex(De=>De.text?.includes("[STEERING HINT: QUEUED]"));if(me!==-1){let De=le.length-1-me,_t=[...le];return _t[De]={..._t[De],text:_t[De].text.replace("[STEERING HINT: QUEUED]","[STEERING HINT: INJECTED]"),color:"cyan"},_t}return le}),Y}return null},Pn),ge=!1,Oe=null,Pe=null,Ke=!1,yn=!1,to=!1,Pt=!1,jo=0,To=null,Xr=/\[?\s*turn\s*:\s*.*?\s*\]?/gi;for await(let Y of $e){if(P&&Y.type==="text"&&(D=Date.now(),P=!1),Y.type==="status"){Jn(Y.content),Vo()&&Ss(Y.content);continue}if(Y.type==="status_history"){Jn(Y.content),Vo()&&Ss(Y.content),W(pe=>[...pe,{id:"condense-"+Date.now(),role:"system",text:`\u2699\uFE0F [SYSTEM] ${Y.content}`,isMeta:!0}]);continue}if(Y.type==="spinner"){Qn(Y.content);continue}if(Y.type==="model_update"){bt(Y.content);continue}if(Y.type==="turn_reset"){Oe=null,Pe=null,ge=!1,Ke=!1,yn=!1,Pt=!1,to=!1;continue}if(Y.type==="interactive_turn_finished"){jr(!1),Vo()&&Ss(null),E=!0,Pl({profile:ve,thinkingLevel:j,mode:d,janitorModel:Me,chatId:Ue,systemSettings:Yt,sessionStats:fe,aiProvider:B,apiKey:be},Y.data.agentText,Y.data.fullAgentTextRaw,Y.data.history,{onMemoryUpdated:()=>W(pe=>{let we=[...pe];return we.length>0&&(we[we.length-1].memoryUpdated=!0),we}),onBackgroundIncrement:()=>Ne(pe=>pe+1)});continue}if(Y.type==="visual_feedback"){W(pe=>[...pe,{id:"feedback-"+Date.now(),role:"system",text:Y.content,isVisualFeedback:!0}]);continue}if(Y.type==="exec_start")continue;if(Y.type==="liveTokens"){it({tokens:Y.content});continue}if(Y.type==="usage"){let pe=Y.content.totalTokenCount||0,we=Y.content.cachedContentTokenCount||0,Ze=Y.content.candidatesTokenCount||0;it({tokens:pe}),jt(Ct=>Ct+pe),we>0&&go(Ct=>Ct+we),Ze>0&&pn(Ct=>Ct+Ze),St(Ct=>Ct+1);continue}if(Y.type==="tool_time"){Zi(pe=>pe+Y.content);continue}if(Y.type==="tool_result"){if(W(pe=>[...pe,{id:"tool-"+Date.now(),role:"system",text:Y.content,fullText:Y.aiContent,binaryPart:Y.binaryPart,toolName:Y.toolName}]),Y.toolName==="update_file"&&Y.aiContent){let pe=Y.aiContent.split(`
|
|
588
|
+
`),we=0,Ze=0,Ct=!1;for(let At of pe){if(At.includes("[DIFF_START]")){Ct=!0;continue}if(At.includes("[DIFF_END]")){Ct=!1;continue}Ct&&(/^\+\d+/.test(At)?we++:/^\-\d+/.test(At)&&Ze++)}ks+=we,Is+=Ze,Co("linesAdded",we),Co("linesRemoved",Ze)}else if(Y.toolName==="write_file"&&Y.aiContent){let pe=Y.aiContent.match(/- Stats: \[(\d+) lines/),we=pe?parseInt(pe[1]):0,Ze=0;if(Y.aiContent.includes("Old File contents:")){let Ct=Y.aiContent.split(`
|
|
589
|
+
`),At=!1;for(let oo of Ct){if(oo.includes("Old File contents:")){At=!0;continue}At&&(oo.trim()===""?At=!1:/^\d+ \|/.test(oo)&&Ze++)}}ks+=we,Is+=Ze,Co("linesAdded",we),Co("linesRemoved",Ze)}continue}let le=Y.content,me=le.toLowerCase();if(le.includes("```")&&(Ke=!Ke),me.includes("tool:functions.")&&(yn=!0,jo=0,To=null,le.includes("[tool:functions.")&&(jo=0)),yn){for(let pe=0;pe<le.length;pe++){let we=le[pe];!To&&(we==="'"||we==='"'||we==="`")?To=we:To&&we===To&&le[pe-1]!=="\\"&&(To=null),To||(we==="("||we==="["?jo++:(we===")"||we==="]")&&jo--)}jo<=0&&!To&&(yn=!1)}if((me.includes("<think")||me.includes("<thought"))&&(!ge&&!Ke&&!yn&&!to)&&(ge=!0,to=!0,le=le.replace(/<(think|thought)>[\s\S]*?<\/(think|thought)>/gi,"").replace(/<(think|thought)>/gi,""),Oe="think-"+Date.now(),W(pe=>[...pe,{id:Oe,role:"think",text:"",isStreaming:!0,startTime:Date.now()}])),(me.includes("</think>")||me.includes("</thought>"))&&Oe){let pe=le.split(/<\/(think|thought)>/gi),we=pe[0]||"",Ze=pe.slice(2).join("").replace(/<\/?(think|thought)>/gi,"");W(Ct=>{let At=Ct.map(oo=>{if(oo.id===Oe&&typeof oo.id=="string"){let Kr=oo.startTime||parseInt(oo.id.split("-")[1])||Date.now(),$s=Date.now()-Kr;return{...oo,text:oo.text+we,isStreaming:!1,duration:$s}}return oo});return ge=!1,Pe="agent-"+Date.now(),[...At,{id:Pe,role:"agent",text:Ze,isStreaming:!0}]});continue}if(ge&&Oe)W(pe=>{let we=!1,Ze="",Ct=pe.map(At=>{if(At.id===Oe){let oo=At.text+le;if(oo.toLowerCase().includes("</think>")){we=!0;let Kr=oo.split(/<\/think>/gi);Ze=Kr.slice(1).join("</think>")||"";let $s=At.startTime||parseInt(At.id.split("-")[1])||Date.now(),mc=Date.now()-$s;return{...At,text:Kr[0],isStreaming:!1,duration:mc}}return{...At,text:oo,isStreaming:!0}}return At});return we?(ge=!1,Pe="agent-"+Date.now(),[...Ct,{id:Pe,role:"agent",text:Ze.replace(/<\/?(think|thought)>/gi,""),isStreaming:!0}]):Ct});else if(!ge){let pe=le.toLowerCase();!Pt&&pe.includes("tool:functions.")&&(Pt=!0),Pe?W(we=>we.map(Ze=>Ze.id===Pe?{...Ze,text:Ze.text+le,isStreaming:!0}:Ze)):(Pe="agent-"+Date.now(),W(we=>[...we,{id:Pe,role:"agent",text:le,isStreaming:!0}]))}}let er=Date.now();gr(Y=>Y+(er-D))}catch(G){W(q=>(ee(q.length+1),[...q,{id:"error-"+Date.now(),role:"system",text:`\u274C ERROR: ${G.message}`}]))}finally{if(jr(!1),Jn(null),E||process.stdout.isTTY&&(process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")),Do.current){on(Do.current),Fe(null);let G=Do.current;Do.current=null,W(q=>{let $e=[...q],ge=$e.reverse().find(Oe=>Oe.text?.includes("[STEERING HINT: QUEUED]"));return ge&&(ge.text=ge.text.replace("[STEERING HINT: QUEUED]","[STEERING HINT: FINISHED_TURN]")),$e.reverse()}),H("resolution")}W(G=>{let q=Date.now()-D,$e=!1,ge=[...G].reverse().map(Pe=>{let Ke=Pe.isStreaming?{...Pe,isStreaming:!1}:Pe;return!$e&&Ke.role==="agent"&&($e=!0,Ke={...Ke,workedDuration:q}),Ke}).reverse(),Oe=ge.filter(Pe=>!String(Pe.id).startsWith("welcome")&&!Pe.isMeta);return ms(Ue,null,Oe),ee(ge.length),ge})}})()}u(""),a(!1)}},Ce=Ur(()=>{if(l.startsWith("/")&&!I){let O=l.split(" "),N=O[O.length-1].toLowerCase();if(O.length===1){let $=N.startsWith("/")?N.slice(1):N;return Ve.filter(U=>(U.cmd.startsWith("/")?U.cmd.slice(1):U.cmd).toLowerCase().includes($))}let M=Ve;for(let $=0;$<O.length-1;$++){let U=O[$].toLowerCase(),E=M.find(D=>D.cmd.toLowerCase()===U);if(E&&E.subs)M=E.subs;else return[]}return M.filter($=>$.cmd.toLowerCase().includes(N))}let x=l.split(" "),g=x[x.length-1];if(g&&g.startsWith("@")&&!I){let O=g.indexOf("#"),N=O!==-1,M=N?g.substring(1,O).toLowerCase():g.slice(1).toLowerCase(),$=N?g.substring(O):"";return Ju(process.cwd()).filter(D=>D.name.toLowerCase().includes(M)).map(D=>{let P=D.relativePath.replace(/\\/g,"/");return{cmd:"@["+(P.startsWith(".")?P:"./"+P)+$+"]",desc:D.relativePath}})}return[]},[l,I]);io(()=>{w(0)},[Ce]);let wo=()=>{switch(Vt){case"settings":return i.createElement(qs,{systemSettings:Yt,setSystemSettings:te,apiTier:Ge,setActiveView:H,setInputConfig:Oo,saveSettings:Cn,quotas:zt,setMessages:W,aiProvider:B});case"selectProvider":return i.createElement(fo,{title:"SELECT AI PROVIDER",items:[{label:"Google (Free/Paid)",value:"Google"},{label:"DeepSeek (Paid)",value:"DeepSeek"},{label:"OpenRouter (Free/Paid) [EXPERIMENTAL]",value:"OpenRouter"},{label:"Back",value:"settings"}],onSelect:async x=>{if(x.value==="settings"||x.value==="Back"){H("settings");return}let g=x.value,O=await Zr(g);if(O){z(g),rt(O),Br(O,{aiProvider:g,onIDEApproval:tn});let N="gemma-4-31b-it";g==="OpenRouter"?N="google/gemma-4-31b-it:free":g==="DeepSeek"&&(N="deepseek-v4-flash"),_e(N),Cn({aiProvider:g,activeModel:N,apiTier:Ge,quotas:zt}),W(M=>[...M,{role:"system",text:`\u2705 Switched to ${g}! Key loaded from Vault. Model set to ${N}.`,isMeta:!0}]),H("settings")}else Oo({label:`Enter ${g} API Key:`,key:"providerKey",provider:g,value:"",returnView:"settings"}),H("input")},onClose:()=>H("settings")});case"apiTier":return i.createElement(fo,{title:i.createElement(y,null,"SELECT YOUR CURRENT API TIER BASED ON ",i.createElement(y,{color:"cyan",underline:!0,bold:!0},"\x1B]8;;https://aistudio.google.com/projects\x07AI STUDIO\x1B]8;;\x07"),". (CURRENT: ",Ge.toUpperCase(),")"),items:[{label:"Free Tier (Gemini API Free Tier)",value:"Free"},{label:"Paid Tier (API with Billing Account)",value:"Paid"},{label:"Back",value:"settings"}],onSelect:x=>{if(x.value==="settings"||x.value==="Back"){H("settings");return}let g=x.value;Rr(g),g==="Paid"?(Oo({label:"Enter Agent daily budget (requests made):",key:"quotas",subKey:"agentLimit",value:String(zt.agentLimit)}),H("input")):(Cn({apiTier:g,quotas:zt}),H("settings"))},onClose:()=>H("settings")});case"input":return i.createElement(k,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},i.createElement(k,{paddingX:1},i.createElement(y,{color:"magenta",bold:!0},"\u{1F527} DATA CONFIGURATION")),ht?.note&&i.createElement(k,{paddingX:1,marginBottom:1},i.createElement(y,{color:"yellow",dimColor:!0,italic:!0},ht.note)),i.createElement(k,{paddingX:1,flexDirection:"row"},i.createElement(y,{color:"cyan",bold:!0},ht?.label," "),i.createElement(oc,{value:ht?.value||"",onChange:x=>Oo(g=>({...g,value:x})),onSubmit:async x=>{let{key:g,subKey:O,next:N}=ht,M={...zt},$={};if(g==="quotas"){let U=O.toLowerCase().includes("limit")?parseInt(x)||0:x;M[O]=U,qn(M),$.quotas=M}else if(g==="activeModel")_e(x),$.activeModel=x;else if(g==="janitorModel")je(x),$.janitorModel=x;else if(g==="autoApproveCommands"||g==="autoDisallowCommands"||g==="alwaysAskCommands"){let U={...Yt,[g]:x.trim(),sandboxPreset:"Custom"};te(U),$.systemSettings=U}else if(g==="externalDataPath"){let U={...Yt,useExternalData:!0,externalDataPath:x.trim()};te(U),$.systemSettings=U,W(E=>[...E,{id:Date.now(),role:"system",text:"\u{1F4C1} [EXTERNAL STORAGE] Flux Flow will use "+x.trim()+" for data after restart."}])}else if(g==="imageSettings"){let U=x.trim();if(U.startsWith("sk_")){let E={...de,apiKey:U};he(E),$.imageSettings=E,W(D=>(ee(D.length+1),[...D,{id:Date.now(),role:"system",text:"\u{1F511} [IMAGE KEY] Custom API key saved successfully.",isMeta:!0}]))}else he(E=>({...E,keyType:"Default"})),$.imageSettings={...de,keyType:"Default"},W(E=>(ee(E.length+1),[...E,{id:Date.now(),role:"system",text:"\u274C [IMAGE KEY ERROR] API key must start with sk_. Key strategy reset to Default.",isMeta:!0}]))}else if(g==="providerKey"){let U=x.trim(),E=ht.provider;await es(E,U),z(E),rt(U),Br(U,{aiProvider:E,onIDEApproval:tn});let D="gemma-4-31b-it";E==="OpenRouter"?D="google/gemma-4-31b-it:free":E==="DeepSeek"&&(D="deepseek-v4-flash"),_e(D),$.aiProvider=E,$.activeModel=D,W(P=>(ee(P.length+1),[...P,{id:Date.now(),role:"system",text:`\u2705 ${E} API Key saved successfully! Model set to ${D}.`,isMeta:!0}]))}N?Oo(N(g==="quotas"?M:x)):(Cn({...$,apiTier:Ge,quotas:M,imageSettings:$.imageSettings||de}),Oo(null),H(ht?.returnView||"settings"))}})),i.createElement(k,{paddingX:1,marginTop:1},i.createElement(y,{color:"gray",dimColor:!0,italic:!0},"(Press Enter to confirm selection)")));case"stats":return i.createElement(k,{flexDirection:"column",borderStyle:"round",paddingX:3,paddingY:1,width:Math.min(100,(r?.columns||100)-2)},i.createElement(k,{marginBottom:1},i.createElement(y,{color:"white",bold:!0,underline:!0},"SESSION TELEMETRY")),i.createElement(k,{flexDirection:"column"},i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Session Duration:")),i.createElement(y,{color:"white"},Ro(Date.now()-Qi))),i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Agent Interactions:")),i.createElement(y,{color:"white"},Bo)),i.createElement(k,{marginLeft:2},i.createElement(k,{width:23},i.createElement(y,{color:"grey"},"\xBB API Time:")),i.createElement(y,{color:"white"},Ro(hr))),i.createElement(k,{marginLeft:2},i.createElement(k,{width:23},i.createElement(y,{color:"grey"},"\xBB Tool Time:")),i.createElement(y,{color:"white"},Ro(Vn))),i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Background Tasks:")),i.createElement(y,{color:"white"},gt)),i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Tokens Consumed:")),i.createElement(y,{color:"white"},so(ae))),ae>0&&i.createElement(i.Fragment,null,i.createElement(k,{marginLeft:2},i.createElement(k,{width:23},i.createElement(y,{color:"grey"},"\xBB Input Tokens:")),i.createElement(y,{color:"white"},so(ae-xt))),at>0&&i.createElement(k,{marginLeft:4},i.createElement(k,{width:21},i.createElement(y,{color:"grey"},"\xBB Cached:")),i.createElement(y,{color:"white"},so(at))),xt>0&&i.createElement(k,{marginLeft:2},i.createElement(k,{width:23},i.createElement(y,{color:"grey"},"\xBB Output Tokens:")),i.createElement(y,{color:"white"},so(xt)))),xr>0&&i.createElement(i.Fragment,null,i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Images Made:")),i.createElement(y,{color:"white"},xr)),i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Image Credits:")),i.createElement(y,{color:"white"},Number(((_n||0)*1e3).toFixed(0))," credits"))),i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Code Changes (Sess):")),i.createElement(y,{color:"white"},i.createElement(y,{color:"green"},"+",ks)," ",i.createElement(y,{color:"red"},"-",Is))),i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Tool Calls (Sess):")),i.createElement(y,{color:"white"},ot+Gt+en," ( "),i.createElement(y,{color:"green"},"\u2713 ",ot),i.createElement(y,{color:"white"}," "),i.createElement(y,{color:"yellow"},"\u2298 ",en),i.createElement(y,{color:"white"}," "),i.createElement(y,{color:"red"},"\u2715 ",Gt),i.createElement(y,{color:"white"}," )"))),i.createElement(k,{flexDirection:"column",marginTop:1},i.createElement(y,{color:"white",bold:!0,underline:!0},"DAILY USAGE TRACKER"),i.createElement(k,{marginTop:1},i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Wall Time Today:")),i.createElement(y,{color:"white"},Yr(se?.duration||0))),i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Agent Interactions:")),i.createElement(y,{color:"white"},se?.agent||0)),i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Background Tasks:")),i.createElement(y,{color:"white"},se?.background||0)),i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Tokens Used Today:")),i.createElement(y,{color:"white"},so(se?.tokens||0))),(se?.tokens||0)>0&&i.createElement(i.Fragment,null,i.createElement(k,{marginLeft:2},i.createElement(k,{width:23},i.createElement(y,{color:"grey"},"\xBB Input Tokens:")),i.createElement(y,{color:"white"},so((se?.tokens||0)-(se?.candidateTokens||0)))),(se?.cachedTokens||0)>0&&i.createElement(k,{marginLeft:4},i.createElement(k,{width:21},i.createElement(y,{color:"grey"},"\xBB Cached:")),i.createElement(y,{color:"white"},so(se.cachedTokens))),(se?.candidateTokens||0)>0&&i.createElement(k,{marginLeft:2},i.createElement(k,{width:23},i.createElement(y,{color:"grey"},"\xBB Output Tokens:")),i.createElement(y,{color:"white"},so(se.candidateTokens)))),(se?.imageCalls?.length||0)>0&&i.createElement(i.Fragment,null,i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Images Made Today:")),i.createElement(y,{color:"white"},se.imageCalls.length)),i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Image Credits Today:")),i.createElement(y,{color:"white"},Number(((se.imageCalls.reduce((x,g)=>x+g.cost,0)||0)*1e3).toFixed(0))," credits"))),i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Code Changes Today:")),i.createElement(y,{color:"white"},i.createElement(y,{color:"green"},"+",se?.linesAdded||0)," ",i.createElement(y,{color:"red"},"-",se?.linesRemoved||0))),i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Tool Calls Today:")),i.createElement(y,{color:"white"},(se?.toolSuccess||0)+(se?.toolFailure||0)+(se?.toolDenied||0)," ( "),i.createElement(y,{color:"green"},"\u2713 ",se?.toolSuccess||0),i.createElement(y,{color:"white"}," "),i.createElement(y,{color:"yellow"},"\u2298 ",se?.toolDenied||0),i.createElement(y,{color:"white"}," "),i.createElement(y,{color:"red"},"\u2715 ",se?.toolFailure||0),i.createElement(y,{color:"white"}," )"))),i.createElement(y,{dimColor:!0,marginTop:1,italic:!0},"(Press ESC to return to chat)"));case"autoExecDanger":return i.createElement(k,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:2,paddingY:1,width:"100%"},i.createElement(y,{color:"yellow",bold:!0,underline:!0},"\u26A0\uFE0F SECURITY WARNING: YOLO MODE"),i.createElement(y,{marginTop:1},"Turning this ON allows the agent to execute terminal commands automatically without requiring your approval for each step."),i.createElement(y,{marginTop:1,color:"yellow"},"RISKS INVOLVED:"),i.createElement(y,null,"\u2022 The agent may execute destructive commands (rm -rf, etc.) by mistake."),i.createElement(y,null,"\u2022 Unintended system changes if the agent hallucinates a path or command."),i.createElement(y,null,"\u2022 Reduced control over the agent's step-by-step decision making."),i.createElement(k,{marginTop:1},i.createElement(fo,{title:"Confirm Intent",items:[{label:"I know the risk and turning on intentionally",value:"on"},{label:"Keep Off (Recommended)",value:"off"}],onSelect:x=>{x.value==="on"&&te(g=>({...g,autoExec:!0})),H("settings")}})));case"externalDanger":return i.createElement(k,{flexDirection:"column",borderStyle:"round",borderColor:"red",paddingX:2,paddingY:1,width:"100%"},i.createElement(y,{color:"red",bold:!0,underline:!0},"\u26A0\uFE0F SECURITY WARNING: EXTERNAL WORKSPACE ACCESS"),i.createElement(y,{marginTop:1},"Turning this ON allows the agent to execute tools (Read/Write/Exec) outside of the current active workspace directory."),i.createElement(y,{marginTop:1,color:"yellow"},"RISKS INVOLVED:"),i.createElement(y,null,"\u2022 Access to sensitive system files (SSH keys, Browser data, etc.)"),i.createElement(y,null,"\u2022 Potential for accidental or malicious deletion of OS-critical files."),i.createElement(y,null,"\u2022 Unauthorized script execution across your entire file system."),i.createElement(k,{marginTop:1},i.createElement(fo,{title:"Confirm Intent",items:[{label:"I know the risk and turning on intentionally",value:"on"},{label:"Keep Off (Recommended)",value:"off"}],onSelect:x=>{x.value==="on"&&te(g=>({...g,allowExternalAccess:!0})),H("settings")}})));case"doubleDanger":return i.createElement(k,{flexDirection:"column",borderStyle:"round",borderColor:"red",paddingX:2,paddingY:1,width:"100%"},i.createElement(y,{color:"red",bold:!0,underline:!0},"\u26D4 CRITICAL SECURITY WARNING: COMBINED SYSTEM RISK"),i.createElement(y,{marginTop:1},"You are attempting to enable BOTH [YOLO Mode] and [External Workspace Access] simultaneously."),i.createElement(y,{marginTop:1,color:"red",bold:!0},"THIS IS NOT RECOMMENDED."),i.createElement(y,{marginTop:1,color:"yellow"},"THE CRITICAL RISK:"),i.createElement(y,null,"The agent will have the power to execute any command across your entire system WITHOUT your approval or supervision."),i.createElement(y,{color:"red",italic:!0,marginTop:1},"A single hallucination or error could result in full system wipe or data theft."),i.createElement(k,{marginTop:1},i.createElement(fo,{title:"Final Confirmation",items:[{label:"I agree knowing the consequences",value:"on"},{label:"Keep Off",value:"off"}],onSelect:x=>{x.value==="on"&&te(g=>({...g,autoExec:!0,allowExternalAccess:!0})),H("settings")}})));case"key":return i.createElement(fo,{title:"\u{1F511} API KEY MANAGEMENT",items:[{label:"Edit Current Key (Update)",value:"edit"},{label:"Remove Current Key (Purge)",value:"remove"},{label:"Cancel",value:"Cancel"}],onSelect:x=>{if(x.value==="edit"){rt(null),H("chat");let g=Ie(2);W(O=>[...O,{id:Date.now(),role:"system",text:`\u{1F511}${g}[ACTION] Flux waiting for new API Key...`}])}else x.value==="remove"?H("deleteKey"):H("chat")}});case"deleteKey":return i.createElement(k,{flexDirection:"column",borderStyle:"round",borderColor:"red",paddingX:2,paddingY:1},(()=>{let x=Ie(2);return i.createElement(y,{color:"red",bold:!0},"\u26D4",x,"DANGER: PURGE API KEY")})(),i.createElement(y,{marginTop:1},"This will permanently delete the saved API key from the project vault. You will need to enter it again to use Flux."),i.createElement(k,{marginTop:1},i.createElement(fo,{title:"Are you absolutely sure?",items:[{label:"YES, PURGE KEY",value:"yes"},{label:"NO, GO BACK",value:"no"}],onSelect:async x=>{if(x.value==="yes"){await _s(),rt(null),H("chat");let g=Ie(2);W(O=>[...O,{id:Date.now(),role:"system",text:`\u2728${g}[VAULT PURGED] API Key removed successfully.`}])}else H("key")}})));case"exit":return null;case"ask":return i.createElement(k,{width:"100%"},i.createElement(va,{question:hn?.question,options:hn?.options,onResolve:x=>{hn?.resolve&&hn.resolve(x),yr(null),H("chat")}}));case"revert":return i.createElement(k,{width:"100%",alignItems:"center",justifyContent:"center"},i.createElement(zi,{prompts:yt,onSelect:async x=>{try{let g=await kt.rollbackToBefore(x);if(g.success){let{targetPrompt:O}=g,N=$t.findIndex(E=>E.role==="user"&&E.text&&(E.text.startsWith(O)||E.text.includes(O))),M=[...$t];N!==-1&&(M=$t.slice(0,N)),W(M),ee(M.length),u(O),a(O.split(`
|
|
590
|
+
`).length>2);let $=M.filter(E=>!String(E.id).startsWith("welcome")&&!E.isMeta);await ms(Ue,null,$);let U=Ie(2);W(E=>{let D=[...E,{id:"revert-ok-"+Date.now(),role:"system",text:`\u{1F504}${U}[TIME TRAVEL] Codebase rolled back successfully! Reverted prompt loaded to input box.`,isMeta:!0}];return ee(D.length),D}),H("chat")}}catch(g){let O=Ie(2);W(N=>{let M=[...N,{id:"revert-err-"+Date.now(),role:"system",text:`\u274C${O}[TIME TRAVEL ERROR] Failed to rollback: ${g.message}`,isMeta:!0}];return ee(M.length),M}),H("chat")}},onClose:()=>H("chat")}));case"resume":return i.createElement(k,{width:"100%",alignItems:"center",justifyContent:"center"},i.createElement(Gi,{onSelect:async x=>{let g=await _o();if(g[x]){r.write("\x1B[2J\x1B[3J\x1B[H"),ct(x);let O=[...g[x].messages];O[0]?.text?.includes("\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557")||O.unshift({id:"welcome-"+Date.now(),role:"system",text:pr+`
|
|
590
591
|
|
|
591
|
-
\u{1F30A}\u26A1 Resuming Flux Flow Session...`,isMeta:!0}),
|
|
592
|
-
\u{1F680} **Restart Flux Flow to see changes.**`,isMeta:!0}])),
|
|
592
|
+
\u{1F30A}\u26A1 Resuming Flux Flow Session...`,isMeta:!0}),W(O),H("chat"),W(M=>{let $=[...M,{id:"sys-"+Date.now(),role:"system",text:`\u{1F4E1} SESSION RESUMED: [${x}]`,isMeta:!0}];return ee($.length),$})}},onDelete:async x=>await ti(x),onClose:()=>H("chat")}));case"memory":return i.createElement(k,{width:"100%",alignItems:"center",justifyContent:"center"},i.createElement(Xi,{onClose:()=>H("chat")}));case"parserDownload":return i.createElement(k,{width:"100%",alignItems:"center",justifyContent:"center"},i.createElement(Ki,{onClose:()=>H("settings")}));case"profile":return i.createElement(zs,{initialData:ve,onSave:x=>{st(x),W(g=>[...g,{id:Date.now(),role:"system",text:`\u2705 Profile updated: ${x.name} (${x.nickname})`}]),H("chat")},onCancel:()=>H("chat")});case"resolution":return i.createElement(k,{width:"100%",alignItems:"center",justifyContent:"center"},i.createElement(Vu,{data:Yo,onResolve:x=>{on(null),H("chat"),setTimeout(()=>{wt(x,!0)},500)},onEdit:x=>{on(null),H("chat"),u(x)}}));case"approval":return i.createElement(k,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:2,paddingY:1,width:"100%"},i.createElement(y,{color:"yellow",bold:!0,underline:!0},"\u{1F510} SECURITY GATE: FILE WRITE PERMISSION"),i.createElement(y,{marginTop:1},"The agent is attempting to modify: ",i.createElement(y,{color:"cyan"},ne(Ft?.args||"{}").path||"Unknown File")),Vo()?i.createElement(k,{marginTop:1,paddingX:1},i.createElement(y,{color:"cyan",italic:!0},"\u26A1\uFE0F FluxFlow Companion is active. Review the changes in your editor.")):i.createElement(k,{marginTop:1,borderStyle:"single",borderColor:"#333",paddingX:1,flexDirection:"column"},i.createElement(y,{color:"gray"},"--- PROPOSED CONTENT / DIFF ---"),(()=>{let x=ne(Ft?.args||"{}"),g=[],O=new Set;if(Object.keys(x).forEach($=>{let U=$.match(/^(replaceContent|newContent|content_to_replace|content_to_add|TargetContent|ReplacementContent|replacementContent)(\d+)?$/);if(U){let E=U[2]?parseInt(U[2]):1;O.add(E)}}),Array.from(O).sort(($,U)=>$-U).forEach($=>{let U,E;$===1?(U=x.replaceContent1??x.content_to_replace1??x.replaceContent??x.content_to_replace??x.TargetContent??null,E=x.newContent1??x.content_to_add1??x.newContent??x.content_to_add??x.ReplacementContent??x.replacementContent??null):(U=x[`replaceContent${$}`]??x[`content_to_replace${$}`]??null,E=x[`newContent${$}`]??x[`content_to_add${$}`]??null),(U!==null||E!==null)&&g.push({replace:U,new:E})}),g.length>0)return i.createElement(k,{flexDirection:"column",marginTop:1},g.map(($,U)=>{let E=$.replace!==null,D=$.new!==null;return i.createElement(k,{key:U,flexDirection:"column",marginTop:U>0?1:0},g.length>1&&i.createElement(y,{color:"gray"},"Block ",U+1,":"),E&&i.createElement(k,null,i.createElement(y,{color:"red",wrap:"anywhere",bold:!0},"- ",$.replace)),D&&i.createElement(k,{marginTop:E?1:0},i.createElement(y,{color:"green",wrap:"anywhere",bold:!0},"+ ",$.new.replace(/\[\/n\]?/g,"\\n"))))}));let M=x.content||x.ReplacementContent||x.content_to_add||x.replacementContent||x.newContent||null;return i.createElement(y,{color:"white",wrap:"anywhere"},(M?M.replace(/\[\/n\]?/g,"\\n"):null)||"Updating file content...")})()),i.createElement(k,{marginTop:1},i.createElement(fo,{title:"Action Required",items:[{label:"\u2705 Accept this time",value:"allow"},{label:"\u{1F510} Accept for this session",value:"always"},{label:"\u274C Don't accept",value:"deny"}],onSelect:x=>{x.value==="always"&&Re(!0);let g=x.value==="deny"?"deny":"allow";Ft.resolve(g),Uo(null),H("chat")}})));case"updateManager":return i.createElement(fo,{title:"Select Preferred Update Manager",subtitle:"NOTE: If you are unsure about these, go with NPM",items:[{label:"NPM (Standard)",value:"npm"},{label:"PNPM (Recommended)",value:"pnpm"},{label:"BUN (Ultra Fast)",value:"bun"},{label:"YARN (Classic)",value:"yarn"},{label:"Custom Command",value:"custom"},{label:"Back",value:"settings"}],onSelect:x=>{if(x.value==="settings"||x.value==="Back"){H("settings");return}x.value==="custom"?(Oo({label:"Enter Custom Update Command (Global install recommended):",key:"customUpdateCommand",value:Yt.customUpdateCommand,next:g=>(te(O=>({...O,updateManager:"custom",customUpdateCommand:g})),null)}),H("input")):(te(g=>({...g,updateManager:x.value})),H("settings"))}});case"update":return i.createElement(Gl,{latest:Le,current:Pn,settings:Yt,onClose:()=>H("chat"),onSuccess:()=>{W(x=>(ee(x.length+1),[...x,{id:"update-success-"+Date.now(),role:"system",text:`\u2728 **[UPDATE COMPLETED]** Flux Flow successfully upgraded to v${Le}.
|
|
593
|
+
\u{1F680} **Restart Flux Flow to see changes.**`,isMeta:!0}])),H("chat")},onUpdateSettings:x=>{H("updateManager")}});case"terminalApproval":return i.createElement(k,{flexDirection:"column",borderStyle:"round",borderColor:"red",paddingX:2,paddingY:1,width:"100%"},i.createElement(y,{color:"red",bold:!0,underline:!0},"\u{1F510} SECURITY GATE: TERMINAL COMMAND OVERSIGHT"),i.createElement(k,{marginTop:1},i.createElement(y,null,"Agent requested to run: ",i.createElement(y,{color:"yellow",bold:!0},ne(Ft?.args||"{}").command||"Unknown Command"))),i.createElement(k,{marginTop:1},i.createElement(fo,{title:"Risk Assessment Required",items:[{label:"\u{1F680} Run",value:"allow"},{label:"\u274C Deny",value:"deny"}],onSelect:x=>{Ft.resolve(x.value),Uo(null),H("chat")}})));default:return i.createElement(k,{flexDirection:"column",marginTop:1,flexShrink:0,width:"100%"},i.createElement(k,{paddingX:1,marginBottom:0,justifyContent:"space-between",width:"100%"},i.createElement(k,null,zn?i.createElement(k,null,Sr&&!Sr&&i.createElement(qu,null),i.createElement(y,{color:"magenta",bold:!0,italic:!0},Sr&&!Sr?" ":"",zn.toUpperCase()),wr&&i.createElement(y,{color:"gray",dimColor:!0,italic:!0}," ",wr)):i.createElement(y,{color:"cyan",dimColor:!0,italic:!0}," ",l.length>0&&J?"Press ESC again to clear input":"READY FOR COMMAND...")),i.createElement(k,null,i.createElement(y,{color:"gray",bold:!0},"[ "),i.createElement(y,{color:"white"},Bn||Ye),i.createElement(y,{color:"gray",bold:!0}," ]"))),i.createElement(k,{borderStyle:"round",borderColor:gn?"magenta":"cyan",paddingX:1,paddingY:0,width:"100%"},i.createElement(k,{flexDirection:"column",width:"100%"},i.createElement(k,{flexDirection:"row",width:"100%",paddingY:0},i.createElement(k,{flexShrink:0,width:4},i.createElement(y,{color:gn?"magenta":"cyan",bold:!0},gn?"\u2726 ":"\u{1F4A0} ")),i.createElement(k,{flexGrow:1},i.createElement(k,{flexGrow:1,position:"relative"},l===""&&i.createElement(k,{position:"absolute",paddingLeft:0},Et&&!Zt?i.createElement(y,{color:"yellow"},ie?" Terminal is waiting for user input. Press TAB to interact":" Press TAB to interact with terminal..."):Et&&Zt?i.createElement(y,{color:"yellow",bold:!0}," [ TERMINAL FOCUSED ] Type to interact, press TAB to exit..."):J===1?i.createElement(y,{color:"cyan",bold:!0}," Press ESC again to ",l.length>0?"clear input":"revert codebase to checkpoint","..."):i.createElement(y,{color:"gray"},Wo?" Press ESC again to cancel the request.":gn?" Enter a prompt to steer the agent.":` Send message or /cmd ... (${Ls.shortcut} for newline), @file`)),i.createElement(ua,{key:`input-${f}`,focus:!Zt,showCursor:pt,lastFocusEventTime:Wt.current,value:l,columns:h.columns,onChange:x=>{let g=x.replace(/\r\n/g,`
|
|
593
594
|
`).replace(/\r/g,`
|
|
594
595
|
`).replace(/\\\s*\n/g,`
|
|
595
|
-
`);d(g),v(!1)},onSubmit:Ze,maxRows:3,keyBindings:{submit:x=>x.return&&!x.shift&&!x.ctrl,newline:x=>x.return&&x.shift||x.return&&x.ctrl}})))))))}};return s.createElement(b,{flexDirection:"column",width:"100%"},R?s.createElement(ld,{width:r?.columns||80,height:r?.rows||24,selectedIndex:F}):s.createElement(s.Fragment,null,s.createElement(b,{flexDirection:"column",width:"100%",flexGrow:1},Pi.items.map((x,g)=>s.createElement(Ds,{key:x.id||g,msg:x,showFullThinking:pe,columns:r?.columns||80}))),s.createElement(b,{flexDirection:"column",padding:1,width:"100%"},(qt==="chat"||["ask","approval","terminalApproval"].includes(qt))&&s.createElement(b,{flexDirection:"column",width:"100%"},s.createElement(Zi,{messages:kt.slice(jn),showFullThinking:pe,columns:Math.max(20,(r?.columns||80)-1)}),Et&&s.createElement(b,{marginTop:1},s.createElement(Qr,{command:Et,output:Jt,isFocused:Qt,isPty:Io}))),de?s.createElement(b,{borderStyle:"double",borderColor:"magenta",padding:1,flexShrink:0},s.createElement(w,{color:"magenta"},"\u{1F30A} Starting Flux Flow...")):Me?bt():s.createElement(b,{borderStyle:"round",borderColor:"gray",padding:0,flexDirection:"column",flexShrink:0,width:"100%"},s.createElement(b,{paddingX:1,marginBottom:1},s.createElement(w,{color:"yellow",bold:!0},"\u{1F511}",Oe(2),"API KEY REQUIRED")),s.createElement(b,{paddingX:1,flexDirection:"column"},gt===0?s.createElement(s.Fragment,null,s.createElement(w,null,"Select your Preferred Provider:"),s.createElement(b,{marginTop:1},s.createElement(mo,{items:[{label:"Google (Free/Paid)",value:"Google"},{label:"DeepSeek (Paid)",value:"DeepSeek"},{label:"OpenRouter (Free/Paid) [EXPERIMENTAL]",value:"OpenRouter"}],onSelect:x=>{V(x.value),fe(1)}}))):s.createElement(s.Fragment,null,s.createElement(w,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)."),s.createElement(b,{marginTop:1},s.createElement(w,{color:"cyan",bold:!0},"\u{1F4A0} "),s.createElement(Cl,{value:Oo,onChange:ao,onSubmit:dr,mask:"*"})),s.createElement(b,{marginTop:1},s.createElement(w,{color:"gray",italic:!0},"(Press ESC to go back to provider selection)")))),s.createElement(b,{paddingX:1,marginTop:1},s.createElement(w,{color:"gray",dimColor:!0,italic:!0},gt===0?"(Use arrows to select and Enter to confirm)":"(Press Enter to confirm and initialize)"))),o&&s.createElement(b,{borderStyle:"round",borderColor:"red",paddingX:2,marginY:0,width:"100%"},s.createElement(w,{color:"red",bold:!0},"\u{1F534} EXIT CONFIRMATION: "),s.createElement(w,{color:"white"},"Press "),s.createElement(w,{color:"red",bold:!0},"CTRL + C"),s.createElement(w,{color:"white"}," again to exit (",n,"s). Press "),s.createElement(w,{color:"cyan",bold:!0},"ESC"),s.createElement(w,{color:"white"}," to cancel.")),s.createElement(b,{flexShrink:0,width:"100%"},s.createElement(ta,{mode:m,thinkingLevel:W,tokens:ge.tokens,tokensTotal:ge.tokens,chatId:Re,isMemoryEnabled:Wt.memory,apiTier:Ke,aiProvider:_})),qt==="exit"&&(()=>{let x=Date.now()-$i,g=nt+Ht,O=g>0?(nt/g*100).toFixed(1):"0.0",P=ir+Rn,k=P>0?(ir/P*100).toFixed(1):"0.0",$=P>0?(Rn/P*100).toFixed(1):"0.0";return s.createElement(b,{flexDirection:"column",borderStyle:"round",paddingX:3,paddingY:1,borderColor:"red",width:Math.min(100,(r?.columns||100)-2),marginTop:0,marginBottom:0},s.createElement(b,{marginBottom:1},s.createElement(w,{color:"cyan",bold:!0},"Agent powering down. ",s.createElement(w,{color:"magenta"},"Goodbye!"))),s.createElement(b,{flexDirection:"column"},s.createElement(w,{color:"white",bold:!0,underline:!0},"Interaction Summary"),s.createElement(b,{marginTop:1},s.createElement(b,{width:20},s.createElement(w,{color:"blue"},"Session ID:")),s.createElement(w,{color:"white"},Re)),s.createElement(b,null,s.createElement(b,{width:20},s.createElement(w,{color:"blue"},"Tool Calls:")),s.createElement(w,{color:"white"},nt+Ht+zo," ( ",s.createElement(w,{color:"green"},"\u2713 ",nt)," ",s.createElement(w,{color:"yellow"},"\u2298 ",zo)," ",s.createElement(w,{color:"red"},"\u2715 ",Ht)," )")),s.createElement(b,null,s.createElement(b,{width:20},s.createElement(w,{color:"blue"},"Success Rate:")),s.createElement(w,{color:"white"},O,"%")),s.createElement(b,null,s.createElement(b,{width:20},s.createElement(w,{color:"blue"},"Code Changes:")),s.createElement(w,{color:"white"},s.createElement(w,{color:"green"},"+",hs)," ",s.createElement(w,{color:"red"},"-",gs))),s.createElement(b,null,s.createElement(b,{width:20},s.createElement(w,{color:"blue"},"Tokens Consumed:")),s.createElement(w,{color:"white"},oo(ce))),ce>0&&s.createElement(s.Fragment,null,s.createElement(b,{marginLeft:2},s.createElement(b,{width:18},s.createElement(w,{color:"blue",dimColor:!0},"\xBB Input Tokens:")),s.createElement(w,{color:"white"},oo(ce-yt))),dt>0&&s.createElement(b,{marginLeft:4},s.createElement(b,{width:16},s.createElement(w,{color:"blue",dimColor:!0},"\xBB Cached:")),s.createElement(w,{color:"white"},oo(dt))),yt>0&&s.createElement(b,{marginLeft:2},s.createElement(b,{width:18},s.createElement(w,{color:"blue",dimColor:!0},"\xBB Output Tokens:")),s.createElement(w,{color:"white"},oo(yt)))),lr>0&&s.createElement(s.Fragment,null,s.createElement(b,null,s.createElement(b,{width:20},s.createElement(w,{color:"blue"},"Images Made:")),s.createElement(w,{color:"white"},lr)),s.createElement(b,null,s.createElement(b,{width:20},s.createElement(w,{color:"blue"},"Image Credits:")),s.createElement(w,{color:"white"},Number(((An||0)*1e3).toFixed(0))," credits")))),s.createElement(b,{flexDirection:"column",marginTop:1},s.createElement(w,{color:"white",bold:!0,underline:!0},"Performance"),s.createElement(b,{marginTop:1},s.createElement(b,{width:20},s.createElement(w,{color:"blue"},"Wall Time:")),s.createElement(w,{color:"white"},_o(x))),s.createElement(b,null,s.createElement(b,{width:20},s.createElement(w,{color:"blue"},"Agent Active:")),s.createElement(w,{color:"white"},_o(P))),s.createElement(b,{marginLeft:2},s.createElement(b,{width:18},s.createElement(w,{color:"blue",dimColor:!0},"\xBB API Time:")),s.createElement(w,{color:"white"},_o(ir)," (",k,"%)")),s.createElement(b,{marginLeft:2},s.createElement(b,{width:18},s.createElement(w,{color:"blue",dimColor:!0},"\xBB Tool Time:")),s.createElement(w,{color:"white"},_o(Rn)," (",$,"%)"))))})(),Ee.length>0&&(()=>{let g=Math.max(0,Math.min(T-2,Ee.length-5)),O=Ee.slice(g,g+5),P=Ee.length-(g+O.length);return s.createElement(b,{flexDirection:"column",borderStyle:"round",borderColor:"gray",paddingX:0,paddingY:0,width:"100%"},s.createElement(b,{paddingX:1,marginBottom:0,justifyContent:"space-between",width:"100%"},s.createElement(w,{color:"gray",bold:!0,dimColor:!0},Ee[0]?.cmd?.startsWith("@")?"\u{1F4C1} FILE SUGGESTIONS":"\u{1F50D} COMMAND SUGGESTIONS"),Ee[0]?.cmd?.startsWith("@")?s.createElement(w,{color:"gray",dimColor:!0,italic:!0},"(Use '#Lstart-Lend' to specify line numbers)"):l.startsWith("/model")&&Ke==="Free"?(()=>{let k="https://aistudio.google.com/billing",$="billing";return _==="DeepSeek"?(k="https://platform.deepseek.com/usage",$="billing"):_==="OpenRouter"&&(k="https://openrouter.ai/settings/profile",$="profile"),s.createElement(w,{color:"gray",dimColor:!0,italic:!0},"Paid API has more models. Configure ",s.createElement(w,{color:"cyan",underline:!0},`\x1B]8;;${k}\x07${$}\x1B]8;;\x07`)," & /settings")})():null),O.map((k,$)=>{let I=g+$===T,D=k.cmd==="gemma-4-31b-it"&&Ke!=="Free";return s.createElement(b,{key:k.cmd,flexDirection:"row",backgroundColor:I?"#2a2a2a":void 0,paddingX:1},s.createElement(b,{width:3},s.createElement(w,{color:I?"cyan":"gray",bold:I},I?" \u276F":" ")),s.createElement(b,{width:55},s.createElement(w,{color:D?"gray":I?"yellow":"white",bold:I,dimColor:D&&!I},k.cmd?.startsWith("@[")&&k.cmd?.endsWith("]")?(()=>{let q=k.cmd.slice(2,-1).split(/[/\\]/);return q[q.length-1]})():k.cmd)),s.createElement(b,{flexGrow:1},s.createElement(w,{color:"gray",italic:!0,dimColor:!I},k.desc)))}),Ee.length>5&&s.createElement(b,{paddingX:1,height:1},P>0?s.createElement(w,{color:"gray",dimColor:!0,italic:!0}," ... (",P," more commands available)"):s.createElement(w,{color:"gray",dimColor:!0,italic:!0}," (End of list)")))})())))}var xs,Ml,ld,$i,kl,hs,gs,cd,Al,Mn,dd,Il,ud,md,sr,fd,pd,Dl=le(async()=>{Ki();ea();oa();na();await la();ca();ua();pr();await dl();Kr();Er();ul();ml();await xl();nn();wl();is();Ls();no();to();yn();await Tr();El();Fn();Ti();xs=()=>{let e=(process.env.TERM_PROGRAM||"").toLowerCase();if(process.env.WT_SESSION)return"Windows Terminal";let o=t=>{let n=t.toLowerCase();for(let[i,r]of Object.entries(process.env))if(!["PATH","PWD","CWD","PS1","LS_COLORS","PROMPT"].includes(i)&&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"},Ml=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},ld=({width:e,height:o,selectedIndex:t})=>{let n=xs(),i=Ml(n);return s.createElement(b,{flexDirection:"column",alignItems:"center",justifyContent:"center",width:e,height:o},s.createElement(b,{marginBottom:1},s.createElement(w,null,sr)),s.createElement(b,{flexDirection:"column",borderStyle:"double",borderColor:"cyan",paddingX:3,paddingY:1,width:Math.min(80,e-4)},s.createElement(w,{bold:!0,color:"cyan",textAlign:"center"},"\u{1F680} UPGRADE YOUR WORKFLOW"),s.createElement(b,{marginY:1,flexDirection:"column",alignItems:"left"},s.createElement(w,null,"You're in ",s.createElement(w,{bold:!0,color:"cyan"},n),", but the ",s.createElement(w,{bold:!0,color:"magenta"},"FluxFlow-CLI Companion")," is not installed."),s.createElement(b,{flexDirection:"column",marginY:1},s.createElement(w,{color:"gray"}," \u2705 Real-time file & cursor tracking"),s.createElement(w,{color:"gray"}," \u2705 Auto-open files created by agent"),s.createElement(w,{color:"gray"}," \u2705 Native DIFF viewer for AI edits"),s.createElement(w,{color:"gray"}," \u2705 Direct IDE context sharing"),s.createElement(w,{color:"gray"}," \u2705 Surgical Diagnostic Sync"),s.createElement(w,{color:"gray"}," \u2705 Native Right-Click \u276F Chat integration"),s.createElement(w,{color:"gray"}," \u2705 Live Status in IDE"),s.createElement(w,{color:"gray"}," \u2705 Clickable terminal-to-code links"))),s.createElement(b,{flexDirection:"column",marginTop:1},i.map((r,l)=>s.createElement(b,{key:l},s.createElement(w,{color:t===l?"yellow":"white",bold:t===l},t===l?" \u276F ":" ",r.label)))),s.createElement(b,{marginTop:1,alignItems:"center",justifyContent:"center"},s.createElement(w,{dimColor:!0,italic:!0},"(Use arrows to navigate, Enter to select)"))))},$i=Date.now(),kl="https://fluxflow-cli.onrender.com/changelog.html",hs=0,gs=0,cd=_n.join(_n.dirname(id(import.meta.url)),"../package.json"),Al=JSON.parse(ro.readFileSync(cd,"utf8")),Mn=Al.version,dd=Al.date||"2026-05-20",Il=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],ud=()=>{let[e,o]=z(0);return po(()=>{let t=setInterval(()=>{o(n=>(n+1)%1e3)},33);return()=>clearInterval(t)},[]),s.createElement(w,{color:"magenta"},Il[Math.floor(e/3)%Il.length])},md=({data:e,onResolve:o,onEdit:t})=>s.createElement(b,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},s.createElement(b,{paddingX:1},s.createElement(w,{color:"magenta",bold:!0,underline:!0},"\u{1F7E3} STEERING HINT RESOLUTION")),s.createElement(b,{paddingX:1,marginTop:1},s.createElement(w,null,"The agent already finished the task before your hint was consumed.")),s.createElement(b,{marginTop:1,backgroundColor:"#222",paddingX:2,width:"100%"},s.createElement(w,{italic:!0,color:"gray"},'"',e,'"')),s.createElement(b,{paddingX:1,marginTop:1},s.createElement(w,{color:"cyan"},"How would you like to proceed?")),s.createElement(b,{marginTop:0},s.createElement(mo,{title:"Select Action",items:[{label:"Send Anyway",value:"send"},{label:"Edit Prompt",value:"edit"}],onSelect:n=>{n==="send"?o(e):t(e)}}))),sr=ad(["#00ffff","#0077ff","#ff00ff"]).multiline(`\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2557
|
|
596
|
+
`);u(g),L(!1)},onSubmit:wt,maxRows:3,keyBindings:{submit:x=>x.return&&!x.shift&&!x.ctrl,newline:x=>x.return&&x.shift||x.return&&x.ctrl}})))))))}};return i.createElement(k,{flexDirection:"column",width:"100%"},_?i.createElement(Hu,{width:r?.columns||80,height:r?.rows||24,selectedIndex:v}):i.createElement(i.Fragment,null,i.createElement(k,{flexDirection:"column",width:"100%",flexGrow:1},Hr.items.map((x,g)=>i.createElement(Ys,{key:x.id||g,msg:x,showFullThinking:ue,columns:r?.columns||80}))),i.createElement(k,{flexDirection:"column",padding:1,width:"100%"},(Vt==="chat"||["ask","approval","terminalApproval"].includes(Vt))&&i.createElement(k,{flexDirection:"column",width:"100%"},i.createElement(xa,{messages:$t.slice(Fs),showFullThinking:ue,columns:Math.max(20,(r?.columns||80)-1)}),Et&&i.createElement(k,{marginTop:1},i.createElement(as,{command:Et,output:Qt,isFocused:Zt,isPty:$o}))),ye?i.createElement(k,{borderStyle:"double",borderColor:"magenta",padding:1,flexShrink:0},i.createElement(y,{color:"magenta"},"\u{1F30A} Starting Flux Flow...")):be?wo():i.createElement(k,{borderStyle:"round",borderColor:"gray",padding:0,flexDirection:"column",flexShrink:0,width:"100%"},i.createElement(k,{paddingX:1,marginBottom:1},i.createElement(y,{color:"yellow",bold:!0},"\u{1F511}",Ie(2),"API KEY REQUIRED")),i.createElement(k,{paddingX:1,flexDirection:"column"},mt===0?i.createElement(i.Fragment,null,i.createElement(y,null,"Select your Preferred Provider:"),i.createElement(k,{marginTop:1},i.createElement(fo,{items:[{label:"Google (Free/Paid)",value:"Google"},{label:"DeepSeek (Paid)",value:"DeepSeek"},{label:"OpenRouter (Free/Paid) [EXPERIMENTAL]",value:"OpenRouter"}],onSelect:x=>{z(x.value),ce(1)}}))):i.createElement(i.Fragment,null,i.createElement(y,null,"Please enter your ",B," API Key to initialize the agent (If billing is enabled set Tier to paid in /settings \u2192 other \u2192 API Tier)."),i.createElement(k,{marginTop:1},i.createElement(y,{color:"cyan",bold:!0},"\u{1F4A0} "),i.createElement(oc,{value:Ao,onChange:co,onSubmit:Ae,mask:"*"})),i.createElement(k,{marginTop:1},i.createElement(y,{color:"gray",italic:!0},"(Press ESC to go back to provider selection)")))),i.createElement(k,{paddingX:1,marginTop:1},i.createElement(y,{color:"gray",dimColor:!0,italic:!0},mt===0?"(Use arrows to select and Enter to confirm)":"(Press Enter to confirm and initialize)"))),o&&i.createElement(k,{borderStyle:"round",borderColor:"red",paddingX:2,marginY:0,width:"100%"},i.createElement(y,{color:"red",bold:!0},"\u{1F534} EXIT CONFIRMATION: "),i.createElement(y,{color:"white"},"Press "),i.createElement(y,{color:"red",bold:!0},"CTRL + C"),i.createElement(y,{color:"white"}," again to exit (",n,"s). Press "),i.createElement(y,{color:"cyan",bold:!0},"ESC"),i.createElement(y,{color:"white"}," to cancel.")),i.createElement(k,{flexShrink:0,width:"100%"},i.createElement(wa,{mode:d,thinkingLevel:j,tokens:fe.tokens,tokensTotal:fe.tokens,chatId:Ue,isMemoryEnabled:Yt.memory,apiTier:Ge,aiProvider:B})),Vt==="exit"&&(()=>{let x=Date.now()-Qi,g=ot+Gt,O=g>0?(ot/g*100).toFixed(1):"0.0",N=hr+Vn,M=N>0?(hr/N*100).toFixed(1):"0.0",$=N>0?(Vn/N*100).toFixed(1):"0.0";return i.createElement(k,{flexDirection:"column",borderStyle:"round",paddingX:3,paddingY:1,borderColor:"red",width:Math.min(100,(r?.columns||100)-2),marginTop:0,marginBottom:0},i.createElement(k,{marginBottom:1},i.createElement(y,{bold:!0},sc(["blue","purple"])("Agent powering down. Goodbye!"))),i.createElement(k,{flexDirection:"column"},i.createElement(y,{color:"white",bold:!0,underline:!0},"Interaction Summary"),i.createElement(k,{marginTop:1},i.createElement(k,{width:20},i.createElement(y,{color:"blue"},"Session ID:")),i.createElement(y,{color:"white"},Ue)),i.createElement(k,null,i.createElement(k,{width:20},i.createElement(y,{color:"blue"},"Tool Calls:")),i.createElement(y,{color:"white"},ot+Gt+en," ( ",i.createElement(y,{color:"green"},"\u2713 ",ot)," ",i.createElement(y,{color:"yellow"},"\u2298 ",en)," ",i.createElement(y,{color:"red"},"\u2715 ",Gt)," )")),i.createElement(k,null,i.createElement(k,{width:20},i.createElement(y,{color:"blue"},"Success Rate:")),i.createElement(y,{color:"white"},O,"%")),i.createElement(k,null,i.createElement(k,{width:20},i.createElement(y,{color:"blue"},"Code Changes:")),i.createElement(y,{color:"white"},i.createElement(y,{color:"green"},"+",ks)," ",i.createElement(y,{color:"red"},"-",Is))),i.createElement(k,null,i.createElement(k,{width:20},i.createElement(y,{color:"blue"},"Tokens Consumed:")),i.createElement(y,{color:"white"},so(ae))),ae>0&&i.createElement(i.Fragment,null,i.createElement(k,{marginLeft:2},i.createElement(k,{width:18},i.createElement(y,{color:"grey"},"\xBB Input Tokens:")),i.createElement(y,{color:"white"},so(ae-xt))),at>0&&i.createElement(k,{marginLeft:4},i.createElement(k,{width:16},i.createElement(y,{color:"grey"},"\xBB Cached:")),i.createElement(y,{color:"white"},so(at))),xt>0&&i.createElement(k,{marginLeft:2},i.createElement(k,{width:18},i.createElement(y,{color:"grey"},"\xBB Output Tokens:")),i.createElement(y,{color:"white"},so(xt)))),xr>0&&i.createElement(i.Fragment,null,i.createElement(k,null,i.createElement(k,{width:20},i.createElement(y,{color:"blue"},"Images Made:")),i.createElement(y,{color:"white"},xr)),i.createElement(k,null,i.createElement(k,{width:20},i.createElement(y,{color:"blue"},"Image Credits:")),i.createElement(y,{color:"white"},Number(((_n||0)*1e3).toFixed(0))," credits")))),i.createElement(k,{flexDirection:"column",marginTop:1},i.createElement(y,{color:"white",bold:!0,underline:!0},"Performance"),i.createElement(k,{marginTop:1},i.createElement(k,{width:20},i.createElement(y,{color:"blue"},"Wall Time:")),i.createElement(y,{color:"white"},Ro(x))),i.createElement(k,null,i.createElement(k,{width:20},i.createElement(y,{color:"blue"},"Agent Active:")),i.createElement(y,{color:"white"},Ro(N))),i.createElement(k,{marginLeft:2},i.createElement(k,{width:18},i.createElement(y,{color:"grey"},"\xBB API Time:")),i.createElement(y,{color:"white"},Ro(hr)," (",M,"%)")),i.createElement(k,{marginLeft:2},i.createElement(k,{width:18},i.createElement(y,{color:"grey"},"\xBB Tool Time:")),i.createElement(y,{color:"white"},Ro(Vn)," (",$,"%)"))))})(),Ce.length>0&&(()=>{let g=Math.max(0,Math.min(T-2,Ce.length-5)),O=Ce.slice(g,g+5),N=Ce.length-(g+O.length);return i.createElement(k,{flexDirection:"column",borderStyle:"round",borderColor:"gray",paddingX:0,paddingY:0,width:"100%"},i.createElement(k,{paddingX:1,marginBottom:0,justifyContent:"space-between",width:"100%"},i.createElement(y,{color:"gray",bold:!0,dimColor:!0},Ce[0]?.cmd?.startsWith("@")?"\u{1F4C1} FILE SUGGESTIONS":"\u{1F50D} COMMAND SUGGESTIONS"),Ce[0]?.cmd?.startsWith("@")?i.createElement(y,{color:"gray",dimColor:!0,italic:!0},"(Use '#Lstart-Lend' to specify line numbers)"):l.startsWith("/model")&&Ge==="Free"?(()=>{let M="https://aistudio.google.com/billing",$="billing";return B==="DeepSeek"?(M="https://platform.deepseek.com/usage",$="billing"):B==="OpenRouter"&&(M="https://openrouter.ai/settings/profile",$="profile"),i.createElement(y,{color:"gray",dimColor:!0,italic:!0},"Paid API has more models. Configure ",i.createElement(y,{color:"cyan",underline:!0},`\x1B]8;;${M}\x07${$}\x1B]8;;\x07`)," & /settings")})():null),O.map((M,$)=>{let E=g+$===T,D=M.cmd==="gemma-4-31b-it"&&Ge!=="Free";return i.createElement(k,{key:M.cmd,flexDirection:"row",backgroundColor:E?"#2a2a2a":void 0,paddingX:1},i.createElement(k,{width:3},i.createElement(y,{color:E?"cyan":"gray",bold:E},E?" \u276F":" ")),i.createElement(k,{width:55},i.createElement(y,{color:D?"gray":E?"yellow":"white",bold:E,dimColor:D&&!E},M.cmd?.startsWith("@[")&&M.cmd?.endsWith("]")?(()=>{let G=M.cmd.slice(2,-1).split(/[/\\]/);return G[G.length-1]})():M.cmd)),i.createElement(k,{flexGrow:1},i.createElement(y,{color:"gray",italic:!0,dimColor:!E},M.desc)))}),Ce.length>5&&i.createElement(k,{paddingX:1,height:1},N>0?i.createElement(y,{color:"gray",dimColor:!0,italic:!0}," ... (",N," more commands available)"):i.createElement(y,{color:"gray",dimColor:!0,italic:!0}," (End of list)")))})())))}var Ms,ic,Hu,Qi,nc,ks,Is,Xu,ac,Pn,Ku,rc,qu,Vu,pr,zu,Ju,uc=re(async()=>{da();ya();Ta();Sa();await Ia();Ma();Aa();kr();await Bl();os();$r();Ul();Rl();await Hl();Kl();un();ql();Vl();zl();hs();Ws();Xt();Bt();rn();await Dr();ec();Wn();_i();Ms=()=>{let e=(process.env.TERM_PROGRAM||"").toLowerCase();if(process.env.WT_SESSION)return"Windows Terminal";let o=t=>{let n=t.toLowerCase();for(let[s,r]of Object.entries(process.env))if(!["PATH","PWD","CWD","PS1","LS_COLORS","PROMPT"].includes(s)&&String(r).toLowerCase().includes(n))return!0;return!1};return e==="cursor"||process.env.CURSOR_SETTINGS_DIR||o("cursor")?"Cursor":e==="windsurf"||o("windsurf")?"Windsurf":o("antigravity")?"Antigravity":e==="trae"||o("trae")?"Trae":e==="codium"||o("codium")||o("vscode-oss")?"VSCodium":o("positron")?"Positron":e==="vscode"||process.env.VSCODE_GIT_IPC_HANDLE||o("vscode")?"VS Code":process.env.INTELLIJ_TERMINAL_COMMAND_BLOCKS||o("intellij")?"JetBrains":"Terminal"},ic=e=>{let o=e==="VS Code",t=[];return o?(t.push({label:"Install Manually (VSIX)",url:"https://github.com/KushalRoyChowdhury/fluxflow-cli/releases"}),t.push({label:"Install from VS Code Marketplace",url:"https://marketplace.visualstudio.com/items?itemName=fluxflow-cli.fluxflow-cli-companion"})):t.push({label:`Download for ${e} (GitHub)`,url:"https://github.com/KushalRoyChowdhury/fluxflow-cli/releases"}),t.push({label:"Continue to CLI only",action:"dismiss"}),t},Hu=({width:e,height:o,selectedIndex:t})=>{let n=Ms(),s=ic(n);return i.createElement(k,{flexDirection:"column",alignItems:"center",justifyContent:"center",width:e,height:o},i.createElement(k,{marginBottom:1},i.createElement(y,null,pr)),i.createElement(k,{flexDirection:"column",borderStyle:"double",borderColor:"cyan",paddingX:3,paddingY:1,width:Math.min(80,e-4)},i.createElement(y,{bold:!0,color:"cyan",textAlign:"center"},"\u{1F680} UPGRADE YOUR WORKFLOW"),i.createElement(k,{marginY:1,flexDirection:"column",alignItems:"left"},i.createElement(y,null,"You're in ",i.createElement(y,{bold:!0,color:"cyan"},n),", but the ",i.createElement(y,{bold:!0,color:"magenta"},"FluxFlow-CLI Companion")," is not installed."),i.createElement(k,{flexDirection:"column",marginY:1},i.createElement(y,{color:"gray"}," \u2705 Real-time file & cursor tracking"),i.createElement(y,{color:"gray"}," \u2705 Auto-open files created by agent"),i.createElement(y,{color:"gray"}," \u2705 Native DIFF viewer for AI edits"),i.createElement(y,{color:"gray"}," \u2705 Direct IDE context sharing"),i.createElement(y,{color:"gray"}," \u2705 Surgical Diagnostic Sync"),i.createElement(y,{color:"gray"}," \u2705 Native Right-Click \u276F Chat integration"),i.createElement(y,{color:"gray"}," \u2705 Live Status in IDE"),i.createElement(y,{color:"gray"}," \u2705 Clickable terminal-to-code links"))),i.createElement(k,{flexDirection:"column",marginTop:1},s.map((r,l)=>i.createElement(k,{key:l},i.createElement(y,{color:t===l?"yellow":"white",bold:t===l},t===l?" \u276F ":" ",r.label)))),i.createElement(k,{marginTop:1,alignItems:"center",justifyContent:"center"},i.createElement(y,{dimColor:!0,italic:!0},"(Use arrows to navigate, Enter to select)"))))},Qi=Date.now(),nc="https://fluxflow-cli.onrender.com/changelog.html",ks=0,Is=0,Xu=Kn.join(Kn.dirname(Gu(import.meta.url)),"../package.json"),ac=JSON.parse(ao.readFileSync(Xu,"utf8")),Pn=ac.version,Ku=ac.date||"2026-05-20",rc=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],qu=()=>{let[e,o]=V(0);return io(()=>{let t=setInterval(()=>{o(n=>(n+1)%1e3)},33);return()=>clearInterval(t)},[]),i.createElement(y,{color:"magenta"},rc[Math.floor(e/3)%rc.length])},Vu=({data:e,onResolve:o,onEdit:t})=>i.createElement(k,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},i.createElement(k,{paddingX:1},i.createElement(y,{color:"magenta",bold:!0,underline:!0},"\u{1F7E3} STEERING HINT RESOLUTION")),i.createElement(k,{paddingX:1,marginTop:1},i.createElement(y,null,"The agent already finished the task before your hint was consumed.")),i.createElement(k,{marginTop:1,backgroundColor:"#222",paddingX:2,width:"100%"},i.createElement(y,{italic:!0,color:"gray"},'"',e,'"')),i.createElement(k,{paddingX:1,marginTop:1},i.createElement(y,{color:"cyan"},"How would you like to proceed?")),i.createElement(k,{marginTop:0},i.createElement(fo,{title:"Select Action",items:[{label:"Send Anyway",value:"send"},{label:"Edit Prompt",value:"edit"}],onSelect:n=>{n==="send"?o(e):t(e)}}))),pr=sc(["#00ffff","#0077ff","#ff00ff"]).multiline(`\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2557
|
|
596
597
|
\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u255A\u2588\u2588\u2557\u2588\u2588\u2554\u255D \u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2551
|
|
597
598
|
\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2557 \u2588\u2588\u2551
|
|
598
599
|
\u2588\u2588\u2554\u2550\u2550\u255D \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2554\u2588\u2588\u2557 \u2588\u2588\u2554\u2550\u2550\u255D \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2588\u2557\u2588\u2588\u2551
|
|
599
600
|
\u2588\u2588\u2551 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2554\u255D \u2588\u2588\u2557 \u2588\u2588\u2551 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u255A\u2588\u2588\u2588\u2554\u2588\u2588\u2588\u2554\u255D
|
|
600
|
-
\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`),
|
|
601
|
+
\u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u255D\u255A\u2550\u2550\u255D`),zu=e=>{let o=[],t=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,n=0,s;for(;(s=t.exec(e))!==null;){let r=s[1],l=s.index+s[0].length-1,u=0,f=null,m=-1,c=-1;for(let a=l;a<e.length;a++){let d=e[a];if(f){if(d===f){let p=0;for(let h=a-1;h>=0&&e[h]==="\\";h--)p++;p%2===0&&(f=null)}}else if(d==='"'||d==="'"||d==="`")f=d;else if(d==="(")u++;else if(d===")"&&(u--,u===0)){c=a;let p=a+1;for(;p<e.length&&/\s/.test(e[p]);)p++;if(p<e.length&&e[p]==="]"){m=p;break}}}if(m!==-1){let a=e.substring(n,s.index);a.trim()&&o.push({type:"output",content:a});let d=e.substring(l+1,c);o.push({type:"tool",toolName:r.trim(),args:d.trim()}),n=m+1,t.lastIndex=n}else break}if(n<e.length){let r=e.substring(n);r.trim()&&o.push({type:"output",content:r})}return o},Ju=(()=>{let e=null,o=0;return t=>{let n=Date.now();if(e&&n-o<5e3)return e;let s=[],r=l=>{try{let u=ao.readdirSync(l);for(let f of u){if(["node_modules",".git",".gemini","dist","build",".next",".cache","out"].includes(f))continue;let m=Kn.join(l,f);ao.statSync(m).isDirectory()?r(m):s.push({name:f,relativePath:Kn.relative(process.cwd(),m)})}}catch{}};return r(t),e=s,o=n,s}})()});import{spawn as Qu}from"child_process";import{fileURLToPath as dc}from"url";var Zu=4096,ed=dc(import.meta.url).endsWith(".js");if(ed&&!process.execArgv.some(e=>e.includes("max-old-space-size")))Qu(process.execPath,[`--max-old-space-size=${Zu}`,dc(import.meta.url),...process.argv.slice(2)],{stdio:"inherit"}).on("exit",o=>process.exit(o||0));else{let e=process.argv.slice(2),o=e.includes("--help")&&e[e.indexOf("--help")+1]==="commands",t=e.includes("--help")&&!o,n=e.includes("--version")||e.includes("-v"),s=e[0]==="--update";if(n||t||o||s){let p=await import("fs"),h=await import("path"),{fileURLToPath:S}=await import("url"),T=h.join(h.dirname(S(import.meta.url)),"../package.json"),I=JSON.parse(p.readFileSync(T,"utf8")).version;if(n&&(console.log(`v${I}`),process.exit(0)),t&&(console.log(`FluxFlow CLI Arguments:
|
|
601
602
|
--mode <flux|flow> Set startup mode (flux: Agent / flow: Chat)
|
|
602
603
|
--model <model_name> Set startup AI model
|
|
603
604
|
--key <key@provider> Set API key and provider
|
|
@@ -640,4 +641,4 @@ Selection: ${Te}`,isAskRecord:!0}]),me(Te)}}),j("ask")})},async()=>{if(bo.curren
|
|
|
640
641
|
/changelog View latest updates
|
|
641
642
|
/fluxflow init Create FluxFlow.md template
|
|
642
643
|
/update check Check for new version
|
|
643
|
-
/update latest Install latest release`),process.exit(0)),
|
|
644
|
+
/update latest Install latest release`),process.exit(0)),s){let L=e[1];if(L==="check"){let _=e[2]==="latest";try{let b=(await(await fetch("https://registry.npmjs.org/fluxflow-cli",{cache:"no-store"})).json())["dist-tags"]?.latest;b||(console.error("Error: Could not retrieve latest version."),process.exit(1)),console.log(_?`Latest version: v${b}`:b!==I?`A new version of FluxFlow is available: v${b} (current: v${I}). Run "fluxflow --update latest" to upgrade.`:`FluxFlow is up to date (v${I}).`)}catch(R){console.error("Error checking for updates:",R.message),process.exit(1)}process.exit(0)}else if(L==="latest"){console.log("Checking latest version and settings...");try{let v=(await(await fetch("https://registry.npmjs.org/fluxflow-cli",{cache:"no-store"})).json())["dist-tags"]?.latest;v||(console.error("Error: Could not retrieve latest version."),process.exit(1)),v===I&&(console.log(`FluxFlow is already up to date (v${I}).`),process.exit(0));let b=async()=>{let B=(await import("react")).default,{useState:z}=B,{render:mt,Box:ce,Text:Le}=await import("ink"),Je=(await import("ink-select-input")).default,ue=(await import("ink-text-input")).default;return new Promise(tt=>{let Ye=[{label:"NPM",value:"npm"},{label:"PNPM",value:"pnpm"},{label:"Yarn",value:"yarn"},{label:"Bun",value:"bun"},{label:"Custom Command",value:"custom"}],_e=({label:pt,isSelected:lo})=>B.createElement(ce,{width:"100%"},B.createElement(Le,{color:lo?"cyan":"gray",bold:lo},"\u2514\u2500 ",lo?"\u25C9":"\u25CB"," ",pt)),Me,je=()=>{let[pt,lo]=z("select"),[Wt,be]=z(""),rt=co=>{co.value==="custom"?lo("custom"):ye({manager:co.value})},Ao=co=>{ye({manager:"custom",customCommand:co})};return pt==="custom"?B.createElement(ce,{flexDirection:"column",marginY:1},B.createElement(ce,{marginBottom:1},B.createElement(Le,{color:"magenta",bold:!0},"\u{1F527} Enter custom update command:")),B.createElement(ce,{flexDirection:"row"},B.createElement(Le,{color:"cyan",bold:!0}," \u276F "),B.createElement(ue,{value:Wt,onChange:be,onSubmit:Ao})),B.createElement(ce,{marginTop:1},B.createElement(Le,{color:"gray",dimColor:!0,italic:!0}," (Press Enter to confirm)"))):B.createElement(ce,{flexDirection:"column",marginY:1},B.createElement(ce,{marginBottom:1},B.createElement(Le,{color:"magenta",bold:!0},"\u{1F4E6} Select a package manager for the update:")),B.createElement(Je,{items:Ye,onSelect:rt,itemComponent:_e,indicatorComponent:()=>null}))},ye=pt=>{Me&&Me(),tt(pt)},{unmount:ft}=mt(B.createElement(je,null));Me=ft})},A,F="",Q;try{let{loadSettings:B}=await Promise.resolve().then(()=>(os(),aa));Q=await B(),A=Q?.systemSettings?.updateManager||Q?.updateManager}catch{}if(!A){let B=await b();A=B.manager,F=B.customCommand}let j="";A==="pnpm"?j=`pnpm add -g fluxflow-cli@${v}`:A==="bun"?j=`bun add -g fluxflow-cli@${v}`:A==="yarn"?j=`yarn global add fluxflow-cli@${v}`:A==="custom"?j=F||Q?.customUpdateCommand||`npm install -g fluxflow-cli@${v}`:j=`npm install -g fluxflow-cli@${v}`,console.log(`Updating FluxFlow to v${v} using ${A}...`),console.log(`Running: ${j}`);let{execSync:Z}=await import("child_process");Z(j,{stdio:"inherit"}),console.log(`\x1B[32m\u2705 Update successful! FluxFlow updated to v${v}.\x1B[0m`)}catch(_){console.error("\x1B[31m\u274C Update failed:\x1B[0m",_.message),process.exit(1)}process.exit(0)}else console.error("Unknown update command. Available options: --update check, --update check latest, --update latest"),process.exit(1)}}let{default:r}=await import("react"),{render:l}=await import("ink"),{default:u}=await uc().then(()=>cc);process.env.NODE_NO_WARNINGS="1";let f=["cuimp","Found existing binary","Binary verified","curl.exe not found","Falling back to .bat file","DeprecationWarning"],m=console.log,c=console.warn,a=console.error,d=p=>{let h=p.map(String).join(" ");return f.some(S=>h.includes(S))};console.log=(...p)=>!d(p)&&m(...p),console.warn=(...p)=>!d(p)&&c(...p),console.error=(...p)=>!d(p)&&a(...p),process.stdout.write("\x1B[2J\x1B[3J\x1B[H"),process.stdout.isTTY&&(process.stdout.write("\x1B]0;FluxFlow\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow\x07")),l(r.createElement(u,{args:process.argv.slice(2)}),{exitOnCtrlC:!1})}
|