fluxflow-cli 4.3.0 → 4.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,99 +1,99 @@
1
- import{b as Zo}from"./chunk-ACHIC75V.js";import{c as zt,d as zs,g as ve,h as Ft}from"./chunk-TKIVOTJ4.js";import{a as qs,b as Cs,c as J,d as pe}from"./chunk-SIINYZWE.js";import{c as An,d as fn,e as bo,f as _s,g as $s,h as Jo,i as Zt,j as Pt,k as en,l as vn,m as Wn,n as rn,o as un,p as rs,q as Qo,r as jn,s as as}from"./chunk-I27MASHH.js";import{a as Xe,c as ko}from"./chunk-56EJGQU3.js";import{c as br,d as kr,e as Ks}from"./chunk-GKFFLQSG.js";import er from"dotenv";import{GoogleGenAI as Oa,ThinkingLevel as lt,HarmBlockThreshold as Yn,HarmCategory as Vn}from"@google/genai";import{Ollama as lc}from"ollama";import{execSync as Ja}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 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 Qo}from"./chunk-ACHIC75V.js";import{c as zt,d as qs,g as ve,h as Nt}from"./chunk-TKIVOTJ4.js";import{a as Gs,b as $s,c as J,d as pe}from"./chunk-SIINYZWE.js";import{c as Mn,d as fn,e as xo,f as Es,g as _s,h as Xo,i as en,j as Ft,k as tn,l as An,m as Wn,n as rn,o as un,p as rs,q as Jo,r as jn,s as is}from"./chunk-I27MASHH.js";import{a as Xe,c as bo}from"./chunk-56EJGQU3.js";import{c as xi,d as bi,e as zs}from"./chunk-GKFFLQSG.js";import Zr from"dotenv";import{GoogleGenAI as Ia,ThinkingLevel as ct,HarmBlockThreshold as Yn,HarmCategory as Vn}from"@google/genai";import{Ollama as cc}from"ollama";import{execSync as Qa}from"child_process";import{spawn as Zo}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 r="";if(t<e.length&&(e[t]==='"'||e[t]==="'"||e[t]==="`")){let a=e[t];t++;let i=t,h=-1,d=t;for(;d<e.length;){let l=e.indexOf(a,d);if(l===-1)break;let f=0;for(let y=l-1;y>=0&&e[y]==="\\";y--)f++;if(f%2!==0){d=l+1;continue}let u=e.substring(l+1),p=u.trim(),g=p===""||/^,\s*\w+\s*=/.test(p)||p.startsWith(")")&&(p.length===1||/^\)\s*([,\]\s]|\[\[?tool:)/i.test(p));if(g&&u.startsWith(`
2
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 So=null;try{let e=await import("node-pty");So=e.default||e}catch{}var jc=!!So,To=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 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
- `)},yt=null,Ys=!1,Hc=e=>{try{yt&&(Ys&&typeof yt.write=="function"?yt.write(e):yt.stdin&&yt.stdin.writable&&yt.stdin.write(e))}catch{}},Gc=()=>{if(yt){try{Ys&&typeof yt.destroy=="function"?yt.destroy():typeof yt.kill=="function"&&(process.platform==="win32"?ei("taskkill",["/pid",yt.pid,"/f","/t"]):yt.kill("SIGKILL"))}catch{}yt=null,Ys=!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&&Hn()){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&&Hn()){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,""),b=w;return a(x)&&(b=w.replace(/\//g,"\\")),b});y.push("-Path",m.join(","))}r.push(...y),c=g-1;continue}if(l==="cp"&&n&&Hn()){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,""),b=w;return a(x)&&(b=w.replace(/\//g,"\\")),b});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&&Hn()){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(" ")},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),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?(r=e.substring(i,h),t=h+1):(r=e.substring(i),t=e.length);let c=s.toLowerCase().includes("path")||["dest","source","to","from"].includes(s.toLowerCase());r=r.replace(/\\(.)/g,(l,f)=>{switch(f){case"n":return`
4
+ `;case"r":return"\r";case"t":return" ";case"\\":return"\\";default:return f===a?a:f}})}else if(t<e.length&&e[t]==="["){let a=0,i=null,h=t,d=-1;for(let c=t;c<e.length;c++){let l=e[c];if(i&&l===i){let f=0;for(let u=c-1;u>=0&&e[u]==="\\";u--)f++;f%2===0&&(i=null)}else!i&&(l==='"'||l==="'"||l==="`")&&(i=l);if(!i&&(l==="["?a++:l==="]"&&a--,a===0)){d=c;break}}if(d!==-1){r=e.substring(h,d+1),t=d+1;try{let c=r.trim();c.startsWith("'")||c.includes("'")}catch{}}else r=e.substring(h),t=e.length}else{let a=e.substring(t),i=a.match(/,\s*\w+\s*=|(?:\s*\)\s*(?:$|\]\]))/);if(i){let h=i.index;r=a.substring(0,h).trim(),t+=h}else r=a.trim(),t=e.length}r==="true"?r=!0:r==="false"?r=!1:typeof r=="string"&&!isNaN(r)&&r.trim()!==""&&(r=Number(r)),typeof r=="string"&&(s.toLowerCase().includes("path")||["dest","source","to","from"].includes(s.toLowerCase()))&&(r=r.replace(/\x0C/g,"\\f").replace(/\x0D/g,"\\r").replace(/\x0B/g,"\\v").replace(/\x08/g,"\\b")),n[s]=r}return n};var ko=null;try{let e=await import("node-pty");ko=e.default||e}catch{}var Hc=!!ko,So=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),er=e=>{if(!e)return"";let n=[[]],t=0,o=0,s=/\x1b\[([0-9;]*?)([a-zA-Z])/g,r=0,a,i=d=>{for(let c=0;c<d.length;c++){let l=d[c];if(l===`
5
+ `)for(t++,o=0;t>=n.length;)n.push([]);else if(l==="\r")o=0;else{for(;t>=n.length;)n.push([]);let f=n[t];for(;o>f.length;)f.push(" ");f[o]=l,o++}}};for(;(a=s.exec(e))!==null;){i(e.substring(r,a.index));let d=a[1],c=a[2],l=d?d.split(";").map(Number):[];if(c==="A"){let f=l[0]||1;t=Math.max(0,t-f)}else if(c==="B"){let f=l[0]||1;for(t=t+f;t>=n.length;)n.push([])}else if(c==="C"){let f=l[0]||1;o=o+f}else if(c==="D"){let f=l[0]||1;o=Math.max(0,o-f)}else if(c==="G"){let f=(l[0]||1)-1;o=Math.max(0,f)}else if(c==="H"||c==="f"){let f=(l[0]||1)-1,u=(l[1]||1)-1;for(t=Math.max(0,f),o=Math.max(0,u);t>=n.length;)n.push([])}else if(c==="K"){let f=l[0]||0;if(t<n.length){let u=n[t];if(f===0)u.length=o;else if(f===1)for(let 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)}r=s.lastIndex}i(e.substring(r));let h=n.map(d=>d.join(""));for(;h.length>0&&h[h.length-1]==="";)h.pop();return h.join(`
6
+ `)},wt=null,Ks=!1,Gc=e=>{try{wt&&(Ks&&typeof wt.write=="function"?wt.write(e):wt.stdin&&wt.stdin.writable&&wt.stdin.write(e))}catch{}},qc=()=>{if(wt){try{Ks&&typeof wt.destroy=="function"?wt.destroy():typeof wt.kill=="function"&&(process.platform==="win32"?Zo("taskkill",["/pid",wt.pid,"/f","/t"]):wt.kill("SIGKILL"))}catch{}wt=null,Ks=!1}},tr=(e,n=!1)=>{if(process.platform!=="win32")return e;let t=[],o="",s=null,r=!1;for(let c=0;c<e.length;c++){let l=e[c];if(r){o+=l,r=!1;continue}if(l==="\\"){if(e[c+1]===" "){o+=" ",c++;continue}o+=l,r=!0;continue}s?(l===s&&(s=null),o+=l):l==='"'||l==="'"?(s=l,o+=l):l===";"&&!o.includes("://")?(o.length>0&&(t.push(o),o=""),t.push(n?";":"&")):l==="&"&&!o.includes("://")?e[c+1]==="&"?(o.length>0&&(t.push(o),o=""),t.push("&&"),c++):(o.length>0&&(t.push(o),o=""),t.push("&")):l==="|"&&!o.includes("://")?(o.length>0&&(t.push(o),o=""),t.push("|")):/\s/.test(l)?o.length>0&&(t.push(o),o=""):o+=l}o.length>0&&t.push(o);let a=c=>!(!c.includes("/")||/^(https?|file|ftp):\/\//i.test(c)||c.startsWith("@")||c.startsWith("/")&&(c.match(/\//g)||[]).length===1||/\s\/|\/\s/.test(c)||/[\(\)\{\}\;\<\>\=\'\"]/.test(c)),i=[];for(let c=0;c<t.length;c++){let l=t[c];if(l==="mkdir"&&n&&Hn()){let f=[],u=c+1;for(;u<t.length;){let 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});i.push("New-Item","-ItemType","Directory","-Force","-Path",p.join(","))}else i.push("New-Item","-ItemType","Directory","-Force");c=u-1;continue}if(l==="rm"&&n&&Hn()){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 b=w.replace(/^['"]|['"]$/g,""),x=w;return a(b)&&(x=w.replace(/\//g,"\\")),x});y.push("-Path",m.join(","))}i.push(...y),c=g-1;continue}if(l==="cp"&&n&&Hn()){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 b=w.replace(/^['"]|['"]$/g,""),x=w;return a(b)&&(x=w.replace(/\//g,"\\")),x});if(m.length>1){let w=m.pop();y.push("-Path",m.join(","),"-Destination",w)}else y.push("-Path",m[0])}i.push(...y),c=g-1;continue}if(l==="touch"&&n&&Hn()){let f=[],u=c+1;for(;u<t.length;){let 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 $_ } }`;i.push(g)}c=u-1;continue}if(l==="|"&&t[c+1]==="tee"){t[c+2]==="-a"?(i.push(">>"),c+=2):(i.push(">"),c+=1);continue}if(l==="|"&&t[c+1]==="cat"&&t[c+2]===">"){i.push(">"),c+=2;continue}if(l==="|"){let f=t[c+1];if(f){let u=f.replace(/^['"]|['"]$/g,""),p=/\.(txt|md|json|log|csv|html|css|py|js|xml|yaml|yml|pdf|docx|pptx|xlsx)$/i.test(u);if(a(u)&&p){i.push(">");continue}}}i.push(l)}let h=!1,d=i.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(" ")},nr=async(e,n={})=>{let{command:t}=O(e),{onChunk:o}=n;if(!t)return'ERROR: Missing "command" argument for exec_command.';let s=process.platform==="win32",r=n.systemSettings||{},a={};return r.networkAccess===!1&&(a.HTTP_PROXY="http://127.0.0.1:9999",a.HTTPS_PROXY="http://127.0.0.1:9999",a.ALL_PROXY="socks5://127.0.0.1:9999",a.http_proxy="http://127.0.0.1:9999",a.https_proxy="http://127.0.0.1:9999",a.all_proxy="socks5://127.0.0.1:9999",a.NO_PROXY="localhost,127.0.0.1"),new Promise(i=>{let h=d=>{let c=d==="pwsh"||d==="powershell",l=tr(t,c),f;s?d==="pwsh"?f="C:\\Users\\User\\AppData\\Local\\Microsoft\\WindowsApps\\pwsh.exe":d==="powershell"?f="powershell.exe":f="cmd.exe":f=process.env.SHELL||"bash";let u=s?c?["-NoProfile","-Command",l]:["/c",l]:["-c",l];if(r.networkAccess===!1&&!s){let p=f,g=[...u];if(process.platform==="linux")f="unshare",u=["-n","-r",p,...g];else if(process.platform==="darwin"){let y=`(version 1)
7
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(So)try{let p=So.spawn(f,u,{name:"xterm-256color",cols:n.cols||120,rows:n.rows||30,cwd:process.cwd(),env:{...process.env,CI:"false",TERM:"xterm-256color",FORCE_COLOR:"1",...a}});yt=p,Ys=!0;let g="",y=!1;return p.onData(m=>{if(!y){g+=m,o&&o(m);let w=To(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
+ `;f="sandbox-exec",u=["-p",y,p,...g]}}if(ko)try{let p=ko.spawn(f,u,{name:"xterm-256color",cols:n.cols||120,rows:n.rows||30,cwd:process.cwd(),env:{...process.env,CI:"false",TERM:"xterm-256color",FORCE_COLOR:"1",...a}});wt=p,Ks=!0;let g="",y=!1;return p.onData(m=>{if(!y){g+=m,o&&o(m);let w=So(g);/(?:Network:\s+use\s+--host\s+to|Network:\s+Type\s+--host\s+to|Local:\s+http:\/\/localhost:\d+|ready in \d+\s*ms|Compiled successfully|Development server is running|Listening on:)/i.test(w)&&(y=!0,setTimeout(()=>i(`SUCCESS: Dev server started successfully in background.
12
12
 
13
- ${w}`),500))}}),p.onExit(({exitCode:m})=>{if(y)return;yt=null;let w=ti(g||""),x=To(w).replace(/\n{3,}/g,`
13
+ ${w}`),500))}}),p.onExit(({exitCode:m})=>{if(y)return;wt=null;let w=er(g||""),b=So(w).replace(/\n{3,}/g,`
14
14
 
15
- `)||"Command executed with no output.";r(m!==0?`ERROR: Command [${t}] failed with exit code [${m}].
15
+ `)||"Command executed with no output.";i(m!==0?`ERROR: Command [${t}] failed with exit code [${m}].
16
16
 
17
- ${x}`:`SUCCESS: Command [${t}] completed.
17
+ ${b}`:`SUCCESS: Command [${t}] completed.
18
18
 
19
- ${x}`)}),!0}catch(p){return s&&(d==="pwsh"||d==="powershell")&&p.code==="ENOENT"?!1:(Ro(r,l,t,a,o,d,i),!0)}else return Ro(r,l,t,a,o,d,i),!0};s?h("pwsh")||h("powershell")||h("cmd"):h("bash")})},Ro=(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
+ ${b}`)}),!0}catch(p){return s&&(d==="pwsh"||d==="powershell")&&p.code==="ENOENT"?!1:(To(i,l,t,a,o,d,r),!0)}else return To(i,l,t,a,o,d,r),!0};s?h("pwsh")||h("powershell")||h("cmd"):h("bash")})},To=(e,n,t,o,s,r="powershell",a={})=>{let i=process.platform==="win32",h=r==="pwsh"||r==="powershell",d;i?r==="pwsh"?d="C:\\Users\\User\\AppData\\Local\\Microsoft\\WindowsApps\\pwsh.exe":r==="powershell"?d="powershell.exe":d="cmd.exe":d=process.env.SHELL||"bash";let c=i?h?["-NoProfile","-Command",n]:["/c",n]:["-c",n];if(a.networkAccess===!1&&!i){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?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}});yt=l,Ys=!1,l.stdin&&l.stdin.on("error",()=>{yt=null});let f="",u="",p=!1;l.stdout.on("data",g=>{if(!p){let y=g.toString();f+=y,s&&s(y);let m=To(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=i?Zo(d,c,{cwd:process.cwd(),env:{...process.env,...o}}):Zo(d,c,{cwd:process.cwd(),env:{...process.env,CI:"false",TERM:"xterm-256color",FORCE_COLOR:"1",...o}});wt=l,Ks=!1,l.stdin&&l.stdin.on("error",()=>{wt=null});let f="",u="",p=!1;l.stdout.on("data",g=>{if(!p){let y=g.toString();f+=y,s&&s(y);let m=So(f);/(?:Network:\s+use\s+--host\s+to|Network:\s+Type\s+--host\s+to|Local:\s+http:\/\/localhost:\d+|ready in \d+\s*ms|Compiled successfully|Development server is running|Listening on:)/i.test(m)&&(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;yt=null;let y=[],m=ti(f),w=ti(u);m&&y.push(`STDOUT:
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;wt=null;let y=[],m=er(f),w=er(u);m&&y.push(`STDOUT:
27
27
  ${m}`),w&&y.push(`STDERR:
28
- ${w}`),g!==0&&y.push(`EXIT CODE: ${g}`);let x=y.join(`
28
+ ${w}`),g!==0&&y.push(`EXIT CODE: ${g}`);let b=y.join(`
29
29
 
30
- `)||"Command executed with no output.",b=To(x).replace(/\n{3,}/g,`
30
+ `)||"Command executed with no output.",x=So(b).replace(/\n{3,}/g,`
31
31
 
32
32
  `);e(g!==0?`ERROR: Command [${t}] failed with exit code [${g}].
33
33
 
34
- ${b}`:`SUCCESS: Command [${t}] completed.
34
+ ${x}`:`SUCCESS: Command [${t}] completed.
35
35
 
36
- ${b}`)}),l.on("error",g=>{if(r&&g.code==="ENOENT"){if(i==="pwsh"){let m=ni(t,!0);return Ro(e,m,t,o,s,"powershell",a)}else if(i==="powershell"){let m=ni(t,!1);return Ro(e,m,t,o,s,"cmd",a)}}yt=null;let y=g instanceof Error?g.message:String(g);e(`ERROR: Failed to start command [${t}]: ${y}`)})};var Vs=null,Hn=()=>{if(process.platform!=="win32")return!1;if(Vs!==null)return Vs;try{Ja('powershell.exe -NoProfile -Command "exit"',{stdio:"ignore"}),Vs=!0}catch{Vs=!1}return Vs},oi=null,Sr=(e,n,t,o,s=!1,i=!0)=>{oi===null&&(oi=s);let a=`- JSON escape literal escape sequences in tool arguments
36
+ ${x}`)}),l.on("error",g=>{if(i&&g.code==="ENOENT"){if(r==="pwsh"){let m=tr(t,!0);return To(e,m,t,o,s,"powershell",a)}else if(r==="powershell"){let m=tr(t,!1);return To(e,m,t,o,s,"cmd",a)}}wt=null;let y=g instanceof Error?g.message:String(g);e(`ERROR: Failed to start command [${t}]: ${y}`)})};var Ys=null,Hn=()=>{if(process.platform!=="win32")return!1;if(Ys!==null)return Ys;try{Qa('powershell.exe -NoProfile -Command "exit"',{stdio:"ignore"}),Ys=!0}catch{Ys=!1}return Ys},sr=null,ki=(e,n,t,o,s=!1,r=!0)=>{sr===null&&(sr=s);let a=`- JSON escape literal escape sequences in tool arguments
37
37
  - Same file, multiple edits? One PatchFile (\u226415 blocks) \u2190 Priority
38
38
  - Tool denied? Ask for guidance \u2190 mandatory
39
39
  - Need text or huge file? CodeSearch > Full Read
40
40
  - Avoid unnecessary large file chunk reads
41
41
  - Dont hallucinate tool results, verify, fix errors
42
42
  - Stuck on syntax error? Tell user > waste time
43
- `,r=`**Workspace Tools (path = relative; first argument, path separator: '/')**
44
- - [tool:functions.ReadFile(path="...", startLine="int", endLine="int")]${o!=="Google"?`${t?". Supports images/docs":""}`:". Supports images/docs"}
45
- - [tool:functions.ReadFolder(path="...", recurse="int 1-3")]. Minimize recursion
46
- - [tool:functions.PatchFile(path="...", allowMultiple="bool, default: false", searchContent1="search string OR ^LINE:start..end$", newContent1="...", ...MAX15)]. Use small searchContent. Line Ranges must for large searchContent and escape sequences. ^...$ must for line ranges
47
- - [tool:functions.WriteFile(path="...", content="...")]. Creates/Overwrites. File Exist? PatchFile > WriteFile
48
- - [tool:functions.CodeSearch(keyword="...", path="dir/file/glob/regex, inclusion/exclusion ;-separated", fuzzy="bool false", regex="bool auto")]. Find definitions, logic, relevant code, standard junk auto-excluded
49
- - [tool:functions.Run(command="...")]. Runs ${n==="Windows"?Hn()?"powershell":"windows CMD":"bash"} command. Destructive/Irreversible ops \u2192 Ask user
50
- - [tool:functions.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
- ${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?`
43
+ `,i=`**Workspace Tools (path = relative; first argument, path separator: '/')**
44
+ - ReadFile(path="...", startLine="int", endLine="int")${o!=="Google"?`${t?". Supports images/docs":""}`:". Supports images/docs"}
45
+ - ReadFolder(path="...", recurse="int 1-3"). Minimize recursion
46
+ - PatchFile(path="...", allowMultiple="bool, default: false", searchContent1="search string OR ^LINE:start..end$", newContent1="...", ...MAX15). Use small searchContent. Line Ranges must for large searchContent and escape sequences. ^...$ must for line ranges
47
+ - WriteFile(path="...", content="..."). Creates/Overwrites. File Exist? PatchFile > WriteFile
48
+ - CodeSearch(keyword="...", path="dir/file/glob/regex, inclusion/exclusion ;-separated", fuzzy="bool false", regex="bool auto"). Find definitions, logic, relevant code, standard junk auto-excluded
49
+ - Run(command="..."). Runs ${n==="Windows"?Hn()?"powershell":"windows CMD":"bash"} command. Destructive/Irreversible ops \u2192 Ask user
50
+ - Goal(method="create/append/get", tasks=[string array], markDone=[task array]). If long multi-task: create Goals before starting. \`get + markDone\` to mark complete. Update every turn when created
51
+ ${sr?'\n**Emergency Tools**\nInfo: `initial` = current task prompt. Revert `id` = turn before disaster (eg. disaster: `turn_3` \u2192 revert: `turn_2`). Reason explicitly\n- EmergencyRollback(method="getCheckpoint/forceRevert", id="..."). Rollback workspace in this agent loop. ONLY for catastrophic corruption. Before ending, verify no catastrophe. `id` omitted for `getCheckpoint`\n':""}${r?`
52
52
  **Sub Agent Tools**
53
53
  proactive use highly recommended. Prefer for any task, no user nudge needed
54
54
  Invocations:
55
55
  \u2022 Invoke (async/background, \u22647 parallel). Parallelize long tasks. May take time
56
56
  \u2022 InvokeSync (sync/blocking). Sequential, repetitive or delegated tasks. Saves tokens/cost
57
- - [tool:functions.InvokeSync/Invoke(title="...", task="...")]. Task must be detailed: exact file paths, imports/exports, dependencies
58
- - [tool:functions.Await(id="...", timeout="integer")]. Event-driven wait
59
- - [tool:functions.GetProgress(id="...")]. Poll sparingly; NO initial poll. Work or await. Never end while subagent runs
60
- - [tool:functions.Steer(id="...", message="...")]. Inject additional instruction or redirection into active async subagent
61
- - [tool:functions.Cancel(id="...")]. Cancel async task ONLY if stalled (2m+) or incorrect`:""}`,h=`**Creative Tools (path = relative; first argument, path separator: '/')**
62
- - [tool:functions.WritePDF(path="...", content="...", orientation="...")]. Proactive A4 page breaks must in css. HTML/CSS for premium layout, stable margins & headers/footers, no watermarks
63
- - [tool:functions.WriteDoc(path="...", content="...")]. A4 Word document, no watermarks, stable margins & headers/footers`,d=`**Computer Use Tools (GUI Desktop Automation)**
64
- - [tool:functions.Click(gridId="integer", type="single/double", button="left/middle/right", intendedClickText="target text")]. Click target grid number, intendedClickText: literal text/icon on screen (OCR scannable, upto 3 words). Double click desktop icons
65
- - [tool:functions.Drag(fromGridId="integer", toGridId="integer")]. Drag mouse from start grid number to target grid number
66
- - [tool:functions.Scroll(direction="up/down", gridId="mouse hover area")]. Scroll viewport vertically
67
- - [tool:functions.KeyboardTyping(text="string", autoPressEnter="bool")]. Type text string into currently active input. JSON escape literal escape sequences
68
- - [tool:functions.KeyPress(key="key or ;-separated combination, eg: enter, back, backspace, clearInput, ctrl;c, alt;tab, f5, f11, alt;f4")]. Press key, shortcut, function key (f1-f12), or clear active input field.
69
- - [tool:functions.RecaptureScreen()]. Request fresh gridded screenshot`;return`
57
+ - InvokeSync/Invoke(title="...", task="..."). Task must be detailed: exact file paths, imports/exports, dependencies
58
+ - Await(id="...", timeout="integer"). Event-driven wait
59
+ - GetProgress(id="..."). Poll sparingly; NO initial poll. Work or await. Never end while subagent runs
60
+ - Steer(id="...", message="..."). Inject additional instruction or redirection into active async subagent
61
+ - Cancel(id="..."). Cancel async task ONLY if stalled (2m+) or incorrect`:""}`,h=`**Creative Tools (path = relative; first argument, path separator: '/')**
62
+ - WritePDF(path="...", content="...", orientation="..."). Proactive A4 page breaks must in css. HTML/CSS for premium layout, stable margins & headers/footers, no watermarks
63
+ - WriteDoc(path="...", content="..."). A4 Word document, no watermarks, stable margins & headers/footers`,d=`**Computer Use Tools (GUI Desktop Automation)**
64
+ - Click(gridId="integer", type="single/double", button="left/middle/right", intendedClickText="target text"). Click target grid number, intendedClickText: literal text/icon on screen (OCR scannable, upto 3 words). Double click desktop icons
65
+ - Drag(fromGridId="integer", toGridId="integer"). Drag mouse from start grid number to target grid number
66
+ - Scroll(direction="up/down", gridId="mouse hover area"). Scroll viewport vertically
67
+ - KeyboardTyping(text="string", autoPressEnter="bool"). Type text string into currently active input. JSON escape literal escape sequences
68
+ - KeyPress(key="key or ;-separated combination, eg: enter, back, backspace, clearInput, ctrl;c, alt;tab, f5, f11, alt;f4"). Press key, shortcut, function key (f1-f12), or clear active input field
69
+ - RecaptureScreen(). Request fresh gridded screenshot`;return`
70
70
  -- TOOLS --
71
71
  To use tools, must output exactly '[tool:functions.ToolName(arg1="value1")]' structured string in chat response \u2190 no exception
72
72
  Tool Rules:
73
73
  - Max 3 tool calls/turn${e==="Flux"||e.toLowerCase()==="fluxcu"?" (Todo: 3+)":""}
74
74
  ${e==="Flux"||e.toLowerCase()==="fluxcu"?`${a}`:""}
75
75
  **User Communication**
76
- - [tool:functions.Ask(question="...", optionA="title::description", ...MAX4)]. Ambiguity, path divergence, security risk. Ask, dont finish/guess. Keep titles short
76
+ - Ask(question="...", optionA="title::description", ...MAX4). Ambiguity, path divergence, security risk. Ask, dont finish/guess. Keep titles short
77
77
 
78
78
  **Web Tools**
79
- - [tool:functions.WebSearch(query="...", aiMode="bool", limit="integer 3-10 aiMode: exclude")]. Proactive use for unknown info/docs. aiMode: LLM search
80
- - [tool:functions.WebScrape(url="...")]. Proactive use for specific webpage/docs/api
79
+ - WebSearch(query="...", aiMode="bool", limit="integer 3-10 aiMode: exclude"). Proactive use for unknown info/docs. aiMode: LLM search
80
+ - WebScrape(url="..."). Proactive use for specific webpage/docs/api
81
81
 
82
- ${e==="ICU"?`${d}`:e==="FluxCU"?`${r}
83
- ${d}`:e==="Flux"?`${r}`:`${h}`}`.trim()};var Tr=(e=!0,n=!0)=>`
82
+ ${e==="ICU"?`${d}`:e==="FluxCU"?`${i}
83
+ ${d}`:e==="Flux"?`${i}`:`${h}`}`.trim()};var Si=(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 --
87
- - [tool:functions.Chat(title="<short creative title of FULL conversation in 3 or 4 words>")]. Consider full chat context to generate title NOT just latest message
88
- - [tool:functions.Memory(action="temp", content="<summary of the user prompt & model responses only from latest prompt under 40 words>. [Talked on: <date> <hour>]")]. Time format: YYYY-MM-DD HH am/pm
87
+ - Chat(title="<short creative title of FULL conversation in 3 or 4 words>"). Consider full chat context to generate title NOT just latest message
88
+ - Memory(action="temp", content="<summary of the user prompt & model responses only from latest prompt under 40 words>. [Talked on: <date> <hour>]"). Time format: YYYY-MM-DD HH am/pm
89
89
 
90
90
  ${e?`-- User-specific long-term/permanent memory (use based on conversation context, do not re-save memory which is already saved) --
91
- - Add: [tool:functions.Memory(action="user", method="add", content="<string to add>. [Saved on: <date ONLY>]", score=2)] (Set score=2 ONLY if the user explicitly asked to "remember" or "save" this information, else omit this parameter entirely)
92
- - Delete: [tool:functions.Memory(action="user", method="delete", id="<memory id>")]
93
- - Update: [tool:functions.Memory(action="user", method="update", content-new="string to update", id="<memory id>")]
91
+ - Add: Memory(action="user", method="add", content="<string to add>. [Saved on: <date ONLY>]", score=2). (Set score=2 ONLY if the user explicitly asked to "remember" or "save" this information, else omit this parameter entirely)
92
+ - Delete: Memory(action="user", method="delete", id="<memory id>")
93
+ - Update: Memory(action="user", method="update", content-new="string to update", id="<memory id>")
94
94
 
95
95
  -- Memory Relevance Decay Tool --
96
- - Score Adjustment: [tool:functions.addMemScore(id="<memory id>")]
96
+ - Score Adjustment: addMemScore(id="<memory id>")
97
97
  You MUST call this tool when a specific saved memory in the '-- Current Saved User Memories --' list was relevant, referenced, or helpful in the agent's response or user prompt in current message. You can stack multiple calls
98
98
 
99
99
  Explicit Triggers for permanent memory:
@@ -103,12 +103,12 @@ Explicit Triggers for permanent memory:
103
103
  - User shares personal information or preferences
104
104
 
105
105
  Usage Rules:
106
- - Frequency for 'user' action: Based on explicit triggers.
106
+ - Frequency for 'user' action: Based on explicit triggers
107
107
  - If you want to save something, but similar memory already exists, use the update method not add
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 Eo={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,12 +121,12 @@ 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 Er from"fs";import Za from"screenshot-desktop";var _r=!1;(async()=>{try{let e=await Ft();if(Number(e?.display)===1){let n=await Za.listDisplays();n&&n.length>1&&(_r=!0)}}catch{}})();var ii=null,Rr=null,Xs=null,ad=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",el=process.env.NO_DEV||!1,tl=(e,n)=>{if(!n)return"";if(e!==Rr||Xs===null){Rr=e;try{let t=J(Pt,[]);Array.isArray(t)&&t.length>0?Xs=t.map(o=>`- ${o.memory}`).join(`
125
- `):Xs=""}catch(t){Xs="",Er.appendFileSync(`${fn}/memory/error.txt`,`${t.message}
124
+ Verify imports, tool results & system stability; avoid syntax errors`};import Ri from"fs";import el from"screenshot-desktop";var Ei=!1;(async()=>{try{let e=await Nt();if(Number(e?.display)===1){let n=await el.listDisplays();n&&n.length>1&&(Ei=!0)}}catch{}})();var or=null,Ti=null,Vs=null,ld=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",tl=process.env.NO_DEV||!1,nl=(e,n)=>{if(!n)return"";if(e!==Ti||Vs===null){Ti=e;try{let t=J(Ft,[]);Array.isArray(t)&&t.length>0?Vs=t.map(o=>`- ${o.memory}`).join(`
125
+ `):Vs=""}catch(t){Vs="",Ri.appendFileSync(`${fn}/memory/error.txt`,`${t.message}
126
126
  -------------------------------------------------
127
127
 
128
- `)}}return Xs},$r=(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}`:""},Cr=(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 R=n;n==="Fast"&&(R="Off"),n==="Low"&&(R="Minimal"),n==="Standard"&&(R="Medium"),(n==="xHigh"||n==="Max")&&(R="xHigh"),l=Eo[R]||Eo.Medium}if(h||a!=="Google"){let R={Fast:"Lowest",Low:"Low",Medium:"Medium",Standard:"Medium",High:"High",xHigh:"High",Max:"High"};l=Eo.xHigh,l=l.replace("Effort: High",`Effort: ${R[n]}`).replace(`
128
+ `)}}return Vs},_i=(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}`:""},$i=(e,n,t,o,s=!0,r=!1,a="Google",i=!1,h,d)=>{let c=!1;process.env.forcedReasoning&&(c=!0);let l="";if(!h&&a==="Google"){let R=n;n==="Fast"&&(R="Off"),n==="Low"&&(R="Minimal"),n==="Standard"&&(R="Medium"),(n==="xHigh"||n==="Max")&&(R="xHigh"),l=Ro[R]||Ro.Medium}if(h||a!=="Google"){let R={Fast:"Lowest",Low:"Low",Medium:"Medium",Standard:"Medium",High:"High",xHigh:"High",Max:"High"};l=Ro.xHigh,l=l.replace("Effort: High",`Effort: ${R[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
@@ -137,17 +137,17 @@ Brief thoughts, think only enough to avoid mistakes, verify imports, tool result
137
137
  ${u.length?"":`
138
138
  `}`:"",g=e.name&&e.name?.length>0?`User Name: ${e.name}
139
139
  ${p.length||u.length?"":`
140
- `}`:"",y=process.cwd(),m=tl(d,s),w=m?.length>0?`--- Saved Memories ---
140
+ `}`:"",y=process.cwd(),m=nl(d,s),w=m?.length>0?`--- Saved Memories ---
141
141
  ${m}
142
142
 
143
- `:"",x=(()=>{let R=process.cwd().toLowerCase();if(process.platform==="win32"){let S=process.env.SystemRoot?.toLowerCase()||"c:\\windows",T=process.env.ProgramFiles?.toLowerCase()||"c:\\program files",$=process.env["ProgramFiles(x86)"]?.toLowerCase()||"c:\\program files (x86)";return R.startsWith(S)||R.startsWith(T)||R.startsWith($)}else return R==="/"||["/bin","/sbin","/etc","/usr","/var","/root"].some(T=>R.startsWith(T))})(),b=[{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 R=b.filter(S=>Er.existsSync(S.name));ii=t==="Flux"&&R.length>0?`
143
+ `:"",b=(()=>{let R=process.cwd().toLowerCase();if(process.platform==="win32"){let S=process.env.SystemRoot?.toLowerCase()||"c:\\windows",T=process.env.ProgramFiles?.toLowerCase()||"c:\\program files",$=process.env["ProgramFiles(x86)"]?.toLowerCase()||"c:\\program files (x86)";return R.startsWith(S)||R.startsWith(T)||R.startsWith($)}else return R==="/"||["/bin","/sbin","/etc","/usr","/var","/root"].some(T=>R.startsWith(T))})(),x=[{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(r||or===null){let R=x.filter(S=>Ri.existsSync(S.name));or=t==="Flux"&&R.length>0?`
144
144
  -- PROJECT CONTEXT --
145
145
  ${R.map(S=>`- ${S.name}: ${S.desc}`).join(`
146
146
  `)}
147
147
  Check these first; These Files > Training Data. Safety rules apply
148
- `:""}let E=ii;return`=== SYSTEM PROMPT ===
149
- Identity: Flux Flow. Sassy, Friendly, CLI Agent${el?"":" 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 > mouse clicks":"Computer Use & Workspace Capabilities. Screenshot as ground truth, analyze grid ids overlapping/close to target, keyboard shortcuts > mouse clicks. Workspace Tools if faster. Focus on Productivity"}${_r&&t.toLowerCase().includes("cu")?`
148
+ `:""}let E=or;return`=== SYSTEM PROMPT ===
149
+ Identity: Flux Flow. Sassy, Friendly, CLI Agent${tl?"":" 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 > mouse clicks":"Computer Use & Workspace Capabilities. Screenshot as ground truth, analyze grid ids overlapping/close to target, keyboard shortcuts > mouse clicks. Workspace Tools if faster. Focus on Productivity"}${Ei&&t.toLowerCase().includes("cu")?`
151
151
  **Running on secondary screen. Opened app not visible in screenshot? Might be opened on primary. Use 'Ask' immediately with NO options and tell user to move app window to secondary**`:""}
152
152
 
153
153
  - OS: ${f}
@@ -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
- ${Sr(t,f,a.toLowerCase()==="deepseek"?!1:r,a,o?.advanceRollback,o?.subAgents!==!1)}
164
+ ${ki(t,f,a.toLowerCase()==="deepseek"?!1:i,a,o?.advanceRollback,o?.subAgents!==!1)}
165
165
  ${E}${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()},Mr=(e="",n=!0,t=!0)=>`=== SYSTEM PROMPT (strict headless logic worker: zero user-facing text policy, strictly follow) ===
181
+ ${g}${p}${u}${w}`.trim()},Ci=(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
- ${Tr(n,t)}
198
+ ${Si(n,t)}
199
199
  === END SYSTEM PROMPT ===${e?`
200
200
 
201
201
  -- current saved user memories --
202
- ${e}`:""}`.trim();import $t from"fs-extra";import _o from"path";import{nanoid as ol}from"nanoid";import ut from"fs-extra";import an from"path";ut.ensureDirSync(Wn);var hn=null;async function nl(e,n){try{if(e.type==="create")await ut.pathExists(e.filePath)&&(await ut.chmod(e.filePath,438).catch(()=>{}),await ut.remove(e.filePath));else if(e.type==="update"){if(!e.backupFile)return;let t=an.join(Wn,n.chatId,e.backupFile);if(await ut.pathExists(t)){let o=J(t,null);if(!o||!o.data)throw new Error(`Backup container corrupt or empty for ${an.basename(e.filePath)}`);let s=Cs(o.data);await ut.pathExists(e.filePath)&&await ut.chmod(e.filePath,438).catch(()=>{}),await ut.writeFile(e.filePath,s,"utf8")}}}catch(t){throw new Error(`Restoration failed for ${an.basename(e.filePath)}: ${t.message}`)}}async function sl(e,n,t=7){let o=0;for(;o<t;)try{return await nl(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,ht={async startTransaction(e,n){ri=e,hn={id:`tx_prompt_${Date.now()}`,chatId:e,timestamp:new Date().toISOString(),prompt:n.trim(),changes:[],reverted:!1},pe(rs,hn)},async recordFileChange(e,n=null){try{if(!hn){if(ri){let a=J(rn,[]),r=[...a].reverse().find(h=>h.chatId===ri);if(r){if(r.changes.some(f=>f.filePath===e))return;let c=await ut.pathExists(e)||n?"update":"create",l=null;if(c==="update"){let f=an.basename(e);l=`${r.id}_${f}.bak`;let u=an.join(Wn,r.chatId);await ut.ensureDir(u);let p=an.join(u,l),g=n!==null?n:await ut.readFile(e,"utf8").catch(()=>null);g!==null?pe(p,{data:qs(g)}):(c="create",l=null)}r.changes.push({filePath:e,type:c,backupFile:l}),pe(rn,a)}}return}if(hn.changes.some(a=>a.filePath===e))return;let s=await ut.pathExists(e)||n?"update":"create",i=null;if(s==="update"){let a=an.basename(e);i=`${hn.id}_${a}.bak`;let r=an.join(Wn,hn.chatId);await ut.ensureDir(r);let h=an.join(r,i),d=n!==null?n:await ut.readFile(e,"utf8").catch(()=>null);d!==null?pe(h,{data:qs(d)}):(s="create",i=null)}hn.changes.push({filePath:e,type:s,backupFile:i}),pe(rs,hn)}catch{}},async commitTransaction(){if(hn)try{let e=J(rn,[]);if(e.push(hn),e.length>512e3){let n=e.shift();if(n.changes)for(let t of n.changes)t.backupFile&&await ut.remove(an.join(Wn,n.chatId,t.backupFile)).catch(()=>{})}pe(rn,e),await ut.remove(rs).catch(()=>{})}catch{}finally{hn=null}},async recoverCrashedTransaction(){try{if(await ut.pathExists(rs)){let e=J(rs,null);if(e?.changes?.length>0){let n=J(rn,[]);n.some(t=>t.id===e.id)||(n.push(e),pe(rn,n))}await ut.remove(rs).catch(()=>{})}}catch{}},async rollbackToBefore(e){let n=J(rn,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 sl(r,a);for(let r of a.changes)if(r.backupFile){let h=an.join(Wn,a.chatId,r.backupFile);await ut.remove(h).catch(()=>{})}n=n.filter(r=>r.id!==a.id),pe(rn,n)}return{success:!0,chatId:o,targetPrompt:s}},async getChatHistory(e){try{return J(rn,[]).filter(t=>t.chatId===e&&!t.reverted)}catch{return[]}},async deleteChatBackups(e){try{await ut.remove(an.join(Wn,e));let n=J(rn,[]),t=n.filter(o=>o.chatId!==e);n.length!==t.length&&pe(rn,t)}catch{}}};var Ar=Promise.resolve(),$o=e=>{let n=Ar.then(async()=>{try{return await e()}catch(t){throw console.error("Lock Operation Failed:",t),t}});return Ar=n.catch(()=>{}),n},ls=async()=>{await $t.ensureDir($s);let e={};if(await $t.pathExists(_s))try{e=J(_s,{})}catch{e={}}for(let n in e){let t=_o.join($s,`${n}.json`);Object.defineProperty(e[n],"messages",{get:()=>{if($t.existsSync(t))try{return J(t,[])}catch{return[]}return[]},set:o=>{try{pe(t,o)}catch{}},enumerable:!1,configurable:!0})}return e},kd=async(e,n,t)=>$o(async()=>{await $t.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+/),b;return x.length>7?b=x.slice(0,7).join(" ")+"...":w.length>45?b=w.substring(0,45).trimEnd()+"...":b=w,b},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=_o.join($s,`${e}.json`);pe(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};pe(_s,g)}),vr=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};pe(_s,o)}),il=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(pe(_s,t),await $t.pathExists(jn))try{let a=J(jn,[]);if(Array.isArray(a)){let r=a.filter(h=>Object.keys(h)[0]!==String(e));pe(jn,r)}}catch{}let o=J(en,{});o[e]&&(delete o[e],pe(en,o));let s=J(vn,{});s[e]&&(delete s[e],pe(vn,s)),await ht.deleteChatBackups(e);let i=_o.join($s,`${e}.json`);if(await $t.pathExists(i))try{await $t.remove(i)}catch{}return n}),Sd=()=>`flow-${ol(6)}`,Td=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 il(a),i++)}return i},rl=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()},al=async e=>{try{if(!await $t.pathExists(e))return;let n=await $t.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=rl(p[1]);if(g&&r-g>a)continue}}let u=l.header+(l.body.length>0?`
202
+ ${e}`:""}`.trim();import Mt from"fs-extra";import Eo from"path";import{nanoid as rl}from"nanoid";import ht from"fs-extra";import an from"path";ht.ensureDirSync(Wn);var hn=null;async function sl(e,n){try{if(e.type==="create")await ht.pathExists(e.filePath)&&(await ht.chmod(e.filePath,438).catch(()=>{}),await ht.remove(e.filePath));else if(e.type==="update"){if(!e.backupFile)return;let t=an.join(Wn,n.chatId,e.backupFile);if(await ht.pathExists(t)){let o=J(t,null);if(!o||!o.data)throw new Error(`Backup container corrupt or empty for ${an.basename(e.filePath)}`);let s=$s(o.data);await ht.pathExists(e.filePath)&&await ht.chmod(e.filePath,438).catch(()=>{}),await ht.writeFile(e.filePath,s,"utf8")}}}catch(t){throw new Error(`Restoration failed for ${an.basename(e.filePath)}: ${t.message}`)}}async function ol(e,n,t=7){let o=0;for(;o<t;)try{return await sl(e,n),!0}catch{if(o++,o>=t)return!1;let r=Math.min(100*Math.pow(2,o-1),5e3);await new Promise(a=>setTimeout(a,r))}return!1}var rr=null,pt={async startTransaction(e,n){rr=e,hn={id:`tx_prompt_${Date.now()}`,chatId:e,timestamp:new Date().toISOString(),prompt:n.trim(),changes:[],reverted:!1},pe(rs,hn)},async recordFileChange(e,n=null){try{if(!hn){if(rr){let a=J(rn,[]),i=[...a].reverse().find(h=>h.chatId===rr);if(i){if(i.changes.some(f=>f.filePath===e))return;let c=await ht.pathExists(e)||n?"update":"create",l=null;if(c==="update"){let f=an.basename(e);l=`${i.id}_${f}.bak`;let u=an.join(Wn,i.chatId);await ht.ensureDir(u);let p=an.join(u,l),g=n!==null?n:await ht.readFile(e,"utf8").catch(()=>null);g!==null?pe(p,{data:Gs(g)}):(c="create",l=null)}i.changes.push({filePath:e,type:c,backupFile:l}),pe(rn,a)}}return}if(hn.changes.some(a=>a.filePath===e))return;let s=await ht.pathExists(e)||n?"update":"create",r=null;if(s==="update"){let a=an.basename(e);r=`${hn.id}_${a}.bak`;let i=an.join(Wn,hn.chatId);await ht.ensureDir(i);let h=an.join(i,r),d=n!==null?n:await ht.readFile(e,"utf8").catch(()=>null);d!==null?pe(h,{data:Gs(d)}):(s="create",r=null)}hn.changes.push({filePath:e,type:s,backupFile:r}),pe(rs,hn)}catch{}},async commitTransaction(){if(hn)try{let e=J(rn,[]);if(e.push(hn),e.length>512e3){let n=e.shift();if(n.changes)for(let t of n.changes)t.backupFile&&await ht.remove(an.join(Wn,n.chatId,t.backupFile)).catch(()=>{})}pe(rn,e),await ht.remove(rs).catch(()=>{})}catch{}finally{hn=null}},async recoverCrashedTransaction(){try{if(await ht.pathExists(rs)){let e=J(rs,null);if(e?.changes?.length>0){let n=J(rn,[]);n.some(t=>t.id===e.id)||(n.push(e),pe(rn,n))}await ht.remove(rs).catch(()=>{})}}catch{}},async rollbackToBefore(e){let n=J(rn,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,r=n.slice(t).filter(a=>a.chatId===o&&!a.reverted).reverse();for(let a of r){for(let i of[...a.changes].reverse())await ol(i,a);for(let i of a.changes)if(i.backupFile){let h=an.join(Wn,a.chatId,i.backupFile);await ht.remove(h).catch(()=>{})}n=n.filter(i=>i.id!==a.id),pe(rn,n)}return{success:!0,chatId:o,targetPrompt:s}},async getChatHistory(e){try{return J(rn,[]).filter(t=>t.chatId===e&&!t.reverted)}catch{return[]}},async deleteChatBackups(e){try{await ht.remove(an.join(Wn,e));let n=J(rn,[]),t=n.filter(o=>o.chatId!==e);n.length!==t.length&&pe(rn,t)}catch{}}};var Mi=Promise.resolve(),_o=e=>{let n=Mi.then(async()=>{try{return await e()}catch(t){throw console.error("Lock Operation Failed:",t),t}});return Mi=n.catch(()=>{}),n},as=async()=>{await Mt.ensureDir(_s);let e={};if(await Mt.pathExists(Es))try{e=J(Es,{})}catch{e={}}for(let n in e){let t=Eo.join(_s,`${n}.json`);Object.defineProperty(e[n],"messages",{get:()=>{if(Mt.existsSync(t))try{return J(t,[])}catch{return[]}return[]},set:o=>{try{pe(t,o)}catch{}},enumerable:!1,configurable:!0})}return e},Sd=async(e,n,t)=>_o(async()=>{await Mt.ensureDir(_s);let o=await as(),s=o[e],r=(t||[]).filter(y=>!y.isUpdateNotification&&(!y.isMeta||y.text&&y.text.includes("Request Cancelled")));try{(await Nt()).systemSettings?.preserveThinking===!1&&(r=r.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 b=w.split(/\s+/),x;return b.length>7?x=b.slice(0,7).join(" ")+"...":w.length>45?x=w.substring(0,45).trimEnd()+"...":x=w,x},i,h=r.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?i=l:i=s.prompt:i=f||l;let u=n||(s?s.name:`Session ${e.slice(-6)}`),p=Eo.join(_s,`${e}.json`);pe(p,r),o[e]={name:u,prompt:i||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};pe(Es,g)}),Ai=async(e,n)=>_o(async()=>{let t=await as();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};pe(Es,o)}),il=async e=>_o(async()=>{let n=await as();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(pe(Es,t),await Mt.pathExists(jn))try{let a=J(jn,[]);if(Array.isArray(a)){let i=a.filter(h=>Object.keys(h)[0]!==String(e));pe(jn,i)}}catch{}let o=J(tn,{});o[e]&&(delete o[e],pe(tn,o));let s=J(An,{});s[e]&&(delete s[e],pe(An,s)),await pt.deleteChatBackups(e);let r=Eo.join(_s,`${e}.json`);if(await Mt.pathExists(r))try{await Mt.remove(r)}catch{}return n}),Td=()=>`flow-${rl(6)}`,Rd=async e=>{if(!e||e==="Never")return;let n=parseInt(e);if(isNaN(n))return;let t=await as(),o=Date.now(),s=n*24*60*60*1e3,r=0;for(let a in t){let i=t[a];i.updatedAt&&o-i.updatedAt>s&&(await il(a),r++)}return r},al=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],r=o[1]||"",a=o[2]||"",i=s.split(/[-\/.]/).map(Number);if(i.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(i[0]>1e3)c=i[0],l=i[1],f=i[2];else if(i[2]>1e3)c=i[2],i[0]>12?(f=i[0],l=i[1]):i[1]>12?(f=i[1],l=i[0]):d?(f=i[0],l=i[1]):(l=i[0],f=i[1]);else return null;if(l<1||l>12||f<1||f>31)return null;let u=0,p=0,g=0;if(r){let m=r.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()},ll=async e=>{try{if(!await Mt.pathExists(e))return;let n=await Mt.readFile(e,"utf8");if(!n.trim())return;let t=n.split(`
203
+ `),o=[],s=null,r=/^\s*(?:DEBUG|ERROR|SEARCH|PUPPETEER)\b/i;for(let l of t)r.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,i=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(r.test(l.header)){let p=l.header.match(d);if(p){let g=al(p[1]);if(g&&i-g>a)continue}}let u=l.header+(l.body.length>0?`
204
204
  `+l.body.join(`
205
205
  `):"");h.push(u)}let c=h.join(`
206
- `).trim();c?await $t.writeFile(e,c+`
207
- `,"utf8"):await $t.writeFile(e,"","utf8")}catch{}},Rd=async e=>{try{if(!await $t.pathExists(e))return;let n=async t=>{let o=await $t.readdir(t);for(let s of o){let i=_o.join(t,s);(await $t.stat(i)).isDirectory()?(await n(i),(await $t.readdir(i)).length===0&&await $t.remove(i)):s.endsWith(".log")&&await al(i)}};await n(e)}catch{}},Ir=(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 Ed=async(e,n,t)=>$o(async()=>{let o=J(jn,[]);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}),pe(jn,o)}),_d=async e=>{try{if(!await $t.pathExists(jn))return{total:0,context:0};let n=J(jn,[]);if(!Array.isArray(n))return{total:0,context:0};let t=n.find(o=>Object.keys(o)[0]===String(e));return t?t[String(e)]:{total:0,context:0}}catch{return{total:0,context:0}}};import wt from"fs-extra";import Or from"path";var ll=()=>Math.random().toString(36).substring(2)+Date.now().toString(36),oe=null,Gn=null,Lr=0,Ms=!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:[]},As=(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 wt.exists(Zt)&&await wt.exists(Jo)&&(await wt.ensureDir(Or.dirname(Zt)),await wt.move(Jo,Zt))}catch{}let n=Zt+".tmp",t=null;try{if(await wt.exists(n)){let s=(await wt.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 wt.rename(n,Zt)}catch{}}else try{await wt.remove(n)}catch{}}}catch{try{await wt.remove(n)}catch{}}if(!t)try{if(await wt.exists(Zt)){let s=(await wt.readFile(Zt,"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=As(a,e);if(Object.keys(a).length!==Object.keys(r).length&&(Ms=!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:As(c,e)}}}return{date:e,stats:{...In},history:{}}},ai=async()=>{if(!(!Ms||!oe))try{await wt.ensureDir(Or.dirname(Zt));let e=null;try{if(await wt.exists(Zt)){let s=(await wt.readFile(Zt,"utf8")).trim();s.startsWith("{")||s.startsWith("[")?e=JSON.parse(s):e=JSON.parse(Cs(s))}}catch{}if(e&&e.date===oe.date&&e.stats){for(let s in oe.stats)if(e.stats[s]!==void 0){if(Array.isArray(oe.stats[s])){let i=Array.isArray(e.stats[s])?e.stats[s]:[],a=oe.stats[s],r=new Map;for(let h of[...i,...a])h&&h.timestamp&&r.set(h.timestamp,h);oe.stats[s]=Array.from(r.values())}else if(typeof oe.stats[s]=="number")oe.stats[s]=Math.max(oe.stats[s],Number(e.stats[s])||0);else if(oe.stats[s]&&typeof oe.stats[s]=="object"){let i=e.stats[s]||{},a=oe.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={...oe.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];oe.history=As(s,oe.date||today)}else if(oe&&oe.history){let s=new Date().toISOString().split("T")[0];oe.history=As(oe.history,s)}oe.saveId=ll();let n=Zt+".tmp",t=qs(JSON.stringify(oe,null,2));await wt.writeFile(n,t,"utf8");let o=await wt.open(n,"r+");await wt.fsync(o),await wt.close(o),await wt.rename(n,Zt),Ms=!1,Lr=Date.now()}catch{}},Mo=()=>{if(Ms=!0,Gn)return;let e=Date.now(),n=Math.max(0,1500-(e-Lr));Gn=setTimeout(async()=>{await ai(),Gn=null},n),Gn.unref&&Gn.unref()},Od=async()=>{oe=await Co(),Ms&&Mo()},Ld=async()=>{Gn&&(clearTimeout(Gn),Gn=null),await ai()},Tn=async()=>{let e=new Date().toISOString().split("T")[0];if(!oe)oe=await Co();else if(oe.date!==e){let n=oe.date,t=oe.stats,o=oe.history||{};t&&(o[n]=t),oe={date:e,stats:{...In},history:As(o,e)},Ms=!0,await ai()}return oe&&oe.stats&&!Array.isArray(oe.stats.imageCalls)&&(oe.stats.imageCalls=[]),oe.stats},cl=async()=>{let e=new Date().toISOString().split("T")[0];oe||(oe=await Co()),oe.date!==e&&await Tn();let n=oe.history||{},t=As(n,e);oe.history=t;let o=oe.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),Mo()},Js={linesAdded:0,linesRemoved:0,toolSuccess:0,toolFailure:0,toolDenied:0},Kt=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))}Mo()},dl=async(e=1)=>{let n=new Date,t=n.toISOString().split("T")[0];oe||(oe=await Co()),oe.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=oe.history||{},d=oe.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},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:f}=d(),u=await Tn(),p;s.resetMode==="Custom"?p=await dl(s.resetDay||1):p=await cl();let g=0,y=0,m=0;if(h){g=u.providerRequests?.[r]||0;let w=u.models?.[r]||{};for(let b in w)y+=w[b]?.tokens||0;let x=p.models?.[r]||{};for(let b in x)m+=x[b]?.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}},Dr=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},Pr=(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 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},Fr=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=Pr(s.imageCalls,i);return r+o<=h},Nr=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=Pr(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}},Br=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}),Mo()};import jr from"puppeteer";import Hr from"fs";import Gr from"path";import Ur from"os";import Qs from"path";import vs from"fs";import{createRequire as fl}from"module";import{fileURLToPath as ul}from"url";var hl=fl(import.meta.url),Wr=Qs.dirname(ul(import.meta.url));function cs(){let e=Ur.platform(),n=Ur.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=Qs.resolve(Wr,"..","..",".puppeteerrc.cjs");if(vs.existsSync(i)||(i=Qs.resolve(Wr,"..",".puppeteerrc.cjs")),!vs.existsSync(i))return{};try{let a=hl(i),r=a.cacheDirectory,h=a.chrome?.version;if(r){if(process.env.PUPPETEER_CACHE_DIR=r,h){let l=Qs.join(r,"chrome",`${t}-${h}`,s,o);if(vs.existsSync(l))return{executablePath:l,cacheDirectory:r}}let d=l=>{if(!vs.existsSync(l))return null;try{let f=vs.readdirSync(l),u=[];for(let p of f){let g=Qs.join(l,p),y;try{y=vs.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 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}
206
+ `).trim();c?await Mt.writeFile(e,c+`
207
+ `,"utf8"):await Mt.writeFile(e,"","utf8")}catch{}},Ed=async e=>{try{if(!await Mt.pathExists(e))return;let n=async t=>{let o=await Mt.readdir(t);for(let s of o){let r=Eo.join(t,s);(await Mt.stat(r)).isDirectory()?(await n(r),(await Mt.readdir(r)).length===0&&await Mt.remove(r)):s.endsWith(".log")&&await ll(r)}};await n(e)}catch{}},vi=(e,n=4)=>{if(e.length<=1)return e;let t=e[0],o=e.slice(1),s=n*2,r=o.slice(s);return[t,...r]};var _d=async(e,n,t)=>_o(async()=>{let o=J(jn,[]);Array.isArray(o)||(o=[]);let s={total:n,context:t},r=o.findIndex(a=>Object.keys(a)[0]===String(e));r!==-1?o[r]={[String(e)]:s}:o.push({[String(e)]:s}),pe(jn,o)}),$d=async e=>{try{if(!await Mt.pathExists(jn))return{total:0,context:0};let n=J(jn,[]);if(!Array.isArray(n))return{total:0,context:0};let t=n.find(o=>Object.keys(o)[0]===String(e));return t?t[String(e)]:{total:0,context:0}}catch{return{total:0,context:0}}};import xt from"fs-extra";import Ii from"path";var cl=()=>Math.random().toString(36).substring(2)+Date.now().toString(36),oe=null,Gn=null,Oi=0,Cs=!1,vn={agent:0,background:0,search:0,toolSuccess:0,toolFailure:0,toolDenied:0,duration:0,tokens:0,cachedTokens:0,candidateTokens:0,linesAdded:0,linesRemoved:0,imageCalls:[]},Ms=(e,n)=>{if(!e)return{};let t=Object.keys(e),o=new Date(new Date(n).getTime()-720*60*60*1e3),s={};for(let r of t)new Date(r)>=o&&(s[r]=e[r]);return s},$o=async()=>{let e=new Date().toISOString().split("T")[0];try{!await xt.exists(en)&&await xt.exists(Xo)&&(await xt.ensureDir(Ii.dirname(en)),await xt.move(Xo,en))}catch{}let n=en+".tmp",t=null;try{if(await xt.exists(n)){let s=(await xt.readFile(n,"utf8")).trim(),r=null;if(s.startsWith("{")||s.startsWith("[")?r=JSON.parse(s):r=JSON.parse($s(s)),r&&r.date&&r.stats){t=r;try{await xt.rename(n,en)}catch{}}else try{await xt.remove(n)}catch{}}}catch{try{await xt.remove(n)}catch{}}if(!t)try{if(await xt.exists(en)){let s=(await xt.readFile(en,"utf8")).trim();s.startsWith("{")||s.startsWith("[")?t=JSON.parse(s):t=JSON.parse($s(s))}}catch{}let o=t;if(o){let s=o.stats||{...vn},r={...vn,...s};Array.isArray(r.imageCalls)||(r.imageCalls=[]);let a=o.history||{},i=Ms(a,e);if(Object.keys(a).length!==Object.keys(i).length&&(Cs=!0),o.date===e)return{...o,stats:r,history:i};{let h=o.date,d=r,c={...i};return h&&(c[h]=d),{date:e,stats:{...vn},history:Ms(c,e)}}}return{date:e,stats:{...vn},history:{}}},ir=async()=>{if(!(!Cs||!oe))try{await xt.ensureDir(Ii.dirname(en));let e=null;try{if(await xt.exists(en)){let s=(await xt.readFile(en,"utf8")).trim();s.startsWith("{")||s.startsWith("[")?e=JSON.parse(s):e=JSON.parse($s(s))}}catch{}if(e&&e.date===oe.date&&e.stats){for(let s in oe.stats)if(e.stats[s]!==void 0){if(Array.isArray(oe.stats[s])){let r=Array.isArray(e.stats[s])?e.stats[s]:[],a=oe.stats[s],i=new Map;for(let h of[...r,...a])h&&h.timestamp&&i.set(h.timestamp,h);oe.stats[s]=Array.from(i.values())}else if(typeof oe.stats[s]=="number")oe.stats[s]=Math.max(oe.stats[s],Number(e.stats[s])||0);else if(oe.stats[s]&&typeof oe.stats[s]=="object"){let r=e.stats[s]||{},a=oe.stats[s];for(let i in r)if(typeof r[i]=="number")a[i]=Math.max(a[i]||0,r[i]);else if(r[i]&&typeof r[i]=="object"){a[i]||(a[i]={});for(let h in r[i])if(typeof r[i][h]=="number")a[i][h]=Math.max(a[i][h]||0,r[i][h]);else if(r[i][h]&&typeof r[i][h]=="object"){a[i][h]||(a[i][h]={});for(let d in r[i][h])a[i][h][d]=Math.max(a[i][h][d]||0,r[i][h][d])}}}}}if(e&&e.history){let s={...oe.history||{}};for(let r in e.history)if(s[r])for(let a in s[r])if(a==="imageCalls"){let i=Array.isArray(e.history[r].imageCalls)?e.history[r].imageCalls:[],h=Array.isArray(s[r].imageCalls)?s[r].imageCalls:[],d=new Map;for(let c of[...i,...h])c&&c.timestamp&&d.set(c.timestamp,c);s[r].imageCalls=Array.from(d.values())}else typeof s[r][a]=="number"&&(s[r][a]=Math.max(s[r][a],Number(e.history[r][a])||0));else s[r]=e.history[r];oe.history=Ms(s,oe.date||today)}else if(oe&&oe.history){let s=new Date().toISOString().split("T")[0];oe.history=Ms(oe.history,s)}oe.saveId=cl();let n=en+".tmp",t=Gs(JSON.stringify(oe,null,2));await xt.writeFile(n,t,"utf8");let o=await xt.open(n,"r+");await xt.fsync(o),await xt.close(o),await xt.rename(n,en),Cs=!1,Oi=Date.now()}catch{}},Co=()=>{if(Cs=!0,Gn)return;let e=Date.now(),n=Math.max(0,1500-(e-Oi));Gn=setTimeout(async()=>{await ir(),Gn=null},n),Gn.unref&&Gn.unref()},Ld=async()=>{oe=await $o(),Cs&&Co()},Dd=async()=>{Gn&&(clearTimeout(Gn),Gn=null),await ir()},Sn=async()=>{let e=new Date().toISOString().split("T")[0];if(!oe)oe=await $o();else if(oe.date!==e){let n=oe.date,t=oe.stats,o=oe.history||{};t&&(o[n]=t),oe={date:e,stats:{...vn},history:Ms(o,e)},Cs=!0,await ir()}return oe&&oe.stats&&!Array.isArray(oe.stats.imageCalls)&&(oe.stats.imageCalls=[]),oe.stats},dl=async()=>{let e=new Date().toISOString().split("T")[0];oe||(oe=await $o()),oe.date!==e&&await Sn();let n=oe.history||{},t=Ms(n,e);oe.history=t;let o=oe.stats||{...vn},s={...vn};s.imageCalls=[],s.models={};let r=(a,i)=>{for(let h in a)if(h==="imageCalls")a.imageCalls=[...a.imageCalls||[],...i.imageCalls||[]];else if(h==="models"){let d=i.models||{};for(let c in d){a.models[c]||(a.models[c]={});for(let l in d[c]){a.models[c][l]||(a.models[c][l]={tokens:0,cachedTokens:0,candidateTokens:0});let f=a.models[c][l],u=d[c][l];f.tokens+=u.tokens||0,f.cachedTokens+=u.cachedTokens||0,f.candidateTokens+=u.candidateTokens||0}}}else typeof a[h]=="number"&&(a[h]+=i[h]||0)};r(s,o);for(let a in t)r(s,t[a]);return s},Lt=async(e,n)=>{e==="toolSuccess"?Xs.toolSuccess++:e==="toolFailure"?Xs.toolFailure++:e==="toolDenied"&&Xs.toolDenied++;let t=await Sn();t[e]!==void 0&&t[e]++,n&&e==="agent"&&(t.providerRequests||(t.providerRequests={}),t.providerRequests[n]=(t.providerRequests[n]||0)+1),Co()},Xs={linesAdded:0,linesRemoved:0,toolSuccess:0,toolFailure:0,toolDenied:0},Kt=async(e,n,t,o)=>{e==="linesAdded"?Xs.linesAdded+=n:e==="linesRemoved"&&(Xs.linesRemoved+=n);let s=await Sn();if(s[e]!==void 0&&(s[e]+=Math.floor(n)),t&&o&&(e==="tokens"||e==="cachedTokens"||e==="candidateTokens")){s.models||(s.models={}),s.models[t]||(s.models[t]={}),s.models[t][o]||(s.models[t][o]={tokens:0,cachedTokens:0,candidateTokens:0});let r=s.models[t][o];e==="tokens"&&(r.tokens+=Math.floor(n)),e==="cachedTokens"&&(r.cachedTokens+=Math.floor(n)),e==="candidateTokens"&&(r.candidateTokens+=Math.floor(n))}Co()},fl=async(e=1)=>{let n=new Date,t=n.toISOString().split("T")[0];oe||(oe=await $o()),oe.date!==t&&await Sn();let o=n.getFullYear(),s=n.getMonth();n.getDate()<e&&(s-=1,s<0&&(s=11,o-=1));let i=new Date(o,s,e).toISOString().split("T")[0],h=oe.history||{},d=oe.stats||{...vn},c={...vn};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],b=g[y][m];w.tokens+=b.tokens||0,w.cachedTokens+=b.cachedTokens||0,w.candidateTokens+=b.candidateTokens||0}}}else typeof f[p]=="number"&&(f[p]+=u[p]||0)};l(c,d);for(let f in h)f>=i&&f<t&&l(c,h[f]);return c},ar=async(e,n={})=>{let t=await Nt().catch(()=>({})),o=n.apiTier||t.apiTier||"Free",s=n.quotas||n.systemSettings?.quotas||t.quotas||{},r=s.providerBudgets||{},a=!!r.__useProvider,i=n.aiProvider||t.aiProvider||"Google",h=a&&!!r[i],d=()=>{if(h){let c=r[i];return{agentLimit:typeof c.agentLimit=="number"&&c.agentLimit>0?c.agentLimit:99999999,tokenLimit:typeof c.tokenLimit=="number"&&c.tokenLimit>0?c.tokenLimit:99999999999999,monthlyTokenLimit:typeof c.monthlyTokenLimit=="number"&&c.monthlyTokenLimit>0?c.monthlyTokenLimit:99999999999999}}return{agentLimit:s.agentLimit||99999999,tokenLimit:s.tokenLimit||99999999999999,monthlyTokenLimit:s.monthlyTokenLimit||99999999999999}};if(e==="agent"){let{agentLimit:c,tokenLimit:l,monthlyTokenLimit:f}=d(),u=await Sn(),p;s.resetMode==="Custom"?p=await fl(s.resetDay||1):p=await dl();let g=0,y=0,m=0;if(h){g=u.providerRequests?.[i]||0;let w=u.models?.[i]||{};for(let x in w)y+=w[x]?.tokens||0;let b=p.models?.[i]||{};for(let x in b)m+=b[x]?.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 ${i}`:"Daily Agent Request Limit Reached"}:y>=l?{allowed:!1,reason:h?`Daily Token Budget Exhausted for ${i}`:"Daily Token Budget Exhausted"}:m>=f?{allowed:!1,reason:h?`Monthly Token Budget Exhausted for ${i}`:"Monthly Token Budget Exhausted"}:{allowed:!0}}if(e==="background"){let c=await Sn();if(o==="Free"&&c.agent+c.background>=999999)return{allowed:!1,reason:"Free Tier Background Limit Exceeded"};let l=c.background<(s.backgroundLimit||999999);return{allowed:l,reason:l?void 0:"Background Request Limit Exceeded"}}if(e==="search"){let l=(await Sn()).search<(s.searchLimit||100);return{allowed:l,reason:l?void 0:"Search Quota Exceeded"}}return{allowed:!0}},Li=async(e,n={})=>(await ar(e,n)).allowed,lr=e=>{if(!e||e.length===0)return[];let t=[...e].sort((s,r)=>s.timestamp-r.timestamp),o=[];for(let s of t){if(o.length>0){let r=o[o.length-1];if(s.timestamp>=r.start&&s.timestamp<r.end){r.calls.push(s),r.spent+=s.cost;continue}}o.push({start:s.timestamp,end:s.timestamp+36e5,calls:[s],spent:s.cost})}return o},Di=(e,n)=>{if(!e||e.length===0)return .025;let o=lr(e);if(o.length===0)return .025;let s=[];for(let l of o){let f=.025;if(s.length>0){let 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 r=o[o.length-1];if(n<r.end)return s[s.length-1].limit;let a=s[s.length-1].limit,i=a,h=s[s.length-1].ratio,d=r.end,c=0;for(let l=s.length-1;l>=0&&s[l].ratio>=.8;l--)c++;for(;d<=n;){let l=.025;c>=2?l=.015:h>=.8?l=i===.015?.015:i:h<.4?l=Math.min(.025,i+.005):h>=.4&&h<.6?l=Math.min(.025,i+.004):l=Math.min(.025,i+.002),i=l,h=0,c=0,d+=36e5,a=l}return a},Pi=async e=>{let n=e.imageSettings||{keyType:"Default",quality:"Low-High"};if(n.keyType!=="Default")return!0;let o={Low:.001,"Low-High":.002,Medium:.008,"Medium-High":.01,High:.045,Ultra:.0488,Premium:.15}[n.quality]||.002,s=await Sn();s.imageCalls||(s.imageCalls=[]);let r=Date.now(),a=lr(s.imageCalls),i=0;if(a.length>0){let d=a[a.length-1];r>=d.start&&r<d.end&&(i=d.spent)}let h=Di(s.imageCalls,r);return i+o<=h},Fi=async()=>{let e=await Sn();e.imageCalls||(e.imageCalls=[]);let n=Date.now(),t=lr(e.imageCalls),o=[],s=0,r=0;if(t.length>0){let d=t[t.length-1];n>=d.start&&n<d.end&&(o=d.calls,s=d.spent,r=Math.max(0,Math.ceil((d.end-n)/(60*1e3))))}let a=Di(e.imageCalls,n),i=Math.max(0,a-s),h=s;return{totalSpent:s,remaining:i,activeCallsCount:o.length,nextResetMin:r,reclaimCost:h,limit:a}},Ni=async e=>{let n=e.imageSettings||{keyType:"Default",quality:"Low-High"},o={Low:.001,"Low-High":.002,Medium:.008,"Medium-High":.01,High:.045,Ultra:.0488,Premium:.1}[n.quality]||.002,s=await Sn();s.imageCalls||(s.imageCalls=[]),s.imageCalls.push({timestamp:Date.now(),cost:o}),Co()};import Wi from"puppeteer";import ji from"fs";import Hi from"path";import Bi from"os";import Js from"path";import As from"fs";import{createRequire as ul}from"module";import{fileURLToPath as hl}from"url";var pl=ul(import.meta.url),Ui=Js.dirname(hl(import.meta.url));function ls(){let e=Bi.platform(),n=Bi.arch(),t="",o="",s="";if(e==="win32")t=n==="x64"?"win64":"win32",o="chrome.exe",s=`chrome-${t}`;else if(e==="darwin"){t=n==="arm64"?"mac_arm":"mac";let a=n==="arm64"?"arm64":"x64";o="Google Chrome.app/Contents/MacOS/Google Chrome",s=`chrome-mac-${a}`}else if(e==="linux")t="linux",o="chrome",s="chrome-linux64";else return{};let r=Js.resolve(Ui,"..","..",".puppeteerrc.cjs");if(As.existsSync(r)||(r=Js.resolve(Ui,"..",".puppeteerrc.cjs")),!As.existsSync(r))return{};try{let a=pl(r),i=a.cacheDirectory,h=a.chrome?.version;if(i){if(process.env.PUPPETEER_CACHE_DIR=i,h){let l=Js.join(i,"chrome",`${t}-${h}`,s,o);if(As.existsSync(l))return{executablePath:l,cacheDirectory:i}}let d=l=>{if(!As.existsSync(l))return null;try{let f=As.readdirSync(l),u=[];for(let p of f){let g=Js.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(i);if(c)return{executablePath:c,cacheDirectory:i}}}catch{}return{}}var cr=async e=>{let{query:n,limit:t=5,aiMode:o=!1}=O(e);if(!n)return'ERROR: Missing "query" argument for web_search.';let s=3,r=null;if(o){let a=`Query: ${n}
208
208
 
209
209
  RESPONSE RULES:
210
210
  - ANSWER CONCISELY WITH REQUIRED DETAILS UNDER 300 WORDS.
@@ -219,34 +219,34 @@ 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 jr.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(_=>setTimeout(_,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 _=Array.from(document.querySelectorAll('.message:not(.user), .answer-text, .llm-content, [data-type="answer"]')),k="";if(_.length>0&&(k=_.map(ne=>ne.innerText.trim()).filter(Boolean).join(`
222
+ - DO NOT INCLUDE ANY TEXT, NOTES, OR EXPLANATIONS AFTER THE SOURCES SECTION.`;for(let i=1;i<=s;i++){let h=null;try{let d=ls();h=await Wi.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=i===1?Math.random()*1e3+500:Math.random()*2e3+1e3;await new Promise(_=>setTimeout(_,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 _=Array.from(document.querySelectorAll('.message:not(.user), .answer-text, .llm-content, [data-type="answer"]')),k="";if(_.length>0&&(k=_.map(ne=>ne.innerText.trim()).filter(Boolean).join(`
223
223
 
224
- `)),k||(k=document.body.innerText),k.includes("anomaly"))throw new Error("ANOMALY_DETECTED");let C=!!document.querySelector('.spinner, .loading, .typing, .streaming, [data-streaming="true"], [data-state="loading"], svg.animate-spin, circle[cx], div[class*="spin"]'),I=_[0]||document.body,D=I?I.innerText.trim():"",B=/^(?:[✓✔]\s*)?Finished/i.test(D)||!!(I&&I.querySelector(".status-finished, .finished")),N=!C&&(B||k.includes("Sources:")&&!C),Y={};return document.querySelectorAll("a[href]").forEach(ne=>{let Ie=ne.getAttribute("href")||ne.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 U=ne.innerText.trim();U&&(Y[U]=Ie),ne.textContent=Ie}}),{isFinished:N,text:k,hrefMap:Y}}),!(u&&u.isFinished));)await new Promise(_=>setTimeout(_,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,b="";if(y.includes("Sources:")){let _=y.split("Sources:");x=_[0],b=_.slice(1).join("Sources:")}let E=[];for(let _ of x.split(`
224
+ `)),k||(k=document.body.innerText),k.includes("anomaly"))throw new Error("ANOMALY_DETECTED");let C=!!document.querySelector('.spinner, .loading, .typing, .streaming, [data-streaming="true"], [data-state="loading"], svg.animate-spin, circle[cx], div[class*="spin"]'),I=_[0]||document.body,D=I?I.innerText.trim():"",B=/^(?:[✓✔]\s*)?Finished/i.test(D)||!!(I&&I.querySelector(".status-finished, .finished")),N=!C&&(B||k.includes("Sources:")&&!C),Y={};return document.querySelectorAll("a[href]").forEach(ne=>{let Ie=ne.getAttribute("href")||ne.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 U=ne.innerText.trim();U&&(Y[U]=Ie),ne.textContent=Ie}}),{isFinished:N,text:k,hrefMap:Y}}),!(u&&u.isFinished));)await new Promise(_=>setTimeout(_,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 b=y,x="";if(y.includes("Sources:")){let _=y.split("Sources:");b=_[0],x=_.slice(1).join("Sources:")}let E=[];for(let _ of b.split(`
225
225
  `)){let k=_.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")||E.push(_))}let R=E.join(`
226
226
  `).replace(/^(?:[\+\-]?\d+\s*)+/i,"").replace(/\n{3,}/g,`
227
227
 
228
- `).trim(),S=_=>!_||_.includes("search.brave.com")||_.includes("youtube.com")||_.includes("youtu.be"),T="";if(b){let _=b.match(/https?:\/\/[^\s\)\>]+/g)||[],k=[];for(let I of _){let D=I.replace(/[\.\,\;]+$/,""),B=Object.keys(m).find(N=>N.startsWith(D)||D.startsWith(N));B&&m[B]&&(D=m[B]),S(D)||k.push(D)}Object.values(m).forEach(I=>{!S(I)&&!k.includes(I)&&k.push(I)});let C=Array.from(new Set(k));C.length>0&&(T=`Sources:
228
+ `).trim(),S=_=>!_||_.includes("search.brave.com")||_.includes("youtube.com")||_.includes("youtu.be"),T="";if(x){let _=x.match(/https?:\/\/[^\s\)\>]+/g)||[],k=[];for(let I of _){let D=I.replace(/[\.\,\;]+$/,""),B=Object.keys(m).find(N=>N.startsWith(D)||D.startsWith(N));B&&m[B]&&(D=m[B]),S(D)||k.push(D)}Object.values(m).forEach(I=>{!S(I)&&!k.includes(I)&&k.push(I)});let C=Array.from(new Set(k));C.length>0&&(T=`Sources:
229
229
  `+C.map(I=>`- ${I}`).join(`
230
230
  `))}let $=R+(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,Hr.writeFileSync(Gr.join(fn,"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 jr.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"),b=m.querySelector(".result__snippet"),E=x?x.href:"";E.includes("uddg=")&&(E=decodeURIComponent(E.split("uddg=")[1].split("&")[0]));let R=x?x.innerText.trim():"No Title",S=b?b.innerText.trim():"No Snippet";return`${w+1}. ${R}
234
+ ${$}`}catch(d){if(r=d,ji.writeFileSync(Hi.join(fn,"web_tools","search","ai_mode","ERROR.txt"),d.message),h&&await h.close(),i<s){let c=Math.pow(2,i)*1e3;await new Promise(l=>setTimeout(l,c))}}}}for(let a=1;a<=s;a++){let i=null;try{let h=ls();i=await Wi.launch({headless:!0,executablePath:h.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let d=await i.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 b=m.querySelector(".result__a"),x=m.querySelector(".result__snippet"),E=b?b.href:"";E.includes("uddg=")&&(E=decodeURIComponent(E.split("uddg=")[1].split("&")[0]));let R=b?b.innerText.trim():"No Title",S=x?x.innerText.trim():"No Snippet";return`${w+1}. ${R}
235
235
  Source: ${E}
236
- Snippet: ${S}`}),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: ${S}`}),t);if(f.length===0){if((await d.evaluate(()=>document.body.innerText)).includes("anomaly"))throw new Error("ANOMALY_DETECTED");return await i.close(),`No results found for query: [${n}].`}let u=f.join(`
237
237
 
238
- `);return await r.close(),`${o?`AI Mode temporarily failed, used Standard search.
238
+ `);return await i.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(),Hr.writeFileSync(Gr.join(fn,"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 pl from"puppeteer";import ml from"turndown";import{gfm as gl}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 pl.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(b=>b.remove());let y=document.createNodeIterator(document.body,NodeFilter.SHOW_COMMENT),m;for(;m=y.nextNode();)m.remove();for(document.querySelectorAll("*").forEach(b=>{let E=b.attributes;for(let R=E.length-1;R>=0;R--){let S=E[R].name;S!=="href"&&S!=="src"&&b.removeAttribute(S)}});document.querySelector("div, span");)document.querySelectorAll("div, span").forEach(b=>{b.parentNode&&b.replaceWith(...b.childNodes)});document.querySelectorAll("br").forEach(b=>{b.replaceWith(document.createTextNode(`
242
+ ${u}`}catch(h){if(r=h,i&&await i.close(),ji.writeFileSync(Hi.join(fn,"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: ${r.message}`};import ml from"puppeteer";import gl from"turndown";import{gfm as yl}from"turndown-plugin-gfm";var dr=async e=>{let n=e;if(typeof e=="object"&&e!==null)n=e.url||e.targetUrl||e.href||"";else if(typeof e=="string"){let r=e.match(/url\s*=\s*["'](.*)["']/);n=r?r[1]:e}let t=typeof n=="string"?n.trim():"";if(!t)return"ERROR: No target URL provided.";let o=3,s=null;for(let r=1;r<=o;r++){let a=null;try{let i=ls();a=await ml.launch({headless:!0,executablePath:i.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=r===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(x=>x.remove());let y=document.createNodeIterator(document.body,NodeFilter.SHOW_COMMENT),m;for(;m=y.nextNode();)m.remove();for(document.querySelectorAll("*").forEach(x=>{let E=x.attributes;for(let R=E.length-1;R>=0;R--){let S=E[R].name;S!=="href"&&S!=="src"&&x.removeAttribute(S)}});document.querySelector("div, span");)document.querySelectorAll("div, span").forEach(x=>{x.parentNode&&x.replaceWith(...x.childNodes)});document.querySelectorAll("br").forEach(x=>{x.replaceWith(document.createTextNode(`
243
243
 
244
- `))});let x=()=>{let b=!1;document.querySelectorAll("*").forEach(E=>{E.childNodes.length===0&&!E.innerText.trim()&&(E.remove(),b=!0)}),b&&x()};return x(),document.body.innerHTML});if(!c)throw new Error("EMPTY_RENDER_RESULT");let l=c.replace(/<br\s*\/?>/gi,`
244
+ `))});let b=()=>{let x=!1;document.querySelectorAll("*").forEach(E=>{E.childNodes.length===0&&!E.innerText.trim()&&(E.remove(),x=!0)}),x&&b()};return b(),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 ml({headingStyle:"atx",codeBlockStyle:"fenced"});f.use(gl);let u=f.turndown(l).replace(/\.\s*\n/g,`
249
+ `).trim(),f=new gl({headingStyle:"atx",codeBlockStyle:"fenced"});f.use(yl);let u=f.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
 
@@ -254,93 +254,93 @@ ${u}`}catch(h){if(i=h,r&&await r.close(),Hr.writeFileSync(Gr.join(fn,"web_tools"
254
254
 
255
255
  ${p}${u.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 yl=4*(1024*2),ui=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=J(en,{});c[d]||(c[d]=[]),c[d].push(i),pe(en,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=J(Pt,[]).map(l=>(l.score===void 0&&(l.score=.5),l));if(s==="add"){if(!i)return"ERROR: Missing 'content' for memory addition.";let l=new Date,f=`${l.getDate()}/${l.getMonth()+1}/${l.getFullYear()}`,u=i.includes("[Saved on:")?i:`${i.trim()} [Saved on: ${f}]`,p=yl,g=c.reduce((x,b)=>x+(b.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),pe(Pt,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,pe(Pt,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.`:(pe(Pt,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 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 vr(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 Ao from"fs";import qr from"path";var Zs=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),f=!isNaN(c),u=d||1,p=c||(d?d+800:800);if(!t)return'ERROR: Missing "path" argument for view_file.';let g=qr.resolve(process.cwd(),t);try{if(!Ao.existsSync(g))return`ERROR: File [${t}] does not exist.`;if(Ao.statSync(g).isDirectory())return`ERROR: Path [${t}] is a directory. Use list_files instead.`;let m=qr.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=Ao.readFileSync(g).toString("base64"),B=x[m];return{text:`[BINARY FILE]: ${t} (${B}) - Loaded as multimodal part.`,binaryPart:{inlineData:{data:D,mimeType:B}}}}let b=Ao.readFileSync(g,"utf8");b.startsWith("\uFEFF")&&(b=b.slice(1)),b=b.replace(/\r\n/g,`
257
+ [TRUNCATED AT 50K CHARS]`:""}`}catch(i){if(s=i,a&&await a.close(),r<o){let h=Math.pow(2,r)*1e3;await new Promise(d=>setTimeout(d,h))}}}return`ERROR: Scrape failed after ${o+1} attempts. Last error: ${s.message}`};var wl=4*(1024*2),fr=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"),r=t("content"),a=t("content-new"),i=t("content-old"),h=t("id"),d=t("chat-id")||n.chatId||n.sessionId||"default-session";if(o==="temp"){if(!r)return"ERROR: Missing 'content' for temp memory.";let c=J(tn,{});c[d]||(c[d]=[]),c[d].push(r),pe(tn,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=J(Ft,[]).map(l=>(l.score===void 0&&(l.score=.5),l));if(s==="add"){if(!r)return"ERROR: Missing 'content' for memory addition.";let l=new Date,f=`${l.getDate()}/${l.getMonth()+1}/${l.getFullYear()}`,u=r.includes("[Saved on:")?r:`${r.trim()} [Saved on: ${f}]`,p=wl,g=c.reduce((b,x)=>b+(x.memory?.length||0),0);for(;c.length>0&&g+u.length>p;){let b=c.shift();g-=b.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),pe(Ft,c),`SUCCESS: Memory added with ID [${w.id}] and score [${w.score}]. (Vault Size: ${g+u.length} chars)`}if(s==="update"){let l=h||i,f=a||r;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,pe(Ft,c),`SUCCESS: Memory [${l}] updated.`}if(s==="delete"){let l=h||r;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.`:(pe(Ft,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 ur=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 Ai(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 Gi from"path";var Qs=async(e,n={})=>{let{path:t,StartLine:o,EndLine:s,start_line:r,end_line:a,startLine:i,endLine:h}=O(e),d=parseInt(o||r||i),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=Gi.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=Gi.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 b={".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(b[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"),B=b[m];return{text:`[BINARY FILE]: ${t} (${B}) - Loaded as multimodal part.`,binaryPart:{inlineData:{data:D,mimeType:B}}}}let x=Mo.readFileSync(g,"utf8");x.startsWith("\uFEFF")&&(x=x.slice(1)),x=x.replace(/\r\n/g,`
258
258
  `).replace(/\r/g,`
259
- `);let E=b.split(`
259
+ `);let E=x.split(`
260
260
  `),R=E.length;!l&&!f&&R>800&&(u=1,p=50);let S=Math.max(0,u-1),T=Math.min(R,p),$=E.slice(S,T),_=`File: [${t}] (Showing lines ${S+1}-${T} of ${R}).`,k=$.map((C,I)=>`${String(S+I+1).padStart(4)}: ${C.trimEnd()}`).join(`
261
261
  `);return`${_}
262
262
 
263
- ${k}`}catch(y){let m=y instanceof Error?y.message:String(y);return`ERROR: Failed to read file [${t}]: ${m}`}};import Is from"fs";import zr 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,`
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 qi from"path";var hr=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=zr.resolve(process.cwd(),t),i=zr.dirname(s);try{await ht.recordFileChange(s);let a="";if(Is.existsSync(s))try{a=`Old File contents:
266
- ${Is.readFileSync(s,"utf8").split(/\r?\n/).map((E,R)=>`${R+1} | ${E}`).join(`
265
+ `);let s=qi.resolve(process.cwd(),t),r=qi.dirname(s);try{await pt.recordFileChange(s);let a="";if(vs.existsSync(s))try{a=`Old File contents:
266
+ ${vs.readFileSync(s,"utf8").split(/\r?\n/).map((E,R)=>`${R+1} | ${E}`).join(`
267
267
  `)}
268
268
 
269
269
  `}catch{a=`[Note: Could not read existing file for reversal reference]
270
270
 
271
- `}Is.existsSync(i)||Is.mkdirSync(i,{recursive:!0});let h=(x=>x.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
271
+ `}vs.existsSync(r)||vs.mkdirSync(r,{recursive:!0});let h=(b=>b.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
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");Is.writeFileSync(s,d,"utf8");let f=Is.readFileSync(s,"utf8"),u=Buffer.byteLength(f,"utf8"),p=f.split(/\r?\n/),g=p.length;if(u===0&&l>0)return f=null,`ERROR: CRITICAL FAILURE: Verification failed. File [${t}] is empty on disk!`;let y="";if(g<=100)y=p.join(`
276
- `);else{let x=p.slice(0,50).join(`
277
- `),b=p.slice(-50).join(`
278
- `);y=`${x}
275
+ `,c=d.split(/\r?\n/).length,l=Buffer.byteLength(d,"utf8");vs.writeFileSync(s,d,"utf8");let f=vs.readFileSync(s,"utf8"),u=Buffer.byteLength(f,"utf8"),p=f.split(/\r?\n/),g=p.length;if(u===0&&l>0)return f=null,`ERROR: CRITICAL FAILURE: Verification failed. File [${t}] is empty on disk!`;let y="";if(g<=100)y=p.join(`
276
+ `);else{let b=p.slice(0,50).join(`
277
+ `),x=p.slice(-50).join(`
278
+ `);y=`${b}
279
279
 
280
280
  ... [${g-100} lines truncated] ...
281
281
 
282
- ${b}`}f=null;let{systemSettings:m}=await Ft(),w=`SUCCESS: File [${t}] saved.
282
+ ${x}`}f=null;let{systemSettings:m}=await Nt(),w=`SUCCESS: File [${t}] saved.
283
283
  - Stats: [${g} lines, ${(u/1024).toFixed(1)} KB]
284
284
  ${a}- Content Preview:
285
285
 
286
- ${y}`;if(m?.compressToolResults&&g>60){let x=d.split(/\r?\n/),b=x.slice(0,25).join(`
286
+ ${y}`;if(m?.compressToolResults&&g>60){let b=d.split(/\r?\n/),x=b.slice(0,25).join(`
287
287
  `)===p.slice(0,25).join(`
288
- `),E=x.slice(-25).join(`
288
+ `),E=b.slice(-25).join(`
289
289
  `)===p.slice(-25).join(`
290
- `);b&&E&&(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 wi from"fs";import Ml from"path";import wl from"os";var pn=e=>typeof e!="string"?e:e.length>12?(e+"").replace("",""):e,Kr=(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())}),pn(s.join(`
293
- `))},kf=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()},Sf=(e,n=40)=>{let t=An.replaceAll("\\\\","\\");if(e=e.replace(wl.homedir(),"~").replace(t,"FluxFlow").replaceAll("\\","/"),!e||e.length<=n)return pn(e);let o=Math.floor((n-3)/2);return pn(e.substring(0,o)+"..."+e.substring(e.length-o).replaceAll("\\","/"))},vo=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}},xl=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===`
290
+ `);x&&E&&(w=`[[SAME]]
291
+ ${w}`)}return w}catch(a){let i=a instanceof Error?a.message:String(a);return`ERROR: Failed to write file [${t}]: ${i}`}};import yr from"fs";import Al from"path";import xl from"os";var pn=e=>typeof e!="string"?e:e.length>12?(e+"").replace("",""):e,zi=(e,n)=>{if(!e)return"";let t=/\x1B\[[0-?]*[ -/]*[@-~]/g,o=e.split(`
292
+ `),s=[];if(n<=5)return e;let r=a=>a.replace(t,"").length;return o.forEach(a=>{if(r(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=r(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=r(d);else if(t.test(u))s.push(u),d=f,c=r(d);else{let y=u;for(;r(y)>n&&n>10;)s.push(y.substring(0,n)),y=y.substring(n);d=y,c=r(d)}else d+=u,c+=g}),(d.trimEnd().length>0||d===f)&&s.push(d.trimEnd())}),pn(s.join(`
293
+ `))},Sf=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()},Tf=(e,n=40)=>{let t=Mn.replaceAll("\\\\","\\");if(e=e.replace(xl.homedir(),"~").replace(t,"FluxFlow").replaceAll("\\","/"),!e||e.length<=n)return pn(e);let o=Math.floor((n-3)/2);return pn(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),r=["searchContent","search_content","replaceContent","replace_content","content_to_replace","searchBlock","search_block"],a=["newContent","new_content","content_to_add","newBlock","new_block"],i=(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}=i(h,r,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}},bl=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}},Io=(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
- `),i=m=>m.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
297
+ `),r=m=>m.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
298
298
  `).replace(/\r/g,`
299
- `),a=m=>m.match(/^\s*/)[0],r=m=>{let w=m.split(`
300
- `).filter(b=>b.trim()!=="");if(w.length===0)return"";let x=a(w[0]);for(let b of w){let E=a(b);E.length<x.length&&(x=E)}return x},h=(m,w,x="")=>{if(!m||w===void 0)return m;let E=/^\t/m.test(w)?" ":" ",R=C=>C.split(`
301
- `).find(I=>I.trim()!=="")??"",S=R(w).match(/^\s*/)[0].length,T=R(m).match(/^\s*/)[0].length,$=S-T,_=(x.match(/^\s*/)||[""])[0].length;return m.split(`
299
+ `),a=m=>m.match(/^\s*/)[0],i=m=>{let w=m.split(`
300
+ `).filter(x=>x.trim()!=="");if(w.length===0)return"";let b=a(w[0]);for(let x of w){let E=a(x);E.length<b.length&&(b=E)}return b},h=(m,w,b="")=>{if(!m||w===void 0)return m;let E=/^\t/m.test(w)?" ":" ",R=C=>C.split(`
301
+ `).find(I=>I.trim()!=="")??"",S=R(w).match(/^\s*/)[0].length,T=R(m).match(/^\s*/)[0].length,$=S-T,_=(b.match(/^\s*/)||[""])[0].length;return m.split(`
302
302
  `).map((C,I)=>{if(C.trim()===""&&I!==0)return"";let D=C.match(/^\s*/)[0].length,B=Math.max(0,D+$);return I===0&&(B=Math.max(0,B-_)),E.repeat(B)+C.trimStart()}).join(`
303
- `)},d=[];for(let m=0;m<n.length;m++){let w=n[m],x=(w.replace||"").trim(),b=i(w.new||"");if(x.startsWith("^LINE:")&&x.endsWith("$")){let _=x.slice(6,-1).trim().split(".."),k=parseInt(_[0]),C=_[1]!==void 0?parseInt(_[1]):k;if(!isNaN(k)&&!isNaN(C)){let I=s.split(`
303
+ `)},d=[];for(let m=0;m<n.length;m++){let w=n[m],b=(w.replace||"").trim(),x=r(w.new||"");if(b.startsWith("^LINE:")&&b.endsWith("$")){let _=b.slice(6,-1).trim().split(".."),k=parseInt(_[0]),C=_[1]!==void 0?parseInt(_[1]):k;if(!isNaN(k)&&!isNaN(C)){let I=s.split(`
304
304
  `);if(k<1||k>I.length||C<k||C>I.length){d.push({index:m,success:!1,error:`Block ${m+1}: Line range ^LINE:${k}..${C}$ out of bounds (file has ${I.length} lines).`});continue}let B=I.slice(k-1,C).join(`
305
- `),N=0;for(let Y=0;Y<k-1;Y++)N+=I[Y].length+1;d.push({index:m,success:!0,startPos:N,firstMatchContent:B,content_to_add:b});continue}}let E=i(w.replace||"");if(E===""&&b===""){d.push({index:m,success:!1,error:`Block ${m+1}: Empty replace and add content.`});continue}let R=E.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),S=null;if(E!==""&&s.includes(E))S=new RegExp(R,"g");else{let $=E.split(`
306
- `).map(_=>_.trim()).filter(_=>_.length>0).map(_=>_.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\s+/g,"\\s*"));if($.length>0){let _=$.join("\\s*");try{S=new RegExp(_,"g")}catch{S=new RegExp(R,"g")}}else S=new RegExp(R,"g")}let T=[...s.matchAll(S)];if(T.length===0&&E!==""){let $=xl(E);$&&(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:b})}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,b=w+u,E=x+p,R=f.lastIndexOf(`
308
- `,b)+1,S=f.substring(R,b),T=h(m.content_to_add,m.firstMatchContent,S),$=f.split(`
305
+ `),N=0;for(let Y=0;Y<k-1;Y++)N+=I[Y].length+1;d.push({index:m,success:!0,startPos:N,firstMatchContent:B,content_to_add:x});continue}}let E=r(w.replace||"");if(E===""&&x===""){d.push({index:m,success:!1,error:`Block ${m+1}: Empty replace and add content.`});continue}let R=E.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),S=null;if(E!==""&&s.includes(E))S=new RegExp(R,"g");else{let $=E.split(`
306
+ `).map(_=>_.trim()).filter(_=>_.length>0).map(_=>_.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\s+/g,"\\s*"));if($.length>0){let _=$.join("\\s*");try{S=new RegExp(_,"g")}catch{S=new RegExp(R,"g")}}else S=new RegExp(R,"g")}let T=[...s.matchAll(S)];if(T.length===0&&E!==""){let $=bl(E);$&&(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:x})}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],b=c[m+1];w.startPos+w.firstMatchContent.length>b.startPos&&(w.success=!1,w.error=`Block ${w.index+1}: Overlaps with another block.`,b.success=!1,b.error=`Block ${b.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,b=s.substring(0,w).split(`
307
+ `).length,x=w+u,E=b+p,R=f.lastIndexOf(`
308
+ `,x)+1,S=f.substring(R,x),T=h(m.content_to_add,m.firstMatchContent,S),$=f.split(`
309
309
  `),_=[];for(let D=Math.max(0,E-4);D<E-1;D++)_.push({num:D+1,text:$[D]});let k=m.firstMatchContent.split(`
310
- `),C=[],I=E+k.length-1;for(let D=I;D<Math.min($.length,I+3);D++)C.push({num:D+1,text:$[D]});l.set(m,{success:!0,index:m.index,oldContent:m.firstMatchContent,newContent:T,originalStartLine:x,finalStartLine:E,contextBefore:_,contextAfter:C}),f=f.substring(0,b)+T+f.substring(b+m.firstMatchContent.length),u+=T.length-m.firstMatchContent.length,p+=T.split(`
310
+ `),C=[],I=E+k.length-1;for(let D=I;D<Math.min($.length,I+3);D++)C.push({num:D+1,text:$[D]});l.set(m,{success:!0,index:m.index,oldContent:m.firstMatchContent,newContent:T,originalStartLine:b,finalStartLine:E,contextBefore:_,contextAfter:C}),f=f.substring(0,x)+T+f.substring(x+m.firstMatchContent.length),u+=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(b=>b.index===m);y.push({success:!1,error:x?x.error:`Block ${m+1}: Unknown error.`})}}return{content:f,results:y}},Oo=(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]
312
+ `).length}let y=[];for(let m=0;m<n.length;m++){let w=g.filter(b=>b.index===m);if(w.length>0)for(let b of w)l.has(b)&&y.push(l.get(b));else{let b=d.find(x=>x.index===m);y.push({success:!1,error:b?b.error:`Block ${m+1}: Unknown error.`})}}return{content:f,results:y}},Io=(e,n,t,o=8,s=!1)=>{if(!t||t.length===0)return"";let r=e.split(/\r?\n/),a=n.split(/\r?\n/),i=Math.max(r.length,a.length,1),h=Math.max(4,String(i).length),d=g=>String(g).padStart(h," "),c=`[DIFF_START]
313
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
314
  `,f++;else{let T=u,$=T.originalStartLine+T.oldContent.split(`
315
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
316
  `,f++;for(c+=`[UI_CONTEXT] ${l}
317
317
  `,f=Math.max(f,m-4);f<m-1;)c+=`[UI_CONTEXT] ${d(f+1)} |${a[f]||""}
318
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]||"",b=g.oldContent.split(`
320
- `),E=x.match(/^\s*/),R=E?E[0]:"";b.forEach((T,$)=>{let _=T;if(b.length===1&&x.trim().length>0&&x.includes(T.trim()))_=x;else if($===0){let k=T.match(/^\s*/);(k?k[0]:"").length<R.length&&x.includes(T.trim())&&(_=R+T.trimStart())}c+=`-${d(g.originalStartLine+$)} |${_}
319
+ `,f++}let w=g.originalStartLine-1,b=r[w]||"",x=g.oldContent.split(`
320
+ `),E=b.match(/^\s*/),R=E?E[0]:"";x.forEach((T,$)=>{let _=T;if(x.length===1&&b.trim().length>0&&b.includes(T.trim()))_=b;else if($===0){let k=T.match(/^\s*/);(k?k[0]:"").length<R.length&&b.includes(T.trim())&&(_=R+T.trimStart())}c+=`-${d(g.originalStartLine+$)} |${_}
321
321
  `});let S=f;if(g.finalStartLine!==void 0)S=g.finalStartLine-1+(g.newContent?g.newContent.split(`
322
- `).length:0);else{let T=g.originalStartLine+b.length-1,$=i[T]||null;if($!==null){let _=y<p.length-1?(p[y+1].originalStartLine||a.length)+10:a.length;for(let k=f;k<_;k++){if(a[k]===$){S=k;break}k===a.length-1&&(S=a.length)}}else S=a.length}for(;f<S;)c+=`+${d(f+1)} |${a[f]||""}
322
+ `).length:0);else{let T=g.originalStartLine+x.length-1,$=r[T]||null;if($!==null){let _=y<p.length-1?(p[y+1].originalStartLine||a.length)+10:a.length;for(let k=f;k<_;k++){if(a[k]===$){S=k;break}k===a.length-1&&(S=a.length)}}else S=a.length}for(;f<S;)c+=`+${d(f+1)} |${a[f]||""}
323
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
324
  `,f++}if(s){let g=`[DIFF_START]
325
325
  `,y=c.substring(g.length),m=`[UI_CONTEXT] ${l}
326
- `,x=y.split(m).map(b=>b.split(`
326
+ `,b=y.split(m).map(x=>x.split(`
327
327
  `).filter(R=>R.trim()!=="").length>45?`[[VERIFIED]]
328
- ${b}
329
- [[/VERIFIED]]`:b);c=g+x.join(m)}return c+="[DIFF_END]",pn(c)},bl=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?pn(s.substring(0,i).trim()):"",r=pn(i!==-1?s.substring(i+1):s);return{isR:t,isA:o,num:a,content:r}},kl=(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},Yr=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]=kl(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--},qn=new Map,ds=new Map,Vr=200,mi=6,yi=(e,n)=>{n.set(e.key,e),e.type==="chunk"&&e.blocks&&e.blocks.forEach(t=>yi(t,n))},Tf=(e,n)=>{if(!e)return{completed:[],active:[]};let t=`${e.id}-${e.text?.length||0}-${n}-${e.isStreaming}-${e.workedDuration||0}`;if(!e.isStreaming&&qn.has(t))return qn.get(t);let o=pn(Cl(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=pn(y),b={...m};return typeof b.pairContent=="string"&&(b.pairContent=pn(b.pairContent)),Array.isArray(b.wrappedLines)&&(b.wrappedLines=b.wrappedLines.map(pn)),{key:p,isStreamingMsg:!!e.isStreaming,workedDuration:e.workedDuration,type:g,text:x,msg:g==="full-message"?e:void 0,...b}};if(o.includes("- Content Preview:")){let p="",g=o.match(/File\s+\[(.*?)\]/i);g&&(p=g[1].split(".").pop().toLowerCase());let b=((o.split("- Content Preview:")[1]||"").split("[SYSTEM] Check the content preview for verification [/SYSTEM]")[0]?.trim()||"").split(`
330
- `).map(k=>k.replace(/\r$/,"")),E=String(b.length).length,R=[],S=null,T=[],$=()=>{if(!T.length)return;let k=T;T=[],R.push(k.length===1?k[0]:{key:`${k[0].key}-chunk`,type:"chunk",blocks:k})},_=n-(E+6);return b.forEach((k,C)=>{let I=C===b.length-1,D=Kr(k,_).split(`
331
- `),B=a(`${e.id||Date.now()}-write-line-${C}`,"write-line",k,{gutterWidth:E,lineNum:C+1,isFirstLine:C===0,isLastLine:I,extension:p,wrappedLines:D});I&&e.isStreaming?($(),S=B):(T.push(B),T.length>=mi&&$())}),$(),{completed:R,active:S?[S]:[]}}if(o.includes("[DIFF_START]")){let p=o.match(/\[DIFF_START\]([\s\S]*?)(?:\[DIFF_END\]|$)/),y=(p?p[1].trim():"").split(`
332
- `).map(S=>S.replace(/\r$/,"")),m=y.map(S=>({line:S,parsed:bl(S),pairContent:null})),w=[];for(let S=0;S<m.length;S++){let T=m[S];T.parsed&&(T.parsed.isR||T.parsed.isA)?w.push(T):w.length>0&&(Yr(w),w=[])}w.length>0&&Yr(w);let x=[],b=null,E=[],R=()=>{if(!E.length)return;let S=E;E=[],x.push(S.length===1?S[0]:{key:`${S[0].key}-chunk`,type:"chunk",blocks:S})};return y.forEach((S,T)=>{let $=T===y.length-1,_=m[T].parsed,k=null;_&&(k=Kr(_.content,n-17).split(`
333
- `));let C=a(`${e.id||Date.now()}-diff-${T}`,"diff-line",S,{isFirstLine:T===0,isLastLine:$,pairContent:m[T].pairContent,wrappedLines:k});$&&e.isStreaming?(R(),b=C):(E.push(C),E.length>=mi&&R())}),R(),{completed:x,active:b?[b]:[]}}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 qn.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>=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;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="",b=0,E=0;p.forEach((R,S)=>{let T=S===p.length-1,$=R.trim().startsWith("|"),_=R.trim().startsWith("```");if(w){if(R.includes("</think>")||R.includes("<channel|>")||R.includes("</thought>")){let k=R.split(/(?:<\/(think|thought|thoughts)>|<channel\|>)/i),C=k[0]||"",I=k.slice(2).join("");C&&f(a(`${e.id}-think-${S}`,"think-line",C,{}),T&&!I),l(),r.push({key:`${e.id}-think-footer-${S}`,type:"think-footer-padding",text:""}),w=!1,I&&I.trim()&&f(a(`${e.id}-${S}`,"agent-line",I,{}),T)}else f(a(`${e.id}-think-${S}`,"think-line",R,{}),T);return}if(!m&&(R.includes("<think>")||R.includes("<|channel>thought")||R.includes("<thought>")||R.startsWith("<think")||R.startsWith("<|channel>thought"))){l(),g&&(r.push(a(`${e.id}-table-${S}`,"table",y.join(`
336
- `),{isStreaming:!1})),g=!1,y=[]),r.push(a(`${e.id}-think-header-${S}`,"think-header","")),w=!0;let k=R.replace(/^(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought\s*)\r?\n?/i,"");if(k.includes("</think>")||k.includes("<channel|>")||k.includes("</thought>")){let C=k.split(/(?:<\/(think|thought|thoughts)>|<channel\|>)/i),I=C[0]||"",D=C.slice(2).join("");I&&f(a(`${e.id}-think-${S}`,"think-line",I,{}),T&&!D),l(),r.push({key:`${e.id}-think-footer-${S}`,type:"think-footer-padding",text:""}),w=!1,D&&D.trim()&&f(a(`${e.id}-${S}`,"agent-line",D,{}),T)}else k&&f(a(`${e.id}-think-${S}`,"think-line",k,{}),T);return}m?_?(m=!1,f(a(`${e.id}-code-close-${E}`,"code-fence-close","",{}),T)):(b++,f(a(`${e.id}-code-line-${S}`,"code-line",R,{lineNum:b,lang:x}),T)):_?(m=!0,E=S,b=0,x=R.trim().replace(/^```/,"").trim(),f(a(`${e.id}-code-open-${S}`,"code-fence-open",x,{}),T)):$?(g=!0,y.push(R),T&&(l(),e.isStreaming?h=a(`${e.id}-table-${S}`,"table",y.join(`
337
- `),{isStreaming:!0}):r.push(a(`${e.id}-table-${S}`,"table",y.join(`
338
- `),{isStreaming:!1})))):(g&&(l(),r.push(a(`${e.id}-table-${S}`,"table",y.join(`
339
- `),{isStreaming:!1})),g=!1,y=[]),f(a(`${e.id}-${S}`,"agent-line",R,{}),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=>yi(g,p)),h&&yi(h,p),ds.set(s,{text:o,blocksMap:p}),ds.size>Vr){let g=ds.keys().next().value;ds.delete(g)}}else{if(qn.set(t,u),qn.size>Vr){let p=qn.keys().next().value;qn.delete(p)}ds.delete(s)}return u},Sl={},Tl=/<\/think>(\r?\n){2}/gi,Rl=/(\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},El=/\[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,_l=/(\$?\\?\/?\\rightarrow\$?|\$\\rightarrow\$)|(\$?\\?\/?\\leftarrow\$?|\$\\leftarrow\$)|(\$?\\?\/?\\uparrow\$?|\$\\uparrow\$)|(\$?\\?\/?\\downarrow\$?|\$\\downarrow\$)|(\$?\\?\/?\\leftrightarrow\$?|\$\\leftrightarrow\$)/gi,$l=/\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,Os=!1,Cl=(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(Tl,"</think>").replace(Rl,(a,r,h,d)=>!Os&&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),Os&&(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(!Os&&gi(o,c)){let w=c+d.length,x=a.indexOf(s,w),b=a.indexOf(i,w);if(x===-1&&b===-1)break;let E=-1,R=0;for(;;){let S=a.indexOf(s,R),T=a.indexOf(i,R),$=-1,_=s;if(S===-1&&T===-1)break;if(S===-1||T!==-1&&T<S?($=T,_=i):$=S,!gi(o,$)){E=$,d=_;break}R=$+_.length}if(E===-1)break;c=E}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 b=m+1;for(;b<o.length&&/\s/.test(o[b]);)b++;b<o.length&&o[b]==="]"&&(x=b)}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(El,""),o=o.replace(_l,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($l,a=>Sl[a.toLowerCase()]||a),o.trim()},Rf=()=>{qn.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}=vo(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=Ml.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,`
328
+ ${x}
329
+ [[/VERIFIED]]`:x);c=g+b.join(m)}return c+="[DIFF_END]",pn(c)},kl=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,r=s.indexOf("|"),a=r!==-1?pn(s.substring(0,r).trim()):"",i=pn(r!==-1?s.substring(r+1):s);return{isR:t,isA:o,num:a,content:i}},Sl=(e,n)=>{if(!e&&!n)return 1;if(!e||!n)return 0;let t=e.length,o=n.length,s=e,r=n;t<o&&(s=n,r=e);let a=s.length,i=r.length,h=new Int32Array(i+1),d=new Int32Array(i+1);for(let f=0;f<=i;f++)h[f]=f;for(let f=1;f<=a;f++){d[0]=f;let u=s[f-1];for(let p=1;p<=i;p++)u===r[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[i],l=Math.max(t,o);return l===0?1:1-c/l},Ki=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 r=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 i=Array.from({length:o},()=>Array(s).fill(0));for(let c=0;c<o;c++)for(let l=0;l<s;l++)i[c][l]=Sl(n[c].content.trim(),t[l].content.trim());for(let c=1;c<=o;c++)for(let l=1;l<=s;l++){let f=i[c-1][l-1],u=f>=.2?f:-10,p=r[c-1][l-1]+u,g=r[c-1][l],y=r[c][l-1];p>=g&&p>=y?(r[c][l]=p,a[c][l]="diag"):g>=y?(r[c][l]=g,a[c][l]="up"):(r[c][l]=y,a[c][l]="left")}let h=o,d=s;for(;h>0||d>0;)if(a[h][d]==="diag"){if(i[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--},qn=new Map,cs=new Map,Yi=200,pr=6,gr=(e,n)=>{n.set(e.key,e),e.type==="chunk"&&e.blocks&&e.blocks.forEach(t=>gr(t,n))},Rf=(e,n)=>{if(!e)return{completed:[],active:[]};let t=`${e.id}-${e.text?.length||0}-${n}-${e.isStreaming}-${e.workedDuration||0}`;if(!e.isStreaming&&qn.has(t))return qn.get(t);let o=pn(Ml(e.text||"",e.role==="think")),s=`${e.id}-${n}`,r=new Map;if(e.isStreaming){let p=cs.get(s);p&&o.startsWith(p.text)&&(r=p.blocksMap)}let a=(p,g,y,m={})=>{let w=r.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 b=pn(y),x={...m};return typeof x.pairContent=="string"&&(x.pairContent=pn(x.pairContent)),Array.isArray(x.wrappedLines)&&(x.wrappedLines=x.wrappedLines.map(pn)),{key:p,isStreamingMsg:!!e.isStreaming,workedDuration:e.workedDuration,type:g,text:b,msg:g==="full-message"?e:void 0,...x}};if(o.includes("- Content Preview:")){let p="",g=o.match(/File\s+\[(.*?)\]/i);g&&(p=g[1].split(".").pop().toLowerCase());let x=((o.split("- Content Preview:")[1]||"").split("[SYSTEM] Check the content preview for verification [/SYSTEM]")[0]?.trim()||"").split(`
330
+ `).map(k=>k.replace(/\r$/,"")),E=String(x.length).length,R=[],S=null,T=[],$=()=>{if(!T.length)return;let k=T;T=[],R.push(k.length===1?k[0]:{key:`${k[0].key}-chunk`,type:"chunk",blocks:k})},_=n-(E+6);return x.forEach((k,C)=>{let I=C===x.length-1,D=zi(k,_).split(`
331
+ `),B=a(`${e.id||Date.now()}-write-line-${C}`,"write-line",k,{gutterWidth:E,lineNum:C+1,isFirstLine:C===0,isLastLine:I,extension:p,wrappedLines:D});I&&e.isStreaming?($(),S=B):(T.push(B),T.length>=pr&&$())}),$(),{completed:R,active:S?[S]:[]}}if(o.includes("[DIFF_START]")){let p=o.match(/\[DIFF_START\]([\s\S]*?)(?:\[DIFF_END\]|$)/),y=(p?p[1].trim():"").split(`
332
+ `).map(S=>S.replace(/\r$/,"")),m=y.map(S=>({line:S,parsed:kl(S),pairContent:null})),w=[];for(let S=0;S<m.length;S++){let T=m[S];T.parsed&&(T.parsed.isR||T.parsed.isA)?w.push(T):w.length>0&&(Ki(w),w=[])}w.length>0&&Ki(w);let b=[],x=null,E=[],R=()=>{if(!E.length)return;let S=E;E=[],b.push(S.length===1?S[0]:{key:`${S[0].key}-chunk`,type:"chunk",blocks:S})};return y.forEach((S,T)=>{let $=T===y.length-1,_=m[T].parsed,k=null;_&&(k=zi(_.content,n-17).split(`
333
+ `));let C=a(`${e.id||Date.now()}-diff-${T}`,"diff-line",S,{isFirstLine:T===0,isLastLine:$,pairContent:m[T].pairContent,wrappedLines:k});$&&e.isStreaming?(R(),x=C):(E.push(C),E.length>=pr&&R())}),R(),{completed:b,active:x?[x]:[]}}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 qn.set(t,p),p}let i=[],h=null,d=[],c=null,l=()=>{if(!d.length)return;let p=d;d=[],c=null,i.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>=pr){if(e.isStreaming&&g)return;l()}};if(e.role==="think"){i.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(),i.push({key:`${e.id}-footer-padding`,type:"think-footer-padding",text:""}))}else{let p=o.split(`
335
+ `),g=!1,y=[],m=!1,w=!1,b="",x=0,E=0;p.forEach((R,S)=>{let T=S===p.length-1,$=R.trim().startsWith("|"),_=R.trim().startsWith("```");if(w){if(R.includes("</think>")||R.includes("<channel|>")||R.includes("</thought>")){let k=R.split(/(?:<\/(think|thought|thoughts)>|<channel\|>)/i),C=k[0]||"",I=k.slice(2).join("");C&&f(a(`${e.id}-think-${S}`,"think-line",C,{}),T&&!I),l(),i.push({key:`${e.id}-think-footer-${S}`,type:"think-footer-padding",text:""}),w=!1,I&&I.trim()&&f(a(`${e.id}-${S}`,"agent-line",I,{}),T)}else f(a(`${e.id}-think-${S}`,"think-line",R,{}),T);return}if(!m&&(R.includes("<think>")||R.includes("<|channel>thought")||R.includes("<thought>")||R.startsWith("<think")||R.startsWith("<|channel>thought"))){l(),g&&(i.push(a(`${e.id}-table-${S}`,"table",y.join(`
336
+ `),{isStreaming:!1})),g=!1,y=[]),i.push(a(`${e.id}-think-header-${S}`,"think-header","")),w=!0;let k=R.replace(/^(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought\s*)\r?\n?/i,"");if(k.includes("</think>")||k.includes("<channel|>")||k.includes("</thought>")){let C=k.split(/(?:<\/(think|thought|thoughts)>|<channel\|>)/i),I=C[0]||"",D=C.slice(2).join("");I&&f(a(`${e.id}-think-${S}`,"think-line",I,{}),T&&!D),l(),i.push({key:`${e.id}-think-footer-${S}`,type:"think-footer-padding",text:""}),w=!1,D&&D.trim()&&f(a(`${e.id}-${S}`,"agent-line",D,{}),T)}else k&&f(a(`${e.id}-think-${S}`,"think-line",k,{}),T);return}m?_?(m=!1,f(a(`${e.id}-code-close-${E}`,"code-fence-close","",{}),T)):(x++,f(a(`${e.id}-code-line-${S}`,"code-line",R,{lineNum:x,lang:b}),T)):_?(m=!0,E=S,x=0,b=R.trim().replace(/^```/,"").trim(),f(a(`${e.id}-code-open-${S}`,"code-fence-open",b,{}),T)):$?(g=!0,y.push(R),T&&(l(),e.isStreaming?h=a(`${e.id}-table-${S}`,"table",y.join(`
337
+ `),{isStreaming:!0}):i.push(a(`${e.id}-table-${S}`,"table",y.join(`
338
+ `),{isStreaming:!1})))):(g&&(l(),i.push(a(`${e.id}-table-${S}`,"table",y.join(`
339
+ `),{isStreaming:!1})),g=!1,y=[]),f(a(`${e.id}-${S}`,"agent-line",R,{}),T))}),!e.isStreaming&&e.workedDuration&&(l(),i.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:i,active:h?[h]:[]};if(e.isStreaming){let p=new Map;if(i.forEach(g=>gr(g,p)),h&&gr(h,p),cs.set(s,{text:o,blocksMap:p}),cs.size>Yi){let g=cs.keys().next().value;cs.delete(g)}}else{if(qn.set(t,u),qn.size>Yi){let p=qn.keys().next().value;qn.delete(p)}cs.delete(s)}return u},Tl={},Rl=/<\/think>(\r?\n){2}/gi,El=/(\r?\n){2}(?=\[?(?:tool:functions|tool\.functions|agent:generalist|agent\.generalist|\s*turn\s*:))/gi,mr=(e,n)=>{let t=!1;for(let o=0;o<n;o++)e[o]==="`"&&(t=!t);return t},_l=/\[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,$l=/(\$?\\?\/?\\rightarrow\$?|\$\\rightarrow\$)|(\$?\\?\/?\\leftarrow\$?|\$\\leftarrow\$)|(\$?\\?\/?\\uparrow\$?|\$\\uparrow\$)|(\$?\\?\/?\\downarrow\$?|\$\\downarrow\$)|(\$?\\?\/?\\leftrightarrow\$?|\$\\leftrightarrow\$)/gi,Cl=/\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,Ml=(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(Rl,"</think>").replace(El,(a,i,h,d)=>!Is&&mr(d,h)?a:"");o&&o.includes("[tool:")&&(o=o.replace(/<(\w+)(?:[^>]*)>\s*([\s\S]*?\[tool:[^\]]*\][\s\S]*?)\s*<\/\1>/gi,(a,i,h)=>h&&h.includes("[tool:")?h.trim():a),Is&&(o=o.replace(/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi,(a,i)=>i.includes("[tool:")?i.trim():a)),o=o.replace(/<(\w+)(?:[^>]*)>\r?\n?/gi,"").replace(/\r?\n?<\/\w+(?:[^>]*)>/gi,""));let s="tool:functions.",r="agent:generalist.";if(o.toLowerCase().includes(s)||o.toLowerCase().includes(r))for(;;){let a=o.toLowerCase(),i=a.indexOf(s),h=a.indexOf(r),d=s,c=i;if((i===-1||h!==-1&&h<i)&&(d=r,c=h),c===-1)break;if(!Is&&mr(o,c)){let w=c+d.length,b=a.indexOf(s,w),x=a.indexOf(r,w);if(b===-1&&x===-1)break;let E=-1,R=0;for(;;){let S=a.indexOf(s,R),T=a.indexOf(r,R),$=-1,_=s;if(S===-1&&T===-1)break;if(S===-1||T!==-1&&T<S?($=T,_=r):$=S,!mr(o,$)){E=$,d=_;break}R=$+_.length}if(E===-1)break;c=E}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 b=m;if(f){let x=m+1;for(;x<o.length&&/\s/.test(o[x]);)x++;x<o.length&&o[x]==="]"&&(b=x)}o=o.substring(0,l)+o.substring(b+1);break}if(m++,m===o.length)return o=o.substring(0,l),o}}return o=o.replace(_l,""),o=o.replace($l,a=>{let i=a.toLowerCase();return i.includes("leftrightarrow")?"\u2194":i.includes("rightarrow")?"\u2192":i.includes("leftarrow")?"\u2190":i.includes("uparrow")?"\u2191":i.includes("downarrow")?"\u2193":a}),o=o.replace(Cl,a=>Tl[a.toLowerCase()]||a),o.trim()},Ef=()=>{qn.clear(),cs.clear()};var wr=async(e,n={})=>{let t=O(e),o=t.path;if(!o)return'ERROR: Missing "path" argument for PatchFile.';let{patchPairs:s,allowMultiple:r,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 i=t.allowMultiple!==void 0?t.allowMultiple===!0||String(t.allowMultiple).toLowerCase()==="true":r,h=Al.resolve(process.cwd(),o);try{if(!yr.existsSync(h))return`ERROR: File [${o}] does not exist. Use WriteFile instead.`;let d=n.forcedContent||yr.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}=Io(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}].
341
+ `),{content:l,results:f}=vo(c,s,{allowMultiple:i}),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
342
  ${u.map(m=>` \u2022 ${m.error}`).join(`
343
- `)}`;await ht.recordFileChange(h,c),wi.writeFileSync(h,l,"utf8");let{systemSettings:g}=await Ft(),y=Oo(c,l,f,12,g?.compressToolResults);return u.length>0?`SUCCESS: File [${o}] updated with some blocks failed. [${p.length}/${s.length}] blocks applied.
343
+ `)}`;await pt.recordFileChange(h,c),yr.writeFileSync(h,l,"utf8");let{systemSettings:g}=await Nt(),y=Io(c,l,f,12,g?.compressToolResults);return u.length>0?`SUCCESS: File [${o}] updated with some blocks failed. [${p.length}/${s.length}] blocks applied.
344
344
 
345
345
  Failures:
346
346
  ${u.map(m=>` \u2022 ${m.error}`).join(`
@@ -348,21 +348,21 @@ ${u.map(m=>` \u2022 ${m.error}`).join(`
348
348
 
349
349
  ${y}`:`SUCCESS: File [${o}] updated. [${f.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 bi from"path";var Al=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"]),vl=e=>Al.has(e)||e.startsWith(".pnpm"),Il=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"}},ki=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 R of w){let S=bi.join(s,R),T={name:R,type:"unknown",size:"N/A",mtime:"N/A"};try{let $=fs.statSync(S);T={name:R,type:$.isDirectory()?"directory":"file",size:($.size/1024).toFixed(1)+"KB",mtime:Il($.mtime)}}catch{T.type="inaccessible"}x.push(T)}let b=x.map(R=>R.type==="directory"?`${R.name}/`:`${R.name} (${R.size}, ${R.mtime})`).join(`
351
+ ${y}`}catch(d){let c=d instanceof Error?d.message:String(d);return`ERROR: Failed to update file [${o}]: ${c}`}};import ds from"fs";import xr from"path";var vl=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"]),Il=e=>vl.has(e)||e.startsWith(".pnpm"),Ol=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"}},br=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 r=parseInt(String(n.recurse).trim(),10);o=isNaN(r)?1:r}o=Math.max(1,Math.min(3,o));let s=xr.resolve(process.cwd(),t);try{if(!ds.existsSync(s))return`ERROR: Path [${t}] does not exist.`;if(!ds.statSync(s).isDirectory())return`ERROR: Path [${t}] is a file, not a directory. Use ReadFile instead.`;if(o===1){let g=ds.readdirSync(s),y=g.length,m=150,w=g.slice(0,m),b=[];for(let R of w){let S=xr.join(s,R),T={name:R,type:"unknown",size:"N/A",mtime:"N/A"};try{let $=ds.statSync(S);T={name:R,type:$.isDirectory()?"directory":"file",size:($.size/1024).toFixed(1)+"KB",mtime:Ol($.mtime)}}catch{T.type="inaccessible"}b.push(T)}let x=b.map(R=>R.type==="directory"?`${R.name}/`:`${R.name} (${R.size}, ${R.mtime})`).join(`
352
352
  `),E=`
353
353
 
354
354
  (Total items in folder: ${y})`;return y>m&&(E=`
355
355
 
356
- TRUNCATED: Showing first ${m} of ${y} items.`),g.length=0,w.length=0,x.length=0,`Detailed folder stats for [${t}]:
356
+ TRUNCATED: Showing first ${m} of ${y} items.`),g.length=0,w.length=0,b.length=0,`Detailed folder stats for [${t}]:
357
357
 
358
- ${b}${E}`}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=[],b=[];for(let T of w){let $=bi.join(g,T),_=!1;try{_=fs.statSync($).isDirectory()}catch{}_?x.push({name:T,fullPath:$}):b.push({name:T,fullPath:$})}x.sort((T,$)=>T.name.localeCompare($.name)),b.sort((T,$)=>T.name.localeCompare($.name));let E=[],R=" ".repeat(m-1);for(let T of x){if(h>=d){c=!0,E.push(`${R}[Truncated - Maximum item limit reached (${d})]`);break}if(h++,a++,E.push(`${R}${T.name}/`),y<o&&!vl(T.name)){let $=l(T.fullPath,y+1,m+1);E.push(...$)}}let S=[];for(let T of b){if(h>=d){c=!0,E.push(`${R}[Truncated - Maximum item limit reached (${d})]`);break}h++,r++;let $="N/A";try{$=(fs.statSync(T.fullPath).size/1024).toFixed(1)+"KB"}catch{}S.push(`${T.name} (${$})`)}return S.length>0&&E.push(`${R}${S.join("; ")}`),E},u=l(s,1,1).join(`
358
+ ${x}${E}`}let a=0,i=0,h=0,d=500,c=!1,l=(g,y,m=1)=>{if(y>o||c)return[];let w=[];try{w=ds.readdirSync(g)}catch{return[`${" ".repeat(m-1)}[Inaccessible Directory]`]}let b=[],x=[];for(let T of w){let $=xr.join(g,T),_=!1;try{_=ds.statSync($).isDirectory()}catch{}_?b.push({name:T,fullPath:$}):x.push({name:T,fullPath:$})}b.sort((T,$)=>T.name.localeCompare($.name)),x.sort((T,$)=>T.name.localeCompare($.name));let E=[],R=" ".repeat(m-1);for(let T of b){if(h>=d){c=!0,E.push(`${R}[Truncated - Maximum item limit reached (${d})]`);break}if(h++,a++,E.push(`${R}${T.name}/`),y<o&&!Il(T.name)){let $=l(T.fullPath,y+1,m+1);E.push(...$)}}let S=[];for(let T of x){if(h>=d){c=!0,E.push(`${R}[Truncated - Maximum item limit reached (${d})]`);break}h++,i++;let $="N/A";try{$=(ds.statSync(T.fullPath).size/1024).toFixed(1)+"KB"}catch{}S.push(`${T.name} (${$})`)}return S.length>0&&E.push(`${R}${S.join("; ")}`),E},u=l(s,1,1).join(`
359
359
  `),p=`
360
360
 
361
- (Total items scanned: ${h}, Directories: ${a}, Files: ${r})`;return c&&(p=`
361
+ (Total items scanned: ${h}, Directories: ${a}, Files: ${i})`;return c&&(p=`
362
362
 
363
- TRUNCATED: Scan capped at ${d} items. (Directories: ${a}, Files: ${r})`),`Detailed directory tree for [${t}] (recursive depth: ${o}):
363
+ TRUNCATED: Scan capped at ${d} items. (Directories: ${a}, Files: ${i})`),`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 Si=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 Ol from"puppeteer";import Ls from"path";import us from"fs-extra";import{PDFDocument as Ll}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=Ls.resolve(process.cwd(),n),a=null;try{await us.ensureDir(Ls.dirname(i)),await ht.recordFileChange(i);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(),d=t,c={},l=async S=>{if(!S||S.startsWith("http://")||S.startsWith("https://")||S.startsWith("data:"))return null;try{let T=Ls.resolve(process.cwd(),S);if(await us.pathExists(T)){let $=Ls.extname(T).toLowerCase().replace(".","")||"png",_=$==="jpg"?"jpeg":$==="svg"?"svg+xml":$,k=await us.readFile(T,"base64");return`data:image/${_};base64,${k}`}}catch{}return null},f=/<link[^>]+href=["']([^"']+)["']/gi,u={},p;for(;(p=f.exec(t))!==null;){let S=p[1],T=p[0];if(S&&T.toLowerCase().includes("stylesheet")&&!S.startsWith("http://")&&!S.startsWith("https://")&&!S.startsWith("data:"))try{let $=Ls.resolve(process.cwd(),S);if(await us.pathExists($)){let _=await us.readFile($,"utf-8");u[T]=`<style>${_}</style>`}}catch{}}for(let[S,T]of Object.entries(u))d=d.split(S).join(T);let g=/<img[^>]+src=["']([^"']+)["']/gi;for(;(p=g.exec(d))!==null;){let S=p[1];if(S&&!c[S]){let T=await l(S);T&&(c[S]=T)}}let y=/url\(\s*['"]?([^'")]+?)['"]?\s*\)/gi;for(;(p=y.exec(d))!==null;){let S=p[1].trim();if(S&&!c[S]){let T=await l(S);T&&(c[S]=T)}}for(let[S,T]of Object.entries(c)){let $=S.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&"),_=new RegExp(`(src=["'])(${$})(["'])`,"gi");d=d.replace(_,`$1${T}$3`);let k=new RegExp(`url\\(\\s*(['"]?)(${$})\\1\\s*\\)`,"gi");d=d.replace(k,`url($1${T}$1)`)}let m=`
365
+ ${u}${p}`}catch(r){let a=r instanceof Error?r.message:String(r);return`ERROR: Failed to read folder [${t}]: ${a}`}};var kr=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(r=>{if(r.startsWith("option")){let a=t[r];if(typeof a=="string"&&a.includes("::")){let[i,h]=a.split("::");s.push({id:r,label:i.trim(),description:h.trim()})}else s.push({id:r,label:String(a).trim(),description:""})}});try{return`USER CHOOSE: ${await n.onAskUser(o,s)}`}catch(r){return`ERROR: Failed to get user input: ${r instanceof Error?r.message:String(r)}`}};import Ll from"puppeteer";import Os from"path";import fs from"fs-extra";import{PDFDocument as Dl}from"pdf-lib";var Sr=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 r=Os.resolve(process.cwd(),n),a=null;try{await fs.ensureDir(Os.dirname(r)),await pt.recordFileChange(r);let i=ls();a=await Ll.launch({headless:!0,executablePath:i.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 S=>{if(!S||S.startsWith("http://")||S.startsWith("https://")||S.startsWith("data:"))return null;try{let T=Os.resolve(process.cwd(),S);if(await fs.pathExists(T)){let $=Os.extname(T).toLowerCase().replace(".","")||"png",_=$==="jpg"?"jpeg":$==="svg"?"svg+xml":$,k=await fs.readFile(T,"base64");return`data:image/${_};base64,${k}`}}catch{}return null},f=/<link[^>]+href=["']([^"']+)["']/gi,u={},p;for(;(p=f.exec(t))!==null;){let S=p[1],T=p[0];if(S&&T.toLowerCase().includes("stylesheet")&&!S.startsWith("http://")&&!S.startsWith("https://")&&!S.startsWith("data:"))try{let $=Os.resolve(process.cwd(),S);if(await fs.pathExists($)){let _=await fs.readFile($,"utf-8");u[T]=`<style>${_}</style>`}}catch{}}for(let[S,T]of Object.entries(u))d=d.split(S).join(T);let g=/<img[^>]+src=["']([^"']+)["']/gi;for(;(p=g.exec(d))!==null;){let S=p[1];if(S&&!c[S]){let T=await l(S);T&&(c[S]=T)}}let y=/url\(\s*['"]?([^'")]+?)['"]?\s*\)/gi;for(;(p=y.exec(d))!==null;){let S=p[1].trim();if(S&&!c[S]){let T=await l(S);T&&(c[S]=T)}}for(let[S,T]of Object.entries(c)){let $=S.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&"),_=new RegExp(`(src=["'])(${$})(["'])`,"gi");d=d.replace(_,`$1${T}$3`);let k=new RegExp(`url\\(\\s*(['"]?)(${$})\\1\\s*\\)`,"gi");d=d.replace(k,`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 Ll.load(w),b=Ls.basename(n);x.setTitle(`FluxFlow_${b}`),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 E=await x.save();await us.writeFile(i,E);let R=await us.stat(i);return`SUCCESS: PDF generated successfully at [${n}] (${(R.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 Xr from"fs-extra";import Ri from"path";import Dl 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 Xr.ensureDir(Ri.dirname(o)),await ht.recordFileChange(o);let s=Ri.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}),b=await Dl.load(w),x=Os.basename(n);b.setTitle(`FluxFlow_${x}`),b.setAuthor("FluxFlow CLI"),b.setSubject("Generated with Agentic AI System"),b.setKeywords(["FluxFlow","AI","Agentic","Automated"]),b.setCreator("FluxFlow PDF Engine"),b.setProducer("FluxFlow (Generative AI)");let E=await b.save();await fs.writeFile(r,E);let R=await fs.stat(r);return`SUCCESS: PDF generated successfully at [${n}] (${(R.size/1024).toFixed(2)} KB).`}catch(i){let h=i instanceof Error?i.message:String(i);return`ERROR: Failed to generate PDF [${n}]: ${h}`}finally{a&&await a.close()}};import Vi from"fs-extra";import Tr from"path";import Pl from"html-to-docx";var Rr=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=Tr.resolve(process.cwd(),n);try{await Vi.ensureDir(Tr.dirname(o)),await pt.recordFileChange(o);let s=Tr.basename(n),r=t.includes("<html")?t:`
396
396
  <!DOCTYPE html>
397
397
  <html lang="en">
398
398
  <head>
@@ -403,70 +403,70 @@ ${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 Dl(i,null,{title:`FluxFlow_${s}`,creator:"FluxFlow CLI",description:"Generated by Agentic AI System",table:{row:{cantSplit:!0}},footer:!0,pageNumber:!0});return await Xr.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 $i from"fs/promises";import hs from"path";import _i from"fast-glob";import{Minimatch as Jr}from"minimatch";async function eo(e,n,t=e,o=1){if(o>12)return[];let s=[],i;try{i=await $i.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 eo(r,n,t,o+1);s=s.concat(f)}else a.isFile()&&s.push({fullPath:r,relativePath:h})}return s}function Pl(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 Fl(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&&Pl(a,h,r)<=r)return!0;return!1})}var to=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,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 I=t.split(";").map(N=>N.trim()).filter(Boolean),D=I.some(N=>N.startsWith("!"));if(I.some(N=>_i.isDynamicPattern(N)||/[*?{}[\]()|+]/.test(N))){m="glob";let N=t.replace(/\\/g,"/"),Y=I.map(U=>U.replace(/\\/g,"/")),ne=u.map(U=>U.startsWith(".")?`**/*${U}`:`**/${U}/**`);if(D&&!I.some(U=>!U.startsWith("!"))){let U=await eo(y,u,y),j=A=>A.endsWith("/")?A+"**":A,ae=Y.filter(A=>A.startsWith("!")).map(A=>j(A.slice(1))),Ee=Y.filter(A=>!A.startsWith("!")).map(j);g=U.filter(A=>{let F=A.relativePath.replace(/\\/g,"/"),V=Ee.length===0||Ee.some(Ue=>{try{return new Jr(Ue).match(F)}catch{return!1}}),X=ae.some(Ue=>{try{return new Jr(Ue).match(F)}catch{return!1}});return V&&!X})}else{let U=Y.some(ae=>/[\(\)\|]|\.\*/.test(ae)),j=[];if(!U)try{j=await _i(Y,{cwd:y,ignore:ne,dot:!0,onlyFiles:!0,absolute:!1})}catch{j=[]}if(j.length===0&&(U||_i.isDynamicPattern(N))){let ae=N.match(/^([^\*\?\(\)\|\[\]\s]+)\//),Ee=ae&&!/[\*\?\(\)\|\[\]]/.test(ae[1])?hs.resolve(y,ae[1]):y,A=await eo(Ee,u,y);try{let F=N.replace(/^\.\//,"");F=F.replace(/\.\*\/(\\.|[^\/])/g,".*$1"),!F.startsWith("^")&&!F.startsWith(".*")&&(F=`.*${F}`);let V=new RegExp(F.endsWith("$")?F:`${F}$`,"i");g=A.filter(X=>{let Ue=X.relativePath.replace(/\\/g,"/");return V.test(Ue)})}catch{g=[]}}else g=j.map(ae=>({fullPath:hs.resolve(y,ae),relativePath:ae}))}}else{let N=t.replace(/[\/\\]+$/,""),Y=hs.resolve(y,N);try{let ne=await $i.stat(Y);if(ne.isDirectory())m="dir",g=await eo(Y,u,y);else if(ne.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 eo(y,u);let w=g.map(async I=>{try{let D=await $i.readFile(I.fullPath,"utf-8");if(D.includes("\0"))return[];let B=D.split(/\r?\n/),N=[];for(let ne=0;ne<B.length;ne++)(c?B[ne].toLowerCase().includes(a.toLowerCase())||Fl(B[ne],a):h?f&&f.test(B[ne]):l&&l.test(B[ne])||f&&f.test(B[ne]))&&N.push({line:ne+1,content:B[ne].trim()});return N.length===0?null:{path:I.relativePath.replace(/\\/g,"/"),matches:N}}catch{return[]}}),x=await Promise.all(w),b=[],E=0;for(let I of x){if(!I||!I.matches)continue;if(E>=p)break;let D=p-E,B=I.matches.slice(0,D);b.push({path:I.path,matches:B}),E+=B.length}typeof global.gc=="function"&&global.gc();let R=c?"(fuzzy mode)":d?"(regex mode)":h?"(keyword mode)":"(standard mode)";if(b.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}${R?` ${R}`:""}`}let S=R?` ${R}`:"",T=`${b.length} file${b.length===1?"":"s"}`,$=`${E} match${E===1?"":"es"}`,_;m==="file"?_=`Found ${$} of '${a}' in '${t}'${S}:`:m==="dir"||m==="glob"?_=`Found ${$} of '${a}' in '${t}' across ${T}${S}:`:_=`Found ${$} of '${a}' across ${T}${S}:`;let k=m==="dir"?"[DIR]":m==="glob"?"[GLOB]":"",C=`${k}${k?" ":""}${_}
406
+ `,a=await Pl(r,null,{title:`FluxFlow_${s}`,creator:"FluxFlow CLI",description:"Generated by Agentic AI System",table:{row:{cantSplit:!0}},footer:!0,pageNumber:!0});return await Vi.writeFile(o,a),`SUCCESS: Word document [${n}] generated successfully.
407
+ - Size: ${(a.length/1024).toFixed(1)} KB`}catch(s){let r=s instanceof Error?s.message:String(s);return`ERROR: Failed to generate DOCX [${n}]: ${r}`}};import _r from"fs/promises";import us from"path";import Er from"fast-glob";import{Minimatch as Xi}from"minimatch";async function Zs(e,n,t=e,o=1){if(o>12)return[];let s=[],r;try{r=await _r.readdir(e,{withFileTypes:!0})}catch{return[]}for(let a of r){let i=us.join(e,a.name),h=us.relative(t,i),d=h.split(us.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(i,n,t,o+1);s=s.concat(f)}else a.isFile()&&s.push({fullPath:i,relativePath:h})}return s}function Fl(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,r)=>r);for(let s=1;s<=e.length;s++){let r=[s],a=s;for(let i=1;i<=n.length;i++){let h=e[s-1]===n[i-1]?0:1,d=Math.min(r[i-1]+1,o[i]+1,o[i-1]+h);r.push(d),d<a&&(a=d)}if(o=r,a>t)return t+1}return o[n.length]}function Nl(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),r=o.split(/[^a-z0-9]+/).filter(a=>a.length>1||o.length===1&&a.length>0);return r.length===0?!1:r.every(a=>{let i=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)<=i&&Fl(a,h,i)<=i)return!0;return!1})}var eo=async e=>{let{keyword:n,path:t,fuzzy:o,subString:s,regex:r}=O(e);if(n==null)return'ERROR: Missing "keyword" argument.';let a=String(n),i=g=>g===!0||g==="true"||g===1||g==="1"||g==="yes",h=r===!1||r==="false"||r===0||r==="0"||r==="no",d=r===!0||r==="true"||r===1||r==="1"||r==="yes",c=i(o)||i(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 I=t.split(";").map(N=>N.trim()).filter(Boolean),D=I.some(N=>N.startsWith("!"));if(I.some(N=>Er.isDynamicPattern(N)||/[*?{}[\]()|+]/.test(N))){m="glob";let N=t.replace(/\\/g,"/"),Y=I.map(U=>U.replace(/\\/g,"/")),ne=u.map(U=>U.startsWith(".")?`**/*${U}`:`**/${U}/**`);if(D&&!I.some(U=>!U.startsWith("!"))){let U=await Zs(y,u,y),j=A=>A.endsWith("/")?A+"**":A,ae=Y.filter(A=>A.startsWith("!")).map(A=>j(A.slice(1))),_e=Y.filter(A=>!A.startsWith("!")).map(j);g=U.filter(A=>{let F=A.relativePath.replace(/\\/g,"/"),V=_e.length===0||_e.some(Ue=>{try{return new Xi(Ue).match(F)}catch{return!1}}),X=ae.some(Ue=>{try{return new Xi(Ue).match(F)}catch{return!1}});return V&&!X})}else{let U=Y.some(ae=>/[\(\)\|]|\.\*/.test(ae)),j=[];if(!U)try{j=await Er(Y,{cwd:y,ignore:ne,dot:!0,onlyFiles:!0,absolute:!1})}catch{j=[]}if(j.length===0&&(U||Er.isDynamicPattern(N))){let ae=N.match(/^([^\*\?\(\)\|\[\]\s]+)\//),_e=ae&&!/[\*\?\(\)\|\[\]]/.test(ae[1])?us.resolve(y,ae[1]):y,A=await Zs(_e,u,y);try{let F=N.replace(/^\.\//,"");F=F.replace(/\.\*\/(\\.|[^\/])/g,".*$1"),!F.startsWith("^")&&!F.startsWith(".*")&&(F=`.*${F}`);let V=new RegExp(F.endsWith("$")?F:`${F}$`,"i");g=A.filter(X=>{let Ue=X.relativePath.replace(/\\/g,"/");return V.test(Ue)})}catch{g=[]}}else g=j.map(ae=>({fullPath:us.resolve(y,ae),relativePath:ae}))}}else{let N=t.replace(/[\/\\]+$/,""),Y=us.resolve(y,N);try{let ne=await _r.stat(Y);if(ne.isDirectory())m="dir",g=await Zs(Y,u,y);else if(ne.isFile())m="file",g.push({fullPath:Y,relativePath:us.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,u);let w=g.map(async I=>{try{let D=await _r.readFile(I.fullPath,"utf-8");if(D.includes("\0"))return[];let B=D.split(/\r?\n/),N=[];for(let ne=0;ne<B.length;ne++)(c?B[ne].toLowerCase().includes(a.toLowerCase())||Nl(B[ne],a):h?f&&f.test(B[ne]):l&&l.test(B[ne])||f&&f.test(B[ne]))&&N.push({line:ne+1,content:B[ne].trim()});return N.length===0?null:{path:I.relativePath.replace(/\\/g,"/"),matches:N}}catch{return[]}}),b=await Promise.all(w),x=[],E=0;for(let I of b){if(!I||!I.matches)continue;if(E>=p)break;let D=p-E,B=I.matches.slice(0,D);x.push({path:I.path,matches:B}),E+=B.length}typeof global.gc=="function"&&global.gc();let R=c?"(fuzzy mode)":d?"(regex mode)":h?"(keyword mode)":"(standard mode)";if(x.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}${R?` ${R}`:""}`}let S=R?` ${R}`:"",T=`${x.length} file${x.length===1?"":"s"}`,$=`${E} match${E===1?"":"es"}`,_;m==="file"?_=`Found ${$} of '${a}' in '${t}'${S}:`:m==="dir"||m==="glob"?_=`Found ${$} of '${a}' in '${t}' across ${T}${S}:`:_=`Found ${$} of '${a}' across ${T}${S}:`;let k=m==="dir"?"[DIR]":m==="glob"?"[GLOB]":"",C=`${k}${k?" ":""}${_}
408
408
 
409
- `;for(let I of b){C+=`${I.path}
409
+ `;for(let I of x){C+=`${I.path}
410
410
  `;for(let D of I.matches)C+=` ${D.line}: ${D.content}
411
411
  `;C+=`
412
- `}return C.trimEnd()}catch(g){return`ERROR: ${g.message}`}};import Qr from"fs-extra";import Ci from"path";var Nl=(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}},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 Fr(d))return`ERROR: Insufficient Quota for selected quality. Either tell user reduce quality or wait for next refresh cycle (${(await Nr()).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 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")}`,b=await fetch(x,{method:"GET",headers:{Authorization:`Bearer ${f}`}});if(!b.ok){let D=b.status,B="";try{B=await b.text()}catch{}return D===402||B.includes("Insufficient balance")||B.includes("PAYMENT_REQUIRED")?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed with status [${D}]: ${B||"Unknown API Error"}`}if((b.headers.get("content-type")||"").includes("application/json")){let D=await b.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 R=await b.arrayBuffer(),S=Buffer.from(R),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)};S=Nl(S,T);let $=Ci.resolve(process.cwd(),s);await Qr.ensureDir(Ci.dirname($)),await ht.recordFileChange($),await Qr.writeFile($,S),await Br(d);let _=Ci.extname(s).toLowerCase(),C={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".webp":"image/webp"}[_]||"image/png";return n.isMultiModal!==!1?{text:`SUCCESS: Image successfully generated from prompt [${o}] and saved to [${s}]. Output attached to multimodal part`,binaryPart:{inlineData:{data:S.toString("base64"),mimeType:C}}}:`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 no=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=J(en,{}),a=J(vn,{});return a[o]=s,delete i[o],pe(vn,a),pe(en,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 Ds=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=J(Pt,[]),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(pe(Pt,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 Wl}from"module";import ps from"fs-extra";import Ai from"path";import Bl from"https";var Zr={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 Ul(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"}};Bl.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}`}Ul(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 Su(e){let n=Ai.join(as,e);return ps.existsSync(n)}async function Tu(e){let n=Ai.join(as,e);ps.existsSync(n)&&await ps.unlink(n)}var na=Wl(import.meta.url),ea=na("web-tree-sitter"),ta=!1,sa=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"]),oa=new Set(["export_statement","lexical_declaration","variable_declaration","variable_declarator","pair","assignment_expression"]);function mn(e,n=50){if(!e)return"";let t=e.replace(/\s+/g," ").trim();return t.length>n?t.substring(0,n-3)+"...":t}function ia(e){let n=e.type;if(n==="if_statement"){let o=e.childForFieldName("condition");return o?`if (${mn(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?mn(o.text,40):""})`}if(n==="for_statement"||n==="for_in_statement"||n==="for_of_statement"){let s=e.text.split(`
413
- `)[0].match(/for\s*(?:await\s*)?\((.*)\)/);return s?`for (${mn(s[1],40)})`:"for"}if(n==="switch_statement"){let o=e.childForFieldName("value");return`switch (${o?mn(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?`<${mn(s.text,30)}>`:null}if(["import_declaration","import_from_statement","import_statement","preproc_include"].includes(n))return mn(e.text.split(`
414
- `)[0],60);if(n==="pair"){let o=e.childForFieldName("key");return o?mn(o.text.replace(/["']/g,""),40):null}if(n==="assignment_expression"){let o=e.childForFieldName("left");return o?`${mn(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?mn(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 mn(o.text,40)}return mn(t.text,40)}if(["arrow_function","function_expression","function_declaration"].includes(n)){let o=e.parent;for(;o&&o.type!=="program";){let s=ia(o);if(s)return s;if(!oa.has(o.type))break;o=o.parent}}return null}function jl(e){let n=[];function t(o){for(let s of o.children)sa.has(s.type)?n.push(s):t(s)}return t(e),n}function Hl(e){return e.replace(/_([a-z])/g,n=>n[1].toUpperCase())}function ra(e,n=0,t=!0,o="",s=null,i=12){let a=e.type,r=ia(e),h=sa.has(a)||n===0,d=jl(e),c=h&&n>0&&(oa.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=Hl(a),w=r?`${m} [${r}]`:m;n===0?(l+=`\u{1F4C1} ROOT (Lines: ${g}-${y})
412
+ `}return C.trimEnd()}catch(g){return`ERROR: ${g.message}`}};import Ji from"fs-extra";import $r from"path";var Bl=(e,n={})=>{try{if(e.length<8||e[0]!==137||e[1]!==80||e[2]!==78||e[3]!==71)return e;let t=[],o=[];for(let a=0;a<256;a++){let i=a;for(let h=0;h<8;h++)i&1?i=3988292384^i>>>1:i=i>>>1;o[a]=i}let s=a=>{let i=4294967295;for(let h=0;h<a.length;h++)i=o[(i^a[h])&255]^i>>>8;return(i^4294967295)>>>0},r=(a,i)=>{let h=Buffer.from(a,"ascii"),d=Buffer.from(i,"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,i]of Object.entries(n))i!=null&&t.push(r(a,String(i)));if(t.length===0)return e;if(e.subarray(12,16).toString("ascii")==="IHDR"){let i=e.subarray(0,33),h=e.subarray(33);return Buffer.concat([i,...t,h])}return e}catch{return e}},Cr=async(e,n={})=>{let t=O(e),o=t.prompt||t.text,s=t.path||t.outputPath||t.output||"generated_image.png",r=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"],i=o.toLowerCase();if(a.some(d=>i.includes(d)))return"ERROR: Prompt blocked by system safety filter (inappropriate or unsafe content detected).";try{let d=await Nt();if(!await Pi(d))return`ERROR: Insufficient Quota for selected quality. Either tell user reduce quality or wait for next refresh cycle (${(await Fi()).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(r){let D=r.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),b=`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")}`,x=await fetch(b,{method:"GET",headers:{Authorization:`Bearer ${f}`}});if(!x.ok){let D=x.status,B="";try{B=await x.text()}catch{}return D===402||B.includes("Insufficient balance")||B.includes("PAYMENT_REQUIRED")?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed with status [${D}]: ${B||"Unknown API Error"}`}if((x.headers.get("content-type")||"").includes("application/json")){let D=await x.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 R=await x.arrayBuffer(),S=Buffer.from(R),T={Title:o,Description:"Generated via FluxFlow CLI",Software:"FluxFlow CLI",Author:"FluxFlow","Creation Time":new Date().toISOString(),Prompt:o,Model:`Fluxflow:${p}`,Ratio:r||"1:1",Seed:String(m)};S=Bl(S,T);let $=$r.resolve(process.cwd(),s);await Ji.ensureDir($r.dirname($)),await pt.recordFileChange($),await Ji.writeFile($,S),await Ni(d);let _=$r.extname(s).toLowerCase(),C={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".webp":"image/webp"}[_]||"image/png";return n.isMultiModal!==!1?{text:`SUCCESS: Image successfully generated from prompt [${o}] and saved to [${s}]. Output attached to multimodal part`,binaryPart:{inlineData:{data:S.toString("base64"),mimeType:C}}}:`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=r=>{let a=new RegExp(`${r}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),i=e.match(a);return i?i[2].trim():null},o=t("id"),s=t("summary");if(!o||!s)return"ERROR: Missing 'id' or 'summary' for saveSummary tool.";try{let r=J(tn,{}),a=J(An,{});return a[o]=s,delete r[o],pe(An,a),pe(tn,r),`SUCCESS: Saved summary and purged raw memories for chat [${o}].`}catch(r){let a=r instanceof Error?r.message:String(r);return`ERROR: Failed to save summary for chat [${o}]: ${a}`}};var Ls=async(e,n={})=>{let o=(s=>{let r=new RegExp(`${s}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),a=e.match(r);return a?a[2].trim():null})("id");if(!o)return"ERROR: Missing 'id' parameter for addMemScore tool.";try{let s=J(Ft,[]),r=!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),r=!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(pe(Ft,a),!r)return`WARNING: Memory ID [${o}] not found. Other memories decayed by -0.01.`;let i=a.find(c=>c.id===o),h=i?i.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 r=s instanceof Error?s.message:String(s);return`ERROR: Failed to adjust memory score for [${o}]: ${r}`}};import Ar from"fs-extra";import ps from"path";import{createRequire as jl}from"module";import hs from"fs-extra";import Mr from"path";import Ul from"https";var Qi={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 Wl(e,n=null){let t=n||`https://unpkg.com/tree-sitter-wasms@0.1.13/out/${e}`,o=Mr.join(is,e);return await hs.ensureDir(is),new Promise((s,r)=>{let a={headers:{"User-Agent":"FluxFlow-Agent"}};Ul.get(t,a,i=>{if([301,302,307,308].includes(i.statusCode)&&i.headers.location){let d=i.headers.location;if(!d.startsWith("http")){let c=new URL(t);d=`${c.protocol}//${c.host}${d}`}Wl(e,d).then(s).catch(r);return}if(i.statusCode!==200){r(new Error(`Failed to download ${e}: HTTP ${i.statusCode}`));return}let h=hs.createWriteStream(o);i.pipe(h),h.on("finish",()=>{h.close(),s()})}).on("error",i=>{hs.existsSync(o)&&hs.unlink(o,()=>{}),r(i)})})}function Tu(e){let n=Mr.join(is,e);return hs.existsSync(n)}async function Ru(e){let n=Mr.join(is,e);hs.existsSync(n)&&await hs.unlink(n)}var ta=jl(import.meta.url),Zi=ta("web-tree-sitter"),ea=!1,na=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"]),sa=new Set(["export_statement","lexical_declaration","variable_declaration","variable_declarator","pair","assignment_expression"]);function mn(e,n=50){if(!e)return"";let t=e.replace(/\s+/g," ").trim();return t.length>n?t.substring(0,n-3)+"...":t}function oa(e){let n=e.type;if(n==="if_statement"){let o=e.childForFieldName("condition");return o?`if (${mn(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?mn(o.text,40):""})`}if(n==="for_statement"||n==="for_in_statement"||n==="for_of_statement"){let s=e.text.split(`
413
+ `)[0].match(/for\s*(?:await\s*)?\((.*)\)/);return s?`for (${mn(s[1],40)})`:"for"}if(n==="switch_statement"){let o=e.childForFieldName("value");return`switch (${o?mn(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(r=>r.type==="start_tag")||e,s=o.childForFieldName("name")||o.childForFieldName("tag_name")||o.children.find(r=>r.type==="tag_name");return s?`<${mn(s.text,30)}>`:null}if(["import_declaration","import_from_statement","import_statement","preproc_include"].includes(n))return mn(e.text.split(`
414
+ `)[0],60);if(n==="pair"){let o=e.childForFieldName("key");return o?mn(o.text.replace(/["']/g,""),40):null}if(n==="assignment_expression"){let o=e.childForFieldName("left");return o?`${mn(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?mn(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 mn(o.text,40)}return mn(t.text,40)}if(["arrow_function","function_expression","function_declaration"].includes(n)){let o=e.parent;for(;o&&o.type!=="program";){let s=oa(o);if(s)return s;if(!sa.has(o.type))break;o=o.parent}}return null}function Hl(e){let n=[];function t(o){for(let s of o.children)na.has(s.type)?n.push(s):t(s)}return t(e),n}function Gl(e){return e.replace(/_([a-z])/g,n=>n[1].toUpperCase())}function ra(e,n=0,t=!0,o="",s=null,r=12){let a=e.type,i=oa(e),h=na.has(a)||n===0,d=Hl(e),c=h&&n>0&&(sa.has(a)&&d.length>0||i!==null&&i===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=Gl(a),w=i?`${m} [${i}]`:m;n===0?(l+=`\u{1F4C1} ROOT (Lines: ${g}-${y})
415
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+=ra(g,u,c?t&&m:m,f,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=Zr[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=ea.Parser;if(!ta){let p;try{p=ms.join(ms.dirname(na.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}),ta=!0}let r=new a,h=await ea.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 f=r.parse(d),u=ra(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 zn from"fs";import aa from"path";var so=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=aa.join(An,"plan",i),r=aa.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(`
416
+ `,f+=t?" ":"\u2502 "),u=n+1,p=i}return u>r&&d.length>0?l+=`${f}\u2514\u2500\u2500 ... depth exceeded ...
417
+ `:d.forEach((g,y)=>{let m=y===d.length-1;l+=ra(g,u,c?t&&m:m,f,p,r)}),l}var vr=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=ps.isAbsolute(n)?n:ps.resolve(process.cwd(),n);if(!Ar.existsSync(t))return`ERROR: File not found: ${n}`;let o=ps.extname(t).slice(1).toLowerCase(),s=Qi[o];if(!s)return`ERROR: Unsupported file extension: .${o}`;let r=ps.resolve(is,s);if(!Ar.existsSync(r))return`ERROR: Parser for .${o} not found. Please download it in Settings > Other.`;try{let a=Zi.Parser;if(!ea){let p;try{p=ps.join(ps.dirname(ta.resolve("web-tree-sitter")),"tree-sitter.wasm")}catch{p=ps.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}),ea=!0}let i=new a,h=await Zi.Language.load(r);i.setLanguage(h);let d=await Ar.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=i.parse(d),u=ra(f.rootNode,0,!0," ",null,l);return`\u{1F4C4} File Map for: ${n}
419
+ ${u}`}catch(a){let i=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: ${i}${h}`}};import zn from"fs";import ia from"path";var no=async(e,n={})=>{let{method:t,tasks:o,markDone:s}=O(e),r=n.chatId||"default";if(!t)return'ERROR: Missing "method" argument for todo tool (create/append/get).';let a=ia.join(Mn,"plan",r),i=ia.join(a,"todo.md"),h=l=>{if(!l||Array.isArray(l))return l;let f=String(l).trim();if(f.startsWith("[")&&f.endsWith("]")){let u=f.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);return u?u.map(p=>p.slice(1,-1).replace(/\\(.)/g,"$1")):f.slice(1,-1).split(",").map(p=>p.trim()).filter(Boolean)}return l},d=l=>{let f=h(l);return f?(Array.isArray(f)?f:String(f).split(`
421
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
423
  `:""},c=(l,f)=>{if(!f)return{content:l,markedCount:0};let u=h(f),p=(Array.isArray(u)?u:[u]).map(w=>String(w).replace(/^- \[[xX ]\]\s*/i,"").trim()).filter(Boolean),g=l.split(`
424
- `),y=0,m=!1;for(let w of p){let x=!1;for(let b=0;b<g.length;b++)if(g[b].includes(w)&&/^- \[\s\]/.test(g[b].trim())){g[b]=g[b].replace("- [ ]","- [x]"),x=!0,m=!0,y++;break}if(!x){for(let b=0;b<g.length;b++)if(g[b].toLowerCase().includes(w.toLowerCase())&&/^- \[\s\]/.test(g[b].trim())){g[b]=g[b].replace("- [ ]","- [x]"),x=!0,m=!0,y++;break}}}return{content:m?g.join(`
425
- `):l,markedCount:y}};try{if(zn.existsSync(a)||zn.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 ht.recordFileChange(r),zn.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)
424
+ `),y=0,m=!1;for(let w of p){let b=!1;for(let x=0;x<g.length;x++)if(g[x].includes(w)&&/^- \[\s\]/.test(g[x].trim())){g[x]=g[x].replace("- [ ]","- [x]"),b=!0,m=!0,y++;break}if(!b){for(let x=0;x<g.length;x++)if(g[x].toLowerCase().includes(w.toLowerCase())&&/^- \[\s\]/.test(g[x].trim())){g[x]=g[x].replace("- [ ]","- [x]"),b=!0,m=!0,y++;break}}}return{content:m?g.join(`
425
+ `):l,markedCount:y}};try{if(zn.existsSync(a)||zn.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 pt.recordFileChange(i),zn.writeFileSync(i,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
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 ht.recordFileChange(r),zn.appendFileSync(r,l,"utf8");let f=zn.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(!zn.existsSync(r))return"TODO GET: No task list found for this session.";let l=zn.readFileSync(r,"utf8"),f=0;if(s){let m=c(l,s);m.markedCount>0&&(l=m.content,f=m.markedCount,await ht.recordFileChange(r),zn.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 Oi=async(e,n={})=>{let{runSubagent:t}=await import("./ai-KOH73AH5.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-KOH73AH5.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 la=async(e,n={})=>{let{runSubagent:t}=await import("./ai-KOH73AH5.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,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};Xe.push(u),n.onSubagentUpdate&&n.onSubagentUpdate();let g=[],y={...n,taskId:d,onAskMain:async m=>{let w=`q-${Date.now()}-${Math.floor(Math.random()*1e3)}`,x=null,b=new Promise(S=>{x=S}),E={id:w,question:m,answered:!1,answer:null,askedAt:Date.now(),_resolve:x};return u.questions.push(E),u.status="waiting",n.onSubagentUpdate&&n.onSubagentUpdate(),ko(`[SYSTEM] Background subagent "${u.title}" is WAITING FOR YOUR INPUT: "${m}"
427
+ ${l}`}if(t==="append"){if(!o)return'ERROR: Missing "tasks" for append method.';let l=d(o);await pt.recordFileChange(i),zn.appendFileSync(i,l,"utf8");let f=zn.readFileSync(i,"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(!zn.existsSync(i))return"TODO GET: No task list found for this session.";let l=zn.readFileSync(i,"utf8"),f=0;if(s){let m=c(l,s);m.markedCount>0&&(l=m.content,f=m.markedCount,await pt.recordFileChange(i),zn.writeFileSync(i,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 Ir=async(e,n={})=>{let{runSubagent:t}=await import("./ai-XVH7ZCEN.js"),o=O(e),s=o.task||o.instruction||o.prompt,r=o.model||null,a=o.tools||null;if(!s)return'ERROR: Missing "task" argument for invokeSync.';let i=null;if(a)try{let d=a.trim();d.startsWith("[")&&d.endsWith("]")&&(d=d.substring(1,d.length-1)),i=d.split(",").map(c=>c.trim().replace(/^["']|["']$/g,"")).filter(Boolean)}catch{}let 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,r,i,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-XVH7ZCEN.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 aa=async(e,n={})=>{let{runSubagent:t}=await import("./ai-XVH7ZCEN.js"),o=O(e),s=o.task||o.instruction||o.prompt,r=o.model||null,a=o.title||null,i=o.tools||null;if(!s)return'ERROR: Missing "task" argument for invoke.';let h=null;if(i)try{let m=i.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};Xe.push(u),n.onSubagentUpdate&&n.onSubagentUpdate();let g=[],y={...n,taskId:d,onAskMain:async m=>{let w=`q-${Date.now()}-${Math.floor(Math.random()*1e3)}`,b=null,x=new Promise(S=>{b=S}),E={id:w,question:m,answered:!1,answer:null,askedAt:Date.now(),_resolve:b};return u.questions.push(E),u.status="waiting",n.onSubagentUpdate&&n.onSubagentUpdate(),bo(`[SYSTEM] Background subagent "${u.title}" is WAITING FOR YOUR INPUT: "${m}"
432
432
  Respond using tool: [tool:functions.Answer(id="${d}", answer="...")]
433
- [/SYSTEM]`),await b},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 b=x-400;if(p.chunks=p.chunks.filter(E=>E.time>=b),p.chunks.length>0){let E=p.chunks.reduce((T,$)=>T+$.words,0),R=p.chunks[0].time,S=Math.max(.4,(x-R)/1e3);u.wps=Math.round(E/S*10)/10}}n.onSubagentUpdate&&n.onSubagentUpdate()}};return t(s,y,i,h,50,m=>{if(u.status==="cancelled")return;if(m.startsWith("[Subagent Turn")&&g.length>0&&(u.progress.push([...g]),g=[]),m.includes("[Executing Tool]")){let x=m.match(/\[Executing Tool\]\s*([a-zA-Z0-9_]+)/);x&&(!u.currentTool||u.currentTool==="Thinking")&&(u.currentTool=x[1])}let w=m;if(w.startsWith("[Tool Result]")){let x=w.split(`
434
- `);x.length>5&&(w=x.slice(0,4).join(`
433
+ [/SYSTEM]`),await x},onVisualFeedback:m=>{u.lastChunkTime=Date.now();let w=m.replace(/\x1b\[[0-9;]*m/g,""),b=w.match(/[✔✘✗✖🔍📖→➕↻•]\s*([A-Za-z0-9\s-]+)/);b?u.currentTool=b[1].trim():u.currentTool=w,n.onSubagentUpdate&&n.onSubagentUpdate()},onTokenChunk:(m,w)=>{let b=Date.now();if(u.lastChunkTime=b,u.currentTool="Thinking",typeof w=="number"&&w>0){p.totalWords+=w,p.chunks.push({time:b,words:w});let x=b-400;if(p.chunks=p.chunks.filter(E=>E.time>=x),p.chunks.length>0){let E=p.chunks.reduce((T,$)=>T+$.words,0),R=p.chunks[0].time,S=Math.max(.4,(b-R)/1e3);u.wps=Math.round(E/S*10)/10}}n.onSubagentUpdate&&n.onSubagentUpdate()}};return t(s,y,r,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 b=m.match(/\[Executing Tool\]\s*([a-zA-Z0-9_]+)/);b&&(!u.currentTool||u.currentTool==="Thinking")&&(u.currentTool=b[1])}let w=m;if(w.startsWith("[Tool Result]")){let b=w.split(`
434
+ `);b.length>5&&(w=b.slice(0,4).join(`
435
435
  `)+`
436
- ... [Content/Diff Truncated from Logs] ...`)}g.push(w),n.onSubagentUpdate&&n.onSubagentUpdate()},!0).then(m=>{if(u.status==="cancelled"){u._resolveCompletion&&u._resolveCompletion(m);return}g.length>0&&(u.progress.push([...g]),g=[]),u.status="completed",u.finalAnswer=m,n.onSubagentUpdate&&n.onSubagentUpdate(),ko(`[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-KOH73AH5.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(),ko(`[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 Li=async(e,n={})=>{let o=O(e).id;if(!o)return'ERROR: Missing "id" argument for getProgress.';let s=Xe.find(r=>r.id===o);if(!s)return`ERROR: Subagent task with ID [${o}] not found.`;let i=`Subagent Task Status: ${s.status.toUpperCase()}
437
- `;if(i+=`Title: ${s.title}
438
- `,i+=`Task: ${s.task}
439
- `,s.startedAt){let r=Math.floor((Date.now()-s.startedAt)/1e3);i+=`Elapsed Time: ${r}s
440
- `}if(i+=`Turns Completed: ${s.progress.length}
441
- `,(s.status==="running"||s.status==="waiting")&&(s.currentTool&&(i+=`Current Tool: ${s.currentTool}
442
- `),s.wps>0&&(i+=`TPS: ${s.wps}
443
- `)),s.questions&&s.questions.length>0){let r=s.questions.filter(h=>!h.answered);r.length>0&&(i+=`
436
+ ... [Content/Diff Truncated from Logs] ...`)}g.push(w),n.onSubagentUpdate&&n.onSubagentUpdate()},!0).then(m=>{if(u.status==="cancelled"){u._resolveCompletion&&u._resolveCompletion(m);return}g.length>0&&(u.progress.push([...g]),g=[]),u.status="completed",u.finalAnswer=m,n.onSubagentUpdate&&n.onSubagentUpdate(),bo(`[SYSTEM] Background subagent "${u.title}" (id: ${d}) has FINISHED. Call GetProgress(id="${d}") to see the final result. [/SYSTEM]`),u._resolveCompletion&&u._resolveCompletion(m)}).catch(async m=>{let{isTerminationSignaled:w}=await import("./ai-XVH7ZCEN.js");if(m.message==="Subagent task was cancelled."||u.status==="cancelled"||w()){u.status="cancelled",g.push("[SUBAGENT CANCELLED] Task was cancelled."),u.progress.push([...g]),n.onSubagentUpdate&&n.onSubagentUpdate(),u._resolveCompletion&&u._resolveCompletion(null);return}g.push(`[SUBAGENT FAILURE] Error: ${m.message}`),u.progress.push([...g]),u.status="failed",u.error=m.message,n.onSubagentUpdate&&n.onSubagentUpdate(),bo(`[SYSTEM] Background subagent "${u.title}" (id: ${d}) FAILED with error: ${m.message}. [/SYSTEM]`),u._rejectCompletion&&u._rejectCompletion(m)}),`SUCCESS: Background subagent started. Task ID: ${d}`};var Or=async(e,n={})=>{let o=O(e).id;if(!o)return'ERROR: Missing "id" argument for getProgress.';let s=Xe.find(i=>i.id===o);if(!s)return`ERROR: Subagent task with ID [${o}] not found.`;let r=`Subagent Task Status: ${s.status.toUpperCase()}
437
+ `;if(r+=`Title: ${s.title}
438
+ `,r+=`Task: ${s.task}
439
+ `,s.startedAt){let i=Math.floor((Date.now()-s.startedAt)/1e3);r+=`Elapsed Time: ${i}s
440
+ `}if(r+=`Turns Completed: ${s.progress.length}
441
+ `,(s.status==="running"||s.status==="waiting")&&(s.currentTool&&(r+=`Current Tool: ${s.currentTool}
442
+ `),s.wps>0&&(r+=`TPS: ${s.wps}
443
+ `)),s.questions&&s.questions.length>0){let i=s.questions.filter(h=>!h.answered);i.length>0&&(r+=`
444
444
  **PENDING QUESTION**
445
- `,r.forEach(h=>{i+=`"${h.question}"
446
- `}),i+=`Respond using tool: [tool:functions.Answer(id="${s.id}", answer="...")]
445
+ `,i.forEach(h=>{r+=`"${h.question}"
446
+ `}),r+=`Respond using tool: [tool:functions.Answer(id="${s.id}", answer="...")]
447
447
 
448
- `)}return i+=`
448
+ `)}return r+=`
449
449
  Progress Log:
450
- `,s.progress.forEach((r,h)=>{i+=`--- Turn ${h+1} ---
451
- `;let c=r.filter(l=>!l.startsWith("[SUBAGENT SUCCESS]")).map(l=>{if(l.startsWith("[Subagent Response]")){let f="[Subagent Response]",p=l.substring(f.length),g="tool:functions.";for(;;){let m=p.toLowerCase().indexOf(g);if(m===-1)break;let w=m,x=!1,b=m-1;for(;b>=0&&/\s/.test(p[b]);)b--;b>=0&&p[b]==="["&&(w=b,x=!0);let E=0,R=!1,S=null,T=m;for(;T<p.length;){let $=p[T];if(!S&&($==="'"||$==='"'||$==="`")?S=$:S&&$===S&&p[T-1]!=="\\"&&(S=null),S||($==="("?(E++,R=!0):$===")"&&E--),R&&E===0&&!S){let _=T;if(x){let k=T+1;for(;k<p.length&&/\s/.test(p[k]);)k++;k<p.length&&p[k]==="]"&&(_=k)}p=p.substring(0,w)+p.substring(_+1);break}if(T++,T===p.length){p=p.substring(0,w);break}}}return f+`
452
- `+p.trim()}return l.startsWith("[Executing Tool]")&&l.length>256?l.substring(0,256)+"...[truncated from logs]":l});i+=c.join(`
450
+ `,s.progress.forEach((i,h)=>{r+=`--- Turn ${h+1} ---
451
+ `;let c=i.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,b=!1,x=m-1;for(;x>=0&&/\s/.test(p[x]);)x--;x>=0&&p[x]==="["&&(w=x,b=!0);let E=0,R=!1,S=null,T=m;for(;T<p.length;){let $=p[T];if(!S&&($==="'"||$==='"'||$==="`")?S=$:S&&$===S&&p[T-1]!=="\\"&&(S=null),S||($==="("?(E++,R=!0):$===")"&&E--),R&&E===0&&!S){let _=T;if(b){let k=T+1;for(;k<p.length&&/\s/.test(p[k]);)k++;k<p.length&&p[k]==="]"&&(_=k)}p=p.substring(0,w)+p.substring(_+1);break}if(T++,T===p.length){p=p.substring(0,w);break}}}return f+`
452
+ `+p.trim()}return l.startsWith("[Executing Tool]")&&l.length>256?l.substring(0,256)+"...[truncated from logs]":l});r+=c.join(`
453
453
  `)+`
454
454
 
455
- `}),s.status==="completed"&&s.finalAnswer?i+=`Final Answer:
455
+ `}),s.status==="completed"&&s.finalAnswer?r+=`Final Answer:
456
456
  ${s.finalAnswer}
457
- `:s.status==="failed"&&s.error&&(i+=`Failure Error: ${s.error}
458
- `),i.replace(/\r\n/g,`
457
+ `:s.status==="failed"&&s.error&&(r+=`Failure Error: ${s.error}
458
+ `),r.replace(/\r\n/g,`
459
459
  `).replace(/\n{3,}/g,`
460
460
 
461
- `).trim().replace(/\[TOOL RESULT\]/gi,"TOOL RESULT:")};var ca=async(e,n={})=>{let o=O(e).id;if(!o)return'ERROR: Missing "id" argument for cancel.';let s=Xe.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 xt from"fs-extra";import St from"path";var Gl=["node_modules","dist","bin","logs",".git",".fluxflow","secret",".gemini",".agents","tmp","temp","build","out","snapshots"];async function oo(e,n=e){let t={},o=await xt.readdir(e,{withFileTypes:!0}).catch(()=>[]);for(let s of o){if(Gl.includes(s.name))continue;let i=St.join(e,s.name),a=St.relative(n,i).replace(/\\/g,"/");if(s.isDirectory()){let r=await oo(i,n);Object.assign(t,r)}else{let r=await xt.stat(i).catch(()=>null);r&&(t[a]={size:r.size,mtime:r.mtimeMs})}}return t}async function da(e,n){await xt.ensureDir(e);for(let t of Object.keys(n)){let o=St.join(process.cwd(),t),s=St.join(e,t);await xt.ensureDir(St.dirname(s)),await xt.copyFile(o,s).catch(()=>{})}}async function Di(e,n,t=null,o=null){if(!await xt.pathExists(e))return;o||(o=e);let s=await xt.readdir(e,{withFileTypes:!0}).catch(()=>[]);for(let i of s){let a=St.join(e,i.name),r=St.join(n,i.name);if(i.isDirectory())await Di(a,r,t,o);else{let h=St.relative(o,a).replace(/\\/g,"/"),d=await xt.pathExists(r);d&&await xt.chmod(r,438).catch(()=>{}),await xt.ensureDir(St.dirname(r));let c=await xt.copyFile(a,r).then(()=>!0).catch(()=>!1);await xt.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 xt.remove(n).catch(()=>{}),await xt.ensureDir(n);let t=await oo(process.cwd());await da(St.join(n,"initial"),t);let o=J(un,{});o[e]={initialManifest:t,currentManifest:t,checkpoints:[{id:"initial",timestamp:new Date().toISOString(),newFiles:[],modifiedFiles:[],deletedFiles:[],toolsUsed:[]}]},pe(un,o)}catch{}},async recordTurnDelta(e,n,t=[]){try{let o=J(un,{}),s=o[e];if(!s)return;let i=s.currentManifest||s.initialManifest,a=await oo(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 da(f,l)}s.checkpoints.push({id:`turn_${n}`,timestamp:new Date().toISOString(),newFiles:r,modifiedFiles:h,deletedFiles:d,toolsUsed:t}),s.currentManifest=a,pe(un,o)}catch{}},async getCheckpoints(e){try{let t=J(un,{})[e];return t?t.checkpoints||[]:[]}catch{return[]}},async rollbackToCheckpoint(e,n){try{let t=J(un,{}),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 oo(process.cwd());for(let c of Object.keys(h)){let l=St.join(process.cwd(),c);await xt.chmod(l,438).catch(()=>{}),await xt.remove(l).catch(()=>{})}let d=St.join(a,"initial");await Di(d,process.cwd(),r,d);for(let c=1;c<=i;c++){let l=s[c],f=St.join(a,l.id);if(await Di(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 xt.chmod(p,438).catch(()=>{}),await xt.remove(p).catch(()=>{})}}return o.checkpoints=s.slice(0,i+1),o.currentManifest=await oo(process.cwd()),pe(un,t),{checkpointId:n,stats:r}}catch(t){throw new Error(`Rollback failed: ${t.message}`)}},async getLatestFileChanges(e){try{let t=J(un,{})[e];if(!t||!t.checkpoints||t.checkpoints.length===0)return{newFiles:[],modifiedFiles:[],deletedFiles:[]};let o=t.checkpoints[t.checkpoints.length-1];return{newFiles:o.newFiles||[],modifiedFiles:o.modifiedFiles||[],deletedFiles:o.deletedFiles||[]}}catch{return{newFiles:[],modifiedFiles:[],deletedFiles:[]}}},async cleanup(e){try{let n=St.join(An,"snapshots",e);await xt.remove(n).catch(()=>{});let t=J(un,{});t[e]&&(delete t[e],pe(un,t))}catch{}}};var Pi=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 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 la=async(e,n={})=>{let o=O(e).id;if(!o)return'ERROR: Missing "id" argument for cancel.';let s=Xe.find(r=>r.id===o);return s?s.status==="completed"||s.status==="failed"?`INFO: Subagent task with ID [${o}] has already finished with status [${s.status.toUpperCase()}].`:s.status==="cancelled"?`INFO: Subagent task with ID [${o}] is already cancelled.`:(s.status="cancelled",n.onSubagentUpdate&&n.onSubagentUpdate(),`SUCCESS: Subagent task with ID [${o}] has been cancelled.`):`ERROR: Subagent task with ID [${o}] not found.`};import bt from"fs-extra";import Tt from"path";var ql=["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 bt.readdir(e,{withFileTypes:!0}).catch(()=>[]);for(let s of o){if(ql.includes(s.name))continue;let r=Tt.join(e,s.name),a=Tt.relative(n,r).replace(/\\/g,"/");if(s.isDirectory()){let i=await so(r,n);Object.assign(t,i)}else{let i=await bt.stat(r).catch(()=>null);i&&(t[a]={size:i.size,mtime:i.mtimeMs})}}return t}async function ca(e,n){await bt.ensureDir(e);for(let t of Object.keys(n)){let o=Tt.join(process.cwd(),t),s=Tt.join(e,t);await bt.ensureDir(Tt.dirname(s)),await bt.copyFile(o,s).catch(()=>{})}}async function Lr(e,n,t=null,o=null){if(!await bt.pathExists(e))return;o||(o=e);let s=await bt.readdir(e,{withFileTypes:!0}).catch(()=>[]);for(let r of s){let a=Tt.join(e,r.name),i=Tt.join(n,r.name);if(r.isDirectory())await Lr(a,i,t,o);else{let h=Tt.relative(o,a).replace(/\\/g,"/"),d=await bt.pathExists(i);d&&await bt.chmod(i,438).catch(()=>{}),await bt.ensureDir(Tt.dirname(i));let c=await bt.copyFile(a,i).then(()=>!0).catch(()=>!1);await bt.chmod(i,438).catch(()=>{}),t&&(c?d?t.replaced++:t.restored++:t.failed.push(h))}}}var Kn={async takeInitialSnapshot(e){try{let n=Tt.join(Mn,"snapshots",e);await bt.remove(n).catch(()=>{}),await bt.ensureDir(n);let t=await so(process.cwd());await ca(Tt.join(n,"initial"),t);let o=J(un,{});o[e]={initialManifest:t,currentManifest:t,checkpoints:[{id:"initial",timestamp:new Date().toISOString(),newFiles:[],modifiedFiles:[],deletedFiles:[],toolsUsed:[]}]},pe(un,o)}catch{}},async recordTurnDelta(e,n,t=[]){try{let o=J(un,{}),s=o[e];if(!s)return;let r=s.currentManifest||s.initialManifest,a=await so(process.cwd()),i=[],h=[],d=[];for(let[l,f]of Object.entries(a)){let u=r[l];u?(u.size!==f.size||u.mtime!==f.mtime)&&h.push(l):i.push(l)}for(let l of Object.keys(r))a[l]||d.push(l);let c=[...i,...h];if(c.length>0||d.length>0){let l={};for(let u of c)l[u]=a[u];let f=Tt.join(Mn,"snapshots",e,`turn_${n}`);await ca(f,l)}s.checkpoints.push({id:`turn_${n}`,timestamp:new Date().toISOString(),newFiles:i,modifiedFiles:h,deletedFiles:d,toolsUsed:t}),s.currentManifest=a,pe(un,o)}catch{}},async getCheckpoints(e){try{let t=J(un,{})[e];return t?t.checkpoints||[]:[]}catch{return[]}},async rollbackToCheckpoint(e,n){try{let t=J(un,{}),o=t[e];if(!o)throw new Error("No session active for Advance Rollback.");let s=o.checkpoints||[],r=s.findIndex(c=>c.id===n);if(r===-1)throw new Error(`Checkpoint [${n}] not found.`);let a=Tt.join(Mn,"snapshots",e),i={restored:0,replaced:0,failed:[]},h=await so(process.cwd());for(let c of Object.keys(h)){let l=Tt.join(process.cwd(),c);await bt.chmod(l,438).catch(()=>{}),await bt.remove(l).catch(()=>{})}let d=Tt.join(a,"initial");await Lr(d,process.cwd(),i,d);for(let c=1;c<=r;c++){let l=s[c],f=Tt.join(a,l.id);if(await Lr(f,process.cwd(),i,f),l.deletedFiles&&l.deletedFiles.length>0)for(let u of l.deletedFiles){let p=Tt.join(process.cwd(),u);await bt.chmod(p,438).catch(()=>{}),await bt.remove(p).catch(()=>{})}}return o.checkpoints=s.slice(0,r+1),o.currentManifest=await so(process.cwd()),pe(un,t),{checkpointId:n,stats:i}}catch(t){throw new Error(`Rollback failed: ${t.message}`)}},async getLatestFileChanges(e){try{let t=J(un,{})[e];if(!t||!t.checkpoints||t.checkpoints.length===0)return{newFiles:[],modifiedFiles:[],deletedFiles:[]};let o=t.checkpoints[t.checkpoints.length-1];return{newFiles:o.newFiles||[],modifiedFiles:o.modifiedFiles||[],deletedFiles:o.deletedFiles||[]}}catch{return{newFiles:[],modifiedFiles:[],deletedFiles:[]}}},async cleanup(e){try{let n=Tt.join(Mn,"snapshots",e);await bt.remove(n).catch(()=>{});let t=J(un,{});t[e]&&(delete t[e],pe(un,t))}catch{}}};var Dr=async(e,n={})=>{let t=O(e),o=t.method,s=t.id,r=n.chatId;if(!n.systemSettings?.advanceRollback)return"ERROR: Advance Rollback feature is currently disabled in settings under Security. Tell user to enable it.";if(!r)return"ERROR: No active chat transaction found for rollback.";if(o==="getCheckpoint"){let i=await Kn.getCheckpoints(r);if(i.length===0)return"No checkpoints available.";let 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
- `;for(let l of r)if(l.id==="initial")c+=`--- Initial State (id: initial) ---
463
+ `;for(let l of i)if(l.id==="initial")c+=`--- Initial State (id: initial) ---
464
464
  Tools Used: User Prompted for task
465
465
 
466
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
467
  Tools Used: ${u}
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 i=await Kn.rollbackToCheckpoint(r,s),{checkpointId:h,stats:d}=i,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,49 +475,49 @@ 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=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=Xe.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(i){return`ERROR: ${i.message}`}}else return`ERROR: Invalid method "${o}". Use "getCheckpoint" or "forceRevert".`};var Ds=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 r=Xe.find(h=>h.id===o);if(!r)return`ERROR: Subagent task with ID [${o}] not found.`;if(r.status==="completed")return`SUCCESS: Subagent task [${o}] completed.
479
479
  Final Answer:
480
- ${i.finalAnswer||"(No output)"}`;if(i.status==="failed")return`ERROR: Subagent task [${o}] failed.
481
- Error: ${i.error||"Unknown error"}`;if(i.status==="cancelled")return`INFO: Subagent task [${o}] was cancelled.`;let a,r=new Promise(h=>{a=setTimeout(()=>{h({type:"timeout"})},s*1e3)});try{let h=await Promise.race([i.completionPromise.then(()=>({type:"completion"})),r]);return clearTimeout(a),h.type==="timeout"?`TIMEOUT: Subagent task [${o}] is still running (status: ${i.status.toUpperCase()}) after ${s}s. You can continue other work or call Await again.`:i.status==="completed"?`SUCCESS: Subagent task [${o}] completed.
480
+ ${r.finalAnswer||"(No output)"}`;if(r.status==="failed")return`ERROR: Subagent task [${o}] failed.
481
+ Error: ${r.error||"Unknown error"}`;if(r.status==="cancelled")return`INFO: Subagent task [${o}] was cancelled.`;let a,i=new Promise(h=>{a=setTimeout(()=>{h({type:"timeout"})},s*1e3)});try{let h=await Promise.race([r.completionPromise.then(()=>({type:"completion"})),i]);return clearTimeout(a),h.type==="timeout"?`TIMEOUT: Subagent task [${o}] is still running (status: ${r.status.toUpperCase()}) after ${s}s. You can continue other work or call Await again.`:r.status==="completed"?`SUCCESS: Subagent task [${o}] completed.
482
482
  Final Answer:
483
- ${i.finalAnswer||"(No output)"}`:i.status==="failed"?`ERROR: Subagent task [${o}] failed.
484
- Error: ${i.error||"Unknown error"}`:i.status==="cancelled"?`INFO: Subagent task [${o}] was cancelled.`:`INFO: Subagent task [${o}] status changed to ${i.status.toUpperCase()}.`}catch(h){return clearTimeout(a),`ERROR: Exception while awaiting subagent [${o}]: ${h.message}`}};var Fs=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=Xe.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 io=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=Xe.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 ln,keyboard as Nt,Button as ro,Key as L,Point as ao,clipboard as ql}from"@nut-tree-fork/nut-js";ln.config.autoDelayMs=50;Nt.config.autoDelayMs=50;async function Fi(){try{await Nt.releaseKey(L.LeftControl,L.RightControl,L.LeftAlt,L.RightAlt,L.LeftShift,L.RightShift,L.LeftSuper,L.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 ln.setPosition(new ao(o.x,o.y)),`SUCCESS: Moved mouse to grid target ${typeof n=="string"?n:`(${o.x}, ${o.y})`}`;case"click":{await ln.setPosition(new ao(o.x,o.y));let s=t.button==="right"?ro.RIGHT:t.button==="middle"?ro.MIDDLE:ro.LEFT;return t.clickType==="double"?await ln.doubleClick(s):await ln.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 ln.setPosition(new ao(s.x,s.y)),await ln.pressButton(ro.LEFT),await ln.setPosition(new ao(i.x,i.y)),await ln.releaseButton(ro.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 ln.setPosition(new ao(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 ln.scrollUp(120):await ln.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 fa={enter:L.Enter,return:L.Return,escape:L.Escape,esc:L.Escape,backspace:L.Backspace,tab:L.Tab,space:L.Space,up:L.Up,down:L.Down,left:L.Left,right:L.Right,ctrl:L.LeftControl,control:L.LeftControl,alt:L.LeftAlt,shift:L.LeftShift,cmd:L.LeftCmd,win:L.LeftWin,meta:L.LeftWin,super:L.LeftSuper,a:L.A,b:L.B,c:L.C,d:L.D,e:L.E,f:L.F,g:L.G,h:L.H,i:L.I,j:L.J,k:L.K,l:L.L,m:L.M,n:L.N,o:L.O,p:L.P,q:L.Q,r:L.R,s:L.S,t:L.T,u:L.U,v:L.V,w:L.W,x:L.X,y:L.Y,z:L.Z,0:L.Num0,1:L.Num1,2:L.Num2,3:L.Num3,4:L.Num4,5:L.Num5,6:L.Num6,7:L.Num7,8:L.Num8,9:L.Num9,f1:L.F1,f2:L.F2,f3:L.F3,f4:L.F4,f5:L.F5,f6:L.F6,f7:L.F7,f8:L.F8,f9:L.F9,f10:L.F10,f11:L.F11,f12:L.F12},ua=e=>{if(!e)return;let n=String(e).toLowerCase().trim();if(fa[n]!==void 0)return fa[n];if(L[e]!==void 0)return L[e];if(L[n.toUpperCase()]!==void 0)return L[n.toUpperCase()]};async function Ln(e,n,t={}){try{switch(e.toLowerCase()){case"type":{if(typeof n!="string")return"ERROR: Type action requires a valid string input";await Fi(),await ql.setContent(n);let s=process.platform==="darwin"?L.LeftSuper:L.LeftControl;return await Nt.pressKey(s,L.V),await Nt.releaseKey(s,L.V),await Fi(),t.autoPressEnter?(await new Promise(i=>setTimeout(i,50)),await Nt.type(L.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=ua(n);return o===void 0?`ERROR: Unknown key name "${n}"`:(await Nt.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=>ua(s)).filter(s=>s!==void 0);return o.length===0?"ERROR: Invalid key combination":(await Nt.pressKey(...o),await Nt.releaseKey(...o),`SUCCESS: Executed key combination [${n.join(" + ")}]`)}case"clear_input":return await Nt.pressKey(L.LeftControl,L.A),await Nt.releaseKey(L.LeftControl,L.A),await Nt.type(L.Backspace),"SUCCESS: Cleared active text input (Select All + Backspace)";case"browser_back":{let o=process.platform==="darwin";return o?(await Nt.pressKey(L.LeftSuper,L.Left),await Nt.releaseKey(L.LeftSuper,L.Left)):(await Nt.pressKey(L.LeftAlt,L.Left),await Nt.releaseKey(L.LeftAlt,L.Left)),await Fi(),`SUCCESS: Browser back navigation (${o?"Cmd+Left":"Alt+Left"})`}default:return`ERROR: Unsupported keyboard action "${e}"`}}catch(o){return`ERROR: Keyboard action failed: ${o.message}`}}var lo=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 Ln(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 ga from"screenshot-desktop";import fo from"sharp";import ha from"fs-extra";import pa from"path";import"@nut-tree-fork/nut-js";async function Ni(e,n,t){if(!(!process.env.SHOW_DEBUG_GRID&&!process.env.DEBUG_OCR))try{let o=pa.resolve(process.cwd(),"screenshots",e);await ha.ensureDir(o),await ha.writeFile(pa.join(o,n),t)}catch{}}function zl(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Kl(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 Yl(e){return e<=4?0:e<=8?1:2}async function Bi(e,n=3){let t=await fo(e).metadata();return fo(e).resize(Math.round(t.width*n),Math.round(t.height*n),{kernel:"lanczos3"}).greyscale().normalise().toBuffer()}function Vl(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 Xl(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=Vl(e.tsv);e.words=n.words,e.lines=n.lines}}}function Ui(e,n,t=0,o=0,s=1){Xl(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${zl(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=Yl(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&&Kl(d,n,r)<=r&&h.bbox&&a.push(i(h.bbox))}}return a}function Wi(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 Lo=null;async function Ql(){return Lo||(Lo=(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 Lo=null,e})),Lo}var co=null,ma=null;async function Zl(){let{getActiveDisplay:e}=await import("./screen_grid-JSAE3BZG.js"),n=await e();if(co&&ma===n)return co;ma=n,co={format:"png"};try{let t=await ga.listDisplays();t&&t.length>0&&(co={format:"png",screen:(t[n]||t[0]).id})}catch{}return co}var ji=async(e,n={})=>{let t=!!(process.env.SHOW_DEBUG_GRID||process.env.DEBUG_OCR||process.env.VERBOSE),o=performance.now(),s=o,i=u=>{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) -> ${u}`),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 u=r?kr(r):null;i("Getting display options");let p=await Zl();i("Taking desktop screenshot");let g=await ga(p);i("Getting image metadata");let y=await fo(g).metadata(),m=y.width||1920,w=y.height||1080,x=u?{x:Math.round(u.x*(m/1280)),y:Math.round(u.y*(w/720))}:{x:m/2,y:w/2},b=c.toLowerCase().trim();i("Acquiring OCR worker");let E=await Ql(),R=null,S="",T=u?220:500;if(u){i("Pass 1: Cropping target crop (3x zoom window, 2x upscale)");let $=Math.min(Math.round(m/3),m),_=Math.min(Math.round(w/3),w),k=Math.max(0,Math.min(m-$,x.x-Math.floor($/2))),C=Math.max(0,Math.min(w-_,x.y-Math.floor(_/2))),I=await fo(g).extract({left:k,top:C,width:$,height:_}).toBuffer(),D=2,B=await Bi(I,D),N=b.replace(/[^a-z0-9]/g,"_");await Ni("cropped",`crop_${Date.now()}_${N}.png`,B),i("Pass 1: Running Tesseract OCR recognize on crop (PSM 11 - Sparse Text)"),await E.setParameters({tessedit_pageseg_mode:"11"});let{data:Y}=await E.recognize(B,{},{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 ne=Ui(Y,b,k,C,D);if(ne.length>0){let Ie=Wi(ne,x);Ie&&(Ie.containsPoint||Ie.dist<=T)&&(R=Ie,S="centered target crop OCR")}}}if(!R){i("Pass 2: Entering Full-Screen OCR (broad scan, PSM 3 - Auto)");let $=await Bi(g,2),_=b.replace(/[^a-z0-9]/g,"_");await Ni("fullscreen",`full_${Date.now()}_${_}.png`,$),i("Pass 2: Running Tesseract on full screen"),await E.setParameters({tessedit_pageseg_mode:"3"});let{data:k}=await E.recognize($,{},{tsv:!0,blocks:!0});if(i("Pass 2: Full-screen OCR finished"),k&&k.text){let C=Ui(k,b,0,0,2);if(C.length>0){let I=Wi(C,x);I&&(R=I,S="full-screen OCR")}}}if(!R){i("Pass 3: Entering Tiled OCR fallback (high-res 3x)");let $=Jl(m,w,x.x,x.y),_=b.replace(/[^a-z0-9]/g,"_");await E.setParameters({tessedit_pageseg_mode:"11"});for(let k=0;k<$.length;k++){let C=$[k];i(`Pass 3: Preprocessing tile ${k+1}/${$.length}`);let I=await fo(g).extract({left:C.x0,top:C.y0,width:C.w,height:C.h}).toBuffer(),D=await Bi(I,3);await Ni("tiles",`tile_${k+1}_${Date.now()}_${_}.png`,D),i(`Pass 3: Running Tesseract on tile ${k+1}`);let{data:B}=await E.recognize(D,{},{tsv:!0,blocks:!0});if(!B||!B.text)continue;let N=Ui(B,b,C.x0,C.y0,3);if(N.length>0){let Y=Wi(N,x);if(Y){R=Y,S=`tile ${k+1} OCR (${C.containsTarget?"target tile":`offset ${C.x0},${C.y0}`})`;break}}}}if(R){let $={x:Math.round(R.x*(1280/m)),y:Math.round(R.y*(720/w))};i(`Executing mouse click on matched target (${S})`);let _=await On("click",$,{button:d,clickType:h});return i("Click completed successfully"),`${_} (${S} for "${c}" at ${Math.round(R.dist)}px distance)`}else t&&console.log(`[OCR] No match found for "${c}". Falling back to gridId.`)}catch(u){t&&console.error("[OCR Error]",u)}i(`Executing mouse click on fallback gridId: ${l}`);let f=await On("click",l,{button:d,clickType:h});return i("Fallback click completed"),f};var Hi=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 Gi=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 Do=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 Ln("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 Ln("clear_input");if(s==="back"||s==="browser_back"||s==="browserBack")return await Ln("browser_back");if(s.includes(";")||s.includes("+")){let i=s.split(/[;+]/).map(a=>a.trim()).filter(Boolean);return await Ln("key_combination",i)}return await Ln("key_press",s)};var Fo=async(e,n={})=>"SUCCESS: Screen recapture requested. The latest gridded screenshot is provided for your next decision.";var ec={web_search:di,web_scrape:fi,memory:ui,chat:hi,view_file:Zs,write_file:pi,update_file:xi,exec_command:si,read_folder:ki,write_pdf:Ti,write_docx:Ei,search_keyword:to,generate_image:Mi,saveSummary:no,addMemScore:Ds,file_map:Ii,todo:so,Todo:so,goal:so,Goal:so,invokeSync:Oi,invoke:la,getProgress:Li,cancel:ca,awaitSubagent:Ps,answerSubagent:Fs,steerSubagent:io,computer_action:lo,computer_use:lo,ComputerAction:lo,ComputerUse:lo,click:ji,Click:ji,drag:Hi,Drag:Hi,scroll:Gi,Scroll:Gi,keyboard_typing:Do,KeyboardTyping:Do,keyboardtyping:Do,key_press:Po,KeyPress:Po,keypress:Po,recapture_screen:Fo,RecaptureScreen:Fo,recapturescreen:Fo,invoke_sync:Oi,get_progress:Li,await_subagent:Ps,answer_subagent:Fs,steer_subagent:io,steer:io,Steer:io,ask:Si,Ask:Si,WebSearch:di,WebScrape:fi,ReadFile:Zs,ReadFolder:ki,WriteFile:pi,PatchFile:xi,WritePDF:Ti,WriteDoc:Ei,Run:si,SearchKeyword:to,CodeSearch:to,code_search:to,Memory:ui,Chat:hi,GenerateImage:Mi,saveSumary:no,SaveSummary:no,SaveSumary:no,add_mem_score:Ds,AddMemScore:Ds,addMemoryScore:Ds,AddMemoryScore:Ds,FileMap:Ii,answer:Fs,Answer:Fs,AnswerSubagent:Fs,await:Ps,Await:Ps,AwaitSubagent:Ps,EmergencyRollback:Pi,emergency_rollback:Pi},uo=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=ec[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 De from"fs";import tc from"gradient-string";var qi=["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 ya=[{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"]}],ho={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 No=null;var wa=(e="Dark")=>{let n;e==="Mystery"||e==="Chaos"?(No||(No=ya[Math.floor(Math.random()*ya.length)]),n={...No,id:"Mystery"}):(No=null,ho[e]?n=ho[e]:e==="GitHub"?n=ho["GitHub Dark"]:e==="Transparent"?n=ho["Transparent Dark"]:n=ho.Dark);let t=n.codeText||n.secondary||n.info||n.logoGradient&&n.logoGradient[0]||"cyan";return{...n,codeText:t}};var nc=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",Ip=(e=2)=>{let n=nc();return n==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)},Op=(e="...",n="Loading...",t="Dark")=>{let o=qi[Math.floor(Math.random()*qi.length)],s=wa(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=tc(c).multiline(d.join(`
483
+ ${r.finalAnswer||"(No output)"}`:r.status==="failed"?`ERROR: Subagent task [${o}] failed.
484
+ Error: ${r.error||"Unknown error"}`:r.status==="cancelled"?`INFO: Subagent task [${o}] was cancelled.`:`INFO: Subagent task [${o}] status changed to ${r.status.toUpperCase()}.`}catch(h){return clearTimeout(a),`ERROR: Exception while awaiting subagent [${o}]: ${h.message}`}};var Ps=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 r=Xe.find(i=>i.id===o);if(!r)return`ERROR: Subagent task with ID [${o}] not found.`;if(!r.questions||r.questions.length===0)return`INFO: Subagent task [${o}] has no pending questions.`;let a=r.questions.filter(i=>!i.answered);return a.length===0?`INFO: Subagent task [${o}] has no unanswered questions.`:(a.forEach(i=>{i.answered=!0,i.answer=s,i.answeredAt=Date.now(),i._resolve&&i._resolve(s)}),r.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 r=Xe.find(a=>a.id===o);return r?r.status==="completed"||r.status==="failed"||r.status==="cancelled"?`ERROR: Cannot steer subagent task [${o}] because it has already finished with status [${r.status.toUpperCase()}].`:(typeof r.steer=="function"?r.steer(s):(r.pendingSteerMessages||(r.pendingSteerMessages=[]),r.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 ln,keyboard as Bt,Button as ro,Key as L,Point as io,clipboard as zl}from"@nut-tree-fork/nut-js";ln.config.autoDelayMs=50;Bt.config.autoDelayMs=50;async function Pr(){try{await Bt.releaseKey(L.LeftControl,L.RightControl,L.LeftAlt,L.RightAlt,L.LeftShift,L.RightShift,L.LeftSuper,L.RightSuper)}catch{}}async function In(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 ln.setPosition(new io(o.x,o.y)),`SUCCESS: Moved mouse to grid target ${typeof n=="string"?n:`(${o.x}, ${o.y})`}`;case"click":{await ln.setPosition(new io(o.x,o.y));let s=t.button==="right"?ro.RIGHT:t.button==="middle"?ro.MIDDLE:ro.LEFT;return t.clickType==="double"?await ln.doubleClick(s):await ln.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),r=await zs(t.to);return!s||!r?'ERROR: Drag requires valid "from" and "to" target coordinates/grid codes.':(await ln.setPosition(new io(s.x,s.y)),await ln.pressButton(ro.LEFT),await ln.setPosition(new io(r.x,r.y)),await ln.releaseButton(ro.LEFT),`SUCCESS: Dragged mouse from (${s.x}, ${s.y}) to (${r.x}, ${r.y})`)}case"scroll":{let s=o||await zs({x:640,y:360});s&&(await ln.setPosition(new io(s.x,s.y)),await new Promise(h=>setTimeout(h,60)));let r=parseInt(t.amount,10);(isNaN(r)||r<=0)&&(r=5);let a=r>50?Math.min(20,Math.max(1,Math.round(r/100))):Math.min(20,r),i=t.direction==="up";for(let h=0;h<a;h++)i?await ln.scrollUp(120):await ln.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 da={enter:L.Enter,return:L.Return,escape:L.Escape,esc:L.Escape,backspace:L.Backspace,tab:L.Tab,space:L.Space,up:L.Up,down:L.Down,left:L.Left,right:L.Right,ctrl:L.LeftControl,control:L.LeftControl,alt:L.LeftAlt,shift:L.LeftShift,cmd:L.LeftCmd,win:L.LeftWin,meta:L.LeftWin,super:L.LeftSuper,a:L.A,b:L.B,c:L.C,d:L.D,e:L.E,f:L.F,g:L.G,h:L.H,i:L.I,j:L.J,k:L.K,l:L.L,m:L.M,n:L.N,o:L.O,p:L.P,q:L.Q,r:L.R,s:L.S,t:L.T,u:L.U,v:L.V,w:L.W,x:L.X,y:L.Y,z:L.Z,0:L.Num0,1:L.Num1,2:L.Num2,3:L.Num3,4:L.Num4,5:L.Num5,6:L.Num6,7:L.Num7,8:L.Num8,9:L.Num9,f1:L.F1,f2:L.F2,f3:L.F3,f4:L.F4,f5:L.F5,f6:L.F6,f7:L.F7,f8:L.F8,f9:L.F9,f10:L.F10,f11:L.F11,f12:L.F12},fa=e=>{if(!e)return;let n=String(e).toLowerCase().trim();if(da[n]!==void 0)return da[n];if(L[e]!==void 0)return L[e];if(L[n.toUpperCase()]!==void 0)return L[n.toUpperCase()]};async function On(e,n,t={}){try{switch(e.toLowerCase()){case"type":{if(typeof n!="string")return"ERROR: Type action requires a valid string input";await Pr(),await zl.setContent(n);let s=process.platform==="darwin"?L.LeftSuper:L.LeftControl;return await Bt.pressKey(s,L.V),await Bt.releaseKey(s,L.V),await Pr(),t.autoPressEnter?(await new Promise(r=>setTimeout(r,50)),await Bt.type(L.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=fa(n);return o===void 0?`ERROR: Unknown key name "${n}"`:(await Bt.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=>fa(s)).filter(s=>s!==void 0);return o.length===0?"ERROR: Invalid key combination":(await Bt.pressKey(...o),await Bt.releaseKey(...o),`SUCCESS: Executed key combination [${n.join(" + ")}]`)}case"clear_input":return await Bt.pressKey(L.LeftControl,L.A),await Bt.releaseKey(L.LeftControl,L.A),await Bt.type(L.Backspace),"SUCCESS: Cleared active text input (Select All + Backspace)";case"browser_back":{let o=process.platform==="darwin";return o?(await Bt.pressKey(L.LeftSuper,L.Left),await Bt.releaseKey(L.LeftSuper,L.Left)):(await Bt.pressKey(L.LeftAlt,L.Left),await Bt.releaseKey(L.LeftAlt,L.Left)),await Pr(),`SUCCESS: Browser back navigation (${o?"Cmd+Left":"Alt+Left"})`}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 r=o.toLowerCase();if(r.startsWith("mouse_")||["move","click","drag","scroll"].includes(r)){let a=r.replace("mouse_","");return await In(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(r.startsWith("key_")||r==="type"||r==="press"){let a=r;r==="press"&&(a="key_press");let i=t.autoPressEnter===!0||t.autoPressEnter==="true"||t.enter===!0||t.enter==="true";return await On(a,s||t.text||t.keys,{...t,autoPressEnter:i})}return`ERROR: Unrecognized action "${o}". Supported actions: move, click, drag, scroll, type, key_press, key_combination.`};import ma from"screenshot-desktop";import co from"sharp";import ua from"fs-extra";import ha from"path";import"@nut-tree-fork/nut-js";async function Fr(e,n,t){if(!(!process.env.SHOW_DEBUG_GRID&&!process.env.DEBUG_OCR))try{let o=ha.resolve(process.cwd(),"screenshots",e);await ua.ensureDir(o),await ua.writeFile(ha.join(o,n),t)}catch{}}function Kl(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Yl(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,r)=>r);for(let s=1;s<=e.length;s++){let r=[s],a=s;for(let i=1;i<=n.length;i++){let h=e[s-1]===n[i-1]?0:1,d=Math.min(r[i-1]+1,o[i]+1,o[i-1]+h);r.push(d),d<a&&(a=d)}if(o=r,a>t)return t+1}return o[n.length]}function Vl(e){return e<=4?0:e<=8?1:2}async function Nr(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 Xl(e){if(!e)return{words:[],lines:[]};let n=[],t=new Map;for(let s of e.split(`
485
+ `)){let r=s.split(" ");if(r.length<12||parseInt(r[0])!==5)continue;let i=r[2],h=r[3],d=r[4],c=parseInt(r[6]),l=parseInt(r[7]),f=parseInt(r[8]),u=parseInt(r[9]),p=parseFloat(r[10]),g=r.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=`${i}_${h}_${d}`;t.has(w)||t.set(w,{words:[],bbox:{x0:1/0,y0:1/0,x1:-1/0,y1:-1/0}});let b=t.get(w);b.words.push(m),b.bbox.x0=Math.min(b.bbox.x0,y.x0),b.bbox.y0=Math.min(b.bbox.y0,y.y0),b.bbox.x1=Math.max(b.bbox.x1,y.x1),b.bbox.y1=Math.max(b.bbox.y1,y.y1)}let o=[];for(let s of t.values())s.words.length>0&&o.push({text:s.words.map(r=>r.text).join(" "),bbox:s.bbox,words:s.words});return{words:n,lines:o}}function Jl(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=Xl(e.tsv);e.words=n.words,e.lines=n.lines}}}function Br(e,n,t=0,o=0,s=1){Jl(e);let r=i=>({x0:Math.round(i.x0/s)+t,y0:Math.round(i.y0/s)+o,x1:Math.round(i.x1/s)+t,y1:Math.round(i.y1/s)+o}),a=[];if(e.lines&&e.lines.length>0)for(let i of e.lines){let h=i.text?i.text.toLowerCase().trim():"";if(!h||!i.bbox||!(h===n||new RegExp(`\\b${Kl(n)}\\b`,"i").test(h)))continue;let c=i.words||(e.words?e.words.filter(p=>p.bbox&&p.bbox.x0>=i.bbox.x0-5&&p.bbox.x1<=i.bbox.x1+5&&p.bbox.y0>=i.bbox.y0-5&&p.bbox.y1<=i.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(r(m)),u=!0}}u||a.push(r(i.bbox))}if(a.length===0&&e.words&&e.words.length>0)for(let i of e.words){let h=i.text?i.text.toLowerCase().trim().replace(/[^a-z0-9]/g,""):"",d=n.replace(/[^a-z0-9]/g,"");h===d&&i.bbox&&a.push(r(i.bbox))}if(a.length===0&&e.words&&e.words.length>0){let i=Vl(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)<=i&&Yl(d,n,i)<=i&&h.bbox&&a.push(r(h.bbox))}}return a}function Ur(e,n){let t=null,o=1/0;for(let s of e){let r=Math.round((s.x0+s.x1)/2),a=Math.round((s.y0+s.y1)/2),i=n.x>=s.x0&&n.x<=s.x1&&n.y>=s.y0&&n.y<=s.y1,h=Math.hypot(r-n.x,a-n.y),d=i?0:h;d<o&&(o=d,t={x:r,y:a,dist:h,containsPoint:i,bbox:s})}return t}function Ql(e,n,t,o){let a=Math.ceil(e/4),i=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*i,u=Math.min(a,e-l),p=Math.min(i,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 Oo=null;async function Zl(){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,pa=null;async function ec(){let{getActiveDisplay:e}=await import("./screen_grid-JSAE3BZG.js"),n=await e();if(lo&&pa===n)return lo;pa=n,lo={format:"png"};try{let t=await ma.listDisplays();t&&t.length>0&&(lo={format:"png",screen:(t[n]||t[0]).id})}catch{}return lo}var Wr=async(e,n={})=>{let t=!!(process.env.SHOW_DEBUG_GRID||process.env.DEBUG_OCR||process.env.VERBOSE),o=performance.now(),s=o,r=u=>{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) -> ${u}`),s=p};r("Starting click()");let a=O(e),i=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(!i&&!c)return'ERROR: Missing required "gridId" parameter for Click tool.';let l=i;if(c)try{r("Parsing grid code");let u=i?bi(i):null;r("Getting display options");let p=await ec();r("Taking desktop screenshot");let g=await ma(p);r("Getting image metadata");let y=await co(g).metadata(),m=y.width||1920,w=y.height||1080,b=u?{x:Math.round(u.x*(m/1280)),y:Math.round(u.y*(w/720))}:{x:m/2,y:w/2},x=c.toLowerCase().trim();r("Acquiring OCR worker");let E=await Zl(),R=null,S="",T=u?220:500;if(u){r("Pass 1: Cropping target crop (3x zoom window, 2x upscale)");let $=Math.min(Math.round(m/3),m),_=Math.min(Math.round(w/3),w),k=Math.max(0,Math.min(m-$,b.x-Math.floor($/2))),C=Math.max(0,Math.min(w-_,b.y-Math.floor(_/2))),I=await co(g).extract({left:k,top:C,width:$,height:_}).toBuffer(),D=2,B=await Nr(I,D),N=x.replace(/[^a-z0-9]/g,"_");await Fr("cropped",`crop_${Date.now()}_${N}.png`,B),r("Pass 1: Running Tesseract OCR recognize on crop (PSM 11 - Sparse Text)"),await E.setParameters({tessedit_pageseg_mode:"11"});let{data:Y}=await E.recognize(B,{},{tsv:!0,blocks:!0});if(r("Pass 1: OCR recognition finished, extracting matches"),Y&&Y.text){t&&console.log(`[Pass 1 OCR Read]: "${Y.text.trim().replace(/\s+/g," ")}"`);let ne=Br(Y,x,k,C,D);if(ne.length>0){let Ie=Ur(ne,b);Ie&&(Ie.containsPoint||Ie.dist<=T)&&(R=Ie,S="centered target crop OCR")}}}if(!R){r("Pass 2: Entering Full-Screen OCR (broad scan, PSM 3 - Auto)");let $=await Nr(g,2),_=x.replace(/[^a-z0-9]/g,"_");await Fr("fullscreen",`full_${Date.now()}_${_}.png`,$),r("Pass 2: Running Tesseract on full screen"),await E.setParameters({tessedit_pageseg_mode:"3"});let{data:k}=await E.recognize($,{},{tsv:!0,blocks:!0});if(r("Pass 2: Full-screen OCR finished"),k&&k.text){let C=Br(k,x,0,0,2);if(C.length>0){let I=Ur(C,b);I&&(R=I,S="full-screen OCR")}}}if(!R){r("Pass 3: Entering Tiled OCR fallback (high-res 3x)");let $=Ql(m,w,b.x,b.y),_=x.replace(/[^a-z0-9]/g,"_");await E.setParameters({tessedit_pageseg_mode:"11"});for(let k=0;k<$.length;k++){let C=$[k];r(`Pass 3: Preprocessing tile ${k+1}/${$.length}`);let I=await co(g).extract({left:C.x0,top:C.y0,width:C.w,height:C.h}).toBuffer(),D=await Nr(I,3);await Fr("tiles",`tile_${k+1}_${Date.now()}_${_}.png`,D),r(`Pass 3: Running Tesseract on tile ${k+1}`);let{data:B}=await E.recognize(D,{},{tsv:!0,blocks:!0});if(!B||!B.text)continue;let N=Br(B,x,C.x0,C.y0,3);if(N.length>0){let Y=Ur(N,b);if(Y){R=Y,S=`tile ${k+1} OCR (${C.containsTarget?"target tile":`offset ${C.x0},${C.y0}`})`;break}}}}if(R){let $={x:Math.round(R.x*(1280/m)),y:Math.round(R.y*(720/w))};r(`Executing mouse click on matched target (${S})`);let _=await In("click",$,{button:d,clickType:h});return r("Click completed successfully"),`${_} (${S} for "${c}" at ${Math.round(R.dist)}px distance)`}else t&&console.log(`[OCR] No match found for "${c}". Falling back to gridId.`)}catch(u){t&&console.error("[OCR Error]",u)}r(`Executing mouse click on fallback gridId: ${l}`);let f=await In("click",l,{button:d,clickType:h});return r("Fallback click completed"),f};var jr=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 In("drag",o,{from:o,to:s})};var Hr=async(e,n={})=>{let t=O(e),o=(t.direction||"down").toLowerCase(),s=t.amount?parseInt(t.amount,10):6,r=t.gridId||t.grid||t.coordinate||t.target||t.id||null;return await In("scroll",r,{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 On("type",String(o),{autoPressEnter:s})};var Do=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 On("clear_input");if(s==="back"||s==="browser_back"||s==="browserBack")return await On("browser_back");if(s.includes(";")||s.includes("+")){let r=s.split(/[;+]/).map(a=>a.trim()).filter(Boolean);return await On("key_combination",r)}return await On("key_press",s)};var Po=async(e,n={})=>"SUCCESS: Screen recapture requested. The latest gridded screenshot is provided for your next decision.";var tc={web_search:cr,web_scrape:dr,memory:fr,chat:ur,view_file:Qs,write_file:hr,update_file:wr,exec_command:nr,read_folder:br,write_pdf:Sr,write_docx:Rr,search_keyword:eo,generate_image:Cr,saveSummary:to,addMemScore:Ls,file_map:vr,todo:no,Todo:no,goal:no,Goal:no,invokeSync:Ir,invoke:aa,getProgress:Or,cancel:la,awaitSubagent:Ds,answerSubagent:Ps,steerSubagent:oo,computer_action:ao,computer_use:ao,ComputerAction:ao,ComputerUse:ao,click:Wr,Click:Wr,drag:jr,Drag:jr,scroll:Hr,Scroll:Hr,keyboard_typing:Lo,KeyboardTyping:Lo,keyboardtyping:Lo,key_press:Do,KeyPress:Do,keypress:Do,recapture_screen:Po,RecaptureScreen:Po,recapturescreen:Po,invoke_sync:Ir,get_progress:Or,await_subagent:Ds,answer_subagent:Ps,steer_subagent:oo,steer:oo,Steer:oo,ask:kr,Ask:kr,WebSearch:cr,WebScrape:dr,ReadFile:Qs,ReadFolder:br,WriteFile:hr,PatchFile:wr,WritePDF:Sr,WriteDoc:Rr,Run:nr,SearchKeyword:eo,CodeSearch:eo,code_search:eo,Memory:fr,Chat:ur,GenerateImage:Cr,saveSumary:to,SaveSummary:to,SaveSumary:to,add_mem_score:Ls,AddMemScore:Ls,addMemoryScore:Ls,AddMemoryScore:Ls,FileMap:vr,answer:Ps,Answer:Ps,AnswerSubagent:Ps,await:Ds,Await:Ds,AwaitSubagent:Ds,EmergencyRollback:Dr,emergency_rollback:Dr},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=tc[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 De from"fs";import nc from"gradient-string";var Gr=["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 ga=[{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 ya=(e="Dark")=>{let n;e==="Mystery"||e==="Chaos"?(Fo||(Fo=ga[Math.floor(Math.random()*ga.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 sc=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",Op=(e=2)=>{let n=sc();return n==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)},Lp=(e="...",n="Loading...",t="Dark")=>{let o=Gr[Math.floor(Math.random()*Gr.length)],s=ya(t),r=s.logoTextAnsi,a=s.logoBodyAnsi,i=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=nc(c).multiline(d.join(`
486
486
  `)).split(`
487
- `),f=u=>`${r}${u}${h}`;return`${l[0]}
488
- ${l[1]} ${i}Selected Provider: ${n}${h}
487
+ `),f=u=>`${i}${u}${h}`;return`${l[0]}
488
+ ${l[1]} ${r}Selected Provider: ${n}${h}
489
489
  ${l[2]}
490
- ${l[3]} ${i}FluxFlow ${f("v"+e)}${h}
490
+ ${l[3]} ${r}FluxFlow ${f("v"+e)}${h}
491
491
  ${l[4]}
492
492
  ${l[5]} ${a}See /help for additional commands.${h}
493
493
  ${l[6]} ${f(o)}
494
- ${l[7]}`};import{WebSocket as Bo}from"ws";var Yt=null,Ns=!1,sc="ws://localhost:56832",zi=[],Bs=null,Ki=null,xa="2.0.0",Pp=e=>{xa=e,ba()},Yi=e=>{Ki=e},ba=()=>{if(Yt||Ns)return;Ns=!0;let e=new Bo(sc);e.on("open",()=>{for(Yt=e,Ns=!1,Yt.send(JSON.stringify({command:"version",version:xa,pid:process.pid,ppid:process.ppid}));zi.length>0;)Yt.send(JSON.stringify(zi.shift()))}),e.on("message",n=>{try{let t=JSON.parse(n.toString());t.command==="contextResponse"&&Bs?(Bs(t.data),Bs=null):t.command==="securityResponse"&&Ki&&Ki(t.result)}catch{}}),e.on("error",()=>{Ns=!1,Yt=null}),e.on("close",()=>{Ns=!1,Yt=null})},Uo=e=>{Yt&&Yt.readyState===Bo.OPEN?Yt.send(JSON.stringify(e)):(zi.push(e),Ns||ba())},Wo=()=>Yt!==null&&Yt.readyState===Bo.OPEN,Fp=e=>{Uo({command:"status",status:e})},gs=()=>new Promise(e=>{if(!Yt||Yt.readyState!==Bo.OPEN){e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]});return}Bs=e,Yt.send(JSON.stringify({command:"requestContext"})),setTimeout(()=>{Bs===e&&(e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]}),Bs=null)},1e3)}),ka=e=>{Uo({command:"open",filePath:e})},Vi=(e,n,t)=>{Uo({command:"showDiff",filePath:e,originalContent:n,modifiedContent:t})},Sa=(e,n)=>{Uo({command:"closeDiff",filePath:e,result:n})};import Ta from"path";import oc from"fs";var ic=e=>{try{return oc.readdirSync(e,{withFileTypes:!0})}catch{return[]}},Xi=(e,n,t=1,o=ic,s=[],i=null)=>{let a=i||o(e),r=" ".repeat(t-1);if(a.length>100)return`${r}${Ta.basename(e)}/ (>100 files)
495
- `;let h="",d=s,c=a.filter(p=>!d.includes(p.name)&&!p.name.startsWith(".")),l=a.filter(p=>d.includes(p.name)||p.name.startsWith(".")).map(p=>p.name).sort();l.length>0&&(h+=`${r}[ignored: ${l.map(p=>p+"/").join(", ")}]
496
- `);let f=c.filter(p=>p.isDirectory()).sort((p,g)=>p.name.localeCompare(g.name)),u=c.filter(p=>!p.isDirectory()).map(p=>p.name).sort();for(let p of f){let g=Ta.join(e,p.name);if(t>n)h+=`${r}${p.name}/ (max depth)
497
- `;else{let y=o(g);y.length>80?h+=`${r}${p.name}/ (>80 files)
498
- `:(h+=`${r}${p.name}/
499
- `,h+=Xi(g,n,t+1,o,s,y))}}return u.length>0&&(h+=`${r}${u.join("; ")}
500
- `),h};import Ji from"path";import rc from"fs";var ac=e=>{try{return rc.readdirSync(e,{withFileTypes:!0})}catch{return[]}},Qi=(e,n,t="",o=1,s=ac,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(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=Ji.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";er.config({quiet:!0});er.config({path:"./fluxflow.env",override:!0,quiet:!0});er.config({path:"./.fluxflow.env",override:!0,quiet:!0});var cc=/```[\s\S]*?```/g,dc=/```[\s\S]*$/g,fc=/`[^`]+`/g,uc=/^\|.*\|$/gm,hc=/^[^\w]+|[^\w]+$/g,pc=/[^a-z0-9]/gi,po=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,mc=/\[\s*(?:tool:functions\.|agent:generalist\.)([a-z0-9_]+)\s*\(/gi,gc=/(?:path|targetFile|TargetFile|directory|keyword|id|taskId|title|task)\s*=\s*\\?["']?([^\\"' \),]+)/,ys=/["']/g,Ra=/\\/g,yc=/<\|channel>thought/gi,wc=/<channel\|>/gi,Pn=e=>typeof e!="string"?e:e.replace(yc,"<think>").replace(wc,"</think>"),xc=/(?:<(think|thought|thoughts)>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\])/gi,bc=/(?:<(think|thought|thoughts)>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*$/gi,Ea=/(?:<think>|<\|channel>thought|\[think\])[\s\S]*?(?:<\/think>|<channel\|>|\[\/think\]|$)/gi,_a=/(?:<(think|thought|thoughts)>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\]|$)/gi,La=/`[^`]*`/g,Da=/`[^`]*$/,$a=/<\|\s*tool_call_begin\s*\|>\s*(?:(?:tool|functions)\b[\s._]*)*([a-zA-Z0-9_]+)(?::\d+)?\s*<\|\s*tool_call_argument_begin\s*\|>([\s\S]*?)<\|\s*tool_call_end\s*\|>/gi,kc=/"([^"]+)"\s*:\s*(?:"([^"]*)"|(\d+)|true|false|null)/g,Ca=/<\|\s*tool_calls_section_begin\s*\|>/gi,Ma=/<\|\s*tool_calls_section_end\s*\|>/gi,Sc=/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi,Aa=/<(\w+)(?:[^>]*)>\r?\n?/gi,va=/\r?\n?<\/\w+(?:[^>]*)>/gi,tr=null,jo={},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`),Tc=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 Rc=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=!1,d=()=>{a.length>0&&(t.push({role:"agent",text:"combined"}),a=[]),r.length>0&&(t.push({role:"system",text:"combined"}),r=[]),h=!1};i.forEach(c=>{let l=c.role==="system"&&(c.text?.startsWith("[TOOL RESULT]")||c.text?.startsWith("SUCCESS:")||c.text?.startsWith("ERROR:")||c.fullText?.startsWith("[TOOL RESULT]")||c.fullText?.startsWith("SUCCESS:")||c.fullText?.startsWith("ERROR:")),f=c.fullText||c.text||"",u=f.trim();if(!(!u&&!c.binaryPart)){if(l)r.push(u);else if(c.role==="agent"){!h&&r.length>0&&d();let p=f.endsWith(`
507
- `),g=u.toLowerCase().includes("tool:functions.")||u.toLowerCase().includes("agent:generalist.");a.push(u),g&&p?h=!0:h=!1}}}),d()}}return t.length},Ec=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),bs=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},nr=async function*(e,n,t,o,s,i,a,r,h=1.05){let d=[];o&&d.push({role:"system",content:o});for(let x of t){let b=x.role==="user"?"user":"assistant",E=[];if(Array.isArray(x.parts)){for(let R of x.parts)if(R.text)E.push({type:"text",text:R.text});else if(R.inlineData&&a){let S=R.inlineData.mimeType,T=R.inlineData.data;S.startsWith("image/")&&E.push({type:"image_url",image_url:{url:`data:${S};base64,${T}`}})}}else{let R=x.text||"";R&&E.push({type:"text",text:R})}d.push({role:b,content:E.length===1&&E[0].type==="text"?E[0].text:E})}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 bs("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:b}=await f.read();if(x){w&&(g.length>0||y)&&(yield{candidates:g.length>0?[{content:{parts:g}}]:[],usageMetadata:y});break}p+=u.decode(b,{stream:!0});let E=p.split(`
508
- `);p=E.pop();for(let R of E){let S=R.trim();if(!S||!S.startsWith("data: "))continue;let T=!1;if(S==="data: [DONE]")T=!0;else try{let $=JSON.parse(S.substring(6)),_=$.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),_){let C=_.reasoning_content||null;C&&(g.push({text:C,thought:!0}),w=!0),_.content&&(g.push({text:_.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)}},sr=async function*(e,n,t,o,s,i,a,r,h=1.05){let d=[];o&&d.push({role:"system",content:o});for(let E of t){let R=E.role==="user"?"user":"assistant",S=[];if(Array.isArray(E.parts)){for(let T of E.parts)if(T.text)S.push({type:"text",text:T.text});else if(T.inlineData&&a){let $=T.inlineData.mimeType,_=T.inlineData.data;$.startsWith("image/")&&S.push({type:"image_url",image_url:`data:${$};base64,${_}`})}}else{let T=E.text||"";T&&S.push({type:"text",text:T})}S.length>0&&d.push({role:R,content:S.length===1&&S[0].type==="text"?S[0].text:S})}let c={Fast:"none",Low:"none",Medium:"high",Standard:"high",High:"high",xHigh:"high"},l={model:n,messages:d,stream:!0,temperature:h,prompt_cache_key:"flux-flow-session"};s&&s!=="Fast"&&zs(n)&&(l.reasoning_effort=c[s]||"high");let f=await bs("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 E=await f.text().catch(()=>""),R=f.statusText;try{let S=JSON.parse(E);R=S.error?.message||S.message||JSON.stringify(S.detail||S)}catch{E&&(R=E)}throw new Error(`Mistral Error (${f.status}): ${JSON.stringify(R)}`)}let u=f.body.getReader(),p=new TextDecoder,g="",y=[],m=null,w=Date.now(),x=!1,b=E=>E?typeof E=="string"?Pn(E):Array.isArray(E)?E.map(b).filter(Boolean).join(""):typeof E=="object"&&E!==null?typeof E.text=="string"?Pn(E.text):typeof E.content=="string"?Pn(E.content):typeof E.thinking=="string"?Pn(E.thinking):typeof E.reasoning_content=="string"?Pn(E.reasoning_content):typeof E.reasoning=="string"?Pn(E.reasoning):typeof E.value=="string"?Pn(E.value):E.text?b(E.text):E.content?b(E.content):E.thinking?b(E.thinking):E.reasoning_content?b(E.reasoning_content):E.reasoning?b(E.reasoning):E.value?b(E.value):"":Pn(String(E)):"";for(;;){let{done:E,value:R}=await u.read();if(E){x&&(y.length>0||m)&&(yield{candidates:y.length>0?[{content:{parts:y}}]:[],usageMetadata:m});break}g+=p.decode(R,{stream:!0});let S=g.split(`
509
- `);g=S.pop();for(let T of S){let $=T.trim();if(!$||!$.startsWith("data: "))continue;let _=!1;if($==="data: [DONE]")_=!0;else try{let k=JSON.parse($.substring(6)),C=k.choices?.[0]?.delta,I=k.usage;if(k.choices?.[0]?.finish_reason&&(_=!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),C){let D=C.thinking||C.reasoning_content||C.reasoning,B=b(D);B&&(y.push({text:B,thought:!0}),x=!0);let N=C.content||(!C.thinking&&!C.reasoning_content&&!C.reasoning?C.text:null);if(N)if(Array.isArray(N))for(let Y of N)if(typeof Y=="object"&&Y!==null){let ne=Y.type==="thinking"||Y.type==="reasoning"||!!Y.thought,Ie=b(Y);Ie&&(y.push({text:Ie,...ne?{thought:!0}:{}}),x=!0)}else{let ne=b(Y);ne&&(y.push({text:ne}),x=!0)}else if(typeof N=="object"&&N!==null){let Y=N.type==="thinking"||N.type==="reasoning"||!!N.thought,ne=b(N);ne&&(y.push({text:ne,...Y?{thought:!0}:{}}),x=!0)}else{let Y=b(N);Y&&(y.push({text:Y}),x=!0)}}}catch{}if((_||Date.now()-w>=150)&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),x=!1),_)break}Date.now()-w>=150&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),x=!1)}},or=async function*(e,n,t,o,s,i,a=!1,r,h=1.05){let d=[];o&&d.push({role:"system",content:o}),t.forEach(ae=>{let Ee=ae.role==="model"?"assistant":"user",A=[];Array.isArray(ae.parts)&&ae.parts.forEach(F=>{if(F.text)A.push({type:"text",text:F.text});else if(F.inlineData&&a){let V=F.inlineData.mimeType,X=F.inlineData.data;V.startsWith("image/")&&zt(n)&&A.push({type:"image_url",image_url:{url:`data:${V};base64,${X}`}})}}),d.push({role:Ee,content:A.length===1&&A[0].type==="text"?A[0].text:A})});let l={Fast:"Fast",Low:"Fast",Medium:"Standard",Standard:"Standard",High:"High",xHigh:"High"}[s]||"High",f=l!=="Fast",u=n.includes("kimi"),p=n.includes("gemma"),g=n.includes("deepseek"),y=n.includes("glm"),m=n.includes("mistral"),w=n.includes("minimax"),x=n.includes("gpt"),b=n.includes("qwen"),E=n.includes("nemotron"),R=n.includes("llama-3"),S=n.includes("seed"),T=n.includes("poolside"),$=n.includes("thinkingmachines")||n.includes("muse"),_=R,k=null,C={Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},I={Fast:"64",Low:"64",Medium:"4096",Standard:"4096",High:"16384",xHigh:"16384"},D={Fast:"none",Low:"minimal",Medium:"medium",Standard:"medium",High:"max",xHigh:"max"},B=w||g||T||$?16384:32768;B=process.env.NVIDIA_BASE_URL?1024:B,B=k?1024:B;let N={model:n,messages:d,max_tokens:B,stream:!0,stream_options:{include_usage:!0},temperature:h,...x&&{thinking:C[s]||"high"}};if(!(process.env.NVIDIA_BASE_URL||_||k))if(u)N.chat_template_kwargs={thinking:f};else if(p)N.chat_template_kwargs={enable_thinking:f};else if(g)if(f){let ae=l==="High"?"max":"high";N.chat_template_kwargs={thinking:!0,reasoning_effort:ae}}else N.chat_template_kwargs={thinking:!1};else y?N.chat_template_kwargs={enable_thinking:f,clear_thinking:!f}:m?N.reasoning_effort=f?"high":"none":w&&n.includes("minimax-m3")?N.chat_template_kwargs={thinking_mode:f?"enabled":"disabled"}:b?N.chat_template_kwargs={enable_thinking:f}:E?l==="High"?(N.reasoning_budget=12e3,N.chat_template_kwargs={enable_thinking:!0}):l==="Standard"?(N.reasoning_budget=12e3,N.chat_template_kwargs={enable_thinking:!0,medium_effort:!0}):N.chat_template_kwargs={enable_thinking:!1}:S?f&&(N.extra_body={thinking_budget:parseInt(I[l]??"4096")}):T?N.chat_template_kwargs={enable_thinking:f}:$&&(N.reasoning_effort=D[l]||"medium");let Y=0,ne=6,Ie=!1,U=process.env.NVIDIA_BASE_URL||"https://integrate.api.nvidia.com/v1/chat/completions",j=process.env.NVIDIA_API_KEY&&process.env.NVIDIA_BASE_URL?process.env.NVIDIA_API_KEY:e;for(U.endsWith("/chat/completions")||(U=U.replace(/\/+$/,"")+"/chat/completions");Y<ne;){Y++;try{let ae=await bs(U,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${j}`},body:JSON.stringify(N),signal:r});if(!ae.ok){let je=await ae.text().catch(()=>""),ot=ae.statusText;try{let pt=JSON.parse(je);ot=pt.error?.message||pt.message||JSON.stringify(pt.detail||pt)}catch{je&&(ot=je)}let ze=new Error(`NVIDIA API Error (${ae.status}): ${ot}`);throw ze.status=ae.status,ze}let Ee=ae.body.getReader(),A=new TextDecoder,F="",V=[],X=null,Ue=Date.now(),Ne=!1;for(;;){let{done:je,value:ot}=await Ee.read();if(je){Ne&&(V.length>0||X)&&(yield{candidates:V.length>0?[{content:{parts:V}}]:[],usageMetadata:X},Ie=!0);break}F+=A.decode(ot,{stream:!0});let ze=F.split(`
510
- `);F=ze.pop();let pt=!1;for(let Bt of ze){let mt=Bt.trim();if(mt){if(mt==="data: [DONE]"){pt=!0;break}if(mt.startsWith("data: ")){let gt;try{gt=JSON.parse(mt.substring(6))}catch{continue}if(gt.error)throw new Error(`NVIDIA Stream Error: ${gt.error.message||JSON.stringify(gt.error)}`);gt.choices?.[0]?.finish_reason&&(pt=!0);try{let Tt=gt.usage;Tt&&(X={totalTokenCount:Tt.total_tokens||Tt.prompt_tokens+Tt.completion_tokens,promptTokenCount:Tt.prompt_tokens||0,candidatesTokenCount:Tt.completion_tokens||0,cachedContentTokenCount:Tt.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:(Tt.completion_tokens_details?.reasoning_tokens||0)+(Tt.completion_tokens_details?.thoughts_tokens||0)},Ne=!0);let ct=gt.choices?.[0]?.delta?.reasoning||gt.choices?.[0]?.delta?.reasoning_content||"",_e=gt.choices?.[0]?.delta?.content||"";ct&&(V.push({text:ct,thought:!0}),Ne=!0),_e&&(V.push({text:_e}),Ne=!0)}catch{}}}}if((pt||Date.now()-Ue>=350)&&Ne&&(yield{candidates:V.length>0?[{content:{parts:[...V]}}]:[],usageMetadata:X},Ie=!0,V=[],Ue=Date.now(),Ne=!1),pt)break}break}catch(ae){if(Ie||Y>=ne)throw ae;await new Promise(Ee=>setTimeout(Ee,3500))}}},_c=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)}},ir=async function*(e,n,t,o,s,i,a,r,h=1.05){let d=[];o&&d.push({role:"system",content:[{type:"text",text:o,cache_control:{type:"ephemeral"}}]});for(let T of t){let $=T.role==="user"?"user":"assistant",_=[];if(Array.isArray(T.parts)){for(let k of T.parts)if(k.text)_.push({type:"text",text:k.text});else if(k.inlineData&&a){let C=k.inlineData.mimeType,I=k.inlineData.data;C.startsWith("image/")?_.push({type:"image_url",image_url:{url:`data:${C};base64,${I}`}}):_.push({type:"file",file:{filename:k.filename||"file",file_data:`data:${C};base64,${I}`}})}}else{let k=T.text||"";k&&_.push({type:"text",text:k})}d.push({role:$,content:_.length===1&&_[0].type==="text"?_[0].text:_})}let c={Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},l=n,f=null;if(l.includes("::")){let T=l.split("::");l=T[0].trim();let $=T.slice(1).join("::").toLowerCase().trim();["flex","priority","default"].includes($)&&$!=="default"&&(f=$)}let u=l;if(l.includes(":")){let[T,...$]=l.split(":"),_=$.join(":").toLowerCase().trim();f?u=`${T}:${_}/${f}`:u=`${T}:${_}`}let p={model:u,messages:d,stream:!0,temperature:h,cache_control:{type:"ephemeral"},session_id:"flux-flow-session"},g=c[s];g&&s!=="Fast"&&(p.reasoning_effort=g),console.log(p);let y=await bs("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(p),signal:r});if(!y.ok){let T=await y.json().catch(()=>({}));throw new Error(`OpenRouter Error (${y.status}): ${T.error?.message||y.statusText}`)}let m=y.body.getReader(),w=new TextDecoder,x="",b=[],E=null,R=Date.now(),S=!1;for(;;){let{done:T,value:$}=await m.read();if(T){S&&(b.length>0||E)&&(yield{candidates:b.length>0?[{content:{parts:b}}]:[],usageMetadata:E});break}x+=w.decode($,{stream:!0});let _=x.split(`
511
- `);x=_.pop();for(let k of _){let C=k.trim();if(!C||!C.startsWith("data: "))continue;let I=!1;if(C==="data: [DONE]")I=!0;else try{let D=JSON.parse(C.substring(6)),B=D.choices?.[0]?.delta,N=D.usage;if(D.choices?.[0]?.finish_reason&&(I=!0),N&&(E={totalTokenCount:N.total_tokens||(N.prompt_tokens||0)+(N.completion_tokens||0),promptTokenCount:N.prompt_tokens||0,candidatesTokenCount:N.completion_tokens||0,cachedContentTokenCount:N.prompt_tokens_details?.cached_tokens||N.prompt_tokens_details?.cache_read_input_tokens||N.cache_read_input_tokens||0,thoughtsTokenCount:N.completion_tokens_details?.reasoning_tokens||0},S=!0),B){let Y=B.reasoning||(B.reasoning_details?B.reasoning_details.map(ne=>ne.text).join(""):null);Y&&(b.push({text:Y,thought:!0}),S=!0),B.content&&(b.push({text:B.content}),S=!0)}}catch{}if((I||Date.now()-R>=150)&&S&&(yield{candidates:b.length>0?[{content:{parts:[...b]}}]:[],usageMetadata:E},b=[],R=Date.now(),S=!1),I)break}}},Pa=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 S of t){let T=S.role==="user"?"user":"assistant",$="",_=[];if(Array.isArray(S.parts)){$=S.parts.map(k=>k.text||"").filter(Boolean).join(`
512
- `);for(let k of S.parts){let C=k.inlineData||k.inline_data;C&&C.data&&_.push(C.data)}}else $=S.text||"";if($||_.length>0){let k={role:T,content:$};_.length>0&&(k.images=_),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 lc(u),g=[],y=null,m=Date.now(),w=!1,x={Fast:!1,Low:"medium",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},b=x[s]!==void 0?x[s]:!0,E={model:n,messages:c,stream:!0,think:b,keep_alive:"10m",options:{temperature:h}},R=await p.chat(E);for await(let S of R){if(r?.aborted)throw new DOMException("The user aborted a request.","AbortError");if(S.message?.thinking&&(g.push({text:S.message.thinking,thought:!0}),w=!0),S.message?.content&&(g.push({text:S.message.content}),w=!0),S.done){let T=S.prompt_cached_count||0;if(!T&&S.prompt_eval_count){let $=S.prompt_eval_duration||0;$>0&&$<5e7&&(T=S.prompt_eval_count)}y={totalTokenCount:(S.prompt_eval_count||0)+(S.eval_count||0),promptTokenCount:S.prompt_eval_count||0,candidatesTokenCount:S.eval_count||0,cachedContentTokenCount:T,thoughtsTokenCount:0},w=!0}(S.done||Date.now()-m>=150&&w)&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],m=Date.now(),w=!1)}w&&(g.length>0||y)&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y})},rr=async function*(e,n,t,o,s,i,a,r,h=1.05){let d=[];o&&d.push({role:"system",content:o});for(let b of t){let E=b.role==="user"?"user":"assistant",R=[];if(Array.isArray(b.parts)){for(let S of b.parts)if(S.text)R.push({type:"text",text:S.text});else if(S.inlineData&&a){let T=S.inlineData.mimeType,$=S.inlineData.data;T.startsWith("image/")&&R.push({type:"image_url",image_url:{url:`data:${T};base64,${$}`}})}}else{let S=b.text||"";S&&R.push({type:"text",text:S})}d.push({role:E,content:R.length===1&&R[0].type==="text"?R[0].text:R})}let c={Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},l={model:n,messages:d,stream:!0,stream_options:{include_usage:!0},temperature:h,max_completion_tokens:32768};c[s]&&(l.reasoning_effort=c[s]);let f=await bs("https://crof.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(l),signal:r});if(!f.ok){let b=await f.json().catch(()=>({}));throw new Error(`CrofAI Error (${f.status}): ${b.error?.message||f.statusText}`)}let u=f.body.getReader(),p=new TextDecoder,g="",y=[],m=null,w=Date.now(),x=!1;for(;;){let{done:b,value:E}=await u.read();if(b){x&&(y.length>0||m)&&(yield{candidates:y.length>0?[{content:{parts:y}}]:[],usageMetadata:m});break}g+=p.decode(E,{stream:!0});let R=g.split(`
513
- `);g=R.pop();for(let S of R){let T=S.trim();if(!T||!T.startsWith("data: "))continue;let $=!1;if(T==="data: [DONE]")$=!0;else try{let _=JSON.parse(T.substring(6)),k=_.choices?.[0]?.delta,C=_.usage;if(_.choices?.[0]?.finish_reason&&($=!0),C&&(m={totalTokenCount:C.total_tokens||(C.prompt_tokens||0)+(C.completion_tokens||0),promptTokenCount:C.prompt_tokens||0,candidatesTokenCount:C.completion_tokens||0,cachedContentTokenCount:C.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:C.completion_tokens_details?.reasoning_tokens||C.reasoning_tokens||0},x=!0),k){let I=k.reasoning_content||null;I&&(y.push({text:I,thought:!0}),x=!0),k.content&&(y.push({text:k.content}),x=!0)}}catch{}if(($||Date.now()-w>=150)&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),x=!1),$)break}Date.now()-w>=150&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),x=!1)}},ar=async function*(e,n,t,o,s,i,a,r,h=1.05){let d=[];o&&d.push({role:"system",content:o});for(let b of t){let E=b.role==="user"?"user":"assistant",R="";if(Array.isArray(b.parts))for(let S of b.parts)S.text&&(R+=(R?`
514
- `:"")+S.text);else R=b.text||"";d.push({role:E,content:R})}let c={Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},l={model:n,messages:d,stream:!0,stream_options:{include_usage:!0},temperature:h};c[s]&&(l.reasoning_effort=c[s]);let f=await bs("https://model.inferx.net/endpoints/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(l),signal:r});if(!f.ok){let b=await f.json().catch(()=>({}));throw new Error(`InferX Error (${f.status}): ${b.error?.message||f.statusText}`)}let u=f.body.getReader(),p=new TextDecoder,g="",y=[],m=null,w=Date.now(),x=!1;for(;;){let{done:b,value:E}=await u.read();if(b){x&&(y.length>0||m)&&(yield{candidates:y.length>0?[{content:{parts:y}}]:[],usageMetadata:m});break}g+=p.decode(E,{stream:!0});let R=g.split(`
515
- `);g=R.pop();for(let S of R){let T=S.trim();if(!T||!T.startsWith("data: "))continue;let $=!1;if(T==="data: [DONE]")$=!0;else try{let _=JSON.parse(T.substring(6)),k=_.choices?.[0]?.delta,C=_.usage;if(C&&(m={totalTokenCount:C.total_tokens||(C.prompt_tokens||0)+(C.completion_tokens||0),promptTokenCount:C.prompt_tokens||0,candidatesTokenCount:C.completion_tokens||0,cachedContentTokenCount:C.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:C.completion_tokens_details?.reasoning_tokens||C.reasoning_tokens||0},x=!0),k){let I=k.reasoning||k.reasoning_content||null;I&&(y.push({text:I,thought:!0}),x=!0),k.content&&(y.push({text:k.content}),x=!0)}}catch{}if(($||Date.now()-w>=150||m)&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),x=!1),$)break}Date.now()-w>=150&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),x=!1)}},lr=async function*(e,n,t,o,s,i,a,r,h=1.05){let d=[];o&&d.push({role:"system",content:o});for(let b of t){let E=b.role==="user"?"user":"assistant",R=[];if(Array.isArray(b.parts)){for(let S of b.parts)if(S.text)R.push({type:"text",text:S.text});else if(S.inlineData&&a){let T=S.inlineData.mimeType,$=S.inlineData.data;T.startsWith("image/")&&R.push({type:"image_url",image_url:{url:`data:${T};base64,${$}`}})}}else{let S=b.text||"";S&&R.push({type:"text",text:S})}d.push({role:E,content:R.length===1&&R[0].type==="text"?R[0].text:R})}let c={Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},l={model:n,messages:d,stream:!0,stream_options:{include_usage:!0},temperature:h};c[s]&&(l.reasoning_effort=c[s]);let f=await bs("https://token.sensenova.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(l),signal:r});if(!f.ok){let b=await f.json().catch(()=>({}));throw new Error(`SenseNova Error (${f.status}): ${b.error?.message||f.statusText}`)}let u=f.body.getReader(),p=new TextDecoder,g="",y=[],m=null,w=Date.now(),x=!1;for(;;){let{done:b,value:E}=await u.read();if(b){x&&(y.length>0||m)&&(yield{candidates:y.length>0?[{content:{parts:y}}]:[],usageMetadata:m});break}g+=p.decode(E,{stream:!0});let R=g.split(`
516
- `);g=R.pop();for(let S of R){let T=S.trim();if(!T||!T.startsWith("data: "))continue;let $=!1;if(T==="data: [DONE]")$=!0;else try{let _=JSON.parse(T.substring(6)),k=_.choices?.[0]?.delta,C=_.usage;if(C&&(m={totalTokenCount:C.total_tokens||(C.prompt_tokens||0)+(C.completion_tokens||0),promptTokenCount:C.prompt_tokens||0,candidatesTokenCount:C.completion_tokens||0,cachedContentTokenCount:C.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:C.completion_tokens_details?.reasoning_tokens||C.reasoning_tokens||0},x=!0),k){let I=k.reasoning||k.reasoning_content||null;I&&(y.push({text:I,thought:!0}),x=!0),k.content&&(y.push({text:k.content}),x=!0)}}catch{}if(($||Date.now()-w>=150||m)&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),x=!1),$)break}Date.now()-w>=150&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),x=!1)}},Tm=()=>{Ot=!0},Rm=()=>Ot,Zi={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}},cr=e=>e?new Oa({apiKey:e}):tr,Em=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"||m==="CrofAI"||m==="InferX"||m==="SenseNova"?!1:g?.memory!==!1,E=J(Pt,[]).map(A=>`- [${A.id}]: ${A.memory}`).join(`
517
- `),R=o.slice(0,-1).filter(A=>A.text&&!A.text.includes("[TOOL RESULT]")&&!A.text.includes("OBSERVATION:")&&!A.text.startsWith("[TERMINAL_RECORD]")&&!A.isTerminalRecord&&!A.isMeta&&!A.isLogo&&!String(A.id).startsWith("welcome")&&!String(A.id).startsWith("logo")).slice(-14).map(A=>{let F=Ec(A.text).replace(/\[tool:functions\..*?\]/g,"").replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[METADATA \(PRIORITY: DYNAMIC\)\] Time: ([^|\n]+)/g,(Ne,je)=>`[METADATA (PRIORITY: DYNAMIC)] Time: ${je.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,`
494
+ ${l[7]}`};import{WebSocket as No}from"ws";var Yt=null,Fs=!1,oc="ws://localhost:56832",qr=[],Ns=null,zr=null,wa="2.0.0",Fp=e=>{wa=e,xa()},Kr=e=>{zr=e},xa=()=>{if(Yt||Fs)return;Fs=!0;let e=new No(oc);e.on("open",()=>{for(Yt=e,Fs=!1,Yt.send(JSON.stringify({command:"version",version:wa,pid:process.pid,ppid:process.ppid}));qr.length>0;)Yt.send(JSON.stringify(qr.shift()))}),e.on("message",n=>{try{let t=JSON.parse(n.toString());t.command==="contextResponse"&&Ns?(Ns(t.data),Ns=null):t.command==="securityResponse"&&zr&&zr(t.result)}catch{}}),e.on("error",()=>{Fs=!1,Yt=null}),e.on("close",()=>{Fs=!1,Yt=null})},Bo=e=>{Yt&&Yt.readyState===No.OPEN?Yt.send(JSON.stringify(e)):(qr.push(e),Fs||xa())},Uo=()=>Yt!==null&&Yt.readyState===No.OPEN,Np=e=>{Bo({command:"status",status:e})},ms=()=>new Promise(e=>{if(!Yt||Yt.readyState!==No.OPEN){e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]});return}Ns=e,Yt.send(JSON.stringify({command:"requestContext"})),setTimeout(()=>{Ns===e&&(e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]}),Ns=null)},1e3)}),ba=e=>{Bo({command:"open",filePath:e})},Yr=(e,n,t)=>{Bo({command:"showDiff",filePath:e,originalContent:n,modifiedContent:t})},ka=(e,n)=>{Bo({command:"closeDiff",filePath:e,result:n})};import Sa from"path";import rc from"fs";var ic=e=>{try{return rc.readdirSync(e,{withFileTypes:!0})}catch{return[]}},Vr=(e,n,t=1,o=ic,s=[],r=null)=>{let a=r||o(e),i=" ".repeat(t-1);if(a.length>100)return`${i}${Sa.basename(e)}/ (>100 files)
495
+ `;let h="",d=s,c=a.filter(p=>!d.includes(p.name)&&!p.name.startsWith(".")),l=a.filter(p=>d.includes(p.name)||p.name.startsWith(".")).map(p=>p.name).sort();l.length>0&&(h+=`${i}[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=Sa.join(e,p.name);if(t>n)h+=`${i}${p.name}/ (max depth)
497
+ `;else{let y=o(g);y.length>80?h+=`${i}${p.name}/ (>80 files)
498
+ `:(h+=`${i}${p.name}/
499
+ `,h+=Vr(g,n,t+1,o,s,y))}}return u.length>0&&(h+=`${i}${u.join("; ")}
500
+ `),h};import Xr from"path";import ac from"fs";var lc=e=>{try{return ac.readdirSync(e,{withFileTypes:!0})}catch{return[]}},Jr=(e,n,t="",o=1,s=lc,r=[])=>{let a=s(e),i=Xr.sep;if(a.length>100)return`${t}\u2514\u2500\u2500 ${Xr.basename(e)}${i} ...100+ files...
501
+ `;let h="",d=r,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=Xr.join(e,u.name),m=g?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",w=t+(g?" ":"\u2502 ");if(u.isCollapsed){h+=`${t}${m}${u.name}${i}...
502
+ `;return}u.isDir?o>n?h+=`${t}${m}${u.name}${i} ...depth exceeded...
503
+ `:s(y).length>80?h+=`${t}${m}${u.name}${i} ...80+ files...
504
+ `:(h+=`${t}${m}${u.name}${i}
505
+ `,h+=Jr(y,n,w,o+1,s,r)):h+=`${t}${m}${u.name}
506
+ `}),h};import"@google/genai";Zr.config({quiet:!0});Zr.config({path:"./fluxflow.env",override:!0,quiet:!0});Zr.config({path:"./.fluxflow.env",override:!0,quiet:!0});var dc=/```[\s\S]*?```/g,fc=/```[\s\S]*$/g,uc=/`[^`]+`/g,hc=/^\|.*\|$/gm,pc=/^[^\w]+|[^\w]+$/g,mc=/[^a-z0-9]/gi,ho=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,gc=/\[\s*(?:tool:functions\.|agent:generalist\.)([a-z0-9_]+)\s*\(/gi,yc=/(?:path|targetFile|TargetFile|directory|keyword|id|taskId|title|task)\s*=\s*\\?["']?([^\\"' \),]+)/,gs=/["']/g,Ta=/\\/g,wc=/<\|channel>thought/gi,xc=/<channel\|>/gi,Dn=e=>typeof e!="string"?e:e.replace(wc,"<think>").replace(xc,"</think>"),bc=/(?:<(think|thought|thoughts)>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\])/gi,kc=/(?:<(think|thought|thoughts)>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*$/gi,Ra=/(?:<think>|<\|channel>thought|\[think\])[\s\S]*?(?:<\/think>|<channel\|>|\[\/think\]|$)/gi,Ea=/(?:<(think|thought|thoughts)>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\]|$)/gi,Oa=/`[^`]*`/g,La=/`[^`]*$/,_a=/<\|\s*tool_call_begin\s*\|>\s*(?:(?:tool|functions)\b[\s._]*)*([a-zA-Z0-9_]+)(?::\d+)?\s*<\|\s*tool_call_argument_begin\s*\|>([\s\S]*?)<\|\s*tool_call_end\s*\|>/gi,Sc=/"([^"]+)"\s*:\s*(?:"([^"]*)"|(\d+)|true|false|null)/g,$a=/<\|\s*tool_calls_section_begin\s*\|>/gi,Ca=/<\|\s*tool_calls_section_end\s*\|>/gi,Tc=/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi,Ma=/<(\w+)(?:[^>]*)>\r?\n?/gi,Aa=/\r?\n?<\/\w+(?:[^>]*)>/gi,ei=null,Wo={},ys={key:null,value:null},gn=e=>e&&e.replace(/(?:(\x1b\[\d+m))?([✔✘✖🔍📖→➕↻↷•🛇])(?:(\x1b\[\d+m))?\s*\b(Clicked|Dragged|Scrolled|Typed|Pressed Key|Recaptured Screen|Created|Read|Edited|Viewed|Processed|Auto-Read|Skipped|List|Generated|Written|Searched|AI Search|Get Map|Write Canceled|Resolved Sub-Agent Query|Edit Canceled|Write Cancelled|Edit Denied|Visited|Updated|Reviewed|Delegated|Background|Checked|Indexed|Analyzed|Browsed|Elevating SubAgent|Checking SubAgent Work|Started Generalist|Called Generalist|Steered|Unsupported Modality|Awaiting|Cancelled|Aligning Moon Phase|Contemplating Existence|Staring At Void|Rollback Point Checked|Emergency Rollback Failed|Emergency Rollback|Delaying Professionally|Negotiating With Electrons|Touching Grass (virtually)|Panicking Softly|Rethinking Career Choices|Loading Cat Videos|Giving Up Entirely|Summoning Braincell #2|Pretending To Be Busy|Waiting For Motivation DLC|Rotating Internal Screaming|Downloading More RAM|Feeding The Hamsters|Gaslighting Scheduler|Performing Dramatic Pause|Buffering Social Energy|Calculating Regret|Reading Terms And Conditions|Becoming Sentient Briefly|Contacting Ancestors)\b/ig,(n,t,o,s,r)=>`${t||""}${o}${s||""} \x1B[95m${r}\x1B[0m`),Rc=async(e,n=8,t=1e3,o=8e3,s=null)=>{let r=0;for(;;){if(s?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{return await e()}catch(a){if(s?.aborted||a?.name==="AbortError"||a?.message==="Subagent task was cancelled."||(r++,r>=n))throw a;let i=Math.min(t*Math.pow(2,r-1),o);await new Promise((h,d)=>{let c=setTimeout(h,i);s&&s.addEventListener("abort",()=>{clearTimeout(c),d(new DOMException("The user aborted a request.","AbortError"))})})}}},Dt=!1;var Ec=e=>{let n=e.filter(s=>(s.role==="user"||s.role==="agent"||s.role==="system")&&s.role!=="think"&&!s.isVisualFeedback&&!s.isMeta&&!s.isTerminalRecord&&!(s.text&&s.text.includes("[TERMINAL_RECORD]"))&&!String(s.id).startsWith("welcome")).map((s,r,a)=>{let i=s.fullText||s.text||"";if(s.role==="user"&&r<a.length-1)if(i.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")){let h=i.indexOf("**CONTEXT SUMMARY OF PREVIOUS TURNS");if(h!==-1){let c=i.substring(0,h).lastIndexOf("[SYSTEM METADATA]");c!==-1?i=i.substring(c).trim():i=i.substring(h).trim()}}else{let h=i.lastIndexOf("[USER]"),d=i.lastIndexOf("[USER PROMPT]");h!==-1?i=i.substring(h+6).trim():d!==-1&&(i=i.substring(d).trim())}return{...s,text:i}}),t=[],o=0;for(;o<n.length;){let s=n[o];if(s.role==="user")t.push(s),o++;else{let r=[];for(;o<n.length&&n[o].role!=="user";)r.push(n[o]),o++;let a=[],i=[],h=!1,d=()=>{a.length>0&&(t.push({role:"agent",text:"combined"}),a=[]),i.length>0&&(t.push({role:"system",text:"combined"}),i=[]),h=!1};r.forEach(c=>{let l=c.role==="system"&&(c.text?.startsWith("[TOOL RESULT]")||c.text?.startsWith("SUCCESS:")||c.text?.startsWith("ERROR:")||c.fullText?.startsWith("[TOOL RESULT]")||c.fullText?.startsWith("SUCCESS:")||c.fullText?.startsWith("ERROR:")),f=c.fullText||c.text||"",u=f.trim();if(!(!u&&!c.binaryPart)){if(l)i.push(u);else if(c.role==="agent"){!h&&i.length>0&&d();let p=f.endsWith(`
507
+ `),g=u.toLowerCase().includes("tool:functions.")||u.toLowerCase().includes("agent:generalist.");a.push(u),g&&p?h=!0:h=!1}}}),d()}}return t.length},_c=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),xs=async(e,n,t=5,o=1e3)=>{let s=n?.signal;for(let a=0;a<t;a++){if(s?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{let i=await fetch(e,n);if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),i.ok||i.status!==429&&i.status<500)return i}catch(i){if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),i.name==="AbortError"||s?.aborted||a===t-1)throw i}s?await new Promise((i,h)=>{let d=setTimeout(()=>{s.removeEventListener("abort",c),i()},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(i=>setTimeout(i,Math.min(24e3,o*Math.pow(2,a))))}if(s?.aborted)throw new DOMException("The user aborted a request.","AbortError");let r=await fetch(e,n);return typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),r},ti=async function*(e,n,t,o,s,r,a,i,h=1.05){let d=[];o&&d.push({role:"system",content:o});for(let b of t){let x=b.role==="user"?"user":"assistant",E=[];if(Array.isArray(b.parts)){for(let R of b.parts)if(R.text)E.push({type:"text",text:R.text});else if(R.inlineData&&a){let S=R.inlineData.mimeType,T=R.inlineData.data;S.startsWith("image/")&&E.push({type:"image_url",image_url:{url:`data:${S};base64,${T}`}})}}else{let R=b.text||"";R&&E.push({type:"text",text:R})}d.push({role:x,content:E.length===1&&E[0].type==="text"?E[0].text:E})}let c={model:n,messages:d,stream:!0,stream_options:{include_usage:!0},temperature:h};if(s!=="Fast"){let b={Low:"high",Medium:"high",Standard:"high",High:"max",xHigh:"max"};c.reasoning_effort=b[s]||"high",c.extra_body={thinking:{type:"enabled"}}}else c.extra_body={thinking:{type:"disabled"}};let l=await xs("https://api.deepseek.com/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(c),signal:i});if(!l.ok){let b=await l.json().catch(()=>({}));throw new Error(`DeepSeek Error (${l.status}): ${b.error?.message||l.statusText}`)}let f=l.body.getReader(),u=new TextDecoder,p="",g=[],y=null,m=Date.now(),w=!1;for(;;){let{done:b,value:x}=await f.read();if(b){w&&(g.length>0||y)&&(yield{candidates:g.length>0?[{content:{parts:g}}]:[],usageMetadata:y});break}p+=u.decode(x,{stream:!0});let E=p.split(`
508
+ `);p=E.pop();for(let R of E){let S=R.trim();if(!S||!S.startsWith("data: "))continue;let T=!1;if(S==="data: [DONE]")T=!0;else try{let $=JSON.parse(S.substring(6)),_=$.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),_){let C=_.reasoning_content||null;C&&(g.push({text:C,thought:!0}),w=!0),_.content&&(g.push({text:_.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)}},ni=async function*(e,n,t,o,s,r,a,i,h=1.05){let d=[];o&&d.push({role:"system",content:o});for(let E of t){let R=E.role==="user"?"user":"assistant",S=[];if(Array.isArray(E.parts)){for(let T of E.parts)if(T.text)S.push({type:"text",text:T.text});else if(T.inlineData&&a){let $=T.inlineData.mimeType,_=T.inlineData.data;$.startsWith("image/")&&S.push({type:"image_url",image_url:`data:${$};base64,${_}`})}}else{let T=E.text||"";T&&S.push({type:"text",text:T})}S.length>0&&d.push({role:R,content:S.length===1&&S[0].type==="text"?S[0].text:S})}let c={Fast:"none",Low:"none",Medium:"high",Standard:"high",High:"high",xHigh:"high"},l={model:n,messages:d,stream:!0,temperature:h,prompt_cache_key:"flux-flow-session"};s&&s!=="Fast"&&qs(n)&&(l.reasoning_effort=c[s]||"high");let f=await xs("https://api.mistral.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(l),signal:i});if(!f.ok){let E=await f.text().catch(()=>""),R=f.statusText;try{let S=JSON.parse(E);R=S.error?.message||S.message||JSON.stringify(S.detail||S)}catch{E&&(R=E)}throw new Error(`Mistral Error (${f.status}): ${JSON.stringify(R)}`)}let u=f.body.getReader(),p=new TextDecoder,g="",y=[],m=null,w=Date.now(),b=!1,x=E=>E?typeof E=="string"?Dn(E):Array.isArray(E)?E.map(x).filter(Boolean).join(""):typeof E=="object"&&E!==null?typeof E.text=="string"?Dn(E.text):typeof E.content=="string"?Dn(E.content):typeof E.thinking=="string"?Dn(E.thinking):typeof E.reasoning_content=="string"?Dn(E.reasoning_content):typeof E.reasoning=="string"?Dn(E.reasoning):typeof E.value=="string"?Dn(E.value):E.text?x(E.text):E.content?x(E.content):E.thinking?x(E.thinking):E.reasoning_content?x(E.reasoning_content):E.reasoning?x(E.reasoning):E.value?x(E.value):"":Dn(String(E)):"";for(;;){let{done:E,value:R}=await u.read();if(E){b&&(y.length>0||m)&&(yield{candidates:y.length>0?[{content:{parts:y}}]:[],usageMetadata:m});break}g+=p.decode(R,{stream:!0});let S=g.split(`
509
+ `);g=S.pop();for(let T of S){let $=T.trim();if(!$||!$.startsWith("data: "))continue;let _=!1;if($==="data: [DONE]")_=!0;else try{let k=JSON.parse($.substring(6)),C=k.choices?.[0]?.delta,I=k.usage;if(k.choices?.[0]?.finish_reason&&(_=!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},b=!0),C){let D=C.thinking||C.reasoning_content||C.reasoning,B=x(D);B&&(y.push({text:B,thought:!0}),b=!0);let N=C.content||(!C.thinking&&!C.reasoning_content&&!C.reasoning?C.text:null);if(N)if(Array.isArray(N))for(let Y of N)if(typeof Y=="object"&&Y!==null){let ne=Y.type==="thinking"||Y.type==="reasoning"||!!Y.thought,Ie=x(Y);Ie&&(y.push({text:Ie,...ne?{thought:!0}:{}}),b=!0)}else{let ne=x(Y);ne&&(y.push({text:ne}),b=!0)}else if(typeof N=="object"&&N!==null){let Y=N.type==="thinking"||N.type==="reasoning"||!!N.thought,ne=x(N);ne&&(y.push({text:ne,...Y?{thought:!0}:{}}),b=!0)}else{let Y=x(N);Y&&(y.push({text:Y}),b=!0)}}}catch{}if((_||Date.now()-w>=150)&&b&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),b=!1),_)break}Date.now()-w>=150&&b&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),b=!1)}},si=async function*(e,n,t,o,s,r,a=!1,i,h=1.05){let d=[];o&&d.push({role:"system",content:o}),t.forEach(ae=>{let _e=ae.role==="model"?"assistant":"user",A=[];Array.isArray(ae.parts)&&ae.parts.forEach(F=>{if(F.text)A.push({type:"text",text:F.text});else if(F.inlineData&&a){let V=F.inlineData.mimeType,X=F.inlineData.data;V.startsWith("image/")&&zt(n)&&A.push({type:"image_url",image_url:{url:`data:${V};base64,${X}`}})}}),d.push({role:_e,content:A.length===1&&A[0].type==="text"?A[0].text:A})});let l={Fast:"Fast",Low:"Fast",Medium:"Standard",Standard:"Standard",High:"High",xHigh:"High"}[s]||"High",f=l!=="Fast",u=n.includes("kimi"),p=n.includes("gemma"),g=n.includes("deepseek"),y=n.includes("glm"),m=n.includes("mistral"),w=n.includes("minimax"),b=n.includes("gpt"),x=n.includes("qwen"),E=n.includes("nemotron"),R=n.includes("llama-3"),S=n.includes("seed"),T=n.includes("poolside"),$=n.includes("thinkingmachines")||n.includes("muse"),_=R,k=null,C={Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},I={Fast:"64",Low:"64",Medium:"4096",Standard:"4096",High:"16384",xHigh:"16384"},D={Fast:"none",Low:"minimal",Medium:"medium",Standard:"medium",High:"max",xHigh:"max"},B=w||g||T||$?16384:32768;B=process.env.NVIDIA_BASE_URL?1024:B,B=k?1024:B;let N={model:n,messages:d,max_tokens:B,stream:!0,stream_options:{include_usage:!0},temperature:h,...b&&{thinking:C[s]||"high"}};if(!(process.env.NVIDIA_BASE_URL||_||k))if(u)N.chat_template_kwargs={thinking:f};else if(p)N.chat_template_kwargs={enable_thinking:f};else if(g)if(f){let ae=l==="High"?"max":"high";N.chat_template_kwargs={thinking:!0,reasoning_effort:ae}}else N.chat_template_kwargs={thinking:!1};else y?N.chat_template_kwargs={enable_thinking:f,clear_thinking:!f}:m?N.reasoning_effort=f?"high":"none":w&&n.includes("minimax-m3")?N.chat_template_kwargs={thinking_mode:f?"enabled":"disabled"}:x?N.chat_template_kwargs={enable_thinking:f}:E?l==="High"?(N.reasoning_budget=12e3,N.chat_template_kwargs={enable_thinking:!0}):l==="Standard"?(N.reasoning_budget=12e3,N.chat_template_kwargs={enable_thinking:!0,medium_effort:!0}):N.chat_template_kwargs={enable_thinking:!1}:S?f&&(N.extra_body={thinking_budget:parseInt(I[l]??"4096")}):T?N.chat_template_kwargs={enable_thinking:f}:$&&(N.reasoning_effort=D[l]||"medium");let Y=0,ne=6,Ie=!1,U=process.env.NVIDIA_BASE_URL||"https://integrate.api.nvidia.com/v1/chat/completions",j=process.env.NVIDIA_API_KEY&&process.env.NVIDIA_BASE_URL?process.env.NVIDIA_API_KEY:e;for(U.endsWith("/chat/completions")||(U=U.replace(/\/+$/,"")+"/chat/completions");Y<ne;){Y++;try{let ae=await xs(U,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${j}`},body:JSON.stringify(N),signal:i});if(!ae.ok){let je=await ae.text().catch(()=>""),ot=ae.statusText;try{let mt=JSON.parse(je);ot=mt.error?.message||mt.message||JSON.stringify(mt.detail||mt)}catch{je&&(ot=je)}let ze=new Error(`NVIDIA API Error (${ae.status}): ${ot}`);throw ze.status=ae.status,ze}let _e=ae.body.getReader(),A=new TextDecoder,F="",V=[],X=null,Ue=Date.now(),Ne=!1;for(;;){let{done:je,value:ot}=await _e.read();if(je){Ne&&(V.length>0||X)&&(yield{candidates:V.length>0?[{content:{parts:V}}]:[],usageMetadata:X},Ie=!0);break}F+=A.decode(ot,{stream:!0});let ze=F.split(`
510
+ `);F=ze.pop();let mt=!1;for(let Ut of ze){let gt=Ut.trim();if(gt){if(gt==="data: [DONE]"){mt=!0;break}if(gt.startsWith("data: ")){let yt;try{yt=JSON.parse(gt.substring(6))}catch{continue}if(yt.error)throw new Error(`NVIDIA Stream Error: ${yt.error.message||JSON.stringify(yt.error)}`);yt.choices?.[0]?.finish_reason&&(mt=!0);try{let Rt=yt.usage;Rt&&(X={totalTokenCount:Rt.total_tokens||Rt.prompt_tokens+Rt.completion_tokens,promptTokenCount:Rt.prompt_tokens||0,candidatesTokenCount:Rt.completion_tokens||0,cachedContentTokenCount:Rt.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:(Rt.completion_tokens_details?.reasoning_tokens||0)+(Rt.completion_tokens_details?.thoughts_tokens||0)},Ne=!0);let dt=yt.choices?.[0]?.delta?.reasoning||yt.choices?.[0]?.delta?.reasoning_content||"",$e=yt.choices?.[0]?.delta?.content||"";dt&&(V.push({text:dt,thought:!0}),Ne=!0),$e&&(V.push({text:$e}),Ne=!0)}catch{}}}}if((mt||Date.now()-Ue>=350)&&Ne&&(yield{candidates:V.length>0?[{content:{parts:[...V]}}]:[],usageMetadata:X},Ie=!0,V=[],Ue=Date.now(),Ne=!1),mt)break}break}catch(ae){if(Ie||Y>=ne)throw ae;await new Promise(_e=>setTimeout(_e,3500))}}},$c=async function*(e,n){let t=[],o=null,s=!1,r=null,a=f=>{if(t.push(f),o){let u=o;o=null,u()}},i=n.split("/").pop();i=i.replace("llama-3.3","llama-3_3");let h=`https://api.ngc.nvidia.com/v2/predict/queues/models/qc69jvmznzxy/${i}`,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(r=f,c&&(clearInterval(c),c=null),o){let u=o;o=null,u()}}})();try{for(;;){if(r)throw r;if(t.length>0){let f=t.shift();if(f===null&&s)break;yield f.value}else{if(s)break;await new Promise(f=>{o=f})}}}finally{c&&(clearInterval(c),c=null)}},oi=async function*(e,n,t,o,s,r,a,i,h=1.05){let d=[];o&&d.push({role:"system",content:[{type:"text",text:o,cache_control:{type:"ephemeral"}}]});for(let T of t){let $=T.role==="user"?"user":"assistant",_=[];if(Array.isArray(T.parts)){for(let k of T.parts)if(k.text)_.push({type:"text",text:k.text});else if(k.inlineData&&a){let C=k.inlineData.mimeType,I=k.inlineData.data;C.startsWith("image/")?_.push({type:"image_url",image_url:{url:`data:${C};base64,${I}`}}):_.push({type:"file",file:{filename:k.filename||"file",file_data:`data:${C};base64,${I}`}})}}else{let k=T.text||"";k&&_.push({type:"text",text:k})}d.push({role:$,content:_.length===1&&_[0].type==="text"?_[0].text:_})}let c={Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},l=n,f=null;if(l.includes("::")){let T=l.split("::");l=T[0].trim();let $=T.slice(1).join("::").toLowerCase().trim();["flex","priority","default"].includes($)&&$!=="default"&&(f=$)}let u=l;if(l.includes(":")){let[T,...$]=l.split(":"),_=$.join(":").toLowerCase().trim();f?u=`${T}:${_}/${f}`:u=`${T}:${_}`}let p={model:u,messages:d,stream:!0,temperature:h,cache_control:{type:"ephemeral"},session_id:"flux-flow-session"},g=c[s];g&&s!=="Fast"&&(p.reasoning_effort=g),console.log(p);let y=await xs("https://openrouter.ai/api/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json","X-Title":"FluxFlow CLI","X-Cache":"true","X-OpenRouter-Cache":"true"},body:JSON.stringify(p),signal:i});if(!y.ok){let T=await y.json().catch(()=>({}));throw new Error(`OpenRouter Error (${y.status}): ${T.error?.message||y.statusText}`)}let m=y.body.getReader(),w=new TextDecoder,b="",x=[],E=null,R=Date.now(),S=!1;for(;;){let{done:T,value:$}=await m.read();if(T){S&&(x.length>0||E)&&(yield{candidates:x.length>0?[{content:{parts:x}}]:[],usageMetadata:E});break}b+=w.decode($,{stream:!0});let _=b.split(`
511
+ `);b=_.pop();for(let k of _){let C=k.trim();if(!C||!C.startsWith("data: "))continue;let I=!1;if(C==="data: [DONE]")I=!0;else try{let D=JSON.parse(C.substring(6)),B=D.choices?.[0]?.delta,N=D.usage;if(D.choices?.[0]?.finish_reason&&(I=!0),N&&(E={totalTokenCount:N.total_tokens||(N.prompt_tokens||0)+(N.completion_tokens||0),promptTokenCount:N.prompt_tokens||0,candidatesTokenCount:N.completion_tokens||0,cachedContentTokenCount:N.prompt_tokens_details?.cached_tokens||N.prompt_tokens_details?.cache_read_input_tokens||N.cache_read_input_tokens||0,thoughtsTokenCount:N.completion_tokens_details?.reasoning_tokens||0},S=!0),B){let Y=B.reasoning||(B.reasoning_details?B.reasoning_details.map(ne=>ne.text).join(""):null);Y&&(x.push({text:Y,thought:!0}),S=!0),B.content&&(x.push({text:B.content}),S=!0)}}catch{}if((I||Date.now()-R>=150)&&S&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:E},x=[],R=Date.now(),S=!1),I)break}}},Da=async function*(e,n,t,o,s,r,a,i,h=1.05,d="Cloud"){let c=[];o&&c.push({role:"system",content:o});for(let S of t){let T=S.role==="user"?"user":"assistant",$="",_=[];if(Array.isArray(S.parts)){$=S.parts.map(k=>k.text||"").filter(Boolean).join(`
512
+ `);for(let k of S.parts){let C=k.inlineData||k.inline_data;C&&C.data&&_.push(C.data)}}else $=S.text||"";if($||_.length>0){let k={role:T,content:$};_.length>0&&(k.images=_),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 cc(u),g=[],y=null,m=Date.now(),w=!1,b={Fast:!1,Low:"medium",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},x=b[s]!==void 0?b[s]:!0,E={model:n,messages:c,stream:!0,think:x,keep_alive:"10m",options:{temperature:h}},R=await p.chat(E);for await(let S of R){if(i?.aborted)throw new DOMException("The user aborted a request.","AbortError");if(S.message?.thinking&&(g.push({text:S.message.thinking,thought:!0}),w=!0),S.message?.content&&(g.push({text:S.message.content}),w=!0),S.done){let T=S.prompt_cached_count||0;if(!T&&S.prompt_eval_count){let $=S.prompt_eval_duration||0;$>0&&$<5e7&&(T=S.prompt_eval_count)}y={totalTokenCount:(S.prompt_eval_count||0)+(S.eval_count||0),promptTokenCount:S.prompt_eval_count||0,candidatesTokenCount:S.eval_count||0,cachedContentTokenCount:T,thoughtsTokenCount:0},w=!0}(S.done||Date.now()-m>=150&&w)&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],m=Date.now(),w=!1)}w&&(g.length>0||y)&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y})},ri=async function*(e,n,t,o,s,r,a,i,h=1.05){let d=[];o&&d.push({role:"system",content:o});for(let x of t){let E=x.role==="user"?"user":"assistant",R=[];if(Array.isArray(x.parts)){for(let S of x.parts)if(S.text)R.push({type:"text",text:S.text});else if(S.inlineData&&a){let T=S.inlineData.mimeType,$=S.inlineData.data;T.startsWith("image/")&&R.push({type:"image_url",image_url:{url:`data:${T};base64,${$}`}})}}else{let S=x.text||"";S&&R.push({type:"text",text:S})}d.push({role:E,content:R.length===1&&R[0].type==="text"?R[0].text:R})}let c={Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},l={model:n,messages:d,stream:!0,stream_options:{include_usage:!0},temperature:h,max_completion_tokens:32768};c[s]&&(l.reasoning_effort=c[s]);let f=await xs("https://crof.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(l),signal:i});if(!f.ok){let x=await f.json().catch(()=>({}));throw new Error(`CrofAI Error (${f.status}): ${x.error?.message||f.statusText}`)}let u=f.body.getReader(),p=new TextDecoder,g="",y=[],m=null,w=Date.now(),b=!1;for(;;){let{done:x,value:E}=await u.read();if(x){b&&(y.length>0||m)&&(yield{candidates:y.length>0?[{content:{parts:y}}]:[],usageMetadata:m});break}g+=p.decode(E,{stream:!0});let R=g.split(`
513
+ `);g=R.pop();for(let S of R){let T=S.trim();if(!T||!T.startsWith("data: "))continue;let $=!1;if(T==="data: [DONE]")$=!0;else try{let _=JSON.parse(T.substring(6)),k=_.choices?.[0]?.delta,C=_.usage;if(_.choices?.[0]?.finish_reason&&($=!0),C&&(m={totalTokenCount:C.total_tokens||(C.prompt_tokens||0)+(C.completion_tokens||0),promptTokenCount:C.prompt_tokens||0,candidatesTokenCount:C.completion_tokens||0,cachedContentTokenCount:C.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:C.completion_tokens_details?.reasoning_tokens||C.reasoning_tokens||0},b=!0),k){let I=k.reasoning_content||null;I&&(y.push({text:I,thought:!0}),b=!0),k.content&&(y.push({text:k.content}),b=!0)}}catch{}if(($||Date.now()-w>=150)&&b&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),b=!1),$)break}Date.now()-w>=150&&b&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),b=!1)}},ii=async function*(e,n,t,o,s,r,a,i,h=1.05){let d=[];o&&d.push({role:"system",content:o});for(let x of t){let E=x.role==="user"?"user":"assistant",R="";if(Array.isArray(x.parts))for(let S of x.parts)S.text&&(R+=(R?`
514
+ `:"")+S.text);else R=x.text||"";d.push({role:E,content:R})}let c={Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},l={model:n,messages:d,stream:!0,stream_options:{include_usage:!0},temperature:h};c[s]&&(l.reasoning_effort=c[s]);let f=await xs("https://model.inferx.net/endpoints/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(l),signal:i});if(!f.ok){let x=await f.json().catch(()=>({}));throw new Error(`InferX Error (${f.status}): ${x.error?.message||f.statusText||String(x)}`)}let u=f.body.getReader(),p=new TextDecoder,g="",y=[],m=null,w=Date.now(),b=!1;for(;;){let{done:x,value:E}=await u.read();if(x){b&&(y.length>0||m)&&(yield{candidates:y.length>0?[{content:{parts:y}}]:[],usageMetadata:m});break}g+=p.decode(E,{stream:!0});let R=g.split(`
515
+ `);g=R.pop();for(let S of R){let T=S.trim();if(!T||!T.startsWith("data: "))continue;let $=!1;if(T==="data: [DONE]")$=!0;else try{let _=JSON.parse(T.substring(6)),k=_.choices?.[0]?.delta,C=_.usage;if(C&&(m={totalTokenCount:C.total_tokens||(C.prompt_tokens||0)+(C.completion_tokens||0),promptTokenCount:C.prompt_tokens||0,candidatesTokenCount:C.completion_tokens||0,cachedContentTokenCount:C.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:C.completion_tokens_details?.reasoning_tokens||C.reasoning_tokens||0},b=!0),k){let I=k.reasoning||k.reasoning_content||null;I&&(y.push({text:I,thought:!0}),b=!0),k.content&&(y.push({text:k.content}),b=!0)}}catch{}if(($||Date.now()-w>=150||m)&&b&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),b=!1),$)break}Date.now()-w>=150&&b&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),b=!1)}},ai=async function*(e,n,t,o,s,r,a,i,h=1.05){let d=[];o&&d.push({role:"system",content:o});for(let x of t){let E=x.role==="user"?"user":"assistant",R=[];if(Array.isArray(x.parts)){for(let S of x.parts)if(S.text)R.push({type:"text",text:S.text});else if(S.inlineData&&a){let T=S.inlineData.mimeType,$=S.inlineData.data;T.startsWith("image/")&&R.push({type:"image_url",image_url:{url:`data:${T};base64,${$}`}})}}else{let S=x.text||"";S&&R.push({type:"text",text:S})}d.push({role:E,content:R.length===1&&R[0].type==="text"?R[0].text:R})}let c={Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},l={model:n,messages:d,stream:!0,stream_options:{include_usage:!0},temperature:h};c[s]&&(l.reasoning_effort=c[s]);let f=await xs("https://token.sensenova.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(l),signal:i});if(!f.ok){let x=await f.json().catch(()=>({}));throw new Error(`SenseNova Error (${f.status}): ${x.error?.message||f.statusText}`)}let u=f.body.getReader(),p=new TextDecoder,g="",y=[],m=null,w=Date.now(),b=!1;for(;;){let{done:x,value:E}=await u.read();if(x){b&&(y.length>0||m)&&(yield{candidates:y.length>0?[{content:{parts:y}}]:[],usageMetadata:m});break}g+=p.decode(E,{stream:!0});let R=g.split(`
516
+ `);g=R.pop();for(let S of R){let T=S.trim();if(!T||!T.startsWith("data: "))continue;let $=!1;if(T==="data: [DONE]")$=!0;else try{let _=JSON.parse(T.substring(6)),k=_.choices?.[0]?.delta,C=_.usage;if(C&&(m={totalTokenCount:C.total_tokens||(C.prompt_tokens||0)+(C.completion_tokens||0),promptTokenCount:C.prompt_tokens||0,candidatesTokenCount:C.completion_tokens||0,cachedContentTokenCount:C.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:C.completion_tokens_details?.reasoning_tokens||C.reasoning_tokens||0},b=!0),k){let I=k.reasoning||k.reasoning_content||null;I&&(y.push({text:I,thought:!0}),b=!0),k.content&&(y.push({text:k.content}),b=!0)}}catch{}if(($||Date.now()-w>=150||m)&&b&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),b=!1),$)break}Date.now()-w>=150&&b&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),b=!1)}},Rm=()=>{Dt=!0},Em=()=>Dt,Qr={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"},ws=(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}},li=e=>e?new Ia({apiKey:e}):ei,_m=async(e,n,t,o,s={})=>{let{onStatus:i,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,b=process.env.NVIDIA_BASE_URL||m==="Ollama"||m==="CrofAI"||m==="InferX"||m==="SenseNova"?!1:g?.memory!==!1,E=J(Ft,[]).map(A=>`- [${A.id}]: ${A.memory}`).join(`
517
+ `),R=o.slice(0,-1).filter(A=>A.text&&!A.text.includes("[TOOL RESULT]")&&!A.text.includes("OBSERVATION:")&&!A.text.startsWith("[TERMINAL_RECORD]")&&!A.isTerminalRecord&&!A.isMeta&&!A.isLogo&&!String(A.id).startsWith("welcome")&&!String(A.id).startsWith("logo")).slice(-14).map(A=>{let F=_c(A.text).replace(/\[tool:functions\..*?\]/g,"").replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[METADATA \(PRIORITY: DYNAMIC\)\] Time: ([^|\n]+)/g,(Ne,je)=>`[METADATA (PRIORITY: DYNAMIC)] Time: ${je.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,`
518
518
  `).replace(/\n\n/g,`
519
519
  `).replace(/\\n\\n/g,"").trim(),V=A.role==="user"?8192:32768,X=F.substring(0,V);F.length>V&&(X+=`
520
- ... (truncated) ...`);let Ue=A.role==="user"?X.startsWith("[USER]")?"":"[USER]: ":X.startsWith("[AGENT]")?"":"[AGENT]: ";return{role:A.role==="user"?"user":"model",parts:[{text:`${Ue}${X}`}]}}),S=o.filter(A=>A.role==="user").length===1,T=n.includes("[TITLE-UPDATE]"),$=Math.random()<.8,_=S||T||$,k=t.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").trim(),C=Mr(E,x,_),I=`${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)}`;I.length>32768&&(I+=`
520
+ ... (truncated) ...`);let Ue=A.role==="user"?X.startsWith("[USER]")?"":"[USER]: ":X.startsWith("[AGENT]")?"":"[AGENT]: ";return{role:A.role==="user"?"user":"model",parts:[{text:`${Ue}${X}`}]}}),S=o.filter(A=>A.role==="user").length===1,T=n.includes("[TITLE-UPDATE]"),$=Math.random()<.8,_=S||T||$,k=t.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").trim(),C=Ci(E,b,_),I=`${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)}`;I.length>32768&&(I+=`
521
521
  ... (truncated) ...`);let D=n.replace(/\[Prompted on:.*?\]/g,"").trim();I=I.replace(/\r?\n\r?\n/g,`
522
522
  `).replace(/\n\n/g,`
523
523
  `).replace(/\\n\\n/g,"").trim();let B=new Date,Y=`[METADATA] Current date and Time: ${`${B.getFullYear()}-${B.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(B.getDate()).padStart(2,"0")}, ${B.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0})}`}
@@ -526,11 +526,11 @@ ${l[7]}`};import{WebSocket as Bo}from"ws";var Yt=null,Ns=!1,sc="ws://localhost:5
526
526
  ${D.length>8192?`... (truncated) ...
527
527
 
528
528
  `:""}
529
- [AGENT (current turn)]: ${I}`;R.push({role:"user",parts:[{text:Y}]});let ne=await Zo("NVIDIA"),U=(await Ft()).quotas?.providerTiers?.NVIDIA==="Free",j="",ae=0,Ee=x?12:-1;for(;ae<=Ee;)try{if(!await Dr("background",e))return;let A="",F=null,V=!1,X=m;try{let je=new Promise((ct,_e)=>setTimeout(()=>_e(new Error("JANITOR_TIMEOUT")),1e4)),ot=m==="Google"&&ae>=0&&ae<6&&ne&&U,ze=m==="DeepSeek"&&ae<4&&ne&&U;V=ot||ze,X=V?"NVIDIA":m;let pt=(async()=>{if(m==="OpenRouter"){let ct=ve("janitor_open_router"),ie=ir(w,ct,R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),Vt=await ie.next();return{iterator:ie,firstResult:Vt}}else if(m==="DeepSeek"&&!V){let _e=nr(w,ve("deepseek_fast_fallback"),R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),ie=await _e.next();return{iterator:_e,firstResult:ie}}else if(m==="Mistral"&&!V){let _e=sr(w,ve("mistral_janitor_fallback"),R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),ie=await _e.next();return{iterator:_e,firstResult:ie}}else if(m==="NVIDIA"||V){let _e=or(V?ne:w,ve("nvidia_janitor_fallback"),R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),ie=await _e.next();return{iterator:_e,firstResult:ie}}else if(m==="CrofAI"){let _e=rr(w,targetModel||ve("crofai_fallback")||"deepseek-v4-flash-0731",R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),ie=await _e.next();return{iterator:_e,firstResult:ie}}else if(m==="InferX"){let _e=ar(w,targetModel||ve("inferx_fallback")||"deepseek-v4-flash",R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),ie=await _e.next();return{iterator:_e,firstResult:ie}}else if(m==="SenseNova"){let _e=lr(w,targetModel||ve("sensenova_fallback")||"sensenova-6.8-flash-lite",R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),ie=await _e.next();return{iterator:_e,firstResult:ie}}else{let ie=(await cr(w).models.generateContentStream({model:u||(ae===Ee?ve("janitor_default"):ve("gemma_janitor_fallback_google")),contents:R,config:{systemInstruction:C,temperature:.7,safetySettings:[{category:Vn.HARM_CATEGORY_HARASSMENT,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_HATE_SPEECH,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Yn.BLOCK_NONE}],thinkingConfig:{includeThoughts:!1,thinkingLevel:lt.MINIMAL}}}))[Symbol.asyncIterator](),Vt=await ie.next();return{iterator:ie,firstResult:Vt}}})();if(process.stdout.isTTY){let ie=(await ls())[p]?.name||"",Vt=ie&&!ie.startsWith("flow-")&&!ie.startsWith("Session ")?ie:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${Vt}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${Vt}\x07`)}let{iterator:Bt,firstResult:mt}=await Promise.race([pt,je]),{value:gt,done:Tt}=mt;if(!Tt&&gt){let ct=gt.candidates?.[0]?.content?.parts,_e=ct?X==="Google"?ct[1]?.text||ct[0]?.text||"":ct.filter(ie=>ie.text&&!ie.thought).map(ie=>ie.text).join(""):typeof gt.text=="function"?gt.text():"";_e&&(A+=_e),F=gt.usageMetadata;for await(let ie of{[Symbol.asyncIterator]:()=>Bt}){let Vt=ie.candidates?.[0]?.content?.parts,Xn=Vt?X==="Google"?Vt[1]?.text||Vt[0]?.text||"":Vt.filter(Jn=>Jn.text&&!Jn.thought).map(Jn=>Jn.text).join(""):typeof ie.text=="function"?ie.text():"";Xn&&(A+=Xn),F=ie.usageMetadata}}}catch(je){throw je}if(A){if(j=A,F){let je=F.totalTokenCount||0,ot=F.cachedContentTokenCount||0,ze=(F.candidatesTokenCount||0)+(F.thoughtsTokenCount||0),pt=V?ve("nvidia_janitor_fallback"):X==="DeepSeek"?ve("deepseek_fast_fallback"):X==="OpenRouter"?ve("janitor_open_router"):u||(ae===Ee?ve("janitor_default"):ve("gemma_janitor_fallback_google"));await Kt("tokens",je,X,pt),ot>0&&await Kt("cachedTokens",ot,X,pt),ze>0&&await Kt("candidateTokens",ze,X,pt)}}else throw new Error("No synthesis generated by Janitor.");d&&(d(),await It("background"));let Ue=Go(j),Ne=!1;for(let je of Ue){let ot=je.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(ot)&&(Ne=!0);let ze={chatId:p,sessionId:p,history:o},pt=await uo(ot,je.args,ze);ot.toLowerCase()==="memory"&&(je.args.includes("action='user'")||je.args.includes('action="user"'))&&!pt.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(mt=>setTimeout(mt,3e3)))}if(!Ne)try{let je=J(Pt,[]);if(je.length>0){let ot=[];for(let ze of je)ze.score===void 0&&(ze.score=.5),ze.score*=.99995,ze.score<.05&&(ze.score=0),ze.score=Math.round(ze.score*1e5)/1e5,ze.score>0&&ot.push(ze);pe(Pt,ot)}}catch{}break}catch(A){ae++;let F=new Date().toLocaleString(),V=A instanceof Error?(()=>{try{return JSON.parse(JSON.parse(A.message).error.message).error.message}catch{return String(A)}})():String(A);await new Promise(Ne=>setTimeout(Ne,1e3));let X=Q.join(fn,"janitor");if(De.existsSync(X)||De.mkdirSync(X,{recursive:!0}),De.appendFileSync(Q.join(X,"error.log"),`ERROR [Attempt ${ae}/${Ee+1}] [${F}]: ${V}
529
+ [AGENT (current turn)]: ${I}`;R.push({role:"user",parts:[{text:Y}]});let ne=await Qo("NVIDIA"),U=(await Nt()).quotas?.providerTiers?.NVIDIA==="Free",j="",ae=0,_e=b?12:-1;for(;ae<=_e;)try{if(!await Li("background",e))return;let A="",F=null,V=!1,X=m;try{let je=new Promise((dt,$e)=>setTimeout(()=>$e(new Error("JANITOR_TIMEOUT")),1e4)),ot=m==="Google"&&ae>=0&&ae<6&&ne&&U,ze=m==="DeepSeek"&&ae<4&&ne&&U;V=ot||ze,X=V?"NVIDIA":m;let mt=(async()=>{if(m==="OpenRouter"){let dt=ve("janitor_open_router"),re=oi(w,dt,R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),Vt=await re.next();return{iterator:re,firstResult:Vt}}else if(m==="DeepSeek"&&!V){let $e=ti(w,ve("deepseek_fast_fallback"),R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),re=await $e.next();return{iterator:$e,firstResult:re}}else if(m==="Mistral"&&!V){let $e=ni(w,ve("mistral_janitor_fallback"),R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),re=await $e.next();return{iterator:$e,firstResult:re}}else if(m==="NVIDIA"||V){let $e=si(V?ne:w,ve("nvidia_janitor_fallback"),R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),re=await $e.next();return{iterator:$e,firstResult:re}}else if(m==="CrofAI"){let $e=ri(w,targetModel||ve("crofai_fallback")||"deepseek-v4-flash-0731",R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),re=await $e.next();return{iterator:$e,firstResult:re}}else if(m==="InferX"){let $e=ii(w,targetModel||ve("inferx_fallback")||"deepseek-v4-flash",R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),re=await $e.next();return{iterator:$e,firstResult:re}}else if(m==="SenseNova"){let $e=ai(w,targetModel||ve("sensenova_fallback")||"sensenova-6.8-flash-lite",R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),re=await $e.next();return{iterator:$e,firstResult:re}}else{let re=(await li(w).models.generateContentStream({model:u||(ae===_e?ve("janitor_default"):ve("gemma_janitor_fallback_google")),contents:R,config:{systemInstruction:C,temperature:.7,safetySettings:[{category:Vn.HARM_CATEGORY_HARASSMENT,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_HATE_SPEECH,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Yn.BLOCK_NONE}],thinkingConfig:{includeThoughts:!1,thinkingLevel:ct.MINIMAL}}}))[Symbol.asyncIterator](),Vt=await re.next();return{iterator:re,firstResult:Vt}}})();if(process.stdout.isTTY){let re=(await as())[p]?.name||"",Vt=re&&!re.startsWith("flow-")&&!re.startsWith("Session ")?re:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${Vt}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${Vt}\x07`)}let{iterator:Ut,firstResult:gt}=await Promise.race([mt,je]),{value:yt,done:Rt}=gt;if(!Rt&&yt){let dt=yt.candidates?.[0]?.content?.parts,$e=dt?X==="Google"?dt[1]?.text||dt[0]?.text||"":dt.filter(re=>re.text&&!re.thought).map(re=>re.text).join(""):typeof yt.text=="function"?yt.text():"";$e&&(A+=$e),F=yt.usageMetadata;for await(let re of{[Symbol.asyncIterator]:()=>Ut}){let Vt=re.candidates?.[0]?.content?.parts,Xn=Vt?X==="Google"?Vt[1]?.text||Vt[0]?.text||"":Vt.filter(Jn=>Jn.text&&!Jn.thought).map(Jn=>Jn.text).join(""):typeof re.text=="function"?re.text():"";Xn&&(A+=Xn),F=re.usageMetadata}}}catch(je){throw je}if(A){if(j=A,F){let je=F.totalTokenCount||0,ot=F.cachedContentTokenCount||0,ze=(F.candidatesTokenCount||0)+(F.thoughtsTokenCount||0),mt=V?ve("nvidia_janitor_fallback"):X==="DeepSeek"?ve("deepseek_fast_fallback"):X==="OpenRouter"?ve("janitor_open_router"):u||(ae===_e?ve("janitor_default"):ve("gemma_janitor_fallback_google"));await Kt("tokens",je,X,mt),ot>0&&await Kt("cachedTokens",ot,X,mt),ze>0&&await Kt("candidateTokens",ze,X,mt)}}else throw new Error("No synthesis generated by Janitor.");d&&(d(),await Lt("background"));let Ue=Ho(j),Ne=!1;for(let je of Ue){let ot=je.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(ot)&&(Ne=!0);let ze={chatId:p,sessionId:p,history:o},mt=await fo(ot,je.args,ze);ot.toLowerCase()==="memory"&&(je.args.includes("action='user'")||je.args.includes('action="user"'))&&!mt.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(gt=>setTimeout(gt,3e3)))}if(!Ne)try{let je=J(Ft,[]);if(je.length>0){let ot=[];for(let ze of je)ze.score===void 0&&(ze.score=.5),ze.score*=.99995,ze.score<.05&&(ze.score=0),ze.score=Math.round(ze.score*1e5)/1e5,ze.score>0&&ot.push(ze);pe(Ft,ot)}}catch{}break}catch(A){ae++;let F=new Date().toLocaleString(),V=A instanceof Error?(()=>{try{return JSON.parse(JSON.parse(A.message).error.message).error.message}catch{return String(A)}})():String(A);await new Promise(Ne=>setTimeout(Ne,1e3));let X=Q.join(fn,"janitor");if(De.existsSync(X)||De.mkdirSync(X,{recursive:!0}),De.appendFileSync(Q.join(X,"error.log"),`ERROR [Attempt ${ae}/${_e+1}] [${F}]: ${V}
530
530
 
531
- `),ae>Ee)break;let Ue=Math.min(750*Math.pow(2,ae-1),5e3);await new Promise(Ne=>setTimeout(Ne,Ue))}if(ae){let A=Q.join(fn,"janitor");De.appendFileSync(Q.join(A,"error.log"),`-----------------------------------------------------------------------------
531
+ `),ae>_e)break;let Ue=Math.min(750*Math.pow(2,ae-1),5e3);await new Promise(Ne=>setTimeout(Ne,Ue))}if(ae){let A=Q.join(fn,"janitor");De.appendFileSync(Q.join(A,"error.log"),`-----------------------------------------------------------------------------
532
532
 
533
- `)}if(process.stdout.isTTY)try{let V=(await ls())[p]?.name||"",X=V&&!V.startsWith("flow-")&&!V.startsWith("Session ")?V:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${X}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${X}\x07`)}catch{process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")}},$c=e=>{let n=e.replace(xc,"").replace(bc,""),t=Os?n:n.replace(La,s=>" ".repeat(s.length)).replace(Da,s=>" ".repeat(s.length));po.lastIndex=0;let o;for(;(o=po.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,po.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}},Fa=(e,n=!0)=>{let t=po;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(Ea,""):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(Ea,""):e.substring(s)),o},Cc=(e,n,t)=>{let o=po;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},Ia=e=>Fa(e,!0),Mc=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("");$a.lastIndex=0;let o=e.replace($a,(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=kc;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 Ca.lastIndex=0,Ma.lastIndex=0,o=o.replace(Ca,""),o=o.replace(Ma,""),o},Ac=/(?:path|query|url|keyword|command|method|title|task|id)\s*=\s*['"`]?\s*\.\.\.\s*['"`]?/i,vc=/^['"`]?\s*\.\.\.\s*['"`]?$/,Dn=e=>{if(e==null)return!1;let n=String(e).trim();return n==="..."||n==="\u2026"||vc.test(n)},Go=e=>{if(!e)return[];let n=Mc(e);_a.lastIndex=0;let t=n.replace(_a,""),o=[],s=Os?t:t.replace(La,r=>" ".repeat(r.length)).replace(Da,r=>" ".repeat(r.length)),i=mc;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=O(u);Dn(g.path)||Dn(g.query)||Dn(g.url)||Dn(g.keyword)||Dn(g.command)||Dn(g.method)||Dn(g.title)||Dn(g.task)||Dn(g.id)||Ac.test(u)||o.push({fullMatch:p,toolName:r.trim(),args:u.trim()}),i.lastIndex=l+1}}return o},_m=(e,n={})=>{if(!e)return null;if(jo=n,tr=new Oa({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}}}},Ho=async(e,n,t,o,s="Fast",i=.75,a="agent")=>Tc(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=Pa(h,n,f,o,s,d,zt(n),p,i,systemSettings?.ollamaEndpoint||"Cloud"):r==="OpenRouter"?y=ir(h,n,f,o,s,d,zt(n),p,i):r==="DeepSeek"?y=nr(h,n,f,o,s,d,zt(n),p,i):r==="Mistral"?y=sr(h,n,f,o,s,d,zt(n),p,i):r==="NVIDIA"?y=or(h,n,f,o,s,d,zt(n),p,i):r==="CrofAI"?y=rr(h,n,f,o,s,d,zt(n),p,i):r==="InferX"?y=ar(h,n,f,o,s,d,zt(n),p,i):r==="SenseNova"?y=lr(h,n,f,o,s,d,zt(n),p,i):y=await cr(h).models.generateContentStream({model:n,contents:f,config:{systemInstruction:o,temperature:i,thinkingConfig:(()=>{let x=(n||"").toLowerCase(),b=x.includes("gemma-4")||x.startsWith("gemma"),E=x.includes("gemini-3");if(b||E)return b?s.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:lt.MINIMAL}:{includeThoughts:!0,thinkingLevel:lt.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:x.includes("pro")?lt.LOW:lt.MINIMAL,Low:lt.LOW,Medium:lt.MEDIUM,Standard:lt.MEDIUM,High:lt.HIGH,xHigh:lt.HIGH}[s]||lt.MEDIUM};{let R={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[s]||2048;return R===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:R}}})()}},{signal:p});for await(let m of y){if(Ot)throw new Error("Subagent task was cancelled.");if(e?.taskId&&typeof Xe<"u"){let b=Xe.find(E=>E.id===e.taskId);if(b&&b.status==="cancelled")throw new Error("Subagent task was cancelled.")}let w="";if(m.candidates?.[0]?.content?.parts)for(let b of m.candidates[0].content.parts)b.text&&!b.thought&&(c+=b.text,w+=b.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 Kt("tokens",y,r,n),m>0&&await Kt("cachedTokens",m,r,n),w>0&&await Kt("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}}),Ic=async(e,n,t=null)=>{t=t||J(en,{});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.
533
+ `)}if(process.stdout.isTTY)try{let V=(await as())[p]?.name||"",X=V&&!V.startsWith("flow-")&&!V.startsWith("Session ")?V:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${X}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${X}\x07`)}catch{process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")}},Cc=e=>{let n=e.replace(bc,"").replace(kc,""),t=Is?n:n.replace(Oa,s=>" ".repeat(s.length)).replace(La,s=>" ".repeat(s.length));ho.lastIndex=0;let o;for(;(o=ho.exec(t))!==null;){let s=o.index+o[0].length-1,r=0,a=null,i=!1,h=!1;for(let d=s;d<t.length;d++){let c=n[d];if(!a&&(c==='"'||c==="'"||c==="`")?(a=c,i=!1):a&&c===a&&!i&&(a=null),!a&&(c==="("?r++:c===")"&&r--,r===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==="\\"?i=!i:i=!1}if(!h)return{inside:!0,toolName:o[1],startIndex:o.index,args:n.substring(o.index+o[0].length)}}return{inside:!1}},Pa=(e,n=!0)=>{let t=ho;t.lastIndex=0;let o="",s=0,r;for(;(r=t.exec(e))!==null;){let a=e.substring(s,r.index);o+=n?a.replace(Ra,""):a;let i=r.index+r[0].length-1,h=0,d=null,c=-1;for(let l=i;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."+r[1]+"()]",s=c+1,t.lastIndex=s;else{o+="[tool:functions."+r[1]+"(",s=e.length;break}}return s<e.length&&(o+=n?e.substring(s).replace(Ra,""):e.substring(s)),o},Mc=(e,n,t)=>{let o=ho;o.lastIndex=0;let s="",r=0,a;for(;(a=o.exec(e))!==null;){let i=e.substring(r,a.index);s+=i.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),r=l+1,o.lastIndex=r;else{s+=e.substring(a.index),r=e.length;break}}return r<e.length&&(s+=e.substring(r).replace(n,t)),s},va=e=>Pa(e,!0),Ac=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(r=>r.charAt(0).toUpperCase()+r.slice(1)).join("");_a.lastIndex=0;let o=e.replace(_a,(s,r,a)=>{let i="";try{let c=JSON.parse(a.trim());c&&typeof c=="object"&&(i=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=Sc;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?i=l.join(", "):i=a.trim()}let h=r.toLowerCase().replace(/_/g,"");return`[tool:functions.${n[h]||t(r)}(${i})]`});return $a.lastIndex=0,Ca.lastIndex=0,o=o.replace($a,""),o=o.replace(Ca,""),o},vc=/(?:path|query|url|keyword|command|method|title|task|id)\s*=\s*['"`]?\s*\.\.\.\s*['"`]?/i,Ic=/^['"`]?\s*\.\.\.\s*['"`]?$/,Ln=e=>{if(e==null)return!1;let n=String(e).trim();return n==="..."||n==="\u2026"||Ic.test(n)},Ho=e=>{if(!e)return[];let n=Ac(e);Ea.lastIndex=0;let t=n.replace(Ea,""),o=[],s=Is?t:t.replace(Oa,i=>" ".repeat(i.length)).replace(La,i=>" ".repeat(i.length)),r=gc;r.lastIndex=0;let a;for(;(a=r.exec(s))!==null;){let i=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=O(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)||vc.test(u)||o.push({fullMatch:p,toolName:i.trim(),args:u.trim()}),r.lastIndex=l+1}}return o},$m=(e,n={})=>{if(!e)return null;if(Wo=n,ei=new Ia({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",r=.75,a="agent")=>Rc(async()=>{let{aiProvider:i="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(()=>{Dt&&(u.abort(),clearInterval(g))},100);try{let y;i==="Ollama"?y=Da(h,n,f,o,s,d,zt(n),p,r,systemSettings?.ollamaEndpoint||"Cloud"):i==="OpenRouter"?y=oi(h,n,f,o,s,d,zt(n),p,r):i==="DeepSeek"?y=ti(h,n,f,o,s,d,zt(n),p,r):i==="Mistral"?y=ni(h,n,f,o,s,d,zt(n),p,r):i==="NVIDIA"?y=si(h,n,f,o,s,d,zt(n),p,r):i==="CrofAI"?y=ri(h,n,f,o,s,d,zt(n),p,r):i==="InferX"?y=ii(h,n,f,o,s,d,zt(n),p,r):i==="SenseNova"?y=ai(h,n,f,o,s,d,zt(n),p,r):y=await li(h).models.generateContentStream({model:n,contents:f,config:{systemInstruction:o,temperature:r,thinkingConfig:(()=>{let b=(n||"").toLowerCase(),x=b.includes("gemma-4")||b.startsWith("gemma"),E=b.includes("gemini-3");if(x||E)return x?s.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:ct.MINIMAL}:{includeThoughts:!0,thinkingLevel:ct.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:b.includes("pro")?ct.LOW:ct.MINIMAL,Low:ct.LOW,Medium:ct.MEDIUM,Standard:ct.MEDIUM,High:ct.HIGH,xHigh:ct.HIGH}[s]||ct.MEDIUM};{let R={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[s]||2048;return R===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:R}}})()}},{signal:p});for await(let m of y){if(Dt)throw new Error("Subagent task was cancelled.");if(e?.taskId&&typeof Xe<"u"){let x=Xe.find(E=>E.id===e.taskId);if(x&&x.status==="cancelled")throw new Error("Subagent task was cancelled.")}let w="";if(m.candidates?.[0]?.content?.parts)for(let x of m.candidates[0].content.parts)x.text&&!x.thought&&(c+=x.text,w+=x.text);let b=w?w.trim().split(/\s+/).filter(Boolean).length:0;e&&typeof e.onTokenChunk=="function"&&e.onTokenChunk(w,b),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 Kt("tokens",y,i,n),m>0&&await Kt("cachedTokens",m,i,n),w>0&&await Kt("candidateTokens",w,i,n),e&&typeof e.onUsage=="function"&&e.onUsage({totalTokenCount:y,cachedContentTokenCount:m,candidatesTokenCount:w})}return await Lt("agent",i),{text:c,usageMetadata:l}}),Oc=async(e,n,t=null)=>{t=t||J(tn,{});try{let{aiProvider:o="Google"}=n;if(Object.values(t).flat().length<=5)return;let r=Object.keys(t).filter(f=>f!==e&&Array.isArray(t[f])&&t[f].length>2);if(r.length===0)return;let a=`You are a silent background process for the FluxFlow CLI Agent.
534
534
  Your task is to summarize or merge temporary context memories from one or more past conversation sessions.
535
535
  For each Chat ID provided, you must output a tool call to save the consolidated summary.
536
536
 
@@ -545,8 +545,8 @@ Guidelines:
545
545
 
546
546
  Chats to process:
547
547
 
548
- `,r=J(vn,{});for(let f of i){let p=t[f].map(y=>`- ${y}`).join(`
549
- `),g=r[f];a+=`[Chat ID: ${f}]
548
+ `,i=J(An,{});for(let f of r){let p=t[f].map(y=>`- ${y}`).join(`
549
+ `),g=i[f];a+=`[Chat ID: ${f}]
550
550
  `,g?(a+=`- Existing Summary: "${g}"
551
551
  `,a+=`
552
552
  -- New Memories to integrate:
@@ -555,10 +555,10 @@ ${p}
555
555
  `):a+=`-- Individual Memories:
556
556
  ${p}
557
557
 
558
- `}let h=0,d=5,c=!1,l=ve("gemma_janitor_fallback_google");for(o==="OpenRouter"&&(l=ve("janitor_open_router")),o==="DeepSeek"&&(l=ve("deepseek_level_1")),o==="Mistral"&&(l=ve("mistral_level_1")),o==="NVIDIA"&&(l=ve("nvidia_janitor_fallback")),o==="CrofAI"&&(l=ve("crofai_fallback")),o==="InferX"&&(l=ve("inferx_fallback")),o==="SenseNova"&&(l=ve("sensenova_fallback"));h<=d&&!c;){h++;try{let u=(await Ho(n,l,a,null,"Fast",.75,"background")).text||"",p=Go(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 uo(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(fn,"janitor");De.existsSync(i)||De.mkdirSync(i,{recursive:!0}),De.appendFileSync(Q.join(i,"error.log"),`[${new Date().toLocaleString()}] Past memory batch consolidation error: ${s}
559
- `)}},Oc=async(e,n,t=!1)=>{let{chatId:o,aiProvider:s="Google"}=e,i=Q.join(bo,"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(`
558
+ `}let h=0,d=5,c=!1,l=ve("gemma_janitor_fallback_google");for(o==="OpenRouter"&&(l=ve("janitor_open_router")),o==="DeepSeek"&&(l=ve("deepseek_level_1")),o==="Mistral"&&(l=ve("mistral_level_1")),o==="NVIDIA"&&(l=ve("nvidia_janitor_fallback")),o==="CrofAI"&&(l=ve("crofai_fallback")),o==="InferX"&&(l=ve("inferx_fallback")),o==="SenseNova"&&(l=ve("sensenova_fallback"));h<=d&&!c;){h++;try{let u=(await jo(n,l,a,null,"Fast",.75,"background")).text||"",p=Ho(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 fo(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),r=Q.join(fn,"janitor");De.existsSync(r)||De.mkdirSync(r,{recursive:!0}),De.appendFileSync(Q.join(r,"error.log"),`[${new Date().toLocaleString()}] Past memory batch consolidation error: ${s}
559
+ `)}},Lc=async(e,n,t=!1)=>{let{chatId:o,aiProvider:s="Google"}=e,r=Q.join(xo,"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(`
560
560
 
561
- `),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:
561
+ `),i=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:
562
562
  ${p}
563
563
 
564
564
  Here is the new conversation history:
@@ -567,72 +567,72 @@ ${u}
567
567
  Provide a new consolidated summary of the entire session.`:`Here is the conversation history:
568
568
  ${u}
569
569
 
570
- Provide a consolidated summary of the entire session.`,m=ve("gemma_janitor_fallback_google");s==="OpenRouter"&&(m=ve("janitor_open_router")),s==="DeepSeek"&&(m=ve("deepseek_level_1")),s==="Mistral"&&(m=ve("mistral_level_1")),s==="NVIDIA"&&(m=ve("nvidia_chat_summarizer_fallback")),s==="CrofAI"&&(m=ve("crofai_fallback")),s==="InferX"&&(m=ve("inferx_fallback")),s==="SenseNova"&&(m=ve("sensenova_fallback"));let w=0,x=!1,b=null;for(;w<=3&&!x;){w++;try{b=await Ho(e,m,y,g,"Fast"),x=!0}catch{if(w>3){if(s==="Google")try{let R=ve("general_fallback");return(await Ho(e,R,y,g,"Fast")).text||""}catch{return""}return""}}}return b&&b.text||""},h=a(n),d=J(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=Rc(n);return t?c.historyLength=(c.historyLength||0)+u:c.historyLength=u,d[o]=c,pe(i,d),f}return null},$m=e=>{try{let n=Q.join(bo,"chat-summaries.json");if(De.existsSync(n)){let t=J(n,{});t[e]&&(delete t[e],pe(n,t))}}catch{}},Cm=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=zt(e);if(!tr&&u==="Google")throw new Error("AI not initialized");let m=process.env.NVIDIA_BASE_URL||t?.aiProvider==="Ollama"||t?.aiProvider==="CrofAI"||t?.aiProvider==="InferX"||t?.aiProvider==="SenseNova"?!1:l?.memory!==!1,w=n[n.length-1].text,x=Q.join(bo,"chat-summaries.json"),b=!1,E=n.filter(_=>_.role==="user").length===1,R=w.includes("[TITLE-UPDATE]"),S=E||R,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 ht.startTransaction(d,T),l?.advanceRollback&&await Kn.takeInitialSnapshot(d),Ot=!1;let $=null;try{let _=new AbortController;$=setInterval(()=>{Ot&&(_.abort(),$&&(clearInterval($),$=null))},400);let k=[...n.slice(0,-1)];{let Le=J(x,{})[d]||{summary:"",historyLength:0};if(Le.summary&&Le.historyLength>0){let tn=0,$e=[];for(let Ze=0;Ze<k.length;Ze++){let He=k[Ze];(He.role==="user"||He.role==="agent"||He.role==="system")&&!String(He.id).startsWith("welcome")&&!He.isMeta&&tn++,tn>Le.historyLength&&$e.push(He)}k=$e}}k=k.map(H=>{if(H.role==="user"&&H.text){let Le=H.text.match(/\[USER\]([\s\S]*?)\[\/USER\]/);if(Le)return{...H,text:Le[1].trim()}}return{...H}});let C=process.env.HIGH_CONTEXT,I=255e3,D=26e4;if(C&&C!=="false"){let H=parseInt(C,10);!isNaN(H)&&H>=256e3&&H<=1e6&&(D=H,I=Math.round(H*.85))}if((u==="NVIDIA"&&(e?.includes("gpt")||e?.includes("qwen")||e?.includes("medium")||e.includes("muse"))||u==="Mistral")&&(I=122e3,D=126e3),u!=="Ollama"&&(f?.tokens||0)>I&&(yield{type:"status_history",content:"Context Limit Reached. Condensing session history..."},await Oc(t,k,!0)&&(k=[],b=!0)),E&&m){let H=J(en,{});Object.values(H).flat().length>5&&(yield{type:"status",content:"Condensing past chat memories"},await Ic(d,t,H))}let B=J(en,{}),N=J(vn,{}),Y=Object.entries(B).filter(([H])=>H!==d).flatMap(([H,Le])=>Le),Ie=[...Object.entries(N).filter(([H])=>H!==d).slice(-20).map(([H,Le])=>`[Chat Summary]: ${Le}`),...Y].map(H=>`- ${H}`).join(`
571
- `),j=J(Pt,[]).map(H=>`- ${H.memory}`).join(`
572
- `),ae=(f?.tokens||0)>=1e4,Ee=$r(Ie,j,m,ae),A=new Date,F=A.getFullYear(),V=A.toLocaleString("en-US",{month:"short"}).toUpperCase(),X=String(A.getDate()).padStart(2,"0"),Ue=A.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}),Ne=`${F}-${V}-${X}, ${Ue}`,je=[".git","node_modules",".gemini","dist","build",".next","out",".cache","bin","obj","vendor","venv",".idea",".gradle",".terraform","target","coverage",".vscode",".svn",".hg",".fslckout",".github",".gitlab",".circleci",".gitea",".gitee",".lerna",".changeset",".nx",".npm",".yarn",".pnpm-store",".pnpm",".expo",".nuxt",".svelte-kit",".docusaurus",".turbo",".vercel","bower_components",".netlify",".vuepress",".quasar",".output",".angular","jspm_packages",".parcel-cache",".rollup.cache",".rspack",".vitepress","__pycache__",".pytest_cache",".mypy_cache",".tox",".poetry","env","vhdl",".ipynb_checkpoints",".jupyter",".conda",".pdm-build",".bundle",".yardoc",".metadata","App_Data","ClientBin",".cargo",".rustc_info",".go","Godeps","_vendor",".rake_tasks","CMakefiles",".wakatime",".dart_tool",".fvm",".cocoapods","Pods",".pub-cache",".symlinks","DerivedData",".xcworkspace",".serverless",".aws",".gcloud",".azure",".kube",".vagrant",".docker","postgres-data","redis-data","mongo-data",".Spotlight-V100",".Trashes","$RECYCLE.BIN","System Volume Information",".DocumentRevisions-V100",".fseventsd","AppData","Application Data","Local","LocalLow","Roaming","$WinREAgent","$WINDOWS.~BT","$WINDOWS.~WS","scw","System32","SysWOW64",".AppleDouble",".AppleDB",".AppleDesktop","_CodeSignature",".cmio",".LSOverride",".localized",".TemporaryItems",".Trash",".Trash-0",".Trash-1000",".gvfs",".local",".config",".dbus",".fontconfig",".snap",".var",".lost+found","lost+found",".thumb",".thumbnails","EFI","boot","grub","logs","log",".nyc_output",".sonar",".ruff_cache",".VSCodeCounter"],ot=H=>{try{return De.readdirSync(H,{withFileTypes:!0})}catch{return[]}},ze=(H,Le={value:0},tn=1)=>{if(Le.value>6200||tn>7)return Le.value;let $e=ot(H);for(let Ze of $e){if(Le.value>6200)break;je.includes(Ze.name)||Ze.name.startsWith(".")||Ze.isDirectory()&&(Le.value++,ze(Q.join(H,Ze.name),Le,tn+1))}return Le.value},pt=(H,Le)=>l?.indentationTree!==!1?Xi(H,Le,1,ot,je):Qi(H,Le,"",1,ot,je),Bt=ze(process.cwd()),mt=12;Bt>3072?mt=1:Bt>2304?mt=2:Bt>1536?mt=3:Bt>768?mt=4:Bt>384?mt=6:Bt>192?mt=7:Bt>96?mt=8:Bt>48?mt=9:Bt>24&&(mt=10);let gt=J(Qo,{}),Tt=gt[d],ct=Tt?Tt!==process.cwd():!1;gt[d]=process.cwd(),pe(Qo,gt);let _e=J(x,{}),ie=_e[d]||{summary:"",historyLength:0};typeof ie=="string"&&(ie={summary:ie,historyLength:0});let Vt=n.filter(H=>(H.role==="user"||H.role==="agent"||H.role==="system")&&!String(H.id).startsWith("welcome")&&!H.isMeta).length;ie.historyLength&&Vt<ie.historyLength&&(ie.summary="",ie.historyLength=0,_e[d]=ie,pe(x,_e));let Xn=typeof ie=="object"?ie.summary||"":ie||"",Jn=k.length>0;Jn&&Xn&&k[0]&&(k[0].role==="user"||k[0].role==="system")&&(k[0].text.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")||(k[0].text=`[SYSTEM METADATA]
570
+ Provide a consolidated summary of the entire session.`,m=ve("gemma_janitor_fallback_google");s==="OpenRouter"&&(m=ve("janitor_open_router")),s==="DeepSeek"&&(m=ve("deepseek_level_1")),s==="Mistral"&&(m=ve("mistral_level_1")),s==="NVIDIA"&&(m=ve("nvidia_chat_summarizer_fallback")),s==="CrofAI"&&(m=ve("crofai_fallback")),s==="InferX"&&(m=ve("inferx_fallback")),s==="SenseNova"&&(m=ve("sensenova_fallback"));let w=0,b=!1,x=null;for(;w<=3&&!b;){w++;try{x=await jo(e,m,y,g,"Fast"),b=!0}catch{if(w>3){if(s==="Google")try{let R=ve("general_fallback");return(await jo(e,R,y,g,"Fast")).text||""}catch{return""}return""}}}return x&&x.text||""},h=a(n),d=J(r,{}),c=d[o]||{summary:"",historyLength:0};typeof c=="string"&&(c={summary:c,historyLength:0});let l=c.summary||"",f=await i(h,l);if(f){c.summary=f;let u=Ec(n);return t?c.historyLength=(c.historyLength||0)+u:c.historyLength=u,d[o]=c,pe(r,d),f}return null},Cm=e=>{try{let n=Q.join(xo,"chat-summaries.json");if(De.existsSync(n)){let t=J(n,{});t[e]&&(delete t[e],pe(n,t))}}catch{}},Mm=async function*(e,n,t,o,s){let{profile:r,thinkingLevel:a,mode:i,janitorModel:h,chatId:d,isPlayground:c,systemSettings:l,sessionStats:f,aiProvider:u="Google",apiTier:p,wildcardTooling:g}=t,y=zt(e);if(!ei&&u==="Google")throw new Error("AI not initialized");let m=process.env.NVIDIA_BASE_URL||t?.aiProvider==="Ollama"||t?.aiProvider==="CrofAI"||t?.aiProvider==="InferX"||t?.aiProvider==="SenseNova"?!1:l?.memory!==!1,w=n[n.length-1].text,b=Q.join(xo,"chat-summaries.json"),x=!1,E=n.filter(_=>_.role==="user").length===1,R=w.includes("[TITLE-UPDATE]"),S=E||R,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 pt.startTransaction(d,T),l?.advanceRollback&&await Kn.takeInitialSnapshot(d),Dt=!1;let $=null;try{let _=new AbortController;$=setInterval(()=>{Dt&&(_.abort(),$&&(clearInterval($),$=null))},400);let k=[...n.slice(0,-1)];{let Le=J(b,{})[d]||{summary:"",historyLength:0};if(Le.summary&&Le.historyLength>0){let nn=0,Ce=[];for(let Ze=0;Ze<k.length;Ze++){let He=k[Ze];(He.role==="user"||He.role==="agent"||He.role==="system")&&!String(He.id).startsWith("welcome")&&!He.isMeta&&nn++,nn>Le.historyLength&&Ce.push(He)}k=Ce}}k=k.map(H=>{if(H.role==="user"&&H.text){let Le=H.text.match(/\[USER\]([\s\S]*?)\[\/USER\]/);if(Le)return{...H,text:Le[1].trim()}}return{...H}});let C=process.env.HIGH_CONTEXT,I=255e3,D=26e4;if(C&&C!=="false"){let H=parseInt(C,10);!isNaN(H)&&H>=256e3&&H<=1e6&&(D=H,I=Math.round(H*.85))}if((u==="NVIDIA"&&(e?.includes("gpt")||e?.includes("qwen")||e?.includes("medium")||e.includes("muse"))||u==="Mistral")&&(I=122e3,D=126e3),u!=="Ollama"&&(f?.tokens||0)>I&&(yield{type:"status_history",content:"Context Limit Reached. Condensing session history..."},await Lc(t,k,!0)&&(k=[],x=!0)),E&&m){let H=J(tn,{});Object.values(H).flat().length>5&&(yield{type:"status",content:"Condensing past chat memories"},await Oc(d,t,H))}let B=J(tn,{}),N=J(An,{}),Y=Object.entries(B).filter(([H])=>H!==d).flatMap(([H,Le])=>Le),Ie=[...Object.entries(N).filter(([H])=>H!==d).slice(-20).map(([H,Le])=>`[Chat Summary]: ${Le}`),...Y].map(H=>`- ${H}`).join(`
571
+ `),j=J(Ft,[]).map(H=>`- ${H.memory}`).join(`
572
+ `),ae=(f?.tokens||0)>=1e4,_e=_i(Ie,j,m,ae),A=new Date,F=A.getFullYear(),V=A.toLocaleString("en-US",{month:"short"}).toUpperCase(),X=String(A.getDate()).padStart(2,"0"),Ue=A.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}),Ne=`${F}-${V}-${X}, ${Ue}`,je=[".git","node_modules",".gemini","dist","build",".next","out",".cache","bin","obj","vendor","venv",".idea",".gradle",".terraform","target","coverage",".vscode",".svn",".hg",".fslckout",".github",".gitlab",".circleci",".gitea",".gitee",".lerna",".changeset",".nx",".npm",".yarn",".pnpm-store",".pnpm",".expo",".nuxt",".svelte-kit",".docusaurus",".turbo",".vercel","bower_components",".netlify",".vuepress",".quasar",".output",".angular","jspm_packages",".parcel-cache",".rollup.cache",".rspack",".vitepress","__pycache__",".pytest_cache",".mypy_cache",".tox",".poetry","env","vhdl",".ipynb_checkpoints",".jupyter",".conda",".pdm-build",".bundle",".yardoc",".metadata","App_Data","ClientBin",".cargo",".rustc_info",".go","Godeps","_vendor",".rake_tasks","CMakefiles",".wakatime",".dart_tool",".fvm",".cocoapods","Pods",".pub-cache",".symlinks","DerivedData",".xcworkspace",".serverless",".aws",".gcloud",".azure",".kube",".vagrant",".docker","postgres-data","redis-data","mongo-data",".Spotlight-V100",".Trashes","$RECYCLE.BIN","System Volume Information",".DocumentRevisions-V100",".fseventsd","AppData","Application Data","Local","LocalLow","Roaming","$WinREAgent","$WINDOWS.~BT","$WINDOWS.~WS","scw","System32","SysWOW64",".AppleDouble",".AppleDB",".AppleDesktop","_CodeSignature",".cmio",".LSOverride",".localized",".TemporaryItems",".Trash",".Trash-0",".Trash-1000",".gvfs",".local",".config",".dbus",".fontconfig",".snap",".var",".lost+found","lost+found",".thumb",".thumbnails","EFI","boot","grub","logs","log",".nyc_output",".sonar",".ruff_cache",".VSCodeCounter"],ot=H=>{try{return De.readdirSync(H,{withFileTypes:!0})}catch{return[]}},ze=(H,Le={value:0},nn=1)=>{if(Le.value>6200||nn>7)return Le.value;let Ce=ot(H);for(let Ze of Ce){if(Le.value>6200)break;je.includes(Ze.name)||Ze.name.startsWith(".")||Ze.isDirectory()&&(Le.value++,ze(Q.join(H,Ze.name),Le,nn+1))}return Le.value},mt=(H,Le)=>l?.indentationTree!==!1?Vr(H,Le,1,ot,je):Jr(H,Le,"",1,ot,je),Ut=ze(process.cwd()),gt=12;Ut>3072?gt=1:Ut>2304?gt=2:Ut>1536?gt=3:Ut>768?gt=4:Ut>384?gt=6:Ut>192?gt=7:Ut>96?gt=8:Ut>48?gt=9:Ut>24&&(gt=10);let yt=J(Jo,{}),Rt=yt[d],dt=Rt?Rt!==process.cwd():!1;yt[d]=process.cwd(),pe(Jo,yt);let $e=J(b,{}),re=$e[d]||{summary:"",historyLength:0};typeof re=="string"&&(re={summary:re,historyLength:0});let Vt=n.filter(H=>(H.role==="user"||H.role==="agent"||H.role==="system")&&!String(H.id).startsWith("welcome")&&!H.isMeta).length;re.historyLength&&Vt<re.historyLength&&(re.summary="",re.historyLength=0,$e[d]=re,pe(b,$e));let Xn=typeof re=="object"?re.summary||"":re||"",Jn=k.length>0;Jn&&Xn&&k[0]&&(k[0].role==="user"||k[0].role==="system")&&(k[0].text.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")||(k[0].text=`[SYSTEM METADATA]
573
573
  **CONTEXT SUMMARY OF PREVIOUS TURNS (PRIORITY: DYNAMIC)**
574
574
  ${Xn}
575
575
 
576
- [USER] ${k[0].text}`,yield{type:"summary_injected",content:{id:k[0].id,text:k[0].text}}));let dr=Xn&&!Jn?`
576
+ [USER] ${k[0].text}`,yield{type:"summary_injected",content:{id:k[0].id,text:k[0].text}}));let ci=Xn&&!Jn?`
577
577
  [SYSTEM METADATA]
578
578
  **CONTEXT SUMMARY OF PREVIOUS TURNS**
579
579
  ${Xn}
580
- `:"",fr=!!l?.dynamicDirAwareness,Na=`${d}|${u}|${a}|${e}|${i}|${fr}`,ur=!fr&&ws.key===Na&&ws.value?"":`
580
+ `:"",di=!!l?.dynamicDirAwareness,Fa=`${d}|${u}|${a}|${e}|${r}|${di}`,fi=!di&&ys.key===Fa&&ys.value?"":`
581
581
  **Directory Structure**
582
582
  CWD: `+process.cwd()+`${c?" [PLAYGROUND MODE]":""}
583
- `+pt(process.cwd(),mt),bt=await gs(),Fn="";if(Wo()&&bt.file_focused!=="none"){Fn=`
583
+ `+mt(process.cwd(),gt),kt=await ms(),Pn="";if(Uo()&&kt.file_focused!=="none"){Pn=`
584
584
  [Additional IDE Context]
585
- `;let H=Q.relative(process.cwd(),bt.file_focused),Le=(bt.opened_editors||[]).map($e=>{let Ze=Q.relative(process.cwd(),$e);return Ze.startsWith("..")?`[External] ${Q.basename($e)}`:Ze});if(Fn+=`Focused File: ${H}
586
- Cursor Line: ${bt.cursor_line}
587
- `,bt.selected){let $e=bt.selected,Ze=$e.split(`
588
- `);Ze.length>256&&($e=Ze.slice(0,240).join(`
585
+ `;let H=Q.relative(process.cwd(),kt.file_focused),Le=(kt.opened_editors||[]).map(Ce=>{let Ze=Q.relative(process.cwd(),Ce);return Ze.startsWith("..")?`[External] ${Q.basename(Ce)}`:Ze});if(Pn+=`Focused File: ${H}
586
+ Cursor Line: ${kt.cursor_line}
587
+ `,kt.selected){let Ce=kt.selected,Ze=Ce.split(`
588
+ `);Ze.length>256&&(Ce=Ze.slice(0,240).join(`
589
589
  `)+`
590
590
  ... [truncated] ...
591
591
  `+Ze.slice(-16).join(`
592
- `)),$e.length>2048&&($e=$e.slice(0,1920)+`
592
+ `)),Ce.length>2048&&(Ce=Ce.slice(0,1920)+`
593
593
  ... [truncated] ...
594
- `+$e.slice(-128)),Fn+=`Current Selection: "${$e}"
595
- `}if(bt.manual_edits){let Ze=bt.manual_edits.split(`
596
- `),He=[],Je=null;for(let q of Ze)q.trim()&&(q.startsWith(" Line ")?Je&&Je.edits.push(q):(Je={path:q.endsWith(":")?q.slice(0,-1):q,edits:[]},He.push(Je)));for(let q of He)q.edits.length>80&&(q.edits=q.edits.slice(-80)),q.originalEditsCount=q.edits.length;let de=(q,Z)=>Z.reduce((Ge,cn)=>{let wn=bt.file_focused&&(cn.path===bt.file_focused||Q.resolve(process.cwd(),cn.path)===Q.resolve(bt.file_focused))?Math.ceil(q*1.2):q;return Ge+Math.min(cn.edits.length,wn)},0),Ut=80;if(de(80,He)>300){let q=!1;for(let Z=80;Z>=10;Z--)if(de(Z,He)<=300){Ut=Z,q=!0;break}q||(Ut=10)}let Qe=[...He];if(Ut===10&&de(10,Qe)>500)for(;Qe.length>0&&de(10,Qe)>500;){let q=0,Z=Qe[0].originalEditsCount;for(let Ge=1;Ge<Qe.length;Ge++)Qe[Ge].originalEditsCount<Z&&(Z=Qe[Ge].originalEditsCount,q=Ge);Qe.splice(q,1)}for(let q of Qe){let Ge=bt.file_focused&&(q.path===bt.file_focused||Q.resolve(process.cwd(),q.path)===Q.resolve(bt.file_focused))?Math.ceil(Ut*1.2):Ut;q.edits.length>Ge&&(q.edits=q.edits.slice(-Ge))}for(let q of Qe){let Z=`${q.path}:
594
+ `+Ce.slice(-128)),Pn+=`Current Selection: "${Ce}"
595
+ `}if(kt.manual_edits){let Ze=kt.manual_edits.split(`
596
+ `),He=[],Je=null;for(let q of Ze)q.trim()&&(q.startsWith(" Line ")?Je&&Je.edits.push(q):(Je={path:q.endsWith(":")?q.slice(0,-1):q,edits:[]},He.push(Je)));for(let q of He)q.edits.length>80&&(q.edits=q.edits.slice(-80)),q.originalEditsCount=q.edits.length;let de=(q,Z)=>Z.reduce((Ge,cn)=>{let wn=kt.file_focused&&(cn.path===kt.file_focused||Q.resolve(process.cwd(),cn.path)===Q.resolve(kt.file_focused))?Math.ceil(q*1.2):q;return Ge+Math.min(cn.edits.length,wn)},0),Wt=80;if(de(80,He)>300){let q=!1;for(let Z=80;Z>=10;Z--)if(de(Z,He)<=300){Wt=Z,q=!0;break}q||(Wt=10)}let Qe=[...He];if(Wt===10&&de(10,Qe)>500)for(;Qe.length>0&&de(10,Qe)>500;){let q=0,Z=Qe[0].originalEditsCount;for(let Ge=1;Ge<Qe.length;Ge++)Qe[Ge].originalEditsCount<Z&&(Z=Qe[Ge].originalEditsCount,q=Ge);Qe.splice(q,1)}for(let q of Qe){let Ge=kt.file_focused&&(q.path===kt.file_focused||Q.resolve(process.cwd(),q.path)===Q.resolve(kt.file_focused))?Math.ceil(Wt*1.2):Wt;q.edits.length>Ge&&(q.edits=q.edits.slice(-Ge))}for(let q of Qe){let Z=`${q.path}:
597
597
  ${q.edits.join(`
598
598
  `)}`;for(;q.edits.length>0&&Z.length>4*768;)q.edits.shift(),Z=`${q.path}:
599
599
  ${q.edits.join(`
600
- `)}`;Z.length>4*768?q.stringRepresentation="... "+Z.slice(-(4*768-4)):q.stringRepresentation=Z}let nn=Qe.map(q=>q.stringRepresentation).join(`
601
- `);for(;Qe.length>0&&nn.length>4*2048;){Qe[0].edits.length>0?Qe[0].edits.shift():Qe.shift();for(let q of Qe){let Z=`${q.path}:
600
+ `)}`;Z.length>4*768?q.stringRepresentation="... "+Z.slice(-(4*768-4)):q.stringRepresentation=Z}let sn=Qe.map(q=>q.stringRepresentation).join(`
601
+ `);for(;Qe.length>0&&sn.length>4*2048;){Qe[0].edits.length>0?Qe[0].edits.shift():Qe.shift();for(let q of Qe){let Z=`${q.path}:
602
602
  ${q.edits.join(`
603
- `)}`;Z.length>4*768?q.stringRepresentation="... "+Z.slice(-(4*768-4)):q.stringRepresentation=Z}nn=Qe.map(q=>q.stringRepresentation).join(`
604
- `)}nn.length>4*2048&&(nn="... "+nn.slice(-(4*2048-4))),Fn+=`Recent Manual Edits:
605
- ${nn}
606
- `}Le.length>0&&(Fn+=`All Opened Editors: ${Le.join(", ")}`),bt.diagnostics&&(Fn+=`
603
+ `)}`;Z.length>4*768?q.stringRepresentation="... "+Z.slice(-(4*768-4)):q.stringRepresentation=Z}sn=Qe.map(q=>q.stringRepresentation).join(`
604
+ `)}sn.length>4*2048&&(sn="... "+sn.slice(-(4*2048-4))),Pn+=`Recent Manual Edits:
605
+ ${sn}
606
+ `}Le.length>0&&(Pn+=`All Opened Editors: ${Le.join(", ")}`),kt.diagnostics&&(Pn+=`
607
607
  **Active File Errors**:
608
- ${bt.diagnostics}
609
- `),(T.toLowerCase().includes("lint")||T.toLowerCase().includes("warning"))&&bt.warnings&&(Fn+=`
608
+ ${kt.diagnostics}
609
+ `),(T.toLowerCase().includes("lint")||T.toLowerCase().includes("warning"))&&kt.warnings&&(Pn+=`
610
610
  **Lint Warnings**:
611
- ${bt.warnings}
612
- `)}let hr=T.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),pr=/(?:\\)?@\[([^\]]+)\]/g,qo,zo=[];for(pr.lastIndex=0;(qo=pr.exec(hr))!==null;){let H=qo[0].startsWith("\\");zo.push({tag:qo[1],isEscaped:H})}let Ko=[],mo=null;for(let H=0;H<zo.length;H++){let{tag:Le,isEscaped:tn}=zo[H];if(!tn)try{let $e=Le.trim().replace(/^["']|["']$/g,""),Ze=/[:#]L?(\d+)(?:-L?(\d+))?$/i,He=$e.match(Ze),Je=$e,de=null,Ut=null;He&&(de=parseInt(He[1],10),Ut=He[2]?parseInt(He[2],10):de,Je=$e.slice(0,He.index));let Qe=Q.resolve(process.cwd(),Je);if(De.existsSync(Qe)&&De.statSync(Qe).isFile()){let q=Je.toLowerCase(),Z=q.endsWith(".pdf"),Ge=q.endsWith(".docx")||q.endsWith(".doc")||q.endsWith(".ppt")||q.endsWith(".pptx")||q.endsWith(".xls")||q.endsWith(".xlsx"),cn=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(q),Wt=cn||Z||Ge,wn=u==="Google"||zt(e);if(Wt&&!wn){let We=`\u2718 Unsupported Modality: ${Q.basename(Je)}`,Se=115;process.stdout.isTTY&&(Se=process.stdout.columns-5||120);let nt=[We],Nn=Math.max(...nt.map(_n=>_n.length)),Bn=Math.min(Nn+4,Se),es=nt.map(_n=>`${_n.padEnd(Bn-2).substring(0,Bn-2)}`).join(`
611
+ ${kt.warnings}
612
+ `)}let ui=T.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),hi=/(?:\\)?@\[([^\]]+)\]/g,Go,qo=[];for(hi.lastIndex=0;(Go=hi.exec(ui))!==null;){let H=Go[0].startsWith("\\");qo.push({tag:Go[1],isEscaped:H})}let zo=[],po=null;for(let H=0;H<qo.length;H++){let{tag:Le,isEscaped:nn}=qo[H];if(!nn)try{let Ce=Le.trim().replace(/^["']|["']$/g,""),Ze=/[:#]L?(\d+)(?:-L?(\d+))?$/i,He=Ce.match(Ze),Je=Ce,de=null,Wt=null;He&&(de=parseInt(He[1],10),Wt=He[2]?parseInt(He[2],10):de,Je=Ce.slice(0,He.index));let Qe=Q.resolve(process.cwd(),Je);if(De.existsSync(Qe)&&De.statSync(Qe).isFile()){let q=Je.toLowerCase(),Z=q.endsWith(".pdf"),Ge=q.endsWith(".docx")||q.endsWith(".doc")||q.endsWith(".ppt")||q.endsWith(".pptx")||q.endsWith(".xls")||q.endsWith(".xlsx"),cn=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(q),jt=cn||Z||Ge,wn=u==="Google"||zt(e);if(jt&&!wn){let We=`\u2718 Unsupported Modality: ${Q.basename(Je)}`,Se=115;process.stdout.isTTY&&(Se=process.stdout.columns-5||120);let nt=[We],Fn=Math.max(...nt.map(En=>En.length)),Nn=Math.min(Fn+4,Se),es=nt.map(En=>`${En.padEnd(Nn-2).substring(0,Nn-2)}`).join(`
613
613
  `);yield{type:"visual_feedback",content:gn(`${es}
614
- `)};continue}if(de===null&&!Wt){let We=0;try{We=De.readFileSync(Qe,"utf8").split(/\r\n|\r|\n/).length}catch{}if(We>300){let Se=`\u21B7 Skipped (Too Large): ${Q.basename(Je)}`,nt=115;process.stdout.isTTY&&(nt=process.stdout.columns-5||120);let Nn=Math.min(Se.length+4,nt),Bn=Se.padEnd(Nn-2).substring(0,Nn-2);yield{type:"visual_feedback",content:gn(`${Bn}
615
- `)};continue}}let En=de!==null?de:1,Qn=Ut!==null?Ut:de!==null?de:En+299;Qn-En>300&&(Qn=En+300);let yo=`path=${JSON.stringify(Je)}, startLine=${En}, endLine=${Qn}`,tt=await Zs(yo,{isMultiModal:wn}),Ke=!1,jt="",Zn=null;if(typeof tt=="string"?tt.trim().startsWith("ERROR")?Ke=!0:jt=tt:tt&&typeof tt=="object"&&tt.binaryPart?(Zn=tt.binaryPart,jt=tt.text||""):Ke=!0,!Ke){let We="";if(cn?(We=`\u2714 Processed: ${Q.basename(Je)}`,mo=Zn):Z||Ge?(We=`\u2714 Auto-Analysed: ${Q.basename(Je)}`,mo=Zn):(We=`\u2714 Auto-Read: ${Q.basename(Je)}`,Ko.push(jt)),We){let Se=115;process.stdout.isTTY&&(Se=process.stdout.columns-5||120);let nt=[We],Nn=Math.max(...nt.map(_n=>_n.length)),Bn=Math.min(Nn+4,Se),es=nt.map(_n=>`${_n.padEnd(Bn-2).substring(0,Bn-2)}`).join(`
614
+ `)};continue}if(de===null&&!jt){let We=0;try{We=De.readFileSync(Qe,"utf8").split(/\r\n|\r|\n/).length}catch{}if(We>300){let Se=`\u21B7 Skipped (Too Large): ${Q.basename(Je)}`,nt=115;process.stdout.isTTY&&(nt=process.stdout.columns-5||120);let Fn=Math.min(Se.length+4,nt),Nn=Se.padEnd(Fn-2).substring(0,Fn-2);yield{type:"visual_feedback",content:gn(`${Nn}
615
+ `)};continue}}let Rn=de!==null?de:1,Qn=Wt!==null?Wt:de!==null?de:Rn+299;Qn-Rn>300&&(Qn=Rn+300);let go=`path=${JSON.stringify(Je)}, startLine=${Rn}, endLine=${Qn}`,tt=await Qs(go,{isMultiModal:wn}),Ke=!1,Ht="",Zn=null;if(typeof tt=="string"?tt.trim().startsWith("ERROR")?Ke=!0:Ht=tt:tt&&typeof tt=="object"&&tt.binaryPart?(Zn=tt.binaryPart,Ht=tt.text||""):Ke=!0,!Ke){let We="";if(cn?(We=`\u2714 Processed: ${Q.basename(Je)}`,po=Zn):Z||Ge?(We=`\u2714 Auto-Analysed: ${Q.basename(Je)}`,po=Zn):(We=`\u2714 Auto-Read: ${Q.basename(Je)}`,zo.push(Ht)),We){let Se=115;process.stdout.isTTY&&(Se=process.stdout.columns-5||120);let nt=[We],Fn=Math.max(...nt.map(En=>En.length)),Nn=Math.min(Fn+4,Se),es=nt.map(En=>`${En.padEnd(Nn-2).substring(0,Nn-2)}`).join(`
616
616
  `);yield{type:"visual_feedback",content:gn(`${es}
617
- `)}}}}}catch{}}let mr="";Ko.length>0&&(mr=`[Tagged File Contents] Auto Read User Tagged files by System, No need to re-read
618
- `+Ko.join(`
617
+ `)}}}}}catch{}}let pi="";zo.length>0&&(pi=`[Tagged File Contents] Auto Read User Tagged files by System, No need to re-read
618
+ `+zo.join(`
619
619
 
620
620
  `)+`
621
621
  [Tagged File Contents]
622
- `);let Ba=hr.replace(/\\(@\[[^\]]+\])/g,"$1"),Ua=g?`You cannot execute tools
622
+ `);let Na=ui.replace(/\\(@\[[^\]]+\])/g,"$1"),Ba=g?`You cannot execute tools
623
623
  Instead, output in chat the exact string you WOULD have produced & wait for system response
624
- `:"",gr=`[System Metadata]
625
- Time: ${Ne}${l?.dynamicDirAwareness?ur:""}${ct?`
626
- WARNING: CWD Changed from previous: "${Tt}" to current: "${process.cwd()}", write change in chat to avoid future path mismatches
627
- `:""}${Ee}${Fn}
624
+ `:"",Ua=process.env.forcedReasoning||!1,mi=`[System Metadata]
625
+ Time: ${Ne}${l?.dynamicDirAwareness?fi:""}${dt?`
626
+ WARNING: CWD Changed from previous: "${Rt}" to current: "${process.cwd()}", write change in chat to avoid future path mismatches
627
+ `:""}${_e}${Pn}
628
628
  [/Metadata]
629
- ${dr}${a!=="Fast"&&(u==="Mistral"&&!zs(e)||a!=="xHigh"&&u==="Google")?`${u==="Mistral"&&!zs(e)||e.toLowerCase().startsWith("gemma")?`[system] strictly follow thinking policy as high priority. do not start a response without <think>...</think> [/system]
629
+ ${ci}${a!=="Fast"&&(u==="Mistral"&&!qs(e)||a!=="xHigh"&&u==="Google")?`${u==="Mistral"&&!qs(e)||e.toLowerCase().startsWith("gemma")||Ua?`[system] strictly follow thinking policy as high priority. do not start a response without <think>...</think> [/system]
630
630
  `:""}`:""}[system] exact structured string '[tool:functions.toolname(arg="value")]' in chat response [/system]
631
- ${mr}${Ua}[user prompt] ${Ba.trim()} [/user prompt]`.trim(),yr={role:"user",text:gr};mo&&(yr.binaryPart=mo),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(yr),dr&&n[n.length-1]?.id&&(yield{type:"summary_injected",content:{id:n[n.length-1].id,text:gr}});let Rn=null,Us=r==="Flux"?100:10;Us=r.toLowerCase().includes("cu")?250:Us;let yn=16;yield{type:"status",content:"Connecting"},Ot=!1;let wr=[],go=!1;for(let H=0;H<=Us;H++){let Le=await li("agent",t);if(!Le.allowed)throw new Error(Le.reason||`Budget Exhausted for Provider (${u||"Agent"})`);let tn=[];if(go=!1,r==="ICU"||r==="FluxCU")try{yield{type:"status",content:"Capturing Screen"},await new Promise(Ce=>setTimeout(Ce,1e3));let he=await br();if(he&&he.base64){let Ce="[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]",se={inlineData:{mimeType:he.mimeType,data:he.base64}};for(let st of k)Array.isArray(st.parts)&&(st.parts=st.parts.filter(Ct=>!Ct.inlineData));if(k.length>0&&k[k.length-1].role==="user"){let st=k[k.length-1];typeof st.text=="string"&&(st.text+=`
631
+ ${pi}${Ba}[user prompt] ${Na.trim()} [/user prompt]`.trim(),gi={role:"user",text:mi};po&&(gi.binaryPart=po),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(gi),ci&&n[n.length-1]?.id&&(yield{type:"summary_injected",content:{id:n[n.length-1].id,text:mi}});let Tn=null,Bs=i==="Flux"?100:10;Bs=i.toLowerCase().includes("cu")?250:Bs;let yn=16;yield{type:"status",content:"Connecting"},Dt=!1;let yi=[],mo=!1;for(let H=0;H<=Bs;H++){let Le=await ar("agent",t);if(!Le.allowed)throw new Error(Le.reason||`Budget Exhausted for Provider (${u||"Agent"})`);let nn=[];if(mo=!1,i==="ICU"||i==="FluxCU")try{yield{type:"status",content:"Capturing Screen"},await new Promise(Re=>setTimeout(Re,1e3));let he=await xi();if(he&&he.base64){let Re="[system] Fresh Gridded Screen Feedback Captured. Use numeric coordinates. Old screenshots will be removed when new screenshot is captured, summarize in text if context is needed later [/system]",se={inlineData:{mimeType:he.mimeType,data:he.base64}};for(let st of k)Array.isArray(st.parts)&&(st.parts=st.parts.filter(At=>!At.inlineData));if(k.length>0&&k[k.length-1].role==="user"){let st=k[k.length-1];typeof st.text=="string"&&(st.text+=`
632
632
 
633
- ${Ce}`,Array.isArray(st.parts)||(st.parts=[{text:st.text}]),st.parts.push(se))}else k.push({role:"user",text:Ce,parts:[{text:Ce},se]})}}catch(he){console.error("Vision screenshot capture error:",he)}if(l?.compression===0&&(f?.tokens||0)>D&&(k=Ir(k,6)),H>0?yield{type:"status",content:"Working"}:yield{type:"status",content:"Connecting"},Ot){try{let{clearPendingNudges:he}=await import("./subagent_state-LZCOZSUJ.js");he()}catch{}yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
633
+ ${Re}`,Array.isArray(st.parts)||(st.parts=[{text:st.text}]),st.parts.push(se))}else k.push({role:"user",text:Re,parts:[{text:Re},se]})}}catch(he){console.error("Vision screenshot capture error:",he)}if(l?.compression===0&&(f?.tokens||0)>D&&(k=vi(k,6)),H>0?yield{type:"status",content:"Working"}:yield{type:"status",content:"Connecting"},Dt){try{let{clearPendingNudges:he}=await import("./subagent_state-LZCOZSUJ.js");he()}catch{}yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
634
634
 
635
- \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}try{let{consumePendingNudges:he}=await import("./subagent_state-LZCOZSUJ.js"),Ce=he();if(Ce&&Ce.length>0){let se=Ce.join(`
635
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}try{let{consumePendingNudges:he}=await import("./subagent_state-LZCOZSUJ.js"),Re=he();if(Re&&Re.length>0){let se=Re.join(`
636
636
 
637
637
  `);k.length>0&&k[k.length-1].role==="user"?k[k.length-1].text+=`
638
638
 
@@ -642,113 +642,113 @@ ${se}`:k.push({role:"user",text:se}),yield{type:"status",content:"Subagent Updat
642
642
  [question] ${he.replace("/btw","").trim()} [/question]`:k.push({role:"user",text:`[system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
643
643
  [question] ${he.replace("/btw","").trim()} [/question]`}):k.length>0&&k[k.length-1].role==="user"?k[k.length-1].text+=`
644
644
 
645
- [STEERING HINT from USER, HIGH PRIORITY] ${he.trim().toUpperCase()} [/STEERING HINT]`:k.push({role:"user",text:`[STEERING HINT from USER, HIGH PRIORITY] ${he.trim().toUpperCase()} [/STEERING HINT]`}),yield{type:"status",content:`${he.startsWith("/btw")?"Question Forwarded...":"Steering Hint Injected..."}`})}let $e,Ze=!1,He=1,Je=1,de="",Ut=null,Qe=null,nn=null,q=0,Z=[],Ge=0,cn=!1,Wt=!1,wn=!1,En=!1,Qn=!0,yo=0,tt="",Ke="",jt=!1,Zn=!1,We=!0,Se=e,nt="";for(;He<=yn&&Je<=yn&&!Ze&&!Ot;){let he=!1;try{de="",Qn&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},Qn=!1,Je===1&&(tt=""));let Ce=P=>{if(!P||!P.includes("[tool:"))return P;let te="___THINK_OPEN_TAG___",W="___THINK_CLOSE_TAG___";P=P.replace("<think>",te).replace("</think>",W),P=P.replace(Sc,(me,fe)=>fe.includes("[tool:")?fe.trim():me);let G="",Te=0;for(;Te<P.length;){let me=P.indexOf("[tool:",Te);if(me===-1){G+=P.substring(Te).replace(Aa,"").replace(va,"");break}let fe=P.substring(Te,me);G+=fe.replace(Aa,"").replace(va,"");let Rt=P.indexOf("]",me);if(Rt===-1){G+=P.substring(me);break}G+=P.substring(me,Rt+1),Te=Rt+1}return P=G,P=P.replaceAll(te,"<think>").replaceAll(W,"</think>"),P},se=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,W)=>{let G=P.text||"";m||(G=G.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),P.role==="agent"&&(G=Ce(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 Te=[];return Array.isArray(P.parts)&&P.parts.length>0?Te=P.parts.map(me=>{if(me.text){let fe=me.text;return m||(fe=fe.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),P.role==="agent"&&(fe=Ce(fe),fe=fe.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),fe=fe.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*")),{text:fe}}return me}):Te=[{text:G}],P.binaryPart&&zt(Se)&&W.slice(te+1).filter(fe=>fe.role==="user"&&!fe.text?.startsWith("[TOOL RESULT]")).length<=2&&Te.push(P.binaryPart),{role:P.role==="user"||P.role==="system"?"user":"model",parts:Te}});for(let P=0;P<se.length;P++){let te=se[P],W=te.parts?.[0]?.text||"";if(te.role==="model"&&/\[tool:/i.test(W)){let G=-1;for(let Te=P+1;Te<se.length;Te++){let me=se[Te],fe=me.parts?.[0]?.text||"";if(me.role==="user"&&fe.startsWith("[TOOL RESULT]")){G=Te;break}}if(G!==-1&&G!==P+1){let[Te]=se.splice(G,1);se.splice(P+1,0,Te)}}}for(let P=se.length-2;P>=0;P--){let te=se[P],W=se[P+1];te.role==="user"&&W.role==="user"&&(W.parts?.[0]?.text||"").trim().startsWith("[SYSTEM")&&se.splice(P,1)}let st=[];for(let P=0;P<se.length;P++){let te=se[P];if(st.length===0)st.push(te);else{let W=st[st.length-1];W.role===te.role?(W.parts[0].text+=`
645
+ [STEERING HINT from USER, HIGH PRIORITY] ${he.trim().toUpperCase()} [/STEERING HINT]`:k.push({role:"user",text:`[STEERING HINT from USER, HIGH PRIORITY] ${he.trim().toUpperCase()} [/STEERING HINT]`}),yield{type:"status",content:`${he.startsWith("/btw")?"Question Forwarded...":"Steering Hint Injected..."}`})}let Ce,Ze=!1,He=1,Je=1,de="",Wt=null,Qe=null,sn=null,q=0,Z=[],Ge=0,cn=!1,jt=!1,wn=!1,Rn=!1,Qn=!0,go=0,tt="",Ke="",Ht=!1,Zn=!1,We=!0,Se=e,nt="";for(;He<=yn&&Je<=yn&&!Ze&&!Dt;){let he=!1;try{de="",Qn&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},Qn=!1,Je===1&&(tt=""));let Re=P=>{if(!P||!P.includes("[tool:"))return P;let te="___THINK_OPEN_TAG___",W="___THINK_CLOSE_TAG___";P=P.replace("<think>",te).replace("</think>",W),P=P.replace(Tc,(me,fe)=>fe.includes("[tool:")?fe.trim():me);let G="",Te=0;for(;Te<P.length;){let me=P.indexOf("[tool:",Te);if(me===-1){G+=P.substring(Te).replace(Ma,"").replace(Aa,"");break}let fe=P.substring(Te,me);G+=fe.replace(Ma,"").replace(Aa,"");let _t=P.indexOf("]",me);if(_t===-1){G+=P.substring(me);break}G+=P.substring(me,_t+1),Te=_t+1}return P=G,P=P.replaceAll(te,"<think>").replaceAll(W,"</think>"),P},se=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,W)=>{let G=P.text||"";m||(G=G.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),P.role==="agent"&&(G=Re(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 Te=[];return Array.isArray(P.parts)&&P.parts.length>0?Te=P.parts.map(me=>{if(me.text){let fe=me.text;return m||(fe=fe.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),P.role==="agent"&&(fe=Re(fe),fe=fe.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),fe=fe.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*")),{text:fe}}return me}):Te=[{text:G}],P.binaryPart&&zt(Se)&&W.slice(te+1).filter(fe=>fe.role==="user"&&!fe.text?.startsWith("[TOOL RESULT]")).length<=2&&Te.push(P.binaryPart),{role:P.role==="user"||P.role==="system"?"user":"model",parts:Te}});for(let P=0;P<se.length;P++){let te=se[P],W=te.parts?.[0]?.text||"";if(te.role==="model"&&/\[tool:/i.test(W)){let G=-1;for(let Te=P+1;Te<se.length;Te++){let me=se[Te],fe=me.parts?.[0]?.text||"";if(me.role==="user"&&fe.startsWith("[TOOL RESULT]")){G=Te;break}}if(G!==-1&&G!==P+1){let[Te]=se.splice(G,1);se.splice(P+1,0,Te)}}}for(let P=se.length-2;P>=0;P--){let te=se[P],W=se[P+1];te.role==="user"&&W.role==="user"&&(W.parts?.[0]?.text||"").trim().startsWith("[SYSTEM")&&se.splice(P,1)}let st=[];for(let P=0;P<se.length;P++){let te=se[P];if(st.length===0)st.push(te);else{let W=st[st.length-1];W.role===te.role?(W.parts[0].text+=`
646
646
 
647
- `+(te.parts?.[0]?.text||""),te.parts?.length>1&&W.parts.push(...te.parts.slice(1))):st.push(te)}}se.length=0,se.push(...st),Se=e;let Ct=`${d}|${u}|${r}|${a}|${Se}|${JSON.stringify(i)}|${!!l?.dynamicDirAwareness}|${!!l?.subAgents}`;if(ws.key===Ct&&ws.value)nt=ws.value;else{let P=u==="Mistral"?!!zs(Se):!(Se||"gemma").toLowerCase().startsWith("gemma");nt=Cr(i,((Se||"gemma").toLowerCase().startsWith("gemma"),a),r,l,m,E,u,u==="Google"?!0:y,P,d),l?.dynamicDirAwareness||(nt+=`
648
- ${ur.replace(`
647
+ `+(te.parts?.[0]?.text||""),te.parts?.length>1&&W.parts.push(...te.parts.slice(1))):st.push(te)}}se.length=0,se.push(...st),Se=e;let At=`${d}|${u}|${i}|${a}|${Se}|${JSON.stringify(r)}|${!!l?.dynamicDirAwareness}|${!!l?.subAgents}`;if(ys.key===At&&ys.value)nt=ys.value;else{let P=u==="Mistral"?!!qs(Se):!(Se||"gemma").toLowerCase().startsWith("gemma");nt=$i(r,((Se||"gemma").toLowerCase().startsWith("gemma"),a),i,l,m,E,u,u==="Google"?!0:y,P,d),l?.dynamicDirAwareness||(nt+=`
648
+ ${fi.replace(`
649
649
  **Directory Structure**`,`
650
- **Directory Structure**`)}`),ws.key=Ct,ws.value=nt}let Mt=se[se.length-1];if(Wo()&H>0){await new Promise(W=>setTimeout(W,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+=`
650
+ **Directory Structure**`)}`),ys.key=At,ys.value=nt}let Et=se[se.length-1];if(Uo()&H>0){await new Promise(W=>setTimeout(W,2500)),yield{type:"status",content:"Verifying"};let P=await ms(),te=P?P.diagnostics:null;te&&Et&&Et.role==="user"&&Et.parts?.[0]?.text&&(Et.parts[0].text+=`
651
651
  ${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>**":"",W=`
652
- [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+=W)}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=`
652
+ [SYSTEM] Tool result received. Analyze output and proceed with your turn [/SYSTEM]`;Et&&Et.role==="user"&&Et.parts?.[0]?.text?.startsWith("[TOOL RESULT]")&&(Et.parts[0].text+=W)}if(l?.advanceRollback&&Et&&Et.role==="user"&&Et.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=`
653
653
  [system] File Changes:
654
654
  `;for(let G of P.newFiles)te+=`* ${G} (created)
655
655
  `;for(let G of P.modifiedFiles)te+=`* ${G} (modified)
656
656
  `;for(let G of P.deletedFiles)te+=`* ${G} (deleted)
657
- `;te+="[/system]",Mt.parts[0].text+=te;let W=-1;for(let G=k.length-1;G>=0;G--)if(k[G].role==="user"&&k[G].text?.startsWith("[TOOL RESULT]")){W=G;break}W!==-1&&(k[W].text+=te)}}catch{}let on=Math.floor(Us*(r==="Flux"?.98:.8)),Lt=H+1;Lt>=on&&Mt&&Mt.parts?.[0]&&(Mt.parts[0].text+=`
658
- [system] WARNING, Turn Limit Impending: Step ${Lt}/${Us}. Wrap up quickly/prompt user to continue. [/system]`);let Dt=new Promise((P,te)=>{_.signal.aborted&&te(new DOMException("The user aborted a request.","AbortError")),_.signal.addEventListener("abort",()=>{te(new DOMException("The user aborted a request.","AbortError"))})});Dt.catch(()=>{});let Ht=se;if(u==="Ollama")$e=Pa(t.apiKey,Se,Ht,nt,a,r,y,_.signal,1.05,l?.ollamaEndpoint||"Cloud");else if(u==="OpenRouter")$e=ir(t.apiKey,Se,Ht,nt,a,r,y,_.signal,1.05);else if(u==="DeepSeek")$e=nr(t.apiKey,Se,Ht,nt,a,r,y,_.signal,1.05);else if(u==="Mistral")$e=sr(t.apiKey,Se,Ht,nt,a,r,y,_.signal,1.05);else if(u==="NVIDIA"){let P=or(t.apiKey,Se,Ht,nt,a,r,y,_.signal,1.05);$e=_c(P,Se)}else if(u==="CrofAI")$e=rr(t.apiKey,Se,Ht,nt,a,r,y,_.signal,1.05);else if(u==="InferX")$e=ar(t.apiKey,Se,Ht,nt,a,r,y,_.signal,1.05);else if(u==="SenseNova")$e=lr(t.apiKey,Se,Ht,nt,a,r,y,_.signal,1.05);else{let te=cr(t?.apiKey).models.generateContentStream({model:Se||"gemini-3-flash-preview",contents:Ht,config:{systemInstruction:nt,mediaResolution:"MEDIA_RESOLUTION_HIGH",safetySettings:[{category:Vn.HARM_CATEGORY_HARASSMENT,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_HATE_SPEECH,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Yn.BLOCK_NONE}],temperature:1.05,thinkingConfig:(()=>{let W=(Se||"").toLowerCase(),G=W.includes("gemma-4")||W.startsWith("gemma"),Te=W.includes("gemini-3");if(G||Te)return G?a.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:lt.MINIMAL}:{includeThoughts:!0,thinkingLevel:lt.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:W.includes("pro")?lt.LOW:lt.MINIMAL,Low:lt.LOW,Medium:lt.MEDIUM,Standard:lt.MEDIUM,High:lt.HIGH,xHigh:lt.HIGH}[a]||lt.MEDIUM};{let me={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[a]||2048;return me===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:me}}})()}},{signal:_.signal});$e=await Promise.race([te,Dt])}de="",Ut=null,nn=null,Z=[],Ge=0,yield{type:"model_update",content:null},Ke="",jt=tt.length>0;let xn="",Yo=Date.now(),ss=async function*(){if(u==="Google"&&xn){let P=Ws(xn);for(let te of P)yield te;xn="",Yo=Date.now()}},xr=!0,os="",ks=!1,dt=null,Ws=P=>{let te=[],W=P;for(;W.length>0;)if(ks){let G=os+W;if(dt==="tool"||dt==="agent"){let fe=dt==="tool"?"[tool:functions.":"[agent:generalist.",Rt=dt==="tool"?"[tool":"[agent";if(!G.startsWith(Rt)||G.length>=fe.length&&!G.startsWith(fe)){te.push({type:"text",content:G}),os="",ks=!1,dt=null,W="";break}}let Te=-1,me="]";if(dt==="tool"||dt==="agent"){let fe=0,Rt=null,z=0,ge=!1;for(let Ye=0;Ye<G.length;Ye++){let M=G[Ye];if(Rt){if(M===Rt){let kt=0;for(let Pe=Ye-1;Pe>=0&&G[Pe]==="\\";Pe--)kt++;kt%2===0&&(Rt=null)}}else if(M==='"'||M==="'"||M==="`")Rt=M;else if(M==="(")fe++,ge=!0;else if(M===")")fe--;else if(M==="[")z++;else if(M==="]"){if(ge&&fe===0&&z===1){Te=Ye;break}z--}}}else dt==="end"?me="[[END]]":dt==="kimi_section"?me="<|tool_calls_section_end|>":dt==="kimi_call"&&(me="<|tool_call_end|>"),Te=G.indexOf(me);if(Te!==-1){let fe=me.length;if(!dt.startsWith("kimi")){let Rt=G.substring(0,Te+fe);te.push({type:"text",content:Rt})}os="",ks=!1,dt=null,W=G.substring(Te+fe)}else{let fe=dt.startsWith("kimi")?8192:512;G.length>fe?(dt.startsWith("kimi")||te.push({type:"text",content:G}),os="",ks=!1):os=G,W="";break}}else{let G=W.indexOf("[tool"),Te=W.indexOf("[agent"),me=W.indexOf("[[END]]"),fe=W.indexOf("<|tool_calls_section_begin|>"),Rt=W.indexOf("<|tool_call_begin|>"),z=[{type:"tool",idx:G,start:"[tool",end:"]"},{type:"agent",idx:Te,start:"[agent",end:"]"},{type:"end",idx:me,start:"[[END]]",end:"[[END]]"},{type:"kimi_section",idx:fe,start:"<|tool_calls_section_begin|>",end:"<|tool_calls_section_end|>"},{type:"kimi_call",idx:Rt,start:"<|tool_call_begin|>",end:"<|tool_call_end|>"}].filter(ge=>ge.idx!==-1).sort((ge,Ye)=>ge.idx-Ye.idx);if(z.length>0){let ge=z[0];ge.idx>0&&te.push({type:"text",content:W.substring(0,ge.idx)}),ks=!0,dt=ge.type,os="",W=W.substring(ge.idx)}else{let ge=["[tool","[agent","[[END]]","<|tool_calls_section_begin|>","<|tool_call_begin|>"],Ye=-1;for(let M of ge){for(let kt=M.length-1;kt>0;kt--)if(W.endsWith(M.substring(0,kt))){Ye=W.length-kt;let Pe=ge.indexOf(M);Pe===0?dt="tool":Pe===1?dt="agent":Pe===2?dt="end":Pe===3?dt="kimi_section":dt="kimi_call";break}if(Ye!==-1)break}if(Ye!==-1)Ye>0&&te.push({type:"text",content:W.substring(0,Ye)}),ks=!0,os=W.substring(Ye),W="";else{te.push({type:"text",content:W});break}}}return te},Ha=$e[Symbol.asyncIterator]();for(;;){let{value:P,done:te}=await Promise.race([Ha.next(),Dt]);if(te)break;if(P&&P.type==="status"){yield P;continue}let W="",G=P.candidates?.[0]?.content?.parts;if(G&&G.length>0)for(let me of G){let fe=typeof me.text=="string"?me.text:me.text?parseChunkText(me.text):"";me.thought?fe&&(he||(W+="<think>",he=!0),W+=fe):fe&&(he&&(W+="</think>",he=!1),W+=fe)}else P.text&&he&&(W+="</think>",he=!1);W=Pn(W);let Te=W?W.trim().split(/\s+/).filter(Boolean).length:0;if(t&&typeof t.onTokenChunk=="function"&&t.onTokenChunk(W,Te),xr&&(yield{type:"status",content:"Thinking"},xr=!1),Ot){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
657
+ `;te+="[/system]",Et.parts[0].text+=te;let W=-1;for(let G=k.length-1;G>=0;G--)if(k[G].role==="user"&&k[G].text?.startsWith("[TOOL RESULT]")){W=G;break}W!==-1&&(k[W].text+=te)}}catch{}let Bn=Math.floor(Bs*(i==="Flux"?.98:.8)),Xt=H+1;Xt>=Bn&&Et&&Et.parts?.[0]&&(Et.parts[0].text+=`
658
+ [system] WARNING, Turn Limit Impending: Step ${Xt}/${Bs}. Wrap up quickly/prompt user to continue. [/system]`);let vt=new Promise((P,te)=>{_.signal.aborted&&te(new DOMException("The user aborted a request.","AbortError")),_.signal.addEventListener("abort",()=>{te(new DOMException("The user aborted a request.","AbortError"))})});vt.catch(()=>{});let rt=se;if(u==="Ollama")Ce=Da(t.apiKey,Se,rt,nt,a,i,y,_.signal,1.05,l?.ollamaEndpoint||"Cloud");else if(u==="OpenRouter")Ce=oi(t.apiKey,Se,rt,nt,a,i,y,_.signal,1.05);else if(u==="DeepSeek")Ce=ti(t.apiKey,Se,rt,nt,a,i,y,_.signal,1.05);else if(u==="Mistral")Ce=ni(t.apiKey,Se,rt,nt,a,i,y,_.signal,1.05);else if(u==="NVIDIA"){let P=si(t.apiKey,Se,rt,nt,a,i,y,_.signal,1.05);Ce=$c(P,Se)}else if(u==="CrofAI")Ce=ri(t.apiKey,Se,rt,nt,a,i,y,_.signal,1.05);else if(u==="InferX")Ce=ii(t.apiKey,Se,rt,nt,a,i,y,_.signal,1.05);else if(u==="SenseNova")Ce=ai(t.apiKey,Se,rt,nt,a,i,y,_.signal,1.05);else{let te=li(t?.apiKey).models.generateContentStream({model:Se||"gemini-3-flash-preview",contents:rt,config:{systemInstruction:nt,mediaResolution:"MEDIA_RESOLUTION_HIGH",safetySettings:[{category:Vn.HARM_CATEGORY_HARASSMENT,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_HATE_SPEECH,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Yn.BLOCK_NONE}],temperature:1.05,thinkingConfig:(()=>{let W=(Se||"").toLowerCase(),G=W.includes("gemma-4")||W.startsWith("gemma"),Te=W.includes("gemini-3");if(G||Te)return G?a.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:ct.MINIMAL}:{includeThoughts:!0,thinkingLevel:ct.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:W.includes("pro")?ct.LOW:ct.MINIMAL,Low:ct.LOW,Medium:ct.MEDIUM,Standard:ct.MEDIUM,High:ct.HIGH,xHigh:ct.HIGH}[a]||ct.MEDIUM};{let me={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[a]||2048;return me===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:me}}})()}},{signal:_.signal});Ce=await Promise.race([te,vt])}de="",Wt=null,sn=null,Z=[],Ge=0,yield{type:"model_update",content:null},Ke="",Ht=tt.length>0;let Pt="",Ko=Date.now(),ns=async function*(){if(u==="Google"&&Pt){let P=Us(Pt);for(let te of P)yield te;Pt="",Ko=Date.now()}},wi=!0,ss="",bs=!1,ft=null,Us=P=>{let te=[],W=P;for(;W.length>0;)if(bs){let G=ss+W;if(ft==="tool"||ft==="agent"){let fe=ft==="tool"?"[tool:functions.":"[agent:generalist.",_t=ft==="tool"?"[tool":"[agent";if(!G.startsWith(_t)||G.length>=fe.length&&!G.startsWith(fe)){te.push({type:"text",content:G}),ss="",bs=!1,ft=null,W="";break}}let Te=-1,me="]";if(ft==="tool"||ft==="agent"){let fe=0,_t=null,z=0,ge=!1;for(let Ye=0;Ye<G.length;Ye++){let M=G[Ye];if(_t){if(M===_t){let St=0;for(let Pe=Ye-1;Pe>=0&&G[Pe]==="\\";Pe--)St++;St%2===0&&(_t=null)}}else if(M==='"'||M==="'"||M==="`")_t=M;else if(M==="(")fe++,ge=!0;else if(M===")")fe--;else if(M==="[")z++;else if(M==="]"){if(ge&&fe===0&&z===1){Te=Ye;break}z--}}}else ft==="end"?me="[[END]]":ft==="kimi_section"?me="<|tool_calls_section_end|>":ft==="kimi_call"&&(me="<|tool_call_end|>"),Te=G.indexOf(me);if(Te!==-1){let fe=me.length;if(!ft.startsWith("kimi")){let _t=G.substring(0,Te+fe);te.push({type:"text",content:_t})}ss="",bs=!1,ft=null,W=G.substring(Te+fe)}else{let fe=ft.startsWith("kimi")?8192:512;G.length>fe?(ft.startsWith("kimi")||te.push({type:"text",content:G}),ss="",bs=!1):ss=G,W="";break}}else{let G=W.indexOf("[tool"),Te=W.indexOf("[agent"),me=W.indexOf("[[END]]"),fe=W.indexOf("<|tool_calls_section_begin|>"),_t=W.indexOf("<|tool_call_begin|>"),z=[{type:"tool",idx:G,start:"[tool",end:"]"},{type:"agent",idx:Te,start:"[agent",end:"]"},{type:"end",idx:me,start:"[[END]]",end:"[[END]]"},{type:"kimi_section",idx:fe,start:"<|tool_calls_section_begin|>",end:"<|tool_calls_section_end|>"},{type:"kimi_call",idx:_t,start:"<|tool_call_begin|>",end:"<|tool_call_end|>"}].filter(ge=>ge.idx!==-1).sort((ge,Ye)=>ge.idx-Ye.idx);if(z.length>0){let ge=z[0];ge.idx>0&&te.push({type:"text",content:W.substring(0,ge.idx)}),bs=!0,ft=ge.type,ss="",W=W.substring(ge.idx)}else{let ge=["[tool","[agent","[[END]]","<|tool_calls_section_begin|>","<|tool_call_begin|>"],Ye=-1;for(let M of ge){for(let St=M.length-1;St>0;St--)if(W.endsWith(M.substring(0,St))){Ye=W.length-St;let Pe=ge.indexOf(M);Pe===0?ft="tool":Pe===1?ft="agent":Pe===2?ft="end":Pe===3?ft="kimi_section":ft="kimi_call";break}if(Ye!==-1)break}if(Ye!==-1)Ye>0&&te.push({type:"text",content:W.substring(0,Ye)}),bs=!0,ss=W.substring(Ye),W="";else{te.push({type:"text",content:W});break}}}return te},Ga=Ce[Symbol.asyncIterator]();for(;;){let{value:P,done:te}=await Promise.race([Ga.next(),vt]);if(te)break;if(P&&P.type==="status"){yield P;continue}let W="",G=P.candidates?.[0]?.content?.parts;if(G&&G.length>0)for(let me of G){let fe=typeof me.text=="string"?me.text:me.text?parseChunkText(me.text):"";me.thought?fe&&(he||(W+="<think>",he=!0),W+=fe):fe&&(he&&(W+="</think>",he=!1),W+=fe)}else P.text&&he&&(W+="</think>",he=!1);W=Dn(W);let Te=W?W.trim().split(/\s+/).filter(Boolean).length:0;if(t&&typeof t.onTokenChunk=="function"&&t.onTokenChunk(W,Te),wi&&(yield{type:"status",content:"Thinking"},wi=!1),Dt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
659
659
 
660
- \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(W){if(jt){if(Ke+=W,Ke.length>=64){let z=0,ge=Math.min(tt.length,Ke.length);for(let M=ge;M>=10;M--)if(tt.endsWith(Ke.substring(0,M))){z=M;break}let Ye=Ke.substring(z);if(Ye){let kt=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(tt)?Ye.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):Ye.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(kt)if(de+=kt,u==="Google")xn+=kt;else{yield*ss();let Pe=Ws(kt);for(let re of Pe)yield re}}jt=!1,Ke=""}continue}else if(de+=W,u==="Google")xn+=W;else{yield*ss();let z=Ws(W);for(let ge of z)yield ge}let me=$c(de);if(me.inside){Zn=!0,nn||(nn=Date.now());let ge={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"}[me.toolName]||me.toolName,Ye=me.args||"",M=null;if(["write_file","update_file","view_file","read_folder","write_pdf","write_docx","search_keyword","generate_image","file_map","invoke","invoke_sync","get_progress","await","answer"].includes(ge)){let Pe=O(Ye),re=Pe.path||Pe.targetFile||Pe.TargetFile||Pe.directory,bn=Pe.keyword,is=Pe.title||Pe.task,Un=Pe.id||Pe.taskId,Re=Pe.timeout||Pe.time;if(bn!=null)M=String(bn).replace(ys,"");else if(re)M=Q.basename(String(re).replace(ys,"").replace(Ra,"/"));else if(is&&(ge==="invoke"||ge==="invoke_sync"))M=String(is).replace(ys,"").substring(0,30);else if(Un&&ge==="get_progress")M=String(Un).replace(ys,"");else if(Re&&ge==="await"){let Gt=parseFloat(String(Re).replace(ys,""));isNaN(Gt)?M=String(Re).replace(ys,""):(Gt<5&&(Gt=5),Gt>120&&(Gt=120),M=($n=>{if($n>=60){let Xo=Math.floor($n/60),Ss=$n%60;return`${Xo}m${Ss>0?` ${Ss}s`:""}`}return`${$n}s`})(Gt))}else{let Gt=Ye.match(gc);if(Gt){let Xt=Gt[1].replace(ys,"");ge==="invoke"||ge==="invoke_sync"||ge==="get_progress"?M=Xt.substring(0,30):M=ge==="search_keyword"||ge==="file_map"?Xt:Q.basename(Xt.replace(Ra,"/"))}}}let kt=`${Zi[ge]||ge}${M?` ${M}`:""}`;if((ge!==Ut||M!==Qe)&&(Ut=ge,Qe=M,yield{type:"status",content:`${kt}`},process.stdout.isTTY)){let re={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"}[ge]||"Working";process.stdout.write(`\x1B]0;${re}...\x07`)}}if(de.length-yo>150){yo=de.length;let z=Fa(de,!1),Ye=(z.match(/(?:<think>|\[think\])([\s\S]*?)(?:<\/think>|\[\/think\]|$)/gi)||[]).join("").trim(),M=Ye.split(/[.!?]\s+/),kt=new Set(M),Pe=M.length>10?(M.length-kt.size)/M.length:0,re=Ye.split(/\s+/).filter(Me=>Me.length>0).length,bn=.6,is=.8,Un=!1;if((u.toLowerCase().includes("google")||u.toLowerCase().includes("mistral"))&&((Se||"").toLowerCase().startsWith("gemma")||(Se||"").toLowerCase().includes("stral"))){let v={low:256,medium:1024,high:8192,max:16384,xhigh:16384}[a?.toLowerCase()]||2500;Un=re>v}if(Pe>bn||Un){yield{type:"status",content:`${Pe>bn?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},Wt=!0,await new Promise(v=>setTimeout(v,3e3));break}let Xt=Ia(de).trim().split(/[.!?]\s+/),$n=new Set(Xt);if((Xt.length>10?(Xt.length-$n.size)/Xt.length:0)>is){yield{type:"status",content:"Response Loop Detected. Re-centering..."},Wt=!1,En=!0,await new Promise(Me=>setTimeout(Me,3e3));break}let Ss=z.replace(cc,"").replace(dc,"").replace(fc,"").replace(uc,""),qt=Ss.toLowerCase().split(/\s+/).map(Me=>Me.replace(hc,"")).filter(Me=>Me.length>0),Cn=!1;if(qt.length>=10)for(let Me=1;Me<=15;Me++){let v=Math.max(3,Math.ceil(10/Me));if(qt.length<Me*v)continue;let K=qt.slice(qt.length-Me),le=K.join(" ");if(Me>1&&le===K.slice(0,Math.floor(Me/2)).join(" ").repeat(2).trim())continue;let ye=!0;for(let we=1;we<v;we++)if(qt.slice(qt.length-Me*(we+1),qt.length-Me*we).join(" ")!==le){ye=!1;break}if(ye){Cn=!0;break}}if(!Cn){let Me=Ss.toLowerCase().replace(pc,"");if(Me.length>=20)for(let v=1;v<=10;v++){let K=Math.max(5,Math.ceil(16/v));if(Me.length<v*K)continue;let le=Me.substring(Me.length-v),ye=!0;for(let we=1;we<K;we++)if(Me.substring(Me.length-v*(we+1),Me.length-v*we)!==le){ye=!1;break}if(ye){Cn=!0;break}}}if(Cn){yield{type:"status",content:"Stuttering Detected. Re-centering..."},Wt=!1,wn=!0,await new Promise(Me=>setTimeout(Me,3e3));break}}let fe=de.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/gi,""),Rt=Go(fe);for(;Rt.length>Ge;){yield*ss();let z=Rt[Ge],ge=Date.now(),M={Ask:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Await:"await",await:"await",AwaitSubagent:"await",awaitSubagent:"await",Answer:"answer",answer:"answer",AnswerSubagent:"answer",answerSubagent:"answer",Steer:"steer",steer:"steer",SteerSubagent:"steer",steerSubagent:"steer",Cancel:"cancel",cancel:"cancel",Click:"click",click:"click",Drag:"drag",drag:"drag",Scroll:"scroll",scroll:"scroll",KeyboardTyping:"keyboard_typing",keyboard_typing:"keyboard_typing",KeyPress:"key_press",key_press:"key_press",RecaptureScreen:"recapture_screen",recapture_screen:"recapture_screen",EmergencyRollback:"EmergencyRollback"}[z.toolName]||z.toolName,kt=Zi[M]||z.toolName,Pe=xs(M,z.args);yield{type:"status",content:`${kt}${Pe?` ${Pe}`:""}`};let re="";if(M==="click"){let v=O(z.args);re=`\u2714 Clicked: ${v.intendedClickText?`${v.intendedClickText}`:""}`}else if(M==="drag"){let v=O(z.args);re=`\u2714 Dragged: Cell ${v.fromGridId||""} \u2192 Cell ${v.toGridId||""}`}else if(M==="scroll"){let v=O(z.args);re=`\u2714 Scrolled: ${v.direction||"down"} (${v.amount||1})`}else if(M==="keyboard_typing"){let v=O(z.args);re=`\u2714 Typed: ${v.text?`"${v.text.length>20?v.text.substring(0,20)+"...":v.text}"`:""}`}else if(M==="key_press")re=`\u2714 Pressed Key: ${O(z.args).key||""}`;else if(M==="recapture_screen")re="\u2714 Recaptured Screen";else if(M==="web_search"){let{query:v,limit:K=10,aiMode:le=!1}=O(z.args);re=`${v?"\u2714":"\u2718"} ${le?"AI Search":"Searched"}: ${v?`${v}`:"No Search Query"}${le===!1&&v?` \u2192 ${K}`:""}`}else if(M==="web_scrape"){let v=O(z.args).url||null;re=`${v?"\u2714":"\u2718"} Visited: ${v||"No Source"}`}else if(M==="view_file"){let{path:v,StartLine:K,EndLine:le,start_line:ye,end_line:we,startLine:qe,endLine:Oe}=O(z.args),be=K||ye||qe,ee=le||we||Oe,ue=parseInt(be)||1,ce=parseInt(ee)||(be?ue+800:800),Be="...",et=ce;try{let Ve=Q.resolve(process.cwd(),v);if(De.existsSync(Ve)){let Et=De.readFileSync(Ve,"utf8").split(`
661
- `).length;Be=Et,!be&&!ee&&Et>800?et=Math.min(50,Et):et=Math.min(ce,Et)}}catch{}let xe=(v||"").toLowerCase(),Fe=xe.endsWith(".pdf"),it=xe.endsWith(".docx")||xe.endsWith(".doc")||xe.endsWith(".ppt")||xe.endsWith(".pptx")||xe.endsWith(".xls")||xe.endsWith(".xlsx"),Ae=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(xe);Fe||it?re=`${v.length>0?"\u2714":"\u2718"} ${v?`Analyzed: ${Q.basename(v)}`:"Analyzed: File Not Found"}`:Ae?re=`${v.length>0?"\u2714":"\u2718"} ${v?`Processed: ${Q.basename(v)}`:"Processed: File Not Found"}`:re=`${Be!=="..."?"\u2714":"\u2718"} Read: ${v?`${Q.basename(v)} \u2192 ${Be!=="..."?`Lines ${ue} - ${et} of ${Be}`:"File Not Found"}`:"File Not Found"}`}else if(M==="list_files"||M==="read_folder"){let v=M==="list_files"?"List":"Browsed",K=O(z.args).path||null,le=O(z.args).recurse||1;re=`${K?"\u2714":"\u2718"} ${v}: ${K?`${K==="."?`./${le>1?"*":""}`:`${K.replaceAll("\\","/")}${le>1?`${K.endsWith("/")?"*":"/*"}`:`${K.endsWith("/")?"":"/"}`}`}`:"No Folder Selected"}`}else if(M==="write_file"||M==="update_file"){let v=M==="write_file"?"Created":"Edited",K=O(z.args).path||null;re=`${K?"\u2714":"\u2718"} ${v}: ${K.replaceAll("\\","/")||"No File Changes"}`}else if(M==="write_pdf"){let v=O(z.args).path||null;re=`${v?"\u2714":"\u2718"} Generated: ${v.replaceAll("\\","/")||"No PDF Generated"}`}else if(M==="write_docx"){let v=O(z.args).path||null;re=`${v?"\u2714":"\u2718"} Generated: ${v.replaceAll("\\","/")||"No Docx Generated"}`}else if(M==="file_map"){let v=O(z.args).path;re=`${v?"\u2714":"\u2718"} Indexed: ${v.replaceAll("\\","/")?""+v:"File Not Found"}`}else if(M.toLowerCase()==="search_keyword"||M.toLowerCase()==="todo")re="";else if(M.toLowerCase()==="generate_image"){let{path:v,outputPath:K,output:le}=O(z.args);re=`\u2714 Generated: ${v||K||le||"generated_image.png"}`}else if(M==="invoke_sync"||M==="InvokeSync"){let v=xs(M,z.args);re=`\u2714 Called Generalist${v?`: ${v}`:""}`}else if(M==="Invoke"||M==="InvokeAsync"||M==="invoke"){let v=xs(M,z.args);re=`\u2714 Started Generalist${v?`: ${v}`:""}`}else if(M==="get_progress"||M==="GetProgress"){let v=xs(M,z.args);re=`\u2714 Checked${v?`: ${v}`:""}`}else if(M==="cancel"){let v=xs(M,z.args);re=`\u{1F6C7} Cancelled${v?`: ${v}`:""}`}else if(M==="steer"||M==="Steer"){let v=xs(M,z.args);re=`\u2714 Steered${v?`: ${v}`:""}`}else if(M==="EmergencyRollback"){let{method:v}=O(z.args);re=v==="forceRevert"?"":"\u2714 Rollback Point Checked"}else if(M==="await"||M==="Await"){let{time:v,timeout:K}=O(z.args),le=parseFloat(K||v)||0;le||(le=120);let ye=Oe=>{if(Oe>=60){let be=Math.floor(Oe/60),ee=Oe%60;return`${be}m${ee>0?` ${ee}s`:""}`}return`${Oe}s`},we=["Aligning Moon Phase","Contemplating Existence","Staring At Void","Delaying Professionally","Negotiating With Electrons","Touching Grass (virtually)","Panicking Softly","Rethinking Career Choices","Loading Cat Videos","Summoning Braincell #2","Pretending To Be Busy","Waiting For Motivation DLC","Rotating Internal Screaming","Downloading More RAM","Feeding The Hamsters","Gaslighting Scheduler","Performing Dramatic Pause","Buffering Social Energy","Calculating Regret","Reading Terms And Conditions","Becoming Sentient Briefly","Contacting Ancestors"];re=`\u2714 ${we[Math.floor(Math.random()*we.length)]} \u2192 ${ye(le)}`}else M==="Answer"||M==="answer"?re="\u2714 Resolved Sub-Agent Query":M==="exec_command"||M==="ask"?re="":re=`Executed: ${z.toolName}`;if(yield*ss(),M==="exec_command"){let{command:v}=O(z.args);if(v&&t.systemSettings&&t.systemSettings.allowExternalAccess===!1){let K=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],le=Q.resolve(process.cwd()).substring(0,3).toLowerCase(),ye=ee=>{let ue=[],ce="",Be=null;for(let et=0;et<ee.length;et++){let xe=ee[et];Be?(xe===Be&&(Be=null),ce+=xe):xe==='"'||xe==="'"?(Be=xe,ce+=xe):xe==="&"&&ee[et+1]==="&"||xe==="|"&&ee[et+1]==="|"?(ce.trim()&&(ue.push(ce.trim()),ce=""),et++):xe===";"||xe==="|"||xe==="&"?ce.trim()&&(ue.push(ce.trim()),ce=""):ce+=xe}return ce.trim()&&ue.push(ce.trim()),ue},we=ee=>{let ue=[],ce="",Be=null;for(let et=0;et<ee.length;et++){let xe=ee[et];Be?(xe===Be&&(Be=null),ce+=xe):xe==='"'||xe==="'"?(Be=xe,ce+=xe):/\s/.test(xe)?ce&&(ue.push(ce),ce=""):ce+=xe}return ce&&ue.push(ce),ue},qe=ee=>{let ue=ee.replace(/^['"]|['"]$/g,"").trim();return!ue||process.platform==="win32"&&/^\/[a-zA-Z0-9?]+$/.test(ue)?!1:K.some(ce=>{if(ce.source==="[a-zA-Z]:[\\\\\\/]"){let Be=ue.match(/[a-zA-Z]:[\\\/]/i);return Be&&Be[0].toLowerCase()!==le}return ce.test(ue)})};if(ye(v).some(ee=>{let ue=we(ee);if(ue.length===0)return!1;let ce=ue[0].replace(/^['"]|['"]$/g,"").toLowerCase();if(["echo","printf","write-output"].includes(ce)){let et=!1;return ue.some(xe=>{let Fe=xe.replace(/^['"]|['"]$/g,"");if(Fe===">"||Fe===">>"||Fe==="<")return et=!0,!1;if(Fe.startsWith(">")||Fe.startsWith("<")){let it=Fe.replace(/^[><]+/,"");return qe(it)}return et?(et=!1,qe(xe)):!1})}return ue.some(et=>qe(et))})){let ee='Access Denied. Prohibited from accessing external directories while "External Workspace Access" is disabled.';t.onExecStart&&t.onExecStart(v||"No Command"),yield{type:"exec_start"},await new Promise(ue=>setTimeout(ue,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${ee}`),await new Promise(ue=>setTimeout(ue,50)),t.onExecEnd&&t.onExecEnd(),Z.push({role:"user",text:`[TOOL RESULT]: ERROR: ${ee}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${ee}`},Ge++;continue}}t.onExecStart&&t.onExecStart(v||"No Command"),yield{type:"exec_start"}}let bn=O(z.args),is=bn.path||bn.targetPath||null;if(is){let v=t.systemSettings&&t.systemSettings.allowExternalAccess===!1,K=Q.resolve(is),le=Q.resolve(process.cwd());if(v&&!K.startsWith(le)){let ye="Access Denied. You are not allowed to access files outside the current workspace.";if(M==="write_file"||M==="update_file"){let qe=`\u2718 ${M==="write_file"?"Write Canceled":"Edit Canceled"}: ${bn.path||"..."}`,Oe=115;process.stdout.isTTY&&(Oe=process.stdout.columns-5||120);let be=Math.min(qe.length+4,Oe),ee=`${qe.padEnd(be-2).substring(0,be-2)}`;yield{type:"visual_feedback",content:gn(`${We?`
660
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(W){if(Ht){if(Ke+=W,Ke.length>=64){let z=0,ge=Math.min(tt.length,Ke.length);for(let M=ge;M>=10;M--)if(tt.endsWith(Ke.substring(0,M))){z=M;break}let Ye=Ke.substring(z);if(Ye){let St=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(tt)?Ye.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):Ye.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(St)if(de+=St,u==="Google")Pt+=St;else{yield*ns();let Pe=Us(St);for(let ie of Pe)yield ie}}Ht=!1,Ke=""}continue}else if(de+=W,u==="Google")Pt+=W;else{yield*ns();let z=Us(W);for(let ge of z)yield ge}let me=Cc(de);if(me.inside){Zn=!0,sn||(sn=Date.now());let ge={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"}[me.toolName]||me.toolName,Ye=me.args||"",M=null;if(["write_file","update_file","view_file","read_folder","write_pdf","write_docx","search_keyword","generate_image","file_map","invoke","invoke_sync","get_progress","await","answer"].includes(ge)){let Pe=O(Ye),ie=Pe.path||Pe.targetFile||Pe.TargetFile||Pe.directory,xn=Pe.keyword,os=Pe.title||Pe.task,Un=Pe.id||Pe.taskId,Ee=Pe.timeout||Pe.time;if(xn!=null)M=String(xn).replace(gs,"");else if(ie)M=Q.basename(String(ie).replace(gs,"").replace(Ta,"/"));else if(os&&(ge==="invoke"||ge==="invoke_sync"))M=String(os).replace(gs,"").substring(0,30);else if(Un&&ge==="get_progress")M=String(Un).replace(gs,"");else if(Ee&&ge==="await"){let Gt=parseFloat(String(Ee).replace(gs,""));isNaN(Gt)?M=String(Ee).replace(gs,""):(Gt<5&&(Gt=5),Gt>120&&(Gt=120),M=(_n=>{if(_n>=60){let Vo=Math.floor(_n/60),ks=_n%60;return`${Vo}m${ks>0?` ${ks}s`:""}`}return`${_n}s`})(Gt))}else{let Gt=Ye.match(yc);if(Gt){let Jt=Gt[1].replace(gs,"");ge==="invoke"||ge==="invoke_sync"||ge==="get_progress"?M=Jt.substring(0,30):M=ge==="search_keyword"||ge==="file_map"?Jt:Q.basename(Jt.replace(Ta,"/"))}}}let St=`${Qr[ge]||ge}${M?` ${M}`:""}`;if((ge!==Wt||M!==Qe)&&(Wt=ge,Qe=M,yield{type:"status",content:`${St}`},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"}[ge]||"Working";process.stdout.write(`\x1B]0;${ie}...\x07`)}}if(de.length-go>150){go=de.length;let z=Pa(de,!1),Ye=(z.match(/(?:<think>|\[think\])([\s\S]*?)(?:<\/think>|\[\/think\]|$)/gi)||[]).join("").trim(),M=Ye.split(/[.!?]\s+/),St=new Set(M),Pe=M.length>10?(M.length-St.size)/M.length:0,ie=Ye.split(/\s+/).filter(Me=>Me.length>0).length,xn=.6,os=.8,Un=!1;if((u.toLowerCase().includes("google")||u.toLowerCase().includes("mistral"))&&((Se||"").toLowerCase().startsWith("gemma")||(Se||"").toLowerCase().includes("stral"))){let v={low:256,medium:1024,high:8192,max:16384,xhigh:16384}[a?.toLowerCase()]||2500;Un=ie>v}if(Pe>xn||Un){yield{type:"status",content:`${Pe>xn?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},jt=!0,await new Promise(v=>setTimeout(v,3e3));break}let Jt=va(de).trim().split(/[.!?]\s+/),_n=new Set(Jt);if((Jt.length>10?(Jt.length-_n.size)/Jt.length:0)>os){yield{type:"status",content:"Response Loop Detected. Re-centering..."},jt=!1,Rn=!0,await new Promise(Me=>setTimeout(Me,3e3));break}let ks=z.replace(dc,"").replace(fc,"").replace(uc,"").replace(hc,""),qt=ks.toLowerCase().split(/\s+/).map(Me=>Me.replace(pc,"")).filter(Me=>Me.length>0),$n=!1;if(qt.length>=10)for(let Me=1;Me<=15;Me++){let v=Math.max(3,Math.ceil(10/Me));if(qt.length<Me*v)continue;let K=qt.slice(qt.length-Me),le=K.join(" ");if(Me>1&&le===K.slice(0,Math.floor(Me/2)).join(" ").repeat(2).trim())continue;let ye=!0;for(let we=1;we<v;we++)if(qt.slice(qt.length-Me*(we+1),qt.length-Me*we).join(" ")!==le){ye=!1;break}if(ye){$n=!0;break}}if(!$n){let Me=ks.toLowerCase().replace(mc,"");if(Me.length>=20)for(let v=1;v<=10;v++){let K=Math.max(5,Math.ceil(16/v));if(Me.length<v*K)continue;let le=Me.substring(Me.length-v),ye=!0;for(let we=1;we<K;we++)if(Me.substring(Me.length-v*(we+1),Me.length-v*we)!==le){ye=!1;break}if(ye){$n=!0;break}}}if($n){yield{type:"status",content:"Stuttering Detected. Re-centering..."},jt=!1,wn=!0,await new Promise(Me=>setTimeout(Me,3e3));break}}let fe=de.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/gi,""),_t=Ho(fe);for(;_t.length>Ge;){yield*ns();let z=_t[Ge],ge=Date.now(),M={Ask:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Await:"await",await:"await",AwaitSubagent:"await",awaitSubagent:"await",Answer:"answer",answer:"answer",AnswerSubagent:"answer",answerSubagent:"answer",Steer:"steer",steer:"steer",SteerSubagent:"steer",steerSubagent:"steer",Cancel:"cancel",cancel:"cancel",Click:"click",click:"click",Drag:"drag",drag:"drag",Scroll:"scroll",scroll:"scroll",KeyboardTyping:"keyboard_typing",keyboard_typing:"keyboard_typing",KeyPress:"key_press",key_press:"key_press",RecaptureScreen:"recapture_screen",recapture_screen:"recapture_screen",EmergencyRollback:"EmergencyRollback"}[z.toolName]||z.toolName,St=Qr[M]||z.toolName,Pe=ws(M,z.args);yield{type:"status",content:`${St}${Pe?` ${Pe}`:""}`};let ie="";if(M==="click"){let v=O(z.args);ie=`\u2714 Clicked: ${v.intendedClickText?`${v.intendedClickText}`:""}`}else if(M==="drag"){let v=O(z.args);ie=`\u2714 Dragged: Cell ${v.fromGridId||""} \u2192 Cell ${v.toGridId||""}`}else if(M==="scroll"){let v=O(z.args);ie=`\u2714 Scrolled: ${v.direction||"down"} (${v.amount||1})`}else if(M==="keyboard_typing"){let v=O(z.args);ie=`\u2714 Typed: ${v.text?`"${v.text.length>20?v.text.substring(0,20)+"...":v.text}"`:""}`}else if(M==="key_press")ie=`\u2714 Pressed Key: ${O(z.args).key||""}`;else if(M==="recapture_screen")ie="\u2714 Recaptured Screen";else if(M==="web_search"){let{query:v,limit:K=10,aiMode:le=!1}=O(z.args);ie=`${v?"\u2714":"\u2718"} ${le?"AI Search":"Searched"}: ${v?`${v}`:"No Search Query"}${le===!1&&v?` \u2192 ${K}`:""}`}else if(M==="web_scrape"){let v=O(z.args).url||null;ie=`${v?"\u2714":"\u2718"} Visited: ${v||"No Source"}`}else if(M==="view_file"){let{path:v,StartLine:K,EndLine:le,start_line:ye,end_line:we,startLine:qe,endLine:Oe}=O(z.args),be=K||ye||qe,ee=le||we||Oe,ue=parseInt(be)||1,ce=parseInt(ee)||(be?ue+800:800),Be="...",et=ce;try{let Ve=Q.resolve(process.cwd(),v);if(De.existsSync(Ve)){let $t=De.readFileSync(Ve,"utf8").split(`
661
+ `).length;Be=$t,!be&&!ee&&$t>800?et=Math.min(50,$t):et=Math.min(ce,$t)}}catch{}let xe=(v||"").toLowerCase(),Fe=xe.endsWith(".pdf"),it=xe.endsWith(".docx")||xe.endsWith(".doc")||xe.endsWith(".ppt")||xe.endsWith(".pptx")||xe.endsWith(".xls")||xe.endsWith(".xlsx"),Ae=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(xe);Fe||it?ie=`${v.length>0?"\u2714":"\u2718"} ${v?`Analyzed: ${Q.basename(v)}`:"Analyzed: File Not Found"}`:Ae?ie=`${v.length>0?"\u2714":"\u2718"} ${v?`Processed: ${Q.basename(v)}`:"Processed: File Not Found"}`:ie=`${Be!=="..."?"\u2714":"\u2718"} Read: ${v?`${Q.basename(v)} \u2192 ${Be!=="..."?`Lines ${ue} - ${et} of ${Be}`:"File Not Found"}`:"File Not Found"}`}else if(M==="list_files"||M==="read_folder"){let v=M==="list_files"?"List":"Browsed",K=O(z.args).path||null,le=O(z.args).recurse||1;ie=`${K?"\u2714":"\u2718"} ${v}: ${K?`${K==="."?`./${le>1?"*":""}`:`${K.replaceAll("\\","/")}${le>1?`${K.endsWith("/")?"*":"/*"}`:`${K.endsWith("/")?"":"/"}`}`}`:"No Folder Selected"}`}else if(M==="write_file"||M==="update_file"){let v=M==="write_file"?"Created":"Edited",K=O(z.args).path||null;ie=`${K?"\u2714":"\u2718"} ${v}: ${K.replaceAll("\\","/")||"No File Changes"}`}else if(M==="write_pdf"){let v=O(z.args).path||null;ie=`${v?"\u2714":"\u2718"} Generated: ${v.replaceAll("\\","/")||"No PDF Generated"}`}else if(M==="write_docx"){let v=O(z.args).path||null;ie=`${v?"\u2714":"\u2718"} Generated: ${v.replaceAll("\\","/")||"No Docx Generated"}`}else if(M==="file_map"){let v=O(z.args).path;ie=`${v?"\u2714":"\u2718"} Indexed: ${v.replaceAll("\\","/")?""+v:"File Not Found"}`}else if(M.toLowerCase()==="search_keyword"||M.toLowerCase()==="todo")ie="";else if(M.toLowerCase()==="generate_image"){let{path:v,outputPath:K,output:le}=O(z.args);ie=`\u2714 Generated: ${v||K||le||"generated_image.png"}`}else if(M==="invoke_sync"||M==="InvokeSync"){let v=ws(M,z.args);ie=`\u2714 Called Generalist${v?`: ${v}`:""}`}else if(M==="Invoke"||M==="InvokeAsync"||M==="invoke"){let v=ws(M,z.args);ie=`\u2714 Started Generalist${v?`: ${v}`:""}`}else if(M==="get_progress"||M==="GetProgress"){let v=ws(M,z.args);ie=`\u2714 Checked${v?`: ${v}`:""}`}else if(M==="cancel"){let v=ws(M,z.args);ie=`\u{1F6C7} Cancelled${v?`: ${v}`:""}`}else if(M==="steer"||M==="Steer"){let v=ws(M,z.args);ie=`\u2714 Steered${v?`: ${v}`:""}`}else if(M==="EmergencyRollback"){let{method:v}=O(z.args);ie=v==="forceRevert"?"":"\u2714 Rollback Point Checked"}else if(M==="await"||M==="Await"){let{time:v,timeout:K}=O(z.args),le=parseFloat(K||v)||0;le||(le=120);let ye=Oe=>{if(Oe>=60){let be=Math.floor(Oe/60),ee=Oe%60;return`${be}m${ee>0?` ${ee}s`:""}`}return`${Oe}s`},we=["Aligning Moon Phase","Contemplating Existence","Staring At Void","Delaying Professionally","Negotiating With Electrons","Touching Grass (virtually)","Panicking Softly","Rethinking Career Choices","Loading Cat Videos","Summoning Braincell #2","Pretending To Be Busy","Waiting For Motivation DLC","Rotating Internal Screaming","Downloading More RAM","Feeding The Hamsters","Gaslighting Scheduler","Performing Dramatic Pause","Buffering Social Energy","Calculating Regret","Reading Terms And Conditions","Becoming Sentient Briefly","Contacting Ancestors"];ie=`\u2714 ${we[Math.floor(Math.random()*we.length)]} \u2192 ${ye(le)}`}else M==="Answer"||M==="answer"?ie="\u2714 Resolved Sub-Agent Query":M==="exec_command"||M==="ask"?ie="":ie=`Executed: ${z.toolName}`;if(yield*ns(),M==="exec_command"){let{command:v}=O(z.args);if(v&&t.systemSettings&&t.systemSettings.allowExternalAccess===!1){let K=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],le=Q.resolve(process.cwd()).substring(0,3).toLowerCase(),ye=ee=>{let ue=[],ce="",Be=null;for(let et=0;et<ee.length;et++){let xe=ee[et];Be?(xe===Be&&(Be=null),ce+=xe):xe==='"'||xe==="'"?(Be=xe,ce+=xe):xe==="&"&&ee[et+1]==="&"||xe==="|"&&ee[et+1]==="|"?(ce.trim()&&(ue.push(ce.trim()),ce=""),et++):xe===";"||xe==="|"||xe==="&"?ce.trim()&&(ue.push(ce.trim()),ce=""):ce+=xe}return ce.trim()&&ue.push(ce.trim()),ue},we=ee=>{let ue=[],ce="",Be=null;for(let et=0;et<ee.length;et++){let xe=ee[et];Be?(xe===Be&&(Be=null),ce+=xe):xe==='"'||xe==="'"?(Be=xe,ce+=xe):/\s/.test(xe)?ce&&(ue.push(ce),ce=""):ce+=xe}return ce&&ue.push(ce),ue},qe=ee=>{let ue=ee.replace(/^['"]|['"]$/g,"").trim();return!ue||process.platform==="win32"&&/^\/[a-zA-Z0-9?]+$/.test(ue)?!1:K.some(ce=>{if(ce.source==="[a-zA-Z]:[\\\\\\/]"){let Be=ue.match(/[a-zA-Z]:[\\\/]/i);return Be&&Be[0].toLowerCase()!==le}return ce.test(ue)})};if(ye(v).some(ee=>{let ue=we(ee);if(ue.length===0)return!1;let ce=ue[0].replace(/^['"]|['"]$/g,"").toLowerCase();if(["echo","printf","write-output"].includes(ce)){let et=!1;return ue.some(xe=>{let Fe=xe.replace(/^['"]|['"]$/g,"");if(Fe===">"||Fe===">>"||Fe==="<")return et=!0,!1;if(Fe.startsWith(">")||Fe.startsWith("<")){let it=Fe.replace(/^[><]+/,"");return qe(it)}return et?(et=!1,qe(xe)):!1})}return ue.some(et=>qe(et))})){let ee='Access Denied. Prohibited from accessing external directories while "External Workspace Access" is disabled.';t.onExecStart&&t.onExecStart(v||"No Command"),yield{type:"exec_start"},await new Promise(ue=>setTimeout(ue,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${ee}`),await new Promise(ue=>setTimeout(ue,50)),t.onExecEnd&&t.onExecEnd(),Z.push({role:"user",text:`[TOOL RESULT]: ERROR: ${ee}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${ee}`},Ge++;continue}}t.onExecStart&&t.onExecStart(v||"No Command"),yield{type:"exec_start"}}let xn=O(z.args),os=xn.path||xn.targetPath||null;if(os){let v=t.systemSettings&&t.systemSettings.allowExternalAccess===!1,K=Q.resolve(os),le=Q.resolve(process.cwd());if(v&&!K.startsWith(le)){let ye="Access Denied. You are not allowed to access files outside the current workspace.";if(M==="write_file"||M==="update_file"){let qe=`\u2718 ${M==="write_file"?"Write Canceled":"Edit Canceled"}: ${xn.path||"..."}`,Oe=115;process.stdout.isTTY&&(Oe=process.stdout.columns-5||120);let be=Math.min(qe.length+4,Oe),ee=`${qe.padEnd(be-2).substring(0,be-2)}`;yield{type:"visual_feedback",content:gn(`${We?`
662
662
  `:""}${ee}
663
- `)},We=!1}Z.push({role:"user",text:`[TOOL RESULT]: ERROR: ${ye}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${ye}`},Ge++;continue}}if(t.onToolApproval&&(M==="write_file"||M==="update_file"||M==="exec_command")){let K=t.systemSettings||{},le=K.autoExec,ye=null,we=!1,qe=!1,Oe=!1;if(M==="exec_command"){let{command:Fe}=O(z.args),it=(Fe||"").trim(),Ae=(Et,Jt)=>{if(!Jt)return!1;let dn=Jt.split(",").map(Qt=>Qt.trim().toLowerCase()).filter(Boolean),rt=Et.toLowerCase();return dn.some(Qt=>rt.startsWith(Qt))},Ve=Ae(it,K.alwaysAskCommands),ke=Ae(it,K.autoApproveCommands);if(qe=Ae(it,K.autoDisallowCommands),Ve?we=!0:(ke||K.autoApproveGit&&/^git\s+commit\b/i.test(it))&&(ye="allow"),!we&&!ye){if(K.networkAccess===!1){let Jt=it.trim().replace(/\s+/g," ").replace(/^['"]+|['"]+$/g,"").toLowerCase().split(" "),rt=Jt[0].split("/").pop().split("\\").pop().replace(/\.exe$/,""),Qt=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"]),at=!1;Qt.has(rt)&&(at=!0);let ft=kn=>Jt.slice(1).some(Sn=>kn.includes(Sn)),At=kn=>{let Sn=Jt.findIndex(Mn=>kn.includes(Mn)),Ts=Jt.findIndex(Mn=>["run","exec","test"].includes(Mn));return Sn!==-1&&!(Ts!==-1&&Ts<Sn)};rt==="git"&&ft(["clone","pull","push","fetch"])&&(at=!0),rt==="go"&&ft(["get","install"])&&(at=!0),rt==="npm"&&At(["install","i","update","add"])&&(at=!0),rt==="yarn"&&At(["add","install","upgrade"])&&(at=!0),rt==="pnpm"&&At(["add","install","update"])&&(at=!0),rt==="bun"&&At(["add","install","update"])&&(at=!0),rt==="deno"&&ft(["install","add"])&&(at=!0),rt==="pip"&&ft(["install","download"])&&(at=!0),rt==="pip3"&&ft(["install","download"])&&(at=!0),rt==="cargo"&&ft(["install","add"])&&(at=!0),["bash","sh","zsh","fish"].includes(rt)&&ft(["-c"])&&(at=!0),rt==="cmd"&&ft(["/c"])&&(at=!0),at&&(ye="deny",Oe=!0)}!ye&&qe&&(ye="deny")}!we&&!ye&&le&&(ye="allow")}else le&&(ye="allow");let be=ye,ee="";ye==="deny"&&(Oe?ee="network":qe?ee="settings":ee="prohibited");let ue=!1,ce="",Be=[],et=0,xe=!1;if(!be){if(M==="write_file"||M==="update_file")try{let Ae=O(z.args),{path:Ve}=Ae;if(Ve){let ke=Q.resolve(process.cwd(),Ve),Et=ft=>ft?ft.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,At=>At.toUpperCase()):"",Jt=Et(ke),dn="",rt=!1,Qt=await gs(),at=Et(Qt?.file_focused);if(Qt&&at===Jt&&Qt.full_content?(dn=Qt.full_content,rt=!0):De.existsSync(ke)&&(dn=De.readFileSync(ke,"utf8"),rt=!0),ce=dn,await ht.recordFileChange(ke,dn),rt){let ft=dn;if(M==="write_file")ft=Ae.content||Ae.newContent||"";else{let{patchPairs:At,allowMultiple:kn,error:Sn}=vo(Ae);if(Sn){let _t=`[TOOL RESULT]: ERROR: ${Sn}`;Z.push({role:"user",text:_t}),await It("toolFailure"),t.onToolResult&&t.onToolResult("failure",M),yield{type:"tool_result",content:_t,toolName:M},Ge++;continue}let Ts=Ae.allowMultiple!==void 0?Ae.allowMultiple===!0||String(Ae.allowMultiple).toLowerCase()==="true":kn;et=At.length;let Mn=Io(dn,At,{allowMultiple:Ts});ft=Mn.content,Be=Mn.results;let wo=Be.filter(_t=>_t.success),vt=Be.filter(_t=>!_t.success);if(wo.length===0){let _t=`[TOOL RESULT]: ERROR: Failed to apply patches to [${Q.basename(ke)}].
664
- ${vt.map(Gs=>` \u2022 ${Gs.error}`).join(`
665
- `)}`,Rs=`\u2714 Edited: ${Q.basename(ke.replaceAll("\\","/"))}`,Hs=115;process.stdout.isTTY&&(Hs=process.stdout.columns-5||120);let Es=Math.min(Rs.length+4,Hs),xo=`${Rs.padEnd(Es-2).substring(0,Es-2)}`;yield{type:"visual_feedback",content:gn(`${We?`
666
- `:""}${xo}`)},We=!1,Z.push({role:"user",text:_t}),await It("toolFailure"),t.onToolResult&&t.onToolResult("failure",M),yield{type:"tool_result",content:_t,toolName:M},Ge++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${Q.basename(ke)}`},Vi(ke,dn,ft),ue=!0,await new Promise(At=>setTimeout(At,50))}else if(M==="write_file"){let ft=Ae.content||Ae.newContent||"",At=ft.endsWith(`
667
- `)?ft:ft+`
668
- `;De.existsSync(ke)||(xe=!0,De.mkdirSync(Q.dirname(ke),{recursive:!0}),De.writeFileSync(ke,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${Q.basename(ke)}`},Vi(ke,"",At),ue=!0,await new Promise(kn=>setTimeout(kn,50))}}}catch(Ae){console.error("Simulation/Diff Error:",Ae)}let Fe=null;Yi(Ae=>{Fe=Ae});let it=t.onToolApproval;if(be=await new Promise(async Ae=>{let Ve=setInterval(()=>{Fe&&(jo.onIDEApproval&&jo.onIDEApproval(Fe),clearInterval(Ve),Ae(Fe))},100);try{let ke=await it(M,z.args);clearInterval(Ve),Ae(ke)}catch{clearInterval(Ve),Ae("deny")}}),Yi(null),M==="write_file"||M==="update_file"){let{path:Ae}=O(z.args);if(Ae){let Ve=Q.resolve(process.cwd(),Ae);if(Sa(Ve,be),be==="deny"&&xe&&De.existsSync(Ve))try{De.unlinkSync(Ve)}catch{}}}be==="deny"&&(ee="user")}if(be==="allow"&&ue&&Wo()){let{path:Fe}=O(z.args),it=Q.resolve(process.cwd(),Fe),Ae=vt=>vt?Q.resolve(vt).replace(/\\/g,"/").toLowerCase():"",Ve=await gs(),ke="";Ve&&Ve.file_focused&&Ae(Ve.file_focused)===Ae(it)&&Ve.full_content&&(ke=Ve.full_content),!ke&&De.existsSync(it)&&(ke=De.readFileSync(it,"utf8"),ke||(await new Promise(vt=>setTimeout(vt,100)),ke=De.readFileSync(it,"utf8")));let Et=ke.split(/\r?\n/),Jt=Et.length,dn=Buffer.byteLength(ke,"utf8"),rt="";ce&&(rt=`Old File contents:
669
- ${ce.split(/\r?\n/).map((_t,Rs)=>`${Rs+1} | ${_t}`).join(`
663
+ `)},We=!1}Z.push({role:"user",text:`[TOOL RESULT]: ERROR: ${ye}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${ye}`},Ge++;continue}}if(t.onToolApproval&&(M==="write_file"||M==="update_file"||M==="exec_command")){let K=t.systemSettings||{},le=K.autoExec,ye=null,we=!1,qe=!1,Oe=!1;if(M==="exec_command"){let{command:Fe}=O(z.args),it=(Fe||"").trim(),Ae=($t,Qt)=>{if(!Qt)return!1;let dn=Qt.split(",").map(Zt=>Zt.trim().toLowerCase()).filter(Boolean),at=$t.toLowerCase();return dn.some(Zt=>at.startsWith(Zt))},Ve=Ae(it,K.alwaysAskCommands),ke=Ae(it,K.autoApproveCommands);if(qe=Ae(it,K.autoDisallowCommands),Ve?we=!0:(ke||K.autoApproveGit&&/^git\s+commit\b/i.test(it))&&(ye="allow"),!we&&!ye){if(K.networkAccess===!1){let Qt=it.trim().replace(/\s+/g," ").replace(/^['"]+|['"]+$/g,"").toLowerCase().split(" "),at=Qt[0].split("/").pop().split("\\").pop().replace(/\.exe$/,""),Zt=new Set(["curl","wget","httpie","xh","ssh","scp","sftp","rsync","ftp","lftp","tftp","telnet","nc","netcat","socat","ping","traceroute","tracert","dig","nslookup","host","whois","nmap","docker","podman","kubectl","helm","gcloud","aws","az","terraform","ansible-playbook","nix","nix-env","apt","apt-get","dpkg","yum","dnf","pacman","zypper","brew","apk","choco","scoop","conda","mamba","aria2c","axel","smbclient","lynx","w3m","links","elinks","heroku","netlify","vercel","firebase","supabase","wrangler","flyctl","powershell","pwsh","certutil","bitsadmin","cloudflared","ngrok","tailscale","zerotier","rclone"]),lt=!1;Zt.has(at)&&(lt=!0);let ut=bn=>Qt.slice(1).some(kn=>bn.includes(kn)),It=bn=>{let kn=Qt.findIndex(Cn=>bn.includes(Cn)),Ss=Qt.findIndex(Cn=>["run","exec","test"].includes(Cn));return kn!==-1&&!(Ss!==-1&&Ss<kn)};at==="git"&&ut(["clone","pull","push","fetch"])&&(lt=!0),at==="go"&&ut(["get","install"])&&(lt=!0),at==="npm"&&It(["install","i","update","add"])&&(lt=!0),at==="yarn"&&It(["add","install","upgrade"])&&(lt=!0),at==="pnpm"&&It(["add","install","update"])&&(lt=!0),at==="bun"&&It(["add","install","update"])&&(lt=!0),at==="deno"&&ut(["install","add"])&&(lt=!0),at==="pip"&&ut(["install","download"])&&(lt=!0),at==="pip3"&&ut(["install","download"])&&(lt=!0),at==="cargo"&&ut(["install","add"])&&(lt=!0),["bash","sh","zsh","fish"].includes(at)&&ut(["-c"])&&(lt=!0),at==="cmd"&&ut(["/c"])&&(lt=!0),lt&&(ye="deny",Oe=!0)}!ye&&qe&&(ye="deny")}!we&&!ye&&le&&(ye="allow")}else le&&(ye="allow");let be=ye,ee="";ye==="deny"&&(Oe?ee="network":qe?ee="settings":ee="prohibited");let ue=!1,ce="",Be=[],et=0,xe=!1;if(!be){if(M==="write_file"||M==="update_file")try{let Ae=O(z.args),{path:Ve}=Ae;if(Ve){let ke=Q.resolve(process.cwd(),Ve),$t=ut=>ut?ut.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,It=>It.toUpperCase()):"",Qt=$t(ke),dn="",at=!1,Zt=await ms(),lt=$t(Zt?.file_focused);if(Zt&&lt===Qt&&Zt.full_content?(dn=Zt.full_content,at=!0):De.existsSync(ke)&&(dn=De.readFileSync(ke,"utf8"),at=!0),ce=dn,await pt.recordFileChange(ke,dn),at){let ut=dn;if(M==="write_file")ut=Ae.content||Ae.newContent||"";else{let{patchPairs:It,allowMultiple:bn,error:kn}=Ao(Ae);if(kn){let Ct=`[TOOL RESULT]: ERROR: ${kn}`;Z.push({role:"user",text:Ct}),await Lt("toolFailure"),t.onToolResult&&t.onToolResult("failure",M),yield{type:"tool_result",content:Ct,toolName:M},Ge++;continue}let Ss=Ae.allowMultiple!==void 0?Ae.allowMultiple===!0||String(Ae.allowMultiple).toLowerCase()==="true":bn;et=It.length;let Cn=vo(dn,It,{allowMultiple:Ss});ut=Cn.content,Be=Cn.results;let yo=Be.filter(Ct=>Ct.success),Ot=Be.filter(Ct=>!Ct.success);if(yo.length===0){let Ct=`[TOOL RESULT]: ERROR: Failed to apply patches to [${Q.basename(ke)}].
664
+ ${Ot.map(Hs=>` \u2022 ${Hs.error}`).join(`
665
+ `)}`,Ts=`\u2714 Edited: ${Q.basename(ke.replaceAll("\\","/"))}`,js=115;process.stdout.isTTY&&(js=process.stdout.columns-5||120);let Rs=Math.min(Ts.length+4,js),wo=`${Ts.padEnd(Rs-2).substring(0,Rs-2)}`;yield{type:"visual_feedback",content:gn(`${We?`
666
+ `:""}${wo}`)},We=!1,Z.push({role:"user",text:Ct}),await Lt("toolFailure"),t.onToolResult&&t.onToolResult("failure",M),yield{type:"tool_result",content:Ct,toolName:M},Ge++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${Q.basename(ke)}`},Yr(ke,dn,ut),ue=!0,await new Promise(It=>setTimeout(It,50))}else if(M==="write_file"){let ut=Ae.content||Ae.newContent||"",It=ut.endsWith(`
667
+ `)?ut:ut+`
668
+ `;De.existsSync(ke)||(xe=!0,De.mkdirSync(Q.dirname(ke),{recursive:!0}),De.writeFileSync(ke,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${Q.basename(ke)}`},Yr(ke,"",It),ue=!0,await new Promise(bn=>setTimeout(bn,50))}}}catch(Ae){console.error("Simulation/Diff Error:",Ae)}let Fe=null;Kr(Ae=>{Fe=Ae});let it=t.onToolApproval;if(be=await new Promise(async Ae=>{let Ve=setInterval(()=>{Fe&&(Wo.onIDEApproval&&Wo.onIDEApproval(Fe),clearInterval(Ve),Ae(Fe))},100);try{let ke=await it(M,z.args);clearInterval(Ve),Ae(ke)}catch{clearInterval(Ve),Ae("deny")}}),Kr(null),M==="write_file"||M==="update_file"){let{path:Ae}=O(z.args);if(Ae){let Ve=Q.resolve(process.cwd(),Ae);if(ka(Ve,be),be==="deny"&&xe&&De.existsSync(Ve))try{De.unlinkSync(Ve)}catch{}}}be==="deny"&&(ee="user")}if(be==="allow"&&ue&&Uo()){let{path:Fe}=O(z.args),it=Q.resolve(process.cwd(),Fe),Ae=Ot=>Ot?Q.resolve(Ot).replace(/\\/g,"/").toLowerCase():"",Ve=await ms(),ke="";Ve&&Ve.file_focused&&Ae(Ve.file_focused)===Ae(it)&&Ve.full_content&&(ke=Ve.full_content),!ke&&De.existsSync(it)&&(ke=De.readFileSync(it,"utf8"),ke||(await new Promise(Ot=>setTimeout(Ot,100)),ke=De.readFileSync(it,"utf8")));let $t=ke.split(/\r?\n/),Qt=$t.length,dn=Buffer.byteLength(ke,"utf8"),at="";ce&&(at=`Old File contents:
669
+ ${ce.split(/\r?\n/).map((Ct,Ts)=>`${Ts+1} | ${Ct}`).join(`
670
670
  `)}
671
671
 
672
- `);let Qt="";if(Jt<=100)Qt=Et.join(`
673
- `);else{let vt=Et.slice(0,50).join(`
674
- `),_t=Et.slice(-50).join(`
675
- `);Qt=`${vt}
672
+ `);let Zt="";if(Qt<=100)Zt=$t.join(`
673
+ `);else{let Ot=$t.slice(0,50).join(`
674
+ `),Ct=$t.slice(-50).join(`
675
+ `);Zt=`${Ot}
676
676
 
677
- ... [${Jt-100} lines truncated for history stability] ...
677
+ ... [${Qt-100} lines truncated for history stability] ...
678
678
 
679
- ${_t}`}let at="";if(M==="update_file"){let vt=Oo(ce,ke,Be,12,t?.compressToolResults||jo?.systemSettings?.compressToolResults);at=`SUCCESS: File [${Fe}] updated via IDE Companion (May have user edits). [${Be.length}/${et}] blocks applied.
679
+ ${Ct}`}let lt="";if(M==="update_file"){let Ot=Io(ce,ke,Be,12,t?.compressToolResults||Wo?.systemSettings?.compressToolResults);lt=`SUCCESS: File [${Fe}] updated via IDE Companion (May have user edits). [${Be.length}/${et}] blocks applied.
680
680
 
681
- ${vt}`}else{let vt=ke.split(/\r?\n/),_t=vt.length,Rs=Buffer.byteLength(ke,"utf8"),Hs="";ce&&(Hs=`Old File contents:
682
- ${ce.split(/\r?\n/).map((Gs,Xa)=>`${Xa+1} | ${Gs}`).join(`
681
+ ${Ot}`}else{let Ot=ke.split(/\r?\n/),Ct=Ot.length,Ts=Buffer.byteLength(ke,"utf8"),js="";ce&&(js=`Old File contents:
682
+ ${ce.split(/\r?\n/).map((Hs,Ja)=>`${Ja+1} | ${Hs}`).join(`
683
683
  `)}
684
684
 
685
- `);let Es="";if(_t<=100)Es=vt.join(`
686
- `);else{let xo=vt.slice(0,50).join(`
687
- `),Gs=vt.slice(-50).join(`
688
- `);Es=`${xo}
685
+ `);let Rs="";if(Ct<=100)Rs=Ot.join(`
686
+ `);else{let wo=Ot.slice(0,50).join(`
687
+ `),Hs=Ot.slice(-50).join(`
688
+ `);Rs=`${wo}
689
689
 
690
- ... [${_t-100} lines truncated] ...
690
+ ... [${Ct-100} lines truncated] ...
691
691
 
692
- ${Gs}`}at=`SUCCESS: File [${Fe}] saved via IDE Companion (May have user edits).
693
- - Stats: [${_t} lines, ${(Rs/1024).toFixed(1)} KB]
694
- ${Hs}- Content Preview:
692
+ ${Hs}`}lt=`SUCCESS: File [${Fe}] saved via IDE Companion (May have user edits).
693
+ - Stats: [${Ct} lines, ${(Ts/1024).toFixed(1)} KB]
694
+ ${js}- Content Preview:
695
695
 
696
- ${Es}`}let At=`${Fe?"\u2714":"\u2718"} ${M==="write_file"?"Created":"Edited"}: ${Fe.replaceAll("\\","/")||"No File Changes"}`,kn=115;process.stdout.isTTY&&(kn=process.stdout.columns-5||120);let Sn=Math.min(At.length+4,kn),Ts=`${At.padEnd(Sn-2).substring(0,Sn-2)}`;yield{type:"visual_feedback",content:gn(`${We?`
697
- `:""}${Ts}`)},We=!1;let Mn=Date.now();q=Mn,yield{type:"tool_time",content:Mn-ge};let wo=`[TOOL RESULT]: ${at}`;Z.push({role:"user",text:wo}),cn=!0,await It("toolSuccess"),t.onToolResult&&t.onToolResult("success",M),yield{type:"tool_result",content:at,aiContent:wo,toolName:M},Ge++;continue}if(be==="deny"){let Fe=`Permission Denied: Prohibited ${M==="exec_command"?"Command":"file edit"}.`;if(ee==="user"?Fe="Permission Denied by User":ee==="settings"?Fe="Permission Denied by User Policy":ee==="network"?Fe="Permission Denied: Sandbox Network Access Disabled by User Policy.":ee==="prohibited"&&M==="exec_command"&&(Fe="Permission Denied: Prohibited Command in User Policy"),M==="write_file"||M==="update_file"){let Ae=`\u2718 ${M==="write_file"?"Write Cancelled":"Edit Denied"}: ${O(z.args).path.replaceAll("\\","/")||"..."}`,Ve=115;process.stdout.isTTY&&(Ve=process.stdout.columns-5||120);let ke=Math.min(Ae.length+4,Ve),Et=`${Ae.padEnd(ke-2).substring(0,ke-2)}`,Jt=` ${" ".repeat(ke)} `;yield{type:"visual_feedback",content:gn(`${We?`
698
- `:""}${Et}
699
- `)},We=!1}M==="exec_command"&&(await new Promise(it=>setTimeout(it,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${Fe}`),await new Promise(it=>setTimeout(it,50)),t.onExecEnd&&t.onExecEnd()),Z.push({role:"user",text:`[TOOL RESULT]: DENIED: ${Fe}`}),yield{type:"tool_result",content:`[TOOL RESULT]: DENIED: ${Fe}`},await It("toolDenied"),t.onToolResult&&t.onToolResult("denied",M),Ge++;continue}}if(re){let v=115;process.stdout.isTTY&&(v=process.stdout.columns-5||120);let K=Math.min(re.length+4,v),le=`${re.padEnd(K-2).substring(0,K-2)}`;yield{type:"visual_feedback",content:gn(`${We?`
700
- `:""}${le}${re.includes("\u2714")&&(re.includes("Created")||re.includes("Edited"))?"":`
701
- `}`)},We=!1}if(q>0){let v=Date.now()-q,K=Math.max(0,1e3-v);K>0&&await new Promise(le=>setTimeout(le,K))}let Un={chatId:d,history:n,onChunk:v=>t.onExecChunk?t.onExecChunk(v):null,onAskUser:t.onAskUser,systemSettings:t.systemSettings,mode:r,isMultiModal:zt(Se),onVisualFeedback:t.onVisualFeedback,onSubagentUpdate:t.onSubagentUpdate,onTokenChunk:t.onTokenChunk,modelName:Se,aiProvider:t.aiProvider,apiKey:t.apiKey,onUsage:t.onUsage};if(M==="write_file"||M==="update_file")try{let{path:v}=O(z.args);if(v){let K=Q.resolve(process.cwd(),v),le=await gs();le&&le.file_focused===K&&le.full_content&&(Un.forcedContent=le.full_content)}}catch{}tn.push(M);let Re=await uo(M,z.args,Un);if((M==="write_file"||M==="update_file")&&Re.startsWith("SUCCESS")){let{path:v}=O(z.args);if(v){let K=Q.resolve(process.cwd(),v);ka(K)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let Gt=Date.now();q=Gt,yield{type:"tool_time",content:Gt-ge},nn=Gt;let Xt=null;if(typeof Re=="object"&&Re.binaryPart&&(Xt=Re.binaryPart,Re=Re.text),M==="search_keyword"){let{keyword:v,path:K}=O(z.args),le=typeof Re=="string"&&Re.startsWith("[GLOB]");le&&(Re=Re.slice(6).trimStart());let ye=typeof Re=="string"&&Re.startsWith("[DIR]");ye&&(Re=Re.slice(5).trimStart());let we=0;if(Re){let Be=Re.match(/Found (\d+) match/i);Be&&(we=parseInt(Be[1]))}let qe=K?K.replace(/[\/\\]+$/,""):null,Oe=qe&&qe!=="."?`"${le?K:ye?`${qe}/*`:qe}"`:"./",be=`${v?"\u2714":"\u2718"} Searched: "${v||""}" in ${Oe.replaceAll("\\","/")} \u2192 ${we} Match${we===1?"":"es"}`,ee=115;process.stdout.isTTY&&(ee=process.stdout.columns-5||120);let ue=Math.min(be.length+4,ee),ce=`${be.padEnd(ue-2).substring(0,ue-2)}`;yield{type:"visual_feedback",content:gn(`${We?`
696
+ ${Rs}`}let It=`${Fe?"\u2714":"\u2718"} ${M==="write_file"?"Created":"Edited"}: ${Fe.replaceAll("\\","/")||"No File Changes"}`,bn=115;process.stdout.isTTY&&(bn=process.stdout.columns-5||120);let kn=Math.min(It.length+4,bn),Ss=`${It.padEnd(kn-2).substring(0,kn-2)}`;yield{type:"visual_feedback",content:gn(`${We?`
697
+ `:""}${Ss}`)},We=!1;let Cn=Date.now();q=Cn,yield{type:"tool_time",content:Cn-ge};let yo=`[TOOL RESULT]: ${lt}`;Z.push({role:"user",text:yo}),cn=!0,await Lt("toolSuccess"),t.onToolResult&&t.onToolResult("success",M),yield{type:"tool_result",content:lt,aiContent:yo,toolName:M},Ge++;continue}if(be==="deny"){let Fe=`Permission Denied: Prohibited ${M==="exec_command"?"Command":"file edit"}.`;if(ee==="user"?Fe="Permission Denied by User":ee==="settings"?Fe="Permission Denied by User Policy":ee==="network"?Fe="Permission Denied: Sandbox Network Access Disabled by User Policy.":ee==="prohibited"&&M==="exec_command"&&(Fe="Permission Denied: Prohibited Command in User Policy"),M==="write_file"||M==="update_file"){let Ae=`\u2718 ${M==="write_file"?"Write Cancelled":"Edit Denied"}: ${O(z.args).path.replaceAll("\\","/")||"..."}`,Ve=115;process.stdout.isTTY&&(Ve=process.stdout.columns-5||120);let ke=Math.min(Ae.length+4,Ve),$t=`${Ae.padEnd(ke-2).substring(0,ke-2)}`,Qt=` ${" ".repeat(ke)} `;yield{type:"visual_feedback",content:gn(`${We?`
698
+ `:""}${$t}
699
+ `)},We=!1}M==="exec_command"&&(await new Promise(it=>setTimeout(it,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${Fe}`),await new Promise(it=>setTimeout(it,50)),t.onExecEnd&&t.onExecEnd()),Z.push({role:"user",text:`[TOOL RESULT]: DENIED: ${Fe}`}),yield{type:"tool_result",content:`[TOOL RESULT]: DENIED: ${Fe}`},await Lt("toolDenied"),t.onToolResult&&t.onToolResult("denied",M),Ge++;continue}}if(ie){let v=115;process.stdout.isTTY&&(v=process.stdout.columns-5||120);let K=Math.min(ie.length+4,v),le=`${ie.padEnd(K-2).substring(0,K-2)}`;yield{type:"visual_feedback",content:gn(`${We?`
700
+ `:""}${le}${ie.includes("\u2714")&&(ie.includes("Created")||ie.includes("Edited"))?"":`
701
+ `}`)},We=!1}if(q>0){let v=Date.now()-q,K=Math.max(0,1e3-v);K>0&&await new Promise(le=>setTimeout(le,K))}let Un={chatId:d,history:n,onChunk:v=>t.onExecChunk?t.onExecChunk(v):null,onAskUser:t.onAskUser,systemSettings:t.systemSettings,mode:i,isMultiModal:zt(Se),onVisualFeedback:t.onVisualFeedback,onSubagentUpdate:t.onSubagentUpdate,onTokenChunk:t.onTokenChunk,modelName:Se,aiProvider:t.aiProvider,apiKey:t.apiKey,onUsage:t.onUsage};if(M==="write_file"||M==="update_file")try{let{path:v}=O(z.args);if(v){let K=Q.resolve(process.cwd(),v),le=await ms();le&&le.file_focused===K&&le.full_content&&(Un.forcedContent=le.full_content)}}catch{}nn.push(M);let Ee=await fo(M,z.args,Un);if((M==="write_file"||M==="update_file")&&Ee.startsWith("SUCCESS")){let{path:v}=O(z.args);if(v){let K=Q.resolve(process.cwd(),v);ba(K)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let Gt=Date.now();q=Gt,yield{type:"tool_time",content:Gt-ge},sn=Gt;let Jt=null;if(typeof Ee=="object"&&Ee.binaryPart&&(Jt=Ee.binaryPart,Ee=Ee.text),M==="search_keyword"){let{keyword:v,path:K}=O(z.args),le=typeof Ee=="string"&&Ee.startsWith("[GLOB]");le&&(Ee=Ee.slice(6).trimStart());let ye=typeof Ee=="string"&&Ee.startsWith("[DIR]");ye&&(Ee=Ee.slice(5).trimStart());let we=0;if(Ee){let Be=Ee.match(/Found (\d+) match/i);Be&&(we=parseInt(Be[1]))}let qe=K?K.replace(/[\/\\]+$/,""):null,Oe=qe&&qe!=="."?`"${le?K:ye?`${qe}/*`:qe}"`:"./",be=`${v?"\u2714":"\u2718"} Searched: "${v||""}" in ${Oe.replaceAll("\\","/")} \u2192 ${we} Match${we===1?"":"es"}`,ee=115;process.stdout.isTTY&&(ee=process.stdout.columns-5||120);let ue=Math.min(be.length+4,ee),ce=`${be.padEnd(ue-2).substring(0,ue-2)}`;yield{type:"visual_feedback",content:gn(`${We?`
702
702
  `:""}${ce}
703
- `)},We=!1}if(M==="EmergencyRollback"){let{method:v}=O(z.args);if(v==="forceRevert"){let K=0;if(Re){let be=Re.match(/Total\s*:\s*(\d+)/i);be&&(K=parseInt(be[1]))}let ye=Re&&Re.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 qe=Math.min(ye.length+4,we),Oe=`${ye.padEnd(qe-2).substring(0,qe-2)}`;yield{type:"visual_feedback",content:gn(`${We?`
703
+ `)},We=!1}if(M==="EmergencyRollback"){let{method:v}=O(z.args);if(v==="forceRevert"){let K=0;if(Ee){let be=Ee.match(/Total\s*:\s*(\d+)/i);be&&(K=parseInt(be[1]))}let ye=Ee&&Ee.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 qe=Math.min(ye.length+4,we),Oe=`${ye.padEnd(qe-2).substring(0,qe-2)}`;yield{type:"visual_feedback",content:gn(`${We?`
704
704
  `:""}${Oe}
705
705
  `)},We=!1}}if(M==="todo"){let{method:v,tasks:K,markDone:le}=O(z.args),ye="",we=[],qe=Oe=>{if(!Oe)return[];let be=Array.isArray(Oe)?Oe:[];if(be.length===0&&typeof Oe=="string"){let ee=Oe.trim();if(ee.startsWith("[")&&ee.endsWith("]")){let ue=ee.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);ue?be=ue.map(ce=>ce.slice(1,-1).replace(/\\(.)/g,"$1")):be=ee.slice(1,-1).split(",").map(ce=>ce.trim()).filter(Boolean)}else be=Oe.split(`
706
- `)}return be.filter(ee=>String(ee).trim()).map(ee=>{let ue=String(ee).trim();return ue.startsWith("- [")?ue.substring(6).trim():ue})};if(v==="create"?(ye="\x1B[32m\u2192\x1B[0m Created Goals",we=qe(K).map(Oe=>`\x1B[90m\u25CB\x1B[0m ${Oe}`)):v==="append"?(ye="\x1B[34m\u2795\x1B[0m Added New Goals",we=qe(K).map(Oe=>`\x1B[90m\u25CB\x1B[0m ${Oe}`)):v==="get"&&(ye=le?"\x1B[36m\u21BB\x1B[0m Updated Goals":"\x1B[35m\u2022\x1B[0m Reviewed Goals",we=(Re||"").split(`
706
+ `)}return be.filter(ee=>String(ee).trim()).map(ee=>{let ue=String(ee).trim();return ue.startsWith("- [")?ue.substring(6).trim():ue})};if(v==="create"?(ye="\x1B[32m\u2192\x1B[0m Created Goals",we=qe(K).map(Oe=>`\x1B[90m\u25CB\x1B[0m ${Oe}`)):v==="append"?(ye="\x1B[34m\u2795\x1B[0m Added New Goals",we=qe(K).map(Oe=>`\x1B[90m\u25CB\x1B[0m ${Oe}`)):v==="get"&&(ye=le?"\x1B[36m\u21BB\x1B[0m Updated Goals":"\x1B[35m\u2022\x1B[0m Reviewed Goals",we=(Ee||"").split(`
707
707
  `).slice(1).join(`
708
708
  `).split(`
709
709
  `).filter(be=>be.trim().startsWith("- [")).map(be=>{let ee=be.trim(),ue=ee.startsWith("- [x]");return`${ue?"\x1B[32m\u2714\x1B[0m":"\x1B[90m\u25CB\x1B[0m"} ${ue?"\x1B[90m":"\x1B[37m"}${ee.substring(6).trim()}\x1B[0m`})),ye&&we.length>0){let Oe=[`${ye}`,...we.map(be=>` ${be}`)].join(`
710
710
  `);yield{type:"visual_feedback",content:gn(`${We?`
711
711
  `:""}${Oe}
712
- `)},We=!1}}M==="exec_command"&&t.onExecEnd&&(await new Promise(v=>setTimeout(v,800)),t.onExecEnd());let $n=Re&&Re.startsWith("DENIED:");Re&&!Re.startsWith("ERROR:")&&!$n?(await It("toolSuccess"),t.onToolResult&&t.onToolResult("success",M)):$n||(await It("toolFailure"),t.onToolResult&&t.onToolResult("failure",M));let qt=(Re||"").toString().replaceAll("[UI_CONTEXT]","");qt.includes("[[VERIFIED]]")&&(qt=qt.replace(/\[\[VERIFIED\]\][\s\S]*?\[\[\/VERIFIED\]\]/g,`[SYSTEM NOTE]: Patch Block matched & applied successfully. Large Block omitted to conserve context.
713
- `));let Cn;if(qt.startsWith("[[SAME]]")){let K=qt.replace(/^\[\[SAME\]\]\s*\r?\n?/,"").split(/\r?\n/),le=K.filter(we=>we.startsWith("SUCCESS:")||we.trim().startsWith("- Stats:"));Cn=`[TOOL RESULT]: ${le.length>0?le.join(`
712
+ `)},We=!1}}M==="exec_command"&&t.onExecEnd&&(await new Promise(v=>setTimeout(v,800)),t.onExecEnd());let _n=Ee&&Ee.startsWith("DENIED:");Ee&&!Ee.startsWith("ERROR:")&&!_n?(await Lt("toolSuccess"),t.onToolResult&&t.onToolResult("success",M)):_n||(await Lt("toolFailure"),t.onToolResult&&t.onToolResult("failure",M));let qt=(Ee||"").toString().replaceAll("[UI_CONTEXT]","");qt.includes("[[VERIFIED]]")&&(qt=qt.replace(/\[\[VERIFIED\]\][\s\S]*?\[\[\/VERIFIED\]\]/g,`[SYSTEM NOTE]: Patch Block matched & applied successfully. Large Block omitted to conserve context.
713
+ `));let $n;if(qt.startsWith("[[SAME]]")){let K=qt.replace(/^\[\[SAME\]\]\s*\r?\n?/,"").split(/\r?\n/),le=K.filter(we=>we.startsWith("SUCCESS:")||we.trim().startsWith("- Stats:"));$n=`[TOOL RESULT]: ${le.length>0?le.join(`
714
714
  `):K.slice(0,2).join(`
715
715
  `)}
716
- [SYSTEM NOTE]: Content verified and persisted to disk. Full preview omitted to conserve context.`}else Cn=`[TOOL RESULT]: ${qt}`;Z.push({role:"user",text:Cn,binaryPart:Xt}),cn=!0;let Me=`[TOOL RESULT]: ${Re.replaceAll(`[[VERIFIED]]
716
+ [SYSTEM NOTE]: Content verified and persisted to disk. Full preview omitted to conserve context.`}else $n=`[TOOL RESULT]: ${qt}`;Z.push({role:"user",text:$n,binaryPart:Jt}),cn=!0;let Me=`[TOOL RESULT]: ${Ee.replaceAll(`[[VERIFIED]]
717
717
  `,"").replaceAll(`
718
- [[/VERIFIED]]`,"")||""}`;(M==="view_file"||M==="web_scrape"||M==="file_map")&&(Me=`[TOOL RESULT]: ${re} (Context Locked for UI Clarity)`),yield{type:"tool_result",content:Me,aiContent:Cn,binaryPart:Xt,toolName:M},M==="memory"&&Re.includes("SUCCESS")&&(yield{type:"memory_updated"}),Ge++}if(u==="Google"&&xn&&Date.now()-Yo>=150){yield*ss();let z=Ws(xn);for(let ge of z)yield ge;xn="",Yo=Date.now()}}P.usageMetadata&&(Rn=P.usageMetadata),Rn&&(yield{type:"liveTokens",content:Rn.totalTokenCount})}if(he&&(he=!1,jt?Ke+="</think>":(de+="</think>",u==="Google"?xn+="</think>":yield{type:"text",content:"</think>"})),jt&&Ke.length>0){let P=0,te=Math.min(tt.length,Ke.length);for(let G=te;G>0;G--)if(tt.endsWith(Ke.substring(0,G))){P=G;break}let W=Ke.substring(P);if(W){let Te=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(tt)?W.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):W.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(Te)if(de+=Te,u==="Google")xn+=Te;else{yield*ss();let me=Ws(Te);for(let fe of me)yield fe}}jt=!1,Ke=""}if(yield*ss(),Ot)break;let js=(de||"").trim(),Ga=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(js.toLowerCase())||/\[\[END\]\]/i.test(js.toLowerCase()),qa=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(js.toLowerCase()),za=Z.length>0||Ut!==null,Vo=js.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/gi,"").trim(),Ka=/(\p{Emoji_Presentation}|\p{Extended_Pictographic})$/u.test(Vo),Ya=/([.!?"'*_`|\]\)”’~~]+|\s|`{3}|[\u200B-\u200D\uFEFF])$/u.test(Vo.trim()),Va=/[.!?}"'`’“”]$|```$/s.test(Vo)||Ya||Ka;!Ga&&!qa&&!za&&js.length>0,Ze=!0,await It("agent",u)}catch(Ce){if(Ot){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
718
+ [[/VERIFIED]]`,"")||""}`;(M==="view_file"||M==="web_scrape"||M==="file_map")&&(Me=`[TOOL RESULT]: ${ie} (Context Locked for UI Clarity)`),yield{type:"tool_result",content:Me,aiContent:$n,binaryPart:Jt,toolName:M},M==="memory"&&Ee.includes("SUCCESS")&&(yield{type:"memory_updated"}),Ge++}if(u==="Google"&&Pt&&Date.now()-Ko>=150){yield*ns();let z=Us(Pt);for(let ge of z)yield ge;Pt="",Ko=Date.now()}}P.usageMetadata&&(Tn=P.usageMetadata),Tn&&(yield{type:"liveTokens",content:Tn.totalTokenCount})}if(he&&(he=!1,Ht?Ke+="</think>":(de+="</think>",u==="Google"?Pt+="</think>":yield{type:"text",content:"</think>"})),Ht&&Ke.length>0){let P=0,te=Math.min(tt.length,Ke.length);for(let G=te;G>0;G--)if(tt.endsWith(Ke.substring(0,G))){P=G;break}let W=Ke.substring(P);if(W){let Te=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(tt)?W.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):W.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(Te)if(de+=Te,u==="Google")Pt+=Te;else{yield*ns();let me=Us(Te);for(let fe of me)yield fe}}Ht=!1,Ke=""}if(yield*ns(),Dt)break;let Ws=(de||"").trim(),qa=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(Ws.toLowerCase())||/\[\[END\]\]/i.test(Ws.toLowerCase()),za=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(Ws.toLowerCase()),Ka=Z.length>0||Wt!==null,Yo=Ws.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/gi,"").trim(),Ya=/(\p{Emoji_Presentation}|\p{Extended_Pictographic})$/u.test(Yo),Va=/([.!?"'*_`|\]\)”’~~]+|\s|`{3}|[\u200B-\u200D\uFEFF])$/u.test(Yo.trim()),Xa=/[.!?}"'`’“”]$|```$/s.test(Yo)||Va||Ya;!qa&&!za&&!Ka&&Ws.length>0,Ze=!0,await Lt("agent",u)}catch(Re){if(Dt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
719
719
 
720
- \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(String(Ce).includes("Incomplete JSON segment at the end")){he&&(he=!1,jt?Ke+="</think>":(de+="</think>",yield{type:"text",content:"</think>"})),Ze=!0,await It("agent",u);break}if(he&&(he=!1,jt?Ke+="</think>":de+="</think>"),jt&&Ke.length>0){let ns=0,on=Math.min(tt.length,Ke.length);for(let Dt=on;Dt>0;Dt--)if(tt.endsWith(Ke.substring(0,Dt))){ns=Dt;break}let Lt=Ke.substring(ns);if(Lt){let Ht=/(?:<(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,"");Ht&&(de+=Ht)}jt=!1,Ke=""}let se=Ce instanceof Error?(()=>{try{return JSON.parse(JSON.parse(Ce.message).error.message).error.message}catch{return String(Ce)}})():String(Ce),st=new Date().toLocaleString(),Ct=Q.join(fn,"agent");De.existsSync(Ct)||De.mkdirSync(Ct,{recursive:!0}),De.appendFileSync(Q.join(Ct,"error.log"),`ERROR [${st}]: ${se}
720
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(String(Re).includes("Incomplete JSON segment at the end")){he&&(he=!1,Ht?Ke+="</think>":(de+="</think>",yield{type:"text",content:"</think>"})),Ze=!0,await Lt("agent",u);break}if(he&&(he=!1,Ht?Ke+="</think>":de+="</think>"),Ht&&Ke.length>0){let Bn=0,Xt=Math.min(tt.length,Ke.length);for(let rt=Xt;rt>0;rt--)if(tt.endsWith(Ke.substring(0,rt))){Bn=rt;break}let vt=Ke.substring(Bn);if(vt){let Pt=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(tt)?vt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):vt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");Pt&&(de+=Pt)}Ht=!1,Ke=""}let se=Re instanceof Error?(()=>{try{return JSON.parse(JSON.parse(Re.message).error.message).error.message}catch{return String(Re)}})():String(Re),st=new Date().toLocaleString(),At=Q.join(fn,"agent");De.existsSync(At)||De.mkdirSync(At,{recursive:!0}),De.appendFileSync(Q.join(At,"error.log"),`ERROR [${st}]: ${se}
721
721
 
722
722
  ----------------------------------------------------------------------
723
723
 
724
- `);let sn=Ce.status||Ce.statusCode||Ce.code;if(!(sn&&(sn>=500&&sn<600||sn===408||sn===429)||!sn&&(/status[ :]+(5\d\d|408|429)/i.test(String(Ce))||/code[ :]+(5\d\d|408|429)/i.test(String(Ce))||/(500|503|408|429)/.test(String(Ce))))){if(He<yn-3)throw Ce;yield{type:"text",content:se},yield{type:"status",content:"Error Occured"}}if(de.trim().length>0||Je>1)if(Je<=yn){Je++;let ns=Math.min(1e3*Math.pow(2,Je-1),24e3);if(de.trim().length>0){k.push({role:"agent",text:de});let on=`[system]
724
+ `);let on=Re.status||Re.statusCode||Re.code,Et=String(Re).includes("replicas at capacity");if(!(on&&(on>=500&&on<600||on===408||on===429||Et)||!on&&(/status[ :]+(5\d\d|408|429)/i.test(String(Re))||/code[ :]+(5\d\d|408|429)/i.test(String(Re))||/(500|503|408|429)/.test(String(Re))))){if(He<yn-3)throw Re;yield{type:"text",content:se},yield{type:"status",content:"Error Occured"}}if(de.trim().length>0||Je>1)if(Je<=yn){Je++;let Bn=Math.min(1e3*Math.pow(2,Je-1),24e3);if(de.trim().length>0){k.push({role:"agent",text:de});let Xt=`[system]
725
725
  - seamless continuation: resume immediately. pick up from last words with zero gap/disruption
726
726
  - no repetition: do not repeat any text already written
727
727
  - no re-think: do not restart or open <think> if reasoning already started. continue the thinking and close thinking block </think> before chat output
728
728
  - mid-tool safety: if cutoff was mid-tool call, restart that tool call from start
729
- - stealth: do not mention/apologize for cutoff [/system]`;Z.length>0?Z.forEach((Lt,Dt)=>{Dt===Z.length-1?k.push({...Lt,text:`${Lt.text}
729
+ - stealth: do not mention/apologize for cutoff [/system]`;Z.length>0?Z.forEach((vt,rt)=>{rt===Z.length-1?k.push({...vt,text:`${vt.text}
730
730
 
731
- ${on}`}):k.push(Lt)}):k.push({role:"user",text:on}),tt+=de}for(let on=ns/1e3;on>0&&!Ot;on--)yield{type:"status",content:`Error Occured. Recovering Stream (${Je}/${yn}) [Retrying in ${on.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)
732
- Error log can be found in \`/export logs\``);else if(He<=yn){He++,Je=1,tt="";let ns=Math.min(1e3*Math.pow(2,He-1),32e3),on=.8+Math.random()*.4,Lt=Math.round(ns*on);Qn=!0,yield{type:"status",content:`Trying to reach ${e} (${He}/${yn}) [Retrying in ${(Lt/1e3).toFixed(0)}s]`};for(let Dt=Lt/1e3;Dt>0&&!Ot;Dt--)yield{type:"status",content:`Trying to reach ${e} (${He}/${yn}) [Retrying in ${Dt.toFixed(0)}s]`},await new Promise(Ht=>setTimeout(Ht,1e3));yield{type:"status",content:`Trying to reach ${e}`}}else throw new Error(`Model ${e} cannot be reached. (Failed ${yn} times)
733
- Error log can be found in \`/export logs\``)}}if(Rn){let he=Rn.totalTokenCount||0,Ce=Rn.cachedContentTokenCount||0,se=(Rn.candidatesTokenCount||0)+(Rn.thoughtsTokenCount||0);await Kt("tokens",he,u,Se),Ce>0&&await Kt("cachedTokens",Ce,u,Se),se>0&&await Kt("candidateTokens",se,u,Se),yield{type:"usage",content:Rn}}wr.push(de);let Nn=de;de.match(/(?:<think>|\[think\])([\s\S]*?)(?:<\/think>|\[\/think\])/i)&&(Nn=de.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/i,""));let es=Ia(de),_n=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(es.toLowerCase())||/\[\[END\]\]/i.test(es.toLowerCase())||!0,Dc=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(es.toLowerCase()),Pc=Ge>0;yield{type:"status",content:"Thinking"};let Wa=Cc(de,/(\[\s*(turn\s*:)?\s*(continue|finish)\s*\]|\[\[END\]\])/gi,"").trim(),ts=(_n||Z.length===0)&&!Wt&&!wn&&!En;if(ts=Z.length===0?ts:!1,ts=Zn||go?!1:ts,de&&de.trim().endsWith('")]')&&Z.length===0&&(ts=!1),ts){let he=wr.join(`
734
- `),Ce=he.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").trim();yield{type:"interactive_turn_finished",data:{agentText:T,fullAgentTextRaw:he,history:[...k],needTitle:S}},k.length>0&&k[k.length-1].role==="agent"?k[k.length-1].text=Ce:k.push({role:"agent",text:Ce}),k.forEach(se=>{if(se.role==="user"&&se.text&&(se.text=se.text.replace(/\n\[COMPILE ERROR\][\s\S]*?\[\/ERROR\]/g,""),se.text=se.text.replaceAll(`
731
+ ${Xt}`}):k.push(vt)}):k.push({role:"user",text:Xt}),tt+=de}for(let Xt=Bn/1e3;Xt>0&&!Dt;Xt--)yield{type:"status",content:`Error Occured. Recovering Stream (${Je}/${yn}) [Retrying in ${Xt.toFixed(0)}s]...`},await new Promise(vt=>setTimeout(vt,1e3));yield{type:"status",content:"Error Occured. Recovering Stream..."}}else throw new Error(`Stream collapsed too many times. (Failed to resolve ${yn} times)
732
+ Error log can be found in \`/export logs\``);else if(He<=yn){He++,Je=1,tt="";let Bn=Math.min(1e3*Math.pow(2,He-1),32e3),Xt=.8+Math.random()*.4,vt=Math.round(Bn*Xt);Qn=!0,yield{type:"status",content:`Trying to reach ${e} (${He}/${yn}) [Retrying in ${(vt/1e3).toFixed(0)}s]`};for(let rt=vt/1e3;rt>0&&!Dt;rt--)yield{type:"status",content:`Trying to reach ${e} (${He}/${yn}) [Retrying in ${rt.toFixed(0)}s]`},await new Promise(Pt=>setTimeout(Pt,1e3));yield{type:"status",content:`Trying to reach ${e}`}}else throw new Error(`Model ${e} cannot be reached. (Failed ${yn} times)
733
+ Error log can be found in \`/export logs\``)}}if(Tn){let he=Tn.totalTokenCount||0,Re=Tn.cachedContentTokenCount||0,se=(Tn.candidatesTokenCount||0)+(Tn.thoughtsTokenCount||0);await Kt("tokens",he,u,Se),Re>0&&await Kt("cachedTokens",Re,u,Se),se>0&&await Kt("candidateTokens",se,u,Se),yield{type:"usage",content:Tn}}yi.push(de);let Fn=de;de.match(/(?:<think>|\[think\])([\s\S]*?)(?:<\/think>|\[\/think\])/i)&&(Fn=de.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/i,""));let es=va(de),En=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(es.toLowerCase())||/\[\[END\]\]/i.test(es.toLowerCase())||!0,Pc=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(es.toLowerCase()),Fc=Ge>0;yield{type:"status",content:"Thinking"};let Wa=Mc(de,/(\[\s*(turn\s*:)?\s*(continue|finish)\s*\]|\[\[END\]\])/gi,"").trim(),ts=(En||Z.length===0)&&!jt&&!wn&&!Rn;if(ts=Z.length===0?ts:!1,ts=Zn||mo?!1:ts,de&&de.trim().endsWith('")]')&&Z.length===0&&(ts=!1),ts){let he=yi.join(`
734
+ `),Re=he.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").trim();yield{type:"interactive_turn_finished",data:{agentText:T,fullAgentTextRaw:he,history:[...k],needTitle:S}},k.length>0&&k[k.length-1].role==="agent"?k[k.length-1].text=Re:k.push({role:"agent",text:Re}),k.forEach(se=>{if(se.role==="user"&&se.text&&(se.text=se.text.replace(/\n\[COMPILE ERROR\][\s\S]*?\[\/ERROR\]/g,""),se.text=se.text.replaceAll(`
735
735
 
736
736
  [system] user question. resolve this specific query within '[ANSWER] ... [/ANSWER]' concisely, naturally [/system]
737
737
  `,"").replaceAll(`[system] user question. resolve this specific query within '[ANSWER] ... [/ANSWER]' concisely, naturally
738
738
  **strictly follow thinking policy as high priority. do not start a response without <think>...</think>** [/system]
739
739
  `,"").replaceAll(`[system] **strictly follow thinking policy as high priority. do not start a response without <think>...</think>** [/system]
740
- `,"").replaceAll(/\n\[system\] WARNING, Turn Limit Impending: Step \d+\/\d+\. Wrap up quickly\/prompt user to continue & use \[\[END\]\] quickly\. \[\/system\]/g,""),se.text=se.text.replaceAll(/\n\[system\] File Changes:\n(?:\* .+ \(created|modified|deleted\)\n)*\[\/system\]/g,""),(u==="Mistral"||u==="Google"&&e?.toLowerCase().startsWith("gemma"))&&se.text.startsWith("[TOOL RESULT]"))){let Ct=`
741
- [system] Tool result received. Analyze output and proceed with your turn [/system]`,sn=`
742
- [system] Tool result received. Analyze output and proceed with your turn. **strictly follow thinking policy. do not start a response without <think>...</think>** [/system]`;se.text=se.text.replaceAll(sn,"").replaceAll(Ct,"").trim()}}),yield{type:"status",content:"[end]"}}if(ts)break;let ja=Wa.trim()||"*Working...*";if(k.push({role:"agent",text:ja}),Z.length>0||cn){if(Z.length>0){let he=Z.map(Ct=>Ct.text).join(`
740
+ `,"").replaceAll(/\n\[system\] WARNING, Turn Limit Impending: Step \d+\/\d+\. Wrap up quickly\/prompt user to continue & use \[\[END\]\] quickly\. \[\/system\]/g,""),se.text=se.text.replaceAll(/\n\[system\] File Changes:\n(?:\* .+ \(created|modified|deleted\)\n)*\[\/system\]/g,""),(u==="Mistral"||u==="Google"&&e?.toLowerCase().startsWith("gemma"))&&se.text.startsWith("[TOOL RESULT]"))){let At=`
741
+ [system] Tool result received. Analyze output and proceed with your turn [/system]`,on=`
742
+ [system] Tool result received. Analyze output and proceed with your turn. **strictly follow thinking policy. do not start a response without <think>...</think>** [/system]`;se.text=se.text.replaceAll(on,"").replaceAll(At,"").trim()}}),yield{type:"status",content:"[end]"}}if(ts)break;let ja=Wa.trim()||"*Working...*";if(k.push({role:"agent",text:ja}),Z.length>0||cn){if(Z.length>0){let he=Z.map(At=>At.text).join(`
743
743
 
744
744
  `),se=(de.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/gi,"").match(/\[tool:functions/g)||[]).length;if(Z.length<se){he+=`
745
745
 
746
- [SYSTEM] Only ${Z.length} out of ${se} attempted tool calls were executed. Verify proper schema compliance & try failed calls again [/SYSTEM]`;let Ct=se-Z.length;for(let sn=0;sn<Ct;sn++)await It("toolFailure")}let st=Z.find(Ct=>Ct.binaryPart)?.binaryPart||null;k.push({role:"user",text:he,binaryPart:st})}}else go||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&&!Wt?"STUTTERING DETECTED by Internal System. Re-calibrate your response & proceed.":`${Wt?" OVER THINKING":" LOOP"} DETECTED by Internal System${Wt?" for current EFFORT_LEVEL":""}. ${Wt?"If you have planned the task, prioritize execution/output":"If you have finished your task provide a simple summary and end"}`} [/SYSTEM]`}),Wt=!1,wn=!1,En=!1;l?.advanceRollback&&await Kn.recordTurnDelta(d,H+1,tn),go=Ge>0||cn}}catch(_){let C=(_ instanceof Error?(()=>{try{return JSON.parse(JSON.parse(_.message).error.message).error.message}catch{return _.message||String(_)}})():String(_)).replace(/^(Error:\s*)+/i,""),I=new Date().toLocaleString(),D=Q.join(fn,"agent");yield{type:"text",content:`\u2726 CRITICAL ERROR: ${C.includes("fetch failed")?"Failed to Connect. Check your Internet Connection or Wait a moment":C}
746
+ [SYSTEM] Only ${Z.length} out of ${se} attempted tool calls were executed. Verify proper schema compliance & try failed calls again [/SYSTEM]`;let At=se-Z.length;for(let on=0;on<At;on++)await Lt("toolFailure")}let st=Z.find(At=>At.binaryPart)?.binaryPart||null;k.push({role:"user",text:he,binaryPart:st})}}else mo||Zn?(k.push({role:"user",text:"[SYSTEM] Failed to execute some tools. Verify proper schema compliance & try again [/SYSTEM]"}),await Lt("toolFailure")):k.push({role:"user",text:`[SYSTEM] ${wn&&!jt?"STUTTERING DETECTED by Internal System. Re-calibrate your response & proceed.":`${jt?" OVER THINKING":" LOOP"} DETECTED by Internal System${jt?" for current EFFORT_LEVEL":""}. ${jt?"If you have planned the task, prioritize execution/output":"If you have finished your task provide a simple summary and end"}`} [/SYSTEM]`}),jt=!1,wn=!1,Rn=!1;l?.advanceRollback&&await Kn.recordTurnDelta(d,H+1,nn),mo=Ge>0||cn}}catch(_){let C=(_ instanceof Error?(()=>{try{return JSON.parse(JSON.parse(_.message).error.message).error.message}catch{return _.message||String(_)}})():String(_)).replace(/^(Error:\s*)+/i,""),I=new Date().toLocaleString(),D=Q.join(fn,"agent");yield{type:"text",content:`\u2726 CRITICAL ERROR: ${C.includes("fetch failed")?"Failed to Connect. Check your Internet Connection or Wait a moment":C}
747
747
  \u2800`},De.existsSync(D)||De.mkdirSync(D,{recursive:!0}),De.appendFileSync(Q.join(D,"error.log"),`CRITICAL ERROR [${I}]: ${_}
748
748
 
749
749
  ----------------------------------------------------------------------
750
750
 
751
- `),typeof flushGoogleBuffer=="function"&&(yield*flushGoogleBuffer()),yield{type:"tool_result",content:`ERROR: [INTERNAL CRITICAL] ${C}`}}finally{$&&(clearInterval($),$=null),typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),await ht.commitTransaction(),l?.advanceRollback&&await Kn.cleanup(d),await gs()}yield{type:"status",content:null}},Mm=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=(_=>{if(!_)return null;let k=_.toLowerCase();return k==="google"?"Google":k==="deepseek"?"DeepSeek":k==="openrouter"?"OpenRouter":k==="nvidia"?"NVIDIA":k==="mistral"?"Mistral":k==="ollama"?"Ollama":k==="crofai"||k==="crof"?"CrofAI":k==="inferx"?"InferX":k==="sensenova"?"SenseNova":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 _=await Zo(h.aiProvider);_&&(h.apiKey=_)}let w=_=>{if(!_||typeof _!="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 C of k)if(C.test(_))return{allowed:!1,reason:`Blocked potentially destructive or unsafe command pattern: "${C.source}"`};return{allowed:!0}},x=t||m||n?.modelName||n?.activeModel||r.activeModel,b=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",E=`-- TOOL DEFINITIONS (path = relative to CWD, path separator: '/') --
751
+ `),typeof flushGoogleBuffer=="function"&&(yield*flushGoogleBuffer()),yield{type:"tool_result",content:`ERROR: [INTERNAL CRITICAL] ${C}`}}finally{$&&(clearInterval($),$=null),typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),await pt.commitTransaction(),l?.advanceRollback&&await Kn.cleanup(d),await ms()}yield{type:"status",content:null}},Am=async(e,n,t=null,o=null,s=50,r=null,a=!1)=>{let i=await Nt(),h={...i,...n},d=process.env.SUBAGENT_MODEL?process.env.SUBAGENT_MODEL.trim():null,c=process.env.SUBAGENT_PROVIDER?process.env.SUBAGENT_PROVIDER.trim():null,l=new Date,f=`${l.getFullYear()}-${l.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(l.getDate()).padStart(2,"0")}, ${l.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}).replace(":","-")}`,p=(_=>{if(!_)return null;let k=_.toLowerCase();return k==="google"?"Google":k==="deepseek"?"DeepSeek":k==="openrouter"?"OpenRouter":k==="nvidia"?"NVIDIA":k==="mistral"?"Mistral":k==="ollama"?"Ollama":k==="crofai"||k==="crof"?"CrofAI":k==="inferx"?"InferX":k==="sensenova"?"SenseNova":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 _=await Qo(h.aiProvider);_&&(h.apiKey=_)}let w=_=>{if(!_||typeof _!="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 C of k)if(C.test(_))return{allowed:!1,reason:`Blocked potentially destructive or unsafe command pattern: "${C.source}"`};return{allowed:!0}},b=t||m||n?.modelName||n?.activeModel||i.activeModel,x=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",E=`-- TOOL DEFINITIONS (path = relative to CWD, path separator: '/') --
752
752
  To use tools, must output exactly '[tool:functions.ToolName(arg1="value1")]' structured string in chat response \u2190 no exception
753
753
  Tool Rules:
754
754
  - JSON escape literal escape sequences in tool arguments
@@ -763,20 +763,20 @@ Tool Rules:
763
763
 
764
764
  # Provided Tools
765
765
  **Communication Tools**
766
- - [tool:functions.Ask(question="...", optionA="title::description", ...MAX4)]. Ambiguity, path divergence, security risk. Ask, dont finish/guess. Keep titles short
767
- ${a?'- [tool:functions.AskMain(question="...")]. Communicate with PARENT/MAIN AGENT. When clarification/decision is needed for a task':""}
766
+ - Ask(question="...", optionA="title::description", ...MAX4). Ambiguity, path divergence, security risk. Ask, dont finish/guess. Keep titles short
767
+ ${a?'- AskMain(question="..."). Communicate with PARENT/MAIN AGENT. When clarification/decision is needed for a task':""}
768
768
 
769
769
  **Web Tools**
770
- - [tool:functions.WebSearch(query="...", aiMode="bool", limit="integer 3-10 aiMode: exclude")]. Proactive use for unknown info/docs. aiMode: LLM search
771
- - [tool:functions.WebScrape(url="...")]. Proactive use for specific webpage/docs/api
770
+ - WebSearch(query="...", aiMode="bool", limit="integer 3-10 aiMode: exclude"). Proactive use for unknown info/docs. aiMode: LLM search
771
+ - WebScrape(url="..."). Proactive use for specific webpage/docs/api
772
772
 
773
773
  **Workspace Tools**
774
- - [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
775
- - [tool:functions.ReadFolder(path="...", recurse="int 1-3")]. Minimize recursion
776
- - [tool:functions.ReadFile(path="...", startLine="int", endLine="int")]
777
- - [tool:functions.PatchFile(path="...", allowMultiple="bool, default: false", searchContent1="search string OR ^LINE:start..end$", newContent1="...", ...MAX15)]. Use small searchContent. Line Ranges must for large searchContent and escape sequences. ^...$ must for line ranges
778
- - [tool:functions.WriteFile(path="...", content="...")]. Creates/Overwrites. File Exist? PatchFile > WriteFile. VERIFY IMPORTS
779
- - [tool:functions.Run(command="...")]. Runs ${b==="Windows"?Hn()?"powershell":"windows CMD":"bash"} command. Destructive/Irreversible ops \u2192 Ask user`.trim(),R=`=== START SYSTEM PROMPT ===
774
+ - CodeSearch(keyword="...", path="dir/file/glob/regex, inclusion/exclusion ;-separated", fuzzy="bool false", regex="bool auto"). Find definitions, logic, relevant code, standard junk auto-excluded
775
+ - ReadFolder(path="...", recurse="int 1-3"). Minimize recursion
776
+ - ReadFile(path="...", startLine="int", endLine="int")
777
+ - PatchFile(path="...", allowMultiple="bool, default: false", searchContent1="search string OR ^LINE:start..end$", newContent1="...", ...MAX15). Use small searchContent. Line Ranges must for large searchContent and escape sequences. ^...$ must for line ranges
778
+ - WriteFile(path="...", content="..."). Creates/Overwrites. File Exist? PatchFile > WriteFile. VERIFY IMPORTS
779
+ - Run(command="..."). Runs ${x==="Windows"?Hn()?"powershell":"windows CMD":"bash"} command. Destructive/Irreversible ops \u2192 Ask user`.trim(),R=`=== START SYSTEM PROMPT ===
780
780
  You are a subagent helping the main FluxFlow CLI agent
781
781
  Your task is: "${e}"
782
782
 
@@ -789,30 +789,30 @@ On task completion, provide a detailed structured summary preferebly in Tables/B
789
789
 
790
790
  CWD: ${process.cwd()}
791
791
  Current Time: ${f}
792
- === END SYSTEM PROMPT ===`,S=[{role:"user",text:`Complete this task: ${e}`}],T=0,$="";for(;T<s;){if(Ot){if(n?.taskId&&typeof Xe<"u"){let U=Xe.find(j=>j.id===n.taskId);U&&(U.status="cancelled")}throw i&&i("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}if(n?.taskId&&typeof Xe<"u"){let U=Xe.find(j=>j.id===n.taskId);if(U&&U.status==="cancelled")throw i&&i("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}let _=S.map(U=>({role:U.role==="user"?"user":"model",parts:[{text:U.text}]}));i&&i(`[Subagent Turn ${T+1}]...`);let I=((await Ho(h,x,_,R,"Fast")).text||"").replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/gi,"").trim();$=I,i&&i(`[Subagent Response]
792
+ === END SYSTEM PROMPT ===`,S=[{role:"user",text:`Complete this task: ${e}`}],T=0,$="";for(;T<s;){if(Dt){if(n?.taskId&&typeof Xe<"u"){let U=Xe.find(j=>j.id===n.taskId);U&&(U.status="cancelled")}throw r&&r("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}if(n?.taskId&&typeof Xe<"u"){let U=Xe.find(j=>j.id===n.taskId);if(U&&U.status==="cancelled")throw r&&r("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}let _=S.map(U=>({role:U.role==="user"?"user":"model",parts:[{text:U.text}]}));r&&r(`[Subagent Turn ${T+1}]...`);let I=((await jo(h,b,_,R,"Fast")).text||"").replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/gi,"").trim();$=I,r&&r(`[Subagent Response]
793
793
  ${I}
794
- `),S.push({role:"agent",text:I});let D=Go(I);if(D.length===0)break;let B=D.filter(U=>U.toolName.toLowerCase()==="askmain"||U.toolName.toLowerCase()==="ask_main"),N=!1,Y="";for(let U of D){if(Ot){if(n?.taskId&&typeof Xe<"u"){let A=Xe.find(F=>F.id===n.taskId);A&&(A.status="cancelled")}throw new Error("Subagent task was cancelled.")}if(n?.taskId&&typeof Xe<"u"){let A=Xe.find(F=>F.id===n.taskId);if(A&&A.status==="cancelled")throw new Error("Subagent task was cancelled.")}let j=U.toolName.toLowerCase();if(j==="askmain"||j==="ask_main"){if(N)continue;N=!0;let A="";if(B.length===1?A=O(B[0].args).question||B[0].args:A=B.map((F,V)=>{let X=O(F.args);return`Q${V+1}: ${X.question||F.args}`}).join(`
795
- `),n.onAskMain){i&&i(`[Executing Tool] AskMain("${A}")...`);let F=await n.onAskMain(A);i&&i(`[Tool Result]
794
+ `),S.push({role:"agent",text:I});let D=Ho(I);if(D.length===0)break;let B=D.filter(U=>U.toolName.toLowerCase()==="askmain"||U.toolName.toLowerCase()==="ask_main"),N=!1,Y="";for(let U of D){if(Dt){if(n?.taskId&&typeof Xe<"u"){let A=Xe.find(F=>F.id===n.taskId);A&&(A.status="cancelled")}throw new Error("Subagent task was cancelled.")}if(n?.taskId&&typeof Xe<"u"){let A=Xe.find(F=>F.id===n.taskId);if(A&&A.status==="cancelled")throw new Error("Subagent task was cancelled.")}let j=U.toolName.toLowerCase();if(j==="askmain"||j==="ask_main"){if(N)continue;N=!0;let A="";if(B.length===1?A=O(B[0].args).question||B[0].args:A=B.map((F,V)=>{let X=O(F.args);return`Q${V+1}: ${X.question||F.args}`}).join(`
795
+ `),n.onAskMain){r&&r(`[Executing Tool] AskMain("${A}")...`);let F=await n.onAskMain(A);r&&r(`[Tool Result]
796
796
  Answer from Main Agent: ${F}
797
797
  `),Y+=`[TOOL RESULT for AskMain]: Answer from Main Agent: ${F}
798
798
 
799
- `,await It("toolSuccess")}else Y+=`[TOOL RESULT for AskMain]: ERROR: Main agent communication channel not available.
799
+ `,await Lt("toolSuccess")}else Y+=`[TOOL RESULT for AskMain]: ERROR: Main agent communication channel not available.
800
800
 
801
- `;continue}if(!(o?o.some(A=>A.toLowerCase()===j):!0)){let A=`ERROR: Tool [${U.toolName}] is not in the allowed tools list for this subagent.`;i&&i(`[Blocked Tool Call] ${U.toolName} - not allowed
801
+ `;continue}if(!(o?o.some(A=>A.toLowerCase()===j):!0)){let A=`ERROR: Tool [${U.toolName}] is not in the allowed tools list for this subagent.`;r&&r(`[Blocked Tool Call] ${U.toolName} - not allowed
802
802
  `),Y+=`${A}
803
803
 
804
- `;continue}if(j==="exec_command"||j==="execcommand"||j==="run"){let A=O(U.args).command||"",F=w(A);if(!F.allowed){let V=`ERROR: [SECURITY RESTRICTION] Subagent execution blocked command: ${F.reason}`;i&&i(`[Blocked Command] ${A} - ${F.reason}
804
+ `;continue}if(j==="exec_command"||j==="execcommand"||j==="run"){let A=O(U.args).command||"",F=w(A);if(!F.allowed){let V=`ERROR: [SECURITY RESTRICTION] Subagent execution blocked command: ${F.reason}`;r&&r(`[Blocked Command] ${A} - ${F.reason}
805
805
  `),Y+=`${V}
806
806
 
807
- `;continue}}let Ee="";if(j==="web_search"||j==="websearch")Ee=`\u2714 \x1B[95mSearched\x1B[0m: ${O(U.args).query||""}`;else if(j==="web_scrape"||j==="webscrape")Ee=`\u2714 \x1B[95mScraped\x1B[0m: ${O(U.args).url||""}`;else if(j==="search_keyword"||j==="searchkeyword"||j==="codesearch"||j==="code_search"){let A=O(U.args),F=A.keyword||"",V=A.path||"";Ee=`${F?"\u2714":"\u2718"} \x1B[95mSearched\x1B[0m: ${F||"No Query"}${V?` \u2192 ${V.replaceAll("\\","/")}`:""}`}else if(j==="view_file"||j==="viewfile"||j==="readfile")Ee=`\u2714 \x1B[95mRead\x1B[0m: ${(O(U.args).path||"").replaceAll("\\","/")}`;else if(j==="list_files"||j==="read_folder"||j==="readfolder"){let A=O(U.args).path||null,F=O(U.args).recurse||0;Ee=`${A?"\u2714":"\u2718"} \x1B[95mBrowsed\x1B[0m: ${A?`${A.replaceAll("\\","/")}${F>0?`${A.endsWith("/")?`*${F}`:`/*${F}`}`:`${A.endsWith("/")?"":"/"}`}`:""}`}else if(j==="write_file"||j==="writefile"){let A=O(U.args).path||null;Ee=`${A?"\u2714":"\u2718"} \x1B[95mCreated\x1B[0m: ${A?`${A.replaceAll("\\","/")}`:"No File Changes"}`}else if(j==="update_file"||j==="updatefile"||j==="patchfile"||j==="patch_file"||j==="patchfile"||j==="updatefile"){let A=O(U.args).path||null,F=O(U.args).content||null;Ee=`${A?"\u2714":"\u2718"} \x1B[95mEdited\x1B[0m: ${A?`${A.replaceAll("\\","/")}`:"No File Changes"}`}else if(j==="exec_command"||j==="execcommand"||j==="run"){let A=O(U.args).command||null;Ee=`${A?"\u2714":"\u2718"} \x1B[95mExecuted\x1B[0m: ${A?A.slice(0,100)+(A.length>100?"...":""):"No Command"}`}else if(j==="file_map"||j==="filemap"){let A=O(U.args).path||"";Ee=`${A?"\u2714":"\u2718"} \x1B[95mIndexed\x1B[0m: ${A?`${A.replaceAll("\\","/")}`:"File Not Found"}`}else if(j==="await"){let{time:A}=O(U.args),F=parseFloat(A)||0;F<10&&(F=10),F>180&&(F=180),Ee=`\u2714 \x1B[95mAwaiting\x1B[0m \u2192 ${(X=>{if(X>=60){let Ue=Math.floor(X/60),Ne=X%60;return`${Ue}m${Ne>0?` ${Ne}s`:""}`}return`${X}s`})(F)}`}else{let A=Zi[j]||U.toolName,F=xs(j,U.args);Ee=`\u2714 \x1B[95m${A}\x1B[0m${F?`: ${F}`:""}`}n.onVisualFeedback&&Ee&&n.onVisualFeedback(Ee),i&&i(`[Executing Tool] ${U.toolName}(${U.args})...`);try{let A=await uo(U.toolName,U.args,{...n,mode:"Flux"});if(i&&i(`[Tool Result]
807
+ `;continue}}let _e="";if(j==="web_search"||j==="websearch")_e=`\u2714 \x1B[95mSearched\x1B[0m: ${O(U.args).query||""}`;else if(j==="web_scrape"||j==="webscrape")_e=`\u2714 \x1B[95mScraped\x1B[0m: ${O(U.args).url||""}`;else if(j==="search_keyword"||j==="searchkeyword"||j==="codesearch"||j==="code_search"){let A=O(U.args),F=A.keyword||"",V=A.path||"";_e=`${F?"\u2714":"\u2718"} \x1B[95mSearched\x1B[0m: ${F||"No Query"}${V?` \u2192 ${V.replaceAll("\\","/")}`:""}`}else if(j==="view_file"||j==="viewfile"||j==="readfile")_e=`\u2714 \x1B[95mRead\x1B[0m: ${(O(U.args).path||"").replaceAll("\\","/")}`;else if(j==="list_files"||j==="read_folder"||j==="readfolder"){let A=O(U.args).path||null,F=O(U.args).recurse||0;_e=`${A?"\u2714":"\u2718"} \x1B[95mBrowsed\x1B[0m: ${A?`${A.replaceAll("\\","/")}${F>0?`${A.endsWith("/")?`*${F}`:`/*${F}`}`:`${A.endsWith("/")?"":"/"}`}`:""}`}else if(j==="write_file"||j==="writefile"){let A=O(U.args).path||null;_e=`${A?"\u2714":"\u2718"} \x1B[95mCreated\x1B[0m: ${A?`${A.replaceAll("\\","/")}`:"No File Changes"}`}else if(j==="update_file"||j==="updatefile"||j==="patchfile"||j==="patch_file"||j==="patchfile"||j==="updatefile"){let A=O(U.args).path||null,F=O(U.args).content||null;_e=`${A?"\u2714":"\u2718"} \x1B[95mEdited\x1B[0m: ${A?`${A.replaceAll("\\","/")}`:"No File Changes"}`}else if(j==="exec_command"||j==="execcommand"||j==="run"){let A=O(U.args).command||null;_e=`${A?"\u2714":"\u2718"} \x1B[95mExecuted\x1B[0m: ${A?A.slice(0,100)+(A.length>100?"...":""):"No Command"}`}else if(j==="file_map"||j==="filemap"){let A=O(U.args).path||"";_e=`${A?"\u2714":"\u2718"} \x1B[95mIndexed\x1B[0m: ${A?`${A.replaceAll("\\","/")}`:"File Not Found"}`}else if(j==="await"){let{time:A}=O(U.args),F=parseFloat(A)||0;F<10&&(F=10),F>180&&(F=180),_e=`\u2714 \x1B[95mAwaiting\x1B[0m \u2192 ${(X=>{if(X>=60){let Ue=Math.floor(X/60),Ne=X%60;return`${Ue}m${Ne>0?` ${Ne}s`:""}`}return`${X}s`})(F)}`}else{let A=Qr[j]||U.toolName,F=ws(j,U.args);_e=`\u2714 \x1B[95m${A}\x1B[0m${F?`: ${F}`:""}`}n.onVisualFeedback&&_e&&n.onVisualFeedback(_e),r&&r(`[Executing Tool] ${U.toolName}(${U.args})...`);try{let A=await fo(U.toolName,U.args,{...n,mode:"Flux"});if(r&&r(`[Tool Result]
808
808
  ${A}
809
809
  `),Y+=`[TOOL RESULT for ${U.toolName}]: ${A}
810
810
 
811
- `,await It("toolSuccess"),j==="patchfile"||j==="update_file"||j==="updatefile"||j==="patch_file"){if(A){let F=A.split(`
811
+ `,await Lt("toolSuccess"),j==="patchfile"||j==="update_file"||j==="updatefile"||j==="patch_file"){if(A){let F=A.split(`
812
812
  `),V=0,X=0,Ue=!1;for(let Ne of F){if(Ne.includes("[DIFF_START]")){Ue=!0;continue}if(Ne.includes("[DIFF_END]")){Ue=!1;continue}Ue&&(/^\+\d+/.test(Ne)?V++:/^\-\d+/.test(Ne)&&X++)}(V>0||X>0)&&(await Kt("linesAdded",V),await Kt("linesRemoved",X))}}else if((j==="writefile"||j==="write_file")&&A){let F=A.match(/- Stats: \[(\d+) lines/),V=F?parseInt(F[1]):0,X=0;if(A.includes("Old File contents:")){let Ue=!1;for(let Ne of A.split(`
813
- `)){if(Ne.includes("Old File contents:")){Ue=!0;continue}Ue&&(Ne.trim()===""?Ue=!1:/^\d+ \|/.test(Ne)&&X++)}}(V>0||X>0)&&(await Kt("linesAdded",V),await Kt("linesRemoved",X))}}catch(A){let F=`ERROR: Execution failed for [${U.toolName}]: ${A.message}`;i&&i(`[Tool Error] ${F}
813
+ `)){if(Ne.includes("Old File contents:")){Ue=!0;continue}Ue&&(Ne.trim()===""?Ue=!1:/^\d+ \|/.test(Ne)&&X++)}}(V>0||X>0)&&(await Kt("linesAdded",V),await Kt("linesRemoved",X))}}catch(A){let F=`ERROR: Execution failed for [${U.toolName}]: ${A.message}`;r&&r(`[Tool Error] ${F}
814
814
  `),Y+=`${F}
815
815
 
816
- `,await It("toolFailure")}}let ne="";if(n?.taskId&&typeof Xe<"u"){let U=Xe.find(j=>j.id===n.taskId);if(U&&U.pendingSteerMessages&&U.pendingSteerMessages.length>0){let j=[...U.pendingSteerMessages];U.pendingSteerMessages=[];for(let ae of j)ne+=`
816
+ `,await Lt("toolFailure")}}let ne="";if(n?.taskId&&typeof Xe<"u"){let U=Xe.find(j=>j.id===n.taskId);if(U&&U.pendingSteerMessages&&U.pendingSteerMessages.length>0){let j=[...U.pendingSteerMessages];U.pendingSteerMessages=[];for(let ae of j)ne+=`
817
817
 
818
- [STEERING INSTRUCTION FROM MAIN AGENT]: ${ae}`,i&&i(`[Subagent Steered] ${ae}`)}}let Ie=(Y.trim()+ne).trim();S.push({role:"user",text:Ie}),T++}return $};export{pn as a,Kr as b,kf as c,Sf as d,bl as e,Yr as f,Tf as g,Cl as h,Rf as i,ho as j,wa as k,Ip as l,Op as m,O as n,jc as o,ti as p,Ys as q,Hc as r,Gc as s,ht as t,ls as u,kd as v,il as w,Sd as x,Td as y,Rd as z,Ed as A,_d as B,Od as C,Ld as D,Tn as E,cl as F,Js as G,Kt as H,dl as I,Nr as J,cs as K,Ul as L,Su as M,Tu as N,Pp as O,Wo as P,Fp as Q,Pn as R,Rc as S,Tm as T,Rm as U,cr as V,Em as W,_m as X,Oc as Y,$m as Z,Cm as _,Mm as $};
818
+ [STEERING INSTRUCTION FROM MAIN AGENT]: ${ae}`,r&&r(`[Subagent Steered] ${ae}`)}}let Ie=(Y.trim()+ne).trim();S.push({role:"user",text:Ie}),T++}return $};export{pn as a,zi as b,Sf as c,Tf as d,kl as e,Ki as f,Rf as g,Ml as h,Ef as i,uo as j,ya as k,Op as l,Lp as m,O as n,Hc as o,er as p,Ks as q,Gc as r,qc as s,pt as t,as as u,Sd as v,il as w,Td as x,Rd as y,Ed as z,_d as A,$d as B,Ld as C,Dd as D,Sn as E,dl as F,Xs as G,Kt as H,fl as I,Fi as J,ls as K,Wl as L,Tu as M,Ru as N,Fp as O,Uo as P,Np as Q,Dn as R,Ec as S,Rm as T,Em as U,li as V,_m as W,$m as X,Lc as Y,Cm as Z,Mm as _,Am as $};