fluxflow-cli 4.9.0 → 4.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,16 +1,16 @@
1
- import{b as mr}from"./chunk-JSVFQZL2.js";import{e as Ot,g as zt,i as Li,j as Di,k as Pi,l as Fi,m as Ni}from"./chunk-CCXXAPYH.js";import{c as xt,d as vo,g as de,h as tn}from"./chunk-LD4KZAYI.js";import{a as pr,b as Oi,c as se,d as ye}from"./chunk-SIINYZWE.js";import{a as _t,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 fr,r as Yn,s as uo}from"./chunk-4TZKD2XR.js";import{a as Qe,c as Rs}from"./chunk-56EJGQU3.js";import{c as Ui,d as Bi,e as Yo}from"./chunk-BQQGML7T.js";import Yt from"dotenv";import{GoogleGenAI as ml,ThinkingLevel as mt,HarmBlockThreshold as eo,HarmCategory as to}from"@google/genai";import{execSync as ji}from"child_process";import{spawn as hr}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 f=0;for(let y=l-1;y>=0&&e[y]==="\\";y--)f++;if(f%2!==0){d=l+1;continue}let u=e.substring(l+1),m=u.trim(),g=m===""||/^,\s*\w+\s*=/.test(m)||m.startsWith(")")&&(m.length===1||/^\)\s*([,\]\s]|\[\[?tool:)/i.test(m));if(g&&u.startsWith(`
1
+ import{b as mr}from"./chunk-JSVFQZL2.js";import{e as Dt,g as Vt,i as Li,j as Di,k as Pi,l as Fi,m as Ni}from"./chunk-W3TQYL57.js";import{c as bt,d as vo,g as de,h as on}from"./chunk-QQXHAYOT.js";import{a as pr,b as Oi,c as se,d as ye}from"./chunk-SIINYZWE.js";import{a as Ct,c as Fn,d as yn,e as Ts,f as Ao,g as Mo,j as Ut,k as nn,l as Nn,m as Kn,n as dn,o as wn,p as co,q as fr,r as Yn,s as uo}from"./chunk-4TZKD2XR.js";import{a as Qe,c as Rs}from"./chunk-56EJGQU3.js";import{c as Ui,d as Bi,e as Yo}from"./chunk-OZ2EUJLG.js";import Jt from"dotenv";import{GoogleGenAI as ml,ThinkingLevel as mt,HarmBlockThreshold as eo,HarmCategory as to}from"@google/genai";import{execSync as ji}from"child_process";import{spawn as hr}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 f=0;for(let y=l-1;y>=0&&e[y]==="\\";y--)f++;if(f%2!==0){d=l+1;continue}let u=e.substring(l+1),m=u.trim(),g=m===""||/^,\s*\w+\s*=/.test(m)||m.startsWith(")")&&(m.length===1||/^\)\s*([,\]\s]|\[\[?tool:)/i.test(m));if(g&&u.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,f)=>{switch(f){case"n":return`
4
4
  `;case"r":return"\r";case"t":return" ";case"\\":return"\\";default:return f===a?a:f}})}else if(t<e.length&&e[t]==="["){let a=0,i=null,p=t,d=-1;for(let c=t;c<e.length;c++){let l=e[c];if(i&&l===i){let f=0;for(let u=c-1;u>=0&&e[u]==="\\";u--)f++;f%2===0&&(i=null)}else!i&&(l==='"'||l==="'"||l==="`")&&(i=l);if(!i&&(l==="["?a++:l==="]"&&a--,a===0)){d=c;break}}if(d!==-1){r=e.substring(p,d+1),t=d+1;try{let c=r.trim();c.startsWith("'")||c.includes("'")}catch{}}else r=e.substring(p),t=e.length}else{let a=e.substring(t),i=a.match(/,\s*\w+\s*=|(?:\s*\)\s*(?:$|\]\]))/);if(i){let p=i.index;r=a.substring(0,p).trim(),t+=p}else r=a.trim(),t=e.length}r==="true"?r=!0:r==="false"?r=!1:typeof r=="string"&&!isNaN(r)&&r.trim()!==""&&(r=Number(r)),typeof r=="string"&&(s.toLowerCase().includes("path")||["dest","source","to","from"].includes(s.toLowerCase()))&&(r=r.replace(/\x0C/g,"\\f").replace(/\x0D/g,"\\r").replace(/\x0B/g,"\\v").replace(/\x08/g,"\\b")),n[s]=r}return n};var Es=null;try{let e=await import("node-pty");Es=e.default||e}catch{}var vd=!!Es,_s=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),gr=e=>{if(!e)return"";let n=[[]],t=0,o=0,s=/\x1b\[([0-9;]*?)([a-zA-Z])/g,r=0,a,i=d=>{for(let c=0;c<d.length;c++){let l=d[c];if(l===`
5
5
  `)for(t++,o=0;t>=n.length;)n.push([]);else if(l==="\r")o=0;else{for(;t>=n.length;)n.push([]);let f=n[t];for(;o>f.length;)f.push(" ");f[o]=l,o++}}};for(;(a=s.exec(e))!==null;){i(e.substring(r,a.index));let d=a[1],c=a[2],l=d?d.split(";").map(Number):[];if(c==="A"){let f=l[0]||1;t=Math.max(0,t-f)}else if(c==="B"){let f=l[0]||1;for(t=t+f;t>=n.length;)n.push([])}else if(c==="C"){let f=l[0]||1;o=o+f}else if(c==="D"){let f=l[0]||1;o=Math.max(0,o-f)}else if(c==="G"){let f=(l[0]||1)-1;o=Math.max(0,f)}else if(c==="H"||c==="f"){let f=(l[0]||1)-1,u=(l[1]||1)-1;for(t=Math.max(0,f),o=Math.max(0,u);t>=n.length;)n.push([])}else if(c==="K"){let f=l[0]||0;if(t<n.length){let u=n[t];if(f===0)u.length=o;else if(f===1)for(let m=0;m<o&&m<u.length;m++)u[m]=" ";else f===2&&(u.length=0)}}else if(c==="J"){let f=l[0]||0;(f===2||f===3)&&(n.length=0,n.push([]),t=0,o=0)}r=s.lastIndex}i(e.substring(r));let p=n.map(d=>d.join(""));for(;p.length>0&&p[p.length-1]==="";)p.pop();return p.join(`
6
- `)},bt=null,Vo=!1,Id=e=>{try{bt&&(Vo&&typeof bt.write=="function"?bt.write(e):bt.stdin&&bt.stdin.writable&&bt.stdin.write(e))}catch{}},Od=()=>{if(bt){try{Vo&&typeof bt.destroy=="function"?bt.destroy():typeof bt.kill=="function"&&(process.platform==="win32"?hr("taskkill",["/pid",bt.pid,"/f","/t"]):bt.kill("SIGKILL"))}catch{}bt=null,Vo=!1}},yr=(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 f=[],u=c+1;for(;u<t.length;){let m=t[u];if([">",">>","<","&","&&","|","||",";"].includes(m))break;m!=="-p"&&m!=="--parents"&&m!=="-v"&&m!=="--verbose"&&f.push(m),u++}if(f.length>0){let m=f.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=u-1;continue}if(l==="rm"&&n&&Fn()){let f=[],u=!1,m=!1,g=c+1;for(;g<t.length;){let h=t[g];if([">",">>","<","&","&&","|","||",";"].includes(h))break;h==="-rf"||h==="-fr"?(u=!0,m=!0):h==="-r"||h==="-R"||h==="--recursive"?u=!0:h==="-f"||h==="--force"?m=!0:f.push(h),g++}let y=["Remove-Item"];if(u&&y.push("-Recurse"),m&&y.push("-Force"),f.length>0){let h=f.map(b=>{let w=b.replace(/^['"]|['"]$/g,""),T=b;return a(w)&&(T=b.replace(/\//g,"\\")),T});y.push("-Path",h.join(","))}i.push(...y),c=g-1;continue}if(l==="cp"&&n&&Fn()){let f=[],u=!1,m=!1,g=c+1;for(;g<t.length;){let h=t[g];if([">",">>","<","&","&&","|","||",";"].includes(h))break;h==="-r"||h==="-R"||h==="--recursive"?u=!0:h==="-f"||h==="--force"?m=!0:f.push(h),g++}let y=["Copy-Item"];if(u&&y.push("-Recurse"),m&&y.push("-Force"),f.length>0){let h=f.map(b=>{let w=b.replace(/^['"]|['"]$/g,""),T=b;return a(w)&&(T=b.replace(/\//g,"\\")),T});if(h.length>1){let b=h.pop();y.push("-Path",h.join(","),"-Destination",b)}else y.push("-Path",h[0])}i.push(...y),c=g-1;continue}if(l==="touch"&&n&&Fn()){let f=[],u=c+1;for(;u<t.length;){let m=t[u];if([">",">>","<","&","&&","|","||",";"].includes(m))break;f.push(m),u++}if(f.length>0){let g=`(${f.map(y=>{let h=y.replace(/^['"]|['"]$/g,""),b=y;return a(h)&&(b=y.replace(/\//g,"\\")),b}).join(", ")}) | ForEach-Object { if (Test-Path $_) { (Get-Item $_).LastWriteTime = [System.DateTime]::Now } else { $null | Out-File -FilePath $_ } }`;i.push(g)}c=u-1;continue}if(l==="|"&&t[c+1]==="tee"){t[c+2]==="-a"?(i.push(">>"),c+=2):(i.push(">"),c+=1);continue}if(l==="|"&&t[c+1]==="cat"&&t[c+2]===">"){i.push(">"),c+=2;continue}if(l==="|"){let f=t[c+1];if(f){let u=f.replace(/^['"]|['"]$/g,""),m=/\.(txt|md|json|log|csv|html|css|py|js|xml|yaml|yml|pdf|docx|pptx|xlsx)$/i.test(u);if(a(u)&&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 f=/^['"]|['"]$/.test(c),u=c;p&&f&&(u=c.replace(/^['"]|['"]$/g,""));let m=/^['"]|['"]$/.test(u),g=u.replace(/^['"]|['"]$/g,"");a(g)&&(u=u.replace(/\//g,"\\"));let y=u.replace(/^['"]|['"]$/g,"");return y.includes(" ")&&!m&&(u=`"${y}"`),u});if(n){let c="",l=0;for(let f=0;f<d.length;f++){let u=d[f];u==="&&"?(c+="; if ($?) {",l++):u===";"?(c+=" }".repeat(l)+";",l=0):(c&&!c.endsWith(" ")&&!c.endsWith("{")&&(c+=" "),c+=u)}return c+=" }".repeat(l),c}return d.join(" ")},wr=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=yr(t,c),f;s?d==="pwsh"?f="pwsh.exe":d==="powershell"?f="powershell.exe":f="cmd.exe":f=process.env.SHELL||"bash";let u=s?c?["-NoProfile","-Command",l]:["/c",l]:["-c",l];if(r.networkAccess===!1&&!s){let m=f,g=[...u];if(process.platform==="linux")f="unshare",u=["-n","-r",m,...g];else if(process.platform==="darwin"){let y=`(version 1)
6
+ `)},kt=null,Vo=!1,Id=e=>{try{kt&&(Vo&&typeof kt.write=="function"?kt.write(e):kt.stdin&&kt.stdin.writable&&kt.stdin.write(e))}catch{}},Od=()=>{if(kt){try{Vo&&typeof kt.destroy=="function"?kt.destroy():typeof kt.kill=="function"&&(process.platform==="win32"?hr("taskkill",["/pid",kt.pid,"/f","/t"]):kt.kill("SIGKILL"))}catch{}kt=null,Vo=!1}},yr=(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&&Un()){let f=[],u=c+1;for(;u<t.length;){let m=t[u];if([">",">>","<","&","&&","|","||",";"].includes(m))break;m!=="-p"&&m!=="--parents"&&m!=="-v"&&m!=="--verbose"&&f.push(m),u++}if(f.length>0){let m=f.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=u-1;continue}if(l==="rm"&&n&&Un()){let f=[],u=!1,m=!1,g=c+1;for(;g<t.length;){let h=t[g];if([">",">>","<","&","&&","|","||",";"].includes(h))break;h==="-rf"||h==="-fr"?(u=!0,m=!0):h==="-r"||h==="-R"||h==="--recursive"?u=!0:h==="-f"||h==="--force"?m=!0:f.push(h),g++}let y=["Remove-Item"];if(u&&y.push("-Recurse"),m&&y.push("-Force"),f.length>0){let h=f.map(b=>{let w=b.replace(/^['"]|['"]$/g,""),T=b;return a(w)&&(T=b.replace(/\//g,"\\")),T});y.push("-Path",h.join(","))}i.push(...y),c=g-1;continue}if(l==="cp"&&n&&Un()){let f=[],u=!1,m=!1,g=c+1;for(;g<t.length;){let h=t[g];if([">",">>","<","&","&&","|","||",";"].includes(h))break;h==="-r"||h==="-R"||h==="--recursive"?u=!0:h==="-f"||h==="--force"?m=!0:f.push(h),g++}let y=["Copy-Item"];if(u&&y.push("-Recurse"),m&&y.push("-Force"),f.length>0){let h=f.map(b=>{let w=b.replace(/^['"]|['"]$/g,""),T=b;return a(w)&&(T=b.replace(/\//g,"\\")),T});if(h.length>1){let b=h.pop();y.push("-Path",h.join(","),"-Destination",b)}else y.push("-Path",h[0])}i.push(...y),c=g-1;continue}if(l==="touch"&&n&&Un()){let f=[],u=c+1;for(;u<t.length;){let m=t[u];if([">",">>","<","&","&&","|","||",";"].includes(m))break;f.push(m),u++}if(f.length>0){let g=`(${f.map(y=>{let h=y.replace(/^['"]|['"]$/g,""),b=y;return a(h)&&(b=y.replace(/\//g,"\\")),b}).join(", ")}) | ForEach-Object { if (Test-Path $_) { (Get-Item $_).LastWriteTime = [System.DateTime]::Now } else { $null | Out-File -FilePath $_ } }`;i.push(g)}c=u-1;continue}if(l==="|"&&t[c+1]==="tee"){t[c+2]==="-a"?(i.push(">>"),c+=2):(i.push(">"),c+=1);continue}if(l==="|"&&t[c+1]==="cat"&&t[c+2]===">"){i.push(">"),c+=2;continue}if(l==="|"){let f=t[c+1];if(f){let u=f.replace(/^['"]|['"]$/g,""),m=/\.(txt|md|json|log|csv|html|css|py|js|xml|yaml|yml|pdf|docx|pptx|xlsx)$/i.test(u);if(a(u)&&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 f=/^['"]|['"]$/.test(c),u=c;p&&f&&(u=c.replace(/^['"]|['"]$/g,""));let m=/^['"]|['"]$/.test(u),g=u.replace(/^['"]|['"]$/g,"");a(g)&&(u=u.replace(/\//g,"\\"));let y=u.replace(/^['"]|['"]$/g,"");return y.includes(" ")&&!m&&(u=`"${y}"`),u});if(n){let c="",l=0;for(let f=0;f<d.length;f++){let u=d[f];u==="&&"?(c+="; if ($?) {",l++):u===";"?(c+=" }".repeat(l)+";",l=0):(c&&!c.endsWith(" ")&&!c.endsWith("{")&&(c+=" "),c+=u)}return c+=" }".repeat(l),c}return d.join(" ")},wr=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=yr(t,c),f;s?d==="pwsh"?f="pwsh.exe":d==="powershell"?f="powershell.exe":f="cmd.exe":f=process.env.SHELL||"bash";let u=s?c?["-NoProfile","-Command",l]:["/c",l]:["-c",l];if(r.networkAccess===!1&&!s){let m=f,g=[...u];if(process.platform==="linux")f="unshare",u=["-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
- `;f="sandbox-exec",u=["-p",y,m,...g]}}if(Es)try{let m=Es.spawn(f,u,{name:"xterm-256color",cols:n.cols||120,rows:n.rows||30,cwd:process.cwd(),env:{...process.env,CI:"false",TERM:"xterm-256color",FORCE_COLOR:"1",...a}});bt=m,Vo=!0;let g="",y=!1;return m.onData(h=>{if(!y){g+=h,o&&o(h);let b=_s(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(b)&&(y=!0,setTimeout(()=>i(`SUCCESS: Dev server started successfully in background.
11
+ `;f="sandbox-exec",u=["-p",y,m,...g]}}if(Es)try{let m=Es.spawn(f,u,{name:"xterm-256color",cols:n.cols||120,rows:n.rows||30,cwd:process.cwd(),env:{...process.env,CI:"false",TERM:"xterm-256color",FORCE_COLOR:"1",...a}});kt=m,Vo=!0;let g="",y=!1;return m.onData(h=>{if(!y){g+=h,o&&o(h);let b=_s(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(b)&&(y=!0,setTimeout(()=>i(`SUCCESS: Dev server started successfully in background.
12
12
 
13
- ${b}`),500))}}),m.onExit(({exitCode:h})=>{if(y)return;bt=null;let b=gr(g||""),w=_s(b).replace(/\n{3,}/g,`
13
+ ${b}`),500))}}),m.onExit(({exitCode:h})=>{if(y)return;kt=null;let b=gr(g||""),w=_s(b).replace(/\n{3,}/g,`
14
14
 
15
15
  `)||"Command executed with no output.";i(h!==0?`ERROR: Command [${t}] failed with exit code [${h}].
16
16
 
@@ -21,9 +21,9 @@ ${w}`)}),!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?hr(d,c,{cwd:process.cwd(),env:{...process.env,...o}}):hr(d,c,{cwd:process.cwd(),env:{...process.env,CI:"false",TERM:"xterm-256color",FORCE_COLOR:"1",...o}});bt=l,Vo=!1,l.stdin&&l.stdin.on("error",()=>{bt=null});let f="",u="",m=!1;l.stdout.on("data",g=>{if(!m){let y=g.toString();f+=y,s&&s(y);let h=_s(f);/(?:Network:\s+use\s+--host\s+to|Network:\s+Type\s+--host\s+to|Local:\s+http:\/\/localhost:\d+|ready in \d+\s*ms|Compiled successfully|Development server is running|Listening on:)/i.test(h)&&(m=!0,setTimeout(()=>e(`SUCCESS: Dev server started successfully in background.
24
+ `;d="sandbox-exec",c=["-p",h,g,...y]}}let l=i?hr(d,c,{cwd:process.cwd(),env:{...process.env,...o}}):hr(d,c,{cwd:process.cwd(),env:{...process.env,CI:"false",TERM:"xterm-256color",FORCE_COLOR:"1",...o}});kt=l,Vo=!1,l.stdin&&l.stdin.on("error",()=>{kt=null});let f="",u="",m=!1;l.stdout.on("data",g=>{if(!m){let y=g.toString();f+=y,s&&s(y);let h=_s(f);/(?:Network:\s+use\s+--host\s+to|Network:\s+Type\s+--host\s+to|Local:\s+http:\/\/localhost:\d+|ready in \d+\s*ms|Compiled successfully|Development server is running|Listening on:)/i.test(h)&&(m=!0,setTimeout(()=>e(`SUCCESS: Dev server started successfully in background.
25
25
 
26
- ${h}`),500))}}),l.stderr.on("data",g=>{if(!m){let y=g.toString();u+=y,s&&s(y)}}),l.on("close",g=>{if(m)return;bt=null;let y=[],h=gr(f),b=gr(u);h&&y.push(`STDOUT:
26
+ ${h}`),500))}}),l.stderr.on("data",g=>{if(!m){let y=g.toString();u+=y,s&&s(y)}}),l.on("close",g=>{if(m)return;kt=null;let y=[],h=gr(f),b=gr(u);h&&y.push(`STDOUT:
27
27
  ${h}`),b&&y.push(`STDERR:
28
28
  ${b}`),g!==0&&y.push(`EXIT CODE: ${g}`);let w=y.join(`
29
29
 
@@ -33,7 +33,7 @@ ${b}`),g!==0&&y.push(`EXIT CODE: ${g}`);let w=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=yr(t,!0);return Cs(e,h,t,o,s,"powershell",a)}else if(r==="powershell"){let h=yr(t,!1);return Cs(e,h,t,o,s,"cmd",a)}}bt=null;let y=g instanceof Error?g.message:String(g);e(`ERROR: Failed to start command [${t}]: ${y}`)})};var Xo=null,Ol=()=>{if(process.platform!=="win32")return!1;if(Xo!==null)return Xo;try{ji("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{ji("where.exe powershell.exe",{stdio:"ignore",windowsHide:!0}),Jo=!0}catch{Jo=!1}return Jo},Wi=()=>Ol()?"pwsh":Fn()?"powershell":"cmd",xr=null,Gi=(e,n,t,o,s=!1,r=!0,a)=>{xr===null&&(xr=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=yr(t,!0);return Cs(e,h,t,o,s,"powershell",a)}else if(r==="powershell"){let h=yr(t,!1);return Cs(e,h,t,o,s,"cmd",a)}}kt=null;let y=g instanceof Error?g.message:String(g);e(`ERROR: Failed to start command [${t}]: ${y}`)})};var Xo=null,Ol=()=>{if(process.platform!=="win32")return!1;if(Xo!==null)return Xo;try{ji("where.exe pwsh.exe",{stdio:"ignore",windowsHide:!0}),Xo=!0}catch{Xo=!1}return Xo},Jo=null,Un=()=>{if(process.platform!=="win32")return!1;if(Jo!==null)return Jo;try{ji("where.exe powershell.exe",{stdio:"ignore",windowsHide:!0}),Jo=!0}catch{Jo=!1}return Jo},Wi=()=>Ol()?"pwsh":Un()?"powershell":"cmd",xr=null,Gi=(e,n,t,o,s=!1,r=!0,a)=>{xr===null&&(xr=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,7 +46,7 @@ ${T}`)}),l.on("error",g=>{if(i&&g.code==="ENOENT"){if(r==="pwsh"){let h=yr(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"?Fn()?"powershell":"windows CMD":"bash"} command. Destructive command \u2192 Ask user
49
+ - Run(command=string). Runs ${n==="Windows"?Un()?"powershell":"windows CMD":"bash"} command. Destructive command \u2192 Ask user
50
50
  - Goal(method="create/append/get", tasks=string[], markDone=string[]). If long multi-task: create Goals before starting. get + markDone marks complete
51
51
  ${xr?`
52
52
  **Emergency Tools**
@@ -132,7 +132,7 @@ Dont waste tokens, be efficient, use least thinking tokens, focus on result
132
132
  Gather useful context
133
133
  Brief thoughts, think only enough to avoid mistakes, verify imports, system stability`,Off:`Effort: Lowest
134
134
  No thinking. Immediate response
135
- Verify imports, tool results & system stability`};import Xn from"fs";import $r from"path";import Pl from"os";import Fl from"screenshot-desktop";import Cn from"fs";import Vn from"path";import oa from"fs";import br from"path";import{execSync as sa}from"child_process";import{fileURLToPath as Dl}from"url";var qi=`# FluxFlow CLI Startup & Flags Reference
135
+ Verify imports, tool results & system stability`};import Xn from"fs";import $r from"path";import Pl from"os";import Fl from"screenshot-desktop";import An from"fs";import Vn from"path";import oa from"fs";import br from"path";import{execSync as sa}from"child_process";import{fileURLToPath as Dl}from"url";var qi=`# FluxFlow CLI Startup & Flags Reference
136
136
 
137
137
  Launch command syntax:
138
138
  fluxflow [options]
@@ -510,15 +510,15 @@ Documentation: https://fluxflow-cli.onrender.com
510
510
  * Priority Instructions (AGENTS.md/FLUXFLOW.md) & Skill System \u2192 references/PLUGINS.md
511
511
  * Agent Architecture & Memory System \u2192 references/ARCHITECTURE.md
512
512
 
513
- Docs missing required info? Say you are not sure enough to answer. Dont give wrong info`,"references/MODES.md":ea,"references/PROVIDERS.md":ta,"references/PLUGINS.md":na,"references/STARTUP.md":qi,"references/ENV.md":zi,"references/COMMANDS.md":Ki,"references/SETTINGS.md":Yi,"references/TOOLS.md":Vi,"references/ARCHITECTURE.md":Xi,"references/SUB_AGENTS.md":Ji,"references/SECURITY.md":Qi,"references/IDE.md":Zi};var ra=()=>{try{let e=Vn.join(_t,"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){Cn.existsSync(e)&&Cn.rmSync(e,{recursive:!0,force:!0});return}let o=new Set(Object.keys(kr).map(s=>Vn.normalize(s)));for(let[s,r]of Object.entries(kr)){let a=Vn.join(e,s),i=Vn.dirname(a);Cn.existsSync(i)||Cn.mkdirSync(i,{recursive:!0});let p=r.trim()+`
514
- `,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=Vn.normalize(Vn.join("references",r));if(!o.has(a)){let i=Vn.join(n,r);try{Cn.rmSync(i,{recursive:!0,force:!0})}catch{}}}}}catch{}};var Ar=(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=$r.join(e,r);if(Xn.statSync(a).isFile())return a}}}catch{}return null},la=(e,n)=>{let t=Ar(e,n);if(t)try{return Xn.readFileSync(t,"utf8")}catch{}return""},Er=Ar(_t,["fluxflow.md","agent.md","agents.md"]),_r=Ar(process.cwd(),["fluxflow.md","agent.md","agents.md"]),Nl=Er?la(_t,["fluxflow.md","agent.md","agents.md"]).trim():"",Cr="",ca=!1,Ul=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&&(Cr=s[1].trim(),process.env.NO_INS=!0),/<><\s*NO_INS/.test(t)&&(ca=!0),o.trim()},Io=Ul(Nl);ra();var Zo=_r?la(process.cwd(),["fluxflow.md","agent.md","agents.md"]).trim():"",Bl=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},Wl=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=$r.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},da=e=>{let n=Wl(e),t=[];for(let o of n)try{let s=Xn.readFileSync(o,"utf8"),r=Bl(s);r&&t.push({...r,filePath:o})}catch{}return t},ua=e=>!e||e.length===0?"":e.map(n=>`- ${n.name}: ${n.description}`).join(`
515
- `),fa=da(_t),pa=da(process.cwd()),Sr=ua(fa),Tr=ua(pa),ma=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"},ha=()=>(fa||[]).filter(e=>!ma(e)),ga=()=>(pa||[]).filter(e=>!ma(e)),Iu=(Io?1:0)+(Zo?1:0)+ha().length+ga().length,Rr=(e,n="Project")=>{if(!e)return"";let t=e.replace(/\\/g,"/");if(n==="Global"){let s=Pl.homedir().replace(/\\/g,"/");return t.toLowerCase().startsWith(s.toLowerCase())?"~"+t.slice(s.length):t}let o=$r.relative(process.cwd(),e).replace(/\\/g,"/");return o.startsWith(".")?o:`./${o}`},Ou=()=>{let e=[];Er&&Io.length>0&&e.push({scope:"Global",path:Er}),_r&&Zo.length>0&&e.push({scope:"Project",path:_r});let n=ha(),t=ga(),o=e.length+n.length+t.length;if(o===0)return`\u2726 Loaded Files & Instructions
513
+ Docs missing required info? Say you are not sure enough to answer. Dont give wrong info`,"references/MODES.md":ea,"references/PROVIDERS.md":ta,"references/PLUGINS.md":na,"references/STARTUP.md":qi,"references/ENV.md":zi,"references/COMMANDS.md":Ki,"references/SETTINGS.md":Yi,"references/TOOLS.md":Vi,"references/ARCHITECTURE.md":Xi,"references/SUB_AGENTS.md":Ji,"references/SECURITY.md":Qi,"references/IDE.md":Zi};var ra=()=>{try{let e=Vn.join(Ct,"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){An.existsSync(e)&&An.rmSync(e,{recursive:!0,force:!0});return}let o=new Set(Object.keys(kr).map(s=>Vn.normalize(s)));for(let[s,r]of Object.entries(kr)){let a=Vn.join(e,s),i=Vn.dirname(a);An.existsSync(i)||An.mkdirSync(i,{recursive:!0});let p=r.trim()+`
514
+ `,d=null;An.existsSync(a)&&(d=An.readFileSync(a,"utf8")),d!==p&&An.writeFileSync(a,p,"utf8")}if(An.existsSync(n)){let s=An.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{An.rmSync(i,{recursive:!0,force:!0})}catch{}}}}}catch{}};var Ar=(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=$r.join(e,r);if(Xn.statSync(a).isFile())return a}}}catch{}return null},la=(e,n)=>{let t=Ar(e,n);if(t)try{return Xn.readFileSync(t,"utf8")}catch{}return""},Er=Ar(Ct,["fluxflow.md","agent.md","agents.md"]),_r=Ar(process.cwd(),["fluxflow.md","agent.md","agents.md"]),Nl=Er?la(Ct,["fluxflow.md","agent.md","agents.md"]).trim():"",Cr="",ca=!1,Ul=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&&(Cr=s[1].trim(),process.env.NO_INS=!0),/<><\s*NO_INS/.test(t)&&(ca=!0),o.trim()},Io=Ul(Nl);ra();var Zo=_r?la(process.cwd(),["fluxflow.md","agent.md","agents.md"]).trim():"",Bl=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},Wl=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=$r.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},da=e=>{let n=Wl(e),t=[];for(let o of n)try{let s=Xn.readFileSync(o,"utf8"),r=Bl(s);r&&t.push({...r,filePath:o})}catch{}return t},ua=e=>!e||e.length===0?"":e.map(n=>`- ${n.name}: ${n.description}`).join(`
515
+ `),fa=da(Ct),pa=da(process.cwd()),Sr=ua(fa),Tr=ua(pa),ma=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"},ha=()=>(fa||[]).filter(e=>!ma(e)),ga=()=>(pa||[]).filter(e=>!ma(e)),Iu=(Io?1:0)+(Zo?1:0)+ha().length+ga().length,Rr=(e,n="Project")=>{if(!e)return"";let t=e.replace(/\\/g,"/");if(n==="Global"){let s=Pl.homedir().replace(/\\/g,"/");return t.toLowerCase().startsWith(s.toLowerCase())?"~"+t.slice(s.length):t}let o=$r.relative(process.cwd(),e).replace(/\\/g,"/");return o.startsWith(".")?o:`./${o}`},Ou=()=>{let e=[];Er&&Io.length>0&&e.push({scope:"Global",path:Er}),_r&&Zo.length>0&&e.push({scope:"Project",path:_r});let n=ha(),t=ga(),o=e.length+n.length+t.length;if(o===0)return`\u2726 Loaded Files & Instructions
516
516
  \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m No instruction or skill files are currently loaded.
517
517
  \u2800`;let s=[];return s.push(`\u2726 Loaded Files & Instructions (${o} ${o===1?"file":"files"} active)`),e.length>0&&(s.push(`
518
518
  \x1B[1mInstructions:\x1B[22m`),e.forEach(r=>{s.push(` \u2022 [${r.scope}] ${Rr(r.path,r.scope)}`)})),(n?.length>0||t?.length>0)&&(s.push(`
519
519
  \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 ${Rr(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 ${Rr(r.filePath,"Project")}\x1B[22m`)})),s.push("\u2800"),s.join(`
520
- `)},ya=!1;(async()=>{try{let e=await tn();if(Number(e?.display)===1){let n=await Fl.listDisplays();n&&n.length>1&&(ya=!0)}}catch{}})();var ia=null,Qo=null,aa=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",Lu=process.env.NO_DEV||!1,jl=(e,n)=>{if(!n)return"";if(e!==ia||Qo===null){ia=e;try{let t=se(Ft,[]);Array.isArray(t)&&t.length>0?Qo=t.map(o=>`- ${o.memory}`).join(`
521
- `):Qo=""}catch(t){Qo="",Xn.appendFileSync(`${hn}/memory/error.txt`,`${t.message}
520
+ `)},ya=!1;(async()=>{try{let e=await on();if(Number(e?.display)===1){let n=await Fl.listDisplays();n&&n.length>1&&(ya=!0)}}catch{}})();var ia=null,Qo=null,aa=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",Lu=process.env.NO_DEV||!1,jl=(e,n)=>{if(!n)return"";if(e!==ia||Qo===null){ia=e;try{let t=se(Ut,[]);Array.isArray(t)&&t.length>0?Qo=t.map(o=>`- ${o.memory}`).join(`
521
+ `):Qo=""}catch(t){Qo="",Xn.appendFileSync(`${yn}/memory/error.txt`,`${t.message}
522
522
  -------------------------------------------------
523
523
 
524
524
  `)}}return Qo},wa=(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) --
@@ -547,7 +547,7 @@ ${Zo}`:""}
547
547
  `:"",w=(()=>{let $=process.cwd().toLowerCase();if(process.platform==="win32"){let R=process.env.SystemRoot?.toLowerCase()||"c:\\windows",k=process.env.ProgramFiles?.toLowerCase()||"c:\\program files",S=process.env["ProgramFiles(x86)"]?.toLowerCase()||"c:\\program files (x86)";return $.startsWith(R)||$.startsWith(k)||$.startsWith(S)}else return $==="/"||["/bin","/sbin","/etc","/usr","/var","/root"].some(k=>$.startsWith(k))})();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 ===
548
548
  Identity: ${Cr.length>1?Cr:"Flux Flow. Sassy, Friendly, CLI Assistant"}
549
549
  ${ca?"":`${t==="Flux"?"Stepwise Execution, Run Automated Tests. Task Completion":t==="Flow"?"Concise, Humorous, Sarcastic":t==="ICU"?"Computer Use Capabilities. Screenshot as ground truth, analyze grid ids overlapping/close to target, keyboard shortcuts > mouse clicks":"Computer Use & Workspace Capabilities. Screenshot as ground truth, analyze grid ids overlapping/close to target, keyboard shortcuts > mouse clicks. Workspace Tools if faster. Focus on Productivity"}`}${ya&&t.toLowerCase().includes("cu")?`
550
- **Running on secondary screen. Opened app not visible in screenshot? Might be opened on primary. Use 'AskUser' with NO options and tell user to move app window to secondary**`:""}
550
+ - Running on secondary screen. Opened app not visible in screenshot? Might be opened on primary. Use 'AskUser' with NO options and tell user to move app window to secondary`:""}
551
551
 
552
552
  - OS: ${aa}${s?`
553
553
  - Use relative time reference eg. few mins ago
@@ -560,7 +560,7 @@ ${a==="Mistral"||a==="Google"&&!p?`${l}
560
560
  ${c||n!=="Fast"&&(a==="Mistral"&&!p||n!=="xHigh"&&!p)?`critical thinking policy
561
561
  Use <think>...</think> for reasoning before responding any queries
562
562
  `:""}`:`${l}
563
- `}${a==="ExpLabs"?`Before calling tools: Briefly state plan, rationale & path chosen in text
563
+ `}${a==="ExpLabs"?`Before calling tools: Summarize your reasoning briefly, including plans, and decisions
564
564
  `:""}No text after tool call in same turn
565
565
 
566
566
  ${Gi(t,aa,i,a,o?.advanceRollback,o?.subAgents!==!1,!!o?.autoExec)}${s?`
@@ -604,12 +604,12 @@ ${Hi(n,t)}
604
604
  === END SYSTEM PROMPT ===${e?`
605
605
 
606
606
  -- current saved user memories --
607
- ${e}`:""}`.trim();import vt from"fs-extra";import Ms from"path";import{nanoid as ql}from"nanoid";import ht from"fs-extra";import cn from"path";ht.ensureDirSync(Kn);var yn=null;async function Gl(e,n){try{if(e.type==="create")await ht.pathExists(e.filePath)&&(await ht.chmod(e.filePath,438).catch(()=>{}),await ht.remove(e.filePath));else if(e.type==="update"){if(!e.backupFile)return;let t=cn.join(Kn,n.chatId,e.backupFile);if(await ht.pathExists(t)){let o=se(t,null);if(!o||!o.data)throw new Error(`Backup container corrupt or empty for ${cn.basename(e.filePath)}`);let s=Oi(o.data);await ht.pathExists(e.filePath)&&await ht.chmod(e.filePath,438).catch(()=>{}),await ht.writeFile(e.filePath,s,"utf8")}}}catch(t){throw new Error(`Restoration failed for ${cn.basename(e.filePath)}: ${t.message}`)}}async function Hl(e,n,t=7){let o=0;for(;o<t;)try{return await Gl(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 Mr=null,gt={async startTransaction(e,n){Mr=e,yn={id:`tx_prompt_${Date.now()}`,chatId:e,timestamp:new Date().toISOString(),prompt:n.trim(),changes:[],reverted:!1},ye(co,yn)},async recordFileChange(e,n=null){try{if(!yn){if(Mr){let a=se(ln,[]),i=[...a].reverse().find(p=>p.chatId===Mr);if(i){if(i.changes.some(f=>f.filePath===e))return;let c=await ht.pathExists(e)||n?"update":"create",l=null;if(c==="update"){let f=cn.basename(e);l=`${i.id}_${f}.bak`;let u=cn.join(Kn,i.chatId);await ht.ensureDir(u);let m=cn.join(u,l),g=n!==null?n:await ht.readFile(e,"utf8").catch(()=>null);g!==null?ye(m,{data:pr(g)}):(c="create",l=null)}i.changes.push({filePath:e,type:c,backupFile:l}),ye(ln,a)}}return}if(yn.changes.some(a=>a.filePath===e))return;let s=await ht.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 ht.ensureDir(i);let p=cn.join(i,r),d=n!==null?n:await ht.readFile(e,"utf8").catch(()=>null);d!==null?ye(p,{data:pr(d)}):(s="create",r=null)}yn.changes.push({filePath:e,type:s,backupFile:r}),ye(co,yn)}catch{}},async commitTransaction(){if(yn)try{let e=se(ln,[]);if(e.push(yn),e.length>512e3){let n=e.shift();if(n.changes)for(let t of n.changes)t.backupFile&&await ht.remove(cn.join(Kn,n.chatId,t.backupFile)).catch(()=>{})}ye(ln,e),await ht.remove(co).catch(()=>{})}catch{}finally{yn=null}},async recoverCrashedTransaction(){try{if(await ht.pathExists(co)){let e=se(co,null);if(e?.changes?.length>0){let n=se(ln,[]);n.some(t=>t.id===e.id)||(n.push(e),ye(ln,n))}await ht.remove(co).catch(()=>{})}}catch{}},async rollbackToBefore(e){let n=se(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 Hl(i,a);for(let i of a.changes)if(i.backupFile){let p=cn.join(Kn,a.chatId,i.backupFile);await ht.remove(p).catch(()=>{})}n=n.filter(i=>i.id!==a.id),ye(ln,n)}return{success:!0,chatId:o,targetPrompt:s}},async getChatHistory(e){try{return se(ln,[]).filter(t=>t.chatId===e&&!t.reverted)}catch{return[]}},async deleteChatBackups(e){try{await ht.remove(cn.join(Kn,e));let n=se(ln,[]),t=n.filter(o=>o.chatId!==e);n.length!==t.length&&ye(ln,t)}catch{}}};var ka=Promise.resolve(),vs=e=>{let n=ka.then(async()=>{try{return await e()}catch(t){throw console.error("Lock Operation Failed:",t),t}});return ka=n.catch(()=>{}),n},fo=async()=>{await vt.ensureDir(Mo);let e={};if(await vt.pathExists(Ao))try{e=se(Ao,{})}catch{e={}}for(let n in e){let t=Ms.join(Mo,`${n}.json`);Object.defineProperty(e[n],"messages",{get:()=>{if(vt.existsSync(t))try{return se(t,[])}catch{return[]}return[]},set:o=>{try{ye(t,o)}catch{}},enumerable:!1,configurable:!0})}return e},Yu=async(e,n,t)=>vs(async()=>{await vt.ensureDir(Mo);let o=await fo(),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 b=h.replace(/\s*\n+\s*\[Prompted on:.*?\]/g,"").replace(/\[\/?(?:STEERING HINT|QUESTION)(?::\s*\w+)?\]/gi,"").trim();if(!b)return;let w=b.split(/\s+/),T;return w.length>7?T=w.slice(0,7).join(" ")+"...":b.length>45?T=b.substring(0,45).trimEnd()+"...":T=b,T},i,p=r.filter(y=>y.role==="user"),d=p[0],c=p[p.length-1],l=a(c),f=a(d);s&&s.prompt?Math.random()<.3&&l?i=l:i=s.prompt:i=f||l;let u=n||(s?s.name:`Session ${e.slice(-6)}`),m=Ms.join(Mo,`${e}.json`);ye(m,r),o[e]={name:u,prompt:i||void 0,updatedAt:Date.now()};let g={};for(let y in o)g[y]={name:o[y].name,prompt:o[y].prompt||void 0,updatedAt:o[y].updatedAt};ye(Ao,g)}),Sa=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};ye(Ao,o)}),zl=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(ye(Ao,t),await vt.pathExists(Yn))try{let a=se(Yn,[]);if(Array.isArray(a)){let i=a.filter(p=>Object.keys(p)[0]!==String(e));ye(Yn,i)}}catch{}let o=se(en,{});o[e]&&(delete o[e],ye(en,o));let s=se(Pn,{});s[e]&&(delete s[e],ye(Pn,s)),await gt.deleteChatBackups(e);let r=Ms.join(Mo,`${e}.json`);if(await vt.pathExists(r))try{await vt.remove(r)}catch{}return n}),Vu=()=>`flow-${ql(6)}`,Xu=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 zl(a),r++)}return r},Kl=e=>{let n=e.replace(/[\[\]]/g,"").trim(),t=new Date(n);if(!isNaN(t.getTime()))return t.getTime();let o=n.split(/,\s*|\s+/);if(o.length===0)return null;let s=o[0],r=o[1]||"",a=o[2]||"",i=s.split(/[-\/.]/).map(Number);if(i.length!==3)return null;let p="en";try{p=Intl.DateTimeFormat().resolvedOptions().locale||"en"}catch{}let d=!/^en[-_]?us$|^en$/.test(p?.toLowerCase()),c,l,f;if(i[0]>1e3)c=i[0],l=i[1],f=i[2];else if(i[2]>1e3)c=i[2],i[0]>12?(f=i[0],l=i[1]):i[1]>12?(f=i[1],l=i[0]):d?(f=i[0],l=i[1]):(l=i[0],f=i[1]);else return null;if(l<1||l>12||f<1||f>31)return null;let u=0,m=0,g=0;if(r){let h=r.split(":").map(Number);u=h[0]||0,m=h[1]||0,g=h[2]||0,a.toLowerCase()==="pm"&&u<12?u+=12:a.toLowerCase()==="am"&&u===12&&(u=0)}let y=new Date(c,l-1,f,u,m,g);return isNaN(y.getTime())?null:y.getTime()},Yl=async e=>{try{if(!await vt.pathExists(e))return;let n=await vt.readFile(e,"utf8");if(!n.trim())return;let t=n.split(`
607
+ ${e}`:""}`.trim();import Ot from"fs-extra";import Ms from"path";import{nanoid as ql}from"nanoid";import gt from"fs-extra";import un from"path";gt.ensureDirSync(Kn);var xn=null;async function Gl(e,n){try{if(e.type==="create")await gt.pathExists(e.filePath)&&(await gt.chmod(e.filePath,438).catch(()=>{}),await gt.remove(e.filePath));else if(e.type==="update"){if(!e.backupFile)return;let t=un.join(Kn,n.chatId,e.backupFile);if(await gt.pathExists(t)){let o=se(t,null);if(!o||!o.data)throw new Error(`Backup container corrupt or empty for ${un.basename(e.filePath)}`);let s=Oi(o.data);await gt.pathExists(e.filePath)&&await gt.chmod(e.filePath,438).catch(()=>{}),await gt.writeFile(e.filePath,s,"utf8")}}}catch(t){throw new Error(`Restoration failed for ${un.basename(e.filePath)}: ${t.message}`)}}async function Hl(e,n,t=7){let o=0;for(;o<t;)try{return await Gl(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 Mr=null,yt={async startTransaction(e,n){Mr=e,xn={id:`tx_prompt_${Date.now()}`,chatId:e,timestamp:new Date().toISOString(),prompt:n.trim(),changes:[],reverted:!1},ye(co,xn)},async recordFileChange(e,n=null){try{if(!xn){if(Mr){let a=se(dn,[]),i=[...a].reverse().find(p=>p.chatId===Mr);if(i){if(i.changes.some(f=>f.filePath===e))return;let c=await gt.pathExists(e)||n?"update":"create",l=null;if(c==="update"){let f=un.basename(e);l=`${i.id}_${f}.bak`;let u=un.join(Kn,i.chatId);await gt.ensureDir(u);let m=un.join(u,l),g=n!==null?n:await gt.readFile(e,"utf8").catch(()=>null);g!==null?ye(m,{data:pr(g)}):(c="create",l=null)}i.changes.push({filePath:e,type:c,backupFile:l}),ye(dn,a)}}return}if(xn.changes.some(a=>a.filePath===e))return;let s=await gt.pathExists(e)||n?"update":"create",r=null;if(s==="update"){let a=un.basename(e);r=`${xn.id}_${a}.bak`;let i=un.join(Kn,xn.chatId);await gt.ensureDir(i);let p=un.join(i,r),d=n!==null?n:await gt.readFile(e,"utf8").catch(()=>null);d!==null?ye(p,{data:pr(d)}):(s="create",r=null)}xn.changes.push({filePath:e,type:s,backupFile:r}),ye(co,xn)}catch{}},async commitTransaction(){if(xn)try{let e=se(dn,[]);if(e.push(xn),e.length>512e3){let n=e.shift();if(n.changes)for(let t of n.changes)t.backupFile&&await gt.remove(un.join(Kn,n.chatId,t.backupFile)).catch(()=>{})}ye(dn,e),await gt.remove(co).catch(()=>{})}catch{}finally{xn=null}},async recoverCrashedTransaction(){try{if(await gt.pathExists(co)){let e=se(co,null);if(e?.changes?.length>0){let n=se(dn,[]);n.some(t=>t.id===e.id)||(n.push(e),ye(dn,n))}await gt.remove(co).catch(()=>{})}}catch{}},async rollbackToBefore(e){let n=se(dn,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 Hl(i,a);for(let i of a.changes)if(i.backupFile){let p=un.join(Kn,a.chatId,i.backupFile);await gt.remove(p).catch(()=>{})}n=n.filter(i=>i.id!==a.id),ye(dn,n)}return{success:!0,chatId:o,targetPrompt:s}},async getChatHistory(e){try{return se(dn,[]).filter(t=>t.chatId===e&&!t.reverted)}catch{return[]}},async deleteChatBackups(e){try{await gt.remove(un.join(Kn,e));let n=se(dn,[]),t=n.filter(o=>o.chatId!==e);n.length!==t.length&&ye(dn,t)}catch{}}};var ka=Promise.resolve(),vs=e=>{let n=ka.then(async()=>{try{return await e()}catch(t){throw console.error("Lock Operation Failed:",t),t}});return ka=n.catch(()=>{}),n},fo=async()=>{await Ot.ensureDir(Mo);let e={};if(await Ot.pathExists(Ao))try{e=se(Ao,{})}catch{e={}}for(let n in e){let t=Ms.join(Mo,`${n}.json`);Object.defineProperty(e[n],"messages",{get:()=>{if(Ot.existsSync(t))try{return se(t,[])}catch{return[]}return[]},set:o=>{try{ye(t,o)}catch{}},enumerable:!1,configurable:!0})}return e},Yu=async(e,n,t)=>vs(async()=>{await Ot.ensureDir(Mo);let o=await fo(),s=o[e],r=(t||[]).filter(y=>!y.isUpdateNotification&&(!y.isMeta||y.text&&y.text.includes("Request Cancelled")));try{(await on()).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 b=h.replace(/\s*\n+\s*\[Prompted on:.*?\]/g,"").replace(/\[\/?(?:STEERING HINT|QUESTION)(?::\s*\w+)?\]/gi,"").trim();if(!b)return;let w=b.split(/\s+/),T;return w.length>7?T=w.slice(0,7).join(" ")+"...":b.length>45?T=b.substring(0,45).trimEnd()+"...":T=b,T},i,p=r.filter(y=>y.role==="user"),d=p[0],c=p[p.length-1],l=a(c),f=a(d);s&&s.prompt?Math.random()<.3&&l?i=l:i=s.prompt:i=f||l;let u=n||(s?s.name:`Session ${e.slice(-6)}`),m=Ms.join(Mo,`${e}.json`);ye(m,r),o[e]={name:u,prompt:i||void 0,updatedAt:Date.now()};let g={};for(let y in o)g[y]={name:o[y].name,prompt:o[y].prompt||void 0,updatedAt:o[y].updatedAt};ye(Ao,g)}),Sa=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};ye(Ao,o)}),zl=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(ye(Ao,t),await Ot.pathExists(Yn))try{let a=se(Yn,[]);if(Array.isArray(a)){let i=a.filter(p=>Object.keys(p)[0]!==String(e));ye(Yn,i)}}catch{}let o=se(nn,{});o[e]&&(delete o[e],ye(nn,o));let s=se(Nn,{});s[e]&&(delete s[e],ye(Nn,s)),await yt.deleteChatBackups(e);let r=Ms.join(Mo,`${e}.json`);if(await Ot.pathExists(r))try{await Ot.remove(r)}catch{}return n}),Vu=()=>`flow-${ql(6)}`,Xu=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 zl(a),r++)}return r},Kl=e=>{let n=e.replace(/[\[\]]/g,"").trim(),t=new Date(n);if(!isNaN(t.getTime()))return t.getTime();let o=n.split(/,\s*|\s+/);if(o.length===0)return null;let s=o[0],r=o[1]||"",a=o[2]||"",i=s.split(/[-\/.]/).map(Number);if(i.length!==3)return null;let p="en";try{p=Intl.DateTimeFormat().resolvedOptions().locale||"en"}catch{}let d=!/^en[-_]?us$|^en$/.test(p?.toLowerCase()),c,l,f;if(i[0]>1e3)c=i[0],l=i[1],f=i[2];else if(i[2]>1e3)c=i[2],i[0]>12?(f=i[0],l=i[1]):i[1]>12?(f=i[1],l=i[0]):d?(f=i[0],l=i[1]):(l=i[0],f=i[1]);else return null;if(l<1||l>12||f<1||f>31)return null;let u=0,m=0,g=0;if(r){let h=r.split(":").map(Number);u=h[0]||0,m=h[1]||0,g=h[2]||0,a.toLowerCase()==="pm"&&u<12?u+=12:a.toLowerCase()==="am"&&u===12&&(u=0)}let y=new Date(c,l-1,f,u,m,g);return isNaN(y.getTime())?null:y.getTime()},Yl=async e=>{try{if(!await Ot.pathExists(e))return;let n=await Ot.readFile(e,"utf8");if(!n.trim())return;let t=n.split(`
608
608
  `),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=Kl(m[1]);if(g&&i-g>a)continue}}let u=l.header+(l.body.length>0?`
609
609
  `+l.body.join(`
610
610
  `):"");p.push(u)}let c=p.join(`
611
- `).trim();c?await vt.writeFile(e,c+`
612
- `,"utf8"):await vt.writeFile(e,"","utf8")}catch{}},Ju=async e=>{try{if(!await vt.pathExists(e))return;let n=async t=>{let o=await vt.readdir(t);for(let s of o){let r=Ms.join(t,s);(await vt.stat(r)).isDirectory()?(await n(r),(await vt.readdir(r)).length===0&&await vt.remove(r)):s.endsWith(".log")&&await Yl(r)}};await n(e)}catch{}},Ta=(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 Qu=async(e,n,t,o=0)=>vs(async()=>{let s=se(Yn,[]);Array.isArray(s)||(s=[]);let r={total:n,context:t,cached:o},a=s.findIndex(i=>Object.keys(i)[0]===String(e));a!==-1?s[a]={[String(e)]:r}:s.push({[String(e)]:r}),ye(Yn,s)}),Zu=async e=>{try{if(!await vt.pathExists(Yn))return{total:0,context:0,cached:0};let n=se(Yn,[]);if(!Array.isArray(n))return{total:0,context:0,cached:0};let t=n.find(o=>Object.keys(o)[0]===String(e));return t?{total:0,context:0,cached:0,...t[String(e)]}:{total:0,context:0,cached:0}}catch{return{total:0,context:0,cached:0}}};import _a from"puppeteer";import Ca from"fs";import $a from"path";import Ra from"os";import es from"path";import Oo from"fs";import{createRequire as Vl}from"module";import{fileURLToPath as Xl}from"url";var Jl=Vl(import.meta.url),Ea=es.dirname(Xl(import.meta.url));function po(){let e=Ra.platform(),n=Ra.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(Ea,"..","..",".puppeteerrc.cjs");if(Oo.existsSync(r)||(r=es.resolve(Ea,"..",".puppeteerrc.cjs")),!Oo.existsSync(r))return{};try{let a=Jl(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 f=Oo.readdirSync(l),u=[];for(let m of f){let g=es.join(l,m),y;try{y=Oo.statSync(g)}catch{continue}if(y.isDirectory())u.push(g);else if(m.toLowerCase()===o.toLowerCase()&&(!p||g.includes(p)))return g}if(p){for(let m of u)if(m.includes(p)){let g=d(m);if(g)return g}}for(let m of u)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 vr=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}
611
+ `).trim();c?await Ot.writeFile(e,c+`
612
+ `,"utf8"):await Ot.writeFile(e,"","utf8")}catch{}},Ju=async e=>{try{if(!await Ot.pathExists(e))return;let n=async t=>{let o=await Ot.readdir(t);for(let s of o){let r=Ms.join(t,s);(await Ot.stat(r)).isDirectory()?(await n(r),(await Ot.readdir(r)).length===0&&await Ot.remove(r)):s.endsWith(".log")&&await Yl(r)}};await n(e)}catch{}},Ta=(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 Qu=async(e,n,t,o=0)=>vs(async()=>{let s=se(Yn,[]);Array.isArray(s)||(s=[]);let r={total:n,context:t,cached:o},a=s.findIndex(i=>Object.keys(i)[0]===String(e));a!==-1?s[a]={[String(e)]:r}:s.push({[String(e)]:r}),ye(Yn,s)}),Zu=async e=>{try{if(!await Ot.pathExists(Yn))return{total:0,context:0,cached:0};let n=se(Yn,[]);if(!Array.isArray(n))return{total:0,context:0,cached:0};let t=n.find(o=>Object.keys(o)[0]===String(e));return t?{total:0,context:0,cached:0,...t[String(e)]}:{total:0,context:0,cached:0}}catch{return{total:0,context:0,cached:0}}};import _a from"puppeteer";import Ca from"fs";import $a from"path";import Ra from"os";import es from"path";import Oo from"fs";import{createRequire as Vl}from"module";import{fileURLToPath as Xl}from"url";var Jl=Vl(import.meta.url),Ea=es.dirname(Xl(import.meta.url));function po(){let e=Ra.platform(),n=Ra.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(Ea,"..","..",".puppeteerrc.cjs");if(Oo.existsSync(r)||(r=es.resolve(Ea,"..",".puppeteerrc.cjs")),!Oo.existsSync(r))return{};try{let a=Jl(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 f=Oo.readdirSync(l),u=[];for(let m of f){let g=es.join(l,m),y;try{y=Oo.statSync(g)}catch{continue}if(y.isDirectory())u.push(g);else if(m.toLowerCase()===o.toLowerCase()&&(!p||g.includes(p)))return g}if(p){for(let m of u)if(m.includes(p)){let g=d(m);if(g)return g}}for(let m of u)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 vr=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}
613
613
 
614
614
  RESPONSE RULES:
615
615
  - ANSWER CONCISELY WITH REQUIRED DETAILS UNDER 300 WORDS.
@@ -636,7 +636,7 @@ Sources:
636
636
 
637
637
  `+S:"");if(!_||/^(\+\d+|Searching|Answering|Thinking|Finished)$/i.test(_))throw new Error("EMPTY_AI_RESPONSE");return await p.close(),`AI Search results for [${n}]:
638
638
 
639
- ${_}`}catch(d){if(r=d,Ca.writeFileSync($a.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 _a.launch({headless:!0,executablePath:p.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let d=await i.newPage();await d.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.178 Safari/537.36"),await d.setViewport({width:1366,height:768});let c=a===1?Math.random()*1e3+500:Math.random()*2e3+1e3;await new Promise(g=>setTimeout(g,c));let l=`https://html.duckduckgo.com/html/?q=${encodeURIComponent(n)}`;await d.goto(l,{waitUntil:"networkidle2",timeout:18e4});let f=await d.$$eval(".result",(g,y)=>g.slice(0,y).map((h,b)=>{let w=h.querySelector(".result__a"),T=h.querySelector(".result__snippet"),$=w?w.href:"";$.includes("uddg=")&&($=decodeURIComponent($.split("uddg=")[1].split("&")[0]));let R=w?w.innerText.trim():"No Title",k=T?T.innerText.trim():"No Snippet";return`${b+1}. ${R}
639
+ ${_}`}catch(d){if(r=d,Ca.writeFileSync($a.join(yn,"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 _a.launch({headless:!0,executablePath:p.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let d=await i.newPage();await d.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.178 Safari/537.36"),await d.setViewport({width:1366,height:768});let c=a===1?Math.random()*1e3+500:Math.random()*2e3+1e3;await new Promise(g=>setTimeout(g,c));let l=`https://html.duckduckgo.com/html/?q=${encodeURIComponent(n)}`;await d.goto(l,{waitUntil:"networkidle2",timeout:18e4});let f=await d.$$eval(".result",(g,y)=>g.slice(0,y).map((h,b)=>{let w=h.querySelector(".result__a"),T=h.querySelector(".result__snippet"),$=w?w.href:"";$.includes("uddg=")&&($=decodeURIComponent($.split("uddg=")[1].split("&")[0]));let R=w?w.innerText.trim():"No Title",k=T?T.innerText.trim():"No Snippet";return`${b+1}. ${R}
640
640
  Source: ${$}
641
641
  Snippet: ${k}`}),t);if(f.length===0){if((await d.evaluate(()=>document.body.innerText)).includes("anomaly"))throw new Error("ANOMALY_DETECTED");return await i.close(),`No results found for query: [${n}].`}let u=f.join(`
642
642
 
@@ -644,7 +644,7 @@ Snippet: ${k}`}),t);if(f.length===0){if((await d.evaluate(()=>document.body.inne
644
644
 
645
645
  `:""}Search results for [${n}]:
646
646
 
647
- ${u}`}catch(p){if(r=p,i&&await i.close(),Ca.writeFileSync($a.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 Ql from"puppeteer";import Zl from"turndown";import{gfm as ec}from"turndown-plugin-gfm";var Ir=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 Ql.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 k=$[R].name;k!=="href"&&k!=="src"&&T.removeAttribute(k)}});document.querySelector("div, span");)document.querySelectorAll("div, span").forEach(T=>{T.parentNode&&T.replaceWith(...T.childNodes)});document.querySelectorAll("br").forEach(T=>{T.replaceWith(document.createTextNode(`
647
+ ${u}`}catch(p){if(r=p,i&&await i.close(),Ca.writeFileSync($a.join(yn,"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 Ql from"puppeteer";import Zl from"turndown";import{gfm as ec}from"turndown-plugin-gfm";var Ir=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 Ql.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 k=$[R].name;k!=="href"&&k!=="src"&&T.removeAttribute(k)}});document.querySelector("div, span");)document.querySelectorAll("div, span").forEach(T=>{T.parentNode&&T.replaceWith(...T.childNodes)});document.querySelectorAll("br").forEach(T=>{T.replaceWith(document.createTextNode(`
648
648
 
649
649
  `))});let w=()=>{let T=!1;document.querySelectorAll("*").forEach($=>{$.childNodes.length===0&&!$.innerText.trim()&&($.remove(),T=!0)}),T&&w()};return w(),document.body.innerHTML});if(!c)throw new Error("EMPTY_RENDER_RESULT");let l=c.replace(/<br\s*\/?>/gi,`
650
650
 
@@ -659,15 +659,15 @@ ${u}`}catch(p){if(r=p,i&&await i.close(),Ca.writeFileSync($a.join(hn,"web_tools"
659
659
 
660
660
  ${m}${u.length>5e4?`
661
661
 
662
- [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 tc=4*(1024*2),Or=async(e,n={})=>{let t=c=>{let l=new RegExp(`${c}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),f=e.match(l);if(f)return f[2].trim();let u=new RegExp(`${c}\\s*[:=]\\s*([^,\\s)]+)`,"s"),m=e.match(u);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=se(en,{});c[d]||(c[d]=[]),c[d].push(r),ye(en,c);let l=c[d].reduce((f,u)=>f+u.length,0);return`SUCCESS: Temporary context saved for session [${d}]. (Size: ${l} chars)`}if(o==="user"){let c=se(Ft,[]).map(l=>(l.score===void 0&&(l.score=.5),l));if(s==="add"){if(!r)return"ERROR: Missing 'content' for memory addition.";let l=new Date,f=`${l.getDate()}/${l.getMonth()+1}/${l.getFullYear()}`,u=r.includes("[Saved on:")?r:`${r.trim()} [Saved on: ${f}]`,m=tc,g=c.reduce((w,T)=>w+(T.memory?.length||0),0);for(;c.length>0&&g+u.length>m;){let w=c.shift();g-=w.memory?.length||0}let y=t("score"),h=y?parseFloat(y):.5,b={id:`mem-${Date.now().toString(36)}`,memory:u,score:Math.min(2,isNaN(h)?.5:h)};return c.push(b),ye(Ft,c),`SUCCESS: Memory added with ID [${b.id}] and score [${b.score}]. (Vault Size: ${g+u.length} chars)`}if(s==="update"){let l=p||i,f=a||r;if(!l||!f)return"ERROR: Missing 'id' or content for update.";let u=c.findIndex(h=>h.id===l);if(u===-1)return`ERROR: Memory ID [${l}] not found.`;let m=new Date,g=`${m.getDate()}/${m.getMonth()+1}/${m.getFullYear()}`,y=f.includes("[Saved on:")?f:`${f.trim()} [Saved on: ${g}]`;return c[u].memory=y,ye(Ft,c),`SUCCESS: Memory [${l}] updated.`}if(s==="delete"){let l=p||r;if(!l)return"ERROR: Missing 'id' for deletion.";let f=c.length,u=c.filter(m=>m.id!==l);return u.length===f?`ERROR: Memory ID [${l}] not found.`:(ye(Ft,u),`SUCCESS: Memory [${l}] deleted.`)}return`ERROR: Invalid method [${s}] for user memory. Use 'add', 'update', or 'delete'.`}return`ERROR: Unknown action [${o}] for memory tool.`};var Lr=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 Sa(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 nc=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},oc=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},sc=e=>e.replace(/^(\s*---\r?\n)([\s\S]*?)(\r?\n---)/,(n,t,o,s)=>{let r=o.split(`
662
+ [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 tc=4*(1024*2),Or=async(e,n={})=>{let t=c=>{let l=new RegExp(`${c}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),f=e.match(l);if(f)return f[2].trim();let u=new RegExp(`${c}\\s*[:=]\\s*([^,\\s)]+)`,"s"),m=e.match(u);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=se(nn,{});c[d]||(c[d]=[]),c[d].push(r),ye(nn,c);let l=c[d].reduce((f,u)=>f+u.length,0);return`SUCCESS: Temporary context saved for session [${d}]. (Size: ${l} chars)`}if(o==="user"){let c=se(Ut,[]).map(l=>(l.score===void 0&&(l.score=.5),l));if(s==="add"){if(!r)return"ERROR: Missing 'content' for memory addition.";let l=new Date,f=`${l.getDate()}/${l.getMonth()+1}/${l.getFullYear()}`,u=r.includes("[Saved on:")?r:`${r.trim()} [Saved on: ${f}]`,m=tc,g=c.reduce((w,T)=>w+(T.memory?.length||0),0);for(;c.length>0&&g+u.length>m;){let w=c.shift();g-=w.memory?.length||0}let y=t("score"),h=y?parseFloat(y):.5,b={id:`mem-${Date.now().toString(36)}`,memory:u,score:Math.min(2,isNaN(h)?.5:h)};return c.push(b),ye(Ut,c),`SUCCESS: Memory added with ID [${b.id}] and score [${b.score}]. (Vault Size: ${g+u.length} chars)`}if(s==="update"){let l=p||i,f=a||r;if(!l||!f)return"ERROR: Missing 'id' or content for update.";let u=c.findIndex(h=>h.id===l);if(u===-1)return`ERROR: Memory ID [${l}] not found.`;let m=new Date,g=`${m.getDate()}/${m.getMonth()+1}/${m.getFullYear()}`,y=f.includes("[Saved on:")?f:`${f.trim()} [Saved on: ${g}]`;return c[u].memory=y,ye(Ut,c),`SUCCESS: Memory [${l}] updated.`}if(s==="delete"){let l=p||r;if(!l)return"ERROR: Missing 'id' for deletion.";let f=c.length,u=c.filter(m=>m.id!==l);return u.length===f?`ERROR: Memory ID [${l}] not found.`:(ye(Ut,u),`SUCCESS: Memory [${l}] deleted.`)}return`ERROR: Invalid method [${s}] for user memory. Use 'add', 'update', or 'delete'.`}return`ERROR: Unknown action [${o}] for memory tool.`};var Lr=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 Sa(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 fn from"fs";import Mn from"path";var nc=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},oc=e=>{let n=[];if(!e||!fn.existsSync(e))return n;let t=(o,s=0)=>{if(!(s>5))try{let r=fn.readdirSync(o,{withFileTypes:!0});for(let a of r){let i=Mn.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},sc=e=>e.replace(/^(\s*---\r?\n)([\s\S]*?)(\r?\n---)/,(n,t,o,s)=>{let r=o.split(`
663
663
  `),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(`
664
- `)}${s}`}),rc=(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}=D(e),d=parseInt(o||r||i),c=parseInt(s||a||p),l=!isNaN(d),f=!isNaN(c),u=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),b=h[0]?.toLowerCase();if(b!=="global"&&b!=="project")return`ERROR: Invalid skill scope '${b||""}'. Expected 'global' or 'project'.`;let w=h[1];if(!w)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=b==="global"?_t:process.cwd(),k=oc(R),S=null;for(let C of k)try{let M=dn.readFileSync(C,"utf8"),v=nc(M),L=$n.basename($n.dirname(C)).toLowerCase();if(v?.name&&v.name.toLowerCase()===w.toLowerCase()||L===w.toLowerCase()||C.toLowerCase()===$n.join(R,"skill.md").toLowerCase()&&w.toLowerCase()==="skill"){S=C;break}}catch{}if(!S)return`No '${w}' exist in given scope.`;let _=$n.dirname(S),E=S,x=!0;if(T){if(!$)return`ERROR: Missing reference file name in path [${t}].`;let C=rc(_,$);if(!C)return`No such reference exist for skill '${w}'`;E=C,x=!1}try{let C=dn.readFileSync(E,"utf8");C.startsWith("\uFEFF")&&(C=C.slice(1)),C=C.replace(/\r\n/g,`
664
+ `)}${s}`}),rc=(e,n)=>{let t=[Mn.join(e,"references"),Mn.join(e,"reference"),e],o=n.toLowerCase().endsWith(".md")?n.toLowerCase():`${n.toLowerCase()}.md`,s=n.toLowerCase();for(let r of t)if(fn.existsSync(r)&&fn.statSync(r).isDirectory())try{let a=fn.readdirSync(r);for(let i of a){let p=i.toLowerCase();if(p===o||p===s){let d=Mn.join(r,i);if(fn.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}=D(e),d=parseInt(o||r||i),c=parseInt(s||a||p),l=!isNaN(d),f=!isNaN(c),u=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),b=h[0]?.toLowerCase();if(b!=="global"&&b!=="project")return`ERROR: Invalid skill scope '${b||""}'. Expected 'global' or 'project'.`;let w=h[1];if(!w)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=b==="global"?Ct:process.cwd(),k=oc(R),S=null;for(let C of k)try{let M=fn.readFileSync(C,"utf8"),v=nc(M),L=Mn.basename(Mn.dirname(C)).toLowerCase();if(v?.name&&v.name.toLowerCase()===w.toLowerCase()||L===w.toLowerCase()||C.toLowerCase()===Mn.join(R,"skill.md").toLowerCase()&&w.toLowerCase()==="skill"){S=C;break}}catch{}if(!S)return`No '${w}' exist in given scope.`;let _=Mn.dirname(S),E=S,x=!0;if(T){if(!$)return`ERROR: Missing reference file name in path [${t}].`;let C=rc(_,$);if(!C)return`No such reference exist for skill '${w}'`;E=C,x=!1}try{let C=fn.readFileSync(E,"utf8");C.startsWith("\uFEFF")&&(C=C.slice(1)),C=C.replace(/\r\n/g,`
665
665
  `).replace(/\r/g,`
666
666
  `),x&&(C=sc(C));let M=C.split(`
667
667
  `),v=M.length,L=l?Math.max(0,u-1):0,U=f?Math.min(v,m):v,j=M.slice(L,U),ee=t.replace(/\\/g,"/").toLowerCase(),F=`${ee.includes("#skill/global/fluxflow")||ee.includes("#skills/global/fluxflow")?"DOCs":"Skill"}: [${t.replace(/\\/g,"/")}]`,W=j.map(ne=>ne.trimEnd()).join(`
668
668
  `);return`${F}
669
669
 
670
- ${W}`}catch(C){let M=C instanceof Error?C.message:String(C);return`ERROR: Failed to read skill file [${t}]: ${M}`}}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 w={".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(w[h]){if(!(n.isMultiModal!==!1))return`ERROR: Multimodality is not supported for the current model. Unable to load [${t}].`;let v=dn.readFileSync(g).toString("base64"),L=w[h];return{text:`[BINARY FILE]: ${t} (${L}) - Loaded as multimodal part.`,binaryPart:{inlineData:{data:v,mimeType:L}}}}let T=dn.readFileSync(g,"utf8");T.startsWith("\uFEFF")&&(T=T.slice(1)),T=T.replace(/\r\n/g,`
670
+ ${W}`}catch(C){let M=C instanceof Error?C.message:String(C);return`ERROR: Failed to read skill file [${t}]: ${M}`}}try{let g=Mn.resolve(process.cwd(),t);if(!fn.existsSync(g))return`ERROR: File [${t}] does not exist.`;if(fn.statSync(g).isDirectory())return`ERROR: Path [${t}] is a directory. Use list_files instead.`;let h=Mn.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 w={".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(w[h]){if(!(n.isMultiModal!==!1))return`ERROR: Multimodality is not supported for the current model. Unable to load [${t}].`;let v=fn.readFileSync(g).toString("base64"),L=w[h];return{text:`[BINARY FILE]: ${t} (${L}) - Loaded as multimodal part.`,binaryPart:{inlineData:{data:v,mimeType:L}}}}let T=fn.readFileSync(g,"utf8");T.startsWith("\uFEFF")&&(T=T.slice(1)),T=T.replace(/\r\n/g,`
671
671
  `).replace(/\r/g,`
672
672
  `);let $=T.split(`
673
673
  `),R=$.length;!l&&!f&&R>800&&(u=1,m=50);let k=Math.max(0,u-1),S=Math.min(R,m),_=$.slice(k,S),E=`File: [${t}] (Showing lines ${k+1}-${S} of ${R}).`,x=_.map((C,M)=>`${String(k+M+1).padStart(4)}: ${C.trimEnd()}`).join(`
@@ -675,7 +675,7 @@ ${W}`}catch(C){let M=C instanceof Error?C.message:String(C);return`ERROR: Failed
675
675
 
676
676
  ${x}`}catch(g){let y=g instanceof Error?g.message:String(g);return`ERROR: Failed to read file [${t}]: ${y}`}};import Lo from"fs";import Aa from"path";var Dr=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,`
677
677
  `).replace(/\r/g,`
678
- `);let s=Aa.resolve(process.cwd(),t),r=Aa.dirname(s);try{await gt.recordFileChange(s);let a="";if(Lo.existsSync(s))try{a=`Old File contents:
678
+ `);let s=Aa.resolve(process.cwd(),t),r=Aa.dirname(s);try{await yt.recordFileChange(s);let a="";if(Lo.existsSync(s))try{a=`Old File contents:
679
679
  ${Lo.readFileSync(s,"utf8").split(/\r?\n/).map(($,R)=>`${R+1} | ${$}`).join(`
680
680
  `)}
681
681
 
@@ -692,7 +692,7 @@ ${Lo.readFileSync(s,"utf8").split(/\r?\n/).map(($,R)=>`${R+1} | ${$}`).join(`
692
692
 
693
693
  ... [${g-100} lines truncated] ...
694
694
 
695
- ${T}`}f=null;let{systemSettings:h}=await tn(),b=`SUCCESS: File [${t}] saved.
695
+ ${T}`}f=null;let{systemSettings:h}=await on(),b=`SUCCESS: File [${t}] saved.
696
696
  - Stats: [${g} lines, ${(u/1024).toFixed(1)} KB]
697
697
  ${a}- Content Preview:
698
698
 
@@ -701,9 +701,9 @@ ${y}`;if(h?.compressToolResults&&g>60){let w=d.split(/\r?\n/),T=w.slice(0,25).jo
701
701
  `),$=w.slice(-25).join(`
702
702
  `)===m.slice(-25).join(`
703
703
  `);T&&$&&(b=`[[SAME]]
704
- ${b}`)}return b}catch(a){let i=a instanceof Error?a.message:String(a);return`ERROR: Failed to write file [${t}]: ${i}`}};import Nr from"fs";import gc from"path";import ic from"os";var wn=e=>typeof e!="string"?e:e.length>12?(e+"").replace("",""):e,Ma=(e,n)=>{if(!e)return"";let t=/\x1B\[[0-?]*[ -/]*[@-~]/g,o=e.split(`
705
- `),s=[];if(n<=5)return e;let r=a=>a.replace(t,"").length;return o.forEach(a=>{if(r(a)<=n){s.push(a);return}let p=a.split(/(\s+)/),d="",c=0,l=a.match(/^(\s*)/),f=l?l[1]:"";p.forEach((u,m)=>{if(u.length===0)return;let g=r(u);if(c+g>n)if(d.trim().length>0)s.push(d.trimEnd()),d=f.substring(0,Math.min(f.length,8))+u,c=r(d);else if(t.test(u))s.push(u),d=f,c=r(d);else{let y=u;for(;r(y)>n&&n>10;)s.push(y.substring(0,n)),y=y.substring(n);d=y,c=r(d)}else d+=u,c+=g}),(d.trimEnd().length>0||d===f)&&s.push(d.trimEnd())}),wn(s.join(`
706
- `))},Wf=e=>{if(!e&&e!==0)return"0.0k";let n=typeof e=="string"?parseFloat(e):e;return n>=1e6?`${(n/1e6).toFixed(1)}m`:n>=1e3?`${(n/1e3).toFixed(1)}k`:n.toString()},jf=(e,n=40)=>{let t=Dn.replaceAll("\\\\","\\");if(e=e.replace(ic.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,f;for(let u of d){let m=p===1?[`${u}1`,u,`${u}_1`]:[`${u}${p}`,`${u}_${p}`];for(let g of m)if(e[g]!==void 0){l=e[g];break}if(l!==void 0)break}for(let u of c){let m=p===1?[`${u}1`,u,`${u}_1`]:[`${u}${p}`,`${u}_${p}`];for(let g of m)if(e[g]!==void 0){f=e[g];break}if(f!==void 0)break}return{r:l,n:f}};for(let p of s){let{r:d,n:c}=i(p,r,a);if(d!==void 0&&c!==void 0)n.push({replace:d,new:c});else if(d!==void 0||c!==void 0)return{error:`Mismatched replacement pair for index ${p}. Both replacement and new content must be provided.`,allowMultiple:o}}return{patchPairs:n,allowMultiple:o}},ac=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===`
704
+ ${b}`)}return b}catch(a){let i=a instanceof Error?a.message:String(a);return`ERROR: Failed to write file [${t}]: ${i}`}};import Nr from"fs";import gc from"path";import ic from"os";var bn=e=>typeof e!="string"?e:e.length>12?(e+"").replace("",""):e,Ma=(e,n)=>{if(!e)return"";let t=/\x1B\[[0-?]*[ -/]*[@-~]/g,o=e.split(`
705
+ `),s=[];if(n<=5)return e;let r=a=>a.replace(t,"").length;return o.forEach(a=>{if(r(a)<=n){s.push(a);return}let p=a.split(/(\s+)/),d="",c=0,l=a.match(/^(\s*)/),f=l?l[1]:"";p.forEach((u,m)=>{if(u.length===0)return;let g=r(u);if(c+g>n)if(d.trim().length>0)s.push(d.trimEnd()),d=f.substring(0,Math.min(f.length,8))+u,c=r(d);else if(t.test(u))s.push(u),d=f,c=r(d);else{let y=u;for(;r(y)>n&&n>10;)s.push(y.substring(0,n)),y=y.substring(n);d=y,c=r(d)}else d+=u,c+=g}),(d.trimEnd().length>0||d===f)&&s.push(d.trimEnd())}),bn(s.join(`
706
+ `))},Wf=e=>{if(!e&&e!==0)return"0.0k";let n=typeof e=="string"?parseFloat(e):e;return n>=1e6?`${(n/1e6).toFixed(1)}m`:n>=1e3?`${(n/1e3).toFixed(1)}k`:n.toString()},jf=(e,n=40)=>{let t=Fn.replaceAll("\\\\","\\");if(e=e.replace(ic.homedir(),"~").replace(t,"FluxFlow").replaceAll("\\","/"),!e||e.length<=n)return bn(e);let o=Math.floor((n-3)/2);return bn(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,f;for(let u of d){let m=p===1?[`${u}1`,u,`${u}_1`]:[`${u}${p}`,`${u}_${p}`];for(let g of m)if(e[g]!==void 0){l=e[g];break}if(l!==void 0)break}for(let u of c){let m=p===1?[`${u}1`,u,`${u}_1`]:[`${u}${p}`,`${u}_${p}`];for(let g of m)if(e[g]!==void 0){f=e[g];break}if(f!==void 0)break}return{r:l,n:f}};for(let p of s){let{r:d,n:c}=i(p,r,a);if(d!==void 0&&c!==void 0)n.push({replace:d,new:c});else if(d!==void 0||c!==void 0)return{error:`Mismatched replacement pair for index ${p}. Both replacement and new content must be provided.`,allowMultiple:o}}return{patchPairs:n,allowMultiple:o}},ac=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===`
707
707
  `)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]!==`
708
708
  `&&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,`
709
709
  `).replace(/\r/g,`
@@ -739,7 +739,7 @@ ${b}`)}return b}catch(a){let i=a instanceof Error?a.message:String(a);return`ERR
739
739
  `,w=y.split(h).map(T=>T.split(`
740
740
  `).filter(R=>R.trim()!=="").length>45?`[[VERIFIED]]
741
741
  ${T}
742
- [[/VERIFIED]]`:T);c=g+w.join(h)}return c+="[DIFF_END]",wn(c)},lc=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}},cc=(e,n)=>{if(!e&&!n)return 1;if(!e||!n)return 0;let t=e.length,o=n.length,s=e,r=n;t<o&&(s=n,r=e);let a=s.length,i=r.length,p=new Int32Array(i+1),d=new Int32Array(i+1);for(let f=0;f<=i;f++)p[f]=f;for(let f=1;f<=a;f++){d[0]=f;let u=s[f-1];for(let m=1;m<=i;m++)u===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},va=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]=cc(n[c].content.trim(),t[l].content.trim());for(let c=1;c<=o;c++)for(let l=1;l<=s;l++){let f=i[c-1][l-1],u=f>=.2?f:-10,m=r[c-1][l-1]+u,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,f=t[d-1].index;e[l].pairContent=e[f].parsed.content,e[f].pairContent=e[l].parsed.content}p--,d--}else a[p][d]==="up"?p--:d--},Jn=new Map,mo=new Map,Ia=200,Pr=6,Fr=(e,n)=>{n.set(e.key,e),e.type==="chunk"&&e.blocks&&e.blocks.forEach(t=>Fr(t,n))},Gf=(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(hc(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 b=r.get(m);if(b&&b.text===y&&b.type===g&&!!b.isActiveBlock==!!h.isActiveBlock&&!!b.isStreaming==!!h.isStreaming&&b.pairContent===h.pairContent)return b;let w=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:w,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(`
742
+ [[/VERIFIED]]`:T);c=g+w.join(h)}return c+="[DIFF_END]",bn(c)},lc=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?bn(s.substring(0,r).trim()):"",i=bn(r!==-1?s.substring(r+1):s);return{isR:t,isA:o,num:a,content:i}},cc=(e,n)=>{if(!e&&!n)return 1;if(!e||!n)return 0;let t=e.length,o=n.length,s=e,r=n;t<o&&(s=n,r=e);let a=s.length,i=r.length,p=new Int32Array(i+1),d=new Int32Array(i+1);for(let f=0;f<=i;f++)p[f]=f;for(let f=1;f<=a;f++){d[0]=f;let u=s[f-1];for(let m=1;m<=i;m++)u===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},va=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]=cc(n[c].content.trim(),t[l].content.trim());for(let c=1;c<=o;c++)for(let l=1;l<=s;l++){let f=i[c-1][l-1],u=f>=.2?f:-10,m=r[c-1][l-1]+u,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,f=t[d-1].index;e[l].pairContent=e[f].parsed.content,e[f].pairContent=e[l].parsed.content}p--,d--}else a[p][d]==="up"?p--:d--},Jn=new Map,mo=new Map,Ia=200,Pr=6,Fr=(e,n)=>{n.set(e.key,e),e.type==="chunk"&&e.blocks&&e.blocks.forEach(t=>Fr(t,n))},Gf=(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=bn(hc(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 b=r.get(m);if(b&&b.text===y&&b.type===g&&!!b.isActiveBlock==!!h.isActiveBlock&&!!b.isStreaming==!!h.isStreaming&&b.pairContent===h.pairContent)return b;let w=bn(y),T={...h};return typeof T.pairContent=="string"&&(T.pairContent=bn(T.pairContent)),Array.isArray(T.wrappedLines)&&(T.wrappedLines=T.wrappedLines.map(bn)),{key:m,isStreamingMsg:!!e.isStreaming,workedDuration:e.workedDuration,type:g,text:w,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(`
743
743
  `).map(x=>x.replace(/\r$/,"")),$=String(T.length).length,R=[],k=null,S=[],_=()=>{if(!S.length)return;let x=S;S=[],R.push(x.length===1?x[0]:{key:`${x[0].key}-chunk`,type:"chunk",blocks:x})},E=n-($+6);return T.forEach((x,C)=>{let M=C===T.length-1,v=Ma(x,E).split(`
744
744
  `),L=a(`${e.id||Date.now()}-write-line-${C}`,"write-line",x,{gutterWidth:$,lineNum:C+1,isFirstLine:C===0,isLastLine:M,extension:m,wrappedLines:v});M&&e.isStreaming?(_(),k=L):(S.push(L),S.length>=Pr&&_())}),_(),{completed:R,active:k?[k]:[]}}if(o.includes("[DIFF_START]")){let m=o.match(/\[DIFF_START\]([\s\S]*?)(?:\[DIFF_END\]|$)/),y=(m?m[1].trim():"").split(`
745
745
  `).map(k=>k.replace(/\r$/,"")),h=y.map(k=>({line:k,parsed:lc(k),pairContent:null})),b=[];for(let k=0;k<h.length;k++){let S=h[k];S.parsed&&(S.parsed.isR||S.parsed.isA)?b.push(S):b.length>0&&(va(b),b=[])}b.length>0&&va(b);let w=[],T=null,$=[],R=()=>{if(!$.length)return;let k=$;$=[],w.push(k.length===1?k[0]:{key:`${k[0].key}-chunk`,type:"chunk",blocks:k})};return y.forEach((k,S)=>{let _=S===y.length-1,E=h[S].parsed,x=null;E&&(x=Ma(E.content,n-17).split(`
@@ -752,7 +752,7 @@ ${T}
752
752
  `).replace(/\r/g,`
753
753
  `),{content:l,results:f}=Ls(c,s,{allowMultiple:i}),u=f.filter(h=>!h.success),m=f.filter(h=>h.success);if(m.length===0)return`ERROR: Patch Failed to apply to [${o}].
754
754
  ${u.map(h=>` \u2022 ${h.error}`).join(`
755
- `)}`;await gt.recordFileChange(p,c),Nr.writeFileSync(p,l,"utf8");let{systemSettings:g}=await tn(),y=Ds(c,l,f,12,g?.compressToolResults);return u.length>0?`SUCCESS: File [${o}] updated with some blocks failed. [${m.length}/${s.length}] blocks applied.
755
+ `)}`;await yt.recordFileChange(p,c),Nr.writeFileSync(p,l,"utf8");let{systemSettings:g}=await on(),y=Ds(c,l,f,12,g?.compressToolResults);return u.length>0?`SUCCESS: File [${o}] updated with some blocks failed. [${m.length}/${s.length}] blocks applied.
756
756
 
757
757
  Failures:
758
758
  ${u.map(h=>` \u2022 ${h.error}`).join(`
@@ -774,7 +774,7 @@ ${T}${$}`}let a=0,i=0,p=0,d=500,c=!1,l=(g,y,h=1)=>{if(y>o||c)return[];let b=[];t
774
774
 
775
775
  TRUNCATED: Scan capped at ${d} items. (Directories: ${a}, Files: ${i})`),`Detailed directory tree for [${t}] (recursive depth: ${o}):
776
776
 
777
- ${u}${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 bc from"puppeteer";import Po from"path";import go from"fs-extra";import{PDFDocument as kc}from"pdf-lib";var jr=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=Po.resolve(process.cwd(),n),a=null;try{await go.ensureDir(Po.dirname(r)),await gt.recordFileChange(r);let i=po();a=await bc.launch({headless:!0,executablePath:i.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let p=await a.newPage(),d=t,c={},l=async k=>{if(!k||k.startsWith("http://")||k.startsWith("https://")||k.startsWith("data:"))return null;try{let S=Po.resolve(process.cwd(),k);if(await go.pathExists(S)){let _=Po.extname(S).toLowerCase().replace(".","")||"png",E=_==="jpg"?"jpeg":_==="svg"?"svg+xml":_,x=await go.readFile(S,"base64");return`data:image/${E};base64,${x}`}}catch{}return null},f=/<link[^>]+href=["']([^"']+)["']/gi,u={},m;for(;(m=f.exec(t))!==null;){let k=m[1],S=m[0];if(k&&S.toLowerCase().includes("stylesheet")&&!k.startsWith("http://")&&!k.startsWith("https://")&&!k.startsWith("data:"))try{let _=Po.resolve(process.cwd(),k);if(await go.pathExists(_)){let E=await go.readFile(_,"utf-8");u[S]=`<style>${E}</style>`}}catch{}}for(let[k,S]of Object.entries(u))d=d.split(k).join(S);let g=/<img[^>]+src=["']([^"']+)["']/gi;for(;(m=g.exec(d))!==null;){let k=m[1];if(k&&!c[k]){let S=await l(k);S&&(c[k]=S)}}let y=/url\(\s*['"]?([^'")]+?)['"]?\s*\)/gi;for(;(m=y.exec(d))!==null;){let k=m[1].trim();if(k&&!c[k]){let S=await l(k);S&&(c[k]=S)}}for(let[k,S]of Object.entries(c)){let _=k.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&"),E=new RegExp(`(src=["'])(${_})(["'])`,"gi");d=d.replace(E,`$1${S}$3`);let x=new RegExp(`url\\(\\s*(['"]?)(${_})\\1\\s*\\)`,"gi");d=d.replace(x,`url($1${S}$1)`)}let h=`
777
+ ${u}${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 bc from"puppeteer";import Po from"path";import go from"fs-extra";import{PDFDocument as kc}from"pdf-lib";var jr=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=Po.resolve(process.cwd(),n),a=null;try{await go.ensureDir(Po.dirname(r)),await yt.recordFileChange(r);let i=po();a=await bc.launch({headless:!0,executablePath:i.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let p=await a.newPage(),d=t,c={},l=async k=>{if(!k||k.startsWith("http://")||k.startsWith("https://")||k.startsWith("data:"))return null;try{let S=Po.resolve(process.cwd(),k);if(await go.pathExists(S)){let _=Po.extname(S).toLowerCase().replace(".","")||"png",E=_==="jpg"?"jpeg":_==="svg"?"svg+xml":_,x=await go.readFile(S,"base64");return`data:image/${E};base64,${x}`}}catch{}return null},f=/<link[^>]+href=["']([^"']+)["']/gi,u={},m;for(;(m=f.exec(t))!==null;){let k=m[1],S=m[0];if(k&&S.toLowerCase().includes("stylesheet")&&!k.startsWith("http://")&&!k.startsWith("https://")&&!k.startsWith("data:"))try{let _=Po.resolve(process.cwd(),k);if(await go.pathExists(_)){let E=await go.readFile(_,"utf-8");u[S]=`<style>${E}</style>`}}catch{}}for(let[k,S]of Object.entries(u))d=d.split(k).join(S);let g=/<img[^>]+src=["']([^"']+)["']/gi;for(;(m=g.exec(d))!==null;){let k=m[1];if(k&&!c[k]){let S=await l(k);S&&(c[k]=S)}}let y=/url\(\s*['"]?([^'")]+?)['"]?\s*\)/gi;for(;(m=y.exec(d))!==null;){let k=m[1].trim();if(k&&!c[k]){let S=await l(k);S&&(c[k]=S)}}for(let[k,S]of Object.entries(c)){let _=k.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&"),E=new RegExp(`(src=["'])(${_})(["'])`,"gi");d=d.replace(E,`$1${S}$3`);let x=new RegExp(`url\\(\\s*(['"]?)(${_})\\1\\s*\\)`,"gi");d=d.replace(x,`url($1${S}$1)`)}let h=`
778
778
  <style>
779
779
  @page {
780
780
  margin: ${s};
@@ -804,7 +804,7 @@ ${u}${m}`}catch(s){let r=s instanceof Error?s.message:String(s);return`ERROR: Fa
804
804
  </style>
805
805
  <div class="watermark">Generated by FluxFlow CLI (AI)</div>
806
806
  ${d}
807
- `;await p.setContent(h,{waitUntil:"networkidle0",timeout:18e4});let b=await p.pdf({format:"A4",landscape:String(o).toLowerCase()==="landscape",margin:{top:s,right:s,bottom:s,left:s},printBackground:!0}),w=await kc.load(b),T=Po.basename(n);w.setTitle(`FluxFlow_${T}`),w.setAuthor("FluxFlow CLI"),w.setSubject("Generated with Agentic AI System"),w.setKeywords(["FluxFlow","AI","Agentic","Automated"]),w.setCreator("FluxFlow PDF Engine"),w.setProducer("FluxFlow (Generative AI)");let $=await w.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 Oa from"fs-extra";import Gr from"path";import Sc from"html-to-docx";var Hr=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=Gr.resolve(process.cwd(),n);try{await Oa.ensureDir(Gr.dirname(o)),await gt.recordFileChange(o);let s=Gr.basename(n),r=t.includes("<html")?t:`
807
+ `;await p.setContent(h,{waitUntil:"networkidle0",timeout:18e4});let b=await p.pdf({format:"A4",landscape:String(o).toLowerCase()==="landscape",margin:{top:s,right:s,bottom:s,left:s},printBackground:!0}),w=await kc.load(b),T=Po.basename(n);w.setTitle(`FluxFlow_${T}`),w.setAuthor("FluxFlow CLI"),w.setSubject("Generated with Agentic AI System"),w.setKeywords(["FluxFlow","AI","Agentic","Automated"]),w.setCreator("FluxFlow PDF Engine"),w.setProducer("FluxFlow (Generative AI)");let $=await w.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 Oa from"fs-extra";import Gr from"path";import Sc from"html-to-docx";var Hr=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=Gr.resolve(process.cwd(),n);try{await Oa.ensureDir(Gr.dirname(o)),await yt.recordFileChange(o);let s=Gr.basename(n),r=t.includes("<html")?t:`
808
808
  <!DOCTYPE html>
809
809
  <html lang="en">
810
810
  <head>
@@ -816,38 +816,38 @@ ${u}${m}`}catch(s){let r=s instanceof Error?s.message:String(s);return`ERROR: Fa
816
816
  </body>
817
817
  </html>
818
818
  `,a=await Sc(r,null,{title:`FluxFlow_${s}`,creator:"FluxFlow CLI",description:"Generated by Agentic AI System",table:{row:{cantSplit:!0}},footer:!0,pageNumber:!0});return await Oa.writeFile(o,a),`SUCCESS: Word document [${n}] generated successfully.
819
- - 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 qr from"fast-glob";import{Minimatch as La}from"minimatch";import Tc 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(f=>f.toLowerCase()),c=a.name.toLowerCase();if(!n.some(f=>{let u=f.toLowerCase();return u.startsWith(".")&&c.endsWith(u)?!0:d.some(m=>m===u||m.startsWith(".pnpm"))}))if(a.isDirectory()){let f=await ns(i,n,t,o+1);s=s.concat(f)}else a.isFile()&&s.push({fullPath:i,relativePath:p})}return s}function Rc(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 Ec(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&&Rc(a,p,i)<=i)return!0;return!1})}async function _c(e){let n=xn.join(_t,"skills","fluxflow"),t=xn.join(n,"references");if(!Tc.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 f=xn.join(p,l.name);l.isDirectory()?d=d.concat(await o(f)):l.isFile()&&d.push(f)}}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}":
819
+ - 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 kn from"path";import qr from"fast-glob";import{Minimatch as La}from"minimatch";import Tc 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=kn.join(e,a.name),p=kn.relative(t,i),d=p.split(kn.sep).map(f=>f.toLowerCase()),c=a.name.toLowerCase();if(!n.some(f=>{let u=f.toLowerCase();return u.startsWith(".")&&c.endsWith(u)?!0:d.some(m=>m===u||m.startsWith(".pnpm"))}))if(a.isDirectory()){let f=await ns(i,n,t,o+1);s=s.concat(f)}else a.isFile()&&s.push({fullPath:i,relativePath:p})}return s}function Rc(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 Ec(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&&Rc(a,p,i)<=i)return!0;return!1})}async function _c(e){let n=kn.join(Ct,"skills","fluxflow"),t=kn.join(n,"references");if(!Tc.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 f=kn.join(p,l.name);l.isDirectory()?d=d.concat(await o(f)):l.isFile()&&d.push(f)}}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=kn.relative(n,p).replace(/\\/g,"/");i.push(l)}}catch{}return i.length===0?`No matches found for "${e}" in #docs.`:`DOCs Search "${e}":
820
820
  ${i.map(p=>`- ${p}`).join(`
821
- `)}`}var ss=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 _c(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,f=null;if(p)c||(f=new RegExp(`(?<![\\w])${a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\\w])`,"i"));else{try{l=new RegExp(a,"i")}catch(g){if(d)return`ERROR: Invalid regex pattern "${a}": ${g.message}`}f=new RegExp(`(?<![\\w])${a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\\w])`,"i")}let u=[".git","node_modules",".gemini","dist","build",".next","out",".cache","bin","obj","vendor","venv",".idea",".gradle",".terraform","target","coverage",".vscode",".svn",".hg",".fslckout",".github",".gitlab",".circleci",".gitea",".gitee",".lerna",".changeset",".nx",".npm",".yarn",".pnpm-store",".pnpm",".expo",".nuxt",".svelte-kit",".docusaurus",".turbo",".vercel","bower_components",".netlify",".vuepress",".quasar",".output",".angular","jspm_packages",".parcel-cache",".rollup.cache",".rspack",".vitepress","__pycache__",".pytest_cache",".mypy_cache",".tox",".poetry","env","vhdl",".ipynb_checkpoints",".jupyter",".conda",".pdm-build",".bundle",".yardoc",".metadata","App_Data","ClientBin",".cargo",".rustc_info",".go","Godeps","_vendor",".rake_tasks","CMakefiles",".wakatime",".dart_tool",".fvm",".cocoapods","Pods",".pub-cache",".symlinks","DerivedData",".xcworkspace",".serverless",".aws",".gcloud",".azure",".kube",".vagrant",".docker","postgres-data","redis-data","mongo-data",".Spotlight-V100",".Trashes","$RECYCLE.BIN","System Volume Information",".DocumentRevisions-V100",".fseventsd","AppData","Application Data","Local","LocalLow","Roaming","$WinREAgent","$WINDOWS.~BT","$WINDOWS.~WS","scw","System32","SysWOW64",".AppleDouble",".AppleDB",".AppleDesktop","_CodeSignature",".cmio",".LSOverride",".localized",".TemporaryItems",".Trash",".Trash-0",".Trash-1000",".gvfs",".local",".config",".dbus",".fontconfig",".snap",".var",".lost+found","lost+found",".thumb",".thumbnails","EFI","boot","grub","logs","log",".nyc_output",".sonar",".ruff_cache",".VSCodeCounter",".exe",".dll",".so",".dylib",".png",".jpg",".jpeg",".gif",".ico",".svg",".webp",".mp3",".mp4",".avi",".zip",".tgz",".tar",".gz",".7z",".rar",".pdf",".docx",".xlsx",".pptx",".woff",".woff2",".ttf",".eot",".skills","skills"],m=150;try{let g=[],y=process.cwd(),h=null;if(t){let M=t.split(";").map(U=>U.trim()).filter(Boolean),v=M.some(U=>U.startsWith("!"));if(M.some(U=>qr.isDynamicPattern(U)||/[*?{}[\]()|+]/.test(U))){h="glob";let U=t.replace(/\\/g,"/"),j=M.map(F=>F.replace(/\\/g,"/")),ee=u.map(F=>F.startsWith(".")?`**/*${F}`:`**/${F}/**`);if(v&&!M.some(F=>!F.startsWith("!"))){let F=await ns(y,u,y),W=O=>O.endsWith("/")?O+"**":O,ne=j.filter(O=>O.startsWith("!")).map(O=>W(O.slice(1))),Me=j.filter(O=>!O.startsWith("!")).map(W);g=F.filter(O=>{let B=O.relativePath.replace(/\\/g,"/"),J=Me.length===0||Me.some(We=>{try{return new La(We).match(B)}catch{return!1}}),Q=ne.some(We=>{try{return new La(We).match(B)}catch{return!1}});return J&&!Q})}else{let F=j.some(ne=>/[\(\)\|]|\.\*/.test(ne)),W=[];if(!F)try{W=await qr(j,{cwd:y,ignore:ee,dot:!0,onlyFiles:!0,absolute:!1})}catch{W=[]}if(W.length===0&&(F||qr.isDynamicPattern(U))){let ne=U.match(/^([^\*\?\(\)\|\[\]\s]+)\//),Me=ne&&!/[\*\?\(\)\|\[\]]/.test(ne[1])?xn.resolve(y,ne[1]):y,O=await ns(Me,u,y);try{let B=U.replace(/^\.\//,"");B=B.replace(/\.\*\/(\\.|[^\/])/g,".*$1"),!B.startsWith("^")&&!B.startsWith(".*")&&(B=`.*${B}`);let J=new RegExp(B.endsWith("$")?B:`${B}$`,"i");g=O.filter(Q=>{let We=Q.relativePath.replace(/\\/g,"/");return J.test(We)})}catch{g=[]}}else g=W.map(ne=>({fullPath:xn.resolve(y,ne),relativePath:ne}))}}else{let U=t.replace(/[\/\\]+$/,""),j=xn.resolve(y,U);try{let ee=await os.stat(j);if(ee.isDirectory())h="dir",g=await ns(j,u,y);else if(ee.isFile())h="file",g.push({fullPath:j,relativePath:xn.relative(y,j)});else return`ERROR: Path is neither a file nor a directory: ${t}`}catch{return`ERROR: Path not found: ${t}`}}}else g=await ns(y,u);let b=g.map(async M=>{try{let v=await os.readFile(M.fullPath,"utf-8");if(v.includes("\0"))return[];let L=v.split(/\r?\n/),U=[];for(let ee=0;ee<L.length;ee++)(c?L[ee].toLowerCase().includes(a.toLowerCase())||Ec(L[ee],a):p?f&&f.test(L[ee]):l&&l.test(L[ee])||f&&f.test(L[ee]))&&U.push({line:ee+1,content:L[ee].trim()});return U.length===0?null:{path:M.relativePath.replace(/\\/g,"/"),matches:U}}catch{return[]}}),w=await Promise.all(b),T=[],$=0;for(let M of w){if(!M||!M.matches)continue;if($>=m)break;let v=m-$,L=M.matches.slice(0,v);T.push({path:M.path,matches:L}),$+=L.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 M=h==="file"?` in '${t}'`:h==="dir"||h==="glob"?` in '${t}'`:". Try to specify files",v=h==="dir"?"[DIR]":h==="glob"?"[GLOB]":"";return`${v}${v?" ":""}Found 0 matches of '${a}'${M}${R?` ${R}`:""}`}let k=R?` ${R}`:"",S=`${T.length} file${T.length===1?"":"s"}`,_=`${$} match${$===1?"":"es"}`,E;h==="file"?E=`Found ${_} of '${a}' in '${t}'${k}:`:h==="dir"||h==="glob"?E=`Found ${_} of '${a}' in '${t}' across ${S}${k}:`:E=`Found ${_} of '${a}' across ${S}${k}:`;let x=h==="dir"?"[DIR]":h==="glob"?"[GLOB]":"",C=`${x}${x?" ":""}${E}
821
+ `)}`}var ss=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 _c(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,f=null;if(p)c||(f=new RegExp(`(?<![\\w])${a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\\w])`,"i"));else{try{l=new RegExp(a,"i")}catch(g){if(d)return`ERROR: Invalid regex pattern "${a}": ${g.message}`}f=new RegExp(`(?<![\\w])${a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\\w])`,"i")}let u=[".git","node_modules",".gemini","dist","build",".next","out",".cache","bin","obj","vendor","venv",".idea",".gradle",".terraform","target","coverage",".vscode",".svn",".hg",".fslckout",".github",".gitlab",".circleci",".gitea",".gitee",".lerna",".changeset",".nx",".npm",".yarn",".pnpm-store",".pnpm",".expo",".nuxt",".svelte-kit",".docusaurus",".turbo",".vercel","bower_components",".netlify",".vuepress",".quasar",".output",".angular","jspm_packages",".parcel-cache",".rollup.cache",".rspack",".vitepress","__pycache__",".pytest_cache",".mypy_cache",".tox",".poetry","env","vhdl",".ipynb_checkpoints",".jupyter",".conda",".pdm-build",".bundle",".yardoc",".metadata","App_Data","ClientBin",".cargo",".rustc_info",".go","Godeps","_vendor",".rake_tasks","CMakefiles",".wakatime",".dart_tool",".fvm",".cocoapods","Pods",".pub-cache",".symlinks","DerivedData",".xcworkspace",".serverless",".aws",".gcloud",".azure",".kube",".vagrant",".docker","postgres-data","redis-data","mongo-data",".Spotlight-V100",".Trashes","$RECYCLE.BIN","System Volume Information",".DocumentRevisions-V100",".fseventsd","AppData","Application Data","Local","LocalLow","Roaming","$WinREAgent","$WINDOWS.~BT","$WINDOWS.~WS","scw","System32","SysWOW64",".AppleDouble",".AppleDB",".AppleDesktop","_CodeSignature",".cmio",".LSOverride",".localized",".TemporaryItems",".Trash",".Trash-0",".Trash-1000",".gvfs",".local",".config",".dbus",".fontconfig",".snap",".var",".lost+found","lost+found",".thumb",".thumbnails","EFI","boot","grub","logs","log",".nyc_output",".sonar",".ruff_cache",".VSCodeCounter",".exe",".dll",".so",".dylib",".png",".jpg",".jpeg",".gif",".ico",".svg",".webp",".mp3",".mp4",".avi",".zip",".tgz",".tar",".gz",".7z",".rar",".pdf",".docx",".xlsx",".pptx",".woff",".woff2",".ttf",".eot",".skills","skills"],m=150;try{let g=[],y=process.cwd(),h=null;if(t){let M=t.split(";").map(U=>U.trim()).filter(Boolean),v=M.some(U=>U.startsWith("!"));if(M.some(U=>qr.isDynamicPattern(U)||/[*?{}[\]()|+]/.test(U))){h="glob";let U=t.replace(/\\/g,"/"),j=M.map(F=>F.replace(/\\/g,"/")),ee=u.map(F=>F.startsWith(".")?`**/*${F}`:`**/${F}/**`);if(v&&!M.some(F=>!F.startsWith("!"))){let F=await ns(y,u,y),W=O=>O.endsWith("/")?O+"**":O,ne=j.filter(O=>O.startsWith("!")).map(O=>W(O.slice(1))),Me=j.filter(O=>!O.startsWith("!")).map(W);g=F.filter(O=>{let B=O.relativePath.replace(/\\/g,"/"),J=Me.length===0||Me.some(We=>{try{return new La(We).match(B)}catch{return!1}}),Q=ne.some(We=>{try{return new La(We).match(B)}catch{return!1}});return J&&!Q})}else{let F=j.some(ne=>/[\(\)\|]|\.\*/.test(ne)),W=[];if(!F)try{W=await qr(j,{cwd:y,ignore:ee,dot:!0,onlyFiles:!0,absolute:!1})}catch{W=[]}if(W.length===0&&(F||qr.isDynamicPattern(U))){let ne=U.match(/^([^\*\?\(\)\|\[\]\s]+)\//),Me=ne&&!/[\*\?\(\)\|\[\]]/.test(ne[1])?kn.resolve(y,ne[1]):y,O=await ns(Me,u,y);try{let B=U.replace(/^\.\//,"");B=B.replace(/\.\*\/(\\.|[^\/])/g,".*$1"),!B.startsWith("^")&&!B.startsWith(".*")&&(B=`.*${B}`);let J=new RegExp(B.endsWith("$")?B:`${B}$`,"i");g=O.filter(Q=>{let We=Q.relativePath.replace(/\\/g,"/");return J.test(We)})}catch{g=[]}}else g=W.map(ne=>({fullPath:kn.resolve(y,ne),relativePath:ne}))}}else{let U=t.replace(/[\/\\]+$/,""),j=kn.resolve(y,U);try{let ee=await os.stat(j);if(ee.isDirectory())h="dir",g=await ns(j,u,y);else if(ee.isFile())h="file",g.push({fullPath:j,relativePath:kn.relative(y,j)});else return`ERROR: Path is neither a file nor a directory: ${t}`}catch{return`ERROR: Path not found: ${t}`}}}else g=await ns(y,u);let b=g.map(async M=>{try{let v=await os.readFile(M.fullPath,"utf-8");if(v.includes("\0"))return[];let L=v.split(/\r?\n/),U=[];for(let ee=0;ee<L.length;ee++)(c?L[ee].toLowerCase().includes(a.toLowerCase())||Ec(L[ee],a):p?f&&f.test(L[ee]):l&&l.test(L[ee])||f&&f.test(L[ee]))&&U.push({line:ee+1,content:L[ee].trim()});return U.length===0?null:{path:M.relativePath.replace(/\\/g,"/"),matches:U}}catch{return[]}}),w=await Promise.all(b),T=[],$=0;for(let M of w){if(!M||!M.matches)continue;if($>=m)break;let v=m-$,L=M.matches.slice(0,v);T.push({path:M.path,matches:L}),$+=L.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 M=h==="file"?` in '${t}'`:h==="dir"||h==="glob"?` in '${t}'`:". Try to specify files",v=h==="dir"?"[DIR]":h==="glob"?"[GLOB]":"";return`${v}${v?" ":""}Found 0 matches of '${a}'${M}${R?` ${R}`:""}`}let k=R?` ${R}`:"",S=`${T.length} file${T.length===1?"":"s"}`,_=`${$} match${$===1?"":"es"}`,E;h==="file"?E=`Found ${_} of '${a}' in '${t}'${k}:`:h==="dir"||h==="glob"?E=`Found ${_} of '${a}' in '${t}' across ${S}${k}:`:E=`Found ${_} of '${a}' across ${S}${k}:`;let x=h==="dir"?"[DIR]":h==="glob"?"[GLOB]":"",C=`${x}${x?" ":""}${E}
822
822
 
823
823
  `;for(let M of T){C+=`${M.path}
824
824
  `;for(let v of M.matches)C+=` ${v.line}: ${v.content}
825
825
  `;C+=`
826
- `}return C.trimEnd()}catch(g){return`ERROR: ${g.message}`}};import Da from"fs-extra";import zr from"path";var Cc=(e,n={})=>{try{if(e.length<8||e[0]!==137||e[1]!==80||e[2]!==78||e[3]!==71)return e;let t=[],o=[];for(let a=0;a<256;a++){let i=a;for(let p=0;p<8;p++)i&1?i=3988292384^i>>>1:i=i>>>1;o[a]=i}let s=a=>{let i=4294967295;for(let p=0;p<a.length;p++)i=o[(i^a[p])&255]^i>>>8;return(i^4294967295)>>>0},r=(a,i)=>{let p=Buffer.from(a,"ascii"),d=Buffer.from(i,"utf-8"),c=p.length+1+d.length,l=Buffer.alloc(8+c+4);l.writeUInt32BE(c,0),l.write("tEXt",4,"ascii"),p.copy(l,8),l[8+p.length]=0,d.copy(l,8+p.length+1);let f=s(l.subarray(4,8+c));return l.writeUInt32BE(f,8+c),l};for(let[a,i]of Object.entries(n))i!=null&&t.push(r(a,String(i)));if(t.length===0)return e;if(e.subarray(12,16).toString("ascii")==="IHDR"){let i=e.subarray(0,33),p=e.subarray(33);return Buffer.concat([i,...t,p])}return e}catch{return e}},Kr=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 tn();if(!await Pi(d))return`ERROR: Insufficient Quota for selected quality. Either tell user reduce quality or wait for next refresh cycle (${(await Fi()).nextResetMin||60}m).`;let l=d.imageSettings||{keyType:"Default",quality:"Low-High",apiKey:""},f=l.keyType==="Custom"&&l.apiKey?l.apiKey:FALLBACK_IMAGE_KEY,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 v=r.replace(/\s+/g,"");v==="16:9"?(g=1024,y=576):v==="9:16"?(g=576,y=1024):v==="4:3"?(g=1024,y=768):v==="3:4"?(g=768,y=1024):v==="1:1"&&(g=1024,y=1024)}let h=Math.floor(Math.random()*1e7),w=`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(w,{method:"GET",headers:{Authorization:`Bearer ${f}`}});if(!T.ok){let v=T.status,L="";try{L=await T.text()}catch{}return v===402||L.includes("Insufficient balance")||L.includes("PAYMENT_REQUIRED")?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed with status [${v}]: ${L||"Unknown API Error"}`}if((T.headers.get("content-type")||"").includes("application/json")){let v=await T.json();return v.status===402||v.error&&v.error.code==="PAYMENT_REQUIRED"?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed: ${v.error?.message||JSON.stringify(v)}`}let R=await T.arrayBuffer(),k=Buffer.from(R),S={Title:o,Description:"Generated via FluxFlow CLI",Software:"FluxFlow CLI",Author:"FluxFlow","Creation Time":new Date().toISOString(),Prompt:o,Model:`Fluxflow:${m}`,Ratio:r||"1:1",Seed:String(h)};k=Cc(k,S);let _=zr.resolve(process.cwd(),s);await Da.ensureDir(zr.dirname(_)),await gt.recordFileChange(_),await Da.writeFile(_,k),await Ni(d);let E=zr.extname(s).toLowerCase(),C={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".webp":"image/webp"}[E]||"image/png";return n.isMultiModal!==!1?{text:`SUCCESS: Image successfully generated from prompt [${o}] and saved to [${s}]. Output attached to multimodal part`,binaryPart:{inlineData:{data:k.toString("base64"),mimeType:C}}}:`SUCCESS: Image successfully generated from prompt [${o}] and saved to [${s}].`}catch(d){return`ERROR: Failed during image generation: ${d instanceof Error?d.message:String(d)}`}};var 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=se(en,{}),a=se(Pn,{});return a[o]=s,delete r[o],ye(Pn,a),ye(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=se(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(ye(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 Vr from"fs-extra";import wo from"path";import{createRequire as Mc}from"module";import yo from"fs-extra";import Yr from"path";import $c from"https";var Pa={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 Ac(e,n=null){let t=n||`https://unpkg.com/tree-sitter-wasms@0.1.13/out/${e}`,o=Yr.join(uo,e);return await yo.ensureDir(uo),new Promise((s,r)=>{let a={headers:{"User-Agent":"FluxFlow-Agent"}};$c.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}`}Ac(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 Hp(e){let n=Yr.join(uo,e);return yo.existsSync(n)}async function qp(e){let n=Yr.join(uo,e);yo.existsSync(n)&&await yo.unlink(n)}var Ua=Mc(import.meta.url),Fa=Ua("web-tree-sitter"),Na=!1,Ba=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"]),Wa=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 ja(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(`
827
- `)[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(`
828
- `)[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=ja(o);if(s)return s;if(!Wa.has(o.type))break;o=o.parent}}return null}function vc(e){let n=[];function t(o){for(let s of o.children)Ba.has(s.type)?n.push(s):t(s)}return t(e),n}function Ic(e){return e.replace(/_([a-z])/g,n=>n[1].toUpperCase())}function Ga(e,n=0,t=!0,o="",s=null,r=12){let a=e.type,i=ja(e),p=Ba.has(a)||n===0,d=vc(e),c=p&&n>0&&(Wa.has(a)&&d.length>0||i!==null&&i===s&&d.length>0),l="",f=o,u=n,m=s;if(p&&!c){let g=e.startPosition.row+1,y=e.endPosition.row+1,h=Ic(a),b=i?`${h} [${i}]`:h;n===0?(l+=`\u{1F4C1} ROOT (Lines: ${g}-${y})
826
+ `}return C.trimEnd()}catch(g){return`ERROR: ${g.message}`}};import Da from"fs-extra";import zr from"path";var Cc=(e,n={})=>{try{if(e.length<8||e[0]!==137||e[1]!==80||e[2]!==78||e[3]!==71)return e;let t=[],o=[];for(let a=0;a<256;a++){let i=a;for(let p=0;p<8;p++)i&1?i=3988292384^i>>>1:i=i>>>1;o[a]=i}let s=a=>{let i=4294967295;for(let p=0;p<a.length;p++)i=o[(i^a[p])&255]^i>>>8;return(i^4294967295)>>>0},r=(a,i)=>{let p=Buffer.from(a,"ascii"),d=Buffer.from(i,"utf-8"),c=p.length+1+d.length,l=Buffer.alloc(8+c+4);l.writeUInt32BE(c,0),l.write("tEXt",4,"ascii"),p.copy(l,8),l[8+p.length]=0,d.copy(l,8+p.length+1);let f=s(l.subarray(4,8+c));return l.writeUInt32BE(f,8+c),l};for(let[a,i]of Object.entries(n))i!=null&&t.push(r(a,String(i)));if(t.length===0)return e;if(e.subarray(12,16).toString("ascii")==="IHDR"){let i=e.subarray(0,33),p=e.subarray(33);return Buffer.concat([i,...t,p])}return e}catch{return e}},Kr=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 on();if(!await Pi(d))return`ERROR: Insufficient Quota for selected quality. Either tell user reduce quality or wait for next refresh cycle (${(await Fi()).nextResetMin||60}m).`;let l=d.imageSettings||{keyType:"Default",quality:"Low-High",apiKey:""},f=l.keyType==="Custom"&&l.apiKey?l.apiKey:FALLBACK_IMAGE_KEY,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 v=r.replace(/\s+/g,"");v==="16:9"?(g=1024,y=576):v==="9:16"?(g=576,y=1024):v==="4:3"?(g=1024,y=768):v==="3:4"?(g=768,y=1024):v==="1:1"&&(g=1024,y=1024)}let h=Math.floor(Math.random()*1e7),w=`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(w,{method:"GET",headers:{Authorization:`Bearer ${f}`}});if(!T.ok){let v=T.status,L="";try{L=await T.text()}catch{}return v===402||L.includes("Insufficient balance")||L.includes("PAYMENT_REQUIRED")?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed with status [${v}]: ${L||"Unknown API Error"}`}if((T.headers.get("content-type")||"").includes("application/json")){let v=await T.json();return v.status===402||v.error&&v.error.code==="PAYMENT_REQUIRED"?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed: ${v.error?.message||JSON.stringify(v)}`}let R=await T.arrayBuffer(),k=Buffer.from(R),S={Title:o,Description:"Generated via FluxFlow CLI",Software:"FluxFlow CLI",Author:"FluxFlow","Creation Time":new Date().toISOString(),Prompt:o,Model:`Fluxflow:${m}`,Ratio:r||"1:1",Seed:String(h)};k=Cc(k,S);let _=zr.resolve(process.cwd(),s);await Da.ensureDir(zr.dirname(_)),await yt.recordFileChange(_),await Da.writeFile(_,k),await Ni(d);let E=zr.extname(s).toLowerCase(),C={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".webp":"image/webp"}[E]||"image/png";return n.isMultiModal!==!1?{text:`SUCCESS: Image successfully generated from prompt [${o}] and saved to [${s}]. Output attached to multimodal part`,binaryPart:{inlineData:{data:k.toString("base64"),mimeType:C}}}:`SUCCESS: Image successfully generated from prompt [${o}] and saved to [${s}].`}catch(d){return`ERROR: Failed during image generation: ${d instanceof Error?d.message:String(d)}`}};var 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=se(nn,{}),a=se(Nn,{});return a[o]=s,delete r[o],ye(Nn,a),ye(nn,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=se(Ut,[]),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(ye(Ut,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 Vr from"fs-extra";import wo from"path";import{createRequire as Mc}from"module";import yo from"fs-extra";import Yr from"path";import $c from"https";var Pa={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 Ac(e,n=null){let t=n||`https://unpkg.com/tree-sitter-wasms@0.1.13/out/${e}`,o=Yr.join(uo,e);return await yo.ensureDir(uo),new Promise((s,r)=>{let a={headers:{"User-Agent":"FluxFlow-Agent"}};$c.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}`}Ac(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 Hp(e){let n=Yr.join(uo,e);return yo.existsSync(n)}async function qp(e){let n=Yr.join(uo,e);yo.existsSync(n)&&await yo.unlink(n)}var Ua=Mc(import.meta.url),Fa=Ua("web-tree-sitter"),Na=!1,Ba=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"]),Wa=new Set(["export_statement","lexical_declaration","variable_declaration","variable_declarator","pair","assignment_expression"]);function Sn(e,n=50){if(!e)return"";let t=e.replace(/\s+/g," ").trim();return t.length>n?t.substring(0,n-3)+"...":t}function ja(e){let n=e.type;if(n==="if_statement"){let o=e.childForFieldName("condition");return o?`if (${Sn(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?Sn(o.text,40):""})`}if(n==="for_statement"||n==="for_in_statement"||n==="for_of_statement"){let s=e.text.split(`
827
+ `)[0].match(/for\s*(?:await\s*)?\((.*)\)/);return s?`for (${Sn(s[1],40)})`:"for"}if(n==="switch_statement"){let o=e.childForFieldName("value");return`switch (${o?Sn(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?`<${Sn(s.text,30)}>`:null}if(["import_declaration","import_from_statement","import_statement","preproc_include"].includes(n))return Sn(e.text.split(`
828
+ `)[0],60);if(n==="pair"){let o=e.childForFieldName("key");return o?Sn(o.text.replace(/["']/g,""),40):null}if(n==="assignment_expression"){let o=e.childForFieldName("left");return o?`${Sn(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?Sn(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 Sn(o.text,40)}return Sn(t.text,40)}if(["arrow_function","function_expression","function_declaration"].includes(n)){let o=e.parent;for(;o&&o.type!=="program";){let s=ja(o);if(s)return s;if(!Wa.has(o.type))break;o=o.parent}}return null}function vc(e){let n=[];function t(o){for(let s of o.children)Ba.has(s.type)?n.push(s):t(s)}return t(e),n}function Ic(e){return e.replace(/_([a-z])/g,n=>n[1].toUpperCase())}function Ga(e,n=0,t=!0,o="",s=null,r=12){let a=e.type,i=ja(e),p=Ba.has(a)||n===0,d=vc(e),c=p&&n>0&&(Wa.has(a)&&d.length>0||i!==null&&i===s&&d.length>0),l="",f=o,u=n,m=s;if(p&&!c){let g=e.startPosition.row+1,y=e.endPosition.row+1,h=Ic(a),b=i?`${h} [${i}]`:h;n===0?(l+=`\u{1F4C1} ROOT (Lines: ${g}-${y})
829
829
  `,f=o):(l+=`${o}${t?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 "}${b} (Lines: ${g}-${y})
830
830
  `,f+=t?" ":"\u2502 "),u=n+1,m=i}return u>r&&d.length>0?l+=`${f}\u2514\u2500\u2500 ... depth exceeded ...
831
831
  `:d.forEach((g,y)=>{let h=y===d.length-1;l+=Ga(g,u,c?t&&h:h,f,m,r)}),l}var Xr=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=wo.isAbsolute(n)?n:wo.resolve(process.cwd(),n);if(!Vr.existsSync(t))return`ERROR: File not found: ${n}`;let o=wo.extname(t).slice(1).toLowerCase(),s=Pa[o];if(!s)return`ERROR: Unsupported file extension: .${o}`;let r=wo.resolve(uo,s);if(!Vr.existsSync(r))return`ERROR: Parser for .${o} not found. Please download it in Settings > Other.`;try{let a=Fa.Parser;if(!Na){let m;try{m=wo.join(wo.dirname(Ua.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}),Na=!0}let i=new a,p=await Fa.Language.load(r);i.setLanguage(p);let d=await Vr.readFile(t,"utf8"),c=d.split(`
832
832
  `).length,l=12;c>1e4?l=2:c>=8e3?l=3:c>=5e3?l=5:c>=4e3?l=8:c>2e3&&(l=10);let f=i.parse(d),u=Ga(f.rootNode,0,!0," ",null,l);return`\u{1F4C4} File Map for: ${n}
833
833
  ${u}`}catch(a){let i=a instanceof Error?a.message:typeof a=="object"?JSON.stringify(a):String(a),p=a instanceof Error?`
834
- Stack: ${a.stack}`:"";return`ERROR: Failed to map file: ${i}${p}`}};import Qn from"fs";import Ha from"path";var is=async(e,n={})=>{let{method:t,tasks:o,markDone:s}=D(e),r=n.chatId||"default";if(!t)return'ERROR: Missing "method" argument for Goal tool (create/append/get).';let a=Ha.join(Dn,"plan",r),i=Ha.join(a,"todo.md"),p=l=>{if(!l||Array.isArray(l))return l;let f=String(l).trim();if(f.startsWith("[")&&f.endsWith("]")){let u=f.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);return u?u.map(m=>m.slice(1,-1).replace(/\\(.)/g,"$1")):f.slice(1,-1).split(",").map(m=>m.trim()).filter(Boolean)}return l},d=l=>{let f=p(l);return f?(Array.isArray(f)?f:String(f).split(`
834
+ Stack: ${a.stack}`:"";return`ERROR: Failed to map file: ${i}${p}`}};import Qn from"fs";import Ha from"path";var is=async(e,n={})=>{let{method:t,tasks:o,markDone:s}=D(e),r=n.chatId||"default";if(!t)return'ERROR: Missing "method" argument for Goal tool (create/append/get).';let a=Ha.join(Fn,"plan",r),i=Ha.join(a,"todo.md"),p=l=>{if(!l||Array.isArray(l))return l;let f=String(l).trim();if(f.startsWith("[")&&f.endsWith("]")){let u=f.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);return u?u.map(m=>m.slice(1,-1).replace(/\\(.)/g,"$1")):f.slice(1,-1).split(",").map(m=>m.trim()).filter(Boolean)}return l},d=l=>{let f=p(l);return f?(Array.isArray(f)?f:String(f).split(`
835
835
  `)).map(m=>{let g=String(m).trim();return g?g.startsWith("- [ ]")||g.startsWith("- [x]")||g.startsWith("- [X]")?g:`- [ ] ${g}`:null}).filter(Boolean).join(`
836
836
  `)+`
837
837
  `:""},c=(l,f)=>{if(!f)return{content:l,markedCount:0};let u=p(f),m=(Array.isArray(u)?u:[u]).map(b=>String(b).replace(/^- \[[xX ]\]\s*/i,"").trim()).filter(Boolean),g=l.split(`
838
838
  `),y=0,h=!1;for(let b of m){let w=!1;for(let T=0;T<g.length;T++)if(g[T].includes(b)&&/^- \[\s\]/.test(g[T].trim())){g[T]=g[T].replace("- [ ]","- [x]"),w=!0,h=!0,y++;break}if(!w){for(let T=0;T<g.length;T++)if(g[T].toLowerCase().includes(b.toLowerCase())&&/^- \[\s\]/.test(g[T].trim())){g[T]=g[T].replace("- [ ]","- [x]"),w=!0,h=!0,y++;break}}}return{content:h?g.join(`
839
- `):l,markedCount:y}};try{if(Qn.existsSync(a)||Qn.mkdirSync(a,{recursive:!0}),t==="create"){if(!o)return'ERROR: Missing "tasks" for create method.';let l=d(o),f=0;if(s){let m=c(l,s);l=m.content,f=m.markedCount}await gt.recordFileChange(i),Qn.writeFileSync(i,l,"utf8");let u=l.split(/\r?\n/).map(m=>m.trim()).filter(m=>m.startsWith("- [ ]")||m.startsWith("- [x]")||m.startsWith("- [X]")).length;if(f>0){let m=l.split(/\r?\n/).map(g=>g.trim()).filter(g=>g.startsWith("- [x]")||g.startsWith("- [X]")).length;return`SUCCESS: Goal Created (${f} marked done, ${m} completed, ${u-m} left)
839
+ `):l,markedCount:y}};try{if(Qn.existsSync(a)||Qn.mkdirSync(a,{recursive:!0}),t==="create"){if(!o)return'ERROR: Missing "tasks" for create method.';let l=d(o),f=0;if(s){let m=c(l,s);l=m.content,f=m.markedCount}await yt.recordFileChange(i),Qn.writeFileSync(i,l,"utf8");let u=l.split(/\r?\n/).map(m=>m.trim()).filter(m=>m.startsWith("- [ ]")||m.startsWith("- [x]")||m.startsWith("- [X]")).length;if(f>0){let m=l.split(/\r?\n/).map(g=>g.trim()).filter(g=>g.startsWith("- [x]")||g.startsWith("- [X]")).length;return`SUCCESS: Goal Created (${f} marked done, ${m} completed, ${u-m} left)
840
840
  ${l}`}return`SUCCESS: Goal Created (${u} total)
841
- ${l}`}if(t==="append"){if(!o)return'ERROR: Missing "tasks" for append method.';let l=d(o);await gt.recordFileChange(i),Qn.appendFileSync(i,l,"utf8");let f=Qn.readFileSync(i,"utf8"),u=f.split(/\r?\n/).map(h=>h.trim()),m=u.filter(h=>h.startsWith("- [ ]")||h.startsWith("- [x]")||h.startsWith("- [X]")).length,g=u.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: Goal Appended (${g} completed, ${m-g} left, ${y} added)
842
- ${f}`}if(t==="get"){if(!Qn.existsSync(i))return"Goal: No task list found for this session.";let l=Qn.readFileSync(i,"utf8"),f=0;if(s){let h=c(l,s);h.markedCount>0&&(l=h.content,f=h.markedCount,await gt.recordFileChange(i),Qn.writeFileSync(i,l,"utf8"))}let u=l.split(/\r?\n/).map(h=>h.trim()),m=u.filter(h=>h.startsWith("- [ ]")||h.startsWith("- [x]")||h.startsWith("- [X]")).length,g=u.filter(h=>h.startsWith("- [x]")||h.startsWith("- [X]")).length;return`${f>0?`SUCCESS: ${f} Goal(s) Marked Done`:"Goal"}: ${g} Completed, ${m-g} left
843
- ${l}`}return`ERROR: Unknown method "${t}". Use create, append, or get.`}catch(l){return`ERROR: Goal failure: ${l instanceof Error?l.message:String(l)}`}};var Jr=async(e,n={})=>{let{runSubagent:t}=await import("./ai-C6SSGCTT.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]
844
- `),d}catch(d){let{isTerminationSignaled:c}=await import("./ai-C6SSGCTT.js"),l=d.message==="Subagent task was cancelled by user."||c();if(n.onVisualFeedback){let f=l?"[CANCELLED]":"[FAILED]";n.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${p} ${f}
845
- `)}return`ERROR: Subagent execution failed: ${d.message}`}};var qa=async(e,n={})=>{let{runSubagent:t}=await import("./ai-C6SSGCTT.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(b=>b.trim().replace(/^["']|["']$/g,"")).filter(Boolean)}catch{}let d=`subagent-${Date.now()}-${Math.floor(Math.random()*1e3)}`,c=null,l=null,f=new Promise((h,b)=>{c=h,l=b}),u={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&&u.pendingSteerMessages.push(h)},completionPromise:f,_resolveCompletion:c,_rejectCompletion:l,progress:[]},m={chunks:[],totalWords:0};Qe.push(u),n.onSubagentUpdate&&n.onSubagentUpdate();let g=[],y={...n,taskId:d,onAskMain:async h=>{let b=`q-${Date.now()}-${Math.floor(Math.random()*1e3)}`,w=null,T=new Promise(k=>{w=k}),$={id:b,question:h,answered:!1,answer:null,askedAt:Date.now(),_resolve:w};return u.questions.push($),u.status="waiting",n.onSubagentUpdate&&n.onSubagentUpdate(),Rs(`[SYSTEM] Background subagent "${u.title}" is WAITING FOR YOUR INPUT: "${h}"
841
+ ${l}`}if(t==="append"){if(!o)return'ERROR: Missing "tasks" for append method.';let l=d(o);await yt.recordFileChange(i),Qn.appendFileSync(i,l,"utf8");let f=Qn.readFileSync(i,"utf8"),u=f.split(/\r?\n/).map(h=>h.trim()),m=u.filter(h=>h.startsWith("- [ ]")||h.startsWith("- [x]")||h.startsWith("- [X]")).length,g=u.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: Goal Appended (${g} completed, ${m-g} left, ${y} added)
842
+ ${f}`}if(t==="get"){if(!Qn.existsSync(i))return"Goal: No task list found for this session.";let l=Qn.readFileSync(i,"utf8"),f=0;if(s){let h=c(l,s);h.markedCount>0&&(l=h.content,f=h.markedCount,await yt.recordFileChange(i),Qn.writeFileSync(i,l,"utf8"))}let u=l.split(/\r?\n/).map(h=>h.trim()),m=u.filter(h=>h.startsWith("- [ ]")||h.startsWith("- [x]")||h.startsWith("- [X]")).length,g=u.filter(h=>h.startsWith("- [x]")||h.startsWith("- [X]")).length;return`${f>0?`SUCCESS: ${f} Goal(s) Marked Done`:"Goal"}: ${g} Completed, ${m-g} left
843
+ ${l}`}return`ERROR: Unknown method "${t}". Use create, append, or get.`}catch(l){return`ERROR: Goal failure: ${l instanceof Error?l.message:String(l)}`}};var Jr=async(e,n={})=>{let{runSubagent:t}=await import("./ai-K5UWT7PR.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]
844
+ `),d}catch(d){let{isTerminationSignaled:c}=await import("./ai-K5UWT7PR.js"),l=d.message==="Subagent task was cancelled by user."||c();if(n.onVisualFeedback){let f=l?"[CANCELLED]":"[FAILED]";n.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${p} ${f}
845
+ `)}return`ERROR: Subagent execution failed: ${d.message}`}};var qa=async(e,n={})=>{let{runSubagent:t}=await import("./ai-K5UWT7PR.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(b=>b.trim().replace(/^["']|["']$/g,"")).filter(Boolean)}catch{}let d=`subagent-${Date.now()}-${Math.floor(Math.random()*1e3)}`,c=null,l=null,f=new Promise((h,b)=>{c=h,l=b}),u={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&&u.pendingSteerMessages.push(h)},completionPromise:f,_resolveCompletion:c,_rejectCompletion:l,progress:[]},m={chunks:[],totalWords:0};Qe.push(u),n.onSubagentUpdate&&n.onSubagentUpdate();let g=[],y={...n,taskId:d,onAskMain:async h=>{let b=`q-${Date.now()}-${Math.floor(Math.random()*1e3)}`,w=null,T=new Promise(k=>{w=k}),$={id:b,question:h,answered:!1,answer:null,askedAt:Date.now(),_resolve:w};return u.questions.push($),u.status="waiting",n.onSubagentUpdate&&n.onSubagentUpdate(),Rs(`[SYSTEM] Background subagent "${u.title}" is WAITING FOR YOUR INPUT: "${h}"
846
846
  Respond using tool: [tool:functions.Answer(id="${d}", answer="...")]
847
847
  [/SYSTEM]`),await T},onVisualFeedback:h=>{u.lastChunkTime=Date.now();let b=h.replace(/\x1b\[[0-9;]*m/g,""),w=b.match(/[✔✘✗✖🔍📖→➕↻•]\s*([A-Za-z0-9\s-]+)/);w?u.currentTool=w[1].trim():u.currentTool=b,n.onSubagentUpdate&&n.onSubagentUpdate()},onTokenChunk:(h,b)=>{let w=Date.now();if(u.lastChunkTime=w,u.currentTool="Thinking",typeof b=="number"&&b>0){m.totalWords+=b,m.chunks.push({time:w,words:b});let T=w-400;if(m.chunks=m.chunks.filter($=>$.time>=T),m.chunks.length>0){let $=m.chunks.reduce((S,_)=>S+_.words,0),R=m.chunks[0].time,k=Math.max(.4,(w-R)/1e3);u.wps=Math.round($/k*10)/10}}n.onSubagentUpdate&&n.onSubagentUpdate()}};return t(s,y,r,p,50,h=>{if(u.status==="cancelled")return;if(h.startsWith("[Subagent Turn")&&g.length>0&&(u.progress.push([...g]),g=[]),h.includes("[Executing Tool]")){let w=h.match(/\[Executing Tool\]\s*([a-zA-Z0-9_]+)/);w&&(!u.currentTool||u.currentTool==="Thinking")&&(u.currentTool=w[1])}let b=h;if(b.startsWith("[Tool Result]")){let w=b.split(`
848
848
  `);w.length>5&&(b=w.slice(0,4).join(`
849
849
  `)+`
850
- ... [Content/Diff Truncated from Logs] ...`)}g.push(b),n.onSubagentUpdate&&n.onSubagentUpdate()},!0).then(h=>{if(u.status==="cancelled"){u._resolveCompletion&&u._resolveCompletion(h);return}g.length>0&&(u.progress.push([...g]),g=[]),u.status="completed",u.finalAnswer=h,n.onSubagentUpdate&&n.onSubagentUpdate(),Rs(`[SYSTEM] Background subagent "${u.title}" (id: ${d}) has FINISHED. Call GetProgress(id="${d}") to see the final result. [/SYSTEM]`),u._resolveCompletion&&u._resolveCompletion(h)}).catch(async h=>{let{isTerminationSignaled:b}=await import("./ai-C6SSGCTT.js");if(h.message==="Subagent task was cancelled."||u.status==="cancelled"||b()){u.status="cancelled",g.push("[SUBAGENT CANCELLED] Task was cancelled."),u.progress.push([...g]),n.onSubagentUpdate&&n.onSubagentUpdate(),u._resolveCompletion&&u._resolveCompletion(null);return}g.push(`[SUBAGENT FAILURE] Error: ${h.message}`),u.progress.push([...g]),u.status="failed",u.error=h.message,n.onSubagentUpdate&&n.onSubagentUpdate(),Rs(`[SYSTEM] Background subagent "${u.title}" (id: ${d}) FAILED with error: ${h.message}. [/SYSTEM]`),u._rejectCompletion&&u._rejectCompletion(h)}),`SUCCESS: Background subagent started. Task ID: ${d}`};var Qr=async(e,n={})=>{let o=D(e).id;if(!o)return'ERROR: Missing "id" argument for getProgress.';let s=Qe.find(i=>i.id===o);if(!s)return`ERROR: Subagent task with ID [${o}] not found.`;let r=`Subagent Task Status: ${s.status.toUpperCase()}
850
+ ... [Content/Diff Truncated from Logs] ...`)}g.push(b),n.onSubagentUpdate&&n.onSubagentUpdate()},!0).then(h=>{if(u.status==="cancelled"){u._resolveCompletion&&u._resolveCompletion(h);return}g.length>0&&(u.progress.push([...g]),g=[]),u.status="completed",u.finalAnswer=h,n.onSubagentUpdate&&n.onSubagentUpdate(),Rs(`[SYSTEM] Background subagent "${u.title}" (id: ${d}) has FINISHED. Call GetProgress(id="${d}") to see the final result. [/SYSTEM]`),u._resolveCompletion&&u._resolveCompletion(h)}).catch(async h=>{let{isTerminationSignaled:b}=await import("./ai-K5UWT7PR.js");if(h.message==="Subagent task was cancelled."||u.status==="cancelled"||b()){u.status="cancelled",g.push("[SUBAGENT CANCELLED] Task was cancelled."),u.progress.push([...g]),n.onSubagentUpdate&&n.onSubagentUpdate(),u._resolveCompletion&&u._resolveCompletion(null);return}g.push(`[SUBAGENT FAILURE] Error: ${h.message}`),u.progress.push([...g]),u.status="failed",u.error=h.message,n.onSubagentUpdate&&n.onSubagentUpdate(),Rs(`[SYSTEM] Background subagent "${u.title}" (id: ${d}) FAILED with error: ${h.message}. [/SYSTEM]`),u._rejectCompletion&&u._rejectCompletion(h)}),`SUCCESS: Background subagent started. Task ID: ${d}`};var Qr=async(e,n={})=>{let o=D(e).id;if(!o)return'ERROR: Missing "id" argument for getProgress.';let s=Qe.find(i=>i.id===o);if(!s)return`ERROR: Subagent task with ID [${o}] not found.`;let r=`Subagent Task Status: ${s.status.toUpperCase()}
851
851
  `;if(r+=`Title: ${s.title}
852
852
  `,r+=`Task: ${s.task}
853
853
  `,s.startedAt){let i=Math.floor((Date.now()-s.startedAt)/1e3);r+=`Elapsed Time: ${i}s
@@ -872,7 +872,7 @@ ${s.finalAnswer}
872
872
  `),r.replace(/\r\n/g,`
873
873
  `).replace(/\n{3,}/g,`
874
874
 
875
- `).trim().replace(/\[TOOL RESULT\]/gi,"TOOL RESULT:")};var za=async(e,n={})=>{let o=D(e).id;if(!o)return'ERROR: Missing "id" argument for cancel.';let s=Qe.find(r=>r.id===o);return s?s.status==="completed"||s.status==="failed"?`INFO: Subagent task with ID [${o}] has already finished with status [${s.status.toUpperCase()}].`:s.status==="cancelled"?`INFO: Subagent task with ID [${o}] is already cancelled.`:(s.status="cancelled",n.onSubagentUpdate&&n.onSubagentUpdate(),`SUCCESS: Subagent task with ID [${o}] has been cancelled.`):`ERROR: Subagent task with ID [${o}] not found.`};import kt from"fs-extra";import Ct from"path";var Oc=["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 kt.readdir(e,{withFileTypes:!0}).catch(()=>[]);for(let s of o){if(Oc.includes(s.name))continue;let r=Ct.join(e,s.name),a=Ct.relative(n,r).replace(/\\/g,"/");if(s.isDirectory()){let i=await as(r,n);Object.assign(t,i)}else{let i=await kt.stat(r).catch(()=>null);i&&(t[a]={size:i.size,mtime:i.mtimeMs})}}return t}async function Ka(e,n){await kt.ensureDir(e);for(let t of Object.keys(n)){let o=Ct.join(process.cwd(),t),s=Ct.join(e,t);await kt.ensureDir(Ct.dirname(s)),await kt.copyFile(o,s).catch(()=>{})}}async function Zr(e,n,t=null,o=null){if(!await kt.pathExists(e))return;o||(o=e);let s=await kt.readdir(e,{withFileTypes:!0}).catch(()=>[]);for(let r of s){let a=Ct.join(e,r.name),i=Ct.join(n,r.name);if(r.isDirectory())await Zr(a,i,t,o);else{let p=Ct.relative(o,a).replace(/\\/g,"/"),d=await kt.pathExists(i);d&&await kt.chmod(i,438).catch(()=>{}),await kt.ensureDir(Ct.dirname(i));let c=await kt.copyFile(a,i).then(()=>!0).catch(()=>!1);await kt.chmod(i,438).catch(()=>{}),t&&(c?d?t.replaced++:t.restored++:t.failed.push(p))}}}var Zn={async takeInitialSnapshot(e){try{let n=Ct.join(Dn,"snapshots",e);await kt.remove(n).catch(()=>{}),await kt.ensureDir(n);let t=await as(process.cwd());await Ka(Ct.join(n,"initial"),t);let o=se(gn,{});o[e]={initialManifest:t,currentManifest:t,checkpoints:[{id:"initial",timestamp:new Date().toISOString(),newFiles:[],modifiedFiles:[],deletedFiles:[],toolsUsed:[]}]},ye(gn,o)}catch{}},async recordTurnDelta(e,n,t=[]){try{let o=se(gn,{}),s=o[e];if(!s)return;let r=s.currentManifest||s.initialManifest,a=await as(process.cwd()),i=[],p=[],d=[];for(let[l,f]of Object.entries(a)){let u=r[l];u?(u.size!==f.size||u.mtime!==f.mtime)&&p.push(l):i.push(l)}for(let l of Object.keys(r))a[l]||d.push(l);let c=[...i,...p];if(c.length>0||d.length>0){let l={};for(let u of c)l[u]=a[u];let f=Ct.join(Dn,"snapshots",e,`turn_${n}`);await Ka(f,l)}s.checkpoints.push({id:`turn_${n}`,timestamp:new Date().toISOString(),newFiles:i,modifiedFiles:p,deletedFiles:d,toolsUsed:t}),s.currentManifest=a,ye(gn,o)}catch{}},async getCheckpoints(e){try{let t=se(gn,{})[e];return t?t.checkpoints||[]:[]}catch{return[]}},async rollbackToCheckpoint(e,n){try{let t=se(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=Ct.join(Dn,"snapshots",e),i={restored:0,replaced:0,failed:[]},p=await as(process.cwd());for(let c of Object.keys(p)){let l=Ct.join(process.cwd(),c);await kt.chmod(l,438).catch(()=>{}),await kt.remove(l).catch(()=>{})}let d=Ct.join(a,"initial");await Zr(d,process.cwd(),i,d);for(let c=1;c<=r;c++){let l=s[c],f=Ct.join(a,l.id);if(await Zr(f,process.cwd(),i,f),l.deletedFiles&&l.deletedFiles.length>0)for(let u of l.deletedFiles){let m=Ct.join(process.cwd(),u);await kt.chmod(m,438).catch(()=>{}),await kt.remove(m).catch(()=>{})}}return o.checkpoints=s.slice(0,r+1),o.currentManifest=await as(process.cwd()),ye(gn,t),{checkpointId:n,stats:i}}catch(t){throw new Error(`Rollback failed: ${t.message}`)}},async getLatestFileChanges(e){try{let t=se(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=Ct.join(Dn,"snapshots",e);await kt.remove(n).catch(()=>{});let t=se(gn,{});t[e]&&(delete t[e],ye(gn,t))}catch{}}};var ei=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 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:
875
+ `).trim().replace(/\[TOOL RESULT\]/gi,"TOOL RESULT:")};var za=async(e,n={})=>{let o=D(e).id;if(!o)return'ERROR: Missing "id" argument for cancel.';let s=Qe.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 St from"fs-extra";import $t from"path";var Oc=["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 St.readdir(e,{withFileTypes:!0}).catch(()=>[]);for(let s of o){if(Oc.includes(s.name))continue;let r=$t.join(e,s.name),a=$t.relative(n,r).replace(/\\/g,"/");if(s.isDirectory()){let i=await as(r,n);Object.assign(t,i)}else{let i=await St.stat(r).catch(()=>null);i&&(t[a]={size:i.size,mtime:i.mtimeMs})}}return t}async function Ka(e,n){await St.ensureDir(e);for(let t of Object.keys(n)){let o=$t.join(process.cwd(),t),s=$t.join(e,t);await St.ensureDir($t.dirname(s)),await St.copyFile(o,s).catch(()=>{})}}async function Zr(e,n,t=null,o=null){if(!await St.pathExists(e))return;o||(o=e);let s=await St.readdir(e,{withFileTypes:!0}).catch(()=>[]);for(let r of s){let a=$t.join(e,r.name),i=$t.join(n,r.name);if(r.isDirectory())await Zr(a,i,t,o);else{let p=$t.relative(o,a).replace(/\\/g,"/"),d=await St.pathExists(i);d&&await St.chmod(i,438).catch(()=>{}),await St.ensureDir($t.dirname(i));let c=await St.copyFile(a,i).then(()=>!0).catch(()=>!1);await St.chmod(i,438).catch(()=>{}),t&&(c?d?t.replaced++:t.restored++:t.failed.push(p))}}}var Zn={async takeInitialSnapshot(e){try{let n=$t.join(Fn,"snapshots",e);await St.remove(n).catch(()=>{}),await St.ensureDir(n);let t=await as(process.cwd());await Ka($t.join(n,"initial"),t);let o=se(wn,{});o[e]={initialManifest:t,currentManifest:t,checkpoints:[{id:"initial",timestamp:new Date().toISOString(),newFiles:[],modifiedFiles:[],deletedFiles:[],toolsUsed:[]}]},ye(wn,o)}catch{}},async recordTurnDelta(e,n,t=[]){try{let o=se(wn,{}),s=o[e];if(!s)return;let r=s.currentManifest||s.initialManifest,a=await as(process.cwd()),i=[],p=[],d=[];for(let[l,f]of Object.entries(a)){let u=r[l];u?(u.size!==f.size||u.mtime!==f.mtime)&&p.push(l):i.push(l)}for(let l of Object.keys(r))a[l]||d.push(l);let c=[...i,...p];if(c.length>0||d.length>0){let l={};for(let u of c)l[u]=a[u];let f=$t.join(Fn,"snapshots",e,`turn_${n}`);await Ka(f,l)}s.checkpoints.push({id:`turn_${n}`,timestamp:new Date().toISOString(),newFiles:i,modifiedFiles:p,deletedFiles:d,toolsUsed:t}),s.currentManifest=a,ye(wn,o)}catch{}},async getCheckpoints(e){try{let t=se(wn,{})[e];return t?t.checkpoints||[]:[]}catch{return[]}},async rollbackToCheckpoint(e,n){try{let t=se(wn,{}),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=$t.join(Fn,"snapshots",e),i={restored:0,replaced:0,failed:[]},p=await as(process.cwd());for(let c of Object.keys(p)){let l=$t.join(process.cwd(),c);await St.chmod(l,438).catch(()=>{}),await St.remove(l).catch(()=>{})}let d=$t.join(a,"initial");await Zr(d,process.cwd(),i,d);for(let c=1;c<=r;c++){let l=s[c],f=$t.join(a,l.id);if(await Zr(f,process.cwd(),i,f),l.deletedFiles&&l.deletedFiles.length>0)for(let u of l.deletedFiles){let m=$t.join(process.cwd(),u);await St.chmod(m,438).catch(()=>{}),await St.remove(m).catch(()=>{})}}return o.checkpoints=s.slice(0,r+1),o.currentManifest=await as(process.cwd()),ye(wn,t),{checkpointId:n,stats:i}}catch(t){throw new Error(`Rollback failed: ${t.message}`)}},async getLatestFileChanges(e){try{let t=se(wn,{})[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=$t.join(Fn,"snapshots",e);await St.remove(n).catch(()=>{});let t=se(wn,{});t[e]&&(delete t[e],ye(wn,t))}catch{}}};var ei=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 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:
876
876
 
877
877
  `;for(let l of i)if(l.id==="initial")c+=`--- Initial State (id: initial) ---
878
878
  Tools Used: User Prompted for task
@@ -895,8 +895,8 @@ ${r.finalAnswer||"(No output)"}`;if(r.status==="failed")return`ERROR: Subagent t
895
895
  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.
896
896
  Final Answer:
897
897
  ${r.finalAnswer||"(No output)"}`:r.status==="failed"?`ERROR: Subagent task [${o}] failed.
898
- 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=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=Qe.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=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=Qe.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 un,keyboard as Nt,Button as cs,Key as P,Point as ds,clipboard as Lc}from"@nut-tree-fork/nut-js";un.config.autoDelayMs=50;Nt.config.autoDelayMs=50;async function ti(){try{await Nt.releaseKey(P.LeftControl,P.RightControl,P.LeftAlt,P.RightAlt,P.LeftShift,P.RightShift,P.LeftSuper,P.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 un.setPosition(new ds(o.x,o.y)),`SUCCESS: Moved mouse to grid target ${typeof n=="string"?n:`(${o.x}, ${o.y})`}`;case"click":{await un.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 un.doubleClick(s):await un.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 un.setPosition(new ds(s.x,s.y)),await un.pressButton(cs.LEFT),await un.setPosition(new ds(r.x,r.y)),await un.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 un.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 un.scrollUp(120):await un.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 Ya={enter:P.Enter,return:P.Return,escape:P.Escape,esc:P.Escape,backspace:P.Backspace,tab:P.Tab,space:P.Space,up:P.Up,down:P.Down,left:P.Left,right:P.Right,ctrl:P.LeftControl,control:P.LeftControl,alt:P.LeftAlt,shift:P.LeftShift,cmd:P.LeftCmd,win:P.LeftWin,meta:P.LeftWin,super:P.LeftSuper,a:P.A,b:P.B,c:P.C,d:P.D,e:P.E,f:P.F,g:P.G,h:P.H,i:P.I,j:P.J,k:P.K,l:P.L,m:P.M,n:P.N,o:P.O,p:P.P,q:P.Q,r:P.R,s:P.S,t:P.T,u:P.U,v:P.V,w:P.W,x:P.X,y:P.Y,z:P.Z,0:P.Num0,1:P.Num1,2:P.Num2,3:P.Num3,4:P.Num4,5:P.Num5,6:P.Num6,7:P.Num7,8:P.Num8,9:P.Num9,f1:P.F1,f2:P.F2,f3:P.F3,f4:P.F4,f5:P.F5,f6:P.F6,f7:P.F7,f8:P.F8,f9:P.F9,f10:P.F10,f11:P.F11,f12:P.F12},Va=e=>{if(!e)return;let n=String(e).toLowerCase().trim();if(Ya[n]!==void 0)return Ya[n];if(P[e]!==void 0)return P[e];if(P[n.toUpperCase()]!==void 0)return P[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 ti(),await Lc.setContent(n);let s=process.platform==="darwin"?P.LeftSuper:P.LeftControl;return await Nt.pressKey(s,P.V),await Nt.releaseKey(s,P.V),await ti(),t.autoPressEnter?(await new Promise(r=>setTimeout(r,50)),await Nt.type(P.Enter),`SUCCESS: Typed text input ("${n.length>20?n.substring(0,20)+"...":n}") and pressed Enter`):`SUCCESS: Typed text input ("${n.length>20?n.substring(0,20)+"...":n}")`}case"key_press":{let o=Va(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=>Va(s)).filter(s=>s!==void 0);return o.length===0?"ERROR: Invalid key combination":(await Nt.pressKey(...o),await Nt.releaseKey(...o),`SUCCESS: Executed key combination [${n.join(" + ")}]`)}case"clear_input":return await Nt.pressKey(P.LeftControl,P.A),await Nt.releaseKey(P.LeftControl,P.A),await Nt.type(P.Backspace),"SUCCESS: Cleared active text input (Select All + Backspace)";case"browser_back":{let o=process.platform==="darwin";return o?(await Nt.pressKey(P.LeftSuper,P.Left),await Nt.releaseKey(P.LeftSuper,P.Left)):(await Nt.pressKey(P.LeftAlt,P.Left),await Nt.releaseKey(P.LeftAlt,P.Left)),await ti(),`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 us=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 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 Za from"screenshot-desktop";import ps from"sharp";import Xa from"fs-extra";import Ja from"path";import"@nut-tree-fork/nut-js";async function ni(e,n,t){if(!(!process.env.SHOW_DEBUG_GRID&&!process.env.DEBUG_OCR))try{let o=Ja.resolve(process.cwd(),"screenshots",e);await Xa.ensureDir(o),await Xa.writeFile(Ja.join(o,n),t)}catch{}}function Dc(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Pc(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 Fc(e){return e<=4?0:e<=8?1:2}async function oi(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 Nc(e){if(!e)return{words:[],lines:[]};let n=[],t=new Map;for(let s of e.split(`
899
- `)){let r=s.split(" ");if(r.length<12||parseInt(r[0])!==5)continue;let i=r[2],p=r[3],d=r[4],c=parseInt(r[6]),l=parseInt(r[7]),f=parseInt(r[8]),u=parseInt(r[9]),m=parseFloat(r[10]),g=r.slice(11).join(" ").trim();if(!g||m<0)continue;let y={x0:c,y0:l,x1:c+f,y1:l+u},h={text:g,confidence:m,bbox:y};n.push(h);let b=`${i}_${p}_${d}`;t.has(b)||t.set(b,{words:[],bbox:{x0:1/0,y0:1/0,x1:-1/0,y1:-1/0}});let w=t.get(b);w.words.push(h),w.bbox.x0=Math.min(w.bbox.x0,y.x0),w.bbox.y0=Math.min(w.bbox.y0,y.y0),w.bbox.x1=Math.max(w.bbox.x1,y.x1),w.bbox.y1=Math.max(w.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 Uc(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=Nc(e.tsv);e.words=n.words,e.lines=n.lines}}}function si(e,n,t=0,o=0,s=1){Uc(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${Dc(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+/),f=l.map(m=>m.replace(/[^a-z0-9]/g,"")).join(" "),u=!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===f||y.includes(f)){let h={x0:Math.min(...g.map(b=>b.bbox.x0)),y0:Math.min(...g.map(b=>b.bbox.y0)),x1:Math.max(...g.map(b=>b.bbox.x1)),y1:Math.max(...g.map(b=>b.bbox.y1))};a.push(r(h)),u=!0}}u||a.push(r(i.bbox))}if(a.length===0&&e.words&&e.words.length>0)for(let i of e.words){let p=i.text?i.text.toLowerCase().trim().replace(/[^a-z0-9]/g,""):"",d=n.replace(/[^a-z0-9]/g,"");p===d&&i.bbox&&a.push(r(i.bbox))}if(a.length===0&&e.words&&e.words.length>0){let i=Fc(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&&Pc(d,n,i)<=i&&p.bbox&&a.push(r(p.bbox))}}return a}function ri(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 Bc(e,n,t,o){let a=Math.ceil(e/4),i=Math.ceil(n/2),p=[];for(let d=0;d<2;d++)for(let c=0;c<4;c++){let l=c*a,f=d*i,u=Math.min(a,e-l),m=Math.min(i,n-f),g=l+u/2,y=f+m/2,h=t>=l&&t<l+u&&o>=f&&o<f+m;p.push({x0:l,y0:f,w:u,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),f=Math.hypot(c.cx-t,c.cy-o);return l-f})}var Fs=null;async function Wc(){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,Qa=null;async function jc(){let{getActiveDisplay:e}=await import("./screen_grid-QAZBAXG2.js"),n=await e();if(fs&&Qa===n)return fs;Qa=n,fs={format:"png"};try{let t=await Za.listDisplays();t&&t.length>0&&(fs={format:"png",screen:(t[n]||t[0]).id})}catch{}return fs}var ii=async(e,n={})=>{let t=!!(process.env.SHOW_DEBUG_GRID||process.env.DEBUG_OCR||process.env.VERBOSE),o=performance.now(),s=o,r=u=>{if(!t)return;let m=performance.now(),g=(m-s).toFixed(0),y=(m-o).toFixed(0);console.log(`[Click Perf] +${g}ms (${y}ms total) -> ${u}`),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 u=i?Bi(i):null;r("Getting display options");let m=await jc();r("Taking desktop screenshot");let g=await Za(m);r("Getting image metadata");let y=await ps(g).metadata(),h=y.width||1920,b=y.height||1080,w=u?{x:Math.round(u.x*(h/1280)),y:Math.round(u.y*(b/720))}:{x:h/2,y:b/2},T=c.toLowerCase().trim();r("Acquiring OCR worker");let $=await Wc(),R=null,k="",S=u?220:500;if(u){r("Pass 1: Cropping target crop (3x zoom window, 2x upscale)");let _=Math.min(Math.round(h/3),h),E=Math.min(Math.round(b/3),b),x=Math.max(0,Math.min(h-_,w.x-Math.floor(_/2))),C=Math.max(0,Math.min(b-E,w.y-Math.floor(E/2))),M=await ps(g).extract({left:x,top:C,width:_,height:E}).toBuffer(),v=2,L=await oi(M,v),U=T.replace(/[^a-z0-9]/g,"_");await ni("cropped",`crop_${Date.now()}_${U}.png`,L),r("Pass 1: Running Tesseract OCR recognize on crop (PSM 11 - Sparse Text)"),await $.setParameters({tessedit_pageseg_mode:"11"});let{data:j}=await $.recognize(L,{},{tsv:!0,blocks:!0});if(r("Pass 1: OCR recognition finished, extracting matches"),j&&j.text){t&&console.log(`[Pass 1 OCR Read]: "${j.text.trim().replace(/\s+/g," ")}"`);let ee=si(j,T,x,C,v);if(ee.length>0){let X=ri(ee,w);X&&(X.containsPoint||X.dist<=S)&&(R=X,k="centered target crop OCR")}}}if(!R){r("Pass 2: Entering Full-Screen OCR (broad scan, PSM 3 - Auto)");let _=await oi(g,2),E=T.replace(/[^a-z0-9]/g,"_");await ni("fullscreen",`full_${Date.now()}_${E}.png`,_),r("Pass 2: Running Tesseract on full screen"),await $.setParameters({tessedit_pageseg_mode:"3"});let{data:x}=await $.recognize(_,{},{tsv:!0,blocks:!0});if(r("Pass 2: Full-screen OCR finished"),x&&x.text){let C=si(x,T,0,0,2);if(C.length>0){let M=ri(C,w);M&&(R=M,k="full-screen OCR")}}}if(!R){r("Pass 3: Entering Tiled OCR fallback (high-res 3x)");let _=Bc(h,b,w.x,w.y),E=T.replace(/[^a-z0-9]/g,"_");await $.setParameters({tessedit_pageseg_mode:"11"});for(let x=0;x<_.length;x++){let C=_[x];r(`Pass 3: Preprocessing tile ${x+1}/${_.length}`);let M=await ps(g).extract({left:C.x0,top:C.y0,width:C.w,height:C.h}).toBuffer(),v=await oi(M,3);await ni("tiles",`tile_${x+1}_${Date.now()}_${E}.png`,v),r(`Pass 3: Running Tesseract on tile ${x+1}`);let{data:L}=await $.recognize(v,{},{tsv:!0,blocks:!0});if(!L||!L.text)continue;let U=si(L,T,C.x0,C.y0,3);if(U.length>0){let j=ri(U,w);if(j){R=j,k=`tile ${x+1} OCR (${C.containsTarget?"target tile":`offset ${C.x0},${C.y0}`})`;break}}}}if(R){let _={x:Math.round(R.x*(1280/h)),y:Math.round(R.y*(720/b))};r(`Executing mouse click on matched target (${k})`);let E=await Nn("click",_,{button:d,clickType:p});return r("Click completed successfully"),`${E} (${k} for "${c}" at ${Math.round(R.dist)}px distance)`}else t&&console.log(`[OCR] No match found for "${c}". Falling back to gridId.`)}catch(u){t&&console.error("[OCR Error]",u)}r(`Executing mouse click on fallback gridId: ${l}`);let f=await Nn("click",l,{button:d,clickType:p});return r("Fallback click completed"),f};var ai=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 Nn("drag",o,{from:o,to:s})};var li=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 Nn("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 Un("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 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 Gc={web_search:vr,web_scrape:Ir,memory:Or,chat:Lr,view_file:ts,write_file:Dr,update_file:Ur,exec_command:wr,read_folder:Wr,write_pdf:jr,write_docx:Hr,search_keyword:ss,generate_image:Kr,saveSummary:rs,addMemScore:Fo,file_map:Xr,todo:is,Todo:is,goal:is,Goal:is,invokeSync:Jr,invoke:qa,getProgress:Qr,cancel:za,awaitSubagent:No,answerSubagent:Uo,steerSubagent:ls,computer_action:us,computer_use:us,ComputerAction:us,ComputerUse:us,click:ii,Click:ii,drag:ai,Drag:ai,scroll:li,Scroll:li,keyboard_typing:Ns,KeyboardTyping:Ns,keyboardtyping:Ns,key_press:Us,KeyPress:Us,keypress:Us,recapture_screen:Bs,RecaptureScreen:Bs,recapturescreen:Bs,invoke_sync:Jr,get_progress:Qr,await_subagent:No,answer_subagent:Uo,steer_subagent:ls,steer:ls,Steer:ls,ask:Ps,Ask:Ps,AskUser:Ps,WebSearch:vr,WebScrape:Ir,ReadFile:ts,ReadFolder:Wr,WriteFile:Dr,PatchFile:Ur,WritePDF:jr,WriteDoc:Hr,Run:wr,SearchKeyword:ss,CodeSearch:ss,code_search:ss,Memory:Or,Chat:Lr,GenerateImage:Kr,saveSumary:rs,SaveSummary:rs,SaveSumary:rs,add_mem_score:Fo,AddMemScore:Fo,addMemoryScore:Fo,AddMemoryScore:Fo,FileMap:Xr,answer:Uo,Answer:Uo,AnswerSubagent:Uo,await:No,Await:No,AwaitSubagent:No,EmergencyRollback:ei,emergency_rollback:ei},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=Gc[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 te from"path";import Fe from"fs";import Hc from"gradient-string";var ci=["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 el=[{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 tl=(e="Dark")=>{let n;e==="Mystery"||e==="Chaos"?(Ws||(Ws=el[Math.floor(Math.random()*el.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 qc=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",eg=(e=2)=>{let n=qc();return n==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)},tg=(e="...",n="Loading...",t="Dark")=>{let o=ci[Math.floor(Math.random()*ci.length)],s=tl(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=Hc(c).multiline(d.join(`
898
+ 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=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=Qe.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=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=Qe.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 pn,keyboard as Bt,Button as cs,Key as P,Point as ds,clipboard as Lc}from"@nut-tree-fork/nut-js";pn.config.autoDelayMs=50;Bt.config.autoDelayMs=50;async function ti(){try{await Bt.releaseKey(P.LeftControl,P.RightControl,P.LeftAlt,P.RightAlt,P.LeftShift,P.RightShift,P.LeftSuper,P.RightSuper)}catch{}}async function Bn(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 pn.setPosition(new ds(o.x,o.y)),`SUCCESS: Moved mouse to grid target ${typeof n=="string"?n:`(${o.x}, ${o.y})`}`;case"click":{await pn.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 pn.doubleClick(s):await pn.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 pn.setPosition(new ds(s.x,s.y)),await pn.pressButton(cs.LEFT),await pn.setPosition(new ds(r.x,r.y)),await pn.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 pn.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 pn.scrollUp(120):await pn.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 Ya={enter:P.Enter,return:P.Return,escape:P.Escape,esc:P.Escape,backspace:P.Backspace,tab:P.Tab,space:P.Space,up:P.Up,down:P.Down,left:P.Left,right:P.Right,ctrl:P.LeftControl,control:P.LeftControl,alt:P.LeftAlt,shift:P.LeftShift,cmd:P.LeftCmd,win:P.LeftWin,meta:P.LeftWin,super:P.LeftSuper,a:P.A,b:P.B,c:P.C,d:P.D,e:P.E,f:P.F,g:P.G,h:P.H,i:P.I,j:P.J,k:P.K,l:P.L,m:P.M,n:P.N,o:P.O,p:P.P,q:P.Q,r:P.R,s:P.S,t:P.T,u:P.U,v:P.V,w:P.W,x:P.X,y:P.Y,z:P.Z,0:P.Num0,1:P.Num1,2:P.Num2,3:P.Num3,4:P.Num4,5:P.Num5,6:P.Num6,7:P.Num7,8:P.Num8,9:P.Num9,f1:P.F1,f2:P.F2,f3:P.F3,f4:P.F4,f5:P.F5,f6:P.F6,f7:P.F7,f8:P.F8,f9:P.F9,f10:P.F10,f11:P.F11,f12:P.F12},Va=e=>{if(!e)return;let n=String(e).toLowerCase().trim();if(Ya[n]!==void 0)return Ya[n];if(P[e]!==void 0)return P[e];if(P[n.toUpperCase()]!==void 0)return P[n.toUpperCase()]};async function Wn(e,n,t={}){try{switch(e.toLowerCase()){case"type":{if(typeof n!="string")return"ERROR: Type action requires a valid string input";await ti(),await Lc.setContent(n);let s=process.platform==="darwin"?P.LeftSuper:P.LeftControl;return await Bt.pressKey(s,P.V),await Bt.releaseKey(s,P.V),await ti(),t.autoPressEnter?(await new Promise(r=>setTimeout(r,50)),await Bt.type(P.Enter),`SUCCESS: Typed text input ("${n.length>20?n.substring(0,20)+"...":n}") and pressed Enter`):`SUCCESS: Typed text input ("${n.length>20?n.substring(0,20)+"...":n}")`}case"key_press":{let o=Va(n);return o===void 0?`ERROR: Unknown key name "${n}"`:(await Bt.type(o),`SUCCESS: Pressed key ${n}`)}case"key_combination":{if(!Array.isArray(n))return'ERROR: key_combination requires an array of keys (e.g. ["ctrl", "c"])';let o=n.map(s=>Va(s)).filter(s=>s!==void 0);return o.length===0?"ERROR: Invalid key combination":(await Bt.pressKey(...o),await Bt.releaseKey(...o),`SUCCESS: Executed key combination [${n.join(" + ")}]`)}case"clear_input":return await Bt.pressKey(P.LeftControl,P.A),await Bt.releaseKey(P.LeftControl,P.A),await Bt.type(P.Backspace),"SUCCESS: Cleared active text input (Select All + Backspace)";case"browser_back":{let o=process.platform==="darwin";return o?(await Bt.pressKey(P.LeftSuper,P.Left),await Bt.releaseKey(P.LeftSuper,P.Left)):(await Bt.pressKey(P.LeftAlt,P.Left),await Bt.releaseKey(P.LeftAlt,P.Left)),await ti(),`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 us=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 Bn(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 Wn(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 Za from"screenshot-desktop";import ps from"sharp";import Xa from"fs-extra";import Ja from"path";import"@nut-tree-fork/nut-js";async function ni(e,n,t){if(!(!process.env.SHOW_DEBUG_GRID&&!process.env.DEBUG_OCR))try{let o=Ja.resolve(process.cwd(),"screenshots",e);await Xa.ensureDir(o),await Xa.writeFile(Ja.join(o,n),t)}catch{}}function Dc(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Pc(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 Fc(e){return e<=4?0:e<=8?1:2}async function oi(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 Nc(e){if(!e)return{words:[],lines:[]};let n=[],t=new Map;for(let s of e.split(`
899
+ `)){let r=s.split(" ");if(r.length<12||parseInt(r[0])!==5)continue;let i=r[2],p=r[3],d=r[4],c=parseInt(r[6]),l=parseInt(r[7]),f=parseInt(r[8]),u=parseInt(r[9]),m=parseFloat(r[10]),g=r.slice(11).join(" ").trim();if(!g||m<0)continue;let y={x0:c,y0:l,x1:c+f,y1:l+u},h={text:g,confidence:m,bbox:y};n.push(h);let b=`${i}_${p}_${d}`;t.has(b)||t.set(b,{words:[],bbox:{x0:1/0,y0:1/0,x1:-1/0,y1:-1/0}});let w=t.get(b);w.words.push(h),w.bbox.x0=Math.min(w.bbox.x0,y.x0),w.bbox.y0=Math.min(w.bbox.y0,y.y0),w.bbox.x1=Math.max(w.bbox.x1,y.x1),w.bbox.y1=Math.max(w.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 Uc(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=Nc(e.tsv);e.words=n.words,e.lines=n.lines}}}function si(e,n,t=0,o=0,s=1){Uc(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${Dc(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+/),f=l.map(m=>m.replace(/[^a-z0-9]/g,"")).join(" "),u=!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===f||y.includes(f)){let h={x0:Math.min(...g.map(b=>b.bbox.x0)),y0:Math.min(...g.map(b=>b.bbox.y0)),x1:Math.max(...g.map(b=>b.bbox.x1)),y1:Math.max(...g.map(b=>b.bbox.y1))};a.push(r(h)),u=!0}}u||a.push(r(i.bbox))}if(a.length===0&&e.words&&e.words.length>0)for(let i of e.words){let p=i.text?i.text.toLowerCase().trim().replace(/[^a-z0-9]/g,""):"",d=n.replace(/[^a-z0-9]/g,"");p===d&&i.bbox&&a.push(r(i.bbox))}if(a.length===0&&e.words&&e.words.length>0){let i=Fc(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&&Pc(d,n,i)<=i&&p.bbox&&a.push(r(p.bbox))}}return a}function ri(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 Bc(e,n,t,o){let a=Math.ceil(e/4),i=Math.ceil(n/2),p=[];for(let d=0;d<2;d++)for(let c=0;c<4;c++){let l=c*a,f=d*i,u=Math.min(a,e-l),m=Math.min(i,n-f),g=l+u/2,y=f+m/2,h=t>=l&&t<l+u&&o>=f&&o<f+m;p.push({x0:l,y0:f,w:u,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),f=Math.hypot(c.cx-t,c.cy-o);return l-f})}var Fs=null;async function Wc(){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,Qa=null;async function jc(){let{getActiveDisplay:e}=await import("./screen_grid-2QLQELW7.js"),n=await e();if(fs&&Qa===n)return fs;Qa=n,fs={format:"png"};try{let t=await Za.listDisplays();t&&t.length>0&&(fs={format:"png",screen:(t[n]||t[0]).id})}catch{}return fs}var ii=async(e,n={})=>{let t=!!(process.env.SHOW_DEBUG_GRID||process.env.DEBUG_OCR||process.env.VERBOSE),o=performance.now(),s=o,r=u=>{if(!t)return;let m=performance.now(),g=(m-s).toFixed(0),y=(m-o).toFixed(0);console.log(`[Click Perf] +${g}ms (${y}ms total) -> ${u}`),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 u=i?Bi(i):null;r("Getting display options");let m=await jc();r("Taking desktop screenshot");let g=await Za(m);r("Getting image metadata");let y=await ps(g).metadata(),h=y.width||1920,b=y.height||1080,w=u?{x:Math.round(u.x*(h/1280)),y:Math.round(u.y*(b/720))}:{x:h/2,y:b/2},T=c.toLowerCase().trim();r("Acquiring OCR worker");let $=await Wc(),R=null,k="",S=u?220:500;if(u){r("Pass 1: Cropping target crop (3x zoom window, 2x upscale)");let _=Math.min(Math.round(h/3),h),E=Math.min(Math.round(b/3),b),x=Math.max(0,Math.min(h-_,w.x-Math.floor(_/2))),C=Math.max(0,Math.min(b-E,w.y-Math.floor(E/2))),M=await ps(g).extract({left:x,top:C,width:_,height:E}).toBuffer(),v=2,L=await oi(M,v),U=T.replace(/[^a-z0-9]/g,"_");await ni("cropped",`crop_${Date.now()}_${U}.png`,L),r("Pass 1: Running Tesseract OCR recognize on crop (PSM 11 - Sparse Text)"),await $.setParameters({tessedit_pageseg_mode:"11"});let{data:j}=await $.recognize(L,{},{tsv:!0,blocks:!0});if(r("Pass 1: OCR recognition finished, extracting matches"),j&&j.text){t&&console.log(`[Pass 1 OCR Read]: "${j.text.trim().replace(/\s+/g," ")}"`);let ee=si(j,T,x,C,v);if(ee.length>0){let X=ri(ee,w);X&&(X.containsPoint||X.dist<=S)&&(R=X,k="centered target crop OCR")}}}if(!R){r("Pass 2: Entering Full-Screen OCR (broad scan, PSM 3 - Auto)");let _=await oi(g,2),E=T.replace(/[^a-z0-9]/g,"_");await ni("fullscreen",`full_${Date.now()}_${E}.png`,_),r("Pass 2: Running Tesseract on full screen"),await $.setParameters({tessedit_pageseg_mode:"3"});let{data:x}=await $.recognize(_,{},{tsv:!0,blocks:!0});if(r("Pass 2: Full-screen OCR finished"),x&&x.text){let C=si(x,T,0,0,2);if(C.length>0){let M=ri(C,w);M&&(R=M,k="full-screen OCR")}}}if(!R){r("Pass 3: Entering Tiled OCR fallback (high-res 3x)");let _=Bc(h,b,w.x,w.y),E=T.replace(/[^a-z0-9]/g,"_");await $.setParameters({tessedit_pageseg_mode:"11"});for(let x=0;x<_.length;x++){let C=_[x];r(`Pass 3: Preprocessing tile ${x+1}/${_.length}`);let M=await ps(g).extract({left:C.x0,top:C.y0,width:C.w,height:C.h}).toBuffer(),v=await oi(M,3);await ni("tiles",`tile_${x+1}_${Date.now()}_${E}.png`,v),r(`Pass 3: Running Tesseract on tile ${x+1}`);let{data:L}=await $.recognize(v,{},{tsv:!0,blocks:!0});if(!L||!L.text)continue;let U=si(L,T,C.x0,C.y0,3);if(U.length>0){let j=ri(U,w);if(j){R=j,k=`tile ${x+1} OCR (${C.containsTarget?"target tile":`offset ${C.x0},${C.y0}`})`;break}}}}if(R){let _={x:Math.round(R.x*(1280/h)),y:Math.round(R.y*(720/b))};r(`Executing mouse click on matched target (${k})`);let E=await Bn("click",_,{button:d,clickType:p});return r("Click completed successfully"),`${E} (${k} for "${c}" at ${Math.round(R.dist)}px distance)`}else t&&console.log(`[OCR] No match found for "${c}". Falling back to gridId.`)}catch(u){t&&console.error("[OCR Error]",u)}r(`Executing mouse click on fallback gridId: ${l}`);let f=await Bn("click",l,{button:d,clickType:p});return r("Fallback click completed"),f};var ai=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 Bn("drag",o,{from:o,to:s})};var li=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 Bn("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 Wn("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 Wn("clear_input");if(s==="back"||s==="browser_back"||s==="browserBack")return await Wn("browser_back");if(s.includes(";")||s.includes("+")){let r=s.split(/[;+]/).map(a=>a.trim()).filter(Boolean);return await Wn("key_combination",r)}return await Wn("key_press",s)};var Bs=async(e,n={})=>"SUCCESS: Screen recapture requested. The latest gridded screenshot is provided for your next decision.";var Gc={web_search:vr,web_scrape:Ir,memory:Or,chat:Lr,view_file:ts,write_file:Dr,update_file:Ur,exec_command:wr,read_folder:Wr,write_pdf:jr,write_docx:Hr,search_keyword:ss,generate_image:Kr,saveSummary:rs,addMemScore:Fo,file_map:Xr,todo:is,Todo:is,goal:is,Goal:is,invokeSync:Jr,invoke:qa,getProgress:Qr,cancel:za,awaitSubagent:No,answerSubagent:Uo,steerSubagent:ls,computer_action:us,computer_use:us,ComputerAction:us,ComputerUse:us,click:ii,Click:ii,drag:ai,Drag:ai,scroll:li,Scroll:li,keyboard_typing:Ns,KeyboardTyping:Ns,keyboardtyping:Ns,key_press:Us,KeyPress:Us,keypress:Us,recapture_screen:Bs,RecaptureScreen:Bs,recapturescreen:Bs,invoke_sync:Jr,get_progress:Qr,await_subagent:No,answer_subagent:Uo,steer_subagent:ls,steer:ls,Steer:ls,ask:Ps,Ask:Ps,AskUser:Ps,WebSearch:vr,WebScrape:Ir,ReadFile:ts,ReadFolder:Wr,WriteFile:Dr,PatchFile:Ur,WritePDF:jr,WriteDoc:Hr,Run:wr,SearchKeyword:ss,CodeSearch:ss,code_search:ss,Memory:Or,Chat:Lr,GenerateImage:Kr,saveSumary:rs,SaveSummary:rs,SaveSumary:rs,add_mem_score:Fo,AddMemScore:Fo,addMemoryScore:Fo,AddMemoryScore:Fo,FileMap:Xr,answer:Uo,Answer:Uo,AnswerSubagent:Uo,await:No,Await:No,AwaitSubagent:No,EmergencyRollback:ei,emergency_rollback:ei},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=Gc[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 te from"path";import Fe from"fs";import Hc from"gradient-string";var ci=["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 el=[{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 tl=(e="Dark")=>{let n;e==="Mystery"||e==="Chaos"?(Ws||(Ws=el[Math.floor(Math.random()*el.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 qc=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",eg=(e=2)=>{let n=qc();return n==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)},tg=(e="...",n="Loading...",t="Dark")=>{let o=ci[Math.floor(Math.random()*ci.length)],s=tl(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=Hc(c).multiline(d.join(`
900
900
  `)).split(`
901
901
  `),f=u=>`${i}${u}${p}`;return`${l[0]}
902
902
  ${l[1]} ${r}Selected Provider: ${n}${p}
@@ -906,7 +906,7 @@ ${l[4]}
906
906
  ${l[5]} ${a}See /help for additional commands.${p}
907
907
  ${l[6]} ${f(o)}
908
908
  ${l[7]}
909
- `};import{WebSocket as js}from"ws";var Kt=null,Bo=!1,zc="ws://localhost:56832",di=[],Wo=null,ui=null,nl="2.0.0",sg=e=>{nl=e,ol()},fi=e=>{ui=e},ol=()=>{if(Kt||Bo)return;Bo=!0;let e=new js(zc);e.on("open",()=>{for(Kt=e,Bo=!1,Kt.send(JSON.stringify({command:"version",version:nl,pid:process.pid,ppid:process.ppid}));di.length>0;)Kt.send(JSON.stringify(di.shift()))}),e.on("message",n=>{try{let t=JSON.parse(n.toString());t.command==="contextResponse"&&Wo?(Wo(t.data),Wo=null):t.command==="securityResponse"&&ui&&ui(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)):(di.push(e),Bo||ol())},Hs=()=>Kt!==null&&Kt.readyState===js.OPEN,rg=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)}),sl=e=>{Gs({command:"open",filePath:e})},pi=(e,n,t)=>{Gs({command:"showDiff",filePath:e,originalContent:n,modifiedContent:t})},rl=(e,n)=>{Gs({command:"closeDiff",filePath:e,result:n})};import il from"path";import Kc from"fs";var Yc=e=>{try{return Kc.readdirSync(e,{withFileTypes:!0})}catch{return[]}},mi=(e,n,t=1,o=Yc,s=[],r=null)=>{let a=r||o(e),i=" ".repeat(t-1);if(a.length>100)return`${i}${il.basename(e)}/ (>100 files)
909
+ `};import{WebSocket as js}from"ws";var Xt=null,Bo=!1,zc="ws://localhost:56832",di=[],Wo=null,ui=null,nl="2.0.0",sg=e=>{nl=e,ol()},fi=e=>{ui=e},ol=()=>{if(Xt||Bo)return;Bo=!0;let e=new js(zc);e.on("open",()=>{for(Xt=e,Bo=!1,Xt.send(JSON.stringify({command:"version",version:nl,pid:process.pid,ppid:process.ppid}));di.length>0;)Xt.send(JSON.stringify(di.shift()))}),e.on("message",n=>{try{let t=JSON.parse(n.toString());t.command==="contextResponse"&&Wo?(Wo(t.data),Wo=null):t.command==="securityResponse"&&ui&&ui(t.result)}catch{}}),e.on("error",()=>{Bo=!1,Xt=null}),e.on("close",()=>{Bo=!1,Xt=null})},Gs=e=>{Xt&&Xt.readyState===js.OPEN?Xt.send(JSON.stringify(e)):(di.push(e),Bo||ol())},Hs=()=>Xt!==null&&Xt.readyState===js.OPEN,rg=e=>{Gs({command:"status",status:e})},xo=()=>new Promise(e=>{if(!Xt||Xt.readyState!==js.OPEN){e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]});return}Wo=e,Xt.send(JSON.stringify({command:"requestContext"})),setTimeout(()=>{Wo===e&&(e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]}),Wo=null)},1e3)}),sl=e=>{Gs({command:"open",filePath:e})},pi=(e,n,t)=>{Gs({command:"showDiff",filePath:e,originalContent:n,modifiedContent:t})},rl=(e,n)=>{Gs({command:"closeDiff",filePath:e,result:n})};import il from"path";import Kc from"fs";var Yc=e=>{try{return Kc.readdirSync(e,{withFileTypes:!0})}catch{return[]}},mi=(e,n,t=1,o=Yc,s=[],r=null)=>{let a=r||o(e),i=" ".repeat(t-1);if(a.length>100)return`${i}${il.basename(e)}/ (>100 files)
910
910
  `;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(", ")}]
911
911
  `);let f=c.filter(m=>m.isDirectory()).sort((m,g)=>m.name.localeCompare(g.name)),u=c.filter(m=>!m.isDirectory()).map(m=>m.name).sort();for(let m of f){let g=il.join(e,m.name);if(t>n)p+=`${i}${m.name}/ (max depth)
912
912
  `;else{let y=o(g);y.length>80?p+=`${i}${m.name}/ (>80 files)
@@ -918,25 +918,25 @@ ${l[7]}
918
918
  `:s(y).length>80?p+=`${t}${h}${u.name}${i} ...80+ files...
919
919
  `:(p+=`${t}${h}${u.name}${i}
920
920
  `,p+=gi(y,n,b,o+1,s,r)):p+=`${t}${h}${u.name}
921
- `}),p};import"@google/genai";var ct=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 w of t){let T=w.role==="user"?"user":"assistant",$=[];if(Array.isArray(w.parts)){for(let R of w.parts)if(R.text)$.push({type:"text",text:R.text});else if((R.inlineData||R.inline_data)&&a){let k=R.inlineData||R.inline_data,S=k.mimeType||k.mime_type||"image/jpeg",_=k.data;S.startsWith("image/")&&$.push({type:"image_url",image_url:{url:`data:${S};base64,${_}`}})}}else{let R=w.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 w={Low:"high",Medium:"high",Standard:"high",High:"max",xHigh:"max"};c.reasoning_effort=w[s]||"high",c.extra_body={thinking:{type:"enabled"}}}else c.extra_body={thinking:{type:"disabled"}};let l=await ct("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 w=await l.json().catch(()=>({}));throw new Error(`DeepSeek Error (${l.status}): ${w.error?.message||l.statusText}`)}let f=l.body.getReader(),u=new TextDecoder,m="",g=[],y=null,h=Date.now(),b=!1;for(;;){let{done:w,value:T}=await f.read();if(w){b&&(g.length>0||y)&&(yield{candidates:g.length>0?[{content:{parts:g}}]:[],usageMetadata:y});break}m+=u.decode(T,{stream:!0});let $=m.split(`
922
- `);m=$.pop();for(let R of $){let k=R.trim();if(!k||!k.startsWith("data: "))continue;let S=!1;if(k==="data: [DONE]")S=!0;else try{let _=JSON.parse(k.substring(6)),E=_.choices?.[0]?.delta,x=_.usage;if(_.choices?.[0]?.finish_reason&&(S=!0),x&&(y={totalTokenCount:x.total_tokens||x.prompt_tokens+x.completion_tokens,promptTokenCount:x.prompt_tokens||0,candidatesTokenCount:x.completion_tokens||0,cachedContentTokenCount:x.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:x.completion_tokens_details?.reasoning_tokens||0},b=!0),E){let C=E.reasoning_content||null;C&&(g.push({text:C,thought:!0}),b=!0),E.content&&(g.push({text:E.content}),b=!0)}}catch{}if((S||Date.now()-h>=150)&&b&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],h=Date.now(),b=!1),S)break}Date.now()-h>=150&&b&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],h=Date.now(),b=!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 S of t){let _=S.role==="user"?"user":"assistant",E=[];if(Array.isArray(S.parts)){for(let x of S.parts)if(x.text)E.push({type:"text",text:x.text});else if(x.inlineData&&a){let C=x.inlineData.mimeType,M=x.inlineData.data;C.startsWith("image/")&&E.push({type:"image_url",image_url:`data:${C};base64,${M}`})}}else{let x=S.text||"";x&&E.push({type:"text",text:x})}E.length>0&&c.push({role:_,content:E.length===1&&E[0].type==="text"?E[0].text:E})}let l={Fast:"none",Low:"none",Medium:"high",Standard:"high",High:"high",xHigh:"high"},f=`${e.slice(-5)}${d||""}${s}${n}`,u=await qs(f),m={model:n,messages:c,stream:!0,temperature:p,prompt_cache_key:u};s&&s!=="Fast"&&vo(n)&&(m.reasoning_effort=l[s]||"high");let g=await ct("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 S=await g.text().catch(()=>""),_=g.statusText;try{let E=JSON.parse(S);_=E.error?.message||E.message||JSON.stringify(E.detail||E)}catch{S&&(_=S)}throw new Error(`Mistral Error (${g.status}): ${JSON.stringify(_)}`)}let y=g.body.getReader(),h=new TextDecoder,b="",w=[],T=null,$=Date.now(),R=!1,k=S=>S?typeof S=="string"?Bn(S):Array.isArray(S)?S.map(k).filter(Boolean).join(""):typeof S=="object"&&S!==null?typeof S.text=="string"?Bn(S.text):typeof S.content=="string"?Bn(S.content):typeof S.thinking=="string"?Bn(S.thinking):typeof S.reasoning_content=="string"?Bn(S.reasoning_content):typeof S.reasoning=="string"?Bn(S.reasoning):typeof S.value=="string"?Bn(S.value):S.text?k(S.text):S.content?k(S.content):S.thinking?k(S.thinking):S.reasoning_content?k(S.reasoning_content):S.reasoning?k(S.reasoning):S.value?k(S.value):"":Bn(String(S)):"";for(;;){let{done:S,value:_}=await y.read();if(S){R&&(w.length>0||T)&&(yield{candidates:w.length>0?[{content:{parts:w}}]:[],usageMetadata:T});break}b+=h.decode(_,{stream:!0});let E=b.split(`
923
- `);b=E.pop();for(let x of E){let C=x.trim();if(!C||!C.startsWith("data: "))continue;let M=!1;if(C==="data: [DONE]")M=!0;else try{let v=JSON.parse(C.substring(6)),L=v.choices?.[0]?.delta,U=v.usage;if(v.choices?.[0]?.finish_reason&&(M=!0),U&&(T={totalTokenCount:U.total_tokens||(U.prompt_tokens||0)+(U.completion_tokens||0),promptTokenCount:U.prompt_tokens||0,candidatesTokenCount:U.completion_tokens||0,cachedContentTokenCount:U.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:U.completion_tokens_details?.reasoning_tokens||0},R=!0),L){let j=L.thinking||L.reasoning_content||L.reasoning,ee=k(j);ee&&(w.push({text:ee,thought:!0}),R=!0);let X=L.content||(!L.thinking&&!L.reasoning_content&&!L.reasoning?L.text:null);if(X)if(Array.isArray(X))for(let F of X)if(typeof F=="object"&&F!==null){let W=F.type==="thinking"||F.type==="reasoning"||!!F.thought,ne=k(F);ne&&(w.push({text:ne,...W?{thought:!0}:{}}),R=!0)}else{let W=k(F);W&&(w.push({text:W}),R=!0)}else if(typeof X=="object"&&X!==null){let F=X.type==="thinking"||X.type==="reasoning"||!!X.thought,W=k(X);W&&(w.push({text:W,...F?{thought:!0}:{}}),R=!0)}else{let F=k(X);F&&(w.push({text:F}),R=!0)}}}catch{}if((M||Date.now()-$>=150)&&R&&(yield{candidates:w.length>0?[{content:{parts:[...w]}}]:[],usageMetadata:T},w=[],$=Date.now(),R=!1),M)break}Date.now()-$>=150&&R&&(yield{candidates:w.length>0?[{content:{parts:[...w]}}]:[],usageMetadata:T},w=[],$=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(ne=>{let Me=ne.role==="model"?"assistant":"user",O=[];Array.isArray(ne.parts)&&ne.parts.forEach(B=>{if(B.text)O.push({type:"text",text:B.text});else if(B.inlineData&&a){let J=B.inlineData.mimeType,Q=B.inlineData.data;J.startsWith("image/")&&xt(n)&&O.push({type:"image_url",image_url:{url:`data:${J};base64,${Q}`}})}}),d.push({role:Me,content:O.length===1&&O[0].type==="text"?O[0].text:O})});let l={Fast:"Fast",Low:"Fast",Medium:"Standard",Standard:"Standard",High:"High",xHigh:"High"}[s]||"High",f=l!=="Fast",u=n.includes("kimi"),m=n.includes("gemma"),g=n.includes("deepseek"),y=n.includes("glm"),h=n.includes("mistral"),b=n.includes("minimax"),w=n.includes("gpt"),T=n.includes("qwen"),$=n.includes("nemotron"),R=n.includes("llama-3"),k=n.includes("seed"),S=n.includes("poolside"),_=n.includes("thinkingmachines")||n.includes("muse"),E=R,x=null,C={Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},M={Fast:"64",Low:"64",Medium:"4096",Standard:"4096",High:"16384",xHigh:"16384"},v={Fast:"none",Low:"minimal",Medium:"medium",Standard:"medium",High:"max",xHigh:"max"},L=b||g||S||_?16384:32768;L=process.env.NVIDIA_BASE_URL?1024:L,L=x?1024:L;let U={model:n,messages:d,max_tokens:L,stream:!0,stream_options:{include_usage:!0},temperature:p,...w&&{thinking:C[s]||"high"}};if(!(process.env.NVIDIA_BASE_URL||E||x))if(u)U.chat_template_kwargs={thinking:f};else if(m)U.chat_template_kwargs={enable_thinking:f};else if(g)if(f){let ne=l==="High"?"max":"high";U.chat_template_kwargs={thinking:!0,reasoning_effort:ne}}else U.chat_template_kwargs={thinking:!1};else y?U.chat_template_kwargs={enable_thinking:f,clear_thinking:!f}:h?U.reasoning_effort=f?"high":"none":b&&n.includes("minimax-m3")?U.chat_template_kwargs={thinking_mode:f?"enabled":"disabled"}:T?U.chat_template_kwargs={enable_thinking:f}:$?l==="High"?U.chat_template_kwargs={enable_thinking:!0}:l==="Standard"?U.chat_template_kwargs={enable_thinking:!0,medium_effort:!0}:U.chat_template_kwargs={enable_thinking:!1}:k?f&&(U.extra_body={thinking_budget:parseInt(M[l]??"4096")}):S?U.chat_template_kwargs={enable_thinking:f}:_&&(U.reasoning_effort=v[l]||"medium");let j=0,ee=6,X=!1,F=process.env.NVIDIA_BASE_URL||"https://integrate.api.nvidia.com/v1/chat/completions",W=process.env.NVIDIA_API_KEY&&process.env.NVIDIA_BASE_URL?process.env.NVIDIA_API_KEY:e;for(F.endsWith("/chat/completions")||(F=F.replace(/\/+$/,"")+"/chat/completions");j<ee;){j++;try{let ne=await ct(F,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${W}`},body:JSON.stringify(U),signal:i});if(!ne.ok){let Ze=await ne.text().catch(()=>""),dt=ne.statusText;try{let yt=JSON.parse(Ze);dt=yt.error?.message||yt.message||JSON.stringify(yt.detail||yt)}catch{Ze&&(dt=Ze)}let He=new Error(`NVIDIA API Error (${ne.status}): ${dt}`);throw He.status=ne.status,He}let Me=ne.body.getReader(),O=new TextDecoder,B="",J=[],Q=null,We=Date.now(),Ne=!1;for(;;){let{done:Ze,value:dt}=await Me.read();if(Ze){Ne&&(J.length>0||Q)&&(yield{candidates:J.length>0?[{content:{parts:J}}]:[],usageMetadata:Q},X=!0);break}B+=O.decode(dt,{stream:!0});let He=B.split(`
924
- `);B=He.pop();let yt=!1;for(let To of He){let St=To.trim();if(St){if(St==="data: [DONE]"){yt=!0;break}if(St.startsWith("data: ")){let Ve;try{Ve=JSON.parse(St.substring(6))}catch{continue}if(Ve.error)throw new Error(`NVIDIA Stream Error: ${Ve.error.message||JSON.stringify(Ve.error)}`);try{let $t=Ve.usage;$t&&(Q={totalTokenCount:$t.total_tokens||$t.prompt_tokens+$t.completion_tokens,promptTokenCount:$t.prompt_tokens||0,candidatesTokenCount:$t.completion_tokens||0,cachedContentTokenCount:$t.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:($t.completion_tokens_details?.reasoning_tokens||0)+($t.completion_tokens_details?.thoughts_tokens||0)},Ne=!0);let qe=Ve.choices?.[0]?.delta?.reasoning||Ve.choices?.[0]?.delta?.reasoning_content||"",fe=Ve.choices?.[0]?.delta?.content||"";qe&&(J.push({text:qe,thought:!0}),Ne=!0),fe&&(J.push({text:fe}),Ne=!0)}catch{}}}}if((yt||Date.now()-We>=350)&&Ne&&(yield{candidates:J.length>0?[{content:{parts:[...J]}}]:[],usageMetadata:Q},X=!0,J=[],We=Date.now(),Ne=!1),yt)break}break}catch(ne){if(X||j>=ee)throw ne;await new Promise(Me=>setTimeout(Me,3500))}}},al=async function*(e,n){let t=[],o=null,s=!1,r=null,a=f=>{if(t.push(f),o){let u=o;o=null,u()}},i=n.split("/").pop();i=i.replace("llama-3.3","llama-3_3");let p=`https://api.ngc.nvidia.com/v2/predict/queues/models/qc69jvmznzxy/${i}`,d=!1,c=null,l=async()=>{try{let f=await fetch(p);if(f.ok){let u=await f.json();if(u&&u.queues&&u.queues[0]&&typeof u.queues[0].queueDepth=="number"){let m=u.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 f=e[Symbol.asyncIterator]();for(;;){let{value:u,done:m}=await f.next();if(m)break;d=!0,c&&(clearInterval(c),c=null),a({value:u,done:!1})}s=!0,a(null)}catch(f){if(r=f,c&&(clearInterval(c),c=null),o){let u=o;o=null,u()}}})();try{for(;;){if(r)throw r;if(t.length>0){let f=t.shift();if(f===null&&s)break;yield f.value}else{if(s)break;await new Promise(f=>{o=f})}}}finally{c&&(clearInterval(c),c=null)}};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 x of t){let C=x.role==="user"?"user":"assistant",M=[];if(Array.isArray(x.parts)){for(let v of x.parts)if(v.text)M.push({type:"text",text:v.text});else if(v.inlineData&&a){let L=v.inlineData.mimeType,U=v.inlineData.data;L.startsWith("image/")?M.push({type:"image_url",image_url:{url:`data:${L};base64,${U}`}}):M.push({type:"file",file:{filename:v.filename||"file",file_data:`data:${L};base64,${U}`}})}}else{let v=x.text||"";v&&M.push({type:"text",text:v})}c.push({role:C,content:M.length===1&&M[0].type==="text"?M[0].text:M})}let l={Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},f=["free","nitro","floor","exact","extended","beta","online"],u=n,m=null;if(n.includes(":")){let x=n.split(":"),C=x[x.length-1].toLowerCase().trim();if(f.includes(C))u=n.trim();else{let M=x.pop().trim();u=x.join(":").trim(),M&&(m={order:[M],allow_fallbacks:!1})}}let g=`${e.slice(-5)}${d||""}${s}${u}${m?JSON.stringify(m):""}`,y=await qs(g),h={model:u,messages:c,stream:!0,temperature:p,cache_control:{type:"ephemeral"},session_id:y};m&&(h.provider=m);let b=l[s];b&&s!=="Fast"&&(h.reasoning_effort=b);let w=await ct("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(!w.ok){let x=await w.json().catch(()=>({})),C=x.error?.metadata?.raw||x.error?.message||(typeof x.error=="string"?x.error:"")||w.statusText||"Unknown error";throw new Error(`OpenRouter Error (${w.status}): ${C}`)}let T=w.body.getReader(),$=new TextDecoder,R="",k=[],S=null,_=Date.now(),E=!1;for(;;){let{done:x,value:C}=await T.read();if(x){E&&(k.length>0||S)&&(yield{candidates:k.length>0?[{content:{parts:k}}]:[],usageMetadata:S});break}R+=$.decode(C,{stream:!0});let M=R.split(`
921
+ `}),p};import"@google/genai";var lt=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 jn=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 w of t){let T=w.role==="user"?"user":"assistant",$=[];if(Array.isArray(w.parts)){for(let R of w.parts)if(R.text)$.push({type:"text",text:R.text});else if((R.inlineData||R.inline_data)&&a){let k=R.inlineData||R.inline_data,S=k.mimeType||k.mime_type||"image/jpeg",_=k.data;S.startsWith("image/")&&$.push({type:"image_url",image_url:{url:`data:${S};base64,${_}`}})}}else{let R=w.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 w={Low:"high",Medium:"high",Standard:"high",High:"max",xHigh:"max"};c.reasoning_effort=w[s]||"high",c.extra_body={thinking:{type:"enabled"}}}else c.extra_body={thinking:{type:"disabled"}};let l=await lt("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 w=await l.json().catch(()=>({}));throw new Error(`DeepSeek Error (${l.status}): ${w.error?.message||l.statusText}`)}let f=l.body.getReader(),u=new TextDecoder,m="",g=[],y=null,h=Date.now(),b=!1;for(;;){let{done:w,value:T}=await f.read();if(w){b&&(g.length>0||y)&&(yield{candidates:g.length>0?[{content:{parts:g}}]:[],usageMetadata:y});break}m+=u.decode(T,{stream:!0});let $=m.split(`
922
+ `);m=$.pop();for(let R of $){let k=R.trim();if(!k||!k.startsWith("data: "))continue;let S=!1;if(k==="data: [DONE]")S=!0;else try{let _=JSON.parse(k.substring(6)),E=_.choices?.[0]?.delta,x=_.usage;if(_.choices?.[0]?.finish_reason&&(S=!0),x&&(y={totalTokenCount:x.total_tokens||x.prompt_tokens+x.completion_tokens,promptTokenCount:x.prompt_tokens||0,candidatesTokenCount:x.completion_tokens||0,cachedContentTokenCount:x.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:x.completion_tokens_details?.reasoning_tokens||0},b=!0),E){let C=E.reasoning_content||null;C&&(g.push({text:C,thought:!0}),b=!0),E.content&&(g.push({text:E.content}),b=!0)}}catch{}if((S||Date.now()-h>=150)&&b&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],h=Date.now(),b=!1),S)break}Date.now()-h>=150&&b&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],h=Date.now(),b=!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 S of t){let _=S.role==="user"?"user":"assistant",E=[];if(Array.isArray(S.parts)){for(let x of S.parts)if(x.text)E.push({type:"text",text:x.text});else if(x.inlineData&&a){let C=x.inlineData.mimeType,M=x.inlineData.data;C.startsWith("image/")&&E.push({type:"image_url",image_url:`data:${C};base64,${M}`})}}else{let x=S.text||"";x&&E.push({type:"text",text:x})}E.length>0&&c.push({role:_,content:E.length===1&&E[0].type==="text"?E[0].text:E})}let l={Fast:"none",Low:"none",Medium:"high",Standard:"high",High:"high",xHigh:"high"},f=`${e.slice(-5)}${d||""}${s}${n}`,u=await qs(f),m={model:n,messages:c,stream:!0,temperature:p,prompt_cache_key:u};s&&s!=="Fast"&&vo(n)&&(m.reasoning_effort=l[s]||"high");let g=await lt("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 S=await g.text().catch(()=>""),_=g.statusText;try{let E=JSON.parse(S);_=E.error?.message||E.message||JSON.stringify(E.detail||E)}catch{S&&(_=S)}throw new Error(`Mistral Error (${g.status}): ${JSON.stringify(_)}`)}let y=g.body.getReader(),h=new TextDecoder,b="",w=[],T=null,$=Date.now(),R=!1,k=S=>S?typeof S=="string"?jn(S):Array.isArray(S)?S.map(k).filter(Boolean).join(""):typeof S=="object"&&S!==null?typeof S.text=="string"?jn(S.text):typeof S.content=="string"?jn(S.content):typeof S.thinking=="string"?jn(S.thinking):typeof S.reasoning_content=="string"?jn(S.reasoning_content):typeof S.reasoning=="string"?jn(S.reasoning):typeof S.value=="string"?jn(S.value):S.text?k(S.text):S.content?k(S.content):S.thinking?k(S.thinking):S.reasoning_content?k(S.reasoning_content):S.reasoning?k(S.reasoning):S.value?k(S.value):"":jn(String(S)):"";for(;;){let{done:S,value:_}=await y.read();if(S){R&&(w.length>0||T)&&(yield{candidates:w.length>0?[{content:{parts:w}}]:[],usageMetadata:T});break}b+=h.decode(_,{stream:!0});let E=b.split(`
923
+ `);b=E.pop();for(let x of E){let C=x.trim();if(!C||!C.startsWith("data: "))continue;let M=!1;if(C==="data: [DONE]")M=!0;else try{let v=JSON.parse(C.substring(6)),L=v.choices?.[0]?.delta,U=v.usage;if(v.choices?.[0]?.finish_reason&&(M=!0),U&&(T={totalTokenCount:U.total_tokens||(U.prompt_tokens||0)+(U.completion_tokens||0),promptTokenCount:U.prompt_tokens||0,candidatesTokenCount:U.completion_tokens||0,cachedContentTokenCount:U.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:U.completion_tokens_details?.reasoning_tokens||0},R=!0),L){let j=L.thinking||L.reasoning_content||L.reasoning,ee=k(j);ee&&(w.push({text:ee,thought:!0}),R=!0);let X=L.content||(!L.thinking&&!L.reasoning_content&&!L.reasoning?L.text:null);if(X)if(Array.isArray(X))for(let F of X)if(typeof F=="object"&&F!==null){let W=F.type==="thinking"||F.type==="reasoning"||!!F.thought,ne=k(F);ne&&(w.push({text:ne,...W?{thought:!0}:{}}),R=!0)}else{let W=k(F);W&&(w.push({text:W}),R=!0)}else if(typeof X=="object"&&X!==null){let F=X.type==="thinking"||X.type==="reasoning"||!!X.thought,W=k(X);W&&(w.push({text:W,...F?{thought:!0}:{}}),R=!0)}else{let F=k(X);F&&(w.push({text:F}),R=!0)}}}catch{}if((M||Date.now()-$>=150)&&R&&(yield{candidates:w.length>0?[{content:{parts:[...w]}}]:[],usageMetadata:T},w=[],$=Date.now(),R=!1),M)break}Date.now()-$>=150&&R&&(yield{candidates:w.length>0?[{content:{parts:[...w]}}]:[],usageMetadata:T},w=[],$=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(ne=>{let Me=ne.role==="model"?"assistant":"user",O=[];Array.isArray(ne.parts)&&ne.parts.forEach(B=>{if(B.text)O.push({type:"text",text:B.text});else if(B.inlineData&&a){let J=B.inlineData.mimeType,Q=B.inlineData.data;J.startsWith("image/")&&bt(n)&&O.push({type:"image_url",image_url:{url:`data:${J};base64,${Q}`}})}}),d.push({role:Me,content:O.length===1&&O[0].type==="text"?O[0].text:O})});let l={Fast:"Fast",Low:"Fast",Medium:"Standard",Standard:"Standard",High:"High",xHigh:"High"}[s]||"High",f=l!=="Fast",u=n.includes("kimi"),m=n.includes("gemma"),g=n.includes("deepseek"),y=n.includes("glm"),h=n.includes("mistral"),b=n.includes("minimax"),w=n.includes("gpt"),T=n.includes("qwen"),$=n.includes("nemotron"),R=n.includes("llama-3"),k=n.includes("seed"),S=n.includes("poolside"),_=n.includes("thinkingmachines")||n.includes("muse"),E=R,x=null,C={Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},M={Fast:"64",Low:"64",Medium:"4096",Standard:"4096",High:"16384",xHigh:"16384"},v={Fast:"none",Low:"minimal",Medium:"medium",Standard:"medium",High:"max",xHigh:"max"},L=b||g||S||_?16384:32768;L=process.env.NVIDIA_BASE_URL?1024:L,L=x?1024:L;let U={model:n,messages:d,max_tokens:L,stream:!0,stream_options:{include_usage:!0},temperature:p,...w&&{thinking:C[s]||"high"}};if(!(process.env.NVIDIA_BASE_URL||E||x))if(u)U.chat_template_kwargs={thinking:f};else if(m)U.chat_template_kwargs={enable_thinking:f};else if(g)if(f){let ne=l==="High"?"max":"high";U.chat_template_kwargs={thinking:!0,reasoning_effort:ne}}else U.chat_template_kwargs={thinking:!1};else y?U.chat_template_kwargs={enable_thinking:f,clear_thinking:!f}:h?U.reasoning_effort=f?"high":"none":b&&n.includes("minimax-m3")?U.chat_template_kwargs={thinking_mode:f?"enabled":"disabled"}:T?U.chat_template_kwargs={enable_thinking:f}:$?l==="High"?U.chat_template_kwargs={enable_thinking:!0}:l==="Standard"?U.chat_template_kwargs={enable_thinking:!0,medium_effort:!0}:U.chat_template_kwargs={enable_thinking:!1}:k?f&&(U.extra_body={thinking_budget:parseInt(M[l]??"4096")}):S?U.chat_template_kwargs={enable_thinking:f}:_&&(U.reasoning_effort=v[l]||"medium");let j=0,ee=6,X=!1,F=process.env.NVIDIA_BASE_URL||"https://integrate.api.nvidia.com/v1/chat/completions",W=process.env.NVIDIA_API_KEY&&process.env.NVIDIA_BASE_URL?process.env.NVIDIA_API_KEY:e;for(F.endsWith("/chat/completions")||(F=F.replace(/\/+$/,"")+"/chat/completions");j<ee;){j++;try{let ne=await lt(F,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${W}`},body:JSON.stringify(U),signal:i});if(!ne.ok){let Ze=await ne.text().catch(()=>""),ct=ne.statusText;try{let wt=JSON.parse(Ze);ct=wt.error?.message||wt.message||JSON.stringify(wt.detail||wt)}catch{Ze&&(ct=Ze)}let He=new Error(`NVIDIA API Error (${ne.status}): ${ct}`);throw He.status=ne.status,He}let Me=ne.body.getReader(),O=new TextDecoder,B="",J=[],Q=null,We=Date.now(),Ne=!1;for(;;){let{done:Ze,value:ct}=await Me.read();if(Ze){Ne&&(J.length>0||Q)&&(yield{candidates:J.length>0?[{content:{parts:J}}]:[],usageMetadata:Q},X=!0);break}B+=O.decode(ct,{stream:!0});let He=B.split(`
924
+ `);B=He.pop();let wt=!1;for(let To of He){let Tt=To.trim();if(Tt){if(Tt==="data: [DONE]"){wt=!0;break}if(Tt.startsWith("data: ")){let Ve;try{Ve=JSON.parse(Tt.substring(6))}catch{continue}if(Ve.error)throw new Error(`NVIDIA Stream Error: ${Ve.error.message||JSON.stringify(Ve.error)}`);try{let At=Ve.usage;At&&(Q={totalTokenCount:At.total_tokens||At.prompt_tokens+At.completion_tokens,promptTokenCount:At.prompt_tokens||0,candidatesTokenCount:At.completion_tokens||0,cachedContentTokenCount:At.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:(At.completion_tokens_details?.reasoning_tokens||0)+(At.completion_tokens_details?.thoughts_tokens||0)},Ne=!0);let qe=Ve.choices?.[0]?.delta?.reasoning||Ve.choices?.[0]?.delta?.reasoning_content||"",fe=Ve.choices?.[0]?.delta?.content||"";qe&&(J.push({text:qe,thought:!0}),Ne=!0),fe&&(J.push({text:fe}),Ne=!0)}catch{}}}}if((wt||Date.now()-We>=350)&&Ne&&(yield{candidates:J.length>0?[{content:{parts:[...J]}}]:[],usageMetadata:Q},X=!0,J=[],We=Date.now(),Ne=!1),wt)break}break}catch(ne){if(X||j>=ee)throw ne;await new Promise(Me=>setTimeout(Me,3500))}}},al=async function*(e,n){let t=[],o=null,s=!1,r=null,a=f=>{if(t.push(f),o){let u=o;o=null,u()}},i=n.split("/").pop();i=i.replace("llama-3.3","llama-3_3");let p=`https://api.ngc.nvidia.com/v2/predict/queues/models/qc69jvmznzxy/${i}`,d=!1,c=null,l=async()=>{try{let f=await fetch(p);if(f.ok){let u=await f.json();if(u&&u.queues&&u.queues[0]&&typeof u.queues[0].queueDepth=="number"){let m=u.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 f=e[Symbol.asyncIterator]();for(;;){let{value:u,done:m}=await f.next();if(m)break;d=!0,c&&(clearInterval(c),c=null),a({value:u,done:!1})}s=!0,a(null)}catch(f){if(r=f,c&&(clearInterval(c),c=null),o){let u=o;o=null,u()}}})();try{for(;;){if(r)throw r;if(t.length>0){let f=t.shift();if(f===null&&s)break;yield f.value}else{if(s)break;await new Promise(f=>{o=f})}}}finally{c&&(clearInterval(c),c=null)}};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 x of t){let C=x.role==="user"?"user":"assistant",M=[];if(Array.isArray(x.parts)){for(let v of x.parts)if(v.text)M.push({type:"text",text:v.text});else if(v.inlineData&&a){let L=v.inlineData.mimeType,U=v.inlineData.data;L.startsWith("image/")?M.push({type:"image_url",image_url:{url:`data:${L};base64,${U}`}}):M.push({type:"file",file:{filename:v.filename||"file",file_data:`data:${L};base64,${U}`}})}}else{let v=x.text||"";v&&M.push({type:"text",text:v})}c.push({role:C,content:M.length===1&&M[0].type==="text"?M[0].text:M})}let l={Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},f=["free","nitro","floor","exact","extended","beta","online"],u=n,m=null;if(n.includes(":")){let x=n.split(":"),C=x[x.length-1].toLowerCase().trim();if(f.includes(C))u=n.trim();else{let M=x.pop().trim();u=x.join(":").trim(),M&&(m={order:[M],allow_fallbacks:!1})}}let g=`${e.slice(-5)}${d||""}${s}${u}${m?JSON.stringify(m):""}`,y=await qs(g),h={model:u,messages:c,stream:!0,temperature:p,cache_control:{type:"ephemeral"},session_id:y};m&&(h.provider=m);let b=l[s];b&&s!=="Fast"&&(h.reasoning_effort=b);let w=await lt("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(!w.ok){let x=await w.json().catch(()=>({})),C=x.error?.metadata?.raw||x.error?.message||(typeof x.error=="string"?x.error:"")||w.statusText||"Unknown error";throw new Error(`OpenRouter Error (${w.status}): ${C}`)}let T=w.body.getReader(),$=new TextDecoder,R="",k=[],S=null,_=Date.now(),E=!1;for(;;){let{done:x,value:C}=await T.read();if(x){E&&(k.length>0||S)&&(yield{candidates:k.length>0?[{content:{parts:k}}]:[],usageMetadata:S});break}R+=$.decode(C,{stream:!0});let M=R.split(`
925
925
  `);R=M.pop();for(let v of M){let L=v.trim();if(!L||!L.startsWith("data: "))continue;let U=!1;if(L==="data: [DONE]")U=!0;else try{let j=JSON.parse(L.substring(6));if(j.error){let F=j.error.metadata?.raw||j.error.message||JSON.stringify(j.error);throw new Error(`OpenRouter Stream Error: ${F}`)}let ee=j.choices?.[0]?.delta,X=j.usage;if(j.choices?.[0]?.finish_reason&&(U=!0),X&&(S={totalTokenCount:X.total_tokens||(X.prompt_tokens||0)+(X.completion_tokens||0),promptTokenCount:X.prompt_tokens||0,candidatesTokenCount:X.completion_tokens||0,cachedContentTokenCount:X.prompt_tokens_details?.cached_tokens||X.prompt_tokens_details?.cache_read_input_tokens||X.cache_read_input_tokens||0,thoughtsTokenCount:X.completion_tokens_details?.reasoning_tokens||0},E=!0),ee){let F=ee.reasoning||(ee.reasoning_details?ee.reasoning_details.map(W=>W.text).join(""):null);F&&(k.push({text:F,thought:!0}),E=!0),ee.content&&(k.push({text:ee.content}),E=!0)}}catch(j){if(j.message&&j.message.startsWith("OpenRouter Stream Error:"))throw j}if((U||Date.now()-_>=150)&&E&&(yield{candidates:k.length>0?[{content:{parts:[...k]}}]:[],usageMetadata:S},k=[],_=Date.now(),E=!1),U)break}}};import{Ollama as Jc}from"ollama";var yi=async function*(e,n,t,o,s,r,a,i,p=1,d="Cloud"){let c=[];o&&c.push({role:"system",content:o});for(let k of t){let S=k.role==="user"?"user":"assistant",_="",E=[];if(Array.isArray(k.parts)){_=k.parts.map(x=>x.text||"").filter(Boolean).join(`
926
- `);for(let x of k.parts){let C=x.inlineData||x.inline_data;C&&C.data&&E.push(C.data)}}else _=k.text||"";if(_||E.length>0){let x={role:S,content:_};E.length>0&&(x.images=E),c.push(x)}}let l=d==="Local"||!e||e==="LOCAL",u={host:l?process.env.OLLAMA_HOST||"http://127.0.0.1:11434":process.env.OLLAMA_HOST||"https://ollama.com"};!l&&e&&(u.headers={Authorization:"Bearer "+e});let m=new Jc(u),g=[],y=null,h=Date.now(),b=!1,w={Fast:!1,Low:"medium",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},T=w[s]!==void 0?w[s]:!0,$={model:n,messages:c,stream:!0,think:T,keep_alive:"10m",options:{temperature:p}},R=await m.chat($);for await(let k of R){if(i?.aborted)throw new DOMException("The user aborted a request.","AbortError");if(k.message?.thinking&&(g.push({text:k.message.thinking,thought:!0}),b=!0),k.message?.content&&(g.push({text:k.message.content}),b=!0),k.done){let S=k.prompt_cached_count||0;if(!S&&k.prompt_eval_count){let _=k.prompt_eval_duration||0;_>0&&_<5e7&&(S=k.prompt_eval_count)}y={totalTokenCount:(k.prompt_eval_count||0)+(k.eval_count||0),promptTokenCount:k.prompt_eval_count||0,candidatesTokenCount:k.eval_count||0,cachedContentTokenCount:S,thoughtsTokenCount:0},b=!0}(k.done||Date.now()-h>=150&&b)&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],h=Date.now(),b=!1)}b&&(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 k of T.parts)if(k.text)R.push({type:"text",text:k.text});else if(k.inlineData&&a){let S=k.inlineData.mimeType,_=k.inlineData.data;S.startsWith("image/")&&R.push({type:"image_url",image_url:{url:`data:${S};base64,${_}`}})}}else{let k=T.text||"";k&&R.push({type:"text",text:k})}d.push({role:$,content:R.length===1&&R[0].type==="text"?R[0].text:R})}let c={Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},l={model:n,messages:d,stream:!0,stream_options:{include_usage:!0},temperature:p,max_completion_tokens:32768};c[s]&&(l.reasoning_effort=c[s]);let f=await ct("https://crof.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(l),signal:i});if(!f.ok){let T=await f.json().catch(()=>({}));throw new Error(`CrofAI Error (${f.status}): ${T.error?.message||f.statusText}`)}let u=f.body.getReader(),m=new TextDecoder,g="",y=[],h=null,b=Date.now(),w=!1;for(;;){let{done:T,value:$}=await u.read();if(T){w&&(y.length>0||h)&&(yield{candidates:y.length>0?[{content:{parts:y}}]:[],usageMetadata:h});break}g+=m.decode($,{stream:!0});let R=g.split(`
926
+ `);for(let x of k.parts){let C=x.inlineData||x.inline_data;C&&C.data&&E.push(C.data)}}else _=k.text||"";if(_||E.length>0){let x={role:S,content:_};E.length>0&&(x.images=E),c.push(x)}}let l=d==="Local"||!e||e==="LOCAL",u={host:l?process.env.OLLAMA_HOST||"http://127.0.0.1:11434":process.env.OLLAMA_HOST||"https://ollama.com"};!l&&e&&(u.headers={Authorization:"Bearer "+e});let m=new Jc(u),g=[],y=null,h=Date.now(),b=!1,w={Fast:!1,Low:"medium",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},T=w[s]!==void 0?w[s]:!0,$={model:n,messages:c,stream:!0,think:T,keep_alive:"10m",options:{temperature:p}},R=await m.chat($);for await(let k of R){if(i?.aborted)throw new DOMException("The user aborted a request.","AbortError");if(k.message?.thinking&&(g.push({text:k.message.thinking,thought:!0}),b=!0),k.message?.content&&(g.push({text:k.message.content}),b=!0),k.done){let S=k.prompt_cached_count||0;if(!S&&k.prompt_eval_count){let _=k.prompt_eval_duration||0;_>0&&_<5e7&&(S=k.prompt_eval_count)}y={totalTokenCount:(k.prompt_eval_count||0)+(k.eval_count||0),promptTokenCount:k.prompt_eval_count||0,candidatesTokenCount:k.eval_count||0,cachedContentTokenCount:S,thoughtsTokenCount:0},b=!0}(k.done||Date.now()-h>=150&&b)&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],h=Date.now(),b=!1)}b&&(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 k of T.parts)if(k.text)R.push({type:"text",text:k.text});else if(k.inlineData&&a){let S=k.inlineData.mimeType,_=k.inlineData.data;S.startsWith("image/")&&R.push({type:"image_url",image_url:{url:`data:${S};base64,${_}`}})}}else{let k=T.text||"";k&&R.push({type:"text",text:k})}d.push({role:$,content:R.length===1&&R[0].type==="text"?R[0].text:R})}let c={Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},l={model:n,messages:d,stream:!0,stream_options:{include_usage:!0},temperature:p,max_completion_tokens:32768};c[s]&&(l.reasoning_effort=c[s]);let f=await lt("https://crof.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(l),signal:i});if(!f.ok){let T=await f.json().catch(()=>({}));throw new Error(`CrofAI Error (${f.status}): ${T.error?.message||f.statusText}`)}let u=f.body.getReader(),m=new TextDecoder,g="",y=[],h=null,b=Date.now(),w=!1;for(;;){let{done:T,value:$}=await u.read();if(T){w&&(y.length>0||h)&&(yield{candidates:y.length>0?[{content:{parts:y}}]:[],usageMetadata:h});break}g+=m.decode($,{stream:!0});let R=g.split(`
927
927
  `);g=R.pop();for(let k of R){let S=k.trim();if(!S||!S.startsWith("data: "))continue;let _=!1;if(S==="data: [DONE]")_=!0;else try{let E=JSON.parse(S.substring(6)),x=E.choices?.[0]?.delta,C=E.usage;if(E.choices?.[0]?.finish_reason&&(_=!0),C&&(h={totalTokenCount:C.total_tokens||(C.prompt_tokens||0)+(C.completion_tokens||0),promptTokenCount:C.prompt_tokens||0,candidatesTokenCount:C.completion_tokens||0,cachedContentTokenCount:C.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:C.completion_tokens_details?.reasoning_tokens||C.reasoning_tokens||0},w=!0),x){let M=x.reasoning_content||null;M&&(y.push({text:M,thought:!0}),w=!0),x.content&&(y.push({text:x.content}),w=!0)}}catch{}if((_||Date.now()-b>=150)&&w&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:h},y=[],b=Date.now(),w=!1),_)break}Date.now()-b>=150&&w&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:h},y=[],b=Date.now(),w=!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 k of t){let S=k.role==="user"?"user":"assistant",_="";if(Array.isArray(k.parts))for(let E of k.parts)E.text&&(_+=(_?`
928
- `:"")+E.text);else _=k.text||"";d.push({role:S,content:_})}let c={Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},l=n&&n.toLowerCase().includes("qwen3.8-27b"),f=n&&(n.toLowerCase().includes("qwen3.8-27b")||n.toLowerCase().includes("qwen3.6-35b-a3b-fp8")),u={model:n,messages:d.filter(k=>k.content&&String(k.content).trim().length>0),stream:!0,stream_options:{include_usage:!0},temperature:p};l||(u.stream_options={include_usage:!0},c[s]&&(u.reasoning_effort=c[s]));let m=await ct("https://model.inferx.net/endpoints/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(u),signal:i});if(!m.ok){let k=await m.text().catch(()=>""),S="";try{let _=JSON.parse(k);S=_.error?.message||_.error?.detail||_.message||_.detail||(typeof _.error=="string"?_.error:"")||(k&&k!=="{}"?k:"")}catch{S=k}throw(!S||S==="{}")&&(S=m.statusText||"Unknown error"),new Error(`InferX Error (${m.status}): ${S}`)}let g=m.body.getReader(),y=new TextDecoder,h="",b=[],w=null,T=Date.now(),$=!1,R=!0;for(;;){let{done:k,value:S}=await g.read();if(k){$&&(b.length>0||w)&&(yield{candidates:b.length>0?[{content:{parts:b}}]:[],usageMetadata:w});break}h+=y.decode(S,{stream:!0});let _=h.split(`
929
- `);h=_.pop();for(let E of _){let x=E.trim();if(!x||!x.startsWith("data: "))continue;let C=!1;if(x==="data: [DONE]")C=!0;else try{let M=JSON.parse(x.substring(6)),v=M.choices?.[0]?.delta,L=M.usage;if(L&&(w={totalTokenCount:L.total_tokens||(L.prompt_tokens||0)+(L.completion_tokens||0),promptTokenCount:L.prompt_tokens||0,candidatesTokenCount:L.completion_tokens||0,cachedContentTokenCount:L.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:L.completion_tokens_details?.reasoning_tokens||L.reasoning_tokens||0},$=!0),v){let U=v.reasoning||v.reasoning_content||null;if(U&&(b.push({text:U,thought:!0}),$=!0),v.content){let j=v.content;f&&R&&j.length>0&&(j="<think>"+j,R=!1),b.push({text:j}),$=!0}}}catch{}if((C||Date.now()-T>=150||w)&&$&&(yield{candidates:b.length>0?[{content:{parts:[...b]}}]:[],usageMetadata:w},b=[],T=Date.now(),$=!1),C)break}Date.now()-T>=150&&$&&(yield{candidates:b.length>0?[{content:{parts:[...b]}}]:[],usageMetadata:w},b=[],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 k of T.parts)if(k.text)R.push({type:"text",text:k.text});else if(k.inlineData&&a){let S=k.inlineData.mimeType,_=k.inlineData.data;S.startsWith("image/")&&R.push({type:"image_url",image_url:{url:`data:${S};base64,${_}`}})}}else{let k=T.text||"";k&&R.push({type:"text",text:k})}d.push({role:$,content:R.length===1&&R[0].type==="text"?R[0].text:R})}let c={Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},l={model:n,messages:d,stream:!0,stream_options:{include_usage:!0},temperature:p};c[s]&&(l.reasoning_effort=c[s]);let f=await ct("https://token.sensenova.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(l),signal:i});if(!f.ok){let T=await f.json().catch(()=>({}));throw new Error(`SenseNova Error (${f.status}): ${T.error?.message||f.statusText}`)}let u=f.body.getReader(),m=new TextDecoder,g="",y=[],h=null,b=Date.now(),w=!1;for(;;){let{done:T,value:$}=await u.read();if(T){w&&(y.length>0||h)&&(yield{candidates:y.length>0?[{content:{parts:y}}]:[],usageMetadata:h});break}g+=m.decode($,{stream:!0});let R=g.split(`
930
- `);g=R.pop();for(let k of R){let S=k.trim();if(!S||!S.startsWith("data: "))continue;let _=!1;if(S==="data: [DONE]")_=!0;else try{let E=JSON.parse(S.substring(6)),x=E.choices?.[0]?.delta,C=E.usage;if(C&&(h={totalTokenCount:C.total_tokens||(C.prompt_tokens||0)+(C.completion_tokens||0),promptTokenCount:C.prompt_tokens||0,candidatesTokenCount:C.completion_tokens||0,cachedContentTokenCount:C.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:C.completion_tokens_details?.reasoning_tokens||C.reasoning_tokens||0},w=!0),x){let M=x.reasoning||x.reasoning_content||null;M&&(y.push({text:M,thought:!0}),w=!0),x.content&&(y.push({text:x.content}),w=!0)}}catch{}if((_||Date.now()-b>=150||h)&&w&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:h},y=[],b=Date.now(),w=!1),_)break}Date.now()-b>=150&&w&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:h},y=[],b=Date.now(),w=!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 k of T.parts)if(k.text)R.push({type:"text",text:k.text});else if(k.inlineData&&a){let S=k.inlineData.mimeType,_=k.inlineData.data;S.startsWith("image/")&&R.push({type:"image_url",image_url:{url:`data:${S};base64,${_}`}})}}else{let k=T.text||"";k&&R.push({type:"text",text:k})}d.push({role:$,content:R.length===1&&R[0].type==="text"?R[0].text:R})}let c={Fast:"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 f=await ct("https://aihubmix.com/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(l),signal:i});if(!f.ok){let T=await f.json().catch(()=>({}));throw new Error(`AIHubMix Error (${f.status}): ${T.error?.message||f.statusText}`)}let u=f.body.getReader(),m=new TextDecoder,g="",y=[],h=null,b=Date.now(),w=!1;for(;;){let{done:T,value:$}=await u.read();if(T){w&&(y.length>0||h)&&(yield{candidates:y.length>0?[{content:{parts:y}}]:[],usageMetadata:h});break}g+=m.decode($,{stream:!0});let R=g.split(`
931
- `);g=R.pop();for(let k of R){let S=k.trim();if(!S||!S.startsWith("data: "))continue;let _=!1;if(S==="data: [DONE]")_=!0;else try{let E=JSON.parse(S.substring(6)),x=E.choices?.[0]?.delta,C=E.usage;if(E.choices?.[0]?.finish_reason&&(_=!0),C&&(h={totalTokenCount:C.total_tokens||(C.prompt_tokens||0)+(C.completion_tokens||0),promptTokenCount:C.prompt_tokens||0,candidatesTokenCount:C.completion_tokens||0,cachedContentTokenCount:C.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:C.completion_tokens_details?.reasoning_tokens||C.reasoning_tokens||0},w=!0),x){let M=x.reasoning_content||null;M&&(y.push({text:M,thought:!0}),w=!0),x.content&&(y.push({text:x.content}),w=!0)}}catch{}if((_||Date.now()-b>=150)&&w&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:h},y=[],b=Date.now(),w=!1),_)break}Date.now()-b>=150&&w&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:h},y=[],b=Date.now(),w=!1)}};var er=async function*(e,n,t,o,s,r,a,i,p=1){let d=[];o&&d.push({role:"system",content:o});for(let T of t){let $=T.role==="user"?"user":"assistant",R=[];if(Array.isArray(T.parts)){for(let k of T.parts)if(k.text)R.push({type:"text",text:k.text});else if(k.inlineData&&a){let S=k.inlineData.mimeType,_=k.inlineData.data;S.startsWith("image/")&&R.push({type:"image_url",image_url:{url:`data:${S};base64,${_}`}})}}else{let k=T.text||"";k&&R.push({type:"text",text:k})}d.push({role:$,content:R.length===1&&R[0].type==="text"?R[0].text:R})}let c=s==="Fast",l={model:n,messages:d,stream:!0,stream_options:{include_usage:!0},temperature:p};c&&(l.chat_template_kwargs={enable_thinking:!1});let f=await ct("https://inference.poolside.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(l),signal:i});if(!f.ok){let T=await f.json().catch(()=>({}));throw new Error(`Poolside Error (${f.status}): ${T.error?.message||f.statusText}`)}let u=f.body.getReader(),m=new TextDecoder,g="",y=[],h=null,b=Date.now(),w=!1;for(;;){let{done:T,value:$}=await u.read();if(T){w&&(y.length>0||h)&&(yield{candidates:y.length>0?[{content:{parts:y}}]:[],usageMetadata:h});break}g+=m.decode($,{stream:!0});let R=g.split(`
932
- `);g=R.pop();for(let k of R){let S=k.trim();if(!S||!S.startsWith("data: "))continue;let _=!1;if(S==="data: [DONE]")_=!0;else try{let E=JSON.parse(S.substring(6)),x=E.choices?.[0]?.delta,C=E.usage;if(E.choices?.[0]?.finish_reason&&(_=!0),C&&(h={totalTokenCount:C.total_tokens||(C.prompt_tokens||0)+(C.completion_tokens||0),promptTokenCount:C.prompt_tokens||0,candidatesTokenCount:C.completion_tokens||0,cachedContentTokenCount:C.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:C.completion_tokens_details?.reasoning_tokens||C.reasoning_tokens||0},w=!0),x){let M=x.reasoning_content||x.reasoning||null;M&&(y.push({text:M,thought:!0}),w=!0),x.content&&(y.push({text:x.content}),w=!0)}}catch{}if((_||Date.now()-b>=150)&&w&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:h},y=[],b=Date.now(),w=!1),_)break}Date.now()-b>=150&&w&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:h},y=[],b=Date.now(),w=!1)}};var tr=async function*(e,n,t,o,s,r,a,i,p=1){let d=[];o&&d.push({role:"system",content:o});for(let k of t){let S=k.role==="user"?"user":"assistant",_=[];if(Array.isArray(k.parts)){for(let E of k.parts)if(E.text)_.push({type:"text",text:E.text});else if(E.inlineData&&a){let x=E.inlineData.mimeType,C=E.inlineData.data;x.startsWith("image/")&&_.push({type:"image_url",image_url:{url:`data:${x};base64,${C}`}})}}else{let E=k.text||"";E&&_.push({type:"text",text:E})}d.push({role:S,content:_.length===1&&_[0].type==="text"?_[0].text:_})}let c={Fast:"none",Low:"low",Medium:"medium",High:"high"},l={model:n,messages:d,stream:!0,stream_options:{include_usage:!0},temperature:p};c[s]&&(l.reasoning_effort=c[s]);let f=process.env["9ROUTER_URL"]||process.env.NINEROUTER_URL||"http://127.0.0.1:20128/v1/chat/completions",u={"Content-Type":"application/json"},m=e&&e!=="LOCAL"?e:process.env["9ROUTER_API_KEY"]||"dummy-key";u.Authorization=`Bearer ${m}`;let g=await ct(f,{method:"POST",headers:u,body:JSON.stringify(l),signal:i});if(!g.ok){let k=await g.json().catch(()=>({}));throw new Error(`9router Error (${g.status}): ${k.error?.message||g.statusText}`)}let y=g.body.getReader(),h=new TextDecoder,b="",w=[],T=null,$=Date.now(),R=!1;for(;;){let{done:k,value:S}=await y.read();if(k){R&&(w.length>0||T)&&(yield{candidates:w.length>0?[{content:{parts:w}}]:[],usageMetadata:T});break}b+=h.decode(S,{stream:!0});let _=b.split(`
933
- `);b=_.pop();for(let E of _){let x=E.trim();if(!x||!x.startsWith("data: "))continue;let C=!1;if(x==="data: [DONE]")C=!0;else try{let M=JSON.parse(x.substring(6)),v=M.choices?.[0]?.delta,L=M.usage;if(M.choices?.[0]?.finish_reason&&(C=!0),L&&(T={totalTokenCount:L.total_tokens||(L.prompt_tokens||0)+(L.completion_tokens||0),promptTokenCount:L.prompt_tokens||0,candidatesTokenCount:L.completion_tokens||0,cachedContentTokenCount:L.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:L.completion_tokens_details?.reasoning_tokens||L.reasoning_tokens||0},R=!0),v){let U=v.reasoning_content||v.reasoning||null;!U&&Array.isArray(v.reasoning_details)&&v.reasoning_details.length>0&&(U=v.reasoning_details.map(j=>j.text||"").filter(Boolean).join("")),U&&(w.push({text:U,thought:!0}),R=!0),v.content&&(w.push({text:v.content}),R=!0)}}catch{}if((C||Date.now()-$>=150)&&R&&(yield{candidates:w.length>0?[{content:{parts:[...w]}}]:[],usageMetadata:T},w=[],$=Date.now(),R=!1),C)break}Date.now()-$>=150&&R&&(yield{candidates:w.length>0?[{content:{parts:[...w]}}]:[],usageMetadata:T},w=[],$=Date.now(),R=!1)}};var nr=async function*(e,n,t,o,s,r,a,i,p=1){let d=[];o&&d.push({role:"system",content:o});for(let k of t){let S=k.role==="user"?"user":"assistant",_=[];if(Array.isArray(k.parts)){for(let E of k.parts)if(E.text)_.push({type:"text",text:E.text});else if(E.inlineData&&a){let x=E.inlineData.mimeType,C=E.inlineData.data;x.startsWith("image/")&&_.push({type:"image_url",image_url:{url:`data:${x};base64,${C}`}})}}else{let E=k.text||"";E&&_.push({type:"text",text:E})}d.push({role:S,content:_.length===1&&_[0].type==="text"?_[0].text:_})}let c={Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},l={model:n,messages:d,stream:!0,stream_options:{include_usage:!0},temperature:p};c[s]&&(l.reasoning_effort=c[s]);let f=process.env.EXPLABS_URL||process.env.EXPERIENTIALLABS_URL||"https://api.experientiallabs.ai/v1/chat/completions",u={"Content-Type":"application/json"},m=e||process.env.EXPLABS_API_KEY||process.env.EXPERIENTIALLABS_API_KEY||"";u.Authorization=`Bearer ${m}`;let g=await ct(f,{method:"POST",headers:u,body:JSON.stringify(l),signal:i});if(!g.ok){let k=await g.json().catch(()=>({}));throw new Error(`Experiential Labs Error (${g.status}): ${k.error?.message||k.message||g.statusText}`)}let y=g.body.getReader(),h=new TextDecoder,b="",w=[],T=null,$=Date.now(),R=!1;for(;;){let{done:k,value:S}=await y.read();if(k){R&&(w.length>0||T)&&(yield{candidates:w.length>0?[{content:{parts:w}}]:[],usageMetadata:T});break}b+=h.decode(S,{stream:!0});let _=b.split(`
934
- `);b=_.pop();for(let E of _){let x=E.trim();if(!x||!x.startsWith("data: "))continue;let C=!1;if(x==="data: [DONE]")C=!0;else try{let M=JSON.parse(x.substring(6)),v=M.choices?.[0]?.delta,L=M.usage;if(L&&(T={totalTokenCount:L.total_tokens||(L.prompt_tokens||0)+(L.completion_tokens||0),promptTokenCount:L.prompt_tokens||0,candidatesTokenCount:L.completion_tokens||0,cachedContentTokenCount:L.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:L.completion_tokens_details?.reasoning_tokens||L.reasoning_tokens||0},R=!0),v){let U=v.reasoning_content||v.reasoning||null;!U&&Array.isArray(v.reasoning_details)&&v.reasoning_details.length>0&&(U=v.reasoning_details.map(j=>j.text||"").filter(Boolean).join("")),U&&(w.push({text:U,thought:!0}),R=!0),v.content&&(w.push({text:v.content}),R=!0)}}catch{}if((C||Date.now()-$>=150)&&R&&(yield{candidates:w.length>0?[{content:{parts:[...w]}}]:[],usageMetadata:T},w=[],$=Date.now(),R=!1),C)break}Date.now()-$>=150&&R&&(yield{candidates:w.length>0?[{content:{parts:[...w]}}]:[],usageMetadata:T},w=[],$=Date.now(),R=!1)}};Yt.config({path:"./.env",override:!0,quiet:!0});Yt.config({path:`${_t}/.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:`${_t}/agents.env`,override:!0,quiet:!0});Yt.config({path:`${_t}/.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:`${_t}/fluxflow.env`,override:!0,quiet:!0});Yt.config({path:`${_t}/.fluxflow.env`,override:!0,quiet:!0});Yt.config({path:`${_t}/.env.agents`,override:!0,quiet:!0});Yt.config({path:`${_t}/.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 Qc=/```[\s\S]*?```/g,Zc=/```[\s\S]*$/g,ed=/`[^`]+`/g,td=/^\|.*\|$/gm,nd=/^[^\w]+|[^\w]+$/g,od=/[^a-z0-9]/gi,gs=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,sd=/\[\s*(?:tool:functions\.|agent:generalist\.)([a-z0-9_]+)\s*\(/gi,rd=/(?:path|targetFile|TargetFile|directory|keyword|id|taskId|title|task)\s*=\s*\\?["']?([^\\"' \),]+)/,bo=/["']/g,ll=/\\/g,id=/<\|channel>thought/gi,ad=/<channel\|>/gi,ld=e=>typeof e!="string"?e:e.replace(id,"<think>").replace(ad,"</think>"),Ay=/^\s*(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\]|$)/i,cd=(e,n)=>{let t=!1;for(let o=0;o<n;o++)e[o]==="`"&&(t=!t);return t},dd=e=>{let n=/(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\])/gi,t;for(;(t=n.exec(e))!==null;)if(!cd(e,t.index))return{index:t.index,length:t[0].length};return{index:-1,length:0}},wi=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=dd(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=wi(e);return n?n.remainingText.trimStart():e};var hl=/`[^`]*`/g,gl=/`[^`]*$/,cl=/<\|\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,ud=/"([^"]+)"\s*:\s*(?:"([^"]*)"|(\d+)|true|false|null)/g,dl=/<\|\s*tool_calls_section_begin\s*\|>/gi,ul=/<\|\s*tool_calls_section_end\s*\|>/gi,fd=/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi;var fl=e=>!e||typeof e!="string"?e:e.replace(/(```[\s\S]*?```|`[^`]*`)|(<(?:\w+)(?:[^>]*)>\r?\n?|\r?\n?<\/\w+(?:[^>]*)>)/gi,(n,t)=>t||""),bi=null,or={},ko={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`),pd=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"))})})}}},It=!1;var md=e=>{let n=e.filter(s=>(s.role==="user"||s.role==="agent"||s.role==="system")&&s.role!=="think"&&!s.isVisualFeedback&&!s.isMeta&&!s.isTerminalRecord&&!(s.text&&s.text.includes("[TERMINAL_RECORD]"))&&!String(s.id).startsWith("welcome")).map((s,r,a)=>{let i=s.fullText||s.text||"";if(s.role==="user"&&r<a.length-1)if(i.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")){let p=i.indexOf("**CONTEXT SUMMARY OF PREVIOUS TURNS");if(p!==-1){let c=i.substring(0,p).lastIndexOf("[SYSTEM METADATA]");c!==-1?i=i.substring(c).trim():i=i.substring(p).trim()}}else{let p=i.lastIndexOf("[USER]"),d=i.lastIndexOf("[USER PROMPT]");p!==-1?i=i.substring(p+6).trim():d!==-1&&(i=i.substring(d).trim())}return{...s,text:i}}),t=[],o=0;for(;o<n.length;){let s=n[o];if(s.role==="user")t.push(s),o++;else{let r=[];for(;o<n.length&&n[o].role!=="user";)r.push(n[o]),o++;let a=[],i=[],p=!1,d=()=>{a.length>0&&(t.push({role:"agent",text:"combined"}),a=[]),i.length>0&&(t.push({role:"system",text:"combined"}),i=[]),p=!1};r.forEach(c=>{let l=c.role==="system"&&(c.text?.startsWith("[TOOL RESULT]")||c.text?.startsWith("SUCCESS:")||c.text?.startsWith("ERROR:")||c.fullText?.startsWith("[TOOL RESULT]")||c.fullText?.startsWith("SUCCESS:")||c.fullText?.startsWith("ERROR:")),f=c.fullText||c.text||"",u=f.trim();if(!(!u&&!c.binaryPart)){if(l)i.push(u);else if(c.role==="agent"){!p&&i.length>0&&d();let m=f.endsWith(`
935
- `),g=u.toLowerCase().includes("tool:functions.")||u.toLowerCase().includes("agent:generalist.");a.push(u),g&&m?p=!0:p=!1}}}),d()}}return t.length},hd=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),My=()=>{It=!0},vy=()=>It,xi={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?te.basename(s.replace(/["']/g,"").replace(/\\/g,"/")):null}catch{return null}},ki=e=>e?new ml({apiKey:e}):bi,Iy=async(e,n,t,o,s={})=>{let{onStatus:i,onMemoryUpdated:p,onBackgroundIncrement:d}=s,{profile:c,thinkingLevel:l,mode:f,janitorModel:u,chatId:m,systemSettings:g,sessionStats:y,aiProvider:h="Google",apiKey:b}=e,w=process.env.NVIDIA_BASE_URL||h==="Ollama"||h==="CrofAI"||h==="InferX"||h==="SenseNova"||h==="AIHubMix"||h==="Poolside"||h==="9router"||h==="ExpLabs"||h==="ExperientialLabs"?!1:g?.memory!==!1,$=se(Ft,[]).map(O=>`- [${O.id}]: ${O.memory}`).join(`
936
- `),R=o.slice(0,-1).filter(O=>O.text&&!O.text.includes("[TOOL RESULT]")&&!O.text.includes("OBSERVATION:")&&!O.text.startsWith("[TERMINAL_RECORD]")&&!O.isTerminalRecord&&!O.isMeta&&!O.isLogo&&!String(O.id).startsWith("welcome")&&!String(O.id).startsWith("logo")).slice(-14).map(O=>{let B=on(hd(O.text)).replace(/\[tool:functions\..*?\]/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[METADATA \(PRIORITY: DYNAMIC\)\] Time: ([^|\n]+)/g,(Ne,Ze)=>`[METADATA (PRIORITY: DYNAMIC)] Time: ${Ze.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,`
928
+ `:"")+E.text);else _=k.text||"";d.push({role:S,content:_})}let c={Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},l=n&&n.toLowerCase().includes("qwen3.8-27b"),f=n&&(n.toLowerCase().includes("qwen3.8-27b")||n.toLowerCase().includes("qwen3.6-35b-a3b-fp8")),u={model:n,messages:d.filter(k=>k.content&&String(k.content).trim().length>0),stream:!0,stream_options:{include_usage:!0},temperature:p};l||(u.stream_options={include_usage:!0},c[s]&&(u.reasoning_effort=c[s]));let m=await lt("https://model.inferx.net/endpoints/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(u),signal:i});if(!m.ok){let k=await m.text().catch(()=>""),S="";try{let _=JSON.parse(k);S=_.error?.message||_.error?.detail||_.message||_.detail||(typeof _.error=="string"?_.error:"")||(k&&k!=="{}"?k:"")}catch{S=k}throw(!S||S==="{}")&&(S=m.statusText||"Unknown error"),new Error(`InferX Error (${m.status}): ${S}`)}let g=m.body.getReader(),y=new TextDecoder,h="",b=[],w=null,T=Date.now(),$=!1,R=!0;for(;;){let{done:k,value:S}=await g.read();if(k){$&&(b.length>0||w)&&(yield{candidates:b.length>0?[{content:{parts:b}}]:[],usageMetadata:w});break}h+=y.decode(S,{stream:!0});let _=h.split(`
929
+ `);h=_.pop();for(let E of _){let x=E.trim();if(!x||!x.startsWith("data: "))continue;let C=!1;if(x==="data: [DONE]")C=!0;else try{let M=JSON.parse(x.substring(6)),v=M.choices?.[0]?.delta,L=M.usage;if(L&&(w={totalTokenCount:L.total_tokens||(L.prompt_tokens||0)+(L.completion_tokens||0),promptTokenCount:L.prompt_tokens||0,candidatesTokenCount:L.completion_tokens||0,cachedContentTokenCount:L.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:L.completion_tokens_details?.reasoning_tokens||L.reasoning_tokens||0},$=!0),v){let U=v.reasoning||v.reasoning_content||null;if(U&&(b.push({text:U,thought:!0}),$=!0),v.content){let j=v.content;f&&R&&j.length>0&&(j="<think>"+j,R=!1),b.push({text:j}),$=!0}}}catch{}if((C||Date.now()-T>=150||w)&&$&&(yield{candidates:b.length>0?[{content:{parts:[...b]}}]:[],usageMetadata:w},b=[],T=Date.now(),$=!1),C)break}Date.now()-T>=150&&$&&(yield{candidates:b.length>0?[{content:{parts:[...b]}}]:[],usageMetadata:w},b=[],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 k of T.parts)if(k.text)R.push({type:"text",text:k.text});else if(k.inlineData&&a){let S=k.inlineData.mimeType,_=k.inlineData.data;S.startsWith("image/")&&R.push({type:"image_url",image_url:{url:`data:${S};base64,${_}`}})}}else{let k=T.text||"";k&&R.push({type:"text",text:k})}d.push({role:$,content:R.length===1&&R[0].type==="text"?R[0].text:R})}let c={Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},l={model:n,messages:d,stream:!0,stream_options:{include_usage:!0},temperature:p};c[s]&&(l.reasoning_effort=c[s]);let f=await lt("https://token.sensenova.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(l),signal:i});if(!f.ok){let T=await f.json().catch(()=>({}));throw new Error(`SenseNova Error (${f.status}): ${T.error?.message||f.statusText}`)}let u=f.body.getReader(),m=new TextDecoder,g="",y=[],h=null,b=Date.now(),w=!1;for(;;){let{done:T,value:$}=await u.read();if(T){w&&(y.length>0||h)&&(yield{candidates:y.length>0?[{content:{parts:y}}]:[],usageMetadata:h});break}g+=m.decode($,{stream:!0});let R=g.split(`
930
+ `);g=R.pop();for(let k of R){let S=k.trim();if(!S||!S.startsWith("data: "))continue;let _=!1;if(S==="data: [DONE]")_=!0;else try{let E=JSON.parse(S.substring(6)),x=E.choices?.[0]?.delta,C=E.usage;if(C&&(h={totalTokenCount:C.total_tokens||(C.prompt_tokens||0)+(C.completion_tokens||0),promptTokenCount:C.prompt_tokens||0,candidatesTokenCount:C.completion_tokens||0,cachedContentTokenCount:C.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:C.completion_tokens_details?.reasoning_tokens||C.reasoning_tokens||0},w=!0),x){let M=x.reasoning||x.reasoning_content||null;M&&(y.push({text:M,thought:!0}),w=!0),x.content&&(y.push({text:x.content}),w=!0)}}catch{}if((_||Date.now()-b>=150||h)&&w&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:h},y=[],b=Date.now(),w=!1),_)break}Date.now()-b>=150&&w&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:h},y=[],b=Date.now(),w=!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 k of T.parts)if(k.text)R.push({type:"text",text:k.text});else if(k.inlineData&&a){let S=k.inlineData.mimeType,_=k.inlineData.data;S.startsWith("image/")&&R.push({type:"image_url",image_url:{url:`data:${S};base64,${_}`}})}}else{let k=T.text||"";k&&R.push({type:"text",text:k})}d.push({role:$,content:R.length===1&&R[0].type==="text"?R[0].text:R})}let c={Fast:"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 f=await lt("https://aihubmix.com/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(l),signal:i});if(!f.ok){let T=await f.json().catch(()=>({}));throw new Error(`AIHubMix Error (${f.status}): ${T.error?.message||f.statusText}`)}let u=f.body.getReader(),m=new TextDecoder,g="",y=[],h=null,b=Date.now(),w=!1;for(;;){let{done:T,value:$}=await u.read();if(T){w&&(y.length>0||h)&&(yield{candidates:y.length>0?[{content:{parts:y}}]:[],usageMetadata:h});break}g+=m.decode($,{stream:!0});let R=g.split(`
931
+ `);g=R.pop();for(let k of R){let S=k.trim();if(!S||!S.startsWith("data: "))continue;let _=!1;if(S==="data: [DONE]")_=!0;else try{let E=JSON.parse(S.substring(6)),x=E.choices?.[0]?.delta,C=E.usage;if(E.choices?.[0]?.finish_reason&&(_=!0),C&&(h={totalTokenCount:C.total_tokens||(C.prompt_tokens||0)+(C.completion_tokens||0),promptTokenCount:C.prompt_tokens||0,candidatesTokenCount:C.completion_tokens||0,cachedContentTokenCount:C.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:C.completion_tokens_details?.reasoning_tokens||C.reasoning_tokens||0},w=!0),x){let M=x.reasoning_content||null;M&&(y.push({text:M,thought:!0}),w=!0),x.content&&(y.push({text:x.content}),w=!0)}}catch{}if((_||Date.now()-b>=150)&&w&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:h},y=[],b=Date.now(),w=!1),_)break}Date.now()-b>=150&&w&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:h},y=[],b=Date.now(),w=!1)}};var er=async function*(e,n,t,o,s,r,a,i,p=1){let d=[];o&&d.push({role:"system",content:o});for(let T of t){let $=T.role==="user"?"user":"assistant",R=[];if(Array.isArray(T.parts)){for(let k of T.parts)if(k.text)R.push({type:"text",text:k.text});else if(k.inlineData&&a){let S=k.inlineData.mimeType,_=k.inlineData.data;S.startsWith("image/")&&R.push({type:"image_url",image_url:{url:`data:${S};base64,${_}`}})}}else{let k=T.text||"";k&&R.push({type:"text",text:k})}d.push({role:$,content:R.length===1&&R[0].type==="text"?R[0].text:R})}let c=s==="Fast",l={model:n,messages:d,stream:!0,stream_options:{include_usage:!0},temperature:p};c&&(l.chat_template_kwargs={enable_thinking:!1});let f=await lt("https://inference.poolside.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(l),signal:i});if(!f.ok){let T=await f.json().catch(()=>({}));throw new Error(`Poolside Error (${f.status}): ${T.error?.message||f.statusText}`)}let u=f.body.getReader(),m=new TextDecoder,g="",y=[],h=null,b=Date.now(),w=!1;for(;;){let{done:T,value:$}=await u.read();if(T){w&&(y.length>0||h)&&(yield{candidates:y.length>0?[{content:{parts:y}}]:[],usageMetadata:h});break}g+=m.decode($,{stream:!0});let R=g.split(`
932
+ `);g=R.pop();for(let k of R){let S=k.trim();if(!S||!S.startsWith("data: "))continue;let _=!1;if(S==="data: [DONE]")_=!0;else try{let E=JSON.parse(S.substring(6)),x=E.choices?.[0]?.delta,C=E.usage;if(E.choices?.[0]?.finish_reason&&(_=!0),C&&(h={totalTokenCount:C.total_tokens||(C.prompt_tokens||0)+(C.completion_tokens||0),promptTokenCount:C.prompt_tokens||0,candidatesTokenCount:C.completion_tokens||0,cachedContentTokenCount:C.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:C.completion_tokens_details?.reasoning_tokens||C.reasoning_tokens||0},w=!0),x){let M=x.reasoning_content||x.reasoning||null;M&&(y.push({text:M,thought:!0}),w=!0),x.content&&(y.push({text:x.content}),w=!0)}}catch{}if((_||Date.now()-b>=150)&&w&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:h},y=[],b=Date.now(),w=!1),_)break}Date.now()-b>=150&&w&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:h},y=[],b=Date.now(),w=!1)}};var tr=async function*(e,n,t,o,s,r,a,i,p=1){let d=[];o&&d.push({role:"system",content:o});for(let k of t){let S=k.role==="user"?"user":"assistant",_=[];if(Array.isArray(k.parts)){for(let E of k.parts)if(E.text)_.push({type:"text",text:E.text});else if(E.inlineData&&a){let x=E.inlineData.mimeType,C=E.inlineData.data;x.startsWith("image/")&&_.push({type:"image_url",image_url:{url:`data:${x};base64,${C}`}})}}else{let E=k.text||"";E&&_.push({type:"text",text:E})}d.push({role:S,content:_.length===1&&_[0].type==="text"?_[0].text:_})}let c={Fast:"none",Low:"low",Medium:"medium",High:"high"},l={model:n,messages:d,stream:!0,stream_options:{include_usage:!0},temperature:p};c[s]&&(l.reasoning_effort=c[s]);let f=process.env["9ROUTER_URL"]||process.env.NINEROUTER_URL||"http://127.0.0.1:20128/v1/chat/completions",u={"Content-Type":"application/json"},m=e&&e!=="LOCAL"?e:process.env["9ROUTER_API_KEY"]||"dummy-key";u.Authorization=`Bearer ${m}`;let g=await lt(f,{method:"POST",headers:u,body:JSON.stringify(l),signal:i});if(!g.ok){let k=await g.json().catch(()=>({}));throw new Error(`9router Error (${g.status}): ${k.error?.message||g.statusText}`)}let y=g.body.getReader(),h=new TextDecoder,b="",w=[],T=null,$=Date.now(),R=!1;for(;;){let{done:k,value:S}=await y.read();if(k){R&&(w.length>0||T)&&(yield{candidates:w.length>0?[{content:{parts:w}}]:[],usageMetadata:T});break}b+=h.decode(S,{stream:!0});let _=b.split(`
933
+ `);b=_.pop();for(let E of _){let x=E.trim();if(!x||!x.startsWith("data: "))continue;let C=!1;if(x==="data: [DONE]")C=!0;else try{let M=JSON.parse(x.substring(6)),v=M.choices?.[0]?.delta,L=M.usage;if(M.choices?.[0]?.finish_reason&&(C=!0),L&&(T={totalTokenCount:L.total_tokens||(L.prompt_tokens||0)+(L.completion_tokens||0),promptTokenCount:L.prompt_tokens||0,candidatesTokenCount:L.completion_tokens||0,cachedContentTokenCount:L.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:L.completion_tokens_details?.reasoning_tokens||L.reasoning_tokens||0},R=!0),v){let U=v.reasoning_content||v.reasoning||null;!U&&Array.isArray(v.reasoning_details)&&v.reasoning_details.length>0&&(U=v.reasoning_details.map(j=>j.text||"").filter(Boolean).join("")),U&&(w.push({text:U,thought:!0}),R=!0),v.content&&(w.push({text:v.content}),R=!0)}}catch{}if((C||Date.now()-$>=150)&&R&&(yield{candidates:w.length>0?[{content:{parts:[...w]}}]:[],usageMetadata:T},w=[],$=Date.now(),R=!1),C)break}Date.now()-$>=150&&R&&(yield{candidates:w.length>0?[{content:{parts:[...w]}}]:[],usageMetadata:T},w=[],$=Date.now(),R=!1)}};var nr=async function*(e,n,t,o,s,r,a,i,p=1){let d=[];o&&d.push({role:"system",content:o});for(let k of t){let S=k.role==="user"?"user":"assistant",_=[];if(Array.isArray(k.parts)){for(let E of k.parts)if(E.text)_.push({type:"text",text:E.text});else if(E.inlineData&&a){let x=E.inlineData.mimeType,C=E.inlineData.data;x.startsWith("image/")&&_.push({type:"image_url",image_url:{url:`data:${x};base64,${C}`}})}}else{let E=k.text||"";E&&_.push({type:"text",text:E})}d.push({role:S,content:_.length===1&&_[0].type==="text"?_[0].text:_})}let c={Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},l={model:n,messages:d,stream:!0,stream_options:{include_usage:!0},temperature:p};c[s]&&(l.reasoning_effort=c[s]);let f=process.env.EXPLABS_URL||process.env.EXPERIENTIALLABS_URL||"https://api.experientiallabs.ai/v1/chat/completions",u={"Content-Type":"application/json"},m=e||process.env.EXPLABS_API_KEY||process.env.EXPERIENTIALLABS_API_KEY||"";u.Authorization=`Bearer ${m}`;let g=await lt(f,{method:"POST",headers:u,body:JSON.stringify(l),signal:i});if(!g.ok){let k=await g.json().catch(()=>({}));throw new Error(`Experiential Labs Error (${g.status}): ${k.error?.message||k.message||g.statusText}`)}let y=g.body.getReader(),h=new TextDecoder,b="",w=[],T=null,$=Date.now(),R=!1;for(;;){let{done:k,value:S}=await y.read();if(k){R&&(w.length>0||T)&&(yield{candidates:w.length>0?[{content:{parts:w}}]:[],usageMetadata:T});break}b+=h.decode(S,{stream:!0});let _=b.split(`
934
+ `);b=_.pop();for(let E of _){let x=E.trim();if(!x||!x.startsWith("data: "))continue;let C=!1;if(x==="data: [DONE]")C=!0;else try{let M=JSON.parse(x.substring(6)),v=M.choices?.[0]?.delta,L=M.usage;if(L&&(T={totalTokenCount:L.total_tokens||(L.prompt_tokens||0)+(L.completion_tokens||0),promptTokenCount:L.prompt_tokens||0,candidatesTokenCount:L.completion_tokens||0,cachedContentTokenCount:L.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:L.completion_tokens_details?.reasoning_tokens||L.reasoning_tokens||0},R=!0),v){let U=v.reasoning_content||v.reasoning||null;!U&&Array.isArray(v.reasoning_details)&&v.reasoning_details.length>0&&(U=v.reasoning_details.map(j=>j.text||"").filter(Boolean).join("")),U&&(w.push({text:U,thought:!0}),R=!0),v.content&&(w.push({text:v.content}),R=!0)}}catch{}if((C||Date.now()-$>=150)&&R&&(yield{candidates:w.length>0?[{content:{parts:[...w]}}]:[],usageMetadata:T},w=[],$=Date.now(),R=!1),C)break}Date.now()-$>=150&&R&&(yield{candidates:w.length>0?[{content:{parts:[...w]}}]:[],usageMetadata:T},w=[],$=Date.now(),R=!1)}};Jt.config({path:"./.env",override:!0,quiet:!0});Jt.config({path:`${Ct}/.env`,override:!0,quiet:!0});Jt.config({path:"./agents.env",override:!0,quiet:!0});Jt.config({path:"./.agents.env",override:!0,quiet:!0});Jt.config({path:`${Ct}/agents.env`,override:!0,quiet:!0});Jt.config({path:`${Ct}/.agents.env`,override:!0,quiet:!0});Jt.config({path:"./fluxflow.env",override:!0,quiet:!0});Jt.config({path:"./.fluxflow.env",override:!0,quiet:!0});Jt.config({path:`${Ct}/fluxflow.env`,override:!0,quiet:!0});Jt.config({path:`${Ct}/.fluxflow.env`,override:!0,quiet:!0});Jt.config({path:`${Ct}/.env.agents`,override:!0,quiet:!0});Jt.config({path:`${Ct}/.env.fluxflow`,override:!0,quiet:!0});Jt.config({path:"./.env.agents",override:!0,quiet:!0});Jt.config({path:"./.env.fluxflow",override:!0,quiet:!0});var Qc=/```[\s\S]*?```/g,Zc=/```[\s\S]*$/g,ed=/`[^`]+`/g,td=/^\|.*\|$/gm,nd=/^[^\w]+|[^\w]+$/g,od=/[^a-z0-9]/gi,gs=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,sd=/\[\s*(?:tool:functions\.|agent:generalist\.)([a-z0-9_]+)\s*\(/gi,rd=/(?:path|targetFile|TargetFile|directory|keyword|id|taskId|title|task)\s*=\s*\\?["']?([^\\"' \),]+)/,bo=/["']/g,ll=/\\/g,id=/<\|channel>thought/gi,ad=/<channel\|>/gi,ld=e=>typeof e!="string"?e:e.replace(id,"<think>").replace(ad,"</think>"),Ay=/^\s*(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\]|$)/i,cd=(e,n)=>{let t=!1;for(let o=0;o<n;o++)e[o]==="`"&&(t=!t);return t},dd=e=>{let n=/(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\])/gi,t;for(;(t=n.exec(e))!==null;)if(!cd(e,t.index))return{index:t.index,length:t[0].length};return{index:-1,length:0}},wi=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=dd(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:""}},rn=e=>{if(!e||typeof e!="string")return e;let n=wi(e);return n?n.remainingText.trimStart():e};var hl=/`[^`]*`/g,gl=/`[^`]*$/,cl=/<\|\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,ud=/"([^"]+)"\s*:\s*(?:"([^"]*)"|(\d+)|true|false|null)/g,dl=/<\|\s*tool_calls_section_begin\s*\|>/gi,ul=/<\|\s*tool_calls_section_end\s*\|>/gi,fd=/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi;var fl=e=>!e||typeof e!="string"?e:e.replace(/(```[\s\S]*?```|`[^`]*`)|(<(?:\w+)(?:[^>]*)>\r?\n?|\r?\n?<\/\w+(?:[^>]*)>)/gi,(n,t)=>t||""),bi=null,or={},ko={key:null,value:null},sn=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`),pd=async(e,n=8,t=1e3,o=8e3,s=null)=>{let r=0;for(;;){if(s?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{return await e()}catch(a){if(s?.aborted||a?.name==="AbortError"||a?.message==="Subagent task was cancelled."||(r++,r>=n))throw a;let i=Math.min(t*Math.pow(2,r-1),o);await new Promise((p,d)=>{let c=setTimeout(p,i);s&&s.addEventListener("abort",()=>{clearTimeout(c),d(new DOMException("The user aborted a request.","AbortError"))})})}}},Lt=!1;var md=e=>{let n=e.filter(s=>(s.role==="user"||s.role==="agent"||s.role==="system")&&s.role!=="think"&&!s.isVisualFeedback&&!s.isMeta&&!s.isTerminalRecord&&!(s.text&&s.text.includes("[TERMINAL_RECORD]"))&&!String(s.id).startsWith("welcome")).map((s,r,a)=>{let i=s.fullText||s.text||"";if(s.role==="user"&&r<a.length-1)if(i.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")){let p=i.indexOf("**CONTEXT SUMMARY OF PREVIOUS TURNS");if(p!==-1){let c=i.substring(0,p).lastIndexOf("[SYSTEM METADATA]");c!==-1?i=i.substring(c).trim():i=i.substring(p).trim()}}else{let p=i.lastIndexOf("[USER]"),d=i.lastIndexOf("[USER PROMPT]");p!==-1?i=i.substring(p+6).trim():d!==-1&&(i=i.substring(d).trim())}return{...s,text:i}}),t=[],o=0;for(;o<n.length;){let s=n[o];if(s.role==="user")t.push(s),o++;else{let r=[];for(;o<n.length&&n[o].role!=="user";)r.push(n[o]),o++;let a=[],i=[],p=!1,d=()=>{a.length>0&&(t.push({role:"agent",text:"combined"}),a=[]),i.length>0&&(t.push({role:"system",text:"combined"}),i=[]),p=!1};r.forEach(c=>{let l=c.role==="system"&&(c.text?.startsWith("[TOOL RESULT]")||c.text?.startsWith("SUCCESS:")||c.text?.startsWith("ERROR:")||c.fullText?.startsWith("[TOOL RESULT]")||c.fullText?.startsWith("SUCCESS:")||c.fullText?.startsWith("ERROR:")),f=c.fullText||c.text||"",u=f.trim();if(!(!u&&!c.binaryPart)){if(l)i.push(u);else if(c.role==="agent"){!p&&i.length>0&&d();let m=f.endsWith(`
935
+ `),g=u.toLowerCase().includes("tool:functions.")||u.toLowerCase().includes("agent:generalist.");a.push(u),g&&m?p=!0:p=!1}}}),d()}}return t.length},hd=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),My=()=>{Lt=!0},vy=()=>Lt,xi={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?te.basename(s.replace(/["']/g,"").replace(/\\/g,"/")):null}catch{return null}},ki=e=>e?new ml({apiKey:e}):bi,Iy=async(e,n,t,o,s={})=>{let{onStatus:i,onMemoryUpdated:p,onBackgroundIncrement:d}=s,{profile:c,thinkingLevel:l,mode:f,janitorModel:u,chatId:m,systemSettings:g,sessionStats:y,aiProvider:h="Google",apiKey:b}=e,w=process.env.NVIDIA_BASE_URL||h==="Ollama"||h==="CrofAI"||h==="InferX"||h==="SenseNova"||h==="AIHubMix"||h==="Poolside"||h==="9router"||h==="ExpLabs"||h==="ExperientialLabs"?!1:g?.memory!==!1,$=se(Ut,[]).map(O=>`- [${O.id}]: ${O.memory}`).join(`
936
+ `),R=o.slice(0,-1).filter(O=>O.text&&!O.text.includes("[TOOL RESULT]")&&!O.text.includes("OBSERVATION:")&&!O.text.startsWith("[TERMINAL_RECORD]")&&!O.isTerminalRecord&&!O.isMeta&&!O.isLogo&&!String(O.id).startsWith("welcome")&&!String(O.id).startsWith("logo")).slice(-14).map(O=>{let B=rn(hd(O.text)).replace(/\[tool:functions\..*?\]/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[METADATA \(PRIORITY: DYNAMIC\)\] Time: ([^|\n]+)/g,(Ne,Ze)=>`[METADATA (PRIORITY: DYNAMIC)] Time: ${Ze.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,`
937
937
  `).replace(/\n\n/g,`
938
938
  `).replace(/\\n\\n/g,"").trim(),J=O.role==="user"?8192:32768,Q=B.substring(0,J);B.length>J&&(Q+=`
939
- ... (truncated) ...`);let We=O.role==="user"?Q.startsWith("[USER]")?"":"[USER]: ":Q.startsWith("[AGENT]")?"":"[AGENT]: ";return{role:O.role==="user"?"user":"model",parts:[{text:`${We}${Q}`}]}}),k=o.filter(O=>O.role==="user").length===1,S=n.includes("[TITLE-UPDATE]"),_=Math.random()<.8,E=k||S||_,x=on(t).trim(),C=ba($,w,E),M=`${x.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)}`;M.length>32768&&(M+=`
939
+ ... (truncated) ...`);let We=O.role==="user"?Q.startsWith("[USER]")?"":"[USER]: ":Q.startsWith("[AGENT]")?"":"[AGENT]: ";return{role:O.role==="user"?"user":"model",parts:[{text:`${We}${Q}`}]}}),k=o.filter(O=>O.role==="user").length===1,S=n.includes("[TITLE-UPDATE]"),_=Math.random()<.8,E=k||S||_,x=rn(t).trim(),C=ba($,w,E),M=`${x.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)}`;M.length>32768&&(M+=`
940
940
  ... (truncated) ...`);let v=n.replace(/\[Prompted on:.*?\]/g,"").trim();M=M.replace(/\r?\n\r?\n/g,`
941
941
  `).replace(/\n\n/g,`
942
942
  `).replace(/\\n\\n/g,"").trim();let L=new Date,j=`[METADATA] Current date and Time: ${`${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})}`}
@@ -945,11 +945,11 @@ ${l[7]}
945
945
  ${v.length>8192?`... (truncated) ...
946
946
 
947
947
  `:""}
948
- [AGENT (current turn)]: ${M}`;R.push({role:"user",parts:[{text:j}]});let ee=await mr("NVIDIA"),F=(await tn()).quotas?.providerTiers?.NVIDIA==="Free",W="",ne=0,Me=w?12:-1;for(;ne<=Me;)try{if(!await Di("background",e))return;let O="",B=null,J=!1,Q=h;try{let Ze=new Promise((qe,fe)=>setTimeout(()=>fe(new Error("JANITOR_TIMEOUT")),1e4)),dt=h==="Google"&&ne>=0&&ne<6&&ee&&F,He=h==="DeepSeek"&&ne<4&&ee&&F;J=dt||He,Q=J?"NVIDIA":h;let yt=(async()=>{if(h==="OpenRouter"){let qe=de("janitor_open_router"),le=Vs(b,qe,R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),nt=await le.next();return{iterator:le,firstResult:nt}}else if(h==="DeepSeek"&&!J){let fe=zs(b,de("deepseek_fast_fallback"),R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await fe.next();return{iterator:fe,firstResult:le}}else if(h==="Mistral"&&!J){let fe=Ks(b,de("mistral_janitor_fallback"),R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await fe.next();return{iterator:fe,firstResult:le}}else if(h==="NVIDIA"||J){let fe=Ys(J?ee:b,de("nvidia_janitor_fallback"),R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await fe.next();return{iterator:fe,firstResult:le}}else if(h==="CrofAI"){let fe=Xs(b,targetModel||de("crofai_fallback")||"deepseek-v4-flash-0731",R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await fe.next();return{iterator:fe,firstResult:le}}else if(h==="InferX"){let fe=Js(b,targetModel||de("inferx_fallback")||"deepseek-v4-flash",R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await fe.next();return{iterator:fe,firstResult:le}}else if(h==="SenseNova"){let fe=Qs(b,targetModel||de("sensenova_fallback")||"sensenova-6.8-flash-lite",R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await fe.next();return{iterator:fe,firstResult:le}}else if(h==="AIHubMix"){let fe=Zs(b,targetModel||de("aihubmix_fallback")||"gpt-4o-mini",R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await fe.next();return{iterator:fe,firstResult:le}}else if(h==="Poolside"){let fe=er(b,targetModel||de("poolside_fallback")||"poolside/laguna-s-2.1",R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await fe.next();return{iterator:fe,firstResult:le}}else if(h==="9router"||h==="9Router"){let fe=tr(b,targetModel||de("9router_fallback")||"z-ai/glm-5.3-flash",R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await fe.next();return{iterator:fe,firstResult:le}}else if(h==="ExpLabs"||h==="ExperientialLabs"){let fe=nr(b,targetModel||de("explabs_fallback")||"deepseek-v4-pro-0813",R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await fe.next();return{iterator:fe,firstResult:le}}else{let le=(await ki(b).models.generateContentStream({model:u||(ne===Me?de("janitor_default"):de("gemma_janitor_fallback_google")),contents:R,config:{systemInstruction:C,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:mt.MINIMAL}}}))[Symbol.asyncIterator](),nt=await le.next();return{iterator:le,firstResult:nt}}})();if(process.stdout.isTTY){let le=(await fo())[m]?.name||"",nt=le&&!le.startsWith("flow-")&&!le.startsWith("Session ")?le:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${nt}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${nt}\x07`)}let{iterator:To,firstResult:St}=await Promise.race([yt,Ze]),{value:Ve,done:$t}=St;if(!$t&&Ve){let qe=Ve.candidates?.[0]?.content?.parts,fe=qe?Q==="Google"?qe[1]?.text||qe[0]?.text||"":qe.filter(le=>le.text&&!le.thought).map(le=>le.text).join(""):typeof Ve.text=="function"?Ve.text():"";fe&&(O+=fe),B=Ve.usageMetadata;for await(let le of{[Symbol.asyncIterator]:()=>To}){let nt=le.candidates?.[0]?.content?.parts,ys=nt?Q==="Google"?nt[1]?.text||nt[0]?.text||"":nt.filter(An=>An.text&&!An.thought).map(An=>An.text).join(""):typeof le.text=="function"?le.text():"";ys&&(O+=ys),B=le.usageMetadata}}}catch(Ze){throw Ze}if(O){if(W=O,B){let Ze=B.totalTokenCount||0,dt=B.cachedContentTokenCount||0,He=(B.candidatesTokenCount||0)+(B.thoughtsTokenCount||0),yt=J?de("nvidia_janitor_fallback"):Q==="DeepSeek"?de("deepseek_fast_fallback"):Q==="ExpLabs"||Q==="ExperientialLabs"?de("explabs_fallback")||"deepseek-v4-pro-0813":Q==="OpenRouter"?de("janitor_open_router"):u||(ne===Me?de("janitor_default"):de("gemma_janitor_fallback_google"));await zt("tokens",Ze,Q,yt),dt>0&&await zt("cachedTokens",dt,Q,yt),He>0&&await zt("candidateTokens",He,Q,yt)}}else throw new Error("No synthesis generated by Janitor.");d&&(d(),await Ot("background"));let We=rr(W),Ne=!1;for(let Ze of We){let dt=Ze.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(dt)&&(Ne=!0);let He={chatId:m,sessionId:m,history:o},yt=await ms(dt,Ze.args,He);dt.toLowerCase()==="memory"&&(Ze.args.includes("action='user'")||Ze.args.includes('action="user"'))&&!yt.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(St=>setTimeout(St,3e3)))}if(!Ne)try{let Ze=se(Ft,[]);if(Ze.length>0){let dt=[];for(let He of Ze)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&&dt.push(He);ye(Ft,dt)}}catch{}break}catch(O){ne++;let B=new Date().toLocaleString(),J=O instanceof Error?(()=>{try{return JSON.parse(JSON.parse(O.message).error.message).error.message}catch{return String(O)}})():String(O);await new Promise(Ne=>setTimeout(Ne,1e3));let Q=te.join(hn,"janitor");if(Fe.existsSync(Q)||Fe.mkdirSync(Q,{recursive:!0}),Fe.appendFileSync(te.join(Q,"error.log"),`ERROR [Attempt ${ne}/${Me+1}] [${B}]: ${J}
948
+ [AGENT (current turn)]: ${M}`;R.push({role:"user",parts:[{text:j}]});let ee=await mr("NVIDIA"),F=(await on()).quotas?.providerTiers?.NVIDIA==="Free",W="",ne=0,Me=w?12:-1;for(;ne<=Me;)try{if(!await Di("background",e))return;let O="",B=null,J=!1,Q=h;try{let Ze=new Promise((qe,fe)=>setTimeout(()=>fe(new Error("JANITOR_TIMEOUT")),1e4)),ct=h==="Google"&&ne>=0&&ne<6&&ee&&F,He=h==="DeepSeek"&&ne<4&&ee&&F;J=ct||He,Q=J?"NVIDIA":h;let wt=(async()=>{if(h==="OpenRouter"){let qe=de("janitor_open_router"),le=Vs(b,qe,R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),nt=await le.next();return{iterator:le,firstResult:nt}}else if(h==="DeepSeek"&&!J){let fe=zs(b,de("deepseek_fast_fallback"),R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await fe.next();return{iterator:fe,firstResult:le}}else if(h==="Mistral"&&!J){let fe=Ks(b,de("mistral_janitor_fallback"),R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await fe.next();return{iterator:fe,firstResult:le}}else if(h==="NVIDIA"||J){let fe=Ys(J?ee:b,de("nvidia_janitor_fallback"),R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await fe.next();return{iterator:fe,firstResult:le}}else if(h==="CrofAI"){let fe=Xs(b,targetModel||de("crofai_fallback")||"deepseek-v4-flash-0731",R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await fe.next();return{iterator:fe,firstResult:le}}else if(h==="InferX"){let fe=Js(b,targetModel||de("inferx_fallback")||"deepseek-v4-flash",R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await fe.next();return{iterator:fe,firstResult:le}}else if(h==="SenseNova"){let fe=Qs(b,targetModel||de("sensenova_fallback")||"sensenova-6.8-flash-lite",R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await fe.next();return{iterator:fe,firstResult:le}}else if(h==="AIHubMix"){let fe=Zs(b,targetModel||de("aihubmix_fallback")||"gpt-4o-mini",R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await fe.next();return{iterator:fe,firstResult:le}}else if(h==="Poolside"){let fe=er(b,targetModel||de("poolside_fallback")||"poolside/laguna-s-2.1",R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await fe.next();return{iterator:fe,firstResult:le}}else if(h==="9router"||h==="9Router"){let fe=tr(b,targetModel||de("9router_fallback")||"z-ai/glm-5.3-flash",R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await fe.next();return{iterator:fe,firstResult:le}}else if(h==="ExpLabs"||h==="ExperientialLabs"){let fe=nr(b,targetModel||de("explabs_fallback")||"deepseek-v4-pro-0813",R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await fe.next();return{iterator:fe,firstResult:le}}else{let le=(await ki(b).models.generateContentStream({model:u||(ne===Me?de("janitor_default"):de("gemma_janitor_fallback_google")),contents:R,config:{systemInstruction:C,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:mt.MINIMAL}}}))[Symbol.asyncIterator](),nt=await le.next();return{iterator:le,firstResult:nt}}})();if(process.stdout.isTTY){let le=(await fo())[m]?.name||"",nt=le&&!le.startsWith("flow-")&&!le.startsWith("Session ")?le:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${nt}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${nt}\x07`)}let{iterator:To,firstResult:Tt}=await Promise.race([wt,Ze]),{value:Ve,done:At}=Tt;if(!At&&Ve){let qe=Ve.candidates?.[0]?.content?.parts,fe=qe?Q==="Google"?qe[1]?.text||qe[0]?.text||"":qe.filter(le=>le.text&&!le.thought).map(le=>le.text).join(""):typeof Ve.text=="function"?Ve.text():"";fe&&(O+=fe),B=Ve.usageMetadata;for await(let le of{[Symbol.asyncIterator]:()=>To}){let nt=le.candidates?.[0]?.content?.parts,ys=nt?Q==="Google"?nt[1]?.text||nt[0]?.text||"":nt.filter(vn=>vn.text&&!vn.thought).map(vn=>vn.text).join(""):typeof le.text=="function"?le.text():"";ys&&(O+=ys),B=le.usageMetadata}}}catch(Ze){throw Ze}if(O){if(W=O,B){let Ze=B.totalTokenCount||0,ct=B.cachedContentTokenCount||0,He=(B.candidatesTokenCount||0)+(B.thoughtsTokenCount||0),wt=J?de("nvidia_janitor_fallback"):Q==="DeepSeek"?de("deepseek_fast_fallback"):Q==="ExpLabs"||Q==="ExperientialLabs"?de("explabs_fallback")||"deepseek-v4-pro-0813":Q==="OpenRouter"?de("janitor_open_router"):u||(ne===Me?de("janitor_default"):de("gemma_janitor_fallback_google"));await Vt("tokens",Ze,Q,wt),ct>0&&await Vt("cachedTokens",ct,Q,wt),He>0&&await Vt("candidateTokens",He,Q,wt)}}else throw new Error("No synthesis generated by Janitor.");d&&(d(),await Dt("background"));let We=rr(W),Ne=!1;for(let Ze of We){let ct=Ze.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(ct)&&(Ne=!0);let He={chatId:m,sessionId:m,history:o},wt=await ms(ct,Ze.args,He);ct.toLowerCase()==="memory"&&(Ze.args.includes("action='user'")||Ze.args.includes('action="user"'))&&!wt.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(Tt=>setTimeout(Tt,3e3)))}if(!Ne)try{let Ze=se(Ut,[]);if(Ze.length>0){let ct=[];for(let He of Ze)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);ye(Ut,ct)}}catch{}break}catch(O){ne++;let B=new Date().toLocaleString(),J=O instanceof Error?(()=>{try{return JSON.parse(JSON.parse(O.message).error.message).error.message}catch{return String(O)}})():String(O);await new Promise(Ne=>setTimeout(Ne,1e3));let Q=te.join(yn,"janitor");if(Fe.existsSync(Q)||Fe.mkdirSync(Q,{recursive:!0}),Fe.appendFileSync(te.join(Q,"error.log"),`ERROR [Attempt ${ne}/${Me+1}] [${B}]: ${J}
949
949
 
950
- `),ne>Me)break;let We=Math.min(750*Math.pow(2,ne-1),5e3);await new Promise(Ne=>setTimeout(Ne,We))}if(ne){let O=te.join(hn,"janitor");Fe.appendFileSync(te.join(O,"error.log"),`-----------------------------------------------------------------------------
950
+ `),ne>Me)break;let We=Math.min(750*Math.pow(2,ne-1),5e3);await new Promise(Ne=>setTimeout(Ne,We))}if(ne){let O=te.join(yn,"janitor");Fe.appendFileSync(te.join(O,"error.log"),`-----------------------------------------------------------------------------
951
951
 
952
- `)}if(process.stdout.isTTY)try{let J=(await fo())[m]?.name||"",Q=J&&!J.startsWith("flow-")&&!J.startsWith("Session ")?J:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${Q}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${Q}\x07`)}catch{process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")}},gd=e=>{let n=on(e),t=Do?n:n.replace(hl,s=>" ".repeat(s.length)).replace(gl,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}},yl=(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 f=e[l];if(d){if(f===d){let u=0;for(let m=l-1;m>=0&&e[m]==="\\";m--)u++;u%2===0&&(d=null)}}else if(f==='"'||f==="'"||f==="`")d=f;else if(f==="(")p++;else if(f===")"&&(p--,p===0)){let u=l+1;for(;u<e.length&&/\s/.test(e[u]);)u++;if(u<e.length&&e[u]==="]"){c=u;break}}}if(c!==-1)o+="[tool:functions."+r[1]+"()]",s=c+1,t.lastIndex=s;else{o+="[tool:functions."+r[1]+"(",s=e.length;break}}return s<e.length&&(o+=n&&s===0?on(e.substring(s)):e.substring(s)),o},yd=(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 f=p;f<e.length;f++){let u=e[f];if(c){if(u===c){let m=0;for(let g=f-1;g>=0&&e[g]==="\\";g--)m++;m%2===0&&(c=null)}}else if(u==='"'||u==="'"||u==="`")c=u;else if(u==="(")d++;else if(u===")"&&(d--,d===0)){let m=f+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},pl=e=>yl(e,!0),wd=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("");cl.lastIndex=0;let o=e.replace(cl,(s,r,a)=>{let i="";try{let c=JSON.parse(a.trim());c&&typeof c=="object"&&(i=Object.entries(c).map(([f,u])=>{let m=typeof u=="string"?u:JSON.stringify(u);return`${f}=${JSON.stringify(m)}`}).join(", "))}catch{let l=[],f=ud;f.lastIndex=0;let u;for(;(u=f.exec(a))!==null;){let m=u[1],g=u[2]!==void 0?u[2]:u[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 dl.lastIndex=0,ul.lastIndex=0,o=o.replace(dl,""),o=o.replace(ul,""),o},xd=/(?:path|query|url|keyword|command|method|title|task|id)\s*=\s*['"`]?\s*\.\.\.\s*['"`]?/i,bd=/^['"`]?\s*\.\.\.\s*['"`]?$/,Wn=e=>{if(e==null)return!1;let n=String(e).trim();return n==="..."||n==="\u2026"||bd.test(n)},rr=e=>{if(!e)return[];let n=wd(e),t=on(n),o=[],s=Do?t:t.replace(hl,i=>" ".repeat(i.length)).replace(gl,i=>" ".repeat(i.length)),r=sd;r.lastIndex=0;let a;for(;(a=r.exec(s))!==null;){let i=a[1],p=a.index+a[0].length-1,d=0,c=null,l=-1,f=-1;for(let u=p;u<s.length;u++){let m=t[u];if(c){if(m===c){let g=0;for(let y=u-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)){f=u;let g=u+1;for(;g<s.length&&/\s/.test(s[g]);)g++;if(g<s.length&&s[g]==="]"){l=g;break}}}if(l!==-1){let u=t.substring(p+1,f),m=t.substring(a.index,l+1),g=D(u);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)||xd.test(u)||o.push({fullMatch:m,toolName:i.trim(),args:u.trim()}),r.lastIndex=l+1}}return o},Oy=(e,n={})=>{if(!e)return null;if(or=n,bi=new ml({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}}}},sr=async(e,n,t,o,s="Fast",r=.75,a="agent")=>pd(async()=>{let{aiProvider:i="Google",apiKey:p,mode:d}=e,c="",l=null,f=typeof t=="string"?[{role:"user",parts:[{text:t}]}]:t,u=new AbortController,m=u.signal,g=setInterval(()=>{It&&(u.abort(),clearInterval(g))},100);try{let y;i==="Ollama"?y=yi(p,n,f,o,s,d,xt(n),m,r,systemSettings?.ollamaEndpoint||"Cloud"):i==="OpenRouter"?y=Vs(p,n,f,o,s,d,xt(n),m,r):i==="DeepSeek"?y=zs(p,n,f,o,s,d,xt(n),m,r):i==="Mistral"?y=Ks(p,n,f,o,s,d,xt(n),m,r):i==="NVIDIA"?y=Ys(p,n,f,o,s,d,xt(n),m,r):i==="CrofAI"?y=Xs(p,n,f,o,s,d,xt(n),m,r):i==="InferX"?y=Js(p,n,f,o,s,d,xt(n),m,r):i==="SenseNova"?y=Qs(p,n,f,o,s,d,xt(n),m,r):i==="AIHubMix"?y=Zs(p,n,f,o,s,d,xt(n),m,r):i==="Poolside"?y=er(p,n,f,o,s,d,xt(n),m,r):i==="9router"||i==="9Router"?y=tr(p,n,f,o,s,d,xt(n),m,r):i==="ExpLabs"||i==="ExperientialLabs"?y=nr(p,n,f,o,s,d,xt(n),m,r):y=await ki(p).models.generateContentStream({model:n,contents:f,config:{systemInstruction:o,temperature:r,thinkingConfig:(()=>{let w=(n||"").toLowerCase(),T=w.includes("gemma-4")||w.startsWith("gemma"),$=w.includes("gemini-3");if(T||$)return T?s.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:mt.MINIMAL}:{includeThoughts:!0,thinkingLevel:mt.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:w.includes("pro")?mt.LOW:mt.MINIMAL,Low:mt.LOW,Medium:mt.MEDIUM,Standard:mt.MEDIUM,High:mt.HIGH,xHigh:mt.HIGH}[s]||mt.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(It)throw new Error("Subagent task was cancelled.");if(e?.taskId&&typeof Qe<"u"){let T=Qe.find($=>$.id===e.taskId);if(T&&T.status==="cancelled")throw new Error("Subagent task was cancelled.")}let b="";if(h.candidates?.[0]?.content?.parts)for(let T of h.candidates[0].content.parts)T.text&&!T.thought&&(c+=T.text,b+=T.text);let w=b?b.trim().split(/\s+/).filter(Boolean).length:0;e&&typeof e.onTokenChunk=="function"&&e.onTokenChunk(b,w),h.usageMetadata&&(l=h.usageMetadata)}}finally{clearInterval(g)}if(l){let y=l.totalTokenCount||0,h=l.cachedContentTokenCount||0,b=(l.candidatesTokenCount||0)+(l.thoughtsTokenCount||0);await zt("tokens",y,i,n),h>0&&await zt("cachedTokens",h,i,n),b>0&&await zt("candidateTokens",b,i,n),e&&typeof e.onUsage=="function"&&e.onUsage({totalTokenCount:y,cachedContentTokenCount:h,candidatesTokenCount:b})}return await Ot("agent",i),{text:c,usageMetadata:l}}),kd=async(e,n,t=null)=>{t=t||se(en,{});try{let{aiProvider:o="Google"}=n;if(Object.values(t).flat().length<=5)return;let r=Object.keys(t).filter(f=>f!==e&&Array.isArray(t[f])&&t[f].length>2);if(r.length===0)return;let a=`You are a silent background process for the FluxFlow CLI Agent.
952
+ `)}if(process.stdout.isTTY)try{let J=(await fo())[m]?.name||"",Q=J&&!J.startsWith("flow-")&&!J.startsWith("Session ")?J:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${Q}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${Q}\x07`)}catch{process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")}},gd=e=>{let n=rn(e),t=Do?n:n.replace(hl,s=>" ".repeat(s.length)).replace(gl,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}},yl=(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?rn(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 f=e[l];if(d){if(f===d){let u=0;for(let m=l-1;m>=0&&e[m]==="\\";m--)u++;u%2===0&&(d=null)}}else if(f==='"'||f==="'"||f==="`")d=f;else if(f==="(")p++;else if(f===")"&&(p--,p===0)){let u=l+1;for(;u<e.length&&/\s/.test(e[u]);)u++;if(u<e.length&&e[u]==="]"){c=u;break}}}if(c!==-1)o+="[tool:functions."+r[1]+"()]",s=c+1,t.lastIndex=s;else{o+="[tool:functions."+r[1]+"(",s=e.length;break}}return s<e.length&&(o+=n&&s===0?rn(e.substring(s)):e.substring(s)),o},yd=(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 f=p;f<e.length;f++){let u=e[f];if(c){if(u===c){let m=0;for(let g=f-1;g>=0&&e[g]==="\\";g--)m++;m%2===0&&(c=null)}}else if(u==='"'||u==="'"||u==="`")c=u;else if(u==="(")d++;else if(u===")"&&(d--,d===0)){let m=f+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},pl=e=>yl(e,!0),wd=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("");cl.lastIndex=0;let o=e.replace(cl,(s,r,a)=>{let i="";try{let c=JSON.parse(a.trim());c&&typeof c=="object"&&(i=Object.entries(c).map(([f,u])=>{let m=typeof u=="string"?u:JSON.stringify(u);return`${f}=${JSON.stringify(m)}`}).join(", "))}catch{let l=[],f=ud;f.lastIndex=0;let u;for(;(u=f.exec(a))!==null;){let m=u[1],g=u[2]!==void 0?u[2]:u[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 dl.lastIndex=0,ul.lastIndex=0,o=o.replace(dl,""),o=o.replace(ul,""),o},xd=/(?:path|query|url|keyword|command|method|title|task|id)\s*=\s*['"`]?\s*\.\.\.\s*['"`]?/i,bd=/^['"`]?\s*\.\.\.\s*['"`]?$/,Gn=e=>{if(e==null)return!1;let n=String(e).trim();return n==="..."||n==="\u2026"||bd.test(n)},rr=e=>{if(!e)return[];let n=wd(e),t=rn(n),o=[],s=Do?t:t.replace(hl,i=>" ".repeat(i.length)).replace(gl,i=>" ".repeat(i.length)),r=sd;r.lastIndex=0;let a;for(;(a=r.exec(s))!==null;){let i=a[1],p=a.index+a[0].length-1,d=0,c=null,l=-1,f=-1;for(let u=p;u<s.length;u++){let m=t[u];if(c){if(m===c){let g=0;for(let y=u-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)){f=u;let g=u+1;for(;g<s.length&&/\s/.test(s[g]);)g++;if(g<s.length&&s[g]==="]"){l=g;break}}}if(l!==-1){let u=t.substring(p+1,f),m=t.substring(a.index,l+1),g=D(u);Gn(g.path)||Gn(g.query)||Gn(g.url)||Gn(g.keyword)||Gn(g.command)||Gn(g.method)||Gn(g.title)||Gn(g.task)||Gn(g.id)||xd.test(u)||o.push({fullMatch:m,toolName:i.trim(),args:u.trim()}),r.lastIndex=l+1}}return o},Oy=(e,n={})=>{if(!e)return null;if(or=n,bi=new ml({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}}}},sr=async(e,n,t,o,s="Fast",r=.75,a="agent")=>pd(async()=>{let{aiProvider:i="Google",apiKey:p,mode:d}=e,c="",l=null,f=typeof t=="string"?[{role:"user",parts:[{text:t}]}]:t,u=new AbortController,m=u.signal,g=setInterval(()=>{Lt&&(u.abort(),clearInterval(g))},100);try{let y;i==="Ollama"?y=yi(p,n,f,o,s,d,bt(n),m,r,systemSettings?.ollamaEndpoint||"Cloud"):i==="OpenRouter"?y=Vs(p,n,f,o,s,d,bt(n),m,r):i==="DeepSeek"?y=zs(p,n,f,o,s,d,bt(n),m,r):i==="Mistral"?y=Ks(p,n,f,o,s,d,bt(n),m,r):i==="NVIDIA"?y=Ys(p,n,f,o,s,d,bt(n),m,r):i==="CrofAI"?y=Xs(p,n,f,o,s,d,bt(n),m,r):i==="InferX"?y=Js(p,n,f,o,s,d,bt(n),m,r):i==="SenseNova"?y=Qs(p,n,f,o,s,d,bt(n),m,r):i==="AIHubMix"?y=Zs(p,n,f,o,s,d,bt(n),m,r):i==="Poolside"?y=er(p,n,f,o,s,d,bt(n),m,r):i==="9router"||i==="9Router"?y=tr(p,n,f,o,s,d,bt(n),m,r):i==="ExpLabs"||i==="ExperientialLabs"?y=nr(p,n,f,o,s,d,bt(n),m,r):y=await ki(p).models.generateContentStream({model:n,contents:f,config:{systemInstruction:o,temperature:r,thinkingConfig:(()=>{let w=(n||"").toLowerCase(),T=w.includes("gemma-4")||w.startsWith("gemma"),$=w.includes("gemini-3");if(T||$)return T?s.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:mt.MINIMAL}:{includeThoughts:!0,thinkingLevel:mt.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:w.includes("pro")?mt.LOW:mt.MINIMAL,Low:mt.LOW,Medium:mt.MEDIUM,Standard:mt.MEDIUM,High:mt.HIGH,xHigh:mt.HIGH}[s]||mt.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(Lt)throw new Error("Subagent task was cancelled.");if(e?.taskId&&typeof Qe<"u"){let T=Qe.find($=>$.id===e.taskId);if(T&&T.status==="cancelled")throw new Error("Subagent task was cancelled.")}let b="";if(h.candidates?.[0]?.content?.parts)for(let T of h.candidates[0].content.parts)T.text&&!T.thought&&(c+=T.text,b+=T.text);let w=b?b.trim().split(/\s+/).filter(Boolean).length:0;e&&typeof e.onTokenChunk=="function"&&e.onTokenChunk(b,w),h.usageMetadata&&(l=h.usageMetadata)}}finally{clearInterval(g)}if(l){let y=l.totalTokenCount||0,h=l.cachedContentTokenCount||0,b=(l.candidatesTokenCount||0)+(l.thoughtsTokenCount||0);await Vt("tokens",y,i,n),h>0&&await Vt("cachedTokens",h,i,n),b>0&&await Vt("candidateTokens",b,i,n),e&&typeof e.onUsage=="function"&&e.onUsage({totalTokenCount:y,cachedContentTokenCount:h,candidatesTokenCount:b})}return await Dt("agent",i),{text:c,usageMetadata:l}}),kd=async(e,n,t=null)=>{t=t||se(nn,{});try{let{aiProvider:o="Google"}=n;if(Object.values(t).flat().length<=5)return;let r=Object.keys(t).filter(f=>f!==e&&Array.isArray(t[f])&&t[f].length>2);if(r.length===0)return;let a=`You are a silent background process for the FluxFlow CLI Agent.
953
953
  Your task is to summarize or merge temporary context memories from one or more past conversation sessions.
954
954
  For each Chat ID provided, you must output a tool call to save the consolidated summary.
955
955
 
@@ -964,7 +964,7 @@ Guidelines:
964
964
 
965
965
  Chats to process:
966
966
 
967
- `,i=se(Pn,{});for(let f of r){let m=t[f].map(y=>`- ${y}`).join(`
967
+ `,i=se(Nn,{});for(let f of r){let m=t[f].map(y=>`- ${y}`).join(`
968
968
  `),g=i[f];a+=`[Chat ID: ${f}]
969
969
  `,g?(a+=`- Existing Summary: "${g}"
970
970
  `,a+=`
@@ -974,7 +974,7 @@ ${m}
974
974
  `):a+=`-- Individual Memories:
975
975
  ${m}
976
976
 
977
- `}let p=0,d=5,c=!1,l=de("gemma_janitor_fallback_google");for(o==="OpenRouter"&&(l=de("janitor_open_router")),o==="DeepSeek"&&(l=de("deepseek_level_1")),o==="Mistral"&&(l=de("mistral_level_1")),o==="NVIDIA"&&(l=de("nvidia_janitor_fallback")),o==="CrofAI"&&(l=de("crofai_fallback")),o==="InferX"&&(l=de("inferx_fallback")),o==="SenseNova"&&(l=de("sensenova_fallback")),o==="AIHubMix"&&(l=de("aihubmix_fallback")),o==="Poolside"&&(l=de("poolside_fallback")),(o==="9router"||o==="9Router")&&(l=de("9router_fallback"));p<=d&&!c;){p++;try{let u=(await sr(n,l,a,null,"Fast",.75,"background")).text||"",m=rr(u);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(f){if(p>=d)throw new Error(`Failed after ${d} attempts. Last error: ${f.message}`)}}}catch(o){let s=o instanceof Error?(()=>{try{return JSON.parse(JSON.parse(o.message).error.message).error.message}catch{return String(o)}})():String(o),r=te.join(hn,"janitor");Fe.existsSync(r)||Fe.mkdirSync(r,{recursive:!0}),Fe.appendFileSync(te.join(r,"error.log"),`[${new Date().toLocaleString()}] Past memory batch consolidation error: ${s}
977
+ `}let p=0,d=5,c=!1,l=de("gemma_janitor_fallback_google");for(o==="OpenRouter"&&(l=de("janitor_open_router")),o==="DeepSeek"&&(l=de("deepseek_level_1")),o==="Mistral"&&(l=de("mistral_level_1")),o==="NVIDIA"&&(l=de("nvidia_janitor_fallback")),o==="CrofAI"&&(l=de("crofai_fallback")),o==="InferX"&&(l=de("inferx_fallback")),o==="SenseNova"&&(l=de("sensenova_fallback")),o==="AIHubMix"&&(l=de("aihubmix_fallback")),o==="Poolside"&&(l=de("poolside_fallback")),(o==="9router"||o==="9Router")&&(l=de("9router_fallback"));p<=d&&!c;){p++;try{let u=(await sr(n,l,a,null,"Fast",.75,"background")).text||"",m=rr(u);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(f){if(p>=d)throw new Error(`Failed after ${d} attempts. Last error: ${f.message}`)}}}catch(o){let s=o instanceof Error?(()=>{try{return JSON.parse(JSON.parse(o.message).error.message).error.message}catch{return String(o)}})():String(o),r=te.join(yn,"janitor");Fe.existsSync(r)||Fe.mkdirSync(r,{recursive:!0}),Fe.appendFileSync(te.join(r,"error.log"),`[${new Date().toLocaleString()}] Past memory batch consolidation error: ${s}
978
978
  `)}},Sd=async(e,n,t=!1)=>{let{chatId:o,aiProvider:s="Google"}=e,r=te.join(Ts,"chat-summaries.json"),a=u=>u.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(`
979
979
 
980
980
  `),i=async(u,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:
@@ -986,53 +986,53 @@ ${u}
986
986
  Provide a new consolidated summary of the entire session.`:`Here is the conversation history:
987
987
  ${u}
988
988
 
989
- Provide a consolidated summary of the entire session.`,h=de("gemma_janitor_fallback_google");s==="OpenRouter"&&(h=de("janitor_open_router")),s==="DeepSeek"&&(h=de("deepseek_level_1")),s==="Mistral"&&(h=de("mistral_level_1")),s==="NVIDIA"&&(h=de("nvidia_chat_summarizer_fallback")),s==="CrofAI"&&(h=de("crofai_fallback")),s==="InferX"&&(h=de("inferx_fallback")),s==="SenseNova"&&(h=de("sensenova_fallback")),s==="AIHubMix"&&(h=de("aihubmix_fallback")),s==="Poolside"&&(h=de("poolside_fallback")),(s==="9router"||s==="9Router")&&(h=de("9router_fallback")),(s==="ExpLabs"||s==="ExperientialLabs")&&(h=de("explabs_fallback")||"deepseek-v4-pro-0813");let b=0,w=!1,T=null;for(;b<=3&&!w;){b++;try{T=await sr(e,h,y,g,"Fast"),w=!0}catch{if(b>3){if(s==="Google")try{let R=de("general_fallback");return(await sr(e,R,y,g,"Fast")).text||""}catch{return""}return""}}}return T&&T.text||""},p=a(n),d=se(r,{}),c=d[o]||{summary:"",historyLength:0};typeof c=="string"&&(c={summary:c,historyLength:0});let l=c.summary||"",f=await i(p,l);if(f){c.summary=f;let u=md(n);return t?c.historyLength=(c.historyLength||0)+u:c.historyLength=u,d[o]=c,ye(r,d),f}return null},Ly=e=>{try{let n=te.join(Ts,"chat-summaries.json");if(Fe.existsSync(n)){let t=se(n,{});t[e]&&(delete t[e],ye(n,t))}}catch{}},Dy=async function*(e,n,t,o,s){let{profile:r,thinkingLevel:a,mode:i,janitorModel:p,chatId:d,isPlayground:c,systemSettings:l,sessionStats:f,aiProvider:u="Google",apiTier:m,wildcardTooling:g}=t,y=xt(e);if(!bi&&u==="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"||t?.aiProvider==="Poolside"||t?.aiProvider==="9router"||t?.aiProvider==="ExpLabs"||t?.aiProvider==="ExperientialLabs"?!1:l?.memory!==!1,b=n[n.length-1].text,w=te.join(Ts,"chat-summaries.json"),T=!1,$=n.filter(E=>E.role==="user").length===1,R=b.includes("[TITLE-UPDATE]"),k=$||R,S=b.replace(/\[TITLE-UPDATE\]/g,"").trim();S=S.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),yield{type:"status",content:"[start]"},yield{type:"status",content:"Gathering Context"},await gt.startTransaction(d,S),l?.advanceRollback&&await Zn.takeInitialSnapshot(d),It=!1;let _=null;try{let E=new AbortController;_=setInterval(()=>{It&&(E.abort(),_&&(clearInterval(_),_=null))},400);let x=[...n.slice(0,-1)];{let Pe=se(w,{})[d]||{summary:"",historyLength:0};if(Pe.summary&&Pe.historyLength>0){let sn=0,Ee=[];for(let ot=0;ot<x.length;ot++){let ze=x[ot];(ze.role==="user"||ze.role==="agent"||ze.role==="system")&&!String(ze.id).startsWith("welcome")&&!ze.isMeta&&sn++,sn>Pe.historyLength&&Ee.push(ze)}x=Ee}}x=x.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 C=process.env.HIGH_CONTEXT,M=process.env.GOOGLE_GEMMA_NONSENSE==="true"||process.env.GOOGLE_GEMMA_NONSENSE===!0||!1,v=255e3,L=26e4;if(C&&C!=="false"){let z=parseInt(C,10);!isNaN(z)&&z>=0&&z<=1e6&&(L=z,v=Math.round(z*.85))}if((u==="NVIDIA"&&(e?.includes("gpt")||e?.includes("qwen")||e?.includes("medium")||e.includes("muse"))||u==="Mistral")&&(v=122e3,L=126e3),u==="Google"&&e?.includes("gemma")&&M&&(v=14e3,L=16e3),(u==="Ollama"||u==="9router"||u==="9Router"||u==="ExpLabs"||u==="ExperientialLabs")&&(f?.tokens||0)>v){yield{type:"text",content:"\u2726 Maximum Context Limit Reached. Start a new chat."};return}if(u!=="Ollama"&&u!=="9router"&&u!=="9Router"&&u!=="ExpLabs"&&u!=="ExperientialLabs"&&(f?.tokens||0)>v&&(yield{type:"status_history",content:"Context Limit Reached. Condensing session history..."},await Sd(t,x,!0)&&(x=[],T=!0)),$&&h){let z=se(en,{});Object.values(z).flat().length>5&&(yield{type:"status",content:"Condensing past chat memories"},await kd(d,t,z))}let U=se(en,{}),j=se(Pn,{}),ee=Object.entries(U).filter(([z])=>z!==d).flatMap(([z,Pe])=>Pe),F=[...Object.entries(j).filter(([z])=>z!==d).slice(-20).map(([z,Pe])=>`[Chat Summary]: ${Pe}`),...ee].map(z=>`- ${z}`).join(`
990
- `),ne=se(Ft,[]).map(z=>`- ${z.memory}`).join(`
991
- `),Me=(f?.tokens||0)>=1e4,O=wa(F,ne,h,Me),B=new Date,J=B.getFullYear(),Q=B.toLocaleString("en-US",{month:"short"}).toUpperCase(),We=String(B.getDate()).padStart(2,"0"),Ne=B.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}),Ze=`${J}-${Q}-${We}, ${Ne}`,dt=[".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[]}},yt=(z,Pe={value:0},sn=1)=>{if(Pe.value>6200||sn>7)return Pe.value;let Ee=He(z);for(let ot of Ee){if(Pe.value>6200)break;dt.includes(ot.name)||ot.name.startsWith(".")||ot.isDirectory()&&(Pe.value++,yt(te.join(z,ot.name),Pe,sn+1))}return Pe.value},To=(z,Pe)=>l?.indentationTree!==!1?mi(z,Pe,1,He,dt):gi(z,Pe,"",1,He,dt),St=yt(process.cwd()),Ve=10;St>3072||St>2304?Ve=1:St>1536?Ve=2:St>768?Ve=3:St>384?Ve=5:St>192?Ve=6:St>96?Ve=7:(St>48||St>24)&&(Ve=9);let $t=se(fr,{}),qe=$t[d],fe=qe?qe!==process.cwd():!1;$t[d]=process.cwd(),ye(fr,$t);let le=se(w,{}),nt=le[d]||{summary:"",historyLength:0};typeof nt=="string"&&(nt={summary:nt,historyLength:0});let ys=n.filter(z=>(z.role==="user"||z.role==="agent"||z.role==="system")&&!String(z.id).startsWith("welcome")&&!z.isMeta).length;nt.historyLength&&ys<nt.historyLength&&(nt.summary="",nt.historyLength=0,le[d]=nt,ye(w,le));let An=typeof nt=="object"?nt.summary||"":nt||"",Si=x.length>0;Si&&An&&x[0]&&(x[0].role==="user"||x[0].role==="system")&&(x[0].text.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")||(x[0].text=`[SYSTEM METADATA]
989
+ Provide a consolidated summary of the entire session.`,h=de("gemma_janitor_fallback_google");s==="OpenRouter"&&(h=de("janitor_open_router")),s==="DeepSeek"&&(h=de("deepseek_level_1")),s==="Mistral"&&(h=de("mistral_level_1")),s==="NVIDIA"&&(h=de("nvidia_chat_summarizer_fallback")),s==="CrofAI"&&(h=de("crofai_fallback")),s==="InferX"&&(h=de("inferx_fallback")),s==="SenseNova"&&(h=de("sensenova_fallback")),s==="AIHubMix"&&(h=de("aihubmix_fallback")),s==="Poolside"&&(h=de("poolside_fallback")),(s==="9router"||s==="9Router")&&(h=de("9router_fallback")),(s==="ExpLabs"||s==="ExperientialLabs")&&(h=de("explabs_fallback")||"deepseek-v4-pro-0813");let b=0,w=!1,T=null;for(;b<=3&&!w;){b++;try{T=await sr(e,h,y,g,"Fast"),w=!0}catch{if(b>3){if(s==="Google")try{let R=de("general_fallback");return(await sr(e,R,y,g,"Fast")).text||""}catch{return""}return""}}}return T&&T.text||""},p=a(n),d=se(r,{}),c=d[o]||{summary:"",historyLength:0};typeof c=="string"&&(c={summary:c,historyLength:0});let l=c.summary||"",f=await i(p,l);if(f){c.summary=f;let u=md(n);return t?c.historyLength=(c.historyLength||0)+u:c.historyLength=u,d[o]=c,ye(r,d),f}return null},Ly=e=>{try{let n=te.join(Ts,"chat-summaries.json");if(Fe.existsSync(n)){let t=se(n,{});t[e]&&(delete t[e],ye(n,t))}}catch{}},Dy=async function*(e,n,t,o,s){let{profile:r,thinkingLevel:a,mode:i,janitorModel:p,chatId:d,isPlayground:c,systemSettings:l,sessionStats:f,aiProvider:u="Google",apiTier:m,wildcardTooling:g}=t,y=bt(e);if(!bi&&u==="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"||t?.aiProvider==="Poolside"||t?.aiProvider==="9router"||t?.aiProvider==="ExpLabs"||t?.aiProvider==="ExperientialLabs"?!1:l?.memory!==!1,b=n[n.length-1].text,w=te.join(Ts,"chat-summaries.json"),T=!1,$=n.filter(E=>E.role==="user").length===1,R=b.includes("[TITLE-UPDATE]"),k=$||R,S=b.replace(/\[TITLE-UPDATE\]/g,"").trim();S=S.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),yield{type:"status",content:"[start]"},yield{type:"status",content:"Gathering Context"},await yt.startTransaction(d,S),l?.advanceRollback&&await Zn.takeInitialSnapshot(d),Lt=!1;let _=null;try{let E=new AbortController;_=setInterval(()=>{Lt&&(E.abort(),_&&(clearInterval(_),_=null))},400);let x=[...n.slice(0,-1)];{let Pe=se(w,{})[d]||{summary:"",historyLength:0};if(Pe.summary&&Pe.historyLength>0){let an=0,Ee=[];for(let ot=0;ot<x.length;ot++){let ze=x[ot];(ze.role==="user"||ze.role==="agent"||ze.role==="system")&&!String(ze.id).startsWith("welcome")&&!ze.isMeta&&an++,an>Pe.historyLength&&Ee.push(ze)}x=Ee}}x=x.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 C=process.env.HIGH_CONTEXT,M=process.env.GOOGLE_GEMMA_NONSENSE==="true"||process.env.GOOGLE_GEMMA_NONSENSE===!0||!1,v=255e3,L=26e4;if(C&&C!=="false"){let z=parseInt(C,10);!isNaN(z)&&z>=0&&z<=1e6&&(L=z,v=Math.round(z*.85))}if((u==="NVIDIA"&&(e?.includes("gpt")||e?.includes("qwen")||e?.includes("medium")||e.includes("muse"))||u==="Mistral")&&(v=122e3,L=126e3),u==="Google"&&e?.includes("gemma")&&M&&(v=14e3,L=16e3),(u==="Ollama"||u==="9router"||u==="9Router"||u==="ExpLabs"||u==="ExperientialLabs")&&(f?.tokens||0)>v){yield{type:"text",content:"\u2726 Maximum Context Limit Reached. Start a new chat."};return}if(u!=="Ollama"&&u!=="9router"&&u!=="9Router"&&u!=="ExpLabs"&&u!=="ExperientialLabs"&&(f?.tokens||0)>v&&(yield{type:"status_history",content:"Context Limit Reached. Condensing session history..."},await Sd(t,x,!0)&&(x=[],T=!0)),$&&h){let z=se(nn,{});Object.values(z).flat().length>5&&(yield{type:"status",content:"Condensing past chat memories"},await kd(d,t,z))}let U=se(nn,{}),j=se(Nn,{}),ee=Object.entries(U).filter(([z])=>z!==d).flatMap(([z,Pe])=>Pe),F=[...Object.entries(j).filter(([z])=>z!==d).slice(-20).map(([z,Pe])=>`[Chat Summary]: ${Pe}`),...ee].map(z=>`- ${z}`).join(`
990
+ `),ne=se(Ut,[]).map(z=>`- ${z.memory}`).join(`
991
+ `),Me=(f?.tokens||0)>=1e4,O=wa(F,ne,h,Me),B=new Date,J=B.getFullYear(),Q=B.toLocaleString("en-US",{month:"short"}).toUpperCase(),We=String(B.getDate()).padStart(2,"0"),Ne=B.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}),Ze=`${J}-${Q}-${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[]}},wt=(z,Pe={value:0},an=1)=>{if(Pe.value>6200||an>7)return Pe.value;let Ee=He(z);for(let ot of Ee){if(Pe.value>6200)break;ct.includes(ot.name)||ot.name.startsWith(".")||ot.isDirectory()&&(Pe.value++,wt(te.join(z,ot.name),Pe,an+1))}return Pe.value},To=(z,Pe)=>l?.indentationTree!==!1?mi(z,Pe,1,He,ct):gi(z,Pe,"",1,He,ct),Tt=wt(process.cwd()),Ve=10;Tt>3072||Tt>2304?Ve=1:Tt>1536?Ve=2:Tt>768?Ve=3:Tt>384?Ve=5:Tt>192?Ve=6:Tt>96?Ve=7:(Tt>48||Tt>24)&&(Ve=9);let At=se(fr,{}),qe=At[d],fe=qe?qe!==process.cwd():!1;At[d]=process.cwd(),ye(fr,At);let le=se(w,{}),nt=le[d]||{summary:"",historyLength:0};typeof nt=="string"&&(nt={summary:nt,historyLength:0});let ys=n.filter(z=>(z.role==="user"||z.role==="agent"||z.role==="system")&&!String(z.id).startsWith("welcome")&&!z.isMeta).length;nt.historyLength&&ys<nt.historyLength&&(nt.summary="",nt.historyLength=0,le[d]=nt,ye(w,le));let vn=typeof nt=="object"?nt.summary||"":nt||"",Si=x.length>0;Si&&vn&&x[0]&&(x[0].role==="user"||x[0].role==="system")&&(x[0].text.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")||(x[0].text=`[SYSTEM METADATA]
992
992
  **CONTEXT SUMMARY OF PREVIOUS TURNS (PRIORITY: DYNAMIC)**
993
- ${An}
993
+ ${vn}
994
994
 
995
- [USER] ${x[0].text}`,yield{type:"summary_injected",content:{id:x[0].id,text:x[0].text}}));let Ti=An&&!Si?`
995
+ [USER] ${x[0].text}`,yield{type:"summary_injected",content:{id:x[0].id,text:x[0].text}}));let Ti=vn&&!Si?`
996
996
  [SYSTEM METADATA]
997
997
  **CONTEXT SUMMARY OF PREVIOUS TURNS**
998
- ${An}
998
+ ${vn}
999
999
  `:"",Ri=!!l?.dynamicDirAwareness,wl=`${d}|${u}|${a}|${e}|${r}|${Ri}`,Ei=!Ri&&ko.key===wl&&ko.value?"":`
1000
1000
  **Directory Structure**
1001
1001
  CWD: `+process.cwd()+`${c?" [PLAYGROUND MODE]":""}
1002
- `+To(process.cwd(),Ve),Tt=await xo(),jn="";if(Hs()&&Tt.file_focused!=="none"){jn=`
1002
+ `+To(process.cwd(),Ve),Rt=await xo(),Hn="";if(Hs()&&Rt.file_focused!=="none"){Hn=`
1003
1003
  [Additional IDE Context]
1004
- `;let z=te.relative(process.cwd(),Tt.file_focused),Pe=(Tt.opened_editors||[]).map(Ee=>{let ot=te.relative(process.cwd(),Ee);return ot.startsWith("..")?`[External] ${te.basename(Ee)}`:ot});if(jn+=`Focused File: ${z}
1005
- Cursor Line: ${Tt.cursor_line}
1006
- `,Tt.selected){let Ee=Tt.selected,ot=Ee.split(`
1004
+ `;let z=te.relative(process.cwd(),Rt.file_focused),Pe=(Rt.opened_editors||[]).map(Ee=>{let ot=te.relative(process.cwd(),Ee);return ot.startsWith("..")?`[External] ${te.basename(Ee)}`:ot});if(Hn+=`Focused File: ${z}
1005
+ Cursor Line: ${Rt.cursor_line}
1006
+ `,Rt.selected){let Ee=Rt.selected,ot=Ee.split(`
1007
1007
  `);ot.length>256&&(Ee=ot.slice(0,240).join(`
1008
1008
  `)+`
1009
1009
  ... [truncated] ...
1010
1010
  `+ot.slice(-16).join(`
1011
1011
  `)),Ee.length>2048&&(Ee=Ee.slice(0,1920)+`
1012
1012
  ... [truncated] ...
1013
- `+Ee.slice(-128)),jn+=`Current Selection: "${Ee}"
1014
- `}if(Tt.manual_edits){let ot=Tt.manual_edits.split(`
1015
- `),ze=[],et=null;for(let K of ot)K.trim()&&(K.startsWith(" Line ")?et&&et.edits.push(K):(et={path:K.endsWith(":")?K.slice(0,-1):K,edits:[]},ze.push(et)));for(let K of ze)K.edits.length>80&&(K.edits=K.edits.slice(-80)),K.originalEditsCount=K.edits.length;let ge=(K,oe)=>oe.reduce((Ke,fn)=>{let Sn=Tt.file_focused&&(fn.path===Tt.file_focused||te.resolve(process.cwd(),fn.path)===te.resolve(Tt.file_focused))?Math.ceil(K*1.2):K;return Ke+Math.min(fn.edits.length,Sn)},0),Ut=80;if(ge(80,ze)>300){let K=!1;for(let oe=80;oe>=10;oe--)if(ge(oe,ze)<=300){Ut=oe,K=!0;break}K||(Ut=10)}let tt=[...ze];if(Ut===10&&ge(10,tt)>500)for(;tt.length>0&&ge(10,tt)>500;){let K=0,oe=tt[0].originalEditsCount;for(let Ke=1;Ke<tt.length;Ke++)tt[Ke].originalEditsCount<oe&&(oe=tt[Ke].originalEditsCount,K=Ke);tt.splice(K,1)}for(let K of tt){let Ke=Tt.file_focused&&(K.path===Tt.file_focused||te.resolve(process.cwd(),K.path)===te.resolve(Tt.file_focused))?Math.ceil(Ut*1.2):Ut;K.edits.length>Ke&&(K.edits=K.edits.slice(-Ke))}for(let K of tt){let oe=`${K.path}:
1013
+ `+Ee.slice(-128)),Hn+=`Current Selection: "${Ee}"
1014
+ `}if(Rt.manual_edits){let ot=Rt.manual_edits.split(`
1015
+ `),ze=[],et=null;for(let K of ot)K.trim()&&(K.startsWith(" Line ")?et&&et.edits.push(K):(et={path:K.endsWith(":")?K.slice(0,-1):K,edits:[]},ze.push(et)));for(let K of ze)K.edits.length>80&&(K.edits=K.edits.slice(-80)),K.originalEditsCount=K.edits.length;let ge=(K,oe)=>oe.reduce((Ke,mn)=>{let Rn=Rt.file_focused&&(mn.path===Rt.file_focused||te.resolve(process.cwd(),mn.path)===te.resolve(Rt.file_focused))?Math.ceil(K*1.2):K;return Ke+Math.min(mn.edits.length,Rn)},0),Wt=80;if(ge(80,ze)>300){let K=!1;for(let oe=80;oe>=10;oe--)if(ge(oe,ze)<=300){Wt=oe,K=!0;break}K||(Wt=10)}let tt=[...ze];if(Wt===10&&ge(10,tt)>500)for(;tt.length>0&&ge(10,tt)>500;){let K=0,oe=tt[0].originalEditsCount;for(let Ke=1;Ke<tt.length;Ke++)tt[Ke].originalEditsCount<oe&&(oe=tt[Ke].originalEditsCount,K=Ke);tt.splice(K,1)}for(let K of tt){let Ke=Rt.file_focused&&(K.path===Rt.file_focused||te.resolve(process.cwd(),K.path)===te.resolve(Rt.file_focused))?Math.ceil(Wt*1.2):Wt;K.edits.length>Ke&&(K.edits=K.edits.slice(-Ke))}for(let K of tt){let oe=`${K.path}:
1016
1016
  ${K.edits.join(`
1017
1017
  `)}`;for(;K.edits.length>0&&oe.length>4*768;)K.edits.shift(),oe=`${K.path}:
1018
1018
  ${K.edits.join(`
1019
- `)}`;oe.length>4*768?K.stringRepresentation="... "+oe.slice(-(4*768-4)):K.stringRepresentation=oe}let rn=tt.map(K=>K.stringRepresentation).join(`
1020
- `);for(;tt.length>0&&rn.length>4*2048;){tt[0].edits.length>0?tt[0].edits.shift():tt.shift();for(let K of tt){let oe=`${K.path}:
1019
+ `)}`;oe.length>4*768?K.stringRepresentation="... "+oe.slice(-(4*768-4)):K.stringRepresentation=oe}let ln=tt.map(K=>K.stringRepresentation).join(`
1020
+ `);for(;tt.length>0&&ln.length>4*2048;){tt[0].edits.length>0?tt[0].edits.shift():tt.shift();for(let K of tt){let oe=`${K.path}:
1021
1021
  ${K.edits.join(`
1022
- `)}`;oe.length>4*768?K.stringRepresentation="... "+oe.slice(-(4*768-4)):K.stringRepresentation=oe}rn=tt.map(K=>K.stringRepresentation).join(`
1023
- `)}rn.length>4*2048&&(rn="... "+rn.slice(-(4*2048-4))),jn+=`Recent Manual Edits:
1024
- ${rn}
1025
- `}Pe.length>0&&(jn+=`All Opened Editors: ${Pe.join(", ")}`),Tt.diagnostics&&(jn+=`
1022
+ `)}`;oe.length>4*768?K.stringRepresentation="... "+oe.slice(-(4*768-4)):K.stringRepresentation=oe}ln=tt.map(K=>K.stringRepresentation).join(`
1023
+ `)}ln.length>4*2048&&(ln="... "+ln.slice(-(4*2048-4))),Hn+=`Recent Manual Edits:
1024
+ ${ln}
1025
+ `}Pe.length>0&&(Hn+=`All Opened Editors: ${Pe.join(", ")}`),Rt.diagnostics&&(Hn+=`
1026
1026
  **Active File Errors**:
1027
- ${Tt.diagnostics}
1028
- `),(S.toLowerCase().includes("lint")||S.toLowerCase().includes("warning"))&&Tt.warnings&&(jn+=`
1027
+ ${Rt.diagnostics}
1028
+ `),(S.toLowerCase().includes("lint")||S.toLowerCase().includes("warning"))&&Rt.warnings&&(Hn+=`
1029
1029
  **Lint Warnings**:
1030
- ${Tt.warnings}
1031
- `)}let _i=S.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),Ci=/(?:\\)?@\[([^\]]+)\]/g,ir,ar=[];for(Ci.lastIndex=0;(ir=Ci.exec(_i))!==null;){let z=ir[0].startsWith("\\");ar.push({tag:ir[1],isEscaped:z})}let lr=[],ws=null;for(let z=0;z<ar.length;z++){let{tag:Pe,isEscaped:sn}=ar[z];if(!sn)try{let Ee=Pe.trim().replace(/^["']|["']$/g,""),ot=/[:#]L?(\d+)(?:-L?(\d+))?$/i,ze=Ee.match(ot),et=Ee,ge=null,Ut=null;ze&&(ge=parseInt(ze[1],10),Ut=ze[2]?parseInt(ze[2],10):ge,et=Ee.slice(0,ze.index));let tt=te.resolve(process.cwd(),et);if(Fe.existsSync(tt)&&Fe.statSync(tt).isFile()){let K=et.toLowerCase(),oe=K.endsWith(".pdf"),Ke=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),Bt=fn||oe||Ke,Sn=u==="Google"||xt(e);if(Bt&&!Sn){let je=`\u2718 Unsupported Modality: ${te.basename(et)}`,ke=115;process.stdout.isTTY&&(ke=process.stdout.columns-5||120);let Ye=[je],so=Math.max(...Ye.map(Gn=>Gn.length)),pn=Math.min(so+4,ke),Go=Ye.map(Gn=>`${Gn.padEnd(pn-2).substring(0,pn-2)}`).join(`
1032
- `);yield{type:"visual_feedback",content:nn(`${Go}
1033
- `)};continue}if(ge===null&&!Bt){let je=0;try{je=Fe.readFileSync(tt,"utf8").split(/\r\n|\r|\n/).length}catch{}if(je>300){let ke=`\u21B7 Skipped (Too Large): ${te.basename(et)}`,Ye=115;process.stdout.isTTY&&(Ye=process.stdout.columns-5||120);let so=Math.min(ke.length+4,Ye),pn=ke.padEnd(so-2).substring(0,so-2);yield{type:"visual_feedback",content:nn(`${pn}
1034
- `)};continue}}let vn=ge!==null?ge:1,no=Ut!==null?Ut:ge!==null?ge:vn+299;no-vn>300&&(no=vn+300);let bs=`path=${JSON.stringify(et)}, startLine=${vn}, endLine=${no}`,it=await ts(bs,{isMultiModal:Sn}),Xe=!1,Wt="",oo=null;if(typeof it=="string"?it.trim().startsWith("ERROR")?Xe=!0:Wt=it:it&&typeof it=="object"&&it.binaryPart?(oo=it.binaryPart,Wt=it.text||""):Xe=!0,!Xe){let je="";if(fn?(je=`\u2714 Processed: ${te.basename(et)}`,ws=oo):oe||Ke?(je=`\u2714 Auto-Analysed: ${te.basename(et)}`,ws=oo):(je=`\u2714 Auto-Read: ${te.basename(et)}`,lr.push(Wt)),je){let ke=115;process.stdout.isTTY&&(ke=process.stdout.columns-5||120);let Ye=[je],so=Math.max(...Ye.map(Gn=>Gn.length)),pn=Math.min(so+4,ke),Go=Ye.map(Gn=>`${Gn.padEnd(pn-2).substring(0,pn-2)}`).join(`
1035
- `);yield{type:"visual_feedback",content:nn(`${Go}
1030
+ ${Rt.warnings}
1031
+ `)}let _i=S.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),Ci=/(?:\\)?@\[([^\]]+)\]/g,ir,ar=[];for(Ci.lastIndex=0;(ir=Ci.exec(_i))!==null;){let z=ir[0].startsWith("\\");ar.push({tag:ir[1],isEscaped:z})}let lr=[],ws=null;for(let z=0;z<ar.length;z++){let{tag:Pe,isEscaped:an}=ar[z];if(!an)try{let Ee=Pe.trim().replace(/^["']|["']$/g,""),ot=/[:#]L?(\d+)(?:-L?(\d+))?$/i,ze=Ee.match(ot),et=Ee,ge=null,Wt=null;ze&&(ge=parseInt(ze[1],10),Wt=ze[2]?parseInt(ze[2],10):ge,et=Ee.slice(0,ze.index));let tt=te.resolve(process.cwd(),et);if(Fe.existsSync(tt)&&Fe.statSync(tt).isFile()){let K=et.toLowerCase(),oe=K.endsWith(".pdf"),Ke=K.endsWith(".docx")||K.endsWith(".doc")||K.endsWith(".ppt")||K.endsWith(".pptx")||K.endsWith(".xls")||K.endsWith(".xlsx"),mn=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(K),jt=mn||oe||Ke,Rn=u==="Google"||bt(e);if(jt&&!Rn){let je=`\u2718 Unsupported Modality: ${te.basename(et)}`,ke=115;process.stdout.isTTY&&(ke=process.stdout.columns-5||120);let Ye=[je],so=Math.max(...Ye.map(qn=>qn.length)),hn=Math.min(so+4,ke),Go=Ye.map(qn=>`${qn.padEnd(hn-2).substring(0,hn-2)}`).join(`
1032
+ `);yield{type:"visual_feedback",content:sn(`${Go}
1033
+ `)};continue}if(ge===null&&!jt){let je=0;try{je=Fe.readFileSync(tt,"utf8").split(/\r\n|\r|\n/).length}catch{}if(je>300){let ke=`\u21B7 Skipped (Too Large): ${te.basename(et)}`,Ye=115;process.stdout.isTTY&&(Ye=process.stdout.columns-5||120);let so=Math.min(ke.length+4,Ye),hn=ke.padEnd(so-2).substring(0,so-2);yield{type:"visual_feedback",content:sn(`${hn}
1034
+ `)};continue}}let On=ge!==null?ge:1,no=Wt!==null?Wt:ge!==null?ge:On+299;no-On>300&&(no=On+300);let bs=`path=${JSON.stringify(et)}, startLine=${On}, endLine=${no}`,it=await ts(bs,{isMultiModal:Rn}),Xe=!1,Gt="",oo=null;if(typeof it=="string"?it.trim().startsWith("ERROR")?Xe=!0:Gt=it:it&&typeof it=="object"&&it.binaryPart?(oo=it.binaryPart,Gt=it.text||""):Xe=!0,!Xe){let je="";if(mn?(je=`\u2714 Processed: ${te.basename(et)}`,ws=oo):oe||Ke?(je=`\u2714 Auto-Analysed: ${te.basename(et)}`,ws=oo):(je=`\u2714 Auto-Read: ${te.basename(et)}`,lr.push(Gt)),je){let ke=115;process.stdout.isTTY&&(ke=process.stdout.columns-5||120);let Ye=[je],so=Math.max(...Ye.map(qn=>qn.length)),hn=Math.min(so+4,ke),Go=Ye.map(qn=>`${qn.padEnd(hn-2).substring(0,hn-2)}`).join(`
1035
+ `);yield{type:"visual_feedback",content:sn(`${Go}
1036
1036
  `)}}}}}catch{}}let $i="";lr.length>0&&($i=`[Tagged File Contents] Auto Read User Tagged files by System, No need to re-read
1037
1037
  `+lr.join(`
1038
1038
 
@@ -1043,13 +1043,13 @@ Instead, output in chat the exact string you WOULD have produced & wait for syst
1043
1043
  `:"",kl=process.env.forcedReasoning||!1,Ai=`[System Metadata]
1044
1044
  Time: ${Ze}${l?.dynamicDirAwareness?Ei:""}${fe?`
1045
1045
  WARNING: CWD Changed from previous: "${qe}" to current: "${process.cwd()}", write change in chat to avoid future path mismatches
1046
- `:""}${O}${jn}
1046
+ `:""}${O}${Hn}
1047
1047
  [/Metadata]
1048
1048
  ${Ti}${a!=="Fast"&&(u==="Mistral"&&!vo(e)||a!=="xHigh"&&u==="Google")?`${u==="Mistral"&&!vo(e)||e.toLowerCase().startsWith("gemma")||kl?`[system] strictly follow thinking policy as high priority. do not start a response without <think>...</think> [/system]
1049
1049
  `:""}`:""}[system] exact tool string [tool:functions.ToolName(arg="value")] in chat [/system]
1050
- ${$i}${bl}[user prompt] ${xl.trim()} [/user prompt]`.trim(),Mi={role:"user",text:Ai};ws&&(Mi.binaryPart=ws),x.forEach(z=>{z.text&&z.role==="agent"&&(z.text=on(z.text))}),x.push(Mi),Ti&&n[n.length-1]?.id&&(yield{type:"summary_injected",content:{id:n[n.length-1].id,text:Ai}});let Mn=null,jo=i==="Flux"?100:10;jo=i.toLowerCase().includes("cu")?250:jo;let kn=16;yield{type:"status",content:"Connecting"},It=!1;let vi=[],xs=!1;for(let z=0;z<=jo;z++){let Pe=await Li("agent",t);if(!Pe.allowed)throw new Error(Pe.reason||`Budget Exhausted for Provider (${u||"Agent"})`);let sn=[];if(xs=!1,i==="ICU"||i==="FluxCU")try{yield{type:"status",content:"Capturing Screen"},await new Promise(Te=>setTimeout(Te,1e3));let pe=await Ui();if(pe&&pe.base64){let Te="[system] Fresh Gridded Screen Feedback Captured. Use numeric coordinates. Old screenshots will be removed when new screenshot is captured, summarize in text if context is needed later [/system]",me={inlineData:{mimeType:pe.mimeType,data:pe.base64}};for(let at of x)Array.isArray(at.parts)&&(at.parts=at.parts.filter(jt=>!jt.inlineData));if(x.length>0&&x[x.length-1].role==="user"){let at=x[x.length-1];typeof at.text=="string"&&(at.text+=`
1050
+ ${$i}${bl}[user prompt] ${xl.trim()} [/user prompt]`.trim(),Mi={role:"user",text:Ai};ws&&(Mi.binaryPart=ws),x.forEach(z=>{z.text&&z.role==="agent"&&(z.text=rn(z.text))}),x.push(Mi),Ti&&n[n.length-1]?.id&&(yield{type:"summary_injected",content:{id:n[n.length-1].id,text:Ai}});let In=null,jo=i==="Flux"?100:10;jo=i.toLowerCase().includes("cu")?250:jo;let Tn=16;yield{type:"status",content:"Connecting"},Lt=!1;let vi=[],xs=!1;for(let z=0;z<=jo;z++){let Pe=await Li("agent",t);if(!Pe.allowed)throw new Error(Pe.reason||`Budget Exhausted for Provider (${u||"Agent"})`);let an=[];if(xs=!1,i==="ICU"||i==="FluxCU")try{yield{type:"status",content:"Capturing Screen"},await new Promise(Te=>setTimeout(Te,1e3));let pe=await Ui();if(pe&&pe.base64){let Te="[system] Fresh Gridded Screen Feedback Captured. Use numeric coordinates. Old screenshots will be removed when new screenshot is captured, summarize in text if context is needed later [/system]",me={inlineData:{mimeType:pe.mimeType,data:pe.base64}},Ht=l?.imageHistoryCU||"Standard",Pt=Ht==="Low"?1:Ht==="Extended"?5:3,Mt=x.filter(ht=>Array.isArray(ht.parts)&&ht.parts.some(dt=>dt.inlineData));if(Mt.length>=Pt){let ht=Mt.length-Pt+1;for(let dt=0;dt<ht;dt++){let cn=Mt[dt];Array.isArray(cn.parts)&&(cn.parts=cn.parts.filter(qt=>!qt.inlineData))}}if(x.length>0&&x[x.length-1].role==="user"){let ht=x[x.length-1];typeof ht.text=="string"&&(ht.text+=`
1051
1051
 
1052
- ${Te}`,Array.isArray(at.parts)||(at.parts=[{text:at.text}]),at.parts.push(me))}else x.push({role:"user",text:Te,parts:[{text:Te},me]})}}catch(pe){console.error("Vision screenshot capture error:",pe)}if(l?.compression===0&&(f?.tokens||0)>L&&(x=Ta(x,6)),z>0?yield{type:"status",content:"Working"}:yield{type:"status",content:"Connecting"},It){try{let{clearPendingNudges:pe}=await import("./subagent_state-LZCOZSUJ.js");pe()}catch{}yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
1052
+ ${Te}`,Array.isArray(ht.parts)||(ht.parts=[{text:ht.text}]),ht.parts.push(me))}else x.push({role:"user",text:Te,parts:[{text:Te},me]})}}catch(pe){console.error("Vision screenshot capture error:",pe)}if(l?.compression===0&&(f?.tokens||0)>L&&(x=Ta(x,6)),z>0?yield{type:"status",content:"Working"}:yield{type:"status",content:"Connecting"},Lt){try{let{clearPendingNudges:pe}=await import("./subagent_state-LZCOZSUJ.js");pe()}catch{}yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
1053
1053
 
1054
1054
  \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}try{let{consumePendingNudges:pe}=await import("./subagent_state-LZCOZSUJ.js"),Te=pe();if(Te&&Te.length>0){let me=Te.join(`
1055
1055
 
@@ -1061,120 +1061,120 @@ ${me}`:x.push({role:"user",text:me}),yield{type:"status",content:"Subagent Updat
1061
1061
  [question] ${pe.replace("/btw","").trim()} [/question]`:x.push({role:"user",text:`[system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
1062
1062
  [question] ${pe.replace("/btw","").trim()} [/question]`}):x.length>0&&x[x.length-1].role==="user"?x[x.length-1].text+=`
1063
1063
 
1064
- [STEERING HINT from USER, High Priority] ${pe.trim()} [/STEERING HINT]`:x.push({role:"user",text:`[STEERING HINT from USER, High Priority] ${pe.trim()} [/STEERING HINT]`}),yield{type:"status",content:`${pe.startsWith("/btw")?"Question Forwarded...":"Steering Hint Injected..."}`})}let Ee,ot=!1,ze=1,et=1,ge="",Ut=null,tt=null,rn=null,K=0,oe=[],Ke=0,fn=!1,Bt=!1,Sn=!1,vn=!1,no=!0,bs=0,it="",Xe="",Wt=!1,oo=!1,je=!0,ke=e,Ye="";for(;ze<=kn&&et<=kn&&!ot&&!It;){let pe=!1;try{ge="",no&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},no=!1,et===1&&(it=""));let Te=N=>{if(!N||!N.includes("[tool:"))return N;let ae="",H=wi(N);H&&(ae=H.fullBlock,N=H.remainingText),N=N.replace(fd,(we,_e)=>_e.includes("[tool:")?_e.trim():we);let q="",Re=0;for(;Re<N.length;){let we=N.indexOf("[tool:",Re);if(we===-1){q+=fl(N.substring(Re));break}let _e=N.substring(Re,we);q+=fl(_e);let st=-1,G=null,re=0;for(let Ue=we;Ue<N.length;Ue++){let A=N[Ue];if(G){if(A===G){let Be=0;for(let ve=Ue-1;ve>=0&&N[ve]==="\\";ve--)Be++;Be%2===0&&(G=null)}}else if(A==='"'||A==="'"||A==="`")G=A;else if(A==="(")re++;else if(A===")")re--;else if(A==="]"&&re<=0){st=Ue;break}}if(st===-1){q+=N.substring(we);break}q+=N.substring(we,st+1),Re=st+1}return ae+q},me=x.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,ae,H)=>{let q=N.text||"";h||(q=q.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),N.role==="agent"&&(q=Te(q),q=q.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),q=q.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*"));let Re=[];return Array.isArray(N.parts)&&N.parts.length>0?Re=N.parts.map(we=>{if(we.text){let _e=we.text;return h||(_e=_e.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),N.role==="agent"&&(_e=Te(_e),_e=_e.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),_e=_e.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*")),{text:_e}}return we}):Re=[{text:q}],N.binaryPart&&xt(ke)&&H.slice(ae+1).filter(_e=>_e.role==="user"&&!_e.text?.startsWith("[TOOL RESULT]")).length<=2&&Re.push(N.binaryPart),{role:N.role==="user"||N.role==="system"?"user":"model",parts:Re}});for(let N=0;N<me.length;N++){let ae=me[N],H=ae.parts?.[0]?.text||"";if(ae.role==="model"&&/\[tool:/i.test(H)){let q=-1;for(let Re=N+1;Re<me.length;Re++){let we=me[Re],_e=we.parts?.[0]?.text||"";if(we.role==="user"&&_e.startsWith("[TOOL RESULT]")){q=Re;break}}if(q!==-1&&q!==N+1){let[Re]=me.splice(q,1);me.splice(N+1,0,Re)}}}for(let N=me.length-2;N>=0;N--){let ae=me[N],H=me[N+1];ae.role==="user"&&H.role==="user"&&(H.parts?.[0]?.text||"").trim().startsWith("[SYSTEM")&&me.splice(N,1)}let at=[];for(let N=0;N<me.length;N++){let ae=me[N];if(at.length===0)at.push(ae);else{let H=at[at.length-1];H.role===ae.role?(H.parts[0].text+=`
1064
+ [STEERING HINT from USER, High Priority] ${pe.trim()} [/STEERING HINT]`:x.push({role:"user",text:`[STEERING HINT from USER, High Priority] ${pe.trim()} [/STEERING HINT]`}),yield{type:"status",content:`${pe.startsWith("/btw")?"Question Forwarded...":"Steering Hint Injected..."}`})}let Ee,ot=!1,ze=1,et=1,ge="",Wt=null,tt=null,ln=null,K=0,oe=[],Ke=0,mn=!1,jt=!1,Rn=!1,On=!1,no=!0,bs=0,it="",Xe="",Gt=!1,oo=!1,je=!0,ke=e,Ye="";for(;ze<=Tn&&et<=Tn&&!ot&&!Lt;){let pe=!1;try{ge="",no&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},no=!1,et===1&&(it=""));let Te=N=>{if(!N||!N.includes("[tool:"))return N;let ae="",H=wi(N);H&&(ae=H.fullBlock,N=H.remainingText),N=N.replace(fd,(we,_e)=>_e.includes("[tool:")?_e.trim():we);let q="",Re=0;for(;Re<N.length;){let we=N.indexOf("[tool:",Re);if(we===-1){q+=fl(N.substring(Re));break}let _e=N.substring(Re,we);q+=fl(_e);let st=-1,G=null,re=0;for(let Ue=we;Ue<N.length;Ue++){let A=N[Ue];if(G){if(A===G){let Be=0;for(let ve=Ue-1;ve>=0&&N[ve]==="\\";ve--)Be++;Be%2===0&&(G=null)}}else if(A==='"'||A==="'"||A==="`")G=A;else if(A==="(")re++;else if(A===")")re--;else if(A==="]"&&re<=0){st=Ue;break}}if(st===-1){q+=N.substring(we);break}q+=N.substring(we,st+1),Re=st+1}return ae+q},me=x.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,ae,H)=>{let q=N.text||"";h||(q=q.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),N.role==="agent"&&(q=Te(q),q=q.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),q=q.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*"));let Re=[];return Array.isArray(N.parts)&&N.parts.length>0?Re=N.parts.map(we=>{if(we.text){let _e=we.text;return h||(_e=_e.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),N.role==="agent"&&(_e=Te(_e),_e=_e.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),_e=_e.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*")),{text:_e}}return we}):Re=[{text:q}],N.binaryPart&&bt(ke)&&H.slice(ae+1).filter(_e=>_e.role==="user"&&!_e.text?.startsWith("[TOOL RESULT]")).length<=2&&Re.push(N.binaryPart),{role:N.role==="user"||N.role==="system"?"user":"model",parts:Re}});for(let N=0;N<me.length;N++){let ae=me[N],H=ae.parts?.[0]?.text||"";if(ae.role==="model"&&/\[tool:/i.test(H)){let q=-1;for(let Re=N+1;Re<me.length;Re++){let we=me[Re],_e=we.parts?.[0]?.text||"";if(we.role==="user"&&_e.startsWith("[TOOL RESULT]")){q=Re;break}}if(q!==-1&&q!==N+1){let[Re]=me.splice(q,1);me.splice(N+1,0,Re)}}}for(let N=me.length-2;N>=0;N--){let ae=me[N],H=me[N+1];ae.role==="user"&&H.role==="user"&&(H.parts?.[0]?.text||"").trim().startsWith("[SYSTEM")&&me.splice(N,1)}let Ht=[];for(let N=0;N<me.length;N++){let ae=me[N];if(Ht.length===0)Ht.push(ae);else{let H=Ht[Ht.length-1];H.role===ae.role?(H.parts[0].text+=`
1065
1065
 
1066
- `+(ae.parts?.[0]?.text||""),ae.parts?.length>1&&H.parts.push(...ae.parts.slice(1))):at.push(ae)}}me.length=0,me.push(...at),ke=e;let jt=`${d}|${u}|${i}|${a}|${ke}|${JSON.stringify(r)}|${!!l?.dynamicDirAwareness}|${!!l?.subAgents}`,Vt=ko.key===jt&&ko.value;if((process.env.I_HAVE_TOO_MUCH_MONEY==="true"||process.env.I_HAVE_TOO_MUCH_MONEY===!0)&&(Vt=!1),Vt)Ye=ko.value;else{let N=u==="Mistral"?!!vo(ke):!(ke||"gemma").toLowerCase().startsWith("gemma");Ye=xa(r,((ke||"gemma").toLowerCase().startsWith("gemma"),a),i,l,h,$,u,u==="Google"?!0:y,N,d),l?.dynamicDirAwareness||(Ye+=`
1066
+ `+(ae.parts?.[0]?.text||""),ae.parts?.length>1&&H.parts.push(...ae.parts.slice(1))):Ht.push(ae)}}me.length=0,me.push(...Ht),ke=e;let Pt=`${d}|${u}|${i}|${a}|${ke}|${JSON.stringify(r)}|${!!l?.dynamicDirAwareness}|${!!l?.subAgents}`,Mt=ko.key===Pt&&ko.value;if((process.env.I_HAVE_TOO_MUCH_MONEY==="true"||process.env.I_HAVE_TOO_MUCH_MONEY===!0)&&(Mt=!1),Mt)Ye=ko.value;else{let N=u==="Mistral"?!!vo(ke):!(ke||"gemma").toLowerCase().startsWith("gemma");Ye=xa(r,((ke||"gemma").toLowerCase().startsWith("gemma"),a),i,l,h,$,u,u==="Google"?!0:y,N,d),l?.dynamicDirAwareness||(Ye+=`
1067
1067
  ${Ei.replace(`
1068
1068
  **Directory Structure**`,`
1069
- -- Directory Structure --`)}`),ko.key=jt,ko.value=Ye}let Lt=me[me.length-1];if(Hs()&z>0){await new Promise(H=>setTimeout(H,2500)),yield{type:"status",content:"Verifying"};let N=await xo(),ae=N?N.diagnostics:null;ae&&Lt&&Lt.role==="user"&&Lt.parts?.[0]?.text&&(Lt.parts[0].text+=`
1070
- ${ae} [/ERROR]`),yield{type:"status",content:"Working"}}let qn=u==="Mistral"||u==="Google"&&e?.toLowerCase().startsWith("gemma");if(l?.advanceRollback&&Lt&&Lt.role==="user"&&Lt.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 ae=`
1069
+ -- Directory Structure --`)}`),ko.key=Pt,ko.value=Ye}let dt=me[me.length-1];if(Hs()&z>0){await new Promise(H=>setTimeout(H,2500)),yield{type:"status",content:"Verifying"};let N=await xo(),ae=N?N.diagnostics:null;ae&&dt&&dt.role==="user"&&dt.parts?.[0]?.text&&(dt.parts[0].text+=`
1070
+ ${ae} [/ERROR]`),yield{type:"status",content:"Working"}}let cn=u==="Mistral"||u==="Google"&&e?.toLowerCase().startsWith("gemma");if(l?.advanceRollback&&dt&&dt.role==="user"&&dt.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 ae=`
1071
1071
  [system] File Changes:
1072
1072
  `;for(let q of N.newFiles)ae+=`* ${q} (created)
1073
1073
  `;for(let q of N.modifiedFiles)ae+=`* ${q} (modified)
1074
1074
  `;for(let q of N.deletedFiles)ae+=`* ${q} (deleted)
1075
- `;ae+="[/system]",Lt.parts[0].text+=ae;let H=-1;for(let q=x.length-1;q>=0;q--)if(x[q].role==="user"&&x[q].text?.startsWith("[TOOL RESULT]")){H=q;break}H!==-1&&(x[H].text+=ae)}}catch{}let an=Math.floor(jo*(i==="Flux"?.98:.8)),Dt=z+1;Dt>=an&&Lt&&Lt.parts?.[0]&&(Lt.parts[0].text+=`
1076
- [system] WARNING, Turn Limit Impending: Step ${Dt}/${jo}. Wrap up quickly/prompt user to continue. [/system]`);let Pt=new Promise((N,ae)=>{E.signal.aborted&&ae(new DOMException("The user aborted a request.","AbortError")),E.signal.addEventListener("abort",()=>{ae(new DOMException("The user aborted a request.","AbortError"))})});Pt.catch(()=>{});let Rt=me;if(u==="Ollama")Ee=yi(t.apiKey,ke,Rt,Ye,a,i,y,E.signal,1,l?.ollamaEndpoint||"Cloud");else if(u==="OpenRouter")Ee=Vs(t.apiKey,ke,Rt,Ye,a,i,y,E.signal,1,d);else if(u==="DeepSeek")Ee=zs(t.apiKey,ke,Rt,Ye,a,i,y,E.signal,1);else if(u==="Mistral")Ee=Ks(t.apiKey,ke,Rt,Ye,a,i,y,E.signal,1,d);else if(u==="NVIDIA"){let N=Ys(t.apiKey,ke,Rt,Ye,a,i,y,E.signal,1);Ee=al(N,ke)}else if(u==="CrofAI")Ee=Xs(t.apiKey,ke,Rt,Ye,a,i,y,E.signal,1);else if(u==="InferX")Ee=Js(t.apiKey,ke,Rt,Ye,a,i,y,E.signal,1);else if(u==="SenseNova")Ee=Qs(t.apiKey,ke,Rt,Ye,a,i,y,E.signal,1);else if(u==="AIHubMix")Ee=Zs(t.apiKey,ke,Rt,Ye,a,i,y,E.signal,1);else if(u==="Poolside")Ee=er(t.apiKey,ke,Rt,Ye,a,i,y,E.signal,1);else if(u==="9router"||u==="9Router")Ee=tr(t.apiKey,ke,Rt,Ye,a,i,y,E.signal,1);else if(u==="ExpLabs"||u==="ExperientialLabs")Ee=nr(t.apiKey,ke,Rt,Ye,a,i,y,E.signal,1);else{let ae=ki(t?.apiKey).models.generateContentStream({model:ke||"gemini-3-flash-preview",contents:Rt,config:{systemInstruction:Ye,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 H=(ke||"").toLowerCase(),q=H.includes("gemma-4")||H.startsWith("gemma"),Re=H.includes("gemini-3");if(q||Re)return q?a.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:mt.MINIMAL}:{includeThoughts:!0,thinkingLevel:mt.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:H.includes("pro")?mt.LOW:mt.MINIMAL,Low:mt.LOW,Medium:mt.MEDIUM,Standard:mt.MEDIUM,High:mt.HIGH,xHigh:mt.HIGH}[a]||mt.MEDIUM};{let we={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[a]||2048;return we===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:we}}})()}},{signal:E.signal});Ee=await Promise.race([ae,Pt])}ge="",Ut=null,rn=null,oe=[],Ke=0,yield{type:"model_update",content:null},Xe="",Wt=it.length>0;let Tn="",cr=Date.now(),io=async function*(){if(u==="Google"&&Tn){let N=Ho(Tn);for(let ae of N)yield ae;Tn="",cr=Date.now()}},Ii=!0,ao="",Ro=!1,Gt=null,Rl={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 ae=[],H=N;for(;H.length>0;)if(Ro){let q=ao+H,Re=Rl[Gt];if(Re){let st=!1;if(q.length<Re.startPrefix.length?Re.startPrefix.startsWith(q)||(st=!0):q.startsWith(Re.startPrefix)?q.length>=Re.fullPrefix.length&&!q.startsWith(Re.fullPrefix)&&(st=!0):st=!0,st){ae.push({type:"text",content:q}),ao="",Ro=!1,Gt=null,H="";break}}let we=-1,_e=Re?Re.endTag:"]";if(Gt==="tool"||Gt==="agent"){let st=0,G=null,re=0,Ue=!1;for(let A=0;A<q.length;A++){let Be=q[A];if(G){if(Be===G){let ve=0;for(let Z=A-1;Z>=0&&q[Z]==="\\";Z--)ve++;ve%2===0&&(G=null)}}else if(Be==='"'||Be==="'"||Be==="`")G=Be;else if(Be==="(")st++,Ue=!0;else if(Be===")")st--;else if(Be==="[")re++;else if(Be==="]"){if(Ue&&st===0&&re===1){we=A;break}re--}}}else we=q.indexOf(_e);if(we!==-1){let st=_e.length;if(!Gt?.startsWith("kimi")){let G=q.substring(0,we+st);ae.push({type:"text",content:G})}ao="",Ro=!1,Gt=null,H=q.substring(we+st)}else{let st=Gt?.startsWith("kimi")?8192:512;q.length>st?(ae.push({type:"text",content:q}),ao="",Ro=!1,Gt=null):ao=q,H="";break}}else{let q=H.indexOf("[tool"),Re=H.indexOf("[agent"),we=H.indexOf("[[END]]"),_e=H.indexOf("<|tool_calls_section_begin|>"),st=H.indexOf("<|tool_call_begin|>"),G=[{type:"tool",idx:q,start:"[tool",end:"]"},{type:"agent",idx:Re,start:"[agent",end:"]"},{type:"end",idx:we,start:"[[END]]",end:"[[END]]"},{type:"kimi_section",idx:_e,start:"<|tool_calls_section_begin|>",end:"<|tool_calls_section_end|>"},{type:"kimi_call",idx:st,start:"<|tool_call_begin|>",end:"<|tool_call_end|>"}].filter(re=>re.idx!==-1).sort((re,Ue)=>re.idx-Ue.idx);if(G.length>0){let re=G[0];re.idx>0&&ae.push({type:"text",content:H.substring(0,re.idx)}),Ro=!0,Gt=re.type,ao="",H=H.substring(re.idx)}else{let re=["[tool","[agent","[[END]]","<|tool_calls_section_begin|>","<|tool_call_begin|>"],Ue=-1;for(let A of re){for(let Be=A.length-1;Be>0;Be--)if(H.endsWith(A.substring(0,Be))){Ue=H.length-Be;let ve=re.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&&ae.push({type:"text",content:H.substring(0,Ue)}),Ro=!0,ao=H.substring(Ue),H="";else{ae.push({type:"text",content:H});break}}}return ae},El=Ee[Symbol.asyncIterator]();for(;;){let{value:N,done:ae}=await Promise.race([El.next(),Pt]);if(ae)break;if(N&&N.type==="status"){yield N;continue}let H="",q=N.candidates?.[0]?.content?.parts;if(q&&q.length>0)for(let we of q){let _e=typeof we.text=="string"?we.text:we.text?parseChunkText(we.text):"";we.thought?_e&&(pe||(H+="<think>",pe=!0),H+=_e):_e&&(pe&&(H+="</think>",pe=!1),H+=_e)}else N.text&&pe&&(H+="</think>",pe=!1);H=ld(H);let Re=H?H.trim().split(/\s+/).filter(Boolean).length:0;if(t&&typeof t.onTokenChunk=="function"&&t.onTokenChunk(H,Re),Ii&&(yield{type:"status",content:"Thinking"},Ii=!1),It){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
1075
+ `;ae+="[/system]",dt.parts[0].text+=ae;let H=-1;for(let q=x.length-1;q>=0;q--)if(x[q].role==="user"&&x[q].text?.startsWith("[TOOL RESULT]")){H=q;break}H!==-1&&(x[H].text+=ae)}}catch{}let qt=Math.floor(jo*(i==="Flux"?.98:.8)),Ft=z+1;Ft>=qt&&dt&&dt.parts?.[0]&&(dt.parts[0].text+=`
1076
+ [system] WARNING, Turn Limit Impending: Step ${Ft}/${jo}. Wrap up quickly/prompt user to continue. [/system]`);let Nt=new Promise((N,ae)=>{E.signal.aborted&&ae(new DOMException("The user aborted a request.","AbortError")),E.signal.addEventListener("abort",()=>{ae(new DOMException("The user aborted a request.","AbortError"))})});Nt.catch(()=>{});let Et=me;if(u==="Ollama")Ee=yi(t.apiKey,ke,Et,Ye,a,i,y,E.signal,1,l?.ollamaEndpoint||"Cloud");else if(u==="OpenRouter")Ee=Vs(t.apiKey,ke,Et,Ye,a,i,y,E.signal,1,d);else if(u==="DeepSeek")Ee=zs(t.apiKey,ke,Et,Ye,a,i,y,E.signal,1);else if(u==="Mistral")Ee=Ks(t.apiKey,ke,Et,Ye,a,i,y,E.signal,1,d);else if(u==="NVIDIA"){let N=Ys(t.apiKey,ke,Et,Ye,a,i,y,E.signal,1);Ee=al(N,ke)}else if(u==="CrofAI")Ee=Xs(t.apiKey,ke,Et,Ye,a,i,y,E.signal,1);else if(u==="InferX")Ee=Js(t.apiKey,ke,Et,Ye,a,i,y,E.signal,1);else if(u==="SenseNova")Ee=Qs(t.apiKey,ke,Et,Ye,a,i,y,E.signal,1);else if(u==="AIHubMix")Ee=Zs(t.apiKey,ke,Et,Ye,a,i,y,E.signal,1);else if(u==="Poolside")Ee=er(t.apiKey,ke,Et,Ye,a,i,y,E.signal,1);else if(u==="9router"||u==="9Router")Ee=tr(t.apiKey,ke,Et,Ye,a,i,y,E.signal,1);else if(u==="ExpLabs"||u==="ExperientialLabs")Ee=nr(t.apiKey,ke,Et,Ye,a,i,y,E.signal,1);else{let ae=ki(t?.apiKey).models.generateContentStream({model:ke||"gemini-3-flash-preview",contents:Et,config:{systemInstruction:Ye,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 H=(ke||"").toLowerCase(),q=H.includes("gemma-4")||H.startsWith("gemma"),Re=H.includes("gemini-3");if(q||Re)return q?a.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:mt.MINIMAL}:{includeThoughts:!0,thinkingLevel:mt.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:H.includes("pro")?mt.LOW:mt.MINIMAL,Low:mt.LOW,Medium:mt.MEDIUM,Standard:mt.MEDIUM,High:mt.HIGH,xHigh:mt.HIGH}[a]||mt.MEDIUM};{let we={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[a]||2048;return we===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:we}}})()}},{signal:E.signal});Ee=await Promise.race([ae,Nt])}ge="",Wt=null,ln=null,oe=[],Ke=0,yield{type:"model_update",content:null},Xe="",Gt=it.length>0;let En="",cr=Date.now(),io=async function*(){if(u==="Google"&&En){let N=Ho(En);for(let ae of N)yield ae;En="",cr=Date.now()}},Ii=!0,ao="",Ro=!1,zt=null,Rl={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 ae=[],H=N;for(;H.length>0;)if(Ro){let q=ao+H,Re=Rl[zt];if(Re){let st=!1;if(q.length<Re.startPrefix.length?Re.startPrefix.startsWith(q)||(st=!0):q.startsWith(Re.startPrefix)?q.length>=Re.fullPrefix.length&&!q.startsWith(Re.fullPrefix)&&(st=!0):st=!0,st){ae.push({type:"text",content:q}),ao="",Ro=!1,zt=null,H="";break}}let we=-1,_e=Re?Re.endTag:"]";if(zt==="tool"||zt==="agent"){let st=0,G=null,re=0,Ue=!1;for(let A=0;A<q.length;A++){let Be=q[A];if(G){if(Be===G){let ve=0;for(let Z=A-1;Z>=0&&q[Z]==="\\";Z--)ve++;ve%2===0&&(G=null)}}else if(Be==='"'||Be==="'"||Be==="`")G=Be;else if(Be==="(")st++,Ue=!0;else if(Be===")")st--;else if(Be==="[")re++;else if(Be==="]"){if(Ue&&st===0&&re===1){we=A;break}re--}}}else we=q.indexOf(_e);if(we!==-1){let st=_e.length;if(!zt?.startsWith("kimi")){let G=q.substring(0,we+st);ae.push({type:"text",content:G})}ao="",Ro=!1,zt=null,H=q.substring(we+st)}else{let st=zt?.startsWith("kimi")?8192:512;q.length>st?(ae.push({type:"text",content:q}),ao="",Ro=!1,zt=null):ao=q,H="";break}}else{let q=H.indexOf("[tool"),Re=H.indexOf("[agent"),we=H.indexOf("[[END]]"),_e=H.indexOf("<|tool_calls_section_begin|>"),st=H.indexOf("<|tool_call_begin|>"),G=[{type:"tool",idx:q,start:"[tool",end:"]"},{type:"agent",idx:Re,start:"[agent",end:"]"},{type:"end",idx:we,start:"[[END]]",end:"[[END]]"},{type:"kimi_section",idx:_e,start:"<|tool_calls_section_begin|>",end:"<|tool_calls_section_end|>"},{type:"kimi_call",idx:st,start:"<|tool_call_begin|>",end:"<|tool_call_end|>"}].filter(re=>re.idx!==-1).sort((re,Ue)=>re.idx-Ue.idx);if(G.length>0){let re=G[0];re.idx>0&&ae.push({type:"text",content:H.substring(0,re.idx)}),Ro=!0,zt=re.type,ao="",H=H.substring(re.idx)}else{let re=["[tool","[agent","[[END]]","<|tool_calls_section_begin|>","<|tool_call_begin|>"],Ue=-1;for(let A of re){for(let Be=A.length-1;Be>0;Be--)if(H.endsWith(A.substring(0,Be))){Ue=H.length-Be;let ve=re.indexOf(A);ve===0?zt="tool":ve===1?zt="agent":ve===2?zt="end":ve===3?zt="kimi_section":zt="kimi_call";break}if(Ue!==-1)break}if(Ue!==-1)Ue>0&&ae.push({type:"text",content:H.substring(0,Ue)}),Ro=!0,ao=H.substring(Ue),H="";else{ae.push({type:"text",content:H});break}}}return ae},El=Ee[Symbol.asyncIterator]();for(;;){let{value:N,done:ae}=await Promise.race([El.next(),Nt]);if(ae)break;if(N&&N.type==="status"){yield N;continue}let H="",q=N.candidates?.[0]?.content?.parts;if(q&&q.length>0)for(let we of q){let _e=typeof we.text=="string"?we.text:we.text?parseChunkText(we.text):"";we.thought?_e&&(pe||(H+="<think>",pe=!0),H+=_e):_e&&(pe&&(H+="</think>",pe=!1),H+=_e)}else N.text&&pe&&(H+="</think>",pe=!1);H=ld(H);let Re=H?H.trim().split(/\s+/).filter(Boolean).length:0;if(t&&typeof t.onTokenChunk=="function"&&t.onTokenChunk(H,Re),Ii&&(yield{type:"status",content:"Thinking"},Ii=!1),Lt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
1077
1077
 
1078
- \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(H){if(Wt){if(Xe+=H,Xe.length>=64){let G=0,re=Math.min(it.length,Xe.length);for(let A=re;A>=10;A--)if(it.endsWith(Xe.substring(0,A))){G=A;break}let Ue=Xe.substring(G);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(ge+=Be,u==="Google")Tn+=Be;else{yield*io();let ve=Ho(Be);for(let Z of ve)yield Z}}Wt=!1,Xe=""}continue}else if(ge+=H,u==="Google")Tn+=H;else{yield*io();let G=Ho(H);for(let re of G)yield re}let we=gd(ge);if(we.inside){oo=!0,rn||(rn=Date.now());let re={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"}[we.toolName]||we.toolName,Ue=we.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(re)){let ve=D(Ue),Z=ve.path||ve.targetFile||ve.TargetFile||ve.directory,Rn=ve.keyword,lo=ve.title||ve.task,zn=ve.id||ve.taskId,Ce=ve.timeout||ve.time;if(Rn!=null)A=String(Rn).replace(bo,"");else if(Z)A=te.basename(String(Z).replace(bo,"").replace(ll,"/"));else if(lo&&(re==="invoke"||re==="invoke_sync"))A=String(lo).replace(bo,"").substring(0,30);else if(zn&&re==="get_progress")A=String(zn).replace(bo,"");else if(Ce&&re==="await"){let Ht=parseFloat(String(Ce).replace(bo,""));isNaN(Ht)?A=String(Ce).replace(bo,""):(Ht<5&&(Ht=5),Ht>120&&(Ht=120),A=(In=>{if(In>=60){let ur=Math.floor(In/60),Eo=In%60;return`${ur}m${Eo>0?` ${Eo}s`:""}`}return`${In}s`})(Ht))}else{let Ht=Ue.match(rd);if(Ht){let Xt=Ht[1].replace(bo,"");re==="invoke"||re==="invoke_sync"||re==="get_progress"?A=Xt.substring(0,30):A=re==="search_keyword"||re==="file_map"?Xt:te.basename(Xt.replace(ll,"/"))}}}let Be=`${xi[re]||re}${A?` ${A}`:""}`;if((re!==Ut||A!==tt)&&(Ut=re,tt=A,yield{type:"status",content:`${Be}`},process.stdout.isTTY)){let Z={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"}[re]||"Working";process.stdout.write(`\x1B]0;${Z}...\x07`)}}if(ge.length-bs>150){bs=ge.length;let G=yl(ge,!1),re=wi(G),Ue=re?(re.innerContent||"").trim():"",A=Ue.split(/[.!?]\s+/),Be=new Set(A),ve=A.length>10?(A.length-Be.size)/A.length:0,Z=Ue.split(/\s+/).filter(Ie=>Ie.length>0).length,Rn=.6,lo=.8,zn=!1;if((u.toLowerCase().includes("google")||u.toLowerCase().includes("mistral"))&&((ke||"").toLowerCase().startsWith("gemma")||(ke||"").toLowerCase().includes("stral"))){let I={low:256,medium:1024,high:8192,max:16384,xhigh:16384}[a?.toLowerCase()]||2500;zn=Z>I}if(ve>Rn||zn){yield{type:"status",content:`${ve>Rn?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},Bt=!0,await new Promise(I=>setTimeout(I,3e3));break}let Xt=pl(ge).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=G.replace(Qc,"").replace(Zc,"").replace(ed,"").replace(td,""),qt=Eo.toLowerCase().split(/\s+/).map(Ie=>Ie.replace(nd,"")).filter(Ie=>Ie.length>0),On=!1;if(qt.length>=10)for(let Ie=1;Ie<=15;Ie++){let I=Math.max(3,Math.ceil(10/Ie));if(qt.length<Ie*I)continue;let Y=qt.slice(qt.length-Ie),ce=Y.join(" ");if(Ie>1&&ce===Y.slice(0,Math.floor(Ie/2)).join(" ").repeat(2).trim())continue;let he=!0;for(let be=1;be<I;be++)if(qt.slice(qt.length-Ie*(be+1),qt.length-Ie*be).join(" ")!==ce){he=!1;break}if(he){On=!0;break}}if(!On){let Ie=Eo.toLowerCase().replace(od,"");if(Ie.length>=20)for(let I=1;I<=10;I++){let Y=Math.max(5,Math.ceil(16/I));if(Ie.length<I*Y)continue;let ce=Ie.substring(Ie.length-I),he=!0;for(let be=1;be<Y;be++)if(Ie.substring(Ie.length-I*(be+1),Ie.length-I*be)!==ce){he=!1;break}if(he){On=!0;break}}}if(On){yield{type:"status",content:"Stuttering Detected. Re-centering..."},Bt=!1,Sn=!0,await new Promise(Ie=>setTimeout(Ie,3e3));break}}let _e=on(ge),st=rr(_e);for(;st.length>Ke;){yield*io();let G=st[Ke],re=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"}[G.toolName]||G.toolName,Be=xi[A]||G.toolName,ve=So(A,G.args);yield{type:"status",content:`${Be}${ve?` ${ve}`:""}`};let Z="";if(A==="click"){let I=D(G.args);Z=`\u2714 Clicked: ${I.intendedClickText?`${I.intendedClickText}`:""}`}else if(A==="drag"){let I=D(G.args);Z=`\u2714 Dragged: Cell ${I.fromGridId||""} \u2192 Cell ${I.toGridId||""}`}else if(A==="scroll"){let I=D(G.args);Z=`\u2714 Scrolled: ${I.direction||"down"} (${I.amount||1})`}else if(A==="keyboard_typing"){let I=D(G.args);Z=`\u2714 Typed: ${I.text?`"${I.text.length>20?I.text.substring(0,20)+"...":I.text}"`:""}`}else if(A==="key_press")Z=`\u2714 Pressed Key: ${D(G.args).key||""}`;else if(A==="recapture_screen")Z="\u2714 Recaptured Screen";else if(A==="web_search"){let{query:I,limit:Y=10,aiMode:ce=!1}=D(G.args);Z=`${I?"\u2714":"\u2718"} ${ce?"AI Search":"Searched"}: ${I?`${I}`:"No Search Query"}${ce===!1&&I?` \u2192 ${Y}`:""}`}else if(A==="web_scrape"){let I=D(G.args).url||null;Z=`${I?"\u2714":"\u2718"} Visited: ${I||"No Source"}`}else if(A==="view_file"){let{path:I,StartLine:Y,EndLine:ce,start_line:he,end_line:be,startLine:Ge,endLine:Oe}=D(G.args),Se=Y||he||Ge,V=ce||be||Oe,ie=parseInt(Se)||1,ue=parseInt(V)||(Se?ie+800:800),$e="...",Je=ue,Ae=(I||"").trim().toLowerCase().replaceAll("\\","/");if(Ae.startsWith("#skill"))Ae.startsWith("#skill/global/fluxflow")||Ae.startsWith("#skills/global/fluxflow")?Z="\u2714 Read Documentation":Z=`\u2714 Read Skill: ${te.basename(I.replaceAll("\\","/"))}`;else{try{let xe=te.resolve(process.cwd(),I);if(Fe.existsSync(xe)){let Et=Fe.readFileSync(xe,"utf8").split(`
1079
- `).length;$e=Et,!Se&&!V&&Et>800?Je=Math.min(50,Et):Je=Math.min(ue,Et)}}catch{}let De=(I||"").toLowerCase(),wt=De.endsWith(".pdf"),Le=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);wt||Le?Z=`${I.length>0?"\u2714":"\u2718"} ${I?`Analyzed: ${te.basename(I)}`:"Analyzed: File Not Found"}`:rt?Z=`${I.length>0?"\u2714":"\u2718"} ${I?`Processed: ${te.basename(I)}`:"Processed: File Not Found"}`:Z=`${$e!=="..."?"\u2714":"\u2718"} Read: ${I?`${te.basename(I)} \u2192 ${$e!=="..."?`Lines ${ie} - ${Je} of ${$e}`:"File Not Found"}`:"File Not Found"}`}}else if(A==="list_files"||A==="read_folder"){let I=A==="list_files"?"List":"Browsed",Y=D(G.args).path||null,ce=D(G.args).recurse||1;Z=`${Y?"\u2714":"\u2718"} ${I}: ${Y?`${Y==="."?`./${ce>1?"*":""}`:`${Y.replaceAll("\\","/")}${ce>1?`${Y.endsWith("/")?"*":"/*"}`:`${Y.endsWith("/")?"":"/"}`}`}`:"No Folder Selected"}`}else if(A==="write_file"||A==="update_file"){let I=A==="write_file"?"Created":"Edited",Y=D(G.args).path||null;Z=`${Y?"\u2714":"\u2718"} ${I}: ${Y.replaceAll("\\","/")||"No File Changes"}`}else if(A==="write_pdf"){let I=D(G.args).path||null;Z=`${I?"\u2714":"\u2718"} Generated: ${I.replaceAll("\\","/")||"No PDF Generated"}`}else if(A==="write_docx"){let I=D(G.args).path||null;Z=`${I?"\u2714":"\u2718"} Generated: ${I.replaceAll("\\","/")||"No Docx Generated"}`}else if(A==="file_map"){let I=D(G.args).path;Z=`${I?"\u2714":"\u2718"} Indexed: ${I.replaceAll("\\","/")?""+I:"File Not Found"}`}else if(A.toLowerCase()==="search_keyword"||A.toLowerCase()==="todo")Z="";else if(A.toLowerCase()==="generate_image"){let{path:I,outputPath:Y,output:ce}=D(G.args);Z=`\u2714 Generated: ${I||Y||ce||"generated_image.png"}`}else if(A==="invoke_sync"||A==="InvokeSync"){let I=So(A,G.args);Z=`\u2714 Called Generalist${I?`: ${I}`:""}`}else if(A==="Invoke"||A==="InvokeAsync"||A==="invoke"){let I=So(A,G.args);Z=`\u2714 Started Generalist${I?`: ${I}`:""}`}else if(A==="get_progress"||A==="GetProgress"){let I=So(A,G.args);Z=`\u2714 Checked${I?`: ${I}`:""}`}else if(A==="cancel"){let I=So(A,G.args);Z=`\u{1F6C7} Cancelled${I?`: ${I}`:""}`}else if(A==="steer"||A==="Steer"){let I=So(A,G.args);Z=`\u2714 Steered${I?`: ${I}`:""}`}else if(A==="EmergencyRollback"){let{method:I}=D(G.args);Z=I==="forceRevert"?"":"\u2714 Rollback Point Checked"}else if(A==="await"||A==="Await"){let{time:I,timeout:Y}=D(G.args),ce=parseFloat(Y||I)||0;ce||(ce=120);let he=Oe=>{if(Oe>=60){let Se=Math.floor(Oe/60),V=Oe%60;return`${Se}m${V>0?` ${V}s`:""}`}return`${Oe}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"];Z=`\u2714 ${be[Math.floor(Math.random()*be.length)]} \u2192 ${he(ce)}`}else A==="Answer"||A==="answer"?Z="\u2714 Resolved Sub-Agent Query":A==="exec_command"||A==="ask"?Z="":Z=`Executed: ${G.toolName}`;if(yield*io(),A==="exec_command"){let{command:I}=D(G.args);if(I&&t.systemSettings&&t.systemSettings.allowExternalAccess===!1){let Y=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],ce=te.resolve(process.cwd()).substring(0,3).toLowerCase(),he=V=>{let ie=[],ue="",$e=null;for(let Je=0;Je<V.length;Je++){let Ae=V[Je];$e?(Ae===$e&&($e=null),ue+=Ae):Ae==='"'||Ae==="'"?($e=Ae,ue+=Ae):Ae==="&"&&V[Je+1]==="&"||Ae==="|"&&V[Je+1]==="|"?(ue.trim()&&(ie.push(ue.trim()),ue=""),Je++):Ae===";"||Ae==="|"||Ae==="&"?ue.trim()&&(ie.push(ue.trim()),ue=""):ue+=Ae}return ue.trim()&&ie.push(ue.trim()),ie},be=V=>{let ie=[],ue="",$e=null;for(let Je=0;Je<V.length;Je++){let Ae=V[Je];$e?(Ae===$e&&($e=null),ue+=Ae):Ae==='"'||Ae==="'"?($e=Ae,ue+=Ae):/\s/.test(Ae)?ue&&(ie.push(ue),ue=""):ue+=Ae}return ue&&ie.push(ue),ie},Ge=V=>{let ie=V.replace(/^['"]|['"]$/g,"").trim();return!ie||process.platform==="win32"&&/^\/[a-zA-Z0-9?]+$/.test(ie)?!1:Y.some(ue=>{if(ue.source==="[a-zA-Z]:[\\\\\\/]"){let $e=ie.match(/[a-zA-Z]:[\\\/]/i);return $e&&$e[0].toLowerCase()!==ce}return ue.test(ie)})};if(he(I).some(V=>{let ie=be(V);if(ie.length===0)return!1;let ue=ie[0].replace(/^['"]|['"]$/g,"").toLowerCase();if(["echo","printf","write-output"].includes(ue)){let Je=!1;return ie.some(Ae=>{let Jt=Ae.replace(/^['"]|['"]$/g,"");if(Jt===">"||Jt===">>"||Jt==="<")return Je=!0,!1;if(Jt.startsWith(">")||Jt.startsWith("<")){let De=Jt.replace(/^[><]+/,"");return Ge(De)}return Je?(Je=!1,Ge(Ae)):!1})}return ie.some(Je=>Ge(Je))})){let V='Access Denied. Prohibited from accessing external directories while "External Workspace Access" is disabled.';t.onExecStart&&t.onExecStart(I||"No Command"),yield{type:"exec_start"},await new Promise(ie=>setTimeout(ie,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${V}`),await new Promise(ie=>setTimeout(ie,50)),t.onExecEnd&&t.onExecEnd(),oe.push({role:"user",text:`[TOOL RESULT]: ERROR: ${V}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${V}`},Ke++;continue}}t.onExecStart&&t.onExecStart(I||"No Command"),yield{type:"exec_start"}}let Rn=D(G.args),lo=Rn.path||Rn.targetPath||null;if(lo){let I=t.systemSettings&&t.systemSettings.allowExternalAccess===!1,Y=te.resolve(lo),ce=te.resolve(process.cwd());if(I&&!Y.startsWith(ce)){let he="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||"..."}`,Oe=115;process.stdout.isTTY&&(Oe=process.stdout.columns-5||120);let Se=Math.min(Ge.length+4,Oe),V=`${Ge.padEnd(Se-2).substring(0,Se-2)}`;yield{type:"visual_feedback",content:nn(`${je?`
1078
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(H){if(Gt){if(Xe+=H,Xe.length>=64){let G=0,re=Math.min(it.length,Xe.length);for(let A=re;A>=10;A--)if(it.endsWith(Xe.substring(0,A))){G=A;break}let Ue=Xe.substring(G);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(ge+=Be,u==="Google")En+=Be;else{yield*io();let ve=Ho(Be);for(let Z of ve)yield Z}}Gt=!1,Xe=""}continue}else if(ge+=H,u==="Google")En+=H;else{yield*io();let G=Ho(H);for(let re of G)yield re}let we=gd(ge);if(we.inside){oo=!0,ln||(ln=Date.now());let re={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"}[we.toolName]||we.toolName,Ue=we.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(re)){let ve=D(Ue),Z=ve.path||ve.targetFile||ve.TargetFile||ve.directory,_n=ve.keyword,lo=ve.title||ve.task,zn=ve.id||ve.taskId,Ce=ve.timeout||ve.time;if(_n!=null)A=String(_n).replace(bo,"");else if(Z)A=te.basename(String(Z).replace(bo,"").replace(ll,"/"));else if(lo&&(re==="invoke"||re==="invoke_sync"))A=String(lo).replace(bo,"").substring(0,30);else if(zn&&re==="get_progress")A=String(zn).replace(bo,"");else if(Ce&&re==="await"){let Kt=parseFloat(String(Ce).replace(bo,""));isNaN(Kt)?A=String(Ce).replace(bo,""):(Kt<5&&(Kt=5),Kt>120&&(Kt=120),A=(Ln=>{if(Ln>=60){let ur=Math.floor(Ln/60),Eo=Ln%60;return`${ur}m${Eo>0?` ${Eo}s`:""}`}return`${Ln}s`})(Kt))}else{let Kt=Ue.match(rd);if(Kt){let Qt=Kt[1].replace(bo,"");re==="invoke"||re==="invoke_sync"||re==="get_progress"?A=Qt.substring(0,30):A=re==="search_keyword"||re==="file_map"?Qt:te.basename(Qt.replace(ll,"/"))}}}let Be=`${xi[re]||re}${A?` ${A}`:""}`;if((re!==Wt||A!==tt)&&(Wt=re,tt=A,yield{type:"status",content:`${Be}`},process.stdout.isTTY)){let Z={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"}[re]||"Working";process.stdout.write(`\x1B]0;${Z}...\x07`)}}if(ge.length-bs>150){bs=ge.length;let G=yl(ge,!1),re=wi(G),Ue=re?(re.innerContent||"").trim():"",A=Ue.split(/[.!?]\s+/),Be=new Set(A),ve=A.length>10?(A.length-Be.size)/A.length:0,Z=Ue.split(/\s+/).filter(Ie=>Ie.length>0).length,_n=.6,lo=.8,zn=!1;if((u.toLowerCase().includes("google")||u.toLowerCase().includes("mistral"))&&((ke||"").toLowerCase().startsWith("gemma")||(ke||"").toLowerCase().includes("stral"))){let I={low:256,medium:1024,high:8192,max:16384,xhigh:16384}[a?.toLowerCase()]||2500;zn=Z>I}if(ve>_n||zn){yield{type:"status",content:`${ve>_n?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},jt=!0,await new Promise(I=>setTimeout(I,3e3));break}let Qt=pl(ge).trim().split(/[.!?]\s+/),Ln=new Set(Qt);if((Qt.length>10?(Qt.length-Ln.size)/Qt.length:0)>lo){yield{type:"status",content:"Response Loop Detected. Re-centering..."},jt=!1,On=!0,await new Promise(Ie=>setTimeout(Ie,3e3));break}let Eo=G.replace(Qc,"").replace(Zc,"").replace(ed,"").replace(td,""),Yt=Eo.toLowerCase().split(/\s+/).map(Ie=>Ie.replace(nd,"")).filter(Ie=>Ie.length>0),Dn=!1;if(Yt.length>=10)for(let Ie=1;Ie<=15;Ie++){let I=Math.max(3,Math.ceil(10/Ie));if(Yt.length<Ie*I)continue;let Y=Yt.slice(Yt.length-Ie),ce=Y.join(" ");if(Ie>1&&ce===Y.slice(0,Math.floor(Ie/2)).join(" ").repeat(2).trim())continue;let he=!0;for(let be=1;be<I;be++)if(Yt.slice(Yt.length-Ie*(be+1),Yt.length-Ie*be).join(" ")!==ce){he=!1;break}if(he){Dn=!0;break}}if(!Dn){let Ie=Eo.toLowerCase().replace(od,"");if(Ie.length>=20)for(let I=1;I<=10;I++){let Y=Math.max(5,Math.ceil(16/I));if(Ie.length<I*Y)continue;let ce=Ie.substring(Ie.length-I),he=!0;for(let be=1;be<Y;be++)if(Ie.substring(Ie.length-I*(be+1),Ie.length-I*be)!==ce){he=!1;break}if(he){Dn=!0;break}}}if(Dn){yield{type:"status",content:"Stuttering Detected. Re-centering..."},jt=!1,Rn=!0,await new Promise(Ie=>setTimeout(Ie,3e3));break}}let _e=rn(ge),st=rr(_e);for(;st.length>Ke;){yield*io();let G=st[Ke],re=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"}[G.toolName]||G.toolName,Be=xi[A]||G.toolName,ve=So(A,G.args);yield{type:"status",content:`${Be}${ve?` ${ve}`:""}`};let Z="";if(A==="click"){let I=D(G.args);Z=`\u2714 Clicked: ${I.intendedClickText?`${I.intendedClickText}`:""}`}else if(A==="drag"){let I=D(G.args);Z=`\u2714 Dragged: Cell ${I.fromGridId||""} \u2192 Cell ${I.toGridId||""}`}else if(A==="scroll"){let I=D(G.args);Z=`\u2714 Scrolled: ${I.direction||"down"} (${I.amount||1})`}else if(A==="keyboard_typing"){let I=D(G.args);Z=`\u2714 Typed: ${I.text?`"${I.text.length>20?I.text.substring(0,20)+"...":I.text}"`:""}`}else if(A==="key_press")Z=`\u2714 Pressed Key: ${D(G.args).key||""}`;else if(A==="recapture_screen")Z="\u2714 Recaptured Screen";else if(A==="web_search"){let{query:I,limit:Y=10,aiMode:ce=!1}=D(G.args);Z=`${I?"\u2714":"\u2718"} ${ce?"AI Search":"Searched"}: ${I?`${I}`:"No Search Query"}${ce===!1&&I?` \u2192 ${Y}`:""}`}else if(A==="web_scrape"){let I=D(G.args).url||null;Z=`${I?"\u2714":"\u2718"} Visited: ${I||"No Source"}`}else if(A==="view_file"){let{path:I,StartLine:Y,EndLine:ce,start_line:he,end_line:be,startLine:Ge,endLine:Oe}=D(G.args),Se=Y||he||Ge,V=ce||be||Oe,ie=parseInt(Se)||1,ue=parseInt(V)||(Se?ie+800:800),$e="...",Je=ue,Ae=(I||"").trim().toLowerCase().replaceAll("\\","/");if(Ae.startsWith("#skill"))Ae.startsWith("#skill/global/fluxflow")||Ae.startsWith("#skills/global/fluxflow")?Z="\u2714 Read Documentation":Z=`\u2714 Read Skill: ${te.basename(I.replaceAll("\\","/"))}`;else{try{let xe=te.resolve(process.cwd(),I);if(Fe.existsSync(xe)){let _t=Fe.readFileSync(xe,"utf8").split(`
1079
+ `).length;$e=_t,!Se&&!V&&_t>800?Je=Math.min(50,_t):Je=Math.min(ue,_t)}}catch{}let De=(I||"").toLowerCase(),xt=De.endsWith(".pdf"),Le=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);xt||Le?Z=`${I.length>0?"\u2714":"\u2718"} ${I?`Analyzed: ${te.basename(I)}`:"Analyzed: File Not Found"}`:rt?Z=`${I.length>0?"\u2714":"\u2718"} ${I?`Processed: ${te.basename(I)}`:"Processed: File Not Found"}`:Z=`${$e!=="..."?"\u2714":"\u2718"} Read: ${I?`${te.basename(I)} \u2192 ${$e!=="..."?`Lines ${ie} - ${Je} of ${$e}`:"File Not Found"}`:"File Not Found"}`}}else if(A==="list_files"||A==="read_folder"){let I=A==="list_files"?"List":"Browsed",Y=D(G.args).path||null,ce=D(G.args).recurse||1;Z=`${Y?"\u2714":"\u2718"} ${I}: ${Y?`${Y==="."?`./${ce>1?"*":""}`:`${Y.replaceAll("\\","/")}${ce>1?`${Y.endsWith("/")?"*":"/*"}`:`${Y.endsWith("/")?"":"/"}`}`}`:"No Folder Selected"}`}else if(A==="write_file"||A==="update_file"){let I=A==="write_file"?"Created":"Edited",Y=D(G.args).path||null;Z=`${Y?"\u2714":"\u2718"} ${I}: ${Y.replaceAll("\\","/")||"No File Changes"}`}else if(A==="write_pdf"){let I=D(G.args).path||null;Z=`${I?"\u2714":"\u2718"} Generated: ${I.replaceAll("\\","/")||"No PDF Generated"}`}else if(A==="write_docx"){let I=D(G.args).path||null;Z=`${I?"\u2714":"\u2718"} Generated: ${I.replaceAll("\\","/")||"No Docx Generated"}`}else if(A==="file_map"){let I=D(G.args).path;Z=`${I?"\u2714":"\u2718"} Indexed: ${I.replaceAll("\\","/")?""+I:"File Not Found"}`}else if(A.toLowerCase()==="search_keyword"||A.toLowerCase()==="todo")Z="";else if(A.toLowerCase()==="generate_image"){let{path:I,outputPath:Y,output:ce}=D(G.args);Z=`\u2714 Generated: ${I||Y||ce||"generated_image.png"}`}else if(A==="invoke_sync"||A==="InvokeSync"){let I=So(A,G.args);Z=`\u2714 Called Generalist${I?`: ${I}`:""}`}else if(A==="Invoke"||A==="InvokeAsync"||A==="invoke"){let I=So(A,G.args);Z=`\u2714 Started Generalist${I?`: ${I}`:""}`}else if(A==="get_progress"||A==="GetProgress"){let I=So(A,G.args);Z=`\u2714 Checked${I?`: ${I}`:""}`}else if(A==="cancel"){let I=So(A,G.args);Z=`\u{1F6C7} Cancelled${I?`: ${I}`:""}`}else if(A==="steer"||A==="Steer"){let I=So(A,G.args);Z=`\u2714 Steered${I?`: ${I}`:""}`}else if(A==="EmergencyRollback"){let{method:I}=D(G.args);Z=I==="forceRevert"?"":"\u2714 Rollback Point Checked"}else if(A==="await"||A==="Await"){let{time:I,timeout:Y}=D(G.args),ce=parseFloat(Y||I)||0;ce||(ce=120);let he=Oe=>{if(Oe>=60){let Se=Math.floor(Oe/60),V=Oe%60;return`${Se}m${V>0?` ${V}s`:""}`}return`${Oe}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"];Z=`\u2714 ${be[Math.floor(Math.random()*be.length)]} \u2192 ${he(ce)}`}else A==="Answer"||A==="answer"?Z="\u2714 Resolved Sub-Agent Query":A==="exec_command"||A==="ask"?Z="":Z=`Executed: ${G.toolName}`;if(yield*io(),A==="exec_command"){let{command:I}=D(G.args);if(I&&t.systemSettings&&t.systemSettings.allowExternalAccess===!1){let Y=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],ce=te.resolve(process.cwd()).substring(0,3).toLowerCase(),he=V=>{let ie=[],ue="",$e=null;for(let Je=0;Je<V.length;Je++){let Ae=V[Je];$e?(Ae===$e&&($e=null),ue+=Ae):Ae==='"'||Ae==="'"?($e=Ae,ue+=Ae):Ae==="&"&&V[Je+1]==="&"||Ae==="|"&&V[Je+1]==="|"?(ue.trim()&&(ie.push(ue.trim()),ue=""),Je++):Ae===";"||Ae==="|"||Ae==="&"?ue.trim()&&(ie.push(ue.trim()),ue=""):ue+=Ae}return ue.trim()&&ie.push(ue.trim()),ie},be=V=>{let ie=[],ue="",$e=null;for(let Je=0;Je<V.length;Je++){let Ae=V[Je];$e?(Ae===$e&&($e=null),ue+=Ae):Ae==='"'||Ae==="'"?($e=Ae,ue+=Ae):/\s/.test(Ae)?ue&&(ie.push(ue),ue=""):ue+=Ae}return ue&&ie.push(ue),ie},Ge=V=>{let ie=V.replace(/^['"]|['"]$/g,"").trim();return!ie||process.platform==="win32"&&/^\/[a-zA-Z0-9?]+$/.test(ie)?!1:Y.some(ue=>{if(ue.source==="[a-zA-Z]:[\\\\\\/]"){let $e=ie.match(/[a-zA-Z]:[\\\/]/i);return $e&&$e[0].toLowerCase()!==ce}return ue.test(ie)})};if(he(I).some(V=>{let ie=be(V);if(ie.length===0)return!1;let ue=ie[0].replace(/^['"]|['"]$/g,"").toLowerCase();if(["echo","printf","write-output"].includes(ue)){let Je=!1;return ie.some(Ae=>{let Zt=Ae.replace(/^['"]|['"]$/g,"");if(Zt===">"||Zt===">>"||Zt==="<")return Je=!0,!1;if(Zt.startsWith(">")||Zt.startsWith("<")){let De=Zt.replace(/^[><]+/,"");return Ge(De)}return Je?(Je=!1,Ge(Ae)):!1})}return ie.some(Je=>Ge(Je))})){let V='Access Denied. Prohibited from accessing external directories while "External Workspace Access" is disabled.';t.onExecStart&&t.onExecStart(I||"No Command"),yield{type:"exec_start"},await new Promise(ie=>setTimeout(ie,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${V}`),await new Promise(ie=>setTimeout(ie,50)),t.onExecEnd&&t.onExecEnd(),oe.push({role:"user",text:`[TOOL RESULT]: ERROR: ${V}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${V}`},Ke++;continue}}t.onExecStart&&t.onExecStart(I||"No Command"),yield{type:"exec_start"}}let _n=D(G.args),lo=_n.path||_n.targetPath||null;if(lo){let I=t.systemSettings&&t.systemSettings.allowExternalAccess===!1,Y=te.resolve(lo),ce=te.resolve(process.cwd());if(I&&!Y.startsWith(ce)){let he="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"}: ${_n.path||"..."}`,Oe=115;process.stdout.isTTY&&(Oe=process.stdout.columns-5||120);let Se=Math.min(Ge.length+4,Oe),V=`${Ge.padEnd(Se-2).substring(0,Se-2)}`;yield{type:"visual_feedback",content:sn(`${je?`
1080
1080
  `:""}${V}
1081
- `)},je=!1}oe.push({role:"user",text:`[TOOL RESULT]: ERROR: ${he}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${he}`},Ke++;continue}}if(t.onToolApproval&&(A==="write_file"||A==="update_file"||A==="exec_command")){let Y=t.systemSettings||{},ce=Y.autoExec,he=null,be=!1,Ge=!1,Oe=!1;if(A==="exec_command"){let{command:De}=D(G.args),wt=(De||"").trim(),Le=(Qt,Et)=>{if(!Et)return!1;let mn=Et.split(",").map(Zt=>Zt.trim().toLowerCase()).filter(Boolean),ut=Qt.toLowerCase();return mn.some(Zt=>ut.startsWith(Zt))},rt=Le(wt,Y.alwaysAskCommands),xe=Le(wt,Y.autoApproveCommands);if(Ge=Le(wt,Y.autoDisallowCommands),rt?be=!0:(xe||Y.autoApproveGit&&/^git\s+commit\b/i.test(wt))&&(he="allow"),!be&&!he){if(Y.networkAccess===!1){let Et=wt.trim().replace(/\s+/g," ").replace(/^['"]+|['"]+$/g,"").toLowerCase().split(" "),ut=Et[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(ut)&&(ft=!0);let lt=En=>Et.slice(1).some(_n=>En.includes(_n)),pt=En=>{let _n=Et.findIndex(Ln=>En.includes(Ln)),_o=Et.findIndex(Ln=>["run","exec","test"].includes(Ln));return _n!==-1&&!(_o!==-1&&_o<_n)};ut==="git"&&lt(["clone","pull","push","fetch"])&&(ft=!0),ut==="go"&&lt(["get","install"])&&(ft=!0),ut==="npm"&&pt(["install","i","update","add"])&&(ft=!0),ut==="yarn"&&pt(["add","install","upgrade"])&&(ft=!0),ut==="pnpm"&&pt(["add","install","update"])&&(ft=!0),ut==="bun"&&pt(["add","install","update"])&&(ft=!0),ut==="deno"&&lt(["install","add"])&&(ft=!0),ut==="pip"&&lt(["install","download"])&&(ft=!0),ut==="pip3"&&lt(["install","download"])&&(ft=!0),ut==="cargo"&&lt(["install","add"])&&(ft=!0),["bash","sh","zsh","fish"].includes(ut)&&lt(["-c"])&&(ft=!0),ut==="cmd"&&lt(["/c"])&&(ft=!0),ft&&(he="deny",Oe=!0)}!he&&Ge&&(he="deny")}!be&&!he&&ce&&(he="allow")}else ce&&(he="allow");let Se=he,V="";he==="deny"&&(Oe?V="network":Ge?V="settings":V="prohibited");let ie=!1,ue="",$e=[],Je=0,Ae=!1,Jt="";if(!Se){if(A==="write_file"||A==="update_file")try{let Le=D(G.args),{path:rt}=Le;if(rt){let xe=te.resolve(process.cwd(),rt),Qt=lt=>lt?lt.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,pt=>pt.toUpperCase()):"",Et=Qt(xe),mn="",ut=!1,Zt=await xo(),ft=Qt(Zt?.file_focused);if(Zt&&ft===Et&&Zt.full_content?(mn=Zt.full_content,ut=!0):Fe.existsSync(xe)&&(mn=Fe.readFileSync(xe,"utf8"),ut=!0),ue=mn,await gt.recordFileChange(xe,mn),ut){let lt=mn;if(A==="write_file"){let pt=Le.content||Le.newContent||"";lt=pt.endsWith(`
1081
+ `)},je=!1}oe.push({role:"user",text:`[TOOL RESULT]: ERROR: ${he}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${he}`},Ke++;continue}}if(t.onToolApproval&&(A==="write_file"||A==="update_file"||A==="exec_command")){let Y=t.systemSettings||{},ce=Y.autoExec,he=null,be=!1,Ge=!1,Oe=!1;if(A==="exec_command"){let{command:De}=D(G.args),xt=(De||"").trim(),Le=(en,_t)=>{if(!_t)return!1;let gn=_t.split(",").map(tn=>tn.trim().toLowerCase()).filter(Boolean),ut=en.toLowerCase();return gn.some(tn=>ut.startsWith(tn))},rt=Le(xt,Y.alwaysAskCommands),xe=Le(xt,Y.autoApproveCommands);if(Ge=Le(xt,Y.autoDisallowCommands),rt?be=!0:(xe||Y.autoApproveGit&&/^git\s+commit\b/i.test(xt))&&(he="allow"),!be&&!he){if(Y.networkAccess===!1){let _t=xt.trim().replace(/\s+/g," ").replace(/^['"]+|['"]+$/g,"").toLowerCase().split(" "),ut=_t[0].split("/").pop().split("\\").pop().replace(/\.exe$/,""),tn=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;tn.has(ut)&&(ft=!0);let at=Cn=>_t.slice(1).some($n=>Cn.includes($n)),pt=Cn=>{let $n=_t.findIndex(Pn=>Cn.includes(Pn)),_o=_t.findIndex(Pn=>["run","exec","test"].includes(Pn));return $n!==-1&&!(_o!==-1&&_o<$n)};ut==="git"&&at(["clone","pull","push","fetch"])&&(ft=!0),ut==="go"&&at(["get","install"])&&(ft=!0),ut==="npm"&&pt(["install","i","update","add"])&&(ft=!0),ut==="yarn"&&pt(["add","install","upgrade"])&&(ft=!0),ut==="pnpm"&&pt(["add","install","update"])&&(ft=!0),ut==="bun"&&pt(["add","install","update"])&&(ft=!0),ut==="deno"&&at(["install","add"])&&(ft=!0),ut==="pip"&&at(["install","download"])&&(ft=!0),ut==="pip3"&&at(["install","download"])&&(ft=!0),ut==="cargo"&&at(["install","add"])&&(ft=!0),["bash","sh","zsh","fish"].includes(ut)&&at(["-c"])&&(ft=!0),ut==="cmd"&&at(["/c"])&&(ft=!0),ft&&(he="deny",Oe=!0)}!he&&Ge&&(he="deny")}!be&&!he&&ce&&(he="allow")}else ce&&(he="allow");let Se=he,V="";he==="deny"&&(Oe?V="network":Ge?V="settings":V="prohibited");let ie=!1,ue="",$e=[],Je=0,Ae=!1,Zt="";if(!Se){if(A==="write_file"||A==="update_file")try{let Le=D(G.args),{path:rt}=Le;if(rt){let xe=te.resolve(process.cwd(),rt),en=at=>at?at.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,pt=>pt.toUpperCase()):"",_t=en(xe),gn="",ut=!1,tn=await xo(),ft=en(tn?.file_focused);if(tn&&ft===_t&&tn.full_content?(gn=tn.full_content,ut=!0):Fe.existsSync(xe)&&(gn=Fe.readFileSync(xe,"utf8"),ut=!0),ue=gn,await yt.recordFileChange(xe,gn),ut){let at=gn;if(A==="write_file"){let pt=Le.content||Le.newContent||"";at=pt.endsWith(`
1082
1082
  `)?pt:pt+`
1083
- `,Jt=lt}else{let{patchPairs:pt,allowMultiple:En,error:_n}=Os(Le);if(_n){let Mt=`[TOOL RESULT]: ERROR: ${_n}`;oe.push({role:"user",text:Mt}),await Ot("toolFailure"),t.onToolResult&&t.onToolResult("failure",A),yield{type:"tool_result",content:Mt,toolName:A},Ke++;continue}let _o=Le.allowMultiple!==void 0?Le.allowMultiple===!0||String(Le.allowMultiple).toLowerCase()==="true":En;Je=pt.length;let Ln=Ls(mn,pt,{allowMultiple:_o});lt=Ln.content,Jt=lt,$e=Ln.results;let ks=$e.filter(Mt=>Mt.success),At=$e.filter(Mt=>!Mt.success);if(ks.length===0){let Mt=`[TOOL RESULT]: ERROR: Failed to apply patches to [${te.basename(xe)}].
1084
- ${At.map(Ko=>` \u2022 ${Ko.error}`).join(`
1085
- `)}`,Co=`\u2714 Edited: ${te.basename(xe.replaceAll("\\","/"))}`,zo=115;process.stdout.isTTY&&(zo=process.stdout.columns-5||120);let $o=Math.min(Co.length+4,zo),Ss=`${Co.padEnd($o-2).substring(0,$o-2)}`;yield{type:"visual_feedback",content:nn(`${je?`
1086
- `:""}${Ss}`)},je=!1,oe.push({role:"user",text:Mt}),await Ot("toolFailure"),t.onToolResult&&t.onToolResult("failure",A),yield{type:"tool_result",content:Mt,toolName:A},Ke++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${te.basename(xe)}`},pi(xe,mn,lt),ie=!0,await new Promise(pt=>setTimeout(pt,50))}else if(A==="write_file"){let lt=Le.content||Le.newContent||"",pt=lt.endsWith(`
1087
- `)?lt:lt+`
1088
- `;Jt=pt,Fe.existsSync(xe)||(Ae=!0,Fe.mkdirSync(te.dirname(xe),{recursive:!0}),Fe.writeFileSync(xe,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${te.basename(xe)}`},pi(xe,"",pt),ie=!0,await new Promise(En=>setTimeout(En,50))}}}catch(Le){console.error("Simulation/Diff Error:",Le)}let De=null;fi(Le=>{De=Le});let wt=t.onToolApproval;if(Se=await new Promise(async Le=>{let rt=setInterval(()=>{De&&(or.onIDEApproval&&or.onIDEApproval(De),clearInterval(rt),Le(De))},100);try{let xe=await wt(A,G.args);clearInterval(rt),Le(xe)}catch{clearInterval(rt),Le("deny")}}),fi(null),A==="write_file"||A==="update_file"){let{path:Le}=D(G.args);if(Le){let rt=te.resolve(process.cwd(),Le);if(rl(rt,Se),Se==="deny"&&Ae&&Fe.existsSync(rt))try{Fe.unlinkSync(rt)}catch{}}}Se==="deny"&&(V="user")}if(Se==="allow"&&ie&&Hs()){let{path:De}=D(G.args),wt=te.resolve(process.cwd(),De),Le=At=>At?te.resolve(At).replace(/\\/g,"/").toLowerCase():"",rt=await xo(),xe="";if(rt&&rt.file_focused&&Le(rt.file_focused)===Le(wt)&&rt.full_content&&(xe=rt.full_content),!xe&&Fe.existsSync(wt)){let At=Fe.readFileSync(wt,"utf8");At&&(xe=At)}!xe&&Jt&&(xe=Jt),(xe||Ae)&&Fe.writeFileSync(wt,xe,"utf8");let Qt=xe.split(/\r?\n/),Et=Qt.length,mn=Buffer.byteLength(xe,"utf8"),ut="";ue&&(ut=`Old File contents:
1089
- ${ue.split(/\r?\n/).map((Mt,Co)=>`${Co+1} | ${Mt}`).join(`
1083
+ `,Zt=at}else{let{patchPairs:pt,allowMultiple:Cn,error:$n}=Os(Le);if($n){let It=`[TOOL RESULT]: ERROR: ${$n}`;oe.push({role:"user",text:It}),await Dt("toolFailure"),t.onToolResult&&t.onToolResult("failure",A),yield{type:"tool_result",content:It,toolName:A},Ke++;continue}let _o=Le.allowMultiple!==void 0?Le.allowMultiple===!0||String(Le.allowMultiple).toLowerCase()==="true":Cn;Je=pt.length;let Pn=Ls(gn,pt,{allowMultiple:_o});at=Pn.content,Zt=at,$e=Pn.results;let ks=$e.filter(It=>It.success),vt=$e.filter(It=>!It.success);if(ks.length===0){let It=`[TOOL RESULT]: ERROR: Failed to apply patches to [${te.basename(xe)}].
1084
+ ${vt.map(Ko=>` \u2022 ${Ko.error}`).join(`
1085
+ `)}`,Co=`\u2714 Edited: ${te.basename(xe.replaceAll("\\","/"))}`,zo=115;process.stdout.isTTY&&(zo=process.stdout.columns-5||120);let $o=Math.min(Co.length+4,zo),Ss=`${Co.padEnd($o-2).substring(0,$o-2)}`;yield{type:"visual_feedback",content:sn(`${je?`
1086
+ `:""}${Ss}`)},je=!1,oe.push({role:"user",text:It}),await Dt("toolFailure"),t.onToolResult&&t.onToolResult("failure",A),yield{type:"tool_result",content:It,toolName:A},Ke++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${te.basename(xe)}`},pi(xe,gn,at),ie=!0,await new Promise(pt=>setTimeout(pt,50))}else if(A==="write_file"){let at=Le.content||Le.newContent||"",pt=at.endsWith(`
1087
+ `)?at:at+`
1088
+ `;Zt=pt,Fe.existsSync(xe)||(Ae=!0,Fe.mkdirSync(te.dirname(xe),{recursive:!0}),Fe.writeFileSync(xe,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${te.basename(xe)}`},pi(xe,"",pt),ie=!0,await new Promise(Cn=>setTimeout(Cn,50))}}}catch(Le){console.error("Simulation/Diff Error:",Le)}let De=null;fi(Le=>{De=Le});let xt=t.onToolApproval;if(Se=await new Promise(async Le=>{let rt=setInterval(()=>{De&&(or.onIDEApproval&&or.onIDEApproval(De),clearInterval(rt),Le(De))},100);try{let xe=await xt(A,G.args);clearInterval(rt),Le(xe)}catch{clearInterval(rt),Le("deny")}}),fi(null),A==="write_file"||A==="update_file"){let{path:Le}=D(G.args);if(Le){let rt=te.resolve(process.cwd(),Le);if(rl(rt,Se),Se==="deny"&&Ae&&Fe.existsSync(rt))try{Fe.unlinkSync(rt)}catch{}}}Se==="deny"&&(V="user")}if(Se==="allow"&&ie&&Hs()){let{path:De}=D(G.args),xt=te.resolve(process.cwd(),De),Le=vt=>vt?te.resolve(vt).replace(/\\/g,"/").toLowerCase():"",rt=await xo(),xe="";if(rt&&rt.file_focused&&Le(rt.file_focused)===Le(xt)&&rt.full_content&&(xe=rt.full_content),!xe&&Fe.existsSync(xt)){let vt=Fe.readFileSync(xt,"utf8");vt&&(xe=vt)}!xe&&Zt&&(xe=Zt),(xe||Ae)&&Fe.writeFileSync(xt,xe,"utf8");let en=xe.split(/\r?\n/),_t=en.length,gn=Buffer.byteLength(xe,"utf8"),ut="";ue&&(ut=`Old File contents:
1089
+ ${ue.split(/\r?\n/).map((It,Co)=>`${Co+1} | ${It}`).join(`
1090
1090
  `)}
1091
1091
 
1092
- `);let Zt="";if(Et<=100)Zt=Qt.join(`
1093
- `);else{let At=Qt.slice(0,50).join(`
1094
- `),Mt=Qt.slice(-50).join(`
1095
- `);Zt=`${At}
1092
+ `);let tn="";if(_t<=100)tn=en.join(`
1093
+ `);else{let vt=en.slice(0,50).join(`
1094
+ `),It=en.slice(-50).join(`
1095
+ `);tn=`${vt}
1096
1096
 
1097
- ... [${Et-100} lines truncated for history stability] ...
1097
+ ... [${_t-100} lines truncated for history stability] ...
1098
1098
 
1099
- ${Mt}`}let ft="";if(A==="update_file"){let At=Ds(ue,xe,$e,12,t?.compressToolResults||or?.systemSettings?.compressToolResults);ft=`SUCCESS: File [${De}] updated via IDE Companion (May have user edits). [${$e.length}/${Je}] blocks applied.
1099
+ ${It}`}let ft="";if(A==="update_file"){let vt=Ds(ue,xe,$e,12,t?.compressToolResults||or?.systemSettings?.compressToolResults);ft=`SUCCESS: File [${De}] updated via IDE Companion (May have user edits). [${$e.length}/${Je}] blocks applied.
1100
1100
 
1101
- ${At}`}else{let At=xe.split(/\r?\n/),Mt=At.length,Co=Buffer.byteLength(xe,"utf8"),zo="";ue&&(zo=`Old File contents:
1101
+ ${vt}`}else{let vt=xe.split(/\r?\n/),It=vt.length,Co=Buffer.byteLength(xe,"utf8"),zo="";ue&&(zo=`Old File contents:
1102
1102
  ${ue.split(/\r?\n/).map((Ko,Il)=>`${Il+1} | ${Ko}`).join(`
1103
1103
  `)}
1104
1104
 
1105
- `);let $o="";if(Mt<=100)$o=At.join(`
1106
- `);else{let Ss=At.slice(0,50).join(`
1107
- `),Ko=At.slice(-50).join(`
1105
+ `);let $o="";if(It<=100)$o=vt.join(`
1106
+ `);else{let Ss=vt.slice(0,50).join(`
1107
+ `),Ko=vt.slice(-50).join(`
1108
1108
  `);$o=`${Ss}
1109
1109
 
1110
- ... [${Mt-100} lines truncated] ...
1110
+ ... [${It-100} lines truncated] ...
1111
1111
 
1112
1112
  ${Ko}`}ft=`SUCCESS: File [${De}] saved via IDE Companion (May have user edits).
1113
- - Stats: [${Mt} lines, ${(Co/1024).toFixed(1)} KB]
1113
+ - Stats: [${It} lines, ${(Co/1024).toFixed(1)} KB]
1114
1114
  ${zo}- Content Preview:
1115
1115
 
1116
- ${$o}`}let pt=`${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 _n=Math.min(pt.length+4,En),_o=`${pt.padEnd(_n-2).substring(0,_n-2)}`;yield{type:"visual_feedback",content:nn(`${je?`
1117
- `:""}${_o}`)},je=!1;let Ln=Date.now();K=Ln,yield{type:"tool_time",content:Ln-re};let ks=`[TOOL RESULT]: ${ft}`;oe.push({role:"user",text:ks}),fn=!0,await Ot("toolSuccess"),t.onToolResult&&t.onToolResult("success",A),yield{type:"tool_result",content:ft,aiContent:ks,toolName:A},Ke++;continue}if(Se==="deny"){let De=`Permission Denied: Prohibited ${A==="exec_command"?"Command":"file edit"}.`;if(V==="user"?De="Permission Denied by User":V==="settings"?De="Permission Denied by User Policy":V==="network"?De="Permission Denied: Sandbox Network Access Disabled by User Policy.":V==="prohibited"&&A==="exec_command"&&(De="Permission Denied: Prohibited Command in User Policy"),A==="write_file"||A==="update_file"){let Le=`\u2718 ${A==="write_file"?"Write Cancelled":"Edit Denied"}: ${D(G.args).path.replaceAll("\\","/")||"..."}`,rt=115;process.stdout.isTTY&&(rt=process.stdout.columns-5||120);let xe=Math.min(Le.length+4,rt),Qt=`${Le.padEnd(xe-2).substring(0,xe-2)}`,Et=` ${" ".repeat(xe)} `;yield{type:"visual_feedback",content:nn(`${je?`
1118
- `:""}${Qt}
1119
- `)},je=!1}A==="exec_command"&&(await new Promise(wt=>setTimeout(wt,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${De}`),await new Promise(wt=>setTimeout(wt,50)),t.onExecEnd&&t.onExecEnd()),oe.push({role:"user",text:`[TOOL RESULT]: DENIED: ${De}`}),yield{type:"tool_result",content:`[TOOL RESULT]: DENIED: ${De}`},await Ot("toolDenied"),t.onToolResult&&t.onToolResult("denied",A),Ke++;continue}}if(Z){let I=115;process.stdout.isTTY&&(I=process.stdout.columns-5||120);let Y=await o(),ce=!1;Y&&(ce=Y.trim().length>0);let he=Math.min(Z.length+4,I),be=`${Z.padEnd(he-2).substring(0,he-2)}`;yield{type:"visual_feedback",content:nn(`${je?`
1116
+ ${$o}`}let pt=`${De?"\u2714":"\u2718"} ${A==="write_file"?"Created":"Edited"}: ${De.replaceAll("\\","/")||"No File Changes"}`,Cn=115;process.stdout.isTTY&&(Cn=process.stdout.columns-5||120);let $n=Math.min(pt.length+4,Cn),_o=`${pt.padEnd($n-2).substring(0,$n-2)}`;yield{type:"visual_feedback",content:sn(`${je?`
1117
+ `:""}${_o}`)},je=!1;let Pn=Date.now();K=Pn,yield{type:"tool_time",content:Pn-re};let ks=`[TOOL RESULT]: ${ft}`;oe.push({role:"user",text:ks}),mn=!0,await Dt("toolSuccess"),t.onToolResult&&t.onToolResult("success",A),yield{type:"tool_result",content:ft,aiContent:ks,toolName:A},Ke++;continue}if(Se==="deny"){let De=`Permission Denied: Prohibited ${A==="exec_command"?"Command":"file edit"}.`;if(V==="user"?De="Permission Denied by User":V==="settings"?De="Permission Denied by User Policy":V==="network"?De="Permission Denied: Sandbox Network Access Disabled by User Policy.":V==="prohibited"&&A==="exec_command"&&(De="Permission Denied: Prohibited Command in User Policy"),A==="write_file"||A==="update_file"){let Le=`\u2718 ${A==="write_file"?"Write Cancelled":"Edit Denied"}: ${D(G.args).path.replaceAll("\\","/")||"..."}`,rt=115;process.stdout.isTTY&&(rt=process.stdout.columns-5||120);let xe=Math.min(Le.length+4,rt),en=`${Le.padEnd(xe-2).substring(0,xe-2)}`,_t=` ${" ".repeat(xe)} `;yield{type:"visual_feedback",content:sn(`${je?`
1118
+ `:""}${en}
1119
+ `)},je=!1}A==="exec_command"&&(await new Promise(xt=>setTimeout(xt,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${De}`),await new Promise(xt=>setTimeout(xt,50)),t.onExecEnd&&t.onExecEnd()),oe.push({role:"user",text:`[TOOL RESULT]: DENIED: ${De}`}),yield{type:"tool_result",content:`[TOOL RESULT]: DENIED: ${De}`},await Dt("toolDenied"),t.onToolResult&&t.onToolResult("denied",A),Ke++;continue}}if(Z){let I=115;process.stdout.isTTY&&(I=process.stdout.columns-5||120);let Y=await o(),ce=!1;Y&&(ce=Y.trim().length>0);let he=Math.min(Z.length+4,I),be=`${Z.padEnd(he-2).substring(0,he-2)}`;yield{type:"visual_feedback",content:sn(`${je?`
1120
1120
  `:""}${be}${Z.includes("\u2714")&&(Z.includes("Created")||Z.includes("Edited"))?"":`${ce?"":`
1121
- `}`}`)},je=!1}if(K>0){let I=Date.now()-K,Y=Math.max(0,1e3-I);Y>0&&await new Promise(ce=>setTimeout(ce,Y))}let zn={chatId:d,history:n,onChunk:I=>t.onExecChunk?t.onExecChunk(I):null,onAskUser:t.onAskUser,systemSettings:t.systemSettings,mode:i,isMultiModal:xt(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:I}=D(G.args);if(I){let Y=te.resolve(process.cwd(),I),ce=await xo();ce&&ce.file_focused===Y&&ce.full_content&&(zn.forcedContent=ce.full_content)}}catch{}sn.push(A);let Ce=await ms(A,G.args,zn);if((A==="write_file"||A==="update_file")&&Ce.startsWith("SUCCESS")){let{path:I}=D(G.args);if(I){let Y=te.resolve(process.cwd(),I);sl(Y)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let Ht=Date.now();K=Ht,yield{type:"tool_time",content:Ht-re},rn=Ht;let Xt=null;if(typeof Ce=="object"&&Ce.binaryPart&&(Xt=Ce.binaryPart,Ce=Ce.text),A==="search_keyword"){let{keyword:I,path:Y}=D(G.args),ce=typeof Ce=="string"&&Ce.startsWith("[GLOB]");ce&&(Ce=Ce.slice(6).trimStart());let he=typeof Ce=="string"&&Ce.startsWith("[DIR]");he&&(Ce=Ce.slice(5).trimStart());let be=0;if(Ce){let $e=Ce.match(/Found (\d+) match/i);$e&&(be=parseInt($e[1]))}let Ge=(Y||"").trim().toLowerCase().replaceAll("\\","/"),Oe=Ge==="#doc"||Ge==="#docs"||Ge==="#documentation"||Ge.includes("#skill/global/fluxflow")||Ge.includes("#skills/global/fluxflow"),Se;if(Oe)Se=`${I?"\u2714":"\u2718"} Searched Documentation`;else{let $e=Y?Y.replace(/[\/\\]+$/,""):null,Je=$e&&$e!=="."?`"${ce?Y:he?`${$e}/*`:$e}"`:"./";Se=`${I?"\u2714":"\u2718"} Searched: "${I||""}" in ${Je.replaceAll("\\","/")} \u2192 ${be} Match${be===1?"":"es"}`}let V=115;process.stdout.isTTY&&(V=process.stdout.columns-5||120);let ie=Math.min(Se.length+4,V),ue=`${Se.padEnd(ie-2).substring(0,ie-2)}`;yield{type:"visual_feedback",content:nn(`${je?`
1121
+ `}`}`)},je=!1}if(K>0){let I=Date.now()-K,Y=Math.max(0,1e3-I);Y>0&&await new Promise(ce=>setTimeout(ce,Y))}let zn={chatId:d,history:n,onChunk:I=>t.onExecChunk?t.onExecChunk(I):null,onAskUser:t.onAskUser,systemSettings:t.systemSettings,mode:i,isMultiModal:bt(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:I}=D(G.args);if(I){let Y=te.resolve(process.cwd(),I),ce=await xo();ce&&ce.file_focused===Y&&ce.full_content&&(zn.forcedContent=ce.full_content)}}catch{}an.push(A);let Ce=await ms(A,G.args,zn);if((A==="write_file"||A==="update_file")&&Ce.startsWith("SUCCESS")){let{path:I}=D(G.args);if(I){let Y=te.resolve(process.cwd(),I);sl(Y)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let Kt=Date.now();K=Kt,yield{type:"tool_time",content:Kt-re},ln=Kt;let Qt=null;if(typeof Ce=="object"&&Ce.binaryPart&&(Qt=Ce.binaryPart,Ce=Ce.text),A==="search_keyword"){let{keyword:I,path:Y}=D(G.args),ce=typeof Ce=="string"&&Ce.startsWith("[GLOB]");ce&&(Ce=Ce.slice(6).trimStart());let he=typeof Ce=="string"&&Ce.startsWith("[DIR]");he&&(Ce=Ce.slice(5).trimStart());let be=0;if(Ce){let $e=Ce.match(/Found (\d+) match/i);$e&&(be=parseInt($e[1]))}let Ge=(Y||"").trim().toLowerCase().replaceAll("\\","/"),Oe=Ge==="#doc"||Ge==="#docs"||Ge==="#documentation"||Ge.includes("#skill/global/fluxflow")||Ge.includes("#skills/global/fluxflow"),Se;if(Oe)Se=`${I?"\u2714":"\u2718"} Searched Documentation`;else{let $e=Y?Y.replace(/[\/\\]+$/,""):null,Je=$e&&$e!=="."?`"${ce?Y:he?`${$e}/*`:$e}"`:"./";Se=`${I?"\u2714":"\u2718"} Searched: "${I||""}" in ${Je.replaceAll("\\","/")} \u2192 ${be} Match${be===1?"":"es"}`}let V=115;process.stdout.isTTY&&(V=process.stdout.columns-5||120);let ie=Math.min(Se.length+4,V),ue=`${Se.padEnd(ie-2).substring(0,ie-2)}`;yield{type:"visual_feedback",content:sn(`${je?`
1122
1122
  `:""}${ue}
1123
- `)},je=!1}if(A==="EmergencyRollback"){let{method:I}=D(G.args);if(I==="forceRevert"){let Y=0;if(Ce){let ie=Ce.match(/Total\s*:\s*(\d+)/i);ie&&(Y=parseInt(ie[1]))}let he=Ce&&Ce.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=await o(),Oe=!1;Ge&&(Oe=Ge.trim().length>0);let Se=Math.min(he.length+4,be),V=`${he.padEnd(Se-2).substring(0,Se-2)}`;yield{type:"visual_feedback",content:nn(`${je?`
1123
+ `)},je=!1}if(A==="EmergencyRollback"){let{method:I}=D(G.args);if(I==="forceRevert"){let Y=0;if(Ce){let ie=Ce.match(/Total\s*:\s*(\d+)/i);ie&&(Y=parseInt(ie[1]))}let he=Ce&&Ce.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=await o(),Oe=!1;Ge&&(Oe=Ge.trim().length>0);let Se=Math.min(he.length+4,be),V=`${he.padEnd(Se-2).substring(0,Se-2)}`;yield{type:"visual_feedback",content:sn(`${je?`
1124
1124
  `:""}${V}${Oe?"":`
1125
1125
  `}`)},je=!1}}if(A==="todo"){let{method:I,tasks:Y,markDone:ce}=D(G.args),he="",be=[],Ge=Oe=>{if(!Oe)return[];let Se=Array.isArray(Oe)?Oe:[];if(Se.length===0&&typeof Oe=="string"){let V=Oe.trim();if(V.startsWith("[")&&V.endsWith("]")){let ie=V.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);ie?Se=ie.map(ue=>ue.slice(1,-1).replace(/\\(.)/g,"$1")):Se=V.slice(1,-1).split(",").map(ue=>ue.trim()).filter(Boolean)}else Se=Oe.split(`
1126
1126
  `)}return Se.filter(V=>String(V).trim()).map(V=>{let ie=String(V).trim();return ie.startsWith("- [")?ie.substring(6).trim():ie})};if(I==="create"?(he="\x1B[32m\u2192\x1B[0m Created Goals",be=Ge(Y).map(Oe=>`\x1B[90m\u25CB\x1B[0m ${Oe}`)):I==="append"?(he="\x1B[34m\u2795\x1B[0m Added New Goals",be=Ge(Y).map(Oe=>`\x1B[90m\u25CB\x1B[0m ${Oe}`)):I==="get"&&(he=ce?"\x1B[36m\u21BB\x1B[0m Updated Goals":"\x1B[35m\u2022\x1B[0m Reviewed Goals",be=(Ce||"").split(`
1127
1127
  `).slice(1).join(`
1128
1128
  `).split(`
1129
1129
  `).filter(Se=>Se.trim().startsWith("- [")).map(Se=>{let V=Se.trim(),ie=V.startsWith("- [x]");return`${ie?"\x1B[32m\u2714\x1B[0m":"\x1B[90m\u25CB\x1B[0m"} ${ie?"\x1B[90m":"\x1B[37m"}${V.substring(6).trim()}\x1B[0m`})),he&&be.length>0){let Oe=[`${he}`,...be.map(ie=>` ${ie}`)].join(`
1130
- `),Se=await o(),V=!1;Se&&(V=Se.trim().length>0),yield{type:"visual_feedback",content:nn(`${je?`
1130
+ `),Se=await o(),V=!1;Se&&(V=Se.trim().length>0),yield{type:"visual_feedback",content:sn(`${je?`
1131
1131
  `:""}${Oe}${V?"":`
1132
- `}`)},je=!1}}A==="exec_command"&&t.onExecEnd&&(await new Promise(I=>setTimeout(I,800)),t.onExecEnd());let In=Ce&&Ce.startsWith("DENIED:");Ce&&!Ce.startsWith("ERROR:")&&!In?(await Ot("toolSuccess"),t.onToolResult&&t.onToolResult("success",A)):In||(await Ot("toolFailure"),t.onToolResult&&t.onToolResult("failure",A));let qt=(Ce||"").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.
1133
- `));let On;if(qt.startsWith("[[SAME]]")){let Y=qt.replace(/^\[\[SAME\]\]\s*\r?\n?/,"").split(/\r?\n/),ce=Y.filter(be=>be.startsWith("SUCCESS:")||be.trim().startsWith("- Stats:"));On=`[TOOL RESULT]: ${ce.length>0?ce.join(`
1132
+ `}`)},je=!1}}A==="exec_command"&&t.onExecEnd&&(await new Promise(I=>setTimeout(I,800)),t.onExecEnd());let Ln=Ce&&Ce.startsWith("DENIED:");Ce&&!Ce.startsWith("ERROR:")&&!Ln?(await Dt("toolSuccess"),t.onToolResult&&t.onToolResult("success",A)):Ln||(await Dt("toolFailure"),t.onToolResult&&t.onToolResult("failure",A));let Yt=(Ce||"").toString().replaceAll("[UI_CONTEXT]","");Yt.includes("[[VERIFIED]]")&&(Yt=Yt.replace(/\[\[VERIFIED\]\][\s\S]*?\[\[\/VERIFIED\]\]/g,`[SYSTEM NOTE]: Patch Block matched & applied successfully. Large Block omitted to conserve context.
1133
+ `));let Dn;if(Yt.startsWith("[[SAME]]")){let Y=Yt.replace(/^\[\[SAME\]\]\s*\r?\n?/,"").split(/\r?\n/),ce=Y.filter(be=>be.startsWith("SUCCESS:")||be.trim().startsWith("- Stats:"));Dn=`[TOOL RESULT]: ${ce.length>0?ce.join(`
1134
1134
  `):Y.slice(0,2).join(`
1135
1135
  `)}
1136
- [SYSTEM NOTE]: Content verified and persisted to disk. Full preview omitted to conserve context.`}else On=`[TOOL RESULT]: ${qt}`;oe.push({role:"user",text:On,binaryPart:Xt}),fn=!0;let Ie=`[TOOL RESULT]: ${Ce.replaceAll(`[[VERIFIED]]
1136
+ [SYSTEM NOTE]: Content verified and persisted to disk. Full preview omitted to conserve context.`}else Dn=`[TOOL RESULT]: ${Yt}`;oe.push({role:"user",text:Dn,binaryPart:Qt}),mn=!0;let Ie=`[TOOL RESULT]: ${Ce.replaceAll(`[[VERIFIED]]
1137
1137
  `,"").replaceAll(`
1138
- [[/VERIFIED]]`,"")||""}`;(A==="view_file"||A==="web_scrape"||A==="file_map")&&(Ie=`[TOOL RESULT]: ${Z} (Context Locked for UI Clarity)`),yield{type:"tool_result",content:Ie,aiContent:On,binaryPart:Xt,toolName:A},A==="memory"&&Ce.includes("SUCCESS")&&(yield{type:"memory_updated"}),Ke++}if(u==="Google"&&Tn&&Date.now()-cr>=150){yield*io();let G=Ho(Tn);for(let re of G)yield re;Tn="",cr=Date.now()}}N.usageMetadata&&(Mn=N.usageMetadata),Mn&&(yield{type:"liveTokens",content:Mn.totalTokenCount})}if(pe&&(pe=!1,Wt?Xe+="</think>":(ge+="</think>",u==="Google"?Tn+="</think>":yield{type:"text",content:"</think>"})),Wt&&Xe.length>0){let N=0,ae=Math.min(it.length,Xe.length);for(let q=ae;q>0;q--)if(it.endsWith(Xe.substring(0,q))){N=q;break}let H=Xe.substring(N);if(H){let Re=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(it)?H.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):H.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(Re)if(ge+=Re,u==="Google")Tn+=Re;else{yield*io();let we=Ho(Re);for(let _e of we)yield _e}}Wt=!1,Xe=""}if(yield*io(),It)break;let qo=(ge||"").trim(),_l=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(qo.toLowerCase())||/\[\[END\]\]/i.test(qo.toLowerCase()),Cl=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(qo.toLowerCase()),$l=oe.length>0||Ut!==null,dr=on(qo).trim(),Al=/(\p{Emoji_Presentation}|\p{Extended_Pictographic})$/u.test(dr),Ml=/([.!?"'*_`|\]\)”’~~]+|\s|`{3}|[\u200B-\u200D\uFEFF])$/u.test(dr.trim()),vl=/[.!?}"'`’“”]$|```$/s.test(dr)||Ml||Al;!_l&&!Cl&&!$l&&qo.length>0,ot=!0,await Ot("agent",u)}catch(Te){if(It){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
1138
+ [[/VERIFIED]]`,"")||""}`;(A==="view_file"||A==="web_scrape"||A==="file_map")&&(Ie=`[TOOL RESULT]: ${Z} (Context Locked for UI Clarity)`),yield{type:"tool_result",content:Ie,aiContent:Dn,binaryPart:Qt,toolName:A},A==="memory"&&Ce.includes("SUCCESS")&&(yield{type:"memory_updated"}),Ke++}if(u==="Google"&&En&&Date.now()-cr>=150){yield*io();let G=Ho(En);for(let re of G)yield re;En="",cr=Date.now()}}N.usageMetadata&&(In=N.usageMetadata),In&&(yield{type:"liveTokens",content:In.totalTokenCount})}if(pe&&(pe=!1,Gt?Xe+="</think>":(ge+="</think>",u==="Google"?En+="</think>":yield{type:"text",content:"</think>"})),Gt&&Xe.length>0){let N=0,ae=Math.min(it.length,Xe.length);for(let q=ae;q>0;q--)if(it.endsWith(Xe.substring(0,q))){N=q;break}let H=Xe.substring(N);if(H){let Re=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(it)?H.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):H.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(Re)if(ge+=Re,u==="Google")En+=Re;else{yield*io();let we=Ho(Re);for(let _e of we)yield _e}}Gt=!1,Xe=""}if(yield*io(),Lt)break;let qo=(ge||"").trim(),_l=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(qo.toLowerCase())||/\[\[END\]\]/i.test(qo.toLowerCase()),Cl=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(qo.toLowerCase()),$l=oe.length>0||Wt!==null,dr=rn(qo).trim(),Al=/(\p{Emoji_Presentation}|\p{Extended_Pictographic})$/u.test(dr),Ml=/([.!?"'*_`|\]\)”’~~]+|\s|`{3}|[\u200B-\u200D\uFEFF])$/u.test(dr.trim()),vl=/[.!?}"'`’“”]$|```$/s.test(dr)||Ml||Al;!_l&&!Cl&&!$l&&qo.length>0,ot=!0,await Dt("agent",u)}catch(Te){if(Lt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
1139
1139
 
1140
- \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(String(Te).includes("Incomplete JSON segment at the end")){pe&&(pe=!1,Wt?Xe+="</think>":(ge+="</think>",yield{type:"text",content:"</think>"})),ot=!0,await Ot("agent",u);break}if(pe&&(pe=!1,Wt?Xe+="</think>":ge+="</think>"),Wt&&Xe.length>0){let qn=0,an=Math.min(it.length,Xe.length);for(let Pt=an;Pt>0;Pt--)if(it.endsWith(Xe.substring(0,Pt))){qn=Pt;break}let Dt=Xe.substring(qn);if(Dt){let Rt=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(it)?Dt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):Dt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");Rt&&(ge+=Rt)}Wt=!1,Xe=""}let me=Te instanceof Error?(()=>{try{return JSON.parse(JSON.parse(Te.message).error.message).error.message}catch{return String(Te)}})():String(Te),at=new Date().toLocaleString(),jt=te.join(hn,"agent");Fe.existsSync(jt)||Fe.mkdirSync(jt,{recursive:!0}),Fe.appendFileSync(te.join(jt,"error.log"),`ERROR [${at}]: ${me}
1140
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(String(Te).includes("Incomplete JSON segment at the end")){pe&&(pe=!1,Gt?Xe+="</think>":(ge+="</think>",yield{type:"text",content:"</think>"})),ot=!0,await Dt("agent",u);break}if(pe&&(pe=!1,Gt?Xe+="</think>":ge+="</think>"),Gt&&Xe.length>0){let cn=0,qt=Math.min(it.length,Xe.length);for(let Nt=qt;Nt>0;Nt--)if(it.endsWith(Xe.substring(0,Nt))){cn=Nt;break}let Ft=Xe.substring(cn);if(Ft){let Et=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(it)?Ft.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):Ft.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");Et&&(ge+=Et)}Gt=!1,Xe=""}let me=Te instanceof Error?(()=>{try{return JSON.parse(JSON.parse(Te.message).error.message).error.message}catch{return String(Te)}})():String(Te),Ht=new Date().toLocaleString(),Pt=te.join(yn,"agent");Fe.existsSync(Pt)||Fe.mkdirSync(Pt,{recursive:!0}),Fe.appendFileSync(te.join(Pt,"error.log"),`ERROR [${Ht}]: ${me}
1141
1141
 
1142
1142
  ----------------------------------------------------------------------
1143
1143
 
1144
- `);let Vt=Te.status||Te.statusCode||Te.code,Hn=String(Te).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(Te))||/code[ :]+(5\d\d|408|429)/i.test(String(Te))||/(500|503|408|429)/.test(String(Te))))){if(ze<kn-3)throw Te;yield{type:"text",content:me},yield{type:"status",content:"Error Occured"}}if(ge.trim().length>0||et>1)if(et<=kn){et++;let qn=Math.min(1e3*Math.pow(2,et-1),24e3);if(ge.trim().length>0){x.push({role:"agent",text:ge});let an=`[system]
1144
+ `);let Mt=Te.status||Te.statusCode||Te.code,ht=String(Te).includes("replicas at capacity");if(!(Mt&&(Mt>=500&&Mt<600||Mt===408||Mt===429||ht)||!Mt&&(/status[ :]+(5\d\d|408|429)/i.test(String(Te))||/code[ :]+(5\d\d|408|429)/i.test(String(Te))||/(500|503|408|429)/.test(String(Te))))){if(ze<Tn-3)throw Te;yield{type:"text",content:me},yield{type:"status",content:"Error Occured"}}if(ge.trim().length>0||et>1)if(et<=Tn){et++;let cn=Math.min(1e3*Math.pow(2,et-1),24e3);if(ge.trim().length>0){x.push({role:"agent",text:ge});let qt=`[system]
1145
1145
  - seamless continuation: resume immediately. pick up from last words with zero gap/disruption
1146
1146
  - no repetition: do not repeat any text already written
1147
1147
  - no re-think: do not restart or open <think> if reasoning already started. continue the thinking and close thinking block </think> before chat output
1148
1148
  - mid-tool safety: if cutoff was mid-tool call, restart that tool call from start
1149
- - stealth: do not mention/apologize for cutoff [/system]`;oe.length>0?oe.forEach((Dt,Pt)=>{Pt===oe.length-1?x.push({...Dt,text:`${Dt.text}
1149
+ - stealth: do not mention/apologize for cutoff [/system]`;oe.length>0?oe.forEach((Ft,Nt)=>{Nt===oe.length-1?x.push({...Ft,text:`${Ft.text}
1150
1150
 
1151
- ${an}`}):x.push(Dt)}):x.push({role:"user",text:an}),it+=ge}for(let an=qn/1e3;an>0&&!It;an--)yield{type:"status",content:`Error Occured. Recovering Stream (${et}/${kn}) [Retrying in ${an.toFixed(0)}s]...`},await new Promise(Dt=>setTimeout(Dt,1e3));yield{type:"status",content:"Error Occured. Recovering Stream..."}}else throw new Error(`Stream collapsed too many times. (Failed to resolve ${kn} times)
1152
- Error log can be found in \`/export logs\``);else if(ze<=kn){ze++,et=1,it="";let qn=Math.min(1e3*Math.pow(2,ze-1),32e3),an=.8+Math.random()*.4,Dt=Math.round(qn*an);no=!0,yield{type:"status",content:`Trying to reach ${e} (${ze}/${kn}) [Retrying in ${(Dt/1e3).toFixed(0)}s]`};for(let Pt=Dt/1e3;Pt>0&&!It;Pt--)yield{type:"status",content:`Trying to reach ${e} (${ze}/${kn}) [Retrying in ${Pt.toFixed(0)}s]`},await new Promise(Rt=>setTimeout(Rt,1e3));yield{type:"status",content:`Trying to reach ${e}`}}else throw new Error(`Model ${e} cannot be reached. (Failed ${kn} times)
1153
- Error log can be found in \`/export logs\``)}}if(Mn){let pe=Mn.totalTokenCount||0,Te=Mn.cachedContentTokenCount||0,me=(Mn.candidatesTokenCount||0)+(Mn.thoughtsTokenCount||0);await zt("tokens",pe,u,ke),Te>0&&await zt("cachedTokens",Te,u,ke),me>0&&await zt("candidateTokens",me,u,ke),yield{type:"usage",content:Mn}}vi.push(ge);let so=on(ge),pn=pl(ge),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()),Rd=Ke>0;yield{type:"status",content:"Thinking"};let Sl=yd(ge,/(\[\s*(turn\s*:)?\s*(continue|finish)\s*\]|\[\[END\]\])/gi,"").trim(),ro=(Go||oe.length===0)&&!Bt&&!Sn&&!vn;if(ro=oe.length===0?ro:!1,ro=oo||xs?!1:ro,ge&&ge.trim().endsWith('")]')&&oe.length===0&&(ro=!1),ro){let pe=vi.join(`
1154
- `),Te=on(pe).trim();yield{type:"interactive_turn_finished",data:{agentText:S,fullAgentTextRaw:pe,history:[...x],needTitle:k}},x.length>0&&x[x.length-1].role==="agent"?x[x.length-1].text=Te:x.push({role:"agent",text:Te}),x.forEach(me=>{if(me.role==="user"&&me.text&&(me.text=me.text.replace(/\n\[COMPILE ERROR\][\s\S]*?\[\/ERROR\]/g,""),me.text=me.text.replaceAll(`
1151
+ ${qt}`}):x.push(Ft)}):x.push({role:"user",text:qt}),it+=ge}for(let qt=cn/1e3;qt>0&&!Lt;qt--)yield{type:"status",content:`Error Occured. Recovering Stream (${et}/${Tn}) [Retrying in ${qt.toFixed(0)}s]...`},await new Promise(Ft=>setTimeout(Ft,1e3));yield{type:"status",content:"Error Occured. Recovering Stream..."}}else throw new Error(`Stream collapsed too many times. (Failed to resolve ${Tn} times)
1152
+ Error log can be found in \`/export logs\``);else if(ze<=Tn){ze++,et=1,it="";let cn=Math.min(1e3*Math.pow(2,ze-1),32e3),qt=.8+Math.random()*.4,Ft=Math.round(cn*qt);no=!0,yield{type:"status",content:`Trying to reach ${e} (${ze}/${Tn}) [Retrying in ${(Ft/1e3).toFixed(0)}s]`};for(let Nt=Ft/1e3;Nt>0&&!Lt;Nt--)yield{type:"status",content:`Trying to reach ${e} (${ze}/${Tn}) [Retrying in ${Nt.toFixed(0)}s]`},await new Promise(Et=>setTimeout(Et,1e3));yield{type:"status",content:`Trying to reach ${e}`}}else throw new Error(`Model ${e} cannot be reached. (Failed ${Tn} times)
1153
+ Error log can be found in \`/export logs\``)}}if(In){let pe=In.totalTokenCount||0,Te=In.cachedContentTokenCount||0,me=(In.candidatesTokenCount||0)+(In.thoughtsTokenCount||0);await Vt("tokens",pe,u,ke),Te>0&&await Vt("cachedTokens",Te,u,ke),me>0&&await Vt("candidateTokens",me,u,ke),yield{type:"usage",content:In}}vi.push(ge);let so=rn(ge),hn=pl(ge),Go=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(hn.toLowerCase())||/\[\[END\]\]/i.test(hn.toLowerCase())||!0,qn=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(hn.toLowerCase()),Rd=Ke>0;yield{type:"status",content:"Thinking"};let Sl=yd(ge,/(\[\s*(turn\s*:)?\s*(continue|finish)\s*\]|\[\[END\]\])/gi,"").trim(),ro=(Go||oe.length===0)&&!jt&&!Rn&&!On;if(ro=oe.length===0?ro:!1,ro=oo||xs?!1:ro,ge&&ge.trim().endsWith('")]')&&oe.length===0&&(ro=!1),ro){let pe=vi.join(`
1154
+ `),Te=rn(pe).trim();yield{type:"interactive_turn_finished",data:{agentText:S,fullAgentTextRaw:pe,history:[...x],needTitle:k}},x.length>0&&x[x.length-1].role==="agent"?x[x.length-1].text=Te:x.push({role:"agent",text:Te}),x.forEach(me=>{if(me.role==="user"&&me.text&&(me.text=me.text.replace(/\n\[COMPILE ERROR\][\s\S]*?\[\/ERROR\]/g,""),me.text=me.text.replaceAll(`
1155
1155
 
1156
1156
  [system] user question. resolve this specific query within '[ANSWER] ... [/ANSWER]' concisely, naturally [/system]
1157
1157
  `,"").replaceAll(`[system] user question. resolve this specific query within '[ANSWER] ... [/ANSWER]' concisely, naturally
1158
1158
  **strictly follow thinking policy as high priority. do not start a response without <think>...</think>** [/system]
1159
1159
  `,"").replaceAll(`[system] **strictly follow thinking policy as high priority. do not start a response without <think>...</think>** [/system]
1160
- `,"").replaceAll(/\n\[system\] WARNING, Turn Limit Impending: Step \d+\/\d+\. Wrap up quickly\/prompt user to continue & use \[\[END\]\] quickly\. \[\/system\]/g,""),me.text=me.text.replaceAll(/\n\[system\] File Changes:\n(?:\* .+ \(created|modified|deleted\)\n)*\[\/system\]/g,""),(u==="Mistral"||u==="Google"&&e?.toLowerCase().startsWith("gemma"))&&me.text.startsWith("[TOOL RESULT]"))){let jt=`
1161
- [system] Tool result received. Analyze output and proceed with your turn [/system]`,Vt=`
1162
- [system] Tool result received. Analyze output and proceed with your turn. **strictly follow thinking policy. do not start a response without <think>...</think>** [/system]`;me.text=me.text.replaceAll(Vt,"").replaceAll(jt,"").trim()}}),yield{type:"status",content:"[end]"}}if(ro)break;let Tl=Sl.trim()||"*Working...*";if(x.push({role:"agent",text:Tl}),oe.length>0||fn){if(oe.length>0){let pe=oe.map(Hn=>Hn.text).join(`
1160
+ `,"").replaceAll(/\n\[system\] WARNING, Turn Limit Impending: Step \d+\/\d+\. Wrap up quickly\/prompt user to continue & use \[\[END\]\] quickly\. \[\/system\]/g,""),me.text=me.text.replaceAll(/\n\[system\] File Changes:\n(?:\* .+ \(created|modified|deleted\)\n)*\[\/system\]/g,""),(u==="Mistral"||u==="Google"&&e?.toLowerCase().startsWith("gemma"))&&me.text.startsWith("[TOOL RESULT]"))){let Pt=`
1161
+ [system] Tool result received. Analyze output and proceed with your turn [/system]`,Mt=`
1162
+ [system] Tool result received. Analyze output and proceed with your turn. **strictly follow thinking policy. do not start a response without <think>...</think>** [/system]`;me.text=me.text.replaceAll(Mt,"").replaceAll(Pt,"").trim()}}),yield{type:"status",content:"[end]"}}if(ro)break;let Tl=Sl.trim()||"*Working...*";if(x.push({role:"agent",text:Tl}),oe.length>0||mn){if(oe.length>0){let pe=oe.map(ht=>ht.text).join(`
1163
1163
 
1164
- `),at=(on(ge).replace(/\[{1,2}tool:[\s\S]*?\)\s*\]{1,2}/gi,"").match(/\[tool:/gi)||[]).length,jt=oe.length+at;if(oe.length<jt){pe+=`
1164
+ `),Ht=(rn(ge).replace(/\[{1,2}tool:[\s\S]*?\)\s*\]{1,2}/gi,"").match(/\[tool:/gi)||[]).length,Pt=oe.length+Ht;if(oe.length<Pt){pe+=`
1165
1165
 
1166
- [system] Only ${oe.length} out of ${jt} attempted tool calls were executed. Verify proper structure compliance & try failed calls again [/system]`;let Hn=jt-oe.length;for(let Lt=0;Lt<Hn;Lt++)await Ot("toolFailure")}let Vt=oe.find(Hn=>Hn.binaryPart)?.binaryPart||null;x.push({role:"user",text:pe,binaryPart:Vt})}}else if(!It){let Te=(ge.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/i,"").match(/\[tool:/gi)||[]).length;xs||oo||Te>0?(x.push({role:"user",text:`[system] Failed to execute ${Te} tool${Te>1?"s":""}. Verify proper structure compliance & try again [/system]`}),await Ot("toolFailure"),yield{type:"visual_feedback",content:`
1167
- ${nn("\u2718 Execution Error")}
1166
+ [system] Only ${oe.length} out of ${Pt} attempted tool calls were executed. Verify proper structure compliance & try failed calls again [/system]`;let ht=Pt-oe.length;for(let dt=0;dt<ht;dt++)await Dt("toolFailure")}let Mt=oe.find(ht=>ht.binaryPart)?.binaryPart||null;x.push({role:"user",text:pe,binaryPart:Mt})}}else if(!Lt){let Te=(ge.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/i,"").match(/\[tool:/gi)||[]).length;xs||oo||Te>0?(x.push({role:"user",text:`[system] Failed to execute ${Te} tool${Te>1?"s":""}. Verify proper structure compliance & try again [/system]`}),await Dt("toolFailure"),yield{type:"visual_feedback",content:`
1167
+ ${sn("\u2718 Execution Error")}
1168
1168
  `}):(yield{type:"visual_feedback",content:`
1169
- ${nn("\u2718 Loop Detected")}
1170
- `},x.push({role:"user",text:`[system] ${Sn&&!Bt?"Stuttering Detected by Internal System. Re-calibrate your response & proceed.":`${Bt?" Over Thinking":" Loop"} Detected by Internal System${Bt?" for current Effort Level":""}. ${Bt?"If you have planned the task, prioritize execution/output":"If you have finished your task provide a simple summary and end"}`} [/system]`})),Bt=!1,Sn=!1,vn=!1}l?.advanceRollback&&await Zn.recordTurnDelta(d,z+1,sn),xs=Ke>0||fn}}catch(E){let C=(E instanceof Error?(()=>{try{return JSON.parse(JSON.parse(E.message).error.message).error.message}catch{return E.message||String(E)}})():String(E)).replace(/^(Error:\s*)+/i,""),M=new Date().toLocaleString(),v=te.join(hn,"agent");yield{type:"text",content:`
1169
+ ${sn("\u2718 Loop Detected")}
1170
+ `},x.push({role:"user",text:`[system] ${Rn&&!jt?"Stuttering Detected by Internal System. Re-calibrate your response & proceed.":`${jt?" Over Thinking":" Loop"} Detected by Internal System${jt?" for current Effort Level":""}. ${jt?"If you have planned the task, prioritize execution/output":"If you have finished your task provide a simple summary and end"}`} [/system]`})),jt=!1,Rn=!1,On=!1}l?.advanceRollback&&await Zn.recordTurnDelta(d,z+1,an),xs=Ke>0||mn}}catch(E){let C=(E instanceof Error?(()=>{try{return JSON.parse(JSON.parse(E.message).error.message).error.message}catch{return E.message||String(E)}})():String(E)).replace(/^(Error:\s*)+/i,""),M=new Date().toLocaleString(),v=te.join(yn,"agent");yield{type:"text",content:`
1171
1171
 
1172
1172
  \u2726 CRITICAL ERROR: ${C.includes("fetch failed")?"Failed to Connect. Check your Internet Connection or Wait a moment":C}
1173
1173
  \u2800`},Fe.existsSync(v)||Fe.mkdirSync(v,{recursive:!0}),Fe.appendFileSync(te.join(v,"error.log"),`CRITICAL ERROR [${M}]: ${E}
1174
1174
 
1175
1175
  ----------------------------------------------------------------------
1176
1176
 
1177
- `),typeof flushGoogleBuffer=="function"&&(yield*flushGoogleBuffer()),yield{type:"tool_result",content:`ERROR: [INTERNAL CRITICAL] ${C}`}}finally{_&&(clearInterval(_),_=null),typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),await gt.commitTransaction(),l?.advanceRollback&&await Zn.cleanup(d),await xo()}yield{type:"status",content:null}},Py=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,f=`${l.getFullYear()}-${l.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(l.getDate()).padStart(2,"0")}, ${l.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}).replace(":","-")}`,m=(E=>{if(!E)return null;let x=E.toLowerCase();return x==="google"?"Google":x==="deepseek"?"DeepSeek":x==="openrouter"?"OpenRouter":x==="nvidia"?"NVIDIA":x==="mistral"?"Mistral":x==="ollama"?"Ollama":x==="crofai"||x==="crof"?"CrofAI":x==="inferx"?"InferX":x==="sensenova"?"SenseNova":x==="poolside"?"Poolside":x==="9router"||x==="9Router"?"9router":x==="aihubmix"||x==="aihub"?"AIHubMix":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 mr(p.aiProvider);E&&(p.apiKey=E)}let b=E=>{if(!E||typeof E!="string")return{allowed:!0};let x=[/rm\s+-[rf]{1,2}\s+[\/*.]/i,/rmdir\s+\/[sq]/i,/del\s+\/[fsq]/i,/\bformat\b\s+[a-z]:/i,/mkfs/i,/dd\s+if=/i,/\b(shutdown|reboot|poweroff|init\s+0|init\s+6)\b/i,/chmod\s+(-R\s+)?777\s+[\/*.]/i,/chown\s+(-R\s+)?root/i,/git\s+push\s+.*--force/i,/git\s+clean\s+-fdx/i,/\bsudo\s+su\b/i,/\bsu\s+-\b/i];for(let C of x)if(C.test(E))return{allowed:!1,reason:`Blocked potentially destructive or unsafe command pattern: "${C.source}"`};return{allowed:!0}},w=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: '/') --
1177
+ `),typeof flushGoogleBuffer=="function"&&(yield*flushGoogleBuffer()),yield{type:"tool_result",content:`ERROR: [INTERNAL CRITICAL] ${C}`}}finally{_&&(clearInterval(_),_=null),typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),await yt.commitTransaction(),l?.advanceRollback&&await Zn.cleanup(d),await xo()}yield{type:"status",content:null}},Py=async(e,n,t=null,o=null,s=50,r=null,a=!1)=>{let i=await on(),p={...i,...n},d=process.env.SUBAGENT_MODEL?process.env.SUBAGENT_MODEL.trim():null,c=process.env.SUBAGENT_PROVIDER?process.env.SUBAGENT_PROVIDER.trim():null,l=new Date,f=`${l.getFullYear()}-${l.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(l.getDate()).padStart(2,"0")}, ${l.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}).replace(":","-")}`,m=(E=>{if(!E)return null;let x=E.toLowerCase();return x==="google"?"Google":x==="deepseek"?"DeepSeek":x==="openrouter"?"OpenRouter":x==="nvidia"?"NVIDIA":x==="mistral"?"Mistral":x==="ollama"?"Ollama":x==="crofai"||x==="crof"?"CrofAI":x==="inferx"?"InferX":x==="sensenova"?"SenseNova":x==="poolside"?"Poolside":x==="9router"||x==="9Router"?"9router":x==="aihubmix"||x==="aihub"?"AIHubMix":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 mr(p.aiProvider);E&&(p.apiKey=E)}let b=E=>{if(!E||typeof E!="string")return{allowed:!0};let x=[/rm\s+-[rf]{1,2}\s+[\/*.]/i,/rmdir\s+\/[sq]/i,/del\s+\/[fsq]/i,/\bformat\b\s+[a-z]:/i,/mkfs/i,/dd\s+if=/i,/\b(shutdown|reboot|poweroff|init\s+0|init\s+6)\b/i,/chmod\s+(-R\s+)?777\s+[\/*.]/i,/chown\s+(-R\s+)?root/i,/git\s+push\s+.*--force/i,/git\s+clean\s+-fdx/i,/\bsudo\s+su\b/i,/\bsu\s+-\b/i];for(let C of x)if(C.test(E))return{allowed:!1,reason:`Blocked potentially destructive or unsafe command pattern: "${C.source}"`};return{allowed:!0}},w=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: '/') --
1178
1178
  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
1179
1179
  Tool Rules:
1180
1180
  - Mandatorily JSON escape literal sequences (backslash: \\\\, newLine: \\ n, quote: \\")
@@ -1200,7 +1200,7 @@ ${a?"- AskMain(question=string). Communicate with PARENT/MAIN AGENT. When clarif
1200
1200
  - ReadFile(path=string, startLine?=int, endLine?=int)
1201
1201
  - 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
1202
1202
  - WriteFile(path=string, content=string). Creates/Overwrites. File Exist? PatchFile > WriteFile
1203
- - Run(command=string). Runs ${T==="Windows"?Fn()?"powershell":"windows CMD":"bash"} command. Destructive command \u2192 Ask user`.trim(),R=`=== START SYSTEM PROMPT ===
1203
+ - Run(command=string). Runs ${T==="Windows"?Un()?"powershell":"windows CMD":"bash"} command. Destructive command \u2192 Ask user`.trim(),R=`=== START SYSTEM PROMPT ===
1204
1204
  Identity: FluxFlow subagent helping the main Agent
1205
1205
  Your task is: "${e}"
1206
1206
 
@@ -1214,14 +1214,14 @@ CWD: ${process.cwd()}
1214
1214
  ${$.trimEnd()}
1215
1215
 
1216
1216
  Current Time: ${f}
1217
- === END SYSTEM PROMPT ===`,k=[{role:"user",text:`Complete this task: ${e}`}],S=0,_="";for(;S<s;){if(It){if(n?.taskId&&typeof Qe<"u"){let F=Qe.find(W=>W.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 Qe<"u"){let F=Qe.find(W=>W.id===n.taskId);if(F&&F.status==="cancelled")throw r&&r("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}let E=k.map(F=>({role:F.role==="user"?"user":"model",parts:[{text:F.text}]}));r&&r(`[Subagent Turn ${S+1}]...`);let C=(await sr(p,w,E,R,"Fast")).text||"",M=on(C).trim();_=M,r&&r(`[Subagent Response]
1217
+ === END SYSTEM PROMPT ===`,k=[{role:"user",text:`Complete this task: ${e}`}],S=0,_="";for(;S<s;){if(Lt){if(n?.taskId&&typeof Qe<"u"){let F=Qe.find(W=>W.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 Qe<"u"){let F=Qe.find(W=>W.id===n.taskId);if(F&&F.status==="cancelled")throw r&&r("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}let E=k.map(F=>({role:F.role==="user"?"user":"model",parts:[{text:F.text}]}));r&&r(`[Subagent Turn ${S+1}]...`);let C=(await sr(p,w,E,R,"Fast")).text||"",M=rn(C).trim();_=M,r&&r(`[Subagent Response]
1218
1218
  ${M}
1219
- `),k.push({role:"agent",text:M});let v=rr(M);if(v.length===0)break;let L=v.filter(F=>F.toolName.toLowerCase()==="askmain"||F.toolName.toLowerCase()==="ask_main"),U=!1,j="";for(let F of v){if(It){if(n?.taskId&&typeof Qe<"u"){let O=Qe.find(B=>B.id===n.taskId);O&&(O.status="cancelled")}throw new Error("Subagent task was cancelled.")}if(n?.taskId&&typeof Qe<"u"){let O=Qe.find(B=>B.id===n.taskId);if(O&&O.status==="cancelled")throw new Error("Subagent task was cancelled.")}let W=F.toolName.toLowerCase();if(W==="askuser"&&(W="ask"),W==="askmain"||W==="ask_main"){if(U)continue;U=!0;let O="";if(L.length===1?O=D(L[0].args).question||L[0].args:O=L.map((B,J)=>{let Q=D(B.args);return`Q${J+1}: ${Q.question||B.args}`}).join(`
1219
+ `),k.push({role:"agent",text:M});let v=rr(M);if(v.length===0)break;let L=v.filter(F=>F.toolName.toLowerCase()==="askmain"||F.toolName.toLowerCase()==="ask_main"),U=!1,j="";for(let F of v){if(Lt){if(n?.taskId&&typeof Qe<"u"){let O=Qe.find(B=>B.id===n.taskId);O&&(O.status="cancelled")}throw new Error("Subagent task was cancelled.")}if(n?.taskId&&typeof Qe<"u"){let O=Qe.find(B=>B.id===n.taskId);if(O&&O.status==="cancelled")throw new Error("Subagent task was cancelled.")}let W=F.toolName.toLowerCase();if(W==="askuser"&&(W="ask"),W==="askmain"||W==="ask_main"){if(U)continue;U=!0;let O="";if(L.length===1?O=D(L[0].args).question||L[0].args:O=L.map((B,J)=>{let Q=D(B.args);return`Q${J+1}: ${Q.question||B.args}`}).join(`
1220
1220
  `),n.onAskMain){r&&r(`[Executing Tool] AskMain("${O}")...`);let B=await n.onAskMain(O);r&&r(`[Tool Result]
1221
1221
  Answer from Main Agent: ${B}
1222
1222
  `),j+=`[TOOL RESULT for AskMain]: Answer from Main Agent: ${B}
1223
1223
 
1224
- `,await Ot("toolSuccess")}else j+=`[TOOL RESULT for AskMain]: ERROR: Main agent communication channel not available.
1224
+ `,await Dt("toolSuccess")}else j+=`[TOOL RESULT for AskMain]: ERROR: Main agent communication channel not available.
1225
1225
 
1226
1226
  `;continue}if(!(o?o.some(O=>O.toLowerCase()===W):!0)){let O=`ERROR: Tool [${F.toolName}] is not in the allowed tools list for this subagent.`;r&&r(`[Blocked Tool Call] ${F.toolName} - not allowed
1227
1227
  `),j+=`${O}
@@ -1233,11 +1233,11 @@ Answer from Main Agent: ${B}
1233
1233
  ${O}
1234
1234
  `),j+=`[TOOL RESULT for ${F.toolName}]: ${O}
1235
1235
 
1236
- `,await Ot("toolSuccess"),W==="patchfile"||W==="update_file"||W==="updatefile"||W==="patch_file"){if(O){let B=O.split(`
1237
- `),J=0,Q=0,We=!1;for(let Ne of B){if(Ne.includes("[DIFF_START]")){We=!0;continue}if(Ne.includes("[DIFF_END]")){We=!1;continue}We&&(/^\+\d+/.test(Ne)?J++:/^\-\d+/.test(Ne)&&Q++)}(J>0||Q>0)&&(await zt("linesAdded",J),await zt("linesRemoved",Q))}}else if((W==="writefile"||W==="write_file")&&O){let B=O.match(/- Stats: \[(\d+) lines/),J=B?parseInt(B[1]):0,Q=0;if(O.includes("Old File contents:")){let We=!1;for(let Ne of O.split(`
1238
- `)){if(Ne.includes("Old File contents:")){We=!0;continue}We&&(Ne.trim()===""?We=!1:/^\d+ \|/.test(Ne)&&Q++)}}(J>0||Q>0)&&(await zt("linesAdded",J),await zt("linesRemoved",Q))}}catch(O){let B=`ERROR: Execution failed for [${F.toolName}]: ${O.message}`;r&&r(`[Tool Error] ${B}
1236
+ `,await Dt("toolSuccess"),W==="patchfile"||W==="update_file"||W==="updatefile"||W==="patch_file"){if(O){let B=O.split(`
1237
+ `),J=0,Q=0,We=!1;for(let Ne of B){if(Ne.includes("[DIFF_START]")){We=!0;continue}if(Ne.includes("[DIFF_END]")){We=!1;continue}We&&(/^\+\d+/.test(Ne)?J++:/^\-\d+/.test(Ne)&&Q++)}(J>0||Q>0)&&(await Vt("linesAdded",J),await Vt("linesRemoved",Q))}}else if((W==="writefile"||W==="write_file")&&O){let B=O.match(/- Stats: \[(\d+) lines/),J=B?parseInt(B[1]):0,Q=0;if(O.includes("Old File contents:")){let We=!1;for(let Ne of O.split(`
1238
+ `)){if(Ne.includes("Old File contents:")){We=!0;continue}We&&(Ne.trim()===""?We=!1:/^\d+ \|/.test(Ne)&&Q++)}}(J>0||Q>0)&&(await Vt("linesAdded",J),await Vt("linesRemoved",Q))}}catch(O){let B=`ERROR: Execution failed for [${F.toolName}]: ${O.message}`;r&&r(`[Tool Error] ${B}
1239
1239
  `),j+=`${B}
1240
1240
 
1241
- `,await Ot("toolFailure")}}let ee="";if(n?.taskId&&typeof Qe<"u"){let F=Qe.find(W=>W.id===n.taskId);if(F&&F.pendingSteerMessages&&F.pendingSteerMessages.length>0){let W=[...F.pendingSteerMessages];F.pendingSteerMessages=[];for(let ne of W)ee+=`
1241
+ `,await Dt("toolFailure")}}let ee="";if(n?.taskId&&typeof Qe<"u"){let F=Qe.find(W=>W.id===n.taskId);if(F&&F.pendingSteerMessages&&F.pendingSteerMessages.length>0){let W=[...F.pendingSteerMessages];F.pendingSteerMessages=[];for(let ne of W)ee+=`
1242
1242
 
1243
- [STEERING INSTRUCTION FROM MAIN AGENT]: ${ne}`,r&&r(`[Subagent Steered] ${ne}`)}}let X=(j.trim()+ee).trim();k.push({role:"user",text:X}),S++}return _};export{wn as a,Ma as b,Wf as c,jf as d,lc as e,va as f,Gf as g,hc as h,Hf as i,hs as j,tl as k,eg as l,tg as m,D as n,vd as o,gr as p,Vo as q,Id as r,Od as s,Iu as t,Ou as u,gt as v,fo as w,Yu as x,zl as y,Vu as z,Xu as A,Ju as B,Qu as C,Zu as D,po as E,Ac as F,Hp as G,qp as H,sg as I,Hs as J,rg as K,ld as L,Ay as M,cd as N,dd as O,wi as P,on as Q,fl as R,md as S,My as T,vy as U,ki as V,Iy as W,Oy as X,Sd as Y,Ly as Z,Dy as _,Py as $};
1243
+ [STEERING INSTRUCTION FROM MAIN AGENT]: ${ne}`,r&&r(`[Subagent Steered] ${ne}`)}}let X=(j.trim()+ee).trim();k.push({role:"user",text:X}),S++}return _};export{bn as a,Ma as b,Wf as c,jf as d,lc as e,va as f,Gf as g,hc as h,Hf as i,hs as j,tl as k,eg as l,tg as m,D as n,vd as o,gr as p,Vo as q,Id as r,Od as s,Iu as t,Ou as u,yt as v,fo as w,Yu as x,zl as y,Vu as z,Xu as A,Ju as B,Qu as C,Zu as D,po as E,Ac as F,Hp as G,qp as H,sg as I,Hs as J,rg as K,ld as L,Ay as M,cd as N,dd as O,wi as P,rn as Q,fl as R,md as S,My as T,vy as U,ki as V,Iy as W,Oy as X,Sd as Y,Ly as Z,Dy as _,Py as $};