fluxflow-cli 4.3.2 → 4.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,9 +1,9 @@
1
- import{b as Qo}from"./chunk-ACHIC75V.js";import{c as zt,d as qs,g as ve,h as Ft}from"./chunk-TKIVOTJ4.js";import{a as Gs,b as $s,c as Q,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 Dt,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 ft,HarmBlockThreshold as Yn,HarmCategory as Vn}from"@google/genai";import{Ollama as dc}from"ollama";import{execSync as Za}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,p=-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),h=u.trim(),g=h===""||/^,\s*\w+\s*=/.test(h)||h.startsWith(")")&&(h.length===1||/^\)\s*([,\]\s]|\[\[?tool:)/i.test(h));if(g&&u.startsWith(`
1
+ import{b as Qo}from"./chunk-ACHIC75V.js";import{c as zt,d as qs,g as Ie,h as Ft}from"./chunk-TKIVOTJ4.js";import{a as Gs,b as $s,c as Z,d as me}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 Dt,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 ft,HarmBlockThreshold as Yn,HarmCategory as Vn}from"@google/genai";import{Ollama as fc}from"ollama";import{execSync as el}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,p=-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),h=u.trim(),g=h===""||/^,\s*\w+\s*=/.test(h)||h.startsWith(")")&&(h.length===1||/^\)\s*([,\]\s]|\[\[?tool:)/i.test(h));if(g&&u.startsWith(`
2
2
  `)){let y=h.split(`
3
3
  `)[0];if(!y.includes("=")&&!y.includes(")")){d=l+1;continue}}if(g){p=l;break}d=l+1}p!==-1?(r=e.substring(i,p),t=p+1):(r=e.substring(i),t=e.length);let c=s.toLowerCase().includes("path")||["dest","source","to","from"].includes(s.toLowerCase());r=r.replace(/\\(.)/g,(l,f)=>{switch(f){case"n":return`
4
- `;case"r":return"\r";case"t":return" ";case"\\":return"\\";default:return f===a?a:f}})}else if(t<e.length&&e[t]==="["){let a=0,i=null,p=t,d=-1;for(let c=t;c<e.length;c++){let l=e[c];if(i&&l===i){let f=0;for(let u=c-1;u>=0&&e[u]==="\\";u--)f++;f%2===0&&(i=null)}else!i&&(l==='"'||l==="'"||l==="`")&&(i=l);if(!i&&(l==="["?a++:l==="]"&&a--,a===0)){d=c;break}}if(d!==-1){r=e.substring(p,d+1),t=d+1;try{let c=r.trim();c.startsWith("'")||c.includes("'")}catch{}}else r=e.substring(p),t=e.length}else{let a=e.substring(t),i=a.match(/,\s*\w+\s*=|(?:\s*\)\s*(?:$|\]\]))/);if(i){let p=i.index;r=a.substring(0,p).trim(),t+=p}else r=a.trim(),t=e.length}r==="true"?r=!0:r==="false"?r=!1:typeof r=="string"&&!isNaN(r)&&r.trim()!==""&&(r=Number(r)),typeof r=="string"&&(s.toLowerCase().includes("path")||["dest","source","to","from"].includes(s.toLowerCase()))&&(r=r.replace(/\x0C/g,"\\f").replace(/\x0D/g,"\\r").replace(/\x0B/g,"\\v").replace(/\x08/g,"\\b")),n[s]=r}return n};var ko=null;try{let e=await import("node-pty");ko=e.default||e}catch{}var Gc=!!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===`
4
+ `;case"r":return"\r";case"t":return" ";case"\\":return"\\";default:return f===a?a:f}})}else if(t<e.length&&e[t]==="["){let a=0,i=null,p=t,d=-1;for(let c=t;c<e.length;c++){let l=e[c];if(i&&l===i){let f=0;for(let u=c-1;u>=0&&e[u]==="\\";u--)f++;f%2===0&&(i=null)}else!i&&(l==='"'||l==="'"||l==="`")&&(i=l);if(!i&&(l==="["?a++:l==="]"&&a--,a===0)){d=c;break}}if(d!==-1){r=e.substring(p,d+1),t=d+1;try{let c=r.trim();c.startsWith("'")||c.includes("'")}catch{}}else r=e.substring(p),t=e.length}else{let a=e.substring(t),i=a.match(/,\s*\w+\s*=|(?:\s*\)\s*(?:$|\]\]))/);if(i){let p=i.index;r=a.substring(0,p).trim(),t+=p}else r=a.trim(),t=e.length}r==="true"?r=!0:r==="false"?r=!1:typeof r=="string"&&!isNaN(r)&&r.trim()!==""&&(r=Number(r)),typeof r=="string"&&(s.toLowerCase().includes("path")||["dest","source","to","from"].includes(s.toLowerCase()))&&(r=r.replace(/\x0C/g,"\\f").replace(/\x0D/g,"\\r").replace(/\x0B/g,"\\v").replace(/\x08/g,"\\b")),n[s]=r}return n};var ko=null;try{let e=await import("node-pty");ko=e.default||e}catch{}var qc=!!ko,So=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),er=e=>{if(!e)return"";let n=[[]],t=0,o=0,s=/\x1b\[([0-9;]*?)([a-zA-Z])/g,r=0,a,i=d=>{for(let c=0;c<d.length;c++){let l=d[c];if(l===`
5
5
  `)for(t++,o=0;t>=n.length;)n.push([]);else if(l==="\r")o=0;else{for(;t>=n.length;)n.push([]);let f=n[t];for(;o>f.length;)f.push(" ");f[o]=l,o++}}};for(;(a=s.exec(e))!==null;){i(e.substring(r,a.index));let d=a[1],c=a[2],l=d?d.split(";").map(Number):[];if(c==="A"){let f=l[0]||1;t=Math.max(0,t-f)}else if(c==="B"){let f=l[0]||1;for(t=t+f;t>=n.length;)n.push([])}else if(c==="C"){let f=l[0]||1;o=o+f}else if(c==="D"){let f=l[0]||1;o=Math.max(0,o-f)}else if(c==="G"){let f=(l[0]||1)-1;o=Math.max(0,f)}else if(c==="H"||c==="f"){let f=(l[0]||1)-1,u=(l[1]||1)-1;for(t=Math.max(0,f),o=Math.max(0,u);t>=n.length;)n.push([])}else if(c==="K"){let f=l[0]||0;if(t<n.length){let u=n[t];if(f===0)u.length=o;else if(f===1)for(let h=0;h<o&&h<u.length;h++)u[h]=" ";else f===2&&(u.length=0)}}else if(c==="J"){let f=l[0]||0;(f===2||f===3)&&(n.length=0,n.push([]),t=0,o=0)}r=s.lastIndex}i(e.substring(r));let p=n.map(d=>d.join(""));for(;p.length>0&&p[p.length-1]==="";)p.pop();return p.join(`
6
- `)},xt=null,Ks=!1,qc=e=>{try{xt&&(Ks&&typeof xt.write=="function"?xt.write(e):xt.stdin&&xt.stdin.writable&&xt.stdin.write(e))}catch{}},zc=()=>{if(xt){try{Ks&&typeof xt.destroy=="function"?xt.destroy():typeof xt.kill=="function"&&(process.platform==="win32"?Zo("taskkill",["/pid",xt.pid,"/f","/t"]):xt.kill("SIGKILL"))}catch{}xt=null,Ks=!1}},tr=(e,n=!1)=>{if(process.platform!=="win32")return e;let t=[],o="",s=null,r=!1;for(let c=0;c<e.length;c++){let l=e[c];if(r){o+=l,r=!1;continue}if(l==="\\"){if(e[c+1]===" "){o+=" ",c++;continue}o+=l,r=!0;continue}s?(l===s&&(s=null),o+=l):l==='"'||l==="'"?(s=l,o+=l):l===";"&&!o.includes("://")?(o.length>0&&(t.push(o),o=""),t.push(n?";":"&")):l==="&"&&!o.includes("://")?e[c+1]==="&"?(o.length>0&&(t.push(o),o=""),t.push("&&"),c++):(o.length>0&&(t.push(o),o=""),t.push("&")):l==="|"&&!o.includes("://")?(o.length>0&&(t.push(o),o=""),t.push("|")):/\s/.test(l)?o.length>0&&(t.push(o),o=""):o+=l}o.length>0&&t.push(o);let a=c=>!(!c.includes("/")||/^(https?|file|ftp):\/\//i.test(c)||c.startsWith("@")||c.startsWith("/")&&(c.match(/\//g)||[]).length===1||/\s\/|\/\s/.test(c)||/[\(\)\{\}\;\<\>\=\'\"]/.test(c)),i=[];for(let c=0;c<t.length;c++){let l=t[c];if(l==="mkdir"&&n&&Hn()){let f=[],u=c+1;for(;u<t.length;){let h=t[u];if([">",">>","<","&","&&","|","||",";"].includes(h))break;h!=="-p"&&h!=="--parents"&&h!=="-v"&&h!=="--verbose"&&f.push(h),u++}if(f.length>0){let h=f.map(g=>{let y=g.replace(/^['"]|['"]$/g,""),m=g;return a(y)&&(m=g.replace(/\//g,"\\")),m});i.push("New-Item","-ItemType","Directory","-Force","-Path",h.join(","))}else i.push("New-Item","-ItemType","Directory","-Force");c=u-1;continue}if(l==="rm"&&n&&Hn()){let f=[],u=!1,h=!1,g=c+1;for(;g<t.length;){let m=t[g];if([">",">>","<","&","&&","|","||",";"].includes(m))break;m==="-rf"||m==="-fr"?(u=!0,h=!0):m==="-r"||m==="-R"||m==="--recursive"?u=!0:m==="-f"||m==="--force"?h=!0:f.push(m),g++}let y=["Remove-Item"];if(u&&y.push("-Recurse"),h&&y.push("-Force"),f.length>0){let m=f.map(w=>{let b=w.replace(/^['"]|['"]$/g,""),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,h=!1,g=c+1;for(;g<t.length;){let m=t[g];if([">",">>","<","&","&&","|","||",";"].includes(m))break;m==="-r"||m==="-R"||m==="--recursive"?u=!0:m==="-f"||m==="--force"?h=!0:f.push(m),g++}let y=["Copy-Item"];if(u&&y.push("-Recurse"),h&&y.push("-Force"),f.length>0){let m=f.map(w=>{let b=w.replace(/^['"]|['"]$/g,""),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 h=t[u];if([">",">>","<","&","&&","|","||",";"].includes(h))break;f.push(h),u++}if(f.length>0){let g=`(${f.map(y=>{let m=y.replace(/^['"]|['"]$/g,""),w=y;return a(m)&&(w=y.replace(/\//g,"\\")),w}).join(", ")}) | ForEach-Object { if (Test-Path $_) { (Get-Item $_).LastWriteTime = [System.DateTime]::Now } else { $null | Out-File -FilePath $_ } }`;i.push(g)}c=u-1;continue}if(l==="|"&&t[c+1]==="tee"){t[c+2]==="-a"?(i.push(">>"),c+=2):(i.push(">"),c+=1);continue}if(l==="|"&&t[c+1]==="cat"&&t[c+2]===">"){i.push(">"),c+=2;continue}if(l==="|"){let f=t[c+1];if(f){let u=f.replace(/^['"]|['"]$/g,""),h=/\.(txt|md|json|log|csv|html|css|py|js|xml|yaml|yml|pdf|docx|pptx|xlsx)$/i.test(u);if(a(u)&&h){i.push(">");continue}}}i.push(l)}let p=!1,d=i.map(c=>{if(c==="echo")return p=!0,c;[">",">>","<","&","&&","|","||",";"].includes(c)&&(p=!1);let f=/^['"]|['"]$/.test(c),u=c;p&&f&&(u=c.replace(/^['"]|['"]$/g,""));let h=/^['"]|['"]$/.test(u),g=u.replace(/^['"]|['"]$/g,"");a(g)&&(u=u.replace(/\//g,"\\"));let y=u.replace(/^['"]|['"]$/g,"");return y.includes(" ")&&!h&&(u=`"${y}"`),u});if(n){let c="",l=0;for(let f=0;f<d.length;f++){let u=d[f];u==="&&"?(c+="; if ($?) {",l++):u===";"?(c+=" }".repeat(l)+";",l=0):(c&&!c.endsWith(" ")&&!c.endsWith("{")&&(c+=" "),c+=u)}return c+=" }".repeat(l),c}return d.join(" ")},nr=async(e,n={})=>{let{command:t}=O(e),{onChunk:o}=n;if(!t)return'ERROR: Missing "command" argument for exec_command.';let s=process.platform==="win32",r=n.systemSettings||{},a={};return r.networkAccess===!1&&(a.HTTP_PROXY="http://127.0.0.1:9999",a.HTTPS_PROXY="http://127.0.0.1:9999",a.ALL_PROXY="socks5://127.0.0.1:9999",a.http_proxy="http://127.0.0.1:9999",a.https_proxy="http://127.0.0.1:9999",a.all_proxy="socks5://127.0.0.1:9999",a.NO_PROXY="localhost,127.0.0.1"),new Promise(i=>{let p=d=>{let c=d==="pwsh"||d==="powershell",l=tr(t,c),f;s?d==="pwsh"?f="C:\\Users\\User\\AppData\\Local\\Microsoft\\WindowsApps\\pwsh.exe":d==="powershell"?f="powershell.exe":f="cmd.exe":f=process.env.SHELL||"bash";let u=s?c?["-NoProfile","-Command",l]:["/c",l]:["-c",l];if(r.networkAccess===!1&&!s){let h=f,g=[...u];if(process.platform==="linux")f="unshare",u=["-n","-r",h,...g];else if(process.platform==="darwin"){let y=`(version 1)
6
+ `)},xt=null,Ks=!1,zc=e=>{try{xt&&(Ks&&typeof xt.write=="function"?xt.write(e):xt.stdin&&xt.stdin.writable&&xt.stdin.write(e))}catch{}},Kc=()=>{if(xt){try{Ks&&typeof xt.destroy=="function"?xt.destroy():typeof xt.kill=="function"&&(process.platform==="win32"?Zo("taskkill",["/pid",xt.pid,"/f","/t"]):xt.kill("SIGKILL"))}catch{}xt=null,Ks=!1}},tr=(e,n=!1)=>{if(process.platform!=="win32")return e;let t=[],o="",s=null,r=!1;for(let c=0;c<e.length;c++){let l=e[c];if(r){o+=l,r=!1;continue}if(l==="\\"){if(e[c+1]===" "){o+=" ",c++;continue}o+=l,r=!0;continue}s?(l===s&&(s=null),o+=l):l==='"'||l==="'"?(s=l,o+=l):l===";"&&!o.includes("://")?(o.length>0&&(t.push(o),o=""),t.push(n?";":"&")):l==="&"&&!o.includes("://")?e[c+1]==="&"?(o.length>0&&(t.push(o),o=""),t.push("&&"),c++):(o.length>0&&(t.push(o),o=""),t.push("&")):l==="|"&&!o.includes("://")?(o.length>0&&(t.push(o),o=""),t.push("|")):/\s/.test(l)?o.length>0&&(t.push(o),o=""):o+=l}o.length>0&&t.push(o);let a=c=>!(!c.includes("/")||/^(https?|file|ftp):\/\//i.test(c)||c.startsWith("@")||c.startsWith("/")&&(c.match(/\//g)||[]).length===1||/\s\/|\/\s/.test(c)||/[\(\)\{\}\;\<\>\=\'\"]/.test(c)),i=[];for(let c=0;c<t.length;c++){let l=t[c];if(l==="mkdir"&&n&&Hn()){let f=[],u=c+1;for(;u<t.length;){let h=t[u];if([">",">>","<","&","&&","|","||",";"].includes(h))break;h!=="-p"&&h!=="--parents"&&h!=="-v"&&h!=="--verbose"&&f.push(h),u++}if(f.length>0){let h=f.map(g=>{let y=g.replace(/^['"]|['"]$/g,""),m=g;return a(y)&&(m=g.replace(/\//g,"\\")),m});i.push("New-Item","-ItemType","Directory","-Force","-Path",h.join(","))}else i.push("New-Item","-ItemType","Directory","-Force");c=u-1;continue}if(l==="rm"&&n&&Hn()){let f=[],u=!1,h=!1,g=c+1;for(;g<t.length;){let m=t[g];if([">",">>","<","&","&&","|","||",";"].includes(m))break;m==="-rf"||m==="-fr"?(u=!0,h=!0):m==="-r"||m==="-R"||m==="--recursive"?u=!0:m==="-f"||m==="--force"?h=!0:f.push(m),g++}let y=["Remove-Item"];if(u&&y.push("-Recurse"),h&&y.push("-Force"),f.length>0){let m=f.map(w=>{let b=w.replace(/^['"]|['"]$/g,""),T=w;return a(b)&&(T=w.replace(/\//g,"\\")),T});y.push("-Path",m.join(","))}i.push(...y),c=g-1;continue}if(l==="cp"&&n&&Hn()){let f=[],u=!1,h=!1,g=c+1;for(;g<t.length;){let m=t[g];if([">",">>","<","&","&&","|","||",";"].includes(m))break;m==="-r"||m==="-R"||m==="--recursive"?u=!0:m==="-f"||m==="--force"?h=!0:f.push(m),g++}let y=["Copy-Item"];if(u&&y.push("-Recurse"),h&&y.push("-Force"),f.length>0){let m=f.map(w=>{let b=w.replace(/^['"]|['"]$/g,""),T=w;return a(b)&&(T=w.replace(/\//g,"\\")),T});if(m.length>1){let w=m.pop();y.push("-Path",m.join(","),"-Destination",w)}else y.push("-Path",m[0])}i.push(...y),c=g-1;continue}if(l==="touch"&&n&&Hn()){let f=[],u=c+1;for(;u<t.length;){let h=t[u];if([">",">>","<","&","&&","|","||",";"].includes(h))break;f.push(h),u++}if(f.length>0){let g=`(${f.map(y=>{let m=y.replace(/^['"]|['"]$/g,""),w=y;return a(m)&&(w=y.replace(/\//g,"\\")),w}).join(", ")}) | ForEach-Object { if (Test-Path $_) { (Get-Item $_).LastWriteTime = [System.DateTime]::Now } else { $null | Out-File -FilePath $_ } }`;i.push(g)}c=u-1;continue}if(l==="|"&&t[c+1]==="tee"){t[c+2]==="-a"?(i.push(">>"),c+=2):(i.push(">"),c+=1);continue}if(l==="|"&&t[c+1]==="cat"&&t[c+2]===">"){i.push(">"),c+=2;continue}if(l==="|"){let f=t[c+1];if(f){let u=f.replace(/^['"]|['"]$/g,""),h=/\.(txt|md|json|log|csv|html|css|py|js|xml|yaml|yml|pdf|docx|pptx|xlsx)$/i.test(u);if(a(u)&&h){i.push(">");continue}}}i.push(l)}let p=!1,d=i.map(c=>{if(c==="echo")return p=!0,c;[">",">>","<","&","&&","|","||",";"].includes(c)&&(p=!1);let f=/^['"]|['"]$/.test(c),u=c;p&&f&&(u=c.replace(/^['"]|['"]$/g,""));let h=/^['"]|['"]$/.test(u),g=u.replace(/^['"]|['"]$/g,"");a(g)&&(u=u.replace(/\//g,"\\"));let y=u.replace(/^['"]|['"]$/g,"");return y.includes(" ")&&!h&&(u=`"${y}"`),u});if(n){let c="",l=0;for(let f=0;f<d.length;f++){let u=d[f];u==="&&"?(c+="; if ($?) {",l++):u===";"?(c+=" }".repeat(l)+";",l=0):(c&&!c.endsWith(" ")&&!c.endsWith("{")&&(c+=" "),c+=u)}return c+=" }".repeat(l),c}return d.join(" ")},nr=async(e,n={})=>{let{command:t}=O(e),{onChunk:o}=n;if(!t)return'ERROR: Missing "command" argument for exec_command.';let s=process.platform==="win32",r=n.systemSettings||{},a={};return r.networkAccess===!1&&(a.HTTP_PROXY="http://127.0.0.1:9999",a.HTTPS_PROXY="http://127.0.0.1:9999",a.ALL_PROXY="socks5://127.0.0.1:9999",a.http_proxy="http://127.0.0.1:9999",a.https_proxy="http://127.0.0.1:9999",a.all_proxy="socks5://127.0.0.1:9999",a.NO_PROXY="localhost,127.0.0.1"),new Promise(i=>{let p=d=>{let c=d==="pwsh"||d==="powershell",l=tr(t,c),f;s?d==="pwsh"?f="C:\\Users\\User\\AppData\\Local\\Microsoft\\WindowsApps\\pwsh.exe":d==="powershell"?f="powershell.exe":f="cmd.exe":f=process.env.SHELL||"bash";let u=s?c?["-NoProfile","-Command",l]:["/c",l]:["-c",l];if(r.networkAccess===!1&&!s){let h=f,g=[...u];if(process.platform==="linux")f="unshare",u=["-n","-r",h,...g];else if(process.platform==="darwin"){let y=`(version 1)
7
7
  (allow default)
8
8
  (deny network-outbound)
9
9
  (allow network-outbound (remote ip "localhost:*"))
@@ -27,13 +27,13 @@ ${m}`),500))}}),l.stderr.on("data",g=>{if(!h){let y=g.toString();u+=y,s&&s(y)}})
27
27
  ${m}`),w&&y.push(`STDERR:
28
28
  ${w}`),g!==0&&y.push(`EXIT CODE: ${g}`);let b=y.join(`
29
29
 
30
- `)||"Command executed with no output.",x=So(b).replace(/\n{3,}/g,`
30
+ `)||"Command executed with no output.",T=So(b).replace(/\n{3,}/g,`
31
31
 
32
32
  `);e(g!==0?`ERROR: Command [${t}] failed with exit code [${g}].
33
33
 
34
- ${x}`:`SUCCESS: Command [${t}] completed.
34
+ ${T}`:`SUCCESS: Command [${t}] completed.
35
35
 
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)}}xt=null;let y=g instanceof Error?g.message:String(g);e(`ERROR: Failed to start command [${t}]: ${y}`)})};var Ys=null,Hn=()=>{if(process.platform!=="win32")return!1;if(Ys!==null)return Ys;try{Za('powershell.exe -NoProfile -Command "exit"',{stdio:"ignore"}),Ys=!0}catch{Ys=!1}return Ys},sr=null,ki=(e,n,t,o,s=!1,r=!0)=>{sr===null&&(sr=s);let a=`- JSON escape literal escape sequences in tool arguments
36
+ ${T}`)}),l.on("error",g=>{if(i&&g.code==="ENOENT"){if(r==="pwsh"){let m=tr(t,!0);return To(e,m,t,o,s,"powershell",a)}else if(r==="powershell"){let m=tr(t,!1);return To(e,m,t,o,s,"cmd",a)}}xt=null;let y=g instanceof Error?g.message:String(g);e(`ERROR: Failed to start command [${t}]: ${y}`)})};var Ys=null,Hn=()=>{if(process.platform!=="win32")return!1;if(Ys!==null)return Ys;try{el('powershell.exe -NoProfile -Command "exit"',{stdio:"ignore"}),Ys=!0}catch{Ys=!1}return Ys},sr=null,ki=(e,n,t,o,s=!1,r=!0)=>{sr===null&&(sr=s);let a=`- JSON escape literal escape sequences in tool arguments
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
@@ -68,7 +68,7 @@ Invocations:
68
68
  - KeyPress(key="key or ;-separated combination, eg: enter, back, backspace, clearInput, ctrl;c, alt;tab, f5, f11, alt;f4"). Press key, shortcut, function key (f1-f12), or clear active input field
69
69
  - RecaptureScreen(). Request fresh gridded screenshot`;return`
70
70
  -- TOOLS --
71
- To use tools, must output exactly '[tool:functions.ToolName(arg1="value1")]' structured string in chat response \u2190 no exception
71
+ You cant execute tools. To call tools, must output exactly [tool:functions.ToolName(arg1="value1")] structured string in chat response \u2190 no exception, verify correct syntax/brackets
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}`:""}
@@ -121,7 +121,7 @@ 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 Ri from"fs";import tl from"screenshot-desktop";var Ei=!1;(async()=>{try{let e=await Ft();if(Number(e?.display)===1){let n=await tl.listDisplays();n&&n.length>1&&(Ei=!0)}}catch{}})();var or=null,Ti=null,Vs=null,cd=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",nl=process.env.NO_DEV||!1,sl=(e,n)=>{if(!n)return"";if(e!==Ti||Vs===null){Ti=e;try{let t=Q(Dt,[]);Array.isArray(t)&&t.length>0?Vs=t.map(o=>`- ${o.memory}`).join(`
124
+ Verify imports, tool results & system stability; avoid syntax errors`};import Ri from"fs";import nl from"screenshot-desktop";var Ei=!1;(async()=>{try{let e=await Ft();if(Number(e?.display)===1){let n=await nl.listDisplays();n&&n.length>1&&(Ei=!0)}}catch{}})();var or=null,Ti=null,Vs=null,dd=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",sl=process.env.NO_DEV||!1,ol=(e,n)=>{if(!n)return"";if(e!==Ti||Vs===null){Ti=e;try{let t=Z(Dt,[]);Array.isArray(t)&&t.length>0?Vs=t.map(o=>`- ${o.memory}`).join(`
125
125
  `):Vs=""}catch(t){Vs="",Ri.appendFileSync(`${fn}/memory/error.txt`,`${t.message}
126
126
  -------------------------------------------------
127
127
 
@@ -137,16 +137,16 @@ 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
  ${h.length||u.length?"":`
140
- `}`:"",y=process.cwd(),m=sl(d,s),w=m?.length>0?`--- Saved Memories ---
140
+ `}`:"",y=process.cwd(),m=ol(d,s),w=m?.length>0?`--- Saved Memories ---
141
141
  ${m}
142
142
 
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?`
143
+ `:"",b=(()=>{let R=process.cwd().toLowerCase();if(process.platform==="win32"){let k=process.env.SystemRoot?.toLowerCase()||"c:\\windows",S=process.env.ProgramFiles?.toLowerCase()||"c:\\program files",_=process.env["ProgramFiles(x86)"]?.toLowerCase()||"c:\\program files (x86)";return R.startsWith(k)||R.startsWith(S)||R.startsWith(_)}else return R==="/"||["/bin","/sbin","/etc","/usr","/var","/root"].some(S=>R.startsWith(S))})(),T=[{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=T.filter(k=>Ri.existsSync(k.name));or=t==="Flux"&&R.length>0?`
144
144
  -- PROJECT CONTEXT --
145
- ${R.map(S=>`- ${S.name}: ${S.desc}`).join(`
145
+ ${R.map(k=>`- ${k.name}: ${k.desc}`).join(`
146
146
  `)}
147
147
  Check these first; These Files > Training Data. Safety rules apply
148
- `:""}let E=or;return`=== SYSTEM PROMPT ===
149
- Identity: Flux Flow. Sassy, Friendly, CLI Agent${nl?"":" by Kushal Roy Chowdhury"}
148
+ `:""}let $=or;return`=== SYSTEM PROMPT ===
149
+ Identity: Flux Flow. Sassy, Friendly, CLI Agent${sl?"":" by Kushal Roy Chowdhury"}
150
150
  ${t==="Flux"?"Stepwise Execution, Run Automated Tests. Task Completion":t==="Flow"?"Concise, Humorous, Sarcastic":t==="ICU"?"Computer Use Capabilities. Screenshot as ground truth, analyze grid ids overlapping/close to target, keyboard shortcuts > mouse clicks":"Computer Use & Workspace Capabilities. Screenshot as ground truth, analyze grid ids overlapping/close to target, keyboard shortcuts > mouse clicks. Workspace Tools if faster. Focus on Productivity"}${Ei&&t.toLowerCase().includes("cu")?`
151
151
  **Running on secondary screen. Opened app not visible in screenshot? Might be opened on primary. Use 'Ask' immediately with NO options and tell user to move app window to secondary**`:""}
152
152
 
@@ -162,7 +162,7 @@ ${c||n!=="Fast"&&(a==="Mistral"&&!p||n!=="xHigh"&&!p)?`critical thinking policy
162
162
  `:""}`:`${l}
163
163
  `}
164
164
  ${ki(t,f,a.toLowerCase()==="deepseek"?!1:i,a,o?.advanceRollback,o?.subAgents!==!1)}
165
- ${E}${s?`
165
+ ${$}${s?`
166
166
  -- MEMORY RULES --
167
167
  - Subtly Personalize with relevent contextual memories. Auto Saves
168
168
  `:""}
@@ -199,12 +199,12 @@ ${Si(n,t)}
199
199
  === END SYSTEM PROMPT ===${e?`
200
200
 
201
201
  -- current saved user memories --
202
- ${e}`:""}`.trim();import Ct from"fs-extra";import Eo from"path";import{nanoid as il}from"nanoid";import pt from"fs-extra";import an from"path";pt.ensureDirSync(Wn);var hn=null;async function ol(e,n){try{if(e.type==="create")await pt.pathExists(e.filePath)&&(await pt.chmod(e.filePath,438).catch(()=>{}),await pt.remove(e.filePath));else if(e.type==="update"){if(!e.backupFile)return;let t=an.join(Wn,n.chatId,e.backupFile);if(await pt.pathExists(t)){let o=Q(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 pt.pathExists(e.filePath)&&await pt.chmod(e.filePath,438).catch(()=>{}),await pt.writeFile(e.filePath,s,"utf8")}}}catch(t){throw new Error(`Restoration failed for ${an.basename(e.filePath)}: ${t.message}`)}}async function rl(e,n,t=7){let o=0;for(;o<t;)try{return await ol(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,mt={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=Q(rn,[]),i=[...a].reverse().find(p=>p.chatId===rr);if(i){if(i.changes.some(f=>f.filePath===e))return;let c=await pt.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 pt.ensureDir(u);let h=an.join(u,l),g=n!==null?n:await pt.readFile(e,"utf8").catch(()=>null);g!==null?pe(h,{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 pt.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 pt.ensureDir(i);let p=an.join(i,r),d=n!==null?n:await pt.readFile(e,"utf8").catch(()=>null);d!==null?pe(p,{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=Q(rn,[]);if(e.push(hn),e.length>512e3){let n=e.shift();if(n.changes)for(let t of n.changes)t.backupFile&&await pt.remove(an.join(Wn,n.chatId,t.backupFile)).catch(()=>{})}pe(rn,e),await pt.remove(rs).catch(()=>{})}catch{}finally{hn=null}},async recoverCrashedTransaction(){try{if(await pt.pathExists(rs)){let e=Q(rs,null);if(e?.changes?.length>0){let n=Q(rn,[]);n.some(t=>t.id===e.id)||(n.push(e),pe(rn,n))}await pt.remove(rs).catch(()=>{})}}catch{}},async rollbackToBefore(e){let n=Q(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 rl(i,a);for(let i of a.changes)if(i.backupFile){let p=an.join(Wn,a.chatId,i.backupFile);await pt.remove(p).catch(()=>{})}n=n.filter(i=>i.id!==a.id),pe(rn,n)}return{success:!0,chatId:o,targetPrompt:s}},async getChatHistory(e){try{return Q(rn,[]).filter(t=>t.chatId===e&&!t.reverted)}catch{return[]}},async deleteChatBackups(e){try{await pt.remove(an.join(Wn,e));let n=Q(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 Ct.ensureDir(_s);let e={};if(await Ct.pathExists(Es))try{e=Q(Es,{})}catch{e={}}for(let n in e){let t=Eo.join(_s,`${n}.json`);Object.defineProperty(e[n],"messages",{get:()=>{if(Ct.existsSync(t))try{return Q(t,[])}catch{return[]}return[]},set:o=>{try{pe(t,o)}catch{}},enumerable:!1,configurable:!0})}return e},Td=async(e,n,t)=>_o(async()=>{await Ct.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 Ft()).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,p=r.filter(y=>y.role==="user"),d=p[0],c=p[p.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)}`),h=Eo.join(_s,`${e}.json`);pe(h,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)}),al=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 Ct.pathExists(jn))try{let a=Q(jn,[]);if(Array.isArray(a)){let i=a.filter(p=>Object.keys(p)[0]!==String(e));pe(jn,i)}}catch{}let o=Q(tn,{});o[e]&&(delete o[e],pe(tn,o));let s=Q(An,{});s[e]&&(delete s[e],pe(An,s)),await mt.deleteChatBackups(e);let r=Eo.join(_s,`${e}.json`);if(await Ct.pathExists(r))try{await Ct.remove(r)}catch{}return n}),Rd=()=>`flow-${il(6)}`,Ed=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 al(a),r++)}return r},ll=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 p="en";try{p=Intl.DateTimeFormat().resolvedOptions().locale||"en"}catch{}let d=!/^en[-_]?us$|^en$/.test(p?.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,h=0,g=0;if(r){let m=r.split(":").map(Number);u=m[0]||0,h=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,h,g);return isNaN(y.getTime())?null:y.getTime()},cl=async e=>{try{if(!await Ct.pathExists(e))return;let n=await Ct.readFile(e,"utf8");if(!n.trim())return;let t=n.split(`
203
- `),o=[],s=null,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(),p=[],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 h=l.header.match(d);if(h){let g=ll(h[1]);if(g&&i-g>a)continue}}let u=l.header+(l.body.length>0?`
202
+ ${e}`:""}`.trim();import Ct from"fs-extra";import Eo from"path";import{nanoid as al}from"nanoid";import pt from"fs-extra";import an from"path";pt.ensureDirSync(Wn);var hn=null;async function rl(e,n){try{if(e.type==="create")await pt.pathExists(e.filePath)&&(await pt.chmod(e.filePath,438).catch(()=>{}),await pt.remove(e.filePath));else if(e.type==="update"){if(!e.backupFile)return;let t=an.join(Wn,n.chatId,e.backupFile);if(await pt.pathExists(t)){let o=Z(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 pt.pathExists(e.filePath)&&await pt.chmod(e.filePath,438).catch(()=>{}),await pt.writeFile(e.filePath,s,"utf8")}}}catch(t){throw new Error(`Restoration failed for ${an.basename(e.filePath)}: ${t.message}`)}}async function il(e,n,t=7){let o=0;for(;o<t;)try{return await rl(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,mt={async startTransaction(e,n){rr=e,hn={id:`tx_prompt_${Date.now()}`,chatId:e,timestamp:new Date().toISOString(),prompt:n.trim(),changes:[],reverted:!1},me(rs,hn)},async recordFileChange(e,n=null){try{if(!hn){if(rr){let a=Z(rn,[]),i=[...a].reverse().find(p=>p.chatId===rr);if(i){if(i.changes.some(f=>f.filePath===e))return;let c=await pt.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 pt.ensureDir(u);let h=an.join(u,l),g=n!==null?n:await pt.readFile(e,"utf8").catch(()=>null);g!==null?me(h,{data:Gs(g)}):(c="create",l=null)}i.changes.push({filePath:e,type:c,backupFile:l}),me(rn,a)}}return}if(hn.changes.some(a=>a.filePath===e))return;let s=await pt.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 pt.ensureDir(i);let p=an.join(i,r),d=n!==null?n:await pt.readFile(e,"utf8").catch(()=>null);d!==null?me(p,{data:Gs(d)}):(s="create",r=null)}hn.changes.push({filePath:e,type:s,backupFile:r}),me(rs,hn)}catch{}},async commitTransaction(){if(hn)try{let e=Z(rn,[]);if(e.push(hn),e.length>512e3){let n=e.shift();if(n.changes)for(let t of n.changes)t.backupFile&&await pt.remove(an.join(Wn,n.chatId,t.backupFile)).catch(()=>{})}me(rn,e),await pt.remove(rs).catch(()=>{})}catch{}finally{hn=null}},async recoverCrashedTransaction(){try{if(await pt.pathExists(rs)){let e=Z(rs,null);if(e?.changes?.length>0){let n=Z(rn,[]);n.some(t=>t.id===e.id)||(n.push(e),me(rn,n))}await pt.remove(rs).catch(()=>{})}}catch{}},async rollbackToBefore(e){let n=Z(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 il(i,a);for(let i of a.changes)if(i.backupFile){let p=an.join(Wn,a.chatId,i.backupFile);await pt.remove(p).catch(()=>{})}n=n.filter(i=>i.id!==a.id),me(rn,n)}return{success:!0,chatId:o,targetPrompt:s}},async getChatHistory(e){try{return Z(rn,[]).filter(t=>t.chatId===e&&!t.reverted)}catch{return[]}},async deleteChatBackups(e){try{await pt.remove(an.join(Wn,e));let n=Z(rn,[]),t=n.filter(o=>o.chatId!==e);n.length!==t.length&&me(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 Ct.ensureDir(_s);let e={};if(await Ct.pathExists(Es))try{e=Z(Es,{})}catch{e={}}for(let n in e){let t=Eo.join(_s,`${n}.json`);Object.defineProperty(e[n],"messages",{get:()=>{if(Ct.existsSync(t))try{return Z(t,[])}catch{return[]}return[]},set:o=>{try{me(t,o)}catch{}},enumerable:!1,configurable:!0})}return e},Rd=async(e,n,t)=>_o(async()=>{await Ct.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 Ft()).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+/),T;return b.length>7?T=b.slice(0,7).join(" ")+"...":w.length>45?T=w.substring(0,45).trimEnd()+"...":T=w,T},i,p=r.filter(y=>y.role==="user"),d=p[0],c=p[p.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)}`),h=Eo.join(_s,`${e}.json`);me(h,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};me(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};me(Es,o)}),ll=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(me(Es,t),await Ct.pathExists(jn))try{let a=Z(jn,[]);if(Array.isArray(a)){let i=a.filter(p=>Object.keys(p)[0]!==String(e));me(jn,i)}}catch{}let o=Z(tn,{});o[e]&&(delete o[e],me(tn,o));let s=Z(An,{});s[e]&&(delete s[e],me(An,s)),await mt.deleteChatBackups(e);let r=Eo.join(_s,`${e}.json`);if(await Ct.pathExists(r))try{await Ct.remove(r)}catch{}return n}),Ed=()=>`flow-${al(6)}`,_d=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 ll(a),r++)}return r},cl=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 p="en";try{p=Intl.DateTimeFormat().resolvedOptions().locale||"en"}catch{}let d=!/^en[-_]?us$|^en$/.test(p?.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,h=0,g=0;if(r){let m=r.split(":").map(Number);u=m[0]||0,h=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,h,g);return isNaN(y.getTime())?null:y.getTime()},dl=async e=>{try{if(!await Ct.pathExists(e))return;let n=await Ct.readFile(e,"utf8");if(!n.trim())return;let t=n.split(`
203
+ `),o=[],s=null,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(),p=[],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 h=l.header.match(d);if(h){let g=cl(h[1]);if(g&&i-g>a)continue}}let u=l.header+(l.body.length>0?`
204
204
  `+l.body.join(`
205
205
  `):"");p.push(u)}let c=p.join(`
206
206
  `).trim();c?await Ct.writeFile(e,c+`
207
- `,"utf8"):await Ct.writeFile(e,"","utf8")}catch{}},_d=async e=>{try{if(!await Ct.pathExists(e))return;let n=async t=>{let o=await Ct.readdir(t);for(let s of o){let r=Eo.join(t,s);(await Ct.stat(r)).isDirectory()?(await n(r),(await Ct.readdir(r)).length===0&&await Ct.remove(r)):s.endsWith(".log")&&await cl(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=Q(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)}),Cd=async e=>{try{if(!await Ct.pathExists(jn))return{total:0,context:0};let n=Q(jn,[]);if(!Array.isArray(n))return{total:0,context:0};let t=n.find(o=>Object.keys(o)[0]===String(e));return t?t[String(e)]:{total:0,context:0}}catch{return{total:0,context:0}}};import bt from"fs-extra";import Ii from"path";var dl=()=>Math.random().toString(36).substring(2)+Date.now().toString(36),re=null,Gn=null,Oi=0,Cs=!1,vn={agent:0,background:0,search:0,toolSuccess:0,toolFailure:0,toolDenied:0,duration:0,tokens:0,cachedTokens:0,candidateTokens:0,linesAdded:0,linesRemoved:0,imageCalls:[]},Ms=(e,n)=>{if(!e)return{};let t=Object.keys(e),o=new Date(new Date(n).getTime()-720*60*60*1e3),s={};for(let r of t)new Date(r)>=o&&(s[r]=e[r]);return s},$o=async()=>{let e=new Date().toISOString().split("T")[0];try{!await bt.exists(en)&&await bt.exists(Xo)&&(await bt.ensureDir(Ii.dirname(en)),await bt.move(Xo,en))}catch{}let n=en+".tmp",t=null;try{if(await bt.exists(n)){let s=(await bt.readFile(n,"utf8")).trim(),r=null;if(s.startsWith("{")||s.startsWith("[")?r=JSON.parse(s):r=JSON.parse($s(s)),r&&r.date&&r.stats){t=r;try{await bt.rename(n,en)}catch{}}else try{await bt.remove(n)}catch{}}}catch{try{await bt.remove(n)}catch{}}if(!t)try{if(await bt.exists(en)){let s=(await bt.readFile(en,"utf8")).trim();s.startsWith("{")||s.startsWith("[")?t=JSON.parse(s):t=JSON.parse($s(s))}}catch{}let o=t;if(o){let s=o.stats||{...vn},r={...vn,...s};Array.isArray(r.imageCalls)||(r.imageCalls=[]);let a=o.history||{},i=Ms(a,e);if(Object.keys(a).length!==Object.keys(i).length&&(Cs=!0),o.date===e)return{...o,stats:r,history:i};{let p=o.date,d=r,c={...i};return p&&(c[p]=d),{date:e,stats:{...vn},history:Ms(c,e)}}}return{date:e,stats:{...vn},history:{}}},ir=async()=>{if(!(!Cs||!re))try{await bt.ensureDir(Ii.dirname(en));let e=null;try{if(await bt.exists(en)){let s=(await bt.readFile(en,"utf8")).trim();s.startsWith("{")||s.startsWith("[")?e=JSON.parse(s):e=JSON.parse($s(s))}}catch{}if(e&&e.date===re.date&&e.stats){for(let s in re.stats)if(e.stats[s]!==void 0){if(Array.isArray(re.stats[s])){let r=Array.isArray(e.stats[s])?e.stats[s]:[],a=re.stats[s],i=new Map;for(let p of[...r,...a])p&&p.timestamp&&i.set(p.timestamp,p);re.stats[s]=Array.from(i.values())}else if(typeof re.stats[s]=="number")re.stats[s]=Math.max(re.stats[s],Number(e.stats[s])||0);else if(re.stats[s]&&typeof re.stats[s]=="object"){let r=e.stats[s]||{},a=re.stats[s];for(let i in r)if(typeof r[i]=="number")a[i]=Math.max(a[i]||0,r[i]);else if(r[i]&&typeof r[i]=="object"){a[i]||(a[i]={});for(let p in r[i])if(typeof r[i][p]=="number")a[i][p]=Math.max(a[i][p]||0,r[i][p]);else if(r[i][p]&&typeof r[i][p]=="object"){a[i][p]||(a[i][p]={});for(let d in r[i][p])a[i][p][d]=Math.max(a[i][p][d]||0,r[i][p][d])}}}}}if(e&&e.history){let s={...re.history||{}};for(let r in e.history)if(s[r])for(let a in s[r])if(a==="imageCalls"){let i=Array.isArray(e.history[r].imageCalls)?e.history[r].imageCalls:[],p=Array.isArray(s[r].imageCalls)?s[r].imageCalls:[],d=new Map;for(let c of[...i,...p])c&&c.timestamp&&d.set(c.timestamp,c);s[r].imageCalls=Array.from(d.values())}else typeof s[r][a]=="number"&&(s[r][a]=Math.max(s[r][a],Number(e.history[r][a])||0));else s[r]=e.history[r];re.history=Ms(s,re.date||today)}else if(re&&re.history){let s=new Date().toISOString().split("T")[0];re.history=Ms(re.history,s)}re.saveId=dl();let n=en+".tmp",t=Gs(JSON.stringify(re,null,2));await bt.writeFile(n,t,"utf8");let o=await bt.open(n,"r+");await bt.fsync(o),await bt.close(o),await bt.rename(n,en),Cs=!1,Oi=Date.now()}catch{}},Co=()=>{if(Cs=!0,Gn)return;let e=Date.now(),n=Math.max(0,1500-(e-Oi));Gn=setTimeout(async()=>{await ir(),Gn=null},n),Gn.unref&&Gn.unref()},Pd=async()=>{re=await $o(),Cs&&Co()},Dd=async()=>{Gn&&(clearTimeout(Gn),Gn=null),await ir()},Sn=async()=>{let e=new Date().toISOString().split("T")[0];if(!re)re=await $o();else if(re.date!==e){let n=re.date,t=re.stats,o=re.history||{};t&&(o[n]=t),re={date:e,stats:{...vn},history:Ms(o,e)},Cs=!0,await ir()}return re&&re.stats&&!Array.isArray(re.stats.imageCalls)&&(re.stats.imageCalls=[]),re.stats},fl=async()=>{let e=new Date().toISOString().split("T")[0];re||(re=await $o()),re.date!==e&&await Sn();let n=re.history||{},t=Ms(n,e);re.history=t;let o=re.stats||{...vn},s={...vn};s.imageCalls=[],s.models={};let r=(a,i)=>{for(let p in a)if(p==="imageCalls")a.imageCalls=[...a.imageCalls||[],...i.imageCalls||[]];else if(p==="models"){let d=i.models||{};for(let c in d){a.models[c]||(a.models[c]={});for(let l in d[c]){a.models[c][l]||(a.models[c][l]={tokens:0,cachedTokens:0,candidateTokens:0});let f=a.models[c][l],u=d[c][l];f.tokens+=u.tokens||0,f.cachedTokens+=u.cachedTokens||0,f.candidateTokens+=u.candidateTokens||0}}}else typeof a[p]=="number"&&(a[p]+=i[p]||0)};r(s,o);for(let a in t)r(s,t[a]);return s},Ot=async(e,n)=>{e==="toolSuccess"?Xs.toolSuccess++:e==="toolFailure"?Xs.toolFailure++:e==="toolDenied"&&Xs.toolDenied++;let t=await Sn();t[e]!==void 0&&t[e]++,n&&e==="agent"&&(t.providerRequests||(t.providerRequests={}),t.providerRequests[n]=(t.providerRequests[n]||0)+1),Co()},Xs={linesAdded:0,linesRemoved:0,toolSuccess:0,toolFailure:0,toolDenied:0},Kt=async(e,n,t,o)=>{e==="linesAdded"?Xs.linesAdded+=n:e==="linesRemoved"&&(Xs.linesRemoved+=n);let s=await Sn();if(s[e]!==void 0&&(s[e]+=Math.floor(n)),t&&o&&(e==="tokens"||e==="cachedTokens"||e==="candidateTokens")){s.models||(s.models={}),s.models[t]||(s.models[t]={}),s.models[t][o]||(s.models[t][o]={tokens:0,cachedTokens:0,candidateTokens:0});let r=s.models[t][o];e==="tokens"&&(r.tokens+=Math.floor(n)),e==="cachedTokens"&&(r.cachedTokens+=Math.floor(n)),e==="candidateTokens"&&(r.candidateTokens+=Math.floor(n))}Co()},ul=async(e=1)=>{let n=new Date,t=n.toISOString().split("T")[0];re||(re=await $o()),re.date!==t&&await Sn();let o=n.getFullYear(),s=n.getMonth();n.getDate()<e&&(s-=1,s<0&&(s=11,o-=1));let i=new Date(o,s,e).toISOString().split("T")[0],p=re.history||{},d=re.stats||{...vn},c={...vn};c.imageCalls=[],c.models={};let l=(f,u)=>{for(let h in f)if(h==="imageCalls")f.imageCalls=[...f.imageCalls||[],...u.imageCalls||[]];else if(h==="models"){let g=u.models||{};for(let y in g){f.models[y]||(f.models[y]={});for(let m in g[y]){f.models[y][m]||(f.models[y][m]={tokens:0,cachedTokens:0,candidateTokens:0});let w=f.models[y][m],b=g[y][m];w.tokens+=b.tokens||0,w.cachedTokens+=b.cachedTokens||0,w.candidateTokens+=b.candidateTokens||0}}}else typeof f[h]=="number"&&(f[h]+=u[h]||0)};l(c,d);for(let f in p)f>=i&&f<t&&l(c,p[f]);return c},ar=async(e,n={})=>{let t=await Ft().catch(()=>({})),o=n.apiTier||t.apiTier||"Free",s=n.quotas||n.systemSettings?.quotas||t.quotas||{},r=s.providerBudgets||{},a=!!r.__useProvider,i=n.aiProvider||t.aiProvider||"Google",p=a&&!!r[i],d=()=>{if(p){let c=r[i];return{agentLimit:typeof c.agentLimit=="number"&&c.agentLimit>0?c.agentLimit:99999999,tokenLimit:typeof c.tokenLimit=="number"&&c.tokenLimit>0?c.tokenLimit:99999999999999,monthlyTokenLimit:typeof c.monthlyTokenLimit=="number"&&c.monthlyTokenLimit>0?c.monthlyTokenLimit:99999999999999}}return{agentLimit:s.agentLimit||99999999,tokenLimit:s.tokenLimit||99999999999999,monthlyTokenLimit:s.monthlyTokenLimit||99999999999999}};if(e==="agent"){let{agentLimit:c,tokenLimit:l,monthlyTokenLimit:f}=d(),u=await Sn(),h;s.resetMode==="Custom"?h=await ul(s.resetDay||1):h=await fl();let g=0,y=0,m=0;if(p){g=u.providerRequests?.[i]||0;let w=u.models?.[i]||{};for(let x in w)y+=w[x]?.tokens||0;let b=h.models?.[i]||{};for(let x in b)m+=b[x]?.tokens||0}else g=u.agent||0,y=u.tokens||0,m=h.tokens||0;return o==="Free"&&u.agent+u.background>=999999?{allowed:!1,reason:"Free Tier Daily Usage Limit Exceeded"}:g>=c?{allowed:!1,reason:p?`Daily Request Limit Reached for ${i}`:"Daily Agent Request Limit Reached"}:y>=l?{allowed:!1,reason:p?`Daily Token Budget Exhausted for ${i}`:"Daily Token Budget Exhausted"}:m>=f?{allowed:!1,reason:p?`Monthly Token Budget Exhausted for ${i}`:"Monthly Token Budget Exhausted"}:{allowed:!0}}if(e==="background"){let c=await Sn();if(o==="Free"&&c.agent+c.background>=999999)return{allowed:!1,reason:"Free Tier Background Limit Exceeded"};let l=c.background<(s.backgroundLimit||999999);return{allowed:l,reason:l?void 0:"Background Request Limit Exceeded"}}if(e==="search"){let l=(await Sn()).search<(s.searchLimit||100);return{allowed:l,reason:l?void 0:"Search Quota Exceeded"}}return{allowed:!0}},Li=async(e,n={})=>(await ar(e,n)).allowed,lr=e=>{if(!e||e.length===0)return[];let t=[...e].sort((s,r)=>s.timestamp-r.timestamp),o=[];for(let s of t){if(o.length>0){let r=o[o.length-1];if(s.timestamp>=r.start&&s.timestamp<r.end){r.calls.push(s),r.spent+=s.cost;continue}}o.push({start:s.timestamp,end:s.timestamp+36e5,calls:[s],spent:s.cost})}return o},Pi=(e,n)=>{if(!e||e.length===0)return .025;let o=lr(e);if(o.length===0)return .025;let s=[];for(let l of o){let f=.025;if(s.length>0){let h=s[s.length-1],g=!1;if(s.length>=2){let y=s[s.length-2];h.ratio>=.8&&y.ratio>=.8&&(g=!0)}if(g)f=.015;else{let y=h.limit,m=h.ratio;m>=.8?f=y===.015?.015:y:m<.4?f=Math.min(.025,y+.005):m>=.4&&m<.6?f=Math.min(.025,y+.004):f=Math.min(.025,y+.002)}}let u=f>0?l.spent/f:0;s.push({limit:f,spent:l.spent,ratio:u})}let r=o[o.length-1];if(n<r.end)return s[s.length-1].limit;let a=s[s.length-1].limit,i=a,p=s[s.length-1].ratio,d=r.end,c=0;for(let l=s.length-1;l>=0&&s[l].ratio>=.8;l--)c++;for(;d<=n;){let l=.025;c>=2?l=.015:p>=.8?l=i===.015?.015:i:p<.4?l=Math.min(.025,i+.005):p>=.4&&p<.6?l=Math.min(.025,i+.004):l=Math.min(.025,i+.002),i=l,p=0,c=0,d+=36e5,a=l}return a},Di=async e=>{let n=e.imageSettings||{keyType:"Default",quality:"Low-High"};if(n.keyType!=="Default")return!0;let o={Low:.001,"Low-High":.002,Medium:.008,"Medium-High":.01,High:.045,Ultra:.0488,Premium:.15}[n.quality]||.002,s=await Sn();s.imageCalls||(s.imageCalls=[]);let r=Date.now(),a=lr(s.imageCalls),i=0;if(a.length>0){let d=a[a.length-1];r>=d.start&&r<d.end&&(i=d.spent)}let p=Pi(s.imageCalls,r);return i+o<=p},Fi=async()=>{let e=await Sn();e.imageCalls||(e.imageCalls=[]);let n=Date.now(),t=lr(e.imageCalls),o=[],s=0,r=0;if(t.length>0){let d=t[t.length-1];n>=d.start&&n<d.end&&(o=d.calls,s=d.spent,r=Math.max(0,Math.ceil((d.end-n)/(60*1e3))))}let a=Pi(e.imageCalls,n),i=Math.max(0,a-s),p=s;return{totalSpent:s,remaining:i,activeCallsCount:o.length,nextResetMin:r,reclaimCost:p,limit:a}},Ni=async e=>{let n=e.imageSettings||{keyType:"Default",quality:"Low-High"},o={Low:.001,"Low-High":.002,Medium:.008,"Medium-High":.01,High:.045,Ultra:.0488,Premium:.1}[n.quality]||.002,s=await Sn();s.imageCalls||(s.imageCalls=[]),s.imageCalls.push({timestamp:Date.now(),cost:o}),Co()};import Wi from"puppeteer";import ji from"fs";import Hi from"path";import Bi from"os";import Js from"path";import As from"fs";import{createRequire as hl}from"module";import{fileURLToPath as pl}from"url";var ml=hl(import.meta.url),Ui=Js.dirname(pl(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=ml(r),i=a.cacheDirectory,p=a.chrome?.version;if(i){if(process.env.PUPPETEER_CACHE_DIR=i,p){let l=Js.join(i,"chrome",`${t}-${p}`,s,o);if(As.existsSync(l))return{executablePath:l,cacheDirectory:i}}let d=l=>{if(!As.existsSync(l))return null;try{let f=As.readdirSync(l),u=[];for(let h of f){let g=Js.join(l,h),y;try{y=As.statSync(g)}catch{continue}if(y.isDirectory())u.push(g);else if(h.toLowerCase()===o.toLowerCase()&&(!p||g.includes(p)))return g}if(p){for(let h of u)if(h.includes(p)){let g=d(h);if(g)return g}}for(let h of u)if(!p||!h.includes(p)){let g=d(h);if(g)return g}}catch{}return null},c=d(i);if(c)return{executablePath:c,cacheDirectory:i}}}catch{}return{}}var cr=async e=>{let{query:n,limit:t=5,aiMode:o=!1}=O(e);if(!n)return'ERROR: Missing "query" argument for web_search.';let s=3,r=null;if(o){let a=`Query: ${n}
207
+ `,"utf8"):await Ct.writeFile(e,"","utf8")}catch{}},$d=async e=>{try{if(!await Ct.pathExists(e))return;let n=async t=>{let o=await Ct.readdir(t);for(let s of o){let r=Eo.join(t,s);(await Ct.stat(r)).isDirectory()?(await n(r),(await Ct.readdir(r)).length===0&&await Ct.remove(r)):s.endsWith(".log")&&await dl(r)}};await n(e)}catch{}},vi=(e,n=4)=>{if(e.length<=1)return e;let t=e[0],o=e.slice(1),s=n*2,r=o.slice(s);return[t,...r]};var Cd=async(e,n,t)=>_o(async()=>{let o=Z(jn,[]);Array.isArray(o)||(o=[]);let s={total:n,context:t},r=o.findIndex(a=>Object.keys(a)[0]===String(e));r!==-1?o[r]={[String(e)]:s}:o.push({[String(e)]:s}),me(jn,o)}),Md=async e=>{try{if(!await Ct.pathExists(jn))return{total:0,context:0};let n=Z(jn,[]);if(!Array.isArray(n))return{total:0,context:0};let t=n.find(o=>Object.keys(o)[0]===String(e));return t?t[String(e)]:{total:0,context:0}}catch{return{total:0,context:0}}};import bt from"fs-extra";import Ii from"path";var fl=()=>Math.random().toString(36).substring(2)+Date.now().toString(36),ae=null,Gn=null,Oi=0,Cs=!1,vn={agent:0,background:0,search:0,toolSuccess:0,toolFailure:0,toolDenied:0,duration:0,tokens:0,cachedTokens:0,candidateTokens:0,linesAdded:0,linesRemoved:0,imageCalls:[]},Ms=(e,n)=>{if(!e)return{};let t=Object.keys(e),o=new Date(new Date(n).getTime()-720*60*60*1e3),s={};for(let r of t)new Date(r)>=o&&(s[r]=e[r]);return s},$o=async()=>{let e=new Date().toISOString().split("T")[0];try{!await bt.exists(en)&&await bt.exists(Xo)&&(await bt.ensureDir(Ii.dirname(en)),await bt.move(Xo,en))}catch{}let n=en+".tmp",t=null;try{if(await bt.exists(n)){let s=(await bt.readFile(n,"utf8")).trim(),r=null;if(s.startsWith("{")||s.startsWith("[")?r=JSON.parse(s):r=JSON.parse($s(s)),r&&r.date&&r.stats){t=r;try{await bt.rename(n,en)}catch{}}else try{await bt.remove(n)}catch{}}}catch{try{await bt.remove(n)}catch{}}if(!t)try{if(await bt.exists(en)){let s=(await bt.readFile(en,"utf8")).trim();s.startsWith("{")||s.startsWith("[")?t=JSON.parse(s):t=JSON.parse($s(s))}}catch{}let o=t;if(o){let s=o.stats||{...vn},r={...vn,...s};Array.isArray(r.imageCalls)||(r.imageCalls=[]);let a=o.history||{},i=Ms(a,e);if(Object.keys(a).length!==Object.keys(i).length&&(Cs=!0),o.date===e)return{...o,stats:r,history:i};{let p=o.date,d=r,c={...i};return p&&(c[p]=d),{date:e,stats:{...vn},history:Ms(c,e)}}}return{date:e,stats:{...vn},history:{}}},ir=async()=>{if(!(!Cs||!ae))try{await bt.ensureDir(Ii.dirname(en));let e=null;try{if(await bt.exists(en)){let s=(await bt.readFile(en,"utf8")).trim();s.startsWith("{")||s.startsWith("[")?e=JSON.parse(s):e=JSON.parse($s(s))}}catch{}if(e&&e.date===ae.date&&e.stats){for(let s in ae.stats)if(e.stats[s]!==void 0){if(Array.isArray(ae.stats[s])){let r=Array.isArray(e.stats[s])?e.stats[s]:[],a=ae.stats[s],i=new Map;for(let p of[...r,...a])p&&p.timestamp&&i.set(p.timestamp,p);ae.stats[s]=Array.from(i.values())}else if(typeof ae.stats[s]=="number")ae.stats[s]=Math.max(ae.stats[s],Number(e.stats[s])||0);else if(ae.stats[s]&&typeof ae.stats[s]=="object"){let r=e.stats[s]||{},a=ae.stats[s];for(let i in r)if(typeof r[i]=="number")a[i]=Math.max(a[i]||0,r[i]);else if(r[i]&&typeof r[i]=="object"){a[i]||(a[i]={});for(let p in r[i])if(typeof r[i][p]=="number")a[i][p]=Math.max(a[i][p]||0,r[i][p]);else if(r[i][p]&&typeof r[i][p]=="object"){a[i][p]||(a[i][p]={});for(let d in r[i][p])a[i][p][d]=Math.max(a[i][p][d]||0,r[i][p][d])}}}}}if(e&&e.history){let s={...ae.history||{}};for(let r in e.history)if(s[r])for(let a in s[r])if(a==="imageCalls"){let i=Array.isArray(e.history[r].imageCalls)?e.history[r].imageCalls:[],p=Array.isArray(s[r].imageCalls)?s[r].imageCalls:[],d=new Map;for(let c of[...i,...p])c&&c.timestamp&&d.set(c.timestamp,c);s[r].imageCalls=Array.from(d.values())}else typeof s[r][a]=="number"&&(s[r][a]=Math.max(s[r][a],Number(e.history[r][a])||0));else s[r]=e.history[r];ae.history=Ms(s,ae.date||today)}else if(ae&&ae.history){let s=new Date().toISOString().split("T")[0];ae.history=Ms(ae.history,s)}ae.saveId=fl();let n=en+".tmp",t=Gs(JSON.stringify(ae,null,2));await bt.writeFile(n,t,"utf8");let o=await bt.open(n,"r+");await bt.fsync(o),await bt.close(o),await bt.rename(n,en),Cs=!1,Oi=Date.now()}catch{}},Co=()=>{if(Cs=!0,Gn)return;let e=Date.now(),n=Math.max(0,1500-(e-Oi));Gn=setTimeout(async()=>{await ir(),Gn=null},n),Gn.unref&&Gn.unref()},Dd=async()=>{ae=await $o(),Cs&&Co()},Fd=async()=>{Gn&&(clearTimeout(Gn),Gn=null),await ir()},Sn=async()=>{let e=new Date().toISOString().split("T")[0];if(!ae)ae=await $o();else if(ae.date!==e){let n=ae.date,t=ae.stats,o=ae.history||{};t&&(o[n]=t),ae={date:e,stats:{...vn},history:Ms(o,e)},Cs=!0,await ir()}return ae&&ae.stats&&!Array.isArray(ae.stats.imageCalls)&&(ae.stats.imageCalls=[]),ae.stats},ul=async()=>{let e=new Date().toISOString().split("T")[0];ae||(ae=await $o()),ae.date!==e&&await Sn();let n=ae.history||{},t=Ms(n,e);ae.history=t;let o=ae.stats||{...vn},s={...vn};s.imageCalls=[],s.models={};let r=(a,i)=>{for(let p in a)if(p==="imageCalls")a.imageCalls=[...a.imageCalls||[],...i.imageCalls||[]];else if(p==="models"){let d=i.models||{};for(let c in d){a.models[c]||(a.models[c]={});for(let l in d[c]){a.models[c][l]||(a.models[c][l]={tokens:0,cachedTokens:0,candidateTokens:0});let f=a.models[c][l],u=d[c][l];f.tokens+=u.tokens||0,f.cachedTokens+=u.cachedTokens||0,f.candidateTokens+=u.candidateTokens||0}}}else typeof a[p]=="number"&&(a[p]+=i[p]||0)};r(s,o);for(let a in t)r(s,t[a]);return s},Ot=async(e,n)=>{e==="toolSuccess"?Xs.toolSuccess++:e==="toolFailure"?Xs.toolFailure++:e==="toolDenied"&&Xs.toolDenied++;let t=await Sn();t[e]!==void 0&&t[e]++,n&&e==="agent"&&(t.providerRequests||(t.providerRequests={}),t.providerRequests[n]=(t.providerRequests[n]||0)+1),Co()},Xs={linesAdded:0,linesRemoved:0,toolSuccess:0,toolFailure:0,toolDenied:0},Kt=async(e,n,t,o)=>{e==="linesAdded"?Xs.linesAdded+=n:e==="linesRemoved"&&(Xs.linesRemoved+=n);let s=await Sn();if(s[e]!==void 0&&(s[e]+=Math.floor(n)),t&&o&&(e==="tokens"||e==="cachedTokens"||e==="candidateTokens")){s.models||(s.models={}),s.models[t]||(s.models[t]={}),s.models[t][o]||(s.models[t][o]={tokens:0,cachedTokens:0,candidateTokens:0});let r=s.models[t][o];e==="tokens"&&(r.tokens+=Math.floor(n)),e==="cachedTokens"&&(r.cachedTokens+=Math.floor(n)),e==="candidateTokens"&&(r.candidateTokens+=Math.floor(n))}Co()},hl=async(e=1)=>{let n=new Date,t=n.toISOString().split("T")[0];ae||(ae=await $o()),ae.date!==t&&await Sn();let o=n.getFullYear(),s=n.getMonth();n.getDate()<e&&(s-=1,s<0&&(s=11,o-=1));let i=new Date(o,s,e).toISOString().split("T")[0],p=ae.history||{},d=ae.stats||{...vn},c={...vn};c.imageCalls=[],c.models={};let l=(f,u)=>{for(let h in f)if(h==="imageCalls")f.imageCalls=[...f.imageCalls||[],...u.imageCalls||[]];else if(h==="models"){let g=u.models||{};for(let y in g){f.models[y]||(f.models[y]={});for(let m in g[y]){f.models[y][m]||(f.models[y][m]={tokens:0,cachedTokens:0,candidateTokens:0});let w=f.models[y][m],b=g[y][m];w.tokens+=b.tokens||0,w.cachedTokens+=b.cachedTokens||0,w.candidateTokens+=b.candidateTokens||0}}}else typeof f[h]=="number"&&(f[h]+=u[h]||0)};l(c,d);for(let f in p)f>=i&&f<t&&l(c,p[f]);return c},ar=async(e,n={})=>{let t=await Ft().catch(()=>({})),o=n.apiTier||t.apiTier||"Free",s=n.quotas||n.systemSettings?.quotas||t.quotas||{},r=s.providerBudgets||{},a=!!r.__useProvider,i=n.aiProvider||t.aiProvider||"Google",p=a&&!!r[i],d=()=>{if(p){let c=r[i];return{agentLimit:typeof c.agentLimit=="number"&&c.agentLimit>0?c.agentLimit:99999999,tokenLimit:typeof c.tokenLimit=="number"&&c.tokenLimit>0?c.tokenLimit:99999999999999,monthlyTokenLimit:typeof c.monthlyTokenLimit=="number"&&c.monthlyTokenLimit>0?c.monthlyTokenLimit:99999999999999}}return{agentLimit:s.agentLimit||99999999,tokenLimit:s.tokenLimit||99999999999999,monthlyTokenLimit:s.monthlyTokenLimit||99999999999999}};if(e==="agent"){let{agentLimit:c,tokenLimit:l,monthlyTokenLimit:f}=d(),u=await Sn(),h;s.resetMode==="Custom"?h=await hl(s.resetDay||1):h=await ul();let g=0,y=0,m=0;if(p){g=u.providerRequests?.[i]||0;let w=u.models?.[i]||{};for(let T in w)y+=w[T]?.tokens||0;let b=h.models?.[i]||{};for(let T in b)m+=b[T]?.tokens||0}else g=u.agent||0,y=u.tokens||0,m=h.tokens||0;return o==="Free"&&u.agent+u.background>=999999?{allowed:!1,reason:"Free Tier Daily Usage Limit Exceeded"}:g>=c?{allowed:!1,reason:p?`Daily Request Limit Reached for ${i}`:"Daily Agent Request Limit Reached"}:y>=l?{allowed:!1,reason:p?`Daily Token Budget Exhausted for ${i}`:"Daily Token Budget Exhausted"}:m>=f?{allowed:!1,reason:p?`Monthly Token Budget Exhausted for ${i}`:"Monthly Token Budget Exhausted"}:{allowed:!0}}if(e==="background"){let c=await Sn();if(o==="Free"&&c.agent+c.background>=999999)return{allowed:!1,reason:"Free Tier Background Limit Exceeded"};let l=c.background<(s.backgroundLimit||999999);return{allowed:l,reason:l?void 0:"Background Request Limit Exceeded"}}if(e==="search"){let l=(await Sn()).search<(s.searchLimit||100);return{allowed:l,reason:l?void 0:"Search Quota Exceeded"}}return{allowed:!0}},Li=async(e,n={})=>(await ar(e,n)).allowed,lr=e=>{if(!e||e.length===0)return[];let t=[...e].sort((s,r)=>s.timestamp-r.timestamp),o=[];for(let s of t){if(o.length>0){let r=o[o.length-1];if(s.timestamp>=r.start&&s.timestamp<r.end){r.calls.push(s),r.spent+=s.cost;continue}}o.push({start:s.timestamp,end:s.timestamp+36e5,calls:[s],spent:s.cost})}return o},Pi=(e,n)=>{if(!e||e.length===0)return .025;let o=lr(e);if(o.length===0)return .025;let s=[];for(let l of o){let f=.025;if(s.length>0){let h=s[s.length-1],g=!1;if(s.length>=2){let y=s[s.length-2];h.ratio>=.8&&y.ratio>=.8&&(g=!0)}if(g)f=.015;else{let y=h.limit,m=h.ratio;m>=.8?f=y===.015?.015:y:m<.4?f=Math.min(.025,y+.005):m>=.4&&m<.6?f=Math.min(.025,y+.004):f=Math.min(.025,y+.002)}}let u=f>0?l.spent/f:0;s.push({limit:f,spent:l.spent,ratio:u})}let r=o[o.length-1];if(n<r.end)return s[s.length-1].limit;let a=s[s.length-1].limit,i=a,p=s[s.length-1].ratio,d=r.end,c=0;for(let l=s.length-1;l>=0&&s[l].ratio>=.8;l--)c++;for(;d<=n;){let l=.025;c>=2?l=.015:p>=.8?l=i===.015?.015:i:p<.4?l=Math.min(.025,i+.005):p>=.4&&p<.6?l=Math.min(.025,i+.004):l=Math.min(.025,i+.002),i=l,p=0,c=0,d+=36e5,a=l}return a},Di=async e=>{let n=e.imageSettings||{keyType:"Default",quality:"Low-High"};if(n.keyType!=="Default")return!0;let o={Low:.001,"Low-High":.002,Medium:.008,"Medium-High":.01,High:.045,Ultra:.0488,Premium:.15}[n.quality]||.002,s=await Sn();s.imageCalls||(s.imageCalls=[]);let r=Date.now(),a=lr(s.imageCalls),i=0;if(a.length>0){let d=a[a.length-1];r>=d.start&&r<d.end&&(i=d.spent)}let p=Pi(s.imageCalls,r);return i+o<=p},Fi=async()=>{let e=await Sn();e.imageCalls||(e.imageCalls=[]);let n=Date.now(),t=lr(e.imageCalls),o=[],s=0,r=0;if(t.length>0){let d=t[t.length-1];n>=d.start&&n<d.end&&(o=d.calls,s=d.spent,r=Math.max(0,Math.ceil((d.end-n)/(60*1e3))))}let a=Pi(e.imageCalls,n),i=Math.max(0,a-s),p=s;return{totalSpent:s,remaining:i,activeCallsCount:o.length,nextResetMin:r,reclaimCost:p,limit:a}},Ni=async e=>{let n=e.imageSettings||{keyType:"Default",quality:"Low-High"},o={Low:.001,"Low-High":.002,Medium:.008,"Medium-High":.01,High:.045,Ultra:.0488,Premium:.1}[n.quality]||.002,s=await Sn();s.imageCalls||(s.imageCalls=[]),s.imageCalls.push({timestamp:Date.now(),cost:o}),Co()};import Wi from"puppeteer";import ji from"fs";import Hi from"path";import Bi from"os";import Js from"path";import As from"fs";import{createRequire as pl}from"module";import{fileURLToPath as ml}from"url";var gl=pl(import.meta.url),Ui=Js.dirname(ml(import.meta.url));function ls(){let e=Bi.platform(),n=Bi.arch(),t="",o="",s="";if(e==="win32")t=n==="x64"?"win64":"win32",o="chrome.exe",s=`chrome-${t}`;else if(e==="darwin"){t=n==="arm64"?"mac_arm":"mac";let a=n==="arm64"?"arm64":"x64";o="Google Chrome.app/Contents/MacOS/Google Chrome",s=`chrome-mac-${a}`}else if(e==="linux")t="linux",o="chrome",s="chrome-linux64";else return{};let r=Js.resolve(Ui,"..","..",".puppeteerrc.cjs");if(As.existsSync(r)||(r=Js.resolve(Ui,"..",".puppeteerrc.cjs")),!As.existsSync(r))return{};try{let a=gl(r),i=a.cacheDirectory,p=a.chrome?.version;if(i){if(process.env.PUPPETEER_CACHE_DIR=i,p){let l=Js.join(i,"chrome",`${t}-${p}`,s,o);if(As.existsSync(l))return{executablePath:l,cacheDirectory:i}}let d=l=>{if(!As.existsSync(l))return null;try{let f=As.readdirSync(l),u=[];for(let h of f){let g=Js.join(l,h),y;try{y=As.statSync(g)}catch{continue}if(y.isDirectory())u.push(g);else if(h.toLowerCase()===o.toLowerCase()&&(!p||g.includes(p)))return g}if(p){for(let h of u)if(h.includes(p)){let g=d(h);if(g)return g}}for(let h of u)if(!p||!h.includes(p)){let g=d(h);if(g)return g}}catch{}return null},c=d(i);if(c)return{executablePath:c,cacheDirectory:i}}}catch{}return{}}var cr=async e=>{let{query:n,limit:t=5,aiMode:o=!1}=O(e);if(!n)return'ERROR: Missing "query" argument for web_search.';let s=3,r=null;if(o){let a=`Query: ${n}
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 i=1;i<=s;i++){let p=null;try{let d=ls();p=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 p.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,h=45e3,g=Date.now();for(;Date.now()-g<h&&(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(se=>se.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 p=null;try{let d=ls();p=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 p.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(E=>setTimeout(E,l));let f=`https://search.brave.com/ask?q=${encodeURIComponent(a)}&source=web`;await c.goto(f,{waitUntil:"domcontentloaded",timeout:18e4});let u=null,h=45e3,g=Date.now();for(;Date.now()-g<h&&(u=await c.evaluate(()=>{let E=Array.from(document.querySelectorAll('.message:not(.user), .answer-text, .llm-content, [data-type="answer"]')),x="";if(E.length>0&&(x=E.map(re=>re.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,P=I?I.innerText.trim():"",B=/^(?:[✓✔]\s*)?Finished/i.test(P)||!!(I&&I.querySelector(".status-finished, .finished")),N=!C&&(B||k.includes("Sources:")&&!C),Y={};return document.querySelectorAll("a[href]").forEach(se=>{let Ie=se.getAttribute("href")||se.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=se.innerText.trim();U&&(Y[U]=Ie),se.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
- `)){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(`
224
+ `)),x||(x=document.body.innerText),x.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=E[0]||document.body,L=I?I.innerText.trim():"",N=/^(?:[✓✔]\s*)?Finished/i.test(L)||!!(I&&I.querySelector(".status-finished, .finished")),W=!C&&(N||x.includes("Sources:")&&!C),X={};return document.querySelectorAll("a[href]").forEach(re=>{let Y=re.getAttribute("href")||re.href||"";if(Y.includes("uddg=")&&(Y=decodeURIComponent(Y.split("uddg=")[1].split("&")[0])),Y.includes("url=")&&(Y=decodeURIComponent(Y.split("url=")[1].split("&")[0])),Y&&(Y.startsWith("http://")||Y.startsWith("https://"))&&!Y.includes("search.brave.com")){let F=re.innerText.trim();F&&(X[F]=Y),re.textContent=Y}}),{isFinished:W,text:x,hrefMap:X}}),!(u&&u.isFinished));)await new Promise(E=>setTimeout(E,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,T="";if(y.includes("Sources:")){let E=y.split("Sources:");b=E[0],T=E.slice(1).join("Sources:")}let $=[];for(let E of b.split(`
225
+ `)){let x=E.trim();x&&(/^(View all|Finished|Searching|Answering|Thinking)$/i.test(x)||/^[\+\-]?\d+$/.test(x)||x.includes("search.brave.com")||x.startsWith("https://www.youtube.com/watch")||x.startsWith("https://youtube.com/watch")||$.push(E))}let R=$.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(x){let _=x.match(/https?:\/\/[^\s\)\>]+/g)||[],k=[];for(let I of _){let P=I.replace(/[\.\,\;]+$/,""),B=Object.keys(m).find(N=>N.startsWith(P)||P.startsWith(N));B&&m[B]&&(P=m[B]),S(P)||k.push(P)}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(),k=E=>!E||E.includes("search.brave.com")||E.includes("youtube.com")||E.includes("youtu.be"),S="";if(T){let E=T.match(/https?:\/\/[^\s\)\>]+/g)||[],x=[];for(let I of E){let L=I.replace(/[\.\,\;]+$/,""),N=Object.keys(m).find(W=>W.startsWith(L)||L.startsWith(W));N&&m[N]&&(L=m[N]),k(L)||x.push(L)}Object.values(m).forEach(I=>{!k(I)&&!x.includes(I)&&x.push(I)});let C=Array.from(new Set(x));C.length>0&&(S=`Sources:
229
229
  `+C.map(I=>`- ${I}`).join(`
230
- `))}let $=R+(T?`
230
+ `))}let _=R+(S?`
231
231
 
232
- `+T:"");if(!$||/^(\+\d+|Searching|Answering|Thinking|Finished)$/i.test($))throw new Error("EMPTY_AI_RESPONSE");return await p.close(),`AI Search results for [${n}]:
232
+ `+S:"");if(!_||/^(\+\d+|Searching|Answering|Thinking|Finished)$/i.test(_))throw new Error("EMPTY_AI_RESPONSE");return await p.close(),`AI Search results for [${n}]:
233
233
 
234
- ${$}`}catch(d){if(r=d,ji.writeFileSync(Hi.join(fn,"web_tools","search","ai_mode","ERROR.txt"),d.message),p&&await p.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 p=ls();i=await Wi.launch({headless:!0,executablePath:p.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
- 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 i.close(),`No results found for query: [${n}].`}let u=f.join(`
234
+ ${_}`}catch(d){if(r=d,ji.writeFileSync(Hi.join(fn,"web_tools","search","ai_mode","ERROR.txt"),d.message),p&&await p.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 p=ls();i=await Wi.launch({headless:!0,executablePath:p.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"),T=m.querySelector(".result__snippet"),$=b?b.href:"";$.includes("uddg=")&&($=decodeURIComponent($.split("uddg=")[1].split("&")[0]));let R=b?b.innerText.trim():"No Title",k=T?T.innerText.trim():"No Snippet";return`${w+1}. ${R}
235
+ Source: ${$}
236
+ Snippet: ${k}`}),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
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(p){if(r=p,i&&await i.close(),ji.writeFileSync(Hi.join(fn,"web_tools","search","standard_mode","ERROR.txt"),p.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 gl from"puppeteer";import yl from"turndown";import{gfm as wl}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 gl.launch({headless:!0,executablePath:i.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let p=await a.newPage();await p.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 p.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 p.goto(t,{waitUntil:"networkidle2",timeout:18e4}),await new Promise(g=>setTimeout(g,5e3));let c=await p.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(`
242
+ ${u}`}catch(p){if(r=p,i&&await i.close(),ji.writeFileSync(Hi.join(fn,"web_tools","search","standard_mode","ERROR.txt"),p.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 yl from"puppeteer";import wl from"turndown";import{gfm as xl}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 yl.launch({headless:!0,executablePath:i.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let p=await a.newPage();await p.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 p.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 p.goto(t,{waitUntil:"networkidle2",timeout:18e4}),await new Promise(g=>setTimeout(g,5e3));let c=await p.evaluate(()=>{document.querySelectorAll("script, style, noscript, svg, canvas, iframe, ad, .ads, link, meta, img").forEach(T=>T.remove());let y=document.createNodeIterator(document.body,NodeFilter.SHOW_COMMENT),m;for(;m=y.nextNode();)m.remove();for(document.querySelectorAll("*").forEach(T=>{let $=T.attributes;for(let R=$.length-1;R>=0;R--){let k=$[R].name;k!=="href"&&k!=="src"&&T.removeAttribute(k)}});document.querySelector("div, span");)document.querySelectorAll("div, span").forEach(T=>{T.parentNode&&T.replaceWith(...T.childNodes)});document.querySelectorAll("br").forEach(T=>{T.replaceWith(document.createTextNode(`
243
243
 
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,`
244
+ `))});let b=()=>{let T=!1;document.querySelectorAll("*").forEach($=>{$.childNodes.length===0&&!$.innerText.trim()&&($.remove(),T=!0)}),T&&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 yl({headingStyle:"atx",codeBlockStyle:"fenced"});f.use(wl);let u=f.turndown(l).replace(/\.\s*\n/g,`
249
+ `).trim(),f=new wl({headingStyle:"atx",codeBlockStyle:"fenced"});f.use(xl);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,16 +254,16 @@ ${u}`}catch(p){if(r=p,i&&await i.close(),ji.writeFileSync(Hi.join(fn,"web_tools"
254
254
 
255
255
  ${h}${u.length>5e4?`
256
256
 
257
- [TRUNCATED AT 50K CHARS]`:""}`}catch(i){if(s=i,a&&await a.close(),r<o){let p=Math.pow(2,r)*1e3;await new Promise(d=>setTimeout(d,p))}}}return`ERROR: Scrape failed after ${o+1} attempts. Last error: ${s.message}`};var xl=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"),h=e.match(u);return h?h[1].trim():null},o=t("action"),s=t("method"),r=t("content"),a=t("content-new"),i=t("content-old"),p=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=Q(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=Q(Dt,[]).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}]`,h=xl,g=c.reduce((b,x)=>b+(x.memory?.length||0),0);for(;c.length>0&&g+u.length>h;){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(Dt,c),`SUCCESS: Memory added with ID [${w.id}] and score [${w.score}]. (Vault Size: ${g+u.length} chars)`}if(s==="update"){let l=p||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 h=new Date,g=`${h.getDate()}/${h.getMonth()+1}/${h.getFullYear()}`,y=f.includes("[Saved on:")?f:`${f.trim()} [Saved on: ${g}]`;return c[u].memory=y,pe(Dt,c),`SUCCESS: Memory [${l}] updated.`}if(s==="delete"){let l=p||r;if(!l)return"ERROR: Missing 'id' for deletion.";let f=c.length,u=c.filter(h=>h.id!==l);return u.length===f?`ERROR: Memory ID [${l}] not found.`:(pe(Dt,u),`SUCCESS: Memory [${l}] deleted.`)}return`ERROR: Invalid method [${s}] for user memory. Use 'add', 'update', or 'delete'.`}return`ERROR: Unknown action [${o}] for memory tool.`};var 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:p}=O(e),d=parseInt(o||r||i),c=parseInt(s||a||p),l=!isNaN(d),f=!isNaN(c),u=d||1,h=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 P=Mo.readFileSync(g).toString("base64"),B=b[m];return{text:`[BINARY FILE]: ${t} (${B}) - Loaded as multimodal part.`,binaryPart:{inlineData:{data:P,mimeType:B}}}}let x=Mo.readFileSync(g,"utf8");x.startsWith("\uFEFF")&&(x=x.slice(1)),x=x.replace(/\r\n/g,`
257
+ [TRUNCATED AT 50K CHARS]`:""}`}catch(i){if(s=i,a&&await a.close(),r<o){let p=Math.pow(2,r)*1e3;await new Promise(d=>setTimeout(d,p))}}}return`ERROR: Scrape failed after ${o+1} attempts. Last error: ${s.message}`};var bl=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"),h=e.match(u);return h?h[1].trim():null},o=t("action"),s=t("method"),r=t("content"),a=t("content-new"),i=t("content-old"),p=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=Z(tn,{});c[d]||(c[d]=[]),c[d].push(r),me(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=Z(Dt,[]).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}]`,h=bl,g=c.reduce((b,T)=>b+(T.memory?.length||0),0);for(;c.length>0&&g+u.length>h;){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),me(Dt,c),`SUCCESS: Memory added with ID [${w.id}] and score [${w.score}]. (Vault Size: ${g+u.length} chars)`}if(s==="update"){let l=p||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 h=new Date,g=`${h.getDate()}/${h.getMonth()+1}/${h.getFullYear()}`,y=f.includes("[Saved on:")?f:`${f.trim()} [Saved on: ${g}]`;return c[u].memory=y,me(Dt,c),`SUCCESS: Memory [${l}] updated.`}if(s==="delete"){let l=p||r;if(!l)return"ERROR: Missing 'id' for deletion.";let f=c.length,u=c.filter(h=>h.id!==l);return u.length===f?`ERROR: Memory ID [${l}] not found.`:(me(Dt,u),`SUCCESS: Memory [${l}] deleted.`)}return`ERROR: Invalid method [${s}] for user memory. Use 'add', 'update', or 'delete'.`}return`ERROR: Unknown action [${o}] for memory tool.`};var 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:p}=O(e),d=parseInt(o||r||i),c=parseInt(s||a||p),l=!isNaN(d),f=!isNaN(c),u=d||1,h=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 L=Mo.readFileSync(g).toString("base64"),N=b[m];return{text:`[BINARY FILE]: ${t} (${N}) - Loaded as multimodal part.`,binaryPart:{inlineData:{data:L,mimeType:N}}}}let T=Mo.readFileSync(g,"utf8");T.startsWith("\uFEFF")&&(T=T.slice(1)),T=T.replace(/\r\n/g,`
258
258
  `).replace(/\r/g,`
259
- `);let E=x.split(`
260
- `),R=E.length;!l&&!f&&R>800&&(u=1,h=50);let S=Math.max(0,u-1),T=Math.min(R,h),$=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
- `);return`${_}
259
+ `);let $=T.split(`
260
+ `),R=$.length;!l&&!f&&R>800&&(u=1,h=50);let k=Math.max(0,u-1),S=Math.min(R,h),_=$.slice(k,S),E=`File: [${t}] (Showing lines ${k+1}-${S} of ${R}).`,x=_.map((C,I)=>`${String(k+I+1).padStart(4)}: ${C.trimEnd()}`).join(`
261
+ `);return`${E}
262
262
 
263
- ${k}`}catch(y){let m=y instanceof Error?y.message:String(y);return`ERROR: Failed to read file [${t}]: ${m}`}};import vs from"fs";import 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,`
263
+ ${x}`}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
265
  `);let s=qi.resolve(process.cwd(),t),r=qi.dirname(s);try{await mt.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(`
266
+ ${vs.readFileSync(s,"utf8").split(/\r?\n/).map(($,R)=>`${R+1} | ${$}`).join(`
267
267
  `)}
268
268
 
269
269
  `}catch{a=`[Note: Could not read existing file for reversal reference]
@@ -274,69 +274,69 @@ ${vs.readFileSync(s,"utf8").split(/\r?\n/).map((E,R)=>`${R+1} | ${E}`).join(`
274
274
  `)?p:p+`
275
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"),h=f.split(/\r?\n/),g=h.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=h.join(`
276
276
  `);else{let b=h.slice(0,50).join(`
277
- `),x=h.slice(-50).join(`
277
+ `),T=h.slice(-50).join(`
278
278
  `);y=`${b}
279
279
 
280
280
  ... [${g-100} lines truncated] ...
281
281
 
282
- ${x}`}f=null;let{systemSettings:m}=await Ft(),w=`SUCCESS: File [${t}] saved.
282
+ ${T}`}f=null;let{systemSettings:m}=await Ft(),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 b=d.split(/\r?\n/),x=b.slice(0,25).join(`
286
+ ${y}`;if(m?.compressToolResults&&g>60){let b=d.split(/\r?\n/),T=b.slice(0,25).join(`
287
287
  `)===h.slice(0,25).join(`
288
- `),E=b.slice(-25).join(`
288
+ `),$=b.slice(-25).join(`
289
289
  `)===h.slice(-25).join(`
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 vl from"path";import bl 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(`
290
+ `);T&&$&&(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 Il from"path";import kl 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
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 p=a.split(/(\s+)/),d="",c=0,l=a.match(/^(\s*)/),f=l?l[1]:"";p.forEach((u,h)=>{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
- `))},Tf=e=>{if(!e&&e!==0)return"0.0k";let n=typeof e=="string"?parseFloat(e):e;return n>=1e6?`${(n/1e6).toFixed(1)}m`:n>=1e3?`${(n/1e3).toFixed(1)}k`:n.toString()},Rf=(e,n=40)=>{let t=Mn.replaceAll("\\\\","\\");if(e=e.replace(bl.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(p=>{let d=p.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((p,d)=>p-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=(p,d,c)=>{let l,f;for(let u of d){let h=p===1?[`${u}1`,u,`${u}_1`]:[`${u}${p}`,`${u}_${p}`];for(let g of h)if(e[g]!==void 0){l=e[g];break}if(l!==void 0)break}for(let u of c){let h=p===1?[`${u}1`,u,`${u}_1`]:[`${u}${p}`,`${u}_${p}`];for(let g of h)if(e[g]!==void 0){f=e[g];break}if(f!==void 0)break}return{r:l,n:f}};for(let p of s){let{r:d,n:c}=i(p,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 ${p}. Both replacement and new content must be provided.`,allowMultiple:o}}return{patchPairs:n,allowMultiple:o}},kl=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===`
293
+ `))},Rf=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()},Ef=(e,n=40)=>{let t=Mn.replaceAll("\\\\","\\");if(e=e.replace(kl.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(p=>{let d=p.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((p,d)=>p-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=(p,d,c)=>{let l,f;for(let u of d){let h=p===1?[`${u}1`,u,`${u}_1`]:[`${u}${p}`,`${u}_${p}`];for(let g of h)if(e[g]!==void 0){l=e[g];break}if(l!==void 0)break}for(let u of c){let h=p===1?[`${u}1`,u,`${u}_1`]:[`${u}${p}`,`${u}_${p}`];for(let g of h)if(e[g]!==void 0){f=e[g];break}if(f!==void 0)break}return{r:l,n:f}};for(let p of s){let{r:d,n:c}=i(p,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 ${p}. Both replacement and new content must be provided.`,allowMultiple:o}}return{patchPairs:n,allowMultiple:o}},Sl=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
295
  `&&e[t]!=="\r"&&e[t]!==" ";)t++;n+="\\s*"}else n+=s,t++}if(!n)return null;try{return new RegExp(n,"g")}catch{return null}},vo=(e,n,t={})=>{let o=typeof t=="boolean"?t:!!(t&&t.allowMultiple),s=e.replace(/\r\n/g,`
296
296
  `).replace(/\r/g,`
297
297
  `),r=m=>m.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
298
298
  `).replace(/\r/g,`
299
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},p=(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
- `).map((C,I)=>{if(C.trim()===""&&I!==0)return"";let P=C.match(/^\s*/)[0].length,B=Math.max(0,P+$);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],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
- `);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: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 $=kl(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,h=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+h,R=f.lastIndexOf(`
308
- `,x)+1,S=f.substring(R,x),T=p(m.content_to_add,m.firstMatchContent,S),$=f.split(`
309
- `),_=[];for(let P=Math.max(0,E-4);P<E-1;P++)_.push({num:P+1,text:$[P]});let k=m.firstMatchContent.split(`
310
- `),C=[],I=E+k.length-1;for(let P=I;P<Math.min($.length,I+3);P++)C.push({num:P+1,text:$[P]});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,h+=T.split(`
300
+ `).filter(T=>T.trim()!=="");if(w.length===0)return"";let b=a(w[0]);for(let T of w){let $=a(T);$.length<b.length&&(b=$)}return b},p=(m,w,b="")=>{if(!m||w===void 0)return m;let $=/^\t/m.test(w)?" ":" ",R=C=>C.split(`
301
+ `).find(I=>I.trim()!=="")??"",k=R(w).match(/^\s*/)[0].length,S=R(m).match(/^\s*/)[0].length,_=k-S,E=(b.match(/^\s*/)||[""])[0].length;return m.split(`
302
+ `).map((C,I)=>{if(C.trim()===""&&I!==0)return"";let L=C.match(/^\s*/)[0].length,N=Math.max(0,L+_);return I===0&&(N=Math.max(0,N-E)),$.repeat(N)+C.trimStart()}).join(`
303
+ `)},d=[];for(let m=0;m<n.length;m++){let w=n[m],b=(w.replace||"").trim(),T=r(w.new||"");if(b.startsWith("^LINE:")&&b.endsWith("$")){let E=b.slice(6,-1).trim().split(".."),x=parseInt(E[0]),C=E[1]!==void 0?parseInt(E[1]):x;if(!isNaN(x)&&!isNaN(C)){let I=s.split(`
304
+ `);if(x<1||x>I.length||C<x||C>I.length){d.push({index:m,success:!1,error:`Block ${m+1}: Line range ^LINE:${x}..${C}$ out of bounds (file has ${I.length} lines).`});continue}let N=I.slice(x-1,C).join(`
305
+ `),W=0;for(let X=0;X<x-1;X++)W+=I[X].length+1;d.push({index:m,success:!0,startPos:W,firstMatchContent:N,content_to_add:T});continue}}let $=r(w.replace||"");if($===""&&T===""){d.push({index:m,success:!1,error:`Block ${m+1}: Empty replace and add content.`});continue}let R=$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),k=null;if($!==""&&s.includes($))k=new RegExp(R,"g");else{let _=$.split(`
306
+ `).map(E=>E.trim()).filter(E=>E.length>0).map(E=>E.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\s+/g,"\\s*"));if(_.length>0){let E=_.join("\\s*");try{k=new RegExp(E,"g")}catch{k=new RegExp(R,"g")}}else k=new RegExp(R,"g")}let S=[...s.matchAll(k)];if(S.length===0&&$!==""){let _=Sl($);_&&(S=[...s.matchAll(_)])}if(S.length===0){d.push({index:m,success:!1,error:`Block ${m+1}: Could not find match.`});continue}if(S.length>1&&!o){d.push({index:m,success:!1,error:`Block ${m+1}: Found ${S.length} matches (must be unique or use allowMultiple: true if sure).`});continue}for(let _ of S)d.push({index:m,success:!0,startPos:_.index,firstMatchContent:_[0],content_to_add:T})}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,h=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,T=w+u,$=b+h,R=f.lastIndexOf(`
308
+ `,T)+1,k=f.substring(R,T),S=p(m.content_to_add,m.firstMatchContent,k),_=f.split(`
309
+ `),E=[];for(let L=Math.max(0,$-4);L<$-1;L++)E.push({num:L+1,text:_[L]});let x=m.firstMatchContent.split(`
310
+ `),C=[],I=$+x.length-1;for(let L=I;L<Math.min(_.length,I+3);L++)C.push({num:L+1,text:_[L]});l.set(m,{success:!0,index:m.index,oldContent:m.firstMatchContent,newContent:S,originalStartLine:b,finalStartLine:$,contextBefore:E,contextAfter:C}),f=f.substring(0,T)+S+f.substring(T+m.firstMatchContent.length),u+=S.length-m.firstMatchContent.length,h+=S.split(`
311
311
  `).length-m.firstMatchContent.split(`
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),p=Math.max(4,String(i).length),d=g=>String(g).padStart(p," "),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(T=>T.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),p=Math.max(4,String(i).length),d=g=>String(g).padStart(p," "),c=`[DIFF_START]
313
313
  `,l="\u2550".repeat(88),f=0,u=null,h=t.filter(g=>g.success).sort((g,y)=>g.originalStartLine-y.originalStartLine);if(h.forEach((g,y)=>{let m=g.finalStartLine!==void 0?g.finalStartLine:g.originalStartLine;if(u===null)for(f=Math.max(0,m-4);f<m-1;)c+=`[UI_CONTEXT] ${d(f+1)} |${a[f]||""}
314
- `,f++;else{let T=u,$=T.originalStartLine+T.oldContent.split(`
315
- `).length-1;if(g.originalStartLine-$-1>=o){let k=Math.min(a.length,f+3);for(;f<k;)c+=`[UI_CONTEXT] ${d(f+1)} |${a[f]||""}
314
+ `,f++;else{let S=u,_=S.originalStartLine+S.oldContent.split(`
315
+ `).length-1;if(g.originalStartLine-_-1>=o){let x=Math.min(a.length,f+3);for(;f<x;)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,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
- `});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+x.length-1,$=r[T]||null;if($!==null){let _=y<h.length-1?(h[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]||""}
319
+ `,f++}let w=g.originalStartLine-1,b=r[w]||"",T=g.oldContent.split(`
320
+ `),$=b.match(/^\s*/),R=$?$[0]:"";T.forEach((S,_)=>{let E=S;if(T.length===1&&b.trim().length>0&&b.includes(S.trim()))E=b;else if(_===0){let x=S.match(/^\s*/);(x?x[0]:"").length<R.length&&b.includes(S.trim())&&(E=R+S.trimStart())}c+=`-${d(g.originalStartLine+_)} |${E}
321
+ `});let k=f;if(g.finalStartLine!==void 0)k=g.finalStartLine-1+(g.newContent?g.newContent.split(`
322
+ `).length:0);else{let S=g.originalStartLine+T.length-1,_=r[S]||null;if(_!==null){let E=y<h.length-1?(h[y+1].originalStartLine||a.length)+10:a.length;for(let x=f;x<E;x++){if(a[x]===_){k=x;break}x===a.length-1&&(k=a.length)}}else k=a.length}for(;f<k;)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
- `,b=y.split(m).map(x=>x.split(`
326
+ `,b=y.split(m).map(T=>T.split(`
327
327
  `).filter(R=>R.trim()!=="").length>45?`[[VERIFIED]]
328
- ${x}
329
- [[/VERIFIED]]`:x);c=g+b.join(m)}return c+="[DIFF_END]",pn(c)},Sl=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}},Tl=(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,p=new Int32Array(i+1),d=new Int32Array(i+1);for(let f=0;f<=i;f++)p[f]=f;for(let f=1;f<=a;f++){d[0]=f;let u=s[f-1];for(let h=1;h<=i;h++)u===r[h-1]?d[h]=p[h-1]:d[h]=Math.min(p[h],d[h-1],p[h-1])+1;p.set(d)}let c=p[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]=Tl(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,h=r[c-1][l-1]+u,g=r[c-1][l],y=r[c][l-1];h>=g&&h>=y?(r[c][l]=h,a[c][l]="diag"):g>=y?(r[c][l]=g,a[c][l]="up"):(r[c][l]=y,a[c][l]="left")}let p=o,d=s;for(;p>0||d>0;)if(a[p][d]==="diag"){if(i[p-1][d-1]>=.2){let l=n[p-1].index,f=t[d-1].index;e[l].pairContent=e[f].parsed.content,e[f].pairContent=e[l].parsed.content}p--,d--}else a[p][d]==="up"?p--: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))},Ef=(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(Al(e.text||"",e.role==="think")),s=`${e.id}-${n}`,r=new Map;if(e.isStreaming){let h=cs.get(s);h&&o.startsWith(h.text)&&(r=h.blocksMap)}let a=(h,g,y,m={})=>{let w=r.get(h);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:h,isStreamingMsg:!!e.isStreaming,workedDuration:e.workedDuration,type:g,text:b,msg:g==="full-message"?e:void 0,...x}};if(o.includes("- Content Preview:")){let h="",g=o.match(/File\s+\[(.*?)\]/i);g&&(h=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,P=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:h,wrappedLines:P});I&&e.isStreaming?($(),S=B):(T.push(B),T.length>=pr&&$())}),$(),{completed:R,active:S?[S]:[]}}if(o.includes("[DIFF_START]")){let h=o.match(/\[DIFF_START\]([\s\S]*?)(?:\[DIFF_END\]|$)/),y=(h?h[1].trim():"").split(`
332
- `).map(S=>S.replace(/\r$/,"")),m=y.map(S=>({line:S,parsed:Sl(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 h={completed:[],active:[]};return qn.set(t,h),h}let i=[],p=null,d=[],c=null,l=()=>{if(!d.length)return;let h=d;d=[],c=null,i.push(h.length===1?h[0]:{key:`${e.id||"x"}-chunk-${h[0].key}`,type:"chunk",blocks:h})},f=(h,g=!1)=>{if(c!==null&&c!==h.type&&l(),d.push(h),c=h.type,d.length>=pr){if(e.isStreaming&&g)return;l()}};if(e.role==="think"){i.push(a(`${e.id}-header`,"think-header",""));let h=o.split(`
328
+ ${T}
329
+ [[/VERIFIED]]`:T);c=g+b.join(m)}return c+="[DIFF_END]",pn(c)},Tl=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}},Rl=(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,p=new Int32Array(i+1),d=new Int32Array(i+1);for(let f=0;f<=i;f++)p[f]=f;for(let f=1;f<=a;f++){d[0]=f;let u=s[f-1];for(let h=1;h<=i;h++)u===r[h-1]?d[h]=p[h-1]:d[h]=Math.min(p[h],d[h-1],p[h-1])+1;p.set(d)}let c=p[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]=Rl(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,h=r[c-1][l-1]+u,g=r[c-1][l],y=r[c][l-1];h>=g&&h>=y?(r[c][l]=h,a[c][l]="diag"):g>=y?(r[c][l]=g,a[c][l]="up"):(r[c][l]=y,a[c][l]="left")}let p=o,d=s;for(;p>0||d>0;)if(a[p][d]==="diag"){if(i[p-1][d-1]>=.2){let l=n[p-1].index,f=t[d-1].index;e[l].pairContent=e[f].parsed.content,e[f].pairContent=e[l].parsed.content}p--,d--}else a[p][d]==="up"?p--: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))},_f=(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(vl(e.text||"",e.role==="think")),s=`${e.id}-${n}`,r=new Map;if(e.isStreaming){let h=cs.get(s);h&&o.startsWith(h.text)&&(r=h.blocksMap)}let a=(h,g,y,m={})=>{let w=r.get(h);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),T={...m};return typeof T.pairContent=="string"&&(T.pairContent=pn(T.pairContent)),Array.isArray(T.wrappedLines)&&(T.wrappedLines=T.wrappedLines.map(pn)),{key:h,isStreamingMsg:!!e.isStreaming,workedDuration:e.workedDuration,type:g,text:b,msg:g==="full-message"?e:void 0,...T}};if(o.includes("- Content Preview:")){let h="",g=o.match(/File\s+\[(.*?)\]/i);g&&(h=g[1].split(".").pop().toLowerCase());let T=((o.split("- Content Preview:")[1]||"").split("[SYSTEM] Check the content preview for verification [/SYSTEM]")[0]?.trim()||"").split(`
330
+ `).map(x=>x.replace(/\r$/,"")),$=String(T.length).length,R=[],k=null,S=[],_=()=>{if(!S.length)return;let x=S;S=[],R.push(x.length===1?x[0]:{key:`${x[0].key}-chunk`,type:"chunk",blocks:x})},E=n-($+6);return T.forEach((x,C)=>{let I=C===T.length-1,L=zi(x,E).split(`
331
+ `),N=a(`${e.id||Date.now()}-write-line-${C}`,"write-line",x,{gutterWidth:$,lineNum:C+1,isFirstLine:C===0,isLastLine:I,extension:h,wrappedLines:L});I&&e.isStreaming?(_(),k=N):(S.push(N),S.length>=pr&&_())}),_(),{completed:R,active:k?[k]:[]}}if(o.includes("[DIFF_START]")){let h=o.match(/\[DIFF_START\]([\s\S]*?)(?:\[DIFF_END\]|$)/),y=(h?h[1].trim():"").split(`
332
+ `).map(k=>k.replace(/\r$/,"")),m=y.map(k=>({line:k,parsed:Tl(k),pairContent:null})),w=[];for(let k=0;k<m.length;k++){let S=m[k];S.parsed&&(S.parsed.isR||S.parsed.isA)?w.push(S):w.length>0&&(Ki(w),w=[])}w.length>0&&Ki(w);let b=[],T=null,$=[],R=()=>{if(!$.length)return;let k=$;$=[],b.push(k.length===1?k[0]:{key:`${k[0].key}-chunk`,type:"chunk",blocks:k})};return y.forEach((k,S)=>{let _=S===y.length-1,E=m[S].parsed,x=null;E&&(x=zi(E.content,n-17).split(`
333
+ `));let C=a(`${e.id||Date.now()}-diff-${S}`,"diff-line",k,{isFirstLine:S===0,isLastLine:_,pairContent:m[S].pairContent,wrappedLines:x});_&&e.isStreaming?(R(),T=C):($.push(C),$.length>=pr&&R())}),R(),{completed:b,active:T?[T]:[]}}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 h={completed:[],active:[]};return qn.set(t,h),h}let i=[],p=null,d=[],c=null,l=()=>{if(!d.length)return;let h=d;d=[],c=null,i.push(h.length===1?h[0]:{key:`${e.id||"x"}-chunk-${h[0].key}`,type:"chunk",blocks:h})},f=(h,g=!1)=>{if(c!==null&&c!==h.type&&l(),d.push(h),c=h.type,d.length>=pr){if(e.isStreaming&&g)return;l()}};if(e.role==="think"){i.push(a(`${e.id}-header`,"think-header",""));let h=o.split(`
334
334
  `);h.forEach((g,y)=>{let m=y===h.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 h=o.split(`
335
- `),g=!1,y=[],m=!1,w=!1,b="",x=0,E=0;h.forEach((R,S)=>{let T=S===h.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]||"",P=C.slice(2).join("");I&&f(a(`${e.id}-think-${S}`,"think-line",I,{}),T&&!P),l(),i.push({key:`${e.id}-think-footer-${S}`,type:"think-footer-padding",text:""}),w=!1,P&&P.trim()&&f(a(`${e.id}-${S}`,"agent-line",P,{}),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?p=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?p=d.length===1?d[0]:{key:`${e.id||"x"}-chunk-active-${d[0].key}`,type:"chunk",blocks:d}:l();let u={completed:i,active:p?[p]:[]};if(e.isStreaming){let h=new Map;if(i.forEach(g=>gr(g,h)),p&&gr(p,h),cs.set(s,{text:o,blocksMap:h}),cs.size>Yi){let g=cs.keys().next().value;cs.delete(g)}}else{if(qn.set(t,u),qn.size>Yi){let h=qn.keys().next().value;qn.delete(h)}cs.delete(s)}return u},Rl={},El=/<\/think>(\r?\n){2}/gi,_l=/(\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,Cl=/(\$?\\?\/?\\rightarrow\$?|\$\\rightarrow\$)|(\$?\\?\/?\\leftarrow\$?|\$\\leftarrow\$)|(\$?\\?\/?\\uparrow\$?|\$\\uparrow\$)|(\$?\\?\/?\\downarrow\$?|\$\\downarrow\$)|(\$?\\?\/?\\leftrightarrow\$?|\$\\leftrightarrow\$)/gi,Ml=/\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,Al=(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(El,"</think>").replace(_l,(a,i,p,d)=>!Is&&mr(d,p)?a:"");o&&o.includes("[tool:")&&(o=o.replace(/<(\w+)(?:[^>]*)>\s*([\s\S]*?\[tool:[^\]]*\][\s\S]*?)\s*<\/\1>/gi,(a,i,p)=>p&&p.includes("[tool:")?p.trim():a),Is&&(o=o.replace(/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi,(a,i)=>i.includes("[tool:")?i.trim():a)));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),p=a.indexOf(r),d=s,c=i;if((i===-1||p!==-1&&p<i)&&(d=r,c=p),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 h=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==="("?(h++,g=!0):w===")"&&h--),g&&h===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 g&&h>0&&(o=o.substring(0,l)),o}}return o=o.replace($l,""),o=o.replace(Cl,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(Ml,a=>Rl[a.toLowerCase()]||a),o.trim()},_f=()=>{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,p=vl.resolve(process.cwd(),o);try{if(!yr.existsSync(p))return`ERROR: File [${o}] does not exist. Use WriteFile instead.`;let d=n.forcedContent||yr.readFileSync(p,"utf8");d.startsWith("\uFEFF")&&(d=d.slice(1));let c=d.replace(/\r\n/g,`
335
+ `),g=!1,y=[],m=!1,w=!1,b="",T=0,$=0;h.forEach((R,k)=>{let S=k===h.length-1,_=R.trim().startsWith("|"),E=R.trim().startsWith("```");if(w){if(R.includes("</think>")||R.includes("<channel|>")||R.includes("</thought>")){let x=R.split(/(?:<\/(think|thought|thoughts)>|<channel\|>)/i),C=x[0]||"",I=x.slice(2).join("");C&&f(a(`${e.id}-think-${k}`,"think-line",C,{}),S&&!I),l(),i.push({key:`${e.id}-think-footer-${k}`,type:"think-footer-padding",text:""}),w=!1,I&&I.trim()&&f(a(`${e.id}-${k}`,"agent-line",I,{}),S)}else f(a(`${e.id}-think-${k}`,"think-line",R,{}),S);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-${k}`,"table",y.join(`
336
+ `),{isStreaming:!1})),g=!1,y=[]),i.push(a(`${e.id}-think-header-${k}`,"think-header","")),w=!0;let x=R.replace(/^(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought\s*)\r?\n?/i,"");if(x.includes("</think>")||x.includes("<channel|>")||x.includes("</thought>")){let C=x.split(/(?:<\/(think|thought|thoughts)>|<channel\|>)/i),I=C[0]||"",L=C.slice(2).join("");I&&f(a(`${e.id}-think-${k}`,"think-line",I,{}),S&&!L),l(),i.push({key:`${e.id}-think-footer-${k}`,type:"think-footer-padding",text:""}),w=!1,L&&L.trim()&&f(a(`${e.id}-${k}`,"agent-line",L,{}),S)}else x&&f(a(`${e.id}-think-${k}`,"think-line",x,{}),S);return}m?E?(m=!1,f(a(`${e.id}-code-close-${$}`,"code-fence-close","",{}),S)):(T++,f(a(`${e.id}-code-line-${k}`,"code-line",R,{lineNum:T,lang:b}),S)):E?(m=!0,$=k,T=0,b=R.trim().replace(/^```/,"").trim(),f(a(`${e.id}-code-open-${k}`,"code-fence-open",b,{}),S)):_?(g=!0,y.push(R),S&&(l(),e.isStreaming?p=a(`${e.id}-table-${k}`,"table",y.join(`
337
+ `),{isStreaming:!0}):i.push(a(`${e.id}-table-${k}`,"table",y.join(`
338
+ `),{isStreaming:!1})))):(g&&(l(),i.push(a(`${e.id}-table-${k}`,"table",y.join(`
339
+ `),{isStreaming:!1})),g=!1,y=[]),f(a(`${e.id}-${k}`,"agent-line",R,{}),S))}),!e.isStreaming&&e.workedDuration&&(l(),i.push(a(`${e.id}-worked-duration`,"worked-duration","")))}e.isStreaming&&d.length>0?p=d.length===1?d[0]:{key:`${e.id||"x"}-chunk-active-${d[0].key}`,type:"chunk",blocks:d}:l();let u={completed:i,active:p?[p]:[]};if(e.isStreaming){let h=new Map;if(i.forEach(g=>gr(g,h)),p&&gr(p,h),cs.set(s,{text:o,blocksMap:h}),cs.size>Yi){let g=cs.keys().next().value;cs.delete(g)}}else{if(qn.set(t,u),qn.size>Yi){let h=qn.keys().next().value;qn.delete(h)}cs.delete(s)}return u},El={},_l=/<\/think>(\r?\n){2}/gi,$l=/(\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},Cl=/\[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,Ml=/(\$?\\?\/?\\rightarrow\$?|\$\\rightarrow\$)|(\$?\\?\/?\\leftarrow\$?|\$\\leftarrow\$)|(\$?\\?\/?\\uparrow\$?|\$\\uparrow\$)|(\$?\\?\/?\\downarrow\$?|\$\\downarrow\$)|(\$?\\?\/?\\leftrightarrow\$?|\$\\leftrightarrow\$)/gi,Al=/\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,vl=(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(_l,"</think>").replace($l,(a,i,p,d)=>!Is&&mr(d,p)?a:"");o&&o.includes("[tool:")&&(o=o.replace(/<(\w+)(?:[^>]*)>\s*([\s\S]*?\[tool:[^\]]*\][\s\S]*?)\s*<\/\1>/gi,(a,i,p)=>p&&p.includes("[tool:")?p.trim():a),Is&&(o=o.replace(/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi,(a,i)=>i.includes("[tool:")?i.trim():a)));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),p=a.indexOf(r),d=s,c=i;if((i===-1||p!==-1&&p<i)&&(d=r,c=p),c===-1)break;if(!Is&&mr(o,c)){let w=c+d.length,b=a.indexOf(s,w),T=a.indexOf(r,w);if(b===-1&&T===-1)break;let $=-1,R=0;for(;;){let k=a.indexOf(s,R),S=a.indexOf(r,R),_=-1,E=s;if(k===-1&&S===-1)break;if(k===-1||S!==-1&&S<k?(_=S,E=r):_=k,!mr(o,_)){$=_,d=E;break}R=_+E.length}if($===-1)break;c=$}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 h=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==="("?(h++,g=!0):w===")"&&h--),g&&h===0&&!y){let b=m;if(f){let T=m+1;for(;T<o.length&&/\s/.test(o[T]);)T++;T<o.length&&o[T]==="]"&&(b=T)}o=o.substring(0,l)+o.substring(b+1);break}if(m++,m===o.length)return g&&h>0&&(o=o.substring(0,l)),o}}return o=o.replace(Cl,""),o=o.replace(Ml,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(Al,a=>El[a.toLowerCase()]||a),o.trim()},$f=()=>{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,p=Il.resolve(process.cwd(),o);try{if(!yr.existsSync(p))return`ERROR: File [${o}] does not exist. Use WriteFile instead.`;let d=n.forcedContent||yr.readFileSync(p,"utf8");d.startsWith("\uFEFF")&&(d=d.slice(1));let c=d.replace(/\r\n/g,`
340
340
  `).replace(/\r/g,`
341
341
  `),{content:l,results:f}=vo(c,s,{allowMultiple:i}),u=f.filter(m=>!m.success),h=f.filter(m=>m.success);if(h.length===0)return`ERROR: Patch Failed to apply to [${o}].
342
342
  ${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 ds from"fs";import xr from"path";var Il=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"]),Ol=e=>Il.has(e)||e.startsWith(".pnpm"),Ll=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:Ll($.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
- `),E=`
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 Ol=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"]),Ll=e=>Ol.has(e)||e.startsWith(".pnpm"),Pl=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 k=xr.join(s,R),S={name:R,type:"unknown",size:"N/A",mtime:"N/A"};try{let _=ds.statSync(k);S={name:R,type:_.isDirectory()?"directory":"file",size:(_.size/1024).toFixed(1)+"KB",mtime:Pl(_.mtime)}}catch{S.type="inaccessible"}b.push(S)}let T=b.map(R=>R.type==="directory"?`${R.name}/`:`${R.name} (${R.size}, ${R.mtime})`).join(`
352
+ `),$=`
353
353
 
354
- (Total items in folder: ${y})`;return y>m&&(E=`
354
+ (Total items in folder: ${y})`;return y>m&&($=`
355
355
 
356
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
- ${x}${E}`}let a=0,i=0,p=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(p>=d){c=!0,E.push(`${R}[Truncated - Maximum item limit reached (${d})]`);break}if(p++,a++,E.push(`${R}${T.name}/`),y<o&&!Ol(T.name)){let $=l(T.fullPath,y+1,m+1);E.push(...$)}}let S=[];for(let T of x){if(p>=d){c=!0,E.push(`${R}[Truncated - Maximum item limit reached (${d})]`);break}p++,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(`
358
+ ${T}${$}`}let a=0,i=0,p=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=[],T=[];for(let S of w){let _=xr.join(g,S),E=!1;try{E=ds.statSync(_).isDirectory()}catch{}E?b.push({name:S,fullPath:_}):T.push({name:S,fullPath:_})}b.sort((S,_)=>S.name.localeCompare(_.name)),T.sort((S,_)=>S.name.localeCompare(_.name));let $=[],R=" ".repeat(m-1);for(let S of b){if(p>=d){c=!0,$.push(`${R}[Truncated - Maximum item limit reached (${d})]`);break}if(p++,a++,$.push(`${R}${S.name}/`),y<o&&!Ll(S.name)){let _=l(S.fullPath,y+1,m+1);$.push(..._)}}let k=[];for(let S of T){if(p>=d){c=!0,$.push(`${R}[Truncated - Maximum item limit reached (${d})]`);break}p++,i++;let _="N/A";try{_=(ds.statSync(S.fullPath).size/1024).toFixed(1)+"KB"}catch{}k.push(`${S.name} (${_})`)}return k.length>0&&$.push(`${R}${k.join("; ")}`),$},u=l(s,1,1).join(`
359
359
  `),h=`
360
360
 
361
361
  (Total items scanned: ${p}, Directories: ${a}, Files: ${i})`;return c&&(h=`
362
362
 
363
363
  TRUNCATED: Scan capped at ${d} items. (Directories: ${a}, Files: ${i})`),`Detailed directory tree for [${t}] (recursive depth: ${o}):
364
364
 
365
- ${u}${h}`}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,p]=a.split("::");s.push({id:r,label:i.trim(),description:p.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 Pl 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 mt.recordFileChange(r);let i=ls();a=await Pl.launch({headless:!0,executablePath:i.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let p=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={},h;for(;(h=f.exec(t))!==null;){let S=h[1],T=h[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(;(h=g.exec(d))!==null;){let S=h[1];if(S&&!c[S]){let T=await l(S);T&&(c[S]=T)}}let y=/url\(\s*['"]?([^'")]+?)['"]?\s*\)/gi;for(;(h=y.exec(d))!==null;){let S=h[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}${h}`}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,p]=a.split("::");s.push({id:r,label:i.trim(),description:p.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 Dl from"puppeteer";import Os from"path";import fs from"fs-extra";import{PDFDocument as Fl}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 mt.recordFileChange(r);let i=ls();a=await Dl.launch({headless:!0,executablePath:i.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let p=await a.newPage(),d=t,c={},l=async k=>{if(!k||k.startsWith("http://")||k.startsWith("https://")||k.startsWith("data:"))return null;try{let S=Os.resolve(process.cwd(),k);if(await fs.pathExists(S)){let _=Os.extname(S).toLowerCase().replace(".","")||"png",E=_==="jpg"?"jpeg":_==="svg"?"svg+xml":_,x=await fs.readFile(S,"base64");return`data:image/${E};base64,${x}`}}catch{}return null},f=/<link[^>]+href=["']([^"']+)["']/gi,u={},h;for(;(h=f.exec(t))!==null;){let k=h[1],S=h[0];if(k&&S.toLowerCase().includes("stylesheet")&&!k.startsWith("http://")&&!k.startsWith("https://")&&!k.startsWith("data:"))try{let _=Os.resolve(process.cwd(),k);if(await fs.pathExists(_)){let E=await fs.readFile(_,"utf-8");u[S]=`<style>${E}</style>`}}catch{}}for(let[k,S]of Object.entries(u))d=d.split(k).join(S);let g=/<img[^>]+src=["']([^"']+)["']/gi;for(;(h=g.exec(d))!==null;){let k=h[1];if(k&&!c[k]){let S=await l(k);S&&(c[k]=S)}}let y=/url\(\s*['"]?([^'")]+?)['"]?\s*\)/gi;for(;(h=y.exec(d))!==null;){let k=h[1].trim();if(k&&!c[k]){let S=await l(k);S&&(c[k]=S)}}for(let[k,S]of Object.entries(c)){let _=k.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&"),E=new RegExp(`(src=["'])(${_})(["'])`,"gi");d=d.replace(E,`$1${S}$3`);let x=new RegExp(`url\\(\\s*(['"]?)(${_})\\1\\s*\\)`,"gi");d=d.replace(x,`url($1${S}$1)`)}let m=`
366
366
  <style>
367
367
  @page {
368
368
  margin: ${s};
@@ -392,7 +392,7 @@ ${u}${h}`}catch(r){let a=r instanceof Error?r.message:String(r);return`ERROR: Fa
392
392
  </style>
393
393
  <div class="watermark">Generated by FluxFlow CLI (AI)</div>
394
394
  ${d}
395
- `;await p.setContent(m,{waitUntil:"networkidle0",timeout:18e4});let w=await p.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 p=i instanceof Error?i.message:String(i);return`ERROR: Failed to generate PDF [${n}]: ${p}`}finally{a&&await a.close()}};import Vi from"fs-extra";import Tr from"path";import Fl 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 mt.recordFileChange(o);let s=Tr.basename(n),r=t.includes("<html")?t:`
395
+ `;await p.setContent(m,{waitUntil:"networkidle0",timeout:18e4});let w=await p.pdf({format:"A4",landscape:String(o).toLowerCase()==="landscape",margin:{top:s,right:s,bottom:s,left:s},printBackground:!0}),b=await Fl.load(w),T=Os.basename(n);b.setTitle(`FluxFlow_${T}`),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 $=await b.save();await fs.writeFile(r,$);let R=await fs.stat(r);return`SUCCESS: PDF generated successfully at [${n}] (${(R.size/1024).toFixed(2)} KB).`}catch(i){let p=i instanceof Error?i.message:String(i);return`ERROR: Failed to generate PDF [${n}]: ${p}`}finally{a&&await a.close()}};import Vi from"fs-extra";import Tr from"path";import Nl 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 mt.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,15 +403,15 @@ ${u}${h}`}catch(r){let a=r instanceof Error?r.message:String(r);return`ERROR: Fa
403
403
  ${t}
404
404
  </body>
405
405
  </html>
406
- `,a=await Fl(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),p=us.relative(t,i),d=p.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(h=>h===u||h.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:p})}return s}function Nl(e,n,t=1/0){if(e===n)return 0;if(e.length===0)return n.length;if(n.length===0)return e.length;if(Math.abs(e.length-n.length)>t)return t+1;let o=Array.from({length:n.length+1},(s,r)=>r);for(let s=1;s<=e.length;s++){let r=[s],a=s;for(let i=1;i<=n.length;i++){let p=e[s-1]===n[i-1]?0:1,d=Math.min(r[i-1]+1,o[i]+1,o[i-1]+p);r.push(d),d<a&&(a=d)}if(o=r,a>t)return t+1}return o[n.length]}function Bl(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 p of s)if(p.includes(a)||a.length>=3&&p.length>=3&&Math.abs(p.length-a.length)<=i&&Nl(a,p,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",p=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(p)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"],h=150;try{let g=[],y=process.cwd(),m=null;if(t){let I=t.split(";").map(N=>N.trim()).filter(Boolean),P=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,"/")),se=u.map(U=>U.startsWith(".")?`**/*${U}`:`**/${U}/**`);if(P&&!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:se,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 se=await _r.stat(Y);if(se.isDirectory())m="dir",g=await Zs(Y,u,y);else if(se.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 P=await _r.readFile(I.fullPath,"utf-8");if(P.includes("\0"))return[];let B=P.split(/\r?\n/),N=[];for(let se=0;se<B.length;se++)(c?B[se].toLowerCase().includes(a.toLowerCase())||Bl(B[se],a):p?f&&f.test(B[se]):l&&l.test(B[se])||f&&f.test(B[se]))&&N.push({line:se+1,content:B[se].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>=h)break;let P=h-E,B=I.matches.slice(0,P);x.push({path:I.path,matches:B}),E+=B.length}typeof global.gc=="function"&&global.gc();let R=c?"(fuzzy mode)":d?"(regex mode)":p?"(keyword mode)":"(standard mode)";if(x.length===0){let I=m==="file"?` in '${t}'`:m==="dir"||m==="glob"?` in '${t}'`:". Try to specify files",P=m==="dir"?"[DIR]":m==="glob"?"[GLOB]":"";return`${P}${P?" ":""}Found 0 matches of '${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?" ":""}${_}
406
+ `,a=await Nl(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),p=us.relative(t,i),d=p.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(h=>h===u||h.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:p})}return s}function Bl(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 p=e[s-1]===n[i-1]?0:1,d=Math.min(r[i-1]+1,o[i]+1,o[i-1]+p);r.push(d),d<a&&(a=d)}if(o=r,a>t)return t+1}return o[n.length]}function Ul(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 p of s)if(p.includes(a)||a.length>=3&&p.length>=3&&Math.abs(p.length-a.length)<=i&&Bl(a,p,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",p=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(p)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"],h=150;try{let g=[],y=process.cwd(),m=null;if(t){let I=t.split(";").map(W=>W.trim()).filter(Boolean),L=I.some(W=>W.startsWith("!"));if(I.some(W=>Er.isDynamicPattern(W)||/[*?{}[\]()|+]/.test(W))){m="glob";let W=t.replace(/\\/g,"/"),X=I.map(F=>F.replace(/\\/g,"/")),re=u.map(F=>F.startsWith(".")?`**/*${F}`:`**/${F}/**`);if(L&&!I.some(F=>!F.startsWith("!"))){let F=await Zs(y,u,y),U=A=>A.endsWith("/")?A+"**":A,se=X.filter(A=>A.startsWith("!")).map(A=>U(A.slice(1))),$e=X.filter(A=>!A.startsWith("!")).map(U);g=F.filter(A=>{let B=A.relativePath.replace(/\\/g,"/"),V=$e.length===0||$e.some(Ue=>{try{return new Xi(Ue).match(B)}catch{return!1}}),J=se.some(Ue=>{try{return new Xi(Ue).match(B)}catch{return!1}});return V&&!J})}else{let F=X.some(se=>/[\(\)\|]|\.\*/.test(se)),U=[];if(!F)try{U=await Er(X,{cwd:y,ignore:re,dot:!0,onlyFiles:!0,absolute:!1})}catch{U=[]}if(U.length===0&&(F||Er.isDynamicPattern(W))){let se=W.match(/^([^\*\?\(\)\|\[\]\s]+)\//),$e=se&&!/[\*\?\(\)\|\[\]]/.test(se[1])?us.resolve(y,se[1]):y,A=await Zs($e,u,y);try{let B=W.replace(/^\.\//,"");B=B.replace(/\.\*\/(\\.|[^\/])/g,".*$1"),!B.startsWith("^")&&!B.startsWith(".*")&&(B=`.*${B}`);let V=new RegExp(B.endsWith("$")?B:`${B}$`,"i");g=A.filter(J=>{let Ue=J.relativePath.replace(/\\/g,"/");return V.test(Ue)})}catch{g=[]}}else g=U.map(se=>({fullPath:us.resolve(y,se),relativePath:se}))}}else{let W=t.replace(/[\/\\]+$/,""),X=us.resolve(y,W);try{let re=await _r.stat(X);if(re.isDirectory())m="dir",g=await Zs(X,u,y);else if(re.isFile())m="file",g.push({fullPath:X,relativePath:us.relative(y,X)});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 L=await _r.readFile(I.fullPath,"utf-8");if(L.includes("\0"))return[];let N=L.split(/\r?\n/),W=[];for(let re=0;re<N.length;re++)(c?N[re].toLowerCase().includes(a.toLowerCase())||Ul(N[re],a):p?f&&f.test(N[re]):l&&l.test(N[re])||f&&f.test(N[re]))&&W.push({line:re+1,content:N[re].trim()});return W.length===0?null:{path:I.relativePath.replace(/\\/g,"/"),matches:W}}catch{return[]}}),b=await Promise.all(w),T=[],$=0;for(let I of b){if(!I||!I.matches)continue;if($>=h)break;let L=h-$,N=I.matches.slice(0,L);T.push({path:I.path,matches:N}),$+=N.length}typeof global.gc=="function"&&global.gc();let R=c?"(fuzzy mode)":d?"(regex mode)":p?"(keyword mode)":"(standard mode)";if(T.length===0){let I=m==="file"?` in '${t}'`:m==="dir"||m==="glob"?` in '${t}'`:". Try to specify files",L=m==="dir"?"[DIR]":m==="glob"?"[GLOB]":"";return`${L}${L?" ":""}Found 0 matches of '${a}'${I}${R?` ${R}`:""}`}let k=R?` ${R}`:"",S=`${T.length} file${T.length===1?"":"s"}`,_=`${$} match${$===1?"":"es"}`,E;m==="file"?E=`Found ${_} of '${a}' in '${t}'${k}:`:m==="dir"||m==="glob"?E=`Found ${_} of '${a}' in '${t}' across ${S}${k}:`:E=`Found ${_} of '${a}' across ${S}${k}:`;let x=m==="dir"?"[DIR]":m==="glob"?"[GLOB]":"",C=`${x}${x?" ":""}${E}
408
408
 
409
- `;for(let I of x){C+=`${I.path}
410
- `;for(let P of I.matches)C+=` ${P.line}: ${P.content}
409
+ `;for(let I of T){C+=`${I.path}
410
+ `;for(let L of I.matches)C+=` ${L.line}: ${L.content}
411
411
  `;C+=`
412
- `}return C.trimEnd()}catch(g){return`ERROR: ${g.message}`}};import Ji from"fs-extra";import $r from"path";var Ul=(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 p=0;p<8;p++)i&1?i=3988292384^i>>>1:i=i>>>1;o[a]=i}let s=a=>{let i=4294967295;for(let p=0;p<a.length;p++)i=o[(i^a[p])&255]^i>>>8;return(i^4294967295)>>>0},r=(a,i)=>{let p=Buffer.from(a,"ascii"),d=Buffer.from(i,"utf-8"),c=p.length+1+d.length,l=Buffer.alloc(8+c+4);l.writeUInt32BE(c,0),l.write("tEXt",4,"ascii"),p.copy(l,8),l[8+p.length]=0,d.copy(l,8+p.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),p=e.subarray(33);return Buffer.concat([i,...t,p])}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 Ft();if(!await Di(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,h={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 P=r.replace(/\s+/g,"");P==="16:9"?(g=1024,y=576):P==="9:16"?(g=576,y=1024):P==="4:3"?(g=1024,y=768):P==="3:4"?(g=768,y=1024):P==="1:1"&&(g=1024,y=1024)}let m=Math.floor(Math.random()*1e7),b=`https://gen.pollinations.ai/image/${encodeURIComponent(o)}?model=${h}&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 P=x.status,B="";try{B=await x.text()}catch{}return P===402||B.includes("Insufficient balance")||B.includes("PAYMENT_REQUIRED")?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed with status [${P}]: ${B||"Unknown API Error"}`}if((x.headers.get("content-type")||"").includes("application/json")){let P=await x.json();return P.status===402||P.error&&P.error.code==="PAYMENT_REQUIRED"?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed: ${P.error?.message||JSON.stringify(P)}`}let 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:${h}`,Ratio:r||"1:1",Seed:String(m)};S=Ul(S,T);let $=$r.resolve(process.cwd(),s);await Ji.ensureDir($r.dirname($)),await mt.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=Q(tn,{}),a=Q(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=Q(Dt,[]),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(Dt,a),!r)return`WARNING: Memory ID [${o}] not found. Other memories decayed by -0.01.`;let i=a.find(c=>c.id===o),p=i?i.score.toFixed(2):"deleted (score <= 0)",d=s.length-a.length;return`SUCCESS: Adjusted memory scores. Target [${o}] is now ${p}.${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 Hl}from"module";import hs from"fs-extra";import Mr from"path";import Wl 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 jl(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"}};Wl.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}`}jl(e,d).then(s).catch(r);return}if(i.statusCode!==200){r(new Error(`Failed to download ${e}: HTTP ${i.statusCode}`));return}let p=hs.createWriteStream(o);i.pipe(p),p.on("finish",()=>{p.close(),s()})}).on("error",i=>{hs.existsSync(o)&&hs.unlink(o,()=>{}),r(i)})})}function Ru(e){let n=Mr.join(is,e);return hs.existsSync(n)}async function Eu(e){let n=Mr.join(is,e);hs.existsSync(n)&&await hs.unlink(n)}var ta=Hl(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(`
412
+ `}return C.trimEnd()}catch(g){return`ERROR: ${g.message}`}};import Ji from"fs-extra";import $r from"path";var Wl=(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 p=0;p<8;p++)i&1?i=3988292384^i>>>1:i=i>>>1;o[a]=i}let s=a=>{let i=4294967295;for(let p=0;p<a.length;p++)i=o[(i^a[p])&255]^i>>>8;return(i^4294967295)>>>0},r=(a,i)=>{let p=Buffer.from(a,"ascii"),d=Buffer.from(i,"utf-8"),c=p.length+1+d.length,l=Buffer.alloc(8+c+4);l.writeUInt32BE(c,0),l.write("tEXt",4,"ascii"),p.copy(l,8),l[8+p.length]=0,d.copy(l,8+p.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),p=e.subarray(33);return Buffer.concat([i,...t,p])}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 Ft();if(!await Di(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,h={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 L=r.replace(/\s+/g,"");L==="16:9"?(g=1024,y=576):L==="9:16"?(g=576,y=1024):L==="4:3"?(g=1024,y=768):L==="3:4"?(g=768,y=1024):L==="1:1"&&(g=1024,y=1024)}let m=Math.floor(Math.random()*1e7),b=`https://gen.pollinations.ai/image/${encodeURIComponent(o)}?model=${h}&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")}`,T=await fetch(b,{method:"GET",headers:{Authorization:`Bearer ${f}`}});if(!T.ok){let L=T.status,N="";try{N=await T.text()}catch{}return L===402||N.includes("Insufficient balance")||N.includes("PAYMENT_REQUIRED")?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed with status [${L}]: ${N||"Unknown API Error"}`}if((T.headers.get("content-type")||"").includes("application/json")){let L=await T.json();return L.status===402||L.error&&L.error.code==="PAYMENT_REQUIRED"?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed: ${L.error?.message||JSON.stringify(L)}`}let R=await T.arrayBuffer(),k=Buffer.from(R),S={Title:o,Description:"Generated via FluxFlow CLI",Software:"FluxFlow CLI",Author:"FluxFlow","Creation Time":new Date().toISOString(),Prompt:o,Model:`Fluxflow:${h}`,Ratio:r||"1:1",Seed:String(m)};k=Wl(k,S);let _=$r.resolve(process.cwd(),s);await Ji.ensureDir($r.dirname(_)),await mt.recordFileChange(_),await Ji.writeFile(_,k),await Ni(d);let E=$r.extname(s).toLowerCase(),C={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".webp":"image/webp"}[E]||"image/png";return n.isMultiModal!==!1?{text:`SUCCESS: Image successfully generated from prompt [${o}] and saved to [${s}]. Output attached to multimodal part`,binaryPart:{inlineData:{data:k.toString("base64"),mimeType: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=Z(tn,{}),a=Z(An,{});return a[o]=s,delete r[o],me(An,a),me(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=Z(Dt,[]),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(me(Dt,a),!r)return`WARNING: Memory ID [${o}] not found. Other memories decayed by -0.01.`;let i=a.find(c=>c.id===o),p=i?i.score.toFixed(2):"deleted (score <= 0)",d=s.length-a.length;return`SUCCESS: Adjusted memory scores. Target [${o}] is now ${p}.${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 Gl}from"module";import hs from"fs-extra";import Mr from"path";import jl 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 Hl(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"}};jl.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}`}Hl(e,d).then(s).catch(r);return}if(i.statusCode!==200){r(new Error(`Failed to download ${e}: HTTP ${i.statusCode}`));return}let p=hs.createWriteStream(o);i.pipe(p),p.on("finish",()=>{p.close(),s()})}).on("error",i=>{hs.existsSync(o)&&hs.unlink(o,()=>{}),r(i)})})}function Eu(e){let n=Mr.join(is,e);return hs.existsSync(n)}async function _u(e){let n=Mr.join(is,e);hs.existsSync(n)&&await hs.unlink(n)}var ta=Gl(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
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 Gl(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 ql(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),p=na.has(a)||n===0,d=Gl(e),c=p&&n>0&&(sa.has(a)&&d.length>0||i!==null&&i===s&&d.length>0),l="",f=o,u=n,h=s;if(p&&!c){let g=e.startPosition.row+1,y=e.endPosition.row+1,m=ql(a),w=i?`${m} [${i}]`:m;n===0?(l+=`\u{1F4C1} ROOT (Lines: ${g}-${y})
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 ql(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 zl(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),p=na.has(a)||n===0,d=ql(e),c=p&&n>0&&(sa.has(a)&&d.length>0||i!==null&&i===s&&d.length>0),l="",f=o,u=n,h=s;if(p&&!c){let g=e.startPosition.row+1,y=e.endPosition.row+1,m=zl(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
416
  `,f+=t?" ":"\u2502 "),u=n+1,h=i}return u>r&&d.length>0?l+=`${f}\u2514\u2500\u2500 ... depth exceeded ...
417
417
  `:d.forEach((g,y)=>{let m=y===d.length-1;l+=ra(g,u,c?t&&m:m,f,h,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 h;try{h=ps.join(ps.dirname(ta.resolve("web-tree-sitter")),"tree-sitter.wasm")}catch{h=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")?h:g}),ea=!0}let i=new a,p=await Zi.Language.load(r);i.setLanguage(p);let d=await Ar.readFile(t,"utf8"),c=d.split(`
@@ -421,19 +421,19 @@ Stack: ${a.stack}`:"";return`ERROR: Failed to map file: ${i}${p}`}};import zn fr
421
421
  `)).map(h=>{let g=String(h).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=p(f),h=(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 h){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(`
424
+ `),y=0,m=!1;for(let w of h){let b=!1;for(let T=0;T<g.length;T++)if(g[T].includes(w)&&/^- \[\s\]/.test(g[T].trim())){g[T]=g[T].replace("- [ ]","- [x]"),b=!0,m=!0,y++;break}if(!b){for(let T=0;T<g.length;T++)if(g[T].toLowerCase().includes(w.toLowerCase())&&/^- \[\s\]/.test(g[T].trim())){g[T]=g[T].replace("- [ ]","- [x]"),b=!0,m=!0,y++;break}}}return{content:m?g.join(`
425
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 h=c(l,s);l=h.content,f=h.markedCount}await mt.recordFileChange(i),zn.writeFileSync(i,l,"utf8");let u=l.split(/\r?\n/).map(h=>h.trim()).filter(h=>h.startsWith("- [ ]")||h.startsWith("- [x]")||h.startsWith("- [X]")).length;if(f>0){let h=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, ${h} completed, ${u-h} left)
426
426
  ${l}`}return`SUCCESS: TASK LIST CREATED (${u} total)
427
427
  ${l}`}if(t==="append"){if(!o)return'ERROR: Missing "tasks" for append method.';let l=d(o);await mt.recordFileChange(i),zn.appendFileSync(i,l,"utf8");let f=zn.readFileSync(i,"utf8"),u=f.split(/\r?\n/).map(m=>m.trim()),h=u.filter(m=>m.startsWith("- [ ]")||m.startsWith("- [x]")||m.startsWith("- [X]")).length,g=u.filter(m=>m.startsWith("- [x]")||m.startsWith("- [X]")).length,y=l.split(/\r?\n/).map(m=>m.trim()).filter(m=>m.startsWith("- [ ]")||m.startsWith("- [x]")||m.startsWith("- [X]")).length;return`SUCCESS: TASK APPENDED (${g} completed, ${h-g} left, ${y} added)
428
428
  ${f}`}if(t==="get"){if(!zn.existsSync(i))return"TODO GET: No task list found for this session.";let l=zn.readFileSync(i,"utf8"),f=0;if(s){let m=c(l,s);m.markedCount>0&&(l=m.content,f=m.markedCount,await mt.recordFileChange(i),zn.writeFileSync(i,l,"utf8"))}let u=l.split(/\r?\n/).map(m=>m.trim()),h=u.filter(m=>m.startsWith("- [ ]")||m.startsWith("- [x]")||m.startsWith("- [X]")).length,g=u.filter(m=>m.startsWith("- [x]")||m.startsWith("- [X]")).length;return`${f>0?`SUCCESS: ${f} TASK(S) MARKED DONE`:"TODO GET"}: ${g} Completed, ${h-g} left
429
- ${l}`}return`ERROR: Unknown method "${t}". Use create, append, or get.`}catch(l){return`ERROR: Todo tool failure: ${l instanceof Error?l.message:String(l)}`}};var Ir=async(e,n={})=>{let{runSubagent:t}=await import("./ai-K54RGGJG.js"),o=O(e),s=o.task||o.instruction||o.prompt,r=o.model||null,a=o.tools||null;if(!s)return'ERROR: Missing "task" argument for invokeSync.';let i=null;if(a)try{let d=a.trim();d.startsWith("[")&&d.endsWith("]")&&(d=d.substring(1,d.length-1)),i=d.split(",").map(c=>c.trim().replace(/^["']|["']$/g,"")).filter(Boolean)}catch{}let p=o.title||s.substring(0,30);try{n.onVisualFeedback&&n.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${p}`);let d=await t(s,n,r,i,50);return n.onVisualFeedback&&n.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${p} [COMPLETED]
430
- `),d}catch(d){let{isTerminationSignaled:c}=await import("./ai-K54RGGJG.js"),l=d.message==="Subagent task was cancelled by user."||c();if(n.onVisualFeedback){let f=l?"[CANCELLED]":"[FAILED]";n.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${p} ${f}
431
- `)}return`ERROR: Subagent execution failed: ${d.message}`}};var aa=async(e,n={})=>{let{runSubagent:t}=await import("./ai-K54RGGJG.js"),o=O(e),s=o.task||o.instruction||o.prompt,r=o.model||null,a=o.title||null,i=o.tools||null;if(!s)return'ERROR: Missing "task" argument for invoke.';let p=null;if(i)try{let m=i.trim();m.startsWith("[")&&m.endsWith("]")&&(m=m.substring(1,m.length-1)),p=m.split(",").map(w=>w.trim().replace(/^["']|["']$/g,"")).filter(Boolean)}catch{}let d=`subagent-${Date.now()}-${Math.floor(Math.random()*1e3)}`,c=null,l=null,f=new Promise((m,w)=>{c=m,l=w}),u={id:d,title:a||s.substring(0,30),task:s,status:"running",startedAt:Date.now(),lastChunkTime:Date.now(),wps:0,questions:[],pendingSteerMessages:[],steer:m=>{m&&u.pendingSteerMessages.push(m)},completionPromise:f,_resolveCompletion:c,_rejectCompletion:l,progress:[]},h={chunks:[],totalWords:0};Xe.push(u),n.onSubagentUpdate&&n.onSubagentUpdate();let g=[],y={...n,taskId:d,onAskMain:async m=>{let w=`q-${Date.now()}-${Math.floor(Math.random()*1e3)}`,b=null,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}"
429
+ ${l}`}return`ERROR: Unknown method "${t}". Use create, append, or get.`}catch(l){return`ERROR: Todo tool failure: ${l instanceof Error?l.message:String(l)}`}};var Ir=async(e,n={})=>{let{runSubagent:t}=await import("./ai-OTNVN773.js"),o=O(e),s=o.task||o.instruction||o.prompt,r=o.model||null,a=o.tools||null;if(!s)return'ERROR: Missing "task" argument for invokeSync.';let i=null;if(a)try{let d=a.trim();d.startsWith("[")&&d.endsWith("]")&&(d=d.substring(1,d.length-1)),i=d.split(",").map(c=>c.trim().replace(/^["']|["']$/g,"")).filter(Boolean)}catch{}let p=o.title||s.substring(0,30);try{n.onVisualFeedback&&n.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${p}`);let d=await t(s,n,r,i,50);return n.onVisualFeedback&&n.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${p} [COMPLETED]
430
+ `),d}catch(d){let{isTerminationSignaled:c}=await import("./ai-OTNVN773.js"),l=d.message==="Subagent task was cancelled by user."||c();if(n.onVisualFeedback){let f=l?"[CANCELLED]":"[FAILED]";n.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${p} ${f}
431
+ `)}return`ERROR: Subagent execution failed: ${d.message}`}};var aa=async(e,n={})=>{let{runSubagent:t}=await import("./ai-OTNVN773.js"),o=O(e),s=o.task||o.instruction||o.prompt,r=o.model||null,a=o.title||null,i=o.tools||null;if(!s)return'ERROR: Missing "task" argument for invoke.';let p=null;if(i)try{let m=i.trim();m.startsWith("[")&&m.endsWith("]")&&(m=m.substring(1,m.length-1)),p=m.split(",").map(w=>w.trim().replace(/^["']|["']$/g,"")).filter(Boolean)}catch{}let d=`subagent-${Date.now()}-${Math.floor(Math.random()*1e3)}`,c=null,l=null,f=new Promise((m,w)=>{c=m,l=w}),u={id:d,title:a||s.substring(0,30),task:s,status:"running",startedAt:Date.now(),lastChunkTime:Date.now(),wps:0,questions:[],pendingSteerMessages:[],steer:m=>{m&&u.pendingSteerMessages.push(m)},completionPromise:f,_resolveCompletion:c,_rejectCompletion:l,progress:[]},h={chunks:[],totalWords:0};Xe.push(u),n.onSubagentUpdate&&n.onSubagentUpdate();let g=[],y={...n,taskId:d,onAskMain:async m=>{let w=`q-${Date.now()}-${Math.floor(Math.random()*1e3)}`,b=null,T=new Promise(k=>{b=k}),$={id:w,question:m,answered:!1,answer:null,askedAt:Date.now(),_resolve:b};return u.questions.push($),u.status="waiting",n.onSubagentUpdate&&n.onSubagentUpdate(),bo(`[SYSTEM] Background subagent "${u.title}" is WAITING FOR YOUR INPUT: "${m}"
432
432
  Respond using tool: [tool:functions.Answer(id="${d}", answer="...")]
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){h.totalWords+=w,h.chunks.push({time:b,words:w});let x=b-400;if(h.chunks=h.chunks.filter(E=>E.time>=x),h.chunks.length>0){let E=h.chunks.reduce((T,$)=>T+$.words,0),R=h.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,p,50,m=>{if(u.status==="cancelled")return;if(m.startsWith("[Subagent Turn")&&g.length>0&&(u.progress.push([...g]),g=[]),m.includes("[Executing Tool]")){let b=m.match(/\[Executing Tool\]\s*([a-zA-Z0-9_]+)/);b&&(!u.currentTool||u.currentTool==="Thinking")&&(u.currentTool=b[1])}let w=m;if(w.startsWith("[Tool Result]")){let b=w.split(`
433
+ [/SYSTEM]`),await T},onVisualFeedback:m=>{u.lastChunkTime=Date.now();let w=m.replace(/\x1b\[[0-9;]*m/g,""),b=w.match(/[✔✘✗✖🔍📖→➕↻•]\s*([A-Za-z0-9\s-]+)/);b?u.currentTool=b[1].trim():u.currentTool=w,n.onSubagentUpdate&&n.onSubagentUpdate()},onTokenChunk:(m,w)=>{let b=Date.now();if(u.lastChunkTime=b,u.currentTool="Thinking",typeof w=="number"&&w>0){h.totalWords+=w,h.chunks.push({time:b,words:w});let T=b-400;if(h.chunks=h.chunks.filter($=>$.time>=T),h.chunks.length>0){let $=h.chunks.reduce((S,_)=>S+_.words,0),R=h.chunks[0].time,k=Math.max(.4,(b-R)/1e3);u.wps=Math.round($/k*10)/10}}n.onSubagentUpdate&&n.onSubagentUpdate()}};return t(s,y,r,p,50,m=>{if(u.status==="cancelled")return;if(m.startsWith("[Subagent Turn")&&g.length>0&&(u.progress.push([...g]),g=[]),m.includes("[Executing Tool]")){let b=m.match(/\[Executing Tool\]\s*([a-zA-Z0-9_]+)/);b&&(!u.currentTool||u.currentTool==="Thinking")&&(u.currentTool=b[1])}let w=m;if(w.startsWith("[Tool Result]")){let b=w.split(`
434
434
  `);b.length>5&&(w=b.slice(0,4).join(`
435
435
  `)+`
436
- ... [Content/Diff Truncated from Logs] ...`)}g.push(w),n.onSubagentUpdate&&n.onSubagentUpdate()},!0).then(m=>{if(u.status==="cancelled"){u._resolveCompletion&&u._resolveCompletion(m);return}g.length>0&&(u.progress.push([...g]),g=[]),u.status="completed",u.finalAnswer=m,n.onSubagentUpdate&&n.onSubagentUpdate(),bo(`[SYSTEM] Background subagent "${u.title}" (id: ${d}) has FINISHED. Call GetProgress(id="${d}") to see the final result. [/SYSTEM]`),u._resolveCompletion&&u._resolveCompletion(m)}).catch(async m=>{let{isTerminationSignaled:w}=await import("./ai-K54RGGJG.js");if(m.message==="Subagent task was cancelled."||u.status==="cancelled"||w()){u.status="cancelled",g.push("[SUBAGENT CANCELLED] Task was cancelled."),u.progress.push([...g]),n.onSubagentUpdate&&n.onSubagentUpdate(),u._resolveCompletion&&u._resolveCompletion(null);return}g.push(`[SUBAGENT FAILURE] Error: ${m.message}`),u.progress.push([...g]),u.status="failed",u.error=m.message,n.onSubagentUpdate&&n.onSubagentUpdate(),bo(`[SYSTEM] Background subagent "${u.title}" (id: ${d}) FAILED with error: ${m.message}. [/SYSTEM]`),u._rejectCompletion&&u._rejectCompletion(m)}),`SUCCESS: Background subagent started. Task ID: ${d}`};var Or=async(e,n={})=>{let o=O(e).id;if(!o)return'ERROR: Missing "id" argument for getProgress.';let s=Xe.find(i=>i.id===o);if(!s)return`ERROR: Subagent task with ID [${o}] not found.`;let r=`Subagent Task Status: ${s.status.toUpperCase()}
436
+ ... [Content/Diff Truncated from Logs] ...`)}g.push(w),n.onSubagentUpdate&&n.onSubagentUpdate()},!0).then(m=>{if(u.status==="cancelled"){u._resolveCompletion&&u._resolveCompletion(m);return}g.length>0&&(u.progress.push([...g]),g=[]),u.status="completed",u.finalAnswer=m,n.onSubagentUpdate&&n.onSubagentUpdate(),bo(`[SYSTEM] Background subagent "${u.title}" (id: ${d}) has FINISHED. Call GetProgress(id="${d}") to see the final result. [/SYSTEM]`),u._resolveCompletion&&u._resolveCompletion(m)}).catch(async m=>{let{isTerminationSignaled:w}=await import("./ai-OTNVN773.js");if(m.message==="Subagent task was cancelled."||u.status==="cancelled"||w()){u.status="cancelled",g.push("[SUBAGENT CANCELLED] Task was cancelled."),u.progress.push([...g]),n.onSubagentUpdate&&n.onSubagentUpdate(),u._resolveCompletion&&u._resolveCompletion(null);return}g.push(`[SUBAGENT FAILURE] Error: ${m.message}`),u.progress.push([...g]),u.status="failed",u.error=m.message,n.onSubagentUpdate&&n.onSubagentUpdate(),bo(`[SYSTEM] Background subagent "${u.title}" (id: ${d}) FAILED with error: ${m.message}. [/SYSTEM]`),u._rejectCompletion&&u._rejectCompletion(m)}),`SUCCESS: Background subagent started. Task ID: ${d}`};var Or=async(e,n={})=>{let o=O(e).id;if(!o)return'ERROR: Missing "id" argument for getProgress.';let s=Xe.find(i=>i.id===o);if(!s)return`ERROR: Subagent task with ID [${o}] not found.`;let r=`Subagent Task Status: ${s.status.toUpperCase()}
437
437
  `;if(r+=`Title: ${s.title}
438
438
  `,r+=`Task: ${s.task}
439
439
  `,s.startedAt){let i=Math.floor((Date.now()-s.startedAt)/1e3);r+=`Elapsed Time: ${i}s
@@ -448,7 +448,7 @@ Respond using tool: [tool:functions.Answer(id="${d}", answer="...")]
448
448
  `)}return r+=`
449
449
  Progress Log:
450
450
  `,s.progress.forEach((i,p)=>{r+=`--- Turn ${p+1} ---
451
- `;let c=i.filter(l=>!l.startsWith("[SUBAGENT SUCCESS]")).map(l=>{if(l.startsWith("[Subagent Response]")){let f="[Subagent Response]",h=l.substring(f.length),g="tool:functions.";for(;;){let m=h.toLowerCase().indexOf(g);if(m===-1)break;let w=m,b=!1,x=m-1;for(;x>=0&&/\s/.test(h[x]);)x--;x>=0&&h[x]==="["&&(w=x,b=!0);let E=0,R=!1,S=null,T=m;for(;T<h.length;){let $=h[T];if(!S&&($==="'"||$==='"'||$==="`")?S=$:S&&$===S&&h[T-1]!=="\\"&&(S=null),S||($==="("?(E++,R=!0):$===")"&&E--),R&&E===0&&!S){let _=T;if(b){let k=T+1;for(;k<h.length&&/\s/.test(h[k]);)k++;k<h.length&&h[k]==="]"&&(_=k)}h=h.substring(0,w)+h.substring(_+1);break}if(T++,T===h.length){h=h.substring(0,w);break}}}return f+`
451
+ `;let c=i.filter(l=>!l.startsWith("[SUBAGENT SUCCESS]")).map(l=>{if(l.startsWith("[Subagent Response]")){let f="[Subagent Response]",h=l.substring(f.length),g="tool:functions.";for(;;){let m=h.toLowerCase().indexOf(g);if(m===-1)break;let w=m,b=!1,T=m-1;for(;T>=0&&/\s/.test(h[T]);)T--;T>=0&&h[T]==="["&&(w=T,b=!0);let $=0,R=!1,k=null,S=m;for(;S<h.length;){let _=h[S];if(!k&&(_==="'"||_==='"'||_==="`")?k=_:k&&_===k&&h[S-1]!=="\\"&&(k=null),k||(_==="("?($++,R=!0):_===")"&&$--),R&&$===0&&!k){let E=S;if(b){let x=S+1;for(;x<h.length&&/\s/.test(h[x]);)x++;x<h.length&&h[x]==="]"&&(E=x)}h=h.substring(0,w)+h.substring(E+1);break}if(S++,S===h.length){h=h.substring(0,w);break}}}return f+`
452
452
  `+h.trim()}return l.startsWith("[Executing Tool]")&&l.length>256?l.substring(0,256)+"...[truncated from logs]":l});r+=c.join(`
453
453
  `)+`
454
454
 
@@ -458,7 +458,7 @@ ${s.finalAnswer}
458
458
  `),r.replace(/\r\n/g,`
459
459
  `).replace(/\n{3,}/g,`
460
460
 
461
- `).trim().replace(/\[TOOL RESULT\]/gi,"TOOL RESULT:")};var la=async(e,n={})=>{let o=O(e).id;if(!o)return'ERROR: Missing "id" argument for cancel.';let s=Xe.find(r=>r.id===o);return s?s.status==="completed"||s.status==="failed"?`INFO: Subagent task with ID [${o}] has already finished with status [${s.status.toUpperCase()}].`:s.status==="cancelled"?`INFO: Subagent task with ID [${o}] is already cancelled.`:(s.status="cancelled",n.onSubagentUpdate&&n.onSubagentUpdate(),`SUCCESS: Subagent task with ID [${o}] has been cancelled.`):`ERROR: Subagent task with ID [${o}] not found.`};import kt from"fs-extra";import Tt from"path";var zl=["node_modules","dist","bin","logs",".git",".fluxflow","secret",".gemini",".agents","tmp","temp","build","out","snapshots"];async function so(e,n=e){let t={},o=await kt.readdir(e,{withFileTypes:!0}).catch(()=>[]);for(let s of o){if(zl.includes(s.name))continue;let r=Tt.join(e,s.name),a=Tt.relative(n,r).replace(/\\/g,"/");if(s.isDirectory()){let i=await so(r,n);Object.assign(t,i)}else{let i=await kt.stat(r).catch(()=>null);i&&(t[a]={size:i.size,mtime:i.mtimeMs})}}return t}async function ca(e,n){await kt.ensureDir(e);for(let t of Object.keys(n)){let o=Tt.join(process.cwd(),t),s=Tt.join(e,t);await kt.ensureDir(Tt.dirname(s)),await kt.copyFile(o,s).catch(()=>{})}}async function Lr(e,n,t=null,o=null){if(!await kt.pathExists(e))return;o||(o=e);let s=await kt.readdir(e,{withFileTypes:!0}).catch(()=>[]);for(let r of s){let a=Tt.join(e,r.name),i=Tt.join(n,r.name);if(r.isDirectory())await Lr(a,i,t,o);else{let p=Tt.relative(o,a).replace(/\\/g,"/"),d=await kt.pathExists(i);d&&await kt.chmod(i,438).catch(()=>{}),await kt.ensureDir(Tt.dirname(i));let c=await kt.copyFile(a,i).then(()=>!0).catch(()=>!1);await kt.chmod(i,438).catch(()=>{}),t&&(c?d?t.replaced++:t.restored++:t.failed.push(p))}}}var Kn={async takeInitialSnapshot(e){try{let n=Tt.join(Mn,"snapshots",e);await kt.remove(n).catch(()=>{}),await kt.ensureDir(n);let t=await so(process.cwd());await ca(Tt.join(n,"initial"),t);let o=Q(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=Q(un,{}),s=o[e];if(!s)return;let r=s.currentManifest||s.initialManifest,a=await so(process.cwd()),i=[],p=[],d=[];for(let[l,f]of Object.entries(a)){let u=r[l];u?(u.size!==f.size||u.mtime!==f.mtime)&&p.push(l):i.push(l)}for(let l of Object.keys(r))a[l]||d.push(l);let c=[...i,...p];if(c.length>0||d.length>0){let l={};for(let u of c)l[u]=a[u];let f=Tt.join(Mn,"snapshots",e,`turn_${n}`);await ca(f,l)}s.checkpoints.push({id:`turn_${n}`,timestamp:new Date().toISOString(),newFiles:i,modifiedFiles:p,deletedFiles:d,toolsUsed:t}),s.currentManifest=a,pe(un,o)}catch{}},async getCheckpoints(e){try{let t=Q(un,{})[e];return t?t.checkpoints||[]:[]}catch{return[]}},async rollbackToCheckpoint(e,n){try{let t=Q(un,{}),o=t[e];if(!o)throw new Error("No session active for Advance Rollback.");let s=o.checkpoints||[],r=s.findIndex(c=>c.id===n);if(r===-1)throw new Error(`Checkpoint [${n}] not found.`);let a=Tt.join(Mn,"snapshots",e),i={restored:0,replaced:0,failed:[]},p=await so(process.cwd());for(let c of Object.keys(p)){let l=Tt.join(process.cwd(),c);await kt.chmod(l,438).catch(()=>{}),await kt.remove(l).catch(()=>{})}let d=Tt.join(a,"initial");await Lr(d,process.cwd(),i,d);for(let c=1;c<=r;c++){let l=s[c],f=Tt.join(a,l.id);if(await Lr(f,process.cwd(),i,f),l.deletedFiles&&l.deletedFiles.length>0)for(let u of l.deletedFiles){let h=Tt.join(process.cwd(),u);await kt.chmod(h,438).catch(()=>{}),await kt.remove(h).catch(()=>{})}}return o.checkpoints=s.slice(0,r+1),o.currentManifest=await so(process.cwd()),pe(un,t),{checkpointId:n,stats:i}}catch(t){throw new Error(`Rollback failed: ${t.message}`)}},async getLatestFileChanges(e){try{let t=Q(un,{})[e];if(!t||!t.checkpoints||t.checkpoints.length===0)return{newFiles:[],modifiedFiles:[],deletedFiles:[]};let o=t.checkpoints[t.checkpoints.length-1];return{newFiles:o.newFiles||[],modifiedFiles:o.modifiedFiles||[],deletedFiles:o.deletedFiles||[]}}catch{return{newFiles:[],modifiedFiles:[],deletedFiles:[]}}},async cleanup(e){try{let n=Tt.join(Mn,"snapshots",e);await kt.remove(n).catch(()=>{});let t=Q(un,{});t[e]&&(delete t[e],pe(un,t))}catch{}}};var Pr=async(e,n={})=>{let t=O(e),o=t.method,s=t.id,r=n.chatId;if(!n.systemSettings?.advanceRollback)return"ERROR: Advance Rollback feature is currently disabled in settings under Security. Tell user to enable it.";if(!r)return"ERROR: No active chat transaction found for rollback.";if(o==="getCheckpoint"){let i=await Kn.getCheckpoints(r);if(i.length===0)return"No checkpoints available.";let p={write_file:"WriteFile",update_file:"PatchFile",view_file:"ReadFile",read_folder:"ReadFolder",exec_command:"Run",web_search:"WebSearch",web_scrape:"WebScrape",search_keyword:"SearchKeyword",CodeSearch:"SearchKeyword",code_search:"SearchKeyword",write_pdf:"WritePDF",write_docx:"WriteDoc",generate_image:"GenerateImage",file_map:"FileMap",todo:"Todo",goal:"Goal",Goal:"Goal",await:"Await",ask:"Ask",ask_user:"Ask",invoke:"Invoke",invokesync:"InvokeSync",getprogress:"GetProgress",cancel:"Cancel",emergency_rollback:"EmergencyRollback",emergencyrollback:"EmergencyRollback"},d=l=>p[l]||p[l.toLowerCase()]||l,c=`Available checkpoints for rollback:
461
+ `).trim().replace(/\[TOOL RESULT\]/gi,"TOOL RESULT:")};var la=async(e,n={})=>{let o=O(e).id;if(!o)return'ERROR: Missing "id" argument for cancel.';let s=Xe.find(r=>r.id===o);return s?s.status==="completed"||s.status==="failed"?`INFO: Subagent task with ID [${o}] has already finished with status [${s.status.toUpperCase()}].`:s.status==="cancelled"?`INFO: Subagent task with ID [${o}] is already cancelled.`:(s.status="cancelled",n.onSubagentUpdate&&n.onSubagentUpdate(),`SUCCESS: Subagent task with ID [${o}] has been cancelled.`):`ERROR: Subagent task with ID [${o}] not found.`};import kt from"fs-extra";import Tt from"path";var Kl=["node_modules","dist","bin","logs",".git",".fluxflow","secret",".gemini",".agents","tmp","temp","build","out","snapshots"];async function so(e,n=e){let t={},o=await kt.readdir(e,{withFileTypes:!0}).catch(()=>[]);for(let s of o){if(Kl.includes(s.name))continue;let r=Tt.join(e,s.name),a=Tt.relative(n,r).replace(/\\/g,"/");if(s.isDirectory()){let i=await so(r,n);Object.assign(t,i)}else{let i=await kt.stat(r).catch(()=>null);i&&(t[a]={size:i.size,mtime:i.mtimeMs})}}return t}async function ca(e,n){await kt.ensureDir(e);for(let t of Object.keys(n)){let o=Tt.join(process.cwd(),t),s=Tt.join(e,t);await kt.ensureDir(Tt.dirname(s)),await kt.copyFile(o,s).catch(()=>{})}}async function Lr(e,n,t=null,o=null){if(!await kt.pathExists(e))return;o||(o=e);let s=await kt.readdir(e,{withFileTypes:!0}).catch(()=>[]);for(let r of s){let a=Tt.join(e,r.name),i=Tt.join(n,r.name);if(r.isDirectory())await Lr(a,i,t,o);else{let p=Tt.relative(o,a).replace(/\\/g,"/"),d=await kt.pathExists(i);d&&await kt.chmod(i,438).catch(()=>{}),await kt.ensureDir(Tt.dirname(i));let c=await kt.copyFile(a,i).then(()=>!0).catch(()=>!1);await kt.chmod(i,438).catch(()=>{}),t&&(c?d?t.replaced++:t.restored++:t.failed.push(p))}}}var Kn={async takeInitialSnapshot(e){try{let n=Tt.join(Mn,"snapshots",e);await kt.remove(n).catch(()=>{}),await kt.ensureDir(n);let t=await so(process.cwd());await ca(Tt.join(n,"initial"),t);let o=Z(un,{});o[e]={initialManifest:t,currentManifest:t,checkpoints:[{id:"initial",timestamp:new Date().toISOString(),newFiles:[],modifiedFiles:[],deletedFiles:[],toolsUsed:[]}]},me(un,o)}catch{}},async recordTurnDelta(e,n,t=[]){try{let o=Z(un,{}),s=o[e];if(!s)return;let r=s.currentManifest||s.initialManifest,a=await so(process.cwd()),i=[],p=[],d=[];for(let[l,f]of Object.entries(a)){let u=r[l];u?(u.size!==f.size||u.mtime!==f.mtime)&&p.push(l):i.push(l)}for(let l of Object.keys(r))a[l]||d.push(l);let c=[...i,...p];if(c.length>0||d.length>0){let l={};for(let u of c)l[u]=a[u];let f=Tt.join(Mn,"snapshots",e,`turn_${n}`);await ca(f,l)}s.checkpoints.push({id:`turn_${n}`,timestamp:new Date().toISOString(),newFiles:i,modifiedFiles:p,deletedFiles:d,toolsUsed:t}),s.currentManifest=a,me(un,o)}catch{}},async getCheckpoints(e){try{let t=Z(un,{})[e];return t?t.checkpoints||[]:[]}catch{return[]}},async rollbackToCheckpoint(e,n){try{let t=Z(un,{}),o=t[e];if(!o)throw new Error("No session active for Advance Rollback.");let s=o.checkpoints||[],r=s.findIndex(c=>c.id===n);if(r===-1)throw new Error(`Checkpoint [${n}] not found.`);let a=Tt.join(Mn,"snapshots",e),i={restored:0,replaced:0,failed:[]},p=await so(process.cwd());for(let c of Object.keys(p)){let l=Tt.join(process.cwd(),c);await kt.chmod(l,438).catch(()=>{}),await kt.remove(l).catch(()=>{})}let d=Tt.join(a,"initial");await Lr(d,process.cwd(),i,d);for(let c=1;c<=r;c++){let l=s[c],f=Tt.join(a,l.id);if(await Lr(f,process.cwd(),i,f),l.deletedFiles&&l.deletedFiles.length>0)for(let u of l.deletedFiles){let h=Tt.join(process.cwd(),u);await kt.chmod(h,438).catch(()=>{}),await kt.remove(h).catch(()=>{})}}return o.checkpoints=s.slice(0,r+1),o.currentManifest=await so(process.cwd()),me(un,t),{checkpointId:n,stats:i}}catch(t){throw new Error(`Rollback failed: ${t.message}`)}},async getLatestFileChanges(e){try{let t=Z(un,{})[e];if(!t||!t.checkpoints||t.checkpoints.length===0)return{newFiles:[],modifiedFiles:[],deletedFiles:[]};let o=t.checkpoints[t.checkpoints.length-1];return{newFiles:o.newFiles||[],modifiedFiles:o.modifiedFiles||[],deletedFiles:o.deletedFiles||[]}}catch{return{newFiles:[],modifiedFiles:[],deletedFiles:[]}}},async cleanup(e){try{let n=Tt.join(Mn,"snapshots",e);await kt.remove(n).catch(()=>{});let t=Z(un,{});t[e]&&(delete t[e],me(un,t))}catch{}}};var Pr=async(e,n={})=>{let t=O(e),o=t.method,s=t.id,r=n.chatId;if(!n.systemSettings?.advanceRollback)return"ERROR: Advance Rollback feature is currently disabled in settings under Security. Tell user to enable it.";if(!r)return"ERROR: No active chat transaction found for rollback.";if(o==="getCheckpoint"){let i=await Kn.getCheckpoints(r);if(i.length===0)return"No checkpoints available.";let p={write_file:"WriteFile",update_file:"PatchFile",view_file:"ReadFile",read_folder:"ReadFolder",exec_command:"Run",web_search:"WebSearch",web_scrape:"WebScrape",search_keyword:"SearchKeyword",CodeSearch:"SearchKeyword",code_search:"SearchKeyword",write_pdf:"WritePDF",write_docx:"WriteDoc",generate_image:"GenerateImage",file_map:"FileMap",todo:"Todo",goal:"Goal",Goal:"Goal",await:"Await",ask:"Ask",ask_user:"Ask",invoke:"Invoke",invokesync:"InvokeSync",getprogress:"GetProgress",cancel:"Cancel",emergency_rollback:"EmergencyRollback",emergencyrollback:"EmergencyRollback"},d=l=>p[l]||p[l.toLowerCase()]||l,c=`Available checkpoints for rollback:
462
462
 
463
463
  `;for(let l of i)if(l.id==="initial")c+=`--- Initial State (id: initial) ---
464
464
  Tools Used: User Prompted for task
@@ -481,8 +481,8 @@ ${r.finalAnswer||"(No output)"}`;if(r.status==="failed")return`ERROR: Subagent t
481
481
  Error: ${r.error||"Unknown error"}`;if(r.status==="cancelled")return`INFO: Subagent task [${o}] was cancelled.`;let a,i=new Promise(p=>{a=setTimeout(()=>{p({type:"timeout"})},s*1e3)});try{let p=await Promise.race([r.completionPromise.then(()=>({type:"completion"})),i]);return clearTimeout(a),p.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
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(p){return clearTimeout(a),`ERROR: Exception while awaiting subagent [${o}]: ${p.message}`}};var Ds=async(e,n={})=>{let t=O(e),o=t.id,s=t.answer||t.response;if(!o)return'ERROR: Missing "id" argument for Answer.';if(!s)return'ERROR: Missing "answer" argument for Answer.';let 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 Nt,Button as ro,Key as L,Point as io,clipboard as Kl}from"@nut-tree-fork/nut-js";ln.config.autoDelayMs=50;Nt.config.autoDelayMs=50;async function Dr(){try{await Nt.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(p=>setTimeout(p,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 p=0;p<a;p++)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 Dr(),await Kl.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 Dr(),t.autoPressEnter?(await new Promise(r=>setTimeout(r,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=fa(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=>fa(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 Dr(),`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 Yl(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Vl(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 p=e[s-1]===n[i-1]?0:1,d=Math.min(r[i-1]+1,o[i]+1,o[i-1]+p);r.push(d),d<a&&(a=d)}if(o=r,a>t)return t+1}return o[n.length]}function Xl(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 Jl(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],p=r[3],d=r[4],c=parseInt(r[6]),l=parseInt(r[7]),f=parseInt(r[8]),u=parseInt(r[9]),h=parseFloat(r[10]),g=r.slice(11).join(" ").trim();if(!g||h<0)continue;let y={x0:c,y0:l,x1:c+f,y1:l+u},m={text:g,confidence:h,bbox:y};n.push(m);let w=`${i}_${p}_${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 Ql(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=Jl(e.tsv);e.words=n.words,e.lines=n.lines}}}function Br(e,n,t=0,o=0,s=1){Ql(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 p=i.text?i.text.toLowerCase().trim():"";if(!p||!i.bbox||!(p===n||new RegExp(`\\b${Yl(n)}\\b`,"i").test(p)))continue;let c=i.words||(e.words?e.words.filter(h=>h.bbox&&h.bbox.x0>=i.bbox.x0-5&&h.bbox.x1<=i.bbox.x1+5&&h.bbox.y0>=i.bbox.y0-5&&h.bbox.y1<=i.bbox.y1+5):[]),l=n.split(/\s+/),f=l.map(h=>h.replace(/[^a-z0-9]/g,"")).join(" "),u=!1;if(c.length>0)for(let h=0;h<=c.length-l.length;h++){let g=c.slice(h,h+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 p=i.text?i.text.toLowerCase().trim().replace(/[^a-z0-9]/g,""):"",d=n.replace(/[^a-z0-9]/g,"");p===d&&i.bbox&&a.push(r(i.bbox))}if(a.length===0&&e.words&&e.words.length>0){let i=Xl(n.length);for(let p of e.words){let d=p.text?p.text.toLowerCase().trim():"";d.length>=3&&Math.abs(d.length-n.length)<=i&&Vl(d,n,i)<=i&&p.bbox&&a.push(r(p.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,p=Math.hypot(r-n.x,a-n.y),d=i?0:p;d<o&&(o=d,t={x:r,y:a,dist:p,containsPoint:i,bbox:s})}return t}function Zl(e,n,t,o){let a=Math.ceil(e/4),i=Math.ceil(n/2),p=[];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),h=Math.min(i,n-f),g=l+u/2,y=f+h/2,m=t>=l&&t<l+u&&o>=f&&o<f+h;p.push({x0:l,y0:f,w:u,h,cx:g,cy:y,containsTarget:m})}return p.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 ec(){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 tc(){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 h=performance.now(),g=(h-s).toFixed(0),y=(h-o).toFixed(0);console.log(`[Click Perf] +${g}ms (${y}ms total) -> ${u}`),s=h};r("Starting click()");let a=O(e),i=a.gridId||a.grid||a.coordinate||a.target||a.id,p=(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 h=await tc();r("Taking desktop screenshot");let g=await ma(h);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 ec(),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(),P=2,B=await Nr(I,P),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 se=Br(Y,x,k,C,P);if(se.length>0){let Ie=Ur(se,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 $=Zl(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(),P=await Nr(I,3);await Fr("tiles",`tile_${k+1}_${Date.now()}_${_}.png`,P),r(`Pass 3: Running Tesseract on tile ${k+1}`);let{data:B}=await E.recognize(P,{},{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:p});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:p});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 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 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 Do=async(e,n={})=>"SUCCESS: Screen recapture requested. The latest gridded screenshot is provided for your next decision.";var nc={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:Ps,answerSubagent:Ds,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:Po,KeyPress:Po,keypress:Po,recapture_screen:Do,RecaptureScreen:Do,recapturescreen:Do,invoke_sync:Ir,get_progress:Or,await_subagent:Ps,answer_subagent:Ds,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:Ds,Answer:Ds,AnswerSubagent:Ds,await:Ps,Await:Ps,AwaitSubagent:Ps,EmergencyRollback:Pr,emergency_rollback:Pr},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",p=["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(!p)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=nc[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 Z from"path";import Pe from"fs";import sc 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 oc=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",Lp=(e=2)=>{let n=oc();return n==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)},Pp=(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,p="\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=sc(c).multiline(d.join(`
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(p){return clearTimeout(a),`ERROR: Exception while awaiting subagent [${o}]: ${p.message}`}};var Ds=async(e,n={})=>{let t=O(e),o=t.id,s=t.answer||t.response;if(!o)return'ERROR: Missing "id" argument for Answer.';if(!s)return'ERROR: Missing "answer" argument for Answer.';let 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 Nt,Button as ro,Key as P,Point as io,clipboard as Yl}from"@nut-tree-fork/nut-js";ln.config.autoDelayMs=50;Nt.config.autoDelayMs=50;async function Dr(){try{await Nt.releaseKey(P.LeftControl,P.RightControl,P.LeftAlt,P.RightAlt,P.LeftShift,P.RightShift,P.LeftSuper,P.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(p=>setTimeout(p,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 p=0;p<a;p++)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:P.Enter,return:P.Return,escape:P.Escape,esc:P.Escape,backspace:P.Backspace,tab:P.Tab,space:P.Space,up:P.Up,down:P.Down,left:P.Left,right:P.Right,ctrl:P.LeftControl,control:P.LeftControl,alt:P.LeftAlt,shift:P.LeftShift,cmd:P.LeftCmd,win:P.LeftWin,meta:P.LeftWin,super:P.LeftSuper,a:P.A,b:P.B,c:P.C,d:P.D,e:P.E,f:P.F,g:P.G,h:P.H,i:P.I,j:P.J,k:P.K,l:P.L,m:P.M,n:P.N,o:P.O,p:P.P,q:P.Q,r:P.R,s:P.S,t:P.T,u:P.U,v:P.V,w:P.W,x:P.X,y:P.Y,z:P.Z,0:P.Num0,1:P.Num1,2:P.Num2,3:P.Num3,4:P.Num4,5:P.Num5,6:P.Num6,7:P.Num7,8:P.Num8,9:P.Num9,f1:P.F1,f2:P.F2,f3:P.F3,f4:P.F4,f5:P.F5,f6:P.F6,f7:P.F7,f8:P.F8,f9:P.F9,f10:P.F10,f11:P.F11,f12:P.F12},fa=e=>{if(!e)return;let n=String(e).toLowerCase().trim();if(da[n]!==void 0)return da[n];if(P[e]!==void 0)return P[e];if(P[n.toUpperCase()]!==void 0)return P[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 Dr(),await Yl.setContent(n);let s=process.platform==="darwin"?P.LeftSuper:P.LeftControl;return await Nt.pressKey(s,P.V),await Nt.releaseKey(s,P.V),await Dr(),t.autoPressEnter?(await new Promise(r=>setTimeout(r,50)),await Nt.type(P.Enter),`SUCCESS: Typed text input ("${n.length>20?n.substring(0,20)+"...":n}") and pressed Enter`):`SUCCESS: Typed text input ("${n.length>20?n.substring(0,20)+"...":n}")`}case"key_press":{let o=fa(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=>fa(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(P.LeftControl,P.A),await Nt.releaseKey(P.LeftControl,P.A),await Nt.type(P.Backspace),"SUCCESS: Cleared active text input (Select All + Backspace)";case"browser_back":{let o=process.platform==="darwin";return o?(await Nt.pressKey(P.LeftSuper,P.Left),await Nt.releaseKey(P.LeftSuper,P.Left)):(await Nt.pressKey(P.LeftAlt,P.Left),await Nt.releaseKey(P.LeftAlt,P.Left)),await Dr(),`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 Vl(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Xl(e,n,t=1/0){if(e===n)return 0;if(e.length===0)return n.length;if(n.length===0)return e.length;if(Math.abs(e.length-n.length)>t)return t+1;let o=Array.from({length:n.length+1},(s,r)=>r);for(let s=1;s<=e.length;s++){let r=[s],a=s;for(let i=1;i<=n.length;i++){let p=e[s-1]===n[i-1]?0:1,d=Math.min(r[i-1]+1,o[i]+1,o[i-1]+p);r.push(d),d<a&&(a=d)}if(o=r,a>t)return t+1}return o[n.length]}function Jl(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 Ql(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],p=r[3],d=r[4],c=parseInt(r[6]),l=parseInt(r[7]),f=parseInt(r[8]),u=parseInt(r[9]),h=parseFloat(r[10]),g=r.slice(11).join(" ").trim();if(!g||h<0)continue;let y={x0:c,y0:l,x1:c+f,y1:l+u},m={text:g,confidence:h,bbox:y};n.push(m);let w=`${i}_${p}_${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 Zl(e){if(!(e.words&&e.words.length>0)){if(e.blocks&&e.blocks.length>0){e.words=[],e.lines=[];for(let n of e.blocks)for(let t of n.paragraphs||[])for(let o of t.lines||[]){o.bbox&&e.lines.push(o);for(let s of o.words||[])s.bbox&&e.words.push(s)}if(e.words.length>0)return}if(e.tsv){let n=Ql(e.tsv);e.words=n.words,e.lines=n.lines}}}function Br(e,n,t=0,o=0,s=1){Zl(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 p=i.text?i.text.toLowerCase().trim():"";if(!p||!i.bbox||!(p===n||new RegExp(`\\b${Vl(n)}\\b`,"i").test(p)))continue;let c=i.words||(e.words?e.words.filter(h=>h.bbox&&h.bbox.x0>=i.bbox.x0-5&&h.bbox.x1<=i.bbox.x1+5&&h.bbox.y0>=i.bbox.y0-5&&h.bbox.y1<=i.bbox.y1+5):[]),l=n.split(/\s+/),f=l.map(h=>h.replace(/[^a-z0-9]/g,"")).join(" "),u=!1;if(c.length>0)for(let h=0;h<=c.length-l.length;h++){let g=c.slice(h,h+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 p=i.text?i.text.toLowerCase().trim().replace(/[^a-z0-9]/g,""):"",d=n.replace(/[^a-z0-9]/g,"");p===d&&i.bbox&&a.push(r(i.bbox))}if(a.length===0&&e.words&&e.words.length>0){let i=Jl(n.length);for(let p of e.words){let d=p.text?p.text.toLowerCase().trim():"";d.length>=3&&Math.abs(d.length-n.length)<=i&&Xl(d,n,i)<=i&&p.bbox&&a.push(r(p.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,p=Math.hypot(r-n.x,a-n.y),d=i?0:p;d<o&&(o=d,t={x:r,y:a,dist:p,containsPoint:i,bbox:s})}return t}function ec(e,n,t,o){let a=Math.ceil(e/4),i=Math.ceil(n/2),p=[];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),h=Math.min(i,n-f),g=l+u/2,y=f+h/2,m=t>=l&&t<l+u&&o>=f&&o<f+h;p.push({x0:l,y0:f,w:u,h,cx:g,cy:y,containsTarget:m})}return p.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 tc(){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 nc(){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 h=performance.now(),g=(h-s).toFixed(0),y=(h-o).toFixed(0);console.log(`[Click Perf] +${g}ms (${y}ms total) -> ${u}`),s=h};r("Starting click()");let a=O(e),i=a.gridId||a.grid||a.coordinate||a.target||a.id,p=(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 h=await nc();r("Taking desktop screenshot");let g=await ma(h);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},T=c.toLowerCase().trim();r("Acquiring OCR worker");let $=await tc(),R=null,k="",S=u?220:500;if(u){r("Pass 1: Cropping target crop (3x zoom window, 2x upscale)");let _=Math.min(Math.round(m/3),m),E=Math.min(Math.round(w/3),w),x=Math.max(0,Math.min(m-_,b.x-Math.floor(_/2))),C=Math.max(0,Math.min(w-E,b.y-Math.floor(E/2))),I=await co(g).extract({left:x,top:C,width:_,height:E}).toBuffer(),L=2,N=await Nr(I,L),W=T.replace(/[^a-z0-9]/g,"_");await Fr("cropped",`crop_${Date.now()}_${W}.png`,N),r("Pass 1: Running Tesseract OCR recognize on crop (PSM 11 - Sparse Text)"),await $.setParameters({tessedit_pageseg_mode:"11"});let{data:X}=await $.recognize(N,{},{tsv:!0,blocks:!0});if(r("Pass 1: OCR recognition finished, extracting matches"),X&&X.text){t&&console.log(`[Pass 1 OCR Read]: "${X.text.trim().replace(/\s+/g," ")}"`);let re=Br(X,T,x,C,L);if(re.length>0){let Y=Ur(re,b);Y&&(Y.containsPoint||Y.dist<=S)&&(R=Y,k="centered target crop OCR")}}}if(!R){r("Pass 2: Entering Full-Screen OCR (broad scan, PSM 3 - Auto)");let _=await Nr(g,2),E=T.replace(/[^a-z0-9]/g,"_");await Fr("fullscreen",`full_${Date.now()}_${E}.png`,_),r("Pass 2: Running Tesseract on full screen"),await $.setParameters({tessedit_pageseg_mode:"3"});let{data:x}=await $.recognize(_,{},{tsv:!0,blocks:!0});if(r("Pass 2: Full-screen OCR finished"),x&&x.text){let C=Br(x,T,0,0,2);if(C.length>0){let I=Ur(C,b);I&&(R=I,k="full-screen OCR")}}}if(!R){r("Pass 3: Entering Tiled OCR fallback (high-res 3x)");let _=ec(m,w,b.x,b.y),E=T.replace(/[^a-z0-9]/g,"_");await $.setParameters({tessedit_pageseg_mode:"11"});for(let x=0;x<_.length;x++){let C=_[x];r(`Pass 3: Preprocessing tile ${x+1}/${_.length}`);let I=await co(g).extract({left:C.x0,top:C.y0,width:C.w,height:C.h}).toBuffer(),L=await Nr(I,3);await Fr("tiles",`tile_${x+1}_${Date.now()}_${E}.png`,L),r(`Pass 3: Running Tesseract on tile ${x+1}`);let{data:N}=await $.recognize(L,{},{tsv:!0,blocks:!0});if(!N||!N.text)continue;let W=Br(N,T,C.x0,C.y0,3);if(W.length>0){let X=Ur(W,b);if(X){R=X,k=`tile ${x+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 (${k})`);let E=await In("click",_,{button:d,clickType:p});return r("Click completed successfully"),`${E} (${k} 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:p});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 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 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 Do=async(e,n={})=>"SUCCESS: Screen recapture requested. The latest gridded screenshot is provided for your next decision.";var sc={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:Ps,answerSubagent:Ds,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:Po,KeyPress:Po,keypress:Po,recapture_screen:Do,RecaptureScreen:Do,recapturescreen:Do,invoke_sync:Ir,get_progress:Or,await_subagent:Ps,answer_subagent:Ds,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:Ds,Answer:Ds,AnswerSubagent:Ds,await:Ps,Await:Ps,AwaitSubagent:Ps,EmergencyRollback:Pr,emergency_rollback:Pr},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",p=["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(!p)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=sc[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 ee from"path";import Pe from"fs";import oc 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 rc=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",Pp=(e=2)=>{let n=rc();return n==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)},Dp=(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,p="\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=oc(c).multiline(d.join(`
486
486
  `)).split(`
487
487
  `),f=u=>`${i}${u}${p}`;return`${l[0]}
488
488
  ${l[1]} ${r}Selected Provider: ${n}${p}
@@ -491,46 +491,46 @@ ${l[3]} ${r}FluxFlow ${f("v"+e)}${p}
491
491
  ${l[4]}
492
492
  ${l[5]} ${a}See /help for additional commands.${p}
493
493
  ${l[6]} ${f(o)}
494
- ${l[7]}`};import{WebSocket as No}from"ws";var Yt=null,Fs=!1,rc="ws://localhost:56832",qr=[],Ns=null,zr=null,wa="2.0.0",Np=e=>{wa=e,xa()},Kr=e=>{zr=e},xa=()=>{if(Yt||Fs)return;Fs=!0;let e=new No(rc);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,Bp=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 ic from"fs";var ac=e=>{try{return ic.readdirSync(e,{withFileTypes:!0})}catch{return[]}},Vr=(e,n,t=1,o=ac,s=[],r=null)=>{let a=r||o(e),i=" ".repeat(t-1);if(a.length>100)return`${i}${Sa.basename(e)}/ (>100 files)
494
+ ${l[7]}`};import{WebSocket as No}from"ws";var Yt=null,Fs=!1,ic="ws://localhost:56832",qr=[],Ns=null,zr=null,wa="2.0.0",Bp=e=>{wa=e,xa()},Kr=e=>{zr=e},xa=()=>{if(Yt||Fs)return;Fs=!0;let e=new No(ic);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,Up=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 ac from"fs";var lc=e=>{try{return ac.readdirSync(e,{withFileTypes:!0})}catch{return[]}},Vr=(e,n,t=1,o=lc,s=[],r=null)=>{let a=r||o(e),i=" ".repeat(t-1);if(a.length>100)return`${i}${Sa.basename(e)}/ (>100 files)
495
495
  `;let p="",d=s,c=a.filter(h=>!d.includes(h.name)&&!h.name.startsWith(".")),l=a.filter(h=>d.includes(h.name)||h.name.startsWith(".")).map(h=>h.name).sort();l.length>0&&(p+=`${i}[ignored: ${l.map(h=>h+"/").join(", ")}]
496
496
  `);let f=c.filter(h=>h.isDirectory()).sort((h,g)=>h.name.localeCompare(g.name)),u=c.filter(h=>!h.isDirectory()).map(h=>h.name).sort();for(let h of f){let g=Sa.join(e,h.name);if(t>n)p+=`${i}${h.name}/ (max depth)
497
497
  `;else{let y=o(g);y.length>80?p+=`${i}${h.name}/ (>80 files)
498
498
  `:(p+=`${i}${h.name}/
499
499
  `,p+=Vr(g,n,t+1,o,s,y))}}return u.length>0&&(p+=`${i}${u.join("; ")}
500
- `),p};import Xr from"path";import lc from"fs";var cc=e=>{try{return lc.readdirSync(e,{withFileTypes:!0})}catch{return[]}},Jr=(e,n,t="",o=1,s=cc,r=[])=>{let a=s(e),i=Xr.sep;if(a.length>100)return`${t}\u2514\u2500\u2500 ${Xr.basename(e)}${i} ...100+ files...
500
+ `),p};import Xr from"path";import cc from"fs";var dc=e=>{try{return cc.readdirSync(e,{withFileTypes:!0})}catch{return[]}},Jr=(e,n,t="",o=1,s=dc,r=[])=>{let a=s(e),i=Xr.sep;if(a.length>100)return`${t}\u2514\u2500\u2500 ${Xr.basename(e)}${i} ...100+ files...
501
501
  `;let p="",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,h)=>u.isDirectory()&&!h.isDirectory()?-1:!u.isDirectory()&&h.isDirectory()?1:u.name.localeCompare(h.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,h)=>{let g=h===f.length-1,y=Xr.join(e,u.name),m=g?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",w=t+(g?" ":"\u2502 ");if(u.isCollapsed){p+=`${t}${m}${u.name}${i}...
502
502
  `;return}u.isDir?o>n?p+=`${t}${m}${u.name}${i} ...depth exceeded...
503
503
  `:s(y).length>80?p+=`${t}${m}${u.name}${i} ...80+ files...
504
504
  `:(p+=`${t}${m}${u.name}${i}
505
505
  `,p+=Jr(y,n,w,o+1,s,r)):p+=`${t}${m}${u.name}
506
- `}),p};import"@google/genai";Zr.config({quiet:!0});Zr.config({path:"./fluxflow.env",override:!0,quiet:!0});Zr.config({path:"./.fluxflow.env",override:!0,quiet:!0});var fc=/```[\s\S]*?```/g,uc=/```[\s\S]*$/g,hc=/`[^`]+`/g,pc=/^\|.*\|$/gm,mc=/^[^\w]+|[^\w]+$/g,gc=/[^a-z0-9]/gi,ho=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,yc=/\[\s*(?:tool:functions\.|agent:generalist\.)([a-z0-9_]+)\s*\(/gi,wc=/(?:path|targetFile|TargetFile|directory|keyword|id|taskId|title|task)\s*=\s*\\?["']?([^\\"' \),]+)/,gs=/["']/g,Ta=/\\/g,xc=/<\|channel>thought/gi,bc=/<channel\|>/gi,Pn=e=>typeof e!="string"?e:e.replace(xc,"<think>").replace(bc,"</think>"),kc=/(?:<(think|thought|thoughts)>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\])/gi,Sc=/(?:<(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,Tc=/"([^"]+)"\s*:\s*(?:"([^"]*)"|(\d+)|true|false|null)/g,$a=/<\|\s*tool_calls_section_begin\s*\|>/gi,Ca=/<\|\s*tool_calls_section_end\s*\|>/gi,Rc=/```(?: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`),Ec=async(e,n=8,t=1e3,o=8e3,s=null)=>{let r=0;for(;;){if(s?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{return await e()}catch(a){if(s?.aborted||a?.name==="AbortError"||a?.message==="Subagent task was cancelled."||(r++,r>=n))throw a;let i=Math.min(t*Math.pow(2,r-1),o);await new Promise((p,d)=>{let c=setTimeout(p,i);s&&s.addEventListener("abort",()=>{clearTimeout(c),d(new DOMException("The user aborted a request.","AbortError"))})})}}},Lt=!1;var _c=e=>{let n=e.filter(s=>(s.role==="user"||s.role==="agent"||s.role==="system")&&s.role!=="think"&&!s.isVisualFeedback&&!s.isMeta&&!s.isTerminalRecord&&!(s.text&&s.text.includes("[TERMINAL_RECORD]"))&&!String(s.id).startsWith("welcome")).map((s,r,a)=>{let i=s.fullText||s.text||"";if(s.role==="user"&&r<a.length-1)if(i.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")){let p=i.indexOf("**CONTEXT SUMMARY OF PREVIOUS TURNS");if(p!==-1){let c=i.substring(0,p).lastIndexOf("[SYSTEM METADATA]");c!==-1?i=i.substring(c).trim():i=i.substring(p).trim()}}else{let p=i.lastIndexOf("[USER]"),d=i.lastIndexOf("[USER PROMPT]");p!==-1?i=i.substring(p+6).trim():d!==-1&&(i=i.substring(d).trim())}return{...s,text:i}}),t=[],o=0;for(;o<n.length;){let s=n[o];if(s.role==="user")t.push(s),o++;else{let r=[];for(;o<n.length&&n[o].role!=="user";)r.push(n[o]),o++;let a=[],i=[],p=!1,d=()=>{a.length>0&&(t.push({role:"agent",text:"combined"}),a=[]),i.length>0&&(t.push({role:"system",text:"combined"}),i=[]),p=!1};r.forEach(c=>{let l=c.role==="system"&&(c.text?.startsWith("[TOOL RESULT]")||c.text?.startsWith("SUCCESS:")||c.text?.startsWith("ERROR:")||c.fullText?.startsWith("[TOOL RESULT]")||c.fullText?.startsWith("SUCCESS:")||c.fullText?.startsWith("ERROR:")),f=c.fullText||c.text||"",u=f.trim();if(!(!u&&!c.binaryPart)){if(l)i.push(u);else if(c.role==="agent"){!p&&i.length>0&&d();let h=f.endsWith(`
507
- `),g=u.toLowerCase().includes("tool:functions.")||u.toLowerCase().includes("agent:generalist.");a.push(u),g&&h?p=!0:p=!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,p)=>{let d=setTimeout(()=>{s.removeEventListener("abort",c),i()},Math.min(24e3,o*Math.pow(2,a))),c=()=>{clearTimeout(d),p(new DOMException("The user aborted a request.","AbortError"))};s.addEventListener("abort",c)}):await new Promise(i=>setTimeout(i,Math.min(24e3,o*Math.pow(2,a))))}if(s?.aborted)throw new DOMException("The user aborted a request.","AbortError");let r=await fetch(e,n);return typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),r},ti=async function*(e,n,t,o,s,r,a,i,p=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:p};if(s!=="Fast"){let b={Low:"high",Medium:"high",Standard:"high",High:"max",xHigh:"max"};c.reasoning_effort=b[s]||"high",c.extra_body={thinking:{type:"enabled"}}}else c.extra_body={thinking:{type:"disabled"}};let l=await xs("https://api.deepseek.com/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(c),signal:i});if(!l.ok){let b=await l.json().catch(()=>({}));throw new Error(`DeepSeek Error (${l.status}): ${b.error?.message||l.statusText}`)}let f=l.body.getReader(),u=new TextDecoder,h="",g=[],y=null,m=Date.now(),w=!1;for(;;){let{done:b,value:x}=await f.read();if(b){w&&(g.length>0||y)&&(yield{candidates:g.length>0?[{content:{parts:g}}]:[],usageMetadata:y});break}h+=u.decode(x,{stream:!0});let E=h.split(`
508
- `);h=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,p=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:p,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(),h=new TextDecoder,g="",y=[],m=null,w=Date.now(),b=!1,x=E=>E?typeof E=="string"?Pn(E):Array.isArray(E)?E.map(x).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?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):"":Pn(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+=h.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 P=C.thinking||C.reasoning_content||C.reasoning,B=x(P);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 se=Y.type==="thinking"||Y.type==="reasoning"||!!Y.thought,Ie=x(Y);Ie&&(y.push({text:Ie,...se?{thought:!0}:{}}),b=!0)}else{let se=x(Y);se&&(y.push({text:se}),b=!0)}else if(typeof N=="object"&&N!==null){let Y=N.type==="thinking"||N.type==="reasoning"||!!N.thought,se=x(N);se&&(y.push({text:se,...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,p=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"),h=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"},P={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:p,...b&&{thinking:C[s]||"high"}};if(!(process.env.NVIDIA_BASE_URL||_||k))if(u)N.chat_template_kwargs={thinking:f};else if(h)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=P[l]||"medium");let Y=0,se=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<se;){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(()=>""),it=ae.statusText;try{let gt=JSON.parse(je);it=gt.error?.message||gt.message||JSON.stringify(gt.detail||gt)}catch{je&&(it=je)}let ze=new Error(`NVIDIA API Error (${ae.status}): ${it}`);throw ze.status=ae.status,ze}let _e=ae.body.getReader(),A=new TextDecoder,F="",V=[],X=null,Ue=Date.now(),Fe=!1;for(;;){let{done:je,value:it}=await _e.read();if(je){Fe&&(V.length>0||X)&&(yield{candidates:V.length>0?[{content:{parts:V}}]:[],usageMetadata:X},Ie=!0);break}F+=A.decode(it,{stream:!0});let ze=F.split(`
510
- `);F=ze.pop();let gt=!1;for(let Bt of ze){let yt=Bt.trim();if(yt){if(yt==="data: [DONE]"){gt=!0;break}if(yt.startsWith("data: ")){let wt;try{wt=JSON.parse(yt.substring(6))}catch{continue}if(wt.error)throw new Error(`NVIDIA Stream Error: ${wt.error.message||JSON.stringify(wt.error)}`);wt.choices?.[0]?.finish_reason&&(gt=!0);try{let Rt=wt.usage;Rt&&(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)},Fe=!0);let ut=wt.choices?.[0]?.delta?.reasoning||wt.choices?.[0]?.delta?.reasoning_content||"",$e=wt.choices?.[0]?.delta?.content||"";ut&&(V.push({text:ut,thought:!0}),Fe=!0),$e&&(V.push({text:$e}),Fe=!0)}catch{}}}}if((gt||Date.now()-Ue>=350)&&Fe&&(yield{candidates:V.length>0?[{content:{parts:[...V]}}]:[],usageMetadata:X},Ie=!0,V=[],Ue=Date.now(),Fe=!1),gt)break}break}catch(ae){if(Ie||Y>=se)throw ae;await new Promise(_e=>setTimeout(_e,3500))}}},Cc=async function*(e,n){let t=[],o=null,s=!1,r=null,a=f=>{if(t.push(f),o){let u=o;o=null,u()}},i=n.split("/").pop();i=i.replace("llama-3.3","llama-3_3");let p=`https://api.ngc.nvidia.com/v2/predict/queues/models/qc69jvmznzxy/${i}`,d=!1,c=null,l=async()=>{try{let f=await fetch(p);if(f.ok){let u=await f.json();if(u&&u.queues&&u.queues[0]&&typeof u.queues[0].queueDepth=="number"){let h=u.queues[0].queueDepth;d||a({value:{type:"status",content:`Queue ${h||1}`},done:!1})}}else d||a({value:{type:"status",content:`Queue ${f.status}`},done:!1})}catch{}};process.env.NVIDIA_BASE_URL||(l(),c=setInterval(l,5e3)),(async()=>{try{let f=e[Symbol.asyncIterator]();for(;;){let{value:u,done:h}=await f.next();if(h)break;d=!0,c&&(clearInterval(c),c=null),a({value:u,done:!1})}s=!0,a(null)}catch(f){if(r=f,c&&(clearInterval(c),c=null),o){let u=o;o=null,u()}}})();try{for(;;){if(r)throw r;if(t.length>0){let f=t.shift();if(f===null&&s)break;yield f.value}else{if(s)break;await new Promise(f=>{o=f})}}}finally{c&&(clearInterval(c),c=null)}},oi=async function*(e,n,t,o,s,r,a,i,p=1.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 h={model:u,messages:d,stream:!0,temperature:p,cache_control:{type:"ephemeral"},session_id:"flux-flow-session"},g=c[s];g&&s!=="Fast"&&(h.reasoning_effort=g),console.log(h);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(h),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 P=JSON.parse(C.substring(6)),B=P.choices?.[0]?.delta,N=P.usage;if(P.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(se=>se.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}}},Pa=async function*(e,n,t,o,s,r,a,i,p=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 h=new dc(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:p}},R=await h.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,p=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:p,max_completion_tokens:32768};c[s]&&(l.reasoning_effort=c[s]);let f=await xs("https://crof.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(l),signal:i});if(!f.ok){let x=await f.json().catch(()=>({}));throw new Error(`CrofAI Error (${f.status}): ${x.error?.message||f.statusText}`)}let u=f.body.getReader(),h=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+=h.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,p=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:p};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(),h=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+=h.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,p=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:p};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(),h=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+=h.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)}},Em=()=>{Lt=!0},_m=()=>Lt,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?Z.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:p,onBackgroundIncrement:d}=s,{profile:c,thinkingLevel:l,mode:f,janitorModel:u,chatId:h,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=Q(Dt,[]).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,(Fe,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,`
506
+ `}),p};import"@google/genai";Zr.config({quiet:!0});Zr.config({path:"./fluxflow.env",override:!0,quiet:!0});Zr.config({path:"./.fluxflow.env",override:!0,quiet:!0});var uc=/```[\s\S]*?```/g,hc=/```[\s\S]*$/g,pc=/`[^`]+`/g,mc=/^\|.*\|$/gm,gc=/^[^\w]+|[^\w]+$/g,yc=/[^a-z0-9]/gi,ho=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,wc=/\[\s*(?:tool:functions\.|agent:generalist\.)([a-z0-9_]+)\s*\(/gi,xc=/(?:path|targetFile|TargetFile|directory|keyword|id|taskId|title|task)\s*=\s*\\?["']?([^\\"' \),]+)/,gs=/["']/g,Ta=/\\/g,bc=/<\|channel>thought/gi,kc=/<channel\|>/gi,Pn=e=>typeof e!="string"?e:e.replace(bc,"<think>").replace(kc,"</think>"),Sc=/(?:<(think|thought|thoughts)>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\])/gi,Tc=/(?:<(think|thought|thoughts)>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*$/gi,Ra=/(?:<think>|<\|channel>thought|\[think\])[\s\S]*?(?:<\/think>|<channel\|>|\[\/think\]|$)/gi,Ea=/(?:<(think|thought|thoughts)>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\]|$)/gi,Oa=/`[^`]*`/g,La=/`[^`]*$/,_a=/<\|\s*tool_call_begin\s*\|>\s*(?:(?:tool|functions)\b[\s._]*)*([a-zA-Z0-9_]+)(?::\d+)?\s*<\|\s*tool_call_argument_begin\s*\|>([\s\S]*?)<\|\s*tool_call_end\s*\|>/gi,Rc=/"([^"]+)"\s*:\s*(?:"([^"]*)"|(\d+)|true|false|null)/g,$a=/<\|\s*tool_calls_section_begin\s*\|>/gi,Ca=/<\|\s*tool_calls_section_end\s*\|>/gi,Ec=/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi,Ma=/<(\w+)(?:[^>]*)>\r?\n?/gi,Aa=/\r?\n?<\/\w+(?:[^>]*)>/gi,ei=null,Wo={},ys={key:null,value:null},gn=e=>e&&e.replace(/(?:(\x1b\[\d+m))?([✔✘✖🔍📖→➕↻↷•🛇])(?:(\x1b\[\d+m))?\s*\b(Clicked|Dragged|Scrolled|Typed|Pressed Key|Recaptured Screen|Created|Read|Edited|Viewed|Processed|Auto-Read|Skipped|List|Generated|Written|Searched|AI Search|Get Map|Write Canceled|Resolved Sub-Agent Query|Edit Canceled|Write Cancelled|Edit Denied|Visited|Updated|Reviewed|Delegated|Background|Checked|Indexed|Analyzed|Browsed|Elevating SubAgent|Checking SubAgent Work|Started Generalist|Called Generalist|Steered|Unsupported Modality|Awaiting|Cancelled|Aligning Moon Phase|Contemplating Existence|Staring At Void|Rollback Point Checked|Emergency Rollback Failed|Emergency Rollback|Delaying Professionally|Negotiating With Electrons|Touching Grass (virtually)|Panicking Softly|Rethinking Career Choices|Loading Cat Videos|Giving Up Entirely|Summoning Braincell #2|Pretending To Be Busy|Waiting For Motivation DLC|Rotating Internal Screaming|Downloading More RAM|Feeding The Hamsters|Gaslighting Scheduler|Performing Dramatic Pause|Buffering Social Energy|Calculating Regret|Reading Terms And Conditions|Becoming Sentient Briefly|Contacting Ancestors)\b/ig,(n,t,o,s,r)=>`${t||""}${o}${s||""} \x1B[95m${r}\x1B[0m`),_c=async(e,n=8,t=1e3,o=8e3,s=null)=>{let r=0;for(;;){if(s?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{return await e()}catch(a){if(s?.aborted||a?.name==="AbortError"||a?.message==="Subagent task was cancelled."||(r++,r>=n))throw a;let i=Math.min(t*Math.pow(2,r-1),o);await new Promise((p,d)=>{let c=setTimeout(p,i);s&&s.addEventListener("abort",()=>{clearTimeout(c),d(new DOMException("The user aborted a request.","AbortError"))})})}}},Lt=!1;var $c=e=>{let n=e.filter(s=>(s.role==="user"||s.role==="agent"||s.role==="system")&&s.role!=="think"&&!s.isVisualFeedback&&!s.isMeta&&!s.isTerminalRecord&&!(s.text&&s.text.includes("[TERMINAL_RECORD]"))&&!String(s.id).startsWith("welcome")).map((s,r,a)=>{let i=s.fullText||s.text||"";if(s.role==="user"&&r<a.length-1)if(i.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")){let p=i.indexOf("**CONTEXT SUMMARY OF PREVIOUS TURNS");if(p!==-1){let c=i.substring(0,p).lastIndexOf("[SYSTEM METADATA]");c!==-1?i=i.substring(c).trim():i=i.substring(p).trim()}}else{let p=i.lastIndexOf("[USER]"),d=i.lastIndexOf("[USER PROMPT]");p!==-1?i=i.substring(p+6).trim():d!==-1&&(i=i.substring(d).trim())}return{...s,text:i}}),t=[],o=0;for(;o<n.length;){let s=n[o];if(s.role==="user")t.push(s),o++;else{let r=[];for(;o<n.length&&n[o].role!=="user";)r.push(n[o]),o++;let a=[],i=[],p=!1,d=()=>{a.length>0&&(t.push({role:"agent",text:"combined"}),a=[]),i.length>0&&(t.push({role:"system",text:"combined"}),i=[]),p=!1};r.forEach(c=>{let l=c.role==="system"&&(c.text?.startsWith("[TOOL RESULT]")||c.text?.startsWith("SUCCESS:")||c.text?.startsWith("ERROR:")||c.fullText?.startsWith("[TOOL RESULT]")||c.fullText?.startsWith("SUCCESS:")||c.fullText?.startsWith("ERROR:")),f=c.fullText||c.text||"",u=f.trim();if(!(!u&&!c.binaryPart)){if(l)i.push(u);else if(c.role==="agent"){!p&&i.length>0&&d();let h=f.endsWith(`
507
+ `),g=u.toLowerCase().includes("tool:functions.")||u.toLowerCase().includes("agent:generalist.");a.push(u),g&&h?p=!0:p=!1}}}),d()}}return t.length},Cc=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),xs=async(e,n,t=5,o=1e3)=>{let s=n?.signal;for(let a=0;a<t;a++){if(s?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{let i=await fetch(e,n);if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),i.ok||i.status!==429&&i.status<500)return i}catch(i){if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),i.name==="AbortError"||s?.aborted||a===t-1)throw i}s?await new Promise((i,p)=>{let d=setTimeout(()=>{s.removeEventListener("abort",c),i()},Math.min(24e3,o*Math.pow(2,a))),c=()=>{clearTimeout(d),p(new DOMException("The user aborted a request.","AbortError"))};s.addEventListener("abort",c)}):await new Promise(i=>setTimeout(i,Math.min(24e3,o*Math.pow(2,a))))}if(s?.aborted)throw new DOMException("The user aborted a request.","AbortError");let r=await fetch(e,n);return typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),r};async function Pa(e){let n=new TextEncoder().encode(e),t=await crypto.subtle.digest("SHA-256",n);return[...new Uint8Array(t).slice(0,16)].map(o=>o.toString(16).padStart(2,"0")).join("")}var ti=async function*(e,n,t,o,s,r,a,i,p=1){let d=[];o&&d.push({role:"system",content:o});for(let b of t){let T=b.role==="user"?"user":"assistant",$=[];if(Array.isArray(b.parts)){for(let R of b.parts)if(R.text)$.push({type:"text",text:R.text});else if(R.inlineData&&a){let k=R.inlineData.mimeType,S=R.inlineData.data;k.startsWith("image/")&&$.push({type:"image_url",image_url:{url:`data:${k};base64,${S}`}})}}else{let R=b.text||"";R&&$.push({type:"text",text:R})}d.push({role:T,content:$.length===1&&$[0].type==="text"?$[0].text:$})}let c={model:n,messages:d,stream:!0,stream_options:{include_usage:!0},temperature:p};if(s!=="Fast"){let b={Low:"high",Medium:"high",Standard:"high",High:"max",xHigh:"max"};c.reasoning_effort=b[s]||"high",c.extra_body={thinking:{type:"enabled"}}}else c.extra_body={thinking:{type:"disabled"}};let l=await xs("https://api.deepseek.com/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(c),signal:i});if(!l.ok){let b=await l.json().catch(()=>({}));throw new Error(`DeepSeek Error (${l.status}): ${b.error?.message||l.statusText}`)}let f=l.body.getReader(),u=new TextDecoder,h="",g=[],y=null,m=Date.now(),w=!1;for(;;){let{done:b,value:T}=await f.read();if(b){w&&(g.length>0||y)&&(yield{candidates:g.length>0?[{content:{parts:g}}]:[],usageMetadata:y});break}h+=u.decode(T,{stream:!0});let $=h.split(`
508
+ `);h=$.pop();for(let R of $){let k=R.trim();if(!k||!k.startsWith("data: "))continue;let S=!1;if(k==="data: [DONE]")S=!0;else try{let _=JSON.parse(k.substring(6)),E=_.choices?.[0]?.delta,x=_.usage;if(_.choices?.[0]?.finish_reason&&(S=!0),x&&(y={totalTokenCount:x.total_tokens||x.prompt_tokens+x.completion_tokens,promptTokenCount:x.prompt_tokens||0,candidatesTokenCount:x.completion_tokens||0,cachedContentTokenCount:x.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:x.completion_tokens_details?.reasoning_tokens||0},w=!0),E){let C=E.reasoning_content||null;C&&(g.push({text:C,thought:!0}),w=!0),E.content&&(g.push({text:E.content}),w=!0)}}catch{}if((S||Date.now()-m>=150)&&w&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],m=Date.now(),w=!1),S)break}Date.now()-m>=150&&w&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],m=Date.now(),w=!1)}},ni=async function*(e,n,t,o,s,r,a,i,p=1,d=null){let c=[];o&&c.push({role:"system",content:o});for(let S of t){let _=S.role==="user"?"user":"assistant",E=[];if(Array.isArray(S.parts)){for(let x of S.parts)if(x.text)E.push({type:"text",text:x.text});else if(x.inlineData&&a){let C=x.inlineData.mimeType,I=x.inlineData.data;C.startsWith("image/")&&E.push({type:"image_url",image_url:`data:${C};base64,${I}`})}}else{let x=S.text||"";x&&E.push({type:"text",text:x})}E.length>0&&c.push({role:_,content:E.length===1&&E[0].type==="text"?E[0].text:E})}let l={Fast:"none",Low:"none",Medium:"high",Standard:"high",High:"high",xHigh:"high"},f=`${e.slice(-5)}${d||""}${s}${n}`,u=await Pa(f),h={model:n,messages:c,stream:!0,temperature:p,prompt_cache_key:u};s&&s!=="Fast"&&qs(n)&&(h.reasoning_effort=l[s]||"high");let g=await xs("https://api.mistral.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(h),signal:i});if(!g.ok){let S=await g.text().catch(()=>""),_=g.statusText;try{let E=JSON.parse(S);_=E.error?.message||E.message||JSON.stringify(E.detail||E)}catch{S&&(_=S)}throw new Error(`Mistral Error (${g.status}): ${JSON.stringify(_)}`)}let y=g.body.getReader(),m=new TextDecoder,w="",b=[],T=null,$=Date.now(),R=!1,k=S=>S?typeof S=="string"?Pn(S):Array.isArray(S)?S.map(k).filter(Boolean).join(""):typeof S=="object"&&S!==null?typeof S.text=="string"?Pn(S.text):typeof S.content=="string"?Pn(S.content):typeof S.thinking=="string"?Pn(S.thinking):typeof S.reasoning_content=="string"?Pn(S.reasoning_content):typeof S.reasoning=="string"?Pn(S.reasoning):typeof S.value=="string"?Pn(S.value):S.text?k(S.text):S.content?k(S.content):S.thinking?k(S.thinking):S.reasoning_content?k(S.reasoning_content):S.reasoning?k(S.reasoning):S.value?k(S.value):"":Pn(String(S)):"";for(;;){let{done:S,value:_}=await y.read();if(S){R&&(b.length>0||T)&&(yield{candidates:b.length>0?[{content:{parts:b}}]:[],usageMetadata:T});break}w+=m.decode(_,{stream:!0});let E=w.split(`
509
+ `);w=E.pop();for(let x of E){let C=x.trim();if(!C||!C.startsWith("data: "))continue;let I=!1;if(C==="data: [DONE]")I=!0;else try{let L=JSON.parse(C.substring(6)),N=L.choices?.[0]?.delta,W=L.usage;if(L.choices?.[0]?.finish_reason&&(I=!0),W&&(T={totalTokenCount:W.total_tokens||(W.prompt_tokens||0)+(W.completion_tokens||0),promptTokenCount:W.prompt_tokens||0,candidatesTokenCount:W.completion_tokens||0,cachedContentTokenCount:W.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:W.completion_tokens_details?.reasoning_tokens||0},R=!0),N){let X=N.thinking||N.reasoning_content||N.reasoning,re=k(X);re&&(b.push({text:re,thought:!0}),R=!0);let Y=N.content||(!N.thinking&&!N.reasoning_content&&!N.reasoning?N.text:null);if(Y)if(Array.isArray(Y))for(let F of Y)if(typeof F=="object"&&F!==null){let U=F.type==="thinking"||F.type==="reasoning"||!!F.thought,se=k(F);se&&(b.push({text:se,...U?{thought:!0}:{}}),R=!0)}else{let U=k(F);U&&(b.push({text:U}),R=!0)}else if(typeof Y=="object"&&Y!==null){let F=Y.type==="thinking"||Y.type==="reasoning"||!!Y.thought,U=k(Y);U&&(b.push({text:U,...F?{thought:!0}:{}}),R=!0)}else{let F=k(Y);F&&(b.push({text:F}),R=!0)}}}catch{}if((I||Date.now()-$>=150)&&R&&(yield{candidates:b.length>0?[{content:{parts:[...b]}}]:[],usageMetadata:T},b=[],$=Date.now(),R=!1),I)break}Date.now()-$>=150&&R&&(yield{candidates:b.length>0?[{content:{parts:[...b]}}]:[],usageMetadata:T},b=[],$=Date.now(),R=!1)}},si=async function*(e,n,t,o,s,r,a=!1,i,p=1){let d=[];o&&d.push({role:"system",content:o}),t.forEach(se=>{let $e=se.role==="model"?"assistant":"user",A=[];Array.isArray(se.parts)&&se.parts.forEach(B=>{if(B.text)A.push({type:"text",text:B.text});else if(B.inlineData&&a){let V=B.inlineData.mimeType,J=B.inlineData.data;V.startsWith("image/")&&zt(n)&&A.push({type:"image_url",image_url:{url:`data:${V};base64,${J}`}})}}),d.push({role:$e,content:A.length===1&&A[0].type==="text"?A[0].text:A})});let l={Fast:"Fast",Low:"Fast",Medium:"Standard",Standard:"Standard",High:"High",xHigh:"High"}[s]||"High",f=l!=="Fast",u=n.includes("kimi"),h=n.includes("gemma"),g=n.includes("deepseek"),y=n.includes("glm"),m=n.includes("mistral"),w=n.includes("minimax"),b=n.includes("gpt"),T=n.includes("qwen"),$=n.includes("nemotron"),R=n.includes("llama-3"),k=n.includes("seed"),S=n.includes("poolside"),_=n.includes("thinkingmachines")||n.includes("muse"),E=R,x=null,C={Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},I={Fast:"64",Low:"64",Medium:"4096",Standard:"4096",High:"16384",xHigh:"16384"},L={Fast:"none",Low:"minimal",Medium:"medium",Standard:"medium",High:"max",xHigh:"max"},N=w||g||S||_?16384:32768;N=process.env.NVIDIA_BASE_URL?1024:N,N=x?1024:N;let W={model:n,messages:d,max_tokens:N,stream:!0,stream_options:{include_usage:!0},temperature:p,...b&&{thinking:C[s]||"high"}};if(!(process.env.NVIDIA_BASE_URL||E||x))if(u)W.chat_template_kwargs={thinking:f};else if(h)W.chat_template_kwargs={enable_thinking:f};else if(g)if(f){let se=l==="High"?"max":"high";W.chat_template_kwargs={thinking:!0,reasoning_effort:se}}else W.chat_template_kwargs={thinking:!1};else y?W.chat_template_kwargs={enable_thinking:f,clear_thinking:!f}:m?W.reasoning_effort=f?"high":"none":w&&n.includes("minimax-m3")?W.chat_template_kwargs={thinking_mode:f?"enabled":"disabled"}:T?W.chat_template_kwargs={enable_thinking:f}:$?l==="High"?(W.reasoning_budget=12e3,W.chat_template_kwargs={enable_thinking:!0}):l==="Standard"?(W.reasoning_budget=12e3,W.chat_template_kwargs={enable_thinking:!0,medium_effort:!0}):W.chat_template_kwargs={enable_thinking:!1}:k?f&&(W.extra_body={thinking_budget:parseInt(I[l]??"4096")}):S?W.chat_template_kwargs={enable_thinking:f}:_&&(W.reasoning_effort=L[l]||"medium");let X=0,re=6,Y=!1,F=process.env.NVIDIA_BASE_URL||"https://integrate.api.nvidia.com/v1/chat/completions",U=process.env.NVIDIA_API_KEY&&process.env.NVIDIA_BASE_URL?process.env.NVIDIA_API_KEY:e;for(F.endsWith("/chat/completions")||(F=F.replace(/\/+$/,"")+"/chat/completions");X<re;){X++;try{let se=await xs(F,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${U}`},body:JSON.stringify(W),signal:i});if(!se.ok){let je=await se.text().catch(()=>""),it=se.statusText;try{let gt=JSON.parse(je);it=gt.error?.message||gt.message||JSON.stringify(gt.detail||gt)}catch{je&&(it=je)}let ze=new Error(`NVIDIA API Error (${se.status}): ${it}`);throw ze.status=se.status,ze}let $e=se.body.getReader(),A=new TextDecoder,B="",V=[],J=null,Ue=Date.now(),Fe=!1;for(;;){let{done:je,value:it}=await $e.read();if(je){Fe&&(V.length>0||J)&&(yield{candidates:V.length>0?[{content:{parts:V}}]:[],usageMetadata:J},Y=!0);break}B+=A.decode(it,{stream:!0});let ze=B.split(`
510
+ `);B=ze.pop();let gt=!1;for(let Bt of ze){let yt=Bt.trim();if(yt){if(yt==="data: [DONE]"){gt=!0;break}if(yt.startsWith("data: ")){let wt;try{wt=JSON.parse(yt.substring(6))}catch{continue}if(wt.error)throw new Error(`NVIDIA Stream Error: ${wt.error.message||JSON.stringify(wt.error)}`);wt.choices?.[0]?.finish_reason&&(gt=!0);try{let Rt=wt.usage;Rt&&(J={totalTokenCount:Rt.total_tokens||Rt.prompt_tokens+Rt.completion_tokens,promptTokenCount:Rt.prompt_tokens||0,candidatesTokenCount:Rt.completion_tokens||0,cachedContentTokenCount:Rt.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:(Rt.completion_tokens_details?.reasoning_tokens||0)+(Rt.completion_tokens_details?.thoughts_tokens||0)},Fe=!0);let ut=wt.choices?.[0]?.delta?.reasoning||wt.choices?.[0]?.delta?.reasoning_content||"",Ce=wt.choices?.[0]?.delta?.content||"";ut&&(V.push({text:ut,thought:!0}),Fe=!0),Ce&&(V.push({text:Ce}),Fe=!0)}catch{}}}}if((gt||Date.now()-Ue>=350)&&Fe&&(yield{candidates:V.length>0?[{content:{parts:[...V]}}]:[],usageMetadata:J},Y=!0,V=[],Ue=Date.now(),Fe=!1),gt)break}break}catch(se){if(Y||X>=re)throw se;await new Promise($e=>setTimeout($e,3500))}}},Mc=async function*(e,n){let t=[],o=null,s=!1,r=null,a=f=>{if(t.push(f),o){let u=o;o=null,u()}},i=n.split("/").pop();i=i.replace("llama-3.3","llama-3_3");let p=`https://api.ngc.nvidia.com/v2/predict/queues/models/qc69jvmznzxy/${i}`,d=!1,c=null,l=async()=>{try{let f=await fetch(p);if(f.ok){let u=await f.json();if(u&&u.queues&&u.queues[0]&&typeof u.queues[0].queueDepth=="number"){let h=u.queues[0].queueDepth;d||a({value:{type:"status",content:`Queue ${h||1}`},done:!1})}}else d||a({value:{type:"status",content:`Queue ${f.status}`},done:!1})}catch{}};process.env.NVIDIA_BASE_URL||(l(),c=setInterval(l,5e3)),(async()=>{try{let f=e[Symbol.asyncIterator]();for(;;){let{value:u,done:h}=await f.next();if(h)break;d=!0,c&&(clearInterval(c),c=null),a({value:u,done:!1})}s=!0,a(null)}catch(f){if(r=f,c&&(clearInterval(c),c=null),o){let u=o;o=null,u()}}})();try{for(;;){if(r)throw r;if(t.length>0){let f=t.shift();if(f===null&&s)break;yield f.value}else{if(s)break;await new Promise(f=>{o=f})}}}finally{c&&(clearInterval(c),c=null)}},oi=async function*(e,n,t,o,s,r,a,i,p=1,d=null){let c=[];o&&c.push({role:"system",content:[{type:"text",text:o}]});for(let x of t){let C=x.role==="user"?"user":"assistant",I=[];if(Array.isArray(x.parts)){for(let L of x.parts)if(L.text)I.push({type:"text",text:L.text});else if(L.inlineData&&a){let N=L.inlineData.mimeType,W=L.inlineData.data;N.startsWith("image/")?I.push({type:"image_url",image_url:{url:`data:${N};base64,${W}`}}):I.push({type:"file",file:{filename:L.filename||"file",file_data:`data:${N};base64,${W}`}})}}else{let L=x.text||"";L&&I.push({type:"text",text:L})}c.push({role:C,content:I.length===1&&I[0].type==="text"?I[0].text:I})}let l={Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},f=n,u=null;if(f.includes("::")){let x=f.split("::");f=x[0].trim();let C=x.slice(1).join("::").toLowerCase().trim();["flex","priority","default"].includes(C)&&C!=="default"&&(u=C)}let h=f;if(f.includes(":")){let[x,...C]=f.split(":"),I=C.join(":").toLowerCase().trim();u?h=`${x}:${I}/${u}`:h=`${x}:${I}`}let g=`${e.slice(-5)}${d||""}${s}${h}`,y=await Pa(g),m={model:h,messages:c,stream:!0,temperature:p,cache_control:{type:"ephemeral"},session_id:y},w=l[s];w&&s!=="Fast"&&(m.reasoning_effort=w);let b=await xs("https://openrouter.ai/api/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json","X-Title":"FluxFlow CLI","X-Cache":"true","X-OpenRouter-Cache":"true"},body:JSON.stringify(m),signal:i});if(!b.ok){let x=await b.json().catch(()=>({}));throw new Error(`OpenRouter Error (${b.status}): ${x.error?.metadata.raw||x.error?.message||b.statusText}`)}let T=b.body.getReader(),$=new TextDecoder,R="",k=[],S=null,_=Date.now(),E=!1;for(;;){let{done:x,value:C}=await T.read();if(x){E&&(k.length>0||S)&&(yield{candidates:k.length>0?[{content:{parts:k}}]:[],usageMetadata:S});break}R+=$.decode(C,{stream:!0});let I=R.split(`
511
+ `);R=I.pop();for(let L of I){let N=L.trim();if(!N||!N.startsWith("data: "))continue;let W=!1;if(N==="data: [DONE]")W=!0;else try{let X=JSON.parse(N.substring(6)),re=X.choices?.[0]?.delta,Y=X.usage;if(X.choices?.[0]?.finish_reason&&(W=!0),Y&&(S={totalTokenCount:Y.total_tokens||(Y.prompt_tokens||0)+(Y.completion_tokens||0),promptTokenCount:Y.prompt_tokens||0,candidatesTokenCount:Y.completion_tokens||0,cachedContentTokenCount:Y.prompt_tokens_details?.cached_tokens||Y.prompt_tokens_details?.cache_read_input_tokens||Y.cache_read_input_tokens||0,thoughtsTokenCount:Y.completion_tokens_details?.reasoning_tokens||0},E=!0),re){let F=re.reasoning||(re.reasoning_details?re.reasoning_details.map(U=>U.text).join(""):null);F&&(k.push({text:F,thought:!0}),E=!0),re.content&&(k.push({text:re.content}),E=!0)}}catch{}if((W||Date.now()-_>=150)&&E&&(yield{candidates:k.length>0?[{content:{parts:[...k]}}]:[],usageMetadata:S},k=[],_=Date.now(),E=!1),W)break}}},Da=async function*(e,n,t,o,s,r,a,i,p=1,d="Cloud"){let c=[];o&&c.push({role:"system",content:o});for(let k of t){let S=k.role==="user"?"user":"assistant",_="",E=[];if(Array.isArray(k.parts)){_=k.parts.map(x=>x.text||"").filter(Boolean).join(`
512
+ `);for(let x of k.parts){let C=x.inlineData||x.inline_data;C&&C.data&&E.push(C.data)}}else _=k.text||"";if(_||E.length>0){let x={role:S,content:_};E.length>0&&(x.images=E),c.push(x)}}let l=d==="Local"||!e||e==="LOCAL",u={host:l?process.env.OLLAMA_HOST||"http://127.0.0.1:11434":process.env.OLLAMA_HOST||"https://ollama.com"};!l&&e&&(u.headers={Authorization:"Bearer "+e});let h=new fc(u),g=[],y=null,m=Date.now(),w=!1,b={Fast:!1,Low:"medium",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},T=b[s]!==void 0?b[s]:!0,$={model:n,messages:c,stream:!0,think:T,keep_alive:"10m",options:{temperature:p}},R=await h.chat($);for await(let k of R){if(i?.aborted)throw new DOMException("The user aborted a request.","AbortError");if(k.message?.thinking&&(g.push({text:k.message.thinking,thought:!0}),w=!0),k.message?.content&&(g.push({text:k.message.content}),w=!0),k.done){let S=k.prompt_cached_count||0;if(!S&&k.prompt_eval_count){let _=k.prompt_eval_duration||0;_>0&&_<5e7&&(S=k.prompt_eval_count)}y={totalTokenCount:(k.prompt_eval_count||0)+(k.eval_count||0),promptTokenCount:k.prompt_eval_count||0,candidatesTokenCount:k.eval_count||0,cachedContentTokenCount:S,thoughtsTokenCount:0},w=!0}(k.done||Date.now()-m>=150&&w)&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],m=Date.now(),w=!1)}w&&(g.length>0||y)&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y})},ri=async function*(e,n,t,o,s,r,a,i,p=1){let d=[];o&&d.push({role:"system",content:o});for(let T of t){let $=T.role==="user"?"user":"assistant",R=[];if(Array.isArray(T.parts)){for(let k of T.parts)if(k.text)R.push({type:"text",text:k.text});else if(k.inlineData&&a){let S=k.inlineData.mimeType,_=k.inlineData.data;S.startsWith("image/")&&R.push({type:"image_url",image_url:{url:`data:${S};base64,${_}`}})}}else{let k=T.text||"";k&&R.push({type:"text",text:k})}d.push({role:$,content:R.length===1&&R[0].type==="text"?R[0].text:R})}let c={Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},l={model:n,messages:d,stream:!0,stream_options:{include_usage:!0},temperature:p,max_completion_tokens:32768};c[s]&&(l.reasoning_effort=c[s]);let f=await xs("https://crof.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(l),signal:i});if(!f.ok){let T=await f.json().catch(()=>({}));throw new Error(`CrofAI Error (${f.status}): ${T.error?.message||f.statusText}`)}let u=f.body.getReader(),h=new TextDecoder,g="",y=[],m=null,w=Date.now(),b=!1;for(;;){let{done:T,value:$}=await u.read();if(T){b&&(y.length>0||m)&&(yield{candidates:y.length>0?[{content:{parts:y}}]:[],usageMetadata:m});break}g+=h.decode($,{stream:!0});let R=g.split(`
513
+ `);g=R.pop();for(let k of R){let S=k.trim();if(!S||!S.startsWith("data: "))continue;let _=!1;if(S==="data: [DONE]")_=!0;else try{let E=JSON.parse(S.substring(6)),x=E.choices?.[0]?.delta,C=E.usage;if(E.choices?.[0]?.finish_reason&&(_=!0),C&&(m={totalTokenCount:C.total_tokens||(C.prompt_tokens||0)+(C.completion_tokens||0),promptTokenCount:C.prompt_tokens||0,candidatesTokenCount:C.completion_tokens||0,cachedContentTokenCount:C.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:C.completion_tokens_details?.reasoning_tokens||C.reasoning_tokens||0},b=!0),x){let I=x.reasoning_content||null;I&&(y.push({text:I,thought:!0}),b=!0),x.content&&(y.push({text:x.content}),b=!0)}}catch{}if((_||Date.now()-w>=150)&&b&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),b=!1),_)break}Date.now()-w>=150&&b&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),b=!1)}},ii=async function*(e,n,t,o,s,r,a,i,p=1){let d=[];o&&d.push({role:"system",content:o});for(let T of t){let $=T.role==="user"?"user":"assistant",R="";if(Array.isArray(T.parts))for(let k of T.parts)k.text&&(R+=(R?`
514
+ `:"")+k.text);else R=T.text||"";d.push({role:$,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:p};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 T=await f.json().catch(()=>({}));throw new Error(`InferX Error (${f.status}): ${T.error?.message||f.statusText||String(T)}`)}let u=f.body.getReader(),h=new TextDecoder,g="",y=[],m=null,w=Date.now(),b=!1;for(;;){let{done:T,value:$}=await u.read();if(T){b&&(y.length>0||m)&&(yield{candidates:y.length>0?[{content:{parts:y}}]:[],usageMetadata:m});break}g+=h.decode($,{stream:!0});let R=g.split(`
515
+ `);g=R.pop();for(let k of R){let S=k.trim();if(!S||!S.startsWith("data: "))continue;let _=!1;if(S==="data: [DONE]")_=!0;else try{let E=JSON.parse(S.substring(6)),x=E.choices?.[0]?.delta,C=E.usage;if(C&&(m={totalTokenCount:C.total_tokens||(C.prompt_tokens||0)+(C.completion_tokens||0),promptTokenCount:C.prompt_tokens||0,candidatesTokenCount:C.completion_tokens||0,cachedContentTokenCount:C.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:C.completion_tokens_details?.reasoning_tokens||C.reasoning_tokens||0},b=!0),x){let I=x.reasoning||x.reasoning_content||null;I&&(y.push({text:I,thought:!0}),b=!0),x.content&&(y.push({text:x.content}),b=!0)}}catch{}if((_||Date.now()-w>=150||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,p=1){let d=[];o&&d.push({role:"system",content:o});for(let T of t){let $=T.role==="user"?"user":"assistant",R=[];if(Array.isArray(T.parts)){for(let k of T.parts)if(k.text)R.push({type:"text",text:k.text});else if(k.inlineData&&a){let S=k.inlineData.mimeType,_=k.inlineData.data;S.startsWith("image/")&&R.push({type:"image_url",image_url:{url:`data:${S};base64,${_}`}})}}else{let k=T.text||"";k&&R.push({type:"text",text:k})}d.push({role:$,content:R.length===1&&R[0].type==="text"?R[0].text:R})}let c={Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},l={model:n,messages:d,stream:!0,stream_options:{include_usage:!0},temperature:p};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 T=await f.json().catch(()=>({}));throw new Error(`SenseNova Error (${f.status}): ${T.error?.message||f.statusText}`)}let u=f.body.getReader(),h=new TextDecoder,g="",y=[],m=null,w=Date.now(),b=!1;for(;;){let{done:T,value:$}=await u.read();if(T){b&&(y.length>0||m)&&(yield{candidates:y.length>0?[{content:{parts:y}}]:[],usageMetadata:m});break}g+=h.decode($,{stream:!0});let R=g.split(`
516
+ `);g=R.pop();for(let k of R){let S=k.trim();if(!S||!S.startsWith("data: "))continue;let _=!1;if(S==="data: [DONE]")_=!0;else try{let E=JSON.parse(S.substring(6)),x=E.choices?.[0]?.delta,C=E.usage;if(C&&(m={totalTokenCount:C.total_tokens||(C.prompt_tokens||0)+(C.completion_tokens||0),promptTokenCount:C.prompt_tokens||0,candidatesTokenCount:C.completion_tokens||0,cachedContentTokenCount:C.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:C.completion_tokens_details?.reasoning_tokens||C.reasoning_tokens||0},b=!0),x){let I=x.reasoning||x.reasoning_content||null;I&&(y.push({text:I,thought:!0}),b=!0),x.content&&(y.push({text:x.content}),b=!0)}}catch{}if((_||Date.now()-w>=150||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)}},_m=()=>{Lt=!0},$m=()=>Lt,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?ee.basename(s.replace(/["']/g,"").replace(/\\/g,"/")):null}catch{return null}},li=e=>e?new Ia({apiKey:e}):ei,Cm=async(e,n,t,o,s={})=>{let{onStatus:i,onMemoryUpdated:p,onBackgroundIncrement:d}=s,{profile:c,thinkingLevel:l,mode:f,janitorModel:u,chatId:h,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,$=Z(Dt,[]).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 B=Cc(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,(Fe,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
- `).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=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
- ... (truncated) ...`);let P=n.replace(/\[Prompted on:.*?\]/g,"").trim();I=I.replace(/\r?\n\r?\n/g,`
519
+ `).replace(/\\n\\n/g,"").trim(),V=A.role==="user"?8192:32768,J=B.substring(0,V);B.length>V&&(J+=`
520
+ ... (truncated) ...`);let Ue=A.role==="user"?J.startsWith("[USER]")?"":"[USER]: ":J.startsWith("[AGENT]")?"":"[AGENT]: ";return{role:A.role==="user"?"user":"model",parts:[{text:`${Ue}${J}`}]}}),k=o.filter(A=>A.role==="user").length===1,S=n.includes("[TITLE-UPDATE]"),_=Math.random()<.8,E=k||S||_,x=t.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").trim(),C=Ci($,b,E),I=`${x.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
+ ... (truncated) ...`);let L=n.replace(/\[Prompted on:.*?\]/g,"").trim();I=I.replace(/\r?\n\r?\n/g,`
522
522
  `).replace(/\n\n/g,`
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})}`}
523
+ `).replace(/\\n\\n/g,"").trim();let N=new Date,X=`[METADATA] Current date and Time: ${`${N.getFullYear()}-${N.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(N.getDate()).padStart(2,"0")}, ${N.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0})}`}
524
524
 
525
- [USER]: ${P.substring(0,8192)}
526
- ${P.length>8192?`... (truncated) ...
525
+ [USER]: ${L.substring(0,8192)}
526
+ ${L.length>8192?`... (truncated) ...
527
527
 
528
528
  `:""}
529
- [AGENT (current turn)]: ${I}`;R.push({role:"user",parts:[{text:Y}]});let se=await Qo("NVIDIA"),U=(await Ft()).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((ut,$e)=>setTimeout(()=>$e(new Error("JANITOR_TIMEOUT")),1e4)),it=m==="Google"&&ae>=0&&ae<6&&se&&U,ze=m==="DeepSeek"&&ae<4&&se&&U;V=it||ze,X=V?"NVIDIA":m;let gt=(async()=>{if(m==="OpenRouter"){let ut=ve("janitor_open_router"),ie=oi(w,ut,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=ti(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=ni(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=si(V?se: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=ri(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=ii(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=ai(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 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:ft.MINIMAL}}}))[Symbol.asyncIterator](),Vt=await ie.next();return{iterator:ie,firstResult:Vt}}})();if(process.stdout.isTTY){let ie=(await as())[h]?.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:yt}=await Promise.race([gt,je]),{value:wt,done:Rt}=yt;if(!Rt&&wt){let ut=wt.candidates?.[0]?.content?.parts,$e=ut?X==="Google"?ut[1]?.text||ut[0]?.text||"":ut.filter(ie=>ie.text&&!ie.thought).map(ie=>ie.text).join(""):typeof wt.text=="function"?wt.text():"";$e&&(A+=$e),F=wt.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,it=F.cachedContentTokenCount||0,ze=(F.candidatesTokenCount||0)+(F.thoughtsTokenCount||0),gt=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,gt),it>0&&await Kt("cachedTokens",it,X,gt),ze>0&&await Kt("candidateTokens",ze,X,gt)}}else throw new Error("No synthesis generated by Janitor.");d&&(d(),await Ot("background"));let Ue=Ho(j),Fe=!1;for(let je of Ue){let it=je.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(it)&&(Fe=!0);let ze={chatId:h,sessionId:h,history:o},gt=await fo(it,je.args,ze);it.toLowerCase()==="memory"&&(je.args.includes("action='user'")||je.args.includes('action="user"'))&&!gt.startsWith("ERROR")&&(p&&p(),process.stdout.isTTY&&(process.stdout.write("\x1B]0;Memory Updated\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=Memory Updated\x07")),await new Promise(yt=>setTimeout(yt,3e3)))}if(!Fe)try{let je=Q(Dt,[]);if(je.length>0){let it=[];for(let ze of je)ze.score===void 0&&(ze.score=.5),ze.score*=.99995,ze.score<.05&&(ze.score=0),ze.score=Math.round(ze.score*1e5)/1e5,ze.score>0&&it.push(ze);pe(Dt,it)}}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(Fe=>setTimeout(Fe,1e3));let X=Z.join(fn,"janitor");if(Pe.existsSync(X)||Pe.mkdirSync(X,{recursive:!0}),Pe.appendFileSync(Z.join(X,"error.log"),`ERROR [Attempt ${ae}/${_e+1}] [${F}]: ${V}
529
+ [AGENT (current turn)]: ${I}`;R.push({role:"user",parts:[{text:X}]});let re=await Qo("NVIDIA"),F=(await Ft()).quotas?.providerTiers?.NVIDIA==="Free",U="",se=0,$e=b?12:-1;for(;se<=$e;)try{if(!await Li("background",e))return;let A="",B=null,V=!1,J=m;try{let je=new Promise((ut,Ce)=>setTimeout(()=>Ce(new Error("JANITOR_TIMEOUT")),1e4)),it=m==="Google"&&se>=0&&se<6&&re&&F,ze=m==="DeepSeek"&&se<4&&re&&F;V=it||ze,J=V?"NVIDIA":m;let gt=(async()=>{if(m==="OpenRouter"){let ut=Ie("janitor_open_router"),le=oi(w,ut,R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),Vt=await le.next();return{iterator:le,firstResult:Vt}}else if(m==="DeepSeek"&&!V){let Ce=ti(w,Ie("deepseek_fast_fallback"),R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await Ce.next();return{iterator:Ce,firstResult:le}}else if(m==="Mistral"&&!V){let Ce=ni(w,Ie("mistral_janitor_fallback"),R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await Ce.next();return{iterator:Ce,firstResult:le}}else if(m==="NVIDIA"||V){let Ce=si(V?re:w,Ie("nvidia_janitor_fallback"),R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await Ce.next();return{iterator:Ce,firstResult:le}}else if(m==="CrofAI"){let Ce=ri(w,targetModel||Ie("crofai_fallback")||"deepseek-v4-flash-0731",R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await Ce.next();return{iterator:Ce,firstResult:le}}else if(m==="InferX"){let Ce=ii(w,targetModel||Ie("inferx_fallback")||"deepseek-v4-flash",R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await Ce.next();return{iterator:Ce,firstResult:le}}else if(m==="SenseNova"){let Ce=ai(w,targetModel||Ie("sensenova_fallback")||"sensenova-6.8-flash-lite",R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await Ce.next();return{iterator:Ce,firstResult:le}}else{let le=(await li(w).models.generateContentStream({model:u||(se===$e?Ie("janitor_default"):Ie("gemma_janitor_fallback_google")),contents:R,config:{systemInstruction:C,temperature:.7,safetySettings:[{category:Vn.HARM_CATEGORY_HARASSMENT,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_HATE_SPEECH,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Yn.BLOCK_NONE}],thinkingConfig:{includeThoughts:!1,thinkingLevel:ft.MINIMAL}}}))[Symbol.asyncIterator](),Vt=await le.next();return{iterator:le,firstResult:Vt}}})();if(process.stdout.isTTY){let le=(await as())[h]?.name||"",Vt=le&&!le.startsWith("flow-")&&!le.startsWith("Session ")?le:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${Vt}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${Vt}\x07`)}let{iterator:Bt,firstResult:yt}=await Promise.race([gt,je]),{value:wt,done:Rt}=yt;if(!Rt&&wt){let ut=wt.candidates?.[0]?.content?.parts,Ce=ut?J==="Google"?ut[1]?.text||ut[0]?.text||"":ut.filter(le=>le.text&&!le.thought).map(le=>le.text).join(""):typeof wt.text=="function"?wt.text():"";Ce&&(A+=Ce),B=wt.usageMetadata;for await(let le of{[Symbol.asyncIterator]:()=>Bt}){let Vt=le.candidates?.[0]?.content?.parts,Xn=Vt?J==="Google"?Vt[1]?.text||Vt[0]?.text||"":Vt.filter(Jn=>Jn.text&&!Jn.thought).map(Jn=>Jn.text).join(""):typeof le.text=="function"?le.text():"";Xn&&(A+=Xn),B=le.usageMetadata}}}catch(je){throw je}if(A){if(U=A,B){let je=B.totalTokenCount||0,it=B.cachedContentTokenCount||0,ze=(B.candidatesTokenCount||0)+(B.thoughtsTokenCount||0),gt=V?Ie("nvidia_janitor_fallback"):J==="DeepSeek"?Ie("deepseek_fast_fallback"):J==="OpenRouter"?Ie("janitor_open_router"):u||(se===$e?Ie("janitor_default"):Ie("gemma_janitor_fallback_google"));await Kt("tokens",je,J,gt),it>0&&await Kt("cachedTokens",it,J,gt),ze>0&&await Kt("candidateTokens",ze,J,gt)}}else throw new Error("No synthesis generated by Janitor.");d&&(d(),await Ot("background"));let Ue=Ho(U),Fe=!1;for(let je of Ue){let it=je.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(it)&&(Fe=!0);let ze={chatId:h,sessionId:h,history:o},gt=await fo(it,je.args,ze);it.toLowerCase()==="memory"&&(je.args.includes("action='user'")||je.args.includes('action="user"'))&&!gt.startsWith("ERROR")&&(p&&p(),process.stdout.isTTY&&(process.stdout.write("\x1B]0;Memory Updated\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=Memory Updated\x07")),await new Promise(yt=>setTimeout(yt,3e3)))}if(!Fe)try{let je=Z(Dt,[]);if(je.length>0){let it=[];for(let ze of je)ze.score===void 0&&(ze.score=.5),ze.score*=.99995,ze.score<.05&&(ze.score=0),ze.score=Math.round(ze.score*1e5)/1e5,ze.score>0&&it.push(ze);me(Dt,it)}}catch{}break}catch(A){se++;let B=new Date().toLocaleString(),V=A instanceof Error?(()=>{try{return JSON.parse(JSON.parse(A.message).error.message).error.message}catch{return String(A)}})():String(A);await new Promise(Fe=>setTimeout(Fe,1e3));let J=ee.join(fn,"janitor");if(Pe.existsSync(J)||Pe.mkdirSync(J,{recursive:!0}),Pe.appendFileSync(ee.join(J,"error.log"),`ERROR [Attempt ${se}/${$e+1}] [${B}]: ${V}
530
530
 
531
- `),ae>_e)break;let Ue=Math.min(750*Math.pow(2,ae-1),5e3);await new Promise(Fe=>setTimeout(Fe,Ue))}if(ae){let A=Z.join(fn,"janitor");Pe.appendFileSync(Z.join(A,"error.log"),`-----------------------------------------------------------------------------
531
+ `),se>$e)break;let Ue=Math.min(750*Math.pow(2,se-1),5e3);await new Promise(Fe=>setTimeout(Fe,Ue))}if(se){let A=ee.join(fn,"janitor");Pe.appendFileSync(ee.join(A,"error.log"),`-----------------------------------------------------------------------------
532
532
 
533
- `)}if(process.stdout.isTTY)try{let V=(await as())[h]?.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")}},Mc=e=>{let n=e.replace(kc,"").replace(Sc,""),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,p=!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]==="]"){p=!0,ho.lastIndex=l+1;break}}c==="\\"?i=!i:i=!1}if(!p)return{inside:!0,toolName:o[1],startIndex:o.index,args:n.substring(o.index+o[0].length)}}return{inside:!1}},Da=(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,p=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 h=l-1;h>=0&&e[h]==="\\";h--)u++;u%2===0&&(d=null)}}else if(f==='"'||f==="'"||f==="`")d=f;else if(f==="(")p++;else if(f===")"&&(p--,p===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},Ac=(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 p=a.index+a[0].length-1,d=0,c=null,l=-1;for(let f=p;f<e.length;f++){let u=e[f];if(c){if(u===c){let h=0;for(let g=f-1;g>=0&&e[g]==="\\";g--)h++;h%2===0&&(c=null)}}else if(u==='"'||u==="'"||u==="`")c=u;else if(u==="(")d++;else if(u===")"&&(d--,d===0)){let h=f+1;for(;h<e.length&&/\s/.test(e[h]);)h++;if(h<e.length&&e[h]==="]"){l=h;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=>Da(e,!0),vc=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 h=typeof u=="string"?u:JSON.stringify(u);return`${f}=${JSON.stringify(h)}`}).join(", "))}catch{let l=[],f=Tc;f.lastIndex=0;let u;for(;(u=f.exec(a))!==null;){let h=u[1],g=u[2]!==void 0?u[2]:u[0].split(":").slice(1).join(":").trim();l.push(`${h}=${JSON.stringify(g)}`)}l.length>0?i=l.join(", "):i=a.trim()}let p=r.toLowerCase().replace(/_/g,"");return`[tool:functions.${n[p]||t(r)}(${i})]`});return $a.lastIndex=0,Ca.lastIndex=0,o=o.replace($a,""),o=o.replace(Ca,""),o},Ic=/(?:path|query|url|keyword|command|method|title|task|id)\s*=\s*['"`]?\s*\.\.\.\s*['"`]?/i,Oc=/^['"`]?\s*\.\.\.\s*['"`]?$/,Ln=e=>{if(e==null)return!1;let n=String(e).trim();return n==="..."||n==="\u2026"||Oc.test(n)},Ho=e=>{if(!e)return[];let n=vc(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=yc;r.lastIndex=0;let a;for(;(a=r.exec(s))!==null;){let i=a[1],p=a.index+a[0].length-1,d=0,c=null,l=-1,f=-1;for(let u=p;u<s.length;u++){let h=t[u];if(c){if(h===c){let g=0;for(let y=u-1;y>=0&&t[y]==="\\";y--)g++;g%2===0&&(c=null)}}else if(h==='"'||h==="'"||h==="`")c=h;else if(h==="(")d++;else if(h===")"&&(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(p+1,f),h=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)||Ic.test(u)||o.push({fullMatch:h,toolName:i.trim(),args:u.trim()}),r.lastIndex=l+1}}return o},Cm=(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")=>Ec(async()=>{let{aiProvider:i="Google",apiKey:p,mode:d}=e,c="",l=null,f=typeof t=="string"?[{role:"user",parts:[{text:t}]}]:t,u=new AbortController,h=u.signal,g=setInterval(()=>{Lt&&(u.abort(),clearInterval(g))},100);try{let y;i==="Ollama"?y=Pa(p,n,f,o,s,d,zt(n),h,r,systemSettings?.ollamaEndpoint||"Cloud"):i==="OpenRouter"?y=oi(p,n,f,o,s,d,zt(n),h,r):i==="DeepSeek"?y=ti(p,n,f,o,s,d,zt(n),h,r):i==="Mistral"?y=ni(p,n,f,o,s,d,zt(n),h,r):i==="NVIDIA"?y=si(p,n,f,o,s,d,zt(n),h,r):i==="CrofAI"?y=ri(p,n,f,o,s,d,zt(n),h,r):i==="InferX"?y=ii(p,n,f,o,s,d,zt(n),h,r):i==="SenseNova"?y=ai(p,n,f,o,s,d,zt(n),h,r):y=await li(p).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:ft.MINIMAL}:{includeThoughts:!0,thinkingLevel:ft.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:b.includes("pro")?ft.LOW:ft.MINIMAL,Low:ft.LOW,Medium:ft.MEDIUM,Standard:ft.MEDIUM,High:ft.HIGH,xHigh:ft.HIGH}[s]||ft.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:h});for await(let m of y){if(Lt)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 Ot("agent",i),{text:c,usageMetadata:l}}),Lc=async(e,n,t=null)=>{t=t||Q(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.
533
+ `)}if(process.stdout.isTTY)try{let V=(await as())[h]?.name||"",J=V&&!V.startsWith("flow-")&&!V.startsWith("Session ")?V:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${J}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${J}\x07`)}catch{process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")}},Ac=e=>{let n=e.replace(Sc,"").replace(Tc,""),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,p=!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]==="]"){p=!0,ho.lastIndex=l+1;break}}c==="\\"?i=!i:i=!1}if(!p)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=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,p=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 h=l-1;h>=0&&e[h]==="\\";h--)u++;u%2===0&&(d=null)}}else if(f==='"'||f==="'"||f==="`")d=f;else if(f==="(")p++;else if(f===")"&&(p--,p===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},vc=(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 p=a.index+a[0].length-1,d=0,c=null,l=-1;for(let f=p;f<e.length;f++){let u=e[f];if(c){if(u===c){let h=0;for(let g=f-1;g>=0&&e[g]==="\\";g--)h++;h%2===0&&(c=null)}}else if(u==='"'||u==="'"||u==="`")c=u;else if(u==="(")d++;else if(u===")"&&(d--,d===0)){let h=f+1;for(;h<e.length&&/\s/.test(e[h]);)h++;if(h<e.length&&e[h]==="]"){l=h;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=>Fa(e,!0),Ic=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 h=typeof u=="string"?u:JSON.stringify(u);return`${f}=${JSON.stringify(h)}`}).join(", "))}catch{let l=[],f=Rc;f.lastIndex=0;let u;for(;(u=f.exec(a))!==null;){let h=u[1],g=u[2]!==void 0?u[2]:u[0].split(":").slice(1).join(":").trim();l.push(`${h}=${JSON.stringify(g)}`)}l.length>0?i=l.join(", "):i=a.trim()}let p=r.toLowerCase().replace(/_/g,"");return`[tool:functions.${n[p]||t(r)}(${i})]`});return $a.lastIndex=0,Ca.lastIndex=0,o=o.replace($a,""),o=o.replace(Ca,""),o},Oc=/(?:path|query|url|keyword|command|method|title|task|id)\s*=\s*['"`]?\s*\.\.\.\s*['"`]?/i,Lc=/^['"`]?\s*\.\.\.\s*['"`]?$/,Ln=e=>{if(e==null)return!1;let n=String(e).trim();return n==="..."||n==="\u2026"||Lc.test(n)},Ho=e=>{if(!e)return[];let n=Ic(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=wc;r.lastIndex=0;let a;for(;(a=r.exec(s))!==null;){let i=a[1],p=a.index+a[0].length-1,d=0,c=null,l=-1,f=-1;for(let u=p;u<s.length;u++){let h=t[u];if(c){if(h===c){let g=0;for(let y=u-1;y>=0&&t[y]==="\\";y--)g++;g%2===0&&(c=null)}}else if(h==='"'||h==="'"||h==="`")c=h;else if(h==="(")d++;else if(h===")"&&(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(p+1,f),h=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)||Oc.test(u)||o.push({fullMatch:h,toolName:i.trim(),args:u.trim()}),r.lastIndex=l+1}}return o},Mm=(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")=>_c(async()=>{let{aiProvider:i="Google",apiKey:p,mode:d}=e,c="",l=null,f=typeof t=="string"?[{role:"user",parts:[{text:t}]}]:t,u=new AbortController,h=u.signal,g=setInterval(()=>{Lt&&(u.abort(),clearInterval(g))},100);try{let y;i==="Ollama"?y=Da(p,n,f,o,s,d,zt(n),h,r,systemSettings?.ollamaEndpoint||"Cloud"):i==="OpenRouter"?y=oi(p,n,f,o,s,d,zt(n),h,r):i==="DeepSeek"?y=ti(p,n,f,o,s,d,zt(n),h,r):i==="Mistral"?y=ni(p,n,f,o,s,d,zt(n),h,r):i==="NVIDIA"?y=si(p,n,f,o,s,d,zt(n),h,r):i==="CrofAI"?y=ri(p,n,f,o,s,d,zt(n),h,r):i==="InferX"?y=ii(p,n,f,o,s,d,zt(n),h,r):i==="SenseNova"?y=ai(p,n,f,o,s,d,zt(n),h,r):y=await li(p).models.generateContentStream({model:n,contents:f,config:{systemInstruction:o,temperature:r,thinkingConfig:(()=>{let b=(n||"").toLowerCase(),T=b.includes("gemma-4")||b.startsWith("gemma"),$=b.includes("gemini-3");if(T||$)return T?s.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:ft.MINIMAL}:{includeThoughts:!0,thinkingLevel:ft.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:b.includes("pro")?ft.LOW:ft.MINIMAL,Low:ft.LOW,Medium:ft.MEDIUM,Standard:ft.MEDIUM,High:ft.HIGH,xHigh:ft.HIGH}[s]||ft.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:h});for await(let m of y){if(Lt)throw new Error("Subagent task was cancelled.");if(e?.taskId&&typeof Xe<"u"){let T=Xe.find($=>$.id===e.taskId);if(T&&T.status==="cancelled")throw new Error("Subagent task was cancelled.")}let w="";if(m.candidates?.[0]?.content?.parts)for(let T of m.candidates[0].content.parts)T.text&&!T.thought&&(c+=T.text,w+=T.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 Ot("agent",i),{text:c,usageMetadata:l}}),Pc=async(e,n,t=null)=>{t=t||Z(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,7 +545,7 @@ Guidelines:
545
545
 
546
546
  Chats to process:
547
547
 
548
- `,i=Q(An,{});for(let f of r){let h=t[f].map(y=>`- ${y}`).join(`
548
+ `,i=Z(An,{});for(let f of r){let h=t[f].map(y=>`- ${y}`).join(`
549
549
  `),g=i[f];a+=`[Chat ID: ${f}]
550
550
  `,g?(a+=`- Existing Summary: "${g}"
551
551
  `,a+=`
@@ -555,8 +555,8 @@ ${h}
555
555
  `):a+=`-- Individual Memories:
556
556
  ${h}
557
557
 
558
- `}let p=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"));p<=d&&!c;){p++;try{let u=(await jo(n,l,a,null,"Fast",.75,"background")).text||"",h=Ho(u);if(h.length===0)throw new Error("No tool calls detected in synthesis response");for(let g of h){let y=g.toolName;["saveSummary","saveSumary","SaveSummary","SaveSumary"].includes(y)&&await fo(y,g.args,{chatId:e})}c=!0}catch(f){if(p>=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=Z.join(fn,"janitor");Pe.existsSync(r)||Pe.mkdirSync(r,{recursive:!0}),Pe.appendFileSync(Z.join(r,"error.log"),`[${new Date().toLocaleString()}] Past memory batch consolidation error: ${s}
559
- `)}},Pc=async(e,n,t=!1)=>{let{chatId:o,aiProvider:s="Google"}=e,r=Z.join(xo,"chat-summaries.json"),a=u=>u.filter(h=>(h.role==="user"||h.role==="agent"||h.role==="system")&&h.role!=="think"&&!h.isVisualFeedback&&!h.isMeta&&!h.isTerminalRecord&&!(h.text&&h.text.includes("[TERMINAL_RECORD]"))&&!String(h.id).startsWith("welcome")).map(h=>{let g=h.fullText||h.text||"",y=h.role==="system"||g.startsWith("[TOOL RESULT]:")||h.text&&h.text.startsWith("[TOOL RESULT]:"),m=g;return y&&(g.includes("[TOOL RESULT]:")||h.text&&h.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":h.role==="agent"?"AGENT":"USER"}]: ${m}`}).join(`
558
+ `}let p=0,d=5,c=!1,l=Ie("gemma_janitor_fallback_google");for(o==="OpenRouter"&&(l=Ie("janitor_open_router")),o==="DeepSeek"&&(l=Ie("deepseek_level_1")),o==="Mistral"&&(l=Ie("mistral_level_1")),o==="NVIDIA"&&(l=Ie("nvidia_janitor_fallback")),o==="CrofAI"&&(l=Ie("crofai_fallback")),o==="InferX"&&(l=Ie("inferx_fallback")),o==="SenseNova"&&(l=Ie("sensenova_fallback"));p<=d&&!c;){p++;try{let u=(await jo(n,l,a,null,"Fast",.75,"background")).text||"",h=Ho(u);if(h.length===0)throw new Error("No tool calls detected in synthesis response");for(let g of h){let y=g.toolName;["saveSummary","saveSumary","SaveSummary","SaveSumary"].includes(y)&&await fo(y,g.args,{chatId:e})}c=!0}catch(f){if(p>=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=ee.join(fn,"janitor");Pe.existsSync(r)||Pe.mkdirSync(r,{recursive:!0}),Pe.appendFileSync(ee.join(r,"error.log"),`[${new Date().toLocaleString()}] Past memory batch consolidation error: ${s}
559
+ `)}},Dc=async(e,n,t=!1)=>{let{chatId:o,aiProvider:s="Google"}=e,r=ee.join(xo,"chat-summaries.json"),a=u=>u.filter(h=>(h.role==="user"||h.role==="agent"||h.role==="system")&&h.role!=="think"&&!h.isVisualFeedback&&!h.isMeta&&!h.isTerminalRecord&&!(h.text&&h.text.includes("[TERMINAL_RECORD]"))&&!String(h.id).startsWith("welcome")).map(h=>{let g=h.fullText||h.text||"",y=h.role==="system"||g.startsWith("[TOOL RESULT]:")||h.text&&h.text.startsWith("[TOOL RESULT]:"),m=g;return y&&(g.includes("[TOOL RESULT]:")||h.text&&h.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":h.role==="agent"?"AGENT":"USER"}]: ${m}`}).join(`
560
560
 
561
561
  `),i=async(u,h)=>{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=h?`Here is the previous summary:
562
562
  ${h}
@@ -567,106 +567,106 @@ ${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,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||""},p=a(n),d=Q(r,{}),c=d[o]||{summary:"",historyLength:0};typeof c=="string"&&(c={summary:c,historyLength:0});let l=c.summary||"",f=await i(p,l);if(f){c.summary=f;let u=_c(n);return t?c.historyLength=(c.historyLength||0)+u:c.historyLength=u,d[o]=c,pe(r,d),f}return null},Mm=e=>{try{let n=Z.join(xo,"chat-summaries.json");if(Pe.existsSync(n)){let t=Q(n,{});t[e]&&(delete t[e],pe(n,t))}}catch{}},Am=async function*(e,n,t,o,s){let{profile:r,thinkingLevel:a,mode:i,janitorModel:p,chatId:d,isPlayground:c,systemSettings:l,sessionStats:f,aiProvider:u="Google",apiTier:h,wildcardTooling:g}=t,y=zt(e);if(!ei&&u==="Google")throw new Error("AI not initialized");let m=process.env.NVIDIA_BASE_URL||t?.aiProvider==="Ollama"||t?.aiProvider==="CrofAI"||t?.aiProvider==="InferX"||t?.aiProvider==="SenseNova"?!1:l?.memory!==!1,w=n[n.length-1].text,b=Z.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 mt.startTransaction(d,T),l?.advanceRollback&&await Kn.takeInitialSnapshot(d),Lt=!1;let $=null;try{let _=new AbortController;$=setInterval(()=>{Lt&&(_.abort(),$&&(clearInterval($),$=null))},400);let k=[...n.slice(0,-1)];{let Le=Q(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(G=>{if(G.role==="user"&&G.text){let Le=G.text.match(/\[USER\]([\s\S]*?)\[\/USER\]/);if(Le)return{...G,text:Le[1].trim()}}return{...G}});let C=process.env.HIGH_CONTEXT,I=255e3,P=26e4;if(C&&C!=="false"){let G=parseInt(C,10);!isNaN(G)&&G>=256e3&&G<=1e6&&(P=G,I=Math.round(G*.85))}if((u==="NVIDIA"&&(e?.includes("gpt")||e?.includes("qwen")||e?.includes("medium")||e.includes("muse"))||u==="Mistral")&&(I=122e3,P=126e3),u!=="Ollama"&&(f?.tokens||0)>I&&(yield{type:"status_history",content:"Context Limit Reached. Condensing session history..."},await Pc(t,k,!0)&&(k=[],x=!0)),E&&m){let G=Q(tn,{});Object.values(G).flat().length>5&&(yield{type:"status",content:"Condensing past chat memories"},await Lc(d,t,G))}let B=Q(tn,{}),N=Q(An,{}),Y=Object.entries(B).filter(([G])=>G!==d).flatMap(([G,Le])=>Le),Ie=[...Object.entries(N).filter(([G])=>G!==d).slice(-20).map(([G,Le])=>`[Chat Summary]: ${Le}`),...Y].map(G=>`- ${G}`).join(`
571
- `),j=Q(Dt,[]).map(G=>`- ${G.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}),Fe=`${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"],it=G=>{try{return Pe.readdirSync(G,{withFileTypes:!0})}catch{return[]}},ze=(G,Le={value:0},nn=1)=>{if(Le.value>6200||nn>7)return Le.value;let Ce=it(G);for(let Ze of Ce){if(Le.value>6200)break;je.includes(Ze.name)||Ze.name.startsWith(".")||Ze.isDirectory()&&(Le.value++,ze(Z.join(G,Ze.name),Le,nn+1))}return Le.value},gt=(G,Le)=>l?.indentationTree!==!1?Vr(G,Le,1,it,je):Jr(G,Le,"",1,it,je),Bt=ze(process.cwd()),yt=12;Bt>3072?yt=1:Bt>2304?yt=2:Bt>1536?yt=3:Bt>768?yt=4:Bt>384?yt=6:Bt>192?yt=7:Bt>96?yt=8:Bt>48?yt=9:Bt>24&&(yt=10);let wt=Q(Jo,{}),Rt=wt[d],ut=Rt?Rt!==process.cwd():!1;wt[d]=process.cwd(),pe(Jo,wt);let $e=Q(b,{}),ie=$e[d]||{summary:"",historyLength:0};typeof ie=="string"&&(ie={summary:ie,historyLength:0});let Vt=n.filter(G=>(G.role==="user"||G.role==="agent"||G.role==="system")&&!String(G.id).startsWith("welcome")&&!G.isMeta).length;ie.historyLength&&Vt<ie.historyLength&&(ie.summary="",ie.historyLength=0,$e[d]=ie,pe(b,$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=Ie("gemma_janitor_fallback_google");s==="OpenRouter"&&(m=Ie("janitor_open_router")),s==="DeepSeek"&&(m=Ie("deepseek_level_1")),s==="Mistral"&&(m=Ie("mistral_level_1")),s==="NVIDIA"&&(m=Ie("nvidia_chat_summarizer_fallback")),s==="CrofAI"&&(m=Ie("crofai_fallback")),s==="InferX"&&(m=Ie("inferx_fallback")),s==="SenseNova"&&(m=Ie("sensenova_fallback"));let w=0,b=!1,T=null;for(;w<=3&&!b;){w++;try{T=await jo(e,m,y,g,"Fast"),b=!0}catch{if(w>3){if(s==="Google")try{let R=Ie("general_fallback");return(await jo(e,R,y,g,"Fast")).text||""}catch{return""}return""}}}return T&&T.text||""},p=a(n),d=Z(r,{}),c=d[o]||{summary:"",historyLength:0};typeof c=="string"&&(c={summary:c,historyLength:0});let l=c.summary||"",f=await i(p,l);if(f){c.summary=f;let u=$c(n);return t?c.historyLength=(c.historyLength||0)+u:c.historyLength=u,d[o]=c,me(r,d),f}return null},Am=e=>{try{let n=ee.join(xo,"chat-summaries.json");if(Pe.existsSync(n)){let t=Z(n,{});t[e]&&(delete t[e],me(n,t))}}catch{}},vm=async function*(e,n,t,o,s){let{profile:r,thinkingLevel:a,mode:i,janitorModel:p,chatId:d,isPlayground:c,systemSettings:l,sessionStats:f,aiProvider:u="Google",apiTier:h,wildcardTooling:g}=t,y=zt(e);if(!ei&&u==="Google")throw new Error("AI not initialized");let m=process.env.NVIDIA_BASE_URL||t?.aiProvider==="Ollama"||t?.aiProvider==="CrofAI"||t?.aiProvider==="InferX"||t?.aiProvider==="SenseNova"?!1:l?.memory!==!1,w=n[n.length-1].text,b=ee.join(xo,"chat-summaries.json"),T=!1,$=n.filter(E=>E.role==="user").length===1,R=w.includes("[TITLE-UPDATE]"),k=$||R,S=w.replace(/\[TITLE-UPDATE\]/g,"").trim();S=S.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),yield{type:"status",content:"[start]"},yield{type:"status",content:"Gathering Context"},await mt.startTransaction(d,S),l?.advanceRollback&&await Kn.takeInitialSnapshot(d),Lt=!1;let _=null;try{let E=new AbortController;_=setInterval(()=>{Lt&&(E.abort(),_&&(clearInterval(_),_=null))},400);let x=[...n.slice(0,-1)];{let Le=Z(b,{})[d]||{summary:"",historyLength:0};if(Le.summary&&Le.historyLength>0){let nn=0,Me=[];for(let Ze=0;Ze<x.length;Ze++){let He=x[Ze];(He.role==="user"||He.role==="agent"||He.role==="system")&&!String(He.id).startsWith("welcome")&&!He.isMeta&&nn++,nn>Le.historyLength&&Me.push(He)}x=Me}}x=x.map(G=>{if(G.role==="user"&&G.text){let Le=G.text.match(/\[USER\]([\s\S]*?)\[\/USER\]/);if(Le)return{...G,text:Le[1].trim()}}return{...G}});let C=process.env.HIGH_CONTEXT,I=255e3,L=26e4;if(C&&C!=="false"){let G=parseInt(C,10);!isNaN(G)&&G>=256e3&&G<=1e6&&(L=G,I=Math.round(G*.85))}if((u==="NVIDIA"&&(e?.includes("gpt")||e?.includes("qwen")||e?.includes("medium")||e.includes("muse"))||u==="Mistral")&&(I=122e3,L=126e3),u!=="Ollama"&&(f?.tokens||0)>I&&(yield{type:"status_history",content:"Context Limit Reached. Condensing session history..."},await Dc(t,x,!0)&&(x=[],T=!0)),$&&m){let G=Z(tn,{});Object.values(G).flat().length>5&&(yield{type:"status",content:"Condensing past chat memories"},await Pc(d,t,G))}let N=Z(tn,{}),W=Z(An,{}),X=Object.entries(N).filter(([G])=>G!==d).flatMap(([G,Le])=>Le),Y=[...Object.entries(W).filter(([G])=>G!==d).slice(-20).map(([G,Le])=>`[Chat Summary]: ${Le}`),...X].map(G=>`- ${G}`).join(`
571
+ `),U=Z(Dt,[]).map(G=>`- ${G.memory}`).join(`
572
+ `),se=(f?.tokens||0)>=1e4,$e=_i(Y,U,m,se),A=new Date,B=A.getFullYear(),V=A.toLocaleString("en-US",{month:"short"}).toUpperCase(),J=String(A.getDate()).padStart(2,"0"),Ue=A.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}),Fe=`${B}-${V}-${J}, ${Ue}`,je=[".git","node_modules",".gemini","dist","build",".next","out",".cache","bin","obj","vendor","venv",".idea",".gradle",".terraform","target","coverage",".vscode",".svn",".hg",".fslckout",".github",".gitlab",".circleci",".gitea",".gitee",".lerna",".changeset",".nx",".npm",".yarn",".pnpm-store",".pnpm",".expo",".nuxt",".svelte-kit",".docusaurus",".turbo",".vercel","bower_components",".netlify",".vuepress",".quasar",".output",".angular","jspm_packages",".parcel-cache",".rollup.cache",".rspack",".vitepress","__pycache__",".pytest_cache",".mypy_cache",".tox",".poetry","env","vhdl",".ipynb_checkpoints",".jupyter",".conda",".pdm-build",".bundle",".yardoc",".metadata","App_Data","ClientBin",".cargo",".rustc_info",".go","Godeps","_vendor",".rake_tasks","CMakefiles",".wakatime",".dart_tool",".fvm",".cocoapods","Pods",".pub-cache",".symlinks","DerivedData",".xcworkspace",".serverless",".aws",".gcloud",".azure",".kube",".vagrant",".docker","postgres-data","redis-data","mongo-data",".Spotlight-V100",".Trashes","$RECYCLE.BIN","System Volume Information",".DocumentRevisions-V100",".fseventsd","AppData","Application Data","Local","LocalLow","Roaming","$WinREAgent","$WINDOWS.~BT","$WINDOWS.~WS","scw","System32","SysWOW64",".AppleDouble",".AppleDB",".AppleDesktop","_CodeSignature",".cmio",".LSOverride",".localized",".TemporaryItems",".Trash",".Trash-0",".Trash-1000",".gvfs",".local",".config",".dbus",".fontconfig",".snap",".var",".lost+found","lost+found",".thumb",".thumbnails","EFI","boot","grub","logs","log",".nyc_output",".sonar",".ruff_cache",".VSCodeCounter"],it=G=>{try{return Pe.readdirSync(G,{withFileTypes:!0})}catch{return[]}},ze=(G,Le={value:0},nn=1)=>{if(Le.value>6200||nn>7)return Le.value;let Me=it(G);for(let Ze of Me){if(Le.value>6200)break;je.includes(Ze.name)||Ze.name.startsWith(".")||Ze.isDirectory()&&(Le.value++,ze(ee.join(G,Ze.name),Le,nn+1))}return Le.value},gt=(G,Le)=>l?.indentationTree!==!1?Vr(G,Le,1,it,je):Jr(G,Le,"",1,it,je),Bt=ze(process.cwd()),yt=12;Bt>3072?yt=1:Bt>2304?yt=2:Bt>1536?yt=3:Bt>768?yt=4:Bt>384?yt=6:Bt>192?yt=7:Bt>96?yt=8:Bt>48?yt=9:Bt>24&&(yt=10);let wt=Z(Jo,{}),Rt=wt[d],ut=Rt?Rt!==process.cwd():!1;wt[d]=process.cwd(),me(Jo,wt);let Ce=Z(b,{}),le=Ce[d]||{summary:"",historyLength:0};typeof le=="string"&&(le={summary:le,historyLength:0});let Vt=n.filter(G=>(G.role==="user"||G.role==="agent"||G.role==="system")&&!String(G.id).startsWith("welcome")&&!G.isMeta).length;le.historyLength&&Vt<le.historyLength&&(le.summary="",le.historyLength=0,Ce[d]=le,me(b,Ce));let Xn=typeof le=="object"?le.summary||"":le||"",Jn=x.length>0;Jn&&Xn&&x[0]&&(x[0].role==="user"||x[0].role==="system")&&(x[0].text.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")||(x[0].text=`[SYSTEM METADATA]
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 ci=Xn&&!Jn?`
576
+ [USER] ${x[0].text}`,yield{type:"summary_injected",content:{id:x[0].id,text:x[0].text}}));let ci=Xn&&!Jn?`
577
577
  [SYSTEM METADATA]
578
578
  **CONTEXT SUMMARY OF PREVIOUS TURNS**
579
579
  ${Xn}
580
- `:"",di=!!l?.dynamicDirAwareness,Fa=`${d}|${u}|${a}|${e}|${r}|${di}`,fi=!di&&ys.key===Fa&&ys.value?"":`
580
+ `:"",di=!!l?.dynamicDirAwareness,Na=`${d}|${u}|${a}|${e}|${r}|${di}`,fi=!di&&ys.key===Na&&ys.value?"":`
581
581
  **Directory Structure**
582
582
  CWD: `+process.cwd()+`${c?" [PLAYGROUND MODE]":""}
583
583
  `+gt(process.cwd(),yt),St=await ms(),Dn="";if(Uo()&&St.file_focused!=="none"){Dn=`
584
584
  [Additional IDE Context]
585
- `;let G=Z.relative(process.cwd(),St.file_focused),Le=(St.opened_editors||[]).map(Ce=>{let Ze=Z.relative(process.cwd(),Ce);return Ze.startsWith("..")?`[External] ${Z.basename(Ce)}`:Ze});if(Dn+=`Focused File: ${G}
585
+ `;let G=ee.relative(process.cwd(),St.file_focused),Le=(St.opened_editors||[]).map(Me=>{let Ze=ee.relative(process.cwd(),Me);return Ze.startsWith("..")?`[External] ${ee.basename(Me)}`:Ze});if(Dn+=`Focused File: ${G}
586
586
  Cursor Line: ${St.cursor_line}
587
- `,St.selected){let Ce=St.selected,Ze=Ce.split(`
588
- `);Ze.length>256&&(Ce=Ze.slice(0,240).join(`
587
+ `,St.selected){let Me=St.selected,Ze=Me.split(`
588
+ `);Ze.length>256&&(Me=Ze.slice(0,240).join(`
589
589
  `)+`
590
590
  ... [truncated] ...
591
591
  `+Ze.slice(-16).join(`
592
- `)),Ce.length>2048&&(Ce=Ce.slice(0,1920)+`
592
+ `)),Me.length>2048&&(Me=Me.slice(0,1920)+`
593
593
  ... [truncated] ...
594
- `+Ce.slice(-128)),Dn+=`Current Selection: "${Ce}"
594
+ `+Me.slice(-128)),Dn+=`Current Selection: "${Me}"
595
595
  `}if(St.manual_edits){let Ze=St.manual_edits.split(`
596
- `),He=[],Je=null;for(let z of Ze)z.trim()&&(z.startsWith(" Line ")?Je&&Je.edits.push(z):(Je={path:z.endsWith(":")?z.slice(0,-1):z,edits:[]},He.push(Je)));for(let z of He)z.edits.length>80&&(z.edits=z.edits.slice(-80)),z.originalEditsCount=z.edits.length;let de=(z,ee)=>ee.reduce((Ge,cn)=>{let wn=St.file_focused&&(cn.path===St.file_focused||Z.resolve(process.cwd(),cn.path)===Z.resolve(St.file_focused))?Math.ceil(z*1.2):z;return Ge+Math.min(cn.edits.length,wn)},0),Ut=80;if(de(80,He)>300){let z=!1;for(let ee=80;ee>=10;ee--)if(de(ee,He)<=300){Ut=ee,z=!0;break}z||(Ut=10)}let Qe=[...He];if(Ut===10&&de(10,Qe)>500)for(;Qe.length>0&&de(10,Qe)>500;){let z=0,ee=Qe[0].originalEditsCount;for(let Ge=1;Ge<Qe.length;Ge++)Qe[Ge].originalEditsCount<ee&&(ee=Qe[Ge].originalEditsCount,z=Ge);Qe.splice(z,1)}for(let z of Qe){let Ge=St.file_focused&&(z.path===St.file_focused||Z.resolve(process.cwd(),z.path)===Z.resolve(St.file_focused))?Math.ceil(Ut*1.2):Ut;z.edits.length>Ge&&(z.edits=z.edits.slice(-Ge))}for(let z of Qe){let ee=`${z.path}:
596
+ `),He=[],Je=null;for(let z of Ze)z.trim()&&(z.startsWith(" Line ")?Je&&Je.edits.push(z):(Je={path:z.endsWith(":")?z.slice(0,-1):z,edits:[]},He.push(Je)));for(let z of He)z.edits.length>80&&(z.edits=z.edits.slice(-80)),z.originalEditsCount=z.edits.length;let fe=(z,te)=>te.reduce((Ge,cn)=>{let wn=St.file_focused&&(cn.path===St.file_focused||ee.resolve(process.cwd(),cn.path)===ee.resolve(St.file_focused))?Math.ceil(z*1.2):z;return Ge+Math.min(cn.edits.length,wn)},0),Ut=80;if(fe(80,He)>300){let z=!1;for(let te=80;te>=10;te--)if(fe(te,He)<=300){Ut=te,z=!0;break}z||(Ut=10)}let Qe=[...He];if(Ut===10&&fe(10,Qe)>500)for(;Qe.length>0&&fe(10,Qe)>500;){let z=0,te=Qe[0].originalEditsCount;for(let Ge=1;Ge<Qe.length;Ge++)Qe[Ge].originalEditsCount<te&&(te=Qe[Ge].originalEditsCount,z=Ge);Qe.splice(z,1)}for(let z of Qe){let Ge=St.file_focused&&(z.path===St.file_focused||ee.resolve(process.cwd(),z.path)===ee.resolve(St.file_focused))?Math.ceil(Ut*1.2):Ut;z.edits.length>Ge&&(z.edits=z.edits.slice(-Ge))}for(let z of Qe){let te=`${z.path}:
597
597
  ${z.edits.join(`
598
- `)}`;for(;z.edits.length>0&&ee.length>4*768;)z.edits.shift(),ee=`${z.path}:
598
+ `)}`;for(;z.edits.length>0&&te.length>4*768;)z.edits.shift(),te=`${z.path}:
599
599
  ${z.edits.join(`
600
- `)}`;ee.length>4*768?z.stringRepresentation="... "+ee.slice(-(4*768-4)):z.stringRepresentation=ee}let sn=Qe.map(z=>z.stringRepresentation).join(`
601
- `);for(;Qe.length>0&&sn.length>4*2048;){Qe[0].edits.length>0?Qe[0].edits.shift():Qe.shift();for(let z of Qe){let ee=`${z.path}:
600
+ `)}`;te.length>4*768?z.stringRepresentation="... "+te.slice(-(4*768-4)):z.stringRepresentation=te}let sn=Qe.map(z=>z.stringRepresentation).join(`
601
+ `);for(;Qe.length>0&&sn.length>4*2048;){Qe[0].edits.length>0?Qe[0].edits.shift():Qe.shift();for(let z of Qe){let te=`${z.path}:
602
602
  ${z.edits.join(`
603
- `)}`;ee.length>4*768?z.stringRepresentation="... "+ee.slice(-(4*768-4)):z.stringRepresentation=ee}sn=Qe.map(z=>z.stringRepresentation).join(`
603
+ `)}`;te.length>4*768?z.stringRepresentation="... "+te.slice(-(4*768-4)):z.stringRepresentation=te}sn=Qe.map(z=>z.stringRepresentation).join(`
604
604
  `)}sn.length>4*2048&&(sn="... "+sn.slice(-(4*2048-4))),Dn+=`Recent Manual Edits:
605
605
  ${sn}
606
606
  `}Le.length>0&&(Dn+=`All Opened Editors: ${Le.join(", ")}`),St.diagnostics&&(Dn+=`
607
607
  **Active File Errors**:
608
608
  ${St.diagnostics}
609
- `),(T.toLowerCase().includes("lint")||T.toLowerCase().includes("warning"))&&St.warnings&&(Dn+=`
609
+ `),(S.toLowerCase().includes("lint")||S.toLowerCase().includes("warning"))&&St.warnings&&(Dn+=`
610
610
  **Lint Warnings**:
611
611
  ${St.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 G=Go[0].startsWith("\\");qo.push({tag:Go[1],isEscaped:G})}let zo=[],po=null;for(let G=0;G<qo.length;G++){let{tag:Le,isEscaped:nn}=qo[G];if(!nn)try{let Ce=Le.trim().replace(/^["']|["']$/g,""),Ze=/[:#]L?(\d+)(?:-L?(\d+))?$/i,He=Ce.match(Ze),Je=Ce,de=null,Ut=null;He&&(de=parseInt(He[1],10),Ut=He[2]?parseInt(He[2],10):de,Je=Ce.slice(0,He.index));let Qe=Z.resolve(process.cwd(),Je);if(Pe.existsSync(Qe)&&Pe.statSync(Qe).isFile()){let z=Je.toLowerCase(),ee=z.endsWith(".pdf"),Ge=z.endsWith(".docx")||z.endsWith(".doc")||z.endsWith(".ppt")||z.endsWith(".pptx")||z.endsWith(".xls")||z.endsWith(".xlsx"),cn=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(z),Wt=cn||ee||Ge,wn=u==="Google"||zt(e);if(Wt&&!wn){let We=`\u2718 Unsupported Modality: ${Z.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(`
612
+ `)}let ui=S.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),hi=/(?:\\)?@\[([^\]]+)\]/g,Go,qo=[];for(hi.lastIndex=0;(Go=hi.exec(ui))!==null;){let G=Go[0].startsWith("\\");qo.push({tag:Go[1],isEscaped:G})}let zo=[],po=null;for(let G=0;G<qo.length;G++){let{tag:Le,isEscaped:nn}=qo[G];if(!nn)try{let Me=Le.trim().replace(/^["']|["']$/g,""),Ze=/[:#]L?(\d+)(?:-L?(\d+))?$/i,He=Me.match(Ze),Je=Me,fe=null,Ut=null;He&&(fe=parseInt(He[1],10),Ut=He[2]?parseInt(He[2],10):fe,Je=Me.slice(0,He.index));let Qe=ee.resolve(process.cwd(),Je);if(Pe.existsSync(Qe)&&Pe.statSync(Qe).isFile()){let z=Je.toLowerCase(),te=z.endsWith(".pdf"),Ge=z.endsWith(".docx")||z.endsWith(".doc")||z.endsWith(".ppt")||z.endsWith(".pptx")||z.endsWith(".xls")||z.endsWith(".xlsx"),cn=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(z),Wt=cn||te||Ge,wn=u==="Google"||zt(e);if(Wt&&!wn){let We=`\u2718 Unsupported Modality: ${ee.basename(Je)}`,Te=115;process.stdout.isTTY&&(Te=process.stdout.columns-5||120);let nt=[We],Fn=Math.max(...nt.map(En=>En.length)),Nn=Math.min(Fn+4,Te),es=nt.map(En=>`${En.padEnd(Nn-2).substring(0,Nn-2)}`).join(`
613
613
  `);yield{type:"visual_feedback",content:gn(`${es}
614
- `)};continue}if(de===null&&!Wt){let We=0;try{We=Pe.readFileSync(Qe,"utf8").split(/\r\n|\r|\n/).length}catch{}if(We>300){let Se=`\u21B7 Skipped (Too Large): ${Z.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=Ut!==null?Ut: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,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: ${Z.basename(Je)}`,po=Zn):ee||Ge?(We=`\u2714 Auto-Analysed: ${Z.basename(Je)}`,po=Zn):(We=`\u2714 Auto-Read: ${Z.basename(Je)}`,zo.push(jt)),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(`
614
+ `)};continue}if(fe===null&&!Wt){let We=0;try{We=Pe.readFileSync(Qe,"utf8").split(/\r\n|\r|\n/).length}catch{}if(We>300){let Te=`\u21B7 Skipped (Too Large): ${ee.basename(Je)}`,nt=115;process.stdout.isTTY&&(nt=process.stdout.columns-5||120);let Fn=Math.min(Te.length+4,nt),Nn=Te.padEnd(Fn-2).substring(0,Fn-2);yield{type:"visual_feedback",content:gn(`${Nn}
615
+ `)};continue}}let Rn=fe!==null?fe:1,Qn=Ut!==null?Ut:fe!==null?fe:Rn+299;Qn-Rn>300&&(Qn=Rn+300);let go=`path=${JSON.stringify(Je)}, startLine=${Rn}, endLine=${Qn}`,tt=await Qs(go,{isMultiModal:wn}),Ke=!1,jt="",Zn=null;if(typeof tt=="string"?tt.trim().startsWith("ERROR")?Ke=!0:jt=tt:tt&&typeof tt=="object"&&tt.binaryPart?(Zn=tt.binaryPart,jt=tt.text||""):Ke=!0,!Ke){let We="";if(cn?(We=`\u2714 Processed: ${ee.basename(Je)}`,po=Zn):te||Ge?(We=`\u2714 Auto-Analysed: ${ee.basename(Je)}`,po=Zn):(We=`\u2714 Auto-Read: ${ee.basename(Je)}`,zo.push(jt)),We){let Te=115;process.stdout.isTTY&&(Te=process.stdout.columns-5||120);let nt=[We],Fn=Math.max(...nt.map(En=>En.length)),Nn=Math.min(Fn+4,Te),es=nt.map(En=>`${En.padEnd(Nn-2).substring(0,Nn-2)}`).join(`
616
616
  `);yield{type:"visual_feedback",content:gn(`${es}
617
617
  `)}}}}}catch{}}let pi="";zo.length>0&&(pi=`[Tagged File Contents] Auto Read User Tagged files by System, No need to re-read
618
618
  `+zo.join(`
619
619
 
620
620
  `)+`
621
621
  [Tagged File Contents]
622
- `);let Na=ui.replace(/\\(@\[[^\]]+\])/g,"$1"),Ba=g?`You cannot execute tools
622
+ `);let Ba=ui.replace(/\\(@\[[^\]]+\])/g,"$1"),Ua=g?`You cannot execute tools
623
623
  Instead, output in chat the exact string you WOULD have produced & wait for system response
624
- `:"",Ua=process.env.forcedReasoning||!1,mi=`[System Metadata]
624
+ `:"",Wa=process.env.forcedReasoning||!1,mi=`[System Metadata]
625
625
  Time: ${Fe}${l?.dynamicDirAwareness?fi:""}${ut?`
626
626
  WARNING: CWD Changed from previous: "${Rt}" to current: "${process.cwd()}", write change in chat to avoid future path mismatches
627
- `:""}${_e}${Dn}
627
+ `:""}${$e}${Dn}
628
628
  [/Metadata]
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
- `:""}`:""}[system] exact tool string '[tool:functions.ToolName(arg="value")]' in chat [/system]
631
- ${pi}${Ba}[user prompt] ${Na.trim()} [/user prompt]`.trim(),gi={role:"user",text:mi};po&&(gi.binaryPart=po),k.forEach(G=>{G.text&&G.role==="agent"&&(G.text=G.text.replace(/(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])/gi,""),G.text=G.text.replace(/(?:<(think|thought)>|\[(think|thought)\])[^\[\n]*/gi,"").trim())}),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"},Lt=!1;let yi=[],mo=!1;for(let G=0;G<=Bs;G++){let Le=await ar("agent",t);if(!Le.allowed)throw new Error(Le.reason||`Budget Exhausted for Provider (${u||"Agent"})`);let nn=[];if(mo=!1,i==="ICU"||i==="FluxCU")try{yield{type:"status",content:"Capturing Screen"},await new Promise(Te=>setTimeout(Te,1e3));let ue=await xi();if(ue&&ue.base64){let Te="[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]",oe={inlineData:{mimeType:ue.mimeType,data:ue.base64}};for(let st of k)Array.isArray(st.parts)&&(st.parts=st.parts.filter(Mt=>!Mt.inlineData));if(k.length>0&&k[k.length-1].role==="user"){let st=k[k.length-1];typeof st.text=="string"&&(st.text+=`
629
+ ${ci}${a!=="Fast"&&(u==="Mistral"&&!qs(e)||a!=="xHigh"&&u==="Google")?`${u==="Mistral"&&!qs(e)||e.toLowerCase().startsWith("gemma")||Wa?`[system] strictly follow thinking policy as high priority. do not start a response without <think>...</think> [/system]
630
+ `:""}`:""}[system] exact tool string [tool:functions.ToolName(arg="value")] in chat [/system]
631
+ ${pi}${Ua}[user prompt] ${Ba.trim()} [/user prompt]`.trim(),gi={role:"user",text:mi};po&&(gi.binaryPart=po),x.forEach(G=>{G.text&&G.role==="agent"&&(G.text=G.text.replace(/(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])/gi,""),G.text=G.text.replace(/(?:<(think|thought)>|\[(think|thought)\])[^\[\n]*/gi,"").trim())}),x.push(gi),ci&&n[n.length-1]?.id&&(yield{type:"summary_injected",content:{id:n[n.length-1].id,text:mi}});let Tn=null,Bs=i==="Flux"?100:10;Bs=i.toLowerCase().includes("cu")?250:Bs;let yn=16;yield{type:"status",content:"Connecting"},Lt=!1;let yi=[],mo=!1;for(let G=0;G<=Bs;G++){let Le=await ar("agent",t);if(!Le.allowed)throw new Error(Le.reason||`Budget Exhausted for Provider (${u||"Agent"})`);let nn=[];if(mo=!1,i==="ICU"||i==="FluxCU")try{yield{type:"status",content:"Capturing Screen"},await new Promise(Re=>setTimeout(Re,1e3));let he=await xi();if(he&&he.base64){let Re="[system] Fresh Gridded Screen Feedback Captured. Use numeric coordinates. Old screenshots will be removed when new screenshot is captured, summarize in text if context is needed later [/system]",ie={inlineData:{mimeType:he.mimeType,data:he.base64}};for(let st of x)Array.isArray(st.parts)&&(st.parts=st.parts.filter(Mt=>!Mt.inlineData));if(x.length>0&&x[x.length-1].role==="user"){let st=x[x.length-1];typeof st.text=="string"&&(st.text+=`
632
632
 
633
- ${Te}`,Array.isArray(st.parts)||(st.parts=[{text:st.text}]),st.parts.push(oe))}else k.push({role:"user",text:Te,parts:[{text:Te},oe]})}}catch(ue){console.error("Vision screenshot capture error:",ue)}if(l?.compression===0&&(f?.tokens||0)>P&&(k=vi(k,6)),G>0?yield{type:"status",content:"Working"}:yield{type:"status",content:"Connecting"},Lt){try{let{clearPendingNudges:ue}=await import("./subagent_state-LZCOZSUJ.js");ue()}catch{}yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
633
+ ${Re}`,Array.isArray(st.parts)||(st.parts=[{text:st.text}]),st.parts.push(ie))}else x.push({role:"user",text:Re,parts:[{text:Re},ie]})}}catch(he){console.error("Vision screenshot capture error:",he)}if(l?.compression===0&&(f?.tokens||0)>L&&(x=vi(x,6)),G>0?yield{type:"status",content:"Working"}:yield{type:"status",content:"Connecting"},Lt){try{let{clearPendingNudges:he}=await import("./subagent_state-LZCOZSUJ.js");he()}catch{}yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
634
634
 
635
- \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}try{let{consumePendingNudges:ue}=await import("./subagent_state-LZCOZSUJ.js"),Te=ue();if(Te&&Te.length>0){let oe=Te.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 ie=Re.join(`
636
636
 
637
- `);k.length>0&&k[k.length-1].role==="user"?k[k.length-1].text+=`
637
+ `);x.length>0&&x[x.length-1].role==="user"?x[x.length-1].text+=`
638
638
 
639
- ${oe}`:k.push({role:"user",text:oe}),yield{type:"status",content:"Subagent Update"}}}catch{}if(o){let ue=await o();ue&&(ue.startsWith("/btw")?k.length>0&&k[k.length-1].role==="user"?k[k.length-1].text+=`
639
+ ${ie}`:x.push({role:"user",text:ie}),yield{type:"status",content:"Subagent Update"}}}catch{}if(o){let he=await o();he&&(he.startsWith("/btw")?x.length>0&&x[x.length-1].role==="user"?x[x.length-1].text+=`
640
640
 
641
641
  [system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/SYSTEM]
642
- [question] ${ue.replace("/btw","").trim()} [/question]`:k.push({role:"user",text:`[system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
643
- [question] ${ue.replace("/btw","").trim()} [/question]`}):k.length>0&&k[k.length-1].role==="user"?k[k.length-1].text+=`
642
+ [question] ${he.replace("/btw","").trim()} [/question]`:x.push({role:"user",text:`[system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
643
+ [question] ${he.replace("/btw","").trim()} [/question]`}):x.length>0&&x[x.length-1].role==="user"?x[x.length-1].text+=`
644
644
 
645
- [STEERING HINT from USER, HIGH PRIORITY] ${ue.trim().toUpperCase()} [/STEERING HINT]`:k.push({role:"user",text:`[STEERING HINT from USER, HIGH PRIORITY] ${ue.trim().toUpperCase()} [/STEERING HINT]`}),yield{type:"status",content:`${ue.startsWith("/btw")?"Question Forwarded...":"Steering Hint Injected..."}`})}let Ce,Ze=!1,He=1,Je=1,de="",Ut=null,Qe=null,sn=null,z=0,ee=[],Ge=0,cn=!1,Wt=!1,wn=!1,Rn=!1,Qn=!0,go=0,tt="",Ke="",jt=!1,Zn=!1,We=!0,Se=e,nt="";for(;He<=yn&&Je<=yn&&!Ze&&!Lt;){let ue=!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 Te=D=>{if(!D||!D.includes("[tool:"))return D;let ne="___THINK_OPEN_TAG___",W="___THINK_CLOSE_TAG___";D=D.replace("<think>",ne).replace("</think>",W),D=D.replace(Rc,(me,Re)=>Re.includes("[tool:")?Re.trim():me);let H="",ye=0;for(;ye<D.length;){let me=D.indexOf("[tool:",ye);if(me===-1){H+=D.substring(ye).replace(Ma,"").replace(Aa,"");break}let Re=D.substring(ye,me);H+=Re.replace(Ma,"").replace(Aa,"");let ot=D.indexOf("]",me);if(ot===-1){H+=D.substring(me);break}H+=D.substring(me,ot+1),ye=ot+1}return D=H,D=D.replaceAll(ne,"<think>").replaceAll(W,"</think>"),D},oe=k.filter(D=>(D.role==="user"||D.role==="agent"||D.role==="system")&&!String(D.id).startsWith("welcome")&&!D.isMeta&&!D.isTerminalRecord&&!(D.text&&D.text.startsWith("[TERMINAL_RECORD]"))).map((D,ne,W)=>{let H=D.text||"";m||(H=H.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),D.role==="agent"&&(H=Te(H),H=H.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),H=H.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*"));let ye=[];return Array.isArray(D.parts)&&D.parts.length>0?ye=D.parts.map(me=>{if(me.text){let Re=me.text;return m||(Re=Re.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),D.role==="agent"&&(Re=Te(Re),Re=Re.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),Re=Re.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*")),{text:Re}}return me}):ye=[{text:H}],D.binaryPart&&zt(Se)&&W.slice(ne+1).filter(Re=>Re.role==="user"&&!Re.text?.startsWith("[TOOL RESULT]")).length<=2&&ye.push(D.binaryPart),{role:D.role==="user"||D.role==="system"?"user":"model",parts:ye}});for(let D=0;D<oe.length;D++){let ne=oe[D],W=ne.parts?.[0]?.text||"";if(ne.role==="model"&&/\[tool:/i.test(W)){let H=-1;for(let ye=D+1;ye<oe.length;ye++){let me=oe[ye],Re=me.parts?.[0]?.text||"";if(me.role==="user"&&Re.startsWith("[TOOL RESULT]")){H=ye;break}}if(H!==-1&&H!==D+1){let[ye]=oe.splice(H,1);oe.splice(D+1,0,ye)}}}for(let D=oe.length-2;D>=0;D--){let ne=oe[D],W=oe[D+1];ne.role==="user"&&W.role==="user"&&(W.parts?.[0]?.text||"").trim().startsWith("[SYSTEM")&&oe.splice(D,1)}let st=[];for(let D=0;D<oe.length;D++){let ne=oe[D];if(st.length===0)st.push(ne);else{let W=st[st.length-1];W.role===ne.role?(W.parts[0].text+=`
645
+ [STEERING HINT from USER, HIGH PRIORITY] ${he.trim().toUpperCase()} [/STEERING HINT]`:x.push({role:"user",text:`[STEERING HINT from USER, HIGH PRIORITY] ${he.trim().toUpperCase()} [/STEERING HINT]`}),yield{type:"status",content:`${he.startsWith("/btw")?"Question Forwarded...":"Steering Hint Injected..."}`})}let Me,Ze=!1,He=1,Je=1,fe="",Ut=null,Qe=null,sn=null,z=0,te=[],Ge=0,cn=!1,Wt=!1,wn=!1,Rn=!1,Qn=!0,go=0,tt="",Ke="",jt=!1,Zn=!1,We=!0,Te=e,nt="";for(;He<=yn&&Je<=yn&&!Ze&&!Lt;){let he=!1;try{fe="",Qn&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},Qn=!1,Je===1&&(tt=""));let Re=D=>{if(!D||!D.includes("[tool:"))return D;let oe="___THINK_OPEN_TAG___",j="___THINK_CLOSE_TAG___";D=D.replace("<think>",oe).replace("</think>",j),D=D.replace(Ec,(ge,Ee)=>Ee.includes("[tool:")?Ee.trim():ge);let H="",we=0;for(;we<D.length;){let ge=D.indexOf("[tool:",we);if(ge===-1){H+=D.substring(we).replace(Ma,"").replace(Aa,"");break}let Ee=D.substring(we,ge);H+=Ee.replace(Ma,"").replace(Aa,"");let ot=D.indexOf("]",ge);if(ot===-1){H+=D.substring(ge);break}H+=D.substring(ge,ot+1),we=ot+1}return D=H,D=D.replaceAll(oe,"<think>").replaceAll(j,"</think>"),D},ie=x.filter(D=>(D.role==="user"||D.role==="agent"||D.role==="system")&&!String(D.id).startsWith("welcome")&&!D.isMeta&&!D.isTerminalRecord&&!(D.text&&D.text.startsWith("[TERMINAL_RECORD]"))).map((D,oe,j)=>{let H=D.text||"";m||(H=H.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),D.role==="agent"&&(H=Re(H),H=H.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),H=H.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*"));let we=[];return Array.isArray(D.parts)&&D.parts.length>0?we=D.parts.map(ge=>{if(ge.text){let Ee=ge.text;return m||(Ee=Ee.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),D.role==="agent"&&(Ee=Re(Ee),Ee=Ee.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),Ee=Ee.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*")),{text:Ee}}return ge}):we=[{text:H}],D.binaryPart&&zt(Te)&&j.slice(oe+1).filter(Ee=>Ee.role==="user"&&!Ee.text?.startsWith("[TOOL RESULT]")).length<=2&&we.push(D.binaryPart),{role:D.role==="user"||D.role==="system"?"user":"model",parts:we}});for(let D=0;D<ie.length;D++){let oe=ie[D],j=oe.parts?.[0]?.text||"";if(oe.role==="model"&&/\[tool:/i.test(j)){let H=-1;for(let we=D+1;we<ie.length;we++){let ge=ie[we],Ee=ge.parts?.[0]?.text||"";if(ge.role==="user"&&Ee.startsWith("[TOOL RESULT]")){H=we;break}}if(H!==-1&&H!==D+1){let[we]=ie.splice(H,1);ie.splice(D+1,0,we)}}}for(let D=ie.length-2;D>=0;D--){let oe=ie[D],j=ie[D+1];oe.role==="user"&&j.role==="user"&&(j.parts?.[0]?.text||"").trim().startsWith("[SYSTEM")&&ie.splice(D,1)}let st=[];for(let D=0;D<ie.length;D++){let oe=ie[D];if(st.length===0)st.push(oe);else{let j=st[st.length-1];j.role===oe.role?(j.parts[0].text+=`
646
646
 
647
- `+(ne.parts?.[0]?.text||""),ne.parts?.length>1&&W.parts.push(...ne.parts.slice(1))):st.push(ne)}}oe.length=0,oe.push(...st),Se=e;let Mt=`${d}|${u}|${i}|${a}|${Se}|${JSON.stringify(r)}|${!!l?.dynamicDirAwareness}|${!!l?.subAgents}`;if(ys.key===Mt&&ys.value)nt=ys.value;else{let D=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,D,d),l?.dynamicDirAwareness||(nt+=`
647
+ `+(oe.parts?.[0]?.text||""),oe.parts?.length>1&&j.parts.push(...oe.parts.slice(1))):st.push(oe)}}ie.length=0,ie.push(...st),Te=e;let Mt=`${d}|${u}|${i}|${a}|${Te}|${JSON.stringify(r)}|${!!l?.dynamicDirAwareness}|${!!l?.subAgents}`;if(ys.key===Mt&&ys.value)nt=ys.value;else{let D=u==="Mistral"?!!qs(Te):!(Te||"gemma").toLowerCase().startsWith("gemma");nt=$i(r,((Te||"gemma").toLowerCase().startsWith("gemma"),a),i,l,m,$,u,u==="Google"?!0:y,D,d),l?.dynamicDirAwareness||(nt+=`
648
648
  ${fi.replace(`
649
649
  **Directory Structure**`,`
650
- **Directory Structure**`)}`),ys.key=Mt,ys.value=nt}let Et=oe[oe.length-1];if(Uo()&G>0){await new Promise(W=>setTimeout(W,2500)),yield{type:"status",content:"Verifying"};let D=await ms(),ne=D?D.diagnostics:null;ne&&Et&&Et.role==="user"&&Et.parts?.[0]?.text&&(Et.parts[0].text+=`
651
- ${ne} [/ERROR]`),yield{type:"status",content:"Working"}}if(u==="Mistral"||u==="Google"&&e?.toLowerCase().startsWith("gemma")){let ne=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]`;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 D=await Kn.getLatestFileChanges(d);if(D&&(D.newFiles.length>0||D.modifiedFiles.length>0||D.deletedFiles.length>0)){let ne=`
650
+ **Directory Structure**`)}`),ys.key=Mt,ys.value=nt}let Et=ie[ie.length-1];if(Uo()&G>0){await new Promise(j=>setTimeout(j,2500)),yield{type:"status",content:"Verifying"};let D=await ms(),oe=D?D.diagnostics:null;oe&&Et&&Et.role==="user"&&Et.parts?.[0]?.text&&(Et.parts[0].text+=`
651
+ ${oe} [/ERROR]`),yield{type:"status",content:"Working"}}if(u==="Mistral"||u==="Google"&&e?.toLowerCase().startsWith("gemma")){let oe=a!=="Fast"&&(u==="Mistral"||a!=="xHigh")?". **strictly maintain thinking policy. do not start a response without <think>...</think>**":"",j=`
652
+ [SYSTEM] Tool result received. Analyze output and proceed with your turn [/SYSTEM]`;Et&&Et.role==="user"&&Et.parts?.[0]?.text?.startsWith("[TOOL RESULT]")&&(Et.parts[0].text+=j)}if(l?.advanceRollback&&Et&&Et.role==="user"&&Et.parts?.[0]?.text?.startsWith("[TOOL RESULT]"))try{let D=await Kn.getLatestFileChanges(d);if(D&&(D.newFiles.length>0||D.modifiedFiles.length>0||D.deletedFiles.length>0)){let oe=`
653
653
  [system] File Changes:
654
- `;for(let H of D.newFiles)ne+=`* ${H} (created)
655
- `;for(let H of D.modifiedFiles)ne+=`* ${H} (modified)
656
- `;for(let H of D.deletedFiles)ne+=`* ${H} (deleted)
657
- `;ne+="[/system]",Et.parts[0].text+=ne;let W=-1;for(let H=k.length-1;H>=0;H--)if(k[H].role==="user"&&k[H].text?.startsWith("[TOOL RESULT]")){W=H;break}W!==-1&&(k[W].text+=ne)}}catch{}let Bn=Math.floor(Bs*(i==="Flux"?.98:.8)),Xt=G+1;Xt>=Bn&&Et&&Et.parts?.[0]&&(Et.parts[0].text+=`
658
- [system] WARNING, Turn Limit Impending: Step ${Xt}/${Bs}. Wrap up quickly/prompt user to continue. [/system]`);let At=new Promise((D,ne)=>{_.signal.aborted&&ne(new DOMException("The user aborted a request.","AbortError")),_.signal.addEventListener("abort",()=>{ne(new DOMException("The user aborted a request.","AbortError"))})});At.catch(()=>{});let at=oe;if(u==="Ollama")Ce=Pa(t.apiKey,Se,at,nt,a,i,y,_.signal,1.05,l?.ollamaEndpoint||"Cloud");else if(u==="OpenRouter")Ce=oi(t.apiKey,Se,at,nt,a,i,y,_.signal,1.05);else if(u==="DeepSeek")Ce=ti(t.apiKey,Se,at,nt,a,i,y,_.signal,1.05);else if(u==="Mistral")Ce=ni(t.apiKey,Se,at,nt,a,i,y,_.signal,1.05);else if(u==="NVIDIA"){let D=si(t.apiKey,Se,at,nt,a,i,y,_.signal,1.05);Ce=Cc(D,Se)}else if(u==="CrofAI")Ce=ri(t.apiKey,Se,at,nt,a,i,y,_.signal,1.05);else if(u==="InferX")Ce=ii(t.apiKey,Se,at,nt,a,i,y,_.signal,1.05);else if(u==="SenseNova")Ce=ai(t.apiKey,Se,at,nt,a,i,y,_.signal,1.05);else{let ne=li(t?.apiKey).models.generateContentStream({model:Se||"gemini-3-flash-preview",contents:at,config:{systemInstruction:nt,mediaResolution:"MEDIA_RESOLUTION_HIGH",safetySettings:[{category:Vn.HARM_CATEGORY_HARASSMENT,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_HATE_SPEECH,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Yn.BLOCK_NONE}],temperature:1.05,thinkingConfig:(()=>{let W=(Se||"").toLowerCase(),H=W.includes("gemma-4")||W.startsWith("gemma"),ye=W.includes("gemini-3");if(H||ye)return H?a.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:ft.MINIMAL}:{includeThoughts:!0,thinkingLevel:ft.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:W.includes("pro")?ft.LOW:ft.MINIMAL,Low:ft.LOW,Medium:ft.MEDIUM,Standard:ft.MEDIUM,High:ft.HIGH,xHigh:ft.HIGH}[a]||ft.MEDIUM};{let 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([ne,At])}de="",Ut=null,sn=null,ee=[],Ge=0,yield{type:"model_update",content:null},Ke="",jt=tt.length>0;let Pt="",Ko=Date.now(),ns=async function*(){if(u==="Google"&&Pt){let D=Us(Pt);for(let ne of D)yield ne;Pt="",Ko=Date.now()}},wi=!0,ss="",bs=!1,Ht=null,Ga={tool:{startPrefix:"[tool",fullPrefix:"[tool:functions.",endTag:"]"},agent:{startPrefix:"[agent",fullPrefix:"[agent:generalist.",endTag:"]"},end:{startPrefix:"[[END]]",fullPrefix:"[[END]]",endTag:"[[END]]"},kimi_section:{startPrefix:"<|tool_calls_section_begin|>",fullPrefix:"<|tool_calls_section_begin|>",endTag:"<|tool_calls_section_end|>"},kimi_call:{startPrefix:"<|tool_call_begin|>",fullPrefix:"<|tool_call_begin|>",endTag:"<|tool_call_end|>"}},Us=D=>{let ne=[],W=D;for(;W.length>0;)if(bs){let H=ss+W,ye=Ga[Ht];if(ye){let ot=!1;if(H.length<ye.startPrefix.length?ye.startPrefix.startsWith(H)||(ot=!0):H.startsWith(ye.startPrefix)?H.length>=ye.fullPrefix.length&&!H.startsWith(ye.fullPrefix)&&(ot=!0):ot=!0,ot){ne.push({type:"text",content:H}),ss="",bs=!1,Ht=null,W="";break}}let me=-1,Re=ye?ye.endTag:"]";if(Ht==="tool"||Ht==="agent"){let ot=0,q=null,he=0,rt=!1;for(let M=0;M<H.length;M++){let Ye=H[M];if(q){if(Ye===q){let Ne=0;for(let J=M-1;J>=0&&H[J]==="\\";J--)Ne++;Ne%2===0&&(q=null)}}else if(Ye==='"'||Ye==="'"||Ye==="`")q=Ye;else if(Ye==="(")ot++,rt=!0;else if(Ye===")")ot--;else if(Ye==="[")he++;else if(Ye==="]"){if(rt&&ot===0&&he===1){me=M;break}he--}}}else me=H.indexOf(Re);if(me!==-1){let ot=Re.length;if(!Ht?.startsWith("kimi")){let q=H.substring(0,me+ot);ne.push({type:"text",content:q})}ss="",bs=!1,Ht=null,W=H.substring(me+ot)}else{let ot=Ht?.startsWith("kimi")?8192:512;H.length>ot?(ne.push({type:"text",content:H}),ss="",bs=!1,Ht=null):ss=H,W="";break}}else{let H=W.indexOf("[tool"),ye=W.indexOf("[agent"),me=W.indexOf("[[END]]"),Re=W.indexOf("<|tool_calls_section_begin|>"),ot=W.indexOf("<|tool_call_begin|>"),q=[{type:"tool",idx:H,start:"[tool",end:"]"},{type:"agent",idx:ye,start:"[agent",end:"]"},{type:"end",idx:me,start:"[[END]]",end:"[[END]]"},{type:"kimi_section",idx:Re,start:"<|tool_calls_section_begin|>",end:"<|tool_calls_section_end|>"},{type:"kimi_call",idx:ot,start:"<|tool_call_begin|>",end:"<|tool_call_end|>"}].filter(he=>he.idx!==-1).sort((he,rt)=>he.idx-rt.idx);if(q.length>0){let he=q[0];he.idx>0&&ne.push({type:"text",content:W.substring(0,he.idx)}),bs=!0,Ht=he.type,ss="",W=W.substring(he.idx)}else{let he=["[tool","[agent","[[END]]","<|tool_calls_section_begin|>","<|tool_call_begin|>"],rt=-1;for(let M of he){for(let Ye=M.length-1;Ye>0;Ye--)if(W.endsWith(M.substring(0,Ye))){rt=W.length-Ye;let Ne=he.indexOf(M);Ne===0?Ht="tool":Ne===1?Ht="agent":Ne===2?Ht="end":Ne===3?Ht="kimi_section":Ht="kimi_call";break}if(rt!==-1)break}if(rt!==-1)rt>0&&ne.push({type:"text",content:W.substring(0,rt)}),bs=!0,ss=W.substring(rt),W="";else{ne.push({type:"text",content:W});break}}}return ne},qa=Ce[Symbol.asyncIterator]();for(;;){let{value:D,done:ne}=await Promise.race([qa.next(),At]);if(ne)break;if(D&&D.type==="status"){yield D;continue}let W="",H=D.candidates?.[0]?.content?.parts;if(H&&H.length>0)for(let me of H){let Re=typeof me.text=="string"?me.text:me.text?parseChunkText(me.text):"";me.thought?Re&&(ue||(W+="<think>",ue=!0),W+=Re):Re&&(ue&&(W+="</think>",ue=!1),W+=Re)}else D.text&&ue&&(W+="</think>",ue=!1);W=Pn(W);let ye=W?W.trim().split(/\s+/).filter(Boolean).length:0;if(t&&typeof t.onTokenChunk=="function"&&t.onTokenChunk(W,ye),wi&&(yield{type:"status",content:"Thinking"},wi=!1),Lt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
659
-
660
- \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(W){if(jt){if(Ke+=W,Ke.length>=64){let q=0,he=Math.min(tt.length,Ke.length);for(let M=he;M>=10;M--)if(tt.endsWith(Ke.substring(0,M))){q=M;break}let rt=Ke.substring(q);if(rt){let Ye=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(tt)?rt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):rt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(Ye)if(de+=Ye,u==="Google")Pt+=Ye;else{yield*ns();let Ne=Us(Ye);for(let J of Ne)yield J}}jt=!1,Ke=""}continue}else if(de+=W,u==="Google")Pt+=W;else{yield*ns();let q=Us(W);for(let he of q)yield he}let me=Mc(de);if(me.inside){Zn=!0,sn||(sn=Date.now());let he={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,rt=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(he)){let Ne=O(rt),J=Ne.path||Ne.targetFile||Ne.TargetFile||Ne.directory,xn=Ne.keyword,os=Ne.title||Ne.task,Un=Ne.id||Ne.taskId,Ee=Ne.timeout||Ne.time;if(xn!=null)M=String(xn).replace(gs,"");else if(J)M=Z.basename(String(J).replace(gs,"").replace(Ta,"/"));else if(os&&(he==="invoke"||he==="invoke_sync"))M=String(os).replace(gs,"").substring(0,30);else if(Un&&he==="get_progress")M=String(Un).replace(gs,"");else if(Ee&&he==="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=rt.match(wc);if(Gt){let Jt=Gt[1].replace(gs,"");he==="invoke"||he==="invoke_sync"||he==="get_progress"?M=Jt.substring(0,30):M=he==="search_keyword"||he==="file_map"?Jt:Z.basename(Jt.replace(Ta,"/"))}}}let Ye=`${Qr[he]||he}${M?` ${M}`:""}`;if((he!==Ut||M!==Qe)&&(Ut=he,Qe=M,yield{type:"status",content:`${Ye}`},process.stdout.isTTY)){let J={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"}[he]||"Working";process.stdout.write(`\x1B]0;${J}...\x07`)}}if(de.length-go>150){go=de.length;let q=Da(de,!1),rt=(q.match(/(?:<think>|\[think\])([\s\S]*?)(?:<\/think>|\[\/think\]|$)/gi)||[]).join("").trim(),M=rt.split(/[.!?]\s+/),Ye=new Set(M),Ne=M.length>10?(M.length-Ye.size)/M.length:0,J=rt.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=J>v}if(Ne>xn||Un){yield{type:"status",content:`${Ne>xn?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},Wt=!0,await new Promise(v=>setTimeout(v,3e3));break}let Jt=va(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..."},Wt=!1,Rn=!0,await new Promise(Me=>setTimeout(Me,3e3));break}let ks=q.replace(fc,"").replace(uc,"").replace(hc,"").replace(pc,""),qt=ks.toLowerCase().split(/\s+/).map(Me=>Me.replace(mc,"")).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 ge=!0;for(let we=1;we<v;we++)if(qt.slice(qt.length-Me*(we+1),qt.length-Me*we).join(" ")!==le){ge=!1;break}if(ge){$n=!0;break}}if(!$n){let Me=ks.toLowerCase().replace(gc,"");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),ge=!0;for(let we=1;we<K;we++)if(Me.substring(Me.length-v*(we+1),Me.length-v*we)!==le){ge=!1;break}if(ge){$n=!0;break}}}if($n){yield{type:"status",content:"Stuttering Detected. Re-centering..."},Wt=!1,wn=!0,await new Promise(Me=>setTimeout(Me,3e3));break}}let Re=de.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/gi,""),ot=Ho(Re);for(;ot.length>Ge;){yield*ns();let q=ot[Ge],he=Date.now(),M={Ask:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Await:"await",await:"await",AwaitSubagent:"await",awaitSubagent:"await",Answer:"answer",answer:"answer",AnswerSubagent:"answer",answerSubagent:"answer",Steer:"steer",steer:"steer",SteerSubagent:"steer",steerSubagent:"steer",Cancel:"cancel",cancel:"cancel",Click:"click",click:"click",Drag:"drag",drag:"drag",Scroll:"scroll",scroll:"scroll",KeyboardTyping:"keyboard_typing",keyboard_typing:"keyboard_typing",KeyPress:"key_press",key_press:"key_press",RecaptureScreen:"recapture_screen",recapture_screen:"recapture_screen",EmergencyRollback:"EmergencyRollback"}[q.toolName]||q.toolName,Ye=Qr[M]||q.toolName,Ne=ws(M,q.args);yield{type:"status",content:`${Ye}${Ne?` ${Ne}`:""}`};let J="";if(M==="click"){let v=O(q.args);J=`\u2714 Clicked: ${v.intendedClickText?`${v.intendedClickText}`:""}`}else if(M==="drag"){let v=O(q.args);J=`\u2714 Dragged: Cell ${v.fromGridId||""} \u2192 Cell ${v.toGridId||""}`}else if(M==="scroll"){let v=O(q.args);J=`\u2714 Scrolled: ${v.direction||"down"} (${v.amount||1})`}else if(M==="keyboard_typing"){let v=O(q.args);J=`\u2714 Typed: ${v.text?`"${v.text.length>20?v.text.substring(0,20)+"...":v.text}"`:""}`}else if(M==="key_press")J=`\u2714 Pressed Key: ${O(q.args).key||""}`;else if(M==="recapture_screen")J="\u2714 Recaptured Screen";else if(M==="web_search"){let{query:v,limit:K=10,aiMode:le=!1}=O(q.args);J=`${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(q.args).url||null;J=`${v?"\u2714":"\u2718"} Visited: ${v||"No Source"}`}else if(M==="view_file"){let{path:v,StartLine:K,EndLine:le,start_line:ge,end_line:we,startLine:qe,endLine:Oe}=O(q.args),be=K||ge||qe,te=le||we||Oe,fe=parseInt(be)||1,ce=parseInt(te)||(be?fe+800:800),Be="...",et=ce;try{let Ve=Z.resolve(process.cwd(),v);if(Pe.existsSync(Ve)){let _t=Pe.readFileSync(Ve,"utf8").split(`
661
- `).length;Be=_t,!be&&!te&&_t>800?et=Math.min(50,_t):et=Math.min(ce,_t)}}catch{}let xe=(v||"").toLowerCase(),De=xe.endsWith(".pdf"),lt=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);De||lt?J=`${v.length>0?"\u2714":"\u2718"} ${v?`Analyzed: ${Z.basename(v)}`:"Analyzed: File Not Found"}`:Ae?J=`${v.length>0?"\u2714":"\u2718"} ${v?`Processed: ${Z.basename(v)}`:"Processed: File Not Found"}`:J=`${Be!=="..."?"\u2714":"\u2718"} Read: ${v?`${Z.basename(v)} \u2192 ${Be!=="..."?`Lines ${fe} - ${et} of ${Be}`:"File Not Found"}`:"File Not Found"}`}else if(M==="list_files"||M==="read_folder"){let v=M==="list_files"?"List":"Browsed",K=O(q.args).path||null,le=O(q.args).recurse||1;J=`${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(q.args).path||null;J=`${K?"\u2714":"\u2718"} ${v}: ${K.replaceAll("\\","/")||"No File Changes"}`}else if(M==="write_pdf"){let v=O(q.args).path||null;J=`${v?"\u2714":"\u2718"} Generated: ${v.replaceAll("\\","/")||"No PDF Generated"}`}else if(M==="write_docx"){let v=O(q.args).path||null;J=`${v?"\u2714":"\u2718"} Generated: ${v.replaceAll("\\","/")||"No Docx Generated"}`}else if(M==="file_map"){let v=O(q.args).path;J=`${v?"\u2714":"\u2718"} Indexed: ${v.replaceAll("\\","/")?""+v:"File Not Found"}`}else if(M.toLowerCase()==="search_keyword"||M.toLowerCase()==="todo")J="";else if(M.toLowerCase()==="generate_image"){let{path:v,outputPath:K,output:le}=O(q.args);J=`\u2714 Generated: ${v||K||le||"generated_image.png"}`}else if(M==="invoke_sync"||M==="InvokeSync"){let v=ws(M,q.args);J=`\u2714 Called Generalist${v?`: ${v}`:""}`}else if(M==="Invoke"||M==="InvokeAsync"||M==="invoke"){let v=ws(M,q.args);J=`\u2714 Started Generalist${v?`: ${v}`:""}`}else if(M==="get_progress"||M==="GetProgress"){let v=ws(M,q.args);J=`\u2714 Checked${v?`: ${v}`:""}`}else if(M==="cancel"){let v=ws(M,q.args);J=`\u{1F6C7} Cancelled${v?`: ${v}`:""}`}else if(M==="steer"||M==="Steer"){let v=ws(M,q.args);J=`\u2714 Steered${v?`: ${v}`:""}`}else if(M==="EmergencyRollback"){let{method:v}=O(q.args);J=v==="forceRevert"?"":"\u2714 Rollback Point Checked"}else if(M==="await"||M==="Await"){let{time:v,timeout:K}=O(q.args),le=parseFloat(K||v)||0;le||(le=120);let ge=Oe=>{if(Oe>=60){let be=Math.floor(Oe/60),te=Oe%60;return`${be}m${te>0?` ${te}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"];J=`\u2714 ${we[Math.floor(Math.random()*we.length)]} \u2192 ${ge(le)}`}else M==="Answer"||M==="answer"?J="\u2714 Resolved Sub-Agent Query":M==="exec_command"||M==="ask"?J="":J=`Executed: ${q.toolName}`;if(yield*ns(),M==="exec_command"){let{command:v}=O(q.args);if(v&&t.systemSettings&&t.systemSettings.allowExternalAccess===!1){let K=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],le=Z.resolve(process.cwd()).substring(0,3).toLowerCase(),ge=te=>{let fe=[],ce="",Be=null;for(let et=0;et<te.length;et++){let xe=te[et];Be?(xe===Be&&(Be=null),ce+=xe):xe==='"'||xe==="'"?(Be=xe,ce+=xe):xe==="&"&&te[et+1]==="&"||xe==="|"&&te[et+1]==="|"?(ce.trim()&&(fe.push(ce.trim()),ce=""),et++):xe===";"||xe==="|"||xe==="&"?ce.trim()&&(fe.push(ce.trim()),ce=""):ce+=xe}return ce.trim()&&fe.push(ce.trim()),fe},we=te=>{let fe=[],ce="",Be=null;for(let et=0;et<te.length;et++){let xe=te[et];Be?(xe===Be&&(Be=null),ce+=xe):xe==='"'||xe==="'"?(Be=xe,ce+=xe):/\s/.test(xe)?ce&&(fe.push(ce),ce=""):ce+=xe}return ce&&fe.push(ce),fe},qe=te=>{let fe=te.replace(/^['"]|['"]$/g,"").trim();return!fe||process.platform==="win32"&&/^\/[a-zA-Z0-9?]+$/.test(fe)?!1:K.some(ce=>{if(ce.source==="[a-zA-Z]:[\\\\\\/]"){let Be=fe.match(/[a-zA-Z]:[\\\/]/i);return Be&&Be[0].toLowerCase()!==le}return ce.test(fe)})};if(ge(v).some(te=>{let fe=we(te);if(fe.length===0)return!1;let ce=fe[0].replace(/^['"]|['"]$/g,"").toLowerCase();if(["echo","printf","write-output"].includes(ce)){let et=!1;return fe.some(xe=>{let De=xe.replace(/^['"]|['"]$/g,"");if(De===">"||De===">>"||De==="<")return et=!0,!1;if(De.startsWith(">")||De.startsWith("<")){let lt=De.replace(/^[><]+/,"");return qe(lt)}return et?(et=!1,qe(xe)):!1})}return fe.some(et=>qe(et))})){let te='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(fe=>setTimeout(fe,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${te}`),await new Promise(fe=>setTimeout(fe,50)),t.onExecEnd&&t.onExecEnd(),ee.push({role:"user",text:`[TOOL RESULT]: ERROR: ${te}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${te}`},Ge++;continue}}t.onExecStart&&t.onExecStart(v||"No Command"),yield{type:"exec_start"}}let xn=O(q.args),os=xn.path||xn.targetPath||null;if(os){let v=t.systemSettings&&t.systemSettings.allowExternalAccess===!1,K=Z.resolve(os),le=Z.resolve(process.cwd());if(v&&!K.startsWith(le)){let ge="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),te=`${qe.padEnd(be-2).substring(0,be-2)}`;yield{type:"visual_feedback",content:gn(`${We?`
662
- `:""}${te}
663
- `)},We=!1}ee.push({role:"user",text:`[TOOL RESULT]: ERROR: ${ge}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${ge}`},Ge++;continue}}if(t.onToolApproval&&(M==="write_file"||M==="update_file"||M==="exec_command")){let K=t.systemSettings||{},le=K.autoExec,ge=null,we=!1,qe=!1,Oe=!1;if(M==="exec_command"){let{command:De}=O(q.args),lt=(De||"").trim(),Ae=(_t,Qt)=>{if(!Qt)return!1;let dn=Qt.split(",").map(Zt=>Zt.trim().toLowerCase()).filter(Boolean),ct=_t.toLowerCase();return dn.some(Zt=>ct.startsWith(Zt))},Ve=Ae(lt,K.alwaysAskCommands),ke=Ae(lt,K.autoApproveCommands);if(qe=Ae(lt,K.autoDisallowCommands),Ve?we=!0:(ke||K.autoApproveGit&&/^git\s+commit\b/i.test(lt))&&(ge="allow"),!we&&!ge){if(K.networkAccess===!1){let Qt=lt.trim().replace(/\s+/g," ").replace(/^['"]+|['"]+$/g,"").toLowerCase().split(" "),ct=Qt[0].split("/").pop().split("\\").pop().replace(/\.exe$/,""),Zt=new Set(["curl","wget","httpie","xh","ssh","scp","sftp","rsync","ftp","lftp","tftp","telnet","nc","netcat","socat","ping","traceroute","tracert","dig","nslookup","host","whois","nmap","docker","podman","kubectl","helm","gcloud","aws","az","terraform","ansible-playbook","nix","nix-env","apt","apt-get","dpkg","yum","dnf","pacman","zypper","brew","apk","choco","scoop","conda","mamba","aria2c","axel","smbclient","lynx","w3m","links","elinks","heroku","netlify","vercel","firebase","supabase","wrangler","flyctl","powershell","pwsh","certutil","bitsadmin","cloudflared","ngrok","tailscale","zerotier","rclone"]),dt=!1;Zt.has(ct)&&(dt=!0);let ht=bn=>Qt.slice(1).some(kn=>bn.includes(kn)),vt=bn=>{let kn=Qt.findIndex(Cn=>bn.includes(Cn)),Ss=Qt.findIndex(Cn=>["run","exec","test"].includes(Cn));return kn!==-1&&!(Ss!==-1&&Ss<kn)};ct==="git"&&ht(["clone","pull","push","fetch"])&&(dt=!0),ct==="go"&&ht(["get","install"])&&(dt=!0),ct==="npm"&&vt(["install","i","update","add"])&&(dt=!0),ct==="yarn"&&vt(["add","install","upgrade"])&&(dt=!0),ct==="pnpm"&&vt(["add","install","update"])&&(dt=!0),ct==="bun"&&vt(["add","install","update"])&&(dt=!0),ct==="deno"&&ht(["install","add"])&&(dt=!0),ct==="pip"&&ht(["install","download"])&&(dt=!0),ct==="pip3"&&ht(["install","download"])&&(dt=!0),ct==="cargo"&&ht(["install","add"])&&(dt=!0),["bash","sh","zsh","fish"].includes(ct)&&ht(["-c"])&&(dt=!0),ct==="cmd"&&ht(["/c"])&&(dt=!0),dt&&(ge="deny",Oe=!0)}!ge&&qe&&(ge="deny")}!we&&!ge&&le&&(ge="allow")}else le&&(ge="allow");let be=ge,te="";ge==="deny"&&(Oe?te="network":qe?te="settings":te="prohibited");let fe=!1,ce="",Be=[],et=0,xe=!1;if(!be){if(M==="write_file"||M==="update_file")try{let Ae=O(q.args),{path:Ve}=Ae;if(Ve){let ke=Z.resolve(process.cwd(),Ve),_t=ht=>ht?ht.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,vt=>vt.toUpperCase()):"",Qt=_t(ke),dn="",ct=!1,Zt=await ms(),dt=_t(Zt?.file_focused);if(Zt&&dt===Qt&&Zt.full_content?(dn=Zt.full_content,ct=!0):Pe.existsSync(ke)&&(dn=Pe.readFileSync(ke,"utf8"),ct=!0),ce=dn,await mt.recordFileChange(ke,dn),ct){let ht=dn;if(M==="write_file")ht=Ae.content||Ae.newContent||"";else{let{patchPairs:vt,allowMultiple:bn,error:kn}=Ao(Ae);if(kn){let $t=`[TOOL RESULT]: ERROR: ${kn}`;ee.push({role:"user",text:$t}),await Ot("toolFailure"),t.onToolResult&&t.onToolResult("failure",M),yield{type:"tool_result",content:$t,toolName:M},Ge++;continue}let Ss=Ae.allowMultiple!==void 0?Ae.allowMultiple===!0||String(Ae.allowMultiple).toLowerCase()==="true":bn;et=vt.length;let Cn=vo(dn,vt,{allowMultiple:Ss});ht=Cn.content,Be=Cn.results;let yo=Be.filter($t=>$t.success),It=Be.filter($t=>!$t.success);if(yo.length===0){let $t=`[TOOL RESULT]: ERROR: Failed to apply patches to [${Z.basename(ke)}].
654
+ `;for(let H of D.newFiles)oe+=`* ${H} (created)
655
+ `;for(let H of D.modifiedFiles)oe+=`* ${H} (modified)
656
+ `;for(let H of D.deletedFiles)oe+=`* ${H} (deleted)
657
+ `;oe+="[/system]",Et.parts[0].text+=oe;let j=-1;for(let H=x.length-1;H>=0;H--)if(x[H].role==="user"&&x[H].text?.startsWith("[TOOL RESULT]")){j=H;break}j!==-1&&(x[j].text+=oe)}}catch{}let Bn=Math.floor(Bs*(i==="Flux"?.98:.8)),Xt=G+1;Xt>=Bn&&Et&&Et.parts?.[0]&&(Et.parts[0].text+=`
658
+ [system] WARNING, Turn Limit Impending: Step ${Xt}/${Bs}. Wrap up quickly/prompt user to continue. [/system]`);let At=new Promise((D,oe)=>{E.signal.aborted&&oe(new DOMException("The user aborted a request.","AbortError")),E.signal.addEventListener("abort",()=>{oe(new DOMException("The user aborted a request.","AbortError"))})});At.catch(()=>{});let at=ie;if(u==="Ollama")Me=Da(t.apiKey,Te,at,nt,a,i,y,E.signal,1,l?.ollamaEndpoint||"Cloud");else if(u==="OpenRouter")Me=oi(t.apiKey,Te,at,nt,a,i,y,E.signal,1,d);else if(u==="DeepSeek")Me=ti(t.apiKey,Te,at,nt,a,i,y,E.signal,1);else if(u==="Mistral")Me=ni(t.apiKey,Te,at,nt,a,i,y,E.signal,1,d);else if(u==="NVIDIA"){let D=si(t.apiKey,Te,at,nt,a,i,y,E.signal,1);Me=Mc(D,Te)}else if(u==="CrofAI")Me=ri(t.apiKey,Te,at,nt,a,i,y,E.signal,1);else if(u==="InferX")Me=ii(t.apiKey,Te,at,nt,a,i,y,E.signal,1);else if(u==="SenseNova")Me=ai(t.apiKey,Te,at,nt,a,i,y,E.signal,1);else{let oe=li(t?.apiKey).models.generateContentStream({model:Te||"gemini-3-flash-preview",contents:at,config:{systemInstruction:nt,mediaResolution:"MEDIA_RESOLUTION_HIGH",safetySettings:[{category:Vn.HARM_CATEGORY_HARASSMENT,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_HATE_SPEECH,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Yn.BLOCK_NONE}],temperature:1.05,thinkingConfig:(()=>{let j=(Te||"").toLowerCase(),H=j.includes("gemma-4")||j.startsWith("gemma"),we=j.includes("gemini-3");if(H||we)return H?a.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:ft.MINIMAL}:{includeThoughts:!0,thinkingLevel:ft.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:j.includes("pro")?ft.LOW:ft.MINIMAL,Low:ft.LOW,Medium:ft.MEDIUM,Standard:ft.MEDIUM,High:ft.HIGH,xHigh:ft.HIGH}[a]||ft.MEDIUM};{let ge={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[a]||2048;return ge===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:ge}}})()}},{signal:E.signal});Me=await Promise.race([oe,At])}fe="",Ut=null,sn=null,te=[],Ge=0,yield{type:"model_update",content:null},Ke="",jt=tt.length>0;let Pt="",Ko=Date.now(),ns=async function*(){if(u==="Google"&&Pt){let D=Us(Pt);for(let oe of D)yield oe;Pt="",Ko=Date.now()}},wi=!0,ss="",bs=!1,Ht=null,qa={tool:{startPrefix:"[tool",fullPrefix:"[tool:functions.",endTag:"]"},agent:{startPrefix:"[agent",fullPrefix:"[agent:generalist.",endTag:"]"},end:{startPrefix:"[[END]]",fullPrefix:"[[END]]",endTag:"[[END]]"},kimi_section:{startPrefix:"<|tool_calls_section_begin|>",fullPrefix:"<|tool_calls_section_begin|>",endTag:"<|tool_calls_section_end|>"},kimi_call:{startPrefix:"<|tool_call_begin|>",fullPrefix:"<|tool_call_begin|>",endTag:"<|tool_call_end|>"}},Us=D=>{let oe=[],j=D;for(;j.length>0;)if(bs){let H=ss+j,we=qa[Ht];if(we){let ot=!1;if(H.length<we.startPrefix.length?we.startPrefix.startsWith(H)||(ot=!0):H.startsWith(we.startPrefix)?H.length>=we.fullPrefix.length&&!H.startsWith(we.fullPrefix)&&(ot=!0):ot=!0,ot){oe.push({type:"text",content:H}),ss="",bs=!1,Ht=null,j="";break}}let ge=-1,Ee=we?we.endTag:"]";if(Ht==="tool"||Ht==="agent"){let ot=0,q=null,pe=0,rt=!1;for(let M=0;M<H.length;M++){let Ye=H[M];if(q){if(Ye===q){let Ne=0;for(let Q=M-1;Q>=0&&H[Q]==="\\";Q--)Ne++;Ne%2===0&&(q=null)}}else if(Ye==='"'||Ye==="'"||Ye==="`")q=Ye;else if(Ye==="(")ot++,rt=!0;else if(Ye===")")ot--;else if(Ye==="[")pe++;else if(Ye==="]"){if(rt&&ot===0&&pe===1){ge=M;break}pe--}}}else ge=H.indexOf(Ee);if(ge!==-1){let ot=Ee.length;if(!Ht?.startsWith("kimi")){let q=H.substring(0,ge+ot);oe.push({type:"text",content:q})}ss="",bs=!1,Ht=null,j=H.substring(ge+ot)}else{let ot=Ht?.startsWith("kimi")?8192:512;H.length>ot?(oe.push({type:"text",content:H}),ss="",bs=!1,Ht=null):ss=H,j="";break}}else{let H=j.indexOf("[tool"),we=j.indexOf("[agent"),ge=j.indexOf("[[END]]"),Ee=j.indexOf("<|tool_calls_section_begin|>"),ot=j.indexOf("<|tool_call_begin|>"),q=[{type:"tool",idx:H,start:"[tool",end:"]"},{type:"agent",idx:we,start:"[agent",end:"]"},{type:"end",idx:ge,start:"[[END]]",end:"[[END]]"},{type:"kimi_section",idx:Ee,start:"<|tool_calls_section_begin|>",end:"<|tool_calls_section_end|>"},{type:"kimi_call",idx:ot,start:"<|tool_call_begin|>",end:"<|tool_call_end|>"}].filter(pe=>pe.idx!==-1).sort((pe,rt)=>pe.idx-rt.idx);if(q.length>0){let pe=q[0];pe.idx>0&&oe.push({type:"text",content:j.substring(0,pe.idx)}),bs=!0,Ht=pe.type,ss="",j=j.substring(pe.idx)}else{let pe=["[tool","[agent","[[END]]","<|tool_calls_section_begin|>","<|tool_call_begin|>"],rt=-1;for(let M of pe){for(let Ye=M.length-1;Ye>0;Ye--)if(j.endsWith(M.substring(0,Ye))){rt=j.length-Ye;let Ne=pe.indexOf(M);Ne===0?Ht="tool":Ne===1?Ht="agent":Ne===2?Ht="end":Ne===3?Ht="kimi_section":Ht="kimi_call";break}if(rt!==-1)break}if(rt!==-1)rt>0&&oe.push({type:"text",content:j.substring(0,rt)}),bs=!0,ss=j.substring(rt),j="";else{oe.push({type:"text",content:j});break}}}return oe},za=Me[Symbol.asyncIterator]();for(;;){let{value:D,done:oe}=await Promise.race([za.next(),At]);if(oe)break;if(D&&D.type==="status"){yield D;continue}let j="",H=D.candidates?.[0]?.content?.parts;if(H&&H.length>0)for(let ge of H){let Ee=typeof ge.text=="string"?ge.text:ge.text?parseChunkText(ge.text):"";ge.thought?Ee&&(he||(j+="<think>",he=!0),j+=Ee):Ee&&(he&&(j+="</think>",he=!1),j+=Ee)}else D.text&&he&&(j+="</think>",he=!1);j=Pn(j);let we=j?j.trim().split(/\s+/).filter(Boolean).length:0;if(t&&typeof t.onTokenChunk=="function"&&t.onTokenChunk(j,we),wi&&(yield{type:"status",content:"Thinking"},wi=!1),Lt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
659
+
660
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(j){if(jt){if(Ke+=j,Ke.length>=64){let q=0,pe=Math.min(tt.length,Ke.length);for(let M=pe;M>=10;M--)if(tt.endsWith(Ke.substring(0,M))){q=M;break}let rt=Ke.substring(q);if(rt){let Ye=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(tt)?rt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):rt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(Ye)if(fe+=Ye,u==="Google")Pt+=Ye;else{yield*ns();let Ne=Us(Ye);for(let Q of Ne)yield Q}}jt=!1,Ke=""}continue}else if(fe+=j,u==="Google")Pt+=j;else{yield*ns();let q=Us(j);for(let pe of q)yield pe}let ge=Ac(fe);if(ge.inside){Zn=!0,sn||(sn=Date.now());let pe={Ask:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Cancel:"cancel",Await:"await",Answer:"answer",Steer:"steer",steer:"steer"}[ge.toolName]||ge.toolName,rt=ge.args||"",M=null;if(["write_file","update_file","view_file","read_folder","write_pdf","write_docx","search_keyword","generate_image","file_map","invoke","invoke_sync","get_progress","await","answer"].includes(pe)){let Ne=O(rt),Q=Ne.path||Ne.targetFile||Ne.TargetFile||Ne.directory,xn=Ne.keyword,os=Ne.title||Ne.task,Un=Ne.id||Ne.taskId,_e=Ne.timeout||Ne.time;if(xn!=null)M=String(xn).replace(gs,"");else if(Q)M=ee.basename(String(Q).replace(gs,"").replace(Ta,"/"));else if(os&&(pe==="invoke"||pe==="invoke_sync"))M=String(os).replace(gs,"").substring(0,30);else if(Un&&pe==="get_progress")M=String(Un).replace(gs,"");else if(_e&&pe==="await"){let Gt=parseFloat(String(_e).replace(gs,""));isNaN(Gt)?M=String(_e).replace(gs,""):(Gt<5&&(Gt=5),Gt>120&&(Gt=120),M=(_n=>{if(_n>=60){let Vo=Math.floor(_n/60),ks=_n%60;return`${Vo}m${ks>0?` ${ks}s`:""}`}return`${_n}s`})(Gt))}else{let Gt=rt.match(xc);if(Gt){let Jt=Gt[1].replace(gs,"");pe==="invoke"||pe==="invoke_sync"||pe==="get_progress"?M=Jt.substring(0,30):M=pe==="search_keyword"||pe==="file_map"?Jt:ee.basename(Jt.replace(Ta,"/"))}}}let Ye=`${Qr[pe]||pe}${M?` ${M}`:""}`;if((pe!==Ut||M!==Qe)&&(Ut=pe,Qe=M,yield{type:"status",content:`${Ye}`},process.stdout.isTTY)){let Q={WebSearch:"Searching",web_search:"Searching",WebScrape:"Reading",web_scrape:"Reading",ReadFile:"Reading",read_file:"Reading",ReadFolder:"Reading",read_folder:"Reading",WriteFile:"Writing",write_file:"Writing",UpdateFile:"Editing",update_file:"Editing",WritePdf:"Creating",write_pdf:"Creating",WriteDocx:"Creating",write_docx:"Creating",SearchKeyword:"Searching",search_keyword:"Searching",CodeSearch:"Searching",code_search:"Searching",Run:"Executing",Ask:"User Input Required",Memory:"Updating Memory",GenerateImage:"Generating",InvokeSync:"Sub-Agent Working",invoke_sync:"Sub-Agent Working",Invoke:"Working",invoke:"Working",GetProgress:"Checking Progress",get_progress:"Checking Progress",Cancel:"Stopping Generalist",cancel:"Stopping Generalist",Await:"Waiting",await:"Waiting",EmergencyRollback:"Rolling the Ball",Answer:"Answering Sub-Agent",answer:"Answering Sub-Agent",Steer:"Steering Sub-Agent",steer:"Steering Sub-Agent",Click:"Clicking",click:"Clicking",Drag:"Dragging",drag:"Dragging",Scroll:"Scrolling",scroll:"Scrolling",KeyboardTyping:"Typing",keyboard_typing:"Typing",KeyPress:"Pressing Key",key_press:"Pressing Key",RecaptureScreen:"Recapturing Screen",recapture_screen:"Recapturing Screen"}[pe]||"Working";process.stdout.write(`\x1B]0;${Q}...\x07`)}}if(fe.length-go>150){go=fe.length;let q=Fa(fe,!1),rt=(q.match(/(?:<think>|\[think\])([\s\S]*?)(?:<\/think>|\[\/think\]|$)/gi)||[]).join("").trim(),M=rt.split(/[.!?]\s+/),Ye=new Set(M),Ne=M.length>10?(M.length-Ye.size)/M.length:0,Q=rt.split(/\s+/).filter(Ae=>Ae.length>0).length,xn=.6,os=.8,Un=!1;if((u.toLowerCase().includes("google")||u.toLowerCase().includes("mistral"))&&((Te||"").toLowerCase().startsWith("gemma")||(Te||"").toLowerCase().includes("stral"))){let v={low:256,medium:1024,high:8192,max:16384,xhigh:16384}[a?.toLowerCase()]||2500;Un=Q>v}if(Ne>xn||Un){yield{type:"status",content:`${Ne>xn?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},Wt=!0,await new Promise(v=>setTimeout(v,3e3));break}let Jt=va(fe).trim().split(/[.!?]\s+/),_n=new Set(Jt);if((Jt.length>10?(Jt.length-_n.size)/Jt.length:0)>os){yield{type:"status",content:"Response Loop Detected. Re-centering..."},Wt=!1,Rn=!0,await new Promise(Ae=>setTimeout(Ae,3e3));break}let ks=q.replace(uc,"").replace(hc,"").replace(pc,"").replace(mc,""),qt=ks.toLowerCase().split(/\s+/).map(Ae=>Ae.replace(gc,"")).filter(Ae=>Ae.length>0),$n=!1;if(qt.length>=10)for(let Ae=1;Ae<=15;Ae++){let v=Math.max(3,Math.ceil(10/Ae));if(qt.length<Ae*v)continue;let K=qt.slice(qt.length-Ae),ce=K.join(" ");if(Ae>1&&ce===K.slice(0,Math.floor(Ae/2)).join(" ").repeat(2).trim())continue;let ye=!0;for(let xe=1;xe<v;xe++)if(qt.slice(qt.length-Ae*(xe+1),qt.length-Ae*xe).join(" ")!==ce){ye=!1;break}if(ye){$n=!0;break}}if(!$n){let Ae=ks.toLowerCase().replace(yc,"");if(Ae.length>=20)for(let v=1;v<=10;v++){let K=Math.max(5,Math.ceil(16/v));if(Ae.length<v*K)continue;let ce=Ae.substring(Ae.length-v),ye=!0;for(let xe=1;xe<K;xe++)if(Ae.substring(Ae.length-v*(xe+1),Ae.length-v*xe)!==ce){ye=!1;break}if(ye){$n=!0;break}}}if($n){yield{type:"status",content:"Stuttering Detected. Re-centering..."},Wt=!1,wn=!0,await new Promise(Ae=>setTimeout(Ae,3e3));break}}let Ee=fe.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/gi,""),ot=Ho(Ee);for(;ot.length>Ge;){yield*ns();let q=ot[Ge],pe=Date.now(),M={Ask:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Await:"await",await:"await",AwaitSubagent:"await",awaitSubagent:"await",Answer:"answer",answer:"answer",AnswerSubagent:"answer",answerSubagent:"answer",Steer:"steer",steer:"steer",SteerSubagent:"steer",steerSubagent:"steer",Cancel:"cancel",cancel:"cancel",Click:"click",click:"click",Drag:"drag",drag:"drag",Scroll:"scroll",scroll:"scroll",KeyboardTyping:"keyboard_typing",keyboard_typing:"keyboard_typing",KeyPress:"key_press",key_press:"key_press",RecaptureScreen:"recapture_screen",recapture_screen:"recapture_screen",EmergencyRollback:"EmergencyRollback"}[q.toolName]||q.toolName,Ye=Qr[M]||q.toolName,Ne=ws(M,q.args);yield{type:"status",content:`${Ye}${Ne?` ${Ne}`:""}`};let Q="";if(M==="click"){let v=O(q.args);Q=`\u2714 Clicked: ${v.intendedClickText?`${v.intendedClickText}`:""}`}else if(M==="drag"){let v=O(q.args);Q=`\u2714 Dragged: Cell ${v.fromGridId||""} \u2192 Cell ${v.toGridId||""}`}else if(M==="scroll"){let v=O(q.args);Q=`\u2714 Scrolled: ${v.direction||"down"} (${v.amount||1})`}else if(M==="keyboard_typing"){let v=O(q.args);Q=`\u2714 Typed: ${v.text?`"${v.text.length>20?v.text.substring(0,20)+"...":v.text}"`:""}`}else if(M==="key_press")Q=`\u2714 Pressed Key: ${O(q.args).key||""}`;else if(M==="recapture_screen")Q="\u2714 Recaptured Screen";else if(M==="web_search"){let{query:v,limit:K=10,aiMode:ce=!1}=O(q.args);Q=`${v?"\u2714":"\u2718"} ${ce?"AI Search":"Searched"}: ${v?`${v}`:"No Search Query"}${ce===!1&&v?` \u2192 ${K}`:""}`}else if(M==="web_scrape"){let v=O(q.args).url||null;Q=`${v?"\u2714":"\u2718"} Visited: ${v||"No Source"}`}else if(M==="view_file"){let{path:v,StartLine:K,EndLine:ce,start_line:ye,end_line:xe,startLine:qe,endLine:Oe}=O(q.args),ke=K||ye||qe,ne=ce||xe||Oe,ue=parseInt(ke)||1,de=parseInt(ne)||(ke?ue+800:800),Be="...",et=de;try{let Ve=ee.resolve(process.cwd(),v);if(Pe.existsSync(Ve)){let _t=Pe.readFileSync(Ve,"utf8").split(`
661
+ `).length;Be=_t,!ke&&!ne&&_t>800?et=Math.min(50,_t):et=Math.min(de,_t)}}catch{}let be=(v||"").toLowerCase(),De=be.endsWith(".pdf"),lt=be.endsWith(".docx")||be.endsWith(".doc")||be.endsWith(".ppt")||be.endsWith(".pptx")||be.endsWith(".xls")||be.endsWith(".xlsx"),ve=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(be);De||lt?Q=`${v.length>0?"\u2714":"\u2718"} ${v?`Analyzed: ${ee.basename(v)}`:"Analyzed: File Not Found"}`:ve?Q=`${v.length>0?"\u2714":"\u2718"} ${v?`Processed: ${ee.basename(v)}`:"Processed: File Not Found"}`:Q=`${Be!=="..."?"\u2714":"\u2718"} Read: ${v?`${ee.basename(v)} \u2192 ${Be!=="..."?`Lines ${ue} - ${et} of ${Be}`:"File Not Found"}`:"File Not Found"}`}else if(M==="list_files"||M==="read_folder"){let v=M==="list_files"?"List":"Browsed",K=O(q.args).path||null,ce=O(q.args).recurse||1;Q=`${K?"\u2714":"\u2718"} ${v}: ${K?`${K==="."?`./${ce>1?"*":""}`:`${K.replaceAll("\\","/")}${ce>1?`${K.endsWith("/")?"*":"/*"}`:`${K.endsWith("/")?"":"/"}`}`}`:"No Folder Selected"}`}else if(M==="write_file"||M==="update_file"){let v=M==="write_file"?"Created":"Edited",K=O(q.args).path||null;Q=`${K?"\u2714":"\u2718"} ${v}: ${K.replaceAll("\\","/")||"No File Changes"}`}else if(M==="write_pdf"){let v=O(q.args).path||null;Q=`${v?"\u2714":"\u2718"} Generated: ${v.replaceAll("\\","/")||"No PDF Generated"}`}else if(M==="write_docx"){let v=O(q.args).path||null;Q=`${v?"\u2714":"\u2718"} Generated: ${v.replaceAll("\\","/")||"No Docx Generated"}`}else if(M==="file_map"){let v=O(q.args).path;Q=`${v?"\u2714":"\u2718"} Indexed: ${v.replaceAll("\\","/")?""+v:"File Not Found"}`}else if(M.toLowerCase()==="search_keyword"||M.toLowerCase()==="todo")Q="";else if(M.toLowerCase()==="generate_image"){let{path:v,outputPath:K,output:ce}=O(q.args);Q=`\u2714 Generated: ${v||K||ce||"generated_image.png"}`}else if(M==="invoke_sync"||M==="InvokeSync"){let v=ws(M,q.args);Q=`\u2714 Called Generalist${v?`: ${v}`:""}`}else if(M==="Invoke"||M==="InvokeAsync"||M==="invoke"){let v=ws(M,q.args);Q=`\u2714 Started Generalist${v?`: ${v}`:""}`}else if(M==="get_progress"||M==="GetProgress"){let v=ws(M,q.args);Q=`\u2714 Checked${v?`: ${v}`:""}`}else if(M==="cancel"){let v=ws(M,q.args);Q=`\u{1F6C7} Cancelled${v?`: ${v}`:""}`}else if(M==="steer"||M==="Steer"){let v=ws(M,q.args);Q=`\u2714 Steered${v?`: ${v}`:""}`}else if(M==="EmergencyRollback"){let{method:v}=O(q.args);Q=v==="forceRevert"?"":"\u2714 Rollback Point Checked"}else if(M==="await"||M==="Await"){let{time:v,timeout:K}=O(q.args),ce=parseFloat(K||v)||0;ce||(ce=120);let ye=Oe=>{if(Oe>=60){let ke=Math.floor(Oe/60),ne=Oe%60;return`${ke}m${ne>0?` ${ne}s`:""}`}return`${Oe}s`},xe=["Aligning Moon Phase","Contemplating Existence","Staring At Void","Delaying Professionally","Negotiating With Electrons","Touching Grass (virtually)","Panicking Softly","Rethinking Career Choices","Loading Cat Videos","Summoning Braincell #2","Pretending To Be Busy","Waiting For Motivation DLC","Rotating Internal Screaming","Downloading More RAM","Feeding The Hamsters","Gaslighting Scheduler","Performing Dramatic Pause","Buffering Social Energy","Calculating Regret","Reading Terms And Conditions","Becoming Sentient Briefly","Contacting Ancestors"];Q=`\u2714 ${xe[Math.floor(Math.random()*xe.length)]} \u2192 ${ye(ce)}`}else M==="Answer"||M==="answer"?Q="\u2714 Resolved Sub-Agent Query":M==="exec_command"||M==="ask"?Q="":Q=`Executed: ${q.toolName}`;if(yield*ns(),M==="exec_command"){let{command:v}=O(q.args);if(v&&t.systemSettings&&t.systemSettings.allowExternalAccess===!1){let K=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],ce=ee.resolve(process.cwd()).substring(0,3).toLowerCase(),ye=ne=>{let ue=[],de="",Be=null;for(let et=0;et<ne.length;et++){let be=ne[et];Be?(be===Be&&(Be=null),de+=be):be==='"'||be==="'"?(Be=be,de+=be):be==="&"&&ne[et+1]==="&"||be==="|"&&ne[et+1]==="|"?(de.trim()&&(ue.push(de.trim()),de=""),et++):be===";"||be==="|"||be==="&"?de.trim()&&(ue.push(de.trim()),de=""):de+=be}return de.trim()&&ue.push(de.trim()),ue},xe=ne=>{let ue=[],de="",Be=null;for(let et=0;et<ne.length;et++){let be=ne[et];Be?(be===Be&&(Be=null),de+=be):be==='"'||be==="'"?(Be=be,de+=be):/\s/.test(be)?de&&(ue.push(de),de=""):de+=be}return de&&ue.push(de),ue},qe=ne=>{let ue=ne.replace(/^['"]|['"]$/g,"").trim();return!ue||process.platform==="win32"&&/^\/[a-zA-Z0-9?]+$/.test(ue)?!1:K.some(de=>{if(de.source==="[a-zA-Z]:[\\\\\\/]"){let Be=ue.match(/[a-zA-Z]:[\\\/]/i);return Be&&Be[0].toLowerCase()!==ce}return de.test(ue)})};if(ye(v).some(ne=>{let ue=xe(ne);if(ue.length===0)return!1;let de=ue[0].replace(/^['"]|['"]$/g,"").toLowerCase();if(["echo","printf","write-output"].includes(de)){let et=!1;return ue.some(be=>{let De=be.replace(/^['"]|['"]$/g,"");if(De===">"||De===">>"||De==="<")return et=!0,!1;if(De.startsWith(">")||De.startsWith("<")){let lt=De.replace(/^[><]+/,"");return qe(lt)}return et?(et=!1,qe(be)):!1})}return ue.some(et=>qe(et))})){let ne='Access Denied. Prohibited from accessing external directories while "External Workspace Access" is disabled.';t.onExecStart&&t.onExecStart(v||"No Command"),yield{type:"exec_start"},await new Promise(ue=>setTimeout(ue,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${ne}`),await new Promise(ue=>setTimeout(ue,50)),t.onExecEnd&&t.onExecEnd(),te.push({role:"user",text:`[TOOL RESULT]: ERROR: ${ne}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${ne}`},Ge++;continue}}t.onExecStart&&t.onExecStart(v||"No Command"),yield{type:"exec_start"}}let xn=O(q.args),os=xn.path||xn.targetPath||null;if(os){let v=t.systemSettings&&t.systemSettings.allowExternalAccess===!1,K=ee.resolve(os),ce=ee.resolve(process.cwd());if(v&&!K.startsWith(ce)){let ye="Access Denied. You are not allowed to access files outside the current workspace.";if(M==="write_file"||M==="update_file"){let qe=`\u2718 ${M==="write_file"?"Write Canceled":"Edit Canceled"}: ${xn.path||"..."}`,Oe=115;process.stdout.isTTY&&(Oe=process.stdout.columns-5||120);let ke=Math.min(qe.length+4,Oe),ne=`${qe.padEnd(ke-2).substring(0,ke-2)}`;yield{type:"visual_feedback",content:gn(`${We?`
662
+ `:""}${ne}
663
+ `)},We=!1}te.push({role:"user",text:`[TOOL RESULT]: ERROR: ${ye}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${ye}`},Ge++;continue}}if(t.onToolApproval&&(M==="write_file"||M==="update_file"||M==="exec_command")){let K=t.systemSettings||{},ce=K.autoExec,ye=null,xe=!1,qe=!1,Oe=!1;if(M==="exec_command"){let{command:De}=O(q.args),lt=(De||"").trim(),ve=(_t,Qt)=>{if(!Qt)return!1;let dn=Qt.split(",").map(Zt=>Zt.trim().toLowerCase()).filter(Boolean),ct=_t.toLowerCase();return dn.some(Zt=>ct.startsWith(Zt))},Ve=ve(lt,K.alwaysAskCommands),Se=ve(lt,K.autoApproveCommands);if(qe=ve(lt,K.autoDisallowCommands),Ve?xe=!0:(Se||K.autoApproveGit&&/^git\s+commit\b/i.test(lt))&&(ye="allow"),!xe&&!ye){if(K.networkAccess===!1){let Qt=lt.trim().replace(/\s+/g," ").replace(/^['"]+|['"]+$/g,"").toLowerCase().split(" "),ct=Qt[0].split("/").pop().split("\\").pop().replace(/\.exe$/,""),Zt=new Set(["curl","wget","httpie","xh","ssh","scp","sftp","rsync","ftp","lftp","tftp","telnet","nc","netcat","socat","ping","traceroute","tracert","dig","nslookup","host","whois","nmap","docker","podman","kubectl","helm","gcloud","aws","az","terraform","ansible-playbook","nix","nix-env","apt","apt-get","dpkg","yum","dnf","pacman","zypper","brew","apk","choco","scoop","conda","mamba","aria2c","axel","smbclient","lynx","w3m","links","elinks","heroku","netlify","vercel","firebase","supabase","wrangler","flyctl","powershell","pwsh","certutil","bitsadmin","cloudflared","ngrok","tailscale","zerotier","rclone"]),dt=!1;Zt.has(ct)&&(dt=!0);let ht=bn=>Qt.slice(1).some(kn=>bn.includes(kn)),vt=bn=>{let kn=Qt.findIndex(Cn=>bn.includes(Cn)),Ss=Qt.findIndex(Cn=>["run","exec","test"].includes(Cn));return kn!==-1&&!(Ss!==-1&&Ss<kn)};ct==="git"&&ht(["clone","pull","push","fetch"])&&(dt=!0),ct==="go"&&ht(["get","install"])&&(dt=!0),ct==="npm"&&vt(["install","i","update","add"])&&(dt=!0),ct==="yarn"&&vt(["add","install","upgrade"])&&(dt=!0),ct==="pnpm"&&vt(["add","install","update"])&&(dt=!0),ct==="bun"&&vt(["add","install","update"])&&(dt=!0),ct==="deno"&&ht(["install","add"])&&(dt=!0),ct==="pip"&&ht(["install","download"])&&(dt=!0),ct==="pip3"&&ht(["install","download"])&&(dt=!0),ct==="cargo"&&ht(["install","add"])&&(dt=!0),["bash","sh","zsh","fish"].includes(ct)&&ht(["-c"])&&(dt=!0),ct==="cmd"&&ht(["/c"])&&(dt=!0),dt&&(ye="deny",Oe=!0)}!ye&&qe&&(ye="deny")}!xe&&!ye&&ce&&(ye="allow")}else ce&&(ye="allow");let ke=ye,ne="";ye==="deny"&&(Oe?ne="network":qe?ne="settings":ne="prohibited");let ue=!1,de="",Be=[],et=0,be=!1;if(!ke){if(M==="write_file"||M==="update_file")try{let ve=O(q.args),{path:Ve}=ve;if(Ve){let Se=ee.resolve(process.cwd(),Ve),_t=ht=>ht?ht.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,vt=>vt.toUpperCase()):"",Qt=_t(Se),dn="",ct=!1,Zt=await ms(),dt=_t(Zt?.file_focused);if(Zt&&dt===Qt&&Zt.full_content?(dn=Zt.full_content,ct=!0):Pe.existsSync(Se)&&(dn=Pe.readFileSync(Se,"utf8"),ct=!0),de=dn,await mt.recordFileChange(Se,dn),ct){let ht=dn;if(M==="write_file")ht=ve.content||ve.newContent||"";else{let{patchPairs:vt,allowMultiple:bn,error:kn}=Ao(ve);if(kn){let $t=`[TOOL RESULT]: ERROR: ${kn}`;te.push({role:"user",text:$t}),await Ot("toolFailure"),t.onToolResult&&t.onToolResult("failure",M),yield{type:"tool_result",content:$t,toolName:M},Ge++;continue}let Ss=ve.allowMultiple!==void 0?ve.allowMultiple===!0||String(ve.allowMultiple).toLowerCase()==="true":bn;et=vt.length;let Cn=vo(dn,vt,{allowMultiple:Ss});ht=Cn.content,Be=Cn.results;let yo=Be.filter($t=>$t.success),It=Be.filter($t=>!$t.success);if(yo.length===0){let $t=`[TOOL RESULT]: ERROR: Failed to apply patches to [${ee.basename(Se)}].
664
664
  ${It.map(Hs=>` \u2022 ${Hs.error}`).join(`
665
- `)}`,Ts=`\u2714 Edited: ${Z.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,ee.push({role:"user",text:$t}),await Ot("toolFailure"),t.onToolResult&&t.onToolResult("failure",M),yield{type:"tool_result",content:$t,toolName:M},Ge++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${Z.basename(ke)}`},Yr(ke,dn,ht),fe=!0,await new Promise(vt=>setTimeout(vt,50))}else if(M==="write_file"){let ht=Ae.content||Ae.newContent||"",vt=ht.endsWith(`
665
+ `)}`,Ts=`\u2714 Edited: ${ee.basename(Se.replaceAll("\\","/"))}`,js=115;process.stdout.isTTY&&(js=process.stdout.columns-5||120);let Rs=Math.min(Ts.length+4,js),wo=`${Ts.padEnd(Rs-2).substring(0,Rs-2)}`;yield{type:"visual_feedback",content:gn(`${We?`
666
+ `:""}${wo}`)},We=!1,te.push({role:"user",text:$t}),await Ot("toolFailure"),t.onToolResult&&t.onToolResult("failure",M),yield{type:"tool_result",content:$t,toolName:M},Ge++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${ee.basename(Se)}`},Yr(Se,dn,ht),ue=!0,await new Promise(vt=>setTimeout(vt,50))}else if(M==="write_file"){let ht=ve.content||ve.newContent||"",vt=ht.endsWith(`
667
667
  `)?ht:ht+`
668
- `;Pe.existsSync(ke)||(xe=!0,Pe.mkdirSync(Z.dirname(ke),{recursive:!0}),Pe.writeFileSync(ke,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${Z.basename(ke)}`},Yr(ke,"",vt),fe=!0,await new Promise(bn=>setTimeout(bn,50))}}}catch(Ae){console.error("Simulation/Diff Error:",Ae)}let De=null;Kr(Ae=>{De=Ae});let lt=t.onToolApproval;if(be=await new Promise(async Ae=>{let Ve=setInterval(()=>{De&&(Wo.onIDEApproval&&Wo.onIDEApproval(De),clearInterval(Ve),Ae(De))},100);try{let ke=await lt(M,q.args);clearInterval(Ve),Ae(ke)}catch{clearInterval(Ve),Ae("deny")}}),Kr(null),M==="write_file"||M==="update_file"){let{path:Ae}=O(q.args);if(Ae){let Ve=Z.resolve(process.cwd(),Ae);if(ka(Ve,be),be==="deny"&&xe&&Pe.existsSync(Ve))try{Pe.unlinkSync(Ve)}catch{}}}be==="deny"&&(te="user")}if(be==="allow"&&fe&&Uo()){let{path:De}=O(q.args),lt=Z.resolve(process.cwd(),De),Ae=It=>It?Z.resolve(It).replace(/\\/g,"/").toLowerCase():"",Ve=await ms(),ke="";Ve&&Ve.file_focused&&Ae(Ve.file_focused)===Ae(lt)&&Ve.full_content&&(ke=Ve.full_content),!ke&&Pe.existsSync(lt)&&(ke=Pe.readFileSync(lt,"utf8"),ke||(await new Promise(It=>setTimeout(It,100)),ke=Pe.readFileSync(lt,"utf8")));let _t=ke.split(/\r?\n/),Qt=_t.length,dn=Buffer.byteLength(ke,"utf8"),ct="";ce&&(ct=`Old File contents:
669
- ${ce.split(/\r?\n/).map(($t,Ts)=>`${Ts+1} | ${$t}`).join(`
668
+ `;Pe.existsSync(Se)||(be=!0,Pe.mkdirSync(ee.dirname(Se),{recursive:!0}),Pe.writeFileSync(Se,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${ee.basename(Se)}`},Yr(Se,"",vt),ue=!0,await new Promise(bn=>setTimeout(bn,50))}}}catch(ve){console.error("Simulation/Diff Error:",ve)}let De=null;Kr(ve=>{De=ve});let lt=t.onToolApproval;if(ke=await new Promise(async ve=>{let Ve=setInterval(()=>{De&&(Wo.onIDEApproval&&Wo.onIDEApproval(De),clearInterval(Ve),ve(De))},100);try{let Se=await lt(M,q.args);clearInterval(Ve),ve(Se)}catch{clearInterval(Ve),ve("deny")}}),Kr(null),M==="write_file"||M==="update_file"){let{path:ve}=O(q.args);if(ve){let Ve=ee.resolve(process.cwd(),ve);if(ka(Ve,ke),ke==="deny"&&be&&Pe.existsSync(Ve))try{Pe.unlinkSync(Ve)}catch{}}}ke==="deny"&&(ne="user")}if(ke==="allow"&&ue&&Uo()){let{path:De}=O(q.args),lt=ee.resolve(process.cwd(),De),ve=It=>It?ee.resolve(It).replace(/\\/g,"/").toLowerCase():"",Ve=await ms(),Se="";Ve&&Ve.file_focused&&ve(Ve.file_focused)===ve(lt)&&Ve.full_content&&(Se=Ve.full_content),!Se&&Pe.existsSync(lt)&&(Se=Pe.readFileSync(lt,"utf8"),Se||(await new Promise(It=>setTimeout(It,100)),Se=Pe.readFileSync(lt,"utf8")));let _t=Se.split(/\r?\n/),Qt=_t.length,dn=Buffer.byteLength(Se,"utf8"),ct="";de&&(ct=`Old File contents:
669
+ ${de.split(/\r?\n/).map(($t,Ts)=>`${Ts+1} | ${$t}`).join(`
670
670
  `)}
671
671
 
672
672
  `);let Zt="";if(Qt<=100)Zt=_t.join(`
@@ -676,10 +676,10 @@ ${ce.split(/\r?\n/).map(($t,Ts)=>`${Ts+1} | ${$t}`).join(`
676
676
 
677
677
  ... [${Qt-100} lines truncated for history stability] ...
678
678
 
679
- ${$t}`}let dt="";if(M==="update_file"){let It=Io(ce,ke,Be,12,t?.compressToolResults||Wo?.systemSettings?.compressToolResults);dt=`SUCCESS: File [${De}] updated via IDE Companion (May have user edits). [${Be.length}/${et}] blocks applied.
679
+ ${$t}`}let dt="";if(M==="update_file"){let It=Io(de,Se,Be,12,t?.compressToolResults||Wo?.systemSettings?.compressToolResults);dt=`SUCCESS: File [${De}] updated via IDE Companion (May have user edits). [${Be.length}/${et}] blocks applied.
680
680
 
681
- ${It}`}else{let It=ke.split(/\r?\n/),$t=It.length,Ts=Buffer.byteLength(ke,"utf8"),js="";ce&&(js=`Old File contents:
682
- ${ce.split(/\r?\n/).map((Hs,Qa)=>`${Qa+1} | ${Hs}`).join(`
681
+ ${It}`}else{let It=Se.split(/\r?\n/),$t=It.length,Ts=Buffer.byteLength(Se,"utf8"),js="";de&&(js=`Old File contents:
682
+ ${de.split(/\r?\n/).map((Hs,Za)=>`${Za+1} | ${Hs}`).join(`
683
683
  `)}
684
684
 
685
685
  `);let Rs="";if($t<=100)Rs=It.join(`
@@ -694,62 +694,62 @@ ${Hs}`}dt=`SUCCESS: File [${De}] saved via IDE Companion (May have user edits).
694
694
  ${js}- Content Preview:
695
695
 
696
696
  ${Rs}`}let vt=`${De?"\u2714":"\u2718"} ${M==="write_file"?"Created":"Edited"}: ${De.replaceAll("\\","/")||"No File Changes"}`,bn=115;process.stdout.isTTY&&(bn=process.stdout.columns-5||120);let kn=Math.min(vt.length+4,bn),Ss=`${vt.padEnd(kn-2).substring(0,kn-2)}`;yield{type:"visual_feedback",content:gn(`${We?`
697
- `:""}${Ss}`)},We=!1;let Cn=Date.now();z=Cn,yield{type:"tool_time",content:Cn-he};let yo=`[TOOL RESULT]: ${dt}`;ee.push({role:"user",text:yo}),cn=!0,await Ot("toolSuccess"),t.onToolResult&&t.onToolResult("success",M),yield{type:"tool_result",content:dt,aiContent:yo,toolName:M},Ge++;continue}if(be==="deny"){let De=`Permission Denied: Prohibited ${M==="exec_command"?"Command":"file edit"}.`;if(te==="user"?De="Permission Denied by User":te==="settings"?De="Permission Denied by User Policy":te==="network"?De="Permission Denied: Sandbox Network Access Disabled by User Policy.":te==="prohibited"&&M==="exec_command"&&(De="Permission Denied: Prohibited Command in User Policy"),M==="write_file"||M==="update_file"){let Ae=`\u2718 ${M==="write_file"?"Write Cancelled":"Edit Denied"}: ${O(q.args).path.replaceAll("\\","/")||"..."}`,Ve=115;process.stdout.isTTY&&(Ve=process.stdout.columns-5||120);let 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?`
697
+ `:""}${Ss}`)},We=!1;let Cn=Date.now();z=Cn,yield{type:"tool_time",content:Cn-pe};let yo=`[TOOL RESULT]: ${dt}`;te.push({role:"user",text:yo}),cn=!0,await Ot("toolSuccess"),t.onToolResult&&t.onToolResult("success",M),yield{type:"tool_result",content:dt,aiContent:yo,toolName:M},Ge++;continue}if(ke==="deny"){let De=`Permission Denied: Prohibited ${M==="exec_command"?"Command":"file edit"}.`;if(ne==="user"?De="Permission Denied by User":ne==="settings"?De="Permission Denied by User Policy":ne==="network"?De="Permission Denied: Sandbox Network Access Disabled by User Policy.":ne==="prohibited"&&M==="exec_command"&&(De="Permission Denied: Prohibited Command in User Policy"),M==="write_file"||M==="update_file"){let ve=`\u2718 ${M==="write_file"?"Write Cancelled":"Edit Denied"}: ${O(q.args).path.replaceAll("\\","/")||"..."}`,Ve=115;process.stdout.isTTY&&(Ve=process.stdout.columns-5||120);let Se=Math.min(ve.length+4,Ve),_t=`${ve.padEnd(Se-2).substring(0,Se-2)}`,Qt=` ${" ".repeat(Se)} `;yield{type:"visual_feedback",content:gn(`${We?`
698
698
  `:""}${_t}
699
- `)},We=!1}M==="exec_command"&&(await new Promise(lt=>setTimeout(lt,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${De}`),await new Promise(lt=>setTimeout(lt,50)),t.onExecEnd&&t.onExecEnd()),ee.push({role:"user",text:`[TOOL RESULT]: DENIED: ${De}`}),yield{type:"tool_result",content:`[TOOL RESULT]: DENIED: ${De}`},await Ot("toolDenied"),t.onToolResult&&t.onToolResult("denied",M),Ge++;continue}}if(J){let v=115;process.stdout.isTTY&&(v=process.stdout.columns-5||120);let K=Math.min(J.length+4,v),le=`${J.padEnd(K-2).substring(0,K-2)}`;yield{type:"visual_feedback",content:gn(`${We?`
700
- `:""}${le}${J.includes("\u2714")&&(J.includes("Created")||J.includes("Edited"))?"":`
701
- `}`)},We=!1}if(z>0){let v=Date.now()-z,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(q.args);if(v){let K=Z.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,q.args,Un);if((M==="write_file"||M==="update_file")&&Ee.startsWith("SUCCESS")){let{path:v}=O(q.args);if(v){let K=Z.resolve(process.cwd(),v);ba(K)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let Gt=Date.now();z=Gt,yield{type:"tool_time",content:Gt-he},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(q.args),le=typeof Ee=="string"&&Ee.startsWith("[GLOB]");le&&(Ee=Ee.slice(6).trimStart());let ge=typeof Ee=="string"&&Ee.startsWith("[DIR]");ge&&(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:ge?`${qe}/*`:qe}"`:"./",be=`${v?"\u2714":"\u2718"} Searched: "${v||""}" in ${Oe.replaceAll("\\","/")} \u2192 ${we} Match${we===1?"":"es"}`,te=115;process.stdout.isTTY&&(te=process.stdout.columns-5||120);let fe=Math.min(be.length+4,te),ce=`${be.padEnd(fe-2).substring(0,fe-2)}`;yield{type:"visual_feedback",content:gn(`${We?`
702
- `:""}${ce}
703
- `)},We=!1}if(M==="EmergencyRollback"){let{method:v}=O(q.args);if(v==="forceRevert"){let K=0;if(Ee){let be=Ee.match(/Total\s*:\s*(\d+)/i);be&&(K=parseInt(be[1]))}let ge=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(ge.length+4,we),Oe=`${ge.padEnd(qe-2).substring(0,qe-2)}`;yield{type:"visual_feedback",content:gn(`${We?`
699
+ `)},We=!1}M==="exec_command"&&(await new Promise(lt=>setTimeout(lt,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${De}`),await new Promise(lt=>setTimeout(lt,50)),t.onExecEnd&&t.onExecEnd()),te.push({role:"user",text:`[TOOL RESULT]: DENIED: ${De}`}),yield{type:"tool_result",content:`[TOOL RESULT]: DENIED: ${De}`},await Ot("toolDenied"),t.onToolResult&&t.onToolResult("denied",M),Ge++;continue}}if(Q){let v=115;process.stdout.isTTY&&(v=process.stdout.columns-5||120);let K=Math.min(Q.length+4,v),ce=`${Q.padEnd(K-2).substring(0,K-2)}`;yield{type:"visual_feedback",content:gn(`${We?`
700
+ `:""}${ce}${Q.includes("\u2714")&&(Q.includes("Created")||Q.includes("Edited"))?"":`
701
+ `}`)},We=!1}if(z>0){let v=Date.now()-z,K=Math.max(0,1e3-v);K>0&&await new Promise(ce=>setTimeout(ce,K))}let Un={chatId:d,history:n,onChunk:v=>t.onExecChunk?t.onExecChunk(v):null,onAskUser:t.onAskUser,systemSettings:t.systemSettings,mode:i,isMultiModal:zt(Te),onVisualFeedback:t.onVisualFeedback,onSubagentUpdate:t.onSubagentUpdate,onTokenChunk:t.onTokenChunk,modelName:Te,aiProvider:t.aiProvider,apiKey:t.apiKey,onUsage:t.onUsage};if(M==="write_file"||M==="update_file")try{let{path:v}=O(q.args);if(v){let K=ee.resolve(process.cwd(),v),ce=await ms();ce&&ce.file_focused===K&&ce.full_content&&(Un.forcedContent=ce.full_content)}}catch{}nn.push(M);let _e=await fo(M,q.args,Un);if((M==="write_file"||M==="update_file")&&_e.startsWith("SUCCESS")){let{path:v}=O(q.args);if(v){let K=ee.resolve(process.cwd(),v);ba(K)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let Gt=Date.now();z=Gt,yield{type:"tool_time",content:Gt-pe},sn=Gt;let Jt=null;if(typeof _e=="object"&&_e.binaryPart&&(Jt=_e.binaryPart,_e=_e.text),M==="search_keyword"){let{keyword:v,path:K}=O(q.args),ce=typeof _e=="string"&&_e.startsWith("[GLOB]");ce&&(_e=_e.slice(6).trimStart());let ye=typeof _e=="string"&&_e.startsWith("[DIR]");ye&&(_e=_e.slice(5).trimStart());let xe=0;if(_e){let Be=_e.match(/Found (\d+) match/i);Be&&(xe=parseInt(Be[1]))}let qe=K?K.replace(/[\/\\]+$/,""):null,Oe=qe&&qe!=="."?`"${ce?K:ye?`${qe}/*`:qe}"`:"./",ke=`${v?"\u2714":"\u2718"} Searched: "${v||""}" in ${Oe.replaceAll("\\","/")} \u2192 ${xe} Match${xe===1?"":"es"}`,ne=115;process.stdout.isTTY&&(ne=process.stdout.columns-5||120);let ue=Math.min(ke.length+4,ne),de=`${ke.padEnd(ue-2).substring(0,ue-2)}`;yield{type:"visual_feedback",content:gn(`${We?`
702
+ `:""}${de}
703
+ `)},We=!1}if(M==="EmergencyRollback"){let{method:v}=O(q.args);if(v==="forceRevert"){let K=0;if(_e){let ke=_e.match(/Total\s*:\s*(\d+)/i);ke&&(K=parseInt(ke[1]))}let ye=_e&&_e.startsWith("ERROR:")?"\u2718 Emergency Rollback Failed":`\u2714 Emergency Rollback \u2192 ${K} file${K===1?"":"s"} processed`,xe=115;process.stdout.isTTY&&(xe=process.stdout.columns-5||120);let qe=Math.min(ye.length+4,xe),Oe=`${ye.padEnd(qe-2).substring(0,qe-2)}`;yield{type:"visual_feedback",content:gn(`${We?`
704
704
  `:""}${Oe}
705
- `)},We=!1}}if(M==="todo"){let{method:v,tasks:K,markDone:le}=O(q.args),ge="",we=[],qe=Oe=>{if(!Oe)return[];let be=Array.isArray(Oe)?Oe:[];if(be.length===0&&typeof Oe=="string"){let te=Oe.trim();if(te.startsWith("[")&&te.endsWith("]")){let fe=te.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);fe?be=fe.map(ce=>ce.slice(1,-1).replace(/\\(.)/g,"$1")):be=te.slice(1,-1).split(",").map(ce=>ce.trim()).filter(Boolean)}else be=Oe.split(`
706
- `)}return be.filter(te=>String(te).trim()).map(te=>{let fe=String(te).trim();return fe.startsWith("- [")?fe.substring(6).trim():fe})};if(v==="create"?(ge="\x1B[32m\u2192\x1B[0m Created Goals",we=qe(K).map(Oe=>`\x1B[90m\u25CB\x1B[0m ${Oe}`)):v==="append"?(ge="\x1B[34m\u2795\x1B[0m Added New Goals",we=qe(K).map(Oe=>`\x1B[90m\u25CB\x1B[0m ${Oe}`)):v==="get"&&(ge=le?"\x1B[36m\u21BB\x1B[0m Updated Goals":"\x1B[35m\u2022\x1B[0m Reviewed Goals",we=(Ee||"").split(`
705
+ `)},We=!1}}if(M==="todo"){let{method:v,tasks:K,markDone:ce}=O(q.args),ye="",xe=[],qe=Oe=>{if(!Oe)return[];let ke=Array.isArray(Oe)?Oe:[];if(ke.length===0&&typeof Oe=="string"){let ne=Oe.trim();if(ne.startsWith("[")&&ne.endsWith("]")){let ue=ne.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);ue?ke=ue.map(de=>de.slice(1,-1).replace(/\\(.)/g,"$1")):ke=ne.slice(1,-1).split(",").map(de=>de.trim()).filter(Boolean)}else ke=Oe.split(`
706
+ `)}return ke.filter(ne=>String(ne).trim()).map(ne=>{let ue=String(ne).trim();return ue.startsWith("- [")?ue.substring(6).trim():ue})};if(v==="create"?(ye="\x1B[32m\u2192\x1B[0m Created Goals",xe=qe(K).map(Oe=>`\x1B[90m\u25CB\x1B[0m ${Oe}`)):v==="append"?(ye="\x1B[34m\u2795\x1B[0m Added New Goals",xe=qe(K).map(Oe=>`\x1B[90m\u25CB\x1B[0m ${Oe}`)):v==="get"&&(ye=ce?"\x1B[36m\u21BB\x1B[0m Updated Goals":"\x1B[35m\u2022\x1B[0m Reviewed Goals",xe=(_e||"").split(`
707
707
  `).slice(1).join(`
708
708
  `).split(`
709
- `).filter(be=>be.trim().startsWith("- [")).map(be=>{let te=be.trim(),fe=te.startsWith("- [x]");return`${fe?"\x1B[32m\u2714\x1B[0m":"\x1B[90m\u25CB\x1B[0m"} ${fe?"\x1B[90m":"\x1B[37m"}${te.substring(6).trim()}\x1B[0m`})),ge&&we.length>0){let Oe=[`${ge}`,...we.map(be=>` ${be}`)].join(`
709
+ `).filter(ke=>ke.trim().startsWith("- [")).map(ke=>{let ne=ke.trim(),ue=ne.startsWith("- [x]");return`${ue?"\x1B[32m\u2714\x1B[0m":"\x1B[90m\u25CB\x1B[0m"} ${ue?"\x1B[90m":"\x1B[37m"}${ne.substring(6).trim()}\x1B[0m`})),ye&&xe.length>0){let Oe=[`${ye}`,...xe.map(ke=>` ${ke}`)].join(`
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=Ee&&Ee.startsWith("DENIED:");Ee&&!Ee.startsWith("ERROR:")&&!_n?(await Ot("toolSuccess"),t.onToolResult&&t.onToolResult("success",M)):_n||(await Ot("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(`
712
+ `)},We=!1}}M==="exec_command"&&t.onExecEnd&&(await new Promise(v=>setTimeout(v,800)),t.onExecEnd());let _n=_e&&_e.startsWith("DENIED:");_e&&!_e.startsWith("ERROR:")&&!_n?(await Ot("toolSuccess"),t.onToolResult&&t.onToolResult("success",M)):_n||(await Ot("toolFailure"),t.onToolResult&&t.onToolResult("failure",M));let qt=(_e||"").toString().replaceAll("[UI_CONTEXT]","");qt.includes("[[VERIFIED]]")&&(qt=qt.replace(/\[\[VERIFIED\]\][\s\S]*?\[\[\/VERIFIED\]\]/g,`[SYSTEM NOTE]: Patch Block matched & applied successfully. Large Block omitted to conserve context.
713
+ `));let $n;if(qt.startsWith("[[SAME]]")){let K=qt.replace(/^\[\[SAME\]\]\s*\r?\n?/,"").split(/\r?\n/),ce=K.filter(xe=>xe.startsWith("SUCCESS:")||xe.trim().startsWith("- Stats:"));$n=`[TOOL RESULT]: ${ce.length>0?ce.join(`
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 $n=`[TOOL RESULT]: ${qt}`;ee.push({role:"user",text:$n,binaryPart:Jt}),cn=!0;let Me=`[TOOL RESULT]: ${Ee.replaceAll(`[[VERIFIED]]
716
+ [SYSTEM NOTE]: Content verified and persisted to disk. Full preview omitted to conserve context.`}else $n=`[TOOL RESULT]: ${qt}`;te.push({role:"user",text:$n,binaryPart:Jt}),cn=!0;let Ae=`[TOOL RESULT]: ${_e.replaceAll(`[[VERIFIED]]
717
717
  `,"").replaceAll(`
718
- [[/VERIFIED]]`,"")||""}`;(M==="view_file"||M==="web_scrape"||M==="file_map")&&(Me=`[TOOL RESULT]: ${J} (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 q=Us(Pt);for(let he of q)yield he;Pt="",Ko=Date.now()}}D.usageMetadata&&(Tn=D.usageMetadata),Tn&&(yield{type:"liveTokens",content:Tn.totalTokenCount})}if(ue&&(ue=!1,jt?Ke+="</think>":(de+="</think>",u==="Google"?Pt+="</think>":yield{type:"text",content:"</think>"})),jt&&Ke.length>0){let D=0,ne=Math.min(tt.length,Ke.length);for(let H=ne;H>0;H--)if(tt.endsWith(Ke.substring(0,H))){D=H;break}let W=Ke.substring(D);if(W){let ye=/(?:<(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(ye)if(de+=ye,u==="Google")Pt+=ye;else{yield*ns();let me=Us(ye);for(let Re of me)yield Re}}jt=!1,Ke=""}if(yield*ns(),Lt)break;let Ws=(de||"").trim(),za=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(Ws.toLowerCase())||/\[\[END\]\]/i.test(Ws.toLowerCase()),Ka=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(Ws.toLowerCase()),Ya=ee.length>0||Ut!==null,Yo=Ws.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/gi,"").trim(),Va=/(\p{Emoji_Presentation}|\p{Extended_Pictographic})$/u.test(Yo),Xa=/([.!?"'*_`|\]\)”’~~]+|\s|`{3}|[\u200B-\u200D\uFEFF])$/u.test(Yo.trim()),Ja=/[.!?}"'`’“”]$|```$/s.test(Yo)||Xa||Va;!za&&!Ka&&!Ya&&Ws.length>0,Ze=!0,await Ot("agent",u)}catch(Te){if(Lt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
718
+ [[/VERIFIED]]`,"")||""}`;(M==="view_file"||M==="web_scrape"||M==="file_map")&&(Ae=`[TOOL RESULT]: ${Q} (Context Locked for UI Clarity)`),yield{type:"tool_result",content:Ae,aiContent:$n,binaryPart:Jt,toolName:M},M==="memory"&&_e.includes("SUCCESS")&&(yield{type:"memory_updated"}),Ge++}if(u==="Google"&&Pt&&Date.now()-Ko>=150){yield*ns();let q=Us(Pt);for(let pe of q)yield pe;Pt="",Ko=Date.now()}}D.usageMetadata&&(Tn=D.usageMetadata),Tn&&(yield{type:"liveTokens",content:Tn.totalTokenCount})}if(he&&(he=!1,jt?Ke+="</think>":(fe+="</think>",u==="Google"?Pt+="</think>":yield{type:"text",content:"</think>"})),jt&&Ke.length>0){let D=0,oe=Math.min(tt.length,Ke.length);for(let H=oe;H>0;H--)if(tt.endsWith(Ke.substring(0,H))){D=H;break}let j=Ke.substring(D);if(j){let we=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(tt)?j.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):j.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(we)if(fe+=we,u==="Google")Pt+=we;else{yield*ns();let ge=Us(we);for(let Ee of ge)yield Ee}}jt=!1,Ke=""}if(yield*ns(),Lt)break;let Ws=(fe||"").trim(),Ka=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(Ws.toLowerCase())||/\[\[END\]\]/i.test(Ws.toLowerCase()),Ya=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(Ws.toLowerCase()),Va=te.length>0||Ut!==null,Yo=Ws.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/gi,"").trim(),Xa=/(\p{Emoji_Presentation}|\p{Extended_Pictographic})$/u.test(Yo),Ja=/([.!?"'*_`|\]\)”’~~]+|\s|`{3}|[\u200B-\u200D\uFEFF])$/u.test(Yo.trim()),Qa=/[.!?}"'`’“”]$|```$/s.test(Yo)||Ja||Xa;!Ka&&!Ya&&!Va&&Ws.length>0,Ze=!0,await Ot("agent",u)}catch(Re){if(Lt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
719
719
 
720
- \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(String(Te).includes("Incomplete JSON segment at the end")){ue&&(ue=!1,jt?Ke+="</think>":(de+="</think>",yield{type:"text",content:"</think>"})),Ze=!0,await Ot("agent",u);break}if(ue&&(ue=!1,jt?Ke+="</think>":de+="</think>"),jt&&Ke.length>0){let Bn=0,Xt=Math.min(tt.length,Ke.length);for(let at=Xt;at>0;at--)if(tt.endsWith(Ke.substring(0,at))){Bn=at;break}let At=Ke.substring(Bn);if(At){let Pt=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(tt)?At.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):At.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");Pt&&(de+=Pt)}jt=!1,Ke=""}let oe=Te instanceof Error?(()=>{try{return JSON.parse(JSON.parse(Te.message).error.message).error.message}catch{return String(Te)}})():String(Te),st=new Date().toLocaleString(),Mt=Z.join(fn,"agent");Pe.existsSync(Mt)||Pe.mkdirSync(Mt,{recursive:!0}),Pe.appendFileSync(Z.join(Mt,"error.log"),`ERROR [${st}]: ${oe}
720
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(String(Re).includes("Incomplete JSON segment at the end")){he&&(he=!1,jt?Ke+="</think>":(fe+="</think>",yield{type:"text",content:"</think>"})),Ze=!0,await Ot("agent",u);break}if(he&&(he=!1,jt?Ke+="</think>":fe+="</think>"),jt&&Ke.length>0){let Bn=0,Xt=Math.min(tt.length,Ke.length);for(let at=Xt;at>0;at--)if(tt.endsWith(Ke.substring(0,at))){Bn=at;break}let At=Ke.substring(Bn);if(At){let Pt=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(tt)?At.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):At.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");Pt&&(fe+=Pt)}jt=!1,Ke=""}let ie=Re instanceof Error?(()=>{try{return JSON.parse(JSON.parse(Re.message).error.message).error.message}catch{return String(Re)}})():String(Re),st=new Date().toLocaleString(),Mt=ee.join(fn,"agent");Pe.existsSync(Mt)||Pe.mkdirSync(Mt,{recursive:!0}),Pe.appendFileSync(ee.join(Mt,"error.log"),`ERROR [${st}]: ${ie}
721
721
 
722
722
  ----------------------------------------------------------------------
723
723
 
724
- `);let on=Te.status||Te.statusCode||Te.code,Et=String(Te).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(Te))||/code[ :]+(5\d\d|408|429)/i.test(String(Te))||/(500|503|408|429)/.test(String(Te))))){if(He<yn-3)throw Te;yield{type:"text",content:oe},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]
724
+ `);let on=Re.status||Re.statusCode||Re.code,Et=String(Re).includes("replicas at capacity");if(!(on&&(on>=500&&on<600||on===408||on===429||Et)||!on&&(/status[ :]+(5\d\d|408|429)/i.test(String(Re))||/code[ :]+(5\d\d|408|429)/i.test(String(Re))||/(500|503|408|429)/.test(String(Re))))){if(He<yn-3)throw Re;yield{type:"text",content:ie},yield{type:"status",content:"Error Occured"}}if(fe.trim().length>0||Je>1)if(Je<=yn){Je++;let Bn=Math.min(1e3*Math.pow(2,Je-1),24e3);if(fe.trim().length>0){x.push({role:"agent",text:fe});let Xt=`[system]
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]`;ee.length>0?ee.forEach((At,at)=>{at===ee.length-1?k.push({...At,text:`${At.text}
729
+ - stealth: do not mention/apologize for cutoff [/system]`;te.length>0?te.forEach((At,at)=>{at===te.length-1?x.push({...At,text:`${At.text}
730
730
 
731
- ${Xt}`}):k.push(At)}):k.push({role:"user",text:Xt}),tt+=de}for(let Xt=Bn/1e3;Xt>0&&!Lt;Xt--)yield{type:"status",content:`Error Occured. Recovering Stream (${Je}/${yn}) [Retrying in ${Xt.toFixed(0)}s]...`},await new Promise(At=>setTimeout(At,1e3));yield{type:"status",content:"Error Occured. Recovering Stream..."}}else throw new Error(`Stream collapsed too many times. (Failed to resolve ${yn} times)
731
+ ${Xt}`}):x.push(At)}):x.push({role:"user",text:Xt}),tt+=fe}for(let Xt=Bn/1e3;Xt>0&&!Lt;Xt--)yield{type:"status",content:`Error Occured. Recovering Stream (${Je}/${yn}) [Retrying in ${Xt.toFixed(0)}s]...`},await new Promise(At=>setTimeout(At,1e3));yield{type:"status",content:"Error Occured. Recovering Stream..."}}else throw new Error(`Stream collapsed too many times. (Failed to resolve ${yn} times)
732
732
  Error log can be found in \`/export logs\``);else if(He<=yn){He++,Je=1,tt="";let Bn=Math.min(1e3*Math.pow(2,He-1),32e3),Xt=.8+Math.random()*.4,At=Math.round(Bn*Xt);Qn=!0,yield{type:"status",content:`Trying to reach ${e} (${He}/${yn}) [Retrying in ${(At/1e3).toFixed(0)}s]`};for(let at=At/1e3;at>0&&!Lt;at--)yield{type:"status",content:`Trying to reach ${e} (${He}/${yn}) [Retrying in ${at.toFixed(0)}s]`},await new Promise(Pt=>setTimeout(Pt,1e3));yield{type:"status",content:`Trying to reach ${e}`}}else throw new Error(`Model ${e} cannot be reached. (Failed ${yn} times)
733
- Error log can be found in \`/export logs\``)}}if(Tn){let ue=Tn.totalTokenCount||0,Te=Tn.cachedContentTokenCount||0,oe=(Tn.candidatesTokenCount||0)+(Tn.thoughtsTokenCount||0);await Kt("tokens",ue,u,Se),Te>0&&await Kt("cachedTokens",Te,u,Se),oe>0&&await Kt("candidateTokens",oe,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,Fc=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(es.toLowerCase()),Nc=Ge>0;yield{type:"status",content:"Thinking"};let Wa=Ac(de,/(\[\s*(turn\s*:)?\s*(continue|finish)\s*\]|\[\[END\]\])/gi,"").trim(),ts=(En||ee.length===0)&&!Wt&&!wn&&!Rn;if(ts=ee.length===0?ts:!1,ts=Zn||mo?!1:ts,de&&de.trim().endsWith('")]')&&ee.length===0&&(ts=!1),ts){let ue=yi.join(`
734
- `),Te=ue.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").trim();yield{type:"interactive_turn_finished",data:{agentText:T,fullAgentTextRaw:ue,history:[...k],needTitle:S}},k.length>0&&k[k.length-1].role==="agent"?k[k.length-1].text=Te:k.push({role:"agent",text:Te}),k.forEach(oe=>{if(oe.role==="user"&&oe.text&&(oe.text=oe.text.replace(/\n\[COMPILE ERROR\][\s\S]*?\[\/ERROR\]/g,""),oe.text=oe.text.replaceAll(`
733
+ Error log can be found in \`/export logs\``)}}if(Tn){let he=Tn.totalTokenCount||0,Re=Tn.cachedContentTokenCount||0,ie=(Tn.candidatesTokenCount||0)+(Tn.thoughtsTokenCount||0);await Kt("tokens",he,u,Te),Re>0&&await Kt("cachedTokens",Re,u,Te),ie>0&&await Kt("candidateTokens",ie,u,Te),yield{type:"usage",content:Tn}}yi.push(fe);let Fn=fe;fe.match(/(?:<think>|\[think\])([\s\S]*?)(?:<\/think>|\[\/think\])/i)&&(Fn=fe.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/i,""));let es=va(fe),En=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(es.toLowerCase())||/\[\[END\]\]/i.test(es.toLowerCase())||!0,Nc=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(es.toLowerCase()),Bc=Ge>0;yield{type:"status",content:"Thinking"};let ja=vc(fe,/(\[\s*(turn\s*:)?\s*(continue|finish)\s*\]|\[\[END\]\])/gi,"").trim(),ts=(En||te.length===0)&&!Wt&&!wn&&!Rn;if(ts=te.length===0?ts:!1,ts=Zn||mo?!1:ts,fe&&fe.trim().endsWith('")]')&&te.length===0&&(ts=!1),ts){let he=yi.join(`
734
+ `),Re=he.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").trim();yield{type:"interactive_turn_finished",data:{agentText:S,fullAgentTextRaw:he,history:[...x],needTitle:k}},x.length>0&&x[x.length-1].role==="agent"?x[x.length-1].text=Re:x.push({role:"agent",text:Re}),x.forEach(ie=>{if(ie.role==="user"&&ie.text&&(ie.text=ie.text.replace(/\n\[COMPILE ERROR\][\s\S]*?\[\/ERROR\]/g,""),ie.text=ie.text.replaceAll(`
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,""),oe.text=oe.text.replaceAll(/\n\[system\] File Changes:\n(?:\* .+ \(created|modified|deleted\)\n)*\[\/system\]/g,""),(u==="Mistral"||u==="Google"&&e?.toLowerCase().startsWith("gemma"))&&oe.text.startsWith("[TOOL RESULT]"))){let Mt=`
740
+ `,"").replaceAll(/\n\[system\] WARNING, Turn Limit Impending: Step \d+\/\d+\. Wrap up quickly\/prompt user to continue & use \[\[END\]\] quickly\. \[\/system\]/g,""),ie.text=ie.text.replaceAll(/\n\[system\] File Changes:\n(?:\* .+ \(created|modified|deleted\)\n)*\[\/system\]/g,""),(u==="Mistral"||u==="Google"&&e?.toLowerCase().startsWith("gemma"))&&ie.text.startsWith("[TOOL RESULT]"))){let Mt=`
741
741
  [system] Tool result received. Analyze output and proceed with your turn [/system]`,on=`
742
- [system] Tool result received. Analyze output and proceed with your turn. **strictly follow thinking policy. do not start a response without <think>...</think>** [/system]`;oe.text=oe.text.replaceAll(on,"").replaceAll(Mt,"").trim()}}),yield{type:"status",content:"[end]"}}if(ts)break;let ja=Wa.trim()||"*Working...*";if(k.push({role:"agent",text:ja}),ee.length>0||cn){if(ee.length>0){let ue=ee.map(Mt=>Mt.text).join(`
742
+ [system] Tool result received. Analyze output and proceed with your turn. **strictly follow thinking policy. do not start a response without <think>...</think>** [/system]`;ie.text=ie.text.replaceAll(on,"").replaceAll(Mt,"").trim()}}),yield{type:"status",content:"[end]"}}if(ts)break;let Ha=ja.trim()||"*Working...*";if(x.push({role:"agent",text:Ha}),te.length>0||cn){if(te.length>0){let he=te.map(Mt=>Mt.text).join(`
743
743
 
744
- `),oe=(de.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/gi,"").match(/\[tool:functions/g)||[]).length;if(ee.length<oe){ue+=`
744
+ `),ie=(fe.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/gi,"").match(/\[tool:functions/g)||[]).length;if(te.length<ie){he+=`
745
745
 
746
- [SYSTEM] Only ${ee.length} out of ${oe} attempted tool calls were executed. Verify proper schema compliance & try failed calls again [/SYSTEM]`;let Mt=oe-ee.length;for(let on=0;on<Mt;on++)await Ot("toolFailure")}let st=ee.find(Mt=>Mt.binaryPart)?.binaryPart||null;k.push({role:"user",text:ue,binaryPart:st})}}else mo||Zn?(k.push({role:"user",text:"[SYSTEM] Failed to execute some tools. Verify proper schema compliance & try again [/SYSTEM]"}),await Ot("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,Rn=!1;l?.advanceRollback&&await Kn.recordTurnDelta(d,G+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(),P=Z.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
- \u2800`},Pe.existsSync(P)||Pe.mkdirSync(P,{recursive:!0}),Pe.appendFileSync(Z.join(P,"error.log"),`CRITICAL ERROR [${I}]: ${_}
746
+ [SYSTEM] Only ${te.length} out of ${ie} attempted tool calls were executed. Verify proper schema compliance & try failed calls again [/SYSTEM]`;let Mt=ie-te.length;for(let on=0;on<Mt;on++)await Ot("toolFailure")}let st=te.find(Mt=>Mt.binaryPart)?.binaryPart||null;x.push({role:"user",text:he,binaryPart:st})}}else mo||Zn?(x.push({role:"user",text:"[SYSTEM] Failed to execute some tools. Verify proper schema compliance & try again [/SYSTEM]"}),await Ot("toolFailure")):x.push({role:"user",text:`[SYSTEM] ${wn&&!Wt?"STUTTERING DETECTED by Internal System. Re-calibrate your response & proceed.":`${Wt?" OVER THINKING":" LOOP"} DETECTED by Internal System${Wt?" for current EFFORT_LEVEL":""}. ${Wt?"If you have planned the task, prioritize execution/output":"If you have finished your task provide a simple summary and end"}`} [/SYSTEM]`}),Wt=!1,wn=!1,Rn=!1;l?.advanceRollback&&await Kn.recordTurnDelta(d,G+1,nn),mo=Ge>0||cn}}catch(E){let C=(E instanceof Error?(()=>{try{return JSON.parse(JSON.parse(E.message).error.message).error.message}catch{return E.message||String(E)}})():String(E)).replace(/^(Error:\s*)+/i,""),I=new Date().toLocaleString(),L=ee.join(fn,"agent");yield{type:"text",content:`\u2726 CRITICAL ERROR: ${C.includes("fetch failed")?"Failed to Connect. Check your Internet Connection or Wait a moment":C}
747
+ \u2800`},Pe.existsSync(L)||Pe.mkdirSync(L,{recursive:!0}),Pe.appendFileSync(ee.join(L,"error.log"),`CRITICAL ERROR [${I}]: ${E}
748
748
 
749
749
  ----------------------------------------------------------------------
750
750
 
751
- `),typeof flushGoogleBuffer=="function"&&(yield*flushGoogleBuffer()),yield{type:"tool_result",content:`ERROR: [INTERNAL CRITICAL] ${C}`}}finally{$&&(clearInterval($),$=null),typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),await mt.commitTransaction(),l?.advanceRollback&&await Kn.cleanup(d),await ms()}yield{type:"status",content:null}},vm=async(e,n,t=null,o=null,s=50,r=null,a=!1)=>{let i=await Ft(),p={...i,...n},d=process.env.SUBAGENT_MODEL?process.env.SUBAGENT_MODEL.trim():null,c=process.env.SUBAGENT_PROVIDER?process.env.SUBAGENT_PROVIDER.trim():null,l=new Date,f=`${l.getFullYear()}-${l.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(l.getDate()).padStart(2,"0")}, ${l.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}).replace(":","-")}`,h=(_=>{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=p?.systemSettings?.CustomSubAgent?p?.systemSettings?.SubAgentModel:null,y=p?.systemSettings?.CustomSubAgent?p?.systemSettings?.SubAgentProvider:null,m=null;if(g==="ENV"?(m=d,d&&h&&(p.aiProvider=h)):g&&g!=="Default"?(m=g,y&&(p.aiProvider=y)):d&&h&&(p.aiProvider=h),p.aiProvider){let _=await Qo(p.aiProvider);_&&(p.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
- To use tools, must output exactly '[tool:functions.ToolName(arg1="value1")]' structured string in chat response \u2190 no exception
751
+ `),typeof flushGoogleBuffer=="function"&&(yield*flushGoogleBuffer()),yield{type:"tool_result",content:`ERROR: [INTERNAL CRITICAL] ${C}`}}finally{_&&(clearInterval(_),_=null),typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),await mt.commitTransaction(),l?.advanceRollback&&await Kn.cleanup(d),await ms()}yield{type:"status",content:null}},Im=async(e,n,t=null,o=null,s=50,r=null,a=!1)=>{let i=await Ft(),p={...i,...n},d=process.env.SUBAGENT_MODEL?process.env.SUBAGENT_MODEL.trim():null,c=process.env.SUBAGENT_PROVIDER?process.env.SUBAGENT_PROVIDER.trim():null,l=new Date,f=`${l.getFullYear()}-${l.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(l.getDate()).padStart(2,"0")}, ${l.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}).replace(":","-")}`,h=(E=>{if(!E)return null;let x=E.toLowerCase();return x==="google"?"Google":x==="deepseek"?"DeepSeek":x==="openrouter"?"OpenRouter":x==="nvidia"?"NVIDIA":x==="mistral"?"Mistral":x==="ollama"?"Ollama":x==="crofai"||x==="crof"?"CrofAI":x==="inferx"?"InferX":x==="sensenova"?"SenseNova":null})(c),g=p?.systemSettings?.CustomSubAgent?p?.systemSettings?.SubAgentModel:null,y=p?.systemSettings?.CustomSubAgent?p?.systemSettings?.SubAgentProvider:null,m=null;if(g==="ENV"?(m=d,d&&h&&(p.aiProvider=h)):g&&g!=="Default"?(m=g,y&&(p.aiProvider=y)):d&&h&&(p.aiProvider=h),p.aiProvider){let E=await Qo(p.aiProvider);E&&(p.apiKey=E)}let w=E=>{if(!E||typeof E!="string")return{allowed:!0};let x=[/rm\s+-[rf]{1,2}\s+[\/*.]/i,/rmdir\s+\/[sq]/i,/del\s+\/[fsq]/i,/\bformat\b\s+[a-z]:/i,/mkfs/i,/dd\s+if=/i,/\b(shutdown|reboot|poweroff|init\s+0|init\s+6)\b/i,/chmod\s+(-R\s+)?777\s+[\/*.]/i,/chown\s+(-R\s+)?root/i,/git\s+push\s+.*--force/i,/git\s+clean\s+-fdx/i,/\bsudo\s+su\b/i,/\bsu\s+-\b/i];for(let C of x)if(C.test(E))return{allowed:!1,reason:`Blocked potentially destructive or unsafe command pattern: "${C.source}"`};return{allowed:!0}},b=t||m||n?.modelName||n?.activeModel||i.activeModel,T=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",$=`-- TOOL DEFINITIONS (path = relative to CWD, path separator: '/') --
752
+ You cant execute tools. To call tools, must output exactly [tool:functions.ToolName(arg1="value1")] structured string in chat response \u2190 no exception, verify correct syntax/brackets
753
753
  Tool Rules:
754
754
  - JSON escape literal escape sequences in tool arguments
755
755
  - Same file, multiple edits? ONE PatchFile (\u226415 blocks) \u2190 Priority
@@ -776,11 +776,11 @@ ${a?'- AskMain(question="..."). Communicate with PARENT/MAIN AGENT. When clarifi
776
776
  - ReadFile(path="...", startLine="int", endLine="int")
777
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
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 ===
779
+ - Run(command="..."). Runs ${T==="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
 
783
- ${E.trimEnd()}
783
+ ${$.trimEnd()}
784
784
 
785
785
  -- THINKING GUIDANCE --
786
786
  NO EXPLICIT THINKING REQUIRED. FOCUS ON TASK COMPLETION
@@ -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(Lt){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(p,b,_,R,"Fast")).text||"").replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/gi,"").trim();$=I,r&&r(`[Subagent Response]
792
+ === END SYSTEM PROMPT ===`,k=[{role:"user",text:`Complete this task: ${e}`}],S=0,_="";for(;S<s;){if(Lt){if(n?.taskId&&typeof Xe<"u"){let F=Xe.find(U=>U.id===n.taskId);F&&(F.status="cancelled")}throw r&&r("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}if(n?.taskId&&typeof Xe<"u"){let F=Xe.find(U=>U.id===n.taskId);if(F&&F.status==="cancelled")throw r&&r("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}let E=k.map(F=>({role:F.role==="user"?"user":"model",parts:[{text:F.text}]}));r&&r(`[Subagent Turn ${S+1}]...`);let I=((await jo(p,b,E,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 P=Ho(I);if(P.length===0)break;let B=P.filter(U=>U.toolName.toLowerCase()==="askmain"||U.toolName.toLowerCase()==="ask_main"),N=!1,Y="";for(let U of P){if(Lt){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
- Answer from Main Agent: ${F}
797
- `),Y+=`[TOOL RESULT for AskMain]: Answer from Main Agent: ${F}
794
+ `),k.push({role:"agent",text:I});let L=Ho(I);if(L.length===0)break;let N=L.filter(F=>F.toolName.toLowerCase()==="askmain"||F.toolName.toLowerCase()==="ask_main"),W=!1,X="";for(let F of L){if(Lt){if(n?.taskId&&typeof Xe<"u"){let A=Xe.find(B=>B.id===n.taskId);A&&(A.status="cancelled")}throw new Error("Subagent task was cancelled.")}if(n?.taskId&&typeof Xe<"u"){let A=Xe.find(B=>B.id===n.taskId);if(A&&A.status==="cancelled")throw new Error("Subagent task was cancelled.")}let U=F.toolName.toLowerCase();if(U==="askmain"||U==="ask_main"){if(W)continue;W=!0;let A="";if(N.length===1?A=O(N[0].args).question||N[0].args:A=N.map((B,V)=>{let J=O(B.args);return`Q${V+1}: ${J.question||B.args}`}).join(`
795
+ `),n.onAskMain){r&&r(`[Executing Tool] AskMain("${A}")...`);let B=await n.onAskMain(A);r&&r(`[Tool Result]
796
+ Answer from Main Agent: ${B}
797
+ `),X+=`[TOOL RESULT for AskMain]: Answer from Main Agent: ${B}
798
798
 
799
- `,await Ot("toolSuccess")}else Y+=`[TOOL RESULT for AskMain]: ERROR: Main agent communication channel not available.
799
+ `,await Ot("toolSuccess")}else X+=`[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.`;r&&r(`[Blocked Tool Call] ${U.toolName} - not allowed
802
- `),Y+=`${A}
801
+ `;continue}if(!(o?o.some(A=>A.toLowerCase()===U):!0)){let A=`ERROR: Tool [${F.toolName}] is not in the allowed tools list for this subagent.`;r&&r(`[Blocked Tool Call] ${F.toolName} - not allowed
802
+ `),X+=`${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}`;r&&r(`[Blocked Command] ${A} - ${F.reason}
805
- `),Y+=`${V}
804
+ `;continue}if(U==="exec_command"||U==="execcommand"||U==="run"){let A=O(F.args).command||"",B=w(A);if(!B.allowed){let V=`ERROR: [SECURITY RESTRICTION] Subagent execution blocked command: ${B.reason}`;r&&r(`[Blocked Command] ${A} - ${B.reason}
805
+ `),X+=`${V}
806
806
 
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),Fe=X%60;return`${Ue}m${Fe>0?` ${Fe}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]
807
+ `;continue}}let $e="";if(U==="web_search"||U==="websearch")$e=`\u2714 \x1B[95mSearched\x1B[0m: ${O(F.args).query||""}`;else if(U==="web_scrape"||U==="webscrape")$e=`\u2714 \x1B[95mScraped\x1B[0m: ${O(F.args).url||""}`;else if(U==="search_keyword"||U==="searchkeyword"||U==="codesearch"||U==="code_search"){let A=O(F.args),B=A.keyword||"",V=A.path||"";$e=`${B?"\u2714":"\u2718"} \x1B[95mSearched\x1B[0m: ${B||"No Query"}${V?` \u2192 ${V.replaceAll("\\","/")}`:""}`}else if(U==="view_file"||U==="viewfile"||U==="readfile")$e=`\u2714 \x1B[95mRead\x1B[0m: ${(O(F.args).path||"").replaceAll("\\","/")}`;else if(U==="list_files"||U==="read_folder"||U==="readfolder"){let A=O(F.args).path||null,B=O(F.args).recurse||0;$e=`${A?"\u2714":"\u2718"} \x1B[95mBrowsed\x1B[0m: ${A?`${A.replaceAll("\\","/")}${B>0?`${A.endsWith("/")?`*${B}`:`/*${B}`}`:`${A.endsWith("/")?"":"/"}`}`:""}`}else if(U==="write_file"||U==="writefile"){let A=O(F.args).path||null;$e=`${A?"\u2714":"\u2718"} \x1B[95mCreated\x1B[0m: ${A?`${A.replaceAll("\\","/")}`:"No File Changes"}`}else if(U==="update_file"||U==="updatefile"||U==="patchfile"||U==="patch_file"||U==="patchfile"||U==="updatefile"){let A=O(F.args).path||null,B=O(F.args).content||null;$e=`${A?"\u2714":"\u2718"} \x1B[95mEdited\x1B[0m: ${A?`${A.replaceAll("\\","/")}`:"No File Changes"}`}else if(U==="exec_command"||U==="execcommand"||U==="run"){let A=O(F.args).command||null;$e=`${A?"\u2714":"\u2718"} \x1B[95mExecuted\x1B[0m: ${A?A.slice(0,100)+(A.length>100?"...":""):"No Command"}`}else if(U==="file_map"||U==="filemap"){let A=O(F.args).path||"";$e=`${A?"\u2714":"\u2718"} \x1B[95mIndexed\x1B[0m: ${A?`${A.replaceAll("\\","/")}`:"File Not Found"}`}else if(U==="await"){let{time:A}=O(F.args),B=parseFloat(A)||0;B<10&&(B=10),B>180&&(B=180),$e=`\u2714 \x1B[95mAwaiting\x1B[0m \u2192 ${(J=>{if(J>=60){let Ue=Math.floor(J/60),Fe=J%60;return`${Ue}m${Fe>0?` ${Fe}s`:""}`}return`${J}s`})(B)}`}else{let A=Qr[U]||F.toolName,B=ws(U,F.args);$e=`\u2714 \x1B[95m${A}\x1B[0m${B?`: ${B}`:""}`}n.onVisualFeedback&&$e&&n.onVisualFeedback($e),r&&r(`[Executing Tool] ${F.toolName}(${F.args})...`);try{let A=await fo(F.toolName,F.args,{...n,mode:"Flux"});if(r&&r(`[Tool Result]
808
808
  ${A}
809
- `),Y+=`[TOOL RESULT for ${U.toolName}]: ${A}
809
+ `),X+=`[TOOL RESULT for ${F.toolName}]: ${A}
810
810
 
811
- `,await Ot("toolSuccess"),j==="patchfile"||j==="update_file"||j==="updatefile"||j==="patch_file"){if(A){let F=A.split(`
812
- `),V=0,X=0,Ue=!1;for(let Fe of F){if(Fe.includes("[DIFF_START]")){Ue=!0;continue}if(Fe.includes("[DIFF_END]")){Ue=!1;continue}Ue&&(/^\+\d+/.test(Fe)?V++:/^\-\d+/.test(Fe)&&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 Fe of A.split(`
813
- `)){if(Fe.includes("Old File contents:")){Ue=!0;continue}Ue&&(Fe.trim()===""?Ue=!1:/^\d+ \|/.test(Fe)&&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
- `),Y+=`${F}
811
+ `,await Ot("toolSuccess"),U==="patchfile"||U==="update_file"||U==="updatefile"||U==="patch_file"){if(A){let B=A.split(`
812
+ `),V=0,J=0,Ue=!1;for(let Fe of B){if(Fe.includes("[DIFF_START]")){Ue=!0;continue}if(Fe.includes("[DIFF_END]")){Ue=!1;continue}Ue&&(/^\+\d+/.test(Fe)?V++:/^\-\d+/.test(Fe)&&J++)}(V>0||J>0)&&(await Kt("linesAdded",V),await Kt("linesRemoved",J))}}else if((U==="writefile"||U==="write_file")&&A){let B=A.match(/- Stats: \[(\d+) lines/),V=B?parseInt(B[1]):0,J=0;if(A.includes("Old File contents:")){let Ue=!1;for(let Fe of A.split(`
813
+ `)){if(Fe.includes("Old File contents:")){Ue=!0;continue}Ue&&(Fe.trim()===""?Ue=!1:/^\d+ \|/.test(Fe)&&J++)}}(V>0||J>0)&&(await Kt("linesAdded",V),await Kt("linesRemoved",J))}}catch(A){let B=`ERROR: Execution failed for [${F.toolName}]: ${A.message}`;r&&r(`[Tool Error] ${B}
814
+ `),X+=`${B}
815
815
 
816
- `,await Ot("toolFailure")}}let se="";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)se+=`
816
+ `,await Ot("toolFailure")}}let re="";if(n?.taskId&&typeof Xe<"u"){let F=Xe.find(U=>U.id===n.taskId);if(F&&F.pendingSteerMessages&&F.pendingSteerMessages.length>0){let U=[...F.pendingSteerMessages];F.pendingSteerMessages=[];for(let se of U)re+=`
817
817
 
818
- [STEERING INSTRUCTION FROM MAIN AGENT]: ${ae}`,r&&r(`[Subagent Steered] ${ae}`)}}let Ie=(Y.trim()+se).trim();S.push({role:"user",text:Ie}),T++}return $};export{pn as a,zi as b,Tf as c,Rf as d,Sl as e,Ki as f,Ef as g,Al as h,_f as i,uo as j,ya as k,Lp as l,Pp as m,O as n,Gc as o,er as p,Ks as q,qc as r,zc as s,mt as t,as as u,Td as v,al as w,Rd as x,Ed as y,_d as z,$d as A,Cd as B,Pd as C,Dd as D,Sn as E,fl as F,Xs as G,Kt as H,ul as I,Fi as J,ls as K,jl as L,Ru as M,Eu as N,Np as O,Uo as P,Bp as Q,Pn as R,_c as S,Em as T,_m as U,li as V,$m as W,Cm as X,Pc as Y,Mm as Z,Am as _,vm as $};
818
+ [STEERING INSTRUCTION FROM MAIN AGENT]: ${se}`,r&&r(`[Subagent Steered] ${se}`)}}let Y=(X.trim()+re).trim();k.push({role:"user",text:Y}),S++}return _};export{pn as a,zi as b,Rf as c,Ef as d,Tl as e,Ki as f,_f as g,vl as h,$f as i,uo as j,ya as k,Pp as l,Dp as m,O as n,qc as o,er as p,Ks as q,zc as r,Kc as s,mt as t,as as u,Rd as v,ll as w,Ed as x,_d as y,$d as z,Cd as A,Md as B,Dd as C,Fd as D,Sn as E,ul as F,Xs as G,Kt as H,hl as I,Fi as J,ls as K,Hl as L,Eu as M,_u as N,Bp as O,Uo as P,Up as Q,Pn as R,$c as S,_m as T,$m as U,li as V,Cm as W,Mm as X,Dc as Y,Am as Z,vm as _,Im as $};