fluxflow-cli 4.7.1 → 4.7.2

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,14 +1,14 @@
1
- import{b as fr}from"./chunk-JM3JCK2K.js";import{e as Mt,g as qt,i as vi,j as Ii,k as Oi,l as Di,m as Li}from"./chunk-QLPFOHKZ.js";import{c as At,d as Mo,g as Te,h as en}from"./chunk-IJCIHHAH.js";import{a as dr,b as Mi,c as oe,d as pe}from"./chunk-SIINYZWE.js";import{a as Qt,c as Dn,d as mn,e as Ts,f as $o,g as Ao,j as Pt,k as Zt,l as Ln,m as zn,n as an,o as hn,p as lo,q as cr,r as Kn,s as co}from"./chunk-4TZKD2XR.js";import{a as Xe,c as Rs}from"./chunk-56EJGQU3.js";import{c as Pi,d as Fi,e as Ko}from"./chunk-ROHVHR3J.js";import gs from"dotenv";import{GoogleGenAI as fl,ThinkingLevel as pt,HarmBlockThreshold as Zn,HarmCategory as eo}from"@google/genai";import{execSync as Ui}from"child_process";import{spawn as ur}from"child_process";var D=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 u=0;for(let y=l-1;y>=0&&e[y]==="\\";y--)u++;if(u%2!==0){d=l+1;continue}let f=e.substring(l+1),m=f.trim(),g=m===""||/^,\s*\w+\s*=/.test(m)||m.startsWith(")")&&(m.length===1||/^\)\s*([,\]\s]|\[\[?tool:)/i.test(m));if(g&&f.startsWith(`
1
+ import{b as fr}from"./chunk-JM3JCK2K.js";import{e as vt,g as zt,i as vi,j as Ii,k as Oi,l as Li,m as Di}from"./chunk-QLPFOHKZ.js";import{c as Mt,d as vo,g as Te,h as tn}from"./chunk-IJCIHHAH.js";import{a as dr,b as Mi,c as oe,d as pe}from"./chunk-SIINYZWE.js";import{a as Tt,c as Dn,d as hn,e as Ts,f as Ao,g as Mo,j as Ft,k as en,l as Pn,m as Kn,n as ln,o as gn,p as co,q as cr,r as Yn,s as fo}from"./chunk-4TZKD2XR.js";import{a as Xe,c as Rs}from"./chunk-56EJGQU3.js";import{c as Pi,d as Fi,e as Yo}from"./chunk-ROHVHR3J.js";import Yt from"dotenv";import{GoogleGenAI as fl,ThinkingLevel as pt,HarmBlockThreshold as eo,HarmCategory as to}from"@google/genai";import{execSync as Ui}from"child_process";import{spawn as ur}from"child_process";var L=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 u=0;for(let y=l-1;y>=0&&e[y]==="\\";y--)u++;if(u%2!==0){d=l+1;continue}let f=e.substring(l+1),m=f.trim(),g=m===""||/^,\s*\w+\s*=/.test(m)||m.startsWith(")")&&(m.length===1||/^\)\s*([,\]\s]|\[\[?tool:)/i.test(m));if(g&&f.startsWith(`
2
2
  `)){let y=m.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,u)=>{switch(u){case"n":return`
4
4
  `;case"r":return"\r";case"t":return" ";case"\\":return"\\";default:return u===a?a:u}})}else if(t<e.length&&e[t]==="["){let a=0,i=null,p=t,d=-1;for(let c=t;c<e.length;c++){let l=e[c];if(i&&l===i){let u=0;for(let f=c-1;f>=0&&e[f]==="\\";f--)u++;u%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 Es=null;try{let e=await import("node-pty");Es=e.default||e}catch{}var $d=!!Es,Cs=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),pr=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 u=n[t];for(;o>u.length;)u.push(" ");u[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 u=l[0]||1;t=Math.max(0,t-u)}else if(c==="B"){let u=l[0]||1;for(t=t+u;t>=n.length;)n.push([])}else if(c==="C"){let u=l[0]||1;o=o+u}else if(c==="D"){let u=l[0]||1;o=Math.max(0,o-u)}else if(c==="G"){let u=(l[0]||1)-1;o=Math.max(0,u)}else if(c==="H"||c==="f"){let u=(l[0]||1)-1,f=(l[1]||1)-1;for(t=Math.max(0,u),o=Math.max(0,f);t>=n.length;)n.push([])}else if(c==="K"){let u=l[0]||0;if(t<n.length){let f=n[t];if(u===0)f.length=o;else if(u===1)for(let m=0;m<o&&m<f.length;m++)f[m]=" ";else u===2&&(f.length=0)}}else if(c==="J"){let u=l[0]||0;(u===2||u===3)&&(n.length=0,n.push([]),t=0,o=0)}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
- `)},wt=null,Yo=!1,Ad=e=>{try{wt&&(Yo&&typeof wt.write=="function"?wt.write(e):wt.stdin&&wt.stdin.writable&&wt.stdin.write(e))}catch{}},Md=()=>{if(wt){try{Yo&&typeof wt.destroy=="function"?wt.destroy():typeof wt.kill=="function"&&(process.platform==="win32"?ur("taskkill",["/pid",wt.pid,"/f","/t"]):wt.kill("SIGKILL"))}catch{}wt=null,Yo=!1}},mr=(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&&Pn()){let u=[],f=c+1;for(;f<t.length;){let m=t[f];if([">",">>","<","&","&&","|","||",";"].includes(m))break;m!=="-p"&&m!=="--parents"&&m!=="-v"&&m!=="--verbose"&&u.push(m),f++}if(u.length>0){let m=u.map(g=>{let y=g.replace(/^['"]|['"]$/g,""),h=g;return a(y)&&(h=g.replace(/\//g,"\\")),h});i.push("New-Item","-ItemType","Directory","-Force","-Path",m.join(","))}else i.push("New-Item","-ItemType","Directory","-Force");c=f-1;continue}if(l==="rm"&&n&&Pn()){let u=[],f=!1,m=!1,g=c+1;for(;g<t.length;){let h=t[g];if([">",">>","<","&","&&","|","||",";"].includes(h))break;h==="-rf"||h==="-fr"?(f=!0,m=!0):h==="-r"||h==="-R"||h==="--recursive"?f=!0:h==="-f"||h==="--force"?m=!0:u.push(h),g++}let y=["Remove-Item"];if(f&&y.push("-Recurse"),m&&y.push("-Force"),u.length>0){let h=u.map(w=>{let x=w.replace(/^['"]|['"]$/g,""),T=w;return a(x)&&(T=w.replace(/\//g,"\\")),T});y.push("-Path",h.join(","))}i.push(...y),c=g-1;continue}if(l==="cp"&&n&&Pn()){let u=[],f=!1,m=!1,g=c+1;for(;g<t.length;){let h=t[g];if([">",">>","<","&","&&","|","||",";"].includes(h))break;h==="-r"||h==="-R"||h==="--recursive"?f=!0:h==="-f"||h==="--force"?m=!0:u.push(h),g++}let y=["Copy-Item"];if(f&&y.push("-Recurse"),m&&y.push("-Force"),u.length>0){let h=u.map(w=>{let x=w.replace(/^['"]|['"]$/g,""),T=w;return a(x)&&(T=w.replace(/\//g,"\\")),T});if(h.length>1){let w=h.pop();y.push("-Path",h.join(","),"-Destination",w)}else y.push("-Path",h[0])}i.push(...y),c=g-1;continue}if(l==="touch"&&n&&Pn()){let u=[],f=c+1;for(;f<t.length;){let m=t[f];if([">",">>","<","&","&&","|","||",";"].includes(m))break;u.push(m),f++}if(u.length>0){let g=`(${u.map(y=>{let h=y.replace(/^['"]|['"]$/g,""),w=y;return a(h)&&(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=f-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 u=t[c+1];if(u){let f=u.replace(/^['"]|['"]$/g,""),m=/\.(txt|md|json|log|csv|html|css|py|js|xml|yaml|yml|pdf|docx|pptx|xlsx)$/i.test(f);if(a(f)&&m){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 u=/^['"]|['"]$/.test(c),f=c;p&&u&&(f=c.replace(/^['"]|['"]$/g,""));let m=/^['"]|['"]$/.test(f),g=f.replace(/^['"]|['"]$/g,"");a(g)&&(f=f.replace(/\//g,"\\"));let y=f.replace(/^['"]|['"]$/g,"");return y.includes(" ")&&!m&&(f=`"${y}"`),f});if(n){let c="",l=0;for(let u=0;u<d.length;u++){let f=d[u];f==="&&"?(c+="; if ($?) {",l++):f===";"?(c+=" }".repeat(l)+";",l=0):(c&&!c.endsWith(" ")&&!c.endsWith("{")&&(c+=" "),c+=f)}return c+=" }".repeat(l),c}return d.join(" ")},hr=async(e,n={})=>{let{command:t}=D(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=mr(t,c),u;s?d==="pwsh"?u="pwsh.exe":d==="powershell"?u="powershell.exe":u="cmd.exe":u=process.env.SHELL||"bash";let f=s?c?["-NoProfile","-Command",l]:["/c",l]:["-c",l];if(r.networkAccess===!1&&!s){let m=u,g=[...f];if(process.platform==="linux")u="unshare",f=["-n","-r",m,...g];else if(process.platform==="darwin"){let y=`(version 1)
6
+ `)},wt=null,Vo=!1,Ad=e=>{try{wt&&(Vo&&typeof wt.write=="function"?wt.write(e):wt.stdin&&wt.stdin.writable&&wt.stdin.write(e))}catch{}},Md=()=>{if(wt){try{Vo&&typeof wt.destroy=="function"?wt.destroy():typeof wt.kill=="function"&&(process.platform==="win32"?ur("taskkill",["/pid",wt.pid,"/f","/t"]):wt.kill("SIGKILL"))}catch{}wt=null,Vo=!1}},mr=(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&&Fn()){let u=[],f=c+1;for(;f<t.length;){let m=t[f];if([">",">>","<","&","&&","|","||",";"].includes(m))break;m!=="-p"&&m!=="--parents"&&m!=="-v"&&m!=="--verbose"&&u.push(m),f++}if(u.length>0){let m=u.map(g=>{let y=g.replace(/^['"]|['"]$/g,""),h=g;return a(y)&&(h=g.replace(/\//g,"\\")),h});i.push("New-Item","-ItemType","Directory","-Force","-Path",m.join(","))}else i.push("New-Item","-ItemType","Directory","-Force");c=f-1;continue}if(l==="rm"&&n&&Fn()){let u=[],f=!1,m=!1,g=c+1;for(;g<t.length;){let h=t[g];if([">",">>","<","&","&&","|","||",";"].includes(h))break;h==="-rf"||h==="-fr"?(f=!0,m=!0):h==="-r"||h==="-R"||h==="--recursive"?f=!0:h==="-f"||h==="--force"?m=!0:u.push(h),g++}let y=["Remove-Item"];if(f&&y.push("-Recurse"),m&&y.push("-Force"),u.length>0){let h=u.map(w=>{let x=w.replace(/^['"]|['"]$/g,""),T=w;return a(x)&&(T=w.replace(/\//g,"\\")),T});y.push("-Path",h.join(","))}i.push(...y),c=g-1;continue}if(l==="cp"&&n&&Fn()){let u=[],f=!1,m=!1,g=c+1;for(;g<t.length;){let h=t[g];if([">",">>","<","&","&&","|","||",";"].includes(h))break;h==="-r"||h==="-R"||h==="--recursive"?f=!0:h==="-f"||h==="--force"?m=!0:u.push(h),g++}let y=["Copy-Item"];if(f&&y.push("-Recurse"),m&&y.push("-Force"),u.length>0){let h=u.map(w=>{let x=w.replace(/^['"]|['"]$/g,""),T=w;return a(x)&&(T=w.replace(/\//g,"\\")),T});if(h.length>1){let w=h.pop();y.push("-Path",h.join(","),"-Destination",w)}else y.push("-Path",h[0])}i.push(...y),c=g-1;continue}if(l==="touch"&&n&&Fn()){let u=[],f=c+1;for(;f<t.length;){let m=t[f];if([">",">>","<","&","&&","|","||",";"].includes(m))break;u.push(m),f++}if(u.length>0){let g=`(${u.map(y=>{let h=y.replace(/^['"]|['"]$/g,""),w=y;return a(h)&&(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=f-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 u=t[c+1];if(u){let f=u.replace(/^['"]|['"]$/g,""),m=/\.(txt|md|json|log|csv|html|css|py|js|xml|yaml|yml|pdf|docx|pptx|xlsx)$/i.test(f);if(a(f)&&m){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 u=/^['"]|['"]$/.test(c),f=c;p&&u&&(f=c.replace(/^['"]|['"]$/g,""));let m=/^['"]|['"]$/.test(f),g=f.replace(/^['"]|['"]$/g,"");a(g)&&(f=f.replace(/\//g,"\\"));let y=f.replace(/^['"]|['"]$/g,"");return y.includes(" ")&&!m&&(f=`"${y}"`),f});if(n){let c="",l=0;for(let u=0;u<d.length;u++){let f=d[u];f==="&&"?(c+="; if ($?) {",l++):f===";"?(c+=" }".repeat(l)+";",l=0):(c&&!c.endsWith(" ")&&!c.endsWith("{")&&(c+=" "),c+=f)}return c+=" }".repeat(l),c}return d.join(" ")},hr=async(e,n={})=>{let{command:t}=L(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=mr(t,c),u;s?d==="pwsh"?u="pwsh.exe":d==="powershell"?u="powershell.exe":u="cmd.exe":u=process.env.SHELL||"bash";let f=s?c?["-NoProfile","-Command",l]:["/c",l]:["-c",l];if(r.networkAccess===!1&&!s){let m=u,g=[...f];if(process.platform==="linux")u="unshare",f=["-n","-r",m,...g];else if(process.platform==="darwin"){let y=`(version 1)
7
7
  (allow default)
8
8
  (deny network-outbound)
9
9
  (allow network-outbound (remote ip "localhost:*"))
10
10
  (allow network-outbound (remote ip "127.0.0.1:*"))
11
- `;u="sandbox-exec",f=["-p",y,m,...g]}}if(Es)try{let m=Es.spawn(u,f,{name:"xterm-256color",cols:n.cols||120,rows:n.rows||30,cwd:process.cwd(),env:{...process.env,CI:"false",TERM:"xterm-256color",FORCE_COLOR:"1",...a}});wt=m,Yo=!0;let g="",y=!1;return m.onData(h=>{if(!y){g+=h,o&&o(h);let w=Cs(g);/(?:Network:\s+use\s+--host\s+to|Network:\s+Type\s+--host\s+to|Local:\s+http:\/\/localhost:\d+|ready in \d+\s*ms|Compiled successfully|Development server is running|Listening on:)/i.test(w)&&(y=!0,setTimeout(()=>i(`SUCCESS: Dev server started successfully in background.
11
+ `;u="sandbox-exec",f=["-p",y,m,...g]}}if(Es)try{let m=Es.spawn(u,f,{name:"xterm-256color",cols:n.cols||120,rows:n.rows||30,cwd:process.cwd(),env:{...process.env,CI:"false",TERM:"xterm-256color",FORCE_COLOR:"1",...a}});wt=m,Vo=!0;let g="",y=!1;return m.onData(h=>{if(!y){g+=h,o&&o(h);let w=Cs(g);/(?:Network:\s+use\s+--host\s+to|Network:\s+Type\s+--host\s+to|Local:\s+http:\/\/localhost:\d+|ready in \d+\s*ms|Compiled successfully|Development server is running|Listening on:)/i.test(w)&&(y=!0,setTimeout(()=>i(`SUCCESS: Dev server started successfully in background.
12
12
 
13
13
  ${w}`),500))}}),m.onExit(({exitCode:h})=>{if(y)return;wt=null;let w=pr(g||""),x=Cs(w).replace(/\n{3,}/g,`
14
14
 
@@ -21,7 +21,7 @@ ${x}`)}),!0}catch(m){return s&&(d==="pwsh"||d==="powershell")&&m.code==="ENOENT"
21
21
  (deny network-outbound)
22
22
  (allow network-outbound (remote ip "localhost:*"))
23
23
  (allow network-outbound (remote ip "127.0.0.1:*"))
24
- `;d="sandbox-exec",c=["-p",h,g,...y]}}let l=i?ur(d,c,{cwd:process.cwd(),env:{...process.env,...o}}):ur(d,c,{cwd:process.cwd(),env:{...process.env,CI:"false",TERM:"xterm-256color",FORCE_COLOR:"1",...o}});wt=l,Yo=!1,l.stdin&&l.stdin.on("error",()=>{wt=null});let u="",f="",m=!1;l.stdout.on("data",g=>{if(!m){let y=g.toString();u+=y,s&&s(y);let h=Cs(u);/(?:Network:\s+use\s+--host\s+to|Network:\s+Type\s+--host\s+to|Local:\s+http:\/\/localhost:\d+|ready in \d+\s*ms|Compiled successfully|Development server is running|Listening on:)/i.test(h)&&(m=!0,setTimeout(()=>e(`SUCCESS: Dev server started successfully in background.
24
+ `;d="sandbox-exec",c=["-p",h,g,...y]}}let l=i?ur(d,c,{cwd:process.cwd(),env:{...process.env,...o}}):ur(d,c,{cwd:process.cwd(),env:{...process.env,CI:"false",TERM:"xterm-256color",FORCE_COLOR:"1",...o}});wt=l,Vo=!1,l.stdin&&l.stdin.on("error",()=>{wt=null});let u="",f="",m=!1;l.stdout.on("data",g=>{if(!m){let y=g.toString();u+=y,s&&s(y);let h=Cs(u);/(?:Network:\s+use\s+--host\s+to|Network:\s+Type\s+--host\s+to|Local:\s+http:\/\/localhost:\d+|ready in \d+\s*ms|Compiled successfully|Development server is running|Listening on:)/i.test(h)&&(m=!0,setTimeout(()=>e(`SUCCESS: Dev server started successfully in background.
25
25
 
26
26
  ${h}`),500))}}),l.stderr.on("data",g=>{if(!m){let y=g.toString();f+=y,s&&s(y)}}),l.on("close",g=>{if(m)return;wt=null;let y=[],h=pr(u),w=pr(f);h&&y.push(`STDOUT:
27
27
  ${h}`),w&&y.push(`STDERR:
@@ -33,7 +33,7 @@ ${w}`),g!==0&&y.push(`EXIT CODE: ${g}`);let x=y.join(`
33
33
 
34
34
  ${T}`:`SUCCESS: Command [${t}] completed.
35
35
 
36
- ${T}`)}),l.on("error",g=>{if(i&&g.code==="ENOENT"){if(r==="pwsh"){let h=mr(t,!0);return _s(e,h,t,o,s,"powershell",a)}else if(r==="powershell"){let h=mr(t,!1);return _s(e,h,t,o,s,"cmd",a)}}wt=null;let y=g instanceof Error?g.message:String(g);e(`ERROR: Failed to start command [${t}]: ${y}`)})};var Vo=null,Ml=()=>{if(process.platform!=="win32")return!1;if(Vo!==null)return Vo;try{Ui("where.exe pwsh.exe",{stdio:"ignore",windowsHide:!0}),Vo=!0}catch{Vo=!1}return Vo},Xo=null,Pn=()=>{if(process.platform!=="win32")return!1;if(Xo!==null)return Xo;try{Ui("where.exe powershell.exe",{stdio:"ignore",windowsHide:!0}),Xo=!0}catch{Xo=!1}return Xo},Ni=()=>Ml()?"pwsh":Pn()?"powershell":"cmd",gr=null,Bi=(e,n,t,o,s=!1,r=!0,a)=>{gr===null&&(gr=s);let i=`- Mandatorily JSON escape literal sequences (backslash: \\\\, newLine: \\ n, quote: \\")
36
+ ${T}`)}),l.on("error",g=>{if(i&&g.code==="ENOENT"){if(r==="pwsh"){let h=mr(t,!0);return _s(e,h,t,o,s,"powershell",a)}else if(r==="powershell"){let h=mr(t,!1);return _s(e,h,t,o,s,"cmd",a)}}wt=null;let y=g instanceof Error?g.message:String(g);e(`ERROR: Failed to start command [${t}]: ${y}`)})};var Xo=null,Ml=()=>{if(process.platform!=="win32")return!1;if(Xo!==null)return Xo;try{Ui("where.exe pwsh.exe",{stdio:"ignore",windowsHide:!0}),Xo=!0}catch{Xo=!1}return Xo},Jo=null,Fn=()=>{if(process.platform!=="win32")return!1;if(Jo!==null)return Jo;try{Ui("where.exe powershell.exe",{stdio:"ignore",windowsHide:!0}),Jo=!0}catch{Jo=!1}return Jo},Ni=()=>Ml()?"pwsh":Fn()?"powershell":"cmd",gr=null,Bi=(e,n,t,o,s=!1,r=!0,a)=>{gr===null&&(gr=s);let i=`- Mandatorily JSON escape literal sequences (backslash: \\\\, newLine: \\ n, quote: \\")
37
37
  - Same file, multiple edits? One PatchFile (\u226415 blocks)${a?"":`
38
38
  - Tool denied? Ask for guidance`}
39
39
  - Need text or huge file? CodeSearch > Full Read
@@ -46,9 +46,13 @@ ${T}`)}),l.on("error",g=>{if(i&&g.code==="ENOENT"){if(r==="pwsh"){let h=mr(t,!0)
46
46
  - PatchFile(path=string, allowMultiple?=bool, searchContent1="string match OR ^LINE:start..end$", newContent1=string, ...MAX15). Small searchString. Line Ranges: ^...$ syntax, must for large blocks/escape sequences
47
47
  - WriteFile(path=string, content=string). Creates/Overwrites. File Exist? PatchFile > WriteFile
48
48
  - CodeSearch(keyword=string, path?="dir/file/glob/regex, inclusion/exclusion ;-separated", fuzzy?=bool, regex?=bool:auto). Find relevant code, standard junk excluded
49
- - Run(command=string). Runs ${n==="Windows"?Pn()?"powershell":"windows CMD":"bash"} command. Destructive command \u2192 Ask user
50
- - Goal(method="create/append/get", tasks=string[], markDone=string[]). If long multi-task: create Goals before starting. \`get + markDone\` marks complete
51
- ${gr?'\n**Emergency Tools**\nInfo: `initial` = current task prompt. Revert `id` = turn before disaster (eg. disaster: `turn_3` \u2192 revert: `turn_2`). Reason explicitly\n- EmergencyRollback(method="getCheckpoint/forceRevert", id=string). Rollback workspace in this agent loop. ONLY for catastrophic corruption. Before ending, verify no catastrophe. `getCheckpoint`: `id` excluded\n':""}${r?`
49
+ - Run(command=string). Runs ${n==="Windows"?Fn()?"powershell":"windows CMD":"bash"} command. Destructive command \u2192 Ask user
50
+ - Goal(method="create/append/get", tasks=string[], markDone=string[]). If long multi-task: create Goals before starting. get + markDone marks complete
51
+ ${gr?`
52
+ **Emergency Tools**
53
+ Info: initial = current task prompt. Revert id = turn before disaster (eg. disaster: turn_3 \u2192 revert: turn_2). Reason explicitly
54
+ - EmergencyRollback(method="getCheckpoint/forceRevert", id=string). Rollback workspace in this agent loop. ONLY for catastrophic corruption. Before ending, verify no catastrophe. getCheckpoint: id excluded
55
+ `:""}${r?`
52
56
  **Sub Agent Tools**
53
57
  Default to using subagents whenever helpful, no user nudge needed
54
58
  Invocations:
@@ -121,7 +125,7 @@ MANDATORY: Brief verification for technical tasks/greetings`,Minimal:`Effort: Lo
121
125
  Quick, focused thinking, intent & complexity, required tools/files/actions, before acting
122
126
  Brief thoughts, think only enough to avoid mistakes, verify imports, system stability`,Off:`Effort: Lowest
123
127
  No thinking. Immediate response
124
- Verify imports, tool results & system stability`};import Vn from"fs";import Er from"path";import Ol from"os";import Dl from"screenshot-desktop";import Cn from"fs";import Yn from"path";import ea from"fs";import yr from"path";import{execSync as ta}from"child_process";import{fileURLToPath as Il}from"url";var ji=`# FluxFlow CLI Startup & Flags Reference
128
+ Verify imports, tool results & system stability`};import Xn from"fs";import Er from"path";import Ol from"os";import Ll from"screenshot-desktop";import _n from"fs";import Vn from"path";import ea from"fs";import yr from"path";import{execSync as ta}from"child_process";import{fileURLToPath as Il}from"url";var ji=`# FluxFlow CLI Startup & Flags Reference
125
129
 
126
130
  Launch command syntax:
127
131
  fluxflow [options]
@@ -135,7 +139,7 @@ fluxflow [options]
135
139
  * --path project/path \u2192 Set working directory for session
136
140
  * --memory on | off \u2192 Toggle persistent long-term agent memory
137
141
  * --resume session-id \u2192 Resume previous chat session programmatically
138
- * --allocation mb \u2192 Override Node.js \`--max-old-space-size\` in MB (Req \`env.EXPERIMENTAL_MEMORY_MANAGER\` enabled \u2192 Ref: \`references/ENV.md\`)
142
+ * --allocation mb \u2192 Override Node.js --max-old-space-size in MB (Req env.EXPERIMENTAL_MEMORY_MANAGER enabled \u2192 Ref: references/ENV.md)
139
143
  * --package npm | pnpm | yarn | bun \u2192 Override package manager for core updates
140
144
  * --auto-del 1d | 7d | 30d \u2192 History auto-deletion retention timeframe
141
145
  * --auto-exec on | off / --yolo on | off \u2192 Toggle autonomous command execution
@@ -149,9 +153,12 @@ fluxflow [options]
149
153
  * --help \u2192 CLI help menu
150
154
  * --help commands \u2192 In-chat slash commands list
151
155
  * --playground \u2192 Launch Playground mode
152
- `;var Gi=`# FluxFlow Environment Variables Reference
156
+ `;var Gi=`# Env Variables
153
157
 
154
- Configure in shell or place inside \`./.fluxflow.env\` or \`~/.fluxflow/.fluxflow.env\` for globals
158
+ * Locations:
159
+ * Shell
160
+ * Global: ~/.fluxflow/.env.fluxflow | ~/.fluxflow/.env.agents
161
+ * Workspace: ./.env.fluxflow | ./.env.agents
155
162
 
156
163
  ## Core Variables
157
164
  * SUBAGENT_MODEL \u2192 Model override for sub-agents
@@ -171,7 +178,7 @@ Configure in shell or place inside \`./.fluxflow.env\` or \`~/.fluxflow/.fluxflo
171
178
 
172
179
  * I_HAVE_TOO_MUCH_MONEY \u2192 (true|false, default: false) Fun Flag; inserts random padding in system prompt to break provider caching. Not intended for paid APIs unless user hate money
173
180
  * GOOGLE_GEMMA_NONSENSE \u2192 (true|false, default: false) for the 16k TPM nonsense of gemma models on gemini API. False defaults to 256k
174
- `;var Hi=`# FluxFlow In-Session Slash Commands
181
+ `;var Hi=`# Fluxflow in-app /commands
175
182
 
176
183
  Trigger in chat via /command
177
184
 
@@ -216,16 +223,16 @@ Trigger in chat via /command
216
223
  * /update latest \u2192 Install latest release
217
224
  `;var qi=`# FluxFlow In-App Settings Reference
218
225
 
219
- Open in chat via \`/settings\`
226
+ Open in chat via /settings
220
227
 
221
228
  ## Settings Categories & Options
222
229
 
223
- ### 1. Providers & Tips \u2192 \`references/PROVIDERS.md\`
230
+ ### 1. Providers & Tips \u2192 references/PROVIDERS.md
224
231
 
225
232
  ### 2. Appearance
226
233
  * Theme \u2192 UI theme (Dark | Light | Cyberpunk | Forest | Sunset | Matrix | Dracula | Nord | Monokai | Mystery/Chaos)
227
234
  * Loading Phrases \u2192 Humorous status phrases during thinking
228
- * Progressive Rendering \u2192 Smooth streaming token rendering
235
+ * Progressive Rendering [Experimental] \u2192 Smooth streaming token rendering. May have few glitches
229
236
  * Show TPM Estimate \u2192 Real-time Tokens Throughput speed estimate
230
237
 
231
238
  ### 3. Memory
@@ -264,21 +271,21 @@ Open in chat via \`/settings\`
264
271
  * Auto Truncate Results \u2192 Auto-truncate tool results after task finished to save token and improve caching
265
272
  `;var zi=`# FluxFlow Tool Reference
266
273
 
267
- ## Protocol: \`[tool:functions.ToolName(arg1="val")]\`
274
+ ## Protocol: [tool:functions.ToolName(arg1="val")]
268
275
 
269
276
  ## 1. Workspace
270
277
  * ReadFile(path, startLine?, endLine?) \u2192 Read text/code/PDF/image
271
- * PatchFile(path, searchContent1..15, newContent1..15, allowMultiple?) \u2192 Atomic multi-replacement; supports \`^LINE:start..end$\`
278
+ * PatchFile(path, searchContent1..15, newContent1..15, allowMultiple?) \u2192 Atomic multi-replacement; supports ^LINE:start..end$
272
279
  * WriteFile(path, content) \u2192 Create/overwrite file
273
280
  * ReadFolder(path, recurse?) \u2192 List directory tree (depth: 1-3)
274
- * CodeSearch / SearchKeyword(keyword, path?, fuzzy?, regex?) \u2192 Fast text search; \`path="#docs"\` for doc index
281
+ * CodeSearch / SearchKeyword(keyword, path?, fuzzy?, regex?) \u2192 Fast text search; path="#docs" for doc index
275
282
  * Run(command) \u2192 Execute command in shell
276
- * Todo(method, tasks?, markDone?) \u2192 Planner (\`"create" | "append" | "get"\`)
283
+ * Todo(method, tasks?, markDone?) \u2192 Planner ("create" | "append" | "get")
277
284
 
278
285
  ## 2. Web & Communication
279
286
  * WebSearch(query, aiMode?, limit?) \u2192 Live web search + AI summary
280
287
  * WebScrape(url) \u2192 Extract markdown from URL
281
- * Ask(question, optionA..D?) \u2192 Interactive prompt to user (\`"title::desc"\`)
288
+ * Ask(question, optionA..D?) \u2192 Interactive prompt to user ("title::desc")
282
289
 
283
290
  ## 3. Sub-Agents
284
291
  * InvokeSync(title, task) \u2192 Blocking sub-agent
@@ -289,7 +296,7 @@ Open in chat via \`/settings\`
289
296
  * Cancel(id) \u2192 Terminate worker
290
297
 
291
298
  ## 4. Emergency & Rollback
292
- * EmergencyRollback(method, id?) \u2192 Checkpoint restore (\`"getCheckpoint" | "forceRevert"\`)
299
+ * EmergencyRollback(method, id?) \u2192 Checkpoint restore ("getCheckpoint" | "forceRevert")
293
300
 
294
301
  ## 5. Creative Documents
295
302
  * WritePDF(path, content, orientation?) \u2192 Render HTML/CSS to PDF
@@ -298,39 +305,39 @@ Open in chat via \`/settings\`
298
305
  ## 6. Computer Use (GUI)
299
306
  * Click(gridId, type?, button?, intendedClickText?) \u2192 Click coordinate + OCR snap
300
307
  * Drag(fromGridId, toGridId) \u2192 Mouse drag
301
- * Scroll(direction, gridId?) \u2192 Viewport scroll (\`"up" | "down"\`)
308
+ * Scroll(direction, gridId?) \u2192 Viewport scroll ("up" | "down")
302
309
  * KeyboardTyping(text, autoPressEnter?) \u2192 Type string
303
- * KeyPress(key) \u2192 Key/combo dispatch (\`"ctrl;c"\`, \`"enter"\`, etc.)
310
+ * KeyPress(key) \u2192 Key/combo dispatch ("ctrl;c", "enter", etc.)
304
311
  * RecaptureScreen() \u2192 Fresh screenshot + coordinate grid
305
- `;var Ki=`# FluxFlow Architecture
312
+ `;var Ki=`# Fluxflow Architecture
306
313
 
307
314
  ## 1. Terminal Engine
308
315
  * Framework: React + Ink terminal UI
309
- * Sub-Terminal: Live PTY shell bridge; \`TAB\` switches active keyboard focus
310
- * OS Compatibility: Auto-detects \`pwsh\`, \`powershell\`, \`bash\`, \`cmd\`
316
+ * Sub-Terminal: Live PTY shell bridge; TAB switches active keyboard focus
317
+ * OS Compatibility: Auto-detects pwsh, powershell, bash, cmd
311
318
 
312
319
  ## 2. Dual-Model Runtime
313
320
  * Main Agent: Reasoning, code edits, and tool calls
314
- * Memory Agent: Background context & preference synthesizer (fixed models; disable via \`/settings \u2192 Memory\` or use NIM API key)
321
+ * Memory Agent: Background context & preference synthesizer (fixed models; disable via /settings \u2192 Memory or use NIM API key)
315
322
 
316
323
  ## 3. Multi-Agent System
317
- * Execution: Synchronous (\`InvokeSync\`) | Asynchronous (\`Invoke\`, \u2264 7 workers)
324
+ * Execution: Synchronous (InvokeSync) | Asynchronous (Invoke, \u22647 workers)
318
325
  * Isolation: Restricted tool scope per subagent
319
326
  * State Tracking: Mutations logged under parent task ledger
320
327
 
321
328
  ## 4. Security & Sandbox
322
329
  * Approvals: HITL confirmation on destructive file/shell operations
323
330
  * Modes: Strict | Balanced | Autonomous (YOLO)
324
- * Recovery: Pre-turn snapshot indexing via \`EmergencyRollback\`
331
+ * Recovery: Pre-turn snapshot indexing via EmergencyRollback
325
332
 
326
333
  ## 5. Computer Use Automation
327
334
  * Vision: 720p normalized canvas, 4ms variance scan, Set-of-Marks (SoM) overlay
328
335
  * OCR Alignment: Euclidean distance text matching to mark centers
329
- * Hardware I/O: OS input dispatch via \`@nut-tree-fork/nut-js\`
336
+ * Hardware I/O: OS input dispatch via @nut-tree-fork/nut-js
330
337
  * Memory Management: 2-turn sliding window with active V8 GC
331
338
 
332
339
  ## 6. IDE Bridge
333
- * Protocol: WebSocket on \`ws://localhost:56832\`
340
+ * Protocol: WebSocket on ws://localhost:56832
334
341
  * State Sync: Focused file, open tabs, cursor line, selection, diagnostics
335
342
  `;var Yi=`# FluxFlow Sub-Agents & Multi-Agent Architecture
336
343
 
@@ -383,10 +390,10 @@ Route sub-agent workloads to faster/cheaper models independently of the main age
383
390
  * Terminal Network Isolation \u2192 Blocks outbound network sockets for spawned shell commands when networkAccess: OFF
384
391
 
385
392
  ## Recovery & Data Sanctuary
386
- * Emergency Rollback \u2192 Automatic pre-turn file snapshots; Agent can still fix it (default: OFF) \u2192 \`references/SETTINGS.md\`
393
+ * Emergency Rollback \u2192 Automatic pre-turn file snapshots; Agent can still fix it (default: OFF) \u2192 references/SETTINGS.md
387
394
  * Git-less Checkpoint Reversion \u2192 Trigger conversational changes rollback via double-ESC
388
- * External Sanctuary Redirection \u2192 Move \`~/.fluxflow\` data sanctuary (chats, keys etc)
389
- `;var Xi=`# FluxFlow IDE Integration & Real-Time Context
395
+ * External Sanctuary Redirection \u2192 Move ~/.fluxflow data sanctuary (chats, keys etc)
396
+ `;var Xi=`# Fluxflow IDE Companion
390
397
 
391
398
  ## WebSocket Bridge Protocol
392
399
  * Local Bridge \u2192 Runs on ws://localhost:56832 connecting FluxFlow CLI with the companion editor extension
@@ -404,12 +411,55 @@ Route sub-agent workloads to faster/cheaper models independently of the main age
404
411
  * File Focus \u2192 Automatically opens edited files in active IDE window
405
412
  * Diff Preview \u2192 Streams side-by-side or inline diff highlights (showDiff, highlightDiff) directly in editor
406
413
  * Status Bar Sync \u2192 Real-time agent status (thinking, running tool, awaiting input) reflected in IDE status bar
407
- `;var Ji="# FluxFlow Operating Modes\n\n## Modes Overview\n* [Flux] (Workspace / Dev) \u2192 Primary coding & workspace agent\n* [Flow] (Studio / Creative) \u2192 Web research & formatted document authoring (PDF / DOCX)\n* [ICU] (Computer Use) \u2192 Autonomous GUI & OS desktop automation\n* [FluxCU] (Omni) \u2192 Unified full-stack agent (Workspace Dev + Computer Use + Web)\n\n## Tool Availability\n* File Operations: `ReadFile`, `PatchFile`, `WriteFile`, `ReadFolder`, `CodeSearch` \u2192 [Flux] | [FluxCU]\n* Terminal Execution: `Run` \u2192 [Flux] | [FluxCU]\n* Task Management: `Todo` \u2192 [Flux] | [FluxCU]\n* Sub-Agents: `InvokeSync`, `Invoke`, `Await`, `GetProgress`, `Steer`, `Cancel` \u2192 [Flux] | [FluxCU]\n* Checkpoint Recovery: `EmergencyRollback` \u2192 [Flux] | [FluxCU]\n* Web & Research: `WebSearch`, `WebScrape` \u2192 [Universal]\n* User Inquiry: `AskUser` \u2192 [Universal]\n* Document Creation: `WritePDF`, `WriteDoc` \u2192 [Flow]\n* GUI & Desktop Automation: `Click`, `Drag`, `Scroll`, `KeyboardTyping`, `KeyPress`, `RecaptureScreen` \u2192 [ICU] | [FluxCU]\n";var Qi="# FluxFlow Inference Providers & Setup\n\n## Supported Providers\n* Direct: Gemini (aistudio.google.com) | NVIDIA NIM (build.nvidia.com) | DeepSeek (platform.deepseek.com) | Mistral (admin.mistral.ai) | Ollama (ollama.com) | CrofAI (crof.ai) | InferX (model.inferx.net) | SenseNova (platform.sensenova.ai)\n* Aggregators: OpenRouter (openrouter.ai) | AIHubMix (aihubmix.com)\n\n* Fluxflow has default model list for many providers, updated based on vibes. Can be overriden using `/model <model-id>`\n\n## Setup: Local NVIDIA NIM (OpenAI-Compatible)\n1. Environment Variables (`.fluxflow.env` or shell):\n * `NVIDIA_BASE_URL` = `http://<host>:<port>/v1/chat/completions` (or custom endpoint)\n * `NVIDIA_API_KEY` = Optional API key (if NIM container requires authentication)\n2. Switch Provider: Select `NVIDIA` in `/settings \u2192 Providers`\n3. Select Model: `/model <model_name>`\n* Note: Memory agent is automatically disabled on custom/local endpoints & few providers\n\n## Setup: Ollama (Local / Cloud)\n1. Endpoint & Authentication:\n * Local: Set API Key to `LOCAL` in `/settings \u2192 Providers` or on key prompt\n * Endpoint URL: Default is `http://127.0.0.1:11434` (Override via `OLLAMA_HOST`)\n2. Model Selection:\n * Standard: `/model <model-id>`\n * Multimodal (Vision): `/model <model-id> -m`\n3. Context Window Override:\n * Set `HIGH_CONTEXT=<tokens>` in `.fluxflow.env` (range: `32k` to `1M`)\n";var Zi=`# FluxFlow Instructions & Skills System
408
-
409
- ## 1. High Priority Instructions (AGENTS.md / FLUXFLOW.md)
414
+ `;var Ji=`# Fluxflow Modes
415
+
416
+ ## Modes Overview (TAB to cycle)
417
+ * [Flux] (Workspace / Dev) \u2192 Primary coding & workspace agent
418
+ * [Flow] (Studio / Creative) \u2192 Web research & formatted document authoring (PDF / DOCX)
419
+ * [ICU] (Computer Use) \u2192 Autonomous GUI & OS desktop automation
420
+ * [FluxCU] (Omni) \u2192 Unified full-stack agent (Workspace Dev + Computer Use + Web)
421
+
422
+ ## Tool Availability
423
+ * File Operations: ReadFile, PatchFile, WriteFile, ReadFolder, CodeSearch \u2192 [Flux] | [FluxCU]
424
+ * Terminal Execution: Run \u2192 [Flux] | [FluxCU]
425
+ * Task Management: Todo \u2192 [Flux] | [FluxCU]
426
+ * Sub-Agents: InvokeSync, Invoke, Await, GetProgress, Steer, Cancel \u2192 [Flux] | [FluxCU]
427
+ * Checkpoint Recovery: EmergencyRollback \u2192 [Flux] | [FluxCU]
428
+ * Web & Research: WebSearch, WebScrape \u2192 [Universal]
429
+ * User Inquiry: AskUser \u2192 [Universal]
430
+ * Document Creation: WritePDF, WriteDoc \u2192 [Flow]
431
+ * GUI & Desktop Automation: Click, Drag, Scroll, KeyboardTyping, KeyPress, RecaptureScreen \u2192 [ICU] | [FluxCU]
432
+ `;var Qi=`# FluxFlow AI Providers & Setup
433
+
434
+ ## Supported Providers
435
+ * Direct: Gemini (aistudio.google.com) | NVIDIA NIM (build.nvidia.com) | DeepSeek (platform.deepseek.com) | Mistral (admin.mistral.ai) | Ollama (ollama.com) | CrofAI (crof.ai) | InferX (model.inferx.net) | SenseNova (platform.sensenova.ai)
436
+ * Aggregators: OpenRouter (openrouter.ai) | AIHubMix (aihubmix.com)
437
+
438
+ * Fluxflow has default model list for many providers, updated based on vibes. Can be overriden using /model <model-id>
439
+
440
+ ## Setup: Local NVIDIA NIM (OpenAI-Compatible)
441
+ 1. Environment Variables (.fluxflow.env or shell):
442
+ * NVIDIA_BASE_URL = http://<host>:<port>/v1/chat/completions (or custom OpenAI endpoint)
443
+ * NVIDIA_API_KEY = Optional API key (if NIM container requires authentication)
444
+ 2. Switch Provider: Select NVIDIA in /settings \u2192 Providers
445
+ 3. Select Model: /model <model_name>
446
+ * Memory agent is automatically disabled on custom/local & few providers endpoints
447
+
448
+ ## Setup: Ollama (Local / Cloud)
449
+ 1. Endpoint & Authentication:
450
+ * Local: Set API Key to LOCAL in /settings \u2192 Providers or on key prompt
451
+ * Endpoint URL: Default is http://127.0.0.1:11434 (Override via OLLAMA_HOST)
452
+ 2. Model Selection:
453
+ * Standard: /model <model-id>
454
+ * Multimodal (Vision): /model <model-id> -m
455
+ 3. Context Window Override:
456
+ * Set HIGH_CONTEXT=<tokens> in ENV (range: 32k to 1M)
457
+ `;var Zi=`# Fluxflow Instructions & Skills System
458
+
459
+ ## 1. Instructions
410
460
  * Locations:
411
- * Global: ~/.fluxflow/fluxflow.md | ~/.fluxflow/agents.md
412
- * Workspace: ./fluxflow.md | ./agents.md
461
+ * Global: ~/.fluxflow/FLUXFLOW.md | ~/.fluxflow/AGENTS.md
462
+ * Workspace: ./FLUXFLOW.md | ./AGENTS.md
413
463
  * Auto indexed on boot
414
464
 
415
465
  ## 2. Skills System
@@ -430,38 +480,38 @@ description: System Generated Documentation. Read this if asked anything regardi
430
480
 
431
481
  # FluxFlow, by Kushal Roy Chowdhury
432
482
  Open Source Terminal AI Assistant
433
- App Version: ${As}. Check Updates \`fluxflow --update check\`. Update \`fluxflow --update\`
483
+ App Version: ${As}. Check Updates: fluxflow --update check. Update: fluxflow --update
434
484
  GitHub: https://github.com/KushalRoyChowdhury/fluxflow-cli
435
485
  Documentation: https://fluxflow-cli.onrender.com
436
486
 
437
487
  [tool:functions.SearchKeyword(keyword="regex/word", path="#docs")]. Usage: search any keyword across docs, avoid hunting excessive references
438
488
 
439
489
  ## Supported Features & Documentation References
440
- * Operating Modes (Flux, Flow, CU, FluxCU) \u2192 \`references/MODES.md\`
441
- * Inference Providers & Aggregators (Setup, Local NIM, Ollama) \u2192 \`references/PROVIDERS.md\`
442
- * In-App Settings (\`/settings\`) \u2192 \`references/SETTINGS.md\`
443
- * In-app /commands \u2192 \`references/COMMANDS.md\`
444
- * CLI Startup Flags \u2192 \`references/STARTUP.md\`
445
- * Environment Variables \u2192 \`references/ENV.md\`
446
- * Tool System (Workspace, Web, Communication, Sub-Agents, Safety, Creative, Computer Use) \u2192 \`references/TOOLS.md\`
447
- * Sub-Agents & Multi-Agent Runtime \u2192 \`references/SUB_AGENTS.md\`
448
- * Security, Sandboxing & Checkpoints (\`/revert\`, double-ESC) \u2192 \`references/SECURITY.md\`
449
- * IDE Companion Extension & Real-time Context \u2192 \`references/IDE.md\`
450
- * Priority Instructions (AGENTS.md/FLUXFLOW.md) & Skill System \u2192 \`references/PLUGINS.md\`
451
- * Agent Architecture & Memory System \u2192 \`references/ARCHITECTURE.md\`
452
-
453
- Docs missing required info? Say you are not sure enough to answer. Dont give wrong info`,"references/MODES.md":Ji,"references/PROVIDERS.md":Qi,"references/PLUGINS.md":Zi,"references/STARTUP.md":ji,"references/ENV.md":Gi,"references/COMMANDS.md":Hi,"references/SETTINGS.md":qi,"references/TOOLS.md":zi,"references/ARCHITECTURE.md":Ki,"references/SUB_AGENTS.md":Yi,"references/SECURITY.md":Vi,"references/IDE.md":Xi};var na=()=>{try{let e=Yn.join(Qt,"skills","fluxflow"),n=Yn.join(e,"references");if(process.env.NO_DEV==="true"||process.env.NO_DEV==="1"||process.env.NO_DEV===!0||!1){Cn.existsSync(e)&&Cn.rmSync(e,{recursive:!0,force:!0});return}let o=new Set(Object.keys(wr).map(s=>Yn.normalize(s)));for(let[s,r]of Object.entries(wr)){let a=Yn.join(e,s),i=Yn.dirname(a);Cn.existsSync(i)||Cn.mkdirSync(i,{recursive:!0});let p=r.trim()+`
454
- `,d=null;Cn.existsSync(a)&&(d=Cn.readFileSync(a,"utf8")),d!==p&&Cn.writeFileSync(a,p,"utf8")}if(Cn.existsSync(n)){let s=Cn.readdirSync(n);for(let r of s){let a=Yn.normalize(Yn.join("references",r));if(!o.has(a)){let i=Yn.join(n,r);try{Cn.rmSync(i,{recursive:!0,force:!0})}catch{}}}}}catch{}};var Cr=(e,n)=>{try{if(!Vn.existsSync(e))return null;let t=Array.isArray(n)?n.map(s=>s.toLowerCase()):[n.toLowerCase()],o=Vn.readdirSync(e);for(let s of t){let r=o.find(a=>a.toLowerCase()===s);if(r){let a=Er.join(e,r);if(Vn.statSync(a).isFile())return a}}}catch{}return null},ra=(e,n)=>{let t=Cr(e,n);if(t)try{return Vn.readFileSync(t,"utf8")}catch{}return""},kr=Cr(Qt,["fluxflow.md","agent.md","agents.md"]),Tr=Cr(process.cwd(),["fluxflow.md","agent.md","agents.md"]),Ll=kr?ra(Qt,["fluxflow.md","agent.md","agents.md"]).trim():"",Rr="",ia=!1,Pl=e=>{if(!e||!/^<<<[\s\S]*?Identity:/m.test(e))return e;let n=e.match(/^<<<\s*\r?\n([\s\S]*?)\r?\n>>>\s*(?:\r?\n)?([\s\S]*)$/);if(!n)return e;let t=n[1],o=n[2],s=t.match(/^Identity:\s*([\s\S]*?)(?=\r?\n\s*(?:<><|>>>)|$)/m);return s&&(Rr=s[1].trim(),process.env.NO_DEV=!0),/<><\s*NO_INS/.test(t)&&(ia=!0),o.trim()},vo=Pl(Ll);na();var Qo=Tr?ra(process.cwd(),["fluxflow.md","agent.md","agents.md"]).trim():"",Fl=e=>{if(!e)return null;let n=e.match(/^\s*---\r?\n([\s\S]*?)\r?\n---(?:\r?\n)?([\s\S]*)$/);if(!n)return null;let t=n[1];if((n[2]||"").trim().length===0)return null;let s="",r="",a=t.match(/^name:\s*(.+)$/m),i=t.match(/^description:\s*(.+)$/m);return a&&(s=a[1].trim().replace(/^["']|["']$/g,"")),i&&(r=i[1].trim().replace(/^["']|["']$/g,"")),s&&r?{name:s,description:r}:null},Nl=e=>{let n=[];if(!e||!Vn.existsSync(e))return n;let t=(o,s=0)=>{if(!(s>5))try{let r=Vn.readdirSync(o,{withFileTypes:!0});for(let a of r){let i=Er.join(o,a.name),p=a.name.toLowerCase();a.isFile()?p==="skill.md"&&n.push(i):a.isDirectory()&&(s===0?(p==="skills"||p===".skills"||p==="skill"||p===".skill")&&t(i,s+1):t(i,s+1))}}catch{}};return t(e,0),n},aa=e=>{let n=Nl(e),t=[];for(let o of n)try{let s=Vn.readFileSync(o,"utf8"),r=Fl(s);r&&t.push({...r,filePath:o})}catch{}return t},la=e=>!e||e.length===0?"":e.map(n=>`- ${n.name}: ${n.description}`).join(`
455
- `),ca=aa(Qt),da=aa(process.cwd()),xr=la(ca),br=la(da),fa=e=>{if(!e)return!1;let n=(e.filePath||"").replace(/\\/g,"/").toLowerCase();return n.includes("/skills/fluxflow/skill.md")||n.includes("/skills/about-fluxflow/skill.md")||e.name?.toLowerCase()==="fluxflow"},ua=()=>(ca||[]).filter(e=>!fa(e)),pa=()=>(da||[]).filter(e=>!fa(e)),Mf=(vo?1:0)+(Qo?1:0)+ua().length+pa().length,Sr=(e,n="Project")=>{if(!e)return"";let t=e.replace(/\\/g,"/");if(n==="Global"){let s=Ol.homedir().replace(/\\/g,"/");return t.toLowerCase().startsWith(s.toLowerCase())?"~"+t.slice(s.length):t}let o=Er.relative(process.cwd(),e).replace(/\\/g,"/");return o.startsWith(".")?o:`./${o}`},vf=()=>{let e=[];kr&&vo.length>0&&e.push({scope:"Global",path:kr}),Tr&&Qo.length>0&&e.push({scope:"Project",path:Tr});let n=ua(),t=pa(),o=e.length+n.length+t.length;if(o===0)return`\u2726 Loaded Files & Instructions
490
+ * Operating Modes (Flux, Flow, CU, FluxCU) \u2192 references/MODES.md
491
+ * Inference Providers & Aggregators (Setup, Local NIM, Ollama) \u2192 references/PROVIDERS.md
492
+ * In-App Settings (/settings) \u2192 references/SETTINGS.md
493
+ * In-app /commands \u2192 references/COMMANDS.md
494
+ * CLI Startup Flags \u2192 references/STARTUP.md
495
+ * Environment Variables \u2192 references/ENV.md
496
+ * Tool System (Workspace, Web, Communication, Sub-Agents, Safety, Creative, Computer Use) \u2192 references/TOOLS.md
497
+ * Sub-Agents & Multi-Agent Runtime \u2192 references/SUB_AGENTS.md
498
+ * Security, Sandboxing & Checkpoints (/revert, double-ESC) \u2192 references/SECURITY.md
499
+ * IDE Companion Extension & Real-time Context \u2192 references/IDE.md
500
+ * Priority Instructions (AGENTS.md/FLUXFLOW.md) & Skill System \u2192 references/PLUGINS.md
501
+ * Agent Architecture & Memory System \u2192 references/ARCHITECTURE.md
502
+
503
+ Docs missing required info? Say you are not sure enough to answer. Dont give wrong info`,"references/MODES.md":Ji,"references/PROVIDERS.md":Qi,"references/PLUGINS.md":Zi,"references/STARTUP.md":ji,"references/ENV.md":Gi,"references/COMMANDS.md":Hi,"references/SETTINGS.md":qi,"references/TOOLS.md":zi,"references/ARCHITECTURE.md":Ki,"references/SUB_AGENTS.md":Yi,"references/SECURITY.md":Vi,"references/IDE.md":Xi};var na=()=>{try{let e=Vn.join(Tt,"skills","fluxflow"),n=Vn.join(e,"references");if(process.env.NO_DEV==="true"||process.env.NO_DEV==="1"||process.env.NO_DEV===!0||process.env.NO_INS==="true"||process.env.NO_INS==="1"||process.env.NO_INS===!0||!1){_n.existsSync(e)&&_n.rmSync(e,{recursive:!0,force:!0});return}let o=new Set(Object.keys(wr).map(s=>Vn.normalize(s)));for(let[s,r]of Object.entries(wr)){let a=Vn.join(e,s),i=Vn.dirname(a);_n.existsSync(i)||_n.mkdirSync(i,{recursive:!0});let p=r.trim()+`
504
+ `,d=null;_n.existsSync(a)&&(d=_n.readFileSync(a,"utf8")),d!==p&&_n.writeFileSync(a,p,"utf8")}if(_n.existsSync(n)){let s=_n.readdirSync(n);for(let r of s){let a=Vn.normalize(Vn.join("references",r));if(!o.has(a)){let i=Vn.join(n,r);try{_n.rmSync(i,{recursive:!0,force:!0})}catch{}}}}}catch{}};var Cr=(e,n)=>{try{if(!Xn.existsSync(e))return null;let t=Array.isArray(n)?n.map(s=>s.toLowerCase()):[n.toLowerCase()],o=Xn.readdirSync(e);for(let s of t){let r=o.find(a=>a.toLowerCase()===s);if(r){let a=Er.join(e,r);if(Xn.statSync(a).isFile())return a}}}catch{}return null},ra=(e,n)=>{let t=Cr(e,n);if(t)try{return Xn.readFileSync(t,"utf8")}catch{}return""},kr=Cr(Tt,["fluxflow.md","agent.md","agents.md"]),Tr=Cr(process.cwd(),["fluxflow.md","agent.md","agents.md"]),Dl=kr?ra(Tt,["fluxflow.md","agent.md","agents.md"]).trim():"",Rr="",ia=!1,Pl=e=>{if(!e||!/^<<<[\s\S]*?Identity:/m.test(e))return e;let n=e.match(/^<<<\s*\r?\n([\s\S]*?)\r?\n>>>\s*(?:\r?\n)?([\s\S]*)$/);if(!n)return e;let t=n[1],o=n[2],s=t.match(/^Identity:\s*([\s\S]*?)(?=\r?\n\s*(?:<><|>>>)|$)/m);return s&&(Rr=s[1].trim(),process.env.NO_INS=!0),/<><\s*NO_INS/.test(t)&&(ia=!0),o.trim()},Io=Pl(Dl);na();var Zo=Tr?ra(process.cwd(),["fluxflow.md","agent.md","agents.md"]).trim():"",Fl=e=>{if(!e)return null;let n=e.match(/^\s*---\r?\n([\s\S]*?)\r?\n---(?:\r?\n)?([\s\S]*)$/);if(!n)return null;let t=n[1];if((n[2]||"").trim().length===0)return null;let s="",r="",a=t.match(/^name:\s*(.+)$/m),i=t.match(/^description:\s*(.+)$/m);return a&&(s=a[1].trim().replace(/^["']|["']$/g,"")),i&&(r=i[1].trim().replace(/^["']|["']$/g,"")),s&&r?{name:s,description:r}:null},Nl=e=>{let n=[];if(!e||!Xn.existsSync(e))return n;let t=(o,s=0)=>{if(!(s>5))try{let r=Xn.readdirSync(o,{withFileTypes:!0});for(let a of r){let i=Er.join(o,a.name),p=a.name.toLowerCase();a.isFile()?p==="skill.md"&&n.push(i):a.isDirectory()&&(s===0?(p==="skills"||p===".skills"||p==="skill"||p===".skill")&&t(i,s+1):t(i,s+1))}}catch{}};return t(e,0),n},aa=e=>{let n=Nl(e),t=[];for(let o of n)try{let s=Xn.readFileSync(o,"utf8"),r=Fl(s);r&&t.push({...r,filePath:o})}catch{}return t},la=e=>!e||e.length===0?"":e.map(n=>`- ${n.name}: ${n.description}`).join(`
505
+ `),ca=aa(Tt),da=aa(process.cwd()),xr=la(ca),br=la(da),fa=e=>{if(!e)return!1;let n=(e.filePath||"").replace(/\\/g,"/").toLowerCase();return n.includes("/skills/fluxflow/skill.md")||n.includes("/skills/about-fluxflow/skill.md")||e.name?.toLowerCase()==="fluxflow"},ua=()=>(ca||[]).filter(e=>!fa(e)),pa=()=>(da||[]).filter(e=>!fa(e)),Mf=(Io?1:0)+(Zo?1:0)+ua().length+pa().length,Sr=(e,n="Project")=>{if(!e)return"";let t=e.replace(/\\/g,"/");if(n==="Global"){let s=Ol.homedir().replace(/\\/g,"/");return t.toLowerCase().startsWith(s.toLowerCase())?"~"+t.slice(s.length):t}let o=Er.relative(process.cwd(),e).replace(/\\/g,"/");return o.startsWith(".")?o:`./${o}`},vf=()=>{let e=[];kr&&Io.length>0&&e.push({scope:"Global",path:kr}),Tr&&Zo.length>0&&e.push({scope:"Project",path:Tr});let n=ua(),t=pa(),o=e.length+n.length+t.length;if(o===0)return`\u2726 Loaded Files & Instructions
456
506
  \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m No instruction or skill files are currently loaded.
457
507
  \u2800`;let s=[];return s.push(`\u2726 Loaded Files & Instructions (${o} ${o===1?"file":"files"} active)`),e.length>0&&(s.push(`
458
508
  \x1B[1mInstructions:\x1B[22m`),e.forEach(r=>{s.push(` \u2022 [${r.scope}] ${Sr(r.path,r.scope)}`)})),(n?.length>0||t?.length>0)&&(s.push(`
459
509
  \x1B[1mSkills:\x1B[22m`),n?.length>0&&n.forEach(r=>{s.push(` \u2022 [Global] \x1B[36m${r.name}\x1B[39m`),s.push(` \x1B[2m\u2514\u2500 ${Sr(r.filePath,"Global")}\x1B[22m`)}),t?.length>0&&t.forEach(r=>{s.push(` \u2022 [Project] \x1B[36m${r.name}\x1B[39m`),s.push(` \x1B[2m\u2514\u2500 ${Sr(r.filePath,"Project")}\x1B[22m`)})),s.push("\u2800"),s.join(`
460
- `)},ma=!1;(async()=>{try{let e=await en();if(Number(e?.display)===1){let n=await Dl.listDisplays();n&&n.length>1&&(ma=!0)}}catch{}})();var oa=null,Jo=null,sa=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",If=process.env.NO_DEV||!1,Ul=(e,n)=>{if(!n)return"";if(e!==oa||Jo===null){oa=e;try{let t=oe(Pt,[]);Array.isArray(t)&&t.length>0?Jo=t.map(o=>`- ${o.memory}`).join(`
461
- `):Jo=""}catch(t){Jo="",Vn.appendFileSync(`${mn}/memory/error.txt`,`${t.message}
510
+ `)},ma=!1;(async()=>{try{let e=await tn();if(Number(e?.display)===1){let n=await Ll.listDisplays();n&&n.length>1&&(ma=!0)}}catch{}})();var oa=null,Qo=null,sa=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",If=process.env.NO_DEV||!1,Ul=(e,n)=>{if(!n)return"";if(e!==oa||Qo===null){oa=e;try{let t=oe(Ft,[]);Array.isArray(t)&&t.length>0?Qo=t.map(o=>`- ${o.memory}`).join(`
511
+ `):Qo=""}catch(t){Qo="",Xn.appendFileSync(`${hn}/memory/error.txt`,`${t.message}
462
512
  -------------------------------------------------
463
513
 
464
- `)}}return Jo},ha=(e="",n="",t=!0,o=!1)=>{if(typeof n=="boolean"&&(o=t,t=n,n=""),!t)return"";let s=e?.length>0&&!o?`-- Recent context from other chats (Priority: Low, Focus: Chat Context > Recent) --
514
+ `)}}return Qo},ha=(e="",n="",t=!0,o=!1)=>{if(typeof n=="boolean"&&(o=t,t=n,n=""),!t)return"";let s=e?.length>0&&!o?`-- Recent context from other chats (Priority: Low, Focus: Chat Context > Recent) --
465
515
  ${e}`:"";return s?`${s}`:""},ga=(e,n,t,o,s=!0,r=!1,a="Google",i=!1,p,d)=>{let c=!1;process.env.forcedReasoning&&(c=!0);let l="";if(!p&&a==="Google"){let _=n;n==="Fast"&&(_="Off"),n==="Low"&&(_="Minimal"),n==="Standard"&&(_="Medium"),(n==="xHigh"||n==="Max")&&(_="xHigh"),l=$s[_]||$s.Medium}if(p||a!=="Google"){let _={Fast:"Lowest",Low:"Low",Medium:"Medium",Standard:"Medium",High:"High",xHigh:"High",Max:"High"};l=$s.xHigh,l=l.replace("Effort: High",`Effort: ${_[n]}`).replace(`
466
516
  MANDATORY: Full technical verification`,""),n==="Fast"?l=`Effort: Lowest
467
517
  No thinking. Immediate response
@@ -476,12 +526,12 @@ ${f.length||u.length?"":`
476
526
  `}`:"",g=process.cwd(),y=Ul(d,s),h=y?.length>0?`--- Saved Memories ---
477
527
  ${y}
478
528
 
479
- `:"",w=vo.length>0||Qo.length>0?`--- Additional Instructions ---
480
- ${vo.length>0?`-- Global --
481
- ${vo}`:""}${Qo.length>0?`${vo.length>0?`
529
+ `:"",w=Io.length>0||Zo.length>0?`--- Additional Instructions ---
530
+ ${Io.length>0?`-- Global --
531
+ ${Io}`:""}${Zo.length>0?`${Io.length>0?`
482
532
 
483
533
  `:""}-- Project --
484
- ${Qo}`:""}
534
+ ${Zo}`:""}
485
535
 
486
536
  `:"",x=(()=>{let _=process.cwd().toLowerCase();if(process.platform==="win32"){let R=process.env.SystemRoot?.toLowerCase()||"c:\\windows",S=process.env.ProgramFiles?.toLowerCase()||"c:\\program files",k=process.env["ProgramFiles(x86)"]?.toLowerCase()||"c:\\program files (x86)";return _.startsWith(R)||_.startsWith(S)||_.startsWith(k)}else return _==="/"||["/bin","/sbin","/etc","/usr","/var","/root"].some(S=>_.startsWith(S))})();return`${process.env.I_HAVE_TOO_MUCH_MONEY==="true"||process.env.I_HAVE_TOO_MUCH_MONEY===!0||!1?`${" ".repeat(Math.floor(Math.random()*4)+1)}`:""}=== SYSTEM PROMPT ===
487
537
  Identity: ${Rr.length>1?Rr:"Flux Flow. Sassy, Friendly, CLI Assistant"}
@@ -541,12 +591,12 @@ ${Wi(n,t)}
541
591
  === END SYSTEM PROMPT ===${e?`
542
592
 
543
593
  -- current saved user memories --
544
- ${e}`:""}`.trim();import _t from"fs-extra";import Ms from"path";import{nanoid as jl}from"nanoid";import mt from"fs-extra";import ln from"path";mt.ensureDirSync(zn);var gn=null;async function Bl(e,n){try{if(e.type==="create")await mt.pathExists(e.filePath)&&(await mt.chmod(e.filePath,438).catch(()=>{}),await mt.remove(e.filePath));else if(e.type==="update"){if(!e.backupFile)return;let t=ln.join(zn,n.chatId,e.backupFile);if(await mt.pathExists(t)){let o=oe(t,null);if(!o||!o.data)throw new Error(`Backup container corrupt or empty for ${ln.basename(e.filePath)}`);let s=Mi(o.data);await mt.pathExists(e.filePath)&&await mt.chmod(e.filePath,438).catch(()=>{}),await mt.writeFile(e.filePath,s,"utf8")}}}catch(t){throw new Error(`Restoration failed for ${ln.basename(e.filePath)}: ${t.message}`)}}async function Wl(e,n,t=7){let o=0;for(;o<t;)try{return await Bl(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 _r=null,ht={async startTransaction(e,n){_r=e,gn={id:`tx_prompt_${Date.now()}`,chatId:e,timestamp:new Date().toISOString(),prompt:n.trim(),changes:[],reverted:!1},pe(lo,gn)},async recordFileChange(e,n=null){try{if(!gn){if(_r){let a=oe(an,[]),i=[...a].reverse().find(p=>p.chatId===_r);if(i){if(i.changes.some(u=>u.filePath===e))return;let c=await mt.pathExists(e)||n?"update":"create",l=null;if(c==="update"){let u=ln.basename(e);l=`${i.id}_${u}.bak`;let f=ln.join(zn,i.chatId);await mt.ensureDir(f);let m=ln.join(f,l),g=n!==null?n:await mt.readFile(e,"utf8").catch(()=>null);g!==null?pe(m,{data:dr(g)}):(c="create",l=null)}i.changes.push({filePath:e,type:c,backupFile:l}),pe(an,a)}}return}if(gn.changes.some(a=>a.filePath===e))return;let s=await mt.pathExists(e)||n?"update":"create",r=null;if(s==="update"){let a=ln.basename(e);r=`${gn.id}_${a}.bak`;let i=ln.join(zn,gn.chatId);await mt.ensureDir(i);let p=ln.join(i,r),d=n!==null?n:await mt.readFile(e,"utf8").catch(()=>null);d!==null?pe(p,{data:dr(d)}):(s="create",r=null)}gn.changes.push({filePath:e,type:s,backupFile:r}),pe(lo,gn)}catch{}},async commitTransaction(){if(gn)try{let e=oe(an,[]);if(e.push(gn),e.length>512e3){let n=e.shift();if(n.changes)for(let t of n.changes)t.backupFile&&await mt.remove(ln.join(zn,n.chatId,t.backupFile)).catch(()=>{})}pe(an,e),await mt.remove(lo).catch(()=>{})}catch{}finally{gn=null}},async recoverCrashedTransaction(){try{if(await mt.pathExists(lo)){let e=oe(lo,null);if(e?.changes?.length>0){let n=oe(an,[]);n.some(t=>t.id===e.id)||(n.push(e),pe(an,n))}await mt.remove(lo).catch(()=>{})}}catch{}},async rollbackToBefore(e){let n=oe(an,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 Wl(i,a);for(let i of a.changes)if(i.backupFile){let p=ln.join(zn,a.chatId,i.backupFile);await mt.remove(p).catch(()=>{})}n=n.filter(i=>i.id!==a.id),pe(an,n)}return{success:!0,chatId:o,targetPrompt:s}},async getChatHistory(e){try{return oe(an,[]).filter(t=>t.chatId===e&&!t.reverted)}catch{return[]}},async deleteChatBackups(e){try{await mt.remove(ln.join(zn,e));let n=oe(an,[]),t=n.filter(o=>o.chatId!==e);n.length!==t.length&&pe(an,t)}catch{}}};var wa=Promise.resolve(),vs=e=>{let n=wa.then(async()=>{try{return await e()}catch(t){throw console.error("Lock Operation Failed:",t),t}});return wa=n.catch(()=>{}),n},fo=async()=>{await _t.ensureDir(Ao);let e={};if(await _t.pathExists($o))try{e=oe($o,{})}catch{e={}}for(let n in e){let t=Ms.join(Ao,`${n}.json`);Object.defineProperty(e[n],"messages",{get:()=>{if(_t.existsSync(t))try{return oe(t,[])}catch{return[]}return[]},set:o=>{try{pe(t,o)}catch{}},enumerable:!1,configurable:!0})}return e},zf=async(e,n,t)=>vs(async()=>{await _t.ensureDir(Ao);let o=await fo(),s=o[e],r=(t||[]).filter(y=>!y.isUpdateNotification&&(!y.isMeta||y.text&&y.text.includes("Request Cancelled")));try{(await en()).systemSettings?.preserveThinking===!1&&(r=r.filter(h=>h.role!=="think"))}catch{}let a=y=>{if(!y)return;let h=typeof y=="string"?y:y.text||y.content||"";if(!h||typeof h!="string")return;let w=h.replace(/\s*\n+\s*\[Prompted on:.*?\]/g,"").replace(/\[\/?(?:STEERING HINT|QUESTION)(?::\s*\w+)?\]/gi,"").trim();if(!w)return;let x=w.split(/\s+/),T;return x.length>7?T=x.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),u=a(d);s&&s.prompt?Math.random()<.5&&l?i=l:i=s.prompt:i=u||l;let f=n||(s?s.name:`Session ${e.slice(-6)}`),m=Ms.join(Ao,`${e}.json`);pe(m,r),o[e]={name:f,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($o,g)}),xa=async(e,n)=>vs(async()=>{let t=await fo();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($o,o)}),Gl=async e=>vs(async()=>{let n=await fo();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($o,t),await _t.pathExists(Kn))try{let a=oe(Kn,[]);if(Array.isArray(a)){let i=a.filter(p=>Object.keys(p)[0]!==String(e));pe(Kn,i)}}catch{}let o=oe(Zt,{});o[e]&&(delete o[e],pe(Zt,o));let s=oe(Ln,{});s[e]&&(delete s[e],pe(Ln,s)),await ht.deleteChatBackups(e);let r=Ms.join(Ao,`${e}.json`);if(await _t.pathExists(r))try{await _t.remove(r)}catch{}return n}),Kf=()=>`flow-${jl(6)}`,Yf=async e=>{if(!e||e==="Never")return;let n=parseInt(e);if(isNaN(n))return;let t=await fo(),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 Gl(a),r++)}return r},Hl=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,u;if(i[0]>1e3)c=i[0],l=i[1],u=i[2];else if(i[2]>1e3)c=i[2],i[0]>12?(u=i[0],l=i[1]):i[1]>12?(u=i[1],l=i[0]):d?(u=i[0],l=i[1]):(l=i[0],u=i[1]);else return null;if(l<1||l>12||u<1||u>31)return null;let f=0,m=0,g=0;if(r){let h=r.split(":").map(Number);f=h[0]||0,m=h[1]||0,g=h[2]||0,a.toLowerCase()==="pm"&&f<12?f+=12:a.toLowerCase()==="am"&&f===12&&(f=0)}let y=new Date(c,l-1,u,f,m,g);return isNaN(y.getTime())?null:y.getTime()},ql=async e=>{try{if(!await _t.pathExists(e))return;let n=await _t.readFile(e,"utf8");if(!n.trim())return;let t=n.split(`
594
+ ${e}`:""}`.trim();import $t from"fs-extra";import Ms from"path";import{nanoid as jl}from"nanoid";import mt from"fs-extra";import cn from"path";mt.ensureDirSync(Kn);var yn=null;async function Bl(e,n){try{if(e.type==="create")await mt.pathExists(e.filePath)&&(await mt.chmod(e.filePath,438).catch(()=>{}),await mt.remove(e.filePath));else if(e.type==="update"){if(!e.backupFile)return;let t=cn.join(Kn,n.chatId,e.backupFile);if(await mt.pathExists(t)){let o=oe(t,null);if(!o||!o.data)throw new Error(`Backup container corrupt or empty for ${cn.basename(e.filePath)}`);let s=Mi(o.data);await mt.pathExists(e.filePath)&&await mt.chmod(e.filePath,438).catch(()=>{}),await mt.writeFile(e.filePath,s,"utf8")}}}catch(t){throw new Error(`Restoration failed for ${cn.basename(e.filePath)}: ${t.message}`)}}async function Wl(e,n,t=7){let o=0;for(;o<t;)try{return await Bl(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 _r=null,ht={async startTransaction(e,n){_r=e,yn={id:`tx_prompt_${Date.now()}`,chatId:e,timestamp:new Date().toISOString(),prompt:n.trim(),changes:[],reverted:!1},pe(co,yn)},async recordFileChange(e,n=null){try{if(!yn){if(_r){let a=oe(ln,[]),i=[...a].reverse().find(p=>p.chatId===_r);if(i){if(i.changes.some(u=>u.filePath===e))return;let c=await mt.pathExists(e)||n?"update":"create",l=null;if(c==="update"){let u=cn.basename(e);l=`${i.id}_${u}.bak`;let f=cn.join(Kn,i.chatId);await mt.ensureDir(f);let m=cn.join(f,l),g=n!==null?n:await mt.readFile(e,"utf8").catch(()=>null);g!==null?pe(m,{data:dr(g)}):(c="create",l=null)}i.changes.push({filePath:e,type:c,backupFile:l}),pe(ln,a)}}return}if(yn.changes.some(a=>a.filePath===e))return;let s=await mt.pathExists(e)||n?"update":"create",r=null;if(s==="update"){let a=cn.basename(e);r=`${yn.id}_${a}.bak`;let i=cn.join(Kn,yn.chatId);await mt.ensureDir(i);let p=cn.join(i,r),d=n!==null?n:await mt.readFile(e,"utf8").catch(()=>null);d!==null?pe(p,{data:dr(d)}):(s="create",r=null)}yn.changes.push({filePath:e,type:s,backupFile:r}),pe(co,yn)}catch{}},async commitTransaction(){if(yn)try{let e=oe(ln,[]);if(e.push(yn),e.length>512e3){let n=e.shift();if(n.changes)for(let t of n.changes)t.backupFile&&await mt.remove(cn.join(Kn,n.chatId,t.backupFile)).catch(()=>{})}pe(ln,e),await mt.remove(co).catch(()=>{})}catch{}finally{yn=null}},async recoverCrashedTransaction(){try{if(await mt.pathExists(co)){let e=oe(co,null);if(e?.changes?.length>0){let n=oe(ln,[]);n.some(t=>t.id===e.id)||(n.push(e),pe(ln,n))}await mt.remove(co).catch(()=>{})}}catch{}},async rollbackToBefore(e){let n=oe(ln,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 Wl(i,a);for(let i of a.changes)if(i.backupFile){let p=cn.join(Kn,a.chatId,i.backupFile);await mt.remove(p).catch(()=>{})}n=n.filter(i=>i.id!==a.id),pe(ln,n)}return{success:!0,chatId:o,targetPrompt:s}},async getChatHistory(e){try{return oe(ln,[]).filter(t=>t.chatId===e&&!t.reverted)}catch{return[]}},async deleteChatBackups(e){try{await mt.remove(cn.join(Kn,e));let n=oe(ln,[]),t=n.filter(o=>o.chatId!==e);n.length!==t.length&&pe(ln,t)}catch{}}};var wa=Promise.resolve(),vs=e=>{let n=wa.then(async()=>{try{return await e()}catch(t){throw console.error("Lock Operation Failed:",t),t}});return wa=n.catch(()=>{}),n},uo=async()=>{await $t.ensureDir(Mo);let e={};if(await $t.pathExists(Ao))try{e=oe(Ao,{})}catch{e={}}for(let n in e){let t=Ms.join(Mo,`${n}.json`);Object.defineProperty(e[n],"messages",{get:()=>{if($t.existsSync(t))try{return oe(t,[])}catch{return[]}return[]},set:o=>{try{pe(t,o)}catch{}},enumerable:!1,configurable:!0})}return e},zf=async(e,n,t)=>vs(async()=>{await $t.ensureDir(Mo);let o=await uo(),s=o[e],r=(t||[]).filter(y=>!y.isUpdateNotification&&(!y.isMeta||y.text&&y.text.includes("Request Cancelled")));try{(await tn()).systemSettings?.preserveThinking===!1&&(r=r.filter(h=>h.role!=="think"))}catch{}let a=y=>{if(!y)return;let h=typeof y=="string"?y:y.text||y.content||"";if(!h||typeof h!="string")return;let w=h.replace(/\s*\n+\s*\[Prompted on:.*?\]/g,"").replace(/\[\/?(?:STEERING HINT|QUESTION)(?::\s*\w+)?\]/gi,"").trim();if(!w)return;let x=w.split(/\s+/),T;return x.length>7?T=x.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),u=a(d);s&&s.prompt?Math.random()<.5&&l?i=l:i=s.prompt:i=u||l;let f=n||(s?s.name:`Session ${e.slice(-6)}`),m=Ms.join(Mo,`${e}.json`);pe(m,r),o[e]={name:f,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(Ao,g)}),xa=async(e,n)=>vs(async()=>{let t=await uo();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(Ao,o)}),Gl=async e=>vs(async()=>{let n=await uo();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(Ao,t),await $t.pathExists(Yn))try{let a=oe(Yn,[]);if(Array.isArray(a)){let i=a.filter(p=>Object.keys(p)[0]!==String(e));pe(Yn,i)}}catch{}let o=oe(en,{});o[e]&&(delete o[e],pe(en,o));let s=oe(Pn,{});s[e]&&(delete s[e],pe(Pn,s)),await ht.deleteChatBackups(e);let r=Ms.join(Mo,`${e}.json`);if(await $t.pathExists(r))try{await $t.remove(r)}catch{}return n}),Kf=()=>`flow-${jl(6)}`,Yf=async e=>{if(!e||e==="Never")return;let n=parseInt(e);if(isNaN(n))return;let t=await uo(),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 Gl(a),r++)}return r},Hl=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,u;if(i[0]>1e3)c=i[0],l=i[1],u=i[2];else if(i[2]>1e3)c=i[2],i[0]>12?(u=i[0],l=i[1]):i[1]>12?(u=i[1],l=i[0]):d?(u=i[0],l=i[1]):(l=i[0],u=i[1]);else return null;if(l<1||l>12||u<1||u>31)return null;let f=0,m=0,g=0;if(r){let h=r.split(":").map(Number);f=h[0]||0,m=h[1]||0,g=h[2]||0,a.toLowerCase()==="pm"&&f<12?f+=12:a.toLowerCase()==="am"&&f===12&&(f=0)}let y=new Date(c,l-1,u,f,m,g);return isNaN(y.getTime())?null:y.getTime()},ql=async e=>{try{if(!await $t.pathExists(e))return;let n=await $t.readFile(e,"utf8");if(!n.trim())return;let t=n.split(`
545
595
  `),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 m=l.header.match(d);if(m){let g=Hl(m[1]);if(g&&i-g>a)continue}}let f=l.header+(l.body.length>0?`
546
596
  `+l.body.join(`
547
597
  `):"");p.push(f)}let c=p.join(`
548
- `).trim();c?await _t.writeFile(e,c+`
549
- `,"utf8"):await _t.writeFile(e,"","utf8")}catch{}},Vf=async e=>{try{if(!await _t.pathExists(e))return;let n=async t=>{let o=await _t.readdir(t);for(let s of o){let r=Ms.join(t,s);(await _t.stat(r)).isDirectory()?(await n(r),(await _t.readdir(r)).length===0&&await _t.remove(r)):s.endsWith(".log")&&await ql(r)}};await n(e)}catch{}},ba=(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 Xf=async(e,n,t)=>vs(async()=>{let o=oe(Kn,[]);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(Kn,o)}),Jf=async e=>{try{if(!await _t.pathExists(Kn))return{total:0,context:0};let n=oe(Kn,[]);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 Ta from"puppeteer";import Ra from"fs";import Ea from"path";import Sa from"os";import Zo from"path";import Io from"fs";import{createRequire as zl}from"module";import{fileURLToPath as Kl}from"url";var Yl=zl(import.meta.url),ka=Zo.dirname(Kl(import.meta.url));function uo(){let e=Sa.platform(),n=Sa.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=Zo.resolve(ka,"..","..",".puppeteerrc.cjs");if(Io.existsSync(r)||(r=Zo.resolve(ka,"..",".puppeteerrc.cjs")),!Io.existsSync(r))return{};try{let a=Yl(r),i=a.cacheDirectory,p=a.chrome?.version;if(i){if(process.env.PUPPETEER_CACHE_DIR=i,p){let l=Zo.join(i,"chrome",`${t}-${p}`,s,o);if(Io.existsSync(l))return{executablePath:l,cacheDirectory:i}}let d=l=>{if(!Io.existsSync(l))return null;try{let u=Io.readdirSync(l),f=[];for(let m of u){let g=Zo.join(l,m),y;try{y=Io.statSync(g)}catch{continue}if(y.isDirectory())f.push(g);else if(m.toLowerCase()===o.toLowerCase()&&(!p||g.includes(p)))return g}if(p){for(let m of f)if(m.includes(p)){let g=d(m);if(g)return g}}for(let m of f)if(!p||!m.includes(p)){let g=d(m);if(g)return g}}catch{}return null},c=d(i);if(c)return{executablePath:c,cacheDirectory:i}}}catch{}return{}}var $r=async e=>{let{query:n,limit:t=5,aiMode:o=!1}=D(e);if(!n)return'ERROR: Missing "query" argument for web_search.';let s=3,r=null;if(o){let a=`Query: ${n}
598
+ `).trim();c?await $t.writeFile(e,c+`
599
+ `,"utf8"):await $t.writeFile(e,"","utf8")}catch{}},Vf=async e=>{try{if(!await $t.pathExists(e))return;let n=async t=>{let o=await $t.readdir(t);for(let s of o){let r=Ms.join(t,s);(await $t.stat(r)).isDirectory()?(await n(r),(await $t.readdir(r)).length===0&&await $t.remove(r)):s.endsWith(".log")&&await ql(r)}};await n(e)}catch{}},ba=(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 Xf=async(e,n,t)=>vs(async()=>{let o=oe(Yn,[]);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(Yn,o)}),Jf=async e=>{try{if(!await $t.pathExists(Yn))return{total:0,context:0};let n=oe(Yn,[]);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 Ta from"puppeteer";import Ra from"fs";import Ea from"path";import Sa from"os";import es from"path";import Oo from"fs";import{createRequire as zl}from"module";import{fileURLToPath as Kl}from"url";var Yl=zl(import.meta.url),ka=es.dirname(Kl(import.meta.url));function po(){let e=Sa.platform(),n=Sa.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=es.resolve(ka,"..","..",".puppeteerrc.cjs");if(Oo.existsSync(r)||(r=es.resolve(ka,"..",".puppeteerrc.cjs")),!Oo.existsSync(r))return{};try{let a=Yl(r),i=a.cacheDirectory,p=a.chrome?.version;if(i){if(process.env.PUPPETEER_CACHE_DIR=i,p){let l=es.join(i,"chrome",`${t}-${p}`,s,o);if(Oo.existsSync(l))return{executablePath:l,cacheDirectory:i}}let d=l=>{if(!Oo.existsSync(l))return null;try{let u=Oo.readdirSync(l),f=[];for(let m of u){let g=es.join(l,m),y;try{y=Oo.statSync(g)}catch{continue}if(y.isDirectory())f.push(g);else if(m.toLowerCase()===o.toLowerCase()&&(!p||g.includes(p)))return g}if(p){for(let m of f)if(m.includes(p)){let g=d(m);if(g)return g}}for(let m of f)if(!p||!m.includes(p)){let g=d(m);if(g)return g}}catch{}return null},c=d(i);if(c)return{executablePath:c,cacheDirectory:i}}}catch{}return{}}var $r=async e=>{let{query:n,limit:t=5,aiMode:o=!1}=L(e);if(!n)return'ERROR: Missing "query" argument for web_search.';let s=3,r=null;if(o){let a=`Query: ${n}
550
600
 
551
601
  RESPONSE RULES:
552
602
  - ANSWER CONCISELY WITH REQUIRED DETAILS UNDER 300 WORDS.
@@ -561,7 +611,7 @@ Sources:
561
611
 
562
612
  - LIST ONE RAW URL PER BULLET.
563
613
  - DO NOT USE MARKDOWN LINKS.
564
- - 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=uo();p=await Ta.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 u=`https://search.brave.com/ask?q=${encodeURIComponent(a)}&source=web`;await c.goto(u,{waitUntil:"domcontentloaded",timeout:18e4});let f=null,m=45e3,g=Date.now();for(;Date.now()-g<m&&(f=await c.evaluate(()=>{let E=Array.from(document.querySelectorAll('.message:not(.user), .answer-text, .llm-content, [data-type="answer"]')),b="";if(E.length>0&&(b=E.map(Q=>Q.innerText.trim()).filter(Boolean).join(`
614
+ - 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=po();p=await Ta.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 u=`https://search.brave.com/ask?q=${encodeURIComponent(a)}&source=web`;await c.goto(u,{waitUntil:"domcontentloaded",timeout:18e4});let f=null,m=45e3,g=Date.now();for(;Date.now()-g<m&&(f=await c.evaluate(()=>{let E=Array.from(document.querySelectorAll('.message:not(.user), .answer-text, .llm-content, [data-type="answer"]')),b="";if(E.length>0&&(b=E.map(Q=>Q.innerText.trim()).filter(Boolean).join(`
565
615
 
566
616
  `)),b||(b=document.body.innerText),b.includes("anomaly"))throw new Error("ANOMALY_DETECTED");let $=!!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,O=I?I.innerText.trim():"",P=/^(?:[✓✔]\s*)?Finished/i.test(O)||!!(I&&I.querySelector(".status-finished, .finished")),W=!$&&(P||b.includes("Sources:")&&!$),q={};return document.querySelectorAll("a[href]").forEach(Q=>{let V=Q.getAttribute("href")||Q.href||"";if(V.includes("uddg=")&&(V=decodeURIComponent(V.split("uddg=")[1].split("&")[0])),V.includes("url=")&&(V=decodeURIComponent(V.split("url=")[1].split("&")[0])),V&&(V.startsWith("http://")||V.startsWith("https://"))&&!V.includes("search.brave.com")){let F=Q.innerText.trim();F&&(q[F]=V),Q.textContent=V}}),{isFinished:W,text:b,hrefMap:q}}),!(f&&f.isFinished));)await new Promise(E=>setTimeout(E,1e3));let y=(f?f.text:"")||"",h=f?f.hrefMap||{}:{},w="DO NOT INCLUDE ANY TEXT, NOTES, OR EXPLANATIONS AFTER THE SOURCES SECTION.";y.includes(w)&&(y=y.split(w).pop()),y=y.replace(/^.*?(Ctrl \+ Shift \+ O|Ask\nAll\nImages)/s,"").replace(/AI-generated answer\. Please verify critical facts\..*/s,"").replace(/Brave Search uses private usage metrics.*/s,"");let x=y,T="";if(y.includes("Sources:")){let E=y.split("Sources:");x=E[0],T=E.slice(1).join("Sources:")}let _=[];for(let E of x.split(`
567
617
  `)){let b=E.trim();b&&(/^(View all|Finished|Searching|Answering|Thinking)$/i.test(b)||/^[\+\-]?\d+$/.test(b)||b.includes("search.brave.com")||b.startsWith("https://www.youtube.com/watch")||b.startsWith("https://youtube.com/watch")||_.push(E))}let R=_.join(`
@@ -573,7 +623,7 @@ Sources:
573
623
 
574
624
  `+k:"");if(!C||/^(\+\d+|Searching|Answering|Thinking|Finished)$/i.test(C))throw new Error("EMPTY_AI_RESPONSE");return await p.close(),`AI Search results for [${n}]:
575
625
 
576
- ${C}`}catch(d){if(r=d,Ra.writeFileSync(Ea.join(mn,"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=uo();i=await Ta.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 u=await d.$$eval(".result",(g,y)=>g.slice(0,y).map((h,w)=>{let x=h.querySelector(".result__a"),T=h.querySelector(".result__snippet"),_=x?x.href:"";_.includes("uddg=")&&(_=decodeURIComponent(_.split("uddg=")[1].split("&")[0]));let R=x?x.innerText.trim():"No Title",S=T?T.innerText.trim():"No Snippet";return`${w+1}. ${R}
626
+ ${C}`}catch(d){if(r=d,Ra.writeFileSync(Ea.join(hn,"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=po();i=await Ta.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 u=await d.$$eval(".result",(g,y)=>g.slice(0,y).map((h,w)=>{let x=h.querySelector(".result__a"),T=h.querySelector(".result__snippet"),_=x?x.href:"";_.includes("uddg=")&&(_=decodeURIComponent(_.split("uddg=")[1].split("&")[0]));let R=x?x.innerText.trim():"No Title",S=T?T.innerText.trim():"No Snippet";return`${w+1}. ${R}
577
627
  Source: ${_}
578
628
  Snippet: ${S}`}),t);if(u.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 f=u.join(`
579
629
 
@@ -581,7 +631,7 @@ Snippet: ${S}`}),t);if(u.length===0){if((await d.evaluate(()=>document.body.inne
581
631
 
582
632
  `:""}Search results for [${n}]:
583
633
 
584
- ${f}`}catch(p){if(r=p,i&&await i.close(),Ra.writeFileSync(Ea.join(mn,"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 Vl from"puppeteer";import Xl from"turndown";import{gfm as Jl}from"turndown-plugin-gfm";var Ar=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=uo();a=await Vl.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),h;for(;h=y.nextNode();)h.remove();for(document.querySelectorAll("*").forEach(T=>{let _=T.attributes;for(let R=_.length-1;R>=0;R--){let S=_[R].name;S!=="href"&&S!=="src"&&T.removeAttribute(S)}});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(`
634
+ ${f}`}catch(p){if(r=p,i&&await i.close(),Ra.writeFileSync(Ea.join(hn,"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 Vl from"puppeteer";import Xl from"turndown";import{gfm as Jl}from"turndown-plugin-gfm";var Ar=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=po();a=await Vl.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),h;for(;h=y.nextNode();)h.remove();for(document.querySelectorAll("*").forEach(T=>{let _=T.attributes;for(let R=_.length-1;R>=0;R--){let S=_[R].name;S!=="href"&&S!=="src"&&T.removeAttribute(S)}});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(`
585
635
 
586
636
  `))});let x=()=>{let T=!1;document.querySelectorAll("*").forEach(_=>{_.childNodes.length===0&&!_.innerText.trim()&&(_.remove(),T=!0)}),T&&x()};return x(),document.body.innerHTML});if(!c)throw new Error("EMPTY_RENDER_RESULT");let l=c.replace(/<br\s*\/?>/gi,`
587
637
 
@@ -596,40 +646,40 @@ ${f}`}catch(p){if(r=p,i&&await i.close(),Ra.writeFileSync(Ea.join(mn,"web_tools"
596
646
 
597
647
  ${m}${f.length>5e4?`
598
648
 
599
- [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 Ql=4*(1024*2),Mr=async(e,n={})=>{let t=c=>{let l=new RegExp(`${c}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),u=e.match(l);if(u)return u[2].trim();let f=new RegExp(`${c}\\s*[:=]\\s*([^,\\s)]+)`,"s"),m=e.match(f);return m?m[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=oe(Zt,{});c[d]||(c[d]=[]),c[d].push(r),pe(Zt,c);let l=c[d].reduce((u,f)=>u+f.length,0);return`SUCCESS: Temporary context saved for session [${d}]. (Size: ${l} chars)`}if(o==="user"){let c=oe(Pt,[]).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,u=`${l.getDate()}/${l.getMonth()+1}/${l.getFullYear()}`,f=r.includes("[Saved on:")?r:`${r.trim()} [Saved on: ${u}]`,m=Ql,g=c.reduce((x,T)=>x+(T.memory?.length||0),0);for(;c.length>0&&g+f.length>m;){let x=c.shift();g-=x.memory?.length||0}let y=t("score"),h=y?parseFloat(y):.5,w={id:`mem-${Date.now().toString(36)}`,memory:f,score:Math.min(2,isNaN(h)?.5:h)};return c.push(w),pe(Pt,c),`SUCCESS: Memory added with ID [${w.id}] and score [${w.score}]. (Vault Size: ${g+f.length} chars)`}if(s==="update"){let l=p||i,u=a||r;if(!l||!u)return"ERROR: Missing 'id' or content for update.";let f=c.findIndex(h=>h.id===l);if(f===-1)return`ERROR: Memory ID [${l}] not found.`;let m=new Date,g=`${m.getDate()}/${m.getMonth()+1}/${m.getFullYear()}`,y=u.includes("[Saved on:")?u:`${u.trim()} [Saved on: ${g}]`;return c[f].memory=y,pe(Pt,c),`SUCCESS: Memory [${l}] updated.`}if(s==="delete"){let l=p||r;if(!l)return"ERROR: Missing 'id' for deletion.";let u=c.length,f=c.filter(m=>m.id!==l);return f.length===u?`ERROR: Memory ID [${l}] not found.`:(pe(Pt,f),`SUCCESS: Memory [${l}] deleted.`)}return`ERROR: Invalid method [${s}] for user memory. Use 'add', 'update', or 'delete'.`}return`ERROR: Unknown action [${o}] for memory tool.`};var vr=async(e,n={})=>{let t=D(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 xa(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 cn from"fs";import _n from"path";var Zl=e=>{if(!e)return null;let n=e.match(/^\s*---\r?\n([\s\S]*?)\r?\n---(?:\r?\n)?([\s\S]*)$/);if(!n)return null;let t=n[1];if((n[2]||"").trim().length===0)return null;let s="",r=t.match(/^name:\s*(.+)$/m);return r&&(s=r[1].trim().replace(/^["']|["']$/g,"")),s?{name:s}:null},ec=e=>{let n=[];if(!e||!cn.existsSync(e))return n;let t=(o,s=0)=>{if(!(s>5))try{let r=cn.readdirSync(o,{withFileTypes:!0});for(let a of r){let i=_n.join(o,a.name),p=a.name.toLowerCase();a.isFile()?p==="skill.md"&&n.push(i):a.isDirectory()&&(s===0?(p==="skills"||p===".skills"||p==="skill"||p===".skill")&&t(i,s+1):t(i,s+1))}}catch{}};return t(e,0),n},tc=e=>e.replace(/^(\s*---\r?\n)([\s\S]*?)(\r?\n---)/,(n,t,o,s)=>{let r=o.split(`
649
+ [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 Ql=4*(1024*2),Mr=async(e,n={})=>{let t=c=>{let l=new RegExp(`${c}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),u=e.match(l);if(u)return u[2].trim();let f=new RegExp(`${c}\\s*[:=]\\s*([^,\\s)]+)`,"s"),m=e.match(f);return m?m[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=oe(en,{});c[d]||(c[d]=[]),c[d].push(r),pe(en,c);let l=c[d].reduce((u,f)=>u+f.length,0);return`SUCCESS: Temporary context saved for session [${d}]. (Size: ${l} chars)`}if(o==="user"){let c=oe(Ft,[]).map(l=>(l.score===void 0&&(l.score=.5),l));if(s==="add"){if(!r)return"ERROR: Missing 'content' for memory addition.";let l=new Date,u=`${l.getDate()}/${l.getMonth()+1}/${l.getFullYear()}`,f=r.includes("[Saved on:")?r:`${r.trim()} [Saved on: ${u}]`,m=Ql,g=c.reduce((x,T)=>x+(T.memory?.length||0),0);for(;c.length>0&&g+f.length>m;){let x=c.shift();g-=x.memory?.length||0}let y=t("score"),h=y?parseFloat(y):.5,w={id:`mem-${Date.now().toString(36)}`,memory:f,score:Math.min(2,isNaN(h)?.5:h)};return c.push(w),pe(Ft,c),`SUCCESS: Memory added with ID [${w.id}] and score [${w.score}]. (Vault Size: ${g+f.length} chars)`}if(s==="update"){let l=p||i,u=a||r;if(!l||!u)return"ERROR: Missing 'id' or content for update.";let f=c.findIndex(h=>h.id===l);if(f===-1)return`ERROR: Memory ID [${l}] not found.`;let m=new Date,g=`${m.getDate()}/${m.getMonth()+1}/${m.getFullYear()}`,y=u.includes("[Saved on:")?u:`${u.trim()} [Saved on: ${g}]`;return c[f].memory=y,pe(Ft,c),`SUCCESS: Memory [${l}] updated.`}if(s==="delete"){let l=p||r;if(!l)return"ERROR: Missing 'id' for deletion.";let u=c.length,f=c.filter(m=>m.id!==l);return f.length===u?`ERROR: Memory ID [${l}] not found.`:(pe(Ft,f),`SUCCESS: Memory [${l}] deleted.`)}return`ERROR: Invalid method [${s}] for user memory. Use 'add', 'update', or 'delete'.`}return`ERROR: Unknown action [${o}] for memory tool.`};var vr=async(e,n={})=>{let t=L(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 xa(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 dn from"fs";import $n from"path";var Zl=e=>{if(!e)return null;let n=e.match(/^\s*---\r?\n([\s\S]*?)\r?\n---(?:\r?\n)?([\s\S]*)$/);if(!n)return null;let t=n[1];if((n[2]||"").trim().length===0)return null;let s="",r=t.match(/^name:\s*(.+)$/m);return r&&(s=r[1].trim().replace(/^["']|["']$/g,"")),s?{name:s}:null},ec=e=>{let n=[];if(!e||!dn.existsSync(e))return n;let t=(o,s=0)=>{if(!(s>5))try{let r=dn.readdirSync(o,{withFileTypes:!0});for(let a of r){let i=$n.join(o,a.name),p=a.name.toLowerCase();a.isFile()?p==="skill.md"&&n.push(i):a.isDirectory()&&(s===0?(p==="skills"||p===".skills"||p==="skill"||p===".skill")&&t(i,s+1):t(i,s+1))}}catch{}};return t(e,0),n},tc=e=>e.replace(/^(\s*---\r?\n)([\s\S]*?)(\r?\n---)/,(n,t,o,s)=>{let r=o.split(`
600
650
  `),a=[],i=!1;for(let p of r){if(/^\s*description\s*:/i.test(p)){i=!0;continue}if(i){if(/^\s+/.test(p))continue;i=!1}a.push(p)}return`${t}${a.join(`
601
- `)}${s}`}),nc=(e,n)=>{let t=[_n.join(e,"references"),_n.join(e,"reference"),e],o=n.toLowerCase().endsWith(".md")?n.toLowerCase():`${n.toLowerCase()}.md`,s=n.toLowerCase();for(let r of t)if(cn.existsSync(r)&&cn.statSync(r).isDirectory())try{let a=cn.readdirSync(r);for(let i of a){let p=i.toLowerCase();if(p===o||p===s){let d=_n.join(r,i);if(cn.statSync(d).isFile())return d}}}catch{}return null},es=async(e,n={})=>{let{path:t,StartLine:o,EndLine:s,start_line:r,end_line:a,startLine:i,endLine:p}=D(e),d=parseInt(o||r||i),c=parseInt(s||a||p),l=!isNaN(d),u=!isNaN(c),f=d||1,m=c||(d?d+800:800);if(!t)return'ERROR: Missing "path" argument for ReadFile.';if(t.trim().toLowerCase().startsWith("#skill")){let h=t.trim().replace(/\\/g,"/").replace(/^#skills?\/?/i,"").split("/").filter(Boolean),w=h[0]?.toLowerCase();if(w!=="global"&&w!=="project")return`ERROR: Invalid skill scope '${w||""}'. Expected 'global' or 'project'.`;let x=h[1];if(!x)return`ERROR: Missing skill name in path [${t}].`;let T=h[2]?.toLowerCase()==="references"||h[2]?.toLowerCase()==="reference",_=T?h.slice(3).join("/"):null,R=w==="global"?Qt:process.cwd(),S=ec(R),k=null;for(let $ of S)try{let I=cn.readFileSync($,"utf8"),O=Zl(I),P=_n.basename(_n.dirname($)).toLowerCase();if(O?.name&&O.name.toLowerCase()===x.toLowerCase()||P===x.toLowerCase()||$.toLowerCase()===_n.join(R,"skill.md").toLowerCase()&&x.toLowerCase()==="skill"){k=$;break}}catch{}if(!k)return`No '${x}' exist in given scope.`;let C=_n.dirname(k),E=k,b=!0;if(T){if(!_)return`ERROR: Missing reference file name in path [${t}].`;let $=nc(C,_);if(!$)return`No such reference exist for skill '${x}'`;E=$,b=!1}try{let $=cn.readFileSync(E,"utf8");$.startsWith("\uFEFF")&&($=$.slice(1)),$=$.replace(/\r\n/g,`
651
+ `)}${s}`}),nc=(e,n)=>{let t=[$n.join(e,"references"),$n.join(e,"reference"),e],o=n.toLowerCase().endsWith(".md")?n.toLowerCase():`${n.toLowerCase()}.md`,s=n.toLowerCase();for(let r of t)if(dn.existsSync(r)&&dn.statSync(r).isDirectory())try{let a=dn.readdirSync(r);for(let i of a){let p=i.toLowerCase();if(p===o||p===s){let d=$n.join(r,i);if(dn.statSync(d).isFile())return d}}}catch{}return null},ts=async(e,n={})=>{let{path:t,StartLine:o,EndLine:s,start_line:r,end_line:a,startLine:i,endLine:p}=L(e),d=parseInt(o||r||i),c=parseInt(s||a||p),l=!isNaN(d),u=!isNaN(c),f=d||1,m=c||(d?d+800:800);if(!t)return'ERROR: Missing "path" argument for ReadFile.';if(t.trim().toLowerCase().startsWith("#skill")){let h=t.trim().replace(/\\/g,"/").replace(/^#skills?\/?/i,"").split("/").filter(Boolean),w=h[0]?.toLowerCase();if(w!=="global"&&w!=="project")return`ERROR: Invalid skill scope '${w||""}'. Expected 'global' or 'project'.`;let x=h[1];if(!x)return`ERROR: Missing skill name in path [${t}].`;let T=h[2]?.toLowerCase()==="references"||h[2]?.toLowerCase()==="reference",_=T?h.slice(3).join("/"):null,R=w==="global"?Tt:process.cwd(),S=ec(R),k=null;for(let $ of S)try{let I=dn.readFileSync($,"utf8"),O=Zl(I),P=$n.basename($n.dirname($)).toLowerCase();if(O?.name&&O.name.toLowerCase()===x.toLowerCase()||P===x.toLowerCase()||$.toLowerCase()===$n.join(R,"skill.md").toLowerCase()&&x.toLowerCase()==="skill"){k=$;break}}catch{}if(!k)return`No '${x}' exist in given scope.`;let C=$n.dirname(k),E=k,b=!0;if(T){if(!_)return`ERROR: Missing reference file name in path [${t}].`;let $=nc(C,_);if(!$)return`No such reference exist for skill '${x}'`;E=$,b=!1}try{let $=dn.readFileSync(E,"utf8");$.startsWith("\uFEFF")&&($=$.slice(1)),$=$.replace(/\r\n/g,`
602
652
  `).replace(/\r/g,`
603
653
  `),b&&($=tc($));let I=$.split(`
604
654
  `),O=I.length,P=l?Math.max(0,f-1):0,W=u?Math.min(O,m):O,q=I.slice(P,W),Q=t.replace(/\\/g,"/").toLowerCase(),F=`${Q.includes("#skill/global/fluxflow")||Q.includes("#skills/global/fluxflow")?"DOCs":"Skill"}: [${t.replace(/\\/g,"/")}]`,B=q.map(ee=>ee.trimEnd()).join(`
605
655
  `);return`${F}
606
656
 
607
- ${B}`}catch($){let I=$ instanceof Error?$.message:String($);return`ERROR: Failed to read skill file [${t}]: ${I}`}}try{let g=_n.resolve(process.cwd(),t);if(!cn.existsSync(g))return`ERROR: File [${t}] does not exist.`;if(cn.statSync(g).isDirectory())return`ERROR: Path [${t}] is a directory. Use list_files instead.`;let h=_n.extname(t).toLowerCase();if([".mp4",".mkv",".avi",".mov",".webm",".flv",".wmv",".mpeg",".mpg"].includes(h))return`ERROR: Unable to read. Type ${h.slice(1).toUpperCase()} not supported`;let x={".pdf":"application/pdf",".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".webp":"image/webp",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".doc":"application/msword"};if(x[h]){if(!(n.isMultiModal!==!1))return`ERROR: Multimodality is not supported for the current model. Unable to load [${t}].`;let O=cn.readFileSync(g).toString("base64"),P=x[h];return{text:`[BINARY FILE]: ${t} (${P}) - Loaded as multimodal part.`,binaryPart:{inlineData:{data:O,mimeType:P}}}}let T=cn.readFileSync(g,"utf8");T.startsWith("\uFEFF")&&(T=T.slice(1)),T=T.replace(/\r\n/g,`
657
+ ${B}`}catch($){let I=$ instanceof Error?$.message:String($);return`ERROR: Failed to read skill file [${t}]: ${I}`}}try{let g=$n.resolve(process.cwd(),t);if(!dn.existsSync(g))return`ERROR: File [${t}] does not exist.`;if(dn.statSync(g).isDirectory())return`ERROR: Path [${t}] is a directory. Use list_files instead.`;let h=$n.extname(t).toLowerCase();if([".mp4",".mkv",".avi",".mov",".webm",".flv",".wmv",".mpeg",".mpg"].includes(h))return`ERROR: Unable to read. Type ${h.slice(1).toUpperCase()} not supported`;let x={".pdf":"application/pdf",".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".webp":"image/webp",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".doc":"application/msword"};if(x[h]){if(!(n.isMultiModal!==!1))return`ERROR: Multimodality is not supported for the current model. Unable to load [${t}].`;let O=dn.readFileSync(g).toString("base64"),P=x[h];return{text:`[BINARY FILE]: ${t} (${P}) - Loaded as multimodal part.`,binaryPart:{inlineData:{data:O,mimeType:P}}}}let T=dn.readFileSync(g,"utf8");T.startsWith("\uFEFF")&&(T=T.slice(1)),T=T.replace(/\r\n/g,`
608
658
  `).replace(/\r/g,`
609
659
  `);let _=T.split(`
610
660
  `),R=_.length;!l&&!u&&R>800&&(f=1,m=50);let S=Math.max(0,f-1),k=Math.min(R,m),C=_.slice(S,k),E=`File: [${t}] (Showing lines ${S+1}-${k} of ${R}).`,b=C.map(($,I)=>`${String(S+I+1).padStart(4)}: ${$.trimEnd()}`).join(`
611
661
  `);return`${E}
612
662
 
613
- ${b}`}catch(g){let y=g instanceof Error?g.message:String(g);return`ERROR: Failed to read file [${t}]: ${y}`}};import Oo from"fs";import Ca from"path";var Ir=async(e,n={})=>{let{path:t,content:o}=D(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,`
663
+ ${b}`}catch(g){let y=g instanceof Error?g.message:String(g);return`ERROR: Failed to read file [${t}]: ${y}`}};import Lo from"fs";import Ca from"path";var Ir=async(e,n={})=>{let{path:t,content:o}=L(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,`
614
664
  `).replace(/\r/g,`
615
- `);let s=Ca.resolve(process.cwd(),t),r=Ca.dirname(s);try{await ht.recordFileChange(s);let a="";if(Oo.existsSync(s))try{a=`Old File contents:
616
- ${Oo.readFileSync(s,"utf8").split(/\r?\n/).map((_,R)=>`${R+1} | ${_}`).join(`
665
+ `);let s=Ca.resolve(process.cwd(),t),r=Ca.dirname(s);try{await ht.recordFileChange(s);let a="";if(Lo.existsSync(s))try{a=`Old File contents:
666
+ ${Lo.readFileSync(s,"utf8").split(/\r?\n/).map((_,R)=>`${R+1} | ${_}`).join(`
617
667
  `)}
618
668
 
619
669
  `}catch{a=`[Note: Could not read existing file for reversal reference]
620
670
 
621
- `}Oo.existsSync(r)||Oo.mkdirSync(r,{recursive:!0});let p=(x=>x.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
671
+ `}Lo.existsSync(r)||Lo.mkdirSync(r,{recursive:!0});let p=(x=>x.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
622
672
  `).replace(/\r/g,`
623
673
  `))(o),d=p.endsWith(`
624
674
  `)?p:p+`
625
- `,c=d.split(/\r?\n/).length,l=Buffer.byteLength(d,"utf8");Oo.writeFileSync(s,d,"utf8");let u=Oo.readFileSync(s,"utf8"),f=Buffer.byteLength(u,"utf8"),m=u.split(/\r?\n/),g=m.length;if(f===0&&l>0)return u=null,`ERROR: CRITICAL FAILURE: Verification failed. File [${t}] is empty on disk!`;let y="";if(g<=100)y=m.join(`
675
+ `,c=d.split(/\r?\n/).length,l=Buffer.byteLength(d,"utf8");Lo.writeFileSync(s,d,"utf8");let u=Lo.readFileSync(s,"utf8"),f=Buffer.byteLength(u,"utf8"),m=u.split(/\r?\n/),g=m.length;if(f===0&&l>0)return u=null,`ERROR: CRITICAL FAILURE: Verification failed. File [${t}] is empty on disk!`;let y="";if(g<=100)y=m.join(`
626
676
  `);else{let x=m.slice(0,50).join(`
627
677
  `),T=m.slice(-50).join(`
628
678
  `);y=`${x}
629
679
 
630
680
  ... [${g-100} lines truncated] ...
631
681
 
632
- ${T}`}u=null;let{systemSettings:h}=await en(),w=`SUCCESS: File [${t}] saved.
682
+ ${T}`}u=null;let{systemSettings:h}=await tn(),w=`SUCCESS: File [${t}] saved.
633
683
  - Stats: [${g} lines, ${(f/1024).toFixed(1)} KB]
634
684
  ${a}- Content Preview:
635
685
 
@@ -638,11 +688,11 @@ ${y}`;if(h?.compressToolResults&&g>60){let x=d.split(/\r?\n/),T=x.slice(0,25).jo
638
688
  `),_=x.slice(-25).join(`
639
689
  `)===m.slice(-25).join(`
640
690
  `);T&&_&&(w=`[[SAME]]
641
- ${w}`)}return w}catch(a){let i=a instanceof Error?a.message:String(a);return`ERROR: Failed to write file [${t}]: ${i}`}};import Lr from"fs";import pc from"path";import oc from"os";var yn=e=>typeof e!="string"?e:e.length>12?(e+"").replace("",""):e,_a=(e,n)=>{if(!e)return"";let t=/\x1B\[[0-?]*[ -/]*[@-~]/g,o=e.split(`
642
- `),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*)/),u=l?l[1]:"";p.forEach((f,m)=>{if(f.length===0)return;let g=r(f);if(c+g>n)if(d.trim().length>0)s.push(d.trimEnd()),d=u.substring(0,Math.min(u.length,8))+f,c=r(d);else if(t.test(f))s.push(f),d=u,c=r(d);else{let y=f;for(;r(y)>n&&n>10;)s.push(y.substring(0,n)),y=y.substring(n);d=y,c=r(d)}else d+=f,c+=g}),(d.trimEnd().length>0||d===u)&&s.push(d.trimEnd())}),yn(s.join(`
643
- `))},Nu=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()},Uu=(e,n=40)=>{let t=Dn.replaceAll("\\\\","\\");if(e=e.replace(oc.homedir(),"~").replace(t,"FluxFlow").replaceAll("\\","/"),!e||e.length<=n)return yn(e);let o=Math.floor((n-3)/2);return yn(e.substring(0,o)+"..."+e.substring(e.length-o).replaceAll("\\","/"))},Os=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,u;for(let f of d){let m=p===1?[`${f}1`,f,`${f}_1`]:[`${f}${p}`,`${f}_${p}`];for(let g of m)if(e[g]!==void 0){l=e[g];break}if(l!==void 0)break}for(let f of c){let m=p===1?[`${f}1`,f,`${f}_1`]:[`${f}${p}`,`${f}_${p}`];for(let g of m)if(e[g]!==void 0){u=e[g];break}if(u!==void 0)break}return{r:l,n:u}};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}},sc=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===`
691
+ ${w}`)}return w}catch(a){let i=a instanceof Error?a.message:String(a);return`ERROR: Failed to write file [${t}]: ${i}`}};import Dr from"fs";import pc from"path";import oc from"os";var wn=e=>typeof e!="string"?e:e.length>12?(e+"").replace("",""):e,_a=(e,n)=>{if(!e)return"";let t=/\x1B\[[0-?]*[ -/]*[@-~]/g,o=e.split(`
692
+ `),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*)/),u=l?l[1]:"";p.forEach((f,m)=>{if(f.length===0)return;let g=r(f);if(c+g>n)if(d.trim().length>0)s.push(d.trimEnd()),d=u.substring(0,Math.min(u.length,8))+f,c=r(d);else if(t.test(f))s.push(f),d=u,c=r(d);else{let y=f;for(;r(y)>n&&n>10;)s.push(y.substring(0,n)),y=y.substring(n);d=y,c=r(d)}else d+=f,c+=g}),(d.trimEnd().length>0||d===u)&&s.push(d.trimEnd())}),wn(s.join(`
693
+ `))},Nu=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()},Uu=(e,n=40)=>{let t=Dn.replaceAll("\\\\","\\");if(e=e.replace(oc.homedir(),"~").replace(t,"FluxFlow").replaceAll("\\","/"),!e||e.length<=n)return wn(e);let o=Math.floor((n-3)/2);return wn(e.substring(0,o)+"..."+e.substring(e.length-o).replaceAll("\\","/"))},Os=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,u;for(let f of d){let m=p===1?[`${f}1`,f,`${f}_1`]:[`${f}${p}`,`${f}_${p}`];for(let g of m)if(e[g]!==void 0){l=e[g];break}if(l!==void 0)break}for(let f of c){let m=p===1?[`${f}1`,f,`${f}_1`]:[`${f}${p}`,`${f}_${p}`];for(let g of m)if(e[g]!==void 0){u=e[g];break}if(u!==void 0)break}return{r:l,n:u}};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}},sc=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===`
644
694
  `)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]!==`
645
- `&&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}},Ds=(e,n,t={})=>{let o=typeof t=="boolean"?t:!!(t&&t.allowMultiple),s=e.replace(/\r\n/g,`
695
+ `&&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}},Ls=(e,n,t={})=>{let o=typeof t=="boolean"?t:!!(t&&t.allowMultiple),s=e.replace(/\r\n/g,`
646
696
  `).replace(/\r/g,`
647
697
  `),r=h=>h.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
648
698
  `).replace(/\r/g,`
@@ -659,7 +709,7 @@ ${w}`)}return w}catch(a){let i=a instanceof Error?a.message:String(a);return`ERR
659
709
  `),E=[];for(let O=Math.max(0,_-4);O<_-1;O++)E.push({num:O+1,text:C[O]});let b=h.firstMatchContent.split(`
660
710
  `),$=[],I=_+b.length-1;for(let O=I;O<Math.min(C.length,I+3);O++)$.push({num:O+1,text:C[O]});l.set(h,{success:!0,index:h.index,oldContent:h.firstMatchContent,newContent:k,originalStartLine:x,finalStartLine:_,contextBefore:E,contextAfter:$}),u=u.substring(0,T)+k+u.substring(T+h.firstMatchContent.length),f+=k.length-h.firstMatchContent.length,m+=k.split(`
661
711
  `).length-h.firstMatchContent.split(`
662
- `).length}let y=[];for(let h=0;h<n.length;h++){let w=g.filter(x=>x.index===h);if(w.length>0)for(let x of w)l.has(x)&&y.push(l.get(x));else{let x=d.find(T=>T.index===h);y.push({success:!1,error:x?x.error:`Block ${h+1}: Unknown error.`})}}return{content:u,results:y}},Ls=(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]
712
+ `).length}let y=[];for(let h=0;h<n.length;h++){let w=g.filter(x=>x.index===h);if(w.length>0)for(let x of w)l.has(x)&&y.push(l.get(x));else{let x=d.find(T=>T.index===h);y.push({success:!1,error:x?x.error:`Block ${h+1}: Unknown error.`})}}return{content:u,results:y}},Ds=(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]
663
713
  `,l="\u2550".repeat(88),u=0,f=null,m=t.filter(g=>g.success).sort((g,y)=>g.originalStartLine-y.originalStartLine);if(m.forEach((g,y)=>{let h=g.finalStartLine!==void 0?g.finalStartLine:g.originalStartLine;if(f===null)for(u=Math.max(0,h-4);u<h-1;)c+=`[UI_CONTEXT] ${d(u+1)} |${a[u]||""}
664
714
  `,u++;else{let k=f,C=k.originalStartLine+k.oldContent.split(`
665
715
  `).length-1;if(g.originalStartLine-C-1>=o){let b=Math.min(a.length,u+3);for(;u<b;)c+=`[UI_CONTEXT] ${d(u+1)} |${a[u]||""}
@@ -676,20 +726,20 @@ ${w}`)}return w}catch(a){let i=a instanceof Error?a.message:String(a);return`ERR
676
726
  `,x=y.split(h).map(T=>T.split(`
677
727
  `).filter(R=>R.trim()!=="").length>45?`[[VERIFIED]]
678
728
  ${T}
679
- [[/VERIFIED]]`:T);c=g+x.join(h)}return c+="[DIFF_END]",yn(c)},rc=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?yn(s.substring(0,r).trim()):"",i=yn(r!==-1?s.substring(r+1):s);return{isR:t,isA:o,num:a,content:i}},ic=(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 u=0;u<=i;u++)p[u]=u;for(let u=1;u<=a;u++){d[0]=u;let f=s[u-1];for(let m=1;m<=i;m++)f===r[m-1]?d[m]=p[m-1]:d[m]=Math.min(p[m],d[m-1],p[m-1])+1;p.set(d)}let c=p[i],l=Math.max(t,o);return l===0?1:1-c/l},$a=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]=ic(n[c].content.trim(),t[l].content.trim());for(let c=1;c<=o;c++)for(let l=1;l<=s;l++){let u=i[c-1][l-1],f=u>=.2?u:-10,m=r[c-1][l-1]+f,g=r[c-1][l],y=r[c][l-1];m>=g&&m>=y?(r[c][l]=m,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,u=t[d-1].index;e[l].pairContent=e[u].parsed.content,e[u].pairContent=e[l].parsed.content}p--,d--}else a[p][d]==="up"?p--:d--},Xn=new Map,po=new Map,Aa=200,Or=6,Dr=(e,n)=>{n.set(e.key,e),e.type==="chunk"&&e.blocks&&e.blocks.forEach(t=>Dr(t,n))},Bu=(e,n)=>{if(!e)return{completed:[],active:[]};let t=`${e.id}-${e.text?.length||0}-${n}-${e.isStreaming}-${e.workedDuration||0}`;if(!e.isStreaming&&Xn.has(t))return Xn.get(t);let o=yn(uc(e.text||"",e.role)),s=`${e.id}-${n}`,r=new Map;if(e.isStreaming){let m=po.get(s);m&&o.startsWith(m.text)&&(r=m.blocksMap)}let a=(m,g,y,h={})=>{let w=r.get(m);if(w&&w.text===y&&w.type===g&&!!w.isActiveBlock==!!h.isActiveBlock&&!!w.isStreaming==!!h.isStreaming&&w.pairContent===h.pairContent)return w;let x=yn(y),T={...h};return typeof T.pairContent=="string"&&(T.pairContent=yn(T.pairContent)),Array.isArray(T.wrappedLines)&&(T.wrappedLines=T.wrappedLines.map(yn)),{key:m,isStreamingMsg:!!e.isStreaming,workedDuration:e.workedDuration,type:g,text:x,msg:g==="full-message"?e:void 0,...T}};if(o.includes("- Content Preview:")){let m="",g=o.match(/File\s+\[(.*?)\]/i);g&&(m=g[1].split(".").pop().toLowerCase());let T=((o.split("- Content Preview:")[1]||"").split("[SYSTEM] Check the content preview for verification [/SYSTEM]")[0]?.trim()||"").split(`
729
+ [[/VERIFIED]]`:T);c=g+x.join(h)}return c+="[DIFF_END]",wn(c)},rc=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?wn(s.substring(0,r).trim()):"",i=wn(r!==-1?s.substring(r+1):s);return{isR:t,isA:o,num:a,content:i}},ic=(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 u=0;u<=i;u++)p[u]=u;for(let u=1;u<=a;u++){d[0]=u;let f=s[u-1];for(let m=1;m<=i;m++)f===r[m-1]?d[m]=p[m-1]:d[m]=Math.min(p[m],d[m-1],p[m-1])+1;p.set(d)}let c=p[i],l=Math.max(t,o);return l===0?1:1-c/l},$a=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]=ic(n[c].content.trim(),t[l].content.trim());for(let c=1;c<=o;c++)for(let l=1;l<=s;l++){let u=i[c-1][l-1],f=u>=.2?u:-10,m=r[c-1][l-1]+f,g=r[c-1][l],y=r[c][l-1];m>=g&&m>=y?(r[c][l]=m,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,u=t[d-1].index;e[l].pairContent=e[u].parsed.content,e[u].pairContent=e[l].parsed.content}p--,d--}else a[p][d]==="up"?p--:d--},Jn=new Map,mo=new Map,Aa=200,Or=6,Lr=(e,n)=>{n.set(e.key,e),e.type==="chunk"&&e.blocks&&e.blocks.forEach(t=>Lr(t,n))},Bu=(e,n)=>{if(!e)return{completed:[],active:[]};let t=`${e.id}-${e.text?.length||0}-${n}-${e.isStreaming}-${e.workedDuration||0}`;if(!e.isStreaming&&Jn.has(t))return Jn.get(t);let o=wn(uc(e.text||"",e.role)),s=`${e.id}-${n}`,r=new Map;if(e.isStreaming){let m=mo.get(s);m&&o.startsWith(m.text)&&(r=m.blocksMap)}let a=(m,g,y,h={})=>{let w=r.get(m);if(w&&w.text===y&&w.type===g&&!!w.isActiveBlock==!!h.isActiveBlock&&!!w.isStreaming==!!h.isStreaming&&w.pairContent===h.pairContent)return w;let x=wn(y),T={...h};return typeof T.pairContent=="string"&&(T.pairContent=wn(T.pairContent)),Array.isArray(T.wrappedLines)&&(T.wrappedLines=T.wrappedLines.map(wn)),{key:m,isStreamingMsg:!!e.isStreaming,workedDuration:e.workedDuration,type:g,text:x,msg:g==="full-message"?e:void 0,...T}};if(o.includes("- Content Preview:")){let m="",g=o.match(/File\s+\[(.*?)\]/i);g&&(m=g[1].split(".").pop().toLowerCase());let T=((o.split("- Content Preview:")[1]||"").split("[SYSTEM] Check the content preview for verification [/SYSTEM]")[0]?.trim()||"").split(`
680
730
  `).map(b=>b.replace(/\r$/,"")),_=String(T.length).length,R=[],S=null,k=[],C=()=>{if(!k.length)return;let b=k;k=[],R.push(b.length===1?b[0]:{key:`${b[0].key}-chunk`,type:"chunk",blocks:b})},E=n-(_+6);return T.forEach((b,$)=>{let I=$===T.length-1,O=_a(b,E).split(`
681
731
  `),P=a(`${e.id||Date.now()}-write-line-${$}`,"write-line",b,{gutterWidth:_,lineNum:$+1,isFirstLine:$===0,isLastLine:I,extension:m,wrappedLines:O});I&&e.isStreaming?(C(),S=P):(k.push(P),k.length>=Or&&C())}),C(),{completed:R,active:S?[S]:[]}}if(o.includes("[DIFF_START]")){let m=o.match(/\[DIFF_START\]([\s\S]*?)(?:\[DIFF_END\]|$)/),y=(m?m[1].trim():"").split(`
682
732
  `).map(S=>S.replace(/\r$/,"")),h=y.map(S=>({line:S,parsed:rc(S),pairContent:null})),w=[];for(let S=0;S<h.length;S++){let k=h[S];k.parsed&&(k.parsed.isR||k.parsed.isA)?w.push(k):w.length>0&&($a(w),w=[])}w.length>0&&$a(w);let x=[],T=null,_=[],R=()=>{if(!_.length)return;let S=_;_=[],x.push(S.length===1?S[0]:{key:`${S[0].key}-chunk`,type:"chunk",blocks:S})};return y.forEach((S,k)=>{let C=k===y.length-1,E=h[k].parsed,b=null;E&&(b=_a(E.content,n-17).split(`
683
- `));let $=a(`${e.id||Date.now()}-diff-${k}`,"diff-line",S,{isFirstLine:k===0,isLastLine:C,pairContent:h[k].pairContent,wrappedLines:b});C&&e.isStreaming?(R(),T=$):(_.push($),_.length>=Or&&R())}),R(),{completed:x,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 m={completed:[],active:[]};return Xn.set(t,m),m}let i=[],p=null,d=[],c=null,l=()=>{if(!d.length)return;let m=d;d=[],c=null,i.push(m.length===1?m[0]:{key:`${e.id||"x"}-chunk-${m[0].key}`,type:"chunk",blocks:m})},u=(m,g=!1)=>{if(c!==null&&c!==m.type&&l(),d.push(m),c=m.type,d.length>=Or){if(e.isStreaming&&g)return;l()}};if(e.role==="think"){i.push(a(`${e.id}-header`,"think-header",""));let m=o.split(`
733
+ `));let $=a(`${e.id||Date.now()}-diff-${k}`,"diff-line",S,{isFirstLine:k===0,isLastLine:C,pairContent:h[k].pairContent,wrappedLines:b});C&&e.isStreaming?(R(),T=$):(_.push($),_.length>=Or&&R())}),R(),{completed:x,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 m={completed:[],active:[]};return Jn.set(t,m),m}let i=[],p=null,d=[],c=null,l=()=>{if(!d.length)return;let m=d;d=[],c=null,i.push(m.length===1?m[0]:{key:`${e.id||"x"}-chunk-${m[0].key}`,type:"chunk",blocks:m})},u=(m,g=!1)=>{if(c!==null&&c!==m.type&&l(),d.push(m),c=m.type,d.length>=Or){if(e.isStreaming&&g)return;l()}};if(e.role==="think"){i.push(a(`${e.id}-header`,"think-header",""));let m=o.split(`
684
734
  `);m.forEach((g,y)=>{let h=y===m.length-1;u(a(`${e.id}-${y}`,"think-line",g,{}),h)}),e.isStreaming||(l(),i.push({key:`${e.id}-footer-padding`,type:"think-footer-padding",text:""}))}else{let m=o.split(`
685
735
  `),g=!1,y=[],h=!1,w="",x=0,T=0;m.forEach((_,R)=>{let S=R===m.length-1,k=_.trim().startsWith("|"),C=_.trim().startsWith("```");h?C?(h=!1,u(a(`${e.id}-code-close-${T}`,"code-fence-close","",{}),S)):(x++,u(a(`${e.id}-code-line-${R}`,"code-line",_,{lineNum:x,lang:w}),S)):C?(h=!0,T=R,x=0,w=_.trim().replace(/^```/,"").trim(),u(a(`${e.id}-code-open-${R}`,"code-fence-open",w,{}),S)):k?(g=!0,y.push(_),S&&(l(),e.isStreaming?p=a(`${e.id}-table-${R}`,"table",y.join(`
686
736
  `),{isStreaming:!0}):i.push(a(`${e.id}-table-${R}`,"table",y.join(`
687
737
  `),{isStreaming:!1})))):(g&&(l(),i.push(a(`${e.id}-table-${R}`,"table",y.join(`
688
- `),{isStreaming:!1})),g=!1,y=[]),u(a(`${e.id}-${R}`,"agent-line",_,{}),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 f={completed:i,active:p?[p]:[]};if(e.isStreaming){let m=new Map;if(i.forEach(g=>Dr(g,m)),p&&Dr(p,m),po.set(s,{text:o,blocksMap:m}),po.size>Aa){let g=po.keys().next().value;po.delete(g)}}else{if(Xn.set(t,f),Xn.size>Aa){let m=Xn.keys().next().value;Xn.delete(m)}po.delete(s)}return f},ac={},lc=/(\r?\n){2}(?=\[?(?:tool:functions|tool\.functions|agent:generalist|agent\.generalist|\s*turn\s*:))/gi,Is=(e,n)=>{let t=!1,o=!1,s=0;for(;s<n;){if(e.startsWith("```",s)){o=!o,s+=3;continue}!o&&e[s]==="`"&&(s===0||e[s-1]!=="\\")&&(t=!t),s++}return o||t},cc=/\[SYSTEM\][\s\S]*?\[\/SYSTEM\]|\[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,dc=/(\$?\\?\/?\\rightarrow\$?|\$\\rightarrow\$)|(\$?\\?\/?\\leftarrow\$?|\$\\leftarrow\$)|(\$?\\?\/?\\uparrow\$?|\$\\uparrow\$)|(\$?\\?\/?\\downarrow\$?|\$\\downarrow\$)|(\$?\\?\/?\\leftrightarrow\$?|\$\\leftrightarrow\$)/gi,fc=/\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,Do=!1,uc=(e,n="agent")=>{if(!e)return e;let t=n===!0||n==="think",o=n===!1||n==="agent",s=e.replace(/<\|channel>thought/gi,"<think>").replace(/<channel\|>/gi,"</think>");if(t)return s.replace(/^<(think|thought|thoughts|thinking)>/gi,"").replace(/<\/(think|thought|thoughts|thinking)>$/gi,"").replace(/^\r?\n+/,"").replace(/\r?\n+$/,"");let r=s;o&&(r=r.replace(/<\/?(?:think|thought|thoughts|thinking)>/gi,(p,d,c)=>Is(c,d)?p:""),r=r.replace(lc,(p,d,c,l)=>!Do&&Is(l,c)?p:""),r&&r.includes("[tool:")&&(r=r.replace(/<(\w+)(?:[^>]*)>\s*([\s\S]*?\[tool:[^\]]*\][\s\S]*?)\s*<\/\1>/gi,(p,d,c)=>c&&c.includes("[tool:")?c.trim():p),Do&&(r=r.replace(/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi,(p,d)=>d.includes("[tool:")?d.trim():p))));let a="tool:functions.",i="agent:generalist.";if(o&&(r.toLowerCase().includes(a)||r.toLowerCase().includes(i)))for(;;){let p=r.toLowerCase(),d=p.indexOf(a),c=p.indexOf(i),l=a,u=d;if((d===-1||c!==-1&&c<d)&&(l=i,u=c),u===-1)break;if(!Do&&Is(r,u)){let T=u+l.length,_=p.indexOf(a,T),R=p.indexOf(i,T);if(_===-1&&R===-1)break;let S=-1,k=0;for(;;){let C=p.indexOf(a,k),E=p.indexOf(i,k),b=-1,$=a;if(C===-1&&E===-1)break;if(C===-1||E!==-1&&E<C?(b=E,$=i):b=C,!Is(r,b)){S=b,l=$;break}k=b+$.length}if(S===-1)break;u=S}let f=u,m=!1,g=u-1;for(;g>=0&&/\s/.test(r[g]);)g--;g>=0&&r[g]==="["&&(f=g,m=!0);let y=0,h=!1,w=null,x=u;for(;x<r.length;){let T=r[x];if(!w&&(T==="'"||T==='"'||T==="`")?w=T:w&&T===w&&r[x-1]!=="\\"&&(w=null),w||(T==="("?(y++,h=!0):T===")"&&y--),h&&y===0&&!w){let _=x;if(m){let R=x+1;for(;R<r.length&&/\s/.test(r[R]);)R++;R<r.length&&r[R]==="]"&&(_=R)}r=r.substring(0,f)+r.substring(_+1);break}if(x++,x===r.length)return h&&y>0&&(r=r.substring(0,f)),r}}return r=r.replace(cc,""),r=r.replace(dc,p=>{let d=p.toLowerCase();return d.includes("leftrightarrow")?"\u2194":d.includes("rightarrow")?"\u2192":d.includes("leftarrow")?"\u2190":d.includes("uparrow")?"\u2191":d.includes("downarrow")?"\u2193":p}),r=r.replace(fc,p=>ac[p.toLowerCase()]||p),r.trim()},Wu=()=>{Xn.clear(),po.clear()};var Pr=async(e,n={})=>{let t=D(e),o=t.path;if(!o)return'ERROR: Missing "path" argument for PatchFile.';let{patchPairs:s,allowMultiple:r,error:a}=Os(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=pc.resolve(process.cwd(),o);try{if(!Lr.existsSync(p))return`ERROR: File [${o}] does not exist. Use WriteFile instead.`;let d=n.forcedContent||Lr.readFileSync(p,"utf8");d.startsWith("\uFEFF")&&(d=d.slice(1));let c=d.replace(/\r\n/g,`
738
+ `),{isStreaming:!1})),g=!1,y=[]),u(a(`${e.id}-${R}`,"agent-line",_,{}),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 f={completed:i,active:p?[p]:[]};if(e.isStreaming){let m=new Map;if(i.forEach(g=>Lr(g,m)),p&&Lr(p,m),mo.set(s,{text:o,blocksMap:m}),mo.size>Aa){let g=mo.keys().next().value;mo.delete(g)}}else{if(Jn.set(t,f),Jn.size>Aa){let m=Jn.keys().next().value;Jn.delete(m)}mo.delete(s)}return f},ac={},lc=/(\r?\n){2}(?=\[?(?:tool:functions|tool\.functions|agent:generalist|agent\.generalist|\s*turn\s*:))/gi,Is=(e,n)=>{let t=!1,o=!1,s=0;for(;s<n;){if(e.startsWith("```",s)){o=!o,s+=3;continue}!o&&e[s]==="`"&&(s===0||e[s-1]!=="\\")&&(t=!t),s++}return o||t},cc=/\[SYSTEM\][\s\S]*?\[\/SYSTEM\]|\[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,dc=/(\$?\\?\/?\\rightarrow\$?|\$\\rightarrow\$)|(\$?\\?\/?\\leftarrow\$?|\$\\leftarrow\$)|(\$?\\?\/?\\uparrow\$?|\$\\uparrow\$)|(\$?\\?\/?\\downarrow\$?|\$\\downarrow\$)|(\$?\\?\/?\\leftrightarrow\$?|\$\\leftrightarrow\$)/gi,fc=/\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,Do=!1,uc=(e,n="agent")=>{if(!e)return e;let t=n===!0||n==="think",o=n===!1||n==="agent",s=e.replace(/<\|channel>thought/gi,"<think>").replace(/<channel\|>/gi,"</think>");if(t)return s.replace(/^<(think|thought|thoughts|thinking)>/gi,"").replace(/<\/(think|thought|thoughts|thinking)>$/gi,"").replace(/^\r?\n+/,"").replace(/\r?\n+$/,"");let r=s;o&&(r=r.replace(/<\/?(?:think|thought|thoughts|thinking)>/gi,(p,d,c)=>Is(c,d)?p:""),r=r.replace(lc,(p,d,c,l)=>!Do&&Is(l,c)?p:""),r&&r.includes("[tool:")&&(r=r.replace(/<(\w+)(?:[^>]*)>\s*([\s\S]*?\[tool:[^\]]*\][\s\S]*?)\s*<\/\1>/gi,(p,d,c)=>c&&c.includes("[tool:")?c.trim():p),Do&&(r=r.replace(/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi,(p,d)=>d.includes("[tool:")?d.trim():p))));let a="tool:functions.",i="agent:generalist.";if(o&&(r.toLowerCase().includes(a)||r.toLowerCase().includes(i)))for(;;){let p=r.toLowerCase(),d=p.indexOf(a),c=p.indexOf(i),l=a,u=d;if((d===-1||c!==-1&&c<d)&&(l=i,u=c),u===-1)break;if(!Do&&Is(r,u)){let T=u+l.length,_=p.indexOf(a,T),R=p.indexOf(i,T);if(_===-1&&R===-1)break;let S=-1,k=0;for(;;){let C=p.indexOf(a,k),E=p.indexOf(i,k),b=-1,$=a;if(C===-1&&E===-1)break;if(C===-1||E!==-1&&E<C?(b=E,$=i):b=C,!Is(r,b)){S=b,l=$;break}k=b+$.length}if(S===-1)break;u=S}let f=u,m=!1,g=u-1;for(;g>=0&&/\s/.test(r[g]);)g--;g>=0&&r[g]==="["&&(f=g,m=!0);let y=0,h=!1,w=null,x=u;for(;x<r.length;){let T=r[x];if(!w&&(T==="'"||T==='"'||T==="`")?w=T:w&&T===w&&r[x-1]!=="\\"&&(w=null),w||(T==="("?(y++,h=!0):T===")"&&y--),h&&y===0&&!w){let _=x;if(m){let R=x+1;for(;R<r.length&&/\s/.test(r[R]);)R++;R<r.length&&r[R]==="]"&&(_=R)}r=r.substring(0,f)+r.substring(_+1);break}if(x++,x===r.length)return h&&y>0&&(r=r.substring(0,f)),r}}return r=r.replace(cc,""),r=r.replace(dc,p=>{let d=p.toLowerCase();return d.includes("leftrightarrow")?"\u2194":d.includes("rightarrow")?"\u2192":d.includes("leftarrow")?"\u2190":d.includes("uparrow")?"\u2191":d.includes("downarrow")?"\u2193":p}),r=r.replace(fc,p=>ac[p.toLowerCase()]||p),r.trim()},Wu=()=>{Jn.clear(),mo.clear()};var Pr=async(e,n={})=>{let t=L(e),o=t.path;if(!o)return'ERROR: Missing "path" argument for PatchFile.';let{patchPairs:s,allowMultiple:r,error:a}=Os(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=pc.resolve(process.cwd(),o);try{if(!Dr.existsSync(p))return`ERROR: File [${o}] does not exist. Use WriteFile instead.`;let d=n.forcedContent||Dr.readFileSync(p,"utf8");d.startsWith("\uFEFF")&&(d=d.slice(1));let c=d.replace(/\r\n/g,`
689
739
  `).replace(/\r/g,`
690
- `),{content:l,results:u}=Ds(c,s,{allowMultiple:i}),f=u.filter(h=>!h.success),m=u.filter(h=>h.success);if(m.length===0)return`ERROR: Patch Failed to apply to [${o}].
740
+ `),{content:l,results:u}=Ls(c,s,{allowMultiple:i}),f=u.filter(h=>!h.success),m=u.filter(h=>h.success);if(m.length===0)return`ERROR: Patch Failed to apply to [${o}].
691
741
  ${f.map(h=>` \u2022 ${h.error}`).join(`
692
- `)}`;await ht.recordFileChange(p,c),Lr.writeFileSync(p,l,"utf8");let{systemSettings:g}=await en(),y=Ls(c,l,u,12,g?.compressToolResults);return f.length>0?`SUCCESS: File [${o}] updated with some blocks failed. [${m.length}/${s.length}] blocks applied.
742
+ `)}`;await ht.recordFileChange(p,c),Dr.writeFileSync(p,l,"utf8");let{systemSettings:g}=await tn(),y=Ds(c,l,u,12,g?.compressToolResults);return f.length>0?`SUCCESS: File [${o}] updated with some blocks failed. [${m.length}/${s.length}] blocks applied.
693
743
 
694
744
  Failures:
695
745
  ${f.map(h=>` \u2022 ${h.error}`).join(`
@@ -697,21 +747,21 @@ ${f.map(h=>` \u2022 ${h.error}`).join(`
697
747
 
698
748
  ${y}`:`SUCCESS: File [${o}] updated. [${u.length}/${s.length}] blocks applied.
699
749
 
700
- ${y}`}catch(d){let c=d instanceof Error?d.message:String(d);return`ERROR: Failed to update file [${o}]: ${c}`}};import mo from"fs";import Fr from"path";var mc=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",".skills","skills"]),hc=e=>mc.has(e)||e.startsWith(".pnpm"),gc=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"}},Nr=async e=>{let n=D(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 s=parseInt(String(n.recurse).trim(),10);o=isNaN(s)?1:s}o=Math.max(1,Math.min(3,o));try{let s=Fr.resolve(process.cwd(),t);if(!mo.existsSync(s))return`ERROR: Path [${t}] does not exist.`;if(!mo.statSync(s).isDirectory())return`ERROR: Path [${t}] is a file, not a directory. Use ReadFile instead.`;if(o===1){let g=mo.readdirSync(s),y=g.length,h=150,w=g.slice(0,h),x=[];for(let R of w){let S=Fr.join(s,R),k={name:R,type:"unknown",size:"N/A",mtime:"N/A"};try{let C=mo.statSync(S);k={name:R,type:C.isDirectory()?"directory":"file",size:(C.size/1024).toFixed(1)+"KB",mtime:gc(C.mtime)}}catch{k.type="inaccessible"}x.push(k)}let T=x.map(R=>R.type==="directory"?`${R.name}/`:`${R.name} (${R.size}, ${R.mtime})`).join(`
750
+ ${y}`}catch(d){let c=d instanceof Error?d.message:String(d);return`ERROR: Failed to update file [${o}]: ${c}`}};import ho from"fs";import Fr from"path";var mc=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",".skills","skills"]),hc=e=>mc.has(e)||e.startsWith(".pnpm"),gc=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"}},Nr=async e=>{let n=L(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 s=parseInt(String(n.recurse).trim(),10);o=isNaN(s)?1:s}o=Math.max(1,Math.min(3,o));try{let s=Fr.resolve(process.cwd(),t);if(!ho.existsSync(s))return`ERROR: Path [${t}] does not exist.`;if(!ho.statSync(s).isDirectory())return`ERROR: Path [${t}] is a file, not a directory. Use ReadFile instead.`;if(o===1){let g=ho.readdirSync(s),y=g.length,h=150,w=g.slice(0,h),x=[];for(let R of w){let S=Fr.join(s,R),k={name:R,type:"unknown",size:"N/A",mtime:"N/A"};try{let C=ho.statSync(S);k={name:R,type:C.isDirectory()?"directory":"file",size:(C.size/1024).toFixed(1)+"KB",mtime:gc(C.mtime)}}catch{k.type="inaccessible"}x.push(k)}let T=x.map(R=>R.type==="directory"?`${R.name}/`:`${R.name} (${R.size}, ${R.mtime})`).join(`
701
751
  `),_=`
702
752
 
703
753
  (Total items in folder: ${y})`;return y>h&&(_=`
704
754
 
705
755
  TRUNCATED: Showing first ${h} of ${y} items.`),g.length=0,w.length=0,x.length=0,`Detailed folder stats for [${t}]:
706
756
 
707
- ${T}${_}`}let a=0,i=0,p=0,d=500,c=!1,l=(g,y,h=1)=>{if(y>o||c)return[];let w=[];try{w=mo.readdirSync(g)}catch{return[`${" ".repeat(h-1)}[Inaccessible Directory]`]}let x=[],T=[];for(let k of w){let C=Fr.join(g,k),E=!1;try{E=mo.statSync(C).isDirectory()}catch{}E?x.push({name:k,fullPath:C}):T.push({name:k,fullPath:C})}x.sort((k,C)=>k.name.localeCompare(C.name)),T.sort((k,C)=>k.name.localeCompare(C.name));let _=[],R=" ".repeat(h-1);for(let k of x){if(p>=d){c=!0,_.push(`${R}[Truncated - Maximum item limit reached (${d})]`);break}if(p++,a++,_.push(`${R}${k.name}/`),y<o&&!hc(k.name)){let C=l(k.fullPath,y+1,h+1);_.push(...C)}}let S=[];for(let k of T){if(p>=d){c=!0,_.push(`${R}[Truncated - Maximum item limit reached (${d})]`);break}p++,i++;let C="N/A";try{C=(mo.statSync(k.fullPath).size/1024).toFixed(1)+"KB"}catch{}S.push(`${k.name} (${C})`)}return S.length>0&&_.push(`${R}${S.join("; ")}`),_},f=l(s,1,1).join(`
757
+ ${T}${_}`}let a=0,i=0,p=0,d=500,c=!1,l=(g,y,h=1)=>{if(y>o||c)return[];let w=[];try{w=ho.readdirSync(g)}catch{return[`${" ".repeat(h-1)}[Inaccessible Directory]`]}let x=[],T=[];for(let k of w){let C=Fr.join(g,k),E=!1;try{E=ho.statSync(C).isDirectory()}catch{}E?x.push({name:k,fullPath:C}):T.push({name:k,fullPath:C})}x.sort((k,C)=>k.name.localeCompare(C.name)),T.sort((k,C)=>k.name.localeCompare(C.name));let _=[],R=" ".repeat(h-1);for(let k of x){if(p>=d){c=!0,_.push(`${R}[Truncated - Maximum item limit reached (${d})]`);break}if(p++,a++,_.push(`${R}${k.name}/`),y<o&&!hc(k.name)){let C=l(k.fullPath,y+1,h+1);_.push(...C)}}let S=[];for(let k of T){if(p>=d){c=!0,_.push(`${R}[Truncated - Maximum item limit reached (${d})]`);break}p++,i++;let C="N/A";try{C=(ho.statSync(k.fullPath).size/1024).toFixed(1)+"KB"}catch{}S.push(`${k.name} (${C})`)}return S.length>0&&_.push(`${R}${S.join("; ")}`),_},f=l(s,1,1).join(`
708
758
  `),m=`
709
759
 
710
760
  (Total items scanned: ${p}, Directories: ${a}, Files: ${i})`;return c&&(m=`
711
761
 
712
762
  TRUNCATED: Scan capped at ${d} items. (Directories: ${a}, Files: ${i})`),`Detailed directory tree for [${t}] (recursive depth: ${o}):
713
763
 
714
- ${f}${m}`}catch(s){let r=s instanceof Error?s.message:String(s);return`ERROR: Failed to read folder [${t}]: ${r}`}};var Ps=async(e,n)=>{let t=D(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 yc from"puppeteer";import Lo from"path";import ho from"fs-extra";import{PDFDocument as wc}from"pdf-lib";var Ur=async e=>{let{path:n,content:t,orientation:o="portrait",margin:s="0px"}=D(e);if(!n)return'ERROR: Missing "path" argument for write_pdf.';if(!t)return'ERROR: Missing "content" (HTML/CSS) for write_pdf.';let r=Lo.resolve(process.cwd(),n),a=null;try{await ho.ensureDir(Lo.dirname(r)),await ht.recordFileChange(r);let i=uo();a=await yc.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 k=Lo.resolve(process.cwd(),S);if(await ho.pathExists(k)){let C=Lo.extname(k).toLowerCase().replace(".","")||"png",E=C==="jpg"?"jpeg":C==="svg"?"svg+xml":C,b=await ho.readFile(k,"base64");return`data:image/${E};base64,${b}`}}catch{}return null},u=/<link[^>]+href=["']([^"']+)["']/gi,f={},m;for(;(m=u.exec(t))!==null;){let S=m[1],k=m[0];if(S&&k.toLowerCase().includes("stylesheet")&&!S.startsWith("http://")&&!S.startsWith("https://")&&!S.startsWith("data:"))try{let C=Lo.resolve(process.cwd(),S);if(await ho.pathExists(C)){let E=await ho.readFile(C,"utf-8");f[k]=`<style>${E}</style>`}}catch{}}for(let[S,k]of Object.entries(f))d=d.split(S).join(k);let g=/<img[^>]+src=["']([^"']+)["']/gi;for(;(m=g.exec(d))!==null;){let S=m[1];if(S&&!c[S]){let k=await l(S);k&&(c[S]=k)}}let y=/url\(\s*['"]?([^'")]+?)['"]?\s*\)/gi;for(;(m=y.exec(d))!==null;){let S=m[1].trim();if(S&&!c[S]){let k=await l(S);k&&(c[S]=k)}}for(let[S,k]of Object.entries(c)){let C=S.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&"),E=new RegExp(`(src=["'])(${C})(["'])`,"gi");d=d.replace(E,`$1${k}$3`);let b=new RegExp(`url\\(\\s*(['"]?)(${C})\\1\\s*\\)`,"gi");d=d.replace(b,`url($1${k}$1)`)}let h=`
764
+ ${f}${m}`}catch(s){let r=s instanceof Error?s.message:String(s);return`ERROR: Failed to read folder [${t}]: ${r}`}};var Ps=async(e,n)=>{let t=L(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 yc from"puppeteer";import Po from"path";import go from"fs-extra";import{PDFDocument as wc}from"pdf-lib";var Ur=async e=>{let{path:n,content:t,orientation:o="portrait",margin:s="0px"}=L(e);if(!n)return'ERROR: Missing "path" argument for write_pdf.';if(!t)return'ERROR: Missing "content" (HTML/CSS) for write_pdf.';let r=Po.resolve(process.cwd(),n),a=null;try{await go.ensureDir(Po.dirname(r)),await ht.recordFileChange(r);let i=po();a=await yc.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 k=Po.resolve(process.cwd(),S);if(await go.pathExists(k)){let C=Po.extname(k).toLowerCase().replace(".","")||"png",E=C==="jpg"?"jpeg":C==="svg"?"svg+xml":C,b=await go.readFile(k,"base64");return`data:image/${E};base64,${b}`}}catch{}return null},u=/<link[^>]+href=["']([^"']+)["']/gi,f={},m;for(;(m=u.exec(t))!==null;){let S=m[1],k=m[0];if(S&&k.toLowerCase().includes("stylesheet")&&!S.startsWith("http://")&&!S.startsWith("https://")&&!S.startsWith("data:"))try{let C=Po.resolve(process.cwd(),S);if(await go.pathExists(C)){let E=await go.readFile(C,"utf-8");f[k]=`<style>${E}</style>`}}catch{}}for(let[S,k]of Object.entries(f))d=d.split(S).join(k);let g=/<img[^>]+src=["']([^"']+)["']/gi;for(;(m=g.exec(d))!==null;){let S=m[1];if(S&&!c[S]){let k=await l(S);k&&(c[S]=k)}}let y=/url\(\s*['"]?([^'")]+?)['"]?\s*\)/gi;for(;(m=y.exec(d))!==null;){let S=m[1].trim();if(S&&!c[S]){let k=await l(S);k&&(c[S]=k)}}for(let[S,k]of Object.entries(c)){let C=S.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&"),E=new RegExp(`(src=["'])(${C})(["'])`,"gi");d=d.replace(E,`$1${k}$3`);let b=new RegExp(`url\\(\\s*(['"]?)(${C})\\1\\s*\\)`,"gi");d=d.replace(b,`url($1${k}$1)`)}let h=`
715
765
  <style>
716
766
  @page {
717
767
  margin: ${s};
@@ -741,7 +791,7 @@ ${f}${m}`}catch(s){let r=s instanceof Error?s.message:String(s);return`ERROR: Fa
741
791
  </style>
742
792
  <div class="watermark">Generated by FluxFlow CLI (AI)</div>
743
793
  ${d}
744
- `;await p.setContent(h,{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}),x=await wc.load(w),T=Lo.basename(n);x.setTitle(`FluxFlow_${T}`),x.setAuthor("FluxFlow CLI"),x.setSubject("Generated with Agentic AI System"),x.setKeywords(["FluxFlow","AI","Agentic","Automated"]),x.setCreator("FluxFlow PDF Engine"),x.setProducer("FluxFlow (Generative AI)");let _=await x.save();await ho.writeFile(r,_);let R=await ho.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 Ma from"fs-extra";import Br from"path";import xc from"html-to-docx";var Wr=async e=>{let{path:n,content:t}=D(e);if(!n)return'ERROR: Missing "path" argument for write_docx.';if(!t)return'ERROR: Missing "content" (HTML) for write_docx.';let o=Br.resolve(process.cwd(),n);try{await Ma.ensureDir(Br.dirname(o)),await ht.recordFileChange(o);let s=Br.basename(n),r=t.includes("<html")?t:`
794
+ `;await p.setContent(h,{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}),x=await wc.load(w),T=Po.basename(n);x.setTitle(`FluxFlow_${T}`),x.setAuthor("FluxFlow CLI"),x.setSubject("Generated with Agentic AI System"),x.setKeywords(["FluxFlow","AI","Agentic","Automated"]),x.setCreator("FluxFlow PDF Engine"),x.setProducer("FluxFlow (Generative AI)");let _=await x.save();await go.writeFile(r,_);let R=await go.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 Ma from"fs-extra";import Br from"path";import xc from"html-to-docx";var Wr=async e=>{let{path:n,content:t}=L(e);if(!n)return'ERROR: Missing "path" argument for write_docx.';if(!t)return'ERROR: Missing "content" (HTML) for write_docx.';let o=Br.resolve(process.cwd(),n);try{await Ma.ensureDir(Br.dirname(o)),await ht.recordFileChange(o);let s=Br.basename(n),r=t.includes("<html")?t:`
745
795
  <!DOCTYPE html>
746
796
  <html lang="en">
747
797
  <head>
@@ -753,38 +803,38 @@ ${f}${m}`}catch(s){let r=s instanceof Error?s.message:String(s);return`ERROR: Fa
753
803
  </body>
754
804
  </html>
755
805
  `,a=await xc(r,null,{title:`FluxFlow_${s}`,creator:"FluxFlow CLI",description:"Generated by Agentic AI System",table:{row:{cantSplit:!0}},footer:!0,pageNumber:!0});return await Ma.writeFile(o,a),`SUCCESS: Word document [${n}] generated successfully.
756
- - 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 ns from"fs/promises";import wn from"path";import jr from"fast-glob";import{Minimatch as va}from"minimatch";import bc from"fs";async function ts(e,n,t=e,o=1){if(o>12)return[];let s=[],r;try{r=await ns.readdir(e,{withFileTypes:!0})}catch{return[]}for(let a of r){let i=wn.join(e,a.name),p=wn.relative(t,i),d=p.split(wn.sep).map(u=>u.toLowerCase()),c=a.name.toLowerCase();if(!n.some(u=>{let f=u.toLowerCase();return f.startsWith(".")&&c.endsWith(f)?!0:d.some(m=>m===f||m.startsWith(".pnpm"))}))if(a.isDirectory()){let u=await ts(i,n,t,o+1);s=s.concat(u)}else a.isFile()&&s.push({fullPath:i,relativePath:p})}return s}function Sc(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 kc(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&&Sc(a,p,i)<=i)return!0;return!1})}async function Tc(e){let n=wn.join(Qt,"skills","fluxflow"),t=wn.join(n,"references");if(!bc.existsSync(t))return"No documentation found in #docs.";let o=async p=>{let d=[];try{let c=await ns.readdir(p,{withFileTypes:!0});for(let l of c){let u=wn.join(p,l.name);l.isDirectory()?d=d.concat(await o(u)):l.isFile()&&d.push(u)}}catch{}return d},s=await o(t);if(s.length===0)return"No documentation found in #docs.";let r=null;try{r=new RegExp(e,"i")}catch{}let a=e.toLowerCase(),i=[];for(let p of s)try{let d=await ns.readFile(p,"utf8");if(r&&r.test(d)||d.toLowerCase().includes(a)){let l=wn.relative(n,p).replace(/\\/g,"/");i.push(l)}}catch{}return i.length===0?`No matches found for "${e}" in #docs.`:`DOCs Search "${e}":
806
+ - 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 os from"fs/promises";import xn from"path";import jr from"fast-glob";import{Minimatch as va}from"minimatch";import bc from"fs";async function ns(e,n,t=e,o=1){if(o>12)return[];let s=[],r;try{r=await os.readdir(e,{withFileTypes:!0})}catch{return[]}for(let a of r){let i=xn.join(e,a.name),p=xn.relative(t,i),d=p.split(xn.sep).map(u=>u.toLowerCase()),c=a.name.toLowerCase();if(!n.some(u=>{let f=u.toLowerCase();return f.startsWith(".")&&c.endsWith(f)?!0:d.some(m=>m===f||m.startsWith(".pnpm"))}))if(a.isDirectory()){let u=await ns(i,n,t,o+1);s=s.concat(u)}else a.isFile()&&s.push({fullPath:i,relativePath:p})}return s}function Sc(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 kc(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&&Sc(a,p,i)<=i)return!0;return!1})}async function Tc(e){let n=xn.join(Tt,"skills","fluxflow"),t=xn.join(n,"references");if(!bc.existsSync(t))return"No documentation found in #docs.";let o=async p=>{let d=[];try{let c=await os.readdir(p,{withFileTypes:!0});for(let l of c){let u=xn.join(p,l.name);l.isDirectory()?d=d.concat(await o(u)):l.isFile()&&d.push(u)}}catch{}return d},s=await o(t);if(s.length===0)return"No documentation found in #docs.";let r=null;try{r=new RegExp(e,"i")}catch{}let a=e.toLowerCase(),i=[];for(let p of s)try{let d=await os.readFile(p,"utf8");if(r&&r.test(d)||d.toLowerCase().includes(a)){let l=xn.relative(n,p).replace(/\\/g,"/");i.push(l)}}catch{}return i.length===0?`No matches found for "${e}" in #docs.`:`DOCs Search "${e}":
757
807
  ${i.map(p=>`- ${p}`).join(`
758
- `)}`}var os=async e=>{let{keyword:n,path:t,fuzzy:o,subString:s,regex:r}=D(e);if(n==null)return'ERROR: Missing "keyword" argument.';let a=String(n);if(t&&(t.trim().toLowerCase()==="#docs"||t.trim().toLowerCase()==="#doc"||t.trim().toLowerCase()==="#documentation"||t.trim().toLowerCase().includes("#skill/global/fluxflow")))return Tc(a);let 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,u=null;if(p)c||(u=new RegExp(`(?<![\\w])${a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\\w])`,"i"));else{try{l=new RegExp(a,"i")}catch(g){if(d)return`ERROR: Invalid regex pattern "${a}": ${g.message}`}u=new RegExp(`(?<![\\w])${a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\\w])`,"i")}let f=[".git","node_modules",".gemini","dist","build",".next","out",".cache","bin","obj","vendor","venv",".idea",".gradle",".terraform","target","coverage",".vscode",".svn",".hg",".fslckout",".github",".gitlab",".circleci",".gitea",".gitee",".lerna",".changeset",".nx",".npm",".yarn",".pnpm-store",".pnpm",".expo",".nuxt",".svelte-kit",".docusaurus",".turbo",".vercel","bower_components",".netlify",".vuepress",".quasar",".output",".angular","jspm_packages",".parcel-cache",".rollup.cache",".rspack",".vitepress","__pycache__",".pytest_cache",".mypy_cache",".tox",".poetry","env","vhdl",".ipynb_checkpoints",".jupyter",".conda",".pdm-build",".bundle",".yardoc",".metadata","App_Data","ClientBin",".cargo",".rustc_info",".go","Godeps","_vendor",".rake_tasks","CMakefiles",".wakatime",".dart_tool",".fvm",".cocoapods","Pods",".pub-cache",".symlinks","DerivedData",".xcworkspace",".serverless",".aws",".gcloud",".azure",".kube",".vagrant",".docker","postgres-data","redis-data","mongo-data",".Spotlight-V100",".Trashes","$RECYCLE.BIN","System Volume Information",".DocumentRevisions-V100",".fseventsd","AppData","Application Data","Local","LocalLow","Roaming","$WinREAgent","$WINDOWS.~BT","$WINDOWS.~WS","scw","System32","SysWOW64",".AppleDouble",".AppleDB",".AppleDesktop","_CodeSignature",".cmio",".LSOverride",".localized",".TemporaryItems",".Trash",".Trash-0",".Trash-1000",".gvfs",".local",".config",".dbus",".fontconfig",".snap",".var",".lost+found","lost+found",".thumb",".thumbnails","EFI","boot","grub","logs","log",".nyc_output",".sonar",".ruff_cache",".VSCodeCounter",".exe",".dll",".so",".dylib",".png",".jpg",".jpeg",".gif",".ico",".svg",".webp",".mp3",".mp4",".avi",".zip",".tgz",".tar",".gz",".7z",".rar",".pdf",".docx",".xlsx",".pptx",".woff",".woff2",".ttf",".eot",".skills","skills"],m=150;try{let g=[],y=process.cwd(),h=null;if(t){let I=t.split(";").map(W=>W.trim()).filter(Boolean),O=I.some(W=>W.startsWith("!"));if(I.some(W=>jr.isDynamicPattern(W)||/[*?{}[\]()|+]/.test(W))){h="glob";let W=t.replace(/\\/g,"/"),q=I.map(F=>F.replace(/\\/g,"/")),Q=f.map(F=>F.startsWith(".")?`**/*${F}`:`**/${F}/**`);if(O&&!I.some(F=>!F.startsWith("!"))){let F=await ts(y,f,y),B=v=>v.endsWith("/")?v+"**":v,ee=q.filter(v=>v.startsWith("!")).map(v=>B(v.slice(1))),Me=q.filter(v=>!v.startsWith("!")).map(B);g=F.filter(v=>{let U=v.relativePath.replace(/\\/g,"/"),X=Me.length===0||Me.some(We=>{try{return new va(We).match(U)}catch{return!1}}),te=ee.some(We=>{try{return new va(We).match(U)}catch{return!1}});return X&&!te})}else{let F=q.some(ee=>/[\(\)\|]|\.\*/.test(ee)),B=[];if(!F)try{B=await jr(q,{cwd:y,ignore:Q,dot:!0,onlyFiles:!0,absolute:!1})}catch{B=[]}if(B.length===0&&(F||jr.isDynamicPattern(W))){let ee=W.match(/^([^\*\?\(\)\|\[\]\s]+)\//),Me=ee&&!/[\*\?\(\)\|\[\]]/.test(ee[1])?wn.resolve(y,ee[1]):y,v=await ts(Me,f,y);try{let U=W.replace(/^\.\//,"");U=U.replace(/\.\*\/(\\.|[^\/])/g,".*$1"),!U.startsWith("^")&&!U.startsWith(".*")&&(U=`.*${U}`);let X=new RegExp(U.endsWith("$")?U:`${U}$`,"i");g=v.filter(te=>{let We=te.relativePath.replace(/\\/g,"/");return X.test(We)})}catch{g=[]}}else g=B.map(ee=>({fullPath:wn.resolve(y,ee),relativePath:ee}))}}else{let W=t.replace(/[\/\\]+$/,""),q=wn.resolve(y,W);try{let Q=await ns.stat(q);if(Q.isDirectory())h="dir",g=await ts(q,f,y);else if(Q.isFile())h="file",g.push({fullPath:q,relativePath:wn.relative(y,q)});else return`ERROR: Path is neither a file nor a directory: ${t}`}catch{return`ERROR: Path not found: ${t}`}}}else g=await ts(y,f);let w=g.map(async I=>{try{let O=await ns.readFile(I.fullPath,"utf-8");if(O.includes("\0"))return[];let P=O.split(/\r?\n/),W=[];for(let Q=0;Q<P.length;Q++)(c?P[Q].toLowerCase().includes(a.toLowerCase())||kc(P[Q],a):p?u&&u.test(P[Q]):l&&l.test(P[Q])||u&&u.test(P[Q]))&&W.push({line:Q+1,content:P[Q].trim()});return W.length===0?null:{path:I.relativePath.replace(/\\/g,"/"),matches:W}}catch{return[]}}),x=await Promise.all(w),T=[],_=0;for(let I of x){if(!I||!I.matches)continue;if(_>=m)break;let O=m-_,P=I.matches.slice(0,O);T.push({path:I.path,matches:P}),_+=P.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=h==="file"?` in '${t}'`:h==="dir"||h==="glob"?` in '${t}'`:". Try to specify files",O=h==="dir"?"[DIR]":h==="glob"?"[GLOB]":"";return`${O}${O?" ":""}Found 0 matches of '${a}'${I}${R?` ${R}`:""}`}let S=R?` ${R}`:"",k=`${T.length} file${T.length===1?"":"s"}`,C=`${_} match${_===1?"":"es"}`,E;h==="file"?E=`Found ${C} of '${a}' in '${t}'${S}:`:h==="dir"||h==="glob"?E=`Found ${C} of '${a}' in '${t}' across ${k}${S}:`:E=`Found ${C} of '${a}' across ${k}${S}:`;let b=h==="dir"?"[DIR]":h==="glob"?"[GLOB]":"",$=`${b}${b?" ":""}${E}
808
+ `)}`}var ss=async e=>{let{keyword:n,path:t,fuzzy:o,subString:s,regex:r}=L(e);if(n==null)return'ERROR: Missing "keyword" argument.';let a=String(n);if(t&&(t.trim().toLowerCase()==="#docs"||t.trim().toLowerCase()==="#doc"||t.trim().toLowerCase()==="#documentation"||t.trim().toLowerCase().includes("#skill/global/fluxflow")))return Tc(a);let 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,u=null;if(p)c||(u=new RegExp(`(?<![\\w])${a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\\w])`,"i"));else{try{l=new RegExp(a,"i")}catch(g){if(d)return`ERROR: Invalid regex pattern "${a}": ${g.message}`}u=new RegExp(`(?<![\\w])${a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\\w])`,"i")}let f=[".git","node_modules",".gemini","dist","build",".next","out",".cache","bin","obj","vendor","venv",".idea",".gradle",".terraform","target","coverage",".vscode",".svn",".hg",".fslckout",".github",".gitlab",".circleci",".gitea",".gitee",".lerna",".changeset",".nx",".npm",".yarn",".pnpm-store",".pnpm",".expo",".nuxt",".svelte-kit",".docusaurus",".turbo",".vercel","bower_components",".netlify",".vuepress",".quasar",".output",".angular","jspm_packages",".parcel-cache",".rollup.cache",".rspack",".vitepress","__pycache__",".pytest_cache",".mypy_cache",".tox",".poetry","env","vhdl",".ipynb_checkpoints",".jupyter",".conda",".pdm-build",".bundle",".yardoc",".metadata","App_Data","ClientBin",".cargo",".rustc_info",".go","Godeps","_vendor",".rake_tasks","CMakefiles",".wakatime",".dart_tool",".fvm",".cocoapods","Pods",".pub-cache",".symlinks","DerivedData",".xcworkspace",".serverless",".aws",".gcloud",".azure",".kube",".vagrant",".docker","postgres-data","redis-data","mongo-data",".Spotlight-V100",".Trashes","$RECYCLE.BIN","System Volume Information",".DocumentRevisions-V100",".fseventsd","AppData","Application Data","Local","LocalLow","Roaming","$WinREAgent","$WINDOWS.~BT","$WINDOWS.~WS","scw","System32","SysWOW64",".AppleDouble",".AppleDB",".AppleDesktop","_CodeSignature",".cmio",".LSOverride",".localized",".TemporaryItems",".Trash",".Trash-0",".Trash-1000",".gvfs",".local",".config",".dbus",".fontconfig",".snap",".var",".lost+found","lost+found",".thumb",".thumbnails","EFI","boot","grub","logs","log",".nyc_output",".sonar",".ruff_cache",".VSCodeCounter",".exe",".dll",".so",".dylib",".png",".jpg",".jpeg",".gif",".ico",".svg",".webp",".mp3",".mp4",".avi",".zip",".tgz",".tar",".gz",".7z",".rar",".pdf",".docx",".xlsx",".pptx",".woff",".woff2",".ttf",".eot",".skills","skills"],m=150;try{let g=[],y=process.cwd(),h=null;if(t){let I=t.split(";").map(W=>W.trim()).filter(Boolean),O=I.some(W=>W.startsWith("!"));if(I.some(W=>jr.isDynamicPattern(W)||/[*?{}[\]()|+]/.test(W))){h="glob";let W=t.replace(/\\/g,"/"),q=I.map(F=>F.replace(/\\/g,"/")),Q=f.map(F=>F.startsWith(".")?`**/*${F}`:`**/${F}/**`);if(O&&!I.some(F=>!F.startsWith("!"))){let F=await ns(y,f,y),B=v=>v.endsWith("/")?v+"**":v,ee=q.filter(v=>v.startsWith("!")).map(v=>B(v.slice(1))),Me=q.filter(v=>!v.startsWith("!")).map(B);g=F.filter(v=>{let U=v.relativePath.replace(/\\/g,"/"),X=Me.length===0||Me.some(We=>{try{return new va(We).match(U)}catch{return!1}}),te=ee.some(We=>{try{return new va(We).match(U)}catch{return!1}});return X&&!te})}else{let F=q.some(ee=>/[\(\)\|]|\.\*/.test(ee)),B=[];if(!F)try{B=await jr(q,{cwd:y,ignore:Q,dot:!0,onlyFiles:!0,absolute:!1})}catch{B=[]}if(B.length===0&&(F||jr.isDynamicPattern(W))){let ee=W.match(/^([^\*\?\(\)\|\[\]\s]+)\//),Me=ee&&!/[\*\?\(\)\|\[\]]/.test(ee[1])?xn.resolve(y,ee[1]):y,v=await ns(Me,f,y);try{let U=W.replace(/^\.\//,"");U=U.replace(/\.\*\/(\\.|[^\/])/g,".*$1"),!U.startsWith("^")&&!U.startsWith(".*")&&(U=`.*${U}`);let X=new RegExp(U.endsWith("$")?U:`${U}$`,"i");g=v.filter(te=>{let We=te.relativePath.replace(/\\/g,"/");return X.test(We)})}catch{g=[]}}else g=B.map(ee=>({fullPath:xn.resolve(y,ee),relativePath:ee}))}}else{let W=t.replace(/[\/\\]+$/,""),q=xn.resolve(y,W);try{let Q=await os.stat(q);if(Q.isDirectory())h="dir",g=await ns(q,f,y);else if(Q.isFile())h="file",g.push({fullPath:q,relativePath:xn.relative(y,q)});else return`ERROR: Path is neither a file nor a directory: ${t}`}catch{return`ERROR: Path not found: ${t}`}}}else g=await ns(y,f);let w=g.map(async I=>{try{let O=await os.readFile(I.fullPath,"utf-8");if(O.includes("\0"))return[];let P=O.split(/\r?\n/),W=[];for(let Q=0;Q<P.length;Q++)(c?P[Q].toLowerCase().includes(a.toLowerCase())||kc(P[Q],a):p?u&&u.test(P[Q]):l&&l.test(P[Q])||u&&u.test(P[Q]))&&W.push({line:Q+1,content:P[Q].trim()});return W.length===0?null:{path:I.relativePath.replace(/\\/g,"/"),matches:W}}catch{return[]}}),x=await Promise.all(w),T=[],_=0;for(let I of x){if(!I||!I.matches)continue;if(_>=m)break;let O=m-_,P=I.matches.slice(0,O);T.push({path:I.path,matches:P}),_+=P.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=h==="file"?` in '${t}'`:h==="dir"||h==="glob"?` in '${t}'`:". Try to specify files",O=h==="dir"?"[DIR]":h==="glob"?"[GLOB]":"";return`${O}${O?" ":""}Found 0 matches of '${a}'${I}${R?` ${R}`:""}`}let S=R?` ${R}`:"",k=`${T.length} file${T.length===1?"":"s"}`,C=`${_} match${_===1?"":"es"}`,E;h==="file"?E=`Found ${C} of '${a}' in '${t}'${S}:`:h==="dir"||h==="glob"?E=`Found ${C} of '${a}' in '${t}' across ${k}${S}:`:E=`Found ${C} of '${a}' across ${k}${S}:`;let b=h==="dir"?"[DIR]":h==="glob"?"[GLOB]":"",$=`${b}${b?" ":""}${E}
759
809
 
760
810
  `;for(let I of T){$+=`${I.path}
761
811
  `;for(let O of I.matches)$+=` ${O.line}: ${O.content}
762
812
  `;$+=`
763
- `}return $.trimEnd()}catch(g){return`ERROR: ${g.message}`}};import Ia from"fs-extra";import Gr from"path";var Rc=(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 u=s(l.subarray(4,8+c));return l.writeUInt32BE(u,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}},Hr=async(e,n={})=>{let t=D(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 en();if(!await Oi(d))return`ERROR: Insufficient Quota for selected quality. Either tell user reduce quality or wait for next refresh cycle (${(await Di()).nextResetMin||60}m).`;let l=d.imageSettings||{keyType:"Default",quality:"Low-High",apiKey:""},u=l.keyType==="Custom"&&l.apiKey?l.apiKey:FALLBACK_IMAGE_KEY,m={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 O=r.replace(/\s+/g,"");O==="16:9"?(g=1024,y=576):O==="9:16"?(g=576,y=1024):O==="4:3"?(g=1024,y=768):O==="3:4"?(g=768,y=1024):O==="1:1"&&(g=1024,y=1024)}let h=Math.floor(Math.random()*1e7),x=`https://gen.pollinations.ai/image/${encodeURIComponent(o)}?model=${m}&width=${g}&height=${y}&seed=${h}&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(x,{method:"GET",headers:{Authorization:`Bearer ${u}`}});if(!T.ok){let O=T.status,P="";try{P=await T.text()}catch{}return O===402||P.includes("Insufficient balance")||P.includes("PAYMENT_REQUIRED")?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed with status [${O}]: ${P||"Unknown API Error"}`}if((T.headers.get("content-type")||"").includes("application/json")){let O=await T.json();return O.status===402||O.error&&O.error.code==="PAYMENT_REQUIRED"?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed: ${O.error?.message||JSON.stringify(O)}`}let R=await T.arrayBuffer(),S=Buffer.from(R),k={Title:o,Description:"Generated via FluxFlow CLI",Software:"FluxFlow CLI",Author:"FluxFlow","Creation Time":new Date().toISOString(),Prompt:o,Model:`Fluxflow:${m}`,Ratio:r||"1:1",Seed:String(h)};S=Rc(S,k);let C=Gr.resolve(process.cwd(),s);await Ia.ensureDir(Gr.dirname(C)),await ht.recordFileChange(C),await Ia.writeFile(C,S),await Li(d);let E=Gr.extname(s).toLowerCase(),$={".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:S.toString("base64"),mimeType:$}}}:`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 ss=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=oe(Zt,{}),a=oe(Ln,{});return a[o]=s,delete r[o],pe(Ln,a),pe(Zt,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 Po=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=oe(Pt,[]),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(Pt,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 zr from"fs-extra";import yo from"path";import{createRequire as _c}from"module";import go from"fs-extra";import qr from"path";import Ec from"https";var Oa={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 Cc(e,n=null){let t=n||`https://unpkg.com/tree-sitter-wasms@0.1.13/out/${e}`,o=qr.join(co,e);return await go.ensureDir(co),new Promise((s,r)=>{let a={headers:{"User-Agent":"FluxFlow-Agent"}};Ec.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}`}Cc(e,d).then(s).catch(r);return}if(i.statusCode!==200){r(new Error(`Failed to download ${e}: HTTP ${i.statusCode}`));return}let p=go.createWriteStream(o);i.pipe(p),p.on("finish",()=>{p.close(),s()})}).on("error",i=>{go.existsSync(o)&&go.unlink(o,()=>{}),r(i)})})}function Wp(e){let n=qr.join(co,e);return go.existsSync(n)}async function jp(e){let n=qr.join(co,e);go.existsSync(n)&&await go.unlink(n)}var Pa=_c(import.meta.url),Da=Pa("web-tree-sitter"),La=!1,Fa=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"]),Na=new Set(["export_statement","lexical_declaration","variable_declaration","variable_declarator","pair","assignment_expression"]);function xn(e,n=50){if(!e)return"";let t=e.replace(/\s+/g," ").trim();return t.length>n?t.substring(0,n-3)+"...":t}function Ua(e){let n=e.type;if(n==="if_statement"){let o=e.childForFieldName("condition");return o?`if (${xn(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?xn(o.text,40):""})`}if(n==="for_statement"||n==="for_in_statement"||n==="for_of_statement"){let s=e.text.split(`
764
- `)[0].match(/for\s*(?:await\s*)?\((.*)\)/);return s?`for (${xn(s[1],40)})`:"for"}if(n==="switch_statement"){let o=e.childForFieldName("value");return`switch (${o?xn(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?`<${xn(s.text,30)}>`:null}if(["import_declaration","import_from_statement","import_statement","preproc_include"].includes(n))return xn(e.text.split(`
765
- `)[0],60);if(n==="pair"){let o=e.childForFieldName("key");return o?xn(o.text.replace(/["']/g,""),40):null}if(n==="assignment_expression"){let o=e.childForFieldName("left");return o?`${xn(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?xn(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 xn(o.text,40)}return xn(t.text,40)}if(["arrow_function","function_expression","function_declaration"].includes(n)){let o=e.parent;for(;o&&o.type!=="program";){let s=Ua(o);if(s)return s;if(!Na.has(o.type))break;o=o.parent}}return null}function $c(e){let n=[];function t(o){for(let s of o.children)Fa.has(s.type)?n.push(s):t(s)}return t(e),n}function Ac(e){return e.replace(/_([a-z])/g,n=>n[1].toUpperCase())}function Ba(e,n=0,t=!0,o="",s=null,r=12){let a=e.type,i=Ua(e),p=Fa.has(a)||n===0,d=$c(e),c=p&&n>0&&(Na.has(a)&&d.length>0||i!==null&&i===s&&d.length>0),l="",u=o,f=n,m=s;if(p&&!c){let g=e.startPosition.row+1,y=e.endPosition.row+1,h=Ac(a),w=i?`${h} [${i}]`:h;n===0?(l+=`\u{1F4C1} ROOT (Lines: ${g}-${y})
813
+ `}return $.trimEnd()}catch(g){return`ERROR: ${g.message}`}};import Ia from"fs-extra";import Gr from"path";var Rc=(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 u=s(l.subarray(4,8+c));return l.writeUInt32BE(u,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}},Hr=async(e,n={})=>{let t=L(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 tn();if(!await Oi(d))return`ERROR: Insufficient Quota for selected quality. Either tell user reduce quality or wait for next refresh cycle (${(await Li()).nextResetMin||60}m).`;let l=d.imageSettings||{keyType:"Default",quality:"Low-High",apiKey:""},u=l.keyType==="Custom"&&l.apiKey?l.apiKey:FALLBACK_IMAGE_KEY,m={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 O=r.replace(/\s+/g,"");O==="16:9"?(g=1024,y=576):O==="9:16"?(g=576,y=1024):O==="4:3"?(g=1024,y=768):O==="3:4"?(g=768,y=1024):O==="1:1"&&(g=1024,y=1024)}let h=Math.floor(Math.random()*1e7),x=`https://gen.pollinations.ai/image/${encodeURIComponent(o)}?model=${m}&width=${g}&height=${y}&seed=${h}&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(x,{method:"GET",headers:{Authorization:`Bearer ${u}`}});if(!T.ok){let O=T.status,P="";try{P=await T.text()}catch{}return O===402||P.includes("Insufficient balance")||P.includes("PAYMENT_REQUIRED")?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed with status [${O}]: ${P||"Unknown API Error"}`}if((T.headers.get("content-type")||"").includes("application/json")){let O=await T.json();return O.status===402||O.error&&O.error.code==="PAYMENT_REQUIRED"?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed: ${O.error?.message||JSON.stringify(O)}`}let R=await T.arrayBuffer(),S=Buffer.from(R),k={Title:o,Description:"Generated via FluxFlow CLI",Software:"FluxFlow CLI",Author:"FluxFlow","Creation Time":new Date().toISOString(),Prompt:o,Model:`Fluxflow:${m}`,Ratio:r||"1:1",Seed:String(h)};S=Rc(S,k);let C=Gr.resolve(process.cwd(),s);await Ia.ensureDir(Gr.dirname(C)),await ht.recordFileChange(C),await Ia.writeFile(C,S),await Di(d);let E=Gr.extname(s).toLowerCase(),$={".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:S.toString("base64"),mimeType:$}}}:`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 rs=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=oe(en,{}),a=oe(Pn,{});return a[o]=s,delete r[o],pe(Pn,a),pe(en,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 Fo=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=oe(Ft,[]),r=!1,a=[];for(let c of s)c.score===void 0&&(c.score=.5),c.id===o?(c.score=Math.min(2,c.score+.2),r=!0):(c.score*=.98,c.score<.05&&(c.score=0)),c.score=Math.round(c.score*1e5)/1e5,c.score>0&&a.push(c);if(pe(Ft,a),!r)return`WARNING: Memory ID [${o}] not found. Other memories decayed by -0.01.`;let i=a.find(c=>c.id===o),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 zr from"fs-extra";import wo from"path";import{createRequire as _c}from"module";import yo from"fs-extra";import qr from"path";import Ec from"https";var Oa={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 Cc(e,n=null){let t=n||`https://unpkg.com/tree-sitter-wasms@0.1.13/out/${e}`,o=qr.join(fo,e);return await yo.ensureDir(fo),new Promise((s,r)=>{let a={headers:{"User-Agent":"FluxFlow-Agent"}};Ec.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}`}Cc(e,d).then(s).catch(r);return}if(i.statusCode!==200){r(new Error(`Failed to download ${e}: HTTP ${i.statusCode}`));return}let p=yo.createWriteStream(o);i.pipe(p),p.on("finish",()=>{p.close(),s()})}).on("error",i=>{yo.existsSync(o)&&yo.unlink(o,()=>{}),r(i)})})}function Wp(e){let n=qr.join(fo,e);return yo.existsSync(n)}async function jp(e){let n=qr.join(fo,e);yo.existsSync(n)&&await yo.unlink(n)}var Pa=_c(import.meta.url),La=Pa("web-tree-sitter"),Da=!1,Fa=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"]),Na=new Set(["export_statement","lexical_declaration","variable_declaration","variable_declarator","pair","assignment_expression"]);function bn(e,n=50){if(!e)return"";let t=e.replace(/\s+/g," ").trim();return t.length>n?t.substring(0,n-3)+"...":t}function Ua(e){let n=e.type;if(n==="if_statement"){let o=e.childForFieldName("condition");return o?`if (${bn(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?bn(o.text,40):""})`}if(n==="for_statement"||n==="for_in_statement"||n==="for_of_statement"){let s=e.text.split(`
814
+ `)[0].match(/for\s*(?:await\s*)?\((.*)\)/);return s?`for (${bn(s[1],40)})`:"for"}if(n==="switch_statement"){let o=e.childForFieldName("value");return`switch (${o?bn(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?`<${bn(s.text,30)}>`:null}if(["import_declaration","import_from_statement","import_statement","preproc_include"].includes(n))return bn(e.text.split(`
815
+ `)[0],60);if(n==="pair"){let o=e.childForFieldName("key");return o?bn(o.text.replace(/["']/g,""),40):null}if(n==="assignment_expression"){let o=e.childForFieldName("left");return o?`${bn(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?bn(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 bn(o.text,40)}return bn(t.text,40)}if(["arrow_function","function_expression","function_declaration"].includes(n)){let o=e.parent;for(;o&&o.type!=="program";){let s=Ua(o);if(s)return s;if(!Na.has(o.type))break;o=o.parent}}return null}function $c(e){let n=[];function t(o){for(let s of o.children)Fa.has(s.type)?n.push(s):t(s)}return t(e),n}function Ac(e){return e.replace(/_([a-z])/g,n=>n[1].toUpperCase())}function Ba(e,n=0,t=!0,o="",s=null,r=12){let a=e.type,i=Ua(e),p=Fa.has(a)||n===0,d=$c(e),c=p&&n>0&&(Na.has(a)&&d.length>0||i!==null&&i===s&&d.length>0),l="",u=o,f=n,m=s;if(p&&!c){let g=e.startPosition.row+1,y=e.endPosition.row+1,h=Ac(a),w=i?`${h} [${i}]`:h;n===0?(l+=`\u{1F4C1} ROOT (Lines: ${g}-${y})
766
816
  `,u=o):(l+=`${o}${t?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 "}${w} (Lines: ${g}-${y})
767
817
  `,u+=t?" ":"\u2502 "),f=n+1,m=i}return f>r&&d.length>0?l+=`${u}\u2514\u2500\u2500 ... depth exceeded ...
768
- `:d.forEach((g,y)=>{let h=y===d.length-1;l+=Ba(g,f,c?t&&h:h,u,m,r)}),l}var Kr=async e=>{let n;try{n=D(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=yo.isAbsolute(n)?n:yo.resolve(process.cwd(),n);if(!zr.existsSync(t))return`ERROR: File not found: ${n}`;let o=yo.extname(t).slice(1).toLowerCase(),s=Oa[o];if(!s)return`ERROR: Unsupported file extension: .${o}`;let r=yo.resolve(co,s);if(!zr.existsSync(r))return`ERROR: Parser for .${o} not found. Please download it in Settings > Other.`;try{let a=Da.Parser;if(!La){let m;try{m=yo.join(yo.dirname(Pa.resolve("web-tree-sitter")),"tree-sitter.wasm")}catch{m=yo.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")?m:g}),La=!0}let i=new a,p=await Da.Language.load(r);i.setLanguage(p);let d=await zr.readFile(t,"utf8"),c=d.split(`
818
+ `:d.forEach((g,y)=>{let h=y===d.length-1;l+=Ba(g,f,c?t&&h:h,u,m,r)}),l}var Kr=async e=>{let n;try{n=L(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=wo.isAbsolute(n)?n:wo.resolve(process.cwd(),n);if(!zr.existsSync(t))return`ERROR: File not found: ${n}`;let o=wo.extname(t).slice(1).toLowerCase(),s=Oa[o];if(!s)return`ERROR: Unsupported file extension: .${o}`;let r=wo.resolve(fo,s);if(!zr.existsSync(r))return`ERROR: Parser for .${o} not found. Please download it in Settings > Other.`;try{let a=La.Parser;if(!Da){let m;try{m=wo.join(wo.dirname(Pa.resolve("web-tree-sitter")),"tree-sitter.wasm")}catch{m=wo.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")?m:g}),Da=!0}let i=new a,p=await La.Language.load(r);i.setLanguage(p);let d=await zr.readFile(t,"utf8"),c=d.split(`
769
819
  `).length,l=12;c>1e4?l=2:c>=8e3?l=3:c>=5e3?l=5:c>=4e3?l=8:c>2e3&&(l=10);let u=i.parse(d),f=Ba(u.rootNode,0,!0," ",null,l);return`\u{1F4C4} File Map for: ${n}
770
820
  ${f}`}catch(a){let i=a instanceof Error?a.message:typeof a=="object"?JSON.stringify(a):String(a),p=a instanceof Error?`
771
- Stack: ${a.stack}`:"";return`ERROR: Failed to map file: ${i}${p}`}};import Jn from"fs";import Wa from"path";var rs=async(e,n={})=>{let{method:t,tasks:o,markDone:s}=D(e),r=n.chatId||"default";if(!t)return'ERROR: Missing "method" argument for todo tool (create/append/get).';let a=Wa.join(Dn,"plan",r),i=Wa.join(a,"todo.md"),p=l=>{if(!l||Array.isArray(l))return l;let u=String(l).trim();if(u.startsWith("[")&&u.endsWith("]")){let f=u.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);return f?f.map(m=>m.slice(1,-1).replace(/\\(.)/g,"$1")):u.slice(1,-1).split(",").map(m=>m.trim()).filter(Boolean)}return l},d=l=>{let u=p(l);return u?(Array.isArray(u)?u:String(u).split(`
821
+ Stack: ${a.stack}`:"";return`ERROR: Failed to map file: ${i}${p}`}};import Qn from"fs";import Wa from"path";var is=async(e,n={})=>{let{method:t,tasks:o,markDone:s}=L(e),r=n.chatId||"default";if(!t)return'ERROR: Missing "method" argument for todo tool (create/append/get).';let a=Wa.join(Dn,"plan",r),i=Wa.join(a,"todo.md"),p=l=>{if(!l||Array.isArray(l))return l;let u=String(l).trim();if(u.startsWith("[")&&u.endsWith("]")){let f=u.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);return f?f.map(m=>m.slice(1,-1).replace(/\\(.)/g,"$1")):u.slice(1,-1).split(",").map(m=>m.trim()).filter(Boolean)}return l},d=l=>{let u=p(l);return u?(Array.isArray(u)?u:String(u).split(`
772
822
  `)).map(m=>{let g=String(m).trim();return g?g.startsWith("- [ ]")||g.startsWith("- [x]")||g.startsWith("- [X]")?g:`- [ ] ${g}`:null}).filter(Boolean).join(`
773
823
  `)+`
774
824
  `:""},c=(l,u)=>{if(!u)return{content:l,markedCount:0};let f=p(u),m=(Array.isArray(f)?f:[f]).map(w=>String(w).replace(/^- \[[xX ]\]\s*/i,"").trim()).filter(Boolean),g=l.split(`
775
825
  `),y=0,h=!1;for(let w of m){let x=!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]"),x=!0,h=!0,y++;break}if(!x){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]"),x=!0,h=!0,y++;break}}}return{content:h?g.join(`
776
- `):l,markedCount:y}};try{if(Jn.existsSync(a)||Jn.mkdirSync(a,{recursive:!0}),t==="create"){if(!o)return'ERROR: Missing "tasks" for create method.';let l=d(o),u=0;if(s){let m=c(l,s);l=m.content,u=m.markedCount}await ht.recordFileChange(i),Jn.writeFileSync(i,l,"utf8");let f=l.split(/\r?\n/).map(m=>m.trim()).filter(m=>m.startsWith("- [ ]")||m.startsWith("- [x]")||m.startsWith("- [X]")).length;if(u>0){let m=l.split(/\r?\n/).map(g=>g.trim()).filter(g=>g.startsWith("- [x]")||g.startsWith("- [X]")).length;return`SUCCESS: TASK LIST CREATED (${u} marked done, ${m} completed, ${f-m} left)
826
+ `):l,markedCount:y}};try{if(Qn.existsSync(a)||Qn.mkdirSync(a,{recursive:!0}),t==="create"){if(!o)return'ERROR: Missing "tasks" for create method.';let l=d(o),u=0;if(s){let m=c(l,s);l=m.content,u=m.markedCount}await ht.recordFileChange(i),Qn.writeFileSync(i,l,"utf8");let f=l.split(/\r?\n/).map(m=>m.trim()).filter(m=>m.startsWith("- [ ]")||m.startsWith("- [x]")||m.startsWith("- [X]")).length;if(u>0){let m=l.split(/\r?\n/).map(g=>g.trim()).filter(g=>g.startsWith("- [x]")||g.startsWith("- [X]")).length;return`SUCCESS: TASK LIST CREATED (${u} marked done, ${m} completed, ${f-m} left)
777
827
  ${l}`}return`SUCCESS: TASK LIST CREATED (${f} total)
778
- ${l}`}if(t==="append"){if(!o)return'ERROR: Missing "tasks" for append method.';let l=d(o);await ht.recordFileChange(i),Jn.appendFileSync(i,l,"utf8");let u=Jn.readFileSync(i,"utf8"),f=u.split(/\r?\n/).map(h=>h.trim()),m=f.filter(h=>h.startsWith("- [ ]")||h.startsWith("- [x]")||h.startsWith("- [X]")).length,g=f.filter(h=>h.startsWith("- [x]")||h.startsWith("- [X]")).length,y=l.split(/\r?\n/).map(h=>h.trim()).filter(h=>h.startsWith("- [ ]")||h.startsWith("- [x]")||h.startsWith("- [X]")).length;return`SUCCESS: TASK APPENDED (${g} completed, ${m-g} left, ${y} added)
779
- ${u}`}if(t==="get"){if(!Jn.existsSync(i))return"TODO GET: No task list found for this session.";let l=Jn.readFileSync(i,"utf8"),u=0;if(s){let h=c(l,s);h.markedCount>0&&(l=h.content,u=h.markedCount,await ht.recordFileChange(i),Jn.writeFileSync(i,l,"utf8"))}let f=l.split(/\r?\n/).map(h=>h.trim()),m=f.filter(h=>h.startsWith("- [ ]")||h.startsWith("- [x]")||h.startsWith("- [X]")).length,g=f.filter(h=>h.startsWith("- [x]")||h.startsWith("- [X]")).length;return`${u>0?`SUCCESS: ${u} TASK(S) MARKED DONE`:"TODO GET"}: ${g} Completed, ${m-g} left
780
- ${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 Yr=async(e,n={})=>{let{runSubagent:t}=await import("./ai-J235Y6SO.js"),o=D(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]
781
- `),d}catch(d){let{isTerminationSignaled:c}=await import("./ai-J235Y6SO.js"),l=d.message==="Subagent task was cancelled by user."||c();if(n.onVisualFeedback){let u=l?"[CANCELLED]":"[FAILED]";n.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${p} ${u}
782
- `)}return`ERROR: Subagent execution failed: ${d.message}`}};var ja=async(e,n={})=>{let{runSubagent:t}=await import("./ai-J235Y6SO.js"),o=D(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 h=i.trim();h.startsWith("[")&&h.endsWith("]")&&(h=h.substring(1,h.length-1)),p=h.split(",").map(w=>w.trim().replace(/^["']|["']$/g,"")).filter(Boolean)}catch{}let d=`subagent-${Date.now()}-${Math.floor(Math.random()*1e3)}`,c=null,l=null,u=new Promise((h,w)=>{c=h,l=w}),f={id:d,title:a||s.substring(0,30),task:s,status:"running",startedAt:Date.now(),lastChunkTime:Date.now(),wps:0,questions:[],pendingSteerMessages:[],steer:h=>{h&&f.pendingSteerMessages.push(h)},completionPromise:u,_resolveCompletion:c,_rejectCompletion:l,progress:[]},m={chunks:[],totalWords:0};Xe.push(f),n.onSubagentUpdate&&n.onSubagentUpdate();let g=[],y={...n,taskId:d,onAskMain:async h=>{let w=`q-${Date.now()}-${Math.floor(Math.random()*1e3)}`,x=null,T=new Promise(S=>{x=S}),_={id:w,question:h,answered:!1,answer:null,askedAt:Date.now(),_resolve:x};return f.questions.push(_),f.status="waiting",n.onSubagentUpdate&&n.onSubagentUpdate(),Rs(`[SYSTEM] Background subagent "${f.title}" is WAITING FOR YOUR INPUT: "${h}"
828
+ ${l}`}if(t==="append"){if(!o)return'ERROR: Missing "tasks" for append method.';let l=d(o);await ht.recordFileChange(i),Qn.appendFileSync(i,l,"utf8");let u=Qn.readFileSync(i,"utf8"),f=u.split(/\r?\n/).map(h=>h.trim()),m=f.filter(h=>h.startsWith("- [ ]")||h.startsWith("- [x]")||h.startsWith("- [X]")).length,g=f.filter(h=>h.startsWith("- [x]")||h.startsWith("- [X]")).length,y=l.split(/\r?\n/).map(h=>h.trim()).filter(h=>h.startsWith("- [ ]")||h.startsWith("- [x]")||h.startsWith("- [X]")).length;return`SUCCESS: TASK APPENDED (${g} completed, ${m-g} left, ${y} added)
829
+ ${u}`}if(t==="get"){if(!Qn.existsSync(i))return"TODO GET: No task list found for this session.";let l=Qn.readFileSync(i,"utf8"),u=0;if(s){let h=c(l,s);h.markedCount>0&&(l=h.content,u=h.markedCount,await ht.recordFileChange(i),Qn.writeFileSync(i,l,"utf8"))}let f=l.split(/\r?\n/).map(h=>h.trim()),m=f.filter(h=>h.startsWith("- [ ]")||h.startsWith("- [x]")||h.startsWith("- [X]")).length,g=f.filter(h=>h.startsWith("- [x]")||h.startsWith("- [X]")).length;return`${u>0?`SUCCESS: ${u} TASK(S) MARKED DONE`:"TODO GET"}: ${g} Completed, ${m-g} left
830
+ ${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 Yr=async(e,n={})=>{let{runSubagent:t}=await import("./ai-3PF5H72T.js"),o=L(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]
831
+ `),d}catch(d){let{isTerminationSignaled:c}=await import("./ai-3PF5H72T.js"),l=d.message==="Subagent task was cancelled by user."||c();if(n.onVisualFeedback){let u=l?"[CANCELLED]":"[FAILED]";n.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${p} ${u}
832
+ `)}return`ERROR: Subagent execution failed: ${d.message}`}};var ja=async(e,n={})=>{let{runSubagent:t}=await import("./ai-3PF5H72T.js"),o=L(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 h=i.trim();h.startsWith("[")&&h.endsWith("]")&&(h=h.substring(1,h.length-1)),p=h.split(",").map(w=>w.trim().replace(/^["']|["']$/g,"")).filter(Boolean)}catch{}let d=`subagent-${Date.now()}-${Math.floor(Math.random()*1e3)}`,c=null,l=null,u=new Promise((h,w)=>{c=h,l=w}),f={id:d,title:a||s.substring(0,30),task:s,status:"running",startedAt:Date.now(),lastChunkTime:Date.now(),wps:0,questions:[],pendingSteerMessages:[],steer:h=>{h&&f.pendingSteerMessages.push(h)},completionPromise:u,_resolveCompletion:c,_rejectCompletion:l,progress:[]},m={chunks:[],totalWords:0};Xe.push(f),n.onSubagentUpdate&&n.onSubagentUpdate();let g=[],y={...n,taskId:d,onAskMain:async h=>{let w=`q-${Date.now()}-${Math.floor(Math.random()*1e3)}`,x=null,T=new Promise(S=>{x=S}),_={id:w,question:h,answered:!1,answer:null,askedAt:Date.now(),_resolve:x};return f.questions.push(_),f.status="waiting",n.onSubagentUpdate&&n.onSubagentUpdate(),Rs(`[SYSTEM] Background subagent "${f.title}" is WAITING FOR YOUR INPUT: "${h}"
783
833
  Respond using tool: [tool:functions.Answer(id="${d}", answer="...")]
784
834
  [/SYSTEM]`),await T},onVisualFeedback:h=>{f.lastChunkTime=Date.now();let w=h.replace(/\x1b\[[0-9;]*m/g,""),x=w.match(/[✔✘✗✖🔍📖→➕↻•]\s*([A-Za-z0-9\s-]+)/);x?f.currentTool=x[1].trim():f.currentTool=w,n.onSubagentUpdate&&n.onSubagentUpdate()},onTokenChunk:(h,w)=>{let x=Date.now();if(f.lastChunkTime=x,f.currentTool="Thinking",typeof w=="number"&&w>0){m.totalWords+=w,m.chunks.push({time:x,words:w});let T=x-400;if(m.chunks=m.chunks.filter(_=>_.time>=T),m.chunks.length>0){let _=m.chunks.reduce((k,C)=>k+C.words,0),R=m.chunks[0].time,S=Math.max(.4,(x-R)/1e3);f.wps=Math.round(_/S*10)/10}}n.onSubagentUpdate&&n.onSubagentUpdate()}};return t(s,y,r,p,50,h=>{if(f.status==="cancelled")return;if(h.startsWith("[Subagent Turn")&&g.length>0&&(f.progress.push([...g]),g=[]),h.includes("[Executing Tool]")){let x=h.match(/\[Executing Tool\]\s*([a-zA-Z0-9_]+)/);x&&(!f.currentTool||f.currentTool==="Thinking")&&(f.currentTool=x[1])}let w=h;if(w.startsWith("[Tool Result]")){let x=w.split(`
785
835
  `);x.length>5&&(w=x.slice(0,4).join(`
786
836
  `)+`
787
- ... [Content/Diff Truncated from Logs] ...`)}g.push(w),n.onSubagentUpdate&&n.onSubagentUpdate()},!0).then(h=>{if(f.status==="cancelled"){f._resolveCompletion&&f._resolveCompletion(h);return}g.length>0&&(f.progress.push([...g]),g=[]),f.status="completed",f.finalAnswer=h,n.onSubagentUpdate&&n.onSubagentUpdate(),Rs(`[SYSTEM] Background subagent "${f.title}" (id: ${d}) has FINISHED. Call GetProgress(id="${d}") to see the final result. [/SYSTEM]`),f._resolveCompletion&&f._resolveCompletion(h)}).catch(async h=>{let{isTerminationSignaled:w}=await import("./ai-J235Y6SO.js");if(h.message==="Subagent task was cancelled."||f.status==="cancelled"||w()){f.status="cancelled",g.push("[SUBAGENT CANCELLED] Task was cancelled."),f.progress.push([...g]),n.onSubagentUpdate&&n.onSubagentUpdate(),f._resolveCompletion&&f._resolveCompletion(null);return}g.push(`[SUBAGENT FAILURE] Error: ${h.message}`),f.progress.push([...g]),f.status="failed",f.error=h.message,n.onSubagentUpdate&&n.onSubagentUpdate(),Rs(`[SYSTEM] Background subagent "${f.title}" (id: ${d}) FAILED with error: ${h.message}. [/SYSTEM]`),f._rejectCompletion&&f._rejectCompletion(h)}),`SUCCESS: Background subagent started. Task ID: ${d}`};var Vr=async(e,n={})=>{let o=D(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()}
837
+ ... [Content/Diff Truncated from Logs] ...`)}g.push(w),n.onSubagentUpdate&&n.onSubagentUpdate()},!0).then(h=>{if(f.status==="cancelled"){f._resolveCompletion&&f._resolveCompletion(h);return}g.length>0&&(f.progress.push([...g]),g=[]),f.status="completed",f.finalAnswer=h,n.onSubagentUpdate&&n.onSubagentUpdate(),Rs(`[SYSTEM] Background subagent "${f.title}" (id: ${d}) has FINISHED. Call GetProgress(id="${d}") to see the final result. [/SYSTEM]`),f._resolveCompletion&&f._resolveCompletion(h)}).catch(async h=>{let{isTerminationSignaled:w}=await import("./ai-3PF5H72T.js");if(h.message==="Subagent task was cancelled."||f.status==="cancelled"||w()){f.status="cancelled",g.push("[SUBAGENT CANCELLED] Task was cancelled."),f.progress.push([...g]),n.onSubagentUpdate&&n.onSubagentUpdate(),f._resolveCompletion&&f._resolveCompletion(null);return}g.push(`[SUBAGENT FAILURE] Error: ${h.message}`),f.progress.push([...g]),f.status="failed",f.error=h.message,n.onSubagentUpdate&&n.onSubagentUpdate(),Rs(`[SYSTEM] Background subagent "${f.title}" (id: ${d}) FAILED with error: ${h.message}. [/SYSTEM]`),f._rejectCompletion&&f._rejectCompletion(h)}),`SUCCESS: Background subagent started. Task ID: ${d}`};var Vr=async(e,n={})=>{let o=L(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()}
788
838
  `;if(r+=`Title: ${s.title}
789
839
  `,r+=`Task: ${s.task}
790
840
  `,s.startedAt){let i=Math.floor((Date.now()-s.startedAt)/1e3);r+=`Elapsed Time: ${i}s
@@ -809,7 +859,7 @@ ${s.finalAnswer}
809
859
  `),r.replace(/\r\n/g,`
810
860
  `).replace(/\n{3,}/g,`
811
861
 
812
- `).trim().replace(/\[TOOL RESULT\]/gi,"TOOL RESULT:")};var Ga=async(e,n={})=>{let o=D(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 xt from"fs-extra";import Tt from"path";var Mc=["node_modules","dist","bin","logs",".git",".fluxflow","secret",".gemini",".agents","tmp","temp","build","out","snapshots"];async function is(e,n=e){let t={},o=await xt.readdir(e,{withFileTypes:!0}).catch(()=>[]);for(let s of o){if(Mc.includes(s.name))continue;let r=Tt.join(e,s.name),a=Tt.relative(n,r).replace(/\\/g,"/");if(s.isDirectory()){let i=await is(r,n);Object.assign(t,i)}else{let i=await xt.stat(r).catch(()=>null);i&&(t[a]={size:i.size,mtime:i.mtimeMs})}}return t}async function Ha(e,n){await xt.ensureDir(e);for(let t of Object.keys(n)){let o=Tt.join(process.cwd(),t),s=Tt.join(e,t);await xt.ensureDir(Tt.dirname(s)),await xt.copyFile(o,s).catch(()=>{})}}async function Xr(e,n,t=null,o=null){if(!await xt.pathExists(e))return;o||(o=e);let s=await xt.readdir(e,{withFileTypes:!0}).catch(()=>[]);for(let r of s){let a=Tt.join(e,r.name),i=Tt.join(n,r.name);if(r.isDirectory())await Xr(a,i,t,o);else{let p=Tt.relative(o,a).replace(/\\/g,"/"),d=await xt.pathExists(i);d&&await xt.chmod(i,438).catch(()=>{}),await xt.ensureDir(Tt.dirname(i));let c=await xt.copyFile(a,i).then(()=>!0).catch(()=>!1);await xt.chmod(i,438).catch(()=>{}),t&&(c?d?t.replaced++:t.restored++:t.failed.push(p))}}}var Qn={async takeInitialSnapshot(e){try{let n=Tt.join(Dn,"snapshots",e);await xt.remove(n).catch(()=>{}),await xt.ensureDir(n);let t=await is(process.cwd());await Ha(Tt.join(n,"initial"),t);let o=oe(hn,{});o[e]={initialManifest:t,currentManifest:t,checkpoints:[{id:"initial",timestamp:new Date().toISOString(),newFiles:[],modifiedFiles:[],deletedFiles:[],toolsUsed:[]}]},pe(hn,o)}catch{}},async recordTurnDelta(e,n,t=[]){try{let o=oe(hn,{}),s=o[e];if(!s)return;let r=s.currentManifest||s.initialManifest,a=await is(process.cwd()),i=[],p=[],d=[];for(let[l,u]of Object.entries(a)){let f=r[l];f?(f.size!==u.size||f.mtime!==u.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 f of c)l[f]=a[f];let u=Tt.join(Dn,"snapshots",e,`turn_${n}`);await Ha(u,l)}s.checkpoints.push({id:`turn_${n}`,timestamp:new Date().toISOString(),newFiles:i,modifiedFiles:p,deletedFiles:d,toolsUsed:t}),s.currentManifest=a,pe(hn,o)}catch{}},async getCheckpoints(e){try{let t=oe(hn,{})[e];return t?t.checkpoints||[]:[]}catch{return[]}},async rollbackToCheckpoint(e,n){try{let t=oe(hn,{}),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(Dn,"snapshots",e),i={restored:0,replaced:0,failed:[]},p=await is(process.cwd());for(let c of Object.keys(p)){let l=Tt.join(process.cwd(),c);await xt.chmod(l,438).catch(()=>{}),await xt.remove(l).catch(()=>{})}let d=Tt.join(a,"initial");await Xr(d,process.cwd(),i,d);for(let c=1;c<=r;c++){let l=s[c],u=Tt.join(a,l.id);if(await Xr(u,process.cwd(),i,u),l.deletedFiles&&l.deletedFiles.length>0)for(let f of l.deletedFiles){let m=Tt.join(process.cwd(),f);await xt.chmod(m,438).catch(()=>{}),await xt.remove(m).catch(()=>{})}}return o.checkpoints=s.slice(0,r+1),o.currentManifest=await is(process.cwd()),pe(hn,t),{checkpointId:n,stats:i}}catch(t){throw new Error(`Rollback failed: ${t.message}`)}},async getLatestFileChanges(e){try{let t=oe(hn,{})[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(Dn,"snapshots",e);await xt.remove(n).catch(()=>{});let t=oe(hn,{});t[e]&&(delete t[e],pe(hn,t))}catch{}}};var Jr=async(e,n={})=>{let t=D(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 Qn.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:"AskUser",ask_user:"AskUser",AskUser:"AskUser",askuser:"AskUser",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:
862
+ `).trim().replace(/\[TOOL RESULT\]/gi,"TOOL RESULT:")};var Ga=async(e,n={})=>{let o=L(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 xt from"fs-extra";import Rt from"path";var Mc=["node_modules","dist","bin","logs",".git",".fluxflow","secret",".gemini",".agents","tmp","temp","build","out","snapshots"];async function as(e,n=e){let t={},o=await xt.readdir(e,{withFileTypes:!0}).catch(()=>[]);for(let s of o){if(Mc.includes(s.name))continue;let r=Rt.join(e,s.name),a=Rt.relative(n,r).replace(/\\/g,"/");if(s.isDirectory()){let i=await as(r,n);Object.assign(t,i)}else{let i=await xt.stat(r).catch(()=>null);i&&(t[a]={size:i.size,mtime:i.mtimeMs})}}return t}async function Ha(e,n){await xt.ensureDir(e);for(let t of Object.keys(n)){let o=Rt.join(process.cwd(),t),s=Rt.join(e,t);await xt.ensureDir(Rt.dirname(s)),await xt.copyFile(o,s).catch(()=>{})}}async function Xr(e,n,t=null,o=null){if(!await xt.pathExists(e))return;o||(o=e);let s=await xt.readdir(e,{withFileTypes:!0}).catch(()=>[]);for(let r of s){let a=Rt.join(e,r.name),i=Rt.join(n,r.name);if(r.isDirectory())await Xr(a,i,t,o);else{let p=Rt.relative(o,a).replace(/\\/g,"/"),d=await xt.pathExists(i);d&&await xt.chmod(i,438).catch(()=>{}),await xt.ensureDir(Rt.dirname(i));let c=await xt.copyFile(a,i).then(()=>!0).catch(()=>!1);await xt.chmod(i,438).catch(()=>{}),t&&(c?d?t.replaced++:t.restored++:t.failed.push(p))}}}var Zn={async takeInitialSnapshot(e){try{let n=Rt.join(Dn,"snapshots",e);await xt.remove(n).catch(()=>{}),await xt.ensureDir(n);let t=await as(process.cwd());await Ha(Rt.join(n,"initial"),t);let o=oe(gn,{});o[e]={initialManifest:t,currentManifest:t,checkpoints:[{id:"initial",timestamp:new Date().toISOString(),newFiles:[],modifiedFiles:[],deletedFiles:[],toolsUsed:[]}]},pe(gn,o)}catch{}},async recordTurnDelta(e,n,t=[]){try{let o=oe(gn,{}),s=o[e];if(!s)return;let r=s.currentManifest||s.initialManifest,a=await as(process.cwd()),i=[],p=[],d=[];for(let[l,u]of Object.entries(a)){let f=r[l];f?(f.size!==u.size||f.mtime!==u.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 f of c)l[f]=a[f];let u=Rt.join(Dn,"snapshots",e,`turn_${n}`);await Ha(u,l)}s.checkpoints.push({id:`turn_${n}`,timestamp:new Date().toISOString(),newFiles:i,modifiedFiles:p,deletedFiles:d,toolsUsed:t}),s.currentManifest=a,pe(gn,o)}catch{}},async getCheckpoints(e){try{let t=oe(gn,{})[e];return t?t.checkpoints||[]:[]}catch{return[]}},async rollbackToCheckpoint(e,n){try{let t=oe(gn,{}),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=Rt.join(Dn,"snapshots",e),i={restored:0,replaced:0,failed:[]},p=await as(process.cwd());for(let c of Object.keys(p)){let l=Rt.join(process.cwd(),c);await xt.chmod(l,438).catch(()=>{}),await xt.remove(l).catch(()=>{})}let d=Rt.join(a,"initial");await Xr(d,process.cwd(),i,d);for(let c=1;c<=r;c++){let l=s[c],u=Rt.join(a,l.id);if(await Xr(u,process.cwd(),i,u),l.deletedFiles&&l.deletedFiles.length>0)for(let f of l.deletedFiles){let m=Rt.join(process.cwd(),f);await xt.chmod(m,438).catch(()=>{}),await xt.remove(m).catch(()=>{})}}return o.checkpoints=s.slice(0,r+1),o.currentManifest=await as(process.cwd()),pe(gn,t),{checkpointId:n,stats:i}}catch(t){throw new Error(`Rollback failed: ${t.message}`)}},async getLatestFileChanges(e){try{let t=oe(gn,{})[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=Rt.join(Dn,"snapshots",e);await xt.remove(n).catch(()=>{});let t=oe(gn,{});t[e]&&(delete t[e],pe(gn,t))}catch{}}};var Jr=async(e,n={})=>{let t=L(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 Zn.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:"AskUser",ask_user:"AskUser",AskUser:"AskUser",askuser:"AskUser",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:
813
863
 
814
864
  `;for(let l of i)if(l.id==="initial")c+=`--- Initial State (id: initial) ---
815
865
  Tools Used: User Prompted for task
@@ -817,7 +867,7 @@ Tools Used: User Prompted for task
817
867
  `;else{let u=l.id.replace("turn_",""),f=l.toolsUsed&&l.toolsUsed.length>0?l.toolsUsed.map(d).join(", "):"None";c+=`--- Turn ${u} (id: ${l.id}) ---
818
868
  Tools Used: ${f}
819
869
 
820
- `}return c.trim()}else if(o==="forceRevert"){if(!s)return"ERROR: Missing required parameter 'id' for forceRevert.";try{let i=await Qn.rollbackToCheckpoint(r,s),{checkpointId:p,stats:d}=i,c=d.restored+d.replaced+d.failed.length,l=`SUCCESS: Repository rolled back to checkpoint [${p}].
870
+ `}return c.trim()}else if(o==="forceRevert"){if(!s)return"ERROR: Missing required parameter 'id' for forceRevert.";try{let i=await Zn.rollbackToCheckpoint(r,s),{checkpointId:p,stats:d}=i,c=d.restored+d.replaced+d.failed.length,l=`SUCCESS: Repository rolled back to checkpoint [${p}].
821
871
 
822
872
  `;return l+=`Stats:
823
873
  `,l+=` Restored : ${d.restored} file${d.restored!==1?"s":""} (new to workspace)
@@ -826,14 +876,14 @@ Tools Used: ${f}
826
876
  ${d.failed.join(`
827
877
  `)}`),l+=`
828
878
  \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500-
829
- `,l+=` Total : ${c} file${c!==1?"s":""} processed`,l}catch(i){return`ERROR: ${i.message}`}}else return`ERROR: Invalid method "${o}". Use "getCheckpoint" or "forceRevert".`};var Fo=async(e,n={})=>{let t=D(e),o=t.id,s=parseInt(t.timeout||t.time||"120",10);if((isNaN(s)||s<=0)&&(s=120),s>300&&(s=300),!o)return t.time?(await new Promise(p=>setTimeout(p,s*1e3)),`SUCCESS: Waited for ${s}s.`):'ERROR: Missing "id" argument for Await.';let r=Xe.find(p=>p.id===o);if(!r)return`ERROR: Subagent task with ID [${o}] not found.`;if(r.status==="completed")return`SUCCESS: Subagent task [${o}] completed.
879
+ `,l+=` Total : ${c} file${c!==1?"s":""} processed`,l}catch(i){return`ERROR: ${i.message}`}}else return`ERROR: Invalid method "${o}". Use "getCheckpoint" or "forceRevert".`};var No=async(e,n={})=>{let t=L(e),o=t.id,s=parseInt(t.timeout||t.time||"120",10);if((isNaN(s)||s<=0)&&(s=120),s>300&&(s=300),!o)return t.time?(await new Promise(p=>setTimeout(p,s*1e3)),`SUCCESS: Waited for ${s}s.`):'ERROR: Missing "id" argument for Await.';let r=Xe.find(p=>p.id===o);if(!r)return`ERROR: Subagent task with ID [${o}] not found.`;if(r.status==="completed")return`SUCCESS: Subagent task [${o}] completed.
830
880
  Final Answer:
831
881
  ${r.finalAnswer||"(No output)"}`;if(r.status==="failed")return`ERROR: Subagent task [${o}] failed.
832
882
  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.
833
883
  Final Answer:
834
884
  ${r.finalAnswer||"(No output)"}`:r.status==="failed"?`ERROR: Subagent task [${o}] failed.
835
- 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 No=async(e,n={})=>{let t=D(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 as=async(e,n={})=>{let t=D(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 dn,keyboard as Ft,Button as ls,Key as L,Point as cs,clipboard as vc}from"@nut-tree-fork/nut-js";dn.config.autoDelayMs=50;Ft.config.autoDelayMs=50;async function Qr(){try{await Ft.releaseKey(L.LeftControl,L.RightControl,L.LeftAlt,L.RightAlt,L.LeftShift,L.RightShift,L.LeftSuper,L.RightSuper)}catch{}}async function Fn(e,n,t={}){let o=await Ko(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 dn.setPosition(new cs(o.x,o.y)),`SUCCESS: Moved mouse to grid target ${typeof n=="string"?n:`(${o.x}, ${o.y})`}`;case"click":{await dn.setPosition(new cs(o.x,o.y));let s=t.button==="right"?ls.RIGHT:t.button==="middle"?ls.MIDDLE:ls.LEFT;return t.clickType==="double"?await dn.doubleClick(s):await dn.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 Ko(t.from||n),r=await Ko(t.to);return!s||!r?'ERROR: Drag requires valid "from" and "to" target coordinates/grid codes.':(await dn.setPosition(new cs(s.x,s.y)),await dn.pressButton(ls.LEFT),await dn.setPosition(new cs(r.x,r.y)),await dn.releaseButton(ls.LEFT),`SUCCESS: Dragged mouse from (${s.x}, ${s.y}) to (${r.x}, ${r.y})`)}case"scroll":{let s=o||await Ko({x:640,y:360});s&&(await dn.setPosition(new cs(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 dn.scrollUp(120):await dn.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 qa={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},za=e=>{if(!e)return;let n=String(e).toLowerCase().trim();if(qa[n]!==void 0)return qa[n];if(L[e]!==void 0)return L[e];if(L[n.toUpperCase()]!==void 0)return L[n.toUpperCase()]};async function Nn(e,n,t={}){try{switch(e.toLowerCase()){case"type":{if(typeof n!="string")return"ERROR: Type action requires a valid string input";await Qr(),await vc.setContent(n);let s=process.platform==="darwin"?L.LeftSuper:L.LeftControl;return await Ft.pressKey(s,L.V),await Ft.releaseKey(s,L.V),await Qr(),t.autoPressEnter?(await new Promise(r=>setTimeout(r,50)),await Ft.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=za(n);return o===void 0?`ERROR: Unknown key name "${n}"`:(await Ft.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=>za(s)).filter(s=>s!==void 0);return o.length===0?"ERROR: Invalid key combination":(await Ft.pressKey(...o),await Ft.releaseKey(...o),`SUCCESS: Executed key combination [${n.join(" + ")}]`)}case"clear_input":return await Ft.pressKey(L.LeftControl,L.A),await Ft.releaseKey(L.LeftControl,L.A),await Ft.type(L.Backspace),"SUCCESS: Cleared active text input (Select All + Backspace)";case"browser_back":{let o=process.platform==="darwin";return o?(await Ft.pressKey(L.LeftSuper,L.Left),await Ft.releaseKey(L.LeftSuper,L.Left)):(await Ft.pressKey(L.LeftAlt,L.Left),await Ft.releaseKey(L.LeftAlt,L.Left)),await Qr(),`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 ds=async(e,n={})=>{let t=D(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 Fn(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 Nn(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 Xa from"screenshot-desktop";import us from"sharp";import Ka from"fs-extra";import Ya from"path";import"@nut-tree-fork/nut-js";async function Zr(e,n,t){if(!(!process.env.SHOW_DEBUG_GRID&&!process.env.DEBUG_OCR))try{let o=Ya.resolve(process.cwd(),"screenshots",e);await Ka.ensureDir(o),await Ka.writeFile(Ya.join(o,n),t)}catch{}}function Ic(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Oc(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 Dc(e){return e<=4?0:e<=8?1:2}async function ei(e,n=3){let t=await us(e).metadata();return us(e).resize(Math.round(t.width*n),Math.round(t.height*n),{kernel:"lanczos3"}).greyscale().normalise().toBuffer()}function Lc(e){if(!e)return{words:[],lines:[]};let n=[],t=new Map;for(let s of e.split(`
836
- `)){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]),u=parseInt(r[8]),f=parseInt(r[9]),m=parseFloat(r[10]),g=r.slice(11).join(" ").trim();if(!g||m<0)continue;let y={x0:c,y0:l,x1:c+u,y1:l+f},h={text:g,confidence:m,bbox:y};n.push(h);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 x=t.get(w);x.words.push(h),x.bbox.x0=Math.min(x.bbox.x0,y.x0),x.bbox.y0=Math.min(x.bbox.y0,y.y0),x.bbox.x1=Math.max(x.bbox.x1,y.x1),x.bbox.y1=Math.max(x.bbox.y1,y.y1)}let o=[];for(let s of t.values())s.words.length>0&&o.push({text:s.words.map(r=>r.text).join(" "),bbox:s.bbox,words:s.words});return{words:n,lines:o}}function Pc(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=Lc(e.tsv);e.words=n.words,e.lines=n.lines}}}function ti(e,n,t=0,o=0,s=1){Pc(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${Ic(n)}\\b`,"i").test(p)))continue;let c=i.words||(e.words?e.words.filter(m=>m.bbox&&m.bbox.x0>=i.bbox.x0-5&&m.bbox.x1<=i.bbox.x1+5&&m.bbox.y0>=i.bbox.y0-5&&m.bbox.y1<=i.bbox.y1+5):[]),l=n.split(/\s+/),u=l.map(m=>m.replace(/[^a-z0-9]/g,"")).join(" "),f=!1;if(c.length>0)for(let m=0;m<=c.length-l.length;m++){let g=c.slice(m,m+l.length),y=g.map(h=>(h.text||"").toLowerCase().trim().replace(/[^a-z0-9]/g,"")).join(" ");if(y===u||y.includes(u)){let h={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(h)),f=!0}}f||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=Dc(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&&Oc(d,n,i)<=i&&p.bbox&&a.push(r(p.bbox))}}return a}function ni(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 Fc(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,u=d*i,f=Math.min(a,e-l),m=Math.min(i,n-u),g=l+f/2,y=u+m/2,h=t>=l&&t<l+f&&o>=u&&o<u+m;p.push({x0:l,y0:u,w:f,h:m,cx:g,cy:y,containsTarget:h})}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),u=Math.hypot(c.cx-t,c.cy-o);return l-u})}var Fs=null;async function Nc(){return Fs||(Fs=(async()=>{let{createWorker:e}=await import("tesseract.js"),n=await import("fs-extra"),{CU_CACHE_DIR:t}=await import("./paths-CHZDSDRF.js");return n.ensureDirSync(t),e("eng",1,{cachePath:t,logger:()=>{}})})().catch(e=>{throw Fs=null,e})),Fs}var fs=null,Va=null;async function Uc(){let{getActiveDisplay:e}=await import("./screen_grid-WWZV4QEB.js"),n=await e();if(fs&&Va===n)return fs;Va=n,fs={format:"png"};try{let t=await Xa.listDisplays();t&&t.length>0&&(fs={format:"png",screen:(t[n]||t[0]).id})}catch{}return fs}var oi=async(e,n={})=>{let t=!!(process.env.SHOW_DEBUG_GRID||process.env.DEBUG_OCR||process.env.VERBOSE),o=performance.now(),s=o,r=f=>{if(!t)return;let m=performance.now(),g=(m-s).toFixed(0),y=(m-o).toFixed(0);console.log(`[Click Perf] +${g}ms (${y}ms total) -> ${f}`),s=m};r("Starting click()");let a=D(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 f=i?Fi(i):null;r("Getting display options");let m=await Uc();r("Taking desktop screenshot");let g=await Xa(m);r("Getting image metadata");let y=await us(g).metadata(),h=y.width||1920,w=y.height||1080,x=f?{x:Math.round(f.x*(h/1280)),y:Math.round(f.y*(w/720))}:{x:h/2,y:w/2},T=c.toLowerCase().trim();r("Acquiring OCR worker");let _=await Nc(),R=null,S="",k=f?220:500;if(f){r("Pass 1: Cropping target crop (3x zoom window, 2x upscale)");let C=Math.min(Math.round(h/3),h),E=Math.min(Math.round(w/3),w),b=Math.max(0,Math.min(h-C,x.x-Math.floor(C/2))),$=Math.max(0,Math.min(w-E,x.y-Math.floor(E/2))),I=await us(g).extract({left:b,top:$,width:C,height:E}).toBuffer(),O=2,P=await ei(I,O),W=T.replace(/[^a-z0-9]/g,"_");await Zr("cropped",`crop_${Date.now()}_${W}.png`,P),r("Pass 1: Running Tesseract OCR recognize on crop (PSM 11 - Sparse Text)"),await _.setParameters({tessedit_pageseg_mode:"11"});let{data:q}=await _.recognize(P,{},{tsv:!0,blocks:!0});if(r("Pass 1: OCR recognition finished, extracting matches"),q&&q.text){t&&console.log(`[Pass 1 OCR Read]: "${q.text.trim().replace(/\s+/g," ")}"`);let Q=ti(q,T,b,$,O);if(Q.length>0){let V=ni(Q,x);V&&(V.containsPoint||V.dist<=k)&&(R=V,S="centered target crop OCR")}}}if(!R){r("Pass 2: Entering Full-Screen OCR (broad scan, PSM 3 - Auto)");let C=await ei(g,2),E=T.replace(/[^a-z0-9]/g,"_");await Zr("fullscreen",`full_${Date.now()}_${E}.png`,C),r("Pass 2: Running Tesseract on full screen"),await _.setParameters({tessedit_pageseg_mode:"3"});let{data:b}=await _.recognize(C,{},{tsv:!0,blocks:!0});if(r("Pass 2: Full-screen OCR finished"),b&&b.text){let $=ti(b,T,0,0,2);if($.length>0){let I=ni($,x);I&&(R=I,S="full-screen OCR")}}}if(!R){r("Pass 3: Entering Tiled OCR fallback (high-res 3x)");let C=Fc(h,w,x.x,x.y),E=T.replace(/[^a-z0-9]/g,"_");await _.setParameters({tessedit_pageseg_mode:"11"});for(let b=0;b<C.length;b++){let $=C[b];r(`Pass 3: Preprocessing tile ${b+1}/${C.length}`);let I=await us(g).extract({left:$.x0,top:$.y0,width:$.w,height:$.h}).toBuffer(),O=await ei(I,3);await Zr("tiles",`tile_${b+1}_${Date.now()}_${E}.png`,O),r(`Pass 3: Running Tesseract on tile ${b+1}`);let{data:P}=await _.recognize(O,{},{tsv:!0,blocks:!0});if(!P||!P.text)continue;let W=ti(P,T,$.x0,$.y0,3);if(W.length>0){let q=ni(W,x);if(q){R=q,S=`tile ${b+1} OCR (${$.containsTarget?"target tile":`offset ${$.x0},${$.y0}`})`;break}}}}if(R){let C={x:Math.round(R.x*(1280/h)),y:Math.round(R.y*(720/w))};r(`Executing mouse click on matched target (${S})`);let E=await Fn("click",C,{button:d,clickType:p});return r("Click completed successfully"),`${E} (${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(f){t&&console.error("[OCR Error]",f)}r(`Executing mouse click on fallback gridId: ${l}`);let u=await Fn("click",l,{button:d,clickType:p});return r("Fallback click completed"),u};var si=async(e,n={})=>{let t=D(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 Fn("drag",o,{from:o,to:s})};var ri=async(e,n={})=>{let t=D(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 Fn("scroll",r,{direction:o,amount:s})};var Ns=async(e,n={})=>{let t=D(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 Nn("type",String(o),{autoPressEnter:s})};var Us=async(e,n={})=>{let t=D(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 Nn("clear_input");if(s==="back"||s==="browser_back"||s==="browserBack")return await Nn("browser_back");if(s.includes(";")||s.includes("+")){let r=s.split(/[;+]/).map(a=>a.trim()).filter(Boolean);return await Nn("key_combination",r)}return await Nn("key_press",s)};var Bs=async(e,n={})=>"SUCCESS: Screen recapture requested. The latest gridded screenshot is provided for your next decision.";var Bc={web_search:$r,web_scrape:Ar,memory:Mr,chat:vr,view_file:es,write_file:Ir,update_file:Pr,exec_command:hr,read_folder:Nr,write_pdf:Ur,write_docx:Wr,search_keyword:os,generate_image:Hr,saveSummary:ss,addMemScore:Po,file_map:Kr,todo:rs,Todo:rs,goal:rs,Goal:rs,invokeSync:Yr,invoke:ja,getProgress:Vr,cancel:Ga,awaitSubagent:Fo,answerSubagent:No,steerSubagent:as,computer_action:ds,computer_use:ds,ComputerAction:ds,ComputerUse:ds,click:oi,Click:oi,drag:si,Drag:si,scroll:ri,Scroll:ri,keyboard_typing:Ns,KeyboardTyping:Ns,keyboardtyping:Ns,key_press:Us,KeyPress:Us,keypress:Us,recapture_screen:Bs,RecaptureScreen:Bs,recapturescreen:Bs,invoke_sync:Yr,get_progress:Vr,await_subagent:Fo,answer_subagent:No,steer_subagent:as,steer:as,Steer:as,ask:Ps,Ask:Ps,AskUser:Ps,WebSearch:$r,WebScrape:Ar,ReadFile:es,ReadFolder:Nr,WriteFile:Ir,PatchFile:Pr,WritePDF:Ur,WriteDoc:Wr,Run:hr,SearchKeyword:os,CodeSearch:os,code_search:os,Memory:Mr,Chat:vr,GenerateImage:Hr,saveSumary:ss,SaveSummary:ss,SaveSumary:ss,add_mem_score:Po,AddMemScore:Po,addMemoryScore:Po,AddMemoryScore:Po,FileMap:Kr,answer:No,Answer:No,AnswerSubagent:No,await:Fo,Await:Fo,AwaitSubagent:Fo,EmergencyRollback:Jr,emergency_rollback:Jr},ps=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=Bc[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 Fe from"fs";import Wc from"gradient-string";var ii=["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 Ja=[{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"]}],ms={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 Ws=null;var Qa=(e="Dark")=>{let n;e==="Mystery"||e==="Chaos"?(Ws||(Ws=Ja[Math.floor(Math.random()*Ja.length)]),n={...Ws,id:"Mystery"}):(Ws=null,ms[e]?n=ms[e]:e==="GitHub"?n=ms["GitHub Dark"]:e==="Transparent"?n=ms["Transparent Dark"]:n=ms.Dark);let t=n.codeText||n.secondary||n.info||n.logoGradient&&n.logoGradient[0]||"cyan";return{...n,codeText:t}};var jc=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",Jh=(e=2)=>{let n=jc();return n==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)},Qh=(e="...",n="Loading...",t="Dark")=>{let o=ii[Math.floor(Math.random()*ii.length)],s=Qa(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=Wc(c).multiline(d.join(`
885
+ 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 Uo=async(e,n={})=>{let t=L(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 ls=async(e,n={})=>{let t=L(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 fn,keyboard as Nt,Button as cs,Key as D,Point as ds,clipboard as vc}from"@nut-tree-fork/nut-js";fn.config.autoDelayMs=50;Nt.config.autoDelayMs=50;async function Qr(){try{await Nt.releaseKey(D.LeftControl,D.RightControl,D.LeftAlt,D.RightAlt,D.LeftShift,D.RightShift,D.LeftSuper,D.RightSuper)}catch{}}async function Nn(e,n,t={}){let o=await Yo(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 fn.setPosition(new ds(o.x,o.y)),`SUCCESS: Moved mouse to grid target ${typeof n=="string"?n:`(${o.x}, ${o.y})`}`;case"click":{await fn.setPosition(new ds(o.x,o.y));let s=t.button==="right"?cs.RIGHT:t.button==="middle"?cs.MIDDLE:cs.LEFT;return t.clickType==="double"?await fn.doubleClick(s):await fn.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 Yo(t.from||n),r=await Yo(t.to);return!s||!r?'ERROR: Drag requires valid "from" and "to" target coordinates/grid codes.':(await fn.setPosition(new ds(s.x,s.y)),await fn.pressButton(cs.LEFT),await fn.setPosition(new ds(r.x,r.y)),await fn.releaseButton(cs.LEFT),`SUCCESS: Dragged mouse from (${s.x}, ${s.y}) to (${r.x}, ${r.y})`)}case"scroll":{let s=o||await Yo({x:640,y:360});s&&(await fn.setPosition(new ds(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 fn.scrollUp(120):await fn.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 qa={enter:D.Enter,return:D.Return,escape:D.Escape,esc:D.Escape,backspace:D.Backspace,tab:D.Tab,space:D.Space,up:D.Up,down:D.Down,left:D.Left,right:D.Right,ctrl:D.LeftControl,control:D.LeftControl,alt:D.LeftAlt,shift:D.LeftShift,cmd:D.LeftCmd,win:D.LeftWin,meta:D.LeftWin,super:D.LeftSuper,a:D.A,b:D.B,c:D.C,d:D.D,e:D.E,f:D.F,g:D.G,h:D.H,i:D.I,j:D.J,k:D.K,l:D.L,m:D.M,n:D.N,o:D.O,p:D.P,q:D.Q,r:D.R,s:D.S,t:D.T,u:D.U,v:D.V,w:D.W,x:D.X,y:D.Y,z:D.Z,0:D.Num0,1:D.Num1,2:D.Num2,3:D.Num3,4:D.Num4,5:D.Num5,6:D.Num6,7:D.Num7,8:D.Num8,9:D.Num9,f1:D.F1,f2:D.F2,f3:D.F3,f4:D.F4,f5:D.F5,f6:D.F6,f7:D.F7,f8:D.F8,f9:D.F9,f10:D.F10,f11:D.F11,f12:D.F12},za=e=>{if(!e)return;let n=String(e).toLowerCase().trim();if(qa[n]!==void 0)return qa[n];if(D[e]!==void 0)return D[e];if(D[n.toUpperCase()]!==void 0)return D[n.toUpperCase()]};async function Un(e,n,t={}){try{switch(e.toLowerCase()){case"type":{if(typeof n!="string")return"ERROR: Type action requires a valid string input";await Qr(),await vc.setContent(n);let s=process.platform==="darwin"?D.LeftSuper:D.LeftControl;return await Nt.pressKey(s,D.V),await Nt.releaseKey(s,D.V),await Qr(),t.autoPressEnter?(await new Promise(r=>setTimeout(r,50)),await Nt.type(D.Enter),`SUCCESS: Typed text input ("${n.length>20?n.substring(0,20)+"...":n}") and pressed Enter`):`SUCCESS: Typed text input ("${n.length>20?n.substring(0,20)+"...":n}")`}case"key_press":{let o=za(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=>za(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(D.LeftControl,D.A),await Nt.releaseKey(D.LeftControl,D.A),await Nt.type(D.Backspace),"SUCCESS: Cleared active text input (Select All + Backspace)";case"browser_back":{let o=process.platform==="darwin";return o?(await Nt.pressKey(D.LeftSuper,D.Left),await Nt.releaseKey(D.LeftSuper,D.Left)):(await Nt.pressKey(D.LeftAlt,D.Left),await Nt.releaseKey(D.LeftAlt,D.Left)),await Qr(),`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 fs=async(e,n={})=>{let t=L(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 Nn(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 Un(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 Xa from"screenshot-desktop";import ps from"sharp";import Ka from"fs-extra";import Ya from"path";import"@nut-tree-fork/nut-js";async function Zr(e,n,t){if(!(!process.env.SHOW_DEBUG_GRID&&!process.env.DEBUG_OCR))try{let o=Ya.resolve(process.cwd(),"screenshots",e);await Ka.ensureDir(o),await Ka.writeFile(Ya.join(o,n),t)}catch{}}function Ic(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Oc(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 Lc(e){return e<=4?0:e<=8?1:2}async function ei(e,n=3){let t=await ps(e).metadata();return ps(e).resize(Math.round(t.width*n),Math.round(t.height*n),{kernel:"lanczos3"}).greyscale().normalise().toBuffer()}function Dc(e){if(!e)return{words:[],lines:[]};let n=[],t=new Map;for(let s of e.split(`
886
+ `)){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]),u=parseInt(r[8]),f=parseInt(r[9]),m=parseFloat(r[10]),g=r.slice(11).join(" ").trim();if(!g||m<0)continue;let y={x0:c,y0:l,x1:c+u,y1:l+f},h={text:g,confidence:m,bbox:y};n.push(h);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 x=t.get(w);x.words.push(h),x.bbox.x0=Math.min(x.bbox.x0,y.x0),x.bbox.y0=Math.min(x.bbox.y0,y.y0),x.bbox.x1=Math.max(x.bbox.x1,y.x1),x.bbox.y1=Math.max(x.bbox.y1,y.y1)}let o=[];for(let s of t.values())s.words.length>0&&o.push({text:s.words.map(r=>r.text).join(" "),bbox:s.bbox,words:s.words});return{words:n,lines:o}}function Pc(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=Dc(e.tsv);e.words=n.words,e.lines=n.lines}}}function ti(e,n,t=0,o=0,s=1){Pc(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${Ic(n)}\\b`,"i").test(p)))continue;let c=i.words||(e.words?e.words.filter(m=>m.bbox&&m.bbox.x0>=i.bbox.x0-5&&m.bbox.x1<=i.bbox.x1+5&&m.bbox.y0>=i.bbox.y0-5&&m.bbox.y1<=i.bbox.y1+5):[]),l=n.split(/\s+/),u=l.map(m=>m.replace(/[^a-z0-9]/g,"")).join(" "),f=!1;if(c.length>0)for(let m=0;m<=c.length-l.length;m++){let g=c.slice(m,m+l.length),y=g.map(h=>(h.text||"").toLowerCase().trim().replace(/[^a-z0-9]/g,"")).join(" ");if(y===u||y.includes(u)){let h={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(h)),f=!0}}f||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=Lc(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&&Oc(d,n,i)<=i&&p.bbox&&a.push(r(p.bbox))}}return a}function ni(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 Fc(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,u=d*i,f=Math.min(a,e-l),m=Math.min(i,n-u),g=l+f/2,y=u+m/2,h=t>=l&&t<l+f&&o>=u&&o<u+m;p.push({x0:l,y0:u,w:f,h:m,cx:g,cy:y,containsTarget:h})}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),u=Math.hypot(c.cx-t,c.cy-o);return l-u})}var Fs=null;async function Nc(){return Fs||(Fs=(async()=>{let{createWorker:e}=await import("tesseract.js"),n=await import("fs-extra"),{CU_CACHE_DIR:t}=await import("./paths-CHZDSDRF.js");return n.ensureDirSync(t),e("eng",1,{cachePath:t,logger:()=>{}})})().catch(e=>{throw Fs=null,e})),Fs}var us=null,Va=null;async function Uc(){let{getActiveDisplay:e}=await import("./screen_grid-WWZV4QEB.js"),n=await e();if(us&&Va===n)return us;Va=n,us={format:"png"};try{let t=await Xa.listDisplays();t&&t.length>0&&(us={format:"png",screen:(t[n]||t[0]).id})}catch{}return us}var oi=async(e,n={})=>{let t=!!(process.env.SHOW_DEBUG_GRID||process.env.DEBUG_OCR||process.env.VERBOSE),o=performance.now(),s=o,r=f=>{if(!t)return;let m=performance.now(),g=(m-s).toFixed(0),y=(m-o).toFixed(0);console.log(`[Click Perf] +${g}ms (${y}ms total) -> ${f}`),s=m};r("Starting click()");let a=L(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 f=i?Fi(i):null;r("Getting display options");let m=await Uc();r("Taking desktop screenshot");let g=await Xa(m);r("Getting image metadata");let y=await ps(g).metadata(),h=y.width||1920,w=y.height||1080,x=f?{x:Math.round(f.x*(h/1280)),y:Math.round(f.y*(w/720))}:{x:h/2,y:w/2},T=c.toLowerCase().trim();r("Acquiring OCR worker");let _=await Nc(),R=null,S="",k=f?220:500;if(f){r("Pass 1: Cropping target crop (3x zoom window, 2x upscale)");let C=Math.min(Math.round(h/3),h),E=Math.min(Math.round(w/3),w),b=Math.max(0,Math.min(h-C,x.x-Math.floor(C/2))),$=Math.max(0,Math.min(w-E,x.y-Math.floor(E/2))),I=await ps(g).extract({left:b,top:$,width:C,height:E}).toBuffer(),O=2,P=await ei(I,O),W=T.replace(/[^a-z0-9]/g,"_");await Zr("cropped",`crop_${Date.now()}_${W}.png`,P),r("Pass 1: Running Tesseract OCR recognize on crop (PSM 11 - Sparse Text)"),await _.setParameters({tessedit_pageseg_mode:"11"});let{data:q}=await _.recognize(P,{},{tsv:!0,blocks:!0});if(r("Pass 1: OCR recognition finished, extracting matches"),q&&q.text){t&&console.log(`[Pass 1 OCR Read]: "${q.text.trim().replace(/\s+/g," ")}"`);let Q=ti(q,T,b,$,O);if(Q.length>0){let V=ni(Q,x);V&&(V.containsPoint||V.dist<=k)&&(R=V,S="centered target crop OCR")}}}if(!R){r("Pass 2: Entering Full-Screen OCR (broad scan, PSM 3 - Auto)");let C=await ei(g,2),E=T.replace(/[^a-z0-9]/g,"_");await Zr("fullscreen",`full_${Date.now()}_${E}.png`,C),r("Pass 2: Running Tesseract on full screen"),await _.setParameters({tessedit_pageseg_mode:"3"});let{data:b}=await _.recognize(C,{},{tsv:!0,blocks:!0});if(r("Pass 2: Full-screen OCR finished"),b&&b.text){let $=ti(b,T,0,0,2);if($.length>0){let I=ni($,x);I&&(R=I,S="full-screen OCR")}}}if(!R){r("Pass 3: Entering Tiled OCR fallback (high-res 3x)");let C=Fc(h,w,x.x,x.y),E=T.replace(/[^a-z0-9]/g,"_");await _.setParameters({tessedit_pageseg_mode:"11"});for(let b=0;b<C.length;b++){let $=C[b];r(`Pass 3: Preprocessing tile ${b+1}/${C.length}`);let I=await ps(g).extract({left:$.x0,top:$.y0,width:$.w,height:$.h}).toBuffer(),O=await ei(I,3);await Zr("tiles",`tile_${b+1}_${Date.now()}_${E}.png`,O),r(`Pass 3: Running Tesseract on tile ${b+1}`);let{data:P}=await _.recognize(O,{},{tsv:!0,blocks:!0});if(!P||!P.text)continue;let W=ti(P,T,$.x0,$.y0,3);if(W.length>0){let q=ni(W,x);if(q){R=q,S=`tile ${b+1} OCR (${$.containsTarget?"target tile":`offset ${$.x0},${$.y0}`})`;break}}}}if(R){let C={x:Math.round(R.x*(1280/h)),y:Math.round(R.y*(720/w))};r(`Executing mouse click on matched target (${S})`);let E=await Nn("click",C,{button:d,clickType:p});return r("Click completed successfully"),`${E} (${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(f){t&&console.error("[OCR Error]",f)}r(`Executing mouse click on fallback gridId: ${l}`);let u=await Nn("click",l,{button:d,clickType:p});return r("Fallback click completed"),u};var si=async(e,n={})=>{let t=L(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 Nn("drag",o,{from:o,to:s})};var ri=async(e,n={})=>{let t=L(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 Nn("scroll",r,{direction:o,amount:s})};var Ns=async(e,n={})=>{let t=L(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 Un("type",String(o),{autoPressEnter:s})};var Us=async(e,n={})=>{let t=L(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 Un("clear_input");if(s==="back"||s==="browser_back"||s==="browserBack")return await Un("browser_back");if(s.includes(";")||s.includes("+")){let r=s.split(/[;+]/).map(a=>a.trim()).filter(Boolean);return await Un("key_combination",r)}return await Un("key_press",s)};var Bs=async(e,n={})=>"SUCCESS: Screen recapture requested. The latest gridded screenshot is provided for your next decision.";var Bc={web_search:$r,web_scrape:Ar,memory:Mr,chat:vr,view_file:ts,write_file:Ir,update_file:Pr,exec_command:hr,read_folder:Nr,write_pdf:Ur,write_docx:Wr,search_keyword:ss,generate_image:Hr,saveSummary:rs,addMemScore:Fo,file_map:Kr,todo:is,Todo:is,goal:is,Goal:is,invokeSync:Yr,invoke:ja,getProgress:Vr,cancel:Ga,awaitSubagent:No,answerSubagent:Uo,steerSubagent:ls,computer_action:fs,computer_use:fs,ComputerAction:fs,ComputerUse:fs,click:oi,Click:oi,drag:si,Drag:si,scroll:ri,Scroll:ri,keyboard_typing:Ns,KeyboardTyping:Ns,keyboardtyping:Ns,key_press:Us,KeyPress:Us,keypress:Us,recapture_screen:Bs,RecaptureScreen:Bs,recapturescreen:Bs,invoke_sync:Yr,get_progress:Vr,await_subagent:No,answer_subagent:Uo,steer_subagent:ls,steer:ls,Steer:ls,ask:Ps,Ask:Ps,AskUser:Ps,WebSearch:$r,WebScrape:Ar,ReadFile:ts,ReadFolder:Nr,WriteFile:Ir,PatchFile:Pr,WritePDF:Ur,WriteDoc:Wr,Run:hr,SearchKeyword:ss,CodeSearch:ss,code_search:ss,Memory:Mr,Chat:vr,GenerateImage:Hr,saveSumary:rs,SaveSummary:rs,SaveSumary:rs,add_mem_score:Fo,AddMemScore:Fo,addMemoryScore:Fo,AddMemoryScore:Fo,FileMap:Kr,answer:Uo,Answer:Uo,AnswerSubagent:Uo,await:No,Await:No,AwaitSubagent:No,EmergencyRollback:Jr,emergency_rollback:Jr},ms=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=Bc[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 Fe from"fs";import Wc from"gradient-string";var ii=["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 Ja=[{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"]}],hs={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 Ws=null;var Qa=(e="Dark")=>{let n;e==="Mystery"||e==="Chaos"?(Ws||(Ws=Ja[Math.floor(Math.random()*Ja.length)]),n={...Ws,id:"Mystery"}):(Ws=null,hs[e]?n=hs[e]:e==="GitHub"?n=hs["GitHub Dark"]:e==="Transparent"?n=hs["Transparent Dark"]:n=hs.Dark);let t=n.codeText||n.secondary||n.info||n.logoGradient&&n.logoGradient[0]||"cyan";return{...n,codeText:t}};var jc=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",Jh=(e=2)=>{let n=jc();return n==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)},Qh=(e="...",n="Loading...",t="Dark")=>{let o=ii[Math.floor(Math.random()*ii.length)],s=Qa(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=Wc(c).multiline(d.join(`
837
887
  `)).split(`
838
888
  `),u=f=>`${i}${f}${p}`;return`${l[0]}
839
889
  ${l[1]} ${r}Selected Provider: ${n}${p}
@@ -842,7 +892,7 @@ ${l[3]} ${r}FluxFlow ${u("v"+e)}${p}
842
892
  ${l[4]}
843
893
  ${l[5]} ${a}See /help for additional commands.${p}
844
894
  ${l[6]} ${u(o)}
845
- ${l[7]}`};import{WebSocket as js}from"ws";var zt=null,Uo=!1,Gc="ws://localhost:56832",ai=[],Bo=null,li=null,Za="2.0.0",tg=e=>{Za=e,el()},ci=e=>{li=e},el=()=>{if(zt||Uo)return;Uo=!0;let e=new js(Gc);e.on("open",()=>{for(zt=e,Uo=!1,zt.send(JSON.stringify({command:"version",version:Za,pid:process.pid,ppid:process.ppid}));ai.length>0;)zt.send(JSON.stringify(ai.shift()))}),e.on("message",n=>{try{let t=JSON.parse(n.toString());t.command==="contextResponse"&&Bo?(Bo(t.data),Bo=null):t.command==="securityResponse"&&li&&li(t.result)}catch{}}),e.on("error",()=>{Uo=!1,zt=null}),e.on("close",()=>{Uo=!1,zt=null})},Gs=e=>{zt&&zt.readyState===js.OPEN?zt.send(JSON.stringify(e)):(ai.push(e),Uo||el())},Hs=()=>zt!==null&&zt.readyState===js.OPEN,ng=e=>{Gs({command:"status",status:e})},wo=()=>new Promise(e=>{if(!zt||zt.readyState!==js.OPEN){e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]});return}Bo=e,zt.send(JSON.stringify({command:"requestContext"})),setTimeout(()=>{Bo===e&&(e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]}),Bo=null)},1e3)}),tl=e=>{Gs({command:"open",filePath:e})},di=(e,n,t)=>{Gs({command:"showDiff",filePath:e,originalContent:n,modifiedContent:t})},nl=(e,n)=>{Gs({command:"closeDiff",filePath:e,result:n})};import ol from"path";import Hc from"fs";var qc=e=>{try{return Hc.readdirSync(e,{withFileTypes:!0})}catch{return[]}},fi=(e,n,t=1,o=qc,s=[],r=null)=>{let a=r||o(e),i=" ".repeat(t-1);if(a.length>100)return`${i}${ol.basename(e)}/ (>100 files)
895
+ ${l[7]}`};import{WebSocket as js}from"ws";var Kt=null,Bo=!1,Gc="ws://localhost:56832",ai=[],Wo=null,li=null,Za="2.0.0",tg=e=>{Za=e,el()},ci=e=>{li=e},el=()=>{if(Kt||Bo)return;Bo=!0;let e=new js(Gc);e.on("open",()=>{for(Kt=e,Bo=!1,Kt.send(JSON.stringify({command:"version",version:Za,pid:process.pid,ppid:process.ppid}));ai.length>0;)Kt.send(JSON.stringify(ai.shift()))}),e.on("message",n=>{try{let t=JSON.parse(n.toString());t.command==="contextResponse"&&Wo?(Wo(t.data),Wo=null):t.command==="securityResponse"&&li&&li(t.result)}catch{}}),e.on("error",()=>{Bo=!1,Kt=null}),e.on("close",()=>{Bo=!1,Kt=null})},Gs=e=>{Kt&&Kt.readyState===js.OPEN?Kt.send(JSON.stringify(e)):(ai.push(e),Bo||el())},Hs=()=>Kt!==null&&Kt.readyState===js.OPEN,ng=e=>{Gs({command:"status",status:e})},xo=()=>new Promise(e=>{if(!Kt||Kt.readyState!==js.OPEN){e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]});return}Wo=e,Kt.send(JSON.stringify({command:"requestContext"})),setTimeout(()=>{Wo===e&&(e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]}),Wo=null)},1e3)}),tl=e=>{Gs({command:"open",filePath:e})},di=(e,n,t)=>{Gs({command:"showDiff",filePath:e,originalContent:n,modifiedContent:t})},nl=(e,n)=>{Gs({command:"closeDiff",filePath:e,result:n})};import ol from"path";import Hc from"fs";var qc=e=>{try{return Hc.readdirSync(e,{withFileTypes:!0})}catch{return[]}},fi=(e,n,t=1,o=qc,s=[],r=null)=>{let a=r||o(e),i=" ".repeat(t-1);if(a.length>100)return`${i}${ol.basename(e)}/ (>100 files)
846
896
  `;let p="",d=s,c=a.filter(m=>!d.includes(m.name)&&!m.name.startsWith(".")),l=a.filter(m=>d.includes(m.name)||m.name.startsWith(".")).map(m=>m.name).sort();l.length>0&&(p+=`${i}[ignored: ${l.map(m=>m+"/").join(", ")}]
847
897
  `);let u=c.filter(m=>m.isDirectory()).sort((m,g)=>m.name.localeCompare(g.name)),f=c.filter(m=>!m.isDirectory()).map(m=>m.name).sort();for(let m of u){let g=ol.join(e,m.name);if(t>n)p+=`${i}${m.name}/ (max depth)
848
898
  `;else{let y=o(g);y.length>80?p+=`${i}${m.name}/ (>80 files)
@@ -854,22 +904,22 @@ ${l[7]}`};import{WebSocket as js}from"ws";var zt=null,Uo=!1,Gc="ws://localhost:5
854
904
  `:s(y).length>80?p+=`${t}${h}${f.name}${i} ...80+ files...
855
905
  `:(p+=`${t}${h}${f.name}${i}
856
906
  `,p+=pi(y,n,w,o+1,s,r)):p+=`${t}${h}${f.name}
857
- `}),p};import"@google/genai";var vt=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 qs(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 Un=e=>typeof e!="string"?e:e.replace(/<\|channel>thought/gi,"<think>").replace(/<channel\|>/gi,"</think>");var zs=async function*(e,n,t,o,s,r,a,i,p=1){let d=[];o&&d.push({role:"system",content:o});for(let x of t){let T=x.role==="user"?"user":"assistant",_=[];if(Array.isArray(x.parts)){for(let R of x.parts)if(R.text)_.push({type:"text",text:R.text});else if(R.inlineData&&a){let S=R.inlineData.mimeType,k=R.inlineData.data;S.startsWith("image/")&&_.push({type:"image_url",image_url:{url:`data:${S};base64,${k}`}})}}else{let R=x.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 x={Low:"high",Medium:"high",Standard:"high",High:"max",xHigh:"max"};c.reasoning_effort=x[s]||"high",c.extra_body={thinking:{type:"enabled"}}}else c.extra_body={thinking:{type:"disabled"}};let l=await vt("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 x=await l.json().catch(()=>({}));throw new Error(`DeepSeek Error (${l.status}): ${x.error?.message||l.statusText}`)}let u=l.body.getReader(),f=new TextDecoder,m="",g=[],y=null,h=Date.now(),w=!1;for(;;){let{done:x,value:T}=await u.read();if(x){w&&(g.length>0||y)&&(yield{candidates:g.length>0?[{content:{parts:g}}]:[],usageMetadata:y});break}m+=f.decode(T,{stream:!0});let _=m.split(`
858
- `);m=_.pop();for(let R of _){let S=R.trim();if(!S||!S.startsWith("data: "))continue;let k=!1;if(S==="data: [DONE]")k=!0;else try{let C=JSON.parse(S.substring(6)),E=C.choices?.[0]?.delta,b=C.usage;if(C.choices?.[0]?.finish_reason&&(k=!0),b&&(y={totalTokenCount:b.total_tokens||b.prompt_tokens+b.completion_tokens,promptTokenCount:b.prompt_tokens||0,candidatesTokenCount:b.completion_tokens||0,cachedContentTokenCount:b.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:b.completion_tokens_details?.reasoning_tokens||0},w=!0),E){let $=E.reasoning_content||null;$&&(g.push({text:$,thought:!0}),w=!0),E.content&&(g.push({text:E.content}),w=!0)}}catch{}if((k||Date.now()-h>=150)&&w&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],h=Date.now(),w=!1),k)break}Date.now()-h>=150&&w&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],h=Date.now(),w=!1)}};var Ks=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 k of t){let C=k.role==="user"?"user":"assistant",E=[];if(Array.isArray(k.parts)){for(let b of k.parts)if(b.text)E.push({type:"text",text:b.text});else if(b.inlineData&&a){let $=b.inlineData.mimeType,I=b.inlineData.data;$.startsWith("image/")&&E.push({type:"image_url",image_url:`data:${$};base64,${I}`})}}else{let b=k.text||"";b&&E.push({type:"text",text:b})}E.length>0&&c.push({role:C,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"},u=`${e.slice(-5)}${d||""}${s}${n}`,f=await qs(u),m={model:n,messages:c,stream:!0,temperature:p,prompt_cache_key:f};s&&s!=="Fast"&&Mo(n)&&(m.reasoning_effort=l[s]||"high");let g=await vt("https://api.mistral.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(m),signal:i});if(!g.ok){let k=await g.text().catch(()=>""),C=g.statusText;try{let E=JSON.parse(k);C=E.error?.message||E.message||JSON.stringify(E.detail||E)}catch{k&&(C=k)}throw new Error(`Mistral Error (${g.status}): ${JSON.stringify(C)}`)}let y=g.body.getReader(),h=new TextDecoder,w="",x=[],T=null,_=Date.now(),R=!1,S=k=>k?typeof k=="string"?Un(k):Array.isArray(k)?k.map(S).filter(Boolean).join(""):typeof k=="object"&&k!==null?typeof k.text=="string"?Un(k.text):typeof k.content=="string"?Un(k.content):typeof k.thinking=="string"?Un(k.thinking):typeof k.reasoning_content=="string"?Un(k.reasoning_content):typeof k.reasoning=="string"?Un(k.reasoning):typeof k.value=="string"?Un(k.value):k.text?S(k.text):k.content?S(k.content):k.thinking?S(k.thinking):k.reasoning_content?S(k.reasoning_content):k.reasoning?S(k.reasoning):k.value?S(k.value):"":Un(String(k)):"";for(;;){let{done:k,value:C}=await y.read();if(k){R&&(x.length>0||T)&&(yield{candidates:x.length>0?[{content:{parts:x}}]:[],usageMetadata:T});break}w+=h.decode(C,{stream:!0});let E=w.split(`
859
- `);w=E.pop();for(let b of E){let $=b.trim();if(!$||!$.startsWith("data: "))continue;let I=!1;if($==="data: [DONE]")I=!0;else try{let O=JSON.parse($.substring(6)),P=O.choices?.[0]?.delta,W=O.usage;if(O.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),P){let q=P.thinking||P.reasoning_content||P.reasoning,Q=S(q);Q&&(x.push({text:Q,thought:!0}),R=!0);let V=P.content||(!P.thinking&&!P.reasoning_content&&!P.reasoning?P.text:null);if(V)if(Array.isArray(V))for(let F of V)if(typeof F=="object"&&F!==null){let B=F.type==="thinking"||F.type==="reasoning"||!!F.thought,ee=S(F);ee&&(x.push({text:ee,...B?{thought:!0}:{}}),R=!0)}else{let B=S(F);B&&(x.push({text:B}),R=!0)}else if(typeof V=="object"&&V!==null){let F=V.type==="thinking"||V.type==="reasoning"||!!V.thought,B=S(V);B&&(x.push({text:B,...F?{thought:!0}:{}}),R=!0)}else{let F=S(V);F&&(x.push({text:F}),R=!0)}}}catch{}if((I||Date.now()-_>=150)&&R&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:T},x=[],_=Date.now(),R=!1),I)break}Date.now()-_>=150&&R&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:T},x=[],_=Date.now(),R=!1)}};var Ys=async function*(e,n,t,o,s,r,a=!1,i,p=1){let d=[];o&&d.push({role:"system",content:o}),t.forEach(ee=>{let Me=ee.role==="model"?"assistant":"user",v=[];Array.isArray(ee.parts)&&ee.parts.forEach(U=>{if(U.text)v.push({type:"text",text:U.text});else if(U.inlineData&&a){let X=U.inlineData.mimeType,te=U.inlineData.data;X.startsWith("image/")&&At(n)&&v.push({type:"image_url",image_url:{url:`data:${X};base64,${te}`}})}}),d.push({role:Me,content:v.length===1&&v[0].type==="text"?v[0].text:v})});let l={Fast:"Fast",Low:"Fast",Medium:"Standard",Standard:"Standard",High:"High",xHigh:"High"}[s]||"High",u=l!=="Fast",f=n.includes("kimi"),m=n.includes("gemma"),g=n.includes("deepseek"),y=n.includes("glm"),h=n.includes("mistral"),w=n.includes("minimax"),x=n.includes("gpt"),T=n.includes("qwen"),_=n.includes("nemotron"),R=n.includes("llama-3"),S=n.includes("seed"),k=n.includes("poolside"),C=n.includes("thinkingmachines")||n.includes("muse"),E=R,b=null,$={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"},O={Fast:"none",Low:"minimal",Medium:"medium",Standard:"medium",High:"max",xHigh:"max"},P=w||g||k||C?16384:32768;P=process.env.NVIDIA_BASE_URL?1024:P,P=b?1024:P;let W={model:n,messages:d,max_tokens:P,stream:!0,stream_options:{include_usage:!0},temperature:p,...x&&{thinking:$[s]||"high"}};if(!(process.env.NVIDIA_BASE_URL||E||b))if(f)W.chat_template_kwargs={thinking:u};else if(m)W.chat_template_kwargs={enable_thinking:u};else if(g)if(u){let ee=l==="High"?"max":"high";W.chat_template_kwargs={thinking:!0,reasoning_effort:ee}}else W.chat_template_kwargs={thinking:!1};else y?W.chat_template_kwargs={enable_thinking:u,clear_thinking:!u}:h?W.reasoning_effort=u?"high":"none":w&&n.includes("minimax-m3")?W.chat_template_kwargs={thinking_mode:u?"enabled":"disabled"}:T?W.chat_template_kwargs={enable_thinking:u}:_?l==="High"?W.chat_template_kwargs={enable_thinking:!0}:l==="Standard"?W.chat_template_kwargs={enable_thinking:!0,medium_effort:!0}:W.chat_template_kwargs={enable_thinking:!1}:S?u&&(W.extra_body={thinking_budget:parseInt(I[l]??"4096")}):k?W.chat_template_kwargs={enable_thinking:u}:C&&(W.reasoning_effort=O[l]||"medium");let q=0,Q=6,V=!1,F=process.env.NVIDIA_BASE_URL||"https://integrate.api.nvidia.com/v1/chat/completions",B=process.env.NVIDIA_API_KEY&&process.env.NVIDIA_BASE_URL?process.env.NVIDIA_API_KEY:e;for(F.endsWith("/chat/completions")||(F=F.replace(/\/+$/,"")+"/chat/completions");q<Q;){q++;try{let ee=await vt(F,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${B}`},body:JSON.stringify(W),signal:i});if(!ee.ok){let Je=await ee.text().catch(()=>""),ct=ee.statusText;try{let gt=JSON.parse(Je);ct=gt.error?.message||gt.message||JSON.stringify(gt.detail||gt)}catch{Je&&(ct=Je)}let He=new Error(`NVIDIA API Error (${ee.status}): ${ct}`);throw He.status=ee.status,He}let Me=ee.body.getReader(),v=new TextDecoder,U="",X=[],te=null,We=Date.now(),Ne=!1;for(;;){let{done:Je,value:ct}=await Me.read();if(Je){Ne&&(X.length>0||te)&&(yield{candidates:X.length>0?[{content:{parts:X}}]:[],usageMetadata:te},V=!0);break}U+=v.decode(ct,{stream:!0});let He=U.split(`
860
- `);U=He.pop();let gt=!1;for(let ko of He){let bt=ko.trim();if(bt){if(bt==="data: [DONE]"){gt=!0;break}if(bt.startsWith("data: ")){let Ke;try{Ke=JSON.parse(bt.substring(6))}catch{continue}if(Ke.error)throw new Error(`NVIDIA Stream Error: ${Ke.error.message||JSON.stringify(Ke.error)}`);try{let Rt=Ke.usage;Rt&&(te={totalTokenCount:Rt.total_tokens||Rt.prompt_tokens+Rt.completion_tokens,promptTokenCount:Rt.prompt_tokens||0,candidatesTokenCount:Rt.completion_tokens||0,cachedContentTokenCount:Rt.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:(Rt.completion_tokens_details?.reasoning_tokens||0)+(Rt.completion_tokens_details?.thoughts_tokens||0)},Ne=!0);let et=Ke.choices?.[0]?.delta?.reasoning||Ke.choices?.[0]?.delta?.reasoning_content||"",Re=Ke.choices?.[0]?.delta?.content||"";et&&(X.push({text:et,thought:!0}),Ne=!0),Re&&(X.push({text:Re}),Ne=!0)}catch{}}}}if((gt||Date.now()-We>=350)&&Ne&&(yield{candidates:X.length>0?[{content:{parts:[...X]}}]:[],usageMetadata:te},V=!0,X=[],We=Date.now(),Ne=!1),gt)break}break}catch(ee){if(V||q>=Q)throw ee;await new Promise(Me=>setTimeout(Me,3500))}}},sl=async function*(e,n){let t=[],o=null,s=!1,r=null,a=u=>{if(t.push(u),o){let f=o;o=null,f()}},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 u=await fetch(p);if(u.ok){let f=await u.json();if(f&&f.queues&&f.queues[0]&&typeof f.queues[0].queueDepth=="number"){let m=f.queues[0].queueDepth;d||a({value:{type:"status",content:`Queue ${m||1}`},done:!1})}}}catch{}};process.env.NVIDIA_BASE_URL||(l(),c=setInterval(l,5e3)),(async()=>{try{let u=e[Symbol.asyncIterator]();for(;;){let{value:f,done:m}=await u.next();if(m)break;d=!0,c&&(clearInterval(c),c=null),a({value:f,done:!1})}s=!0,a(null)}catch(u){if(r=u,c&&(clearInterval(c),c=null),o){let f=o;o=null,f()}}})();try{for(;;){if(r)throw r;if(t.length>0){let u=t.shift();if(u===null&&s)break;yield u.value}else{if(s)break;await new Promise(u=>{o=u})}}}finally{c&&(clearInterval(c),c=null)}};var Vs=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 b of t){let $=b.role==="user"?"user":"assistant",I=[];if(Array.isArray(b.parts)){for(let O of b.parts)if(O.text)I.push({type:"text",text:O.text});else if(O.inlineData&&a){let P=O.inlineData.mimeType,W=O.inlineData.data;P.startsWith("image/")?I.push({type:"image_url",image_url:{url:`data:${P};base64,${W}`}}):I.push({type:"file",file:{filename:O.filename||"file",file_data:`data:${P};base64,${W}`}})}}else{let O=b.text||"";O&&I.push({type:"text",text:O})}c.push({role:$,content:I.length===1&&I[0].type==="text"?I[0].text:I})}let l={Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},u=["free","nitro","floor","exact","extended","beta","online"],f=n,m=null;if(n.includes(":")){let b=n.split(":"),$=b[b.length-1].toLowerCase().trim();if(u.includes($))f=n.trim();else{let I=b.pop().trim();f=b.join(":").trim(),I&&(m={order:[I],allow_fallbacks:!1})}}let g=`${e.slice(-5)}${d||""}${s}${f}${m?JSON.stringify(m):""}`,y=await qs(g),h={model:f,messages:c,stream:!0,temperature:p,cache_control:{type:"ephemeral"},session_id:y};m&&(h.provider=m);let w=l[s];w&&s!=="Fast"&&(h.reasoning_effort=w);let x=await vt("https://openrouter.ai/api/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json","HTTP-Referer":"https://fluxflow-cli.onrender.com/","X-Title":"FluxFlow CLI","X-OpenRouter-Title":"FluxFlow CLI","X-Cache":"true","X-OpenRouter-Cache":"true"},body:JSON.stringify(h),signal:i});if(!x.ok){let b=await x.json().catch(()=>({})),$=b.error?.metadata?.raw||b.error?.message||(typeof b.error=="string"?b.error:"")||x.statusText||"Unknown error";throw new Error(`OpenRouter Error (${x.status}): ${$}`)}let T=x.body.getReader(),_=new TextDecoder,R="",S=[],k=null,C=Date.now(),E=!1;for(;;){let{done:b,value:$}=await T.read();if(b){E&&(S.length>0||k)&&(yield{candidates:S.length>0?[{content:{parts:S}}]:[],usageMetadata:k});break}R+=_.decode($,{stream:!0});let I=R.split(`
907
+ `}),p};import"@google/genai";var It=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 qs(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 Bn=e=>typeof e!="string"?e:e.replace(/<\|channel>thought/gi,"<think>").replace(/<channel\|>/gi,"</think>");var zs=async function*(e,n,t,o,s,r,a,i,p=1){let d=[];o&&d.push({role:"system",content:o});for(let x of t){let T=x.role==="user"?"user":"assistant",_=[];if(Array.isArray(x.parts)){for(let R of x.parts)if(R.text)_.push({type:"text",text:R.text});else if(R.inlineData&&a){let S=R.inlineData.mimeType,k=R.inlineData.data;S.startsWith("image/")&&_.push({type:"image_url",image_url:{url:`data:${S};base64,${k}`}})}}else{let R=x.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 x={Low:"high",Medium:"high",Standard:"high",High:"max",xHigh:"max"};c.reasoning_effort=x[s]||"high",c.extra_body={thinking:{type:"enabled"}}}else c.extra_body={thinking:{type:"disabled"}};let l=await It("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 x=await l.json().catch(()=>({}));throw new Error(`DeepSeek Error (${l.status}): ${x.error?.message||l.statusText}`)}let u=l.body.getReader(),f=new TextDecoder,m="",g=[],y=null,h=Date.now(),w=!1;for(;;){let{done:x,value:T}=await u.read();if(x){w&&(g.length>0||y)&&(yield{candidates:g.length>0?[{content:{parts:g}}]:[],usageMetadata:y});break}m+=f.decode(T,{stream:!0});let _=m.split(`
908
+ `);m=_.pop();for(let R of _){let S=R.trim();if(!S||!S.startsWith("data: "))continue;let k=!1;if(S==="data: [DONE]")k=!0;else try{let C=JSON.parse(S.substring(6)),E=C.choices?.[0]?.delta,b=C.usage;if(C.choices?.[0]?.finish_reason&&(k=!0),b&&(y={totalTokenCount:b.total_tokens||b.prompt_tokens+b.completion_tokens,promptTokenCount:b.prompt_tokens||0,candidatesTokenCount:b.completion_tokens||0,cachedContentTokenCount:b.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:b.completion_tokens_details?.reasoning_tokens||0},w=!0),E){let $=E.reasoning_content||null;$&&(g.push({text:$,thought:!0}),w=!0),E.content&&(g.push({text:E.content}),w=!0)}}catch{}if((k||Date.now()-h>=150)&&w&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],h=Date.now(),w=!1),k)break}Date.now()-h>=150&&w&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],h=Date.now(),w=!1)}};var Ks=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 k of t){let C=k.role==="user"?"user":"assistant",E=[];if(Array.isArray(k.parts)){for(let b of k.parts)if(b.text)E.push({type:"text",text:b.text});else if(b.inlineData&&a){let $=b.inlineData.mimeType,I=b.inlineData.data;$.startsWith("image/")&&E.push({type:"image_url",image_url:`data:${$};base64,${I}`})}}else{let b=k.text||"";b&&E.push({type:"text",text:b})}E.length>0&&c.push({role:C,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"},u=`${e.slice(-5)}${d||""}${s}${n}`,f=await qs(u),m={model:n,messages:c,stream:!0,temperature:p,prompt_cache_key:f};s&&s!=="Fast"&&vo(n)&&(m.reasoning_effort=l[s]||"high");let g=await It("https://api.mistral.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(m),signal:i});if(!g.ok){let k=await g.text().catch(()=>""),C=g.statusText;try{let E=JSON.parse(k);C=E.error?.message||E.message||JSON.stringify(E.detail||E)}catch{k&&(C=k)}throw new Error(`Mistral Error (${g.status}): ${JSON.stringify(C)}`)}let y=g.body.getReader(),h=new TextDecoder,w="",x=[],T=null,_=Date.now(),R=!1,S=k=>k?typeof k=="string"?Bn(k):Array.isArray(k)?k.map(S).filter(Boolean).join(""):typeof k=="object"&&k!==null?typeof k.text=="string"?Bn(k.text):typeof k.content=="string"?Bn(k.content):typeof k.thinking=="string"?Bn(k.thinking):typeof k.reasoning_content=="string"?Bn(k.reasoning_content):typeof k.reasoning=="string"?Bn(k.reasoning):typeof k.value=="string"?Bn(k.value):k.text?S(k.text):k.content?S(k.content):k.thinking?S(k.thinking):k.reasoning_content?S(k.reasoning_content):k.reasoning?S(k.reasoning):k.value?S(k.value):"":Bn(String(k)):"";for(;;){let{done:k,value:C}=await y.read();if(k){R&&(x.length>0||T)&&(yield{candidates:x.length>0?[{content:{parts:x}}]:[],usageMetadata:T});break}w+=h.decode(C,{stream:!0});let E=w.split(`
909
+ `);w=E.pop();for(let b of E){let $=b.trim();if(!$||!$.startsWith("data: "))continue;let I=!1;if($==="data: [DONE]")I=!0;else try{let O=JSON.parse($.substring(6)),P=O.choices?.[0]?.delta,W=O.usage;if(O.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),P){let q=P.thinking||P.reasoning_content||P.reasoning,Q=S(q);Q&&(x.push({text:Q,thought:!0}),R=!0);let V=P.content||(!P.thinking&&!P.reasoning_content&&!P.reasoning?P.text:null);if(V)if(Array.isArray(V))for(let F of V)if(typeof F=="object"&&F!==null){let B=F.type==="thinking"||F.type==="reasoning"||!!F.thought,ee=S(F);ee&&(x.push({text:ee,...B?{thought:!0}:{}}),R=!0)}else{let B=S(F);B&&(x.push({text:B}),R=!0)}else if(typeof V=="object"&&V!==null){let F=V.type==="thinking"||V.type==="reasoning"||!!V.thought,B=S(V);B&&(x.push({text:B,...F?{thought:!0}:{}}),R=!0)}else{let F=S(V);F&&(x.push({text:F}),R=!0)}}}catch{}if((I||Date.now()-_>=150)&&R&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:T},x=[],_=Date.now(),R=!1),I)break}Date.now()-_>=150&&R&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:T},x=[],_=Date.now(),R=!1)}};var Ys=async function*(e,n,t,o,s,r,a=!1,i,p=1){let d=[];o&&d.push({role:"system",content:o}),t.forEach(ee=>{let Me=ee.role==="model"?"assistant":"user",v=[];Array.isArray(ee.parts)&&ee.parts.forEach(U=>{if(U.text)v.push({type:"text",text:U.text});else if(U.inlineData&&a){let X=U.inlineData.mimeType,te=U.inlineData.data;X.startsWith("image/")&&Mt(n)&&v.push({type:"image_url",image_url:{url:`data:${X};base64,${te}`}})}}),d.push({role:Me,content:v.length===1&&v[0].type==="text"?v[0].text:v})});let l={Fast:"Fast",Low:"Fast",Medium:"Standard",Standard:"Standard",High:"High",xHigh:"High"}[s]||"High",u=l!=="Fast",f=n.includes("kimi"),m=n.includes("gemma"),g=n.includes("deepseek"),y=n.includes("glm"),h=n.includes("mistral"),w=n.includes("minimax"),x=n.includes("gpt"),T=n.includes("qwen"),_=n.includes("nemotron"),R=n.includes("llama-3"),S=n.includes("seed"),k=n.includes("poolside"),C=n.includes("thinkingmachines")||n.includes("muse"),E=R,b=null,$={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"},O={Fast:"none",Low:"minimal",Medium:"medium",Standard:"medium",High:"max",xHigh:"max"},P=w||g||k||C?16384:32768;P=process.env.NVIDIA_BASE_URL?1024:P,P=b?1024:P;let W={model:n,messages:d,max_tokens:P,stream:!0,stream_options:{include_usage:!0},temperature:p,...x&&{thinking:$[s]||"high"}};if(!(process.env.NVIDIA_BASE_URL||E||b))if(f)W.chat_template_kwargs={thinking:u};else if(m)W.chat_template_kwargs={enable_thinking:u};else if(g)if(u){let ee=l==="High"?"max":"high";W.chat_template_kwargs={thinking:!0,reasoning_effort:ee}}else W.chat_template_kwargs={thinking:!1};else y?W.chat_template_kwargs={enable_thinking:u,clear_thinking:!u}:h?W.reasoning_effort=u?"high":"none":w&&n.includes("minimax-m3")?W.chat_template_kwargs={thinking_mode:u?"enabled":"disabled"}:T?W.chat_template_kwargs={enable_thinking:u}:_?l==="High"?W.chat_template_kwargs={enable_thinking:!0}:l==="Standard"?W.chat_template_kwargs={enable_thinking:!0,medium_effort:!0}:W.chat_template_kwargs={enable_thinking:!1}:S?u&&(W.extra_body={thinking_budget:parseInt(I[l]??"4096")}):k?W.chat_template_kwargs={enable_thinking:u}:C&&(W.reasoning_effort=O[l]||"medium");let q=0,Q=6,V=!1,F=process.env.NVIDIA_BASE_URL||"https://integrate.api.nvidia.com/v1/chat/completions",B=process.env.NVIDIA_API_KEY&&process.env.NVIDIA_BASE_URL?process.env.NVIDIA_API_KEY:e;for(F.endsWith("/chat/completions")||(F=F.replace(/\/+$/,"")+"/chat/completions");q<Q;){q++;try{let ee=await It(F,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${B}`},body:JSON.stringify(W),signal:i});if(!ee.ok){let Je=await ee.text().catch(()=>""),ct=ee.statusText;try{let gt=JSON.parse(Je);ct=gt.error?.message||gt.message||JSON.stringify(gt.detail||gt)}catch{Je&&(ct=Je)}let He=new Error(`NVIDIA API Error (${ee.status}): ${ct}`);throw He.status=ee.status,He}let Me=ee.body.getReader(),v=new TextDecoder,U="",X=[],te=null,We=Date.now(),Ne=!1;for(;;){let{done:Je,value:ct}=await Me.read();if(Je){Ne&&(X.length>0||te)&&(yield{candidates:X.length>0?[{content:{parts:X}}]:[],usageMetadata:te},V=!0);break}U+=v.decode(ct,{stream:!0});let He=U.split(`
910
+ `);U=He.pop();let gt=!1;for(let To of He){let bt=To.trim();if(bt){if(bt==="data: [DONE]"){gt=!0;break}if(bt.startsWith("data: ")){let Ke;try{Ke=JSON.parse(bt.substring(6))}catch{continue}if(Ke.error)throw new Error(`NVIDIA Stream Error: ${Ke.error.message||JSON.stringify(Ke.error)}`);try{let Et=Ke.usage;Et&&(te={totalTokenCount:Et.total_tokens||Et.prompt_tokens+Et.completion_tokens,promptTokenCount:Et.prompt_tokens||0,candidatesTokenCount:Et.completion_tokens||0,cachedContentTokenCount:Et.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:(Et.completion_tokens_details?.reasoning_tokens||0)+(Et.completion_tokens_details?.thoughts_tokens||0)},Ne=!0);let et=Ke.choices?.[0]?.delta?.reasoning||Ke.choices?.[0]?.delta?.reasoning_content||"",Re=Ke.choices?.[0]?.delta?.content||"";et&&(X.push({text:et,thought:!0}),Ne=!0),Re&&(X.push({text:Re}),Ne=!0)}catch{}}}}if((gt||Date.now()-We>=350)&&Ne&&(yield{candidates:X.length>0?[{content:{parts:[...X]}}]:[],usageMetadata:te},V=!0,X=[],We=Date.now(),Ne=!1),gt)break}break}catch(ee){if(V||q>=Q)throw ee;await new Promise(Me=>setTimeout(Me,3500))}}},sl=async function*(e,n){let t=[],o=null,s=!1,r=null,a=u=>{if(t.push(u),o){let f=o;o=null,f()}},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 u=await fetch(p);if(u.ok){let f=await u.json();if(f&&f.queues&&f.queues[0]&&typeof f.queues[0].queueDepth=="number"){let m=f.queues[0].queueDepth;d||a({value:{type:"status",content:`Queue ${m||1}`},done:!1})}}}catch{}};process.env.NVIDIA_BASE_URL||(l(),c=setInterval(l,5e3)),(async()=>{try{let u=e[Symbol.asyncIterator]();for(;;){let{value:f,done:m}=await u.next();if(m)break;d=!0,c&&(clearInterval(c),c=null),a({value:f,done:!1})}s=!0,a(null)}catch(u){if(r=u,c&&(clearInterval(c),c=null),o){let f=o;o=null,f()}}})();try{for(;;){if(r)throw r;if(t.length>0){let u=t.shift();if(u===null&&s)break;yield u.value}else{if(s)break;await new Promise(u=>{o=u})}}}finally{c&&(clearInterval(c),c=null)}};var Vs=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 b of t){let $=b.role==="user"?"user":"assistant",I=[];if(Array.isArray(b.parts)){for(let O of b.parts)if(O.text)I.push({type:"text",text:O.text});else if(O.inlineData&&a){let P=O.inlineData.mimeType,W=O.inlineData.data;P.startsWith("image/")?I.push({type:"image_url",image_url:{url:`data:${P};base64,${W}`}}):I.push({type:"file",file:{filename:O.filename||"file",file_data:`data:${P};base64,${W}`}})}}else{let O=b.text||"";O&&I.push({type:"text",text:O})}c.push({role:$,content:I.length===1&&I[0].type==="text"?I[0].text:I})}let l={Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},u=["free","nitro","floor","exact","extended","beta","online"],f=n,m=null;if(n.includes(":")){let b=n.split(":"),$=b[b.length-1].toLowerCase().trim();if(u.includes($))f=n.trim();else{let I=b.pop().trim();f=b.join(":").trim(),I&&(m={order:[I],allow_fallbacks:!1})}}let g=`${e.slice(-5)}${d||""}${s}${f}${m?JSON.stringify(m):""}`,y=await qs(g),h={model:f,messages:c,stream:!0,temperature:p,cache_control:{type:"ephemeral"},session_id:y};m&&(h.provider=m);let w=l[s];w&&s!=="Fast"&&(h.reasoning_effort=w);let x=await It("https://openrouter.ai/api/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json","HTTP-Referer":"https://fluxflow-cli.onrender.com/","X-Title":"FluxFlow CLI","X-OpenRouter-Title":"FluxFlow CLI","X-Cache":"true","X-OpenRouter-Cache":"true"},body:JSON.stringify(h),signal:i});if(!x.ok){let b=await x.json().catch(()=>({})),$=b.error?.metadata?.raw||b.error?.message||(typeof b.error=="string"?b.error:"")||x.statusText||"Unknown error";throw new Error(`OpenRouter Error (${x.status}): ${$}`)}let T=x.body.getReader(),_=new TextDecoder,R="",S=[],k=null,C=Date.now(),E=!1;for(;;){let{done:b,value:$}=await T.read();if(b){E&&(S.length>0||k)&&(yield{candidates:S.length>0?[{content:{parts:S}}]:[],usageMetadata:k});break}R+=_.decode($,{stream:!0});let I=R.split(`
861
911
  `);R=I.pop();for(let O of I){let P=O.trim();if(!P||!P.startsWith("data: "))continue;let W=!1;if(P==="data: [DONE]")W=!0;else try{let q=JSON.parse(P.substring(6));if(q.error){let F=q.error.metadata?.raw||q.error.message||JSON.stringify(q.error);throw new Error(`OpenRouter Stream Error: ${F}`)}let Q=q.choices?.[0]?.delta,V=q.usage;if(q.choices?.[0]?.finish_reason&&(W=!0),V&&(k={totalTokenCount:V.total_tokens||(V.prompt_tokens||0)+(V.completion_tokens||0),promptTokenCount:V.prompt_tokens||0,candidatesTokenCount:V.completion_tokens||0,cachedContentTokenCount:V.prompt_tokens_details?.cached_tokens||V.prompt_tokens_details?.cache_read_input_tokens||V.cache_read_input_tokens||0,thoughtsTokenCount:V.completion_tokens_details?.reasoning_tokens||0},E=!0),Q){let F=Q.reasoning||(Q.reasoning_details?Q.reasoning_details.map(B=>B.text).join(""):null);F&&(S.push({text:F,thought:!0}),E=!0),Q.content&&(S.push({text:Q.content}),E=!0)}}catch(q){if(q.message&&q.message.startsWith("OpenRouter Stream Error:"))throw q}if((W||Date.now()-C>=150)&&E&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:k},S=[],C=Date.now(),E=!1),W)break}}};import{Ollama as Yc}from"ollama";var mi=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 S of t){let k=S.role==="user"?"user":"assistant",C="",E=[];if(Array.isArray(S.parts)){C=S.parts.map(b=>b.text||"").filter(Boolean).join(`
862
- `);for(let b of S.parts){let $=b.inlineData||b.inline_data;$&&$.data&&E.push($.data)}}else C=S.text||"";if(C||E.length>0){let b={role:k,content:C};E.length>0&&(b.images=E),c.push(b)}}let l=d==="Local"||!e||e==="LOCAL",f={host:l?process.env.OLLAMA_HOST||"http://127.0.0.1:11434":process.env.OLLAMA_HOST||"https://ollama.com"};!l&&e&&(f.headers={Authorization:"Bearer "+e});let m=new Yc(f),g=[],y=null,h=Date.now(),w=!1,x={Fast:!1,Low:"medium",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},T=x[s]!==void 0?x[s]:!0,_={model:n,messages:c,stream:!0,think:T,keep_alive:"10m",options:{temperature:p}},R=await m.chat(_);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 k=S.prompt_cached_count||0;if(!k&&S.prompt_eval_count){let C=S.prompt_eval_duration||0;C>0&&C<5e7&&(k=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:k,thoughtsTokenCount:0},w=!0}(S.done||Date.now()-h>=150&&w)&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],h=Date.now(),w=!1)}w&&(g.length>0||y)&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y})};var Xs=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 S of T.parts)if(S.text)R.push({type:"text",text:S.text});else if(S.inlineData&&a){let k=S.inlineData.mimeType,C=S.inlineData.data;k.startsWith("image/")&&R.push({type:"image_url",image_url:{url:`data:${k};base64,${C}`}})}}else{let S=T.text||"";S&&R.push({type:"text",text:S})}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 u=await vt("https://crof.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(l),signal:i});if(!u.ok){let T=await u.json().catch(()=>({}));throw new Error(`CrofAI Error (${u.status}): ${T.error?.message||u.statusText}`)}let f=u.body.getReader(),m=new TextDecoder,g="",y=[],h=null,w=Date.now(),x=!1;for(;;){let{done:T,value:_}=await f.read();if(T){x&&(y.length>0||h)&&(yield{candidates:y.length>0?[{content:{parts:y}}]:[],usageMetadata:h});break}g+=m.decode(_,{stream:!0});let R=g.split(`
912
+ `);for(let b of S.parts){let $=b.inlineData||b.inline_data;$&&$.data&&E.push($.data)}}else C=S.text||"";if(C||E.length>0){let b={role:k,content:C};E.length>0&&(b.images=E),c.push(b)}}let l=d==="Local"||!e||e==="LOCAL",f={host:l?process.env.OLLAMA_HOST||"http://127.0.0.1:11434":process.env.OLLAMA_HOST||"https://ollama.com"};!l&&e&&(f.headers={Authorization:"Bearer "+e});let m=new Yc(f),g=[],y=null,h=Date.now(),w=!1,x={Fast:!1,Low:"medium",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},T=x[s]!==void 0?x[s]:!0,_={model:n,messages:c,stream:!0,think:T,keep_alive:"10m",options:{temperature:p}},R=await m.chat(_);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 k=S.prompt_cached_count||0;if(!k&&S.prompt_eval_count){let C=S.prompt_eval_duration||0;C>0&&C<5e7&&(k=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:k,thoughtsTokenCount:0},w=!0}(S.done||Date.now()-h>=150&&w)&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],h=Date.now(),w=!1)}w&&(g.length>0||y)&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y})};var Xs=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 S of T.parts)if(S.text)R.push({type:"text",text:S.text});else if(S.inlineData&&a){let k=S.inlineData.mimeType,C=S.inlineData.data;k.startsWith("image/")&&R.push({type:"image_url",image_url:{url:`data:${k};base64,${C}`}})}}else{let S=T.text||"";S&&R.push({type:"text",text:S})}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 u=await It("https://crof.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(l),signal:i});if(!u.ok){let T=await u.json().catch(()=>({}));throw new Error(`CrofAI Error (${u.status}): ${T.error?.message||u.statusText}`)}let f=u.body.getReader(),m=new TextDecoder,g="",y=[],h=null,w=Date.now(),x=!1;for(;;){let{done:T,value:_}=await f.read();if(T){x&&(y.length>0||h)&&(yield{candidates:y.length>0?[{content:{parts:y}}]:[],usageMetadata:h});break}g+=m.decode(_,{stream:!0});let R=g.split(`
863
913
  `);g=R.pop();for(let S of R){let k=S.trim();if(!k||!k.startsWith("data: "))continue;let C=!1;if(k==="data: [DONE]")C=!0;else try{let E=JSON.parse(k.substring(6)),b=E.choices?.[0]?.delta,$=E.usage;if(E.choices?.[0]?.finish_reason&&(C=!0),$&&(h={totalTokenCount:$.total_tokens||($.prompt_tokens||0)+($.completion_tokens||0),promptTokenCount:$.prompt_tokens||0,candidatesTokenCount:$.completion_tokens||0,cachedContentTokenCount:$.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:$.completion_tokens_details?.reasoning_tokens||$.reasoning_tokens||0},x=!0),b){let I=b.reasoning_content||null;I&&(y.push({text:I,thought:!0}),x=!0),b.content&&(y.push({text:b.content}),x=!0)}}catch{}if((C||Date.now()-w>=150)&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:h},y=[],w=Date.now(),x=!1),C)break}Date.now()-w>=150&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:h},y=[],w=Date.now(),x=!1)}};var Js=async function*(e,n,t,o,s,r,a,i,p=1){let d=[];o&&d.push({role:"system",content:o});for(let S of t){let k=S.role==="user"?"user":"assistant",C="";if(Array.isArray(S.parts))for(let E of S.parts)E.text&&(C+=(C?`
864
- `:"")+E.text);else C=S.text||"";d.push({role:k,content:C})}let c={Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},l=n&&n.toLowerCase().includes("qwen3.8-27b"),u=n&&(n.toLowerCase().includes("qwen3.8-27b")||n.toLowerCase().includes("qwen3.6-35b-a3b-fp8")),f={model:n,messages:d.filter(S=>S.content&&String(S.content).trim().length>0),stream:!0,stream_options:{include_usage:!0},temperature:p};l||(f.stream_options={include_usage:!0},c[s]&&(f.reasoning_effort=c[s]));let m=await vt("https://model.inferx.net/endpoints/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(f),signal:i});if(!m.ok){let S=await m.text().catch(()=>""),k="";try{let C=JSON.parse(S);k=C.error?.message||C.error?.detail||C.message||C.detail||(typeof C.error=="string"?C.error:"")||(S&&S!=="{}"?S:"")}catch{k=S}throw(!k||k==="{}")&&(k=m.statusText||"Unknown error"),new Error(`InferX Error (${m.status}): ${k}`)}let g=m.body.getReader(),y=new TextDecoder,h="",w=[],x=null,T=Date.now(),_=!1,R=!0;for(;;){let{done:S,value:k}=await g.read();if(S){_&&(w.length>0||x)&&(yield{candidates:w.length>0?[{content:{parts:w}}]:[],usageMetadata:x});break}h+=y.decode(k,{stream:!0});let C=h.split(`
865
- `);h=C.pop();for(let E of C){let b=E.trim();if(!b||!b.startsWith("data: "))continue;let $=!1;if(b==="data: [DONE]")$=!0;else try{let I=JSON.parse(b.substring(6)),O=I.choices?.[0]?.delta,P=I.usage;if(P&&(x={totalTokenCount:P.total_tokens||(P.prompt_tokens||0)+(P.completion_tokens||0),promptTokenCount:P.prompt_tokens||0,candidatesTokenCount:P.completion_tokens||0,cachedContentTokenCount:P.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:P.completion_tokens_details?.reasoning_tokens||P.reasoning_tokens||0},_=!0),O){let W=O.reasoning||O.reasoning_content||null;if(W&&(w.push({text:W,thought:!0}),_=!0),O.content){let q=O.content;u&&R&&q.length>0&&(q="<think>"+q,R=!1),w.push({text:q}),_=!0}}}catch{}if(($||Date.now()-T>=150||x)&&_&&(yield{candidates:w.length>0?[{content:{parts:[...w]}}]:[],usageMetadata:x},w=[],T=Date.now(),_=!1),$)break}Date.now()-T>=150&&_&&(yield{candidates:w.length>0?[{content:{parts:[...w]}}]:[],usageMetadata:x},w=[],T=Date.now(),_=!1)}};var Qs=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 S of T.parts)if(S.text)R.push({type:"text",text:S.text});else if(S.inlineData&&a){let k=S.inlineData.mimeType,C=S.inlineData.data;k.startsWith("image/")&&R.push({type:"image_url",image_url:{url:`data:${k};base64,${C}`}})}}else{let S=T.text||"";S&&R.push({type:"text",text:S})}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 u=await vt("https://token.sensenova.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(l),signal:i});if(!u.ok){let T=await u.json().catch(()=>({}));throw new Error(`SenseNova Error (${u.status}): ${T.error?.message||u.statusText}`)}let f=u.body.getReader(),m=new TextDecoder,g="",y=[],h=null,w=Date.now(),x=!1;for(;;){let{done:T,value:_}=await f.read();if(T){x&&(y.length>0||h)&&(yield{candidates:y.length>0?[{content:{parts:y}}]:[],usageMetadata:h});break}g+=m.decode(_,{stream:!0});let R=g.split(`
866
- `);g=R.pop();for(let S of R){let k=S.trim();if(!k||!k.startsWith("data: "))continue;let C=!1;if(k==="data: [DONE]")C=!0;else try{let E=JSON.parse(k.substring(6)),b=E.choices?.[0]?.delta,$=E.usage;if($&&(h={totalTokenCount:$.total_tokens||($.prompt_tokens||0)+($.completion_tokens||0),promptTokenCount:$.prompt_tokens||0,candidatesTokenCount:$.completion_tokens||0,cachedContentTokenCount:$.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:$.completion_tokens_details?.reasoning_tokens||$.reasoning_tokens||0},x=!0),b){let I=b.reasoning||b.reasoning_content||null;I&&(y.push({text:I,thought:!0}),x=!0),b.content&&(y.push({text:b.content}),x=!0)}}catch{}if((C||Date.now()-w>=150||h)&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:h},y=[],w=Date.now(),x=!1),C)break}Date.now()-w>=150&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:h},y=[],w=Date.now(),x=!1)}};var Zs=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 S of T.parts)if(S.text)R.push({type:"text",text:S.text});else if(S.inlineData&&a){let k=S.inlineData.mimeType,C=S.inlineData.data;k.startsWith("image/")&&R.push({type:"image_url",image_url:{url:`data:${k};base64,${C}`}})}}else{let S=T.text||"";S&&R.push({type:"text",text:S})}d.push({role:_,content:R.length===1&&R[0].type==="text"?R[0].text:R})}let c={Fast:"minimal",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 u=await vt("https://aihubmix.com/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(l),signal:i});if(!u.ok){let T=await u.json().catch(()=>({}));throw new Error(`AIHubMix Error (${u.status}): ${T.error?.message||u.statusText}`)}let f=u.body.getReader(),m=new TextDecoder,g="",y=[],h=null,w=Date.now(),x=!1;for(;;){let{done:T,value:_}=await f.read();if(T){x&&(y.length>0||h)&&(yield{candidates:y.length>0?[{content:{parts:y}}]:[],usageMetadata:h});break}g+=m.decode(_,{stream:!0});let R=g.split(`
867
- `);g=R.pop();for(let S of R){let k=S.trim();if(!k||!k.startsWith("data: "))continue;let C=!1;if(k==="data: [DONE]")C=!0;else try{let E=JSON.parse(k.substring(6)),b=E.choices?.[0]?.delta,$=E.usage;if(E.choices?.[0]?.finish_reason&&(C=!0),$&&(h={totalTokenCount:$.total_tokens||($.prompt_tokens||0)+($.completion_tokens||0),promptTokenCount:$.prompt_tokens||0,candidatesTokenCount:$.completion_tokens||0,cachedContentTokenCount:$.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:$.completion_tokens_details?.reasoning_tokens||$.reasoning_tokens||0},x=!0),b){let I=b.reasoning_content||null;I&&(y.push({text:I,thought:!0}),x=!0),b.content&&(y.push({text:b.content}),x=!0)}}catch{}if((C||Date.now()-w>=150)&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:h},y=[],w=Date.now(),x=!1),C)break}Date.now()-w>=150&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:h},y=[],w=Date.now(),x=!1)}};gs.config({quiet:!0});gs.config({path:"./fluxflow.env",override:!0,quiet:!0});gs.config({path:"./.fluxflow.env",override:!0,quiet:!0});gs.config({path:`${Qt}/.fluxflow.env`,override:!0,quiet:!0});gs.config({path:`${Qt}/fluxflow.env`,override:!0,quiet:!0});var Vc=/```[\s\S]*?```/g,Xc=/```[\s\S]*$/g,Jc=/`[^`]+`/g,Qc=/^\|.*\|$/gm,Zc=/^[^\w]+|[^\w]+$/g,ed=/[^a-z0-9]/gi,hs=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,td=/\[\s*(?:tool:functions\.|agent:generalist\.)([a-z0-9_]+)\s*\(/gi,nd=/(?:path|targetFile|TargetFile|directory|keyword|id|taskId|title|task)\s*=\s*\\?["']?([^\\"' \),]+)/,xo=/["']/g,rl=/\\/g,od=/<\|channel>thought/gi,sd=/<channel\|>/gi,rd=e=>typeof e!="string"?e:e.replace(od,"<think>").replace(sd,"</think>"),yy=/^\s*(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\]|$)/i,id=(e,n)=>{let t=!1;for(let o=0;o<n;o++)e[o]==="`"&&(t=!t);return t},ad=e=>{let n=/(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\])/gi,t;for(;(t=n.exec(e))!==null;)if(!id(e,t.index))return{index:t.index,length:t[0].length};return{index:-1,length:0}},hi=e=>{if(!e||typeof e!="string")return null;let n=e.match(/^\s*(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought|\[(think|thought|thoughts)\])/i);if(!n)return null;let t=n.index+n[0].length,o=e.substring(t),s=ad(o);if(s.index!==-1){let r=t+s.index+s.length;return{fullBlock:e.substring(0,r),innerContent:o.substring(0,s.index),remainingText:e.substring(r)}}return{fullBlock:e,innerContent:o,remainingText:""}},nn=e=>{if(!e||typeof e!="string")return e;let n=hi(e);return n?n.remainingText.trimStart():e};var ul=/`[^`]*`/g,pl=/`[^`]*$/,il=/<\|\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,ld=/"([^"]+)"\s*:\s*(?:"([^"]*)"|(\d+)|true|false|null)/g,al=/<\|\s*tool_calls_section_begin\s*\|>/gi,ll=/<\|\s*tool_calls_section_end\s*\|>/gi,cd=/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi;var cl=e=>!e||typeof e!="string"?e:e.replace(/(```[\s\S]*?```|`[^`]*`)|(<(?:\w+)(?:[^>]*)>\r?\n?|\r?\n?<\/\w+(?:[^>]*)>)/gi,(n,t)=>t||""),yi=null,er={},bo={key:null,value:null},tn=e=>e&&e.replace(/(?:(\x1b\[\d+m))?([✔✘✖🔍📖→➕↻↷•🛇])(?:(\x1b\[\d+m))?\s*\b(Clicked|Dragged|Scrolled|Typed|Pressed Key|Recaptured Screen|Created|Read Skill|Read Documentation|Searched Documentation|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|Execution Error|Loop Detected|Contacting Ancestors)\b/ig,(n,t,o,s,r)=>`${t||""}${o}${s||""} \x1B[95m${r}\x1B[0m`),dd=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"))})})}}},$t=!1;var fd=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:")),u=c.fullText||c.text||"",f=u.trim();if(!(!f&&!c.binaryPart)){if(l)i.push(f);else if(c.role==="agent"){!p&&i.length>0&&d();let m=u.endsWith(`
868
- `),g=f.toLowerCase().includes("tool:functions.")||f.toLowerCase().includes("agent:generalist.");a.push(f),g&&m?p=!0:p=!1}}}),d()}}return t.length},ud=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),wy=()=>{$t=!0},xy=()=>$t,gi={write_file:"Writing",update_file:"Editing",read_folder:"Reading",view_file:"Reading",exec_command:"Executing Command",web_search:"Searching",web_scrape:"Reading",memory:"Updating Memory",search_keyword:"Searching",file_map:"Generating Map",ask:"User Input",write_pdf:"Creating",write_docx:"Creating",generate_image:"Generating",todo:"Planning",Todo:"Planning",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"},So=(e,n)=>{try{let t=D(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}},wi=e=>e?new fl({apiKey:e}):yi,by=async(e,n,t,o,s={})=>{let{onStatus:i,onMemoryUpdated:p,onBackgroundIncrement:d}=s,{profile:c,thinkingLevel:l,mode:u,janitorModel:f,chatId:m,systemSettings:g,sessionStats:y,aiProvider:h="Google",apiKey:w}=e,x=process.env.NVIDIA_BASE_URL||h==="Ollama"||h==="CrofAI"||h==="InferX"||h==="SenseNova"||h==="AIHubMix"?!1:g?.memory!==!1,_=oe(Pt,[]).map(v=>`- [${v.id}]: ${v.memory}`).join(`
869
- `),R=o.slice(0,-1).filter(v=>v.text&&!v.text.includes("[TOOL RESULT]")&&!v.text.includes("OBSERVATION:")&&!v.text.startsWith("[TERMINAL_RECORD]")&&!v.isTerminalRecord&&!v.isMeta&&!v.isLogo&&!String(v.id).startsWith("welcome")&&!String(v.id).startsWith("logo")).slice(-14).map(v=>{let U=nn(ud(v.text)).replace(/\[tool:functions\..*?\]/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[METADATA \(PRIORITY: DYNAMIC\)\] Time: ([^|\n]+)/g,(Ne,Je)=>`[METADATA (PRIORITY: DYNAMIC)] Time: ${Je.replace(/:\d{2}/g,"")}`).replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[TOOL RESULTS\]/g,"").replace(/\[tool results\]/g,"").replace(/\r?\n\r?\n/g,`
914
+ `:"")+E.text);else C=S.text||"";d.push({role:k,content:C})}let c={Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},l=n&&n.toLowerCase().includes("qwen3.8-27b"),u=n&&(n.toLowerCase().includes("qwen3.8-27b")||n.toLowerCase().includes("qwen3.6-35b-a3b-fp8")),f={model:n,messages:d.filter(S=>S.content&&String(S.content).trim().length>0),stream:!0,stream_options:{include_usage:!0},temperature:p};l||(f.stream_options={include_usage:!0},c[s]&&(f.reasoning_effort=c[s]));let m=await It("https://model.inferx.net/endpoints/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(f),signal:i});if(!m.ok){let S=await m.text().catch(()=>""),k="";try{let C=JSON.parse(S);k=C.error?.message||C.error?.detail||C.message||C.detail||(typeof C.error=="string"?C.error:"")||(S&&S!=="{}"?S:"")}catch{k=S}throw(!k||k==="{}")&&(k=m.statusText||"Unknown error"),new Error(`InferX Error (${m.status}): ${k}`)}let g=m.body.getReader(),y=new TextDecoder,h="",w=[],x=null,T=Date.now(),_=!1,R=!0;for(;;){let{done:S,value:k}=await g.read();if(S){_&&(w.length>0||x)&&(yield{candidates:w.length>0?[{content:{parts:w}}]:[],usageMetadata:x});break}h+=y.decode(k,{stream:!0});let C=h.split(`
915
+ `);h=C.pop();for(let E of C){let b=E.trim();if(!b||!b.startsWith("data: "))continue;let $=!1;if(b==="data: [DONE]")$=!0;else try{let I=JSON.parse(b.substring(6)),O=I.choices?.[0]?.delta,P=I.usage;if(P&&(x={totalTokenCount:P.total_tokens||(P.prompt_tokens||0)+(P.completion_tokens||0),promptTokenCount:P.prompt_tokens||0,candidatesTokenCount:P.completion_tokens||0,cachedContentTokenCount:P.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:P.completion_tokens_details?.reasoning_tokens||P.reasoning_tokens||0},_=!0),O){let W=O.reasoning||O.reasoning_content||null;if(W&&(w.push({text:W,thought:!0}),_=!0),O.content){let q=O.content;u&&R&&q.length>0&&(q="<think>"+q,R=!1),w.push({text:q}),_=!0}}}catch{}if(($||Date.now()-T>=150||x)&&_&&(yield{candidates:w.length>0?[{content:{parts:[...w]}}]:[],usageMetadata:x},w=[],T=Date.now(),_=!1),$)break}Date.now()-T>=150&&_&&(yield{candidates:w.length>0?[{content:{parts:[...w]}}]:[],usageMetadata:x},w=[],T=Date.now(),_=!1)}};var Qs=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 S of T.parts)if(S.text)R.push({type:"text",text:S.text});else if(S.inlineData&&a){let k=S.inlineData.mimeType,C=S.inlineData.data;k.startsWith("image/")&&R.push({type:"image_url",image_url:{url:`data:${k};base64,${C}`}})}}else{let S=T.text||"";S&&R.push({type:"text",text:S})}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 u=await It("https://token.sensenova.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(l),signal:i});if(!u.ok){let T=await u.json().catch(()=>({}));throw new Error(`SenseNova Error (${u.status}): ${T.error?.message||u.statusText}`)}let f=u.body.getReader(),m=new TextDecoder,g="",y=[],h=null,w=Date.now(),x=!1;for(;;){let{done:T,value:_}=await f.read();if(T){x&&(y.length>0||h)&&(yield{candidates:y.length>0?[{content:{parts:y}}]:[],usageMetadata:h});break}g+=m.decode(_,{stream:!0});let R=g.split(`
916
+ `);g=R.pop();for(let S of R){let k=S.trim();if(!k||!k.startsWith("data: "))continue;let C=!1;if(k==="data: [DONE]")C=!0;else try{let E=JSON.parse(k.substring(6)),b=E.choices?.[0]?.delta,$=E.usage;if($&&(h={totalTokenCount:$.total_tokens||($.prompt_tokens||0)+($.completion_tokens||0),promptTokenCount:$.prompt_tokens||0,candidatesTokenCount:$.completion_tokens||0,cachedContentTokenCount:$.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:$.completion_tokens_details?.reasoning_tokens||$.reasoning_tokens||0},x=!0),b){let I=b.reasoning||b.reasoning_content||null;I&&(y.push({text:I,thought:!0}),x=!0),b.content&&(y.push({text:b.content}),x=!0)}}catch{}if((C||Date.now()-w>=150||h)&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:h},y=[],w=Date.now(),x=!1),C)break}Date.now()-w>=150&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:h},y=[],w=Date.now(),x=!1)}};var Zs=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 S of T.parts)if(S.text)R.push({type:"text",text:S.text});else if(S.inlineData&&a){let k=S.inlineData.mimeType,C=S.inlineData.data;k.startsWith("image/")&&R.push({type:"image_url",image_url:{url:`data:${k};base64,${C}`}})}}else{let S=T.text||"";S&&R.push({type:"text",text:S})}d.push({role:_,content:R.length===1&&R[0].type==="text"?R[0].text:R})}let c={Fast:"minimal",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 u=await It("https://aihubmix.com/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(l),signal:i});if(!u.ok){let T=await u.json().catch(()=>({}));throw new Error(`AIHubMix Error (${u.status}): ${T.error?.message||u.statusText}`)}let f=u.body.getReader(),m=new TextDecoder,g="",y=[],h=null,w=Date.now(),x=!1;for(;;){let{done:T,value:_}=await f.read();if(T){x&&(y.length>0||h)&&(yield{candidates:y.length>0?[{content:{parts:y}}]:[],usageMetadata:h});break}g+=m.decode(_,{stream:!0});let R=g.split(`
917
+ `);g=R.pop();for(let S of R){let k=S.trim();if(!k||!k.startsWith("data: "))continue;let C=!1;if(k==="data: [DONE]")C=!0;else try{let E=JSON.parse(k.substring(6)),b=E.choices?.[0]?.delta,$=E.usage;if(E.choices?.[0]?.finish_reason&&(C=!0),$&&(h={totalTokenCount:$.total_tokens||($.prompt_tokens||0)+($.completion_tokens||0),promptTokenCount:$.prompt_tokens||0,candidatesTokenCount:$.completion_tokens||0,cachedContentTokenCount:$.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:$.completion_tokens_details?.reasoning_tokens||$.reasoning_tokens||0},x=!0),b){let I=b.reasoning_content||null;I&&(y.push({text:I,thought:!0}),x=!0),b.content&&(y.push({text:b.content}),x=!0)}}catch{}if((C||Date.now()-w>=150)&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:h},y=[],w=Date.now(),x=!1),C)break}Date.now()-w>=150&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:h},y=[],w=Date.now(),x=!1)}};Yt.config({path:"./.env",override:!0,quiet:!0});Yt.config({path:`${Tt}/.env`,override:!0,quiet:!0});Yt.config({path:"./agents.env",override:!0,quiet:!0});Yt.config({path:"./.agents.env",override:!0,quiet:!0});Yt.config({path:`${Tt}/agents.env`,override:!0,quiet:!0});Yt.config({path:`${Tt}/.agents.env`,override:!0,quiet:!0});Yt.config({path:"./fluxflow.env",override:!0,quiet:!0});Yt.config({path:"./.fluxflow.env",override:!0,quiet:!0});Yt.config({path:`${Tt}/fluxflow.env`,override:!0,quiet:!0});Yt.config({path:`${Tt}/.fluxflow.env`,override:!0,quiet:!0});Yt.config({path:`${Tt}/.env.agents`,override:!0,quiet:!0});Yt.config({path:`${Tt}/.env.fluxflow`,override:!0,quiet:!0});Yt.config({path:"./.env.agents",override:!0,quiet:!0});Yt.config({path:"./.env.fluxflow",override:!0,quiet:!0});var Vc=/```[\s\S]*?```/g,Xc=/```[\s\S]*$/g,Jc=/`[^`]+`/g,Qc=/^\|.*\|$/gm,Zc=/^[^\w]+|[^\w]+$/g,ed=/[^a-z0-9]/gi,gs=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,td=/\[\s*(?:tool:functions\.|agent:generalist\.)([a-z0-9_]+)\s*\(/gi,nd=/(?:path|targetFile|TargetFile|directory|keyword|id|taskId|title|task)\s*=\s*\\?["']?([^\\"' \),]+)/,bo=/["']/g,rl=/\\/g,od=/<\|channel>thought/gi,sd=/<channel\|>/gi,rd=e=>typeof e!="string"?e:e.replace(od,"<think>").replace(sd,"</think>"),yy=/^\s*(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\]|$)/i,id=(e,n)=>{let t=!1;for(let o=0;o<n;o++)e[o]==="`"&&(t=!t);return t},ad=e=>{let n=/(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\])/gi,t;for(;(t=n.exec(e))!==null;)if(!id(e,t.index))return{index:t.index,length:t[0].length};return{index:-1,length:0}},hi=e=>{if(!e||typeof e!="string")return null;let n=e.match(/^\s*(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought|\[(think|thought|thoughts)\])/i);if(!n)return null;let t=n.index+n[0].length,o=e.substring(t),s=ad(o);if(s.index!==-1){let r=t+s.index+s.length;return{fullBlock:e.substring(0,r),innerContent:o.substring(0,s.index),remainingText:e.substring(r)}}return{fullBlock:e,innerContent:o,remainingText:""}},on=e=>{if(!e||typeof e!="string")return e;let n=hi(e);return n?n.remainingText.trimStart():e};var ul=/`[^`]*`/g,pl=/`[^`]*$/,il=/<\|\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,ld=/"([^"]+)"\s*:\s*(?:"([^"]*)"|(\d+)|true|false|null)/g,al=/<\|\s*tool_calls_section_begin\s*\|>/gi,ll=/<\|\s*tool_calls_section_end\s*\|>/gi,cd=/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi;var cl=e=>!e||typeof e!="string"?e:e.replace(/(```[\s\S]*?```|`[^`]*`)|(<(?:\w+)(?:[^>]*)>\r?\n?|\r?\n?<\/\w+(?:[^>]*)>)/gi,(n,t)=>t||""),yi=null,er={},So={key:null,value:null},nn=e=>e&&e.replace(/(?:(\x1b\[\d+m))?([✔✘✖🔍📖→➕↻↷•🛇])(?:(\x1b\[\d+m))?\s*\b(Clicked|Dragged|Scrolled|Typed|Pressed Key|Recaptured Screen|Created|Read Skill|Read Documentation|Searched Documentation|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|Execution Error|Loop Detected|Contacting Ancestors)\b/ig,(n,t,o,s,r)=>`${t||""}${o}${s||""} \x1B[95m${r}\x1B[0m`),dd=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"))})})}}},At=!1;var fd=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:")),u=c.fullText||c.text||"",f=u.trim();if(!(!f&&!c.binaryPart)){if(l)i.push(f);else if(c.role==="agent"){!p&&i.length>0&&d();let m=u.endsWith(`
918
+ `),g=f.toLowerCase().includes("tool:functions.")||f.toLowerCase().includes("agent:generalist.");a.push(f),g&&m?p=!0:p=!1}}}),d()}}return t.length},ud=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),wy=()=>{At=!0},xy=()=>At,gi={write_file:"Writing",update_file:"Editing",read_folder:"Reading",view_file:"Reading",exec_command:"Executing Command",web_search:"Searching",web_scrape:"Reading",memory:"Updating Memory",search_keyword:"Searching",file_map:"Generating Map",ask:"User Input",write_pdf:"Creating",write_docx:"Creating",generate_image:"Generating",todo:"Planning",Todo:"Planning",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"},ko=(e,n)=>{try{let t=L(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}},wi=e=>e?new fl({apiKey:e}):yi,by=async(e,n,t,o,s={})=>{let{onStatus:i,onMemoryUpdated:p,onBackgroundIncrement:d}=s,{profile:c,thinkingLevel:l,mode:u,janitorModel:f,chatId:m,systemSettings:g,sessionStats:y,aiProvider:h="Google",apiKey:w}=e,x=process.env.NVIDIA_BASE_URL||h==="Ollama"||h==="CrofAI"||h==="InferX"||h==="SenseNova"||h==="AIHubMix"?!1:g?.memory!==!1,_=oe(Ft,[]).map(v=>`- [${v.id}]: ${v.memory}`).join(`
919
+ `),R=o.slice(0,-1).filter(v=>v.text&&!v.text.includes("[TOOL RESULT]")&&!v.text.includes("OBSERVATION:")&&!v.text.startsWith("[TERMINAL_RECORD]")&&!v.isTerminalRecord&&!v.isMeta&&!v.isLogo&&!String(v.id).startsWith("welcome")&&!String(v.id).startsWith("logo")).slice(-14).map(v=>{let U=on(ud(v.text)).replace(/\[tool:functions\..*?\]/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[METADATA \(PRIORITY: DYNAMIC\)\] Time: ([^|\n]+)/g,(Ne,Je)=>`[METADATA (PRIORITY: DYNAMIC)] Time: ${Je.replace(/:\d{2}/g,"")}`).replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[TOOL RESULTS\]/g,"").replace(/\[tool results\]/g,"").replace(/\r?\n\r?\n/g,`
870
920
  `).replace(/\n\n/g,`
871
921
  `).replace(/\\n\\n/g,"").trim(),X=v.role==="user"?8192:32768,te=U.substring(0,X);U.length>X&&(te+=`
872
- ... (truncated) ...`);let We=v.role==="user"?te.startsWith("[USER]")?"":"[USER]: ":te.startsWith("[AGENT]")?"":"[AGENT]: ";return{role:v.role==="user"?"user":"model",parts:[{text:`${We}${te}`}]}}),S=o.filter(v=>v.role==="user").length===1,k=n.includes("[TITLE-UPDATE]"),C=Math.random()<.8,E=S||k||C,b=nn(t).trim(),$=ya(_,x,E),I=`${b.replace(/\[tool:functions\..*?\]/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+=`
922
+ ... (truncated) ...`);let We=v.role==="user"?te.startsWith("[USER]")?"":"[USER]: ":te.startsWith("[AGENT]")?"":"[AGENT]: ";return{role:v.role==="user"?"user":"model",parts:[{text:`${We}${te}`}]}}),S=o.filter(v=>v.role==="user").length===1,k=n.includes("[TITLE-UPDATE]"),C=Math.random()<.8,E=S||k||C,b=on(t).trim(),$=ya(_,x,E),I=`${b.replace(/\[tool:functions\..*?\]/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+=`
873
923
  ... (truncated) ...`);let O=n.replace(/\[Prompted on:.*?\]/g,"").trim();I=I.replace(/\r?\n\r?\n/g,`
874
924
  `).replace(/\n\n/g,`
875
925
  `).replace(/\\n\\n/g,"").trim();let P=new Date,q=`[METADATA] Current date and Time: ${`${P.getFullYear()}-${P.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(P.getDate()).padStart(2,"0")}, ${P.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0})}`}
@@ -878,11 +928,11 @@ ${l[7]}`};import{WebSocket as js}from"ws";var zt=null,Uo=!1,Gc="ws://localhost:5
878
928
  ${O.length>8192?`... (truncated) ...
879
929
 
880
930
  `:""}
881
- [AGENT (current turn)]: ${I}`;R.push({role:"user",parts:[{text:q}]});let Q=await fr("NVIDIA"),F=(await en()).quotas?.providerTiers?.NVIDIA==="Free",B="",ee=0,Me=x?12:-1;for(;ee<=Me;)try{if(!await Ii("background",e))return;let v="",U=null,X=!1,te=h;try{let Je=new Promise((et,Re)=>setTimeout(()=>Re(new Error("JANITOR_TIMEOUT")),1e4)),ct=h==="Google"&&ee>=0&&ee<6&&Q&&F,He=h==="DeepSeek"&&ee<4&&Q&&F;X=ct||He,te=X?"NVIDIA":h;let gt=(async()=>{if(h==="OpenRouter"){let et=Te("janitor_open_router"),ye=Vs(w,et,R,$,"Fast",u,!1,null,.7)[Symbol.asyncIterator](),tt=await ye.next();return{iterator:ye,firstResult:tt}}else if(h==="DeepSeek"&&!X){let Re=zs(w,Te("deepseek_fast_fallback"),R,$,"Fast",u,!1,null,.7)[Symbol.asyncIterator](),ye=await Re.next();return{iterator:Re,firstResult:ye}}else if(h==="Mistral"&&!X){let Re=Ks(w,Te("mistral_janitor_fallback"),R,$,"Fast",u,!1,null,.7)[Symbol.asyncIterator](),ye=await Re.next();return{iterator:Re,firstResult:ye}}else if(h==="NVIDIA"||X){let Re=Ys(X?Q:w,Te("nvidia_janitor_fallback"),R,$,"Fast",u,!1,null,.7)[Symbol.asyncIterator](),ye=await Re.next();return{iterator:Re,firstResult:ye}}else if(h==="CrofAI"){let Re=Xs(w,targetModel||Te("crofai_fallback")||"deepseek-v4-flash-0731",R,$,"Fast",u,!1,null,.7)[Symbol.asyncIterator](),ye=await Re.next();return{iterator:Re,firstResult:ye}}else if(h==="InferX"){let Re=Js(w,targetModel||Te("inferx_fallback")||"deepseek-v4-flash",R,$,"Fast",u,!1,null,.7)[Symbol.asyncIterator](),ye=await Re.next();return{iterator:Re,firstResult:ye}}else if(h==="SenseNova"){let Re=Qs(w,targetModel||Te("sensenova_fallback")||"sensenova-6.8-flash-lite",R,$,"Fast",u,!1,null,.7)[Symbol.asyncIterator](),ye=await Re.next();return{iterator:Re,firstResult:ye}}else if(h==="AIHubMix"){let Re=Zs(w,targetModel||Te("aihubmix_fallback")||"gpt-4o-mini",R,$,"Fast",u,!1,null,.7)[Symbol.asyncIterator](),ye=await Re.next();return{iterator:Re,firstResult:ye}}else{let ye=(await wi(w).models.generateContentStream({model:f||(ee===Me?Te("janitor_default"):Te("gemma_janitor_fallback_google")),contents:R,config:{systemInstruction:$,temperature:.7,safetySettings:[{category:eo.HARM_CATEGORY_HARASSMENT,threshold:Zn.BLOCK_NONE},{category:eo.HARM_CATEGORY_HATE_SPEECH,threshold:Zn.BLOCK_NONE},{category:eo.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Zn.BLOCK_NONE},{category:eo.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Zn.BLOCK_NONE}],thinkingConfig:{includeThoughts:!1,thinkingLevel:pt.MINIMAL}}}))[Symbol.asyncIterator](),tt=await ye.next();return{iterator:ye,firstResult:tt}}})();if(process.stdout.isTTY){let ye=(await fo())[m]?.name||"",tt=ye&&!ye.startsWith("flow-")&&!ye.startsWith("Session ")?ye:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${tt}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${tt}\x07`)}let{iterator:ko,firstResult:bt}=await Promise.race([gt,Je]),{value:Ke,done:Rt}=bt;if(!Rt&&Ke){let et=Ke.candidates?.[0]?.content?.parts,Re=et?te==="Google"?et[1]?.text||et[0]?.text||"":et.filter(ye=>ye.text&&!ye.thought).map(ye=>ye.text).join(""):typeof Ke.text=="function"?Ke.text():"";Re&&(v+=Re),U=Ke.usageMetadata;for await(let ye of{[Symbol.asyncIterator]:()=>ko}){let tt=ye.candidates?.[0]?.content?.parts,ys=tt?te==="Google"?tt[1]?.text||tt[0]?.text||"":tt.filter($n=>$n.text&&!$n.thought).map($n=>$n.text).join(""):typeof ye.text=="function"?ye.text():"";ys&&(v+=ys),U=ye.usageMetadata}}}catch(Je){throw Je}if(v){if(B=v,U){let Je=U.totalTokenCount||0,ct=U.cachedContentTokenCount||0,He=(U.candidatesTokenCount||0)+(U.thoughtsTokenCount||0),gt=X?Te("nvidia_janitor_fallback"):te==="DeepSeek"?Te("deepseek_fast_fallback"):te==="OpenRouter"?Te("janitor_open_router"):f||(ee===Me?Te("janitor_default"):Te("gemma_janitor_fallback_google"));await qt("tokens",Je,te,gt),ct>0&&await qt("cachedTokens",ct,te,gt),He>0&&await qt("candidateTokens",He,te,gt)}}else throw new Error("No synthesis generated by Janitor.");d&&(d(),await Mt("background"));let We=nr(B),Ne=!1;for(let Je of We){let ct=Je.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(ct)&&(Ne=!0);let He={chatId:m,sessionId:m,history:o},gt=await ps(ct,Je.args,He);ct.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(bt=>setTimeout(bt,3e3)))}if(!Ne)try{let Je=oe(Pt,[]);if(Je.length>0){let ct=[];for(let He of Je)He.score===void 0&&(He.score=.5),He.score*=.99995,He.score<.05&&(He.score=0),He.score=Math.round(He.score*1e5)/1e5,He.score>0&&ct.push(He);pe(Pt,ct)}}catch{}break}catch(v){ee++;let U=new Date().toLocaleString(),X=v instanceof Error?(()=>{try{return JSON.parse(JSON.parse(v.message).error.message).error.message}catch{return String(v)}})():String(v);await new Promise(Ne=>setTimeout(Ne,1e3));let te=Z.join(mn,"janitor");if(Fe.existsSync(te)||Fe.mkdirSync(te,{recursive:!0}),Fe.appendFileSync(Z.join(te,"error.log"),`ERROR [Attempt ${ee}/${Me+1}] [${U}]: ${X}
931
+ [AGENT (current turn)]: ${I}`;R.push({role:"user",parts:[{text:q}]});let Q=await fr("NVIDIA"),F=(await tn()).quotas?.providerTiers?.NVIDIA==="Free",B="",ee=0,Me=x?12:-1;for(;ee<=Me;)try{if(!await Ii("background",e))return;let v="",U=null,X=!1,te=h;try{let Je=new Promise((et,Re)=>setTimeout(()=>Re(new Error("JANITOR_TIMEOUT")),1e4)),ct=h==="Google"&&ee>=0&&ee<6&&Q&&F,He=h==="DeepSeek"&&ee<4&&Q&&F;X=ct||He,te=X?"NVIDIA":h;let gt=(async()=>{if(h==="OpenRouter"){let et=Te("janitor_open_router"),ye=Vs(w,et,R,$,"Fast",u,!1,null,.7)[Symbol.asyncIterator](),tt=await ye.next();return{iterator:ye,firstResult:tt}}else if(h==="DeepSeek"&&!X){let Re=zs(w,Te("deepseek_fast_fallback"),R,$,"Fast",u,!1,null,.7)[Symbol.asyncIterator](),ye=await Re.next();return{iterator:Re,firstResult:ye}}else if(h==="Mistral"&&!X){let Re=Ks(w,Te("mistral_janitor_fallback"),R,$,"Fast",u,!1,null,.7)[Symbol.asyncIterator](),ye=await Re.next();return{iterator:Re,firstResult:ye}}else if(h==="NVIDIA"||X){let Re=Ys(X?Q:w,Te("nvidia_janitor_fallback"),R,$,"Fast",u,!1,null,.7)[Symbol.asyncIterator](),ye=await Re.next();return{iterator:Re,firstResult:ye}}else if(h==="CrofAI"){let Re=Xs(w,targetModel||Te("crofai_fallback")||"deepseek-v4-flash-0731",R,$,"Fast",u,!1,null,.7)[Symbol.asyncIterator](),ye=await Re.next();return{iterator:Re,firstResult:ye}}else if(h==="InferX"){let Re=Js(w,targetModel||Te("inferx_fallback")||"deepseek-v4-flash",R,$,"Fast",u,!1,null,.7)[Symbol.asyncIterator](),ye=await Re.next();return{iterator:Re,firstResult:ye}}else if(h==="SenseNova"){let Re=Qs(w,targetModel||Te("sensenova_fallback")||"sensenova-6.8-flash-lite",R,$,"Fast",u,!1,null,.7)[Symbol.asyncIterator](),ye=await Re.next();return{iterator:Re,firstResult:ye}}else if(h==="AIHubMix"){let Re=Zs(w,targetModel||Te("aihubmix_fallback")||"gpt-4o-mini",R,$,"Fast",u,!1,null,.7)[Symbol.asyncIterator](),ye=await Re.next();return{iterator:Re,firstResult:ye}}else{let ye=(await wi(w).models.generateContentStream({model:f||(ee===Me?Te("janitor_default"):Te("gemma_janitor_fallback_google")),contents:R,config:{systemInstruction:$,temperature:.7,safetySettings:[{category:to.HARM_CATEGORY_HARASSMENT,threshold:eo.BLOCK_NONE},{category:to.HARM_CATEGORY_HATE_SPEECH,threshold:eo.BLOCK_NONE},{category:to.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:eo.BLOCK_NONE},{category:to.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:eo.BLOCK_NONE}],thinkingConfig:{includeThoughts:!1,thinkingLevel:pt.MINIMAL}}}))[Symbol.asyncIterator](),tt=await ye.next();return{iterator:ye,firstResult:tt}}})();if(process.stdout.isTTY){let ye=(await uo())[m]?.name||"",tt=ye&&!ye.startsWith("flow-")&&!ye.startsWith("Session ")?ye:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${tt}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${tt}\x07`)}let{iterator:To,firstResult:bt}=await Promise.race([gt,Je]),{value:Ke,done:Et}=bt;if(!Et&&Ke){let et=Ke.candidates?.[0]?.content?.parts,Re=et?te==="Google"?et[1]?.text||et[0]?.text||"":et.filter(ye=>ye.text&&!ye.thought).map(ye=>ye.text).join(""):typeof Ke.text=="function"?Ke.text():"";Re&&(v+=Re),U=Ke.usageMetadata;for await(let ye of{[Symbol.asyncIterator]:()=>To}){let tt=ye.candidates?.[0]?.content?.parts,ys=tt?te==="Google"?tt[1]?.text||tt[0]?.text||"":tt.filter(An=>An.text&&!An.thought).map(An=>An.text).join(""):typeof ye.text=="function"?ye.text():"";ys&&(v+=ys),U=ye.usageMetadata}}}catch(Je){throw Je}if(v){if(B=v,U){let Je=U.totalTokenCount||0,ct=U.cachedContentTokenCount||0,He=(U.candidatesTokenCount||0)+(U.thoughtsTokenCount||0),gt=X?Te("nvidia_janitor_fallback"):te==="DeepSeek"?Te("deepseek_fast_fallback"):te==="OpenRouter"?Te("janitor_open_router"):f||(ee===Me?Te("janitor_default"):Te("gemma_janitor_fallback_google"));await zt("tokens",Je,te,gt),ct>0&&await zt("cachedTokens",ct,te,gt),He>0&&await zt("candidateTokens",He,te,gt)}}else throw new Error("No synthesis generated by Janitor.");d&&(d(),await vt("background"));let We=nr(B),Ne=!1;for(let Je of We){let ct=Je.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(ct)&&(Ne=!0);let He={chatId:m,sessionId:m,history:o},gt=await ms(ct,Je.args,He);ct.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(bt=>setTimeout(bt,3e3)))}if(!Ne)try{let Je=oe(Ft,[]);if(Je.length>0){let ct=[];for(let He of Je)He.score===void 0&&(He.score=.5),He.score*=.99995,He.score<.05&&(He.score=0),He.score=Math.round(He.score*1e5)/1e5,He.score>0&&ct.push(He);pe(Ft,ct)}}catch{}break}catch(v){ee++;let U=new Date().toLocaleString(),X=v instanceof Error?(()=>{try{return JSON.parse(JSON.parse(v.message).error.message).error.message}catch{return String(v)}})():String(v);await new Promise(Ne=>setTimeout(Ne,1e3));let te=Z.join(hn,"janitor");if(Fe.existsSync(te)||Fe.mkdirSync(te,{recursive:!0}),Fe.appendFileSync(Z.join(te,"error.log"),`ERROR [Attempt ${ee}/${Me+1}] [${U}]: ${X}
882
932
 
883
- `),ee>Me)break;let We=Math.min(750*Math.pow(2,ee-1),5e3);await new Promise(Ne=>setTimeout(Ne,We))}if(ee){let v=Z.join(mn,"janitor");Fe.appendFileSync(Z.join(v,"error.log"),`-----------------------------------------------------------------------------
933
+ `),ee>Me)break;let We=Math.min(750*Math.pow(2,ee-1),5e3);await new Promise(Ne=>setTimeout(Ne,We))}if(ee){let v=Z.join(hn,"janitor");Fe.appendFileSync(Z.join(v,"error.log"),`-----------------------------------------------------------------------------
884
934
 
885
- `)}if(process.stdout.isTTY)try{let X=(await fo())[m]?.name||"",te=X&&!X.startsWith("flow-")&&!X.startsWith("Session ")?X:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${te}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${te}\x07`)}catch{process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")}},pd=e=>{let n=nn(e),t=Do?n:n.replace(ul,s=>" ".repeat(s.length)).replace(pl,s=>" ".repeat(s.length));hs.lastIndex=0;let o;for(;(o=hs.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,hs.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}},ml=(e,n=!0)=>{let t=hs;t.lastIndex=0;let o="",s=0,r;for(;(r=t.exec(e))!==null;){let a=e.substring(s,r.index);o+=n&&s===0?nn(a):a;let i=r.index+r[0].length-1,p=0,d=null,c=-1;for(let l=i;l<e.length;l++){let u=e[l];if(d){if(u===d){let f=0;for(let m=l-1;m>=0&&e[m]==="\\";m--)f++;f%2===0&&(d=null)}}else if(u==='"'||u==="'"||u==="`")d=u;else if(u==="(")p++;else if(u===")"&&(p--,p===0)){let f=l+1;for(;f<e.length&&/\s/.test(e[f]);)f++;if(f<e.length&&e[f]==="]"){c=f;break}}}if(c!==-1)o+="[tool:functions."+r[1]+"()]",s=c+1,t.lastIndex=s;else{o+="[tool:functions."+r[1]+"(",s=e.length;break}}return s<e.length&&(o+=n&&s===0?nn(e.substring(s)):e.substring(s)),o},md=(e,n,t)=>{let o=hs;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 u=p;u<e.length;u++){let f=e[u];if(c){if(f===c){let m=0;for(let g=u-1;g>=0&&e[g]==="\\";g--)m++;m%2===0&&(c=null)}}else if(f==='"'||f==="'"||f==="`")c=f;else if(f==="(")d++;else if(f===")"&&(d--,d===0)){let m=u+1;for(;m<e.length&&/\s/.test(e[m]);)m++;if(m<e.length&&e[m]==="]"){l=m;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},dl=e=>ml(e,!0),hd=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",askuser:"AskUser",ask:"AskUser"},t=s=>s.split("_").map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join("");il.lastIndex=0;let o=e.replace(il,(s,r,a)=>{let i="";try{let c=JSON.parse(a.trim());c&&typeof c=="object"&&(i=Object.entries(c).map(([u,f])=>{let m=typeof f=="string"?f:JSON.stringify(f);return`${u}=${JSON.stringify(m)}`}).join(", "))}catch{let l=[],u=ld;u.lastIndex=0;let f;for(;(f=u.exec(a))!==null;){let m=f[1],g=f[2]!==void 0?f[2]:f[0].split(":").slice(1).join(":").trim();l.push(`${m}=${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 al.lastIndex=0,ll.lastIndex=0,o=o.replace(al,""),o=o.replace(ll,""),o},gd=/(?:path|query|url|keyword|command|method|title|task|id)\s*=\s*['"`]?\s*\.\.\.\s*['"`]?/i,yd=/^['"`]?\s*\.\.\.\s*['"`]?$/,Bn=e=>{if(e==null)return!1;let n=String(e).trim();return n==="..."||n==="\u2026"||yd.test(n)},nr=e=>{if(!e)return[];let n=hd(e),t=nn(n),o=[],s=Do?t:t.replace(ul,i=>" ".repeat(i.length)).replace(pl,i=>" ".repeat(i.length)),r=td;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,u=-1;for(let f=p;f<s.length;f++){let m=t[f];if(c){if(m===c){let g=0;for(let y=f-1;y>=0&&t[y]==="\\";y--)g++;g%2===0&&(c=null)}}else if(m==='"'||m==="'"||m==="`")c=m;else if(m==="(")d++;else if(m===")"&&(d--,d===0)){u=f;let g=f+1;for(;g<s.length&&/\s/.test(s[g]);)g++;if(g<s.length&&s[g]==="]"){l=g;break}}}if(l!==-1){let f=t.substring(p+1,u),m=t.substring(a.index,l+1),g=D(f);Bn(g.path)||Bn(g.query)||Bn(g.url)||Bn(g.keyword)||Bn(g.command)||Bn(g.method)||Bn(g.title)||Bn(g.task)||Bn(g.id)||gd.test(f)||o.push({fullMatch:m,toolName:i.trim(),args:f.trim()}),r.lastIndex=l+1}}return o},Sy=(e,n={})=>{if(!e)return null;if(er=n,yi=new fl({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}}}},tr=async(e,n,t,o,s="Fast",r=.75,a="agent")=>dd(async()=>{let{aiProvider:i="Google",apiKey:p,mode:d}=e,c="",l=null,u=typeof t=="string"?[{role:"user",parts:[{text:t}]}]:t,f=new AbortController,m=f.signal,g=setInterval(()=>{$t&&(f.abort(),clearInterval(g))},100);try{let y;i==="Ollama"?y=mi(p,n,u,o,s,d,At(n),m,r,systemSettings?.ollamaEndpoint||"Cloud"):i==="OpenRouter"?y=Vs(p,n,u,o,s,d,At(n),m,r):i==="DeepSeek"?y=zs(p,n,u,o,s,d,At(n),m,r):i==="Mistral"?y=Ks(p,n,u,o,s,d,At(n),m,r):i==="NVIDIA"?y=Ys(p,n,u,o,s,d,At(n),m,r):i==="CrofAI"?y=Xs(p,n,u,o,s,d,At(n),m,r):i==="InferX"?y=Js(p,n,u,o,s,d,At(n),m,r):i==="SenseNova"?y=Qs(p,n,u,o,s,d,At(n),m,r):i==="AIHubMix"?y=Zs(p,n,u,o,s,d,At(n),m,r):y=await wi(p).models.generateContentStream({model:n,contents:u,config:{systemInstruction:o,temperature:r,thinkingConfig:(()=>{let x=(n||"").toLowerCase(),T=x.includes("gemma-4")||x.startsWith("gemma"),_=x.includes("gemini-3");if(T||_)return T?s.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:pt.MINIMAL}:{includeThoughts:!0,thinkingLevel:pt.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:x.includes("pro")?pt.LOW:pt.MINIMAL,Low:pt.LOW,Medium:pt.MEDIUM,Standard:pt.MEDIUM,High:pt.HIGH,xHigh:pt.HIGH}[s]||pt.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:m});for await(let h of y){if($t)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(h.candidates?.[0]?.content?.parts)for(let T of h.candidates[0].content.parts)T.text&&!T.thought&&(c+=T.text,w+=T.text);let x=w?w.trim().split(/\s+/).filter(Boolean).length:0;e&&typeof e.onTokenChunk=="function"&&e.onTokenChunk(w,x),h.usageMetadata&&(l=h.usageMetadata)}}finally{clearInterval(g)}if(l){let y=l.totalTokenCount||0,h=l.cachedContentTokenCount||0,w=(l.candidatesTokenCount||0)+(l.thoughtsTokenCount||0);await qt("tokens",y,i,n),h>0&&await qt("cachedTokens",h,i,n),w>0&&await qt("candidateTokens",w,i,n),e&&typeof e.onUsage=="function"&&e.onUsage({totalTokenCount:y,cachedContentTokenCount:h,candidatesTokenCount:w})}return await Mt("agent",i),{text:c,usageMetadata:l}}),wd=async(e,n,t=null)=>{t=t||oe(Zt,{});try{let{aiProvider:o="Google"}=n;if(Object.values(t).flat().length<=5)return;let r=Object.keys(t).filter(u=>u!==e&&Array.isArray(t[u])&&t[u].length>2);if(r.length===0)return;let a=`You are a silent background process for the FluxFlow CLI Agent.
935
+ `)}if(process.stdout.isTTY)try{let X=(await uo())[m]?.name||"",te=X&&!X.startsWith("flow-")&&!X.startsWith("Session ")?X:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${te}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${te}\x07`)}catch{process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")}},pd=e=>{let n=on(e),t=Do?n:n.replace(ul,s=>" ".repeat(s.length)).replace(pl,s=>" ".repeat(s.length));gs.lastIndex=0;let o;for(;(o=gs.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,gs.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}},ml=(e,n=!0)=>{let t=gs;t.lastIndex=0;let o="",s=0,r;for(;(r=t.exec(e))!==null;){let a=e.substring(s,r.index);o+=n&&s===0?on(a):a;let i=r.index+r[0].length-1,p=0,d=null,c=-1;for(let l=i;l<e.length;l++){let u=e[l];if(d){if(u===d){let f=0;for(let m=l-1;m>=0&&e[m]==="\\";m--)f++;f%2===0&&(d=null)}}else if(u==='"'||u==="'"||u==="`")d=u;else if(u==="(")p++;else if(u===")"&&(p--,p===0)){let f=l+1;for(;f<e.length&&/\s/.test(e[f]);)f++;if(f<e.length&&e[f]==="]"){c=f;break}}}if(c!==-1)o+="[tool:functions."+r[1]+"()]",s=c+1,t.lastIndex=s;else{o+="[tool:functions."+r[1]+"(",s=e.length;break}}return s<e.length&&(o+=n&&s===0?on(e.substring(s)):e.substring(s)),o},md=(e,n,t)=>{let o=gs;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 u=p;u<e.length;u++){let f=e[u];if(c){if(f===c){let m=0;for(let g=u-1;g>=0&&e[g]==="\\";g--)m++;m%2===0&&(c=null)}}else if(f==='"'||f==="'"||f==="`")c=f;else if(f==="(")d++;else if(f===")"&&(d--,d===0)){let m=u+1;for(;m<e.length&&/\s/.test(e[m]);)m++;if(m<e.length&&e[m]==="]"){l=m;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},dl=e=>ml(e,!0),hd=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",askuser:"AskUser",ask:"AskUser"},t=s=>s.split("_").map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join("");il.lastIndex=0;let o=e.replace(il,(s,r,a)=>{let i="";try{let c=JSON.parse(a.trim());c&&typeof c=="object"&&(i=Object.entries(c).map(([u,f])=>{let m=typeof f=="string"?f:JSON.stringify(f);return`${u}=${JSON.stringify(m)}`}).join(", "))}catch{let l=[],u=ld;u.lastIndex=0;let f;for(;(f=u.exec(a))!==null;){let m=f[1],g=f[2]!==void 0?f[2]:f[0].split(":").slice(1).join(":").trim();l.push(`${m}=${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 al.lastIndex=0,ll.lastIndex=0,o=o.replace(al,""),o=o.replace(ll,""),o},gd=/(?:path|query|url|keyword|command|method|title|task|id)\s*=\s*['"`]?\s*\.\.\.\s*['"`]?/i,yd=/^['"`]?\s*\.\.\.\s*['"`]?$/,Wn=e=>{if(e==null)return!1;let n=String(e).trim();return n==="..."||n==="\u2026"||yd.test(n)},nr=e=>{if(!e)return[];let n=hd(e),t=on(n),o=[],s=Do?t:t.replace(ul,i=>" ".repeat(i.length)).replace(pl,i=>" ".repeat(i.length)),r=td;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,u=-1;for(let f=p;f<s.length;f++){let m=t[f];if(c){if(m===c){let g=0;for(let y=f-1;y>=0&&t[y]==="\\";y--)g++;g%2===0&&(c=null)}}else if(m==='"'||m==="'"||m==="`")c=m;else if(m==="(")d++;else if(m===")"&&(d--,d===0)){u=f;let g=f+1;for(;g<s.length&&/\s/.test(s[g]);)g++;if(g<s.length&&s[g]==="]"){l=g;break}}}if(l!==-1){let f=t.substring(p+1,u),m=t.substring(a.index,l+1),g=L(f);Wn(g.path)||Wn(g.query)||Wn(g.url)||Wn(g.keyword)||Wn(g.command)||Wn(g.method)||Wn(g.title)||Wn(g.task)||Wn(g.id)||gd.test(f)||o.push({fullMatch:m,toolName:i.trim(),args:f.trim()}),r.lastIndex=l+1}}return o},Sy=(e,n={})=>{if(!e)return null;if(er=n,yi=new fl({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}}}},tr=async(e,n,t,o,s="Fast",r=.75,a="agent")=>dd(async()=>{let{aiProvider:i="Google",apiKey:p,mode:d}=e,c="",l=null,u=typeof t=="string"?[{role:"user",parts:[{text:t}]}]:t,f=new AbortController,m=f.signal,g=setInterval(()=>{At&&(f.abort(),clearInterval(g))},100);try{let y;i==="Ollama"?y=mi(p,n,u,o,s,d,Mt(n),m,r,systemSettings?.ollamaEndpoint||"Cloud"):i==="OpenRouter"?y=Vs(p,n,u,o,s,d,Mt(n),m,r):i==="DeepSeek"?y=zs(p,n,u,o,s,d,Mt(n),m,r):i==="Mistral"?y=Ks(p,n,u,o,s,d,Mt(n),m,r):i==="NVIDIA"?y=Ys(p,n,u,o,s,d,Mt(n),m,r):i==="CrofAI"?y=Xs(p,n,u,o,s,d,Mt(n),m,r):i==="InferX"?y=Js(p,n,u,o,s,d,Mt(n),m,r):i==="SenseNova"?y=Qs(p,n,u,o,s,d,Mt(n),m,r):i==="AIHubMix"?y=Zs(p,n,u,o,s,d,Mt(n),m,r):y=await wi(p).models.generateContentStream({model:n,contents:u,config:{systemInstruction:o,temperature:r,thinkingConfig:(()=>{let x=(n||"").toLowerCase(),T=x.includes("gemma-4")||x.startsWith("gemma"),_=x.includes("gemini-3");if(T||_)return T?s.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:pt.MINIMAL}:{includeThoughts:!0,thinkingLevel:pt.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:x.includes("pro")?pt.LOW:pt.MINIMAL,Low:pt.LOW,Medium:pt.MEDIUM,Standard:pt.MEDIUM,High:pt.HIGH,xHigh:pt.HIGH}[s]||pt.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:m});for await(let h of y){if(At)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(h.candidates?.[0]?.content?.parts)for(let T of h.candidates[0].content.parts)T.text&&!T.thought&&(c+=T.text,w+=T.text);let x=w?w.trim().split(/\s+/).filter(Boolean).length:0;e&&typeof e.onTokenChunk=="function"&&e.onTokenChunk(w,x),h.usageMetadata&&(l=h.usageMetadata)}}finally{clearInterval(g)}if(l){let y=l.totalTokenCount||0,h=l.cachedContentTokenCount||0,w=(l.candidatesTokenCount||0)+(l.thoughtsTokenCount||0);await zt("tokens",y,i,n),h>0&&await zt("cachedTokens",h,i,n),w>0&&await zt("candidateTokens",w,i,n),e&&typeof e.onUsage=="function"&&e.onUsage({totalTokenCount:y,cachedContentTokenCount:h,candidatesTokenCount:w})}return await vt("agent",i),{text:c,usageMetadata:l}}),wd=async(e,n,t=null)=>{t=t||oe(en,{});try{let{aiProvider:o="Google"}=n;if(Object.values(t).flat().length<=5)return;let r=Object.keys(t).filter(u=>u!==e&&Array.isArray(t[u])&&t[u].length>2);if(r.length===0)return;let a=`You are a silent background process for the FluxFlow CLI Agent.
886
936
  Your task is to summarize or merge temporary context memories from one or more past conversation sessions.
887
937
  For each Chat ID provided, you must output a tool call to save the consolidated summary.
888
938
 
@@ -897,7 +947,7 @@ Guidelines:
897
947
 
898
948
  Chats to process:
899
949
 
900
- `,i=oe(Ln,{});for(let u of r){let m=t[u].map(y=>`- ${y}`).join(`
950
+ `,i=oe(Pn,{});for(let u of r){let m=t[u].map(y=>`- ${y}`).join(`
901
951
  `),g=i[u];a+=`[Chat ID: ${u}]
902
952
  `,g?(a+=`- Existing Summary: "${g}"
903
953
  `,a+=`
@@ -907,7 +957,7 @@ ${m}
907
957
  `):a+=`-- Individual Memories:
908
958
  ${m}
909
959
 
910
- `}let p=0,d=5,c=!1,l=Te("gemma_janitor_fallback_google");for(o==="OpenRouter"&&(l=Te("janitor_open_router")),o==="DeepSeek"&&(l=Te("deepseek_level_1")),o==="Mistral"&&(l=Te("mistral_level_1")),o==="NVIDIA"&&(l=Te("nvidia_janitor_fallback")),o==="CrofAI"&&(l=Te("crofai_fallback")),o==="InferX"&&(l=Te("inferx_fallback")),o==="SenseNova"&&(l=Te("sensenova_fallback")),o==="AIHubMix"&&(l=Te("aihubmix_fallback"));p<=d&&!c;){p++;try{let f=(await tr(n,l,a,null,"Fast",.75,"background")).text||"",m=nr(f);if(m.length===0)throw new Error("No tool calls detected in synthesis response");for(let g of m){let y=g.toolName;["saveSummary","saveSumary","SaveSummary","SaveSumary"].includes(y)&&await ps(y,g.args,{chatId:e})}c=!0}catch(u){if(p>=d)throw new Error(`Failed after ${d} attempts. Last error: ${u.message}`)}}}catch(o){let s=o instanceof Error?(()=>{try{return JSON.parse(JSON.parse(o.message).error.message).error.message}catch{return String(o)}})():String(o),r=Z.join(mn,"janitor");Fe.existsSync(r)||Fe.mkdirSync(r,{recursive:!0}),Fe.appendFileSync(Z.join(r,"error.log"),`[${new Date().toLocaleString()}] Past memory batch consolidation error: ${s}
960
+ `}let p=0,d=5,c=!1,l=Te("gemma_janitor_fallback_google");for(o==="OpenRouter"&&(l=Te("janitor_open_router")),o==="DeepSeek"&&(l=Te("deepseek_level_1")),o==="Mistral"&&(l=Te("mistral_level_1")),o==="NVIDIA"&&(l=Te("nvidia_janitor_fallback")),o==="CrofAI"&&(l=Te("crofai_fallback")),o==="InferX"&&(l=Te("inferx_fallback")),o==="SenseNova"&&(l=Te("sensenova_fallback")),o==="AIHubMix"&&(l=Te("aihubmix_fallback"));p<=d&&!c;){p++;try{let f=(await tr(n,l,a,null,"Fast",.75,"background")).text||"",m=nr(f);if(m.length===0)throw new Error("No tool calls detected in synthesis response");for(let g of m){let y=g.toolName;["saveSummary","saveSumary","SaveSummary","SaveSumary"].includes(y)&&await ms(y,g.args,{chatId:e})}c=!0}catch(u){if(p>=d)throw new Error(`Failed after ${d} attempts. Last error: ${u.message}`)}}}catch(o){let s=o instanceof Error?(()=>{try{return JSON.parse(JSON.parse(o.message).error.message).error.message}catch{return String(o)}})():String(o),r=Z.join(hn,"janitor");Fe.existsSync(r)||Fe.mkdirSync(r,{recursive:!0}),Fe.appendFileSync(Z.join(r,"error.log"),`[${new Date().toLocaleString()}] Past memory batch consolidation error: ${s}
911
961
  `)}},xd=async(e,n,t=!1)=>{let{chatId:o,aiProvider:s="Google"}=e,r=Z.join(Ts,"chat-summaries.json"),a=f=>f.filter(m=>(m.role==="user"||m.role==="agent"||m.role==="system")&&m.role!=="think"&&!m.isVisualFeedback&&!m.isMeta&&!m.isTerminalRecord&&!(m.text&&m.text.includes("[TERMINAL_RECORD]"))&&!String(m.id).startsWith("welcome")).map(m=>{let g=m.fullText||m.text||"",y=m.role==="system"||g.startsWith("[TOOL RESULT]:")||m.text&&m.text.startsWith("[TOOL RESULT]:"),h=g;return y&&(g.includes("[TOOL RESULT]:")||m.text&&m.text.includes("[TOOL RESULT]:"))?h="[TOOL RESULT]: ...truncated for summary":h=h.replace(/(\[(?:tool|agent):[a-zA-Z0-9_\.]+)\([\s\S]*?\)(\])/g,"$1(...)$2"),`[${y?"TOOL":m.role==="agent"?"AGENT":"USER"}]: ${h}`}).join(`
912
962
 
913
963
  `),i=async(f,m)=>{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=m?`Here is the previous summary:
@@ -919,22 +969,22 @@ ${f}
919
969
  Provide a new consolidated summary of the entire session.`:`Here is the conversation history:
920
970
  ${f}
921
971
 
922
- Provide a consolidated summary of the entire session.`,h=Te("gemma_janitor_fallback_google");s==="OpenRouter"&&(h=Te("janitor_open_router")),s==="DeepSeek"&&(h=Te("deepseek_level_1")),s==="Mistral"&&(h=Te("mistral_level_1")),s==="NVIDIA"&&(h=Te("nvidia_chat_summarizer_fallback")),s==="CrofAI"&&(h=Te("crofai_fallback")),s==="InferX"&&(h=Te("inferx_fallback")),s==="SenseNova"&&(h=Te("sensenova_fallback")),s==="AIHubMix"&&(h=Te("aihubmix_fallback"));let w=0,x=!1,T=null;for(;w<=3&&!x;){w++;try{T=await tr(e,h,y,g,"Fast"),x=!0}catch{if(w>3){if(s==="Google")try{let R=Te("general_fallback");return(await tr(e,R,y,g,"Fast")).text||""}catch{return""}return""}}}return T&&T.text||""},p=a(n),d=oe(r,{}),c=d[o]||{summary:"",historyLength:0};typeof c=="string"&&(c={summary:c,historyLength:0});let l=c.summary||"",u=await i(p,l);if(u){c.summary=u;let f=fd(n);return t?c.historyLength=(c.historyLength||0)+f:c.historyLength=f,d[o]=c,pe(r,d),u}return null},ky=e=>{try{let n=Z.join(Ts,"chat-summaries.json");if(Fe.existsSync(n)){let t=oe(n,{});t[e]&&(delete t[e],pe(n,t))}}catch{}},Ty=async function*(e,n,t,o,s){let{profile:r,thinkingLevel:a,mode:i,janitorModel:p,chatId:d,isPlayground:c,systemSettings:l,sessionStats:u,aiProvider:f="Google",apiTier:m,wildcardTooling:g}=t,y=At(e);if(!yi&&f==="Google")throw new Error("AI not initialized");let h=process.env.NVIDIA_BASE_URL||t?.aiProvider==="Ollama"||t?.aiProvider==="CrofAI"||t?.aiProvider==="InferX"||t?.aiProvider==="SenseNova"||t?.aiProvider==="AIHubMix"?!1:l?.memory!==!1,w=n[n.length-1].text,x=Z.join(Ts,"chat-summaries.json"),T=!1,_=n.filter(E=>E.role==="user").length===1,R=w.includes("[TITLE-UPDATE]"),S=_||R,k=w.replace(/\[TITLE-UPDATE\]/g,"").trim();k=k.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),yield{type:"status",content:"[start]"},yield{type:"status",content:"Gathering Context"},await ht.startTransaction(d,k),l?.advanceRollback&&await Qn.takeInitialSnapshot(d),$t=!1;let C=null;try{let E=new AbortController;C=setInterval(()=>{$t&&(E.abort(),C&&(clearInterval(C),C=null))},400);let b=[...n.slice(0,-1)];{let Pe=oe(x,{})[d]||{summary:"",historyLength:0};if(Pe.summary&&Pe.historyLength>0){let on=0,Ee=[];for(let nt=0;nt<b.length;nt++){let qe=b[nt];(qe.role==="user"||qe.role==="agent"||qe.role==="system")&&!String(qe.id).startsWith("welcome")&&!qe.isMeta&&on++,on>Pe.historyLength&&Ee.push(qe)}b=Ee}}b=b.map(z=>{if(z.role==="user"&&z.text){let Pe=z.text.match(/\[USER\]([\s\S]*?)\[\/USER\]/);if(Pe)return{...z,text:Pe[1].trim()}}return{...z}});let $=process.env.HIGH_CONTEXT,I=process.env.GOOGLE_GEMMA_NONSENSE==="true"||process.env.GOOGLE_GEMMA_NONSENSE===!0||!1,O=255e3,P=26e4;if($&&$!=="false"){let z=parseInt($,10);!isNaN(z)&&z>=0&&z<=1e6&&(P=z,O=Math.round(z*.85))}if((f==="NVIDIA"&&(e?.includes("gpt")||e?.includes("qwen")||e?.includes("medium")||e.includes("muse"))||f==="Mistral")&&(O=122e3,P=126e3),f==="Google"&&e?.includes("gemma")&&I&&(O=14e3,P=16e3),f==="Ollama"&&(u?.tokens||0)>O){yield{type:"text",content:"\u2726 Maximum Context Limit Reached. Start a new chat."};return}if(f!=="Ollama"&&(u?.tokens||0)>O&&(yield{type:"status_history",content:"Context Limit Reached. Condensing session history..."},await xd(t,b,!0)&&(b=[],T=!0)),_&&h){let z=oe(Zt,{});Object.values(z).flat().length>5&&(yield{type:"status",content:"Condensing past chat memories"},await wd(d,t,z))}let W=oe(Zt,{}),q=oe(Ln,{}),Q=Object.entries(W).filter(([z])=>z!==d).flatMap(([z,Pe])=>Pe),F=[...Object.entries(q).filter(([z])=>z!==d).slice(-20).map(([z,Pe])=>`[Chat Summary]: ${Pe}`),...Q].map(z=>`- ${z}`).join(`
923
- `),ee=oe(Pt,[]).map(z=>`- ${z.memory}`).join(`
924
- `),Me=(u?.tokens||0)>=1e4,v=ha(F,ee,h,Me),U=new Date,X=U.getFullYear(),te=U.toLocaleString("en-US",{month:"short"}).toUpperCase(),We=String(U.getDate()).padStart(2,"0"),Ne=U.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}),Je=`${X}-${te}-${We}, ${Ne}`,ct=[".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",".skills","skills"],He=z=>{try{return Fe.readdirSync(z,{withFileTypes:!0})}catch{return[]}},gt=(z,Pe={value:0},on=1)=>{if(Pe.value>6200||on>7)return Pe.value;let Ee=He(z);for(let nt of Ee){if(Pe.value>6200)break;ct.includes(nt.name)||nt.name.startsWith(".")||nt.isDirectory()&&(Pe.value++,gt(Z.join(z,nt.name),Pe,on+1))}return Pe.value},ko=(z,Pe)=>l?.indentationTree!==!1?fi(z,Pe,1,He,ct):pi(z,Pe,"",1,He,ct),bt=gt(process.cwd()),Ke=10;bt>3072||bt>2304?Ke=1:bt>1536?Ke=2:bt>768?Ke=3:bt>384?Ke=5:bt>192?Ke=6:bt>96?Ke=7:(bt>48||bt>24)&&(Ke=9);let Rt=oe(cr,{}),et=Rt[d],Re=et?et!==process.cwd():!1;Rt[d]=process.cwd(),pe(cr,Rt);let ye=oe(x,{}),tt=ye[d]||{summary:"",historyLength:0};typeof tt=="string"&&(tt={summary:tt,historyLength:0});let ys=n.filter(z=>(z.role==="user"||z.role==="agent"||z.role==="system")&&!String(z.id).startsWith("welcome")&&!z.isMeta).length;tt.historyLength&&ys<tt.historyLength&&(tt.summary="",tt.historyLength=0,ye[d]=tt,pe(x,ye));let $n=typeof tt=="object"?tt.summary||"":tt||"",xi=b.length>0;xi&&$n&&b[0]&&(b[0].role==="user"||b[0].role==="system")&&(b[0].text.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")||(b[0].text=`[SYSTEM METADATA]
972
+ Provide a consolidated summary of the entire session.`,h=Te("gemma_janitor_fallback_google");s==="OpenRouter"&&(h=Te("janitor_open_router")),s==="DeepSeek"&&(h=Te("deepseek_level_1")),s==="Mistral"&&(h=Te("mistral_level_1")),s==="NVIDIA"&&(h=Te("nvidia_chat_summarizer_fallback")),s==="CrofAI"&&(h=Te("crofai_fallback")),s==="InferX"&&(h=Te("inferx_fallback")),s==="SenseNova"&&(h=Te("sensenova_fallback")),s==="AIHubMix"&&(h=Te("aihubmix_fallback"));let w=0,x=!1,T=null;for(;w<=3&&!x;){w++;try{T=await tr(e,h,y,g,"Fast"),x=!0}catch{if(w>3){if(s==="Google")try{let R=Te("general_fallback");return(await tr(e,R,y,g,"Fast")).text||""}catch{return""}return""}}}return T&&T.text||""},p=a(n),d=oe(r,{}),c=d[o]||{summary:"",historyLength:0};typeof c=="string"&&(c={summary:c,historyLength:0});let l=c.summary||"",u=await i(p,l);if(u){c.summary=u;let f=fd(n);return t?c.historyLength=(c.historyLength||0)+f:c.historyLength=f,d[o]=c,pe(r,d),u}return null},ky=e=>{try{let n=Z.join(Ts,"chat-summaries.json");if(Fe.existsSync(n)){let t=oe(n,{});t[e]&&(delete t[e],pe(n,t))}}catch{}},Ty=async function*(e,n,t,o,s){let{profile:r,thinkingLevel:a,mode:i,janitorModel:p,chatId:d,isPlayground:c,systemSettings:l,sessionStats:u,aiProvider:f="Google",apiTier:m,wildcardTooling:g}=t,y=Mt(e);if(!yi&&f==="Google")throw new Error("AI not initialized");let h=process.env.NVIDIA_BASE_URL||t?.aiProvider==="Ollama"||t?.aiProvider==="CrofAI"||t?.aiProvider==="InferX"||t?.aiProvider==="SenseNova"||t?.aiProvider==="AIHubMix"?!1:l?.memory!==!1,w=n[n.length-1].text,x=Z.join(Ts,"chat-summaries.json"),T=!1,_=n.filter(E=>E.role==="user").length===1,R=w.includes("[TITLE-UPDATE]"),S=_||R,k=w.replace(/\[TITLE-UPDATE\]/g,"").trim();k=k.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),yield{type:"status",content:"[start]"},yield{type:"status",content:"Gathering Context"},await ht.startTransaction(d,k),l?.advanceRollback&&await Zn.takeInitialSnapshot(d),At=!1;let C=null;try{let E=new AbortController;C=setInterval(()=>{At&&(E.abort(),C&&(clearInterval(C),C=null))},400);let b=[...n.slice(0,-1)];{let Pe=oe(x,{})[d]||{summary:"",historyLength:0};if(Pe.summary&&Pe.historyLength>0){let sn=0,Ee=[];for(let nt=0;nt<b.length;nt++){let qe=b[nt];(qe.role==="user"||qe.role==="agent"||qe.role==="system")&&!String(qe.id).startsWith("welcome")&&!qe.isMeta&&sn++,sn>Pe.historyLength&&Ee.push(qe)}b=Ee}}b=b.map(z=>{if(z.role==="user"&&z.text){let Pe=z.text.match(/\[USER\]([\s\S]*?)\[\/USER\]/);if(Pe)return{...z,text:Pe[1].trim()}}return{...z}});let $=process.env.HIGH_CONTEXT,I=process.env.GOOGLE_GEMMA_NONSENSE==="true"||process.env.GOOGLE_GEMMA_NONSENSE===!0||!1,O=255e3,P=26e4;if($&&$!=="false"){let z=parseInt($,10);!isNaN(z)&&z>=0&&z<=1e6&&(P=z,O=Math.round(z*.85))}if((f==="NVIDIA"&&(e?.includes("gpt")||e?.includes("qwen")||e?.includes("medium")||e.includes("muse"))||f==="Mistral")&&(O=122e3,P=126e3),f==="Google"&&e?.includes("gemma")&&I&&(O=14e3,P=16e3),f==="Ollama"&&(u?.tokens||0)>O){yield{type:"text",content:"\u2726 Maximum Context Limit Reached. Start a new chat."};return}if(f!=="Ollama"&&(u?.tokens||0)>O&&(yield{type:"status_history",content:"Context Limit Reached. Condensing session history..."},await xd(t,b,!0)&&(b=[],T=!0)),_&&h){let z=oe(en,{});Object.values(z).flat().length>5&&(yield{type:"status",content:"Condensing past chat memories"},await wd(d,t,z))}let W=oe(en,{}),q=oe(Pn,{}),Q=Object.entries(W).filter(([z])=>z!==d).flatMap(([z,Pe])=>Pe),F=[...Object.entries(q).filter(([z])=>z!==d).slice(-20).map(([z,Pe])=>`[Chat Summary]: ${Pe}`),...Q].map(z=>`- ${z}`).join(`
973
+ `),ee=oe(Ft,[]).map(z=>`- ${z.memory}`).join(`
974
+ `),Me=(u?.tokens||0)>=1e4,v=ha(F,ee,h,Me),U=new Date,X=U.getFullYear(),te=U.toLocaleString("en-US",{month:"short"}).toUpperCase(),We=String(U.getDate()).padStart(2,"0"),Ne=U.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}),Je=`${X}-${te}-${We}, ${Ne}`,ct=[".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",".skills","skills"],He=z=>{try{return Fe.readdirSync(z,{withFileTypes:!0})}catch{return[]}},gt=(z,Pe={value:0},sn=1)=>{if(Pe.value>6200||sn>7)return Pe.value;let Ee=He(z);for(let nt of Ee){if(Pe.value>6200)break;ct.includes(nt.name)||nt.name.startsWith(".")||nt.isDirectory()&&(Pe.value++,gt(Z.join(z,nt.name),Pe,sn+1))}return Pe.value},To=(z,Pe)=>l?.indentationTree!==!1?fi(z,Pe,1,He,ct):pi(z,Pe,"",1,He,ct),bt=gt(process.cwd()),Ke=10;bt>3072||bt>2304?Ke=1:bt>1536?Ke=2:bt>768?Ke=3:bt>384?Ke=5:bt>192?Ke=6:bt>96?Ke=7:(bt>48||bt>24)&&(Ke=9);let Et=oe(cr,{}),et=Et[d],Re=et?et!==process.cwd():!1;Et[d]=process.cwd(),pe(cr,Et);let ye=oe(x,{}),tt=ye[d]||{summary:"",historyLength:0};typeof tt=="string"&&(tt={summary:tt,historyLength:0});let ys=n.filter(z=>(z.role==="user"||z.role==="agent"||z.role==="system")&&!String(z.id).startsWith("welcome")&&!z.isMeta).length;tt.historyLength&&ys<tt.historyLength&&(tt.summary="",tt.historyLength=0,ye[d]=tt,pe(x,ye));let An=typeof tt=="object"?tt.summary||"":tt||"",xi=b.length>0;xi&&An&&b[0]&&(b[0].role==="user"||b[0].role==="system")&&(b[0].text.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")||(b[0].text=`[SYSTEM METADATA]
925
975
  **CONTEXT SUMMARY OF PREVIOUS TURNS (PRIORITY: DYNAMIC)**
926
- ${$n}
976
+ ${An}
927
977
 
928
- [USER] ${b[0].text}`,yield{type:"summary_injected",content:{id:b[0].id,text:b[0].text}}));let bi=$n&&!xi?`
978
+ [USER] ${b[0].text}`,yield{type:"summary_injected",content:{id:b[0].id,text:b[0].text}}));let bi=An&&!xi?`
929
979
  [SYSTEM METADATA]
930
980
  **CONTEXT SUMMARY OF PREVIOUS TURNS**
931
- ${$n}
932
- `:"",Si=!!l?.dynamicDirAwareness,hl=`${d}|${f}|${a}|${e}|${r}|${Si}`,ki=!Si&&bo.key===hl&&bo.value?"":`
981
+ ${An}
982
+ `:"",Si=!!l?.dynamicDirAwareness,hl=`${d}|${f}|${a}|${e}|${r}|${Si}`,ki=!Si&&So.key===hl&&So.value?"":`
933
983
  **Directory Structure**
934
984
  CWD: `+process.cwd()+`${c?" [PLAYGROUND MODE]":""}
935
- `+ko(process.cwd(),Ke),St=await wo(),Wn="";if(Hs()&&St.file_focused!=="none"){Wn=`
985
+ `+To(process.cwd(),Ke),St=await xo(),jn="";if(Hs()&&St.file_focused!=="none"){jn=`
936
986
  [Additional IDE Context]
937
- `;let z=Z.relative(process.cwd(),St.file_focused),Pe=(St.opened_editors||[]).map(Ee=>{let nt=Z.relative(process.cwd(),Ee);return nt.startsWith("..")?`[External] ${Z.basename(Ee)}`:nt});if(Wn+=`Focused File: ${z}
987
+ `;let z=Z.relative(process.cwd(),St.file_focused),Pe=(St.opened_editors||[]).map(Ee=>{let nt=Z.relative(process.cwd(),Ee);return nt.startsWith("..")?`[External] ${Z.basename(Ee)}`:nt});if(jn+=`Focused File: ${z}
938
988
  Cursor Line: ${St.cursor_line}
939
989
  `,St.selected){let Ee=St.selected,nt=Ee.split(`
940
990
  `);nt.length>256&&(Ee=nt.slice(0,240).join(`
@@ -943,29 +993,29 @@ Cursor Line: ${St.cursor_line}
943
993
  `+nt.slice(-16).join(`
944
994
  `)),Ee.length>2048&&(Ee=Ee.slice(0,1920)+`
945
995
  ... [truncated] ...
946
- `+Ee.slice(-128)),Wn+=`Current Selection: "${Ee}"
996
+ `+Ee.slice(-128)),jn+=`Current Selection: "${Ee}"
947
997
  `}if(St.manual_edits){let nt=St.manual_edits.split(`
948
- `),qe=[],Qe=null;for(let K of nt)K.trim()&&(K.startsWith(" Line ")?Qe&&Qe.edits.push(K):(Qe={path:K.endsWith(":")?K.slice(0,-1):K,edits:[]},qe.push(Qe)));for(let K of qe)K.edits.length>80&&(K.edits=K.edits.slice(-80)),K.originalEditsCount=K.edits.length;let ue=(K,ne)=>ne.reduce((ze,fn)=>{let Sn=St.file_focused&&(fn.path===St.file_focused||Z.resolve(process.cwd(),fn.path)===Z.resolve(St.file_focused))?Math.ceil(K*1.2):K;return ze+Math.min(fn.edits.length,Sn)},0),Nt=80;if(ue(80,qe)>300){let K=!1;for(let ne=80;ne>=10;ne--)if(ue(ne,qe)<=300){Nt=ne,K=!0;break}K||(Nt=10)}let Ze=[...qe];if(Nt===10&&ue(10,Ze)>500)for(;Ze.length>0&&ue(10,Ze)>500;){let K=0,ne=Ze[0].originalEditsCount;for(let ze=1;ze<Ze.length;ze++)Ze[ze].originalEditsCount<ne&&(ne=Ze[ze].originalEditsCount,K=ze);Ze.splice(K,1)}for(let K of Ze){let ze=St.file_focused&&(K.path===St.file_focused||Z.resolve(process.cwd(),K.path)===Z.resolve(St.file_focused))?Math.ceil(Nt*1.2):Nt;K.edits.length>ze&&(K.edits=K.edits.slice(-ze))}for(let K of Ze){let ne=`${K.path}:
998
+ `),qe=[],Qe=null;for(let K of nt)K.trim()&&(K.startsWith(" Line ")?Qe&&Qe.edits.push(K):(Qe={path:K.endsWith(":")?K.slice(0,-1):K,edits:[]},qe.push(Qe)));for(let K of qe)K.edits.length>80&&(K.edits=K.edits.slice(-80)),K.originalEditsCount=K.edits.length;let ue=(K,ne)=>ne.reduce((ze,un)=>{let kn=St.file_focused&&(un.path===St.file_focused||Z.resolve(process.cwd(),un.path)===Z.resolve(St.file_focused))?Math.ceil(K*1.2):K;return ze+Math.min(un.edits.length,kn)},0),Ut=80;if(ue(80,qe)>300){let K=!1;for(let ne=80;ne>=10;ne--)if(ue(ne,qe)<=300){Ut=ne,K=!0;break}K||(Ut=10)}let Ze=[...qe];if(Ut===10&&ue(10,Ze)>500)for(;Ze.length>0&&ue(10,Ze)>500;){let K=0,ne=Ze[0].originalEditsCount;for(let ze=1;ze<Ze.length;ze++)Ze[ze].originalEditsCount<ne&&(ne=Ze[ze].originalEditsCount,K=ze);Ze.splice(K,1)}for(let K of Ze){let ze=St.file_focused&&(K.path===St.file_focused||Z.resolve(process.cwd(),K.path)===Z.resolve(St.file_focused))?Math.ceil(Ut*1.2):Ut;K.edits.length>ze&&(K.edits=K.edits.slice(-ze))}for(let K of Ze){let ne=`${K.path}:
949
999
  ${K.edits.join(`
950
1000
  `)}`;for(;K.edits.length>0&&ne.length>4*768;)K.edits.shift(),ne=`${K.path}:
951
1001
  ${K.edits.join(`
952
- `)}`;ne.length>4*768?K.stringRepresentation="... "+ne.slice(-(4*768-4)):K.stringRepresentation=ne}let sn=Ze.map(K=>K.stringRepresentation).join(`
953
- `);for(;Ze.length>0&&sn.length>4*2048;){Ze[0].edits.length>0?Ze[0].edits.shift():Ze.shift();for(let K of Ze){let ne=`${K.path}:
1002
+ `)}`;ne.length>4*768?K.stringRepresentation="... "+ne.slice(-(4*768-4)):K.stringRepresentation=ne}let rn=Ze.map(K=>K.stringRepresentation).join(`
1003
+ `);for(;Ze.length>0&&rn.length>4*2048;){Ze[0].edits.length>0?Ze[0].edits.shift():Ze.shift();for(let K of Ze){let ne=`${K.path}:
954
1004
  ${K.edits.join(`
955
- `)}`;ne.length>4*768?K.stringRepresentation="... "+ne.slice(-(4*768-4)):K.stringRepresentation=ne}sn=Ze.map(K=>K.stringRepresentation).join(`
956
- `)}sn.length>4*2048&&(sn="... "+sn.slice(-(4*2048-4))),Wn+=`Recent Manual Edits:
957
- ${sn}
958
- `}Pe.length>0&&(Wn+=`All Opened Editors: ${Pe.join(", ")}`),St.diagnostics&&(Wn+=`
1005
+ `)}`;ne.length>4*768?K.stringRepresentation="... "+ne.slice(-(4*768-4)):K.stringRepresentation=ne}rn=Ze.map(K=>K.stringRepresentation).join(`
1006
+ `)}rn.length>4*2048&&(rn="... "+rn.slice(-(4*2048-4))),jn+=`Recent Manual Edits:
1007
+ ${rn}
1008
+ `}Pe.length>0&&(jn+=`All Opened Editors: ${Pe.join(", ")}`),St.diagnostics&&(jn+=`
959
1009
  **Active File Errors**:
960
1010
  ${St.diagnostics}
961
- `),(k.toLowerCase().includes("lint")||k.toLowerCase().includes("warning"))&&St.warnings&&(Wn+=`
1011
+ `),(k.toLowerCase().includes("lint")||k.toLowerCase().includes("warning"))&&St.warnings&&(jn+=`
962
1012
  **Lint Warnings**:
963
1013
  ${St.warnings}
964
- `)}let Ti=k.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),Ri=/(?:\\)?@\[([^\]]+)\]/g,or,sr=[];for(Ri.lastIndex=0;(or=Ri.exec(Ti))!==null;){let z=or[0].startsWith("\\");sr.push({tag:or[1],isEscaped:z})}let rr=[],ws=null;for(let z=0;z<sr.length;z++){let{tag:Pe,isEscaped:on}=sr[z];if(!on)try{let Ee=Pe.trim().replace(/^["']|["']$/g,""),nt=/[:#]L?(\d+)(?:-L?(\d+))?$/i,qe=Ee.match(nt),Qe=Ee,ue=null,Nt=null;qe&&(ue=parseInt(qe[1],10),Nt=qe[2]?parseInt(qe[2],10):ue,Qe=Ee.slice(0,qe.index));let Ze=Z.resolve(process.cwd(),Qe);if(Fe.existsSync(Ze)&&Fe.statSync(Ze).isFile()){let K=Qe.toLowerCase(),ne=K.endsWith(".pdf"),ze=K.endsWith(".docx")||K.endsWith(".doc")||K.endsWith(".ppt")||K.endsWith(".pptx")||K.endsWith(".xls")||K.endsWith(".xlsx"),fn=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(K),Ut=fn||ne||ze,Sn=f==="Google"||At(e);if(Ut&&!Sn){let je=`\u2718 Unsupported Modality: ${Z.basename(Qe)}`,ke=115;process.stdout.isTTY&&(ke=process.stdout.columns-5||120);let ot=[je],oo=Math.max(...ot.map(jn=>jn.length)),un=Math.min(oo+4,ke),jo=ot.map(jn=>`${jn.padEnd(un-2).substring(0,un-2)}`).join(`
965
- `);yield{type:"visual_feedback",content:tn(`${jo}
966
- `)};continue}if(ue===null&&!Ut){let je=0;try{je=Fe.readFileSync(Ze,"utf8").split(/\r\n|\r|\n/).length}catch{}if(je>300){let ke=`\u21B7 Skipped (Too Large): ${Z.basename(Qe)}`,ot=115;process.stdout.isTTY&&(ot=process.stdout.columns-5||120);let oo=Math.min(ke.length+4,ot),un=ke.padEnd(oo-2).substring(0,oo-2);yield{type:"visual_feedback",content:tn(`${un}
967
- `)};continue}}let Mn=ue!==null?ue:1,to=Nt!==null?Nt:ue!==null?ue:Mn+299;to-Mn>300&&(to=Mn+300);let bs=`path=${JSON.stringify(Qe)}, startLine=${Mn}, endLine=${to}`,it=await es(bs,{isMultiModal:Sn}),Ye=!1,Bt="",no=null;if(typeof it=="string"?it.trim().startsWith("ERROR")?Ye=!0:Bt=it:it&&typeof it=="object"&&it.binaryPart?(no=it.binaryPart,Bt=it.text||""):Ye=!0,!Ye){let je="";if(fn?(je=`\u2714 Processed: ${Z.basename(Qe)}`,ws=no):ne||ze?(je=`\u2714 Auto-Analysed: ${Z.basename(Qe)}`,ws=no):(je=`\u2714 Auto-Read: ${Z.basename(Qe)}`,rr.push(Bt)),je){let ke=115;process.stdout.isTTY&&(ke=process.stdout.columns-5||120);let ot=[je],oo=Math.max(...ot.map(jn=>jn.length)),un=Math.min(oo+4,ke),jo=ot.map(jn=>`${jn.padEnd(un-2).substring(0,un-2)}`).join(`
968
- `);yield{type:"visual_feedback",content:tn(`${jo}
1014
+ `)}let Ti=k.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),Ri=/(?:\\)?@\[([^\]]+)\]/g,or,sr=[];for(Ri.lastIndex=0;(or=Ri.exec(Ti))!==null;){let z=or[0].startsWith("\\");sr.push({tag:or[1],isEscaped:z})}let rr=[],ws=null;for(let z=0;z<sr.length;z++){let{tag:Pe,isEscaped:sn}=sr[z];if(!sn)try{let Ee=Pe.trim().replace(/^["']|["']$/g,""),nt=/[:#]L?(\d+)(?:-L?(\d+))?$/i,qe=Ee.match(nt),Qe=Ee,ue=null,Ut=null;qe&&(ue=parseInt(qe[1],10),Ut=qe[2]?parseInt(qe[2],10):ue,Qe=Ee.slice(0,qe.index));let Ze=Z.resolve(process.cwd(),Qe);if(Fe.existsSync(Ze)&&Fe.statSync(Ze).isFile()){let K=Qe.toLowerCase(),ne=K.endsWith(".pdf"),ze=K.endsWith(".docx")||K.endsWith(".doc")||K.endsWith(".ppt")||K.endsWith(".pptx")||K.endsWith(".xls")||K.endsWith(".xlsx"),un=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(K),Bt=un||ne||ze,kn=f==="Google"||Mt(e);if(Bt&&!kn){let je=`\u2718 Unsupported Modality: ${Z.basename(Qe)}`,ke=115;process.stdout.isTTY&&(ke=process.stdout.columns-5||120);let ot=[je],so=Math.max(...ot.map(Gn=>Gn.length)),pn=Math.min(so+4,ke),Go=ot.map(Gn=>`${Gn.padEnd(pn-2).substring(0,pn-2)}`).join(`
1015
+ `);yield{type:"visual_feedback",content:nn(`${Go}
1016
+ `)};continue}if(ue===null&&!Bt){let je=0;try{je=Fe.readFileSync(Ze,"utf8").split(/\r\n|\r|\n/).length}catch{}if(je>300){let ke=`\u21B7 Skipped (Too Large): ${Z.basename(Qe)}`,ot=115;process.stdout.isTTY&&(ot=process.stdout.columns-5||120);let so=Math.min(ke.length+4,ot),pn=ke.padEnd(so-2).substring(0,so-2);yield{type:"visual_feedback",content:nn(`${pn}
1017
+ `)};continue}}let vn=ue!==null?ue:1,no=Ut!==null?Ut:ue!==null?ue:vn+299;no-vn>300&&(no=vn+300);let bs=`path=${JSON.stringify(Qe)}, startLine=${vn}, endLine=${no}`,it=await ts(bs,{isMultiModal:kn}),Ye=!1,Wt="",oo=null;if(typeof it=="string"?it.trim().startsWith("ERROR")?Ye=!0:Wt=it:it&&typeof it=="object"&&it.binaryPart?(oo=it.binaryPart,Wt=it.text||""):Ye=!0,!Ye){let je="";if(un?(je=`\u2714 Processed: ${Z.basename(Qe)}`,ws=oo):ne||ze?(je=`\u2714 Auto-Analysed: ${Z.basename(Qe)}`,ws=oo):(je=`\u2714 Auto-Read: ${Z.basename(Qe)}`,rr.push(Wt)),je){let ke=115;process.stdout.isTTY&&(ke=process.stdout.columns-5||120);let ot=[je],so=Math.max(...ot.map(Gn=>Gn.length)),pn=Math.min(so+4,ke),Go=ot.map(Gn=>`${Gn.padEnd(pn-2).substring(0,pn-2)}`).join(`
1018
+ `);yield{type:"visual_feedback",content:nn(`${Go}
969
1019
  `)}}}}}catch{}}let Ei="";rr.length>0&&(Ei=`[Tagged File Contents] Auto Read User Tagged files by System, No need to re-read
970
1020
  `+rr.join(`
971
1021
 
@@ -976,13 +1026,13 @@ Instead, output in chat the exact string you WOULD have produced & wait for syst
976
1026
  `:"",wl=process.env.forcedReasoning||!1,Ci=`[System Metadata]
977
1027
  Time: ${Je}${l?.dynamicDirAwareness?ki:""}${Re?`
978
1028
  WARNING: CWD Changed from previous: "${et}" to current: "${process.cwd()}", write change in chat to avoid future path mismatches
979
- `:""}${v}${Wn}
1029
+ `:""}${v}${jn}
980
1030
  [/Metadata]
981
- ${bi}${a!=="Fast"&&(f==="Mistral"&&!Mo(e)||a!=="xHigh"&&f==="Google")?`${f==="Mistral"&&!Mo(e)||e.toLowerCase().startsWith("gemma")||wl?`[system] strictly follow thinking policy as high priority. do not start a response without <think>...</think> [/system]
1031
+ ${bi}${a!=="Fast"&&(f==="Mistral"&&!vo(e)||a!=="xHigh"&&f==="Google")?`${f==="Mistral"&&!vo(e)||e.toLowerCase().startsWith("gemma")||wl?`[system] strictly follow thinking policy as high priority. do not start a response without <think>...</think> [/system]
982
1032
  `:""}`:""}[system] exact tool string [tool:functions.ToolName(arg="value")] in chat [/system]
983
- ${Ei}${yl}[user prompt] ${gl.trim()} [/user prompt]`.trim(),_i={role:"user",text:Ci};ws&&(_i.binaryPart=ws),b.forEach(z=>{z.text&&z.role==="agent"&&(z.text=nn(z.text))}),b.push(_i),bi&&n[n.length-1]?.id&&(yield{type:"summary_injected",content:{id:n[n.length-1].id,text:Ci}});let An=null,Wo=i==="Flux"?100:10;Wo=i.toLowerCase().includes("cu")?250:Wo;let bn=16;yield{type:"status",content:"Connecting"},$t=!1;let $i=[],xs=!1;for(let z=0;z<=Wo;z++){let Pe=await vi("agent",t);if(!Pe.allowed)throw new Error(Pe.reason||`Budget Exhausted for Provider (${f||"Agent"})`);let on=[];if(xs=!1,i==="ICU"||i==="FluxCU")try{yield{type:"status",content:"Capturing Screen"},await new Promise(we=>setTimeout(we,1e3));let ce=await Pi();if(ce&&ce.base64){let we="[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]",de={inlineData:{mimeType:ce.mimeType,data:ce.base64}};for(let at of b)Array.isArray(at.parts)&&(at.parts=at.parts.filter(Wt=>!Wt.inlineData));if(b.length>0&&b[b.length-1].role==="user"){let at=b[b.length-1];typeof at.text=="string"&&(at.text+=`
1033
+ ${Ei}${yl}[user prompt] ${gl.trim()} [/user prompt]`.trim(),_i={role:"user",text:Ci};ws&&(_i.binaryPart=ws),b.forEach(z=>{z.text&&z.role==="agent"&&(z.text=on(z.text))}),b.push(_i),bi&&n[n.length-1]?.id&&(yield{type:"summary_injected",content:{id:n[n.length-1].id,text:Ci}});let Mn=null,jo=i==="Flux"?100:10;jo=i.toLowerCase().includes("cu")?250:jo;let Sn=16;yield{type:"status",content:"Connecting"},At=!1;let $i=[],xs=!1;for(let z=0;z<=jo;z++){let Pe=await vi("agent",t);if(!Pe.allowed)throw new Error(Pe.reason||`Budget Exhausted for Provider (${f||"Agent"})`);let sn=[];if(xs=!1,i==="ICU"||i==="FluxCU")try{yield{type:"status",content:"Capturing Screen"},await new Promise(we=>setTimeout(we,1e3));let ce=await Pi();if(ce&&ce.base64){let we="[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]",de={inlineData:{mimeType:ce.mimeType,data:ce.base64}};for(let at of b)Array.isArray(at.parts)&&(at.parts=at.parts.filter(jt=>!jt.inlineData));if(b.length>0&&b[b.length-1].role==="user"){let at=b[b.length-1];typeof at.text=="string"&&(at.text+=`
984
1034
 
985
- ${we}`,Array.isArray(at.parts)||(at.parts=[{text:at.text}]),at.parts.push(de))}else b.push({role:"user",text:we,parts:[{text:we},de]})}}catch(ce){console.error("Vision screenshot capture error:",ce)}if(l?.compression===0&&(u?.tokens||0)>P&&(b=ba(b,6)),z>0?yield{type:"status",content:"Working"}:yield{type:"status",content:"Connecting"},$t){try{let{clearPendingNudges:ce}=await import("./subagent_state-LZCOZSUJ.js");ce()}catch{}yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
1035
+ ${we}`,Array.isArray(at.parts)||(at.parts=[{text:at.text}]),at.parts.push(de))}else b.push({role:"user",text:we,parts:[{text:we},de]})}}catch(ce){console.error("Vision screenshot capture error:",ce)}if(l?.compression===0&&(u?.tokens||0)>P&&(b=ba(b,6)),z>0?yield{type:"status",content:"Working"}:yield{type:"status",content:"Connecting"},At){try{let{clearPendingNudges:ce}=await import("./subagent_state-LZCOZSUJ.js");ce()}catch{}yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
986
1036
 
987
1037
  \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}try{let{consumePendingNudges:ce}=await import("./subagent_state-LZCOZSUJ.js"),we=ce();if(we&&we.length>0){let de=we.join(`
988
1038
 
@@ -994,118 +1044,118 @@ ${de}`:b.push({role:"user",text:de}),yield{type:"status",content:"Subagent Updat
994
1044
  [question] ${ce.replace("/btw","").trim()} [/question]`:b.push({role:"user",text:`[system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
995
1045
  [question] ${ce.replace("/btw","").trim()} [/question]`}):b.length>0&&b[b.length-1].role==="user"?b[b.length-1].text+=`
996
1046
 
997
- [STEERING HINT from USER, HIGH PRIORITY] ${ce.trim().toUpperCase()} [/STEERING HINT]`:b.push({role:"user",text:`[STEERING HINT from USER, HIGH PRIORITY] ${ce.trim().toUpperCase()} [/STEERING HINT]`}),yield{type:"status",content:`${ce.startsWith("/btw")?"Question Forwarded...":"Steering Hint Injected..."}`})}let Ee,nt=!1,qe=1,Qe=1,ue="",Nt=null,Ze=null,sn=null,K=0,ne=[],ze=0,fn=!1,Ut=!1,Sn=!1,Mn=!1,to=!0,bs=0,it="",Ye="",Bt=!1,no=!1,je=!0,ke=e,ot="";for(;qe<=bn&&Qe<=bn&&!nt&&!$t;){let ce=!1;try{ue="",to&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},to=!1,Qe===1&&(it=""));let we=N=>{if(!N||!N.includes("[tool:"))return N;let ie="",G=hi(N);G&&(ie=G.fullBlock,N=G.remainingText),N=N.replace(cd,(me,Ce)=>Ce.includes("[tool:")?Ce.trim():me);let H="",xe=0;for(;xe<N.length;){let me=N.indexOf("[tool:",xe);if(me===-1){H+=cl(N.substring(xe));break}let Ce=N.substring(xe,me);H+=cl(Ce);let st=-1,j=null,se=0;for(let Ue=me;Ue<N.length;Ue++){let A=N[Ue];if(j){if(A===j){let Be=0;for(let ve=Ue-1;ve>=0&&N[ve]==="\\";ve--)Be++;Be%2===0&&(j=null)}}else if(A==='"'||A==="'"||A==="`")j=A;else if(A==="(")se++;else if(A===")")se--;else if(A==="]"&&se<=0){st=Ue;break}}if(st===-1){H+=N.substring(me);break}H+=N.substring(me,st+1),xe=st+1}return ie+H},de=b.filter(N=>(N.role==="user"||N.role==="agent"||N.role==="system")&&!String(N.id).startsWith("welcome")&&!N.isMeta&&!N.isTerminalRecord&&!(N.text&&N.text.startsWith("[TERMINAL_RECORD]"))).map((N,ie,G)=>{let H=N.text||"";h||(H=H.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),N.role==="agent"&&(H=we(H),H=H.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),H=H.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*"));let xe=[];return Array.isArray(N.parts)&&N.parts.length>0?xe=N.parts.map(me=>{if(me.text){let Ce=me.text;return h||(Ce=Ce.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),N.role==="agent"&&(Ce=we(Ce),Ce=Ce.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),Ce=Ce.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*")),{text:Ce}}return me}):xe=[{text:H}],N.binaryPart&&At(ke)&&G.slice(ie+1).filter(Ce=>Ce.role==="user"&&!Ce.text?.startsWith("[TOOL RESULT]")).length<=2&&xe.push(N.binaryPart),{role:N.role==="user"||N.role==="system"?"user":"model",parts:xe}});for(let N=0;N<de.length;N++){let ie=de[N],G=ie.parts?.[0]?.text||"";if(ie.role==="model"&&/\[tool:/i.test(G)){let H=-1;for(let xe=N+1;xe<de.length;xe++){let me=de[xe],Ce=me.parts?.[0]?.text||"";if(me.role==="user"&&Ce.startsWith("[TOOL RESULT]")){H=xe;break}}if(H!==-1&&H!==N+1){let[xe]=de.splice(H,1);de.splice(N+1,0,xe)}}}for(let N=de.length-2;N>=0;N--){let ie=de[N],G=de[N+1];ie.role==="user"&&G.role==="user"&&(G.parts?.[0]?.text||"").trim().startsWith("[SYSTEM")&&de.splice(N,1)}let at=[];for(let N=0;N<de.length;N++){let ie=de[N];if(at.length===0)at.push(ie);else{let G=at[at.length-1];G.role===ie.role?(G.parts[0].text+=`
1047
+ [STEERING HINT from USER, HIGH PRIORITY] ${ce.trim().toUpperCase()} [/STEERING HINT]`:b.push({role:"user",text:`[STEERING HINT from USER, HIGH PRIORITY] ${ce.trim().toUpperCase()} [/STEERING HINT]`}),yield{type:"status",content:`${ce.startsWith("/btw")?"Question Forwarded...":"Steering Hint Injected..."}`})}let Ee,nt=!1,qe=1,Qe=1,ue="",Ut=null,Ze=null,rn=null,K=0,ne=[],ze=0,un=!1,Bt=!1,kn=!1,vn=!1,no=!0,bs=0,it="",Ye="",Wt=!1,oo=!1,je=!0,ke=e,ot="";for(;qe<=Sn&&Qe<=Sn&&!nt&&!At;){let ce=!1;try{ue="",no&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},no=!1,Qe===1&&(it=""));let we=N=>{if(!N||!N.includes("[tool:"))return N;let ie="",G=hi(N);G&&(ie=G.fullBlock,N=G.remainingText),N=N.replace(cd,(me,Ce)=>Ce.includes("[tool:")?Ce.trim():me);let H="",xe=0;for(;xe<N.length;){let me=N.indexOf("[tool:",xe);if(me===-1){H+=cl(N.substring(xe));break}let Ce=N.substring(xe,me);H+=cl(Ce);let st=-1,j=null,se=0;for(let Ue=me;Ue<N.length;Ue++){let A=N[Ue];if(j){if(A===j){let Be=0;for(let ve=Ue-1;ve>=0&&N[ve]==="\\";ve--)Be++;Be%2===0&&(j=null)}}else if(A==='"'||A==="'"||A==="`")j=A;else if(A==="(")se++;else if(A===")")se--;else if(A==="]"&&se<=0){st=Ue;break}}if(st===-1){H+=N.substring(me);break}H+=N.substring(me,st+1),xe=st+1}return ie+H},de=b.filter(N=>(N.role==="user"||N.role==="agent"||N.role==="system")&&!String(N.id).startsWith("welcome")&&!N.isMeta&&!N.isTerminalRecord&&!(N.text&&N.text.startsWith("[TERMINAL_RECORD]"))).map((N,ie,G)=>{let H=N.text||"";h||(H=H.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),N.role==="agent"&&(H=we(H),H=H.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),H=H.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*"));let xe=[];return Array.isArray(N.parts)&&N.parts.length>0?xe=N.parts.map(me=>{if(me.text){let Ce=me.text;return h||(Ce=Ce.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),N.role==="agent"&&(Ce=we(Ce),Ce=Ce.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),Ce=Ce.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*")),{text:Ce}}return me}):xe=[{text:H}],N.binaryPart&&Mt(ke)&&G.slice(ie+1).filter(Ce=>Ce.role==="user"&&!Ce.text?.startsWith("[TOOL RESULT]")).length<=2&&xe.push(N.binaryPart),{role:N.role==="user"||N.role==="system"?"user":"model",parts:xe}});for(let N=0;N<de.length;N++){let ie=de[N],G=ie.parts?.[0]?.text||"";if(ie.role==="model"&&/\[tool:/i.test(G)){let H=-1;for(let xe=N+1;xe<de.length;xe++){let me=de[xe],Ce=me.parts?.[0]?.text||"";if(me.role==="user"&&Ce.startsWith("[TOOL RESULT]")){H=xe;break}}if(H!==-1&&H!==N+1){let[xe]=de.splice(H,1);de.splice(N+1,0,xe)}}}for(let N=de.length-2;N>=0;N--){let ie=de[N],G=de[N+1];ie.role==="user"&&G.role==="user"&&(G.parts?.[0]?.text||"").trim().startsWith("[SYSTEM")&&de.splice(N,1)}let at=[];for(let N=0;N<de.length;N++){let ie=de[N];if(at.length===0)at.push(ie);else{let G=at[at.length-1];G.role===ie.role?(G.parts[0].text+=`
998
1048
 
999
- `+(ie.parts?.[0]?.text||""),ie.parts?.length>1&&G.parts.push(...ie.parts.slice(1))):at.push(ie)}}de.length=0,de.push(...at),ke=e;let Wt=`${d}|${f}|${i}|${a}|${ke}|${JSON.stringify(r)}|${!!l?.dynamicDirAwareness}|${!!l?.subAgents}`,Kt=bo.key===Wt&&bo.value;if((process.env.I_HAVE_TOO_MUCH_MONEY==="true"||process.env.I_HAVE_TOO_MUCH_MONEY===!0)&&(Kt=!1),Kt)ot=bo.value;else{let N=f==="Mistral"?!!Mo(ke):!(ke||"gemma").toLowerCase().startsWith("gemma");ot=ga(r,((ke||"gemma").toLowerCase().startsWith("gemma"),a),i,l,h,_,f,f==="Google"?!0:y,N,d),l?.dynamicDirAwareness||(ot+=`
1049
+ `+(ie.parts?.[0]?.text||""),ie.parts?.length>1&&G.parts.push(...ie.parts.slice(1))):at.push(ie)}}de.length=0,de.push(...at),ke=e;let jt=`${d}|${f}|${i}|${a}|${ke}|${JSON.stringify(r)}|${!!l?.dynamicDirAwareness}|${!!l?.subAgents}`,Vt=So.key===jt&&So.value;if((process.env.I_HAVE_TOO_MUCH_MONEY==="true"||process.env.I_HAVE_TOO_MUCH_MONEY===!0)&&(Vt=!1),Vt)ot=So.value;else{let N=f==="Mistral"?!!vo(ke):!(ke||"gemma").toLowerCase().startsWith("gemma");ot=ga(r,((ke||"gemma").toLowerCase().startsWith("gemma"),a),i,l,h,_,f,f==="Google"?!0:y,N,d),l?.dynamicDirAwareness||(ot+=`
1000
1050
  ${ki.replace(`
1001
1051
  **Directory Structure**`,`
1002
- -- Directory Structure --`)}`),bo.key=Wt,bo.value=ot}let It=de[de.length-1];if(Hs()&z>0){await new Promise(G=>setTimeout(G,2500)),yield{type:"status",content:"Verifying"};let N=await wo(),ie=N?N.diagnostics:null;ie&&It&&It.role==="user"&&It.parts?.[0]?.text&&(It.parts[0].text+=`
1003
- ${ie} [/ERROR]`),yield{type:"status",content:"Working"}}let Hn=f==="Mistral"||f==="Google"&&e?.toLowerCase().startsWith("gemma");if(l?.advanceRollback&&It&&It.role==="user"&&It.parts?.[0]?.text?.startsWith("[TOOL RESULT]"))try{let N=await Qn.getLatestFileChanges(d);if(N&&(N.newFiles.length>0||N.modifiedFiles.length>0||N.deletedFiles.length>0)){let ie=`
1052
+ -- Directory Structure --`)}`),So.key=jt,So.value=ot}let Ot=de[de.length-1];if(Hs()&z>0){await new Promise(G=>setTimeout(G,2500)),yield{type:"status",content:"Verifying"};let N=await xo(),ie=N?N.diagnostics:null;ie&&Ot&&Ot.role==="user"&&Ot.parts?.[0]?.text&&(Ot.parts[0].text+=`
1053
+ ${ie} [/ERROR]`),yield{type:"status",content:"Working"}}let qn=f==="Mistral"||f==="Google"&&e?.toLowerCase().startsWith("gemma");if(l?.advanceRollback&&Ot&&Ot.role==="user"&&Ot.parts?.[0]?.text?.startsWith("[TOOL RESULT]"))try{let N=await Zn.getLatestFileChanges(d);if(N&&(N.newFiles.length>0||N.modifiedFiles.length>0||N.deletedFiles.length>0)){let ie=`
1004
1054
  [system] File Changes:
1005
1055
  `;for(let H of N.newFiles)ie+=`* ${H} (created)
1006
1056
  `;for(let H of N.modifiedFiles)ie+=`* ${H} (modified)
1007
1057
  `;for(let H of N.deletedFiles)ie+=`* ${H} (deleted)
1008
- `;ie+="[/system]",It.parts[0].text+=ie;let G=-1;for(let H=b.length-1;H>=0;H--)if(b[H].role==="user"&&b[H].text?.startsWith("[TOOL RESULT]")){G=H;break}G!==-1&&(b[G].text+=ie)}}catch{}let rn=Math.floor(Wo*(i==="Flux"?.98:.8)),Ot=z+1;Ot>=rn&&It&&It.parts?.[0]&&(It.parts[0].text+=`
1009
- [system] WARNING, Turn Limit Impending: Step ${Ot}/${Wo}. Wrap up quickly/prompt user to continue. [/system]`);let Dt=new Promise((N,ie)=>{E.signal.aborted&&ie(new DOMException("The user aborted a request.","AbortError")),E.signal.addEventListener("abort",()=>{ie(new DOMException("The user aborted a request.","AbortError"))})});Dt.catch(()=>{});let Lt=de;if(f==="Ollama")Ee=mi(t.apiKey,ke,Lt,ot,a,i,y,E.signal,1,l?.ollamaEndpoint||"Cloud");else if(f==="OpenRouter")Ee=Vs(t.apiKey,ke,Lt,ot,a,i,y,E.signal,1,d);else if(f==="DeepSeek")Ee=zs(t.apiKey,ke,Lt,ot,a,i,y,E.signal,1);else if(f==="Mistral")Ee=Ks(t.apiKey,ke,Lt,ot,a,i,y,E.signal,1,d);else if(f==="NVIDIA"){let N=Ys(t.apiKey,ke,Lt,ot,a,i,y,E.signal,1);Ee=sl(N,ke)}else if(f==="CrofAI")Ee=Xs(t.apiKey,ke,Lt,ot,a,i,y,E.signal,1);else if(f==="InferX")Ee=Js(t.apiKey,ke,Lt,ot,a,i,y,E.signal,1);else if(f==="SenseNova")Ee=Qs(t.apiKey,ke,Lt,ot,a,i,y,E.signal,1);else if(f==="AIHubMix")Ee=Zs(t.apiKey,ke,Lt,ot,a,i,y,E.signal,1);else{let ie=wi(t?.apiKey).models.generateContentStream({model:ke||"gemini-3-flash-preview",contents:Lt,config:{systemInstruction:ot,mediaResolution:"MEDIA_RESOLUTION_HIGH",safetySettings:[{category:eo.HARM_CATEGORY_HARASSMENT,threshold:Zn.BLOCK_NONE},{category:eo.HARM_CATEGORY_HATE_SPEECH,threshold:Zn.BLOCK_NONE},{category:eo.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Zn.BLOCK_NONE},{category:eo.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Zn.BLOCK_NONE}],temperature:1.05,thinkingConfig:(()=>{let G=(ke||"").toLowerCase(),H=G.includes("gemma-4")||G.startsWith("gemma"),xe=G.includes("gemini-3");if(H||xe)return H?a.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:pt.MINIMAL}:{includeThoughts:!0,thinkingLevel:pt.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:G.includes("pro")?pt.LOW:pt.MINIMAL,Low:pt.LOW,Medium:pt.MEDIUM,Standard:pt.MEDIUM,High:pt.HIGH,xHigh:pt.HIGH}[a]||pt.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:E.signal});Ee=await Promise.race([ie,Dt])}ue="",Nt=null,sn=null,ne=[],ze=0,yield{type:"model_update",content:null},Ye="",Bt=it.length>0;let kn="",ir=Date.now(),ro=async function*(){if(f==="Google"&&kn){let N=Go(kn);for(let ie of N)yield ie;kn="",ir=Date.now()}},Ai=!0,io="",To=!1,jt=null,Sl={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|>"}},Go=N=>{let ie=[],G=N;for(;G.length>0;)if(To){let H=io+G,xe=Sl[jt];if(xe){let st=!1;if(H.length<xe.startPrefix.length?xe.startPrefix.startsWith(H)||(st=!0):H.startsWith(xe.startPrefix)?H.length>=xe.fullPrefix.length&&!H.startsWith(xe.fullPrefix)&&(st=!0):st=!0,st){ie.push({type:"text",content:H}),io="",To=!1,jt=null,G="";break}}let me=-1,Ce=xe?xe.endTag:"]";if(jt==="tool"||jt==="agent"){let st=0,j=null,se=0,Ue=!1;for(let A=0;A<H.length;A++){let Be=H[A];if(j){if(Be===j){let ve=0;for(let J=A-1;J>=0&&H[J]==="\\";J--)ve++;ve%2===0&&(j=null)}}else if(Be==='"'||Be==="'"||Be==="`")j=Be;else if(Be==="(")st++,Ue=!0;else if(Be===")")st--;else if(Be==="[")se++;else if(Be==="]"){if(Ue&&st===0&&se===1){me=A;break}se--}}}else me=H.indexOf(Ce);if(me!==-1){let st=Ce.length;if(!jt?.startsWith("kimi")){let j=H.substring(0,me+st);ie.push({type:"text",content:j})}io="",To=!1,jt=null,G=H.substring(me+st)}else{let st=jt?.startsWith("kimi")?8192:512;H.length>st?(ie.push({type:"text",content:H}),io="",To=!1,jt=null):io=H,G="";break}}else{let H=G.indexOf("[tool"),xe=G.indexOf("[agent"),me=G.indexOf("[[END]]"),Ce=G.indexOf("<|tool_calls_section_begin|>"),st=G.indexOf("<|tool_call_begin|>"),j=[{type:"tool",idx:H,start:"[tool",end:"]"},{type:"agent",idx:xe,start:"[agent",end:"]"},{type:"end",idx:me,start:"[[END]]",end:"[[END]]"},{type:"kimi_section",idx:Ce,start:"<|tool_calls_section_begin|>",end:"<|tool_calls_section_end|>"},{type:"kimi_call",idx:st,start:"<|tool_call_begin|>",end:"<|tool_call_end|>"}].filter(se=>se.idx!==-1).sort((se,Ue)=>se.idx-Ue.idx);if(j.length>0){let se=j[0];se.idx>0&&ie.push({type:"text",content:G.substring(0,se.idx)}),To=!0,jt=se.type,io="",G=G.substring(se.idx)}else{let se=["[tool","[agent","[[END]]","<|tool_calls_section_begin|>","<|tool_call_begin|>"],Ue=-1;for(let A of se){for(let Be=A.length-1;Be>0;Be--)if(G.endsWith(A.substring(0,Be))){Ue=G.length-Be;let ve=se.indexOf(A);ve===0?jt="tool":ve===1?jt="agent":ve===2?jt="end":ve===3?jt="kimi_section":jt="kimi_call";break}if(Ue!==-1)break}if(Ue!==-1)Ue>0&&ie.push({type:"text",content:G.substring(0,Ue)}),To=!0,io=G.substring(Ue),G="";else{ie.push({type:"text",content:G});break}}}return ie},kl=Ee[Symbol.asyncIterator]();for(;;){let{value:N,done:ie}=await Promise.race([kl.next(),Dt]);if(ie)break;if(N&&N.type==="status"){yield N;continue}let G="",H=N.candidates?.[0]?.content?.parts;if(H&&H.length>0)for(let me of H){let Ce=typeof me.text=="string"?me.text:me.text?parseChunkText(me.text):"";me.thought?Ce&&(ce||(G+="<think>",ce=!0),G+=Ce):Ce&&(ce&&(G+="</think>",ce=!1),G+=Ce)}else N.text&&ce&&(G+="</think>",ce=!1);G=rd(G);let xe=G?G.trim().split(/\s+/).filter(Boolean).length:0;if(t&&typeof t.onTokenChunk=="function"&&t.onTokenChunk(G,xe),Ai&&(yield{type:"status",content:"Thinking"},Ai=!1),$t){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
1058
+ `;ie+="[/system]",Ot.parts[0].text+=ie;let G=-1;for(let H=b.length-1;H>=0;H--)if(b[H].role==="user"&&b[H].text?.startsWith("[TOOL RESULT]")){G=H;break}G!==-1&&(b[G].text+=ie)}}catch{}let an=Math.floor(jo*(i==="Flux"?.98:.8)),Lt=z+1;Lt>=an&&Ot&&Ot.parts?.[0]&&(Ot.parts[0].text+=`
1059
+ [system] WARNING, Turn Limit Impending: Step ${Lt}/${jo}. Wrap up quickly/prompt user to continue. [/system]`);let Dt=new Promise((N,ie)=>{E.signal.aborted&&ie(new DOMException("The user aborted a request.","AbortError")),E.signal.addEventListener("abort",()=>{ie(new DOMException("The user aborted a request.","AbortError"))})});Dt.catch(()=>{});let Pt=de;if(f==="Ollama")Ee=mi(t.apiKey,ke,Pt,ot,a,i,y,E.signal,1,l?.ollamaEndpoint||"Cloud");else if(f==="OpenRouter")Ee=Vs(t.apiKey,ke,Pt,ot,a,i,y,E.signal,1,d);else if(f==="DeepSeek")Ee=zs(t.apiKey,ke,Pt,ot,a,i,y,E.signal,1);else if(f==="Mistral")Ee=Ks(t.apiKey,ke,Pt,ot,a,i,y,E.signal,1,d);else if(f==="NVIDIA"){let N=Ys(t.apiKey,ke,Pt,ot,a,i,y,E.signal,1);Ee=sl(N,ke)}else if(f==="CrofAI")Ee=Xs(t.apiKey,ke,Pt,ot,a,i,y,E.signal,1);else if(f==="InferX")Ee=Js(t.apiKey,ke,Pt,ot,a,i,y,E.signal,1);else if(f==="SenseNova")Ee=Qs(t.apiKey,ke,Pt,ot,a,i,y,E.signal,1);else if(f==="AIHubMix")Ee=Zs(t.apiKey,ke,Pt,ot,a,i,y,E.signal,1);else{let ie=wi(t?.apiKey).models.generateContentStream({model:ke||"gemini-3-flash-preview",contents:Pt,config:{systemInstruction:ot,mediaResolution:"MEDIA_RESOLUTION_HIGH",safetySettings:[{category:to.HARM_CATEGORY_HARASSMENT,threshold:eo.BLOCK_NONE},{category:to.HARM_CATEGORY_HATE_SPEECH,threshold:eo.BLOCK_NONE},{category:to.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:eo.BLOCK_NONE},{category:to.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:eo.BLOCK_NONE}],temperature:1.05,thinkingConfig:(()=>{let G=(ke||"").toLowerCase(),H=G.includes("gemma-4")||G.startsWith("gemma"),xe=G.includes("gemini-3");if(H||xe)return H?a.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:pt.MINIMAL}:{includeThoughts:!0,thinkingLevel:pt.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:G.includes("pro")?pt.LOW:pt.MINIMAL,Low:pt.LOW,Medium:pt.MEDIUM,Standard:pt.MEDIUM,High:pt.HIGH,xHigh:pt.HIGH}[a]||pt.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:E.signal});Ee=await Promise.race([ie,Dt])}ue="",Ut=null,rn=null,ne=[],ze=0,yield{type:"model_update",content:null},Ye="",Wt=it.length>0;let Tn="",ir=Date.now(),io=async function*(){if(f==="Google"&&Tn){let N=Ho(Tn);for(let ie of N)yield ie;Tn="",ir=Date.now()}},Ai=!0,ao="",Ro=!1,Gt=null,Sl={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|>"}},Ho=N=>{let ie=[],G=N;for(;G.length>0;)if(Ro){let H=ao+G,xe=Sl[Gt];if(xe){let st=!1;if(H.length<xe.startPrefix.length?xe.startPrefix.startsWith(H)||(st=!0):H.startsWith(xe.startPrefix)?H.length>=xe.fullPrefix.length&&!H.startsWith(xe.fullPrefix)&&(st=!0):st=!0,st){ie.push({type:"text",content:H}),ao="",Ro=!1,Gt=null,G="";break}}let me=-1,Ce=xe?xe.endTag:"]";if(Gt==="tool"||Gt==="agent"){let st=0,j=null,se=0,Ue=!1;for(let A=0;A<H.length;A++){let Be=H[A];if(j){if(Be===j){let ve=0;for(let J=A-1;J>=0&&H[J]==="\\";J--)ve++;ve%2===0&&(j=null)}}else if(Be==='"'||Be==="'"||Be==="`")j=Be;else if(Be==="(")st++,Ue=!0;else if(Be===")")st--;else if(Be==="[")se++;else if(Be==="]"){if(Ue&&st===0&&se===1){me=A;break}se--}}}else me=H.indexOf(Ce);if(me!==-1){let st=Ce.length;if(!Gt?.startsWith("kimi")){let j=H.substring(0,me+st);ie.push({type:"text",content:j})}ao="",Ro=!1,Gt=null,G=H.substring(me+st)}else{let st=Gt?.startsWith("kimi")?8192:512;H.length>st?(ie.push({type:"text",content:H}),ao="",Ro=!1,Gt=null):ao=H,G="";break}}else{let H=G.indexOf("[tool"),xe=G.indexOf("[agent"),me=G.indexOf("[[END]]"),Ce=G.indexOf("<|tool_calls_section_begin|>"),st=G.indexOf("<|tool_call_begin|>"),j=[{type:"tool",idx:H,start:"[tool",end:"]"},{type:"agent",idx:xe,start:"[agent",end:"]"},{type:"end",idx:me,start:"[[END]]",end:"[[END]]"},{type:"kimi_section",idx:Ce,start:"<|tool_calls_section_begin|>",end:"<|tool_calls_section_end|>"},{type:"kimi_call",idx:st,start:"<|tool_call_begin|>",end:"<|tool_call_end|>"}].filter(se=>se.idx!==-1).sort((se,Ue)=>se.idx-Ue.idx);if(j.length>0){let se=j[0];se.idx>0&&ie.push({type:"text",content:G.substring(0,se.idx)}),Ro=!0,Gt=se.type,ao="",G=G.substring(se.idx)}else{let se=["[tool","[agent","[[END]]","<|tool_calls_section_begin|>","<|tool_call_begin|>"],Ue=-1;for(let A of se){for(let Be=A.length-1;Be>0;Be--)if(G.endsWith(A.substring(0,Be))){Ue=G.length-Be;let ve=se.indexOf(A);ve===0?Gt="tool":ve===1?Gt="agent":ve===2?Gt="end":ve===3?Gt="kimi_section":Gt="kimi_call";break}if(Ue!==-1)break}if(Ue!==-1)Ue>0&&ie.push({type:"text",content:G.substring(0,Ue)}),Ro=!0,ao=G.substring(Ue),G="";else{ie.push({type:"text",content:G});break}}}return ie},kl=Ee[Symbol.asyncIterator]();for(;;){let{value:N,done:ie}=await Promise.race([kl.next(),Dt]);if(ie)break;if(N&&N.type==="status"){yield N;continue}let G="",H=N.candidates?.[0]?.content?.parts;if(H&&H.length>0)for(let me of H){let Ce=typeof me.text=="string"?me.text:me.text?parseChunkText(me.text):"";me.thought?Ce&&(ce||(G+="<think>",ce=!0),G+=Ce):Ce&&(ce&&(G+="</think>",ce=!1),G+=Ce)}else N.text&&ce&&(G+="</think>",ce=!1);G=rd(G);let xe=G?G.trim().split(/\s+/).filter(Boolean).length:0;if(t&&typeof t.onTokenChunk=="function"&&t.onTokenChunk(G,xe),Ai&&(yield{type:"status",content:"Thinking"},Ai=!1),At){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
1010
1060
 
1011
- \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(G){if(Bt){if(Ye+=G,Ye.length>=64){let j=0,se=Math.min(it.length,Ye.length);for(let A=se;A>=10;A--)if(it.endsWith(Ye.substring(0,A))){j=A;break}let Ue=Ye.substring(j);if(Ue){let Be=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(it)?Ue.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):Ue.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(Be)if(ue+=Be,f==="Google")kn+=Be;else{yield*ro();let ve=Go(Be);for(let J of ve)yield J}}Bt=!1,Ye=""}continue}else if(ue+=G,f==="Google")kn+=G;else{yield*ro();let j=Go(G);for(let se of j)yield se}let me=pd(ue);if(me.inside){no=!0,sn||(sn=Date.now());let se={Ask:"ask",AskUser:"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,Ue=me.args||"",A=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(se)){let ve=D(Ue),J=ve.path||ve.targetFile||ve.TargetFile||ve.directory,Tn=ve.keyword,ao=ve.title||ve.task,qn=ve.id||ve.taskId,_e=ve.timeout||ve.time;if(Tn!=null)A=String(Tn).replace(xo,"");else if(J)A=Z.basename(String(J).replace(xo,"").replace(rl,"/"));else if(ao&&(se==="invoke"||se==="invoke_sync"))A=String(ao).replace(xo,"").substring(0,30);else if(qn&&se==="get_progress")A=String(qn).replace(xo,"");else if(_e&&se==="await"){let Gt=parseFloat(String(_e).replace(xo,""));isNaN(Gt)?A=String(_e).replace(xo,""):(Gt<5&&(Gt=5),Gt>120&&(Gt=120),A=(vn=>{if(vn>=60){let lr=Math.floor(vn/60),Ro=vn%60;return`${lr}m${Ro>0?` ${Ro}s`:""}`}return`${vn}s`})(Gt))}else{let Gt=Ue.match(nd);if(Gt){let Yt=Gt[1].replace(xo,"");se==="invoke"||se==="invoke_sync"||se==="get_progress"?A=Yt.substring(0,30):A=se==="search_keyword"||se==="file_map"?Yt:Z.basename(Yt.replace(rl,"/"))}}}let Be=`${gi[se]||se}${A?` ${A}`:""}`;if((se!==Nt||A!==Ze)&&(Nt=se,Ze=A,yield{type:"status",content:`${Be}`},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",AskUser:"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"}[se]||"Working";process.stdout.write(`\x1B]0;${J}...\x07`)}}if(ue.length-bs>150){bs=ue.length;let j=ml(ue,!1),se=hi(j),Ue=se?(se.innerContent||"").trim():"",A=Ue.split(/[.!?]\s+/),Be=new Set(A),ve=A.length>10?(A.length-Be.size)/A.length:0,J=Ue.split(/\s+/).filter(Ie=>Ie.length>0).length,Tn=.6,ao=.8,qn=!1;if((f.toLowerCase().includes("google")||f.toLowerCase().includes("mistral"))&&((ke||"").toLowerCase().startsWith("gemma")||(ke||"").toLowerCase().includes("stral"))){let M={low:256,medium:1024,high:8192,max:16384,xhigh:16384}[a?.toLowerCase()]||2500;qn=J>M}if(ve>Tn||qn){yield{type:"status",content:`${ve>Tn?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},Ut=!0,await new Promise(M=>setTimeout(M,3e3));break}let Yt=dl(ue).trim().split(/[.!?]\s+/),vn=new Set(Yt);if((Yt.length>10?(Yt.length-vn.size)/Yt.length:0)>ao){yield{type:"status",content:"Response Loop Detected. Re-centering..."},Ut=!1,Mn=!0,await new Promise(Ie=>setTimeout(Ie,3e3));break}let Ro=j.replace(Vc,"").replace(Xc,"").replace(Jc,"").replace(Qc,""),Ht=Ro.toLowerCase().split(/\s+/).map(Ie=>Ie.replace(Zc,"")).filter(Ie=>Ie.length>0),In=!1;if(Ht.length>=10)for(let Ie=1;Ie<=15;Ie++){let M=Math.max(3,Math.ceil(10/Ie));if(Ht.length<Ie*M)continue;let Y=Ht.slice(Ht.length-Ie),ae=Y.join(" ");if(Ie>1&&ae===Y.slice(0,Math.floor(Ie/2)).join(" ").repeat(2).trim())continue;let ge=!0;for(let be=1;be<M;be++)if(Ht.slice(Ht.length-Ie*(be+1),Ht.length-Ie*be).join(" ")!==ae){ge=!1;break}if(ge){In=!0;break}}if(!In){let Ie=Ro.toLowerCase().replace(ed,"");if(Ie.length>=20)for(let M=1;M<=10;M++){let Y=Math.max(5,Math.ceil(16/M));if(Ie.length<M*Y)continue;let ae=Ie.substring(Ie.length-M),ge=!0;for(let be=1;be<Y;be++)if(Ie.substring(Ie.length-M*(be+1),Ie.length-M*be)!==ae){ge=!1;break}if(ge){In=!0;break}}}if(In){yield{type:"status",content:"Stuttering Detected. Re-centering..."},Ut=!1,Sn=!0,await new Promise(Ie=>setTimeout(Ie,3e3));break}}let Ce=nn(ue),st=nr(Ce);for(;st.length>ze;){yield*ro();let j=st[ze],se=Date.now(),A={Ask:"ask",AskUser:"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"}[j.toolName]||j.toolName,Be=gi[A]||j.toolName,ve=So(A,j.args);yield{type:"status",content:`${Be}${ve?` ${ve}`:""}`};let J="";if(A==="click"){let M=D(j.args);J=`\u2714 Clicked: ${M.intendedClickText?`${M.intendedClickText}`:""}`}else if(A==="drag"){let M=D(j.args);J=`\u2714 Dragged: Cell ${M.fromGridId||""} \u2192 Cell ${M.toGridId||""}`}else if(A==="scroll"){let M=D(j.args);J=`\u2714 Scrolled: ${M.direction||"down"} (${M.amount||1})`}else if(A==="keyboard_typing"){let M=D(j.args);J=`\u2714 Typed: ${M.text?`"${M.text.length>20?M.text.substring(0,20)+"...":M.text}"`:""}`}else if(A==="key_press")J=`\u2714 Pressed Key: ${D(j.args).key||""}`;else if(A==="recapture_screen")J="\u2714 Recaptured Screen";else if(A==="web_search"){let{query:M,limit:Y=10,aiMode:ae=!1}=D(j.args);J=`${M?"\u2714":"\u2718"} ${ae?"AI Search":"Searched"}: ${M?`${M}`:"No Search Query"}${ae===!1&&M?` \u2192 ${Y}`:""}`}else if(A==="web_scrape"){let M=D(j.args).url||null;J=`${M?"\u2714":"\u2718"} Visited: ${M||"No Source"}`}else if(A==="view_file"){let{path:M,StartLine:Y,EndLine:ae,start_line:ge,end_line:be,startLine:Ge,endLine:De}=D(j.args),Se=Y||ge||Ge,re=ae||be||De,fe=parseInt(Se)||1,le=parseInt(re)||(Se?fe+800:800),$e="...",Ve=le,Ae=(M||"").trim().toLowerCase().replaceAll("\\","/");if(Ae.startsWith("#skill"))Ae.startsWith("#skill/global/fluxflow")||Ae.startsWith("#skills/global/fluxflow")?J="\u2714 Read Documentation":J=`\u2714 Read Skill: ${Z.basename(M.replaceAll("\\","/"))}`;else{try{let he=Z.resolve(process.cwd(),M);if(Fe.existsSync(he)){let kt=Fe.readFileSync(he,"utf8").split(`
1012
- `).length;$e=kt,!Se&&!re&&kt>800?Ve=Math.min(50,kt):Ve=Math.min(le,kt)}}catch{}let Le=(M||"").toLowerCase(),yt=Le.endsWith(".pdf"),Oe=Le.endsWith(".docx")||Le.endsWith(".doc")||Le.endsWith(".ppt")||Le.endsWith(".pptx")||Le.endsWith(".xls")||Le.endsWith(".xlsx"),rt=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(Le);yt||Oe?J=`${M.length>0?"\u2714":"\u2718"} ${M?`Analyzed: ${Z.basename(M)}`:"Analyzed: File Not Found"}`:rt?J=`${M.length>0?"\u2714":"\u2718"} ${M?`Processed: ${Z.basename(M)}`:"Processed: File Not Found"}`:J=`${$e!=="..."?"\u2714":"\u2718"} Read: ${M?`${Z.basename(M)} \u2192 ${$e!=="..."?`Lines ${fe} - ${Ve} of ${$e}`:"File Not Found"}`:"File Not Found"}`}}else if(A==="list_files"||A==="read_folder"){let M=A==="list_files"?"List":"Browsed",Y=D(j.args).path||null,ae=D(j.args).recurse||1;J=`${Y?"\u2714":"\u2718"} ${M}: ${Y?`${Y==="."?`./${ae>1?"*":""}`:`${Y.replaceAll("\\","/")}${ae>1?`${Y.endsWith("/")?"*":"/*"}`:`${Y.endsWith("/")?"":"/"}`}`}`:"No Folder Selected"}`}else if(A==="write_file"||A==="update_file"){let M=A==="write_file"?"Created":"Edited",Y=D(j.args).path||null;J=`${Y?"\u2714":"\u2718"} ${M}: ${Y.replaceAll("\\","/")||"No File Changes"}`}else if(A==="write_pdf"){let M=D(j.args).path||null;J=`${M?"\u2714":"\u2718"} Generated: ${M.replaceAll("\\","/")||"No PDF Generated"}`}else if(A==="write_docx"){let M=D(j.args).path||null;J=`${M?"\u2714":"\u2718"} Generated: ${M.replaceAll("\\","/")||"No Docx Generated"}`}else if(A==="file_map"){let M=D(j.args).path;J=`${M?"\u2714":"\u2718"} Indexed: ${M.replaceAll("\\","/")?""+M:"File Not Found"}`}else if(A.toLowerCase()==="search_keyword"||A.toLowerCase()==="todo")J="";else if(A.toLowerCase()==="generate_image"){let{path:M,outputPath:Y,output:ae}=D(j.args);J=`\u2714 Generated: ${M||Y||ae||"generated_image.png"}`}else if(A==="invoke_sync"||A==="InvokeSync"){let M=So(A,j.args);J=`\u2714 Called Generalist${M?`: ${M}`:""}`}else if(A==="Invoke"||A==="InvokeAsync"||A==="invoke"){let M=So(A,j.args);J=`\u2714 Started Generalist${M?`: ${M}`:""}`}else if(A==="get_progress"||A==="GetProgress"){let M=So(A,j.args);J=`\u2714 Checked${M?`: ${M}`:""}`}else if(A==="cancel"){let M=So(A,j.args);J=`\u{1F6C7} Cancelled${M?`: ${M}`:""}`}else if(A==="steer"||A==="Steer"){let M=So(A,j.args);J=`\u2714 Steered${M?`: ${M}`:""}`}else if(A==="EmergencyRollback"){let{method:M}=D(j.args);J=M==="forceRevert"?"":"\u2714 Rollback Point Checked"}else if(A==="await"||A==="Await"){let{time:M,timeout:Y}=D(j.args),ae=parseFloat(Y||M)||0;ae||(ae=120);let ge=De=>{if(De>=60){let Se=Math.floor(De/60),re=De%60;return`${Se}m${re>0?` ${re}s`:""}`}return`${De}s`},be=["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 ${be[Math.floor(Math.random()*be.length)]} \u2192 ${ge(ae)}`}else A==="Answer"||A==="answer"?J="\u2714 Resolved Sub-Agent Query":A==="exec_command"||A==="ask"?J="":J=`Executed: ${j.toolName}`;if(yield*ro(),A==="exec_command"){let{command:M}=D(j.args);if(M&&t.systemSettings&&t.systemSettings.allowExternalAccess===!1){let Y=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],ae=Z.resolve(process.cwd()).substring(0,3).toLowerCase(),ge=re=>{let fe=[],le="",$e=null;for(let Ve=0;Ve<re.length;Ve++){let Ae=re[Ve];$e?(Ae===$e&&($e=null),le+=Ae):Ae==='"'||Ae==="'"?($e=Ae,le+=Ae):Ae==="&"&&re[Ve+1]==="&"||Ae==="|"&&re[Ve+1]==="|"?(le.trim()&&(fe.push(le.trim()),le=""),Ve++):Ae===";"||Ae==="|"||Ae==="&"?le.trim()&&(fe.push(le.trim()),le=""):le+=Ae}return le.trim()&&fe.push(le.trim()),fe},be=re=>{let fe=[],le="",$e=null;for(let Ve=0;Ve<re.length;Ve++){let Ae=re[Ve];$e?(Ae===$e&&($e=null),le+=Ae):Ae==='"'||Ae==="'"?($e=Ae,le+=Ae):/\s/.test(Ae)?le&&(fe.push(le),le=""):le+=Ae}return le&&fe.push(le),fe},Ge=re=>{let fe=re.replace(/^['"]|['"]$/g,"").trim();return!fe||process.platform==="win32"&&/^\/[a-zA-Z0-9?]+$/.test(fe)?!1:Y.some(le=>{if(le.source==="[a-zA-Z]:[\\\\\\/]"){let $e=fe.match(/[a-zA-Z]:[\\\/]/i);return $e&&$e[0].toLowerCase()!==ae}return le.test(fe)})};if(ge(M).some(re=>{let fe=be(re);if(fe.length===0)return!1;let le=fe[0].replace(/^['"]|['"]$/g,"").toLowerCase();if(["echo","printf","write-output"].includes(le)){let Ve=!1;return fe.some(Ae=>{let Vt=Ae.replace(/^['"]|['"]$/g,"");if(Vt===">"||Vt===">>"||Vt==="<")return Ve=!0,!1;if(Vt.startsWith(">")||Vt.startsWith("<")){let Le=Vt.replace(/^[><]+/,"");return Ge(Le)}return Ve?(Ve=!1,Ge(Ae)):!1})}return fe.some(Ve=>Ge(Ve))})){let re='Access Denied. Prohibited from accessing external directories while "External Workspace Access" is disabled.';t.onExecStart&&t.onExecStart(M||"No Command"),yield{type:"exec_start"},await new Promise(fe=>setTimeout(fe,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${re}`),await new Promise(fe=>setTimeout(fe,50)),t.onExecEnd&&t.onExecEnd(),ne.push({role:"user",text:`[TOOL RESULT]: ERROR: ${re}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${re}`},ze++;continue}}t.onExecStart&&t.onExecStart(M||"No Command"),yield{type:"exec_start"}}let Tn=D(j.args),ao=Tn.path||Tn.targetPath||null;if(ao){let M=t.systemSettings&&t.systemSettings.allowExternalAccess===!1,Y=Z.resolve(ao),ae=Z.resolve(process.cwd());if(M&&!Y.startsWith(ae)){let ge="Access Denied. You are not allowed to access files outside the current workspace.";if(A==="write_file"||A==="update_file"){let Ge=`\u2718 ${A==="write_file"?"Write Canceled":"Edit Canceled"}: ${Tn.path||"..."}`,De=115;process.stdout.isTTY&&(De=process.stdout.columns-5||120);let Se=Math.min(Ge.length+4,De),re=`${Ge.padEnd(Se-2).substring(0,Se-2)}`;yield{type:"visual_feedback",content:tn(`${je?`
1061
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(G){if(Wt){if(Ye+=G,Ye.length>=64){let j=0,se=Math.min(it.length,Ye.length);for(let A=se;A>=10;A--)if(it.endsWith(Ye.substring(0,A))){j=A;break}let Ue=Ye.substring(j);if(Ue){let Be=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(it)?Ue.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):Ue.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(Be)if(ue+=Be,f==="Google")Tn+=Be;else{yield*io();let ve=Ho(Be);for(let J of ve)yield J}}Wt=!1,Ye=""}continue}else if(ue+=G,f==="Google")Tn+=G;else{yield*io();let j=Ho(G);for(let se of j)yield se}let me=pd(ue);if(me.inside){oo=!0,rn||(rn=Date.now());let se={Ask:"ask",AskUser:"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,Ue=me.args||"",A=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(se)){let ve=L(Ue),J=ve.path||ve.targetFile||ve.TargetFile||ve.directory,Rn=ve.keyword,lo=ve.title||ve.task,zn=ve.id||ve.taskId,_e=ve.timeout||ve.time;if(Rn!=null)A=String(Rn).replace(bo,"");else if(J)A=Z.basename(String(J).replace(bo,"").replace(rl,"/"));else if(lo&&(se==="invoke"||se==="invoke_sync"))A=String(lo).replace(bo,"").substring(0,30);else if(zn&&se==="get_progress")A=String(zn).replace(bo,"");else if(_e&&se==="await"){let Ht=parseFloat(String(_e).replace(bo,""));isNaN(Ht)?A=String(_e).replace(bo,""):(Ht<5&&(Ht=5),Ht>120&&(Ht=120),A=(In=>{if(In>=60){let lr=Math.floor(In/60),Eo=In%60;return`${lr}m${Eo>0?` ${Eo}s`:""}`}return`${In}s`})(Ht))}else{let Ht=Ue.match(nd);if(Ht){let Xt=Ht[1].replace(bo,"");se==="invoke"||se==="invoke_sync"||se==="get_progress"?A=Xt.substring(0,30):A=se==="search_keyword"||se==="file_map"?Xt:Z.basename(Xt.replace(rl,"/"))}}}let Be=`${gi[se]||se}${A?` ${A}`:""}`;if((se!==Ut||A!==Ze)&&(Ut=se,Ze=A,yield{type:"status",content:`${Be}`},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",AskUser:"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"}[se]||"Working";process.stdout.write(`\x1B]0;${J}...\x07`)}}if(ue.length-bs>150){bs=ue.length;let j=ml(ue,!1),se=hi(j),Ue=se?(se.innerContent||"").trim():"",A=Ue.split(/[.!?]\s+/),Be=new Set(A),ve=A.length>10?(A.length-Be.size)/A.length:0,J=Ue.split(/\s+/).filter(Ie=>Ie.length>0).length,Rn=.6,lo=.8,zn=!1;if((f.toLowerCase().includes("google")||f.toLowerCase().includes("mistral"))&&((ke||"").toLowerCase().startsWith("gemma")||(ke||"").toLowerCase().includes("stral"))){let M={low:256,medium:1024,high:8192,max:16384,xhigh:16384}[a?.toLowerCase()]||2500;zn=J>M}if(ve>Rn||zn){yield{type:"status",content:`${ve>Rn?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},Bt=!0,await new Promise(M=>setTimeout(M,3e3));break}let Xt=dl(ue).trim().split(/[.!?]\s+/),In=new Set(Xt);if((Xt.length>10?(Xt.length-In.size)/Xt.length:0)>lo){yield{type:"status",content:"Response Loop Detected. Re-centering..."},Bt=!1,vn=!0,await new Promise(Ie=>setTimeout(Ie,3e3));break}let Eo=j.replace(Vc,"").replace(Xc,"").replace(Jc,"").replace(Qc,""),qt=Eo.toLowerCase().split(/\s+/).map(Ie=>Ie.replace(Zc,"")).filter(Ie=>Ie.length>0),On=!1;if(qt.length>=10)for(let Ie=1;Ie<=15;Ie++){let M=Math.max(3,Math.ceil(10/Ie));if(qt.length<Ie*M)continue;let Y=qt.slice(qt.length-Ie),ae=Y.join(" ");if(Ie>1&&ae===Y.slice(0,Math.floor(Ie/2)).join(" ").repeat(2).trim())continue;let ge=!0;for(let be=1;be<M;be++)if(qt.slice(qt.length-Ie*(be+1),qt.length-Ie*be).join(" ")!==ae){ge=!1;break}if(ge){On=!0;break}}if(!On){let Ie=Eo.toLowerCase().replace(ed,"");if(Ie.length>=20)for(let M=1;M<=10;M++){let Y=Math.max(5,Math.ceil(16/M));if(Ie.length<M*Y)continue;let ae=Ie.substring(Ie.length-M),ge=!0;for(let be=1;be<Y;be++)if(Ie.substring(Ie.length-M*(be+1),Ie.length-M*be)!==ae){ge=!1;break}if(ge){On=!0;break}}}if(On){yield{type:"status",content:"Stuttering Detected. Re-centering..."},Bt=!1,kn=!0,await new Promise(Ie=>setTimeout(Ie,3e3));break}}let Ce=on(ue),st=nr(Ce);for(;st.length>ze;){yield*io();let j=st[ze],se=Date.now(),A={Ask:"ask",AskUser:"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"}[j.toolName]||j.toolName,Be=gi[A]||j.toolName,ve=ko(A,j.args);yield{type:"status",content:`${Be}${ve?` ${ve}`:""}`};let J="";if(A==="click"){let M=L(j.args);J=`\u2714 Clicked: ${M.intendedClickText?`${M.intendedClickText}`:""}`}else if(A==="drag"){let M=L(j.args);J=`\u2714 Dragged: Cell ${M.fromGridId||""} \u2192 Cell ${M.toGridId||""}`}else if(A==="scroll"){let M=L(j.args);J=`\u2714 Scrolled: ${M.direction||"down"} (${M.amount||1})`}else if(A==="keyboard_typing"){let M=L(j.args);J=`\u2714 Typed: ${M.text?`"${M.text.length>20?M.text.substring(0,20)+"...":M.text}"`:""}`}else if(A==="key_press")J=`\u2714 Pressed Key: ${L(j.args).key||""}`;else if(A==="recapture_screen")J="\u2714 Recaptured Screen";else if(A==="web_search"){let{query:M,limit:Y=10,aiMode:ae=!1}=L(j.args);J=`${M?"\u2714":"\u2718"} ${ae?"AI Search":"Searched"}: ${M?`${M}`:"No Search Query"}${ae===!1&&M?` \u2192 ${Y}`:""}`}else if(A==="web_scrape"){let M=L(j.args).url||null;J=`${M?"\u2714":"\u2718"} Visited: ${M||"No Source"}`}else if(A==="view_file"){let{path:M,StartLine:Y,EndLine:ae,start_line:ge,end_line:be,startLine:Ge,endLine:Le}=L(j.args),Se=Y||ge||Ge,re=ae||be||Le,fe=parseInt(Se)||1,le=parseInt(re)||(Se?fe+800:800),$e="...",Ve=le,Ae=(M||"").trim().toLowerCase().replaceAll("\\","/");if(Ae.startsWith("#skill"))Ae.startsWith("#skill/global/fluxflow")||Ae.startsWith("#skills/global/fluxflow")?J="\u2714 Read Documentation":J=`\u2714 Read Skill: ${Z.basename(M.replaceAll("\\","/"))}`;else{try{let he=Z.resolve(process.cwd(),M);if(Fe.existsSync(he)){let kt=Fe.readFileSync(he,"utf8").split(`
1062
+ `).length;$e=kt,!Se&&!re&&kt>800?Ve=Math.min(50,kt):Ve=Math.min(le,kt)}}catch{}let De=(M||"").toLowerCase(),yt=De.endsWith(".pdf"),Oe=De.endsWith(".docx")||De.endsWith(".doc")||De.endsWith(".ppt")||De.endsWith(".pptx")||De.endsWith(".xls")||De.endsWith(".xlsx"),rt=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(De);yt||Oe?J=`${M.length>0?"\u2714":"\u2718"} ${M?`Analyzed: ${Z.basename(M)}`:"Analyzed: File Not Found"}`:rt?J=`${M.length>0?"\u2714":"\u2718"} ${M?`Processed: ${Z.basename(M)}`:"Processed: File Not Found"}`:J=`${$e!=="..."?"\u2714":"\u2718"} Read: ${M?`${Z.basename(M)} \u2192 ${$e!=="..."?`Lines ${fe} - ${Ve} of ${$e}`:"File Not Found"}`:"File Not Found"}`}}else if(A==="list_files"||A==="read_folder"){let M=A==="list_files"?"List":"Browsed",Y=L(j.args).path||null,ae=L(j.args).recurse||1;J=`${Y?"\u2714":"\u2718"} ${M}: ${Y?`${Y==="."?`./${ae>1?"*":""}`:`${Y.replaceAll("\\","/")}${ae>1?`${Y.endsWith("/")?"*":"/*"}`:`${Y.endsWith("/")?"":"/"}`}`}`:"No Folder Selected"}`}else if(A==="write_file"||A==="update_file"){let M=A==="write_file"?"Created":"Edited",Y=L(j.args).path||null;J=`${Y?"\u2714":"\u2718"} ${M}: ${Y.replaceAll("\\","/")||"No File Changes"}`}else if(A==="write_pdf"){let M=L(j.args).path||null;J=`${M?"\u2714":"\u2718"} Generated: ${M.replaceAll("\\","/")||"No PDF Generated"}`}else if(A==="write_docx"){let M=L(j.args).path||null;J=`${M?"\u2714":"\u2718"} Generated: ${M.replaceAll("\\","/")||"No Docx Generated"}`}else if(A==="file_map"){let M=L(j.args).path;J=`${M?"\u2714":"\u2718"} Indexed: ${M.replaceAll("\\","/")?""+M:"File Not Found"}`}else if(A.toLowerCase()==="search_keyword"||A.toLowerCase()==="todo")J="";else if(A.toLowerCase()==="generate_image"){let{path:M,outputPath:Y,output:ae}=L(j.args);J=`\u2714 Generated: ${M||Y||ae||"generated_image.png"}`}else if(A==="invoke_sync"||A==="InvokeSync"){let M=ko(A,j.args);J=`\u2714 Called Generalist${M?`: ${M}`:""}`}else if(A==="Invoke"||A==="InvokeAsync"||A==="invoke"){let M=ko(A,j.args);J=`\u2714 Started Generalist${M?`: ${M}`:""}`}else if(A==="get_progress"||A==="GetProgress"){let M=ko(A,j.args);J=`\u2714 Checked${M?`: ${M}`:""}`}else if(A==="cancel"){let M=ko(A,j.args);J=`\u{1F6C7} Cancelled${M?`: ${M}`:""}`}else if(A==="steer"||A==="Steer"){let M=ko(A,j.args);J=`\u2714 Steered${M?`: ${M}`:""}`}else if(A==="EmergencyRollback"){let{method:M}=L(j.args);J=M==="forceRevert"?"":"\u2714 Rollback Point Checked"}else if(A==="await"||A==="Await"){let{time:M,timeout:Y}=L(j.args),ae=parseFloat(Y||M)||0;ae||(ae=120);let ge=Le=>{if(Le>=60){let Se=Math.floor(Le/60),re=Le%60;return`${Se}m${re>0?` ${re}s`:""}`}return`${Le}s`},be=["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 ${be[Math.floor(Math.random()*be.length)]} \u2192 ${ge(ae)}`}else A==="Answer"||A==="answer"?J="\u2714 Resolved Sub-Agent Query":A==="exec_command"||A==="ask"?J="":J=`Executed: ${j.toolName}`;if(yield*io(),A==="exec_command"){let{command:M}=L(j.args);if(M&&t.systemSettings&&t.systemSettings.allowExternalAccess===!1){let Y=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],ae=Z.resolve(process.cwd()).substring(0,3).toLowerCase(),ge=re=>{let fe=[],le="",$e=null;for(let Ve=0;Ve<re.length;Ve++){let Ae=re[Ve];$e?(Ae===$e&&($e=null),le+=Ae):Ae==='"'||Ae==="'"?($e=Ae,le+=Ae):Ae==="&"&&re[Ve+1]==="&"||Ae==="|"&&re[Ve+1]==="|"?(le.trim()&&(fe.push(le.trim()),le=""),Ve++):Ae===";"||Ae==="|"||Ae==="&"?le.trim()&&(fe.push(le.trim()),le=""):le+=Ae}return le.trim()&&fe.push(le.trim()),fe},be=re=>{let fe=[],le="",$e=null;for(let Ve=0;Ve<re.length;Ve++){let Ae=re[Ve];$e?(Ae===$e&&($e=null),le+=Ae):Ae==='"'||Ae==="'"?($e=Ae,le+=Ae):/\s/.test(Ae)?le&&(fe.push(le),le=""):le+=Ae}return le&&fe.push(le),fe},Ge=re=>{let fe=re.replace(/^['"]|['"]$/g,"").trim();return!fe||process.platform==="win32"&&/^\/[a-zA-Z0-9?]+$/.test(fe)?!1:Y.some(le=>{if(le.source==="[a-zA-Z]:[\\\\\\/]"){let $e=fe.match(/[a-zA-Z]:[\\\/]/i);return $e&&$e[0].toLowerCase()!==ae}return le.test(fe)})};if(ge(M).some(re=>{let fe=be(re);if(fe.length===0)return!1;let le=fe[0].replace(/^['"]|['"]$/g,"").toLowerCase();if(["echo","printf","write-output"].includes(le)){let Ve=!1;return fe.some(Ae=>{let Jt=Ae.replace(/^['"]|['"]$/g,"");if(Jt===">"||Jt===">>"||Jt==="<")return Ve=!0,!1;if(Jt.startsWith(">")||Jt.startsWith("<")){let De=Jt.replace(/^[><]+/,"");return Ge(De)}return Ve?(Ve=!1,Ge(Ae)):!1})}return fe.some(Ve=>Ge(Ve))})){let re='Access Denied. Prohibited from accessing external directories while "External Workspace Access" is disabled.';t.onExecStart&&t.onExecStart(M||"No Command"),yield{type:"exec_start"},await new Promise(fe=>setTimeout(fe,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${re}`),await new Promise(fe=>setTimeout(fe,50)),t.onExecEnd&&t.onExecEnd(),ne.push({role:"user",text:`[TOOL RESULT]: ERROR: ${re}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${re}`},ze++;continue}}t.onExecStart&&t.onExecStart(M||"No Command"),yield{type:"exec_start"}}let Rn=L(j.args),lo=Rn.path||Rn.targetPath||null;if(lo){let M=t.systemSettings&&t.systemSettings.allowExternalAccess===!1,Y=Z.resolve(lo),ae=Z.resolve(process.cwd());if(M&&!Y.startsWith(ae)){let ge="Access Denied. You are not allowed to access files outside the current workspace.";if(A==="write_file"||A==="update_file"){let Ge=`\u2718 ${A==="write_file"?"Write Canceled":"Edit Canceled"}: ${Rn.path||"..."}`,Le=115;process.stdout.isTTY&&(Le=process.stdout.columns-5||120);let Se=Math.min(Ge.length+4,Le),re=`${Ge.padEnd(Se-2).substring(0,Se-2)}`;yield{type:"visual_feedback",content:nn(`${je?`
1013
1063
  `:""}${re}
1014
- `)},je=!1}ne.push({role:"user",text:`[TOOL RESULT]: ERROR: ${ge}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${ge}`},ze++;continue}}if(t.onToolApproval&&(A==="write_file"||A==="update_file"||A==="exec_command")){let Y=t.systemSettings||{},ae=Y.autoExec,ge=null,be=!1,Ge=!1,De=!1;if(A==="exec_command"){let{command:Le}=D(j.args),yt=(Le||"").trim(),Oe=(Xt,kt)=>{if(!kt)return!1;let pn=kt.split(",").map(Jt=>Jt.trim().toLowerCase()).filter(Boolean),dt=Xt.toLowerCase();return pn.some(Jt=>dt.startsWith(Jt))},rt=Oe(yt,Y.alwaysAskCommands),he=Oe(yt,Y.autoApproveCommands);if(Ge=Oe(yt,Y.autoDisallowCommands),rt?be=!0:(he||Y.autoApproveGit&&/^git\s+commit\b/i.test(yt))&&(ge="allow"),!be&&!ge){if(Y.networkAccess===!1){let kt=yt.trim().replace(/\s+/g," ").replace(/^['"]+|['"]+$/g,"").toLowerCase().split(" "),dt=kt[0].split("/").pop().split("\\").pop().replace(/\.exe$/,""),Jt=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"]),ft=!1;Jt.has(dt)&&(ft=!0);let lt=Rn=>kt.slice(1).some(En=>Rn.includes(En)),ut=Rn=>{let En=kt.findIndex(On=>Rn.includes(On)),Eo=kt.findIndex(On=>["run","exec","test"].includes(On));return En!==-1&&!(Eo!==-1&&Eo<En)};dt==="git"&&lt(["clone","pull","push","fetch"])&&(ft=!0),dt==="go"&&lt(["get","install"])&&(ft=!0),dt==="npm"&&ut(["install","i","update","add"])&&(ft=!0),dt==="yarn"&&ut(["add","install","upgrade"])&&(ft=!0),dt==="pnpm"&&ut(["add","install","update"])&&(ft=!0),dt==="bun"&&ut(["add","install","update"])&&(ft=!0),dt==="deno"&&lt(["install","add"])&&(ft=!0),dt==="pip"&&lt(["install","download"])&&(ft=!0),dt==="pip3"&&lt(["install","download"])&&(ft=!0),dt==="cargo"&&lt(["install","add"])&&(ft=!0),["bash","sh","zsh","fish"].includes(dt)&&lt(["-c"])&&(ft=!0),dt==="cmd"&&lt(["/c"])&&(ft=!0),ft&&(ge="deny",De=!0)}!ge&&Ge&&(ge="deny")}!be&&!ge&&ae&&(ge="allow")}else ae&&(ge="allow");let Se=ge,re="";ge==="deny"&&(De?re="network":Ge?re="settings":re="prohibited");let fe=!1,le="",$e=[],Ve=0,Ae=!1,Vt="";if(!Se){if(A==="write_file"||A==="update_file")try{let Oe=D(j.args),{path:rt}=Oe;if(rt){let he=Z.resolve(process.cwd(),rt),Xt=lt=>lt?lt.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,ut=>ut.toUpperCase()):"",kt=Xt(he),pn="",dt=!1,Jt=await wo(),ft=Xt(Jt?.file_focused);if(Jt&&ft===kt&&Jt.full_content?(pn=Jt.full_content,dt=!0):Fe.existsSync(he)&&(pn=Fe.readFileSync(he,"utf8"),dt=!0),le=pn,await ht.recordFileChange(he,pn),dt){let lt=pn;if(A==="write_file"){let ut=Oe.content||Oe.newContent||"";lt=ut.endsWith(`
1064
+ `)},je=!1}ne.push({role:"user",text:`[TOOL RESULT]: ERROR: ${ge}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${ge}`},ze++;continue}}if(t.onToolApproval&&(A==="write_file"||A==="update_file"||A==="exec_command")){let Y=t.systemSettings||{},ae=Y.autoExec,ge=null,be=!1,Ge=!1,Le=!1;if(A==="exec_command"){let{command:De}=L(j.args),yt=(De||"").trim(),Oe=(Qt,kt)=>{if(!kt)return!1;let mn=kt.split(",").map(Zt=>Zt.trim().toLowerCase()).filter(Boolean),dt=Qt.toLowerCase();return mn.some(Zt=>dt.startsWith(Zt))},rt=Oe(yt,Y.alwaysAskCommands),he=Oe(yt,Y.autoApproveCommands);if(Ge=Oe(yt,Y.autoDisallowCommands),rt?be=!0:(he||Y.autoApproveGit&&/^git\s+commit\b/i.test(yt))&&(ge="allow"),!be&&!ge){if(Y.networkAccess===!1){let kt=yt.trim().replace(/\s+/g," ").replace(/^['"]+|['"]+$/g,"").toLowerCase().split(" "),dt=kt[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"]),ft=!1;Zt.has(dt)&&(ft=!0);let lt=En=>kt.slice(1).some(Cn=>En.includes(Cn)),ut=En=>{let Cn=kt.findIndex(Ln=>En.includes(Ln)),Co=kt.findIndex(Ln=>["run","exec","test"].includes(Ln));return Cn!==-1&&!(Co!==-1&&Co<Cn)};dt==="git"&&lt(["clone","pull","push","fetch"])&&(ft=!0),dt==="go"&&lt(["get","install"])&&(ft=!0),dt==="npm"&&ut(["install","i","update","add"])&&(ft=!0),dt==="yarn"&&ut(["add","install","upgrade"])&&(ft=!0),dt==="pnpm"&&ut(["add","install","update"])&&(ft=!0),dt==="bun"&&ut(["add","install","update"])&&(ft=!0),dt==="deno"&&lt(["install","add"])&&(ft=!0),dt==="pip"&&lt(["install","download"])&&(ft=!0),dt==="pip3"&&lt(["install","download"])&&(ft=!0),dt==="cargo"&&lt(["install","add"])&&(ft=!0),["bash","sh","zsh","fish"].includes(dt)&&lt(["-c"])&&(ft=!0),dt==="cmd"&&lt(["/c"])&&(ft=!0),ft&&(ge="deny",Le=!0)}!ge&&Ge&&(ge="deny")}!be&&!ge&&ae&&(ge="allow")}else ae&&(ge="allow");let Se=ge,re="";ge==="deny"&&(Le?re="network":Ge?re="settings":re="prohibited");let fe=!1,le="",$e=[],Ve=0,Ae=!1,Jt="";if(!Se){if(A==="write_file"||A==="update_file")try{let Oe=L(j.args),{path:rt}=Oe;if(rt){let he=Z.resolve(process.cwd(),rt),Qt=lt=>lt?lt.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,ut=>ut.toUpperCase()):"",kt=Qt(he),mn="",dt=!1,Zt=await xo(),ft=Qt(Zt?.file_focused);if(Zt&&ft===kt&&Zt.full_content?(mn=Zt.full_content,dt=!0):Fe.existsSync(he)&&(mn=Fe.readFileSync(he,"utf8"),dt=!0),le=mn,await ht.recordFileChange(he,mn),dt){let lt=mn;if(A==="write_file"){let ut=Oe.content||Oe.newContent||"";lt=ut.endsWith(`
1015
1065
  `)?ut:ut+`
1016
- `,Vt=lt}else{let{patchPairs:ut,allowMultiple:Rn,error:En}=Os(Oe);if(En){let Ct=`[TOOL RESULT]: ERROR: ${En}`;ne.push({role:"user",text:Ct}),await Mt("toolFailure"),t.onToolResult&&t.onToolResult("failure",A),yield{type:"tool_result",content:Ct,toolName:A},ze++;continue}let Eo=Oe.allowMultiple!==void 0?Oe.allowMultiple===!0||String(Oe.allowMultiple).toLowerCase()==="true":Rn;Ve=ut.length;let On=Ds(pn,ut,{allowMultiple:Eo});lt=On.content,Vt=lt,$e=On.results;let Ss=$e.filter(Ct=>Ct.success),Et=$e.filter(Ct=>!Ct.success);if(Ss.length===0){let Ct=`[TOOL RESULT]: ERROR: Failed to apply patches to [${Z.basename(he)}].
1017
- ${Et.map(zo=>` \u2022 ${zo.error}`).join(`
1018
- `)}`,Co=`\u2714 Edited: ${Z.basename(he.replaceAll("\\","/"))}`,qo=115;process.stdout.isTTY&&(qo=process.stdout.columns-5||120);let _o=Math.min(Co.length+4,qo),ks=`${Co.padEnd(_o-2).substring(0,_o-2)}`;yield{type:"visual_feedback",content:tn(`${je?`
1019
- `:""}${ks}`)},je=!1,ne.push({role:"user",text:Ct}),await Mt("toolFailure"),t.onToolResult&&t.onToolResult("failure",A),yield{type:"tool_result",content:Ct,toolName:A},ze++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${Z.basename(he)}`},di(he,pn,lt),fe=!0,await new Promise(ut=>setTimeout(ut,50))}else if(A==="write_file"){let lt=Oe.content||Oe.newContent||"",ut=lt.endsWith(`
1066
+ `,Jt=lt}else{let{patchPairs:ut,allowMultiple:En,error:Cn}=Os(Oe);if(Cn){let _t=`[TOOL RESULT]: ERROR: ${Cn}`;ne.push({role:"user",text:_t}),await vt("toolFailure"),t.onToolResult&&t.onToolResult("failure",A),yield{type:"tool_result",content:_t,toolName:A},ze++;continue}let Co=Oe.allowMultiple!==void 0?Oe.allowMultiple===!0||String(Oe.allowMultiple).toLowerCase()==="true":En;Ve=ut.length;let Ln=Ls(mn,ut,{allowMultiple:Co});lt=Ln.content,Jt=lt,$e=Ln.results;let Ss=$e.filter(_t=>_t.success),Ct=$e.filter(_t=>!_t.success);if(Ss.length===0){let _t=`[TOOL RESULT]: ERROR: Failed to apply patches to [${Z.basename(he)}].
1067
+ ${Ct.map(Ko=>` \u2022 ${Ko.error}`).join(`
1068
+ `)}`,_o=`\u2714 Edited: ${Z.basename(he.replaceAll("\\","/"))}`,zo=115;process.stdout.isTTY&&(zo=process.stdout.columns-5||120);let $o=Math.min(_o.length+4,zo),ks=`${_o.padEnd($o-2).substring(0,$o-2)}`;yield{type:"visual_feedback",content:nn(`${je?`
1069
+ `:""}${ks}`)},je=!1,ne.push({role:"user",text:_t}),await vt("toolFailure"),t.onToolResult&&t.onToolResult("failure",A),yield{type:"tool_result",content:_t,toolName:A},ze++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${Z.basename(he)}`},di(he,mn,lt),fe=!0,await new Promise(ut=>setTimeout(ut,50))}else if(A==="write_file"){let lt=Oe.content||Oe.newContent||"",ut=lt.endsWith(`
1020
1070
  `)?lt:lt+`
1021
- `;Vt=ut,Fe.existsSync(he)||(Ae=!0,Fe.mkdirSync(Z.dirname(he),{recursive:!0}),Fe.writeFileSync(he,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${Z.basename(he)}`},di(he,"",ut),fe=!0,await new Promise(Rn=>setTimeout(Rn,50))}}}catch(Oe){console.error("Simulation/Diff Error:",Oe)}let Le=null;ci(Oe=>{Le=Oe});let yt=t.onToolApproval;if(Se=await new Promise(async Oe=>{let rt=setInterval(()=>{Le&&(er.onIDEApproval&&er.onIDEApproval(Le),clearInterval(rt),Oe(Le))},100);try{let he=await yt(A,j.args);clearInterval(rt),Oe(he)}catch{clearInterval(rt),Oe("deny")}}),ci(null),A==="write_file"||A==="update_file"){let{path:Oe}=D(j.args);if(Oe){let rt=Z.resolve(process.cwd(),Oe);if(nl(rt,Se),Se==="deny"&&Ae&&Fe.existsSync(rt))try{Fe.unlinkSync(rt)}catch{}}}Se==="deny"&&(re="user")}if(Se==="allow"&&fe&&Hs()){let{path:Le}=D(j.args),yt=Z.resolve(process.cwd(),Le),Oe=Et=>Et?Z.resolve(Et).replace(/\\/g,"/").toLowerCase():"",rt=await wo(),he="";if(rt&&rt.file_focused&&Oe(rt.file_focused)===Oe(yt)&&rt.full_content&&(he=rt.full_content),!he&&Fe.existsSync(yt)){let Et=Fe.readFileSync(yt,"utf8");Et&&(he=Et)}!he&&Vt&&(he=Vt),(he||Ae)&&Fe.writeFileSync(yt,he,"utf8");let Xt=he.split(/\r?\n/),kt=Xt.length,pn=Buffer.byteLength(he,"utf8"),dt="";le&&(dt=`Old File contents:
1022
- ${le.split(/\r?\n/).map((Ct,Co)=>`${Co+1} | ${Ct}`).join(`
1071
+ `;Jt=ut,Fe.existsSync(he)||(Ae=!0,Fe.mkdirSync(Z.dirname(he),{recursive:!0}),Fe.writeFileSync(he,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${Z.basename(he)}`},di(he,"",ut),fe=!0,await new Promise(En=>setTimeout(En,50))}}}catch(Oe){console.error("Simulation/Diff Error:",Oe)}let De=null;ci(Oe=>{De=Oe});let yt=t.onToolApproval;if(Se=await new Promise(async Oe=>{let rt=setInterval(()=>{De&&(er.onIDEApproval&&er.onIDEApproval(De),clearInterval(rt),Oe(De))},100);try{let he=await yt(A,j.args);clearInterval(rt),Oe(he)}catch{clearInterval(rt),Oe("deny")}}),ci(null),A==="write_file"||A==="update_file"){let{path:Oe}=L(j.args);if(Oe){let rt=Z.resolve(process.cwd(),Oe);if(nl(rt,Se),Se==="deny"&&Ae&&Fe.existsSync(rt))try{Fe.unlinkSync(rt)}catch{}}}Se==="deny"&&(re="user")}if(Se==="allow"&&fe&&Hs()){let{path:De}=L(j.args),yt=Z.resolve(process.cwd(),De),Oe=Ct=>Ct?Z.resolve(Ct).replace(/\\/g,"/").toLowerCase():"",rt=await xo(),he="";if(rt&&rt.file_focused&&Oe(rt.file_focused)===Oe(yt)&&rt.full_content&&(he=rt.full_content),!he&&Fe.existsSync(yt)){let Ct=Fe.readFileSync(yt,"utf8");Ct&&(he=Ct)}!he&&Jt&&(he=Jt),(he||Ae)&&Fe.writeFileSync(yt,he,"utf8");let Qt=he.split(/\r?\n/),kt=Qt.length,mn=Buffer.byteLength(he,"utf8"),dt="";le&&(dt=`Old File contents:
1072
+ ${le.split(/\r?\n/).map((_t,_o)=>`${_o+1} | ${_t}`).join(`
1023
1073
  `)}
1024
1074
 
1025
- `);let Jt="";if(kt<=100)Jt=Xt.join(`
1026
- `);else{let Et=Xt.slice(0,50).join(`
1027
- `),Ct=Xt.slice(-50).join(`
1028
- `);Jt=`${Et}
1075
+ `);let Zt="";if(kt<=100)Zt=Qt.join(`
1076
+ `);else{let Ct=Qt.slice(0,50).join(`
1077
+ `),_t=Qt.slice(-50).join(`
1078
+ `);Zt=`${Ct}
1029
1079
 
1030
1080
  ... [${kt-100} lines truncated for history stability] ...
1031
1081
 
1032
- ${Ct}`}let ft="";if(A==="update_file"){let Et=Ls(le,he,$e,12,t?.compressToolResults||er?.systemSettings?.compressToolResults);ft=`SUCCESS: File [${Le}] updated via IDE Companion (May have user edits). [${$e.length}/${Ve}] blocks applied.
1082
+ ${_t}`}let ft="";if(A==="update_file"){let Ct=Ds(le,he,$e,12,t?.compressToolResults||er?.systemSettings?.compressToolResults);ft=`SUCCESS: File [${De}] updated via IDE Companion (May have user edits). [${$e.length}/${Ve}] blocks applied.
1033
1083
 
1034
- ${Et}`}else{let Et=he.split(/\r?\n/),Ct=Et.length,Co=Buffer.byteLength(he,"utf8"),qo="";le&&(qo=`Old File contents:
1035
- ${le.split(/\r?\n/).map((zo,Al)=>`${Al+1} | ${zo}`).join(`
1084
+ ${Ct}`}else{let Ct=he.split(/\r?\n/),_t=Ct.length,_o=Buffer.byteLength(he,"utf8"),zo="";le&&(zo=`Old File contents:
1085
+ ${le.split(/\r?\n/).map((Ko,Al)=>`${Al+1} | ${Ko}`).join(`
1036
1086
  `)}
1037
1087
 
1038
- `);let _o="";if(Ct<=100)_o=Et.join(`
1039
- `);else{let ks=Et.slice(0,50).join(`
1040
- `),zo=Et.slice(-50).join(`
1041
- `);_o=`${ks}
1088
+ `);let $o="";if(_t<=100)$o=Ct.join(`
1089
+ `);else{let ks=Ct.slice(0,50).join(`
1090
+ `),Ko=Ct.slice(-50).join(`
1091
+ `);$o=`${ks}
1042
1092
 
1043
- ... [${Ct-100} lines truncated] ...
1093
+ ... [${_t-100} lines truncated] ...
1044
1094
 
1045
- ${zo}`}ft=`SUCCESS: File [${Le}] saved via IDE Companion (May have user edits).
1046
- - Stats: [${Ct} lines, ${(Co/1024).toFixed(1)} KB]
1047
- ${qo}- Content Preview:
1095
+ ${Ko}`}ft=`SUCCESS: File [${De}] saved via IDE Companion (May have user edits).
1096
+ - Stats: [${_t} lines, ${(_o/1024).toFixed(1)} KB]
1097
+ ${zo}- Content Preview:
1048
1098
 
1049
- ${_o}`}let ut=`${Le?"\u2714":"\u2718"} ${A==="write_file"?"Created":"Edited"}: ${Le.replaceAll("\\","/")||"No File Changes"}`,Rn=115;process.stdout.isTTY&&(Rn=process.stdout.columns-5||120);let En=Math.min(ut.length+4,Rn),Eo=`${ut.padEnd(En-2).substring(0,En-2)}`;yield{type:"visual_feedback",content:tn(`${je?`
1050
- `:""}${Eo}`)},je=!1;let On=Date.now();K=On,yield{type:"tool_time",content:On-se};let Ss=`[TOOL RESULT]: ${ft}`;ne.push({role:"user",text:Ss}),fn=!0,await Mt("toolSuccess"),t.onToolResult&&t.onToolResult("success",A),yield{type:"tool_result",content:ft,aiContent:Ss,toolName:A},ze++;continue}if(Se==="deny"){let Le=`Permission Denied: Prohibited ${A==="exec_command"?"Command":"file edit"}.`;if(re==="user"?Le="Permission Denied by User":re==="settings"?Le="Permission Denied by User Policy":re==="network"?Le="Permission Denied: Sandbox Network Access Disabled by User Policy.":re==="prohibited"&&A==="exec_command"&&(Le="Permission Denied: Prohibited Command in User Policy"),A==="write_file"||A==="update_file"){let Oe=`\u2718 ${A==="write_file"?"Write Cancelled":"Edit Denied"}: ${D(j.args).path.replaceAll("\\","/")||"..."}`,rt=115;process.stdout.isTTY&&(rt=process.stdout.columns-5||120);let he=Math.min(Oe.length+4,rt),Xt=`${Oe.padEnd(he-2).substring(0,he-2)}`,kt=` ${" ".repeat(he)} `;yield{type:"visual_feedback",content:tn(`${je?`
1051
- `:""}${Xt}
1052
- `)},je=!1}A==="exec_command"&&(await new Promise(yt=>setTimeout(yt,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${Le}`),await new Promise(yt=>setTimeout(yt,50)),t.onExecEnd&&t.onExecEnd()),ne.push({role:"user",text:`[TOOL RESULT]: DENIED: ${Le}`}),yield{type:"tool_result",content:`[TOOL RESULT]: DENIED: ${Le}`},await Mt("toolDenied"),t.onToolResult&&t.onToolResult("denied",A),ze++;continue}}if(J){let M=115;process.stdout.isTTY&&(M=process.stdout.columns-5||120);let Y=Math.min(J.length+4,M),ae=`${J.padEnd(Y-2).substring(0,Y-2)}`;yield{type:"visual_feedback",content:tn(`${je?`
1099
+ ${$o}`}let ut=`${De?"\u2714":"\u2718"} ${A==="write_file"?"Created":"Edited"}: ${De.replaceAll("\\","/")||"No File Changes"}`,En=115;process.stdout.isTTY&&(En=process.stdout.columns-5||120);let Cn=Math.min(ut.length+4,En),Co=`${ut.padEnd(Cn-2).substring(0,Cn-2)}`;yield{type:"visual_feedback",content:nn(`${je?`
1100
+ `:""}${Co}`)},je=!1;let Ln=Date.now();K=Ln,yield{type:"tool_time",content:Ln-se};let Ss=`[TOOL RESULT]: ${ft}`;ne.push({role:"user",text:Ss}),un=!0,await vt("toolSuccess"),t.onToolResult&&t.onToolResult("success",A),yield{type:"tool_result",content:ft,aiContent:Ss,toolName:A},ze++;continue}if(Se==="deny"){let De=`Permission Denied: Prohibited ${A==="exec_command"?"Command":"file edit"}.`;if(re==="user"?De="Permission Denied by User":re==="settings"?De="Permission Denied by User Policy":re==="network"?De="Permission Denied: Sandbox Network Access Disabled by User Policy.":re==="prohibited"&&A==="exec_command"&&(De="Permission Denied: Prohibited Command in User Policy"),A==="write_file"||A==="update_file"){let Oe=`\u2718 ${A==="write_file"?"Write Cancelled":"Edit Denied"}: ${L(j.args).path.replaceAll("\\","/")||"..."}`,rt=115;process.stdout.isTTY&&(rt=process.stdout.columns-5||120);let he=Math.min(Oe.length+4,rt),Qt=`${Oe.padEnd(he-2).substring(0,he-2)}`,kt=` ${" ".repeat(he)} `;yield{type:"visual_feedback",content:nn(`${je?`
1101
+ `:""}${Qt}
1102
+ `)},je=!1}A==="exec_command"&&(await new Promise(yt=>setTimeout(yt,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${De}`),await new Promise(yt=>setTimeout(yt,50)),t.onExecEnd&&t.onExecEnd()),ne.push({role:"user",text:`[TOOL RESULT]: DENIED: ${De}`}),yield{type:"tool_result",content:`[TOOL RESULT]: DENIED: ${De}`},await vt("toolDenied"),t.onToolResult&&t.onToolResult("denied",A),ze++;continue}}if(J){let M=115;process.stdout.isTTY&&(M=process.stdout.columns-5||120);let Y=Math.min(J.length+4,M),ae=`${J.padEnd(Y-2).substring(0,Y-2)}`;yield{type:"visual_feedback",content:nn(`${je?`
1053
1103
  `:""}${ae}${J.includes("\u2714")&&(J.includes("Created")||J.includes("Edited"))?"":`
1054
- `}`)},je=!1}if(K>0){let M=Date.now()-K,Y=Math.max(0,1e3-M);Y>0&&await new Promise(ae=>setTimeout(ae,Y))}let qn={chatId:d,history:n,onChunk:M=>t.onExecChunk?t.onExecChunk(M):null,onAskUser:t.onAskUser,systemSettings:t.systemSettings,mode:i,isMultiModal:At(ke),onVisualFeedback:t.onVisualFeedback,onSubagentUpdate:t.onSubagentUpdate,onTokenChunk:t.onTokenChunk,modelName:ke,aiProvider:t.aiProvider,apiKey:t.apiKey,onUsage:t.onUsage};if(A==="write_file"||A==="update_file")try{let{path:M}=D(j.args);if(M){let Y=Z.resolve(process.cwd(),M),ae=await wo();ae&&ae.file_focused===Y&&ae.full_content&&(qn.forcedContent=ae.full_content)}}catch{}on.push(A);let _e=await ps(A,j.args,qn);if((A==="write_file"||A==="update_file")&&_e.startsWith("SUCCESS")){let{path:M}=D(j.args);if(M){let Y=Z.resolve(process.cwd(),M);tl(Y)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let Gt=Date.now();K=Gt,yield{type:"tool_time",content:Gt-se},sn=Gt;let Yt=null;if(typeof _e=="object"&&_e.binaryPart&&(Yt=_e.binaryPart,_e=_e.text),A==="search_keyword"){let{keyword:M,path:Y}=D(j.args),ae=typeof _e=="string"&&_e.startsWith("[GLOB]");ae&&(_e=_e.slice(6).trimStart());let ge=typeof _e=="string"&&_e.startsWith("[DIR]");ge&&(_e=_e.slice(5).trimStart());let be=0;if(_e){let $e=_e.match(/Found (\d+) match/i);$e&&(be=parseInt($e[1]))}let Ge=(Y||"").trim().toLowerCase().replaceAll("\\","/"),De=Ge==="#doc"||Ge==="#docs"||Ge==="#documentation"||Ge.includes("#skill/global/fluxflow")||Ge.includes("#skills/global/fluxflow"),Se;if(De)Se=`${M?"\u2714":"\u2718"} Searched Documentation`;else{let $e=Y?Y.replace(/[\/\\]+$/,""):null,Ve=$e&&$e!=="."?`"${ae?Y:ge?`${$e}/*`:$e}"`:"./";Se=`${M?"\u2714":"\u2718"} Searched: "${M||""}" in ${Ve.replaceAll("\\","/")} \u2192 ${be} Match${be===1?"":"es"}`}let re=115;process.stdout.isTTY&&(re=process.stdout.columns-5||120);let fe=Math.min(Se.length+4,re),le=`${Se.padEnd(fe-2).substring(0,fe-2)}`;yield{type:"visual_feedback",content:tn(`${je?`
1104
+ `}`)},je=!1}if(K>0){let M=Date.now()-K,Y=Math.max(0,1e3-M);Y>0&&await new Promise(ae=>setTimeout(ae,Y))}let zn={chatId:d,history:n,onChunk:M=>t.onExecChunk?t.onExecChunk(M):null,onAskUser:t.onAskUser,systemSettings:t.systemSettings,mode:i,isMultiModal:Mt(ke),onVisualFeedback:t.onVisualFeedback,onSubagentUpdate:t.onSubagentUpdate,onTokenChunk:t.onTokenChunk,modelName:ke,aiProvider:t.aiProvider,apiKey:t.apiKey,onUsage:t.onUsage};if(A==="write_file"||A==="update_file")try{let{path:M}=L(j.args);if(M){let Y=Z.resolve(process.cwd(),M),ae=await xo();ae&&ae.file_focused===Y&&ae.full_content&&(zn.forcedContent=ae.full_content)}}catch{}sn.push(A);let _e=await ms(A,j.args,zn);if((A==="write_file"||A==="update_file")&&_e.startsWith("SUCCESS")){let{path:M}=L(j.args);if(M){let Y=Z.resolve(process.cwd(),M);tl(Y)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let Ht=Date.now();K=Ht,yield{type:"tool_time",content:Ht-se},rn=Ht;let Xt=null;if(typeof _e=="object"&&_e.binaryPart&&(Xt=_e.binaryPart,_e=_e.text),A==="search_keyword"){let{keyword:M,path:Y}=L(j.args),ae=typeof _e=="string"&&_e.startsWith("[GLOB]");ae&&(_e=_e.slice(6).trimStart());let ge=typeof _e=="string"&&_e.startsWith("[DIR]");ge&&(_e=_e.slice(5).trimStart());let be=0;if(_e){let $e=_e.match(/Found (\d+) match/i);$e&&(be=parseInt($e[1]))}let Ge=(Y||"").trim().toLowerCase().replaceAll("\\","/"),Le=Ge==="#doc"||Ge==="#docs"||Ge==="#documentation"||Ge.includes("#skill/global/fluxflow")||Ge.includes("#skills/global/fluxflow"),Se;if(Le)Se=`${M?"\u2714":"\u2718"} Searched Documentation`;else{let $e=Y?Y.replace(/[\/\\]+$/,""):null,Ve=$e&&$e!=="."?`"${ae?Y:ge?`${$e}/*`:$e}"`:"./";Se=`${M?"\u2714":"\u2718"} Searched: "${M||""}" in ${Ve.replaceAll("\\","/")} \u2192 ${be} Match${be===1?"":"es"}`}let re=115;process.stdout.isTTY&&(re=process.stdout.columns-5||120);let fe=Math.min(Se.length+4,re),le=`${Se.padEnd(fe-2).substring(0,fe-2)}`;yield{type:"visual_feedback",content:nn(`${je?`
1055
1105
  `:""}${le}
1056
- `)},je=!1}if(A==="EmergencyRollback"){let{method:M}=D(j.args);if(M==="forceRevert"){let Y=0;if(_e){let Se=_e.match(/Total\s*:\s*(\d+)/i);Se&&(Y=parseInt(Se[1]))}let ge=_e&&_e.startsWith("ERROR:")?"\u2718 Emergency Rollback Failed":`\u2714 Emergency Rollback \u2192 ${Y} file${Y===1?"":"s"} processed`,be=115;process.stdout.isTTY&&(be=process.stdout.columns-5||120);let Ge=Math.min(ge.length+4,be),De=`${ge.padEnd(Ge-2).substring(0,Ge-2)}`;yield{type:"visual_feedback",content:tn(`${je?`
1057
- `:""}${De}
1058
- `)},je=!1}}if(A==="todo"){let{method:M,tasks:Y,markDone:ae}=D(j.args),ge="",be=[],Ge=De=>{if(!De)return[];let Se=Array.isArray(De)?De:[];if(Se.length===0&&typeof De=="string"){let re=De.trim();if(re.startsWith("[")&&re.endsWith("]")){let fe=re.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);fe?Se=fe.map(le=>le.slice(1,-1).replace(/\\(.)/g,"$1")):Se=re.slice(1,-1).split(",").map(le=>le.trim()).filter(Boolean)}else Se=De.split(`
1059
- `)}return Se.filter(re=>String(re).trim()).map(re=>{let fe=String(re).trim();return fe.startsWith("- [")?fe.substring(6).trim():fe})};if(M==="create"?(ge="\x1B[32m\u2192\x1B[0m Created Goals",be=Ge(Y).map(De=>`\x1B[90m\u25CB\x1B[0m ${De}`)):M==="append"?(ge="\x1B[34m\u2795\x1B[0m Added New Goals",be=Ge(Y).map(De=>`\x1B[90m\u25CB\x1B[0m ${De}`)):M==="get"&&(ge=ae?"\x1B[36m\u21BB\x1B[0m Updated Goals":"\x1B[35m\u2022\x1B[0m Reviewed Goals",be=(_e||"").split(`
1106
+ `)},je=!1}if(A==="EmergencyRollback"){let{method:M}=L(j.args);if(M==="forceRevert"){let Y=0;if(_e){let Se=_e.match(/Total\s*:\s*(\d+)/i);Se&&(Y=parseInt(Se[1]))}let ge=_e&&_e.startsWith("ERROR:")?"\u2718 Emergency Rollback Failed":`\u2714 Emergency Rollback \u2192 ${Y} file${Y===1?"":"s"} processed`,be=115;process.stdout.isTTY&&(be=process.stdout.columns-5||120);let Ge=Math.min(ge.length+4,be),Le=`${ge.padEnd(Ge-2).substring(0,Ge-2)}`;yield{type:"visual_feedback",content:nn(`${je?`
1107
+ `:""}${Le}
1108
+ `)},je=!1}}if(A==="todo"){let{method:M,tasks:Y,markDone:ae}=L(j.args),ge="",be=[],Ge=Le=>{if(!Le)return[];let Se=Array.isArray(Le)?Le:[];if(Se.length===0&&typeof Le=="string"){let re=Le.trim();if(re.startsWith("[")&&re.endsWith("]")){let fe=re.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);fe?Se=fe.map(le=>le.slice(1,-1).replace(/\\(.)/g,"$1")):Se=re.slice(1,-1).split(",").map(le=>le.trim()).filter(Boolean)}else Se=Le.split(`
1109
+ `)}return Se.filter(re=>String(re).trim()).map(re=>{let fe=String(re).trim();return fe.startsWith("- [")?fe.substring(6).trim():fe})};if(M==="create"?(ge="\x1B[32m\u2192\x1B[0m Created Goals",be=Ge(Y).map(Le=>`\x1B[90m\u25CB\x1B[0m ${Le}`)):M==="append"?(ge="\x1B[34m\u2795\x1B[0m Added New Goals",be=Ge(Y).map(Le=>`\x1B[90m\u25CB\x1B[0m ${Le}`)):M==="get"&&(ge=ae?"\x1B[36m\u21BB\x1B[0m Updated Goals":"\x1B[35m\u2022\x1B[0m Reviewed Goals",be=(_e||"").split(`
1060
1110
  `).slice(1).join(`
1061
1111
  `).split(`
1062
- `).filter(Se=>Se.trim().startsWith("- [")).map(Se=>{let re=Se.trim(),fe=re.startsWith("- [x]");return`${fe?"\x1B[32m\u2714\x1B[0m":"\x1B[90m\u25CB\x1B[0m"} ${fe?"\x1B[90m":"\x1B[37m"}${re.substring(6).trim()}\x1B[0m`})),ge&&be.length>0){let De=[`${ge}`,...be.map(Se=>` ${Se}`)].join(`
1063
- `);yield{type:"visual_feedback",content:tn(`${je?`
1064
- `:""}${De}
1065
- `)},je=!1}}A==="exec_command"&&t.onExecEnd&&(await new Promise(M=>setTimeout(M,800)),t.onExecEnd());let vn=_e&&_e.startsWith("DENIED:");_e&&!_e.startsWith("ERROR:")&&!vn?(await Mt("toolSuccess"),t.onToolResult&&t.onToolResult("success",A)):vn||(await Mt("toolFailure"),t.onToolResult&&t.onToolResult("failure",A));let Ht=(_e||"").toString().replaceAll("[UI_CONTEXT]","");Ht.includes("[[VERIFIED]]")&&(Ht=Ht.replace(/\[\[VERIFIED\]\][\s\S]*?\[\[\/VERIFIED\]\]/g,`[SYSTEM NOTE]: Patch Block matched & applied successfully. Large Block omitted to conserve context.
1066
- `));let In;if(Ht.startsWith("[[SAME]]")){let Y=Ht.replace(/^\[\[SAME\]\]\s*\r?\n?/,"").split(/\r?\n/),ae=Y.filter(be=>be.startsWith("SUCCESS:")||be.trim().startsWith("- Stats:"));In=`[TOOL RESULT]: ${ae.length>0?ae.join(`
1112
+ `).filter(Se=>Se.trim().startsWith("- [")).map(Se=>{let re=Se.trim(),fe=re.startsWith("- [x]");return`${fe?"\x1B[32m\u2714\x1B[0m":"\x1B[90m\u25CB\x1B[0m"} ${fe?"\x1B[90m":"\x1B[37m"}${re.substring(6).trim()}\x1B[0m`})),ge&&be.length>0){let Le=[`${ge}`,...be.map(Se=>` ${Se}`)].join(`
1113
+ `);yield{type:"visual_feedback",content:nn(`${je?`
1114
+ `:""}${Le}
1115
+ `)},je=!1}}A==="exec_command"&&t.onExecEnd&&(await new Promise(M=>setTimeout(M,800)),t.onExecEnd());let In=_e&&_e.startsWith("DENIED:");_e&&!_e.startsWith("ERROR:")&&!In?(await vt("toolSuccess"),t.onToolResult&&t.onToolResult("success",A)):In||(await vt("toolFailure"),t.onToolResult&&t.onToolResult("failure",A));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.
1116
+ `));let On;if(qt.startsWith("[[SAME]]")){let Y=qt.replace(/^\[\[SAME\]\]\s*\r?\n?/,"").split(/\r?\n/),ae=Y.filter(be=>be.startsWith("SUCCESS:")||be.trim().startsWith("- Stats:"));On=`[TOOL RESULT]: ${ae.length>0?ae.join(`
1067
1117
  `):Y.slice(0,2).join(`
1068
1118
  `)}
1069
- [SYSTEM NOTE]: Content verified and persisted to disk. Full preview omitted to conserve context.`}else In=`[TOOL RESULT]: ${Ht}`;ne.push({role:"user",text:In,binaryPart:Yt}),fn=!0;let Ie=`[TOOL RESULT]: ${_e.replaceAll(`[[VERIFIED]]
1119
+ [SYSTEM NOTE]: Content verified and persisted to disk. Full preview omitted to conserve context.`}else On=`[TOOL RESULT]: ${qt}`;ne.push({role:"user",text:On,binaryPart:Xt}),un=!0;let Ie=`[TOOL RESULT]: ${_e.replaceAll(`[[VERIFIED]]
1070
1120
  `,"").replaceAll(`
1071
- [[/VERIFIED]]`,"")||""}`;(A==="view_file"||A==="web_scrape"||A==="file_map")&&(Ie=`[TOOL RESULT]: ${J} (Context Locked for UI Clarity)`),yield{type:"tool_result",content:Ie,aiContent:In,binaryPart:Yt,toolName:A},A==="memory"&&_e.includes("SUCCESS")&&(yield{type:"memory_updated"}),ze++}if(f==="Google"&&kn&&Date.now()-ir>=150){yield*ro();let j=Go(kn);for(let se of j)yield se;kn="",ir=Date.now()}}N.usageMetadata&&(An=N.usageMetadata),An&&(yield{type:"liveTokens",content:An.totalTokenCount})}if(ce&&(ce=!1,Bt?Ye+="</think>":(ue+="</think>",f==="Google"?kn+="</think>":yield{type:"text",content:"</think>"})),Bt&&Ye.length>0){let N=0,ie=Math.min(it.length,Ye.length);for(let H=ie;H>0;H--)if(it.endsWith(Ye.substring(0,H))){N=H;break}let G=Ye.substring(N);if(G){let xe=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(it)?G.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):G.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(xe)if(ue+=xe,f==="Google")kn+=xe;else{yield*ro();let me=Go(xe);for(let Ce of me)yield Ce}}Bt=!1,Ye=""}if(yield*ro(),$t)break;let Ho=(ue||"").trim(),Tl=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(Ho.toLowerCase())||/\[\[END\]\]/i.test(Ho.toLowerCase()),Rl=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(Ho.toLowerCase()),El=ne.length>0||Nt!==null,ar=nn(Ho).trim(),Cl=/(\p{Emoji_Presentation}|\p{Extended_Pictographic})$/u.test(ar),_l=/([.!?"'*_`|\]\)”’~~]+|\s|`{3}|[\u200B-\u200D\uFEFF])$/u.test(ar.trim()),$l=/[.!?}"'`’“”]$|```$/s.test(ar)||_l||Cl;!Tl&&!Rl&&!El&&Ho.length>0,nt=!0,await Mt("agent",f)}catch(we){if($t){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
1121
+ [[/VERIFIED]]`,"")||""}`;(A==="view_file"||A==="web_scrape"||A==="file_map")&&(Ie=`[TOOL RESULT]: ${J} (Context Locked for UI Clarity)`),yield{type:"tool_result",content:Ie,aiContent:On,binaryPart:Xt,toolName:A},A==="memory"&&_e.includes("SUCCESS")&&(yield{type:"memory_updated"}),ze++}if(f==="Google"&&Tn&&Date.now()-ir>=150){yield*io();let j=Ho(Tn);for(let se of j)yield se;Tn="",ir=Date.now()}}N.usageMetadata&&(Mn=N.usageMetadata),Mn&&(yield{type:"liveTokens",content:Mn.totalTokenCount})}if(ce&&(ce=!1,Wt?Ye+="</think>":(ue+="</think>",f==="Google"?Tn+="</think>":yield{type:"text",content:"</think>"})),Wt&&Ye.length>0){let N=0,ie=Math.min(it.length,Ye.length);for(let H=ie;H>0;H--)if(it.endsWith(Ye.substring(0,H))){N=H;break}let G=Ye.substring(N);if(G){let xe=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(it)?G.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):G.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(xe)if(ue+=xe,f==="Google")Tn+=xe;else{yield*io();let me=Ho(xe);for(let Ce of me)yield Ce}}Wt=!1,Ye=""}if(yield*io(),At)break;let qo=(ue||"").trim(),Tl=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(qo.toLowerCase())||/\[\[END\]\]/i.test(qo.toLowerCase()),Rl=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(qo.toLowerCase()),El=ne.length>0||Ut!==null,ar=on(qo).trim(),Cl=/(\p{Emoji_Presentation}|\p{Extended_Pictographic})$/u.test(ar),_l=/([.!?"'*_`|\]\)”’~~]+|\s|`{3}|[\u200B-\u200D\uFEFF])$/u.test(ar.trim()),$l=/[.!?}"'`’“”]$|```$/s.test(ar)||_l||Cl;!Tl&&!Rl&&!El&&qo.length>0,nt=!0,await vt("agent",f)}catch(we){if(At){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
1072
1122
 
1073
- \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(String(we).includes("Incomplete JSON segment at the end")){ce&&(ce=!1,Bt?Ye+="</think>":(ue+="</think>",yield{type:"text",content:"</think>"})),nt=!0,await Mt("agent",f);break}if(ce&&(ce=!1,Bt?Ye+="</think>":ue+="</think>"),Bt&&Ye.length>0){let Hn=0,rn=Math.min(it.length,Ye.length);for(let Dt=rn;Dt>0;Dt--)if(it.endsWith(Ye.substring(0,Dt))){Hn=Dt;break}let Ot=Ye.substring(Hn);if(Ot){let Lt=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(it)?Ot.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):Ot.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");Lt&&(ue+=Lt)}Bt=!1,Ye=""}let de=we instanceof Error?(()=>{try{return JSON.parse(JSON.parse(we.message).error.message).error.message}catch{return String(we)}})():String(we),at=new Date().toLocaleString(),Wt=Z.join(mn,"agent");Fe.existsSync(Wt)||Fe.mkdirSync(Wt,{recursive:!0}),Fe.appendFileSync(Z.join(Wt,"error.log"),`ERROR [${at}]: ${de}
1123
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(String(we).includes("Incomplete JSON segment at the end")){ce&&(ce=!1,Wt?Ye+="</think>":(ue+="</think>",yield{type:"text",content:"</think>"})),nt=!0,await vt("agent",f);break}if(ce&&(ce=!1,Wt?Ye+="</think>":ue+="</think>"),Wt&&Ye.length>0){let qn=0,an=Math.min(it.length,Ye.length);for(let Dt=an;Dt>0;Dt--)if(it.endsWith(Ye.substring(0,Dt))){qn=Dt;break}let Lt=Ye.substring(qn);if(Lt){let Pt=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(it)?Lt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):Lt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");Pt&&(ue+=Pt)}Wt=!1,Ye=""}let de=we instanceof Error?(()=>{try{return JSON.parse(JSON.parse(we.message).error.message).error.message}catch{return String(we)}})():String(we),at=new Date().toLocaleString(),jt=Z.join(hn,"agent");Fe.existsSync(jt)||Fe.mkdirSync(jt,{recursive:!0}),Fe.appendFileSync(Z.join(jt,"error.log"),`ERROR [${at}]: ${de}
1074
1124
 
1075
1125
  ----------------------------------------------------------------------
1076
1126
 
1077
- `);let Kt=we.status||we.statusCode||we.code,Gn=String(we).includes("replicas at capacity");if(!(Kt&&(Kt>=500&&Kt<600||Kt===408||Kt===429||Gn)||!Kt&&(/status[ :]+(5\d\d|408|429)/i.test(String(we))||/code[ :]+(5\d\d|408|429)/i.test(String(we))||/(500|503|408|429)/.test(String(we))))){if(qe<bn-3)throw we;yield{type:"text",content:de},yield{type:"status",content:"Error Occured"}}if(ue.trim().length>0||Qe>1)if(Qe<=bn){Qe++;let Hn=Math.min(1e3*Math.pow(2,Qe-1),24e3);if(ue.trim().length>0){b.push({role:"agent",text:ue});let rn=`[system]
1127
+ `);let Vt=we.status||we.statusCode||we.code,Hn=String(we).includes("replicas at capacity");if(!(Vt&&(Vt>=500&&Vt<600||Vt===408||Vt===429||Hn)||!Vt&&(/status[ :]+(5\d\d|408|429)/i.test(String(we))||/code[ :]+(5\d\d|408|429)/i.test(String(we))||/(500|503|408|429)/.test(String(we))))){if(qe<Sn-3)throw we;yield{type:"text",content:de},yield{type:"status",content:"Error Occured"}}if(ue.trim().length>0||Qe>1)if(Qe<=Sn){Qe++;let qn=Math.min(1e3*Math.pow(2,Qe-1),24e3);if(ue.trim().length>0){b.push({role:"agent",text:ue});let an=`[system]
1078
1128
  - seamless continuation: resume immediately. pick up from last words with zero gap/disruption
1079
1129
  - no repetition: do not repeat any text already written
1080
1130
  - no re-think: do not restart or open <think> if reasoning already started. continue the thinking and close thinking block </think> before chat output
1081
1131
  - mid-tool safety: if cutoff was mid-tool call, restart that tool call from start
1082
- - stealth: do not mention/apologize for cutoff [/system]`;ne.length>0?ne.forEach((Ot,Dt)=>{Dt===ne.length-1?b.push({...Ot,text:`${Ot.text}
1132
+ - stealth: do not mention/apologize for cutoff [/system]`;ne.length>0?ne.forEach((Lt,Dt)=>{Dt===ne.length-1?b.push({...Lt,text:`${Lt.text}
1083
1133
 
1084
- ${rn}`}):b.push(Ot)}):b.push({role:"user",text:rn}),it+=ue}for(let rn=Hn/1e3;rn>0&&!$t;rn--)yield{type:"status",content:`Error Occured. Recovering Stream (${Qe}/${bn}) [Retrying in ${rn.toFixed(0)}s]...`},await new Promise(Ot=>setTimeout(Ot,1e3));yield{type:"status",content:"Error Occured. Recovering Stream..."}}else throw new Error(`Stream collapsed too many times. (Failed to resolve ${bn} times)
1085
- Error log can be found in \`/export logs\``);else if(qe<=bn){qe++,Qe=1,it="";let Hn=Math.min(1e3*Math.pow(2,qe-1),32e3),rn=.8+Math.random()*.4,Ot=Math.round(Hn*rn);to=!0,yield{type:"status",content:`Trying to reach ${e} (${qe}/${bn}) [Retrying in ${(Ot/1e3).toFixed(0)}s]`};for(let Dt=Ot/1e3;Dt>0&&!$t;Dt--)yield{type:"status",content:`Trying to reach ${e} (${qe}/${bn}) [Retrying in ${Dt.toFixed(0)}s]`},await new Promise(Lt=>setTimeout(Lt,1e3));yield{type:"status",content:`Trying to reach ${e}`}}else throw new Error(`Model ${e} cannot be reached. (Failed ${bn} times)
1086
- Error log can be found in \`/export logs\``)}}if(An){let ce=An.totalTokenCount||0,we=An.cachedContentTokenCount||0,de=(An.candidatesTokenCount||0)+(An.thoughtsTokenCount||0);await qt("tokens",ce,f,ke),we>0&&await qt("cachedTokens",we,f,ke),de>0&&await qt("candidateTokens",de,f,ke),yield{type:"usage",content:An}}$i.push(ue);let oo=nn(ue),un=dl(ue),jo=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(un.toLowerCase())||/\[\[END\]\]/i.test(un.toLowerCase())||!0,jn=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(un.toLowerCase()),Sd=ze>0;yield{type:"status",content:"Thinking"};let xl=md(ue,/(\[\s*(turn\s*:)?\s*(continue|finish)\s*\]|\[\[END\]\])/gi,"").trim(),so=(jo||ne.length===0)&&!Ut&&!Sn&&!Mn;if(so=ne.length===0?so:!1,so=no||xs?!1:so,ue&&ue.trim().endsWith('")]')&&ne.length===0&&(so=!1),so){let ce=$i.join(`
1087
- `),we=nn(ce).trim();yield{type:"interactive_turn_finished",data:{agentText:k,fullAgentTextRaw:ce,history:[...b],needTitle:S}},b.length>0&&b[b.length-1].role==="agent"?b[b.length-1].text=we:b.push({role:"agent",text:we}),b.forEach(de=>{if(de.role==="user"&&de.text&&(de.text=de.text.replace(/\n\[COMPILE ERROR\][\s\S]*?\[\/ERROR\]/g,""),de.text=de.text.replaceAll(`
1134
+ ${an}`}):b.push(Lt)}):b.push({role:"user",text:an}),it+=ue}for(let an=qn/1e3;an>0&&!At;an--)yield{type:"status",content:`Error Occured. Recovering Stream (${Qe}/${Sn}) [Retrying in ${an.toFixed(0)}s]...`},await new Promise(Lt=>setTimeout(Lt,1e3));yield{type:"status",content:"Error Occured. Recovering Stream..."}}else throw new Error(`Stream collapsed too many times. (Failed to resolve ${Sn} times)
1135
+ Error log can be found in \`/export logs\``);else if(qe<=Sn){qe++,Qe=1,it="";let qn=Math.min(1e3*Math.pow(2,qe-1),32e3),an=.8+Math.random()*.4,Lt=Math.round(qn*an);no=!0,yield{type:"status",content:`Trying to reach ${e} (${qe}/${Sn}) [Retrying in ${(Lt/1e3).toFixed(0)}s]`};for(let Dt=Lt/1e3;Dt>0&&!At;Dt--)yield{type:"status",content:`Trying to reach ${e} (${qe}/${Sn}) [Retrying in ${Dt.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 ${Sn} times)
1136
+ Error log can be found in \`/export logs\``)}}if(Mn){let ce=Mn.totalTokenCount||0,we=Mn.cachedContentTokenCount||0,de=(Mn.candidatesTokenCount||0)+(Mn.thoughtsTokenCount||0);await zt("tokens",ce,f,ke),we>0&&await zt("cachedTokens",we,f,ke),de>0&&await zt("candidateTokens",de,f,ke),yield{type:"usage",content:Mn}}$i.push(ue);let so=on(ue),pn=dl(ue),Go=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(pn.toLowerCase())||/\[\[END\]\]/i.test(pn.toLowerCase())||!0,Gn=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(pn.toLowerCase()),Sd=ze>0;yield{type:"status",content:"Thinking"};let xl=md(ue,/(\[\s*(turn\s*:)?\s*(continue|finish)\s*\]|\[\[END\]\])/gi,"").trim(),ro=(Go||ne.length===0)&&!Bt&&!kn&&!vn;if(ro=ne.length===0?ro:!1,ro=oo||xs?!1:ro,ue&&ue.trim().endsWith('")]')&&ne.length===0&&(ro=!1),ro){let ce=$i.join(`
1137
+ `),we=on(ce).trim();yield{type:"interactive_turn_finished",data:{agentText:k,fullAgentTextRaw:ce,history:[...b],needTitle:S}},b.length>0&&b[b.length-1].role==="agent"?b[b.length-1].text=we:b.push({role:"agent",text:we}),b.forEach(de=>{if(de.role==="user"&&de.text&&(de.text=de.text.replace(/\n\[COMPILE ERROR\][\s\S]*?\[\/ERROR\]/g,""),de.text=de.text.replaceAll(`
1088
1138
 
1089
1139
  [system] user question. resolve this specific query within '[ANSWER] ... [/ANSWER]' concisely, naturally [/system]
1090
1140
  `,"").replaceAll(`[system] user question. resolve this specific query within '[ANSWER] ... [/ANSWER]' concisely, naturally
1091
1141
  **strictly follow thinking policy as high priority. do not start a response without <think>...</think>** [/system]
1092
1142
  `,"").replaceAll(`[system] **strictly follow thinking policy as high priority. do not start a response without <think>...</think>** [/system]
1093
- `,"").replaceAll(/\n\[system\] WARNING, Turn Limit Impending: Step \d+\/\d+\. Wrap up quickly\/prompt user to continue & use \[\[END\]\] quickly\. \[\/system\]/g,""),de.text=de.text.replaceAll(/\n\[system\] File Changes:\n(?:\* .+ \(created|modified|deleted\)\n)*\[\/system\]/g,""),(f==="Mistral"||f==="Google"&&e?.toLowerCase().startsWith("gemma"))&&de.text.startsWith("[TOOL RESULT]"))){let Wt=`
1094
- [system] Tool result received. Analyze output and proceed with your turn [/system]`,Kt=`
1095
- [system] Tool result received. Analyze output and proceed with your turn. **strictly follow thinking policy. do not start a response without <think>...</think>** [/system]`;de.text=de.text.replaceAll(Kt,"").replaceAll(Wt,"").trim()}}),yield{type:"status",content:"[end]"}}if(so)break;let bl=xl.trim()||"*Working...*";if(b.push({role:"agent",text:bl}),ne.length>0||fn){if(ne.length>0){let ce=ne.map(Gn=>Gn.text).join(`
1143
+ `,"").replaceAll(/\n\[system\] WARNING, Turn Limit Impending: Step \d+\/\d+\. Wrap up quickly\/prompt user to continue & use \[\[END\]\] quickly\. \[\/system\]/g,""),de.text=de.text.replaceAll(/\n\[system\] File Changes:\n(?:\* .+ \(created|modified|deleted\)\n)*\[\/system\]/g,""),(f==="Mistral"||f==="Google"&&e?.toLowerCase().startsWith("gemma"))&&de.text.startsWith("[TOOL RESULT]"))){let jt=`
1144
+ [system] Tool result received. Analyze output and proceed with your turn [/system]`,Vt=`
1145
+ [system] Tool result received. Analyze output and proceed with your turn. **strictly follow thinking policy. do not start a response without <think>...</think>** [/system]`;de.text=de.text.replaceAll(Vt,"").replaceAll(jt,"").trim()}}),yield{type:"status",content:"[end]"}}if(ro)break;let bl=xl.trim()||"*Working...*";if(b.push({role:"agent",text:bl}),ne.length>0||un){if(ne.length>0){let ce=ne.map(Hn=>Hn.text).join(`
1096
1146
 
1097
- `),at=(nn(ue).replace(/\[{1,2}tool:[\s\S]*?\)\s*\]{1,2}/gi,"").match(/\[tool:/gi)||[]).length,Wt=ne.length+at;if(ne.length<Wt){ce+=`
1147
+ `),at=(on(ue).replace(/\[{1,2}tool:[\s\S]*?\)\s*\]{1,2}/gi,"").match(/\[tool:/gi)||[]).length,jt=ne.length+at;if(ne.length<jt){ce+=`
1098
1148
 
1099
- [system] Only ${ne.length} out of ${Wt} attempted tool calls were executed. Verify proper structure compliance & try failed calls again [/system]`;let Gn=Wt-ne.length;for(let It=0;It<Gn;It++)await Mt("toolFailure")}let Kt=ne.find(Gn=>Gn.binaryPart)?.binaryPart||null;b.push({role:"user",text:ce,binaryPart:Kt})}}else if(!$t){let we=(ue.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/i,"").match(/\[tool:/gi)||[]).length;xs||no||we>0?(b.push({role:"user",text:`[system] Failed to execute ${we} tool${we>1?"s":""}. Verify proper structure compliance & try again [/system]`}),await Mt("toolFailure"),yield{type:"visual_feedback",content:`
1100
- ${tn("\u2718 Execution Error")}
1149
+ [system] Only ${ne.length} out of ${jt} attempted tool calls were executed. Verify proper structure compliance & try failed calls again [/system]`;let Hn=jt-ne.length;for(let Ot=0;Ot<Hn;Ot++)await vt("toolFailure")}let Vt=ne.find(Hn=>Hn.binaryPart)?.binaryPart||null;b.push({role:"user",text:ce,binaryPart:Vt})}}else if(!At){let we=(ue.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/i,"").match(/\[tool:/gi)||[]).length;xs||oo||we>0?(b.push({role:"user",text:`[system] Failed to execute ${we} tool${we>1?"s":""}. Verify proper structure compliance & try again [/system]`}),await vt("toolFailure"),yield{type:"visual_feedback",content:`
1150
+ ${nn("\u2718 Execution Error")}
1101
1151
  `}):(yield{type:"visual_feedback",content:`
1102
- ${tn("\u2718 Loop Detected")}
1103
- `},b.push({role:"user",text:`[system] ${Sn&&!Ut?"Stuttering Detected by Internal System. Re-calibrate your response & proceed.":`${Ut?" Over Thinking":" Loop"} Detected by Internal System${Ut?" for current Effort Level":""}. ${Ut?"If you have planned the task, prioritize execution/output":"If you have finished your task provide a simple summary and end"}`} [/system]`})),Ut=!1,Sn=!1,Mn=!1}l?.advanceRollback&&await Qn.recordTurnDelta(d,z+1,on),xs=ze>0||fn}}catch(E){let $=(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(),O=Z.join(mn,"agent");yield{type:"text",content:`\u2726 CRITICAL ERROR: ${$.includes("fetch failed")?"Failed to Connect. Check your Internet Connection or Wait a moment":$}
1152
+ ${nn("\u2718 Loop Detected")}
1153
+ `},b.push({role:"user",text:`[system] ${kn&&!Bt?"Stuttering Detected by Internal System. Re-calibrate your response & proceed.":`${Bt?" Over Thinking":" Loop"} Detected by Internal System${Bt?" for current Effort Level":""}. ${Bt?"If you have planned the task, prioritize execution/output":"If you have finished your task provide a simple summary and end"}`} [/system]`})),Bt=!1,kn=!1,vn=!1}l?.advanceRollback&&await Zn.recordTurnDelta(d,z+1,sn),xs=ze>0||un}}catch(E){let $=(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(),O=Z.join(hn,"agent");yield{type:"text",content:`\u2726 CRITICAL ERROR: ${$.includes("fetch failed")?"Failed to Connect. Check your Internet Connection or Wait a moment":$}
1104
1154
  \u2800`},Fe.existsSync(O)||Fe.mkdirSync(O,{recursive:!0}),Fe.appendFileSync(Z.join(O,"error.log"),`CRITICAL ERROR [${I}]: ${E}
1105
1155
 
1106
1156
  ----------------------------------------------------------------------
1107
1157
 
1108
- `),typeof flushGoogleBuffer=="function"&&(yield*flushGoogleBuffer()),yield{type:"tool_result",content:`ERROR: [INTERNAL CRITICAL] ${$}`}}finally{C&&(clearInterval(C),C=null),typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),await ht.commitTransaction(),l?.advanceRollback&&await Qn.cleanup(d),await wo()}yield{type:"status",content:null}},Ry=async(e,n,t=null,o=null,s=50,r=null,a=!1)=>{let i=await en(),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,u=`${l.getFullYear()}-${l.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(l.getDate()).padStart(2,"0")}, ${l.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}).replace(":","-")}`,m=(E=>{if(!E)return null;let b=E.toLowerCase();return b==="google"?"Google":b==="deepseek"?"DeepSeek":b==="openrouter"?"OpenRouter":b==="nvidia"?"NVIDIA":b==="mistral"?"Mistral":b==="ollama"?"Ollama":b==="crofai"||b==="crof"?"CrofAI":b==="inferx"?"InferX":b==="sensenova"?"SenseNova":null})(c),g=p?.systemSettings?.CustomSubAgent?p?.systemSettings?.SubAgentModel:null,y=p?.systemSettings?.CustomSubAgent?p?.systemSettings?.SubAgentProvider:null,h=null;if(g==="ENV"?(h=d,d&&m&&(p.aiProvider=m)):g&&g!=="Default"?(h=g,y&&(p.aiProvider=y)):d&&m&&(p.aiProvider=m),p.aiProvider){let E=await fr(p.aiProvider);E&&(p.apiKey=E)}let w=E=>{if(!E||typeof E!="string")return{allowed:!0};let b=[/rm\s+-[rf]{1,2}\s+[\/*.]/i,/rmdir\s+\/[sq]/i,/del\s+\/[fsq]/i,/\bformat\b\s+[a-z]:/i,/mkfs/i,/dd\s+if=/i,/\b(shutdown|reboot|poweroff|init\s+0|init\s+6)\b/i,/chmod\s+(-R\s+)?777\s+[\/*.]/i,/chown\s+(-R\s+)?root/i,/git\s+push\s+.*--force/i,/git\s+clean\s+-fdx/i,/\bsudo\s+su\b/i,/\bsu\s+-\b/i];for(let $ of b)if($.test(E))return{allowed:!1,reason:`Blocked potentially destructive or unsafe command pattern: "${$.source}"`};return{allowed:!0}},x=t||h||n?.modelName||n?.activeModel||i.activeModel,T=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",_=`-- TOOL DEFINITIONS (path = relative to CWD, path separator: '/') --
1158
+ `),typeof flushGoogleBuffer=="function"&&(yield*flushGoogleBuffer()),yield{type:"tool_result",content:`ERROR: [INTERNAL CRITICAL] ${$}`}}finally{C&&(clearInterval(C),C=null),typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),await ht.commitTransaction(),l?.advanceRollback&&await Zn.cleanup(d),await xo()}yield{type:"status",content:null}},Ry=async(e,n,t=null,o=null,s=50,r=null,a=!1)=>{let i=await tn(),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,u=`${l.getFullYear()}-${l.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(l.getDate()).padStart(2,"0")}, ${l.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}).replace(":","-")}`,m=(E=>{if(!E)return null;let b=E.toLowerCase();return b==="google"?"Google":b==="deepseek"?"DeepSeek":b==="openrouter"?"OpenRouter":b==="nvidia"?"NVIDIA":b==="mistral"?"Mistral":b==="ollama"?"Ollama":b==="crofai"||b==="crof"?"CrofAI":b==="inferx"?"InferX":b==="sensenova"?"SenseNova":null})(c),g=p?.systemSettings?.CustomSubAgent?p?.systemSettings?.SubAgentModel:null,y=p?.systemSettings?.CustomSubAgent?p?.systemSettings?.SubAgentProvider:null,h=null;if(g==="ENV"?(h=d,d&&m&&(p.aiProvider=m)):g&&g!=="Default"?(h=g,y&&(p.aiProvider=y)):d&&m&&(p.aiProvider=m),p.aiProvider){let E=await fr(p.aiProvider);E&&(p.apiKey=E)}let w=E=>{if(!E||typeof E!="string")return{allowed:!0};let b=[/rm\s+-[rf]{1,2}\s+[\/*.]/i,/rmdir\s+\/[sq]/i,/del\s+\/[fsq]/i,/\bformat\b\s+[a-z]:/i,/mkfs/i,/dd\s+if=/i,/\b(shutdown|reboot|poweroff|init\s+0|init\s+6)\b/i,/chmod\s+(-R\s+)?777\s+[\/*.]/i,/chown\s+(-R\s+)?root/i,/git\s+push\s+.*--force/i,/git\s+clean\s+-fdx/i,/\bsudo\s+su\b/i,/\bsu\s+-\b/i];for(let $ of b)if($.test(E))return{allowed:!1,reason:`Blocked potentially destructive or unsafe command pattern: "${$.source}"`};return{allowed:!0}},x=t||h||n?.modelName||n?.activeModel||i.activeModel,T=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",_=`-- TOOL DEFINITIONS (path = relative to CWD, path separator: '/') --
1109
1159
  You cant execute tools. Instead, output in chat the exact string [tool:functions.ToolName(arg1="value1")] & wait for system response \u2190 no exception, tool:functions must
1110
1160
  Tool Rules:
1111
1161
  - Mandatorily JSON escape literal sequences (backslash: \\\\, newLine: \\ n, quote: \\")
@@ -1131,7 +1181,7 @@ ${a?"- AskMain(question=string). Communicate with PARENT/MAIN AGENT. When clarif
1131
1181
  - ReadFile(path=string, startLine?=int, endLine?=int)
1132
1182
  - PatchFile(path=string, allowMultiple?=bool, searchContent1="string match OR ^LINE:start..end$", newContent1=string, ...MAX15). Small searchString. Line Ranges: ^...$ syntax, must for large blocks/escape sequences
1133
1183
  - WriteFile(path=string, content=string). Creates/Overwrites. File Exist? PatchFile > WriteFile
1134
- - Run(command=string). Runs ${T==="Windows"?Pn()?"powershell":"windows CMD":"bash"} command. Destructive command \u2192 Ask user`.trim(),R=`=== START SYSTEM PROMPT ===
1184
+ - Run(command=string). Runs ${T==="Windows"?Fn()?"powershell":"windows CMD":"bash"} command. Destructive command \u2192 Ask user`.trim(),R=`=== START SYSTEM PROMPT ===
1135
1185
  Identity: FluxFlow subagent helping the main Agent
1136
1186
  Your task is: "${e}"
1137
1187
 
@@ -1145,30 +1195,30 @@ CWD: ${process.cwd()}
1145
1195
  ${_.trimEnd()}
1146
1196
 
1147
1197
  Current Time: ${u}
1148
- === END SYSTEM PROMPT ===`,S=[{role:"user",text:`Complete this task: ${e}`}],k=0,C="";for(;k<s;){if($t){if(n?.taskId&&typeof Xe<"u"){let F=Xe.find(B=>B.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(B=>B.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=S.map(F=>({role:F.role==="user"?"user":"model",parts:[{text:F.text}]}));r&&r(`[Subagent Turn ${k+1}]...`);let $=(await tr(p,x,E,R,"Fast")).text||"",I=nn($).trim();C=I,r&&r(`[Subagent Response]
1198
+ === END SYSTEM PROMPT ===`,S=[{role:"user",text:`Complete this task: ${e}`}],k=0,C="";for(;k<s;){if(At){if(n?.taskId&&typeof Xe<"u"){let F=Xe.find(B=>B.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(B=>B.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=S.map(F=>({role:F.role==="user"?"user":"model",parts:[{text:F.text}]}));r&&r(`[Subagent Turn ${k+1}]...`);let $=(await tr(p,x,E,R,"Fast")).text||"",I=on($).trim();C=I,r&&r(`[Subagent Response]
1149
1199
  ${I}
1150
- `),S.push({role:"agent",text:I});let O=nr(I);if(O.length===0)break;let P=O.filter(F=>F.toolName.toLowerCase()==="askmain"||F.toolName.toLowerCase()==="ask_main"),W=!1,q="";for(let F of O){if($t){if(n?.taskId&&typeof Xe<"u"){let v=Xe.find(U=>U.id===n.taskId);v&&(v.status="cancelled")}throw new Error("Subagent task was cancelled.")}if(n?.taskId&&typeof Xe<"u"){let v=Xe.find(U=>U.id===n.taskId);if(v&&v.status==="cancelled")throw new Error("Subagent task was cancelled.")}let B=F.toolName.toLowerCase();if(B==="askuser"&&(B="ask"),B==="askmain"||B==="ask_main"){if(W)continue;W=!0;let v="";if(P.length===1?v=D(P[0].args).question||P[0].args:v=P.map((U,X)=>{let te=D(U.args);return`Q${X+1}: ${te.question||U.args}`}).join(`
1200
+ `),S.push({role:"agent",text:I});let O=nr(I);if(O.length===0)break;let P=O.filter(F=>F.toolName.toLowerCase()==="askmain"||F.toolName.toLowerCase()==="ask_main"),W=!1,q="";for(let F of O){if(At){if(n?.taskId&&typeof Xe<"u"){let v=Xe.find(U=>U.id===n.taskId);v&&(v.status="cancelled")}throw new Error("Subagent task was cancelled.")}if(n?.taskId&&typeof Xe<"u"){let v=Xe.find(U=>U.id===n.taskId);if(v&&v.status==="cancelled")throw new Error("Subagent task was cancelled.")}let B=F.toolName.toLowerCase();if(B==="askuser"&&(B="ask"),B==="askmain"||B==="ask_main"){if(W)continue;W=!0;let v="";if(P.length===1?v=L(P[0].args).question||P[0].args:v=P.map((U,X)=>{let te=L(U.args);return`Q${X+1}: ${te.question||U.args}`}).join(`
1151
1201
  `),n.onAskMain){r&&r(`[Executing Tool] AskMain("${v}")...`);let U=await n.onAskMain(v);r&&r(`[Tool Result]
1152
1202
  Answer from Main Agent: ${U}
1153
1203
  `),q+=`[TOOL RESULT for AskMain]: Answer from Main Agent: ${U}
1154
1204
 
1155
- `,await Mt("toolSuccess")}else q+=`[TOOL RESULT for AskMain]: ERROR: Main agent communication channel not available.
1205
+ `,await vt("toolSuccess")}else q+=`[TOOL RESULT for AskMain]: ERROR: Main agent communication channel not available.
1156
1206
 
1157
1207
  `;continue}if(!(o?o.some(v=>v.toLowerCase()===B):!0)){let v=`ERROR: Tool [${F.toolName}] is not in the allowed tools list for this subagent.`;r&&r(`[Blocked Tool Call] ${F.toolName} - not allowed
1158
1208
  `),q+=`${v}
1159
1209
 
1160
- `;continue}if(B==="exec_command"||B==="execcommand"||B==="run"){let v=D(F.args).command||"",U=w(v);if(!U.allowed){let X=`ERROR: [SECURITY RESTRICTION] Subagent execution blocked command: ${U.reason}`;r&&r(`[Blocked Command] ${v} - ${U.reason}
1210
+ `;continue}if(B==="exec_command"||B==="execcommand"||B==="run"){let v=L(F.args).command||"",U=w(v);if(!U.allowed){let X=`ERROR: [SECURITY RESTRICTION] Subagent execution blocked command: ${U.reason}`;r&&r(`[Blocked Command] ${v} - ${U.reason}
1161
1211
  `),q+=`${X}
1162
1212
 
1163
- `;continue}}let Me="";if(B==="web_search"||B==="websearch")Me=`\u2714 \x1B[95mSearched\x1B[0m: ${D(F.args).query||""}`;else if(B==="web_scrape"||B==="webscrape")Me=`\u2714 \x1B[95mScraped\x1B[0m: ${D(F.args).url||""}`;else if(B==="search_keyword"||B==="searchkeyword"||B==="codesearch"||B==="code_search"){let v=D(F.args),U=v.keyword||"",X=v.path||"";Me=`${U?"\u2714":"\u2718"} \x1B[95mSearched\x1B[0m: ${U||"No Query"}${X?` \u2192 ${X.replaceAll("\\","/")}`:""}`}else if(B==="view_file"||B==="viewfile"||B==="readfile")Me=`\u2714 \x1B[95mRead\x1B[0m: ${(D(F.args).path||"").replaceAll("\\","/")}`;else if(B==="list_files"||B==="read_folder"||B==="readfolder"){let v=D(F.args).path||null,U=D(F.args).recurse||0;Me=`${v?"\u2714":"\u2718"} \x1B[95mBrowsed\x1B[0m: ${v?`${v.replaceAll("\\","/")}${U>0?`${v.endsWith("/")?`*${U}`:`/*${U}`}`:`${v.endsWith("/")?"":"/"}`}`:""}`}else if(B==="write_file"||B==="writefile"){let v=D(F.args).path||null;Me=`${v?"\u2714":"\u2718"} \x1B[95mCreated\x1B[0m: ${v?`${v.replaceAll("\\","/")}`:"No File Changes"}`}else if(B==="update_file"||B==="updatefile"||B==="patchfile"||B==="patch_file"||B==="patchfile"||B==="updatefile"){let v=D(F.args).path||null,U=D(F.args).content||null;Me=`${v?"\u2714":"\u2718"} \x1B[95mEdited\x1B[0m: ${v?`${v.replaceAll("\\","/")}`:"No File Changes"}`}else if(B==="exec_command"||B==="execcommand"||B==="run"){let v=D(F.args).command||null;Me=`${v?"\u2714":"\u2718"} \x1B[95mExecuted\x1B[0m: ${v?v.slice(0,100)+(v.length>100?"...":""):"No Command"}`}else if(B==="file_map"||B==="filemap"){let v=D(F.args).path||"";Me=`${v?"\u2714":"\u2718"} \x1B[95mIndexed\x1B[0m: ${v?`${v.replaceAll("\\","/")}`:"File Not Found"}`}else if(B==="await"){let{time:v}=D(F.args),U=parseFloat(v)||0;U<10&&(U=10),U>180&&(U=180),Me=`\u2714 \x1B[95mAwaiting\x1B[0m \u2192 ${(te=>{if(te>=60){let We=Math.floor(te/60),Ne=te%60;return`${We}m${Ne>0?` ${Ne}s`:""}`}return`${te}s`})(U)}`}else{let v=gi[B]||F.toolName,U=So(B,F.args);Me=`\u2714 \x1B[95m${v}\x1B[0m${U?`: ${U}`:""}`}n.onVisualFeedback&&Me&&n.onVisualFeedback(Me),r&&r(`[Executing Tool] ${F.toolName}(${F.args})...`);try{let v=await ps(F.toolName,F.args,{...n,mode:"Flux"});if(r&&r(`[Tool Result]
1213
+ `;continue}}let Me="";if(B==="web_search"||B==="websearch")Me=`\u2714 \x1B[95mSearched\x1B[0m: ${L(F.args).query||""}`;else if(B==="web_scrape"||B==="webscrape")Me=`\u2714 \x1B[95mScraped\x1B[0m: ${L(F.args).url||""}`;else if(B==="search_keyword"||B==="searchkeyword"||B==="codesearch"||B==="code_search"){let v=L(F.args),U=v.keyword||"",X=v.path||"";Me=`${U?"\u2714":"\u2718"} \x1B[95mSearched\x1B[0m: ${U||"No Query"}${X?` \u2192 ${X.replaceAll("\\","/")}`:""}`}else if(B==="view_file"||B==="viewfile"||B==="readfile")Me=`\u2714 \x1B[95mRead\x1B[0m: ${(L(F.args).path||"").replaceAll("\\","/")}`;else if(B==="list_files"||B==="read_folder"||B==="readfolder"){let v=L(F.args).path||null,U=L(F.args).recurse||0;Me=`${v?"\u2714":"\u2718"} \x1B[95mBrowsed\x1B[0m: ${v?`${v.replaceAll("\\","/")}${U>0?`${v.endsWith("/")?`*${U}`:`/*${U}`}`:`${v.endsWith("/")?"":"/"}`}`:""}`}else if(B==="write_file"||B==="writefile"){let v=L(F.args).path||null;Me=`${v?"\u2714":"\u2718"} \x1B[95mCreated\x1B[0m: ${v?`${v.replaceAll("\\","/")}`:"No File Changes"}`}else if(B==="update_file"||B==="updatefile"||B==="patchfile"||B==="patch_file"||B==="patchfile"||B==="updatefile"){let v=L(F.args).path||null,U=L(F.args).content||null;Me=`${v?"\u2714":"\u2718"} \x1B[95mEdited\x1B[0m: ${v?`${v.replaceAll("\\","/")}`:"No File Changes"}`}else if(B==="exec_command"||B==="execcommand"||B==="run"){let v=L(F.args).command||null;Me=`${v?"\u2714":"\u2718"} \x1B[95mExecuted\x1B[0m: ${v?v.slice(0,100)+(v.length>100?"...":""):"No Command"}`}else if(B==="file_map"||B==="filemap"){let v=L(F.args).path||"";Me=`${v?"\u2714":"\u2718"} \x1B[95mIndexed\x1B[0m: ${v?`${v.replaceAll("\\","/")}`:"File Not Found"}`}else if(B==="await"){let{time:v}=L(F.args),U=parseFloat(v)||0;U<10&&(U=10),U>180&&(U=180),Me=`\u2714 \x1B[95mAwaiting\x1B[0m \u2192 ${(te=>{if(te>=60){let We=Math.floor(te/60),Ne=te%60;return`${We}m${Ne>0?` ${Ne}s`:""}`}return`${te}s`})(U)}`}else{let v=gi[B]||F.toolName,U=ko(B,F.args);Me=`\u2714 \x1B[95m${v}\x1B[0m${U?`: ${U}`:""}`}n.onVisualFeedback&&Me&&n.onVisualFeedback(Me),r&&r(`[Executing Tool] ${F.toolName}(${F.args})...`);try{let v=await ms(F.toolName,F.args,{...n,mode:"Flux"});if(r&&r(`[Tool Result]
1164
1214
  ${v}
1165
1215
  `),q+=`[TOOL RESULT for ${F.toolName}]: ${v}
1166
1216
 
1167
- `,await Mt("toolSuccess"),B==="patchfile"||B==="update_file"||B==="updatefile"||B==="patch_file"){if(v){let U=v.split(`
1168
- `),X=0,te=0,We=!1;for(let Ne of U){if(Ne.includes("[DIFF_START]")){We=!0;continue}if(Ne.includes("[DIFF_END]")){We=!1;continue}We&&(/^\+\d+/.test(Ne)?X++:/^\-\d+/.test(Ne)&&te++)}(X>0||te>0)&&(await qt("linesAdded",X),await qt("linesRemoved",te))}}else if((B==="writefile"||B==="write_file")&&v){let U=v.match(/- Stats: \[(\d+) lines/),X=U?parseInt(U[1]):0,te=0;if(v.includes("Old File contents:")){let We=!1;for(let Ne of v.split(`
1169
- `)){if(Ne.includes("Old File contents:")){We=!0;continue}We&&(Ne.trim()===""?We=!1:/^\d+ \|/.test(Ne)&&te++)}}(X>0||te>0)&&(await qt("linesAdded",X),await qt("linesRemoved",te))}}catch(v){let U=`ERROR: Execution failed for [${F.toolName}]: ${v.message}`;r&&r(`[Tool Error] ${U}
1217
+ `,await vt("toolSuccess"),B==="patchfile"||B==="update_file"||B==="updatefile"||B==="patch_file"){if(v){let U=v.split(`
1218
+ `),X=0,te=0,We=!1;for(let Ne of U){if(Ne.includes("[DIFF_START]")){We=!0;continue}if(Ne.includes("[DIFF_END]")){We=!1;continue}We&&(/^\+\d+/.test(Ne)?X++:/^\-\d+/.test(Ne)&&te++)}(X>0||te>0)&&(await zt("linesAdded",X),await zt("linesRemoved",te))}}else if((B==="writefile"||B==="write_file")&&v){let U=v.match(/- Stats: \[(\d+) lines/),X=U?parseInt(U[1]):0,te=0;if(v.includes("Old File contents:")){let We=!1;for(let Ne of v.split(`
1219
+ `)){if(Ne.includes("Old File contents:")){We=!0;continue}We&&(Ne.trim()===""?We=!1:/^\d+ \|/.test(Ne)&&te++)}}(X>0||te>0)&&(await zt("linesAdded",X),await zt("linesRemoved",te))}}catch(v){let U=`ERROR: Execution failed for [${F.toolName}]: ${v.message}`;r&&r(`[Tool Error] ${U}
1170
1220
  `),q+=`${U}
1171
1221
 
1172
- `,await Mt("toolFailure")}}let Q="";if(n?.taskId&&typeof Xe<"u"){let F=Xe.find(B=>B.id===n.taskId);if(F&&F.pendingSteerMessages&&F.pendingSteerMessages.length>0){let B=[...F.pendingSteerMessages];F.pendingSteerMessages=[];for(let ee of B)Q+=`
1222
+ `,await vt("toolFailure")}}let Q="";if(n?.taskId&&typeof Xe<"u"){let F=Xe.find(B=>B.id===n.taskId);if(F&&F.pendingSteerMessages&&F.pendingSteerMessages.length>0){let B=[...F.pendingSteerMessages];F.pendingSteerMessages=[];for(let ee of B)Q+=`
1173
1223
 
1174
- [STEERING INSTRUCTION FROM MAIN AGENT]: ${ee}`,r&&r(`[Subagent Steered] ${ee}`)}}let V=(q.trim()+Q).trim();S.push({role:"user",text:V}),k++}return C};export{yn as a,_a as b,Nu as c,Uu as d,rc as e,$a as f,Bu as g,uc as h,Wu as i,ms as j,Qa as k,Jh as l,Qh as m,D as n,$d as o,pr as p,Yo as q,Ad as r,Md as s,Mf as t,vf as u,ht as v,fo as w,zf as x,Gl as y,Kf as z,Yf as A,Vf as B,Xf as C,Jf as D,uo as E,Cc as F,Wp as G,jp as H,tg as I,Hs as J,ng as K,rd as L,yy as M,id as N,ad as O,hi as P,nn as Q,cl as R,fd as S,wy as T,xy as U,wi as V,by as W,Sy as X,xd as Y,ky as Z,Ty as _,Ry as $};
1224
+ [STEERING INSTRUCTION FROM MAIN AGENT]: ${ee}`,r&&r(`[Subagent Steered] ${ee}`)}}let V=(q.trim()+Q).trim();S.push({role:"user",text:V}),k++}return C};export{wn as a,_a as b,Nu as c,Uu as d,rc as e,$a as f,Bu as g,uc as h,Wu as i,hs as j,Qa as k,Jh as l,Qh as m,L as n,$d as o,pr as p,Vo as q,Ad as r,Md as s,Mf as t,vf as u,ht as v,uo as w,zf as x,Gl as y,Kf as z,Yf as A,Vf as B,Xf as C,Jf as D,po as E,Cc as F,Wp as G,jp as H,tg as I,Hs as J,ng as K,rd as L,yy as M,id as N,ad as O,hi as P,on as Q,cl as R,fd as S,wy as T,xy as U,wi as V,by as W,Sy as X,xd as Y,ky as Z,Ty as _,Ry as $};