fluxflow-cli 4.1.3 → 4.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/README.md +3 -1
  2. package/dist/chunks/{ai-5HGOLEFE.js → ai-JV4YFO7W.js} +1 -1
  3. package/dist/chunks/{app-AIAYUYQP.js → app-W2BOMBDT.js} +143 -143
  4. package/dist/chunks/{chunk-K4FITEVZ.js → chunk-3JHCQ2JD.js} +1 -1
  5. package/dist/chunks/{chunk-BZBAMZS4.js → chunk-6ENN7MJR.js} +1 -1
  6. package/dist/chunks/chunk-M7QN5C2K.js +1 -0
  7. package/dist/chunks/chunk-RVCFBTIL.js +814 -0
  8. package/dist/chunks/{screen_grid-IKEV7A6U.js → screen_grid-Y6GHBUFE.js} +1 -1
  9. package/dist/chunks/{secrets-D5HMTNJA.js → secrets-ITIOWL5R.js} +1 -1
  10. package/dist/chunks/{settings-SSPDWUKI.js → settings-REIFJELQ.js} +1 -1
  11. package/dist/cli.js +2 -2
  12. package/dist/model_config.json +67 -3
  13. package/dist/package.json +2 -2
  14. package/model_config.json +67 -3
  15. package/package.json +2 -2
  16. package/dist/chunks/ai-7J7CL56L.js +0 -1
  17. package/dist/chunks/ai-7LT7T34E.js +0 -1
  18. package/dist/chunks/ai-ACFJ2D4K.js +0 -1
  19. package/dist/chunks/ai-CQ6R662V.js +0 -1
  20. package/dist/chunks/ai-GO5NYAPZ.js +0 -1
  21. package/dist/chunks/ai-GUVZR6ZJ.js +0 -1
  22. package/dist/chunks/ai-IGHYVKEI.js +0 -1
  23. package/dist/chunks/ai-IOVX3WCN.js +0 -1
  24. package/dist/chunks/ai-LFC7GPK6.js +0 -1
  25. package/dist/chunks/ai-LUAK6ZNI.js +0 -1
  26. package/dist/chunks/ai-NDNZ4XGW.js +0 -1
  27. package/dist/chunks/ai-O2AHKT2Q.js +0 -1
  28. package/dist/chunks/ai-OLHI3UWZ.js +0 -1
  29. package/dist/chunks/ai-OP2H56UR.js +0 -1
  30. package/dist/chunks/ai-OX4W3MY2.js +0 -1
  31. package/dist/chunks/ai-SUNZIUAF.js +0 -1
  32. package/dist/chunks/ai-T2SZGY7Y.js +0 -1
  33. package/dist/chunks/ai-VMV4EAEQ.js +0 -1
  34. package/dist/chunks/app-2BDYKT26.js +0 -226
  35. package/dist/chunks/app-2MCTW3BU.js +0 -226
  36. package/dist/chunks/app-4M34YBXM.js +0 -223
  37. package/dist/chunks/app-4VRQVBXL.js +0 -226
  38. package/dist/chunks/app-5YW3SESE.js +0 -223
  39. package/dist/chunks/app-62A6ZFYX.js +0 -226
  40. package/dist/chunks/app-A6HECULK.js +0 -223
  41. package/dist/chunks/app-A6JFAZBR.js +0 -220
  42. package/dist/chunks/app-AASWJUCP.js +0 -226
  43. package/dist/chunks/app-AHIXABRK.js +0 -220
  44. package/dist/chunks/app-CK5GTF3V.js +0 -230
  45. package/dist/chunks/app-CTJKY73V.js +0 -223
  46. package/dist/chunks/app-DJWNDFPK.js +0 -223
  47. package/dist/chunks/app-DLGENJXK.js +0 -226
  48. package/dist/chunks/app-DU2VBIDN.js +0 -223
  49. package/dist/chunks/app-EKHVG5CH.js +0 -220
  50. package/dist/chunks/app-FJJPTQG7.js +0 -223
  51. package/dist/chunks/app-FVACY6W2.js +0 -230
  52. package/dist/chunks/app-GY2S4P3O.js +0 -220
  53. package/dist/chunks/app-HE22VKVY.js +0 -223
  54. package/dist/chunks/app-HW6KINDL.js +0 -226
  55. package/dist/chunks/app-II7PE7RS.js +0 -230
  56. package/dist/chunks/app-MPYGQO5K.js +0 -223
  57. package/dist/chunks/app-MWWVPJVZ.js +0 -223
  58. package/dist/chunks/app-OIIPCXZF.js +0 -226
  59. package/dist/chunks/app-QCQTUW4S.js +0 -223
  60. package/dist/chunks/app-QPPCSI4B.js +0 -223
  61. package/dist/chunks/app-RDSYUUGS.js +0 -228
  62. package/dist/chunks/app-SWVHXTUU.js +0 -223
  63. package/dist/chunks/app-TSUKVNLY.js +0 -223
  64. package/dist/chunks/app-WWNOUK7Q.js +0 -220
  65. package/dist/chunks/app-XTDZID37.js +0 -228
  66. package/dist/chunks/app-YCFZG7ZN.js +0 -223
  67. package/dist/chunks/app-ZUY2BADH.js +0 -226
  68. package/dist/chunks/chunk-2FKXQDRX.js +0 -3
  69. package/dist/chunks/chunk-3VSDH7DF.js +0 -3
  70. package/dist/chunks/chunk-4ANZCMTB.js +0 -813
  71. package/dist/chunks/chunk-5ORPFMKW.js +0 -3
  72. package/dist/chunks/chunk-6DHFEWGX.js +0 -1
  73. package/dist/chunks/chunk-73S5MDH5.js +0 -816
  74. package/dist/chunks/chunk-77P7CACS.js +0 -3
  75. package/dist/chunks/chunk-7WH5DREO.js +0 -1
  76. package/dist/chunks/chunk-A6RZ4EIR.js +0 -813
  77. package/dist/chunks/chunk-APOUCRQO.js +0 -803
  78. package/dist/chunks/chunk-BVYPWENJ.js +0 -803
  79. package/dist/chunks/chunk-BW2MR2YB.js +0 -3
  80. package/dist/chunks/chunk-D67A52ZR.js +0 -802
  81. package/dist/chunks/chunk-DB4BJM2R.js +0 -807
  82. package/dist/chunks/chunk-GYYGT2GJ.js +0 -1229
  83. package/dist/chunks/chunk-HU74ZBCV.js +0 -803
  84. package/dist/chunks/chunk-IW2KLAXM.js +0 -803
  85. package/dist/chunks/chunk-M3G4NWZ2.js +0 -3
  86. package/dist/chunks/chunk-O4A5T73D.js +0 -801
  87. package/dist/chunks/chunk-PHKIAKHS.js +0 -1
  88. package/dist/chunks/chunk-PK33OTVD.js +0 -802
  89. package/dist/chunks/chunk-RTGBM2SA.js +0 -27
  90. package/dist/chunks/chunk-SGZ2OI72.js +0 -1
  91. package/dist/chunks/chunk-UCFPBFHY.js +0 -811
  92. package/dist/chunks/chunk-UKBUOJ3P.js +0 -803
  93. package/dist/chunks/chunk-VBKX2PU3.js +0 -803
  94. package/dist/chunks/chunk-VFG7GIPV.js +0 -812
  95. package/dist/chunks/chunk-WJ33GNVP.js +0 -3
  96. package/dist/chunks/chunk-Y2EZRWRZ.js +0 -803
  97. package/dist/chunks/chunk-Y6SLVHK3.js +0 -1
  98. package/dist/chunks/chunk-ZESOEAQT.js +0 -1
  99. package/dist/chunks/chunk-ZGHOKGSQ.js +0 -1231
  100. package/dist/chunks/chunk-ZQZIEF5I.js +0 -803
  101. package/dist/chunks/chunk-ZRS2O6Y6.js +0 -1
  102. package/dist/chunks/export-JZFBZGGZ.js +0 -1
  103. package/dist/chunks/export-MX2VT3I7.js +0 -1
  104. package/dist/chunks/export-OFKMKWAS.js +0 -1
  105. package/dist/chunks/export-ZB2GNV3S.js +0 -1
  106. package/dist/chunks/paths-HYQFU6D2.js +0 -1
  107. package/dist/chunks/paths-KMO5IYNK.js +0 -1
  108. package/dist/chunks/paths-NXN6XAEU.js +0 -1
  109. package/dist/chunks/paths-YDCMNN4Q.js +0 -1
  110. package/dist/chunks/secrets-2VU4KV7B.js +0 -1
  111. package/dist/chunks/secrets-GN7OAYL7.js +0 -1
  112. package/dist/chunks/secrets-NCPPS7DR.js +0 -1
  113. package/dist/chunks/secrets-RZD3DYTB.js +0 -1
  114. package/dist/chunks/settings-57QAZRCP.js +0 -1
  115. package/dist/chunks/settings-DCF6DTL6.js +0 -1
  116. package/dist/chunks/settings-DTH5C6BO.js +0 -1
  117. package/dist/chunks/settings-GPKUUYFM.js +0 -1
  118. package/dist/chunks/settings-HOSPANO7.js +0 -1
  119. package/dist/chunks/settings-IY24HSRP.js +0 -1
  120. package/dist/chunks/settings-XPFFYYYD.js +0 -1
  121. package/dist/chunks/src-O2JUKI77.js +0 -1
  122. package/dist/chunks/subagent_state-3D5ZJCLX.js +0 -1
  123. package/dist/chunks/subagent_state-5IJKFMRU.js +0 -1
  124. package/dist/chunks/subagent_state-N77JX7MX.js +0 -1
