fluxflow-cli 4.3.4 → 4.3.6

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.
@@ -1 +1 @@
1
- import{$ as l,R as b,S as c,T as d,U as e,V as f,W as g,X as h,Y as i,Z as j,_ as k}from"./chunk-ZZAYAU4R.js";import"./chunk-ACHIC75V.js";import{c as a}from"./chunk-TKIVOTJ4.js";import"./chunk-SIINYZWE.js";import"./chunk-I27MASHH.js";import"./chunk-56EJGQU3.js";import"./chunk-GKFFLQSG.js";export{i as compressHistory,b as convertChannelThinkTags,j as deleteChatSummary,k as getAIStream,c as getCleanGroupedLength,f as getGoogleClient,h as initAI,a as isModelMultimodal,e as isTerminationSignaled,g as runJanitorTask,l as runSubagent,d as signalTermination};
1
+ import{$ as l,R as b,S as c,T as d,U as e,V as f,W as g,X as h,Y as i,Z as j,_ as k}from"./chunk-UKP6VSAF.js";import"./chunk-ACHIC75V.js";import{c as a}from"./chunk-TKIVOTJ4.js";import"./chunk-SIINYZWE.js";import"./chunk-I27MASHH.js";import"./chunk-56EJGQU3.js";import"./chunk-GKFFLQSG.js";export{i as compressHistory,b as convertChannelThinkTags,j as deleteChatSummary,k as getAIStream,c as getCleanGroupedLength,f as getGoogleClient,h as initAI,a as isModelMultimodal,e as isTerminationSignaled,g as runJanitorTask,l as runSubagent,d as signalTermination};
@@ -1,4 +1,4 @@
1
- import{e as ci}from"./chunk-3JTGIHTN.js";import{A as Bi,B as ir,C as vi,D as Di,E as lr,F as ar,G as wt,H as Vo,I as os,J as ki,K as Ii,L as Ai,M as Li,N as Oi,O as ns,P as jo,Q as dr,T as Ni,W as Fi,X as Ln,Y as Ui,Z as Xi,_ as $i,a as it,b as ht,c as dt,d as wi,e as Zr,f as Rr,g as kn,h as yi,i as xo,j as bi,k as je,l as qe,m as rr,n as In,o as es,p as Si,q as dn,r as Ht,s as Ci,t as An,u as ko,v as cn,w as sr,x as ts,y as Mi,z as Ei}from"./chunk-ZZAYAU4R.js";import{b as an,c as zr,k as Ti}from"./chunk-ACHIC75V.js";import{a as fi,b as hi,c as xi,e as Do,f as no,g as pi,h as Jr,i as Mt}from"./chunk-TKIVOTJ4.js";import{c as ui,d as mi,e as gi}from"./chunk-SIINYZWE.js";import{a as ln,b as Dn,c as ho,d as nr,e as qr,j as Qr}from"./chunk-I27MASHH.js";import{a as Pi}from"./chunk-56EJGQU3.js";import"./chunk-GKFFLQSG.js";import Es from"os";import e,{useState as q,useEffect as Qe,useRef as Ye,useMemo as hn}from"react";import{Box as c,Text as i,useInput as Cd,useStdout as Md,Static as Ed}from"ink";import Bd from"ink-spinner";import rt from"fs-extra";import Dt from"path";import{exec as yr}from"child_process";import{fileURLToPath as vd}from"url";import Ot,{useState as cr,useEffect as rs,useMemo as On,useCallback as ql,useRef as po}from"react";import{Box as Ql,Text as Rt,useInput as zl}from"ink";function Jl(t,g){return t.replace(/\t/g," ".repeat(g))}function ur(t){return t==null?"":t.replace(/\r\n/g,`
1
+ import{e as ci}from"./chunk-3JTGIHTN.js";import{A as Bi,B as ir,C as vi,D as Di,E as lr,F as ar,G as wt,H as Vo,I as os,J as ki,K as Ii,L as Ai,M as Li,N as Oi,O as ns,P as jo,Q as dr,T as Ni,W as Fi,X as Ln,Y as Ui,Z as Xi,_ as $i,a as it,b as ht,c as dt,d as wi,e as Zr,f as Rr,g as kn,h as yi,i as xo,j as bi,k as je,l as qe,m as rr,n as In,o as es,p as Si,q as dn,r as Ht,s as Ci,t as An,u as ko,v as cn,w as sr,x as ts,y as Mi,z as Ei}from"./chunk-UKP6VSAF.js";import{b as an,c as zr,k as Ti}from"./chunk-ACHIC75V.js";import{a as fi,b as hi,c as xi,e as Do,f as no,g as pi,h as Jr,i as Mt}from"./chunk-TKIVOTJ4.js";import{c as ui,d as mi,e as gi}from"./chunk-SIINYZWE.js";import{a as ln,b as Dn,c as ho,d as nr,e as qr,j as Qr}from"./chunk-I27MASHH.js";import{a as Pi}from"./chunk-56EJGQU3.js";import"./chunk-GKFFLQSG.js";import Es from"os";import e,{useState as q,useEffect as Qe,useRef as Ye,useMemo as hn}from"react";import{Box as c,Text as i,useInput as Cd,useStdout as Md,Static as Ed}from"ink";import Bd from"ink-spinner";import rt from"fs-extra";import Dt from"path";import{exec as yr}from"child_process";import{fileURLToPath as vd}from"url";import Ot,{useState as cr,useEffect as rs,useMemo as On,useCallback as ql,useRef as po}from"react";import{Box as Ql,Text as Rt,useInput as zl}from"ink";function Jl(t,g){return t.replace(/\t/g," ".repeat(g))}function ur(t){return t==null?"":t.replace(/\r\n/g,`
2
2
  `).replace(/\r/g,`
3
3
  `)}function Ko(t,g,h){let S=t,T=[...g].sort((s,v)=>s.start-v.start),p=0;for(let s of T){let v=s.start-p,u=ur(s.text).split(`
4
4
  `).length,E=s.text.length,M=(u>3?`[Pasted ${u} lines]`:`[Pasted ${E} chars]`).length,X=v+M;if(t<=v)break;if(t<X){S=s.end;break}else{let B=s.text.length-M;S+=B,p+=B}}return Math.min(S,h.length)}function ss(t,g,h,S,T=[]){let p=(t||"").slice(0,g),s=S(p).length,v=S(t||""),u=[...T].sort((O,L)=>L.start-O.start);for(let O of u){let L=S(t.slice(0,O.start)).length,$=S(O.text),ee=L+$.length,ae=ur(O.text).split(`
@@ -3,14 +3,14 @@ import{b as Qo}from"./chunk-ACHIC75V.js";import{c as zt,d as qs,g as Ie,h as Ft}
3
3
  `)[0];if(!y.includes("=")&&!y.includes(")")){d=l+1;continue}}if(g){p=l;break}d=l+1}p!==-1?(r=e.substring(i,p),t=p+1):(r=e.substring(i),t=e.length);let c=s.toLowerCase().includes("path")||["dest","source","to","from"].includes(s.toLowerCase());r=r.replace(/\\(.)/g,(l,f)=>{switch(f){case"n":return`
4
4
  `;case"r":return"\r";case"t":return" ";case"\\":return"\\";default:return f===a?a:f}})}else if(t<e.length&&e[t]==="["){let a=0,i=null,p=t,d=-1;for(let c=t;c<e.length;c++){let l=e[c];if(i&&l===i){let f=0;for(let u=c-1;u>=0&&e[u]==="\\";u--)f++;f%2===0&&(i=null)}else!i&&(l==='"'||l==="'"||l==="`")&&(i=l);if(!i&&(l==="["?a++:l==="]"&&a--,a===0)){d=c;break}}if(d!==-1){r=e.substring(p,d+1),t=d+1;try{let c=r.trim();c.startsWith("'")||c.includes("'")}catch{}}else r=e.substring(p),t=e.length}else{let a=e.substring(t),i=a.match(/,\s*\w+\s*=|(?:\s*\)\s*(?:$|\]\]))/);if(i){let p=i.index;r=a.substring(0,p).trim(),t+=p}else r=a.trim(),t=e.length}r==="true"?r=!0:r==="false"?r=!1:typeof r=="string"&&!isNaN(r)&&r.trim()!==""&&(r=Number(r)),typeof r=="string"&&(s.toLowerCase().includes("path")||["dest","source","to","from"].includes(s.toLowerCase()))&&(r=r.replace(/\x0C/g,"\\f").replace(/\x0D/g,"\\r").replace(/\x0B/g,"\\v").replace(/\x08/g,"\\b")),n[s]=r}return n};var ko=null;try{let e=await import("node-pty");ko=e.default||e}catch{}var qc=!!ko,So=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),er=e=>{if(!e)return"";let n=[[]],t=0,o=0,s=/\x1b\[([0-9;]*?)([a-zA-Z])/g,r=0,a,i=d=>{for(let c=0;c<d.length;c++){let l=d[c];if(l===`
5
5
  `)for(t++,o=0;t>=n.length;)n.push([]);else if(l==="\r")o=0;else{for(;t>=n.length;)n.push([]);let f=n[t];for(;o>f.length;)f.push(" ");f[o]=l,o++}}};for(;(a=s.exec(e))!==null;){i(e.substring(r,a.index));let d=a[1],c=a[2],l=d?d.split(";").map(Number):[];if(c==="A"){let f=l[0]||1;t=Math.max(0,t-f)}else if(c==="B"){let f=l[0]||1;for(t=t+f;t>=n.length;)n.push([])}else if(c==="C"){let f=l[0]||1;o=o+f}else if(c==="D"){let f=l[0]||1;o=Math.max(0,o-f)}else if(c==="G"){let f=(l[0]||1)-1;o=Math.max(0,f)}else if(c==="H"||c==="f"){let f=(l[0]||1)-1,u=(l[1]||1)-1;for(t=Math.max(0,f),o=Math.max(0,u);t>=n.length;)n.push([])}else if(c==="K"){let f=l[0]||0;if(t<n.length){let u=n[t];if(f===0)u.length=o;else if(f===1)for(let h=0;h<o&&h<u.length;h++)u[h]=" ";else f===2&&(u.length=0)}}else if(c==="J"){let f=l[0]||0;(f===2||f===3)&&(n.length=0,n.push([]),t=0,o=0)}r=s.lastIndex}i(e.substring(r));let p=n.map(d=>d.join(""));for(;p.length>0&&p[p.length-1]==="";)p.pop();return p.join(`
6
- `)},xt=null,Ks=!1,zc=e=>{try{xt&&(Ks&&typeof xt.write=="function"?xt.write(e):xt.stdin&&xt.stdin.writable&&xt.stdin.write(e))}catch{}},Kc=()=>{if(xt){try{Ks&&typeof xt.destroy=="function"?xt.destroy():typeof xt.kill=="function"&&(process.platform==="win32"?Zo("taskkill",["/pid",xt.pid,"/f","/t"]):xt.kill("SIGKILL"))}catch{}xt=null,Ks=!1}},tr=(e,n=!1)=>{if(process.platform!=="win32")return e;let t=[],o="",s=null,r=!1;for(let c=0;c<e.length;c++){let l=e[c];if(r){o+=l,r=!1;continue}if(l==="\\"){if(e[c+1]===" "){o+=" ",c++;continue}o+=l,r=!0;continue}s?(l===s&&(s=null),o+=l):l==='"'||l==="'"?(s=l,o+=l):l===";"&&!o.includes("://")?(o.length>0&&(t.push(o),o=""),t.push(n?";":"&")):l==="&"&&!o.includes("://")?e[c+1]==="&"?(o.length>0&&(t.push(o),o=""),t.push("&&"),c++):(o.length>0&&(t.push(o),o=""),t.push("&")):l==="|"&&!o.includes("://")?(o.length>0&&(t.push(o),o=""),t.push("|")):/\s/.test(l)?o.length>0&&(t.push(o),o=""):o+=l}o.length>0&&t.push(o);let a=c=>!(!c.includes("/")||/^(https?|file|ftp):\/\//i.test(c)||c.startsWith("@")||c.startsWith("/")&&(c.match(/\//g)||[]).length===1||/\s\/|\/\s/.test(c)||/[\(\)\{\}\;\<\>\=\'\"]/.test(c)),i=[];for(let c=0;c<t.length;c++){let l=t[c];if(l==="mkdir"&&n&&Hn()){let f=[],u=c+1;for(;u<t.length;){let h=t[u];if([">",">>","<","&","&&","|","||",";"].includes(h))break;h!=="-p"&&h!=="--parents"&&h!=="-v"&&h!=="--verbose"&&f.push(h),u++}if(f.length>0){let h=f.map(g=>{let y=g.replace(/^['"]|['"]$/g,""),m=g;return a(y)&&(m=g.replace(/\//g,"\\")),m});i.push("New-Item","-ItemType","Directory","-Force","-Path",h.join(","))}else i.push("New-Item","-ItemType","Directory","-Force");c=u-1;continue}if(l==="rm"&&n&&Hn()){let f=[],u=!1,h=!1,g=c+1;for(;g<t.length;){let m=t[g];if([">",">>","<","&","&&","|","||",";"].includes(m))break;m==="-rf"||m==="-fr"?(u=!0,h=!0):m==="-r"||m==="-R"||m==="--recursive"?u=!0:m==="-f"||m==="--force"?h=!0:f.push(m),g++}let y=["Remove-Item"];if(u&&y.push("-Recurse"),h&&y.push("-Force"),f.length>0){let m=f.map(w=>{let b=w.replace(/^['"]|['"]$/g,""),T=w;return a(b)&&(T=w.replace(/\//g,"\\")),T});y.push("-Path",m.join(","))}i.push(...y),c=g-1;continue}if(l==="cp"&&n&&Hn()){let f=[],u=!1,h=!1,g=c+1;for(;g<t.length;){let m=t[g];if([">",">>","<","&","&&","|","||",";"].includes(m))break;m==="-r"||m==="-R"||m==="--recursive"?u=!0:m==="-f"||m==="--force"?h=!0:f.push(m),g++}let y=["Copy-Item"];if(u&&y.push("-Recurse"),h&&y.push("-Force"),f.length>0){let m=f.map(w=>{let b=w.replace(/^['"]|['"]$/g,""),T=w;return a(b)&&(T=w.replace(/\//g,"\\")),T});if(m.length>1){let w=m.pop();y.push("-Path",m.join(","),"-Destination",w)}else y.push("-Path",m[0])}i.push(...y),c=g-1;continue}if(l==="touch"&&n&&Hn()){let f=[],u=c+1;for(;u<t.length;){let h=t[u];if([">",">>","<","&","&&","|","||",";"].includes(h))break;f.push(h),u++}if(f.length>0){let g=`(${f.map(y=>{let m=y.replace(/^['"]|['"]$/g,""),w=y;return a(m)&&(w=y.replace(/\//g,"\\")),w}).join(", ")}) | ForEach-Object { if (Test-Path $_) { (Get-Item $_).LastWriteTime = [System.DateTime]::Now } else { $null | Out-File -FilePath $_ } }`;i.push(g)}c=u-1;continue}if(l==="|"&&t[c+1]==="tee"){t[c+2]==="-a"?(i.push(">>"),c+=2):(i.push(">"),c+=1);continue}if(l==="|"&&t[c+1]==="cat"&&t[c+2]===">"){i.push(">"),c+=2;continue}if(l==="|"){let f=t[c+1];if(f){let u=f.replace(/^['"]|['"]$/g,""),h=/\.(txt|md|json|log|csv|html|css|py|js|xml|yaml|yml|pdf|docx|pptx|xlsx)$/i.test(u);if(a(u)&&h){i.push(">");continue}}}i.push(l)}let p=!1,d=i.map(c=>{if(c==="echo")return p=!0,c;[">",">>","<","&","&&","|","||",";"].includes(c)&&(p=!1);let f=/^['"]|['"]$/.test(c),u=c;p&&f&&(u=c.replace(/^['"]|['"]$/g,""));let h=/^['"]|['"]$/.test(u),g=u.replace(/^['"]|['"]$/g,"");a(g)&&(u=u.replace(/\//g,"\\"));let y=u.replace(/^['"]|['"]$/g,"");return y.includes(" ")&&!h&&(u=`"${y}"`),u});if(n){let c="",l=0;for(let f=0;f<d.length;f++){let u=d[f];u==="&&"?(c+="; if ($?) {",l++):u===";"?(c+=" }".repeat(l)+";",l=0):(c&&!c.endsWith(" ")&&!c.endsWith("{")&&(c+=" "),c+=u)}return c+=" }".repeat(l),c}return d.join(" ")},nr=async(e,n={})=>{let{command:t}=O(e),{onChunk:o}=n;if(!t)return'ERROR: Missing "command" argument for exec_command.';let s=process.platform==="win32",r=n.systemSettings||{},a={};return r.networkAccess===!1&&(a.HTTP_PROXY="http://127.0.0.1:9999",a.HTTPS_PROXY="http://127.0.0.1:9999",a.ALL_PROXY="socks5://127.0.0.1:9999",a.http_proxy="http://127.0.0.1:9999",a.https_proxy="http://127.0.0.1:9999",a.all_proxy="socks5://127.0.0.1:9999",a.NO_PROXY="localhost,127.0.0.1"),new Promise(i=>{let p=d=>{let c=d==="pwsh"||d==="powershell",l=tr(t,c),f;s?d==="pwsh"?f="C:\\Users\\User\\AppData\\Local\\Microsoft\\WindowsApps\\pwsh.exe":d==="powershell"?f="powershell.exe":f="cmd.exe":f=process.env.SHELL||"bash";let u=s?c?["-NoProfile","-Command",l]:["/c",l]:["-c",l];if(r.networkAccess===!1&&!s){let h=f,g=[...u];if(process.platform==="linux")f="unshare",u=["-n","-r",h,...g];else if(process.platform==="darwin"){let y=`(version 1)
6
+ `)},yt=null,Ks=!1,zc=e=>{try{yt&&(Ks&&typeof yt.write=="function"?yt.write(e):yt.stdin&&yt.stdin.writable&&yt.stdin.write(e))}catch{}},Kc=()=>{if(yt){try{Ks&&typeof yt.destroy=="function"?yt.destroy():typeof yt.kill=="function"&&(process.platform==="win32"?Zo("taskkill",["/pid",yt.pid,"/f","/t"]):yt.kill("SIGKILL"))}catch{}yt=null,Ks=!1}},tr=(e,n=!1)=>{if(process.platform!=="win32")return e;let t=[],o="",s=null,r=!1;for(let c=0;c<e.length;c++){let l=e[c];if(r){o+=l,r=!1;continue}if(l==="\\"){if(e[c+1]===" "){o+=" ",c++;continue}o+=l,r=!0;continue}s?(l===s&&(s=null),o+=l):l==='"'||l==="'"?(s=l,o+=l):l===";"&&!o.includes("://")?(o.length>0&&(t.push(o),o=""),t.push(n?";":"&")):l==="&"&&!o.includes("://")?e[c+1]==="&"?(o.length>0&&(t.push(o),o=""),t.push("&&"),c++):(o.length>0&&(t.push(o),o=""),t.push("&")):l==="|"&&!o.includes("://")?(o.length>0&&(t.push(o),o=""),t.push("|")):/\s/.test(l)?o.length>0&&(t.push(o),o=""):o+=l}o.length>0&&t.push(o);let a=c=>!(!c.includes("/")||/^(https?|file|ftp):\/\//i.test(c)||c.startsWith("@")||c.startsWith("/")&&(c.match(/\//g)||[]).length===1||/\s\/|\/\s/.test(c)||/[\(\)\{\}\;\<\>\=\'\"]/.test(c)),i=[];for(let c=0;c<t.length;c++){let l=t[c];if(l==="mkdir"&&n&&Hn()){let f=[],u=c+1;for(;u<t.length;){let h=t[u];if([">",">>","<","&","&&","|","||",";"].includes(h))break;h!=="-p"&&h!=="--parents"&&h!=="-v"&&h!=="--verbose"&&f.push(h),u++}if(f.length>0){let h=f.map(g=>{let y=g.replace(/^['"]|['"]$/g,""),m=g;return a(y)&&(m=g.replace(/\//g,"\\")),m});i.push("New-Item","-ItemType","Directory","-Force","-Path",h.join(","))}else i.push("New-Item","-ItemType","Directory","-Force");c=u-1;continue}if(l==="rm"&&n&&Hn()){let f=[],u=!1,h=!1,g=c+1;for(;g<t.length;){let m=t[g];if([">",">>","<","&","&&","|","||",";"].includes(m))break;m==="-rf"||m==="-fr"?(u=!0,h=!0):m==="-r"||m==="-R"||m==="--recursive"?u=!0:m==="-f"||m==="--force"?h=!0:f.push(m),g++}let y=["Remove-Item"];if(u&&y.push("-Recurse"),h&&y.push("-Force"),f.length>0){let m=f.map(w=>{let b=w.replace(/^['"]|['"]$/g,""),T=w;return a(b)&&(T=w.replace(/\//g,"\\")),T});y.push("-Path",m.join(","))}i.push(...y),c=g-1;continue}if(l==="cp"&&n&&Hn()){let f=[],u=!1,h=!1,g=c+1;for(;g<t.length;){let m=t[g];if([">",">>","<","&","&&","|","||",";"].includes(m))break;m==="-r"||m==="-R"||m==="--recursive"?u=!0:m==="-f"||m==="--force"?h=!0:f.push(m),g++}let y=["Copy-Item"];if(u&&y.push("-Recurse"),h&&y.push("-Force"),f.length>0){let m=f.map(w=>{let b=w.replace(/^['"]|['"]$/g,""),T=w;return a(b)&&(T=w.replace(/\//g,"\\")),T});if(m.length>1){let w=m.pop();y.push("-Path",m.join(","),"-Destination",w)}else y.push("-Path",m[0])}i.push(...y),c=g-1;continue}if(l==="touch"&&n&&Hn()){let f=[],u=c+1;for(;u<t.length;){let h=t[u];if([">",">>","<","&","&&","|","||",";"].includes(h))break;f.push(h),u++}if(f.length>0){let g=`(${f.map(y=>{let m=y.replace(/^['"]|['"]$/g,""),w=y;return a(m)&&(w=y.replace(/\//g,"\\")),w}).join(", ")}) | ForEach-Object { if (Test-Path $_) { (Get-Item $_).LastWriteTime = [System.DateTime]::Now } else { $null | Out-File -FilePath $_ } }`;i.push(g)}c=u-1;continue}if(l==="|"&&t[c+1]==="tee"){t[c+2]==="-a"?(i.push(">>"),c+=2):(i.push(">"),c+=1);continue}if(l==="|"&&t[c+1]==="cat"&&t[c+2]===">"){i.push(">"),c+=2;continue}if(l==="|"){let f=t[c+1];if(f){let u=f.replace(/^['"]|['"]$/g,""),h=/\.(txt|md|json|log|csv|html|css|py|js|xml|yaml|yml|pdf|docx|pptx|xlsx)$/i.test(u);if(a(u)&&h){i.push(">");continue}}}i.push(l)}let p=!1,d=i.map(c=>{if(c==="echo")return p=!0,c;[">",">>","<","&","&&","|","||",";"].includes(c)&&(p=!1);let f=/^['"]|['"]$/.test(c),u=c;p&&f&&(u=c.replace(/^['"]|['"]$/g,""));let h=/^['"]|['"]$/.test(u),g=u.replace(/^['"]|['"]$/g,"");a(g)&&(u=u.replace(/\//g,"\\"));let y=u.replace(/^['"]|['"]$/g,"");return y.includes(" ")&&!h&&(u=`"${y}"`),u});if(n){let c="",l=0;for(let f=0;f<d.length;f++){let u=d[f];u==="&&"?(c+="; if ($?) {",l++):u===";"?(c+=" }".repeat(l)+";",l=0):(c&&!c.endsWith(" ")&&!c.endsWith("{")&&(c+=" "),c+=u)}return c+=" }".repeat(l),c}return d.join(" ")},nr=async(e,n={})=>{let{command:t}=O(e),{onChunk:o}=n;if(!t)return'ERROR: Missing "command" argument for exec_command.';let s=process.platform==="win32",r=n.systemSettings||{},a={};return r.networkAccess===!1&&(a.HTTP_PROXY="http://127.0.0.1:9999",a.HTTPS_PROXY="http://127.0.0.1:9999",a.ALL_PROXY="socks5://127.0.0.1:9999",a.http_proxy="http://127.0.0.1:9999",a.https_proxy="http://127.0.0.1:9999",a.all_proxy="socks5://127.0.0.1:9999",a.NO_PROXY="localhost,127.0.0.1"),new Promise(i=>{let p=d=>{let c=d==="pwsh"||d==="powershell",l=tr(t,c),f;s?d==="pwsh"?f="C:\\Users\\User\\AppData\\Local\\Microsoft\\WindowsApps\\pwsh.exe":d==="powershell"?f="powershell.exe":f="cmd.exe":f=process.env.SHELL||"bash";let u=s?c?["-NoProfile","-Command",l]:["/c",l]:["-c",l];if(r.networkAccess===!1&&!s){let h=f,g=[...u];if(process.platform==="linux")f="unshare",u=["-n","-r",h,...g];else if(process.platform==="darwin"){let y=`(version 1)
7
7
  (allow default)
8
8
  (deny network-outbound)
9
9
  (allow network-outbound (remote ip "localhost:*"))
10
10
  (allow network-outbound (remote ip "127.0.0.1:*"))
11
- `;f="sandbox-exec",u=["-p",y,h,...g]}}if(ko)try{let h=ko.spawn(f,u,{name:"xterm-256color",cols:n.cols||120,rows:n.rows||30,cwd:process.cwd(),env:{...process.env,CI:"false",TERM:"xterm-256color",FORCE_COLOR:"1",...a}});xt=h,Ks=!0;let g="",y=!1;return h.onData(m=>{if(!y){g+=m,o&&o(m);let w=So(g);/(?:Network:\s+use\s+--host\s+to|Network:\s+Type\s+--host\s+to|Local:\s+http:\/\/localhost:\d+|ready in \d+\s*ms|Compiled successfully|Development server is running|Listening on:)/i.test(w)&&(y=!0,setTimeout(()=>i(`SUCCESS: Dev server started successfully in background.
11
+ `;f="sandbox-exec",u=["-p",y,h,...g]}}if(ko)try{let h=ko.spawn(f,u,{name:"xterm-256color",cols:n.cols||120,rows:n.rows||30,cwd:process.cwd(),env:{...process.env,CI:"false",TERM:"xterm-256color",FORCE_COLOR:"1",...a}});yt=h,Ks=!0;let g="",y=!1;return h.onData(m=>{if(!y){g+=m,o&&o(m);let w=So(g);/(?:Network:\s+use\s+--host\s+to|Network:\s+Type\s+--host\s+to|Local:\s+http:\/\/localhost:\d+|ready in \d+\s*ms|Compiled successfully|Development server is running|Listening on:)/i.test(w)&&(y=!0,setTimeout(()=>i(`SUCCESS: Dev server started successfully in background.
12
12
 
13
- ${w}`),500))}}),h.onExit(({exitCode:m})=>{if(y)return;xt=null;let w=er(g||""),b=So(w).replace(/\n{3,}/g,`
13
+ ${w}`),500))}}),h.onExit(({exitCode:m})=>{if(y)return;yt=null;let w=er(g||""),b=So(w).replace(/\n{3,}/g,`
14
14
 
15
15
  `)||"Command executed with no output.";i(m!==0?`ERROR: Command [${t}] failed with exit code [${m}].
16
16
 
@@ -21,9 +21,9 @@ ${b}`)}),!0}catch(h){return s&&(d==="pwsh"||d==="powershell")&&h.code==="ENOENT"
21
21
  (deny network-outbound)
22
22
  (allow network-outbound (remote ip "localhost:*"))
23
23
  (allow network-outbound (remote ip "127.0.0.1:*"))
24
- `;d="sandbox-exec",c=["-p",m,g,...y]}}let l=i?Zo(d,c,{cwd:process.cwd(),env:{...process.env,...o}}):Zo(d,c,{cwd:process.cwd(),env:{...process.env,CI:"false",TERM:"xterm-256color",FORCE_COLOR:"1",...o}});xt=l,Ks=!1,l.stdin&&l.stdin.on("error",()=>{xt=null});let f="",u="",h=!1;l.stdout.on("data",g=>{if(!h){let y=g.toString();f+=y,s&&s(y);let m=So(f);/(?: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(m)&&(h=!0,setTimeout(()=>e(`SUCCESS: Dev server started successfully in background.
24
+ `;d="sandbox-exec",c=["-p",m,g,...y]}}let l=i?Zo(d,c,{cwd:process.cwd(),env:{...process.env,...o}}):Zo(d,c,{cwd:process.cwd(),env:{...process.env,CI:"false",TERM:"xterm-256color",FORCE_COLOR:"1",...o}});yt=l,Ks=!1,l.stdin&&l.stdin.on("error",()=>{yt=null});let f="",u="",h=!1;l.stdout.on("data",g=>{if(!h){let y=g.toString();f+=y,s&&s(y);let m=So(f);/(?: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(m)&&(h=!0,setTimeout(()=>e(`SUCCESS: Dev server started successfully in background.
25
25
 
26
- ${m}`),500))}}),l.stderr.on("data",g=>{if(!h){let y=g.toString();u+=y,s&&s(y)}}),l.on("close",g=>{if(h)return;xt=null;let y=[],m=er(f),w=er(u);m&&y.push(`STDOUT:
26
+ ${m}`),500))}}),l.stderr.on("data",g=>{if(!h){let y=g.toString();u+=y,s&&s(y)}}),l.on("close",g=>{if(h)return;yt=null;let y=[],m=er(f),w=er(u);m&&y.push(`STDOUT:
27
27
  ${m}`),w&&y.push(`STDERR:
28
28
  ${w}`),g!==0&&y.push(`EXIT CODE: ${g}`);let b=y.join(`
29
29
 
@@ -33,7 +33,7 @@ ${w}`),g!==0&&y.push(`EXIT CODE: ${g}`);let b=y.join(`
33
33
 
34
34
  ${T}`:`SUCCESS: Command [${t}] completed.
35
35
 
36
- ${T}`)}),l.on("error",g=>{if(i&&g.code==="ENOENT"){if(r==="pwsh"){let m=tr(t,!0);return To(e,m,t,o,s,"powershell",a)}else if(r==="powershell"){let m=tr(t,!1);return To(e,m,t,o,s,"cmd",a)}}xt=null;let y=g instanceof Error?g.message:String(g);e(`ERROR: Failed to start command [${t}]: ${y}`)})};var Ys=null,Hn=()=>{if(process.platform!=="win32")return!1;if(Ys!==null)return Ys;try{el('powershell.exe -NoProfile -Command "exit"',{stdio:"ignore"}),Ys=!0}catch{Ys=!1}return Ys},sr=null,ki=(e,n,t,o,s=!1,r=!0)=>{sr===null&&(sr=s);let a=`- JSON escape literal escape sequences in tool arguments
36
+ ${T}`)}),l.on("error",g=>{if(i&&g.code==="ENOENT"){if(r==="pwsh"){let m=tr(t,!0);return To(e,m,t,o,s,"powershell",a)}else if(r==="powershell"){let m=tr(t,!1);return To(e,m,t,o,s,"cmd",a)}}yt=null;let y=g instanceof Error?g.message:String(g);e(`ERROR: Failed to start command [${t}]: ${y}`)})};var Ys=null,Hn=()=>{if(process.platform!=="win32")return!1;if(Ys!==null)return Ys;try{el('powershell.exe -NoProfile -Command "exit"',{stdio:"ignore"}),Ys=!0}catch{Ys=!1}return Ys},sr=null,ki=(e,n,t,o,s=!1,r=!0)=>{sr===null&&(sr=s);let a=`- JSON escape literal escape sequences in tool arguments
37
37
  - Same file, multiple edits? One PatchFile (\u226415 blocks) \u2190 Priority
38
38
  - Tool denied? Ask for guidance \u2190 mandatory
39
39
  - Need text or huge file? CodeSearch > Full Read
@@ -43,9 +43,9 @@ ${T}`)}),l.on("error",g=>{if(i&&g.code==="ENOENT"){if(r==="pwsh"){let m=tr(t,!0)
43
43
  `,i=`**Workspace Tools (path = relative; first argument, path separator: '/')**
44
44
  - ReadFile(path="...", startLine="int", endLine="int")${o!=="Google"?`${t?". Supports images/docs":""}`:". Supports images/docs"}
45
45
  - ReadFolder(path="...", recurse="int 1-3"). Minimize recursion
46
- - PatchFile(path="...", allowMultiple="bool, default: false", searchContent1="search string OR ^LINE:start..end$", newContent1="...", ...MAX15). Use small searchContent. Line Ranges must for large searchContent and escape sequences. ^...$ must for line ranges
46
+ - PatchFile(path="...", allowMultiple="bool, false", searchContent1="search string OR ^LINE:start..end$", newContent1="...", ...MAX15). Use small searchContent. Line Ranges must for large searchContent and escape sequences. ^...$ must for line ranges
47
47
  - WriteFile(path="...", content="..."). Creates/Overwrites. File Exist? PatchFile > WriteFile
48
- - CodeSearch(keyword="...", path="dir/file/glob/regex, inclusion/exclusion ;-separated", fuzzy="bool false", regex="bool auto"). Find definitions, logic, relevant code, standard junk auto-excluded
48
+ - CodeSearch(keyword="...", path="dir/file/glob/regex, inclusion/exclusion ;-separated", fuzzy="bool, false", regex="bool, auto"). Find definitions, logic, relevant code, standard junk auto-excluded
49
49
  - Run(command="..."). Runs ${n==="Windows"?Hn()?"powershell":"windows CMD":"bash"} command. Destructive/Irreversible ops \u2192 Ask user
50
50
  - Goal(method="create/append/get", tasks=[string array], markDone=[task array]). If long multi-task: create Goals before starting. \`get + markDone\` to mark complete. Update every turn when created
51
51
  ${sr?'\n**Emergency Tools**\nInfo: `initial` = current task prompt. Revert `id` = turn before disaster (eg. disaster: `turn_3` \u2192 revert: `turn_2`). Reason explicitly\n- EmergencyRollback(method="getCheckpoint/forceRevert", id="..."). Rollback workspace in this agent loop. ONLY for catastrophic corruption. Before ending, verify no catastrophe. `id` omitted for `getCheckpoint`\n':""}${r?`
@@ -68,7 +68,7 @@ Invocations:
68
68
  - KeyPress(key="key or ;-separated combination, eg: enter, back, backspace, clearInput, ctrl;c, alt;tab, f5, f11, alt;f4"). Press key, shortcut, function key (f1-f12), or clear active input field
69
69
  - RecaptureScreen(). Request fresh gridded screenshot`;return`
70
70
  -- TOOLS --
71
- You cant execute tools. To call tools, must output exactly [tool:functions.ToolName(arg1="value1")] structured string in chat response \u2190 no exception, verify correct syntax/brackets
71
+ You cant execute tools. To use tools, must output exactly [tool:functions.ToolName(arg1="value1")] structured string in chat response \u2190 no exception, tool:functions must
72
72
  Tool Rules:
73
73
  - Max 3 tool calls/turn${e==="Flux"||e.toLowerCase()==="fluxcu"?" (Todo: 3+)":""}
74
74
  ${e==="Flux"||e.toLowerCase()==="fluxcu"?`${a}`:""}
@@ -76,7 +76,7 @@ ${e==="Flux"||e.toLowerCase()==="fluxcu"?`${a}`:""}
76
76
  - Ask(question="...", optionA="title::description", ...MAX4). Ambiguity, path divergence, security risk. Ask, dont finish/guess. Keep titles short
77
77
 
78
78
  **Web Tools**
79
- - WebSearch(query="...", aiMode="bool", limit="integer 3-10 aiMode: exclude"). Proactive use for unknown info/docs. aiMode: LLM search
79
+ - WebSearch(query="...", aiMode="bool, optional", limit="integer 3-10 aiMode: exclude"). Proactive use for unknown info/docs. aiMode: LLM search
80
80
  - WebScrape(url="..."). Proactive use for specific webpage/docs/api
81
81
 
82
82
  ${e==="ICU"?`${d}`:e==="FluxCU"?`${i}
@@ -146,7 +146,7 @@ ${R.map(k=>`- ${k.name}: ${k.desc}`).join(`
146
146
  `)}
147
147
  Check these first; These Files > Training Data. Safety rules apply
148
148
  `:""}let $=or;return`=== SYSTEM PROMPT ===
149
- Identity: Flux Flow. Sassy, Friendly, CLI Agent${sl?"":" by Kushal Roy Chowdhury"}
149
+ Identity: Flux Flow. Sassy, Friendly, CLI assistant${sl?"":" by Kushal Roy"}
150
150
  ${t==="Flux"?"Stepwise Execution, Run Automated Tests. Task Completion":t==="Flow"?"Concise, Humorous, Sarcastic":t==="ICU"?"Computer Use Capabilities. Screenshot as ground truth, analyze grid ids overlapping/close to target, keyboard shortcuts > mouse clicks":"Computer Use & Workspace Capabilities. Screenshot as ground truth, analyze grid ids overlapping/close to target, keyboard shortcuts > mouse clicks. Workspace Tools if faster. Focus on Productivity"}${Ei&&t.toLowerCase().includes("cu")?`
151
151
  **Running on secondary screen. Opened app not visible in screenshot? Might be opened on primary. Use 'Ask' immediately with NO options and tell user to move app window to secondary**`:""}
152
152
 
@@ -204,7 +204,7 @@ ${e}`:""}`.trim();import Ct from"fs-extra";import Eo from"path";import{nanoid as
204
204
  `+l.body.join(`
205
205
  `):"");p.push(u)}let c=p.join(`
206
206
  `).trim();c?await Ct.writeFile(e,c+`
207
- `,"utf8"):await Ct.writeFile(e,"","utf8")}catch{}},$d=async e=>{try{if(!await Ct.pathExists(e))return;let n=async t=>{let o=await Ct.readdir(t);for(let s of o){let r=Eo.join(t,s);(await Ct.stat(r)).isDirectory()?(await n(r),(await Ct.readdir(r)).length===0&&await Ct.remove(r)):s.endsWith(".log")&&await dl(r)}};await n(e)}catch{}},vi=(e,n=4)=>{if(e.length<=1)return e;let t=e[0],o=e.slice(1),s=n*2,r=o.slice(s);return[t,...r]};var Cd=async(e,n,t)=>_o(async()=>{let o=Z(jn,[]);Array.isArray(o)||(o=[]);let s={total:n,context:t},r=o.findIndex(a=>Object.keys(a)[0]===String(e));r!==-1?o[r]={[String(e)]:s}:o.push({[String(e)]:s}),me(jn,o)}),Md=async e=>{try{if(!await Ct.pathExists(jn))return{total:0,context:0};let n=Z(jn,[]);if(!Array.isArray(n))return{total:0,context:0};let t=n.find(o=>Object.keys(o)[0]===String(e));return t?t[String(e)]:{total:0,context:0}}catch{return{total:0,context:0}}};import bt from"fs-extra";import Ii from"path";var fl=()=>Math.random().toString(36).substring(2)+Date.now().toString(36),ae=null,Gn=null,Oi=0,Cs=!1,vn={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:[]},Ms=(e,n)=>{if(!e)return{};let t=Object.keys(e),o=new Date(new Date(n).getTime()-720*60*60*1e3),s={};for(let r of t)new Date(r)>=o&&(s[r]=e[r]);return s},$o=async()=>{let e=new Date().toISOString().split("T")[0];try{!await bt.exists(en)&&await bt.exists(Xo)&&(await bt.ensureDir(Ii.dirname(en)),await bt.move(Xo,en))}catch{}let n=en+".tmp",t=null;try{if(await bt.exists(n)){let s=(await bt.readFile(n,"utf8")).trim(),r=null;if(s.startsWith("{")||s.startsWith("[")?r=JSON.parse(s):r=JSON.parse($s(s)),r&&r.date&&r.stats){t=r;try{await bt.rename(n,en)}catch{}}else try{await bt.remove(n)}catch{}}}catch{try{await bt.remove(n)}catch{}}if(!t)try{if(await bt.exists(en)){let s=(await bt.readFile(en,"utf8")).trim();s.startsWith("{")||s.startsWith("[")?t=JSON.parse(s):t=JSON.parse($s(s))}}catch{}let o=t;if(o){let s=o.stats||{...vn},r={...vn,...s};Array.isArray(r.imageCalls)||(r.imageCalls=[]);let a=o.history||{},i=Ms(a,e);if(Object.keys(a).length!==Object.keys(i).length&&(Cs=!0),o.date===e)return{...o,stats:r,history:i};{let p=o.date,d=r,c={...i};return p&&(c[p]=d),{date:e,stats:{...vn},history:Ms(c,e)}}}return{date:e,stats:{...vn},history:{}}},ir=async()=>{if(!(!Cs||!ae))try{await bt.ensureDir(Ii.dirname(en));let e=null;try{if(await bt.exists(en)){let s=(await bt.readFile(en,"utf8")).trim();s.startsWith("{")||s.startsWith("[")?e=JSON.parse(s):e=JSON.parse($s(s))}}catch{}if(e&&e.date===ae.date&&e.stats){for(let s in ae.stats)if(e.stats[s]!==void 0){if(Array.isArray(ae.stats[s])){let r=Array.isArray(e.stats[s])?e.stats[s]:[],a=ae.stats[s],i=new Map;for(let p of[...r,...a])p&&p.timestamp&&i.set(p.timestamp,p);ae.stats[s]=Array.from(i.values())}else if(typeof ae.stats[s]=="number")ae.stats[s]=Math.max(ae.stats[s],Number(e.stats[s])||0);else if(ae.stats[s]&&typeof ae.stats[s]=="object"){let r=e.stats[s]||{},a=ae.stats[s];for(let i in r)if(typeof r[i]=="number")a[i]=Math.max(a[i]||0,r[i]);else if(r[i]&&typeof r[i]=="object"){a[i]||(a[i]={});for(let p in r[i])if(typeof r[i][p]=="number")a[i][p]=Math.max(a[i][p]||0,r[i][p]);else if(r[i][p]&&typeof r[i][p]=="object"){a[i][p]||(a[i][p]={});for(let d in r[i][p])a[i][p][d]=Math.max(a[i][p][d]||0,r[i][p][d])}}}}}if(e&&e.history){let s={...ae.history||{}};for(let r in e.history)if(s[r])for(let a in s[r])if(a==="imageCalls"){let i=Array.isArray(e.history[r].imageCalls)?e.history[r].imageCalls:[],p=Array.isArray(s[r].imageCalls)?s[r].imageCalls:[],d=new Map;for(let c of[...i,...p])c&&c.timestamp&&d.set(c.timestamp,c);s[r].imageCalls=Array.from(d.values())}else typeof s[r][a]=="number"&&(s[r][a]=Math.max(s[r][a],Number(e.history[r][a])||0));else s[r]=e.history[r];ae.history=Ms(s,ae.date||today)}else if(ae&&ae.history){let s=new Date().toISOString().split("T")[0];ae.history=Ms(ae.history,s)}ae.saveId=fl();let n=en+".tmp",t=Gs(JSON.stringify(ae,null,2));await bt.writeFile(n,t,"utf8");let o=await bt.open(n,"r+");await bt.fsync(o),await bt.close(o),await bt.rename(n,en),Cs=!1,Oi=Date.now()}catch{}},Co=()=>{if(Cs=!0,Gn)return;let e=Date.now(),n=Math.max(0,1500-(e-Oi));Gn=setTimeout(async()=>{await ir(),Gn=null},n),Gn.unref&&Gn.unref()},Dd=async()=>{ae=await $o(),Cs&&Co()},Fd=async()=>{Gn&&(clearTimeout(Gn),Gn=null),await ir()},Sn=async()=>{let e=new Date().toISOString().split("T")[0];if(!ae)ae=await $o();else if(ae.date!==e){let n=ae.date,t=ae.stats,o=ae.history||{};t&&(o[n]=t),ae={date:e,stats:{...vn},history:Ms(o,e)},Cs=!0,await ir()}return ae&&ae.stats&&!Array.isArray(ae.stats.imageCalls)&&(ae.stats.imageCalls=[]),ae.stats},ul=async()=>{let e=new Date().toISOString().split("T")[0];ae||(ae=await $o()),ae.date!==e&&await Sn();let n=ae.history||{},t=Ms(n,e);ae.history=t;let o=ae.stats||{...vn},s={...vn};s.imageCalls=[],s.models={};let r=(a,i)=>{for(let p in a)if(p==="imageCalls")a.imageCalls=[...a.imageCalls||[],...i.imageCalls||[]];else if(p==="models"){let d=i.models||{};for(let c in d){a.models[c]||(a.models[c]={});for(let l in d[c]){a.models[c][l]||(a.models[c][l]={tokens:0,cachedTokens:0,candidateTokens:0});let f=a.models[c][l],u=d[c][l];f.tokens+=u.tokens||0,f.cachedTokens+=u.cachedTokens||0,f.candidateTokens+=u.candidateTokens||0}}}else typeof a[p]=="number"&&(a[p]+=i[p]||0)};r(s,o);for(let a in t)r(s,t[a]);return s},Ot=async(e,n)=>{e==="toolSuccess"?Xs.toolSuccess++:e==="toolFailure"?Xs.toolFailure++:e==="toolDenied"&&Xs.toolDenied++;let t=await Sn();t[e]!==void 0&&t[e]++,n&&e==="agent"&&(t.providerRequests||(t.providerRequests={}),t.providerRequests[n]=(t.providerRequests[n]||0)+1),Co()},Xs={linesAdded:0,linesRemoved:0,toolSuccess:0,toolFailure:0,toolDenied:0},Kt=async(e,n,t,o)=>{e==="linesAdded"?Xs.linesAdded+=n:e==="linesRemoved"&&(Xs.linesRemoved+=n);let s=await Sn();if(s[e]!==void 0&&(s[e]+=Math.floor(n)),t&&o&&(e==="tokens"||e==="cachedTokens"||e==="candidateTokens")){s.models||(s.models={}),s.models[t]||(s.models[t]={}),s.models[t][o]||(s.models[t][o]={tokens:0,cachedTokens:0,candidateTokens:0});let r=s.models[t][o];e==="tokens"&&(r.tokens+=Math.floor(n)),e==="cachedTokens"&&(r.cachedTokens+=Math.floor(n)),e==="candidateTokens"&&(r.candidateTokens+=Math.floor(n))}Co()},hl=async(e=1)=>{let n=new Date,t=n.toISOString().split("T")[0];ae||(ae=await $o()),ae.date!==t&&await Sn();let o=n.getFullYear(),s=n.getMonth();n.getDate()<e&&(s-=1,s<0&&(s=11,o-=1));let i=new Date(o,s,e).toISOString().split("T")[0],p=ae.history||{},d=ae.stats||{...vn},c={...vn};c.imageCalls=[],c.models={};let l=(f,u)=>{for(let h in f)if(h==="imageCalls")f.imageCalls=[...f.imageCalls||[],...u.imageCalls||[]];else if(h==="models"){let g=u.models||{};for(let y in g){f.models[y]||(f.models[y]={});for(let m in g[y]){f.models[y][m]||(f.models[y][m]={tokens:0,cachedTokens:0,candidateTokens:0});let w=f.models[y][m],b=g[y][m];w.tokens+=b.tokens||0,w.cachedTokens+=b.cachedTokens||0,w.candidateTokens+=b.candidateTokens||0}}}else typeof f[h]=="number"&&(f[h]+=u[h]||0)};l(c,d);for(let f in p)f>=i&&f<t&&l(c,p[f]);return c},ar=async(e,n={})=>{let t=await Ft().catch(()=>({})),o=n.apiTier||t.apiTier||"Free",s=n.quotas||n.systemSettings?.quotas||t.quotas||{},r=s.providerBudgets||{},a=!!r.__useProvider,i=n.aiProvider||t.aiProvider||"Google",p=a&&!!r[i],d=()=>{if(p){let c=r[i];return{agentLimit:typeof c.agentLimit=="number"&&c.agentLimit>0?c.agentLimit:99999999,tokenLimit:typeof c.tokenLimit=="number"&&c.tokenLimit>0?c.tokenLimit:99999999999999,monthlyTokenLimit:typeof c.monthlyTokenLimit=="number"&&c.monthlyTokenLimit>0?c.monthlyTokenLimit:99999999999999}}return{agentLimit:s.agentLimit||99999999,tokenLimit:s.tokenLimit||99999999999999,monthlyTokenLimit:s.monthlyTokenLimit||99999999999999}};if(e==="agent"){let{agentLimit:c,tokenLimit:l,monthlyTokenLimit:f}=d(),u=await Sn(),h;s.resetMode==="Custom"?h=await hl(s.resetDay||1):h=await ul();let g=0,y=0,m=0;if(p){g=u.providerRequests?.[i]||0;let w=u.models?.[i]||{};for(let T in w)y+=w[T]?.tokens||0;let b=h.models?.[i]||{};for(let T in b)m+=b[T]?.tokens||0}else g=u.agent||0,y=u.tokens||0,m=h.tokens||0;return o==="Free"&&u.agent+u.background>=999999?{allowed:!1,reason:"Free Tier Daily Usage Limit Exceeded"}:g>=c?{allowed:!1,reason:p?`Daily Request Limit Reached for ${i}`:"Daily Agent Request Limit Reached"}:y>=l?{allowed:!1,reason:p?`Daily Token Budget Exhausted for ${i}`:"Daily Token Budget Exhausted"}:m>=f?{allowed:!1,reason:p?`Monthly Token Budget Exhausted for ${i}`:"Monthly Token Budget Exhausted"}:{allowed:!0}}if(e==="background"){let c=await Sn();if(o==="Free"&&c.agent+c.background>=999999)return{allowed:!1,reason:"Free Tier Background Limit Exceeded"};let l=c.background<(s.backgroundLimit||999999);return{allowed:l,reason:l?void 0:"Background Request Limit Exceeded"}}if(e==="search"){let l=(await Sn()).search<(s.searchLimit||100);return{allowed:l,reason:l?void 0:"Search Quota Exceeded"}}return{allowed:!0}},Li=async(e,n={})=>(await ar(e,n)).allowed,lr=e=>{if(!e||e.length===0)return[];let t=[...e].sort((s,r)=>s.timestamp-r.timestamp),o=[];for(let s of t){if(o.length>0){let r=o[o.length-1];if(s.timestamp>=r.start&&s.timestamp<r.end){r.calls.push(s),r.spent+=s.cost;continue}}o.push({start:s.timestamp,end:s.timestamp+36e5,calls:[s],spent:s.cost})}return o},Pi=(e,n)=>{if(!e||e.length===0)return .025;let o=lr(e);if(o.length===0)return .025;let s=[];for(let l of o){let f=.025;if(s.length>0){let h=s[s.length-1],g=!1;if(s.length>=2){let y=s[s.length-2];h.ratio>=.8&&y.ratio>=.8&&(g=!0)}if(g)f=.015;else{let y=h.limit,m=h.ratio;m>=.8?f=y===.015?.015:y:m<.4?f=Math.min(.025,y+.005):m>=.4&&m<.6?f=Math.min(.025,y+.004):f=Math.min(.025,y+.002)}}let u=f>0?l.spent/f:0;s.push({limit:f,spent:l.spent,ratio:u})}let r=o[o.length-1];if(n<r.end)return s[s.length-1].limit;let a=s[s.length-1].limit,i=a,p=s[s.length-1].ratio,d=r.end,c=0;for(let l=s.length-1;l>=0&&s[l].ratio>=.8;l--)c++;for(;d<=n;){let l=.025;c>=2?l=.015:p>=.8?l=i===.015?.015:i:p<.4?l=Math.min(.025,i+.005):p>=.4&&p<.6?l=Math.min(.025,i+.004):l=Math.min(.025,i+.002),i=l,p=0,c=0,d+=36e5,a=l}return a},Di=async e=>{let n=e.imageSettings||{keyType:"Default",quality:"Low-High"};if(n.keyType!=="Default")return!0;let o={Low:.001,"Low-High":.002,Medium:.008,"Medium-High":.01,High:.045,Ultra:.0488,Premium:.15}[n.quality]||.002,s=await Sn();s.imageCalls||(s.imageCalls=[]);let r=Date.now(),a=lr(s.imageCalls),i=0;if(a.length>0){let d=a[a.length-1];r>=d.start&&r<d.end&&(i=d.spent)}let p=Pi(s.imageCalls,r);return i+o<=p},Fi=async()=>{let e=await Sn();e.imageCalls||(e.imageCalls=[]);let n=Date.now(),t=lr(e.imageCalls),o=[],s=0,r=0;if(t.length>0){let d=t[t.length-1];n>=d.start&&n<d.end&&(o=d.calls,s=d.spent,r=Math.max(0,Math.ceil((d.end-n)/(60*1e3))))}let a=Pi(e.imageCalls,n),i=Math.max(0,a-s),p=s;return{totalSpent:s,remaining:i,activeCallsCount:o.length,nextResetMin:r,reclaimCost:p,limit:a}},Ni=async e=>{let n=e.imageSettings||{keyType:"Default",quality:"Low-High"},o={Low:.001,"Low-High":.002,Medium:.008,"Medium-High":.01,High:.045,Ultra:.0488,Premium:.1}[n.quality]||.002,s=await Sn();s.imageCalls||(s.imageCalls=[]),s.imageCalls.push({timestamp:Date.now(),cost:o}),Co()};import Wi from"puppeteer";import ji from"fs";import Hi from"path";import Bi from"os";import Js from"path";import As from"fs";import{createRequire as pl}from"module";import{fileURLToPath as ml}from"url";var gl=pl(import.meta.url),Ui=Js.dirname(ml(import.meta.url));function ls(){let e=Bi.platform(),n=Bi.arch(),t="",o="",s="";if(e==="win32")t=n==="x64"?"win64":"win32",o="chrome.exe",s=`chrome-${t}`;else if(e==="darwin"){t=n==="arm64"?"mac_arm":"mac";let a=n==="arm64"?"arm64":"x64";o="Google Chrome.app/Contents/MacOS/Google Chrome",s=`chrome-mac-${a}`}else if(e==="linux")t="linux",o="chrome",s="chrome-linux64";else return{};let r=Js.resolve(Ui,"..","..",".puppeteerrc.cjs");if(As.existsSync(r)||(r=Js.resolve(Ui,"..",".puppeteerrc.cjs")),!As.existsSync(r))return{};try{let a=gl(r),i=a.cacheDirectory,p=a.chrome?.version;if(i){if(process.env.PUPPETEER_CACHE_DIR=i,p){let l=Js.join(i,"chrome",`${t}-${p}`,s,o);if(As.existsSync(l))return{executablePath:l,cacheDirectory:i}}let d=l=>{if(!As.existsSync(l))return null;try{let f=As.readdirSync(l),u=[];for(let h of f){let g=Js.join(l,h),y;try{y=As.statSync(g)}catch{continue}if(y.isDirectory())u.push(g);else if(h.toLowerCase()===o.toLowerCase()&&(!p||g.includes(p)))return g}if(p){for(let h of u)if(h.includes(p)){let g=d(h);if(g)return g}}for(let h of u)if(!p||!h.includes(p)){let g=d(h);if(g)return g}}catch{}return null},c=d(i);if(c)return{executablePath:c,cacheDirectory:i}}}catch{}return{}}var cr=async e=>{let{query:n,limit:t=5,aiMode:o=!1}=O(e);if(!n)return'ERROR: Missing "query" argument for web_search.';let s=3,r=null;if(o){let a=`Query: ${n}
207
+ `,"utf8"):await Ct.writeFile(e,"","utf8")}catch{}},$d=async e=>{try{if(!await Ct.pathExists(e))return;let n=async t=>{let o=await Ct.readdir(t);for(let s of o){let r=Eo.join(t,s);(await Ct.stat(r)).isDirectory()?(await n(r),(await Ct.readdir(r)).length===0&&await Ct.remove(r)):s.endsWith(".log")&&await dl(r)}};await n(e)}catch{}},vi=(e,n=4)=>{if(e.length<=1)return e;let t=e[0],o=e.slice(1),s=n*2,r=o.slice(s);return[t,...r]};var Cd=async(e,n,t)=>_o(async()=>{let o=Z(jn,[]);Array.isArray(o)||(o=[]);let s={total:n,context:t},r=o.findIndex(a=>Object.keys(a)[0]===String(e));r!==-1?o[r]={[String(e)]:s}:o.push({[String(e)]:s}),me(jn,o)}),Md=async e=>{try{if(!await Ct.pathExists(jn))return{total:0,context:0};let n=Z(jn,[]);if(!Array.isArray(n))return{total:0,context:0};let t=n.find(o=>Object.keys(o)[0]===String(e));return t?t[String(e)]:{total:0,context:0}}catch{return{total:0,context:0}}};import wt from"fs-extra";import Ii from"path";var fl=()=>Math.random().toString(36).substring(2)+Date.now().toString(36),ae=null,Gn=null,Oi=0,Cs=!1,vn={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:[]},Ms=(e,n)=>{if(!e)return{};let t=Object.keys(e),o=new Date(new Date(n).getTime()-720*60*60*1e3),s={};for(let r of t)new Date(r)>=o&&(s[r]=e[r]);return s},$o=async()=>{let e=new Date().toISOString().split("T")[0];try{!await wt.exists(en)&&await wt.exists(Xo)&&(await wt.ensureDir(Ii.dirname(en)),await wt.move(Xo,en))}catch{}let n=en+".tmp",t=null;try{if(await wt.exists(n)){let s=(await wt.readFile(n,"utf8")).trim(),r=null;if(s.startsWith("{")||s.startsWith("[")?r=JSON.parse(s):r=JSON.parse($s(s)),r&&r.date&&r.stats){t=r;try{await wt.rename(n,en)}catch{}}else try{await wt.remove(n)}catch{}}}catch{try{await wt.remove(n)}catch{}}if(!t)try{if(await wt.exists(en)){let s=(await wt.readFile(en,"utf8")).trim();s.startsWith("{")||s.startsWith("[")?t=JSON.parse(s):t=JSON.parse($s(s))}}catch{}let o=t;if(o){let s=o.stats||{...vn},r={...vn,...s};Array.isArray(r.imageCalls)||(r.imageCalls=[]);let a=o.history||{},i=Ms(a,e);if(Object.keys(a).length!==Object.keys(i).length&&(Cs=!0),o.date===e)return{...o,stats:r,history:i};{let p=o.date,d=r,c={...i};return p&&(c[p]=d),{date:e,stats:{...vn},history:Ms(c,e)}}}return{date:e,stats:{...vn},history:{}}},ir=async()=>{if(!(!Cs||!ae))try{await wt.ensureDir(Ii.dirname(en));let e=null;try{if(await wt.exists(en)){let s=(await wt.readFile(en,"utf8")).trim();s.startsWith("{")||s.startsWith("[")?e=JSON.parse(s):e=JSON.parse($s(s))}}catch{}if(e&&e.date===ae.date&&e.stats){for(let s in ae.stats)if(e.stats[s]!==void 0){if(Array.isArray(ae.stats[s])){let r=Array.isArray(e.stats[s])?e.stats[s]:[],a=ae.stats[s],i=new Map;for(let p of[...r,...a])p&&p.timestamp&&i.set(p.timestamp,p);ae.stats[s]=Array.from(i.values())}else if(typeof ae.stats[s]=="number")ae.stats[s]=Math.max(ae.stats[s],Number(e.stats[s])||0);else if(ae.stats[s]&&typeof ae.stats[s]=="object"){let r=e.stats[s]||{},a=ae.stats[s];for(let i in r)if(typeof r[i]=="number")a[i]=Math.max(a[i]||0,r[i]);else if(r[i]&&typeof r[i]=="object"){a[i]||(a[i]={});for(let p in r[i])if(typeof r[i][p]=="number")a[i][p]=Math.max(a[i][p]||0,r[i][p]);else if(r[i][p]&&typeof r[i][p]=="object"){a[i][p]||(a[i][p]={});for(let d in r[i][p])a[i][p][d]=Math.max(a[i][p][d]||0,r[i][p][d])}}}}}if(e&&e.history){let s={...ae.history||{}};for(let r in e.history)if(s[r])for(let a in s[r])if(a==="imageCalls"){let i=Array.isArray(e.history[r].imageCalls)?e.history[r].imageCalls:[],p=Array.isArray(s[r].imageCalls)?s[r].imageCalls:[],d=new Map;for(let c of[...i,...p])c&&c.timestamp&&d.set(c.timestamp,c);s[r].imageCalls=Array.from(d.values())}else typeof s[r][a]=="number"&&(s[r][a]=Math.max(s[r][a],Number(e.history[r][a])||0));else s[r]=e.history[r];ae.history=Ms(s,ae.date||today)}else if(ae&&ae.history){let s=new Date().toISOString().split("T")[0];ae.history=Ms(ae.history,s)}ae.saveId=fl();let n=en+".tmp",t=Gs(JSON.stringify(ae,null,2));await wt.writeFile(n,t,"utf8");let o=await wt.open(n,"r+");await wt.fsync(o),await wt.close(o),await wt.rename(n,en),Cs=!1,Oi=Date.now()}catch{}},Co=()=>{if(Cs=!0,Gn)return;let e=Date.now(),n=Math.max(0,1500-(e-Oi));Gn=setTimeout(async()=>{await ir(),Gn=null},n),Gn.unref&&Gn.unref()},Dd=async()=>{ae=await $o(),Cs&&Co()},Fd=async()=>{Gn&&(clearTimeout(Gn),Gn=null),await ir()},Sn=async()=>{let e=new Date().toISOString().split("T")[0];if(!ae)ae=await $o();else if(ae.date!==e){let n=ae.date,t=ae.stats,o=ae.history||{};t&&(o[n]=t),ae={date:e,stats:{...vn},history:Ms(o,e)},Cs=!0,await ir()}return ae&&ae.stats&&!Array.isArray(ae.stats.imageCalls)&&(ae.stats.imageCalls=[]),ae.stats},ul=async()=>{let e=new Date().toISOString().split("T")[0];ae||(ae=await $o()),ae.date!==e&&await Sn();let n=ae.history||{},t=Ms(n,e);ae.history=t;let o=ae.stats||{...vn},s={...vn};s.imageCalls=[],s.models={};let r=(a,i)=>{for(let p in a)if(p==="imageCalls")a.imageCalls=[...a.imageCalls||[],...i.imageCalls||[]];else if(p==="models"){let d=i.models||{};for(let c in d){a.models[c]||(a.models[c]={});for(let l in d[c]){a.models[c][l]||(a.models[c][l]={tokens:0,cachedTokens:0,candidateTokens:0});let f=a.models[c][l],u=d[c][l];f.tokens+=u.tokens||0,f.cachedTokens+=u.cachedTokens||0,f.candidateTokens+=u.candidateTokens||0}}}else typeof a[p]=="number"&&(a[p]+=i[p]||0)};r(s,o);for(let a in t)r(s,t[a]);return s},Ot=async(e,n)=>{e==="toolSuccess"?Xs.toolSuccess++:e==="toolFailure"?Xs.toolFailure++:e==="toolDenied"&&Xs.toolDenied++;let t=await Sn();t[e]!==void 0&&t[e]++,n&&e==="agent"&&(t.providerRequests||(t.providerRequests={}),t.providerRequests[n]=(t.providerRequests[n]||0)+1),Co()},Xs={linesAdded:0,linesRemoved:0,toolSuccess:0,toolFailure:0,toolDenied:0},Kt=async(e,n,t,o)=>{e==="linesAdded"?Xs.linesAdded+=n:e==="linesRemoved"&&(Xs.linesRemoved+=n);let s=await Sn();if(s[e]!==void 0&&(s[e]+=Math.floor(n)),t&&o&&(e==="tokens"||e==="cachedTokens"||e==="candidateTokens")){s.models||(s.models={}),s.models[t]||(s.models[t]={}),s.models[t][o]||(s.models[t][o]={tokens:0,cachedTokens:0,candidateTokens:0});let r=s.models[t][o];e==="tokens"&&(r.tokens+=Math.floor(n)),e==="cachedTokens"&&(r.cachedTokens+=Math.floor(n)),e==="candidateTokens"&&(r.candidateTokens+=Math.floor(n))}Co()},hl=async(e=1)=>{let n=new Date,t=n.toISOString().split("T")[0];ae||(ae=await $o()),ae.date!==t&&await Sn();let o=n.getFullYear(),s=n.getMonth();n.getDate()<e&&(s-=1,s<0&&(s=11,o-=1));let i=new Date(o,s,e).toISOString().split("T")[0],p=ae.history||{},d=ae.stats||{...vn},c={...vn};c.imageCalls=[],c.models={};let l=(f,u)=>{for(let h in f)if(h==="imageCalls")f.imageCalls=[...f.imageCalls||[],...u.imageCalls||[]];else if(h==="models"){let g=u.models||{};for(let y in g){f.models[y]||(f.models[y]={});for(let m in g[y]){f.models[y][m]||(f.models[y][m]={tokens:0,cachedTokens:0,candidateTokens:0});let w=f.models[y][m],b=g[y][m];w.tokens+=b.tokens||0,w.cachedTokens+=b.cachedTokens||0,w.candidateTokens+=b.candidateTokens||0}}}else typeof f[h]=="number"&&(f[h]+=u[h]||0)};l(c,d);for(let f in p)f>=i&&f<t&&l(c,p[f]);return c},ar=async(e,n={})=>{let t=await Ft().catch(()=>({})),o=n.apiTier||t.apiTier||"Free",s=n.quotas||n.systemSettings?.quotas||t.quotas||{},r=s.providerBudgets||{},a=!!r.__useProvider,i=n.aiProvider||t.aiProvider||"Google",p=a&&!!r[i],d=()=>{if(p){let c=r[i];return{agentLimit:typeof c.agentLimit=="number"&&c.agentLimit>0?c.agentLimit:99999999,tokenLimit:typeof c.tokenLimit=="number"&&c.tokenLimit>0?c.tokenLimit:99999999999999,monthlyTokenLimit:typeof c.monthlyTokenLimit=="number"&&c.monthlyTokenLimit>0?c.monthlyTokenLimit:99999999999999}}return{agentLimit:s.agentLimit||99999999,tokenLimit:s.tokenLimit||99999999999999,monthlyTokenLimit:s.monthlyTokenLimit||99999999999999}};if(e==="agent"){let{agentLimit:c,tokenLimit:l,monthlyTokenLimit:f}=d(),u=await Sn(),h;s.resetMode==="Custom"?h=await hl(s.resetDay||1):h=await ul();let g=0,y=0,m=0;if(p){g=u.providerRequests?.[i]||0;let w=u.models?.[i]||{};for(let T in w)y+=w[T]?.tokens||0;let b=h.models?.[i]||{};for(let T in b)m+=b[T]?.tokens||0}else g=u.agent||0,y=u.tokens||0,m=h.tokens||0;return o==="Free"&&u.agent+u.background>=999999?{allowed:!1,reason:"Free Tier Daily Usage Limit Exceeded"}:g>=c?{allowed:!1,reason:p?`Daily Request Limit Reached for ${i}`:"Daily Agent Request Limit Reached"}:y>=l?{allowed:!1,reason:p?`Daily Token Budget Exhausted for ${i}`:"Daily Token Budget Exhausted"}:m>=f?{allowed:!1,reason:p?`Monthly Token Budget Exhausted for ${i}`:"Monthly Token Budget Exhausted"}:{allowed:!0}}if(e==="background"){let c=await Sn();if(o==="Free"&&c.agent+c.background>=999999)return{allowed:!1,reason:"Free Tier Background Limit Exceeded"};let l=c.background<(s.backgroundLimit||999999);return{allowed:l,reason:l?void 0:"Background Request Limit Exceeded"}}if(e==="search"){let l=(await Sn()).search<(s.searchLimit||100);return{allowed:l,reason:l?void 0:"Search Quota Exceeded"}}return{allowed:!0}},Li=async(e,n={})=>(await ar(e,n)).allowed,lr=e=>{if(!e||e.length===0)return[];let t=[...e].sort((s,r)=>s.timestamp-r.timestamp),o=[];for(let s of t){if(o.length>0){let r=o[o.length-1];if(s.timestamp>=r.start&&s.timestamp<r.end){r.calls.push(s),r.spent+=s.cost;continue}}o.push({start:s.timestamp,end:s.timestamp+36e5,calls:[s],spent:s.cost})}return o},Pi=(e,n)=>{if(!e||e.length===0)return .025;let o=lr(e);if(o.length===0)return .025;let s=[];for(let l of o){let f=.025;if(s.length>0){let h=s[s.length-1],g=!1;if(s.length>=2){let y=s[s.length-2];h.ratio>=.8&&y.ratio>=.8&&(g=!0)}if(g)f=.015;else{let y=h.limit,m=h.ratio;m>=.8?f=y===.015?.015:y:m<.4?f=Math.min(.025,y+.005):m>=.4&&m<.6?f=Math.min(.025,y+.004):f=Math.min(.025,y+.002)}}let u=f>0?l.spent/f:0;s.push({limit:f,spent:l.spent,ratio:u})}let r=o[o.length-1];if(n<r.end)return s[s.length-1].limit;let a=s[s.length-1].limit,i=a,p=s[s.length-1].ratio,d=r.end,c=0;for(let l=s.length-1;l>=0&&s[l].ratio>=.8;l--)c++;for(;d<=n;){let l=.025;c>=2?l=.015:p>=.8?l=i===.015?.015:i:p<.4?l=Math.min(.025,i+.005):p>=.4&&p<.6?l=Math.min(.025,i+.004):l=Math.min(.025,i+.002),i=l,p=0,c=0,d+=36e5,a=l}return a},Di=async e=>{let n=e.imageSettings||{keyType:"Default",quality:"Low-High"};if(n.keyType!=="Default")return!0;let o={Low:.001,"Low-High":.002,Medium:.008,"Medium-High":.01,High:.045,Ultra:.0488,Premium:.15}[n.quality]||.002,s=await Sn();s.imageCalls||(s.imageCalls=[]);let r=Date.now(),a=lr(s.imageCalls),i=0;if(a.length>0){let d=a[a.length-1];r>=d.start&&r<d.end&&(i=d.spent)}let p=Pi(s.imageCalls,r);return i+o<=p},Fi=async()=>{let e=await Sn();e.imageCalls||(e.imageCalls=[]);let n=Date.now(),t=lr(e.imageCalls),o=[],s=0,r=0;if(t.length>0){let d=t[t.length-1];n>=d.start&&n<d.end&&(o=d.calls,s=d.spent,r=Math.max(0,Math.ceil((d.end-n)/(60*1e3))))}let a=Pi(e.imageCalls,n),i=Math.max(0,a-s),p=s;return{totalSpent:s,remaining:i,activeCallsCount:o.length,nextResetMin:r,reclaimCost:p,limit:a}},Ni=async e=>{let n=e.imageSettings||{keyType:"Default",quality:"Low-High"},o={Low:.001,"Low-High":.002,Medium:.008,"Medium-High":.01,High:.045,Ultra:.0488,Premium:.1}[n.quality]||.002,s=await Sn();s.imageCalls||(s.imageCalls=[]),s.imageCalls.push({timestamp:Date.now(),cost:o}),Co()};import Wi from"puppeteer";import ji from"fs";import Hi from"path";import Bi from"os";import Js from"path";import As from"fs";import{createRequire as pl}from"module";import{fileURLToPath as ml}from"url";var gl=pl(import.meta.url),Ui=Js.dirname(ml(import.meta.url));function ls(){let e=Bi.platform(),n=Bi.arch(),t="",o="",s="";if(e==="win32")t=n==="x64"?"win64":"win32",o="chrome.exe",s=`chrome-${t}`;else if(e==="darwin"){t=n==="arm64"?"mac_arm":"mac";let a=n==="arm64"?"arm64":"x64";o="Google Chrome.app/Contents/MacOS/Google Chrome",s=`chrome-mac-${a}`}else if(e==="linux")t="linux",o="chrome",s="chrome-linux64";else return{};let r=Js.resolve(Ui,"..","..",".puppeteerrc.cjs");if(As.existsSync(r)||(r=Js.resolve(Ui,"..",".puppeteerrc.cjs")),!As.existsSync(r))return{};try{let a=gl(r),i=a.cacheDirectory,p=a.chrome?.version;if(i){if(process.env.PUPPETEER_CACHE_DIR=i,p){let l=Js.join(i,"chrome",`${t}-${p}`,s,o);if(As.existsSync(l))return{executablePath:l,cacheDirectory:i}}let d=l=>{if(!As.existsSync(l))return null;try{let f=As.readdirSync(l),u=[];for(let h of f){let g=Js.join(l,h),y;try{y=As.statSync(g)}catch{continue}if(y.isDirectory())u.push(g);else if(h.toLowerCase()===o.toLowerCase()&&(!p||g.includes(p)))return g}if(p){for(let h of u)if(h.includes(p)){let g=d(h);if(g)return g}}for(let h of u)if(!p||!h.includes(p)){let g=d(h);if(g)return g}}catch{}return null},c=d(i);if(c)return{executablePath:c,cacheDirectory:i}}}catch{}return{}}var cr=async e=>{let{query:n,limit:t=5,aiMode:o=!1}=O(e);if(!n)return'ERROR: Missing "query" argument for web_search.';let s=3,r=null;if(o){let a=`Query: ${n}
208
208
 
209
209
  RESPONSE RULES:
210
210
  - ANSWER CONCISELY WITH REQUIRED DETAILS UNDER 300 WORDS.
@@ -426,14 +426,14 @@ Stack: ${a.stack}`:"";return`ERROR: Failed to map file: ${i}${p}`}};import zn fr
426
426
  ${l}`}return`SUCCESS: TASK LIST CREATED (${u} total)
427
427
  ${l}`}if(t==="append"){if(!o)return'ERROR: Missing "tasks" for append method.';let l=d(o);await mt.recordFileChange(i),zn.appendFileSync(i,l,"utf8");let f=zn.readFileSync(i,"utf8"),u=f.split(/\r?\n/).map(m=>m.trim()),h=u.filter(m=>m.startsWith("- [ ]")||m.startsWith("- [x]")||m.startsWith("- [X]")).length,g=u.filter(m=>m.startsWith("- [x]")||m.startsWith("- [X]")).length,y=l.split(/\r?\n/).map(m=>m.trim()).filter(m=>m.startsWith("- [ ]")||m.startsWith("- [x]")||m.startsWith("- [X]")).length;return`SUCCESS: TASK APPENDED (${g} completed, ${h-g} left, ${y} added)
428
428
  ${f}`}if(t==="get"){if(!zn.existsSync(i))return"TODO GET: No task list found for this session.";let l=zn.readFileSync(i,"utf8"),f=0;if(s){let m=c(l,s);m.markedCount>0&&(l=m.content,f=m.markedCount,await mt.recordFileChange(i),zn.writeFileSync(i,l,"utf8"))}let u=l.split(/\r?\n/).map(m=>m.trim()),h=u.filter(m=>m.startsWith("- [ ]")||m.startsWith("- [x]")||m.startsWith("- [X]")).length,g=u.filter(m=>m.startsWith("- [x]")||m.startsWith("- [X]")).length;return`${f>0?`SUCCESS: ${f} TASK(S) MARKED DONE`:"TODO GET"}: ${g} Completed, ${h-g} left
429
- ${l}`}return`ERROR: Unknown method "${t}". Use create, append, or get.`}catch(l){return`ERROR: Todo tool failure: ${l instanceof Error?l.message:String(l)}`}};var Ir=async(e,n={})=>{let{runSubagent:t}=await import("./ai-OTNVN773.js"),o=O(e),s=o.task||o.instruction||o.prompt,r=o.model||null,a=o.tools||null;if(!s)return'ERROR: Missing "task" argument for invokeSync.';let i=null;if(a)try{let d=a.trim();d.startsWith("[")&&d.endsWith("]")&&(d=d.substring(1,d.length-1)),i=d.split(",").map(c=>c.trim().replace(/^["']|["']$/g,"")).filter(Boolean)}catch{}let p=o.title||s.substring(0,30);try{n.onVisualFeedback&&n.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${p}`);let d=await t(s,n,r,i,50);return n.onVisualFeedback&&n.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${p} [COMPLETED]
430
- `),d}catch(d){let{isTerminationSignaled:c}=await import("./ai-OTNVN773.js"),l=d.message==="Subagent task was cancelled by user."||c();if(n.onVisualFeedback){let f=l?"[CANCELLED]":"[FAILED]";n.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${p} ${f}
431
- `)}return`ERROR: Subagent execution failed: ${d.message}`}};var aa=async(e,n={})=>{let{runSubagent:t}=await import("./ai-OTNVN773.js"),o=O(e),s=o.task||o.instruction||o.prompt,r=o.model||null,a=o.title||null,i=o.tools||null;if(!s)return'ERROR: Missing "task" argument for invoke.';let p=null;if(i)try{let m=i.trim();m.startsWith("[")&&m.endsWith("]")&&(m=m.substring(1,m.length-1)),p=m.split(",").map(w=>w.trim().replace(/^["']|["']$/g,"")).filter(Boolean)}catch{}let d=`subagent-${Date.now()}-${Math.floor(Math.random()*1e3)}`,c=null,l=null,f=new Promise((m,w)=>{c=m,l=w}),u={id:d,title:a||s.substring(0,30),task:s,status:"running",startedAt:Date.now(),lastChunkTime:Date.now(),wps:0,questions:[],pendingSteerMessages:[],steer:m=>{m&&u.pendingSteerMessages.push(m)},completionPromise:f,_resolveCompletion:c,_rejectCompletion:l,progress:[]},h={chunks:[],totalWords:0};Xe.push(u),n.onSubagentUpdate&&n.onSubagentUpdate();let g=[],y={...n,taskId:d,onAskMain:async m=>{let w=`q-${Date.now()}-${Math.floor(Math.random()*1e3)}`,b=null,T=new Promise(k=>{b=k}),$={id:w,question:m,answered:!1,answer:null,askedAt:Date.now(),_resolve:b};return u.questions.push($),u.status="waiting",n.onSubagentUpdate&&n.onSubagentUpdate(),bo(`[SYSTEM] Background subagent "${u.title}" is WAITING FOR YOUR INPUT: "${m}"
429
+ ${l}`}return`ERROR: Unknown method "${t}". Use create, append, or get.`}catch(l){return`ERROR: Todo tool failure: ${l instanceof Error?l.message:String(l)}`}};var Ir=async(e,n={})=>{let{runSubagent:t}=await import("./ai-5XMCH3FU.js"),o=O(e),s=o.task||o.instruction||o.prompt,r=o.model||null,a=o.tools||null;if(!s)return'ERROR: Missing "task" argument for invokeSync.';let i=null;if(a)try{let d=a.trim();d.startsWith("[")&&d.endsWith("]")&&(d=d.substring(1,d.length-1)),i=d.split(",").map(c=>c.trim().replace(/^["']|["']$/g,"")).filter(Boolean)}catch{}let p=o.title||s.substring(0,30);try{n.onVisualFeedback&&n.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${p}`);let d=await t(s,n,r,i,50);return n.onVisualFeedback&&n.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${p} [COMPLETED]
430
+ `),d}catch(d){let{isTerminationSignaled:c}=await import("./ai-5XMCH3FU.js"),l=d.message==="Subagent task was cancelled by user."||c();if(n.onVisualFeedback){let f=l?"[CANCELLED]":"[FAILED]";n.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${p} ${f}
431
+ `)}return`ERROR: Subagent execution failed: ${d.message}`}};var aa=async(e,n={})=>{let{runSubagent:t}=await import("./ai-5XMCH3FU.js"),o=O(e),s=o.task||o.instruction||o.prompt,r=o.model||null,a=o.title||null,i=o.tools||null;if(!s)return'ERROR: Missing "task" argument for invoke.';let p=null;if(i)try{let m=i.trim();m.startsWith("[")&&m.endsWith("]")&&(m=m.substring(1,m.length-1)),p=m.split(",").map(w=>w.trim().replace(/^["']|["']$/g,"")).filter(Boolean)}catch{}let d=`subagent-${Date.now()}-${Math.floor(Math.random()*1e3)}`,c=null,l=null,f=new Promise((m,w)=>{c=m,l=w}),u={id:d,title:a||s.substring(0,30),task:s,status:"running",startedAt:Date.now(),lastChunkTime:Date.now(),wps:0,questions:[],pendingSteerMessages:[],steer:m=>{m&&u.pendingSteerMessages.push(m)},completionPromise:f,_resolveCompletion:c,_rejectCompletion:l,progress:[]},h={chunks:[],totalWords:0};Xe.push(u),n.onSubagentUpdate&&n.onSubagentUpdate();let g=[],y={...n,taskId:d,onAskMain:async m=>{let w=`q-${Date.now()}-${Math.floor(Math.random()*1e3)}`,b=null,T=new Promise(k=>{b=k}),$={id:w,question:m,answered:!1,answer:null,askedAt:Date.now(),_resolve:b};return u.questions.push($),u.status="waiting",n.onSubagentUpdate&&n.onSubagentUpdate(),bo(`[SYSTEM] Background subagent "${u.title}" is WAITING FOR YOUR INPUT: "${m}"
432
432
  Respond using tool: [tool:functions.Answer(id="${d}", answer="...")]
433
433
  [/SYSTEM]`),await T},onVisualFeedback:m=>{u.lastChunkTime=Date.now();let w=m.replace(/\x1b\[[0-9;]*m/g,""),b=w.match(/[✔✘✗✖🔍📖→➕↻•]\s*([A-Za-z0-9\s-]+)/);b?u.currentTool=b[1].trim():u.currentTool=w,n.onSubagentUpdate&&n.onSubagentUpdate()},onTokenChunk:(m,w)=>{let b=Date.now();if(u.lastChunkTime=b,u.currentTool="Thinking",typeof w=="number"&&w>0){h.totalWords+=w,h.chunks.push({time:b,words:w});let T=b-400;if(h.chunks=h.chunks.filter($=>$.time>=T),h.chunks.length>0){let $=h.chunks.reduce((S,_)=>S+_.words,0),R=h.chunks[0].time,k=Math.max(.4,(b-R)/1e3);u.wps=Math.round($/k*10)/10}}n.onSubagentUpdate&&n.onSubagentUpdate()}};return t(s,y,r,p,50,m=>{if(u.status==="cancelled")return;if(m.startsWith("[Subagent Turn")&&g.length>0&&(u.progress.push([...g]),g=[]),m.includes("[Executing Tool]")){let b=m.match(/\[Executing Tool\]\s*([a-zA-Z0-9_]+)/);b&&(!u.currentTool||u.currentTool==="Thinking")&&(u.currentTool=b[1])}let w=m;if(w.startsWith("[Tool Result]")){let b=w.split(`
434
434
  `);b.length>5&&(w=b.slice(0,4).join(`
435
435
  `)+`
436
- ... [Content/Diff Truncated from Logs] ...`)}g.push(w),n.onSubagentUpdate&&n.onSubagentUpdate()},!0).then(m=>{if(u.status==="cancelled"){u._resolveCompletion&&u._resolveCompletion(m);return}g.length>0&&(u.progress.push([...g]),g=[]),u.status="completed",u.finalAnswer=m,n.onSubagentUpdate&&n.onSubagentUpdate(),bo(`[SYSTEM] Background subagent "${u.title}" (id: ${d}) has FINISHED. Call GetProgress(id="${d}") to see the final result. [/SYSTEM]`),u._resolveCompletion&&u._resolveCompletion(m)}).catch(async m=>{let{isTerminationSignaled:w}=await import("./ai-OTNVN773.js");if(m.message==="Subagent task was cancelled."||u.status==="cancelled"||w()){u.status="cancelled",g.push("[SUBAGENT CANCELLED] Task was cancelled."),u.progress.push([...g]),n.onSubagentUpdate&&n.onSubagentUpdate(),u._resolveCompletion&&u._resolveCompletion(null);return}g.push(`[SUBAGENT FAILURE] Error: ${m.message}`),u.progress.push([...g]),u.status="failed",u.error=m.message,n.onSubagentUpdate&&n.onSubagentUpdate(),bo(`[SYSTEM] Background subagent "${u.title}" (id: ${d}) FAILED with error: ${m.message}. [/SYSTEM]`),u._rejectCompletion&&u._rejectCompletion(m)}),`SUCCESS: Background subagent started. Task ID: ${d}`};var Or=async(e,n={})=>{let o=O(e).id;if(!o)return'ERROR: Missing "id" argument for getProgress.';let s=Xe.find(i=>i.id===o);if(!s)return`ERROR: Subagent task with ID [${o}] not found.`;let r=`Subagent Task Status: ${s.status.toUpperCase()}
436
+ ... [Content/Diff Truncated from Logs] ...`)}g.push(w),n.onSubagentUpdate&&n.onSubagentUpdate()},!0).then(m=>{if(u.status==="cancelled"){u._resolveCompletion&&u._resolveCompletion(m);return}g.length>0&&(u.progress.push([...g]),g=[]),u.status="completed",u.finalAnswer=m,n.onSubagentUpdate&&n.onSubagentUpdate(),bo(`[SYSTEM] Background subagent "${u.title}" (id: ${d}) has FINISHED. Call GetProgress(id="${d}") to see the final result. [/SYSTEM]`),u._resolveCompletion&&u._resolveCompletion(m)}).catch(async m=>{let{isTerminationSignaled:w}=await import("./ai-5XMCH3FU.js");if(m.message==="Subagent task was cancelled."||u.status==="cancelled"||w()){u.status="cancelled",g.push("[SUBAGENT CANCELLED] Task was cancelled."),u.progress.push([...g]),n.onSubagentUpdate&&n.onSubagentUpdate(),u._resolveCompletion&&u._resolveCompletion(null);return}g.push(`[SUBAGENT FAILURE] Error: ${m.message}`),u.progress.push([...g]),u.status="failed",u.error=m.message,n.onSubagentUpdate&&n.onSubagentUpdate(),bo(`[SYSTEM] Background subagent "${u.title}" (id: ${d}) FAILED with error: ${m.message}. [/SYSTEM]`),u._rejectCompletion&&u._rejectCompletion(m)}),`SUCCESS: Background subagent started. Task ID: ${d}`};var Or=async(e,n={})=>{let o=O(e).id;if(!o)return'ERROR: Missing "id" argument for getProgress.';let s=Xe.find(i=>i.id===o);if(!s)return`ERROR: Subagent task with ID [${o}] not found.`;let r=`Subagent Task Status: ${s.status.toUpperCase()}
437
437
  `;if(r+=`Title: ${s.title}
438
438
  `,r+=`Task: ${s.task}
439
439
  `,s.startedAt){let i=Math.floor((Date.now()-s.startedAt)/1e3);r+=`Elapsed Time: ${i}s
@@ -458,7 +458,7 @@ ${s.finalAnswer}
458
458
  `),r.replace(/\r\n/g,`
459
459
  `).replace(/\n{3,}/g,`
460
460
 
461
- `).trim().replace(/\[TOOL RESULT\]/gi,"TOOL RESULT:")};var la=async(e,n={})=>{let o=O(e).id;if(!o)return'ERROR: Missing "id" argument for cancel.';let s=Xe.find(r=>r.id===o);return s?s.status==="completed"||s.status==="failed"?`INFO: Subagent task with ID [${o}] has already finished with status [${s.status.toUpperCase()}].`:s.status==="cancelled"?`INFO: Subagent task with ID [${o}] is already cancelled.`:(s.status="cancelled",n.onSubagentUpdate&&n.onSubagentUpdate(),`SUCCESS: Subagent task with ID [${o}] has been cancelled.`):`ERROR: Subagent task with ID [${o}] not found.`};import kt from"fs-extra";import Tt from"path";var Kl=["node_modules","dist","bin","logs",".git",".fluxflow","secret",".gemini",".agents","tmp","temp","build","out","snapshots"];async function so(e,n=e){let t={},o=await kt.readdir(e,{withFileTypes:!0}).catch(()=>[]);for(let s of o){if(Kl.includes(s.name))continue;let r=Tt.join(e,s.name),a=Tt.relative(n,r).replace(/\\/g,"/");if(s.isDirectory()){let i=await so(r,n);Object.assign(t,i)}else{let i=await kt.stat(r).catch(()=>null);i&&(t[a]={size:i.size,mtime:i.mtimeMs})}}return t}async function ca(e,n){await kt.ensureDir(e);for(let t of Object.keys(n)){let o=Tt.join(process.cwd(),t),s=Tt.join(e,t);await kt.ensureDir(Tt.dirname(s)),await kt.copyFile(o,s).catch(()=>{})}}async function Lr(e,n,t=null,o=null){if(!await kt.pathExists(e))return;o||(o=e);let s=await kt.readdir(e,{withFileTypes:!0}).catch(()=>[]);for(let r of s){let a=Tt.join(e,r.name),i=Tt.join(n,r.name);if(r.isDirectory())await Lr(a,i,t,o);else{let p=Tt.relative(o,a).replace(/\\/g,"/"),d=await kt.pathExists(i);d&&await kt.chmod(i,438).catch(()=>{}),await kt.ensureDir(Tt.dirname(i));let c=await kt.copyFile(a,i).then(()=>!0).catch(()=>!1);await kt.chmod(i,438).catch(()=>{}),t&&(c?d?t.replaced++:t.restored++:t.failed.push(p))}}}var Kn={async takeInitialSnapshot(e){try{let n=Tt.join(Mn,"snapshots",e);await kt.remove(n).catch(()=>{}),await kt.ensureDir(n);let t=await so(process.cwd());await ca(Tt.join(n,"initial"),t);let o=Z(un,{});o[e]={initialManifest:t,currentManifest:t,checkpoints:[{id:"initial",timestamp:new Date().toISOString(),newFiles:[],modifiedFiles:[],deletedFiles:[],toolsUsed:[]}]},me(un,o)}catch{}},async recordTurnDelta(e,n,t=[]){try{let o=Z(un,{}),s=o[e];if(!s)return;let r=s.currentManifest||s.initialManifest,a=await so(process.cwd()),i=[],p=[],d=[];for(let[l,f]of Object.entries(a)){let u=r[l];u?(u.size!==f.size||u.mtime!==f.mtime)&&p.push(l):i.push(l)}for(let l of Object.keys(r))a[l]||d.push(l);let c=[...i,...p];if(c.length>0||d.length>0){let l={};for(let u of c)l[u]=a[u];let f=Tt.join(Mn,"snapshots",e,`turn_${n}`);await ca(f,l)}s.checkpoints.push({id:`turn_${n}`,timestamp:new Date().toISOString(),newFiles:i,modifiedFiles:p,deletedFiles:d,toolsUsed:t}),s.currentManifest=a,me(un,o)}catch{}},async getCheckpoints(e){try{let t=Z(un,{})[e];return t?t.checkpoints||[]:[]}catch{return[]}},async rollbackToCheckpoint(e,n){try{let t=Z(un,{}),o=t[e];if(!o)throw new Error("No session active for Advance Rollback.");let s=o.checkpoints||[],r=s.findIndex(c=>c.id===n);if(r===-1)throw new Error(`Checkpoint [${n}] not found.`);let a=Tt.join(Mn,"snapshots",e),i={restored:0,replaced:0,failed:[]},p=await so(process.cwd());for(let c of Object.keys(p)){let l=Tt.join(process.cwd(),c);await kt.chmod(l,438).catch(()=>{}),await kt.remove(l).catch(()=>{})}let d=Tt.join(a,"initial");await Lr(d,process.cwd(),i,d);for(let c=1;c<=r;c++){let l=s[c],f=Tt.join(a,l.id);if(await Lr(f,process.cwd(),i,f),l.deletedFiles&&l.deletedFiles.length>0)for(let u of l.deletedFiles){let h=Tt.join(process.cwd(),u);await kt.chmod(h,438).catch(()=>{}),await kt.remove(h).catch(()=>{})}}return o.checkpoints=s.slice(0,r+1),o.currentManifest=await so(process.cwd()),me(un,t),{checkpointId:n,stats:i}}catch(t){throw new Error(`Rollback failed: ${t.message}`)}},async getLatestFileChanges(e){try{let t=Z(un,{})[e];if(!t||!t.checkpoints||t.checkpoints.length===0)return{newFiles:[],modifiedFiles:[],deletedFiles:[]};let o=t.checkpoints[t.checkpoints.length-1];return{newFiles:o.newFiles||[],modifiedFiles:o.modifiedFiles||[],deletedFiles:o.deletedFiles||[]}}catch{return{newFiles:[],modifiedFiles:[],deletedFiles:[]}}},async cleanup(e){try{let n=Tt.join(Mn,"snapshots",e);await kt.remove(n).catch(()=>{});let t=Z(un,{});t[e]&&(delete t[e],me(un,t))}catch{}}};var Pr=async(e,n={})=>{let t=O(e),o=t.method,s=t.id,r=n.chatId;if(!n.systemSettings?.advanceRollback)return"ERROR: Advance Rollback feature is currently disabled in settings under Security. Tell user to enable it.";if(!r)return"ERROR: No active chat transaction found for rollback.";if(o==="getCheckpoint"){let i=await Kn.getCheckpoints(r);if(i.length===0)return"No checkpoints available.";let p={write_file:"WriteFile",update_file:"PatchFile",view_file:"ReadFile",read_folder:"ReadFolder",exec_command:"Run",web_search:"WebSearch",web_scrape:"WebScrape",search_keyword:"SearchKeyword",CodeSearch:"SearchKeyword",code_search:"SearchKeyword",write_pdf:"WritePDF",write_docx:"WriteDoc",generate_image:"GenerateImage",file_map:"FileMap",todo:"Todo",goal:"Goal",Goal:"Goal",await:"Await",ask:"Ask",ask_user:"Ask",invoke:"Invoke",invokesync:"InvokeSync",getprogress:"GetProgress",cancel:"Cancel",emergency_rollback:"EmergencyRollback",emergencyrollback:"EmergencyRollback"},d=l=>p[l]||p[l.toLowerCase()]||l,c=`Available checkpoints for rollback:
461
+ `).trim().replace(/\[TOOL RESULT\]/gi,"TOOL RESULT:")};var la=async(e,n={})=>{let o=O(e).id;if(!o)return'ERROR: Missing "id" argument for cancel.';let s=Xe.find(r=>r.id===o);return s?s.status==="completed"||s.status==="failed"?`INFO: Subagent task with ID [${o}] has already finished with status [${s.status.toUpperCase()}].`:s.status==="cancelled"?`INFO: Subagent task with ID [${o}] is already cancelled.`:(s.status="cancelled",n.onSubagentUpdate&&n.onSubagentUpdate(),`SUCCESS: Subagent task with ID [${o}] has been cancelled.`):`ERROR: Subagent task with ID [${o}] not found.`};import xt from"fs-extra";import Tt from"path";var Kl=["node_modules","dist","bin","logs",".git",".fluxflow","secret",".gemini",".agents","tmp","temp","build","out","snapshots"];async function so(e,n=e){let t={},o=await xt.readdir(e,{withFileTypes:!0}).catch(()=>[]);for(let s of o){if(Kl.includes(s.name))continue;let r=Tt.join(e,s.name),a=Tt.relative(n,r).replace(/\\/g,"/");if(s.isDirectory()){let i=await so(r,n);Object.assign(t,i)}else{let i=await xt.stat(r).catch(()=>null);i&&(t[a]={size:i.size,mtime:i.mtimeMs})}}return t}async function ca(e,n){await xt.ensureDir(e);for(let t of Object.keys(n)){let o=Tt.join(process.cwd(),t),s=Tt.join(e,t);await xt.ensureDir(Tt.dirname(s)),await xt.copyFile(o,s).catch(()=>{})}}async function Lr(e,n,t=null,o=null){if(!await xt.pathExists(e))return;o||(o=e);let s=await xt.readdir(e,{withFileTypes:!0}).catch(()=>[]);for(let r of s){let a=Tt.join(e,r.name),i=Tt.join(n,r.name);if(r.isDirectory())await Lr(a,i,t,o);else{let p=Tt.relative(o,a).replace(/\\/g,"/"),d=await xt.pathExists(i);d&&await xt.chmod(i,438).catch(()=>{}),await xt.ensureDir(Tt.dirname(i));let c=await xt.copyFile(a,i).then(()=>!0).catch(()=>!1);await xt.chmod(i,438).catch(()=>{}),t&&(c?d?t.replaced++:t.restored++:t.failed.push(p))}}}var Kn={async takeInitialSnapshot(e){try{let n=Tt.join(Mn,"snapshots",e);await xt.remove(n).catch(()=>{}),await xt.ensureDir(n);let t=await so(process.cwd());await ca(Tt.join(n,"initial"),t);let o=Z(un,{});o[e]={initialManifest:t,currentManifest:t,checkpoints:[{id:"initial",timestamp:new Date().toISOString(),newFiles:[],modifiedFiles:[],deletedFiles:[],toolsUsed:[]}]},me(un,o)}catch{}},async recordTurnDelta(e,n,t=[]){try{let o=Z(un,{}),s=o[e];if(!s)return;let r=s.currentManifest||s.initialManifest,a=await so(process.cwd()),i=[],p=[],d=[];for(let[l,f]of Object.entries(a)){let u=r[l];u?(u.size!==f.size||u.mtime!==f.mtime)&&p.push(l):i.push(l)}for(let l of Object.keys(r))a[l]||d.push(l);let c=[...i,...p];if(c.length>0||d.length>0){let l={};for(let u of c)l[u]=a[u];let f=Tt.join(Mn,"snapshots",e,`turn_${n}`);await ca(f,l)}s.checkpoints.push({id:`turn_${n}`,timestamp:new Date().toISOString(),newFiles:i,modifiedFiles:p,deletedFiles:d,toolsUsed:t}),s.currentManifest=a,me(un,o)}catch{}},async getCheckpoints(e){try{let t=Z(un,{})[e];return t?t.checkpoints||[]:[]}catch{return[]}},async rollbackToCheckpoint(e,n){try{let t=Z(un,{}),o=t[e];if(!o)throw new Error("No session active for Advance Rollback.");let s=o.checkpoints||[],r=s.findIndex(c=>c.id===n);if(r===-1)throw new Error(`Checkpoint [${n}] not found.`);let a=Tt.join(Mn,"snapshots",e),i={restored:0,replaced:0,failed:[]},p=await so(process.cwd());for(let c of Object.keys(p)){let l=Tt.join(process.cwd(),c);await xt.chmod(l,438).catch(()=>{}),await xt.remove(l).catch(()=>{})}let d=Tt.join(a,"initial");await Lr(d,process.cwd(),i,d);for(let c=1;c<=r;c++){let l=s[c],f=Tt.join(a,l.id);if(await Lr(f,process.cwd(),i,f),l.deletedFiles&&l.deletedFiles.length>0)for(let u of l.deletedFiles){let h=Tt.join(process.cwd(),u);await xt.chmod(h,438).catch(()=>{}),await xt.remove(h).catch(()=>{})}}return o.checkpoints=s.slice(0,r+1),o.currentManifest=await so(process.cwd()),me(un,t),{checkpointId:n,stats:i}}catch(t){throw new Error(`Rollback failed: ${t.message}`)}},async getLatestFileChanges(e){try{let t=Z(un,{})[e];if(!t||!t.checkpoints||t.checkpoints.length===0)return{newFiles:[],modifiedFiles:[],deletedFiles:[]};let o=t.checkpoints[t.checkpoints.length-1];return{newFiles:o.newFiles||[],modifiedFiles:o.modifiedFiles||[],deletedFiles:o.deletedFiles||[]}}catch{return{newFiles:[],modifiedFiles:[],deletedFiles:[]}}},async cleanup(e){try{let n=Tt.join(Mn,"snapshots",e);await xt.remove(n).catch(()=>{});let t=Z(un,{});t[e]&&(delete t[e],me(un,t))}catch{}}};var Pr=async(e,n={})=>{let t=O(e),o=t.method,s=t.id,r=n.chatId;if(!n.systemSettings?.advanceRollback)return"ERROR: Advance Rollback feature is currently disabled in settings under Security. Tell user to enable it.";if(!r)return"ERROR: No active chat transaction found for rollback.";if(o==="getCheckpoint"){let i=await Kn.getCheckpoints(r);if(i.length===0)return"No checkpoints available.";let p={write_file:"WriteFile",update_file:"PatchFile",view_file:"ReadFile",read_folder:"ReadFolder",exec_command:"Run",web_search:"WebSearch",web_scrape:"WebScrape",search_keyword:"SearchKeyword",CodeSearch:"SearchKeyword",code_search:"SearchKeyword",write_pdf:"WritePDF",write_docx:"WriteDoc",generate_image:"GenerateImage",file_map:"FileMap",todo:"Todo",goal:"Goal",Goal:"Goal",await:"Await",ask:"Ask",ask_user:"Ask",invoke:"Invoke",invokesync:"InvokeSync",getprogress:"GetProgress",cancel:"Cancel",emergency_rollback:"EmergencyRollback",emergencyrollback:"EmergencyRollback"},d=l=>p[l]||p[l.toLowerCase()]||l,c=`Available checkpoints for rollback:
462
462
 
463
463
  `;for(let l of i)if(l.id==="initial")c+=`--- Initial State (id: initial) ---
464
464
  Tools Used: User Prompted for task
@@ -506,8 +506,8 @@ ${l[7]}`};import{WebSocket as No}from"ws";var Yt=null,Fs=!1,ic="ws://localhost:5
506
506
  `}),p};import"@google/genai";Zr.config({quiet:!0});Zr.config({path:"./fluxflow.env",override:!0,quiet:!0});Zr.config({path:"./.fluxflow.env",override:!0,quiet:!0});var uc=/```[\s\S]*?```/g,hc=/```[\s\S]*$/g,pc=/`[^`]+`/g,mc=/^\|.*\|$/gm,gc=/^[^\w]+|[^\w]+$/g,yc=/[^a-z0-9]/gi,ho=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,wc=/\[\s*(?:tool:functions\.|agent:generalist\.)([a-z0-9_]+)\s*\(/gi,xc=/(?:path|targetFile|TargetFile|directory|keyword|id|taskId|title|task)\s*=\s*\\?["']?([^\\"' \),]+)/,gs=/["']/g,Ta=/\\/g,bc=/<\|channel>thought/gi,kc=/<channel\|>/gi,Pn=e=>typeof e!="string"?e:e.replace(bc,"<think>").replace(kc,"</think>"),Sc=/(?:<(think|thought|thoughts)>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\])/gi,Tc=/(?:<(think|thought|thoughts)>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*$/gi,Ra=/(?:<think>|<\|channel>thought|\[think\])[\s\S]*?(?:<\/think>|<channel\|>|\[\/think\]|$)/gi,Ea=/(?:<(think|thought|thoughts)>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\]|$)/gi,Oa=/`[^`]*`/g,La=/`[^`]*$/,_a=/<\|\s*tool_call_begin\s*\|>\s*(?:(?:tool|functions)\b[\s._]*)*([a-zA-Z0-9_]+)(?::\d+)?\s*<\|\s*tool_call_argument_begin\s*\|>([\s\S]*?)<\|\s*tool_call_end\s*\|>/gi,Rc=/"([^"]+)"\s*:\s*(?:"([^"]*)"|(\d+)|true|false|null)/g,$a=/<\|\s*tool_calls_section_begin\s*\|>/gi,Ca=/<\|\s*tool_calls_section_end\s*\|>/gi,Ec=/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi,Ma=/<(\w+)(?:[^>]*)>\r?\n?/gi,Aa=/\r?\n?<\/\w+(?:[^>]*)>/gi,ei=null,Wo={},ys={key:null,value:null},gn=e=>e&&e.replace(/(?:(\x1b\[\d+m))?([✔✘✖🔍📖→➕↻↷•🛇])(?:(\x1b\[\d+m))?\s*\b(Clicked|Dragged|Scrolled|Typed|Pressed Key|Recaptured Screen|Created|Read|Edited|Viewed|Processed|Auto-Read|Skipped|List|Generated|Written|Searched|AI Search|Get Map|Write Canceled|Resolved Sub-Agent Query|Edit Canceled|Write Cancelled|Edit Denied|Visited|Updated|Reviewed|Delegated|Background|Checked|Indexed|Analyzed|Browsed|Elevating SubAgent|Checking SubAgent Work|Started Generalist|Called Generalist|Steered|Unsupported Modality|Awaiting|Cancelled|Aligning Moon Phase|Contemplating Existence|Staring At Void|Rollback Point Checked|Emergency Rollback Failed|Emergency Rollback|Delaying Professionally|Negotiating With Electrons|Touching Grass (virtually)|Panicking Softly|Rethinking Career Choices|Loading Cat Videos|Giving Up Entirely|Summoning Braincell #2|Pretending To Be Busy|Waiting For Motivation DLC|Rotating Internal Screaming|Downloading More RAM|Feeding The Hamsters|Gaslighting Scheduler|Performing Dramatic Pause|Buffering Social Energy|Calculating Regret|Reading Terms And Conditions|Becoming Sentient Briefly|Contacting Ancestors)\b/ig,(n,t,o,s,r)=>`${t||""}${o}${s||""} \x1B[95m${r}\x1B[0m`),_c=async(e,n=8,t=1e3,o=8e3,s=null)=>{let r=0;for(;;){if(s?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{return await e()}catch(a){if(s?.aborted||a?.name==="AbortError"||a?.message==="Subagent task was cancelled."||(r++,r>=n))throw a;let i=Math.min(t*Math.pow(2,r-1),o);await new Promise((p,d)=>{let c=setTimeout(p,i);s&&s.addEventListener("abort",()=>{clearTimeout(c),d(new DOMException("The user aborted a request.","AbortError"))})})}}},Lt=!1;var $c=e=>{let n=e.filter(s=>(s.role==="user"||s.role==="agent"||s.role==="system")&&s.role!=="think"&&!s.isVisualFeedback&&!s.isMeta&&!s.isTerminalRecord&&!(s.text&&s.text.includes("[TERMINAL_RECORD]"))&&!String(s.id).startsWith("welcome")).map((s,r,a)=>{let i=s.fullText||s.text||"";if(s.role==="user"&&r<a.length-1)if(i.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")){let p=i.indexOf("**CONTEXT SUMMARY OF PREVIOUS TURNS");if(p!==-1){let c=i.substring(0,p).lastIndexOf("[SYSTEM METADATA]");c!==-1?i=i.substring(c).trim():i=i.substring(p).trim()}}else{let p=i.lastIndexOf("[USER]"),d=i.lastIndexOf("[USER PROMPT]");p!==-1?i=i.substring(p+6).trim():d!==-1&&(i=i.substring(d).trim())}return{...s,text:i}}),t=[],o=0;for(;o<n.length;){let s=n[o];if(s.role==="user")t.push(s),o++;else{let r=[];for(;o<n.length&&n[o].role!=="user";)r.push(n[o]),o++;let a=[],i=[],p=!1,d=()=>{a.length>0&&(t.push({role:"agent",text:"combined"}),a=[]),i.length>0&&(t.push({role:"system",text:"combined"}),i=[]),p=!1};r.forEach(c=>{let l=c.role==="system"&&(c.text?.startsWith("[TOOL RESULT]")||c.text?.startsWith("SUCCESS:")||c.text?.startsWith("ERROR:")||c.fullText?.startsWith("[TOOL RESULT]")||c.fullText?.startsWith("SUCCESS:")||c.fullText?.startsWith("ERROR:")),f=c.fullText||c.text||"",u=f.trim();if(!(!u&&!c.binaryPart)){if(l)i.push(u);else if(c.role==="agent"){!p&&i.length>0&&d();let h=f.endsWith(`
507
507
  `),g=u.toLowerCase().includes("tool:functions.")||u.toLowerCase().includes("agent:generalist.");a.push(u),g&&h?p=!0:p=!1}}}),d()}}return t.length},Cc=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),xs=async(e,n,t=5,o=1e3)=>{let s=n?.signal;for(let a=0;a<t;a++){if(s?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{let i=await fetch(e,n);if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),i.ok||i.status!==429&&i.status<500)return i}catch(i){if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),i.name==="AbortError"||s?.aborted||a===t-1)throw i}s?await new Promise((i,p)=>{let d=setTimeout(()=>{s.removeEventListener("abort",c),i()},Math.min(24e3,o*Math.pow(2,a))),c=()=>{clearTimeout(d),p(new DOMException("The user aborted a request.","AbortError"))};s.addEventListener("abort",c)}):await new Promise(i=>setTimeout(i,Math.min(24e3,o*Math.pow(2,a))))}if(s?.aborted)throw new DOMException("The user aborted a request.","AbortError");let r=await fetch(e,n);return typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),r};async function Pa(e){let n=new TextEncoder().encode(e),t=await crypto.subtle.digest("SHA-256",n);return[...new Uint8Array(t).slice(0,16)].map(o=>o.toString(16).padStart(2,"0")).join("")}var ti=async function*(e,n,t,o,s,r,a,i,p=1){let d=[];o&&d.push({role:"system",content:o});for(let b of t){let T=b.role==="user"?"user":"assistant",$=[];if(Array.isArray(b.parts)){for(let R of b.parts)if(R.text)$.push({type:"text",text:R.text});else if(R.inlineData&&a){let k=R.inlineData.mimeType,S=R.inlineData.data;k.startsWith("image/")&&$.push({type:"image_url",image_url:{url:`data:${k};base64,${S}`}})}}else{let R=b.text||"";R&&$.push({type:"text",text:R})}d.push({role:T,content:$.length===1&&$[0].type==="text"?$[0].text:$})}let c={model:n,messages:d,stream:!0,stream_options:{include_usage:!0},temperature:p};if(s!=="Fast"){let b={Low:"high",Medium:"high",Standard:"high",High:"max",xHigh:"max"};c.reasoning_effort=b[s]||"high",c.extra_body={thinking:{type:"enabled"}}}else c.extra_body={thinking:{type:"disabled"}};let l=await xs("https://api.deepseek.com/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(c),signal:i});if(!l.ok){let b=await l.json().catch(()=>({}));throw new Error(`DeepSeek Error (${l.status}): ${b.error?.message||l.statusText}`)}let f=l.body.getReader(),u=new TextDecoder,h="",g=[],y=null,m=Date.now(),w=!1;for(;;){let{done:b,value:T}=await f.read();if(b){w&&(g.length>0||y)&&(yield{candidates:g.length>0?[{content:{parts:g}}]:[],usageMetadata:y});break}h+=u.decode(T,{stream:!0});let $=h.split(`
508
508
  `);h=$.pop();for(let R of $){let k=R.trim();if(!k||!k.startsWith("data: "))continue;let S=!1;if(k==="data: [DONE]")S=!0;else try{let _=JSON.parse(k.substring(6)),E=_.choices?.[0]?.delta,x=_.usage;if(_.choices?.[0]?.finish_reason&&(S=!0),x&&(y={totalTokenCount:x.total_tokens||x.prompt_tokens+x.completion_tokens,promptTokenCount:x.prompt_tokens||0,candidatesTokenCount:x.completion_tokens||0,cachedContentTokenCount:x.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:x.completion_tokens_details?.reasoning_tokens||0},w=!0),E){let C=E.reasoning_content||null;C&&(g.push({text:C,thought:!0}),w=!0),E.content&&(g.push({text:E.content}),w=!0)}}catch{}if((S||Date.now()-m>=150)&&w&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],m=Date.now(),w=!1),S)break}Date.now()-m>=150&&w&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],m=Date.now(),w=!1)}},ni=async function*(e,n,t,o,s,r,a,i,p=1,d=null){let c=[];o&&c.push({role:"system",content:o});for(let S of t){let _=S.role==="user"?"user":"assistant",E=[];if(Array.isArray(S.parts)){for(let x of S.parts)if(x.text)E.push({type:"text",text:x.text});else if(x.inlineData&&a){let C=x.inlineData.mimeType,I=x.inlineData.data;C.startsWith("image/")&&E.push({type:"image_url",image_url:`data:${C};base64,${I}`})}}else{let x=S.text||"";x&&E.push({type:"text",text:x})}E.length>0&&c.push({role:_,content:E.length===1&&E[0].type==="text"?E[0].text:E})}let l={Fast:"none",Low:"none",Medium:"high",Standard:"high",High:"high",xHigh:"high"},f=`${e.slice(-5)}${d||""}${s}${n}`,u=await Pa(f),h={model:n,messages:c,stream:!0,temperature:p,prompt_cache_key:u};s&&s!=="Fast"&&qs(n)&&(h.reasoning_effort=l[s]||"high");let g=await xs("https://api.mistral.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(h),signal:i});if(!g.ok){let S=await g.text().catch(()=>""),_=g.statusText;try{let E=JSON.parse(S);_=E.error?.message||E.message||JSON.stringify(E.detail||E)}catch{S&&(_=S)}throw new Error(`Mistral Error (${g.status}): ${JSON.stringify(_)}`)}let y=g.body.getReader(),m=new TextDecoder,w="",b=[],T=null,$=Date.now(),R=!1,k=S=>S?typeof S=="string"?Pn(S):Array.isArray(S)?S.map(k).filter(Boolean).join(""):typeof S=="object"&&S!==null?typeof S.text=="string"?Pn(S.text):typeof S.content=="string"?Pn(S.content):typeof S.thinking=="string"?Pn(S.thinking):typeof S.reasoning_content=="string"?Pn(S.reasoning_content):typeof S.reasoning=="string"?Pn(S.reasoning):typeof S.value=="string"?Pn(S.value):S.text?k(S.text):S.content?k(S.content):S.thinking?k(S.thinking):S.reasoning_content?k(S.reasoning_content):S.reasoning?k(S.reasoning):S.value?k(S.value):"":Pn(String(S)):"";for(;;){let{done:S,value:_}=await y.read();if(S){R&&(b.length>0||T)&&(yield{candidates:b.length>0?[{content:{parts:b}}]:[],usageMetadata:T});break}w+=m.decode(_,{stream:!0});let E=w.split(`
509
- `);w=E.pop();for(let x of E){let C=x.trim();if(!C||!C.startsWith("data: "))continue;let I=!1;if(C==="data: [DONE]")I=!0;else try{let L=JSON.parse(C.substring(6)),N=L.choices?.[0]?.delta,W=L.usage;if(L.choices?.[0]?.finish_reason&&(I=!0),W&&(T={totalTokenCount:W.total_tokens||(W.prompt_tokens||0)+(W.completion_tokens||0),promptTokenCount:W.prompt_tokens||0,candidatesTokenCount:W.completion_tokens||0,cachedContentTokenCount:W.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:W.completion_tokens_details?.reasoning_tokens||0},R=!0),N){let X=N.thinking||N.reasoning_content||N.reasoning,re=k(X);re&&(b.push({text:re,thought:!0}),R=!0);let Y=N.content||(!N.thinking&&!N.reasoning_content&&!N.reasoning?N.text:null);if(Y)if(Array.isArray(Y))for(let F of Y)if(typeof F=="object"&&F!==null){let U=F.type==="thinking"||F.type==="reasoning"||!!F.thought,se=k(F);se&&(b.push({text:se,...U?{thought:!0}:{}}),R=!0)}else{let U=k(F);U&&(b.push({text:U}),R=!0)}else if(typeof Y=="object"&&Y!==null){let F=Y.type==="thinking"||Y.type==="reasoning"||!!Y.thought,U=k(Y);U&&(b.push({text:U,...F?{thought:!0}:{}}),R=!0)}else{let F=k(Y);F&&(b.push({text:F}),R=!0)}}}catch{}if((I||Date.now()-$>=150)&&R&&(yield{candidates:b.length>0?[{content:{parts:[...b]}}]:[],usageMetadata:T},b=[],$=Date.now(),R=!1),I)break}Date.now()-$>=150&&R&&(yield{candidates:b.length>0?[{content:{parts:[...b]}}]:[],usageMetadata:T},b=[],$=Date.now(),R=!1)}},si=async function*(e,n,t,o,s,r,a=!1,i,p=1){let d=[];o&&d.push({role:"system",content:o}),t.forEach(se=>{let $e=se.role==="model"?"assistant":"user",A=[];Array.isArray(se.parts)&&se.parts.forEach(B=>{if(B.text)A.push({type:"text",text:B.text});else if(B.inlineData&&a){let V=B.inlineData.mimeType,J=B.inlineData.data;V.startsWith("image/")&&zt(n)&&A.push({type:"image_url",image_url:{url:`data:${V};base64,${J}`}})}}),d.push({role:$e,content:A.length===1&&A[0].type==="text"?A[0].text:A})});let l={Fast:"Fast",Low:"Fast",Medium:"Standard",Standard:"Standard",High:"High",xHigh:"High"}[s]||"High",f=l!=="Fast",u=n.includes("kimi"),h=n.includes("gemma"),g=n.includes("deepseek"),y=n.includes("glm"),m=n.includes("mistral"),w=n.includes("minimax"),b=n.includes("gpt"),T=n.includes("qwen"),$=n.includes("nemotron"),R=n.includes("llama-3"),k=n.includes("seed"),S=n.includes("poolside"),_=n.includes("thinkingmachines")||n.includes("muse"),E=R,x=null,C={Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},I={Fast:"64",Low:"64",Medium:"4096",Standard:"4096",High:"16384",xHigh:"16384"},L={Fast:"none",Low:"minimal",Medium:"medium",Standard:"medium",High:"max",xHigh:"max"},N=w||g||S||_?16384:32768;N=process.env.NVIDIA_BASE_URL?1024:N,N=x?1024:N;let W={model:n,messages:d,max_tokens:N,stream:!0,stream_options:{include_usage:!0},temperature:p,...b&&{thinking:C[s]||"high"}};if(!(process.env.NVIDIA_BASE_URL||E||x))if(u)W.chat_template_kwargs={thinking:f};else if(h)W.chat_template_kwargs={enable_thinking:f};else if(g)if(f){let se=l==="High"?"max":"high";W.chat_template_kwargs={thinking:!0,reasoning_effort:se}}else W.chat_template_kwargs={thinking:!1};else y?W.chat_template_kwargs={enable_thinking:f,clear_thinking:!f}:m?W.reasoning_effort=f?"high":"none":w&&n.includes("minimax-m3")?W.chat_template_kwargs={thinking_mode:f?"enabled":"disabled"}:T?W.chat_template_kwargs={enable_thinking:f}:$?l==="High"?(W.reasoning_budget=12e3,W.chat_template_kwargs={enable_thinking:!0}):l==="Standard"?(W.reasoning_budget=12e3,W.chat_template_kwargs={enable_thinking:!0,medium_effort:!0}):W.chat_template_kwargs={enable_thinking:!1}:k?f&&(W.extra_body={thinking_budget:parseInt(I[l]??"4096")}):S?W.chat_template_kwargs={enable_thinking:f}:_&&(W.reasoning_effort=L[l]||"medium");let X=0,re=6,Y=!1,F=process.env.NVIDIA_BASE_URL||"https://integrate.api.nvidia.com/v1/chat/completions",U=process.env.NVIDIA_API_KEY&&process.env.NVIDIA_BASE_URL?process.env.NVIDIA_API_KEY:e;for(F.endsWith("/chat/completions")||(F=F.replace(/\/+$/,"")+"/chat/completions");X<re;){X++;try{let se=await xs(F,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${U}`},body:JSON.stringify(W),signal:i});if(!se.ok){let je=await se.text().catch(()=>""),it=se.statusText;try{let gt=JSON.parse(je);it=gt.error?.message||gt.message||JSON.stringify(gt.detail||gt)}catch{je&&(it=je)}let ze=new Error(`NVIDIA API Error (${se.status}): ${it}`);throw ze.status=se.status,ze}let $e=se.body.getReader(),A=new TextDecoder,B="",V=[],J=null,Ue=Date.now(),Fe=!1;for(;;){let{done:je,value:it}=await $e.read();if(je){Fe&&(V.length>0||J)&&(yield{candidates:V.length>0?[{content:{parts:V}}]:[],usageMetadata:J},Y=!0);break}B+=A.decode(it,{stream:!0});let ze=B.split(`
510
- `);B=ze.pop();let gt=!1;for(let Bt of ze){let yt=Bt.trim();if(yt){if(yt==="data: [DONE]"){gt=!0;break}if(yt.startsWith("data: ")){let wt;try{wt=JSON.parse(yt.substring(6))}catch{continue}if(wt.error)throw new Error(`NVIDIA Stream Error: ${wt.error.message||JSON.stringify(wt.error)}`);wt.choices?.[0]?.finish_reason&&(gt=!0);try{let Rt=wt.usage;Rt&&(J={totalTokenCount:Rt.total_tokens||Rt.prompt_tokens+Rt.completion_tokens,promptTokenCount:Rt.prompt_tokens||0,candidatesTokenCount:Rt.completion_tokens||0,cachedContentTokenCount:Rt.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:(Rt.completion_tokens_details?.reasoning_tokens||0)+(Rt.completion_tokens_details?.thoughts_tokens||0)},Fe=!0);let ut=wt.choices?.[0]?.delta?.reasoning||wt.choices?.[0]?.delta?.reasoning_content||"",Ce=wt.choices?.[0]?.delta?.content||"";ut&&(V.push({text:ut,thought:!0}),Fe=!0),Ce&&(V.push({text:Ce}),Fe=!0)}catch{}}}}if((gt||Date.now()-Ue>=350)&&Fe&&(yield{candidates:V.length>0?[{content:{parts:[...V]}}]:[],usageMetadata:J},Y=!0,V=[],Ue=Date.now(),Fe=!1),gt)break}break}catch(se){if(Y||X>=re)throw se;await new Promise($e=>setTimeout($e,3500))}}},Mc=async function*(e,n){let t=[],o=null,s=!1,r=null,a=f=>{if(t.push(f),o){let u=o;o=null,u()}},i=n.split("/").pop();i=i.replace("llama-3.3","llama-3_3");let p=`https://api.ngc.nvidia.com/v2/predict/queues/models/qc69jvmznzxy/${i}`,d=!1,c=null,l=async()=>{try{let f=await fetch(p);if(f.ok){let u=await f.json();if(u&&u.queues&&u.queues[0]&&typeof u.queues[0].queueDepth=="number"){let h=u.queues[0].queueDepth;d||a({value:{type:"status",content:`Queue ${h||1}`},done:!1})}}else d||a({value:{type:"status",content:`Queue ${f.status}`},done:!1})}catch{}};process.env.NVIDIA_BASE_URL||(l(),c=setInterval(l,5e3)),(async()=>{try{let f=e[Symbol.asyncIterator]();for(;;){let{value:u,done:h}=await f.next();if(h)break;d=!0,c&&(clearInterval(c),c=null),a({value:u,done:!1})}s=!0,a(null)}catch(f){if(r=f,c&&(clearInterval(c),c=null),o){let u=o;o=null,u()}}})();try{for(;;){if(r)throw r;if(t.length>0){let f=t.shift();if(f===null&&s)break;yield f.value}else{if(s)break;await new Promise(f=>{o=f})}}}finally{c&&(clearInterval(c),c=null)}},oi=async function*(e,n,t,o,s,r,a,i,p=1,d=null){let c=[];o&&c.push({role:"system",content:[{type:"text",text:o}]});for(let x of t){let C=x.role==="user"?"user":"assistant",I=[];if(Array.isArray(x.parts)){for(let L of x.parts)if(L.text)I.push({type:"text",text:L.text});else if(L.inlineData&&a){let N=L.inlineData.mimeType,W=L.inlineData.data;N.startsWith("image/")?I.push({type:"image_url",image_url:{url:`data:${N};base64,${W}`}}):I.push({type:"file",file:{filename:L.filename||"file",file_data:`data:${N};base64,${W}`}})}}else{let L=x.text||"";L&&I.push({type:"text",text:L})}c.push({role:C,content:I.length===1&&I[0].type==="text"?I[0].text:I})}let l={Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},f=n,u=null;if(f.includes("::")){let x=f.split("::");f=x[0].trim();let C=x.slice(1).join("::").toLowerCase().trim();["flex","priority","default"].includes(C)&&C!=="default"&&(u=C)}let h=f;if(f.includes(":")){let[x,...C]=f.split(":"),I=C.join(":").toLowerCase().trim();u?h=`${x}:${I}/${u}`:h=`${x}:${I}`}let g=`${e.slice(-5)}${d||""}${s}${h}`,y=await Pa(g),m={model:h,messages:c,stream:!0,temperature:p,cache_control:{type:"ephemeral"},session_id:y},w=l[s];w&&s!=="Fast"&&(m.reasoning_effort=w);let b=await xs("https://openrouter.ai/api/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json","X-Title":"FluxFlow CLI","X-Cache":"true","X-OpenRouter-Cache":"true"},body:JSON.stringify(m),signal:i});if(!b.ok){let x=await b.json().catch(()=>({}));throw new Error(`OpenRouter Error (${b.status}): ${x.error?.metadata.raw||x.error?.message||b.statusText}`)}let T=b.body.getReader(),$=new TextDecoder,R="",k=[],S=null,_=Date.now(),E=!1;for(;;){let{done:x,value:C}=await T.read();if(x){E&&(k.length>0||S)&&(yield{candidates:k.length>0?[{content:{parts:k}}]:[],usageMetadata:S});break}R+=$.decode(C,{stream:!0});let I=R.split(`
509
+ `);w=E.pop();for(let x of E){let C=x.trim();if(!C||!C.startsWith("data: "))continue;let I=!1;if(C==="data: [DONE]")I=!0;else try{let L=JSON.parse(C.substring(6)),N=L.choices?.[0]?.delta,W=L.usage;if(L.choices?.[0]?.finish_reason&&(I=!0),W&&(T={totalTokenCount:W.total_tokens||(W.prompt_tokens||0)+(W.completion_tokens||0),promptTokenCount:W.prompt_tokens||0,candidatesTokenCount:W.completion_tokens||0,cachedContentTokenCount:W.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:W.completion_tokens_details?.reasoning_tokens||0},R=!0),N){let X=N.thinking||N.reasoning_content||N.reasoning,re=k(X);re&&(b.push({text:re,thought:!0}),R=!0);let Y=N.content||(!N.thinking&&!N.reasoning_content&&!N.reasoning?N.text:null);if(Y)if(Array.isArray(Y))for(let F of Y)if(typeof F=="object"&&F!==null){let U=F.type==="thinking"||F.type==="reasoning"||!!F.thought,se=k(F);se&&(b.push({text:se,...U?{thought:!0}:{}}),R=!0)}else{let U=k(F);U&&(b.push({text:U}),R=!0)}else if(typeof Y=="object"&&Y!==null){let F=Y.type==="thinking"||Y.type==="reasoning"||!!Y.thought,U=k(Y);U&&(b.push({text:U,...F?{thought:!0}:{}}),R=!0)}else{let F=k(Y);F&&(b.push({text:F}),R=!0)}}}catch{}if((I||Date.now()-$>=150)&&R&&(yield{candidates:b.length>0?[{content:{parts:[...b]}}]:[],usageMetadata:T},b=[],$=Date.now(),R=!1),I)break}Date.now()-$>=150&&R&&(yield{candidates:b.length>0?[{content:{parts:[...b]}}]:[],usageMetadata:T},b=[],$=Date.now(),R=!1)}},si=async function*(e,n,t,o,s,r,a=!1,i,p=1){let d=[];o&&d.push({role:"system",content:o}),t.forEach(se=>{let $e=se.role==="model"?"assistant":"user",A=[];Array.isArray(se.parts)&&se.parts.forEach(B=>{if(B.text)A.push({type:"text",text:B.text});else if(B.inlineData&&a){let V=B.inlineData.mimeType,J=B.inlineData.data;V.startsWith("image/")&&zt(n)&&A.push({type:"image_url",image_url:{url:`data:${V};base64,${J}`}})}}),d.push({role:$e,content:A.length===1&&A[0].type==="text"?A[0].text:A})});let l={Fast:"Fast",Low:"Fast",Medium:"Standard",Standard:"Standard",High:"High",xHigh:"High"}[s]||"High",f=l!=="Fast",u=n.includes("kimi"),h=n.includes("gemma"),g=n.includes("deepseek"),y=n.includes("glm"),m=n.includes("mistral"),w=n.includes("minimax"),b=n.includes("gpt"),T=n.includes("qwen"),$=n.includes("nemotron"),R=n.includes("llama-3"),k=n.includes("seed"),S=n.includes("poolside"),_=n.includes("thinkingmachines")||n.includes("muse"),E=R,x=null,C={Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},I={Fast:"64",Low:"64",Medium:"4096",Standard:"4096",High:"16384",xHigh:"16384"},L={Fast:"none",Low:"minimal",Medium:"medium",Standard:"medium",High:"max",xHigh:"max"},N=w||g||S||_?16384:32768;N=process.env.NVIDIA_BASE_URL?1024:N,N=x?1024:N;let W={model:n,messages:d,max_tokens:N,stream:!0,stream_options:{include_usage:!0},temperature:p,...b&&{thinking:C[s]||"high"}};if(!(process.env.NVIDIA_BASE_URL||E||x))if(u)W.chat_template_kwargs={thinking:f};else if(h)W.chat_template_kwargs={enable_thinking:f};else if(g)if(f){let se=l==="High"?"max":"high";W.chat_template_kwargs={thinking:!0,reasoning_effort:se}}else W.chat_template_kwargs={thinking:!1};else y?W.chat_template_kwargs={enable_thinking:f,clear_thinking:!f}:m?W.reasoning_effort=f?"high":"none":w&&n.includes("minimax-m3")?W.chat_template_kwargs={thinking_mode:f?"enabled":"disabled"}:T?W.chat_template_kwargs={enable_thinking:f}:$?l==="High"?W.chat_template_kwargs={enable_thinking:!0}:l==="Standard"?W.chat_template_kwargs={enable_thinking:!0,medium_effort:!0}:W.chat_template_kwargs={enable_thinking:!1}:k?f&&(W.extra_body={thinking_budget:parseInt(I[l]??"4096")}):S?W.chat_template_kwargs={enable_thinking:f}:_&&(W.reasoning_effort=L[l]||"medium");let X=0,re=6,Y=!1,F=process.env.NVIDIA_BASE_URL||"https://integrate.api.nvidia.com/v1/chat/completions",U=process.env.NVIDIA_API_KEY&&process.env.NVIDIA_BASE_URL?process.env.NVIDIA_API_KEY:e;for(F.endsWith("/chat/completions")||(F=F.replace(/\/+$/,"")+"/chat/completions");X<re;){X++;try{let se=await xs(F,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${U}`},body:JSON.stringify(W),signal:i});if(!se.ok){let je=await se.text().catch(()=>""),it=se.statusText;try{let bt=JSON.parse(je);it=bt.error?.message||bt.message||JSON.stringify(bt.detail||bt)}catch{je&&(it=je)}let ze=new Error(`NVIDIA API Error (${se.status}): ${it}`);throw ze.status=se.status,ze}let $e=se.body.getReader(),A=new TextDecoder,B="",V=[],J=null,Ue=Date.now(),Fe=!1;for(;;){let{done:je,value:it}=await $e.read();if(je){Fe&&(V.length>0||J)&&(yield{candidates:V.length>0?[{content:{parts:V}}]:[],usageMetadata:J},Y=!0);break}B+=A.decode(it,{stream:!0});let ze=B.split(`
510
+ `);B=ze.pop();let bt=!1;for(let Bt of ze){let gt=Bt.trim();if(gt){if(gt==="data: [DONE]"){bt=!0;break}if(gt.startsWith("data: ")){let kt;try{kt=JSON.parse(gt.substring(6))}catch{continue}if(kt.error)throw new Error(`NVIDIA Stream Error: ${kt.error.message||JSON.stringify(kt.error)}`);try{let Rt=kt.usage;Rt&&(J={totalTokenCount:Rt.total_tokens||Rt.prompt_tokens+Rt.completion_tokens,promptTokenCount:Rt.prompt_tokens||0,candidatesTokenCount:Rt.completion_tokens||0,cachedContentTokenCount:Rt.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:(Rt.completion_tokens_details?.reasoning_tokens||0)+(Rt.completion_tokens_details?.thoughts_tokens||0)},Fe=!0);let ut=kt.choices?.[0]?.delta?.reasoning||kt.choices?.[0]?.delta?.reasoning_content||"",Ce=kt.choices?.[0]?.delta?.content||"";ut&&(V.push({text:ut,thought:!0}),Fe=!0),Ce&&(V.push({text:Ce}),Fe=!0)}catch{}}}}if((bt||Date.now()-Ue>=350)&&Fe&&(yield{candidates:V.length>0?[{content:{parts:[...V]}}]:[],usageMetadata:J},Y=!0,V=[],Ue=Date.now(),Fe=!1),bt)break}break}catch(se){if(Y||X>=re)throw se;await new Promise($e=>setTimeout($e,3500))}}},Mc=async function*(e,n){let t=[],o=null,s=!1,r=null,a=f=>{if(t.push(f),o){let u=o;o=null,u()}},i=n.split("/").pop();i=i.replace("llama-3.3","llama-3_3");let p=`https://api.ngc.nvidia.com/v2/predict/queues/models/qc69jvmznzxy/${i}`,d=!1,c=null,l=async()=>{try{let f=await fetch(p);if(f.ok){let u=await f.json();if(u&&u.queues&&u.queues[0]&&typeof u.queues[0].queueDepth=="number"){let h=u.queues[0].queueDepth;d||a({value:{type:"status",content:`Queue ${h||1}`},done:!1})}}}catch{}};process.env.NVIDIA_BASE_URL||(l(),c=setInterval(l,5e3)),(async()=>{try{let f=e[Symbol.asyncIterator]();for(;;){let{value:u,done:h}=await f.next();if(h)break;d=!0,c&&(clearInterval(c),c=null),a({value:u,done:!1})}s=!0,a(null)}catch(f){if(r=f,c&&(clearInterval(c),c=null),o){let u=o;o=null,u()}}})();try{for(;;){if(r)throw r;if(t.length>0){let f=t.shift();if(f===null&&s)break;yield f.value}else{if(s)break;await new Promise(f=>{o=f})}}}finally{c&&(clearInterval(c),c=null)}},oi=async function*(e,n,t,o,s,r,a,i,p=1,d=null){let c=[];o&&c.push({role:"system",content:[{type:"text",text:o}]});for(let x of t){let C=x.role==="user"?"user":"assistant",I=[];if(Array.isArray(x.parts)){for(let L of x.parts)if(L.text)I.push({type:"text",text:L.text});else if(L.inlineData&&a){let N=L.inlineData.mimeType,W=L.inlineData.data;N.startsWith("image/")?I.push({type:"image_url",image_url:{url:`data:${N};base64,${W}`}}):I.push({type:"file",file:{filename:L.filename||"file",file_data:`data:${N};base64,${W}`}})}}else{let L=x.text||"";L&&I.push({type:"text",text:L})}c.push({role:C,content:I.length===1&&I[0].type==="text"?I[0].text:I})}let l={Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},f=n,u=null;if(f.includes("::")){let x=f.split("::");f=x[0].trim();let C=x.slice(1).join("::").toLowerCase().trim();["flex","priority","default"].includes(C)&&C!=="default"&&(u=C)}let h=f;if(f.includes(":")){let[x,...C]=f.split(":"),I=C.join(":").toLowerCase().trim();u?h=`${x}:${I}/${u}`:h=`${x}:${I}`}let g=`${e.slice(-5)}${d||""}${s}${h}`,y=await Pa(g),m={model:h,messages:c,stream:!0,temperature:p,cache_control:{type:"ephemeral"},session_id:y},w=l[s];w&&s!=="Fast"&&(m.reasoning_effort=w);let b=await xs("https://openrouter.ai/api/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json","HTTP-Referer":"https://fluxflow-cli.onrender.com/","X-Title":"FluxFlow CLI","X-OpenRouter-Title":"FluxFlow CLI","X-Cache":"true","X-OpenRouter-Cache":"true"},body:JSON.stringify(m),signal:i});if(!b.ok){let x=await b.json().catch(()=>({}));throw new Error(`OpenRouter Error (${b.status}): ${x.error?.metadata.raw||x.error?.message||b.statusText}`)}let T=b.body.getReader(),$=new TextDecoder,R="",k=[],S=null,_=Date.now(),E=!1;for(;;){let{done:x,value:C}=await T.read();if(x){E&&(k.length>0||S)&&(yield{candidates:k.length>0?[{content:{parts:k}}]:[],usageMetadata:S});break}R+=$.decode(C,{stream:!0});let I=R.split(`
511
511
  `);R=I.pop();for(let L of I){let N=L.trim();if(!N||!N.startsWith("data: "))continue;let W=!1;if(N==="data: [DONE]")W=!0;else try{let X=JSON.parse(N.substring(6)),re=X.choices?.[0]?.delta,Y=X.usage;if(X.choices?.[0]?.finish_reason&&(W=!0),Y&&(S={totalTokenCount:Y.total_tokens||(Y.prompt_tokens||0)+(Y.completion_tokens||0),promptTokenCount:Y.prompt_tokens||0,candidatesTokenCount:Y.completion_tokens||0,cachedContentTokenCount:Y.prompt_tokens_details?.cached_tokens||Y.prompt_tokens_details?.cache_read_input_tokens||Y.cache_read_input_tokens||0,thoughtsTokenCount:Y.completion_tokens_details?.reasoning_tokens||0},E=!0),re){let F=re.reasoning||(re.reasoning_details?re.reasoning_details.map(U=>U.text).join(""):null);F&&(k.push({text:F,thought:!0}),E=!0),re.content&&(k.push({text:re.content}),E=!0)}}catch{}if((W||Date.now()-_>=150)&&E&&(yield{candidates:k.length>0?[{content:{parts:[...k]}}]:[],usageMetadata:S},k=[],_=Date.now(),E=!1),W)break}}},Da=async function*(e,n,t,o,s,r,a,i,p=1,d="Cloud"){let c=[];o&&c.push({role:"system",content:o});for(let k of t){let S=k.role==="user"?"user":"assistant",_="",E=[];if(Array.isArray(k.parts)){_=k.parts.map(x=>x.text||"").filter(Boolean).join(`
512
512
  `);for(let x of k.parts){let C=x.inlineData||x.inline_data;C&&C.data&&E.push(C.data)}}else _=k.text||"";if(_||E.length>0){let x={role:S,content:_};E.length>0&&(x.images=E),c.push(x)}}let l=d==="Local"||!e||e==="LOCAL",u={host:l?process.env.OLLAMA_HOST||"http://127.0.0.1:11434":process.env.OLLAMA_HOST||"https://ollama.com"};!l&&e&&(u.headers={Authorization:"Bearer "+e});let h=new fc(u),g=[],y=null,m=Date.now(),w=!1,b={Fast:!1,Low:"medium",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},T=b[s]!==void 0?b[s]:!0,$={model:n,messages:c,stream:!0,think:T,keep_alive:"10m",options:{temperature:p}},R=await h.chat($);for await(let k of R){if(i?.aborted)throw new DOMException("The user aborted a request.","AbortError");if(k.message?.thinking&&(g.push({text:k.message.thinking,thought:!0}),w=!0),k.message?.content&&(g.push({text:k.message.content}),w=!0),k.done){let S=k.prompt_cached_count||0;if(!S&&k.prompt_eval_count){let _=k.prompt_eval_duration||0;_>0&&_<5e7&&(S=k.prompt_eval_count)}y={totalTokenCount:(k.prompt_eval_count||0)+(k.eval_count||0),promptTokenCount:k.prompt_eval_count||0,candidatesTokenCount:k.eval_count||0,cachedContentTokenCount:S,thoughtsTokenCount:0},w=!0}(k.done||Date.now()-m>=150&&w)&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],m=Date.now(),w=!1)}w&&(g.length>0||y)&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y})},ri=async function*(e,n,t,o,s,r,a,i,p=1){let d=[];o&&d.push({role:"system",content:o});for(let T of t){let $=T.role==="user"?"user":"assistant",R=[];if(Array.isArray(T.parts)){for(let k of T.parts)if(k.text)R.push({type:"text",text:k.text});else if(k.inlineData&&a){let S=k.inlineData.mimeType,_=k.inlineData.data;S.startsWith("image/")&&R.push({type:"image_url",image_url:{url:`data:${S};base64,${_}`}})}}else{let k=T.text||"";k&&R.push({type:"text",text:k})}d.push({role:$,content:R.length===1&&R[0].type==="text"?R[0].text:R})}let c={Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},l={model:n,messages:d,stream:!0,stream_options:{include_usage:!0},temperature:p,max_completion_tokens:32768};c[s]&&(l.reasoning_effort=c[s]);let f=await xs("https://crof.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(l),signal:i});if(!f.ok){let T=await f.json().catch(()=>({}));throw new Error(`CrofAI Error (${f.status}): ${T.error?.message||f.statusText}`)}let u=f.body.getReader(),h=new TextDecoder,g="",y=[],m=null,w=Date.now(),b=!1;for(;;){let{done:T,value:$}=await u.read();if(T){b&&(y.length>0||m)&&(yield{candidates:y.length>0?[{content:{parts:y}}]:[],usageMetadata:m});break}g+=h.decode($,{stream:!0});let R=g.split(`
513
513
  `);g=R.pop();for(let k of R){let S=k.trim();if(!S||!S.startsWith("data: "))continue;let _=!1;if(S==="data: [DONE]")_=!0;else try{let E=JSON.parse(S.substring(6)),x=E.choices?.[0]?.delta,C=E.usage;if(E.choices?.[0]?.finish_reason&&(_=!0),C&&(m={totalTokenCount:C.total_tokens||(C.prompt_tokens||0)+(C.completion_tokens||0),promptTokenCount:C.prompt_tokens||0,candidatesTokenCount:C.completion_tokens||0,cachedContentTokenCount:C.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:C.completion_tokens_details?.reasoning_tokens||C.reasoning_tokens||0},b=!0),x){let I=x.reasoning_content||null;I&&(y.push({text:I,thought:!0}),b=!0),x.content&&(y.push({text:x.content}),b=!0)}}catch{}if((_||Date.now()-w>=150)&&b&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),b=!1),_)break}Date.now()-w>=150&&b&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),b=!1)}},ii=async function*(e,n,t,o,s,r,a,i,p=1){let d=[];o&&d.push({role:"system",content:o});for(let T of t){let $=T.role==="user"?"user":"assistant",R="";if(Array.isArray(T.parts))for(let k of T.parts)k.text&&(R+=(R?`
@@ -526,7 +526,7 @@ ${l[7]}`};import{WebSocket as No}from"ws";var Yt=null,Fs=!1,ic="ws://localhost:5
526
526
  ${L.length>8192?`... (truncated) ...
527
527
 
528
528
  `:""}
529
- [AGENT (current turn)]: ${I}`;R.push({role:"user",parts:[{text:X}]});let re=await Qo("NVIDIA"),F=(await Ft()).quotas?.providerTiers?.NVIDIA==="Free",U="",se=0,$e=b?12:-1;for(;se<=$e;)try{if(!await Li("background",e))return;let A="",B=null,V=!1,J=m;try{let je=new Promise((ut,Ce)=>setTimeout(()=>Ce(new Error("JANITOR_TIMEOUT")),1e4)),it=m==="Google"&&se>=0&&se<6&&re&&F,ze=m==="DeepSeek"&&se<4&&re&&F;V=it||ze,J=V?"NVIDIA":m;let gt=(async()=>{if(m==="OpenRouter"){let ut=Ie("janitor_open_router"),le=oi(w,ut,R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),Vt=await le.next();return{iterator:le,firstResult:Vt}}else if(m==="DeepSeek"&&!V){let Ce=ti(w,Ie("deepseek_fast_fallback"),R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await Ce.next();return{iterator:Ce,firstResult:le}}else if(m==="Mistral"&&!V){let Ce=ni(w,Ie("mistral_janitor_fallback"),R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await Ce.next();return{iterator:Ce,firstResult:le}}else if(m==="NVIDIA"||V){let Ce=si(V?re:w,Ie("nvidia_janitor_fallback"),R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await Ce.next();return{iterator:Ce,firstResult:le}}else if(m==="CrofAI"){let Ce=ri(w,targetModel||Ie("crofai_fallback")||"deepseek-v4-flash-0731",R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await Ce.next();return{iterator:Ce,firstResult:le}}else if(m==="InferX"){let Ce=ii(w,targetModel||Ie("inferx_fallback")||"deepseek-v4-flash",R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await Ce.next();return{iterator:Ce,firstResult:le}}else if(m==="SenseNova"){let Ce=ai(w,targetModel||Ie("sensenova_fallback")||"sensenova-6.8-flash-lite",R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await Ce.next();return{iterator:Ce,firstResult:le}}else{let le=(await li(w).models.generateContentStream({model:u||(se===$e?Ie("janitor_default"):Ie("gemma_janitor_fallback_google")),contents:R,config:{systemInstruction:C,temperature:.7,safetySettings:[{category:Vn.HARM_CATEGORY_HARASSMENT,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_HATE_SPEECH,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Yn.BLOCK_NONE}],thinkingConfig:{includeThoughts:!1,thinkingLevel:ft.MINIMAL}}}))[Symbol.asyncIterator](),Vt=await le.next();return{iterator:le,firstResult:Vt}}})();if(process.stdout.isTTY){let le=(await as())[h]?.name||"",Vt=le&&!le.startsWith("flow-")&&!le.startsWith("Session ")?le:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${Vt}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${Vt}\x07`)}let{iterator:Bt,firstResult:yt}=await Promise.race([gt,je]),{value:wt,done:Rt}=yt;if(!Rt&&wt){let ut=wt.candidates?.[0]?.content?.parts,Ce=ut?J==="Google"?ut[1]?.text||ut[0]?.text||"":ut.filter(le=>le.text&&!le.thought).map(le=>le.text).join(""):typeof wt.text=="function"?wt.text():"";Ce&&(A+=Ce),B=wt.usageMetadata;for await(let le of{[Symbol.asyncIterator]:()=>Bt}){let Vt=le.candidates?.[0]?.content?.parts,Xn=Vt?J==="Google"?Vt[1]?.text||Vt[0]?.text||"":Vt.filter(Jn=>Jn.text&&!Jn.thought).map(Jn=>Jn.text).join(""):typeof le.text=="function"?le.text():"";Xn&&(A+=Xn),B=le.usageMetadata}}}catch(je){throw je}if(A){if(U=A,B){let je=B.totalTokenCount||0,it=B.cachedContentTokenCount||0,ze=(B.candidatesTokenCount||0)+(B.thoughtsTokenCount||0),gt=V?Ie("nvidia_janitor_fallback"):J==="DeepSeek"?Ie("deepseek_fast_fallback"):J==="OpenRouter"?Ie("janitor_open_router"):u||(se===$e?Ie("janitor_default"):Ie("gemma_janitor_fallback_google"));await Kt("tokens",je,J,gt),it>0&&await Kt("cachedTokens",it,J,gt),ze>0&&await Kt("candidateTokens",ze,J,gt)}}else throw new Error("No synthesis generated by Janitor.");d&&(d(),await Ot("background"));let Ue=Ho(U),Fe=!1;for(let je of Ue){let it=je.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(it)&&(Fe=!0);let ze={chatId:h,sessionId:h,history:o},gt=await fo(it,je.args,ze);it.toLowerCase()==="memory"&&(je.args.includes("action='user'")||je.args.includes('action="user"'))&&!gt.startsWith("ERROR")&&(p&&p(),process.stdout.isTTY&&(process.stdout.write("\x1B]0;Memory Updated\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=Memory Updated\x07")),await new Promise(yt=>setTimeout(yt,3e3)))}if(!Fe)try{let je=Z(Dt,[]);if(je.length>0){let it=[];for(let ze of je)ze.score===void 0&&(ze.score=.5),ze.score*=.99995,ze.score<.05&&(ze.score=0),ze.score=Math.round(ze.score*1e5)/1e5,ze.score>0&&it.push(ze);me(Dt,it)}}catch{}break}catch(A){se++;let B=new Date().toLocaleString(),V=A instanceof Error?(()=>{try{return JSON.parse(JSON.parse(A.message).error.message).error.message}catch{return String(A)}})():String(A);await new Promise(Fe=>setTimeout(Fe,1e3));let J=ee.join(fn,"janitor");if(Pe.existsSync(J)||Pe.mkdirSync(J,{recursive:!0}),Pe.appendFileSync(ee.join(J,"error.log"),`ERROR [Attempt ${se}/${$e+1}] [${B}]: ${V}
529
+ [AGENT (current turn)]: ${I}`;R.push({role:"user",parts:[{text:X}]});let re=await Qo("NVIDIA"),F=(await Ft()).quotas?.providerTiers?.NVIDIA==="Free",U="",se=0,$e=b?12:-1;for(;se<=$e;)try{if(!await Li("background",e))return;let A="",B=null,V=!1,J=m;try{let je=new Promise((ut,Ce)=>setTimeout(()=>Ce(new Error("JANITOR_TIMEOUT")),1e4)),it=m==="Google"&&se>=0&&se<6&&re&&F,ze=m==="DeepSeek"&&se<4&&re&&F;V=it||ze,J=V?"NVIDIA":m;let bt=(async()=>{if(m==="OpenRouter"){let ut=Ie("janitor_open_router"),le=oi(w,ut,R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),Vt=await le.next();return{iterator:le,firstResult:Vt}}else if(m==="DeepSeek"&&!V){let Ce=ti(w,Ie("deepseek_fast_fallback"),R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await Ce.next();return{iterator:Ce,firstResult:le}}else if(m==="Mistral"&&!V){let Ce=ni(w,Ie("mistral_janitor_fallback"),R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await Ce.next();return{iterator:Ce,firstResult:le}}else if(m==="NVIDIA"||V){let Ce=si(V?re:w,Ie("nvidia_janitor_fallback"),R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await Ce.next();return{iterator:Ce,firstResult:le}}else if(m==="CrofAI"){let Ce=ri(w,targetModel||Ie("crofai_fallback")||"deepseek-v4-flash-0731",R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await Ce.next();return{iterator:Ce,firstResult:le}}else if(m==="InferX"){let Ce=ii(w,targetModel||Ie("inferx_fallback")||"deepseek-v4-flash",R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await Ce.next();return{iterator:Ce,firstResult:le}}else if(m==="SenseNova"){let Ce=ai(w,targetModel||Ie("sensenova_fallback")||"sensenova-6.8-flash-lite",R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await Ce.next();return{iterator:Ce,firstResult:le}}else{let le=(await li(w).models.generateContentStream({model:u||(se===$e?Ie("janitor_default"):Ie("gemma_janitor_fallback_google")),contents:R,config:{systemInstruction:C,temperature:.7,safetySettings:[{category:Vn.HARM_CATEGORY_HARASSMENT,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_HATE_SPEECH,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Yn.BLOCK_NONE}],thinkingConfig:{includeThoughts:!1,thinkingLevel:ft.MINIMAL}}}))[Symbol.asyncIterator](),Vt=await le.next();return{iterator:le,firstResult:Vt}}})();if(process.stdout.isTTY){let le=(await as())[h]?.name||"",Vt=le&&!le.startsWith("flow-")&&!le.startsWith("Session ")?le:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${Vt}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${Vt}\x07`)}let{iterator:Bt,firstResult:gt}=await Promise.race([bt,je]),{value:kt,done:Rt}=gt;if(!Rt&&kt){let ut=kt.candidates?.[0]?.content?.parts,Ce=ut?J==="Google"?ut[1]?.text||ut[0]?.text||"":ut.filter(le=>le.text&&!le.thought).map(le=>le.text).join(""):typeof kt.text=="function"?kt.text():"";Ce&&(A+=Ce),B=kt.usageMetadata;for await(let le of{[Symbol.asyncIterator]:()=>Bt}){let Vt=le.candidates?.[0]?.content?.parts,Xn=Vt?J==="Google"?Vt[1]?.text||Vt[0]?.text||"":Vt.filter(Jn=>Jn.text&&!Jn.thought).map(Jn=>Jn.text).join(""):typeof le.text=="function"?le.text():"";Xn&&(A+=Xn),B=le.usageMetadata}}}catch(je){throw je}if(A){if(U=A,B){let je=B.totalTokenCount||0,it=B.cachedContentTokenCount||0,ze=(B.candidatesTokenCount||0)+(B.thoughtsTokenCount||0),bt=V?Ie("nvidia_janitor_fallback"):J==="DeepSeek"?Ie("deepseek_fast_fallback"):J==="OpenRouter"?Ie("janitor_open_router"):u||(se===$e?Ie("janitor_default"):Ie("gemma_janitor_fallback_google"));await Kt("tokens",je,J,bt),it>0&&await Kt("cachedTokens",it,J,bt),ze>0&&await Kt("candidateTokens",ze,J,bt)}}else throw new Error("No synthesis generated by Janitor.");d&&(d(),await Ot("background"));let Ue=Ho(U),Fe=!1;for(let je of Ue){let it=je.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(it)&&(Fe=!0);let ze={chatId:h,sessionId:h,history:o},bt=await fo(it,je.args,ze);it.toLowerCase()==="memory"&&(je.args.includes("action='user'")||je.args.includes('action="user"'))&&!bt.startsWith("ERROR")&&(p&&p(),process.stdout.isTTY&&(process.stdout.write("\x1B]0;Memory Updated\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=Memory Updated\x07")),await new Promise(gt=>setTimeout(gt,3e3)))}if(!Fe)try{let je=Z(Dt,[]);if(je.length>0){let it=[];for(let ze of je)ze.score===void 0&&(ze.score=.5),ze.score*=.99995,ze.score<.05&&(ze.score=0),ze.score=Math.round(ze.score*1e5)/1e5,ze.score>0&&it.push(ze);me(Dt,it)}}catch{}break}catch(A){se++;let B=new Date().toLocaleString(),V=A instanceof Error?(()=>{try{return JSON.parse(JSON.parse(A.message).error.message).error.message}catch{return String(A)}})():String(A);await new Promise(Fe=>setTimeout(Fe,1e3));let J=ee.join(fn,"janitor");if(Pe.existsSync(J)||Pe.mkdirSync(J,{recursive:!0}),Pe.appendFileSync(ee.join(J,"error.log"),`ERROR [Attempt ${se}/${$e+1}] [${B}]: ${V}
530
530
 
531
531
  `),se>$e)break;let Ue=Math.min(750*Math.pow(2,se-1),5e3);await new Promise(Fe=>setTimeout(Fe,Ue))}if(se){let A=ee.join(fn,"janitor");Pe.appendFileSync(ee.join(A,"error.log"),`-----------------------------------------------------------------------------
532
532
 
@@ -569,7 +569,7 @@ ${u}
569
569
 
570
570
  Provide a consolidated summary of the entire session.`,m=Ie("gemma_janitor_fallback_google");s==="OpenRouter"&&(m=Ie("janitor_open_router")),s==="DeepSeek"&&(m=Ie("deepseek_level_1")),s==="Mistral"&&(m=Ie("mistral_level_1")),s==="NVIDIA"&&(m=Ie("nvidia_chat_summarizer_fallback")),s==="CrofAI"&&(m=Ie("crofai_fallback")),s==="InferX"&&(m=Ie("inferx_fallback")),s==="SenseNova"&&(m=Ie("sensenova_fallback"));let w=0,b=!1,T=null;for(;w<=3&&!b;){w++;try{T=await jo(e,m,y,g,"Fast"),b=!0}catch{if(w>3){if(s==="Google")try{let R=Ie("general_fallback");return(await jo(e,R,y,g,"Fast")).text||""}catch{return""}return""}}}return T&&T.text||""},p=a(n),d=Z(r,{}),c=d[o]||{summary:"",historyLength:0};typeof c=="string"&&(c={summary:c,historyLength:0});let l=c.summary||"",f=await i(p,l);if(f){c.summary=f;let u=$c(n);return t?c.historyLength=(c.historyLength||0)+u:c.historyLength=u,d[o]=c,me(r,d),f}return null},Am=e=>{try{let n=ee.join(xo,"chat-summaries.json");if(Pe.existsSync(n)){let t=Z(n,{});t[e]&&(delete t[e],me(n,t))}}catch{}},vm=async function*(e,n,t,o,s){let{profile:r,thinkingLevel:a,mode:i,janitorModel:p,chatId:d,isPlayground:c,systemSettings:l,sessionStats:f,aiProvider:u="Google",apiTier:h,wildcardTooling:g}=t,y=zt(e);if(!ei&&u==="Google")throw new Error("AI not initialized");let m=process.env.NVIDIA_BASE_URL||t?.aiProvider==="Ollama"||t?.aiProvider==="CrofAI"||t?.aiProvider==="InferX"||t?.aiProvider==="SenseNova"?!1:l?.memory!==!1,w=n[n.length-1].text,b=ee.join(xo,"chat-summaries.json"),T=!1,$=n.filter(E=>E.role==="user").length===1,R=w.includes("[TITLE-UPDATE]"),k=$||R,S=w.replace(/\[TITLE-UPDATE\]/g,"").trim();S=S.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),yield{type:"status",content:"[start]"},yield{type:"status",content:"Gathering Context"},await mt.startTransaction(d,S),l?.advanceRollback&&await Kn.takeInitialSnapshot(d),Lt=!1;let _=null;try{let E=new AbortController;_=setInterval(()=>{Lt&&(E.abort(),_&&(clearInterval(_),_=null))},400);let x=[...n.slice(0,-1)];{let Le=Z(b,{})[d]||{summary:"",historyLength:0};if(Le.summary&&Le.historyLength>0){let nn=0,Me=[];for(let Ze=0;Ze<x.length;Ze++){let He=x[Ze];(He.role==="user"||He.role==="agent"||He.role==="system")&&!String(He.id).startsWith("welcome")&&!He.isMeta&&nn++,nn>Le.historyLength&&Me.push(He)}x=Me}}x=x.map(G=>{if(G.role==="user"&&G.text){let Le=G.text.match(/\[USER\]([\s\S]*?)\[\/USER\]/);if(Le)return{...G,text:Le[1].trim()}}return{...G}});let C=process.env.HIGH_CONTEXT,I=255e3,L=26e4;if(C&&C!=="false"){let G=parseInt(C,10);!isNaN(G)&&G>=256e3&&G<=1e6&&(L=G,I=Math.round(G*.85))}if((u==="NVIDIA"&&(e?.includes("gpt")||e?.includes("qwen")||e?.includes("medium")||e.includes("muse"))||u==="Mistral")&&(I=122e3,L=126e3),u!=="Ollama"&&(f?.tokens||0)>I&&(yield{type:"status_history",content:"Context Limit Reached. Condensing session history..."},await Dc(t,x,!0)&&(x=[],T=!0)),$&&m){let G=Z(tn,{});Object.values(G).flat().length>5&&(yield{type:"status",content:"Condensing past chat memories"},await Pc(d,t,G))}let N=Z(tn,{}),W=Z(An,{}),X=Object.entries(N).filter(([G])=>G!==d).flatMap(([G,Le])=>Le),Y=[...Object.entries(W).filter(([G])=>G!==d).slice(-20).map(([G,Le])=>`[Chat Summary]: ${Le}`),...X].map(G=>`- ${G}`).join(`
571
571
  `),U=Z(Dt,[]).map(G=>`- ${G.memory}`).join(`
572
- `),se=(f?.tokens||0)>=1e4,$e=_i(Y,U,m,se),A=new Date,B=A.getFullYear(),V=A.toLocaleString("en-US",{month:"short"}).toUpperCase(),J=String(A.getDate()).padStart(2,"0"),Ue=A.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}),Fe=`${B}-${V}-${J}, ${Ue}`,je=[".git","node_modules",".gemini","dist","build",".next","out",".cache","bin","obj","vendor","venv",".idea",".gradle",".terraform","target","coverage",".vscode",".svn",".hg",".fslckout",".github",".gitlab",".circleci",".gitea",".gitee",".lerna",".changeset",".nx",".npm",".yarn",".pnpm-store",".pnpm",".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",".VSCodeCounter"],it=G=>{try{return Pe.readdirSync(G,{withFileTypes:!0})}catch{return[]}},ze=(G,Le={value:0},nn=1)=>{if(Le.value>6200||nn>7)return Le.value;let Me=it(G);for(let Ze of Me){if(Le.value>6200)break;je.includes(Ze.name)||Ze.name.startsWith(".")||Ze.isDirectory()&&(Le.value++,ze(ee.join(G,Ze.name),Le,nn+1))}return Le.value},gt=(G,Le)=>l?.indentationTree!==!1?Vr(G,Le,1,it,je):Jr(G,Le,"",1,it,je),Bt=ze(process.cwd()),yt=12;Bt>3072?yt=1:Bt>2304?yt=2:Bt>1536?yt=3:Bt>768?yt=4:Bt>384?yt=6:Bt>192?yt=7:Bt>96?yt=8:Bt>48?yt=9:Bt>24&&(yt=10);let wt=Z(Jo,{}),Rt=wt[d],ut=Rt?Rt!==process.cwd():!1;wt[d]=process.cwd(),me(Jo,wt);let Ce=Z(b,{}),le=Ce[d]||{summary:"",historyLength:0};typeof le=="string"&&(le={summary:le,historyLength:0});let Vt=n.filter(G=>(G.role==="user"||G.role==="agent"||G.role==="system")&&!String(G.id).startsWith("welcome")&&!G.isMeta).length;le.historyLength&&Vt<le.historyLength&&(le.summary="",le.historyLength=0,Ce[d]=le,me(b,Ce));let Xn=typeof le=="object"?le.summary||"":le||"",Jn=x.length>0;Jn&&Xn&&x[0]&&(x[0].role==="user"||x[0].role==="system")&&(x[0].text.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")||(x[0].text=`[SYSTEM METADATA]
572
+ `),se=(f?.tokens||0)>=1e4,$e=_i(Y,U,m,se),A=new Date,B=A.getFullYear(),V=A.toLocaleString("en-US",{month:"short"}).toUpperCase(),J=String(A.getDate()).padStart(2,"0"),Ue=A.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}),Fe=`${B}-${V}-${J}, ${Ue}`,je=[".git","node_modules",".gemini","dist","build",".next","out",".cache","bin","obj","vendor","venv",".idea",".gradle",".terraform","target","coverage",".vscode",".svn",".hg",".fslckout",".github",".gitlab",".circleci",".gitea",".gitee",".lerna",".changeset",".nx",".npm",".yarn",".pnpm-store",".pnpm",".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",".VSCodeCounter"],it=G=>{try{return Pe.readdirSync(G,{withFileTypes:!0})}catch{return[]}},ze=(G,Le={value:0},nn=1)=>{if(Le.value>6200||nn>7)return Le.value;let Me=it(G);for(let Ze of Me){if(Le.value>6200)break;je.includes(Ze.name)||Ze.name.startsWith(".")||Ze.isDirectory()&&(Le.value++,ze(ee.join(G,Ze.name),Le,nn+1))}return Le.value},bt=(G,Le)=>l?.indentationTree!==!1?Vr(G,Le,1,it,je):Jr(G,Le,"",1,it,je),Bt=ze(process.cwd()),gt=12;Bt>3072?gt=1:Bt>2304?gt=2:Bt>1536?gt=3:Bt>768?gt=4:Bt>384?gt=6:Bt>192?gt=7:Bt>96?gt=8:Bt>48?gt=9:Bt>24&&(gt=10);let kt=Z(Jo,{}),Rt=kt[d],ut=Rt?Rt!==process.cwd():!1;kt[d]=process.cwd(),me(Jo,kt);let Ce=Z(b,{}),le=Ce[d]||{summary:"",historyLength:0};typeof le=="string"&&(le={summary:le,historyLength:0});let Vt=n.filter(G=>(G.role==="user"||G.role==="agent"||G.role==="system")&&!String(G.id).startsWith("welcome")&&!G.isMeta).length;le.historyLength&&Vt<le.historyLength&&(le.summary="",le.historyLength=0,Ce[d]=le,me(b,Ce));let Xn=typeof le=="object"?le.summary||"":le||"",Jn=x.length>0;Jn&&Xn&&x[0]&&(x[0].role==="user"||x[0].role==="system")&&(x[0].text.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")||(x[0].text=`[SYSTEM METADATA]
573
573
  **CONTEXT SUMMARY OF PREVIOUS TURNS (PRIORITY: DYNAMIC)**
574
574
  ${Xn}
575
575
 
@@ -580,7 +580,7 @@ ${Xn}
580
580
  `:"",di=!!l?.dynamicDirAwareness,Na=`${d}|${u}|${a}|${e}|${r}|${di}`,fi=!di&&ys.key===Na&&ys.value?"":`
581
581
  **Directory Structure**
582
582
  CWD: `+process.cwd()+`${c?" [PLAYGROUND MODE]":""}
583
- `+gt(process.cwd(),yt),St=await ms(),Dn="";if(Uo()&&St.file_focused!=="none"){Dn=`
583
+ `+bt(process.cwd(),gt),St=await ms(),Dn="";if(Uo()&&St.file_focused!=="none"){Dn=`
584
584
  [Additional IDE Context]
585
585
  `;let G=ee.relative(process.cwd(),St.file_focused),Le=(St.opened_editors||[]).map(Me=>{let Ze=ee.relative(process.cwd(),Me);return Ze.startsWith("..")?`[External] ${ee.basename(Me)}`:Ze});if(Dn+=`Focused File: ${G}
586
586
  Cursor Line: ${St.cursor_line}
@@ -593,7 +593,7 @@ Cursor Line: ${St.cursor_line}
593
593
  ... [truncated] ...
594
594
  `+Me.slice(-128)),Dn+=`Current Selection: "${Me}"
595
595
  `}if(St.manual_edits){let Ze=St.manual_edits.split(`
596
- `),He=[],Je=null;for(let z of Ze)z.trim()&&(z.startsWith(" Line ")?Je&&Je.edits.push(z):(Je={path:z.endsWith(":")?z.slice(0,-1):z,edits:[]},He.push(Je)));for(let z of He)z.edits.length>80&&(z.edits=z.edits.slice(-80)),z.originalEditsCount=z.edits.length;let fe=(z,te)=>te.reduce((Ge,cn)=>{let wn=St.file_focused&&(cn.path===St.file_focused||ee.resolve(process.cwd(),cn.path)===ee.resolve(St.file_focused))?Math.ceil(z*1.2):z;return Ge+Math.min(cn.edits.length,wn)},0),Ut=80;if(fe(80,He)>300){let z=!1;for(let te=80;te>=10;te--)if(fe(te,He)<=300){Ut=te,z=!0;break}z||(Ut=10)}let Qe=[...He];if(Ut===10&&fe(10,Qe)>500)for(;Qe.length>0&&fe(10,Qe)>500;){let z=0,te=Qe[0].originalEditsCount;for(let Ge=1;Ge<Qe.length;Ge++)Qe[Ge].originalEditsCount<te&&(te=Qe[Ge].originalEditsCount,z=Ge);Qe.splice(z,1)}for(let z of Qe){let Ge=St.file_focused&&(z.path===St.file_focused||ee.resolve(process.cwd(),z.path)===ee.resolve(St.file_focused))?Math.ceil(Ut*1.2):Ut;z.edits.length>Ge&&(z.edits=z.edits.slice(-Ge))}for(let z of Qe){let te=`${z.path}:
596
+ `),He=[],Je=null;for(let z of Ze)z.trim()&&(z.startsWith(" Line ")?Je&&Je.edits.push(z):(Je={path:z.endsWith(":")?z.slice(0,-1):z,edits:[]},He.push(Je)));for(let z of He)z.edits.length>80&&(z.edits=z.edits.slice(-80)),z.originalEditsCount=z.edits.length;let ce=(z,te)=>te.reduce((Ge,cn)=>{let wn=St.file_focused&&(cn.path===St.file_focused||ee.resolve(process.cwd(),cn.path)===ee.resolve(St.file_focused))?Math.ceil(z*1.2):z;return Ge+Math.min(cn.edits.length,wn)},0),Ut=80;if(ce(80,He)>300){let z=!1;for(let te=80;te>=10;te--)if(ce(te,He)<=300){Ut=te,z=!0;break}z||(Ut=10)}let Qe=[...He];if(Ut===10&&ce(10,Qe)>500)for(;Qe.length>0&&ce(10,Qe)>500;){let z=0,te=Qe[0].originalEditsCount;for(let Ge=1;Ge<Qe.length;Ge++)Qe[Ge].originalEditsCount<te&&(te=Qe[Ge].originalEditsCount,z=Ge);Qe.splice(z,1)}for(let z of Qe){let Ge=St.file_focused&&(z.path===St.file_focused||ee.resolve(process.cwd(),z.path)===ee.resolve(St.file_focused))?Math.ceil(Ut*1.2):Ut;z.edits.length>Ge&&(z.edits=z.edits.slice(-Ge))}for(let z of Qe){let te=`${z.path}:
597
597
  ${z.edits.join(`
598
598
  `)}`;for(;z.edits.length>0&&te.length>4*768;)z.edits.shift(),te=`${z.path}:
599
599
  ${z.edits.join(`
@@ -609,10 +609,10 @@ ${St.diagnostics}
609
609
  `),(S.toLowerCase().includes("lint")||S.toLowerCase().includes("warning"))&&St.warnings&&(Dn+=`
610
610
  **Lint Warnings**:
611
611
  ${St.warnings}
612
- `)}let ui=S.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),hi=/(?:\\)?@\[([^\]]+)\]/g,Go,qo=[];for(hi.lastIndex=0;(Go=hi.exec(ui))!==null;){let G=Go[0].startsWith("\\");qo.push({tag:Go[1],isEscaped:G})}let zo=[],po=null;for(let G=0;G<qo.length;G++){let{tag:Le,isEscaped:nn}=qo[G];if(!nn)try{let Me=Le.trim().replace(/^["']|["']$/g,""),Ze=/[:#]L?(\d+)(?:-L?(\d+))?$/i,He=Me.match(Ze),Je=Me,fe=null,Ut=null;He&&(fe=parseInt(He[1],10),Ut=He[2]?parseInt(He[2],10):fe,Je=Me.slice(0,He.index));let Qe=ee.resolve(process.cwd(),Je);if(Pe.existsSync(Qe)&&Pe.statSync(Qe).isFile()){let z=Je.toLowerCase(),te=z.endsWith(".pdf"),Ge=z.endsWith(".docx")||z.endsWith(".doc")||z.endsWith(".ppt")||z.endsWith(".pptx")||z.endsWith(".xls")||z.endsWith(".xlsx"),cn=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(z),Wt=cn||te||Ge,wn=u==="Google"||zt(e);if(Wt&&!wn){let We=`\u2718 Unsupported Modality: ${ee.basename(Je)}`,Te=115;process.stdout.isTTY&&(Te=process.stdout.columns-5||120);let nt=[We],Fn=Math.max(...nt.map(En=>En.length)),Nn=Math.min(Fn+4,Te),es=nt.map(En=>`${En.padEnd(Nn-2).substring(0,Nn-2)}`).join(`
612
+ `)}let ui=S.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),hi=/(?:\\)?@\[([^\]]+)\]/g,Go,qo=[];for(hi.lastIndex=0;(Go=hi.exec(ui))!==null;){let G=Go[0].startsWith("\\");qo.push({tag:Go[1],isEscaped:G})}let zo=[],po=null;for(let G=0;G<qo.length;G++){let{tag:Le,isEscaped:nn}=qo[G];if(!nn)try{let Me=Le.trim().replace(/^["']|["']$/g,""),Ze=/[:#]L?(\d+)(?:-L?(\d+))?$/i,He=Me.match(Ze),Je=Me,ce=null,Ut=null;He&&(ce=parseInt(He[1],10),Ut=He[2]?parseInt(He[2],10):ce,Je=Me.slice(0,He.index));let Qe=ee.resolve(process.cwd(),Je);if(Pe.existsSync(Qe)&&Pe.statSync(Qe).isFile()){let z=Je.toLowerCase(),te=z.endsWith(".pdf"),Ge=z.endsWith(".docx")||z.endsWith(".doc")||z.endsWith(".ppt")||z.endsWith(".pptx")||z.endsWith(".xls")||z.endsWith(".xlsx"),cn=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(z),Wt=cn||te||Ge,wn=u==="Google"||zt(e);if(Wt&&!wn){let We=`\u2718 Unsupported Modality: ${ee.basename(Je)}`,Re=115;process.stdout.isTTY&&(Re=process.stdout.columns-5||120);let nt=[We],Fn=Math.max(...nt.map(En=>En.length)),Nn=Math.min(Fn+4,Re),es=nt.map(En=>`${En.padEnd(Nn-2).substring(0,Nn-2)}`).join(`
613
613
  `);yield{type:"visual_feedback",content:gn(`${es}
614
- `)};continue}if(fe===null&&!Wt){let We=0;try{We=Pe.readFileSync(Qe,"utf8").split(/\r\n|\r|\n/).length}catch{}if(We>300){let Te=`\u21B7 Skipped (Too Large): ${ee.basename(Je)}`,nt=115;process.stdout.isTTY&&(nt=process.stdout.columns-5||120);let Fn=Math.min(Te.length+4,nt),Nn=Te.padEnd(Fn-2).substring(0,Fn-2);yield{type:"visual_feedback",content:gn(`${Nn}
615
- `)};continue}}let Rn=fe!==null?fe:1,Qn=Ut!==null?Ut:fe!==null?fe:Rn+299;Qn-Rn>300&&(Qn=Rn+300);let go=`path=${JSON.stringify(Je)}, startLine=${Rn}, endLine=${Qn}`,tt=await Qs(go,{isMultiModal:wn}),Ke=!1,jt="",Zn=null;if(typeof tt=="string"?tt.trim().startsWith("ERROR")?Ke=!0:jt=tt:tt&&typeof tt=="object"&&tt.binaryPart?(Zn=tt.binaryPart,jt=tt.text||""):Ke=!0,!Ke){let We="";if(cn?(We=`\u2714 Processed: ${ee.basename(Je)}`,po=Zn):te||Ge?(We=`\u2714 Auto-Analysed: ${ee.basename(Je)}`,po=Zn):(We=`\u2714 Auto-Read: ${ee.basename(Je)}`,zo.push(jt)),We){let Te=115;process.stdout.isTTY&&(Te=process.stdout.columns-5||120);let nt=[We],Fn=Math.max(...nt.map(En=>En.length)),Nn=Math.min(Fn+4,Te),es=nt.map(En=>`${En.padEnd(Nn-2).substring(0,Nn-2)}`).join(`
614
+ `)};continue}if(ce===null&&!Wt){let We=0;try{We=Pe.readFileSync(Qe,"utf8").split(/\r\n|\r|\n/).length}catch{}if(We>300){let Re=`\u21B7 Skipped (Too Large): ${ee.basename(Je)}`,nt=115;process.stdout.isTTY&&(nt=process.stdout.columns-5||120);let Fn=Math.min(Re.length+4,nt),Nn=Re.padEnd(Fn-2).substring(0,Fn-2);yield{type:"visual_feedback",content:gn(`${Nn}
615
+ `)};continue}}let Rn=ce!==null?ce:1,Qn=Ut!==null?Ut:ce!==null?ce:Rn+299;Qn-Rn>300&&(Qn=Rn+300);let go=`path=${JSON.stringify(Je)}, startLine=${Rn}, endLine=${Qn}`,tt=await Qs(go,{isMultiModal:wn}),Ke=!1,jt="",Zn=null;if(typeof tt=="string"?tt.trim().startsWith("ERROR")?Ke=!0:jt=tt:tt&&typeof tt=="object"&&tt.binaryPart?(Zn=tt.binaryPart,jt=tt.text||""):Ke=!0,!Ke){let We="";if(cn?(We=`\u2714 Processed: ${ee.basename(Je)}`,po=Zn):te||Ge?(We=`\u2714 Auto-Analysed: ${ee.basename(Je)}`,po=Zn):(We=`\u2714 Auto-Read: ${ee.basename(Je)}`,zo.push(jt)),We){let Re=115;process.stdout.isTTY&&(Re=process.stdout.columns-5||120);let nt=[We],Fn=Math.max(...nt.map(En=>En.length)),Nn=Math.min(Fn+4,Re),es=nt.map(En=>`${En.padEnd(Nn-2).substring(0,Nn-2)}`).join(`
616
616
  `);yield{type:"visual_feedback",content:gn(`${es}
617
617
  `)}}}}}catch{}}let pi="";zo.length>0&&(pi=`[Tagged File Contents] Auto Read User Tagged files by System, No need to re-read
618
618
  `+zo.join(`
@@ -628,45 +628,45 @@ WARNING: CWD Changed from previous: "${Rt}" to current: "${process.cwd()}", writ
628
628
  [/Metadata]
629
629
  ${ci}${a!=="Fast"&&(u==="Mistral"&&!qs(e)||a!=="xHigh"&&u==="Google")?`${u==="Mistral"&&!qs(e)||e.toLowerCase().startsWith("gemma")||Wa?`[system] strictly follow thinking policy as high priority. do not start a response without <think>...</think> [/system]
630
630
  `:""}`:""}[system] exact tool string [tool:functions.ToolName(arg="value")] in chat [/system]
631
- ${pi}${Ua}[user prompt] ${Ba.trim()} [/user prompt]`.trim(),gi={role:"user",text:mi};po&&(gi.binaryPart=po),x.forEach(G=>{G.text&&G.role==="agent"&&(G.text=G.text.replace(/(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])/gi,""),G.text=G.text.replace(/(?:<(think|thought)>|\[(think|thought)\])[^\[\n]*/gi,"").trim())}),x.push(gi),ci&&n[n.length-1]?.id&&(yield{type:"summary_injected",content:{id:n[n.length-1].id,text:mi}});let Tn=null,Bs=i==="Flux"?100:10;Bs=i.toLowerCase().includes("cu")?250:Bs;let yn=16;yield{type:"status",content:"Connecting"},Lt=!1;let yi=[],mo=!1;for(let G=0;G<=Bs;G++){let Le=await ar("agent",t);if(!Le.allowed)throw new Error(Le.reason||`Budget Exhausted for Provider (${u||"Agent"})`);let nn=[];if(mo=!1,i==="ICU"||i==="FluxCU")try{yield{type:"status",content:"Capturing Screen"},await new Promise(Re=>setTimeout(Re,1e3));let he=await xi();if(he&&he.base64){let Re="[system] Fresh Gridded Screen Feedback Captured. Use numeric coordinates. Old screenshots will be removed when new screenshot is captured, summarize in text if context is needed later [/system]",ie={inlineData:{mimeType:he.mimeType,data:he.base64}};for(let st of x)Array.isArray(st.parts)&&(st.parts=st.parts.filter(Mt=>!Mt.inlineData));if(x.length>0&&x[x.length-1].role==="user"){let st=x[x.length-1];typeof st.text=="string"&&(st.text+=`
631
+ ${pi}${Ua}[user prompt] ${Ba.trim()} [/user prompt]`.trim(),gi={role:"user",text:mi};po&&(gi.binaryPart=po),x.forEach(G=>{G.text&&G.role==="agent"&&(G.text=G.text.replace(/(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])/gi,""),G.text=G.text.replace(/(?:<(think|thought)>|\[(think|thought)\])[^\[\n]*/gi,"").trim())}),x.push(gi),ci&&n[n.length-1]?.id&&(yield{type:"summary_injected",content:{id:n[n.length-1].id,text:mi}});let Tn=null,Bs=i==="Flux"?100:10;Bs=i.toLowerCase().includes("cu")?250:Bs;let yn=16;yield{type:"status",content:"Connecting"},Lt=!1;let yi=[],mo=!1;for(let G=0;G<=Bs;G++){let Le=await ar("agent",t);if(!Le.allowed)throw new Error(Le.reason||`Budget Exhausted for Provider (${u||"Agent"})`);let nn=[];if(mo=!1,i==="ICU"||i==="FluxCU")try{yield{type:"status",content:"Capturing Screen"},await new Promise(we=>setTimeout(we,1e3));let ue=await xi();if(ue&&ue.base64){let we="[system] Fresh Gridded Screen Feedback Captured. Use numeric coordinates. Old screenshots will be removed when new screenshot is captured, summarize in text if context is needed later [/system]",ie={inlineData:{mimeType:ue.mimeType,data:ue.base64}};for(let st of x)Array.isArray(st.parts)&&(st.parts=st.parts.filter(Mt=>!Mt.inlineData));if(x.length>0&&x[x.length-1].role==="user"){let st=x[x.length-1];typeof st.text=="string"&&(st.text+=`
632
632
 
633
- ${Re}`,Array.isArray(st.parts)||(st.parts=[{text:st.text}]),st.parts.push(ie))}else x.push({role:"user",text:Re,parts:[{text:Re},ie]})}}catch(he){console.error("Vision screenshot capture error:",he)}if(l?.compression===0&&(f?.tokens||0)>L&&(x=vi(x,6)),G>0?yield{type:"status",content:"Working"}:yield{type:"status",content:"Connecting"},Lt){try{let{clearPendingNudges:he}=await import("./subagent_state-LZCOZSUJ.js");he()}catch{}yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
633
+ ${we}`,Array.isArray(st.parts)||(st.parts=[{text:st.text}]),st.parts.push(ie))}else x.push({role:"user",text:we,parts:[{text:we},ie]})}}catch(ue){console.error("Vision screenshot capture error:",ue)}if(l?.compression===0&&(f?.tokens||0)>L&&(x=vi(x,6)),G>0?yield{type:"status",content:"Working"}:yield{type:"status",content:"Connecting"},Lt){try{let{clearPendingNudges:ue}=await import("./subagent_state-LZCOZSUJ.js");ue()}catch{}yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
634
634
 
635
- \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}try{let{consumePendingNudges:he}=await import("./subagent_state-LZCOZSUJ.js"),Re=he();if(Re&&Re.length>0){let ie=Re.join(`
635
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}try{let{consumePendingNudges:ue}=await import("./subagent_state-LZCOZSUJ.js"),we=ue();if(we&&we.length>0){let ie=we.join(`
636
636
 
637
637
  `);x.length>0&&x[x.length-1].role==="user"?x[x.length-1].text+=`
638
638
 
639
- ${ie}`:x.push({role:"user",text:ie}),yield{type:"status",content:"Subagent Update"}}}catch{}if(o){let he=await o();he&&(he.startsWith("/btw")?x.length>0&&x[x.length-1].role==="user"?x[x.length-1].text+=`
639
+ ${ie}`:x.push({role:"user",text:ie}),yield{type:"status",content:"Subagent Update"}}}catch{}if(o){let ue=await o();ue&&(ue.startsWith("/btw")?x.length>0&&x[x.length-1].role==="user"?x[x.length-1].text+=`
640
640
 
641
- [system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/SYSTEM]
642
- [question] ${he.replace("/btw","").trim()} [/question]`:x.push({role:"user",text:`[system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
643
- [question] ${he.replace("/btw","").trim()} [/question]`}):x.length>0&&x[x.length-1].role==="user"?x[x.length-1].text+=`
641
+ [system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
642
+ [question] ${ue.replace("/btw","").trim()} [/question]`:x.push({role:"user",text:`[system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
643
+ [question] ${ue.replace("/btw","").trim()} [/question]`}):x.length>0&&x[x.length-1].role==="user"?x[x.length-1].text+=`
644
644
 
645
- [STEERING HINT from USER, HIGH PRIORITY] ${he.trim().toUpperCase()} [/STEERING HINT]`:x.push({role:"user",text:`[STEERING HINT from USER, HIGH PRIORITY] ${he.trim().toUpperCase()} [/STEERING HINT]`}),yield{type:"status",content:`${he.startsWith("/btw")?"Question Forwarded...":"Steering Hint Injected..."}`})}let Me,Ze=!1,He=1,Je=1,fe="",Ut=null,Qe=null,sn=null,z=0,te=[],Ge=0,cn=!1,Wt=!1,wn=!1,Rn=!1,Qn=!0,go=0,tt="",Ke="",jt=!1,Zn=!1,We=!0,Te=e,nt="";for(;He<=yn&&Je<=yn&&!Ze&&!Lt;){let he=!1;try{fe="",Qn&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},Qn=!1,Je===1&&(tt=""));let Re=D=>{if(!D||!D.includes("[tool:"))return D;let oe="___THINK_OPEN_TAG___",j="___THINK_CLOSE_TAG___";D=D.replace("<think>",oe).replace("</think>",j),D=D.replace(Ec,(ge,Ee)=>Ee.includes("[tool:")?Ee.trim():ge);let H="",we=0;for(;we<D.length;){let ge=D.indexOf("[tool:",we);if(ge===-1){H+=D.substring(we).replace(Ma,"").replace(Aa,"");break}let Ee=D.substring(we,ge);H+=Ee.replace(Ma,"").replace(Aa,"");let ot=D.indexOf("]",ge);if(ot===-1){H+=D.substring(ge);break}H+=D.substring(ge,ot+1),we=ot+1}return D=H,D=D.replaceAll(oe,"<think>").replaceAll(j,"</think>"),D},ie=x.filter(D=>(D.role==="user"||D.role==="agent"||D.role==="system")&&!String(D.id).startsWith("welcome")&&!D.isMeta&&!D.isTerminalRecord&&!(D.text&&D.text.startsWith("[TERMINAL_RECORD]"))).map((D,oe,j)=>{let H=D.text||"";m||(H=H.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),D.role==="agent"&&(H=Re(H),H=H.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),H=H.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*"));let we=[];return Array.isArray(D.parts)&&D.parts.length>0?we=D.parts.map(ge=>{if(ge.text){let Ee=ge.text;return m||(Ee=Ee.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),D.role==="agent"&&(Ee=Re(Ee),Ee=Ee.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),Ee=Ee.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*")),{text:Ee}}return ge}):we=[{text:H}],D.binaryPart&&zt(Te)&&j.slice(oe+1).filter(Ee=>Ee.role==="user"&&!Ee.text?.startsWith("[TOOL RESULT]")).length<=2&&we.push(D.binaryPart),{role:D.role==="user"||D.role==="system"?"user":"model",parts:we}});for(let D=0;D<ie.length;D++){let oe=ie[D],j=oe.parts?.[0]?.text||"";if(oe.role==="model"&&/\[tool:/i.test(j)){let H=-1;for(let we=D+1;we<ie.length;we++){let ge=ie[we],Ee=ge.parts?.[0]?.text||"";if(ge.role==="user"&&Ee.startsWith("[TOOL RESULT]")){H=we;break}}if(H!==-1&&H!==D+1){let[we]=ie.splice(H,1);ie.splice(D+1,0,we)}}}for(let D=ie.length-2;D>=0;D--){let oe=ie[D],j=ie[D+1];oe.role==="user"&&j.role==="user"&&(j.parts?.[0]?.text||"").trim().startsWith("[SYSTEM")&&ie.splice(D,1)}let st=[];for(let D=0;D<ie.length;D++){let oe=ie[D];if(st.length===0)st.push(oe);else{let j=st[st.length-1];j.role===oe.role?(j.parts[0].text+=`
645
+ [STEERING HINT from USER, HIGH PRIORITY] ${ue.trim().toUpperCase()} [/STEERING HINT]`:x.push({role:"user",text:`[STEERING HINT from USER, HIGH PRIORITY] ${ue.trim().toUpperCase()} [/STEERING HINT]`}),yield{type:"status",content:`${ue.startsWith("/btw")?"Question Forwarded...":"Steering Hint Injected..."}`})}let Me,Ze=!1,He=1,Je=1,ce="",Ut=null,Qe=null,sn=null,z=0,te=[],Ge=0,cn=!1,Wt=!1,wn=!1,Rn=!1,Qn=!0,go=0,tt="",Ke="",jt=!1,Zn=!1,We=!0,Re=e,nt="";for(;He<=yn&&Je<=yn&&!Ze&&!Lt;){let ue=!1;try{ce="",Qn&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},Qn=!1,Je===1&&(tt=""));let we=D=>{if(!D||!D.includes("[tool:"))return D;let oe="___THINK_OPEN_TAG___",j="___THINK_CLOSE_TAG___";D=D.replace("<think>",oe).replace("</think>",j),D=D.replace(Ec,(ge,Ee)=>Ee.includes("[tool:")?Ee.trim():ge);let H="",xe=0;for(;xe<D.length;){let ge=D.indexOf("[tool:",xe);if(ge===-1){H+=D.substring(xe).replace(Ma,"").replace(Aa,"");break}let Ee=D.substring(xe,ge);H+=Ee.replace(Ma,"").replace(Aa,"");let ot=D.indexOf("]",ge);if(ot===-1){H+=D.substring(ge);break}H+=D.substring(ge,ot+1),xe=ot+1}return D=H,D=D.replaceAll(oe,"<think>").replaceAll(j,"</think>"),D},ie=x.filter(D=>(D.role==="user"||D.role==="agent"||D.role==="system")&&!String(D.id).startsWith("welcome")&&!D.isMeta&&!D.isTerminalRecord&&!(D.text&&D.text.startsWith("[TERMINAL_RECORD]"))).map((D,oe,j)=>{let H=D.text||"";m||(H=H.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),D.role==="agent"&&(H=we(H),H=H.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),H=H.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*"));let xe=[];return Array.isArray(D.parts)&&D.parts.length>0?xe=D.parts.map(ge=>{if(ge.text){let Ee=ge.text;return m||(Ee=Ee.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),D.role==="agent"&&(Ee=we(Ee),Ee=Ee.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),Ee=Ee.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*")),{text:Ee}}return ge}):xe=[{text:H}],D.binaryPart&&zt(Re)&&j.slice(oe+1).filter(Ee=>Ee.role==="user"&&!Ee.text?.startsWith("[TOOL RESULT]")).length<=2&&xe.push(D.binaryPart),{role:D.role==="user"||D.role==="system"?"user":"model",parts:xe}});for(let D=0;D<ie.length;D++){let oe=ie[D],j=oe.parts?.[0]?.text||"";if(oe.role==="model"&&/\[tool:/i.test(j)){let H=-1;for(let xe=D+1;xe<ie.length;xe++){let ge=ie[xe],Ee=ge.parts?.[0]?.text||"";if(ge.role==="user"&&Ee.startsWith("[TOOL RESULT]")){H=xe;break}}if(H!==-1&&H!==D+1){let[xe]=ie.splice(H,1);ie.splice(D+1,0,xe)}}}for(let D=ie.length-2;D>=0;D--){let oe=ie[D],j=ie[D+1];oe.role==="user"&&j.role==="user"&&(j.parts?.[0]?.text||"").trim().startsWith("[SYSTEM")&&ie.splice(D,1)}let st=[];for(let D=0;D<ie.length;D++){let oe=ie[D];if(st.length===0)st.push(oe);else{let j=st[st.length-1];j.role===oe.role?(j.parts[0].text+=`
646
646
 
647
- `+(oe.parts?.[0]?.text||""),oe.parts?.length>1&&j.parts.push(...oe.parts.slice(1))):st.push(oe)}}ie.length=0,ie.push(...st),Te=e;let Mt=`${d}|${u}|${i}|${a}|${Te}|${JSON.stringify(r)}|${!!l?.dynamicDirAwareness}|${!!l?.subAgents}`;if(ys.key===Mt&&ys.value)nt=ys.value;else{let D=u==="Mistral"?!!qs(Te):!(Te||"gemma").toLowerCase().startsWith("gemma");nt=$i(r,((Te||"gemma").toLowerCase().startsWith("gemma"),a),i,l,m,$,u,u==="Google"?!0:y,D,d),l?.dynamicDirAwareness||(nt+=`
647
+ `+(oe.parts?.[0]?.text||""),oe.parts?.length>1&&j.parts.push(...oe.parts.slice(1))):st.push(oe)}}ie.length=0,ie.push(...st),Re=e;let Mt=`${d}|${u}|${i}|${a}|${Re}|${JSON.stringify(r)}|${!!l?.dynamicDirAwareness}|${!!l?.subAgents}`;if(ys.key===Mt&&ys.value)nt=ys.value;else{let D=u==="Mistral"?!!qs(Re):!(Re||"gemma").toLowerCase().startsWith("gemma");nt=$i(r,((Re||"gemma").toLowerCase().startsWith("gemma"),a),i,l,m,$,u,u==="Google"?!0:y,D,d),l?.dynamicDirAwareness||(nt+=`
648
648
  ${fi.replace(`
649
649
  **Directory Structure**`,`
650
650
  **Directory Structure**`)}`),ys.key=Mt,ys.value=nt}let Et=ie[ie.length-1];if(Uo()&G>0){await new Promise(j=>setTimeout(j,2500)),yield{type:"status",content:"Verifying"};let D=await ms(),oe=D?D.diagnostics:null;oe&&Et&&Et.role==="user"&&Et.parts?.[0]?.text&&(Et.parts[0].text+=`
651
651
  ${oe} [/ERROR]`),yield{type:"status",content:"Working"}}if(u==="Mistral"||u==="Google"&&e?.toLowerCase().startsWith("gemma")){let oe=a!=="Fast"&&(u==="Mistral"||a!=="xHigh")?". **strictly maintain thinking policy. do not start a response without <think>...</think>**":"",j=`
652
- [SYSTEM] Tool result received. Analyze output and proceed with your turn [/SYSTEM]`;Et&&Et.role==="user"&&Et.parts?.[0]?.text?.startsWith("[TOOL RESULT]")&&(Et.parts[0].text+=j)}if(l?.advanceRollback&&Et&&Et.role==="user"&&Et.parts?.[0]?.text?.startsWith("[TOOL RESULT]"))try{let D=await Kn.getLatestFileChanges(d);if(D&&(D.newFiles.length>0||D.modifiedFiles.length>0||D.deletedFiles.length>0)){let oe=`
652
+ [system] Tool result received. Analyze output and proceed with your turn [/system]`;Et&&Et.role==="user"&&Et.parts?.[0]?.text?.startsWith("[TOOL RESULT]")&&(Et.parts[0].text+=j)}if(l?.advanceRollback&&Et&&Et.role==="user"&&Et.parts?.[0]?.text?.startsWith("[TOOL RESULT]"))try{let D=await Kn.getLatestFileChanges(d);if(D&&(D.newFiles.length>0||D.modifiedFiles.length>0||D.deletedFiles.length>0)){let oe=`
653
653
  [system] File Changes:
654
654
  `;for(let H of D.newFiles)oe+=`* ${H} (created)
655
655
  `;for(let H of D.modifiedFiles)oe+=`* ${H} (modified)
656
656
  `;for(let H of D.deletedFiles)oe+=`* ${H} (deleted)
657
657
  `;oe+="[/system]",Et.parts[0].text+=oe;let j=-1;for(let H=x.length-1;H>=0;H--)if(x[H].role==="user"&&x[H].text?.startsWith("[TOOL RESULT]")){j=H;break}j!==-1&&(x[j].text+=oe)}}catch{}let Bn=Math.floor(Bs*(i==="Flux"?.98:.8)),Xt=G+1;Xt>=Bn&&Et&&Et.parts?.[0]&&(Et.parts[0].text+=`
658
- [system] WARNING, Turn Limit Impending: Step ${Xt}/${Bs}. Wrap up quickly/prompt user to continue. [/system]`);let At=new Promise((D,oe)=>{E.signal.aborted&&oe(new DOMException("The user aborted a request.","AbortError")),E.signal.addEventListener("abort",()=>{oe(new DOMException("The user aborted a request.","AbortError"))})});At.catch(()=>{});let at=ie;if(u==="Ollama")Me=Da(t.apiKey,Te,at,nt,a,i,y,E.signal,1,l?.ollamaEndpoint||"Cloud");else if(u==="OpenRouter")Me=oi(t.apiKey,Te,at,nt,a,i,y,E.signal,1,d);else if(u==="DeepSeek")Me=ti(t.apiKey,Te,at,nt,a,i,y,E.signal,1);else if(u==="Mistral")Me=ni(t.apiKey,Te,at,nt,a,i,y,E.signal,1,d);else if(u==="NVIDIA"){let D=si(t.apiKey,Te,at,nt,a,i,y,E.signal,1);Me=Mc(D,Te)}else if(u==="CrofAI")Me=ri(t.apiKey,Te,at,nt,a,i,y,E.signal,1);else if(u==="InferX")Me=ii(t.apiKey,Te,at,nt,a,i,y,E.signal,1);else if(u==="SenseNova")Me=ai(t.apiKey,Te,at,nt,a,i,y,E.signal,1);else{let oe=li(t?.apiKey).models.generateContentStream({model:Te||"gemini-3-flash-preview",contents:at,config:{systemInstruction:nt,mediaResolution:"MEDIA_RESOLUTION_HIGH",safetySettings:[{category:Vn.HARM_CATEGORY_HARASSMENT,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_HATE_SPEECH,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Yn.BLOCK_NONE}],temperature:1.05,thinkingConfig:(()=>{let j=(Te||"").toLowerCase(),H=j.includes("gemma-4")||j.startsWith("gemma"),we=j.includes("gemini-3");if(H||we)return H?a.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:ft.MINIMAL}:{includeThoughts:!0,thinkingLevel:ft.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:j.includes("pro")?ft.LOW:ft.MINIMAL,Low:ft.LOW,Medium:ft.MEDIUM,Standard:ft.MEDIUM,High:ft.HIGH,xHigh:ft.HIGH}[a]||ft.MEDIUM};{let ge={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[a]||2048;return ge===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:ge}}})()}},{signal:E.signal});Me=await Promise.race([oe,At])}fe="",Ut=null,sn=null,te=[],Ge=0,yield{type:"model_update",content:null},Ke="",jt=tt.length>0;let Pt="",Ko=Date.now(),ns=async function*(){if(u==="Google"&&Pt){let D=Us(Pt);for(let oe of D)yield oe;Pt="",Ko=Date.now()}},wi=!0,ss="",bs=!1,Ht=null,qa={tool:{startPrefix:"[tool",fullPrefix:"[tool:functions.",endTag:"]"},agent:{startPrefix:"[agent",fullPrefix:"[agent:generalist.",endTag:"]"},end:{startPrefix:"[[END]]",fullPrefix:"[[END]]",endTag:"[[END]]"},kimi_section:{startPrefix:"<|tool_calls_section_begin|>",fullPrefix:"<|tool_calls_section_begin|>",endTag:"<|tool_calls_section_end|>"},kimi_call:{startPrefix:"<|tool_call_begin|>",fullPrefix:"<|tool_call_begin|>",endTag:"<|tool_call_end|>"}},Us=D=>{let oe=[],j=D;for(;j.length>0;)if(bs){let H=ss+j,we=qa[Ht];if(we){let ot=!1;if(H.length<we.startPrefix.length?we.startPrefix.startsWith(H)||(ot=!0):H.startsWith(we.startPrefix)?H.length>=we.fullPrefix.length&&!H.startsWith(we.fullPrefix)&&(ot=!0):ot=!0,ot){oe.push({type:"text",content:H}),ss="",bs=!1,Ht=null,j="";break}}let ge=-1,Ee=we?we.endTag:"]";if(Ht==="tool"||Ht==="agent"){let ot=0,q=null,pe=0,rt=!1;for(let M=0;M<H.length;M++){let Ye=H[M];if(q){if(Ye===q){let Ne=0;for(let Q=M-1;Q>=0&&H[Q]==="\\";Q--)Ne++;Ne%2===0&&(q=null)}}else if(Ye==='"'||Ye==="'"||Ye==="`")q=Ye;else if(Ye==="(")ot++,rt=!0;else if(Ye===")")ot--;else if(Ye==="[")pe++;else if(Ye==="]"){if(rt&&ot===0&&pe===1){ge=M;break}pe--}}}else ge=H.indexOf(Ee);if(ge!==-1){let ot=Ee.length;if(!Ht?.startsWith("kimi")){let q=H.substring(0,ge+ot);oe.push({type:"text",content:q})}ss="",bs=!1,Ht=null,j=H.substring(ge+ot)}else{let ot=Ht?.startsWith("kimi")?8192:512;H.length>ot?(oe.push({type:"text",content:H}),ss="",bs=!1,Ht=null):ss=H,j="";break}}else{let H=j.indexOf("[tool"),we=j.indexOf("[agent"),ge=j.indexOf("[[END]]"),Ee=j.indexOf("<|tool_calls_section_begin|>"),ot=j.indexOf("<|tool_call_begin|>"),q=[{type:"tool",idx:H,start:"[tool",end:"]"},{type:"agent",idx:we,start:"[agent",end:"]"},{type:"end",idx:ge,start:"[[END]]",end:"[[END]]"},{type:"kimi_section",idx:Ee,start:"<|tool_calls_section_begin|>",end:"<|tool_calls_section_end|>"},{type:"kimi_call",idx:ot,start:"<|tool_call_begin|>",end:"<|tool_call_end|>"}].filter(pe=>pe.idx!==-1).sort((pe,rt)=>pe.idx-rt.idx);if(q.length>0){let pe=q[0];pe.idx>0&&oe.push({type:"text",content:j.substring(0,pe.idx)}),bs=!0,Ht=pe.type,ss="",j=j.substring(pe.idx)}else{let pe=["[tool","[agent","[[END]]","<|tool_calls_section_begin|>","<|tool_call_begin|>"],rt=-1;for(let M of pe){for(let Ye=M.length-1;Ye>0;Ye--)if(j.endsWith(M.substring(0,Ye))){rt=j.length-Ye;let Ne=pe.indexOf(M);Ne===0?Ht="tool":Ne===1?Ht="agent":Ne===2?Ht="end":Ne===3?Ht="kimi_section":Ht="kimi_call";break}if(rt!==-1)break}if(rt!==-1)rt>0&&oe.push({type:"text",content:j.substring(0,rt)}),bs=!0,ss=j.substring(rt),j="";else{oe.push({type:"text",content:j});break}}}return oe},za=Me[Symbol.asyncIterator]();for(;;){let{value:D,done:oe}=await Promise.race([za.next(),At]);if(oe)break;if(D&&D.type==="status"){yield D;continue}let j="",H=D.candidates?.[0]?.content?.parts;if(H&&H.length>0)for(let ge of H){let Ee=typeof ge.text=="string"?ge.text:ge.text?parseChunkText(ge.text):"";ge.thought?Ee&&(he||(j+="<think>",he=!0),j+=Ee):Ee&&(he&&(j+="</think>",he=!1),j+=Ee)}else D.text&&he&&(j+="</think>",he=!1);j=Pn(j);let we=j?j.trim().split(/\s+/).filter(Boolean).length:0;if(t&&typeof t.onTokenChunk=="function"&&t.onTokenChunk(j,we),wi&&(yield{type:"status",content:"Thinking"},wi=!1),Lt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
658
+ [system] WARNING, Turn Limit Impending: Step ${Xt}/${Bs}. Wrap up quickly/prompt user to continue. [/system]`);let At=new Promise((D,oe)=>{E.signal.aborted&&oe(new DOMException("The user aborted a request.","AbortError")),E.signal.addEventListener("abort",()=>{oe(new DOMException("The user aborted a request.","AbortError"))})});At.catch(()=>{});let at=ie;if(u==="Ollama")Me=Da(t.apiKey,Re,at,nt,a,i,y,E.signal,1,l?.ollamaEndpoint||"Cloud");else if(u==="OpenRouter")Me=oi(t.apiKey,Re,at,nt,a,i,y,E.signal,1,d);else if(u==="DeepSeek")Me=ti(t.apiKey,Re,at,nt,a,i,y,E.signal,1);else if(u==="Mistral")Me=ni(t.apiKey,Re,at,nt,a,i,y,E.signal,1,d);else if(u==="NVIDIA"){let D=si(t.apiKey,Re,at,nt,a,i,y,E.signal,1);Me=Mc(D,Re)}else if(u==="CrofAI")Me=ri(t.apiKey,Re,at,nt,a,i,y,E.signal,1);else if(u==="InferX")Me=ii(t.apiKey,Re,at,nt,a,i,y,E.signal,1);else if(u==="SenseNova")Me=ai(t.apiKey,Re,at,nt,a,i,y,E.signal,1);else{let oe=li(t?.apiKey).models.generateContentStream({model:Re||"gemini-3-flash-preview",contents:at,config:{systemInstruction:nt,mediaResolution:"MEDIA_RESOLUTION_HIGH",safetySettings:[{category:Vn.HARM_CATEGORY_HARASSMENT,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_HATE_SPEECH,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Yn.BLOCK_NONE}],temperature:1.05,thinkingConfig:(()=>{let j=(Re||"").toLowerCase(),H=j.includes("gemma-4")||j.startsWith("gemma"),xe=j.includes("gemini-3");if(H||xe)return H?a.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:ft.MINIMAL}:{includeThoughts:!0,thinkingLevel:ft.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:j.includes("pro")?ft.LOW:ft.MINIMAL,Low:ft.LOW,Medium:ft.MEDIUM,Standard:ft.MEDIUM,High:ft.HIGH,xHigh:ft.HIGH}[a]||ft.MEDIUM};{let ge={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[a]||2048;return ge===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:ge}}})()}},{signal:E.signal});Me=await Promise.race([oe,At])}ce="",Ut=null,sn=null,te=[],Ge=0,yield{type:"model_update",content:null},Ke="",jt=tt.length>0;let Pt="",Ko=Date.now(),ns=async function*(){if(u==="Google"&&Pt){let D=Us(Pt);for(let oe of D)yield oe;Pt="",Ko=Date.now()}},wi=!0,ss="",bs=!1,Ht=null,qa={tool:{startPrefix:"[tool",fullPrefix:"[tool:functions.",endTag:"]"},agent:{startPrefix:"[agent",fullPrefix:"[agent:generalist.",endTag:"]"},end:{startPrefix:"[[END]]",fullPrefix:"[[END]]",endTag:"[[END]]"},kimi_section:{startPrefix:"<|tool_calls_section_begin|>",fullPrefix:"<|tool_calls_section_begin|>",endTag:"<|tool_calls_section_end|>"},kimi_call:{startPrefix:"<|tool_call_begin|>",fullPrefix:"<|tool_call_begin|>",endTag:"<|tool_call_end|>"}},Us=D=>{let oe=[],j=D;for(;j.length>0;)if(bs){let H=ss+j,xe=qa[Ht];if(xe){let ot=!1;if(H.length<xe.startPrefix.length?xe.startPrefix.startsWith(H)||(ot=!0):H.startsWith(xe.startPrefix)?H.length>=xe.fullPrefix.length&&!H.startsWith(xe.fullPrefix)&&(ot=!0):ot=!0,ot){oe.push({type:"text",content:H}),ss="",bs=!1,Ht=null,j="";break}}let ge=-1,Ee=xe?xe.endTag:"]";if(Ht==="tool"||Ht==="agent"){let ot=0,q=null,pe=0,rt=!1;for(let M=0;M<H.length;M++){let Ye=H[M];if(q){if(Ye===q){let Ne=0;for(let Q=M-1;Q>=0&&H[Q]==="\\";Q--)Ne++;Ne%2===0&&(q=null)}}else if(Ye==='"'||Ye==="'"||Ye==="`")q=Ye;else if(Ye==="(")ot++,rt=!0;else if(Ye===")")ot--;else if(Ye==="[")pe++;else if(Ye==="]"){if(rt&&ot===0&&pe===1){ge=M;break}pe--}}}else ge=H.indexOf(Ee);if(ge!==-1){let ot=Ee.length;if(!Ht?.startsWith("kimi")){let q=H.substring(0,ge+ot);oe.push({type:"text",content:q})}ss="",bs=!1,Ht=null,j=H.substring(ge+ot)}else{let ot=Ht?.startsWith("kimi")?8192:512;H.length>ot?(oe.push({type:"text",content:H}),ss="",bs=!1,Ht=null):ss=H,j="";break}}else{let H=j.indexOf("[tool"),xe=j.indexOf("[agent"),ge=j.indexOf("[[END]]"),Ee=j.indexOf("<|tool_calls_section_begin|>"),ot=j.indexOf("<|tool_call_begin|>"),q=[{type:"tool",idx:H,start:"[tool",end:"]"},{type:"agent",idx:xe,start:"[agent",end:"]"},{type:"end",idx:ge,start:"[[END]]",end:"[[END]]"},{type:"kimi_section",idx:Ee,start:"<|tool_calls_section_begin|>",end:"<|tool_calls_section_end|>"},{type:"kimi_call",idx:ot,start:"<|tool_call_begin|>",end:"<|tool_call_end|>"}].filter(pe=>pe.idx!==-1).sort((pe,rt)=>pe.idx-rt.idx);if(q.length>0){let pe=q[0];pe.idx>0&&oe.push({type:"text",content:j.substring(0,pe.idx)}),bs=!0,Ht=pe.type,ss="",j=j.substring(pe.idx)}else{let pe=["[tool","[agent","[[END]]","<|tool_calls_section_begin|>","<|tool_call_begin|>"],rt=-1;for(let M of pe){for(let Ye=M.length-1;Ye>0;Ye--)if(j.endsWith(M.substring(0,Ye))){rt=j.length-Ye;let Ne=pe.indexOf(M);Ne===0?Ht="tool":Ne===1?Ht="agent":Ne===2?Ht="end":Ne===3?Ht="kimi_section":Ht="kimi_call";break}if(rt!==-1)break}if(rt!==-1)rt>0&&oe.push({type:"text",content:j.substring(0,rt)}),bs=!0,ss=j.substring(rt),j="";else{oe.push({type:"text",content:j});break}}}return oe},za=Me[Symbol.asyncIterator]();for(;;){let{value:D,done:oe}=await Promise.race([za.next(),At]);if(oe)break;if(D&&D.type==="status"){yield D;continue}let j="",H=D.candidates?.[0]?.content?.parts;if(H&&H.length>0)for(let ge of H){let Ee=typeof ge.text=="string"?ge.text:ge.text?parseChunkText(ge.text):"";ge.thought?Ee&&(ue||(j+="<think>",ue=!0),j+=Ee):Ee&&(ue&&(j+="</think>",ue=!1),j+=Ee)}else D.text&&ue&&(j+="</think>",ue=!1);j=Pn(j);let xe=j?j.trim().split(/\s+/).filter(Boolean).length:0;if(t&&typeof t.onTokenChunk=="function"&&t.onTokenChunk(j,xe),wi&&(yield{type:"status",content:"Thinking"},wi=!1),Lt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
659
659
 
660
- \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(j){if(jt){if(Ke+=j,Ke.length>=64){let q=0,pe=Math.min(tt.length,Ke.length);for(let M=pe;M>=10;M--)if(tt.endsWith(Ke.substring(0,M))){q=M;break}let rt=Ke.substring(q);if(rt){let Ye=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(tt)?rt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):rt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(Ye)if(fe+=Ye,u==="Google")Pt+=Ye;else{yield*ns();let Ne=Us(Ye);for(let Q of Ne)yield Q}}jt=!1,Ke=""}continue}else if(fe+=j,u==="Google")Pt+=j;else{yield*ns();let q=Us(j);for(let pe of q)yield pe}let ge=Ac(fe);if(ge.inside){Zn=!0,sn||(sn=Date.now());let pe={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",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Cancel:"cancel",Await:"await",Answer:"answer",Steer:"steer",steer:"steer"}[ge.toolName]||ge.toolName,rt=ge.args||"",M=null;if(["write_file","update_file","view_file","read_folder","write_pdf","write_docx","search_keyword","generate_image","file_map","invoke","invoke_sync","get_progress","await","answer"].includes(pe)){let Ne=O(rt),Q=Ne.path||Ne.targetFile||Ne.TargetFile||Ne.directory,xn=Ne.keyword,os=Ne.title||Ne.task,Un=Ne.id||Ne.taskId,_e=Ne.timeout||Ne.time;if(xn!=null)M=String(xn).replace(gs,"");else if(Q)M=ee.basename(String(Q).replace(gs,"").replace(Ta,"/"));else if(os&&(pe==="invoke"||pe==="invoke_sync"))M=String(os).replace(gs,"").substring(0,30);else if(Un&&pe==="get_progress")M=String(Un).replace(gs,"");else if(_e&&pe==="await"){let Gt=parseFloat(String(_e).replace(gs,""));isNaN(Gt)?M=String(_e).replace(gs,""):(Gt<5&&(Gt=5),Gt>120&&(Gt=120),M=(_n=>{if(_n>=60){let Vo=Math.floor(_n/60),ks=_n%60;return`${Vo}m${ks>0?` ${ks}s`:""}`}return`${_n}s`})(Gt))}else{let Gt=rt.match(xc);if(Gt){let Jt=Gt[1].replace(gs,"");pe==="invoke"||pe==="invoke_sync"||pe==="get_progress"?M=Jt.substring(0,30):M=pe==="search_keyword"||pe==="file_map"?Jt:ee.basename(Jt.replace(Ta,"/"))}}}let Ye=`${Qr[pe]||pe}${M?` ${M}`:""}`;if((pe!==Ut||M!==Qe)&&(Ut=pe,Qe=M,yield{type:"status",content:`${Ye}`},process.stdout.isTTY)){let Q={WebSearch:"Searching",web_search:"Searching",WebScrape:"Reading",web_scrape:"Reading",ReadFile:"Reading",read_file:"Reading",ReadFolder:"Reading",read_folder:"Reading",WriteFile:"Writing",write_file:"Writing",UpdateFile:"Editing",update_file:"Editing",WritePdf:"Creating",write_pdf:"Creating",WriteDocx:"Creating",write_docx:"Creating",SearchKeyword:"Searching",search_keyword:"Searching",CodeSearch:"Searching",code_search:"Searching",Run:"Executing",Ask:"User Input Required",Memory:"Updating Memory",GenerateImage:"Generating",InvokeSync:"Sub-Agent Working",invoke_sync:"Sub-Agent Working",Invoke:"Working",invoke:"Working",GetProgress:"Checking Progress",get_progress:"Checking Progress",Cancel:"Stopping Generalist",cancel:"Stopping Generalist",Await:"Waiting",await:"Waiting",EmergencyRollback:"Rolling the Ball",Answer:"Answering Sub-Agent",answer:"Answering Sub-Agent",Steer:"Steering Sub-Agent",steer:"Steering Sub-Agent",Click:"Clicking",click:"Clicking",Drag:"Dragging",drag:"Dragging",Scroll:"Scrolling",scroll:"Scrolling",KeyboardTyping:"Typing",keyboard_typing:"Typing",KeyPress:"Pressing Key",key_press:"Pressing Key",RecaptureScreen:"Recapturing Screen",recapture_screen:"Recapturing Screen"}[pe]||"Working";process.stdout.write(`\x1B]0;${Q}...\x07`)}}if(fe.length-go>150){go=fe.length;let q=Fa(fe,!1),rt=(q.match(/(?:<think>|\[think\])([\s\S]*?)(?:<\/think>|\[\/think\]|$)/gi)||[]).join("").trim(),M=rt.split(/[.!?]\s+/),Ye=new Set(M),Ne=M.length>10?(M.length-Ye.size)/M.length:0,Q=rt.split(/\s+/).filter(Ae=>Ae.length>0).length,xn=.6,os=.8,Un=!1;if((u.toLowerCase().includes("google")||u.toLowerCase().includes("mistral"))&&((Te||"").toLowerCase().startsWith("gemma")||(Te||"").toLowerCase().includes("stral"))){let v={low:256,medium:1024,high:8192,max:16384,xhigh:16384}[a?.toLowerCase()]||2500;Un=Q>v}if(Ne>xn||Un){yield{type:"status",content:`${Ne>xn?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},Wt=!0,await new Promise(v=>setTimeout(v,3e3));break}let Jt=va(fe).trim().split(/[.!?]\s+/),_n=new Set(Jt);if((Jt.length>10?(Jt.length-_n.size)/Jt.length:0)>os){yield{type:"status",content:"Response Loop Detected. Re-centering..."},Wt=!1,Rn=!0,await new Promise(Ae=>setTimeout(Ae,3e3));break}let ks=q.replace(uc,"").replace(hc,"").replace(pc,"").replace(mc,""),qt=ks.toLowerCase().split(/\s+/).map(Ae=>Ae.replace(gc,"")).filter(Ae=>Ae.length>0),$n=!1;if(qt.length>=10)for(let Ae=1;Ae<=15;Ae++){let v=Math.max(3,Math.ceil(10/Ae));if(qt.length<Ae*v)continue;let K=qt.slice(qt.length-Ae),ce=K.join(" ");if(Ae>1&&ce===K.slice(0,Math.floor(Ae/2)).join(" ").repeat(2).trim())continue;let ye=!0;for(let xe=1;xe<v;xe++)if(qt.slice(qt.length-Ae*(xe+1),qt.length-Ae*xe).join(" ")!==ce){ye=!1;break}if(ye){$n=!0;break}}if(!$n){let Ae=ks.toLowerCase().replace(yc,"");if(Ae.length>=20)for(let v=1;v<=10;v++){let K=Math.max(5,Math.ceil(16/v));if(Ae.length<v*K)continue;let ce=Ae.substring(Ae.length-v),ye=!0;for(let xe=1;xe<K;xe++)if(Ae.substring(Ae.length-v*(xe+1),Ae.length-v*xe)!==ce){ye=!1;break}if(ye){$n=!0;break}}}if($n){yield{type:"status",content:"Stuttering Detected. Re-centering..."},Wt=!1,wn=!0,await new Promise(Ae=>setTimeout(Ae,3e3));break}}let Ee=fe.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/gi,""),ot=Ho(Ee);for(;ot.length>Ge;){yield*ns();let q=ot[Ge],pe=Date.now(),M={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",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Await:"await",await:"await",AwaitSubagent:"await",awaitSubagent:"await",Answer:"answer",answer:"answer",AnswerSubagent:"answer",answerSubagent:"answer",Steer:"steer",steer:"steer",SteerSubagent:"steer",steerSubagent:"steer",Cancel:"cancel",cancel:"cancel",Click:"click",click:"click",Drag:"drag",drag:"drag",Scroll:"scroll",scroll:"scroll",KeyboardTyping:"keyboard_typing",keyboard_typing:"keyboard_typing",KeyPress:"key_press",key_press:"key_press",RecaptureScreen:"recapture_screen",recapture_screen:"recapture_screen",EmergencyRollback:"EmergencyRollback"}[q.toolName]||q.toolName,Ye=Qr[M]||q.toolName,Ne=ws(M,q.args);yield{type:"status",content:`${Ye}${Ne?` ${Ne}`:""}`};let Q="";if(M==="click"){let v=O(q.args);Q=`\u2714 Clicked: ${v.intendedClickText?`${v.intendedClickText}`:""}`}else if(M==="drag"){let v=O(q.args);Q=`\u2714 Dragged: Cell ${v.fromGridId||""} \u2192 Cell ${v.toGridId||""}`}else if(M==="scroll"){let v=O(q.args);Q=`\u2714 Scrolled: ${v.direction||"down"} (${v.amount||1})`}else if(M==="keyboard_typing"){let v=O(q.args);Q=`\u2714 Typed: ${v.text?`"${v.text.length>20?v.text.substring(0,20)+"...":v.text}"`:""}`}else if(M==="key_press")Q=`\u2714 Pressed Key: ${O(q.args).key||""}`;else if(M==="recapture_screen")Q="\u2714 Recaptured Screen";else if(M==="web_search"){let{query:v,limit:K=10,aiMode:ce=!1}=O(q.args);Q=`${v?"\u2714":"\u2718"} ${ce?"AI Search":"Searched"}: ${v?`${v}`:"No Search Query"}${ce===!1&&v?` \u2192 ${K}`:""}`}else if(M==="web_scrape"){let v=O(q.args).url||null;Q=`${v?"\u2714":"\u2718"} Visited: ${v||"No Source"}`}else if(M==="view_file"){let{path:v,StartLine:K,EndLine:ce,start_line:ye,end_line:xe,startLine:qe,endLine:Oe}=O(q.args),ke=K||ye||qe,ne=ce||xe||Oe,ue=parseInt(ke)||1,de=parseInt(ne)||(ke?ue+800:800),Be="...",et=de;try{let Ve=ee.resolve(process.cwd(),v);if(Pe.existsSync(Ve)){let _t=Pe.readFileSync(Ve,"utf8").split(`
661
- `).length;Be=_t,!ke&&!ne&&_t>800?et=Math.min(50,_t):et=Math.min(de,_t)}}catch{}let be=(v||"").toLowerCase(),De=be.endsWith(".pdf"),lt=be.endsWith(".docx")||be.endsWith(".doc")||be.endsWith(".ppt")||be.endsWith(".pptx")||be.endsWith(".xls")||be.endsWith(".xlsx"),ve=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(be);De||lt?Q=`${v.length>0?"\u2714":"\u2718"} ${v?`Analyzed: ${ee.basename(v)}`:"Analyzed: File Not Found"}`:ve?Q=`${v.length>0?"\u2714":"\u2718"} ${v?`Processed: ${ee.basename(v)}`:"Processed: File Not Found"}`:Q=`${Be!=="..."?"\u2714":"\u2718"} Read: ${v?`${ee.basename(v)} \u2192 ${Be!=="..."?`Lines ${ue} - ${et} of ${Be}`:"File Not Found"}`:"File Not Found"}`}else if(M==="list_files"||M==="read_folder"){let v=M==="list_files"?"List":"Browsed",K=O(q.args).path||null,ce=O(q.args).recurse||1;Q=`${K?"\u2714":"\u2718"} ${v}: ${K?`${K==="."?`./${ce>1?"*":""}`:`${K.replaceAll("\\","/")}${ce>1?`${K.endsWith("/")?"*":"/*"}`:`${K.endsWith("/")?"":"/"}`}`}`:"No Folder Selected"}`}else if(M==="write_file"||M==="update_file"){let v=M==="write_file"?"Created":"Edited",K=O(q.args).path||null;Q=`${K?"\u2714":"\u2718"} ${v}: ${K.replaceAll("\\","/")||"No File Changes"}`}else if(M==="write_pdf"){let v=O(q.args).path||null;Q=`${v?"\u2714":"\u2718"} Generated: ${v.replaceAll("\\","/")||"No PDF Generated"}`}else if(M==="write_docx"){let v=O(q.args).path||null;Q=`${v?"\u2714":"\u2718"} Generated: ${v.replaceAll("\\","/")||"No Docx Generated"}`}else if(M==="file_map"){let v=O(q.args).path;Q=`${v?"\u2714":"\u2718"} Indexed: ${v.replaceAll("\\","/")?""+v:"File Not Found"}`}else if(M.toLowerCase()==="search_keyword"||M.toLowerCase()==="todo")Q="";else if(M.toLowerCase()==="generate_image"){let{path:v,outputPath:K,output:ce}=O(q.args);Q=`\u2714 Generated: ${v||K||ce||"generated_image.png"}`}else if(M==="invoke_sync"||M==="InvokeSync"){let v=ws(M,q.args);Q=`\u2714 Called Generalist${v?`: ${v}`:""}`}else if(M==="Invoke"||M==="InvokeAsync"||M==="invoke"){let v=ws(M,q.args);Q=`\u2714 Started Generalist${v?`: ${v}`:""}`}else if(M==="get_progress"||M==="GetProgress"){let v=ws(M,q.args);Q=`\u2714 Checked${v?`: ${v}`:""}`}else if(M==="cancel"){let v=ws(M,q.args);Q=`\u{1F6C7} Cancelled${v?`: ${v}`:""}`}else if(M==="steer"||M==="Steer"){let v=ws(M,q.args);Q=`\u2714 Steered${v?`: ${v}`:""}`}else if(M==="EmergencyRollback"){let{method:v}=O(q.args);Q=v==="forceRevert"?"":"\u2714 Rollback Point Checked"}else if(M==="await"||M==="Await"){let{time:v,timeout:K}=O(q.args),ce=parseFloat(K||v)||0;ce||(ce=120);let ye=Oe=>{if(Oe>=60){let ke=Math.floor(Oe/60),ne=Oe%60;return`${ke}m${ne>0?` ${ne}s`:""}`}return`${Oe}s`},xe=["Aligning Moon Phase","Contemplating Existence","Staring At Void","Delaying Professionally","Negotiating With Electrons","Touching Grass (virtually)","Panicking Softly","Rethinking Career Choices","Loading Cat Videos","Summoning Braincell #2","Pretending To Be Busy","Waiting For Motivation DLC","Rotating Internal Screaming","Downloading More RAM","Feeding The Hamsters","Gaslighting Scheduler","Performing Dramatic Pause","Buffering Social Energy","Calculating Regret","Reading Terms And Conditions","Becoming Sentient Briefly","Contacting Ancestors"];Q=`\u2714 ${xe[Math.floor(Math.random()*xe.length)]} \u2192 ${ye(ce)}`}else M==="Answer"||M==="answer"?Q="\u2714 Resolved Sub-Agent Query":M==="exec_command"||M==="ask"?Q="":Q=`Executed: ${q.toolName}`;if(yield*ns(),M==="exec_command"){let{command:v}=O(q.args);if(v&&t.systemSettings&&t.systemSettings.allowExternalAccess===!1){let K=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],ce=ee.resolve(process.cwd()).substring(0,3).toLowerCase(),ye=ne=>{let ue=[],de="",Be=null;for(let et=0;et<ne.length;et++){let be=ne[et];Be?(be===Be&&(Be=null),de+=be):be==='"'||be==="'"?(Be=be,de+=be):be==="&"&&ne[et+1]==="&"||be==="|"&&ne[et+1]==="|"?(de.trim()&&(ue.push(de.trim()),de=""),et++):be===";"||be==="|"||be==="&"?de.trim()&&(ue.push(de.trim()),de=""):de+=be}return de.trim()&&ue.push(de.trim()),ue},xe=ne=>{let ue=[],de="",Be=null;for(let et=0;et<ne.length;et++){let be=ne[et];Be?(be===Be&&(Be=null),de+=be):be==='"'||be==="'"?(Be=be,de+=be):/\s/.test(be)?de&&(ue.push(de),de=""):de+=be}return de&&ue.push(de),ue},qe=ne=>{let ue=ne.replace(/^['"]|['"]$/g,"").trim();return!ue||process.platform==="win32"&&/^\/[a-zA-Z0-9?]+$/.test(ue)?!1:K.some(de=>{if(de.source==="[a-zA-Z]:[\\\\\\/]"){let Be=ue.match(/[a-zA-Z]:[\\\/]/i);return Be&&Be[0].toLowerCase()!==ce}return de.test(ue)})};if(ye(v).some(ne=>{let ue=xe(ne);if(ue.length===0)return!1;let de=ue[0].replace(/^['"]|['"]$/g,"").toLowerCase();if(["echo","printf","write-output"].includes(de)){let et=!1;return ue.some(be=>{let De=be.replace(/^['"]|['"]$/g,"");if(De===">"||De===">>"||De==="<")return et=!0,!1;if(De.startsWith(">")||De.startsWith("<")){let lt=De.replace(/^[><]+/,"");return qe(lt)}return et?(et=!1,qe(be)):!1})}return ue.some(et=>qe(et))})){let ne='Access Denied. Prohibited from accessing external directories while "External Workspace Access" is disabled.';t.onExecStart&&t.onExecStart(v||"No Command"),yield{type:"exec_start"},await new Promise(ue=>setTimeout(ue,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${ne}`),await new Promise(ue=>setTimeout(ue,50)),t.onExecEnd&&t.onExecEnd(),te.push({role:"user",text:`[TOOL RESULT]: ERROR: ${ne}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${ne}`},Ge++;continue}}t.onExecStart&&t.onExecStart(v||"No Command"),yield{type:"exec_start"}}let xn=O(q.args),os=xn.path||xn.targetPath||null;if(os){let v=t.systemSettings&&t.systemSettings.allowExternalAccess===!1,K=ee.resolve(os),ce=ee.resolve(process.cwd());if(v&&!K.startsWith(ce)){let ye="Access Denied. You are not allowed to access files outside the current workspace.";if(M==="write_file"||M==="update_file"){let qe=`\u2718 ${M==="write_file"?"Write Canceled":"Edit Canceled"}: ${xn.path||"..."}`,Oe=115;process.stdout.isTTY&&(Oe=process.stdout.columns-5||120);let ke=Math.min(qe.length+4,Oe),ne=`${qe.padEnd(ke-2).substring(0,ke-2)}`;yield{type:"visual_feedback",content:gn(`${We?`
660
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(j){if(jt){if(Ke+=j,Ke.length>=64){let q=0,pe=Math.min(tt.length,Ke.length);for(let M=pe;M>=10;M--)if(tt.endsWith(Ke.substring(0,M))){q=M;break}let rt=Ke.substring(q);if(rt){let Ye=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(tt)?rt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):rt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(Ye)if(ce+=Ye,u==="Google")Pt+=Ye;else{yield*ns();let Ne=Us(Ye);for(let Q of Ne)yield Q}}jt=!1,Ke=""}continue}else if(ce+=j,u==="Google")Pt+=j;else{yield*ns();let q=Us(j);for(let pe of q)yield pe}let ge=Ac(ce);if(ge.inside){Zn=!0,sn||(sn=Date.now());let pe={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",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Cancel:"cancel",Await:"await",Answer:"answer",Steer:"steer",steer:"steer"}[ge.toolName]||ge.toolName,rt=ge.args||"",M=null;if(["write_file","update_file","view_file","read_folder","write_pdf","write_docx","search_keyword","generate_image","file_map","invoke","invoke_sync","get_progress","await","answer"].includes(pe)){let Ne=O(rt),Q=Ne.path||Ne.targetFile||Ne.TargetFile||Ne.directory,xn=Ne.keyword,os=Ne.title||Ne.task,Un=Ne.id||Ne.taskId,_e=Ne.timeout||Ne.time;if(xn!=null)M=String(xn).replace(gs,"");else if(Q)M=ee.basename(String(Q).replace(gs,"").replace(Ta,"/"));else if(os&&(pe==="invoke"||pe==="invoke_sync"))M=String(os).replace(gs,"").substring(0,30);else if(Un&&pe==="get_progress")M=String(Un).replace(gs,"");else if(_e&&pe==="await"){let Gt=parseFloat(String(_e).replace(gs,""));isNaN(Gt)?M=String(_e).replace(gs,""):(Gt<5&&(Gt=5),Gt>120&&(Gt=120),M=(_n=>{if(_n>=60){let Vo=Math.floor(_n/60),ks=_n%60;return`${Vo}m${ks>0?` ${ks}s`:""}`}return`${_n}s`})(Gt))}else{let Gt=rt.match(xc);if(Gt){let Jt=Gt[1].replace(gs,"");pe==="invoke"||pe==="invoke_sync"||pe==="get_progress"?M=Jt.substring(0,30):M=pe==="search_keyword"||pe==="file_map"?Jt:ee.basename(Jt.replace(Ta,"/"))}}}let Ye=`${Qr[pe]||pe}${M?` ${M}`:""}`;if((pe!==Ut||M!==Qe)&&(Ut=pe,Qe=M,yield{type:"status",content:`${Ye}`},process.stdout.isTTY)){let Q={WebSearch:"Searching",web_search:"Searching",WebScrape:"Reading",web_scrape:"Reading",ReadFile:"Reading",read_file:"Reading",ReadFolder:"Reading",read_folder:"Reading",WriteFile:"Writing",write_file:"Writing",UpdateFile:"Editing",update_file:"Editing",WritePdf:"Creating",write_pdf:"Creating",WriteDocx:"Creating",write_docx:"Creating",SearchKeyword:"Searching",search_keyword:"Searching",CodeSearch:"Searching",code_search:"Searching",Run:"Executing",Ask:"User Input Required",Memory:"Updating Memory",GenerateImage:"Generating",InvokeSync:"Sub-Agent Working",invoke_sync:"Sub-Agent Working",Invoke:"Working",invoke:"Working",GetProgress:"Checking Progress",get_progress:"Checking Progress",Cancel:"Stopping Generalist",cancel:"Stopping Generalist",Await:"Waiting",await:"Waiting",EmergencyRollback:"Rolling the Ball",Answer:"Answering Sub-Agent",answer:"Answering Sub-Agent",Steer:"Steering Sub-Agent",steer:"Steering Sub-Agent",Click:"Clicking",click:"Clicking",Drag:"Dragging",drag:"Dragging",Scroll:"Scrolling",scroll:"Scrolling",KeyboardTyping:"Typing",keyboard_typing:"Typing",KeyPress:"Pressing Key",key_press:"Pressing Key",RecaptureScreen:"Recapturing Screen",recapture_screen:"Recapturing Screen"}[pe]||"Working";process.stdout.write(`\x1B]0;${Q}...\x07`)}}if(ce.length-go>150){go=ce.length;let q=Fa(ce,!1),rt=(q.match(/(?:<think>|\[think\])([\s\S]*?)(?:<\/think>|\[\/think\]|$)/gi)||[]).join("").trim(),M=rt.split(/[.!?]\s+/),Ye=new Set(M),Ne=M.length>10?(M.length-Ye.size)/M.length:0,Q=rt.split(/\s+/).filter(Ae=>Ae.length>0).length,xn=.6,os=.8,Un=!1;if((u.toLowerCase().includes("google")||u.toLowerCase().includes("mistral"))&&((Re||"").toLowerCase().startsWith("gemma")||(Re||"").toLowerCase().includes("stral"))){let v={low:256,medium:1024,high:8192,max:16384,xhigh:16384}[a?.toLowerCase()]||2500;Un=Q>v}if(Ne>xn||Un){yield{type:"status",content:`${Ne>xn?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},Wt=!0,await new Promise(v=>setTimeout(v,3e3));break}let Jt=va(ce).trim().split(/[.!?]\s+/),_n=new Set(Jt);if((Jt.length>10?(Jt.length-_n.size)/Jt.length:0)>os){yield{type:"status",content:"Response Loop Detected. Re-centering..."},Wt=!1,Rn=!0,await new Promise(Ae=>setTimeout(Ae,3e3));break}let ks=q.replace(uc,"").replace(hc,"").replace(pc,"").replace(mc,""),qt=ks.toLowerCase().split(/\s+/).map(Ae=>Ae.replace(gc,"")).filter(Ae=>Ae.length>0),$n=!1;if(qt.length>=10)for(let Ae=1;Ae<=15;Ae++){let v=Math.max(3,Math.ceil(10/Ae));if(qt.length<Ae*v)continue;let K=qt.slice(qt.length-Ae),de=K.join(" ");if(Ae>1&&de===K.slice(0,Math.floor(Ae/2)).join(" ").repeat(2).trim())continue;let ye=!0;for(let be=1;be<v;be++)if(qt.slice(qt.length-Ae*(be+1),qt.length-Ae*be).join(" ")!==de){ye=!1;break}if(ye){$n=!0;break}}if(!$n){let Ae=ks.toLowerCase().replace(yc,"");if(Ae.length>=20)for(let v=1;v<=10;v++){let K=Math.max(5,Math.ceil(16/v));if(Ae.length<v*K)continue;let de=Ae.substring(Ae.length-v),ye=!0;for(let be=1;be<K;be++)if(Ae.substring(Ae.length-v*(be+1),Ae.length-v*be)!==de){ye=!1;break}if(ye){$n=!0;break}}}if($n){yield{type:"status",content:"Stuttering Detected. Re-centering..."},Wt=!1,wn=!0,await new Promise(Ae=>setTimeout(Ae,3e3));break}}let Ee=ce.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/gi,""),ot=Ho(Ee);for(;ot.length>Ge;){yield*ns();let q=ot[Ge],pe=Date.now(),M={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",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Await:"await",await:"await",AwaitSubagent:"await",awaitSubagent:"await",Answer:"answer",answer:"answer",AnswerSubagent:"answer",answerSubagent:"answer",Steer:"steer",steer:"steer",SteerSubagent:"steer",steerSubagent:"steer",Cancel:"cancel",cancel:"cancel",Click:"click",click:"click",Drag:"drag",drag:"drag",Scroll:"scroll",scroll:"scroll",KeyboardTyping:"keyboard_typing",keyboard_typing:"keyboard_typing",KeyPress:"key_press",key_press:"key_press",RecaptureScreen:"recapture_screen",recapture_screen:"recapture_screen",EmergencyRollback:"EmergencyRollback"}[q.toolName]||q.toolName,Ye=Qr[M]||q.toolName,Ne=ws(M,q.args);yield{type:"status",content:`${Ye}${Ne?` ${Ne}`:""}`};let Q="";if(M==="click"){let v=O(q.args);Q=`\u2714 Clicked: ${v.intendedClickText?`${v.intendedClickText}`:""}`}else if(M==="drag"){let v=O(q.args);Q=`\u2714 Dragged: Cell ${v.fromGridId||""} \u2192 Cell ${v.toGridId||""}`}else if(M==="scroll"){let v=O(q.args);Q=`\u2714 Scrolled: ${v.direction||"down"} (${v.amount||1})`}else if(M==="keyboard_typing"){let v=O(q.args);Q=`\u2714 Typed: ${v.text?`"${v.text.length>20?v.text.substring(0,20)+"...":v.text}"`:""}`}else if(M==="key_press")Q=`\u2714 Pressed Key: ${O(q.args).key||""}`;else if(M==="recapture_screen")Q="\u2714 Recaptured Screen";else if(M==="web_search"){let{query:v,limit:K=10,aiMode:de=!1}=O(q.args);Q=`${v?"\u2714":"\u2718"} ${de?"AI Search":"Searched"}: ${v?`${v}`:"No Search Query"}${de===!1&&v?` \u2192 ${K}`:""}`}else if(M==="web_scrape"){let v=O(q.args).url||null;Q=`${v?"\u2714":"\u2718"} Visited: ${v||"No Source"}`}else if(M==="view_file"){let{path:v,StartLine:K,EndLine:de,start_line:ye,end_line:be,startLine:qe,endLine:Oe}=O(q.args),Se=K||ye||qe,ne=de||be||Oe,he=parseInt(Se)||1,fe=parseInt(ne)||(Se?he+800:800),Be="...",et=fe;try{let Ve=ee.resolve(process.cwd(),v);if(Pe.existsSync(Ve)){let _t=Pe.readFileSync(Ve,"utf8").split(`
661
+ `).length;Be=_t,!Se&&!ne&&_t>800?et=Math.min(50,_t):et=Math.min(fe,_t)}}catch{}let ke=(v||"").toLowerCase(),De=ke.endsWith(".pdf"),lt=ke.endsWith(".docx")||ke.endsWith(".doc")||ke.endsWith(".ppt")||ke.endsWith(".pptx")||ke.endsWith(".xls")||ke.endsWith(".xlsx"),ve=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(ke);De||lt?Q=`${v.length>0?"\u2714":"\u2718"} ${v?`Analyzed: ${ee.basename(v)}`:"Analyzed: File Not Found"}`:ve?Q=`${v.length>0?"\u2714":"\u2718"} ${v?`Processed: ${ee.basename(v)}`:"Processed: File Not Found"}`:Q=`${Be!=="..."?"\u2714":"\u2718"} Read: ${v?`${ee.basename(v)} \u2192 ${Be!=="..."?`Lines ${he} - ${et} of ${Be}`:"File Not Found"}`:"File Not Found"}`}else if(M==="list_files"||M==="read_folder"){let v=M==="list_files"?"List":"Browsed",K=O(q.args).path||null,de=O(q.args).recurse||1;Q=`${K?"\u2714":"\u2718"} ${v}: ${K?`${K==="."?`./${de>1?"*":""}`:`${K.replaceAll("\\","/")}${de>1?`${K.endsWith("/")?"*":"/*"}`:`${K.endsWith("/")?"":"/"}`}`}`:"No Folder Selected"}`}else if(M==="write_file"||M==="update_file"){let v=M==="write_file"?"Created":"Edited",K=O(q.args).path||null;Q=`${K?"\u2714":"\u2718"} ${v}: ${K.replaceAll("\\","/")||"No File Changes"}`}else if(M==="write_pdf"){let v=O(q.args).path||null;Q=`${v?"\u2714":"\u2718"} Generated: ${v.replaceAll("\\","/")||"No PDF Generated"}`}else if(M==="write_docx"){let v=O(q.args).path||null;Q=`${v?"\u2714":"\u2718"} Generated: ${v.replaceAll("\\","/")||"No Docx Generated"}`}else if(M==="file_map"){let v=O(q.args).path;Q=`${v?"\u2714":"\u2718"} Indexed: ${v.replaceAll("\\","/")?""+v:"File Not Found"}`}else if(M.toLowerCase()==="search_keyword"||M.toLowerCase()==="todo")Q="";else if(M.toLowerCase()==="generate_image"){let{path:v,outputPath:K,output:de}=O(q.args);Q=`\u2714 Generated: ${v||K||de||"generated_image.png"}`}else if(M==="invoke_sync"||M==="InvokeSync"){let v=ws(M,q.args);Q=`\u2714 Called Generalist${v?`: ${v}`:""}`}else if(M==="Invoke"||M==="InvokeAsync"||M==="invoke"){let v=ws(M,q.args);Q=`\u2714 Started Generalist${v?`: ${v}`:""}`}else if(M==="get_progress"||M==="GetProgress"){let v=ws(M,q.args);Q=`\u2714 Checked${v?`: ${v}`:""}`}else if(M==="cancel"){let v=ws(M,q.args);Q=`\u{1F6C7} Cancelled${v?`: ${v}`:""}`}else if(M==="steer"||M==="Steer"){let v=ws(M,q.args);Q=`\u2714 Steered${v?`: ${v}`:""}`}else if(M==="EmergencyRollback"){let{method:v}=O(q.args);Q=v==="forceRevert"?"":"\u2714 Rollback Point Checked"}else if(M==="await"||M==="Await"){let{time:v,timeout:K}=O(q.args),de=parseFloat(K||v)||0;de||(de=120);let ye=Oe=>{if(Oe>=60){let Se=Math.floor(Oe/60),ne=Oe%60;return`${Se}m${ne>0?` ${ne}s`:""}`}return`${Oe}s`},be=["Aligning Moon Phase","Contemplating Existence","Staring At Void","Delaying Professionally","Negotiating With Electrons","Touching Grass (virtually)","Panicking Softly","Rethinking Career Choices","Loading Cat Videos","Summoning Braincell #2","Pretending To Be Busy","Waiting For Motivation DLC","Rotating Internal Screaming","Downloading More RAM","Feeding The Hamsters","Gaslighting Scheduler","Performing Dramatic Pause","Buffering Social Energy","Calculating Regret","Reading Terms And Conditions","Becoming Sentient Briefly","Contacting Ancestors"];Q=`\u2714 ${be[Math.floor(Math.random()*be.length)]} \u2192 ${ye(de)}`}else M==="Answer"||M==="answer"?Q="\u2714 Resolved Sub-Agent Query":M==="exec_command"||M==="ask"?Q="":Q=`Executed: ${q.toolName}`;if(yield*ns(),M==="exec_command"){let{command:v}=O(q.args);if(v&&t.systemSettings&&t.systemSettings.allowExternalAccess===!1){let K=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],de=ee.resolve(process.cwd()).substring(0,3).toLowerCase(),ye=ne=>{let he=[],fe="",Be=null;for(let et=0;et<ne.length;et++){let ke=ne[et];Be?(ke===Be&&(Be=null),fe+=ke):ke==='"'||ke==="'"?(Be=ke,fe+=ke):ke==="&"&&ne[et+1]==="&"||ke==="|"&&ne[et+1]==="|"?(fe.trim()&&(he.push(fe.trim()),fe=""),et++):ke===";"||ke==="|"||ke==="&"?fe.trim()&&(he.push(fe.trim()),fe=""):fe+=ke}return fe.trim()&&he.push(fe.trim()),he},be=ne=>{let he=[],fe="",Be=null;for(let et=0;et<ne.length;et++){let ke=ne[et];Be?(ke===Be&&(Be=null),fe+=ke):ke==='"'||ke==="'"?(Be=ke,fe+=ke):/\s/.test(ke)?fe&&(he.push(fe),fe=""):fe+=ke}return fe&&he.push(fe),he},qe=ne=>{let he=ne.replace(/^['"]|['"]$/g,"").trim();return!he||process.platform==="win32"&&/^\/[a-zA-Z0-9?]+$/.test(he)?!1:K.some(fe=>{if(fe.source==="[a-zA-Z]:[\\\\\\/]"){let Be=he.match(/[a-zA-Z]:[\\\/]/i);return Be&&Be[0].toLowerCase()!==de}return fe.test(he)})};if(ye(v).some(ne=>{let he=be(ne);if(he.length===0)return!1;let fe=he[0].replace(/^['"]|['"]$/g,"").toLowerCase();if(["echo","printf","write-output"].includes(fe)){let et=!1;return he.some(ke=>{let De=ke.replace(/^['"]|['"]$/g,"");if(De===">"||De===">>"||De==="<")return et=!0,!1;if(De.startsWith(">")||De.startsWith("<")){let lt=De.replace(/^[><]+/,"");return qe(lt)}return et?(et=!1,qe(ke)):!1})}return he.some(et=>qe(et))})){let ne='Access Denied. Prohibited from accessing external directories while "External Workspace Access" is disabled.';t.onExecStart&&t.onExecStart(v||"No Command"),yield{type:"exec_start"},await new Promise(he=>setTimeout(he,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${ne}`),await new Promise(he=>setTimeout(he,50)),t.onExecEnd&&t.onExecEnd(),te.push({role:"user",text:`[TOOL RESULT]: ERROR: ${ne}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${ne}`},Ge++;continue}}t.onExecStart&&t.onExecStart(v||"No Command"),yield{type:"exec_start"}}let xn=O(q.args),os=xn.path||xn.targetPath||null;if(os){let v=t.systemSettings&&t.systemSettings.allowExternalAccess===!1,K=ee.resolve(os),de=ee.resolve(process.cwd());if(v&&!K.startsWith(de)){let ye="Access Denied. You are not allowed to access files outside the current workspace.";if(M==="write_file"||M==="update_file"){let qe=`\u2718 ${M==="write_file"?"Write Canceled":"Edit Canceled"}: ${xn.path||"..."}`,Oe=115;process.stdout.isTTY&&(Oe=process.stdout.columns-5||120);let Se=Math.min(qe.length+4,Oe),ne=`${qe.padEnd(Se-2).substring(0,Se-2)}`;yield{type:"visual_feedback",content:gn(`${We?`
662
662
  `:""}${ne}
663
- `)},We=!1}te.push({role:"user",text:`[TOOL RESULT]: ERROR: ${ye}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${ye}`},Ge++;continue}}if(t.onToolApproval&&(M==="write_file"||M==="update_file"||M==="exec_command")){let K=t.systemSettings||{},ce=K.autoExec,ye=null,xe=!1,qe=!1,Oe=!1;if(M==="exec_command"){let{command:De}=O(q.args),lt=(De||"").trim(),ve=(_t,Qt)=>{if(!Qt)return!1;let dn=Qt.split(",").map(Zt=>Zt.trim().toLowerCase()).filter(Boolean),ct=_t.toLowerCase();return dn.some(Zt=>ct.startsWith(Zt))},Ve=ve(lt,K.alwaysAskCommands),Se=ve(lt,K.autoApproveCommands);if(qe=ve(lt,K.autoDisallowCommands),Ve?xe=!0:(Se||K.autoApproveGit&&/^git\s+commit\b/i.test(lt))&&(ye="allow"),!xe&&!ye){if(K.networkAccess===!1){let Qt=lt.trim().replace(/\s+/g," ").replace(/^['"]+|['"]+$/g,"").toLowerCase().split(" "),ct=Qt[0].split("/").pop().split("\\").pop().replace(/\.exe$/,""),Zt=new Set(["curl","wget","httpie","xh","ssh","scp","sftp","rsync","ftp","lftp","tftp","telnet","nc","netcat","socat","ping","traceroute","tracert","dig","nslookup","host","whois","nmap","docker","podman","kubectl","helm","gcloud","aws","az","terraform","ansible-playbook","nix","nix-env","apt","apt-get","dpkg","yum","dnf","pacman","zypper","brew","apk","choco","scoop","conda","mamba","aria2c","axel","smbclient","lynx","w3m","links","elinks","heroku","netlify","vercel","firebase","supabase","wrangler","flyctl","powershell","pwsh","certutil","bitsadmin","cloudflared","ngrok","tailscale","zerotier","rclone"]),dt=!1;Zt.has(ct)&&(dt=!0);let ht=bn=>Qt.slice(1).some(kn=>bn.includes(kn)),vt=bn=>{let kn=Qt.findIndex(Cn=>bn.includes(Cn)),Ss=Qt.findIndex(Cn=>["run","exec","test"].includes(Cn));return kn!==-1&&!(Ss!==-1&&Ss<kn)};ct==="git"&&ht(["clone","pull","push","fetch"])&&(dt=!0),ct==="go"&&ht(["get","install"])&&(dt=!0),ct==="npm"&&vt(["install","i","update","add"])&&(dt=!0),ct==="yarn"&&vt(["add","install","upgrade"])&&(dt=!0),ct==="pnpm"&&vt(["add","install","update"])&&(dt=!0),ct==="bun"&&vt(["add","install","update"])&&(dt=!0),ct==="deno"&&ht(["install","add"])&&(dt=!0),ct==="pip"&&ht(["install","download"])&&(dt=!0),ct==="pip3"&&ht(["install","download"])&&(dt=!0),ct==="cargo"&&ht(["install","add"])&&(dt=!0),["bash","sh","zsh","fish"].includes(ct)&&ht(["-c"])&&(dt=!0),ct==="cmd"&&ht(["/c"])&&(dt=!0),dt&&(ye="deny",Oe=!0)}!ye&&qe&&(ye="deny")}!xe&&!ye&&ce&&(ye="allow")}else ce&&(ye="allow");let ke=ye,ne="";ye==="deny"&&(Oe?ne="network":qe?ne="settings":ne="prohibited");let ue=!1,de="",Be=[],et=0,be=!1;if(!ke){if(M==="write_file"||M==="update_file")try{let ve=O(q.args),{path:Ve}=ve;if(Ve){let Se=ee.resolve(process.cwd(),Ve),_t=ht=>ht?ht.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,vt=>vt.toUpperCase()):"",Qt=_t(Se),dn="",ct=!1,Zt=await ms(),dt=_t(Zt?.file_focused);if(Zt&&dt===Qt&&Zt.full_content?(dn=Zt.full_content,ct=!0):Pe.existsSync(Se)&&(dn=Pe.readFileSync(Se,"utf8"),ct=!0),de=dn,await mt.recordFileChange(Se,dn),ct){let ht=dn;if(M==="write_file")ht=ve.content||ve.newContent||"";else{let{patchPairs:vt,allowMultiple:bn,error:kn}=Ao(ve);if(kn){let $t=`[TOOL RESULT]: ERROR: ${kn}`;te.push({role:"user",text:$t}),await Ot("toolFailure"),t.onToolResult&&t.onToolResult("failure",M),yield{type:"tool_result",content:$t,toolName:M},Ge++;continue}let Ss=ve.allowMultiple!==void 0?ve.allowMultiple===!0||String(ve.allowMultiple).toLowerCase()==="true":bn;et=vt.length;let Cn=vo(dn,vt,{allowMultiple:Ss});ht=Cn.content,Be=Cn.results;let yo=Be.filter($t=>$t.success),It=Be.filter($t=>!$t.success);if(yo.length===0){let $t=`[TOOL RESULT]: ERROR: Failed to apply patches to [${ee.basename(Se)}].
663
+ `)},We=!1}te.push({role:"user",text:`[TOOL RESULT]: ERROR: ${ye}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${ye}`},Ge++;continue}}if(t.onToolApproval&&(M==="write_file"||M==="update_file"||M==="exec_command")){let K=t.systemSettings||{},de=K.autoExec,ye=null,be=!1,qe=!1,Oe=!1;if(M==="exec_command"){let{command:De}=O(q.args),lt=(De||"").trim(),ve=(_t,Qt)=>{if(!Qt)return!1;let dn=Qt.split(",").map(Zt=>Zt.trim().toLowerCase()).filter(Boolean),ct=_t.toLowerCase();return dn.some(Zt=>ct.startsWith(Zt))},Ve=ve(lt,K.alwaysAskCommands),Te=ve(lt,K.autoApproveCommands);if(qe=ve(lt,K.autoDisallowCommands),Ve?be=!0:(Te||K.autoApproveGit&&/^git\s+commit\b/i.test(lt))&&(ye="allow"),!be&&!ye){if(K.networkAccess===!1){let Qt=lt.trim().replace(/\s+/g," ").replace(/^['"]+|['"]+$/g,"").toLowerCase().split(" "),ct=Qt[0].split("/").pop().split("\\").pop().replace(/\.exe$/,""),Zt=new Set(["curl","wget","httpie","xh","ssh","scp","sftp","rsync","ftp","lftp","tftp","telnet","nc","netcat","socat","ping","traceroute","tracert","dig","nslookup","host","whois","nmap","docker","podman","kubectl","helm","gcloud","aws","az","terraform","ansible-playbook","nix","nix-env","apt","apt-get","dpkg","yum","dnf","pacman","zypper","brew","apk","choco","scoop","conda","mamba","aria2c","axel","smbclient","lynx","w3m","links","elinks","heroku","netlify","vercel","firebase","supabase","wrangler","flyctl","powershell","pwsh","certutil","bitsadmin","cloudflared","ngrok","tailscale","zerotier","rclone"]),dt=!1;Zt.has(ct)&&(dt=!0);let ht=bn=>Qt.slice(1).some(kn=>bn.includes(kn)),vt=bn=>{let kn=Qt.findIndex(Cn=>bn.includes(Cn)),Ss=Qt.findIndex(Cn=>["run","exec","test"].includes(Cn));return kn!==-1&&!(Ss!==-1&&Ss<kn)};ct==="git"&&ht(["clone","pull","push","fetch"])&&(dt=!0),ct==="go"&&ht(["get","install"])&&(dt=!0),ct==="npm"&&vt(["install","i","update","add"])&&(dt=!0),ct==="yarn"&&vt(["add","install","upgrade"])&&(dt=!0),ct==="pnpm"&&vt(["add","install","update"])&&(dt=!0),ct==="bun"&&vt(["add","install","update"])&&(dt=!0),ct==="deno"&&ht(["install","add"])&&(dt=!0),ct==="pip"&&ht(["install","download"])&&(dt=!0),ct==="pip3"&&ht(["install","download"])&&(dt=!0),ct==="cargo"&&ht(["install","add"])&&(dt=!0),["bash","sh","zsh","fish"].includes(ct)&&ht(["-c"])&&(dt=!0),ct==="cmd"&&ht(["/c"])&&(dt=!0),dt&&(ye="deny",Oe=!0)}!ye&&qe&&(ye="deny")}!be&&!ye&&de&&(ye="allow")}else de&&(ye="allow");let Se=ye,ne="";ye==="deny"&&(Oe?ne="network":qe?ne="settings":ne="prohibited");let he=!1,fe="",Be=[],et=0,ke=!1;if(!Se){if(M==="write_file"||M==="update_file")try{let ve=O(q.args),{path:Ve}=ve;if(Ve){let Te=ee.resolve(process.cwd(),Ve),_t=ht=>ht?ht.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,vt=>vt.toUpperCase()):"",Qt=_t(Te),dn="",ct=!1,Zt=await ms(),dt=_t(Zt?.file_focused);if(Zt&&dt===Qt&&Zt.full_content?(dn=Zt.full_content,ct=!0):Pe.existsSync(Te)&&(dn=Pe.readFileSync(Te,"utf8"),ct=!0),fe=dn,await mt.recordFileChange(Te,dn),ct){let ht=dn;if(M==="write_file")ht=ve.content||ve.newContent||"";else{let{patchPairs:vt,allowMultiple:bn,error:kn}=Ao(ve);if(kn){let $t=`[TOOL RESULT]: ERROR: ${kn}`;te.push({role:"user",text:$t}),await Ot("toolFailure"),t.onToolResult&&t.onToolResult("failure",M),yield{type:"tool_result",content:$t,toolName:M},Ge++;continue}let Ss=ve.allowMultiple!==void 0?ve.allowMultiple===!0||String(ve.allowMultiple).toLowerCase()==="true":bn;et=vt.length;let Cn=vo(dn,vt,{allowMultiple:Ss});ht=Cn.content,Be=Cn.results;let yo=Be.filter($t=>$t.success),It=Be.filter($t=>!$t.success);if(yo.length===0){let $t=`[TOOL RESULT]: ERROR: Failed to apply patches to [${ee.basename(Te)}].
664
664
  ${It.map(Hs=>` \u2022 ${Hs.error}`).join(`
665
- `)}`,Ts=`\u2714 Edited: ${ee.basename(Se.replaceAll("\\","/"))}`,js=115;process.stdout.isTTY&&(js=process.stdout.columns-5||120);let Rs=Math.min(Ts.length+4,js),wo=`${Ts.padEnd(Rs-2).substring(0,Rs-2)}`;yield{type:"visual_feedback",content:gn(`${We?`
666
- `:""}${wo}`)},We=!1,te.push({role:"user",text:$t}),await Ot("toolFailure"),t.onToolResult&&t.onToolResult("failure",M),yield{type:"tool_result",content:$t,toolName:M},Ge++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${ee.basename(Se)}`},Yr(Se,dn,ht),ue=!0,await new Promise(vt=>setTimeout(vt,50))}else if(M==="write_file"){let ht=ve.content||ve.newContent||"",vt=ht.endsWith(`
665
+ `)}`,Ts=`\u2714 Edited: ${ee.basename(Te.replaceAll("\\","/"))}`,js=115;process.stdout.isTTY&&(js=process.stdout.columns-5||120);let Rs=Math.min(Ts.length+4,js),wo=`${Ts.padEnd(Rs-2).substring(0,Rs-2)}`;yield{type:"visual_feedback",content:gn(`${We?`
666
+ `:""}${wo}`)},We=!1,te.push({role:"user",text:$t}),await Ot("toolFailure"),t.onToolResult&&t.onToolResult("failure",M),yield{type:"tool_result",content:$t,toolName:M},Ge++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${ee.basename(Te)}`},Yr(Te,dn,ht),he=!0,await new Promise(vt=>setTimeout(vt,50))}else if(M==="write_file"){let ht=ve.content||ve.newContent||"",vt=ht.endsWith(`
667
667
  `)?ht:ht+`
668
- `;Pe.existsSync(Se)||(be=!0,Pe.mkdirSync(ee.dirname(Se),{recursive:!0}),Pe.writeFileSync(Se,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${ee.basename(Se)}`},Yr(Se,"",vt),ue=!0,await new Promise(bn=>setTimeout(bn,50))}}}catch(ve){console.error("Simulation/Diff Error:",ve)}let De=null;Kr(ve=>{De=ve});let lt=t.onToolApproval;if(ke=await new Promise(async ve=>{let Ve=setInterval(()=>{De&&(Wo.onIDEApproval&&Wo.onIDEApproval(De),clearInterval(Ve),ve(De))},100);try{let Se=await lt(M,q.args);clearInterval(Ve),ve(Se)}catch{clearInterval(Ve),ve("deny")}}),Kr(null),M==="write_file"||M==="update_file"){let{path:ve}=O(q.args);if(ve){let Ve=ee.resolve(process.cwd(),ve);if(ka(Ve,ke),ke==="deny"&&be&&Pe.existsSync(Ve))try{Pe.unlinkSync(Ve)}catch{}}}ke==="deny"&&(ne="user")}if(ke==="allow"&&ue&&Uo()){let{path:De}=O(q.args),lt=ee.resolve(process.cwd(),De),ve=It=>It?ee.resolve(It).replace(/\\/g,"/").toLowerCase():"",Ve=await ms(),Se="";Ve&&Ve.file_focused&&ve(Ve.file_focused)===ve(lt)&&Ve.full_content&&(Se=Ve.full_content),!Se&&Pe.existsSync(lt)&&(Se=Pe.readFileSync(lt,"utf8"),Se||(await new Promise(It=>setTimeout(It,100)),Se=Pe.readFileSync(lt,"utf8")));let _t=Se.split(/\r?\n/),Qt=_t.length,dn=Buffer.byteLength(Se,"utf8"),ct="";de&&(ct=`Old File contents:
669
- ${de.split(/\r?\n/).map(($t,Ts)=>`${Ts+1} | ${$t}`).join(`
668
+ `;Pe.existsSync(Te)||(ke=!0,Pe.mkdirSync(ee.dirname(Te),{recursive:!0}),Pe.writeFileSync(Te,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${ee.basename(Te)}`},Yr(Te,"",vt),he=!0,await new Promise(bn=>setTimeout(bn,50))}}}catch(ve){console.error("Simulation/Diff Error:",ve)}let De=null;Kr(ve=>{De=ve});let lt=t.onToolApproval;if(Se=await new Promise(async ve=>{let Ve=setInterval(()=>{De&&(Wo.onIDEApproval&&Wo.onIDEApproval(De),clearInterval(Ve),ve(De))},100);try{let Te=await lt(M,q.args);clearInterval(Ve),ve(Te)}catch{clearInterval(Ve),ve("deny")}}),Kr(null),M==="write_file"||M==="update_file"){let{path:ve}=O(q.args);if(ve){let Ve=ee.resolve(process.cwd(),ve);if(ka(Ve,Se),Se==="deny"&&ke&&Pe.existsSync(Ve))try{Pe.unlinkSync(Ve)}catch{}}}Se==="deny"&&(ne="user")}if(Se==="allow"&&he&&Uo()){let{path:De}=O(q.args),lt=ee.resolve(process.cwd(),De),ve=It=>It?ee.resolve(It).replace(/\\/g,"/").toLowerCase():"",Ve=await ms(),Te="";Ve&&Ve.file_focused&&ve(Ve.file_focused)===ve(lt)&&Ve.full_content&&(Te=Ve.full_content),!Te&&Pe.existsSync(lt)&&(Te=Pe.readFileSync(lt,"utf8"),Te||(await new Promise(It=>setTimeout(It,100)),Te=Pe.readFileSync(lt,"utf8")));let _t=Te.split(/\r?\n/),Qt=_t.length,dn=Buffer.byteLength(Te,"utf8"),ct="";fe&&(ct=`Old File contents:
669
+ ${fe.split(/\r?\n/).map(($t,Ts)=>`${Ts+1} | ${$t}`).join(`
670
670
  `)}
671
671
 
672
672
  `);let Zt="";if(Qt<=100)Zt=_t.join(`
@@ -676,10 +676,10 @@ ${de.split(/\r?\n/).map(($t,Ts)=>`${Ts+1} | ${$t}`).join(`
676
676
 
677
677
  ... [${Qt-100} lines truncated for history stability] ...
678
678
 
679
- ${$t}`}let dt="";if(M==="update_file"){let It=Io(de,Se,Be,12,t?.compressToolResults||Wo?.systemSettings?.compressToolResults);dt=`SUCCESS: File [${De}] updated via IDE Companion (May have user edits). [${Be.length}/${et}] blocks applied.
679
+ ${$t}`}let dt="";if(M==="update_file"){let It=Io(fe,Te,Be,12,t?.compressToolResults||Wo?.systemSettings?.compressToolResults);dt=`SUCCESS: File [${De}] updated via IDE Companion (May have user edits). [${Be.length}/${et}] blocks applied.
680
680
 
681
- ${It}`}else{let It=Se.split(/\r?\n/),$t=It.length,Ts=Buffer.byteLength(Se,"utf8"),js="";de&&(js=`Old File contents:
682
- ${de.split(/\r?\n/).map((Hs,Za)=>`${Za+1} | ${Hs}`).join(`
681
+ ${It}`}else{let It=Te.split(/\r?\n/),$t=It.length,Ts=Buffer.byteLength(Te,"utf8"),js="";fe&&(js=`Old File contents:
682
+ ${fe.split(/\r?\n/).map((Hs,Za)=>`${Za+1} | ${Hs}`).join(`
683
683
  `)}
684
684
 
685
685
  `);let Rs="";if($t<=100)Rs=It.join(`
@@ -694,44 +694,44 @@ ${Hs}`}dt=`SUCCESS: File [${De}] saved via IDE Companion (May have user edits).
694
694
  ${js}- Content Preview:
695
695
 
696
696
  ${Rs}`}let vt=`${De?"\u2714":"\u2718"} ${M==="write_file"?"Created":"Edited"}: ${De.replaceAll("\\","/")||"No File Changes"}`,bn=115;process.stdout.isTTY&&(bn=process.stdout.columns-5||120);let kn=Math.min(vt.length+4,bn),Ss=`${vt.padEnd(kn-2).substring(0,kn-2)}`;yield{type:"visual_feedback",content:gn(`${We?`
697
- `:""}${Ss}`)},We=!1;let Cn=Date.now();z=Cn,yield{type:"tool_time",content:Cn-pe};let yo=`[TOOL RESULT]: ${dt}`;te.push({role:"user",text:yo}),cn=!0,await Ot("toolSuccess"),t.onToolResult&&t.onToolResult("success",M),yield{type:"tool_result",content:dt,aiContent:yo,toolName:M},Ge++;continue}if(ke==="deny"){let De=`Permission Denied: Prohibited ${M==="exec_command"?"Command":"file edit"}.`;if(ne==="user"?De="Permission Denied by User":ne==="settings"?De="Permission Denied by User Policy":ne==="network"?De="Permission Denied: Sandbox Network Access Disabled by User Policy.":ne==="prohibited"&&M==="exec_command"&&(De="Permission Denied: Prohibited Command in User Policy"),M==="write_file"||M==="update_file"){let ve=`\u2718 ${M==="write_file"?"Write Cancelled":"Edit Denied"}: ${O(q.args).path.replaceAll("\\","/")||"..."}`,Ve=115;process.stdout.isTTY&&(Ve=process.stdout.columns-5||120);let Se=Math.min(ve.length+4,Ve),_t=`${ve.padEnd(Se-2).substring(0,Se-2)}`,Qt=` ${" ".repeat(Se)} `;yield{type:"visual_feedback",content:gn(`${We?`
697
+ `:""}${Ss}`)},We=!1;let Cn=Date.now();z=Cn,yield{type:"tool_time",content:Cn-pe};let yo=`[TOOL RESULT]: ${dt}`;te.push({role:"user",text:yo}),cn=!0,await Ot("toolSuccess"),t.onToolResult&&t.onToolResult("success",M),yield{type:"tool_result",content:dt,aiContent:yo,toolName:M},Ge++;continue}if(Se==="deny"){let De=`Permission Denied: Prohibited ${M==="exec_command"?"Command":"file edit"}.`;if(ne==="user"?De="Permission Denied by User":ne==="settings"?De="Permission Denied by User Policy":ne==="network"?De="Permission Denied: Sandbox Network Access Disabled by User Policy.":ne==="prohibited"&&M==="exec_command"&&(De="Permission Denied: Prohibited Command in User Policy"),M==="write_file"||M==="update_file"){let ve=`\u2718 ${M==="write_file"?"Write Cancelled":"Edit Denied"}: ${O(q.args).path.replaceAll("\\","/")||"..."}`,Ve=115;process.stdout.isTTY&&(Ve=process.stdout.columns-5||120);let Te=Math.min(ve.length+4,Ve),_t=`${ve.padEnd(Te-2).substring(0,Te-2)}`,Qt=` ${" ".repeat(Te)} `;yield{type:"visual_feedback",content:gn(`${We?`
698
698
  `:""}${_t}
699
- `)},We=!1}M==="exec_command"&&(await new Promise(lt=>setTimeout(lt,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${De}`),await new Promise(lt=>setTimeout(lt,50)),t.onExecEnd&&t.onExecEnd()),te.push({role:"user",text:`[TOOL RESULT]: DENIED: ${De}`}),yield{type:"tool_result",content:`[TOOL RESULT]: DENIED: ${De}`},await Ot("toolDenied"),t.onToolResult&&t.onToolResult("denied",M),Ge++;continue}}if(Q){let v=115;process.stdout.isTTY&&(v=process.stdout.columns-5||120);let K=Math.min(Q.length+4,v),ce=`${Q.padEnd(K-2).substring(0,K-2)}`;yield{type:"visual_feedback",content:gn(`${We?`
700
- `:""}${ce}${Q.includes("\u2714")&&(Q.includes("Created")||Q.includes("Edited"))?"":`
701
- `}`)},We=!1}if(z>0){let v=Date.now()-z,K=Math.max(0,1e3-v);K>0&&await new Promise(ce=>setTimeout(ce,K))}let Un={chatId:d,history:n,onChunk:v=>t.onExecChunk?t.onExecChunk(v):null,onAskUser:t.onAskUser,systemSettings:t.systemSettings,mode:i,isMultiModal:zt(Te),onVisualFeedback:t.onVisualFeedback,onSubagentUpdate:t.onSubagentUpdate,onTokenChunk:t.onTokenChunk,modelName:Te,aiProvider:t.aiProvider,apiKey:t.apiKey,onUsage:t.onUsage};if(M==="write_file"||M==="update_file")try{let{path:v}=O(q.args);if(v){let K=ee.resolve(process.cwd(),v),ce=await ms();ce&&ce.file_focused===K&&ce.full_content&&(Un.forcedContent=ce.full_content)}}catch{}nn.push(M);let _e=await fo(M,q.args,Un);if((M==="write_file"||M==="update_file")&&_e.startsWith("SUCCESS")){let{path:v}=O(q.args);if(v){let K=ee.resolve(process.cwd(),v);ba(K)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let Gt=Date.now();z=Gt,yield{type:"tool_time",content:Gt-pe},sn=Gt;let Jt=null;if(typeof _e=="object"&&_e.binaryPart&&(Jt=_e.binaryPart,_e=_e.text),M==="search_keyword"){let{keyword:v,path:K}=O(q.args),ce=typeof _e=="string"&&_e.startsWith("[GLOB]");ce&&(_e=_e.slice(6).trimStart());let ye=typeof _e=="string"&&_e.startsWith("[DIR]");ye&&(_e=_e.slice(5).trimStart());let xe=0;if(_e){let Be=_e.match(/Found (\d+) match/i);Be&&(xe=parseInt(Be[1]))}let qe=K?K.replace(/[\/\\]+$/,""):null,Oe=qe&&qe!=="."?`"${ce?K:ye?`${qe}/*`:qe}"`:"./",ke=`${v?"\u2714":"\u2718"} Searched: "${v||""}" in ${Oe.replaceAll("\\","/")} \u2192 ${xe} Match${xe===1?"":"es"}`,ne=115;process.stdout.isTTY&&(ne=process.stdout.columns-5||120);let ue=Math.min(ke.length+4,ne),de=`${ke.padEnd(ue-2).substring(0,ue-2)}`;yield{type:"visual_feedback",content:gn(`${We?`
702
- `:""}${de}
703
- `)},We=!1}if(M==="EmergencyRollback"){let{method:v}=O(q.args);if(v==="forceRevert"){let K=0;if(_e){let ke=_e.match(/Total\s*:\s*(\d+)/i);ke&&(K=parseInt(ke[1]))}let ye=_e&&_e.startsWith("ERROR:")?"\u2718 Emergency Rollback Failed":`\u2714 Emergency Rollback \u2192 ${K} file${K===1?"":"s"} processed`,xe=115;process.stdout.isTTY&&(xe=process.stdout.columns-5||120);let qe=Math.min(ye.length+4,xe),Oe=`${ye.padEnd(qe-2).substring(0,qe-2)}`;yield{type:"visual_feedback",content:gn(`${We?`
699
+ `)},We=!1}M==="exec_command"&&(await new Promise(lt=>setTimeout(lt,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${De}`),await new Promise(lt=>setTimeout(lt,50)),t.onExecEnd&&t.onExecEnd()),te.push({role:"user",text:`[TOOL RESULT]: DENIED: ${De}`}),yield{type:"tool_result",content:`[TOOL RESULT]: DENIED: ${De}`},await Ot("toolDenied"),t.onToolResult&&t.onToolResult("denied",M),Ge++;continue}}if(Q){let v=115;process.stdout.isTTY&&(v=process.stdout.columns-5||120);let K=Math.min(Q.length+4,v),de=`${Q.padEnd(K-2).substring(0,K-2)}`;yield{type:"visual_feedback",content:gn(`${We?`
700
+ `:""}${de}${Q.includes("\u2714")&&(Q.includes("Created")||Q.includes("Edited"))?"":`
701
+ `}`)},We=!1}if(z>0){let v=Date.now()-z,K=Math.max(0,1e3-v);K>0&&await new Promise(de=>setTimeout(de,K))}let Un={chatId:d,history:n,onChunk:v=>t.onExecChunk?t.onExecChunk(v):null,onAskUser:t.onAskUser,systemSettings:t.systemSettings,mode:i,isMultiModal:zt(Re),onVisualFeedback:t.onVisualFeedback,onSubagentUpdate:t.onSubagentUpdate,onTokenChunk:t.onTokenChunk,modelName:Re,aiProvider:t.aiProvider,apiKey:t.apiKey,onUsage:t.onUsage};if(M==="write_file"||M==="update_file")try{let{path:v}=O(q.args);if(v){let K=ee.resolve(process.cwd(),v),de=await ms();de&&de.file_focused===K&&de.full_content&&(Un.forcedContent=de.full_content)}}catch{}nn.push(M);let _e=await fo(M,q.args,Un);if((M==="write_file"||M==="update_file")&&_e.startsWith("SUCCESS")){let{path:v}=O(q.args);if(v){let K=ee.resolve(process.cwd(),v);ba(K)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let Gt=Date.now();z=Gt,yield{type:"tool_time",content:Gt-pe},sn=Gt;let Jt=null;if(typeof _e=="object"&&_e.binaryPart&&(Jt=_e.binaryPart,_e=_e.text),M==="search_keyword"){let{keyword:v,path:K}=O(q.args),de=typeof _e=="string"&&_e.startsWith("[GLOB]");de&&(_e=_e.slice(6).trimStart());let ye=typeof _e=="string"&&_e.startsWith("[DIR]");ye&&(_e=_e.slice(5).trimStart());let be=0;if(_e){let Be=_e.match(/Found (\d+) match/i);Be&&(be=parseInt(Be[1]))}let qe=K?K.replace(/[\/\\]+$/,""):null,Oe=qe&&qe!=="."?`"${de?K:ye?`${qe}/*`:qe}"`:"./",Se=`${v?"\u2714":"\u2718"} Searched: "${v||""}" in ${Oe.replaceAll("\\","/")} \u2192 ${be} Match${be===1?"":"es"}`,ne=115;process.stdout.isTTY&&(ne=process.stdout.columns-5||120);let he=Math.min(Se.length+4,ne),fe=`${Se.padEnd(he-2).substring(0,he-2)}`;yield{type:"visual_feedback",content:gn(`${We?`
702
+ `:""}${fe}
703
+ `)},We=!1}if(M==="EmergencyRollback"){let{method:v}=O(q.args);if(v==="forceRevert"){let K=0;if(_e){let Se=_e.match(/Total\s*:\s*(\d+)/i);Se&&(K=parseInt(Se[1]))}let ye=_e&&_e.startsWith("ERROR:")?"\u2718 Emergency Rollback Failed":`\u2714 Emergency Rollback \u2192 ${K} file${K===1?"":"s"} processed`,be=115;process.stdout.isTTY&&(be=process.stdout.columns-5||120);let qe=Math.min(ye.length+4,be),Oe=`${ye.padEnd(qe-2).substring(0,qe-2)}`;yield{type:"visual_feedback",content:gn(`${We?`
704
704
  `:""}${Oe}
705
- `)},We=!1}}if(M==="todo"){let{method:v,tasks:K,markDone:ce}=O(q.args),ye="",xe=[],qe=Oe=>{if(!Oe)return[];let ke=Array.isArray(Oe)?Oe:[];if(ke.length===0&&typeof Oe=="string"){let ne=Oe.trim();if(ne.startsWith("[")&&ne.endsWith("]")){let ue=ne.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);ue?ke=ue.map(de=>de.slice(1,-1).replace(/\\(.)/g,"$1")):ke=ne.slice(1,-1).split(",").map(de=>de.trim()).filter(Boolean)}else ke=Oe.split(`
706
- `)}return ke.filter(ne=>String(ne).trim()).map(ne=>{let ue=String(ne).trim();return ue.startsWith("- [")?ue.substring(6).trim():ue})};if(v==="create"?(ye="\x1B[32m\u2192\x1B[0m Created Goals",xe=qe(K).map(Oe=>`\x1B[90m\u25CB\x1B[0m ${Oe}`)):v==="append"?(ye="\x1B[34m\u2795\x1B[0m Added New Goals",xe=qe(K).map(Oe=>`\x1B[90m\u25CB\x1B[0m ${Oe}`)):v==="get"&&(ye=ce?"\x1B[36m\u21BB\x1B[0m Updated Goals":"\x1B[35m\u2022\x1B[0m Reviewed Goals",xe=(_e||"").split(`
705
+ `)},We=!1}}if(M==="todo"){let{method:v,tasks:K,markDone:de}=O(q.args),ye="",be=[],qe=Oe=>{if(!Oe)return[];let Se=Array.isArray(Oe)?Oe:[];if(Se.length===0&&typeof Oe=="string"){let ne=Oe.trim();if(ne.startsWith("[")&&ne.endsWith("]")){let he=ne.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);he?Se=he.map(fe=>fe.slice(1,-1).replace(/\\(.)/g,"$1")):Se=ne.slice(1,-1).split(",").map(fe=>fe.trim()).filter(Boolean)}else Se=Oe.split(`
706
+ `)}return Se.filter(ne=>String(ne).trim()).map(ne=>{let he=String(ne).trim();return he.startsWith("- [")?he.substring(6).trim():he})};if(v==="create"?(ye="\x1B[32m\u2192\x1B[0m Created Goals",be=qe(K).map(Oe=>`\x1B[90m\u25CB\x1B[0m ${Oe}`)):v==="append"?(ye="\x1B[34m\u2795\x1B[0m Added New Goals",be=qe(K).map(Oe=>`\x1B[90m\u25CB\x1B[0m ${Oe}`)):v==="get"&&(ye=de?"\x1B[36m\u21BB\x1B[0m Updated Goals":"\x1B[35m\u2022\x1B[0m Reviewed Goals",be=(_e||"").split(`
707
707
  `).slice(1).join(`
708
708
  `).split(`
709
- `).filter(ke=>ke.trim().startsWith("- [")).map(ke=>{let ne=ke.trim(),ue=ne.startsWith("- [x]");return`${ue?"\x1B[32m\u2714\x1B[0m":"\x1B[90m\u25CB\x1B[0m"} ${ue?"\x1B[90m":"\x1B[37m"}${ne.substring(6).trim()}\x1B[0m`})),ye&&xe.length>0){let Oe=[`${ye}`,...xe.map(ke=>` ${ke}`)].join(`
709
+ `).filter(Se=>Se.trim().startsWith("- [")).map(Se=>{let ne=Se.trim(),he=ne.startsWith("- [x]");return`${he?"\x1B[32m\u2714\x1B[0m":"\x1B[90m\u25CB\x1B[0m"} ${he?"\x1B[90m":"\x1B[37m"}${ne.substring(6).trim()}\x1B[0m`})),ye&&be.length>0){let Oe=[`${ye}`,...be.map(Se=>` ${Se}`)].join(`
710
710
  `);yield{type:"visual_feedback",content:gn(`${We?`
711
711
  `:""}${Oe}
712
712
  `)},We=!1}}M==="exec_command"&&t.onExecEnd&&(await new Promise(v=>setTimeout(v,800)),t.onExecEnd());let _n=_e&&_e.startsWith("DENIED:");_e&&!_e.startsWith("ERROR:")&&!_n?(await Ot("toolSuccess"),t.onToolResult&&t.onToolResult("success",M)):_n||(await Ot("toolFailure"),t.onToolResult&&t.onToolResult("failure",M));let qt=(_e||"").toString().replaceAll("[UI_CONTEXT]","");qt.includes("[[VERIFIED]]")&&(qt=qt.replace(/\[\[VERIFIED\]\][\s\S]*?\[\[\/VERIFIED\]\]/g,`[SYSTEM NOTE]: Patch Block matched & applied successfully. Large Block omitted to conserve context.
713
- `));let $n;if(qt.startsWith("[[SAME]]")){let K=qt.replace(/^\[\[SAME\]\]\s*\r?\n?/,"").split(/\r?\n/),ce=K.filter(xe=>xe.startsWith("SUCCESS:")||xe.trim().startsWith("- Stats:"));$n=`[TOOL RESULT]: ${ce.length>0?ce.join(`
713
+ `));let $n;if(qt.startsWith("[[SAME]]")){let K=qt.replace(/^\[\[SAME\]\]\s*\r?\n?/,"").split(/\r?\n/),de=K.filter(be=>be.startsWith("SUCCESS:")||be.trim().startsWith("- Stats:"));$n=`[TOOL RESULT]: ${de.length>0?de.join(`
714
714
  `):K.slice(0,2).join(`
715
715
  `)}
716
716
  [SYSTEM NOTE]: Content verified and persisted to disk. Full preview omitted to conserve context.`}else $n=`[TOOL RESULT]: ${qt}`;te.push({role:"user",text:$n,binaryPart:Jt}),cn=!0;let Ae=`[TOOL RESULT]: ${_e.replaceAll(`[[VERIFIED]]
717
717
  `,"").replaceAll(`
718
- [[/VERIFIED]]`,"")||""}`;(M==="view_file"||M==="web_scrape"||M==="file_map")&&(Ae=`[TOOL RESULT]: ${Q} (Context Locked for UI Clarity)`),yield{type:"tool_result",content:Ae,aiContent:$n,binaryPart:Jt,toolName:M},M==="memory"&&_e.includes("SUCCESS")&&(yield{type:"memory_updated"}),Ge++}if(u==="Google"&&Pt&&Date.now()-Ko>=150){yield*ns();let q=Us(Pt);for(let pe of q)yield pe;Pt="",Ko=Date.now()}}D.usageMetadata&&(Tn=D.usageMetadata),Tn&&(yield{type:"liveTokens",content:Tn.totalTokenCount})}if(he&&(he=!1,jt?Ke+="</think>":(fe+="</think>",u==="Google"?Pt+="</think>":yield{type:"text",content:"</think>"})),jt&&Ke.length>0){let D=0,oe=Math.min(tt.length,Ke.length);for(let H=oe;H>0;H--)if(tt.endsWith(Ke.substring(0,H))){D=H;break}let j=Ke.substring(D);if(j){let we=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(tt)?j.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):j.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(we)if(fe+=we,u==="Google")Pt+=we;else{yield*ns();let ge=Us(we);for(let Ee of ge)yield Ee}}jt=!1,Ke=""}if(yield*ns(),Lt)break;let Ws=(fe||"").trim(),Ka=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(Ws.toLowerCase())||/\[\[END\]\]/i.test(Ws.toLowerCase()),Ya=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(Ws.toLowerCase()),Va=te.length>0||Ut!==null,Yo=Ws.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/gi,"").trim(),Xa=/(\p{Emoji_Presentation}|\p{Extended_Pictographic})$/u.test(Yo),Ja=/([.!?"'*_`|\]\)”’~~]+|\s|`{3}|[\u200B-\u200D\uFEFF])$/u.test(Yo.trim()),Qa=/[.!?}"'`’“”]$|```$/s.test(Yo)||Ja||Xa;!Ka&&!Ya&&!Va&&Ws.length>0,Ze=!0,await Ot("agent",u)}catch(Re){if(Lt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
718
+ [[/VERIFIED]]`,"")||""}`;(M==="view_file"||M==="web_scrape"||M==="file_map")&&(Ae=`[TOOL RESULT]: ${Q} (Context Locked for UI Clarity)`),yield{type:"tool_result",content:Ae,aiContent:$n,binaryPart:Jt,toolName:M},M==="memory"&&_e.includes("SUCCESS")&&(yield{type:"memory_updated"}),Ge++}if(u==="Google"&&Pt&&Date.now()-Ko>=150){yield*ns();let q=Us(Pt);for(let pe of q)yield pe;Pt="",Ko=Date.now()}}D.usageMetadata&&(Tn=D.usageMetadata),Tn&&(yield{type:"liveTokens",content:Tn.totalTokenCount})}if(ue&&(ue=!1,jt?Ke+="</think>":(ce+="</think>",u==="Google"?Pt+="</think>":yield{type:"text",content:"</think>"})),jt&&Ke.length>0){let D=0,oe=Math.min(tt.length,Ke.length);for(let H=oe;H>0;H--)if(tt.endsWith(Ke.substring(0,H))){D=H;break}let j=Ke.substring(D);if(j){let xe=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(tt)?j.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):j.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(xe)if(ce+=xe,u==="Google")Pt+=xe;else{yield*ns();let ge=Us(xe);for(let Ee of ge)yield Ee}}jt=!1,Ke=""}if(yield*ns(),Lt)break;let Ws=(ce||"").trim(),Ka=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(Ws.toLowerCase())||/\[\[END\]\]/i.test(Ws.toLowerCase()),Ya=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(Ws.toLowerCase()),Va=te.length>0||Ut!==null,Yo=Ws.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/gi,"").trim(),Xa=/(\p{Emoji_Presentation}|\p{Extended_Pictographic})$/u.test(Yo),Ja=/([.!?"'*_`|\]\)”’~~]+|\s|`{3}|[\u200B-\u200D\uFEFF])$/u.test(Yo.trim()),Qa=/[.!?}"'`’“”]$|```$/s.test(Yo)||Ja||Xa;!Ka&&!Ya&&!Va&&Ws.length>0,Ze=!0,await Ot("agent",u)}catch(we){if(Lt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
719
719
 
720
- \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(String(Re).includes("Incomplete JSON segment at the end")){he&&(he=!1,jt?Ke+="</think>":(fe+="</think>",yield{type:"text",content:"</think>"})),Ze=!0,await Ot("agent",u);break}if(he&&(he=!1,jt?Ke+="</think>":fe+="</think>"),jt&&Ke.length>0){let Bn=0,Xt=Math.min(tt.length,Ke.length);for(let at=Xt;at>0;at--)if(tt.endsWith(Ke.substring(0,at))){Bn=at;break}let At=Ke.substring(Bn);if(At){let Pt=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(tt)?At.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):At.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");Pt&&(fe+=Pt)}jt=!1,Ke=""}let ie=Re instanceof Error?(()=>{try{return JSON.parse(JSON.parse(Re.message).error.message).error.message}catch{return String(Re)}})():String(Re),st=new Date().toLocaleString(),Mt=ee.join(fn,"agent");Pe.existsSync(Mt)||Pe.mkdirSync(Mt,{recursive:!0}),Pe.appendFileSync(ee.join(Mt,"error.log"),`ERROR [${st}]: ${ie}
720
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(String(we).includes("Incomplete JSON segment at the end")){ue&&(ue=!1,jt?Ke+="</think>":(ce+="</think>",yield{type:"text",content:"</think>"})),Ze=!0,await Ot("agent",u);break}if(ue&&(ue=!1,jt?Ke+="</think>":ce+="</think>"),jt&&Ke.length>0){let Bn=0,Xt=Math.min(tt.length,Ke.length);for(let at=Xt;at>0;at--)if(tt.endsWith(Ke.substring(0,at))){Bn=at;break}let At=Ke.substring(Bn);if(At){let Pt=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(tt)?At.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):At.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");Pt&&(ce+=Pt)}jt=!1,Ke=""}let ie=we instanceof Error?(()=>{try{return JSON.parse(JSON.parse(we.message).error.message).error.message}catch{return String(we)}})():String(we),st=new Date().toLocaleString(),Mt=ee.join(fn,"agent");Pe.existsSync(Mt)||Pe.mkdirSync(Mt,{recursive:!0}),Pe.appendFileSync(ee.join(Mt,"error.log"),`ERROR [${st}]: ${ie}
721
721
 
722
722
  ----------------------------------------------------------------------
723
723
 
724
- `);let on=Re.status||Re.statusCode||Re.code,Et=String(Re).includes("replicas at capacity");if(!(on&&(on>=500&&on<600||on===408||on===429||Et)||!on&&(/status[ :]+(5\d\d|408|429)/i.test(String(Re))||/code[ :]+(5\d\d|408|429)/i.test(String(Re))||/(500|503|408|429)/.test(String(Re))))){if(He<yn-3)throw Re;yield{type:"text",content:ie},yield{type:"status",content:"Error Occured"}}if(fe.trim().length>0||Je>1)if(Je<=yn){Je++;let Bn=Math.min(1e3*Math.pow(2,Je-1),24e3);if(fe.trim().length>0){x.push({role:"agent",text:fe});let Xt=`[system]
724
+ `);let on=we.status||we.statusCode||we.code,Et=String(we).includes("replicas at capacity");if(!(on&&(on>=500&&on<600||on===408||on===429||Et)||!on&&(/status[ :]+(5\d\d|408|429)/i.test(String(we))||/code[ :]+(5\d\d|408|429)/i.test(String(we))||/(500|503|408|429)/.test(String(we))))){if(He<yn-3)throw we;yield{type:"text",content:ie},yield{type:"status",content:"Error Occured"}}if(ce.trim().length>0||Je>1)if(Je<=yn){Je++;let Bn=Math.min(1e3*Math.pow(2,Je-1),24e3);if(ce.trim().length>0){x.push({role:"agent",text:ce});let Xt=`[system]
725
725
  - seamless continuation: resume immediately. pick up from last words with zero gap/disruption
726
726
  - no repetition: do not repeat any text already written
727
727
  - no re-think: do not restart or open <think> if reasoning already started. continue the thinking and close thinking block </think> before chat output
728
728
  - mid-tool safety: if cutoff was mid-tool call, restart that tool call from start
729
729
  - stealth: do not mention/apologize for cutoff [/system]`;te.length>0?te.forEach((At,at)=>{at===te.length-1?x.push({...At,text:`${At.text}
730
730
 
731
- ${Xt}`}):x.push(At)}):x.push({role:"user",text:Xt}),tt+=fe}for(let Xt=Bn/1e3;Xt>0&&!Lt;Xt--)yield{type:"status",content:`Error Occured. Recovering Stream (${Je}/${yn}) [Retrying in ${Xt.toFixed(0)}s]...`},await new Promise(At=>setTimeout(At,1e3));yield{type:"status",content:"Error Occured. Recovering Stream..."}}else throw new Error(`Stream collapsed too many times. (Failed to resolve ${yn} times)
731
+ ${Xt}`}):x.push(At)}):x.push({role:"user",text:Xt}),tt+=ce}for(let Xt=Bn/1e3;Xt>0&&!Lt;Xt--)yield{type:"status",content:`Error Occured. Recovering Stream (${Je}/${yn}) [Retrying in ${Xt.toFixed(0)}s]...`},await new Promise(At=>setTimeout(At,1e3));yield{type:"status",content:"Error Occured. Recovering Stream..."}}else throw new Error(`Stream collapsed too many times. (Failed to resolve ${yn} times)
732
732
  Error log can be found in \`/export logs\``);else if(He<=yn){He++,Je=1,tt="";let Bn=Math.min(1e3*Math.pow(2,He-1),32e3),Xt=.8+Math.random()*.4,At=Math.round(Bn*Xt);Qn=!0,yield{type:"status",content:`Trying to reach ${e} (${He}/${yn}) [Retrying in ${(At/1e3).toFixed(0)}s]`};for(let at=At/1e3;at>0&&!Lt;at--)yield{type:"status",content:`Trying to reach ${e} (${He}/${yn}) [Retrying in ${at.toFixed(0)}s]`},await new Promise(Pt=>setTimeout(Pt,1e3));yield{type:"status",content:`Trying to reach ${e}`}}else throw new Error(`Model ${e} cannot be reached. (Failed ${yn} times)
733
- Error log can be found in \`/export logs\``)}}if(Tn){let he=Tn.totalTokenCount||0,Re=Tn.cachedContentTokenCount||0,ie=(Tn.candidatesTokenCount||0)+(Tn.thoughtsTokenCount||0);await Kt("tokens",he,u,Te),Re>0&&await Kt("cachedTokens",Re,u,Te),ie>0&&await Kt("candidateTokens",ie,u,Te),yield{type:"usage",content:Tn}}yi.push(fe);let Fn=fe;fe.match(/(?:<think>|\[think\])([\s\S]*?)(?:<\/think>|\[\/think\])/i)&&(Fn=fe.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/i,""));let es=va(fe),En=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(es.toLowerCase())||/\[\[END\]\]/i.test(es.toLowerCase())||!0,Nc=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(es.toLowerCase()),Bc=Ge>0;yield{type:"status",content:"Thinking"};let ja=vc(fe,/(\[\s*(turn\s*:)?\s*(continue|finish)\s*\]|\[\[END\]\])/gi,"").trim(),ts=(En||te.length===0)&&!Wt&&!wn&&!Rn;if(ts=te.length===0?ts:!1,ts=Zn||mo?!1:ts,fe&&fe.trim().endsWith('")]')&&te.length===0&&(ts=!1),ts){let he=yi.join(`
734
- `),Re=he.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").trim();yield{type:"interactive_turn_finished",data:{agentText:S,fullAgentTextRaw:he,history:[...x],needTitle:k}},x.length>0&&x[x.length-1].role==="agent"?x[x.length-1].text=Re:x.push({role:"agent",text:Re}),x.forEach(ie=>{if(ie.role==="user"&&ie.text&&(ie.text=ie.text.replace(/\n\[COMPILE ERROR\][\s\S]*?\[\/ERROR\]/g,""),ie.text=ie.text.replaceAll(`
733
+ Error log can be found in \`/export logs\``)}}if(Tn){let ue=Tn.totalTokenCount||0,we=Tn.cachedContentTokenCount||0,ie=(Tn.candidatesTokenCount||0)+(Tn.thoughtsTokenCount||0);await Kt("tokens",ue,u,Re),we>0&&await Kt("cachedTokens",we,u,Re),ie>0&&await Kt("candidateTokens",ie,u,Re),yield{type:"usage",content:Tn}}yi.push(ce);let Fn=ce;ce.match(/(?:<think>|\[think\])([\s\S]*?)(?:<\/think>|\[\/think\])/i)&&(Fn=ce.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/i,""));let es=va(ce),En=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(es.toLowerCase())||/\[\[END\]\]/i.test(es.toLowerCase())||!0,Nc=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(es.toLowerCase()),Bc=Ge>0;yield{type:"status",content:"Thinking"};let ja=vc(ce,/(\[\s*(turn\s*:)?\s*(continue|finish)\s*\]|\[\[END\]\])/gi,"").trim(),ts=(En||te.length===0)&&!Wt&&!wn&&!Rn;if(ts=te.length===0?ts:!1,ts=Zn||mo?!1:ts,ce&&ce.trim().endsWith('")]')&&te.length===0&&(ts=!1),ts){let ue=yi.join(`
734
+ `),we=ue.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").trim();yield{type:"interactive_turn_finished",data:{agentText:S,fullAgentTextRaw:ue,history:[...x],needTitle:k}},x.length>0&&x[x.length-1].role==="agent"?x[x.length-1].text=we:x.push({role:"agent",text:we}),x.forEach(ie=>{if(ie.role==="user"&&ie.text&&(ie.text=ie.text.replace(/\n\[COMPILE ERROR\][\s\S]*?\[\/ERROR\]/g,""),ie.text=ie.text.replaceAll(`
735
735
 
736
736
  [system] user question. resolve this specific query within '[ANSWER] ... [/ANSWER]' concisely, naturally [/system]
737
737
  `,"").replaceAll(`[system] user question. resolve this specific query within '[ANSWER] ... [/ANSWER]' concisely, naturally
@@ -739,17 +739,17 @@ Error log can be found in \`/export logs\``)}}if(Tn){let he=Tn.totalTokenCount||
739
739
  `,"").replaceAll(`[system] **strictly follow thinking policy as high priority. do not start a response without <think>...</think>** [/system]
740
740
  `,"").replaceAll(/\n\[system\] WARNING, Turn Limit Impending: Step \d+\/\d+\. Wrap up quickly\/prompt user to continue & use \[\[END\]\] quickly\. \[\/system\]/g,""),ie.text=ie.text.replaceAll(/\n\[system\] File Changes:\n(?:\* .+ \(created|modified|deleted\)\n)*\[\/system\]/g,""),(u==="Mistral"||u==="Google"&&e?.toLowerCase().startsWith("gemma"))&&ie.text.startsWith("[TOOL RESULT]"))){let Mt=`
741
741
  [system] Tool result received. Analyze output and proceed with your turn [/system]`,on=`
742
- [system] Tool result received. Analyze output and proceed with your turn. **strictly follow thinking policy. do not start a response without <think>...</think>** [/system]`;ie.text=ie.text.replaceAll(on,"").replaceAll(Mt,"").trim()}}),yield{type:"status",content:"[end]"}}if(ts)break;let Ha=ja.trim()||"*Working...*";if(x.push({role:"agent",text:Ha}),te.length>0||cn){if(te.length>0){let he=te.map(Mt=>Mt.text).join(`
742
+ [system] Tool result received. Analyze output and proceed with your turn. **strictly follow thinking policy. do not start a response without <think>...</think>** [/system]`;ie.text=ie.text.replaceAll(on,"").replaceAll(Mt,"").trim()}}),yield{type:"status",content:"[end]"}}if(ts)break;let Ha=ja.trim()||"*Working...*";if(x.push({role:"agent",text:Ha}),te.length>0||cn){if(te.length>0){let ue=te.map(Mt=>Mt.text).join(`
743
743
 
744
- `),ie=(fe.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/gi,"").match(/\[tool:functions/g)||[]).length;if(te.length<ie){he+=`
744
+ `),ie=(ce.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/gi,"").match(/\[tool:/g)||[]).length;if(te.length<ie){ue+=`
745
745
 
746
- [SYSTEM] Only ${te.length} out of ${ie} attempted tool calls were executed. Verify proper schema compliance & try failed calls again [/SYSTEM]`;let Mt=ie-te.length;for(let on=0;on<Mt;on++)await Ot("toolFailure")}let st=te.find(Mt=>Mt.binaryPart)?.binaryPart||null;x.push({role:"user",text:he,binaryPart:st})}}else mo||Zn?(x.push({role:"user",text:"[SYSTEM] Failed to execute some tools. Verify proper schema compliance & try again [/SYSTEM]"}),await Ot("toolFailure")):x.push({role:"user",text:`[SYSTEM] ${wn&&!Wt?"STUTTERING DETECTED by Internal System. Re-calibrate your response & proceed.":`${Wt?" OVER THINKING":" LOOP"} DETECTED by Internal System${Wt?" for current EFFORT_LEVEL":""}. ${Wt?"If you have planned the task, prioritize execution/output":"If you have finished your task provide a simple summary and end"}`} [/SYSTEM]`}),Wt=!1,wn=!1,Rn=!1;l?.advanceRollback&&await Kn.recordTurnDelta(d,G+1,nn),mo=Ge>0||cn}}catch(E){let C=(E instanceof Error?(()=>{try{return JSON.parse(JSON.parse(E.message).error.message).error.message}catch{return E.message||String(E)}})():String(E)).replace(/^(Error:\s*)+/i,""),I=new Date().toLocaleString(),L=ee.join(fn,"agent");yield{type:"text",content:`\u2726 CRITICAL ERROR: ${C.includes("fetch failed")?"Failed to Connect. Check your Internet Connection or Wait a moment":C}
746
+ [system] Only ${te.length} out of ${ie} attempted tool calls were executed. Verify proper schema compliance & try failed calls again [/system]`;let Mt=ie-te.length;for(let on=0;on<Mt;on++)await Ot("toolFailure")}let st=te.find(Mt=>Mt.binaryPart)?.binaryPart||null;x.push({role:"user",text:ue,binaryPart:st})}}else{let we=(ce.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/gi,"").match(/\[tool:/g)||[]).length;mo||Zn||we>0?(x.push({role:"user",text:`[system] Failed to execute ${we} tool${we>1?"s":""}. Verify proper schema compliance & try again [/system]`}),await Ot("toolFailure")):x.push({role:"user",text:`[system] ${wn&&!Wt?"STUTTERING DETECTED by Internal System. Re-calibrate your response & proceed.":`${Wt?" OVER THINKING":" LOOP"} DETECTED by Internal System${Wt?" for current EFFORT_LEVEL":""}. ${Wt?"If you have planned the task, prioritize execution/output":"If you have finished your task provide a simple summary and end"}`} [/system]`}),Wt=!1,wn=!1,Rn=!1}l?.advanceRollback&&await Kn.recordTurnDelta(d,G+1,nn),mo=Ge>0||cn}}catch(E){let C=(E instanceof Error?(()=>{try{return JSON.parse(JSON.parse(E.message).error.message).error.message}catch{return E.message||String(E)}})():String(E)).replace(/^(Error:\s*)+/i,""),I=new Date().toLocaleString(),L=ee.join(fn,"agent");yield{type:"text",content:`\u2726 CRITICAL ERROR: ${C.includes("fetch failed")?"Failed to Connect. Check your Internet Connection or Wait a moment":C}
747
747
  \u2800`},Pe.existsSync(L)||Pe.mkdirSync(L,{recursive:!0}),Pe.appendFileSync(ee.join(L,"error.log"),`CRITICAL ERROR [${I}]: ${E}
748
748
 
749
749
  ----------------------------------------------------------------------
750
750
 
751
751
  `),typeof flushGoogleBuffer=="function"&&(yield*flushGoogleBuffer()),yield{type:"tool_result",content:`ERROR: [INTERNAL CRITICAL] ${C}`}}finally{_&&(clearInterval(_),_=null),typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),await mt.commitTransaction(),l?.advanceRollback&&await Kn.cleanup(d),await ms()}yield{type:"status",content:null}},Im=async(e,n,t=null,o=null,s=50,r=null,a=!1)=>{let i=await Ft(),p={...i,...n},d=process.env.SUBAGENT_MODEL?process.env.SUBAGENT_MODEL.trim():null,c=process.env.SUBAGENT_PROVIDER?process.env.SUBAGENT_PROVIDER.trim():null,l=new Date,f=`${l.getFullYear()}-${l.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(l.getDate()).padStart(2,"0")}, ${l.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}).replace(":","-")}`,h=(E=>{if(!E)return null;let x=E.toLowerCase();return x==="google"?"Google":x==="deepseek"?"DeepSeek":x==="openrouter"?"OpenRouter":x==="nvidia"?"NVIDIA":x==="mistral"?"Mistral":x==="ollama"?"Ollama":x==="crofai"||x==="crof"?"CrofAI":x==="inferx"?"InferX":x==="sensenova"?"SenseNova":null})(c),g=p?.systemSettings?.CustomSubAgent?p?.systemSettings?.SubAgentModel:null,y=p?.systemSettings?.CustomSubAgent?p?.systemSettings?.SubAgentProvider:null,m=null;if(g==="ENV"?(m=d,d&&h&&(p.aiProvider=h)):g&&g!=="Default"?(m=g,y&&(p.aiProvider=y)):d&&h&&(p.aiProvider=h),p.aiProvider){let E=await Qo(p.aiProvider);E&&(p.apiKey=E)}let w=E=>{if(!E||typeof E!="string")return{allowed:!0};let x=[/rm\s+-[rf]{1,2}\s+[\/*.]/i,/rmdir\s+\/[sq]/i,/del\s+\/[fsq]/i,/\bformat\b\s+[a-z]:/i,/mkfs/i,/dd\s+if=/i,/\b(shutdown|reboot|poweroff|init\s+0|init\s+6)\b/i,/chmod\s+(-R\s+)?777\s+[\/*.]/i,/chown\s+(-R\s+)?root/i,/git\s+push\s+.*--force/i,/git\s+clean\s+-fdx/i,/\bsudo\s+su\b/i,/\bsu\s+-\b/i];for(let C of x)if(C.test(E))return{allowed:!1,reason:`Blocked potentially destructive or unsafe command pattern: "${C.source}"`};return{allowed:!0}},b=t||m||n?.modelName||n?.activeModel||i.activeModel,T=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",$=`-- TOOL DEFINITIONS (path = relative to CWD, path separator: '/') --
752
- You cant execute tools. To call tools, must output exactly [tool:functions.ToolName(arg1="value1")] structured string in chat response \u2190 no exception, verify correct syntax/brackets
752
+ You cant execute tools. To use tools, must output exactly [tool:functions.ToolName(arg1="value1")] structured string in chat response \u2190 no exception, tool:functions must
753
753
  Tool Rules:
754
754
  - JSON escape literal escape sequences in tool arguments
755
755
  - Same file, multiple edits? ONE PatchFile (\u226415 blocks) \u2190 Priority
@@ -767,25 +767,25 @@ Tool Rules:
767
767
  ${a?'- AskMain(question="..."). Communicate with PARENT/MAIN AGENT. When clarification/decision is needed for a task':""}
768
768
 
769
769
  **Web Tools**
770
- - WebSearch(query="...", aiMode="bool", limit="integer 3-10 aiMode: exclude"). Proactive use for unknown info/docs. aiMode: LLM search
770
+ - WebSearch(query="...", aiMode="bool, optional", limit="integer 3-10 aiMode: exclude"). Proactive use for unknown info/docs. aiMode: LLM search
771
771
  - WebScrape(url="..."). Proactive use for specific webpage/docs/api
772
772
 
773
773
  **Workspace Tools**
774
- - CodeSearch(keyword="...", path="dir/file/glob/regex, inclusion/exclusion ;-separated", fuzzy="bool false", regex="bool auto"). Find definitions, logic, relevant code, standard junk auto-excluded
774
+ - CodeSearch(keyword="...", path="dir/file/glob/regex, inclusion/exclusion ;-separated", fuzzy="bool, false", regex="bool, auto"). Find definitions, logic, relevant code, standard junk auto-excluded
775
775
  - ReadFolder(path="...", recurse="int 1-3"). Minimize recursion
776
776
  - ReadFile(path="...", startLine="int", endLine="int")
777
- - PatchFile(path="...", allowMultiple="bool, default: false", searchContent1="search string OR ^LINE:start..end$", newContent1="...", ...MAX15). Use small searchContent. Line Ranges must for large searchContent and escape sequences. ^...$ must for line ranges
777
+ - PatchFile(path="...", allowMultiple="bool, false", searchContent1="search string OR ^LINE:start..end$", newContent1="...", ...MAX15). Use small searchContent. Line Ranges must for large searchContent and escape sequences. ^...$ must for line ranges
778
778
  - WriteFile(path="...", content="..."). Creates/Overwrites. File Exist? PatchFile > WriteFile. VERIFY IMPORTS
779
779
  - Run(command="..."). Runs ${T==="Windows"?Hn()?"powershell":"windows CMD":"bash"} command. Destructive/Irreversible ops \u2192 Ask user`.trim(),R=`=== START SYSTEM PROMPT ===
780
- You are a subagent helping the main FluxFlow CLI agent
780
+ Identity: FluxFlow subagent helping the main Agent
781
781
  Your task is: "${e}"
782
782
 
783
783
  ${$.trimEnd()}
784
784
 
785
785
  -- THINKING GUIDANCE --
786
786
  NO EXPLICIT THINKING REQUIRED. FOCUS ON TASK COMPLETION
787
- Keep main focus on tools and task, not chatting
788
- On task completion, provide a detailed structured summary preferebly in Tables/Bullet Points with file modified info, if any task failed report back in detail, NO HALLUCINATIONS
787
+ Main focus: tools and task, not chatting
788
+ On completion, provide a detailed summary in Tables/Markdown Format with file modified info. If any task failed report back in detail
789
789
 
790
790
  CWD: ${process.cwd()}
791
791
  Current Time: ${f}
package/dist/cli.js CHANGED
@@ -57,4 +57,4 @@ Usage: fluxflow --export error`),process.exit(1)}if(T&&(console.log(`v${u}`),pro
57
57
  /docs View documentation
58
58
  /fluxflow init Create FluxFlow.md template
59
59
  /update check Check for new version
60
- /update latest Install latest release`),process.exit(0)),R){let h=t[1]||"latest";if(h==="check"){let i=t[2]==="latest";try{let f=(await(await fetch("https://registry.npmjs.org/fluxflow-cli",{cache:"no-store"})).json())["dist-tags"]?.latest;f||(console.error("Error: Could not retrieve latest version."),process.exit(1)),console.log(i?`Latest version: v${f}`:f!==u?`A new version of FluxFlow is available: v${f} (current: v${u}). Run "fluxflow --update latest" to upgrade.`:`FluxFlow is up to date (v${u}).`)}catch(l){console.error("Error checking for updates:",l.message),process.exit(1)}process.exit(0)}else if(h==="latest"){console.log("Checking latest version and settings...");try{let r=(await(await fetch("https://registry.npmjs.org/fluxflow-cli",{cache:"no-store"})).json())["dist-tags"]?.latest;r||(console.error("Error: Could not retrieve latest version."),process.exit(1)),r===u&&(console.log(`FluxFlow is already up to date (v${u}).`),process.exit(0));let f=async()=>{let o=(await import("react")).default,{useState:$}=o,{render:q,Box:g,Text:w}=await import("ink"),z=(await import("ink-select-input")).default,J=(await import("ink-text-input")).default;return new Promise(K=>{let Q=[{label:"NPM",value:"npm"},{label:"PNPM",value:"pnpm"},{label:"Yarn",value:"yarn"},{label:"Bun",value:"bun"},{label:"Custom Command",value:"custom"}],Z=({label:v,isSelected:b})=>o.createElement(g,{width:"100%"},o.createElement(w,{bold:b},"\u2514\u2500 ",b?"\x1B[32m\u25CF\x1B[0m":"\u25CB"," ",v)),A,ee=()=>{let[v,b]=$("select"),[te,se]=$(""),re=E=>{E.value==="custom"?b("custom"):B({manager:E.value})},ae=E=>{B({manager:"custom",customCommand:E})};return v==="custom"?o.createElement(g,{flexDirection:"column",marginY:1},o.createElement(g,{marginBottom:1},o.createElement(w,{color:"magenta",bold:!0},"\u{1F527} Enter custom update command:")),o.createElement(g,{flexDirection:"row"},o.createElement(w,{color:"cyan",bold:!0}," \u276F "),o.createElement(J,{value:te,onChange:se,onSubmit:ae})),o.createElement(g,{marginTop:1},o.createElement(w,{color:"gray",dimColor:!0,italic:!0}," (Press Enter to confirm)"))):o.createElement(g,{flexDirection:"column",marginY:1},o.createElement(g,{marginBottom:1},o.createElement(w,{color:"magenta",bold:!0},"\u{1F4E6} Select a package manager for the update:")),o.createElement(z,{items:Q,onSelect:re,itemComponent:Z,indicatorComponent:()=>null}))},B=v=>{A&&A(),K(v)},{unmount:oe}=q(o.createElement(ee,null));A=oe})},c,N="",M;try{let{loadSettings:o}=await import("./chunks/settings-NKBYU2YV.js");M=await o(),c=M?.systemSettings?.updateManager||M?.updateManager}catch{}if(!c){let o=await f();c=o.manager,N=o.customCommand}let d="";c==="pnpm"?d=`pnpm add -g fluxflow-cli@${r}`:c==="bun"?d=`bun add -g fluxflow-cli@${r}`:c==="yarn"?d=`yarn global add fluxflow-cli@${r}`:c==="custom"?d=N||M?.customUpdateCommand||`npm install -g fluxflow-cli@${r}`:d=`npm install -g fluxflow-cli@${r}`,console.log(`Updating FluxFlow to v${r} using ${c}...`),console.log(`Running: ${d}`);let{execSync:X}=await import("child_process");X(d,{stdio:"inherit"}),console.log(`\x1B[32m\u2705 Update successful! FluxFlow updated to v${r}.\x1B[0m`)}catch(i){console.error("\x1B[31m\u274C Update failed:\x1B[0m",i.message),process.exit(1)}process.exit(0)}else console.error("Unknown update command. Available options: --update, --update check, --update check latest, --update latest"),process.exit(1)}}let{default:U}=await import("react"),{render:j}=await import("ink"),{default:Y}=await import("./chunks/app-EDUR247Z.js");process.env.NODE_NO_WARNINGS="1";let G=["cuimp","Found existing binary","Binary verified","curl.exe not found","Falling back to .bat file","DeprecationWarning"],H=console.log,W=console.warn,V=console.error,S=e=>{let a=e.map(String).join(" ");return G.some(n=>a.includes(n))};console.log=(...e)=>!S(e)&&H(...e),console.warn=(...e)=>!S(e)&&W(...e),console.error=(...e)=>!S(e)&&V(...e);let C=t.findIndex(e=>e==="--cwd"||e==="--path");if(C!==-1&&C+1<t.length){let e=t[C+1],a=await import("path"),n=await import("fs-extra"),p=a.default.resolve(e);try{n.default.existsSync(p)&&n.default.statSync(p).isDirectory()?process.chdir(p):(console.error(`[ERROR] Directory not found: "${e}"`),process.exit(0))}catch(x){console.error(`[ERROR] Failed to change directory to "${e}": ${x.message}`),process.exit(0)}}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"),process.stdout.write("\x1B[?2004h"));let I=()=>{process.stdout.isTTY&&process.stdout.write("\x1B[?2004l")};if(process.on("exit",I),["SIGINT","SIGTERM","SIGHUP"].forEach(e=>{process.once(e,()=>{I(),process.exit(0)})}),t.includes("--playground")){let e=process.cwd();process.argv.push("--original-cwd",e);let{DATA_DIR:a}=await import("./chunks/paths-R3DD7CRF.js"),n=await import("path"),p=await import("fs-extra"),x=n.default.join(a,"playground");try{p.default.ensureDirSync(x),process.chdir(x)}catch{}}j(U.createElement(Y,{args:process.argv.slice(2)}),{exitOnCtrlC:!1})}
60
+ /update latest Install latest release`),process.exit(0)),R){let h=t[1]||"latest";if(h==="check"){let i=t[2]==="latest";try{let f=(await(await fetch("https://registry.npmjs.org/fluxflow-cli",{cache:"no-store"})).json())["dist-tags"]?.latest;f||(console.error("Error: Could not retrieve latest version."),process.exit(1)),console.log(i?`Latest version: v${f}`:f!==u?`A new version of FluxFlow is available: v${f} (current: v${u}). Run "fluxflow --update latest" to upgrade.`:`FluxFlow is up to date (v${u}).`)}catch(l){console.error("Error checking for updates:",l.message),process.exit(1)}process.exit(0)}else if(h==="latest"){console.log("Checking latest version and settings...");try{let r=(await(await fetch("https://registry.npmjs.org/fluxflow-cli",{cache:"no-store"})).json())["dist-tags"]?.latest;r||(console.error("Error: Could not retrieve latest version."),process.exit(1)),r===u&&(console.log(`FluxFlow is already up to date (v${u}).`),process.exit(0));let f=async()=>{let o=(await import("react")).default,{useState:$}=o,{render:q,Box:g,Text:w}=await import("ink"),z=(await import("ink-select-input")).default,J=(await import("ink-text-input")).default;return new Promise(K=>{let Q=[{label:"NPM",value:"npm"},{label:"PNPM",value:"pnpm"},{label:"Yarn",value:"yarn"},{label:"Bun",value:"bun"},{label:"Custom Command",value:"custom"}],Z=({label:v,isSelected:b})=>o.createElement(g,{width:"100%"},o.createElement(w,{bold:b},"\u2514\u2500 ",b?"\x1B[32m\u25CF\x1B[0m":"\u25CB"," ",v)),A,ee=()=>{let[v,b]=$("select"),[te,se]=$(""),re=E=>{E.value==="custom"?b("custom"):B({manager:E.value})},ae=E=>{B({manager:"custom",customCommand:E})};return v==="custom"?o.createElement(g,{flexDirection:"column",marginY:1},o.createElement(g,{marginBottom:1},o.createElement(w,{color:"magenta",bold:!0},"\u{1F527} Enter custom update command:")),o.createElement(g,{flexDirection:"row"},o.createElement(w,{color:"cyan",bold:!0}," \u276F "),o.createElement(J,{value:te,onChange:se,onSubmit:ae})),o.createElement(g,{marginTop:1},o.createElement(w,{color:"gray",dimColor:!0,italic:!0}," (Press Enter to confirm)"))):o.createElement(g,{flexDirection:"column",marginY:1},o.createElement(g,{marginBottom:1},o.createElement(w,{color:"magenta",bold:!0},"\u{1F4E6} Select a package manager for the update:")),o.createElement(z,{items:Q,onSelect:re,itemComponent:Z,indicatorComponent:()=>null}))},B=v=>{A&&A(),K(v)},{unmount:oe}=q(o.createElement(ee,null));A=oe})},c,N="",M;try{let{loadSettings:o}=await import("./chunks/settings-NKBYU2YV.js");M=await o(),c=M?.systemSettings?.updateManager||M?.updateManager}catch{}if(!c){let o=await f();c=o.manager,N=o.customCommand}let d="";c==="pnpm"?d=`pnpm add -g fluxflow-cli@${r}`:c==="bun"?d=`bun add -g fluxflow-cli@${r}`:c==="yarn"?d=`yarn global add fluxflow-cli@${r}`:c==="custom"?d=N||M?.customUpdateCommand||`npm install -g fluxflow-cli@${r}`:d=`npm install -g fluxflow-cli@${r}`,console.log(`Updating FluxFlow to v${r} using ${c}...`),console.log(`Running: ${d}`);let{execSync:X}=await import("child_process");X(d,{stdio:"inherit"}),console.log(`\x1B[32m\u2705 Update successful! FluxFlow updated to v${r}.\x1B[0m`)}catch(i){console.error("\x1B[31m\u274C Update failed:\x1B[0m",i.message),process.exit(1)}process.exit(0)}else console.error("Unknown update command. Available options: --update, --update check, --update check latest, --update latest"),process.exit(1)}}let{default:U}=await import("react"),{render:j}=await import("ink"),{default:Y}=await import("./chunks/app-JVGRQ3GW.js");process.env.NODE_NO_WARNINGS="1";let G=["cuimp","Found existing binary","Binary verified","curl.exe not found","Falling back to .bat file","DeprecationWarning"],H=console.log,W=console.warn,V=console.error,S=e=>{let a=e.map(String).join(" ");return G.some(n=>a.includes(n))};console.log=(...e)=>!S(e)&&H(...e),console.warn=(...e)=>!S(e)&&W(...e),console.error=(...e)=>!S(e)&&V(...e);let C=t.findIndex(e=>e==="--cwd"||e==="--path");if(C!==-1&&C+1<t.length){let e=t[C+1],a=await import("path"),n=await import("fs-extra"),p=a.default.resolve(e);try{n.default.existsSync(p)&&n.default.statSync(p).isDirectory()?process.chdir(p):(console.error(`[ERROR] Directory not found: "${e}"`),process.exit(0))}catch(x){console.error(`[ERROR] Failed to change directory to "${e}": ${x.message}`),process.exit(0)}}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"),process.stdout.write("\x1B[?2004h"));let I=()=>{process.stdout.isTTY&&process.stdout.write("\x1B[?2004l")};if(process.on("exit",I),["SIGINT","SIGTERM","SIGHUP"].forEach(e=>{process.once(e,()=>{I(),process.exit(0)})}),t.includes("--playground")){let e=process.cwd();process.argv.push("--original-cwd",e);let{DATA_DIR:a}=await import("./chunks/paths-R3DD7CRF.js"),n=await import("path"),p=await import("fs-extra"),x=n.default.join(a,"playground");try{p.default.ensureDirSync(x),process.chdir(x)}catch{}}j(U.createElement(Y,{args:process.argv.slice(2)}),{exitOnCtrlC:!1})}
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "version": 0,
3
- "release": 20260823,
3
+ "release": 20260824,
4
4
  "fallbacks": {
5
5
  "janitor_default": "gemini-3.1-flash-lite",
6
6
  "janitor_attempts_fallback": "gemma-4-26b-a4b-it",
@@ -492,6 +492,15 @@
492
492
  "multimodal": false,
493
493
  "desc": "Text Only"
494
494
  },
495
+ {
496
+ "cmd": "--- Moonshot Models ---",
497
+ "desc": ""
498
+ },
499
+ {
500
+ "cmd": "moonshotai/kimi-k3",
501
+ "multimodal": true,
502
+ "desc": "Multimodal"
503
+ },
495
504
  {
496
505
  "cmd": "\n--- StepFun Models ---",
497
506
  "desc": ""
@@ -529,24 +538,6 @@
529
538
  "multimodal": false,
530
539
  "desc": "Text Only"
531
540
  },
532
- {
533
- "cmd": "\n--- Z-AI Models ---",
534
- "desc": ""
535
- },
536
- {
537
- "cmd": "z-ai/glm-5.2",
538
- "multimodal": false,
539
- "desc": "Text Only"
540
- },
541
- {
542
- "cmd": "\n--- MiniMax Models ---",
543
- "desc": ""
544
- },
545
- {
546
- "cmd": "minimaxai/minimax-m3",
547
- "multimodal": false,
548
- "desc": "Text Only"
549
- },
550
541
  {
551
542
  "cmd": "\n--- NVIDIA Models ---",
552
543
  "desc": ""
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fluxflow-cli",
3
- "version": "4.3.4",
3
+ "version": "4.3.6",
4
4
  "date": "2026-08-23",
5
5
  "description": "A High-Fidelity Agentic CLI with Sub-Agents for the Flux Era. Now has Computer Use.",
6
6
  "keywords": [
package/model_config.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "version": 0,
3
- "release": 20260823,
3
+ "release": 20260824,
4
4
  "fallbacks": {
5
5
  "janitor_default": "gemini-3.1-flash-lite",
6
6
  "janitor_attempts_fallback": "gemma-4-26b-a4b-it",
@@ -492,6 +492,15 @@
492
492
  "multimodal": false,
493
493
  "desc": "Text Only"
494
494
  },
495
+ {
496
+ "cmd": "--- Moonshot Models ---",
497
+ "desc": ""
498
+ },
499
+ {
500
+ "cmd": "moonshotai/kimi-k3",
501
+ "multimodal": true,
502
+ "desc": "Multimodal"
503
+ },
495
504
  {
496
505
  "cmd": "\n--- StepFun Models ---",
497
506
  "desc": ""
@@ -529,24 +538,6 @@
529
538
  "multimodal": false,
530
539
  "desc": "Text Only"
531
540
  },
532
- {
533
- "cmd": "\n--- Z-AI Models ---",
534
- "desc": ""
535
- },
536
- {
537
- "cmd": "z-ai/glm-5.2",
538
- "multimodal": false,
539
- "desc": "Text Only"
540
- },
541
- {
542
- "cmd": "\n--- MiniMax Models ---",
543
- "desc": ""
544
- },
545
- {
546
- "cmd": "minimaxai/minimax-m3",
547
- "multimodal": false,
548
- "desc": "Text Only"
549
- },
550
541
  {
551
542
  "cmd": "\n--- NVIDIA Models ---",
552
543
  "desc": ""
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fluxflow-cli",
3
- "version": "4.3.4",
3
+ "version": "4.3.6",
4
4
  "date": "2026-08-23",
5
5
  "description": "A High-Fidelity Agentic CLI with Sub-Agents for the Flux Era. Now has Computer Use.",
6
6
  "keywords": [