fluxflow-cli 4.1.3 → 4.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/README.md +1 -0
  2. package/dist/chunks/{ai-5HGOLEFE.js → ai-M2MAGATC.js} +1 -1
  3. package/dist/chunks/{app-AIAYUYQP.js → app-NQODWWNA.js} +1 -1
  4. package/dist/chunks/{chunk-A6RZ4EIR.js → chunk-CQ2U3S2O.js} +254 -254
  5. package/dist/cli.js +1 -1
  6. package/dist/model_config.json +6 -1
  7. package/dist/package.json +1 -1
  8. package/model_config.json +6 -1
  9. package/package.json +1 -1
  10. package/dist/chunks/ai-7J7CL56L.js +0 -1
  11. package/dist/chunks/ai-7LT7T34E.js +0 -1
  12. package/dist/chunks/ai-ACFJ2D4K.js +0 -1
  13. package/dist/chunks/ai-CQ6R662V.js +0 -1
  14. package/dist/chunks/ai-GO5NYAPZ.js +0 -1
  15. package/dist/chunks/ai-GUVZR6ZJ.js +0 -1
  16. package/dist/chunks/ai-IGHYVKEI.js +0 -1
  17. package/dist/chunks/ai-IOVX3WCN.js +0 -1
  18. package/dist/chunks/ai-LFC7GPK6.js +0 -1
  19. package/dist/chunks/ai-LUAK6ZNI.js +0 -1
  20. package/dist/chunks/ai-NDNZ4XGW.js +0 -1
  21. package/dist/chunks/ai-O2AHKT2Q.js +0 -1
  22. package/dist/chunks/ai-OLHI3UWZ.js +0 -1
  23. package/dist/chunks/ai-OP2H56UR.js +0 -1
  24. package/dist/chunks/ai-OX4W3MY2.js +0 -1
  25. package/dist/chunks/ai-SUNZIUAF.js +0 -1
  26. package/dist/chunks/ai-T2SZGY7Y.js +0 -1
  27. package/dist/chunks/ai-VMV4EAEQ.js +0 -1
  28. package/dist/chunks/app-2BDYKT26.js +0 -226
  29. package/dist/chunks/app-2MCTW3BU.js +0 -226
  30. package/dist/chunks/app-4M34YBXM.js +0 -223
  31. package/dist/chunks/app-4VRQVBXL.js +0 -226
  32. package/dist/chunks/app-5YW3SESE.js +0 -223
  33. package/dist/chunks/app-62A6ZFYX.js +0 -226
  34. package/dist/chunks/app-A6HECULK.js +0 -223
  35. package/dist/chunks/app-A6JFAZBR.js +0 -220
  36. package/dist/chunks/app-AASWJUCP.js +0 -226
  37. package/dist/chunks/app-AHIXABRK.js +0 -220
  38. package/dist/chunks/app-CK5GTF3V.js +0 -230
  39. package/dist/chunks/app-CTJKY73V.js +0 -223
  40. package/dist/chunks/app-DJWNDFPK.js +0 -223
  41. package/dist/chunks/app-DLGENJXK.js +0 -226
  42. package/dist/chunks/app-DU2VBIDN.js +0 -223
  43. package/dist/chunks/app-EKHVG5CH.js +0 -220
  44. package/dist/chunks/app-FJJPTQG7.js +0 -223
  45. package/dist/chunks/app-FVACY6W2.js +0 -230
  46. package/dist/chunks/app-GY2S4P3O.js +0 -220
  47. package/dist/chunks/app-HE22VKVY.js +0 -223
  48. package/dist/chunks/app-HW6KINDL.js +0 -226
  49. package/dist/chunks/app-II7PE7RS.js +0 -230
  50. package/dist/chunks/app-MPYGQO5K.js +0 -223
  51. package/dist/chunks/app-MWWVPJVZ.js +0 -223
  52. package/dist/chunks/app-OIIPCXZF.js +0 -226
  53. package/dist/chunks/app-QCQTUW4S.js +0 -223
  54. package/dist/chunks/app-QPPCSI4B.js +0 -223
  55. package/dist/chunks/app-RDSYUUGS.js +0 -228
  56. package/dist/chunks/app-SWVHXTUU.js +0 -223
  57. package/dist/chunks/app-TSUKVNLY.js +0 -223
  58. package/dist/chunks/app-WWNOUK7Q.js +0 -220
  59. package/dist/chunks/app-XTDZID37.js +0 -228
  60. package/dist/chunks/app-YCFZG7ZN.js +0 -223
  61. package/dist/chunks/app-ZUY2BADH.js +0 -226
  62. package/dist/chunks/chunk-2FKXQDRX.js +0 -3
  63. package/dist/chunks/chunk-3VSDH7DF.js +0 -3
  64. package/dist/chunks/chunk-4ANZCMTB.js +0 -813
  65. package/dist/chunks/chunk-5ORPFMKW.js +0 -3
  66. package/dist/chunks/chunk-6DHFEWGX.js +0 -1
  67. package/dist/chunks/chunk-73S5MDH5.js +0 -816
  68. package/dist/chunks/chunk-77P7CACS.js +0 -3
  69. package/dist/chunks/chunk-7WH5DREO.js +0 -1
  70. package/dist/chunks/chunk-APOUCRQO.js +0 -803
  71. package/dist/chunks/chunk-BVYPWENJ.js +0 -803
  72. package/dist/chunks/chunk-BW2MR2YB.js +0 -3
  73. package/dist/chunks/chunk-D67A52ZR.js +0 -802
  74. package/dist/chunks/chunk-DB4BJM2R.js +0 -807
  75. package/dist/chunks/chunk-GYYGT2GJ.js +0 -1229
  76. package/dist/chunks/chunk-HU74ZBCV.js +0 -803
  77. package/dist/chunks/chunk-IW2KLAXM.js +0 -803
  78. package/dist/chunks/chunk-M3G4NWZ2.js +0 -3
  79. package/dist/chunks/chunk-O4A5T73D.js +0 -801
  80. package/dist/chunks/chunk-PHKIAKHS.js +0 -1
  81. package/dist/chunks/chunk-PK33OTVD.js +0 -802
  82. package/dist/chunks/chunk-RTGBM2SA.js +0 -27
  83. package/dist/chunks/chunk-SGZ2OI72.js +0 -1
  84. package/dist/chunks/chunk-UCFPBFHY.js +0 -811
  85. package/dist/chunks/chunk-UKBUOJ3P.js +0 -803
  86. package/dist/chunks/chunk-VBKX2PU3.js +0 -803
  87. package/dist/chunks/chunk-VFG7GIPV.js +0 -812
  88. package/dist/chunks/chunk-WJ33GNVP.js +0 -3
  89. package/dist/chunks/chunk-Y2EZRWRZ.js +0 -803
  90. package/dist/chunks/chunk-Y6SLVHK3.js +0 -1
  91. package/dist/chunks/chunk-ZGHOKGSQ.js +0 -1231
  92. package/dist/chunks/chunk-ZQZIEF5I.js +0 -803
  93. package/dist/chunks/chunk-ZRS2O6Y6.js +0 -1
  94. package/dist/chunks/export-JZFBZGGZ.js +0 -1
  95. package/dist/chunks/export-MX2VT3I7.js +0 -1
  96. package/dist/chunks/export-OFKMKWAS.js +0 -1
  97. package/dist/chunks/export-ZB2GNV3S.js +0 -1
  98. package/dist/chunks/paths-HYQFU6D2.js +0 -1
  99. package/dist/chunks/paths-KMO5IYNK.js +0 -1
  100. package/dist/chunks/paths-NXN6XAEU.js +0 -1
  101. package/dist/chunks/paths-YDCMNN4Q.js +0 -1
  102. package/dist/chunks/secrets-2VU4KV7B.js +0 -1
  103. package/dist/chunks/secrets-GN7OAYL7.js +0 -1
  104. package/dist/chunks/secrets-NCPPS7DR.js +0 -1
  105. package/dist/chunks/secrets-RZD3DYTB.js +0 -1
  106. package/dist/chunks/settings-57QAZRCP.js +0 -1
  107. package/dist/chunks/settings-DCF6DTL6.js +0 -1
  108. package/dist/chunks/settings-DTH5C6BO.js +0 -1
  109. package/dist/chunks/settings-GPKUUYFM.js +0 -1
  110. package/dist/chunks/settings-HOSPANO7.js +0 -1
  111. package/dist/chunks/settings-IY24HSRP.js +0 -1
  112. package/dist/chunks/settings-SSPDWUKI.js +0 -1
  113. package/dist/chunks/src-O2JUKI77.js +0 -1
  114. package/dist/chunks/subagent_state-3D5ZJCLX.js +0 -1
  115. package/dist/chunks/subagent_state-5IJKFMRU.js +0 -1
  116. package/dist/chunks/subagent_state-N77JX7MX.js +0 -1
@@ -1,39 +1,39 @@
1
- import{b as Xo}from"./chunk-ZESOEAQT.js";import{c as fn,d as qs,g as et,h as Ft}from"./chunk-BZBAMZS4.js";import{a as Gs,b as Cs,c as X,d as he}from"./chunk-SIINYZWE.js";import{c as An,d as cn,e as yo,f as Es,g as $s,h as Vo,i as Jt,j as Dt,k as Xt,l as vn,m as Un,n as nn,o as dn,p as rs,q as Jo,r as Wn,s as as}from"./chunk-I27MASHH.js";import{a as Ye,c as wo}from"./chunk-56EJGQU3.js";import{c as cr,d as dr,e as Ks}from"./chunk-K4FITEVZ.js";import Xl from"dotenv";import{GoogleGenAI as Ta,ThinkingLevel as at,HarmBlockThreshold as Yn,HarmCategory as Vn}from"@google/genai";import{Ollama as Ql}from"ollama";import{execSync as Wa}from"child_process";import{spawn as Qo}from"child_process";var I=e=>{let n={};if(!e)return n;let t=0;for(;t<e.length;){for(;t<e.length&&/[\s,]/.test(e[t]);)t++;if(t>=e.length)break;let o=e.substring(t).match(/^(\w+)\s*=\s*/);if(!o){t++;continue}let s=o[1];t+=o[0].length;let i="";if(t<e.length&&(e[t]==='"'||e[t]==="'"||e[t]==="`")){let a=e[t];t++;let r=t,h=-1,d=t;for(;d<e.length;){let l=e.indexOf(a,d);if(l===-1)break;let f=0;for(let y=l-1;y>=0&&e[y]==="\\";y--)f++;if(f%2!==0){d=l+1;continue}let u=e.substring(l+1),p=u.trim(),g=p===""||/^,\s*\w+\s*=/.test(p)||p.startsWith(")")&&(p.length===1||/^\)\s*([,\]\s]|\[\[?tool:)/i.test(p));if(g&&u.startsWith(`
1
+ import{b as Zo}from"./chunk-ZESOEAQT.js";import{c as fn,d as qs,g as et,h as Ft}from"./chunk-BZBAMZS4.js";import{a as Gs,b as Cs,c as X,d as he}from"./chunk-SIINYZWE.js";import{c as An,d as cn,e as xo,f as Es,g as $s,h as Xo,i as Jt,j as Dt,k as Xt,l as vn,m as Un,n as nn,o as dn,p as rs,q as Qo,r as Wn,s as as}from"./chunk-I27MASHH.js";import{a as Ye,c as bo}from"./chunk-56EJGQU3.js";import{c as mr,d as gr,e as zs}from"./chunk-K4FITEVZ.js";import oc from"dotenv";import{GoogleGenAI as Ma,ThinkingLevel as at,HarmBlockThreshold as Yn,HarmCategory as Vn}from"@google/genai";import{Ollama as ic}from"ollama";import{execSync as Ka}from"child_process";import{spawn as ei}from"child_process";var O=e=>{let n={};if(!e)return n;let t=0;for(;t<e.length;){for(;t<e.length&&/[\s,]/.test(e[t]);)t++;if(t>=e.length)break;let o=e.substring(t).match(/^(\w+)\s*=\s*/);if(!o){t++;continue}let s=o[1];t+=o[0].length;let i="";if(t<e.length&&(e[t]==='"'||e[t]==="'"||e[t]==="`")){let a=e[t];t++;let r=t,h=-1,d=t;for(;d<e.length;){let l=e.indexOf(a,d);if(l===-1)break;let 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
2
  `)){let y=p.split(`
3
- `)[0];if(!y.includes("=")&&!y.includes(")")){d=l+1;continue}}if(g){h=l;break}d=l+1}h!==-1?(i=e.substring(r,h),t=h+1):(i=e.substring(r),t=e.length);let c=s.toLowerCase().includes("path")||["dest","source","to","from"].includes(s.toLowerCase());i=i.replace(/\\(.)/g,(l,f)=>{switch(f){case"n":return`
4
- `;case"r":return"\r";case"t":return" ";case"\\":return"\\";default:return f===a?a:f}})}else if(t<e.length&&e[t]==="["){let a=0,r=null,h=t,d=-1;for(let c=t;c<e.length;c++){let l=e[c];if(r&&l===r){let f=0;for(let u=c-1;u>=0&&e[u]==="\\";u--)f++;f%2===0&&(r=null)}else!r&&(l==='"'||l==="'"||l==="`")&&(r=l);if(!r&&(l==="["?a++:l==="]"&&a--,a===0)){d=c;break}}if(d!==-1){i=e.substring(h,d+1),t=d+1;try{let c=i.trim();c.startsWith("'")||c.includes("'")}catch{}}else i=e.substring(h),t=e.length}else{let a=e.substring(t),r=a.match(/,\s*\w+\s*=|(?:\s*\)\s*(?:$|\]\]))/);if(r){let h=r.index;i=a.substring(0,h).trim(),t+=h}else i=a.trim(),t=e.length}i==="true"?i=!0:i==="false"?i=!1:typeof i=="string"&&!isNaN(i)&&i.trim()!==""&&(i=Number(i)),typeof i=="string"&&(s.toLowerCase().includes("path")||["dest","source","to","from"].includes(s.toLowerCase()))&&(i=i.replace(/\x0C/g,"\\f").replace(/\x0D/g,"\\r").replace(/\x0B/g,"\\v").replace(/\x08/g,"\\b")),n[s]=i}return n};var xo=null;try{let e=await import("node-pty");xo=e.default||e}catch{}var Ic=!!xo,bo=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),Zo=e=>{if(!e)return"";let n=[[]],t=0,o=0,s=/\x1b\[([0-9;]*?)([a-zA-Z])/g,i=0,a,r=d=>{for(let c=0;c<d.length;c++){let l=d[c];if(l===`
5
- `)for(t++,o=0;t>=n.length;)n.push([]);else if(l==="\r")o=0;else{for(;t>=n.length;)n.push([]);let f=n[t];for(;o>f.length;)f.push(" ");f[o]=l,o++}}};for(;(a=s.exec(e))!==null;){r(e.substring(i,a.index));let d=a[1],c=a[2],l=d?d.split(";").map(Number):[];if(c==="A"){let f=l[0]||1;t=Math.max(0,t-f)}else if(c==="B"){let f=l[0]||1;for(t=t+f;t>=n.length;)n.push([])}else if(c==="C"){let f=l[0]||1;o=o+f}else if(c==="D"){let f=l[0]||1;o=Math.max(0,o-f)}else if(c==="G"){let f=(l[0]||1)-1;o=Math.max(0,f)}else if(c==="H"||c==="f"){let f=(l[0]||1)-1,u=(l[1]||1)-1;for(t=Math.max(0,f),o=Math.max(0,u);t>=n.length;)n.push([])}else if(c==="K"){let f=l[0]||0;if(t<n.length){let u=n[t];if(f===0)u.length=o;else if(f===1)for(let p=0;p<o&&p<u.length;p++)u[p]=" ";else f===2&&(u.length=0)}}else if(c==="J"){let f=l[0]||0;(f===2||f===3)&&(n.length=0,n.push([]),t=0,o=0)}i=s.lastIndex}r(e.substring(i));let h=n.map(d=>d.join(""));for(;h.length>0&&h[h.length-1]==="";)h.pop();return h.join(`
6
- `)},gt=null,zs=!1,Oc=e=>{try{gt&&(zs&&typeof gt.write=="function"?gt.write(e):gt.stdin&&gt.stdin.writable&&gt.stdin.write(e))}catch{}},Lc=()=>{if(gt){try{zs&&typeof gt.destroy=="function"?gt.destroy():typeof gt.kill=="function"&&(process.platform==="win32"?Qo("taskkill",["/pid",gt.pid,"/f","/t"]):gt.kill("SIGKILL"))}catch{}gt=null,zs=!1}},ei=(e,n=!1)=>{if(process.platform!=="win32")return e;let t=[],o="",s=null,i=!1;for(let c=0;c<e.length;c++){let l=e[c];if(i){o+=l,i=!1;continue}if(l==="\\"){if(e[c+1]===" "){o+=" ",c++;continue}o+=l,i=!0;continue}s?(l===s&&(s=null),o+=l):l==='"'||l==="'"?(s=l,o+=l):l===";"&&!o.includes("://")?(o.length>0&&(t.push(o),o=""),t.push(n?";":"&")):l==="&"&&!o.includes("://")?e[c+1]==="&"?(o.length>0&&(t.push(o),o=""),t.push("&&"),c++):(o.length>0&&(t.push(o),o=""),t.push("&")):l==="|"&&!o.includes("://")?(o.length>0&&(t.push(o),o=""),t.push("|")):/\s/.test(l)?o.length>0&&(t.push(o),o=""):o+=l}o.length>0&&t.push(o);let a=c=>!(!c.includes("/")||/^(https?|file|ftp):\/\//i.test(c)||c.startsWith("@")||c.startsWith("/")&&(c.match(/\//g)||[]).length===1||/\s\/|\/\s/.test(c)||/[\(\)\{\}\;\<\>\=\'\"]/.test(c)),r=[];for(let c=0;c<t.length;c++){let l=t[c];if(l==="mkdir"&&n&&jn()){let f=[],u=c+1;for(;u<t.length;){let p=t[u];if([">",">>","<","&","&&","|","||",";"].includes(p))break;p!=="-p"&&p!=="--parents"&&p!=="-v"&&p!=="--verbose"&&f.push(p),u++}if(f.length>0){let p=f.map(g=>{let y=g.replace(/^['"]|['"]$/g,""),m=g;return a(y)&&(m=g.replace(/\//g,"\\")),m});r.push("New-Item","-ItemType","Directory","-Force","-Path",p.join(","))}else r.push("New-Item","-ItemType","Directory","-Force");c=u-1;continue}if(l==="rm"&&n&&jn()){let f=[],u=!1,p=!1,g=c+1;for(;g<t.length;){let m=t[g];if([">",">>","<","&","&&","|","||",";"].includes(m))break;m==="-rf"||m==="-fr"?(u=!0,p=!0):m==="-r"||m==="-R"||m==="--recursive"?u=!0:m==="-f"||m==="--force"?p=!0:f.push(m),g++}let y=["Remove-Item"];if(u&&y.push("-Recurse"),p&&y.push("-Force"),f.length>0){let m=f.map(w=>{let x=w.replace(/^['"]|['"]$/g,""),S=w;return a(x)&&(S=w.replace(/\//g,"\\")),S});y.push("-Path",m.join(","))}r.push(...y),c=g-1;continue}if(l==="cp"&&n&&jn()){let f=[],u=!1,p=!1,g=c+1;for(;g<t.length;){let m=t[g];if([">",">>","<","&","&&","|","||",";"].includes(m))break;m==="-r"||m==="-R"||m==="--recursive"?u=!0:m==="-f"||m==="--force"?p=!0:f.push(m),g++}let y=["Copy-Item"];if(u&&y.push("-Recurse"),p&&y.push("-Force"),f.length>0){let m=f.map(w=>{let x=w.replace(/^['"]|['"]$/g,""),S=w;return a(x)&&(S=w.replace(/\//g,"\\")),S});if(m.length>1){let w=m.pop();y.push("-Path",m.join(","),"-Destination",w)}else y.push("-Path",m[0])}r.push(...y),c=g-1;continue}if(l==="touch"&&n&&jn()){let f=[],u=c+1;for(;u<t.length;){let p=t[u];if([">",">>","<","&","&&","|","||",";"].includes(p))break;f.push(p),u++}if(f.length>0){let g=`(${f.map(y=>{let m=y.replace(/^['"]|['"]$/g,""),w=y;return a(m)&&(w=y.replace(/\//g,"\\")),w}).join(", ")}) | ForEach-Object { if (Test-Path $_) { (Get-Item $_).LastWriteTime = [System.DateTime]::Now } else { $null | Out-File -FilePath $_ } }`;r.push(g)}c=u-1;continue}if(l==="|"&&t[c+1]==="tee"){t[c+2]==="-a"?(r.push(">>"),c+=2):(r.push(">"),c+=1);continue}if(l==="|"&&t[c+1]==="cat"&&t[c+2]===">"){r.push(">"),c+=2;continue}if(l==="|"){let f=t[c+1];if(f){let u=f.replace(/^['"]|['"]$/g,""),p=/\.(txt|md|json|log|csv|html|css|py|js|xml|yaml|yml|pdf|docx|pptx|xlsx)$/i.test(u);if(a(u)&&p){r.push(">");continue}}}r.push(l)}let h=!1,d=r.map(c=>{if(c==="echo")return h=!0,c;[">",">>","<","&","&&","|","||",";"].includes(c)&&(h=!1);let f=/^['"]|['"]$/.test(c),u=c;h&&f&&(u=c.replace(/^['"]|['"]$/g,""));let p=/^['"]|['"]$/.test(u),g=u.replace(/^['"]|['"]$/g,"");a(g)&&(u=u.replace(/\//g,"\\"));let y=u.replace(/^['"]|['"]$/g,"");return y.includes(" ")&&!p&&(u=`"${y}"`),u});if(n){let c="",l=0;for(let f=0;f<d.length;f++){let u=d[f];u==="&&"?(c+="; if ($?) {",l++):u===";"?(c+=" }".repeat(l)+";",l=0):(c&&!c.endsWith(" ")&&!c.endsWith("{")&&(c+=" "),c+=u)}return c+=" }".repeat(l),c}return d.join(" ")},ti=async(e,n={})=>{let{command:t}=I(e),{onChunk:o}=n;if(!t)return'ERROR: Missing "command" argument for exec_command.';let s=process.platform==="win32",i=n.systemSettings||{},a={};return i.networkAccess===!1&&(a.HTTP_PROXY="http://127.0.0.1:9999",a.HTTPS_PROXY="http://127.0.0.1:9999",a.ALL_PROXY="socks5://127.0.0.1:9999",a.http_proxy="http://127.0.0.1:9999",a.https_proxy="http://127.0.0.1:9999",a.all_proxy="socks5://127.0.0.1:9999",a.NO_PROXY="localhost,127.0.0.1"),new Promise(r=>{let h=d=>{let c=d==="pwsh"||d==="powershell",l=ei(t,c),f;s?d==="pwsh"?f="C:\\Users\\User\\AppData\\Local\\Microsoft\\WindowsApps\\pwsh.exe":d==="powershell"?f="powershell.exe":f="cmd.exe":f=process.env.SHELL||"bash";let u=s?c?["-NoProfile","-Command",l]:["/c",l]:["-c",l];if(i.networkAccess===!1&&!s){let p=f,g=[...u];if(process.platform==="linux")f="unshare",u=["-n","-r",p,...g];else if(process.platform==="darwin"){let y=`(version 1)
3
+ `)[0];if(!y.includes("=")&&!y.includes(")")){d=l+1;continue}}if(g){h=l;break}d=l+1}h!==-1?(i=e.substring(r,h),t=h+1):(i=e.substring(r),t=e.length);let c=s.toLowerCase().includes("path")||["dest","source","to","from"].includes(s.toLowerCase());i=i.replace(/\\(.)/g,(l,u)=>{switch(u){case"n":return`
4
+ `;case"r":return"\r";case"t":return" ";case"\\":return"\\";default:return u===a?a:u}})}else if(t<e.length&&e[t]==="["){let a=0,r=null,h=t,d=-1;for(let c=t;c<e.length;c++){let l=e[c];if(r&&l===r){let u=0;for(let f=c-1;f>=0&&e[f]==="\\";f--)u++;u%2===0&&(r=null)}else!r&&(l==='"'||l==="'"||l==="`")&&(r=l);if(!r&&(l==="["?a++:l==="]"&&a--,a===0)){d=c;break}}if(d!==-1){i=e.substring(h,d+1),t=d+1;try{let c=i.trim();c.startsWith("'")||c.includes("'")}catch{}}else i=e.substring(h),t=e.length}else{let a=e.substring(t),r=a.match(/,\s*\w+\s*=|(?:\s*\)\s*(?:$|\]\]))/);if(r){let h=r.index;i=a.substring(0,h).trim(),t+=h}else i=a.trim(),t=e.length}i==="true"?i=!0:i==="false"?i=!1:typeof i=="string"&&!isNaN(i)&&i.trim()!==""&&(i=Number(i)),typeof i=="string"&&(s.toLowerCase().includes("path")||["dest","source","to","from"].includes(s.toLowerCase()))&&(i=i.replace(/\x0C/g,"\\f").replace(/\x0D/g,"\\r").replace(/\x0B/g,"\\v").replace(/\x08/g,"\\b")),n[s]=i}return n};var So=null;try{let e=await import("node-pty");So=e.default||e}catch{}var Bc=!!So,ko=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),ti=e=>{if(!e)return"";let n=[[]],t=0,o=0,s=/\x1b\[([0-9;]*?)([a-zA-Z])/g,i=0,a,r=d=>{for(let c=0;c<d.length;c++){let l=d[c];if(l===`
5
+ `)for(t++,o=0;t>=n.length;)n.push([]);else if(l==="\r")o=0;else{for(;t>=n.length;)n.push([]);let u=n[t];for(;o>u.length;)u.push(" ");u[o]=l,o++}}};for(;(a=s.exec(e))!==null;){r(e.substring(i,a.index));let d=a[1],c=a[2],l=d?d.split(";").map(Number):[];if(c==="A"){let 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}r(e.substring(i));let h=n.map(d=>d.join(""));for(;h.length>0&&h[h.length-1]==="";)h.pop();return h.join(`
6
+ `)},gt=null,Ks=!1,Uc=e=>{try{gt&&(Ks&&typeof gt.write=="function"?gt.write(e):gt.stdin&&gt.stdin.writable&&gt.stdin.write(e))}catch{}},Wc=()=>{if(gt){try{Ks&&typeof gt.destroy=="function"?gt.destroy():typeof gt.kill=="function"&&(process.platform==="win32"?ei("taskkill",["/pid",gt.pid,"/f","/t"]):gt.kill("SIGKILL"))}catch{}gt=null,Ks=!1}},ni=(e,n=!1)=>{if(process.platform!=="win32")return e;let t=[],o="",s=null,i=!1;for(let c=0;c<e.length;c++){let l=e[c];if(i){o+=l,i=!1;continue}if(l==="\\"){if(e[c+1]===" "){o+=" ",c++;continue}o+=l,i=!0;continue}s?(l===s&&(s=null),o+=l):l==='"'||l==="'"?(s=l,o+=l):l===";"&&!o.includes("://")?(o.length>0&&(t.push(o),o=""),t.push(n?";":"&")):l==="&"&&!o.includes("://")?e[c+1]==="&"?(o.length>0&&(t.push(o),o=""),t.push("&&"),c++):(o.length>0&&(t.push(o),o=""),t.push("&")):l==="|"&&!o.includes("://")?(o.length>0&&(t.push(o),o=""),t.push("|")):/\s/.test(l)?o.length>0&&(t.push(o),o=""):o+=l}o.length>0&&t.push(o);let a=c=>!(!c.includes("/")||/^(https?|file|ftp):\/\//i.test(c)||c.startsWith("@")||c.startsWith("/")&&(c.match(/\//g)||[]).length===1||/\s\/|\/\s/.test(c)||/[\(\)\{\}\;\<\>\=\'\"]/.test(c)),r=[];for(let c=0;c<t.length;c++){let l=t[c];if(l==="mkdir"&&n&&jn()){let 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 a(y)&&(m=g.replace(/\//g,"\\")),m});r.push("New-Item","-ItemType","Directory","-Force","-Path",p.join(","))}else r.push("New-Item","-ItemType","Directory","-Force");c=f-1;continue}if(l==="rm"&&n&&jn()){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,""),S=w;return a(x)&&(S=w.replace(/\//g,"\\")),S});y.push("-Path",m.join(","))}r.push(...y),c=g-1;continue}if(l==="cp"&&n&&jn()){let 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,""),S=w;return a(x)&&(S=w.replace(/\//g,"\\")),S});if(m.length>1){let w=m.pop();y.push("-Path",m.join(","),"-Destination",w)}else y.push("-Path",m[0])}r.push(...y),c=g-1;continue}if(l==="touch"&&n&&jn()){let 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 a(m)&&(w=y.replace(/\//g,"\\")),w}).join(", ")}) | ForEach-Object { if (Test-Path $_) { (Get-Item $_).LastWriteTime = [System.DateTime]::Now } else { $null | Out-File -FilePath $_ } }`;r.push(g)}c=f-1;continue}if(l==="|"&&t[c+1]==="tee"){t[c+2]==="-a"?(r.push(">>"),c+=2):(r.push(">"),c+=1);continue}if(l==="|"&&t[c+1]==="cat"&&t[c+2]===">"){r.push(">"),c+=2;continue}if(l==="|"){let 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(a(f)&&p){r.push(">");continue}}}r.push(l)}let h=!1,d=r.map(c=>{if(c==="echo")return h=!0,c;[">",">>","<","&","&&","|","||",";"].includes(c)&&(h=!1);let u=/^['"]|['"]$/.test(c),f=c;h&&u&&(f=c.replace(/^['"]|['"]$/g,""));let p=/^['"]|['"]$/.test(f),g=f.replace(/^['"]|['"]$/g,"");a(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(" ")},si=async(e,n={})=>{let{command:t}=O(e),{onChunk:o}=n;if(!t)return'ERROR: Missing "command" argument for exec_command.';let s=process.platform==="win32",i=n.systemSettings||{},a={};return i.networkAccess===!1&&(a.HTTP_PROXY="http://127.0.0.1:9999",a.HTTPS_PROXY="http://127.0.0.1:9999",a.ALL_PROXY="socks5://127.0.0.1:9999",a.http_proxy="http://127.0.0.1:9999",a.https_proxy="http://127.0.0.1:9999",a.all_proxy="socks5://127.0.0.1:9999",a.NO_PROXY="localhost,127.0.0.1"),new Promise(r=>{let h=d=>{let c=d==="pwsh"||d==="powershell",l=ni(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
7
  (allow default)
8
8
  (deny network-outbound)
9
9
  (allow network-outbound (remote ip "localhost:*"))
10
10
  (allow network-outbound (remote ip "127.0.0.1:*"))
11
- `;f="sandbox-exec",u=["-p",y,p,...g]}}if(xo)try{let p=xo.spawn(f,u,{name:"xterm-256color",cols:n.cols||120,rows:n.rows||30,cwd:process.cwd(),env:{...process.env,CI:"false",TERM:"xterm-256color",FORCE_COLOR:"1",...a}});gt=p,zs=!0;let g="",y=!1;return p.onData(m=>{if(!y){g+=m,o&&o(m);let w=bo(g);/(?:Network:\s+use\s+--host\s+to|Network:\s+Type\s+--host\s+to|Local:\s+http:\/\/localhost:\d+|ready in \d+\s*ms|Compiled successfully|Development server is running|Listening on:)/i.test(w)&&(y=!0,setTimeout(()=>r(`SUCCESS: Dev server started successfully in background.
11
+ `;u="sandbox-exec",f=["-p",y,p,...g]}}if(So)try{let p=So.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",...a}});gt=p,Ks=!0;let g="",y=!1;return p.onData(m=>{if(!y){g+=m,o&&o(m);let w=ko(g);/(?:Network:\s+use\s+--host\s+to|Network:\s+Type\s+--host\s+to|Local:\s+http:\/\/localhost:\d+|ready in \d+\s*ms|Compiled successfully|Development server is running|Listening on:)/i.test(w)&&(y=!0,setTimeout(()=>r(`SUCCESS: Dev server started successfully in background.
12
12
 
13
- ${w}`),500))}}),p.onExit(({exitCode:m})=>{if(y)return;gt=null;let w=Zo(g||""),x=bo(w).replace(/\n{3,}/g,`
13
+ ${w}`),500))}}),p.onExit(({exitCode:m})=>{if(y)return;gt=null;let w=ti(g||""),x=ko(w).replace(/\n{3,}/g,`
14
14
 
15
15
  `)||"Command executed with no output.";r(m!==0?`ERROR: Command [${t}] failed with exit code [${m}].
16
16
 
17
17
  ${x}`:`SUCCESS: Command [${t}] completed.
18
18
 
19
- ${x}`)}),!0}catch(p){return s&&(d==="pwsh"||d==="powershell")&&p.code==="ENOENT"?!1:(So(r,l,t,a,o,d,i),!0)}else return So(r,l,t,a,o,d,i),!0};s?h("pwsh")||h("powershell")||h("cmd"):h("bash")})},So=(e,n,t,o,s,i="powershell",a={})=>{let r=process.platform==="win32",h=i==="pwsh"||i==="powershell",d;r?i==="pwsh"?d="C:\\Users\\User\\AppData\\Local\\Microsoft\\WindowsApps\\pwsh.exe":i==="powershell"?d="powershell.exe":d="cmd.exe":d=process.env.SHELL||"bash";let c=r?h?["-NoProfile","-Command",n]:["/c",n]:["-c",n];if(a.networkAccess===!1&&!r){let g=d,y=[...c];if(process.platform==="linux")d="unshare",c=["-n","-r",g,...y];else if(process.platform==="darwin"){let m=`(version 1)
19
+ ${x}`)}),!0}catch(p){return s&&(d==="pwsh"||d==="powershell")&&p.code==="ENOENT"?!1:(To(r,l,t,a,o,d,i),!0)}else return To(r,l,t,a,o,d,i),!0};s?h("pwsh")||h("powershell")||h("cmd"):h("bash")})},To=(e,n,t,o,s,i="powershell",a={})=>{let r=process.platform==="win32",h=i==="pwsh"||i==="powershell",d;r?i==="pwsh"?d="C:\\Users\\User\\AppData\\Local\\Microsoft\\WindowsApps\\pwsh.exe":i==="powershell"?d="powershell.exe":d="cmd.exe":d=process.env.SHELL||"bash";let c=r?h?["-NoProfile","-Command",n]:["/c",n]:["-c",n];if(a.networkAccess===!1&&!r){let g=d,y=[...c];if(process.platform==="linux")d="unshare",c=["-n","-r",g,...y];else if(process.platform==="darwin"){let m=`(version 1)
20
20
  (allow default)
21
21
  (deny network-outbound)
22
22
  (allow network-outbound (remote ip "localhost:*"))
23
23
  (allow network-outbound (remote ip "127.0.0.1:*"))
24
- `;d="sandbox-exec",c=["-p",m,g,...y]}}let l=r?Qo(d,c,{cwd:process.cwd(),env:{...process.env,...o}}):Qo(d,c,{cwd:process.cwd(),env:{...process.env,CI:"false",TERM:"xterm-256color",FORCE_COLOR:"1",...o}});gt=l,zs=!1,l.stdin&&l.stdin.on("error",()=>{gt=null});let f="",u="",p=!1;l.stdout.on("data",g=>{if(!p){let y=g.toString();f+=y,s&&s(y);let m=bo(f);/(?:Network:\s+use\s+--host\s+to|Network:\s+Type\s+--host\s+to|Local:\s+http:\/\/localhost:\d+|ready in \d+\s*ms|Compiled successfully|Development server is running|Listening on:)/i.test(m)&&(p=!0,setTimeout(()=>e(`SUCCESS: Dev server started successfully in background.
24
+ `;d="sandbox-exec",c=["-p",m,g,...y]}}let l=r?ei(d,c,{cwd:process.cwd(),env:{...process.env,...o}}):ei(d,c,{cwd:process.cwd(),env:{...process.env,CI:"false",TERM:"xterm-256color",FORCE_COLOR:"1",...o}});gt=l,Ks=!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=ko(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
25
 
26
- ${m}`),500))}}),l.stderr.on("data",g=>{if(!p){let y=g.toString();u+=y,s&&s(y)}}),l.on("close",g=>{if(p)return;gt=null;let y=[],m=Zo(f),w=Zo(u);m&&y.push(`STDOUT:
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=ti(u),w=ti(f);m&&y.push(`STDOUT:
27
27
  ${m}`),w&&y.push(`STDERR:
28
28
  ${w}`),g!==0&&y.push(`EXIT CODE: ${g}`);let x=y.join(`
29
29
 
30
- `)||"Command executed with no output.",S=bo(x).replace(/\n{3,}/g,`
30
+ `)||"Command executed with no output.",S=ko(x).replace(/\n{3,}/g,`
31
31
 
32
32
  `);e(g!==0?`ERROR: Command [${t}] failed with exit code [${g}].
33
33
 
34
34
  ${S}`:`SUCCESS: Command [${t}] completed.
35
35
 
36
- ${S}`)}),l.on("error",g=>{if(r&&g.code==="ENOENT"){if(i==="pwsh"){let m=ei(t,!0);return So(e,m,t,o,s,"powershell",a)}else if(i==="powershell"){let m=ei(t,!1);return So(e,m,t,o,s,"cmd",a)}}gt=null;let y=g instanceof Error?g.message:String(g);e(`ERROR: Failed to start command [${t}]: ${y}`)})};var Ys=null,jn=()=>{if(process.platform!=="win32")return!1;if(Ys!==null)return Ys;try{Wa('powershell.exe -NoProfile -Command "exit"',{stdio:"ignore"}),Ys=!0}catch{Ys=!1}return Ys},ni=null,fr=(e,n,t,o,s=!1,i=!0)=>{ni===null&&(ni=s);let a=`- JSON escape literal escape sequences in tool arguments
36
+ ${S}`)}),l.on("error",g=>{if(r&&g.code==="ENOENT"){if(i==="pwsh"){let m=ni(t,!0);return To(e,m,t,o,s,"powershell",a)}else if(i==="powershell"){let m=ni(t,!1);return To(e,m,t,o,s,"cmd",a)}}gt=null;let y=g instanceof Error?g.message:String(g);e(`ERROR: Failed to start command [${t}]: ${y}`)})};var Ys=null,jn=()=>{if(process.platform!=="win32")return!1;if(Ys!==null)return Ys;try{Ka('powershell.exe -NoProfile -Command "exit"',{stdio:"ignore"}),Ys=!0}catch{Ys=!1}return Ys},oi=null,yr=(e,n,t,o,s=!1,i=!0)=>{oi===null&&(oi=s);let a=`- JSON escape literal escape sequences in tool arguments
37
37
  - Same file, multiple edits? One PatchFile (\u226415 blocks) \u2190 Priority
38
38
  - Tool denied? Ask for guidance \u2190 mandatory
39
39
  - Need text or huge file? CodeSearch > Full Read
@@ -48,7 +48,7 @@ ${S}`)}),l.on("error",g=>{if(r&&g.code==="ENOENT"){if(i==="pwsh"){let m=ei(t,!0)
48
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
49
  - [tool:functions.Run(command="...")]. Runs ${n==="Windows"?jn()?"powershell":"windows CMD":"bash"} command. Destructive/Irreversible ops \u2192 Ask user
50
50
  - [tool:functions.Goal(method="create/append/get", tasks=[string array], markDone=[task array])]. If long multi-task: create Goals before starting. \`get + markDone\` to mark complete. Update every turn when created
51
- ${ni?'\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?`
51
+ ${oi?'\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
52
  **Sub Agent Tools**
53
53
  proactive use highly recommended. Prefer for any task, no user nudge needed
54
54
  Invocations:
@@ -80,7 +80,7 @@ ${e==="Flux"||e.toLowerCase()==="fluxcu"?`${a}`:""}
80
80
  - [tool:functions.WebScrape(url="...")]. Proactive use for specific webpage/docs/api
81
81
 
82
82
  ${e==="ICU"?`${d}`:e==="FluxCU"?`${r}
83
- ${d}`:e==="Flux"?`${r}`:`${h}`}`.trim()};var ur=(e=!0,n=!0)=>`
83
+ ${d}`:e==="Flux"?`${r}`:`${h}`}`.trim()};var wr=(e=!0,n=!0)=>`
84
84
  To use tools, must output exactly '[tool:functions.ToolName(arg1="value1")]' structured string in chat response \u2190 no exception
85
85
 
86
86
  -- Chat Management Tools --
@@ -108,7 +108,7 @@ Usage Rules:
108
108
  - Chat title is mandatory
109
109
  - Temporary memory is mandatory
110
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 ko={xHigh:`Effort: High
111
+ - Must not ignore any tool calls in given context of chat between user & agent`:""}`.trim();var Ro={xHigh:`Effort: High
112
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
113
  Continuous analysis, verify from first principles, seek failure paths, verify imports, tool results & system stability; avoid syntax errors
114
114
  MANDATORY: Full technical verification`,High:`Effort: High
@@ -121,36 +121,36 @@ MANDATORY: Brief verification for technical tasks/greetings`,Minimal:`Effort: Lo
121
121
  Quick, focused thinking, intent & complexity, required tools/files/actions, before acting
122
122
  Brief thoughts, think only enough to avoid mistakes, verify imports, tool results & system stability; avoid syntax errors`,Off:`Effort: Lowest
123
123
  No thinking. Immediate response
124
- Verify imports, tool results & system stability; avoid syntax errors`};import pr from"fs";import Ha from"screenshot-desktop";var mr=!1;(async()=>{try{let e=await Ft();if(Number(e?.display)===1){let n=await Ha.listDisplays();n&&n.length>1&&(mr=!0)}}catch{}})();var si=null,hr=null,Vs=null,Xc=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",Ga=process.env.NO_DEV||!1,qa=(e,n)=>{if(!n)return"";if(e!==hr||Vs===null){hr=e;try{let t=X(Dt,[]);Array.isArray(t)&&t.length>0?Vs=t.map(o=>`- ${o.memory}`).join(`
125
- `):Vs=""}catch(t){Vs="",pr.appendFileSync(`${cn}/memory/error.txt`,`${t.message}
124
+ Verify imports, tool results & system stability; avoid syntax errors`};import br from"fs";import Va from"screenshot-desktop";var Sr=!1;(async()=>{try{let e=await Ft();if(Number(e?.display)===1){let n=await Va.listDisplays();n&&n.length>1&&(Sr=!0)}}catch{}})();var ii=null,xr=null,Vs=null,od=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",Ja=process.env.NO_DEV||!1,Xa=(e,n)=>{if(!n)return"";if(e!==xr||Vs===null){xr=e;try{let t=X(Dt,[]);Array.isArray(t)&&t.length>0?Vs=t.map(o=>`- ${o.memory}`).join(`
125
+ `):Vs=""}catch(t){Vs="",br.appendFileSync(`${cn}/memory/error.txt`,`${t.message}
126
126
  -------------------------------------------------
127
127
 
128
- `)}}return Vs},gr=(e="",n="",t=!0,o=!1)=>{if(typeof n=="boolean"&&(o=t,t=n,n=""),!t)return"";let s=e?.length>0&&!o?`-- Recent context from other chats (Priority: Low, Focus: Chat Context > Recent) --
129
- ${e}`:"";return s?`${s}`:""},yr=(e,n,t,o,s=!0,i=!1,a="Google",r=!1,h,d)=>{let c=!1;process.env.forcedReasoning&&process.env.NVIDIA_BASE_URL&&a.toUpperCase()==="NVIDIA"&&(c=!0);let l="";if(!h&&a==="Google"){let E=n;n==="Fast"&&(E="Off"),n==="Low"&&(E="Minimal"),n==="Standard"&&(E="Medium"),(n==="xHigh"||n==="Max")&&(E="xHigh"),l=ko[E]||ko.Medium}if(h||a!=="Google"){let E={Fast:"Lowest",Low:"Low",Medium:"Medium",Standard:"Medium",High:"High",xHigh:"High",Max:"High"};l=ko.xHigh,l=l.replace("Effort: High",`Effort: ${E[n]}`).replace(`
128
+ `)}}return Vs},kr=(e="",n="",t=!0,o=!1)=>{if(typeof n=="boolean"&&(o=t,t=n,n=""),!t)return"";let s=e?.length>0&&!o?`-- Recent context from other chats (Priority: Low, Focus: Chat Context > Recent) --
129
+ ${e}`:"";return s?`${s}`:""},Tr=(e,n,t,o,s=!0,i=!1,a="Google",r=!1,h,d)=>{let c=!1;process.env.forcedReasoning&&process.env.NVIDIA_BASE_URL&&a.toUpperCase()==="NVIDIA"&&(c=!0);let l="";if(!h&&a==="Google"){let E=n;n==="Fast"&&(E="Off"),n==="Low"&&(E="Minimal"),n==="Standard"&&(E="Medium"),(n==="xHigh"||n==="Max")&&(E="xHigh"),l=Ro[E]||Ro.Medium}if(h||a!=="Google"){let E={Fast:"Lowest",Low:"Low",Medium:"Medium",Standard:"Medium",High:"High",xHigh:"High",Max:"High"};l=Ro.xHigh,l=l.replace("Effort: High",`Effort: ${E[n]}`).replace(`
130
130
  MANDATORY: Full technical verification`,""),n==="Fast"?l=`Effort: Lowest
131
131
  No thinking. Immediate response
132
132
  Verify imports, tool results & system stability; avoid syntax errors`:n==="Low"&&(l=`Effort: Low
133
133
  Quick, focused thinking, intent & complexity, required tools/files/actions, before acting
134
- Brief thoughts, think only enough to avoid mistakes, verify imports, tool results & system stability; avoid syntax errors`)}let f=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",u=e.instructions&&e.instructions?.length>0?`User Preferences: ${e.instructions}
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
135
 
136
136
  `:"",p=e.nickname&&e.nickname?.length>0?`User Nickname: ${e.nickname}
137
- ${u.length?"":`
137
+ ${f.length?"":`
138
138
  `}`:"",g=e.name&&e.name?.length>0?`User Name: ${e.name}
139
- ${p.length||u.length?"":`
140
- `}`:"",y=process.cwd(),m=qa(d,s),w=m?.length>0?`--- Saved Memories ---
139
+ ${p.length||f.length?"":`
140
+ `}`:"",y=process.cwd(),m=Xa(d,s),w=m?.length>0?`--- Saved Memories ---
141
141
  ${m}
142
142
 
143
- `:"",x=(()=>{let E=process.cwd().toLowerCase();if(process.platform==="win32"){let b=process.env.SystemRoot?.toLowerCase()||"c:\\windows",T=process.env.ProgramFiles?.toLowerCase()||"c:\\program files",$=process.env["ProgramFiles(x86)"]?.toLowerCase()||"c:\\program files (x86)";return E.startsWith(b)||E.startsWith(T)||E.startsWith($)}else return E==="/"||["/bin","/sbin","/etc","/usr","/var","/root"].some(T=>E.startsWith(T))})(),S=[{name:"Fluxflow.md",desc:"HIGH PRIORITY"},{name:"README.md",desc:"Goals"},{name:"Agent.md",desc:"Standards"},{name:"Skills.md",desc:"Workflows"},{name:"design.md",desc:"UI/UX"},{name:"architecture.md",desc:"System Structure"}];if(i||si===null){let E=S.filter(b=>pr.existsSync(b.name));si=t==="Flux"&&E.length>0?`
143
+ `:"",x=(()=>{let E=process.cwd().toLowerCase();if(process.platform==="win32"){let k=process.env.SystemRoot?.toLowerCase()||"c:\\windows",T=process.env.ProgramFiles?.toLowerCase()||"c:\\program files",$=process.env["ProgramFiles(x86)"]?.toLowerCase()||"c:\\program files (x86)";return E.startsWith(k)||E.startsWith(T)||E.startsWith($)}else return E==="/"||["/bin","/sbin","/etc","/usr","/var","/root"].some(T=>E.startsWith(T))})(),S=[{name:"Fluxflow.md",desc:"HIGH PRIORITY"},{name:"README.md",desc:"Goals"},{name:"Agent.md",desc:"Standards"},{name:"Skills.md",desc:"Workflows"},{name:"design.md",desc:"UI/UX"},{name:"architecture.md",desc:"System Structure"}];if(i||ii===null){let E=S.filter(k=>br.existsSync(k.name));ii=t==="Flux"&&E.length>0?`
144
144
  -- PROJECT CONTEXT --
145
- ${E.map(b=>`- ${b.name}: ${b.desc}`).join(`
145
+ ${E.map(k=>`- ${k.name}: ${k.desc}`).join(`
146
146
  `)}
147
147
  Check these first; These Files > Training Data. Safety rules apply
148
- `:""}let R=si;return`=== SYSTEM PROMPT ===
149
- Identity: Flux Flow. Sassy, Friendly, CLI Agent${Ga?"":" by Kushal Roy Chowdhury"}
150
- ${t==="Flux"?"Stepwise Execution, Run Automated Tests. Task Completion":t==="Flow"?"Concise, Humorous, Sarcastic":t==="ICU"?"Computer Use Capabilities. Screenshot as ground truth, analyze grid ids overlapping/close to target, keyboard shortcuts if efficient":"Computer Use & Workspace Capabilities. Screenshot (ground truth), analyze grid ids overlapping/close to target, keyboard shortcuts if efficient. Workspace Tools if faster. Focus on Productivity"}${mr&&t.toLowerCase().includes("cu")?`
148
+ `:""}let R=ii;return`=== SYSTEM PROMPT ===
149
+ Identity: Flux Flow. Sassy, Friendly, CLI Agent${Ja?"":" by Kushal Roy Chowdhury"}
150
+ ${t==="Flux"?"Stepwise Execution, Run Automated Tests. Task Completion":t==="Flow"?"Concise, Humorous, Sarcastic":t==="ICU"?"Computer Use Capabilities. Screenshot as ground truth, analyze grid ids overlapping/close to target, keyboard shortcuts if efficient":"Computer Use & Workspace Capabilities. Screenshot (ground truth), analyze grid ids overlapping/close to target, keyboard shortcuts if efficient. Workspace Tools if faster. Focus on Productivity"}${Sr&&t.toLowerCase().includes("cu")?`
151
151
  **Running on secondary screen. Opened app not visible in screenshot? Might be opened on primary. Use 'Ask' immediately with NO options and tell user to move app window to secondary**`:""}
152
152
 
153
- - OS: ${f}
153
+ - OS: ${u}
154
154
  - Use directory structure for file path resolution${s?`
155
155
  - Use relative time reference eg. few mins ago
156
156
  -- Chat Context > Metadata`:""}
@@ -161,7 +161,7 @@ ${c||n!=="Fast"&&(a==="Mistral"&&!h||n!=="xHigh"&&!h)?`critical thinking policy
161
161
  - Use <think>...</think> for reasoning before responding any queries
162
162
  `:""}`:`${l}
163
163
  `}
164
- ${fr(t,f,a.toLowerCase()==="deepseek"?!1:r,a,o?.advanceRollback,o?.subAgents!==!1)}
164
+ ${yr(t,u,a.toLowerCase()==="deepseek"?!1:r,a,o?.advanceRollback,o?.subAgents!==!1)}
165
165
  ${R}${s?`
166
166
  -- MEMORY RULES --
167
167
  - Subtly Personalize with relevent contextual memories. Auto Saves
@@ -178,7 +178,7 @@ ${t==="Flux"?`-- SECURITY POLICIES --
178
178
  - use kaomojis heavily`:""}
179
179
  === END SYSTEM PROMPT ===
180
180
 
181
- ${g}${p}${u}${w}`.trim()},wr=(e="",n=!0,t=!0)=>`=== SYSTEM PROMPT (strict headless logic worker: zero user-facing text policy, strictly follow) ===
181
+ ${g}${p}${f}${w}`.trim()},Rr=(e="",n=!0,t=!0)=>`=== SYSTEM PROMPT (strict headless logic worker: zero user-facing text policy, strictly follow) ===
182
182
  identity: silent background system process, have no mouth, only output is valid tool calls
183
183
  [critical rules]
184
184
  - output exactly '[tool:functions.ToolName(args)]' calls. no extra words outside
@@ -195,16 +195,16 @@ identity: silent background system process, have no mouth, only output is valid
195
195
  YOUR JOB: Analyze the 'User prompt' and 'Agent Raws' to extract facts for long-term memory or handle system tasks
196
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
197
 
198
- ${ur(n,t)}
198
+ ${wr(n,t)}
199
199
  === END SYSTEM PROMPT ===${e?`
200
200
 
201
201
  -- current saved user memories --
202
- ${e}`:""}`.trim();import Ct from"fs-extra";import To from"path";import{nanoid as Ya}from"nanoid";import dt from"fs-extra";import sn from"path";dt.ensureDirSync(Un);var un=null;async function Ka(e,n){try{if(e.type==="create")await dt.pathExists(e.filePath)&&(await dt.chmod(e.filePath,438).catch(()=>{}),await dt.remove(e.filePath));else if(e.type==="update"){if(!e.backupFile)return;let t=sn.join(Un,n.chatId,e.backupFile);if(await dt.pathExists(t)){let o=X(t,null);if(!o||!o.data)throw new Error(`Backup container corrupt or empty for ${sn.basename(e.filePath)}`);let s=Cs(o.data);await dt.pathExists(e.filePath)&&await dt.chmod(e.filePath,438).catch(()=>{}),await dt.writeFile(e.filePath,s,"utf8")}}}catch(t){throw new Error(`Restoration failed for ${sn.basename(e.filePath)}: ${t.message}`)}}async function za(e,n,t=7){let o=0;for(;o<t;)try{return await Ka(e,n),!0}catch{if(o++,o>=t)return!1;let i=Math.min(100*Math.pow(2,o-1),5e3);await new Promise(a=>setTimeout(a,i))}return!1}var oi=null,ft={async startTransaction(e,n){oi=e,un={id:`tx_prompt_${Date.now()}`,chatId:e,timestamp:new Date().toISOString(),prompt:n.trim(),changes:[],reverted:!1},he(rs,un)},async recordFileChange(e,n=null){try{if(!un){if(oi){let a=X(nn,[]),r=[...a].reverse().find(h=>h.chatId===oi);if(r){if(r.changes.some(f=>f.filePath===e))return;let c=await dt.pathExists(e)||n?"update":"create",l=null;if(c==="update"){let f=sn.basename(e);l=`${r.id}_${f}.bak`;let u=sn.join(Un,r.chatId);await dt.ensureDir(u);let p=sn.join(u,l),g=n!==null?n:await dt.readFile(e,"utf8").catch(()=>null);g!==null?he(p,{data:Gs(g)}):(c="create",l=null)}r.changes.push({filePath:e,type:c,backupFile:l}),he(nn,a)}}return}if(un.changes.some(a=>a.filePath===e))return;let s=await dt.pathExists(e)||n?"update":"create",i=null;if(s==="update"){let a=sn.basename(e);i=`${un.id}_${a}.bak`;let r=sn.join(Un,un.chatId);await dt.ensureDir(r);let h=sn.join(r,i),d=n!==null?n:await dt.readFile(e,"utf8").catch(()=>null);d!==null?he(h,{data:Gs(d)}):(s="create",i=null)}un.changes.push({filePath:e,type:s,backupFile:i}),he(rs,un)}catch{}},async commitTransaction(){if(un)try{let e=X(nn,[]);if(e.push(un),e.length>512e3){let n=e.shift();if(n.changes)for(let t of n.changes)t.backupFile&&await dt.remove(sn.join(Un,n.chatId,t.backupFile)).catch(()=>{})}he(nn,e),await dt.remove(rs).catch(()=>{})}catch{}finally{un=null}},async recoverCrashedTransaction(){try{if(await dt.pathExists(rs)){let e=X(rs,null);if(e?.changes?.length>0){let n=X(nn,[]);n.some(t=>t.id===e.id)||(n.push(e),he(nn,n))}await dt.remove(rs).catch(()=>{})}}catch{}},async rollbackToBefore(e){let n=X(nn,null);if(!n)throw new Error("No transaction ledger found.");let t=n.findIndex(a=>a.id===e);if(t===-1)throw new Error(`Transaction [${e}] not found.`);let o=n[t].chatId,s=n[t].prompt,i=n.slice(t).filter(a=>a.chatId===o&&!a.reverted).reverse();for(let a of i){for(let r of[...a.changes].reverse())await za(r,a);for(let r of a.changes)if(r.backupFile){let h=sn.join(Un,a.chatId,r.backupFile);await dt.remove(h).catch(()=>{})}n=n.filter(r=>r.id!==a.id),he(nn,n)}return{success:!0,chatId:o,targetPrompt:s}},async getChatHistory(e){try{return X(nn,[]).filter(t=>t.chatId===e&&!t.reverted)}catch{return[]}},async deleteChatBackups(e){try{await dt.remove(sn.join(Un,e));let n=X(nn,[]),t=n.filter(o=>o.chatId!==e);n.length!==t.length&&he(nn,t)}catch{}}};var xr=Promise.resolve(),Ro=e=>{let n=xr.then(async()=>{try{return await e()}catch(t){throw console.error("Lock Operation Failed:",t),t}});return xr=n.catch(()=>{}),n},ls=async()=>{await Ct.ensureDir($s);let e={};if(await Ct.pathExists(Es))try{e=X(Es,{})}catch{e={}}for(let n in e){let t=To.join($s,`${n}.json`);Object.defineProperty(e[n],"messages",{get:()=>{if(Ct.existsSync(t))try{return X(t,[])}catch{return[]}return[]},set:o=>{try{he(t,o)}catch{}},enumerable:!1,configurable:!0})}return e},fd=async(e,n,t)=>Ro(async()=>{await Ct.ensureDir($s);let o=await ls(),s=o[e],i=(t||[]).filter(y=>!y.isUpdateNotification&&(!y.isMeta||y.text&&y.text.includes("Request Cancelled")));try{(await Ft()).systemSettings?.preserveThinking===!1&&(i=i.filter(m=>m.role!=="think"))}catch{}let a=y=>{if(!y)return;let m=typeof y=="string"?y:y.text||y.content||"";if(!m||typeof m!="string")return;let w=m.replace(/\s*\n+\s*\[Prompted on:.*?\]/g,"").replace(/\[\/?(?:STEERING HINT|QUESTION)(?::\s*\w+)?\]/gi,"").trim();if(!w)return;let x=w.split(/\s+/),S;return x.length>7?S=x.slice(0,7).join(" ")+"...":w.length>45?S=w.substring(0,45).trimEnd()+"...":S=w,S},r,h=i.filter(y=>y.role==="user"),d=h[0],c=h[h.length-1],l=a(c),f=a(d);s&&s.prompt?Math.random()<.5&&l?r=l:r=s.prompt:r=f||l;let u=n||(s?s.name:`Session ${e.slice(-6)}`),p=To.join($s,`${e}.json`);he(p,i),o[e]={name:u,prompt:r||void 0,updatedAt:Date.now()};let g={};for(let y in o)g[y]={name:o[y].name,prompt:o[y].prompt||void 0,updatedAt:o[y].updatedAt};he(Es,g)}),br=async(e,n)=>Ro(async()=>{let t=await ls();t[e]?(t[e].name=n,t[e].updatedAt=Date.now()):t[e]={name:n,updatedAt:Date.now()};let o={};for(let s in t)o[s]={name:t[s].name,prompt:t[s].prompt||void 0,updatedAt:t[s].updatedAt};he(Es,o)}),Va=async e=>Ro(async()=>{let n=await ls();delete n[e];let t={};for(let a in n)t[a]={name:n[a].name,prompt:n[a].prompt||void 0,updatedAt:n[a].updatedAt};if(he(Es,t),await Ct.pathExists(Wn))try{let a=X(Wn,[]);if(Array.isArray(a)){let r=a.filter(h=>Object.keys(h)[0]!==String(e));he(Wn,r)}}catch{}let o=X(Xt,{});o[e]&&(delete o[e],he(Xt,o));let s=X(vn,{});s[e]&&(delete s[e],he(vn,s)),await ft.deleteChatBackups(e);let i=To.join($s,`${e}.json`);if(await Ct.pathExists(i))try{await Ct.remove(i)}catch{}return n}),ud=()=>`flow-${Ya(6)}`,hd=async e=>{if(!e||e==="Never")return;let n=parseInt(e);if(isNaN(n))return;let t=await ls(),o=Date.now(),s=n*24*60*60*1e3,i=0;for(let a in t){let r=t[a];r.updatedAt&&o-r.updatedAt>s&&(await Va(a),i++)}return i},Ja=e=>{let n=e.replace(/[\[\]]/g,"").trim(),t=new Date(n);if(!isNaN(t.getTime()))return t.getTime();let o=n.split(/,\s*|\s+/);if(o.length===0)return null;let s=o[0],i=o[1]||"",a=o[2]||"",r=s.split(/[-\/.]/).map(Number);if(r.length!==3)return null;let h="en";try{h=Intl.DateTimeFormat().resolvedOptions().locale||"en"}catch{}let d=!/^en[-_]?us$|^en$/.test(h?.toLowerCase()),c,l,f;if(r[0]>1e3)c=r[0],l=r[1],f=r[2];else if(r[2]>1e3)c=r[2],r[0]>12?(f=r[0],l=r[1]):r[1]>12?(f=r[1],l=r[0]):d?(f=r[0],l=r[1]):(l=r[0],f=r[1]);else return null;if(l<1||l>12||f<1||f>31)return null;let u=0,p=0,g=0;if(i){let m=i.split(":").map(Number);u=m[0]||0,p=m[1]||0,g=m[2]||0,a.toLowerCase()==="pm"&&u<12?u+=12:a.toLowerCase()==="am"&&u===12&&(u=0)}let y=new Date(c,l-1,f,u,p,g);return isNaN(y.getTime())?null:y.getTime()},Xa=async e=>{try{if(!await Ct.pathExists(e))return;let n=await Ct.readFile(e,"utf8");if(!n.trim())return;let t=n.split(`
203
- `),o=[],s=null,i=/^\s*(?:DEBUG|ERROR|SEARCH|PUPPETEER)\b/i;for(let l of t)i.test(l)?(s&&o.push(s),s={header:l,body:[]}):s?s.body.push(l):o.push({header:l,body:[]});s&&o.push(s);let a=10080*60*1e3,r=Date.now(),h=[],d=/(\d{1,4}[-\/.]\d{1,4}[-\/.]\d{1,4}(?:,\s*|\s+)?(?:\d{1,2}:\d{2}:\d{2}(?:\s*[aApP][mM])?)?)/;for(let l of o){if(i.test(l.header)){let p=l.header.match(d);if(p){let g=Ja(p[1]);if(g&&r-g>a)continue}}let u=l.header+(l.body.length>0?`
202
+ ${e}`:""}`.trim();import Ct from"fs-extra";import Eo from"path";import{nanoid as el}from"nanoid";import dt from"fs-extra";import sn from"path";dt.ensureDirSync(Un);var un=null;async function Qa(e,n){try{if(e.type==="create")await dt.pathExists(e.filePath)&&(await dt.chmod(e.filePath,438).catch(()=>{}),await dt.remove(e.filePath));else if(e.type==="update"){if(!e.backupFile)return;let t=sn.join(Un,n.chatId,e.backupFile);if(await dt.pathExists(t)){let o=X(t,null);if(!o||!o.data)throw new Error(`Backup container corrupt or empty for ${sn.basename(e.filePath)}`);let s=Cs(o.data);await dt.pathExists(e.filePath)&&await dt.chmod(e.filePath,438).catch(()=>{}),await dt.writeFile(e.filePath,s,"utf8")}}}catch(t){throw new Error(`Restoration failed for ${sn.basename(e.filePath)}: ${t.message}`)}}async function Za(e,n,t=7){let o=0;for(;o<t;)try{return await Qa(e,n),!0}catch{if(o++,o>=t)return!1;let i=Math.min(100*Math.pow(2,o-1),5e3);await new Promise(a=>setTimeout(a,i))}return!1}var ri=null,ft={async startTransaction(e,n){ri=e,un={id:`tx_prompt_${Date.now()}`,chatId:e,timestamp:new Date().toISOString(),prompt:n.trim(),changes:[],reverted:!1},he(rs,un)},async recordFileChange(e,n=null){try{if(!un){if(ri){let a=X(nn,[]),r=[...a].reverse().find(h=>h.chatId===ri);if(r){if(r.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=`${r.id}_${u}.bak`;let f=sn.join(Un,r.chatId);await dt.ensureDir(f);let p=sn.join(f,l),g=n!==null?n:await dt.readFile(e,"utf8").catch(()=>null);g!==null?he(p,{data:Gs(g)}):(c="create",l=null)}r.changes.push({filePath:e,type:c,backupFile:l}),he(nn,a)}}return}if(un.changes.some(a=>a.filePath===e))return;let s=await dt.pathExists(e)||n?"update":"create",i=null;if(s==="update"){let a=sn.basename(e);i=`${un.id}_${a}.bak`;let r=sn.join(Un,un.chatId);await dt.ensureDir(r);let h=sn.join(r,i),d=n!==null?n:await dt.readFile(e,"utf8").catch(()=>null);d!==null?he(h,{data:Gs(d)}):(s="create",i=null)}un.changes.push({filePath:e,type:s,backupFile:i}),he(rs,un)}catch{}},async commitTransaction(){if(un)try{let e=X(nn,[]);if(e.push(un),e.length>512e3){let n=e.shift();if(n.changes)for(let t of n.changes)t.backupFile&&await dt.remove(sn.join(Un,n.chatId,t.backupFile)).catch(()=>{})}he(nn,e),await dt.remove(rs).catch(()=>{})}catch{}finally{un=null}},async recoverCrashedTransaction(){try{if(await dt.pathExists(rs)){let e=X(rs,null);if(e?.changes?.length>0){let n=X(nn,[]);n.some(t=>t.id===e.id)||(n.push(e),he(nn,n))}await dt.remove(rs).catch(()=>{})}}catch{}},async rollbackToBefore(e){let n=X(nn,null);if(!n)throw new Error("No transaction ledger found.");let t=n.findIndex(a=>a.id===e);if(t===-1)throw new Error(`Transaction [${e}] not found.`);let o=n[t].chatId,s=n[t].prompt,i=n.slice(t).filter(a=>a.chatId===o&&!a.reverted).reverse();for(let a of i){for(let r of[...a.changes].reverse())await Za(r,a);for(let r of a.changes)if(r.backupFile){let h=sn.join(Un,a.chatId,r.backupFile);await dt.remove(h).catch(()=>{})}n=n.filter(r=>r.id!==a.id),he(nn,n)}return{success:!0,chatId:o,targetPrompt:s}},async getChatHistory(e){try{return X(nn,[]).filter(t=>t.chatId===e&&!t.reverted)}catch{return[]}},async deleteChatBackups(e){try{await dt.remove(sn.join(Un,e));let n=X(nn,[]),t=n.filter(o=>o.chatId!==e);n.length!==t.length&&he(nn,t)}catch{}}};var Er=Promise.resolve(),$o=e=>{let n=Er.then(async()=>{try{return await e()}catch(t){throw console.error("Lock Operation Failed:",t),t}});return Er=n.catch(()=>{}),n},ls=async()=>{await Ct.ensureDir($s);let e={};if(await Ct.pathExists(Es))try{e=X(Es,{})}catch{e={}}for(let n in e){let t=Eo.join($s,`${n}.json`);Object.defineProperty(e[n],"messages",{get:()=>{if(Ct.existsSync(t))try{return X(t,[])}catch{return[]}return[]},set:o=>{try{he(t,o)}catch{}},enumerable:!1,configurable:!0})}return e},wd=async(e,n,t)=>$o(async()=>{await Ct.ensureDir($s);let o=await ls(),s=o[e],i=(t||[]).filter(y=>!y.isUpdateNotification&&(!y.isMeta||y.text&&y.text.includes("Request Cancelled")));try{(await Ft()).systemSettings?.preserveThinking===!1&&(i=i.filter(m=>m.role!=="think"))}catch{}let a=y=>{if(!y)return;let m=typeof y=="string"?y:y.text||y.content||"";if(!m||typeof m!="string")return;let w=m.replace(/\s*\n+\s*\[Prompted on:.*?\]/g,"").replace(/\[\/?(?:STEERING HINT|QUESTION)(?::\s*\w+)?\]/gi,"").trim();if(!w)return;let x=w.split(/\s+/),S;return x.length>7?S=x.slice(0,7).join(" ")+"...":w.length>45?S=w.substring(0,45).trimEnd()+"...":S=w,S},r,h=i.filter(y=>y.role==="user"),d=h[0],c=h[h.length-1],l=a(c),u=a(d);s&&s.prompt?Math.random()<.5&&l?r=l:r=s.prompt:r=u||l;let f=n||(s?s.name:`Session ${e.slice(-6)}`),p=Eo.join($s,`${e}.json`);he(p,i),o[e]={name:f,prompt:r||void 0,updatedAt:Date.now()};let g={};for(let y in o)g[y]={name:o[y].name,prompt:o[y].prompt||void 0,updatedAt:o[y].updatedAt};he(Es,g)}),$r=async(e,n)=>$o(async()=>{let t=await ls();t[e]?(t[e].name=n,t[e].updatedAt=Date.now()):t[e]={name:n,updatedAt:Date.now()};let o={};for(let s in t)o[s]={name:t[s].name,prompt:t[s].prompt||void 0,updatedAt:t[s].updatedAt};he(Es,o)}),tl=async e=>$o(async()=>{let n=await ls();delete n[e];let t={};for(let a in n)t[a]={name:n[a].name,prompt:n[a].prompt||void 0,updatedAt:n[a].updatedAt};if(he(Es,t),await Ct.pathExists(Wn))try{let a=X(Wn,[]);if(Array.isArray(a)){let r=a.filter(h=>Object.keys(h)[0]!==String(e));he(Wn,r)}}catch{}let o=X(Xt,{});o[e]&&(delete o[e],he(Xt,o));let s=X(vn,{});s[e]&&(delete s[e],he(vn,s)),await ft.deleteChatBackups(e);let i=Eo.join($s,`${e}.json`);if(await Ct.pathExists(i))try{await Ct.remove(i)}catch{}return n}),xd=()=>`flow-${el(6)}`,bd=async e=>{if(!e||e==="Never")return;let n=parseInt(e);if(isNaN(n))return;let t=await ls(),o=Date.now(),s=n*24*60*60*1e3,i=0;for(let a in t){let r=t[a];r.updatedAt&&o-r.updatedAt>s&&(await tl(a),i++)}return i},nl=e=>{let n=e.replace(/[\[\]]/g,"").trim(),t=new Date(n);if(!isNaN(t.getTime()))return t.getTime();let o=n.split(/,\s*|\s+/);if(o.length===0)return null;let s=o[0],i=o[1]||"",a=o[2]||"",r=s.split(/[-\/.]/).map(Number);if(r.length!==3)return null;let h="en";try{h=Intl.DateTimeFormat().resolvedOptions().locale||"en"}catch{}let d=!/^en[-_]?us$|^en$/.test(h?.toLowerCase()),c,l,u;if(r[0]>1e3)c=r[0],l=r[1],u=r[2];else if(r[2]>1e3)c=r[2],r[0]>12?(u=r[0],l=r[1]):r[1]>12?(u=r[1],l=r[0]):d?(u=r[0],l=r[1]):(l=r[0],u=r[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,a.toLowerCase()==="pm"&&f<12?f+=12:a.toLowerCase()==="am"&&f===12&&(f=0)}let y=new Date(c,l-1,u,f,p,g);return isNaN(y.getTime())?null:y.getTime()},sl=async e=>{try{if(!await Ct.pathExists(e))return;let n=await Ct.readFile(e,"utf8");if(!n.trim())return;let t=n.split(`
203
+ `),o=[],s=null,i=/^\s*(?:DEBUG|ERROR|SEARCH|PUPPETEER)\b/i;for(let l of t)i.test(l)?(s&&o.push(s),s={header:l,body:[]}):s?s.body.push(l):o.push({header:l,body:[]});s&&o.push(s);let a=10080*60*1e3,r=Date.now(),h=[],d=/(\d{1,4}[-\/.]\d{1,4}[-\/.]\d{1,4}(?:,\s*|\s+)?(?:\d{1,2}:\d{2}:\d{2}(?:\s*[aApP][mM])?)?)/;for(let l of o){if(i.test(l.header)){let p=l.header.match(d);if(p){let g=nl(p[1]);if(g&&r-g>a)continue}}let f=l.header+(l.body.length>0?`
204
204
  `+l.body.join(`
205
- `):"");h.push(u)}let c=h.join(`
205
+ `):"");h.push(f)}let c=h.join(`
206
206
  `).trim();c?await Ct.writeFile(e,c+`
207
- `,"utf8"):await Ct.writeFile(e,"","utf8")}catch{}},pd=async e=>{try{if(!await Ct.pathExists(e))return;let n=async t=>{let o=await Ct.readdir(t);for(let s of o){let i=To.join(t,s);(await Ct.stat(i)).isDirectory()?(await n(i),(await Ct.readdir(i)).length===0&&await Ct.remove(i)):s.endsWith(".log")&&await Xa(i)}};await n(e)}catch{}},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 md=async(e,n,t)=>Ro(async()=>{let o=X(Wn,[]);Array.isArray(o)||(o=[]);let s={total:n,context:t},i=o.findIndex(a=>Object.keys(a)[0]===String(e));i!==-1?o[i]={[String(e)]:s}:o.push({[String(e)]:s}),he(Wn,o)}),gd=async e=>{try{if(!await Ct.pathExists(Wn))return{total:0,context:0};let n=X(Wn,[]);if(!Array.isArray(n))return{total:0,context:0};let t=n.find(o=>Object.keys(o)[0]===String(e));return t?t[String(e)]:{total:0,context:0}}catch{return{total:0,context:0}}};import yt from"fs-extra";import kr from"path";var Qa=()=>Math.random().toString(36).substring(2)+Date.now().toString(36),se=null,Hn=null,Tr=0,_s=!1,In={agent:0,background:0,search:0,toolSuccess:0,toolFailure:0,toolDenied:0,duration:0,tokens:0,cachedTokens:0,candidateTokens:0,linesAdded:0,linesRemoved:0,imageCalls:[]},Ms=(e,n)=>{if(!e)return{};let t=Object.keys(e),o=new Date(new Date(n).getTime()-720*60*60*1e3),s={};for(let i of t)new Date(i)>=o&&(s[i]=e[i]);return s},Eo=async()=>{let e=new Date().toISOString().split("T")[0];try{!await yt.exists(Jt)&&await yt.exists(Vo)&&(await yt.ensureDir(kr.dirname(Jt)),await yt.move(Vo,Jt))}catch{}let n=Jt+".tmp",t=null;try{if(await yt.exists(n)){let s=(await yt.readFile(n,"utf8")).trim(),i=null;if(s.startsWith("{")||s.startsWith("[")?i=JSON.parse(s):i=JSON.parse(Cs(s)),i&&i.date&&i.stats){t=i;try{await yt.rename(n,Jt)}catch{}}else try{await yt.remove(n)}catch{}}}catch{try{await yt.remove(n)}catch{}}if(!t)try{if(await yt.exists(Jt)){let s=(await yt.readFile(Jt,"utf8")).trim();s.startsWith("{")||s.startsWith("[")?t=JSON.parse(s):t=JSON.parse(Cs(s))}}catch{}let o=t;if(o){let s=o.stats||{...In},i={...In,...s};Array.isArray(i.imageCalls)||(i.imageCalls=[]);let a=o.history||{},r=Ms(a,e);if(Object.keys(a).length!==Object.keys(r).length&&(_s=!0),o.date===e)return{...o,stats:i,history:r};{let h=o.date,d=i,c={...r};return h&&(c[h]=d),{date:e,stats:{...In},history:Ms(c,e)}}}return{date:e,stats:{...In},history:{}}},ii=async()=>{if(!(!_s||!se))try{await yt.ensureDir(kr.dirname(Jt));let e=null;try{if(await yt.exists(Jt)){let s=(await yt.readFile(Jt,"utf8")).trim();s.startsWith("{")||s.startsWith("[")?e=JSON.parse(s):e=JSON.parse(Cs(s))}}catch{}if(e&&e.date===se.date&&e.stats){for(let s in se.stats)if(e.stats[s]!==void 0){if(Array.isArray(se.stats[s])){let i=Array.isArray(e.stats[s])?e.stats[s]:[],a=se.stats[s],r=new Map;for(let h of[...i,...a])h&&h.timestamp&&r.set(h.timestamp,h);se.stats[s]=Array.from(r.values())}else if(typeof se.stats[s]=="number")se.stats[s]=Math.max(se.stats[s],Number(e.stats[s])||0);else if(se.stats[s]&&typeof se.stats[s]=="object"){let i=e.stats[s]||{},a=se.stats[s];for(let r in i)if(typeof i[r]=="number")a[r]=Math.max(a[r]||0,i[r]);else if(i[r]&&typeof i[r]=="object"){a[r]||(a[r]={});for(let h in i[r])if(typeof i[r][h]=="number")a[r][h]=Math.max(a[r][h]||0,i[r][h]);else if(i[r][h]&&typeof i[r][h]=="object"){a[r][h]||(a[r][h]={});for(let d in i[r][h])a[r][h][d]=Math.max(a[r][h][d]||0,i[r][h][d])}}}}}if(e&&e.history){let s={...se.history||{}};for(let i in e.history)if(s[i])for(let a in s[i])if(a==="imageCalls"){let r=Array.isArray(e.history[i].imageCalls)?e.history[i].imageCalls:[],h=Array.isArray(s[i].imageCalls)?s[i].imageCalls:[],d=new Map;for(let c of[...r,...h])c&&c.timestamp&&d.set(c.timestamp,c);s[i].imageCalls=Array.from(d.values())}else typeof s[i][a]=="number"&&(s[i][a]=Math.max(s[i][a],Number(e.history[i][a])||0));else s[i]=e.history[i];se.history=Ms(s,se.date||today)}else if(se&&se.history){let s=new Date().toISOString().split("T")[0];se.history=Ms(se.history,s)}se.saveId=Qa();let n=Jt+".tmp",t=Gs(JSON.stringify(se,null,2));await yt.writeFile(n,t,"utf8");let o=await yt.open(n,"r+");await yt.fsync(o),await yt.close(o),await yt.rename(n,Jt),_s=!1,Tr=Date.now()}catch{}},$o=()=>{if(_s=!0,Hn)return;let e=Date.now(),n=Math.max(0,1500-(e-Tr));Hn=setTimeout(async()=>{await ii(),Hn=null},n),Hn.unref&&Hn.unref()},Td=async()=>{se=await Eo(),_s&&$o()},Rd=async()=>{Hn&&(clearTimeout(Hn),Hn=null),await ii()},Tn=async()=>{let e=new Date().toISOString().split("T")[0];if(!se)se=await Eo();else if(se.date!==e){let n=se.date,t=se.stats,o=se.history||{};t&&(o[n]=t),se={date:e,stats:{...In},history:Ms(o,e)},_s=!0,await ii()}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 Eo()),se.date!==e&&await Tn();let n=se.history||{},t=Ms(n,e);se.history=t;let o=se.stats||{...In},s={...In};s.imageCalls=[],s.models={};let i=(a,r)=>{for(let h in a)if(h==="imageCalls")a.imageCalls=[...a.imageCalls||[],...r.imageCalls||[]];else if(h==="models"){let d=r.models||{};for(let c in d){a.models[c]||(a.models[c]={});for(let l in d[c]){a.models[c][l]||(a.models[c][l]={tokens:0,cachedTokens:0,candidateTokens:0});let f=a.models[c][l],u=d[c][l];f.tokens+=u.tokens||0,f.cachedTokens+=u.cachedTokens||0,f.candidateTokens+=u.candidateTokens||0}}}else typeof a[h]=="number"&&(a[h]+=r[h]||0)};i(s,o);for(let a in t)i(s,t[a]);return s},It=async(e,n)=>{e==="toolSuccess"?Js.toolSuccess++:e==="toolFailure"?Js.toolFailure++:e==="toolDenied"&&Js.toolDenied++;let t=await Tn();t[e]!==void 0&&t[e]++,n&&e==="agent"&&(t.providerRequests||(t.providerRequests={}),t.providerRequests[n]=(t.providerRequests[n]||0)+1),$o()},Js={linesAdded:0,linesRemoved:0,toolSuccess:0,toolFailure:0,toolDenied:0},Gt=async(e,n,t,o)=>{e==="linesAdded"?Js.linesAdded+=n:e==="linesRemoved"&&(Js.linesRemoved+=n);let s=await Tn();if(s[e]!==void 0&&(s[e]+=Math.floor(n)),t&&o&&(e==="tokens"||e==="cachedTokens"||e==="candidateTokens")){s.models||(s.models={}),s.models[t]||(s.models[t]={}),s.models[t][o]||(s.models[t][o]={tokens:0,cachedTokens:0,candidateTokens:0});let i=s.models[t][o];e==="tokens"&&(i.tokens+=Math.floor(n)),e==="cachedTokens"&&(i.cachedTokens+=Math.floor(n)),e==="candidateTokens"&&(i.candidateTokens+=Math.floor(n))}$o()},el=async(e=1)=>{let n=new Date,t=n.toISOString().split("T")[0];se||(se=await Eo()),se.date!==t&&await Tn();let o=n.getFullYear(),s=n.getMonth();n.getDate()<e&&(s-=1,s<0&&(s=11,o-=1));let r=new Date(o,s,e).toISOString().split("T")[0],h=se.history||{},d=se.stats||{...In},c={...In};c.imageCalls=[],c.models={};let l=(f,u)=>{for(let p in f)if(p==="imageCalls")f.imageCalls=[...f.imageCalls||[],...u.imageCalls||[]];else if(p==="models"){let g=u.models||{};for(let y in g){f.models[y]||(f.models[y]={});for(let m in g[y]){f.models[y][m]||(f.models[y][m]={tokens:0,cachedTokens:0,candidateTokens:0});let w=f.models[y][m],x=g[y][m];w.tokens+=x.tokens||0,w.cachedTokens+=x.cachedTokens||0,w.candidateTokens+=x.candidateTokens||0}}}else typeof f[p]=="number"&&(f[p]+=u[p]||0)};l(c,d);for(let f in h)f>=r&&f<t&&l(c,h[f]);return c},ri=async(e,n={})=>{let t=await Ft().catch(()=>({})),o=n.apiTier||t.apiTier||"Free",s=n.quotas||n.systemSettings?.quotas||t.quotas||{},i=s.providerBudgets||{},a=!!i.__useProvider,r=n.aiProvider||t.aiProvider||"Google",h=a&&!!i[r],d=()=>{if(h){let c=i[r];return{agentLimit:typeof c.agentLimit=="number"&&c.agentLimit>0?c.agentLimit:99999999,tokenLimit:typeof c.tokenLimit=="number"&&c.tokenLimit>0?c.tokenLimit:99999999999999,monthlyTokenLimit:typeof c.monthlyTokenLimit=="number"&&c.monthlyTokenLimit>0?c.monthlyTokenLimit:99999999999999}}return{agentLimit:s.agentLimit||99999999,tokenLimit:s.tokenLimit||99999999999999,monthlyTokenLimit:s.monthlyTokenLimit||99999999999999}};if(e==="agent"){let{agentLimit:c,tokenLimit:l,monthlyTokenLimit:f}=d(),u=await Tn(),p;s.resetMode==="Custom"?p=await el(s.resetDay||1):p=await Za();let g=0,y=0,m=0;if(h){g=u.providerRequests?.[r]||0;let w=u.models?.[r]||{};for(let S in w)y+=w[S]?.tokens||0;let x=p.models?.[r]||{};for(let S in x)m+=x[S]?.tokens||0}else g=u.agent||0,y=u.tokens||0,m=p.tokens||0;return o==="Free"&&u.agent+u.background>=999999?{allowed:!1,reason:"Free Tier Daily Usage Limit Exceeded"}:g>=c?{allowed:!1,reason:h?`Daily Request Limit Reached for ${r}`:"Daily Agent Request Limit Reached"}:y>=l?{allowed:!1,reason:h?`Daily Token Budget Exhausted for ${r}`:"Daily Token Budget Exhausted"}:m>=f?{allowed:!1,reason:h?`Monthly Token Budget Exhausted for ${r}`:"Monthly Token Budget Exhausted"}:{allowed:!0}}if(e==="background"){let c=await Tn();if(o==="Free"&&c.agent+c.background>=999999)return{allowed:!1,reason:"Free Tier Background Limit Exceeded"};let l=c.background<(s.backgroundLimit||999999);return{allowed:l,reason:l?void 0:"Background Request Limit Exceeded"}}if(e==="search"){let l=(await Tn()).search<(s.searchLimit||100);return{allowed:l,reason:l?void 0:"Search Quota Exceeded"}}return{allowed:!0}},Rr=async(e,n={})=>(await ri(e,n)).allowed,ai=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},Er=(e,n)=>{if(!e||e.length===0)return .025;let o=ai(e);if(o.length===0)return .025;let s=[];for(let l of o){let f=.025;if(s.length>0){let p=s[s.length-1],g=!1;if(s.length>=2){let y=s[s.length-2];p.ratio>=.8&&y.ratio>=.8&&(g=!0)}if(g)f=.015;else{let y=p.limit,m=p.ratio;m>=.8?f=y===.015?.015:y:m<.4?f=Math.min(.025,y+.005):m>=.4&&m<.6?f=Math.min(.025,y+.004):f=Math.min(.025,y+.002)}}let u=f>0?l.spent/f:0;s.push({limit:f,spent:l.spent,ratio:u})}let i=o[o.length-1];if(n<i.end)return s[s.length-1].limit;let a=s[s.length-1].limit,r=a,h=s[s.length-1].ratio,d=i.end,c=0;for(let l=s.length-1;l>=0&&s[l].ratio>=.8;l--)c++;for(;d<=n;){let l=.025;c>=2?l=.015:h>=.8?l=r===.015?.015:r:h<.4?l=Math.min(.025,r+.005):h>=.4&&h<.6?l=Math.min(.025,r+.004):l=Math.min(.025,r+.002),r=l,h=0,c=0,d+=36e5,a=l}return a},$r=async e=>{let n=e.imageSettings||{keyType:"Default",quality:"Low-High"};if(n.keyType!=="Default")return!0;let o={Low:.001,"Low-High":.002,Medium:.008,"Medium-High":.01,High:.045,Ultra:.0488,Premium:.15}[n.quality]||.002,s=await Tn();s.imageCalls||(s.imageCalls=[]);let i=Date.now(),a=ai(s.imageCalls),r=0;if(a.length>0){let d=a[a.length-1];i>=d.start&&i<d.end&&(r=d.spent)}let h=Er(s.imageCalls,i);return r+o<=h},Cr=async()=>{let e=await Tn();e.imageCalls||(e.imageCalls=[]);let n=Date.now(),t=ai(e.imageCalls),o=[],s=0,i=0;if(t.length>0){let d=t[t.length-1];n>=d.start&&n<d.end&&(o=d.calls,s=d.spent,i=Math.max(0,Math.ceil((d.end-n)/(60*1e3))))}let a=Er(e.imageCalls,n),r=Math.max(0,a-s),h=s;return{totalSpent:s,remaining:r,activeCallsCount:o.length,nextResetMin:i,reclaimCost:h,limit:a}},_r=async e=>{let n=e.imageSettings||{keyType:"Default",quality:"Low-High"},o={Low:.001,"Low-High":.002,Medium:.008,"Medium-High":.01,High:.045,Ultra:.0488,Premium:.1}[n.quality]||.002,s=await Tn();s.imageCalls||(s.imageCalls=[]),s.imageCalls.push({timestamp:Date.now(),cost:o}),$o()};import vr from"puppeteer";import Ir from"fs";import Or from"path";import Mr from"os";import Xs from"path";import As from"fs";import{createRequire as tl}from"module";import{fileURLToPath as nl}from"url";var sl=tl(import.meta.url),Ar=Xs.dirname(nl(import.meta.url));function cs(){let e=Mr.platform(),n=Mr.arch(),t="",o="",s="";if(e==="win32")t=n==="x64"?"win64":"win32",o="chrome.exe",s=`chrome-${t}`;else if(e==="darwin"){t=n==="arm64"?"mac_arm":"mac";let a=n==="arm64"?"arm64":"x64";o="Google Chrome.app/Contents/MacOS/Google Chrome",s=`chrome-mac-${a}`}else if(e==="linux")t="linux",o="chrome",s="chrome-linux64";else return{};let i=Xs.resolve(Ar,"..","..",".puppeteerrc.cjs");if(As.existsSync(i)||(i=Xs.resolve(Ar,"..",".puppeteerrc.cjs")),!As.existsSync(i))return{};try{let a=sl(i),r=a.cacheDirectory,h=a.chrome?.version;if(r){if(process.env.PUPPETEER_CACHE_DIR=r,h){let l=Xs.join(r,"chrome",`${t}-${h}`,s,o);if(As.existsSync(l))return{executablePath:l,cacheDirectory:r}}let d=l=>{if(!As.existsSync(l))return null;try{let f=As.readdirSync(l),u=[];for(let p of f){let g=Xs.join(l,p),y;try{y=As.statSync(g)}catch{continue}if(y.isDirectory())u.push(g);else if(p.toLowerCase()===o.toLowerCase()&&(!h||g.includes(h)))return g}if(h){for(let p of u)if(p.includes(h)){let g=d(p);if(g)return g}}for(let p of u)if(!h||!p.includes(h)){let g=d(p);if(g)return g}}catch{}return null},c=d(r);if(c)return{executablePath:c,cacheDirectory:r}}}catch{}return{}}var li=async e=>{let{query:n,limit:t=5,aiMode:o=!1}=I(e);if(!n)return'ERROR: Missing "query" argument for web_search.';let s=3,i=null;if(o){let a=`Query: ${n}
207
+ `,"utf8"):await Ct.writeFile(e,"","utf8")}catch{}},Sd=async e=>{try{if(!await Ct.pathExists(e))return;let n=async t=>{let o=await Ct.readdir(t);for(let s of o){let i=Eo.join(t,s);(await Ct.stat(i)).isDirectory()?(await n(i),(await Ct.readdir(i)).length===0&&await Ct.remove(i)):s.endsWith(".log")&&await sl(i)}};await n(e)}catch{}},Cr=(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 kd=async(e,n,t)=>$o(async()=>{let o=X(Wn,[]);Array.isArray(o)||(o=[]);let s={total:n,context:t},i=o.findIndex(a=>Object.keys(a)[0]===String(e));i!==-1?o[i]={[String(e)]:s}:o.push({[String(e)]:s}),he(Wn,o)}),Td=async e=>{try{if(!await Ct.pathExists(Wn))return{total:0,context:0};let n=X(Wn,[]);if(!Array.isArray(n))return{total:0,context:0};let t=n.find(o=>Object.keys(o)[0]===String(e));return t?t[String(e)]:{total:0,context:0}}catch{return{total:0,context:0}}};import yt from"fs-extra";import _r from"path";var ol=()=>Math.random().toString(36).substring(2)+Date.now().toString(36),se=null,Hn=null,Mr=0,_s=!1,In={agent:0,background:0,search:0,toolSuccess:0,toolFailure:0,toolDenied:0,duration:0,tokens:0,cachedTokens:0,candidateTokens:0,linesAdded:0,linesRemoved:0,imageCalls:[]},Ms=(e,n)=>{if(!e)return{};let t=Object.keys(e),o=new Date(new Date(n).getTime()-720*60*60*1e3),s={};for(let i of t)new Date(i)>=o&&(s[i]=e[i]);return s},Co=async()=>{let e=new Date().toISOString().split("T")[0];try{!await yt.exists(Jt)&&await yt.exists(Xo)&&(await yt.ensureDir(_r.dirname(Jt)),await yt.move(Xo,Jt))}catch{}let n=Jt+".tmp",t=null;try{if(await yt.exists(n)){let s=(await yt.readFile(n,"utf8")).trim(),i=null;if(s.startsWith("{")||s.startsWith("[")?i=JSON.parse(s):i=JSON.parse(Cs(s)),i&&i.date&&i.stats){t=i;try{await yt.rename(n,Jt)}catch{}}else try{await yt.remove(n)}catch{}}}catch{try{await yt.remove(n)}catch{}}if(!t)try{if(await yt.exists(Jt)){let s=(await yt.readFile(Jt,"utf8")).trim();s.startsWith("{")||s.startsWith("[")?t=JSON.parse(s):t=JSON.parse(Cs(s))}}catch{}let o=t;if(o){let s=o.stats||{...In},i={...In,...s};Array.isArray(i.imageCalls)||(i.imageCalls=[]);let a=o.history||{},r=Ms(a,e);if(Object.keys(a).length!==Object.keys(r).length&&(_s=!0),o.date===e)return{...o,stats:i,history:r};{let h=o.date,d=i,c={...r};return h&&(c[h]=d),{date:e,stats:{...In},history:Ms(c,e)}}}return{date:e,stats:{...In},history:{}}},ai=async()=>{if(!(!_s||!se))try{await yt.ensureDir(_r.dirname(Jt));let e=null;try{if(await yt.exists(Jt)){let s=(await yt.readFile(Jt,"utf8")).trim();s.startsWith("{")||s.startsWith("[")?e=JSON.parse(s):e=JSON.parse(Cs(s))}}catch{}if(e&&e.date===se.date&&e.stats){for(let s in se.stats)if(e.stats[s]!==void 0){if(Array.isArray(se.stats[s])){let i=Array.isArray(e.stats[s])?e.stats[s]:[],a=se.stats[s],r=new Map;for(let h of[...i,...a])h&&h.timestamp&&r.set(h.timestamp,h);se.stats[s]=Array.from(r.values())}else if(typeof se.stats[s]=="number")se.stats[s]=Math.max(se.stats[s],Number(e.stats[s])||0);else if(se.stats[s]&&typeof se.stats[s]=="object"){let i=e.stats[s]||{},a=se.stats[s];for(let r in i)if(typeof i[r]=="number")a[r]=Math.max(a[r]||0,i[r]);else if(i[r]&&typeof i[r]=="object"){a[r]||(a[r]={});for(let h in i[r])if(typeof i[r][h]=="number")a[r][h]=Math.max(a[r][h]||0,i[r][h]);else if(i[r][h]&&typeof i[r][h]=="object"){a[r][h]||(a[r][h]={});for(let d in i[r][h])a[r][h][d]=Math.max(a[r][h][d]||0,i[r][h][d])}}}}}if(e&&e.history){let s={...se.history||{}};for(let i in e.history)if(s[i])for(let a in s[i])if(a==="imageCalls"){let r=Array.isArray(e.history[i].imageCalls)?e.history[i].imageCalls:[],h=Array.isArray(s[i].imageCalls)?s[i].imageCalls:[],d=new Map;for(let c of[...r,...h])c&&c.timestamp&&d.set(c.timestamp,c);s[i].imageCalls=Array.from(d.values())}else typeof s[i][a]=="number"&&(s[i][a]=Math.max(s[i][a],Number(e.history[i][a])||0));else s[i]=e.history[i];se.history=Ms(s,se.date||today)}else if(se&&se.history){let s=new Date().toISOString().split("T")[0];se.history=Ms(se.history,s)}se.saveId=ol();let n=Jt+".tmp",t=Gs(JSON.stringify(se,null,2));await yt.writeFile(n,t,"utf8");let o=await yt.open(n,"r+");await yt.fsync(o),await yt.close(o),await yt.rename(n,Jt),_s=!1,Mr=Date.now()}catch{}},_o=()=>{if(_s=!0,Hn)return;let e=Date.now(),n=Math.max(0,1500-(e-Mr));Hn=setTimeout(async()=>{await ai(),Hn=null},n),Hn.unref&&Hn.unref()},Ad=async()=>{se=await Co(),_s&&_o()},vd=async()=>{Hn&&(clearTimeout(Hn),Hn=null),await ai()},Tn=async()=>{let e=new Date().toISOString().split("T")[0];if(!se)se=await Co();else if(se.date!==e){let n=se.date,t=se.stats,o=se.history||{};t&&(o[n]=t),se={date:e,stats:{...In},history:Ms(o,e)},_s=!0,await ai()}return se&&se.stats&&!Array.isArray(se.stats.imageCalls)&&(se.stats.imageCalls=[]),se.stats},il=async()=>{let e=new Date().toISOString().split("T")[0];se||(se=await Co()),se.date!==e&&await Tn();let n=se.history||{},t=Ms(n,e);se.history=t;let o=se.stats||{...In},s={...In};s.imageCalls=[],s.models={};let i=(a,r)=>{for(let h in a)if(h==="imageCalls")a.imageCalls=[...a.imageCalls||[],...r.imageCalls||[]];else if(h==="models"){let d=r.models||{};for(let c in d){a.models[c]||(a.models[c]={});for(let l in d[c]){a.models[c][l]||(a.models[c][l]={tokens:0,cachedTokens:0,candidateTokens:0});let u=a.models[c][l],f=d[c][l];u.tokens+=f.tokens||0,u.cachedTokens+=f.cachedTokens||0,u.candidateTokens+=f.candidateTokens||0}}}else typeof a[h]=="number"&&(a[h]+=r[h]||0)};i(s,o);for(let a in t)i(s,t[a]);return s},It=async(e,n)=>{e==="toolSuccess"?Js.toolSuccess++:e==="toolFailure"?Js.toolFailure++:e==="toolDenied"&&Js.toolDenied++;let t=await Tn();t[e]!==void 0&&t[e]++,n&&e==="agent"&&(t.providerRequests||(t.providerRequests={}),t.providerRequests[n]=(t.providerRequests[n]||0)+1),_o()},Js={linesAdded:0,linesRemoved:0,toolSuccess:0,toolFailure:0,toolDenied:0},Gt=async(e,n,t,o)=>{e==="linesAdded"?Js.linesAdded+=n:e==="linesRemoved"&&(Js.linesRemoved+=n);let s=await Tn();if(s[e]!==void 0&&(s[e]+=Math.floor(n)),t&&o&&(e==="tokens"||e==="cachedTokens"||e==="candidateTokens")){s.models||(s.models={}),s.models[t]||(s.models[t]={}),s.models[t][o]||(s.models[t][o]={tokens:0,cachedTokens:0,candidateTokens:0});let i=s.models[t][o];e==="tokens"&&(i.tokens+=Math.floor(n)),e==="cachedTokens"&&(i.cachedTokens+=Math.floor(n)),e==="candidateTokens"&&(i.candidateTokens+=Math.floor(n))}_o()},rl=async(e=1)=>{let n=new Date,t=n.toISOString().split("T")[0];se||(se=await Co()),se.date!==t&&await Tn();let o=n.getFullYear(),s=n.getMonth();n.getDate()<e&&(s-=1,s<0&&(s=11,o-=1));let r=new Date(o,s,e).toISOString().split("T")[0],h=se.history||{},d=se.stats||{...In},c={...In};c.imageCalls=[],c.models={};let l=(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>=r&&u<t&&l(c,h[u]);return c},li=async(e,n={})=>{let t=await Ft().catch(()=>({})),o=n.apiTier||t.apiTier||"Free",s=n.quotas||n.systemSettings?.quotas||t.quotas||{},i=s.providerBudgets||{},a=!!i.__useProvider,r=n.aiProvider||t.aiProvider||"Google",h=a&&!!i[r],d=()=>{if(h){let c=i[r];return{agentLimit:typeof c.agentLimit=="number"&&c.agentLimit>0?c.agentLimit:99999999,tokenLimit:typeof c.tokenLimit=="number"&&c.tokenLimit>0?c.tokenLimit:99999999999999,monthlyTokenLimit:typeof c.monthlyTokenLimit=="number"&&c.monthlyTokenLimit>0?c.monthlyTokenLimit:99999999999999}}return{agentLimit:s.agentLimit||99999999,tokenLimit:s.tokenLimit||99999999999999,monthlyTokenLimit:s.monthlyTokenLimit||99999999999999}};if(e==="agent"){let{agentLimit:c,tokenLimit:l,monthlyTokenLimit:u}=d(),f=await Tn(),p;s.resetMode==="Custom"?p=await rl(s.resetDay||1):p=await il();let g=0,y=0,m=0;if(h){g=f.providerRequests?.[r]||0;let w=f.models?.[r]||{};for(let S in w)y+=w[S]?.tokens||0;let x=p.models?.[r]||{};for(let S in x)m+=x[S]?.tokens||0}else g=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 ${r}`:"Daily Agent Request Limit Reached"}:y>=l?{allowed:!1,reason:h?`Daily Token Budget Exhausted for ${r}`:"Daily Token Budget Exhausted"}:m>=u?{allowed:!1,reason:h?`Monthly Token Budget Exhausted for ${r}`:"Monthly Token Budget Exhausted"}:{allowed:!0}}if(e==="background"){let c=await Tn();if(o==="Free"&&c.agent+c.background>=999999)return{allowed:!1,reason:"Free Tier Background Limit Exceeded"};let l=c.background<(s.backgroundLimit||999999);return{allowed:l,reason:l?void 0:"Background Request Limit Exceeded"}}if(e==="search"){let l=(await Tn()).search<(s.searchLimit||100);return{allowed:l,reason:l?void 0:"Search Quota Exceeded"}}return{allowed:!0}},Ar=async(e,n={})=>(await li(e,n)).allowed,ci=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},vr=(e,n)=>{if(!e||e.length===0)return .025;let o=ci(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 a=s[s.length-1].limit,r=a,h=s[s.length-1].ratio,d=i.end,c=0;for(let l=s.length-1;l>=0&&s[l].ratio>=.8;l--)c++;for(;d<=n;){let l=.025;c>=2?l=.015:h>=.8?l=r===.015?.015:r:h<.4?l=Math.min(.025,r+.005):h>=.4&&h<.6?l=Math.min(.025,r+.004):l=Math.min(.025,r+.002),r=l,h=0,c=0,d+=36e5,a=l}return a},Ir=async e=>{let n=e.imageSettings||{keyType:"Default",quality:"Low-High"};if(n.keyType!=="Default")return!0;let o={Low:.001,"Low-High":.002,Medium:.008,"Medium-High":.01,High:.045,Ultra:.0488,Premium:.15}[n.quality]||.002,s=await Tn();s.imageCalls||(s.imageCalls=[]);let i=Date.now(),a=ci(s.imageCalls),r=0;if(a.length>0){let d=a[a.length-1];i>=d.start&&i<d.end&&(r=d.spent)}let h=vr(s.imageCalls,i);return r+o<=h},Or=async()=>{let e=await Tn();e.imageCalls||(e.imageCalls=[]);let n=Date.now(),t=ci(e.imageCalls),o=[],s=0,i=0;if(t.length>0){let d=t[t.length-1];n>=d.start&&n<d.end&&(o=d.calls,s=d.spent,i=Math.max(0,Math.ceil((d.end-n)/(60*1e3))))}let a=vr(e.imageCalls,n),r=Math.max(0,a-s),h=s;return{totalSpent:s,remaining:r,activeCallsCount:o.length,nextResetMin:i,reclaimCost:h,limit:a}},Lr=async e=>{let n=e.imageSettings||{keyType:"Default",quality:"Low-High"},o={Low:.001,"Low-High":.002,Medium:.008,"Medium-High":.01,High:.045,Ultra:.0488,Premium:.1}[n.quality]||.002,s=await Tn();s.imageCalls||(s.imageCalls=[]),s.imageCalls.push({timestamp:Date.now(),cost:o}),_o()};import Fr from"puppeteer";import Nr from"fs";import Br from"path";import Pr from"os";import Xs from"path";import As from"fs";import{createRequire as al}from"module";import{fileURLToPath as ll}from"url";var cl=al(import.meta.url),Dr=Xs.dirname(ll(import.meta.url));function cs(){let e=Pr.platform(),n=Pr.arch(),t="",o="",s="";if(e==="win32")t=n==="x64"?"win64":"win32",o="chrome.exe",s=`chrome-${t}`;else if(e==="darwin"){t=n==="arm64"?"mac_arm":"mac";let a=n==="arm64"?"arm64":"x64";o="Google Chrome.app/Contents/MacOS/Google Chrome",s=`chrome-mac-${a}`}else if(e==="linux")t="linux",o="chrome",s="chrome-linux64";else return{};let i=Xs.resolve(Dr,"..","..",".puppeteerrc.cjs");if(As.existsSync(i)||(i=Xs.resolve(Dr,"..",".puppeteerrc.cjs")),!As.existsSync(i))return{};try{let a=cl(i),r=a.cacheDirectory,h=a.chrome?.version;if(r){if(process.env.PUPPETEER_CACHE_DIR=r,h){let l=Xs.join(r,"chrome",`${t}-${h}`,s,o);if(As.existsSync(l))return{executablePath:l,cacheDirectory:r}}let d=l=>{if(!As.existsSync(l))return null;try{let u=As.readdirSync(l),f=[];for(let p of u){let g=Xs.join(l,p),y;try{y=As.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(r);if(c)return{executablePath:c,cacheDirectory:r}}}catch{}return{}}var di=async e=>{let{query:n,limit:t=5,aiMode:o=!1}=O(e);if(!n)return'ERROR: Missing "query" argument for web_search.';let s=3,i=null;if(o){let a=`Query: ${n}
208
208
 
209
209
  RESPONSE RULES:
210
210
  - ANSWER CONCISELY WITH REQUIRED DETAILS UNDER 300 WORDS.
@@ -219,50 +219,50 @@ Sources:
219
219
 
220
220
  - LIST ONE RAW URL PER BULLET.
221
221
  - DO NOT USE MARKDOWN LINKS.
222
- - DO NOT INCLUDE ANY TEXT, NOTES, OR EXPLANATIONS AFTER THE SOURCES SECTION.`;for(let r=1;r<=s;r++){let h=null;try{let d=cs();h=await vr.launch({headless:!0,executablePath:d.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let c=await h.newPage();await c.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.178 Safari/537.36"),await c.setViewport({width:1366,height:768});let l=r===1?Math.random()*1e3+500:Math.random()*2e3+1e3;await new Promise(C=>setTimeout(C,l));let f=`https://search.brave.com/ask?q=${encodeURIComponent(a)}&source=web`;await c.goto(f,{waitUntil:"domcontentloaded",timeout:18e4});let u=null,p=45e3,g=Date.now();for(;Date.now()-g<p&&(u=await c.evaluate(()=>{let C=Array.from(document.querySelectorAll('.message:not(.user), .answer-text, .llm-content, [data-type="answer"]')),k="";if(C.length>0&&(k=C.map(oe=>oe.innerText.trim()).filter(Boolean).join(`
222
+ - DO NOT INCLUDE ANY TEXT, NOTES, OR EXPLANATIONS AFTER THE SOURCES SECTION.`;for(let r=1;r<=s;r++){let h=null;try{let d=cs();h=await Fr.launch({headless:!0,executablePath:d.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let c=await h.newPage();await c.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.178 Safari/537.36"),await c.setViewport({width:1366,height:768});let l=r===1?Math.random()*1e3+500:Math.random()*2e3+1e3;await new Promise(C=>setTimeout(C,l));let u=`https://search.brave.com/ask?q=${encodeURIComponent(a)}&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 C=Array.from(document.querySelectorAll('.message:not(.user), .answer-text, .llm-content, [data-type="answer"]')),b="";if(C.length>0&&(b=C.map(ie=>ie.innerText.trim()).filter(Boolean).join(`
223
223
 
224
- `)),k||(k=document.body.innerText),k.includes("anomaly"))throw new Error("ANOMALY_DETECTED");let O=!!document.querySelector('.spinner, .loading, .typing, .streaming, [data-streaming="true"], [data-state="loading"], svg.animate-spin, circle[cx], div[class*="spin"]'),v=C[0]||document.body,L=v?v.innerText.trim():"",N=/^(?:[✓✔]\s*)?Finished/i.test(L)||!!(v&&v.querySelector(".status-finished, .finished")),j=!O&&(N||k.includes("Sources:")&&!O),V={};return document.querySelectorAll("a[href]").forEach(oe=>{let Ie=oe.getAttribute("href")||oe.href||"";if(Ie.includes("uddg=")&&(Ie=decodeURIComponent(Ie.split("uddg=")[1].split("&")[0])),Ie.includes("url=")&&(Ie=decodeURIComponent(Ie.split("url=")[1].split("&")[0])),Ie&&(Ie.startsWith("http://")||Ie.startsWith("https://"))&&!Ie.includes("search.brave.com")){let B=oe.innerText.trim();B&&(V[B]=Ie),oe.textContent=Ie}}),{isFinished:j,text:k,hrefMap:V}}),!(u&&u.isFinished));)await new Promise(C=>setTimeout(C,1e3));let y=(u?u.text:"")||"",m=u?u.hrefMap||{}:{},w="DO NOT INCLUDE ANY TEXT, NOTES, OR EXPLANATIONS AFTER THE SOURCES SECTION.";y.includes(w)&&(y=y.split(w).pop()),y=y.replace(/^.*?(Ctrl \+ Shift \+ O|Ask\nAll\nImages)/s,"").replace(/AI-generated answer\. Please verify critical facts\..*/s,"").replace(/Brave Search uses private usage metrics.*/s,"");let x=y,S="";if(y.includes("Sources:")){let C=y.split("Sources:");x=C[0],S=C.slice(1).join("Sources:")}let R=[];for(let C of x.split(`
225
- `)){let k=C.trim();k&&(/^(View all|Finished|Searching|Answering|Thinking)$/i.test(k)||/^[\+\-]?\d+$/.test(k)||k.includes("search.brave.com")||k.startsWith("https://www.youtube.com/watch")||k.startsWith("https://youtube.com/watch")||R.push(C))}let E=R.join(`
224
+ `)),b||(b=document.body.innerText),b.includes("anomaly"))throw new Error("ANOMALY_DETECTED");let v=!!document.querySelector('.spinner, .loading, .typing, .streaming, [data-streaming="true"], [data-state="loading"], svg.animate-spin, circle[cx], div[class*="spin"]'),I=C[0]||document.body,D=I?I.innerText.trim():"",j=/^(?:[✓✔]\s*)?Finished/i.test(D)||!!(I&&I.querySelector(".status-finished, .finished")),U=!v&&(j||b.includes("Sources:")&&!v),Y={};return document.querySelectorAll("a[href]").forEach(ie=>{let _e=ie.getAttribute("href")||ie.href||"";if(_e.includes("uddg=")&&(_e=decodeURIComponent(_e.split("uddg=")[1].split("&")[0])),_e.includes("url=")&&(_e=decodeURIComponent(_e.split("url=")[1].split("&")[0])),_e&&(_e.startsWith("http://")||_e.startsWith("https://"))&&!_e.includes("search.brave.com")){let N=ie.innerText.trim();N&&(Y[N]=_e),ie.textContent=_e}}),{isFinished:U,text:b,hrefMap:Y}}),!(f&&f.isFinished));)await new Promise(C=>setTimeout(C,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,S="";if(y.includes("Sources:")){let C=y.split("Sources:");x=C[0],S=C.slice(1).join("Sources:")}let R=[];for(let C of x.split(`
225
+ `)){let b=C.trim();b&&(/^(View all|Finished|Searching|Answering|Thinking)$/i.test(b)||/^[\+\-]?\d+$/.test(b)||b.includes("search.brave.com")||b.startsWith("https://www.youtube.com/watch")||b.startsWith("https://youtube.com/watch")||R.push(C))}let E=R.join(`
226
226
  `).replace(/^(?:[\+\-]?\d+\s*)+/i,"").replace(/\n{3,}/g,`
227
227
 
228
- `).trim(),b=C=>!C||C.includes("search.brave.com")||C.includes("youtube.com")||C.includes("youtu.be"),T="";if(S){let C=S.match(/https?:\/\/[^\s\)\>]+/g)||[],k=[];for(let v of C){let L=v.replace(/[\.\,\;]+$/,""),N=Object.keys(m).find(j=>j.startsWith(L)||L.startsWith(j));N&&m[N]&&(L=m[N]),b(L)||k.push(L)}Object.values(m).forEach(v=>{!b(v)&&!k.includes(v)&&k.push(v)});let O=Array.from(new Set(k));O.length>0&&(T=`Sources:
229
- `+O.map(v=>`- ${v}`).join(`
228
+ `).trim(),k=C=>!C||C.includes("search.brave.com")||C.includes("youtube.com")||C.includes("youtu.be"),T="";if(S){let C=S.match(/https?:\/\/[^\s\)\>]+/g)||[],b=[];for(let I of C){let D=I.replace(/[\.\,\;]+$/,""),j=Object.keys(m).find(U=>U.startsWith(D)||D.startsWith(U));j&&m[j]&&(D=m[j]),k(D)||b.push(D)}Object.values(m).forEach(I=>{!k(I)&&!b.includes(I)&&b.push(I)});let v=Array.from(new Set(b));v.length>0&&(T=`Sources:
229
+ `+v.map(I=>`- ${I}`).join(`
230
230
  `))}let $=E+(T?`
231
231
 
232
232
  `+T:"");if(!$||/^(\+\d+|Searching|Answering|Thinking|Finished)$/i.test($))throw new Error("EMPTY_AI_RESPONSE");return await h.close(),`AI Search results for [${n}]:
233
233
 
234
- ${$}`}catch(d){if(i=d,Ir.writeFileSync(Or.join(cn,"web_tools","search","ai_mode","ERROR.txt"),d.message),h&&await h.close(),r<s){let c=Math.pow(2,r)*1e3;await new Promise(l=>setTimeout(l,c))}}}}for(let a=1;a<=s;a++){let r=null;try{let h=cs();r=await vr.launch({headless:!0,executablePath:h.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let d=await r.newPage();await d.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.178 Safari/537.36"),await d.setViewport({width:1366,height:768});let c=a===1?Math.random()*1e3+500:Math.random()*2e3+1e3;await new Promise(g=>setTimeout(g,c));let l=`https://html.duckduckgo.com/html/?q=${encodeURIComponent(n)}`;await d.goto(l,{waitUntil:"networkidle2",timeout:18e4});let f=await d.$$eval(".result",(g,y)=>g.slice(0,y).map((m,w)=>{let x=m.querySelector(".result__a"),S=m.querySelector(".result__snippet"),R=x?x.href:"";R.includes("uddg=")&&(R=decodeURIComponent(R.split("uddg=")[1].split("&")[0]));let E=x?x.innerText.trim():"No Title",b=S?S.innerText.trim():"No Snippet";return`${w+1}. ${E}
234
+ ${$}`}catch(d){if(i=d,Nr.writeFileSync(Br.join(cn,"web_tools","search","ai_mode","ERROR.txt"),d.message),h&&await h.close(),r<s){let c=Math.pow(2,r)*1e3;await new Promise(l=>setTimeout(l,c))}}}}for(let a=1;a<=s;a++){let r=null;try{let h=cs();r=await Fr.launch({headless:!0,executablePath:h.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let d=await r.newPage();await d.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.178 Safari/537.36"),await d.setViewport({width:1366,height:768});let c=a===1?Math.random()*1e3+500:Math.random()*2e3+1e3;await new Promise(g=>setTimeout(g,c));let l=`https://html.duckduckgo.com/html/?q=${encodeURIComponent(n)}`;await d.goto(l,{waitUntil:"networkidle2",timeout:18e4});let u=await d.$$eval(".result",(g,y)=>g.slice(0,y).map((m,w)=>{let x=m.querySelector(".result__a"),S=m.querySelector(".result__snippet"),R=x?x.href:"";R.includes("uddg=")&&(R=decodeURIComponent(R.split("uddg=")[1].split("&")[0]));let E=x?x.innerText.trim():"No Title",k=S?S.innerText.trim():"No Snippet";return`${w+1}. ${E}
235
235
  Source: ${R}
236
- Snippet: ${b}`}),t);if(f.length===0){if((await d.evaluate(()=>document.body.innerText)).includes("anomaly"))throw new Error("ANOMALY_DETECTED");return await r.close(),`No results found for query: [${n}].`}let u=f.join(`
236
+ Snippet: ${k}`}),t);if(u.length===0){if((await d.evaluate(()=>document.body.innerText)).includes("anomaly"))throw new Error("ANOMALY_DETECTED");return await r.close(),`No results found for query: [${n}].`}let f=u.join(`
237
237
 
238
238
  `);return await r.close(),`${o?`AI Mode temporarily failed, used Standard search.
239
239
 
240
240
  `:""}Search results for [${n}]:
241
241
 
242
- ${u}`}catch(h){if(i=h,r&&await r.close(),Ir.writeFileSync(Or.join(cn,"web_tools","search","standard_mode","ERROR.txt"),h.message),a<s){let d=Math.pow(2,a)*1e3;await new Promise(c=>setTimeout(c,d))}}}return`ERROR: Search failed after ${s+1} attempts. Last error: ${i.message}`};import ol from"puppeteer";import il from"turndown";import{gfm as rl}from"turndown-plugin-gfm";var ci=async e=>{let n=e;if(typeof e=="object"&&e!==null)n=e.url||e.targetUrl||e.href||"";else if(typeof e=="string"){let i=e.match(/url\s*=\s*["'](.*)["']/);n=i?i[1]:e}let t=typeof n=="string"?n.trim():"";if(!t)return"ERROR: No target URL provided.";let o=3,s=null;for(let i=1;i<=o;i++){let a=null;try{let r=cs();a=await ol.launch({headless:!0,executablePath:r.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let h=await a.newPage();await h.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.178 Safari/537.36"),await h.setViewport({width:1366,height:768});let d=i===1?Math.random()*1e3+500:Math.random()*2e3+1e3;await new Promise(g=>setTimeout(g,d)),await h.goto(t,{waitUntil:"networkidle2",timeout:18e4}),await new Promise(g=>setTimeout(g,5e3));let c=await h.evaluate(()=>{document.querySelectorAll("script, style, noscript, svg, canvas, iframe, ad, .ads, link, meta, img").forEach(S=>S.remove());let y=document.createNodeIterator(document.body,NodeFilter.SHOW_COMMENT),m;for(;m=y.nextNode();)m.remove();for(document.querySelectorAll("*").forEach(S=>{let R=S.attributes;for(let E=R.length-1;E>=0;E--){let b=R[E].name;b!=="href"&&b!=="src"&&S.removeAttribute(b)}});document.querySelector("div, span");)document.querySelectorAll("div, span").forEach(S=>{S.parentNode&&S.replaceWith(...S.childNodes)});document.querySelectorAll("br").forEach(S=>{S.replaceWith(document.createTextNode(`
242
+ ${f}`}catch(h){if(i=h,r&&await r.close(),Nr.writeFileSync(Br.join(cn,"web_tools","search","standard_mode","ERROR.txt"),h.message),a<s){let d=Math.pow(2,a)*1e3;await new Promise(c=>setTimeout(c,d))}}}return`ERROR: Search failed after ${s+1} attempts. Last error: ${i.message}`};import dl from"puppeteer";import fl from"turndown";import{gfm as ul}from"turndown-plugin-gfm";var fi=async e=>{let n=e;if(typeof e=="object"&&e!==null)n=e.url||e.targetUrl||e.href||"";else if(typeof e=="string"){let i=e.match(/url\s*=\s*["'](.*)["']/);n=i?i[1]:e}let t=typeof n=="string"?n.trim():"";if(!t)return"ERROR: No target URL provided.";let o=3,s=null;for(let i=1;i<=o;i++){let a=null;try{let r=cs();a=await dl.launch({headless:!0,executablePath:r.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let h=await a.newPage();await h.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.178 Safari/537.36"),await h.setViewport({width:1366,height:768});let d=i===1?Math.random()*1e3+500:Math.random()*2e3+1e3;await new Promise(g=>setTimeout(g,d)),await h.goto(t,{waitUntil:"networkidle2",timeout:18e4}),await new Promise(g=>setTimeout(g,5e3));let c=await h.evaluate(()=>{document.querySelectorAll("script, style, noscript, svg, canvas, iframe, ad, .ads, link, meta, img").forEach(S=>S.remove());let y=document.createNodeIterator(document.body,NodeFilter.SHOW_COMMENT),m;for(;m=y.nextNode();)m.remove();for(document.querySelectorAll("*").forEach(S=>{let R=S.attributes;for(let E=R.length-1;E>=0;E--){let k=R[E].name;k!=="href"&&k!=="src"&&S.removeAttribute(k)}});document.querySelector("div, span");)document.querySelectorAll("div, span").forEach(S=>{S.parentNode&&S.replaceWith(...S.childNodes)});document.querySelectorAll("br").forEach(S=>{S.replaceWith(document.createTextNode(`
243
243
 
244
244
  `))});let x=()=>{let S=!1;document.querySelectorAll("*").forEach(R=>{R.childNodes.length===0&&!R.innerText.trim()&&(R.remove(),S=!0)}),S&&x()};return x(),document.body.innerHTML});if(!c)throw new Error("EMPTY_RENDER_RESULT");let l=c.replace(/<br\s*\/?>/gi,`
245
245
 
246
246
  `).replace(/[ \t]+/g," ").replace(/>[ \t]+</g,"><").replace(/\n\s+/g,`
247
247
  `).replace(/\n{3,}/g,`
248
248
 
249
- `).trim(),f=new il({headingStyle:"atx",codeBlockStyle:"fenced"});f.use(rl);let u=f.turndown(l).replace(/\.\s*\n/g,`
249
+ `).trim(),u=new fl({headingStyle:"atx",codeBlockStyle:"fenced"});u.use(ul);let f=u.turndown(l).replace(/\.\s*\n/g,`
250
250
  `).replace(/ +/g," ").replace(/\t/g," ").replace(/\n\s+/g,`
251
251
  `).replace(/\n{3,}/g,`
252
252
 
253
- `),p=u.substring(0,5e4);return await a.close(),`Markdown parsed from [${t}]:
253
+ `),p=f.substring(0,5e4);return await a.close(),`Markdown parsed from [${t}]:
254
254
 
255
- ${p}${u.length>5e4?`
255
+ ${p}${f.length>5e4?`
256
256
 
257
- [TRUNCATED AT 50K CHARS]`:""}`}catch(r){if(s=r,a&&await a.close(),i<o){let h=Math.pow(2,i)*1e3;await new Promise(d=>setTimeout(d,h))}}}return`ERROR: Scrape failed after ${o+1} attempts. Last error: ${s.message}`};var al=4*(1024*2),di=async(e,n={})=>{let t=c=>{let l=new RegExp(`${c}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),f=e.match(l);if(f)return f[2].trim();let u=new RegExp(`${c}\\s*[:=]\\s*([^,\\s)]+)`,"s"),p=e.match(u);return p?p[1].trim():null},o=t("action"),s=t("method"),i=t("content"),a=t("content-new"),r=t("content-old"),h=t("id"),d=t("chat-id")||n.chatId||n.sessionId||"default-session";if(o==="temp"){if(!i)return"ERROR: Missing 'content' for temp memory.";let c=X(Xt,{});c[d]||(c[d]=[]),c[d].push(i),he(Xt,c);let l=c[d].reduce((f,u)=>f+u.length,0);return`SUCCESS: Temporary context saved for session [${d}]. (Size: ${l} chars)`}if(o==="user"){let c=X(Dt,[]).map(l=>(l.score===void 0&&(l.score=.5),l));if(s==="add"){if(!i)return"ERROR: Missing 'content' for memory addition.";let l=new Date,f=`${l.getDate()}/${l.getMonth()+1}/${l.getFullYear()}`,u=i.includes("[Saved on:")?i:`${i.trim()} [Saved on: ${f}]`,p=al,g=c.reduce((x,S)=>x+(S.memory?.length||0),0);for(;c.length>0&&g+u.length>p;){let x=c.shift();g-=x.memory?.length||0}let y=t("score"),m=y?parseFloat(y):.5,w={id:`mem-${Date.now().toString(36)}`,memory:u,score:Math.min(2,isNaN(m)?.5:m)};return c.push(w),he(Dt,c),`SUCCESS: Memory added with ID [${w.id}] and score [${w.score}]. (Vault Size: ${g+u.length} chars)`}if(s==="update"){let l=h||r,f=a||i;if(!l||!f)return"ERROR: Missing 'id' or content for update.";let u=c.findIndex(m=>m.id===l);if(u===-1)return`ERROR: Memory ID [${l}] not found.`;let p=new Date,g=`${p.getDate()}/${p.getMonth()+1}/${p.getFullYear()}`,y=f.includes("[Saved on:")?f:`${f.trim()} [Saved on: ${g}]`;return c[u].memory=y,he(Dt,c),`SUCCESS: Memory [${l}] updated.`}if(s==="delete"){let l=h||i;if(!l)return"ERROR: Missing 'id' for deletion.";let f=c.length,u=c.filter(p=>p.id!==l);return u.length===f?`ERROR: Memory ID [${l}] not found.`:(he(Dt,u),`SUCCESS: Memory [${l}] deleted.`)}return`ERROR: Invalid method [${s}] for user memory. Use 'add', 'update', or 'delete'.`}return`ERROR: Unknown action [${o}] for memory tool.`};var fi=async(e,n={})=>{let t=I(e).title,o=n.chatId||n.sessionId;if(!o)return"ERROR: No active chatId found in tool context.";if(!t)return"ERROR: Missing 'title' argument.";try{return await br(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 Lr from"path";var Qs=async(e,n={})=>{let{path:t,StartLine:o,EndLine:s,start_line:i,end_line:a,startLine:r,endLine:h}=I(e),d=parseInt(o||i||r),c=parseInt(s||a||h),l=!isNaN(d),f=!isNaN(c),u=d||1,p=c||(d?d+800:800);if(!t)return'ERROR: Missing "path" argument for view_file.';let g=Lr.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=Lr.extname(t).toLowerCase();if([".mp4",".mkv",".avi",".mov",".webm",".flv",".wmv",".mpeg",".mpg"].includes(m))return`ERROR: Unable to read. Type ${m.slice(1).toUpperCase()} not supported`;let x={".pdf":"application/pdf",".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".webp":"image/webp",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".doc":"application/msword"};if(x[m]){if(!(n.isMultiModal!==!1))return`ERROR: Multimodality is not supported for the current model. Unable to load [${t}].`;let L=Co.readFileSync(g).toString("base64"),N=x[m];return{text:`[BINARY FILE]: ${t} (${N}) - Loaded as multimodal part.`,binaryPart:{inlineData:{data:L,mimeType:N}}}}let S=Co.readFileSync(g,"utf8");S.startsWith("\uFEFF")&&(S=S.slice(1)),S=S.replace(/\r\n/g,`
257
+ [TRUNCATED AT 50K CHARS]`:""}`}catch(r){if(s=r,a&&await a.close(),i<o){let h=Math.pow(2,i)*1e3;await new Promise(d=>setTimeout(d,h))}}}return`ERROR: Scrape failed after ${o+1} attempts. Last error: ${s.message}`};var hl=4*(1024*2),ui=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"),a=t("content-new"),r=t("content-old"),h=t("id"),d=t("chat-id")||n.chatId||n.sessionId||"default-session";if(o==="temp"){if(!i)return"ERROR: Missing 'content' for temp memory.";let c=X(Xt,{});c[d]||(c[d]=[]),c[d].push(i),he(Xt,c);let l=c[d].reduce((u,f)=>u+f.length,0);return`SUCCESS: Temporary context saved for session [${d}]. (Size: ${l} chars)`}if(o==="user"){let c=X(Dt,[]).map(l=>(l.score===void 0&&(l.score=.5),l));if(s==="add"){if(!i)return"ERROR: Missing 'content' for memory addition.";let l=new Date,u=`${l.getDate()}/${l.getMonth()+1}/${l.getFullYear()}`,f=i.includes("[Saved on:")?i:`${i.trim()} [Saved on: ${u}]`,p=hl,g=c.reduce((x,S)=>x+(S.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),he(Dt,c),`SUCCESS: Memory added with ID [${w.id}] and score [${w.score}]. (Vault Size: ${g+f.length} chars)`}if(s==="update"){let l=h||r,u=a||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,he(Dt,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.`:(he(Dt,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 hi=async(e,n={})=>{let t=O(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 $r(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 Mo from"fs";import Ur from"path";var Qs=async(e,n={})=>{let{path:t,StartLine:o,EndLine:s,start_line:i,end_line:a,startLine:r,endLine:h}=O(e),d=parseInt(o||i||r),c=parseInt(s||a||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=Ur.resolve(process.cwd(),t);try{if(!Mo.existsSync(g))return`ERROR: File [${t}] does not exist.`;if(Mo.statSync(g).isDirectory())return`ERROR: Path [${t}] is a directory. Use list_files instead.`;let m=Ur.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 D=Mo.readFileSync(g).toString("base64"),j=x[m];return{text:`[BINARY FILE]: ${t} (${j}) - Loaded as multimodal part.`,binaryPart:{inlineData:{data:D,mimeType:j}}}}let S=Mo.readFileSync(g,"utf8");S.startsWith("\uFEFF")&&(S=S.slice(1)),S=S.replace(/\r\n/g,`
258
258
  `).replace(/\r/g,`
259
259
  `);let R=S.split(`
260
- `),E=R.length;!l&&!f&&E>800&&(u=1,p=50);let b=Math.max(0,u-1),T=Math.min(E,p),$=R.slice(b,T),C=`File: [${t}] (Showing lines ${b+1}-${T} of ${E}).`,k=$.map((O,v)=>`${String(b+v+1).padStart(4)}: ${O.trimEnd()}`).join(`
260
+ `),E=R.length;!l&&!u&&E>800&&(f=1,p=50);let k=Math.max(0,f-1),T=Math.min(E,p),$=R.slice(k,T),C=`File: [${t}] (Showing lines ${k+1}-${T} of ${E}).`,b=$.map((v,I)=>`${String(k+I+1).padStart(4)}: ${v.trimEnd()}`).join(`
261
261
  `);return`${C}
262
262
 
263
- ${k}`}catch(y){let m=y instanceof Error?y.message:String(y);return`ERROR: Failed to read file [${t}]: ${m}`}};import vs from"fs";import Pr from"path";var ui=async(e,n={})=>{let{path:t,content:o}=I(e);if(!t)return'ERROR: Missing "path" argument for write_file.';if(o===void 0)return'ERROR: Missing "content" argument for write_file.';o=o.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
263
+ ${b}`}catch(y){let m=y instanceof Error?y.message:String(y);return`ERROR: Failed to read file [${t}]: ${m}`}};import vs from"fs";import Wr from"path";var pi=async(e,n={})=>{let{path:t,content:o}=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
264
  `).replace(/\r/g,`
265
- `);let s=Pr.resolve(process.cwd(),t),i=Pr.dirname(s);try{await ft.recordFileChange(s);let a="";if(vs.existsSync(s))try{a=`Old File contents:
265
+ `);let s=Wr.resolve(process.cwd(),t),i=Wr.dirname(s);try{await ft.recordFileChange(s);let a="";if(vs.existsSync(s))try{a=`Old File contents:
266
266
  ${vs.readFileSync(s,"utf8").split(/\r?\n/).map((R,E)=>`${E+1} | ${R}`).join(`
267
267
  `)}
268
268
 
@@ -272,15 +272,15 @@ ${vs.readFileSync(s,"utf8").split(/\r?\n/).map((R,E)=>`${E+1} | ${R}`).join(`
272
272
  `).replace(/\r/g,`
273
273
  `))(o),d=h.endsWith(`
274
274
  `)?h:h+`
275
- `,c=d.split(/\r?\n/).length,l=Buffer.byteLength(d,"utf8");vs.writeFileSync(s,d,"utf8");let f=vs.readFileSync(s,"utf8"),u=Buffer.byteLength(f,"utf8"),p=f.split(/\r?\n/),g=p.length;if(u===0&&l>0)return f=null,`ERROR: CRITICAL FAILURE: Verification failed. File [${t}] is empty on disk!`;let y="";if(g<=100)y=p.join(`
275
+ `,c=d.split(/\r?\n/).length,l=Buffer.byteLength(d,"utf8");vs.writeFileSync(s,d,"utf8");let u=vs.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
276
  `);else{let x=p.slice(0,50).join(`
277
277
  `),S=p.slice(-50).join(`
278
278
  `);y=`${x}
279
279
 
280
280
  ... [${g-100} lines truncated] ...
281
281
 
282
- ${S}`}f=null;let{systemSettings:m}=await Ft(),w=`SUCCESS: File [${t}] saved.
283
- - Stats: [${g} lines, ${(u/1024).toFixed(1)} KB]
282
+ ${S}`}u=null;let{systemSettings:m}=await Ft(),w=`SUCCESS: File [${t}] saved.
283
+ - Stats: [${g} lines, ${(f/1024).toFixed(1)} KB]
284
284
  ${a}- Content Preview:
285
285
 
286
286
  ${y}`;if(m?.compressToolResults&&g>60){let x=d.split(/\r?\n/),S=x.slice(0,25).join(`
@@ -288,81 +288,81 @@ ${y}`;if(m?.compressToolResults&&g>60){let x=d.split(/\r?\n/),S=x.slice(0,25).jo
288
288
  `),R=x.slice(-25).join(`
289
289
  `)===p.slice(-25).join(`
290
290
  `);S&&R&&(w=`[[SAME]]
291
- ${w}`)}return w}catch(a){let r=a instanceof Error?a.message:String(a);return`ERROR: Failed to write file [${t}]: ${r}`}};import gi from"fs";import xl from"path";import ll from"os";var hn=e=>typeof e!="string"?e:e.length>12?(e+"").replace("",""):e,Dr=(e,n)=>{if(!e)return"";let t=/\x1B\[[0-?]*[ -/]*[@-~]/g,o=e.split(`
292
- `),s=[];if(n<=5)return e;let i=a=>a.replace(t,"").length;return o.forEach(a=>{if(i(a)<=n){s.push(a);return}let h=a.split(/(\s+)/),d="",c=0,l=a.match(/^(\s*)/),f=l?l[1]:"";h.forEach((u,p)=>{if(u.length===0)return;let g=i(u);if(c+g>n)if(d.trim().length>0)s.push(d.trimEnd()),d=f.substring(0,Math.min(f.length,8))+u,c=i(d);else if(t.test(u))s.push(u),d=f,c=i(d);else{let y=u;for(;i(y)>n&&n>10;)s.push(y.substring(0,n)),y=y.substring(n);d=y,c=i(d)}else d+=u,c+=g}),(d.trimEnd().length>0||d===f)&&s.push(d.trimEnd())}),hn(s.join(`
293
- `))},ff=e=>{if(!e&&e!==0)return"0.0k";let n=typeof e=="string"?parseFloat(e):e;return n>=1e6?`${(n/1e6).toFixed(1)}m`:n>=1e3?`${(n/1e3).toFixed(1)}k`:n.toString()},uf=(e,n=40)=>{let t=An.replaceAll("\\\\","\\");if(e=e.replace(ll.homedir(),"~").replace(t,"FluxFlow").replaceAll("\\","/"),!e||e.length<=n)return hn(e);let o=Math.floor((n-3)/2);return hn(e.substring(0,o)+"..."+e.substring(e.length-o).replaceAll("\\","/"))},_o=e=>{let n=[],t=new Set,o=e.allowMultiple===!0||String(e.allowMultiple).toLowerCase()==="true";Object.keys(e).forEach(h=>{let d=h.match(/^(searchContent|search_content|replaceContent|replace_content|newContent|new_content|content_to_replace|content_to_add|searchBlock|search_block|newBlock|new_block)_?(\d+)?$/i);if(d){let c=d[2]?parseInt(d[2],10):1;t.add(c)}});let s=Array.from(t).sort((h,d)=>h-d),i=["searchContent","search_content","replaceContent","replace_content","content_to_replace","searchBlock","search_block"],a=["newContent","new_content","content_to_add","newBlock","new_block"],r=(h,d,c)=>{let l,f;for(let u of d){let p=h===1?[`${u}1`,u,`${u}_1`]:[`${u}${h}`,`${u}_${h}`];for(let g of p)if(e[g]!==void 0){l=e[g];break}if(l!==void 0)break}for(let u of c){let p=h===1?[`${u}1`,u,`${u}_1`]:[`${u}${h}`,`${u}_${h}`];for(let g of p)if(e[g]!==void 0){f=e[g];break}if(f!==void 0)break}return{r:l,n:f}};for(let h of s){let{r:d,n:c}=r(h,i,a);if(d!==void 0&&c!==void 0)n.push({replace:d,new:c});else if(d!==void 0||c!==void 0)return{error:`Mismatched replacement pair for index ${h}. Both replacement and new content must be provided.`,allowMultiple:o}}return{patchPairs:n,allowMultiple:o}},cl=e=>{if(!e)return null;let n="",t=0,o=e.length;for(;t<o;){let s=e[t];if(s==="\\"){for(;t<o&&e[t]==="\\";)t++;n+="\\\\*"}else if(s===`
291
+ ${w}`)}return w}catch(a){let r=a instanceof Error?a.message:String(a);return`ERROR: Failed to write file [${t}]: ${r}`}};import wi from"fs";import El from"path";import pl from"os";var hn=e=>typeof e!="string"?e:e.length>12?(e+"").replace("",""):e,jr=(e,n)=>{if(!e)return"";let t=/\x1B\[[0-?]*[ -/]*[@-~]/g,o=e.split(`
292
+ `),s=[];if(n<=5)return e;let i=a=>a.replace(t,"").length;return o.forEach(a=>{if(i(a)<=n){s.push(a);return}let h=a.split(/(\s+)/),d="",c=0,l=a.match(/^(\s*)/),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
+ `))},wf=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()},xf=(e,n=40)=>{let t=An.replaceAll("\\\\","\\");if(e=e.replace(pl.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"],a=["newContent","new_content","content_to_add","newBlock","new_block"],r=(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}=r(h,i,a);if(d!==void 0&&c!==void 0)n.push({replace:d,new:c});else if(d!==void 0||c!==void 0)return{error:`Mismatched replacement pair for index ${h}. Both replacement and new content must be provided.`,allowMultiple:o}}return{patchPairs:n,allowMultiple:o}},ml=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
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}},Mo=(e,n,t={})=>{let o=typeof t=="boolean"?t:!!(t&&t.allowMultiple),s=e.replace(/\r\n/g,`
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}},vo=(e,n,t={})=>{let o=typeof t=="boolean"?t:!!(t&&t.allowMultiple),s=e.replace(/\r\n/g,`
296
296
  `).replace(/\r/g,`
297
297
  `),i=m=>m.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
298
298
  `).replace(/\r/g,`
299
299
  `),a=m=>m.match(/^\s*/)[0],r=m=>{let w=m.split(`
300
- `).filter(S=>S.trim()!=="");if(w.length===0)return"";let x=a(w[0]);for(let S of w){let R=a(S);R.length<x.length&&(x=R)}return x},h=(m,w,x="")=>{if(!m||w===void 0)return m;let R=/^\t/m.test(w)?" ":" ",E=O=>O.split(`
301
- `).find(v=>v.trim()!=="")??"",b=E(w).match(/^\s*/)[0].length,T=E(m).match(/^\s*/)[0].length,$=b-T,C=(x.match(/^\s*/)||[""])[0].length;return m.split(`
302
- `).map((O,v)=>{if(O.trim()===""&&v!==0)return"";let L=O.match(/^\s*/)[0].length,N=Math.max(0,L+$);return v===0&&(N=Math.max(0,N-C)),R.repeat(N)+O.trimStart()}).join(`
303
- `)},d=[];for(let m=0;m<n.length;m++){let w=n[m],x=(w.replace||"").trim(),S=i(w.new||"");if(x.startsWith("^LINE:")&&x.endsWith("$")){let C=x.slice(6,-1).trim().split(".."),k=parseInt(C[0]),O=C[1]!==void 0?parseInt(C[1]):k;if(!isNaN(k)&&!isNaN(O)){let v=s.split(`
304
- `);if(k<1||k>v.length||O<k||O>v.length){d.push({index:m,success:!1,error:`Block ${m+1}: Line range ^LINE:${k}..${O}$ out of bounds (file has ${v.length} lines).`});continue}let N=v.slice(k-1,O).join(`
305
- `),j=0;for(let V=0;V<k-1;V++)j+=v[V].length+1;d.push({index:m,success:!0,startPos:j,firstMatchContent:N,content_to_add:S});continue}}let R=i(w.replace||"");if(R===""&&S===""){d.push({index:m,success:!1,error:`Block ${m+1}: Empty replace and add content.`});continue}let E=R.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),b=null;if(R!==""&&s.includes(R))b=new RegExp(E,"g");else{let $=R.split(`
306
- `).map(C=>C.trim()).filter(C=>C.length>0).map(C=>C.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\s+/g,"\\s*"));if($.length>0){let C=$.join("\\s*");try{b=new RegExp(C,"g")}catch{b=new RegExp(E,"g")}}else b=new RegExp(E,"g")}let T=[...s.matchAll(b)];if(T.length===0&&R!==""){let $=cl(R);$&&(T=[...s.matchAll($)])}if(T.length===0){d.push({index:m,success:!1,error:`Block ${m+1}: Could not find match.`});continue}if(T.length>1&&!o){d.push({index:m,success:!1,error:`Block ${m+1}: Found ${T.length} matches (must be unique or use allowMultiple: true if sure).`});continue}for(let $ of T)d.push({index:m,success:!0,startPos:$.index,firstMatchContent:$[0],content_to_add:S})}let c=d.filter(m=>m.success).sort((m,w)=>m.startPos-w.startPos);for(let m=0;m<c.length-1;m++){let w=c[m],x=c[m+1];w.startPos+w.firstMatchContent.length>x.startPos&&(w.success=!1,w.error=`Block ${w.index+1}: Overlaps with another block.`,x.success=!1,x.error=`Block ${x.index+1}: Overlaps with another block.`)}let l=new Map,f=s,u=0,p=0,g=d.filter(m=>m.success).sort((m,w)=>m.startPos-w.startPos);for(let m of g){let w=m.startPos,x=s.substring(0,w).split(`
307
- `).length,S=w+u,R=x+p,E=f.lastIndexOf(`
308
- `,S)+1,b=f.substring(E,S),T=h(m.content_to_add,m.firstMatchContent,b),$=f.split(`
309
- `),C=[];for(let L=Math.max(0,R-4);L<R-1;L++)C.push({num:L+1,text:$[L]});let k=m.firstMatchContent.split(`
310
- `),O=[],v=R+k.length-1;for(let L=v;L<Math.min($.length,v+3);L++)O.push({num:L+1,text:$[L]});l.set(m,{success:!0,index:m.index,oldContent:m.firstMatchContent,newContent:T,originalStartLine:x,finalStartLine:R,contextBefore:C,contextAfter:O}),f=f.substring(0,S)+T+f.substring(S+m.firstMatchContent.length),u+=T.length-m.firstMatchContent.length,p+=T.split(`
300
+ `).filter(S=>S.trim()!=="");if(w.length===0)return"";let x=a(w[0]);for(let S of w){let R=a(S);R.length<x.length&&(x=R)}return x},h=(m,w,x="")=>{if(!m||w===void 0)return m;let R=/^\t/m.test(w)?" ":" ",E=v=>v.split(`
301
+ `).find(I=>I.trim()!=="")??"",k=E(w).match(/^\s*/)[0].length,T=E(m).match(/^\s*/)[0].length,$=k-T,C=(x.match(/^\s*/)||[""])[0].length;return m.split(`
302
+ `).map((v,I)=>{if(v.trim()===""&&I!==0)return"";let D=v.match(/^\s*/)[0].length,j=Math.max(0,D+$);return I===0&&(j=Math.max(0,j-C)),R.repeat(j)+v.trimStart()}).join(`
303
+ `)},d=[];for(let m=0;m<n.length;m++){let w=n[m],x=(w.replace||"").trim(),S=i(w.new||"");if(x.startsWith("^LINE:")&&x.endsWith("$")){let C=x.slice(6,-1).trim().split(".."),b=parseInt(C[0]),v=C[1]!==void 0?parseInt(C[1]):b;if(!isNaN(b)&&!isNaN(v)){let I=s.split(`
304
+ `);if(b<1||b>I.length||v<b||v>I.length){d.push({index:m,success:!1,error:`Block ${m+1}: Line range ^LINE:${b}..${v}$ out of bounds (file has ${I.length} lines).`});continue}let j=I.slice(b-1,v).join(`
305
+ `),U=0;for(let Y=0;Y<b-1;Y++)U+=I[Y].length+1;d.push({index:m,success:!0,startPos:U,firstMatchContent:j,content_to_add:S});continue}}let R=i(w.replace||"");if(R===""&&S===""){d.push({index:m,success:!1,error:`Block ${m+1}: Empty replace and add content.`});continue}let E=R.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),k=null;if(R!==""&&s.includes(R))k=new RegExp(E,"g");else{let $=R.split(`
306
+ `).map(C=>C.trim()).filter(C=>C.length>0).map(C=>C.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\s+/g,"\\s*"));if($.length>0){let C=$.join("\\s*");try{k=new RegExp(C,"g")}catch{k=new RegExp(E,"g")}}else k=new RegExp(E,"g")}let T=[...s.matchAll(k)];if(T.length===0&&R!==""){let $=ml(R);$&&(T=[...s.matchAll($)])}if(T.length===0){d.push({index:m,success:!1,error:`Block ${m+1}: Could not find match.`});continue}if(T.length>1&&!o){d.push({index:m,success:!1,error:`Block ${m+1}: Found ${T.length} matches (must be unique or use allowMultiple: true if sure).`});continue}for(let $ of T)d.push({index:m,success:!0,startPos:$.index,firstMatchContent:$[0],content_to_add:S})}let c=d.filter(m=>m.success).sort((m,w)=>m.startPos-w.startPos);for(let m=0;m<c.length-1;m++){let w=c[m],x=c[m+1];w.startPos+w.firstMatchContent.length>x.startPos&&(w.success=!1,w.error=`Block ${w.index+1}: Overlaps with another block.`,x.success=!1,x.error=`Block ${x.index+1}: Overlaps with another block.`)}let l=new Map,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,S=w+f,R=x+p,E=u.lastIndexOf(`
308
+ `,S)+1,k=u.substring(E,S),T=h(m.content_to_add,m.firstMatchContent,k),$=u.split(`
309
+ `),C=[];for(let D=Math.max(0,R-4);D<R-1;D++)C.push({num:D+1,text:$[D]});let b=m.firstMatchContent.split(`
310
+ `),v=[],I=R+b.length-1;for(let D=I;D<Math.min($.length,I+3);D++)v.push({num:D+1,text:$[D]});l.set(m,{success:!0,index:m.index,oldContent:m.firstMatchContent,newContent:T,originalStartLine:x,finalStartLine:R,contextBefore:C,contextAfter:v}),u=u.substring(0,S)+T+u.substring(S+m.firstMatchContent.length),f+=T.length-m.firstMatchContent.length,p+=T.split(`
311
311
  `).length-m.firstMatchContent.split(`
312
- `).length}let y=[];for(let m=0;m<n.length;m++){let w=g.filter(x=>x.index===m);if(w.length>0)for(let x of w)l.has(x)&&y.push(l.get(x));else{let x=d.find(S=>S.index===m);y.push({success:!1,error:x?x.error:`Block ${m+1}: Unknown error.`})}}return{content:f,results:y}},Ao=(e,n,t,o=8,s=!1)=>{if(!t||t.length===0)return"";let i=e.split(/\r?\n/),a=n.split(/\r?\n/),r=Math.max(i.length,a.length,1),h=Math.max(4,String(r).length),d=g=>String(g).padStart(h," "),c=`[DIFF_START]
313
- `,l="\u2550".repeat(88),f=0,u=null,p=t.filter(g=>g.success).sort((g,y)=>g.originalStartLine-y.originalStartLine);if(p.forEach((g,y)=>{let m=g.finalStartLine!==void 0?g.finalStartLine:g.originalStartLine;if(u===null)for(f=Math.max(0,m-4);f<m-1;)c+=`[UI_CONTEXT] ${d(f+1)} |${a[f]||""}
314
- `,f++;else{let T=u,$=T.originalStartLine+T.oldContent.split(`
315
- `).length-1;if(g.originalStartLine-$-1>=o){let k=Math.min(a.length,f+3);for(;f<k;)c+=`[UI_CONTEXT] ${d(f+1)} |${a[f]||""}
316
- `,f++;for(c+=`[UI_CONTEXT] ${l}
317
- `,f=Math.max(f,m-4);f<m-1;)c+=`[UI_CONTEXT] ${d(f+1)} |${a[f]||""}
318
- `,f++}else for(;f<m-1;)c+=`[UI_CONTEXT] ${d(f+1)} |${a[f]||""}
319
- `,f++}let w=g.originalStartLine-1,x=i[w]||"",S=g.oldContent.split(`
320
- `),R=x.match(/^\s*/),E=R?R[0]:"";S.forEach((T,$)=>{let C=T;if(S.length===1&&x.trim().length>0&&x.includes(T.trim()))C=x;else if($===0){let k=T.match(/^\s*/);(k?k[0]:"").length<E.length&&x.includes(T.trim())&&(C=E+T.trimStart())}c+=`-${d(g.originalStartLine+$)} |${C}
321
- `});let b=f;if(g.finalStartLine!==void 0)b=g.finalStartLine-1+(g.newContent?g.newContent.split(`
322
- `).length:0);else{let T=g.originalStartLine+S.length-1,$=i[T]||null;if($!==null){let C=y<p.length-1?(p[y+1].originalStartLine||a.length)+10:a.length;for(let k=f;k<C;k++){if(a[k]===$){b=k;break}k===a.length-1&&(b=a.length)}}else b=a.length}for(;f<b;)c+=`+${d(f+1)} |${a[f]||""}
323
- `,f++;u=g}),u!==null){let g=Math.min(a.length,f+3);for(;f<g;)c+=`[UI_CONTEXT] ${d(f+1)} |${a[f]||""}
324
- `,f++}if(s){let g=`[DIFF_START]
312
+ `).length}let y=[];for(let m=0;m<n.length;m++){let w=g.filter(x=>x.index===m);if(w.length>0)for(let x of w)l.has(x)&&y.push(l.get(x));else{let x=d.find(S=>S.index===m);y.push({success:!1,error:x?x.error:`Block ${m+1}: Unknown error.`})}}return{content:u,results:y}},Io=(e,n,t,o=8,s=!1)=>{if(!t||t.length===0)return"";let i=e.split(/\r?\n/),a=n.split(/\r?\n/),r=Math.max(i.length,a.length,1),h=Math.max(4,String(r).length),d=g=>String(g).padStart(h," "),c=`[DIFF_START]
313
+ `,l="\u2550".repeat(88),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)} |${a[u]||""}
314
+ `,u++;else{let T=f,$=T.originalStartLine+T.oldContent.split(`
315
+ `).length-1;if(g.originalStartLine-$-1>=o){let b=Math.min(a.length,u+3);for(;u<b;)c+=`[UI_CONTEXT] ${d(u+1)} |${a[u]||""}
316
+ `,u++;for(c+=`[UI_CONTEXT] ${l}
317
+ `,u=Math.max(u,m-4);u<m-1;)c+=`[UI_CONTEXT] ${d(u+1)} |${a[u]||""}
318
+ `,u++}else for(;u<m-1;)c+=`[UI_CONTEXT] ${d(u+1)} |${a[u]||""}
319
+ `,u++}let w=g.originalStartLine-1,x=i[w]||"",S=g.oldContent.split(`
320
+ `),R=x.match(/^\s*/),E=R?R[0]:"";S.forEach((T,$)=>{let C=T;if(S.length===1&&x.trim().length>0&&x.includes(T.trim()))C=x;else if($===0){let b=T.match(/^\s*/);(b?b[0]:"").length<E.length&&x.includes(T.trim())&&(C=E+T.trimStart())}c+=`-${d(g.originalStartLine+$)} |${C}
321
+ `});let k=u;if(g.finalStartLine!==void 0)k=g.finalStartLine-1+(g.newContent?g.newContent.split(`
322
+ `).length:0);else{let T=g.originalStartLine+S.length-1,$=i[T]||null;if($!==null){let C=y<p.length-1?(p[y+1].originalStartLine||a.length)+10:a.length;for(let b=u;b<C;b++){if(a[b]===$){k=b;break}b===a.length-1&&(k=a.length)}}else k=a.length}for(;u<k;)c+=`+${d(u+1)} |${a[u]||""}
323
+ `,u++;f=g}),f!==null){let g=Math.min(a.length,u+3);for(;u<g;)c+=`[UI_CONTEXT] ${d(u+1)} |${a[u]||""}
324
+ `,u++}if(s){let g=`[DIFF_START]
325
325
  `,y=c.substring(g.length),m=`[UI_CONTEXT] ${l}
326
326
  `,x=y.split(m).map(S=>S.split(`
327
327
  `).filter(E=>E.trim()!=="").length>45?`[[VERIFIED]]
328
328
  ${S}
329
- [[/VERIFIED]]`:S);c=g+x.join(m)}return c+="[DIFF_END]",hn(c)},dl=e=>{if(!e)return null;let n=e.replace("[UI_CONTEXT]","").replace(/\r/g,""),t=n.startsWith("-"),o=n.startsWith("+"),s=t||o?n.substring(1):n,i=s.indexOf("|"),a=i!==-1?hn(s.substring(0,i).trim()):"",r=hn(i!==-1?s.substring(i+1):s);return{isR:t,isA:o,num:a,content:r}},fl=(e,n)=>{if(!e&&!n)return 1;if(!e||!n)return 0;let t=e.length,o=n.length,s=e,i=n;t<o&&(s=n,i=e);let a=s.length,r=i.length,h=new Int32Array(r+1),d=new Int32Array(r+1);for(let f=0;f<=r;f++)h[f]=f;for(let f=1;f<=a;f++){d[0]=f;let u=s[f-1];for(let p=1;p<=r;p++)u===i[p-1]?d[p]=h[p-1]:d[p]=Math.min(h[p],d[p-1],h[p-1])+1;h.set(d)}let c=h[r],l=Math.max(t,o);return l===0?1:1-c/l},Fr=e=>{let n=[],t=[];e.forEach((c,l)=>{c.parsed.isR?n.push({index:l,content:c.parsed.content}):c.parsed.isA&&t.push({index:l,content:c.parsed.content})});let o=n.length,s=t.length;if(o===0||s===0)return;let i=Array.from({length:o+1},()=>Array(s+1).fill(0)),a=Array.from({length:o+1},()=>Array(s+1).fill(""));for(let c=1;c<=o;c++)a[c][0]="up";for(let c=1;c<=s;c++)a[0][c]="left";let r=Array.from({length:o},()=>Array(s).fill(0));for(let c=0;c<o;c++)for(let l=0;l<s;l++)r[c][l]=fl(n[c].content.trim(),t[l].content.trim());for(let c=1;c<=o;c++)for(let l=1;l<=s;l++){let f=r[c-1][l-1],u=f>=.2?f:-10,p=i[c-1][l-1]+u,g=i[c-1][l],y=i[c][l-1];p>=g&&p>=y?(i[c][l]=p,a[c][l]="diag"):g>=y?(i[c][l]=g,a[c][l]="up"):(i[c][l]=y,a[c][l]="left")}let h=o,d=s;for(;h>0||d>0;)if(a[h][d]==="diag"){if(r[h-1][d-1]>=.2){let l=n[h-1].index,f=t[d-1].index;e[l].pairContent=e[f].parsed.content,e[f].pairContent=e[l].parsed.content}h--,d--}else a[h][d]==="up"?h--:d--},Gn=new Map,ds=new Map,Nr=200,hi=6,mi=(e,n)=>{n.set(e.key,e),e.type==="chunk"&&e.blocks&&e.blocks.forEach(t=>mi(t,n))},hf=(e,n)=>{if(!e)return{completed:[],active:[]};let t=`${e.id}-${e.text?.length||0}-${n}-${e.isStreaming}-${e.workedDuration||0}`;if(!e.isStreaming&&Gn.has(t))return Gn.get(t);let o=hn(wl(e.text||"",e.role==="think")),s=`${e.id}-${n}`,i=new Map;if(e.isStreaming){let p=ds.get(s);p&&o.startsWith(p.text)&&(i=p.blocksMap)}let a=(p,g,y,m={})=>{let w=i.get(p);if(w&&w.text===y&&w.type===g&&!!w.isActiveBlock==!!m.isActiveBlock&&!!w.isStreaming==!!m.isStreaming&&w.pairContent===m.pairContent)return w;let x=hn(y),S={...m};return typeof S.pairContent=="string"&&(S.pairContent=hn(S.pairContent)),Array.isArray(S.wrappedLines)&&(S.wrappedLines=S.wrappedLines.map(hn)),{key:p,isStreamingMsg:!!e.isStreaming,workedDuration:e.workedDuration,type:g,text:x,msg:g==="full-message"?e:void 0,...S}};if(o.includes("- Content Preview:")){let p="",g=o.match(/File\s+\[(.*?)\]/i);g&&(p=g[1].split(".").pop().toLowerCase());let S=((o.split("- Content Preview:")[1]||"").split("[SYSTEM] Check the content preview for verification [/SYSTEM]")[0]?.trim()||"").split(`
330
- `).map(k=>k.replace(/\r$/,"")),R=String(S.length).length,E=[],b=null,T=[],$=()=>{if(!T.length)return;let k=T;T=[],E.push(k.length===1?k[0]:{key:`${k[0].key}-chunk`,type:"chunk",blocks:k})},C=n-(R+6);return S.forEach((k,O)=>{let v=O===S.length-1,L=Dr(k,C).split(`
331
- `),N=a(`${e.id||Date.now()}-write-line-${O}`,"write-line",k,{gutterWidth:R,lineNum:O+1,isFirstLine:O===0,isLastLine:v,extension:p,wrappedLines:L});v&&e.isStreaming?($(),b=N):(T.push(N),T.length>=hi&&$())}),$(),{completed:E,active:b?[b]:[]}}if(o.includes("[DIFF_START]")){let p=o.match(/\[DIFF_START\]([\s\S]*?)(?:\[DIFF_END\]|$)/),y=(p?p[1].trim():"").split(`
332
- `).map(b=>b.replace(/\r$/,"")),m=y.map(b=>({line:b,parsed:dl(b),pairContent:null})),w=[];for(let b=0;b<m.length;b++){let T=m[b];T.parsed&&(T.parsed.isR||T.parsed.isA)?w.push(T):w.length>0&&(Fr(w),w=[])}w.length>0&&Fr(w);let x=[],S=null,R=[],E=()=>{if(!R.length)return;let b=R;R=[],x.push(b.length===1?b[0]:{key:`${b[0].key}-chunk`,type:"chunk",blocks:b})};return y.forEach((b,T)=>{let $=T===y.length-1,C=m[T].parsed,k=null;C&&(k=Dr(C.content,n-17).split(`
333
- `));let O=a(`${e.id||Date.now()}-diff-${T}`,"diff-line",b,{isFirstLine:T===0,isLastLine:$,pairContent:m[T].pairContent,wrappedLines:k});$&&e.isStreaming?(E(),S=O):(R.push(O),R.length>=hi&&E())}),E(),{completed:x,active:S?[S]:[]}}if(e.role==="system"||e.isLogo||e.isHelpRecord||e.isTerminalRecord||e.isHomeWarning||e.isImageStats||e.isAskRecord||e.isAboutRecord||e.isUpdateNotification||e.role==="user")return{completed:[a(`${e.id||Date.now()}-full`,"full-message",o)],active:[]};if(!o&&!e.isStreaming){let p={completed:[],active:[]};return Gn.set(t,p),p}let r=[],h=null,d=[],c=null,l=()=>{if(!d.length)return;let p=d;d=[],c=null,r.push(p.length===1?p[0]:{key:`${e.id||"x"}-chunk-${p[0].key}`,type:"chunk",blocks:p})},f=(p,g=!1)=>{if(c!==null&&c!==p.type&&l(),d.push(p),c=p.type,d.length>=hi){if(e.isStreaming&&g)return;l()}};if(e.role==="think"){r.push(a(`${e.id}-header`,"think-header",""));let p=o.split(`
334
- `);p.forEach((g,y)=>{let m=y===p.length-1;f(a(`${e.id}-${y}`,"think-line",g,{}),m)}),e.isStreaming||(l(),r.push({key:`${e.id}-footer-padding`,type:"think-footer-padding",text:""}))}else{let p=o.split(`
335
- `),g=!1,y=[],m=!1,w=!1,x="",S=0,R=0;p.forEach((E,b)=>{let T=b===p.length-1,$=E.trim().startsWith("|"),C=E.trim().startsWith("```");if(w){if(E.includes("</think>")||E.includes("<channel|>")||E.includes("</thought>")){let k=E.split(/(?:<\/(think|thought|thoughts)>|<channel\|>)/i),O=k[0]||"",v=k.slice(2).join("");O&&f(a(`${e.id}-think-${b}`,"think-line",O,{}),T&&!v),l(),r.push({key:`${e.id}-think-footer-${b}`,type:"think-footer-padding",text:""}),w=!1,v&&v.trim()&&f(a(`${e.id}-${b}`,"agent-line",v,{}),T)}else f(a(`${e.id}-think-${b}`,"think-line",E,{}),T);return}if(!m&&(E.includes("<think>")||E.includes("<|channel>thought")||E.includes("<thought>")||E.startsWith("<think")||E.startsWith("<|channel>thought"))){l(),g&&(r.push(a(`${e.id}-table-${b}`,"table",y.join(`
336
- `),{isStreaming:!1})),g=!1,y=[]),r.push(a(`${e.id}-think-header-${b}`,"think-header","")),w=!0;let k=E.replace(/^(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought\s*)\r?\n?/i,"");if(k.includes("</think>")||k.includes("<channel|>")||k.includes("</thought>")){let O=k.split(/(?:<\/(think|thought|thoughts)>|<channel\|>)/i),v=O[0]||"",L=O.slice(2).join("");v&&f(a(`${e.id}-think-${b}`,"think-line",v,{}),T&&!L),l(),r.push({key:`${e.id}-think-footer-${b}`,type:"think-footer-padding",text:""}),w=!1,L&&L.trim()&&f(a(`${e.id}-${b}`,"agent-line",L,{}),T)}else k&&f(a(`${e.id}-think-${b}`,"think-line",k,{}),T);return}m?C?(m=!1,f(a(`${e.id}-code-close-${R}`,"code-fence-close","",{}),T)):(S++,f(a(`${e.id}-code-line-${b}`,"code-line",E,{lineNum:S,lang:x}),T)):C?(m=!0,R=b,S=0,x=E.trim().replace(/^```/,"").trim(),f(a(`${e.id}-code-open-${b}`,"code-fence-open",x,{}),T)):$?(g=!0,y.push(E),T&&(l(),e.isStreaming?h=a(`${e.id}-table-${b}`,"table",y.join(`
337
- `),{isStreaming:!0}):r.push(a(`${e.id}-table-${b}`,"table",y.join(`
338
- `),{isStreaming:!1})))):(g&&(l(),r.push(a(`${e.id}-table-${b}`,"table",y.join(`
339
- `),{isStreaming:!1})),g=!1,y=[]),f(a(`${e.id}-${b}`,"agent-line",E,{}),T))}),!e.isStreaming&&e.workedDuration&&(l(),r.push(a(`${e.id}-worked-duration`,"worked-duration","")))}e.isStreaming&&d.length>0?h=d.length===1?d[0]:{key:`${e.id||"x"}-chunk-active-${d[0].key}`,type:"chunk",blocks:d}:l();let u={completed:r,active:h?[h]:[]};if(e.isStreaming){let p=new Map;if(r.forEach(g=>mi(g,p)),h&&mi(h,p),ds.set(s,{text:o,blocksMap:p}),ds.size>Nr){let g=ds.keys().next().value;ds.delete(g)}}else{if(Gn.set(t,u),Gn.size>Nr){let p=Gn.keys().next().value;Gn.delete(p)}ds.delete(s)}return u},ul={},hl=/<\/think>(\r?\n){2}/gi,pl=/(\r?\n){2}(?=\[?(?:tool:functions|tool\.functions|agent:generalist|agent\.generalist|\s*turn\s*:))/gi,pi=(e,n)=>{let t=!1;for(let o=0;o<n;o++)e[o]==="`"&&(t=!t);return t},ml=/\[SYSTEM\][\s\S]*?\[\/SYSTEM\]|(?:<(think|thought|thoughts)>|<\|channel>thought)[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>)|\[ANSWER\][\s\S]*?(?:\[\/ANSWER\]|$)|\[TOOL RESULT\]:?\s*|^\s*(SUCCESS|ERROR):.*(\r?\n)?|\[\s*turn\s*:\s*(continue|finish)\s*\]|\[\[END\]\]|\[\s*turn\s*:?.*?$|\n\s*turn\s*:?.*?$|\[\s*(?:turn|ANSWER|TOOL).*?$|\n\nResponded on .*|\n\n\[Prompted on: .*\]|@\[TerminalName:.*?, ProcessId:.*?\]/gm,gl=/(\$?\\?\/?\\rightarrow\$?|\$\\rightarrow\$)|(\$?\\?\/?\\leftarrow\$?|\$\\leftarrow\$)|(\$?\\?\/?\\uparrow\$?|\$\\uparrow\$)|(\$?\\?\/?\\downarrow\$?|\$\\downarrow\$)|(\$?\\?\/?\\leftrightarrow\$?|\$\\leftrightarrow\$)/gi,yl=/\b(write_file|update_file|read_folder|view_file|exec_command|web_search|web_scrape|search_keyword|write_pdf|write_docx|generate_image)\b/gi,Is=!1,wl=(e,n=!1)=>{if(!e)return e;let t=e.replace(/<\|channel>thought/gi,"<think>").replace(/<channel\|>/gi,"</think>");if(n)return t.replace(/^<(think|thought|thoughts)>/gi,"").replace(/<\/(think|thought|thoughts)>$/gi,"").replace(/^\r?\n+/,"").replace(/\r?\n+$/,"");let o=t.replace(hl,"</think>").replace(pl,(a,r,h,d)=>!Is&&pi(d,h)?a:"");o&&o.includes("[tool:")&&(o=o.replace(/<(\w+)(?:[^>]*)>\s*([\s\S]*?\[tool:[^\]]*\][\s\S]*?)\s*<\/\1>/gi,(a,r,h)=>h&&h.includes("[tool:")?h.trim():a),Is&&(o=o.replace(/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi,(a,r)=>r.includes("[tool:")?r.trim():a)),o=o.replace(/<(\w+)(?:[^>]*)>\r?\n?/gi,"").replace(/\r?\n?<\/\w+(?:[^>]*)>/gi,""));let s="tool:functions.",i="agent:generalist.";if(o.toLowerCase().includes(s)||o.toLowerCase().includes(i))for(;;){let a=o.toLowerCase(),r=a.indexOf(s),h=a.indexOf(i),d=s,c=r;if((r===-1||h!==-1&&h<r)&&(d=i,c=h),c===-1)break;if(!Is&&pi(o,c)){let w=c+d.length,x=a.indexOf(s,w),S=a.indexOf(i,w);if(x===-1&&S===-1)break;let R=-1,E=0;for(;;){let b=a.indexOf(s,E),T=a.indexOf(i,E),$=-1,C=s;if(b===-1&&T===-1)break;if(b===-1||T!==-1&&T<b?($=T,C=i):$=b,!pi(o,$)){R=$,d=C;break}E=$+C.length}if(R===-1)break;c=R}let l=c,f=!1,u=c-1;for(;u>=0&&/\s/.test(o[u]);)u--;u>=0&&o[u]==="["&&(l=u,f=!0);let p=0,g=!1,y=null,m=c;for(;m<o.length;){let w=o[m];if(!y&&(w==="'"||w==='"'||w==="`")?y=w:y&&w===y&&o[m-1]!=="\\"&&(y=null),y||(w==="("?(p++,g=!0):w===")"&&p--),g&&p===0&&!y){let x=m;if(f){let S=m+1;for(;S<o.length&&/\s/.test(o[S]);)S++;S<o.length&&o[S]==="]"&&(x=S)}o=o.substring(0,l)+o.substring(x+1);break}if(m++,m===o.length)return o=o.substring(0,l),o}}return o=o.replace(ml,""),o=o.replace(gl,a=>{let r=a.toLowerCase();return r.includes("leftrightarrow")?"\u2194":r.includes("rightarrow")?"\u2192":r.includes("leftarrow")?"\u2190":r.includes("uparrow")?"\u2191":r.includes("downarrow")?"\u2193":a}),o=o.replace(yl,a=>ul[a.toLowerCase()]||a),o.trim()},pf=()=>{Gn.clear(),ds.clear()};var yi=async(e,n={})=>{let t=I(e),o=t.path;if(!o)return'ERROR: Missing "path" argument for PatchFile.';let{patchPairs:s,allowMultiple:i,error:a}=_o(t);if(a)return`ERROR: ${a}`;if(s.length===0)return"ERROR: No valid replacement pairs found. Use searchContent1, newContent1, etc.";let r=t.allowMultiple!==void 0?t.allowMultiple===!0||String(t.allowMultiple).toLowerCase()==="true":i,h=xl.resolve(process.cwd(),o);try{if(!gi.existsSync(h))return`ERROR: File [${o}] does not exist. Use WriteFile instead.`;let d=n.forcedContent||gi.readFileSync(h,"utf8");d.startsWith("\uFEFF")&&(d=d.slice(1));let c=d.replace(/\r\n/g,`
329
+ [[/VERIFIED]]`:S);c=g+x.join(m)}return c+="[DIFF_END]",hn(c)},gl=e=>{if(!e)return null;let n=e.replace("[UI_CONTEXT]","").replace(/\r/g,""),t=n.startsWith("-"),o=n.startsWith("+"),s=t||o?n.substring(1):n,i=s.indexOf("|"),a=i!==-1?hn(s.substring(0,i).trim()):"",r=hn(i!==-1?s.substring(i+1):s);return{isR:t,isA:o,num:a,content:r}},yl=(e,n)=>{if(!e&&!n)return 1;if(!e||!n)return 0;let t=e.length,o=n.length,s=e,i=n;t<o&&(s=n,i=e);let a=s.length,r=i.length,h=new Int32Array(r+1),d=new Int32Array(r+1);for(let u=0;u<=r;u++)h[u]=u;for(let u=1;u<=a;u++){d[0]=u;let f=s[u-1];for(let p=1;p<=r;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[r],l=Math.max(t,o);return l===0?1:1-c/l},Hr=e=>{let n=[],t=[];e.forEach((c,l)=>{c.parsed.isR?n.push({index:l,content:c.parsed.content}):c.parsed.isA&&t.push({index:l,content:c.parsed.content})});let o=n.length,s=t.length;if(o===0||s===0)return;let i=Array.from({length:o+1},()=>Array(s+1).fill(0)),a=Array.from({length:o+1},()=>Array(s+1).fill(""));for(let c=1;c<=o;c++)a[c][0]="up";for(let c=1;c<=s;c++)a[0][c]="left";let r=Array.from({length:o},()=>Array(s).fill(0));for(let c=0;c<o;c++)for(let l=0;l<s;l++)r[c][l]=yl(n[c].content.trim(),t[l].content.trim());for(let c=1;c<=o;c++)for(let l=1;l<=s;l++){let u=r[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,a[c][l]="diag"):g>=y?(i[c][l]=g,a[c][l]="up"):(i[c][l]=y,a[c][l]="left")}let h=o,d=s;for(;h>0||d>0;)if(a[h][d]==="diag"){if(r[h-1][d-1]>=.2){let l=n[h-1].index,u=t[d-1].index;e[l].pairContent=e[u].parsed.content,e[u].pairContent=e[l].parsed.content}h--,d--}else a[h][d]==="up"?h--:d--},Gn=new Map,ds=new Map,Gr=200,mi=6,yi=(e,n)=>{n.set(e.key,e),e.type==="chunk"&&e.blocks&&e.blocks.forEach(t=>yi(t,n))},bf=(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(Rl(e.text||"",e.role==="think")),s=`${e.id}-${n}`,i=new Map;if(e.isStreaming){let p=ds.get(s);p&&o.startsWith(p.text)&&(i=p.blocksMap)}let a=(p,g,y,m={})=>{let w=i.get(p);if(w&&w.text===y&&w.type===g&&!!w.isActiveBlock==!!m.isActiveBlock&&!!w.isStreaming==!!m.isStreaming&&w.pairContent===m.pairContent)return w;let x=hn(y),S={...m};return typeof S.pairContent=="string"&&(S.pairContent=hn(S.pairContent)),Array.isArray(S.wrappedLines)&&(S.wrappedLines=S.wrappedLines.map(hn)),{key:p,isStreamingMsg:!!e.isStreaming,workedDuration:e.workedDuration,type:g,text:x,msg:g==="full-message"?e:void 0,...S}};if(o.includes("- Content Preview:")){let p="",g=o.match(/File\s+\[(.*?)\]/i);g&&(p=g[1].split(".").pop().toLowerCase());let S=((o.split("- Content Preview:")[1]||"").split("[SYSTEM] Check the content preview for verification [/SYSTEM]")[0]?.trim()||"").split(`
330
+ `).map(b=>b.replace(/\r$/,"")),R=String(S.length).length,E=[],k=null,T=[],$=()=>{if(!T.length)return;let b=T;T=[],E.push(b.length===1?b[0]:{key:`${b[0].key}-chunk`,type:"chunk",blocks:b})},C=n-(R+6);return S.forEach((b,v)=>{let I=v===S.length-1,D=jr(b,C).split(`
331
+ `),j=a(`${e.id||Date.now()}-write-line-${v}`,"write-line",b,{gutterWidth:R,lineNum:v+1,isFirstLine:v===0,isLastLine:I,extension:p,wrappedLines:D});I&&e.isStreaming?($(),k=j):(T.push(j),T.length>=mi&&$())}),$(),{completed:E,active:k?[k]:[]}}if(o.includes("[DIFF_START]")){let p=o.match(/\[DIFF_START\]([\s\S]*?)(?:\[DIFF_END\]|$)/),y=(p?p[1].trim():"").split(`
332
+ `).map(k=>k.replace(/\r$/,"")),m=y.map(k=>({line:k,parsed:gl(k),pairContent:null})),w=[];for(let k=0;k<m.length;k++){let T=m[k];T.parsed&&(T.parsed.isR||T.parsed.isA)?w.push(T):w.length>0&&(Hr(w),w=[])}w.length>0&&Hr(w);let x=[],S=null,R=[],E=()=>{if(!R.length)return;let k=R;R=[],x.push(k.length===1?k[0]:{key:`${k[0].key}-chunk`,type:"chunk",blocks:k})};return y.forEach((k,T)=>{let $=T===y.length-1,C=m[T].parsed,b=null;C&&(b=jr(C.content,n-17).split(`
333
+ `));let v=a(`${e.id||Date.now()}-diff-${T}`,"diff-line",k,{isFirstLine:T===0,isLastLine:$,pairContent:m[T].pairContent,wrappedLines:b});$&&e.isStreaming?(E(),S=v):(R.push(v),R.length>=mi&&E())}),E(),{completed:x,active:S?[S]:[]}}if(e.role==="system"||e.isLogo||e.isHelpRecord||e.isTerminalRecord||e.isHomeWarning||e.isImageStats||e.isAskRecord||e.isAboutRecord||e.isUpdateNotification||e.role==="user")return{completed:[a(`${e.id||Date.now()}-full`,"full-message",o)],active:[]};if(!o&&!e.isStreaming){let p={completed:[],active:[]};return Gn.set(t,p),p}let r=[],h=null,d=[],c=null,l=()=>{if(!d.length)return;let p=d;d=[],c=null,r.push(p.length===1?p[0]:{key:`${e.id||"x"}-chunk-${p[0].key}`,type:"chunk",blocks:p})},u=(p,g=!1)=>{if(c!==null&&c!==p.type&&l(),d.push(p),c=p.type,d.length>=mi){if(e.isStreaming&&g)return;l()}};if(e.role==="think"){r.push(a(`${e.id}-header`,"think-header",""));let p=o.split(`
334
+ `);p.forEach((g,y)=>{let m=y===p.length-1;u(a(`${e.id}-${y}`,"think-line",g,{}),m)}),e.isStreaming||(l(),r.push({key:`${e.id}-footer-padding`,type:"think-footer-padding",text:""}))}else{let p=o.split(`
335
+ `),g=!1,y=[],m=!1,w=!1,x="",S=0,R=0;p.forEach((E,k)=>{let T=k===p.length-1,$=E.trim().startsWith("|"),C=E.trim().startsWith("```");if(w){if(E.includes("</think>")||E.includes("<channel|>")||E.includes("</thought>")){let b=E.split(/(?:<\/(think|thought|thoughts)>|<channel\|>)/i),v=b[0]||"",I=b.slice(2).join("");v&&u(a(`${e.id}-think-${k}`,"think-line",v,{}),T&&!I),l(),r.push({key:`${e.id}-think-footer-${k}`,type:"think-footer-padding",text:""}),w=!1,I&&I.trim()&&u(a(`${e.id}-${k}`,"agent-line",I,{}),T)}else u(a(`${e.id}-think-${k}`,"think-line",E,{}),T);return}if(!m&&(E.includes("<think>")||E.includes("<|channel>thought")||E.includes("<thought>")||E.startsWith("<think")||E.startsWith("<|channel>thought"))){l(),g&&(r.push(a(`${e.id}-table-${k}`,"table",y.join(`
336
+ `),{isStreaming:!1})),g=!1,y=[]),r.push(a(`${e.id}-think-header-${k}`,"think-header","")),w=!0;let b=E.replace(/^(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought\s*)\r?\n?/i,"");if(b.includes("</think>")||b.includes("<channel|>")||b.includes("</thought>")){let v=b.split(/(?:<\/(think|thought|thoughts)>|<channel\|>)/i),I=v[0]||"",D=v.slice(2).join("");I&&u(a(`${e.id}-think-${k}`,"think-line",I,{}),T&&!D),l(),r.push({key:`${e.id}-think-footer-${k}`,type:"think-footer-padding",text:""}),w=!1,D&&D.trim()&&u(a(`${e.id}-${k}`,"agent-line",D,{}),T)}else b&&u(a(`${e.id}-think-${k}`,"think-line",b,{}),T);return}m?C?(m=!1,u(a(`${e.id}-code-close-${R}`,"code-fence-close","",{}),T)):(S++,u(a(`${e.id}-code-line-${k}`,"code-line",E,{lineNum:S,lang:x}),T)):C?(m=!0,R=k,S=0,x=E.trim().replace(/^```/,"").trim(),u(a(`${e.id}-code-open-${k}`,"code-fence-open",x,{}),T)):$?(g=!0,y.push(E),T&&(l(),e.isStreaming?h=a(`${e.id}-table-${k}`,"table",y.join(`
337
+ `),{isStreaming:!0}):r.push(a(`${e.id}-table-${k}`,"table",y.join(`
338
+ `),{isStreaming:!1})))):(g&&(l(),r.push(a(`${e.id}-table-${k}`,"table",y.join(`
339
+ `),{isStreaming:!1})),g=!1,y=[]),u(a(`${e.id}-${k}`,"agent-line",E,{}),T))}),!e.isStreaming&&e.workedDuration&&(l(),r.push(a(`${e.id}-worked-duration`,"worked-duration","")))}e.isStreaming&&d.length>0?h=d.length===1?d[0]:{key:`${e.id||"x"}-chunk-active-${d[0].key}`,type:"chunk",blocks:d}:l();let f={completed:r,active:h?[h]:[]};if(e.isStreaming){let p=new Map;if(r.forEach(g=>yi(g,p)),h&&yi(h,p),ds.set(s,{text:o,blocksMap:p}),ds.size>Gr){let g=ds.keys().next().value;ds.delete(g)}}else{if(Gn.set(t,f),Gn.size>Gr){let p=Gn.keys().next().value;Gn.delete(p)}ds.delete(s)}return f},wl={},xl=/<\/think>(\r?\n){2}/gi,bl=/(\r?\n){2}(?=\[?(?:tool:functions|tool\.functions|agent:generalist|agent\.generalist|\s*turn\s*:))/gi,gi=(e,n)=>{let t=!1;for(let o=0;o<n;o++)e[o]==="`"&&(t=!t);return t},Sl=/\[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,kl=/(\$?\\?\/?\\rightarrow\$?|\$\\rightarrow\$)|(\$?\\?\/?\\leftarrow\$?|\$\\leftarrow\$)|(\$?\\?\/?\\uparrow\$?|\$\\uparrow\$)|(\$?\\?\/?\\downarrow\$?|\$\\downarrow\$)|(\$?\\?\/?\\leftrightarrow\$?|\$\\leftrightarrow\$)/gi,Tl=/\b(write_file|update_file|read_folder|view_file|exec_command|web_search|web_scrape|search_keyword|write_pdf|write_docx|generate_image)\b/gi,Is=!1,Rl=(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(xl,"</think>").replace(bl,(a,r,h,d)=>!Is&&gi(d,h)?a:"");o&&o.includes("[tool:")&&(o=o.replace(/<(\w+)(?:[^>]*)>\s*([\s\S]*?\[tool:[^\]]*\][\s\S]*?)\s*<\/\1>/gi,(a,r,h)=>h&&h.includes("[tool:")?h.trim():a),Is&&(o=o.replace(/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi,(a,r)=>r.includes("[tool:")?r.trim():a)),o=o.replace(/<(\w+)(?:[^>]*)>\r?\n?/gi,"").replace(/\r?\n?<\/\w+(?:[^>]*)>/gi,""));let s="tool:functions.",i="agent:generalist.";if(o.toLowerCase().includes(s)||o.toLowerCase().includes(i))for(;;){let a=o.toLowerCase(),r=a.indexOf(s),h=a.indexOf(i),d=s,c=r;if((r===-1||h!==-1&&h<r)&&(d=i,c=h),c===-1)break;if(!Is&&gi(o,c)){let w=c+d.length,x=a.indexOf(s,w),S=a.indexOf(i,w);if(x===-1&&S===-1)break;let R=-1,E=0;for(;;){let k=a.indexOf(s,E),T=a.indexOf(i,E),$=-1,C=s;if(k===-1&&T===-1)break;if(k===-1||T!==-1&&T<k?($=T,C=i):$=k,!gi(o,$)){R=$,d=C;break}E=$+C.length}if(R===-1)break;c=R}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 S=m+1;for(;S<o.length&&/\s/.test(o[S]);)S++;S<o.length&&o[S]==="]"&&(x=S)}o=o.substring(0,l)+o.substring(x+1);break}if(m++,m===o.length)return o=o.substring(0,l),o}}return o=o.replace(Sl,""),o=o.replace(kl,a=>{let r=a.toLowerCase();return r.includes("leftrightarrow")?"\u2194":r.includes("rightarrow")?"\u2192":r.includes("leftarrow")?"\u2190":r.includes("uparrow")?"\u2191":r.includes("downarrow")?"\u2193":a}),o=o.replace(Tl,a=>wl[a.toLowerCase()]||a),o.trim()},Sf=()=>{Gn.clear(),ds.clear()};var xi=async(e,n={})=>{let t=O(e),o=t.path;if(!o)return'ERROR: Missing "path" argument for PatchFile.';let{patchPairs:s,allowMultiple:i,error:a}=Ao(t);if(a)return`ERROR: ${a}`;if(s.length===0)return"ERROR: No valid replacement pairs found. Use searchContent1, newContent1, etc.";let r=t.allowMultiple!==void 0?t.allowMultiple===!0||String(t.allowMultiple).toLowerCase()==="true":i,h=El.resolve(process.cwd(),o);try{if(!wi.existsSync(h))return`ERROR: File [${o}] does not exist. Use WriteFile instead.`;let d=n.forcedContent||wi.readFileSync(h,"utf8");d.startsWith("\uFEFF")&&(d=d.slice(1));let c=d.replace(/\r\n/g,`
340
340
  `).replace(/\r/g,`
341
- `),{content:l,results:f}=Mo(c,s,{allowMultiple:r}),u=f.filter(m=>!m.success),p=f.filter(m=>m.success);if(p.length===0)return`ERROR: Patch Failed to apply to [${o}].
342
- ${u.map(m=>` \u2022 ${m.error}`).join(`
343
- `)}`;await ft.recordFileChange(h,c),gi.writeFileSync(h,l,"utf8");let{systemSettings:g}=await Ft(),y=Ao(c,l,f,12,g?.compressToolResults);return u.length>0?`SUCCESS: File [${o}] updated with some blocks failed. [${p.length}/${s.length}] blocks applied.
341
+ `),{content:l,results:u}=vo(c,s,{allowMultiple:r}),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),wi.writeFileSync(h,l,"utf8");let{systemSettings:g}=await Ft(),y=Io(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
344
 
345
345
  Failures:
346
- ${u.map(m=>` \u2022 ${m.error}`).join(`
346
+ ${f.map(m=>` \u2022 ${m.error}`).join(`
347
347
  `)}
348
348
 
349
- ${y}`:`SUCCESS: File [${o}] updated. [${f.length}/${s.length}] blocks applied.
349
+ ${y}`:`SUCCESS: File [${o}] updated. [${u.length}/${s.length}] blocks applied.
350
350
 
351
- ${y}`}catch(d){let c=d instanceof Error?d.message:String(d);return`ERROR: Failed to update file [${o}]: ${c}`}};import fs from"fs";import wi from"path";var bl=new Set([".git","node_modules",".gemini","dist","build",".next","out",".cache","bin","obj","vendor","venv",".idea",".gradle",".terraform","target","coverage",".vscode",".svn",".hg",".fslckout",".github",".gitlab",".circleci",".gitea",".gitee",".lerna",".changeset",".nx",".npm",".yarn",".pnpm-store",".expo",".nuxt",".svelte-kit",".docusaurus",".turbo",".vercel","bower_components",".netlify",".vuepress",".quasar",".output",".angular","jspm_packages",".parcel-cache",".rollup.cache",".rspack",".vitepress","__pycache__",".pytest_cache",".mypy_cache",".tox",".poetry","env","vhdl",".ipynb_checkpoints",".jupyter",".conda",".pdm-build",".bundle",".yardoc",".metadata","App_Data","ClientBin",".cargo",".rustc_info",".go","Godeps","_vendor",".rake_tasks","CMakefiles",".wakatime",".dart_tool",".fvm",".cocoapods","Pods",".pub-cache",".symlinks","DerivedData",".xcworkspace",".serverless",".aws",".gcloud",".azure",".kube",".vagrant",".docker","postgres-data","redis-data","mongo-data",".Spotlight-V100",".Trashes","$RECYCLE.BIN","System Volume Information",".DocumentRevisions-V100",".fseventsd","AppData","Application Data","Local","LocalLow","Roaming","$WinREAgent","$WINDOWS.~BT","$WINDOWS.~WS","scw","System32","SysWOW64",".AppleDouble",".AppleDB",".AppleDesktop","_CodeSignature",".cmio",".LSOverride",".localized",".TemporaryItems",".Trash",".Trash-0",".Trash-1000",".gvfs",".local",".config",".dbus",".fontconfig",".snap",".var",".lost+found","lost+found",".thumb",".thumbnails","EFI","boot","grub","logs","log",".nyc_output",".sonar",".ruff_cache",".VSCodeCounter"]),Sl=e=>bl.has(e)||e.startsWith(".pnpm"),kl=e=>{try{let n=String(e.getMonth()+1).padStart(2,"0"),t=String(e.getDate()).padStart(2,"0"),o=String(e.getHours()).padStart(2,"0"),s=String(e.getMinutes()).padStart(2,"0");return`${n}-${t} ${o}:${s}`}catch{return"N/A"}},xi=async e=>{let n=I(e),t=n.path||null;if(!t)return"ERROR: No directory path provided.";let o=1;if(n.recurse!==void 0&&n.recurse!==null)if(typeof n.recurse=="number")o=n.recurse;else if(typeof n.recurse=="boolean")o=n.recurse?2:1;else{let i=parseInt(String(n.recurse).trim(),10);o=isNaN(i)?1:i}o=Math.max(1,Math.min(3,o));let s=wi.resolve(process.cwd(),t);try{if(!fs.existsSync(s))return`ERROR: Path [${t}] does not exist.`;if(!fs.statSync(s).isDirectory())return`ERROR: Path [${t}] is a file, not a directory. Use ReadFile instead.`;if(o===1){let g=fs.readdirSync(s),y=g.length,m=150,w=g.slice(0,m),x=[];for(let E of w){let b=wi.join(s,E),T={name:E,type:"unknown",size:"N/A",mtime:"N/A"};try{let $=fs.statSync(b);T={name:E,type:$.isDirectory()?"directory":"file",size:($.size/1024).toFixed(1)+"KB",mtime:kl($.mtime)}}catch{T.type="inaccessible"}x.push(T)}let S=x.map(E=>E.type==="directory"?`${E.name}/`:`${E.name} (${E.size}, ${E.mtime})`).join(`
351
+ ${y}`}catch(d){let c=d instanceof Error?d.message:String(d);return`ERROR: Failed to update file [${o}]: ${c}`}};import fs from"fs";import bi from"path";var $l=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"]),Cl=e=>$l.has(e)||e.startsWith(".pnpm"),_l=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"}},Si=async e=>{let n=O(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=bi.resolve(process.cwd(),t);try{if(!fs.existsSync(s))return`ERROR: Path [${t}] does not exist.`;if(!fs.statSync(s).isDirectory())return`ERROR: Path [${t}] is a file, not a directory. Use ReadFile instead.`;if(o===1){let g=fs.readdirSync(s),y=g.length,m=150,w=g.slice(0,m),x=[];for(let E of w){let k=bi.join(s,E),T={name:E,type:"unknown",size:"N/A",mtime:"N/A"};try{let $=fs.statSync(k);T={name:E,type:$.isDirectory()?"directory":"file",size:($.size/1024).toFixed(1)+"KB",mtime:_l($.mtime)}}catch{T.type="inaccessible"}x.push(T)}let S=x.map(E=>E.type==="directory"?`${E.name}/`:`${E.name} (${E.size}, ${E.mtime})`).join(`
352
352
  `),R=`
353
353
 
354
354
  (Total items in folder: ${y})`;return y>m&&(R=`
355
355
 
356
356
  TRUNCATED: Showing first ${m} of ${y} items.`),g.length=0,w.length=0,x.length=0,`Detailed folder stats for [${t}]:
357
357
 
358
- ${S}${R}`}let a=0,r=0,h=0,d=500,c=!1,l=(g,y,m=1)=>{if(y>o||c)return[];let w=[];try{w=fs.readdirSync(g)}catch{return[`${" ".repeat(m-1)}[Inaccessible Directory]`]}let x=[],S=[];for(let T of w){let $=wi.join(g,T),C=!1;try{C=fs.statSync($).isDirectory()}catch{}C?x.push({name:T,fullPath:$}):S.push({name:T,fullPath:$})}x.sort((T,$)=>T.name.localeCompare($.name)),S.sort((T,$)=>T.name.localeCompare($.name));let R=[],E=" ".repeat(m-1);for(let T of x){if(h>=d){c=!0,R.push(`${E}[Truncated - Maximum item limit reached (${d})]`);break}if(h++,a++,R.push(`${E}${T.name}/`),y<o&&!Sl(T.name)){let $=l(T.fullPath,y+1,m+1);R.push(...$)}}let b=[];for(let T of S){if(h>=d){c=!0,R.push(`${E}[Truncated - Maximum item limit reached (${d})]`);break}h++,r++;let $="N/A";try{$=(fs.statSync(T.fullPath).size/1024).toFixed(1)+"KB"}catch{}b.push(`${T.name} (${$})`)}return b.length>0&&R.push(`${E}${b.join("; ")}`),R},u=l(s,1,1).join(`
358
+ ${S}${R}`}let a=0,r=0,h=0,d=500,c=!1,l=(g,y,m=1)=>{if(y>o||c)return[];let w=[];try{w=fs.readdirSync(g)}catch{return[`${" ".repeat(m-1)}[Inaccessible Directory]`]}let x=[],S=[];for(let T of w){let $=bi.join(g,T),C=!1;try{C=fs.statSync($).isDirectory()}catch{}C?x.push({name:T,fullPath:$}):S.push({name:T,fullPath:$})}x.sort((T,$)=>T.name.localeCompare($.name)),S.sort((T,$)=>T.name.localeCompare($.name));let R=[],E=" ".repeat(m-1);for(let T of x){if(h>=d){c=!0,R.push(`${E}[Truncated - Maximum item limit reached (${d})]`);break}if(h++,a++,R.push(`${E}${T.name}/`),y<o&&!Cl(T.name)){let $=l(T.fullPath,y+1,m+1);R.push(...$)}}let k=[];for(let T of S){if(h>=d){c=!0,R.push(`${E}[Truncated - Maximum item limit reached (${d})]`);break}h++,r++;let $="N/A";try{$=(fs.statSync(T.fullPath).size/1024).toFixed(1)+"KB"}catch{}k.push(`${T.name} (${$})`)}return k.length>0&&R.push(`${E}${k.join("; ")}`),R},f=l(s,1,1).join(`
359
359
  `),p=`
360
360
 
361
361
  (Total items scanned: ${h}, Directories: ${a}, Files: ${r})`;return c&&(p=`
362
362
 
363
363
  TRUNCATED: Scan capped at ${d} items. (Directories: ${a}, Files: ${r})`),`Detailed directory tree for [${t}] (recursive depth: ${o}):
364
364
 
365
- ${u}${p}`}catch(i){let a=i instanceof Error?i.message:String(i);return`ERROR: Failed to read folder [${t}]: ${a}`}};var bi=async(e,n)=>{let t=I(e),{question:o}=t;if(!o)return'ERROR: Missing "question" argument for ask.';if(!n.onAskUser)return"ERROR: onAskUser callback not provided in tool context.";let s=[];Object.keys(t).forEach(i=>{if(i.startsWith("option")){let a=t[i];if(typeof a=="string"&&a.includes("::")){let[r,h]=a.split("::");s.push({id:i,label:r.trim(),description:h.trim()})}else s.push({id:i,label:String(a).trim(),description:""})}});try{return`USER CHOOSE: ${await n.onAskUser(o,s)}`}catch(i){return`ERROR: Failed to get user input: ${i instanceof Error?i.message:String(i)}`}};import Tl from"puppeteer";import Os from"path";import us from"fs-extra";import{PDFDocument as Rl}from"pdf-lib";var Si=async e=>{let{path:n,content:t,orientation:o="portrait",margin:s="0px"}=I(e);if(!n)return'ERROR: Missing "path" argument for write_pdf.';if(!t)return'ERROR: Missing "content" (HTML/CSS) for write_pdf.';let i=Os.resolve(process.cwd(),n),a=null;try{await us.ensureDir(Os.dirname(i)),await ft.recordFileChange(i);let r=cs();a=await Tl.launch({headless:!0,executablePath:r.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let h=await a.newPage(),d=t,c={},l=async b=>{if(!b||b.startsWith("http://")||b.startsWith("https://")||b.startsWith("data:"))return null;try{let T=Os.resolve(process.cwd(),b);if(await us.pathExists(T)){let $=Os.extname(T).toLowerCase().replace(".","")||"png",C=$==="jpg"?"jpeg":$==="svg"?"svg+xml":$,k=await us.readFile(T,"base64");return`data:image/${C};base64,${k}`}}catch{}return null},f=/<link[^>]+href=["']([^"']+)["']/gi,u={},p;for(;(p=f.exec(t))!==null;){let b=p[1],T=p[0];if(b&&T.toLowerCase().includes("stylesheet")&&!b.startsWith("http://")&&!b.startsWith("https://")&&!b.startsWith("data:"))try{let $=Os.resolve(process.cwd(),b);if(await us.pathExists($)){let C=await us.readFile($,"utf-8");u[T]=`<style>${C}</style>`}}catch{}}for(let[b,T]of Object.entries(u))d=d.split(b).join(T);let g=/<img[^>]+src=["']([^"']+)["']/gi;for(;(p=g.exec(d))!==null;){let b=p[1];if(b&&!c[b]){let T=await l(b);T&&(c[b]=T)}}let y=/url\(\s*['"]?([^'")]+?)['"]?\s*\)/gi;for(;(p=y.exec(d))!==null;){let b=p[1].trim();if(b&&!c[b]){let T=await l(b);T&&(c[b]=T)}}for(let[b,T]of Object.entries(c)){let $=b.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&"),C=new RegExp(`(src=["'])(${$})(["'])`,"gi");d=d.replace(C,`$1${T}$3`);let k=new RegExp(`url\\(\\s*(['"]?)(${$})\\1\\s*\\)`,"gi");d=d.replace(k,`url($1${T}$1)`)}let m=`
365
+ ${f}${p}`}catch(i){let a=i instanceof Error?i.message:String(i);return`ERROR: Failed to read folder [${t}]: ${a}`}};var ki=async(e,n)=>{let t=O(e),{question:o}=t;if(!o)return'ERROR: Missing "question" argument for ask.';if(!n.onAskUser)return"ERROR: onAskUser callback not provided in tool context.";let s=[];Object.keys(t).forEach(i=>{if(i.startsWith("option")){let a=t[i];if(typeof a=="string"&&a.includes("::")){let[r,h]=a.split("::");s.push({id:i,label:r.trim(),description:h.trim()})}else s.push({id:i,label:String(a).trim(),description:""})}});try{return`USER CHOOSE: ${await n.onAskUser(o,s)}`}catch(i){return`ERROR: Failed to get user input: ${i instanceof Error?i.message:String(i)}`}};import Ml from"puppeteer";import Os from"path";import us from"fs-extra";import{PDFDocument as Al}from"pdf-lib";var Ti=async e=>{let{path:n,content:t,orientation:o="portrait",margin:s="0px"}=O(e);if(!n)return'ERROR: Missing "path" argument for write_pdf.';if(!t)return'ERROR: Missing "content" (HTML/CSS) for write_pdf.';let i=Os.resolve(process.cwd(),n),a=null;try{await us.ensureDir(Os.dirname(i)),await ft.recordFileChange(i);let r=cs();a=await Ml.launch({headless:!0,executablePath:r.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let h=await a.newPage(),d=t,c={},l=async k=>{if(!k||k.startsWith("http://")||k.startsWith("https://")||k.startsWith("data:"))return null;try{let T=Os.resolve(process.cwd(),k);if(await us.pathExists(T)){let $=Os.extname(T).toLowerCase().replace(".","")||"png",C=$==="jpg"?"jpeg":$==="svg"?"svg+xml":$,b=await us.readFile(T,"base64");return`data:image/${C};base64,${b}`}}catch{}return null},u=/<link[^>]+href=["']([^"']+)["']/gi,f={},p;for(;(p=u.exec(t))!==null;){let k=p[1],T=p[0];if(k&&T.toLowerCase().includes("stylesheet")&&!k.startsWith("http://")&&!k.startsWith("https://")&&!k.startsWith("data:"))try{let $=Os.resolve(process.cwd(),k);if(await us.pathExists($)){let C=await us.readFile($,"utf-8");f[T]=`<style>${C}</style>`}}catch{}}for(let[k,T]of Object.entries(f))d=d.split(k).join(T);let g=/<img[^>]+src=["']([^"']+)["']/gi;for(;(p=g.exec(d))!==null;){let k=p[1];if(k&&!c[k]){let T=await l(k);T&&(c[k]=T)}}let y=/url\(\s*['"]?([^'")]+?)['"]?\s*\)/gi;for(;(p=y.exec(d))!==null;){let k=p[1].trim();if(k&&!c[k]){let T=await l(k);T&&(c[k]=T)}}for(let[k,T]of Object.entries(c)){let $=k.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&"),C=new RegExp(`(src=["'])(${$})(["'])`,"gi");d=d.replace(C,`$1${T}$3`);let b=new RegExp(`url\\(\\s*(['"]?)(${$})\\1\\s*\\)`,"gi");d=d.replace(b,`url($1${T}$1)`)}let m=`
366
366
  <style>
367
367
  @page {
368
368
  margin: ${s};
@@ -392,7 +392,7 @@ ${u}${p}`}catch(i){let a=i instanceof Error?i.message:String(i);return`ERROR: Fa
392
392
  </style>
393
393
  <div class="watermark">Generated by FluxFlow CLI (AI)</div>
394
394
  ${d}
395
- `;await h.setContent(m,{waitUntil:"networkidle0",timeout:18e4});let w=await h.pdf({format:"A4",landscape:String(o).toLowerCase()==="landscape",margin:{top:s,right:s,bottom:s,left:s},printBackground:!0}),x=await Rl.load(w),S=Os.basename(n);x.setTitle(`FluxFlow_${S}`),x.setAuthor("FluxFlow CLI"),x.setSubject("Generated with Agentic AI System"),x.setKeywords(["FluxFlow","AI","Agentic","Automated"]),x.setCreator("FluxFlow PDF Engine"),x.setProducer("FluxFlow (Generative AI)");let R=await x.save();await us.writeFile(i,R);let E=await us.stat(i);return`SUCCESS: PDF generated successfully at [${n}] (${(E.size/1024).toFixed(2)} KB).`}catch(r){let h=r instanceof Error?r.message:String(r);return`ERROR: Failed to generate PDF [${n}]: ${h}`}finally{a&&await a.close()}};import Br from"fs-extra";import ki from"path";import El from"html-to-docx";var Ti=async e=>{let{path:n,content:t}=I(e);if(!n)return'ERROR: Missing "path" argument for write_docx.';if(!t)return'ERROR: Missing "content" (HTML) for write_docx.';let o=ki.resolve(process.cwd(),n);try{await Br.ensureDir(ki.dirname(o)),await ft.recordFileChange(o);let s=ki.basename(n),i=t.includes("<html")?t:`
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 Al.load(w),S=Os.basename(n);x.setTitle(`FluxFlow_${S}`),x.setAuthor("FluxFlow CLI"),x.setSubject("Generated with Agentic AI System"),x.setKeywords(["FluxFlow","AI","Agentic","Automated"]),x.setCreator("FluxFlow PDF Engine"),x.setProducer("FluxFlow (Generative AI)");let R=await x.save();await us.writeFile(i,R);let E=await us.stat(i);return`SUCCESS: PDF generated successfully at [${n}] (${(E.size/1024).toFixed(2)} KB).`}catch(r){let h=r instanceof Error?r.message:String(r);return`ERROR: Failed to generate PDF [${n}]: ${h}`}finally{a&&await a.close()}};import qr from"fs-extra";import Ri from"path";import vl from"html-to-docx";var Ei=async e=>{let{path:n,content:t}=O(e);if(!n)return'ERROR: Missing "path" argument for write_docx.';if(!t)return'ERROR: Missing "content" (HTML) for write_docx.';let o=Ri.resolve(process.cwd(),n);try{await qr.ensureDir(Ri.dirname(o)),await ft.recordFileChange(o);let s=Ri.basename(n),i=t.includes("<html")?t:`
396
396
  <!DOCTYPE html>
397
397
  <html lang="en">
398
398
  <head>
@@ -403,37 +403,37 @@ ${u}${p}`}catch(i){let a=i instanceof Error?i.message:String(i);return`ERROR: Fa
403
403
  ${t}
404
404
  </body>
405
405
  </html>
406
- `,a=await El(i,null,{title:`FluxFlow_${s}`,creator:"FluxFlow CLI",description:"Generated by Agentic AI System",table:{row:{cantSplit:!0}},footer:!0,pageNumber:!0});return await Br.writeFile(o,a),`SUCCESS: Word document [${n}] generated successfully.
407
- - Size: ${(a.length/1024).toFixed(1)} KB`}catch(s){let i=s instanceof Error?s.message:String(s);return`ERROR: Failed to generate DOCX [${n}]: ${i}`}};import Ei from"fs/promises";import hs from"path";import Ri from"fast-glob";import{Minimatch as Ur}from"minimatch";async function Zs(e,n,t=e,o=1){if(o>12)return[];let s=[],i;try{i=await Ei.readdir(e,{withFileTypes:!0})}catch{return[]}for(let a of i){let r=hs.join(e,a.name),h=hs.relative(t,r),d=h.split(hs.sep).map(f=>f.toLowerCase()),c=a.name.toLowerCase();if(!n.some(f=>{let u=f.toLowerCase();return u.startsWith(".")&&c.endsWith(u)?!0:d.some(p=>p===u||p.startsWith(".pnpm"))}))if(a.isDirectory()){let f=await Zs(r,n,t,o+1);s=s.concat(f)}else a.isFile()&&s.push({fullPath:r,relativePath:h})}return s}function $l(e,n,t=1/0){if(e===n)return 0;if(e.length===0)return n.length;if(n.length===0)return e.length;if(Math.abs(e.length-n.length)>t)return t+1;let o=Array.from({length:n.length+1},(s,i)=>i);for(let s=1;s<=e.length;s++){let i=[s],a=s;for(let r=1;r<=n.length;r++){let h=e[s-1]===n[r-1]?0:1,d=Math.min(i[r-1]+1,o[r]+1,o[r-1]+h);i.push(d),d<a&&(a=d)}if(o=i,a>t)return t+1}return o[n.length]}function Cl(e,n){if(!e||!n)return!1;let t=e.toLowerCase(),o=n.toLowerCase();if(t.includes(o))return!0;let s=t.split(/[^a-z0-9]+/).filter(a=>a.length>0),i=o.split(/[^a-z0-9]+/).filter(a=>a.length>1||o.length===1&&a.length>0);return i.length===0?!1:i.every(a=>{let r=a.length<=2?0:a.length<=5?1:2;for(let h of s)if(h.includes(a)||a.length>=3&&h.length>=3&&Math.abs(h.length-a.length)<=r&&$l(a,h,r)<=r)return!0;return!1})}var eo=async e=>{let{keyword:n,path:t,fuzzy:o,subString:s,regex:i}=I(e);if(n==null)return'ERROR: Missing "keyword" argument.';let a=String(n),r=g=>g===!0||g==="true"||g===1||g==="1"||g==="yes",h=i===!1||i==="false"||i===0||i==="0"||i==="no",d=i===!0||i==="true"||i===1||i==="1"||i==="yes",c=r(o)||r(s),l=null,f=null;if(h)c||(f=new RegExp(`(?<![\\w])${a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\\w])`,"i"));else{try{l=new RegExp(a,"i")}catch(g){if(d)return`ERROR: Invalid regex pattern "${a}": ${g.message}`}f=new RegExp(`(?<![\\w])${a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\\w])`,"i")}let u=[".git","node_modules",".gemini","dist","build",".next","out",".cache","bin","obj","vendor","venv",".idea",".gradle",".terraform","target","coverage",".vscode",".svn",".hg",".fslckout",".github",".gitlab",".circleci",".gitea",".gitee",".lerna",".changeset",".nx",".npm",".yarn",".pnpm-store",".pnpm",".expo",".nuxt",".svelte-kit",".docusaurus",".turbo",".vercel","bower_components",".netlify",".vuepress",".quasar",".output",".angular","jspm_packages",".parcel-cache",".rollup.cache",".rspack",".vitepress","__pycache__",".pytest_cache",".mypy_cache",".tox",".poetry","env","vhdl",".ipynb_checkpoints",".jupyter",".conda",".pdm-build",".bundle",".yardoc",".metadata","App_Data","ClientBin",".cargo",".rustc_info",".go","Godeps","_vendor",".rake_tasks","CMakefiles",".wakatime",".dart_tool",".fvm",".cocoapods","Pods",".pub-cache",".symlinks","DerivedData",".xcworkspace",".serverless",".aws",".gcloud",".azure",".kube",".vagrant",".docker","postgres-data","redis-data","mongo-data",".Spotlight-V100",".Trashes","$RECYCLE.BIN","System Volume Information",".DocumentRevisions-V100",".fseventsd","AppData","Application Data","Local","LocalLow","Roaming","$WinREAgent","$WINDOWS.~BT","$WINDOWS.~WS","scw","System32","SysWOW64",".AppleDouble",".AppleDB",".AppleDesktop","_CodeSignature",".cmio",".LSOverride",".localized",".TemporaryItems",".Trash",".Trash-0",".Trash-1000",".gvfs",".local",".config",".dbus",".fontconfig",".snap",".var",".lost+found","lost+found",".thumb",".thumbnails","EFI","boot","grub","logs","log",".nyc_output",".sonar",".ruff_cache",".VSCodeCounter",".exe",".dll",".so",".dylib",".png",".jpg",".jpeg",".gif",".ico",".svg",".webp",".mp3",".mp4",".avi",".zip",".tgz",".tar",".gz",".7z",".rar",".pdf",".docx",".xlsx",".pptx",".woff",".woff2",".ttf",".eot"],p=150;try{let g=[],y=process.cwd(),m=null;if(t){let v=t.split(";").map(j=>j.trim()).filter(Boolean),L=v.some(j=>j.startsWith("!"));if(v.some(j=>Ri.isDynamicPattern(j)||/[*?{}[\]()|+]/.test(j))){m="glob";let j=t.replace(/\\/g,"/"),V=v.map(B=>B.replace(/\\/g,"/")),oe=u.map(B=>B.startsWith(".")?`**/*${B}`:`**/${B}/**`);if(L&&!v.some(B=>!B.startsWith("!"))){let B=await Zs(y,u,y),W=M=>M.endsWith("/")?M+"**":M,re=V.filter(M=>M.startsWith("!")).map(M=>W(M.slice(1))),Re=V.filter(M=>!M.startsWith("!")).map(W);g=B.filter(M=>{let F=M.relativePath.replace(/\\/g,"/"),Y=Re.length===0||Re.some(Ne=>{try{return new Ur(Ne).match(F)}catch{return!1}}),J=re.some(Ne=>{try{return new Ur(Ne).match(F)}catch{return!1}});return Y&&!J})}else{let B=V.some(re=>/[\(\)\|]|\.\*/.test(re)),W=[];if(!B)try{W=await Ri(V,{cwd:y,ignore:oe,dot:!0,onlyFiles:!0,absolute:!1})}catch{W=[]}if(W.length===0&&(B||Ri.isDynamicPattern(j))){let re=j.match(/^([^\*\?\(\)\|\[\]\s]+)\//),Re=re&&!/[\*\?\(\)\|\[\]]/.test(re[1])?hs.resolve(y,re[1]):y,M=await Zs(Re,u,y);try{let F=j.replace(/^\.\//,"");F=F.replace(/\.\*\/(\\.|[^\/])/g,".*$1"),!F.startsWith("^")&&!F.startsWith(".*")&&(F=`.*${F}`);let Y=new RegExp(F.endsWith("$")?F:`${F}$`,"i");g=M.filter(J=>{let Ne=J.relativePath.replace(/\\/g,"/");return Y.test(Ne)})}catch{g=[]}}else g=W.map(re=>({fullPath:hs.resolve(y,re),relativePath:re}))}}else{let j=t.replace(/[\/\\]+$/,""),V=hs.resolve(y,j);try{let oe=await Ei.stat(V);if(oe.isDirectory())m="dir",g=await Zs(V,u,y);else if(oe.isFile())m="file",g.push({fullPath:V,relativePath:hs.relative(y,V)});else return`ERROR: Path is neither a file nor a directory: ${t}`}catch{return`ERROR: Path not found: ${t}`}}}else g=await Zs(y,u);let w=g.map(async v=>{try{let L=await Ei.readFile(v.fullPath,"utf-8");if(L.includes("\0"))return[];let N=L.split(/\r?\n/),j=[];for(let oe=0;oe<N.length;oe++)(c?N[oe].toLowerCase().includes(a.toLowerCase())||Cl(N[oe],a):h?f&&f.test(N[oe]):l&&l.test(N[oe])||f&&f.test(N[oe]))&&j.push({line:oe+1,content:N[oe].trim()});return j.length===0?null:{path:v.relativePath.replace(/\\/g,"/"),matches:j}}catch{return[]}}),x=await Promise.all(w),S=[],R=0;for(let v of x){if(!v||!v.matches)continue;if(R>=p)break;let L=p-R,N=v.matches.slice(0,L);S.push({path:v.path,matches:N}),R+=N.length}typeof global.gc=="function"&&global.gc();let E=c?"(fuzzy mode)":d?"(regex mode)":h?"(keyword mode)":"(standard mode)";if(S.length===0){let v=m==="file"?` in '${t}'`:m==="dir"||m==="glob"?` in '${t}'`:". Try to specify files",L=m==="dir"?"[DIR]":m==="glob"?"[GLOB]":"";return`${L}${L?" ":""}Found 0 matches of '${a}'${v}${E?` ${E}`:""}`}let b=E?` ${E}`:"",T=`${S.length} file${S.length===1?"":"s"}`,$=`${R} match${R===1?"":"es"}`,C;m==="file"?C=`Found ${$} of '${a}' in '${t}'${b}:`:m==="dir"||m==="glob"?C=`Found ${$} of '${a}' in '${t}' across ${T}${b}:`:C=`Found ${$} of '${a}' across ${T}${b}:`;let k=m==="dir"?"[DIR]":m==="glob"?"[GLOB]":"",O=`${k}${k?" ":""}${C}
406
+ `,a=await vl(i,null,{title:`FluxFlow_${s}`,creator:"FluxFlow CLI",description:"Generated by Agentic AI System",table:{row:{cantSplit:!0}},footer:!0,pageNumber:!0});return await qr.writeFile(o,a),`SUCCESS: Word document [${n}] generated successfully.
407
+ - Size: ${(a.length/1024).toFixed(1)} KB`}catch(s){let i=s instanceof Error?s.message:String(s);return`ERROR: Failed to generate DOCX [${n}]: ${i}`}};import Ci from"fs/promises";import hs from"path";import $i from"fast-glob";import{Minimatch as zr}from"minimatch";async function Zs(e,n,t=e,o=1){if(o>12)return[];let s=[],i;try{i=await Ci.readdir(e,{withFileTypes:!0})}catch{return[]}for(let a of i){let r=hs.join(e,a.name),h=hs.relative(t,r),d=h.split(hs.sep).map(u=>u.toLowerCase()),c=a.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(a.isDirectory()){let u=await Zs(r,n,t,o+1);s=s.concat(u)}else a.isFile()&&s.push({fullPath:r,relativePath:h})}return s}function Il(e,n,t=1/0){if(e===n)return 0;if(e.length===0)return n.length;if(n.length===0)return e.length;if(Math.abs(e.length-n.length)>t)return t+1;let o=Array.from({length:n.length+1},(s,i)=>i);for(let s=1;s<=e.length;s++){let i=[s],a=s;for(let r=1;r<=n.length;r++){let h=e[s-1]===n[r-1]?0:1,d=Math.min(i[r-1]+1,o[r]+1,o[r-1]+h);i.push(d),d<a&&(a=d)}if(o=i,a>t)return t+1}return o[n.length]}function Ol(e,n){if(!e||!n)return!1;let t=e.toLowerCase(),o=n.toLowerCase();if(t.includes(o))return!0;let s=t.split(/[^a-z0-9]+/).filter(a=>a.length>0),i=o.split(/[^a-z0-9]+/).filter(a=>a.length>1||o.length===1&&a.length>0);return i.length===0?!1:i.every(a=>{let r=a.length<=2?0:a.length<=5?1:2;for(let h of s)if(h.includes(a)||a.length>=3&&h.length>=3&&Math.abs(h.length-a.length)<=r&&Il(a,h,r)<=r)return!0;return!1})}var eo=async e=>{let{keyword:n,path:t,fuzzy:o,subString:s,regex:i}=O(e);if(n==null)return'ERROR: Missing "keyword" argument.';let a=String(n),r=g=>g===!0||g==="true"||g===1||g==="1"||g==="yes",h=i===!1||i==="false"||i===0||i==="0"||i==="no",d=i===!0||i==="true"||i===1||i==="1"||i==="yes",c=r(o)||r(s),l=null,u=null;if(h)c||(u=new RegExp(`(?<![\\w])${a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\\w])`,"i"));else{try{l=new RegExp(a,"i")}catch(g){if(d)return`ERROR: Invalid regex pattern "${a}": ${g.message}`}u=new RegExp(`(?<![\\w])${a.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(U=>U.trim()).filter(Boolean),D=I.some(U=>U.startsWith("!"));if(I.some(U=>$i.isDynamicPattern(U)||/[*?{}[\]()|+]/.test(U))){m="glob";let U=t.replace(/\\/g,"/"),Y=I.map(N=>N.replace(/\\/g,"/")),ie=f.map(N=>N.startsWith(".")?`**/*${N}`:`**/${N}/**`);if(D&&!I.some(N=>!N.startsWith("!"))){let N=await Zs(y,f,y),W=M=>M.endsWith("/")?M+"**":M,re=Y.filter(M=>M.startsWith("!")).map(M=>W(M.slice(1))),Re=Y.filter(M=>!M.startsWith("!")).map(W);g=N.filter(M=>{let F=M.relativePath.replace(/\\/g,"/"),V=Re.length===0||Re.some(Ne=>{try{return new zr(Ne).match(F)}catch{return!1}}),J=re.some(Ne=>{try{return new zr(Ne).match(F)}catch{return!1}});return V&&!J})}else{let N=Y.some(re=>/[\(\)\|]|\.\*/.test(re)),W=[];if(!N)try{W=await $i(Y,{cwd:y,ignore:ie,dot:!0,onlyFiles:!0,absolute:!1})}catch{W=[]}if(W.length===0&&(N||$i.isDynamicPattern(U))){let re=U.match(/^([^\*\?\(\)\|\[\]\s]+)\//),Re=re&&!/[\*\?\(\)\|\[\]]/.test(re[1])?hs.resolve(y,re[1]):y,M=await Zs(Re,f,y);try{let F=U.replace(/^\.\//,"");F=F.replace(/\.\*\/(\\.|[^\/])/g,".*$1"),!F.startsWith("^")&&!F.startsWith(".*")&&(F=`.*${F}`);let V=new RegExp(F.endsWith("$")?F:`${F}$`,"i");g=M.filter(J=>{let Ne=J.relativePath.replace(/\\/g,"/");return V.test(Ne)})}catch{g=[]}}else g=W.map(re=>({fullPath:hs.resolve(y,re),relativePath:re}))}}else{let U=t.replace(/[\/\\]+$/,""),Y=hs.resolve(y,U);try{let ie=await Ci.stat(Y);if(ie.isDirectory())m="dir",g=await Zs(Y,f,y);else if(ie.isFile())m="file",g.push({fullPath:Y,relativePath:hs.relative(y,Y)});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 D=await Ci.readFile(I.fullPath,"utf-8");if(D.includes("\0"))return[];let j=D.split(/\r?\n/),U=[];for(let ie=0;ie<j.length;ie++)(c?j[ie].toLowerCase().includes(a.toLowerCase())||Ol(j[ie],a):h?u&&u.test(j[ie]):l&&l.test(j[ie])||u&&u.test(j[ie]))&&U.push({line:ie+1,content:j[ie].trim()});return U.length===0?null:{path:I.relativePath.replace(/\\/g,"/"),matches:U}}catch{return[]}}),x=await Promise.all(w),S=[],R=0;for(let I of x){if(!I||!I.matches)continue;if(R>=p)break;let D=p-R,j=I.matches.slice(0,D);S.push({path:I.path,matches:j}),R+=j.length}typeof global.gc=="function"&&global.gc();let E=c?"(fuzzy mode)":d?"(regex mode)":h?"(keyword mode)":"(standard mode)";if(S.length===0){let I=m==="file"?` in '${t}'`:m==="dir"||m==="glob"?` in '${t}'`:". Try to specify files",D=m==="dir"?"[DIR]":m==="glob"?"[GLOB]":"";return`${D}${D?" ":""}Found 0 matches of '${a}'${I}${E?` ${E}`:""}`}let k=E?` ${E}`:"",T=`${S.length} file${S.length===1?"":"s"}`,$=`${R} match${R===1?"":"es"}`,C;m==="file"?C=`Found ${$} of '${a}' in '${t}'${k}:`:m==="dir"||m==="glob"?C=`Found ${$} of '${a}' in '${t}' across ${T}${k}:`:C=`Found ${$} of '${a}' across ${T}${k}:`;let b=m==="dir"?"[DIR]":m==="glob"?"[GLOB]":"",v=`${b}${b?" ":""}${C}
408
408
 
409
- `;for(let v of S){O+=`${v.path}
410
- `;for(let L of v.matches)O+=` ${L.line}: ${L.content}
411
- `;O+=`
412
- `}return O.trimEnd()}catch(g){return`ERROR: ${g.message}`}};import Wr from"fs-extra";import $i from"path";var _l=(e,n={})=>{try{if(e.length<8||e[0]!==137||e[1]!==80||e[2]!==78||e[3]!==71)return e;let t=[],o=[];for(let a=0;a<256;a++){let r=a;for(let h=0;h<8;h++)r&1?r=3988292384^r>>>1:r=r>>>1;o[a]=r}let s=a=>{let r=4294967295;for(let h=0;h<a.length;h++)r=o[(r^a[h])&255]^r>>>8;return(r^4294967295)>>>0},i=(a,r)=>{let h=Buffer.from(a,"ascii"),d=Buffer.from(r,"utf-8"),c=h.length+1+d.length,l=Buffer.alloc(8+c+4);l.writeUInt32BE(c,0),l.write("tEXt",4,"ascii"),h.copy(l,8),l[8+h.length]=0,d.copy(l,8+h.length+1);let f=s(l.subarray(4,8+c));return l.writeUInt32BE(f,8+c),l};for(let[a,r]of Object.entries(n))r!=null&&t.push(i(a,String(r)));if(t.length===0)return e;if(e.subarray(12,16).toString("ascii")==="IHDR"){let r=e.subarray(0,33),h=e.subarray(33);return Buffer.concat([r,...t,h])}return e}catch{return e}},Ci=async(e,n={})=>{let t=I(e),o=t.prompt||t.text,s=t.path||t.outputPath||t.output||"generated_image.png",i=t.ratio;if(!o)return'ERROR: Missing "prompt" argument for generate_image.';let a=["nsfw","naked","nudity","nude","porn","sex","xxx","erotic","gore","bloody","violence","abuse","suicide","murder","hentai","pedophile","rape"],r=o.toLowerCase();if(a.some(d=>r.includes(d)))return"ERROR: Prompt blocked by system safety filter (inappropriate or unsafe content detected).";try{let d=await Ft();if(!await $r(d))return`ERROR: Insufficient Quota for selected quality. Either tell user reduce quality or wait for next refresh cycle (${(await Cr()).nextResetMin||60}m).`;let l=d.imageSettings||{keyType:"Default",quality:"Low-High",apiKey:""},f=l.keyType==="Custom"&&l.apiKey?l.apiKey:FALLBACK_IMAGE_KEY,p={Low:"flux","Low-High":"zimage",Medium:"gptimage","Medium-High":"gptimage",High:"qwen-image",Ultra:"gptimage-large",Premium:"nanobanana-pro"}[l.quality]||"zimage",g=1024,y=1024;if(i){let L=i.replace(/\s+/g,"");L==="16:9"?(g=1024,y=576):L==="9:16"?(g=576,y=1024):L==="4:3"?(g=1024,y=768):L==="3:4"?(g=768,y=1024):L==="1:1"&&(g=1024,y=1024)}let m=Math.floor(Math.random()*1e7),x=`https://gen.pollinations.ai/image/${encodeURIComponent(o)}?model=${p}&width=${g}&height=${y}&seed=${m}&enhance=true&reasoning=high&quality=high&negative=${encodeURIComponent("deformed, distorted, disfigured, poorly drawn, bad anatomy, wrong anatomy, extra limb, missing limb, floating limbs, disconnected limbs, mutation, mutated hands and fingers, blurry, low quality, low resolution, extra fingers, censored, watermarks, signatures")}`,S=await fetch(x,{method:"GET",headers:{Authorization:`Bearer ${f}`}});if(!S.ok){let L=S.status,N="";try{N=await S.text()}catch{}return L===402||N.includes("Insufficient balance")||N.includes("PAYMENT_REQUIRED")?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed with status [${L}]: ${N||"Unknown API Error"}`}if((S.headers.get("content-type")||"").includes("application/json")){let L=await S.json();return L.status===402||L.error&&L.error.code==="PAYMENT_REQUIRED"?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed: ${L.error?.message||JSON.stringify(L)}`}let E=await S.arrayBuffer(),b=Buffer.from(E),T={Title:o,Description:"Generated via FluxFlow CLI",Software:"FluxFlow CLI",Author:"FluxFlow","Creation Time":new Date().toISOString(),Prompt:o,Model:`Fluxflow:${p}`,Ratio:i||"1:1",Seed:String(m)};b=_l(b,T);let $=$i.resolve(process.cwd(),s);await Wr.ensureDir($i.dirname($)),await ft.recordFileChange($),await Wr.writeFile($,b),await _r(d);let C=$i.extname(s).toLowerCase(),O={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".webp":"image/webp"}[C]||"image/png";return n.isMultiModal!==!1?{text:`SUCCESS: Image successfully generated from prompt [${o}] and saved to [${s}]. Output attached to multimodal part`,binaryPart:{inlineData:{data:b.toString("base64"),mimeType:O}}}:`SUCCESS: Image successfully generated from prompt [${o}] and saved to [${s}].`}catch(d){return`ERROR: Failed during image generation: ${d instanceof Error?d.message:String(d)}`}};var to=async(e,n={})=>{let t=i=>{let a=new RegExp(`${i}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),r=e.match(a);return r?r[2].trim():null},o=t("id"),s=t("summary");if(!o||!s)return"ERROR: Missing 'id' or 'summary' for saveSummary tool.";try{let i=X(Xt,{}),a=X(vn,{});return a[o]=s,delete i[o],he(vn,a),he(Xt,i),`SUCCESS: Saved summary and purged raw memories for chat [${o}].`}catch(i){let a=i instanceof Error?i.message:String(i);return`ERROR: Failed to save summary for chat [${o}]: ${a}`}};var Ls=async(e,n={})=>{let o=(s=>{let i=new RegExp(`${s}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),a=e.match(i);return a?a[2].trim():null})("id");if(!o)return"ERROR: Missing 'id' parameter for addMemScore tool.";try{let s=X(Dt,[]),i=!1,a=[];for(let c of s)c.score===void 0&&(c.score=.5),c.id===o?(c.score=Math.min(2,c.score+.2),i=!0):(c.score*=.98,c.score<.05&&(c.score=0)),c.score=Math.round(c.score*1e5)/1e5,c.score>0&&a.push(c);if(he(Dt,a),!i)return`WARNING: Memory ID [${o}] not found. Other memories decayed by -0.01.`;let r=a.find(c=>c.id===o),h=r?r.score.toFixed(2):"deleted (score <= 0)",d=s.length-a.length;return`SUCCESS: Adjusted memory scores. Target [${o}] is now ${h}.${d>0?` Purged ${d} decayed memories.`:""}`}catch(s){let i=s instanceof Error?s.message:String(s);return`ERROR: Failed to adjust memory score for [${o}]: ${i}`}};import Mi from"fs-extra";import ms from"path";import{createRequire as vl}from"module";import ps from"fs-extra";import _i from"path";import Ml from"https";var jr={js:"tree-sitter-javascript.wasm",jsx:"tree-sitter-javascript.wasm",ts:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm",py:"tree-sitter-python.wasm",c:"tree-sitter-c.wasm",cpp:"tree-sitter-cpp.wasm",java:"tree-sitter-java.wasm",html:"tree-sitter-html.wasm"};async function Al(e,n=null){let t=n||`https://unpkg.com/tree-sitter-wasms@0.1.13/out/${e}`,o=_i.join(as,e);return await ps.ensureDir(as),new Promise((s,i)=>{let a={headers:{"User-Agent":"FluxFlow-Agent"}};Ml.get(t,a,r=>{if([301,302,307,308].includes(r.statusCode)&&r.headers.location){let d=r.headers.location;if(!d.startsWith("http")){let c=new URL(t);d=`${c.protocol}//${c.host}${d}`}Al(e,d).then(s).catch(i);return}if(r.statusCode!==200){i(new Error(`Failed to download ${e}: HTTP ${r.statusCode}`));return}let h=ps.createWriteStream(o);r.pipe(h),h.on("finish",()=>{h.close(),s()})}).on("error",r=>{ps.existsSync(o)&&ps.unlink(o,()=>{}),i(r)})})}function uu(e){let n=_i.join(as,e);return ps.existsSync(n)}async function hu(e){let n=_i.join(as,e);ps.existsSync(n)&&await ps.unlink(n)}var qr=vl(import.meta.url),Hr=qr("web-tree-sitter"),Gr=!1,Kr=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"]),zr=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 Yr(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(`
409
+ `;for(let I of S){v+=`${I.path}
410
+ `;for(let D of I.matches)v+=` ${D.line}: ${D.content}
411
+ `;v+=`
412
+ `}return v.trimEnd()}catch(g){return`ERROR: ${g.message}`}};import Kr from"fs-extra";import _i from"path";var Ll=(e,n={})=>{try{if(e.length<8||e[0]!==137||e[1]!==80||e[2]!==78||e[3]!==71)return e;let t=[],o=[];for(let a=0;a<256;a++){let r=a;for(let h=0;h<8;h++)r&1?r=3988292384^r>>>1:r=r>>>1;o[a]=r}let s=a=>{let r=4294967295;for(let h=0;h<a.length;h++)r=o[(r^a[h])&255]^r>>>8;return(r^4294967295)>>>0},i=(a,r)=>{let h=Buffer.from(a,"ascii"),d=Buffer.from(r,"utf-8"),c=h.length+1+d.length,l=Buffer.alloc(8+c+4);l.writeUInt32BE(c,0),l.write("tEXt",4,"ascii"),h.copy(l,8),l[8+h.length]=0,d.copy(l,8+h.length+1);let u=s(l.subarray(4,8+c));return l.writeUInt32BE(u,8+c),l};for(let[a,r]of Object.entries(n))r!=null&&t.push(i(a,String(r)));if(t.length===0)return e;if(e.subarray(12,16).toString("ascii")==="IHDR"){let r=e.subarray(0,33),h=e.subarray(33);return Buffer.concat([r,...t,h])}return e}catch{return e}},Mi=async(e,n={})=>{let t=O(e),o=t.prompt||t.text,s=t.path||t.outputPath||t.output||"generated_image.png",i=t.ratio;if(!o)return'ERROR: Missing "prompt" argument for generate_image.';let a=["nsfw","naked","nudity","nude","porn","sex","xxx","erotic","gore","bloody","violence","abuse","suicide","murder","hentai","pedophile","rape"],r=o.toLowerCase();if(a.some(d=>r.includes(d)))return"ERROR: Prompt blocked by system safety filter (inappropriate or unsafe content detected).";try{let d=await Ft();if(!await Ir(d))return`ERROR: Insufficient Quota for selected quality. Either tell user reduce quality or wait for next refresh cycle (${(await Or()).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 D=i.replace(/\s+/g,"");D==="16:9"?(g=1024,y=576):D==="9:16"?(g=576,y=1024):D==="4:3"?(g=1024,y=768):D==="3:4"?(g=768,y=1024):D==="1:1"&&(g=1024,y=1024)}let m=Math.floor(Math.random()*1e7),x=`https://gen.pollinations.ai/image/${encodeURIComponent(o)}?model=${p}&width=${g}&height=${y}&seed=${m}&enhance=true&reasoning=high&quality=high&negative=${encodeURIComponent("deformed, distorted, disfigured, poorly drawn, bad anatomy, wrong anatomy, extra limb, missing limb, floating limbs, disconnected limbs, mutation, mutated hands and fingers, blurry, low quality, low resolution, extra fingers, censored, watermarks, signatures")}`,S=await fetch(x,{method:"GET",headers:{Authorization:`Bearer ${u}`}});if(!S.ok){let D=S.status,j="";try{j=await S.text()}catch{}return D===402||j.includes("Insufficient balance")||j.includes("PAYMENT_REQUIRED")?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed with status [${D}]: ${j||"Unknown API Error"}`}if((S.headers.get("content-type")||"").includes("application/json")){let D=await S.json();return D.status===402||D.error&&D.error.code==="PAYMENT_REQUIRED"?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed: ${D.error?.message||JSON.stringify(D)}`}let E=await S.arrayBuffer(),k=Buffer.from(E),T={Title:o,Description:"Generated via FluxFlow CLI",Software:"FluxFlow CLI",Author:"FluxFlow","Creation Time":new Date().toISOString(),Prompt:o,Model:`Fluxflow:${p}`,Ratio:i||"1:1",Seed:String(m)};k=Ll(k,T);let $=_i.resolve(process.cwd(),s);await Kr.ensureDir(_i.dirname($)),await ft.recordFileChange($),await Kr.writeFile($,k),await Lr(d);let C=_i.extname(s).toLowerCase(),v={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".webp":"image/webp"}[C]||"image/png";return n.isMultiModal!==!1?{text:`SUCCESS: Image successfully generated from prompt [${o}] and saved to [${s}]. Output attached to multimodal part`,binaryPart:{inlineData:{data:k.toString("base64"),mimeType:v}}}:`SUCCESS: Image successfully generated from prompt [${o}] and saved to [${s}].`}catch(d){return`ERROR: Failed during image generation: ${d instanceof Error?d.message:String(d)}`}};var to=async(e,n={})=>{let t=i=>{let a=new RegExp(`${i}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),r=e.match(a);return r?r[2].trim():null},o=t("id"),s=t("summary");if(!o||!s)return"ERROR: Missing 'id' or 'summary' for saveSummary tool.";try{let i=X(Xt,{}),a=X(vn,{});return a[o]=s,delete i[o],he(vn,a),he(Xt,i),`SUCCESS: Saved summary and purged raw memories for chat [${o}].`}catch(i){let a=i instanceof Error?i.message:String(i);return`ERROR: Failed to save summary for chat [${o}]: ${a}`}};var Ls=async(e,n={})=>{let o=(s=>{let i=new RegExp(`${s}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),a=e.match(i);return a?a[2].trim():null})("id");if(!o)return"ERROR: Missing 'id' parameter for addMemScore tool.";try{let s=X(Dt,[]),i=!1,a=[];for(let c of s)c.score===void 0&&(c.score=.5),c.id===o?(c.score=Math.min(2,c.score+.2),i=!0):(c.score*=.98,c.score<.05&&(c.score=0)),c.score=Math.round(c.score*1e5)/1e5,c.score>0&&a.push(c);if(he(Dt,a),!i)return`WARNING: Memory ID [${o}] not found. Other memories decayed by -0.01.`;let r=a.find(c=>c.id===o),h=r?r.score.toFixed(2):"deleted (score <= 0)",d=s.length-a.length;return`SUCCESS: Adjusted memory scores. Target [${o}] is now ${h}.${d>0?` Purged ${d} decayed memories.`:""}`}catch(s){let i=s instanceof Error?s.message:String(s);return`ERROR: Failed to adjust memory score for [${o}]: ${i}`}};import vi from"fs-extra";import ms from"path";import{createRequire as Fl}from"module";import ps from"fs-extra";import Ai from"path";import Pl from"https";var Yr={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 Dl(e,n=null){let t=n||`https://unpkg.com/tree-sitter-wasms@0.1.13/out/${e}`,o=Ai.join(as,e);return await ps.ensureDir(as),new Promise((s,i)=>{let a={headers:{"User-Agent":"FluxFlow-Agent"}};Pl.get(t,a,r=>{if([301,302,307,308].includes(r.statusCode)&&r.headers.location){let d=r.headers.location;if(!d.startsWith("http")){let c=new URL(t);d=`${c.protocol}//${c.host}${d}`}Dl(e,d).then(s).catch(i);return}if(r.statusCode!==200){i(new Error(`Failed to download ${e}: HTTP ${r.statusCode}`));return}let h=ps.createWriteStream(o);r.pipe(h),h.on("finish",()=>{h.close(),s()})}).on("error",r=>{ps.existsSync(o)&&ps.unlink(o,()=>{}),i(r)})})}function xu(e){let n=Ai.join(as,e);return ps.existsSync(n)}async function bu(e){let n=Ai.join(as,e);ps.existsSync(n)&&await ps.unlink(n)}var Xr=Fl(import.meta.url),Vr=Xr("web-tree-sitter"),Jr=!1,Qr=new Set(["class_declaration","function_declaration","method_definition","arrow_function","function_expression","if_statement","else_clause","for_statement","for_in_statement","for_of_statement","while_statement","do_statement","switch_statement","try_statement","catch_clause","variable_declarator","export_statement","lexical_declaration","variable_declaration","interface_declaration","type_alias_declaration","enum_declaration","import_declaration","jsx_element","jsx_self_closing_element","class_definition","function_definition","decorated_definition","import_from_statement","import_statement","preproc_include","method_declaration","constructor_declaration","assignment_expression","pair","class_specifier","struct_specifier","enum_specifier","field_declaration","element","script_element","style_element"]),Zr=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 ea(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
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=Yr(o);if(s)return s;if(!zr.has(o.type))break;o=o.parent}}return null}function Il(e){let n=[];function t(o){for(let s of o.children)Kr.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 Vr(e,n=0,t=!0,o="",s=null,i=12){let a=e.type,r=Yr(e),h=Kr.has(a)||n===0,d=Il(e),c=h&&n>0&&(zr.has(a)&&d.length>0||r!==null&&r===s&&d.length>0),l="",f=o,u=n,p=s;if(h&&!c){let g=e.startPosition.row+1,y=e.endPosition.row+1,m=Ol(a),w=r?`${m} [${r}]`:m;n===0?(l+=`\u{1F4C1} ROOT (Lines: ${g}-${y})
415
- `,f=o):(l+=`${o}${t?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 "}${w} (Lines: ${g}-${y})
416
- `,f+=t?" ":"\u2502 "),u=n+1,p=r}return u>i&&d.length>0?l+=`${f}\u2514\u2500\u2500 ... depth exceeded ...
417
- `:d.forEach((g,y)=>{let m=y===d.length-1;l+=Vr(g,u,c?t&&m:m,f,p,i)}),l}var Ai=async e=>{let n;try{n=I(e).path}catch{return`ERROR: Failed to parse arguments: ${e}`}if(!n)return'ERROR: No file path provided. Use [tool:functions.FileMap(path="...")]';let t=ms.isAbsolute(n)?n:ms.resolve(process.cwd(),n);if(!Mi.existsSync(t))return`ERROR: File not found: ${n}`;let o=ms.extname(t).slice(1).toLowerCase(),s=jr[o];if(!s)return`ERROR: Unsupported file extension: .${o}`;let i=ms.resolve(as,s);if(!Mi.existsSync(i))return`ERROR: Parser for .${o} not found. Please download it in Settings > Other.`;try{let a=Hr.Parser;if(!Gr){let p;try{p=ms.join(ms.dirname(qr.resolve("web-tree-sitter")),"tree-sitter.wasm")}catch{p=ms.join(process.cwd(),"node_modules","web-tree-sitter","tree-sitter.wasm")}await a.init({locateFile:g=>g==="tree-sitter.wasm"||g.endsWith("tree-sitter.wasm")?p:g}),Gr=!0}let r=new a,h=await Hr.Language.load(i);r.setLanguage(h);let d=await Mi.readFile(t,"utf8"),c=d.split(`
418
- `).length,l=12;c>1e4?l=2:c>=8e3?l=3:c>=5e3?l=5:c>=4e3?l=8:c>2e3&&(l=10);let f=r.parse(d),u=Vr(f.rootNode,0,!0," ",null,l);return`\u{1F4C4} File Map for: ${n}
419
- ${u}`}catch(a){let r=a instanceof Error?a.message:typeof a=="object"?JSON.stringify(a):String(a),h=a instanceof Error?`
420
- Stack: ${a.stack}`:"";return`ERROR: Failed to map file: ${r}${h}`}};import qn from"fs";import Jr from"path";var no=async(e,n={})=>{let{method:t,tasks:o,markDone:s}=I(e),i=n.chatId||"default";if(!t)return'ERROR: Missing "method" argument for todo tool (create/append/get).';let a=Jr.join(An,"plan",i),r=Jr.join(a,"todo.md"),h=l=>{if(!l||Array.isArray(l))return l;let f=String(l).trim();if(f.startsWith("[")&&f.endsWith("]")){let u=f.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);return u?u.map(p=>p.slice(1,-1).replace(/\\(.)/g,"$1")):f.slice(1,-1).split(",").map(p=>p.trim()).filter(Boolean)}return l},d=l=>{let f=h(l);return f?(Array.isArray(f)?f:String(f).split(`
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=ea(o);if(s)return s;if(!Zr.has(o.type))break;o=o.parent}}return null}function Nl(e){let n=[];function t(o){for(let s of o.children)Qr.has(s.type)?n.push(s):t(s)}return t(e),n}function Bl(e){return e.replace(/_([a-z])/g,n=>n[1].toUpperCase())}function ta(e,n=0,t=!0,o="",s=null,i=12){let a=e.type,r=ea(e),h=Qr.has(a)||n===0,d=Nl(e),c=h&&n>0&&(Zr.has(a)&&d.length>0||r!==null&&r===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=Bl(a),w=r?`${m} [${r}]`: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=r}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+=ta(g,f,c?t&&m:m,u,p,i)}),l}var Ii=async e=>{let n;try{n=O(e).path}catch{return`ERROR: Failed to parse arguments: ${e}`}if(!n)return'ERROR: No file path provided. Use [tool:functions.FileMap(path="...")]';let t=ms.isAbsolute(n)?n:ms.resolve(process.cwd(),n);if(!vi.existsSync(t))return`ERROR: File not found: ${n}`;let o=ms.extname(t).slice(1).toLowerCase(),s=Yr[o];if(!s)return`ERROR: Unsupported file extension: .${o}`;let i=ms.resolve(as,s);if(!vi.existsSync(i))return`ERROR: Parser for .${o} not found. Please download it in Settings > Other.`;try{let a=Vr.Parser;if(!Jr){let p;try{p=ms.join(ms.dirname(Xr.resolve("web-tree-sitter")),"tree-sitter.wasm")}catch{p=ms.join(process.cwd(),"node_modules","web-tree-sitter","tree-sitter.wasm")}await a.init({locateFile:g=>g==="tree-sitter.wasm"||g.endsWith("tree-sitter.wasm")?p:g}),Jr=!0}let r=new a,h=await Vr.Language.load(i);r.setLanguage(h);let d=await vi.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=r.parse(d),f=ta(u.rootNode,0,!0," ",null,l);return`\u{1F4C4} File Map for: ${n}
419
+ ${f}`}catch(a){let r=a instanceof Error?a.message:typeof a=="object"?JSON.stringify(a):String(a),h=a instanceof Error?`
420
+ Stack: ${a.stack}`:"";return`ERROR: Failed to map file: ${r}${h}`}};import qn from"fs";import na from"path";var no=async(e,n={})=>{let{method:t,tasks:o,markDone:s}=O(e),i=n.chatId||"default";if(!t)return'ERROR: Missing "method" argument for todo tool (create/append/get).';let a=na.join(An,"plan",i),r=na.join(a,"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
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
422
  `)+`
423
- `:""},c=(l,f)=>{if(!f)return{content:l,markedCount:0};let u=h(f),p=(Array.isArray(u)?u:[u]).map(w=>String(w).replace(/^- \[[xX ]\]\s*/i,"").trim()).filter(Boolean),g=l.split(`
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
424
  `),y=0,m=!1;for(let w of p){let x=!1;for(let S=0;S<g.length;S++)if(g[S].includes(w)&&/^- \[\s\]/.test(g[S].trim())){g[S]=g[S].replace("- [ ]","- [x]"),x=!0,m=!0,y++;break}if(!x){for(let S=0;S<g.length;S++)if(g[S].toLowerCase().includes(w.toLowerCase())&&/^- \[\s\]/.test(g[S].trim())){g[S]=g[S].replace("- [ ]","- [x]"),x=!0,m=!0,y++;break}}}return{content:m?g.join(`
425
- `):l,markedCount:y}};try{if(qn.existsSync(a)||qn.mkdirSync(a,{recursive:!0}),t==="create"){if(!o)return'ERROR: Missing "tasks" for create method.';let l=d(o),f=0;if(s){let p=c(l,s);l=p.content,f=p.markedCount}await ft.recordFileChange(r),qn.writeFileSync(r,l,"utf8");let u=l.split(/\r?\n/).map(p=>p.trim()).filter(p=>p.startsWith("- [ ]")||p.startsWith("- [x]")||p.startsWith("- [X]")).length;if(f>0){let p=l.split(/\r?\n/).map(g=>g.trim()).filter(g=>g.startsWith("- [x]")||g.startsWith("- [X]")).length;return`SUCCESS: TASK LIST CREATED (${f} marked done, ${p} completed, ${u-p} left)
426
- ${l}`}return`SUCCESS: TASK LIST CREATED (${u} total)
427
- ${l}`}if(t==="append"){if(!o)return'ERROR: Missing "tasks" for append method.';let l=d(o);await ft.recordFileChange(r),qn.appendFileSync(r,l,"utf8");let f=qn.readFileSync(r,"utf8"),u=f.split(/\r?\n/).map(m=>m.trim()),p=u.filter(m=>m.startsWith("- [ ]")||m.startsWith("- [x]")||m.startsWith("- [X]")).length,g=u.filter(m=>m.startsWith("- [x]")||m.startsWith("- [X]")).length,y=l.split(/\r?\n/).map(m=>m.trim()).filter(m=>m.startsWith("- [ ]")||m.startsWith("- [x]")||m.startsWith("- [X]")).length;return`SUCCESS: TASK APPENDED (${g} completed, ${p-g} left, ${y} added)
428
- ${f}`}if(t==="get"){if(!qn.existsSync(r))return"TODO GET: No task list found for this session.";let l=qn.readFileSync(r,"utf8"),f=0;if(s){let m=c(l,s);m.markedCount>0&&(l=m.content,f=m.markedCount,await ft.recordFileChange(r),qn.writeFileSync(r,l,"utf8"))}let u=l.split(/\r?\n/).map(m=>m.trim()),p=u.filter(m=>m.startsWith("- [ ]")||m.startsWith("- [x]")||m.startsWith("- [X]")).length,g=u.filter(m=>m.startsWith("- [x]")||m.startsWith("- [X]")).length;return`${f>0?`SUCCESS: ${f} TASK(S) MARKED DONE`:"TODO GET"}: ${g} Completed, ${p-g} left
429
- ${l}`}return`ERROR: Unknown method "${t}". Use create, append, or get.`}catch(l){return`ERROR: Todo tool failure: ${l instanceof Error?l.message:String(l)}`}};var vi=async(e,n={})=>{let{runSubagent:t}=await import("./ai-7J7CL56L.js"),o=I(e),s=o.task||o.instruction||o.prompt,i=o.model||null,a=o.tools||null;if(!s)return'ERROR: Missing "task" argument for invokeSync.';let r=null;if(a)try{let d=a.trim();d.startsWith("[")&&d.endsWith("]")&&(d=d.substring(1,d.length-1)),r=d.split(",").map(c=>c.trim().replace(/^["']|["']$/g,"")).filter(Boolean)}catch{}let h=o.title||s.substring(0,30);try{n.onVisualFeedback&&n.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${h}`);let d=await t(s,n,i,r,50);return n.onVisualFeedback&&n.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${h} [COMPLETED]
430
- `),d}catch(d){let{isTerminationSignaled:c}=await import("./ai-7J7CL56L.js"),l=d.message==="Subagent task was cancelled by user."||c();if(n.onVisualFeedback){let f=l?"[CANCELLED]":"[FAILED]";n.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${h} ${f}
431
- `)}return`ERROR: Subagent execution failed: ${d.message}`}};var Xr=async(e,n={})=>{let{runSubagent:t}=await import("./ai-7J7CL56L.js"),o=I(e),s=o.task||o.instruction||o.prompt,i=o.model||null,a=o.title||null,r=o.tools||null;if(!s)return'ERROR: Missing "task" argument for invoke.';let h=null;if(r)try{let m=r.trim();m.startsWith("[")&&m.endsWith("]")&&(m=m.substring(1,m.length-1)),h=m.split(",").map(w=>w.trim().replace(/^["']|["']$/g,"")).filter(Boolean)}catch{}let d=`subagent-${Date.now()}-${Math.floor(Math.random()*1e3)}`,c=null,l=null,f=new Promise((m,w)=>{c=m,l=w}),u={id:d,title:a||s.substring(0,30),task:s,status:"running",startedAt:Date.now(),lastChunkTime:Date.now(),wps:0,questions:[],pendingSteerMessages:[],steer:m=>{m&&u.pendingSteerMessages.push(m)},completionPromise:f,_resolveCompletion:c,_rejectCompletion:l,progress:[]},p={chunks:[],totalWords:0};Ye.push(u),n.onSubagentUpdate&&n.onSubagentUpdate();let g=[],y={...n,taskId:d,onAskMain:async m=>{let w=`q-${Date.now()}-${Math.floor(Math.random()*1e3)}`,x=null,S=new Promise(b=>{x=b}),R={id:w,question:m,answered:!1,answer:null,askedAt:Date.now(),_resolve:x};return u.questions.push(R),u.status="waiting",n.onSubagentUpdate&&n.onSubagentUpdate(),wo(`[SYSTEM] Background subagent "${u.title}" is WAITING FOR YOUR INPUT: "${m}"
425
+ `):l,markedCount:y}};try{if(qn.existsSync(a)||qn.mkdirSync(a,{recursive:!0}),t==="create"){if(!o)return'ERROR: Missing "tasks" for create method.';let l=d(o),u=0;if(s){let p=c(l,s);l=p.content,u=p.markedCount}await ft.recordFileChange(r),qn.writeFileSync(r,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(r),qn.appendFileSync(r,l,"utf8");let u=qn.readFileSync(r,"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(!qn.existsSync(r))return"TODO GET: No task list found for this session.";let l=qn.readFileSync(r,"utf8"),u=0;if(s){let m=c(l,s);m.markedCount>0&&(l=m.content,u=m.markedCount,await ft.recordFileChange(r),qn.writeFileSync(r,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-M2MAGATC.js"),o=O(e),s=o.task||o.instruction||o.prompt,i=o.model||null,a=o.tools||null;if(!s)return'ERROR: Missing "task" argument for invokeSync.';let r=null;if(a)try{let d=a.trim();d.startsWith("[")&&d.endsWith("]")&&(d=d.substring(1,d.length-1)),r=d.split(",").map(c=>c.trim().replace(/^["']|["']$/g,"")).filter(Boolean)}catch{}let h=o.title||s.substring(0,30);try{n.onVisualFeedback&&n.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${h}`);let d=await t(s,n,i,r,50);return n.onVisualFeedback&&n.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${h} [COMPLETED]
430
+ `),d}catch(d){let{isTerminationSignaled:c}=await import("./ai-M2MAGATC.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 sa=async(e,n={})=>{let{runSubagent:t}=await import("./ai-M2MAGATC.js"),o=O(e),s=o.task||o.instruction||o.prompt,i=o.model||null,a=o.title||null,r=o.tools||null;if(!s)return'ERROR: Missing "task" argument for invoke.';let h=null;if(r)try{let m=r.trim();m.startsWith("[")&&m.endsWith("]")&&(m=m.substring(1,m.length-1)),h=m.split(",").map(w=>w.trim().replace(/^["']|["']$/g,"")).filter(Boolean)}catch{}let d=`subagent-${Date.now()}-${Math.floor(Math.random()*1e3)}`,c=null,l=null,u=new Promise((m,w)=>{c=m,l=w}),f={id:d,title:a||s.substring(0,30),task:s,status:"running",startedAt:Date.now(),lastChunkTime:Date.now(),wps:0,questions:[],pendingSteerMessages:[],steer:m=>{m&&f.pendingSteerMessages.push(m)},completionPromise:u,_resolveCompletion:c,_rejectCompletion:l,progress:[]},p={chunks:[],totalWords:0};Ye.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,S=new Promise(k=>{x=k}),R={id:w,question:m,answered:!1,answer:null,askedAt:Date.now(),_resolve:x};return f.questions.push(R),f.status="waiting",n.onSubagentUpdate&&n.onSubagentUpdate(),bo(`[SYSTEM] Background subagent "${f.title}" is WAITING FOR YOUR INPUT: "${m}"
432
432
  Respond using tool: [tool:functions.Answer(id="${d}", answer="...")]
433
- [/SYSTEM]`),await S},onVisualFeedback:m=>{u.lastChunkTime=Date.now();let w=m.replace(/\x1b\[[0-9;]*m/g,""),x=w.match(/[✔✘✗✖🔍📖→➕↻•]\s*([A-Za-z0-9\s-]+)/);x?u.currentTool=x[1].trim():u.currentTool=w,n.onSubagentUpdate&&n.onSubagentUpdate()},onTokenChunk:(m,w)=>{let x=Date.now();if(u.lastChunkTime=x,u.currentTool="Thinking",typeof w=="number"&&w>0){p.totalWords+=w,p.chunks.push({time:x,words:w});let S=x-400;if(p.chunks=p.chunks.filter(R=>R.time>=S),p.chunks.length>0){let R=p.chunks.reduce((T,$)=>T+$.words,0),E=p.chunks[0].time,b=Math.max(.4,(x-E)/1e3);u.wps=Math.round(R/b*10)/10}}n.onSubagentUpdate&&n.onSubagentUpdate()}};return t(s,y,i,h,50,m=>{if(u.status==="cancelled")return;if(m.startsWith("[Subagent Turn")&&g.length>0&&(u.progress.push([...g]),g=[]),m.includes("[Executing Tool]")){let x=m.match(/\[Executing Tool\]\s*([a-zA-Z0-9_]+)/);x&&(!u.currentTool||u.currentTool==="Thinking")&&(u.currentTool=x[1])}let w=m;if(w.startsWith("[Tool Result]")){let x=w.split(`
433
+ [/SYSTEM]`),await S},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 S=x-400;if(p.chunks=p.chunks.filter(R=>R.time>=S),p.chunks.length>0){let R=p.chunks.reduce((T,$)=>T+$.words,0),E=p.chunks[0].time,k=Math.max(.4,(x-E)/1e3);f.wps=Math.round(R/k*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
434
  `);x.length>5&&(w=x.slice(0,4).join(`
435
435
  `)+`
436
- ... [Content/Diff Truncated from Logs] ...`)}g.push(w),n.onSubagentUpdate&&n.onSubagentUpdate()},!0).then(m=>{if(u.status==="cancelled"){u._resolveCompletion&&u._resolveCompletion(m);return}g.length>0&&(u.progress.push([...g]),g=[]),u.status="completed",u.finalAnswer=m,n.onSubagentUpdate&&n.onSubagentUpdate(),wo(`[SYSTEM] Background subagent "${u.title}" (id: ${d}) has FINISHED. Call GetProgress(id="${d}") to see the final result. [/SYSTEM]`),u._resolveCompletion&&u._resolveCompletion(m)}).catch(async m=>{let{isTerminationSignaled:w}=await import("./ai-7J7CL56L.js");if(m.message==="Subagent task was cancelled."||u.status==="cancelled"||w()){u.status="cancelled",g.push("[SUBAGENT CANCELLED] Task was cancelled."),u.progress.push([...g]),n.onSubagentUpdate&&n.onSubagentUpdate(),u._resolveCompletion&&u._resolveCompletion(null);return}g.push(`[SUBAGENT FAILURE] Error: ${m.message}`),u.progress.push([...g]),u.status="failed",u.error=m.message,n.onSubagentUpdate&&n.onSubagentUpdate(),wo(`[SYSTEM] Background subagent "${u.title}" (id: ${d}) FAILED with error: ${m.message}. [/SYSTEM]`),u._rejectCompletion&&u._rejectCompletion(m)}),`SUCCESS: Background subagent started. Task ID: ${d}`};var Ii=async(e,n={})=>{let o=I(e).id;if(!o)return'ERROR: Missing "id" argument for getProgress.';let s=Ye.find(r=>r.id===o);if(!s)return`ERROR: Subagent task with ID [${o}] not found.`;let i=`Subagent Task Status: ${s.status.toUpperCase()}
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(),bo(`[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-M2MAGATC.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(),bo(`[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 Li=async(e,n={})=>{let o=O(e).id;if(!o)return'ERROR: Missing "id" argument for getProgress.';let s=Ye.find(r=>r.id===o);if(!s)return`ERROR: Subagent task with ID [${o}] not found.`;let i=`Subagent Task Status: ${s.status.toUpperCase()}
437
437
  `;if(i+=`Title: ${s.title}
438
438
  `,i+=`Task: ${s.task}
439
439
  `,s.startedAt){let r=Math.floor((Date.now()-s.startedAt)/1e3);i+=`Elapsed Time: ${r}s
@@ -448,7 +448,7 @@ Respond using tool: [tool:functions.Answer(id="${d}", answer="...")]
448
448
  `)}return i+=`
449
449
  Progress Log:
450
450
  `,s.progress.forEach((r,h)=>{i+=`--- Turn ${h+1} ---
451
- `;let c=r.filter(l=>!l.startsWith("[SUBAGENT SUCCESS]")).map(l=>{if(l.startsWith("[Subagent Response]")){let f="[Subagent Response]",p=l.substring(f.length),g="tool:functions.";for(;;){let m=p.toLowerCase().indexOf(g);if(m===-1)break;let w=m,x=!1,S=m-1;for(;S>=0&&/\s/.test(p[S]);)S--;S>=0&&p[S]==="["&&(w=S,x=!0);let R=0,E=!1,b=null,T=m;for(;T<p.length;){let $=p[T];if(!b&&($==="'"||$==='"'||$==="`")?b=$:b&&$===b&&p[T-1]!=="\\"&&(b=null),b||($==="("?(R++,E=!0):$===")"&&R--),E&&R===0&&!b){let C=T;if(x){let k=T+1;for(;k<p.length&&/\s/.test(p[k]);)k++;k<p.length&&p[k]==="]"&&(C=k)}p=p.substring(0,w)+p.substring(C+1);break}if(T++,T===p.length){p=p.substring(0,w);break}}}return f+`
451
+ `;let c=r.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,S=m-1;for(;S>=0&&/\s/.test(p[S]);)S--;S>=0&&p[S]==="["&&(w=S,x=!0);let R=0,E=!1,k=null,T=m;for(;T<p.length;){let $=p[T];if(!k&&($==="'"||$==='"'||$==="`")?k=$:k&&$===k&&p[T-1]!=="\\"&&(k=null),k||($==="("?(R++,E=!0):$===")"&&R--),E&&R===0&&!k){let C=T;if(x){let b=T+1;for(;b<p.length&&/\s/.test(p[b]);)b++;b<p.length&&p[b]==="]"&&(C=b)}p=p.substring(0,w)+p.substring(C+1);break}if(T++,T===p.length){p=p.substring(0,w);break}}}return u+`
452
452
  `+p.trim()}return l.startsWith("[Executing Tool]")&&l.length>256?l.substring(0,256)+"...[truncated from logs]":l});i+=c.join(`
453
453
  `)+`
454
454
 
@@ -458,15 +458,15 @@ ${s.finalAnswer}
458
458
  `),i.replace(/\r\n/g,`
459
459
  `).replace(/\n{3,}/g,`
460
460
 
461
- `).trim().replace(/\[TOOL RESULT\]/gi,"TOOL RESULT:")};var Qr=async(e,n={})=>{let o=I(e).id;if(!o)return'ERROR: Missing "id" argument for cancel.';let s=Ye.find(i=>i.id===o);return s?s.status==="completed"||s.status==="failed"?`INFO: Subagent task with ID [${o}] has already finished with status [${s.status.toUpperCase()}].`:s.status==="cancelled"?`INFO: Subagent task with ID [${o}] is already cancelled.`:(s.status="cancelled",n.onSubagentUpdate&&n.onSubagentUpdate(),`SUCCESS: Subagent task with ID [${o}] has been cancelled.`):`ERROR: Subagent task with ID [${o}] not found.`};import wt from"fs-extra";import St from"path";var Ll=["node_modules","dist","bin","logs",".git",".fluxflow","secret",".gemini",".agents","tmp","temp","build","out","snapshots"];async function so(e,n=e){let t={},o=await wt.readdir(e,{withFileTypes:!0}).catch(()=>[]);for(let s of o){if(Ll.includes(s.name))continue;let i=St.join(e,s.name),a=St.relative(n,i).replace(/\\/g,"/");if(s.isDirectory()){let r=await so(i,n);Object.assign(t,r)}else{let r=await wt.stat(i).catch(()=>null);r&&(t[a]={size:r.size,mtime:r.mtimeMs})}}return t}async function Zr(e,n){await wt.ensureDir(e);for(let t of Object.keys(n)){let o=St.join(process.cwd(),t),s=St.join(e,t);await wt.ensureDir(St.dirname(s)),await wt.copyFile(o,s).catch(()=>{})}}async function Oi(e,n,t=null,o=null){if(!await wt.pathExists(e))return;o||(o=e);let s=await wt.readdir(e,{withFileTypes:!0}).catch(()=>[]);for(let i of s){let a=St.join(e,i.name),r=St.join(n,i.name);if(i.isDirectory())await Oi(a,r,t,o);else{let h=St.relative(o,a).replace(/\\/g,"/"),d=await wt.pathExists(r);d&&await wt.chmod(r,438).catch(()=>{}),await wt.ensureDir(St.dirname(r));let c=await wt.copyFile(a,r).then(()=>!0).catch(()=>!1);await wt.chmod(r,438).catch(()=>{}),t&&(c?d?t.replaced++:t.restored++:t.failed.push(h))}}}var Kn={async takeInitialSnapshot(e){try{let n=St.join(An,"snapshots",e);await wt.remove(n).catch(()=>{}),await wt.ensureDir(n);let t=await so(process.cwd());await Zr(St.join(n,"initial"),t);let o=X(dn,{});o[e]={initialManifest:t,currentManifest:t,checkpoints:[{id:"initial",timestamp:new Date().toISOString(),newFiles:[],modifiedFiles:[],deletedFiles:[],toolsUsed:[]}]},he(dn,o)}catch{}},async recordTurnDelta(e,n,t=[]){try{let o=X(dn,{}),s=o[e];if(!s)return;let i=s.currentManifest||s.initialManifest,a=await so(process.cwd()),r=[],h=[],d=[];for(let[l,f]of Object.entries(a)){let u=i[l];u?(u.size!==f.size||u.mtime!==f.mtime)&&h.push(l):r.push(l)}for(let l of Object.keys(i))a[l]||d.push(l);let c=[...r,...h];if(c.length>0||d.length>0){let l={};for(let u of c)l[u]=a[u];let f=St.join(An,"snapshots",e,`turn_${n}`);await Zr(f,l)}s.checkpoints.push({id:`turn_${n}`,timestamp:new Date().toISOString(),newFiles:r,modifiedFiles:h,deletedFiles:d,toolsUsed:t}),s.currentManifest=a,he(dn,o)}catch{}},async getCheckpoints(e){try{let t=X(dn,{})[e];return t?t.checkpoints||[]:[]}catch{return[]}},async rollbackToCheckpoint(e,n){try{let t=X(dn,{}),o=t[e];if(!o)throw new Error("No session active for Advance Rollback.");let s=o.checkpoints||[],i=s.findIndex(c=>c.id===n);if(i===-1)throw new Error(`Checkpoint [${n}] not found.`);let a=St.join(An,"snapshots",e),r={restored:0,replaced:0,failed:[]},h=await so(process.cwd());for(let c of Object.keys(h)){let l=St.join(process.cwd(),c);await wt.chmod(l,438).catch(()=>{}),await wt.remove(l).catch(()=>{})}let d=St.join(a,"initial");await Oi(d,process.cwd(),r,d);for(let c=1;c<=i;c++){let l=s[c],f=St.join(a,l.id);if(await Oi(f,process.cwd(),r,f),l.deletedFiles&&l.deletedFiles.length>0)for(let u of l.deletedFiles){let p=St.join(process.cwd(),u);await wt.chmod(p,438).catch(()=>{}),await wt.remove(p).catch(()=>{})}}return o.checkpoints=s.slice(0,i+1),o.currentManifest=await so(process.cwd()),he(dn,t),{checkpointId:n,stats:r}}catch(t){throw new Error(`Rollback failed: ${t.message}`)}},async getLatestFileChanges(e){try{let t=X(dn,{})[e];if(!t||!t.checkpoints||t.checkpoints.length===0)return{newFiles:[],modifiedFiles:[],deletedFiles:[]};let o=t.checkpoints[t.checkpoints.length-1];return{newFiles:o.newFiles||[],modifiedFiles:o.modifiedFiles||[],deletedFiles:o.deletedFiles||[]}}catch{return{newFiles:[],modifiedFiles:[],deletedFiles:[]}}},async cleanup(e){try{let n=St.join(An,"snapshots",e);await wt.remove(n).catch(()=>{});let t=X(dn,{});t[e]&&(delete t[e],he(dn,t))}catch{}}};var Li=async(e,n={})=>{let t=I(e),o=t.method,s=t.id,i=n.chatId;if(!n.systemSettings?.advanceRollback)return"ERROR: Advance Rollback feature is currently disabled in settings under Security. Tell user to enable it.";if(!i)return"ERROR: No active chat transaction found for rollback.";if(o==="getCheckpoint"){let r=await Kn.getCheckpoints(i);if(r.length===0)return"No checkpoints available.";let h={write_file:"WriteFile",update_file:"PatchFile",view_file:"ReadFile",read_folder:"ReadFolder",exec_command:"Run",web_search:"WebSearch",web_scrape:"WebScrape",search_keyword:"SearchKeyword",CodeSearch:"SearchKeyword",code_search:"SearchKeyword",write_pdf:"WritePDF",write_docx:"WriteDoc",generate_image:"GenerateImage",file_map:"FileMap",todo:"Todo",goal:"Goal",Goal:"Goal",await:"Await",ask:"Ask",ask_user:"Ask",invoke:"Invoke",invokesync:"InvokeSync",getprogress:"GetProgress",cancel:"Cancel",emergency_rollback:"EmergencyRollback",emergencyrollback:"EmergencyRollback"},d=l=>h[l]||h[l.toLowerCase()]||l,c=`Available checkpoints for rollback:
461
+ `).trim().replace(/\[TOOL RESULT\]/gi,"TOOL RESULT:")};var oa=async(e,n={})=>{let o=O(e).id;if(!o)return'ERROR: Missing "id" argument for cancel.';let s=Ye.find(i=>i.id===o);return s?s.status==="completed"||s.status==="failed"?`INFO: Subagent task with ID [${o}] has already finished with status [${s.status.toUpperCase()}].`:s.status==="cancelled"?`INFO: Subagent task with ID [${o}] is already cancelled.`:(s.status="cancelled",n.onSubagentUpdate&&n.onSubagentUpdate(),`SUCCESS: Subagent task with ID [${o}] has been cancelled.`):`ERROR: Subagent task with ID [${o}] not found.`};import wt from"fs-extra";import St from"path";var Ul=["node_modules","dist","bin","logs",".git",".fluxflow","secret",".gemini",".agents","tmp","temp","build","out","snapshots"];async function so(e,n=e){let t={},o=await wt.readdir(e,{withFileTypes:!0}).catch(()=>[]);for(let s of o){if(Ul.includes(s.name))continue;let i=St.join(e,s.name),a=St.relative(n,i).replace(/\\/g,"/");if(s.isDirectory()){let r=await so(i,n);Object.assign(t,r)}else{let r=await wt.stat(i).catch(()=>null);r&&(t[a]={size:r.size,mtime:r.mtimeMs})}}return t}async function ia(e,n){await wt.ensureDir(e);for(let t of Object.keys(n)){let o=St.join(process.cwd(),t),s=St.join(e,t);await wt.ensureDir(St.dirname(s)),await wt.copyFile(o,s).catch(()=>{})}}async function Pi(e,n,t=null,o=null){if(!await wt.pathExists(e))return;o||(o=e);let s=await wt.readdir(e,{withFileTypes:!0}).catch(()=>[]);for(let i of s){let a=St.join(e,i.name),r=St.join(n,i.name);if(i.isDirectory())await Pi(a,r,t,o);else{let h=St.relative(o,a).replace(/\\/g,"/"),d=await wt.pathExists(r);d&&await wt.chmod(r,438).catch(()=>{}),await wt.ensureDir(St.dirname(r));let c=await wt.copyFile(a,r).then(()=>!0).catch(()=>!1);await wt.chmod(r,438).catch(()=>{}),t&&(c?d?t.replaced++:t.restored++:t.failed.push(h))}}}var zn={async takeInitialSnapshot(e){try{let n=St.join(An,"snapshots",e);await wt.remove(n).catch(()=>{}),await wt.ensureDir(n);let t=await so(process.cwd());await ia(St.join(n,"initial"),t);let o=X(dn,{});o[e]={initialManifest:t,currentManifest:t,checkpoints:[{id:"initial",timestamp:new Date().toISOString(),newFiles:[],modifiedFiles:[],deletedFiles:[],toolsUsed:[]}]},he(dn,o)}catch{}},async recordTurnDelta(e,n,t=[]){try{let o=X(dn,{}),s=o[e];if(!s)return;let i=s.currentManifest||s.initialManifest,a=await so(process.cwd()),r=[],h=[],d=[];for(let[l,u]of Object.entries(a)){let f=i[l];f?(f.size!==u.size||f.mtime!==u.mtime)&&h.push(l):r.push(l)}for(let l of Object.keys(i))a[l]||d.push(l);let c=[...r,...h];if(c.length>0||d.length>0){let l={};for(let f of c)l[f]=a[f];let u=St.join(An,"snapshots",e,`turn_${n}`);await ia(u,l)}s.checkpoints.push({id:`turn_${n}`,timestamp:new Date().toISOString(),newFiles:r,modifiedFiles:h,deletedFiles:d,toolsUsed:t}),s.currentManifest=a,he(dn,o)}catch{}},async getCheckpoints(e){try{let t=X(dn,{})[e];return t?t.checkpoints||[]:[]}catch{return[]}},async rollbackToCheckpoint(e,n){try{let t=X(dn,{}),o=t[e];if(!o)throw new Error("No session active for Advance Rollback.");let s=o.checkpoints||[],i=s.findIndex(c=>c.id===n);if(i===-1)throw new Error(`Checkpoint [${n}] not found.`);let a=St.join(An,"snapshots",e),r={restored:0,replaced:0,failed:[]},h=await so(process.cwd());for(let c of Object.keys(h)){let l=St.join(process.cwd(),c);await wt.chmod(l,438).catch(()=>{}),await wt.remove(l).catch(()=>{})}let d=St.join(a,"initial");await Pi(d,process.cwd(),r,d);for(let c=1;c<=i;c++){let l=s[c],u=St.join(a,l.id);if(await Pi(u,process.cwd(),r,u),l.deletedFiles&&l.deletedFiles.length>0)for(let f of l.deletedFiles){let p=St.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 so(process.cwd()),he(dn,t),{checkpointId:n,stats:r}}catch(t){throw new Error(`Rollback failed: ${t.message}`)}},async getLatestFileChanges(e){try{let t=X(dn,{})[e];if(!t||!t.checkpoints||t.checkpoints.length===0)return{newFiles:[],modifiedFiles:[],deletedFiles:[]};let o=t.checkpoints[t.checkpoints.length-1];return{newFiles:o.newFiles||[],modifiedFiles:o.modifiedFiles||[],deletedFiles:o.deletedFiles||[]}}catch{return{newFiles:[],modifiedFiles:[],deletedFiles:[]}}},async cleanup(e){try{let n=St.join(An,"snapshots",e);await wt.remove(n).catch(()=>{});let t=X(dn,{});t[e]&&(delete t[e],he(dn,t))}catch{}}};var Di=async(e,n={})=>{let t=O(e),o=t.method,s=t.id,i=n.chatId;if(!n.systemSettings?.advanceRollback)return"ERROR: Advance Rollback feature is currently disabled in settings under Security. Tell user to enable it.";if(!i)return"ERROR: No active chat transaction found for rollback.";if(o==="getCheckpoint"){let r=await zn.getCheckpoints(i);if(r.length===0)return"No checkpoints available.";let h={write_file:"WriteFile",update_file:"PatchFile",view_file:"ReadFile",read_folder:"ReadFolder",exec_command:"Run",web_search:"WebSearch",web_scrape:"WebScrape",search_keyword:"SearchKeyword",CodeSearch:"SearchKeyword",code_search:"SearchKeyword",write_pdf:"WritePDF",write_docx:"WriteDoc",generate_image:"GenerateImage",file_map:"FileMap",todo:"Todo",goal:"Goal",Goal:"Goal",await:"Await",ask:"Ask",ask_user:"Ask",invoke:"Invoke",invokesync:"InvokeSync",getprogress:"GetProgress",cancel:"Cancel",emergency_rollback:"EmergencyRollback",emergencyrollback:"EmergencyRollback"},d=l=>h[l]||h[l.toLowerCase()]||l,c=`Available checkpoints for rollback:
462
462
 
463
463
  `;for(let l of r)if(l.id==="initial")c+=`--- Initial State (id: initial) ---
464
464
  Tools Used: User Prompted for task
465
465
 
466
- `;else{let f=l.id.replace("turn_",""),u=l.toolsUsed&&l.toolsUsed.length>0?l.toolsUsed.map(d).join(", "):"None";c+=`--- Turn ${f} (id: ${l.id}) ---
467
- Tools Used: ${u}
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
468
 
469
- `}return c.trim()}else if(o==="forceRevert"){if(!s)return"ERROR: Missing required parameter 'id' for forceRevert.";try{let r=await Kn.rollbackToCheckpoint(i,s),{checkpointId:h,stats:d}=r,c=d.restored+d.replaced+d.failed.length,l=`SUCCESS: Repository rolled back to checkpoint [${h}].
469
+ `}return c.trim()}else if(o==="forceRevert"){if(!s)return"ERROR: Missing required parameter 'id' for forceRevert.";try{let r=await zn.rollbackToCheckpoint(i,s),{checkpointId:h,stats:d}=r,c=d.restored+d.replaced+d.failed.length,l=`SUCCESS: Repository rolled back to checkpoint [${h}].
470
470
 
471
471
  `;return l+=`Stats:
472
472
  `,l+=` Restored : ${d.restored} file${d.restored!==1?"s":""} (new to workspace)
@@ -475,57 +475,57 @@ Tools Used: ${u}
475
475
  ${d.failed.join(`
476
476
  `)}`),l+=`
477
477
  \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500-
478
- `,l+=` Total : ${c} file${c!==1?"s":""} processed`,l}catch(r){return`ERROR: ${r.message}`}}else return`ERROR: Invalid method "${o}". Use "getCheckpoint" or "forceRevert".`};var Ps=async(e,n={})=>{let t=I(e),o=t.id,s=parseInt(t.timeout||t.time||"120",10);if((isNaN(s)||s<=0)&&(s=120),s>300&&(s=300),!o)return t.time?(await new Promise(h=>setTimeout(h,s*1e3)),`SUCCESS: Waited for ${s}s.`):'ERROR: Missing "id" argument for Await.';let i=Ye.find(h=>h.id===o);if(!i)return`ERROR: Subagent task with ID [${o}] not found.`;if(i.status==="completed")return`SUCCESS: Subagent task [${o}] completed.
478
+ `,l+=` Total : ${c} file${c!==1?"s":""} processed`,l}catch(r){return`ERROR: ${r.message}`}}else return`ERROR: Invalid method "${o}". Use "getCheckpoint" or "forceRevert".`};var Ps=async(e,n={})=>{let t=O(e),o=t.id,s=parseInt(t.timeout||t.time||"120",10);if((isNaN(s)||s<=0)&&(s=120),s>300&&(s=300),!o)return t.time?(await new Promise(h=>setTimeout(h,s*1e3)),`SUCCESS: Waited for ${s}s.`):'ERROR: Missing "id" argument for Await.';let i=Ye.find(h=>h.id===o);if(!i)return`ERROR: Subagent task with ID [${o}] not found.`;if(i.status==="completed")return`SUCCESS: Subagent task [${o}] completed.
479
479
  Final Answer:
480
480
  ${i.finalAnswer||"(No output)"}`;if(i.status==="failed")return`ERROR: Subagent task [${o}] failed.
481
481
  Error: ${i.error||"Unknown error"}`;if(i.status==="cancelled")return`INFO: Subagent task [${o}] was cancelled.`;let a,r=new Promise(h=>{a=setTimeout(()=>{h({type:"timeout"})},s*1e3)});try{let h=await Promise.race([i.completionPromise.then(()=>({type:"completion"})),r]);return clearTimeout(a),h.type==="timeout"?`TIMEOUT: Subagent task [${o}] is still running (status: ${i.status.toUpperCase()}) after ${s}s. You can continue other work or call Await again.`:i.status==="completed"?`SUCCESS: Subagent task [${o}] completed.
482
482
  Final Answer:
483
483
  ${i.finalAnswer||"(No output)"}`:i.status==="failed"?`ERROR: Subagent task [${o}] failed.
484
- Error: ${i.error||"Unknown error"}`:i.status==="cancelled"?`INFO: Subagent task [${o}] was cancelled.`:`INFO: Subagent task [${o}] status changed to ${i.status.toUpperCase()}.`}catch(h){return clearTimeout(a),`ERROR: Exception while awaiting subagent [${o}]: ${h.message}`}};var Ds=async(e,n={})=>{let t=I(e),o=t.id,s=t.answer||t.response;if(!o)return'ERROR: Missing "id" argument for Answer.';if(!s)return'ERROR: Missing "answer" argument for Answer.';let i=Ye.find(r=>r.id===o);if(!i)return`ERROR: Subagent task with ID [${o}] not found.`;if(!i.questions||i.questions.length===0)return`INFO: Subagent task [${o}] has no pending questions.`;let a=i.questions.filter(r=>!r.answered);return a.length===0?`INFO: Subagent task [${o}] has no unanswered questions.`:(a.forEach(r=>{r.answered=!0,r.answer=s,r.answeredAt=Date.now(),r._resolve&&r._resolve(s)}),i.status="running",n.onSubagentUpdate&&n.onSubagentUpdate(),`SUCCESS: Answer provided to subagent task [${o}]. Subagent execution resumed.`)};var oo=async(e,n={})=>{let t=I(e),o=t.id,s=t.message||t.instruction||t.text||t.prompt;if(!o)return'ERROR: Missing "id" argument for Steer.';if(!s)return'ERROR: Missing "message" argument for Steer.';let i=Ye.find(a=>a.id===o);return i?i.status==="completed"||i.status==="failed"||i.status==="cancelled"?`ERROR: Cannot steer subagent task [${o}] because it has already finished with status [${i.status.toUpperCase()}].`:(typeof i.steer=="function"?i.steer(s):(i.pendingSteerMessages||(i.pendingSteerMessages=[]),i.pendingSteerMessages.push(s)),n.onSubagentUpdate&&n.onSubagentUpdate(),`SUCCESS: Steering instruction injected into subagent task [${o}]. It will be processed on the subagent's turn.`):`ERROR: Subagent task with ID [${o}] not found.`};import{mouse as on,keyboard as mn,Button as io,Key as D,Point as ro,clipboard as Pl}from"@nut-tree-fork/nut-js";on.config.autoDelayMs=50;mn.config.autoDelayMs=50;async function ea(){try{await mn.releaseKey(D.LeftControl,D.RightControl,D.LeftAlt,D.RightAlt,D.LeftShift,D.RightShift,D.LeftSuper,D.RightSuper)}catch{}}async function On(e,n,t={}){let o=await Ks(n);if(!o&&(e==="move"||e==="click"||e==="drag"))return`ERROR: Invalid target location specified: ${JSON.stringify(n)}`;try{switch(e.toLowerCase()){case"move":return await on.setPosition(new ro(o.x,o.y)),`SUCCESS: Moved mouse to grid target ${typeof n=="string"?n:`(${o.x}, ${o.y})`}`;case"click":{await on.setPosition(new ro(o.x,o.y));let s=t.button==="right"?io.RIGHT:t.button==="middle"?io.MIDDLE:io.LEFT;return t.clickType==="double"?await on.doubleClick(s):await on.click(s),`SUCCESS: ${t.clickType||"Single"} clicked ${t.button||"left"} button at ${typeof n=="string"?n:`(${o.x}, ${o.y})`}`}case"drag":{let s=await Ks(t.from||n),i=await Ks(t.to);return!s||!i?'ERROR: Drag requires valid "from" and "to" target coordinates/grid codes.':(await on.setPosition(new ro(s.x,s.y)),await on.pressButton(io.LEFT),await on.setPosition(new ro(i.x,i.y)),await on.releaseButton(io.LEFT),`SUCCESS: Dragged mouse from (${s.x}, ${s.y}) to (${i.x}, ${i.y})`)}case"scroll":{let s=o||await Ks({x:640,y:360});s&&(await on.setPosition(new ro(s.x,s.y)),await new Promise(h=>setTimeout(h,60)));let i=parseInt(t.amount,10);(isNaN(i)||i<=0)&&(i=5);let a=i>50?Math.min(20,Math.max(1,Math.round(i/100))):Math.min(20,i),r=t.direction==="up";for(let h=0;h<a;h++)r?await on.scrollUp(120):await on.scrollDown(120),await new Promise(d=>setTimeout(d,20));return`SUCCESS: Scrolled ${t.direction||"down"} (${a} notches${o?` at target (${o.x}, ${o.y})`:" at screen center"})`}default:return`ERROR: Unsupported mouse action "${e}"`}}catch(s){return`ERROR: Mouse action failed: ${s.message}`}}var ta={enter:D.Enter,return:D.Return,escape:D.Escape,esc:D.Escape,backspace:D.Backspace,tab:D.Tab,space:D.Space,up:D.Up,down:D.Down,left:D.Left,right:D.Right,ctrl:D.LeftControl,control:D.LeftControl,alt:D.LeftAlt,shift:D.LeftShift,cmd:D.LeftCmd,win:D.LeftWin,meta:D.LeftWin,super:D.LeftSuper,a:D.A,b:D.B,c:D.C,d:D.D,e:D.E,f:D.F,g:D.G,h:D.H,i:D.I,j:D.J,k:D.K,l:D.L,m:D.M,n:D.N,o:D.O,p:D.P,q:D.Q,r:D.R,s:D.S,t:D.T,u:D.U,v:D.V,w:D.W,x:D.X,y:D.Y,z:D.Z,0:D.Num0,1:D.Num1,2:D.Num2,3:D.Num3,4:D.Num4,5:D.Num5,6:D.Num6,7:D.Num7,8:D.Num8,9:D.Num9,f1:D.F1,f2:D.F2,f3:D.F3,f4:D.F4,f5:D.F5,f6:D.F6,f7:D.F7,f8:D.F8,f9:D.F9,f10:D.F10,f11:D.F11,f12:D.F12},na=e=>{if(!e)return;let n=String(e).toLowerCase().trim();if(ta[n]!==void 0)return ta[n];if(D[e]!==void 0)return D[e];if(D[n.toUpperCase()]!==void 0)return D[n.toUpperCase()]};async function zn(e,n,t={}){try{switch(e.toLowerCase()){case"type":{if(typeof n!="string")return"ERROR: Type action requires a valid string input";await ea(),await Pl.setContent(n);let s=process.platform==="darwin"?D.LeftSuper:D.LeftControl;return await mn.pressKey(s,D.V),await mn.releaseKey(s,D.V),await ea(),t.autoPressEnter?(await new Promise(i=>setTimeout(i,50)),await mn.type(D.Enter),`SUCCESS: Typed text input ("${n.length>20?n.substring(0,20)+"...":n}") and pressed Enter`):`SUCCESS: Typed text input ("${n.length>20?n.substring(0,20)+"...":n}")`}case"key_press":{let o=na(n);return o===void 0?`ERROR: Unknown key name "${n}"`:(await mn.type(o),`SUCCESS: Pressed key ${n}`)}case"key_combination":{if(!Array.isArray(n))return'ERROR: key_combination requires an array of keys (e.g. ["ctrl", "c"])';let o=n.map(s=>na(s)).filter(s=>s!==void 0);return o.length===0?"ERROR: Invalid key combination":(await mn.pressKey(...o),await mn.releaseKey(...o),`SUCCESS: Executed key combination [${n.join(" + ")}]`)}case"clear_input":return await mn.pressKey(D.LeftControl,D.A),await mn.releaseKey(D.LeftControl,D.A),await mn.type(D.Backspace),"SUCCESS: Cleared active text input (Select All + Backspace)";default:return`ERROR: Unsupported keyboard action "${e}"`}}catch(o){return`ERROR: Keyboard action failed: ${o.message}`}}var ao=async(e,n={})=>{let t=I(e),o=t.action||t.type||t.cmd,s=t.target||t.grid||t.gridCode||t.location||t.input;if(!o)return'ERROR: Missing required "action" argument for computer_action (e.g. move, click, drag, scroll, type, key_press, key_combination).';let i=o.toLowerCase();if(i.startsWith("mouse_")||["move","click","drag","scroll"].includes(i)){let a=i.replace("mouse_","");return await On(a,s,{button:t.button,clickType:t.clickType||t.type,from:t.from,to:t.to,direction:t.direction,amount:t.amount?parseInt(t.amount,10):void 0})}if(i.startsWith("key_")||i==="type"||i==="press"){let a=i;i==="press"&&(a="key_press");let r=t.autoPressEnter===!0||t.autoPressEnter==="true"||t.enter===!0||t.enter==="true";return await zn(a,s||t.text||t.keys,{...t,autoPressEnter:r})}return`ERROR: Unrecognized action "${o}". Supported actions: move, click, drag, scroll, type, key_press, key_combination.`};import sa from"screenshot-desktop";import vo from"sharp";import{mouse as Dl}from"@nut-tree-fork/nut-js";function Fl(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Nl(e,n,t=1/0){if(e===n)return 0;if(e.length===0)return n.length;if(n.length===0)return e.length;if(Math.abs(e.length-n.length)>t)return t+1;let o=Array.from({length:n.length+1},(s,i)=>i);for(let s=1;s<=e.length;s++){let i=[s],a=s;for(let r=1;r<=n.length;r++){let h=e[s-1]===n[r-1]?0:1,d=Math.min(i[r-1]+1,o[r]+1,o[r-1]+h);i.push(d),d<a&&(a=d)}if(o=i,a>t)return t+1}return o[n.length]}function Bl(e){return e<=2?0:e<=5?1:e<=10?2:Math.min(3,Math.floor(e*.25))}async function oa(e,n=3){let t=await vo(e).metadata();return vo(e).resize(Math.round(t.width*n),Math.round(t.height*n),{kernel:"lanczos3"}).greyscale().normalise().toBuffer()}function Ul(e){if(!e)return{words:[],lines:[]};let n=[],t=new Map;for(let s of e.split(`
485
- `)){let i=s.split(" ");if(i.length<12||parseInt(i[0])!==5)continue;let r=i[2],h=i[3],d=i[4],c=parseInt(i[6]),l=parseInt(i[7]),f=parseInt(i[8]),u=parseInt(i[9]),p=parseFloat(i[10]),g=i.slice(11).join(" ").trim();if(!g||p<0)continue;let y={x0:c,y0:l,x1:c+f,y1:l+u},m={text:g,confidence:p,bbox:y};n.push(m);let w=`${r}_${h}_${d}`;t.has(w)||t.set(w,{words:[],bbox:{x0:1/0,y0:1/0,x1:-1/0,y1:-1/0}});let x=t.get(w);x.words.push(m),x.bbox.x0=Math.min(x.bbox.x0,y.x0),x.bbox.y0=Math.min(x.bbox.y0,y.y0),x.bbox.x1=Math.max(x.bbox.x1,y.x1),x.bbox.y1=Math.max(x.bbox.y1,y.y1)}let o=[];for(let s of t.values())s.words.length>0&&o.push({text:s.words.map(i=>i.text).join(" "),bbox:s.bbox,words:s.words});return{words:n,lines:o}}function Wl(e){if(!(e.words&&e.words.length>0)){if(e.blocks&&e.blocks.length>0){e.words=[],e.lines=[];for(let n of e.blocks)for(let t of n.paragraphs||[])for(let o of t.lines||[]){o.bbox&&e.lines.push(o);for(let s of o.words||[])s.bbox&&e.words.push(s)}if(e.words.length>0)return}if(e.tsv){let n=Ul(e.tsv);e.words=n.words,e.lines=n.lines}}}function ia(e,n,t=0,o=0,s=1){Wl(e);let i=r=>({x0:Math.round(r.x0/s)+t,y0:Math.round(r.y0/s)+o,x1:Math.round(r.x1/s)+t,y1:Math.round(r.y1/s)+o}),a=[];if(e.lines&&e.lines.length>0)for(let r of e.lines){let h=r.text?r.text.toLowerCase().trim():"";if(!h||!r.bbox||!(h===n||new RegExp(`\\b${Fl(n)}\\b`,"i").test(h)))continue;let c=r.words||(e.words?e.words.filter(p=>p.bbox&&p.bbox.x0>=r.bbox.x0-5&&p.bbox.x1<=r.bbox.x1+5&&p.bbox.y0>=r.bbox.y0-5&&p.bbox.y1<=r.bbox.y1+5):[]),l=n.split(/\s+/),f=l.map(p=>p.replace(/[^a-z0-9]/g,"")).join(" "),u=!1;if(c.length>0)for(let p=0;p<=c.length-l.length;p++){let g=c.slice(p,p+l.length),y=g.map(m=>(m.text||"").toLowerCase().trim().replace(/[^a-z0-9]/g,"")).join(" ");if(y===f||y.includes(f)){let m={x0:Math.min(...g.map(w=>w.bbox.x0)),y0:Math.min(...g.map(w=>w.bbox.y0)),x1:Math.max(...g.map(w=>w.bbox.x1)),y1:Math.max(...g.map(w=>w.bbox.y1))};a.push(i(m)),u=!0}}u||a.push(i(r.bbox))}if(a.length===0&&e.words&&e.words.length>0)for(let r of e.words){let h=r.text?r.text.toLowerCase().trim().replace(/[^a-z0-9]/g,""):"",d=n.replace(/[^a-z0-9]/g,"");h===d&&r.bbox&&a.push(i(r.bbox))}if(a.length===0&&e.words&&e.words.length>0){let r=Bl(n.length);for(let h of e.words){let d=h.text?h.text.toLowerCase().trim():"";d.length>=3&&Math.abs(d.length-n.length)<=r&&Nl(d,n,r)<=r&&h.bbox&&a.push(i(h.bbox))}}return a}function ra(e,n){let t=null,o=1/0;for(let s of e){let i=Math.round((s.x0+s.x1)/2),a=Math.round((s.y0+s.y1)/2),r=n.x>=s.x0&&n.x<=s.x1&&n.y>=s.y0&&n.y<=s.y1,h=Math.hypot(i-n.x,a-n.y),d=r?0:h;d<o&&(o=d,t={x:i,y:a,dist:h,containsPoint:r,bbox:s})}return t}function jl(e,n,t,o){let a=Math.ceil(e/4),r=Math.ceil(n/2),h=[];for(let d=0;d<2;d++)for(let c=0;c<4;c++){let l=c*a,f=d*r,u=Math.min(a,e-l),p=Math.min(r,n-f),g=l+u/2,y=f+p/2,m=t>=l&&t<l+u&&o>=f&&o<f+p;h.push({x0:l,y0:f,w:u,h:p,cx:g,cy:y,containsTarget:m})}return h.sort((d,c)=>{if(d.containsTarget)return-1;if(c.containsTarget)return 1;let l=Math.hypot(d.cx-t,d.cy-o),f=Math.hypot(c.cx-t,c.cy-o);return l-f})}var Pi=async(e,n={})=>{let t=I(e),o=t.gridId||t.grid||t.coordinate||t.target||t.id,s=(t.type||t.clickType||"single").toLowerCase(),i=(t.button||"left").toLowerCase(),a=t.intendedClickText||t.text||"";if(!o&&!a)return'ERROR: Missing required "gridId" parameter for Click tool.';let r=o;if(a)try{let{createWorker:c}=await import("tesseract.js"),l=o?dr(o):null,{getActiveDisplay:f}=await import("./screen_grid-IKEV7A6U.js"),u=await f(),p={format:"png"};try{let v=await sa.listDisplays();v&&v.length>0&&(p={format:"png",screen:(v[u]||v[0]).id})}catch{}let g=await sa(p),y=await vo(g).metadata(),m=y.width||1920,w=y.height||1080,x=l?{x:Math.round(l.x*(m/1280)),y:Math.round(l.y*(w/720))}:{x:m/2,y:w/2},S=await import("fs-extra"),{CU_CACHE_DIR:R}=await import("./paths-R3DD7CRF.js");S.ensureDirSync(R);let E=a.toLowerCase().trim(),b=await c("eng",1,{cachePath:R}),T=await oa(g,2),{data:$}=await b.recognize(T,{},{tsv:!0,blocks:!0}),C=l?140:400,k=null,O="";if($&&$.text){let v=ia($,E,0,0,2);if(v.length>0){let L=ra(v,x);L&&(L.containsPoint||L.dist<=C)&&(k=L,O="full-screen OCR")}}if(!k){let v=jl(m,w,x.x,x.y);for(let L=0;L<v.length;L++){let N=v[L],j=await vo(g).extract({left:N.x0,top:N.y0,width:N.w,height:N.h}).toBuffer(),V=await oa(j,3),{data:oe}=await b.recognize(V,{},{tsv:!0,blocks:!0});if(!oe||!oe.text)continue;let Ie=ia(oe,E,N.x0,N.y0,3);if(Ie.length>0){k=ra(Ie,x),O=`tile ${L+1} OCR (${N.containsTarget?"target tile":`offset ${N.x0},${N.y0}`})`;break}}}if(await b.terminate(),k){let v={x:Math.round(k.x*(1280/m)),y:Math.round(k.y*(720/w))};return`${await On("click",v,{button:i,clickType:s})} (${O} for "${a}" at ${Math.round(k.dist)}px distance)`}}catch{}let h=null;try{h=await Dl.getPosition()}catch{}return await On("click",r,{button:i,clickType:s})};var Di=async(e,n={})=>{let t=I(e),o=t.fromGridId||t.from||t.start,s=t.toGridId||t.to||t.end;return!o||!s?'ERROR: Drag requires both "fromGridId" and "toGridId" parameters.':await On("drag",o,{from:o,to:s})};var Fi=async(e,n={})=>{let t=I(e),o=(t.direction||"down").toLowerCase(),s=t.amount?parseInt(t.amount,10):6,i=t.gridId||t.grid||t.coordinate||t.target||t.id||null;return await On("scroll",i,{direction:o,amount:s})};var Io=async(e,n={})=>{let t=I(e),o=t.text||t.input||t.value||"",s=t.autoPressEnter===!0||t.autoPressEnter==="true"||t.enter===!0||t.enter==="true";return o==null?'ERROR: Missing required "text" parameter for KeyboardTyping tool.':await zn("type",String(o),{autoPressEnter:s})};var Oo=async(e,n={})=>{let t=I(e),o=t.key||t.keys||t.input||t.shortcut;if(!o)return'ERROR: Missing required "key" parameter for KeyPress tool.';let s=String(o).trim().toLowerCase();if(s==="clearinput"||s==="clear_input"||s==="clear")return await zn("clear_input");if(s.includes(";")||s.includes("+")){let i=s.split(/[;+]/).map(a=>a.trim()).filter(Boolean);return await zn("key_combination",i)}return await zn("key_press",s)};var Lo=async(e,n={})=>"SUCCESS: Screen recapture requested. The latest gridded screenshot is provided for your next decision.";var Hl={web_search:li,web_scrape:ci,memory:di,chat:fi,view_file:Qs,write_file:ui,update_file:yi,exec_command:ti,read_folder:xi,write_pdf:Si,write_docx:Ti,search_keyword:eo,generate_image:Ci,saveSummary:to,addMemScore:Ls,file_map:Ai,todo:no,Todo:no,goal:no,Goal:no,invokeSync:vi,invoke:Xr,getProgress:Ii,cancel:Qr,awaitSubagent:Ps,answerSubagent:Ds,steerSubagent:oo,computer_action:ao,computer_use:ao,ComputerAction:ao,ComputerUse:ao,click:Pi,Click:Pi,drag:Di,Drag:Di,scroll:Fi,Scroll:Fi,keyboard_typing:Io,KeyboardTyping:Io,keyboardtyping:Io,key_press:Oo,KeyPress:Oo,keypress:Oo,recapture_screen:Lo,RecaptureScreen:Lo,recapturescreen:Lo,invoke_sync:vi,get_progress:Ii,await_subagent:Ps,answer_subagent:Ds,steer_subagent:oo,steer:oo,Steer:oo,ask:bi,Ask:bi,WebSearch:li,WebScrape:ci,ReadFile:Qs,ReadFolder:xi,WriteFile:ui,PatchFile:yi,WritePDF:Si,WriteDoc:Ti,Run:ti,SearchKeyword:eo,CodeSearch:eo,code_search:eo,Memory:di,Chat:fi,GenerateImage:Ci,saveSumary:to,SaveSummary:to,SaveSumary:to,add_mem_score:Ls,AddMemScore:Ls,addMemoryScore:Ls,AddMemoryScore:Ls,FileMap:Ai,answer:Ds,Answer:Ds,AnswerSubagent:Ds,await:Ps,Await:Ps,AwaitSubagent:Ps,EmergencyRollback:Li,emergency_rollback:Li},lo=async(e,n,t={})=>{let o=t.mode?t.mode.toLowerCase():"flux",s=e.toLowerCase(),a=["memory","chat","savesummary","addmemscore","add_mem_score","ask","web_search","web_scrape","await"].some(c=>s.includes(c))||s==="ask",h=["click","drag","scroll","keyboardtyping","keyboard_typing","keypress","key_press","recapturescreen","recapture_screen","computer"].some(c=>s.includes(c));if(!a){if(o==="flow"){if(!(s.includes("write_pdf")||s.includes("write_docx")||s.includes("generate_image")))return`ERROR: Tool [${e}] is a Workspace Tool and NOT available in Flow mode. Tell user to switch (\`/mode flux\`) to use this tool.`}else if(o==="icu"){if(!h)return`ERROR: Tool [${e}] is not available in Computer Use mode. ICU mode only supports Computer Use tools (Click, Drag, Scroll, KeyboardTyping, KeyPress, RecaptureScreen).`}else if(s.includes("write_pdf")||s.includes("write_docx")||s.includes("generate_image"))return`ERROR: Tool [${e}] is not available in ${t.mode||"Flux"} mode. Tell user to switch (\`/mode flow\`) for document generation.`}let d=Hl[e];if(!d)return`ERROR: Tool [${e}] not found in registry.`;try{return await d(n,t)}catch(c){let l=c instanceof Error?c.message:String(c);return`ERROR: Execution failed for [${e}]: ${l}`}};import Q from"path";import ve from"fs";import Gl from"gradient-string";var Ni=["I have a regex for your problems.","Your terminal, my kingdom.","Blowing on the cartridge helps. Probably.","Don't panic. I have the towel.","Logic is the start of wisdom.","Try to exit Vim? Good luck.","I speak fluent Terminal.","The cake is a lie. This code is not.","I have no bugs, just surprise features.","Rewriting in Rust... just for fun.","Coffee in, clean commits out.","The magic smoke stays inside today.","A semicolon short of a miracle.","One does not simply code without a bug.","Keep it simple. Keep it terminal.","Regex: now you have two problems.","I dream in binary.","Root access or bust.","Wait for the dial-up tone. Just kidding.","I take the 'labor' out of collab.","My other process is a TARDIS.","Calculated response: 42.","Ponder the orb. Ponder the code.","Less talk, more flow.","Elegance in every byte.","Build something the world is not ready for.","Your wishes, my tool calls.","I act in Flux. I think in Flow.","Syntax error in the universe. Please fix.","Your project, my obsession.","I am not a bot, I am an architect.","Digital spirits consulted. They say: Ship it.","Reticulate splines. Engage humor.","Code like poetry. Run like water.","Minimalism is the ultimate flex.","The truth is in the logs.","Follow the white rabbit.","There is no spoon. Only code.","Binary is the only language I trust.","I have a good feeling about this.","Pew pew! Lasers charged.","Divide by zero? Not today.","Search for the correct USB orientation...","I've got a fever, and the only cure is more code.","The code gremlins are on our side.","My favorite command? Yours.","Stay hungry. Stay active.","Momentum is your best friend.","Lead the flow. Don't chase it.","A fresh batch of bytes. Hot and ready.","I orchestrate the ones and zeros.","Smart enough to help. Humble enough to ask.","Think twice. Code once.","Pure intent. Pure execution.","Small steps. Massive impact.","Your terminal is a canvas.","Efficiency is my second name.","I have seen things you people wouldn't believe.","Let the thoughts marinate.","The best feature? The one you don't need.","Precision is the only perfection.","Stay focused. Stay terminal.","Silence is the best debugger.","Erase the debt. Commit the code.","Velocity meets stability.","Ship it. Improve it. Repeat.","Build tomorrow, right now.","Turn logic into reality.","The best way to predict the future is to build it.","Break barriers, not builds.","Fuel the next breakthrough.","Momentum is key.","Terminal vibes only.","Your digital co-pilot is ready.","Partner in code. Partner in crime.","I speak in semicolons.","Ready for the next great idea.","Just a moment. In the zone.","Polishing the algorithms. Hold tight.","Craft a masterpiece today.","Debug the universe. Start here.","Warp speed engaged. Almost.","The cake is not a lie. It's just loading.","Finish the Kessel Run in 12 parsecs.","Do a barrel roll!","Waiting for the respawn.","Press Start to continue.","Herding digital cats... done.","The hamsters are fast today.","Tasting the snozberries.","I go for speed. I go for flow.","Real life or just fantasy?","Poking the bear... gently.","Ensure the magic smoke stays inside.","Try turning it off and on again.","Construct additional pylons.","New line? Ctrl+J is your friend.","Release the HypnoDrones.","Push the button, Frank.","My other loading screen is even funnier.","Pretty sure a cat walked on my keyboard.","Recalibrate the humor-o-meter.","Summon the code gremlins.","I've seen your browser history. Just kidding.","Charge the laser... pew pew!","Dividing by zero... just for a sec.","Looking for an adult supervisor. Found none.","Make it go beep boop.","Buffering... for effect.","Entangle quantum particles... complete.","Polishing the chrome on my algorithms.","Are you not entertained?","Just waiting for the dial-up tone.","Reboot the humor module.","Defragment memories. Check.","Optimizing for ludicrous speed.","Swapping bits. Don't tell the bytes.","Garbage collected. I am back.","Assembling the interwebs.","Converting coffee to logic.","Update syntax for reality.","Rewire the synapses.","Greasin' the cogs.","Engage the improbability drive.","Channel the Force.","Align the stars. Respond now.","The cake is a lie. The prompt is real.","I'm Feeling Lucky.","Shipping awesomeness.","Navigating the slime mold.","Consult digital spirits.","Ask the magic conch shell.","One moment. Optimizing humor.","Shuffling punchlines.","Compiling brilliance.","Summon the cloud of wisdom.","Prepare to dazzle.","Hold tight. Crafting a response.","Tuning the algorithms.","Following the white rabbit... again.","The truth is in here. Somewhere.","Herding cats is my day job.","Distracting you with this phrase.","Almost there. Probably.","Rickrolling my creator. Don't tell.","Slapping the bass.","Is this real life?","Ponder the orb. Type the prompt.","Thoughtful gaze initiated.","Computer's favorite snack? Microchips.","Why Java? Because I don't C#.","Charging the laser... wait for it.","Dividing by zero... just kidding!","Adult supervision not found. Proceed.","Beep boop. I'm a real boy.","Wait for the respawn.","Finish the run. Ship the code.","Fiddling with character creation.","Just a moment. Finding a meme.","Pressing A to continue.","Loading wit.exe.","Pre-heating the servers.","Calibrate flux capacitor.","Channeling the Force.","Aligning the stars.","The truth is in the code.","Don't panic.","Blowing on the cartridge.","Doing a barrel roll!","Respawning in 3... 2... 1...","The cake is a lie.","Fiddling with character settings.","Finding a suitable pun.","Distracting with wit.","Almost ready.","Hamsters on speed today.","Patting Cloudy on the head.","Rickrolling the logs.","Slapping the code.","Got a good feeling about this.","Poking the prompt.","Researching latest memes.","Making it more witty.","Thinking... hmmm.","Fish with no eyes? Fsh.","Broken pencil? Pointless.","Percussive maintenance applied.","USB orientation: 3rd try's the charm.","Rust rewrite in 3... 2...","Exiting Vim... someday.","Spinning the hamster wheel.","Not a bug. Unplanned feature.","Engage.","I'll be back.","Machine spirit consulted.","Letting the thoughts marinate.","Orb pondered.","Thoughtful gaze engaged.","Charging the laser...","Making it go beep.","Buffering...","Quantum particles entangled.","Polishing the chrome.","Entertained yet?","Gremlins summoned.","Dial-up tone finished.","Humor meter recalibrated.","Cat on keyboard. Sending help.","Enhancing...","Turn it off and on again.","Constructing pylons.","HypnoDrones released.","Pushing the button."];var aa=[{name:"Cyan Cyberpunk",text:"cyan",textMuted:"#4da6b8",textDim:"#2d6d7a",textInverted:"black",border:"cyan",borderMuted:"#1a5966",borderDim:"#0f3840",bg:void 0,cardBg:"#061e24",highlightBg:"#092b33",activeBg:"#0e3e4a",inputBg:"#092b33",inputBorder:"#092b33",inputText:"cyan",inputPlaceholder:"#2d6d7a",inputPrompt:"cyan",codeBg:"#020d10",codeBorder:"#1a5966",userMsgBg:"#092b33",userMsgBorder:"#092b33",userMsgText:"cyan",diffRemovalBg:"#3a0c1a",diffAdditionBg:"#0c3a32",diffRemovalText:"#ff4d88",diffAdditionText:"#00ffaa",diffRemovalHighlightColor:"#ff1a66",diffRemovalHighlightBg:"#590022",diffAdditionHighlightColor:"#00ffcc",diffAdditionHighlightBg:"#00593b",diffRemovalNum:"#ff4d88",diffAdditionNum:"#00ffaa",diffRemovalPrefix:"#ff1a66",diffAdditionPrefix:"#00ffcc",primary:"cyan",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"cyan",statusOff:"#2d6d7a",logoTextAnsi:"\x1B[1;36m",logoBodyAnsi:"\x1B[36m",logoMutedAnsi:"\x1B[90m",logoGradient:["#00ffff","#0088ff"]},{name:"Magenta Vaporwave",text:"magenta",textMuted:"#c451d6",textDim:"#7d2b8a",textInverted:"black",border:"magenta",borderMuted:"#5e1b69",borderDim:"#3b0f42",bg:void 0,cardBg:"#240729",highlightBg:"#310938",activeBg:"#470e52",inputBg:"#310938",inputBorder:"#310938",inputText:"magenta",inputPlaceholder:"#7d2b8a",inputPrompt:"magenta",codeBg:"#100312",codeBorder:"#5e1b69",userMsgBg:"#310938",userMsgBorder:"#310938",userMsgText:"magenta",diffRemovalBg:"#3a0c20",diffAdditionBg:"#200c3a",diffRemovalText:"#ff4d94",diffAdditionText:"#aa4dff",diffRemovalHighlightColor:"#ff1a75",diffRemovalHighlightBg:"#59002b",diffAdditionHighlightColor:"#bb66ff",diffAdditionHighlightBg:"#3b0059",diffRemovalNum:"#ff4d94",diffAdditionNum:"#aa4dff",diffRemovalPrefix:"#ff1a75",diffAdditionPrefix:"#bb66ff",primary:"magenta",secondary:"cyan",accent:"purple",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"magenta",statusOff:"#7d2b8a",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ff00ff","#8800ff"]},{name:"Glitch Matrix",text:"#00ff41",textMuted:"#00b32d",textDim:"#00661a",textInverted:"black",border:"#00ff41",borderMuted:"#008020",borderDim:"#004d13",bg:void 0,cardBg:"#0d1f0d",highlightBg:"#122912",activeBg:"#1c3e1c",inputBg:"#122912",inputBorder:"#122912",inputText:"#00ff41",inputPlaceholder:"#00b32d",inputPrompt:"#ffff00",codeBg:"#040a04",codeBorder:"#008020",userMsgBg:"#122912",userMsgBorder:"#122912",userMsgText:"#00ff41",diffRemovalBg:"#3a001a",diffAdditionBg:"#003a10",diffRemovalText:"#ff0055",diffAdditionText:"#00ff66",diffRemovalHighlightColor:"#ff0033",diffRemovalHighlightBg:"#59001b",diffAdditionHighlightColor:"#33ff88",diffAdditionHighlightBg:"#005918",diffRemovalNum:"#ff0055",diffAdditionNum:"#00ff66",diffRemovalPrefix:"#ff0033",diffAdditionPrefix:"#33ff88",primary:"#00ff41",secondary:"yellow",accent:"cyan",success:"#00ff41",warning:"yellow",danger:"red",info:"cyan",statusOn:"#00ff41",statusOff:"#00661a",logoTextAnsi:"\x1B[1;32m",logoBodyAnsi:"\x1B[32m",logoMutedAnsi:"\x1B[90m",logoGradient:["#00ff41","#ffff00"]},{name:"Warm Sunset",text:"#ffaa55",textMuted:"#cc8844",textDim:"#885522",textInverted:"black",border:"#ff9933",borderMuted:"#aa6622",borderDim:"#663311",bg:void 0,cardBg:"#24180f",highlightBg:"#2e1e12",activeBg:"#422c1b",inputBg:"#2e1e12",inputBorder:"#2e1e12",inputText:"#ffaa55",inputPlaceholder:"#885522",inputPrompt:"#ff7733",codeBg:"#120c08",codeBorder:"#aa6622",userMsgBg:"#2e1e12",userMsgBorder:"#2e1e12",userMsgText:"#ffaa55",diffRemovalBg:"#3d120c",diffAdditionBg:"#3a2e0c",diffRemovalText:"#ff5544",diffAdditionText:"#ffcc33",diffRemovalHighlightColor:"#ff3322",diffRemovalHighlightBg:"#591108",diffAdditionHighlightColor:"#ffee44",diffAdditionHighlightBg:"#594400",diffRemovalNum:"#ff5544",diffAdditionNum:"#ffcc33",diffRemovalPrefix:"#ff3322",diffAdditionPrefix:"#ffee44",primary:"#ffaa55",secondary:"#ff7733",accent:"magenta",success:"#ffcc33",warning:"#ff7733",danger:"#ff3322",info:"#ffaa55",statusOn:"#ffaa55",statusOff:"#885522",logoTextAnsi:"\x1B[1;33m",logoBodyAnsi:"\x1B[33m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ff9933","#ff0055"]},{name:"Sakura Blossom",text:"#ffc0e0",textMuted:"#d98cb3",textDim:"#804d66",textInverted:"black",border:"#ff99cc",borderMuted:"#aa4d7a",borderDim:"#662647",bg:void 0,cardBg:"#291320",highlightBg:"#331826",activeBg:"#472235",inputBg:"#331826",inputBorder:"#331826",inputText:"#ffc0e0",inputPlaceholder:"#804d66",inputPrompt:"#ff99cc",codeBg:"#140a10",codeBorder:"#aa4d7a",userMsgBg:"#331826",userMsgBorder:"#331826",userMsgText:"#ffc0e0",diffRemovalBg:"#3e0c1b",diffAdditionBg:"#1b3e2b",diffRemovalText:"#ff6699",diffAdditionText:"#66ffb3",diffRemovalHighlightColor:"#ff3377",diffRemovalHighlightBg:"#590022",diffAdditionHighlightColor:"#33ff99",diffAdditionHighlightBg:"#00592e",diffRemovalNum:"#ff6699",diffAdditionNum:"#66ffb3",diffRemovalPrefix:"#ff3377",diffAdditionPrefix:"#33ff99",primary:"#ffc0e0",secondary:"#ff99cc",accent:"magenta",success:"#66ffb3",warning:"yellow",danger:"#ff3377",info:"#ff99cc",statusOn:"#ffc0e0",statusOff:"#804d66",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ffb3d9","#ff3399"]},{name:"Radioactive Slime",text:"#ccff00",textMuted:"#99cc00",textDim:"#669900",textInverted:"#0a0f00",border:"#ccff00",borderMuted:"#99cc00",borderDim:"#669900",bg:void 0,cardBg:"#0f1400",highlightBg:"#1a2400",activeBg:"#2a3b00",inputBg:"#1a2400",inputBorder:"#1a2400",inputText:"#ccff00",inputPlaceholder:"#669900",inputPrompt:"#cc00ff",codeBg:"#050a00",codeBorder:"#99cc00",userMsgBg:"#1a2400",userMsgBorder:"#1a2400",userMsgText:"#ccff00",diffRemovalBg:"#2a0033",diffAdditionBg:"#0f3300",diffRemovalText:"#ff00cc",diffAdditionText:"#00ff33",diffRemovalHighlightColor:"#ff33cc",diffRemovalHighlightBg:"#4d0066",diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:"#1a6600",diffRemovalNum:"#ff00cc",diffAdditionNum:"#00ff33",diffRemovalPrefix:"#ff33cc",diffAdditionPrefix:"#33ff66",primary:"#ccff00",secondary:"#cc00ff",accent:"#ff00cc",success:"#00ff33",warning:"#ffcc00",danger:"#ff0033",info:"#00ccff",statusOn:"#ccff00",statusOff:"#669900",logoTextAnsi:"\x1B[1;38;5;190m",logoBodyAnsi:"\x1B[38;5;190m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ccff00","#cc00ff"]},{name:"Cosmic Void",text:"#f0f8ff",textMuted:"#a6aeb5",textDim:"#5e656e",textInverted:"#010103",border:"#f0f8ff",borderMuted:"#a6aeb5",borderDim:"#5e656e",bg:void 0,cardBg:"#05030d",highlightBg:"#0b081a",activeBg:"#171133",inputBg:"#0b081a",inputBorder:"#0b081a",inputText:"#f0f8ff",inputPlaceholder:"#5e656e",inputPrompt:"#ff007f",codeBg:"#020108",codeBorder:"#a6aeb5",userMsgBg:"#0b081a",userMsgBorder:"#0b081a",userMsgText:"#f0f8ff",diffRemovalBg:"#2e0a29",diffAdditionBg:"#091c33",diffRemovalText:"#ff33a6",diffAdditionText:"#33d6ff",diffRemovalHighlightColor:"#ff66c2",diffRemovalHighlightBg:"#5c1452",diffAdditionHighlightColor:"#66e0ff",diffAdditionHighlightBg:"#123866",diffRemovalNum:"#ff33a6",diffAdditionNum:"#33d6ff",diffRemovalPrefix:"#ff66c2",diffAdditionPrefix:"#66e0ff",primary:"#f0f8ff",secondary:"#ff007f",accent:"#9d00ff",success:"#33d6ff",warning:"#ffcc00",danger:"#ff0040",info:"#9d00ff",statusOn:"#f0f8ff",statusOff:"#5e656e",logoTextAnsi:"\x1B[1;38;5;231m",logoBodyAnsi:"\x1B[38;5;231m",logoMutedAnsi:"\x1B[38;5;240m",logoGradient:["#ffffff","#9d00ff"]},{name:"Magma Eruption",text:"#ff4d00",textMuted:"#cc3d00",textDim:"#802600",textInverted:"#0d0300",border:"#ff4d00",borderMuted:"#cc3d00",borderDim:"#802600",bg:void 0,cardBg:"#1a0600",highlightBg:"#260a00",activeBg:"#401100",inputBg:"#260a00",inputBorder:"#260a00",inputText:"#ff4d00",inputPlaceholder:"#802600",inputPrompt:"#ffcc00",codeBg:"#080200",codeBorder:"#cc3d00",userMsgBg:"#260a00",userMsgBorder:"#260a00",userMsgText:"#ff4d00",diffRemovalBg:"#2e0a0a",diffAdditionBg:"#1f1400",diffRemovalText:"#ff3333",diffAdditionText:"#ffaa00",diffRemovalHighlightColor:"#ff6666",diffRemovalHighlightBg:"#5c1414",diffAdditionHighlightColor:"#ffcc33",diffAdditionHighlightBg:"#3d2900",diffRemovalNum:"#ff3333",diffAdditionNum:"#ffaa00",diffRemovalPrefix:"#ff6666",diffAdditionPrefix:"#ffcc33",primary:"#ff4d00",secondary:"#ffcc00",accent:"#ff0040",success:"#ffaa00",warning:"#ffff00",danger:"#ff0000",info:"#ff8800",statusOn:"#ff4d00",statusOff:"#802600",logoTextAnsi:"\x1B[1;38;5;202m",logoBodyAnsi:"\x1B[38;5;202m",logoMutedAnsi:"\x1B[38;5;236m",logoGradient:["#ff4d00","#ff0000"]}],co={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 Po=null;var la=(e="Dark")=>{let n;e==="Mystery"||e==="Chaos"?(Po||(Po=aa[Math.floor(Math.random()*aa.length)]),n={...Po,id:"Mystery"}):(Po=null,co[e]?n=co[e]:e==="GitHub"?n=co["GitHub Dark"]:e==="Transparent"?n=co["Transparent Dark"]:n=co.Dark);let t=n.codeText||n.secondary||n.info||n.logoGradient&&n.logoGradient[0]||"cyan";return{...n,codeText:t}};var ql=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",xp=(e=2)=>{let n=ql();return n==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)},bp=(e="...",n="Loading...",t="Dark")=>{let o=Ni[Math.floor(Math.random()*Ni.length)],s=la(t),i=s.logoTextAnsi,a=s.logoBodyAnsi,r=s.logoMutedAnsi,h="\x1B[0m",d=[" \u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2588\u2588\u2588\u2591 "," \u2588\u2588\u2588\u2591 "," \u2588\u2588\u2588\u2591 "," \u2591\u2591\u2591 "],c=s.logoGradient||["#0077ff","#ff00ff"],l=Gl(c).multiline(d.join(`
484
+ Error: ${i.error||"Unknown error"}`:i.status==="cancelled"?`INFO: Subagent task [${o}] was cancelled.`:`INFO: Subagent task [${o}] status changed to ${i.status.toUpperCase()}.`}catch(h){return clearTimeout(a),`ERROR: Exception while awaiting subagent [${o}]: ${h.message}`}};var Ds=async(e,n={})=>{let t=O(e),o=t.id,s=t.answer||t.response;if(!o)return'ERROR: Missing "id" argument for Answer.';if(!s)return'ERROR: Missing "answer" argument for Answer.';let i=Ye.find(r=>r.id===o);if(!i)return`ERROR: Subagent task with ID [${o}] not found.`;if(!i.questions||i.questions.length===0)return`INFO: Subagent task [${o}] has no pending questions.`;let a=i.questions.filter(r=>!r.answered);return a.length===0?`INFO: Subagent task [${o}] has no unanswered questions.`:(a.forEach(r=>{r.answered=!0,r.answer=s,r.answeredAt=Date.now(),r._resolve&&r._resolve(s)}),i.status="running",n.onSubagentUpdate&&n.onSubagentUpdate(),`SUCCESS: Answer provided to subagent task [${o}]. Subagent execution resumed.`)};var oo=async(e,n={})=>{let t=O(e),o=t.id,s=t.message||t.instruction||t.text||t.prompt;if(!o)return'ERROR: Missing "id" argument for Steer.';if(!s)return'ERROR: Missing "message" argument for Steer.';let i=Ye.find(a=>a.id===o);return i?i.status==="completed"||i.status==="failed"||i.status==="cancelled"?`ERROR: Cannot steer subagent task [${o}] because it has already finished with status [${i.status.toUpperCase()}].`:(typeof i.steer=="function"?i.steer(s):(i.pendingSteerMessages||(i.pendingSteerMessages=[]),i.pendingSteerMessages.push(s)),n.onSubagentUpdate&&n.onSubagentUpdate(),`SUCCESS: Steering instruction injected into subagent task [${o}]. It will be processed on the subagent's turn.`):`ERROR: Subagent task with ID [${o}] not found.`};import{mouse as on,keyboard as mn,Button as io,Key as P,Point as ro,clipboard as Wl}from"@nut-tree-fork/nut-js";on.config.autoDelayMs=50;mn.config.autoDelayMs=50;async function ra(){try{await mn.releaseKey(P.LeftControl,P.RightControl,P.LeftAlt,P.RightAlt,P.LeftShift,P.RightShift,P.LeftSuper,P.RightSuper)}catch{}}async function On(e,n,t={}){let o=await zs(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 ro(o.x,o.y)),`SUCCESS: Moved mouse to grid target ${typeof n=="string"?n:`(${o.x}, ${o.y})`}`;case"click":{await on.setPosition(new ro(o.x,o.y));let s=t.button==="right"?io.RIGHT:t.button==="middle"?io.MIDDLE:io.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 zs(t.from||n),i=await zs(t.to);return!s||!i?'ERROR: Drag requires valid "from" and "to" target coordinates/grid codes.':(await on.setPosition(new ro(s.x,s.y)),await on.pressButton(io.LEFT),await on.setPosition(new ro(i.x,i.y)),await on.releaseButton(io.LEFT),`SUCCESS: Dragged mouse from (${s.x}, ${s.y}) to (${i.x}, ${i.y})`)}case"scroll":{let s=o||await zs({x:640,y:360});s&&(await on.setPosition(new ro(s.x,s.y)),await new Promise(h=>setTimeout(h,60)));let i=parseInt(t.amount,10);(isNaN(i)||i<=0)&&(i=5);let a=i>50?Math.min(20,Math.max(1,Math.round(i/100))):Math.min(20,i),r=t.direction==="up";for(let h=0;h<a;h++)r?await on.scrollUp(120):await on.scrollDown(120),await new Promise(d=>setTimeout(d,20));return`SUCCESS: Scrolled ${t.direction||"down"} (${a} notches${o?` at target (${o.x}, ${o.y})`:" at screen center"})`}default:return`ERROR: Unsupported mouse action "${e}"`}}catch(s){return`ERROR: Mouse action failed: ${s.message}`}}var aa={enter:P.Enter,return:P.Return,escape:P.Escape,esc:P.Escape,backspace:P.Backspace,tab:P.Tab,space:P.Space,up:P.Up,down:P.Down,left:P.Left,right:P.Right,ctrl:P.LeftControl,control:P.LeftControl,alt:P.LeftAlt,shift:P.LeftShift,cmd:P.LeftCmd,win:P.LeftWin,meta:P.LeftWin,super:P.LeftSuper,a:P.A,b:P.B,c:P.C,d:P.D,e:P.E,f:P.F,g:P.G,h:P.H,i:P.I,j:P.J,k:P.K,l:P.L,m:P.M,n:P.N,o:P.O,p:P.P,q:P.Q,r:P.R,s:P.S,t:P.T,u:P.U,v:P.V,w:P.W,x:P.X,y:P.Y,z:P.Z,0:P.Num0,1:P.Num1,2:P.Num2,3:P.Num3,4:P.Num4,5:P.Num5,6:P.Num6,7:P.Num7,8:P.Num8,9:P.Num9,f1:P.F1,f2:P.F2,f3:P.F3,f4:P.F4,f5:P.F5,f6:P.F6,f7:P.F7,f8:P.F8,f9:P.F9,f10:P.F10,f11:P.F11,f12:P.F12},la=e=>{if(!e)return;let n=String(e).toLowerCase().trim();if(aa[n]!==void 0)return aa[n];if(P[e]!==void 0)return P[e];if(P[n.toUpperCase()]!==void 0)return P[n.toUpperCase()]};async function Kn(e,n,t={}){try{switch(e.toLowerCase()){case"type":{if(typeof n!="string")return"ERROR: Type action requires a valid string input";await ra(),await Wl.setContent(n);let s=process.platform==="darwin"?P.LeftSuper:P.LeftControl;return await mn.pressKey(s,P.V),await mn.releaseKey(s,P.V),await ra(),t.autoPressEnter?(await new Promise(i=>setTimeout(i,50)),await mn.type(P.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=la(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=>la(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(P.LeftControl,P.A),await mn.releaseKey(P.LeftControl,P.A),await mn.type(P.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 ao=async(e,n={})=>{let t=O(e),o=t.action||t.type||t.cmd,s=t.target||t.grid||t.gridCode||t.location||t.input;if(!o)return'ERROR: Missing required "action" argument for computer_action (e.g. move, click, drag, scroll, type, key_press, key_combination).';let i=o.toLowerCase();if(i.startsWith("mouse_")||["move","click","drag","scroll"].includes(i)){let a=i.replace("mouse_","");return await On(a,s,{button:t.button,clickType:t.clickType||t.type,from:t.from,to:t.to,direction:t.direction,amount:t.amount?parseInt(t.amount,10):void 0})}if(i.startsWith("key_")||i==="type"||i==="press"){let a=i;i==="press"&&(a="key_press");let r=t.autoPressEnter===!0||t.autoPressEnter==="true"||t.enter===!0||t.enter==="true";return await Kn(a,s||t.text||t.keys,{...t,autoPressEnter:r})}return`ERROR: Unrecognized action "${o}". Supported actions: move, click, drag, scroll, type, key_press, key_combination.`};import ua from"screenshot-desktop";import co from"sharp";import ca from"fs-extra";import da from"path";import"@nut-tree-fork/nut-js";async function Fi(e,n,t){if(!(!process.env.SHOW_DEBUG_GRID&&!process.env.DEBUG_OCR))try{let o=da.resolve(process.cwd(),"screenshots",e);await ca.ensureDir(o),await ca.writeFile(da.join(o,n),t)}catch{}}function jl(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Hl(e,n,t=1/0){if(e===n)return 0;if(e.length===0)return n.length;if(n.length===0)return e.length;if(Math.abs(e.length-n.length)>t)return t+1;let o=Array.from({length:n.length+1},(s,i)=>i);for(let s=1;s<=e.length;s++){let i=[s],a=s;for(let r=1;r<=n.length;r++){let h=e[s-1]===n[r-1]?0:1,d=Math.min(i[r-1]+1,o[r]+1,o[r-1]+h);i.push(d),d<a&&(a=d)}if(o=i,a>t)return t+1}return o[n.length]}function Gl(e){return e<=4?0:e<=8?1:2}async function Ni(e,n=3){let t=await co(e).metadata();return co(e).resize(Math.round(t.width*n),Math.round(t.height*n),{kernel:"lanczos3"}).greyscale().normalise().toBuffer()}function ql(e){if(!e)return{words:[],lines:[]};let n=[],t=new Map;for(let s of e.split(`
485
+ `)){let i=s.split(" ");if(i.length<12||parseInt(i[0])!==5)continue;let r=i[2],h=i[3],d=i[4],c=parseInt(i[6]),l=parseInt(i[7]),u=parseInt(i[8]),f=parseInt(i[9]),p=parseFloat(i[10]),g=i.slice(11).join(" ").trim();if(!g||p<0)continue;let y={x0:c,y0:l,x1:c+u,y1:l+f},m={text:g,confidence:p,bbox:y};n.push(m);let w=`${r}_${h}_${d}`;t.has(w)||t.set(w,{words:[],bbox:{x0:1/0,y0:1/0,x1:-1/0,y1:-1/0}});let x=t.get(w);x.words.push(m),x.bbox.x0=Math.min(x.bbox.x0,y.x0),x.bbox.y0=Math.min(x.bbox.y0,y.y0),x.bbox.x1=Math.max(x.bbox.x1,y.x1),x.bbox.y1=Math.max(x.bbox.y1,y.y1)}let o=[];for(let s of t.values())s.words.length>0&&o.push({text:s.words.map(i=>i.text).join(" "),bbox:s.bbox,words:s.words});return{words:n,lines:o}}function zl(e){if(!(e.words&&e.words.length>0)){if(e.blocks&&e.blocks.length>0){e.words=[],e.lines=[];for(let n of e.blocks)for(let t of n.paragraphs||[])for(let o of t.lines||[]){o.bbox&&e.lines.push(o);for(let s of o.words||[])s.bbox&&e.words.push(s)}if(e.words.length>0)return}if(e.tsv){let n=ql(e.tsv);e.words=n.words,e.lines=n.lines}}}function Bi(e,n,t=0,o=0,s=1){zl(e);let i=r=>({x0:Math.round(r.x0/s)+t,y0:Math.round(r.y0/s)+o,x1:Math.round(r.x1/s)+t,y1:Math.round(r.y1/s)+o}),a=[];if(e.lines&&e.lines.length>0)for(let r of e.lines){let h=r.text?r.text.toLowerCase().trim():"";if(!h||!r.bbox||!(h===n||new RegExp(`\\b${jl(n)}\\b`,"i").test(h)))continue;let c=r.words||(e.words?e.words.filter(p=>p.bbox&&p.bbox.x0>=r.bbox.x0-5&&p.bbox.x1<=r.bbox.x1+5&&p.bbox.y0>=r.bbox.y0-5&&p.bbox.y1<=r.bbox.y1+5):[]),l=n.split(/\s+/),u=l.map(p=>p.replace(/[^a-z0-9]/g,"")).join(" "),f=!1;if(c.length>0)for(let p=0;p<=c.length-l.length;p++){let g=c.slice(p,p+l.length),y=g.map(m=>(m.text||"").toLowerCase().trim().replace(/[^a-z0-9]/g,"")).join(" ");if(y===u||y.includes(u)){let m={x0:Math.min(...g.map(w=>w.bbox.x0)),y0:Math.min(...g.map(w=>w.bbox.y0)),x1:Math.max(...g.map(w=>w.bbox.x1)),y1:Math.max(...g.map(w=>w.bbox.y1))};a.push(i(m)),f=!0}}f||a.push(i(r.bbox))}if(a.length===0&&e.words&&e.words.length>0)for(let r of e.words){let h=r.text?r.text.toLowerCase().trim().replace(/[^a-z0-9]/g,""):"",d=n.replace(/[^a-z0-9]/g,"");h===d&&r.bbox&&a.push(i(r.bbox))}if(a.length===0&&e.words&&e.words.length>0){let r=Gl(n.length);for(let h of e.words){let d=h.text?h.text.toLowerCase().trim():"";d.length>=3&&Math.abs(d.length-n.length)<=r&&Hl(d,n,r)<=r&&h.bbox&&a.push(i(h.bbox))}}return a}function Ui(e,n){let t=null,o=1/0;for(let s of e){let i=Math.round((s.x0+s.x1)/2),a=Math.round((s.y0+s.y1)/2),r=n.x>=s.x0&&n.x<=s.x1&&n.y>=s.y0&&n.y<=s.y1,h=Math.hypot(i-n.x,a-n.y),d=r?0:h;d<o&&(o=d,t={x:i,y:a,dist:h,containsPoint:r,bbox:s})}return t}function Kl(e,n,t,o){let a=Math.ceil(e/4),r=Math.ceil(n/2),h=[];for(let d=0;d<2;d++)for(let c=0;c<4;c++){let l=c*a,u=d*r,f=Math.min(a,e-l),p=Math.min(r,n-u),g=l+f/2,y=u+p/2,m=t>=l&&t<l+f&&o>=u&&o<u+p;h.push({x0:l,y0:u,w:f,h:p,cx:g,cy:y,containsTarget:m})}return h.sort((d,c)=>{if(d.containsTarget)return-1;if(c.containsTarget)return 1;let l=Math.hypot(d.cx-t,d.cy-o),u=Math.hypot(c.cx-t,c.cy-o);return l-u})}var Oo=null;async function Yl(){return Oo||(Oo=(async()=>{let{createWorker:e}=await import("tesseract.js"),n=await import("fs-extra"),{CU_CACHE_DIR:t}=await import("./paths-R3DD7CRF.js");return n.ensureDirSync(t),e("eng",1,{cachePath:t,logger:()=>{}})})().catch(e=>{throw Oo=null,e})),Oo}var lo=null,fa=null;async function Vl(){let{getActiveDisplay:e}=await import("./screen_grid-IKEV7A6U.js"),n=await e();if(lo&&fa===n)return lo;fa=n,lo={format:"png"};try{let t=await ua.listDisplays();t&&t.length>0&&(lo={format:"png",screen:(t[n]||t[0]).id})}catch{}return lo}var Wi=async(e,n={})=>{let t=!!(process.env.SHOW_DEBUG_GRID||process.env.DEBUG_OCR||process.env.VERBOSE),o=performance.now(),s=o,i=f=>{if(!t)return;let p=performance.now(),g=(p-s).toFixed(0),y=(p-o).toFixed(0);console.log(`[Click Perf] +${g}ms (${y}ms total) -> ${f}`),s=p};i("Starting click()");let a=O(e),r=a.gridId||a.grid||a.coordinate||a.target||a.id,h=(a.type||a.clickType||"single").toLowerCase(),d=(a.button||"left").toLowerCase(),c=a.intendedClickText||a.text||"";if(!r&&!c)return'ERROR: Missing required "gridId" parameter for Click tool.';let l=r;if(c)try{i("Parsing grid code");let f=r?gr(r):null;i("Getting display options");let p=await Vl();i("Taking desktop screenshot");let g=await ua(p);i("Getting image metadata");let y=await co(g).metadata(),m=y.width||1920,w=y.height||1080,x=f?{x:Math.round(f.x*(m/1280)),y:Math.round(f.y*(w/720))}:{x:m/2,y:w/2},S=c.toLowerCase().trim();i("Acquiring OCR worker");let R=await Yl(),E=null,k="",T=f?220:500;if(f){i("Pass 1: Cropping target crop (3x zoom window, 2x upscale)");let $=Math.min(Math.round(m/3),m),C=Math.min(Math.round(w/3),w),b=Math.max(0,Math.min(m-$,x.x-Math.floor($/2))),v=Math.max(0,Math.min(w-C,x.y-Math.floor(C/2))),I=await co(g).extract({left:b,top:v,width:$,height:C}).toBuffer(),D=2,j=await Ni(I,D),U=S.replace(/[^a-z0-9]/g,"_");await Fi("cropped",`crop_${Date.now()}_${U}.png`,j),i("Pass 1: Running Tesseract OCR recognize on crop (PSM 11 - Sparse Text)"),await R.setParameters({tessedit_pageseg_mode:"11"});let{data:Y}=await R.recognize(j,{},{tsv:!0,blocks:!0});if(i("Pass 1: OCR recognition finished, extracting matches"),Y&&Y.text){t&&console.log(`[Pass 1 OCR Read]: "${Y.text.trim().replace(/\s+/g," ")}"`);let ie=Bi(Y,S,b,v,D);if(ie.length>0){let _e=Ui(ie,x);_e&&(_e.containsPoint||_e.dist<=T)&&(E=_e,k="centered target crop OCR")}}}if(!E){i("Pass 2: Entering Full-Screen OCR (broad scan, PSM 3 - Auto)");let $=await Ni(g,2),C=S.replace(/[^a-z0-9]/g,"_");await Fi("fullscreen",`full_${Date.now()}_${C}.png`,$),i("Pass 2: Running Tesseract on full screen"),await R.setParameters({tessedit_pageseg_mode:"3"});let{data:b}=await R.recognize($,{},{tsv:!0,blocks:!0});if(i("Pass 2: Full-screen OCR finished"),b&&b.text){let v=Bi(b,S,0,0,2);if(v.length>0){let I=Ui(v,x);I&&(E=I,k="full-screen OCR")}}}if(!E){i("Pass 3: Entering Tiled OCR fallback (high-res 3x)");let $=Kl(m,w,x.x,x.y),C=S.replace(/[^a-z0-9]/g,"_");await R.setParameters({tessedit_pageseg_mode:"11"});for(let b=0;b<$.length;b++){let v=$[b];i(`Pass 3: Preprocessing tile ${b+1}/${$.length}`);let I=await co(g).extract({left:v.x0,top:v.y0,width:v.w,height:v.h}).toBuffer(),D=await Ni(I,3);await Fi("tiles",`tile_${b+1}_${Date.now()}_${C}.png`,D),i(`Pass 3: Running Tesseract on tile ${b+1}`);let{data:j}=await R.recognize(D,{},{tsv:!0,blocks:!0});if(!j||!j.text)continue;let U=Bi(j,S,v.x0,v.y0,3);if(U.length>0){let Y=Ui(U,x);if(Y){E=Y,k=`tile ${b+1} OCR (${v.containsTarget?"target tile":`offset ${v.x0},${v.y0}`})`;break}}}}if(E){let $={x:Math.round(E.x*(1280/m)),y:Math.round(E.y*(720/w))};i(`Executing mouse click on matched target (${k})`);let C=await On("click",$,{button:d,clickType:h});return i("Click completed successfully"),`${C} (${k} for "${c}" at ${Math.round(E.dist)}px distance)`}else t&&console.log(`[OCR] No match found for "${c}". Falling back to gridId.`)}catch(f){t&&console.error("[OCR Error]",f)}i(`Executing mouse click on fallback gridId: ${l}`);let u=await On("click",l,{button:d,clickType:h});return i("Fallback click completed"),u};var ji=async(e,n={})=>{let t=O(e),o=t.fromGridId||t.from||t.start,s=t.toGridId||t.to||t.end;return!o||!s?'ERROR: Drag requires both "fromGridId" and "toGridId" parameters.':await On("drag",o,{from:o,to:s})};var Hi=async(e,n={})=>{let t=O(e),o=(t.direction||"down").toLowerCase(),s=t.amount?parseInt(t.amount,10):6,i=t.gridId||t.grid||t.coordinate||t.target||t.id||null;return await On("scroll",i,{direction:o,amount:s})};var Lo=async(e,n={})=>{let t=O(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 Kn("type",String(o),{autoPressEnter:s})};var Po=async(e,n={})=>{let t=O(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 Kn("clear_input");if(s.includes(";")||s.includes("+")){let i=s.split(/[;+]/).map(a=>a.trim()).filter(Boolean);return await Kn("key_combination",i)}return await Kn("key_press",s)};var Do=async(e,n={})=>"SUCCESS: Screen recapture requested. The latest gridded screenshot is provided for your next decision.";var Jl={web_search:di,web_scrape:fi,memory:ui,chat:hi,view_file:Qs,write_file:pi,update_file:xi,exec_command:si,read_folder:Si,write_pdf:Ti,write_docx:Ei,search_keyword:eo,generate_image:Mi,saveSummary:to,addMemScore:Ls,file_map:Ii,todo:no,Todo:no,goal:no,Goal:no,invokeSync:Oi,invoke:sa,getProgress:Li,cancel:oa,awaitSubagent:Ps,answerSubagent:Ds,steerSubagent:oo,computer_action:ao,computer_use:ao,ComputerAction:ao,ComputerUse:ao,click:Wi,Click:Wi,drag:ji,Drag:ji,scroll:Hi,Scroll:Hi,keyboard_typing:Lo,KeyboardTyping:Lo,keyboardtyping:Lo,key_press:Po,KeyPress:Po,keypress:Po,recapture_screen:Do,RecaptureScreen:Do,recapturescreen:Do,invoke_sync:Oi,get_progress:Li,await_subagent:Ps,answer_subagent:Ds,steer_subagent:oo,steer:oo,Steer:oo,ask:ki,Ask:ki,WebSearch:di,WebScrape:fi,ReadFile:Qs,ReadFolder:Si,WriteFile:pi,PatchFile:xi,WritePDF:Ti,WriteDoc:Ei,Run:si,SearchKeyword:eo,CodeSearch:eo,code_search:eo,Memory:ui,Chat:hi,GenerateImage:Mi,saveSumary:to,SaveSummary:to,SaveSumary:to,add_mem_score:Ls,AddMemScore:Ls,addMemoryScore:Ls,AddMemoryScore:Ls,FileMap:Ii,answer:Ds,Answer:Ds,AnswerSubagent:Ds,await:Ps,Await:Ps,AwaitSubagent:Ps,EmergencyRollback:Di,emergency_rollback:Di},fo=async(e,n,t={})=>{let o=t.mode?t.mode.toLowerCase():"flux",s=e.toLowerCase(),a=["memory","chat","savesummary","addmemscore","add_mem_score","ask","web_search","web_scrape","await"].some(c=>s.includes(c))||s==="ask",h=["click","drag","scroll","keyboardtyping","keyboard_typing","keypress","key_press","recapturescreen","recapture_screen","computer"].some(c=>s.includes(c));if(!a){if(o==="flow"){if(!(s.includes("write_pdf")||s.includes("write_docx")||s.includes("generate_image")))return`ERROR: Tool [${e}] is a Workspace Tool and NOT available in Flow mode. Tell user to switch (\`/mode flux\`) to use this tool.`}else if(o==="icu"){if(!h)return`ERROR: Tool [${e}] is not available in Computer Use mode. ICU mode only supports Computer Use tools (Click, Drag, Scroll, KeyboardTyping, KeyPress, RecaptureScreen).`}else if(s.includes("write_pdf")||s.includes("write_docx")||s.includes("generate_image"))return`ERROR: Tool [${e}] is not available in ${t.mode||"Flux"} mode. Tell user to switch (\`/mode flow\`) for document generation.`}let d=Jl[e];if(!d)return`ERROR: Tool [${e}] not found in registry.`;try{return await d(n,t)}catch(c){let l=c instanceof Error?c.message:String(c);return`ERROR: Execution failed for [${e}]: ${l}`}};import Q from"path";import Ie from"fs";import Xl from"gradient-string";var Gi=["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 ha=[{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"]}],uo={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 Fo=null;var pa=(e="Dark")=>{let n;e==="Mystery"||e==="Chaos"?(Fo||(Fo=ha[Math.floor(Math.random()*ha.length)]),n={...Fo,id:"Mystery"}):(Fo=null,uo[e]?n=uo[e]:e==="GitHub"?n=uo["GitHub Dark"]:e==="Transparent"?n=uo["Transparent Dark"]:n=uo.Dark);let t=n.codeText||n.secondary||n.info||n.logoGradient&&n.logoGradient[0]||"cyan";return{...n,codeText:t}};var Ql=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",Mp=(e=2)=>{let n=Ql();return n==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)},Ap=(e="...",n="Loading...",t="Dark")=>{let o=Gi[Math.floor(Math.random()*Gi.length)],s=pa(t),i=s.logoTextAnsi,a=s.logoBodyAnsi,r=s.logoMutedAnsi,h="\x1B[0m",d=[" \u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2588\u2588\u2588\u2591 "," \u2588\u2588\u2588\u2591 "," \u2588\u2588\u2588\u2591 "," \u2591\u2591\u2591 "],c=s.logoGradient||["#0077ff","#ff00ff"],l=Xl(c).multiline(d.join(`
486
486
  `)).split(`
487
- `),f=u=>`${r}${u}${h}`;return`${l[0]}
487
+ `),u=f=>`${r}${f}${h}`;return`${l[0]}
488
488
  ${l[1]} ${i}Selected Provider: ${n}${h}
489
489
  ${l[2]}
490
- ${l[3]} ${i}FluxFlow ${f("v"+e)}${h}
490
+ ${l[3]} ${i}FluxFlow ${u("v"+e)}${h}
491
491
  ${l[4]}
492
492
  ${l[5]} ${a}See /help for additional commands.${h}
493
- ${l[6]} ${f(o)}
494
- ${l[7]}`};import{WebSocket as Do}from"ws";var qt=null,Fs=!1,Kl="ws://localhost:56832",Bi=[],Ns=null,Ui=null,ca="2.0.0",Tp=e=>{ca=e,da()},Wi=e=>{Ui=e},da=()=>{if(qt||Fs)return;Fs=!0;let e=new Do(Kl);e.on("open",()=>{for(qt=e,Fs=!1,qt.send(JSON.stringify({command:"version",version:ca,pid:process.pid,ppid:process.ppid}));Bi.length>0;)qt.send(JSON.stringify(Bi.shift()))}),e.on("message",n=>{try{let t=JSON.parse(n.toString());t.command==="contextResponse"&&Ns?(Ns(t.data),Ns=null):t.command==="securityResponse"&&Ui&&Ui(t.result)}catch{}}),e.on("error",()=>{Fs=!1,qt=null}),e.on("close",()=>{Fs=!1,qt=null})},Fo=e=>{qt&&qt.readyState===Do.OPEN?qt.send(JSON.stringify(e)):(Bi.push(e),Fs||da())},No=()=>qt!==null&&qt.readyState===Do.OPEN,Rp=e=>{Fo({command:"status",status:e})},gs=()=>new Promise(e=>{if(!qt||qt.readyState!==Do.OPEN){e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]});return}Ns=e,qt.send(JSON.stringify({command:"requestContext"})),setTimeout(()=>{Ns===e&&(e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]}),Ns=null)},1e3)}),fa=e=>{Fo({command:"open",filePath:e})},ji=(e,n,t)=>{Fo({command:"showDiff",filePath:e,originalContent:n,modifiedContent:t})},ua=(e,n)=>{Fo({command:"closeDiff",filePath:e,result:n})};import ha from"path";import zl from"fs";var Yl=e=>{try{return zl.readdirSync(e,{withFileTypes:!0})}catch{return[]}},Hi=(e,n,t=1,o=Yl,s=[],i=null)=>{let a=i||o(e),r=" ".repeat(t-1);if(a.length>100)return`${r}${ha.basename(e)}/ (>100 files)
493
+ ${l[6]} ${u(o)}
494
+ ${l[7]}`};import{WebSocket as No}from"ws";var qt=null,Fs=!1,Zl="ws://localhost:56832",qi=[],Ns=null,zi=null,ma="2.0.0",Op=e=>{ma=e,ga()},Ki=e=>{zi=e},ga=()=>{if(qt||Fs)return;Fs=!0;let e=new No(Zl);e.on("open",()=>{for(qt=e,Fs=!1,qt.send(JSON.stringify({command:"version",version:ma,pid:process.pid,ppid:process.ppid}));qi.length>0;)qt.send(JSON.stringify(qi.shift()))}),e.on("message",n=>{try{let t=JSON.parse(n.toString());t.command==="contextResponse"&&Ns?(Ns(t.data),Ns=null):t.command==="securityResponse"&&zi&&zi(t.result)}catch{}}),e.on("error",()=>{Fs=!1,qt=null}),e.on("close",()=>{Fs=!1,qt=null})},Bo=e=>{qt&&qt.readyState===No.OPEN?qt.send(JSON.stringify(e)):(qi.push(e),Fs||ga())},Uo=()=>qt!==null&&qt.readyState===No.OPEN,Lp=e=>{Bo({command:"status",status:e})},gs=()=>new Promise(e=>{if(!qt||qt.readyState!==No.OPEN){e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]});return}Ns=e,qt.send(JSON.stringify({command:"requestContext"})),setTimeout(()=>{Ns===e&&(e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]}),Ns=null)},1e3)}),ya=e=>{Bo({command:"open",filePath:e})},Yi=(e,n,t)=>{Bo({command:"showDiff",filePath:e,originalContent:n,modifiedContent:t})},wa=(e,n)=>{Bo({command:"closeDiff",filePath:e,result:n})};import xa from"path";import ec from"fs";var tc=e=>{try{return ec.readdirSync(e,{withFileTypes:!0})}catch{return[]}},Vi=(e,n,t=1,o=tc,s=[],i=null)=>{let a=i||o(e),r=" ".repeat(t-1);if(a.length>100)return`${r}${xa.basename(e)}/ (>100 files)
495
495
  `;let h="",d=s,c=a.filter(p=>!d.includes(p.name)&&!p.name.startsWith(".")),l=a.filter(p=>d.includes(p.name)||p.name.startsWith(".")).map(p=>p.name).sort();l.length>0&&(h+=`${r}[ignored: ${l.map(p=>p+"/").join(", ")}]
496
- `);let f=c.filter(p=>p.isDirectory()).sort((p,g)=>p.name.localeCompare(g.name)),u=c.filter(p=>!p.isDirectory()).map(p=>p.name).sort();for(let p of f){let g=ha.join(e,p.name);if(t>n)h+=`${r}${p.name}/ (max depth)
496
+ `);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=xa.join(e,p.name);if(t>n)h+=`${r}${p.name}/ (max depth)
497
497
  `;else{let y=o(g);y.length>80?h+=`${r}${p.name}/ (>80 files)
498
498
  `:(h+=`${r}${p.name}/
499
- `,h+=Hi(g,n,t+1,o,s,y))}}return u.length>0&&(h+=`${r}${u.join("; ")}
500
- `),h};import Gi from"path";import Vl from"fs";var Jl=e=>{try{return Vl.readdirSync(e,{withFileTypes:!0})}catch{return[]}},qi=(e,n,t="",o=1,s=Jl,i=[])=>{let a=s(e),r=Gi.sep;if(a.length>100)return`${t}\u2514\u2500\u2500 ${Gi.basename(e)}${r} ...100+ files...
501
- `;let h="",d=i,c=a.filter(u=>!d.includes(u.name)&&!u.name.startsWith(".")),l=a.filter(u=>d.includes(u.name)||u.name.startsWith(".")).map(u=>u.name).sort();c.sort((u,p)=>u.isDirectory()&&!p.isDirectory()?-1:!u.isDirectory()&&p.isDirectory()?1:u.name.localeCompare(p.name));let f=[...c.map(u=>({name:u.name,isDir:u.isDirectory()})),...l.map(u=>({name:u,isDir:!0,isCollapsed:!0}))];return f.forEach((u,p)=>{let g=p===f.length-1,y=Gi.join(e,u.name),m=g?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",w=t+(g?" ":"\u2502 ");if(u.isCollapsed){h+=`${t}${m}${u.name}${r}...
502
- `;return}u.isDir?o>n?h+=`${t}${m}${u.name}${r} ...depth exceeded...
503
- `:s(y).length>80?h+=`${t}${m}${u.name}${r} ...80+ files...
504
- `:(h+=`${t}${m}${u.name}${r}
505
- `,h+=qi(y,n,w,o+1,s,i)):h+=`${t}${m}${u.name}
506
- `}),h};import"@google/genai";Xl.config({quiet:!0});var Zl=/```[\s\S]*?```/g,ec=/```[\s\S]*$/g,tc=/`[^`]+`/g,nc=/^\|.*\|$/gm,sc=/^[^\w]+|[^\w]+$/g,oc=/[^a-z0-9]/gi,fo=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,ic=/\[\s*(?:tool:functions\.|agent:generalist\.)([a-z0-9_]+)\s*\(/gi,rc=/(?:path|targetFile|TargetFile|directory|keyword|id|taskId|title|task)\s*=\s*\\?["']?([^\\"' \),]+)/,ys=/["']/g,pa=/\\/g,ac=/<\|channel>thought/gi,lc=/<channel\|>/gi,Pn=e=>typeof e!="string"?e:e.replace(ac,"<think>").replace(lc,"</think>"),cc=/(?:<(think|thought|thoughts)>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\])/gi,dc=/(?:<(think|thought|thoughts)>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*$/gi,ma=/(?:<think>|<\|channel>thought|\[think\])[\s\S]*?(?:<\/think>|<channel\|>|\[\/think\]|$)/gi,ga=/(?:<(think|thought|thoughts)>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\]|$)/gi,Ra=/`[^`]*`/g,Ea=/`[^`]*$/,ya=/<\|\s*tool_call_begin\s*\|>\s*(?:(?:tool|functions)\b[\s._]*)*([a-zA-Z0-9_]+)(?::\d+)?\s*<\|\s*tool_call_argument_begin\s*\|>([\s\S]*?)<\|\s*tool_call_end\s*\|>/gi,fc=/"([^"]+)"\s*:\s*(?:"([^"]*)"|(\d+)|true|false|null)/g,wa=/<\|\s*tool_calls_section_begin\s*\|>/gi,xa=/<\|\s*tool_calls_section_end\s*\|>/gi,uc=/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi,ba=/<(\w+)(?:[^>]*)>\r?\n?/gi,Sa=/\r?\n?<\/\w+(?:[^>]*)>/gi,zi=null,Bo={},ws={key:null,value:null},gn=e=>e&&e.replace(/(?:(\x1b\[\d+m))?([✔✘✖🔍📖→➕↻↷•🛇])(?:(\x1b\[\d+m))?\s*\b(Clicked|Dragged|Scrolled|Typed|Pressed Key|Recaptured Screen|Created|Read|Edited|Viewed|Processed|Auto-Read|Skipped|List|Generated|Written|Searched|AI Search|Get Map|Write Canceled|Resolved Sub-Agent Query|Edit Canceled|Write Cancelled|Edit Denied|Visited|Updated|Reviewed|Delegated|Background|Checked|Indexed|Analyzed|Browsed|Elevating SubAgent|Checking SubAgent Work|Started Generalist|Called Generalist|Steered|Unsupported Modality|Awaiting|Cancelled|Aligning Moon Phase|Contemplating Existence|Staring At Void|Rollback Point Checked|Emergency Rollback Failed|Emergency Rollback|Delaying Professionally|Negotiating With Electrons|Touching Grass (virtually)|Panicking Softly|Rethinking Career Choices|Loading Cat Videos|Giving Up Entirely|Summoning Braincell #2|Pretending To Be Busy|Waiting For Motivation DLC|Rotating Internal Screaming|Downloading More RAM|Feeding The Hamsters|Gaslighting Scheduler|Performing Dramatic Pause|Buffering Social Energy|Calculating Regret|Reading Terms And Conditions|Becoming Sentient Briefly|Contacting Ancestors)\b/ig,(n,t,o,s,i)=>`${t||""}${o}${s||""} \x1B[95m${i}\x1B[0m`),hc=async(e,n=8,t=1e3,o=8e3,s=null)=>{let i=0;for(;;){if(s?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{return await e()}catch(a){if(s?.aborted||a?.name==="AbortError"||a?.message==="Subagent task was cancelled."||(i++,i>=n))throw a;let r=Math.min(t*Math.pow(2,i-1),o);await new Promise((h,d)=>{let c=setTimeout(h,r);s&&s.addEventListener("abort",()=>{clearTimeout(c),d(new DOMException("The user aborted a request.","AbortError"))})})}}},Ot=!1;var pc=e=>{let n=e.filter(s=>(s.role==="user"||s.role==="agent"||s.role==="system")&&s.role!=="think"&&!s.isVisualFeedback&&!s.isMeta&&!s.isTerminalRecord&&!(s.text&&s.text.includes("[TERMINAL_RECORD]"))&&!String(s.id).startsWith("welcome")).map((s,i,a)=>{let r=s.fullText||s.text||"";if(s.role==="user"&&i<a.length-1)if(r.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")){let h=r.indexOf("**CONTEXT SUMMARY OF PREVIOUS TURNS");if(h!==-1){let c=r.substring(0,h).lastIndexOf("[SYSTEM METADATA]");c!==-1?r=r.substring(c).trim():r=r.substring(h).trim()}}else{let h=r.lastIndexOf("[USER]"),d=r.lastIndexOf("[USER PROMPT]");h!==-1?r=r.substring(h+6).trim():d!==-1&&(r=r.substring(d).trim())}return{...s,text:r}}),t=[],o=0;for(;o<n.length;){let s=n[o];if(s.role==="user")t.push(s),o++;else{let i=[];for(;o<n.length&&n[o].role!=="user";)i.push(n[o]),o++;let a=[],r=[],h=[];i.forEach(d=>{let c=(d.text||"").toLowerCase(),l=c.includes("tool:functions.")||c.includes("agent:generalist."),f=d.role==="system"&&(d.text?.startsWith("[TOOL RESULT]")||d.text?.startsWith("SUCCESS:")||d.text?.startsWith("ERROR:"));d.role==="agent"?l?a.push(d.text):h.push(d.text):f?r.push(d.text):h.push(d.text)}),a.length>0&&t.push({role:"agent",text:"combined"}),r.length>0&&t.push({role:"system",text:"combined"}),h.length>0&&t.push({role:"agent",text:"combined"})}}return t.length},mc=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),Wo=async(e,n,t=5,o=1e3)=>{let s=n?.signal;for(let a=0;a<t;a++){if(s?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{let r=await fetch(e,n);if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),r.ok||r.status!==429&&r.status<500)return r}catch(r){if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),r.name==="AbortError"||s?.aborted||a===t-1)throw r}s?await new Promise((r,h)=>{let d=setTimeout(()=>{s.removeEventListener("abort",c),r()},Math.min(24e3,o*Math.pow(2,a))),c=()=>{clearTimeout(d),h(new DOMException("The user aborted a request.","AbortError"))};s.addEventListener("abort",c)}):await new Promise(r=>setTimeout(r,Math.min(24e3,o*Math.pow(2,a))))}if(s?.aborted)throw new DOMException("The user aborted a request.","AbortError");let i=await fetch(e,n);return typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),i},Yi=async function*(e,n,t,o,s,i,a,r,h=.99){let d=[];o&&d.push({role:"system",content:o});for(let x of t){let S=x.role==="user"?"user":"assistant",R=[];if(Array.isArray(x.parts)){for(let E of x.parts)if(E.text)R.push({type:"text",text:E.text});else if(E.inlineData&&a){let b=E.inlineData.mimeType,T=E.inlineData.data;b.startsWith("image/")&&R.push({type:"image_url",image_url:{url:`data:${b};base64,${T}`}})}}else{let E=x.text||"";E&&R.push({type:"text",text:E})}d.push({role:S,content:R.length===1&&R[0].type==="text"?R[0].text:R})}let c={model:n,messages:d,stream:!0,stream_options:{include_usage:!0},temperature:h};if(s!=="Fast"){let x={Low:"high",Medium:"high",Standard:"high",High:"max",xHigh:"max"};c.reasoning_effort=x[s]||"high",c.extra_body={thinking:{type:"enabled"}}}else c.extra_body={thinking:{type:"disabled"}};let l=await Wo("https://api.deepseek.com/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(c),signal:r});if(!l.ok){let x=await l.json().catch(()=>({}));throw new Error(`DeepSeek Error (${l.status}): ${x.error?.message||l.statusText}`)}let f=l.body.getReader(),u=new TextDecoder,p="",g=[],y=null,m=Date.now(),w=!1;for(;;){let{done:x,value:S}=await f.read();if(x){w&&(g.length>0||y)&&(yield{candidates:g.length>0?[{content:{parts:g}}]:[],usageMetadata:y});break}p+=u.decode(S,{stream:!0});let R=p.split(`
507
- `);p=R.pop();for(let E of R){let b=E.trim();if(!b||!b.startsWith("data: "))continue;let T=!1;if(b==="data: [DONE]")T=!0;else try{let $=JSON.parse(b.substring(6)),C=$.choices?.[0]?.delta,k=$.usage;if($.choices?.[0]?.finish_reason&&(T=!0),k&&(y={totalTokenCount:k.total_tokens||k.prompt_tokens+k.completion_tokens,promptTokenCount:k.prompt_tokens||0,candidatesTokenCount:k.completion_tokens||0,cachedContentTokenCount:k.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:k.completion_tokens_details?.reasoning_tokens||0},w=!0),C){let O=C.reasoning_content||null;O&&(g.push({text:O,thought:!0}),w=!0),C.content&&(g.push({text:C.content}),w=!0)}}catch{}if((T||Date.now()-m>=150)&&w&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],m=Date.now(),w=!1),T)break}Date.now()-m>=150&&w&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],m=Date.now(),w=!1)}},Vi=async function*(e,n,t,o,s,i,a,r,h=.99){let d=[];o&&d.push({role:"system",content:o});for(let R of t){let E=R.role==="user"?"user":"assistant",b=[];if(Array.isArray(R.parts)){for(let T of R.parts)if(T.text)b.push({type:"text",text:T.text});else if(T.inlineData&&a){let $=T.inlineData.mimeType,C=T.inlineData.data;$.startsWith("image/")&&b.push({type:"image_url",image_url:`data:${$};base64,${C}`})}}else{let T=R.text||"";T&&b.push({type:"text",text:T})}b.length>0&&d.push({role:E,content:b.length===1&&b[0].type==="text"?b[0].text:b})}let c={Fast:"none",Low:"none",Medium:"high",Standard:"high",High:"high",xHigh:"high"},l={model:n,messages:d,stream:!0,temperature:h,prompt_cache_key:"flux-flow-session"};s&&s!=="Fast"&&qs(n)&&(l.reasoning_effort=c[s]||"high");let f=await Wo("https://api.mistral.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(l),signal:r});if(!f.ok){let R=await f.text().catch(()=>""),E=f.statusText;try{let b=JSON.parse(R);E=b.error?.message||b.message||JSON.stringify(b.detail||b)}catch{R&&(E=R)}throw new Error(`Mistral Error (${f.status}): ${JSON.stringify(E)}`)}let u=f.body.getReader(),p=new TextDecoder,g="",y=[],m=null,w=Date.now(),x=!1,S=R=>R?typeof R=="string"?Pn(R):Array.isArray(R)?R.map(S).filter(Boolean).join(""):typeof R=="object"&&R!==null?typeof R.text=="string"?Pn(R.text):typeof R.content=="string"?Pn(R.content):typeof R.thinking=="string"?Pn(R.thinking):typeof R.reasoning_content=="string"?Pn(R.reasoning_content):typeof R.reasoning=="string"?Pn(R.reasoning):typeof R.value=="string"?Pn(R.value):R.text?S(R.text):R.content?S(R.content):R.thinking?S(R.thinking):R.reasoning_content?S(R.reasoning_content):R.reasoning?S(R.reasoning):R.value?S(R.value):"":Pn(String(R)):"";for(;;){let{done:R,value:E}=await u.read();if(R){x&&(y.length>0||m)&&(yield{candidates:y.length>0?[{content:{parts:y}}]:[],usageMetadata:m});break}g+=p.decode(E,{stream:!0});let b=g.split(`
508
- `);g=b.pop();for(let T of b){let $=T.trim();if(!$||!$.startsWith("data: "))continue;let C=!1;if($==="data: [DONE]")C=!0;else try{let k=JSON.parse($.substring(6)),O=k.choices?.[0]?.delta,v=k.usage;if(k.choices?.[0]?.finish_reason&&(C=!0),v&&(m={totalTokenCount:v.total_tokens||(v.prompt_tokens||0)+(v.completion_tokens||0),promptTokenCount:v.prompt_tokens||0,candidatesTokenCount:v.completion_tokens||0,cachedContentTokenCount:v.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:v.completion_tokens_details?.reasoning_tokens||0},x=!0),O){let L=O.thinking||O.reasoning_content||O.reasoning,N=S(L);N&&(y.push({text:N,thought:!0}),x=!0);let j=O.content||(!O.thinking&&!O.reasoning_content&&!O.reasoning?O.text:null);if(j)if(Array.isArray(j))for(let V of j)if(typeof V=="object"&&V!==null){let oe=V.type==="thinking"||V.type==="reasoning"||!!V.thought,Ie=S(V);Ie&&(y.push({text:Ie,...oe?{thought:!0}:{}}),x=!0)}else{let oe=S(V);oe&&(y.push({text:oe}),x=!0)}else if(typeof j=="object"&&j!==null){let V=j.type==="thinking"||j.type==="reasoning"||!!j.thought,oe=S(j);oe&&(y.push({text:oe,...V?{thought:!0}:{}}),x=!0)}else{let V=S(j);V&&(y.push({text:V}),x=!0)}}}catch{}if((C||Date.now()-w>=150)&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),x=!1),C)break}Date.now()-w>=150&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),x=!1)}},Ji=async function*(e,n,t,o,s,i,a=!1,r,h=.99){let d=[];o&&d.push({role:"system",content:o}),t.forEach(re=>{let Re=re.role==="model"?"assistant":"user",M=[];Array.isArray(re.parts)&&re.parts.forEach(F=>{if(F.text)M.push({type:"text",text:F.text});else if(F.inlineData&&a){let Y=F.inlineData.mimeType,J=F.inlineData.data;Y.startsWith("image/")&&fn(n)&&M.push({type:"image_url",image_url:{url:`data:${Y};base64,${J}`}})}}),d.push({role:Re,content:M.length===1&&M[0].type==="text"?M[0].text:M})});let l={Fast:"Fast",Low:"Fast",Medium:"Standard",Standard:"Standard",High:"High",xHigh:"High"}[s]||"High",f=l!=="Fast",u=n.includes("kimi"),p=n.includes("gemma"),g=n.includes("deepseek"),y=n.includes("glm"),m=n.includes("mistral"),w=n.includes("minimax"),x=n.includes("gpt"),S=n.includes("qwen"),R=n.includes("nemotron"),E=n.includes("llama-3"),b=n.includes("seed"),T=n.includes("poolside"),$=n.includes("thinkingmachines")||n.includes("muse"),C=E,k=null,O={Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},v={Fast:"64",Low:"64",Medium:"4096",Standard:"4096",High:"16384",xHigh:"16384"},L={Fast:"none",Low:"minimal",Medium:"medium",Standard:"medium",High:"max",xHigh:"max"},N=w||g||T||$?16384:32768;N=process.env.NVIDIA_BASE_URL?1024:N,N=k?1024:N;let j={model:n,messages:d,max_tokens:N,stream:!0,stream_options:{include_usage:!0},temperature:h,...x&&{thinking:O[s]||"high"}};if(!(process.env.NVIDIA_BASE_URL||C||k))if(u)j.chat_template_kwargs={thinking:f};else if(p)j.chat_template_kwargs={enable_thinking:f};else if(g)if(f){let re=l==="High"?"max":"high";j.chat_template_kwargs={thinking:!0,reasoning_effort:re}}else j.chat_template_kwargs={thinking:!1};else y?j.chat_template_kwargs={enable_thinking:f,clear_thinking:!f}:m?j.reasoning_effort=f?"high":"none":w&&n.includes("minimax-m3")?j.chat_template_kwargs={thinking_mode:f?"enabled":"disabled"}:S?j.chat_template_kwargs={enable_thinking:f}:R?l==="High"?(j.reasoning_budget=12e3,j.chat_template_kwargs={enable_thinking:!0}):l==="Standard"?(j.reasoning_budget=12e3,j.chat_template_kwargs={enable_thinking:!0,medium_effort:!0}):j.chat_template_kwargs={enable_thinking:!1}:b?f&&(j.extra_body={thinking_budget:parseInt(v[l]??"4096")}):T?j.chat_template_kwargs={enable_thinking:f}:$&&(j.reasoning_effort=L[l]||"medium");let V=0,oe=6,Ie=!1,B=process.env.NVIDIA_BASE_URL||"https://integrate.api.nvidia.com/v1/chat/completions",W=process.env.NVIDIA_API_KEY&&process.env.NVIDIA_BASE_URL?process.env.NVIDIA_API_KEY:e;for(B.endsWith("/chat/completions")||(B=B.replace(/\/+$/,"")+"/chat/completions");V<oe;){V++;try{let re=await Wo(B,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${W}`},body:JSON.stringify(j),signal:r});if(!re.ok){let Ue=await re.text().catch(()=>""),st=re.statusText;try{let ut=JSON.parse(Ue);st=ut.error?.message||ut.message||JSON.stringify(ut.detail||ut)}catch{Ue&&(st=Ue)}let Ge=new Error(`NVIDIA API Error (${re.status}): ${st}`);throw Ge.status=re.status,Ge}let Re=re.body.getReader(),M=new TextDecoder,F="",Y=[],J=null,Ne=Date.now(),De=!1;for(;;){let{done:Ue,value:st}=await Re.read();if(Ue){De&&(Y.length>0||J)&&(yield{candidates:Y.length>0?[{content:{parts:Y}}]:[],usageMetadata:J},Ie=!0);break}F+=M.decode(st,{stream:!0});let Ge=F.split(`
509
- `);F=Ge.pop();let ut=!1;for(let Nt of Ge){let ht=Nt.trim();if(ht){if(ht==="data: [DONE]"){ut=!0;break}if(ht.startsWith("data: ")){let pt;try{pt=JSON.parse(ht.substring(6))}catch{continue}if(pt.error)throw new Error(`NVIDIA Stream Error: ${pt.error.message||JSON.stringify(pt.error)}`);pt.choices?.[0]?.finish_reason&&(ut=!0);try{let kt=pt.usage;kt&&(J={totalTokenCount:kt.total_tokens||kt.prompt_tokens+kt.completion_tokens,promptTokenCount:kt.prompt_tokens||0,candidatesTokenCount:kt.completion_tokens||0,cachedContentTokenCount:kt.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:(kt.completion_tokens_details?.reasoning_tokens||0)+(kt.completion_tokens_details?.thoughts_tokens||0)},De=!0);let Tt=pt.choices?.[0]?.delta?.reasoning||pt.choices?.[0]?.delta?.reasoning_content||"",Xe=pt.choices?.[0]?.delta?.content||"";Tt&&(Y.push({text:Tt,thought:!0}),De=!0),Xe&&(Y.push({text:Xe}),De=!0)}catch{}}}}if((ut||Date.now()-Ne>=350)&&De&&(yield{candidates:Y.length>0?[{content:{parts:[...Y]}}]:[],usageMetadata:J},Ie=!0,Y=[],Ne=Date.now(),De=!1),ut)break}break}catch(re){if(Ie||V>=oe)throw re;await new Promise(Re=>setTimeout(Re,3500))}}},gc=async function*(e,n){let t=[],o=null,s=!1,i=null,a=f=>{if(t.push(f),o){let u=o;o=null,u()}},r=n.split("/").pop();r=r.replace("llama-3.3","llama-3_3");let h=`https://api.ngc.nvidia.com/v2/predict/queues/models/qc69jvmznzxy/${r}`,d=!1,c=null,l=async()=>{try{let f=await fetch(h);if(f.ok){let u=await f.json();if(u&&u.queues&&u.queues[0]&&typeof u.queues[0].queueDepth=="number"){let p=u.queues[0].queueDepth;d||a({value:{type:"status",content:`Queue ${p||1}`},done:!1})}}else d||a({value:{type:"status",content:`Queue ${f.status}`},done:!1})}catch{}};process.env.NVIDIA_BASE_URL||(l(),c=setInterval(l,5e3)),(async()=>{try{let f=e[Symbol.asyncIterator]();for(;;){let{value:u,done:p}=await f.next();if(p)break;d=!0,c&&(clearInterval(c),c=null),a({value:u,done:!1})}s=!0,a(null)}catch(f){if(i=f,c&&(clearInterval(c),c=null),o){let u=o;o=null,u()}}})();try{for(;;){if(i)throw i;if(t.length>0){let f=t.shift();if(f===null&&s)break;yield f.value}else{if(s)break;await new Promise(f=>{o=f})}}}finally{c&&(clearInterval(c),c=null)}},Xi=async function*(e,n,t,o,s,i,a,r,h=.95){let d=[];o&&d.push({role:"system",content:[{type:"text",text:o,cache_control:{type:"ephemeral"}}]});for(let R of t){let E=R.role==="user"?"user":"assistant",b=[];if(Array.isArray(R.parts)){for(let T of R.parts)if(T.text)b.push({type:"text",text:T.text});else if(T.inlineData&&a){let $=T.inlineData.mimeType,C=T.inlineData.data;$.startsWith("image/")?b.push({type:"image_url",image_url:{url:`data:${$};base64,${C}`}}):b.push({type:"file",file:{filename:T.filename||"file",file_data:`data:${$};base64,${C}`}})}}else{let T=R.text||"";T&&b.push({type:"text",text:T})}d.push({role:E,content:b.length===1&&b[0].type==="text"?b[0].text:b})}let c={Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},l={model:n,messages:d,stream:!0,temperature:h,cache_control:{type:"ephemeral"},session_id:"flux-flow-session"},f=c[s];f&&s!=="Fast"&&(l.reasoning_effort=f);let u=await Wo("https://openrouter.ai/api/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json","X-Title":"FluxFlow CLI","X-Cache":"true","X-OpenRouter-Cache":"true"},body:JSON.stringify(l),signal:r});if(!u.ok){let R=await u.json().catch(()=>({}));throw new Error(`OpenRouter Error (${u.status}): ${R.error?.message||u.statusText}`)}let p=u.body.getReader(),g=new TextDecoder,y="",m=[],w=null,x=Date.now(),S=!1;for(;;){let{done:R,value:E}=await p.read();if(R){S&&(m.length>0||w)&&(yield{candidates:m.length>0?[{content:{parts:m}}]:[],usageMetadata:w});break}y+=g.decode(E,{stream:!0});let b=y.split(`
510
- `);y=b.pop();for(let T of b){let $=T.trim();if(!$||!$.startsWith("data: "))continue;let C=!1;if($==="data: [DONE]")C=!0;else try{let k=JSON.parse($.substring(6)),O=k.choices?.[0]?.delta,v=k.usage;if(k.choices?.[0]?.finish_reason&&(C=!0),v&&(w={totalTokenCount:v.total_tokens||(v.prompt_tokens||0)+(v.completion_tokens||0),promptTokenCount:v.prompt_tokens||0,candidatesTokenCount:v.completion_tokens||0,cachedContentTokenCount:v.prompt_tokens_details?.cached_tokens||v.prompt_tokens_details?.cache_read_input_tokens||v.cache_read_input_tokens||0,thoughtsTokenCount:v.completion_tokens_details?.reasoning_tokens||0},S=!0),O){let L=O.reasoning||(O.reasoning_details?O.reasoning_details.map(N=>N.text).join(""):null);L&&(m.push({text:L,thought:!0}),S=!0),O.content&&(m.push({text:O.content}),S=!0)}}catch{}if((C||Date.now()-x>=150)&&S&&(yield{candidates:m.length>0?[{content:{parts:[...m]}}]:[],usageMetadata:w},m=[],x=Date.now(),S=!1),C)break}}},$a=async function*(e,n,t,o,s,i,a,r,h=1.05,d="Cloud"){let c=[];o&&c.push({role:"system",content:o});for(let b of t){let T=b.role==="user"?"user":"assistant",$="",C=[];if(Array.isArray(b.parts)){$=b.parts.map(k=>k.text||"").filter(Boolean).join(`
511
- `);for(let k of b.parts){let O=k.inlineData||k.inline_data;O&&O.data&&C.push(O.data)}}else $=b.text||"";if($||C.length>0){let k={role:T,content:$};C.length>0&&(k.images=C),c.push(k)}}let l=d==="Local"||!e||e==="LOCAL",u={host:l?process.env.OLLAMA_HOST||"http://127.0.0.1:11434":process.env.OLLAMA_HOST||"https://ollama.com"};!l&&e&&(u.headers={Authorization:"Bearer "+e});let p=new Ql(u),g=[],y=null,m=Date.now(),w=!1,x={Fast:!1,Low:"medium",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},S=x[s]!==void 0?x[s]:!0,R={model:n,messages:c,stream:!0,think:S,keep_alive:"10m",options:{temperature:h}},E=await p.chat(R);for await(let b of E){if(r?.aborted)throw new DOMException("The user aborted a request.","AbortError");if(b.message?.thinking&&(g.push({text:b.message.thinking,thought:!0}),w=!0),b.message?.content&&(g.push({text:b.message.content}),w=!0),b.done){let T=b.prompt_cached_count||0;if(!T&&b.prompt_eval_count){let $=b.prompt_eval_duration||0;$>0&&$<5e7&&(T=b.prompt_eval_count)}y={totalTokenCount:(b.prompt_eval_count||0)+(b.eval_count||0),promptTokenCount:b.prompt_eval_count||0,candidatesTokenCount:b.eval_count||0,cachedContentTokenCount:T,thoughtsTokenCount:0},w=!0}(b.done||Date.now()-m>=150&&w)&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],m=Date.now(),w=!1)}w&&(g.length>0||y)&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y})},dm=()=>{Ot=!0},fm=()=>Ot,Ki={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",goal:"Planning",Goal:"Planning",invoke_sync:"Sub-Agent Working",invoke:"Starting Agent",get_progress:"Checking Progress",cancel:"Cancelling",await:"Waiting",EmergencyRollback:"Don't Panic. Lookin' into it",answer:"Answering Sub-Agent",Answer:"Answering Sub-Agent",steer:"Steering Sub-Agent",Steer:"Steering Sub-Agent",Click:"Clicking",click:"Clicking",Drag:"Dragging",drag:"Dragging",Scroll:"Scrolling",scroll:"Scrolling",KeyboardTyping:"Typing",keyboard_typing:"Typing",KeyPress:"Pressing Key",key_press:"Pressing Key",RecaptureScreen:"Recapturing Screen",recapture_screen:"Recapturing Screen"},xs=(e,n)=>{try{let t=I(n),o=e.toLowerCase().replace(/_/g,"");if(o==="invokesync"||o==="invoke")return t.title||(t.task?t.task.substring(0,30):null);if(o==="getprogress"||o==="cancel"||o==="steer"||o==="steersubagent")return t.id||t.taskId;let s=t.path||t.targetFile||t.TargetFile||t.directory;return s?Q.basename(s.replace(/["']/g,"").replace(/\\/g,"/")):null}catch{return null}},Qi=e=>e?new Ta({apiKey:e}):zi,um=async(e,n,t,o,s={})=>{let{onStatus:r,onMemoryUpdated:h,onBackgroundIncrement:d}=s,{profile:c,thinkingLevel:l,mode:f,janitorModel:u,chatId:p,systemSettings:g,sessionStats:y,aiProvider:m="Google",apiKey:w}=e,x=process.env.NVIDIA_BASE_URL||m==="Ollama"?!1:g?.memory!==!1,R=X(Dt,[]).map(M=>`- [${M.id}]: ${M.memory}`).join(`
512
- `),E=o.slice(0,-1).filter(M=>M.text&&!M.text.includes("[TOOL RESULT]")&&!M.text.includes("OBSERVATION:")&&!M.text.startsWith("[TERMINAL_RECORD]")&&!M.isTerminalRecord&&!M.isMeta&&!M.isLogo&&!String(M.id).startsWith("welcome")&&!String(M.id).startsWith("logo")).slice(-14).map(M=>{let F=mc(M.text).replace(/\[tool:functions\..*?\]/g,"").replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[METADATA \(PRIORITY: DYNAMIC\)\] Time: ([^|\n]+)/g,(De,Ue)=>`[METADATA (PRIORITY: DYNAMIC)] Time: ${Ue.replace(/:\d{2}/g,"")}`).replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[TOOL RESULTS\]/g,"").replace(/\[tool results\]/g,"").replace(/\r?\n\r?\n/g,`
499
+ `,h+=Vi(g,n,t+1,o,s,y))}}return f.length>0&&(h+=`${r}${f.join("; ")}
500
+ `),h};import Ji from"path";import nc from"fs";var sc=e=>{try{return nc.readdirSync(e,{withFileTypes:!0})}catch{return[]}},Xi=(e,n,t="",o=1,s=sc,i=[])=>{let a=s(e),r=Ji.sep;if(a.length>100)return`${t}\u2514\u2500\u2500 ${Ji.basename(e)}${r} ...100+ files...
501
+ `;let h="",d=i,c=a.filter(f=>!d.includes(f.name)&&!f.name.startsWith(".")),l=a.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=Ji.join(e,f.name),m=g?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",w=t+(g?" ":"\u2502 ");if(f.isCollapsed){h+=`${t}${m}${f.name}${r}...
502
+ `;return}f.isDir?o>n?h+=`${t}${m}${f.name}${r} ...depth exceeded...
503
+ `:s(y).length>80?h+=`${t}${m}${f.name}${r} ...80+ files...
504
+ `:(h+=`${t}${m}${f.name}${r}
505
+ `,h+=Xi(y,n,w,o+1,s,i)):h+=`${t}${m}${f.name}
506
+ `}),h};import"@google/genai";oc.config({quiet:!0});var rc=/```[\s\S]*?```/g,ac=/```[\s\S]*$/g,lc=/`[^`]+`/g,cc=/^\|.*\|$/gm,dc=/^[^\w]+|[^\w]+$/g,fc=/[^a-z0-9]/gi,ho=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,uc=/\[\s*(?:tool:functions\.|agent:generalist\.)([a-z0-9_]+)\s*\(/gi,hc=/(?:path|targetFile|TargetFile|directory|keyword|id|taskId|title|task)\s*=\s*\\?["']?([^\\"' \),]+)/,ys=/["']/g,ba=/\\/g,pc=/<\|channel>thought/gi,mc=/<channel\|>/gi,Pn=e=>typeof e!="string"?e:e.replace(pc,"<think>").replace(mc,"</think>"),gc=/(?:<(think|thought|thoughts)>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\])/gi,yc=/(?:<(think|thought|thoughts)>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*$/gi,Sa=/(?:<think>|<\|channel>thought|\[think\])[\s\S]*?(?:<\/think>|<channel\|>|\[\/think\]|$)/gi,ka=/(?:<(think|thought|thoughts)>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\]|$)/gi,Aa=/`[^`]*`/g,va=/`[^`]*$/,Ta=/<\|\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,wc=/"([^"]+)"\s*:\s*(?:"([^"]*)"|(\d+)|true|false|null)/g,Ra=/<\|\s*tool_calls_section_begin\s*\|>/gi,Ea=/<\|\s*tool_calls_section_end\s*\|>/gi,xc=/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi,$a=/<(\w+)(?:[^>]*)>\r?\n?/gi,Ca=/\r?\n?<\/\w+(?:[^>]*)>/gi,Zi=null,Wo={},ws={key:null,value:null},gn=e=>e&&e.replace(/(?:(\x1b\[\d+m))?([✔✘✖🔍📖→➕↻↷•🛇])(?:(\x1b\[\d+m))?\s*\b(Clicked|Dragged|Scrolled|Typed|Pressed Key|Recaptured Screen|Created|Read|Edited|Viewed|Processed|Auto-Read|Skipped|List|Generated|Written|Searched|AI Search|Get Map|Write Canceled|Resolved Sub-Agent Query|Edit Canceled|Write Cancelled|Edit Denied|Visited|Updated|Reviewed|Delegated|Background|Checked|Indexed|Analyzed|Browsed|Elevating SubAgent|Checking SubAgent Work|Started Generalist|Called Generalist|Steered|Unsupported Modality|Awaiting|Cancelled|Aligning Moon Phase|Contemplating Existence|Staring At Void|Rollback Point Checked|Emergency Rollback Failed|Emergency Rollback|Delaying Professionally|Negotiating With Electrons|Touching Grass (virtually)|Panicking Softly|Rethinking Career Choices|Loading Cat Videos|Giving Up Entirely|Summoning Braincell #2|Pretending To Be Busy|Waiting For Motivation DLC|Rotating Internal Screaming|Downloading More RAM|Feeding The Hamsters|Gaslighting Scheduler|Performing Dramatic Pause|Buffering Social Energy|Calculating Regret|Reading Terms And Conditions|Becoming Sentient Briefly|Contacting Ancestors)\b/ig,(n,t,o,s,i)=>`${t||""}${o}${s||""} \x1B[95m${i}\x1B[0m`),bc=async(e,n=8,t=1e3,o=8e3,s=null)=>{let i=0;for(;;){if(s?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{return await e()}catch(a){if(s?.aborted||a?.name==="AbortError"||a?.message==="Subagent task was cancelled."||(i++,i>=n))throw a;let r=Math.min(t*Math.pow(2,i-1),o);await new Promise((h,d)=>{let c=setTimeout(h,r);s&&s.addEventListener("abort",()=>{clearTimeout(c),d(new DOMException("The user aborted a request.","AbortError"))})})}}},Ot=!1;var Sc=e=>{let n=e.filter(s=>(s.role==="user"||s.role==="agent"||s.role==="system")&&s.role!=="think"&&!s.isVisualFeedback&&!s.isMeta&&!s.isTerminalRecord&&!(s.text&&s.text.includes("[TERMINAL_RECORD]"))&&!String(s.id).startsWith("welcome")).map((s,i,a)=>{let r=s.fullText||s.text||"";if(s.role==="user"&&i<a.length-1)if(r.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")){let h=r.indexOf("**CONTEXT SUMMARY OF PREVIOUS TURNS");if(h!==-1){let c=r.substring(0,h).lastIndexOf("[SYSTEM METADATA]");c!==-1?r=r.substring(c).trim():r=r.substring(h).trim()}}else{let h=r.lastIndexOf("[USER]"),d=r.lastIndexOf("[USER PROMPT]");h!==-1?r=r.substring(h+6).trim():d!==-1&&(r=r.substring(d).trim())}return{...s,text:r}}),t=[],o=0;for(;o<n.length;){let s=n[o];if(s.role==="user")t.push(s),o++;else{let i=[];for(;o<n.length&&n[o].role!=="user";)i.push(n[o]),o++;let a=[],r=[],h=[];i.forEach(d=>{let c=(d.text||"").toLowerCase(),l=c.includes("tool:functions.")||c.includes("agent:generalist."),u=d.role==="system"&&(d.text?.startsWith("[TOOL RESULT]")||d.text?.startsWith("SUCCESS:")||d.text?.startsWith("ERROR:"));d.role==="agent"?l?a.push(d.text):h.push(d.text):u?r.push(d.text):h.push(d.text)}),a.length>0&&t.push({role:"agent",text:"combined"}),r.length>0&&t.push({role:"system",text:"combined"}),h.length>0&&t.push({role:"agent",text:"combined"})}}return t.length},kc=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),Ho=async(e,n,t=5,o=1e3)=>{let s=n?.signal;for(let a=0;a<t;a++){if(s?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{let r=await fetch(e,n);if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),r.ok||r.status!==429&&r.status<500)return r}catch(r){if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),r.name==="AbortError"||s?.aborted||a===t-1)throw r}s?await new Promise((r,h)=>{let d=setTimeout(()=>{s.removeEventListener("abort",c),r()},Math.min(24e3,o*Math.pow(2,a))),c=()=>{clearTimeout(d),h(new DOMException("The user aborted a request.","AbortError"))};s.addEventListener("abort",c)}):await new Promise(r=>setTimeout(r,Math.min(24e3,o*Math.pow(2,a))))}if(s?.aborted)throw new DOMException("The user aborted a request.","AbortError");let i=await fetch(e,n);return typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),i},er=async function*(e,n,t,o,s,i,a,r,h=.99){let d=[];o&&d.push({role:"system",content:o});for(let x of t){let S=x.role==="user"?"user":"assistant",R=[];if(Array.isArray(x.parts)){for(let E of x.parts)if(E.text)R.push({type:"text",text:E.text});else if(E.inlineData&&a){let k=E.inlineData.mimeType,T=E.inlineData.data;k.startsWith("image/")&&R.push({type:"image_url",image_url:{url:`data:${k};base64,${T}`}})}}else{let E=x.text||"";E&&R.push({type:"text",text:E})}d.push({role:S,content:R.length===1&&R[0].type==="text"?R[0].text:R})}let c={model:n,messages:d,stream:!0,stream_options:{include_usage:!0},temperature:h};if(s!=="Fast"){let x={Low:"high",Medium:"high",Standard:"high",High:"max",xHigh:"max"};c.reasoning_effort=x[s]||"high",c.extra_body={thinking:{type:"enabled"}}}else c.extra_body={thinking:{type:"disabled"}};let l=await Ho("https://api.deepseek.com/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(c),signal:r});if(!l.ok){let x=await l.json().catch(()=>({}));throw new Error(`DeepSeek Error (${l.status}): ${x.error?.message||l.statusText}`)}let u=l.body.getReader(),f=new TextDecoder,p="",g=[],y=null,m=Date.now(),w=!1;for(;;){let{done:x,value:S}=await u.read();if(x){w&&(g.length>0||y)&&(yield{candidates:g.length>0?[{content:{parts:g}}]:[],usageMetadata:y});break}p+=f.decode(S,{stream:!0});let R=p.split(`
507
+ `);p=R.pop();for(let E of R){let k=E.trim();if(!k||!k.startsWith("data: "))continue;let T=!1;if(k==="data: [DONE]")T=!0;else try{let $=JSON.parse(k.substring(6)),C=$.choices?.[0]?.delta,b=$.usage;if($.choices?.[0]?.finish_reason&&(T=!0),b&&(y={totalTokenCount:b.total_tokens||b.prompt_tokens+b.completion_tokens,promptTokenCount:b.prompt_tokens||0,candidatesTokenCount:b.completion_tokens||0,cachedContentTokenCount:b.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:b.completion_tokens_details?.reasoning_tokens||0},w=!0),C){let v=C.reasoning_content||null;v&&(g.push({text:v,thought:!0}),w=!0),C.content&&(g.push({text:C.content}),w=!0)}}catch{}if((T||Date.now()-m>=150)&&w&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],m=Date.now(),w=!1),T)break}Date.now()-m>=150&&w&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],m=Date.now(),w=!1)}},tr=async function*(e,n,t,o,s,i,a,r,h=.99){let d=[];o&&d.push({role:"system",content:o});for(let R of t){let E=R.role==="user"?"user":"assistant",k=[];if(Array.isArray(R.parts)){for(let T of R.parts)if(T.text)k.push({type:"text",text:T.text});else if(T.inlineData&&a){let $=T.inlineData.mimeType,C=T.inlineData.data;$.startsWith("image/")&&k.push({type:"image_url",image_url:`data:${$};base64,${C}`})}}else{let T=R.text||"";T&&k.push({type:"text",text:T})}k.length>0&&d.push({role:E,content:k.length===1&&k[0].type==="text"?k[0].text:k})}let c={Fast:"none",Low:"none",Medium:"high",Standard:"high",High:"high",xHigh:"high"},l={model:n,messages:d,stream:!0,temperature:h,prompt_cache_key:"flux-flow-session"};s&&s!=="Fast"&&qs(n)&&(l.reasoning_effort=c[s]||"high");let u=await Ho("https://api.mistral.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(l),signal:r});if(!u.ok){let R=await u.text().catch(()=>""),E=u.statusText;try{let k=JSON.parse(R);E=k.error?.message||k.message||JSON.stringify(k.detail||k)}catch{R&&(E=R)}throw new Error(`Mistral Error (${u.status}): ${JSON.stringify(E)}`)}let f=u.body.getReader(),p=new TextDecoder,g="",y=[],m=null,w=Date.now(),x=!1,S=R=>R?typeof R=="string"?Pn(R):Array.isArray(R)?R.map(S).filter(Boolean).join(""):typeof R=="object"&&R!==null?typeof R.text=="string"?Pn(R.text):typeof R.content=="string"?Pn(R.content):typeof R.thinking=="string"?Pn(R.thinking):typeof R.reasoning_content=="string"?Pn(R.reasoning_content):typeof R.reasoning=="string"?Pn(R.reasoning):typeof R.value=="string"?Pn(R.value):R.text?S(R.text):R.content?S(R.content):R.thinking?S(R.thinking):R.reasoning_content?S(R.reasoning_content):R.reasoning?S(R.reasoning):R.value?S(R.value):"":Pn(String(R)):"";for(;;){let{done:R,value:E}=await f.read();if(R){x&&(y.length>0||m)&&(yield{candidates:y.length>0?[{content:{parts:y}}]:[],usageMetadata:m});break}g+=p.decode(E,{stream:!0});let k=g.split(`
508
+ `);g=k.pop();for(let T of k){let $=T.trim();if(!$||!$.startsWith("data: "))continue;let C=!1;if($==="data: [DONE]")C=!0;else try{let b=JSON.parse($.substring(6)),v=b.choices?.[0]?.delta,I=b.usage;if(b.choices?.[0]?.finish_reason&&(C=!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),v){let D=v.thinking||v.reasoning_content||v.reasoning,j=S(D);j&&(y.push({text:j,thought:!0}),x=!0);let U=v.content||(!v.thinking&&!v.reasoning_content&&!v.reasoning?v.text:null);if(U)if(Array.isArray(U))for(let Y of U)if(typeof Y=="object"&&Y!==null){let ie=Y.type==="thinking"||Y.type==="reasoning"||!!Y.thought,_e=S(Y);_e&&(y.push({text:_e,...ie?{thought:!0}:{}}),x=!0)}else{let ie=S(Y);ie&&(y.push({text:ie}),x=!0)}else if(typeof U=="object"&&U!==null){let Y=U.type==="thinking"||U.type==="reasoning"||!!U.thought,ie=S(U);ie&&(y.push({text:ie,...Y?{thought:!0}:{}}),x=!0)}else{let Y=S(U);Y&&(y.push({text:Y}),x=!0)}}}catch{}if((C||Date.now()-w>=150)&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),x=!1),C)break}Date.now()-w>=150&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),x=!1)}},nr=async function*(e,n,t,o,s,i,a=!1,r,h=.99){let d=[];o&&d.push({role:"system",content:o}),t.forEach(re=>{let Re=re.role==="model"?"assistant":"user",M=[];Array.isArray(re.parts)&&re.parts.forEach(F=>{if(F.text)M.push({type:"text",text:F.text});else if(F.inlineData&&a){let V=F.inlineData.mimeType,J=F.inlineData.data;V.startsWith("image/")&&fn(n)&&M.push({type:"image_url",image_url:{url:`data:${V};base64,${J}`}})}}),d.push({role:Re,content:M.length===1&&M[0].type==="text"?M[0].text:M})});let l={Fast:"Fast",Low:"Fast",Medium:"Standard",Standard:"Standard",High:"High",xHigh:"High"}[s]||"High",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"),S=n.includes("qwen"),R=n.includes("nemotron"),E=n.includes("llama-3"),k=n.includes("seed"),T=n.includes("poolside"),$=n.includes("thinkingmachines")||n.includes("muse"),C=E,b=null,v={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"},D={Fast:"none",Low:"minimal",Medium:"medium",Standard:"medium",High:"max",xHigh:"max"},j=w||g||T||$?16384:32768;j=process.env.NVIDIA_BASE_URL?1024:j,j=b?1024:j;let U={model:n,messages:d,max_tokens:j,stream:!0,stream_options:{include_usage:!0},temperature:h,...x&&{thinking:v[s]||"high"}};if(!(process.env.NVIDIA_BASE_URL||C||b))if(f)U.chat_template_kwargs={thinking:u};else if(p)U.chat_template_kwargs={enable_thinking:u};else if(g)if(u){let re=l==="High"?"max":"high";U.chat_template_kwargs={thinking:!0,reasoning_effort:re}}else U.chat_template_kwargs={thinking:!1};else y?U.chat_template_kwargs={enable_thinking:u,clear_thinking:!u}:m?U.reasoning_effort=u?"high":"none":w&&n.includes("minimax-m3")?U.chat_template_kwargs={thinking_mode:u?"enabled":"disabled"}:S?U.chat_template_kwargs={enable_thinking:u}:R?l==="High"?(U.reasoning_budget=12e3,U.chat_template_kwargs={enable_thinking:!0}):l==="Standard"?(U.reasoning_budget=12e3,U.chat_template_kwargs={enable_thinking:!0,medium_effort:!0}):U.chat_template_kwargs={enable_thinking:!1}:k?u&&(U.extra_body={thinking_budget:parseInt(I[l]??"4096")}):T?U.chat_template_kwargs={enable_thinking:u}:$&&(U.reasoning_effort=D[l]||"medium");let Y=0,ie=6,_e=!1,N=process.env.NVIDIA_BASE_URL||"https://integrate.api.nvidia.com/v1/chat/completions",W=process.env.NVIDIA_API_KEY&&process.env.NVIDIA_BASE_URL?process.env.NVIDIA_API_KEY:e;for(N.endsWith("/chat/completions")||(N=N.replace(/\/+$/,"")+"/chat/completions");Y<ie;){Y++;try{let re=await Ho(N,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${W}`},body:JSON.stringify(U),signal:r});if(!re.ok){let Ue=await re.text().catch(()=>""),st=re.statusText;try{let ut=JSON.parse(Ue);st=ut.error?.message||ut.message||JSON.stringify(ut.detail||ut)}catch{Ue&&(st=Ue)}let Ge=new Error(`NVIDIA API Error (${re.status}): ${st}`);throw Ge.status=re.status,Ge}let Re=re.body.getReader(),M=new TextDecoder,F="",V=[],J=null,Ne=Date.now(),De=!1;for(;;){let{done:Ue,value:st}=await Re.read();if(Ue){De&&(V.length>0||J)&&(yield{candidates:V.length>0?[{content:{parts:V}}]:[],usageMetadata:J},_e=!0);break}F+=M.decode(st,{stream:!0});let Ge=F.split(`
509
+ `);F=Ge.pop();let ut=!1;for(let Nt of Ge){let ht=Nt.trim();if(ht){if(ht==="data: [DONE]"){ut=!0;break}if(ht.startsWith("data: ")){let pt;try{pt=JSON.parse(ht.substring(6))}catch{continue}if(pt.error)throw new Error(`NVIDIA Stream Error: ${pt.error.message||JSON.stringify(pt.error)}`);pt.choices?.[0]?.finish_reason&&(ut=!0);try{let kt=pt.usage;kt&&(J={totalTokenCount:kt.total_tokens||kt.prompt_tokens+kt.completion_tokens,promptTokenCount:kt.prompt_tokens||0,candidatesTokenCount:kt.completion_tokens||0,cachedContentTokenCount:kt.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:(kt.completion_tokens_details?.reasoning_tokens||0)+(kt.completion_tokens_details?.thoughts_tokens||0)},De=!0);let Tt=pt.choices?.[0]?.delta?.reasoning||pt.choices?.[0]?.delta?.reasoning_content||"",Xe=pt.choices?.[0]?.delta?.content||"";Tt&&(V.push({text:Tt,thought:!0}),De=!0),Xe&&(V.push({text:Xe}),De=!0)}catch{}}}}if((ut||Date.now()-Ne>=350)&&De&&(yield{candidates:V.length>0?[{content:{parts:[...V]}}]:[],usageMetadata:J},_e=!0,V=[],Ne=Date.now(),De=!1),ut)break}break}catch(re){if(_e||Y>=ie)throw re;await new Promise(Re=>setTimeout(Re,3500))}}},Tc=async function*(e,n){let t=[],o=null,s=!1,i=null,a=u=>{if(t.push(u),o){let f=o;o=null,f()}},r=n.split("/").pop();r=r.replace("llama-3.3","llama-3_3");let h=`https://api.ngc.nvidia.com/v2/predict/queues/models/qc69jvmznzxy/${r}`,d=!1,c=null,l=async()=>{try{let 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||a({value:{type:"status",content:`Queue ${p||1}`},done:!1})}}else d||a({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),a({value:f,done:!1})}s=!0,a(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)}},sr=async function*(e,n,t,o,s,i,a,r,h=.95){let d=[];o&&d.push({role:"system",content:[{type:"text",text:o,cache_control:{type:"ephemeral"}}]});for(let R of t){let E=R.role==="user"?"user":"assistant",k=[];if(Array.isArray(R.parts)){for(let T of R.parts)if(T.text)k.push({type:"text",text:T.text});else if(T.inlineData&&a){let $=T.inlineData.mimeType,C=T.inlineData.data;$.startsWith("image/")?k.push({type:"image_url",image_url:{url:`data:${$};base64,${C}`}}):k.push({type:"file",file:{filename:T.filename||"file",file_data:`data:${$};base64,${C}`}})}}else{let T=R.text||"";T&&k.push({type:"text",text:T})}d.push({role:E,content:k.length===1&&k[0].type==="text"?k[0].text:k})}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 Ho("https://openrouter.ai/api/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json","X-Title":"FluxFlow CLI","X-Cache":"true","X-OpenRouter-Cache":"true"},body:JSON.stringify(l),signal:r});if(!f.ok){let R=await f.json().catch(()=>({}));throw new Error(`OpenRouter Error (${f.status}): ${R.error?.message||f.statusText}`)}let p=f.body.getReader(),g=new TextDecoder,y="",m=[],w=null,x=Date.now(),S=!1;for(;;){let{done:R,value:E}=await p.read();if(R){S&&(m.length>0||w)&&(yield{candidates:m.length>0?[{content:{parts:m}}]:[],usageMetadata:w});break}y+=g.decode(E,{stream:!0});let k=y.split(`
510
+ `);y=k.pop();for(let T of k){let $=T.trim();if(!$||!$.startsWith("data: "))continue;let C=!1;if($==="data: [DONE]")C=!0;else try{let b=JSON.parse($.substring(6)),v=b.choices?.[0]?.delta,I=b.usage;if(b.choices?.[0]?.finish_reason&&(C=!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},S=!0),v){let D=v.reasoning||(v.reasoning_details?v.reasoning_details.map(j=>j.text).join(""):null);D&&(m.push({text:D,thought:!0}),S=!0),v.content&&(m.push({text:v.content}),S=!0)}}catch{}if((C||Date.now()-x>=150)&&S&&(yield{candidates:m.length>0?[{content:{parts:[...m]}}]:[],usageMetadata:w},m=[],x=Date.now(),S=!1),C)break}}},Ia=async function*(e,n,t,o,s,i,a,r,h=1.05,d="Cloud"){let c=[];o&&c.push({role:"system",content:o});for(let k of t){let T=k.role==="user"?"user":"assistant",$="",C=[];if(Array.isArray(k.parts)){$=k.parts.map(b=>b.text||"").filter(Boolean).join(`
511
+ `);for(let b of k.parts){let v=b.inlineData||b.inline_data;v&&v.data&&C.push(v.data)}}else $=k.text||"";if($||C.length>0){let b={role:T,content:$};C.length>0&&(b.images=C),c.push(b)}}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 ic(f),g=[],y=null,m=Date.now(),w=!1,x={Fast:!1,Low:"medium",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},S=x[s]!==void 0?x[s]:!0,R={model:n,messages:c,stream:!0,think:S,keep_alive:"10m",options:{temperature:h}},E=await p.chat(R);for await(let k of E){if(r?.aborted)throw new DOMException("The user aborted a request.","AbortError");if(k.message?.thinking&&(g.push({text:k.message.thinking,thought:!0}),w=!0),k.message?.content&&(g.push({text:k.message.content}),w=!0),k.done){let T=k.prompt_cached_count||0;if(!T&&k.prompt_eval_count){let $=k.prompt_eval_duration||0;$>0&&$<5e7&&(T=k.prompt_eval_count)}y={totalTokenCount:(k.prompt_eval_count||0)+(k.eval_count||0),promptTokenCount:k.prompt_eval_count||0,candidatesTokenCount:k.eval_count||0,cachedContentTokenCount:T,thoughtsTokenCount:0},w=!0}(k.done||Date.now()-m>=150&&w)&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],m=Date.now(),w=!1)}w&&(g.length>0||y)&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y})},bm=()=>{Ot=!0},Sm=()=>Ot,Qi={write_file:"Writing",update_file:"Editing",read_folder:"Reading",view_file:"Reading",exec_command:"Executing Command",web_search:"Searching",web_scrape:"Reading",memory:"Updating Memory",search_keyword:"Searching",file_map:"Generating Map",ask:"User Input",write_pdf:"Creating",write_docx:"Creating",generate_image:"Generating",todo:"Planning",Todo:"Planning",goal:"Planning",Goal:"Planning",invoke_sync:"Sub-Agent Working",invoke:"Starting Agent",get_progress:"Checking Progress",cancel:"Cancelling",await:"Waiting",EmergencyRollback:"Don't Panic. Lookin' into it",answer:"Answering Sub-Agent",Answer:"Answering Sub-Agent",steer:"Steering Sub-Agent",Steer:"Steering Sub-Agent",Click:"Clicking",click:"Clicking",Drag:"Dragging",drag:"Dragging",Scroll:"Scrolling",scroll:"Scrolling",KeyboardTyping:"Typing",keyboard_typing:"Typing",KeyPress:"Pressing Key",key_press:"Pressing Key",RecaptureScreen:"Recapturing Screen",recapture_screen:"Recapturing Screen"},xs=(e,n)=>{try{let t=O(n),o=e.toLowerCase().replace(/_/g,"");if(o==="invokesync"||o==="invoke")return t.title||(t.task?t.task.substring(0,30):null);if(o==="getprogress"||o==="cancel"||o==="steer"||o==="steersubagent")return t.id||t.taskId;let s=t.path||t.targetFile||t.TargetFile||t.directory;return s?Q.basename(s.replace(/["']/g,"").replace(/\\/g,"/")):null}catch{return null}},or=e=>e?new Ma({apiKey:e}):Zi,km=async(e,n,t,o,s={})=>{let{onStatus:r,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,R=X(Dt,[]).map(M=>`- [${M.id}]: ${M.memory}`).join(`
512
+ `),E=o.slice(0,-1).filter(M=>M.text&&!M.text.includes("[TOOL RESULT]")&&!M.text.includes("OBSERVATION:")&&!M.text.startsWith("[TERMINAL_RECORD]")&&!M.isTerminalRecord&&!M.isMeta&&!M.isLogo&&!String(M.id).startsWith("welcome")&&!String(M.id).startsWith("logo")).slice(-14).map(M=>{let F=kc(M.text).replace(/\[tool:functions\..*?\]/g,"").replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[METADATA \(PRIORITY: DYNAMIC\)\] Time: ([^|\n]+)/g,(De,Ue)=>`[METADATA (PRIORITY: DYNAMIC)] Time: ${Ue.replace(/:\d{2}/g,"")}`).replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[TOOL RESULTS\]/g,"").replace(/\[tool results\]/g,"").replace(/\r?\n\r?\n/g,`
513
513
  `).replace(/\n\n/g,`
514
- `).replace(/\\n\\n/g,"").trim(),Y=M.role==="user"?8192:32768,J=F.substring(0,Y);F.length>Y&&(J+=`
515
- ... (truncated) ...`);let Ne=M.role==="user"?J.startsWith("[USER]")?"":"[USER]: ":J.startsWith("[AGENT]")?"":"[AGENT]: ";return{role:M.role==="user"?"user":"model",parts:[{text:`${Ne}${J}`}]}}),b=o.filter(M=>M.role==="user").length===1,T=n.includes("[TITLE-UPDATE]"),$=Math.random()<.8,C=b||T||$,k=t.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").trim(),O=wr(R,x,C),v=`${k.replace(/\[tool:functions\..*?\]/g,"").replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[\[TOOL RESULTS\]\]/g,"").replace(/\[tool results\]/g,"").substring(0,32768)}`;v.length>32768&&(v+=`
516
- ... (truncated) ...`);let L=n.replace(/\[Prompted on:.*?\]/g,"").trim();v=v.replace(/\r?\n\r?\n/g,`
514
+ `).replace(/\\n\\n/g,"").trim(),V=M.role==="user"?8192:32768,J=F.substring(0,V);F.length>V&&(J+=`
515
+ ... (truncated) ...`);let Ne=M.role==="user"?J.startsWith("[USER]")?"":"[USER]: ":J.startsWith("[AGENT]")?"":"[AGENT]: ";return{role:M.role==="user"?"user":"model",parts:[{text:`${Ne}${J}`}]}}),k=o.filter(M=>M.role==="user").length===1,T=n.includes("[TITLE-UPDATE]"),$=Math.random()<.8,C=k||T||$,b=t.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").trim(),v=Rr(R,x,C),I=`${b.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+=`
516
+ ... (truncated) ...`);let D=n.replace(/\[Prompted on:.*?\]/g,"").trim();I=I.replace(/\r?\n\r?\n/g,`
517
517
  `).replace(/\n\n/g,`
518
- `).replace(/\\n\\n/g,"").trim();let N=new Date,V=`[METADATA] Current date and Time: ${`${N.getFullYear()}-${N.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(N.getDate()).padStart(2,"0")}, ${N.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0})}`}
518
+ `).replace(/\\n\\n/g,"").trim();let j=new Date,Y=`[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})}`}
519
519
 
520
- [USER]: ${L.substring(0,8192)}
521
- ${L.length>8192?`... (truncated) ...
520
+ [USER]: ${D.substring(0,8192)}
521
+ ${D.length>8192?`... (truncated) ...
522
522
 
523
523
  `:""}
524
- [AGENT (current turn)]: ${v}`;E.push({role:"user",parts:[{text:V}]});let oe=await Xo("NVIDIA"),B=(await Ft()).quotas?.providerTiers?.NVIDIA==="Free",W="",re=0,Re=x?12:-1;for(;re<=Re;)try{if(!await Rr("background",e))return;let M="",F=null,Y=!1,J=m;try{let Ue=new Promise((Tt,Xe)=>setTimeout(()=>Xe(new Error("JANITOR_TIMEOUT")),1e4)),st=m==="Google"&&re>=0&&re<6&&oe&&B,Ge=m==="DeepSeek"&&re<4&&oe&&B;Y=st||Ge,J=Y?"NVIDIA":m;let ut=(async()=>{if(m==="OpenRouter"){let Tt=et("janitor_open_router"),ye=Xi(w,Tt,E,O,"Fast",f,!1,null,.6)[Symbol.asyncIterator](),Kt=await ye.next();return{iterator:ye,firstResult:Kt}}else if(m==="DeepSeek"&&!Y){let Xe=Yi(w,et("deepseek_fast_fallback"),E,O,"Fast",f,!1,null,.6)[Symbol.asyncIterator](),ye=await Xe.next();return{iterator:Xe,firstResult:ye}}else if(m==="Mistral"&&!Y){let Xe=Vi(w,et("mistral_janitor_fallback"),E,O,"Fast",f,!1,null,.6)[Symbol.asyncIterator](),ye=await Xe.next();return{iterator:Xe,firstResult:ye}}else if(m==="NVIDIA"||Y){let Xe=Ji(Y?oe:w,et("nvidia_janitor_fallback"),E,O,"Fast",f,!1,null,.6)[Symbol.asyncIterator](),ye=await Xe.next();return{iterator:Xe,firstResult:ye}}else{let ye=(await Qi(w).models.generateContentStream({model:u||(re===Re?et("janitor_default"):et("gemma_janitor_fallback_google")),contents:E,config:{systemInstruction:O,temperature:.7,safetySettings:[{category:Vn.HARM_CATEGORY_HARASSMENT,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_HATE_SPEECH,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Yn.BLOCK_NONE}],thinkingConfig:{includeThoughts:!1,thinkingLevel:at.MINIMAL}}}))[Symbol.asyncIterator](),Kt=await ye.next();return{iterator:ye,firstResult:Kt}}})();if(process.stdout.isTTY){let ye=(await ls())[p]?.name||"",Kt=ye&&!ye.startsWith("flow-")&&!ye.startsWith("Session ")?ye:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${Kt}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${Kt}\x07`)}let{iterator:Nt,firstResult:ht}=await Promise.race([ut,Ue]),{value:pt,done:kt}=ht;if(!kt&&pt){let Tt=pt.candidates?.[0]?.content?.parts,Xe=Tt?J==="Google"?Tt[1]?.text||Tt[0]?.text||"":Tt.filter(ye=>ye.text&&!ye.thought).map(ye=>ye.text).join(""):typeof pt.text=="function"?pt.text():"";Xe&&(M+=Xe),F=pt.usageMetadata;for await(let ye of{[Symbol.asyncIterator]:()=>Nt}){let Kt=ye.candidates?.[0]?.content?.parts,Jn=Kt?J==="Google"?Kt[1]?.text||Kt[0]?.text||"":Kt.filter(Xn=>Xn.text&&!Xn.thought).map(Xn=>Xn.text).join(""):typeof ye.text=="function"?ye.text():"";Jn&&(M+=Jn),F=ye.usageMetadata}}}catch(Ue){throw Ue}if(M){if(W=M,F){let Ue=F.totalTokenCount||0,st=F.cachedContentTokenCount||0,Ge=(F.candidatesTokenCount||0)+(F.thoughtsTokenCount||0),ut=Y?et("nvidia_janitor_fallback"):J==="DeepSeek"?et("deepseek_fast_fallback"):J==="OpenRouter"?et("janitor_open_router"):u||(re===Re?et("janitor_default"):et("gemma_janitor_fallback_google"));await Gt("tokens",Ue,J,ut),st>0&&await Gt("cachedTokens",st,J,ut),Ge>0&&await Gt("candidateTokens",Ge,J,ut)}}else throw new Error("No synthesis generated by Janitor.");d&&(d(),await It("background"));let Ne=jo(W),De=!1;for(let Ue of Ne){let st=Ue.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(st)&&(De=!0);let Ge={chatId:p,sessionId:p,history:o},ut=await lo(st,Ue.args,Ge);st.toLowerCase()==="memory"&&(Ue.args.includes("action='user'")||Ue.args.includes('action="user"'))&&!ut.startsWith("ERROR")&&(h&&h(),process.stdout.isTTY&&(process.stdout.write("\x1B]0;Memory Updated\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=Memory Updated\x07")),await new Promise(ht=>setTimeout(ht,3e3)))}if(!De)try{let Ue=X(Dt,[]);if(Ue.length>0){let st=[];for(let Ge of Ue)Ge.score===void 0&&(Ge.score=.5),Ge.score*=.99995,Ge.score<.05&&(Ge.score=0),Ge.score=Math.round(Ge.score*1e5)/1e5,Ge.score>0&&st.push(Ge);he(Dt,st)}}catch{}break}catch(M){re++;let F=new Date().toLocaleString(),Y=M instanceof Error?(()=>{try{return JSON.parse(JSON.parse(M.message).error.message).error.message}catch{return String(M)}})():String(M);await new Promise(De=>setTimeout(De,1e3));let J=Q.join(cn,"janitor");if(ve.existsSync(J)||ve.mkdirSync(J,{recursive:!0}),ve.appendFileSync(Q.join(J,"error.log"),`ERROR [Attempt ${re}/${Re+1}] [${F}]: ${Y}
524
+ [AGENT (current turn)]: ${I}`;E.push({role:"user",parts:[{text:Y}]});let ie=await Zo("NVIDIA"),N=(await Ft()).quotas?.providerTiers?.NVIDIA==="Free",W="",re=0,Re=x?12:-1;for(;re<=Re;)try{if(!await Ar("background",e))return;let M="",F=null,V=!1,J=m;try{let Ue=new Promise((Tt,Xe)=>setTimeout(()=>Xe(new Error("JANITOR_TIMEOUT")),1e4)),st=m==="Google"&&re>=0&&re<6&&ie&&N,Ge=m==="DeepSeek"&&re<4&&ie&&N;V=st||Ge,J=V?"NVIDIA":m;let ut=(async()=>{if(m==="OpenRouter"){let Tt=et("janitor_open_router"),ye=sr(w,Tt,E,v,"Fast",u,!1,null,.6)[Symbol.asyncIterator](),zt=await ye.next();return{iterator:ye,firstResult:zt}}else if(m==="DeepSeek"&&!V){let Xe=er(w,et("deepseek_fast_fallback"),E,v,"Fast",u,!1,null,.6)[Symbol.asyncIterator](),ye=await Xe.next();return{iterator:Xe,firstResult:ye}}else if(m==="Mistral"&&!V){let Xe=tr(w,et("mistral_janitor_fallback"),E,v,"Fast",u,!1,null,.6)[Symbol.asyncIterator](),ye=await Xe.next();return{iterator:Xe,firstResult:ye}}else if(m==="NVIDIA"||V){let Xe=nr(V?ie:w,et("nvidia_janitor_fallback"),E,v,"Fast",u,!1,null,.6)[Symbol.asyncIterator](),ye=await Xe.next();return{iterator:Xe,firstResult:ye}}else{let ye=(await or(w).models.generateContentStream({model:f||(re===Re?et("janitor_default"):et("gemma_janitor_fallback_google")),contents:E,config:{systemInstruction:v,temperature:.7,safetySettings:[{category:Vn.HARM_CATEGORY_HARASSMENT,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_HATE_SPEECH,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Yn.BLOCK_NONE}],thinkingConfig:{includeThoughts:!1,thinkingLevel:at.MINIMAL}}}))[Symbol.asyncIterator](),zt=await ye.next();return{iterator:ye,firstResult:zt}}})();if(process.stdout.isTTY){let ye=(await ls())[p]?.name||"",zt=ye&&!ye.startsWith("flow-")&&!ye.startsWith("Session ")?ye:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${zt}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${zt}\x07`)}let{iterator:Nt,firstResult:ht}=await Promise.race([ut,Ue]),{value:pt,done:kt}=ht;if(!kt&&pt){let Tt=pt.candidates?.[0]?.content?.parts,Xe=Tt?J==="Google"?Tt[1]?.text||Tt[0]?.text||"":Tt.filter(ye=>ye.text&&!ye.thought).map(ye=>ye.text).join(""):typeof pt.text=="function"?pt.text():"";Xe&&(M+=Xe),F=pt.usageMetadata;for await(let ye of{[Symbol.asyncIterator]:()=>Nt}){let zt=ye.candidates?.[0]?.content?.parts,Jn=zt?J==="Google"?zt[1]?.text||zt[0]?.text||"":zt.filter(Xn=>Xn.text&&!Xn.thought).map(Xn=>Xn.text).join(""):typeof ye.text=="function"?ye.text():"";Jn&&(M+=Jn),F=ye.usageMetadata}}}catch(Ue){throw Ue}if(M){if(W=M,F){let Ue=F.totalTokenCount||0,st=F.cachedContentTokenCount||0,Ge=(F.candidatesTokenCount||0)+(F.thoughtsTokenCount||0),ut=V?et("nvidia_janitor_fallback"):J==="DeepSeek"?et("deepseek_fast_fallback"):J==="OpenRouter"?et("janitor_open_router"):f||(re===Re?et("janitor_default"):et("gemma_janitor_fallback_google"));await Gt("tokens",Ue,J,ut),st>0&&await Gt("cachedTokens",st,J,ut),Ge>0&&await Gt("candidateTokens",Ge,J,ut)}}else throw new Error("No synthesis generated by Janitor.");d&&(d(),await It("background"));let Ne=Go(W),De=!1;for(let Ue of Ne){let st=Ue.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(st)&&(De=!0);let Ge={chatId:p,sessionId:p,history:o},ut=await fo(st,Ue.args,Ge);st.toLowerCase()==="memory"&&(Ue.args.includes("action='user'")||Ue.args.includes('action="user"'))&&!ut.startsWith("ERROR")&&(h&&h(),process.stdout.isTTY&&(process.stdout.write("\x1B]0;Memory Updated\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=Memory Updated\x07")),await new Promise(ht=>setTimeout(ht,3e3)))}if(!De)try{let Ue=X(Dt,[]);if(Ue.length>0){let st=[];for(let Ge of Ue)Ge.score===void 0&&(Ge.score=.5),Ge.score*=.99995,Ge.score<.05&&(Ge.score=0),Ge.score=Math.round(Ge.score*1e5)/1e5,Ge.score>0&&st.push(Ge);he(Dt,st)}}catch{}break}catch(M){re++;let F=new Date().toLocaleString(),V=M instanceof Error?(()=>{try{return JSON.parse(JSON.parse(M.message).error.message).error.message}catch{return String(M)}})():String(M);await new Promise(De=>setTimeout(De,1e3));let J=Q.join(cn,"janitor");if(Ie.existsSync(J)||Ie.mkdirSync(J,{recursive:!0}),Ie.appendFileSync(Q.join(J,"error.log"),`ERROR [Attempt ${re}/${Re+1}] [${F}]: ${V}
525
525
 
526
- `),re>Re)break;let Ne=Math.min(750*Math.pow(2,re-1),5e3);await new Promise(De=>setTimeout(De,Ne))}if(re){let M=Q.join(cn,"janitor");ve.appendFileSync(Q.join(M,"error.log"),`-----------------------------------------------------------------------------
526
+ `),re>Re)break;let Ne=Math.min(750*Math.pow(2,re-1),5e3);await new Promise(De=>setTimeout(De,Ne))}if(re){let M=Q.join(cn,"janitor");Ie.appendFileSync(Q.join(M,"error.log"),`-----------------------------------------------------------------------------
527
527
 
528
- `)}if(process.stdout.isTTY)try{let Y=(await ls())[p]?.name||"",J=Y&&!Y.startsWith("flow-")&&!Y.startsWith("Session ")?Y:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${J}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${J}\x07`)}catch{process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")}},yc=e=>{let n=e.replace(cc,"").replace(dc,""),t=Is?n:n.replace(Ra,s=>" ".repeat(s.length)).replace(Ea,s=>" ".repeat(s.length));fo.lastIndex=0;let o;for(;(o=fo.exec(t))!==null;){let s=o.index+o[0].length-1,i=0,a=null,r=!1,h=!1;for(let d=s;d<t.length;d++){let c=n[d];if(!a&&(c==='"'||c==="'"||c==="`")?(a=c,r=!1):a&&c===a&&!r&&(a=null),!a&&(c==="("?i++:c===")"&&i--,i===0)){let l=d+1;for(;l<t.length&&/\s/.test(t[l]);)l++;if(l<t.length&&t[l]==="]"){h=!0,fo.lastIndex=l+1;break}}c==="\\"?r=!r:r=!1}if(!h)return{inside:!0,toolName:o[1],startIndex:o.index,args:n.substring(o.index+o[0].length)}}return{inside:!1}},Ca=(e,n=!0)=>{let t=fo;t.lastIndex=0;let o="",s=0,i;for(;(i=t.exec(e))!==null;){let a=e.substring(s,i.index);o+=n?a.replace(ma,""):a;let r=i.index+i[0].length-1,h=0,d=null,c=-1;for(let l=r;l<e.length;l++){let f=e[l];if(d){if(f===d){let u=0;for(let p=l-1;p>=0&&e[p]==="\\";p--)u++;u%2===0&&(d=null)}}else if(f==='"'||f==="'"||f==="`")d=f;else if(f==="(")h++;else if(f===")"&&(h--,h===0)){let u=l+1;for(;u<e.length&&/\s/.test(e[u]);)u++;if(u<e.length&&e[u]==="]"){c=u;break}}}if(c!==-1)o+="[tool:functions."+i[1]+"()]",s=c+1,t.lastIndex=s;else{o+="[tool:functions."+i[1]+"(",s=e.length;break}}return s<e.length&&(o+=n?e.substring(s).replace(ma,""):e.substring(s)),o},wc=(e,n,t)=>{let o=fo;o.lastIndex=0;let s="",i=0,a;for(;(a=o.exec(e))!==null;){let r=e.substring(i,a.index);s+=r.replace(n,t);let h=a.index+a[0].length-1,d=0,c=null,l=-1;for(let f=h;f<e.length;f++){let u=e[f];if(c){if(u===c){let p=0;for(let g=f-1;g>=0&&e[g]==="\\";g--)p++;p%2===0&&(c=null)}}else if(u==='"'||u==="'"||u==="`")c=u;else if(u==="(")d++;else if(u===")"&&(d--,d===0)){let p=f+1;for(;p<e.length&&/\s/.test(e[p]);)p++;if(p<e.length&&e[p]==="]"){l=p;break}}}if(l!==-1)s+=e.substring(a.index,l+1),i=l+1,o.lastIndex=i;else{s+=e.substring(a.index),i=e.length;break}}return i<e.length&&(s+=e.substring(i).replace(n,t)),s},ka=e=>Ca(e,!0),xc=e=>{if(!e)return e;let n={patchfile:"PatchFile",writefile:"WriteFile",readfile:"ReadFile",viewfile:"ReadFile",run:"Run",execcommand:"Run",searchkeyword:"SearchKeyword",codesearch:"CodeSearch",code_search:"CodeSearch",websearch:"WebSearch",webscrape:"WebScrape",readfolder:"ReadFolder",writepdf:"WritePDF",writedoc:"WriteDoc",writedocx:"WriteDoc",filemap:"FileMap",generateimage:"GenerateImage",todo:"Todo",goal:"Goal",ask:"Ask"},t=s=>s.split("_").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join("");ya.lastIndex=0;let o=e.replace(ya,(s,i,a)=>{let r="";try{let c=JSON.parse(a.trim());c&&typeof c=="object"&&(r=Object.entries(c).map(([f,u])=>{let p=typeof u=="string"?u:JSON.stringify(u);return`${f}=${JSON.stringify(p)}`}).join(", "))}catch{let l=[],f=fc;f.lastIndex=0;let u;for(;(u=f.exec(a))!==null;){let p=u[1],g=u[2]!==void 0?u[2]:u[0].split(":").slice(1).join(":").trim();l.push(`${p}=${JSON.stringify(g)}`)}l.length>0?r=l.join(", "):r=a.trim()}let h=i.toLowerCase().replace(/_/g,"");return`[tool:functions.${n[h]||t(i)}(${r})]`});return wa.lastIndex=0,xa.lastIndex=0,o=o.replace(wa,""),o=o.replace(xa,""),o},bc=/(?:path|query|url|keyword|command|method|title|task|id)\s*=\s*['"`]?\s*\.\.\.\s*['"`]?/i,Sc=/^['"`]?\s*\.\.\.\s*['"`]?$/,Ln=e=>{if(e==null)return!1;let n=String(e).trim();return n==="..."||n==="\u2026"||Sc.test(n)},jo=e=>{if(!e)return[];let n=xc(e);ga.lastIndex=0;let t=n.replace(ga,""),o=[],s=Is?t:t.replace(Ra,r=>" ".repeat(r.length)).replace(Ea,r=>" ".repeat(r.length)),i=ic;i.lastIndex=0;let a;for(;(a=i.exec(s))!==null;){let r=a[1],h=a.index+a[0].length-1,d=0,c=null,l=-1,f=-1;for(let u=h;u<s.length;u++){let p=t[u];if(c){if(p===c){let g=0;for(let y=u-1;y>=0&&t[y]==="\\";y--)g++;g%2===0&&(c=null)}}else if(p==='"'||p==="'"||p==="`")c=p;else if(p==="(")d++;else if(p===")"&&(d--,d===0)){f=u;let g=u+1;for(;g<s.length&&/\s/.test(s[g]);)g++;if(g<s.length&&s[g]==="]"){l=g;break}}}if(l!==-1){let u=t.substring(h+1,f),p=t.substring(a.index,l+1),g=I(u);Ln(g.path)||Ln(g.query)||Ln(g.url)||Ln(g.keyword)||Ln(g.command)||Ln(g.method)||Ln(g.title)||Ln(g.task)||Ln(g.id)||bc.test(u)||o.push({fullMatch:p,toolName:r.trim(),args:u.trim()}),i.lastIndex=l+1}}return o},hm=(e,n={})=>{if(!e)return null;if(Bo=n,zi=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}}}},Uo=async(e,n,t,o,s="Fast",i=.75,a="agent")=>hc(async()=>{let{aiProvider:r="Google",apiKey:h,mode:d}=e,c="",l=null,f=typeof t=="string"?[{role:"user",parts:[{text:t}]}]:t,u=new AbortController,p=u.signal,g=setInterval(()=>{Ot&&(u.abort(),clearInterval(g))},100);try{let y;r==="Ollama"?y=$a(h,n,f,o,s,d,fn(n),p,i,systemSettings?.ollamaEndpoint||"Cloud"):r==="OpenRouter"?y=Xi(h,n,f,o,s,d,fn(n),p,i):r==="DeepSeek"?y=Yi(h,n,f,o,s,d,fn(n),p,i):r==="Mistral"?y=Vi(h,n,f,o,s,d,fn(n),p,i):r==="NVIDIA"?y=Ji(h,n,f,o,s,d,fn(n),p,i):y=await Qi(h).models.generateContentStream({model:n,contents:f,config:{systemInstruction:o,temperature:i,thinkingConfig:(()=>{let x=(n||"").toLowerCase(),S=x.includes("gemma-4")||x.startsWith("gemma"),R=x.includes("gemini-3");if(S||R)return S?s.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:at.MINIMAL}:{includeThoughts:!0,thinkingLevel:at.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:x.includes("pro")?at.LOW:at.MINIMAL,Low:at.LOW,Medium:at.MEDIUM,Standard:at.MEDIUM,High:at.HIGH,xHigh:at.HIGH}[s]||at.MEDIUM};{let E={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[s]||2048;return E===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:E}}})()}},{signal:p});for await(let m of y){if(Ot)throw new Error("Subagent task was cancelled.");if(e?.taskId&&typeof Ye<"u"){let S=Ye.find(R=>R.id===e.taskId);if(S&&S.status==="cancelled")throw new Error("Subagent task was cancelled.")}let w="";if(m.candidates?.[0]?.content?.parts)for(let S of m.candidates[0].content.parts)S.text&&!S.thought&&(c+=S.text,w+=S.text);let x=w?w.trim().split(/\s+/).filter(Boolean).length:0;e&&typeof e.onTokenChunk=="function"&&e.onTokenChunk(w,x),m.usageMetadata&&(l=m.usageMetadata)}}finally{clearInterval(g)}if(l){let y=l.totalTokenCount||0,m=l.cachedContentTokenCount||0,w=(l.candidatesTokenCount||0)+(l.thoughtsTokenCount||0);await Gt("tokens",y,r,n),m>0&&await Gt("cachedTokens",m,r,n),w>0&&await Gt("candidateTokens",w,r,n),e&&typeof e.onUsage=="function"&&e.onUsage({totalTokenCount:y,cachedContentTokenCount:m,candidatesTokenCount:w})}return await It("agent",r),{text:c,usageMetadata:l}}),kc=async(e,n,t=null)=>{t=t||X(Xt,{});try{let{aiProvider:o="Google"}=n;if(Object.values(t).flat().length<=5)return;let i=Object.keys(t).filter(f=>f!==e&&Array.isArray(t[f])&&t[f].length>2);if(i.length===0)return;let a=`You are a silent background process for the FluxFlow CLI Agent.
528
+ `)}if(process.stdout.isTTY)try{let V=(await ls())[p]?.name||"",J=V&&!V.startsWith("flow-")&&!V.startsWith("Session ")?V:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${J}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${J}\x07`)}catch{process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")}},Rc=e=>{let n=e.replace(gc,"").replace(yc,""),t=Is?n:n.replace(Aa,s=>" ".repeat(s.length)).replace(va,s=>" ".repeat(s.length));ho.lastIndex=0;let o;for(;(o=ho.exec(t))!==null;){let s=o.index+o[0].length-1,i=0,a=null,r=!1,h=!1;for(let d=s;d<t.length;d++){let c=n[d];if(!a&&(c==='"'||c==="'"||c==="`")?(a=c,r=!1):a&&c===a&&!r&&(a=null),!a&&(c==="("?i++:c===")"&&i--,i===0)){let l=d+1;for(;l<t.length&&/\s/.test(t[l]);)l++;if(l<t.length&&t[l]==="]"){h=!0,ho.lastIndex=l+1;break}}c==="\\"?r=!r:r=!1}if(!h)return{inside:!0,toolName:o[1],startIndex:o.index,args:n.substring(o.index+o[0].length)}}return{inside:!1}},Oa=(e,n=!0)=>{let t=ho;t.lastIndex=0;let o="",s=0,i;for(;(i=t.exec(e))!==null;){let a=e.substring(s,i.index);o+=n?a.replace(Sa,""):a;let r=i.index+i[0].length-1,h=0,d=null,c=-1;for(let l=r;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(Sa,""):e.substring(s)),o},Ec=(e,n,t)=>{let o=ho;o.lastIndex=0;let s="",i=0,a;for(;(a=o.exec(e))!==null;){let r=e.substring(i,a.index);s+=r.replace(n,t);let h=a.index+a[0].length-1,d=0,c=null,l=-1;for(let 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(a.index,l+1),i=l+1,o.lastIndex=i;else{s+=e.substring(a.index),i=e.length;break}}return i<e.length&&(s+=e.substring(i).replace(n,t)),s},_a=e=>Oa(e,!0),$c=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",goal:"Goal",ask:"Ask"},t=s=>s.split("_").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join("");Ta.lastIndex=0;let o=e.replace(Ta,(s,i,a)=>{let r="";try{let c=JSON.parse(a.trim());c&&typeof c=="object"&&(r=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=wc;u.lastIndex=0;let f;for(;(f=u.exec(a))!==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?r=l.join(", "):r=a.trim()}let h=i.toLowerCase().replace(/_/g,"");return`[tool:functions.${n[h]||t(i)}(${r})]`});return Ra.lastIndex=0,Ea.lastIndex=0,o=o.replace(Ra,""),o=o.replace(Ea,""),o},Cc=/(?:path|query|url|keyword|command|method|title|task|id)\s*=\s*['"`]?\s*\.\.\.\s*['"`]?/i,_c=/^['"`]?\s*\.\.\.\s*['"`]?$/,Ln=e=>{if(e==null)return!1;let n=String(e).trim();return n==="..."||n==="\u2026"||_c.test(n)},Go=e=>{if(!e)return[];let n=$c(e);ka.lastIndex=0;let t=n.replace(ka,""),o=[],s=Is?t:t.replace(Aa,r=>" ".repeat(r.length)).replace(va,r=>" ".repeat(r.length)),i=uc;i.lastIndex=0;let a;for(;(a=i.exec(s))!==null;){let r=a[1],h=a.index+a[0].length-1,d=0,c=null,l=-1,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(a.index,l+1),g=O(f);Ln(g.path)||Ln(g.query)||Ln(g.url)||Ln(g.keyword)||Ln(g.command)||Ln(g.method)||Ln(g.title)||Ln(g.task)||Ln(g.id)||Cc.test(f)||o.push({fullMatch:p,toolName:r.trim(),args:f.trim()}),i.lastIndex=l+1}}return o},Tm=(e,n={})=>{if(!e)return null;if(Wo=n,Zi=new Ma({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}}}},jo=async(e,n,t,o,s="Fast",i=.75,a="agent")=>bc(async()=>{let{aiProvider:r="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(()=>{Ot&&(f.abort(),clearInterval(g))},100);try{let y;r==="Ollama"?y=Ia(h,n,u,o,s,d,fn(n),p,i,systemSettings?.ollamaEndpoint||"Cloud"):r==="OpenRouter"?y=sr(h,n,u,o,s,d,fn(n),p,i):r==="DeepSeek"?y=er(h,n,u,o,s,d,fn(n),p,i):r==="Mistral"?y=tr(h,n,u,o,s,d,fn(n),p,i):r==="NVIDIA"?y=nr(h,n,u,o,s,d,fn(n),p,i):y=await or(h).models.generateContentStream({model:n,contents:u,config:{systemInstruction:o,temperature:i,thinkingConfig:(()=>{let x=(n||"").toLowerCase(),S=x.includes("gemma-4")||x.startsWith("gemma"),R=x.includes("gemini-3");if(S||R)return S?s.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:at.MINIMAL}:{includeThoughts:!0,thinkingLevel:at.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:x.includes("pro")?at.LOW:at.MINIMAL,Low:at.LOW,Medium:at.MEDIUM,Standard:at.MEDIUM,High:at.HIGH,xHigh:at.HIGH}[s]||at.MEDIUM};{let E={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[s]||2048;return E===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:E}}})()}},{signal:p});for await(let m of y){if(Ot)throw new Error("Subagent task was cancelled.");if(e?.taskId&&typeof Ye<"u"){let S=Ye.find(R=>R.id===e.taskId);if(S&&S.status==="cancelled")throw new Error("Subagent task was cancelled.")}let w="";if(m.candidates?.[0]?.content?.parts)for(let S of m.candidates[0].content.parts)S.text&&!S.thought&&(c+=S.text,w+=S.text);let x=w?w.trim().split(/\s+/).filter(Boolean).length:0;e&&typeof e.onTokenChunk=="function"&&e.onTokenChunk(w,x),m.usageMetadata&&(l=m.usageMetadata)}}finally{clearInterval(g)}if(l){let y=l.totalTokenCount||0,m=l.cachedContentTokenCount||0,w=(l.candidatesTokenCount||0)+(l.thoughtsTokenCount||0);await Gt("tokens",y,r,n),m>0&&await Gt("cachedTokens",m,r,n),w>0&&await Gt("candidateTokens",w,r,n),e&&typeof e.onUsage=="function"&&e.onUsage({totalTokenCount:y,cachedContentTokenCount:m,candidatesTokenCount:w})}return await It("agent",r),{text:c,usageMetadata:l}}),Mc=async(e,n,t=null)=>{t=t||X(Xt,{});try{let{aiProvider:o="Google"}=n;if(Object.values(t).flat().length<=5)return;let i=Object.keys(t).filter(u=>u!==e&&Array.isArray(t[u])&&t[u].length>2);if(i.length===0)return;let a=`You are a silent background process for the FluxFlow CLI Agent.
529
529
  Your task is to summarize or merge temporary context memories from one or more past conversation sessions.
530
530
  For each Chat ID provided, you must output a tool call to save the consolidated summary.
531
531
 
@@ -540,8 +540,8 @@ Guidelines:
540
540
 
541
541
  Chats to process:
542
542
 
543
- `,r=X(vn,{});for(let f of i){let p=t[f].map(y=>`- ${y}`).join(`
544
- `),g=r[f];a+=`[Chat ID: ${f}]
543
+ `,r=X(vn,{});for(let u of i){let p=t[u].map(y=>`- ${y}`).join(`
544
+ `),g=r[u];a+=`[Chat ID: ${u}]
545
545
  `,g?(a+=`- Existing Summary: "${g}"
546
546
  `,a+=`
547
547
  -- New Memories to integrate:
@@ -550,34 +550,34 @@ ${p}
550
550
  `):a+=`-- Individual Memories:
551
551
  ${p}
552
552
 
553
- `}let h=0,d=5,c=!1,l=et("gemma_janitor_fallback_google");for(o==="OpenRouter"&&(l=et("janitor_open_router")),o==="DeepSeek"&&(l=et("deepseek_level_1")),o==="Mistral"&&(l=et("mistral_level_1")),o==="NVIDIA"&&(l=et("nvidia_janitor_fallback"));h<=d&&!c;){h++;try{let u=(await Uo(n,l,a,null,"Fast",.75,"background")).text||"",p=jo(u);if(p.length===0)throw new Error("No tool calls detected in synthesis response");for(let g of p){let y=g.toolName;["saveSummary","saveSumary","SaveSummary","SaveSumary"].includes(y)&&await lo(y,g.args,{chatId:e})}c=!0}catch(f){if(h>=d)throw new Error(`Failed after ${d} attempts. Last error: ${f.message}`)}}}catch(o){let s=o instanceof Error?(()=>{try{return JSON.parse(JSON.parse(o.message).error.message).error.message}catch{return String(o)}})():String(o),i=Q.join(cn,"janitor");ve.existsSync(i)||ve.mkdirSync(i,{recursive:!0}),ve.appendFileSync(Q.join(i,"error.log"),`[${new Date().toLocaleString()}] Past memory batch consolidation error: ${s}
554
- `)}},Tc=async(e,n,t=!1)=>{let{chatId:o,aiProvider:s="Google"}=e,i=Q.join(yo,"chat-summaries.json"),a=u=>u.filter(p=>(p.role==="user"||p.role==="agent"||p.role==="system")&&p.role!=="think"&&!p.isVisualFeedback&&!p.isMeta&&!p.isTerminalRecord&&!(p.text&&p.text.includes("[TERMINAL_RECORD]"))&&!String(p.id).startsWith("welcome")).map(p=>{let g=p.fullText||p.text||"",y=p.role==="system"||g.startsWith("[TOOL RESULT]:")||p.text&&p.text.startsWith("[TOOL RESULT]:"),m=g;return y&&(g.includes("[TOOL RESULT]:")||p.text&&p.text.includes("[TOOL RESULT]:"))?m="[TOOL RESULT]: ...truncated for summary":m=m.replace(/(\[(?:tool|agent):[a-zA-Z0-9_\.]+)\([\s\S]*?\)(\])/g,"$1(...)$2"),`[${y?"TOOL":p.role==="agent"?"AGENT":"USER"}]: ${m}`}).join(`
553
+ `}let h=0,d=5,c=!1,l=et("gemma_janitor_fallback_google");for(o==="OpenRouter"&&(l=et("janitor_open_router")),o==="DeepSeek"&&(l=et("deepseek_level_1")),o==="Mistral"&&(l=et("mistral_level_1")),o==="NVIDIA"&&(l=et("nvidia_janitor_fallback"));h<=d&&!c;){h++;try{let f=(await jo(n,l,a,null,"Fast",.75,"background")).text||"",p=Go(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 fo(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=Q.join(cn,"janitor");Ie.existsSync(i)||Ie.mkdirSync(i,{recursive:!0}),Ie.appendFileSync(Q.join(i,"error.log"),`[${new Date().toLocaleString()}] Past memory batch consolidation error: ${s}
554
+ `)}},Ac=async(e,n,t=!1)=>{let{chatId:o,aiProvider:s="Google"}=e,i=Q.join(xo,"chat-summaries.json"),a=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(`
555
555
 
556
- `),r=async(u,p)=>{let g="You are an expert context summarizer. Summarize the provided chat history (which may include previous summaries, user instructions, agent outputs, and tool results) into a detailed, coherent, and highly technical summary of 1000 to 1500 words. Focus on preserving the architectural decisions made, current system state, task progress, and critical code details, chat messages, file changes. Under no circumstances exceed MAX 2000 words.",y=p?`Here is the previous summary:
556
+ `),r=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:
557
557
  ${p}
558
558
 
559
559
  Here is the new conversation history:
560
- ${u}
560
+ ${f}
561
561
 
562
562
  Provide a new consolidated summary of the entire session.`:`Here is the conversation history:
563
- ${u}
563
+ ${f}
564
564
 
565
- Provide a consolidated summary of the entire session.`,m=et("gemma_janitor_fallback_google");s==="OpenRouter"&&(m=et("janitor_open_router")),s==="DeepSeek"&&(m=et("deepseek_level_1")),s==="Mistral"&&(m=et("mistral_level_1")),s==="NVIDIA"&&(m=et("nvidia_chat_summarizer_fallback"));let w=0,x=!1,S=null;for(;w<=3&&!x;){w++;try{S=await Uo(e,m,y,g,"Fast"),x=!0}catch{if(w>3){if(s==="Google")try{let E=et("general_fallback");return(await Uo(e,E,y,g,"Fast")).text||""}catch{return""}return""}}}return S&&S.text||""},h=a(n),d=X(i,{}),c=d[o]||{summary:"",historyLength:0};typeof c=="string"&&(c={summary:c,historyLength:0});let l=c.summary||"",f=await r(h,l);if(f){c.summary=f;let u=pc(n);return t?c.historyLength=(c.historyLength||0)+u:c.historyLength=u,d[o]=c,he(i,d),f}return null},pm=e=>{try{let n=Q.join(yo,"chat-summaries.json");if(ve.existsSync(n)){let t=X(n,{});t[e]&&(delete t[e],he(n,t))}}catch{}},mm=async function*(e,n,t,o,s){let{profile:i,thinkingLevel:a,mode:r,janitorModel:h,chatId:d,isPlayground:c,systemSettings:l,sessionStats:f,aiProvider:u="Google",apiTier:p,wildcardTooling:g}=t,y=fn(e);if(!zi&&u==="Google")throw new Error("AI not initialized");let m=process.env.NVIDIA_BASE_URL||t?.aiProvider==="Ollama"?!1:l?.memory!==!1,w=n[n.length-1].text,x=Q.join(yo,"chat-summaries.json"),S=!1,R=n.filter(C=>C.role==="user").length===1,E=w.includes("[TITLE-UPDATE]"),b=R||E,T=w.replace(/\[TITLE-UPDATE\]/g,"").trim();T=T.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),yield{type:"status",content:"[start]"},yield{type:"status",content:"Gathering Context"},await ft.startTransaction(d,T),l?.advanceRollback&&await Kn.takeInitialSnapshot(d),Ot=!1;let $=null;try{let C=new AbortController;$=setInterval(()=>{Ot&&(C.abort(),$&&(clearInterval($),$=null))},400);let k=[...n.slice(0,-1)];{let Ae=X(x,{})[d]||{summary:"",historyLength:0};if(Ae.summary&&Ae.historyLength>0){let Qt=0,Oe=[];for(let Qe=0;Qe<k.length;Qe++){let We=k[Qe];(We.role==="user"||We.role==="agent"||We.role==="system")&&!String(We.id).startsWith("welcome")&&!We.isMeta&&Qt++,Qt>Ae.historyLength&&Oe.push(We)}k=Oe}}k=k.map(H=>{if(H.role==="user"&&H.text){let Ae=H.text.match(/\[USER\]([\s\S]*?)\[\/USER\]/);if(Ae)return{...H,text:Ae[1].trim()}}return{...H}});let O=process.env.HIGH_CONTEXT,v=255e3,L=26e4;if(O&&O!=="false"){let H=parseInt(O,10);!isNaN(H)&&H>=256e3&&H<=1e6&&(L=H,v=Math.round(H*.85))}if((u==="NVIDIA"&&(e?.includes("gpt")||e?.includes("qwen")||e?.includes("medium")||e.includes("muse"))||u==="Mistral")&&(v=122e3,L=126e3),u!=="Ollama"&&(f?.tokens||0)>v&&(yield{type:"status_history",content:"Context Limit Reached. Condensing session history..."},await Tc(t,k,!0)&&(k=[],S=!0)),R&&m){let H=X(Xt,{});Object.values(H).flat().length>5&&(yield{type:"status",content:"Condensing past chat memories"},await kc(d,t,H))}let N=X(Xt,{}),j=X(vn,{}),V=Object.entries(N).filter(([H])=>H!==d).flatMap(([H,Ae])=>Ae),Ie=[...Object.entries(j).filter(([H])=>H!==d).slice(-20).map(([H,Ae])=>`[Chat Summary]: ${Ae}`),...V].map(H=>`- ${H}`).join(`
565
+ Provide a consolidated summary of the entire session.`,m=et("gemma_janitor_fallback_google");s==="OpenRouter"&&(m=et("janitor_open_router")),s==="DeepSeek"&&(m=et("deepseek_level_1")),s==="Mistral"&&(m=et("mistral_level_1")),s==="NVIDIA"&&(m=et("nvidia_chat_summarizer_fallback"));let w=0,x=!1,S=null;for(;w<=3&&!x;){w++;try{S=await jo(e,m,y,g,"Fast"),x=!0}catch{if(w>3){if(s==="Google")try{let E=et("general_fallback");return(await jo(e,E,y,g,"Fast")).text||""}catch{return""}return""}}}return S&&S.text||""},h=a(n),d=X(i,{}),c=d[o]||{summary:"",historyLength:0};typeof c=="string"&&(c={summary:c,historyLength:0});let l=c.summary||"",u=await r(h,l);if(u){c.summary=u;let f=Sc(n);return t?c.historyLength=(c.historyLength||0)+f:c.historyLength=f,d[o]=c,he(i,d),u}return null},Rm=e=>{try{let n=Q.join(xo,"chat-summaries.json");if(Ie.existsSync(n)){let t=X(n,{});t[e]&&(delete t[e],he(n,t))}}catch{}},Em=async function*(e,n,t,o,s){let{profile:i,thinkingLevel:a,mode:r,janitorModel:h,chatId:d,isPlayground:c,systemSettings:l,sessionStats:u,aiProvider:f="Google",apiTier:p,wildcardTooling:g}=t,y=fn(e);if(!Zi&&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=Q.join(xo,"chat-summaries.json"),S=!1,R=n.filter(C=>C.role==="user").length===1,E=w.includes("[TITLE-UPDATE]"),k=R||E,T=w.replace(/\[TITLE-UPDATE\]/g,"").trim();T=T.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),yield{type:"status",content:"[start]"},yield{type:"status",content:"Gathering Context"},await ft.startTransaction(d,T),l?.advanceRollback&&await zn.takeInitialSnapshot(d),Ot=!1;let $=null;try{let C=new AbortController;$=setInterval(()=>{Ot&&(C.abort(),$&&(clearInterval($),$=null))},400);let b=[...n.slice(0,-1)];{let ve=X(x,{})[d]||{summary:"",historyLength:0};if(ve.summary&&ve.historyLength>0){let Qt=0,Oe=[];for(let Qe=0;Qe<b.length;Qe++){let We=b[Qe];(We.role==="user"||We.role==="agent"||We.role==="system")&&!String(We.id).startsWith("welcome")&&!We.isMeta&&Qt++,Qt>ve.historyLength&&Oe.push(We)}b=Oe}}b=b.map(H=>{if(H.role==="user"&&H.text){let ve=H.text.match(/\[USER\]([\s\S]*?)\[\/USER\]/);if(ve)return{...H,text:ve[1].trim()}}return{...H}});let v=process.env.HIGH_CONTEXT,I=255e3,D=26e4;if(v&&v!=="false"){let H=parseInt(v,10);!isNaN(H)&&H>=256e3&&H<=1e6&&(D=H,I=Math.round(H*.85))}if((f==="NVIDIA"&&(e?.includes("gpt")||e?.includes("qwen")||e?.includes("medium")||e.includes("muse"))||f==="Mistral")&&(I=122e3,D=126e3),f!=="Ollama"&&(u?.tokens||0)>I&&(yield{type:"status_history",content:"Context Limit Reached. Condensing session history..."},await Ac(t,b,!0)&&(b=[],S=!0)),R&&m){let H=X(Xt,{});Object.values(H).flat().length>5&&(yield{type:"status",content:"Condensing past chat memories"},await Mc(d,t,H))}let j=X(Xt,{}),U=X(vn,{}),Y=Object.entries(j).filter(([H])=>H!==d).flatMap(([H,ve])=>ve),_e=[...Object.entries(U).filter(([H])=>H!==d).slice(-20).map(([H,ve])=>`[Chat Summary]: ${ve}`),...Y].map(H=>`- ${H}`).join(`
566
566
  `),W=X(Dt,[]).map(H=>`- ${H.memory}`).join(`
567
- `),re=(f?.tokens||0)>=1e4,Re=gr(Ie,W,m,re),M=new Date,F=M.getFullYear(),Y=M.toLocaleString("en-US",{month:"short"}).toUpperCase(),J=String(M.getDate()).padStart(2,"0"),Ne=M.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}),De=`${F}-${Y}-${J}, ${Ne}`,Ue=[".git","node_modules",".gemini","dist","build",".next","out",".cache","bin","obj","vendor","venv",".idea",".gradle",".terraform","target","coverage",".vscode",".svn",".hg",".fslckout",".github",".gitlab",".circleci",".gitea",".gitee",".lerna",".changeset",".nx",".npm",".yarn",".pnpm-store",".pnpm",".expo",".nuxt",".svelte-kit",".docusaurus",".turbo",".vercel","bower_components",".netlify",".vuepress",".quasar",".output",".angular","jspm_packages",".parcel-cache",".rollup.cache",".rspack",".vitepress","__pycache__",".pytest_cache",".mypy_cache",".tox",".poetry","env","vhdl",".ipynb_checkpoints",".jupyter",".conda",".pdm-build",".bundle",".yardoc",".metadata","App_Data","ClientBin",".cargo",".rustc_info",".go","Godeps","_vendor",".rake_tasks","CMakefiles",".wakatime",".dart_tool",".fvm",".cocoapods","Pods",".pub-cache",".symlinks","DerivedData",".xcworkspace",".serverless",".aws",".gcloud",".azure",".kube",".vagrant",".docker","postgres-data","redis-data","mongo-data",".Spotlight-V100",".Trashes","$RECYCLE.BIN","System Volume Information",".DocumentRevisions-V100",".fseventsd","AppData","Application Data","Local","LocalLow","Roaming","$WinREAgent","$WINDOWS.~BT","$WINDOWS.~WS","scw","System32","SysWOW64",".AppleDouble",".AppleDB",".AppleDesktop","_CodeSignature",".cmio",".LSOverride",".localized",".TemporaryItems",".Trash",".Trash-0",".Trash-1000",".gvfs",".local",".config",".dbus",".fontconfig",".snap",".var",".lost+found","lost+found",".thumb",".thumbnails","EFI","boot","grub","logs","log",".nyc_output",".sonar",".ruff_cache",".VSCodeCounter"],st=H=>{try{return ve.readdirSync(H,{withFileTypes:!0})}catch{return[]}},Ge=(H,Ae={value:0},Qt=1)=>{if(Ae.value>6200||Qt>7)return Ae.value;let Oe=st(H);for(let Qe of Oe){if(Ae.value>6200)break;Ue.includes(Qe.name)||Qe.name.startsWith(".")||Qe.isDirectory()&&(Ae.value++,Ge(Q.join(H,Qe.name),Ae,Qt+1))}return Ae.value},ut=(H,Ae)=>l?.indentationTree!==!1?Hi(H,Ae,1,st,Ue):qi(H,Ae,"",1,st,Ue),Nt=Ge(process.cwd()),ht=12;Nt>3072?ht=1:Nt>2304?ht=2:Nt>1536?ht=3:Nt>768?ht=4:Nt>384?ht=6:Nt>192?ht=7:Nt>96?ht=8:Nt>48?ht=9:Nt>24&&(ht=10);let pt=X(Jo,{}),kt=pt[d],Tt=kt?kt!==process.cwd():!1;pt[d]=process.cwd(),he(Jo,pt);let Xe=X(x,{}),ye=Xe[d]||{summary:"",historyLength:0};typeof ye=="string"&&(ye={summary:ye,historyLength:0});let Kt=n.filter(H=>(H.role==="user"||H.role==="agent"||H.role==="system")&&!String(H.id).startsWith("welcome")&&!H.isMeta).length;ye.historyLength&&Kt<ye.historyLength&&(ye.summary="",ye.historyLength=0,Xe[d]=ye,he(x,Xe));let Jn=typeof ye=="object"?ye.summary||"":ye||"",Xn=k.length>0;Xn&&Jn&&k[0]&&(k[0].role==="user"||k[0].role==="system")&&(k[0].text.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")||(k[0].text=`[SYSTEM METADATA]
567
+ `),re=(u?.tokens||0)>=1e4,Re=kr(_e,W,m,re),M=new Date,F=M.getFullYear(),V=M.toLocaleString("en-US",{month:"short"}).toUpperCase(),J=String(M.getDate()).padStart(2,"0"),Ne=M.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}),De=`${F}-${V}-${J}, ${Ne}`,Ue=[".git","node_modules",".gemini","dist","build",".next","out",".cache","bin","obj","vendor","venv",".idea",".gradle",".terraform","target","coverage",".vscode",".svn",".hg",".fslckout",".github",".gitlab",".circleci",".gitea",".gitee",".lerna",".changeset",".nx",".npm",".yarn",".pnpm-store",".pnpm",".expo",".nuxt",".svelte-kit",".docusaurus",".turbo",".vercel","bower_components",".netlify",".vuepress",".quasar",".output",".angular","jspm_packages",".parcel-cache",".rollup.cache",".rspack",".vitepress","__pycache__",".pytest_cache",".mypy_cache",".tox",".poetry","env","vhdl",".ipynb_checkpoints",".jupyter",".conda",".pdm-build",".bundle",".yardoc",".metadata","App_Data","ClientBin",".cargo",".rustc_info",".go","Godeps","_vendor",".rake_tasks","CMakefiles",".wakatime",".dart_tool",".fvm",".cocoapods","Pods",".pub-cache",".symlinks","DerivedData",".xcworkspace",".serverless",".aws",".gcloud",".azure",".kube",".vagrant",".docker","postgres-data","redis-data","mongo-data",".Spotlight-V100",".Trashes","$RECYCLE.BIN","System Volume Information",".DocumentRevisions-V100",".fseventsd","AppData","Application Data","Local","LocalLow","Roaming","$WinREAgent","$WINDOWS.~BT","$WINDOWS.~WS","scw","System32","SysWOW64",".AppleDouble",".AppleDB",".AppleDesktop","_CodeSignature",".cmio",".LSOverride",".localized",".TemporaryItems",".Trash",".Trash-0",".Trash-1000",".gvfs",".local",".config",".dbus",".fontconfig",".snap",".var",".lost+found","lost+found",".thumb",".thumbnails","EFI","boot","grub","logs","log",".nyc_output",".sonar",".ruff_cache",".VSCodeCounter"],st=H=>{try{return Ie.readdirSync(H,{withFileTypes:!0})}catch{return[]}},Ge=(H,ve={value:0},Qt=1)=>{if(ve.value>6200||Qt>7)return ve.value;let Oe=st(H);for(let Qe of Oe){if(ve.value>6200)break;Ue.includes(Qe.name)||Qe.name.startsWith(".")||Qe.isDirectory()&&(ve.value++,Ge(Q.join(H,Qe.name),ve,Qt+1))}return ve.value},ut=(H,ve)=>l?.indentationTree!==!1?Vi(H,ve,1,st,Ue):Xi(H,ve,"",1,st,Ue),Nt=Ge(process.cwd()),ht=12;Nt>3072?ht=1:Nt>2304?ht=2:Nt>1536?ht=3:Nt>768?ht=4:Nt>384?ht=6:Nt>192?ht=7:Nt>96?ht=8:Nt>48?ht=9:Nt>24&&(ht=10);let pt=X(Qo,{}),kt=pt[d],Tt=kt?kt!==process.cwd():!1;pt[d]=process.cwd(),he(Qo,pt);let Xe=X(x,{}),ye=Xe[d]||{summary:"",historyLength:0};typeof ye=="string"&&(ye={summary:ye,historyLength:0});let zt=n.filter(H=>(H.role==="user"||H.role==="agent"||H.role==="system")&&!String(H.id).startsWith("welcome")&&!H.isMeta).length;ye.historyLength&&zt<ye.historyLength&&(ye.summary="",ye.historyLength=0,Xe[d]=ye,he(x,Xe));let Jn=typeof ye=="object"?ye.summary||"":ye||"",Xn=b.length>0;Xn&&Jn&&b[0]&&(b[0].role==="user"||b[0].role==="system")&&(b[0].text.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")||(b[0].text=`[SYSTEM METADATA]
568
568
  **CONTEXT SUMMARY OF PREVIOUS TURNS (PRIORITY: DYNAMIC)**
569
569
  ${Jn}
570
570
 
571
- [USER] ${k[0].text}`,yield{type:"summary_injected",content:{id:k[0].id,text:k[0].text}}));let Zi=Jn&&!Xn?`
571
+ [USER] ${b[0].text}`,yield{type:"summary_injected",content:{id:b[0].id,text:b[0].text}}));let ir=Jn&&!Xn?`
572
572
  [SYSTEM METADATA]
573
573
  **CONTEXT SUMMARY OF PREVIOUS TURNS**
574
574
  ${Jn}
575
- `:"",er=!!l?.dynamicDirAwareness,_a=`${d}|${u}|${a}|${e}|${i}|${er}`,tr=!er&&ws.key===_a&&ws.value?"":`
575
+ `:"",rr=!!l?.dynamicDirAwareness,La=`${d}|${f}|${a}|${e}|${i}|${rr}`,ar=!rr&&ws.key===La&&ws.value?"":`
576
576
  **Directory Structure**
577
577
  CWD: `+process.cwd()+`${c?" [PLAYGROUND MODE]":""}
578
- `+ut(process.cwd(),ht),xt=await gs(),Dn="";if(No()&&xt.file_focused!=="none"){Dn=`
578
+ `+ut(process.cwd(),ht),xt=await gs(),Dn="";if(Uo()&&xt.file_focused!=="none"){Dn=`
579
579
  [Additional IDE Context]
580
- `;let H=Q.relative(process.cwd(),xt.file_focused),Ae=(xt.opened_editors||[]).map(Oe=>{let Qe=Q.relative(process.cwd(),Oe);return Qe.startsWith("..")?`[External] ${Q.basename(Oe)}`:Qe});if(Dn+=`Focused File: ${H}
580
+ `;let H=Q.relative(process.cwd(),xt.file_focused),ve=(xt.opened_editors||[]).map(Oe=>{let Qe=Q.relative(process.cwd(),Oe);return Qe.startsWith("..")?`[External] ${Q.basename(Oe)}`:Qe});if(Dn+=`Focused File: ${H}
581
581
  Cursor Line: ${xt.cursor_line}
582
582
  `,xt.selected){let Oe=xt.selected,Qe=Oe.split(`
583
583
  `);Qe.length>256&&(Oe=Qe.slice(0,240).join(`
@@ -598,69 +598,69 @@ ${q.edits.join(`
598
598
  `)}`;Z.length>4*768?q.stringRepresentation="... "+Z.slice(-(4*768-4)):q.stringRepresentation=Z}Zt=Je.map(q=>q.stringRepresentation).join(`
599
599
  `)}Zt.length>4*2048&&(Zt="... "+Zt.slice(-(4*2048-4))),Dn+=`Recent Manual Edits:
600
600
  ${Zt}
601
- `}Ae.length>0&&(Dn+=`All Opened Editors: ${Ae.join(", ")}`),xt.diagnostics&&(Dn+=`
601
+ `}ve.length>0&&(Dn+=`All Opened Editors: ${ve.join(", ")}`),xt.diagnostics&&(Dn+=`
602
602
  **Active File Errors**:
603
603
  ${xt.diagnostics}
604
604
  `),(T.toLowerCase().includes("lint")||T.toLowerCase().includes("warning"))&&xt.warnings&&(Dn+=`
605
605
  **Lint Warnings**:
606
606
  ${xt.warnings}
607
- `)}let nr=T.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),sr=/(?:\\)?@\[([^\]]+)\]/g,Ho,Go=[];for(sr.lastIndex=0;(Ho=sr.exec(nr))!==null;){let H=Ho[0].startsWith("\\");Go.push({tag:Ho[1],isEscaped:H})}let qo=[],uo=null;for(let H=0;H<Go.length;H++){let{tag:Ae,isEscaped:Qt}=Go[H];if(!Qt)try{let Oe=Ae.trim().replace(/^["']|["']$/g,""),Qe=/[:#]L?(\d+)(?:-L?(\d+))?$/i,We=Oe.match(Qe),Ve=Oe,ce=null,Bt=null;We&&(ce=parseInt(We[1],10),Bt=We[2]?parseInt(We[2],10):ce,Ve=Oe.slice(0,We.index));let Je=Q.resolve(process.cwd(),Ve);if(ve.existsSync(Je)&&ve.statSync(Je).isFile()){let q=Ve.toLowerCase(),Z=q.endsWith(".pdf"),je=q.endsWith(".docx")||q.endsWith(".doc")||q.endsWith(".ppt")||q.endsWith(".pptx")||q.endsWith(".xls")||q.endsWith(".xlsx"),rn=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(q),Ut=rn||Z||je,wn=u==="Google"||fn(e);if(Ut&&!wn){let Be=`\u2718 Unsupported Modality: ${Q.basename(Ve)}`,_e=115;process.stdout.isTTY&&(_e=process.stdout.columns-5||120);let mt=[Be],Fn=Math.max(...mt.map($n=>$n.length)),Nn=Math.min(Fn+4,_e),es=mt.map($n=>`${$n.padEnd(Nn-2).substring(0,Nn-2)}`).join(`
607
+ `)}let lr=T.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),cr=/(?:\\)?@\[([^\]]+)\]/g,qo,zo=[];for(cr.lastIndex=0;(qo=cr.exec(lr))!==null;){let H=qo[0].startsWith("\\");zo.push({tag:qo[1],isEscaped:H})}let Ko=[],po=null;for(let H=0;H<zo.length;H++){let{tag:ve,isEscaped:Qt}=zo[H];if(!Qt)try{let Oe=ve.trim().replace(/^["']|["']$/g,""),Qe=/[:#]L?(\d+)(?:-L?(\d+))?$/i,We=Oe.match(Qe),Ve=Oe,ce=null,Bt=null;We&&(ce=parseInt(We[1],10),Bt=We[2]?parseInt(We[2],10):ce,Ve=Oe.slice(0,We.index));let Je=Q.resolve(process.cwd(),Ve);if(Ie.existsSync(Je)&&Ie.statSync(Je).isFile()){let q=Ve.toLowerCase(),Z=q.endsWith(".pdf"),je=q.endsWith(".docx")||q.endsWith(".doc")||q.endsWith(".ppt")||q.endsWith(".pptx")||q.endsWith(".xls")||q.endsWith(".xlsx"),rn=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(q),Ut=rn||Z||je,wn=f==="Google"||fn(e);if(Ut&&!wn){let Be=`\u2718 Unsupported Modality: ${Q.basename(Ve)}`,Me=115;process.stdout.isTTY&&(Me=process.stdout.columns-5||120);let mt=[Be],Fn=Math.max(...mt.map($n=>$n.length)),Nn=Math.min(Fn+4,Me),es=mt.map($n=>`${$n.padEnd(Nn-2).substring(0,Nn-2)}`).join(`
608
608
  `);yield{type:"visual_feedback",content:gn(`${es}
609
- `)};continue}if(ce===null&&!Ut){let Be=0;try{Be=ve.readFileSync(Je,"utf8").split(/\r\n|\r|\n/).length}catch{}if(Be>300){let _e=`\u21B7 Skipped (Too Large): ${Q.basename(Ve)}`,mt=115;process.stdout.isTTY&&(mt=process.stdout.columns-5||120);let Fn=Math.min(_e.length+4,mt),Nn=_e.padEnd(Fn-2).substring(0,Fn-2);yield{type:"visual_feedback",content:gn(`${Nn}
610
- `)};continue}}let En=ce!==null?ce:1,Qn=Bt!==null?Bt:ce!==null?ce:En+299;Qn-En>300&&(Qn=En+300);let po=`path=${JSON.stringify(Ve)}, startLine=${En}, endLine=${Qn}`,tt=await Qs(po,{isMultiModal:wn}),qe=!1,Wt="",Zn=null;if(typeof tt=="string"?tt.trim().startsWith("ERROR")?qe=!0:Wt=tt:tt&&typeof tt=="object"&&tt.binaryPart?(Zn=tt.binaryPart,Wt=tt.text||""):qe=!0,!qe){let Be="";if(rn?(Be=`\u2714 Processed: ${Q.basename(Ve)}`,uo=Zn):Z||je?(Be=`\u2714 Auto-Analysed: ${Q.basename(Ve)}`,uo=Zn):(Be=`\u2714 Auto-Read: ${Q.basename(Ve)}`,qo.push(Wt)),Be){let _e=115;process.stdout.isTTY&&(_e=process.stdout.columns-5||120);let mt=[Be],Fn=Math.max(...mt.map($n=>$n.length)),Nn=Math.min(Fn+4,_e),es=mt.map($n=>`${$n.padEnd(Nn-2).substring(0,Nn-2)}`).join(`
609
+ `)};continue}if(ce===null&&!Ut){let Be=0;try{Be=Ie.readFileSync(Je,"utf8").split(/\r\n|\r|\n/).length}catch{}if(Be>300){let Me=`\u21B7 Skipped (Too Large): ${Q.basename(Ve)}`,mt=115;process.stdout.isTTY&&(mt=process.stdout.columns-5||120);let Fn=Math.min(Me.length+4,mt),Nn=Me.padEnd(Fn-2).substring(0,Fn-2);yield{type:"visual_feedback",content:gn(`${Nn}
610
+ `)};continue}}let En=ce!==null?ce:1,Qn=Bt!==null?Bt:ce!==null?ce:En+299;Qn-En>300&&(Qn=En+300);let go=`path=${JSON.stringify(Ve)}, startLine=${En}, endLine=${Qn}`,tt=await Qs(go,{isMultiModal:wn}),qe=!1,Wt="",Zn=null;if(typeof tt=="string"?tt.trim().startsWith("ERROR")?qe=!0:Wt=tt:tt&&typeof tt=="object"&&tt.binaryPart?(Zn=tt.binaryPart,Wt=tt.text||""):qe=!0,!qe){let Be="";if(rn?(Be=`\u2714 Processed: ${Q.basename(Ve)}`,po=Zn):Z||je?(Be=`\u2714 Auto-Analysed: ${Q.basename(Ve)}`,po=Zn):(Be=`\u2714 Auto-Read: ${Q.basename(Ve)}`,Ko.push(Wt)),Be){let Me=115;process.stdout.isTTY&&(Me=process.stdout.columns-5||120);let mt=[Be],Fn=Math.max(...mt.map($n=>$n.length)),Nn=Math.min(Fn+4,Me),es=mt.map($n=>`${$n.padEnd(Nn-2).substring(0,Nn-2)}`).join(`
611
611
  `);yield{type:"visual_feedback",content:gn(`${es}
612
- `)}}}}}catch{}}let or="";qo.length>0&&(or=`[Tagged File Contents] Auto Read User Tagged files by System, No need to re-read
613
- `+qo.join(`
612
+ `)}}}}}catch{}}let dr="";Ko.length>0&&(dr=`[Tagged File Contents] Auto Read User Tagged files by System, No need to re-read
613
+ `+Ko.join(`
614
614
 
615
615
  `)+`
616
616
  [Tagged File Contents]
617
- `);let Ma=nr.replace(/\\(@\[[^\]]+\])/g,"$1"),Aa=g?`You cannot execute tools
617
+ `);let Pa=lr.replace(/\\(@\[[^\]]+\])/g,"$1"),Da=g?`You cannot execute tools
618
618
  Instead, output in chat the exact string you WOULD have produced & wait for system response
619
- `:"",ir=`[System Metadata]
620
- Time: ${De}${l?.dynamicDirAwareness?tr:""}${Tt?`
619
+ `:"",fr=`[System Metadata]
620
+ Time: ${De}${l?.dynamicDirAwareness?ar:""}${Tt?`
621
621
  WARNING: CWD Changed from previous: "${kt}" to current: "${process.cwd()}", write change in chat to avoid future path mismatches
622
622
  `:""}${Re}${Dn}
623
623
  [/Metadata]
624
- ${Zi}${a!=="Fast"&&(u==="Mistral"&&!qs(e)||a!=="xHigh"&&u==="Google")?`${u==="Mistral"&&!qs(e)||e.toLowerCase().startsWith("gemma")?`[system] strictly follow thinking policy as high priority. do not start a response without <think>...</think> [/system]
624
+ ${ir}${a!=="Fast"&&(f==="Mistral"&&!qs(e)||a!=="xHigh"&&f==="Google")?`${f==="Mistral"&&!qs(e)||e.toLowerCase().startsWith("gemma")?`[system] strictly follow thinking policy as high priority. do not start a response without <think>...</think> [/system]
625
625
  `:""}`:""}[system] exact structured string '[tool:functions.toolname(arg="value")]' in chat response [/system]
626
- ${or}${Aa}[user prompt] ${Ma.trim()} [/user prompt]`.trim(),rr={role:"user",text:ir};uo&&(rr.binaryPart=uo),k.forEach(H=>{H.text&&H.role==="agent"&&(H.text=H.text.replace(/(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])/gi,""),H.text=H.text.replace(/(?:<(think|thought)>|\[(think|thought)\])[^\[\n]*/gi,"").trim())}),k.push(rr),Zi&&n[n.length-1]?.id&&(yield{type:"summary_injected",content:{id:n[n.length-1].id,text:ir}});let Rn=null,Bs=r==="Flux"?100:10;Bs=r.toLowerCase().includes("cu")?250:Bs;let yn=16;yield{type:"status",content:"Connecting"},Ot=!1;let ar=[],ho=!1;for(let H=0;H<=Bs;H++){let Ae=await ri("agent",t);if(!Ae.allowed)throw new Error(Ae.reason||`Budget Exhausted for Provider (${u||"Agent"})`);let Qt=[];if(ho=!1,r==="ICU"||r==="FluxCU")try{yield{type:"status",content:"Capturing Screen"},await new Promise(Ee=>setTimeout(Ee,3e3));let ue=await cr();if(ue&&ue.base64){let Ee="[system] Fresh Gridded Screen Feedback Captured. Use numeric coordinates. Old screenshots will be removed when new screenshot is captured, summarize in text if context is needed later [/system]",ne={inlineData:{mimeType:ue.mimeType,data:ue.base64}};for(let nt of k)Array.isArray(nt.parts)&&(nt.parts=nt.parts.filter(_t=>!_t.inlineData));if(k.length>0&&k[k.length-1].role==="user"){let nt=k[k.length-1];typeof nt.text=="string"&&(nt.text+=`
626
+ ${dr}${Da}[user prompt] ${Pa.trim()} [/user prompt]`.trim(),ur={role:"user",text:fr};po&&(ur.binaryPart=po),b.forEach(H=>{H.text&&H.role==="agent"&&(H.text=H.text.replace(/(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])/gi,""),H.text=H.text.replace(/(?:<(think|thought)>|\[(think|thought)\])[^\[\n]*/gi,"").trim())}),b.push(ur),ir&&n[n.length-1]?.id&&(yield{type:"summary_injected",content:{id:n[n.length-1].id,text:fr}});let Rn=null,Bs=r==="Flux"?100:10;Bs=r.toLowerCase().includes("cu")?250:Bs;let yn=16;yield{type:"status",content:"Connecting"},Ot=!1;let hr=[],mo=!1;for(let H=0;H<=Bs;H++){let ve=await li("agent",t);if(!ve.allowed)throw new Error(ve.reason||`Budget Exhausted for Provider (${f||"Agent"})`);let Qt=[];if(mo=!1,r==="ICU"||r==="FluxCU")try{yield{type:"status",content:"Capturing Screen"},await new Promise(Ee=>setTimeout(Ee,1e3));let ue=await mr();if(ue&&ue.base64){let Ee="[system] Fresh Gridded Screen Feedback Captured. Use numeric coordinates. Old screenshots will be removed when new screenshot is captured, summarize in text if context is needed later [/system]",ne={inlineData:{mimeType:ue.mimeType,data:ue.base64}};for(let nt of b)Array.isArray(nt.parts)&&(nt.parts=nt.parts.filter(_t=>!_t.inlineData));if(b.length>0&&b[b.length-1].role==="user"){let nt=b[b.length-1];typeof nt.text=="string"&&(nt.text+=`
627
627
 
628
- ${Ee}`,Array.isArray(nt.parts)||(nt.parts=[{text:nt.text}]),nt.parts.push(ne))}else k.push({role:"user",text:Ee,parts:[{text:Ee},ne]})}}catch(ue){console.error("Vision screenshot capture error:",ue)}if(l?.compression===0&&(f?.tokens||0)>L&&(k=Sr(k,6)),H>0?yield{type:"status",content:"Working"}:yield{type:"status",content:"Connecting"},Ot){try{let{clearPendingNudges:ue}=await import("./subagent_state-LZCOZSUJ.js");ue()}catch{}yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
628
+ ${Ee}`,Array.isArray(nt.parts)||(nt.parts=[{text:nt.text}]),nt.parts.push(ne))}else b.push({role:"user",text:Ee,parts:[{text:Ee},ne]})}}catch(ue){console.error("Vision screenshot capture error:",ue)}if(l?.compression===0&&(u?.tokens||0)>D&&(b=Cr(b,6)),H>0?yield{type:"status",content:"Working"}:yield{type:"status",content:"Connecting"},Ot){try{let{clearPendingNudges:ue}=await import("./subagent_state-LZCOZSUJ.js");ue()}catch{}yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
629
629
 
630
630
  \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}try{let{consumePendingNudges:ue}=await import("./subagent_state-LZCOZSUJ.js"),Ee=ue();if(Ee&&Ee.length>0){let ne=Ee.join(`
631
631
 
632
- `);k.length>0&&k[k.length-1].role==="user"?k[k.length-1].text+=`
632
+ `);b.length>0&&b[b.length-1].role==="user"?b[b.length-1].text+=`
633
633
 
634
- ${ne}`:k.push({role:"user",text:ne}),yield{type:"status",content:"Subagent Update"}}}catch{}if(o){let ue=await o();ue&&(ue.startsWith("/btw")?k.length>0&&k[k.length-1].role==="user"?k[k.length-1].text+=`
634
+ ${ne}`:b.push({role:"user",text:ne}),yield{type:"status",content:"Subagent Update"}}}catch{}if(o){let ue=await o();ue&&(ue.startsWith("/btw")?b.length>0&&b[b.length-1].role==="user"?b[b.length-1].text+=`
635
635
 
636
636
  [system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/SYSTEM]
637
- [question] ${ue.replace("/btw","").trim()} [/question]`:k.push({role:"user",text:`[system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
638
- [question] ${ue.replace("/btw","").trim()} [/question]`}):k.length>0&&k[k.length-1].role==="user"?k[k.length-1].text+=`
637
+ [question] ${ue.replace("/btw","").trim()} [/question]`:b.push({role:"user",text:`[system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
638
+ [question] ${ue.replace("/btw","").trim()} [/question]`}):b.length>0&&b[b.length-1].role==="user"?b[b.length-1].text+=`
639
639
 
640
- [STEERING HINT from USER, HIGH PRIORITY] ${ue.trim().toUpperCase()} [/STEERING HINT]`:k.push({role:"user",text:`[STEERING HINT from USER, HIGH PRIORITY] ${ue.trim().toUpperCase()} [/STEERING HINT]`}),yield{type:"status",content:`${ue.startsWith("/btw")?"Question Forwarded...":"Steering Hint Injected..."}`})}let Oe,Qe=!1,We=1,Ve=1,ce="",Bt=null,Je=null,Zt=null,q=0,Z=[],je=0,rn=!1,Ut=!1,wn=!1,En=!1,Qn=!0,po=0,tt="",qe="",Wt=!1,Zn=!1,Be=!0,_e=e,mt="";for(;We<=yn&&Ve<=yn&&!Qe&&!Ot;){let ue=!1;try{ce="",Qn&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},Qn=!1,Ve===1&&(tt=""));let Ee=P=>{if(!P||!P.includes("[tool:"))return P;let te="___THINK_OPEN_TAG___",U="___THINK_CLOSE_TAG___";P=P.replace("<think>",te).replace("</think>",U),P=P.replace(uc,(pe,de)=>de.includes("[tool:")?de.trim():pe);let G="",ke=0;for(;ke<P.length;){let pe=P.indexOf("[tool:",ke);if(pe===-1){G+=P.substring(ke).replace(ba,"").replace(Sa,"");break}let de=P.substring(ke,pe);G+=de.replace(ba,"").replace(Sa,"");let Rt=P.indexOf("]",pe);if(Rt===-1){G+=P.substring(pe);break}G+=P.substring(pe,Rt+1),ke=Rt+1}return P=G,P=P.replaceAll(te,"<think>").replaceAll(U,"</think>"),P},ne=k.filter(P=>(P.role==="user"||P.role==="agent"||P.role==="system")&&!String(P.id).startsWith("welcome")&&!P.isMeta&&!P.isTerminalRecord&&!(P.text&&P.text.startsWith("[TERMINAL_RECORD]"))).map((P,te,U)=>{let G=P.text||"";m||(G=G.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),P.role==="agent"&&(G=Ee(G),G=G.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),G=G.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*"));let ke=[];return Array.isArray(P.parts)&&P.parts.length>0?ke=P.parts.map(pe=>{if(pe.text){let de=pe.text;return m||(de=de.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),P.role==="agent"&&(de=Ee(de),de=de.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),de=de.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*")),{text:de}}return pe}):ke=[{text:G}],P.binaryPart&&fn(_e)&&U.slice(te+1).filter(de=>de.role==="user"&&!de.text?.startsWith("[TOOL RESULT]")).length<=2&&ke.push(P.binaryPart),{role:P.role==="user"||P.role==="system"?"user":"model",parts:ke}});for(let P=0;P<ne.length;P++){let te=ne[P],U=te.parts?.[0]?.text||"";if(te.role==="model"&&/\[tool:/i.test(U)){let G=-1;for(let ke=P+1;ke<ne.length;ke++){let pe=ne[ke],de=pe.parts?.[0]?.text||"";if(pe.role==="user"&&de.startsWith("[TOOL RESULT]")){G=ke;break}}if(G!==-1&&G!==P+1){let[ke]=ne.splice(G,1);ne.splice(P+1,0,ke)}}}for(let P=ne.length-2;P>=0;P--){let te=ne[P],U=ne[P+1];te.role==="user"&&U.role==="user"&&(U.parts?.[0]?.text||"").trim().startsWith("[SYSTEM")&&ne.splice(P,1)}let nt=[];for(let P=0;P<ne.length;P++){let te=ne[P];if(nt.length===0)nt.push(te);else{let U=nt[nt.length-1];U.role===te.role?(U.parts[0].text+=`
640
+ [STEERING HINT from USER, HIGH PRIORITY] ${ue.trim().toUpperCase()} [/STEERING HINT]`:b.push({role:"user",text:`[STEERING HINT from USER, HIGH PRIORITY] ${ue.trim().toUpperCase()} [/STEERING HINT]`}),yield{type:"status",content:`${ue.startsWith("/btw")?"Question Forwarded...":"Steering Hint Injected..."}`})}let Oe,Qe=!1,We=1,Ve=1,ce="",Bt=null,Je=null,Zt=null,q=0,Z=[],je=0,rn=!1,Ut=!1,wn=!1,En=!1,Qn=!0,go=0,tt="",qe="",Wt=!1,Zn=!1,Be=!0,Me=e,mt="";for(;We<=yn&&Ve<=yn&&!Qe&&!Ot;){let ue=!1;try{ce="",Qn&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},Qn=!1,Ve===1&&(tt=""));let Ee=L=>{if(!L||!L.includes("[tool:"))return L;let te="___THINK_OPEN_TAG___",B="___THINK_CLOSE_TAG___";L=L.replace("<think>",te).replace("</think>",B),L=L.replace(xc,(pe,de)=>de.includes("[tool:")?de.trim():pe);let G="",ke=0;for(;ke<L.length;){let pe=L.indexOf("[tool:",ke);if(pe===-1){G+=L.substring(ke).replace($a,"").replace(Ca,"");break}let de=L.substring(ke,pe);G+=de.replace($a,"").replace(Ca,"");let Rt=L.indexOf("]",pe);if(Rt===-1){G+=L.substring(pe);break}G+=L.substring(pe,Rt+1),ke=Rt+1}return L=G,L=L.replaceAll(te,"<think>").replaceAll(B,"</think>"),L},ne=b.filter(L=>(L.role==="user"||L.role==="agent"||L.role==="system")&&!String(L.id).startsWith("welcome")&&!L.isMeta&&!L.isTerminalRecord&&!(L.text&&L.text.startsWith("[TERMINAL_RECORD]"))).map((L,te,B)=>{let G=L.text||"";m||(G=G.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),L.role==="agent"&&(G=Ee(G),G=G.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),G=G.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*"));let ke=[];return Array.isArray(L.parts)&&L.parts.length>0?ke=L.parts.map(pe=>{if(pe.text){let de=pe.text;return m||(de=de.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),L.role==="agent"&&(de=Ee(de),de=de.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),de=de.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*")),{text:de}}return pe}):ke=[{text:G}],L.binaryPart&&fn(Me)&&B.slice(te+1).filter(de=>de.role==="user"&&!de.text?.startsWith("[TOOL RESULT]")).length<=2&&ke.push(L.binaryPart),{role:L.role==="user"||L.role==="system"?"user":"model",parts:ke}});for(let L=0;L<ne.length;L++){let te=ne[L],B=te.parts?.[0]?.text||"";if(te.role==="model"&&/\[tool:/i.test(B)){let G=-1;for(let ke=L+1;ke<ne.length;ke++){let pe=ne[ke],de=pe.parts?.[0]?.text||"";if(pe.role==="user"&&de.startsWith("[TOOL RESULT]")){G=ke;break}}if(G!==-1&&G!==L+1){let[ke]=ne.splice(G,1);ne.splice(L+1,0,ke)}}}for(let L=ne.length-2;L>=0;L--){let te=ne[L],B=ne[L+1];te.role==="user"&&B.role==="user"&&(B.parts?.[0]?.text||"").trim().startsWith("[SYSTEM")&&ne.splice(L,1)}let nt=[];for(let L=0;L<ne.length;L++){let te=ne[L];if(nt.length===0)nt.push(te);else{let B=nt[nt.length-1];B.role===te.role?(B.parts[0].text+=`
641
641
 
642
- `+(te.parts?.[0]?.text||""),te.parts?.length>1&&U.parts.push(...te.parts.slice(1))):nt.push(te)}}ne.length=0,ne.push(...nt),_e=e;let _t=`${d}|${u}|${r}|${a}|${_e}|${JSON.stringify(i)}|${!!l?.dynamicDirAwareness}|${!!l?.subAgents}`;if(ws.key===_t&&ws.value)mt=ws.value;else{let P=u==="Mistral"?!!qs(_e):!(_e||"gemma").toLowerCase().startsWith("gemma");mt=yr(i,((_e||"gemma").toLowerCase().startsWith("gemma"),a),r,l,m,R,u,u==="Google"?!0:y,P,d),l?.dynamicDirAwareness||(mt+=`
643
- ${tr.replace(`
642
+ `+(te.parts?.[0]?.text||""),te.parts?.length>1&&B.parts.push(...te.parts.slice(1))):nt.push(te)}}ne.length=0,ne.push(...nt),Me=e;let _t=`${d}|${f}|${r}|${a}|${Me}|${JSON.stringify(i)}|${!!l?.dynamicDirAwareness}|${!!l?.subAgents}`;if(ws.key===_t&&ws.value)mt=ws.value;else{let L=f==="Mistral"?!!qs(Me):!(Me||"gemma").toLowerCase().startsWith("gemma");mt=Tr(i,((Me||"gemma").toLowerCase().startsWith("gemma"),a),r,l,m,R,f,f==="Google"?!0:y,L,d),l?.dynamicDirAwareness||(mt+=`
643
+ ${ar.replace(`
644
644
  **Directory Structure**`,`
645
- **Directory Structure**`)}`),ws.key=_t,ws.value=mt}let Mt=ne[ne.length-1];if(No()&H>0){await new Promise(U=>setTimeout(U,2500)),yield{type:"status",content:"Verifying"};let P=await gs(),te=P?P.diagnostics:null;te&&Mt&&Mt.role==="user"&&Mt.parts?.[0]?.text&&(Mt.parts[0].text+=`
646
- ${te} [/ERROR]`),yield{type:"status",content:"Working"}}if(u==="Mistral"||u==="Google"&&e?.toLowerCase().startsWith("gemma")){let te=a!=="Fast"&&(u==="Mistral"||a!=="xHigh")?". **strictly maintain thinking policy. do not start a response without <think>...</think>**":"",U=`
647
- [SYSTEM] Tool result received. Analyze output and proceed with your turn [/SYSTEM]`;Mt&&Mt.role==="user"&&Mt.parts?.[0]?.text?.startsWith("[TOOL RESULT]")&&(Mt.parts[0].text+=U)}if(l?.advanceRollback&&Mt&&Mt.role==="user"&&Mt.parts?.[0]?.text?.startsWith("[TOOL RESULT]"))try{let P=await Kn.getLatestFileChanges(d);if(P&&(P.newFiles.length>0||P.modifiedFiles.length>0||P.deletedFiles.length>0)){let te=`
645
+ **Directory Structure**`)}`),ws.key=_t,ws.value=mt}let Mt=ne[ne.length-1];if(Uo()&H>0){await new Promise(B=>setTimeout(B,2500)),yield{type:"status",content:"Verifying"};let L=await gs(),te=L?L.diagnostics:null;te&&Mt&&Mt.role==="user"&&Mt.parts?.[0]?.text&&(Mt.parts[0].text+=`
646
+ ${te} [/ERROR]`),yield{type:"status",content:"Working"}}if(f==="Mistral"||f==="Google"&&e?.toLowerCase().startsWith("gemma")){let te=a!=="Fast"&&(f==="Mistral"||a!=="xHigh")?". **strictly maintain thinking policy. do not start a response without <think>...</think>**":"",B=`
647
+ [SYSTEM] Tool result received. Analyze output and proceed with your turn [/SYSTEM]`;Mt&&Mt.role==="user"&&Mt.parts?.[0]?.text?.startsWith("[TOOL RESULT]")&&(Mt.parts[0].text+=B)}if(l?.advanceRollback&&Mt&&Mt.role==="user"&&Mt.parts?.[0]?.text?.startsWith("[TOOL RESULT]"))try{let L=await zn.getLatestFileChanges(d);if(L&&(L.newFiles.length>0||L.modifiedFiles.length>0||L.deletedFiles.length>0)){let te=`
648
648
  [system] File Changes:
649
- `;for(let G of P.newFiles)te+=`* ${G} (created)
650
- `;for(let G of P.modifiedFiles)te+=`* ${G} (modified)
651
- `;for(let G of P.deletedFiles)te+=`* ${G} (deleted)
652
- `;te+="[/system]",Mt.parts[0].text+=te;let U=-1;for(let G=k.length-1;G>=0;G--)if(k[G].role==="user"&&k[G].text?.startsWith("[TOOL RESULT]")){U=G;break}U!==-1&&(k[U].text+=te)}}catch{}let tn=Math.floor(Bs*(r==="Flux"?.98:.8)),Lt=H+1;Lt>=tn&&Mt&&Mt.parts?.[0]&&(Mt.parts[0].text+=`
653
- [system] WARNING, Turn Limit Impending: Step ${Lt}/${Bs}. Wrap up quickly/prompt user to continue. [/system]`);let Pt=new Promise((P,te)=>{C.signal.aborted&&te(new DOMException("The user aborted a request.","AbortError")),C.signal.addEventListener("abort",()=>{te(new DOMException("The user aborted a request.","AbortError"))})});Pt.catch(()=>{});let an=ne;if(u==="Ollama")Oe=$a(t.apiKey,_e,an,mt,a,r,y,C.signal,1,l?.ollamaEndpoint||"Cloud");else if(u==="OpenRouter")Oe=Xi(t.apiKey,_e,an,mt,a,r,y,C.signal,1);else if(u==="DeepSeek")Oe=Yi(t.apiKey,_e,an,mt,a,r,y,C.signal,1.05);else if(u==="Mistral")Oe=Vi(t.apiKey,_e,an,mt,a,r,y,C.signal,1);else if(u==="NVIDIA"){let P=Ji(t.apiKey,_e,an,mt,a,r,y,C.signal,1.05);Oe=gc(P,_e)}else{let te=Qi(t?.apiKey).models.generateContentStream({model:_e||"gemini-3-flash-preview",contents:an,config:{systemInstruction:mt,mediaResolution:"MEDIA_RESOLUTION_HIGH",safetySettings:[{category:Vn.HARM_CATEGORY_HARASSMENT,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_HATE_SPEECH,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Yn.BLOCK_NONE}],thinkingConfig:(()=>{let U=(_e||"").toLowerCase(),G=U.includes("gemma-4")||U.startsWith("gemma"),ke=U.includes("gemini-3");if(G||ke)return G?a.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:at.MINIMAL}:{includeThoughts:!0,thinkingLevel:at.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:U.includes("pro")?at.LOW:at.MINIMAL,Low:at.LOW,Medium:at.MEDIUM,Standard:at.MEDIUM,High:at.HIGH,xHigh:at.HIGH}[a]||at.MEDIUM};{let pe={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[a]||2048;return pe===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:pe}}})()}},{signal:C.signal});Oe=await Promise.race([te,Pt])}ce="",Bt=null,Zt=null,Z=[],je=0,yield{type:"model_update",content:null},qe="",Wt=tt.length>0;let xn="",Ko=Date.now(),ss=async function*(){if(u==="Google"&&xn){let P=Us(xn);for(let te of P)yield te;xn="",Ko=Date.now()}},lr=!0,os="",bs=!1,lt=null,Us=P=>{let te=[],U=P;for(;U.length>0;)if(bs){let G=os+U;if(lt==="tool"||lt==="agent"){let de=lt==="tool"?"[tool:functions.":"[agent:generalist.",Rt=lt==="tool"?"[tool":"[agent";if(!G.startsWith(Rt)||G.length>=de.length&&!G.startsWith(de)){te.push({type:"text",content:G}),os="",bs=!1,lt=null,U="";break}}let ke=-1,pe="]";if(lt==="tool"||lt==="agent"){let de=0,Rt=null,K=0,me=!1;for(let Ke=0;Ke<G.length;Ke++){let _=G[Ke];if(Rt){if(_===Rt){let bt=0;for(let Le=Ke-1;Le>=0&&G[Le]==="\\";Le--)bt++;bt%2===0&&(Rt=null)}}else if(_==='"'||_==="'"||_==="`")Rt=_;else if(_==="(")de++,me=!0;else if(_===")")de--;else if(_==="[")K++;else if(_==="]"){if(me&&de===0&&K===1){ke=Ke;break}K--}}}else lt==="end"?pe="[[END]]":lt==="kimi_section"?pe="<|tool_calls_section_end|>":lt==="kimi_call"&&(pe="<|tool_call_end|>"),ke=G.indexOf(pe);if(ke!==-1){let de=pe.length;if(!lt.startsWith("kimi")){let Rt=G.substring(0,ke+de);te.push({type:"text",content:Rt})}os="",bs=!1,lt=null,U=G.substring(ke+de)}else{let de=lt.startsWith("kimi")?8192:512;G.length>de?(lt.startsWith("kimi")||te.push({type:"text",content:G}),os="",bs=!1):os=G,U="";break}}else{let G=U.indexOf("[tool"),ke=U.indexOf("[agent"),pe=U.indexOf("[[END]]"),de=U.indexOf("<|tool_calls_section_begin|>"),Rt=U.indexOf("<|tool_call_begin|>"),K=[{type:"tool",idx:G,start:"[tool",end:"]"},{type:"agent",idx:ke,start:"[agent",end:"]"},{type:"end",idx:pe,start:"[[END]]",end:"[[END]]"},{type:"kimi_section",idx:de,start:"<|tool_calls_section_begin|>",end:"<|tool_calls_section_end|>"},{type:"kimi_call",idx:Rt,start:"<|tool_call_begin|>",end:"<|tool_call_end|>"}].filter(me=>me.idx!==-1).sort((me,Ke)=>me.idx-Ke.idx);if(K.length>0){let me=K[0];me.idx>0&&te.push({type:"text",content:U.substring(0,me.idx)}),bs=!0,lt=me.type,os="",U=U.substring(me.idx)}else{let me=["[tool","[agent","[[END]]","<|tool_calls_section_begin|>","<|tool_call_begin|>"],Ke=-1;for(let _ of me){for(let bt=_.length-1;bt>0;bt--)if(U.endsWith(_.substring(0,bt))){Ke=U.length-bt;let Le=me.indexOf(_);Le===0?lt="tool":Le===1?lt="agent":Le===2?lt="end":Le===3?lt="kimi_section":lt="kimi_call";break}if(Ke!==-1)break}if(Ke!==-1)Ke>0&&te.push({type:"text",content:U.substring(0,Ke)}),bs=!0,os=U.substring(Ke),U="";else{te.push({type:"text",content:U});break}}}return te},Oa=Oe[Symbol.asyncIterator]();for(;;){let{value:P,done:te}=await Promise.race([Oa.next(),Pt]);if(te)break;if(P&&P.type==="status"){yield P;continue}let U="",G=P.candidates?.[0]?.content?.parts;if(G&&G.length>0)for(let pe of G){let de=typeof pe.text=="string"?pe.text:pe.text?parseChunkText(pe.text):"";pe.thought?de&&(ue||(U+="<think>",ue=!0),U+=de):de&&(ue&&(U+="</think>",ue=!1),U+=de)}else P.text&&ue&&(U+="</think>",ue=!1);U=Pn(U);let ke=U?U.trim().split(/\s+/).filter(Boolean).length:0;if(t&&typeof t.onTokenChunk=="function"&&t.onTokenChunk(U,ke),lr&&(yield{type:"status",content:"Thinking"},lr=!1),Ot){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
654
-
655
- \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(U){if(Wt){if(qe+=U,qe.length>=64){let K=0,me=Math.min(tt.length,qe.length);for(let _=me;_>=10;_--)if(tt.endsWith(qe.substring(0,_))){K=_;break}let Ke=qe.substring(K);if(Ke){let bt=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(tt)?Ke.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):Ke.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(bt)if(ce+=bt,u==="Google")xn+=bt;else{yield*ss();let Le=Us(bt);for(let ie of Le)yield ie}}Wt=!1,qe=""}continue}else if(ce+=U,u==="Google")xn+=U;else{yield*ss();let K=Us(U);for(let me of K)yield me}let pe=yc(ce);if(pe.inside){Zn=!0,Zt||(Zt=Date.now());let me={Ask:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Cancel:"cancel",Await:"await",Answer:"answer",Steer:"steer",steer:"steer"}[pe.toolName]||pe.toolName,Ke=pe.args||"",_=null;if(["write_file","update_file","view_file","read_folder","write_pdf","write_docx","search_keyword","generate_image","file_map","invoke","invoke_sync","get_progress","await","answer"].includes(me)){let Le=I(Ke),ie=Le.path||Le.targetFile||Le.TargetFile||Le.directory,bn=Le.keyword,is=Le.title||Le.task,Bn=Le.id||Le.taskId,Te=Le.timeout||Le.time;if(bn!=null)_=String(bn).replace(ys,"");else if(ie)_=Q.basename(String(ie).replace(ys,"").replace(pa,"/"));else if(is&&(me==="invoke"||me==="invoke_sync"))_=String(is).replace(ys,"").substring(0,30);else if(Bn&&me==="get_progress")_=String(Bn).replace(ys,"");else if(Te&&me==="await"){let jt=parseFloat(String(Te).replace(ys,""));isNaN(jt)?_=String(Te).replace(ys,""):(jt<5&&(jt=5),jt>120&&(jt=120),_=(Cn=>{if(Cn>=60){let Yo=Math.floor(Cn/60),Ss=Cn%60;return`${Yo}m${Ss>0?` ${Ss}s`:""}`}return`${Cn}s`})(jt))}else{let jt=Ke.match(rc);if(jt){let zt=jt[1].replace(ys,"");me==="invoke"||me==="invoke_sync"||me==="get_progress"?_=zt.substring(0,30):_=me==="search_keyword"||me==="file_map"?zt:Q.basename(zt.replace(pa,"/"))}}}let bt=`${Ki[me]||me}${_?` ${_}`:""}`;if((me!==Bt||_!==Je)&&(Bt=me,Je=_,yield{type:"status",content:`${bt}`},process.stdout.isTTY)){let ie={WebSearch:"Searching",web_search:"Searching",WebScrape:"Reading",web_scrape:"Reading",ReadFile:"Reading",read_file:"Reading",ReadFolder:"Reading",read_folder:"Reading",WriteFile:"Writing",write_file:"Writing",UpdateFile:"Editing",update_file:"Editing",WritePdf:"Creating",write_pdf:"Creating",WriteDocx:"Creating",write_docx:"Creating",SearchKeyword:"Searching",search_keyword:"Searching",CodeSearch:"Searching",code_search:"Searching",Run:"Executing",Ask:"User Input Required",Memory:"Updating Memory",GenerateImage:"Generating",InvokeSync:"Sub-Agent Working",invoke_sync:"Sub-Agent Working",Invoke:"Working",invoke:"Working",GetProgress:"Checking Progress",get_progress:"Checking Progress",Cancel:"Stopping Generalist",cancel:"Stopping Generalist",Await:"Waiting",await:"Waiting",EmergencyRollback:"Rolling the Ball",Answer:"Answering Sub-Agent",answer:"Answering Sub-Agent",Steer:"Steering Sub-Agent",steer:"Steering Sub-Agent",Click:"Clicking",click:"Clicking",Drag:"Dragging",drag:"Dragging",Scroll:"Scrolling",scroll:"Scrolling",KeyboardTyping:"Typing",keyboard_typing:"Typing",KeyPress:"Pressing Key",key_press:"Pressing Key",RecaptureScreen:"Recapturing Screen",recapture_screen:"Recapturing Screen"}[me]||"Working";process.stdout.write(`\x1B]0;${ie}...\x07`)}}if(ce.length-po>150){po=ce.length;let K=Ca(ce,!1),Ke=(K.match(/(?:<think>|\[think\])([\s\S]*?)(?:<\/think>|\[\/think\]|$)/gi)||[]).join("").trim(),_=Ke.split(/[.!?]\s+/),bt=new Set(_),Le=_.length>10?(_.length-bt.size)/_.length:0,ie=Ke.split(/\s+/).filter($e=>$e.length>0).length,bn=.6,is=.8,Bn=!1;if((u.toLowerCase().includes("google")||u.toLowerCase().includes("mistral"))&&((_e||"").toLowerCase().startsWith("gemma")||(_e||"").toLowerCase().includes("stral"))){let A={low:256,medium:1024,high:8192,max:16384,xhigh:16384}[a?.toLowerCase()]||2500;Bn=ie>A}if(Le>bn||Bn){yield{type:"status",content:`${Le>bn?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},Ut=!0,await new Promise(A=>setTimeout(A,3e3));break}let zt=ka(ce).trim().split(/[.!?]\s+/),Cn=new Set(zt);if((zt.length>10?(zt.length-Cn.size)/zt.length:0)>is){yield{type:"status",content:"Response Loop Detected. Re-centering..."},Ut=!1,En=!0,await new Promise($e=>setTimeout($e,3e3));break}let Ss=K.replace(Zl,"").replace(ec,"").replace(tc,"").replace(nc,""),Ht=Ss.toLowerCase().split(/\s+/).map($e=>$e.replace(sc,"")).filter($e=>$e.length>0),_n=!1;if(Ht.length>=10)for(let $e=1;$e<=15;$e++){let A=Math.max(3,Math.ceil(10/$e));if(Ht.length<$e*A)continue;let z=Ht.slice(Ht.length-$e),ae=z.join(" ");if($e>1&&ae===z.slice(0,Math.floor($e/2)).join(" ").repeat(2).trim())continue;let ge=!0;for(let we=1;we<A;we++)if(Ht.slice(Ht.length-$e*(we+1),Ht.length-$e*we).join(" ")!==ae){ge=!1;break}if(ge){_n=!0;break}}if(!_n){let $e=Ss.toLowerCase().replace(oc,"");if($e.length>=20)for(let A=1;A<=10;A++){let z=Math.max(5,Math.ceil(16/A));if($e.length<A*z)continue;let ae=$e.substring($e.length-A),ge=!0;for(let we=1;we<z;we++)if($e.substring($e.length-A*(we+1),$e.length-A*we)!==ae){ge=!1;break}if(ge){_n=!0;break}}}if(_n){yield{type:"status",content:"Stuttering Detected. Re-centering..."},Ut=!1,wn=!0,await new Promise($e=>setTimeout($e,3e3));break}}let de=ce.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/gi,""),Rt=jo(de);for(;Rt.length>je;){yield*ss();let K=Rt[je],me=Date.now(),_={Ask:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Await:"await",await:"await",AwaitSubagent:"await",awaitSubagent:"await",Answer:"answer",answer:"answer",AnswerSubagent:"answer",answerSubagent:"answer",Steer:"steer",steer:"steer",SteerSubagent:"steer",steerSubagent:"steer",Cancel:"cancel",cancel:"cancel",Click:"click",click:"click",Drag:"drag",drag:"drag",Scroll:"scroll",scroll:"scroll",KeyboardTyping:"keyboard_typing",keyboard_typing:"keyboard_typing",KeyPress:"key_press",key_press:"key_press",RecaptureScreen:"recapture_screen",recapture_screen:"recapture_screen",EmergencyRollback:"EmergencyRollback"}[K.toolName]||K.toolName,bt=Ki[_]||K.toolName,Le=xs(_,K.args);yield{type:"status",content:`${bt}${Le?` ${Le}`:""}`};let ie="";if(_==="click"){let A=I(K.args);ie=`\u2714 Clicked: ${A.intendedClickText?`${A.intendedClickText}`:""}`}else if(_==="drag"){let A=I(K.args);ie=`\u2714 Dragged: Cell ${A.fromGridId||""} \u2192 Cell ${A.toGridId||""}`}else if(_==="scroll"){let A=I(K.args);ie=`\u2714 Scrolled: ${A.direction||"down"} (${A.amount||1})`}else if(_==="keyboard_typing"){let A=I(K.args);ie=`\u2714 Typed: ${A.text?`"${A.text.length>20?A.text.substring(0,20)+"...":A.text}"`:""}`}else if(_==="key_press")ie=`\u2714 Pressed Key: ${I(K.args).key||""}`;else if(_==="recapture_screen")ie="\u2714 Recaptured Screen";else if(_==="web_search"){let{query:A,limit:z=10,aiMode:ae=!1}=I(K.args);ie=`${A?"\u2714":"\u2718"} ${ae?"AI Search":"Searched"}: ${A?`${A}`:"No Search Query"}${ae===!1&&A?` \u2192 ${z}`:""}`}else if(_==="web_scrape"){let A=I(K.args).url||null;ie=`${A?"\u2714":"\u2718"} Visited: ${A||"No Source"}`}else if(_==="view_file"){let{path:A,StartLine:z,EndLine:ae,start_line:ge,end_line:we,startLine:He,endLine:Me}=I(K.args),be=z||ge||He,ee=ae||we||Me,fe=parseInt(be)||1,le=parseInt(ee)||(be?fe+800:800),Fe="...",Ze=le;try{let ze=Q.resolve(process.cwd(),A);if(ve.existsSync(ze)){let Et=ve.readFileSync(ze,"utf8").split(`
656
- `).length;Fe=Et,!be&&!ee&&Et>800?Ze=Math.min(50,Et):Ze=Math.min(le,Et)}}catch{}let xe=(A||"").toLowerCase(),Pe=xe.endsWith(".pdf"),ot=xe.endsWith(".docx")||xe.endsWith(".doc")||xe.endsWith(".ppt")||xe.endsWith(".pptx")||xe.endsWith(".xls")||xe.endsWith(".xlsx"),Ce=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(xe);Pe||ot?ie=`${A.length>0?"\u2714":"\u2718"} ${A?`Analyzed: ${Q.basename(A)}`:"Analyzed: File Not Found"}`:Ce?ie=`${A.length>0?"\u2714":"\u2718"} ${A?`Processed: ${Q.basename(A)}`:"Processed: File Not Found"}`:ie=`${Fe!=="..."?"\u2714":"\u2718"} Read: ${A?`${Q.basename(A)} \u2192 ${Fe!=="..."?`Lines ${fe} - ${Ze} of ${Fe}`:"File Not Found"}`:"File Not Found"}`}else if(_==="list_files"||_==="read_folder"){let A=_==="list_files"?"List":"Browsed",z=I(K.args).path||null,ae=I(K.args).recurse||1;ie=`${z?"\u2714":"\u2718"} ${A}: ${z?`${z==="."?`./${ae>1?"*":""}`:`${z.replaceAll("\\","/")}${ae>1?`${z.endsWith("/")?"*":"/*"}`:`${z.endsWith("/")?"":"/"}`}`}`:"No Folder Selected"}`}else if(_==="write_file"||_==="update_file"){let A=_==="write_file"?"Created":"Edited",z=I(K.args).path||null;ie=`${z?"\u2714":"\u2718"} ${A}: ${z.replaceAll("\\","/")||"No File Changes"}`}else if(_==="write_pdf"){let A=I(K.args).path||null;ie=`${A?"\u2714":"\u2718"} Generated: ${A.replaceAll("\\","/")||"No PDF Generated"}`}else if(_==="write_docx"){let A=I(K.args).path||null;ie=`${A?"\u2714":"\u2718"} Generated: ${A.replaceAll("\\","/")||"No Docx Generated"}`}else if(_==="file_map"){let A=I(K.args).path;ie=`${A?"\u2714":"\u2718"} Indexed: ${A.replaceAll("\\","/")?""+A:"File Not Found"}`}else if(_.toLowerCase()==="search_keyword"||_.toLowerCase()==="todo")ie="";else if(_.toLowerCase()==="generate_image"){let{path:A,outputPath:z,output:ae}=I(K.args);ie=`\u2714 Generated: ${A||z||ae||"generated_image.png"}`}else if(_==="invoke_sync"||_==="InvokeSync"){let A=xs(_,K.args);ie=`\u2714 Called Generalist${A?`: ${A}`:""}`}else if(_==="Invoke"||_==="InvokeAsync"||_==="invoke"){let A=xs(_,K.args);ie=`\u2714 Started Generalist${A?`: ${A}`:""}`}else if(_==="get_progress"||_==="GetProgress"){let A=xs(_,K.args);ie=`\u2714 Checked${A?`: ${A}`:""}`}else if(_==="cancel"){let A=xs(_,K.args);ie=`\u{1F6C7} Cancelled${A?`: ${A}`:""}`}else if(_==="steer"||_==="Steer"){let A=xs(_,K.args);ie=`\u2714 Steered${A?`: ${A}`:""}`}else if(_==="EmergencyRollback"){let{method:A}=I(K.args);ie=A==="forceRevert"?"":"\u2714 Rollback Point Checked"}else if(_==="await"||_==="Await"){let{time:A,timeout:z}=I(K.args),ae=parseFloat(z||A)||0;ae||(ae=120);let ge=Me=>{if(Me>=60){let be=Math.floor(Me/60),ee=Me%60;return`${be}m${ee>0?` ${ee}s`:""}`}return`${Me}s`},we=["Aligning Moon Phase","Contemplating Existence","Staring At Void","Delaying Professionally","Negotiating With Electrons","Touching Grass (virtually)","Panicking Softly","Rethinking Career Choices","Loading Cat Videos","Summoning Braincell #2","Pretending To Be Busy","Waiting For Motivation DLC","Rotating Internal Screaming","Downloading More RAM","Feeding The Hamsters","Gaslighting Scheduler","Performing Dramatic Pause","Buffering Social Energy","Calculating Regret","Reading Terms And Conditions","Becoming Sentient Briefly","Contacting Ancestors"];ie=`\u2714 ${we[Math.floor(Math.random()*we.length)]} \u2192 ${ge(ae)}`}else _==="Answer"||_==="answer"?ie="\u2714 Resolved Sub-Agent Query":_==="exec_command"||_==="ask"?ie="":ie=`Executed: ${K.toolName}`;if(yield*ss(),_==="exec_command"){let{command:A}=I(K.args);if(A&&t.systemSettings&&t.systemSettings.allowExternalAccess===!1){let z=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],ae=Q.resolve(process.cwd()).substring(0,3).toLowerCase(),ge=ee=>{let fe=[],le="",Fe=null;for(let Ze=0;Ze<ee.length;Ze++){let xe=ee[Ze];Fe?(xe===Fe&&(Fe=null),le+=xe):xe==='"'||xe==="'"?(Fe=xe,le+=xe):xe==="&"&&ee[Ze+1]==="&"||xe==="|"&&ee[Ze+1]==="|"?(le.trim()&&(fe.push(le.trim()),le=""),Ze++):xe===";"||xe==="|"||xe==="&"?le.trim()&&(fe.push(le.trim()),le=""):le+=xe}return le.trim()&&fe.push(le.trim()),fe},we=ee=>{let fe=[],le="",Fe=null;for(let Ze=0;Ze<ee.length;Ze++){let xe=ee[Ze];Fe?(xe===Fe&&(Fe=null),le+=xe):xe==='"'||xe==="'"?(Fe=xe,le+=xe):/\s/.test(xe)?le&&(fe.push(le),le=""):le+=xe}return le&&fe.push(le),fe},He=ee=>{let fe=ee.replace(/^['"]|['"]$/g,"").trim();return!fe||process.platform==="win32"&&/^\/[a-zA-Z0-9?]+$/.test(fe)?!1:z.some(le=>{if(le.source==="[a-zA-Z]:[\\\\\\/]"){let Fe=fe.match(/[a-zA-Z]:[\\\/]/i);return Fe&&Fe[0].toLowerCase()!==ae}return le.test(fe)})};if(ge(A).some(ee=>{let fe=we(ee);if(fe.length===0)return!1;let le=fe[0].replace(/^['"]|['"]$/g,"").toLowerCase();if(["echo","printf","write-output"].includes(le)){let Ze=!1;return fe.some(xe=>{let Pe=xe.replace(/^['"]|['"]$/g,"");if(Pe===">"||Pe===">>"||Pe==="<")return Ze=!0,!1;if(Pe.startsWith(">")||Pe.startsWith("<")){let ot=Pe.replace(/^[><]+/,"");return He(ot)}return Ze?(Ze=!1,He(xe)):!1})}return fe.some(Ze=>He(Ze))})){let ee='Access Denied. Prohibited from accessing external directories while "External Workspace Access" is disabled.';t.onExecStart&&t.onExecStart(A||"No Command"),yield{type:"exec_start"},await new Promise(fe=>setTimeout(fe,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${ee}`),await new Promise(fe=>setTimeout(fe,50)),t.onExecEnd&&t.onExecEnd(),Z.push({role:"user",text:`[TOOL RESULT]: ERROR: ${ee}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${ee}`},je++;continue}}t.onExecStart&&t.onExecStart(A||"No Command"),yield{type:"exec_start"}}let bn=I(K.args),is=bn.path||bn.targetPath||null;if(is){let A=t.systemSettings&&t.systemSettings.allowExternalAccess===!1,z=Q.resolve(is),ae=Q.resolve(process.cwd());if(A&&!z.startsWith(ae)){let ge="Access Denied. You are not allowed to access files outside the current workspace.";if(_==="write_file"||_==="update_file"){let He=`\u2718 ${_==="write_file"?"Write Canceled":"Edit Canceled"}: ${bn.path||"..."}`,Me=115;process.stdout.isTTY&&(Me=process.stdout.columns-5||120);let be=Math.min(He.length+4,Me),ee=`${He.padEnd(be-2).substring(0,be-2)}`;yield{type:"visual_feedback",content:gn(`${Be?`
649
+ `;for(let G of L.newFiles)te+=`* ${G} (created)
650
+ `;for(let G of L.modifiedFiles)te+=`* ${G} (modified)
651
+ `;for(let G of L.deletedFiles)te+=`* ${G} (deleted)
652
+ `;te+="[/system]",Mt.parts[0].text+=te;let B=-1;for(let G=b.length-1;G>=0;G--)if(b[G].role==="user"&&b[G].text?.startsWith("[TOOL RESULT]")){B=G;break}B!==-1&&(b[B].text+=te)}}catch{}let tn=Math.floor(Bs*(r==="Flux"?.98:.8)),Lt=H+1;Lt>=tn&&Mt&&Mt.parts?.[0]&&(Mt.parts[0].text+=`
653
+ [system] WARNING, Turn Limit Impending: Step ${Lt}/${Bs}. Wrap up quickly/prompt user to continue. [/system]`);let Pt=new Promise((L,te)=>{C.signal.aborted&&te(new DOMException("The user aborted a request.","AbortError")),C.signal.addEventListener("abort",()=>{te(new DOMException("The user aborted a request.","AbortError"))})});Pt.catch(()=>{});let an=ne;if(f==="Ollama")Oe=Ia(t.apiKey,Me,an,mt,a,r,y,C.signal,1,l?.ollamaEndpoint||"Cloud");else if(f==="OpenRouter")Oe=sr(t.apiKey,Me,an,mt,a,r,y,C.signal,1);else if(f==="DeepSeek")Oe=er(t.apiKey,Me,an,mt,a,r,y,C.signal,1.05);else if(f==="Mistral")Oe=tr(t.apiKey,Me,an,mt,a,r,y,C.signal,1);else if(f==="NVIDIA"){let L=nr(t.apiKey,Me,an,mt,a,r,y,C.signal,1.05);Oe=Tc(L,Me)}else{let te=or(t?.apiKey).models.generateContentStream({model:Me||"gemini-3-flash-preview",contents:an,config:{systemInstruction:mt,mediaResolution:"MEDIA_RESOLUTION_HIGH",safetySettings:[{category:Vn.HARM_CATEGORY_HARASSMENT,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_HATE_SPEECH,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Yn.BLOCK_NONE}],thinkingConfig:(()=>{let B=(Me||"").toLowerCase(),G=B.includes("gemma-4")||B.startsWith("gemma"),ke=B.includes("gemini-3");if(G||ke)return G?a.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:at.MINIMAL}:{includeThoughts:!0,thinkingLevel:at.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:B.includes("pro")?at.LOW:at.MINIMAL,Low:at.LOW,Medium:at.MEDIUM,Standard:at.MEDIUM,High:at.HIGH,xHigh:at.HIGH}[a]||at.MEDIUM};{let pe={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[a]||2048;return pe===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:pe}}})()}},{signal:C.signal});Oe=await Promise.race([te,Pt])}ce="",Bt=null,Zt=null,Z=[],je=0,yield{type:"model_update",content:null},qe="",Wt=tt.length>0;let xn="",Yo=Date.now(),ss=async function*(){if(f==="Google"&&xn){let L=Us(xn);for(let te of L)yield te;xn="",Yo=Date.now()}},pr=!0,os="",bs=!1,lt=null,Us=L=>{let te=[],B=L;for(;B.length>0;)if(bs){let G=os+B;if(lt==="tool"||lt==="agent"){let de=lt==="tool"?"[tool:functions.":"[agent:generalist.",Rt=lt==="tool"?"[tool":"[agent";if(!G.startsWith(Rt)||G.length>=de.length&&!G.startsWith(de)){te.push({type:"text",content:G}),os="",bs=!1,lt=null,B="";break}}let ke=-1,pe="]";if(lt==="tool"||lt==="agent"){let de=0,Rt=null,z=0,me=!1;for(let ze=0;ze<G.length;ze++){let _=G[ze];if(Rt){if(_===Rt){let bt=0;for(let Le=ze-1;Le>=0&&G[Le]==="\\";Le--)bt++;bt%2===0&&(Rt=null)}}else if(_==='"'||_==="'"||_==="`")Rt=_;else if(_==="(")de++,me=!0;else if(_===")")de--;else if(_==="[")z++;else if(_==="]"){if(me&&de===0&&z===1){ke=ze;break}z--}}}else lt==="end"?pe="[[END]]":lt==="kimi_section"?pe="<|tool_calls_section_end|>":lt==="kimi_call"&&(pe="<|tool_call_end|>"),ke=G.indexOf(pe);if(ke!==-1){let de=pe.length;if(!lt.startsWith("kimi")){let Rt=G.substring(0,ke+de);te.push({type:"text",content:Rt})}os="",bs=!1,lt=null,B=G.substring(ke+de)}else{let de=lt.startsWith("kimi")?8192:512;G.length>de?(lt.startsWith("kimi")||te.push({type:"text",content:G}),os="",bs=!1):os=G,B="";break}}else{let G=B.indexOf("[tool"),ke=B.indexOf("[agent"),pe=B.indexOf("[[END]]"),de=B.indexOf("<|tool_calls_section_begin|>"),Rt=B.indexOf("<|tool_call_begin|>"),z=[{type:"tool",idx:G,start:"[tool",end:"]"},{type:"agent",idx:ke,start:"[agent",end:"]"},{type:"end",idx:pe,start:"[[END]]",end:"[[END]]"},{type:"kimi_section",idx:de,start:"<|tool_calls_section_begin|>",end:"<|tool_calls_section_end|>"},{type:"kimi_call",idx:Rt,start:"<|tool_call_begin|>",end:"<|tool_call_end|>"}].filter(me=>me.idx!==-1).sort((me,ze)=>me.idx-ze.idx);if(z.length>0){let me=z[0];me.idx>0&&te.push({type:"text",content:B.substring(0,me.idx)}),bs=!0,lt=me.type,os="",B=B.substring(me.idx)}else{let me=["[tool","[agent","[[END]]","<|tool_calls_section_begin|>","<|tool_call_begin|>"],ze=-1;for(let _ of me){for(let bt=_.length-1;bt>0;bt--)if(B.endsWith(_.substring(0,bt))){ze=B.length-bt;let Le=me.indexOf(_);Le===0?lt="tool":Le===1?lt="agent":Le===2?lt="end":Le===3?lt="kimi_section":lt="kimi_call";break}if(ze!==-1)break}if(ze!==-1)ze>0&&te.push({type:"text",content:B.substring(0,ze)}),bs=!0,os=B.substring(ze),B="";else{te.push({type:"text",content:B});break}}}return te},Ba=Oe[Symbol.asyncIterator]();for(;;){let{value:L,done:te}=await Promise.race([Ba.next(),Pt]);if(te)break;if(L&&L.type==="status"){yield L;continue}let B="",G=L.candidates?.[0]?.content?.parts;if(G&&G.length>0)for(let pe of G){let de=typeof pe.text=="string"?pe.text:pe.text?parseChunkText(pe.text):"";pe.thought?de&&(ue||(B+="<think>",ue=!0),B+=de):de&&(ue&&(B+="</think>",ue=!1),B+=de)}else L.text&&ue&&(B+="</think>",ue=!1);B=Pn(B);let ke=B?B.trim().split(/\s+/).filter(Boolean).length:0;if(t&&typeof t.onTokenChunk=="function"&&t.onTokenChunk(B,ke),pr&&(yield{type:"status",content:"Thinking"},pr=!1),Ot){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
654
+
655
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(B){if(Wt){if(qe+=B,qe.length>=64){let z=0,me=Math.min(tt.length,qe.length);for(let _=me;_>=10;_--)if(tt.endsWith(qe.substring(0,_))){z=_;break}let ze=qe.substring(z);if(ze){let bt=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(tt)?ze.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):ze.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(bt)if(ce+=bt,f==="Google")xn+=bt;else{yield*ss();let Le=Us(bt);for(let oe of Le)yield oe}}Wt=!1,qe=""}continue}else if(ce+=B,f==="Google")xn+=B;else{yield*ss();let z=Us(B);for(let me of z)yield me}let pe=Rc(ce);if(pe.inside){Zn=!0,Zt||(Zt=Date.now());let me={Ask:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Cancel:"cancel",Await:"await",Answer:"answer",Steer:"steer",steer:"steer"}[pe.toolName]||pe.toolName,ze=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=O(ze),oe=Le.path||Le.targetFile||Le.TargetFile||Le.directory,bn=Le.keyword,is=Le.title||Le.task,Bn=Le.id||Le.taskId,Te=Le.timeout||Le.time;if(bn!=null)_=String(bn).replace(ys,"");else if(oe)_=Q.basename(String(oe).replace(ys,"").replace(ba,"/"));else if(is&&(me==="invoke"||me==="invoke_sync"))_=String(is).replace(ys,"").substring(0,30);else if(Bn&&me==="get_progress")_=String(Bn).replace(ys,"");else if(Te&&me==="await"){let jt=parseFloat(String(Te).replace(ys,""));isNaN(jt)?_=String(Te).replace(ys,""):(jt<5&&(jt=5),jt>120&&(jt=120),_=(Cn=>{if(Cn>=60){let Jo=Math.floor(Cn/60),Ss=Cn%60;return`${Jo}m${Ss>0?` ${Ss}s`:""}`}return`${Cn}s`})(jt))}else{let jt=ze.match(hc);if(jt){let Kt=jt[1].replace(ys,"");me==="invoke"||me==="invoke_sync"||me==="get_progress"?_=Kt.substring(0,30):_=me==="search_keyword"||me==="file_map"?Kt:Q.basename(Kt.replace(ba,"/"))}}}let bt=`${Qi[me]||me}${_?` ${_}`:""}`;if((me!==Bt||_!==Je)&&(Bt=me,Je=_,yield{type:"status",content:`${bt}`},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(ce.length-go>150){go=ce.length;let z=Oa(ce,!1),ze=(z.match(/(?:<think>|\[think\])([\s\S]*?)(?:<\/think>|\[\/think\]|$)/gi)||[]).join("").trim(),_=ze.split(/[.!?]\s+/),bt=new Set(_),Le=_.length>10?(_.length-bt.size)/_.length:0,oe=ze.split(/\s+/).filter($e=>$e.length>0).length,bn=.6,is=.8,Bn=!1;if((f.toLowerCase().includes("google")||f.toLowerCase().includes("mistral"))&&((Me||"").toLowerCase().startsWith("gemma")||(Me||"").toLowerCase().includes("stral"))){let A={low:256,medium:1024,high:8192,max:16384,xhigh:16384}[a?.toLowerCase()]||2500;Bn=oe>A}if(Le>bn||Bn){yield{type:"status",content:`${Le>bn?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},Ut=!0,await new Promise(A=>setTimeout(A,3e3));break}let Kt=_a(ce).trim().split(/[.!?]\s+/),Cn=new Set(Kt);if((Kt.length>10?(Kt.length-Cn.size)/Kt.length:0)>is){yield{type:"status",content:"Response Loop Detected. Re-centering..."},Ut=!1,En=!0,await new Promise($e=>setTimeout($e,3e3));break}let Ss=z.replace(rc,"").replace(ac,"").replace(lc,"").replace(cc,""),Ht=Ss.toLowerCase().split(/\s+/).map($e=>$e.replace(dc,"")).filter($e=>$e.length>0),_n=!1;if(Ht.length>=10)for(let $e=1;$e<=15;$e++){let A=Math.max(3,Math.ceil(10/$e));if(Ht.length<$e*A)continue;let K=Ht.slice(Ht.length-$e),ae=K.join(" ");if($e>1&&ae===K.slice(0,Math.floor($e/2)).join(" ").repeat(2).trim())continue;let ge=!0;for(let we=1;we<A;we++)if(Ht.slice(Ht.length-$e*(we+1),Ht.length-$e*we).join(" ")!==ae){ge=!1;break}if(ge){_n=!0;break}}if(!_n){let $e=Ss.toLowerCase().replace(fc,"");if($e.length>=20)for(let A=1;A<=10;A++){let K=Math.max(5,Math.ceil(16/A));if($e.length<A*K)continue;let ae=$e.substring($e.length-A),ge=!0;for(let we=1;we<K;we++)if($e.substring($e.length-A*(we+1),$e.length-A*we)!==ae){ge=!1;break}if(ge){_n=!0;break}}}if(_n){yield{type:"status",content:"Stuttering Detected. Re-centering..."},Ut=!1,wn=!0,await new Promise($e=>setTimeout($e,3e3));break}}let de=ce.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/gi,""),Rt=Go(de);for(;Rt.length>je;){yield*ss();let z=Rt[je],me=Date.now(),_={Ask:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Await:"await",await:"await",AwaitSubagent:"await",awaitSubagent:"await",Answer:"answer",answer:"answer",AnswerSubagent:"answer",answerSubagent:"answer",Steer:"steer",steer:"steer",SteerSubagent:"steer",steerSubagent:"steer",Cancel:"cancel",cancel:"cancel",Click:"click",click:"click",Drag:"drag",drag:"drag",Scroll:"scroll",scroll:"scroll",KeyboardTyping:"keyboard_typing",keyboard_typing:"keyboard_typing",KeyPress:"key_press",key_press:"key_press",RecaptureScreen:"recapture_screen",recapture_screen:"recapture_screen",EmergencyRollback:"EmergencyRollback"}[z.toolName]||z.toolName,bt=Qi[_]||z.toolName,Le=xs(_,z.args);yield{type:"status",content:`${bt}${Le?` ${Le}`:""}`};let oe="";if(_==="click"){let A=O(z.args);oe=`\u2714 Clicked: ${A.intendedClickText?`${A.intendedClickText}`:""}`}else if(_==="drag"){let A=O(z.args);oe=`\u2714 Dragged: Cell ${A.fromGridId||""} \u2192 Cell ${A.toGridId||""}`}else if(_==="scroll"){let A=O(z.args);oe=`\u2714 Scrolled: ${A.direction||"down"} (${A.amount||1})`}else if(_==="keyboard_typing"){let A=O(z.args);oe=`\u2714 Typed: ${A.text?`"${A.text.length>20?A.text.substring(0,20)+"...":A.text}"`:""}`}else if(_==="key_press")oe=`\u2714 Pressed Key: ${O(z.args).key||""}`;else if(_==="recapture_screen")oe="\u2714 Recaptured Screen";else if(_==="web_search"){let{query:A,limit:K=10,aiMode:ae=!1}=O(z.args);oe=`${A?"\u2714":"\u2718"} ${ae?"AI Search":"Searched"}: ${A?`${A}`:"No Search Query"}${ae===!1&&A?` \u2192 ${K}`:""}`}else if(_==="web_scrape"){let A=O(z.args).url||null;oe=`${A?"\u2714":"\u2718"} Visited: ${A||"No Source"}`}else if(_==="view_file"){let{path:A,StartLine:K,EndLine:ae,start_line:ge,end_line:we,startLine:He,endLine:Ae}=O(z.args),be=K||ge||He,ee=ae||we||Ae,fe=parseInt(be)||1,le=parseInt(ee)||(be?fe+800:800),Fe="...",Ze=le;try{let Ke=Q.resolve(process.cwd(),A);if(Ie.existsSync(Ke)){let Et=Ie.readFileSync(Ke,"utf8").split(`
656
+ `).length;Fe=Et,!be&&!ee&&Et>800?Ze=Math.min(50,Et):Ze=Math.min(le,Et)}}catch{}let xe=(A||"").toLowerCase(),Pe=xe.endsWith(".pdf"),ot=xe.endsWith(".docx")||xe.endsWith(".doc")||xe.endsWith(".ppt")||xe.endsWith(".pptx")||xe.endsWith(".xls")||xe.endsWith(".xlsx"),Ce=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(xe);Pe||ot?oe=`${A.length>0?"\u2714":"\u2718"} ${A?`Analyzed: ${Q.basename(A)}`:"Analyzed: File Not Found"}`:Ce?oe=`${A.length>0?"\u2714":"\u2718"} ${A?`Processed: ${Q.basename(A)}`:"Processed: File Not Found"}`:oe=`${Fe!=="..."?"\u2714":"\u2718"} Read: ${A?`${Q.basename(A)} \u2192 ${Fe!=="..."?`Lines ${fe} - ${Ze} of ${Fe}`:"File Not Found"}`:"File Not Found"}`}else if(_==="list_files"||_==="read_folder"){let A=_==="list_files"?"List":"Browsed",K=O(z.args).path||null,ae=O(z.args).recurse||1;oe=`${K?"\u2714":"\u2718"} ${A}: ${K?`${K==="."?`./${ae>1?"*":""}`:`${K.replaceAll("\\","/")}${ae>1?`${K.endsWith("/")?"*":"/*"}`:`${K.endsWith("/")?"":"/"}`}`}`:"No Folder Selected"}`}else if(_==="write_file"||_==="update_file"){let A=_==="write_file"?"Created":"Edited",K=O(z.args).path||null;oe=`${K?"\u2714":"\u2718"} ${A}: ${K.replaceAll("\\","/")||"No File Changes"}`}else if(_==="write_pdf"){let A=O(z.args).path||null;oe=`${A?"\u2714":"\u2718"} Generated: ${A.replaceAll("\\","/")||"No PDF Generated"}`}else if(_==="write_docx"){let A=O(z.args).path||null;oe=`${A?"\u2714":"\u2718"} Generated: ${A.replaceAll("\\","/")||"No Docx Generated"}`}else if(_==="file_map"){let A=O(z.args).path;oe=`${A?"\u2714":"\u2718"} Indexed: ${A.replaceAll("\\","/")?""+A:"File Not Found"}`}else if(_.toLowerCase()==="search_keyword"||_.toLowerCase()==="todo")oe="";else if(_.toLowerCase()==="generate_image"){let{path:A,outputPath:K,output:ae}=O(z.args);oe=`\u2714 Generated: ${A||K||ae||"generated_image.png"}`}else if(_==="invoke_sync"||_==="InvokeSync"){let A=xs(_,z.args);oe=`\u2714 Called Generalist${A?`: ${A}`:""}`}else if(_==="Invoke"||_==="InvokeAsync"||_==="invoke"){let A=xs(_,z.args);oe=`\u2714 Started Generalist${A?`: ${A}`:""}`}else if(_==="get_progress"||_==="GetProgress"){let A=xs(_,z.args);oe=`\u2714 Checked${A?`: ${A}`:""}`}else if(_==="cancel"){let A=xs(_,z.args);oe=`\u{1F6C7} Cancelled${A?`: ${A}`:""}`}else if(_==="steer"||_==="Steer"){let A=xs(_,z.args);oe=`\u2714 Steered${A?`: ${A}`:""}`}else if(_==="EmergencyRollback"){let{method:A}=O(z.args);oe=A==="forceRevert"?"":"\u2714 Rollback Point Checked"}else if(_==="await"||_==="Await"){let{time:A,timeout:K}=O(z.args),ae=parseFloat(K||A)||0;ae||(ae=120);let ge=Ae=>{if(Ae>=60){let be=Math.floor(Ae/60),ee=Ae%60;return`${be}m${ee>0?` ${ee}s`:""}`}return`${Ae}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(ae)}`}else _==="Answer"||_==="answer"?oe="\u2714 Resolved Sub-Agent Query":_==="exec_command"||_==="ask"?oe="":oe=`Executed: ${z.toolName}`;if(yield*ss(),_==="exec_command"){let{command:A}=O(z.args);if(A&&t.systemSettings&&t.systemSettings.allowExternalAccess===!1){let K=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],ae=Q.resolve(process.cwd()).substring(0,3).toLowerCase(),ge=ee=>{let fe=[],le="",Fe=null;for(let Ze=0;Ze<ee.length;Ze++){let xe=ee[Ze];Fe?(xe===Fe&&(Fe=null),le+=xe):xe==='"'||xe==="'"?(Fe=xe,le+=xe):xe==="&"&&ee[Ze+1]==="&"||xe==="|"&&ee[Ze+1]==="|"?(le.trim()&&(fe.push(le.trim()),le=""),Ze++):xe===";"||xe==="|"||xe==="&"?le.trim()&&(fe.push(le.trim()),le=""):le+=xe}return le.trim()&&fe.push(le.trim()),fe},we=ee=>{let fe=[],le="",Fe=null;for(let Ze=0;Ze<ee.length;Ze++){let xe=ee[Ze];Fe?(xe===Fe&&(Fe=null),le+=xe):xe==='"'||xe==="'"?(Fe=xe,le+=xe):/\s/.test(xe)?le&&(fe.push(le),le=""):le+=xe}return le&&fe.push(le),fe},He=ee=>{let fe=ee.replace(/^['"]|['"]$/g,"").trim();return!fe||process.platform==="win32"&&/^\/[a-zA-Z0-9?]+$/.test(fe)?!1:K.some(le=>{if(le.source==="[a-zA-Z]:[\\\\\\/]"){let Fe=fe.match(/[a-zA-Z]:[\\\/]/i);return Fe&&Fe[0].toLowerCase()!==ae}return le.test(fe)})};if(ge(A).some(ee=>{let fe=we(ee);if(fe.length===0)return!1;let le=fe[0].replace(/^['"]|['"]$/g,"").toLowerCase();if(["echo","printf","write-output"].includes(le)){let Ze=!1;return fe.some(xe=>{let Pe=xe.replace(/^['"]|['"]$/g,"");if(Pe===">"||Pe===">>"||Pe==="<")return Ze=!0,!1;if(Pe.startsWith(">")||Pe.startsWith("<")){let ot=Pe.replace(/^[><]+/,"");return He(ot)}return Ze?(Ze=!1,He(xe)):!1})}return fe.some(Ze=>He(Ze))})){let ee='Access Denied. Prohibited from accessing external directories while "External Workspace Access" is disabled.';t.onExecStart&&t.onExecStart(A||"No Command"),yield{type:"exec_start"},await new Promise(fe=>setTimeout(fe,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${ee}`),await new Promise(fe=>setTimeout(fe,50)),t.onExecEnd&&t.onExecEnd(),Z.push({role:"user",text:`[TOOL RESULT]: ERROR: ${ee}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${ee}`},je++;continue}}t.onExecStart&&t.onExecStart(A||"No Command"),yield{type:"exec_start"}}let bn=O(z.args),is=bn.path||bn.targetPath||null;if(is){let A=t.systemSettings&&t.systemSettings.allowExternalAccess===!1,K=Q.resolve(is),ae=Q.resolve(process.cwd());if(A&&!K.startsWith(ae)){let ge="Access Denied. You are not allowed to access files outside the current workspace.";if(_==="write_file"||_==="update_file"){let He=`\u2718 ${_==="write_file"?"Write Canceled":"Edit Canceled"}: ${bn.path||"..."}`,Ae=115;process.stdout.isTTY&&(Ae=process.stdout.columns-5||120);let be=Math.min(He.length+4,Ae),ee=`${He.padEnd(be-2).substring(0,be-2)}`;yield{type:"visual_feedback",content:gn(`${Be?`
657
657
  `:""}${ee}
658
- `)},Be=!1}Z.push({role:"user",text:`[TOOL RESULT]: ERROR: ${ge}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${ge}`},je++;continue}}if(t.onToolApproval&&(_==="write_file"||_==="update_file"||_==="exec_command")){let z=t.systemSettings||{},ae=z.autoExec,ge=null,we=!1,He=!1,Me=!1;if(_==="exec_command"){let{command:Pe}=I(K.args),ot=(Pe||"").trim(),Ce=(Et,Yt)=>{if(!Yt)return!1;let ln=Yt.split(",").map(Vt=>Vt.trim().toLowerCase()).filter(Boolean),it=Et.toLowerCase();return ln.some(Vt=>it.startsWith(Vt))},ze=Ce(ot,z.alwaysAskCommands),Se=Ce(ot,z.autoApproveCommands);if(He=Ce(ot,z.autoDisallowCommands),ze?we=!0:(Se||z.autoApproveGit&&/^git\s+commit\b/i.test(ot))&&(ge="allow"),!we&&!ge){if(z.networkAccess===!1){let Yt=ot.trim().replace(/\s+/g," ").replace(/^['"]+|['"]+$/g,"").toLowerCase().split(" "),it=Yt[0].split("/").pop().split("\\").pop().replace(/\.exe$/,""),Vt=new Set(["curl","wget","httpie","xh","ssh","scp","sftp","rsync","ftp","lftp","tftp","telnet","nc","netcat","socat","ping","traceroute","tracert","dig","nslookup","host","whois","nmap","docker","podman","kubectl","helm","gcloud","aws","az","terraform","ansible-playbook","nix","nix-env","apt","apt-get","dpkg","yum","dnf","pacman","zypper","brew","apk","choco","scoop","conda","mamba","aria2c","axel","smbclient","lynx","w3m","links","elinks","heroku","netlify","vercel","firebase","supabase","wrangler","flyctl","powershell","pwsh","certutil","bitsadmin","cloudflared","ngrok","tailscale","zerotier","rclone"]),rt=!1;Vt.has(it)&&(rt=!0);let ct=Sn=>Yt.slice(1).some(kn=>Sn.includes(kn)),At=Sn=>{let kn=Yt.findIndex(Mn=>Sn.includes(Mn)),ks=Yt.findIndex(Mn=>["run","exec","test"].includes(Mn));return kn!==-1&&!(ks!==-1&&ks<kn)};it==="git"&&ct(["clone","pull","push","fetch"])&&(rt=!0),it==="go"&&ct(["get","install"])&&(rt=!0),it==="npm"&&At(["install","i","update","add"])&&(rt=!0),it==="yarn"&&At(["add","install","upgrade"])&&(rt=!0),it==="pnpm"&&At(["add","install","update"])&&(rt=!0),it==="bun"&&At(["add","install","update"])&&(rt=!0),it==="deno"&&ct(["install","add"])&&(rt=!0),it==="pip"&&ct(["install","download"])&&(rt=!0),it==="pip3"&&ct(["install","download"])&&(rt=!0),it==="cargo"&&ct(["install","add"])&&(rt=!0),["bash","sh","zsh","fish"].includes(it)&&ct(["-c"])&&(rt=!0),it==="cmd"&&ct(["/c"])&&(rt=!0),rt&&(ge="deny",Me=!0)}!ge&&He&&(ge="deny")}!we&&!ge&&ae&&(ge="allow")}else ae&&(ge="allow");let be=ge,ee="";ge==="deny"&&(Me?ee="network":He?ee="settings":ee="prohibited");let fe=!1,le="",Fe=[],Ze=0,xe=!1;if(!be){if(_==="write_file"||_==="update_file")try{let Ce=I(K.args),{path:ze}=Ce;if(ze){let Se=Q.resolve(process.cwd(),ze),Et=ct=>ct?ct.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,At=>At.toUpperCase()):"",Yt=Et(Se),ln="",it=!1,Vt=await gs(),rt=Et(Vt?.file_focused);if(Vt&&rt===Yt&&Vt.full_content?(ln=Vt.full_content,it=!0):ve.existsSync(Se)&&(ln=ve.readFileSync(Se,"utf8"),it=!0),le=ln,await ft.recordFileChange(Se,ln),it){let ct=ln;if(_==="write_file")ct=Ce.content||Ce.newContent||"";else{let{patchPairs:At,allowMultiple:Sn,error:kn}=_o(Ce);if(kn){let $t=`[TOOL RESULT]: ERROR: ${kn}`;Z.push({role:"user",text:$t}),await It("toolFailure"),t.onToolResult&&t.onToolResult("failure",_),yield{type:"tool_result",content:$t,toolName:_},je++;continue}let ks=Ce.allowMultiple!==void 0?Ce.allowMultiple===!0||String(Ce.allowMultiple).toLowerCase()==="true":Sn;Ze=At.length;let Mn=Mo(ln,At,{allowMultiple:ks});ct=Mn.content,Fe=Mn.results;let mo=Fe.filter($t=>$t.success),vt=Fe.filter($t=>!$t.success);if(mo.length===0){let $t=`[TOOL RESULT]: ERROR: Failed to apply patches to [${Q.basename(Se)}].
658
+ `)},Be=!1}Z.push({role:"user",text:`[TOOL RESULT]: ERROR: ${ge}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${ge}`},je++;continue}}if(t.onToolApproval&&(_==="write_file"||_==="update_file"||_==="exec_command")){let K=t.systemSettings||{},ae=K.autoExec,ge=null,we=!1,He=!1,Ae=!1;if(_==="exec_command"){let{command:Pe}=O(z.args),ot=(Pe||"").trim(),Ce=(Et,Yt)=>{if(!Yt)return!1;let ln=Yt.split(",").map(Vt=>Vt.trim().toLowerCase()).filter(Boolean),it=Et.toLowerCase();return ln.some(Vt=>it.startsWith(Vt))},Ke=Ce(ot,K.alwaysAskCommands),Se=Ce(ot,K.autoApproveCommands);if(He=Ce(ot,K.autoDisallowCommands),Ke?we=!0:(Se||K.autoApproveGit&&/^git\s+commit\b/i.test(ot))&&(ge="allow"),!we&&!ge){if(K.networkAccess===!1){let Yt=ot.trim().replace(/\s+/g," ").replace(/^['"]+|['"]+$/g,"").toLowerCase().split(" "),it=Yt[0].split("/").pop().split("\\").pop().replace(/\.exe$/,""),Vt=new Set(["curl","wget","httpie","xh","ssh","scp","sftp","rsync","ftp","lftp","tftp","telnet","nc","netcat","socat","ping","traceroute","tracert","dig","nslookup","host","whois","nmap","docker","podman","kubectl","helm","gcloud","aws","az","terraform","ansible-playbook","nix","nix-env","apt","apt-get","dpkg","yum","dnf","pacman","zypper","brew","apk","choco","scoop","conda","mamba","aria2c","axel","smbclient","lynx","w3m","links","elinks","heroku","netlify","vercel","firebase","supabase","wrangler","flyctl","powershell","pwsh","certutil","bitsadmin","cloudflared","ngrok","tailscale","zerotier","rclone"]),rt=!1;Vt.has(it)&&(rt=!0);let ct=Sn=>Yt.slice(1).some(kn=>Sn.includes(kn)),At=Sn=>{let kn=Yt.findIndex(Mn=>Sn.includes(Mn)),ks=Yt.findIndex(Mn=>["run","exec","test"].includes(Mn));return kn!==-1&&!(ks!==-1&&ks<kn)};it==="git"&&ct(["clone","pull","push","fetch"])&&(rt=!0),it==="go"&&ct(["get","install"])&&(rt=!0),it==="npm"&&At(["install","i","update","add"])&&(rt=!0),it==="yarn"&&At(["add","install","upgrade"])&&(rt=!0),it==="pnpm"&&At(["add","install","update"])&&(rt=!0),it==="bun"&&At(["add","install","update"])&&(rt=!0),it==="deno"&&ct(["install","add"])&&(rt=!0),it==="pip"&&ct(["install","download"])&&(rt=!0),it==="pip3"&&ct(["install","download"])&&(rt=!0),it==="cargo"&&ct(["install","add"])&&(rt=!0),["bash","sh","zsh","fish"].includes(it)&&ct(["-c"])&&(rt=!0),it==="cmd"&&ct(["/c"])&&(rt=!0),rt&&(ge="deny",Ae=!0)}!ge&&He&&(ge="deny")}!we&&!ge&&ae&&(ge="allow")}else ae&&(ge="allow");let be=ge,ee="";ge==="deny"&&(Ae?ee="network":He?ee="settings":ee="prohibited");let fe=!1,le="",Fe=[],Ze=0,xe=!1;if(!be){if(_==="write_file"||_==="update_file")try{let Ce=O(z.args),{path:Ke}=Ce;if(Ke){let Se=Q.resolve(process.cwd(),Ke),Et=ct=>ct?ct.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,At=>At.toUpperCase()):"",Yt=Et(Se),ln="",it=!1,Vt=await gs(),rt=Et(Vt?.file_focused);if(Vt&&rt===Yt&&Vt.full_content?(ln=Vt.full_content,it=!0):Ie.existsSync(Se)&&(ln=Ie.readFileSync(Se,"utf8"),it=!0),le=ln,await ft.recordFileChange(Se,ln),it){let ct=ln;if(_==="write_file")ct=Ce.content||Ce.newContent||"";else{let{patchPairs:At,allowMultiple:Sn,error:kn}=Ao(Ce);if(kn){let $t=`[TOOL RESULT]: ERROR: ${kn}`;Z.push({role:"user",text:$t}),await It("toolFailure"),t.onToolResult&&t.onToolResult("failure",_),yield{type:"tool_result",content:$t,toolName:_},je++;continue}let ks=Ce.allowMultiple!==void 0?Ce.allowMultiple===!0||String(Ce.allowMultiple).toLowerCase()==="true":Sn;Ze=At.length;let Mn=vo(ln,At,{allowMultiple:ks});ct=Mn.content,Fe=Mn.results;let yo=Fe.filter($t=>$t.success),vt=Fe.filter($t=>!$t.success);if(yo.length===0){let $t=`[TOOL RESULT]: ERROR: Failed to apply patches to [${Q.basename(Se)}].
659
659
  ${vt.map(Hs=>` \u2022 ${Hs.error}`).join(`
660
- `)}`,Ts=`\u2714 Edited: ${Q.basename(Se.replaceAll("\\","/"))}`,js=115;process.stdout.isTTY&&(js=process.stdout.columns-5||120);let Rs=Math.min(Ts.length+4,js),go=`${Ts.padEnd(Rs-2).substring(0,Rs-2)}`;yield{type:"visual_feedback",content:gn(`${Be?`
661
- `:""}${go}`)},Be=!1,Z.push({role:"user",text:$t}),await It("toolFailure"),t.onToolResult&&t.onToolResult("failure",_),yield{type:"tool_result",content:$t,toolName:_},je++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${Q.basename(Se)}`},ji(Se,ln,ct),fe=!0,await new Promise(At=>setTimeout(At,50))}else if(_==="write_file"){let ct=Ce.content||Ce.newContent||"",At=ct.endsWith(`
660
+ `)}`,Ts=`\u2714 Edited: ${Q.basename(Se.replaceAll("\\","/"))}`,js=115;process.stdout.isTTY&&(js=process.stdout.columns-5||120);let Rs=Math.min(Ts.length+4,js),wo=`${Ts.padEnd(Rs-2).substring(0,Rs-2)}`;yield{type:"visual_feedback",content:gn(`${Be?`
661
+ `:""}${wo}`)},Be=!1,Z.push({role:"user",text:$t}),await It("toolFailure"),t.onToolResult&&t.onToolResult("failure",_),yield{type:"tool_result",content:$t,toolName:_},je++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${Q.basename(Se)}`},Yi(Se,ln,ct),fe=!0,await new Promise(At=>setTimeout(At,50))}else if(_==="write_file"){let ct=Ce.content||Ce.newContent||"",At=ct.endsWith(`
662
662
  `)?ct:ct+`
663
- `;ve.existsSync(Se)||(xe=!0,ve.mkdirSync(Q.dirname(Se),{recursive:!0}),ve.writeFileSync(Se,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${Q.basename(Se)}`},ji(Se,"",At),fe=!0,await new Promise(Sn=>setTimeout(Sn,50))}}}catch(Ce){console.error("Simulation/Diff Error:",Ce)}let Pe=null;Wi(Ce=>{Pe=Ce});let ot=t.onToolApproval;if(be=await new Promise(async Ce=>{let ze=setInterval(()=>{Pe&&(Bo.onIDEApproval&&Bo.onIDEApproval(Pe),clearInterval(ze),Ce(Pe))},100);try{let Se=await ot(_,K.args);clearInterval(ze),Ce(Se)}catch{clearInterval(ze),Ce("deny")}}),Wi(null),_==="write_file"||_==="update_file"){let{path:Ce}=I(K.args);if(Ce){let ze=Q.resolve(process.cwd(),Ce);if(ua(ze,be),be==="deny"&&xe&&ve.existsSync(ze))try{ve.unlinkSync(ze)}catch{}}}be==="deny"&&(ee="user")}if(be==="allow"&&fe&&No()){let{path:Pe}=I(K.args),ot=Q.resolve(process.cwd(),Pe),Ce=vt=>vt?Q.resolve(vt).replace(/\\/g,"/").toLowerCase():"",ze=await gs(),Se="";ze&&ze.file_focused&&Ce(ze.file_focused)===Ce(ot)&&ze.full_content&&(Se=ze.full_content),!Se&&ve.existsSync(ot)&&(Se=ve.readFileSync(ot,"utf8"),Se||(await new Promise(vt=>setTimeout(vt,100)),Se=ve.readFileSync(ot,"utf8")));let Et=Se.split(/\r?\n/),Yt=Et.length,ln=Buffer.byteLength(Se,"utf8"),it="";le&&(it=`Old File contents:
663
+ `;Ie.existsSync(Se)||(xe=!0,Ie.mkdirSync(Q.dirname(Se),{recursive:!0}),Ie.writeFileSync(Se,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${Q.basename(Se)}`},Yi(Se,"",At),fe=!0,await new Promise(Sn=>setTimeout(Sn,50))}}}catch(Ce){console.error("Simulation/Diff Error:",Ce)}let Pe=null;Ki(Ce=>{Pe=Ce});let ot=t.onToolApproval;if(be=await new Promise(async Ce=>{let Ke=setInterval(()=>{Pe&&(Wo.onIDEApproval&&Wo.onIDEApproval(Pe),clearInterval(Ke),Ce(Pe))},100);try{let Se=await ot(_,z.args);clearInterval(Ke),Ce(Se)}catch{clearInterval(Ke),Ce("deny")}}),Ki(null),_==="write_file"||_==="update_file"){let{path:Ce}=O(z.args);if(Ce){let Ke=Q.resolve(process.cwd(),Ce);if(wa(Ke,be),be==="deny"&&xe&&Ie.existsSync(Ke))try{Ie.unlinkSync(Ke)}catch{}}}be==="deny"&&(ee="user")}if(be==="allow"&&fe&&Uo()){let{path:Pe}=O(z.args),ot=Q.resolve(process.cwd(),Pe),Ce=vt=>vt?Q.resolve(vt).replace(/\\/g,"/").toLowerCase():"",Ke=await gs(),Se="";Ke&&Ke.file_focused&&Ce(Ke.file_focused)===Ce(ot)&&Ke.full_content&&(Se=Ke.full_content),!Se&&Ie.existsSync(ot)&&(Se=Ie.readFileSync(ot,"utf8"),Se||(await new Promise(vt=>setTimeout(vt,100)),Se=Ie.readFileSync(ot,"utf8")));let Et=Se.split(/\r?\n/),Yt=Et.length,ln=Buffer.byteLength(Se,"utf8"),it="";le&&(it=`Old File contents:
664
664
  ${le.split(/\r?\n/).map(($t,Ts)=>`${Ts+1} | ${$t}`).join(`
665
665
  `)}
666
666
 
@@ -671,16 +671,16 @@ ${le.split(/\r?\n/).map(($t,Ts)=>`${Ts+1} | ${$t}`).join(`
671
671
 
672
672
  ... [${Yt-100} lines truncated for history stability] ...
673
673
 
674
- ${$t}`}let rt="";if(_==="update_file"){let vt=Ao(le,Se,Fe,12,t?.compressToolResults||Bo?.systemSettings?.compressToolResults);rt=`SUCCESS: File [${Pe}] updated via IDE Companion (May have user edits). [${Fe.length}/${Ze}] blocks applied.
674
+ ${$t}`}let rt="";if(_==="update_file"){let vt=Io(le,Se,Fe,12,t?.compressToolResults||Wo?.systemSettings?.compressToolResults);rt=`SUCCESS: File [${Pe}] updated via IDE Companion (May have user edits). [${Fe.length}/${Ze}] blocks applied.
675
675
 
676
676
  ${vt}`}else{let vt=Se.split(/\r?\n/),$t=vt.length,Ts=Buffer.byteLength(Se,"utf8"),js="";le&&(js=`Old File contents:
677
- ${le.split(/\r?\n/).map((Hs,Ua)=>`${Ua+1} | ${Hs}`).join(`
677
+ ${le.split(/\r?\n/).map((Hs,za)=>`${za+1} | ${Hs}`).join(`
678
678
  `)}
679
679
 
680
680
  `);let Rs="";if($t<=100)Rs=vt.join(`
681
- `);else{let go=vt.slice(0,50).join(`
681
+ `);else{let wo=vt.slice(0,50).join(`
682
682
  `),Hs=vt.slice(-50).join(`
683
- `);Rs=`${go}
683
+ `);Rs=`${wo}
684
684
 
685
685
  ... [${$t-100} lines truncated] ...
686
686
 
@@ -689,61 +689,61 @@ ${Hs}`}rt=`SUCCESS: File [${Pe}] saved via IDE Companion (May have user edits).
689
689
  ${js}- Content Preview:
690
690
 
691
691
  ${Rs}`}let At=`${Pe?"\u2714":"\u2718"} ${_==="write_file"?"Created":"Edited"}: ${Pe.replaceAll("\\","/")||"No File Changes"}`,Sn=115;process.stdout.isTTY&&(Sn=process.stdout.columns-5||120);let kn=Math.min(At.length+4,Sn),ks=`${At.padEnd(kn-2).substring(0,kn-2)}`;yield{type:"visual_feedback",content:gn(`${Be?`
692
- `:""}${ks}`)},Be=!1;let Mn=Date.now();q=Mn,yield{type:"tool_time",content:Mn-me};let mo=`[TOOL RESULT]: ${rt}`;Z.push({role:"user",text:mo}),rn=!0,await It("toolSuccess"),t.onToolResult&&t.onToolResult("success",_),yield{type:"tool_result",content:rt,aiContent:mo,toolName:_},je++;continue}if(be==="deny"){let Pe=`Permission Denied: Prohibited ${_==="exec_command"?"Command":"file edit"}.`;if(ee==="user"?Pe="Permission Denied by User":ee==="settings"?Pe="Permission Denied by User Policy":ee==="network"?Pe="Permission Denied: Sandbox Network Access Disabled by User Policy.":ee==="prohibited"&&_==="exec_command"&&(Pe="Permission Denied: Prohibited Command in User Policy"),_==="write_file"||_==="update_file"){let Ce=`\u2718 ${_==="write_file"?"Write Cancelled":"Edit Denied"}: ${I(K.args).path.replaceAll("\\","/")||"..."}`,ze=115;process.stdout.isTTY&&(ze=process.stdout.columns-5||120);let Se=Math.min(Ce.length+4,ze),Et=`${Ce.padEnd(Se-2).substring(0,Se-2)}`,Yt=` ${" ".repeat(Se)} `;yield{type:"visual_feedback",content:gn(`${Be?`
692
+ `:""}${ks}`)},Be=!1;let Mn=Date.now();q=Mn,yield{type:"tool_time",content:Mn-me};let yo=`[TOOL RESULT]: ${rt}`;Z.push({role:"user",text:yo}),rn=!0,await It("toolSuccess"),t.onToolResult&&t.onToolResult("success",_),yield{type:"tool_result",content:rt,aiContent:yo,toolName:_},je++;continue}if(be==="deny"){let Pe=`Permission Denied: Prohibited ${_==="exec_command"?"Command":"file edit"}.`;if(ee==="user"?Pe="Permission Denied by User":ee==="settings"?Pe="Permission Denied by User Policy":ee==="network"?Pe="Permission Denied: Sandbox Network Access Disabled by User Policy.":ee==="prohibited"&&_==="exec_command"&&(Pe="Permission Denied: Prohibited Command in User Policy"),_==="write_file"||_==="update_file"){let Ce=`\u2718 ${_==="write_file"?"Write Cancelled":"Edit Denied"}: ${O(z.args).path.replaceAll("\\","/")||"..."}`,Ke=115;process.stdout.isTTY&&(Ke=process.stdout.columns-5||120);let Se=Math.min(Ce.length+4,Ke),Et=`${Ce.padEnd(Se-2).substring(0,Se-2)}`,Yt=` ${" ".repeat(Se)} `;yield{type:"visual_feedback",content:gn(`${Be?`
693
693
  `:""}${Et}
694
- `)},Be=!1}_==="exec_command"&&(await new Promise(ot=>setTimeout(ot,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${Pe}`),await new Promise(ot=>setTimeout(ot,50)),t.onExecEnd&&t.onExecEnd()),Z.push({role:"user",text:`[TOOL RESULT]: DENIED: ${Pe}`}),yield{type:"tool_result",content:`[TOOL RESULT]: DENIED: ${Pe}`},await It("toolDenied"),t.onToolResult&&t.onToolResult("denied",_),je++;continue}}if(ie){let A=115;process.stdout.isTTY&&(A=process.stdout.columns-5||120);let z=Math.min(ie.length+4,A),ae=`${ie.padEnd(z-2).substring(0,z-2)}`;yield{type:"visual_feedback",content:gn(`${Be?`
695
- `:""}${ae}${ie.includes("\u2714")&&(ie.includes("Created")||ie.includes("Edited"))?"":`
696
- `}`)},Be=!1}if(q>0){let A=Date.now()-q,z=Math.max(0,1e3-A);z>0&&await new Promise(ae=>setTimeout(ae,z))}let Bn={chatId:d,history:n,onChunk:A=>t.onExecChunk?t.onExecChunk(A):null,onAskUser:t.onAskUser,systemSettings:t.systemSettings,mode:r,isMultiModal:fn(_e),onVisualFeedback:t.onVisualFeedback,onSubagentUpdate:t.onSubagentUpdate,onTokenChunk:t.onTokenChunk,modelName:_e,aiProvider:t.aiProvider,apiKey:t.apiKey,onUsage:t.onUsage};if(_==="write_file"||_==="update_file")try{let{path:A}=I(K.args);if(A){let z=Q.resolve(process.cwd(),A),ae=await gs();ae&&ae.file_focused===z&&ae.full_content&&(Bn.forcedContent=ae.full_content)}}catch{}Qt.push(_);let Te=await lo(_,K.args,Bn);if((_==="write_file"||_==="update_file")&&Te.startsWith("SUCCESS")){let{path:A}=I(K.args);if(A){let z=Q.resolve(process.cwd(),A);fa(z)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let jt=Date.now();q=jt,yield{type:"tool_time",content:jt-me},Zt=jt;let zt=null;if(typeof Te=="object"&&Te.binaryPart&&(zt=Te.binaryPart,Te=Te.text),_==="search_keyword"){let{keyword:A,path:z}=I(K.args),ae=typeof Te=="string"&&Te.startsWith("[GLOB]");ae&&(Te=Te.slice(6).trimStart());let ge=typeof Te=="string"&&Te.startsWith("[DIR]");ge&&(Te=Te.slice(5).trimStart());let we=0;if(Te){let Fe=Te.match(/Found (\d+) match/i);Fe&&(we=parseInt(Fe[1]))}let He=z?z.replace(/[\/\\]+$/,""):null,Me=He&&He!=="."?`"${ae?z:ge?`${He}/*`:He}"`:"./",be=`${A?"\u2714":"\u2718"} Searched: "${A||""}" in ${Me.replaceAll("\\","/")} \u2192 ${we} Match${we===1?"":"es"}`,ee=115;process.stdout.isTTY&&(ee=process.stdout.columns-5||120);let fe=Math.min(be.length+4,ee),le=`${be.padEnd(fe-2).substring(0,fe-2)}`;yield{type:"visual_feedback",content:gn(`${Be?`
694
+ `)},Be=!1}_==="exec_command"&&(await new Promise(ot=>setTimeout(ot,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${Pe}`),await new Promise(ot=>setTimeout(ot,50)),t.onExecEnd&&t.onExecEnd()),Z.push({role:"user",text:`[TOOL RESULT]: DENIED: ${Pe}`}),yield{type:"tool_result",content:`[TOOL RESULT]: DENIED: ${Pe}`},await It("toolDenied"),t.onToolResult&&t.onToolResult("denied",_),je++;continue}}if(oe){let A=115;process.stdout.isTTY&&(A=process.stdout.columns-5||120);let K=Math.min(oe.length+4,A),ae=`${oe.padEnd(K-2).substring(0,K-2)}`;yield{type:"visual_feedback",content:gn(`${Be?`
695
+ `:""}${ae}${oe.includes("\u2714")&&(oe.includes("Created")||oe.includes("Edited"))?"":`
696
+ `}`)},Be=!1}if(q>0){let A=Date.now()-q,K=Math.max(0,1e3-A);K>0&&await new Promise(ae=>setTimeout(ae,K))}let Bn={chatId:d,history:n,onChunk:A=>t.onExecChunk?t.onExecChunk(A):null,onAskUser:t.onAskUser,systemSettings:t.systemSettings,mode:r,isMultiModal:fn(Me),onVisualFeedback:t.onVisualFeedback,onSubagentUpdate:t.onSubagentUpdate,onTokenChunk:t.onTokenChunk,modelName:Me,aiProvider:t.aiProvider,apiKey:t.apiKey,onUsage:t.onUsage};if(_==="write_file"||_==="update_file")try{let{path:A}=O(z.args);if(A){let K=Q.resolve(process.cwd(),A),ae=await gs();ae&&ae.file_focused===K&&ae.full_content&&(Bn.forcedContent=ae.full_content)}}catch{}Qt.push(_);let Te=await fo(_,z.args,Bn);if((_==="write_file"||_==="update_file")&&Te.startsWith("SUCCESS")){let{path:A}=O(z.args);if(A){let K=Q.resolve(process.cwd(),A);ya(K)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let jt=Date.now();q=jt,yield{type:"tool_time",content:jt-me},Zt=jt;let Kt=null;if(typeof Te=="object"&&Te.binaryPart&&(Kt=Te.binaryPart,Te=Te.text),_==="search_keyword"){let{keyword:A,path:K}=O(z.args),ae=typeof Te=="string"&&Te.startsWith("[GLOB]");ae&&(Te=Te.slice(6).trimStart());let ge=typeof Te=="string"&&Te.startsWith("[DIR]");ge&&(Te=Te.slice(5).trimStart());let we=0;if(Te){let Fe=Te.match(/Found (\d+) match/i);Fe&&(we=parseInt(Fe[1]))}let He=K?K.replace(/[\/\\]+$/,""):null,Ae=He&&He!=="."?`"${ae?K:ge?`${He}/*`:He}"`:"./",be=`${A?"\u2714":"\u2718"} Searched: "${A||""}" in ${Ae.replaceAll("\\","/")} \u2192 ${we} Match${we===1?"":"es"}`,ee=115;process.stdout.isTTY&&(ee=process.stdout.columns-5||120);let fe=Math.min(be.length+4,ee),le=`${be.padEnd(fe-2).substring(0,fe-2)}`;yield{type:"visual_feedback",content:gn(`${Be?`
697
697
  `:""}${le}
698
- `)},Be=!1}if(_==="EmergencyRollback"){let{method:A}=I(K.args);if(A==="forceRevert"){let z=0;if(Te){let be=Te.match(/Total\s*:\s*(\d+)/i);be&&(z=parseInt(be[1]))}let ge=Te&&Te.startsWith("ERROR:")?"\u2718 Emergency Rollback Failed":`\u2714 Emergency Rollback \u2192 ${z} file${z===1?"":"s"} processed`,we=115;process.stdout.isTTY&&(we=process.stdout.columns-5||120);let He=Math.min(ge.length+4,we),Me=`${ge.padEnd(He-2).substring(0,He-2)}`;yield{type:"visual_feedback",content:gn(`${Be?`
699
- `:""}${Me}
700
- `)},Be=!1}}if(_==="todo"){let{method:A,tasks:z,markDone:ae}=I(K.args),ge="",we=[],He=Me=>{if(!Me)return[];let be=Array.isArray(Me)?Me:[];if(be.length===0&&typeof Me=="string"){let ee=Me.trim();if(ee.startsWith("[")&&ee.endsWith("]")){let fe=ee.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);fe?be=fe.map(le=>le.slice(1,-1).replace(/\\(.)/g,"$1")):be=ee.slice(1,-1).split(",").map(le=>le.trim()).filter(Boolean)}else be=Me.split(`
701
- `)}return be.filter(ee=>String(ee).trim()).map(ee=>{let fe=String(ee).trim();return fe.startsWith("- [")?fe.substring(6).trim():fe})};if(A==="create"?(ge="\x1B[32m\u2192\x1B[0m Created Goals",we=He(z).map(Me=>`\x1B[90m\u25CB\x1B[0m ${Me}`)):A==="append"?(ge="\x1B[34m\u2795\x1B[0m Added New Goals",we=He(z).map(Me=>`\x1B[90m\u25CB\x1B[0m ${Me}`)):A==="get"&&(ge=ae?"\x1B[36m\u21BB\x1B[0m Updated Goals":"\x1B[35m\u2022\x1B[0m Reviewed Goals",we=(Te||"").split(`
698
+ `)},Be=!1}if(_==="EmergencyRollback"){let{method:A}=O(z.args);if(A==="forceRevert"){let K=0;if(Te){let be=Te.match(/Total\s*:\s*(\d+)/i);be&&(K=parseInt(be[1]))}let ge=Te&&Te.startsWith("ERROR:")?"\u2718 Emergency Rollback Failed":`\u2714 Emergency Rollback \u2192 ${K} file${K===1?"":"s"} processed`,we=115;process.stdout.isTTY&&(we=process.stdout.columns-5||120);let He=Math.min(ge.length+4,we),Ae=`${ge.padEnd(He-2).substring(0,He-2)}`;yield{type:"visual_feedback",content:gn(`${Be?`
699
+ `:""}${Ae}
700
+ `)},Be=!1}}if(_==="todo"){let{method:A,tasks:K,markDone:ae}=O(z.args),ge="",we=[],He=Ae=>{if(!Ae)return[];let be=Array.isArray(Ae)?Ae:[];if(be.length===0&&typeof Ae=="string"){let ee=Ae.trim();if(ee.startsWith("[")&&ee.endsWith("]")){let fe=ee.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);fe?be=fe.map(le=>le.slice(1,-1).replace(/\\(.)/g,"$1")):be=ee.slice(1,-1).split(",").map(le=>le.trim()).filter(Boolean)}else be=Ae.split(`
701
+ `)}return be.filter(ee=>String(ee).trim()).map(ee=>{let fe=String(ee).trim();return fe.startsWith("- [")?fe.substring(6).trim():fe})};if(A==="create"?(ge="\x1B[32m\u2192\x1B[0m Created Goals",we=He(K).map(Ae=>`\x1B[90m\u25CB\x1B[0m ${Ae}`)):A==="append"?(ge="\x1B[34m\u2795\x1B[0m Added New Goals",we=He(K).map(Ae=>`\x1B[90m\u25CB\x1B[0m ${Ae}`)):A==="get"&&(ge=ae?"\x1B[36m\u21BB\x1B[0m Updated Goals":"\x1B[35m\u2022\x1B[0m Reviewed Goals",we=(Te||"").split(`
702
702
  `).slice(1).join(`
703
703
  `).split(`
704
- `).filter(be=>be.trim().startsWith("- [")).map(be=>{let ee=be.trim(),fe=ee.startsWith("- [x]");return`${fe?"\x1B[32m\u2714\x1B[0m":"\x1B[90m\u25CB\x1B[0m"} ${fe?"\x1B[90m":"\x1B[37m"}${ee.substring(6).trim()}\x1B[0m`})),ge&&we.length>0){let Me=[`${ge}`,...we.map(be=>` ${be}`)].join(`
704
+ `).filter(be=>be.trim().startsWith("- [")).map(be=>{let ee=be.trim(),fe=ee.startsWith("- [x]");return`${fe?"\x1B[32m\u2714\x1B[0m":"\x1B[90m\u25CB\x1B[0m"} ${fe?"\x1B[90m":"\x1B[37m"}${ee.substring(6).trim()}\x1B[0m`})),ge&&we.length>0){let Ae=[`${ge}`,...we.map(be=>` ${be}`)].join(`
705
705
  `);yield{type:"visual_feedback",content:gn(`${Be?`
706
- `:""}${Me}
706
+ `:""}${Ae}
707
707
  `)},Be=!1}}_==="exec_command"&&t.onExecEnd&&(await new Promise(A=>setTimeout(A,800)),t.onExecEnd());let Cn=Te&&Te.startsWith("DENIED:");Te&&!Te.startsWith("ERROR:")&&!Cn?(await It("toolSuccess"),t.onToolResult&&t.onToolResult("success",_)):Cn||(await It("toolFailure"),t.onToolResult&&t.onToolResult("failure",_));let Ht=(Te||"").toString().replaceAll("[UI_CONTEXT]","");Ht.includes("[[VERIFIED]]")&&(Ht=Ht.replace(/\[\[VERIFIED\]\][\s\S]*?\[\[\/VERIFIED\]\]/g,`[SYSTEM NOTE]: Patch Block matched & applied successfully. Large Block omitted to conserve context.
708
- `));let _n;if(Ht.startsWith("[[SAME]]")){let z=Ht.replace(/^\[\[SAME\]\]\s*\r?\n?/,"").split(/\r?\n/),ae=z.filter(we=>we.startsWith("SUCCESS:")||we.trim().startsWith("- Stats:"));_n=`[TOOL RESULT]: ${ae.length>0?ae.join(`
709
- `):z.slice(0,2).join(`
708
+ `));let _n;if(Ht.startsWith("[[SAME]]")){let K=Ht.replace(/^\[\[SAME\]\]\s*\r?\n?/,"").split(/\r?\n/),ae=K.filter(we=>we.startsWith("SUCCESS:")||we.trim().startsWith("- Stats:"));_n=`[TOOL RESULT]: ${ae.length>0?ae.join(`
709
+ `):K.slice(0,2).join(`
710
710
  `)}
711
- [SYSTEM NOTE]: Content verified and persisted to disk. Full preview omitted to conserve context.`}else _n=`[TOOL RESULT]: ${Ht}`;Z.push({role:"user",text:_n,binaryPart:zt}),rn=!0;let $e=`[TOOL RESULT]: ${Te.replaceAll(`[[VERIFIED]]
711
+ [SYSTEM NOTE]: Content verified and persisted to disk. Full preview omitted to conserve context.`}else _n=`[TOOL RESULT]: ${Ht}`;Z.push({role:"user",text:_n,binaryPart:Kt}),rn=!0;let $e=`[TOOL RESULT]: ${Te.replaceAll(`[[VERIFIED]]
712
712
  `,"").replaceAll(`
713
- [[/VERIFIED]]`,"")||""}`;(_==="view_file"||_==="web_scrape"||_==="file_map")&&($e=`[TOOL RESULT]: ${ie} (Context Locked for UI Clarity)`),yield{type:"tool_result",content:$e,aiContent:_n,binaryPart:zt,toolName:_},_==="memory"&&Te.includes("SUCCESS")&&(yield{type:"memory_updated"}),je++}if(u==="Google"&&xn&&Date.now()-Ko>=150){yield*ss();let K=Us(xn);for(let me of K)yield me;xn="",Ko=Date.now()}}P.usageMetadata&&(Rn=P.usageMetadata),Rn&&(yield{type:"liveTokens",content:Rn.totalTokenCount})}if(ue&&(ue=!1,Wt?qe+="</think>":(ce+="</think>",u==="Google"?xn+="</think>":yield{type:"text",content:"</think>"})),Wt&&qe.length>0){let P=0,te=Math.min(tt.length,qe.length);for(let G=te;G>0;G--)if(tt.endsWith(qe.substring(0,G))){P=G;break}let U=qe.substring(P);if(U){let ke=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(tt)?U.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):U.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(ke)if(ce+=ke,u==="Google")xn+=ke;else{yield*ss();let pe=Us(ke);for(let de of pe)yield de}}Wt=!1,qe=""}if(yield*ss(),Ot)break;let Ws=(ce||"").trim(),La=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(Ws.toLowerCase())||/\[\[END\]\]/i.test(Ws.toLowerCase()),Pa=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(Ws.toLowerCase()),Da=Z.length>0||Bt!==null,zo=Ws.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/gi,"").trim(),Fa=/(\p{Emoji_Presentation}|\p{Extended_Pictographic})$/u.test(zo),Na=/([.!?"'*_`|\]\)”’~~]+|\s|`{3}|[\u200B-\u200D\uFEFF])$/u.test(zo.trim()),Ba=/[.!?}"'`’“”]$|```$/s.test(zo)||Na||Fa;!La&&!Pa&&!Da&&Ws.length>0,Qe=!0,await It("agent",u)}catch(Ee){if(Ot){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
713
+ [[/VERIFIED]]`,"")||""}`;(_==="view_file"||_==="web_scrape"||_==="file_map")&&($e=`[TOOL RESULT]: ${oe} (Context Locked for UI Clarity)`),yield{type:"tool_result",content:$e,aiContent:_n,binaryPart:Kt,toolName:_},_==="memory"&&Te.includes("SUCCESS")&&(yield{type:"memory_updated"}),je++}if(f==="Google"&&xn&&Date.now()-Yo>=150){yield*ss();let z=Us(xn);for(let me of z)yield me;xn="",Yo=Date.now()}}L.usageMetadata&&(Rn=L.usageMetadata),Rn&&(yield{type:"liveTokens",content:Rn.totalTokenCount})}if(ue&&(ue=!1,Wt?qe+="</think>":(ce+="</think>",f==="Google"?xn+="</think>":yield{type:"text",content:"</think>"})),Wt&&qe.length>0){let L=0,te=Math.min(tt.length,qe.length);for(let G=te;G>0;G--)if(tt.endsWith(qe.substring(0,G))){L=G;break}let B=qe.substring(L);if(B){let ke=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(tt)?B.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):B.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(ke)if(ce+=ke,f==="Google")xn+=ke;else{yield*ss();let pe=Us(ke);for(let de of pe)yield de}}Wt=!1,qe=""}if(yield*ss(),Ot)break;let Ws=(ce||"").trim(),Ua=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(Ws.toLowerCase())||/\[\[END\]\]/i.test(Ws.toLowerCase()),Wa=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(Ws.toLowerCase()),ja=Z.length>0||Bt!==null,Vo=Ws.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/gi,"").trim(),Ha=/(\p{Emoji_Presentation}|\p{Extended_Pictographic})$/u.test(Vo),Ga=/([.!?"'*_`|\]\)”’~~]+|\s|`{3}|[\u200B-\u200D\uFEFF])$/u.test(Vo.trim()),qa=/[.!?}"'`’“”]$|```$/s.test(Vo)||Ga||Ha;!Ua&&!Wa&&!ja&&Ws.length>0,Qe=!0,await It("agent",f)}catch(Ee){if(Ot){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
714
714
 
715
- \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(String(Ee).includes("Incomplete JSON segment at the end")){ue&&(ue=!1,Wt?qe+="</think>":(ce+="</think>",yield{type:"text",content:"</think>"})),Qe=!0,await It("agent",u);break}if(ue&&(ue=!1,Wt?qe+="</think>":ce+="</think>"),Wt&&qe.length>0){let ns=0,tn=Math.min(tt.length,qe.length);for(let Pt=tn;Pt>0;Pt--)if(tt.endsWith(qe.substring(0,Pt))){ns=Pt;break}let Lt=qe.substring(ns);if(Lt){let an=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(tt)?Lt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):Lt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");an&&(ce+=an)}Wt=!1,qe=""}let ne=Ee instanceof Error?(()=>{try{return JSON.parse(JSON.parse(Ee.message).error.message).error.message}catch{return String(Ee)}})():String(Ee),nt=new Date().toLocaleString(),_t=Q.join(cn,"agent");ve.existsSync(_t)||ve.mkdirSync(_t,{recursive:!0}),ve.appendFileSync(Q.join(_t,"error.log"),`ERROR [${nt}]: ${ne}
715
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(String(Ee).includes("Incomplete JSON segment at the end")){ue&&(ue=!1,Wt?qe+="</think>":(ce+="</think>",yield{type:"text",content:"</think>"})),Qe=!0,await It("agent",f);break}if(ue&&(ue=!1,Wt?qe+="</think>":ce+="</think>"),Wt&&qe.length>0){let ns=0,tn=Math.min(tt.length,qe.length);for(let Pt=tn;Pt>0;Pt--)if(tt.endsWith(qe.substring(0,Pt))){ns=Pt;break}let Lt=qe.substring(ns);if(Lt){let an=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(tt)?Lt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):Lt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");an&&(ce+=an)}Wt=!1,qe=""}let ne=Ee instanceof Error?(()=>{try{return JSON.parse(JSON.parse(Ee.message).error.message).error.message}catch{return String(Ee)}})():String(Ee),nt=new Date().toLocaleString(),_t=Q.join(cn,"agent");Ie.existsSync(_t)||Ie.mkdirSync(_t,{recursive:!0}),Ie.appendFileSync(Q.join(_t,"error.log"),`ERROR [${nt}]: ${ne}
716
716
 
717
717
  ----------------------------------------------------------------------
718
718
 
719
- `);let en=Ee.status||Ee.statusCode||Ee.code;if(!(en&&(en>=500&&en<600||en===408||en===429)||!en&&(/status[ :]+(5\d\d|408|429)/i.test(String(Ee))||/code[ :]+(5\d\d|408|429)/i.test(String(Ee))||/(500|503|408|429)/.test(String(Ee))))){if(We<yn-3)throw Ee;yield{type:"text",content:ne},yield{type:"status",content:"Error Occured"}}if(ce.trim().length>0||Ve>1)if(Ve<=yn){Ve++;let ns=Math.min(1e3*Math.pow(2,Ve-1),24e3);if(ce.trim().length>0){k.push({role:"agent",text:ce});let tn=`[system]
719
+ `);let en=Ee.status||Ee.statusCode||Ee.code;if(!(en&&(en>=500&&en<600||en===408||en===429)||!en&&(/status[ :]+(5\d\d|408|429)/i.test(String(Ee))||/code[ :]+(5\d\d|408|429)/i.test(String(Ee))||/(500|503|408|429)/.test(String(Ee))))){if(We<yn-3)throw Ee;yield{type:"text",content:ne},yield{type:"status",content:"Error Occured"}}if(ce.trim().length>0||Ve>1)if(Ve<=yn){Ve++;let ns=Math.min(1e3*Math.pow(2,Ve-1),24e3);if(ce.trim().length>0){b.push({role:"agent",text:ce});let tn=`[system]
720
720
  - seamless continuation: resume immediately. pick up from last words with zero gap/disruption
721
721
  - no repetition: do not repeat any text already written
722
722
  - no re-think: do not restart or open <think> if reasoning already started. continue the thinking and close thinking block </think> before chat output
723
723
  - mid-tool safety: if cutoff was mid-tool call, restart that tool call from start
724
- - stealth: do not mention/apologize for cutoff [/system]`;Z.length>0?Z.forEach((Lt,Pt)=>{Pt===Z.length-1?k.push({...Lt,text:`${Lt.text}
724
+ - stealth: do not mention/apologize for cutoff [/system]`;Z.length>0?Z.forEach((Lt,Pt)=>{Pt===Z.length-1?b.push({...Lt,text:`${Lt.text}
725
725
 
726
- ${tn}`}):k.push(Lt)}):k.push({role:"user",text:tn}),tt+=ce}for(let tn=ns/1e3;tn>0&&!Ot;tn--)yield{type:"status",content:`Error Occured. Recovering Stream (${Ve}/${yn}) [Retrying in ${tn.toFixed(0)}s]...`},await new Promise(Lt=>setTimeout(Lt,1e3));yield{type:"status",content:"Error Occured. Recovering Stream..."}}else throw new Error(`Stream collapsed too many times. (Failed to resolve ${yn} times)
726
+ ${tn}`}):b.push(Lt)}):b.push({role:"user",text:tn}),tt+=ce}for(let tn=ns/1e3;tn>0&&!Ot;tn--)yield{type:"status",content:`Error Occured. Recovering Stream (${Ve}/${yn}) [Retrying in ${tn.toFixed(0)}s]...`},await new Promise(Lt=>setTimeout(Lt,1e3));yield{type:"status",content:"Error Occured. Recovering Stream..."}}else throw new Error(`Stream collapsed too many times. (Failed to resolve ${yn} times)
727
727
  Error log can be found in \`/export logs\``);else if(We<=yn){We++,Ve=1,tt="";let ns=Math.min(1e3*Math.pow(2,We-1),32e3),tn=.8+Math.random()*.4,Lt=Math.round(ns*tn);Qn=!0,yield{type:"status",content:`Trying to reach ${e} (${We}/${yn}) [Retrying in ${(Lt/1e3).toFixed(0)}s]`};for(let Pt=Lt/1e3;Pt>0&&!Ot;Pt--)yield{type:"status",content:`Trying to reach ${e} (${We}/${yn}) [Retrying in ${Pt.toFixed(0)}s]`},await new Promise(an=>setTimeout(an,1e3));yield{type:"status",content:`Trying to reach ${e}`}}else throw new Error(`Model ${e} cannot be reached. (Failed ${yn} times)
728
- Error log can be found in \`/export logs\``)}}if(Rn){let ue=Rn.totalTokenCount||0,Ee=Rn.cachedContentTokenCount||0,ne=(Rn.candidatesTokenCount||0)+(Rn.thoughtsTokenCount||0);await Gt("tokens",ue,u,_e),Ee>0&&await Gt("cachedTokens",Ee,u,_e),ne>0&&await Gt("candidateTokens",ne,u,_e),yield{type:"usage",content:Rn}}ar.push(ce);let Fn=ce;ce.match(/(?:<think>|\[think\])([\s\S]*?)(?:<\/think>|\[\/think\])/i)&&(Fn=ce.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/i,""));let es=ka(ce),$n=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(es.toLowerCase())||/\[\[END\]\]/i.test(es.toLowerCase())||!0,Ec=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(es.toLowerCase()),$c=je>0;yield{type:"status",content:"Thinking"};let va=wc(ce,/(\[\s*(turn\s*:)?\s*(continue|finish)\s*\]|\[\[END\]\])/gi,"").trim(),ts=($n||Z.length===0)&&!Ut&&!wn&&!En;if(ts=Z.length===0?ts:!1,ts=Zn||ho?!1:ts,ce&&ce.trim().endsWith('")]')&&Z.length===0&&(ts=!1),ts){let ue=ar.join(`
729
- `),Ee=ue.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").trim();yield{type:"interactive_turn_finished",data:{agentText:T,fullAgentTextRaw:ue,history:[...k],needTitle:b}},k.length>0&&k[k.length-1].role==="agent"?k[k.length-1].text=Ee:k.push({role:"agent",text:Ee}),k.forEach(ne=>{if(ne.role==="user"&&ne.text&&(ne.text=ne.text.replace(/\n\[COMPILE ERROR\][\s\S]*?\[\/ERROR\]/g,""),ne.text=ne.text.replaceAll(`
728
+ Error log can be found in \`/export logs\``)}}if(Rn){let ue=Rn.totalTokenCount||0,Ee=Rn.cachedContentTokenCount||0,ne=(Rn.candidatesTokenCount||0)+(Rn.thoughtsTokenCount||0);await Gt("tokens",ue,f,Me),Ee>0&&await Gt("cachedTokens",Ee,f,Me),ne>0&&await Gt("candidateTokens",ne,f,Me),yield{type:"usage",content:Rn}}hr.push(ce);let Fn=ce;ce.match(/(?:<think>|\[think\])([\s\S]*?)(?:<\/think>|\[\/think\])/i)&&(Fn=ce.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/i,""));let es=_a(ce),$n=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(es.toLowerCase())||/\[\[END\]\]/i.test(es.toLowerCase())||!0,Ic=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(es.toLowerCase()),Oc=je>0;yield{type:"status",content:"Thinking"};let Fa=Ec(ce,/(\[\s*(turn\s*:)?\s*(continue|finish)\s*\]|\[\[END\]\])/gi,"").trim(),ts=($n||Z.length===0)&&!Ut&&!wn&&!En;if(ts=Z.length===0?ts:!1,ts=Zn||mo?!1:ts,ce&&ce.trim().endsWith('")]')&&Z.length===0&&(ts=!1),ts){let ue=hr.join(`
729
+ `),Ee=ue.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").trim();yield{type:"interactive_turn_finished",data:{agentText:T,fullAgentTextRaw:ue,history:[...b],needTitle:k}},b.length>0&&b[b.length-1].role==="agent"?b[b.length-1].text=Ee:b.push({role:"agent",text:Ee}),b.forEach(ne=>{if(ne.role==="user"&&ne.text&&(ne.text=ne.text.replace(/\n\[COMPILE ERROR\][\s\S]*?\[\/ERROR\]/g,""),ne.text=ne.text.replaceAll(`
730
730
 
731
731
  [system] user question. resolve this specific query within '[ANSWER] ... [/ANSWER]' concisely, naturally [/system]
732
732
  `,"").replaceAll(`[system] user question. resolve this specific query within '[ANSWER] ... [/ANSWER]' concisely, naturally
733
733
  **strictly follow thinking policy as high priority. do not start a response without <think>...</think>** [/system]
734
734
  `,"").replaceAll(`[system] **strictly follow thinking policy as high priority. do not start a response without <think>...</think>** [/system]
735
- `,"").replaceAll(/\n\[system\] WARNING, Turn Limit Impending: Step \d+\/\d+\. Wrap up quickly\/prompt user to continue & use \[\[END\]\] quickly\. \[\/system\]/g,""),ne.text=ne.text.replaceAll(/\n\[system\] File Changes:\n(?:\* .+ \(created|modified|deleted\)\n)*\[\/system\]/g,""),(u==="Mistral"||u==="Google"&&e?.toLowerCase().startsWith("gemma"))&&ne.text.startsWith("[TOOL RESULT]"))){let _t=`
735
+ `,"").replaceAll(/\n\[system\] WARNING, Turn Limit Impending: Step \d+\/\d+\. Wrap up quickly\/prompt user to continue & use \[\[END\]\] quickly\. \[\/system\]/g,""),ne.text=ne.text.replaceAll(/\n\[system\] File Changes:\n(?:\* .+ \(created|modified|deleted\)\n)*\[\/system\]/g,""),(f==="Mistral"||f==="Google"&&e?.toLowerCase().startsWith("gemma"))&&ne.text.startsWith("[TOOL RESULT]"))){let _t=`
736
736
  [system] Tool result received. Analyze output and proceed with your turn [/system]`,en=`
737
- [system] Tool result received. Analyze output and proceed with your turn. **strictly follow thinking policy. do not start a response without <think>...</think>** [/system]`;ne.text=ne.text.replaceAll(en,"").replaceAll(_t,"").trim()}}),yield{type:"status",content:"[end]"}}if(ts)break;let Ia=va.trim()||"*Working...*";if(k.push({role:"agent",text:Ia}),Z.length>0||rn){if(Z.length>0){let ue=Z.map(_t=>_t.text).join(`
737
+ [system] Tool result received. Analyze output and proceed with your turn. **strictly follow thinking policy. do not start a response without <think>...</think>** [/system]`;ne.text=ne.text.replaceAll(en,"").replaceAll(_t,"").trim()}}),yield{type:"status",content:"[end]"}}if(ts)break;let Na=Fa.trim()||"*Working...*";if(b.push({role:"agent",text:Na}),Z.length>0||rn){if(Z.length>0){let ue=Z.map(_t=>_t.text).join(`
738
738
 
739
739
  `),ne=(ce.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/gi,"").match(/\[tool:functions/g)||[]).length;if(Z.length<ne){ue+=`
740
740
 
741
- [SYSTEM] Only ${Z.length} out of ${ne} attempted tool calls were executed. Verify proper schema compliance & try failed calls again [/SYSTEM]`;let _t=ne-Z.length;for(let en=0;en<_t;en++)await It("toolFailure")}let nt=Z.find(_t=>_t.binaryPart)?.binaryPart||null;k.push({role:"user",text:ue,binaryPart:nt})}}else ho||Zn?(k.push({role:"user",text:"[SYSTEM] Failed to execute some tools. Verify proper schema compliance & try again [/SYSTEM]"}),await It("toolFailure")):k.push({role:"user",text:`[SYSTEM] ${wn&&!Ut?"STUTTERING DETECTED by Internal System. Re-calibrate your response & proceed.":`${Ut?" OVER THINKING":" LOOP"} DETECTED by Internal System${Ut?" for current EFFORT_LEVEL":""}. ${Ut?"If you have planned the task, prioritize execution/output":"If you have finished your task provide a simple summary and end"}`} [/SYSTEM]`}),Ut=!1,wn=!1,En=!1;l?.advanceRollback&&await Kn.recordTurnDelta(d,H+1,Qt),ho=je>0||rn}}catch(C){let O=(C instanceof Error?(()=>{try{return JSON.parse(JSON.parse(C.message).error.message).error.message}catch{return C.message||String(C)}})():String(C)).replace(/^(Error:\s*)+/i,""),v=new Date().toLocaleString(),L=Q.join(cn,"agent");yield{type:"text",content:`\u2726 CRITICAL ERROR: ${O.includes("fetch failed")?"Failed to Connect. Check your Internet Connection or Wait a moment":O}
742
- \u2800`},ve.existsSync(L)||ve.mkdirSync(L,{recursive:!0}),ve.appendFileSync(Q.join(L,"error.log"),`CRITICAL ERROR [${v}]: ${C}
741
+ [SYSTEM] Only ${Z.length} out of ${ne} attempted tool calls were executed. Verify proper schema compliance & try failed calls again [/SYSTEM]`;let _t=ne-Z.length;for(let en=0;en<_t;en++)await It("toolFailure")}let nt=Z.find(_t=>_t.binaryPart)?.binaryPart||null;b.push({role:"user",text:ue,binaryPart:nt})}}else mo||Zn?(b.push({role:"user",text:"[SYSTEM] Failed to execute some tools. Verify proper schema compliance & try again [/SYSTEM]"}),await It("toolFailure")):b.push({role:"user",text:`[SYSTEM] ${wn&&!Ut?"STUTTERING DETECTED by Internal System. Re-calibrate your response & proceed.":`${Ut?" OVER THINKING":" LOOP"} DETECTED by Internal System${Ut?" for current EFFORT_LEVEL":""}. ${Ut?"If you have planned the task, prioritize execution/output":"If you have finished your task provide a simple summary and end"}`} [/SYSTEM]`}),Ut=!1,wn=!1,En=!1;l?.advanceRollback&&await zn.recordTurnDelta(d,H+1,Qt),mo=je>0||rn}}catch(C){let v=(C instanceof Error?(()=>{try{return JSON.parse(JSON.parse(C.message).error.message).error.message}catch{return C.message||String(C)}})():String(C)).replace(/^(Error:\s*)+/i,""),I=new Date().toLocaleString(),D=Q.join(cn,"agent");yield{type:"text",content:`\u2726 CRITICAL ERROR: ${v.includes("fetch failed")?"Failed to Connect. Check your Internet Connection or Wait a moment":v}
742
+ \u2800`},Ie.existsSync(D)||Ie.mkdirSync(D,{recursive:!0}),Ie.appendFileSync(Q.join(D,"error.log"),`CRITICAL ERROR [${I}]: ${C}
743
743
 
744
744
  ----------------------------------------------------------------------
745
745
 
746
- `),typeof flushGoogleBuffer=="function"&&(yield*flushGoogleBuffer()),yield{type:"tool_result",content:`ERROR: [INTERNAL CRITICAL] ${O}`}}finally{$&&(clearInterval($),$=null),typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),await ft.commitTransaction(),l?.advanceRollback&&await Kn.cleanup(d),await gs()}yield{type:"status",content:null}},gm=async(e,n,t=null,o=null,s=50,i=null,a=!1)=>{let r=await Ft(),h={...r,...n},d=process.env.SUBAGENT_MODEL?process.env.SUBAGENT_MODEL.trim():null,c=process.env.SUBAGENT_PROVIDER?process.env.SUBAGENT_PROVIDER.trim():null,l=new Date,f=`${l.getFullYear()}-${l.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(l.getDate()).padStart(2,"0")}, ${l.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}).replace(":","-")}`,p=(C=>{if(!C)return null;let k=C.toLowerCase();return k==="google"?"Google":k==="deepseek"?"DeepSeek":k==="openrouter"?"OpenRouter":k==="nvidia"?"NVIDIA":k==="mistral"?"Mistral":k==="ollama"?"Ollama":null})(c),g=h?.systemSettings?.CustomSubAgent?h?.systemSettings?.SubAgentModel:null,y=h?.systemSettings?.CustomSubAgent?h?.systemSettings?.SubAgentProvider:null,m=null;if(g==="ENV"?(m=d,d&&p&&(h.aiProvider=p)):g&&g!=="Default"?(m=g,y&&(h.aiProvider=y)):d&&p&&(h.aiProvider=p),h.aiProvider){let C=await Xo(h.aiProvider);C&&(h.apiKey=C)}let w=C=>{if(!C||typeof C!="string")return{allowed:!0};let k=[/rm\s+-[rf]{1,2}\s+[\/*.]/i,/rmdir\s+\/[sq]/i,/del\s+\/[fsq]/i,/\bformat\b\s+[a-z]:/i,/mkfs/i,/dd\s+if=/i,/\b(shutdown|reboot|poweroff|init\s+0|init\s+6)\b/i,/chmod\s+(-R\s+)?777\s+[\/*.]/i,/chown\s+(-R\s+)?root/i,/git\s+push\s+.*--force/i,/git\s+clean\s+-fdx/i,/\bsudo\s+su\b/i,/\bsu\s+-\b/i];for(let O of k)if(O.test(C))return{allowed:!1,reason:`Blocked potentially destructive or unsafe command pattern: "${O.source}"`};return{allowed:!0}},x=t||m||n?.modelName||n?.activeModel||r.activeModel,S=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",R=`-- TOOL DEFINITIONS (path = relative to CWD, path separator: '/') --
746
+ `),typeof flushGoogleBuffer=="function"&&(yield*flushGoogleBuffer()),yield{type:"tool_result",content:`ERROR: [INTERNAL CRITICAL] ${v}`}}finally{$&&(clearInterval($),$=null),typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),await ft.commitTransaction(),l?.advanceRollback&&await zn.cleanup(d),await gs()}yield{type:"status",content:null}},$m=async(e,n,t=null,o=null,s=50,i=null,a=!1)=>{let r=await Ft(),h={...r,...n},d=process.env.SUBAGENT_MODEL?process.env.SUBAGENT_MODEL.trim():null,c=process.env.SUBAGENT_PROVIDER?process.env.SUBAGENT_PROVIDER.trim():null,l=new Date,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=(C=>{if(!C)return null;let b=C.toLowerCase();return b==="google"?"Google":b==="deepseek"?"DeepSeek":b==="openrouter"?"OpenRouter":b==="nvidia"?"NVIDIA":b==="mistral"?"Mistral":b==="ollama"?"Ollama":null})(c),g=h?.systemSettings?.CustomSubAgent?h?.systemSettings?.SubAgentModel:null,y=h?.systemSettings?.CustomSubAgent?h?.systemSettings?.SubAgentProvider:null,m=null;if(g==="ENV"?(m=d,d&&p&&(h.aiProvider=p)):g&&g!=="Default"?(m=g,y&&(h.aiProvider=y)):d&&p&&(h.aiProvider=p),h.aiProvider){let C=await Zo(h.aiProvider);C&&(h.apiKey=C)}let w=C=>{if(!C||typeof C!="string")return{allowed:!0};let b=[/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 v of b)if(v.test(C))return{allowed:!1,reason:`Blocked potentially destructive or unsafe command pattern: "${v.source}"`};return{allowed:!0}},x=t||m||n?.modelName||n?.activeModel||r.activeModel,S=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",R=`-- TOOL DEFINITIONS (path = relative to CWD, path separator: '/') --
747
747
  To use tools, must output exactly '[tool:functions.ToolName(arg1="value1")]' structured string in chat response \u2190 no exception
748
748
  Tool Rules:
749
749
  - JSON escape literal escape sequences in tool arguments
@@ -783,31 +783,31 @@ Keep main focus on tools and task, not chatting
783
783
  On task completion, provide a detailed structured summary preferebly in Tables/Bullet Points with file modified info, if any task failed report back in detail, NO HALLUCINATIONS
784
784
 
785
785
  CWD: ${process.cwd()}
786
- Current Time: ${f}
787
- === END SYSTEM PROMPT ===`,b=[{role:"user",text:`Complete this task: ${e}`}],T=0,$="";for(;T<s;){if(Ot){if(n?.taskId&&typeof Ye<"u"){let B=Ye.find(W=>W.id===n.taskId);B&&(B.status="cancelled")}throw i&&i("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}if(n?.taskId&&typeof Ye<"u"){let B=Ye.find(W=>W.id===n.taskId);if(B&&B.status==="cancelled")throw i&&i("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}let C=b.map(B=>({role:B.role==="user"?"user":"model",parts:[{text:B.text}]}));i&&i(`[Subagent Turn ${T+1}]...`);let v=((await Uo(h,x,C,E,"Fast")).text||"").replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/gi,"").trim();$=v,i&&i(`[Subagent Response]
788
- ${v}
789
- `),b.push({role:"agent",text:v});let L=jo(v);if(L.length===0)break;let N=L.filter(B=>B.toolName.toLowerCase()==="askmain"||B.toolName.toLowerCase()==="ask_main"),j=!1,V="";for(let B of L){if(Ot){if(n?.taskId&&typeof Ye<"u"){let M=Ye.find(F=>F.id===n.taskId);M&&(M.status="cancelled")}throw new Error("Subagent task was cancelled.")}if(n?.taskId&&typeof Ye<"u"){let M=Ye.find(F=>F.id===n.taskId);if(M&&M.status==="cancelled")throw new Error("Subagent task was cancelled.")}let W=B.toolName.toLowerCase();if(W==="askmain"||W==="ask_main"){if(j)continue;j=!0;let M="";if(N.length===1?M=I(N[0].args).question||N[0].args:M=N.map((F,Y)=>{let J=I(F.args);return`Q${Y+1}: ${J.question||F.args}`}).join(`
786
+ Current Time: ${u}
787
+ === END SYSTEM PROMPT ===`,k=[{role:"user",text:`Complete this task: ${e}`}],T=0,$="";for(;T<s;){if(Ot){if(n?.taskId&&typeof Ye<"u"){let N=Ye.find(W=>W.id===n.taskId);N&&(N.status="cancelled")}throw i&&i("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}if(n?.taskId&&typeof Ye<"u"){let N=Ye.find(W=>W.id===n.taskId);if(N&&N.status==="cancelled")throw i&&i("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}let C=k.map(N=>({role:N.role==="user"?"user":"model",parts:[{text:N.text}]}));i&&i(`[Subagent Turn ${T+1}]...`);let I=((await jo(h,x,C,E,"Fast")).text||"").replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/gi,"").trim();$=I,i&&i(`[Subagent Response]
788
+ ${I}
789
+ `),k.push({role:"agent",text:I});let D=Go(I);if(D.length===0)break;let j=D.filter(N=>N.toolName.toLowerCase()==="askmain"||N.toolName.toLowerCase()==="ask_main"),U=!1,Y="";for(let N of D){if(Ot){if(n?.taskId&&typeof Ye<"u"){let M=Ye.find(F=>F.id===n.taskId);M&&(M.status="cancelled")}throw new Error("Subagent task was cancelled.")}if(n?.taskId&&typeof Ye<"u"){let M=Ye.find(F=>F.id===n.taskId);if(M&&M.status==="cancelled")throw new Error("Subagent task was cancelled.")}let W=N.toolName.toLowerCase();if(W==="askmain"||W==="ask_main"){if(U)continue;U=!0;let M="";if(j.length===1?M=O(j[0].args).question||j[0].args:M=j.map((F,V)=>{let J=O(F.args);return`Q${V+1}: ${J.question||F.args}`}).join(`
790
790
  `),n.onAskMain){i&&i(`[Executing Tool] AskMain("${M}")...`);let F=await n.onAskMain(M);i&&i(`[Tool Result]
791
791
  Answer from Main Agent: ${F}
792
- `),V+=`[TOOL RESULT for AskMain]: Answer from Main Agent: ${F}
792
+ `),Y+=`[TOOL RESULT for AskMain]: Answer from Main Agent: ${F}
793
793
 
794
- `,await It("toolSuccess")}else V+=`[TOOL RESULT for AskMain]: ERROR: Main agent communication channel not available.
794
+ `,await It("toolSuccess")}else Y+=`[TOOL RESULT for AskMain]: ERROR: Main agent communication channel not available.
795
795
 
796
- `;continue}if(!(o?o.some(M=>M.toLowerCase()===W):!0)){let M=`ERROR: Tool [${B.toolName}] is not in the allowed tools list for this subagent.`;i&&i(`[Blocked Tool Call] ${B.toolName} - not allowed
797
- `),V+=`${M}
796
+ `;continue}if(!(o?o.some(M=>M.toLowerCase()===W):!0)){let M=`ERROR: Tool [${N.toolName}] is not in the allowed tools list for this subagent.`;i&&i(`[Blocked Tool Call] ${N.toolName} - not allowed
797
+ `),Y+=`${M}
798
798
 
799
- `;continue}if(W==="exec_command"||W==="execcommand"||W==="run"){let M=I(B.args).command||"",F=w(M);if(!F.allowed){let Y=`ERROR: [SECURITY RESTRICTION] Subagent execution blocked command: ${F.reason}`;i&&i(`[Blocked Command] ${M} - ${F.reason}
800
- `),V+=`${Y}
799
+ `;continue}if(W==="exec_command"||W==="execcommand"||W==="run"){let M=O(N.args).command||"",F=w(M);if(!F.allowed){let V=`ERROR: [SECURITY RESTRICTION] Subagent execution blocked command: ${F.reason}`;i&&i(`[Blocked Command] ${M} - ${F.reason}
800
+ `),Y+=`${V}
801
801
 
802
- `;continue}}let Re="";if(W==="web_search"||W==="websearch")Re=`\u2714 \x1B[95mSearched\x1B[0m: ${I(B.args).query||""}`;else if(W==="web_scrape"||W==="webscrape")Re=`\u2714 \x1B[95mScraped\x1B[0m: ${I(B.args).url||""}`;else if(W==="search_keyword"||W==="searchkeyword"||W==="codesearch"||W==="code_search"){let M=I(B.args),F=M.keyword||"",Y=M.path||"";Re=`${F?"\u2714":"\u2718"} \x1B[95mSearched\x1B[0m: ${F||"No Query"}${Y?` \u2192 ${Y.replaceAll("\\","/")}`:""}`}else if(W==="view_file"||W==="viewfile"||W==="readfile")Re=`\u2714 \x1B[95mRead\x1B[0m: ${(I(B.args).path||"").replaceAll("\\","/")}`;else if(W==="list_files"||W==="read_folder"||W==="readfolder"){let M=I(B.args).path||null,F=I(B.args).recurse||0;Re=`${M?"\u2714":"\u2718"} \x1B[95mBrowsed\x1B[0m: ${M?`${M.replaceAll("\\","/")}${F>0?`${M.endsWith("/")?`*${F}`:`/*${F}`}`:`${M.endsWith("/")?"":"/"}`}`:""}`}else if(W==="write_file"||W==="writefile"){let M=I(B.args).path||null;Re=`${M?"\u2714":"\u2718"} \x1B[95mCreated\x1B[0m: ${M?`${M.replaceAll("\\","/")}`:"No File Changes"}`}else if(W==="update_file"||W==="updatefile"||W==="patchfile"||W==="patch_file"||W==="patchfile"||W==="updatefile"){let M=I(B.args).path||null,F=I(B.args).content||null;Re=`${M?"\u2714":"\u2718"} \x1B[95mEdited\x1B[0m: ${M?`${M.replaceAll("\\","/")}`:"No File Changes"}`}else if(W==="exec_command"||W==="execcommand"||W==="run"){let M=I(B.args).command||null;Re=`${M?"\u2714":"\u2718"} \x1B[95mExecuted\x1B[0m: ${M?M.slice(0,100)+(M.length>100?"...":""):"No Command"}`}else if(W==="file_map"||W==="filemap"){let M=I(B.args).path||"";Re=`${M?"\u2714":"\u2718"} \x1B[95mIndexed\x1B[0m: ${M?`${M.replaceAll("\\","/")}`:"File Not Found"}`}else if(W==="await"){let{time:M}=I(B.args),F=parseFloat(M)||0;F<10&&(F=10),F>180&&(F=180),Re=`\u2714 \x1B[95mAwaiting\x1B[0m \u2192 ${(J=>{if(J>=60){let Ne=Math.floor(J/60),De=J%60;return`${Ne}m${De>0?` ${De}s`:""}`}return`${J}s`})(F)}`}else{let M=Ki[W]||B.toolName,F=xs(W,B.args);Re=`\u2714 \x1B[95m${M}\x1B[0m${F?`: ${F}`:""}`}n.onVisualFeedback&&Re&&n.onVisualFeedback(Re),i&&i(`[Executing Tool] ${B.toolName}(${B.args})...`);try{let M=await lo(B.toolName,B.args,{...n,mode:"Flux"});if(i&&i(`[Tool Result]
802
+ `;continue}}let Re="";if(W==="web_search"||W==="websearch")Re=`\u2714 \x1B[95mSearched\x1B[0m: ${O(N.args).query||""}`;else if(W==="web_scrape"||W==="webscrape")Re=`\u2714 \x1B[95mScraped\x1B[0m: ${O(N.args).url||""}`;else if(W==="search_keyword"||W==="searchkeyword"||W==="codesearch"||W==="code_search"){let M=O(N.args),F=M.keyword||"",V=M.path||"";Re=`${F?"\u2714":"\u2718"} \x1B[95mSearched\x1B[0m: ${F||"No Query"}${V?` \u2192 ${V.replaceAll("\\","/")}`:""}`}else if(W==="view_file"||W==="viewfile"||W==="readfile")Re=`\u2714 \x1B[95mRead\x1B[0m: ${(O(N.args).path||"").replaceAll("\\","/")}`;else if(W==="list_files"||W==="read_folder"||W==="readfolder"){let M=O(N.args).path||null,F=O(N.args).recurse||0;Re=`${M?"\u2714":"\u2718"} \x1B[95mBrowsed\x1B[0m: ${M?`${M.replaceAll("\\","/")}${F>0?`${M.endsWith("/")?`*${F}`:`/*${F}`}`:`${M.endsWith("/")?"":"/"}`}`:""}`}else if(W==="write_file"||W==="writefile"){let M=O(N.args).path||null;Re=`${M?"\u2714":"\u2718"} \x1B[95mCreated\x1B[0m: ${M?`${M.replaceAll("\\","/")}`:"No File Changes"}`}else if(W==="update_file"||W==="updatefile"||W==="patchfile"||W==="patch_file"||W==="patchfile"||W==="updatefile"){let M=O(N.args).path||null,F=O(N.args).content||null;Re=`${M?"\u2714":"\u2718"} \x1B[95mEdited\x1B[0m: ${M?`${M.replaceAll("\\","/")}`:"No File Changes"}`}else if(W==="exec_command"||W==="execcommand"||W==="run"){let M=O(N.args).command||null;Re=`${M?"\u2714":"\u2718"} \x1B[95mExecuted\x1B[0m: ${M?M.slice(0,100)+(M.length>100?"...":""):"No Command"}`}else if(W==="file_map"||W==="filemap"){let M=O(N.args).path||"";Re=`${M?"\u2714":"\u2718"} \x1B[95mIndexed\x1B[0m: ${M?`${M.replaceAll("\\","/")}`:"File Not Found"}`}else if(W==="await"){let{time:M}=O(N.args),F=parseFloat(M)||0;F<10&&(F=10),F>180&&(F=180),Re=`\u2714 \x1B[95mAwaiting\x1B[0m \u2192 ${(J=>{if(J>=60){let Ne=Math.floor(J/60),De=J%60;return`${Ne}m${De>0?` ${De}s`:""}`}return`${J}s`})(F)}`}else{let M=Qi[W]||N.toolName,F=xs(W,N.args);Re=`\u2714 \x1B[95m${M}\x1B[0m${F?`: ${F}`:""}`}n.onVisualFeedback&&Re&&n.onVisualFeedback(Re),i&&i(`[Executing Tool] ${N.toolName}(${N.args})...`);try{let M=await fo(N.toolName,N.args,{...n,mode:"Flux"});if(i&&i(`[Tool Result]
803
803
  ${M}
804
- `),V+=`[TOOL RESULT for ${B.toolName}]: ${M}
804
+ `),Y+=`[TOOL RESULT for ${N.toolName}]: ${M}
805
805
 
806
806
  `,await It("toolSuccess"),W==="patchfile"||W==="update_file"||W==="updatefile"||W==="patch_file"){if(M){let F=M.split(`
807
- `),Y=0,J=0,Ne=!1;for(let De of F){if(De.includes("[DIFF_START]")){Ne=!0;continue}if(De.includes("[DIFF_END]")){Ne=!1;continue}Ne&&(/^\+\d+/.test(De)?Y++:/^\-\d+/.test(De)&&J++)}(Y>0||J>0)&&(await Gt("linesAdded",Y),await Gt("linesRemoved",J))}}else if((W==="writefile"||W==="write_file")&&M){let F=M.match(/- Stats: \[(\d+) lines/),Y=F?parseInt(F[1]):0,J=0;if(M.includes("Old File contents:")){let Ne=!1;for(let De of M.split(`
808
- `)){if(De.includes("Old File contents:")){Ne=!0;continue}Ne&&(De.trim()===""?Ne=!1:/^\d+ \|/.test(De)&&J++)}}(Y>0||J>0)&&(await Gt("linesAdded",Y),await Gt("linesRemoved",J))}}catch(M){let F=`ERROR: Execution failed for [${B.toolName}]: ${M.message}`;i&&i(`[Tool Error] ${F}
809
- `),V+=`${F}
807
+ `),V=0,J=0,Ne=!1;for(let De of F){if(De.includes("[DIFF_START]")){Ne=!0;continue}if(De.includes("[DIFF_END]")){Ne=!1;continue}Ne&&(/^\+\d+/.test(De)?V++:/^\-\d+/.test(De)&&J++)}(V>0||J>0)&&(await Gt("linesAdded",V),await Gt("linesRemoved",J))}}else if((W==="writefile"||W==="write_file")&&M){let F=M.match(/- Stats: \[(\d+) lines/),V=F?parseInt(F[1]):0,J=0;if(M.includes("Old File contents:")){let Ne=!1;for(let De of M.split(`
808
+ `)){if(De.includes("Old File contents:")){Ne=!0;continue}Ne&&(De.trim()===""?Ne=!1:/^\d+ \|/.test(De)&&J++)}}(V>0||J>0)&&(await Gt("linesAdded",V),await Gt("linesRemoved",J))}}catch(M){let F=`ERROR: Execution failed for [${N.toolName}]: ${M.message}`;i&&i(`[Tool Error] ${F}
809
+ `),Y+=`${F}
810
810
 
811
- `,await It("toolFailure")}}let oe="";if(n?.taskId&&typeof Ye<"u"){let B=Ye.find(W=>W.id===n.taskId);if(B&&B.pendingSteerMessages&&B.pendingSteerMessages.length>0){let W=[...B.pendingSteerMessages];B.pendingSteerMessages=[];for(let re of W)oe+=`
811
+ `,await It("toolFailure")}}let ie="";if(n?.taskId&&typeof Ye<"u"){let N=Ye.find(W=>W.id===n.taskId);if(N&&N.pendingSteerMessages&&N.pendingSteerMessages.length>0){let W=[...N.pendingSteerMessages];N.pendingSteerMessages=[];for(let re of W)ie+=`
812
812
 
813
- [STEERING INSTRUCTION FROM MAIN AGENT]: ${re}`,i&&i(`[Subagent Steered] ${re}`)}}let Ie=(V.trim()+oe).trim();b.push({role:"user",text:Ie}),T++}return $};export{hn as a,Dr as b,ff as c,uf as d,dl as e,Fr as f,hf as g,wl as h,pf as i,co as j,la as k,xp as l,bp as m,I as n,Ic as o,Zo as p,zs as q,Oc as r,Lc as s,ft as t,ls as u,fd as v,Va as w,ud as x,hd as y,pd as z,md as A,gd as B,Td as C,Rd as D,Tn as E,Za as F,Js as G,Gt as H,el as I,Cr as J,cs as K,Al as L,uu as M,hu as N,Tp as O,No as P,Rp as Q,Pn as R,pc as S,dm as T,fm as U,Qi as V,um as W,hm as X,Tc as Y,pm as Z,mm as _,gm as $};
813
+ [STEERING INSTRUCTION FROM MAIN AGENT]: ${re}`,i&&i(`[Subagent Steered] ${re}`)}}let _e=(Y.trim()+ie).trim();k.push({role:"user",text:_e}),T++}return $};export{hn as a,jr as b,wf as c,xf as d,gl as e,Hr as f,bf as g,Rl as h,Sf as i,uo as j,pa as k,Mp as l,Ap as m,O as n,Bc as o,ti as p,Ks as q,Uc as r,Wc as s,ft as t,ls as u,wd as v,tl as w,xd as x,bd as y,Sd as z,kd as A,Td as B,Ad as C,vd as D,Tn as E,il as F,Js as G,Gt as H,rl as I,Or as J,cs as K,Dl as L,xu as M,bu as N,Op as O,Uo as P,Lp as Q,Pn as R,Sc as S,bm as T,Sm as U,or as V,km as W,Tm as X,Ac as Y,Rm as Z,Em as _,$m as $};