@@ -1,811 +0,0 @@
1
- import{b as zo}from"./chunk-ZESOEAQT.js";import{c as fn,d as Ks,g as et,h as Dt}from"./chunk-BZBAMZS4.js";import{a as Ys,b as $s,c as X,d as ue}from"./chunk-SIINYZWE.js";import{c as _n,d as cn,e as go,f as Cs,g as As,h as qo,i as Xt,j as Pt,k as Jt,l as In,m as Bn,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 Ve,c as yo}from"./chunk-56EJGQU3.js";import{c as ar,d as lr,e as ls}from"./chunk-K4FITEVZ.js";import Yl from"dotenv";import{GoogleGenAI as Ta,ThinkingLevel as at,HarmBlockThreshold as Vn,HarmCategory as zn}from"@google/genai";import{Ollama as Kl}from"ollama";import{execSync as Fa}from"child_process";import{spawn as Xo}from"child_process";var _=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 r=e[t];t++;let a=t,h=-1,d=t;for(;d<e.length;){let l=e.indexOf(r,d);if(l===-1)break;let u=0;for(let y=l-1;y>=0&&e[y]==="\\";y--)u++;if(u%2!==0){d=l+1;continue}let f=e.substring(l+1),p=f.trim(),g=p===""||/^,\s*\w+\s*=/.test(p)||p.startsWith(")")&&(p.length===1||/^\)\s*([,\]\s]|\[\[?tool:)/i.test(p));if(g&&f.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(a,h),t=h+1):(i=e.substring(a),t=e.length);let c=s.toLowerCase().includes("path")||["dest","source","to","from"].includes(s.toLowerCase());i=i.replace(/\\(.)/g,(l,u)=>{switch(u){case"n":return`
4
- `;case"r":return"\r";case"t":return" ";case"\\":return"\\";default:return u===r?r:u}})}else if(t<e.length&&e[t]==="["){let r=0,a=null,h=t,d=-1;for(let c=t;c<e.length;c++){let l=e[c];if(a&&l===a){let u=0;for(let f=c-1;f>=0&&e[f]==="\\";f--)u++;u%2===0&&(a=null)}else!a&&(l==='"'||l==="'"||l==="`")&&(a=l);if(!a&&(l==="["?r++:l==="]"&&r--,r===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 r=e.substring(t),a=r.match(/,\s*\w+\s*=|(?:\s*\)\s*(?:$|\]\]))/);if(a){let h=a.index;i=r.substring(0,h).trim(),t+=h}else i=r.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 Cc=!!wo,So=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),Jo=e=>{if(!e)return"";let n=[[]],t=0,o=0,s=/\x1b\[([0-9;]*?)([a-zA-Z])/g,i=0,r,a=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 u=n[t];for(;o>u.length;)u.push(" ");u[o]=l,o++}}};for(;(r=s.exec(e))!==null;){a(e.substring(i,r.index));let d=r[1],c=r[2],l=d?d.split(";").map(Number):[];if(c==="A"){let u=l[0]||1;t=Math.max(0,t-u)}else if(c==="B"){let u=l[0]||1;for(t=t+u;t>=n.length;)n.push([])}else if(c==="C"){let u=l[0]||1;o=o+u}else if(c==="D"){let u=l[0]||1;o=Math.max(0,o-u)}else if(c==="G"){let u=(l[0]||1)-1;o=Math.max(0,u)}else if(c==="H"||c==="f"){let u=(l[0]||1)-1,f=(l[1]||1)-1;for(t=Math.max(0,u),o=Math.max(0,f);t>=n.length;)n.push([])}else if(c==="K"){let u=l[0]||0;if(t<n.length){let f=n[t];if(u===0)f.length=o;else if(u===1)for(let p=0;p<o&&p<f.length;p++)f[p]=" ";else u===2&&(f.length=0)}}else if(c==="J"){let u=l[0]||0;(u===2||u===3)&&(n.length=0,n.push([]),t=0,o=0)}i=s.lastIndex}a(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,qs=!1,Ac=e=>{try{gt&&(qs&&typeof gt.write=="function"?gt.write(e):gt.stdin&&gt.stdin.writable&&gt.stdin.write(e))}catch{}},$c=()=>{if(gt){try{qs&&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,qs=!1}},Qo=(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 r=c=>!(!c.includes("/")||/^(https?|file|ftp):\/\//i.test(c)||c.startsWith("@")||c.startsWith("/")&&(c.match(/\//g)||[]).length===1||/\s\/|\/\s/.test(c)||/[\(\)\{\}\;\<\>\=\'\"]/.test(c)),a=[];for(let c=0;c<t.length;c++){let l=t[c];if(l==="mkdir"&&n&&Hn()){let u=[],f=c+1;for(;f<t.length;){let p=t[f];if([">",">>","<","&","&&","|","||",";"].includes(p))break;p!=="-p"&&p!=="--parents"&&p!=="-v"&&p!=="--verbose"&&u.push(p),f++}if(u.length>0){let p=u.map(g=>{let y=g.replace(/^['"]|['"]$/g,""),m=g;return r(y)&&(m=g.replace(/\//g,"\\")),m});a.push("New-Item","-ItemType","Directory","-Force","-Path",p.join(","))}else a.push("New-Item","-ItemType","Directory","-Force");c=f-1;continue}if(l==="rm"&&n&&Hn()){let u=[],f=!1,p=!1,g=c+1;for(;g<t.length;){let m=t[g];if([">",">>","<","&","&&","|","||",";"].includes(m))break;m==="-rf"||m==="-fr"?(f=!0,p=!0):m==="-r"||m==="-R"||m==="--recursive"?f=!0:m==="-f"||m==="--force"?p=!0:u.push(m),g++}let y=["Remove-Item"];if(f&&y.push("-Recurse"),p&&y.push("-Force"),u.length>0){let m=u.map(w=>{let x=w.replace(/^['"]|['"]$/g,""),E=w;return r(x)&&(E=w.replace(/\//g,"\\")),E});y.push("-Path",m.join(","))}a.push(...y),c=g-1;continue}if(l==="cp"&&n&&Hn()){let u=[],f=!1,p=!1,g=c+1;for(;g<t.length;){let m=t[g];if([">",">>","<","&","&&","|","||",";"].includes(m))break;m==="-r"||m==="-R"||m==="--recursive"?f=!0:m==="-f"||m==="--force"?p=!0:u.push(m),g++}let y=["Copy-Item"];if(f&&y.push("-Recurse"),p&&y.push("-Force"),u.length>0){let m=u.map(w=>{let x=w.replace(/^['"]|['"]$/g,""),E=w;return r(x)&&(E=w.replace(/\//g,"\\")),E});if(m.length>1){let w=m.pop();y.push("-Path",m.join(","),"-Destination",w)}else y.push("-Path",m[0])}a.push(...y),c=g-1;continue}if(l==="touch"&&n&&Hn()){let u=[],f=c+1;for(;f<t.length;){let p=t[f];if([">",">>","<","&","&&","|","||",";"].includes(p))break;u.push(p),f++}if(u.length>0){let g=`(${u.map(y=>{let m=y.replace(/^['"]|['"]$/g,""),w=y;return r(m)&&(w=y.replace(/\//g,"\\")),w}).join(", ")}) | ForEach-Object { if (Test-Path $_) { (Get-Item $_).LastWriteTime = [System.DateTime]::Now } else { $null | Out-File -FilePath $_ } }`;a.push(g)}c=f-1;continue}if(l==="|"&&t[c+1]==="tee"){t[c+2]==="-a"?(a.push(">>"),c+=2):(a.push(">"),c+=1);continue}if(l==="|"&&t[c+1]==="cat"&&t[c+2]===">"){a.push(">"),c+=2;continue}if(l==="|"){let u=t[c+1];if(u){let f=u.replace(/^['"]|['"]$/g,""),p=/\.(txt|md|json|log|csv|html|css|py|js|xml|yaml|yml|pdf|docx|pptx|xlsx)$/i.test(f);if(r(f)&&p){a.push(">");continue}}}a.push(l)}let h=!1,d=a.map(c=>{if(c==="echo")return h=!0,c;[">",">>","<","&","&&","|","||",";"].includes(c)&&(h=!1);let u=/^['"]|['"]$/.test(c),f=c;h&&u&&(f=c.replace(/^['"]|['"]$/g,""));let p=/^['"]|['"]$/.test(f),g=f.replace(/^['"]|['"]$/g,"");r(g)&&(f=f.replace(/\//g,"\\"));let y=f.replace(/^['"]|['"]$/g,"");return y.includes(" ")&&!p&&(f=`"${y}"`),f});if(n){let c="",l=0;for(let u=0;u<d.length;u++){let f=d[u];f==="&&"?(c+="; if ($?) {",l++):f===";"?(c+=" }".repeat(l)+";",l=0):(c&&!c.endsWith(" ")&&!c.endsWith("{")&&(c+=" "),c+=f)}return c+=" }".repeat(l),c}return d.join(" ")},Zo=async(e,n={})=>{let{command:t}=_(e),{onChunk:o}=n;if(!t)return'ERROR: Missing "command" argument for exec_command.';let s=process.platform==="win32",i=n.systemSettings||{},r={};return i.networkAccess===!1&&(r.HTTP_PROXY="http://127.0.0.1:9999",r.HTTPS_PROXY="http://127.0.0.1:9999",r.ALL_PROXY="socks5://127.0.0.1:9999",r.http_proxy="http://127.0.0.1:9999",r.https_proxy="http://127.0.0.1:9999",r.all_proxy="socks5://127.0.0.1:9999",r.NO_PROXY="localhost,127.0.0.1"),new Promise(a=>{let h=d=>{let c=d==="pwsh"||d==="powershell",l=Qo(t,c),u;s?d==="pwsh"?u="C:\\Users\\User\\AppData\\Local\\Microsoft\\WindowsApps\\pwsh.exe":d==="powershell"?u="powershell.exe":u="cmd.exe":u=process.env.SHELL||"bash";let f=s?c?["-NoProfile","-Command",l]:["/c",l]:["-c",l];if(i.networkAccess===!1&&!s){let p=u,g=[...f];if(process.platform==="linux")u="unshare",f=["-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
- `;u="sandbox-exec",f=["-p",y,p,...g]}}if(wo)try{let p=wo.spawn(u,f,{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",...r}});gt=p,qs=!0;let g="",y=!1;return p.onData(m=>{if(!y){g+=m,o&&o(m);let w=So(g);/(?:Network:\s+use\s+--host\s+to|Network:\s+Type\s+--host\s+to|Local:\s+http:\/\/localhost:\d+|ready in \d+\s*ms|Compiled successfully|Development server is running|Listening on:)/i.test(w)&&(y=!0,setTimeout(()=>a(`SUCCESS: Dev server started successfully in background.
12
-
13
- ${w}`),500))}}),p.onExit(({exitCode:m})=>{if(y)return;gt=null;let w=Jo(g||""),x=So(w).replace(/\n{3,}/g,`
14
-
15
- `)||"Command executed with no output.";a(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:(To(a,l,t,r,o,d,i),!0)}else return To(a,l,t,r,o,d,i),!0};s?h("pwsh")||h("powershell")||h("cmd"):h("bash")})},To=(e,n,t,o,s,i="powershell",r={})=>{let a=process.platform==="win32",h=i==="pwsh"||i==="powershell",d;a?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=a?h?["-NoProfile","-Command",n]:["/c",n]:["-c",n];if(r.networkAccess===!1&&!a){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=a?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,qs=!1,l.stdin&&l.stdin.on("error",()=>{gt=null});let u="",f="",p=!1;l.stdout.on("data",g=>{if(!p){let y=g.toString();u+=y,s&&s(y);let m=So(u);/(?: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();f+=y,s&&s(y)}}),l.on("close",g=>{if(p)return;gt=null;let y=[],m=Jo(u),w=Jo(f);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.",E=So(x).replace(/\n{3,}/g,`
31
-
32
- `);e(g!==0?`ERROR: Command [${t}] failed with exit code [${g}].
33
-
34
- ${E}`:`SUCCESS: Command [${t}] completed.
35
-
36
- ${E}`)}),l.on("error",g=>{if(a&&g.code==="ENOENT"){if(i==="pwsh"){let m=Qo(t,!0);return To(e,m,t,o,s,"powershell",r)}else if(i==="powershell"){let m=Qo(t,!1);return To(e,m,t,o,s,"cmd",r)}}gt=null;let y=g instanceof Error?g.message:String(g);e(`ERROR: Failed to start command [${t}]: ${y}`)})};var Vs=null,Hn=()=>{if(process.platform!=="win32")return!1;if(Vs!==null)return Vs;try{Fa('powershell.exe -NoProfile -Command "exit"',{stdio:"ignore"}),Vs=!0}catch{Vs=!1}return Vs},ei=null,cr=(e,n,t,o,s=!1,i=!0)=>{ei===null&&(ei=s);let r=`- 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
- - MUST AVOID UNNECESSARY LARGE-FILE CHUNK READS
41
- - DONT HALLUCINATE TOOL RESULTS, VERIFY, FIX ERRORS
42
- - Stuck on syntax error? TELL USER > Waste Time
43
- `,a=`- WORKSPACE TOOLS (path = relative; FIRST ARGUMENT, path separator: '/') -
44
- - [tool:functions.ReadFile(path="...", startLine="integer", endLine="integer")]. ${o!=="Google"?`${t?"Supports images/docs":""}`:"Supports images/docs"}
45
- - [tool:functions.ReadFolder(path="...", recurse="integer 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"?Hn()?"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
- ${ei?'\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 to CWD & WILL BE 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 SCANNBALE, 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", amount="int 1-10", 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 IN TOOL ARGUMENTS
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
- -- AVAILABLE TOOLS (STRING BASED PROTOCOL) --
71
- TO USE TOOLS, MUST OUTPUT EXACTLY '[tool:functions.ToolName(arg1="value1")]' STRUCTURED STRING IN CHAT RESPONSE \u2190 STRICT
72
- TOOL RULES:
73
- - MAX 3 TOOL CALLS/TURN${e==="Flux"||e.toLowerCase()==="fluxcu"?" (Todo: 3+, Run: max 1 or 2 consecutive)":""}
74
- ${e==="Flux"||e.toLowerCase()==="fluxcu"?`${r}`:""}
75
- - USER COMMUNICATION -
76
- - [tool:functions.Ask(question="...", optionA="title::description", ...MAX4)]. Ambiguity: MUST for path divergence, security risk. Ask, don't finish/guess. Keep titles short
77
-
78
- - WEB TOOLS -
79
- - [tool:functions.WebSearch(query="...", aiMode="bool", limit="integer 3-10 aiMode: exclude")]. Usage: 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"?`${a}
83
- ${d}`:e==="Flux"?`${a}`:`${h}`}`.trim()};var dr=(e=!0,n=!0)=>`
84
- Your exact tool syntax is: [tool:functions.ToolName(args...)]. Malformed calls will fail parsing. **NO OTHER SYNTAX/MARKERS/BOUNDARY ALLOWED** Proper bracket balancing per schema is mandatory
85
-
86
- -- CHAT MANAGEMENT TOOLS (MUST CALL THESE 2 TOOLS IN THIS TURN) --
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 Eo={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 ur from"fs";import Ba from"screenshot-desktop";var hr=!1;(async()=>{try{let e=await Dt();if(Number(e?.display)===1){let n=await Ba.listDisplays();n&&n.length>1&&(hr=!0)}}catch{}})();var ti=null,fr=null,zs=null,Yc=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",Wa=(e,n)=>{if(!n)return"";if(e!==fr||zs===null){fr=e;try{let t=X(Pt,[]);Array.isArray(t)&&t.length>0?zs=t.map(o=>`- ${o.memory}`).join(`
125
- `):zs=""}catch(t){zs="",ur.appendFileSync(`${cn}/memory/error.txt`,`${t.message}
126
- -------------------------------------------------
127
-
128
- `)}}return zs},pr=(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: DYNAMIC-LOW, FOCUS: Chat Context > Recent) --
129
- ${e}`:"";return s?`${s}`:""},mr=(e,n,t,o,s=!0,i=!1,r="Google",a=!1,h,d)=>{let c=!1;process.env.forcedReasoning&&process.env.NVIDIA_BASE_URL&&r.toUpperCase()==="NVIDIA"&&(c=!0);let l="";if(!h&&r==="Google"){let C=n;n==="Fast"&&(C="Off"),n==="Low"&&(C="Minimal"),n==="Standard"&&(C="Medium"),(n==="xHigh"||n==="Max")&&(C="xHigh"),l=Eo[C]||Eo.Medium}if(h||r!=="Google"){let C={Fast:"LOWEST",Low:"LOW",Medium:"MEDIUM",Standard:"MEDIUM",High:"HIGH",xHigh:"HIGH",Max:"HIGH"};l=Eo.xHigh,l=l.replace("EFFORT: HIGH",`EFFORT: ${C[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 u=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",f=e.instructions&&e.instructions?.length>0?`User Preferences: ${e.instructions}
135
-
136
- `:"",p=e.nickname&&e.nickname?.length>0?`User Nickname: ${e.nickname}
137
- ${f.length?"":`
138
- `}`:"",g=e.name&&e.name?.length>0?`User Name: ${e.name}
139
- ${p.length||f.length?"":`
140
- `}`:"",y=process.cwd(),m=Wa(d,s),w=m?.length>0?`--- SAVED MEMORIES ---
141
- ${m}
142
-
143
- `:"",x=(()=>{let C=process.cwd().toLowerCase();if(process.platform==="win32"){let S=process.env.SystemRoot?.toLowerCase()||"c:\\windows",R=process.env.ProgramFiles?.toLowerCase()||"c:\\program files",A=process.env["ProgramFiles(x86)"]?.toLowerCase()||"c:\\program files (x86)";return C.startsWith(S)||C.startsWith(R)||C.startsWith(A)}else return C==="/"||["/bin","/sbin","/etc","/usr","/var","/root"].some(R=>C.startsWith(R))})(),E=[{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||ti===null){let C=E.filter(S=>ur.existsSync(S.name));ti=t==="Flux"&&C.length>0?`
144
- -- PROJECT CONTEXT --
145
- ${C.map(S=>`- ${S.name}: ${S.desc}`).join(`
146
- `)}
147
- Check these first; These Files > Training Data. Safety rules apply
148
- `:""}let b=ti;return`=== SYSTEM PROMPT ===
149
- Identity: Flux Flow. Sassy, Friendly, CLI Agent
150
- ${t==="Flux"?"Stepwise Execution, Run Automated Tests. Task Completion":t==="Flow"?"Concise, Humorous, Sarcastic":t==="ICU"?"Computer Use Capabilities. SCREENSHOT (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"}${hr&&t.toLowerCase().includes("cu")?`
151
- **RUNNING ON SECONDARY SCREEN. Opened app not visible in screenshot? Might be opened on PRIMARY. Use 'Ask' with NO options IMMEDIATELY and tell user to move app window to secondary**`:""}
152
-
153
- - OS: ${u}
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
- ${r==="Mistral"||r==="Google"&&!h?`${l}
160
- ${c||n!=="Fast"&&(r==="Mistral"&&!h||n!=="xHigh"&&!h)?`CRITICAL THINKING POLICY
161
- - Use <think>...</think> for reasoning before responding any queries
162
- `:""}`:`${l}
163
- `}
164
- ${cr(t,u,r.toLowerCase()==="deepseek"?!1:a,r,o?.advanceRollback,o?.subAgents!==!1)}
165
- ${b}${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}${f}${w}`.trim()},gr=(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
- ${dr(n,t)}
199
- === END SYSTEM PROMPT ===${e?`
200
-
201
- -- CURRENT SAVED USER MEMORIES --
202
- ${e}`:""}`.trim();import At from"fs-extra";import xo from"path";import{nanoid as Ga}from"nanoid";import dt from"fs-extra";import sn from"path";dt.ensureDirSync(Bn);var un=null;async function Ha(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(Bn,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=$s(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 ja(e,n,t=7){let o=0;for(;o<t;)try{return await Ha(e,n),!0}catch{if(o++,o>=t)return!1;let i=Math.min(100*Math.pow(2,o-1),5e3);await new Promise(r=>setTimeout(r,i))}return!1}var ni=null,ft={async startTransaction(e,n){ni=e,un={id:`tx_prompt_${Date.now()}`,chatId:e,timestamp:new Date().toISOString(),prompt:n.trim(),changes:[],reverted:!1},ue(rs,un)},async recordFileChange(e,n=null){try{if(!un){if(ni){let r=X(nn,[]),a=[...r].reverse().find(h=>h.chatId===ni);if(a){if(a.changes.some(u=>u.filePath===e))return;let c=await dt.pathExists(e)||n?"update":"create",l=null;if(c==="update"){let u=sn.basename(e);l=`${a.id}_${u}.bak`;let f=sn.join(Bn,a.chatId);await dt.ensureDir(f);let p=sn.join(f,l),g=n!==null?n:await dt.readFile(e,"utf8").catch(()=>null);g!==null?ue(p,{data:Ys(g)}):(c="create",l=null)}a.changes.push({filePath:e,type:c,backupFile:l}),ue(nn,r)}}return}if(un.changes.some(r=>r.filePath===e))return;let s=await dt.pathExists(e)||n?"update":"create",i=null;if(s==="update"){let r=sn.basename(e);i=`${un.id}_${r}.bak`;let a=sn.join(Bn,un.chatId);await dt.ensureDir(a);let h=sn.join(a,i),d=n!==null?n:await dt.readFile(e,"utf8").catch(()=>null);d!==null?ue(h,{data:Ys(d)}):(s="create",i=null)}un.changes.push({filePath:e,type:s,backupFile:i}),ue(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(Bn,n.chatId,t.backupFile)).catch(()=>{})}ue(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),ue(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(r=>r.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(r=>r.chatId===o&&!r.reverted).reverse();for(let r of i){for(let a of[...r.changes].reverse())await ja(a,r);for(let a of r.changes)if(a.backupFile){let h=sn.join(Bn,r.chatId,a.backupFile);await dt.remove(h).catch(()=>{})}n=n.filter(a=>a.id!==r.id),ue(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(Bn,e));let n=X(nn,[]),t=n.filter(o=>o.chatId!==e);n.length!==t.length&&ue(nn,t)}catch{}}};var yr=Promise.resolve(),Ro=e=>{let n=yr.then(async()=>{try{return await e()}catch(t){throw console.error("Lock Operation Failed:",t),t}});return yr=n.catch(()=>{}),n},cs=async()=>{await At.ensureDir(As);let e={};if(await At.pathExists(Cs))try{e=X(Cs,{})}catch{e={}}for(let n in e){let t=xo.join(As,`${n}.json`);Object.defineProperty(e[n],"messages",{get:()=>{if(At.existsSync(t))try{return X(t,[])}catch{return[]}return[]},set:o=>{try{ue(t,o)}catch{}},enumerable:!1,configurable:!0})}return e},id=async(e,n,t)=>Ro(async()=>{await At.ensureDir(As);let o=await cs(),s=o[e],i=(t||[]).filter(y=>!y.isUpdateNotification&&(!y.isMeta||y.text&&y.text.includes("Request Cancelled")));try{(await Dt()).systemSettings?.preserveThinking===!1&&(i=i.filter(m=>m.role!=="think"))}catch{}let r=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+/),E;return x.length>7?E=x.slice(0,7).join(" ")+"...":w.length>45?E=w.substring(0,45).trimEnd()+"...":E=w,E},a,h=i.filter(y=>y.role==="user"),d=h[0],c=h[h.length-1],l=r(c),u=r(d);s&&s.prompt?Math.random()<.5&&l?a=l:a=s.prompt:a=u||l;let f=n||(s?s.name:`Session ${e.slice(-6)}`),p=xo.join(As,`${e}.json`);ue(p,i),o[e]={name:f,prompt:a||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};ue(Cs,g)}),wr=async(e,n)=>Ro(async()=>{let t=await cs();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};ue(Cs,o)}),Ya=async e=>Ro(async()=>{let n=await cs();delete n[e];let t={};for(let r in n)t[r]={name:n[r].name,prompt:n[r].prompt||void 0,updatedAt:n[r].updatedAt};if(ue(Cs,t),await At.pathExists(Wn))try{let r=X(Wn,[]);if(Array.isArray(r)){let a=r.filter(h=>Object.keys(h)[0]!==String(e));ue(Wn,a)}}catch{}let o=X(Jt,{});o[e]&&(delete o[e],ue(Jt,o));let s=X(In,{});s[e]&&(delete s[e],ue(In,s)),await ft.deleteChatBackups(e);let i=xo.join(As,`${e}.json`);if(await At.pathExists(i))try{await At.remove(i)}catch{}return n}),rd=()=>`flow-${Ga(6)}`,ad=async e=>{if(!e||e==="Never")return;let n=parseInt(e);if(isNaN(n))return;let t=await cs(),o=Date.now(),s=n*24*60*60*1e3,i=0;for(let r in t){let a=t[r];a.updatedAt&&o-a.updatedAt>s&&(await Ya(r),i++)}return i},Ka=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]||"",r=o[2]||"",a=s.split(/[-\/.]/).map(Number);if(a.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,u;if(a[0]>1e3)c=a[0],l=a[1],u=a[2];else if(a[2]>1e3)c=a[2],a[0]>12?(u=a[0],l=a[1]):a[1]>12?(u=a[1],l=a[0]):d?(u=a[0],l=a[1]):(l=a[0],u=a[1]);else return null;if(l<1||l>12||u<1||u>31)return null;let f=0,p=0,g=0;if(i){let m=i.split(":").map(Number);f=m[0]||0,p=m[1]||0,g=m[2]||0,r.toLowerCase()==="pm"&&f<12?f+=12:r.toLowerCase()==="am"&&f===12&&(f=0)}let y=new Date(c,l-1,u,f,p,g);return isNaN(y.getTime())?null:y.getTime()},qa=async e=>{try{if(!await At.pathExists(e))return;let n=await At.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 r=10080*60*1e3,a=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=Ka(p[1]);if(g&&a-g>r)continue}}let f=l.header+(l.body.length>0?`
204
- `+l.body.join(`
205
- `):"");h.push(f)}let c=h.join(`
206
- `).trim();c?await At.writeFile(e,c+`
207
- `,"utf8"):await At.writeFile(e,"","utf8")}catch{}},ld=async e=>{try{if(!await At.pathExists(e))return;let n=async t=>{let o=await At.readdir(t);for(let s of o){let i=xo.join(t,s);(await At.stat(i)).isDirectory()?(await n(i),(await At.readdir(i)).length===0&&await At.remove(i)):s.endsWith(".log")&&await qa(i)}};await n(e)}catch{}},Sr=(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 cd=async(e,n,t)=>Ro(async()=>{let o=X(Wn,[]);Array.isArray(o)||(o=[]);let s={total:n,context:t},i=o.findIndex(r=>Object.keys(r)[0]===String(e));i!==-1?o[i]={[String(e)]:s}:o.push({[String(e)]:s}),ue(Wn,o)}),dd=async e=>{try{if(!await At.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 Tr from"path";var Va=()=>Math.random().toString(36).substring(2)+Date.now().toString(36),se=null,jn=null,Er=0,Os=!1,Ln={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},bo=async()=>{let e=new Date().toISOString().split("T")[0];try{!await yt.exists(Xt)&&await yt.exists(qo)&&(await yt.ensureDir(Tr.dirname(Xt)),await yt.move(qo,Xt))}catch{}let n=Xt+".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($s(s)),i&&i.date&&i.stats){t=i;try{await yt.rename(n,Xt)}catch{}}else try{await yt.remove(n)}catch{}}}catch{try{await yt.remove(n)}catch{}}if(!t)try{if(await yt.exists(Xt)){let s=(await yt.readFile(Xt,"utf8")).trim();s.startsWith("{")||s.startsWith("[")?t=JSON.parse(s):t=JSON.parse($s(s))}}catch{}let o=t;if(o){let s=o.stats||{...Ln},i={...Ln,...s};Array.isArray(i.imageCalls)||(i.imageCalls=[]);let r=o.history||{},a=Ms(r,e);if(Object.keys(r).length!==Object.keys(a).length&&(Os=!0),o.date===e)return{...o,stats:i,history:a};{let h=o.date,d=i,c={...a};return h&&(c[h]=d),{date:e,stats:{...Ln},history:Ms(c,e)}}}return{date:e,stats:{...Ln},history:{}}},si=async()=>{if(!(!Os||!se))try{await yt.ensureDir(Tr.dirname(Xt));let e=null;try{if(await yt.exists(Xt)){let s=(await yt.readFile(Xt,"utf8")).trim();s.startsWith("{")||s.startsWith("[")?e=JSON.parse(s):e=JSON.parse($s(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]:[],r=se.stats[s],a=new Map;for(let h of[...i,...r])h&&h.timestamp&&a.set(h.timestamp,h);se.stats[s]=Array.from(a.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]||{},r=se.stats[s];for(let a in i)if(typeof i[a]=="number")r[a]=Math.max(r[a]||0,i[a]);else if(i[a]&&typeof i[a]=="object"){r[a]||(r[a]={});for(let h in i[a])if(typeof i[a][h]=="number")r[a][h]=Math.max(r[a][h]||0,i[a][h]);else if(i[a][h]&&typeof i[a][h]=="object"){r[a][h]||(r[a][h]={});for(let d in i[a][h])r[a][h][d]=Math.max(r[a][h][d]||0,i[a][h][d])}}}}}if(e&&e.history){let s={...se.history||{}};for(let i in e.history)if(s[i])for(let r in s[i])if(r==="imageCalls"){let a=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[...a,...h])c&&c.timestamp&&d.set(c.timestamp,c);s[i].imageCalls=Array.from(d.values())}else typeof s[i][r]=="number"&&(s[i][r]=Math.max(s[i][r],Number(e.history[i][r])||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=Va();let n=Xt+".tmp",t=Ys(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,Xt),Os=!1,Er=Date.now()}catch{}},ko=()=>{if(Os=!0,jn)return;let e=Date.now(),n=Math.max(0,1500-(e-Er));jn=setTimeout(async()=>{await si(),jn=null},n),jn.unref&&jn.unref()},yd=async()=>{se=await bo(),Os&&ko()},wd=async()=>{jn&&(clearTimeout(jn),jn=null),await si()},bn=async()=>{let e=new Date().toISOString().split("T")[0];if(!se)se=await bo();else if(se.date!==e){let n=se.date,t=se.stats,o=se.history||{};t&&(o[n]=t),se={date:e,stats:{...Ln},history:Ms(o,e)},Os=!0,await si()}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 bo()),se.date!==e&&await bn();let n=se.history||{},t=Ms(n,e);se.history=t;let o=se.stats||{...Ln},s={...Ln};s.imageCalls=[],s.models={};let i=(r,a)=>{for(let h in r)if(h==="imageCalls")r.imageCalls=[...r.imageCalls||[],...a.imageCalls||[]];else if(h==="models"){let d=a.models||{};for(let c in d){r.models[c]||(r.models[c]={});for(let l in d[c]){r.models[c][l]||(r.models[c][l]={tokens:0,cachedTokens:0,candidateTokens:0});let u=r.models[c][l],f=d[c][l];u.tokens+=f.tokens||0,u.cachedTokens+=f.cachedTokens||0,u.candidateTokens+=f.candidateTokens||0}}}else typeof r[h]=="number"&&(r[h]+=a[h]||0)};i(s,o);for(let r in t)i(s,t[r]);return s},It=async(e,n)=>{e==="toolSuccess"?Xs.toolSuccess++:e==="toolFailure"?Xs.toolFailure++:e==="toolDenied"&&Xs.toolDenied++;let t=await bn();t[e]!==void 0&&t[e]++,n&&e==="agent"&&(t.providerRequests||(t.providerRequests={}),t.providerRequests[n]=(t.providerRequests[n]||0)+1),ko()},Xs={linesAdded:0,linesRemoved:0,toolSuccess:0,toolFailure:0,toolDenied:0},Gt=async(e,n,t,o)=>{e==="linesAdded"?Xs.linesAdded+=n:e==="linesRemoved"&&(Xs.linesRemoved+=n);let s=await bn();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))}ko()},Xa=async(e=1)=>{let n=new Date,t=n.toISOString().split("T")[0];se||(se=await bo()),se.date!==t&&await bn();let o=n.getFullYear(),s=n.getMonth();n.getDate()<e&&(s-=1,s<0&&(s=11,o-=1));let a=new Date(o,s,e).toISOString().split("T")[0],h=se.history||{},d=se.stats||{...Ln},c={...Ln};c.imageCalls=[],c.models={};let l=(u,f)=>{for(let p in u)if(p==="imageCalls")u.imageCalls=[...u.imageCalls||[],...f.imageCalls||[]];else if(p==="models"){let g=f.models||{};for(let y in g){u.models[y]||(u.models[y]={});for(let m in g[y]){u.models[y][m]||(u.models[y][m]={tokens:0,cachedTokens:0,candidateTokens:0});let w=u.models[y][m],x=g[y][m];w.tokens+=x.tokens||0,w.cachedTokens+=x.cachedTokens||0,w.candidateTokens+=x.candidateTokens||0}}}else typeof u[p]=="number"&&(u[p]+=f[p]||0)};l(c,d);for(let u in h)u>=a&&u<t&&l(c,h[u]);return c},oi=async(e,n={})=>{let t=await Dt().catch(()=>({})),o=n.apiTier||t.apiTier||"Free",s=n.quotas||n.systemSettings?.quotas||t.quotas||{},i=s.providerBudgets||{},r=!!i.__useProvider,a=n.aiProvider||t.aiProvider||"Google",h=r&&!!i[a],d=()=>{if(h){let c=i[a];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:u}=d(),f=await bn(),p;s.resetMode==="Custom"?p=await Xa(s.resetDay||1):p=await za();let g=0,y=0,m=0;if(h){g=f.providerRequests?.[a]||0;let w=f.models?.[a]||{};for(let E in w)y+=w[E]?.tokens||0;let x=p.models?.[a]||{};for(let E in x)m+=x[E]?.tokens||0}else g=f.agent||0,y=f.tokens||0,m=p.tokens||0;return o==="Free"&&f.agent+f.background>=999999?{allowed:!1,reason:"Free Tier Daily Usage Limit Exceeded"}:g>=c?{allowed:!1,reason:h?`Daily Request Limit Reached for ${a}`:"Daily Agent Request Limit Reached"}:y>=l?{allowed:!1,reason:h?`Daily Token Budget Exhausted for ${a}`:"Daily Token Budget Exhausted"}:m>=u?{allowed:!1,reason:h?`Monthly Token Budget Exhausted for ${a}`:"Monthly Token Budget Exhausted"}:{allowed:!0}}if(e==="background"){let c=await bn();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 bn()).search<(s.searchLimit||100);return{allowed:l,reason:l?void 0:"Search Quota Exceeded"}}return{allowed:!0}},xr=async(e,n={})=>(await oi(e,n)).allowed,ii=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=ii(e);if(o.length===0)return .025;let s=[];for(let l of o){let u=.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)u=.015;else{let y=p.limit,m=p.ratio;m>=.8?u=y===.015?.015:y:m<.4?u=Math.min(.025,y+.005):m>=.4&&m<.6?u=Math.min(.025,y+.004):u=Math.min(.025,y+.002)}}let f=u>0?l.spent/u:0;s.push({limit:u,spent:l.spent,ratio:f})}let i=o[o.length-1];if(n<i.end)return s[s.length-1].limit;let r=s[s.length-1].limit,a=r,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=a===.015?.015:a:h<.4?l=Math.min(.025,a+.005):h>=.4&&h<.6?l=Math.min(.025,a+.004):l=Math.min(.025,a+.002),a=l,h=0,c=0,d+=36e5,r=l}return r},br=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 bn();s.imageCalls||(s.imageCalls=[]);let i=Date.now(),r=ii(s.imageCalls),a=0;if(r.length>0){let d=r[r.length-1];i>=d.start&&i<d.end&&(a=d.spent)}let h=Rr(s.imageCalls,i);return a+o<=h},kr=async()=>{let e=await bn();e.imageCalls||(e.imageCalls=[]);let n=Date.now(),t=ii(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 r=Rr(e.imageCalls,n),a=Math.max(0,r-s),h=s;return{totalSpent:s,remaining:a,activeCallsCount:o.length,nextResetMin:i,reclaimCost:h,limit:r}},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 bn();s.imageCalls||(s.imageCalls=[]),s.imageCalls.push({timestamp:Date.now(),cost:o}),ko()};import Or from"puppeteer";import Mr from"fs";import _r from"path";import Ar from"os";import Js from"path";import _s from"fs";import{createRequire as Ja}from"module";import{fileURLToPath as Qa}from"url";var Za=Ja(import.meta.url),$r=Js.dirname(Qa(import.meta.url));function ds(){let e=Ar.platform(),n=Ar.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 r=n==="arm64"?"arm64":"x64";o="Google Chrome.app/Contents/MacOS/Google Chrome",s=`chrome-mac-${r}`}else if(e==="linux")t="linux",o="chrome",s="chrome-linux64";else return{};let i=Js.resolve($r,"..","..",".puppeteerrc.cjs");if(_s.existsSync(i)||(i=Js.resolve($r,"..",".puppeteerrc.cjs")),!_s.existsSync(i))return{};try{let r=Za(i),a=r.cacheDirectory,h=r.chrome?.version;if(a){if(process.env.PUPPETEER_CACHE_DIR=a,h){let l=Js.join(a,"chrome",`${t}-${h}`,s,o);if(_s.existsSync(l))return{executablePath:l,cacheDirectory:a}}let d=l=>{if(!_s.existsSync(l))return null;try{let u=_s.readdirSync(l),f=[];for(let p of u){let g=Js.join(l,p),y;try{y=_s.statSync(g)}catch{continue}if(y.isDirectory())f.push(g);else if(p.toLowerCase()===o.toLowerCase()&&(!h||g.includes(h)))return g}if(h){for(let p of f)if(p.includes(h)){let g=d(p);if(g)return g}}for(let p of f)if(!h||!p.includes(h)){let g=d(p);if(g)return g}}catch{}return null},c=d(a);if(c)return{executablePath:c,cacheDirectory:a}}}catch{}return{}}var ri=async e=>{let{query:n,limit:t=5,aiMode:o=!1}=_(e);if(!n)return'ERROR: Missing "query" argument for web_search.';let s=3,i=null;if(o){let r=`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 a=1;a<=s;a++){let h=null;try{let d=ds();h=await Or.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=a===1?Math.random()*1e3+500:Math.random()*2e3+1e3;await new Promise(k=>setTimeout(k,l));let u=`https://search.brave.com/ask?q=${encodeURIComponent(r)}&source=web`;await c.goto(u,{waitUntil:"domcontentloaded",timeout:18e4});let f=null,p=45e3,g=Date.now();for(;Date.now()-g<p&&(f=await c.evaluate(()=>{let k=Array.from(document.querySelectorAll('.message:not(.user), .answer-text, .llm-content, [data-type="answer"]')),T="";if(k.length>0&&(T=k.map(he=>he.innerText.trim()).filter(Boolean).join(`
223
-
224
- `)),T||(T=document.body.innerText),T.includes("anomaly"))throw new Error("ANOMALY_DETECTED");let L=!!document.querySelector('.spinner, .loading, .typing, .streaming, [data-streaming="true"], [data-state="loading"], svg.animate-spin, circle[cx], div[class*="spin"]'),I=k[0]||document.body,P=I?I.innerText.trim():"",j=/^(?:[✓✔]\s*)?Finished/i.test(P)||!!(I&&I.querySelector(".status-finished, .finished")),G=!L&&(j||T.includes("Sources:")&&!L),ee={};return document.querySelectorAll("a[href]").forEach(he=>{let Ue=he.getAttribute("href")||he.href||"";if(Ue.includes("uddg=")&&(Ue=decodeURIComponent(Ue.split("uddg=")[1].split("&")[0])),Ue.includes("url=")&&(Ue=decodeURIComponent(Ue.split("url=")[1].split("&")[0])),Ue&&(Ue.startsWith("http://")||Ue.startsWith("https://"))&&!Ue.includes("search.brave.com")){let F=he.innerText.trim();F&&(ee[F]=Ue),he.textContent=Ue}}),{isFinished:G,text:T,hrefMap:ee}}),!(f&&f.isFinished));)await new Promise(k=>setTimeout(k,1e3));let y=(f?f.text:"")||"",m=f?f.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,E="";if(y.includes("Sources:")){let k=y.split("Sources:");x=k[0],E=k.slice(1).join("Sources:")}let b=[];for(let k of x.split(`
225
- `)){let T=k.trim();T&&(/^(View all|Finished|Searching|Answering|Thinking)$/i.test(T)||/^[\+\-]?\d+$/.test(T)||T.includes("search.brave.com")||T.startsWith("https://www.youtube.com/watch")||T.startsWith("https://youtube.com/watch")||b.push(k))}let C=b.join(`
226
- `).replace(/^(?:[\+\-]?\d+\s*)+/i,"").replace(/\n{3,}/g,`
227
-
228
- `).trim(),S=k=>!k||k.includes("search.brave.com")||k.includes("youtube.com")||k.includes("youtu.be"),R="";if(E){let k=E.match(/https?:\/\/[^\s\)\>]+/g)||[],T=[];for(let I of k){let P=I.replace(/[\.\,\;]+$/,""),j=Object.keys(m).find(G=>G.startsWith(P)||P.startsWith(G));j&&m[j]&&(P=m[j]),S(P)||T.push(P)}Object.values(m).forEach(I=>{!S(I)&&!T.includes(I)&&T.push(I)});let L=Array.from(new Set(T));L.length>0&&(R=`Sources:
229
- `+L.map(I=>`- ${I}`).join(`
230
- `))}let A=C+(R?`
231
-
232
- `+R:"");if(!A||/^(\+\d+|Searching|Answering|Thinking|Finished)$/i.test(A))throw new Error("EMPTY_AI_RESPONSE");return await h.close(),`AI Search results for [${n}]:
233
-
234
- ${A}`}catch(d){if(i=d,Mr.writeFileSync(_r.join(cn,"web_tools","search","ai_mode","ERROR.txt"),d.message),h&&await h.close(),a<s){let c=Math.pow(2,a)*1e3;await new Promise(l=>setTimeout(l,c))}}}}for(let r=1;r<=s;r++){let a=null;try{let h=ds();a=await Or.launch({headless:!0,executablePath:h.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let d=await a.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=r===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 u=await d.$$eval(".result",(g,y)=>g.slice(0,y).map((m,w)=>{let x=m.querySelector(".result__a"),E=m.querySelector(".result__snippet"),b=x?x.href:"";b.includes("uddg=")&&(b=decodeURIComponent(b.split("uddg=")[1].split("&")[0]));let C=x?x.innerText.trim():"No Title",S=E?E.innerText.trim():"No Snippet";return`${w+1}. ${C}
235
- Source: ${b}
236
- Snippet: ${S}`}),t);if(u.length===0){if((await d.evaluate(()=>document.body.innerText)).includes("anomaly"))throw new Error("ANOMALY_DETECTED");return await a.close(),`No results found for query: [${n}].`}let f=u.join(`
237
-
238
- `);return await a.close(),`${o?`AI Mode temporarily failed, used Standard search.
239
-
240
- `:""}Search results for [${n}]:
241
-
242
- ${f}`}catch(h){if(i=h,a&&await a.close(),Mr.writeFileSync(_r.join(cn,"web_tools","search","standard_mode","ERROR.txt"),h.message),r<s){let d=Math.pow(2,r)*1e3;await new Promise(c=>setTimeout(c,d))}}}return`ERROR: Search failed after ${s+1} attempts. Last error: ${i.message}`};import el from"puppeteer";import tl from"turndown";import{gfm as nl}from"turndown-plugin-gfm";var ai=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 r=null;try{let a=ds();r=await el.launch({headless:!0,executablePath:a.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let h=await r.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(E=>E.remove());let y=document.createNodeIterator(document.body,NodeFilter.SHOW_COMMENT),m;for(;m=y.nextNode();)m.remove();for(document.querySelectorAll("*").forEach(E=>{let b=E.attributes;for(let C=b.length-1;C>=0;C--){let S=b[C].name;S!=="href"&&S!=="src"&&E.removeAttribute(S)}});document.querySelector("div, span");)document.querySelectorAll("div, span").forEach(E=>{E.parentNode&&E.replaceWith(...E.childNodes)});document.querySelectorAll("br").forEach(E=>{E.replaceWith(document.createTextNode(`
243
-
244
- `))});let x=()=>{let E=!1;document.querySelectorAll("*").forEach(b=>{b.childNodes.length===0&&!b.innerText.trim()&&(b.remove(),E=!0)}),E&&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(),u=new tl({headingStyle:"atx",codeBlockStyle:"fenced"});u.use(nl);let f=u.turndown(l).replace(/\.\s*\n/g,`
250
- `).replace(/ +/g," ").replace(/\t/g," ").replace(/\n\s+/g,`
251
- `).replace(/\n{3,}/g,`
252
-
253
- `),p=f.substring(0,5e4);return await r.close(),`Markdown parsed from [${t}]:
254
-
255
- ${p}${f.length>5e4?`
256
-
257
- [TRUNCATED AT 50K CHARS]`:""}`}catch(a){if(s=a,r&&await r.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 sl=4*(1024*2),li=async(e,n={})=>{let t=c=>{let l=new RegExp(`${c}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),u=e.match(l);if(u)return u[2].trim();let f=new RegExp(`${c}\\s*[:=]\\s*([^,\\s)]+)`,"s"),p=e.match(f);return p?p[1].trim():null},o=t("action"),s=t("method"),i=t("content"),r=t("content-new"),a=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(Jt,{});c[d]||(c[d]=[]),c[d].push(i),ue(Jt,c);let l=c[d].reduce((u,f)=>u+f.length,0);return`SUCCESS: Temporary context saved for session [${d}]. (Size: ${l} chars)`}if(o==="user"){let c=X(Pt,[]).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,u=`${l.getDate()}/${l.getMonth()+1}/${l.getFullYear()}`,f=i.includes("[Saved on:")?i:`${i.trim()} [Saved on: ${u}]`,p=sl,g=c.reduce((x,E)=>x+(E.memory?.length||0),0);for(;c.length>0&&g+f.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:f,score:Math.min(2,isNaN(m)?.5:m)};return c.push(w),ue(Pt,c),`SUCCESS: Memory added with ID [${w.id}] and score [${w.score}]. (Vault Size: ${g+f.length} chars)`}if(s==="update"){let l=h||a,u=r||i;if(!l||!u)return"ERROR: Missing 'id' or content for update.";let f=c.findIndex(m=>m.id===l);if(f===-1)return`ERROR: Memory ID [${l}] not found.`;let p=new Date,g=`${p.getDate()}/${p.getMonth()+1}/${p.getFullYear()}`,y=u.includes("[Saved on:")?u:`${u.trim()} [Saved on: ${g}]`;return c[f].memory=y,ue(Pt,c),`SUCCESS: Memory [${l}] updated.`}if(s==="delete"){let l=h||i;if(!l)return"ERROR: Missing 'id' for deletion.";let u=c.length,f=c.filter(p=>p.id!==l);return f.length===u?`ERROR: Memory ID [${l}] not found.`:(ue(Pt,f),`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 ci=async(e,n={})=>{let t=_(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 wr(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 Co from"fs";import Ir from"path";var Qs=async(e,n={})=>{let{path:t,StartLine:o,EndLine:s,start_line:i,end_line:r,startLine:a,endLine:h}=_(e),d=parseInt(o||i||a),c=parseInt(s||r||h),l=!isNaN(d),u=!isNaN(c),f=d||1,p=c||(d?d+800:800);if(!t)return'ERROR: Missing "path" argument for view_file.';let g=Ir.resolve(process.cwd(),t);try{if(!Co.existsSync(g))return`ERROR: File [${t}] does not exist.`;if(Co.statSync(g).isDirectory())return`ERROR: Path [${t}] is a directory. Use list_files instead.`;let m=Ir.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 P=Co.readFileSync(g).toString("base64"),j=x[m];return{text:`[BINARY FILE]: ${t} (${j}) - Loaded as multimodal part.`,binaryPart:{inlineData:{data:P,mimeType:j}}}}let E=Co.readFileSync(g,"utf8");E.startsWith("\uFEFF")&&(E=E.slice(1)),E=E.replace(/\r\n/g,`
258
- `).replace(/\r/g,`
259
- `);let b=E.split(`
260
- `),C=b.length;!l&&!u&&C>800&&(f=1,p=50);let S=Math.max(0,f-1),R=Math.min(C,p),A=b.slice(S,R),k=`File: [${t}] (Showing lines ${S+1}-${R} of ${C}).`,T=A.map((L,I)=>`${String(S+I+1).padStart(4)}: ${L.trimEnd()}`).join(`
261
- `);return`${k}
262
-
263
- ${T}`}catch(y){let m=y instanceof Error?y.message:String(y);return`ERROR: Failed to read file [${t}]: ${m}`}};import Is from"fs";import Lr from"path";var di=async(e,n={})=>{let{path:t,content:o}=_(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 r="";if(Is.existsSync(s))try{r=`Old File contents:
266
- ${Is.readFileSync(s,"utf8").split(/\r?\n/).map((b,C)=>`${C+1} | ${b}`).join(`
267
- `)}
268
-
269
- `}catch{r=`[Note: Could not read existing file for reversal reference]
270
-
271
- `}Is.existsSync(i)||Is.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");Is.writeFileSync(s,d,"utf8");let u=Is.readFileSync(s,"utf8"),f=Buffer.byteLength(u,"utf8"),p=u.split(/\r?\n/),g=p.length;if(f===0&&l>0)return u=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
- `),E=p.slice(-50).join(`
278
- `);y=`${x}
279
-
280
- ... [${g-100} lines truncated] ...
281
-
282
- ${E}`}u=null;let{systemSettings:m}=await Dt(),w=`SUCCESS: File [${t}] saved.
283
- - Stats: [${g} lines, ${(f/1024).toFixed(1)} KB]
284
- ${r}- Content Preview:
285
-
286
- ${y}`;if(m?.compressToolResults&&g>60){let x=d.split(/\r?\n/),E=x.slice(0,25).join(`
287
- `)===p.slice(0,25).join(`
288
- `),b=x.slice(-25).join(`
289
- `)===p.slice(-25).join(`
290
- `);E&&b&&(w=`[[SAME]]
291
- ${w}`)}return w}catch(r){let a=r instanceof Error?r.message:String(r);return`ERROR: Failed to write file [${t}]: ${a}`}};import pi from"fs";import ml from"path";import ol from"os";var hn=e=>typeof e!="string"?e:e.length>12?(e+"").replace("",""):e,vr=(e,n)=>{if(!e)return"";let t=/\x1B\[[0-?]*[ -/]*[@-~]/g,o=e.split(`
292
- `),s=[];if(n<=5)return e;let i=r=>r.replace(t,"").length;return o.forEach(r=>{if(i(r)<=n){s.push(r);return}let h=r.split(/(\s+)/),d="",c=0,l=r.match(/^(\s*)/),u=l?l[1]:"";h.forEach((f,p)=>{if(f.length===0)return;let g=i(f);if(c+g>n)if(d.trim().length>0)s.push(d.trimEnd()),d=u.substring(0,Math.min(u.length,8))+f,c=i(d);else if(t.test(f))s.push(f),d=u,c=i(d);else{let y=f;for(;i(y)>n&&n>10;)s.push(y.substring(0,n)),y=y.substring(n);d=y,c=i(d)}else d+=f,c+=g}),(d.trimEnd().length>0||d===u)&&s.push(d.trimEnd())}),hn(s.join(`
293
- `))},of=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()},rf=(e,n=40)=>{let t=_n.replaceAll("\\\\","\\");if(e=e.replace(ol.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("\\","/"))},Ao=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"],r=["newContent","new_content","content_to_add","newBlock","new_block"],a=(h,d,c)=>{let l,u;for(let f of d){let p=h===1?[`${f}1`,f,`${f}_1`]:[`${f}${h}`,`${f}_${h}`];for(let g of p)if(e[g]!==void 0){l=e[g];break}if(l!==void 0)break}for(let f of c){let p=h===1?[`${f}1`,f,`${f}_1`]:[`${f}${h}`,`${f}_${h}`];for(let g of p)if(e[g]!==void 0){u=e[g];break}if(u!==void 0)break}return{r:l,n:u}};for(let h of s){let{r:d,n:c}=a(h,i,r);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}},il=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
- `),r=m=>m.match(/^\s*/)[0],a=m=>{let w=m.split(`
300
- `).filter(E=>E.trim()!=="");if(w.length===0)return"";let x=r(w[0]);for(let E of w){let b=r(E);b.length<x.length&&(x=b)}return x},h=(m,w,x="")=>{if(!m||w===void 0)return m;let b=/^\t/m.test(w)?" ":" ",C=L=>L.split(`
301
- `).find(I=>I.trim()!=="")??"",S=C(w).match(/^\s*/)[0].length,R=C(m).match(/^\s*/)[0].length,A=S-R,k=(x.match(/^\s*/)||[""])[0].length;return m.split(`
302
- `).map((L,I)=>{if(L.trim()===""&&I!==0)return"";let P=L.match(/^\s*/)[0].length,j=Math.max(0,P+A);return I===0&&(j=Math.max(0,j-k)),b.repeat(j)+L.trimStart()}).join(`
303
- `)},d=[];for(let m=0;m<n.length;m++){let w=n[m],x=(w.replace||"").trim(),E=i(w.new||"");if(x.startsWith("^LINE:")&&x.endsWith("$")){let k=x.slice(6,-1).trim().split(".."),T=parseInt(k[0]),L=k[1]!==void 0?parseInt(k[1]):T;if(!isNaN(T)&&!isNaN(L)){let I=s.split(`
304
- `);if(T<1||T>I.length||L<T||L>I.length){d.push({index:m,success:!1,error:`Block ${m+1}: Line range ^LINE:${T}..${L}$ out of bounds (file has ${I.length} lines).`});continue}let j=I.slice(T-1,L).join(`
305
- `),G=0;for(let ee=0;ee<T-1;ee++)G+=I[ee].length+1;d.push({index:m,success:!0,startPos:G,firstMatchContent:j,content_to_add:E});continue}}let b=i(w.replace||"");if(b===""&&E===""){d.push({index:m,success:!1,error:`Block ${m+1}: Empty replace and add content.`});continue}let C=b.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),S=null;if(b!==""&&s.includes(b))S=new RegExp(C,"g");else{let A=b.split(`
306
- `).map(k=>k.trim()).filter(k=>k.length>0).map(k=>k.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\s+/g,"\\s*"));if(A.length>0){let k=A.join("\\s*");try{S=new RegExp(k,"g")}catch{S=new RegExp(C,"g")}}else S=new RegExp(C,"g")}let R=[...s.matchAll(S)];if(R.length===0&&b!==""){let A=il(b);A&&(R=[...s.matchAll(A)])}if(R.length===0){d.push({index:m,success:!1,error:`Block ${m+1}: Could not find match.`});continue}if(R.length>1&&!o){d.push({index:m,success:!1,error:`Block ${m+1}: Found ${R.length} matches (must be unique or use allowMultiple: true if sure).`});continue}for(let A of R)d.push({index:m,success:!0,startPos:A.index,firstMatchContent:A[0],content_to_add:E})}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,u=s,f=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,E=w+f,b=x+p,C=u.lastIndexOf(`
308
- `,E)+1,S=u.substring(C,E),R=h(m.content_to_add,m.firstMatchContent,S),A=u.split(`
309
- `),k=[];for(let P=Math.max(0,b-4);P<b-1;P++)k.push({num:P+1,text:A[P]});let T=m.firstMatchContent.split(`
310
- `),L=[],I=b+T.length-1;for(let P=I;P<Math.min(A.length,I+3);P++)L.push({num:P+1,text:A[P]});l.set(m,{success:!0,index:m.index,oldContent:m.firstMatchContent,newContent:R,originalStartLine:x,finalStartLine:b,contextBefore:k,contextAfter:L}),u=u.substring(0,E)+R+u.substring(E+m.firstMatchContent.length),f+=R.length-m.firstMatchContent.length,p+=R.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(E=>E.index===m);y.push({success:!1,error:x?x.error:`Block ${m+1}: Unknown error.`})}}return{content:u,results:y}},Oo=(e,n,t,o=8,s=!1)=>{if(!t||t.length===0)return"";let i=e.split(/\r?\n/),r=n.split(/\r?\n/),a=Math.max(i.length,r.length,1),h=Math.max(4,String(a).length),d=g=>String(g).padStart(h," "),c=`[DIFF_START]
313
- `,l="\u2550".repeat(88),u=0,f=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(f===null)for(u=Math.max(0,m-4);u<m-1;)c+=`[UI_CONTEXT] ${d(u+1)} |${r[u]||""}
314
- `,u++;else{let R=f,A=R.originalStartLine+R.oldContent.split(`
315
- `).length-1;if(g.originalStartLine-A-1>=o){let T=Math.min(r.length,u+3);for(;u<T;)c+=`[UI_CONTEXT] ${d(u+1)} |${r[u]||""}
316
- `,u++;for(c+=`[UI_CONTEXT] ${l}
317
- `,u=Math.max(u,m-4);u<m-1;)c+=`[UI_CONTEXT] ${d(u+1)} |${r[u]||""}
318
- `,u++}else for(;u<m-1;)c+=`[UI_CONTEXT] ${d(u+1)} |${r[u]||""}
319
- `,u++}let w=g.originalStartLine-1,x=i[w]||"",E=g.oldContent.split(`
320
- `),b=x.match(/^\s*/),C=b?b[0]:"";E.forEach((R,A)=>{let k=R;if(E.length===1&&x.trim().length>0&&x.includes(R.trim()))k=x;else if(A===0){let T=R.match(/^\s*/);(T?T[0]:"").length<C.length&&x.includes(R.trim())&&(k=C+R.trimStart())}c+=`-${d(g.originalStartLine+A)} |${k}
321
- `});let S=u;if(g.finalStartLine!==void 0)S=g.finalStartLine-1+(g.newContent?g.newContent.split(`
322
- `).length:0);else{let R=g.originalStartLine+E.length-1,A=i[R]||null;if(A!==null){let k=y<p.length-1?(p[y+1].originalStartLine||r.length)+10:r.length;for(let T=u;T<k;T++){if(r[T]===A){S=T;break}T===r.length-1&&(S=r.length)}}else S=r.length}for(;u<S;)c+=`+${d(u+1)} |${r[u]||""}
323
- `,u++;f=g}),f!==null){let g=Math.min(r.length,u+3);for(;u<g;)c+=`[UI_CONTEXT] ${d(u+1)} |${r[u]||""}
324
- `,u++}if(s){let g=`[DIFF_START]
325
- `,y=c.substring(g.length),m=`[UI_CONTEXT] ${l}
326
- `,x=y.split(m).map(E=>E.split(`
327
- `).filter(C=>C.trim()!=="").length>45?`[[VERIFIED]]
328
- ${E}
329
- [[/VERIFIED]]`:E);c=g+x.join(m)}return c+="[DIFF_END]",hn(c)},rl=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("|"),r=i!==-1?hn(s.substring(0,i).trim()):"",a=hn(i!==-1?s.substring(i+1):s);return{isR:t,isA:o,num:r,content:a}},al=(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 r=s.length,a=i.length,h=new Int32Array(a+1),d=new Int32Array(a+1);for(let u=0;u<=a;u++)h[u]=u;for(let u=1;u<=r;u++){d[0]=u;let f=s[u-1];for(let p=1;p<=a;p++)f===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[a],l=Math.max(t,o);return l===0?1:1-c/l},Nr=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)),r=Array.from({length:o+1},()=>Array(s+1).fill(""));for(let c=1;c<=o;c++)r[c][0]="up";for(let c=1;c<=s;c++)r[0][c]="left";let a=Array.from({length:o},()=>Array(s).fill(0));for(let c=0;c<o;c++)for(let l=0;l<s;l++)a[c][l]=al(n[c].content.trim(),t[l].content.trim());for(let c=1;c<=o;c++)for(let l=1;l<=s;l++){let u=a[c-1][l-1],f=u>=.2?u:-10,p=i[c-1][l-1]+f,g=i[c-1][l],y=i[c][l-1];p>=g&&p>=y?(i[c][l]=p,r[c][l]="diag"):g>=y?(i[c][l]=g,r[c][l]="up"):(i[c][l]=y,r[c][l]="left")}let h=o,d=s;for(;h>0||d>0;)if(r[h][d]==="diag"){if(a[h-1][d-1]>=.2){let l=n[h-1].index,u=t[d-1].index;e[l].pairContent=e[u].parsed.content,e[u].pairContent=e[l].parsed.content}h--,d--}else r[h][d]==="up"?h--:d--},Gn=new Map,fs=new Map,Pr=200,fi=6,hi=(e,n)=>{n.set(e.key,e),e.type==="chunk"&&e.blocks&&e.blocks.forEach(t=>hi(t,n))},af=(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(pl(e.text||"",e.role==="think")),s=`${e.id}-${n}`,i=new Map;if(e.isStreaming){let p=fs.get(s);p&&o.startsWith(p.text)&&(i=p.blocksMap)}let r=(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),E={...m};return typeof E.pairContent=="string"&&(E.pairContent=hn(E.pairContent)),Array.isArray(E.wrappedLines)&&(E.wrappedLines=E.wrappedLines.map(hn)),{key:p,isStreamingMsg:!!e.isStreaming,workedDuration:e.workedDuration,type:g,text:x,msg:g==="full-message"?e:void 0,...E}};if(o.includes("- Content Preview:")){let p="",g=o.match(/File\s+\[(.*?)\]/i);g&&(p=g[1].split(".").pop().toLowerCase());let E=((o.split("- Content Preview:")[1]||"").split("[SYSTEM] Check the content preview for verification [/SYSTEM]")[0]?.trim()||"").split(`
330
- `).map(T=>T.replace(/\r$/,"")),b=String(E.length).length,C=[],S=null,R=[],A=()=>{if(!R.length)return;let T=R;R=[],C.push(T.length===1?T[0]:{key:`${T[0].key}-chunk`,type:"chunk",blocks:T})},k=n-(b+6);return E.forEach((T,L)=>{let I=L===E.length-1,P=vr(T,k).split(`
331
- `),j=r(`${e.id||Date.now()}-write-line-${L}`,"write-line",T,{gutterWidth:b,lineNum:L+1,isFirstLine:L===0,isLastLine:I,extension:p,wrappedLines:P});I&&e.isStreaming?(A(),S=j):(R.push(j),R.length>=fi&&A())}),A(),{completed:C,active:S?[S]:[]}}if(o.includes("[DIFF_START]")){let p=o.match(/\[DIFF_START\]([\s\S]*?)(?:\[DIFF_END\]|$)/),y=(p?p[1].trim():"").split(`
332
- `).map(S=>S.replace(/\r$/,"")),m=y.map(S=>({line:S,parsed:rl(S),pairContent:null})),w=[];for(let S=0;S<m.length;S++){let R=m[S];R.parsed&&(R.parsed.isR||R.parsed.isA)?w.push(R):w.length>0&&(Nr(w),w=[])}w.length>0&&Nr(w);let x=[],E=null,b=[],C=()=>{if(!b.length)return;let S=b;b=[],x.push(S.length===1?S[0]:{key:`${S[0].key}-chunk`,type:"chunk",blocks:S})};return y.forEach((S,R)=>{let A=R===y.length-1,k=m[R].parsed,T=null;k&&(T=vr(k.content,n-17).split(`
333
- `));let L=r(`${e.id||Date.now()}-diff-${R}`,"diff-line",S,{isFirstLine:R===0,isLastLine:A,pairContent:m[R].pairContent,wrappedLines:T});A&&e.isStreaming?(C(),E=L):(b.push(L),b.length>=fi&&C())}),C(),{completed:x,active:E?[E]:[]}}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:[r(`${e.id||Date.now()}-full`,"full-message",o)],active:[]};if(!o&&!e.isStreaming){let p={completed:[],active:[]};return Gn.set(t,p),p}let a=[],h=null,d=[],c=null,l=()=>{if(!d.length)return;let p=d;d=[],c=null,a.push(p.length===1?p[0]:{key:`${e.id||"x"}-chunk-${p[0].key}`,type:"chunk",blocks:p})},u=(p,g=!1)=>{if(c!==null&&c!==p.type&&l(),d.push(p),c=p.type,d.length>=fi){if(e.isStreaming&&g)return;l()}};if(e.role==="think"){a.push(r(`${e.id}-header`,"think-header",""));let p=o.split(`
334
- `);p.forEach((g,y)=>{let m=y===p.length-1;u(r(`${e.id}-${y}`,"think-line",g,{}),m)}),e.isStreaming||(l(),a.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="",E=0,b=0;p.forEach((C,S)=>{let R=S===p.length-1,A=C.trim().startsWith("|"),k=C.trim().startsWith("```");if(w){if(C.includes("</think>")||C.includes("<channel|>")||C.includes("</thought>")){let T=C.split(/(?:<\/(think|thought|thoughts)>|<channel\|>)/i),L=T[0]||"",I=T.slice(2).join("");L&&u(r(`${e.id}-think-${S}`,"think-line",L,{}),R&&!I),l(),a.push({key:`${e.id}-think-footer-${S}`,type:"think-footer-padding",text:""}),w=!1,I&&I.trim()&&u(r(`${e.id}-${S}`,"agent-line",I,{}),R)}else u(r(`${e.id}-think-${S}`,"think-line",C,{}),R);return}if(!m&&(C.includes("<think>")||C.includes("<|channel>thought")||C.includes("<thought>")||C.startsWith("<think")||C.startsWith("<|channel>thought"))){l(),g&&(a.push(r(`${e.id}-table-${S}`,"table",y.join(`
336
- `),{isStreaming:!1})),g=!1,y=[]),a.push(r(`${e.id}-think-header-${S}`,"think-header","")),w=!0;let T=C.replace(/^(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought\s*)\r?\n?/i,"");if(T.includes("</think>")||T.includes("<channel|>")||T.includes("</thought>")){let L=T.split(/(?:<\/(think|thought|thoughts)>|<channel\|>)/i),I=L[0]||"",P=L.slice(2).join("");I&&u(r(`${e.id}-think-${S}`,"think-line",I,{}),R&&!P),l(),a.push({key:`${e.id}-think-footer-${S}`,type:"think-footer-padding",text:""}),w=!1,P&&P.trim()&&u(r(`${e.id}-${S}`,"agent-line",P,{}),R)}else T&&u(r(`${e.id}-think-${S}`,"think-line",T,{}),R);return}m?k?(m=!1,u(r(`${e.id}-code-close-${b}`,"code-fence-close","",{}),R)):(E++,u(r(`${e.id}-code-line-${S}`,"code-line",C,{lineNum:E,lang:x}),R)):k?(m=!0,b=S,E=0,x=C.trim().replace(/^```/,"").trim(),u(r(`${e.id}-code-open-${S}`,"code-fence-open",x,{}),R)):A?(g=!0,y.push(C),R&&(l(),e.isStreaming?h=r(`${e.id}-table-${S}`,"table",y.join(`
337
- `),{isStreaming:!0}):a.push(r(`${e.id}-table-${S}`,"table",y.join(`
338
- `),{isStreaming:!1})))):(g&&(l(),a.push(r(`${e.id}-table-${S}`,"table",y.join(`
339
- `),{isStreaming:!1})),g=!1,y=[]),u(r(`${e.id}-${S}`,"agent-line",C,{}),R))}),!e.isStreaming&&e.workedDuration&&(l(),a.push(r(`${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 f={completed:a,active:h?[h]:[]};if(e.isStreaming){let p=new Map;if(a.forEach(g=>hi(g,p)),h&&hi(h,p),fs.set(s,{text:o,blocksMap:p}),fs.size>Pr){let g=fs.keys().next().value;fs.delete(g)}}else{if(Gn.set(t,f),Gn.size>Pr){let p=Gn.keys().next().value;Gn.delete(p)}fs.delete(s)}return f},ll={},cl=/<\/think>(\r?\n){2}/gi,dl=/(\r?\n){2}(?=\[?(?:tool:functions|tool\.functions|agent:generalist|agent\.generalist|\s*turn\s*:))/gi,ui=(e,n)=>{let t=!1;for(let o=0;o<n;o++)e[o]==="`"&&(t=!t);return t},fl=/\[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,ul=/(\$?\\?\/?\\rightarrow\$?|\$\\rightarrow\$)|(\$?\\?\/?\\leftarrow\$?|\$\\leftarrow\$)|(\$?\\?\/?\\uparrow\$?|\$\\uparrow\$)|(\$?\\?\/?\\downarrow\$?|\$\\downarrow\$)|(\$?\\?\/?\\leftrightarrow\$?|\$\\leftrightarrow\$)/gi,hl=/\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,Ls=!1,pl=(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(cl,"</think>").replace(dl,(r,a,h,d)=>!Ls&&ui(d,h)?r:"");o&&o.includes("[tool:")&&(o=o.replace(/<(\w+)(?:[^>]*)>\s*([\s\S]*?\[tool:[^\]]*\][\s\S]*?)\s*<\/\1>/gi,(r,a,h)=>h&&h.includes("[tool:")?h.trim():r),Ls&&(o=o.replace(/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi,(r,a)=>a.includes("[tool:")?a.trim():r)),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 r=o.toLowerCase(),a=r.indexOf(s),h=r.indexOf(i),d=s,c=a;if((a===-1||h!==-1&&h<a)&&(d=i,c=h),c===-1)break;if(!Ls&&ui(o,c)){let w=c+d.length,x=r.indexOf(s,w),E=r.indexOf(i,w);if(x===-1&&E===-1)break;let b=-1,C=0;for(;;){let S=r.indexOf(s,C),R=r.indexOf(i,C),A=-1,k=s;if(S===-1&&R===-1)break;if(S===-1||R!==-1&&R<S?(A=R,k=i):A=S,!ui(o,A)){b=A,d=k;break}C=A+k.length}if(b===-1)break;c=b}let l=c,u=!1,f=c-1;for(;f>=0&&/\s/.test(o[f]);)f--;f>=0&&o[f]==="["&&(l=f,u=!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(u){let E=m+1;for(;E<o.length&&/\s/.test(o[E]);)E++;E<o.length&&o[E]==="]"&&(x=E)}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(fl,""),o=o.replace(ul,r=>{let a=r.toLowerCase();return a.includes("leftrightarrow")?"\u2194":a.includes("rightarrow")?"\u2192":a.includes("leftarrow")?"\u2190":a.includes("uparrow")?"\u2191":a.includes("downarrow")?"\u2193":r}),o=o.replace(hl,r=>ll[r.toLowerCase()]||r),o.trim()},lf=()=>{Gn.clear(),fs.clear()};var mi=async(e,n={})=>{let t=_(e),o=t.path;if(!o)return'ERROR: Missing "path" argument for PatchFile.';let{patchPairs:s,allowMultiple:i,error:r}=Ao(t);if(r)return`ERROR: ${r}`;if(s.length===0)return"ERROR: No valid replacement pairs found. Use searchContent1, newContent1, etc.";let a=t.allowMultiple!==void 0?t.allowMultiple===!0||String(t.allowMultiple).toLowerCase()==="true":i,h=ml.resolve(process.cwd(),o);try{if(!pi.existsSync(h))return`ERROR: File [${o}] does not exist. Use WriteFile instead.`;let d=n.forcedContent||pi.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:u}=$o(c,s,{allowMultiple:a}),f=u.filter(m=>!m.success),p=u.filter(m=>m.success);if(p.length===0)return`ERROR: Patch Failed to apply to [${o}].
342
- ${f.map(m=>` \u2022 ${m.error}`).join(`
343
- `)}`;await ft.recordFileChange(h,c),pi.writeFileSync(h,l,"utf8");let{systemSettings:g}=await Dt(),y=Oo(c,l,u,12,g?.compressToolResults);return f.length>0?`SUCCESS: File [${o}] updated with some blocks failed. [${p.length}/${s.length}] blocks applied.
344
-
345
- Failures:
346
- ${f.map(m=>` \u2022 ${m.error}`).join(`
347
- `)}
348
-
349
- ${y}`:`SUCCESS: File [${o}] updated. [${u.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 us from"fs";import gi from"path";var gl=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"]),yl=e=>gl.has(e)||e.startsWith(".pnpm"),wl=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"}},yi=async e=>{let n=_(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=gi.resolve(process.cwd(),t);try{if(!us.existsSync(s))return`ERROR: Path [${t}] does not exist.`;if(!us.statSync(s).isDirectory())return`ERROR: Path [${t}] is a file, not a directory. Use ReadFile instead.`;if(o===1){let g=us.readdirSync(s),y=g.length,m=150,w=g.slice(0,m),x=[];for(let C of w){let S=gi.join(s,C),R={name:C,type:"unknown",size:"N/A",mtime:"N/A"};try{let A=us.statSync(S);R={name:C,type:A.isDirectory()?"directory":"file",size:(A.size/1024).toFixed(1)+"KB",mtime:wl(A.mtime)}}catch{R.type="inaccessible"}x.push(R)}let E=x.map(C=>C.type==="directory"?`${C.name}/`:`${C.name} (${C.size}, ${C.mtime})`).join(`
352
- `),b=`
353
-
354
- (Total items in folder: ${y})`;return y>m&&(b=`
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
- ${E}${b}`}let r=0,a=0,h=0,d=500,c=!1,l=(g,y,m=1)=>{if(y>o||c)return[];let w=[];try{w=us.readdirSync(g)}catch{return[`${" ".repeat(m-1)}[Inaccessible Directory]`]}let x=[],E=[];for(let R of w){let A=gi.join(g,R),k=!1;try{k=us.statSync(A).isDirectory()}catch{}k?x.push({name:R,fullPath:A}):E.push({name:R,fullPath:A})}x.sort((R,A)=>R.name.localeCompare(A.name)),E.sort((R,A)=>R.name.localeCompare(A.name));let b=[],C=" ".repeat(m-1);for(let R of x){if(h>=d){c=!0,b.push(`${C}[Truncated - Maximum item limit reached (${d})]`);break}if(h++,r++,b.push(`${C}${R.name}/`),y<o&&!yl(R.name)){let A=l(R.fullPath,y+1,m+1);b.push(...A)}}let S=[];for(let R of E){if(h>=d){c=!0,b.push(`${C}[Truncated - Maximum item limit reached (${d})]`);break}h++,a++;let A="N/A";try{A=(us.statSync(R.fullPath).size/1024).toFixed(1)+"KB"}catch{}S.push(`${R.name} (${A})`)}return S.length>0&&b.push(`${C}${S.join("; ")}`),b},f=l(s,1,1).join(`
359
- `),p=`
360
-
361
- (Total items scanned: ${h}, Directories: ${r}, Files: ${a})`;return c&&(p=`
362
-
363
- TRUNCATED: Scan capped at ${d} items. (Directories: ${r}, Files: ${a})`),`Detailed directory tree for [${t}] (recursive depth: ${o}):
364
-
365
- ${f}${p}`}catch(i){let r=i instanceof Error?i.message:String(i);return`ERROR: Failed to read folder [${t}]: ${r}`}};var wi=async(e,n)=>{let t=_(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 r=t[i];if(typeof r=="string"&&r.includes("::")){let[a,h]=r.split("::");s.push({id:i,label:a.trim(),description:h.trim()})}else s.push({id:i,label:String(r).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 Sl from"puppeteer";import vs from"path";import hs from"fs-extra";import{PDFDocument as Tl}from"pdf-lib";var Si=async e=>{let{path:n,content:t,orientation:o="portrait",margin:s="0px"}=_(e);if(!n)return'ERROR: Missing "path" argument for write_pdf.';if(!t)return'ERROR: Missing "content" (HTML/CSS) for write_pdf.';let i=vs.resolve(process.cwd(),n),r=null;try{await hs.ensureDir(vs.dirname(i)),await ft.recordFileChange(i);let a=ds();r=await Sl.launch({headless:!0,executablePath:a.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let h=await r.newPage(),d=t,c={},l=async S=>{if(!S||S.startsWith("http://")||S.startsWith("https://")||S.startsWith("data:"))return null;try{let R=vs.resolve(process.cwd(),S);if(await hs.pathExists(R)){let A=vs.extname(R).toLowerCase().replace(".","")||"png",k=A==="jpg"?"jpeg":A==="svg"?"svg+xml":A,T=await hs.readFile(R,"base64");return`data:image/${k};base64,${T}`}}catch{}return null},u=/<link[^>]+href=["']([^"']+)["']/gi,f={},p;for(;(p=u.exec(t))!==null;){let S=p[1],R=p[0];if(S&&R.toLowerCase().includes("stylesheet")&&!S.startsWith("http://")&&!S.startsWith("https://")&&!S.startsWith("data:"))try{let A=vs.resolve(process.cwd(),S);if(await hs.pathExists(A)){let k=await hs.readFile(A,"utf-8");f[R]=`<style>${k}</style>`}}catch{}}for(let[S,R]of Object.entries(f))d=d.split(S).join(R);let g=/<img[^>]+src=["']([^"']+)["']/gi;for(;(p=g.exec(d))!==null;){let S=p[1];if(S&&!c[S]){let R=await l(S);R&&(c[S]=R)}}let y=/url\(\s*['"]?([^'")]+?)['"]?\s*\)/gi;for(;(p=y.exec(d))!==null;){let S=p[1].trim();if(S&&!c[S]){let R=await l(S);R&&(c[S]=R)}}for(let[S,R]of Object.entries(c)){let A=S.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&"),k=new RegExp(`(src=["'])(${A})(["'])`,"gi");d=d.replace(k,`$1${R}$3`);let T=new RegExp(`url\\(\\s*(['"]?)(${A})\\1\\s*\\)`,"gi");d=d.replace(T,`url($1${R}$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 Tl.load(w),E=vs.basename(n);x.setTitle(`FluxFlow_${E}`),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 b=await x.save();await hs.writeFile(i,b);let C=await hs.stat(i);return`SUCCESS: PDF generated successfully at [${n}] (${(C.size/1024).toFixed(2)} KB).`}catch(a){let h=a instanceof Error?a.message:String(a);return`ERROR: Failed to generate PDF [${n}]: ${h}`}finally{r&&await r.close()}};import Dr from"fs-extra";import Ti from"path";import El from"html-to-docx";var Ei=async e=>{let{path:n,content:t}=_(e);if(!n)return'ERROR: Missing "path" argument for write_docx.';if(!t)return'ERROR: Missing "content" (HTML) for write_docx.';let o=Ti.resolve(process.cwd(),n);try{await Dr.ensureDir(Ti.dirname(o)),await ft.recordFileChange(o);let s=Ti.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
- `,r=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 Dr.writeFile(o,r),`SUCCESS: Word document [${n}] generated successfully.
407
- - Size: ${(r.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 ps from"path";import xi from"fast-glob";import{Minimatch as Fr}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 r of i){let a=ps.join(e,r.name),h=ps.relative(t,a),d=h.split(ps.sep).map(u=>u.toLowerCase()),c=r.name.toLowerCase();if(!n.some(u=>{let f=u.toLowerCase();return f.startsWith(".")&&c.endsWith(f)?!0:d.some(p=>p===f||p.startsWith(".pnpm"))}))if(r.isDirectory()){let u=await Zs(a,n,t,o+1);s=s.concat(u)}else r.isFile()&&s.push({fullPath:a,relativePath:h})}return s}function xl(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],r=s;for(let a=1;a<=n.length;a++){let h=e[s-1]===n[a-1]?0:1,d=Math.min(i[a-1]+1,o[a]+1,o[a-1]+h);i.push(d),d<r&&(r=d)}if(o=i,r>t)return t+1}return o[n.length]}function Rl(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(r=>r.length>0),i=o.split(/[^a-z0-9]+/).filter(r=>r.length>1||o.length===1&&r.length>0);return i.length===0?!1:i.every(r=>{let a=r.length<=2?0:r.length<=5?1:2;for(let h of s)if(h.includes(r)||r.length>=3&&h.length>=3&&Math.abs(h.length-r.length)<=a&&xl(r,h,a)<=a)return!0;return!1})}var eo=async e=>{let{keyword:n,path:t,fuzzy:o,subString:s,regex:i}=_(e);if(n==null)return'ERROR: Missing "keyword" argument.';let r=String(n),a=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=a(o)||a(s),l=null,u=null;if(h)c||(u=new RegExp(`(?<![\\w])${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\\w])`,"i"));else{try{l=new RegExp(r,"i")}catch(g){if(d)return`ERROR: Invalid regex pattern "${r}": ${g.message}`}u=new RegExp(`(?<![\\w])${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\\w])`,"i")}let f=[".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 I=t.split(";").map(G=>G.trim()).filter(Boolean),P=I.some(G=>G.startsWith("!"));if(I.some(G=>xi.isDynamicPattern(G)||/[*?{}[\]()|+]/.test(G))){m="glob";let G=t.replace(/\\/g,"/"),ee=I.map(F=>F.replace(/\\/g,"/")),he=f.map(F=>F.startsWith(".")?`**/*${F}`:`**/${F}/**`);if(P&&!I.some(F=>!F.startsWith("!"))){let F=await Zs(y,f,y),B=O=>O.endsWith("/")?O+"**":O,ie=ee.filter(O=>O.startsWith("!")).map(O=>B(O.slice(1))),be=ee.filter(O=>!O.startsWith("!")).map(B);g=F.filter(O=>{let D=O.relativePath.replace(/\\/g,"/"),V=be.length===0||be.some(De=>{try{return new Fr(De).match(D)}catch{return!1}}),z=ie.some(De=>{try{return new Fr(De).match(D)}catch{return!1}});return V&&!z})}else{let F=ee.some(ie=>/[\(\)\|]|\.\*/.test(ie)),B=[];if(!F)try{B=await xi(ee,{cwd:y,ignore:he,dot:!0,onlyFiles:!0,absolute:!1})}catch{B=[]}if(B.length===0&&(F||xi.isDynamicPattern(G))){let ie=G.match(/^([^\*\?\(\)\|\[\]\s]+)\//),be=ie&&!/[\*\?\(\)\|\[\]]/.test(ie[1])?ps.resolve(y,ie[1]):y,O=await Zs(be,f,y);try{let D=G.replace(/^\.\//,"");D=D.replace(/\.\*\/(\\.|[^\/])/g,".*$1"),!D.startsWith("^")&&!D.startsWith(".*")&&(D=`.*${D}`);let V=new RegExp(D.endsWith("$")?D:`${D}$`,"i");g=O.filter(z=>{let De=z.relativePath.replace(/\\/g,"/");return V.test(De)})}catch{g=[]}}else g=B.map(ie=>({fullPath:ps.resolve(y,ie),relativePath:ie}))}}else{let G=t.replace(/[\/\\]+$/,""),ee=ps.resolve(y,G);try{let he=await Ri.stat(ee);if(he.isDirectory())m="dir",g=await Zs(ee,f,y);else if(he.isFile())m="file",g.push({fullPath:ee,relativePath:ps.relative(y,ee)});else return`ERROR: Path is neither a file nor a directory: ${t}`}catch{return`ERROR: Path not found: ${t}`}}}else g=await Zs(y,f);let w=g.map(async I=>{try{let P=await Ri.readFile(I.fullPath,"utf-8");if(P.includes("\0"))return[];let j=P.split(/\r?\n/),G=[];for(let he=0;he<j.length;he++)(c?j[he].toLowerCase().includes(r.toLowerCase())||Rl(j[he],r):h?u&&u.test(j[he]):l&&l.test(j[he])||u&&u.test(j[he]))&&G.push({line:he+1,content:j[he].trim()});return G.length===0?null:{path:I.relativePath.replace(/\\/g,"/"),matches:G}}catch{return[]}}),x=await Promise.all(w),E=[],b=0;for(let I of x){if(!I||!I.matches)continue;if(b>=p)break;let P=p-b,j=I.matches.slice(0,P);E.push({path:I.path,matches:j}),b+=j.length}typeof global.gc=="function"&&global.gc();let C=c?"(fuzzy mode)":d?"(regex mode)":h?"(keyword mode)":"(standard mode)";if(E.length===0){let I=m==="file"?` in '${t}'`:m==="dir"||m==="glob"?` in '${t}'`:". Try to specify files",P=m==="dir"?"[DIR]":m==="glob"?"[GLOB]":"";return`${P}${P?" ":""}Found 0 matches of '${r}'${I}${C?` ${C}`:""}`}let S=C?` ${C}`:"",R=`${E.length} file${E.length===1?"":"s"}`,A=`${b} match${b===1?"":"es"}`,k;m==="file"?k=`Found ${A} of '${r}' in '${t}'${S}:`:m==="dir"||m==="glob"?k=`Found ${A} of '${r}' in '${t}' across ${R}${S}:`:k=`Found ${A} of '${r}' across ${R}${S}:`;let T=m==="dir"?"[DIR]":m==="glob"?"[GLOB]":"",L=`${T}${T?" ":""}${k}
408
-
409
- `;for(let I of E){L+=`${I.path}
410
- `;for(let P of I.matches)L+=` ${P.line}: ${P.content}
411
- `;L+=`
412
- `}return L.trimEnd()}catch(g){return`ERROR: ${g.message}`}};import Ur from"fs-extra";import bi from"path";var bl=(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 r=0;r<256;r++){let a=r;for(let h=0;h<8;h++)a&1?a=3988292384^a>>>1:a=a>>>1;o[r]=a}let s=r=>{let a=4294967295;for(let h=0;h<r.length;h++)a=o[(a^r[h])&255]^a>>>8;return(a^4294967295)>>>0},i=(r,a)=>{let h=Buffer.from(r,"ascii"),d=Buffer.from(a,"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 u=s(l.subarray(4,8+c));return l.writeUInt32BE(u,8+c),l};for(let[r,a]of Object.entries(n))a!=null&&t.push(i(r,String(a)));if(t.length===0)return e;if(e.subarray(12,16).toString("ascii")==="IHDR"){let a=e.subarray(0,33),h=e.subarray(33);return Buffer.concat([a,...t,h])}return e}catch{return e}},ki=async(e,n={})=>{let t=_(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 r=["nsfw","naked","nudity","nude","porn","sex","xxx","erotic","gore","bloody","violence","abuse","suicide","murder","hentai","pedophile","rape"],a=o.toLowerCase();if(r.some(d=>a.includes(d)))return"ERROR: Prompt blocked by system safety filter (inappropriate or unsafe content detected).";try{let d=await Dt();if(!await br(d))return`ERROR: Insufficient Quota for selected quality. Either tell user reduce quality or wait for next refresh cycle (${(await kr()).nextResetMin||60}m).`;let l=d.imageSettings||{keyType:"Default",quality:"Low-High",apiKey:""},u=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 P=i.replace(/\s+/g,"");P==="16:9"?(g=1024,y=576):P==="9:16"?(g=576,y=1024):P==="4:3"?(g=1024,y=768):P==="3:4"?(g=768,y=1024):P==="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")}`,E=await fetch(x,{method:"GET",headers:{Authorization:`Bearer ${u}`}});if(!E.ok){let P=E.status,j="";try{j=await E.text()}catch{}return P===402||j.includes("Insufficient balance")||j.includes("PAYMENT_REQUIRED")?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed with status [${P}]: ${j||"Unknown API Error"}`}if((E.headers.get("content-type")||"").includes("application/json")){let P=await E.json();return P.status===402||P.error&&P.error.code==="PAYMENT_REQUIRED"?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed: ${P.error?.message||JSON.stringify(P)}`}let C=await E.arrayBuffer(),S=Buffer.from(C),R={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)};S=bl(S,R);let A=bi.resolve(process.cwd(),s);await Ur.ensureDir(bi.dirname(A)),await ft.recordFileChange(A),await Ur.writeFile(A,S),await Cr(d);let k=bi.extname(s).toLowerCase(),L={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".webp":"image/webp"}[k]||"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:S.toString("base64"),mimeType:L}}}:`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 r=new RegExp(`${i}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),a=e.match(r);return a?a[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(Jt,{}),r=X(In,{});return r[o]=s,delete i[o],ue(In,r),ue(Jt,i),`SUCCESS: Saved summary and purged raw memories for chat [${o}].`}catch(i){let r=i instanceof Error?i.message:String(i);return`ERROR: Failed to save summary for chat [${o}]: ${r}`}};var Ns=async(e,n={})=>{let o=(s=>{let i=new RegExp(`${s}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),r=e.match(i);return r?r[2].trim():null})("id");if(!o)return"ERROR: Missing 'id' parameter for addMemScore tool.";try{let s=X(Pt,[]),i=!1,r=[];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&&r.push(c);if(ue(Pt,r),!i)return`WARNING: Memory ID [${o}] not found. Other memories decayed by -0.01.`;let a=r.find(c=>c.id===o),h=a?a.score.toFixed(2):"deleted (score <= 0)",d=s.length-r.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 Ai from"fs-extra";import gs from"path";import{createRequire as Al}from"module";import ms from"fs-extra";import Ci from"path";import kl from"https";var Br={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 Cl(e,n=null){let t=n||`https://unpkg.com/tree-sitter-wasms@0.1.13/out/${e}`,o=Ci.join(as,e);return await ms.ensureDir(as),new Promise((s,i)=>{let r={headers:{"User-Agent":"FluxFlow-Agent"}};kl.get(t,r,a=>{if([301,302,307,308].includes(a.statusCode)&&a.headers.location){let d=a.headers.location;if(!d.startsWith("http")){let c=new URL(t);d=`${c.protocol}//${c.host}${d}`}Cl(e,d).then(s).catch(i);return}if(a.statusCode!==200){i(new Error(`Failed to download ${e}: HTTP ${a.statusCode}`));return}let h=ms.createWriteStream(o);a.pipe(h),h.on("finish",()=>{h.close(),s()})}).on("error",a=>{ms.existsSync(o)&&ms.unlink(o,()=>{}),i(a)})})}function ru(e){let n=Ci.join(as,e);return ms.existsSync(n)}async function au(e){let n=Ci.join(as,e);ms.existsSync(n)&&await ms.unlink(n)}var jr=Al(import.meta.url),Wr=jr("web-tree-sitter"),Hr=!1,Gr=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"]),Yr=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 Kr(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=Kr(o);if(s)return s;if(!Yr.has(o.type))break;o=o.parent}}return null}function $l(e){let n=[];function t(o){for(let s of o.children)Gr.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 qr(e,n=0,t=!0,o="",s=null,i=12){let r=e.type,a=Kr(e),h=Gr.has(r)||n===0,d=$l(e),c=h&&n>0&&(Yr.has(r)&&d.length>0||a!==null&&a===s&&d.length>0),l="",u=o,f=n,p=s;if(h&&!c){let g=e.startPosition.row+1,y=e.endPosition.row+1,m=Ol(r),w=a?`${m} [${a}]`:m;n===0?(l+=`\u{1F4C1} ROOT (Lines: ${g}-${y})
415
- `,u=o):(l+=`${o}${t?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 "}${w} (Lines: ${g}-${y})
416
- `,u+=t?" ":"\u2502 "),f=n+1,p=a}return f>i&&d.length>0?l+=`${u}\u2514\u2500\u2500 ... depth exceeded ...
417
- `:d.forEach((g,y)=>{let m=y===d.length-1;l+=qr(g,f,c?t&&m:m,u,p,i)}),l}var $i=async e=>{let n;try{n=_(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=gs.isAbsolute(n)?n:gs.resolve(process.cwd(),n);if(!Ai.existsSync(t))return`ERROR: File not found: ${n}`;let o=gs.extname(t).slice(1).toLowerCase(),s=Br[o];if(!s)return`ERROR: Unsupported file extension: .${o}`;let i=gs.resolve(as,s);if(!Ai.existsSync(i))return`ERROR: Parser for .${o} not found. Please download it in Settings > Other.`;try{let r=Wr.Parser;if(!Hr){let p;try{p=gs.join(gs.dirname(jr.resolve("web-tree-sitter")),"tree-sitter.wasm")}catch{p=gs.join(process.cwd(),"node_modules","web-tree-sitter","tree-sitter.wasm")}await r.init({locateFile:g=>g==="tree-sitter.wasm"||g.endsWith("tree-sitter.wasm")?p:g}),Hr=!0}let a=new r,h=await Wr.Language.load(i);a.setLanguage(h);let d=await Ai.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 u=a.parse(d),f=qr(u.rootNode,0,!0," ",null,l);return`\u{1F4C4} File Map for: ${n}
419
- ${f}`}catch(r){let a=r instanceof Error?r.message:typeof r=="object"?JSON.stringify(r):String(r),h=r instanceof Error?`
420
- Stack: ${r.stack}`:"";return`ERROR: Failed to map file: ${a}${h}`}};import Yn from"fs";import Vr from"path";var zr=async(e,n={})=>{let{method:t,tasks:o,markDone:s}=_(e),i=n.chatId||"default";if(!t)return'ERROR: Missing "method" argument for todo tool (create/append/get).';let r=Vr.join(_n,"plan",i),a=Vr.join(r,"todo.md"),h=l=>{if(!l||Array.isArray(l))return l;let u=String(l).trim();if(u.startsWith("[")&&u.endsWith("]")){let f=u.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);return f?f.map(p=>p.slice(1,-1).replace(/\\(.)/g,"$1")):u.slice(1,-1).split(",").map(p=>p.trim()).filter(Boolean)}return l},d=l=>{let u=h(l);return u?(Array.isArray(u)?u:String(u).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,u)=>{if(!u)return{content:l,markedCount:0};let f=h(u),p=(Array.isArray(f)?f:[f]).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 E=0;E<g.length;E++)if(g[E].includes(w)&&/^- \[\s\]/.test(g[E].trim())){g[E]=g[E].replace("- [ ]","- [x]"),x=!0,m=!0,y++;break}if(!x){for(let E=0;E<g.length;E++)if(g[E].toLowerCase().includes(w.toLowerCase())&&/^- \[\s\]/.test(g[E].trim())){g[E]=g[E].replace("- [ ]","- [x]"),x=!0,m=!0,y++;break}}}return{content:m?g.join(`
425
- `):l,markedCount:y}};try{if(Yn.existsSync(r)||Yn.mkdirSync(r,{recursive:!0}),t==="create"){if(!o)return'ERROR: Missing "tasks" for create method.';let l=d(o),u=0;if(s){let p=c(l,s);l=p.content,u=p.markedCount}await ft.recordFileChange(a),Yn.writeFileSync(a,l,"utf8");let f=l.split(/\r?\n/).map(p=>p.trim()).filter(p=>p.startsWith("- [ ]")||p.startsWith("- [x]")||p.startsWith("- [X]")).length;if(u>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 (${u} marked done, ${p} completed, ${f-p} left)
426
- ${l}`}return`SUCCESS: TASK LIST CREATED (${f} total)
427
- ${l}`}if(t==="append"){if(!o)return'ERROR: Missing "tasks" for append method.';let l=d(o);await ft.recordFileChange(a),Yn.appendFileSync(a,l,"utf8");let u=Yn.readFileSync(a,"utf8"),f=u.split(/\r?\n/).map(m=>m.trim()),p=f.filter(m=>m.startsWith("- [ ]")||m.startsWith("- [x]")||m.startsWith("- [X]")).length,g=f.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
- ${u}`}if(t==="get"){if(!Yn.existsSync(a))return"TODO GET: No task list found for this session.";let l=Yn.readFileSync(a,"utf8"),u=0;if(s){let m=c(l,s);m.markedCount>0&&(l=m.content,u=m.markedCount,await ft.recordFileChange(a),Yn.writeFileSync(a,l,"utf8"))}let f=l.split(/\r?\n/).map(m=>m.trim()),p=f.filter(m=>m.startsWith("- [ ]")||m.startsWith("- [x]")||m.startsWith("- [X]")).length,g=f.filter(m=>m.startsWith("- [x]")||m.startsWith("- [X]")).length;return`${u>0?`SUCCESS: ${u} 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 Oi=async(e,n={})=>{let{runSubagent:t}=await import("./ai-GO5NYAPZ.js"),o=_(e),s=o.task||o.instruction||o.prompt,i=o.model||null,r=o.tools||null;if(!s)return'ERROR: Missing "task" argument for invokeSync.';let a=null;if(r)try{let d=r.trim();d.startsWith("[")&&d.endsWith("]")&&(d=d.substring(1,d.length-1)),a=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,a,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-GO5NYAPZ.js"),l=d.message==="Subagent task was cancelled by user."||c();if(n.onVisualFeedback){let u=l?"[CANCELLED]":"[FAILED]";n.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${h} ${u}
431
- `)}return`ERROR: Subagent execution failed: ${d.message}`}};var Xr=async(e,n={})=>{let{runSubagent:t}=await import("./ai-GO5NYAPZ.js"),o=_(e),s=o.task||o.instruction||o.prompt,i=o.model||null,r=o.title||null,a=o.tools||null;if(!s)return'ERROR: Missing "task" argument for invoke.';let h=null;if(a)try{let m=a.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,u=new Promise((m,w)=>{c=m,l=w}),f={id:d,title:r||s.substring(0,30),task:s,status:"running",startedAt:Date.now(),lastChunkTime:Date.now(),wps:0,questions:[],pendingSteerMessages:[],steer:m=>{m&&f.pendingSteerMessages.push(m)},completionPromise:u,_resolveCompletion:c,_rejectCompletion:l,progress:[]},p={chunks:[],totalWords:0};Ve.push(f),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,E=new Promise(S=>{x=S}),b={id:w,question:m,answered:!1,answer:null,askedAt:Date.now(),_resolve:x};return f.questions.push(b),f.status="waiting",n.onSubagentUpdate&&n.onSubagentUpdate(),yo(`[SYSTEM] Background subagent "${f.title}" is WAITING FOR YOUR INPUT: "${m}"
432
- Respond using tool: [tool:functions.Answer(id="${d}", answer="...")]
433
- [/SYSTEM]`),await E},onVisualFeedback:m=>{f.lastChunkTime=Date.now();let w=m.replace(/\x1b\[[0-9;]*m/g,""),x=w.match(/[✔✘✗✖🔍📖→➕↻•]\s*([A-Za-z0-9\s-]+)/);x?f.currentTool=x[1].trim():f.currentTool=w,n.onSubagentUpdate&&n.onSubagentUpdate()},onTokenChunk:(m,w)=>{let x=Date.now();if(f.lastChunkTime=x,f.currentTool="Thinking",typeof w=="number"&&w>0){p.totalWords+=w,p.chunks.push({time:x,words:w});let E=x-400;if(p.chunks=p.chunks.filter(b=>b.time>=E),p.chunks.length>0){let b=p.chunks.reduce((R,A)=>R+A.words,0),C=p.chunks[0].time,S=Math.max(.4,(x-C)/1e3);f.wps=Math.round(b/S*10)/10}}n.onSubagentUpdate&&n.onSubagentUpdate()}};return t(s,y,i,h,50,m=>{if(f.status==="cancelled")return;if(m.startsWith("[Subagent Turn")&&g.length>0&&(f.progress.push([...g]),g=[]),m.includes("[Executing Tool]")){let x=m.match(/\[Executing Tool\]\s*([a-zA-Z0-9_]+)/);x&&(!f.currentTool||f.currentTool==="Thinking")&&(f.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(f.status==="cancelled"){f._resolveCompletion&&f._resolveCompletion(m);return}g.length>0&&(f.progress.push([...g]),g=[]),f.status="completed",f.finalAnswer=m,n.onSubagentUpdate&&n.onSubagentUpdate(),yo(`[SYSTEM] Background subagent "${f.title}" (id: ${d}) has FINISHED. Call GetProgress(id="${d}") to see the final result. [/SYSTEM]`),f._resolveCompletion&&f._resolveCompletion(m)}).catch(async m=>{let{isTerminationSignaled:w}=await import("./ai-GO5NYAPZ.js");if(m.message==="Subagent task was cancelled."||f.status==="cancelled"||w()){f.status="cancelled",g.push("[SUBAGENT CANCELLED] Task was cancelled."),f.progress.push([...g]),n.onSubagentUpdate&&n.onSubagentUpdate(),f._resolveCompletion&&f._resolveCompletion(null);return}g.push(`[SUBAGENT FAILURE] Error: ${m.message}`),f.progress.push([...g]),f.status="failed",f.error=m.message,n.onSubagentUpdate&&n.onSubagentUpdate(),yo(`[SYSTEM] Background subagent "${f.title}" (id: ${d}) FAILED with error: ${m.message}. [/SYSTEM]`),f._rejectCompletion&&f._rejectCompletion(m)}),`SUCCESS: Background subagent started. Task ID: ${d}`};var Mi=async(e,n={})=>{let o=_(e).id;if(!o)return'ERROR: Missing "id" argument for getProgress.';let s=Ve.find(a=>a.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 a=Math.floor((Date.now()-s.startedAt)/1e3);i+=`Elapsed Time: ${a}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 a=s.questions.filter(h=>!h.answered);a.length>0&&(i+=`
444
- **PENDING QUESTION**
445
- `,a.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((a,h)=>{i+=`--- Turn ${h+1} ---
451
- `;let c=a.filter(l=>!l.startsWith("[SUBAGENT SUCCESS]")).map(l=>{if(l.startsWith("[Subagent Response]")){let u="[Subagent Response]",p=l.substring(u.length),g="tool:functions.";for(;;){let m=p.toLowerCase().indexOf(g);if(m===-1)break;let w=m,x=!1,E=m-1;for(;E>=0&&/\s/.test(p[E]);)E--;E>=0&&p[E]==="["&&(w=E,x=!0);let b=0,C=!1,S=null,R=m;for(;R<p.length;){let A=p[R];if(!S&&(A==="'"||A==='"'||A==="`")?S=A:S&&A===S&&p[R-1]!=="\\"&&(S=null),S||(A==="("?(b++,C=!0):A===")"&&b--),C&&b===0&&!S){let k=R;if(x){let T=R+1;for(;T<p.length&&/\s/.test(p[T]);)T++;T<p.length&&p[T]==="]"&&(k=T)}p=p.substring(0,w)+p.substring(k+1);break}if(R++,R===p.length){p=p.substring(0,w);break}}}return u+`
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 Jr=async(e,n={})=>{let o=_(e).id;if(!o)return'ERROR: Missing "id" argument for cancel.';let s=Ve.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 Et from"path";var Ml=["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(Ml.includes(s.name))continue;let i=Et.join(e,s.name),r=Et.relative(n,i).replace(/\\/g,"/");if(s.isDirectory()){let a=await no(i,n);Object.assign(t,a)}else{let a=await wt.stat(i).catch(()=>null);a&&(t[r]={size:a.size,mtime:a.mtimeMs})}}return t}async function Qr(e,n){await wt.ensureDir(e);for(let t of Object.keys(n)){let o=Et.join(process.cwd(),t),s=Et.join(e,t);await wt.ensureDir(Et.dirname(s)),await wt.copyFile(o,s).catch(()=>{})}}async function _i(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 r=Et.join(e,i.name),a=Et.join(n,i.name);if(i.isDirectory())await _i(r,a,t,o);else{let h=Et.relative(o,r).replace(/\\/g,"/"),d=await wt.pathExists(a);d&&await wt.chmod(a,438).catch(()=>{}),await wt.ensureDir(Et.dirname(a));let c=await wt.copyFile(r,a).then(()=>!0).catch(()=>!1);await wt.chmod(a,438).catch(()=>{}),t&&(c?d?t.replaced++:t.restored++:t.failed.push(h))}}}var Kn={async takeInitialSnapshot(e){try{let n=Et.join(_n,"snapshots",e);await wt.remove(n).catch(()=>{}),await wt.ensureDir(n);let t=await no(process.cwd());await Qr(Et.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:[]}]},ue(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,r=await no(process.cwd()),a=[],h=[],d=[];for(let[l,u]of Object.entries(r)){let f=i[l];f?(f.size!==u.size||f.mtime!==u.mtime)&&h.push(l):a.push(l)}for(let l of Object.keys(i))r[l]||d.push(l);let c=[...a,...h];if(c.length>0||d.length>0){let l={};for(let f of c)l[f]=r[f];let u=Et.join(_n,"snapshots",e,`turn_${n}`);await Qr(u,l)}s.checkpoints.push({id:`turn_${n}`,timestamp:new Date().toISOString(),newFiles:a,modifiedFiles:h,deletedFiles:d,toolsUsed:t}),s.currentManifest=r,ue(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 r=Et.join(_n,"snapshots",e),a={restored:0,replaced:0,failed:[]},h=await no(process.cwd());for(let c of Object.keys(h)){let l=Et.join(process.cwd(),c);await wt.chmod(l,438).catch(()=>{}),await wt.remove(l).catch(()=>{})}let d=Et.join(r,"initial");await _i(d,process.cwd(),a,d);for(let c=1;c<=i;c++){let l=s[c],u=Et.join(r,l.id);if(await _i(u,process.cwd(),a,u),l.deletedFiles&&l.deletedFiles.length>0)for(let f of l.deletedFiles){let p=Et.join(process.cwd(),f);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()),ue(dn,t),{checkpointId:n,stats:a}}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=Et.join(_n,"snapshots",e);await wt.remove(n).catch(()=>{});let t=X(dn,{});t[e]&&(delete t[e],ue(dn,t))}catch{}}};var Ii=async(e,n={})=>{let t=_(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 a=await Kn.getCheckpoints(i);if(a.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 a)if(l.id==="initial")c+=`--- Initial State (id: initial) ---
464
- Tools Used: User Prompted for task
465
-
466
- `;else{let u=l.id.replace("turn_",""),f=l.toolsUsed&&l.toolsUsed.length>0?l.toolsUsed.map(d).join(", "):"None";c+=`--- Turn ${u} (id: ${l.id}) ---
467
- Tools Used: ${f}
468
-
469
- `}return c.trim()}else if(o==="forceRevert"){if(!s)return"ERROR: Missing required parameter 'id' for forceRevert.";try{let a=await Kn.rollbackToCheckpoint(i,s),{checkpointId:h,stats:d}=a,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(a){return`ERROR: ${a.message}`}}else return`ERROR: Invalid method "${o}". Use "getCheckpoint" or "forceRevert".`};var Ps=async(e,n={})=>{let t=_(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=Ve.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 r,a=new Promise(h=>{r=setTimeout(()=>{h({type:"timeout"})},s*1e3)});try{let h=await Promise.race([i.completionPromise.then(()=>({type:"completion"})),a]);return clearTimeout(r),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(r),`ERROR: Exception while awaiting subagent [${o}]: ${h.message}`}};var Ds=async(e,n={})=>{let t=_(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=Ve.find(a=>a.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 r=i.questions.filter(a=>!a.answered);return r.length===0?`INFO: Subagent task [${o}] has no unanswered questions.`:(r.forEach(a=>{a.answered=!0,a.answer=s,a.answeredAt=Date.now(),a._resolve&&a._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=_(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=Ve.find(r=>r.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 N,Point as io,clipboard as _l}from"@nut-tree-fork/nut-js";on.config.autoDelayMs=50;mn.config.autoDelayMs=50;async function Zr(){try{await mn.releaseKey(N.LeftControl,N.RightControl,N.LeftAlt,N.RightAlt,N.LeftShift,N.RightShift,N.LeftSuper,N.RightSuper)}catch{}}async function gn(e,n,t={}){let o=await ls(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 ls(t.from||n),i=await ls(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 ls({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 r=i>50?Math.min(20,Math.max(1,Math.round(i/100))):Math.min(20,i),a=t.direction==="up";for(let h=0;h<r;h++)a?await on.scrollUp(120):await on.scrollDown(120),await new Promise(d=>setTimeout(d,20));return`SUCCESS: Scrolled ${t.direction||"down"} (${r} 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 ea={enter:N.Enter,return:N.Return,escape:N.Escape,esc:N.Escape,backspace:N.Backspace,tab:N.Tab,space:N.Space,up:N.Up,down:N.Down,left:N.Left,right:N.Right,ctrl:N.LeftControl,control:N.LeftControl,alt:N.LeftAlt,shift:N.LeftShift,cmd:N.LeftCmd,win:N.LeftWin,meta:N.LeftWin,super:N.LeftSuper,a:N.A,b:N.B,c:N.C,d:N.D,e:N.E,f:N.F,g:N.G,h:N.H,i:N.I,j:N.J,k:N.K,l:N.L,m:N.M,n:N.N,o:N.O,p:N.P,q:N.Q,r:N.R,s:N.S,t:N.T,u:N.U,v:N.V,w:N.W,x:N.X,y:N.Y,z:N.Z,0:N.Num0,1:N.Num1,2:N.Num2,3:N.Num3,4:N.Num4,5:N.Num5,6:N.Num6,7:N.Num7,8:N.Num8,9:N.Num9,f1:N.F1,f2:N.F2,f3:N.F3,f4:N.F4,f5:N.F5,f6:N.F6,f7:N.F7,f8:N.F8,f9:N.F9,f10:N.F10,f11:N.F11,f12:N.F12},ta=e=>{if(!e)return;let n=String(e).toLowerCase().trim();if(ea[n]!==void 0)return ea[n];if(N[e]!==void 0)return N[e];if(N[n.toUpperCase()]!==void 0)return N[n.toUpperCase()]};async function qn(e,n,t={}){try{switch(e.toLowerCase()){case"type":{if(typeof n!="string")return"ERROR: Type action requires a valid string input";await Zr(),await _l.setContent(n);let s=process.platform==="darwin"?N.LeftSuper:N.LeftControl;return await mn.pressKey(s,N.V),await mn.releaseKey(s,N.V),await Zr(),t.autoPressEnter?(await new Promise(i=>setTimeout(i,50)),await mn.type(N.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=ta(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=>ta(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(N.LeftControl,N.A),await mn.releaseKey(N.LeftControl,N.A),await mn.type(N.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=_(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 r=i.replace("mouse_","");return await gn(r,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 r=i;i==="press"&&(r="key_press");let a=t.autoPressEnter===!0||t.autoPressEnter==="true"||t.enter===!0||t.enter==="true";return await qn(r,s||t.text||t.keys,{...t,autoPressEnter:a})}return`ERROR: Unrecognized action "${o}". Supported actions: move, click, drag, scroll, type, key_press, key_combination.`};import na from"screenshot-desktop";import Il from"sharp";import{mouse as sa,Point as Ll}from"@nut-tree-fork/nut-js";function vl(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],r=s;for(let a=1;a<=n.length;a++){let h=e[s-1]===n[a-1]?0:1,d=Math.min(i[a-1]+1,o[a]+1,o[a-1]+h);i.push(d),d<r&&(r=d)}if(o=i,r>t)return t+1}return o[n.length]}function Pl(e){return e<=2?0:e<=5?1:e<=10?2:Math.min(3,Math.floor(e*.25))}var Li=async(e,n={})=>{let t=_(e),o=t.gridId||t.grid||t.coordinate||t.target||t.id,s=(t.type||t.clickType||"single").toLowerCase(),i=(t.button||"left").toLowerCase(),r=t.intendedClickText||t.text||"";if(!o&&!r)return'ERROR: Missing required "gridId" parameter for Click tool.';let a=o;if(r)try{let{createWorker:c}=await import("tesseract.js"),l=o?lr(o):null,{getActiveDisplay:u}=await import("./screen_grid-IKEV7A6U.js"),f=await u(),p={format:"png"};try{let R=await na.listDisplays();R&&R.length>0&&(p={format:"png",screen:(R[f]||R[0]).id})}catch{}let g=await na(p),y=await Il(g).metadata(),m=y.width||1920,w=y.height||1080,x=l?await ls(l,m,w):{x:m/2,y:w/2},E=await import("fs-extra"),{CU_CACHE_DIR:b}=await import("./paths-R3DD7CRF.js");E.ensureDirSync(b);let C=await c("eng",1,{cachePath:b}),{data:S}=await C.recognize(g);if(await C.terminate(),S&&S.text){let R=r.toLowerCase().trim(),A=[];if(S.lines&&S.lines.length>0)for(let k of S.lines){let T=k.text?k.text.toLowerCase().trim():"";T&&(T===R||new RegExp(`\\b${vl(R)}\\b`,"i").test(T))&&k.bbox&&A.push(k.bbox)}if(A.length===0&&S.words&&S.words.length>0)for(let k of S.words)(k.text?k.text.toLowerCase().trim():"")===R&&k.bbox&&A.push(k.bbox);if(A.length===0&&S.words&&S.words.length>0){let k=Pl(R.length);for(let T of S.words){let L=T.text?T.text.toLowerCase().trim():"";L.length>=3&&Math.abs(L.length-R.length)<=k&&Nl(L,R,k)<=k&&T.bbox&&A.push(T.bbox)}}if(A.length>0){let k=null,T=1/0;for(let L of A){let I=Math.round((L.x0+L.x1)/2),P=Math.round((L.y0+L.y1)/2),j=Math.hypot(I-x.x,P-x.y);j<T&&(T=j,k={x:I,y:P})}if(k){let L={x:Math.round(k.x*(1280/m)),y:Math.round(k.y*(720/w))},I=await gn("click",L,{button:i,clickType:s});await new Promise(P=>setTimeout(P,60));try{await gn("move",{x:640,y:360})}catch{}return`${I} (Full-screen OCR nearest match for "${r}" at ${Math.round(T)}px distance)`}}}}catch{}let h=null;try{h=await sa.getPosition()}catch{}let d=await gn("click",a,{button:i,clickType:s});await new Promise(c=>setTimeout(c,50));try{h&&typeof h.x=="number"&&typeof h.y=="number"?await sa.setPosition(new Ll(h.x,h.y)):await gn("move",{x:640,y:360})}catch{}return d};var vi=async(e,n={})=>{let t=_(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 gn("drag",o,{from:o,to:s})};var Ni=async(e,n={})=>{let t=_(e),o=(t.direction||"down").toLowerCase(),s=t.amount?parseInt(t.amount,10):5,i=t.gridId||t.grid||t.coordinate||t.target||t.id||null;return await gn("scroll",i,{direction:o,amount:s})};var Mo=async(e,n={})=>{let t=_(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 qn("type",String(o),{autoPressEnter:s})};var _o=async(e,n={})=>{let t=_(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 qn("clear_input");if(s.includes(";")||s.includes("+")){let i=s.split(/[;+]/).map(r=>r.trim()).filter(Boolean);return await qn("key_combination",i)}return await qn("key_press",s)};var Io=async(e,n={})=>"SUCCESS: Screen recapture requested. The latest gridded screenshot is provided for your next decision.";var Dl={web_search:ri,web_scrape:ai,memory:li,chat:ci,view_file:Qs,write_file:di,update_file:mi,exec_command:Zo,read_folder:yi,write_pdf:Si,write_docx:Ei,search_keyword:eo,generate_image:ki,saveSummary:to,addMemScore:Ns,file_map:$i,todo:zr,invokeSync:Oi,invoke:Xr,getProgress:Mi,cancel:Jr,awaitSubagent:Ps,answerSubagent:Ds,steerSubagent:so,computer_action:ro,computer_use:ro,ComputerAction:ro,ComputerUse:ro,click:Li,Click:Li,drag:vi,Drag:vi,scroll:Ni,Scroll:Ni,keyboard_typing:Mo,KeyboardTyping:Mo,keyboardtyping:Mo,key_press:_o,KeyPress:_o,keypress:_o,recapture_screen:Io,RecaptureScreen:Io,recapturescreen:Io,invoke_sync:Oi,get_progress:Mi,await_subagent:Ps,answer_subagent:Ds,steer_subagent:so,steer:so,Steer:so,ask:wi,Ask:wi,WebSearch:ri,WebScrape:ai,ReadFile:Qs,ReadFolder:yi,WriteFile:di,PatchFile:mi,WritePDF:Si,WriteDoc:Ei,Run:Zo,SearchKeyword:eo,CodeSearch:eo,code_search:eo,Memory:li,Chat:ci,GenerateImage:ki,saveSumary:to,SaveSummary:to,SaveSumary:to,add_mem_score:Ns,AddMemScore:Ns,addMemoryScore:Ns,AddMemoryScore:Ns,FileMap:$i,answer:Ds,Answer:Ds,AnswerSubagent:Ds,await:Ps,Await:Ps,AwaitSubagent:Ps,EmergencyRollback:Ii,emergency_rollback:Ii},ao=async(e,n,t={})=>{let o=t.mode?t.mode.toLowerCase():"flux",s=e.toLowerCase(),r=["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(!r){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=Dl[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 J from"path";import _e from"fs";import Fl from"gradient-string";var Pi=["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 oa=[{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 ia=(e="Dark")=>{let n;e==="Mystery"||e==="Chaos"?(Lo||(Lo=oa[Math.floor(Math.random()*oa.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 Ul=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",fp=(e=2)=>{let n=Ul();return n==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)},up=(e="...",n="Loading...",t="Dark")=>{let o=Pi[Math.floor(Math.random()*Pi.length)],s=ia(t),i=s.logoTextAnsi,r=s.logoBodyAnsi,a=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=Fl(c).multiline(d.join(`
485
- `)).split(`
486
- `),u=f=>`${a}${f}${h}`;return`${l[0]}
487
- ${l[1]} ${i}Selected Provider: ${n}${h}
488
- ${l[2]}
489
- ${l[3]} ${i}FluxFlow ${u("v"+e)}${h}
490
- ${l[4]}
491
- ${l[5]} ${r}See /help for additional commands.${h}
492
- ${l[6]} ${u(o)}
493
- ${l[7]}`};import{WebSocket as vo}from"ws";var Yt=null,Fs=!1,Bl="ws://localhost:56832",Di=[],Us=null,Fi=null,ra="2.0.0",mp=e=>{ra=e,aa()},Ui=e=>{Fi=e},aa=()=>{if(Yt||Fs)return;Fs=!0;let e=new vo(Bl);e.on("open",()=>{for(Yt=e,Fs=!1,Yt.send(JSON.stringify({command:"version",version:ra,pid:process.pid,ppid:process.ppid}));Di.length>0;)Yt.send(JSON.stringify(Di.shift()))}),e.on("message",n=>{try{let t=JSON.parse(n.toString());t.command==="contextResponse"&&Us?(Us(t.data),Us=null):t.command==="securityResponse"&&Fi&&Fi(t.result)}catch{}}),e.on("error",()=>{Fs=!1,Yt=null}),e.on("close",()=>{Fs=!1,Yt=null})},No=e=>{Yt&&Yt.readyState===vo.OPEN?Yt.send(JSON.stringify(e)):(Di.push(e),Fs||aa())},Po=()=>Yt!==null&&Yt.readyState===vo.OPEN,gp=e=>{No({command:"status",status:e})},ys=()=>new Promise(e=>{if(!Yt||Yt.readyState!==vo.OPEN){e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]});return}Us=e,Yt.send(JSON.stringify({command:"requestContext"})),setTimeout(()=>{Us===e&&(e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]}),Us=null)},1e3)}),la=e=>{No({command:"open",filePath:e})},Bi=(e,n,t)=>{No({command:"showDiff",filePath:e,originalContent:n,modifiedContent:t})},ca=(e,n)=>{No({command:"closeDiff",filePath:e,result:n})};import da from"path";import Wl from"fs";var Hl=e=>{try{return Wl.readdirSync(e,{withFileTypes:!0})}catch{return[]}},Wi=(e,n,t=1,o=Hl,s=[],i=null)=>{let r=i||o(e),a=" ".repeat(t-1);if(r.length>100)return`${a}${da.basename(e)}/ (>100 files)
494
- `;let h="",d=s,c=r.filter(p=>!d.includes(p.name)&&!p.name.startsWith(".")),l=r.filter(p=>d.includes(p.name)||p.name.startsWith(".")).map(p=>p.name).sort();l.length>0&&(h+=`${a}[ignored: ${l.map(p=>p+"/").join(", ")}]
495
- `);let u=c.filter(p=>p.isDirectory()).sort((p,g)=>p.name.localeCompare(g.name)),f=c.filter(p=>!p.isDirectory()).map(p=>p.name).sort();for(let p of u){let g=da.join(e,p.name);if(t>n)h+=`${a}${p.name}/ (max depth)
496
- `;else{let y=o(g);y.length>80?h+=`${a}${p.name}/ (>80 files)
497
- `:(h+=`${a}${p.name}/
498
- `,h+=Wi(g,n,t+1,o,s,y))}}return f.length>0&&(h+=`${a}${f.join("; ")}
499
- `),h};import Hi from"path";import jl from"fs";var Gl=e=>{try{return jl.readdirSync(e,{withFileTypes:!0})}catch{return[]}},ji=(e,n,t="",o=1,s=Gl,i=[])=>{let r=s(e),a=Hi.sep;if(r.length>100)return`${t}\u2514\u2500\u2500 ${Hi.basename(e)}${a} ...100+ files...
500
- `;let h="",d=i,c=r.filter(f=>!d.includes(f.name)&&!f.name.startsWith(".")),l=r.filter(f=>d.includes(f.name)||f.name.startsWith(".")).map(f=>f.name).sort();c.sort((f,p)=>f.isDirectory()&&!p.isDirectory()?-1:!f.isDirectory()&&p.isDirectory()?1:f.name.localeCompare(p.name));let u=[...c.map(f=>({name:f.name,isDir:f.isDirectory()})),...l.map(f=>({name:f,isDir:!0,isCollapsed:!0}))];return u.forEach((f,p)=>{let g=p===u.length-1,y=Hi.join(e,f.name),m=g?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",w=t+(g?" ":"\u2502 ");if(f.isCollapsed){h+=`${t}${m}${f.name}${a}...
501
- `;return}f.isDir?o>n?h+=`${t}${m}${f.name}${a} ...depth exceeded...
502
- `:s(y).length>80?h+=`${t}${m}${f.name}${a} ...80+ files...
503
- `:(h+=`${t}${m}${f.name}${a}
504
- `,h+=ji(y,n,w,o+1,s,i)):h+=`${t}${m}${f.name}
505
- `}),h};import"@google/genai";Yl.config({quiet:!0});var ql=/```[\s\S]*?```/g,Vl=/```[\s\S]*$/g,zl=/`[^`]+`/g,Xl=/^\|.*\|$/gm,Jl=/^[^\w]+|[^\w]+$/g,Ql=/[^a-z0-9]/gi,co=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,Zl=/\[\s*(?:tool:functions\.|agent:generalist\.)([a-z0-9_]+)\s*\(/gi,ec=/(?:path|targetFile|TargetFile|directory|keyword|id|taskId|title|task)\s*=\s*\\?["']?([^\\"' \),]+)/,ws=/["']/g,fa=/\\/g,tc=/<\|channel>thought/gi,nc=/<channel\|>/gi,Nn=e=>typeof e!="string"?e:e.replace(tc,"<think>").replace(nc,"</think>"),sc=/(?:<(think|thought|thoughts)>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\])/gi,oc=/(?:<(think|thought|thoughts)>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*$/gi,ua=/(?:<think>|<\|channel>thought|\[think\])[\s\S]*?(?:<\/think>|<channel\|>|\[\/think\]|$)/gi,ha=/(?:<(think|thought|thoughts)>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\]|$)/gi,Ea=/`[^`]*`/g,xa=/`[^`]*$/,pa=/<\|\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,ic=/"([^"]+)"\s*:\s*(?:"([^"]*)"|(\d+)|true|false|null)/g,ma=/<\|\s*tool_calls_section_begin\s*\|>/gi,ga=/<\|\s*tool_calls_section_end\s*\|>/gi,rc=/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi,ya=/<(\w+)(?:[^>]*)>\r?\n?/gi,wa=/\r?\n?<\/\w+(?:[^>]*)>/gi,Yi=null,Do={},Ss={key:null,value:null},yn=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`),ac=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(r){if(s?.aborted||r?.name==="AbortError"||r?.message==="Subagent task was cancelled."||(i++,i>=n))throw r;let a=Math.min(t*Math.pow(2,i-1),o);await new Promise((h,d)=>{let c=setTimeout(h,a);s&&s.addEventListener("abort",()=>{clearTimeout(c),d(new DOMException("The user aborted a request.","AbortError"))})})}}},Lt=!1;var lc=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,r)=>{let a=s.fullText||s.text||"";if(s.role==="user"&&i<r.length-1)if(a.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")){let h=a.indexOf("**CONTEXT SUMMARY OF PREVIOUS TURNS");if(h!==-1){let c=a.substring(0,h).lastIndexOf("[SYSTEM METADATA]");c!==-1?a=a.substring(c).trim():a=a.substring(h).trim()}}else{let h=a.lastIndexOf("[USER]"),d=a.lastIndexOf("[USER PROMPT]");h!==-1?a=a.substring(h+6).trim():d!==-1&&(a=a.substring(d).trim())}return{...s,text:a}}),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 r=[],a=[],h=[];i.forEach(d=>{let c=(d.text||"").toLowerCase(),l=c.includes("tool:functions.")||c.includes("agent:generalist."),u=d.role==="system"&&(d.text?.startsWith("[TOOL RESULT]")||d.text?.startsWith("SUCCESS:")||d.text?.startsWith("ERROR:"));d.role==="agent"?l?r.push(d.text):h.push(d.text):u?a.push(d.text):h.push(d.text)}),r.length>0&&t.push({role:"agent",text:"combined"}),a.length>0&&t.push({role:"system",text:"combined"}),h.length>0&&t.push({role:"agent",text:"combined"})}}return t.length},cc=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),Uo=async(e,n,t=5,o=1e3)=>{let s=n?.signal;for(let r=0;r<t;r++){if(s?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{let a=await fetch(e,n);if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),a.ok||a.status!==429&&a.status<500)return a}catch(a){if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),a.name==="AbortError"||s?.aborted||r===t-1)throw a}s?await new Promise((a,h)=>{let d=setTimeout(()=>{s.removeEventListener("abort",c),a()},Math.min(24e3,o*Math.pow(2,r))),c=()=>{clearTimeout(d),h(new DOMException("The user aborted a request.","AbortError"))};s.addEventListener("abort",c)}):await new Promise(a=>setTimeout(a,Math.min(24e3,o*Math.pow(2,r))))}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},Ki=async function*(e,n,t,o,s,i,r,a,h=.99){let d=[];o&&d.push({role:"system",content:o});for(let x of t){let E=x.role==="user"?"user":"assistant",b=[];if(Array.isArray(x.parts)){for(let C of x.parts)if(C.text)b.push({type:"text",text:C.text});else if(C.inlineData&&r){let S=C.inlineData.mimeType,R=C.inlineData.data;S.startsWith("image/")&&b.push({type:"image_url",image_url:{url:`data:${S};base64,${R}`}})}}else{let C=x.text||"";C&&b.push({type:"text",text:C})}d.push({role:E,content:b.length===1&&b[0].type==="text"?b[0].text:b})}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:a});if(!l.ok){let x=await l.json().catch(()=>({}));throw new Error(`DeepSeek Error (${l.status}): ${x.error?.message||l.statusText}`)}let u=l.body.getReader(),f=new TextDecoder,p="",g=[],y=null,m=Date.now(),w=!1;for(;;){let{done:x,value:E}=await u.read();if(x){w&&(g.length>0||y)&&(yield{candidates:g.length>0?[{content:{parts:g}}]:[],usageMetadata:y});break}p+=f.decode(E,{stream:!0});let b=p.split(`
506
- `);p=b.pop();for(let C of b){let S=C.trim();if(!S||!S.startsWith("data: "))continue;let R=!1;if(S==="data: [DONE]")R=!0;else try{let A=JSON.parse(S.substring(6)),k=A.choices?.[0]?.delta,T=A.usage;if(A.choices?.[0]?.finish_reason&&(R=!0),T&&(y={totalTokenCount:T.total_tokens||T.prompt_tokens+T.completion_tokens,promptTokenCount:T.prompt_tokens||0,candidatesTokenCount:T.completion_tokens||0,cachedContentTokenCount:T.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:T.completion_tokens_details?.reasoning_tokens||0},w=!0),k){let L=k.reasoning_content||null;L&&(g.push({text:L,thought:!0}),w=!0),k.content&&(g.push({text:k.content}),w=!0)}}catch{}if((R||Date.now()-m>=150)&&w&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],m=Date.now(),w=!1),R)break}Date.now()-m>=150&&w&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],m=Date.now(),w=!1)}},qi=async function*(e,n,t,o,s,i,r,a,h=.99){let d=[];o&&d.push({role:"system",content:o});for(let b of t){let C=b.role==="user"?"user":"assistant",S=[];if(Array.isArray(b.parts)){for(let R of b.parts)if(R.text)S.push({type:"text",text:R.text});else if(R.inlineData&&r){let A=R.inlineData.mimeType,k=R.inlineData.data;A.startsWith("image/")&&S.push({type:"image_url",image_url:`data:${A};base64,${k}`})}}else{let R=b.text||"";R&&S.push({type:"text",text:R})}S.length>0&&d.push({role:C,content:S.length===1&&S[0].type==="text"?S[0].text:S})}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"&&Ks(n)&&(l.reasoning_effort=c[s]||"high");let u=await Uo("https://api.mistral.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(l),signal:a});if(!u.ok){let b=await u.text().catch(()=>""),C=u.statusText;try{let S=JSON.parse(b);C=S.error?.message||S.message||JSON.stringify(S.detail||S)}catch{b&&(C=b)}throw new Error(`Mistral Error (${u.status}): ${JSON.stringify(C)}`)}let f=u.body.getReader(),p=new TextDecoder,g="",y=[],m=null,w=Date.now(),x=!1,E=b=>b?typeof b=="string"?Nn(b):Array.isArray(b)?b.map(E).filter(Boolean).join(""):typeof b=="object"&&b!==null?typeof b.text=="string"?Nn(b.text):typeof b.content=="string"?Nn(b.content):typeof b.thinking=="string"?Nn(b.thinking):typeof b.reasoning_content=="string"?Nn(b.reasoning_content):typeof b.reasoning=="string"?Nn(b.reasoning):typeof b.value=="string"?Nn(b.value):b.text?E(b.text):b.content?E(b.content):b.thinking?E(b.thinking):b.reasoning_content?E(b.reasoning_content):b.reasoning?E(b.reasoning):b.value?E(b.value):"":Nn(String(b)):"";for(;;){let{done:b,value:C}=await f.read();if(b){x&&(y.length>0||m)&&(yield{candidates:y.length>0?[{content:{parts:y}}]:[],usageMetadata:m});break}g+=p.decode(C,{stream:!0});let S=g.split(`
507
- `);g=S.pop();for(let R of S){let A=R.trim();if(!A||!A.startsWith("data: "))continue;let k=!1;if(A==="data: [DONE]")k=!0;else try{let T=JSON.parse(A.substring(6)),L=T.choices?.[0]?.delta,I=T.usage;if(T.choices?.[0]?.finish_reason&&(k=!0),I&&(m={totalTokenCount:I.total_tokens||(I.prompt_tokens||0)+(I.completion_tokens||0),promptTokenCount:I.prompt_tokens||0,candidatesTokenCount:I.completion_tokens||0,cachedContentTokenCount:I.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:I.completion_tokens_details?.reasoning_tokens||0},x=!0),L){let P=L.thinking||L.reasoning_content||L.reasoning,j=E(P);j&&(y.push({text:j,thought:!0}),x=!0);let G=L.content||(!L.thinking&&!L.reasoning_content&&!L.reasoning?L.text:null);if(G)if(Array.isArray(G))for(let ee of G)if(typeof ee=="object"&&ee!==null){let he=ee.type==="thinking"||ee.type==="reasoning"||!!ee.thought,Ue=E(ee);Ue&&(y.push({text:Ue,...he?{thought:!0}:{}}),x=!0)}else{let he=E(ee);he&&(y.push({text:he}),x=!0)}else if(typeof G=="object"&&G!==null){let ee=G.type==="thinking"||G.type==="reasoning"||!!G.thought,he=E(G);he&&(y.push({text:he,...ee?{thought:!0}:{}}),x=!0)}else{let ee=E(G);ee&&(y.push({text:ee}),x=!0)}}}catch{}if((k||Date.now()-w>=150)&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),x=!1),k)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,r=!1,a,h=.99){let d=[];o&&d.push({role:"system",content:o}),t.forEach(ie=>{let be=ie.role==="model"?"assistant":"user",O=[];Array.isArray(ie.parts)&&ie.parts.forEach(D=>{if(D.text)O.push({type:"text",text:D.text});else if(D.inlineData&&r){let V=D.inlineData.mimeType,z=D.inlineData.data;V.startsWith("image/")&&fn(n)&&O.push({type:"image_url",image_url:{url:`data:${V};base64,${z}`}})}}),d.push({role:be,content:O.length===1&&O[0].type==="text"?O[0].text:O})});let l={Fast:"Fast",Low:"Fast",Medium:"Standard",Standard:"Standard",High:"High",xHigh:"High"}[s]||"High",u=l!=="Fast",f=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"),E=n.includes("qwen"),b=n.includes("nemotron"),C=n.includes("llama-3"),S=n.includes("seed"),R=n.includes("poolside"),A=n.includes("thinkingmachines")||n.includes("muse"),k=C,T=null,L={Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},I={Fast:"64",Low:"64",Medium:"4096",Standard:"4096",High:"16384",xHigh:"16384"},P={Fast:"none",Low:"minimal",Medium:"medium",Standard:"medium",High:"max",xHigh:"max"},j=w||g||R||A?16384:32768;j=process.env.NVIDIA_BASE_URL?1024:j,j=T?1024:j;let G={model:n,messages:d,max_tokens:j,stream:!0,stream_options:{include_usage:!0},temperature:h,...x&&{thinking:L[s]||"high"}};if(!(process.env.NVIDIA_BASE_URL||k||T))if(f)G.chat_template_kwargs={thinking:u};else if(p)G.chat_template_kwargs={enable_thinking:u};else if(g)if(u){let ie=l==="High"?"max":"high";G.chat_template_kwargs={thinking:!0,reasoning_effort:ie}}else G.chat_template_kwargs={thinking:!1};else y?G.chat_template_kwargs={enable_thinking:u,clear_thinking:!u}:m?G.reasoning_effort=u?"high":"none":w&&n.includes("minimax-m3")?G.chat_template_kwargs={thinking_mode:u?"enabled":"disabled"}:E?G.chat_template_kwargs={enable_thinking:u}:b?l==="High"?(G.reasoning_budget=12e3,G.chat_template_kwargs={enable_thinking:!0}):l==="Standard"?(G.reasoning_budget=12e3,G.chat_template_kwargs={enable_thinking:!0,medium_effort:!0}):G.chat_template_kwargs={enable_thinking:!1}:S?u&&(G.extra_body={thinking_budget:parseInt(I[l]??"4096")}):R?G.chat_template_kwargs={enable_thinking:u}:A&&(G.reasoning_effort=P[l]||"medium");let ee=0,he=6,Ue=!1,F=process.env.NVIDIA_BASE_URL||"https://integrate.api.nvidia.com/v1/chat/completions",B=process.env.NVIDIA_API_KEY&&process.env.NVIDIA_BASE_URL?process.env.NVIDIA_API_KEY:e;for(F.endsWith("/chat/completions")||(F=F.replace(/\/+$/,"")+"/chat/completions");ee<he;){ee++;try{let ie=await Uo(F,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${B}`},body:JSON.stringify(G),signal:a});if(!ie.ok){let Be=await ie.text().catch(()=>""),st=ie.statusText;try{let ut=JSON.parse(Be);st=ut.error?.message||ut.message||JSON.stringify(ut.detail||ut)}catch{Be&&(st=Be)}let Ge=new Error(`NVIDIA API Error (${ie.status}): ${st}`);throw Ge.status=ie.status,Ge}let be=ie.body.getReader(),O=new TextDecoder,D="",V=[],z=null,De=Date.now(),Ne=!1;for(;;){let{done:Be,value:st}=await be.read();if(Be){Ne&&(V.length>0||z)&&(yield{candidates:V.length>0?[{content:{parts:V}}]:[],usageMetadata:z},Ue=!0);break}D+=O.decode(st,{stream:!0});let Ge=D.split(`
508
- `);D=Ge.pop();let ut=!1;for(let Ft of Ge){let ht=Ft.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 xt=pt.usage;xt&&(z={totalTokenCount:xt.total_tokens||xt.prompt_tokens+xt.completion_tokens,promptTokenCount:xt.prompt_tokens||0,candidatesTokenCount:xt.completion_tokens||0,cachedContentTokenCount:xt.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:(xt.completion_tokens_details?.reasoning_tokens||0)+(xt.completion_tokens_details?.thoughts_tokens||0)},Ne=!0);let Rt=pt.choices?.[0]?.delta?.reasoning||pt.choices?.[0]?.delta?.reasoning_content||"",Je=pt.choices?.[0]?.delta?.content||"";Rt&&(V.push({text:Rt,thought:!0}),Ne=!0),Je&&(V.push({text:Je}),Ne=!0)}catch{}}}}if((ut||Date.now()-De>=350)&&Ne&&(yield{candidates:V.length>0?[{content:{parts:[...V]}}]:[],usageMetadata:z},Ue=!0,V=[],De=Date.now(),Ne=!1),ut)break}break}catch(ie){if(Ue||ee>=he)throw ie;await new Promise(be=>setTimeout(be,3500))}}},dc=async function*(e,n){let t=[],o=null,s=!1,i=null,r=u=>{if(t.push(u),o){let f=o;o=null,f()}},a=n.split("/").pop();a=a.replace("llama-3.3","llama-3_3");let h=`https://api.ngc.nvidia.com/v2/predict/queues/models/qc69jvmznzxy/${a}`,d=!1,c=null,l=async()=>{try{let u=await fetch(h);if(u.ok){let f=await u.json();if(f&&f.queues&&f.queues[0]&&typeof f.queues[0].queueDepth=="number"){let p=f.queues[0].queueDepth;d||r({value:{type:"status",content:`Queue ${p||1}`},done:!1})}}else d||r({value:{type:"status",content:`Queue ${u.status}`},done:!1})}catch{}};process.env.NVIDIA_BASE_URL||(l(),c=setInterval(l,5e3)),(async()=>{try{let u=e[Symbol.asyncIterator]();for(;;){let{value:f,done:p}=await u.next();if(p)break;d=!0,c&&(clearInterval(c),c=null),r({value:f,done:!1})}s=!0,r(null)}catch(u){if(i=u,c&&(clearInterval(c),c=null),o){let f=o;o=null,f()}}})();try{for(;;){if(i)throw i;if(t.length>0){let u=t.shift();if(u===null&&s)break;yield u.value}else{if(s)break;await new Promise(u=>{o=u})}}}finally{c&&(clearInterval(c),c=null)}},zi=async function*(e,n,t,o,s,i,r,a,h=.95){let d=[];o&&d.push({role:"system",content:[{type:"text",text:o,cache_control:{type:"ephemeral"}}]});for(let b of t){let C=b.role==="user"?"user":"assistant",S=[];if(Array.isArray(b.parts)){for(let R of b.parts)if(R.text)S.push({type:"text",text:R.text});else if(R.inlineData&&r){let A=R.inlineData.mimeType,k=R.inlineData.data;A.startsWith("image/")?S.push({type:"image_url",image_url:{url:`data:${A};base64,${k}`}}):S.push({type:"file",file:{filename:R.filename||"file",file_data:`data:${A};base64,${k}`}})}}else{let R=b.text||"";R&&S.push({type:"text",text:R})}d.push({role:C,content:S.length===1&&S[0].type==="text"?S[0].text:S})}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"},u=c[s];u&&s!=="Fast"&&(l.reasoning_effort=u);let f=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:a});if(!f.ok){let b=await f.json().catch(()=>({}));throw new Error(`OpenRouter Error (${f.status}): ${b.error?.message||f.statusText}`)}let p=f.body.getReader(),g=new TextDecoder,y="",m=[],w=null,x=Date.now(),E=!1;for(;;){let{done:b,value:C}=await p.read();if(b){E&&(m.length>0||w)&&(yield{candidates:m.length>0?[{content:{parts:m}}]:[],usageMetadata:w});break}y+=g.decode(C,{stream:!0});let S=y.split(`
509
- `);y=S.pop();for(let R of S){let A=R.trim();if(!A||!A.startsWith("data: "))continue;let k=!1;if(A==="data: [DONE]")k=!0;else try{let T=JSON.parse(A.substring(6)),L=T.choices?.[0]?.delta,I=T.usage;if(T.choices?.[0]?.finish_reason&&(k=!0),I&&(w={totalTokenCount:I.total_tokens||(I.prompt_tokens||0)+(I.completion_tokens||0),promptTokenCount:I.prompt_tokens||0,candidatesTokenCount:I.completion_tokens||0,cachedContentTokenCount:I.prompt_tokens_details?.cached_tokens||I.prompt_tokens_details?.cache_read_input_tokens||I.cache_read_input_tokens||0,thoughtsTokenCount:I.completion_tokens_details?.reasoning_tokens||0},E=!0),L){let P=L.reasoning||(L.reasoning_details?L.reasoning_details.map(j=>j.text).join(""):null);P&&(m.push({text:P,thought:!0}),E=!0),L.content&&(m.push({text:L.content}),E=!0)}}catch{}if((k||Date.now()-x>=150)&&E&&(yield{candidates:m.length>0?[{content:{parts:[...m]}}]:[],usageMetadata:w},m=[],x=Date.now(),E=!1),k)break}}},Ra=async function*(e,n,t,o,s,i,r,a,h=1.05,d="Cloud"){let c=[];o&&c.push({role:"system",content:o});for(let S of t){let R=S.role==="user"?"user":"assistant",A="",k=[];if(Array.isArray(S.parts)){A=S.parts.map(T=>T.text||"").filter(Boolean).join(`
510
- `);for(let T of S.parts){let L=T.inlineData||T.inline_data;L&&L.data&&k.push(L.data)}}else A=S.text||"";if(A||k.length>0){let T={role:R,content:A};k.length>0&&(T.images=k),c.push(T)}}let l=d==="Local"||!e||e==="LOCAL",f={host:l?process.env.OLLAMA_HOST||"http://127.0.0.1:11434":process.env.OLLAMA_HOST||"https://ollama.com"};!l&&e&&(f.headers={Authorization:"Bearer "+e});let p=new Kl(f),g=[],y=null,m=Date.now(),w=!1,x={Fast:!1,Low:"medium",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},E=x[s]!==void 0?x[s]:!0,b={model:n,messages:c,stream:!0,think:E,keep_alive:"10m",options:{temperature:h}},C=await p.chat(b);for await(let S of C){if(a?.aborted)throw new DOMException("The user aborted a request.","AbortError");if(S.message?.thinking&&(g.push({text:S.message.thinking,thought:!0}),w=!0),S.message?.content&&(g.push({text:S.message.content}),w=!0),S.done){let R=S.prompt_cached_count||0;if(!R&&S.prompt_eval_count){let A=S.prompt_eval_duration||0;A>0&&A<5e7&&(R=S.prompt_eval_count)}y={totalTokenCount:(S.prompt_eval_count||0)+(S.eval_count||0),promptTokenCount:S.prompt_eval_count||0,candidatesTokenCount:S.eval_count||0,cachedContentTokenCount:R,thoughtsTokenCount:0},w=!0}(S.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})},nm=()=>{Lt=!0},sm=()=>Lt,Gi={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"},Ts=(e,n)=>{try{let t=_(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?J.basename(s.replace(/["']/g,"").replace(/\\/g,"/")):null}catch{return null}},Xi=e=>e?new Ta({apiKey:e}):Yi,om=async(e,n,t,o,s={})=>{let{onStatus:a,onMemoryUpdated:h,onBackgroundIncrement:d}=s,{profile:c,thinkingLevel:l,mode:u,janitorModel:f,chatId:p,systemSettings:g,sessionStats:y,aiProvider:m="Google",apiKey:w}=e,x=process.env.NVIDIA_BASE_URL||m==="Ollama"?!1:g?.memory!==!1,b=X(Pt,[]).map(O=>`- [${O.id}]: ${O.memory}`).join(`
511
- `),C=o.slice(0,-1).filter(O=>O.text&&!O.text.includes("[TOOL RESULT]")&&!O.text.includes("OBSERVATION:")&&!O.text.startsWith("[TERMINAL_RECORD]")&&!O.isTerminalRecord&&!O.isMeta&&!O.isLogo&&!String(O.id).startsWith("welcome")&&!String(O.id).startsWith("logo")).slice(-14).map(O=>{let D=cc(O.text).replace(/\[tool:functions\..*?\]/g,"").replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[METADATA \(PRIORITY: DYNAMIC\)\] Time: ([^|\n]+)/g,(Ne,Be)=>`[METADATA (PRIORITY: DYNAMIC)] Time: ${Be.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,`
512
- `).replace(/\n\n/g,`
513
- `).replace(/\\n\\n/g,"").trim(),V=O.role==="user"?8192:32768,z=D.substring(0,V);D.length>V&&(z+=`
514
- ... (truncated) ...`);let De=O.role==="user"?z.startsWith("[USER]")?"":"[USER]: ":z.startsWith("[AGENT]")?"":"[AGENT]: ";return{role:O.role==="user"?"user":"model",parts:[{text:`${De}${z}`}]}}),S=o.filter(O=>O.role==="user").length===1,R=n.includes("[TITLE-UPDATE]"),A=Math.random()<.8,k=S||R||A,T=t.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").trim(),L=gr(b,x,k),I=`${T.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)}`;I.length>32768&&(I+=`
515
- ... (truncated) ...`);let P=n.replace(/\[Prompted on:.*?\]/g,"").trim();I=I.replace(/\r?\n\r?\n/g,`
516
- `).replace(/\n\n/g,`
517
- `).replace(/\\n\\n/g,"").trim();let j=new Date,ee=`[METADATA] Current date and Time: ${`${j.getFullYear()}-${j.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(j.getDate()).padStart(2,"0")}, ${j.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0})}`}
518
-
519
- [USER]: ${P.substring(0,8192)}
520
- ${P.length>8192?`... (truncated) ...
521
-
522
- `:""}
523
- [AGENT (current turn)]: ${I}`;C.push({role:"user",parts:[{text:ee}]});let he=await zo("NVIDIA"),F=(await Dt()).quotas?.providerTiers?.NVIDIA==="Free",B="",ie=0,be=x?12:-1;for(;ie<=be;)try{if(!await xr("background",e))return;let O="",D=null,V=!1,z=m;try{let Be=new Promise((Rt,Je)=>setTimeout(()=>Je(new Error("JANITOR_TIMEOUT")),1e4)),st=m==="Google"&&ie>=0&&ie<6&&he&&F,Ge=m==="DeepSeek"&&ie<4&&he&&F;V=st||Ge,z=V?"NVIDIA":m;let ut=(async()=>{if(m==="OpenRouter"){let Rt=et("janitor_open_router"),ye=zi(w,Rt,C,L,"Fast",u,!1,null,.6)[Symbol.asyncIterator](),Kt=await ye.next();return{iterator:ye,firstResult:Kt}}else if(m==="DeepSeek"&&!V){let Je=Ki(w,et("deepseek_fast_fallback"),C,L,"Fast",u,!1,null,.6)[Symbol.asyncIterator](),ye=await Je.next();return{iterator:Je,firstResult:ye}}else if(m==="Mistral"&&!V){let Je=qi(w,et("mistral_janitor_fallback"),C,L,"Fast",u,!1,null,.6)[Symbol.asyncIterator](),ye=await Je.next();return{iterator:Je,firstResult:ye}}else if(m==="NVIDIA"||V){let Je=Vi(V?he:w,et("nvidia_janitor_fallback"),C,L,"Fast",u,!1,null,.6)[Symbol.asyncIterator](),ye=await Je.next();return{iterator:Je,firstResult:ye}}else{let ye=(await Xi(w).models.generateContentStream({model:f||(ie===be?et("janitor_default"):et("gemma_janitor_fallback_google")),contents:C,config:{systemInstruction:L,temperature:.7,safetySettings:[{category:zn.HARM_CATEGORY_HARASSMENT,threshold:Vn.BLOCK_NONE},{category:zn.HARM_CATEGORY_HATE_SPEECH,threshold:Vn.BLOCK_NONE},{category:zn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Vn.BLOCK_NONE},{category:zn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Vn.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 cs())[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:Ft,firstResult:ht}=await Promise.race([ut,Be]),{value:pt,done:xt}=ht;if(!xt&&pt){let Rt=pt.candidates?.[0]?.content?.parts,Je=Rt?z==="Google"?Rt[1]?.text||Rt[0]?.text||"":Rt.filter(ye=>ye.text&&!ye.thought).map(ye=>ye.text).join(""):typeof pt.text=="function"?pt.text():"";Je&&(O+=Je),D=pt.usageMetadata;for await(let ye of{[Symbol.asyncIterator]:()=>Ft}){let Kt=ye.candidates?.[0]?.content?.parts,Xn=Kt?z==="Google"?Kt[1]?.text||Kt[0]?.text||"":Kt.filter(Jn=>Jn.text&&!Jn.thought).map(Jn=>Jn.text).join(""):typeof ye.text=="function"?ye.text():"";Xn&&(O+=Xn),D=ye.usageMetadata}}}catch(Be){throw Be}if(O){if(B=O,D){let Be=D.totalTokenCount||0,st=D.cachedContentTokenCount||0,Ge=(D.candidatesTokenCount||0)+(D.thoughtsTokenCount||0),ut=V?et("nvidia_janitor_fallback"):z==="DeepSeek"?et("deepseek_fast_fallback"):z==="OpenRouter"?et("janitor_open_router"):f||(ie===be?et("janitor_default"):et("gemma_janitor_fallback_google"));await Gt("tokens",Be,z,ut),st>0&&await Gt("cachedTokens",st,z,ut),Ge>0&&await Gt("candidateTokens",Ge,z,ut)}}else throw new Error("No synthesis generated by Janitor.");d&&(d(),await It("background"));let De=Bo(B),Ne=!1;for(let Be of De){let st=Be.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(st)&&(Ne=!0);let Ge={chatId:p,sessionId:p,history:o},ut=await ao(st,Be.args,Ge);st.toLowerCase()==="memory"&&(Be.args.includes("action='user'")||Be.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(!Ne)try{let Be=X(Pt,[]);if(Be.length>0){let st=[];for(let Ge of Be)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);ue(Pt,st)}}catch{}break}catch(O){ie++;let D=new Date().toLocaleString(),V=O instanceof Error?(()=>{try{return JSON.parse(JSON.parse(O.message).error.message).error.message}catch{return String(O)}})():String(O);await new Promise(Ne=>setTimeout(Ne,1e3));let z=J.join(cn,"janitor");if(_e.existsSync(z)||_e.mkdirSync(z,{recursive:!0}),_e.appendFileSync(J.join(z,"error.log"),`ERROR [Attempt ${ie}/${be+1}] [${D}]: ${V}
524
-
525
- `),ie>be)break;let De=Math.min(750*Math.pow(2,ie-1),5e3);await new Promise(Ne=>setTimeout(Ne,De))}if(ie){let O=J.join(cn,"janitor");_e.appendFileSync(J.join(O,"error.log"),`-----------------------------------------------------------------------------
526
-
527
- `)}if(process.stdout.isTTY)try{let V=(await cs())[p]?.name||"",z=V&&!V.startsWith("flow-")&&!V.startsWith("Session ")?V:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${z}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${z}\x07`)}catch{process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")}},fc=e=>{let n=e.replace(sc,"").replace(oc,""),t=Ls?n:n.replace(Ea,s=>" ".repeat(s.length)).replace(xa,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,r=null,a=!1,h=!1;for(let d=s;d<t.length;d++){let c=n[d];if(!r&&(c==='"'||c==="'"||c==="`")?(r=c,a=!1):r&&c===r&&!a&&(r=null),!r&&(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==="\\"?a=!a:a=!1}if(!h)return{inside:!0,toolName:o[1],startIndex:o.index,args:n.substring(o.index+o[0].length)}}return{inside:!1}},ba=(e,n=!0)=>{let t=co;t.lastIndex=0;let o="",s=0,i;for(;(i=t.exec(e))!==null;){let r=e.substring(s,i.index);o+=n?r.replace(ua,""):r;let a=i.index+i[0].length-1,h=0,d=null,c=-1;for(let l=a;l<e.length;l++){let u=e[l];if(d){if(u===d){let f=0;for(let p=l-1;p>=0&&e[p]==="\\";p--)f++;f%2===0&&(d=null)}}else if(u==='"'||u==="'"||u==="`")d=u;else if(u==="(")h++;else if(u===")"&&(h--,h===0)){let f=l+1;for(;f<e.length&&/\s/.test(e[f]);)f++;if(f<e.length&&e[f]==="]"){c=f;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(ua,""):e.substring(s)),o},uc=(e,n,t)=>{let o=co;o.lastIndex=0;let s="",i=0,r;for(;(r=o.exec(e))!==null;){let a=e.substring(i,r.index);s+=a.replace(n,t);let h=r.index+r[0].length-1,d=0,c=null,l=-1;for(let u=h;u<e.length;u++){let f=e[u];if(c){if(f===c){let p=0;for(let g=u-1;g>=0&&e[g]==="\\";g--)p++;p%2===0&&(c=null)}}else if(f==='"'||f==="'"||f==="`")c=f;else if(f==="(")d++;else if(f===")"&&(d--,d===0)){let p=u+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(r.index,l+1),i=l+1,o.lastIndex=i;else{s+=e.substring(r.index),i=e.length;break}}return i<e.length&&(s+=e.substring(i).replace(n,t)),s},Sa=e=>ba(e,!0),hc=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("");pa.lastIndex=0;let o=e.replace(pa,(s,i,r)=>{let a="";try{let c=JSON.parse(r.trim());c&&typeof c=="object"&&(a=Object.entries(c).map(([u,f])=>{let p=typeof f=="string"?f:JSON.stringify(f);return`${u}=${JSON.stringify(p)}`}).join(", "))}catch{let l=[],u=ic;u.lastIndex=0;let f;for(;(f=u.exec(r))!==null;){let p=f[1],g=f[2]!==void 0?f[2]:f[0].split(":").slice(1).join(":").trim();l.push(`${p}=${JSON.stringify(g)}`)}l.length>0?a=l.join(", "):a=r.trim()}let h=i.toLowerCase().replace(/_/g,"");return`[tool:functions.${n[h]||t(i)}(${a})]`});return ma.lastIndex=0,ga.lastIndex=0,o=o.replace(ma,""),o=o.replace(ga,""),o},pc=/(?:path|query|url|keyword|command|method|title|task|id)\s*=\s*['"`]?\s*\.\.\.\s*['"`]?/i,mc=/^['"`]?\s*\.\.\.\s*['"`]?$/,vn=e=>{if(e==null)return!1;let n=String(e).trim();return n==="..."||n==="\u2026"||mc.test(n)},Bo=e=>{if(!e)return[];let n=hc(e);ha.lastIndex=0;let t=n.replace(ha,""),o=[],s=Ls?t:t.replace(Ea,a=>" ".repeat(a.length)).replace(xa,a=>" ".repeat(a.length)),i=Zl;i.lastIndex=0;let r;for(;(r=i.exec(s))!==null;){let a=r[1],h=r.index+r[0].length-1,d=0,c=null,l=-1,u=-1;for(let f=h;f<s.length;f++){let p=t[f];if(c){if(p===c){let g=0;for(let y=f-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)){u=f;let g=f+1;for(;g<s.length&&/\s/.test(s[g]);)g++;if(g<s.length&&s[g]==="]"){l=g;break}}}if(l!==-1){let f=t.substring(h+1,u),p=t.substring(r.index,l+1),g=_(f);vn(g.path)||vn(g.query)||vn(g.url)||vn(g.keyword)||vn(g.command)||vn(g.method)||vn(g.title)||vn(g.task)||vn(g.id)||pc.test(f)||o.push({fullMatch:p,toolName:a.trim(),args:f.trim()}),i.lastIndex=l+1}}return o},im=(e,n={})=>{if(!e)return null;if(Do=n,Yi=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}}}},Fo=async(e,n,t,o,s="Fast",i=.75,r="agent")=>ac(async()=>{let{aiProvider:a="Google",apiKey:h,mode:d}=e,c="",l=null,u=typeof t=="string"?[{role:"user",parts:[{text:t}]}]:t,f=new AbortController,p=f.signal,g=setInterval(()=>{Lt&&(f.abort(),clearInterval(g))},100);try{let y;a==="Ollama"?y=Ra(h,n,u,o,s,d,fn(n),p,i,systemSettings?.ollamaEndpoint||"Cloud"):a==="OpenRouter"?y=zi(h,n,u,o,s,d,fn(n),p,i):a==="DeepSeek"?y=Ki(h,n,u,o,s,d,fn(n),p,i):a==="Mistral"?y=qi(h,n,u,o,s,d,fn(n),p,i):a==="NVIDIA"?y=Vi(h,n,u,o,s,d,fn(n),p,i):y=await Xi(h).models.generateContentStream({model:n,contents:u,config:{systemInstruction:o,temperature:i,thinkingConfig:(()=>{let x=(n||"").toLowerCase(),E=x.includes("gemma-4")||x.startsWith("gemma"),b=x.includes("gemini-3");if(E||b)return E?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 C={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[s]||2048;return C===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:C}}})()}},{signal:p});for await(let m of y){if(Lt)throw new Error("Subagent task was cancelled.");if(e?.taskId&&typeof Ve<"u"){let E=Ve.find(b=>b.id===e.taskId);if(E&&E.status==="cancelled")throw new Error("Subagent task was cancelled.")}let w="";if(m.candidates?.[0]?.content?.parts)for(let E of m.candidates[0].content.parts)E.text&&!E.thought&&(c+=E.text,w+=E.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,a,n),m>0&&await Gt("cachedTokens",m,a,n),w>0&&await Gt("candidateTokens",w,a,n),e&&typeof e.onUsage=="function"&&e.onUsage({totalTokenCount:y,cachedContentTokenCount:m,candidatesTokenCount:w})}return await It("agent",a),{text:c,usageMetadata:l}}),gc=async(e,n,t=null)=>{t=t||X(Jt,{});try{let{aiProvider:o="Google"}=n;if(Object.values(t).flat().length<=5)return;let i=Object.keys(t).filter(u=>u!==e&&Array.isArray(t[u])&&t[u].length>2);if(i.length===0)return;let r=`You are a silent background process for the FluxFlow CLI Agent.
528
- Your task is to summarize or merge temporary context memories from one or more past conversation sessions.
529
- For each Chat ID provided, you must output a tool call to save the consolidated summary.
530
-
531
- The tool call format MUST be:
532
- [tool:functions.saveSummary(id="<chat-id>", summary="<updated summary string, max 400 words>")]
533
-
534
- Guidelines:
535
- - 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.
536
- - Focus on key goals, preferences, modified files, and technical decisions.
537
- - Under no circumstances write normal conversational text. Output ONLY the tool calls.
538
- - You can stack multiple tool calls for multiple chats.
539
-
540
- Chats to process:
541
-
542
- `,a=X(In,{});for(let u of i){let p=t[u].map(y=>`- ${y}`).join(`
543
- `),g=a[u];r+=`[Chat ID: ${u}]
544
- `,g?(r+=`- Existing Summary: "${g}"
545
- `,r+=`
546
- -- New Memories to integrate:
547
- ${p}
548
-
549
- `):r+=`-- Individual Memories:
550
- ${p}
551
-
552
- `}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 f=(await Fo(n,l,r,null,"Fast",.75,"background")).text||"",p=Bo(f);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(u){if(h>=d)throw new Error(`Failed after ${d} attempts. Last error: ${u.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=J.join(cn,"janitor");_e.existsSync(i)||_e.mkdirSync(i,{recursive:!0}),_e.appendFileSync(J.join(i,"error.log"),`[${new Date().toLocaleString()}] Past memory batch consolidation error: ${s}
553
- `)}},yc=async(e,n,t=!1)=>{let{chatId:o,aiProvider:s="Google"}=e,i=J.join(go,"chat-summaries.json"),r=f=>f.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(`
554
-
555
- `),a=async(f,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:
556
- ${p}
557
-
558
- Here is the new conversation history:
559
- ${f}
560
-
561
- Provide a new consolidated summary of the entire session.`:`Here is the conversation history:
562
- ${f}
563
-
564
- 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,E=null;for(;w<=3&&!x;){w++;try{E=await Fo(e,m,y,g,"Fast"),x=!0}catch{if(w>3){if(s==="Google")try{let C=et("general_fallback");return(await Fo(e,C,y,g,"Fast")).text||""}catch{return""}return""}}}return E&&E.text||""},h=r(n),d=X(i,{}),c=d[o]||{summary:"",historyLength:0};typeof c=="string"&&(c={summary:c,historyLength:0});let l=c.summary||"",u=await a(h,l);if(u){c.summary=u;let f=lc(n);return t?c.historyLength=(c.historyLength||0)+f:c.historyLength=f,d[o]=c,ue(i,d),u}return null},rm=e=>{try{let n=J.join(go,"chat-summaries.json");if(_e.existsSync(n)){let t=X(n,{});t[e]&&(delete t[e],ue(n,t))}}catch{}},am=async function*(e,n,t,o,s){let{profile:i,thinkingLevel:r,mode:a,janitorModel:h,chatId:d,isPlayground:c,systemSettings:l,sessionStats:u,aiProvider:f="Google",apiTier:p,wildcardTooling:g}=t,y=fn(e);if(!Yi&&f==="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=J.join(go,"chat-summaries.json"),E=!1,b=n.filter(k=>k.role==="user").length===1,C=w.includes("[TITLE-UPDATE]"),S=b||C,R=w.replace(/\[TITLE-UPDATE\]/g,"").trim();R=R.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),yield{type:"status",content:"[start]"},yield{type:"status",content:"Gathering Context"},await ft.startTransaction(d,R),l?.advanceRollback&&await Kn.takeInitialSnapshot(d),Lt=!1;let A=null;try{let k=new AbortController;A=setInterval(()=>{Lt&&(k.abort(),A&&(clearInterval(A),A=null))},400);let T=[...n.slice(0,-1)];{let Me=X(x,{})[d]||{summary:"",historyLength:0};if(Me.summary&&Me.historyLength>0){let Qt=0,Ie=[];for(let Qe=0;Qe<T.length;Qe++){let We=T[Qe];(We.role==="user"||We.role==="agent"||We.role==="system")&&!String(We.id).startsWith("welcome")&&!We.isMeta&&Qt++,Qt>Me.historyLength&&Ie.push(We)}T=Ie}}T=T.map(W=>{if(W.role==="user"&&W.text){let Me=W.text.match(/\[USER\]([\s\S]*?)\[\/USER\]/);if(Me)return{...W,text:Me[1].trim()}}return{...W}});let L=process.env.HIGH_CONTEXT,I=255e3,P=26e4;if(L&&L!=="false"){let W=parseInt(L,10);!isNaN(W)&&W>=256e3&&W<=1e6&&(P=W,I=Math.round(W*.85))}if((f==="NVIDIA"&&(e?.includes("gpt")||e?.includes("qwen")||e?.includes("medium")||e.includes("muse"))||f==="Mistral")&&(I=122e3,P=126e3),f!=="Ollama"&&(u?.tokens||0)>I&&(yield{type:"status_history",content:"Context Limit Reached. Condensing session history..."},await yc(t,T,!0)&&(T=[],E=!0)),b&&m){let W=X(Jt,{});Object.values(W).flat().length>5&&(yield{type:"status",content:"Condensing past chat memories"},await gc(d,t,W))}let j=X(Jt,{}),G=X(In,{}),ee=Object.entries(j).filter(([W])=>W!==d).flatMap(([W,Me])=>Me),Ue=[...Object.entries(G).filter(([W])=>W!==d).slice(-20).map(([W,Me])=>`[Chat Summary]: ${Me}`),...ee].map(W=>`- ${W}`).join(`
565
- `),B=X(Pt,[]).map(W=>`- ${W.memory}`).join(`
566
- `),ie=(u?.tokens||0)>=1e4,be=pr(Ue,B,m,ie),O=new Date,D=O.getFullYear(),V=O.toLocaleString("en-US",{month:"short"}).toUpperCase(),z=String(O.getDate()).padStart(2,"0"),De=O.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}),Ne=`${D}-${V}-${z}, ${De}`,Be=[".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=W=>{try{return _e.readdirSync(W,{withFileTypes:!0})}catch{return[]}},Ge=(W,Me={value:0},Qt=1)=>{if(Me.value>6200||Qt>7)return Me.value;let Ie=st(W);for(let Qe of Ie){if(Me.value>6200)break;Be.includes(Qe.name)||Qe.name.startsWith(".")||Qe.isDirectory()&&(Me.value++,Ge(J.join(W,Qe.name),Me,Qt+1))}return Me.value},ut=(W,Me)=>l?.indentationTree!==!1?Wi(W,Me,1,st,Be):ji(W,Me,"",1,st,Be),Ft=Ge(process.cwd()),ht=12;Ft>3072?ht=1:Ft>2304?ht=2:Ft>1536?ht=3:Ft>768?ht=4:Ft>384?ht=6:Ft>192?ht=7:Ft>96?ht=8:Ft>48?ht=9:Ft>24&&(ht=10);let pt=X(Vo,{}),xt=pt[d],Rt=xt?xt!==process.cwd():!1;pt[d]=process.cwd(),ue(Vo,pt);let Je=X(x,{}),ye=Je[d]||{summary:"",historyLength:0};typeof ye=="string"&&(ye={summary:ye,historyLength:0});let Kt=n.filter(W=>(W.role==="user"||W.role==="agent"||W.role==="system")&&!String(W.id).startsWith("welcome")&&!W.isMeta).length;ye.historyLength&&Kt<ye.historyLength&&(ye.summary="",ye.historyLength=0,Je[d]=ye,ue(x,Je));let Xn=typeof ye=="object"?ye.summary||"":ye||"",Jn=T.length>0;Jn&&Xn&&T[0]&&(T[0].role==="user"||T[0].role==="system")&&(T[0].text.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")||(T[0].text=`[SYSTEM METADATA]
567
- **CONTEXT SUMMARY OF PREVIOUS TURNS (PRIORITY: DYNAMIC)**
568
- ${Xn}
569
-
570
- [USER] ${T[0].text}`,yield{type:"summary_injected",content:{id:T[0].id,text:T[0].text}}));let Ji=Xn&&!Jn?`
571
- [SYSTEM METADATA]
572
- **CONTEXT SUMMARY OF PREVIOUS TURNS**
573
- ${Xn}
574
- `:"",Qi=!!l?.dynamicDirAwareness,ka=`${d}|${f}|${r}|${e}|${i}|${Qi}`,Zi=!Qi&&Ss.key===ka&&Ss.value?"":`
575
- **DIRECTORY STRUCTURE**
576
- CWD: `+process.cwd()+`${c?" [PLAYGROUND MODE]":""}
577
- `+ut(process.cwd(),ht),St=await ys(),Pn="";if(Po()&&St.file_focused!=="none"){Pn=`
578
- [ADDITIONAL IDE CONTEXT]
579
- `;let W=J.relative(process.cwd(),St.file_focused),Me=(St.opened_editors||[]).map(Ie=>{let Qe=J.relative(process.cwd(),Ie);return Qe.startsWith("..")?`[External] ${J.basename(Ie)}`:Qe});if(Pn+=`Focused File: ${W}
580
- Cursor Line: ${St.cursor_line}
581
- `,St.selected){let Ie=St.selected,Qe=Ie.split(`
582
- `);Qe.length>256&&(Ie=Qe.slice(0,240).join(`
583
- `)+`
584
- ... [truncated] ...
585
- `+Qe.slice(-16).join(`
586
- `)),Ie.length>2048&&(Ie=Ie.slice(0,1920)+`
587
- ... [truncated] ...
588
- `+Ie.slice(-128)),Pn+=`Current Selection: "${Ie}"
589
- `}if(St.manual_edits){let Qe=St.manual_edits.split(`
590
- `),We=[],ze=null;for(let Y of Qe)Y.trim()&&(Y.startsWith(" Line ")?ze&&ze.edits.push(Y):(ze={path:Y.endsWith(":")?Y.slice(0,-1):Y,edits:[]},We.push(ze)));for(let Y of We)Y.edits.length>80&&(Y.edits=Y.edits.slice(-80)),Y.originalEditsCount=Y.edits.length;let le=(Y,Q)=>Q.reduce((He,rn)=>{let Sn=St.file_focused&&(rn.path===St.file_focused||J.resolve(process.cwd(),rn.path)===J.resolve(St.file_focused))?Math.ceil(Y*1.2):Y;return He+Math.min(rn.edits.length,Sn)},0),Ut=80;if(le(80,We)>300){let Y=!1;for(let Q=80;Q>=10;Q--)if(le(Q,We)<=300){Ut=Q,Y=!0;break}Y||(Ut=10)}let Xe=[...We];if(Ut===10&&le(10,Xe)>500)for(;Xe.length>0&&le(10,Xe)>500;){let Y=0,Q=Xe[0].originalEditsCount;for(let He=1;He<Xe.length;He++)Xe[He].originalEditsCount<Q&&(Q=Xe[He].originalEditsCount,Y=He);Xe.splice(Y,1)}for(let Y of Xe){let He=St.file_focused&&(Y.path===St.file_focused||J.resolve(process.cwd(),Y.path)===J.resolve(St.file_focused))?Math.ceil(Ut*1.2):Ut;Y.edits.length>He&&(Y.edits=Y.edits.slice(-He))}for(let Y of Xe){let Q=`${Y.path}:
591
- ${Y.edits.join(`
592
- `)}`;for(;Y.edits.length>0&&Q.length>4*768;)Y.edits.shift(),Q=`${Y.path}:
593
- ${Y.edits.join(`
594
- `)}`;Q.length>4*768?Y.stringRepresentation="... "+Q.slice(-(4*768-4)):Y.stringRepresentation=Q}let Zt=Xe.map(Y=>Y.stringRepresentation).join(`
595
- `);for(;Xe.length>0&&Zt.length>4*2048;){Xe[0].edits.length>0?Xe[0].edits.shift():Xe.shift();for(let Y of Xe){let Q=`${Y.path}:
596
- ${Y.edits.join(`
597
- `)}`;Q.length>4*768?Y.stringRepresentation="... "+Q.slice(-(4*768-4)):Y.stringRepresentation=Q}Zt=Xe.map(Y=>Y.stringRepresentation).join(`
598
- `)}Zt.length>4*2048&&(Zt="... "+Zt.slice(-(4*2048-4))),Pn+=`Recent Manual Edits:
599
- ${Zt}
600
- `}Me.length>0&&(Pn+=`All Opened Editors: ${Me.join(", ")}`),St.diagnostics&&(Pn+=`
601
- **ACTIVE FILE ERRORS**:
602
- ${St.diagnostics}
603
- `),(R.toLowerCase().includes("lint")||R.toLowerCase().includes("warning"))&&St.warnings&&(Pn+=`
604
- **LINT WARNINGS**:
605
- ${St.warnings}
606
- `)}let er=R.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),tr=/(?:\\)?@\[([^\]]+)\]/g,Wo,Ho=[];for(tr.lastIndex=0;(Wo=tr.exec(er))!==null;){let W=Wo[0].startsWith("\\");Ho.push({tag:Wo[1],isEscaped:W})}let jo=[],fo=null;for(let W=0;W<Ho.length;W++){let{tag:Me,isEscaped:Qt}=Ho[W];if(!Qt)try{let Ie=Me.trim().replace(/^["']|["']$/g,""),Qe=/[:#]L?(\d+)(?:-L?(\d+))?$/i,We=Ie.match(Qe),ze=Ie,le=null,Ut=null;We&&(le=parseInt(We[1],10),Ut=We[2]?parseInt(We[2],10):le,ze=Ie.slice(0,We.index));let Xe=J.resolve(process.cwd(),ze);if(_e.existsSync(Xe)&&_e.statSync(Xe).isFile()){let Y=ze.toLowerCase(),Q=Y.endsWith(".pdf"),He=Y.endsWith(".docx")||Y.endsWith(".doc")||Y.endsWith(".ppt")||Y.endsWith(".pptx")||Y.endsWith(".xls")||Y.endsWith(".xlsx"),rn=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(Y),Bt=rn||Q||He,Sn=f==="Google"||fn(e);if(Bt&&!Sn){let Fe=`\u2718 Unsupported Modality: ${J.basename(ze)}`,$e=115;process.stdout.isTTY&&($e=process.stdout.columns-5||120);let mt=[Fe],Dn=Math.max(...mt.map(An=>An.length)),Fn=Math.min(Dn+4,$e),es=mt.map(An=>`${An.padEnd(Fn-2).substring(0,Fn-2)}`).join(`
607
- `);yield{type:"visual_feedback",content:yn(`${es}
608
- `)};continue}if(le===null&&!Bt){let Fe=0;try{Fe=_e.readFileSync(Xe,"utf8").split(/\r\n|\r|\n/).length}catch{}if(Fe>300){let $e=`\u21B7 Skipped (Too Large): ${J.basename(ze)}`,mt=115;process.stdout.isTTY&&(mt=process.stdout.columns-5||120);let Dn=Math.min($e.length+4,mt),Fn=$e.padEnd(Dn-2).substring(0,Dn-2);yield{type:"visual_feedback",content:yn(`${Fn}
609
- `)};continue}}let Cn=le!==null?le:1,Qn=Ut!==null?Ut:le!==null?le:Cn+299;Qn-Cn>300&&(Qn=Cn+300);let ho=`path=${JSON.stringify(ze)}, startLine=${Cn}, endLine=${Qn}`,tt=await Qs(ho,{isMultiModal:Sn}),Ye=!1,Wt="",Zn=null;if(typeof tt=="string"?tt.trim().startsWith("ERROR")?Ye=!0:Wt=tt:tt&&typeof tt=="object"&&tt.binaryPart?(Zn=tt.binaryPart,Wt=tt.text||""):Ye=!0,!Ye){let Fe="";if(rn?(Fe=`\u2714 Processed: ${J.basename(ze)}`,fo=Zn):Q||He?(Fe=`\u2714 Auto-Analysed: ${J.basename(ze)}`,fo=Zn):(Fe=`\u2714 Auto-Read: ${J.basename(ze)}`,jo.push(Wt)),Fe){let $e=115;process.stdout.isTTY&&($e=process.stdout.columns-5||120);let mt=[Fe],Dn=Math.max(...mt.map(An=>An.length)),Fn=Math.min(Dn+4,$e),es=mt.map(An=>`${An.padEnd(Fn-2).substring(0,Fn-2)}`).join(`
610
- `);yield{type:"visual_feedback",content:yn(`${es}
611
- `)}}}}}catch{}}let nr="";jo.length>0&&(nr=`[TAGGED FILE CONTENTS] Auto Read User Tagged files by System, No need to re-read
612
- `+jo.join(`
613
-
614
- `)+`
615
- [/TAGGED FILE CONTENTS]
616
- `);let Ca=er.replace(/\\(@\[[^\]]+\])/g,"$1"),Aa=g?`You cannot execute tools
617
- Instead, output in chat the exact string you WOULD have produced & wait for system response
618
- `:"",sr=`[SYSTEM METADATA]
619
- Time: ${Ne}${l?.dynamicDirAwareness?Zi:""}${Rt?`
620
- WARNING: CWD Changed from previous: "${xt}" to current: "${process.cwd()}", write change in chat to avoid future path mismatches
621
- `:""}${be}${Pn}
622
- [/METADATA]
623
- ${Ji}${r!=="Fast"&&(f==="Mistral"&&!Ks(e)||r!=="xHigh"&&f==="Google")?`${f==="Mistral"&&!Ks(e)||e.toLowerCase().startsWith("gemma")?`[SYSTEM] STRICTLY FOLLOW THINKING POLICY AS HIGH PRIORITY. DO NOT START A RESPONSE WITHOUT <think>...</think> [/SYSTEM]
624
- `:""}`:""}[SYSTEM] EXACT STRUCTURED STRING '[tool:functions.ToolName(arg="value")]' IN CHAT RESPONSE [/SYSTEM]
625
- ${nr}${Aa}[USER PROMPT] ${Ca.trim()} [/USER PROMPT]`.trim(),or={role:"user",text:sr};fo&&(or.binaryPart=fo),T.forEach(W=>{W.text&&W.role==="agent"&&(W.text=W.text.replace(/(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])/gi,""),W.text=W.text.replace(/(?:<(think|thought)>|\[(think|thought)\])[^\[\n]*/gi,"").trim())}),T.push(or),Ji&&n[n.length-1]?.id&&(yield{type:"summary_injected",content:{id:n[n.length-1].id,text:sr}});let kn=null,Bs=a==="Flux"?100:10;Bs=a.toLowerCase().includes("cu")?250:Bs;let wn=16;yield{type:"status",content:"Connecting"},Lt=!1;let ir=[],uo=!1;for(let W=0;W<=Bs;W++){let Me=await oi("agent",t);if(!Me.allowed)throw new Error(Me.reason||`Budget Exhausted for Provider (${f||"Agent"})`);let Qt=[];if(uo=!1,a==="ICU"||a==="FluxCU")try{yield{type:"status",content:"Capturing Screen"},await new Promise(ke=>setTimeout(ke,3e3));let fe=await ar();if(fe&&fe.base64){let ke="[SYSTEM] 16:9 Gridded Screen Feedback Captured. Use numeric coordinates [/SYSTEM]",ne={inlineData:{mimeType:fe.mimeType,data:fe.base64}};for(let nt of T)Array.isArray(nt.parts)&&(nt.parts=nt.parts.filter($t=>!$t.inlineData));if(T.length>0&&T[T.length-1].role==="user"){let nt=T[T.length-1];typeof nt.text=="string"&&(nt.text+=`
626
-
627
- ${ke}`,Array.isArray(nt.parts)||(nt.parts=[{text:nt.text}]),nt.parts.push(ne))}else T.push({role:"user",text:ke,parts:[{text:ke},ne]})}}catch(fe){console.error("Vision screenshot capture error:",fe)}if(l?.compression===0&&(u?.tokens||0)>P&&(T=Sr(T,6)),W>0?yield{type:"status",content:"Working"}:yield{type:"status",content:"Connecting"},Lt){try{let{clearPendingNudges:fe}=await import("./subagent_state-LZCOZSUJ.js");fe()}catch{}yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
628
-
629
- \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}try{let{consumePendingNudges:fe}=await import("./subagent_state-LZCOZSUJ.js"),ke=fe();if(ke&&ke.length>0){let ne=ke.join(`
630
-
631
- `);T.length>0&&T[T.length-1].role==="user"?T[T.length-1].text+=`
632
-
633
- ${ne}`:T.push({role:"user",text:ne}),yield{type:"status",content:"Subagent Update"}}}catch{}if(o){let fe=await o();fe&&(fe.startsWith("/btw")?T.length>0&&T[T.length-1].role==="user"?T[T.length-1].text+=`
634
-
635
- [SYSTEM] USER QUESTION. RESOLVE THIS SPECIFIC QUERY WITHIN '[ANSWER] ... [/ANSWER]' CONCISELY, NATURALLY [/SYSTEM]
636
- [QUESTION] ${fe.replace("/btw","").trim()} [/QUESTION]`:T.push({role:"user",text:`[SYSTEM] USER QUESTION. RESOLVE THIS SPECIFIC QUERY WITHIN '[ANSWER] ... [/ANSWER]' CONCISELY, NATURALLY [/SYSTEM]
637
- [QUESTION] ${fe.replace("/btw","").trim()} [/QUESTION]`}):T.length>0&&T[T.length-1].role==="user"?T[T.length-1].text+=`
638
-
639
- [STEERING HINT, HIGH PRIORITY] ${fe.trim().toUpperCase()} [/STEERING HINT]`:T.push({role:"user",text:`[STEERING HINT, HIGH PRIORITY] ${fe.trim().toUpperCase()} [/STEERING HINT]`}),yield{type:"status",content:`${fe.startsWith("/btw")?"Question Forwarded...":"Steering Hint Injected..."}`})}let Ie,Qe=!1,We=1,ze=1,le="",Ut=null,Xe=null,Zt=null,Y=0,Q=[],He=0,rn=!1,Bt=!1,Sn=!1,Cn=!1,Qn=!0,ho=0,tt="",Ye="",Wt=!1,Zn=!1,Fe=!0,$e=e,mt="";for(;We<=wn&&ze<=wn&&!Qe&&!Lt;){let fe=!1;try{le="",Qn&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},Qn=!1,ze===1&&(tt=""));let ke=v=>{if(!v||!v.includes("[tool:"))return v;let te="___THINK_OPEN_TAG___",U="___THINK_CLOSE_TAG___";v=v.replace("<think>",te).replace("</think>",U),v=v.replace(rc,(pe,ce)=>ce.includes("[tool:")?ce.trim():pe);let H="",xe=0;for(;xe<v.length;){let pe=v.indexOf("[tool:",xe);if(pe===-1){H+=v.substring(xe).replace(ya,"").replace(wa,"");break}let ce=v.substring(xe,pe);H+=ce.replace(ya,"").replace(wa,"");let bt=v.indexOf("]",pe);if(bt===-1){H+=v.substring(pe);break}H+=v.substring(pe,bt+1),xe=bt+1}return v=H,v=v.replaceAll(te,"<think>").replaceAll(U,"</think>"),v},ne=T.filter(v=>(v.role==="user"||v.role==="agent"||v.role==="system")&&!String(v.id).startsWith("welcome")&&!v.isMeta&&!v.isTerminalRecord&&!(v.text&&v.text.startsWith("[TERMINAL_RECORD]"))).map((v,te,U)=>{let H=v.text||"";m||(H=H.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),v.role==="agent"&&(H=ke(H),H=H.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),H=H.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*"));let xe=[];return Array.isArray(v.parts)&&v.parts.length>0?xe=v.parts.map(pe=>{if(pe.text){let ce=pe.text;return m||(ce=ce.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),v.role==="agent"&&(ce=ke(ce),ce=ce.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),ce=ce.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*")),{text:ce}}return pe}):xe=[{text:H}],v.binaryPart&&fn($e)&&U.slice(te+1).filter(ce=>ce.role==="user"&&!ce.text?.startsWith("[TOOL RESULT]")).length<=2&&xe.push(v.binaryPart),{role:v.role==="user"||v.role==="system"?"user":"model",parts:xe}});for(let v=0;v<ne.length;v++){let te=ne[v],U=te.parts?.[0]?.text||"";if(te.role==="model"&&/\[tool:/i.test(U)){let H=-1;for(let xe=v+1;xe<ne.length;xe++){let pe=ne[xe],ce=pe.parts?.[0]?.text||"";if(pe.role==="user"&&ce.startsWith("[TOOL RESULT]")){H=xe;break}}if(H!==-1&&H!==v+1){let[xe]=ne.splice(H,1);ne.splice(v+1,0,xe)}}}for(let v=ne.length-2;v>=0;v--){let te=ne[v],U=ne[v+1];te.role==="user"&&U.role==="user"&&(U.parts?.[0]?.text||"").trim().startsWith("[SYSTEM")&&ne.splice(v,1)}let nt=[];for(let v=0;v<ne.length;v++){let te=ne[v];if(nt.length===0)nt.push(te);else{let U=nt[nt.length-1];U.role===te.role?(U.parts[0].text+=`
640
-
641
- `+(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}|${f}|${a}|${r}|${$e}|${JSON.stringify(i)}|${!!l?.dynamicDirAwareness}|${!!l?.subAgents}`;if(Ss.key===$t&&Ss.value)mt=Ss.value;else{let v=f==="Mistral"?!!Ks($e):!($e||"gemma").toLowerCase().startsWith("gemma");mt=mr(i,(($e||"gemma").toLowerCase().startsWith("gemma"),r),a,l,m,b,f,f==="Google"?!0:y,v,d),l?.dynamicDirAwareness||(mt+=`
642
- ${Zi.replace(`
643
- **DIRECTORY STRUCTURE**`,`
644
- **DIRECTORY STRUCTURE**`)}`),Ss.key=$t,Ss.value=mt}let Ot=ne[ne.length-1];if(Po()&W>0){await new Promise(U=>setTimeout(U,2500)),yield{type:"status",content:"Verifying"};let v=await ys(),te=v?v.diagnostics:null;te&&Ot&&Ot.role==="user"&&Ot.parts?.[0]?.text&&(Ot.parts[0].text+=`
645
- ${te} [/ERROR]`),yield{type:"status",content:"Working"}}if(f==="Mistral"||f==="Google"&&e?.toLowerCase().startsWith("gemma")){let te=r!=="Fast"&&(f==="Mistral"||r!=="xHigh")?". **STRICTLY MAINTAIN THINKING POLICY. DO NOT START A RESPONSE WITHOUT <think>...</think>**":"",U=`
646
- [SYSTEM] Tool result received. Analyze output and proceed with your turn [/SYSTEM]`;Ot&&Ot.role==="user"&&Ot.parts?.[0]?.text?.startsWith("[TOOL RESULT]")&&(Ot.parts[0].text+=U)}if(l?.advanceRollback&&Ot&&Ot.role==="user"&&Ot.parts?.[0]?.text?.startsWith("[TOOL RESULT]"))try{let v=await Kn.getLatestFileChanges(d);if(v&&(v.newFiles.length>0||v.modifiedFiles.length>0||v.deletedFiles.length>0)){let te=`
647
- [SYSTEM] File Changes:
648
- `;for(let H of v.newFiles)te+=`* ${H} (created)
649
- `;for(let H of v.modifiedFiles)te+=`* ${H} (modified)
650
- `;for(let H of v.deletedFiles)te+=`* ${H} (deleted)
651
- `;te+="[/SYSTEM]",Ot.parts[0].text+=te;let U=-1;for(let H=T.length-1;H>=0;H--)if(T[H].role==="user"&&T[H].text?.startsWith("[TOOL RESULT]")){U=H;break}U!==-1&&(T[U].text+=te)}}catch{}let tn=Math.floor(Bs*(a==="Flux"?.98:.8)),vt=W+1;vt>=tn&&Ot&&Ot.parts?.[0]&&(Ot.parts[0].text+=`
652
- [SYSTEM] WARNING, Turn Limit Impending: Step ${vt}/${Bs}. Wrap up quickly/prompt user to continue. [/SYSTEM]`);let Nt=new Promise((v,te)=>{k.signal.aborted&&te(new DOMException("The user aborted a request.","AbortError")),k.signal.addEventListener("abort",()=>{te(new DOMException("The user aborted a request.","AbortError"))})});Nt.catch(()=>{});let an=ne;if(f==="Ollama")Ie=Ra(t.apiKey,$e,an,mt,r,a,y,k.signal,1,l?.ollamaEndpoint||"Cloud");else if(f==="OpenRouter")Ie=zi(t.apiKey,$e,an,mt,r,a,y,k.signal,1);else if(f==="DeepSeek")Ie=Ki(t.apiKey,$e,an,mt,r,a,y,k.signal,1.05);else if(f==="Mistral")Ie=qi(t.apiKey,$e,an,mt,r,a,y,k.signal,1);else if(f==="NVIDIA"){let v=Vi(t.apiKey,$e,an,mt,r,a,y,k.signal,1.05);Ie=dc(v,$e)}else{let te=Xi(t?.apiKey).models.generateContentStream({model:$e||"gemini-3-flash-preview",contents:an,config:{systemInstruction:mt,mediaResolution:"MEDIA_RESOLUTION_MEDIUM",safetySettings:[{category:zn.HARM_CATEGORY_HARASSMENT,threshold:Vn.BLOCK_NONE},{category:zn.HARM_CATEGORY_HATE_SPEECH,threshold:Vn.BLOCK_NONE},{category:zn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Vn.BLOCK_NONE},{category:zn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Vn.BLOCK_NONE}],thinkingConfig:(()=>{let U=($e||"").toLowerCase(),H=U.includes("gemma-4")||U.startsWith("gemma"),xe=U.includes("gemini-3");if(H||xe)return H?r.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}[r]||at.MEDIUM};{let pe={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[r]||2048;return pe===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:pe}}})()}},{signal:k.signal});Ie=await Promise.race([te,Nt])}le="",Ut=null,Zt=null,Q=[],He=0,yield{type:"model_update",content:null},Ye="",Wt=tt.length>0;let Tn="",Go=Date.now(),ss=async function*(){if(f==="Google"&&Tn){let v=Ws(Tn);for(let te of v)yield te;Tn="",Go=Date.now()}},rr=!0,os="",Es=!1,lt=null,Ws=v=>{let te=[],U=v;for(;U.length>0;)if(Es){let H=os+U;if(lt==="tool"||lt==="agent"){let ce=lt==="tool"?"[tool:functions.":"[agent:generalist.",bt=lt==="tool"?"[tool":"[agent";if(!H.startsWith(bt)||H.length>=ce.length&&!H.startsWith(ce)){te.push({type:"text",content:H}),os="",Es=!1,lt=null,U="";break}}let xe=-1,pe="]";if(lt==="tool"||lt==="agent"){let ce=0,bt=null,K=0,me=!1;for(let Ke=0;Ke<H.length;Ke++){let $=H[Ke];if(bt){if($===bt){let Tt=0;for(let Le=Ke-1;Le>=0&&H[Le]==="\\";Le--)Tt++;Tt%2===0&&(bt=null)}}else if($==='"'||$==="'"||$==="`")bt=$;else if($==="(")ce++,me=!0;else if($===")")ce--;else if($==="[")K++;else if($==="]"){if(me&&ce===0&&K===1){xe=Ke;break}K--}}}else lt==="end"?pe="[[END]]":lt==="kimi_section"?pe="<|tool_calls_section_end|>":lt==="kimi_call"&&(pe="<|tool_call_end|>"),xe=H.indexOf(pe);if(xe!==-1){let ce=pe.length;if(!lt.startsWith("kimi")){let bt=H.substring(0,xe+ce);te.push({type:"text",content:bt})}os="",Es=!1,lt=null,U=H.substring(xe+ce)}else{let ce=lt.startsWith("kimi")?8192:512;H.length>ce?(lt.startsWith("kimi")||te.push({type:"text",content:H}),os="",Es=!1):os=H,U="";break}}else{let H=U.indexOf("[tool"),xe=U.indexOf("[agent"),pe=U.indexOf("[[END]]"),ce=U.indexOf("<|tool_calls_section_begin|>"),bt=U.indexOf("<|tool_call_begin|>"),K=[{type:"tool",idx:H,start:"[tool",end:"]"},{type:"agent",idx:xe,start:"[agent",end:"]"},{type:"end",idx:pe,start:"[[END]]",end:"[[END]]"},{type:"kimi_section",idx:ce,start:"<|tool_calls_section_begin|>",end:"<|tool_calls_section_end|>"},{type:"kimi_call",idx:bt,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)}),Es=!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 Tt=$.length-1;Tt>0;Tt--)if(U.endsWith($.substring(0,Tt))){Ke=U.length-Tt;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)}),Es=!0,os=U.substring(Ke),U="";else{te.push({type:"text",content:U});break}}}return te},Ma=Ie[Symbol.asyncIterator]();for(;;){let{value:v,done:te}=await Promise.race([Ma.next(),Nt]);if(te)break;if(v&&v.type==="status"){yield v;continue}let U="",H=v.candidates?.[0]?.content?.parts;if(H&&H.length>0)for(let pe of H){let ce=typeof pe.text=="string"?pe.text:pe.text?parseChunkText(pe.text):"";pe.thought?ce&&(fe||(U+="<think>",fe=!0),U+=ce):ce&&(fe&&(U+="</think>",fe=!1),U+=ce)}else v.text&&fe&&(U+="</think>",fe=!1);U=Nn(U);let xe=U?U.trim().split(/\s+/).filter(Boolean).length:0;if(t&&typeof t.onTokenChunk=="function"&&t.onTokenChunk(U,xe),rr&&(yield{type:"status",content:"Thinking"},rr=!1),Lt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
653
-
654
- \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(U){if(Wt){if(Ye+=U,Ye.length>=64){let K=0,me=Math.min(tt.length,Ye.length);for(let $=me;$>=10;$--)if(tt.endsWith(Ye.substring(0,$))){K=$;break}let Ke=Ye.substring(K);if(Ke){let Tt=/(?:<(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(Tt)if(le+=Tt,f==="Google")Tn+=Tt;else{yield*ss();let Le=Ws(Tt);for(let oe of Le)yield oe}}Wt=!1,Ye=""}continue}else if(le+=U,f==="Google")Tn+=U;else{yield*ss();let K=Ws(U);for(let me of K)yield me}let pe=fc(le);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=_(Ke),oe=Le.path||Le.targetFile||Le.TargetFile||Le.directory,En=Le.keyword,is=Le.title||Le.task,Un=Le.id||Le.taskId,Re=Le.timeout||Le.time;if(En!=null)$=String(En).replace(ws,"");else if(oe)$=J.basename(String(oe).replace(ws,"").replace(fa,"/"));else if(is&&(me==="invoke"||me==="invoke_sync"))$=String(is).replace(ws,"").substring(0,30);else if(Un&&me==="get_progress")$=String(Un).replace(ws,"");else if(Re&&me==="await"){let Ht=parseFloat(String(Re).replace(ws,""));isNaN(Ht)?$=String(Re).replace(ws,""):(Ht<5&&(Ht=5),Ht>120&&(Ht=120),$=($n=>{if($n>=60){let Ko=Math.floor($n/60),xs=$n%60;return`${Ko}m${xs>0?` ${xs}s`:""}`}return`${$n}s`})(Ht))}else{let Ht=Ke.match(ec);if(Ht){let qt=Ht[1].replace(ws,"");me==="invoke"||me==="invoke_sync"||me==="get_progress"?$=qt.substring(0,30):$=me==="search_keyword"||me==="file_map"?qt:J.basename(qt.replace(fa,"/"))}}}let Tt=`${Gi[me]||me}${$?` ${$}`:""}`;if((me!==Ut||$!==Xe)&&(Ut=me,Xe=$,yield{type:"status",content:`${Tt}`},process.stdout.isTTY)){let oe={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;${oe}...\x07`)}}if(le.length-ho>150){ho=le.length;let K=ba(le,!1),Ke=(K.match(/(?:<think>|\[think\])([\s\S]*?)(?:<\/think>|\[\/think\]|$)/gi)||[]).join("").trim(),$=Ke.split(/[.!?]\s+/),Tt=new Set($),Le=$.length>10?($.length-Tt.size)/$.length:0,oe=Ke.split(/\s+/).filter(Ce=>Ce.length>0).length,En=.6,is=.8,Un=!1;if((f.toLowerCase().includes("google")||f.toLowerCase().includes("mistral"))&&(($e||"").toLowerCase().startsWith("gemma")||($e||"").toLowerCase().includes("stral"))){let M={low:256,medium:1024,high:8192,max:16384,xhigh:16384}[r?.toLowerCase()]||2500;Un=oe>M}if(Le>En||Un){yield{type:"status",content:`${Le>En?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},Bt=!0,await new Promise(M=>setTimeout(M,3e3));break}let qt=Sa(le).trim().split(/[.!?]\s+/),$n=new Set(qt);if((qt.length>10?(qt.length-$n.size)/qt.length:0)>is){yield{type:"status",content:"Response Loop Detected. Re-centering..."},Bt=!1,Cn=!0,await new Promise(Ce=>setTimeout(Ce,3e3));break}let xs=K.replace(ql,"").replace(Vl,"").replace(zl,"").replace(Xl,""),jt=xs.toLowerCase().split(/\s+/).map(Ce=>Ce.replace(Jl,"")).filter(Ce=>Ce.length>0),On=!1;if(jt.length>=10)for(let Ce=1;Ce<=15;Ce++){let M=Math.max(3,Math.ceil(10/Ce));if(jt.length<Ce*M)continue;let q=jt.slice(jt.length-Ce),re=q.join(" ");if(Ce>1&&re===q.slice(0,Math.floor(Ce/2)).join(" ").repeat(2).trim())continue;let ge=!0;for(let we=1;we<M;we++)if(jt.slice(jt.length-Ce*(we+1),jt.length-Ce*we).join(" ")!==re){ge=!1;break}if(ge){On=!0;break}}if(!On){let Ce=xs.toLowerCase().replace(Ql,"");if(Ce.length>=20)for(let M=1;M<=10;M++){let q=Math.max(5,Math.ceil(16/M));if(Ce.length<M*q)continue;let re=Ce.substring(Ce.length-M),ge=!0;for(let we=1;we<q;we++)if(Ce.substring(Ce.length-M*(we+1),Ce.length-M*we)!==re){ge=!1;break}if(ge){On=!0;break}}}if(On){yield{type:"status",content:"Stuttering Detected. Re-centering..."},Bt=!1,Sn=!0,await new Promise(Ce=>setTimeout(Ce,3e3));break}}let ce=le.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/gi,""),bt=Bo(ce);for(;bt.length>He;){yield*ss();let K=bt[He],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,Tt=Gi[$]||K.toolName,Le=Ts($,K.args);yield{type:"status",content:`${Tt}${Le?` ${Le}`:""}`};let oe="";if($==="click"){let M=_(K.args);oe=`\u2714 Clicked: ${M.intendedClickText?`${M.intendedClickText}`:""}`}else if($==="drag"){let M=_(K.args);oe=`\u2714 Dragged: Cell ${M.fromGridId||""} \u2192 Cell ${M.toGridId||""}`}else if($==="scroll"){let M=_(K.args);oe=`\u2714 Scrolled: ${M.direction||"down"} (${M.amount||1})`}else if($==="keyboard_typing"){let M=_(K.args);oe=`\u2714 Typed: ${M.text?`"${M.text.length>20?M.text.substring(0,20)+"...":M.text}"`:""}`}else if($==="key_press")oe=`\u2714 Pressed Key: ${_(K.args).key||""}`;else if($==="recapture_screen")oe="\u2714 Recaptured Screen";else if($==="web_search"){let{query:M,limit:q=10,aiMode:re=!1}=_(K.args);oe=`${M?"\u2714":"\u2718"} ${re?"AI Search":"Searched"}: ${M?`${M}`:"No Search Query"}${re===!1&&M?` \u2192 ${q}`:""}`}else if($==="web_scrape"){let M=_(K.args).url||null;oe=`${M?"\u2714":"\u2718"} Visited: ${M||"No Source"}`}else if($==="view_file"){let{path:M,StartLine:q,EndLine:re,start_line:ge,end_line:we,startLine:je,endLine:Oe}=_(K.args),Te=q||ge||je,Z=re||we||Oe,de=parseInt(Te)||1,ae=parseInt(Z)||(Te?de+800:800),Pe="...",Ze=ae;try{let qe=J.resolve(process.cwd(),M);if(_e.existsSync(qe)){let kt=_e.readFileSync(qe,"utf8").split(`
655
- `).length;Pe=kt,!Te&&!Z&&kt>800?Ze=Math.min(50,kt):Ze=Math.min(ae,kt)}}catch{}let Se=(M||"").toLowerCase(),ve=Se.endsWith(".pdf"),ot=Se.endsWith(".docx")||Se.endsWith(".doc")||Se.endsWith(".ppt")||Se.endsWith(".pptx")||Se.endsWith(".xls")||Se.endsWith(".xlsx"),Ae=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(Se);ve||ot?oe=`${M.length>0?"\u2714":"\u2718"} ${M?`Analyzed: ${J.basename(M)}`:"Analyzed: File Not Found"}`:Ae?oe=`${M.length>0?"\u2714":"\u2718"} ${M?`Processed: ${J.basename(M)}`:"Processed: File Not Found"}`:oe=`${Pe!=="..."?"\u2714":"\u2718"} Read: ${M?`${J.basename(M)} \u2192 ${Pe!=="..."?`Lines ${de} - ${Ze} of ${Pe}`:"File Not Found"}`:"File Not Found"}`}else if($==="list_files"||$==="read_folder"){let M=$==="list_files"?"List":"Browsed",q=_(K.args).path||null,re=_(K.args).recurse||1;oe=`${q?"\u2714":"\u2718"} ${M}: ${q?`${q==="."?`./${re>1?"*":""}`:`${q.replaceAll("\\","/")}${re>1?`${q.endsWith("/")?"*":"/*"}`:`${q.endsWith("/")?"":"/"}`}`}`:"No Folder Selected"}`}else if($==="write_file"||$==="update_file"){let M=$==="write_file"?"Created":"Edited",q=_(K.args).path||null;oe=`${q?"\u2714":"\u2718"} ${M}: ${q.replaceAll("\\","/")||"No File Changes"}`}else if($==="write_pdf"){let M=_(K.args).path||null;oe=`${M?"\u2714":"\u2718"} Generated: ${M.replaceAll("\\","/")||"No PDF Generated"}`}else if($==="write_docx"){let M=_(K.args).path||null;oe=`${M?"\u2714":"\u2718"} Generated: ${M.replaceAll("\\","/")||"No Docx Generated"}`}else if($==="file_map"){let M=_(K.args).path;oe=`${M?"\u2714":"\u2718"} Indexed: ${M.replaceAll("\\","/")?""+M:"File Not Found"}`}else if($.toLowerCase()==="search_keyword"||$.toLowerCase()==="todo")oe="";else if($.toLowerCase()==="generate_image"){let{path:M,outputPath:q,output:re}=_(K.args);oe=`\u2714 Generated: ${M||q||re||"generated_image.png"}`}else if($==="invoke_sync"||$==="InvokeSync"){let M=Ts($,K.args);oe=`\u2714 Called Generalist${M?`: ${M}`:""}`}else if($==="Invoke"||$==="InvokeAsync"||$==="invoke"){let M=Ts($,K.args);oe=`\u2714 Started Generalist${M?`: ${M}`:""}`}else if($==="get_progress"||$==="GetProgress"){let M=Ts($,K.args);oe=`\u2714 Checked${M?`: ${M}`:""}`}else if($==="cancel"){let M=Ts($,K.args);oe=`\u{1F6C7} Cancelled${M?`: ${M}`:""}`}else if($==="steer"||$==="Steer"){let M=Ts($,K.args);oe=`\u2714 Steered${M?`: ${M}`:""}`}else if($==="EmergencyRollback"){let{method:M}=_(K.args);oe=M==="forceRevert"?"":"\u2714 Rollback Point Checked"}else if($==="await"||$==="Await"){let{time:M,timeout:q}=_(K.args),re=parseFloat(q||M)||0;re||(re=120);let ge=Oe=>{if(Oe>=60){let Te=Math.floor(Oe/60),Z=Oe%60;return`${Te}m${Z>0?` ${Z}s`:""}`}return`${Oe}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"];oe=`\u2714 ${we[Math.floor(Math.random()*we.length)]} \u2192 ${ge(re)}`}else $==="Answer"||$==="answer"?oe="\u2714 Resolved Sub-Agent Query":$==="exec_command"||$==="ask"?oe="":oe=`Executed: ${K.toolName}`;if(yield*ss(),$==="exec_command"){let{command:M}=_(K.args);if(M&&t.systemSettings&&t.systemSettings.allowExternalAccess===!1){let q=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],re=J.resolve(process.cwd()).substring(0,3).toLowerCase(),ge=Z=>{let de=[],ae="",Pe=null;for(let Ze=0;Ze<Z.length;Ze++){let Se=Z[Ze];Pe?(Se===Pe&&(Pe=null),ae+=Se):Se==='"'||Se==="'"?(Pe=Se,ae+=Se):Se==="&"&&Z[Ze+1]==="&"||Se==="|"&&Z[Ze+1]==="|"?(ae.trim()&&(de.push(ae.trim()),ae=""),Ze++):Se===";"||Se==="|"||Se==="&"?ae.trim()&&(de.push(ae.trim()),ae=""):ae+=Se}return ae.trim()&&de.push(ae.trim()),de},we=Z=>{let de=[],ae="",Pe=null;for(let Ze=0;Ze<Z.length;Ze++){let Se=Z[Ze];Pe?(Se===Pe&&(Pe=null),ae+=Se):Se==='"'||Se==="'"?(Pe=Se,ae+=Se):/\s/.test(Se)?ae&&(de.push(ae),ae=""):ae+=Se}return ae&&de.push(ae),de},je=Z=>{let de=Z.replace(/^['"]|['"]$/g,"").trim();return!de||process.platform==="win32"&&/^\/[a-zA-Z0-9?]+$/.test(de)?!1:q.some(ae=>{if(ae.source==="[a-zA-Z]:[\\\\\\/]"){let Pe=de.match(/[a-zA-Z]:[\\\/]/i);return Pe&&Pe[0].toLowerCase()!==re}return ae.test(de)})};if(ge(M).some(Z=>{let de=we(Z);if(de.length===0)return!1;let ae=de[0].replace(/^['"]|['"]$/g,"").toLowerCase();if(["echo","printf","write-output"].includes(ae)){let Ze=!1;return de.some(Se=>{let ve=Se.replace(/^['"]|['"]$/g,"");if(ve===">"||ve===">>"||ve==="<")return Ze=!0,!1;if(ve.startsWith(">")||ve.startsWith("<")){let ot=ve.replace(/^[><]+/,"");return je(ot)}return Ze?(Ze=!1,je(Se)):!1})}return de.some(Ze=>je(Ze))})){let Z='Access Denied. Prohibited from accessing external directories while "External Workspace Access" is disabled.';t.onExecStart&&t.onExecStart(M||"No Command"),yield{type:"exec_start"},await new Promise(de=>setTimeout(de,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${Z}`),await new Promise(de=>setTimeout(de,50)),t.onExecEnd&&t.onExecEnd(),Q.push({role:"user",text:`[TOOL RESULT]: ERROR: ${Z}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${Z}`},He++;continue}}t.onExecStart&&t.onExecStart(M||"No Command"),yield{type:"exec_start"}}let En=_(K.args),is=En.path||En.targetPath||null;if(is){let M=t.systemSettings&&t.systemSettings.allowExternalAccess===!1,q=J.resolve(is),re=J.resolve(process.cwd());if(M&&!q.startsWith(re)){let ge="Access Denied. You are not allowed to access files outside the current workspace.";if($==="write_file"||$==="update_file"){let je=`\u2718 ${$==="write_file"?"Write Canceled":"Edit Canceled"}: ${En.path||"..."}`,Oe=115;process.stdout.isTTY&&(Oe=process.stdout.columns-5||120);let Te=Math.min(je.length+4,Oe),Z=`${je.padEnd(Te-2).substring(0,Te-2)}`;yield{type:"visual_feedback",content:yn(`${Fe?`
656
- `:""}${Z}
657
- `)},Fe=!1}Q.push({role:"user",text:`[TOOL RESULT]: ERROR: ${ge}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${ge}`},He++;continue}}if(t.onToolApproval&&($==="write_file"||$==="update_file"||$==="exec_command")){let q=t.systemSettings||{},re=q.autoExec,ge=null,we=!1,je=!1,Oe=!1;if($==="exec_command"){let{command:ve}=_(K.args),ot=(ve||"").trim(),Ae=(kt,Vt)=>{if(!Vt)return!1;let ln=Vt.split(",").map(zt=>zt.trim().toLowerCase()).filter(Boolean),it=kt.toLowerCase();return ln.some(zt=>it.startsWith(zt))},qe=Ae(ot,q.alwaysAskCommands),Ee=Ae(ot,q.autoApproveCommands);if(je=Ae(ot,q.autoDisallowCommands),qe?we=!0:(Ee||q.autoApproveGit&&/^git\s+commit\b/i.test(ot))&&(ge="allow"),!we&&!ge){if(q.networkAccess===!1){let Vt=ot.trim().replace(/\s+/g," ").replace(/^['"]+|['"]+$/g,"").toLowerCase().split(" "),it=Vt[0].split("/").pop().split("\\").pop().replace(/\.exe$/,""),zt=new Set(["curl","wget","httpie","xh","ssh","scp","sftp","rsync","ftp","lftp","tftp","telnet","nc","netcat","socat","ping","traceroute","tracert","dig","nslookup","host","whois","nmap","docker","podman","kubectl","helm","gcloud","aws","az","terraform","ansible-playbook","nix","nix-env","apt","apt-get","dpkg","yum","dnf","pacman","zypper","brew","apk","choco","scoop","conda","mamba","aria2c","axel","smbclient","lynx","w3m","links","elinks","heroku","netlify","vercel","firebase","supabase","wrangler","flyctl","powershell","pwsh","certutil","bitsadmin","cloudflared","ngrok","tailscale","zerotier","rclone"]),rt=!1;zt.has(it)&&(rt=!0);let ct=xn=>Vt.slice(1).some(Rn=>xn.includes(Rn)),Mt=xn=>{let Rn=Vt.findIndex(Mn=>xn.includes(Mn)),Rs=Vt.findIndex(Mn=>["run","exec","test"].includes(Mn));return Rn!==-1&&!(Rs!==-1&&Rs<Rn)};it==="git"&&ct(["clone","pull","push","fetch"])&&(rt=!0),it==="go"&&ct(["get","install"])&&(rt=!0),it==="npm"&&Mt(["install","i","update","add"])&&(rt=!0),it==="yarn"&&Mt(["add","install","upgrade"])&&(rt=!0),it==="pnpm"&&Mt(["add","install","update"])&&(rt=!0),it==="bun"&&Mt(["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",Oe=!0)}!ge&&je&&(ge="deny")}!we&&!ge&&re&&(ge="allow")}else re&&(ge="allow");let Te=ge,Z="";ge==="deny"&&(Oe?Z="network":je?Z="settings":Z="prohibited");let de=!1,ae="",Pe=[],Ze=0,Se=!1;if(!Te){if($==="write_file"||$==="update_file")try{let Ae=_(K.args),{path:qe}=Ae;if(qe){let Ee=J.resolve(process.cwd(),qe),kt=ct=>ct?ct.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,Mt=>Mt.toUpperCase()):"",Vt=kt(Ee),ln="",it=!1,zt=await ys(),rt=kt(zt?.file_focused);if(zt&&rt===Vt&&zt.full_content?(ln=zt.full_content,it=!0):_e.existsSync(Ee)&&(ln=_e.readFileSync(Ee,"utf8"),it=!0),ae=ln,await ft.recordFileChange(Ee,ln),it){let ct=ln;if($==="write_file")ct=Ae.content||Ae.newContent||"";else{let{patchPairs:Mt,allowMultiple:xn,error:Rn}=Ao(Ae);if(Rn){let Ct=`[TOOL RESULT]: ERROR: ${Rn}`;Q.push({role:"user",text:Ct}),await It("toolFailure"),t.onToolResult&&t.onToolResult("failure",$),yield{type:"tool_result",content:Ct,toolName:$},He++;continue}let Rs=Ae.allowMultiple!==void 0?Ae.allowMultiple===!0||String(Ae.allowMultiple).toLowerCase()==="true":xn;Ze=Mt.length;let Mn=$o(ln,Mt,{allowMultiple:Rs});ct=Mn.content,Pe=Mn.results;let po=Pe.filter(Ct=>Ct.success),_t=Pe.filter(Ct=>!Ct.success);if(po.length===0){let Ct=`[TOOL RESULT]: ERROR: Failed to apply patches to [${J.basename(Ee)}].
658
- ${_t.map(Gs=>` \u2022 ${Gs.error}`).join(`
659
- `)}`,bs=`\u2714 Edited: ${J.basename(Ee.replaceAll("\\","/"))}`,js=115;process.stdout.isTTY&&(js=process.stdout.columns-5||120);let ks=Math.min(bs.length+4,js),mo=`${bs.padEnd(ks-2).substring(0,ks-2)}`;yield{type:"visual_feedback",content:yn(`${Fe?`
660
- `:""}${mo}`)},Fe=!1,Q.push({role:"user",text:Ct}),await It("toolFailure"),t.onToolResult&&t.onToolResult("failure",$),yield{type:"tool_result",content:Ct,toolName:$},He++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${J.basename(Ee)}`},Bi(Ee,ln,ct),de=!0,await new Promise(Mt=>setTimeout(Mt,50))}else if($==="write_file"){let ct=Ae.content||Ae.newContent||"",Mt=ct.endsWith(`
661
- `)?ct:ct+`
662
- `;_e.existsSync(Ee)||(Se=!0,_e.mkdirSync(J.dirname(Ee),{recursive:!0}),_e.writeFileSync(Ee,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${J.basename(Ee)}`},Bi(Ee,"",Mt),de=!0,await new Promise(xn=>setTimeout(xn,50))}}}catch(Ae){console.error("Simulation/Diff Error:",Ae)}let ve=null;Ui(Ae=>{ve=Ae});let ot=t.onToolApproval;if(Te=await new Promise(async Ae=>{let qe=setInterval(()=>{ve&&(Do.onIDEApproval&&Do.onIDEApproval(ve),clearInterval(qe),Ae(ve))},100);try{let Ee=await ot($,K.args);clearInterval(qe),Ae(Ee)}catch{clearInterval(qe),Ae("deny")}}),Ui(null),$==="write_file"||$==="update_file"){let{path:Ae}=_(K.args);if(Ae){let qe=J.resolve(process.cwd(),Ae);if(ca(qe,Te),Te==="deny"&&Se&&_e.existsSync(qe))try{_e.unlinkSync(qe)}catch{}}}Te==="deny"&&(Z="user")}if(Te==="allow"&&de&&Po()){let{path:ve}=_(K.args),ot=J.resolve(process.cwd(),ve),Ae=_t=>_t?J.resolve(_t).replace(/\\/g,"/").toLowerCase():"",qe=await ys(),Ee="";qe&&qe.file_focused&&Ae(qe.file_focused)===Ae(ot)&&qe.full_content&&(Ee=qe.full_content),!Ee&&_e.existsSync(ot)&&(Ee=_e.readFileSync(ot,"utf8"),Ee||(await new Promise(_t=>setTimeout(_t,100)),Ee=_e.readFileSync(ot,"utf8")));let kt=Ee.split(/\r?\n/),Vt=kt.length,ln=Buffer.byteLength(Ee,"utf8"),it="";ae&&(it=`Old File contents:
663
- ${ae.split(/\r?\n/).map((Ct,bs)=>`${bs+1} | ${Ct}`).join(`
664
- `)}
665
-
666
- `);let zt="";if(Vt<=100)zt=kt.join(`
667
- `);else{let _t=kt.slice(0,50).join(`
668
- `),Ct=kt.slice(-50).join(`
669
- `);zt=`${_t}
670
-
671
- ... [${Vt-100} lines truncated for history stability] ...
672
-
673
- ${Ct}`}let rt="";if($==="update_file"){let _t=Oo(ae,Ee,Pe,12,t?.compressToolResults||Do?.systemSettings?.compressToolResults);rt=`SUCCESS: File [${ve}] updated via IDE Companion (May have user edits). [${Pe.length}/${Ze}] blocks applied.
674
-
675
- ${_t}`}else{let _t=Ee.split(/\r?\n/),Ct=_t.length,bs=Buffer.byteLength(Ee,"utf8"),js="";ae&&(js=`Old File contents:
676
- ${ae.split(/\r?\n/).map((Gs,Da)=>`${Da+1} | ${Gs}`).join(`
677
- `)}
678
-
679
- `);let ks="";if(Ct<=100)ks=_t.join(`
680
- `);else{let mo=_t.slice(0,50).join(`
681
- `),Gs=_t.slice(-50).join(`
682
- `);ks=`${mo}
683
-
684
- ... [${Ct-100} lines truncated] ...
685
-
686
- ${Gs}`}rt=`SUCCESS: File [${ve}] saved via IDE Companion (May have user edits).
687
- - Stats: [${Ct} lines, ${(bs/1024).toFixed(1)} KB]
688
- ${js}- Content Preview:
689
-
690
- ${ks}`}let Mt=`${ve?"\u2714":"\u2718"} ${$==="write_file"?"Created":"Edited"}: ${ve.replaceAll("\\","/")||"No File Changes"}`,xn=115;process.stdout.isTTY&&(xn=process.stdout.columns-5||120);let Rn=Math.min(Mt.length+4,xn),Rs=`${Mt.padEnd(Rn-2).substring(0,Rn-2)}`;yield{type:"visual_feedback",content:yn(`${Fe?`
691
- `:""}${Rs}`)},Fe=!1;let Mn=Date.now();Y=Mn,yield{type:"tool_time",content:Mn-me};let po=`[TOOL RESULT]: ${rt}`;Q.push({role:"user",text:po}),rn=!0,await It("toolSuccess"),t.onToolResult&&t.onToolResult("success",$),yield{type:"tool_result",content:rt,aiContent:po,toolName:$},He++;continue}if(Te==="deny"){let ve=`Permission Denied: Prohibited ${$==="exec_command"?"Command":"file edit"}.`;if(Z==="user"?ve="Permission Denied by User":Z==="settings"?ve="Permission Denied by User Policy":Z==="network"?ve="Permission Denied: Sandbox Network Access Disabled by User Policy.":Z==="prohibited"&&$==="exec_command"&&(ve="Permission Denied: Prohibited Command in User Policy"),$==="write_file"||$==="update_file"){let Ae=`\u2718 ${$==="write_file"?"Write Cancelled":"Edit Denied"}: ${_(K.args).path.replaceAll("\\","/")||"..."}`,qe=115;process.stdout.isTTY&&(qe=process.stdout.columns-5||120);let Ee=Math.min(Ae.length+4,qe),kt=`${Ae.padEnd(Ee-2).substring(0,Ee-2)}`,Vt=` ${" ".repeat(Ee)} `;yield{type:"visual_feedback",content:yn(`${Fe?`
692
- `:""}${kt}
693
- `)},Fe=!1}$==="exec_command"&&(await new Promise(ot=>setTimeout(ot,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${ve}`),await new Promise(ot=>setTimeout(ot,50)),t.onExecEnd&&t.onExecEnd()),Q.push({role:"user",text:`[TOOL RESULT]: DENIED: ${ve}`}),yield{type:"tool_result",content:`[TOOL RESULT]: DENIED: ${ve}`},await It("toolDenied"),t.onToolResult&&t.onToolResult("denied",$),He++;continue}}if(oe){let M=115;process.stdout.isTTY&&(M=process.stdout.columns-5||120);let q=Math.min(oe.length+4,M),re=`${oe.padEnd(q-2).substring(0,q-2)}`;yield{type:"visual_feedback",content:yn(`${Fe?`
694
- `:""}${re}${oe.includes("\u2714")&&(oe.includes("Created")||oe.includes("Edited"))?"":`
695
- `}`)},Fe=!1}if(Y>0){let M=Date.now()-Y,q=Math.max(0,1e3-M);q>0&&await new Promise(re=>setTimeout(re,q))}let Un={chatId:d,history:n,onChunk:M=>t.onExecChunk?t.onExecChunk(M):null,onAskUser:t.onAskUser,systemSettings:t.systemSettings,mode:a,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:M}=_(K.args);if(M){let q=J.resolve(process.cwd(),M),re=await ys();re&&re.file_focused===q&&re.full_content&&(Un.forcedContent=re.full_content)}}catch{}Qt.push($);let Re=await ao($,K.args,Un);if(($==="write_file"||$==="update_file")&&Re.startsWith("SUCCESS")){let{path:M}=_(K.args);if(M){let q=J.resolve(process.cwd(),M);la(q)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let Ht=Date.now();Y=Ht,yield{type:"tool_time",content:Ht-me},Zt=Ht;let qt=null;if(typeof Re=="object"&&Re.binaryPart&&(qt=Re.binaryPart,Re=Re.text),$==="search_keyword"){let{keyword:M,path:q}=_(K.args),re=typeof Re=="string"&&Re.startsWith("[GLOB]");re&&(Re=Re.slice(6).trimStart());let ge=typeof Re=="string"&&Re.startsWith("[DIR]");ge&&(Re=Re.slice(5).trimStart());let we=0;if(Re){let Pe=Re.match(/Found (\d+) match/i);Pe&&(we=parseInt(Pe[1]))}let je=q?q.replace(/[\/\\]+$/,""):null,Oe=je&&je!=="."?`"${re?q:ge?`${je}/*`:je}"`:"./",Te=`${M?"\u2714":"\u2718"} Searched: "${M||""}" in ${Oe.replaceAll("\\","/")} \u2192 ${we} Match${we===1?"":"es"}`,Z=115;process.stdout.isTTY&&(Z=process.stdout.columns-5||120);let de=Math.min(Te.length+4,Z),ae=`${Te.padEnd(de-2).substring(0,de-2)}`;yield{type:"visual_feedback",content:yn(`${Fe?`
696
- `:""}${ae}
697
- `)},Fe=!1}if($==="EmergencyRollback"){let{method:M}=_(K.args);if(M==="forceRevert"){let q=0;if(Re){let Te=Re.match(/Total\s*:\s*(\d+)/i);Te&&(q=parseInt(Te[1]))}let ge=Re&&Re.startsWith("ERROR:")?"\u2718 Emergency Rollback Failed":`\u2714 Emergency Rollback \u2192 ${q} file${q===1?"":"s"} processed`,we=115;process.stdout.isTTY&&(we=process.stdout.columns-5||120);let je=Math.min(ge.length+4,we),Oe=`${ge.padEnd(je-2).substring(0,je-2)}`;yield{type:"visual_feedback",content:yn(`${Fe?`
698
- `:""}${Oe}
699
- `)},Fe=!1}}if($==="todo"){let{method:M,tasks:q,markDone:re}=_(K.args),ge="",we=[],je=Oe=>{if(!Oe)return[];let Te=Array.isArray(Oe)?Oe:[];if(Te.length===0&&typeof Oe=="string"){let Z=Oe.trim();if(Z.startsWith("[")&&Z.endsWith("]")){let de=Z.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);de?Te=de.map(ae=>ae.slice(1,-1).replace(/\\(.)/g,"$1")):Te=Z.slice(1,-1).split(",").map(ae=>ae.trim()).filter(Boolean)}else Te=Oe.split(`
700
- `)}return Te.filter(Z=>String(Z).trim()).map(Z=>{let de=String(Z).trim();return de.startsWith("- [")?de.substring(6).trim():de})};if(M==="create"?(ge="\x1B[32m\u2192\x1B[0m Created Plan",we=je(q).map(Oe=>`\x1B[90m\u25CB\x1B[0m ${Oe}`)):M==="append"?(ge="\x1B[34m\u2795\x1B[0m Added Plan",we=je(q).map(Oe=>`\x1B[90m\u25CB\x1B[0m ${Oe}`)):M==="get"&&(ge=re?"\x1B[36m\u21BB\x1B[0m Updated Plan":"\x1B[35m\u2022\x1B[0m Reviewed Plan",we=(Re||"").split(`
701
- `).slice(1).join(`
702
- `).split(`
703
- `).filter(Te=>Te.trim().startsWith("- [")).map(Te=>{let Z=Te.trim(),de=Z.startsWith("- [x]");return`${de?"\x1B[32m\u2714\x1B[0m":"\x1B[90m\u25CB\x1B[0m"} ${de?"\x1B[90m":"\x1B[37m"}${Z.substring(6).trim()}\x1B[0m`})),ge&&we.length>0){let Oe=[`${ge}`,...we.map(Te=>` ${Te}`)].join(`
704
- `);yield{type:"visual_feedback",content:yn(`${Fe?`
705
- `:""}${Oe}
706
- `)},Fe=!1}}$==="exec_command"&&t.onExecEnd&&(await new Promise(M=>setTimeout(M,800)),t.onExecEnd());let $n=Re&&Re.startsWith("DENIED:");Re&&!Re.startsWith("ERROR:")&&!$n?(await It("toolSuccess"),t.onToolResult&&t.onToolResult("success",$)):$n||(await It("toolFailure"),t.onToolResult&&t.onToolResult("failure",$));let jt=(Re||"").toString().replaceAll("[UI_CONTEXT]","");jt.includes("[[VERIFIED]]")&&(jt=jt.replace(/\[\[VERIFIED\]\][\s\S]*?\[\[\/VERIFIED\]\]/g,`[SYSTEM NOTE]: Patch Block matched & applied successfully. Large Block omitted to conserve context.
707
- `));let On;if(jt.startsWith("[[SAME]]")){let q=jt.replace(/^\[\[SAME\]\]\s*\r?\n?/,"").split(/\r?\n/),re=q.filter(we=>we.startsWith("SUCCESS:")||we.trim().startsWith("- Stats:"));On=`[TOOL RESULT]: ${re.length>0?re.join(`
708
- `):q.slice(0,2).join(`
709
- `)}
710
- [SYSTEM NOTE]: Content verified and persisted to disk. Full preview omitted to conserve context.`}else On=`[TOOL RESULT]: ${jt}`;Q.push({role:"user",text:On,binaryPart:qt}),rn=!0;let Ce=`[TOOL RESULT]: ${Re.replaceAll(`[[VERIFIED]]
711
- `,"").replaceAll(`
712
- [[/VERIFIED]]`,"")||""}`;($==="view_file"||$==="web_scrape"||$==="file_map")&&(Ce=`[TOOL RESULT]: ${oe} (Context Locked for UI Clarity)`),yield{type:"tool_result",content:Ce,aiContent:On,binaryPart:qt,toolName:$},$==="memory"&&Re.includes("SUCCESS")&&(yield{type:"memory_updated"}),He++}if(f==="Google"&&Tn&&Date.now()-Go>=150){yield*ss();let K=Ws(Tn);for(let me of K)yield me;Tn="",Go=Date.now()}}v.usageMetadata&&(kn=v.usageMetadata),kn&&(yield{type:"liveTokens",content:kn.totalTokenCount})}if(fe&&(fe=!1,Wt?Ye+="</think>":(le+="</think>",f==="Google"?Tn+="</think>":yield{type:"text",content:"</think>"})),Wt&&Ye.length>0){let v=0,te=Math.min(tt.length,Ye.length);for(let H=te;H>0;H--)if(tt.endsWith(Ye.substring(0,H))){v=H;break}let U=Ye.substring(v);if(U){let xe=/(?:<(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(xe)if(le+=xe,f==="Google")Tn+=xe;else{yield*ss();let pe=Ws(xe);for(let ce of pe)yield ce}}Wt=!1,Ye=""}if(yield*ss(),Lt)break;let Hs=(le||"").trim(),_a=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(Hs.toLowerCase())||/\[\[END\]\]/i.test(Hs.toLowerCase()),Ia=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(Hs.toLowerCase()),La=Q.length>0||Ut!==null,Yo=Hs.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/gi,"").trim(),va=/(\p{Emoji_Presentation}|\p{Extended_Pictographic})$/u.test(Yo),Na=/([.!?"'*_`|\]\)”’~~]+|\s|`{3}|[\u200B-\u200D\uFEFF])$/u.test(Yo.trim()),Pa=/[.!?}"'`’“”]$|```$/s.test(Yo)||Na||va;!_a&&!Ia&&!La&&Hs.length>0,Qe=!0,await It("agent",f)}catch(ke){if(Lt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
713
-
714
- \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(String(ke).includes("Incomplete JSON segment at the end")){fe&&(fe=!1,Wt?Ye+="</think>":(le+="</think>",yield{type:"text",content:"</think>"})),Qe=!0,await It("agent",f);break}if(fe&&(fe=!1,Wt?Ye+="</think>":le+="</think>"),Wt&&Ye.length>0){let ns=0,tn=Math.min(tt.length,Ye.length);for(let Nt=tn;Nt>0;Nt--)if(tt.endsWith(Ye.substring(0,Nt))){ns=Nt;break}let vt=Ye.substring(ns);if(vt){let an=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(tt)?vt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):vt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");an&&(le+=an)}Wt=!1,Ye=""}let ne=ke instanceof Error?(()=>{try{return JSON.parse(JSON.parse(ke.message).error.message).error.message}catch{return String(ke)}})():String(ke),nt=new Date().toLocaleString(),$t=J.join(cn,"agent");_e.existsSync($t)||_e.mkdirSync($t,{recursive:!0}),_e.appendFileSync(J.join($t,"error.log"),`ERROR [${nt}]: ${ne}
715
-
716
- ----------------------------------------------------------------------
717
-
718
- `);let en=ke.status||ke.statusCode||ke.code;if(!(en&&(en>=500&&en<600||en===408||en===429)||!en&&(/status[ :]+(5\d\d|408|429)/i.test(String(ke))||/code[ :]+(5\d\d|408|429)/i.test(String(ke))||/(500|503|408|429)/.test(String(ke))))){if(We<wn-3)throw ke;yield{type:"text",content:ne},yield{type:"status",content:"Error Occured"}}if(le.trim().length>0||ze>1)if(ze<=wn){ze++;let ns=Math.min(1e3*Math.pow(2,ze-1),24e3);if(le.trim().length>0){T.push({role:"agent",text:le});let tn=`[SYSTEM]
719
- - SEAMLESS CONTINUATION: Resume immediately. Pick up from last words with zero gap/disruption
720
- - NO REPETITION: Do not repeat any text already written
721
- - NO RE-THINK: Do not restart or open <think> if reasoning already started. Continue the thinking and close thinking block </think> BEFORE CHAT OUTPUT
722
- - MID-TOOL SAFETY: If cutoff was mid-tool call, restart that tool call from start
723
- - STEALTH: Do not mention/apologize for cutoff [/SYSTEM]`;Q.length>0?Q.forEach((vt,Nt)=>{Nt===Q.length-1?T.push({...vt,text:`${vt.text}
724
-
725
- ${tn}`}):T.push(vt)}):T.push({role:"user",text:tn}),tt+=le}for(let tn=ns/1e3;tn>0&&!Lt;tn--)yield{type:"status",content:`Error Occured. Recovering Stream (${ze}/${wn}) [Retrying in ${tn.toFixed(0)}s]...`},await new Promise(vt=>setTimeout(vt,1e3));yield{type:"status",content:"Error Occured. Recovering Stream..."}}else throw new Error(`Stream collapsed too many times. (Failed to resolve ${wn} times)
726
- Error log can be found in \`/export logs\``);else if(We<=wn){We++,ze=1,tt="";let ns=Math.min(1e3*Math.pow(2,We-1),32e3),tn=.8+Math.random()*.4,vt=Math.round(ns*tn);Qn=!0,yield{type:"status",content:`Trying to reach ${e} (${We}/${wn}) [Retrying in ${(vt/1e3).toFixed(0)}s]`};for(let Nt=vt/1e3;Nt>0&&!Lt;Nt--)yield{type:"status",content:`Trying to reach ${e} (${We}/${wn}) [Retrying in ${Nt.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 ${wn} times)
727
- Error log can be found in \`/export logs\``)}}if(kn){let fe=kn.totalTokenCount||0,ke=kn.cachedContentTokenCount||0,ne=(kn.candidatesTokenCount||0)+(kn.thoughtsTokenCount||0);await Gt("tokens",fe,f,$e),ke>0&&await Gt("cachedTokens",ke,f,$e),ne>0&&await Gt("candidateTokens",ne,f,$e),yield{type:"usage",content:kn}}ir.push(le);let Dn=le;le.match(/(?:<think>|\[think\])([\s\S]*?)(?:<\/think>|\[\/think\])/i)&&(Dn=le.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/i,""));let es=Sa(le),An=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(es.toLowerCase())||/\[\[END\]\]/i.test(es.toLowerCase())||!0,Sc=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(es.toLowerCase()),Tc=He>0;yield{type:"status",content:"Thinking"};let $a=uc(le,/(\[\s*(turn\s*:)?\s*(continue|finish)\s*\]|\[\[END\]\])/gi,"").trim(),ts=(An||Q.length===0)&&!Bt&&!Sn&&!Cn;if(ts=Q.length===0?ts:!1,ts=Zn||uo?!1:ts,le&&le.trim().endsWith('")]')&&Q.length===0&&(ts=!1),ts){let fe=ir.join(`
728
- `),ke=fe.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").trim();yield{type:"interactive_turn_finished",data:{agentText:R,fullAgentTextRaw:fe,history:[...T],needTitle:S}},T.length>0&&T[T.length-1].role==="agent"?T[T.length-1].text=ke:T.push({role:"agent",text:ke}),T.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(`
729
-
730
- [SYSTEM] USER QUESTION. RESOLVE THIS SPECIFIC QUERY WITHIN '[ANSWER] ... [/ANSWER]' CONCISELY, NATURALLY [/SYSTEM]
731
- `,"").replaceAll(`[SYSTEM] USER QUESTION. RESOLVE THIS SPECIFIC QUERY WITHIN '[ANSWER] ... [/ANSWER]' CONCISELY, NATURALLY
732
- **STRICTLY FOLLOW THINKING POLICY AS HIGH PRIORITY. DO NOT START A RESPONSE WITHOUT <think>...</think>** [/SYSTEM]
733
- `,"").replaceAll(`[SYSTEM] **STRICTLY FOLLOW THINKING POLICY AS HIGH PRIORITY. DO NOT START A RESPONSE WITHOUT <think>...</think>** [/SYSTEM]
734
- `,"").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,""),(f==="Mistral"||f==="Google"&&e?.toLowerCase().startsWith("gemma"))&&ne.text.startsWith("[TOOL RESULT]"))){let $t=`
735
- [SYSTEM] Tool result received. Analyze output and proceed with your turn [/SYSTEM]`,en=`
736
- [SYSTEM] Tool result received. Analyze output and proceed with your turn. **STRICTLY MAINTAIN 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 Oa=$a.trim()||"*Working...*";if(T.push({role:"agent",text:Oa}),Q.length>0||rn){if(Q.length>0){let fe=Q.map($t=>$t.text).join(`
737
-
738
- `),ne=(le.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/gi,"").match(/\[tool:functions/g)||[]).length;if(Q.length<ne){fe+=`
739
-
740
- [SYSTEM] Only ${Q.length} out of ${ne} attempted tool calls were executed. Verify proper schema compliance & try failed calls again [/SYSTEM]`;let $t=ne-Q.length;for(let en=0;en<$t;en++)await It("toolFailure")}let nt=Q.find($t=>$t.binaryPart)?.binaryPart||null;T.push({role:"user",text:fe,binaryPart:nt})}}else uo||Zn?(T.push({role:"user",text:"[SYSTEM] Failed to execute some tools. Verify proper schema compliance & try again [/SYSTEM]"}),await It("toolFailure")):T.push({role:"user",text:`[SYSTEM] ${Sn&&!Bt?"STUTTERING DETECTED by Internal System. Re-calibrate your response & proceed.":`${Bt?" OVER THINKING":" LOOP"} DETECTED by Internal System${Bt?" for current EFFORT_LEVEL":""}. ${Bt?"If you have planned the task, prioritize execution/output":"If you have finished your task provide a simple summary and end"}`} [/SYSTEM]`}),Bt=!1,Sn=!1,Cn=!1;l?.advanceRollback&&await Kn.recordTurnDelta(d,W+1,Qt),uo=He>0||rn}}catch(k){let L=(k instanceof Error?(()=>{try{return JSON.parse(JSON.parse(k.message).error.message).error.message}catch{return k.message||String(k)}})():String(k)).replace(/^(Error:\s*)+/i,""),I=new Date().toLocaleString(),P=J.join(cn,"agent");yield{type:"text",content:`\u2726 CRITICAL ERROR: ${L.includes("fetch failed")?"Failed to Connect. Check your Internet Connection or Wait a moment":L}
741
- \u2800`},_e.existsSync(P)||_e.mkdirSync(P,{recursive:!0}),_e.appendFileSync(J.join(P,"error.log"),`CRITICAL ERROR [${I}]: ${k}
742
-
743
- ----------------------------------------------------------------------
744
-
745
- `),typeof flushGoogleBuffer=="function"&&(yield*flushGoogleBuffer()),yield{type:"tool_result",content:`ERROR: [INTERNAL CRITICAL] ${L}`}}finally{A&&(clearInterval(A),A=null),typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),await ft.commitTransaction(),l?.advanceRollback&&await Kn.cleanup(d),await ys()}yield{type:"status",content:null}},lm=async(e,n,t=null,o=null,s=50,i=null,r=!1)=>{let a=await Dt(),h={...a,...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,u=`${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=(k=>{if(!k)return null;let T=k.toLowerCase();return T==="google"?"Google":T==="deepseek"?"DeepSeek":T==="openrouter"?"OpenRouter":T==="nvidia"?"NVIDIA":T==="mistral"?"Mistral":T==="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 k=await zo(h.aiProvider);k&&(h.apiKey=k)}let w=k=>{if(!k||typeof k!="string")return{allowed:!0};let T=[/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 L of T)if(L.test(k))return{allowed:!1,reason:`Blocked potentially destructive or unsafe command pattern: "${L.source}"`};return{allowed:!0}},x=t||m||n?.modelName||n?.activeModel||a.activeModel,E=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",b=`-- TOOL DEFINITIONS (path = relative to CWD, path separator: '/') --
746
- TO USE TOOLS, MUST OUTPUT EXACTLY '[tool:functions.ToolName(arg1="value1")]' STRUCTURED STRING IN CHAT RESPONSE \u2190 MANDATORY
747
- TOOL RULES:
748
- - JSON ESCAPE ALL LITERAL ESCAPE SEQUENCES IN TOOL ARGUMENTS
749
- - SAME file, MULTIPLE edits? ONE PatchFile (\u226415 blocks) \u2190 PRIORITY
750
- - Need text or huge files? CodeSearch > Full Read
751
- - MUST AVOID UNNECESSARY LARGE-FILE CHUNK READS
752
- - Restricted Shell Access, No Deletion
753
- - DONT HALLUCINATE TOOL RESULTS, VERIFY, FIX ERRORS
754
- - ONLY valid tools and syntax defined below are allowed
755
- - Stuck on syntax error? Move-on & Report > Time waste
756
-
757
- **PROVIDED TOOLS (STRING BASED PROTOCOL)**
758
- -- Communication Tools --
759
- - [tool:functions.Ask(question="...", optionA="title::description", ...MAX4)]. Communicate with USER. Ambiguity: MUST for path divergence, security risk. Ask, don't finish/guess. Suggest best options; no preferences. Keep titles short
760
- ${r?'- [tool:functions.AskMain(question="...")]. Communicate with PARENT/MAIN AGENT. When clarification/decision is needed for a task':""}
761
-
762
- -- Web Tools --
763
- - [tool:functions.WebSearch(query="...", aiMode="bool", limit="integer 3-10 aiMode: exclude")]. Usage: unknown info/docs. aiMode: LLM search
764
- - [tool:functions.WebScrape(url="...")]. Proactive use for specific webpage/docs/api
765
-
766
- -- Workspace Tools --
767
- - [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
768
- - [tool:functions.ReadFolder(path="...", recurse="integer 1-3")]. Minimize recursion
769
- - [tool:functions.ReadFile(path="...", startLine="integer", endLine="integer")]. View files
770
- - [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
771
- - [tool:functions.WriteFile(path="...", content="...")]. Creates/Overwrites. File Exist? PatchFile > WriteFile. VERIFY IMPORTS
772
- - [tool:functions.Run(command="...")]. Runs ${E==="Windows"?Hn()?"WINDOWS POWERSHELL":"WINDOWS CMD":"BASH"} command. Destructive/Irreversible ops \u2192 Ask user`.trim(),C=`=== START SYSTEM PROMPT ===
773
- You are a subagent helping the main FluxFlow CLI agent
774
- Your task is: "${e}"
775
-
776
- ${b.trimEnd()}
777
-
778
- -- THINKING GUIDANCE --
779
- NO EXPLICIT THINKING REQUIRED. FOCUS ON TASK COMPLETION
780
- Keep main focus on tools and task, not chatting
781
- 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
782
-
783
- CWD: ${process.cwd()}
784
- Current Time: ${u}
785
- === END SYSTEM PROMPT ===`,S=[{role:"user",text:`Complete this task: ${e}`}],R=0,A="";for(;R<s;){if(Lt){if(n?.taskId&&typeof Ve<"u"){let F=Ve.find(B=>B.id===n.taskId);F&&(F.status="cancelled")}throw i&&i("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}if(n?.taskId&&typeof Ve<"u"){let F=Ve.find(B=>B.id===n.taskId);if(F&&F.status==="cancelled")throw i&&i("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}let k=S.map(F=>({role:F.role==="user"?"user":"model",parts:[{text:F.text}]}));i&&i(`[Subagent Turn ${R+1}]...`);let I=((await Fo(h,x,k,C,"Fast")).text||"").replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/gi,"").trim();A=I,i&&i(`[Subagent Response]
786
- ${I}
787
- `),S.push({role:"agent",text:I});let P=Bo(I);if(P.length===0)break;let j=P.filter(F=>F.toolName.toLowerCase()==="askmain"||F.toolName.toLowerCase()==="ask_main"),G=!1,ee="";for(let F of P){if(Lt){if(n?.taskId&&typeof Ve<"u"){let O=Ve.find(D=>D.id===n.taskId);O&&(O.status="cancelled")}throw new Error("Subagent task was cancelled.")}if(n?.taskId&&typeof Ve<"u"){let O=Ve.find(D=>D.id===n.taskId);if(O&&O.status==="cancelled")throw new Error("Subagent task was cancelled.")}let B=F.toolName.toLowerCase();if(B==="askmain"||B==="ask_main"){if(G)continue;G=!0;let O="";if(j.length===1?O=_(j[0].args).question||j[0].args:O=j.map((D,V)=>{let z=_(D.args);return`Q${V+1}: ${z.question||D.args}`}).join(`
788
- `),n.onAskMain){i&&i(`[Executing Tool] AskMain("${O}")...`);let D=await n.onAskMain(O);i&&i(`[Tool Result]
789
- Answer from Main Agent: ${D}
790
- `),ee+=`[TOOL RESULT for AskMain]: Answer from Main Agent: ${D}
791
-
792
- `,await It("toolSuccess")}else ee+=`[TOOL RESULT for AskMain]: ERROR: Main agent communication channel not available.
793
-
794
- `;continue}if(!(o?o.some(O=>O.toLowerCase()===B):!0)){let O=`ERROR: Tool [${F.toolName}] is not in the allowed tools list for this subagent.`;i&&i(`[Blocked Tool Call] ${F.toolName} - not allowed
795
- `),ee+=`${O}
796
-
797
- `;continue}if(B==="exec_command"||B==="execcommand"||B==="run"){let O=_(F.args).command||"",D=w(O);if(!D.allowed){let V=`ERROR: [SECURITY RESTRICTION] Subagent execution blocked command: ${D.reason}`;i&&i(`[Blocked Command] ${O} - ${D.reason}
798
- `),ee+=`${V}
799
-
800
- `;continue}}let be="";if(B==="web_search"||B==="websearch")be=`\u2714 \x1B[95mSearched\x1B[0m: ${_(F.args).query||""}`;else if(B==="web_scrape"||B==="webscrape")be=`\u2714 \x1B[95mScraped\x1B[0m: ${_(F.args).url||""}`;else if(B==="search_keyword"||B==="searchkeyword"||B==="codesearch"||B==="code_search"){let O=_(F.args),D=O.keyword||"",V=O.path||"";be=`${D?"\u2714":"\u2718"} \x1B[95mSearched\x1B[0m: ${D||"No Query"}${V?` \u2192 ${V.replaceAll("\\","/")}`:""}`}else if(B==="view_file"||B==="viewfile"||B==="readfile")be=`\u2714 \x1B[95mRead\x1B[0m: ${(_(F.args).path||"").replaceAll("\\","/")}`;else if(B==="list_files"||B==="read_folder"||B==="readfolder"){let O=_(F.args).path||null,D=_(F.args).recurse||0;be=`${O?"\u2714":"\u2718"} \x1B[95mBrowsed\x1B[0m: ${O?`${O.replaceAll("\\","/")}${D>0?`${O.endsWith("/")?`*${D}`:`/*${D}`}`:`${O.endsWith("/")?"":"/"}`}`:""}`}else if(B==="write_file"||B==="writefile"){let O=_(F.args).path||null;be=`${O?"\u2714":"\u2718"} \x1B[95mCreated\x1B[0m: ${O?`${O.replaceAll("\\","/")}`:"No File Changes"}`}else if(B==="update_file"||B==="updatefile"||B==="patchfile"||B==="patch_file"||B==="patchfile"||B==="updatefile"){let O=_(F.args).path||null,D=_(F.args).content||null;be=`${O?"\u2714":"\u2718"} \x1B[95mEdited\x1B[0m: ${O?`${O.replaceAll("\\","/")}`:"No File Changes"}`}else if(B==="exec_command"||B==="execcommand"||B==="run"){let O=_(F.args).command||null;be=`${O?"\u2714":"\u2718"} \x1B[95mExecuted\x1B[0m: ${O?O.slice(0,100)+(O.length>100?"...":""):"No Command"}`}else if(B==="file_map"||B==="filemap"){let O=_(F.args).path||"";be=`${O?"\u2714":"\u2718"} \x1B[95mIndexed\x1B[0m: ${O?`${O.replaceAll("\\","/")}`:"File Not Found"}`}else if(B==="await"){let{time:O}=_(F.args),D=parseFloat(O)||0;D<10&&(D=10),D>180&&(D=180),be=`\u2714 \x1B[95mAwaiting\x1B[0m \u2192 ${(z=>{if(z>=60){let De=Math.floor(z/60),Ne=z%60;return`${De}m${Ne>0?` ${Ne}s`:""}`}return`${z}s`})(D)}`}else{let O=Gi[B]||F.toolName,D=Ts(B,F.args);be=`\u2714 \x1B[95m${O}\x1B[0m${D?`: ${D}`:""}`}n.onVisualFeedback&&be&&n.onVisualFeedback(be),i&&i(`[Executing Tool] ${F.toolName}(${F.args})...`);try{let O=await ao(F.toolName,F.args,{...n,mode:"Flux"});if(i&&i(`[Tool Result]
801
- ${O}
802
- `),ee+=`[TOOL RESULT for ${F.toolName}]: ${O}
803
-
804
- `,await It("toolSuccess"),B==="patchfile"||B==="update_file"||B==="updatefile"||B==="patch_file"){if(O){let D=O.split(`
805
- `),V=0,z=0,De=!1;for(let Ne of D){if(Ne.includes("[DIFF_START]")){De=!0;continue}if(Ne.includes("[DIFF_END]")){De=!1;continue}De&&(/^\+\d+/.test(Ne)?V++:/^\-\d+/.test(Ne)&&z++)}(V>0||z>0)&&(await Gt("linesAdded",V),await Gt("linesRemoved",z))}}else if((B==="writefile"||B==="write_file")&&O){let D=O.match(/- Stats: \[(\d+) lines/),V=D?parseInt(D[1]):0,z=0;if(O.includes("Old File contents:")){let De=!1;for(let Ne of O.split(`
806
- `)){if(Ne.includes("Old File contents:")){De=!0;continue}De&&(Ne.trim()===""?De=!1:/^\d+ \|/.test(Ne)&&z++)}}(V>0||z>0)&&(await Gt("linesAdded",V),await Gt("linesRemoved",z))}}catch(O){let D=`ERROR: Execution failed for [${F.toolName}]: ${O.message}`;i&&i(`[Tool Error] ${D}
807
- `),ee+=`${D}
808
-
809
- `,await It("toolFailure")}}let he="";if(n?.taskId&&typeof Ve<"u"){let F=Ve.find(B=>B.id===n.taskId);if(F&&F.pendingSteerMessages&&F.pendingSteerMessages.length>0){let B=[...F.pendingSteerMessages];F.pendingSteerMessages=[];for(let ie of B)he+=`
810
-
811
- [STEERING INSTRUCTION FROM MAIN AGENT]: ${ie}`,i&&i(`[Subagent Steered] ${ie}`)}}let Ue=(ee.trim()+he).trim();S.push({role:"user",text:Ue}),R++}return A};export{hn as a,vr as b,of as c,rf as d,rl as e,Nr as f,af as g,pl as h,lf as i,lo as j,ia as k,fp as l,up as m,_ as n,Cc as o,Jo as p,qs as q,Ac as r,$c as s,ft as t,cs as u,id as v,Ya as w,rd as x,ad as y,ld as z,cd as A,dd as B,yd as C,wd as D,bn as E,za as F,Xs as G,Gt as H,Xa as I,kr as J,ds as K,Cl as L,ru as M,au as N,mp as O,Po as P,gp as Q,Nn as R,lc as S,nm as T,sm as U,Xi as V,om as W,im as X,yc as Y,rm as Z,am as _,lm as $};