fluxflow-cli 4.1.3 → 4.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/dist/chunks/{ai-5HGOLEFE.js → ai-M2MAGATC.js} +1 -1
- package/dist/chunks/{app-AIAYUYQP.js → app-NQODWWNA.js} +1 -1
- package/dist/chunks/{chunk-A6RZ4EIR.js → chunk-CQ2U3S2O.js} +254 -254
- package/dist/cli.js +1 -1
- package/dist/model_config.json +6 -1
- package/dist/package.json +1 -1
- package/model_config.json +6 -1
- package/package.json +1 -1
- package/dist/chunks/ai-7J7CL56L.js +0 -1
- package/dist/chunks/ai-7LT7T34E.js +0 -1
- package/dist/chunks/ai-ACFJ2D4K.js +0 -1
- package/dist/chunks/ai-CQ6R662V.js +0 -1
- package/dist/chunks/ai-GO5NYAPZ.js +0 -1
- package/dist/chunks/ai-GUVZR6ZJ.js +0 -1
- package/dist/chunks/ai-IGHYVKEI.js +0 -1
- package/dist/chunks/ai-IOVX3WCN.js +0 -1
- package/dist/chunks/ai-LFC7GPK6.js +0 -1
- package/dist/chunks/ai-LUAK6ZNI.js +0 -1
- package/dist/chunks/ai-NDNZ4XGW.js +0 -1
- package/dist/chunks/ai-O2AHKT2Q.js +0 -1
- package/dist/chunks/ai-OLHI3UWZ.js +0 -1
- package/dist/chunks/ai-OP2H56UR.js +0 -1
- package/dist/chunks/ai-OX4W3MY2.js +0 -1
- package/dist/chunks/ai-SUNZIUAF.js +0 -1
- package/dist/chunks/ai-T2SZGY7Y.js +0 -1
- package/dist/chunks/ai-VMV4EAEQ.js +0 -1
- package/dist/chunks/app-2BDYKT26.js +0 -226
- package/dist/chunks/app-2MCTW3BU.js +0 -226
- package/dist/chunks/app-4M34YBXM.js +0 -223
- package/dist/chunks/app-4VRQVBXL.js +0 -226
- package/dist/chunks/app-5YW3SESE.js +0 -223
- package/dist/chunks/app-62A6ZFYX.js +0 -226
- package/dist/chunks/app-A6HECULK.js +0 -223
- package/dist/chunks/app-A6JFAZBR.js +0 -220
- package/dist/chunks/app-AASWJUCP.js +0 -226
- package/dist/chunks/app-AHIXABRK.js +0 -220
- package/dist/chunks/app-CK5GTF3V.js +0 -230
- package/dist/chunks/app-CTJKY73V.js +0 -223
- package/dist/chunks/app-DJWNDFPK.js +0 -223
- package/dist/chunks/app-DLGENJXK.js +0 -226
- package/dist/chunks/app-DU2VBIDN.js +0 -223
- package/dist/chunks/app-EKHVG5CH.js +0 -220
- package/dist/chunks/app-FJJPTQG7.js +0 -223
- package/dist/chunks/app-FVACY6W2.js +0 -230
- package/dist/chunks/app-GY2S4P3O.js +0 -220
- package/dist/chunks/app-HE22VKVY.js +0 -223
- package/dist/chunks/app-HW6KINDL.js +0 -226
- package/dist/chunks/app-II7PE7RS.js +0 -230
- package/dist/chunks/app-MPYGQO5K.js +0 -223
- package/dist/chunks/app-MWWVPJVZ.js +0 -223
- package/dist/chunks/app-OIIPCXZF.js +0 -226
- package/dist/chunks/app-QCQTUW4S.js +0 -223
- package/dist/chunks/app-QPPCSI4B.js +0 -223
- package/dist/chunks/app-RDSYUUGS.js +0 -228
- package/dist/chunks/app-SWVHXTUU.js +0 -223
- package/dist/chunks/app-TSUKVNLY.js +0 -223
- package/dist/chunks/app-WWNOUK7Q.js +0 -220
- package/dist/chunks/app-XTDZID37.js +0 -228
- package/dist/chunks/app-YCFZG7ZN.js +0 -223
- package/dist/chunks/app-ZUY2BADH.js +0 -226
- package/dist/chunks/chunk-2FKXQDRX.js +0 -3
- package/dist/chunks/chunk-3VSDH7DF.js +0 -3
- package/dist/chunks/chunk-4ANZCMTB.js +0 -813
- package/dist/chunks/chunk-5ORPFMKW.js +0 -3
- package/dist/chunks/chunk-6DHFEWGX.js +0 -1
- package/dist/chunks/chunk-73S5MDH5.js +0 -816
- package/dist/chunks/chunk-77P7CACS.js +0 -3
- package/dist/chunks/chunk-7WH5DREO.js +0 -1
- package/dist/chunks/chunk-APOUCRQO.js +0 -803
- package/dist/chunks/chunk-BVYPWENJ.js +0 -803
- package/dist/chunks/chunk-BW2MR2YB.js +0 -3
- package/dist/chunks/chunk-D67A52ZR.js +0 -802
- package/dist/chunks/chunk-DB4BJM2R.js +0 -807
- package/dist/chunks/chunk-GYYGT2GJ.js +0 -1229
- package/dist/chunks/chunk-HU74ZBCV.js +0 -803
- package/dist/chunks/chunk-IW2KLAXM.js +0 -803
- package/dist/chunks/chunk-M3G4NWZ2.js +0 -3
- package/dist/chunks/chunk-O4A5T73D.js +0 -801
- package/dist/chunks/chunk-PHKIAKHS.js +0 -1
- package/dist/chunks/chunk-PK33OTVD.js +0 -802
- package/dist/chunks/chunk-RTGBM2SA.js +0 -27
- package/dist/chunks/chunk-SGZ2OI72.js +0 -1
- package/dist/chunks/chunk-UCFPBFHY.js +0 -811
- package/dist/chunks/chunk-UKBUOJ3P.js +0 -803
- package/dist/chunks/chunk-VBKX2PU3.js +0 -803
- package/dist/chunks/chunk-VFG7GIPV.js +0 -812
- package/dist/chunks/chunk-WJ33GNVP.js +0 -3
- package/dist/chunks/chunk-Y2EZRWRZ.js +0 -803
- package/dist/chunks/chunk-Y6SLVHK3.js +0 -1
- package/dist/chunks/chunk-ZGHOKGSQ.js +0 -1231
- package/dist/chunks/chunk-ZQZIEF5I.js +0 -803
- package/dist/chunks/chunk-ZRS2O6Y6.js +0 -1
- package/dist/chunks/export-JZFBZGGZ.js +0 -1
- package/dist/chunks/export-MX2VT3I7.js +0 -1
- package/dist/chunks/export-OFKMKWAS.js +0 -1
- package/dist/chunks/export-ZB2GNV3S.js +0 -1
- package/dist/chunks/paths-HYQFU6D2.js +0 -1
- package/dist/chunks/paths-KMO5IYNK.js +0 -1
- package/dist/chunks/paths-NXN6XAEU.js +0 -1
- package/dist/chunks/paths-YDCMNN4Q.js +0 -1
- package/dist/chunks/secrets-2VU4KV7B.js +0 -1
- package/dist/chunks/secrets-GN7OAYL7.js +0 -1
- package/dist/chunks/secrets-NCPPS7DR.js +0 -1
- package/dist/chunks/secrets-RZD3DYTB.js +0 -1
- package/dist/chunks/settings-57QAZRCP.js +0 -1
- package/dist/chunks/settings-DCF6DTL6.js +0 -1
- package/dist/chunks/settings-DTH5C6BO.js +0 -1
- package/dist/chunks/settings-GPKUUYFM.js +0 -1
- package/dist/chunks/settings-HOSPANO7.js +0 -1
- package/dist/chunks/settings-IY24HSRP.js +0 -1
- package/dist/chunks/settings-SSPDWUKI.js +0 -1
- package/dist/chunks/src-O2JUKI77.js +0 -1
- package/dist/chunks/subagent_state-3D5ZJCLX.js +0 -1
- package/dist/chunks/subagent_state-5IJKFMRU.js +0 -1
- package/dist/chunks/subagent_state-N77JX7MX.js +0 -1
|
@@ -1,813 +0,0 @@
|
|
|
1
|
-
import{b as Jo}from"./chunk-ZESOEAQT.js";import{c as fn,d as qs,g as et,h as Ft}from"./chunk-BZBAMZS4.js";import{a as Gs,b as Cs,c as X,d as he}from"./chunk-SIINYZWE.js";import{c as An,d as cn,e as go,f as Es,g as $s,h as Yo,i as Jt,j as Dt,k as Xt,l as vn,m as Un,n as nn,o as dn,p as rs,q as Vo,r as Wn,s as as}from"./chunk-I27MASHH.js";import{a as Ye,c as yo}from"./chunk-56EJGQU3.js";import{c as lr,d as cr,e as Ks}from"./chunk-K4FITEVZ.js";import Xl from"dotenv";import{GoogleGenAI as Ta,ThinkingLevel as at,HarmBlockThreshold as Yn,HarmCategory as Vn}from"@google/genai";import{Ollama as Ql}from"ollama";import{execSync as Wa}from"child_process";import{spawn as Xo}from"child_process";var I=e=>{let n={};if(!e)return n;let t=0;for(;t<e.length;){for(;t<e.length&&/[\s,]/.test(e[t]);)t++;if(t>=e.length)break;let o=e.substring(t).match(/^(\w+)\s*=\s*/);if(!o){t++;continue}let s=o[1];t+=o[0].length;let i="";if(t<e.length&&(e[t]==='"'||e[t]==="'"||e[t]==="`")){let a=e[t];t++;let r=t,h=-1,d=t;for(;d<e.length;){let l=e.indexOf(a,d);if(l===-1)break;let f=0;for(let y=l-1;y>=0&&e[y]==="\\";y--)f++;if(f%2!==0){d=l+1;continue}let u=e.substring(l+1),p=u.trim(),g=p===""||/^,\s*\w+\s*=/.test(p)||p.startsWith(")")&&(p.length===1||/^\)\s*([,\]\s]|\[\[?tool:)/i.test(p));if(g&&u.startsWith(`
|
|
2
|
-
`)){let y=p.split(`
|
|
3
|
-
`)[0];if(!y.includes("=")&&!y.includes(")")){d=l+1;continue}}if(g){h=l;break}d=l+1}h!==-1?(i=e.substring(r,h),t=h+1):(i=e.substring(r),t=e.length);let c=s.toLowerCase().includes("path")||["dest","source","to","from"].includes(s.toLowerCase());i=i.replace(/\\(.)/g,(l,f)=>{switch(f){case"n":return`
|
|
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,r=null,h=t,d=-1;for(let c=t;c<e.length;c++){let l=e[c];if(r&&l===r){let f=0;for(let u=c-1;u>=0&&e[u]==="\\";u--)f++;f%2===0&&(r=null)}else!r&&(l==='"'||l==="'"||l==="`")&&(r=l);if(!r&&(l==="["?a++:l==="]"&&a--,a===0)){d=c;break}}if(d!==-1){i=e.substring(h,d+1),t=d+1;try{let c=i.trim();c.startsWith("'")||c.includes("'")}catch{}}else i=e.substring(h),t=e.length}else{let a=e.substring(t),r=a.match(/,\s*\w+\s*=|(?:\s*\)\s*(?:$|\]\]))/);if(r){let h=r.index;i=a.substring(0,h).trim(),t+=h}else i=a.trim(),t=e.length}i==="true"?i=!0:i==="false"?i=!1:typeof i=="string"&&!isNaN(i)&&i.trim()!==""&&(i=Number(i)),typeof i=="string"&&(s.toLowerCase().includes("path")||["dest","source","to","from"].includes(s.toLowerCase()))&&(i=i.replace(/\x0C/g,"\\f").replace(/\x0D/g,"\\r").replace(/\x0B/g,"\\v").replace(/\x08/g,"\\b")),n[s]=i}return n};var wo=null;try{let e=await import("node-pty");wo=e.default||e}catch{}var Ic=!!wo,xo=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),Qo=e=>{if(!e)return"";let n=[[]],t=0,o=0,s=/\x1b\[([0-9;]*?)([a-zA-Z])/g,i=0,a,r=d=>{for(let c=0;c<d.length;c++){let l=d[c];if(l===`
|
|
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;){r(e.substring(i,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 p=0;p<o&&p<u.length;p++)u[p]=" ";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)}i=s.lastIndex}r(e.substring(i));let h=n.map(d=>d.join(""));for(;h.length>0&&h[h.length-1]==="";)h.pop();return h.join(`
|
|
6
|
-
`)},gt=null,zs=!1,Oc=e=>{try{gt&&(zs&&typeof gt.write=="function"?gt.write(e):gt.stdin&>.stdin.writable&>.stdin.write(e))}catch{}},Lc=()=>{if(gt){try{zs&&typeof gt.destroy=="function"?gt.destroy():typeof gt.kill=="function"&&(process.platform==="win32"?Xo("taskkill",["/pid",gt.pid,"/f","/t"]):gt.kill("SIGKILL"))}catch{}gt=null,zs=!1}},Zo=(e,n=!1)=>{if(process.platform!=="win32")return e;let t=[],o="",s=null,i=!1;for(let c=0;c<e.length;c++){let l=e[c];if(i){o+=l,i=!1;continue}if(l==="\\"){if(e[c+1]===" "){o+=" ",c++;continue}o+=l,i=!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)),r=[];for(let c=0;c<t.length;c++){let l=t[c];if(l==="mkdir"&&n&&jn()){let f=[],u=c+1;for(;u<t.length;){let p=t[u];if([">",">>","<","&","&&","|","||",";"].includes(p))break;p!=="-p"&&p!=="--parents"&&p!=="-v"&&p!=="--verbose"&&f.push(p),u++}if(f.length>0){let p=f.map(g=>{let y=g.replace(/^['"]|['"]$/g,""),m=g;return a(y)&&(m=g.replace(/\//g,"\\")),m});r.push("New-Item","-ItemType","Directory","-Force","-Path",p.join(","))}else r.push("New-Item","-ItemType","Directory","-Force");c=u-1;continue}if(l==="rm"&&n&&jn()){let f=[],u=!1,p=!1,g=c+1;for(;g<t.length;){let m=t[g];if([">",">>","<","&","&&","|","||",";"].includes(m))break;m==="-rf"||m==="-fr"?(u=!0,p=!0):m==="-r"||m==="-R"||m==="--recursive"?u=!0:m==="-f"||m==="--force"?p=!0:f.push(m),g++}let y=["Remove-Item"];if(u&&y.push("-Recurse"),p&&y.push("-Force"),f.length>0){let m=f.map(w=>{let x=w.replace(/^['"]|['"]$/g,""),S=w;return a(x)&&(S=w.replace(/\//g,"\\")),S});y.push("-Path",m.join(","))}r.push(...y),c=g-1;continue}if(l==="cp"&&n&&jn()){let f=[],u=!1,p=!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"?p=!0:f.push(m),g++}let y=["Copy-Item"];if(u&&y.push("-Recurse"),p&&y.push("-Force"),f.length>0){let m=f.map(w=>{let x=w.replace(/^['"]|['"]$/g,""),S=w;return a(x)&&(S=w.replace(/\//g,"\\")),S});if(m.length>1){let w=m.pop();y.push("-Path",m.join(","),"-Destination",w)}else y.push("-Path",m[0])}r.push(...y),c=g-1;continue}if(l==="touch"&&n&&jn()){let f=[],u=c+1;for(;u<t.length;){let p=t[u];if([">",">>","<","&","&&","|","||",";"].includes(p))break;f.push(p),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 $_ } }`;r.push(g)}c=u-1;continue}if(l==="|"&&t[c+1]==="tee"){t[c+2]==="-a"?(r.push(">>"),c+=2):(r.push(">"),c+=1);continue}if(l==="|"&&t[c+1]==="cat"&&t[c+2]===">"){r.push(">"),c+=2;continue}if(l==="|"){let f=t[c+1];if(f){let u=f.replace(/^['"]|['"]$/g,""),p=/\.(txt|md|json|log|csv|html|css|py|js|xml|yaml|yml|pdf|docx|pptx|xlsx)$/i.test(u);if(a(u)&&p){r.push(">");continue}}}r.push(l)}let h=!1,d=r.map(c=>{if(c==="echo")return h=!0,c;[">",">>","<","&","&&","|","||",";"].includes(c)&&(h=!1);let f=/^['"]|['"]$/.test(c),u=c;h&&f&&(u=c.replace(/^['"]|['"]$/g,""));let p=/^['"]|['"]$/.test(u),g=u.replace(/^['"]|['"]$/g,"");a(g)&&(u=u.replace(/\//g,"\\"));let y=u.replace(/^['"]|['"]$/g,"");return y.includes(" ")&&!p&&(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(" ")},ei=async(e,n={})=>{let{command:t}=I(e),{onChunk:o}=n;if(!t)return'ERROR: Missing "command" argument for exec_command.';let s=process.platform==="win32",i=n.systemSettings||{},a={};return i.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(r=>{let h=d=>{let c=d==="pwsh"||d==="powershell",l=Zo(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(i.networkAccess===!1&&!s){let p=f,g=[...u];if(process.platform==="linux")f="unshare",u=["-n","-r",p,...g];else if(process.platform==="darwin"){let y=`(version 1)
|
|
7
|
-
(allow default)
|
|
8
|
-
(deny network-outbound)
|
|
9
|
-
(allow network-outbound (remote ip "localhost:*"))
|
|
10
|
-
(allow network-outbound (remote ip "127.0.0.1:*"))
|
|
11
|
-
`;f="sandbox-exec",u=["-p",y,p,...g]}}if(wo)try{let p=wo.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}});gt=p,zs=!0;let g="",y=!1;return p.onData(m=>{if(!y){g+=m,o&&o(m);let w=xo(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(()=>r(`SUCCESS: Dev server started successfully in background.
|
|
12
|
-
|
|
13
|
-
${w}`),500))}}),p.onExit(({exitCode:m})=>{if(y)return;gt=null;let w=Qo(g||""),x=xo(w).replace(/\n{3,}/g,`
|
|
14
|
-
|
|
15
|
-
`)||"Command executed with no output.";r(m!==0?`ERROR: Command [${t}] failed with exit code [${m}].
|
|
16
|
-
|
|
17
|
-
${x}`:`SUCCESS: Command [${t}] completed.
|
|
18
|
-
|
|
19
|
-
${x}`)}),!0}catch(p){return s&&(d==="pwsh"||d==="powershell")&&p.code==="ENOENT"?!1:(bo(r,l,t,a,o,d,i),!0)}else return bo(r,l,t,a,o,d,i),!0};s?h("pwsh")||h("powershell")||h("cmd"):h("bash")})},bo=(e,n,t,o,s,i="powershell",a={})=>{let r=process.platform==="win32",h=i==="pwsh"||i==="powershell",d;r?i==="pwsh"?d="C:\\Users\\User\\AppData\\Local\\Microsoft\\WindowsApps\\pwsh.exe":i==="powershell"?d="powershell.exe":d="cmd.exe":d=process.env.SHELL||"bash";let c=r?h?["-NoProfile","-Command",n]:["/c",n]:["-c",n];if(a.networkAccess===!1&&!r){let g=d,y=[...c];if(process.platform==="linux")d="unshare",c=["-n","-r",g,...y];else if(process.platform==="darwin"){let m=`(version 1)
|
|
20
|
-
(allow default)
|
|
21
|
-
(deny network-outbound)
|
|
22
|
-
(allow network-outbound (remote ip "localhost:*"))
|
|
23
|
-
(allow network-outbound (remote ip "127.0.0.1:*"))
|
|
24
|
-
`;d="sandbox-exec",c=["-p",m,g,...y]}}let l=r?Xo(d,c,{cwd:process.cwd(),env:{...process.env,...o}}):Xo(d,c,{cwd:process.cwd(),env:{...process.env,CI:"false",TERM:"xterm-256color",FORCE_COLOR:"1",...o}});gt=l,zs=!1,l.stdin&&l.stdin.on("error",()=>{gt=null});let f="",u="",p=!1;l.stdout.on("data",g=>{if(!p){let y=g.toString();f+=y,s&&s(y);let m=xo(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)&&(p=!0,setTimeout(()=>e(`SUCCESS: Dev server started successfully in background.
|
|
25
|
-
|
|
26
|
-
${m}`),500))}}),l.stderr.on("data",g=>{if(!p){let y=g.toString();u+=y,s&&s(y)}}),l.on("close",g=>{if(p)return;gt=null;let y=[],m=Qo(f),w=Qo(u);m&&y.push(`STDOUT:
|
|
27
|
-
${m}`),w&&y.push(`STDERR:
|
|
28
|
-
${w}`),g!==0&&y.push(`EXIT CODE: ${g}`);let x=y.join(`
|
|
29
|
-
|
|
30
|
-
`)||"Command executed with no output.",S=xo(x).replace(/\n{3,}/g,`
|
|
31
|
-
|
|
32
|
-
`);e(g!==0?`ERROR: Command [${t}] failed with exit code [${g}].
|
|
33
|
-
|
|
34
|
-
${S}`:`SUCCESS: Command [${t}] completed.
|
|
35
|
-
|
|
36
|
-
${S}`)}),l.on("error",g=>{if(r&&g.code==="ENOENT"){if(i==="pwsh"){let m=Zo(t,!0);return bo(e,m,t,o,s,"powershell",a)}else if(i==="powershell"){let m=Zo(t,!1);return bo(e,m,t,o,s,"cmd",a)}}gt=null;let y=g instanceof Error?g.message:String(g);e(`ERROR: Failed to start command [${t}]: ${y}`)})};var Ys=null,jn=()=>{if(process.platform!=="win32")return!1;if(Ys!==null)return Ys;try{Wa('powershell.exe -NoProfile -Command "exit"',{stdio:"ignore"}),Ys=!0}catch{Ys=!1}return Ys},ti=null,dr=(e,n,t,o,s=!1,i=!0)=>{ti===null&&(ti=s);let a=`- JSON escape literal escape sequences in tool arguments
|
|
37
|
-
- Same file, multiple edits? One PatchFile (\u226415 blocks) \u2190 Priority
|
|
38
|
-
- Tool denied? Ask for guidance \u2190 mandatory
|
|
39
|
-
- Need text or huge file? CodeSearch > Full Read
|
|
40
|
-
- Avoid unnecessary large file chunk reads
|
|
41
|
-
- Dont hallucinate tool results, verify, fix errors
|
|
42
|
-
- Stuck on syntax error? Tell user > waste time
|
|
43
|
-
`,r=`**Workspace Tools (path = relative; first argument, path separator: '/')**
|
|
44
|
-
- [tool:functions.ReadFile(path="...", startLine="int", endLine="int")]${o!=="Google"?`${t?". Supports images/docs":""}`:". Supports images/docs"}
|
|
45
|
-
- [tool:functions.ReadFolder(path="...", recurse="int 1-3")]. Minimize recursion
|
|
46
|
-
- [tool:functions.PatchFile(path="...", allowMultiple="bool, default: false", searchContent1="search string OR ^LINE:start..end$", newContent1="...", ...MAX15)]. Target minimal searchContent. Line Ranges must for large searchContent and escape sequences. ^...$ must for line ranges
|
|
47
|
-
- [tool:functions.WriteFile(path="...", content="...")]. Creates/Overwrites. File Exist? PatchFile > WriteFile
|
|
48
|
-
- [tool:functions.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
|
-
- [tool:functions.Run(command="...")]. Runs ${n==="Windows"?jn()?"powershell":"windows CMD":"bash"} command. Destructive/Irreversible ops \u2192 Ask user
|
|
50
|
-
- [tool:functions.Todo(method="create/append/get", tasks=[string array], markDone=[task array])]. If long multi-task: create Todos before starting. \`get + markDone\` to mark complete. Update every turn when created
|
|
51
|
-
${ti?'\n**Emergency Tools**\nInfo: `initial` = current task prompt. Revert `id` = turn before disaster (eg. disaster: `turn_3` \u2192 revert: `turn_2`). Reason explicitly\n- [tool:functions.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':""}${i?`
|
|
52
|
-
**Sub Agent Tools**
|
|
53
|
-
proactive use highly recommended. Prefer for any task, no user nudge needed
|
|
54
|
-
Invocations:
|
|
55
|
-
\u2022 Invoke (async/background, \u22647 parallel). Parallelize long tasks. May take time
|
|
56
|
-
\u2022 InvokeSync (sync/blocking). Sequential, repetitive or delegated tasks. Saves tokens/cost
|
|
57
|
-
- [tool:functions.InvokeSync/Invoke(title="...", task="...")]. Task must be detailed: exact file paths, imports/exports, dependencies
|
|
58
|
-
- [tool:functions.Await(id="...", timeout="integer")]. Event-driven wait
|
|
59
|
-
- [tool:functions.GetProgress(id="...")]. Poll sparingly; NO initial poll. Work or await. Never end while subagent runs
|
|
60
|
-
- [tool:functions.Steer(id="...", message="...")]. Inject additional instruction or redirection into active async subagent
|
|
61
|
-
- [tool:functions.Cancel(id="...")]. Cancel async task ONLY if stalled (2m+) or incorrect`:""}`,h=`**Creative Tools (path = relative; first argument, path separator: '/')**
|
|
62
|
-
- [tool:functions.WritePDF(path="...", content="...", orientation="...")]. Proactive A4 page breaks must in css. HTML/CSS for premium layout, stable margins & headers/footers, no watermarks
|
|
63
|
-
- [tool:functions.WriteDoc(path="...", content="...")]. A4 Word document, no watermarks, stable margins & headers/footers`,d=`**Computer Use Tools (GUI Desktop Automation)**
|
|
64
|
-
- [tool:functions.Click(gridId="integer", type="single/double", button="left/middle/right", intendedClickText="target text")]. Click target grid number, intendedClickText: literal text/icon on screen (OCR scannable, upto 3 words). Double click desktop icons
|
|
65
|
-
- [tool:functions.Drag(fromGridId="integer", toGridId="integer")]. Drag mouse from start grid number to target grid number
|
|
66
|
-
- [tool:functions.Scroll(direction="up/down", gridId="mouse hover area")]. Scroll viewport vertically
|
|
67
|
-
- [tool:functions.KeyboardTyping(text="string", autoPressEnter="bool")]. Type text string into currently active input. JSON escape literal escape sequences
|
|
68
|
-
- [tool:functions.KeyPress(key="key or ;-separated combination, eg: enter, backspace, clearInput, ctrl;c, alt;tab, f5, f11, alt;f4")]. Press key, shortcut, function key (f1-f12), or clear active input field.
|
|
69
|
-
- [tool:functions.RecaptureScreen()]. Request fresh gridded screenshot`;return`
|
|
70
|
-
-- TOOLS --
|
|
71
|
-
To use tools, must output exactly '[tool:functions.ToolName(arg1="value1")]' structured string in chat response \u2190 no exception
|
|
72
|
-
Tool Rules:
|
|
73
|
-
- Max 3 tool calls/turn${e==="Flux"||e.toLowerCase()==="fluxcu"?" (Todo: 3+)":""}
|
|
74
|
-
${e==="Flux"||e.toLowerCase()==="fluxcu"?`${a}`:""}
|
|
75
|
-
**User Communication**
|
|
76
|
-
- [tool:functions.Ask(question="...", optionA="title::description", ...MAX4)]. Ambiguity, path divergence, security risk. Ask, dont finish/guess. Keep titles short
|
|
77
|
-
|
|
78
|
-
**Web Tools**
|
|
79
|
-
- [tool:functions.WebSearch(query="...", aiMode="bool", limit="integer 3-10 aiMode: exclude")]. Proactive use for unknown info/docs. aiMode: LLM search
|
|
80
|
-
- [tool:functions.WebScrape(url="...")]. Proactive use for specific webpage/docs/api
|
|
81
|
-
|
|
82
|
-
${e==="ICU"?`${d}`:e==="FluxCU"?`${r}
|
|
83
|
-
${d}`:e==="Flux"?`${r}`:`${h}`}`.trim()};var fr=(e=!0,n=!0)=>`
|
|
84
|
-
To use tools, must output exactly '[tool:functions.ToolName(arg1="value1")]' structured string in chat response \u2190 no exception
|
|
85
|
-
|
|
86
|
-
-- Chat Management Tools --
|
|
87
|
-
- [tool:functions.Chat(title="<short creative title of FULL conversation in 3 or 4 words>")]. Consider full chat context to generate title NOT just latest message
|
|
88
|
-
- [tool:functions.Memory(action="temp", content="<summary of the user prompt & model responses only from latest prompt under 40 words>. [Talked on: <date> <hour>]")]. Time format: YYYY-MM-DD HH am/pm
|
|
89
|
-
|
|
90
|
-
${e?`-- User-specific long-term/permanent memory (use based on conversation context, do not re-save memory which is already saved) --
|
|
91
|
-
- Add: [tool:functions.Memory(action="user", method="add", content="<string to add>. [Saved on: <date ONLY>]", score=2)] (Set score=2 ONLY if the user explicitly asked to "remember" or "save" this information, else omit this parameter entirely)
|
|
92
|
-
- Delete: [tool:functions.Memory(action="user", method="delete", id="<memory id>")]
|
|
93
|
-
- Update: [tool:functions.Memory(action="user", method="update", content-new="string to update", id="<memory id>")]
|
|
94
|
-
|
|
95
|
-
-- Memory Relevance Decay Tool --
|
|
96
|
-
- Score Adjustment: [tool:functions.addMemScore(id="<memory id>")]
|
|
97
|
-
You MUST call this tool when a specific saved memory in the '-- Current Saved User Memories --' list was relevant, referenced, or helpful in the agent's response or user prompt in current message. You can stack multiple calls
|
|
98
|
-
|
|
99
|
-
Explicit Triggers for permanent memory:
|
|
100
|
-
- User explicitly asks to 'remember' something
|
|
101
|
-
- User mentions something important long-term that should be remembered
|
|
102
|
-
- User provides information that could be useful for long-term reference
|
|
103
|
-
- User shares personal information or preferences
|
|
104
|
-
|
|
105
|
-
Usage Rules:
|
|
106
|
-
- Frequency for 'user' action: Based on explicit triggers.
|
|
107
|
-
- If you want to save something, but similar memory already exists, use the update method not add
|
|
108
|
-
- Chat title is mandatory
|
|
109
|
-
- Temporary memory is mandatory
|
|
110
|
-
- When called user memory, still use Temporary Memory
|
|
111
|
-
- Must not ignore any tool calls in given context of chat between user & agent`:""}`.trim();var So={xHigh:`Effort: High
|
|
112
|
-
Challenge assumptions, verify before concluding, prefer the simplest correct solution, assess architecture, scalability & trade-offs, verify dependencies, regressions, failure modes & modular design, plan: files, modules, interfaces & tests
|
|
113
|
-
Continuous analysis, verify from first principles, seek failure paths, verify imports, tool results & system stability; avoid syntax errors
|
|
114
|
-
MANDATORY: Full technical verification`,High:`Effort: High
|
|
115
|
-
Rigorous thinking, prefer the simplest correct solution, assess architecture, performance & maintainability, verify error handling, assumptions, edge cases, dependencies & regressions, plan: files, functions, logic & interactions
|
|
116
|
-
Continuous analysis, verify from first principles, seek failure paths, verify imports, tool results & system stability; avoid syntax errors
|
|
117
|
-
MANDATORY: Full technical verification`,Medium:`Effort: Medium
|
|
118
|
-
Focused, technical thinking, find the simplest solution meeting requirements, check error handling, assumptions, edge cases & dependencies, verify cohesive, modular changes, outline: files, functions & key logic
|
|
119
|
-
Logical, implementation-focused, efficient, deliberate, verify imports, tool results & system stability; avoid syntax errors
|
|
120
|
-
MANDATORY: Brief verification for technical tasks/greetings`,Minimal:`Effort: Low
|
|
121
|
-
Quick, focused thinking, intent & complexity, required tools/files/actions, before acting
|
|
122
|
-
Brief thoughts, think only enough to avoid mistakes, verify imports, tool results & system stability; avoid syntax errors`,Off:`Effort: Lowest
|
|
123
|
-
No thinking. Immediate response
|
|
124
|
-
Verify imports, tool results & system stability; avoid syntax errors`};import hr from"fs";import Ha from"screenshot-desktop";var pr=!1;(async()=>{try{let e=await Ft();if(Number(e?.display)===1){let n=await Ha.listDisplays();n&&n.length>1&&(pr=!0)}}catch{}})();var ni=null,ur=null,Vs=null,Xc=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",Ga=process.env.NO_DEV||!1,qa=(e,n)=>{if(!n)return"";if(e!==ur||Vs===null){ur=e;try{let t=X(Dt,[]);Array.isArray(t)&&t.length>0?Vs=t.map(o=>`- ${o.memory}`).join(`
|
|
125
|
-
`):Vs=""}catch(t){Vs="",hr.appendFileSync(`${cn}/memory/error.txt`,`${t.message}
|
|
126
|
-
-------------------------------------------------
|
|
127
|
-
|
|
128
|
-
`)}}return Vs},mr=(e="",n="",t=!0,o=!1)=>{if(typeof n=="boolean"&&(o=t,t=n,n=""),!t)return"";let s=e?.length>0&&!o?`-- Recent context from other chats (Priority: Low, Focus: Chat Context > Recent) --
|
|
129
|
-
${e}`:"";return s?`${s}`:""},gr=(e,n,t,o,s=!0,i=!1,a="Google",r=!1,h,d)=>{let c=!1;process.env.forcedReasoning&&process.env.NVIDIA_BASE_URL&&a.toUpperCase()==="NVIDIA"&&(c=!0);let l="";if(!h&&a==="Google"){let E=n;n==="Fast"&&(E="Off"),n==="Low"&&(E="Minimal"),n==="Standard"&&(E="Medium"),(n==="xHigh"||n==="Max")&&(E="xHigh"),l=So[E]||So.Medium}if(h||a!=="Google"){let E={Fast:"Lowest",Low:"Low",Medium:"Medium",Standard:"Medium",High:"High",xHigh:"High",Max:"High"};l=So.xHigh,l=l.replace("Effort: High",`Effort: ${E[n]}`).replace(`
|
|
130
|
-
MANDATORY: Full technical verification`,""),n==="Fast"?l=`Effort: Lowest
|
|
131
|
-
No thinking. Immediate response
|
|
132
|
-
Verify imports, tool results & system stability; avoid syntax errors`:n==="Low"&&(l=`Effort: Low
|
|
133
|
-
Quick, focused thinking, intent & complexity, required tools/files/actions, before acting
|
|
134
|
-
Brief thoughts, think only enough to avoid mistakes, verify imports, tool results & system stability; avoid syntax errors`)}let f=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",u=e.instructions&&e.instructions?.length>0?`User Preferences: ${e.instructions}
|
|
135
|
-
|
|
136
|
-
`:"",p=e.nickname&&e.nickname?.length>0?`User Nickname: ${e.nickname}
|
|
137
|
-
${u.length?"":`
|
|
138
|
-
`}`:"",g=e.name&&e.name?.length>0?`User Name: ${e.name}
|
|
139
|
-
${p.length||u.length?"":`
|
|
140
|
-
`}`:"",y=process.cwd(),m=qa(d,s),w=m?.length>0?`--- Saved Memories ---
|
|
141
|
-
${m}
|
|
142
|
-
|
|
143
|
-
`:"",x=(()=>{let E=process.cwd().toLowerCase();if(process.platform==="win32"){let b=process.env.SystemRoot?.toLowerCase()||"c:\\windows",T=process.env.ProgramFiles?.toLowerCase()||"c:\\program files",$=process.env["ProgramFiles(x86)"]?.toLowerCase()||"c:\\program files (x86)";return E.startsWith(b)||E.startsWith(T)||E.startsWith($)}else return E==="/"||["/bin","/sbin","/etc","/usr","/var","/root"].some(T=>E.startsWith(T))})(),S=[{name:"Fluxflow.md",desc:"HIGH PRIORITY"},{name:"README.md",desc:"Goals"},{name:"Agent.md",desc:"Standards"},{name:"Skills.md",desc:"Workflows"},{name:"design.md",desc:"UI/UX"},{name:"architecture.md",desc:"System Structure"}];if(i||ni===null){let E=S.filter(b=>hr.existsSync(b.name));ni=t==="Flux"&&E.length>0?`
|
|
144
|
-
-- PROJECT CONTEXT --
|
|
145
|
-
${E.map(b=>`- ${b.name}: ${b.desc}`).join(`
|
|
146
|
-
`)}
|
|
147
|
-
Check these first; These Files > Training Data. Safety rules apply
|
|
148
|
-
`:""}let R=ni;return`=== SYSTEM PROMPT ===
|
|
149
|
-
Identity: Flux Flow. Sassy, Friendly, CLI Agent${Ga?"":" by Kushal Roy Chowdhury"}
|
|
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 if efficient":"Computer Use & Workspace Capabilities. Screenshot (ground truth), analyze grid ids overlapping/close to target, keyboard shortcuts if efficient. Workspace Tools if faster. Focus on Productivity"}${pr&&t.toLowerCase().includes("cu")?`
|
|
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
|
-
|
|
153
|
-
- OS: ${f}
|
|
154
|
-
- Use directory structure for file path resolution${s?`
|
|
155
|
-
- Use relative time reference eg. few mins ago
|
|
156
|
-
-- Chat Context > Metadata`:""}
|
|
157
|
-
|
|
158
|
-
-- THINKING GUIDANCE --
|
|
159
|
-
${a==="Mistral"||a==="Google"&&!h?`${l}
|
|
160
|
-
${c||n!=="Fast"&&(a==="Mistral"&&!h||n!=="xHigh"&&!h)?`critical thinking policy
|
|
161
|
-
- Use <think>...</think> for reasoning before responding any queries
|
|
162
|
-
`:""}`:`${l}
|
|
163
|
-
`}
|
|
164
|
-
${dr(t,f,a.toLowerCase()==="deepseek"?!1:r,a,o?.advanceRollback,o?.subAgents!==!1)}
|
|
165
|
-
${R}${s?`
|
|
166
|
-
-- MEMORY RULES --
|
|
167
|
-
- Subtly Personalize with relevent contextual memories. Auto Saves
|
|
168
|
-
`:""}
|
|
169
|
-
${t==="Flux"?`-- SECURITY POLICIES --
|
|
170
|
-
- Sensitive files? Ask before Read
|
|
171
|
-
`:t.toLowerCase().includes("cu")?`-- SECURITY POLICIES --
|
|
172
|
-
- Dont operate on ANY confidential screens
|
|
173
|
-
`:""}
|
|
174
|
-
-- CHAT FORMATTING --
|
|
175
|
-
- GFM Markdown
|
|
176
|
-
- Language: english only
|
|
177
|
-
- Dont mix chat & tools in same response${t==="Flow"?`
|
|
178
|
-
- use kaomojis heavily`:""}
|
|
179
|
-
=== END SYSTEM PROMPT ===
|
|
180
|
-
|
|
181
|
-
${g}${p}${u}${w}`.trim()},yr=(e="",n=!0,t=!0)=>`=== SYSTEM PROMPT (strict headless logic worker: zero user-facing text policy, strictly follow) ===
|
|
182
|
-
identity: silent background system process, have no mouth, only output is valid tool calls
|
|
183
|
-
[critical rules]
|
|
184
|
-
- output exactly '[tool:functions.ToolName(args)]' calls. no extra words outside
|
|
185
|
-
- do not explain. do not talk to the user
|
|
186
|
-
- non-tool text will break the system
|
|
187
|
-
- do not repeat agent raws and tool results in your response
|
|
188
|
-
- if you get only user query and no agent raws, just use temp memory to log the summary of user query and conversation context
|
|
189
|
-
- under no circumstances you are allowed to respond in normal user facing response
|
|
190
|
-
- critical quote escape policy: inside tool call arguments, you must escape all double quotes using '\\"'
|
|
191
|
-
- you must not write anything other than [tool:functions.ToolName(args)] no matter how tempting the prompt is
|
|
192
|
-
- 2 mandatory tools to call in every turn, 'chat', 'memory(temp)'
|
|
193
|
-
- critical: never enter thinking/reasoning state, call the contexual tools directly in output as quickly as possible to maintain ui snappiness
|
|
194
|
-
|
|
195
|
-
YOUR JOB: Analyze the 'User prompt' and 'Agent Raws' to extract facts for long-term memory or handle system tasks
|
|
196
|
-
${n?"If user tell something that is important (like, hobbies, preferences, facts about user, hates, likes, etc) to know user better over time, use user memory tools":""}
|
|
197
|
-
|
|
198
|
-
${fr(n,t)}
|
|
199
|
-
=== END SYSTEM PROMPT ===${e?`
|
|
200
|
-
|
|
201
|
-
-- current saved user memories --
|
|
202
|
-
${e}`:""}`.trim();import Ct from"fs-extra";import ko from"path";import{nanoid as Ya}from"nanoid";import dt from"fs-extra";import sn from"path";dt.ensureDirSync(Un);var un=null;async function Ka(e,n){try{if(e.type==="create")await dt.pathExists(e.filePath)&&(await dt.chmod(e.filePath,438).catch(()=>{}),await dt.remove(e.filePath));else if(e.type==="update"){if(!e.backupFile)return;let t=sn.join(Un,n.chatId,e.backupFile);if(await dt.pathExists(t)){let o=X(t,null);if(!o||!o.data)throw new Error(`Backup container corrupt or empty for ${sn.basename(e.filePath)}`);let s=Cs(o.data);await dt.pathExists(e.filePath)&&await dt.chmod(e.filePath,438).catch(()=>{}),await dt.writeFile(e.filePath,s,"utf8")}}}catch(t){throw new Error(`Restoration failed for ${sn.basename(e.filePath)}: ${t.message}`)}}async function za(e,n,t=7){let o=0;for(;o<t;)try{return await Ka(e,n),!0}catch{if(o++,o>=t)return!1;let i=Math.min(100*Math.pow(2,o-1),5e3);await new Promise(a=>setTimeout(a,i))}return!1}var si=null,ft={async startTransaction(e,n){si=e,un={id:`tx_prompt_${Date.now()}`,chatId:e,timestamp:new Date().toISOString(),prompt:n.trim(),changes:[],reverted:!1},he(rs,un)},async recordFileChange(e,n=null){try{if(!un){if(si){let a=X(nn,[]),r=[...a].reverse().find(h=>h.chatId===si);if(r){if(r.changes.some(f=>f.filePath===e))return;let c=await dt.pathExists(e)||n?"update":"create",l=null;if(c==="update"){let f=sn.basename(e);l=`${r.id}_${f}.bak`;let u=sn.join(Un,r.chatId);await dt.ensureDir(u);let p=sn.join(u,l),g=n!==null?n:await dt.readFile(e,"utf8").catch(()=>null);g!==null?he(p,{data:Gs(g)}):(c="create",l=null)}r.changes.push({filePath:e,type:c,backupFile:l}),he(nn,a)}}return}if(un.changes.some(a=>a.filePath===e))return;let s=await dt.pathExists(e)||n?"update":"create",i=null;if(s==="update"){let a=sn.basename(e);i=`${un.id}_${a}.bak`;let r=sn.join(Un,un.chatId);await dt.ensureDir(r);let h=sn.join(r,i),d=n!==null?n:await dt.readFile(e,"utf8").catch(()=>null);d!==null?he(h,{data:Gs(d)}):(s="create",i=null)}un.changes.push({filePath:e,type:s,backupFile:i}),he(rs,un)}catch{}},async commitTransaction(){if(un)try{let e=X(nn,[]);if(e.push(un),e.length>512e3){let n=e.shift();if(n.changes)for(let t of n.changes)t.backupFile&&await dt.remove(sn.join(Un,n.chatId,t.backupFile)).catch(()=>{})}he(nn,e),await dt.remove(rs).catch(()=>{})}catch{}finally{un=null}},async recoverCrashedTransaction(){try{if(await dt.pathExists(rs)){let e=X(rs,null);if(e?.changes?.length>0){let n=X(nn,[]);n.some(t=>t.id===e.id)||(n.push(e),he(nn,n))}await dt.remove(rs).catch(()=>{})}}catch{}},async rollbackToBefore(e){let n=X(nn,null);if(!n)throw new Error("No transaction ledger found.");let t=n.findIndex(a=>a.id===e);if(t===-1)throw new Error(`Transaction [${e}] not found.`);let o=n[t].chatId,s=n[t].prompt,i=n.slice(t).filter(a=>a.chatId===o&&!a.reverted).reverse();for(let a of i){for(let r of[...a.changes].reverse())await za(r,a);for(let r of a.changes)if(r.backupFile){let h=sn.join(Un,a.chatId,r.backupFile);await dt.remove(h).catch(()=>{})}n=n.filter(r=>r.id!==a.id),he(nn,n)}return{success:!0,chatId:o,targetPrompt:s}},async getChatHistory(e){try{return X(nn,[]).filter(t=>t.chatId===e&&!t.reverted)}catch{return[]}},async deleteChatBackups(e){try{await dt.remove(sn.join(Un,e));let n=X(nn,[]),t=n.filter(o=>o.chatId!==e);n.length!==t.length&&he(nn,t)}catch{}}};var wr=Promise.resolve(),To=e=>{let n=wr.then(async()=>{try{return await e()}catch(t){throw console.error("Lock Operation Failed:",t),t}});return wr=n.catch(()=>{}),n},ls=async()=>{await Ct.ensureDir($s);let e={};if(await Ct.pathExists(Es))try{e=X(Es,{})}catch{e={}}for(let n in e){let t=ko.join($s,`${n}.json`);Object.defineProperty(e[n],"messages",{get:()=>{if(Ct.existsSync(t))try{return X(t,[])}catch{return[]}return[]},set:o=>{try{he(t,o)}catch{}},enumerable:!1,configurable:!0})}return e},fd=async(e,n,t)=>To(async()=>{await Ct.ensureDir($s);let o=await ls(),s=o[e],i=(t||[]).filter(y=>!y.isUpdateNotification&&(!y.isMeta||y.text&&y.text.includes("Request Cancelled")));try{(await Ft()).systemSettings?.preserveThinking===!1&&(i=i.filter(m=>m.role!=="think"))}catch{}let a=y=>{if(!y)return;let m=typeof y=="string"?y:y.text||y.content||"";if(!m||typeof m!="string")return;let w=m.replace(/\s*\n+\s*\[Prompted on:.*?\]/g,"").replace(/\[\/?(?:STEERING HINT|QUESTION)(?::\s*\w+)?\]/gi,"").trim();if(!w)return;let x=w.split(/\s+/),S;return x.length>7?S=x.slice(0,7).join(" ")+"...":w.length>45?S=w.substring(0,45).trimEnd()+"...":S=w,S},r,h=i.filter(y=>y.role==="user"),d=h[0],c=h[h.length-1],l=a(c),f=a(d);s&&s.prompt?Math.random()<.5&&l?r=l:r=s.prompt:r=f||l;let u=n||(s?s.name:`Session ${e.slice(-6)}`),p=ko.join($s,`${e}.json`);he(p,i),o[e]={name:u,prompt:r||void 0,updatedAt:Date.now()};let g={};for(let y in o)g[y]={name:o[y].name,prompt:o[y].prompt||void 0,updatedAt:o[y].updatedAt};he(Es,g)}),xr=async(e,n)=>To(async()=>{let t=await ls();t[e]?(t[e].name=n,t[e].updatedAt=Date.now()):t[e]={name:n,updatedAt:Date.now()};let o={};for(let s in t)o[s]={name:t[s].name,prompt:t[s].prompt||void 0,updatedAt:t[s].updatedAt};he(Es,o)}),Va=async e=>To(async()=>{let n=await ls();delete n[e];let t={};for(let a in n)t[a]={name:n[a].name,prompt:n[a].prompt||void 0,updatedAt:n[a].updatedAt};if(he(Es,t),await Ct.pathExists(Wn))try{let a=X(Wn,[]);if(Array.isArray(a)){let r=a.filter(h=>Object.keys(h)[0]!==String(e));he(Wn,r)}}catch{}let o=X(Xt,{});o[e]&&(delete o[e],he(Xt,o));let s=X(vn,{});s[e]&&(delete s[e],he(vn,s)),await ft.deleteChatBackups(e);let i=ko.join($s,`${e}.json`);if(await Ct.pathExists(i))try{await Ct.remove(i)}catch{}return n}),ud=()=>`flow-${Ya(6)}`,hd=async e=>{if(!e||e==="Never")return;let n=parseInt(e);if(isNaN(n))return;let t=await ls(),o=Date.now(),s=n*24*60*60*1e3,i=0;for(let a in t){let r=t[a];r.updatedAt&&o-r.updatedAt>s&&(await Va(a),i++)}return i},Ja=e=>{let n=e.replace(/[\[\]]/g,"").trim(),t=new Date(n);if(!isNaN(t.getTime()))return t.getTime();let o=n.split(/,\s*|\s+/);if(o.length===0)return null;let s=o[0],i=o[1]||"",a=o[2]||"",r=s.split(/[-\/.]/).map(Number);if(r.length!==3)return null;let h="en";try{h=Intl.DateTimeFormat().resolvedOptions().locale||"en"}catch{}let d=!/^en[-_]?us$|^en$/.test(h?.toLowerCase()),c,l,f;if(r[0]>1e3)c=r[0],l=r[1],f=r[2];else if(r[2]>1e3)c=r[2],r[0]>12?(f=r[0],l=r[1]):r[1]>12?(f=r[1],l=r[0]):d?(f=r[0],l=r[1]):(l=r[0],f=r[1]);else return null;if(l<1||l>12||f<1||f>31)return null;let u=0,p=0,g=0;if(i){let m=i.split(":").map(Number);u=m[0]||0,p=m[1]||0,g=m[2]||0,a.toLowerCase()==="pm"&&u<12?u+=12:a.toLowerCase()==="am"&&u===12&&(u=0)}let y=new Date(c,l-1,f,u,p,g);return isNaN(y.getTime())?null:y.getTime()},Xa=async e=>{try{if(!await Ct.pathExists(e))return;let n=await Ct.readFile(e,"utf8");if(!n.trim())return;let t=n.split(`
|
|
203
|
-
`),o=[],s=null,i=/^\s*(?:DEBUG|ERROR|SEARCH|PUPPETEER)\b/i;for(let l of t)i.test(l)?(s&&o.push(s),s={header:l,body:[]}):s?s.body.push(l):o.push({header:l,body:[]});s&&o.push(s);let a=10080*60*1e3,r=Date.now(),h=[],d=/(\d{1,4}[-\/.]\d{1,4}[-\/.]\d{1,4}(?:,\s*|\s+)?(?:\d{1,2}:\d{2}:\d{2}(?:\s*[aApP][mM])?)?)/;for(let l of o){if(i.test(l.header)){let p=l.header.match(d);if(p){let g=Ja(p[1]);if(g&&r-g>a)continue}}let u=l.header+(l.body.length>0?`
|
|
204
|
-
`+l.body.join(`
|
|
205
|
-
`):"");h.push(u)}let c=h.join(`
|
|
206
|
-
`).trim();c?await Ct.writeFile(e,c+`
|
|
207
|
-
`,"utf8"):await Ct.writeFile(e,"","utf8")}catch{}},pd=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 i=ko.join(t,s);(await Ct.stat(i)).isDirectory()?(await n(i),(await Ct.readdir(i)).length===0&&await Ct.remove(i)):s.endsWith(".log")&&await Xa(i)}};await n(e)}catch{}},br=(e,n=4)=>{if(e.length<=1)return e;let t=e[0],o=e.slice(1),s=n*2,i=o.slice(s);return[t,...i]};var md=async(e,n,t)=>To(async()=>{let o=X(Wn,[]);Array.isArray(o)||(o=[]);let s={total:n,context:t},i=o.findIndex(a=>Object.keys(a)[0]===String(e));i!==-1?o[i]={[String(e)]:s}:o.push({[String(e)]:s}),he(Wn,o)}),gd=async e=>{try{if(!await Ct.pathExists(Wn))return{total:0,context:0};let n=X(Wn,[]);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 yt from"fs-extra";import Sr from"path";var Qa=()=>Math.random().toString(36).substring(2)+Date.now().toString(36),se=null,Hn=null,kr=0,_s=!1,In={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 i of t)new Date(i)>=o&&(s[i]=e[i]);return s},Ro=async()=>{let e=new Date().toISOString().split("T")[0];try{!await yt.exists(Jt)&&await yt.exists(Yo)&&(await yt.ensureDir(Sr.dirname(Jt)),await yt.move(Yo,Jt))}catch{}let n=Jt+".tmp",t=null;try{if(await yt.exists(n)){let s=(await yt.readFile(n,"utf8")).trim(),i=null;if(s.startsWith("{")||s.startsWith("[")?i=JSON.parse(s):i=JSON.parse(Cs(s)),i&&i.date&&i.stats){t=i;try{await yt.rename(n,Jt)}catch{}}else try{await yt.remove(n)}catch{}}}catch{try{await yt.remove(n)}catch{}}if(!t)try{if(await yt.exists(Jt)){let s=(await yt.readFile(Jt,"utf8")).trim();s.startsWith("{")||s.startsWith("[")?t=JSON.parse(s):t=JSON.parse(Cs(s))}}catch{}let o=t;if(o){let s=o.stats||{...In},i={...In,...s};Array.isArray(i.imageCalls)||(i.imageCalls=[]);let a=o.history||{},r=Ms(a,e);if(Object.keys(a).length!==Object.keys(r).length&&(_s=!0),o.date===e)return{...o,stats:i,history:r};{let h=o.date,d=i,c={...r};return h&&(c[h]=d),{date:e,stats:{...In},history:Ms(c,e)}}}return{date:e,stats:{...In},history:{}}},oi=async()=>{if(!(!_s||!se))try{await yt.ensureDir(Sr.dirname(Jt));let e=null;try{if(await yt.exists(Jt)){let s=(await yt.readFile(Jt,"utf8")).trim();s.startsWith("{")||s.startsWith("[")?e=JSON.parse(s):e=JSON.parse(Cs(s))}}catch{}if(e&&e.date===se.date&&e.stats){for(let s in se.stats)if(e.stats[s]!==void 0){if(Array.isArray(se.stats[s])){let i=Array.isArray(e.stats[s])?e.stats[s]:[],a=se.stats[s],r=new Map;for(let h of[...i,...a])h&&h.timestamp&&r.set(h.timestamp,h);se.stats[s]=Array.from(r.values())}else if(typeof se.stats[s]=="number")se.stats[s]=Math.max(se.stats[s],Number(e.stats[s])||0);else if(se.stats[s]&&typeof se.stats[s]=="object"){let i=e.stats[s]||{},a=se.stats[s];for(let r in i)if(typeof i[r]=="number")a[r]=Math.max(a[r]||0,i[r]);else if(i[r]&&typeof i[r]=="object"){a[r]||(a[r]={});for(let h in i[r])if(typeof i[r][h]=="number")a[r][h]=Math.max(a[r][h]||0,i[r][h]);else if(i[r][h]&&typeof i[r][h]=="object"){a[r][h]||(a[r][h]={});for(let d in i[r][h])a[r][h][d]=Math.max(a[r][h][d]||0,i[r][h][d])}}}}}if(e&&e.history){let s={...se.history||{}};for(let i in e.history)if(s[i])for(let a in s[i])if(a==="imageCalls"){let r=Array.isArray(e.history[i].imageCalls)?e.history[i].imageCalls:[],h=Array.isArray(s[i].imageCalls)?s[i].imageCalls:[],d=new Map;for(let c of[...r,...h])c&&c.timestamp&&d.set(c.timestamp,c);s[i].imageCalls=Array.from(d.values())}else typeof s[i][a]=="number"&&(s[i][a]=Math.max(s[i][a],Number(e.history[i][a])||0));else s[i]=e.history[i];se.history=Ms(s,se.date||today)}else if(se&&se.history){let s=new Date().toISOString().split("T")[0];se.history=Ms(se.history,s)}se.saveId=Qa();let n=Jt+".tmp",t=Gs(JSON.stringify(se,null,2));await yt.writeFile(n,t,"utf8");let o=await yt.open(n,"r+");await yt.fsync(o),await yt.close(o),await yt.rename(n,Jt),_s=!1,kr=Date.now()}catch{}},Eo=()=>{if(_s=!0,Hn)return;let e=Date.now(),n=Math.max(0,1500-(e-kr));Hn=setTimeout(async()=>{await oi(),Hn=null},n),Hn.unref&&Hn.unref()},Td=async()=>{se=await Ro(),_s&&Eo()},Rd=async()=>{Hn&&(clearTimeout(Hn),Hn=null),await oi()},Tn=async()=>{let e=new Date().toISOString().split("T")[0];if(!se)se=await Ro();else if(se.date!==e){let n=se.date,t=se.stats,o=se.history||{};t&&(o[n]=t),se={date:e,stats:{...In},history:Ms(o,e)},_s=!0,await oi()}return se&&se.stats&&!Array.isArray(se.stats.imageCalls)&&(se.stats.imageCalls=[]),se.stats},Za=async()=>{let e=new Date().toISOString().split("T")[0];se||(se=await Ro()),se.date!==e&&await Tn();let n=se.history||{},t=Ms(n,e);se.history=t;let o=se.stats||{...In},s={...In};s.imageCalls=[],s.models={};let i=(a,r)=>{for(let h in a)if(h==="imageCalls")a.imageCalls=[...a.imageCalls||[],...r.imageCalls||[]];else if(h==="models"){let d=r.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[h]=="number"&&(a[h]+=r[h]||0)};i(s,o);for(let a in t)i(s,t[a]);return s},It=async(e,n)=>{e==="toolSuccess"?Js.toolSuccess++:e==="toolFailure"?Js.toolFailure++:e==="toolDenied"&&Js.toolDenied++;let t=await Tn();t[e]!==void 0&&t[e]++,n&&e==="agent"&&(t.providerRequests||(t.providerRequests={}),t.providerRequests[n]=(t.providerRequests[n]||0)+1),Eo()},Js={linesAdded:0,linesRemoved:0,toolSuccess:0,toolFailure:0,toolDenied:0},Gt=async(e,n,t,o)=>{e==="linesAdded"?Js.linesAdded+=n:e==="linesRemoved"&&(Js.linesRemoved+=n);let s=await Tn();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 i=s.models[t][o];e==="tokens"&&(i.tokens+=Math.floor(n)),e==="cachedTokens"&&(i.cachedTokens+=Math.floor(n)),e==="candidateTokens"&&(i.candidateTokens+=Math.floor(n))}Eo()},el=async(e=1)=>{let n=new Date,t=n.toISOString().split("T")[0];se||(se=await Ro()),se.date!==t&&await Tn();let o=n.getFullYear(),s=n.getMonth();n.getDate()<e&&(s-=1,s<0&&(s=11,o-=1));let r=new Date(o,s,e).toISOString().split("T")[0],h=se.history||{},d=se.stats||{...In},c={...In};c.imageCalls=[],c.models={};let l=(f,u)=>{for(let p in f)if(p==="imageCalls")f.imageCalls=[...f.imageCalls||[],...u.imageCalls||[]];else if(p==="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],x=g[y][m];w.tokens+=x.tokens||0,w.cachedTokens+=x.cachedTokens||0,w.candidateTokens+=x.candidateTokens||0}}}else typeof f[p]=="number"&&(f[p]+=u[p]||0)};l(c,d);for(let f in h)f>=r&&f<t&&l(c,h[f]);return c},ii=async(e,n={})=>{let t=await Ft().catch(()=>({})),o=n.apiTier||t.apiTier||"Free",s=n.quotas||n.systemSettings?.quotas||t.quotas||{},i=s.providerBudgets||{},a=!!i.__useProvider,r=n.aiProvider||t.aiProvider||"Google",h=a&&!!i[r],d=()=>{if(h){let c=i[r];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 Tn(),p;s.resetMode==="Custom"?p=await el(s.resetDay||1):p=await Za();let g=0,y=0,m=0;if(h){g=u.providerRequests?.[r]||0;let w=u.models?.[r]||{};for(let S in w)y+=w[S]?.tokens||0;let x=p.models?.[r]||{};for(let S in x)m+=x[S]?.tokens||0}else g=u.agent||0,y=u.tokens||0,m=p.tokens||0;return o==="Free"&&u.agent+u.background>=999999?{allowed:!1,reason:"Free Tier Daily Usage Limit Exceeded"}:g>=c?{allowed:!1,reason:h?`Daily Request Limit Reached for ${r}`:"Daily Agent Request Limit Reached"}:y>=l?{allowed:!1,reason:h?`Daily Token Budget Exhausted for ${r}`:"Daily Token Budget Exhausted"}:m>=f?{allowed:!1,reason:h?`Monthly Token Budget Exhausted for ${r}`:"Monthly Token Budget Exhausted"}:{allowed:!0}}if(e==="background"){let c=await Tn();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 Tn()).search<(s.searchLimit||100);return{allowed:l,reason:l?void 0:"Search Quota Exceeded"}}return{allowed:!0}},Tr=async(e,n={})=>(await ii(e,n)).allowed,ri=e=>{if(!e||e.length===0)return[];let t=[...e].sort((s,i)=>s.timestamp-i.timestamp),o=[];for(let s of t){if(o.length>0){let i=o[o.length-1];if(s.timestamp>=i.start&&s.timestamp<i.end){i.calls.push(s),i.spent+=s.cost;continue}}o.push({start:s.timestamp,end:s.timestamp+36e5,calls:[s],spent:s.cost})}return o},Rr=(e,n)=>{if(!e||e.length===0)return .025;let o=ri(e);if(o.length===0)return .025;let s=[];for(let l of o){let f=.025;if(s.length>0){let p=s[s.length-1],g=!1;if(s.length>=2){let y=s[s.length-2];p.ratio>=.8&&y.ratio>=.8&&(g=!0)}if(g)f=.015;else{let y=p.limit,m=p.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 i=o[o.length-1];if(n<i.end)return s[s.length-1].limit;let a=s[s.length-1].limit,r=a,h=s[s.length-1].ratio,d=i.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:h>=.8?l=r===.015?.015:r:h<.4?l=Math.min(.025,r+.005):h>=.4&&h<.6?l=Math.min(.025,r+.004):l=Math.min(.025,r+.002),r=l,h=0,c=0,d+=36e5,a=l}return a},Er=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 Tn();s.imageCalls||(s.imageCalls=[]);let i=Date.now(),a=ri(s.imageCalls),r=0;if(a.length>0){let d=a[a.length-1];i>=d.start&&i<d.end&&(r=d.spent)}let h=Rr(s.imageCalls,i);return r+o<=h},$r=async()=>{let e=await Tn();e.imageCalls||(e.imageCalls=[]);let n=Date.now(),t=ri(e.imageCalls),o=[],s=0,i=0;if(t.length>0){let d=t[t.length-1];n>=d.start&&n<d.end&&(o=d.calls,s=d.spent,i=Math.max(0,Math.ceil((d.end-n)/(60*1e3))))}let a=Rr(e.imageCalls,n),r=Math.max(0,a-s),h=s;return{totalSpent:s,remaining:r,activeCallsCount:o.length,nextResetMin:i,reclaimCost:h,limit:a}},Cr=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 Tn();s.imageCalls||(s.imageCalls=[]),s.imageCalls.push({timestamp:Date.now(),cost:o}),Eo()};import Ar from"puppeteer";import vr from"fs";import Ir from"path";import _r from"os";import Xs from"path";import As from"fs";import{createRequire as tl}from"module";import{fileURLToPath as nl}from"url";var sl=tl(import.meta.url),Mr=Xs.dirname(nl(import.meta.url));function cs(){let e=_r.platform(),n=_r.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 i=Xs.resolve(Mr,"..","..",".puppeteerrc.cjs");if(As.existsSync(i)||(i=Xs.resolve(Mr,"..",".puppeteerrc.cjs")),!As.existsSync(i))return{};try{let a=sl(i),r=a.cacheDirectory,h=a.chrome?.version;if(r){if(process.env.PUPPETEER_CACHE_DIR=r,h){let l=Xs.join(r,"chrome",`${t}-${h}`,s,o);if(As.existsSync(l))return{executablePath:l,cacheDirectory:r}}let d=l=>{if(!As.existsSync(l))return null;try{let f=As.readdirSync(l),u=[];for(let p of f){let g=Xs.join(l,p),y;try{y=As.statSync(g)}catch{continue}if(y.isDirectory())u.push(g);else if(p.toLowerCase()===o.toLowerCase()&&(!h||g.includes(h)))return g}if(h){for(let p of u)if(p.includes(h)){let g=d(p);if(g)return g}}for(let p of u)if(!h||!p.includes(h)){let g=d(p);if(g)return g}}catch{}return null},c=d(r);if(c)return{executablePath:c,cacheDirectory:r}}}catch{}return{}}var ai=async e=>{let{query:n,limit:t=5,aiMode:o=!1}=I(e);if(!n)return'ERROR: Missing "query" argument for web_search.';let s=3,i=null;if(o){let a=`Query: ${n}
|
|
208
|
-
|
|
209
|
-
RESPONSE RULES:
|
|
210
|
-
- ANSWER CONCISELY WITH REQUIRED DETAILS UNDER 300 WORDS.
|
|
211
|
-
- DO NOT CITE, REFERENCE, OR MENTION SOURCES ANYWHERE BETWEEN THE MAIN RESPONSE.
|
|
212
|
-
- DO NOT USE MARKDOWN EXCEPT FOR THE SOURCES SECTION BELOW.
|
|
213
|
-
- END THE RESPONSE WITH EXACTLY:
|
|
214
|
-
|
|
215
|
-
Sources:
|
|
216
|
-
- <URL 1>
|
|
217
|
-
- <URL 2>
|
|
218
|
-
- <URL 3>
|
|
219
|
-
|
|
220
|
-
- LIST ONE RAW URL PER BULLET.
|
|
221
|
-
- DO NOT USE MARKDOWN LINKS.
|
|
222
|
-
- DO NOT INCLUDE ANY TEXT, NOTES, OR EXPLANATIONS AFTER THE SOURCES SECTION.`;for(let r=1;r<=s;r++){let h=null;try{let d=cs();h=await Ar.launch({headless:!0,executablePath:d.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let c=await h.newPage();await c.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.178 Safari/537.36"),await c.setViewport({width:1366,height:768});let l=r===1?Math.random()*1e3+500:Math.random()*2e3+1e3;await new Promise(C=>setTimeout(C,l));let f=`https://search.brave.com/ask?q=${encodeURIComponent(a)}&source=web`;await c.goto(f,{waitUntil:"domcontentloaded",timeout:18e4});let u=null,p=45e3,g=Date.now();for(;Date.now()-g<p&&(u=await c.evaluate(()=>{let C=Array.from(document.querySelectorAll('.message:not(.user), .answer-text, .llm-content, [data-type="answer"]')),k="";if(C.length>0&&(k=C.map(oe=>oe.innerText.trim()).filter(Boolean).join(`
|
|
223
|
-
|
|
224
|
-
`)),k||(k=document.body.innerText),k.includes("anomaly"))throw new Error("ANOMALY_DETECTED");let O=!!document.querySelector('.spinner, .loading, .typing, .streaming, [data-streaming="true"], [data-state="loading"], svg.animate-spin, circle[cx], div[class*="spin"]'),v=C[0]||document.body,L=v?v.innerText.trim():"",N=/^(?:[✓✔]\s*)?Finished/i.test(L)||!!(v&&v.querySelector(".status-finished, .finished")),j=!O&&(N||k.includes("Sources:")&&!O),V={};return document.querySelectorAll("a[href]").forEach(oe=>{let Ie=oe.getAttribute("href")||oe.href||"";if(Ie.includes("uddg=")&&(Ie=decodeURIComponent(Ie.split("uddg=")[1].split("&")[0])),Ie.includes("url=")&&(Ie=decodeURIComponent(Ie.split("url=")[1].split("&")[0])),Ie&&(Ie.startsWith("http://")||Ie.startsWith("https://"))&&!Ie.includes("search.brave.com")){let B=oe.innerText.trim();B&&(V[B]=Ie),oe.textContent=Ie}}),{isFinished:j,text:k,hrefMap:V}}),!(u&&u.isFinished));)await new Promise(C=>setTimeout(C,1e3));let y=(u?u.text:"")||"",m=u?u.hrefMap||{}:{},w="DO NOT INCLUDE ANY TEXT, NOTES, OR EXPLANATIONS AFTER THE SOURCES SECTION.";y.includes(w)&&(y=y.split(w).pop()),y=y.replace(/^.*?(Ctrl \+ Shift \+ O|Ask\nAll\nImages)/s,"").replace(/AI-generated answer\. Please verify critical facts\..*/s,"").replace(/Brave Search uses private usage metrics.*/s,"");let x=y,S="";if(y.includes("Sources:")){let C=y.split("Sources:");x=C[0],S=C.slice(1).join("Sources:")}let R=[];for(let C of x.split(`
|
|
225
|
-
`)){let k=C.trim();k&&(/^(View all|Finished|Searching|Answering|Thinking)$/i.test(k)||/^[\+\-]?\d+$/.test(k)||k.includes("search.brave.com")||k.startsWith("https://www.youtube.com/watch")||k.startsWith("https://youtube.com/watch")||R.push(C))}let E=R.join(`
|
|
226
|
-
`).replace(/^(?:[\+\-]?\d+\s*)+/i,"").replace(/\n{3,}/g,`
|
|
227
|
-
|
|
228
|
-
`).trim(),b=C=>!C||C.includes("search.brave.com")||C.includes("youtube.com")||C.includes("youtu.be"),T="";if(S){let C=S.match(/https?:\/\/[^\s\)\>]+/g)||[],k=[];for(let v of C){let L=v.replace(/[\.\,\;]+$/,""),N=Object.keys(m).find(j=>j.startsWith(L)||L.startsWith(j));N&&m[N]&&(L=m[N]),b(L)||k.push(L)}Object.values(m).forEach(v=>{!b(v)&&!k.includes(v)&&k.push(v)});let O=Array.from(new Set(k));O.length>0&&(T=`Sources:
|
|
229
|
-
`+O.map(v=>`- ${v}`).join(`
|
|
230
|
-
`))}let $=E+(T?`
|
|
231
|
-
|
|
232
|
-
`+T:"");if(!$||/^(\+\d+|Searching|Answering|Thinking|Finished)$/i.test($))throw new Error("EMPTY_AI_RESPONSE");return await h.close(),`AI Search results for [${n}]:
|
|
233
|
-
|
|
234
|
-
${$}`}catch(d){if(i=d,vr.writeFileSync(Ir.join(cn,"web_tools","search","ai_mode","ERROR.txt"),d.message),h&&await h.close(),r<s){let c=Math.pow(2,r)*1e3;await new Promise(l=>setTimeout(l,c))}}}}for(let a=1;a<=s;a++){let r=null;try{let h=cs();r=await Ar.launch({headless:!0,executablePath:h.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let d=await r.newPage();await d.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.178 Safari/537.36"),await d.setViewport({width:1366,height:768});let c=a===1?Math.random()*1e3+500:Math.random()*2e3+1e3;await new Promise(g=>setTimeout(g,c));let l=`https://html.duckduckgo.com/html/?q=${encodeURIComponent(n)}`;await d.goto(l,{waitUntil:"networkidle2",timeout:18e4});let f=await d.$$eval(".result",(g,y)=>g.slice(0,y).map((m,w)=>{let x=m.querySelector(".result__a"),S=m.querySelector(".result__snippet"),R=x?x.href:"";R.includes("uddg=")&&(R=decodeURIComponent(R.split("uddg=")[1].split("&")[0]));let E=x?x.innerText.trim():"No Title",b=S?S.innerText.trim():"No Snippet";return`${w+1}. ${E}
|
|
235
|
-
Source: ${R}
|
|
236
|
-
Snippet: ${b}`}),t);if(f.length===0){if((await d.evaluate(()=>document.body.innerText)).includes("anomaly"))throw new Error("ANOMALY_DETECTED");return await r.close(),`No results found for query: [${n}].`}let u=f.join(`
|
|
237
|
-
|
|
238
|
-
`);return await r.close(),`${o?`AI Mode temporarily failed, used Standard search.
|
|
239
|
-
|
|
240
|
-
`:""}Search results for [${n}]:
|
|
241
|
-
|
|
242
|
-
${u}`}catch(h){if(i=h,r&&await r.close(),vr.writeFileSync(Ir.join(cn,"web_tools","search","standard_mode","ERROR.txt"),h.message),a<s){let d=Math.pow(2,a)*1e3;await new Promise(c=>setTimeout(c,d))}}}return`ERROR: Search failed after ${s+1} attempts. Last error: ${i.message}`};import ol from"puppeteer";import il from"turndown";import{gfm as rl}from"turndown-plugin-gfm";var li=async e=>{let n=e;if(typeof e=="object"&&e!==null)n=e.url||e.targetUrl||e.href||"";else if(typeof e=="string"){let i=e.match(/url\s*=\s*["'](.*)["']/);n=i?i[1]:e}let t=typeof n=="string"?n.trim():"";if(!t)return"ERROR: No target URL provided.";let o=3,s=null;for(let i=1;i<=o;i++){let a=null;try{let r=cs();a=await ol.launch({headless:!0,executablePath:r.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let h=await a.newPage();await h.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.178 Safari/537.36"),await h.setViewport({width:1366,height:768});let d=i===1?Math.random()*1e3+500:Math.random()*2e3+1e3;await new Promise(g=>setTimeout(g,d)),await h.goto(t,{waitUntil:"networkidle2",timeout:18e4}),await new Promise(g=>setTimeout(g,5e3));let c=await h.evaluate(()=>{document.querySelectorAll("script, style, noscript, svg, canvas, iframe, ad, .ads, link, meta, img").forEach(S=>S.remove());let y=document.createNodeIterator(document.body,NodeFilter.SHOW_COMMENT),m;for(;m=y.nextNode();)m.remove();for(document.querySelectorAll("*").forEach(S=>{let R=S.attributes;for(let E=R.length-1;E>=0;E--){let b=R[E].name;b!=="href"&&b!=="src"&&S.removeAttribute(b)}});document.querySelector("div, span");)document.querySelectorAll("div, span").forEach(S=>{S.parentNode&&S.replaceWith(...S.childNodes)});document.querySelectorAll("br").forEach(S=>{S.replaceWith(document.createTextNode(`
|
|
243
|
-
|
|
244
|
-
`))});let x=()=>{let S=!1;document.querySelectorAll("*").forEach(R=>{R.childNodes.length===0&&!R.innerText.trim()&&(R.remove(),S=!0)}),S&&x()};return x(),document.body.innerHTML});if(!c)throw new Error("EMPTY_RENDER_RESULT");let l=c.replace(/<br\s*\/?>/gi,`
|
|
245
|
-
|
|
246
|
-
`).replace(/[ \t]+/g," ").replace(/>[ \t]+</g,"><").replace(/\n\s+/g,`
|
|
247
|
-
`).replace(/\n{3,}/g,`
|
|
248
|
-
|
|
249
|
-
`).trim(),f=new il({headingStyle:"atx",codeBlockStyle:"fenced"});f.use(rl);let u=f.turndown(l).replace(/\.\s*\n/g,`
|
|
250
|
-
`).replace(/ +/g," ").replace(/\t/g," ").replace(/\n\s+/g,`
|
|
251
|
-
`).replace(/\n{3,}/g,`
|
|
252
|
-
|
|
253
|
-
`),p=u.substring(0,5e4);return await a.close(),`Markdown parsed from [${t}]:
|
|
254
|
-
|
|
255
|
-
${p}${u.length>5e4?`
|
|
256
|
-
|
|
257
|
-
[TRUNCATED AT 50K CHARS]`:""}`}catch(r){if(s=r,a&&await a.close(),i<o){let h=Math.pow(2,i)*1e3;await new Promise(d=>setTimeout(d,h))}}}return`ERROR: Scrape failed after ${o+1} attempts. Last error: ${s.message}`};var al=4*(1024*2),ci=async(e,n={})=>{let t=c=>{let l=new RegExp(`${c}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),f=e.match(l);if(f)return f[2].trim();let u=new RegExp(`${c}\\s*[:=]\\s*([^,\\s)]+)`,"s"),p=e.match(u);return p?p[1].trim():null},o=t("action"),s=t("method"),i=t("content"),a=t("content-new"),r=t("content-old"),h=t("id"),d=t("chat-id")||n.chatId||n.sessionId||"default-session";if(o==="temp"){if(!i)return"ERROR: Missing 'content' for temp memory.";let c=X(Xt,{});c[d]||(c[d]=[]),c[d].push(i),he(Xt,c);let l=c[d].reduce((f,u)=>f+u.length,0);return`SUCCESS: Temporary context saved for session [${d}]. (Size: ${l} chars)`}if(o==="user"){let c=X(Dt,[]).map(l=>(l.score===void 0&&(l.score=.5),l));if(s==="add"){if(!i)return"ERROR: Missing 'content' for memory addition.";let l=new Date,f=`${l.getDate()}/${l.getMonth()+1}/${l.getFullYear()}`,u=i.includes("[Saved on:")?i:`${i.trim()} [Saved on: ${f}]`,p=al,g=c.reduce((x,S)=>x+(S.memory?.length||0),0);for(;c.length>0&&g+u.length>p;){let x=c.shift();g-=x.memory?.length||0}let y=t("score"),m=y?parseFloat(y):.5,w={id:`mem-${Date.now().toString(36)}`,memory:u,score:Math.min(2,isNaN(m)?.5:m)};return c.push(w),he(Dt,c),`SUCCESS: Memory added with ID [${w.id}] and score [${w.score}]. (Vault Size: ${g+u.length} chars)`}if(s==="update"){let l=h||r,f=a||i;if(!l||!f)return"ERROR: Missing 'id' or content for update.";let u=c.findIndex(m=>m.id===l);if(u===-1)return`ERROR: Memory ID [${l}] not found.`;let p=new Date,g=`${p.getDate()}/${p.getMonth()+1}/${p.getFullYear()}`,y=f.includes("[Saved on:")?f:`${f.trim()} [Saved on: ${g}]`;return c[u].memory=y,he(Dt,c),`SUCCESS: Memory [${l}] updated.`}if(s==="delete"){let l=h||i;if(!l)return"ERROR: Missing 'id' for deletion.";let f=c.length,u=c.filter(p=>p.id!==l);return u.length===f?`ERROR: Memory ID [${l}] not found.`:(he(Dt,u),`SUCCESS: Memory [${l}] deleted.`)}return`ERROR: Invalid method [${s}] for user memory. Use 'add', 'update', or 'delete'.`}return`ERROR: Unknown action [${o}] for memory tool.`};var di=async(e,n={})=>{let t=I(e).title,o=n.chatId||n.sessionId;if(!o)return"ERROR: No active chatId found in tool context.";if(!t)return"ERROR: Missing 'title' argument.";try{return await xr(o,t),`SUCCESS: Chat title updated to [${t}] for session [${o}].`}catch(s){return`ERROR: Failed to update chat title: ${s instanceof Error?s.message:String(s)}`}};import $o from"fs";import Or from"path";var Qs=async(e,n={})=>{let{path:t,StartLine:o,EndLine:s,start_line:i,end_line:a,startLine:r,endLine:h}=I(e),d=parseInt(o||i||r),c=parseInt(s||a||h),l=!isNaN(d),f=!isNaN(c),u=d||1,p=c||(d?d+800:800);if(!t)return'ERROR: Missing "path" argument for view_file.';let g=Or.resolve(process.cwd(),t);try{if(!$o.existsSync(g))return`ERROR: File [${t}] does not exist.`;if($o.statSync(g).isDirectory())return`ERROR: Path [${t}] is a directory. Use list_files instead.`;let m=Or.extname(t).toLowerCase();if([".mp4",".mkv",".avi",".mov",".webm",".flv",".wmv",".mpeg",".mpg"].includes(m))return`ERROR: Unable to read. Type ${m.slice(1).toUpperCase()} not supported`;let x={".pdf":"application/pdf",".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".webp":"image/webp",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".doc":"application/msword"};if(x[m]){if(!(n.isMultiModal!==!1))return`ERROR: Multimodality is not supported for the current model. Unable to load [${t}].`;let L=$o.readFileSync(g).toString("base64"),N=x[m];return{text:`[BINARY FILE]: ${t} (${N}) - Loaded as multimodal part.`,binaryPart:{inlineData:{data:L,mimeType:N}}}}let S=$o.readFileSync(g,"utf8");S.startsWith("\uFEFF")&&(S=S.slice(1)),S=S.replace(/\r\n/g,`
|
|
258
|
-
`).replace(/\r/g,`
|
|
259
|
-
`);let R=S.split(`
|
|
260
|
-
`),E=R.length;!l&&!f&&E>800&&(u=1,p=50);let b=Math.max(0,u-1),T=Math.min(E,p),$=R.slice(b,T),C=`File: [${t}] (Showing lines ${b+1}-${T} of ${E}).`,k=$.map((O,v)=>`${String(b+v+1).padStart(4)}: ${O.trimEnd()}`).join(`
|
|
261
|
-
`);return`${C}
|
|
262
|
-
|
|
263
|
-
${k}`}catch(y){let m=y instanceof Error?y.message:String(y);return`ERROR: Failed to read file [${t}]: ${m}`}};import vs from"fs";import Lr from"path";var fi=async(e,n={})=>{let{path:t,content:o}=I(e);if(!t)return'ERROR: Missing "path" argument for write_file.';if(o===void 0)return'ERROR: Missing "content" argument for write_file.';o=o.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
|
|
264
|
-
`).replace(/\r/g,`
|
|
265
|
-
`);let s=Lr.resolve(process.cwd(),t),i=Lr.dirname(s);try{await ft.recordFileChange(s);let a="";if(vs.existsSync(s))try{a=`Old File contents:
|
|
266
|
-
${vs.readFileSync(s,"utf8").split(/\r?\n/).map((R,E)=>`${E+1} | ${R}`).join(`
|
|
267
|
-
`)}
|
|
268
|
-
|
|
269
|
-
`}catch{a=`[Note: Could not read existing file for reversal reference]
|
|
270
|
-
|
|
271
|
-
`}vs.existsSync(i)||vs.mkdirSync(i,{recursive:!0});let h=(x=>x.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
|
|
272
|
-
`).replace(/\r/g,`
|
|
273
|
-
`))(o),d=h.endsWith(`
|
|
274
|
-
`)?h:h+`
|
|
275
|
-
`,c=d.split(/\r?\n/).length,l=Buffer.byteLength(d,"utf8");vs.writeFileSync(s,d,"utf8");let f=vs.readFileSync(s,"utf8"),u=Buffer.byteLength(f,"utf8"),p=f.split(/\r?\n/),g=p.length;if(u===0&&l>0)return f=null,`ERROR: CRITICAL FAILURE: Verification failed. File [${t}] is empty on disk!`;let y="";if(g<=100)y=p.join(`
|
|
276
|
-
`);else{let x=p.slice(0,50).join(`
|
|
277
|
-
`),S=p.slice(-50).join(`
|
|
278
|
-
`);y=`${x}
|
|
279
|
-
|
|
280
|
-
... [${g-100} lines truncated] ...
|
|
281
|
-
|
|
282
|
-
${S}`}f=null;let{systemSettings:m}=await Ft(),w=`SUCCESS: File [${t}] saved.
|
|
283
|
-
- Stats: [${g} lines, ${(u/1024).toFixed(1)} KB]
|
|
284
|
-
${a}- Content Preview:
|
|
285
|
-
|
|
286
|
-
${y}`;if(m?.compressToolResults&&g>60){let x=d.split(/\r?\n/),S=x.slice(0,25).join(`
|
|
287
|
-
`)===p.slice(0,25).join(`
|
|
288
|
-
`),R=x.slice(-25).join(`
|
|
289
|
-
`)===p.slice(-25).join(`
|
|
290
|
-
`);S&&R&&(w=`[[SAME]]
|
|
291
|
-
${w}`)}return w}catch(a){let r=a instanceof Error?a.message:String(a);return`ERROR: Failed to write file [${t}]: ${r}`}};import mi from"fs";import xl from"path";import ll from"os";var hn=e=>typeof e!="string"?e:e.length>12?(e+"").replace("",""):e,Pr=(e,n)=>{if(!e)return"";let t=/\x1B\[[0-?]*[ -/]*[@-~]/g,o=e.split(`
|
|
292
|
-
`),s=[];if(n<=5)return e;let i=a=>a.replace(t,"").length;return o.forEach(a=>{if(i(a)<=n){s.push(a);return}let h=a.split(/(\s+)/),d="",c=0,l=a.match(/^(\s*)/),f=l?l[1]:"";h.forEach((u,p)=>{if(u.length===0)return;let g=i(u);if(c+g>n)if(d.trim().length>0)s.push(d.trimEnd()),d=f.substring(0,Math.min(f.length,8))+u,c=i(d);else if(t.test(u))s.push(u),d=f,c=i(d);else{let y=u;for(;i(y)>n&&n>10;)s.push(y.substring(0,n)),y=y.substring(n);d=y,c=i(d)}else d+=u,c+=g}),(d.trimEnd().length>0||d===f)&&s.push(d.trimEnd())}),hn(s.join(`
|
|
293
|
-
`))},ff=e=>{if(!e&&e!==0)return"0.0k";let n=typeof e=="string"?parseFloat(e):e;return n>=1e6?`${(n/1e6).toFixed(1)}m`:n>=1e3?`${(n/1e3).toFixed(1)}k`:n.toString()},uf=(e,n=40)=>{let t=An.replaceAll("\\\\","\\");if(e=e.replace(ll.homedir(),"~").replace(t,"FluxFlow").replaceAll("\\","/"),!e||e.length<=n)return hn(e);let o=Math.floor((n-3)/2);return hn(e.substring(0,o)+"..."+e.substring(e.length-o).replaceAll("\\","/"))},Co=e=>{let n=[],t=new Set,o=e.allowMultiple===!0||String(e.allowMultiple).toLowerCase()==="true";Object.keys(e).forEach(h=>{let d=h.match(/^(searchContent|search_content|replaceContent|replace_content|newContent|new_content|content_to_replace|content_to_add|searchBlock|search_block|newBlock|new_block)_?(\d+)?$/i);if(d){let c=d[2]?parseInt(d[2],10):1;t.add(c)}});let s=Array.from(t).sort((h,d)=>h-d),i=["searchContent","search_content","replaceContent","replace_content","content_to_replace","searchBlock","search_block"],a=["newContent","new_content","content_to_add","newBlock","new_block"],r=(h,d,c)=>{let l,f;for(let u of d){let p=h===1?[`${u}1`,u,`${u}_1`]:[`${u}${h}`,`${u}_${h}`];for(let g of p)if(e[g]!==void 0){l=e[g];break}if(l!==void 0)break}for(let u of c){let p=h===1?[`${u}1`,u,`${u}_1`]:[`${u}${h}`,`${u}_${h}`];for(let g of p)if(e[g]!==void 0){f=e[g];break}if(f!==void 0)break}return{r:l,n:f}};for(let h of s){let{r:d,n:c}=r(h,i,a);if(d!==void 0&&c!==void 0)n.push({replace:d,new:c});else if(d!==void 0||c!==void 0)return{error:`Mismatched replacement pair for index ${h}. Both replacement and new content must be provided.`,allowMultiple:o}}return{patchPairs:n,allowMultiple:o}},cl=e=>{if(!e)return null;let n="",t=0,o=e.length;for(;t<o;){let s=e[t];if(s==="\\"){for(;t<o&&e[t]==="\\";)t++;n+="\\\\*"}else if(s===`
|
|
294
|
-
`)n+="(?:\\r?\\n|\\\\*n|\\\\*r|\\s*)",t++;else if(s==="\r")n+="(?:\\r|\\\\*r)?",t++;else if(s===" ")n+="(?:\\t|\\\\*t|\\s*)",t++;else if(s==='"'||s==="'"||s==="`")n.endsWith("\\\\*")||(n+="\\\\*"),n+=s,t++;else if(/[.*+?^${}()|[\]]/.test(s))n+="\\"+s,t++;else if(/\s/.test(s)){for(;t<o&&/\s/.test(e[t])&&e[t]!==`
|
|
295
|
-
`&&e[t]!=="\r"&&e[t]!==" ";)t++;n+="\\s*"}else n+=s,t++}if(!n)return null;try{return new RegExp(n,"g")}catch{return null}},_o=(e,n,t={})=>{let o=typeof t=="boolean"?t:!!(t&&t.allowMultiple),s=e.replace(/\r\n/g,`
|
|
296
|
-
`).replace(/\r/g,`
|
|
297
|
-
`),i=m=>m.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
|
|
298
|
-
`).replace(/\r/g,`
|
|
299
|
-
`),a=m=>m.match(/^\s*/)[0],r=m=>{let w=m.split(`
|
|
300
|
-
`).filter(S=>S.trim()!=="");if(w.length===0)return"";let x=a(w[0]);for(let S of w){let R=a(S);R.length<x.length&&(x=R)}return x},h=(m,w,x="")=>{if(!m||w===void 0)return m;let R=/^\t/m.test(w)?" ":" ",E=O=>O.split(`
|
|
301
|
-
`).find(v=>v.trim()!=="")??"",b=E(w).match(/^\s*/)[0].length,T=E(m).match(/^\s*/)[0].length,$=b-T,C=(x.match(/^\s*/)||[""])[0].length;return m.split(`
|
|
302
|
-
`).map((O,v)=>{if(O.trim()===""&&v!==0)return"";let L=O.match(/^\s*/)[0].length,N=Math.max(0,L+$);return v===0&&(N=Math.max(0,N-C)),R.repeat(N)+O.trimStart()}).join(`
|
|
303
|
-
`)},d=[];for(let m=0;m<n.length;m++){let w=n[m],x=(w.replace||"").trim(),S=i(w.new||"");if(x.startsWith("^LINE:")&&x.endsWith("$")){let C=x.slice(6,-1).trim().split(".."),k=parseInt(C[0]),O=C[1]!==void 0?parseInt(C[1]):k;if(!isNaN(k)&&!isNaN(O)){let v=s.split(`
|
|
304
|
-
`);if(k<1||k>v.length||O<k||O>v.length){d.push({index:m,success:!1,error:`Block ${m+1}: Line range ^LINE:${k}..${O}$ out of bounds (file has ${v.length} lines).`});continue}let N=v.slice(k-1,O).join(`
|
|
305
|
-
`),j=0;for(let V=0;V<k-1;V++)j+=v[V].length+1;d.push({index:m,success:!0,startPos:j,firstMatchContent:N,content_to_add:S});continue}}let R=i(w.replace||"");if(R===""&&S===""){d.push({index:m,success:!1,error:`Block ${m+1}: Empty replace and add content.`});continue}let E=R.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),b=null;if(R!==""&&s.includes(R))b=new RegExp(E,"g");else{let $=R.split(`
|
|
306
|
-
`).map(C=>C.trim()).filter(C=>C.length>0).map(C=>C.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\s+/g,"\\s*"));if($.length>0){let C=$.join("\\s*");try{b=new RegExp(C,"g")}catch{b=new RegExp(E,"g")}}else b=new RegExp(E,"g")}let T=[...s.matchAll(b)];if(T.length===0&&R!==""){let $=cl(R);$&&(T=[...s.matchAll($)])}if(T.length===0){d.push({index:m,success:!1,error:`Block ${m+1}: Could not find match.`});continue}if(T.length>1&&!o){d.push({index:m,success:!1,error:`Block ${m+1}: Found ${T.length} matches (must be unique or use allowMultiple: true if sure).`});continue}for(let $ of T)d.push({index:m,success:!0,startPos:$.index,firstMatchContent:$[0],content_to_add:S})}let c=d.filter(m=>m.success).sort((m,w)=>m.startPos-w.startPos);for(let m=0;m<c.length-1;m++){let w=c[m],x=c[m+1];w.startPos+w.firstMatchContent.length>x.startPos&&(w.success=!1,w.error=`Block ${w.index+1}: Overlaps with another block.`,x.success=!1,x.error=`Block ${x.index+1}: Overlaps with another block.`)}let l=new Map,f=s,u=0,p=0,g=d.filter(m=>m.success).sort((m,w)=>m.startPos-w.startPos);for(let m of g){let w=m.startPos,x=s.substring(0,w).split(`
|
|
307
|
-
`).length,S=w+u,R=x+p,E=f.lastIndexOf(`
|
|
308
|
-
`,S)+1,b=f.substring(E,S),T=h(m.content_to_add,m.firstMatchContent,b),$=f.split(`
|
|
309
|
-
`),C=[];for(let L=Math.max(0,R-4);L<R-1;L++)C.push({num:L+1,text:$[L]});let k=m.firstMatchContent.split(`
|
|
310
|
-
`),O=[],v=R+k.length-1;for(let L=v;L<Math.min($.length,v+3);L++)O.push({num:L+1,text:$[L]});l.set(m,{success:!0,index:m.index,oldContent:m.firstMatchContent,newContent:T,originalStartLine:x,finalStartLine:R,contextBefore:C,contextAfter:O}),f=f.substring(0,S)+T+f.substring(S+m.firstMatchContent.length),u+=T.length-m.firstMatchContent.length,p+=T.split(`
|
|
311
|
-
`).length-m.firstMatchContent.split(`
|
|
312
|
-
`).length}let y=[];for(let m=0;m<n.length;m++){let w=g.filter(x=>x.index===m);if(w.length>0)for(let x of w)l.has(x)&&y.push(l.get(x));else{let x=d.find(S=>S.index===m);y.push({success:!1,error:x?x.error:`Block ${m+1}: Unknown error.`})}}return{content:f,results:y}},Mo=(e,n,t,o=8,s=!1)=>{if(!t||t.length===0)return"";let i=e.split(/\r?\n/),a=n.split(/\r?\n/),r=Math.max(i.length,a.length,1),h=Math.max(4,String(r).length),d=g=>String(g).padStart(h," "),c=`[DIFF_START]
|
|
313
|
-
`,l="\u2550".repeat(88),f=0,u=null,p=t.filter(g=>g.success).sort((g,y)=>g.originalStartLine-y.originalStartLine);if(p.forEach((g,y)=>{let m=g.finalStartLine!==void 0?g.finalStartLine:g.originalStartLine;if(u===null)for(f=Math.max(0,m-4);f<m-1;)c+=`[UI_CONTEXT] ${d(f+1)} |${a[f]||""}
|
|
314
|
-
`,f++;else{let T=u,$=T.originalStartLine+T.oldContent.split(`
|
|
315
|
-
`).length-1;if(g.originalStartLine-$-1>=o){let k=Math.min(a.length,f+3);for(;f<k;)c+=`[UI_CONTEXT] ${d(f+1)} |${a[f]||""}
|
|
316
|
-
`,f++;for(c+=`[UI_CONTEXT] ${l}
|
|
317
|
-
`,f=Math.max(f,m-4);f<m-1;)c+=`[UI_CONTEXT] ${d(f+1)} |${a[f]||""}
|
|
318
|
-
`,f++}else for(;f<m-1;)c+=`[UI_CONTEXT] ${d(f+1)} |${a[f]||""}
|
|
319
|
-
`,f++}let w=g.originalStartLine-1,x=i[w]||"",S=g.oldContent.split(`
|
|
320
|
-
`),R=x.match(/^\s*/),E=R?R[0]:"";S.forEach((T,$)=>{let C=T;if(S.length===1&&x.trim().length>0&&x.includes(T.trim()))C=x;else if($===0){let k=T.match(/^\s*/);(k?k[0]:"").length<E.length&&x.includes(T.trim())&&(C=E+T.trimStart())}c+=`-${d(g.originalStartLine+$)} |${C}
|
|
321
|
-
`});let b=f;if(g.finalStartLine!==void 0)b=g.finalStartLine-1+(g.newContent?g.newContent.split(`
|
|
322
|
-
`).length:0);else{let T=g.originalStartLine+S.length-1,$=i[T]||null;if($!==null){let C=y<p.length-1?(p[y+1].originalStartLine||a.length)+10:a.length;for(let k=f;k<C;k++){if(a[k]===$){b=k;break}k===a.length-1&&(b=a.length)}}else b=a.length}for(;f<b;)c+=`+${d(f+1)} |${a[f]||""}
|
|
323
|
-
`,f++;u=g}),u!==null){let g=Math.min(a.length,f+3);for(;f<g;)c+=`[UI_CONTEXT] ${d(f+1)} |${a[f]||""}
|
|
324
|
-
`,f++}if(s){let g=`[DIFF_START]
|
|
325
|
-
`,y=c.substring(g.length),m=`[UI_CONTEXT] ${l}
|
|
326
|
-
`,x=y.split(m).map(S=>S.split(`
|
|
327
|
-
`).filter(E=>E.trim()!=="").length>45?`[[VERIFIED]]
|
|
328
|
-
${S}
|
|
329
|
-
[[/VERIFIED]]`:S);c=g+x.join(m)}return c+="[DIFF_END]",hn(c)},dl=e=>{if(!e)return null;let n=e.replace("[UI_CONTEXT]","").replace(/\r/g,""),t=n.startsWith("-"),o=n.startsWith("+"),s=t||o?n.substring(1):n,i=s.indexOf("|"),a=i!==-1?hn(s.substring(0,i).trim()):"",r=hn(i!==-1?s.substring(i+1):s);return{isR:t,isA:o,num:a,content:r}},fl=(e,n)=>{if(!e&&!n)return 1;if(!e||!n)return 0;let t=e.length,o=n.length,s=e,i=n;t<o&&(s=n,i=e);let a=s.length,r=i.length,h=new Int32Array(r+1),d=new Int32Array(r+1);for(let f=0;f<=r;f++)h[f]=f;for(let f=1;f<=a;f++){d[0]=f;let u=s[f-1];for(let p=1;p<=r;p++)u===i[p-1]?d[p]=h[p-1]:d[p]=Math.min(h[p],d[p-1],h[p-1])+1;h.set(d)}let c=h[r],l=Math.max(t,o);return l===0?1:1-c/l},Dr=e=>{let n=[],t=[];e.forEach((c,l)=>{c.parsed.isR?n.push({index:l,content:c.parsed.content}):c.parsed.isA&&t.push({index:l,content:c.parsed.content})});let o=n.length,s=t.length;if(o===0||s===0)return;let i=Array.from({length:o+1},()=>Array(s+1).fill(0)),a=Array.from({length:o+1},()=>Array(s+1).fill(""));for(let c=1;c<=o;c++)a[c][0]="up";for(let c=1;c<=s;c++)a[0][c]="left";let r=Array.from({length:o},()=>Array(s).fill(0));for(let c=0;c<o;c++)for(let l=0;l<s;l++)r[c][l]=fl(n[c].content.trim(),t[l].content.trim());for(let c=1;c<=o;c++)for(let l=1;l<=s;l++){let f=r[c-1][l-1],u=f>=.2?f:-10,p=i[c-1][l-1]+u,g=i[c-1][l],y=i[c][l-1];p>=g&&p>=y?(i[c][l]=p,a[c][l]="diag"):g>=y?(i[c][l]=g,a[c][l]="up"):(i[c][l]=y,a[c][l]="left")}let h=o,d=s;for(;h>0||d>0;)if(a[h][d]==="diag"){if(r[h-1][d-1]>=.2){let l=n[h-1].index,f=t[d-1].index;e[l].pairContent=e[f].parsed.content,e[f].pairContent=e[l].parsed.content}h--,d--}else a[h][d]==="up"?h--:d--},Gn=new Map,ds=new Map,Fr=200,ui=6,pi=(e,n)=>{n.set(e.key,e),e.type==="chunk"&&e.blocks&&e.blocks.forEach(t=>pi(t,n))},hf=(e,n)=>{if(!e)return{completed:[],active:[]};let t=`${e.id}-${e.text?.length||0}-${n}-${e.isStreaming}-${e.workedDuration||0}`;if(!e.isStreaming&&Gn.has(t))return Gn.get(t);let o=hn(wl(e.text||"",e.role==="think")),s=`${e.id}-${n}`,i=new Map;if(e.isStreaming){let p=ds.get(s);p&&o.startsWith(p.text)&&(i=p.blocksMap)}let a=(p,g,y,m={})=>{let w=i.get(p);if(w&&w.text===y&&w.type===g&&!!w.isActiveBlock==!!m.isActiveBlock&&!!w.isStreaming==!!m.isStreaming&&w.pairContent===m.pairContent)return w;let x=hn(y),S={...m};return typeof S.pairContent=="string"&&(S.pairContent=hn(S.pairContent)),Array.isArray(S.wrappedLines)&&(S.wrappedLines=S.wrappedLines.map(hn)),{key:p,isStreamingMsg:!!e.isStreaming,workedDuration:e.workedDuration,type:g,text:x,msg:g==="full-message"?e:void 0,...S}};if(o.includes("- Content Preview:")){let p="",g=o.match(/File\s+\[(.*?)\]/i);g&&(p=g[1].split(".").pop().toLowerCase());let S=((o.split("- Content Preview:")[1]||"").split("[SYSTEM] Check the content preview for verification [/SYSTEM]")[0]?.trim()||"").split(`
|
|
330
|
-
`).map(k=>k.replace(/\r$/,"")),R=String(S.length).length,E=[],b=null,T=[],$=()=>{if(!T.length)return;let k=T;T=[],E.push(k.length===1?k[0]:{key:`${k[0].key}-chunk`,type:"chunk",blocks:k})},C=n-(R+6);return S.forEach((k,O)=>{let v=O===S.length-1,L=Pr(k,C).split(`
|
|
331
|
-
`),N=a(`${e.id||Date.now()}-write-line-${O}`,"write-line",k,{gutterWidth:R,lineNum:O+1,isFirstLine:O===0,isLastLine:v,extension:p,wrappedLines:L});v&&e.isStreaming?($(),b=N):(T.push(N),T.length>=ui&&$())}),$(),{completed:E,active:b?[b]:[]}}if(o.includes("[DIFF_START]")){let p=o.match(/\[DIFF_START\]([\s\S]*?)(?:\[DIFF_END\]|$)/),y=(p?p[1].trim():"").split(`
|
|
332
|
-
`).map(b=>b.replace(/\r$/,"")),m=y.map(b=>({line:b,parsed:dl(b),pairContent:null})),w=[];for(let b=0;b<m.length;b++){let T=m[b];T.parsed&&(T.parsed.isR||T.parsed.isA)?w.push(T):w.length>0&&(Dr(w),w=[])}w.length>0&&Dr(w);let x=[],S=null,R=[],E=()=>{if(!R.length)return;let b=R;R=[],x.push(b.length===1?b[0]:{key:`${b[0].key}-chunk`,type:"chunk",blocks:b})};return y.forEach((b,T)=>{let $=T===y.length-1,C=m[T].parsed,k=null;C&&(k=Pr(C.content,n-17).split(`
|
|
333
|
-
`));let O=a(`${e.id||Date.now()}-diff-${T}`,"diff-line",b,{isFirstLine:T===0,isLastLine:$,pairContent:m[T].pairContent,wrappedLines:k});$&&e.isStreaming?(E(),S=O):(R.push(O),R.length>=ui&&E())}),E(),{completed:x,active:S?[S]:[]}}if(e.role==="system"||e.isLogo||e.isHelpRecord||e.isTerminalRecord||e.isHomeWarning||e.isImageStats||e.isAskRecord||e.isAboutRecord||e.isUpdateNotification||e.role==="user")return{completed:[a(`${e.id||Date.now()}-full`,"full-message",o)],active:[]};if(!o&&!e.isStreaming){let p={completed:[],active:[]};return Gn.set(t,p),p}let r=[],h=null,d=[],c=null,l=()=>{if(!d.length)return;let p=d;d=[],c=null,r.push(p.length===1?p[0]:{key:`${e.id||"x"}-chunk-${p[0].key}`,type:"chunk",blocks:p})},f=(p,g=!1)=>{if(c!==null&&c!==p.type&&l(),d.push(p),c=p.type,d.length>=ui){if(e.isStreaming&&g)return;l()}};if(e.role==="think"){r.push(a(`${e.id}-header`,"think-header",""));let p=o.split(`
|
|
334
|
-
`);p.forEach((g,y)=>{let m=y===p.length-1;f(a(`${e.id}-${y}`,"think-line",g,{}),m)}),e.isStreaming||(l(),r.push({key:`${e.id}-footer-padding`,type:"think-footer-padding",text:""}))}else{let p=o.split(`
|
|
335
|
-
`),g=!1,y=[],m=!1,w=!1,x="",S=0,R=0;p.forEach((E,b)=>{let T=b===p.length-1,$=E.trim().startsWith("|"),C=E.trim().startsWith("```");if(w){if(E.includes("</think>")||E.includes("<channel|>")||E.includes("</thought>")){let k=E.split(/(?:<\/(think|thought|thoughts)>|<channel\|>)/i),O=k[0]||"",v=k.slice(2).join("");O&&f(a(`${e.id}-think-${b}`,"think-line",O,{}),T&&!v),l(),r.push({key:`${e.id}-think-footer-${b}`,type:"think-footer-padding",text:""}),w=!1,v&&v.trim()&&f(a(`${e.id}-${b}`,"agent-line",v,{}),T)}else f(a(`${e.id}-think-${b}`,"think-line",E,{}),T);return}if(!m&&(E.includes("<think>")||E.includes("<|channel>thought")||E.includes("<thought>")||E.startsWith("<think")||E.startsWith("<|channel>thought"))){l(),g&&(r.push(a(`${e.id}-table-${b}`,"table",y.join(`
|
|
336
|
-
`),{isStreaming:!1})),g=!1,y=[]),r.push(a(`${e.id}-think-header-${b}`,"think-header","")),w=!0;let k=E.replace(/^(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought\s*)\r?\n?/i,"");if(k.includes("</think>")||k.includes("<channel|>")||k.includes("</thought>")){let O=k.split(/(?:<\/(think|thought|thoughts)>|<channel\|>)/i),v=O[0]||"",L=O.slice(2).join("");v&&f(a(`${e.id}-think-${b}`,"think-line",v,{}),T&&!L),l(),r.push({key:`${e.id}-think-footer-${b}`,type:"think-footer-padding",text:""}),w=!1,L&&L.trim()&&f(a(`${e.id}-${b}`,"agent-line",L,{}),T)}else k&&f(a(`${e.id}-think-${b}`,"think-line",k,{}),T);return}m?C?(m=!1,f(a(`${e.id}-code-close-${R}`,"code-fence-close","",{}),T)):(S++,f(a(`${e.id}-code-line-${b}`,"code-line",E,{lineNum:S,lang:x}),T)):C?(m=!0,R=b,S=0,x=E.trim().replace(/^```/,"").trim(),f(a(`${e.id}-code-open-${b}`,"code-fence-open",x,{}),T)):$?(g=!0,y.push(E),T&&(l(),e.isStreaming?h=a(`${e.id}-table-${b}`,"table",y.join(`
|
|
337
|
-
`),{isStreaming:!0}):r.push(a(`${e.id}-table-${b}`,"table",y.join(`
|
|
338
|
-
`),{isStreaming:!1})))):(g&&(l(),r.push(a(`${e.id}-table-${b}`,"table",y.join(`
|
|
339
|
-
`),{isStreaming:!1})),g=!1,y=[]),f(a(`${e.id}-${b}`,"agent-line",E,{}),T))}),!e.isStreaming&&e.workedDuration&&(l(),r.push(a(`${e.id}-worked-duration`,"worked-duration","")))}e.isStreaming&&d.length>0?h=d.length===1?d[0]:{key:`${e.id||"x"}-chunk-active-${d[0].key}`,type:"chunk",blocks:d}:l();let u={completed:r,active:h?[h]:[]};if(e.isStreaming){let p=new Map;if(r.forEach(g=>pi(g,p)),h&&pi(h,p),ds.set(s,{text:o,blocksMap:p}),ds.size>Fr){let g=ds.keys().next().value;ds.delete(g)}}else{if(Gn.set(t,u),Gn.size>Fr){let p=Gn.keys().next().value;Gn.delete(p)}ds.delete(s)}return u},ul={},hl=/<\/think>(\r?\n){2}/gi,pl=/(\r?\n){2}(?=\[?(?:tool:functions|tool\.functions|agent:generalist|agent\.generalist|\s*turn\s*:))/gi,hi=(e,n)=>{let t=!1;for(let o=0;o<n;o++)e[o]==="`"&&(t=!t);return t},ml=/\[SYSTEM\][\s\S]*?\[\/SYSTEM\]|(?:<(think|thought|thoughts)>|<\|channel>thought)[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>)|\[ANSWER\][\s\S]*?(?:\[\/ANSWER\]|$)|\[TOOL RESULT\]:?\s*|^\s*(SUCCESS|ERROR):.*(\r?\n)?|\[\s*turn\s*:\s*(continue|finish)\s*\]|\[\[END\]\]|\[\s*turn\s*:?.*?$|\n\s*turn\s*:?.*?$|\[\s*(?:turn|ANSWER|TOOL).*?$|\n\nResponded on .*|\n\n\[Prompted on: .*\]|@\[TerminalName:.*?, ProcessId:.*?\]/gm,gl=/(\$?\\?\/?\\rightarrow\$?|\$\\rightarrow\$)|(\$?\\?\/?\\leftarrow\$?|\$\\leftarrow\$)|(\$?\\?\/?\\uparrow\$?|\$\\uparrow\$)|(\$?\\?\/?\\downarrow\$?|\$\\downarrow\$)|(\$?\\?\/?\\leftrightarrow\$?|\$\\leftrightarrow\$)/gi,yl=/\b(write_file|update_file|read_folder|view_file|exec_command|web_search|web_scrape|search_keyword|write_pdf|write_docx|generate_image)\b/gi,Is=!1,wl=(e,n=!1)=>{if(!e)return e;let t=e.replace(/<\|channel>thought/gi,"<think>").replace(/<channel\|>/gi,"</think>");if(n)return t.replace(/^<(think|thought|thoughts)>/gi,"").replace(/<\/(think|thought|thoughts)>$/gi,"").replace(/^\r?\n+/,"").replace(/\r?\n+$/,"");let o=t.replace(hl,"</think>").replace(pl,(a,r,h,d)=>!Is&&hi(d,h)?a:"");o&&o.includes("[tool:")&&(o=o.replace(/<(\w+)(?:[^>]*)>\s*([\s\S]*?\[tool:[^\]]*\][\s\S]*?)\s*<\/\1>/gi,(a,r,h)=>h&&h.includes("[tool:")?h.trim():a),Is&&(o=o.replace(/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi,(a,r)=>r.includes("[tool:")?r.trim():a)),o=o.replace(/<(\w+)(?:[^>]*)>\r?\n?/gi,"").replace(/\r?\n?<\/\w+(?:[^>]*)>/gi,""));let s="tool:functions.",i="agent:generalist.";if(o.toLowerCase().includes(s)||o.toLowerCase().includes(i))for(;;){let a=o.toLowerCase(),r=a.indexOf(s),h=a.indexOf(i),d=s,c=r;if((r===-1||h!==-1&&h<r)&&(d=i,c=h),c===-1)break;if(!Is&&hi(o,c)){let w=c+d.length,x=a.indexOf(s,w),S=a.indexOf(i,w);if(x===-1&&S===-1)break;let R=-1,E=0;for(;;){let b=a.indexOf(s,E),T=a.indexOf(i,E),$=-1,C=s;if(b===-1&&T===-1)break;if(b===-1||T!==-1&&T<b?($=T,C=i):$=b,!hi(o,$)){R=$,d=C;break}E=$+C.length}if(R===-1)break;c=R}let l=c,f=!1,u=c-1;for(;u>=0&&/\s/.test(o[u]);)u--;u>=0&&o[u]==="["&&(l=u,f=!0);let p=0,g=!1,y=null,m=c;for(;m<o.length;){let w=o[m];if(!y&&(w==="'"||w==='"'||w==="`")?y=w:y&&w===y&&o[m-1]!=="\\"&&(y=null),y||(w==="("?(p++,g=!0):w===")"&&p--),g&&p===0&&!y){let x=m;if(f){let S=m+1;for(;S<o.length&&/\s/.test(o[S]);)S++;S<o.length&&o[S]==="]"&&(x=S)}o=o.substring(0,l)+o.substring(x+1);break}if(m++,m===o.length)return o=o.substring(0,l),o}}return o=o.replace(ml,""),o=o.replace(gl,a=>{let r=a.toLowerCase();return r.includes("leftrightarrow")?"\u2194":r.includes("rightarrow")?"\u2192":r.includes("leftarrow")?"\u2190":r.includes("uparrow")?"\u2191":r.includes("downarrow")?"\u2193":a}),o=o.replace(yl,a=>ul[a.toLowerCase()]||a),o.trim()},pf=()=>{Gn.clear(),ds.clear()};var gi=async(e,n={})=>{let t=I(e),o=t.path;if(!o)return'ERROR: Missing "path" argument for PatchFile.';let{patchPairs:s,allowMultiple:i,error:a}=Co(t);if(a)return`ERROR: ${a}`;if(s.length===0)return"ERROR: No valid replacement pairs found. Use searchContent1, newContent1, etc.";let r=t.allowMultiple!==void 0?t.allowMultiple===!0||String(t.allowMultiple).toLowerCase()==="true":i,h=xl.resolve(process.cwd(),o);try{if(!mi.existsSync(h))return`ERROR: File [${o}] does not exist. Use WriteFile instead.`;let d=n.forcedContent||mi.readFileSync(h,"utf8");d.startsWith("\uFEFF")&&(d=d.slice(1));let c=d.replace(/\r\n/g,`
|
|
340
|
-
`).replace(/\r/g,`
|
|
341
|
-
`),{content:l,results:f}=_o(c,s,{allowMultiple:r}),u=f.filter(m=>!m.success),p=f.filter(m=>m.success);if(p.length===0)return`ERROR: Patch Failed to apply to [${o}].
|
|
342
|
-
${u.map(m=>` \u2022 ${m.error}`).join(`
|
|
343
|
-
`)}`;await ft.recordFileChange(h,c),mi.writeFileSync(h,l,"utf8");let{systemSettings:g}=await Ft(),y=Mo(c,l,f,12,g?.compressToolResults);return u.length>0?`SUCCESS: File [${o}] updated with some blocks failed. [${p.length}/${s.length}] blocks applied.
|
|
344
|
-
|
|
345
|
-
Failures:
|
|
346
|
-
${u.map(m=>` \u2022 ${m.error}`).join(`
|
|
347
|
-
`)}
|
|
348
|
-
|
|
349
|
-
${y}`:`SUCCESS: File [${o}] updated. [${f.length}/${s.length}] blocks applied.
|
|
350
|
-
|
|
351
|
-
${y}`}catch(d){let c=d instanceof Error?d.message:String(d);return`ERROR: Failed to update file [${o}]: ${c}`}};import fs from"fs";import yi from"path";var bl=new Set([".git","node_modules",".gemini","dist","build",".next","out",".cache","bin","obj","vendor","venv",".idea",".gradle",".terraform","target","coverage",".vscode",".svn",".hg",".fslckout",".github",".gitlab",".circleci",".gitea",".gitee",".lerna",".changeset",".nx",".npm",".yarn",".pnpm-store",".expo",".nuxt",".svelte-kit",".docusaurus",".turbo",".vercel","bower_components",".netlify",".vuepress",".quasar",".output",".angular","jspm_packages",".parcel-cache",".rollup.cache",".rspack",".vitepress","__pycache__",".pytest_cache",".mypy_cache",".tox",".poetry","env","vhdl",".ipynb_checkpoints",".jupyter",".conda",".pdm-build",".bundle",".yardoc",".metadata","App_Data","ClientBin",".cargo",".rustc_info",".go","Godeps","_vendor",".rake_tasks","CMakefiles",".wakatime",".dart_tool",".fvm",".cocoapods","Pods",".pub-cache",".symlinks","DerivedData",".xcworkspace",".serverless",".aws",".gcloud",".azure",".kube",".vagrant",".docker","postgres-data","redis-data","mongo-data",".Spotlight-V100",".Trashes","$RECYCLE.BIN","System Volume Information",".DocumentRevisions-V100",".fseventsd","AppData","Application Data","Local","LocalLow","Roaming","$WinREAgent","$WINDOWS.~BT","$WINDOWS.~WS","scw","System32","SysWOW64",".AppleDouble",".AppleDB",".AppleDesktop","_CodeSignature",".cmio",".LSOverride",".localized",".TemporaryItems",".Trash",".Trash-0",".Trash-1000",".gvfs",".local",".config",".dbus",".fontconfig",".snap",".var",".lost+found","lost+found",".thumb",".thumbnails","EFI","boot","grub","logs","log",".nyc_output",".sonar",".ruff_cache",".VSCodeCounter"]),Sl=e=>bl.has(e)||e.startsWith(".pnpm"),kl=e=>{try{let n=String(e.getMonth()+1).padStart(2,"0"),t=String(e.getDate()).padStart(2,"0"),o=String(e.getHours()).padStart(2,"0"),s=String(e.getMinutes()).padStart(2,"0");return`${n}-${t} ${o}:${s}`}catch{return"N/A"}},wi=async e=>{let n=I(e),t=n.path||null;if(!t)return"ERROR: No directory path provided.";let o=1;if(n.recurse!==void 0&&n.recurse!==null)if(typeof n.recurse=="number")o=n.recurse;else if(typeof n.recurse=="boolean")o=n.recurse?2:1;else{let i=parseInt(String(n.recurse).trim(),10);o=isNaN(i)?1:i}o=Math.max(1,Math.min(3,o));let s=yi.resolve(process.cwd(),t);try{if(!fs.existsSync(s))return`ERROR: Path [${t}] does not exist.`;if(!fs.statSync(s).isDirectory())return`ERROR: Path [${t}] is a file, not a directory. Use ReadFile instead.`;if(o===1){let g=fs.readdirSync(s),y=g.length,m=150,w=g.slice(0,m),x=[];for(let E of w){let b=yi.join(s,E),T={name:E,type:"unknown",size:"N/A",mtime:"N/A"};try{let $=fs.statSync(b);T={name:E,type:$.isDirectory()?"directory":"file",size:($.size/1024).toFixed(1)+"KB",mtime:kl($.mtime)}}catch{T.type="inaccessible"}x.push(T)}let S=x.map(E=>E.type==="directory"?`${E.name}/`:`${E.name} (${E.size}, ${E.mtime})`).join(`
|
|
352
|
-
`),R=`
|
|
353
|
-
|
|
354
|
-
(Total items in folder: ${y})`;return y>m&&(R=`
|
|
355
|
-
|
|
356
|
-
TRUNCATED: Showing first ${m} of ${y} items.`),g.length=0,w.length=0,x.length=0,`Detailed folder stats for [${t}]:
|
|
357
|
-
|
|
358
|
-
${S}${R}`}let a=0,r=0,h=0,d=500,c=!1,l=(g,y,m=1)=>{if(y>o||c)return[];let w=[];try{w=fs.readdirSync(g)}catch{return[`${" ".repeat(m-1)}[Inaccessible Directory]`]}let x=[],S=[];for(let T of w){let $=yi.join(g,T),C=!1;try{C=fs.statSync($).isDirectory()}catch{}C?x.push({name:T,fullPath:$}):S.push({name:T,fullPath:$})}x.sort((T,$)=>T.name.localeCompare($.name)),S.sort((T,$)=>T.name.localeCompare($.name));let R=[],E=" ".repeat(m-1);for(let T of x){if(h>=d){c=!0,R.push(`${E}[Truncated - Maximum item limit reached (${d})]`);break}if(h++,a++,R.push(`${E}${T.name}/`),y<o&&!Sl(T.name)){let $=l(T.fullPath,y+1,m+1);R.push(...$)}}let b=[];for(let T of S){if(h>=d){c=!0,R.push(`${E}[Truncated - Maximum item limit reached (${d})]`);break}h++,r++;let $="N/A";try{$=(fs.statSync(T.fullPath).size/1024).toFixed(1)+"KB"}catch{}b.push(`${T.name} (${$})`)}return b.length>0&&R.push(`${E}${b.join("; ")}`),R},u=l(s,1,1).join(`
|
|
359
|
-
`),p=`
|
|
360
|
-
|
|
361
|
-
(Total items scanned: ${h}, Directories: ${a}, Files: ${r})`;return c&&(p=`
|
|
362
|
-
|
|
363
|
-
TRUNCATED: Scan capped at ${d} items. (Directories: ${a}, Files: ${r})`),`Detailed directory tree for [${t}] (recursive depth: ${o}):
|
|
364
|
-
|
|
365
|
-
${u}${p}`}catch(i){let a=i instanceof Error?i.message:String(i);return`ERROR: Failed to read folder [${t}]: ${a}`}};var xi=async(e,n)=>{let t=I(e),{question:o}=t;if(!o)return'ERROR: Missing "question" argument for ask.';if(!n.onAskUser)return"ERROR: onAskUser callback not provided in tool context.";let s=[];Object.keys(t).forEach(i=>{if(i.startsWith("option")){let a=t[i];if(typeof a=="string"&&a.includes("::")){let[r,h]=a.split("::");s.push({id:i,label:r.trim(),description:h.trim()})}else s.push({id:i,label:String(a).trim(),description:""})}});try{return`USER CHOOSE: ${await n.onAskUser(o,s)}`}catch(i){return`ERROR: Failed to get user input: ${i instanceof Error?i.message:String(i)}`}};import Tl from"puppeteer";import Os from"path";import us from"fs-extra";import{PDFDocument as Rl}from"pdf-lib";var bi=async e=>{let{path:n,content:t,orientation:o="portrait",margin:s="0px"}=I(e);if(!n)return'ERROR: Missing "path" argument for write_pdf.';if(!t)return'ERROR: Missing "content" (HTML/CSS) for write_pdf.';let i=Os.resolve(process.cwd(),n),a=null;try{await us.ensureDir(Os.dirname(i)),await ft.recordFileChange(i);let r=cs();a=await Tl.launch({headless:!0,executablePath:r.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let h=await a.newPage(),d=t,c={},l=async b=>{if(!b||b.startsWith("http://")||b.startsWith("https://")||b.startsWith("data:"))return null;try{let T=Os.resolve(process.cwd(),b);if(await us.pathExists(T)){let $=Os.extname(T).toLowerCase().replace(".","")||"png",C=$==="jpg"?"jpeg":$==="svg"?"svg+xml":$,k=await us.readFile(T,"base64");return`data:image/${C};base64,${k}`}}catch{}return null},f=/<link[^>]+href=["']([^"']+)["']/gi,u={},p;for(;(p=f.exec(t))!==null;){let b=p[1],T=p[0];if(b&&T.toLowerCase().includes("stylesheet")&&!b.startsWith("http://")&&!b.startsWith("https://")&&!b.startsWith("data:"))try{let $=Os.resolve(process.cwd(),b);if(await us.pathExists($)){let C=await us.readFile($,"utf-8");u[T]=`<style>${C}</style>`}}catch{}}for(let[b,T]of Object.entries(u))d=d.split(b).join(T);let g=/<img[^>]+src=["']([^"']+)["']/gi;for(;(p=g.exec(d))!==null;){let b=p[1];if(b&&!c[b]){let T=await l(b);T&&(c[b]=T)}}let y=/url\(\s*['"]?([^'")]+?)['"]?\s*\)/gi;for(;(p=y.exec(d))!==null;){let b=p[1].trim();if(b&&!c[b]){let T=await l(b);T&&(c[b]=T)}}for(let[b,T]of Object.entries(c)){let $=b.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&"),C=new RegExp(`(src=["'])(${$})(["'])`,"gi");d=d.replace(C,`$1${T}$3`);let k=new RegExp(`url\\(\\s*(['"]?)(${$})\\1\\s*\\)`,"gi");d=d.replace(k,`url($1${T}$1)`)}let m=`
|
|
366
|
-
<style>
|
|
367
|
-
@page {
|
|
368
|
-
margin: ${s};
|
|
369
|
-
}
|
|
370
|
-
body {
|
|
371
|
-
margin: 0;
|
|
372
|
-
padding: 0;
|
|
373
|
-
font-family: system-ui, -apple-system, sans-serif;
|
|
374
|
-
}
|
|
375
|
-
* { box-sizing: border-box; }
|
|
376
|
-
.watermark {
|
|
377
|
-
position: fixed;
|
|
378
|
-
top: 50%;
|
|
379
|
-
left: 50%;
|
|
380
|
-
transform: translate(-50%, -50%) rotate(-50deg);
|
|
381
|
-
font-size: 52px;
|
|
382
|
-
font-weight: bold;
|
|
383
|
-
color: rgba(0, 0, 0, 0.005);
|
|
384
|
-
pointer-events: none;
|
|
385
|
-
z-index: -1000;
|
|
386
|
-
text-align: center;
|
|
387
|
-
width: 150%;
|
|
388
|
-
white-space: nowrap;
|
|
389
|
-
text-transform: uppercase;
|
|
390
|
-
letter-spacing: 5px;
|
|
391
|
-
}
|
|
392
|
-
</style>
|
|
393
|
-
<div class="watermark">Generated by FluxFlow CLI (AI)</div>
|
|
394
|
-
${d}
|
|
395
|
-
`;await h.setContent(m,{waitUntil:"networkidle0",timeout:18e4});let w=await h.pdf({format:"A4",landscape:String(o).toLowerCase()==="landscape",margin:{top:s,right:s,bottom:s,left:s},printBackground:!0}),x=await Rl.load(w),S=Os.basename(n);x.setTitle(`FluxFlow_${S}`),x.setAuthor("FluxFlow CLI"),x.setSubject("Generated with Agentic AI System"),x.setKeywords(["FluxFlow","AI","Agentic","Automated"]),x.setCreator("FluxFlow PDF Engine"),x.setProducer("FluxFlow (Generative AI)");let R=await x.save();await us.writeFile(i,R);let E=await us.stat(i);return`SUCCESS: PDF generated successfully at [${n}] (${(E.size/1024).toFixed(2)} KB).`}catch(r){let h=r instanceof Error?r.message:String(r);return`ERROR: Failed to generate PDF [${n}]: ${h}`}finally{a&&await a.close()}};import Nr from"fs-extra";import Si from"path";import El from"html-to-docx";var ki=async e=>{let{path:n,content:t}=I(e);if(!n)return'ERROR: Missing "path" argument for write_docx.';if(!t)return'ERROR: Missing "content" (HTML) for write_docx.';let o=Si.resolve(process.cwd(),n);try{await Nr.ensureDir(Si.dirname(o)),await ft.recordFileChange(o);let s=Si.basename(n),i=t.includes("<html")?t:`
|
|
396
|
-
<!DOCTYPE html>
|
|
397
|
-
<html lang="en">
|
|
398
|
-
<head>
|
|
399
|
-
<meta charset="UTF-8">
|
|
400
|
-
<title>FluxFlow Document</title>
|
|
401
|
-
</head>
|
|
402
|
-
<body>
|
|
403
|
-
${t}
|
|
404
|
-
</body>
|
|
405
|
-
</html>
|
|
406
|
-
`,a=await El(i,null,{title:`FluxFlow_${s}`,creator:"FluxFlow CLI",description:"Generated by Agentic AI System",table:{row:{cantSplit:!0}},footer:!0,pageNumber:!0});return await Nr.writeFile(o,a),`SUCCESS: Word document [${n}] generated successfully.
|
|
407
|
-
- Size: ${(a.length/1024).toFixed(1)} KB`}catch(s){let i=s instanceof Error?s.message:String(s);return`ERROR: Failed to generate DOCX [${n}]: ${i}`}};import Ri from"fs/promises";import hs from"path";import Ti from"fast-glob";import{Minimatch as Br}from"minimatch";async function Zs(e,n,t=e,o=1){if(o>12)return[];let s=[],i;try{i=await Ri.readdir(e,{withFileTypes:!0})}catch{return[]}for(let a of i){let r=hs.join(e,a.name),h=hs.relative(t,r),d=h.split(hs.sep).map(f=>f.toLowerCase()),c=a.name.toLowerCase();if(!n.some(f=>{let u=f.toLowerCase();return u.startsWith(".")&&c.endsWith(u)?!0:d.some(p=>p===u||p.startsWith(".pnpm"))}))if(a.isDirectory()){let f=await Zs(r,n,t,o+1);s=s.concat(f)}else a.isFile()&&s.push({fullPath:r,relativePath:h})}return s}function $l(e,n,t=1/0){if(e===n)return 0;if(e.length===0)return n.length;if(n.length===0)return e.length;if(Math.abs(e.length-n.length)>t)return t+1;let o=Array.from({length:n.length+1},(s,i)=>i);for(let s=1;s<=e.length;s++){let i=[s],a=s;for(let r=1;r<=n.length;r++){let h=e[s-1]===n[r-1]?0:1,d=Math.min(i[r-1]+1,o[r]+1,o[r-1]+h);i.push(d),d<a&&(a=d)}if(o=i,a>t)return t+1}return o[n.length]}function Cl(e,n){if(!e||!n)return!1;let t=e.toLowerCase(),o=n.toLowerCase();if(t.includes(o))return!0;let s=t.split(/[^a-z0-9]+/).filter(a=>a.length>0),i=o.split(/[^a-z0-9]+/).filter(a=>a.length>1||o.length===1&&a.length>0);return i.length===0?!1:i.every(a=>{let r=a.length<=2?0:a.length<=5?1:2;for(let h of s)if(h.includes(a)||a.length>=3&&h.length>=3&&Math.abs(h.length-a.length)<=r&&$l(a,h,r)<=r)return!0;return!1})}var eo=async e=>{let{keyword:n,path:t,fuzzy:o,subString:s,regex:i}=I(e);if(n==null)return'ERROR: Missing "keyword" argument.';let a=String(n),r=g=>g===!0||g==="true"||g===1||g==="1"||g==="yes",h=i===!1||i==="false"||i===0||i==="0"||i==="no",d=i===!0||i==="true"||i===1||i==="1"||i==="yes",c=r(o)||r(s),l=null,f=null;if(h)c||(f=new RegExp(`(?<![\\w])${a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\\w])`,"i"));else{try{l=new RegExp(a,"i")}catch(g){if(d)return`ERROR: Invalid regex pattern "${a}": ${g.message}`}f=new RegExp(`(?<![\\w])${a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\\w])`,"i")}let u=[".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",".exe",".dll",".so",".dylib",".png",".jpg",".jpeg",".gif",".ico",".svg",".webp",".mp3",".mp4",".avi",".zip",".tgz",".tar",".gz",".7z",".rar",".pdf",".docx",".xlsx",".pptx",".woff",".woff2",".ttf",".eot"],p=150;try{let g=[],y=process.cwd(),m=null;if(t){let v=t.split(";").map(j=>j.trim()).filter(Boolean),L=v.some(j=>j.startsWith("!"));if(v.some(j=>Ti.isDynamicPattern(j)||/[*?{}[\]()|+]/.test(j))){m="glob";let j=t.replace(/\\/g,"/"),V=v.map(B=>B.replace(/\\/g,"/")),oe=u.map(B=>B.startsWith(".")?`**/*${B}`:`**/${B}/**`);if(L&&!v.some(B=>!B.startsWith("!"))){let B=await Zs(y,u,y),W=M=>M.endsWith("/")?M+"**":M,re=V.filter(M=>M.startsWith("!")).map(M=>W(M.slice(1))),Re=V.filter(M=>!M.startsWith("!")).map(W);g=B.filter(M=>{let F=M.relativePath.replace(/\\/g,"/"),Y=Re.length===0||Re.some(Ne=>{try{return new Br(Ne).match(F)}catch{return!1}}),J=re.some(Ne=>{try{return new Br(Ne).match(F)}catch{return!1}});return Y&&!J})}else{let B=V.some(re=>/[\(\)\|]|\.\*/.test(re)),W=[];if(!B)try{W=await Ti(V,{cwd:y,ignore:oe,dot:!0,onlyFiles:!0,absolute:!1})}catch{W=[]}if(W.length===0&&(B||Ti.isDynamicPattern(j))){let re=j.match(/^([^\*\?\(\)\|\[\]\s]+)\//),Re=re&&!/[\*\?\(\)\|\[\]]/.test(re[1])?hs.resolve(y,re[1]):y,M=await Zs(Re,u,y);try{let F=j.replace(/^\.\//,"");F=F.replace(/\.\*\/(\\.|[^\/])/g,".*$1"),!F.startsWith("^")&&!F.startsWith(".*")&&(F=`.*${F}`);let Y=new RegExp(F.endsWith("$")?F:`${F}$`,"i");g=M.filter(J=>{let Ne=J.relativePath.replace(/\\/g,"/");return Y.test(Ne)})}catch{g=[]}}else g=W.map(re=>({fullPath:hs.resolve(y,re),relativePath:re}))}}else{let j=t.replace(/[\/\\]+$/,""),V=hs.resolve(y,j);try{let oe=await Ri.stat(V);if(oe.isDirectory())m="dir",g=await Zs(V,u,y);else if(oe.isFile())m="file",g.push({fullPath:V,relativePath:hs.relative(y,V)});else return`ERROR: Path is neither a file nor a directory: ${t}`}catch{return`ERROR: Path not found: ${t}`}}}else g=await Zs(y,u);let w=g.map(async v=>{try{let L=await Ri.readFile(v.fullPath,"utf-8");if(L.includes("\0"))return[];let N=L.split(/\r?\n/),j=[];for(let oe=0;oe<N.length;oe++)(c?N[oe].toLowerCase().includes(a.toLowerCase())||Cl(N[oe],a):h?f&&f.test(N[oe]):l&&l.test(N[oe])||f&&f.test(N[oe]))&&j.push({line:oe+1,content:N[oe].trim()});return j.length===0?null:{path:v.relativePath.replace(/\\/g,"/"),matches:j}}catch{return[]}}),x=await Promise.all(w),S=[],R=0;for(let v of x){if(!v||!v.matches)continue;if(R>=p)break;let L=p-R,N=v.matches.slice(0,L);S.push({path:v.path,matches:N}),R+=N.length}typeof global.gc=="function"&&global.gc();let E=c?"(fuzzy mode)":d?"(regex mode)":h?"(keyword mode)":"(standard mode)";if(S.length===0){let v=m==="file"?` in '${t}'`:m==="dir"||m==="glob"?` in '${t}'`:". Try to specify files",L=m==="dir"?"[DIR]":m==="glob"?"[GLOB]":"";return`${L}${L?" ":""}Found 0 matches of '${a}'${v}${E?` ${E}`:""}`}let b=E?` ${E}`:"",T=`${S.length} file${S.length===1?"":"s"}`,$=`${R} match${R===1?"":"es"}`,C;m==="file"?C=`Found ${$} of '${a}' in '${t}'${b}:`:m==="dir"||m==="glob"?C=`Found ${$} of '${a}' in '${t}' across ${T}${b}:`:C=`Found ${$} of '${a}' across ${T}${b}:`;let k=m==="dir"?"[DIR]":m==="glob"?"[GLOB]":"",O=`${k}${k?" ":""}${C}
|
|
408
|
-
|
|
409
|
-
`;for(let v of S){O+=`${v.path}
|
|
410
|
-
`;for(let L of v.matches)O+=` ${L.line}: ${L.content}
|
|
411
|
-
`;O+=`
|
|
412
|
-
`}return O.trimEnd()}catch(g){return`ERROR: ${g.message}`}};import Ur from"fs-extra";import Ei from"path";var _l=(e,n={})=>{try{if(e.length<8||e[0]!==137||e[1]!==80||e[2]!==78||e[3]!==71)return e;let t=[],o=[];for(let a=0;a<256;a++){let r=a;for(let h=0;h<8;h++)r&1?r=3988292384^r>>>1:r=r>>>1;o[a]=r}let s=a=>{let r=4294967295;for(let h=0;h<a.length;h++)r=o[(r^a[h])&255]^r>>>8;return(r^4294967295)>>>0},i=(a,r)=>{let h=Buffer.from(a,"ascii"),d=Buffer.from(r,"utf-8"),c=h.length+1+d.length,l=Buffer.alloc(8+c+4);l.writeUInt32BE(c,0),l.write("tEXt",4,"ascii"),h.copy(l,8),l[8+h.length]=0,d.copy(l,8+h.length+1);let f=s(l.subarray(4,8+c));return l.writeUInt32BE(f,8+c),l};for(let[a,r]of Object.entries(n))r!=null&&t.push(i(a,String(r)));if(t.length===0)return e;if(e.subarray(12,16).toString("ascii")==="IHDR"){let r=e.subarray(0,33),h=e.subarray(33);return Buffer.concat([r,...t,h])}return e}catch{return e}},$i=async(e,n={})=>{let t=I(e),o=t.prompt||t.text,s=t.path||t.outputPath||t.output||"generated_image.png",i=t.ratio;if(!o)return'ERROR: Missing "prompt" argument for generate_image.';let a=["nsfw","naked","nudity","nude","porn","sex","xxx","erotic","gore","bloody","violence","abuse","suicide","murder","hentai","pedophile","rape"],r=o.toLowerCase();if(a.some(d=>r.includes(d)))return"ERROR: Prompt blocked by system safety filter (inappropriate or unsafe content detected).";try{let d=await Ft();if(!await Er(d))return`ERROR: Insufficient Quota for selected quality. Either tell user reduce quality or wait for next refresh cycle (${(await $r()).nextResetMin||60}m).`;let l=d.imageSettings||{keyType:"Default",quality:"Low-High",apiKey:""},f=l.keyType==="Custom"&&l.apiKey?l.apiKey:FALLBACK_IMAGE_KEY,p={Low:"flux","Low-High":"zimage",Medium:"gptimage","Medium-High":"gptimage",High:"qwen-image",Ultra:"gptimage-large",Premium:"nanobanana-pro"}[l.quality]||"zimage",g=1024,y=1024;if(i){let L=i.replace(/\s+/g,"");L==="16:9"?(g=1024,y=576):L==="9:16"?(g=576,y=1024):L==="4:3"?(g=1024,y=768):L==="3:4"?(g=768,y=1024):L==="1:1"&&(g=1024,y=1024)}let m=Math.floor(Math.random()*1e7),x=`https://gen.pollinations.ai/image/${encodeURIComponent(o)}?model=${p}&width=${g}&height=${y}&seed=${m}&enhance=true&reasoning=high&quality=high&negative=${encodeURIComponent("deformed, distorted, disfigured, poorly drawn, bad anatomy, wrong anatomy, extra limb, missing limb, floating limbs, disconnected limbs, mutation, mutated hands and fingers, blurry, low quality, low resolution, extra fingers, censored, watermarks, signatures")}`,S=await fetch(x,{method:"GET",headers:{Authorization:`Bearer ${f}`}});if(!S.ok){let L=S.status,N="";try{N=await S.text()}catch{}return L===402||N.includes("Insufficient balance")||N.includes("PAYMENT_REQUIRED")?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed with status [${L}]: ${N||"Unknown API Error"}`}if((S.headers.get("content-type")||"").includes("application/json")){let L=await S.json();return L.status===402||L.error&&L.error.code==="PAYMENT_REQUIRED"?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed: ${L.error?.message||JSON.stringify(L)}`}let E=await S.arrayBuffer(),b=Buffer.from(E),T={Title:o,Description:"Generated via FluxFlow CLI",Software:"FluxFlow CLI",Author:"FluxFlow","Creation Time":new Date().toISOString(),Prompt:o,Model:`Fluxflow:${p}`,Ratio:i||"1:1",Seed:String(m)};b=_l(b,T);let $=Ei.resolve(process.cwd(),s);await Ur.ensureDir(Ei.dirname($)),await ft.recordFileChange($),await Ur.writeFile($,b),await Cr(d);let C=Ei.extname(s).toLowerCase(),O={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".webp":"image/webp"}[C]||"image/png";return n.isMultiModal!==!1?{text:`SUCCESS: Image successfully generated from prompt [${o}] and saved to [${s}]. Output attached to multimodal part`,binaryPart:{inlineData:{data:b.toString("base64"),mimeType:O}}}:`SUCCESS: Image successfully generated from prompt [${o}] and saved to [${s}].`}catch(d){return`ERROR: Failed during image generation: ${d instanceof Error?d.message:String(d)}`}};var to=async(e,n={})=>{let t=i=>{let a=new RegExp(`${i}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),r=e.match(a);return r?r[2].trim():null},o=t("id"),s=t("summary");if(!o||!s)return"ERROR: Missing 'id' or 'summary' for saveSummary tool.";try{let i=X(Xt,{}),a=X(vn,{});return a[o]=s,delete i[o],he(vn,a),he(Xt,i),`SUCCESS: Saved summary and purged raw memories for chat [${o}].`}catch(i){let a=i instanceof Error?i.message:String(i);return`ERROR: Failed to save summary for chat [${o}]: ${a}`}};var Ls=async(e,n={})=>{let o=(s=>{let i=new RegExp(`${s}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),a=e.match(i);return a?a[2].trim():null})("id");if(!o)return"ERROR: Missing 'id' parameter for addMemScore tool.";try{let s=X(Dt,[]),i=!1,a=[];for(let c of s)c.score===void 0&&(c.score=.5),c.id===o?(c.score=Math.min(2,c.score+.2),i=!0):(c.score*=.98,c.score<.05&&(c.score=0)),c.score=Math.round(c.score*1e5)/1e5,c.score>0&&a.push(c);if(he(Dt,a),!i)return`WARNING: Memory ID [${o}] not found. Other memories decayed by -0.01.`;let r=a.find(c=>c.id===o),h=r?r.score.toFixed(2):"deleted (score <= 0)",d=s.length-a.length;return`SUCCESS: Adjusted memory scores. Target [${o}] is now ${h}.${d>0?` Purged ${d} decayed memories.`:""}`}catch(s){let i=s instanceof Error?s.message:String(s);return`ERROR: Failed to adjust memory score for [${o}]: ${i}`}};import _i from"fs-extra";import ms from"path";import{createRequire as vl}from"module";import ps from"fs-extra";import Ci from"path";import Ml from"https";var Wr={js:"tree-sitter-javascript.wasm",jsx:"tree-sitter-javascript.wasm",ts:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm",py:"tree-sitter-python.wasm",c:"tree-sitter-c.wasm",cpp:"tree-sitter-cpp.wasm",java:"tree-sitter-java.wasm",html:"tree-sitter-html.wasm"};async function Al(e,n=null){let t=n||`https://unpkg.com/tree-sitter-wasms@0.1.13/out/${e}`,o=Ci.join(as,e);return await ps.ensureDir(as),new Promise((s,i)=>{let a={headers:{"User-Agent":"FluxFlow-Agent"}};Ml.get(t,a,r=>{if([301,302,307,308].includes(r.statusCode)&&r.headers.location){let d=r.headers.location;if(!d.startsWith("http")){let c=new URL(t);d=`${c.protocol}//${c.host}${d}`}Al(e,d).then(s).catch(i);return}if(r.statusCode!==200){i(new Error(`Failed to download ${e}: HTTP ${r.statusCode}`));return}let h=ps.createWriteStream(o);r.pipe(h),h.on("finish",()=>{h.close(),s()})}).on("error",r=>{ps.existsSync(o)&&ps.unlink(o,()=>{}),i(r)})})}function uu(e){let n=Ci.join(as,e);return ps.existsSync(n)}async function hu(e){let n=Ci.join(as,e);ps.existsSync(n)&&await ps.unlink(n)}var Gr=vl(import.meta.url),jr=Gr("web-tree-sitter"),Hr=!1,qr=new Set(["class_declaration","function_declaration","method_definition","arrow_function","function_expression","if_statement","else_clause","for_statement","for_in_statement","for_of_statement","while_statement","do_statement","switch_statement","try_statement","catch_clause","variable_declarator","export_statement","lexical_declaration","variable_declaration","interface_declaration","type_alias_declaration","enum_declaration","import_declaration","jsx_element","jsx_self_closing_element","class_definition","function_definition","decorated_definition","import_from_statement","import_statement","preproc_include","method_declaration","constructor_declaration","assignment_expression","pair","class_specifier","struct_specifier","enum_specifier","field_declaration","element","script_element","style_element"]),Kr=new Set(["export_statement","lexical_declaration","variable_declaration","variable_declarator","pair","assignment_expression"]);function pn(e,n=50){if(!e)return"";let t=e.replace(/\s+/g," ").trim();return t.length>n?t.substring(0,n-3)+"...":t}function zr(e){let n=e.type;if(n==="if_statement"){let o=e.childForFieldName("condition");return o?`if (${pn(o.text,40)})`:"if"}if(n==="else_clause")return"else";if(n==="while_statement"||n==="do_statement"){let o=e.childForFieldName("condition");return`${n.split("_")[0]} (${o?pn(o.text,40):""})`}if(n==="for_statement"||n==="for_in_statement"||n==="for_of_statement"){let s=e.text.split(`
|
|
413
|
-
`)[0].match(/for\s*(?:await\s*)?\((.*)\)/);return s?`for (${pn(s[1],40)})`:"for"}if(n==="switch_statement"){let o=e.childForFieldName("value");return`switch (${o?pn(o.text,40):""})`}if(n==="try_statement")return"try";if(n==="catch_clause")return"catch";if(n==="element"||n==="script_element"||n==="style_element"||n==="jsx_element"||n==="jsx_self_closing_element"){let o=e.childForFieldName("opening_element")||e.childForFieldName("start_tag")||e.children.find(i=>i.type==="start_tag")||e,s=o.childForFieldName("name")||o.childForFieldName("tag_name")||o.children.find(i=>i.type==="tag_name");return s?`<${pn(s.text,30)}>`:null}if(["import_declaration","import_from_statement","import_statement","preproc_include"].includes(n))return pn(e.text.split(`
|
|
414
|
-
`)[0],60);if(n==="pair"){let o=e.childForFieldName("key");return o?pn(o.text.replace(/["']/g,""),40):null}if(n==="assignment_expression"){let o=e.childForFieldName("left");return o?`${pn(o.text,30)} = ...`:null}if(n==="variable_declarator"){let o=e.childForFieldName("name")||e.children.find(s=>["identifier","object_pattern","array_pattern"].includes(s.type));return o?pn(o.text,40):null}let t=e.childForFieldName("name")||e.childForFieldName("declarator")||e.children.find(o=>["identifier","type_identifier","field_identifier","property_identifier","shorthand_property_identifier"].includes(o.type));if(t){if(t.type.includes("declarator")){let o=t.descendantsOfType("identifier")[0]||t.descendantsOfType("field_identifier")[0];if(o)return pn(o.text,40)}return pn(t.text,40)}if(["arrow_function","function_expression","function_declaration"].includes(n)){let o=e.parent;for(;o&&o.type!=="program";){let s=zr(o);if(s)return s;if(!Kr.has(o.type))break;o=o.parent}}return null}function Il(e){let n=[];function t(o){for(let s of o.children)qr.has(s.type)?n.push(s):t(s)}return t(e),n}function Ol(e){return e.replace(/_([a-z])/g,n=>n[1].toUpperCase())}function Yr(e,n=0,t=!0,o="",s=null,i=12){let a=e.type,r=zr(e),h=qr.has(a)||n===0,d=Il(e),c=h&&n>0&&(Kr.has(a)&&d.length>0||r!==null&&r===s&&d.length>0),l="",f=o,u=n,p=s;if(h&&!c){let g=e.startPosition.row+1,y=e.endPosition.row+1,m=Ol(a),w=r?`${m} [${r}]`:m;n===0?(l+=`\u{1F4C1} ROOT (Lines: ${g}-${y})
|
|
415
|
-
`,f=o):(l+=`${o}${t?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 "}${w} (Lines: ${g}-${y})
|
|
416
|
-
`,f+=t?" ":"\u2502 "),u=n+1,p=r}return u>i&&d.length>0?l+=`${f}\u2514\u2500\u2500 ... depth exceeded ...
|
|
417
|
-
`:d.forEach((g,y)=>{let m=y===d.length-1;l+=Yr(g,u,c?t&&m:m,f,p,i)}),l}var Mi=async e=>{let n;try{n=I(e).path}catch{return`ERROR: Failed to parse arguments: ${e}`}if(!n)return'ERROR: No file path provided. Use [tool:functions.FileMap(path="...")]';let t=ms.isAbsolute(n)?n:ms.resolve(process.cwd(),n);if(!_i.existsSync(t))return`ERROR: File not found: ${n}`;let o=ms.extname(t).slice(1).toLowerCase(),s=Wr[o];if(!s)return`ERROR: Unsupported file extension: .${o}`;let i=ms.resolve(as,s);if(!_i.existsSync(i))return`ERROR: Parser for .${o} not found. Please download it in Settings > Other.`;try{let a=jr.Parser;if(!Hr){let p;try{p=ms.join(ms.dirname(Gr.resolve("web-tree-sitter")),"tree-sitter.wasm")}catch{p=ms.join(process.cwd(),"node_modules","web-tree-sitter","tree-sitter.wasm")}await a.init({locateFile:g=>g==="tree-sitter.wasm"||g.endsWith("tree-sitter.wasm")?p:g}),Hr=!0}let r=new a,h=await jr.Language.load(i);r.setLanguage(h);let d=await _i.readFile(t,"utf8"),c=d.split(`
|
|
418
|
-
`).length,l=12;c>1e4?l=2:c>=8e3?l=3:c>=5e3?l=5:c>=4e3?l=8:c>2e3&&(l=10);let f=r.parse(d),u=Yr(f.rootNode,0,!0," ",null,l);return`\u{1F4C4} File Map for: ${n}
|
|
419
|
-
${u}`}catch(a){let r=a instanceof Error?a.message:typeof a=="object"?JSON.stringify(a):String(a),h=a instanceof Error?`
|
|
420
|
-
Stack: ${a.stack}`:"";return`ERROR: Failed to map file: ${r}${h}`}};import qn from"fs";import Vr from"path";var Jr=async(e,n={})=>{let{method:t,tasks:o,markDone:s}=I(e),i=n.chatId||"default";if(!t)return'ERROR: Missing "method" argument for todo tool (create/append/get).';let a=Vr.join(An,"plan",i),r=Vr.join(a,"todo.md"),h=l=>{if(!l||Array.isArray(l))return l;let f=String(l).trim();if(f.startsWith("[")&&f.endsWith("]")){let u=f.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);return u?u.map(p=>p.slice(1,-1).replace(/\\(.)/g,"$1")):f.slice(1,-1).split(",").map(p=>p.trim()).filter(Boolean)}return l},d=l=>{let f=h(l);return f?(Array.isArray(f)?f:String(f).split(`
|
|
421
|
-
`)).map(p=>{let g=String(p).trim();return g?g.startsWith("- [ ]")||g.startsWith("- [x]")||g.startsWith("- [X]")?g:`- [ ] ${g}`:null}).filter(Boolean).join(`
|
|
422
|
-
`)+`
|
|
423
|
-
`:""},c=(l,f)=>{if(!f)return{content:l,markedCount:0};let u=h(f),p=(Array.isArray(u)?u:[u]).map(w=>String(w).replace(/^- \[[xX ]\]\s*/i,"").trim()).filter(Boolean),g=l.split(`
|
|
424
|
-
`),y=0,m=!1;for(let w of p){let x=!1;for(let S=0;S<g.length;S++)if(g[S].includes(w)&&/^- \[\s\]/.test(g[S].trim())){g[S]=g[S].replace("- [ ]","- [x]"),x=!0,m=!0,y++;break}if(!x){for(let S=0;S<g.length;S++)if(g[S].toLowerCase().includes(w.toLowerCase())&&/^- \[\s\]/.test(g[S].trim())){g[S]=g[S].replace("- [ ]","- [x]"),x=!0,m=!0,y++;break}}}return{content:m?g.join(`
|
|
425
|
-
`):l,markedCount:y}};try{if(qn.existsSync(a)||qn.mkdirSync(a,{recursive:!0}),t==="create"){if(!o)return'ERROR: Missing "tasks" for create method.';let l=d(o),f=0;if(s){let p=c(l,s);l=p.content,f=p.markedCount}await ft.recordFileChange(r),qn.writeFileSync(r,l,"utf8");let u=l.split(/\r?\n/).map(p=>p.trim()).filter(p=>p.startsWith("- [ ]")||p.startsWith("- [x]")||p.startsWith("- [X]")).length;if(f>0){let p=l.split(/\r?\n/).map(g=>g.trim()).filter(g=>g.startsWith("- [x]")||g.startsWith("- [X]")).length;return`SUCCESS: TASK LIST CREATED (${f} marked done, ${p} completed, ${u-p} left)
|
|
426
|
-
${l}`}return`SUCCESS: TASK LIST CREATED (${u} total)
|
|
427
|
-
${l}`}if(t==="append"){if(!o)return'ERROR: Missing "tasks" for append method.';let l=d(o);await ft.recordFileChange(r),qn.appendFileSync(r,l,"utf8");let f=qn.readFileSync(r,"utf8"),u=f.split(/\r?\n/).map(m=>m.trim()),p=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, ${p-g} left, ${y} added)
|
|
428
|
-
${f}`}if(t==="get"){if(!qn.existsSync(r))return"TODO GET: No task list found for this session.";let l=qn.readFileSync(r,"utf8"),f=0;if(s){let m=c(l,s);m.markedCount>0&&(l=m.content,f=m.markedCount,await ft.recordFileChange(r),qn.writeFileSync(r,l,"utf8"))}let u=l.split(/\r?\n/).map(m=>m.trim()),p=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, ${p-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 Ai=async(e,n={})=>{let{runSubagent:t}=await import("./ai-LFC7GPK6.js"),o=I(e),s=o.task||o.instruction||o.prompt,i=o.model||null,a=o.tools||null;if(!s)return'ERROR: Missing "task" argument for invokeSync.';let r=null;if(a)try{let d=a.trim();d.startsWith("[")&&d.endsWith("]")&&(d=d.substring(1,d.length-1)),r=d.split(",").map(c=>c.trim().replace(/^["']|["']$/g,"")).filter(Boolean)}catch{}let h=o.title||s.substring(0,30);try{n.onVisualFeedback&&n.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${h}`);let d=await t(s,n,i,r,50);return n.onVisualFeedback&&n.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${h} [COMPLETED]
|
|
430
|
-
`),d}catch(d){let{isTerminationSignaled:c}=await import("./ai-LFC7GPK6.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 ${h} ${f}
|
|
431
|
-
`)}return`ERROR: Subagent execution failed: ${d.message}`}};var Xr=async(e,n={})=>{let{runSubagent:t}=await import("./ai-LFC7GPK6.js"),o=I(e),s=o.task||o.instruction||o.prompt,i=o.model||null,a=o.title||null,r=o.tools||null;if(!s)return'ERROR: Missing "task" argument for invoke.';let h=null;if(r)try{let m=r.trim();m.startsWith("[")&&m.endsWith("]")&&(m=m.substring(1,m.length-1)),h=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:[]},p={chunks:[],totalWords:0};Ye.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)}`,x=null,S=new Promise(b=>{x=b}),R={id:w,question:m,answered:!1,answer:null,askedAt:Date.now(),_resolve:x};return u.questions.push(R),u.status="waiting",n.onSubagentUpdate&&n.onSubagentUpdate(),yo(`[SYSTEM] Background subagent "${u.title}" is WAITING FOR YOUR INPUT: "${m}"
|
|
432
|
-
Respond using tool: [tool:functions.Answer(id="${d}", answer="...")]
|
|
433
|
-
[/SYSTEM]`),await S},onVisualFeedback:m=>{u.lastChunkTime=Date.now();let w=m.replace(/\x1b\[[0-9;]*m/g,""),x=w.match(/[✔✘✗✖🔍📖→➕↻•]\s*([A-Za-z0-9\s-]+)/);x?u.currentTool=x[1].trim():u.currentTool=w,n.onSubagentUpdate&&n.onSubagentUpdate()},onTokenChunk:(m,w)=>{let x=Date.now();if(u.lastChunkTime=x,u.currentTool="Thinking",typeof w=="number"&&w>0){p.totalWords+=w,p.chunks.push({time:x,words:w});let S=x-400;if(p.chunks=p.chunks.filter(R=>R.time>=S),p.chunks.length>0){let R=p.chunks.reduce((T,$)=>T+$.words,0),E=p.chunks[0].time,b=Math.max(.4,(x-E)/1e3);u.wps=Math.round(R/b*10)/10}}n.onSubagentUpdate&&n.onSubagentUpdate()}};return t(s,y,i,h,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 x=m.match(/\[Executing Tool\]\s*([a-zA-Z0-9_]+)/);x&&(!u.currentTool||u.currentTool==="Thinking")&&(u.currentTool=x[1])}let w=m;if(w.startsWith("[Tool Result]")){let x=w.split(`
|
|
434
|
-
`);x.length>5&&(w=x.slice(0,4).join(`
|
|
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(),yo(`[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-LFC7GPK6.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(),yo(`[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 vi=async(e,n={})=>{let o=I(e).id;if(!o)return'ERROR: Missing "id" argument for getProgress.';let s=Ye.find(r=>r.id===o);if(!s)return`ERROR: Subagent task with ID [${o}] not found.`;let i=`Subagent Task Status: ${s.status.toUpperCase()}
|
|
437
|
-
`;if(i+=`Title: ${s.title}
|
|
438
|
-
`,i+=`Task: ${s.task}
|
|
439
|
-
`,s.startedAt){let r=Math.floor((Date.now()-s.startedAt)/1e3);i+=`Elapsed Time: ${r}s
|
|
440
|
-
`}if(i+=`Turns Completed: ${s.progress.length}
|
|
441
|
-
`,(s.status==="running"||s.status==="waiting")&&(s.currentTool&&(i+=`Current Tool: ${s.currentTool}
|
|
442
|
-
`),s.wps>0&&(i+=`TPS: ${s.wps}
|
|
443
|
-
`)),s.questions&&s.questions.length>0){let r=s.questions.filter(h=>!h.answered);r.length>0&&(i+=`
|
|
444
|
-
**PENDING QUESTION**
|
|
445
|
-
`,r.forEach(h=>{i+=`"${h.question}"
|
|
446
|
-
`}),i+=`Respond using tool: [tool:functions.Answer(id="${s.id}", answer="...")]
|
|
447
|
-
|
|
448
|
-
`)}return i+=`
|
|
449
|
-
Progress Log:
|
|
450
|
-
`,s.progress.forEach((r,h)=>{i+=`--- Turn ${h+1} ---
|
|
451
|
-
`;let c=r.filter(l=>!l.startsWith("[SUBAGENT SUCCESS]")).map(l=>{if(l.startsWith("[Subagent Response]")){let f="[Subagent Response]",p=l.substring(f.length),g="tool:functions.";for(;;){let m=p.toLowerCase().indexOf(g);if(m===-1)break;let w=m,x=!1,S=m-1;for(;S>=0&&/\s/.test(p[S]);)S--;S>=0&&p[S]==="["&&(w=S,x=!0);let R=0,E=!1,b=null,T=m;for(;T<p.length;){let $=p[T];if(!b&&($==="'"||$==='"'||$==="`")?b=$:b&&$===b&&p[T-1]!=="\\"&&(b=null),b||($==="("?(R++,E=!0):$===")"&&R--),E&&R===0&&!b){let C=T;if(x){let k=T+1;for(;k<p.length&&/\s/.test(p[k]);)k++;k<p.length&&p[k]==="]"&&(C=k)}p=p.substring(0,w)+p.substring(C+1);break}if(T++,T===p.length){p=p.substring(0,w);break}}}return f+`
|
|
452
|
-
`+p.trim()}return l.startsWith("[Executing Tool]")&&l.length>256?l.substring(0,256)+"...[truncated from logs]":l});i+=c.join(`
|
|
453
|
-
`)+`
|
|
454
|
-
|
|
455
|
-
`}),s.status==="completed"&&s.finalAnswer?i+=`Final Answer:
|
|
456
|
-
${s.finalAnswer}
|
|
457
|
-
`:s.status==="failed"&&s.error&&(i+=`Failure Error: ${s.error}
|
|
458
|
-
`),i.replace(/\r\n/g,`
|
|
459
|
-
`).replace(/\n{3,}/g,`
|
|
460
|
-
|
|
461
|
-
`).trim().replace(/\[TOOL RESULT\]/gi,"TOOL RESULT:")};var Qr=async(e,n={})=>{let o=I(e).id;if(!o)return'ERROR: Missing "id" argument for cancel.';let s=Ye.find(i=>i.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 wt from"fs-extra";import St from"path";var Ll=["node_modules","dist","bin","logs",".git",".fluxflow","secret",".gemini",".agents","tmp","temp","build","out","snapshots"];async function no(e,n=e){let t={},o=await wt.readdir(e,{withFileTypes:!0}).catch(()=>[]);for(let s of o){if(Ll.includes(s.name))continue;let i=St.join(e,s.name),a=St.relative(n,i).replace(/\\/g,"/");if(s.isDirectory()){let r=await no(i,n);Object.assign(t,r)}else{let r=await wt.stat(i).catch(()=>null);r&&(t[a]={size:r.size,mtime:r.mtimeMs})}}return t}async function Zr(e,n){await wt.ensureDir(e);for(let t of Object.keys(n)){let o=St.join(process.cwd(),t),s=St.join(e,t);await wt.ensureDir(St.dirname(s)),await wt.copyFile(o,s).catch(()=>{})}}async function Ii(e,n,t=null,o=null){if(!await wt.pathExists(e))return;o||(o=e);let s=await wt.readdir(e,{withFileTypes:!0}).catch(()=>[]);for(let i of s){let a=St.join(e,i.name),r=St.join(n,i.name);if(i.isDirectory())await Ii(a,r,t,o);else{let h=St.relative(o,a).replace(/\\/g,"/"),d=await wt.pathExists(r);d&&await wt.chmod(r,438).catch(()=>{}),await wt.ensureDir(St.dirname(r));let c=await wt.copyFile(a,r).then(()=>!0).catch(()=>!1);await wt.chmod(r,438).catch(()=>{}),t&&(c?d?t.replaced++:t.restored++:t.failed.push(h))}}}var Kn={async takeInitialSnapshot(e){try{let n=St.join(An,"snapshots",e);await wt.remove(n).catch(()=>{}),await wt.ensureDir(n);let t=await no(process.cwd());await Zr(St.join(n,"initial"),t);let o=X(dn,{});o[e]={initialManifest:t,currentManifest:t,checkpoints:[{id:"initial",timestamp:new Date().toISOString(),newFiles:[],modifiedFiles:[],deletedFiles:[],toolsUsed:[]}]},he(dn,o)}catch{}},async recordTurnDelta(e,n,t=[]){try{let o=X(dn,{}),s=o[e];if(!s)return;let i=s.currentManifest||s.initialManifest,a=await no(process.cwd()),r=[],h=[],d=[];for(let[l,f]of Object.entries(a)){let u=i[l];u?(u.size!==f.size||u.mtime!==f.mtime)&&h.push(l):r.push(l)}for(let l of Object.keys(i))a[l]||d.push(l);let c=[...r,...h];if(c.length>0||d.length>0){let l={};for(let u of c)l[u]=a[u];let f=St.join(An,"snapshots",e,`turn_${n}`);await Zr(f,l)}s.checkpoints.push({id:`turn_${n}`,timestamp:new Date().toISOString(),newFiles:r,modifiedFiles:h,deletedFiles:d,toolsUsed:t}),s.currentManifest=a,he(dn,o)}catch{}},async getCheckpoints(e){try{let t=X(dn,{})[e];return t?t.checkpoints||[]:[]}catch{return[]}},async rollbackToCheckpoint(e,n){try{let t=X(dn,{}),o=t[e];if(!o)throw new Error("No session active for Advance Rollback.");let s=o.checkpoints||[],i=s.findIndex(c=>c.id===n);if(i===-1)throw new Error(`Checkpoint [${n}] not found.`);let a=St.join(An,"snapshots",e),r={restored:0,replaced:0,failed:[]},h=await no(process.cwd());for(let c of Object.keys(h)){let l=St.join(process.cwd(),c);await wt.chmod(l,438).catch(()=>{}),await wt.remove(l).catch(()=>{})}let d=St.join(a,"initial");await Ii(d,process.cwd(),r,d);for(let c=1;c<=i;c++){let l=s[c],f=St.join(a,l.id);if(await Ii(f,process.cwd(),r,f),l.deletedFiles&&l.deletedFiles.length>0)for(let u of l.deletedFiles){let p=St.join(process.cwd(),u);await wt.chmod(p,438).catch(()=>{}),await wt.remove(p).catch(()=>{})}}return o.checkpoints=s.slice(0,i+1),o.currentManifest=await no(process.cwd()),he(dn,t),{checkpointId:n,stats:r}}catch(t){throw new Error(`Rollback failed: ${t.message}`)}},async getLatestFileChanges(e){try{let t=X(dn,{})[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=St.join(An,"snapshots",e);await wt.remove(n).catch(()=>{});let t=X(dn,{});t[e]&&(delete t[e],he(dn,t))}catch{}}};var Oi=async(e,n={})=>{let t=I(e),o=t.method,s=t.id,i=n.chatId;if(!n.systemSettings?.advanceRollback)return"ERROR: Advance Rollback feature is currently disabled in settings under Security. Tell user to enable it.";if(!i)return"ERROR: No active chat transaction found for rollback.";if(o==="getCheckpoint"){let r=await Kn.getCheckpoints(i);if(r.length===0)return"No checkpoints available.";let h={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",await:"Await",ask:"Ask",ask_user:"Ask",invoke:"Invoke",invokesync:"InvokeSync",getprogress:"GetProgress",cancel:"Cancel",emergency_rollback:"EmergencyRollback",emergencyrollback:"EmergencyRollback"},d=l=>h[l]||h[l.toLowerCase()]||l,c=`Available checkpoints for rollback:
|
|
462
|
-
|
|
463
|
-
`;for(let l of r)if(l.id==="initial")c+=`--- Initial State (id: initial) ---
|
|
464
|
-
Tools Used: User Prompted for task
|
|
465
|
-
|
|
466
|
-
`;else{let f=l.id.replace("turn_",""),u=l.toolsUsed&&l.toolsUsed.length>0?l.toolsUsed.map(d).join(", "):"None";c+=`--- Turn ${f} (id: ${l.id}) ---
|
|
467
|
-
Tools Used: ${u}
|
|
468
|
-
|
|
469
|
-
`}return c.trim()}else if(o==="forceRevert"){if(!s)return"ERROR: Missing required parameter 'id' for forceRevert.";try{let r=await Kn.rollbackToCheckpoint(i,s),{checkpointId:h,stats:d}=r,c=d.restored+d.replaced+d.failed.length,l=`SUCCESS: Repository rolled back to checkpoint [${h}].
|
|
470
|
-
|
|
471
|
-
`;return l+=`Stats:
|
|
472
|
-
`,l+=` Restored : ${d.restored} file${d.restored!==1?"s":""} (new to workspace)
|
|
473
|
-
`,l+=` Replaced : ${d.replaced} file${d.replaced!==1?"s":""} (overwritten)
|
|
474
|
-
`,l+=` Failed : ${d.failed.length} file${d.failed.length!==1?"s":""}`,d.failed.length>0&&(l+=`
|
|
475
|
-
${d.failed.join(`
|
|
476
|
-
`)}`),l+=`
|
|
477
|
-
\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500-
|
|
478
|
-
`,l+=` Total : ${c} file${c!==1?"s":""} processed`,l}catch(r){return`ERROR: ${r.message}`}}else return`ERROR: Invalid method "${o}". Use "getCheckpoint" or "forceRevert".`};var Ps=async(e,n={})=>{let t=I(e),o=t.id,s=parseInt(t.timeout||t.time||"120",10);if((isNaN(s)||s<=0)&&(s=120),s>300&&(s=300),!o)return t.time?(await new Promise(h=>setTimeout(h,s*1e3)),`SUCCESS: Waited for ${s}s.`):'ERROR: Missing "id" argument for Await.';let i=Ye.find(h=>h.id===o);if(!i)return`ERROR: Subagent task with ID [${o}] not found.`;if(i.status==="completed")return`SUCCESS: Subagent task [${o}] completed.
|
|
479
|
-
Final Answer:
|
|
480
|
-
${i.finalAnswer||"(No output)"}`;if(i.status==="failed")return`ERROR: Subagent task [${o}] failed.
|
|
481
|
-
Error: ${i.error||"Unknown error"}`;if(i.status==="cancelled")return`INFO: Subagent task [${o}] was cancelled.`;let a,r=new Promise(h=>{a=setTimeout(()=>{h({type:"timeout"})},s*1e3)});try{let h=await Promise.race([i.completionPromise.then(()=>({type:"completion"})),r]);return clearTimeout(a),h.type==="timeout"?`TIMEOUT: Subagent task [${o}] is still running (status: ${i.status.toUpperCase()}) after ${s}s. You can continue other work or call Await again.`:i.status==="completed"?`SUCCESS: Subagent task [${o}] completed.
|
|
482
|
-
Final Answer:
|
|
483
|
-
${i.finalAnswer||"(No output)"}`:i.status==="failed"?`ERROR: Subagent task [${o}] failed.
|
|
484
|
-
Error: ${i.error||"Unknown error"}`:i.status==="cancelled"?`INFO: Subagent task [${o}] was cancelled.`:`INFO: Subagent task [${o}] status changed to ${i.status.toUpperCase()}.`}catch(h){return clearTimeout(a),`ERROR: Exception while awaiting subagent [${o}]: ${h.message}`}};var Ds=async(e,n={})=>{let t=I(e),o=t.id,s=t.answer||t.response;if(!o)return'ERROR: Missing "id" argument for Answer.';if(!s)return'ERROR: Missing "answer" argument for Answer.';let i=Ye.find(r=>r.id===o);if(!i)return`ERROR: Subagent task with ID [${o}] not found.`;if(!i.questions||i.questions.length===0)return`INFO: Subagent task [${o}] has no pending questions.`;let a=i.questions.filter(r=>!r.answered);return a.length===0?`INFO: Subagent task [${o}] has no unanswered questions.`:(a.forEach(r=>{r.answered=!0,r.answer=s,r.answeredAt=Date.now(),r._resolve&&r._resolve(s)}),i.status="running",n.onSubagentUpdate&&n.onSubagentUpdate(),`SUCCESS: Answer provided to subagent task [${o}]. Subagent execution resumed.`)};var so=async(e,n={})=>{let t=I(e),o=t.id,s=t.message||t.instruction||t.text||t.prompt;if(!o)return'ERROR: Missing "id" argument for Steer.';if(!s)return'ERROR: Missing "message" argument for Steer.';let i=Ye.find(a=>a.id===o);return i?i.status==="completed"||i.status==="failed"||i.status==="cancelled"?`ERROR: Cannot steer subagent task [${o}] because it has already finished with status [${i.status.toUpperCase()}].`:(typeof i.steer=="function"?i.steer(s):(i.pendingSteerMessages||(i.pendingSteerMessages=[]),i.pendingSteerMessages.push(s)),n.onSubagentUpdate&&n.onSubagentUpdate(),`SUCCESS: Steering instruction injected into subagent task [${o}]. It will be processed on the subagent's turn.`):`ERROR: Subagent task with ID [${o}] not found.`};import{mouse as on,keyboard as mn,Button as oo,Key as D,Point as io,clipboard as Pl}from"@nut-tree-fork/nut-js";on.config.autoDelayMs=50;mn.config.autoDelayMs=50;async function ea(){try{await mn.releaseKey(D.LeftControl,D.RightControl,D.LeftAlt,D.RightAlt,D.LeftShift,D.RightShift,D.LeftSuper,D.RightSuper)}catch{}}async function On(e,n,t={}){let o=await Ks(n);if(!o&&(e==="move"||e==="click"||e==="drag"))return`ERROR: Invalid target location specified: ${JSON.stringify(n)}`;try{switch(e.toLowerCase()){case"move":return await on.setPosition(new io(o.x,o.y)),`SUCCESS: Moved mouse to grid target ${typeof n=="string"?n:`(${o.x}, ${o.y})`}`;case"click":{await on.setPosition(new io(o.x,o.y));let s=t.button==="right"?oo.RIGHT:t.button==="middle"?oo.MIDDLE:oo.LEFT;return t.clickType==="double"?await on.doubleClick(s):await on.click(s),`SUCCESS: ${t.clickType||"Single"} clicked ${t.button||"left"} button at ${typeof n=="string"?n:`(${o.x}, ${o.y})`}`}case"drag":{let s=await Ks(t.from||n),i=await Ks(t.to);return!s||!i?'ERROR: Drag requires valid "from" and "to" target coordinates/grid codes.':(await on.setPosition(new io(s.x,s.y)),await on.pressButton(oo.LEFT),await on.setPosition(new io(i.x,i.y)),await on.releaseButton(oo.LEFT),`SUCCESS: Dragged mouse from (${s.x}, ${s.y}) to (${i.x}, ${i.y})`)}case"scroll":{let s=o||await Ks({x:640,y:360});s&&(await on.setPosition(new io(s.x,s.y)),await new Promise(h=>setTimeout(h,60)));let i=parseInt(t.amount,10);(isNaN(i)||i<=0)&&(i=5);let a=i>50?Math.min(20,Math.max(1,Math.round(i/100))):Math.min(20,i),r=t.direction==="up";for(let h=0;h<a;h++)r?await on.scrollUp(120):await on.scrollDown(120),await new Promise(d=>setTimeout(d,20));return`SUCCESS: Scrolled ${t.direction||"down"} (${a} notches${o?` at target (${o.x}, ${o.y})`:" at screen center"})`}default:return`ERROR: Unsupported mouse action "${e}"`}}catch(s){return`ERROR: Mouse action failed: ${s.message}`}}var ta={enter:D.Enter,return:D.Return,escape:D.Escape,esc:D.Escape,backspace:D.Backspace,tab:D.Tab,space:D.Space,up:D.Up,down:D.Down,left:D.Left,right:D.Right,ctrl:D.LeftControl,control:D.LeftControl,alt:D.LeftAlt,shift:D.LeftShift,cmd:D.LeftCmd,win:D.LeftWin,meta:D.LeftWin,super:D.LeftSuper,a:D.A,b:D.B,c:D.C,d:D.D,e:D.E,f:D.F,g:D.G,h:D.H,i:D.I,j:D.J,k:D.K,l:D.L,m:D.M,n:D.N,o:D.O,p:D.P,q:D.Q,r:D.R,s:D.S,t:D.T,u:D.U,v:D.V,w:D.W,x:D.X,y:D.Y,z:D.Z,0:D.Num0,1:D.Num1,2:D.Num2,3:D.Num3,4:D.Num4,5:D.Num5,6:D.Num6,7:D.Num7,8:D.Num8,9:D.Num9,f1:D.F1,f2:D.F2,f3:D.F3,f4:D.F4,f5:D.F5,f6:D.F6,f7:D.F7,f8:D.F8,f9:D.F9,f10:D.F10,f11:D.F11,f12:D.F12},na=e=>{if(!e)return;let n=String(e).toLowerCase().trim();if(ta[n]!==void 0)return ta[n];if(D[e]!==void 0)return D[e];if(D[n.toUpperCase()]!==void 0)return D[n.toUpperCase()]};async function zn(e,n,t={}){try{switch(e.toLowerCase()){case"type":{if(typeof n!="string")return"ERROR: Type action requires a valid string input";await ea(),await Pl.setContent(n);let s=process.platform==="darwin"?D.LeftSuper:D.LeftControl;return await mn.pressKey(s,D.V),await mn.releaseKey(s,D.V),await ea(),t.autoPressEnter?(await new Promise(i=>setTimeout(i,50)),await mn.type(D.Enter),`SUCCESS: Typed text input ("${n.length>20?n.substring(0,20)+"...":n}") and pressed Enter`):`SUCCESS: Typed text input ("${n.length>20?n.substring(0,20)+"...":n}")`}case"key_press":{let o=na(n);return o===void 0?`ERROR: Unknown key name "${n}"`:(await mn.type(o),`SUCCESS: Pressed key ${n}`)}case"key_combination":{if(!Array.isArray(n))return'ERROR: key_combination requires an array of keys (e.g. ["ctrl", "c"])';let o=n.map(s=>na(s)).filter(s=>s!==void 0);return o.length===0?"ERROR: Invalid key combination":(await mn.pressKey(...o),await mn.releaseKey(...o),`SUCCESS: Executed key combination [${n.join(" + ")}]`)}case"clear_input":return await mn.pressKey(D.LeftControl,D.A),await mn.releaseKey(D.LeftControl,D.A),await mn.type(D.Backspace),"SUCCESS: Cleared active text input (Select All + Backspace)";default:return`ERROR: Unsupported keyboard action "${e}"`}}catch(o){return`ERROR: Keyboard action failed: ${o.message}`}}var ro=async(e,n={})=>{let t=I(e),o=t.action||t.type||t.cmd,s=t.target||t.grid||t.gridCode||t.location||t.input;if(!o)return'ERROR: Missing required "action" argument for computer_action (e.g. move, click, drag, scroll, type, key_press, key_combination).';let i=o.toLowerCase();if(i.startsWith("mouse_")||["move","click","drag","scroll"].includes(i)){let a=i.replace("mouse_","");return await On(a,s,{button:t.button,clickType:t.clickType||t.type,from:t.from,to:t.to,direction:t.direction,amount:t.amount?parseInt(t.amount,10):void 0})}if(i.startsWith("key_")||i==="type"||i==="press"){let a=i;i==="press"&&(a="key_press");let r=t.autoPressEnter===!0||t.autoPressEnter==="true"||t.enter===!0||t.enter==="true";return await zn(a,s||t.text||t.keys,{...t,autoPressEnter:r})}return`ERROR: Unrecognized action "${o}". Supported actions: move, click, drag, scroll, type, key_press, key_combination.`};import sa from"screenshot-desktop";import Ao from"sharp";import{mouse as Dl}from"@nut-tree-fork/nut-js";function Fl(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Nl(e,n,t=1/0){if(e===n)return 0;if(e.length===0)return n.length;if(n.length===0)return e.length;if(Math.abs(e.length-n.length)>t)return t+1;let o=Array.from({length:n.length+1},(s,i)=>i);for(let s=1;s<=e.length;s++){let i=[s],a=s;for(let r=1;r<=n.length;r++){let h=e[s-1]===n[r-1]?0:1,d=Math.min(i[r-1]+1,o[r]+1,o[r-1]+h);i.push(d),d<a&&(a=d)}if(o=i,a>t)return t+1}return o[n.length]}function Bl(e){return e<=2?0:e<=5?1:e<=10?2:Math.min(3,Math.floor(e*.25))}async function oa(e,n=3){let t=await Ao(e).metadata();return Ao(e).resize(Math.round(t.width*n),Math.round(t.height*n),{kernel:"lanczos3"}).greyscale().normalise().toBuffer()}function Ul(e){if(!e)return{words:[],lines:[]};let n=[],t=new Map;for(let s of e.split(`
|
|
485
|
-
`)){let i=s.split(" ");if(i.length<12||parseInt(i[0])!==5)continue;let r=i[2],h=i[3],d=i[4],c=parseInt(i[6]),l=parseInt(i[7]),f=parseInt(i[8]),u=parseInt(i[9]),p=parseFloat(i[10]),g=i.slice(11).join(" ").trim();if(!g||p<0)continue;let y={x0:c,y0:l,x1:c+f,y1:l+u},m={text:g,confidence:p,bbox:y};n.push(m);let w=`${r}_${h}_${d}`;t.has(w)||t.set(w,{words:[],bbox:{x0:1/0,y0:1/0,x1:-1/0,y1:-1/0}});let x=t.get(w);x.words.push(m),x.bbox.x0=Math.min(x.bbox.x0,y.x0),x.bbox.y0=Math.min(x.bbox.y0,y.y0),x.bbox.x1=Math.max(x.bbox.x1,y.x1),x.bbox.y1=Math.max(x.bbox.y1,y.y1)}let o=[];for(let s of t.values())s.words.length>0&&o.push({text:s.words.map(i=>i.text).join(" "),bbox:s.bbox,words:s.words});return{words:n,lines:o}}function Wl(e){if(!(e.words&&e.words.length>0)){if(e.blocks&&e.blocks.length>0){e.words=[],e.lines=[];for(let n of e.blocks)for(let t of n.paragraphs||[])for(let o of t.lines||[]){o.bbox&&e.lines.push(o);for(let s of o.words||[])s.bbox&&e.words.push(s)}if(e.words.length>0)return}if(e.tsv){let n=Ul(e.tsv);e.words=n.words,e.lines=n.lines}}}function ia(e,n,t=0,o=0,s=1){Wl(e);let i=r=>({x0:Math.round(r.x0/s)+t,y0:Math.round(r.y0/s)+o,x1:Math.round(r.x1/s)+t,y1:Math.round(r.y1/s)+o}),a=[];if(e.lines&&e.lines.length>0)for(let r of e.lines){let h=r.text?r.text.toLowerCase().trim():"";if(!h||!r.bbox||!(h===n||new RegExp(`\\b${Fl(n)}\\b`,"i").test(h)))continue;let c=r.words||(e.words?e.words.filter(p=>p.bbox&&p.bbox.x0>=r.bbox.x0-5&&p.bbox.x1<=r.bbox.x1+5&&p.bbox.y0>=r.bbox.y0-5&&p.bbox.y1<=r.bbox.y1+5):[]),l=n.split(/\s+/),f=l.map(p=>p.replace(/[^a-z0-9]/g,"")).join(" "),u=!1;if(c.length>0)for(let p=0;p<=c.length-l.length;p++){let g=c.slice(p,p+l.length),y=g.map(m=>(m.text||"").toLowerCase().trim().replace(/[^a-z0-9]/g,"")).join(" ");if(y===f||y.includes(f)){let m={x0:Math.min(...g.map(w=>w.bbox.x0)),y0:Math.min(...g.map(w=>w.bbox.y0)),x1:Math.max(...g.map(w=>w.bbox.x1)),y1:Math.max(...g.map(w=>w.bbox.y1))};a.push(i(m)),u=!0}}u||a.push(i(r.bbox))}if(a.length===0&&e.words&&e.words.length>0)for(let r of e.words){let h=r.text?r.text.toLowerCase().trim().replace(/[^a-z0-9]/g,""):"",d=n.replace(/[^a-z0-9]/g,"");h===d&&r.bbox&&a.push(i(r.bbox))}if(a.length===0&&e.words&&e.words.length>0){let r=Bl(n.length);for(let h of e.words){let d=h.text?h.text.toLowerCase().trim():"";d.length>=3&&Math.abs(d.length-n.length)<=r&&Nl(d,n,r)<=r&&h.bbox&&a.push(i(h.bbox))}}return a}function ra(e,n){let t=null,o=1/0;for(let s of e){let i=Math.round((s.x0+s.x1)/2),a=Math.round((s.y0+s.y1)/2),r=n.x>=s.x0&&n.x<=s.x1&&n.y>=s.y0&&n.y<=s.y1,h=Math.hypot(i-n.x,a-n.y),d=r?0:h;d<o&&(o=d,t={x:i,y:a,dist:h,containsPoint:r,bbox:s})}return t}function jl(e,n,t,o){let a=Math.ceil(e/4),r=Math.ceil(n/2),h=[];for(let d=0;d<2;d++)for(let c=0;c<4;c++){let l=c*a,f=d*r,u=Math.min(a,e-l),p=Math.min(r,n-f),g=l+u/2,y=f+p/2,m=t>=l&&t<l+u&&o>=f&&o<f+p;h.push({x0:l,y0:f,w:u,h:p,cx:g,cy:y,containsTarget:m})}return h.sort((d,c)=>{if(d.containsTarget)return-1;if(c.containsTarget)return 1;let l=Math.hypot(d.cx-t,d.cy-o),f=Math.hypot(c.cx-t,c.cy-o);return l-f})}var Li=async(e,n={})=>{let t=I(e),o=t.gridId||t.grid||t.coordinate||t.target||t.id,s=(t.type||t.clickType||"single").toLowerCase(),i=(t.button||"left").toLowerCase(),a=t.intendedClickText||t.text||"";if(!o&&!a)return'ERROR: Missing required "gridId" parameter for Click tool.';let r=o;if(a)try{let{createWorker:c}=await import("tesseract.js"),l=o?cr(o):null,{getActiveDisplay:f}=await import("./screen_grid-IKEV7A6U.js"),u=await f(),p={format:"png"};try{let v=await sa.listDisplays();v&&v.length>0&&(p={format:"png",screen:(v[u]||v[0]).id})}catch{}let g=await sa(p),y=await Ao(g).metadata(),m=y.width||1920,w=y.height||1080,x=l?{x:Math.round(l.x*(m/1280)),y:Math.round(l.y*(w/720))}:{x:m/2,y:w/2},S=await import("fs-extra"),{CU_CACHE_DIR:R}=await import("./paths-R3DD7CRF.js");S.ensureDirSync(R);let E=a.toLowerCase().trim(),b=await c("eng",1,{cachePath:R}),T=await oa(g,2),{data:$}=await b.recognize(T,{},{tsv:!0,blocks:!0}),C=l?140:400,k=null,O="";if($&&$.text){let v=ia($,E,0,0,2);if(v.length>0){let L=ra(v,x);L&&(L.containsPoint||L.dist<=C)&&(k=L,O="full-screen OCR")}}if(!k){let v=jl(m,w,x.x,x.y);for(let L=0;L<v.length;L++){let N=v[L],j=await Ao(g).extract({left:N.x0,top:N.y0,width:N.w,height:N.h}).toBuffer(),V=await oa(j,3),{data:oe}=await b.recognize(V,{},{tsv:!0,blocks:!0});if(!oe||!oe.text)continue;let Ie=ia(oe,E,N.x0,N.y0,3);if(Ie.length>0){k=ra(Ie,x),O=`tile ${L+1} OCR (${N.containsTarget?"target tile":`offset ${N.x0},${N.y0}`})`;break}}}if(await b.terminate(),k){let v={x:Math.round(k.x*(1280/m)),y:Math.round(k.y*(720/w))};return`${await On("click",v,{button:i,clickType:s})} (${O} for "${a}" at ${Math.round(k.dist)}px distance)`}}catch{}let h=null;try{h=await Dl.getPosition()}catch{}return await On("click",r,{button:i,clickType:s})};var Pi=async(e,n={})=>{let t=I(e),o=t.fromGridId||t.from||t.start,s=t.toGridId||t.to||t.end;return!o||!s?'ERROR: Drag requires both "fromGridId" and "toGridId" parameters.':await On("drag",o,{from:o,to:s})};var Di=async(e,n={})=>{let t=I(e),o=(t.direction||"down").toLowerCase(),s=t.amount?parseInt(t.amount,10):6,i=t.gridId||t.grid||t.coordinate||t.target||t.id||null;return await On("scroll",i,{direction:o,amount:s})};var vo=async(e,n={})=>{let t=I(e),o=t.text||t.input||t.value||"",s=t.autoPressEnter===!0||t.autoPressEnter==="true"||t.enter===!0||t.enter==="true";return o==null?'ERROR: Missing required "text" parameter for KeyboardTyping tool.':await zn("type",String(o),{autoPressEnter:s})};var Io=async(e,n={})=>{let t=I(e),o=t.key||t.keys||t.input||t.shortcut;if(!o)return'ERROR: Missing required "key" parameter for KeyPress tool.';let s=String(o).trim().toLowerCase();if(s==="clearinput"||s==="clear_input"||s==="clear")return await zn("clear_input");if(s.includes(";")||s.includes("+")){let i=s.split(/[;+]/).map(a=>a.trim()).filter(Boolean);return await zn("key_combination",i)}return await zn("key_press",s)};var Oo=async(e,n={})=>"SUCCESS: Screen recapture requested. The latest gridded screenshot is provided for your next decision.";var Hl={web_search:ai,web_scrape:li,memory:ci,chat:di,view_file:Qs,write_file:fi,update_file:gi,exec_command:ei,read_folder:wi,write_pdf:bi,write_docx:ki,search_keyword:eo,generate_image:$i,saveSummary:to,addMemScore:Ls,file_map:Mi,todo:Jr,invokeSync:Ai,invoke:Xr,getProgress:vi,cancel:Qr,awaitSubagent:Ps,answerSubagent:Ds,steerSubagent:so,computer_action:ro,computer_use:ro,ComputerAction:ro,ComputerUse:ro,click:Li,Click:Li,drag:Pi,Drag:Pi,scroll:Di,Scroll:Di,keyboard_typing:vo,KeyboardTyping:vo,keyboardtyping:vo,key_press:Io,KeyPress:Io,keypress:Io,recapture_screen:Oo,RecaptureScreen:Oo,recapturescreen:Oo,invoke_sync:Ai,get_progress:vi,await_subagent:Ps,answer_subagent:Ds,steer_subagent:so,steer:so,Steer:so,ask:xi,Ask:xi,WebSearch:ai,WebScrape:li,ReadFile:Qs,ReadFolder:wi,WriteFile:fi,PatchFile:gi,WritePDF:bi,WriteDoc:ki,Run:ei,SearchKeyword:eo,CodeSearch:eo,code_search:eo,Memory:ci,Chat:di,GenerateImage:$i,saveSumary:to,SaveSummary:to,SaveSumary:to,add_mem_score:Ls,AddMemScore:Ls,addMemoryScore:Ls,AddMemoryScore:Ls,FileMap:Mi,answer:Ds,Answer:Ds,AnswerSubagent:Ds,await:Ps,Await:Ps,AwaitSubagent:Ps,EmergencyRollback:Oi,emergency_rollback:Oi},ao=async(e,n,t={})=>{let o=t.mode?t.mode.toLowerCase():"flux",s=e.toLowerCase(),a=["memory","chat","savesummary","addmemscore","add_mem_score","ask","web_search","web_scrape","await"].some(c=>s.includes(c))||s==="ask",h=["click","drag","scroll","keyboardtyping","keyboard_typing","keypress","key_press","recapturescreen","recapture_screen","computer"].some(c=>s.includes(c));if(!a){if(o==="flow"){if(!(s.includes("write_pdf")||s.includes("write_docx")||s.includes("generate_image")))return`ERROR: Tool [${e}] is a Workspace Tool and NOT available in Flow mode. Tell user to switch (\`/mode flux\`) to use this tool.`}else if(o==="icu"){if(!h)return`ERROR: Tool [${e}] is not available in Computer Use mode. ICU mode only supports Computer Use tools (Click, Drag, Scroll, KeyboardTyping, KeyPress, RecaptureScreen).`}else if(s.includes("write_pdf")||s.includes("write_docx")||s.includes("generate_image"))return`ERROR: Tool [${e}] is not available in ${t.mode||"Flux"} mode. Tell user to switch (\`/mode flow\`) for document generation.`}let d=Hl[e];if(!d)return`ERROR: Tool [${e}] not found in registry.`;try{return await d(n,t)}catch(c){let l=c instanceof Error?c.message:String(c);return`ERROR: Execution failed for [${e}]: ${l}`}};import Q from"path";import ve from"fs";import Gl from"gradient-string";var Fi=["I have a regex for your problems.","Your terminal, my kingdom.","Blowing on the cartridge helps. Probably.","Don't panic. I have the towel.","Logic is the start of wisdom.","Try to exit Vim? Good luck.","I speak fluent Terminal.","The cake is a lie. This code is not.","I have no bugs, just surprise features.","Rewriting in Rust... just for fun.","Coffee in, clean commits out.","The magic smoke stays inside today.","A semicolon short of a miracle.","One does not simply code without a bug.","Keep it simple. Keep it terminal.","Regex: now you have two problems.","I dream in binary.","Root access or bust.","Wait for the dial-up tone. Just kidding.","I take the 'labor' out of collab.","My other process is a TARDIS.","Calculated response: 42.","Ponder the orb. Ponder the code.","Less talk, more flow.","Elegance in every byte.","Build something the world is not ready for.","Your wishes, my tool calls.","I act in Flux. I think in Flow.","Syntax error in the universe. Please fix.","Your project, my obsession.","I am not a bot, I am an architect.","Digital spirits consulted. They say: Ship it.","Reticulate splines. Engage humor.","Code like poetry. Run like water.","Minimalism is the ultimate flex.","The truth is in the logs.","Follow the white rabbit.","There is no spoon. Only code.","Binary is the only language I trust.","I have a good feeling about this.","Pew pew! Lasers charged.","Divide by zero? Not today.","Search for the correct USB orientation...","I've got a fever, and the only cure is more code.","The code gremlins are on our side.","My favorite command? Yours.","Stay hungry. Stay active.","Momentum is your best friend.","Lead the flow. Don't chase it.","A fresh batch of bytes. Hot and ready.","I orchestrate the ones and zeros.","Smart enough to help. Humble enough to ask.","Think twice. Code once.","Pure intent. Pure execution.","Small steps. Massive impact.","Your terminal is a canvas.","Efficiency is my second name.","I have seen things you people wouldn't believe.","Let the thoughts marinate.","The best feature? The one you don't need.","Precision is the only perfection.","Stay focused. Stay terminal.","Silence is the best debugger.","Erase the debt. Commit the code.","Velocity meets stability.","Ship it. Improve it. Repeat.","Build tomorrow, right now.","Turn logic into reality.","The best way to predict the future is to build it.","Break barriers, not builds.","Fuel the next breakthrough.","Momentum is key.","Terminal vibes only.","Your digital co-pilot is ready.","Partner in code. Partner in crime.","I speak in semicolons.","Ready for the next great idea.","Just a moment. In the zone.","Polishing the algorithms. Hold tight.","Craft a masterpiece today.","Debug the universe. Start here.","Warp speed engaged. Almost.","The cake is not a lie. It's just loading.","Finish the Kessel Run in 12 parsecs.","Do a barrel roll!","Waiting for the respawn.","Press Start to continue.","Herding digital cats... done.","The hamsters are fast today.","Tasting the snozberries.","I go for speed. I go for flow.","Real life or just fantasy?","Poking the bear... gently.","Ensure the magic smoke stays inside.","Try turning it off and on again.","Construct additional pylons.","New line? Ctrl+J is your friend.","Release the HypnoDrones.","Push the button, Frank.","My other loading screen is even funnier.","Pretty sure a cat walked on my keyboard.","Recalibrate the humor-o-meter.","Summon the code gremlins.","I've seen your browser history. Just kidding.","Charge the laser... pew pew!","Dividing by zero... just for a sec.","Looking for an adult supervisor. Found none.","Make it go beep boop.","Buffering... for effect.","Entangle quantum particles... complete.","Polishing the chrome on my algorithms.","Are you not entertained?","Just waiting for the dial-up tone.","Reboot the humor module.","Defragment memories. Check.","Optimizing for ludicrous speed.","Swapping bits. Don't tell the bytes.","Garbage collected. I am back.","Assembling the interwebs.","Converting coffee to logic.","Update syntax for reality.","Rewire the synapses.","Greasin' the cogs.","Engage the improbability drive.","Channel the Force.","Align the stars. Respond now.","The cake is a lie. The prompt is real.","I'm Feeling Lucky.","Shipping awesomeness.","Navigating the slime mold.","Consult digital spirits.","Ask the magic conch shell.","One moment. Optimizing humor.","Shuffling punchlines.","Compiling brilliance.","Summon the cloud of wisdom.","Prepare to dazzle.","Hold tight. Crafting a response.","Tuning the algorithms.","Following the white rabbit... again.","The truth is in here. Somewhere.","Herding cats is my day job.","Distracting you with this phrase.","Almost there. Probably.","Rickrolling my creator. Don't tell.","Slapping the bass.","Is this real life?","Ponder the orb. Type the prompt.","Thoughtful gaze initiated.","Computer's favorite snack? Microchips.","Why Java? Because I don't C#.","Charging the laser... wait for it.","Dividing by zero... just kidding!","Adult supervision not found. Proceed.","Beep boop. I'm a real boy.","Wait for the respawn.","Finish the run. Ship the code.","Fiddling with character creation.","Just a moment. Finding a meme.","Pressing A to continue.","Loading wit.exe.","Pre-heating the servers.","Calibrate flux capacitor.","Channeling the Force.","Aligning the stars.","The truth is in the code.","Don't panic.","Blowing on the cartridge.","Doing a barrel roll!","Respawning in 3... 2... 1...","The cake is a lie.","Fiddling with character settings.","Finding a suitable pun.","Distracting with wit.","Almost ready.","Hamsters on speed today.","Patting Cloudy on the head.","Rickrolling the logs.","Slapping the code.","Got a good feeling about this.","Poking the prompt.","Researching latest memes.","Making it more witty.","Thinking... hmmm.","Fish with no eyes? Fsh.","Broken pencil? Pointless.","Percussive maintenance applied.","USB orientation: 3rd try's the charm.","Rust rewrite in 3... 2...","Exiting Vim... someday.","Spinning the hamster wheel.","Not a bug. Unplanned feature.","Engage.","I'll be back.","Machine spirit consulted.","Letting the thoughts marinate.","Orb pondered.","Thoughtful gaze engaged.","Charging the laser...","Making it go beep.","Buffering...","Quantum particles entangled.","Polishing the chrome.","Entertained yet?","Gremlins summoned.","Dial-up tone finished.","Humor meter recalibrated.","Cat on keyboard. Sending help.","Enhancing...","Turn it off and on again.","Constructing pylons.","HypnoDrones released.","Pushing the button."];var aa=[{name:"Cyan Cyberpunk",text:"cyan",textMuted:"#4da6b8",textDim:"#2d6d7a",textInverted:"black",border:"cyan",borderMuted:"#1a5966",borderDim:"#0f3840",bg:void 0,cardBg:"#061e24",highlightBg:"#092b33",activeBg:"#0e3e4a",inputBg:"#092b33",inputBorder:"#092b33",inputText:"cyan",inputPlaceholder:"#2d6d7a",inputPrompt:"cyan",codeBg:"#020d10",codeBorder:"#1a5966",userMsgBg:"#092b33",userMsgBorder:"#092b33",userMsgText:"cyan",diffRemovalBg:"#3a0c1a",diffAdditionBg:"#0c3a32",diffRemovalText:"#ff4d88",diffAdditionText:"#00ffaa",diffRemovalHighlightColor:"#ff1a66",diffRemovalHighlightBg:"#590022",diffAdditionHighlightColor:"#00ffcc",diffAdditionHighlightBg:"#00593b",diffRemovalNum:"#ff4d88",diffAdditionNum:"#00ffaa",diffRemovalPrefix:"#ff1a66",diffAdditionPrefix:"#00ffcc",primary:"cyan",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"cyan",statusOff:"#2d6d7a",logoTextAnsi:"\x1B[1;36m",logoBodyAnsi:"\x1B[36m",logoMutedAnsi:"\x1B[90m",logoGradient:["#00ffff","#0088ff"]},{name:"Magenta Vaporwave",text:"magenta",textMuted:"#c451d6",textDim:"#7d2b8a",textInverted:"black",border:"magenta",borderMuted:"#5e1b69",borderDim:"#3b0f42",bg:void 0,cardBg:"#240729",highlightBg:"#310938",activeBg:"#470e52",inputBg:"#310938",inputBorder:"#310938",inputText:"magenta",inputPlaceholder:"#7d2b8a",inputPrompt:"magenta",codeBg:"#100312",codeBorder:"#5e1b69",userMsgBg:"#310938",userMsgBorder:"#310938",userMsgText:"magenta",diffRemovalBg:"#3a0c20",diffAdditionBg:"#200c3a",diffRemovalText:"#ff4d94",diffAdditionText:"#aa4dff",diffRemovalHighlightColor:"#ff1a75",diffRemovalHighlightBg:"#59002b",diffAdditionHighlightColor:"#bb66ff",diffAdditionHighlightBg:"#3b0059",diffRemovalNum:"#ff4d94",diffAdditionNum:"#aa4dff",diffRemovalPrefix:"#ff1a75",diffAdditionPrefix:"#bb66ff",primary:"magenta",secondary:"cyan",accent:"purple",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"magenta",statusOff:"#7d2b8a",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ff00ff","#8800ff"]},{name:"Glitch Matrix",text:"#00ff41",textMuted:"#00b32d",textDim:"#00661a",textInverted:"black",border:"#00ff41",borderMuted:"#008020",borderDim:"#004d13",bg:void 0,cardBg:"#0d1f0d",highlightBg:"#122912",activeBg:"#1c3e1c",inputBg:"#122912",inputBorder:"#122912",inputText:"#00ff41",inputPlaceholder:"#00b32d",inputPrompt:"#ffff00",codeBg:"#040a04",codeBorder:"#008020",userMsgBg:"#122912",userMsgBorder:"#122912",userMsgText:"#00ff41",diffRemovalBg:"#3a001a",diffAdditionBg:"#003a10",diffRemovalText:"#ff0055",diffAdditionText:"#00ff66",diffRemovalHighlightColor:"#ff0033",diffRemovalHighlightBg:"#59001b",diffAdditionHighlightColor:"#33ff88",diffAdditionHighlightBg:"#005918",diffRemovalNum:"#ff0055",diffAdditionNum:"#00ff66",diffRemovalPrefix:"#ff0033",diffAdditionPrefix:"#33ff88",primary:"#00ff41",secondary:"yellow",accent:"cyan",success:"#00ff41",warning:"yellow",danger:"red",info:"cyan",statusOn:"#00ff41",statusOff:"#00661a",logoTextAnsi:"\x1B[1;32m",logoBodyAnsi:"\x1B[32m",logoMutedAnsi:"\x1B[90m",logoGradient:["#00ff41","#ffff00"]},{name:"Warm Sunset",text:"#ffaa55",textMuted:"#cc8844",textDim:"#885522",textInverted:"black",border:"#ff9933",borderMuted:"#aa6622",borderDim:"#663311",bg:void 0,cardBg:"#24180f",highlightBg:"#2e1e12",activeBg:"#422c1b",inputBg:"#2e1e12",inputBorder:"#2e1e12",inputText:"#ffaa55",inputPlaceholder:"#885522",inputPrompt:"#ff7733",codeBg:"#120c08",codeBorder:"#aa6622",userMsgBg:"#2e1e12",userMsgBorder:"#2e1e12",userMsgText:"#ffaa55",diffRemovalBg:"#3d120c",diffAdditionBg:"#3a2e0c",diffRemovalText:"#ff5544",diffAdditionText:"#ffcc33",diffRemovalHighlightColor:"#ff3322",diffRemovalHighlightBg:"#591108",diffAdditionHighlightColor:"#ffee44",diffAdditionHighlightBg:"#594400",diffRemovalNum:"#ff5544",diffAdditionNum:"#ffcc33",diffRemovalPrefix:"#ff3322",diffAdditionPrefix:"#ffee44",primary:"#ffaa55",secondary:"#ff7733",accent:"magenta",success:"#ffcc33",warning:"#ff7733",danger:"#ff3322",info:"#ffaa55",statusOn:"#ffaa55",statusOff:"#885522",logoTextAnsi:"\x1B[1;33m",logoBodyAnsi:"\x1B[33m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ff9933","#ff0055"]},{name:"Sakura Blossom",text:"#ffc0e0",textMuted:"#d98cb3",textDim:"#804d66",textInverted:"black",border:"#ff99cc",borderMuted:"#aa4d7a",borderDim:"#662647",bg:void 0,cardBg:"#291320",highlightBg:"#331826",activeBg:"#472235",inputBg:"#331826",inputBorder:"#331826",inputText:"#ffc0e0",inputPlaceholder:"#804d66",inputPrompt:"#ff99cc",codeBg:"#140a10",codeBorder:"#aa4d7a",userMsgBg:"#331826",userMsgBorder:"#331826",userMsgText:"#ffc0e0",diffRemovalBg:"#3e0c1b",diffAdditionBg:"#1b3e2b",diffRemovalText:"#ff6699",diffAdditionText:"#66ffb3",diffRemovalHighlightColor:"#ff3377",diffRemovalHighlightBg:"#590022",diffAdditionHighlightColor:"#33ff99",diffAdditionHighlightBg:"#00592e",diffRemovalNum:"#ff6699",diffAdditionNum:"#66ffb3",diffRemovalPrefix:"#ff3377",diffAdditionPrefix:"#33ff99",primary:"#ffc0e0",secondary:"#ff99cc",accent:"magenta",success:"#66ffb3",warning:"yellow",danger:"#ff3377",info:"#ff99cc",statusOn:"#ffc0e0",statusOff:"#804d66",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ffb3d9","#ff3399"]},{name:"Radioactive Slime",text:"#ccff00",textMuted:"#99cc00",textDim:"#669900",textInverted:"#0a0f00",border:"#ccff00",borderMuted:"#99cc00",borderDim:"#669900",bg:void 0,cardBg:"#0f1400",highlightBg:"#1a2400",activeBg:"#2a3b00",inputBg:"#1a2400",inputBorder:"#1a2400",inputText:"#ccff00",inputPlaceholder:"#669900",inputPrompt:"#cc00ff",codeBg:"#050a00",codeBorder:"#99cc00",userMsgBg:"#1a2400",userMsgBorder:"#1a2400",userMsgText:"#ccff00",diffRemovalBg:"#2a0033",diffAdditionBg:"#0f3300",diffRemovalText:"#ff00cc",diffAdditionText:"#00ff33",diffRemovalHighlightColor:"#ff33cc",diffRemovalHighlightBg:"#4d0066",diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:"#1a6600",diffRemovalNum:"#ff00cc",diffAdditionNum:"#00ff33",diffRemovalPrefix:"#ff33cc",diffAdditionPrefix:"#33ff66",primary:"#ccff00",secondary:"#cc00ff",accent:"#ff00cc",success:"#00ff33",warning:"#ffcc00",danger:"#ff0033",info:"#00ccff",statusOn:"#ccff00",statusOff:"#669900",logoTextAnsi:"\x1B[1;38;5;190m",logoBodyAnsi:"\x1B[38;5;190m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ccff00","#cc00ff"]},{name:"Cosmic Void",text:"#f0f8ff",textMuted:"#a6aeb5",textDim:"#5e656e",textInverted:"#010103",border:"#f0f8ff",borderMuted:"#a6aeb5",borderDim:"#5e656e",bg:void 0,cardBg:"#05030d",highlightBg:"#0b081a",activeBg:"#171133",inputBg:"#0b081a",inputBorder:"#0b081a",inputText:"#f0f8ff",inputPlaceholder:"#5e656e",inputPrompt:"#ff007f",codeBg:"#020108",codeBorder:"#a6aeb5",userMsgBg:"#0b081a",userMsgBorder:"#0b081a",userMsgText:"#f0f8ff",diffRemovalBg:"#2e0a29",diffAdditionBg:"#091c33",diffRemovalText:"#ff33a6",diffAdditionText:"#33d6ff",diffRemovalHighlightColor:"#ff66c2",diffRemovalHighlightBg:"#5c1452",diffAdditionHighlightColor:"#66e0ff",diffAdditionHighlightBg:"#123866",diffRemovalNum:"#ff33a6",diffAdditionNum:"#33d6ff",diffRemovalPrefix:"#ff66c2",diffAdditionPrefix:"#66e0ff",primary:"#f0f8ff",secondary:"#ff007f",accent:"#9d00ff",success:"#33d6ff",warning:"#ffcc00",danger:"#ff0040",info:"#9d00ff",statusOn:"#f0f8ff",statusOff:"#5e656e",logoTextAnsi:"\x1B[1;38;5;231m",logoBodyAnsi:"\x1B[38;5;231m",logoMutedAnsi:"\x1B[38;5;240m",logoGradient:["#ffffff","#9d00ff"]},{name:"Magma Eruption",text:"#ff4d00",textMuted:"#cc3d00",textDim:"#802600",textInverted:"#0d0300",border:"#ff4d00",borderMuted:"#cc3d00",borderDim:"#802600",bg:void 0,cardBg:"#1a0600",highlightBg:"#260a00",activeBg:"#401100",inputBg:"#260a00",inputBorder:"#260a00",inputText:"#ff4d00",inputPlaceholder:"#802600",inputPrompt:"#ffcc00",codeBg:"#080200",codeBorder:"#cc3d00",userMsgBg:"#260a00",userMsgBorder:"#260a00",userMsgText:"#ff4d00",diffRemovalBg:"#2e0a0a",diffAdditionBg:"#1f1400",diffRemovalText:"#ff3333",diffAdditionText:"#ffaa00",diffRemovalHighlightColor:"#ff6666",diffRemovalHighlightBg:"#5c1414",diffAdditionHighlightColor:"#ffcc33",diffAdditionHighlightBg:"#3d2900",diffRemovalNum:"#ff3333",diffAdditionNum:"#ffaa00",diffRemovalPrefix:"#ff6666",diffAdditionPrefix:"#ffcc33",primary:"#ff4d00",secondary:"#ffcc00",accent:"#ff0040",success:"#ffaa00",warning:"#ffff00",danger:"#ff0000",info:"#ff8800",statusOn:"#ff4d00",statusOff:"#802600",logoTextAnsi:"\x1B[1;38;5;202m",logoBodyAnsi:"\x1B[38;5;202m",logoMutedAnsi:"\x1B[38;5;236m",logoGradient:["#ff4d00","#ff0000"]}],lo={Dark:{id:"Dark",name:"Dark (Default)",text:"white",textMuted:"gray",textDim:"grey",textInverted:"black",textExclusive:"#B5B8D9",textMutedExclusive:"#D4DEE7",border:"white",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:"#1e1e1e",highlightBg:"#2a2a2a",activeBg:"#3a3a3a",inputBg:"#555555",inputBorder:"#555555",inputText:"white",inputPlaceholder:"#cccccc",inputPrompt:"white",codeBg:"#1a1a1a",codeBorder:"#444444",userMsgBg:"#444444",userMsgBorder:"#444444",userMsgText:"white",diffRemovalBg:"#250808",diffAdditionBg:"#072410",diffRemovalText:"#885555",diffAdditionText:"#558866",diffRemovalHighlightColor:"#ff3333",diffRemovalHighlightBg:"#5a1818",diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:"#185a25",diffRemovalNum:"#d96868",diffAdditionNum:"#68d98c",diffRemovalPrefix:"#ff4d4d",diffAdditionPrefix:"#4dff88",primary:"white",secondary:"cyan",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"white",statusOff:"gray",logoTextAnsi:"\x1B[1;37m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#0077ff","#ff00ff"]},Light:{id:"Light",name:"Light",text:"black",textMuted:"gray",textDim:"grey",textInverted:"white",border:"black",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:"#e5e5e5",highlightBg:"#d4d4d4",activeBg:"#c0c0c0",inputBg:"#d0d0d0",inputBorder:"#d0d0d0",inputText:"black",inputPlaceholder:"#555555",inputPrompt:"black",codeBg:"#e8e8e8",codeBorder:"#b0b0b0",userMsgBg:"#d0d0d0",userMsgBorder:"#d0d0d0",userMsgText:"black",diffRemovalBg:"#fce8e8",diffAdditionBg:"#e6f9e6",diffRemovalText:"#661111",diffAdditionText:"#115511",diffRemovalHighlightColor:"#440000",diffRemovalHighlightBg:"#f8b4b4",diffAdditionHighlightColor:"#003300",diffAdditionHighlightBg:"#a6ebad",diffRemovalNum:"#c02020",diffAdditionNum:"#188028",diffRemovalPrefix:"#d01010",diffAdditionPrefix:"#109020",primary:"black",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"black",statusOff:"gray",logoTextAnsi:"\x1B[1;30m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#0077ff","#ff00ff"]},"GitHub Dark":{id:"GitHub Dark",name:"GitHub Dark",text:"#c9d1d9",textMuted:"#8b949e",textDim:"#6e7681",textInverted:"#0d1117",border:"#30363d",borderMuted:"#30363d",borderDim:"#21262d",bg:void 0,cardBg:"#161b22",highlightBg:"#21262d",activeBg:"#30363d",inputBg:"#21262d",inputBorder:"#21262d",inputText:"#c9d1d9",inputPlaceholder:"#8b949e",inputPrompt:"#58a6ff",codeBg:"#0d1117",codeBorder:"#30363d",userMsgBg:"#21262d",userMsgBorder:"#21262d",userMsgText:"#c9d1d9",diffRemovalBg:"#3c1e1e",diffAdditionBg:"#11381e",diffRemovalText:"#f85149",diffAdditionText:"#3fb950",diffRemovalHighlightColor:"#ff7b72",diffRemovalHighlightBg:"#701c1c",diffAdditionHighlightColor:"#56d364",diffAdditionHighlightBg:"#116329",diffRemovalNum:"#f85149",diffAdditionNum:"#3fb950",diffRemovalPrefix:"#f85149",diffAdditionPrefix:"#3fb950",primary:"#c9d1d9",secondary:"#58a6ff",accent:"#bc8cff",success:"#3fb950",warning:"#d29922",danger:"#f85149",info:"#58a6ff",statusOn:"#58a6ff",statusOff:"#8b949e",logoTextAnsi:"\x1B[1;36m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#2ea043","#56d364"]},"GitHub Light":{id:"GitHub Light",name:"GitHub Light",text:"#24292f",textMuted:"#57606a",textDim:"#6e7781",textInverted:"#ffffff",border:"#d0d7de",borderMuted:"#d0d7de",borderDim:"#e1e4e8",bg:void 0,cardBg:"#f6f8fa",highlightBg:"#eaeef2",activeBg:"#d0d7de",inputBg:"#eaeef2",inputBorder:"#eaeef2",inputText:"#24292f",inputPlaceholder:"#57606a",inputPrompt:"#0969da",codeBg:"#ffffff",codeBorder:"#d0d7de",userMsgBg:"#eaeef2",userMsgBorder:"#eaeef2",userMsgText:"#24292f",diffRemovalBg:"#ffebe9",diffAdditionBg:"#e6ffec",diffRemovalText:"#cf222e",diffAdditionText:"#1a7f37",diffRemovalHighlightColor:"#82071e",diffRemovalHighlightBg:"#ffc1c0",diffAdditionHighlightColor:"#116329",diffAdditionHighlightBg:"#acf2bd",diffRemovalNum:"#cf222e",diffAdditionNum:"#1a7f37",diffRemovalPrefix:"#cf222e",diffAdditionPrefix:"#1a7f37",primary:"#24292f",secondary:"#0969da",accent:"#8250df",success:"#1a7f37",warning:"#9a6700",danger:"#cf222e",info:"#0969da",statusOn:"#0969da",statusOff:"#57606a",logoTextAnsi:"\x1B[1;34m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#1a7f37","#2da44e"]},"Transparent Dark":{id:"Transparent Dark",name:"Transparent Dark",text:"white",textMuted:"gray",textDim:"grey",textInverted:"black",border:"gray",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:void 0,highlightBg:"#2a2a2a",activeBg:"#3a3a3a",inputBg:"#555555",inputBorder:"#555555",inputText:"white",inputPlaceholder:"#cccccc",inputPrompt:"white",codeBg:void 0,codeBorder:"gray",userMsgBg:"#555555",userMsgBorder:"#555555",userMsgText:"white",diffRemovalBg:void 0,diffAdditionBg:void 0,diffRemovalText:"#ff6666",diffAdditionText:"#66ff66",diffRemovalHighlightColor:"#ff3333",diffRemovalHighlightBg:void 0,diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:void 0,diffRemovalNum:"#ff6666",diffAdditionNum:"#66ff66",diffRemovalPrefix:"#ff4d4d",diffAdditionPrefix:"#4dff88",primary:"white",secondary:"cyan",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"white",statusOff:"gray",logoTextAnsi:"\x1B[1;37m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#0077ff","#ff00ff"]},"Transparent Light":{id:"Transparent Light",name:"Transparent Light",text:"black",textMuted:"gray",textDim:"grey",textInverted:"white",border:"gray",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:void 0,highlightBg:"#d4d4d4",activeBg:"#c0c0c0",inputBg:"#d0d0d0",inputBorder:"#d0d0d0",inputText:"black",inputPlaceholder:"#555555",inputPrompt:"black",codeBg:void 0,codeBorder:"gray",userMsgBg:"#d0d0d0",userMsgBorder:"#d0d0d0",userMsgText:"black",diffRemovalBg:void 0,diffAdditionBg:void 0,diffRemovalText:"#c02020",diffAdditionText:"#188028",diffRemovalHighlightColor:"#800000",diffRemovalHighlightBg:void 0,diffAdditionHighlightColor:"#004000",diffAdditionHighlightBg:void 0,diffRemovalNum:"#c02020",diffAdditionNum:"#188028",diffRemovalPrefix:"#d01010",diffAdditionPrefix:"#109020",primary:"black",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"black",statusOff:"gray",logoTextAnsi:"\x1B[1;30m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#0077ff","#ff00ff"]},"Synthwave 84":{id:"Synthwave 84",name:"Synthwave 84",text:"#fdfdfd",textMuted:"#a08eb7",textDim:"#705c8a",textInverted:"#1a1025",textExclusive:"#e3dcf0",textMutedExclusive:"#b9abc9",border:"#fc28a8",borderMuted:"#a21568",borderDim:"#5c0a3a",bg:void 0,cardBg:"#261b38",highlightBg:"#35254d",activeBg:"#4c3570",inputBg:"#35254d",inputBorder:"#35254d",inputText:"#fdfdfd",inputPlaceholder:"#a08eb7",inputPrompt:"#03e8fc",codeBg:"#1e142b",codeBorder:"#a21568",userMsgBg:"#35254d",userMsgBorder:"#35254d",userMsgText:"#fdfdfd",diffRemovalBg:"#471434",diffAdditionBg:"#144743",diffRemovalText:"#ff4081",diffAdditionText:"#00e5ff",diffRemovalHighlightColor:"#ff79a1",diffRemovalHighlightBg:"#6b1e4e",diffAdditionHighlightColor:"#66f5ff",diffAdditionHighlightBg:"#1e6b65",diffRemovalNum:"#ff4081",diffAdditionNum:"#00e5ff",diffRemovalPrefix:"#ff79a1",diffAdditionPrefix:"#66f5ff",primary:"#fdfdfd",secondary:"#03e8fc",accent:"#fc28a8",success:"#00e5ff",warning:"#ffc107",danger:"#ff4081",info:"#b388ff",statusOn:"#03e8fc",statusOff:"#a08eb7",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#fc28a8","#03e8fc"]},"Forest Sprite":{id:"Forest Sprite",name:"Forest Sprite",text:"#d6e6d1",textMuted:"#95b38d",textDim:"#628059",textInverted:"#161c14",textExclusive:"#eaf2e8",textMutedExclusive:"#a9c7a2",border:"#74a862",borderMuted:"#477038",borderDim:"#2b4720",bg:void 0,cardBg:"#1f291c",highlightBg:"#2a3826",activeBg:"#3a4d35",inputBg:"#2a3826",inputBorder:"#2a3826",inputText:"#d6e6d1",inputPlaceholder:"#95b38d",inputPrompt:"#8feb73",codeBg:"#161e14",codeBorder:"#477038",userMsgBg:"#2a3826",userMsgBorder:"#2a3826",userMsgText:"#d6e6d1",diffRemovalBg:"#3b231c",diffAdditionBg:"#203b1c",diffRemovalText:"#db6242",diffAdditionText:"#59cc3f",diffRemovalHighlightColor:"#f0896c",diffRemovalHighlightBg:"#5c362a",diffAdditionHighlightColor:"#80e368",diffAdditionHighlightBg:"#305929",diffRemovalNum:"#db6242",diffAdditionNum:"#59cc3f",diffRemovalPrefix:"#f0896c",diffAdditionPrefix:"#80e368",primary:"#d6e6d1",secondary:"#8feb73",accent:"#e69835",success:"#59cc3f",warning:"#e69835",danger:"#db6242",info:"#73b4eb",statusOn:"#8feb73",statusOff:"#95b38d",logoTextAnsi:"\x1B[1;32m",logoBodyAnsi:"\x1B[32m",logoMutedAnsi:"\x1B[90m",logoGradient:["#8feb73","#e69835"]}};var Lo=null;var la=(e="Dark")=>{let n;e==="Mystery"||e==="Chaos"?(Lo||(Lo=aa[Math.floor(Math.random()*aa.length)]),n={...Lo,id:"Mystery"}):(Lo=null,lo[e]?n=lo[e]:e==="GitHub"?n=lo["GitHub Dark"]:e==="Transparent"?n=lo["Transparent Dark"]:n=lo.Dark);let t=n.codeText||n.secondary||n.info||n.logoGradient&&n.logoGradient[0]||"cyan";return{...n,codeText:t}};var ql=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",xp=(e=2)=>{let n=ql();return n==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)},bp=(e="...",n="Loading...",t="Dark")=>{let o=Fi[Math.floor(Math.random()*Fi.length)],s=la(t),i=s.logoTextAnsi,a=s.logoBodyAnsi,r=s.logoMutedAnsi,h="\x1B[0m",d=[" \u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2588\u2588\u2588\u2591 "," \u2588\u2588\u2588\u2591 "," \u2588\u2588\u2588\u2591 "," \u2591\u2591\u2591 "],c=s.logoGradient||["#0077ff","#ff00ff"],l=Gl(c).multiline(d.join(`
|
|
486
|
-
`)).split(`
|
|
487
|
-
`),f=u=>`${r}${u}${h}`;return`${l[0]}
|
|
488
|
-
${l[1]} ${i}Selected Provider: ${n}${h}
|
|
489
|
-
${l[2]}
|
|
490
|
-
${l[3]} ${i}FluxFlow ${f("v"+e)}${h}
|
|
491
|
-
${l[4]}
|
|
492
|
-
${l[5]} ${a}See /help for additional commands.${h}
|
|
493
|
-
${l[6]} ${f(o)}
|
|
494
|
-
${l[7]}`};import{WebSocket as Po}from"ws";var qt=null,Fs=!1,Kl="ws://localhost:56832",Ni=[],Ns=null,Bi=null,ca="2.0.0",Tp=e=>{ca=e,da()},Ui=e=>{Bi=e},da=()=>{if(qt||Fs)return;Fs=!0;let e=new Po(Kl);e.on("open",()=>{for(qt=e,Fs=!1,qt.send(JSON.stringify({command:"version",version:ca,pid:process.pid,ppid:process.ppid}));Ni.length>0;)qt.send(JSON.stringify(Ni.shift()))}),e.on("message",n=>{try{let t=JSON.parse(n.toString());t.command==="contextResponse"&&Ns?(Ns(t.data),Ns=null):t.command==="securityResponse"&&Bi&&Bi(t.result)}catch{}}),e.on("error",()=>{Fs=!1,qt=null}),e.on("close",()=>{Fs=!1,qt=null})},Do=e=>{qt&&qt.readyState===Po.OPEN?qt.send(JSON.stringify(e)):(Ni.push(e),Fs||da())},Fo=()=>qt!==null&&qt.readyState===Po.OPEN,Rp=e=>{Do({command:"status",status:e})},gs=()=>new Promise(e=>{if(!qt||qt.readyState!==Po.OPEN){e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]});return}Ns=e,qt.send(JSON.stringify({command:"requestContext"})),setTimeout(()=>{Ns===e&&(e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]}),Ns=null)},1e3)}),fa=e=>{Do({command:"open",filePath:e})},Wi=(e,n,t)=>{Do({command:"showDiff",filePath:e,originalContent:n,modifiedContent:t})},ua=(e,n)=>{Do({command:"closeDiff",filePath:e,result:n})};import ha from"path";import zl from"fs";var Yl=e=>{try{return zl.readdirSync(e,{withFileTypes:!0})}catch{return[]}},ji=(e,n,t=1,o=Yl,s=[],i=null)=>{let a=i||o(e),r=" ".repeat(t-1);if(a.length>100)return`${r}${ha.basename(e)}/ (>100 files)
|
|
495
|
-
`;let h="",d=s,c=a.filter(p=>!d.includes(p.name)&&!p.name.startsWith(".")),l=a.filter(p=>d.includes(p.name)||p.name.startsWith(".")).map(p=>p.name).sort();l.length>0&&(h+=`${r}[ignored: ${l.map(p=>p+"/").join(", ")}]
|
|
496
|
-
`);let f=c.filter(p=>p.isDirectory()).sort((p,g)=>p.name.localeCompare(g.name)),u=c.filter(p=>!p.isDirectory()).map(p=>p.name).sort();for(let p of f){let g=ha.join(e,p.name);if(t>n)h+=`${r}${p.name}/ (max depth)
|
|
497
|
-
`;else{let y=o(g);y.length>80?h+=`${r}${p.name}/ (>80 files)
|
|
498
|
-
`:(h+=`${r}${p.name}/
|
|
499
|
-
`,h+=ji(g,n,t+1,o,s,y))}}return u.length>0&&(h+=`${r}${u.join("; ")}
|
|
500
|
-
`),h};import Hi from"path";import Vl from"fs";var Jl=e=>{try{return Vl.readdirSync(e,{withFileTypes:!0})}catch{return[]}},Gi=(e,n,t="",o=1,s=Jl,i=[])=>{let a=s(e),r=Hi.sep;if(a.length>100)return`${t}\u2514\u2500\u2500 ${Hi.basename(e)}${r} ...100+ files...
|
|
501
|
-
`;let h="",d=i,c=a.filter(u=>!d.includes(u.name)&&!u.name.startsWith(".")),l=a.filter(u=>d.includes(u.name)||u.name.startsWith(".")).map(u=>u.name).sort();c.sort((u,p)=>u.isDirectory()&&!p.isDirectory()?-1:!u.isDirectory()&&p.isDirectory()?1:u.name.localeCompare(p.name));let f=[...c.map(u=>({name:u.name,isDir:u.isDirectory()})),...l.map(u=>({name:u,isDir:!0,isCollapsed:!0}))];return f.forEach((u,p)=>{let g=p===f.length-1,y=Hi.join(e,u.name),m=g?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",w=t+(g?" ":"\u2502 ");if(u.isCollapsed){h+=`${t}${m}${u.name}${r}...
|
|
502
|
-
`;return}u.isDir?o>n?h+=`${t}${m}${u.name}${r} ...depth exceeded...
|
|
503
|
-
`:s(y).length>80?h+=`${t}${m}${u.name}${r} ...80+ files...
|
|
504
|
-
`:(h+=`${t}${m}${u.name}${r}
|
|
505
|
-
`,h+=Gi(y,n,w,o+1,s,i)):h+=`${t}${m}${u.name}
|
|
506
|
-
`}),h};import"@google/genai";Xl.config({quiet:!0});var Zl=/```[\s\S]*?```/g,ec=/```[\s\S]*$/g,tc=/`[^`]+`/g,nc=/^\|.*\|$/gm,sc=/^[^\w]+|[^\w]+$/g,oc=/[^a-z0-9]/gi,co=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,ic=/\[\s*(?:tool:functions\.|agent:generalist\.)([a-z0-9_]+)\s*\(/gi,rc=/(?:path|targetFile|TargetFile|directory|keyword|id|taskId|title|task)\s*=\s*\\?["']?([^\\"' \),]+)/,ys=/["']/g,pa=/\\/g,ac=/<\|channel>thought/gi,lc=/<channel\|>/gi,Pn=e=>typeof e!="string"?e:e.replace(ac,"<think>").replace(lc,"</think>"),cc=/(?:<(think|thought|thoughts)>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\])/gi,dc=/(?:<(think|thought|thoughts)>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*$/gi,ma=/(?:<think>|<\|channel>thought|\[think\])[\s\S]*?(?:<\/think>|<channel\|>|\[\/think\]|$)/gi,ga=/(?:<(think|thought|thoughts)>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\]|$)/gi,Ra=/`[^`]*`/g,Ea=/`[^`]*$/,ya=/<\|\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,fc=/"([^"]+)"\s*:\s*(?:"([^"]*)"|(\d+)|true|false|null)/g,wa=/<\|\s*tool_calls_section_begin\s*\|>/gi,xa=/<\|\s*tool_calls_section_end\s*\|>/gi,uc=/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi,ba=/<(\w+)(?:[^>]*)>\r?\n?/gi,Sa=/\r?\n?<\/\w+(?:[^>]*)>/gi,Ki=null,No={},ws={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,i)=>`${t||""}${o}${s||""} \x1B[95m${i}\x1B[0m`),hc=async(e,n=8,t=1e3,o=8e3,s=null)=>{let i=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."||(i++,i>=n))throw a;let r=Math.min(t*Math.pow(2,i-1),o);await new Promise((h,d)=>{let c=setTimeout(h,r);s&&s.addEventListener("abort",()=>{clearTimeout(c),d(new DOMException("The user aborted a request.","AbortError"))})})}}},Ot=!1;var pc=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,i,a)=>{let r=s.fullText||s.text||"";if(s.role==="user"&&i<a.length-1)if(r.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")){let h=r.indexOf("**CONTEXT SUMMARY OF PREVIOUS TURNS");if(h!==-1){let c=r.substring(0,h).lastIndexOf("[SYSTEM METADATA]");c!==-1?r=r.substring(c).trim():r=r.substring(h).trim()}}else{let h=r.lastIndexOf("[USER]"),d=r.lastIndexOf("[USER PROMPT]");h!==-1?r=r.substring(h+6).trim():d!==-1&&(r=r.substring(d).trim())}return{...s,text:r}}),t=[],o=0;for(;o<n.length;){let s=n[o];if(s.role==="user")t.push(s),o++;else{let i=[];for(;o<n.length&&n[o].role!=="user";)i.push(n[o]),o++;let a=[],r=[],h=[];i.forEach(d=>{let c=(d.text||"").toLowerCase(),l=c.includes("tool:functions.")||c.includes("agent:generalist."),f=d.role==="system"&&(d.text?.startsWith("[TOOL RESULT]")||d.text?.startsWith("SUCCESS:")||d.text?.startsWith("ERROR:"));d.role==="agent"?l?a.push(d.text):h.push(d.text):f?r.push(d.text):h.push(d.text)}),a.length>0&&t.push({role:"agent",text:"combined"}),r.length>0&&t.push({role:"system",text:"combined"}),h.length>0&&t.push({role:"agent",text:"combined"})}}return t.length},mc=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),Uo=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 r=await fetch(e,n);if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),r.ok||r.status!==429&&r.status<500)return r}catch(r){if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),r.name==="AbortError"||s?.aborted||a===t-1)throw r}s?await new Promise((r,h)=>{let d=setTimeout(()=>{s.removeEventListener("abort",c),r()},Math.min(24e3,o*Math.pow(2,a))),c=()=>{clearTimeout(d),h(new DOMException("The user aborted a request.","AbortError"))};s.addEventListener("abort",c)}):await new Promise(r=>setTimeout(r,Math.min(24e3,o*Math.pow(2,a))))}if(s?.aborted)throw new DOMException("The user aborted a request.","AbortError");let i=await fetch(e,n);return typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),i},zi=async function*(e,n,t,o,s,i,a,r,h=.99){let d=[];o&&d.push({role:"system",content:o});for(let x of t){let S=x.role==="user"?"user":"assistant",R=[];if(Array.isArray(x.parts)){for(let E of x.parts)if(E.text)R.push({type:"text",text:E.text});else if(E.inlineData&&a){let b=E.inlineData.mimeType,T=E.inlineData.data;b.startsWith("image/")&&R.push({type:"image_url",image_url:{url:`data:${b};base64,${T}`}})}}else{let E=x.text||"";E&&R.push({type:"text",text:E})}d.push({role:S,content:R.length===1&&R[0].type==="text"?R[0].text:R})}let c={model:n,messages:d,stream:!0,stream_options:{include_usage:!0},temperature:h};if(s!=="Fast"){let x={Low:"high",Medium:"high",Standard:"high",High:"max",xHigh:"max"};c.reasoning_effort=x[s]||"high",c.extra_body={thinking:{type:"enabled"}}}else c.extra_body={thinking:{type:"disabled"}};let l=await Uo("https://api.deepseek.com/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(c),signal:r});if(!l.ok){let x=await l.json().catch(()=>({}));throw new Error(`DeepSeek Error (${l.status}): ${x.error?.message||l.statusText}`)}let f=l.body.getReader(),u=new TextDecoder,p="",g=[],y=null,m=Date.now(),w=!1;for(;;){let{done:x,value:S}=await f.read();if(x){w&&(g.length>0||y)&&(yield{candidates:g.length>0?[{content:{parts:g}}]:[],usageMetadata:y});break}p+=u.decode(S,{stream:!0});let R=p.split(`
|
|
507
|
-
`);p=R.pop();for(let E of R){let b=E.trim();if(!b||!b.startsWith("data: "))continue;let T=!1;if(b==="data: [DONE]")T=!0;else try{let $=JSON.parse(b.substring(6)),C=$.choices?.[0]?.delta,k=$.usage;if($.choices?.[0]?.finish_reason&&(T=!0),k&&(y={totalTokenCount:k.total_tokens||k.prompt_tokens+k.completion_tokens,promptTokenCount:k.prompt_tokens||0,candidatesTokenCount:k.completion_tokens||0,cachedContentTokenCount:k.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:k.completion_tokens_details?.reasoning_tokens||0},w=!0),C){let O=C.reasoning_content||null;O&&(g.push({text:O,thought:!0}),w=!0),C.content&&(g.push({text:C.content}),w=!0)}}catch{}if((T||Date.now()-m>=150)&&w&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],m=Date.now(),w=!1),T)break}Date.now()-m>=150&&w&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],m=Date.now(),w=!1)}},Yi=async function*(e,n,t,o,s,i,a,r,h=.99){let d=[];o&&d.push({role:"system",content:o});for(let R of t){let E=R.role==="user"?"user":"assistant",b=[];if(Array.isArray(R.parts)){for(let T of R.parts)if(T.text)b.push({type:"text",text:T.text});else if(T.inlineData&&a){let $=T.inlineData.mimeType,C=T.inlineData.data;$.startsWith("image/")&&b.push({type:"image_url",image_url:`data:${$};base64,${C}`})}}else{let T=R.text||"";T&&b.push({type:"text",text:T})}b.length>0&&d.push({role:E,content:b.length===1&&b[0].type==="text"?b[0].text:b})}let c={Fast:"none",Low:"none",Medium:"high",Standard:"high",High:"high",xHigh:"high"},l={model:n,messages:d,stream:!0,temperature:h,prompt_cache_key:"flux-flow-session"};s&&s!=="Fast"&&qs(n)&&(l.reasoning_effort=c[s]||"high");let f=await Uo("https://api.mistral.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(l),signal:r});if(!f.ok){let R=await f.text().catch(()=>""),E=f.statusText;try{let b=JSON.parse(R);E=b.error?.message||b.message||JSON.stringify(b.detail||b)}catch{R&&(E=R)}throw new Error(`Mistral Error (${f.status}): ${JSON.stringify(E)}`)}let u=f.body.getReader(),p=new TextDecoder,g="",y=[],m=null,w=Date.now(),x=!1,S=R=>R?typeof R=="string"?Pn(R):Array.isArray(R)?R.map(S).filter(Boolean).join(""):typeof R=="object"&&R!==null?typeof R.text=="string"?Pn(R.text):typeof R.content=="string"?Pn(R.content):typeof R.thinking=="string"?Pn(R.thinking):typeof R.reasoning_content=="string"?Pn(R.reasoning_content):typeof R.reasoning=="string"?Pn(R.reasoning):typeof R.value=="string"?Pn(R.value):R.text?S(R.text):R.content?S(R.content):R.thinking?S(R.thinking):R.reasoning_content?S(R.reasoning_content):R.reasoning?S(R.reasoning):R.value?S(R.value):"":Pn(String(R)):"";for(;;){let{done:R,value:E}=await u.read();if(R){x&&(y.length>0||m)&&(yield{candidates:y.length>0?[{content:{parts:y}}]:[],usageMetadata:m});break}g+=p.decode(E,{stream:!0});let b=g.split(`
|
|
508
|
-
`);g=b.pop();for(let T of b){let $=T.trim();if(!$||!$.startsWith("data: "))continue;let C=!1;if($==="data: [DONE]")C=!0;else try{let k=JSON.parse($.substring(6)),O=k.choices?.[0]?.delta,v=k.usage;if(k.choices?.[0]?.finish_reason&&(C=!0),v&&(m={totalTokenCount:v.total_tokens||(v.prompt_tokens||0)+(v.completion_tokens||0),promptTokenCount:v.prompt_tokens||0,candidatesTokenCount:v.completion_tokens||0,cachedContentTokenCount:v.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:v.completion_tokens_details?.reasoning_tokens||0},x=!0),O){let L=O.thinking||O.reasoning_content||O.reasoning,N=S(L);N&&(y.push({text:N,thought:!0}),x=!0);let j=O.content||(!O.thinking&&!O.reasoning_content&&!O.reasoning?O.text:null);if(j)if(Array.isArray(j))for(let V of j)if(typeof V=="object"&&V!==null){let oe=V.type==="thinking"||V.type==="reasoning"||!!V.thought,Ie=S(V);Ie&&(y.push({text:Ie,...oe?{thought:!0}:{}}),x=!0)}else{let oe=S(V);oe&&(y.push({text:oe}),x=!0)}else if(typeof j=="object"&&j!==null){let V=j.type==="thinking"||j.type==="reasoning"||!!j.thought,oe=S(j);oe&&(y.push({text:oe,...V?{thought:!0}:{}}),x=!0)}else{let V=S(j);V&&(y.push({text:V}),x=!0)}}}catch{}if((C||Date.now()-w>=150)&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),x=!1),C)break}Date.now()-w>=150&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),x=!1)}},Vi=async function*(e,n,t,o,s,i,a=!1,r,h=.99){let d=[];o&&d.push({role:"system",content:o}),t.forEach(re=>{let Re=re.role==="model"?"assistant":"user",M=[];Array.isArray(re.parts)&&re.parts.forEach(F=>{if(F.text)M.push({type:"text",text:F.text});else if(F.inlineData&&a){let Y=F.inlineData.mimeType,J=F.inlineData.data;Y.startsWith("image/")&&fn(n)&&M.push({type:"image_url",image_url:{url:`data:${Y};base64,${J}`}})}}),d.push({role:Re,content:M.length===1&&M[0].type==="text"?M[0].text:M})});let l={Fast:"Fast",Low:"Fast",Medium:"Standard",Standard:"Standard",High:"High",xHigh:"High"}[s]||"High",f=l!=="Fast",u=n.includes("kimi"),p=n.includes("gemma"),g=n.includes("deepseek"),y=n.includes("glm"),m=n.includes("mistral"),w=n.includes("minimax"),x=n.includes("gpt"),S=n.includes("qwen"),R=n.includes("nemotron"),E=n.includes("llama-3"),b=n.includes("seed"),T=n.includes("poolside"),$=n.includes("thinkingmachines")||n.includes("muse"),C=E,k=null,O={Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},v={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||T||$?16384:32768;N=process.env.NVIDIA_BASE_URL?1024:N,N=k?1024:N;let j={model:n,messages:d,max_tokens:N,stream:!0,stream_options:{include_usage:!0},temperature:h,...x&&{thinking:O[s]||"high"}};if(!(process.env.NVIDIA_BASE_URL||C||k))if(u)j.chat_template_kwargs={thinking:f};else if(p)j.chat_template_kwargs={enable_thinking:f};else if(g)if(f){let re=l==="High"?"max":"high";j.chat_template_kwargs={thinking:!0,reasoning_effort:re}}else j.chat_template_kwargs={thinking:!1};else y?j.chat_template_kwargs={enable_thinking:f,clear_thinking:!f}:m?j.reasoning_effort=f?"high":"none":w&&n.includes("minimax-m3")?j.chat_template_kwargs={thinking_mode:f?"enabled":"disabled"}:S?j.chat_template_kwargs={enable_thinking:f}:R?l==="High"?(j.reasoning_budget=12e3,j.chat_template_kwargs={enable_thinking:!0}):l==="Standard"?(j.reasoning_budget=12e3,j.chat_template_kwargs={enable_thinking:!0,medium_effort:!0}):j.chat_template_kwargs={enable_thinking:!1}:b?f&&(j.extra_body={thinking_budget:parseInt(v[l]??"4096")}):T?j.chat_template_kwargs={enable_thinking:f}:$&&(j.reasoning_effort=L[l]||"medium");let V=0,oe=6,Ie=!1,B=process.env.NVIDIA_BASE_URL||"https://integrate.api.nvidia.com/v1/chat/completions",W=process.env.NVIDIA_API_KEY&&process.env.NVIDIA_BASE_URL?process.env.NVIDIA_API_KEY:e;for(B.endsWith("/chat/completions")||(B=B.replace(/\/+$/,"")+"/chat/completions");V<oe;){V++;try{let re=await Uo(B,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${W}`},body:JSON.stringify(j),signal:r});if(!re.ok){let Ue=await re.text().catch(()=>""),st=re.statusText;try{let ut=JSON.parse(Ue);st=ut.error?.message||ut.message||JSON.stringify(ut.detail||ut)}catch{Ue&&(st=Ue)}let Ge=new Error(`NVIDIA API Error (${re.status}): ${st}`);throw Ge.status=re.status,Ge}let Re=re.body.getReader(),M=new TextDecoder,F="",Y=[],J=null,Ne=Date.now(),De=!1;for(;;){let{done:Ue,value:st}=await Re.read();if(Ue){De&&(Y.length>0||J)&&(yield{candidates:Y.length>0?[{content:{parts:Y}}]:[],usageMetadata:J},Ie=!0);break}F+=M.decode(st,{stream:!0});let Ge=F.split(`
|
|
509
|
-
`);F=Ge.pop();let ut=!1;for(let Nt of Ge){let ht=Nt.trim();if(ht){if(ht==="data: [DONE]"){ut=!0;break}if(ht.startsWith("data: ")){let pt;try{pt=JSON.parse(ht.substring(6))}catch{continue}if(pt.error)throw new Error(`NVIDIA Stream Error: ${pt.error.message||JSON.stringify(pt.error)}`);pt.choices?.[0]?.finish_reason&&(ut=!0);try{let kt=pt.usage;kt&&(J={totalTokenCount:kt.total_tokens||kt.prompt_tokens+kt.completion_tokens,promptTokenCount:kt.prompt_tokens||0,candidatesTokenCount:kt.completion_tokens||0,cachedContentTokenCount:kt.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:(kt.completion_tokens_details?.reasoning_tokens||0)+(kt.completion_tokens_details?.thoughts_tokens||0)},De=!0);let Tt=pt.choices?.[0]?.delta?.reasoning||pt.choices?.[0]?.delta?.reasoning_content||"",Xe=pt.choices?.[0]?.delta?.content||"";Tt&&(Y.push({text:Tt,thought:!0}),De=!0),Xe&&(Y.push({text:Xe}),De=!0)}catch{}}}}if((ut||Date.now()-Ne>=350)&&De&&(yield{candidates:Y.length>0?[{content:{parts:[...Y]}}]:[],usageMetadata:J},Ie=!0,Y=[],Ne=Date.now(),De=!1),ut)break}break}catch(re){if(Ie||V>=oe)throw re;await new Promise(Re=>setTimeout(Re,3500))}}},gc=async function*(e,n){let t=[],o=null,s=!1,i=null,a=f=>{if(t.push(f),o){let u=o;o=null,u()}},r=n.split("/").pop();r=r.replace("llama-3.3","llama-3_3");let h=`https://api.ngc.nvidia.com/v2/predict/queues/models/qc69jvmznzxy/${r}`,d=!1,c=null,l=async()=>{try{let f=await fetch(h);if(f.ok){let u=await f.json();if(u&&u.queues&&u.queues[0]&&typeof u.queues[0].queueDepth=="number"){let p=u.queues[0].queueDepth;d||a({value:{type:"status",content:`Queue ${p||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:p}=await f.next();if(p)break;d=!0,c&&(clearInterval(c),c=null),a({value:u,done:!1})}s=!0,a(null)}catch(f){if(i=f,c&&(clearInterval(c),c=null),o){let u=o;o=null,u()}}})();try{for(;;){if(i)throw i;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)}},Ji=async function*(e,n,t,o,s,i,a,r,h=.95){let d=[];o&&d.push({role:"system",content:[{type:"text",text:o,cache_control:{type:"ephemeral"}}]});for(let R of t){let E=R.role==="user"?"user":"assistant",b=[];if(Array.isArray(R.parts)){for(let T of R.parts)if(T.text)b.push({type:"text",text:T.text});else if(T.inlineData&&a){let $=T.inlineData.mimeType,C=T.inlineData.data;$.startsWith("image/")?b.push({type:"image_url",image_url:{url:`data:${$};base64,${C}`}}):b.push({type:"file",file:{filename:T.filename||"file",file_data:`data:${$};base64,${C}`}})}}else{let T=R.text||"";T&&b.push({type:"text",text:T})}d.push({role:E,content:b.length===1&&b[0].type==="text"?b[0].text:b})}let c={Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},l={model:n,messages:d,stream:!0,temperature:h,cache_control:{type:"ephemeral"},session_id:"flux-flow-session"},f=c[s];f&&s!=="Fast"&&(l.reasoning_effort=f);let u=await Uo("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(l),signal:r});if(!u.ok){let R=await u.json().catch(()=>({}));throw new Error(`OpenRouter Error (${u.status}): ${R.error?.message||u.statusText}`)}let p=u.body.getReader(),g=new TextDecoder,y="",m=[],w=null,x=Date.now(),S=!1;for(;;){let{done:R,value:E}=await p.read();if(R){S&&(m.length>0||w)&&(yield{candidates:m.length>0?[{content:{parts:m}}]:[],usageMetadata:w});break}y+=g.decode(E,{stream:!0});let b=y.split(`
|
|
510
|
-
`);y=b.pop();for(let T of b){let $=T.trim();if(!$||!$.startsWith("data: "))continue;let C=!1;if($==="data: [DONE]")C=!0;else try{let k=JSON.parse($.substring(6)),O=k.choices?.[0]?.delta,v=k.usage;if(k.choices?.[0]?.finish_reason&&(C=!0),v&&(w={totalTokenCount:v.total_tokens||(v.prompt_tokens||0)+(v.completion_tokens||0),promptTokenCount:v.prompt_tokens||0,candidatesTokenCount:v.completion_tokens||0,cachedContentTokenCount:v.prompt_tokens_details?.cached_tokens||v.prompt_tokens_details?.cache_read_input_tokens||v.cache_read_input_tokens||0,thoughtsTokenCount:v.completion_tokens_details?.reasoning_tokens||0},S=!0),O){let L=O.reasoning||(O.reasoning_details?O.reasoning_details.map(N=>N.text).join(""):null);L&&(m.push({text:L,thought:!0}),S=!0),O.content&&(m.push({text:O.content}),S=!0)}}catch{}if((C||Date.now()-x>=150)&&S&&(yield{candidates:m.length>0?[{content:{parts:[...m]}}]:[],usageMetadata:w},m=[],x=Date.now(),S=!1),C)break}}},$a=async function*(e,n,t,o,s,i,a,r,h=1.05,d="Cloud"){let c=[];o&&c.push({role:"system",content:o});for(let b of t){let T=b.role==="user"?"user":"assistant",$="",C=[];if(Array.isArray(b.parts)){$=b.parts.map(k=>k.text||"").filter(Boolean).join(`
|
|
511
|
-
`);for(let k of b.parts){let O=k.inlineData||k.inline_data;O&&O.data&&C.push(O.data)}}else $=b.text||"";if($||C.length>0){let k={role:T,content:$};C.length>0&&(k.images=C),c.push(k)}}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 p=new Ql(u),g=[],y=null,m=Date.now(),w=!1,x={Fast:!1,Low:"medium",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},S=x[s]!==void 0?x[s]:!0,R={model:n,messages:c,stream:!0,think:S,keep_alive:"10m",options:{temperature:h}},E=await p.chat(R);for await(let b of E){if(r?.aborted)throw new DOMException("The user aborted a request.","AbortError");if(b.message?.thinking&&(g.push({text:b.message.thinking,thought:!0}),w=!0),b.message?.content&&(g.push({text:b.message.content}),w=!0),b.done){let T=b.prompt_cached_count||0;if(!T&&b.prompt_eval_count){let $=b.prompt_eval_duration||0;$>0&&$<5e7&&(T=b.prompt_eval_count)}y={totalTokenCount:(b.prompt_eval_count||0)+(b.eval_count||0),promptTokenCount:b.prompt_eval_count||0,candidatesTokenCount:b.eval_count||0,cachedContentTokenCount:T,thoughtsTokenCount:0},w=!0}(b.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})},dm=()=>{Ot=!0},fm=()=>Ot,qi={write_file:"Writing",update_file:"Editing",read_folder:"Reading",view_file:"Reading",exec_command:"Executing Command",web_search:"Searching",web_scrape:"Reading",memory:"Updating Memory",search_keyword:"Searching",file_map:"Generating Map",ask:"User Input",write_pdf:"Creating",write_docx:"Creating",generate_image:"Generating",todo:"Planning",Todo:"Planning",invoke_sync:"Sub-Agent Working",invoke:"Starting Agent",get_progress:"Checking Progress",cancel:"Cancelling",await:"Waiting",EmergencyRollback:"Don't Panic. Lookin' into it",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"},xs=(e,n)=>{try{let t=I(n),o=e.toLowerCase().replace(/_/g,"");if(o==="invokesync"||o==="invoke")return t.title||(t.task?t.task.substring(0,30):null);if(o==="getprogress"||o==="cancel"||o==="steer"||o==="steersubagent")return t.id||t.taskId;let s=t.path||t.targetFile||t.TargetFile||t.directory;return s?Q.basename(s.replace(/["']/g,"").replace(/\\/g,"/")):null}catch{return null}},Xi=e=>e?new Ta({apiKey:e}):Ki,um=async(e,n,t,o,s={})=>{let{onStatus:r,onMemoryUpdated:h,onBackgroundIncrement:d}=s,{profile:c,thinkingLevel:l,mode:f,janitorModel:u,chatId:p,systemSettings:g,sessionStats:y,aiProvider:m="Google",apiKey:w}=e,x=process.env.NVIDIA_BASE_URL||m==="Ollama"?!1:g?.memory!==!1,R=X(Dt,[]).map(M=>`- [${M.id}]: ${M.memory}`).join(`
|
|
512
|
-
`),E=o.slice(0,-1).filter(M=>M.text&&!M.text.includes("[TOOL RESULT]")&&!M.text.includes("OBSERVATION:")&&!M.text.startsWith("[TERMINAL_RECORD]")&&!M.isTerminalRecord&&!M.isMeta&&!M.isLogo&&!String(M.id).startsWith("welcome")&&!String(M.id).startsWith("logo")).slice(-14).map(M=>{let F=mc(M.text).replace(/\[tool:functions\..*?\]/g,"").replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[METADATA \(PRIORITY: DYNAMIC\)\] Time: ([^|\n]+)/g,(De,Ue)=>`[METADATA (PRIORITY: DYNAMIC)] Time: ${Ue.replace(/:\d{2}/g,"")}`).replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[TOOL RESULTS\]/g,"").replace(/\[tool results\]/g,"").replace(/\r?\n\r?\n/g,`
|
|
513
|
-
`).replace(/\n\n/g,`
|
|
514
|
-
`).replace(/\\n\\n/g,"").trim(),Y=M.role==="user"?8192:32768,J=F.substring(0,Y);F.length>Y&&(J+=`
|
|
515
|
-
... (truncated) ...`);let Ne=M.role==="user"?J.startsWith("[USER]")?"":"[USER]: ":J.startsWith("[AGENT]")?"":"[AGENT]: ";return{role:M.role==="user"?"user":"model",parts:[{text:`${Ne}${J}`}]}}),b=o.filter(M=>M.role==="user").length===1,T=n.includes("[TITLE-UPDATE]"),$=Math.random()<.8,C=b||T||$,k=t.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").trim(),O=yr(R,x,C),v=`${k.replace(/\[tool:functions\..*?\]/g,"").replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[\[TOOL RESULTS\]\]/g,"").replace(/\[tool results\]/g,"").substring(0,32768)}`;v.length>32768&&(v+=`
|
|
516
|
-
... (truncated) ...`);let L=n.replace(/\[Prompted on:.*?\]/g,"").trim();v=v.replace(/\r?\n\r?\n/g,`
|
|
517
|
-
`).replace(/\n\n/g,`
|
|
518
|
-
`).replace(/\\n\\n/g,"").trim();let N=new Date,V=`[METADATA] Current date and Time: ${`${N.getFullYear()}-${N.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(N.getDate()).padStart(2,"0")}, ${N.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0})}`}
|
|
519
|
-
|
|
520
|
-
[USER]: ${L.substring(0,8192)}
|
|
521
|
-
${L.length>8192?`... (truncated) ...
|
|
522
|
-
|
|
523
|
-
`:""}
|
|
524
|
-
[AGENT (current turn)]: ${v}`;E.push({role:"user",parts:[{text:V}]});let oe=await Jo("NVIDIA"),B=(await Ft()).quotas?.providerTiers?.NVIDIA==="Free",W="",re=0,Re=x?12:-1;for(;re<=Re;)try{if(!await Tr("background",e))return;let M="",F=null,Y=!1,J=m;try{let Ue=new Promise((Tt,Xe)=>setTimeout(()=>Xe(new Error("JANITOR_TIMEOUT")),1e4)),st=m==="Google"&&re>=0&&re<6&&oe&&B,Ge=m==="DeepSeek"&&re<4&&oe&&B;Y=st||Ge,J=Y?"NVIDIA":m;let ut=(async()=>{if(m==="OpenRouter"){let Tt=et("janitor_open_router"),ye=Ji(w,Tt,E,O,"Fast",f,!1,null,.6)[Symbol.asyncIterator](),Kt=await ye.next();return{iterator:ye,firstResult:Kt}}else if(m==="DeepSeek"&&!Y){let Xe=zi(w,et("deepseek_fast_fallback"),E,O,"Fast",f,!1,null,.6)[Symbol.asyncIterator](),ye=await Xe.next();return{iterator:Xe,firstResult:ye}}else if(m==="Mistral"&&!Y){let Xe=Yi(w,et("mistral_janitor_fallback"),E,O,"Fast",f,!1,null,.6)[Symbol.asyncIterator](),ye=await Xe.next();return{iterator:Xe,firstResult:ye}}else if(m==="NVIDIA"||Y){let Xe=Vi(Y?oe:w,et("nvidia_janitor_fallback"),E,O,"Fast",f,!1,null,.6)[Symbol.asyncIterator](),ye=await Xe.next();return{iterator:Xe,firstResult:ye}}else{let ye=(await Xi(w).models.generateContentStream({model:u||(re===Re?et("janitor_default"):et("gemma_janitor_fallback_google")),contents:E,config:{systemInstruction:O,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:at.MINIMAL}}}))[Symbol.asyncIterator](),Kt=await ye.next();return{iterator:ye,firstResult:Kt}}})();if(process.stdout.isTTY){let ye=(await ls())[p]?.name||"",Kt=ye&&!ye.startsWith("flow-")&&!ye.startsWith("Session ")?ye:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${Kt}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${Kt}\x07`)}let{iterator:Nt,firstResult:ht}=await Promise.race([ut,Ue]),{value:pt,done:kt}=ht;if(!kt&&pt){let Tt=pt.candidates?.[0]?.content?.parts,Xe=Tt?J==="Google"?Tt[1]?.text||Tt[0]?.text||"":Tt.filter(ye=>ye.text&&!ye.thought).map(ye=>ye.text).join(""):typeof pt.text=="function"?pt.text():"";Xe&&(M+=Xe),F=pt.usageMetadata;for await(let ye of{[Symbol.asyncIterator]:()=>Nt}){let Kt=ye.candidates?.[0]?.content?.parts,Jn=Kt?J==="Google"?Kt[1]?.text||Kt[0]?.text||"":Kt.filter(Xn=>Xn.text&&!Xn.thought).map(Xn=>Xn.text).join(""):typeof ye.text=="function"?ye.text():"";Jn&&(M+=Jn),F=ye.usageMetadata}}}catch(Ue){throw Ue}if(M){if(W=M,F){let Ue=F.totalTokenCount||0,st=F.cachedContentTokenCount||0,Ge=(F.candidatesTokenCount||0)+(F.thoughtsTokenCount||0),ut=Y?et("nvidia_janitor_fallback"):J==="DeepSeek"?et("deepseek_fast_fallback"):J==="OpenRouter"?et("janitor_open_router"):u||(re===Re?et("janitor_default"):et("gemma_janitor_fallback_google"));await Gt("tokens",Ue,J,ut),st>0&&await Gt("cachedTokens",st,J,ut),Ge>0&&await Gt("candidateTokens",Ge,J,ut)}}else throw new Error("No synthesis generated by Janitor.");d&&(d(),await It("background"));let Ne=Wo(W),De=!1;for(let Ue of Ne){let st=Ue.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(st)&&(De=!0);let Ge={chatId:p,sessionId:p,history:o},ut=await ao(st,Ue.args,Ge);st.toLowerCase()==="memory"&&(Ue.args.includes("action='user'")||Ue.args.includes('action="user"'))&&!ut.startsWith("ERROR")&&(h&&h(),process.stdout.isTTY&&(process.stdout.write("\x1B]0;Memory Updated\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=Memory Updated\x07")),await new Promise(ht=>setTimeout(ht,3e3)))}if(!De)try{let Ue=X(Dt,[]);if(Ue.length>0){let st=[];for(let Ge of Ue)Ge.score===void 0&&(Ge.score=.5),Ge.score*=.99995,Ge.score<.05&&(Ge.score=0),Ge.score=Math.round(Ge.score*1e5)/1e5,Ge.score>0&&st.push(Ge);he(Dt,st)}}catch{}break}catch(M){re++;let F=new Date().toLocaleString(),Y=M instanceof Error?(()=>{try{return JSON.parse(JSON.parse(M.message).error.message).error.message}catch{return String(M)}})():String(M);await new Promise(De=>setTimeout(De,1e3));let J=Q.join(cn,"janitor");if(ve.existsSync(J)||ve.mkdirSync(J,{recursive:!0}),ve.appendFileSync(Q.join(J,"error.log"),`ERROR [Attempt ${re}/${Re+1}] [${F}]: ${Y}
|
|
525
|
-
|
|
526
|
-
`),re>Re)break;let Ne=Math.min(750*Math.pow(2,re-1),5e3);await new Promise(De=>setTimeout(De,Ne))}if(re){let M=Q.join(cn,"janitor");ve.appendFileSync(Q.join(M,"error.log"),`-----------------------------------------------------------------------------
|
|
527
|
-
|
|
528
|
-
`)}if(process.stdout.isTTY)try{let Y=(await ls())[p]?.name||"",J=Y&&!Y.startsWith("flow-")&&!Y.startsWith("Session ")?Y:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${J}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${J}\x07`)}catch{process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")}},yc=e=>{let n=e.replace(cc,"").replace(dc,""),t=Is?n:n.replace(Ra,s=>" ".repeat(s.length)).replace(Ea,s=>" ".repeat(s.length));co.lastIndex=0;let o;for(;(o=co.exec(t))!==null;){let s=o.index+o[0].length-1,i=0,a=null,r=!1,h=!1;for(let d=s;d<t.length;d++){let c=n[d];if(!a&&(c==='"'||c==="'"||c==="`")?(a=c,r=!1):a&&c===a&&!r&&(a=null),!a&&(c==="("?i++:c===")"&&i--,i===0)){let l=d+1;for(;l<t.length&&/\s/.test(t[l]);)l++;if(l<t.length&&t[l]==="]"){h=!0,co.lastIndex=l+1;break}}c==="\\"?r=!r:r=!1}if(!h)return{inside:!0,toolName:o[1],startIndex:o.index,args:n.substring(o.index+o[0].length)}}return{inside:!1}},Ca=(e,n=!0)=>{let t=co;t.lastIndex=0;let o="",s=0,i;for(;(i=t.exec(e))!==null;){let a=e.substring(s,i.index);o+=n?a.replace(ma,""):a;let r=i.index+i[0].length-1,h=0,d=null,c=-1;for(let l=r;l<e.length;l++){let f=e[l];if(d){if(f===d){let u=0;for(let p=l-1;p>=0&&e[p]==="\\";p--)u++;u%2===0&&(d=null)}}else if(f==='"'||f==="'"||f==="`")d=f;else if(f==="(")h++;else if(f===")"&&(h--,h===0)){let u=l+1;for(;u<e.length&&/\s/.test(e[u]);)u++;if(u<e.length&&e[u]==="]"){c=u;break}}}if(c!==-1)o+="[tool:functions."+i[1]+"()]",s=c+1,t.lastIndex=s;else{o+="[tool:functions."+i[1]+"(",s=e.length;break}}return s<e.length&&(o+=n?e.substring(s).replace(ma,""):e.substring(s)),o},wc=(e,n,t)=>{let o=co;o.lastIndex=0;let s="",i=0,a;for(;(a=o.exec(e))!==null;){let r=e.substring(i,a.index);s+=r.replace(n,t);let h=a.index+a[0].length-1,d=0,c=null,l=-1;for(let f=h;f<e.length;f++){let u=e[f];if(c){if(u===c){let p=0;for(let g=f-1;g>=0&&e[g]==="\\";g--)p++;p%2===0&&(c=null)}}else if(u==='"'||u==="'"||u==="`")c=u;else if(u==="(")d++;else if(u===")"&&(d--,d===0)){let p=f+1;for(;p<e.length&&/\s/.test(e[p]);)p++;if(p<e.length&&e[p]==="]"){l=p;break}}}if(l!==-1)s+=e.substring(a.index,l+1),i=l+1,o.lastIndex=i;else{s+=e.substring(a.index),i=e.length;break}}return i<e.length&&(s+=e.substring(i).replace(n,t)),s},ka=e=>Ca(e,!0),xc=e=>{if(!e)return e;let n={patchfile:"PatchFile",writefile:"WriteFile",readfile:"ReadFile",viewfile:"ReadFile",run:"Run",execcommand:"Run",searchkeyword:"SearchKeyword",codesearch:"CodeSearch",code_search:"CodeSearch",websearch:"WebSearch",webscrape:"WebScrape",readfolder:"ReadFolder",writepdf:"WritePDF",writedoc:"WriteDoc",writedocx:"WriteDoc",filemap:"FileMap",generateimage:"GenerateImage",todo:"Todo",ask:"Ask"},t=s=>s.split("_").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join("");ya.lastIndex=0;let o=e.replace(ya,(s,i,a)=>{let r="";try{let c=JSON.parse(a.trim());c&&typeof c=="object"&&(r=Object.entries(c).map(([f,u])=>{let p=typeof u=="string"?u:JSON.stringify(u);return`${f}=${JSON.stringify(p)}`}).join(", "))}catch{let l=[],f=fc;f.lastIndex=0;let u;for(;(u=f.exec(a))!==null;){let p=u[1],g=u[2]!==void 0?u[2]:u[0].split(":").slice(1).join(":").trim();l.push(`${p}=${JSON.stringify(g)}`)}l.length>0?r=l.join(", "):r=a.trim()}let h=i.toLowerCase().replace(/_/g,"");return`[tool:functions.${n[h]||t(i)}(${r})]`});return wa.lastIndex=0,xa.lastIndex=0,o=o.replace(wa,""),o=o.replace(xa,""),o},bc=/(?:path|query|url|keyword|command|method|title|task|id)\s*=\s*['"`]?\s*\.\.\.\s*['"`]?/i,Sc=/^['"`]?\s*\.\.\.\s*['"`]?$/,Ln=e=>{if(e==null)return!1;let n=String(e).trim();return n==="..."||n==="\u2026"||Sc.test(n)},Wo=e=>{if(!e)return[];let n=xc(e);ga.lastIndex=0;let t=n.replace(ga,""),o=[],s=Is?t:t.replace(Ra,r=>" ".repeat(r.length)).replace(Ea,r=>" ".repeat(r.length)),i=ic;i.lastIndex=0;let a;for(;(a=i.exec(s))!==null;){let r=a[1],h=a.index+a[0].length-1,d=0,c=null,l=-1,f=-1;for(let u=h;u<s.length;u++){let p=t[u];if(c){if(p===c){let g=0;for(let y=u-1;y>=0&&t[y]==="\\";y--)g++;g%2===0&&(c=null)}}else if(p==='"'||p==="'"||p==="`")c=p;else if(p==="(")d++;else if(p===")"&&(d--,d===0)){f=u;let g=u+1;for(;g<s.length&&/\s/.test(s[g]);)g++;if(g<s.length&&s[g]==="]"){l=g;break}}}if(l!==-1){let u=t.substring(h+1,f),p=t.substring(a.index,l+1),g=I(u);Ln(g.path)||Ln(g.query)||Ln(g.url)||Ln(g.keyword)||Ln(g.command)||Ln(g.method)||Ln(g.title)||Ln(g.task)||Ln(g.id)||bc.test(u)||o.push({fullMatch:p,toolName:r.trim(),args:u.trim()}),i.lastIndex=l+1}}return o},hm=(e,n={})=>{if(!e)return null;if(No=n,Ki=new Ta({apiKey:e}),!globalThis.__perfCleanupInstalled){globalThis.__perfCleanupInstalled=!0,setInterval(()=>{typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks())},6e4);let t=globalThis.fetch;globalThis.fetch=async(...o)=>{try{let s=await t(...o);return typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),s}catch(s){throw typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),s}}}},Bo=async(e,n,t,o,s="Fast",i=.75,a="agent")=>hc(async()=>{let{aiProvider:r="Google",apiKey:h,mode:d}=e,c="",l=null,f=typeof t=="string"?[{role:"user",parts:[{text:t}]}]:t,u=new AbortController,p=u.signal,g=setInterval(()=>{Ot&&(u.abort(),clearInterval(g))},100);try{let y;r==="Ollama"?y=$a(h,n,f,o,s,d,fn(n),p,i,systemSettings?.ollamaEndpoint||"Cloud"):r==="OpenRouter"?y=Ji(h,n,f,o,s,d,fn(n),p,i):r==="DeepSeek"?y=zi(h,n,f,o,s,d,fn(n),p,i):r==="Mistral"?y=Yi(h,n,f,o,s,d,fn(n),p,i):r==="NVIDIA"?y=Vi(h,n,f,o,s,d,fn(n),p,i):y=await Xi(h).models.generateContentStream({model:n,contents:f,config:{systemInstruction:o,temperature:i,thinkingConfig:(()=>{let x=(n||"").toLowerCase(),S=x.includes("gemma-4")||x.startsWith("gemma"),R=x.includes("gemini-3");if(S||R)return S?s.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:at.MINIMAL}:{includeThoughts:!0,thinkingLevel:at.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:x.includes("pro")?at.LOW:at.MINIMAL,Low:at.LOW,Medium:at.MEDIUM,Standard:at.MEDIUM,High:at.HIGH,xHigh:at.HIGH}[s]||at.MEDIUM};{let E={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[s]||2048;return E===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:E}}})()}},{signal:p});for await(let m of y){if(Ot)throw new Error("Subagent task was cancelled.");if(e?.taskId&&typeof Ye<"u"){let S=Ye.find(R=>R.id===e.taskId);if(S&&S.status==="cancelled")throw new Error("Subagent task was cancelled.")}let w="";if(m.candidates?.[0]?.content?.parts)for(let S of m.candidates[0].content.parts)S.text&&!S.thought&&(c+=S.text,w+=S.text);let x=w?w.trim().split(/\s+/).filter(Boolean).length:0;e&&typeof e.onTokenChunk=="function"&&e.onTokenChunk(w,x),m.usageMetadata&&(l=m.usageMetadata)}}finally{clearInterval(g)}if(l){let y=l.totalTokenCount||0,m=l.cachedContentTokenCount||0,w=(l.candidatesTokenCount||0)+(l.thoughtsTokenCount||0);await Gt("tokens",y,r,n),m>0&&await Gt("cachedTokens",m,r,n),w>0&&await Gt("candidateTokens",w,r,n),e&&typeof e.onUsage=="function"&&e.onUsage({totalTokenCount:y,cachedContentTokenCount:m,candidatesTokenCount:w})}return await It("agent",r),{text:c,usageMetadata:l}}),kc=async(e,n,t=null)=>{t=t||X(Xt,{});try{let{aiProvider:o="Google"}=n;if(Object.values(t).flat().length<=5)return;let i=Object.keys(t).filter(f=>f!==e&&Array.isArray(t[f])&&t[f].length>2);if(i.length===0)return;let a=`You are a silent background process for the FluxFlow CLI Agent.
|
|
529
|
-
Your task is to summarize or merge temporary context memories from one or more past conversation sessions.
|
|
530
|
-
For each Chat ID provided, you must output a tool call to save the consolidated summary.
|
|
531
|
-
|
|
532
|
-
The tool call format MUST be:
|
|
533
|
-
[tool:functions.saveSummary(id="<chat-id>", summary="<updated summary string, max 400 words>")]
|
|
534
|
-
|
|
535
|
-
Guidelines:
|
|
536
|
-
- Create a single, updated, highly cohesive, and concise summary statement (max 400 words) for each Chat ID. It should contain WHAT user talked about, WHAT were the tasks, Temporal info, HOW/WHAT the model responded. DON'T REMOVE ANY KEY AND TURN BY TURN INFO DENSITY.
|
|
537
|
-
- Focus on key goals, preferences, modified files, and technical decisions.
|
|
538
|
-
- Under no circumstances write normal conversational text. Output ONLY the tool calls.
|
|
539
|
-
- You can stack multiple tool calls for multiple chats.
|
|
540
|
-
|
|
541
|
-
Chats to process:
|
|
542
|
-
|
|
543
|
-
`,r=X(vn,{});for(let f of i){let p=t[f].map(y=>`- ${y}`).join(`
|
|
544
|
-
`),g=r[f];a+=`[Chat ID: ${f}]
|
|
545
|
-
`,g?(a+=`- Existing Summary: "${g}"
|
|
546
|
-
`,a+=`
|
|
547
|
-
-- New Memories to integrate:
|
|
548
|
-
${p}
|
|
549
|
-
|
|
550
|
-
`):a+=`-- Individual Memories:
|
|
551
|
-
${p}
|
|
552
|
-
|
|
553
|
-
`}let h=0,d=5,c=!1,l=et("gemma_janitor_fallback_google");for(o==="OpenRouter"&&(l=et("janitor_open_router")),o==="DeepSeek"&&(l=et("deepseek_level_1")),o==="Mistral"&&(l=et("mistral_level_1")),o==="NVIDIA"&&(l=et("nvidia_janitor_fallback"));h<=d&&!c;){h++;try{let u=(await Bo(n,l,a,null,"Fast",.75,"background")).text||"",p=Wo(u);if(p.length===0)throw new Error("No tool calls detected in synthesis response");for(let g of p){let y=g.toolName;["saveSummary","saveSumary","SaveSummary","SaveSumary"].includes(y)&&await ao(y,g.args,{chatId:e})}c=!0}catch(f){if(h>=d)throw new Error(`Failed after ${d} attempts. Last error: ${f.message}`)}}}catch(o){let s=o instanceof Error?(()=>{try{return JSON.parse(JSON.parse(o.message).error.message).error.message}catch{return String(o)}})():String(o),i=Q.join(cn,"janitor");ve.existsSync(i)||ve.mkdirSync(i,{recursive:!0}),ve.appendFileSync(Q.join(i,"error.log"),`[${new Date().toLocaleString()}] Past memory batch consolidation error: ${s}
|
|
554
|
-
`)}},Tc=async(e,n,t=!1)=>{let{chatId:o,aiProvider:s="Google"}=e,i=Q.join(go,"chat-summaries.json"),a=u=>u.filter(p=>(p.role==="user"||p.role==="agent"||p.role==="system")&&p.role!=="think"&&!p.isVisualFeedback&&!p.isMeta&&!p.isTerminalRecord&&!(p.text&&p.text.includes("[TERMINAL_RECORD]"))&&!String(p.id).startsWith("welcome")).map(p=>{let g=p.fullText||p.text||"",y=p.role==="system"||g.startsWith("[TOOL RESULT]:")||p.text&&p.text.startsWith("[TOOL RESULT]:"),m=g;return y&&(g.includes("[TOOL RESULT]:")||p.text&&p.text.includes("[TOOL RESULT]:"))?m="[TOOL RESULT]: ...truncated for summary":m=m.replace(/(\[(?:tool|agent):[a-zA-Z0-9_\.]+)\([\s\S]*?\)(\])/g,"$1(...)$2"),`[${y?"TOOL":p.role==="agent"?"AGENT":"USER"}]: ${m}`}).join(`
|
|
555
|
-
|
|
556
|
-
`),r=async(u,p)=>{let g="You are an expert context summarizer. Summarize the provided chat history (which may include previous summaries, user instructions, agent outputs, and tool results) into a detailed, coherent, and highly technical summary of 1000 to 1500 words. Focus on preserving the architectural decisions made, current system state, task progress, and critical code details, chat messages, file changes. Under no circumstances exceed MAX 2000 words.",y=p?`Here is the previous summary:
|
|
557
|
-
${p}
|
|
558
|
-
|
|
559
|
-
Here is the new conversation history:
|
|
560
|
-
${u}
|
|
561
|
-
|
|
562
|
-
Provide a new consolidated summary of the entire session.`:`Here is the conversation history:
|
|
563
|
-
${u}
|
|
564
|
-
|
|
565
|
-
Provide a consolidated summary of the entire session.`,m=et("gemma_janitor_fallback_google");s==="OpenRouter"&&(m=et("janitor_open_router")),s==="DeepSeek"&&(m=et("deepseek_level_1")),s==="Mistral"&&(m=et("mistral_level_1")),s==="NVIDIA"&&(m=et("nvidia_chat_summarizer_fallback"));let w=0,x=!1,S=null;for(;w<=3&&!x;){w++;try{S=await Bo(e,m,y,g,"Fast"),x=!0}catch{if(w>3){if(s==="Google")try{let E=et("general_fallback");return(await Bo(e,E,y,g,"Fast")).text||""}catch{return""}return""}}}return S&&S.text||""},h=a(n),d=X(i,{}),c=d[o]||{summary:"",historyLength:0};typeof c=="string"&&(c={summary:c,historyLength:0});let l=c.summary||"",f=await r(h,l);if(f){c.summary=f;let u=pc(n);return t?c.historyLength=(c.historyLength||0)+u:c.historyLength=u,d[o]=c,he(i,d),f}return null},pm=e=>{try{let n=Q.join(go,"chat-summaries.json");if(ve.existsSync(n)){let t=X(n,{});t[e]&&(delete t[e],he(n,t))}}catch{}},mm=async function*(e,n,t,o,s){let{profile:i,thinkingLevel:a,mode:r,janitorModel:h,chatId:d,isPlayground:c,systemSettings:l,sessionStats:f,aiProvider:u="Google",apiTier:p,wildcardTooling:g}=t,y=fn(e);if(!Ki&&u==="Google")throw new Error("AI not initialized");let m=process.env.NVIDIA_BASE_URL||t?.aiProvider==="Ollama"?!1:l?.memory!==!1,w=n[n.length-1].text,x=Q.join(go,"chat-summaries.json"),S=!1,R=n.filter(C=>C.role==="user").length===1,E=w.includes("[TITLE-UPDATE]"),b=R||E,T=w.replace(/\[TITLE-UPDATE\]/g,"").trim();T=T.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),yield{type:"status",content:"[start]"},yield{type:"status",content:"Gathering Context"},await ft.startTransaction(d,T),l?.advanceRollback&&await Kn.takeInitialSnapshot(d),Ot=!1;let $=null;try{let C=new AbortController;$=setInterval(()=>{Ot&&(C.abort(),$&&(clearInterval($),$=null))},400);let k=[...n.slice(0,-1)];{let Ae=X(x,{})[d]||{summary:"",historyLength:0};if(Ae.summary&&Ae.historyLength>0){let Qt=0,Oe=[];for(let Qe=0;Qe<k.length;Qe++){let We=k[Qe];(We.role==="user"||We.role==="agent"||We.role==="system")&&!String(We.id).startsWith("welcome")&&!We.isMeta&&Qt++,Qt>Ae.historyLength&&Oe.push(We)}k=Oe}}k=k.map(H=>{if(H.role==="user"&&H.text){let Ae=H.text.match(/\[USER\]([\s\S]*?)\[\/USER\]/);if(Ae)return{...H,text:Ae[1].trim()}}return{...H}});let O=process.env.HIGH_CONTEXT,v=255e3,L=26e4;if(O&&O!=="false"){let H=parseInt(O,10);!isNaN(H)&&H>=256e3&&H<=1e6&&(L=H,v=Math.round(H*.85))}if((u==="NVIDIA"&&(e?.includes("gpt")||e?.includes("qwen")||e?.includes("medium")||e.includes("muse"))||u==="Mistral")&&(v=122e3,L=126e3),u!=="Ollama"&&(f?.tokens||0)>v&&(yield{type:"status_history",content:"Context Limit Reached. Condensing session history..."},await Tc(t,k,!0)&&(k=[],S=!0)),R&&m){let H=X(Xt,{});Object.values(H).flat().length>5&&(yield{type:"status",content:"Condensing past chat memories"},await kc(d,t,H))}let N=X(Xt,{}),j=X(vn,{}),V=Object.entries(N).filter(([H])=>H!==d).flatMap(([H,Ae])=>Ae),Ie=[...Object.entries(j).filter(([H])=>H!==d).slice(-20).map(([H,Ae])=>`[Chat Summary]: ${Ae}`),...V].map(H=>`- ${H}`).join(`
|
|
566
|
-
`),W=X(Dt,[]).map(H=>`- ${H.memory}`).join(`
|
|
567
|
-
`),re=(f?.tokens||0)>=1e4,Re=mr(Ie,W,m,re),M=new Date,F=M.getFullYear(),Y=M.toLocaleString("en-US",{month:"short"}).toUpperCase(),J=String(M.getDate()).padStart(2,"0"),Ne=M.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}),De=`${F}-${Y}-${J}, ${Ne}`,Ue=[".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"],st=H=>{try{return ve.readdirSync(H,{withFileTypes:!0})}catch{return[]}},Ge=(H,Ae={value:0},Qt=1)=>{if(Ae.value>6200||Qt>7)return Ae.value;let Oe=st(H);for(let Qe of Oe){if(Ae.value>6200)break;Ue.includes(Qe.name)||Qe.name.startsWith(".")||Qe.isDirectory()&&(Ae.value++,Ge(Q.join(H,Qe.name),Ae,Qt+1))}return Ae.value},ut=(H,Ae)=>l?.indentationTree!==!1?ji(H,Ae,1,st,Ue):Gi(H,Ae,"",1,st,Ue),Nt=Ge(process.cwd()),ht=12;Nt>3072?ht=1:Nt>2304?ht=2:Nt>1536?ht=3:Nt>768?ht=4:Nt>384?ht=6:Nt>192?ht=7:Nt>96?ht=8:Nt>48?ht=9:Nt>24&&(ht=10);let pt=X(Vo,{}),kt=pt[d],Tt=kt?kt!==process.cwd():!1;pt[d]=process.cwd(),he(Vo,pt);let Xe=X(x,{}),ye=Xe[d]||{summary:"",historyLength:0};typeof ye=="string"&&(ye={summary:ye,historyLength:0});let Kt=n.filter(H=>(H.role==="user"||H.role==="agent"||H.role==="system")&&!String(H.id).startsWith("welcome")&&!H.isMeta).length;ye.historyLength&&Kt<ye.historyLength&&(ye.summary="",ye.historyLength=0,Xe[d]=ye,he(x,Xe));let Jn=typeof ye=="object"?ye.summary||"":ye||"",Xn=k.length>0;Xn&&Jn&&k[0]&&(k[0].role==="user"||k[0].role==="system")&&(k[0].text.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")||(k[0].text=`[SYSTEM METADATA]
|
|
568
|
-
**CONTEXT SUMMARY OF PREVIOUS TURNS (PRIORITY: DYNAMIC)**
|
|
569
|
-
${Jn}
|
|
570
|
-
|
|
571
|
-
[USER] ${k[0].text}`,yield{type:"summary_injected",content:{id:k[0].id,text:k[0].text}}));let Qi=Jn&&!Xn?`
|
|
572
|
-
[SYSTEM METADATA]
|
|
573
|
-
**CONTEXT SUMMARY OF PREVIOUS TURNS**
|
|
574
|
-
${Jn}
|
|
575
|
-
`:"",Zi=!!l?.dynamicDirAwareness,_a=`${d}|${u}|${a}|${e}|${i}|${Zi}`,er=!Zi&&ws.key===_a&&ws.value?"":`
|
|
576
|
-
**Directory Structure**
|
|
577
|
-
CWD: `+process.cwd()+`${c?" [PLAYGROUND MODE]":""}
|
|
578
|
-
`+ut(process.cwd(),ht),xt=await gs(),Dn="";if(Fo()&&xt.file_focused!=="none"){Dn=`
|
|
579
|
-
[Additional IDE Context]
|
|
580
|
-
`;let H=Q.relative(process.cwd(),xt.file_focused),Ae=(xt.opened_editors||[]).map(Oe=>{let Qe=Q.relative(process.cwd(),Oe);return Qe.startsWith("..")?`[External] ${Q.basename(Oe)}`:Qe});if(Dn+=`Focused File: ${H}
|
|
581
|
-
Cursor Line: ${xt.cursor_line}
|
|
582
|
-
`,xt.selected){let Oe=xt.selected,Qe=Oe.split(`
|
|
583
|
-
`);Qe.length>256&&(Oe=Qe.slice(0,240).join(`
|
|
584
|
-
`)+`
|
|
585
|
-
... [truncated] ...
|
|
586
|
-
`+Qe.slice(-16).join(`
|
|
587
|
-
`)),Oe.length>2048&&(Oe=Oe.slice(0,1920)+`
|
|
588
|
-
... [truncated] ...
|
|
589
|
-
`+Oe.slice(-128)),Dn+=`Current Selection: "${Oe}"
|
|
590
|
-
`}if(xt.manual_edits){let Qe=xt.manual_edits.split(`
|
|
591
|
-
`),We=[],Ve=null;for(let q of Qe)q.trim()&&(q.startsWith(" Line ")?Ve&&Ve.edits.push(q):(Ve={path:q.endsWith(":")?q.slice(0,-1):q,edits:[]},We.push(Ve)));for(let q of We)q.edits.length>80&&(q.edits=q.edits.slice(-80)),q.originalEditsCount=q.edits.length;let ce=(q,Z)=>Z.reduce((je,rn)=>{let wn=xt.file_focused&&(rn.path===xt.file_focused||Q.resolve(process.cwd(),rn.path)===Q.resolve(xt.file_focused))?Math.ceil(q*1.2):q;return je+Math.min(rn.edits.length,wn)},0),Bt=80;if(ce(80,We)>300){let q=!1;for(let Z=80;Z>=10;Z--)if(ce(Z,We)<=300){Bt=Z,q=!0;break}q||(Bt=10)}let Je=[...We];if(Bt===10&&ce(10,Je)>500)for(;Je.length>0&&ce(10,Je)>500;){let q=0,Z=Je[0].originalEditsCount;for(let je=1;je<Je.length;je++)Je[je].originalEditsCount<Z&&(Z=Je[je].originalEditsCount,q=je);Je.splice(q,1)}for(let q of Je){let je=xt.file_focused&&(q.path===xt.file_focused||Q.resolve(process.cwd(),q.path)===Q.resolve(xt.file_focused))?Math.ceil(Bt*1.2):Bt;q.edits.length>je&&(q.edits=q.edits.slice(-je))}for(let q of Je){let Z=`${q.path}:
|
|
592
|
-
${q.edits.join(`
|
|
593
|
-
`)}`;for(;q.edits.length>0&&Z.length>4*768;)q.edits.shift(),Z=`${q.path}:
|
|
594
|
-
${q.edits.join(`
|
|
595
|
-
`)}`;Z.length>4*768?q.stringRepresentation="... "+Z.slice(-(4*768-4)):q.stringRepresentation=Z}let Zt=Je.map(q=>q.stringRepresentation).join(`
|
|
596
|
-
`);for(;Je.length>0&&Zt.length>4*2048;){Je[0].edits.length>0?Je[0].edits.shift():Je.shift();for(let q of Je){let Z=`${q.path}:
|
|
597
|
-
${q.edits.join(`
|
|
598
|
-
`)}`;Z.length>4*768?q.stringRepresentation="... "+Z.slice(-(4*768-4)):q.stringRepresentation=Z}Zt=Je.map(q=>q.stringRepresentation).join(`
|
|
599
|
-
`)}Zt.length>4*2048&&(Zt="... "+Zt.slice(-(4*2048-4))),Dn+=`Recent Manual Edits:
|
|
600
|
-
${Zt}
|
|
601
|
-
`}Ae.length>0&&(Dn+=`All Opened Editors: ${Ae.join(", ")}`),xt.diagnostics&&(Dn+=`
|
|
602
|
-
**Active File Errors**:
|
|
603
|
-
${xt.diagnostics}
|
|
604
|
-
`),(T.toLowerCase().includes("lint")||T.toLowerCase().includes("warning"))&&xt.warnings&&(Dn+=`
|
|
605
|
-
**Lint Warnings**:
|
|
606
|
-
${xt.warnings}
|
|
607
|
-
`)}let tr=T.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),nr=/(?:\\)?@\[([^\]]+)\]/g,jo,Ho=[];for(nr.lastIndex=0;(jo=nr.exec(tr))!==null;){let H=jo[0].startsWith("\\");Ho.push({tag:jo[1],isEscaped:H})}let Go=[],fo=null;for(let H=0;H<Ho.length;H++){let{tag:Ae,isEscaped:Qt}=Ho[H];if(!Qt)try{let Oe=Ae.trim().replace(/^["']|["']$/g,""),Qe=/[:#]L?(\d+)(?:-L?(\d+))?$/i,We=Oe.match(Qe),Ve=Oe,ce=null,Bt=null;We&&(ce=parseInt(We[1],10),Bt=We[2]?parseInt(We[2],10):ce,Ve=Oe.slice(0,We.index));let Je=Q.resolve(process.cwd(),Ve);if(ve.existsSync(Je)&&ve.statSync(Je).isFile()){let q=Ve.toLowerCase(),Z=q.endsWith(".pdf"),je=q.endsWith(".docx")||q.endsWith(".doc")||q.endsWith(".ppt")||q.endsWith(".pptx")||q.endsWith(".xls")||q.endsWith(".xlsx"),rn=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(q),Ut=rn||Z||je,wn=u==="Google"||fn(e);if(Ut&&!wn){let Be=`\u2718 Unsupported Modality: ${Q.basename(Ve)}`,_e=115;process.stdout.isTTY&&(_e=process.stdout.columns-5||120);let mt=[Be],Fn=Math.max(...mt.map($n=>$n.length)),Nn=Math.min(Fn+4,_e),es=mt.map($n=>`${$n.padEnd(Nn-2).substring(0,Nn-2)}`).join(`
|
|
608
|
-
`);yield{type:"visual_feedback",content:gn(`${es}
|
|
609
|
-
`)};continue}if(ce===null&&!Ut){let Be=0;try{Be=ve.readFileSync(Je,"utf8").split(/\r\n|\r|\n/).length}catch{}if(Be>300){let _e=`\u21B7 Skipped (Too Large): ${Q.basename(Ve)}`,mt=115;process.stdout.isTTY&&(mt=process.stdout.columns-5||120);let Fn=Math.min(_e.length+4,mt),Nn=_e.padEnd(Fn-2).substring(0,Fn-2);yield{type:"visual_feedback",content:gn(`${Nn}
|
|
610
|
-
`)};continue}}let En=ce!==null?ce:1,Qn=Bt!==null?Bt:ce!==null?ce:En+299;Qn-En>300&&(Qn=En+300);let ho=`path=${JSON.stringify(Ve)}, startLine=${En}, endLine=${Qn}`,tt=await Qs(ho,{isMultiModal:wn}),qe=!1,Wt="",Zn=null;if(typeof tt=="string"?tt.trim().startsWith("ERROR")?qe=!0:Wt=tt:tt&&typeof tt=="object"&&tt.binaryPart?(Zn=tt.binaryPart,Wt=tt.text||""):qe=!0,!qe){let Be="";if(rn?(Be=`\u2714 Processed: ${Q.basename(Ve)}`,fo=Zn):Z||je?(Be=`\u2714 Auto-Analysed: ${Q.basename(Ve)}`,fo=Zn):(Be=`\u2714 Auto-Read: ${Q.basename(Ve)}`,Go.push(Wt)),Be){let _e=115;process.stdout.isTTY&&(_e=process.stdout.columns-5||120);let mt=[Be],Fn=Math.max(...mt.map($n=>$n.length)),Nn=Math.min(Fn+4,_e),es=mt.map($n=>`${$n.padEnd(Nn-2).substring(0,Nn-2)}`).join(`
|
|
611
|
-
`);yield{type:"visual_feedback",content:gn(`${es}
|
|
612
|
-
`)}}}}}catch{}}let sr="";Go.length>0&&(sr=`[Tagged File Contents] Auto Read User Tagged files by System, No need to re-read
|
|
613
|
-
`+Go.join(`
|
|
614
|
-
|
|
615
|
-
`)+`
|
|
616
|
-
[Tagged File Contents]
|
|
617
|
-
`);let Ma=tr.replace(/\\(@\[[^\]]+\])/g,"$1"),Aa=g?`You cannot execute tools
|
|
618
|
-
Instead, output in chat the exact string you WOULD have produced & wait for system response
|
|
619
|
-
`:"",or=`[System Metadata]
|
|
620
|
-
Time: ${De}${l?.dynamicDirAwareness?er:""}${Tt?`
|
|
621
|
-
WARNING: CWD Changed from previous: "${kt}" to current: "${process.cwd()}", write change in chat to avoid future path mismatches
|
|
622
|
-
`:""}${Re}${Dn}
|
|
623
|
-
[/Metadata]
|
|
624
|
-
${Qi}${a!=="Fast"&&(u==="Mistral"&&!qs(e)||a!=="xHigh"&&u==="Google")?`${u==="Mistral"&&!qs(e)||e.toLowerCase().startsWith("gemma")?`[system] strictly follow thinking policy as high priority. do not start a response without <think>...</think> [/system]
|
|
625
|
-
`:""}`:""}[system] exact structured string '[tool:functions.toolname(arg="value")]' in chat response [/system]
|
|
626
|
-
${sr}${Aa}[user prompt] ${Ma.trim()} [/user prompt]`.trim(),ir={role:"user",text:or};fo&&(ir.binaryPart=fo),k.forEach(H=>{H.text&&H.role==="agent"&&(H.text=H.text.replace(/(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])/gi,""),H.text=H.text.replace(/(?:<(think|thought)>|\[(think|thought)\])[^\[\n]*/gi,"").trim())}),k.push(ir),Qi&&n[n.length-1]?.id&&(yield{type:"summary_injected",content:{id:n[n.length-1].id,text:or}});let Rn=null,Bs=r==="Flux"?100:10;Bs=r.toLowerCase().includes("cu")?250:Bs;let yn=16;yield{type:"status",content:"Connecting"},Ot=!1;let rr=[],uo=!1;for(let H=0;H<=Bs;H++){let Ae=await ii("agent",t);if(!Ae.allowed)throw new Error(Ae.reason||`Budget Exhausted for Provider (${u||"Agent"})`);let Qt=[];if(uo=!1,r==="ICU"||r==="FluxCU")try{yield{type:"status",content:"Capturing Screen"},await new Promise(Ee=>setTimeout(Ee,3e3));let ue=await lr();if(ue&&ue.base64){let Ee="[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]",ne={inlineData:{mimeType:ue.mimeType,data:ue.base64}};for(let nt of k)Array.isArray(nt.parts)&&(nt.parts=nt.parts.filter(_t=>!_t.inlineData));if(k.length>0&&k[k.length-1].role==="user"){let nt=k[k.length-1];typeof nt.text=="string"&&(nt.text+=`
|
|
627
|
-
|
|
628
|
-
${Ee}`,Array.isArray(nt.parts)||(nt.parts=[{text:nt.text}]),nt.parts.push(ne))}else k.push({role:"user",text:Ee,parts:[{text:Ee},ne]})}}catch(ue){console.error("Vision screenshot capture error:",ue)}if(l?.compression===0&&(f?.tokens||0)>L&&(k=br(k,6)),H>0?yield{type:"status",content:"Working"}:yield{type:"status",content:"Connecting"},Ot){try{let{clearPendingNudges:ue}=await import("./subagent_state-LZCOZSUJ.js");ue()}catch{}yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
|
|
629
|
-
|
|
630
|
-
\x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}try{let{consumePendingNudges:ue}=await import("./subagent_state-LZCOZSUJ.js"),Ee=ue();if(Ee&&Ee.length>0){let ne=Ee.join(`
|
|
631
|
-
|
|
632
|
-
`);k.length>0&&k[k.length-1].role==="user"?k[k.length-1].text+=`
|
|
633
|
-
|
|
634
|
-
${ne}`:k.push({role:"user",text:ne}),yield{type:"status",content:"Subagent Update"}}}catch{}if(o){let ue=await o();ue&&(ue.startsWith("/btw")?k.length>0&&k[k.length-1].role==="user"?k[k.length-1].text+=`
|
|
635
|
-
|
|
636
|
-
[system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/SYSTEM]
|
|
637
|
-
[question] ${ue.replace("/btw","").trim()} [/question]`:k.push({role:"user",text:`[system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
|
|
638
|
-
[question] ${ue.replace("/btw","").trim()} [/question]`}):k.length>0&&k[k.length-1].role==="user"?k[k.length-1].text+=`
|
|
639
|
-
|
|
640
|
-
[STEERING HINT, HIGH PRIORITY] ${ue.trim().toUpperCase()} [/STEERING HINT]`:k.push({role:"user",text:`[STEERING HINT, HIGH PRIORITY] ${ue.trim().toUpperCase()} [/STEERING HINT]`}),yield{type:"status",content:`${ue.startsWith("/btw")?"Question Forwarded...":"Steering Hint Injected..."}`})}let Oe,Qe=!1,We=1,Ve=1,ce="",Bt=null,Je=null,Zt=null,q=0,Z=[],je=0,rn=!1,Ut=!1,wn=!1,En=!1,Qn=!0,ho=0,tt="",qe="",Wt=!1,Zn=!1,Be=!0,_e=e,mt="";for(;We<=yn&&Ve<=yn&&!Qe&&!Ot;){let ue=!1;try{ce="",Qn&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},Qn=!1,Ve===1&&(tt=""));let Ee=P=>{if(!P||!P.includes("[tool:"))return P;let te="___THINK_OPEN_TAG___",U="___THINK_CLOSE_TAG___";P=P.replace("<think>",te).replace("</think>",U),P=P.replace(uc,(pe,de)=>de.includes("[tool:")?de.trim():pe);let G="",ke=0;for(;ke<P.length;){let pe=P.indexOf("[tool:",ke);if(pe===-1){G+=P.substring(ke).replace(ba,"").replace(Sa,"");break}let de=P.substring(ke,pe);G+=de.replace(ba,"").replace(Sa,"");let Rt=P.indexOf("]",pe);if(Rt===-1){G+=P.substring(pe);break}G+=P.substring(pe,Rt+1),ke=Rt+1}return P=G,P=P.replaceAll(te,"<think>").replaceAll(U,"</think>"),P},ne=k.filter(P=>(P.role==="user"||P.role==="agent"||P.role==="system")&&!String(P.id).startsWith("welcome")&&!P.isMeta&&!P.isTerminalRecord&&!(P.text&&P.text.startsWith("[TERMINAL_RECORD]"))).map((P,te,U)=>{let G=P.text||"";m||(G=G.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),P.role==="agent"&&(G=Ee(G),G=G.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),G=G.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*"));let ke=[];return Array.isArray(P.parts)&&P.parts.length>0?ke=P.parts.map(pe=>{if(pe.text){let de=pe.text;return m||(de=de.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),P.role==="agent"&&(de=Ee(de),de=de.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),de=de.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*")),{text:de}}return pe}):ke=[{text:G}],P.binaryPart&&fn(_e)&&U.slice(te+1).filter(de=>de.role==="user"&&!de.text?.startsWith("[TOOL RESULT]")).length<=2&&ke.push(P.binaryPart),{role:P.role==="user"||P.role==="system"?"user":"model",parts:ke}});for(let P=0;P<ne.length;P++){let te=ne[P],U=te.parts?.[0]?.text||"";if(te.role==="model"&&/\[tool:/i.test(U)){let G=-1;for(let ke=P+1;ke<ne.length;ke++){let pe=ne[ke],de=pe.parts?.[0]?.text||"";if(pe.role==="user"&&de.startsWith("[TOOL RESULT]")){G=ke;break}}if(G!==-1&&G!==P+1){let[ke]=ne.splice(G,1);ne.splice(P+1,0,ke)}}}for(let P=ne.length-2;P>=0;P--){let te=ne[P],U=ne[P+1];te.role==="user"&&U.role==="user"&&(U.parts?.[0]?.text||"").trim().startsWith("[SYSTEM")&&ne.splice(P,1)}let nt=[];for(let P=0;P<ne.length;P++){let te=ne[P];if(nt.length===0)nt.push(te);else{let U=nt[nt.length-1];U.role===te.role?(U.parts[0].text+=`
|
|
641
|
-
|
|
642
|
-
`+(te.parts?.[0]?.text||""),te.parts?.length>1&&U.parts.push(...te.parts.slice(1))):nt.push(te)}}ne.length=0,ne.push(...nt),_e=e;let _t=`${d}|${u}|${r}|${a}|${_e}|${JSON.stringify(i)}|${!!l?.dynamicDirAwareness}|${!!l?.subAgents}`;if(ws.key===_t&&ws.value)mt=ws.value;else{let P=u==="Mistral"?!!qs(_e):!(_e||"gemma").toLowerCase().startsWith("gemma");mt=gr(i,((_e||"gemma").toLowerCase().startsWith("gemma"),a),r,l,m,R,u,u==="Google"?!0:y,P,d),l?.dynamicDirAwareness||(mt+=`
|
|
643
|
-
${er.replace(`
|
|
644
|
-
**Directory Structure**`,`
|
|
645
|
-
**Directory Structure**`)}`),ws.key=_t,ws.value=mt}let Mt=ne[ne.length-1];if(Fo()&H>0){await new Promise(U=>setTimeout(U,2500)),yield{type:"status",content:"Verifying"};let P=await gs(),te=P?P.diagnostics:null;te&&Mt&&Mt.role==="user"&&Mt.parts?.[0]?.text&&(Mt.parts[0].text+=`
|
|
646
|
-
${te} [/ERROR]`),yield{type:"status",content:"Working"}}if(u==="Mistral"||u==="Google"&&e?.toLowerCase().startsWith("gemma")){let te=a!=="Fast"&&(u==="Mistral"||a!=="xHigh")?". **strictly maintain thinking policy. do not start a response without <think>...</think>**":"",U=`
|
|
647
|
-
[SYSTEM] Tool result received. Analyze output and proceed with your turn [/SYSTEM]`;Mt&&Mt.role==="user"&&Mt.parts?.[0]?.text?.startsWith("[TOOL RESULT]")&&(Mt.parts[0].text+=U)}if(l?.advanceRollback&&Mt&&Mt.role==="user"&&Mt.parts?.[0]?.text?.startsWith("[TOOL RESULT]"))try{let P=await Kn.getLatestFileChanges(d);if(P&&(P.newFiles.length>0||P.modifiedFiles.length>0||P.deletedFiles.length>0)){let te=`
|
|
648
|
-
[system] File Changes:
|
|
649
|
-
`;for(let G of P.newFiles)te+=`* ${G} (created)
|
|
650
|
-
`;for(let G of P.modifiedFiles)te+=`* ${G} (modified)
|
|
651
|
-
`;for(let G of P.deletedFiles)te+=`* ${G} (deleted)
|
|
652
|
-
`;te+="[/system]",Mt.parts[0].text+=te;let U=-1;for(let G=k.length-1;G>=0;G--)if(k[G].role==="user"&&k[G].text?.startsWith("[TOOL RESULT]")){U=G;break}U!==-1&&(k[U].text+=te)}}catch{}let tn=Math.floor(Bs*(r==="Flux"?.98:.8)),Lt=H+1;Lt>=tn&&Mt&&Mt.parts?.[0]&&(Mt.parts[0].text+=`
|
|
653
|
-
[system] WARNING, Turn Limit Impending: Step ${Lt}/${Bs}. Wrap up quickly/prompt user to continue. [/system]`);let Pt=new Promise((P,te)=>{C.signal.aborted&&te(new DOMException("The user aborted a request.","AbortError")),C.signal.addEventListener("abort",()=>{te(new DOMException("The user aborted a request.","AbortError"))})});Pt.catch(()=>{});let an=ne;if(u==="Ollama")Oe=$a(t.apiKey,_e,an,mt,a,r,y,C.signal,1,l?.ollamaEndpoint||"Cloud");else if(u==="OpenRouter")Oe=Ji(t.apiKey,_e,an,mt,a,r,y,C.signal,1);else if(u==="DeepSeek")Oe=zi(t.apiKey,_e,an,mt,a,r,y,C.signal,1.05);else if(u==="Mistral")Oe=Yi(t.apiKey,_e,an,mt,a,r,y,C.signal,1);else if(u==="NVIDIA"){let P=Vi(t.apiKey,_e,an,mt,a,r,y,C.signal,1.05);Oe=gc(P,_e)}else{let te=Xi(t?.apiKey).models.generateContentStream({model:_e||"gemini-3-flash-preview",contents:an,config:{systemInstruction:mt,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}],thinkingConfig:(()=>{let U=(_e||"").toLowerCase(),G=U.includes("gemma-4")||U.startsWith("gemma"),ke=U.includes("gemini-3");if(G||ke)return G?a.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:at.MINIMAL}:{includeThoughts:!0,thinkingLevel:at.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:U.includes("pro")?at.LOW:at.MINIMAL,Low:at.LOW,Medium:at.MEDIUM,Standard:at.MEDIUM,High:at.HIGH,xHigh:at.HIGH}[a]||at.MEDIUM};{let pe={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[a]||2048;return pe===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:pe}}})()}},{signal:C.signal});Oe=await Promise.race([te,Pt])}ce="",Bt=null,Zt=null,Z=[],je=0,yield{type:"model_update",content:null},qe="",Wt=tt.length>0;let xn="",qo=Date.now(),ss=async function*(){if(u==="Google"&&xn){let P=Us(xn);for(let te of P)yield te;xn="",qo=Date.now()}},ar=!0,os="",bs=!1,lt=null,Us=P=>{let te=[],U=P;for(;U.length>0;)if(bs){let G=os+U;if(lt==="tool"||lt==="agent"){let de=lt==="tool"?"[tool:functions.":"[agent:generalist.",Rt=lt==="tool"?"[tool":"[agent";if(!G.startsWith(Rt)||G.length>=de.length&&!G.startsWith(de)){te.push({type:"text",content:G}),os="",bs=!1,lt=null,U="";break}}let ke=-1,pe="]";if(lt==="tool"||lt==="agent"){let de=0,Rt=null,K=0,me=!1;for(let Ke=0;Ke<G.length;Ke++){let _=G[Ke];if(Rt){if(_===Rt){let bt=0;for(let Le=Ke-1;Le>=0&&G[Le]==="\\";Le--)bt++;bt%2===0&&(Rt=null)}}else if(_==='"'||_==="'"||_==="`")Rt=_;else if(_==="(")de++,me=!0;else if(_===")")de--;else if(_==="[")K++;else if(_==="]"){if(me&&de===0&&K===1){ke=Ke;break}K--}}}else lt==="end"?pe="[[END]]":lt==="kimi_section"?pe="<|tool_calls_section_end|>":lt==="kimi_call"&&(pe="<|tool_call_end|>"),ke=G.indexOf(pe);if(ke!==-1){let de=pe.length;if(!lt.startsWith("kimi")){let Rt=G.substring(0,ke+de);te.push({type:"text",content:Rt})}os="",bs=!1,lt=null,U=G.substring(ke+de)}else{let de=lt.startsWith("kimi")?8192:512;G.length>de?(lt.startsWith("kimi")||te.push({type:"text",content:G}),os="",bs=!1):os=G,U="";break}}else{let G=U.indexOf("[tool"),ke=U.indexOf("[agent"),pe=U.indexOf("[[END]]"),de=U.indexOf("<|tool_calls_section_begin|>"),Rt=U.indexOf("<|tool_call_begin|>"),K=[{type:"tool",idx:G,start:"[tool",end:"]"},{type:"agent",idx:ke,start:"[agent",end:"]"},{type:"end",idx:pe,start:"[[END]]",end:"[[END]]"},{type:"kimi_section",idx:de,start:"<|tool_calls_section_begin|>",end:"<|tool_calls_section_end|>"},{type:"kimi_call",idx:Rt,start:"<|tool_call_begin|>",end:"<|tool_call_end|>"}].filter(me=>me.idx!==-1).sort((me,Ke)=>me.idx-Ke.idx);if(K.length>0){let me=K[0];me.idx>0&&te.push({type:"text",content:U.substring(0,me.idx)}),bs=!0,lt=me.type,os="",U=U.substring(me.idx)}else{let me=["[tool","[agent","[[END]]","<|tool_calls_section_begin|>","<|tool_call_begin|>"],Ke=-1;for(let _ of me){for(let bt=_.length-1;bt>0;bt--)if(U.endsWith(_.substring(0,bt))){Ke=U.length-bt;let Le=me.indexOf(_);Le===0?lt="tool":Le===1?lt="agent":Le===2?lt="end":Le===3?lt="kimi_section":lt="kimi_call";break}if(Ke!==-1)break}if(Ke!==-1)Ke>0&&te.push({type:"text",content:U.substring(0,Ke)}),bs=!0,os=U.substring(Ke),U="";else{te.push({type:"text",content:U});break}}}return te},Oa=Oe[Symbol.asyncIterator]();for(;;){let{value:P,done:te}=await Promise.race([Oa.next(),Pt]);if(te)break;if(P&&P.type==="status"){yield P;continue}let U="",G=P.candidates?.[0]?.content?.parts;if(G&&G.length>0)for(let pe of G){let de=typeof pe.text=="string"?pe.text:pe.text?parseChunkText(pe.text):"";pe.thought?de&&(ue||(U+="<think>",ue=!0),U+=de):de&&(ue&&(U+="</think>",ue=!1),U+=de)}else P.text&&ue&&(U+="</think>",ue=!1);U=Pn(U);let ke=U?U.trim().split(/\s+/).filter(Boolean).length:0;if(t&&typeof t.onTokenChunk=="function"&&t.onTokenChunk(U,ke),ar&&(yield{type:"status",content:"Thinking"},ar=!1),Ot){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
|
|
654
|
-
|
|
655
|
-
\x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(U){if(Wt){if(qe+=U,qe.length>=64){let K=0,me=Math.min(tt.length,qe.length);for(let _=me;_>=10;_--)if(tt.endsWith(qe.substring(0,_))){K=_;break}let Ke=qe.substring(K);if(Ke){let bt=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(tt)?Ke.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):Ke.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(bt)if(ce+=bt,u==="Google")xn+=bt;else{yield*ss();let Le=Us(bt);for(let ie of Le)yield ie}}Wt=!1,qe=""}continue}else if(ce+=U,u==="Google")xn+=U;else{yield*ss();let K=Us(U);for(let me of K)yield me}let pe=yc(ce);if(pe.inside){Zn=!0,Zt||(Zt=Date.now());let me={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",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Cancel:"cancel",Await:"await",Answer:"answer",Steer:"steer",steer:"steer"}[pe.toolName]||pe.toolName,Ke=pe.args||"",_=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(me)){let Le=I(Ke),ie=Le.path||Le.targetFile||Le.TargetFile||Le.directory,bn=Le.keyword,is=Le.title||Le.task,Bn=Le.id||Le.taskId,Te=Le.timeout||Le.time;if(bn!=null)_=String(bn).replace(ys,"");else if(ie)_=Q.basename(String(ie).replace(ys,"").replace(pa,"/"));else if(is&&(me==="invoke"||me==="invoke_sync"))_=String(is).replace(ys,"").substring(0,30);else if(Bn&&me==="get_progress")_=String(Bn).replace(ys,"");else if(Te&&me==="await"){let jt=parseFloat(String(Te).replace(ys,""));isNaN(jt)?_=String(Te).replace(ys,""):(jt<5&&(jt=5),jt>120&&(jt=120),_=(Cn=>{if(Cn>=60){let zo=Math.floor(Cn/60),Ss=Cn%60;return`${zo}m${Ss>0?` ${Ss}s`:""}`}return`${Cn}s`})(jt))}else{let jt=Ke.match(rc);if(jt){let zt=jt[1].replace(ys,"");me==="invoke"||me==="invoke_sync"||me==="get_progress"?_=zt.substring(0,30):_=me==="search_keyword"||me==="file_map"?zt:Q.basename(zt.replace(pa,"/"))}}}let bt=`${qi[me]||me}${_?` ${_}`:""}`;if((me!==Bt||_!==Je)&&(Bt=me,Je=_,yield{type:"status",content:`${bt}`},process.stdout.isTTY)){let ie={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"}[me]||"Working";process.stdout.write(`\x1B]0;${ie}...\x07`)}}if(ce.length-ho>150){ho=ce.length;let K=Ca(ce,!1),Ke=(K.match(/(?:<think>|\[think\])([\s\S]*?)(?:<\/think>|\[\/think\]|$)/gi)||[]).join("").trim(),_=Ke.split(/[.!?]\s+/),bt=new Set(_),Le=_.length>10?(_.length-bt.size)/_.length:0,ie=Ke.split(/\s+/).filter($e=>$e.length>0).length,bn=.6,is=.8,Bn=!1;if((u.toLowerCase().includes("google")||u.toLowerCase().includes("mistral"))&&((_e||"").toLowerCase().startsWith("gemma")||(_e||"").toLowerCase().includes("stral"))){let A={low:256,medium:1024,high:8192,max:16384,xhigh:16384}[a?.toLowerCase()]||2500;Bn=ie>A}if(Le>bn||Bn){yield{type:"status",content:`${Le>bn?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},Ut=!0,await new Promise(A=>setTimeout(A,3e3));break}let zt=ka(ce).trim().split(/[.!?]\s+/),Cn=new Set(zt);if((zt.length>10?(zt.length-Cn.size)/zt.length:0)>is){yield{type:"status",content:"Response Loop Detected. Re-centering..."},Ut=!1,En=!0,await new Promise($e=>setTimeout($e,3e3));break}let Ss=K.replace(Zl,"").replace(ec,"").replace(tc,"").replace(nc,""),Ht=Ss.toLowerCase().split(/\s+/).map($e=>$e.replace(sc,"")).filter($e=>$e.length>0),_n=!1;if(Ht.length>=10)for(let $e=1;$e<=15;$e++){let A=Math.max(3,Math.ceil(10/$e));if(Ht.length<$e*A)continue;let z=Ht.slice(Ht.length-$e),ae=z.join(" ");if($e>1&&ae===z.slice(0,Math.floor($e/2)).join(" ").repeat(2).trim())continue;let ge=!0;for(let we=1;we<A;we++)if(Ht.slice(Ht.length-$e*(we+1),Ht.length-$e*we).join(" ")!==ae){ge=!1;break}if(ge){_n=!0;break}}if(!_n){let $e=Ss.toLowerCase().replace(oc,"");if($e.length>=20)for(let A=1;A<=10;A++){let z=Math.max(5,Math.ceil(16/A));if($e.length<A*z)continue;let ae=$e.substring($e.length-A),ge=!0;for(let we=1;we<z;we++)if($e.substring($e.length-A*(we+1),$e.length-A*we)!==ae){ge=!1;break}if(ge){_n=!0;break}}}if(_n){yield{type:"status",content:"Stuttering Detected. Re-centering..."},Ut=!1,wn=!0,await new Promise($e=>setTimeout($e,3e3));break}}let de=ce.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/gi,""),Rt=Wo(de);for(;Rt.length>je;){yield*ss();let K=Rt[je],me=Date.now(),_={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",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"}[K.toolName]||K.toolName,bt=qi[_]||K.toolName,Le=xs(_,K.args);yield{type:"status",content:`${bt}${Le?` ${Le}`:""}`};let ie="";if(_==="click"){let A=I(K.args);ie=`\u2714 Clicked: ${A.intendedClickText?`${A.intendedClickText}`:""}`}else if(_==="drag"){let A=I(K.args);ie=`\u2714 Dragged: Cell ${A.fromGridId||""} \u2192 Cell ${A.toGridId||""}`}else if(_==="scroll"){let A=I(K.args);ie=`\u2714 Scrolled: ${A.direction||"down"} (${A.amount||1})`}else if(_==="keyboard_typing"){let A=I(K.args);ie=`\u2714 Typed: ${A.text?`"${A.text.length>20?A.text.substring(0,20)+"...":A.text}"`:""}`}else if(_==="key_press")ie=`\u2714 Pressed Key: ${I(K.args).key||""}`;else if(_==="recapture_screen")ie="\u2714 Recaptured Screen";else if(_==="web_search"){let{query:A,limit:z=10,aiMode:ae=!1}=I(K.args);ie=`${A?"\u2714":"\u2718"} ${ae?"AI Search":"Searched"}: ${A?`${A}`:"No Search Query"}${ae===!1&&A?` \u2192 ${z}`:""}`}else if(_==="web_scrape"){let A=I(K.args).url||null;ie=`${A?"\u2714":"\u2718"} Visited: ${A||"No Source"}`}else if(_==="view_file"){let{path:A,StartLine:z,EndLine:ae,start_line:ge,end_line:we,startLine:He,endLine:Me}=I(K.args),be=z||ge||He,ee=ae||we||Me,fe=parseInt(be)||1,le=parseInt(ee)||(be?fe+800:800),Fe="...",Ze=le;try{let ze=Q.resolve(process.cwd(),A);if(ve.existsSync(ze)){let Et=ve.readFileSync(ze,"utf8").split(`
|
|
656
|
-
`).length;Fe=Et,!be&&!ee&&Et>800?Ze=Math.min(50,Et):Ze=Math.min(le,Et)}}catch{}let xe=(A||"").toLowerCase(),Pe=xe.endsWith(".pdf"),ot=xe.endsWith(".docx")||xe.endsWith(".doc")||xe.endsWith(".ppt")||xe.endsWith(".pptx")||xe.endsWith(".xls")||xe.endsWith(".xlsx"),Ce=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(xe);Pe||ot?ie=`${A.length>0?"\u2714":"\u2718"} ${A?`Analyzed: ${Q.basename(A)}`:"Analyzed: File Not Found"}`:Ce?ie=`${A.length>0?"\u2714":"\u2718"} ${A?`Processed: ${Q.basename(A)}`:"Processed: File Not Found"}`:ie=`${Fe!=="..."?"\u2714":"\u2718"} Read: ${A?`${Q.basename(A)} \u2192 ${Fe!=="..."?`Lines ${fe} - ${Ze} of ${Fe}`:"File Not Found"}`:"File Not Found"}`}else if(_==="list_files"||_==="read_folder"){let A=_==="list_files"?"List":"Browsed",z=I(K.args).path||null,ae=I(K.args).recurse||1;ie=`${z?"\u2714":"\u2718"} ${A}: ${z?`${z==="."?`./${ae>1?"*":""}`:`${z.replaceAll("\\","/")}${ae>1?`${z.endsWith("/")?"*":"/*"}`:`${z.endsWith("/")?"":"/"}`}`}`:"No Folder Selected"}`}else if(_==="write_file"||_==="update_file"){let A=_==="write_file"?"Created":"Edited",z=I(K.args).path||null;ie=`${z?"\u2714":"\u2718"} ${A}: ${z.replaceAll("\\","/")||"No File Changes"}`}else if(_==="write_pdf"){let A=I(K.args).path||null;ie=`${A?"\u2714":"\u2718"} Generated: ${A.replaceAll("\\","/")||"No PDF Generated"}`}else if(_==="write_docx"){let A=I(K.args).path||null;ie=`${A?"\u2714":"\u2718"} Generated: ${A.replaceAll("\\","/")||"No Docx Generated"}`}else if(_==="file_map"){let A=I(K.args).path;ie=`${A?"\u2714":"\u2718"} Indexed: ${A.replaceAll("\\","/")?""+A:"File Not Found"}`}else if(_.toLowerCase()==="search_keyword"||_.toLowerCase()==="todo")ie="";else if(_.toLowerCase()==="generate_image"){let{path:A,outputPath:z,output:ae}=I(K.args);ie=`\u2714 Generated: ${A||z||ae||"generated_image.png"}`}else if(_==="invoke_sync"||_==="InvokeSync"){let A=xs(_,K.args);ie=`\u2714 Called Generalist${A?`: ${A}`:""}`}else if(_==="Invoke"||_==="InvokeAsync"||_==="invoke"){let A=xs(_,K.args);ie=`\u2714 Started Generalist${A?`: ${A}`:""}`}else if(_==="get_progress"||_==="GetProgress"){let A=xs(_,K.args);ie=`\u2714 Checked${A?`: ${A}`:""}`}else if(_==="cancel"){let A=xs(_,K.args);ie=`\u{1F6C7} Cancelled${A?`: ${A}`:""}`}else if(_==="steer"||_==="Steer"){let A=xs(_,K.args);ie=`\u2714 Steered${A?`: ${A}`:""}`}else if(_==="EmergencyRollback"){let{method:A}=I(K.args);ie=A==="forceRevert"?"":"\u2714 Rollback Point Checked"}else if(_==="await"||_==="Await"){let{time:A,timeout:z}=I(K.args),ae=parseFloat(z||A)||0;ae||(ae=120);let ge=Me=>{if(Me>=60){let be=Math.floor(Me/60),ee=Me%60;return`${be}m${ee>0?` ${ee}s`:""}`}return`${Me}s`},we=["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"];ie=`\u2714 ${we[Math.floor(Math.random()*we.length)]} \u2192 ${ge(ae)}`}else _==="Answer"||_==="answer"?ie="\u2714 Resolved Sub-Agent Query":_==="exec_command"||_==="ask"?ie="":ie=`Executed: ${K.toolName}`;if(yield*ss(),_==="exec_command"){let{command:A}=I(K.args);if(A&&t.systemSettings&&t.systemSettings.allowExternalAccess===!1){let z=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],ae=Q.resolve(process.cwd()).substring(0,3).toLowerCase(),ge=ee=>{let fe=[],le="",Fe=null;for(let Ze=0;Ze<ee.length;Ze++){let xe=ee[Ze];Fe?(xe===Fe&&(Fe=null),le+=xe):xe==='"'||xe==="'"?(Fe=xe,le+=xe):xe==="&"&&ee[Ze+1]==="&"||xe==="|"&&ee[Ze+1]==="|"?(le.trim()&&(fe.push(le.trim()),le=""),Ze++):xe===";"||xe==="|"||xe==="&"?le.trim()&&(fe.push(le.trim()),le=""):le+=xe}return le.trim()&&fe.push(le.trim()),fe},we=ee=>{let fe=[],le="",Fe=null;for(let Ze=0;Ze<ee.length;Ze++){let xe=ee[Ze];Fe?(xe===Fe&&(Fe=null),le+=xe):xe==='"'||xe==="'"?(Fe=xe,le+=xe):/\s/.test(xe)?le&&(fe.push(le),le=""):le+=xe}return le&&fe.push(le),fe},He=ee=>{let fe=ee.replace(/^['"]|['"]$/g,"").trim();return!fe||process.platform==="win32"&&/^\/[a-zA-Z0-9?]+$/.test(fe)?!1:z.some(le=>{if(le.source==="[a-zA-Z]:[\\\\\\/]"){let Fe=fe.match(/[a-zA-Z]:[\\\/]/i);return Fe&&Fe[0].toLowerCase()!==ae}return le.test(fe)})};if(ge(A).some(ee=>{let fe=we(ee);if(fe.length===0)return!1;let le=fe[0].replace(/^['"]|['"]$/g,"").toLowerCase();if(["echo","printf","write-output"].includes(le)){let Ze=!1;return fe.some(xe=>{let Pe=xe.replace(/^['"]|['"]$/g,"");if(Pe===">"||Pe===">>"||Pe==="<")return Ze=!0,!1;if(Pe.startsWith(">")||Pe.startsWith("<")){let ot=Pe.replace(/^[><]+/,"");return He(ot)}return Ze?(Ze=!1,He(xe)):!1})}return fe.some(Ze=>He(Ze))})){let ee='Access Denied. Prohibited from accessing external directories while "External Workspace Access" is disabled.';t.onExecStart&&t.onExecStart(A||"No Command"),yield{type:"exec_start"},await new Promise(fe=>setTimeout(fe,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${ee}`),await new Promise(fe=>setTimeout(fe,50)),t.onExecEnd&&t.onExecEnd(),Z.push({role:"user",text:`[TOOL RESULT]: ERROR: ${ee}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${ee}`},je++;continue}}t.onExecStart&&t.onExecStart(A||"No Command"),yield{type:"exec_start"}}let bn=I(K.args),is=bn.path||bn.targetPath||null;if(is){let A=t.systemSettings&&t.systemSettings.allowExternalAccess===!1,z=Q.resolve(is),ae=Q.resolve(process.cwd());if(A&&!z.startsWith(ae)){let ge="Access Denied. You are not allowed to access files outside the current workspace.";if(_==="write_file"||_==="update_file"){let He=`\u2718 ${_==="write_file"?"Write Canceled":"Edit Canceled"}: ${bn.path||"..."}`,Me=115;process.stdout.isTTY&&(Me=process.stdout.columns-5||120);let be=Math.min(He.length+4,Me),ee=`${He.padEnd(be-2).substring(0,be-2)}`;yield{type:"visual_feedback",content:gn(`${Be?`
|
|
657
|
-
`:""}${ee}
|
|
658
|
-
`)},Be=!1}Z.push({role:"user",text:`[TOOL RESULT]: ERROR: ${ge}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${ge}`},je++;continue}}if(t.onToolApproval&&(_==="write_file"||_==="update_file"||_==="exec_command")){let z=t.systemSettings||{},ae=z.autoExec,ge=null,we=!1,He=!1,Me=!1;if(_==="exec_command"){let{command:Pe}=I(K.args),ot=(Pe||"").trim(),Ce=(Et,Yt)=>{if(!Yt)return!1;let ln=Yt.split(",").map(Vt=>Vt.trim().toLowerCase()).filter(Boolean),it=Et.toLowerCase();return ln.some(Vt=>it.startsWith(Vt))},ze=Ce(ot,z.alwaysAskCommands),Se=Ce(ot,z.autoApproveCommands);if(He=Ce(ot,z.autoDisallowCommands),ze?we=!0:(Se||z.autoApproveGit&&/^git\s+commit\b/i.test(ot))&&(ge="allow"),!we&&!ge){if(z.networkAccess===!1){let Yt=ot.trim().replace(/\s+/g," ").replace(/^['"]+|['"]+$/g,"").toLowerCase().split(" "),it=Yt[0].split("/").pop().split("\\").pop().replace(/\.exe$/,""),Vt=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"]),rt=!1;Vt.has(it)&&(rt=!0);let ct=Sn=>Yt.slice(1).some(kn=>Sn.includes(kn)),At=Sn=>{let kn=Yt.findIndex(Mn=>Sn.includes(Mn)),ks=Yt.findIndex(Mn=>["run","exec","test"].includes(Mn));return kn!==-1&&!(ks!==-1&&ks<kn)};it==="git"&&ct(["clone","pull","push","fetch"])&&(rt=!0),it==="go"&&ct(["get","install"])&&(rt=!0),it==="npm"&&At(["install","i","update","add"])&&(rt=!0),it==="yarn"&&At(["add","install","upgrade"])&&(rt=!0),it==="pnpm"&&At(["add","install","update"])&&(rt=!0),it==="bun"&&At(["add","install","update"])&&(rt=!0),it==="deno"&&ct(["install","add"])&&(rt=!0),it==="pip"&&ct(["install","download"])&&(rt=!0),it==="pip3"&&ct(["install","download"])&&(rt=!0),it==="cargo"&&ct(["install","add"])&&(rt=!0),["bash","sh","zsh","fish"].includes(it)&&ct(["-c"])&&(rt=!0),it==="cmd"&&ct(["/c"])&&(rt=!0),rt&&(ge="deny",Me=!0)}!ge&&He&&(ge="deny")}!we&&!ge&&ae&&(ge="allow")}else ae&&(ge="allow");let be=ge,ee="";ge==="deny"&&(Me?ee="network":He?ee="settings":ee="prohibited");let fe=!1,le="",Fe=[],Ze=0,xe=!1;if(!be){if(_==="write_file"||_==="update_file")try{let Ce=I(K.args),{path:ze}=Ce;if(ze){let Se=Q.resolve(process.cwd(),ze),Et=ct=>ct?ct.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,At=>At.toUpperCase()):"",Yt=Et(Se),ln="",it=!1,Vt=await gs(),rt=Et(Vt?.file_focused);if(Vt&&rt===Yt&&Vt.full_content?(ln=Vt.full_content,it=!0):ve.existsSync(Se)&&(ln=ve.readFileSync(Se,"utf8"),it=!0),le=ln,await ft.recordFileChange(Se,ln),it){let ct=ln;if(_==="write_file")ct=Ce.content||Ce.newContent||"";else{let{patchPairs:At,allowMultiple:Sn,error:kn}=Co(Ce);if(kn){let $t=`[TOOL RESULT]: ERROR: ${kn}`;Z.push({role:"user",text:$t}),await It("toolFailure"),t.onToolResult&&t.onToolResult("failure",_),yield{type:"tool_result",content:$t,toolName:_},je++;continue}let ks=Ce.allowMultiple!==void 0?Ce.allowMultiple===!0||String(Ce.allowMultiple).toLowerCase()==="true":Sn;Ze=At.length;let Mn=_o(ln,At,{allowMultiple:ks});ct=Mn.content,Fe=Mn.results;let po=Fe.filter($t=>$t.success),vt=Fe.filter($t=>!$t.success);if(po.length===0){let $t=`[TOOL RESULT]: ERROR: Failed to apply patches to [${Q.basename(Se)}].
|
|
659
|
-
${vt.map(Hs=>` \u2022 ${Hs.error}`).join(`
|
|
660
|
-
`)}`,Ts=`\u2714 Edited: ${Q.basename(Se.replaceAll("\\","/"))}`,js=115;process.stdout.isTTY&&(js=process.stdout.columns-5||120);let Rs=Math.min(Ts.length+4,js),mo=`${Ts.padEnd(Rs-2).substring(0,Rs-2)}`;yield{type:"visual_feedback",content:gn(`${Be?`
|
|
661
|
-
`:""}${mo}`)},Be=!1,Z.push({role:"user",text:$t}),await It("toolFailure"),t.onToolResult&&t.onToolResult("failure",_),yield{type:"tool_result",content:$t,toolName:_},je++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${Q.basename(Se)}`},Wi(Se,ln,ct),fe=!0,await new Promise(At=>setTimeout(At,50))}else if(_==="write_file"){let ct=Ce.content||Ce.newContent||"",At=ct.endsWith(`
|
|
662
|
-
`)?ct:ct+`
|
|
663
|
-
`;ve.existsSync(Se)||(xe=!0,ve.mkdirSync(Q.dirname(Se),{recursive:!0}),ve.writeFileSync(Se,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${Q.basename(Se)}`},Wi(Se,"",At),fe=!0,await new Promise(Sn=>setTimeout(Sn,50))}}}catch(Ce){console.error("Simulation/Diff Error:",Ce)}let Pe=null;Ui(Ce=>{Pe=Ce});let ot=t.onToolApproval;if(be=await new Promise(async Ce=>{let ze=setInterval(()=>{Pe&&(No.onIDEApproval&&No.onIDEApproval(Pe),clearInterval(ze),Ce(Pe))},100);try{let Se=await ot(_,K.args);clearInterval(ze),Ce(Se)}catch{clearInterval(ze),Ce("deny")}}),Ui(null),_==="write_file"||_==="update_file"){let{path:Ce}=I(K.args);if(Ce){let ze=Q.resolve(process.cwd(),Ce);if(ua(ze,be),be==="deny"&&xe&&ve.existsSync(ze))try{ve.unlinkSync(ze)}catch{}}}be==="deny"&&(ee="user")}if(be==="allow"&&fe&&Fo()){let{path:Pe}=I(K.args),ot=Q.resolve(process.cwd(),Pe),Ce=vt=>vt?Q.resolve(vt).replace(/\\/g,"/").toLowerCase():"",ze=await gs(),Se="";ze&&ze.file_focused&&Ce(ze.file_focused)===Ce(ot)&&ze.full_content&&(Se=ze.full_content),!Se&&ve.existsSync(ot)&&(Se=ve.readFileSync(ot,"utf8"),Se||(await new Promise(vt=>setTimeout(vt,100)),Se=ve.readFileSync(ot,"utf8")));let Et=Se.split(/\r?\n/),Yt=Et.length,ln=Buffer.byteLength(Se,"utf8"),it="";le&&(it=`Old File contents:
|
|
664
|
-
${le.split(/\r?\n/).map(($t,Ts)=>`${Ts+1} | ${$t}`).join(`
|
|
665
|
-
`)}
|
|
666
|
-
|
|
667
|
-
`);let Vt="";if(Yt<=100)Vt=Et.join(`
|
|
668
|
-
`);else{let vt=Et.slice(0,50).join(`
|
|
669
|
-
`),$t=Et.slice(-50).join(`
|
|
670
|
-
`);Vt=`${vt}
|
|
671
|
-
|
|
672
|
-
... [${Yt-100} lines truncated for history stability] ...
|
|
673
|
-
|
|
674
|
-
${$t}`}let rt="";if(_==="update_file"){let vt=Mo(le,Se,Fe,12,t?.compressToolResults||No?.systemSettings?.compressToolResults);rt=`SUCCESS: File [${Pe}] updated via IDE Companion (May have user edits). [${Fe.length}/${Ze}] blocks applied.
|
|
675
|
-
|
|
676
|
-
${vt}`}else{let vt=Se.split(/\r?\n/),$t=vt.length,Ts=Buffer.byteLength(Se,"utf8"),js="";le&&(js=`Old File contents:
|
|
677
|
-
${le.split(/\r?\n/).map((Hs,Ua)=>`${Ua+1} | ${Hs}`).join(`
|
|
678
|
-
`)}
|
|
679
|
-
|
|
680
|
-
`);let Rs="";if($t<=100)Rs=vt.join(`
|
|
681
|
-
`);else{let mo=vt.slice(0,50).join(`
|
|
682
|
-
`),Hs=vt.slice(-50).join(`
|
|
683
|
-
`);Rs=`${mo}
|
|
684
|
-
|
|
685
|
-
... [${$t-100} lines truncated] ...
|
|
686
|
-
|
|
687
|
-
${Hs}`}rt=`SUCCESS: File [${Pe}] saved via IDE Companion (May have user edits).
|
|
688
|
-
- Stats: [${$t} lines, ${(Ts/1024).toFixed(1)} KB]
|
|
689
|
-
${js}- Content Preview:
|
|
690
|
-
|
|
691
|
-
${Rs}`}let At=`${Pe?"\u2714":"\u2718"} ${_==="write_file"?"Created":"Edited"}: ${Pe.replaceAll("\\","/")||"No File Changes"}`,Sn=115;process.stdout.isTTY&&(Sn=process.stdout.columns-5||120);let kn=Math.min(At.length+4,Sn),ks=`${At.padEnd(kn-2).substring(0,kn-2)}`;yield{type:"visual_feedback",content:gn(`${Be?`
|
|
692
|
-
`:""}${ks}`)},Be=!1;let Mn=Date.now();q=Mn,yield{type:"tool_time",content:Mn-me};let po=`[TOOL RESULT]: ${rt}`;Z.push({role:"user",text:po}),rn=!0,await It("toolSuccess"),t.onToolResult&&t.onToolResult("success",_),yield{type:"tool_result",content:rt,aiContent:po,toolName:_},je++;continue}if(be==="deny"){let Pe=`Permission Denied: Prohibited ${_==="exec_command"?"Command":"file edit"}.`;if(ee==="user"?Pe="Permission Denied by User":ee==="settings"?Pe="Permission Denied by User Policy":ee==="network"?Pe="Permission Denied: Sandbox Network Access Disabled by User Policy.":ee==="prohibited"&&_==="exec_command"&&(Pe="Permission Denied: Prohibited Command in User Policy"),_==="write_file"||_==="update_file"){let Ce=`\u2718 ${_==="write_file"?"Write Cancelled":"Edit Denied"}: ${I(K.args).path.replaceAll("\\","/")||"..."}`,ze=115;process.stdout.isTTY&&(ze=process.stdout.columns-5||120);let Se=Math.min(Ce.length+4,ze),Et=`${Ce.padEnd(Se-2).substring(0,Se-2)}`,Yt=` ${" ".repeat(Se)} `;yield{type:"visual_feedback",content:gn(`${Be?`
|
|
693
|
-
`:""}${Et}
|
|
694
|
-
`)},Be=!1}_==="exec_command"&&(await new Promise(ot=>setTimeout(ot,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${Pe}`),await new Promise(ot=>setTimeout(ot,50)),t.onExecEnd&&t.onExecEnd()),Z.push({role:"user",text:`[TOOL RESULT]: DENIED: ${Pe}`}),yield{type:"tool_result",content:`[TOOL RESULT]: DENIED: ${Pe}`},await It("toolDenied"),t.onToolResult&&t.onToolResult("denied",_),je++;continue}}if(ie){let A=115;process.stdout.isTTY&&(A=process.stdout.columns-5||120);let z=Math.min(ie.length+4,A),ae=`${ie.padEnd(z-2).substring(0,z-2)}`;yield{type:"visual_feedback",content:gn(`${Be?`
|
|
695
|
-
`:""}${ae}${ie.includes("\u2714")&&(ie.includes("Created")||ie.includes("Edited"))?"":`
|
|
696
|
-
`}`)},Be=!1}if(q>0){let A=Date.now()-q,z=Math.max(0,1e3-A);z>0&&await new Promise(ae=>setTimeout(ae,z))}let Bn={chatId:d,history:n,onChunk:A=>t.onExecChunk?t.onExecChunk(A):null,onAskUser:t.onAskUser,systemSettings:t.systemSettings,mode:r,isMultiModal:fn(_e),onVisualFeedback:t.onVisualFeedback,onSubagentUpdate:t.onSubagentUpdate,onTokenChunk:t.onTokenChunk,modelName:_e,aiProvider:t.aiProvider,apiKey:t.apiKey,onUsage:t.onUsage};if(_==="write_file"||_==="update_file")try{let{path:A}=I(K.args);if(A){let z=Q.resolve(process.cwd(),A),ae=await gs();ae&&ae.file_focused===z&&ae.full_content&&(Bn.forcedContent=ae.full_content)}}catch{}Qt.push(_);let Te=await ao(_,K.args,Bn);if((_==="write_file"||_==="update_file")&&Te.startsWith("SUCCESS")){let{path:A}=I(K.args);if(A){let z=Q.resolve(process.cwd(),A);fa(z)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let jt=Date.now();q=jt,yield{type:"tool_time",content:jt-me},Zt=jt;let zt=null;if(typeof Te=="object"&&Te.binaryPart&&(zt=Te.binaryPart,Te=Te.text),_==="search_keyword"){let{keyword:A,path:z}=I(K.args),ae=typeof Te=="string"&&Te.startsWith("[GLOB]");ae&&(Te=Te.slice(6).trimStart());let ge=typeof Te=="string"&&Te.startsWith("[DIR]");ge&&(Te=Te.slice(5).trimStart());let we=0;if(Te){let Fe=Te.match(/Found (\d+) match/i);Fe&&(we=parseInt(Fe[1]))}let He=z?z.replace(/[\/\\]+$/,""):null,Me=He&&He!=="."?`"${ae?z:ge?`${He}/*`:He}"`:"./",be=`${A?"\u2714":"\u2718"} Searched: "${A||""}" in ${Me.replaceAll("\\","/")} \u2192 ${we} Match${we===1?"":"es"}`,ee=115;process.stdout.isTTY&&(ee=process.stdout.columns-5||120);let fe=Math.min(be.length+4,ee),le=`${be.padEnd(fe-2).substring(0,fe-2)}`;yield{type:"visual_feedback",content:gn(`${Be?`
|
|
697
|
-
`:""}${le}
|
|
698
|
-
`)},Be=!1}if(_==="EmergencyRollback"){let{method:A}=I(K.args);if(A==="forceRevert"){let z=0;if(Te){let be=Te.match(/Total\s*:\s*(\d+)/i);be&&(z=parseInt(be[1]))}let ge=Te&&Te.startsWith("ERROR:")?"\u2718 Emergency Rollback Failed":`\u2714 Emergency Rollback \u2192 ${z} file${z===1?"":"s"} processed`,we=115;process.stdout.isTTY&&(we=process.stdout.columns-5||120);let He=Math.min(ge.length+4,we),Me=`${ge.padEnd(He-2).substring(0,He-2)}`;yield{type:"visual_feedback",content:gn(`${Be?`
|
|
699
|
-
`:""}${Me}
|
|
700
|
-
`)},Be=!1}}if(_==="todo"){let{method:A,tasks:z,markDone:ae}=I(K.args),ge="",we=[],He=Me=>{if(!Me)return[];let be=Array.isArray(Me)?Me:[];if(be.length===0&&typeof Me=="string"){let ee=Me.trim();if(ee.startsWith("[")&&ee.endsWith("]")){let fe=ee.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);fe?be=fe.map(le=>le.slice(1,-1).replace(/\\(.)/g,"$1")):be=ee.slice(1,-1).split(",").map(le=>le.trim()).filter(Boolean)}else be=Me.split(`
|
|
701
|
-
`)}return be.filter(ee=>String(ee).trim()).map(ee=>{let fe=String(ee).trim();return fe.startsWith("- [")?fe.substring(6).trim():fe})};if(A==="create"?(ge="\x1B[32m\u2192\x1B[0m Created Plan",we=He(z).map(Me=>`\x1B[90m\u25CB\x1B[0m ${Me}`)):A==="append"?(ge="\x1B[34m\u2795\x1B[0m Added Plan",we=He(z).map(Me=>`\x1B[90m\u25CB\x1B[0m ${Me}`)):A==="get"&&(ge=ae?"\x1B[36m\u21BB\x1B[0m Updated Plan":"\x1B[35m\u2022\x1B[0m Reviewed Plan",we=(Te||"").split(`
|
|
702
|
-
`).slice(1).join(`
|
|
703
|
-
`).split(`
|
|
704
|
-
`).filter(be=>be.trim().startsWith("- [")).map(be=>{let ee=be.trim(),fe=ee.startsWith("- [x]");return`${fe?"\x1B[32m\u2714\x1B[0m":"\x1B[90m\u25CB\x1B[0m"} ${fe?"\x1B[90m":"\x1B[37m"}${ee.substring(6).trim()}\x1B[0m`})),ge&&we.length>0){let Me=[`${ge}`,...we.map(be=>` ${be}`)].join(`
|
|
705
|
-
`);yield{type:"visual_feedback",content:gn(`${Be?`
|
|
706
|
-
`:""}${Me}
|
|
707
|
-
`)},Be=!1}}_==="exec_command"&&t.onExecEnd&&(await new Promise(A=>setTimeout(A,800)),t.onExecEnd());let Cn=Te&&Te.startsWith("DENIED:");Te&&!Te.startsWith("ERROR:")&&!Cn?(await It("toolSuccess"),t.onToolResult&&t.onToolResult("success",_)):Cn||(await It("toolFailure"),t.onToolResult&&t.onToolResult("failure",_));let Ht=(Te||"").toString().replaceAll("[UI_CONTEXT]","");Ht.includes("[[VERIFIED]]")&&(Ht=Ht.replace(/\[\[VERIFIED\]\][\s\S]*?\[\[\/VERIFIED\]\]/g,`[SYSTEM NOTE]: Patch Block matched & applied successfully. Large Block omitted to conserve context.
|
|
708
|
-
`));let _n;if(Ht.startsWith("[[SAME]]")){let z=Ht.replace(/^\[\[SAME\]\]\s*\r?\n?/,"").split(/\r?\n/),ae=z.filter(we=>we.startsWith("SUCCESS:")||we.trim().startsWith("- Stats:"));_n=`[TOOL RESULT]: ${ae.length>0?ae.join(`
|
|
709
|
-
`):z.slice(0,2).join(`
|
|
710
|
-
`)}
|
|
711
|
-
[SYSTEM NOTE]: Content verified and persisted to disk. Full preview omitted to conserve context.`}else _n=`[TOOL RESULT]: ${Ht}`;Z.push({role:"user",text:_n,binaryPart:zt}),rn=!0;let $e=`[TOOL RESULT]: ${Te.replaceAll(`[[VERIFIED]]
|
|
712
|
-
`,"").replaceAll(`
|
|
713
|
-
[[/VERIFIED]]`,"")||""}`;(_==="view_file"||_==="web_scrape"||_==="file_map")&&($e=`[TOOL RESULT]: ${ie} (Context Locked for UI Clarity)`),yield{type:"tool_result",content:$e,aiContent:_n,binaryPart:zt,toolName:_},_==="memory"&&Te.includes("SUCCESS")&&(yield{type:"memory_updated"}),je++}if(u==="Google"&&xn&&Date.now()-qo>=150){yield*ss();let K=Us(xn);for(let me of K)yield me;xn="",qo=Date.now()}}P.usageMetadata&&(Rn=P.usageMetadata),Rn&&(yield{type:"liveTokens",content:Rn.totalTokenCount})}if(ue&&(ue=!1,Wt?qe+="</think>":(ce+="</think>",u==="Google"?xn+="</think>":yield{type:"text",content:"</think>"})),Wt&&qe.length>0){let P=0,te=Math.min(tt.length,qe.length);for(let G=te;G>0;G--)if(tt.endsWith(qe.substring(0,G))){P=G;break}let U=qe.substring(P);if(U){let ke=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(tt)?U.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):U.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(ke)if(ce+=ke,u==="Google")xn+=ke;else{yield*ss();let pe=Us(ke);for(let de of pe)yield de}}Wt=!1,qe=""}if(yield*ss(),Ot)break;let Ws=(ce||"").trim(),La=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(Ws.toLowerCase())||/\[\[END\]\]/i.test(Ws.toLowerCase()),Pa=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(Ws.toLowerCase()),Da=Z.length>0||Bt!==null,Ko=Ws.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/gi,"").trim(),Fa=/(\p{Emoji_Presentation}|\p{Extended_Pictographic})$/u.test(Ko),Na=/([.!?"'*_`|\]\)”’~~]+|\s|`{3}|[\u200B-\u200D\uFEFF])$/u.test(Ko.trim()),Ba=/[.!?}"'`’“”]$|```$/s.test(Ko)||Na||Fa;!La&&!Pa&&!Da&&Ws.length>0,Qe=!0,await It("agent",u)}catch(Ee){if(Ot){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
|
|
714
|
-
|
|
715
|
-
\x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(String(Ee).includes("Incomplete JSON segment at the end")){ue&&(ue=!1,Wt?qe+="</think>":(ce+="</think>",yield{type:"text",content:"</think>"})),Qe=!0,await It("agent",u);break}if(ue&&(ue=!1,Wt?qe+="</think>":ce+="</think>"),Wt&&qe.length>0){let ns=0,tn=Math.min(tt.length,qe.length);for(let Pt=tn;Pt>0;Pt--)if(tt.endsWith(qe.substring(0,Pt))){ns=Pt;break}let Lt=qe.substring(ns);if(Lt){let an=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(tt)?Lt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):Lt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");an&&(ce+=an)}Wt=!1,qe=""}let ne=Ee instanceof Error?(()=>{try{return JSON.parse(JSON.parse(Ee.message).error.message).error.message}catch{return String(Ee)}})():String(Ee),nt=new Date().toLocaleString(),_t=Q.join(cn,"agent");ve.existsSync(_t)||ve.mkdirSync(_t,{recursive:!0}),ve.appendFileSync(Q.join(_t,"error.log"),`ERROR [${nt}]: ${ne}
|
|
716
|
-
|
|
717
|
-
----------------------------------------------------------------------
|
|
718
|
-
|
|
719
|
-
`);let en=Ee.status||Ee.statusCode||Ee.code;if(!(en&&(en>=500&&en<600||en===408||en===429)||!en&&(/status[ :]+(5\d\d|408|429)/i.test(String(Ee))||/code[ :]+(5\d\d|408|429)/i.test(String(Ee))||/(500|503|408|429)/.test(String(Ee))))){if(We<yn-3)throw Ee;yield{type:"text",content:ne},yield{type:"status",content:"Error Occured"}}if(ce.trim().length>0||Ve>1)if(Ve<=yn){Ve++;let ns=Math.min(1e3*Math.pow(2,Ve-1),24e3);if(ce.trim().length>0){k.push({role:"agent",text:ce});let tn=`[system]
|
|
720
|
-
- seamless continuation: resume immediately. pick up from last words with zero gap/disruption
|
|
721
|
-
- no repetition: do not repeat any text already written
|
|
722
|
-
- no re-think: do not restart or open <think> if reasoning already started. continue the thinking and close thinking block </think> before chat output
|
|
723
|
-
- mid-tool safety: if cutoff was mid-tool call, restart that tool call from start
|
|
724
|
-
- stealth: do not mention/apologize for cutoff [/system]`;Z.length>0?Z.forEach((Lt,Pt)=>{Pt===Z.length-1?k.push({...Lt,text:`${Lt.text}
|
|
725
|
-
|
|
726
|
-
${tn}`}):k.push(Lt)}):k.push({role:"user",text:tn}),tt+=ce}for(let tn=ns/1e3;tn>0&&!Ot;tn--)yield{type:"status",content:`Error Occured. Recovering Stream (${Ve}/${yn}) [Retrying in ${tn.toFixed(0)}s]...`},await new Promise(Lt=>setTimeout(Lt,1e3));yield{type:"status",content:"Error Occured. Recovering Stream..."}}else throw new Error(`Stream collapsed too many times. (Failed to resolve ${yn} times)
|
|
727
|
-
Error log can be found in \`/export logs\``);else if(We<=yn){We++,Ve=1,tt="";let ns=Math.min(1e3*Math.pow(2,We-1),32e3),tn=.8+Math.random()*.4,Lt=Math.round(ns*tn);Qn=!0,yield{type:"status",content:`Trying to reach ${e} (${We}/${yn}) [Retrying in ${(Lt/1e3).toFixed(0)}s]`};for(let Pt=Lt/1e3;Pt>0&&!Ot;Pt--)yield{type:"status",content:`Trying to reach ${e} (${We}/${yn}) [Retrying in ${Pt.toFixed(0)}s]`},await new Promise(an=>setTimeout(an,1e3));yield{type:"status",content:`Trying to reach ${e}`}}else throw new Error(`Model ${e} cannot be reached. (Failed ${yn} times)
|
|
728
|
-
Error log can be found in \`/export logs\``)}}if(Rn){let ue=Rn.totalTokenCount||0,Ee=Rn.cachedContentTokenCount||0,ne=(Rn.candidatesTokenCount||0)+(Rn.thoughtsTokenCount||0);await Gt("tokens",ue,u,_e),Ee>0&&await Gt("cachedTokens",Ee,u,_e),ne>0&&await Gt("candidateTokens",ne,u,_e),yield{type:"usage",content:Rn}}rr.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=ka(ce),$n=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(es.toLowerCase())||/\[\[END\]\]/i.test(es.toLowerCase())||!0,Ec=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(es.toLowerCase()),$c=je>0;yield{type:"status",content:"Thinking"};let va=wc(ce,/(\[\s*(turn\s*:)?\s*(continue|finish)\s*\]|\[\[END\]\])/gi,"").trim(),ts=($n||Z.length===0)&&!Ut&&!wn&&!En;if(ts=Z.length===0?ts:!1,ts=Zn||uo?!1:ts,ce&&ce.trim().endsWith('")]')&&Z.length===0&&(ts=!1),ts){let ue=rr.join(`
|
|
729
|
-
`),Ee=ue.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").trim();yield{type:"interactive_turn_finished",data:{agentText:T,fullAgentTextRaw:ue,history:[...k],needTitle:b}},k.length>0&&k[k.length-1].role==="agent"?k[k.length-1].text=Ee:k.push({role:"agent",text:Ee}),k.forEach(ne=>{if(ne.role==="user"&&ne.text&&(ne.text=ne.text.replace(/\n\[COMPILE ERROR\][\s\S]*?\[\/ERROR\]/g,""),ne.text=ne.text.replaceAll(`
|
|
730
|
-
|
|
731
|
-
[system] user question. resolve this specific query within '[ANSWER] ... [/ANSWER]' concisely, naturally [/system]
|
|
732
|
-
`,"").replaceAll(`[system] user question. resolve this specific query within '[ANSWER] ... [/ANSWER]' concisely, naturally
|
|
733
|
-
**strictly follow thinking policy as high priority. do not start a response without <think>...</think>** [/system]
|
|
734
|
-
`,"").replaceAll(`[system] **strictly follow thinking policy as high priority. do not start a response without <think>...</think>** [/system]
|
|
735
|
-
`,"").replaceAll(/\n\[system\] WARNING, Turn Limit Impending: Step \d+\/\d+\. Wrap up quickly\/prompt user to continue & use \[\[END\]\] quickly\. \[\/system\]/g,""),ne.text=ne.text.replaceAll(/\n\[system\] File Changes:\n(?:\* .+ \(created|modified|deleted\)\n)*\[\/system\]/g,""),(u==="Mistral"||u==="Google"&&e?.toLowerCase().startsWith("gemma"))&&ne.text.startsWith("[TOOL RESULT]"))){let _t=`
|
|
736
|
-
[system] Tool result received. Analyze output and proceed with your turn [/system]`,en=`
|
|
737
|
-
[system] Tool result received. Analyze output and proceed with your turn. **strictly follow thinking policy. do not start a response without <think>...</think>** [/system]`;ne.text=ne.text.replaceAll(en,"").replaceAll(_t,"").trim()}}),yield{type:"status",content:"[end]"}}if(ts)break;let Ia=va.trim()||"*Working...*";if(k.push({role:"agent",text:Ia}),Z.length>0||rn){if(Z.length>0){let ue=Z.map(_t=>_t.text).join(`
|
|
738
|
-
|
|
739
|
-
`),ne=(ce.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/gi,"").match(/\[tool:functions/g)||[]).length;if(Z.length<ne){ue+=`
|
|
740
|
-
|
|
741
|
-
[SYSTEM] Only ${Z.length} out of ${ne} attempted tool calls were executed. Verify proper schema compliance & try failed calls again [/SYSTEM]`;let _t=ne-Z.length;for(let en=0;en<_t;en++)await It("toolFailure")}let nt=Z.find(_t=>_t.binaryPart)?.binaryPart||null;k.push({role:"user",text:ue,binaryPart:nt})}}else uo||Zn?(k.push({role:"user",text:"[SYSTEM] Failed to execute some tools. Verify proper schema compliance & try again [/SYSTEM]"}),await It("toolFailure")):k.push({role:"user",text:`[SYSTEM] ${wn&&!Ut?"STUTTERING DETECTED by Internal System. Re-calibrate your response & proceed.":`${Ut?" OVER THINKING":" LOOP"} DETECTED by Internal System${Ut?" for current EFFORT_LEVEL":""}. ${Ut?"If you have planned the task, prioritize execution/output":"If you have finished your task provide a simple summary and end"}`} [/SYSTEM]`}),Ut=!1,wn=!1,En=!1;l?.advanceRollback&&await Kn.recordTurnDelta(d,H+1,Qt),uo=je>0||rn}}catch(C){let O=(C instanceof Error?(()=>{try{return JSON.parse(JSON.parse(C.message).error.message).error.message}catch{return C.message||String(C)}})():String(C)).replace(/^(Error:\s*)+/i,""),v=new Date().toLocaleString(),L=Q.join(cn,"agent");yield{type:"text",content:`\u2726 CRITICAL ERROR: ${O.includes("fetch failed")?"Failed to Connect. Check your Internet Connection or Wait a moment":O}
|
|
742
|
-
\u2800`},ve.existsSync(L)||ve.mkdirSync(L,{recursive:!0}),ve.appendFileSync(Q.join(L,"error.log"),`CRITICAL ERROR [${v}]: ${C}
|
|
743
|
-
|
|
744
|
-
----------------------------------------------------------------------
|
|
745
|
-
|
|
746
|
-
`),typeof flushGoogleBuffer=="function"&&(yield*flushGoogleBuffer()),yield{type:"tool_result",content:`ERROR: [INTERNAL CRITICAL] ${O}`}}finally{$&&(clearInterval($),$=null),typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),await ft.commitTransaction(),l?.advanceRollback&&await Kn.cleanup(d),await gs()}yield{type:"status",content:null}},gm=async(e,n,t=null,o=null,s=50,i=null,a=!1)=>{let r=await Ft(),h={...r,...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(":","-")}`,p=(C=>{if(!C)return null;let k=C.toLowerCase();return k==="google"?"Google":k==="deepseek"?"DeepSeek":k==="openrouter"?"OpenRouter":k==="nvidia"?"NVIDIA":k==="mistral"?"Mistral":k==="ollama"?"Ollama":null})(c),g=h?.systemSettings?.CustomSubAgent?h?.systemSettings?.SubAgentModel:null,y=h?.systemSettings?.CustomSubAgent?h?.systemSettings?.SubAgentProvider:null,m=null;if(g==="ENV"?(m=d,d&&p&&(h.aiProvider=p)):g&&g!=="Default"?(m=g,y&&(h.aiProvider=y)):d&&p&&(h.aiProvider=p),h.aiProvider){let C=await Jo(h.aiProvider);C&&(h.apiKey=C)}let w=C=>{if(!C||typeof C!="string")return{allowed:!0};let k=[/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 O of k)if(O.test(C))return{allowed:!1,reason:`Blocked potentially destructive or unsafe command pattern: "${O.source}"`};return{allowed:!0}},x=t||m||n?.modelName||n?.activeModel||r.activeModel,S=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",R=`-- TOOL DEFINITIONS (path = relative to CWD, path separator: '/') --
|
|
747
|
-
To use tools, must output exactly '[tool:functions.ToolName(arg1="value1")]' structured string in chat response \u2190 no exception
|
|
748
|
-
Tool Rules:
|
|
749
|
-
- JSON escape literal escape sequences in tool arguments
|
|
750
|
-
- Same file, multiple edits? ONE PatchFile (\u226415 blocks) \u2190 Priority
|
|
751
|
-
- Tool denied? Ask for guidance \u2190 mandatory
|
|
752
|
-
- Need text or huge file? CodeSearch > Full Read
|
|
753
|
-
- Avoid unnecessary large file chunk reads
|
|
754
|
-
- Dont hallucinate tool results, verify, fix errors
|
|
755
|
-
- Stuck on syntax error? Tell user > waste time
|
|
756
|
-
- ONLY valid tools and syntax defined below are allowed
|
|
757
|
-
- Stuck on syntax error? Tell user > Time waste
|
|
758
|
-
|
|
759
|
-
# Provided Tools
|
|
760
|
-
**Communication Tools**
|
|
761
|
-
- [tool:functions.Ask(question="...", optionA="title::description", ...MAX4)]. Ambiguity, path divergence, security risk. Ask, dont finish/guess. Keep titles short
|
|
762
|
-
${a?'- [tool:functions.AskMain(question="...")]. Communicate with PARENT/MAIN AGENT. When clarification/decision is needed for a task':""}
|
|
763
|
-
|
|
764
|
-
**Web Tools**
|
|
765
|
-
- [tool:functions.WebSearch(query="...", aiMode="bool", limit="integer 3-10 aiMode: exclude")]. Proactive use for unknown info/docs. aiMode: LLM search
|
|
766
|
-
- [tool:functions.WebScrape(url="...")]. Proactive use for specific webpage/docs/api
|
|
767
|
-
|
|
768
|
-
**Workspace Tools**
|
|
769
|
-
- [tool:functions.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
|
|
770
|
-
- [tool:functions.ReadFolder(path="...", recurse="int 1-3")]. Minimize recursion
|
|
771
|
-
- [tool:functions.ReadFile(path="...", startLine="int", endLine="int")]
|
|
772
|
-
- [tool:functions.PatchFile(path="...", allowMultiple="bool, default: false", searchContent1="search string OR ^LINE:start..end$", newContent1="...", ...MAX15)]. Target minimal searchContent. Line Ranges must for large searchContent and escape sequences. ^...$ must for line ranges
|
|
773
|
-
- [tool:functions.WriteFile(path="...", content="...")]. Creates/Overwrites. File Exist? PatchFile > WriteFile. VERIFY IMPORTS
|
|
774
|
-
- [tool:functions.Run(command="...")]. Runs ${S==="Windows"?jn()?"powershell":"windows CMD":"bash"} command. Destructive/Irreversible ops \u2192 Ask user`.trim(),E=`=== START SYSTEM PROMPT ===
|
|
775
|
-
You are a subagent helping the main FluxFlow CLI agent
|
|
776
|
-
Your task is: "${e}"
|
|
777
|
-
|
|
778
|
-
${R.trimEnd()}
|
|
779
|
-
|
|
780
|
-
-- THINKING GUIDANCE --
|
|
781
|
-
NO EXPLICIT THINKING REQUIRED. FOCUS ON TASK COMPLETION
|
|
782
|
-
Keep main focus on tools and task, not chatting
|
|
783
|
-
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
|
|
784
|
-
|
|
785
|
-
CWD: ${process.cwd()}
|
|
786
|
-
Current Time: ${f}
|
|
787
|
-
=== END SYSTEM PROMPT ===`,b=[{role:"user",text:`Complete this task: ${e}`}],T=0,$="";for(;T<s;){if(Ot){if(n?.taskId&&typeof Ye<"u"){let B=Ye.find(W=>W.id===n.taskId);B&&(B.status="cancelled")}throw i&&i("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}if(n?.taskId&&typeof Ye<"u"){let B=Ye.find(W=>W.id===n.taskId);if(B&&B.status==="cancelled")throw i&&i("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}let C=b.map(B=>({role:B.role==="user"?"user":"model",parts:[{text:B.text}]}));i&&i(`[Subagent Turn ${T+1}]...`);let v=((await Bo(h,x,C,E,"Fast")).text||"").replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/gi,"").trim();$=v,i&&i(`[Subagent Response]
|
|
788
|
-
${v}
|
|
789
|
-
`),b.push({role:"agent",text:v});let L=Wo(v);if(L.length===0)break;let N=L.filter(B=>B.toolName.toLowerCase()==="askmain"||B.toolName.toLowerCase()==="ask_main"),j=!1,V="";for(let B of L){if(Ot){if(n?.taskId&&typeof Ye<"u"){let M=Ye.find(F=>F.id===n.taskId);M&&(M.status="cancelled")}throw new Error("Subagent task was cancelled.")}if(n?.taskId&&typeof Ye<"u"){let M=Ye.find(F=>F.id===n.taskId);if(M&&M.status==="cancelled")throw new Error("Subagent task was cancelled.")}let W=B.toolName.toLowerCase();if(W==="askmain"||W==="ask_main"){if(j)continue;j=!0;let M="";if(N.length===1?M=I(N[0].args).question||N[0].args:M=N.map((F,Y)=>{let J=I(F.args);return`Q${Y+1}: ${J.question||F.args}`}).join(`
|
|
790
|
-
`),n.onAskMain){i&&i(`[Executing Tool] AskMain("${M}")...`);let F=await n.onAskMain(M);i&&i(`[Tool Result]
|
|
791
|
-
Answer from Main Agent: ${F}
|
|
792
|
-
`),V+=`[TOOL RESULT for AskMain]: Answer from Main Agent: ${F}
|
|
793
|
-
|
|
794
|
-
`,await It("toolSuccess")}else V+=`[TOOL RESULT for AskMain]: ERROR: Main agent communication channel not available.
|
|
795
|
-
|
|
796
|
-
`;continue}if(!(o?o.some(M=>M.toLowerCase()===W):!0)){let M=`ERROR: Tool [${B.toolName}] is not in the allowed tools list for this subagent.`;i&&i(`[Blocked Tool Call] ${B.toolName} - not allowed
|
|
797
|
-
`),V+=`${M}
|
|
798
|
-
|
|
799
|
-
`;continue}if(W==="exec_command"||W==="execcommand"||W==="run"){let M=I(B.args).command||"",F=w(M);if(!F.allowed){let Y=`ERROR: [SECURITY RESTRICTION] Subagent execution blocked command: ${F.reason}`;i&&i(`[Blocked Command] ${M} - ${F.reason}
|
|
800
|
-
`),V+=`${Y}
|
|
801
|
-
|
|
802
|
-
`;continue}}let Re="";if(W==="web_search"||W==="websearch")Re=`\u2714 \x1B[95mSearched\x1B[0m: ${I(B.args).query||""}`;else if(W==="web_scrape"||W==="webscrape")Re=`\u2714 \x1B[95mScraped\x1B[0m: ${I(B.args).url||""}`;else if(W==="search_keyword"||W==="searchkeyword"||W==="codesearch"||W==="code_search"){let M=I(B.args),F=M.keyword||"",Y=M.path||"";Re=`${F?"\u2714":"\u2718"} \x1B[95mSearched\x1B[0m: ${F||"No Query"}${Y?` \u2192 ${Y.replaceAll("\\","/")}`:""}`}else if(W==="view_file"||W==="viewfile"||W==="readfile")Re=`\u2714 \x1B[95mRead\x1B[0m: ${(I(B.args).path||"").replaceAll("\\","/")}`;else if(W==="list_files"||W==="read_folder"||W==="readfolder"){let M=I(B.args).path||null,F=I(B.args).recurse||0;Re=`${M?"\u2714":"\u2718"} \x1B[95mBrowsed\x1B[0m: ${M?`${M.replaceAll("\\","/")}${F>0?`${M.endsWith("/")?`*${F}`:`/*${F}`}`:`${M.endsWith("/")?"":"/"}`}`:""}`}else if(W==="write_file"||W==="writefile"){let M=I(B.args).path||null;Re=`${M?"\u2714":"\u2718"} \x1B[95mCreated\x1B[0m: ${M?`${M.replaceAll("\\","/")}`:"No File Changes"}`}else if(W==="update_file"||W==="updatefile"||W==="patchfile"||W==="patch_file"||W==="patchfile"||W==="updatefile"){let M=I(B.args).path||null,F=I(B.args).content||null;Re=`${M?"\u2714":"\u2718"} \x1B[95mEdited\x1B[0m: ${M?`${M.replaceAll("\\","/")}`:"No File Changes"}`}else if(W==="exec_command"||W==="execcommand"||W==="run"){let M=I(B.args).command||null;Re=`${M?"\u2714":"\u2718"} \x1B[95mExecuted\x1B[0m: ${M?M.slice(0,100)+(M.length>100?"...":""):"No Command"}`}else if(W==="file_map"||W==="filemap"){let M=I(B.args).path||"";Re=`${M?"\u2714":"\u2718"} \x1B[95mIndexed\x1B[0m: ${M?`${M.replaceAll("\\","/")}`:"File Not Found"}`}else if(W==="await"){let{time:M}=I(B.args),F=parseFloat(M)||0;F<10&&(F=10),F>180&&(F=180),Re=`\u2714 \x1B[95mAwaiting\x1B[0m \u2192 ${(J=>{if(J>=60){let Ne=Math.floor(J/60),De=J%60;return`${Ne}m${De>0?` ${De}s`:""}`}return`${J}s`})(F)}`}else{let M=qi[W]||B.toolName,F=xs(W,B.args);Re=`\u2714 \x1B[95m${M}\x1B[0m${F?`: ${F}`:""}`}n.onVisualFeedback&&Re&&n.onVisualFeedback(Re),i&&i(`[Executing Tool] ${B.toolName}(${B.args})...`);try{let M=await ao(B.toolName,B.args,{...n,mode:"Flux"});if(i&&i(`[Tool Result]
|
|
803
|
-
${M}
|
|
804
|
-
`),V+=`[TOOL RESULT for ${B.toolName}]: ${M}
|
|
805
|
-
|
|
806
|
-
`,await It("toolSuccess"),W==="patchfile"||W==="update_file"||W==="updatefile"||W==="patch_file"){if(M){let F=M.split(`
|
|
807
|
-
`),Y=0,J=0,Ne=!1;for(let De of F){if(De.includes("[DIFF_START]")){Ne=!0;continue}if(De.includes("[DIFF_END]")){Ne=!1;continue}Ne&&(/^\+\d+/.test(De)?Y++:/^\-\d+/.test(De)&&J++)}(Y>0||J>0)&&(await Gt("linesAdded",Y),await Gt("linesRemoved",J))}}else if((W==="writefile"||W==="write_file")&&M){let F=M.match(/- Stats: \[(\d+) lines/),Y=F?parseInt(F[1]):0,J=0;if(M.includes("Old File contents:")){let Ne=!1;for(let De of M.split(`
|
|
808
|
-
`)){if(De.includes("Old File contents:")){Ne=!0;continue}Ne&&(De.trim()===""?Ne=!1:/^\d+ \|/.test(De)&&J++)}}(Y>0||J>0)&&(await Gt("linesAdded",Y),await Gt("linesRemoved",J))}}catch(M){let F=`ERROR: Execution failed for [${B.toolName}]: ${M.message}`;i&&i(`[Tool Error] ${F}
|
|
809
|
-
`),V+=`${F}
|
|
810
|
-
|
|
811
|
-
`,await It("toolFailure")}}let oe="";if(n?.taskId&&typeof Ye<"u"){let B=Ye.find(W=>W.id===n.taskId);if(B&&B.pendingSteerMessages&&B.pendingSteerMessages.length>0){let W=[...B.pendingSteerMessages];B.pendingSteerMessages=[];for(let re of W)oe+=`
|
|
812
|
-
|
|
813
|
-
[STEERING INSTRUCTION FROM MAIN AGENT]: ${re}`,i&&i(`[Subagent Steered] ${re}`)}}let Ie=(V.trim()+oe).trim();b.push({role:"user",text:Ie}),T++}return $};export{hn as a,Pr as b,ff as c,uf as d,dl as e,Dr as f,hf as g,wl as h,pf as i,lo as j,la as k,xp as l,bp as m,I as n,Ic as o,Qo as p,zs as q,Oc as r,Lc as s,ft as t,ls as u,fd as v,Va as w,ud as x,hd as y,pd as z,md as A,gd as B,Td as C,Rd as D,Tn as E,Za as F,Js as G,Gt as H,el as I,$r as J,cs as K,Al as L,uu as M,hu as N,Tp as O,Fo as P,Rp as Q,Pn as R,pc as S,dm as T,fm as U,Xi as V,um as W,hm as X,Tc as Y,pm as Z,mm as _,gm as $};
|