fluxflow-cli 4.1.4 → 4.2.0
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.
- package/README.md +2 -1
- package/dist/chunks/{ai-M2MAGATC.js → ai-JV4YFO7W.js} +1 -1
- package/dist/chunks/{app-NQODWWNA.js → app-W2BOMBDT.js} +143 -143
- package/dist/chunks/{chunk-K4FITEVZ.js → chunk-3JHCQ2JD.js} +1 -1
- package/dist/chunks/{chunk-BZBAMZS4.js → chunk-6ENN7MJR.js} +1 -1
- package/dist/chunks/chunk-M7QN5C2K.js +1 -0
- package/dist/chunks/{chunk-CQ2U3S2O.js → chunk-RVCFBTIL.js} +244 -243
- package/dist/chunks/{screen_grid-IKEV7A6U.js → screen_grid-Y6GHBUFE.js} +1 -1
- package/dist/chunks/{secrets-D5HMTNJA.js → secrets-ITIOWL5R.js} +1 -1
- package/dist/chunks/{settings-XPFFYYYD.js → settings-REIFJELQ.js} +1 -1
- package/dist/cli.js +2 -2
- package/dist/model_config.json +62 -3
- package/dist/package.json +2 -2
- package/model_config.json +62 -3
- package/package.json +2 -2
- package/dist/chunks/chunk-ZESOEAQT.js +0 -1
|
@@ -1,39 +1,39 @@
|
|
|
1
|
-
import{b as Zo}from"./chunk-
|
|
1
|
+
import{b as Zo}from"./chunk-M7QN5C2K.js";import{c as rn,d as qs,g as et,h as Ft}from"./chunk-6ENN7MJR.js";import{a as Gs,b as _s,c as X,d as he}from"./chunk-SIINYZWE.js";import{c as An,d as fn,e as bo,f as Es,g as $s,h as Xo,i as Xt,j as Pt,k as Qt,l as vn,m as Wn,n as on,o as un,p as rs,q as Qo,r as jn,s as as}from"./chunk-I27MASHH.js";import{a as Ve,c as ko}from"./chunk-56EJGQU3.js";import{c as yr,d as wr,e as zs}from"./chunk-3JHCQ2JD.js";import ic from"dotenv";import{GoogleGenAI as Aa,ThinkingLevel as at,HarmBlockThreshold as Yn,HarmCategory as Vn}from"@google/genai";import{Ollama as rc}from"ollama";import{execSync as Ya}from"child_process";import{spawn as ei}from"child_process";var O=e=>{let n={};if(!e)return n;let t=0;for(;t<e.length;){for(;t<e.length&&/[\s,]/.test(e[t]);)t++;if(t>=e.length)break;let o=e.substring(t).match(/^(\w+)\s*=\s*/);if(!o){t++;continue}let s=o[1];t+=o[0].length;let i="";if(t<e.length&&(e[t]==='"'||e[t]==="'"||e[t]==="`")){let a=e[t];t++;let r=t,h=-1,d=t;for(;d<e.length;){let l=e.indexOf(a,d);if(l===-1)break;let u=0;for(let y=l-1;y>=0&&e[y]==="\\";y--)u++;if(u%2!==0){d=l+1;continue}let f=e.substring(l+1),p=f.trim(),g=p===""||/^,\s*\w+\s*=/.test(p)||p.startsWith(")")&&(p.length===1||/^\)\s*([,\]\s]|\[\[?tool:)/i.test(p));if(g&&f.startsWith(`
|
|
2
2
|
`)){let y=p.split(`
|
|
3
3
|
`)[0];if(!y.includes("=")&&!y.includes(")")){d=l+1;continue}}if(g){h=l;break}d=l+1}h!==-1?(i=e.substring(r,h),t=h+1):(i=e.substring(r),t=e.length);let c=s.toLowerCase().includes("path")||["dest","source","to","from"].includes(s.toLowerCase());i=i.replace(/\\(.)/g,(l,u)=>{switch(u){case"n":return`
|
|
4
|
-
`;case"r":return"\r";case"t":return" ";case"\\":return"\\";default:return u===a?a:u}})}else if(t<e.length&&e[t]==="["){let a=0,r=null,h=t,d=-1;for(let c=t;c<e.length;c++){let l=e[c];if(r&&l===r){let u=0;for(let f=c-1;f>=0&&e[f]==="\\";f--)u++;u%2===0&&(r=null)}else!r&&(l==='"'||l==="'"||l==="`")&&(r=l);if(!r&&(l==="["?a++:l==="]"&&a--,a===0)){d=c;break}}if(d!==-1){i=e.substring(h,d+1),t=d+1;try{let c=i.trim();c.startsWith("'")||c.includes("'")}catch{}}else i=e.substring(h),t=e.length}else{let a=e.substring(t),r=a.match(/,\s*\w+\s*=|(?:\s*\)\s*(?:$|\]\]))/);if(r){let h=r.index;i=a.substring(0,h).trim(),t+=h}else i=a.trim(),t=e.length}i==="true"?i=!0:i==="false"?i=!1:typeof i=="string"&&!isNaN(i)&&i.trim()!==""&&(i=Number(i)),typeof i=="string"&&(s.toLowerCase().includes("path")||["dest","source","to","from"].includes(s.toLowerCase()))&&(i=i.replace(/\x0C/g,"\\f").replace(/\x0D/g,"\\r").replace(/\x0B/g,"\\v").replace(/\x08/g,"\\b")),n[s]=i}return n};var So=null;try{let e=await import("node-pty");So=e.default||e}catch{}var
|
|
4
|
+
`;case"r":return"\r";case"t":return" ";case"\\":return"\\";default:return u===a?a:u}})}else if(t<e.length&&e[t]==="["){let a=0,r=null,h=t,d=-1;for(let c=t;c<e.length;c++){let l=e[c];if(r&&l===r){let u=0;for(let f=c-1;f>=0&&e[f]==="\\";f--)u++;u%2===0&&(r=null)}else!r&&(l==='"'||l==="'"||l==="`")&&(r=l);if(!r&&(l==="["?a++:l==="]"&&a--,a===0)){d=c;break}}if(d!==-1){i=e.substring(h,d+1),t=d+1;try{let c=i.trim();c.startsWith("'")||c.includes("'")}catch{}}else i=e.substring(h),t=e.length}else{let a=e.substring(t),r=a.match(/,\s*\w+\s*=|(?:\s*\)\s*(?:$|\]\]))/);if(r){let h=r.index;i=a.substring(0,h).trim(),t+=h}else i=a.trim(),t=e.length}i==="true"?i=!0:i==="false"?i=!1:typeof i=="string"&&!isNaN(i)&&i.trim()!==""&&(i=Number(i)),typeof i=="string"&&(s.toLowerCase().includes("path")||["dest","source","to","from"].includes(s.toLowerCase()))&&(i=i.replace(/\x0C/g,"\\f").replace(/\x0D/g,"\\r").replace(/\x0B/g,"\\v").replace(/\x08/g,"\\b")),n[s]=i}return n};var So=null;try{let e=await import("node-pty");So=e.default||e}catch{}var Uc=!!So,To=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),ti=e=>{if(!e)return"";let n=[[]],t=0,o=0,s=/\x1b\[([0-9;]*?)([a-zA-Z])/g,i=0,a,r=d=>{for(let c=0;c<d.length;c++){let l=d[c];if(l===`
|
|
5
5
|
`)for(t++,o=0;t>=n.length;)n.push([]);else if(l==="\r")o=0;else{for(;t>=n.length;)n.push([]);let u=n[t];for(;o>u.length;)u.push(" ");u[o]=l,o++}}};for(;(a=s.exec(e))!==null;){r(e.substring(i,a.index));let d=a[1],c=a[2],l=d?d.split(";").map(Number):[];if(c==="A"){let u=l[0]||1;t=Math.max(0,t-u)}else if(c==="B"){let u=l[0]||1;for(t=t+u;t>=n.length;)n.push([])}else if(c==="C"){let u=l[0]||1;o=o+u}else if(c==="D"){let u=l[0]||1;o=Math.max(0,o-u)}else if(c==="G"){let u=(l[0]||1)-1;o=Math.max(0,u)}else if(c==="H"||c==="f"){let u=(l[0]||1)-1,f=(l[1]||1)-1;for(t=Math.max(0,u),o=Math.max(0,f);t>=n.length;)n.push([])}else if(c==="K"){let u=l[0]||0;if(t<n.length){let f=n[t];if(u===0)f.length=o;else if(u===1)for(let p=0;p<o&&p<f.length;p++)f[p]=" ";else u===2&&(f.length=0)}}else if(c==="J"){let u=l[0]||0;(u===2||u===3)&&(n.length=0,n.push([]),t=0,o=0)}i=s.lastIndex}r(e.substring(i));let h=n.map(d=>d.join(""));for(;h.length>0&&h[h.length-1]==="";)h.pop();return h.join(`
|
|
6
|
-
`)},gt=null,Ks=!1,
|
|
6
|
+
`)},gt=null,Ks=!1,Wc=e=>{try{gt&&(Ks&&typeof gt.write=="function"?gt.write(e):gt.stdin&>.stdin.writable&>.stdin.write(e))}catch{}},jc=()=>{if(gt){try{Ks&&typeof gt.destroy=="function"?gt.destroy():typeof gt.kill=="function"&&(process.platform==="win32"?ei("taskkill",["/pid",gt.pid,"/f","/t"]):gt.kill("SIGKILL"))}catch{}gt=null,Ks=!1}},ni=(e,n=!1)=>{if(process.platform!=="win32")return e;let t=[],o="",s=null,i=!1;for(let c=0;c<e.length;c++){let l=e[c];if(i){o+=l,i=!1;continue}if(l==="\\"){if(e[c+1]===" "){o+=" ",c++;continue}o+=l,i=!0;continue}s?(l===s&&(s=null),o+=l):l==='"'||l==="'"?(s=l,o+=l):l===";"&&!o.includes("://")?(o.length>0&&(t.push(o),o=""),t.push(n?";":"&")):l==="&"&&!o.includes("://")?e[c+1]==="&"?(o.length>0&&(t.push(o),o=""),t.push("&&"),c++):(o.length>0&&(t.push(o),o=""),t.push("&")):l==="|"&&!o.includes("://")?(o.length>0&&(t.push(o),o=""),t.push("|")):/\s/.test(l)?o.length>0&&(t.push(o),o=""):o+=l}o.length>0&&t.push(o);let a=c=>!(!c.includes("/")||/^(https?|file|ftp):\/\//i.test(c)||c.startsWith("@")||c.startsWith("/")&&(c.match(/\//g)||[]).length===1||/\s\/|\/\s/.test(c)||/[\(\)\{\}\;\<\>\=\'\"]/.test(c)),r=[];for(let c=0;c<t.length;c++){let l=t[c];if(l==="mkdir"&&n&&Hn()){let u=[],f=c+1;for(;f<t.length;){let p=t[f];if([">",">>","<","&","&&","|","||",";"].includes(p))break;p!=="-p"&&p!=="--parents"&&p!=="-v"&&p!=="--verbose"&&u.push(p),f++}if(u.length>0){let p=u.map(g=>{let y=g.replace(/^['"]|['"]$/g,""),m=g;return a(y)&&(m=g.replace(/\//g,"\\")),m});r.push("New-Item","-ItemType","Directory","-Force","-Path",p.join(","))}else r.push("New-Item","-ItemType","Directory","-Force");c=f-1;continue}if(l==="rm"&&n&&Hn()){let u=[],f=!1,p=!1,g=c+1;for(;g<t.length;){let m=t[g];if([">",">>","<","&","&&","|","||",";"].includes(m))break;m==="-rf"||m==="-fr"?(f=!0,p=!0):m==="-r"||m==="-R"||m==="--recursive"?f=!0:m==="-f"||m==="--force"?p=!0:u.push(m),g++}let y=["Remove-Item"];if(f&&y.push("-Recurse"),p&&y.push("-Force"),u.length>0){let m=u.map(w=>{let b=w.replace(/^['"]|['"]$/g,""),k=w;return a(b)&&(k=w.replace(/\//g,"\\")),k});y.push("-Path",m.join(","))}r.push(...y),c=g-1;continue}if(l==="cp"&&n&&Hn()){let u=[],f=!1,p=!1,g=c+1;for(;g<t.length;){let m=t[g];if([">",">>","<","&","&&","|","||",";"].includes(m))break;m==="-r"||m==="-R"||m==="--recursive"?f=!0:m==="-f"||m==="--force"?p=!0:u.push(m),g++}let y=["Copy-Item"];if(f&&y.push("-Recurse"),p&&y.push("-Force"),u.length>0){let m=u.map(w=>{let b=w.replace(/^['"]|['"]$/g,""),k=w;return a(b)&&(k=w.replace(/\//g,"\\")),k});if(m.length>1){let w=m.pop();y.push("-Path",m.join(","),"-Destination",w)}else y.push("-Path",m[0])}r.push(...y),c=g-1;continue}if(l==="touch"&&n&&Hn()){let u=[],f=c+1;for(;f<t.length;){let p=t[f];if([">",">>","<","&","&&","|","||",";"].includes(p))break;u.push(p),f++}if(u.length>0){let g=`(${u.map(y=>{let m=y.replace(/^['"]|['"]$/g,""),w=y;return a(m)&&(w=y.replace(/\//g,"\\")),w}).join(", ")}) | ForEach-Object { if (Test-Path $_) { (Get-Item $_).LastWriteTime = [System.DateTime]::Now } else { $null | Out-File -FilePath $_ } }`;r.push(g)}c=f-1;continue}if(l==="|"&&t[c+1]==="tee"){t[c+2]==="-a"?(r.push(">>"),c+=2):(r.push(">"),c+=1);continue}if(l==="|"&&t[c+1]==="cat"&&t[c+2]===">"){r.push(">"),c+=2;continue}if(l==="|"){let u=t[c+1];if(u){let f=u.replace(/^['"]|['"]$/g,""),p=/\.(txt|md|json|log|csv|html|css|py|js|xml|yaml|yml|pdf|docx|pptx|xlsx)$/i.test(f);if(a(f)&&p){r.push(">");continue}}}r.push(l)}let h=!1,d=r.map(c=>{if(c==="echo")return h=!0,c;[">",">>","<","&","&&","|","||",";"].includes(c)&&(h=!1);let u=/^['"]|['"]$/.test(c),f=c;h&&u&&(f=c.replace(/^['"]|['"]$/g,""));let p=/^['"]|['"]$/.test(f),g=f.replace(/^['"]|['"]$/g,"");a(g)&&(f=f.replace(/\//g,"\\"));let y=f.replace(/^['"]|['"]$/g,"");return y.includes(" ")&&!p&&(f=`"${y}"`),f});if(n){let c="",l=0;for(let u=0;u<d.length;u++){let f=d[u];f==="&&"?(c+="; if ($?) {",l++):f===";"?(c+=" }".repeat(l)+";",l=0):(c&&!c.endsWith(" ")&&!c.endsWith("{")&&(c+=" "),c+=f)}return c+=" }".repeat(l),c}return d.join(" ")},si=async(e,n={})=>{let{command:t}=O(e),{onChunk:o}=n;if(!t)return'ERROR: Missing "command" argument for exec_command.';let s=process.platform==="win32",i=n.systemSettings||{},a={};return i.networkAccess===!1&&(a.HTTP_PROXY="http://127.0.0.1:9999",a.HTTPS_PROXY="http://127.0.0.1:9999",a.ALL_PROXY="socks5://127.0.0.1:9999",a.http_proxy="http://127.0.0.1:9999",a.https_proxy="http://127.0.0.1:9999",a.all_proxy="socks5://127.0.0.1:9999",a.NO_PROXY="localhost,127.0.0.1"),new Promise(r=>{let h=d=>{let c=d==="pwsh"||d==="powershell",l=ni(t,c),u;s?d==="pwsh"?u="C:\\Users\\User\\AppData\\Local\\Microsoft\\WindowsApps\\pwsh.exe":d==="powershell"?u="powershell.exe":u="cmd.exe":u=process.env.SHELL||"bash";let f=s?c?["-NoProfile","-Command",l]:["/c",l]:["-c",l];if(i.networkAccess===!1&&!s){let p=u,g=[...f];if(process.platform==="linux")u="unshare",f=["-n","-r",p,...g];else if(process.platform==="darwin"){let y=`(version 1)
|
|
7
7
|
(allow default)
|
|
8
8
|
(deny network-outbound)
|
|
9
9
|
(allow network-outbound (remote ip "localhost:*"))
|
|
10
10
|
(allow network-outbound (remote ip "127.0.0.1:*"))
|
|
11
|
-
`;u="sandbox-exec",f=["-p",y,p,...g]}}if(So)try{let p=So.spawn(u,f,{name:"xterm-256color",cols:n.cols||120,rows:n.rows||30,cwd:process.cwd(),env:{...process.env,CI:"false",TERM:"xterm-256color",FORCE_COLOR:"1",...a}});gt=p,Ks=!0;let g="",y=!1;return p.onData(m=>{if(!y){g+=m,o&&o(m);let w=
|
|
11
|
+
`;u="sandbox-exec",f=["-p",y,p,...g]}}if(So)try{let p=So.spawn(u,f,{name:"xterm-256color",cols:n.cols||120,rows:n.rows||30,cwd:process.cwd(),env:{...process.env,CI:"false",TERM:"xterm-256color",FORCE_COLOR:"1",...a}});gt=p,Ks=!0;let g="",y=!1;return p.onData(m=>{if(!y){g+=m,o&&o(m);let w=To(g);/(?:Network:\s+use\s+--host\s+to|Network:\s+Type\s+--host\s+to|Local:\s+http:\/\/localhost:\d+|ready in \d+\s*ms|Compiled successfully|Development server is running|Listening on:)/i.test(w)&&(y=!0,setTimeout(()=>r(`SUCCESS: Dev server started successfully in background.
|
|
12
12
|
|
|
13
|
-
${w}`),500))}}),p.onExit(({exitCode:m})=>{if(y)return;gt=null;let w=ti(g||""),
|
|
13
|
+
${w}`),500))}}),p.onExit(({exitCode:m})=>{if(y)return;gt=null;let w=ti(g||""),b=To(w).replace(/\n{3,}/g,`
|
|
14
14
|
|
|
15
15
|
`)||"Command executed with no output.";r(m!==0?`ERROR: Command [${t}] failed with exit code [${m}].
|
|
16
16
|
|
|
17
|
-
${
|
|
17
|
+
${b}`:`SUCCESS: Command [${t}] completed.
|
|
18
18
|
|
|
19
|
-
${
|
|
19
|
+
${b}`)}),!0}catch(p){return s&&(d==="pwsh"||d==="powershell")&&p.code==="ENOENT"?!1:(Ro(r,l,t,a,o,d,i),!0)}else return Ro(r,l,t,a,o,d,i),!0};s?h("pwsh")||h("powershell")||h("cmd"):h("bash")})},Ro=(e,n,t,o,s,i="powershell",a={})=>{let r=process.platform==="win32",h=i==="pwsh"||i==="powershell",d;r?i==="pwsh"?d="C:\\Users\\User\\AppData\\Local\\Microsoft\\WindowsApps\\pwsh.exe":i==="powershell"?d="powershell.exe":d="cmd.exe":d=process.env.SHELL||"bash";let c=r?h?["-NoProfile","-Command",n]:["/c",n]:["-c",n];if(a.networkAccess===!1&&!r){let g=d,y=[...c];if(process.platform==="linux")d="unshare",c=["-n","-r",g,...y];else if(process.platform==="darwin"){let m=`(version 1)
|
|
20
20
|
(allow default)
|
|
21
21
|
(deny network-outbound)
|
|
22
22
|
(allow network-outbound (remote ip "localhost:*"))
|
|
23
23
|
(allow network-outbound (remote ip "127.0.0.1:*"))
|
|
24
|
-
`;d="sandbox-exec",c=["-p",m,g,...y]}}let l=r?ei(d,c,{cwd:process.cwd(),env:{...process.env,...o}}):ei(d,c,{cwd:process.cwd(),env:{...process.env,CI:"false",TERM:"xterm-256color",FORCE_COLOR:"1",...o}});gt=l,Ks=!1,l.stdin&&l.stdin.on("error",()=>{gt=null});let u="",f="",p=!1;l.stdout.on("data",g=>{if(!p){let y=g.toString();u+=y,s&&s(y);let m=
|
|
24
|
+
`;d="sandbox-exec",c=["-p",m,g,...y]}}let l=r?ei(d,c,{cwd:process.cwd(),env:{...process.env,...o}}):ei(d,c,{cwd:process.cwd(),env:{...process.env,CI:"false",TERM:"xterm-256color",FORCE_COLOR:"1",...o}});gt=l,Ks=!1,l.stdin&&l.stdin.on("error",()=>{gt=null});let u="",f="",p=!1;l.stdout.on("data",g=>{if(!p){let y=g.toString();u+=y,s&&s(y);let m=To(u);/(?:Network:\s+use\s+--host\s+to|Network:\s+Type\s+--host\s+to|Local:\s+http:\/\/localhost:\d+|ready in \d+\s*ms|Compiled successfully|Development server is running|Listening on:)/i.test(m)&&(p=!0,setTimeout(()=>e(`SUCCESS: Dev server started successfully in background.
|
|
25
25
|
|
|
26
26
|
${m}`),500))}}),l.stderr.on("data",g=>{if(!p){let y=g.toString();f+=y,s&&s(y)}}),l.on("close",g=>{if(p)return;gt=null;let y=[],m=ti(u),w=ti(f);m&&y.push(`STDOUT:
|
|
27
27
|
${m}`),w&&y.push(`STDERR:
|
|
28
|
-
${w}`),g!==0&&y.push(`EXIT CODE: ${g}`);let
|
|
28
|
+
${w}`),g!==0&&y.push(`EXIT CODE: ${g}`);let b=y.join(`
|
|
29
29
|
|
|
30
|
-
`)||"Command executed with no output.",
|
|
30
|
+
`)||"Command executed with no output.",k=To(b).replace(/\n{3,}/g,`
|
|
31
31
|
|
|
32
32
|
`);e(g!==0?`ERROR: Command [${t}] failed with exit code [${g}].
|
|
33
33
|
|
|
34
|
-
${
|
|
34
|
+
${k}`:`SUCCESS: Command [${t}] completed.
|
|
35
35
|
|
|
36
|
-
${
|
|
36
|
+
${k}`)}),l.on("error",g=>{if(r&&g.code==="ENOENT"){if(i==="pwsh"){let m=ni(t,!0);return Ro(e,m,t,o,s,"powershell",a)}else if(i==="powershell"){let m=ni(t,!1);return Ro(e,m,t,o,s,"cmd",a)}}gt=null;let y=g instanceof Error?g.message:String(g);e(`ERROR: Failed to start command [${t}]: ${y}`)})};var Ys=null,Hn=()=>{if(process.platform!=="win32")return!1;if(Ys!==null)return Ys;try{Ya('powershell.exe -NoProfile -Command "exit"',{stdio:"ignore"}),Ys=!0}catch{Ys=!1}return Ys},oi=null,xr=(e,n,t,o,s=!1,i=!0)=>{oi===null&&(oi=s);let a=`- JSON escape literal escape sequences in tool arguments
|
|
37
37
|
- Same file, multiple edits? One PatchFile (\u226415 blocks) \u2190 Priority
|
|
38
38
|
- Tool denied? Ask for guidance \u2190 mandatory
|
|
39
39
|
- Need text or huge file? CodeSearch > Full Read
|
|
@@ -46,7 +46,7 @@ ${S}`)}),l.on("error",g=>{if(r&&g.code==="ENOENT"){if(i==="pwsh"){let m=ni(t,!0)
|
|
|
46
46
|
- [tool:functions.PatchFile(path="...", allowMultiple="bool, default: false", searchContent1="search string OR ^LINE:start..end$", newContent1="...", ...MAX15)]. Target minimal searchContent. Line Ranges must for large searchContent and escape sequences. ^...$ must for line ranges
|
|
47
47
|
- [tool:functions.WriteFile(path="...", content="...")]. Creates/Overwrites. File Exist? PatchFile > WriteFile
|
|
48
48
|
- [tool:functions.CodeSearch(keyword="...", path="dir/file/glob/regex, inclusion/exclusion ;-separated", fuzzy="bool false", regex="bool auto")]. Find definitions, logic, relevant code, standard junk auto-excluded
|
|
49
|
-
- [tool:functions.Run(command="...")]. Runs ${n==="Windows"?
|
|
49
|
+
- [tool:functions.Run(command="...")]. Runs ${n==="Windows"?Hn()?"powershell":"windows CMD":"bash"} command. Destructive/Irreversible ops \u2192 Ask user
|
|
50
50
|
- [tool:functions.Goal(method="create/append/get", tasks=[string array], markDone=[task array])]. If long multi-task: create Goals before starting. \`get + markDone\` to mark complete. Update every turn when created
|
|
51
51
|
${oi?'\n**Emergency Tools**\nInfo: `initial` = current task prompt. Revert `id` = turn before disaster (eg. disaster: `turn_3` \u2192 revert: `turn_2`). Reason explicitly\n- [tool:functions.EmergencyRollback(method="getCheckpoint/forceRevert", id="...")]. Rollback workspace in this agent loop. ONLY for catastrophic corruption. Before ending, verify no catastrophe. `id` omitted for `getCheckpoint`\n':""}${i?`
|
|
52
52
|
**Sub Agent Tools**
|
|
@@ -65,7 +65,7 @@ Invocations:
|
|
|
65
65
|
- [tool:functions.Drag(fromGridId="integer", toGridId="integer")]. Drag mouse from start grid number to target grid number
|
|
66
66
|
- [tool:functions.Scroll(direction="up/down", gridId="mouse hover area")]. Scroll viewport vertically
|
|
67
67
|
- [tool:functions.KeyboardTyping(text="string", autoPressEnter="bool")]. Type text string into currently active input. JSON escape literal escape sequences
|
|
68
|
-
- [tool:functions.KeyPress(key="key or ;-separated combination, eg: enter, backspace, clearInput, ctrl;c, alt;tab, f5, f11, alt;f4")]. Press key, shortcut, function key (f1-f12), or clear active input field.
|
|
68
|
+
- [tool:functions.KeyPress(key="key or ;-separated combination, eg: enter, back, backspace, clearInput, ctrl;c, alt;tab, f5, f11, alt;f4")]. Press key, shortcut, function key (f1-f12), or clear active input field.
|
|
69
69
|
- [tool:functions.RecaptureScreen()]. Request fresh gridded screenshot`;return`
|
|
70
70
|
-- TOOLS --
|
|
71
71
|
To use tools, must output exactly '[tool:functions.ToolName(arg1="value1")]' structured string in chat response \u2190 no exception
|
|
@@ -80,7 +80,7 @@ ${e==="Flux"||e.toLowerCase()==="fluxcu"?`${a}`:""}
|
|
|
80
80
|
- [tool:functions.WebScrape(url="...")]. Proactive use for specific webpage/docs/api
|
|
81
81
|
|
|
82
82
|
${e==="ICU"?`${d}`:e==="FluxCU"?`${r}
|
|
83
|
-
${d}`:e==="Flux"?`${r}`:`${h}`}`.trim()};var
|
|
83
|
+
${d}`:e==="Flux"?`${r}`:`${h}`}`.trim()};var br=(e=!0,n=!0)=>`
|
|
84
84
|
To use tools, must output exactly '[tool:functions.ToolName(arg1="value1")]' structured string in chat response \u2190 no exception
|
|
85
85
|
|
|
86
86
|
-- Chat Management Tools --
|
|
@@ -108,7 +108,7 @@ Usage Rules:
|
|
|
108
108
|
- Chat title is mandatory
|
|
109
109
|
- Temporary memory is mandatory
|
|
110
110
|
- When called user memory, still use Temporary Memory
|
|
111
|
-
- Must not ignore any tool calls in given context of chat between user & agent`:""}`.trim();var
|
|
111
|
+
- Must not ignore any tool calls in given context of chat between user & agent`:""}`.trim();var Eo={xHigh:`Effort: High
|
|
112
112
|
Challenge assumptions, verify before concluding, prefer the simplest correct solution, assess architecture, scalability & trade-offs, verify dependencies, regressions, failure modes & modular design, plan: files, modules, interfaces & tests
|
|
113
113
|
Continuous analysis, verify from first principles, seek failure paths, verify imports, tool results & system stability; avoid syntax errors
|
|
114
114
|
MANDATORY: Full technical verification`,High:`Effort: High
|
|
@@ -121,12 +121,12 @@ MANDATORY: Brief verification for technical tasks/greetings`,Minimal:`Effort: Lo
|
|
|
121
121
|
Quick, focused thinking, intent & complexity, required tools/files/actions, before acting
|
|
122
122
|
Brief thoughts, think only enough to avoid mistakes, verify imports, tool results & system stability; avoid syntax errors`,Off:`Effort: Lowest
|
|
123
123
|
No thinking. Immediate response
|
|
124
|
-
Verify imports, tool results & system stability; avoid syntax errors`};import
|
|
125
|
-
`):Vs=""}catch(t){Vs="",
|
|
124
|
+
Verify imports, tool results & system stability; avoid syntax errors`};import Sr from"fs";import Ja from"screenshot-desktop";var Tr=!1;(async()=>{try{let e=await Ft();if(Number(e?.display)===1){let n=await Ja.listDisplays();n&&n.length>1&&(Tr=!0)}}catch{}})();var ii=null,kr=null,Vs=null,id=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",Xa=process.env.NO_DEV||!1,Qa=(e,n)=>{if(!n)return"";if(e!==kr||Vs===null){kr=e;try{let t=X(Pt,[]);Array.isArray(t)&&t.length>0?Vs=t.map(o=>`- ${o.memory}`).join(`
|
|
125
|
+
`):Vs=""}catch(t){Vs="",Sr.appendFileSync(`${fn}/memory/error.txt`,`${t.message}
|
|
126
126
|
-------------------------------------------------
|
|
127
127
|
|
|
128
|
-
`)}}return Vs},
|
|
129
|
-
${e}`:"";return s?`${s}`:""},
|
|
128
|
+
`)}}return Vs},Rr=(e="",n="",t=!0,o=!1)=>{if(typeof n=="boolean"&&(o=t,t=n,n=""),!t)return"";let s=e?.length>0&&!o?`-- Recent context from other chats (Priority: Low, Focus: Chat Context > Recent) --
|
|
129
|
+
${e}`:"";return s?`${s}`:""},Er=(e,n,t,o,s=!0,i=!1,a="Google",r=!1,h,d)=>{let c=!1;process.env.forcedReasoning&&process.env.NVIDIA_BASE_URL&&a.toUpperCase()==="NVIDIA"&&(c=!0);let l="";if(!h&&a==="Google"){let E=n;n==="Fast"&&(E="Off"),n==="Low"&&(E="Minimal"),n==="Standard"&&(E="Medium"),(n==="xHigh"||n==="Max")&&(E="xHigh"),l=Eo[E]||Eo.Medium}if(h||a!=="Google"){let E={Fast:"Lowest",Low:"Low",Medium:"Medium",Standard:"Medium",High:"High",xHigh:"High",Max:"High"};l=Eo.xHigh,l=l.replace("Effort: High",`Effort: ${E[n]}`).replace(`
|
|
130
130
|
MANDATORY: Full technical verification`,""),n==="Fast"?l=`Effort: Lowest
|
|
131
131
|
No thinking. Immediate response
|
|
132
132
|
Verify imports, tool results & system stability; avoid syntax errors`:n==="Low"&&(l=`Effort: Low
|
|
@@ -137,17 +137,17 @@ Brief thoughts, think only enough to avoid mistakes, verify imports, tool result
|
|
|
137
137
|
${f.length?"":`
|
|
138
138
|
`}`:"",g=e.name&&e.name?.length>0?`User Name: ${e.name}
|
|
139
139
|
${p.length||f.length?"":`
|
|
140
|
-
`}`:"",y=process.cwd(),m=
|
|
140
|
+
`}`:"",y=process.cwd(),m=Qa(d,s),w=m?.length>0?`--- Saved Memories ---
|
|
141
141
|
${m}
|
|
142
142
|
|
|
143
|
-
`:"",
|
|
143
|
+
`:"",b=(()=>{let E=process.cwd().toLowerCase();if(process.platform==="win32"){let x=process.env.SystemRoot?.toLowerCase()||"c:\\windows",T=process.env.ProgramFiles?.toLowerCase()||"c:\\program files",$=process.env["ProgramFiles(x86)"]?.toLowerCase()||"c:\\program files (x86)";return E.startsWith(x)||E.startsWith(T)||E.startsWith($)}else return E==="/"||["/bin","/sbin","/etc","/usr","/var","/root"].some(T=>E.startsWith(T))})(),k=[{name:"Fluxflow.md",desc:"HIGH PRIORITY"},{name:"README.md",desc:"Goals"},{name:"Agent.md",desc:"Standards"},{name:"Skills.md",desc:"Workflows"},{name:"design.md",desc:"UI/UX"},{name:"architecture.md",desc:"System Structure"}];if(i||ii===null){let E=k.filter(x=>Sr.existsSync(x.name));ii=t==="Flux"&&E.length>0?`
|
|
144
144
|
-- PROJECT CONTEXT --
|
|
145
|
-
${E.map(
|
|
145
|
+
${E.map(x=>`- ${x.name}: ${x.desc}`).join(`
|
|
146
146
|
`)}
|
|
147
147
|
Check these first; These Files > Training Data. Safety rules apply
|
|
148
148
|
`:""}let R=ii;return`=== SYSTEM PROMPT ===
|
|
149
|
-
Identity: Flux Flow. Sassy, Friendly, CLI Agent${
|
|
150
|
-
${t==="Flux"?"Stepwise Execution, Run Automated Tests. Task Completion":t==="Flow"?"Concise, Humorous, Sarcastic":t==="ICU"?"Computer Use Capabilities. Screenshot as ground truth, analyze grid ids overlapping/close to target, keyboard shortcuts if efficient":"Computer Use & Workspace Capabilities. Screenshot (ground truth), analyze grid ids overlapping/close to target, keyboard shortcuts if efficient. Workspace Tools if faster. Focus on Productivity"}${
|
|
149
|
+
Identity: Flux Flow. Sassy, Friendly, CLI Agent${Xa?"":" by Kushal Roy Chowdhury"}
|
|
150
|
+
${t==="Flux"?"Stepwise Execution, Run Automated Tests. Task Completion":t==="Flow"?"Concise, Humorous, Sarcastic":t==="ICU"?"Computer Use Capabilities. Screenshot as ground truth, analyze grid ids overlapping/close to target, keyboard shortcuts if efficient":"Computer Use & Workspace Capabilities. Screenshot (ground truth), analyze grid ids overlapping/close to target, keyboard shortcuts if efficient. Workspace Tools if faster. Focus on Productivity"}${Tr&&t.toLowerCase().includes("cu")?`
|
|
151
151
|
**Running on secondary screen. Opened app not visible in screenshot? Might be opened on primary. Use 'Ask' immediately with NO options and tell user to move app window to secondary**`:""}
|
|
152
152
|
|
|
153
153
|
- OS: ${u}
|
|
@@ -161,7 +161,7 @@ ${c||n!=="Fast"&&(a==="Mistral"&&!h||n!=="xHigh"&&!h)?`critical thinking policy
|
|
|
161
161
|
- Use <think>...</think> for reasoning before responding any queries
|
|
162
162
|
`:""}`:`${l}
|
|
163
163
|
`}
|
|
164
|
-
${
|
|
164
|
+
${xr(t,u,a.toLowerCase()==="deepseek"?!1:r,a,o?.advanceRollback,o?.subAgents!==!1)}
|
|
165
165
|
${R}${s?`
|
|
166
166
|
-- MEMORY RULES --
|
|
167
167
|
- Subtly Personalize with relevent contextual memories. Auto Saves
|
|
@@ -178,7 +178,7 @@ ${t==="Flux"?`-- SECURITY POLICIES --
|
|
|
178
178
|
- use kaomojis heavily`:""}
|
|
179
179
|
=== END SYSTEM PROMPT ===
|
|
180
180
|
|
|
181
|
-
${g}${p}${f}${w}`.trim()}
|
|
181
|
+
${g}${p}${f}${w}`.trim()},$r=(e="",n=!0,t=!0)=>`=== SYSTEM PROMPT (strict headless logic worker: zero user-facing text policy, strictly follow) ===
|
|
182
182
|
identity: silent background system process, have no mouth, only output is valid tool calls
|
|
183
183
|
[critical rules]
|
|
184
184
|
- output exactly '[tool:functions.ToolName(args)]' calls. no extra words outside
|
|
@@ -195,16 +195,16 @@ identity: silent background system process, have no mouth, only output is valid
|
|
|
195
195
|
YOUR JOB: Analyze the 'User prompt' and 'Agent Raws' to extract facts for long-term memory or handle system tasks
|
|
196
196
|
${n?"If user tell something that is important (like, hobbies, preferences, facts about user, hates, likes, etc) to know user better over time, use user memory tools":""}
|
|
197
197
|
|
|
198
|
-
${
|
|
198
|
+
${br(n,t)}
|
|
199
199
|
=== END SYSTEM PROMPT ===${e?`
|
|
200
200
|
|
|
201
201
|
-- current saved user memories --
|
|
202
|
-
${e}`:""}`.trim();import
|
|
203
|
-
`),o=[],s=null,i=/^\s*(?:DEBUG|ERROR|SEARCH|PUPPETEER)\b/i;for(let l of t)i.test(l)?(s&&o.push(s),s={header:l,body:[]}):s?s.body.push(l):o.push({header:l,body:[]});s&&o.push(s);let a=10080*60*1e3,r=Date.now(),h=[],d=/(\d{1,4}[-\/.]\d{1,4}[-\/.]\d{1,4}(?:,\s*|\s+)?(?:\d{1,2}:\d{2}:\d{2}(?:\s*[aApP][mM])?)?)/;for(let l of o){if(i.test(l.header)){let p=l.header.match(d);if(p){let g=
|
|
202
|
+
${e}`:""}`.trim();import _t from"fs-extra";import $o from"path";import{nanoid as tl}from"nanoid";import ft from"fs-extra";import an from"path";ft.ensureDirSync(Wn);var hn=null;async function Za(e,n){try{if(e.type==="create")await ft.pathExists(e.filePath)&&(await ft.chmod(e.filePath,438).catch(()=>{}),await ft.remove(e.filePath));else if(e.type==="update"){if(!e.backupFile)return;let t=an.join(Wn,n.chatId,e.backupFile);if(await ft.pathExists(t)){let o=X(t,null);if(!o||!o.data)throw new Error(`Backup container corrupt or empty for ${an.basename(e.filePath)}`);let s=_s(o.data);await ft.pathExists(e.filePath)&&await ft.chmod(e.filePath,438).catch(()=>{}),await ft.writeFile(e.filePath,s,"utf8")}}}catch(t){throw new Error(`Restoration failed for ${an.basename(e.filePath)}: ${t.message}`)}}async function el(e,n,t=7){let o=0;for(;o<t;)try{return await Za(e,n),!0}catch{if(o++,o>=t)return!1;let i=Math.min(100*Math.pow(2,o-1),5e3);await new Promise(a=>setTimeout(a,i))}return!1}var ri=null,ut={async startTransaction(e,n){ri=e,hn={id:`tx_prompt_${Date.now()}`,chatId:e,timestamp:new Date().toISOString(),prompt:n.trim(),changes:[],reverted:!1},he(rs,hn)},async recordFileChange(e,n=null){try{if(!hn){if(ri){let a=X(on,[]),r=[...a].reverse().find(h=>h.chatId===ri);if(r){if(r.changes.some(u=>u.filePath===e))return;let c=await ft.pathExists(e)||n?"update":"create",l=null;if(c==="update"){let u=an.basename(e);l=`${r.id}_${u}.bak`;let f=an.join(Wn,r.chatId);await ft.ensureDir(f);let p=an.join(f,l),g=n!==null?n:await ft.readFile(e,"utf8").catch(()=>null);g!==null?he(p,{data:Gs(g)}):(c="create",l=null)}r.changes.push({filePath:e,type:c,backupFile:l}),he(on,a)}}return}if(hn.changes.some(a=>a.filePath===e))return;let s=await ft.pathExists(e)||n?"update":"create",i=null;if(s==="update"){let a=an.basename(e);i=`${hn.id}_${a}.bak`;let r=an.join(Wn,hn.chatId);await ft.ensureDir(r);let h=an.join(r,i),d=n!==null?n:await ft.readFile(e,"utf8").catch(()=>null);d!==null?he(h,{data:Gs(d)}):(s="create",i=null)}hn.changes.push({filePath:e,type:s,backupFile:i}),he(rs,hn)}catch{}},async commitTransaction(){if(hn)try{let e=X(on,[]);if(e.push(hn),e.length>512e3){let n=e.shift();if(n.changes)for(let t of n.changes)t.backupFile&&await ft.remove(an.join(Wn,n.chatId,t.backupFile)).catch(()=>{})}he(on,e),await ft.remove(rs).catch(()=>{})}catch{}finally{hn=null}},async recoverCrashedTransaction(){try{if(await ft.pathExists(rs)){let e=X(rs,null);if(e?.changes?.length>0){let n=X(on,[]);n.some(t=>t.id===e.id)||(n.push(e),he(on,n))}await ft.remove(rs).catch(()=>{})}}catch{}},async rollbackToBefore(e){let n=X(on,null);if(!n)throw new Error("No transaction ledger found.");let t=n.findIndex(a=>a.id===e);if(t===-1)throw new Error(`Transaction [${e}] not found.`);let o=n[t].chatId,s=n[t].prompt,i=n.slice(t).filter(a=>a.chatId===o&&!a.reverted).reverse();for(let a of i){for(let r of[...a.changes].reverse())await el(r,a);for(let r of a.changes)if(r.backupFile){let h=an.join(Wn,a.chatId,r.backupFile);await ft.remove(h).catch(()=>{})}n=n.filter(r=>r.id!==a.id),he(on,n)}return{success:!0,chatId:o,targetPrompt:s}},async getChatHistory(e){try{return X(on,[]).filter(t=>t.chatId===e&&!t.reverted)}catch{return[]}},async deleteChatBackups(e){try{await ft.remove(an.join(Wn,e));let n=X(on,[]),t=n.filter(o=>o.chatId!==e);n.length!==t.length&&he(on,t)}catch{}}};var _r=Promise.resolve(),_o=e=>{let n=_r.then(async()=>{try{return await e()}catch(t){throw console.error("Lock Operation Failed:",t),t}});return _r=n.catch(()=>{}),n},ls=async()=>{await _t.ensureDir($s);let e={};if(await _t.pathExists(Es))try{e=X(Es,{})}catch{e={}}for(let n in e){let t=$o.join($s,`${n}.json`);Object.defineProperty(e[n],"messages",{get:()=>{if(_t.existsSync(t))try{return X(t,[])}catch{return[]}return[]},set:o=>{try{he(t,o)}catch{}},enumerable:!1,configurable:!0})}return e},xd=async(e,n,t)=>_o(async()=>{await _t.ensureDir($s);let o=await ls(),s=o[e],i=(t||[]).filter(y=>!y.isUpdateNotification&&(!y.isMeta||y.text&&y.text.includes("Request Cancelled")));try{(await Ft()).systemSettings?.preserveThinking===!1&&(i=i.filter(m=>m.role!=="think"))}catch{}let a=y=>{if(!y)return;let m=typeof y=="string"?y:y.text||y.content||"";if(!m||typeof m!="string")return;let w=m.replace(/\s*\n+\s*\[Prompted on:.*?\]/g,"").replace(/\[\/?(?:STEERING HINT|QUESTION)(?::\s*\w+)?\]/gi,"").trim();if(!w)return;let b=w.split(/\s+/),k;return b.length>7?k=b.slice(0,7).join(" ")+"...":w.length>45?k=w.substring(0,45).trimEnd()+"...":k=w,k},r,h=i.filter(y=>y.role==="user"),d=h[0],c=h[h.length-1],l=a(c),u=a(d);s&&s.prompt?Math.random()<.5&&l?r=l:r=s.prompt:r=u||l;let f=n||(s?s.name:`Session ${e.slice(-6)}`),p=$o.join($s,`${e}.json`);he(p,i),o[e]={name:f,prompt:r||void 0,updatedAt:Date.now()};let g={};for(let y in o)g[y]={name:o[y].name,prompt:o[y].prompt||void 0,updatedAt:o[y].updatedAt};he(Es,g)}),Cr=async(e,n)=>_o(async()=>{let t=await ls();t[e]?(t[e].name=n,t[e].updatedAt=Date.now()):t[e]={name:n,updatedAt:Date.now()};let o={};for(let s in t)o[s]={name:t[s].name,prompt:t[s].prompt||void 0,updatedAt:t[s].updatedAt};he(Es,o)}),nl=async e=>_o(async()=>{let n=await ls();delete n[e];let t={};for(let a in n)t[a]={name:n[a].name,prompt:n[a].prompt||void 0,updatedAt:n[a].updatedAt};if(he(Es,t),await _t.pathExists(jn))try{let a=X(jn,[]);if(Array.isArray(a)){let r=a.filter(h=>Object.keys(h)[0]!==String(e));he(jn,r)}}catch{}let o=X(Qt,{});o[e]&&(delete o[e],he(Qt,o));let s=X(vn,{});s[e]&&(delete s[e],he(vn,s)),await ut.deleteChatBackups(e);let i=$o.join($s,`${e}.json`);if(await _t.pathExists(i))try{await _t.remove(i)}catch{}return n}),bd=()=>`flow-${tl(6)}`,kd=async e=>{if(!e||e==="Never")return;let n=parseInt(e);if(isNaN(n))return;let t=await ls(),o=Date.now(),s=n*24*60*60*1e3,i=0;for(let a in t){let r=t[a];r.updatedAt&&o-r.updatedAt>s&&(await nl(a),i++)}return i},sl=e=>{let n=e.replace(/[\[\]]/g,"").trim(),t=new Date(n);if(!isNaN(t.getTime()))return t.getTime();let o=n.split(/,\s*|\s+/);if(o.length===0)return null;let s=o[0],i=o[1]||"",a=o[2]||"",r=s.split(/[-\/.]/).map(Number);if(r.length!==3)return null;let h="en";try{h=Intl.DateTimeFormat().resolvedOptions().locale||"en"}catch{}let d=!/^en[-_]?us$|^en$/.test(h?.toLowerCase()),c,l,u;if(r[0]>1e3)c=r[0],l=r[1],u=r[2];else if(r[2]>1e3)c=r[2],r[0]>12?(u=r[0],l=r[1]):r[1]>12?(u=r[1],l=r[0]):d?(u=r[0],l=r[1]):(l=r[0],u=r[1]);else return null;if(l<1||l>12||u<1||u>31)return null;let f=0,p=0,g=0;if(i){let m=i.split(":").map(Number);f=m[0]||0,p=m[1]||0,g=m[2]||0,a.toLowerCase()==="pm"&&f<12?f+=12:a.toLowerCase()==="am"&&f===12&&(f=0)}let y=new Date(c,l-1,u,f,p,g);return isNaN(y.getTime())?null:y.getTime()},ol=async e=>{try{if(!await _t.pathExists(e))return;let n=await _t.readFile(e,"utf8");if(!n.trim())return;let t=n.split(`
|
|
203
|
+
`),o=[],s=null,i=/^\s*(?:DEBUG|ERROR|SEARCH|PUPPETEER)\b/i;for(let l of t)i.test(l)?(s&&o.push(s),s={header:l,body:[]}):s?s.body.push(l):o.push({header:l,body:[]});s&&o.push(s);let a=10080*60*1e3,r=Date.now(),h=[],d=/(\d{1,4}[-\/.]\d{1,4}[-\/.]\d{1,4}(?:,\s*|\s+)?(?:\d{1,2}:\d{2}:\d{2}(?:\s*[aApP][mM])?)?)/;for(let l of o){if(i.test(l.header)){let p=l.header.match(d);if(p){let g=sl(p[1]);if(g&&r-g>a)continue}}let f=l.header+(l.body.length>0?`
|
|
204
204
|
`+l.body.join(`
|
|
205
205
|
`):"");h.push(f)}let c=h.join(`
|
|
206
|
-
`).trim();c?await
|
|
207
|
-
`,"utf8"):await Ct.writeFile(e,"","utf8")}catch{}},Sd=async e=>{try{if(!await Ct.pathExists(e))return;let n=async t=>{let o=await Ct.readdir(t);for(let s of o){let i=Eo.join(t,s);(await Ct.stat(i)).isDirectory()?(await n(i),(await Ct.readdir(i)).length===0&&await Ct.remove(i)):s.endsWith(".log")&&await sl(i)}};await n(e)}catch{}},Cr=(e,n=4)=>{if(e.length<=1)return e;let t=e[0],o=e.slice(1),s=n*2,i=o.slice(s);return[t,...i]};var kd=async(e,n,t)=>$o(async()=>{let o=X(Wn,[]);Array.isArray(o)||(o=[]);let s={total:n,context:t},i=o.findIndex(a=>Object.keys(a)[0]===String(e));i!==-1?o[i]={[String(e)]:s}:o.push({[String(e)]:s}),he(Wn,o)}),Td=async e=>{try{if(!await Ct.pathExists(Wn))return{total:0,context:0};let n=X(Wn,[]);if(!Array.isArray(n))return{total:0,context:0};let t=n.find(o=>Object.keys(o)[0]===String(e));return t?t[String(e)]:{total:0,context:0}}catch{return{total:0,context:0}}};import yt from"fs-extra";import _r from"path";var ol=()=>Math.random().toString(36).substring(2)+Date.now().toString(36),se=null,Hn=null,Mr=0,_s=!1,In={agent:0,background:0,search:0,toolSuccess:0,toolFailure:0,toolDenied:0,duration:0,tokens:0,cachedTokens:0,candidateTokens:0,linesAdded:0,linesRemoved:0,imageCalls:[]},Ms=(e,n)=>{if(!e)return{};let t=Object.keys(e),o=new Date(new Date(n).getTime()-720*60*60*1e3),s={};for(let i of t)new Date(i)>=o&&(s[i]=e[i]);return s},Co=async()=>{let e=new Date().toISOString().split("T")[0];try{!await yt.exists(Jt)&&await yt.exists(Xo)&&(await yt.ensureDir(_r.dirname(Jt)),await yt.move(Xo,Jt))}catch{}let n=Jt+".tmp",t=null;try{if(await yt.exists(n)){let s=(await yt.readFile(n,"utf8")).trim(),i=null;if(s.startsWith("{")||s.startsWith("[")?i=JSON.parse(s):i=JSON.parse(Cs(s)),i&&i.date&&i.stats){t=i;try{await yt.rename(n,Jt)}catch{}}else try{await yt.remove(n)}catch{}}}catch{try{await yt.remove(n)}catch{}}if(!t)try{if(await yt.exists(Jt)){let s=(await yt.readFile(Jt,"utf8")).trim();s.startsWith("{")||s.startsWith("[")?t=JSON.parse(s):t=JSON.parse(Cs(s))}}catch{}let o=t;if(o){let s=o.stats||{...In},i={...In,...s};Array.isArray(i.imageCalls)||(i.imageCalls=[]);let a=o.history||{},r=Ms(a,e);if(Object.keys(a).length!==Object.keys(r).length&&(_s=!0),o.date===e)return{...o,stats:i,history:r};{let h=o.date,d=i,c={...r};return h&&(c[h]=d),{date:e,stats:{...In},history:Ms(c,e)}}}return{date:e,stats:{...In},history:{}}},ai=async()=>{if(!(!_s||!se))try{await yt.ensureDir(_r.dirname(Jt));let e=null;try{if(await yt.exists(Jt)){let s=(await yt.readFile(Jt,"utf8")).trim();s.startsWith("{")||s.startsWith("[")?e=JSON.parse(s):e=JSON.parse(Cs(s))}}catch{}if(e&&e.date===se.date&&e.stats){for(let s in se.stats)if(e.stats[s]!==void 0){if(Array.isArray(se.stats[s])){let i=Array.isArray(e.stats[s])?e.stats[s]:[],a=se.stats[s],r=new Map;for(let h of[...i,...a])h&&h.timestamp&&r.set(h.timestamp,h);se.stats[s]=Array.from(r.values())}else if(typeof se.stats[s]=="number")se.stats[s]=Math.max(se.stats[s],Number(e.stats[s])||0);else if(se.stats[s]&&typeof se.stats[s]=="object"){let i=e.stats[s]||{},a=se.stats[s];for(let r in i)if(typeof i[r]=="number")a[r]=Math.max(a[r]||0,i[r]);else if(i[r]&&typeof i[r]=="object"){a[r]||(a[r]={});for(let h in i[r])if(typeof i[r][h]=="number")a[r][h]=Math.max(a[r][h]||0,i[r][h]);else if(i[r][h]&&typeof i[r][h]=="object"){a[r][h]||(a[r][h]={});for(let d in i[r][h])a[r][h][d]=Math.max(a[r][h][d]||0,i[r][h][d])}}}}}if(e&&e.history){let s={...se.history||{}};for(let i in e.history)if(s[i])for(let a in s[i])if(a==="imageCalls"){let r=Array.isArray(e.history[i].imageCalls)?e.history[i].imageCalls:[],h=Array.isArray(s[i].imageCalls)?s[i].imageCalls:[],d=new Map;for(let c of[...r,...h])c&&c.timestamp&&d.set(c.timestamp,c);s[i].imageCalls=Array.from(d.values())}else typeof s[i][a]=="number"&&(s[i][a]=Math.max(s[i][a],Number(e.history[i][a])||0));else s[i]=e.history[i];se.history=Ms(s,se.date||today)}else if(se&&se.history){let s=new Date().toISOString().split("T")[0];se.history=Ms(se.history,s)}se.saveId=ol();let n=Jt+".tmp",t=Gs(JSON.stringify(se,null,2));await yt.writeFile(n,t,"utf8");let o=await yt.open(n,"r+");await yt.fsync(o),await yt.close(o),await yt.rename(n,Jt),_s=!1,Mr=Date.now()}catch{}},_o=()=>{if(_s=!0,Hn)return;let e=Date.now(),n=Math.max(0,1500-(e-Mr));Hn=setTimeout(async()=>{await ai(),Hn=null},n),Hn.unref&&Hn.unref()},Ad=async()=>{se=await Co(),_s&&_o()},vd=async()=>{Hn&&(clearTimeout(Hn),Hn=null),await ai()},Tn=async()=>{let e=new Date().toISOString().split("T")[0];if(!se)se=await Co();else if(se.date!==e){let n=se.date,t=se.stats,o=se.history||{};t&&(o[n]=t),se={date:e,stats:{...In},history:Ms(o,e)},_s=!0,await ai()}return se&&se.stats&&!Array.isArray(se.stats.imageCalls)&&(se.stats.imageCalls=[]),se.stats},il=async()=>{let e=new Date().toISOString().split("T")[0];se||(se=await Co()),se.date!==e&&await Tn();let n=se.history||{},t=Ms(n,e);se.history=t;let o=se.stats||{...In},s={...In};s.imageCalls=[],s.models={};let i=(a,r)=>{for(let h in a)if(h==="imageCalls")a.imageCalls=[...a.imageCalls||[],...r.imageCalls||[]];else if(h==="models"){let d=r.models||{};for(let c in d){a.models[c]||(a.models[c]={});for(let l in d[c]){a.models[c][l]||(a.models[c][l]={tokens:0,cachedTokens:0,candidateTokens:0});let u=a.models[c][l],f=d[c][l];u.tokens+=f.tokens||0,u.cachedTokens+=f.cachedTokens||0,u.candidateTokens+=f.candidateTokens||0}}}else typeof a[h]=="number"&&(a[h]+=r[h]||0)};i(s,o);for(let a in t)i(s,t[a]);return s},It=async(e,n)=>{e==="toolSuccess"?Js.toolSuccess++:e==="toolFailure"?Js.toolFailure++:e==="toolDenied"&&Js.toolDenied++;let t=await Tn();t[e]!==void 0&&t[e]++,n&&e==="agent"&&(t.providerRequests||(t.providerRequests={}),t.providerRequests[n]=(t.providerRequests[n]||0)+1),_o()},Js={linesAdded:0,linesRemoved:0,toolSuccess:0,toolFailure:0,toolDenied:0},Gt=async(e,n,t,o)=>{e==="linesAdded"?Js.linesAdded+=n:e==="linesRemoved"&&(Js.linesRemoved+=n);let s=await Tn();if(s[e]!==void 0&&(s[e]+=Math.floor(n)),t&&o&&(e==="tokens"||e==="cachedTokens"||e==="candidateTokens")){s.models||(s.models={}),s.models[t]||(s.models[t]={}),s.models[t][o]||(s.models[t][o]={tokens:0,cachedTokens:0,candidateTokens:0});let i=s.models[t][o];e==="tokens"&&(i.tokens+=Math.floor(n)),e==="cachedTokens"&&(i.cachedTokens+=Math.floor(n)),e==="candidateTokens"&&(i.candidateTokens+=Math.floor(n))}_o()},rl=async(e=1)=>{let n=new Date,t=n.toISOString().split("T")[0];se||(se=await Co()),se.date!==t&&await Tn();let o=n.getFullYear(),s=n.getMonth();n.getDate()<e&&(s-=1,s<0&&(s=11,o-=1));let r=new Date(o,s,e).toISOString().split("T")[0],h=se.history||{},d=se.stats||{...In},c={...In};c.imageCalls=[],c.models={};let l=(u,f)=>{for(let p in u)if(p==="imageCalls")u.imageCalls=[...u.imageCalls||[],...f.imageCalls||[]];else if(p==="models"){let g=f.models||{};for(let y in g){u.models[y]||(u.models[y]={});for(let m in g[y]){u.models[y][m]||(u.models[y][m]={tokens:0,cachedTokens:0,candidateTokens:0});let w=u.models[y][m],x=g[y][m];w.tokens+=x.tokens||0,w.cachedTokens+=x.cachedTokens||0,w.candidateTokens+=x.candidateTokens||0}}}else typeof u[p]=="number"&&(u[p]+=f[p]||0)};l(c,d);for(let u in h)u>=r&&u<t&&l(c,h[u]);return c},li=async(e,n={})=>{let t=await Ft().catch(()=>({})),o=n.apiTier||t.apiTier||"Free",s=n.quotas||n.systemSettings?.quotas||t.quotas||{},i=s.providerBudgets||{},a=!!i.__useProvider,r=n.aiProvider||t.aiProvider||"Google",h=a&&!!i[r],d=()=>{if(h){let c=i[r];return{agentLimit:typeof c.agentLimit=="number"&&c.agentLimit>0?c.agentLimit:99999999,tokenLimit:typeof c.tokenLimit=="number"&&c.tokenLimit>0?c.tokenLimit:99999999999999,monthlyTokenLimit:typeof c.monthlyTokenLimit=="number"&&c.monthlyTokenLimit>0?c.monthlyTokenLimit:99999999999999}}return{agentLimit:s.agentLimit||99999999,tokenLimit:s.tokenLimit||99999999999999,monthlyTokenLimit:s.monthlyTokenLimit||99999999999999}};if(e==="agent"){let{agentLimit:c,tokenLimit:l,monthlyTokenLimit:u}=d(),f=await Tn(),p;s.resetMode==="Custom"?p=await rl(s.resetDay||1):p=await il();let g=0,y=0,m=0;if(h){g=f.providerRequests?.[r]||0;let w=f.models?.[r]||{};for(let S in w)y+=w[S]?.tokens||0;let x=p.models?.[r]||{};for(let S in x)m+=x[S]?.tokens||0}else g=f.agent||0,y=f.tokens||0,m=p.tokens||0;return o==="Free"&&f.agent+f.background>=999999?{allowed:!1,reason:"Free Tier Daily Usage Limit Exceeded"}:g>=c?{allowed:!1,reason:h?`Daily Request Limit Reached for ${r}`:"Daily Agent Request Limit Reached"}:y>=l?{allowed:!1,reason:h?`Daily Token Budget Exhausted for ${r}`:"Daily Token Budget Exhausted"}:m>=u?{allowed:!1,reason:h?`Monthly Token Budget Exhausted for ${r}`:"Monthly Token Budget Exhausted"}:{allowed:!0}}if(e==="background"){let c=await Tn();if(o==="Free"&&c.agent+c.background>=999999)return{allowed:!1,reason:"Free Tier Background Limit Exceeded"};let l=c.background<(s.backgroundLimit||999999);return{allowed:l,reason:l?void 0:"Background Request Limit Exceeded"}}if(e==="search"){let l=(await Tn()).search<(s.searchLimit||100);return{allowed:l,reason:l?void 0:"Search Quota Exceeded"}}return{allowed:!0}},Ar=async(e,n={})=>(await li(e,n)).allowed,ci=e=>{if(!e||e.length===0)return[];let t=[...e].sort((s,i)=>s.timestamp-i.timestamp),o=[];for(let s of t){if(o.length>0){let i=o[o.length-1];if(s.timestamp>=i.start&&s.timestamp<i.end){i.calls.push(s),i.spent+=s.cost;continue}}o.push({start:s.timestamp,end:s.timestamp+36e5,calls:[s],spent:s.cost})}return o},vr=(e,n)=>{if(!e||e.length===0)return .025;let o=ci(e);if(o.length===0)return .025;let s=[];for(let l of o){let u=.025;if(s.length>0){let p=s[s.length-1],g=!1;if(s.length>=2){let y=s[s.length-2];p.ratio>=.8&&y.ratio>=.8&&(g=!0)}if(g)u=.015;else{let y=p.limit,m=p.ratio;m>=.8?u=y===.015?.015:y:m<.4?u=Math.min(.025,y+.005):m>=.4&&m<.6?u=Math.min(.025,y+.004):u=Math.min(.025,y+.002)}}let f=u>0?l.spent/u:0;s.push({limit:u,spent:l.spent,ratio:f})}let i=o[o.length-1];if(n<i.end)return s[s.length-1].limit;let a=s[s.length-1].limit,r=a,h=s[s.length-1].ratio,d=i.end,c=0;for(let l=s.length-1;l>=0&&s[l].ratio>=.8;l--)c++;for(;d<=n;){let l=.025;c>=2?l=.015:h>=.8?l=r===.015?.015:r:h<.4?l=Math.min(.025,r+.005):h>=.4&&h<.6?l=Math.min(.025,r+.004):l=Math.min(.025,r+.002),r=l,h=0,c=0,d+=36e5,a=l}return a},Ir=async e=>{let n=e.imageSettings||{keyType:"Default",quality:"Low-High"};if(n.keyType!=="Default")return!0;let o={Low:.001,"Low-High":.002,Medium:.008,"Medium-High":.01,High:.045,Ultra:.0488,Premium:.15}[n.quality]||.002,s=await Tn();s.imageCalls||(s.imageCalls=[]);let i=Date.now(),a=ci(s.imageCalls),r=0;if(a.length>0){let d=a[a.length-1];i>=d.start&&i<d.end&&(r=d.spent)}let h=vr(s.imageCalls,i);return r+o<=h},Or=async()=>{let e=await Tn();e.imageCalls||(e.imageCalls=[]);let n=Date.now(),t=ci(e.imageCalls),o=[],s=0,i=0;if(t.length>0){let d=t[t.length-1];n>=d.start&&n<d.end&&(o=d.calls,s=d.spent,i=Math.max(0,Math.ceil((d.end-n)/(60*1e3))))}let a=vr(e.imageCalls,n),r=Math.max(0,a-s),h=s;return{totalSpent:s,remaining:r,activeCallsCount:o.length,nextResetMin:i,reclaimCost:h,limit:a}},Lr=async e=>{let n=e.imageSettings||{keyType:"Default",quality:"Low-High"},o={Low:.001,"Low-High":.002,Medium:.008,"Medium-High":.01,High:.045,Ultra:.0488,Premium:.1}[n.quality]||.002,s=await Tn();s.imageCalls||(s.imageCalls=[]),s.imageCalls.push({timestamp:Date.now(),cost:o}),_o()};import Fr from"puppeteer";import Nr from"fs";import Br from"path";import Pr from"os";import Xs from"path";import As from"fs";import{createRequire as al}from"module";import{fileURLToPath as ll}from"url";var cl=al(import.meta.url),Dr=Xs.dirname(ll(import.meta.url));function cs(){let e=Pr.platform(),n=Pr.arch(),t="",o="",s="";if(e==="win32")t=n==="x64"?"win64":"win32",o="chrome.exe",s=`chrome-${t}`;else if(e==="darwin"){t=n==="arm64"?"mac_arm":"mac";let a=n==="arm64"?"arm64":"x64";o="Google Chrome.app/Contents/MacOS/Google Chrome",s=`chrome-mac-${a}`}else if(e==="linux")t="linux",o="chrome",s="chrome-linux64";else return{};let i=Xs.resolve(Dr,"..","..",".puppeteerrc.cjs");if(As.existsSync(i)||(i=Xs.resolve(Dr,"..",".puppeteerrc.cjs")),!As.existsSync(i))return{};try{let a=cl(i),r=a.cacheDirectory,h=a.chrome?.version;if(r){if(process.env.PUPPETEER_CACHE_DIR=r,h){let l=Xs.join(r,"chrome",`${t}-${h}`,s,o);if(As.existsSync(l))return{executablePath:l,cacheDirectory:r}}let d=l=>{if(!As.existsSync(l))return null;try{let u=As.readdirSync(l),f=[];for(let p of u){let g=Xs.join(l,p),y;try{y=As.statSync(g)}catch{continue}if(y.isDirectory())f.push(g);else if(p.toLowerCase()===o.toLowerCase()&&(!h||g.includes(h)))return g}if(h){for(let p of f)if(p.includes(h)){let g=d(p);if(g)return g}}for(let p of f)if(!h||!p.includes(h)){let g=d(p);if(g)return g}}catch{}return null},c=d(r);if(c)return{executablePath:c,cacheDirectory:r}}}catch{}return{}}var di=async e=>{let{query:n,limit:t=5,aiMode:o=!1}=O(e);if(!n)return'ERROR: Missing "query" argument for web_search.';let s=3,i=null;if(o){let a=`Query: ${n}
|
|
206
|
+
`).trim();c?await _t.writeFile(e,c+`
|
|
207
|
+
`,"utf8"):await _t.writeFile(e,"","utf8")}catch{}},Sd=async e=>{try{if(!await _t.pathExists(e))return;let n=async t=>{let o=await _t.readdir(t);for(let s of o){let i=$o.join(t,s);(await _t.stat(i)).isDirectory()?(await n(i),(await _t.readdir(i)).length===0&&await _t.remove(i)):s.endsWith(".log")&&await ol(i)}};await n(e)}catch{}},Mr=(e,n=4)=>{if(e.length<=1)return e;let t=e[0],o=e.slice(1),s=n*2,i=o.slice(s);return[t,...i]};var Td=async(e,n,t)=>_o(async()=>{let o=X(jn,[]);Array.isArray(o)||(o=[]);let s={total:n,context:t},i=o.findIndex(a=>Object.keys(a)[0]===String(e));i!==-1?o[i]={[String(e)]:s}:o.push({[String(e)]:s}),he(jn,o)}),Rd=async e=>{try{if(!await _t.pathExists(jn))return{total:0,context:0};let n=X(jn,[]);if(!Array.isArray(n))return{total:0,context:0};let t=n.find(o=>Object.keys(o)[0]===String(e));return t?t[String(e)]:{total:0,context:0}}catch{return{total:0,context:0}}};import yt from"fs-extra";import Ar from"path";var il=()=>Math.random().toString(36).substring(2)+Date.now().toString(36),se=null,Gn=null,vr=0,Cs=!1,In={agent:0,background:0,search:0,toolSuccess:0,toolFailure:0,toolDenied:0,duration:0,tokens:0,cachedTokens:0,candidateTokens:0,linesAdded:0,linesRemoved:0,imageCalls:[]},Ms=(e,n)=>{if(!e)return{};let t=Object.keys(e),o=new Date(new Date(n).getTime()-720*60*60*1e3),s={};for(let i of t)new Date(i)>=o&&(s[i]=e[i]);return s},Co=async()=>{let e=new Date().toISOString().split("T")[0];try{!await yt.exists(Xt)&&await yt.exists(Xo)&&(await yt.ensureDir(Ar.dirname(Xt)),await yt.move(Xo,Xt))}catch{}let n=Xt+".tmp",t=null;try{if(await yt.exists(n)){let s=(await yt.readFile(n,"utf8")).trim(),i=null;if(s.startsWith("{")||s.startsWith("[")?i=JSON.parse(s):i=JSON.parse(_s(s)),i&&i.date&&i.stats){t=i;try{await yt.rename(n,Xt)}catch{}}else try{await yt.remove(n)}catch{}}}catch{try{await yt.remove(n)}catch{}}if(!t)try{if(await yt.exists(Xt)){let s=(await yt.readFile(Xt,"utf8")).trim();s.startsWith("{")||s.startsWith("[")?t=JSON.parse(s):t=JSON.parse(_s(s))}}catch{}let o=t;if(o){let s=o.stats||{...In},i={...In,...s};Array.isArray(i.imageCalls)||(i.imageCalls=[]);let a=o.history||{},r=Ms(a,e);if(Object.keys(a).length!==Object.keys(r).length&&(Cs=!0),o.date===e)return{...o,stats:i,history:r};{let h=o.date,d=i,c={...r};return h&&(c[h]=d),{date:e,stats:{...In},history:Ms(c,e)}}}return{date:e,stats:{...In},history:{}}},ai=async()=>{if(!(!Cs||!se))try{await yt.ensureDir(Ar.dirname(Xt));let e=null;try{if(await yt.exists(Xt)){let s=(await yt.readFile(Xt,"utf8")).trim();s.startsWith("{")||s.startsWith("[")?e=JSON.parse(s):e=JSON.parse(_s(s))}}catch{}if(e&&e.date===se.date&&e.stats){for(let s in se.stats)if(e.stats[s]!==void 0){if(Array.isArray(se.stats[s])){let i=Array.isArray(e.stats[s])?e.stats[s]:[],a=se.stats[s],r=new Map;for(let h of[...i,...a])h&&h.timestamp&&r.set(h.timestamp,h);se.stats[s]=Array.from(r.values())}else if(typeof se.stats[s]=="number")se.stats[s]=Math.max(se.stats[s],Number(e.stats[s])||0);else if(se.stats[s]&&typeof se.stats[s]=="object"){let i=e.stats[s]||{},a=se.stats[s];for(let r in i)if(typeof i[r]=="number")a[r]=Math.max(a[r]||0,i[r]);else if(i[r]&&typeof i[r]=="object"){a[r]||(a[r]={});for(let h in i[r])if(typeof i[r][h]=="number")a[r][h]=Math.max(a[r][h]||0,i[r][h]);else if(i[r][h]&&typeof i[r][h]=="object"){a[r][h]||(a[r][h]={});for(let d in i[r][h])a[r][h][d]=Math.max(a[r][h][d]||0,i[r][h][d])}}}}}if(e&&e.history){let s={...se.history||{}};for(let i in e.history)if(s[i])for(let a in s[i])if(a==="imageCalls"){let r=Array.isArray(e.history[i].imageCalls)?e.history[i].imageCalls:[],h=Array.isArray(s[i].imageCalls)?s[i].imageCalls:[],d=new Map;for(let c of[...r,...h])c&&c.timestamp&&d.set(c.timestamp,c);s[i].imageCalls=Array.from(d.values())}else typeof s[i][a]=="number"&&(s[i][a]=Math.max(s[i][a],Number(e.history[i][a])||0));else s[i]=e.history[i];se.history=Ms(s,se.date||today)}else if(se&&se.history){let s=new Date().toISOString().split("T")[0];se.history=Ms(se.history,s)}se.saveId=il();let n=Xt+".tmp",t=Gs(JSON.stringify(se,null,2));await yt.writeFile(n,t,"utf8");let o=await yt.open(n,"r+");await yt.fsync(o),await yt.close(o),await yt.rename(n,Xt),Cs=!1,vr=Date.now()}catch{}},Mo=()=>{if(Cs=!0,Gn)return;let e=Date.now(),n=Math.max(0,1500-(e-vr));Gn=setTimeout(async()=>{await ai(),Gn=null},n),Gn.unref&&Gn.unref()},vd=async()=>{se=await Co(),Cs&&Mo()},Id=async()=>{Gn&&(clearTimeout(Gn),Gn=null),await ai()},Tn=async()=>{let e=new Date().toISOString().split("T")[0];if(!se)se=await Co();else if(se.date!==e){let n=se.date,t=se.stats,o=se.history||{};t&&(o[n]=t),se={date:e,stats:{...In},history:Ms(o,e)},Cs=!0,await ai()}return se&&se.stats&&!Array.isArray(se.stats.imageCalls)&&(se.stats.imageCalls=[]),se.stats},rl=async()=>{let e=new Date().toISOString().split("T")[0];se||(se=await Co()),se.date!==e&&await Tn();let n=se.history||{},t=Ms(n,e);se.history=t;let o=se.stats||{...In},s={...In};s.imageCalls=[],s.models={};let i=(a,r)=>{for(let h in a)if(h==="imageCalls")a.imageCalls=[...a.imageCalls||[],...r.imageCalls||[]];else if(h==="models"){let d=r.models||{};for(let c in d){a.models[c]||(a.models[c]={});for(let l in d[c]){a.models[c][l]||(a.models[c][l]={tokens:0,cachedTokens:0,candidateTokens:0});let u=a.models[c][l],f=d[c][l];u.tokens+=f.tokens||0,u.cachedTokens+=f.cachedTokens||0,u.candidateTokens+=f.candidateTokens||0}}}else typeof a[h]=="number"&&(a[h]+=r[h]||0)};i(s,o);for(let a in t)i(s,t[a]);return s},It=async(e,n)=>{e==="toolSuccess"?Js.toolSuccess++:e==="toolFailure"?Js.toolFailure++:e==="toolDenied"&&Js.toolDenied++;let t=await Tn();t[e]!==void 0&&t[e]++,n&&e==="agent"&&(t.providerRequests||(t.providerRequests={}),t.providerRequests[n]=(t.providerRequests[n]||0)+1),Mo()},Js={linesAdded:0,linesRemoved:0,toolSuccess:0,toolFailure:0,toolDenied:0},qt=async(e,n,t,o)=>{e==="linesAdded"?Js.linesAdded+=n:e==="linesRemoved"&&(Js.linesRemoved+=n);let s=await Tn();if(s[e]!==void 0&&(s[e]+=Math.floor(n)),t&&o&&(e==="tokens"||e==="cachedTokens"||e==="candidateTokens")){s.models||(s.models={}),s.models[t]||(s.models[t]={}),s.models[t][o]||(s.models[t][o]={tokens:0,cachedTokens:0,candidateTokens:0});let i=s.models[t][o];e==="tokens"&&(i.tokens+=Math.floor(n)),e==="cachedTokens"&&(i.cachedTokens+=Math.floor(n)),e==="candidateTokens"&&(i.candidateTokens+=Math.floor(n))}Mo()},al=async(e=1)=>{let n=new Date,t=n.toISOString().split("T")[0];se||(se=await Co()),se.date!==t&&await Tn();let o=n.getFullYear(),s=n.getMonth();n.getDate()<e&&(s-=1,s<0&&(s=11,o-=1));let r=new Date(o,s,e).toISOString().split("T")[0],h=se.history||{},d=se.stats||{...In},c={...In};c.imageCalls=[],c.models={};let l=(u,f)=>{for(let p in u)if(p==="imageCalls")u.imageCalls=[...u.imageCalls||[],...f.imageCalls||[]];else if(p==="models"){let g=f.models||{};for(let y in g){u.models[y]||(u.models[y]={});for(let m in g[y]){u.models[y][m]||(u.models[y][m]={tokens:0,cachedTokens:0,candidateTokens:0});let w=u.models[y][m],b=g[y][m];w.tokens+=b.tokens||0,w.cachedTokens+=b.cachedTokens||0,w.candidateTokens+=b.candidateTokens||0}}}else typeof u[p]=="number"&&(u[p]+=f[p]||0)};l(c,d);for(let u in h)u>=r&&u<t&&l(c,h[u]);return c},li=async(e,n={})=>{let t=await Ft().catch(()=>({})),o=n.apiTier||t.apiTier||"Free",s=n.quotas||n.systemSettings?.quotas||t.quotas||{},i=s.providerBudgets||{},a=!!i.__useProvider,r=n.aiProvider||t.aiProvider||"Google",h=a&&!!i[r],d=()=>{if(h){let c=i[r];return{agentLimit:typeof c.agentLimit=="number"&&c.agentLimit>0?c.agentLimit:99999999,tokenLimit:typeof c.tokenLimit=="number"&&c.tokenLimit>0?c.tokenLimit:99999999999999,monthlyTokenLimit:typeof c.monthlyTokenLimit=="number"&&c.monthlyTokenLimit>0?c.monthlyTokenLimit:99999999999999}}return{agentLimit:s.agentLimit||99999999,tokenLimit:s.tokenLimit||99999999999999,monthlyTokenLimit:s.monthlyTokenLimit||99999999999999}};if(e==="agent"){let{agentLimit:c,tokenLimit:l,monthlyTokenLimit:u}=d(),f=await Tn(),p;s.resetMode==="Custom"?p=await al(s.resetDay||1):p=await rl();let g=0,y=0,m=0;if(h){g=f.providerRequests?.[r]||0;let w=f.models?.[r]||{};for(let k in w)y+=w[k]?.tokens||0;let b=p.models?.[r]||{};for(let k in b)m+=b[k]?.tokens||0}else g=f.agent||0,y=f.tokens||0,m=p.tokens||0;return o==="Free"&&f.agent+f.background>=999999?{allowed:!1,reason:"Free Tier Daily Usage Limit Exceeded"}:g>=c?{allowed:!1,reason:h?`Daily Request Limit Reached for ${r}`:"Daily Agent Request Limit Reached"}:y>=l?{allowed:!1,reason:h?`Daily Token Budget Exhausted for ${r}`:"Daily Token Budget Exhausted"}:m>=u?{allowed:!1,reason:h?`Monthly Token Budget Exhausted for ${r}`:"Monthly Token Budget Exhausted"}:{allowed:!0}}if(e==="background"){let c=await Tn();if(o==="Free"&&c.agent+c.background>=999999)return{allowed:!1,reason:"Free Tier Background Limit Exceeded"};let l=c.background<(s.backgroundLimit||999999);return{allowed:l,reason:l?void 0:"Background Request Limit Exceeded"}}if(e==="search"){let l=(await Tn()).search<(s.searchLimit||100);return{allowed:l,reason:l?void 0:"Search Quota Exceeded"}}return{allowed:!0}},Ir=async(e,n={})=>(await li(e,n)).allowed,ci=e=>{if(!e||e.length===0)return[];let t=[...e].sort((s,i)=>s.timestamp-i.timestamp),o=[];for(let s of t){if(o.length>0){let i=o[o.length-1];if(s.timestamp>=i.start&&s.timestamp<i.end){i.calls.push(s),i.spent+=s.cost;continue}}o.push({start:s.timestamp,end:s.timestamp+36e5,calls:[s],spent:s.cost})}return o},Or=(e,n)=>{if(!e||e.length===0)return .025;let o=ci(e);if(o.length===0)return .025;let s=[];for(let l of o){let u=.025;if(s.length>0){let p=s[s.length-1],g=!1;if(s.length>=2){let y=s[s.length-2];p.ratio>=.8&&y.ratio>=.8&&(g=!0)}if(g)u=.015;else{let y=p.limit,m=p.ratio;m>=.8?u=y===.015?.015:y:m<.4?u=Math.min(.025,y+.005):m>=.4&&m<.6?u=Math.min(.025,y+.004):u=Math.min(.025,y+.002)}}let f=u>0?l.spent/u:0;s.push({limit:u,spent:l.spent,ratio:f})}let i=o[o.length-1];if(n<i.end)return s[s.length-1].limit;let a=s[s.length-1].limit,r=a,h=s[s.length-1].ratio,d=i.end,c=0;for(let l=s.length-1;l>=0&&s[l].ratio>=.8;l--)c++;for(;d<=n;){let l=.025;c>=2?l=.015:h>=.8?l=r===.015?.015:r:h<.4?l=Math.min(.025,r+.005):h>=.4&&h<.6?l=Math.min(.025,r+.004):l=Math.min(.025,r+.002),r=l,h=0,c=0,d+=36e5,a=l}return a},Lr=async e=>{let n=e.imageSettings||{keyType:"Default",quality:"Low-High"};if(n.keyType!=="Default")return!0;let o={Low:.001,"Low-High":.002,Medium:.008,"Medium-High":.01,High:.045,Ultra:.0488,Premium:.15}[n.quality]||.002,s=await Tn();s.imageCalls||(s.imageCalls=[]);let i=Date.now(),a=ci(s.imageCalls),r=0;if(a.length>0){let d=a[a.length-1];i>=d.start&&i<d.end&&(r=d.spent)}let h=Or(s.imageCalls,i);return r+o<=h},Dr=async()=>{let e=await Tn();e.imageCalls||(e.imageCalls=[]);let n=Date.now(),t=ci(e.imageCalls),o=[],s=0,i=0;if(t.length>0){let d=t[t.length-1];n>=d.start&&n<d.end&&(o=d.calls,s=d.spent,i=Math.max(0,Math.ceil((d.end-n)/(60*1e3))))}let a=Or(e.imageCalls,n),r=Math.max(0,a-s),h=s;return{totalSpent:s,remaining:r,activeCallsCount:o.length,nextResetMin:i,reclaimCost:h,limit:a}},Pr=async e=>{let n=e.imageSettings||{keyType:"Default",quality:"Low-High"},o={Low:.001,"Low-High":.002,Medium:.008,"Medium-High":.01,High:.045,Ultra:.0488,Premium:.1}[n.quality]||.002,s=await Tn();s.imageCalls||(s.imageCalls=[]),s.imageCalls.push({timestamp:Date.now(),cost:o}),Mo()};import Br from"puppeteer";import Ur from"fs";import Wr from"path";import Fr from"os";import Xs from"path";import As from"fs";import{createRequire as ll}from"module";import{fileURLToPath as cl}from"url";var dl=ll(import.meta.url),Nr=Xs.dirname(cl(import.meta.url));function cs(){let e=Fr.platform(),n=Fr.arch(),t="",o="",s="";if(e==="win32")t=n==="x64"?"win64":"win32",o="chrome.exe",s=`chrome-${t}`;else if(e==="darwin"){t=n==="arm64"?"mac_arm":"mac";let a=n==="arm64"?"arm64":"x64";o="Google Chrome.app/Contents/MacOS/Google Chrome",s=`chrome-mac-${a}`}else if(e==="linux")t="linux",o="chrome",s="chrome-linux64";else return{};let i=Xs.resolve(Nr,"..","..",".puppeteerrc.cjs");if(As.existsSync(i)||(i=Xs.resolve(Nr,"..",".puppeteerrc.cjs")),!As.existsSync(i))return{};try{let a=dl(i),r=a.cacheDirectory,h=a.chrome?.version;if(r){if(process.env.PUPPETEER_CACHE_DIR=r,h){let l=Xs.join(r,"chrome",`${t}-${h}`,s,o);if(As.existsSync(l))return{executablePath:l,cacheDirectory:r}}let d=l=>{if(!As.existsSync(l))return null;try{let u=As.readdirSync(l),f=[];for(let p of u){let g=Xs.join(l,p),y;try{y=As.statSync(g)}catch{continue}if(y.isDirectory())f.push(g);else if(p.toLowerCase()===o.toLowerCase()&&(!h||g.includes(h)))return g}if(h){for(let p of f)if(p.includes(h)){let g=d(p);if(g)return g}}for(let p of f)if(!h||!p.includes(h)){let g=d(p);if(g)return g}}catch{}return null},c=d(r);if(c)return{executablePath:c,cacheDirectory:r}}}catch{}return{}}var di=async e=>{let{query:n,limit:t=5,aiMode:o=!1}=O(e);if(!n)return'ERROR: Missing "query" argument for web_search.';let s=3,i=null;if(o){let a=`Query: ${n}
|
|
208
208
|
|
|
209
209
|
RESPONSE RULES:
|
|
210
210
|
- ANSWER CONCISELY WITH REQUIRED DETAILS UNDER 300 WORDS.
|
|
@@ -219,34 +219,34 @@ Sources:
|
|
|
219
219
|
|
|
220
220
|
- LIST ONE RAW URL PER BULLET.
|
|
221
221
|
- DO NOT USE MARKDOWN LINKS.
|
|
222
|
-
- DO NOT INCLUDE ANY TEXT, NOTES, OR EXPLANATIONS AFTER THE SOURCES SECTION.`;for(let r=1;r<=s;r++){let h=null;try{let d=cs();h=await
|
|
222
|
+
- DO NOT INCLUDE ANY TEXT, NOTES, OR EXPLANATIONS AFTER THE SOURCES SECTION.`;for(let r=1;r<=s;r++){let h=null;try{let d=cs();h=await Br.launch({headless:!0,executablePath:d.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let c=await h.newPage();await c.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.178 Safari/537.36"),await c.setViewport({width:1366,height:768});let l=r===1?Math.random()*1e3+500:Math.random()*2e3+1e3;await new Promise(_=>setTimeout(_,l));let u=`https://search.brave.com/ask?q=${encodeURIComponent(a)}&source=web`;await c.goto(u,{waitUntil:"domcontentloaded",timeout:18e4});let f=null,p=45e3,g=Date.now();for(;Date.now()-g<p&&(f=await c.evaluate(()=>{let _=Array.from(document.querySelectorAll('.message:not(.user), .answer-text, .llm-content, [data-type="answer"]')),S="";if(_.length>0&&(S=_.map(ie=>ie.innerText.trim()).filter(Boolean).join(`
|
|
223
223
|
|
|
224
|
-
`)),
|
|
225
|
-
`)){let
|
|
224
|
+
`)),S||(S=document.body.innerText),S.includes("anomaly"))throw new Error("ANOMALY_DETECTED");let v=!!document.querySelector('.spinner, .loading, .typing, .streaming, [data-streaming="true"], [data-state="loading"], svg.animate-spin, circle[cx], div[class*="spin"]'),I=_[0]||document.body,P=I?I.innerText.trim():"",j=/^(?:[✓✔]\s*)?Finished/i.test(P)||!!(I&&I.querySelector(".status-finished, .finished")),U=!v&&(j||S.includes("Sources:")&&!v),Y={};return document.querySelectorAll("a[href]").forEach(ie=>{let Me=ie.getAttribute("href")||ie.href||"";if(Me.includes("uddg=")&&(Me=decodeURIComponent(Me.split("uddg=")[1].split("&")[0])),Me.includes("url=")&&(Me=decodeURIComponent(Me.split("url=")[1].split("&")[0])),Me&&(Me.startsWith("http://")||Me.startsWith("https://"))&&!Me.includes("search.brave.com")){let N=ie.innerText.trim();N&&(Y[N]=Me),ie.textContent=Me}}),{isFinished:U,text:S,hrefMap:Y}}),!(f&&f.isFinished));)await new Promise(_=>setTimeout(_,1e3));let y=(f?f.text:"")||"",m=f?f.hrefMap||{}:{},w="DO NOT INCLUDE ANY TEXT, NOTES, OR EXPLANATIONS AFTER THE SOURCES SECTION.";y.includes(w)&&(y=y.split(w).pop()),y=y.replace(/^.*?(Ctrl \+ Shift \+ O|Ask\nAll\nImages)/s,"").replace(/AI-generated answer\. Please verify critical facts\..*/s,"").replace(/Brave Search uses private usage metrics.*/s,"");let b=y,k="";if(y.includes("Sources:")){let _=y.split("Sources:");b=_[0],k=_.slice(1).join("Sources:")}let R=[];for(let _ of b.split(`
|
|
225
|
+
`)){let S=_.trim();S&&(/^(View all|Finished|Searching|Answering|Thinking)$/i.test(S)||/^[\+\-]?\d+$/.test(S)||S.includes("search.brave.com")||S.startsWith("https://www.youtube.com/watch")||S.startsWith("https://youtube.com/watch")||R.push(_))}let E=R.join(`
|
|
226
226
|
`).replace(/^(?:[\+\-]?\d+\s*)+/i,"").replace(/\n{3,}/g,`
|
|
227
227
|
|
|
228
|
-
`).trim(),
|
|
228
|
+
`).trim(),x=_=>!_||_.includes("search.brave.com")||_.includes("youtube.com")||_.includes("youtu.be"),T="";if(k){let _=k.match(/https?:\/\/[^\s\)\>]+/g)||[],S=[];for(let I of _){let P=I.replace(/[\.\,\;]+$/,""),j=Object.keys(m).find(U=>U.startsWith(P)||P.startsWith(U));j&&m[j]&&(P=m[j]),x(P)||S.push(P)}Object.values(m).forEach(I=>{!x(I)&&!S.includes(I)&&S.push(I)});let v=Array.from(new Set(S));v.length>0&&(T=`Sources:
|
|
229
229
|
`+v.map(I=>`- ${I}`).join(`
|
|
230
230
|
`))}let $=E+(T?`
|
|
231
231
|
|
|
232
232
|
`+T:"");if(!$||/^(\+\d+|Searching|Answering|Thinking|Finished)$/i.test($))throw new Error("EMPTY_AI_RESPONSE");return await h.close(),`AI Search results for [${n}]:
|
|
233
233
|
|
|
234
|
-
${$}`}catch(d){if(i=d,
|
|
234
|
+
${$}`}catch(d){if(i=d,Ur.writeFileSync(Wr.join(fn,"web_tools","search","ai_mode","ERROR.txt"),d.message),h&&await h.close(),r<s){let c=Math.pow(2,r)*1e3;await new Promise(l=>setTimeout(l,c))}}}}for(let a=1;a<=s;a++){let r=null;try{let h=cs();r=await Br.launch({headless:!0,executablePath:h.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let d=await r.newPage();await d.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.178 Safari/537.36"),await d.setViewport({width:1366,height:768});let c=a===1?Math.random()*1e3+500:Math.random()*2e3+1e3;await new Promise(g=>setTimeout(g,c));let l=`https://html.duckduckgo.com/html/?q=${encodeURIComponent(n)}`;await d.goto(l,{waitUntil:"networkidle2",timeout:18e4});let u=await d.$$eval(".result",(g,y)=>g.slice(0,y).map((m,w)=>{let b=m.querySelector(".result__a"),k=m.querySelector(".result__snippet"),R=b?b.href:"";R.includes("uddg=")&&(R=decodeURIComponent(R.split("uddg=")[1].split("&")[0]));let E=b?b.innerText.trim():"No Title",x=k?k.innerText.trim():"No Snippet";return`${w+1}. ${E}
|
|
235
235
|
Source: ${R}
|
|
236
|
-
Snippet: ${
|
|
236
|
+
Snippet: ${x}`}),t);if(u.length===0){if((await d.evaluate(()=>document.body.innerText)).includes("anomaly"))throw new Error("ANOMALY_DETECTED");return await r.close(),`No results found for query: [${n}].`}let f=u.join(`
|
|
237
237
|
|
|
238
238
|
`);return await r.close(),`${o?`AI Mode temporarily failed, used Standard search.
|
|
239
239
|
|
|
240
240
|
`:""}Search results for [${n}]:
|
|
241
241
|
|
|
242
|
-
${f}`}catch(h){if(i=h,r&&await r.close(),
|
|
242
|
+
${f}`}catch(h){if(i=h,r&&await r.close(),Ur.writeFileSync(Wr.join(fn,"web_tools","search","standard_mode","ERROR.txt"),h.message),a<s){let d=Math.pow(2,a)*1e3;await new Promise(c=>setTimeout(c,d))}}}return`ERROR: Search failed after ${s+1} attempts. Last error: ${i.message}`};import fl from"puppeteer";import ul from"turndown";import{gfm as hl}from"turndown-plugin-gfm";var fi=async e=>{let n=e;if(typeof e=="object"&&e!==null)n=e.url||e.targetUrl||e.href||"";else if(typeof e=="string"){let i=e.match(/url\s*=\s*["'](.*)["']/);n=i?i[1]:e}let t=typeof n=="string"?n.trim():"";if(!t)return"ERROR: No target URL provided.";let o=3,s=null;for(let i=1;i<=o;i++){let a=null;try{let r=cs();a=await fl.launch({headless:!0,executablePath:r.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let h=await a.newPage();await h.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.178 Safari/537.36"),await h.setViewport({width:1366,height:768});let d=i===1?Math.random()*1e3+500:Math.random()*2e3+1e3;await new Promise(g=>setTimeout(g,d)),await h.goto(t,{waitUntil:"networkidle2",timeout:18e4}),await new Promise(g=>setTimeout(g,5e3));let c=await h.evaluate(()=>{document.querySelectorAll("script, style, noscript, svg, canvas, iframe, ad, .ads, link, meta, img").forEach(k=>k.remove());let y=document.createNodeIterator(document.body,NodeFilter.SHOW_COMMENT),m;for(;m=y.nextNode();)m.remove();for(document.querySelectorAll("*").forEach(k=>{let R=k.attributes;for(let E=R.length-1;E>=0;E--){let x=R[E].name;x!=="href"&&x!=="src"&&k.removeAttribute(x)}});document.querySelector("div, span");)document.querySelectorAll("div, span").forEach(k=>{k.parentNode&&k.replaceWith(...k.childNodes)});document.querySelectorAll("br").forEach(k=>{k.replaceWith(document.createTextNode(`
|
|
243
243
|
|
|
244
|
-
`))});let
|
|
244
|
+
`))});let b=()=>{let k=!1;document.querySelectorAll("*").forEach(R=>{R.childNodes.length===0&&!R.innerText.trim()&&(R.remove(),k=!0)}),k&&b()};return b(),document.body.innerHTML});if(!c)throw new Error("EMPTY_RENDER_RESULT");let l=c.replace(/<br\s*\/?>/gi,`
|
|
245
245
|
|
|
246
246
|
`).replace(/[ \t]+/g," ").replace(/>[ \t]+</g,"><").replace(/\n\s+/g,`
|
|
247
247
|
`).replace(/\n{3,}/g,`
|
|
248
248
|
|
|
249
|
-
`).trim(),u=new
|
|
249
|
+
`).trim(),u=new ul({headingStyle:"atx",codeBlockStyle:"fenced"});u.use(hl);let f=u.turndown(l).replace(/\.\s*\n/g,`
|
|
250
250
|
`).replace(/ +/g," ").replace(/\t/g," ").replace(/\n\s+/g,`
|
|
251
251
|
`).replace(/\n{3,}/g,`
|
|
252
252
|
|
|
@@ -254,93 +254,93 @@ ${f}`}catch(h){if(i=h,r&&await r.close(),Nr.writeFileSync(Br.join(cn,"web_tools"
|
|
|
254
254
|
|
|
255
255
|
${p}${f.length>5e4?`
|
|
256
256
|
|
|
257
|
-
[TRUNCATED AT 50K CHARS]`:""}`}catch(r){if(s=r,a&&await a.close(),i<o){let h=Math.pow(2,i)*1e3;await new Promise(d=>setTimeout(d,h))}}}return`ERROR: Scrape failed after ${o+1} attempts. Last error: ${s.message}`};var
|
|
257
|
+
[TRUNCATED AT 50K CHARS]`:""}`}catch(r){if(s=r,a&&await a.close(),i<o){let h=Math.pow(2,i)*1e3;await new Promise(d=>setTimeout(d,h))}}}return`ERROR: Scrape failed after ${o+1} attempts. Last error: ${s.message}`};var pl=4*(1024*2),ui=async(e,n={})=>{let t=c=>{let l=new RegExp(`${c}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),u=e.match(l);if(u)return u[2].trim();let f=new RegExp(`${c}\\s*[:=]\\s*([^,\\s)]+)`,"s"),p=e.match(f);return p?p[1].trim():null},o=t("action"),s=t("method"),i=t("content"),a=t("content-new"),r=t("content-old"),h=t("id"),d=t("chat-id")||n.chatId||n.sessionId||"default-session";if(o==="temp"){if(!i)return"ERROR: Missing 'content' for temp memory.";let c=X(Qt,{});c[d]||(c[d]=[]),c[d].push(i),he(Qt,c);let l=c[d].reduce((u,f)=>u+f.length,0);return`SUCCESS: Temporary context saved for session [${d}]. (Size: ${l} chars)`}if(o==="user"){let c=X(Pt,[]).map(l=>(l.score===void 0&&(l.score=.5),l));if(s==="add"){if(!i)return"ERROR: Missing 'content' for memory addition.";let l=new Date,u=`${l.getDate()}/${l.getMonth()+1}/${l.getFullYear()}`,f=i.includes("[Saved on:")?i:`${i.trim()} [Saved on: ${u}]`,p=pl,g=c.reduce((b,k)=>b+(k.memory?.length||0),0);for(;c.length>0&&g+f.length>p;){let b=c.shift();g-=b.memory?.length||0}let y=t("score"),m=y?parseFloat(y):.5,w={id:`mem-${Date.now().toString(36)}`,memory:f,score:Math.min(2,isNaN(m)?.5:m)};return c.push(w),he(Pt,c),`SUCCESS: Memory added with ID [${w.id}] and score [${w.score}]. (Vault Size: ${g+f.length} chars)`}if(s==="update"){let l=h||r,u=a||i;if(!l||!u)return"ERROR: Missing 'id' or content for update.";let f=c.findIndex(m=>m.id===l);if(f===-1)return`ERROR: Memory ID [${l}] not found.`;let p=new Date,g=`${p.getDate()}/${p.getMonth()+1}/${p.getFullYear()}`,y=u.includes("[Saved on:")?u:`${u.trim()} [Saved on: ${g}]`;return c[f].memory=y,he(Pt,c),`SUCCESS: Memory [${l}] updated.`}if(s==="delete"){let l=h||i;if(!l)return"ERROR: Missing 'id' for deletion.";let u=c.length,f=c.filter(p=>p.id!==l);return f.length===u?`ERROR: Memory ID [${l}] not found.`:(he(Pt,f),`SUCCESS: Memory [${l}] deleted.`)}return`ERROR: Invalid method [${s}] for user memory. Use 'add', 'update', or 'delete'.`}return`ERROR: Unknown action [${o}] for memory tool.`};var hi=async(e,n={})=>{let t=O(e).title,o=n.chatId||n.sessionId;if(!o)return"ERROR: No active chatId found in tool context.";if(!t)return"ERROR: Missing 'title' argument.";try{return await Cr(o,t),`SUCCESS: Chat title updated to [${t}] for session [${o}].`}catch(s){return`ERROR: Failed to update chat title: ${s instanceof Error?s.message:String(s)}`}};import Ao from"fs";import jr from"path";var Qs=async(e,n={})=>{let{path:t,StartLine:o,EndLine:s,start_line:i,end_line:a,startLine:r,endLine:h}=O(e),d=parseInt(o||i||r),c=parseInt(s||a||h),l=!isNaN(d),u=!isNaN(c),f=d||1,p=c||(d?d+800:800);if(!t)return'ERROR: Missing "path" argument for view_file.';let g=jr.resolve(process.cwd(),t);try{if(!Ao.existsSync(g))return`ERROR: File [${t}] does not exist.`;if(Ao.statSync(g).isDirectory())return`ERROR: Path [${t}] is a directory. Use list_files instead.`;let m=jr.extname(t).toLowerCase();if([".mp4",".mkv",".avi",".mov",".webm",".flv",".wmv",".mpeg",".mpg"].includes(m))return`ERROR: Unable to read. Type ${m.slice(1).toUpperCase()} not supported`;let b={".pdf":"application/pdf",".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".webp":"image/webp",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".doc":"application/msword"};if(b[m]){if(!(n.isMultiModal!==!1))return`ERROR: Multimodality is not supported for the current model. Unable to load [${t}].`;let P=Ao.readFileSync(g).toString("base64"),j=b[m];return{text:`[BINARY FILE]: ${t} (${j}) - Loaded as multimodal part.`,binaryPart:{inlineData:{data:P,mimeType:j}}}}let k=Ao.readFileSync(g,"utf8");k.startsWith("\uFEFF")&&(k=k.slice(1)),k=k.replace(/\r\n/g,`
|
|
258
258
|
`).replace(/\r/g,`
|
|
259
|
-
`);let R=
|
|
260
|
-
`),E=R.length;!l&&!u&&E>800&&(f=1,p=50);let
|
|
261
|
-
`);return`${
|
|
259
|
+
`);let R=k.split(`
|
|
260
|
+
`),E=R.length;!l&&!u&&E>800&&(f=1,p=50);let x=Math.max(0,f-1),T=Math.min(E,p),$=R.slice(x,T),_=`File: [${t}] (Showing lines ${x+1}-${T} of ${E}).`,S=$.map((v,I)=>`${String(x+I+1).padStart(4)}: ${v.trimEnd()}`).join(`
|
|
261
|
+
`);return`${_}
|
|
262
262
|
|
|
263
|
-
${
|
|
263
|
+
${S}`}catch(y){let m=y instanceof Error?y.message:String(y);return`ERROR: Failed to read file [${t}]: ${m}`}};import vs from"fs";import Hr from"path";var pi=async(e,n={})=>{let{path:t,content:o}=O(e);if(!t)return'ERROR: Missing "path" argument for write_file.';if(o===void 0)return'ERROR: Missing "content" argument for write_file.';o=o.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
|
|
264
264
|
`).replace(/\r/g,`
|
|
265
|
-
`);let s=
|
|
265
|
+
`);let s=Hr.resolve(process.cwd(),t),i=Hr.dirname(s);try{await ut.recordFileChange(s);let a="";if(vs.existsSync(s))try{a=`Old File contents:
|
|
266
266
|
${vs.readFileSync(s,"utf8").split(/\r?\n/).map((R,E)=>`${E+1} | ${R}`).join(`
|
|
267
267
|
`)}
|
|
268
268
|
|
|
269
269
|
`}catch{a=`[Note: Could not read existing file for reversal reference]
|
|
270
270
|
|
|
271
|
-
`}vs.existsSync(i)||vs.mkdirSync(i,{recursive:!0});let h=(
|
|
271
|
+
`}vs.existsSync(i)||vs.mkdirSync(i,{recursive:!0});let h=(b=>b.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
|
|
272
272
|
`).replace(/\r/g,`
|
|
273
273
|
`))(o),d=h.endsWith(`
|
|
274
274
|
`)?h:h+`
|
|
275
275
|
`,c=d.split(/\r?\n/).length,l=Buffer.byteLength(d,"utf8");vs.writeFileSync(s,d,"utf8");let u=vs.readFileSync(s,"utf8"),f=Buffer.byteLength(u,"utf8"),p=u.split(/\r?\n/),g=p.length;if(f===0&&l>0)return u=null,`ERROR: CRITICAL FAILURE: Verification failed. File [${t}] is empty on disk!`;let y="";if(g<=100)y=p.join(`
|
|
276
|
-
`);else{let
|
|
277
|
-
`),
|
|
278
|
-
`);y=`${
|
|
276
|
+
`);else{let b=p.slice(0,50).join(`
|
|
277
|
+
`),k=p.slice(-50).join(`
|
|
278
|
+
`);y=`${b}
|
|
279
279
|
|
|
280
280
|
... [${g-100} lines truncated] ...
|
|
281
281
|
|
|
282
|
-
${
|
|
282
|
+
${k}`}u=null;let{systemSettings:m}=await Ft(),w=`SUCCESS: File [${t}] saved.
|
|
283
283
|
- Stats: [${g} lines, ${(f/1024).toFixed(1)} KB]
|
|
284
284
|
${a}- Content Preview:
|
|
285
285
|
|
|
286
|
-
${y}`;if(m?.compressToolResults&&g>60){let
|
|
286
|
+
${y}`;if(m?.compressToolResults&&g>60){let b=d.split(/\r?\n/),k=b.slice(0,25).join(`
|
|
287
287
|
`)===p.slice(0,25).join(`
|
|
288
|
-
`),R=
|
|
288
|
+
`),R=b.slice(-25).join(`
|
|
289
289
|
`)===p.slice(-25).join(`
|
|
290
|
-
`);
|
|
291
|
-
${w}`)}return w}catch(a){let r=a instanceof Error?a.message:String(a);return`ERROR: Failed to write file [${t}]: ${r}`}};import wi from"fs";import
|
|
292
|
-
`),s=[];if(n<=5)return e;let i=a=>a.replace(t,"").length;return o.forEach(a=>{if(i(a)<=n){s.push(a);return}let h=a.split(/(\s+)/),d="",c=0,l=a.match(/^(\s*)/),u=l?l[1]:"";h.forEach((f,p)=>{if(f.length===0)return;let g=i(f);if(c+g>n)if(d.trim().length>0)s.push(d.trimEnd()),d=u.substring(0,Math.min(u.length,8))+f,c=i(d);else if(t.test(f))s.push(f),d=u,c=i(d);else{let y=f;for(;i(y)>n&&n>10;)s.push(y.substring(0,n)),y=y.substring(n);d=y,c=i(d)}else d+=f,c+=g}),(d.trimEnd().length>0||d===u)&&s.push(d.trimEnd())}),
|
|
293
|
-
`))},
|
|
290
|
+
`);k&&R&&(w=`[[SAME]]
|
|
291
|
+
${w}`)}return w}catch(a){let r=a instanceof Error?a.message:String(a);return`ERROR: Failed to write file [${t}]: ${r}`}};import wi from"fs";import $l from"path";import ml from"os";var pn=e=>typeof e!="string"?e:e.length>12?(e+"").replace("",""):e,Gr=(e,n)=>{if(!e)return"";let t=/\x1B\[[0-?]*[ -/]*[@-~]/g,o=e.split(`
|
|
292
|
+
`),s=[];if(n<=5)return e;let i=a=>a.replace(t,"").length;return o.forEach(a=>{if(i(a)<=n){s.push(a);return}let h=a.split(/(\s+)/),d="",c=0,l=a.match(/^(\s*)/),u=l?l[1]:"";h.forEach((f,p)=>{if(f.length===0)return;let g=i(f);if(c+g>n)if(d.trim().length>0)s.push(d.trimEnd()),d=u.substring(0,Math.min(u.length,8))+f,c=i(d);else if(t.test(f))s.push(f),d=u,c=i(d);else{let y=f;for(;i(y)>n&&n>10;)s.push(y.substring(0,n)),y=y.substring(n);d=y,c=i(d)}else d+=f,c+=g}),(d.trimEnd().length>0||d===u)&&s.push(d.trimEnd())}),pn(s.join(`
|
|
293
|
+
`))},xf=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()},bf=(e,n=40)=>{let t=An.replaceAll("\\\\","\\");if(e=e.replace(ml.homedir(),"~").replace(t,"FluxFlow").replaceAll("\\","/"),!e||e.length<=n)return pn(e);let o=Math.floor((n-3)/2);return pn(e.substring(0,o)+"..."+e.substring(e.length-o).replaceAll("\\","/"))},vo=e=>{let n=[],t=new Set,o=e.allowMultiple===!0||String(e.allowMultiple).toLowerCase()==="true";Object.keys(e).forEach(h=>{let d=h.match(/^(searchContent|search_content|replaceContent|replace_content|newContent|new_content|content_to_replace|content_to_add|searchBlock|search_block|newBlock|new_block)_?(\d+)?$/i);if(d){let c=d[2]?parseInt(d[2],10):1;t.add(c)}});let s=Array.from(t).sort((h,d)=>h-d),i=["searchContent","search_content","replaceContent","replace_content","content_to_replace","searchBlock","search_block"],a=["newContent","new_content","content_to_add","newBlock","new_block"],r=(h,d,c)=>{let l,u;for(let f of d){let p=h===1?[`${f}1`,f,`${f}_1`]:[`${f}${h}`,`${f}_${h}`];for(let g of p)if(e[g]!==void 0){l=e[g];break}if(l!==void 0)break}for(let f of c){let p=h===1?[`${f}1`,f,`${f}_1`]:[`${f}${h}`,`${f}_${h}`];for(let g of p)if(e[g]!==void 0){u=e[g];break}if(u!==void 0)break}return{r:l,n:u}};for(let h of s){let{r:d,n:c}=r(h,i,a);if(d!==void 0&&c!==void 0)n.push({replace:d,new:c});else if(d!==void 0||c!==void 0)return{error:`Mismatched replacement pair for index ${h}. Both replacement and new content must be provided.`,allowMultiple:o}}return{patchPairs:n,allowMultiple:o}},gl=e=>{if(!e)return null;let n="",t=0,o=e.length;for(;t<o;){let s=e[t];if(s==="\\"){for(;t<o&&e[t]==="\\";)t++;n+="\\\\*"}else if(s===`
|
|
294
294
|
`)n+="(?:\\r?\\n|\\\\*n|\\\\*r|\\s*)",t++;else if(s==="\r")n+="(?:\\r|\\\\*r)?",t++;else if(s===" ")n+="(?:\\t|\\\\*t|\\s*)",t++;else if(s==='"'||s==="'"||s==="`")n.endsWith("\\\\*")||(n+="\\\\*"),n+=s,t++;else if(/[.*+?^${}()|[\]]/.test(s))n+="\\"+s,t++;else if(/\s/.test(s)){for(;t<o&&/\s/.test(e[t])&&e[t]!==`
|
|
295
|
-
`&&e[t]!=="\r"&&e[t]!==" ";)t++;n+="\\s*"}else n+=s,t++}if(!n)return null;try{return new RegExp(n,"g")}catch{return null}},
|
|
295
|
+
`&&e[t]!=="\r"&&e[t]!==" ";)t++;n+="\\s*"}else n+=s,t++}if(!n)return null;try{return new RegExp(n,"g")}catch{return null}},Io=(e,n,t={})=>{let o=typeof t=="boolean"?t:!!(t&&t.allowMultiple),s=e.replace(/\r\n/g,`
|
|
296
296
|
`).replace(/\r/g,`
|
|
297
297
|
`),i=m=>m.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
|
|
298
298
|
`).replace(/\r/g,`
|
|
299
299
|
`),a=m=>m.match(/^\s*/)[0],r=m=>{let w=m.split(`
|
|
300
|
-
`).filter(
|
|
301
|
-
`).find(I=>I.trim()!=="")??"",
|
|
302
|
-
`).map((v,I)=>{if(v.trim()===""&&I!==0)return"";let
|
|
303
|
-
`)},d=[];for(let m=0;m<n.length;m++){let w=n[m],
|
|
304
|
-
`);if(
|
|
305
|
-
`),U=0;for(let Y=0;Y<
|
|
306
|
-
`).map(
|
|
307
|
-
`).length,
|
|
308
|
-
`,
|
|
309
|
-
`),
|
|
310
|
-
`),v=[],I=R+
|
|
300
|
+
`).filter(k=>k.trim()!=="");if(w.length===0)return"";let b=a(w[0]);for(let k of w){let R=a(k);R.length<b.length&&(b=R)}return b},h=(m,w,b="")=>{if(!m||w===void 0)return m;let R=/^\t/m.test(w)?" ":" ",E=v=>v.split(`
|
|
301
|
+
`).find(I=>I.trim()!=="")??"",x=E(w).match(/^\s*/)[0].length,T=E(m).match(/^\s*/)[0].length,$=x-T,_=(b.match(/^\s*/)||[""])[0].length;return m.split(`
|
|
302
|
+
`).map((v,I)=>{if(v.trim()===""&&I!==0)return"";let P=v.match(/^\s*/)[0].length,j=Math.max(0,P+$);return I===0&&(j=Math.max(0,j-_)),R.repeat(j)+v.trimStart()}).join(`
|
|
303
|
+
`)},d=[];for(let m=0;m<n.length;m++){let w=n[m],b=(w.replace||"").trim(),k=i(w.new||"");if(b.startsWith("^LINE:")&&b.endsWith("$")){let _=b.slice(6,-1).trim().split(".."),S=parseInt(_[0]),v=_[1]!==void 0?parseInt(_[1]):S;if(!isNaN(S)&&!isNaN(v)){let I=s.split(`
|
|
304
|
+
`);if(S<1||S>I.length||v<S||v>I.length){d.push({index:m,success:!1,error:`Block ${m+1}: Line range ^LINE:${S}..${v}$ out of bounds (file has ${I.length} lines).`});continue}let j=I.slice(S-1,v).join(`
|
|
305
|
+
`),U=0;for(let Y=0;Y<S-1;Y++)U+=I[Y].length+1;d.push({index:m,success:!0,startPos:U,firstMatchContent:j,content_to_add:k});continue}}let R=i(w.replace||"");if(R===""&&k===""){d.push({index:m,success:!1,error:`Block ${m+1}: Empty replace and add content.`});continue}let E=R.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),x=null;if(R!==""&&s.includes(R))x=new RegExp(E,"g");else{let $=R.split(`
|
|
306
|
+
`).map(_=>_.trim()).filter(_=>_.length>0).map(_=>_.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\s+/g,"\\s*"));if($.length>0){let _=$.join("\\s*");try{x=new RegExp(_,"g")}catch{x=new RegExp(E,"g")}}else x=new RegExp(E,"g")}let T=[...s.matchAll(x)];if(T.length===0&&R!==""){let $=gl(R);$&&(T=[...s.matchAll($)])}if(T.length===0){d.push({index:m,success:!1,error:`Block ${m+1}: Could not find match.`});continue}if(T.length>1&&!o){d.push({index:m,success:!1,error:`Block ${m+1}: Found ${T.length} matches (must be unique or use allowMultiple: true if sure).`});continue}for(let $ of T)d.push({index:m,success:!0,startPos:$.index,firstMatchContent:$[0],content_to_add:k})}let c=d.filter(m=>m.success).sort((m,w)=>m.startPos-w.startPos);for(let m=0;m<c.length-1;m++){let w=c[m],b=c[m+1];w.startPos+w.firstMatchContent.length>b.startPos&&(w.success=!1,w.error=`Block ${w.index+1}: Overlaps with another block.`,b.success=!1,b.error=`Block ${b.index+1}: Overlaps with another block.`)}let l=new Map,u=s,f=0,p=0,g=d.filter(m=>m.success).sort((m,w)=>m.startPos-w.startPos);for(let m of g){let w=m.startPos,b=s.substring(0,w).split(`
|
|
307
|
+
`).length,k=w+f,R=b+p,E=u.lastIndexOf(`
|
|
308
|
+
`,k)+1,x=u.substring(E,k),T=h(m.content_to_add,m.firstMatchContent,x),$=u.split(`
|
|
309
|
+
`),_=[];for(let P=Math.max(0,R-4);P<R-1;P++)_.push({num:P+1,text:$[P]});let S=m.firstMatchContent.split(`
|
|
310
|
+
`),v=[],I=R+S.length-1;for(let P=I;P<Math.min($.length,I+3);P++)v.push({num:P+1,text:$[P]});l.set(m,{success:!0,index:m.index,oldContent:m.firstMatchContent,newContent:T,originalStartLine:b,finalStartLine:R,contextBefore:_,contextAfter:v}),u=u.substring(0,k)+T+u.substring(k+m.firstMatchContent.length),f+=T.length-m.firstMatchContent.length,p+=T.split(`
|
|
311
311
|
`).length-m.firstMatchContent.split(`
|
|
312
|
-
`).length}let y=[];for(let m=0;m<n.length;m++){let w=g.filter(
|
|
312
|
+
`).length}let y=[];for(let m=0;m<n.length;m++){let w=g.filter(b=>b.index===m);if(w.length>0)for(let b of w)l.has(b)&&y.push(l.get(b));else{let b=d.find(k=>k.index===m);y.push({success:!1,error:b?b.error:`Block ${m+1}: Unknown error.`})}}return{content:u,results:y}},Oo=(e,n,t,o=8,s=!1)=>{if(!t||t.length===0)return"";let i=e.split(/\r?\n/),a=n.split(/\r?\n/),r=Math.max(i.length,a.length,1),h=Math.max(4,String(r).length),d=g=>String(g).padStart(h," "),c=`[DIFF_START]
|
|
313
313
|
`,l="\u2550".repeat(88),u=0,f=null,p=t.filter(g=>g.success).sort((g,y)=>g.originalStartLine-y.originalStartLine);if(p.forEach((g,y)=>{let m=g.finalStartLine!==void 0?g.finalStartLine:g.originalStartLine;if(f===null)for(u=Math.max(0,m-4);u<m-1;)c+=`[UI_CONTEXT] ${d(u+1)} |${a[u]||""}
|
|
314
314
|
`,u++;else{let T=f,$=T.originalStartLine+T.oldContent.split(`
|
|
315
|
-
`).length-1;if(g.originalStartLine-$-1>=o){let
|
|
315
|
+
`).length-1;if(g.originalStartLine-$-1>=o){let S=Math.min(a.length,u+3);for(;u<S;)c+=`[UI_CONTEXT] ${d(u+1)} |${a[u]||""}
|
|
316
316
|
`,u++;for(c+=`[UI_CONTEXT] ${l}
|
|
317
317
|
`,u=Math.max(u,m-4);u<m-1;)c+=`[UI_CONTEXT] ${d(u+1)} |${a[u]||""}
|
|
318
318
|
`,u++}else for(;u<m-1;)c+=`[UI_CONTEXT] ${d(u+1)} |${a[u]||""}
|
|
319
|
-
`,u++}let w=g.originalStartLine-1,
|
|
320
|
-
`),R=
|
|
321
|
-
`});let
|
|
322
|
-
`).length:0);else{let T=g.originalStartLine+
|
|
319
|
+
`,u++}let w=g.originalStartLine-1,b=i[w]||"",k=g.oldContent.split(`
|
|
320
|
+
`),R=b.match(/^\s*/),E=R?R[0]:"";k.forEach((T,$)=>{let _=T;if(k.length===1&&b.trim().length>0&&b.includes(T.trim()))_=b;else if($===0){let S=T.match(/^\s*/);(S?S[0]:"").length<E.length&&b.includes(T.trim())&&(_=E+T.trimStart())}c+=`-${d(g.originalStartLine+$)} |${_}
|
|
321
|
+
`});let x=u;if(g.finalStartLine!==void 0)x=g.finalStartLine-1+(g.newContent?g.newContent.split(`
|
|
322
|
+
`).length:0);else{let T=g.originalStartLine+k.length-1,$=i[T]||null;if($!==null){let _=y<p.length-1?(p[y+1].originalStartLine||a.length)+10:a.length;for(let S=u;S<_;S++){if(a[S]===$){x=S;break}S===a.length-1&&(x=a.length)}}else x=a.length}for(;u<x;)c+=`+${d(u+1)} |${a[u]||""}
|
|
323
323
|
`,u++;f=g}),f!==null){let g=Math.min(a.length,u+3);for(;u<g;)c+=`[UI_CONTEXT] ${d(u+1)} |${a[u]||""}
|
|
324
324
|
`,u++}if(s){let g=`[DIFF_START]
|
|
325
325
|
`,y=c.substring(g.length),m=`[UI_CONTEXT] ${l}
|
|
326
|
-
`,
|
|
326
|
+
`,b=y.split(m).map(k=>k.split(`
|
|
327
327
|
`).filter(E=>E.trim()!=="").length>45?`[[VERIFIED]]
|
|
328
|
-
${
|
|
329
|
-
[[/VERIFIED]]`:
|
|
330
|
-
`).map(
|
|
331
|
-
`),j=a(`${e.id||Date.now()}-write-line-${v}`,"write-line",
|
|
332
|
-
`).map(
|
|
333
|
-
`));let v=a(`${e.id||Date.now()}-diff-${T}`,"diff-line",
|
|
328
|
+
${k}
|
|
329
|
+
[[/VERIFIED]]`:k);c=g+b.join(m)}return c+="[DIFF_END]",pn(c)},yl=e=>{if(!e)return null;let n=e.replace("[UI_CONTEXT]","").replace(/\r/g,""),t=n.startsWith("-"),o=n.startsWith("+"),s=t||o?n.substring(1):n,i=s.indexOf("|"),a=i!==-1?pn(s.substring(0,i).trim()):"",r=pn(i!==-1?s.substring(i+1):s);return{isR:t,isA:o,num:a,content:r}},wl=(e,n)=>{if(!e&&!n)return 1;if(!e||!n)return 0;let t=e.length,o=n.length,s=e,i=n;t<o&&(s=n,i=e);let a=s.length,r=i.length,h=new Int32Array(r+1),d=new Int32Array(r+1);for(let u=0;u<=r;u++)h[u]=u;for(let u=1;u<=a;u++){d[0]=u;let f=s[u-1];for(let p=1;p<=r;p++)f===i[p-1]?d[p]=h[p-1]:d[p]=Math.min(h[p],d[p-1],h[p-1])+1;h.set(d)}let c=h[r],l=Math.max(t,o);return l===0?1:1-c/l},qr=e=>{let n=[],t=[];e.forEach((c,l)=>{c.parsed.isR?n.push({index:l,content:c.parsed.content}):c.parsed.isA&&t.push({index:l,content:c.parsed.content})});let o=n.length,s=t.length;if(o===0||s===0)return;let i=Array.from({length:o+1},()=>Array(s+1).fill(0)),a=Array.from({length:o+1},()=>Array(s+1).fill(""));for(let c=1;c<=o;c++)a[c][0]="up";for(let c=1;c<=s;c++)a[0][c]="left";let r=Array.from({length:o},()=>Array(s).fill(0));for(let c=0;c<o;c++)for(let l=0;l<s;l++)r[c][l]=wl(n[c].content.trim(),t[l].content.trim());for(let c=1;c<=o;c++)for(let l=1;l<=s;l++){let u=r[c-1][l-1],f=u>=.2?u:-10,p=i[c-1][l-1]+f,g=i[c-1][l],y=i[c][l-1];p>=g&&p>=y?(i[c][l]=p,a[c][l]="diag"):g>=y?(i[c][l]=g,a[c][l]="up"):(i[c][l]=y,a[c][l]="left")}let h=o,d=s;for(;h>0||d>0;)if(a[h][d]==="diag"){if(r[h-1][d-1]>=.2){let l=n[h-1].index,u=t[d-1].index;e[l].pairContent=e[u].parsed.content,e[u].pairContent=e[l].parsed.content}h--,d--}else a[h][d]==="up"?h--:d--},qn=new Map,ds=new Map,zr=200,mi=6,yi=(e,n)=>{n.set(e.key,e),e.type==="chunk"&&e.blocks&&e.blocks.forEach(t=>yi(t,n))},kf=(e,n)=>{if(!e)return{completed:[],active:[]};let t=`${e.id}-${e.text?.length||0}-${n}-${e.isStreaming}-${e.workedDuration||0}`;if(!e.isStreaming&&qn.has(t))return qn.get(t);let o=pn(El(e.text||"",e.role==="think")),s=`${e.id}-${n}`,i=new Map;if(e.isStreaming){let p=ds.get(s);p&&o.startsWith(p.text)&&(i=p.blocksMap)}let a=(p,g,y,m={})=>{let w=i.get(p);if(w&&w.text===y&&w.type===g&&!!w.isActiveBlock==!!m.isActiveBlock&&!!w.isStreaming==!!m.isStreaming&&w.pairContent===m.pairContent)return w;let b=pn(y),k={...m};return typeof k.pairContent=="string"&&(k.pairContent=pn(k.pairContent)),Array.isArray(k.wrappedLines)&&(k.wrappedLines=k.wrappedLines.map(pn)),{key:p,isStreamingMsg:!!e.isStreaming,workedDuration:e.workedDuration,type:g,text:b,msg:g==="full-message"?e:void 0,...k}};if(o.includes("- Content Preview:")){let p="",g=o.match(/File\s+\[(.*?)\]/i);g&&(p=g[1].split(".").pop().toLowerCase());let k=((o.split("- Content Preview:")[1]||"").split("[SYSTEM] Check the content preview for verification [/SYSTEM]")[0]?.trim()||"").split(`
|
|
330
|
+
`).map(S=>S.replace(/\r$/,"")),R=String(k.length).length,E=[],x=null,T=[],$=()=>{if(!T.length)return;let S=T;T=[],E.push(S.length===1?S[0]:{key:`${S[0].key}-chunk`,type:"chunk",blocks:S})},_=n-(R+6);return k.forEach((S,v)=>{let I=v===k.length-1,P=Gr(S,_).split(`
|
|
331
|
+
`),j=a(`${e.id||Date.now()}-write-line-${v}`,"write-line",S,{gutterWidth:R,lineNum:v+1,isFirstLine:v===0,isLastLine:I,extension:p,wrappedLines:P});I&&e.isStreaming?($(),x=j):(T.push(j),T.length>=mi&&$())}),$(),{completed:E,active:x?[x]:[]}}if(o.includes("[DIFF_START]")){let p=o.match(/\[DIFF_START\]([\s\S]*?)(?:\[DIFF_END\]|$)/),y=(p?p[1].trim():"").split(`
|
|
332
|
+
`).map(x=>x.replace(/\r$/,"")),m=y.map(x=>({line:x,parsed:yl(x),pairContent:null})),w=[];for(let x=0;x<m.length;x++){let T=m[x];T.parsed&&(T.parsed.isR||T.parsed.isA)?w.push(T):w.length>0&&(qr(w),w=[])}w.length>0&&qr(w);let b=[],k=null,R=[],E=()=>{if(!R.length)return;let x=R;R=[],b.push(x.length===1?x[0]:{key:`${x[0].key}-chunk`,type:"chunk",blocks:x})};return y.forEach((x,T)=>{let $=T===y.length-1,_=m[T].parsed,S=null;_&&(S=Gr(_.content,n-17).split(`
|
|
333
|
+
`));let v=a(`${e.id||Date.now()}-diff-${T}`,"diff-line",x,{isFirstLine:T===0,isLastLine:$,pairContent:m[T].pairContent,wrappedLines:S});$&&e.isStreaming?(E(),k=v):(R.push(v),R.length>=mi&&E())}),E(),{completed:b,active:k?[k]:[]}}if(e.role==="system"||e.isLogo||e.isHelpRecord||e.isTerminalRecord||e.isHomeWarning||e.isImageStats||e.isAskRecord||e.isAboutRecord||e.isUpdateNotification||e.role==="user")return{completed:[a(`${e.id||Date.now()}-full`,"full-message",o)],active:[]};if(!o&&!e.isStreaming){let p={completed:[],active:[]};return qn.set(t,p),p}let r=[],h=null,d=[],c=null,l=()=>{if(!d.length)return;let p=d;d=[],c=null,r.push(p.length===1?p[0]:{key:`${e.id||"x"}-chunk-${p[0].key}`,type:"chunk",blocks:p})},u=(p,g=!1)=>{if(c!==null&&c!==p.type&&l(),d.push(p),c=p.type,d.length>=mi){if(e.isStreaming&&g)return;l()}};if(e.role==="think"){r.push(a(`${e.id}-header`,"think-header",""));let p=o.split(`
|
|
334
334
|
`);p.forEach((g,y)=>{let m=y===p.length-1;u(a(`${e.id}-${y}`,"think-line",g,{}),m)}),e.isStreaming||(l(),r.push({key:`${e.id}-footer-padding`,type:"think-footer-padding",text:""}))}else{let p=o.split(`
|
|
335
|
-
`),g=!1,y=[],m=!1,w=!1,
|
|
336
|
-
`),{isStreaming:!1})),g=!1,y=[]),r.push(a(`${e.id}-think-header-${
|
|
337
|
-
`),{isStreaming:!0}):r.push(a(`${e.id}-table-${
|
|
338
|
-
`),{isStreaming:!1})))):(g&&(l(),r.push(a(`${e.id}-table-${
|
|
339
|
-
`),{isStreaming:!1})),g=!1,y=[]),u(a(`${e.id}-${
|
|
335
|
+
`),g=!1,y=[],m=!1,w=!1,b="",k=0,R=0;p.forEach((E,x)=>{let T=x===p.length-1,$=E.trim().startsWith("|"),_=E.trim().startsWith("```");if(w){if(E.includes("</think>")||E.includes("<channel|>")||E.includes("</thought>")){let S=E.split(/(?:<\/(think|thought|thoughts)>|<channel\|>)/i),v=S[0]||"",I=S.slice(2).join("");v&&u(a(`${e.id}-think-${x}`,"think-line",v,{}),T&&!I),l(),r.push({key:`${e.id}-think-footer-${x}`,type:"think-footer-padding",text:""}),w=!1,I&&I.trim()&&u(a(`${e.id}-${x}`,"agent-line",I,{}),T)}else u(a(`${e.id}-think-${x}`,"think-line",E,{}),T);return}if(!m&&(E.includes("<think>")||E.includes("<|channel>thought")||E.includes("<thought>")||E.startsWith("<think")||E.startsWith("<|channel>thought"))){l(),g&&(r.push(a(`${e.id}-table-${x}`,"table",y.join(`
|
|
336
|
+
`),{isStreaming:!1})),g=!1,y=[]),r.push(a(`${e.id}-think-header-${x}`,"think-header","")),w=!0;let S=E.replace(/^(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought\s*)\r?\n?/i,"");if(S.includes("</think>")||S.includes("<channel|>")||S.includes("</thought>")){let v=S.split(/(?:<\/(think|thought|thoughts)>|<channel\|>)/i),I=v[0]||"",P=v.slice(2).join("");I&&u(a(`${e.id}-think-${x}`,"think-line",I,{}),T&&!P),l(),r.push({key:`${e.id}-think-footer-${x}`,type:"think-footer-padding",text:""}),w=!1,P&&P.trim()&&u(a(`${e.id}-${x}`,"agent-line",P,{}),T)}else S&&u(a(`${e.id}-think-${x}`,"think-line",S,{}),T);return}m?_?(m=!1,u(a(`${e.id}-code-close-${R}`,"code-fence-close","",{}),T)):(k++,u(a(`${e.id}-code-line-${x}`,"code-line",E,{lineNum:k,lang:b}),T)):_?(m=!0,R=x,k=0,b=E.trim().replace(/^```/,"").trim(),u(a(`${e.id}-code-open-${x}`,"code-fence-open",b,{}),T)):$?(g=!0,y.push(E),T&&(l(),e.isStreaming?h=a(`${e.id}-table-${x}`,"table",y.join(`
|
|
337
|
+
`),{isStreaming:!0}):r.push(a(`${e.id}-table-${x}`,"table",y.join(`
|
|
338
|
+
`),{isStreaming:!1})))):(g&&(l(),r.push(a(`${e.id}-table-${x}`,"table",y.join(`
|
|
339
|
+
`),{isStreaming:!1})),g=!1,y=[]),u(a(`${e.id}-${x}`,"agent-line",E,{}),T))}),!e.isStreaming&&e.workedDuration&&(l(),r.push(a(`${e.id}-worked-duration`,"worked-duration","")))}e.isStreaming&&d.length>0?h=d.length===1?d[0]:{key:`${e.id||"x"}-chunk-active-${d[0].key}`,type:"chunk",blocks:d}:l();let f={completed:r,active:h?[h]:[]};if(e.isStreaming){let p=new Map;if(r.forEach(g=>yi(g,p)),h&&yi(h,p),ds.set(s,{text:o,blocksMap:p}),ds.size>zr){let g=ds.keys().next().value;ds.delete(g)}}else{if(qn.set(t,f),qn.size>zr){let p=qn.keys().next().value;qn.delete(p)}ds.delete(s)}return f},xl={},bl=/<\/think>(\r?\n){2}/gi,kl=/(\r?\n){2}(?=\[?(?:tool:functions|tool\.functions|agent:generalist|agent\.generalist|\s*turn\s*:))/gi,gi=(e,n)=>{let t=!1;for(let o=0;o<n;o++)e[o]==="`"&&(t=!t);return t},Sl=/\[SYSTEM\][\s\S]*?\[\/SYSTEM\]|(?:<(think|thought|thoughts)>|<\|channel>thought)[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>)|\[ANSWER\][\s\S]*?(?:\[\/ANSWER\]|$)|\[TOOL RESULT\]:?\s*|^\s*(SUCCESS|ERROR):.*(\r?\n)?|\[\s*turn\s*:\s*(continue|finish)\s*\]|\[\[END\]\]|\[\s*turn\s*:?.*?$|\n\s*turn\s*:?.*?$|\[\s*(?:turn|ANSWER|TOOL).*?$|\n\nResponded on .*|\n\n\[Prompted on: .*\]|@\[TerminalName:.*?, ProcessId:.*?\]/gm,Tl=/(\$?\\?\/?\\rightarrow\$?|\$\\rightarrow\$)|(\$?\\?\/?\\leftarrow\$?|\$\\leftarrow\$)|(\$?\\?\/?\\uparrow\$?|\$\\uparrow\$)|(\$?\\?\/?\\downarrow\$?|\$\\downarrow\$)|(\$?\\?\/?\\leftrightarrow\$?|\$\\leftrightarrow\$)/gi,Rl=/\b(write_file|update_file|read_folder|view_file|exec_command|web_search|web_scrape|search_keyword|write_pdf|write_docx|generate_image)\b/gi,Is=!1,El=(e,n=!1)=>{if(!e)return e;let t=e.replace(/<\|channel>thought/gi,"<think>").replace(/<channel\|>/gi,"</think>");if(n)return t.replace(/^<(think|thought|thoughts)>/gi,"").replace(/<\/(think|thought|thoughts)>$/gi,"").replace(/^\r?\n+/,"").replace(/\r?\n+$/,"");let o=t.replace(bl,"</think>").replace(kl,(a,r,h,d)=>!Is&&gi(d,h)?a:"");o&&o.includes("[tool:")&&(o=o.replace(/<(\w+)(?:[^>]*)>\s*([\s\S]*?\[tool:[^\]]*\][\s\S]*?)\s*<\/\1>/gi,(a,r,h)=>h&&h.includes("[tool:")?h.trim():a),Is&&(o=o.replace(/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi,(a,r)=>r.includes("[tool:")?r.trim():a)),o=o.replace(/<(\w+)(?:[^>]*)>\r?\n?/gi,"").replace(/\r?\n?<\/\w+(?:[^>]*)>/gi,""));let s="tool:functions.",i="agent:generalist.";if(o.toLowerCase().includes(s)||o.toLowerCase().includes(i))for(;;){let a=o.toLowerCase(),r=a.indexOf(s),h=a.indexOf(i),d=s,c=r;if((r===-1||h!==-1&&h<r)&&(d=i,c=h),c===-1)break;if(!Is&&gi(o,c)){let w=c+d.length,b=a.indexOf(s,w),k=a.indexOf(i,w);if(b===-1&&k===-1)break;let R=-1,E=0;for(;;){let x=a.indexOf(s,E),T=a.indexOf(i,E),$=-1,_=s;if(x===-1&&T===-1)break;if(x===-1||T!==-1&&T<x?($=T,_=i):$=x,!gi(o,$)){R=$,d=_;break}E=$+_.length}if(R===-1)break;c=R}let l=c,u=!1,f=c-1;for(;f>=0&&/\s/.test(o[f]);)f--;f>=0&&o[f]==="["&&(l=f,u=!0);let p=0,g=!1,y=null,m=c;for(;m<o.length;){let w=o[m];if(!y&&(w==="'"||w==='"'||w==="`")?y=w:y&&w===y&&o[m-1]!=="\\"&&(y=null),y||(w==="("?(p++,g=!0):w===")"&&p--),g&&p===0&&!y){let b=m;if(u){let k=m+1;for(;k<o.length&&/\s/.test(o[k]);)k++;k<o.length&&o[k]==="]"&&(b=k)}o=o.substring(0,l)+o.substring(b+1);break}if(m++,m===o.length)return o=o.substring(0,l),o}}return o=o.replace(Sl,""),o=o.replace(Tl,a=>{let r=a.toLowerCase();return r.includes("leftrightarrow")?"\u2194":r.includes("rightarrow")?"\u2192":r.includes("leftarrow")?"\u2190":r.includes("uparrow")?"\u2191":r.includes("downarrow")?"\u2193":a}),o=o.replace(Rl,a=>xl[a.toLowerCase()]||a),o.trim()},Sf=()=>{qn.clear(),ds.clear()};var xi=async(e,n={})=>{let t=O(e),o=t.path;if(!o)return'ERROR: Missing "path" argument for PatchFile.';let{patchPairs:s,allowMultiple:i,error:a}=vo(t);if(a)return`ERROR: ${a}`;if(s.length===0)return"ERROR: No valid replacement pairs found. Use searchContent1, newContent1, etc.";let r=t.allowMultiple!==void 0?t.allowMultiple===!0||String(t.allowMultiple).toLowerCase()==="true":i,h=$l.resolve(process.cwd(),o);try{if(!wi.existsSync(h))return`ERROR: File [${o}] does not exist. Use WriteFile instead.`;let d=n.forcedContent||wi.readFileSync(h,"utf8");d.startsWith("\uFEFF")&&(d=d.slice(1));let c=d.replace(/\r\n/g,`
|
|
340
340
|
`).replace(/\r/g,`
|
|
341
|
-
`),{content:l,results:u}=
|
|
341
|
+
`),{content:l,results:u}=Io(c,s,{allowMultiple:r}),f=u.filter(m=>!m.success),p=u.filter(m=>m.success);if(p.length===0)return`ERROR: Patch Failed to apply to [${o}].
|
|
342
342
|
${f.map(m=>` \u2022 ${m.error}`).join(`
|
|
343
|
-
`)}`;await
|
|
343
|
+
`)}`;await ut.recordFileChange(h,c),wi.writeFileSync(h,l,"utf8");let{systemSettings:g}=await Ft(),y=Oo(c,l,u,12,g?.compressToolResults);return f.length>0?`SUCCESS: File [${o}] updated with some blocks failed. [${p.length}/${s.length}] blocks applied.
|
|
344
344
|
|
|
345
345
|
Failures:
|
|
346
346
|
${f.map(m=>` \u2022 ${m.error}`).join(`
|
|
@@ -348,21 +348,21 @@ ${f.map(m=>` \u2022 ${m.error}`).join(`
|
|
|
348
348
|
|
|
349
349
|
${y}`:`SUCCESS: File [${o}] updated. [${u.length}/${s.length}] blocks applied.
|
|
350
350
|
|
|
351
|
-
${y}`}catch(d){let c=d instanceof Error?d.message:String(d);return`ERROR: Failed to update file [${o}]: ${c}`}};import fs from"fs";import bi from"path";var
|
|
351
|
+
${y}`}catch(d){let c=d instanceof Error?d.message:String(d);return`ERROR: Failed to update file [${o}]: ${c}`}};import fs from"fs";import bi from"path";var _l=new Set([".git","node_modules",".gemini","dist","build",".next","out",".cache","bin","obj","vendor","venv",".idea",".gradle",".terraform","target","coverage",".vscode",".svn",".hg",".fslckout",".github",".gitlab",".circleci",".gitea",".gitee",".lerna",".changeset",".nx",".npm",".yarn",".pnpm-store",".expo",".nuxt",".svelte-kit",".docusaurus",".turbo",".vercel","bower_components",".netlify",".vuepress",".quasar",".output",".angular","jspm_packages",".parcel-cache",".rollup.cache",".rspack",".vitepress","__pycache__",".pytest_cache",".mypy_cache",".tox",".poetry","env","vhdl",".ipynb_checkpoints",".jupyter",".conda",".pdm-build",".bundle",".yardoc",".metadata","App_Data","ClientBin",".cargo",".rustc_info",".go","Godeps","_vendor",".rake_tasks","CMakefiles",".wakatime",".dart_tool",".fvm",".cocoapods","Pods",".pub-cache",".symlinks","DerivedData",".xcworkspace",".serverless",".aws",".gcloud",".azure",".kube",".vagrant",".docker","postgres-data","redis-data","mongo-data",".Spotlight-V100",".Trashes","$RECYCLE.BIN","System Volume Information",".DocumentRevisions-V100",".fseventsd","AppData","Application Data","Local","LocalLow","Roaming","$WinREAgent","$WINDOWS.~BT","$WINDOWS.~WS","scw","System32","SysWOW64",".AppleDouble",".AppleDB",".AppleDesktop","_CodeSignature",".cmio",".LSOverride",".localized",".TemporaryItems",".Trash",".Trash-0",".Trash-1000",".gvfs",".local",".config",".dbus",".fontconfig",".snap",".var",".lost+found","lost+found",".thumb",".thumbnails","EFI","boot","grub","logs","log",".nyc_output",".sonar",".ruff_cache",".VSCodeCounter"]),Cl=e=>_l.has(e)||e.startsWith(".pnpm"),Ml=e=>{try{let n=String(e.getMonth()+1).padStart(2,"0"),t=String(e.getDate()).padStart(2,"0"),o=String(e.getHours()).padStart(2,"0"),s=String(e.getMinutes()).padStart(2,"0");return`${n}-${t} ${o}:${s}`}catch{return"N/A"}},ki=async e=>{let n=O(e),t=n.path||null;if(!t)return"ERROR: No directory path provided.";let o=1;if(n.recurse!==void 0&&n.recurse!==null)if(typeof n.recurse=="number")o=n.recurse;else if(typeof n.recurse=="boolean")o=n.recurse?2:1;else{let i=parseInt(String(n.recurse).trim(),10);o=isNaN(i)?1:i}o=Math.max(1,Math.min(3,o));let s=bi.resolve(process.cwd(),t);try{if(!fs.existsSync(s))return`ERROR: Path [${t}] does not exist.`;if(!fs.statSync(s).isDirectory())return`ERROR: Path [${t}] is a file, not a directory. Use ReadFile instead.`;if(o===1){let g=fs.readdirSync(s),y=g.length,m=150,w=g.slice(0,m),b=[];for(let E of w){let x=bi.join(s,E),T={name:E,type:"unknown",size:"N/A",mtime:"N/A"};try{let $=fs.statSync(x);T={name:E,type:$.isDirectory()?"directory":"file",size:($.size/1024).toFixed(1)+"KB",mtime:Ml($.mtime)}}catch{T.type="inaccessible"}b.push(T)}let k=b.map(E=>E.type==="directory"?`${E.name}/`:`${E.name} (${E.size}, ${E.mtime})`).join(`
|
|
352
352
|
`),R=`
|
|
353
353
|
|
|
354
354
|
(Total items in folder: ${y})`;return y>m&&(R=`
|
|
355
355
|
|
|
356
|
-
TRUNCATED: Showing first ${m} of ${y} items.`),g.length=0,w.length=0,
|
|
356
|
+
TRUNCATED: Showing first ${m} of ${y} items.`),g.length=0,w.length=0,b.length=0,`Detailed folder stats for [${t}]:
|
|
357
357
|
|
|
358
|
-
${
|
|
358
|
+
${k}${R}`}let a=0,r=0,h=0,d=500,c=!1,l=(g,y,m=1)=>{if(y>o||c)return[];let w=[];try{w=fs.readdirSync(g)}catch{return[`${" ".repeat(m-1)}[Inaccessible Directory]`]}let b=[],k=[];for(let T of w){let $=bi.join(g,T),_=!1;try{_=fs.statSync($).isDirectory()}catch{}_?b.push({name:T,fullPath:$}):k.push({name:T,fullPath:$})}b.sort((T,$)=>T.name.localeCompare($.name)),k.sort((T,$)=>T.name.localeCompare($.name));let R=[],E=" ".repeat(m-1);for(let T of b){if(h>=d){c=!0,R.push(`${E}[Truncated - Maximum item limit reached (${d})]`);break}if(h++,a++,R.push(`${E}${T.name}/`),y<o&&!Cl(T.name)){let $=l(T.fullPath,y+1,m+1);R.push(...$)}}let x=[];for(let T of k){if(h>=d){c=!0,R.push(`${E}[Truncated - Maximum item limit reached (${d})]`);break}h++,r++;let $="N/A";try{$=(fs.statSync(T.fullPath).size/1024).toFixed(1)+"KB"}catch{}x.push(`${T.name} (${$})`)}return x.length>0&&R.push(`${E}${x.join("; ")}`),R},f=l(s,1,1).join(`
|
|
359
359
|
`),p=`
|
|
360
360
|
|
|
361
361
|
(Total items scanned: ${h}, Directories: ${a}, Files: ${r})`;return c&&(p=`
|
|
362
362
|
|
|
363
363
|
TRUNCATED: Scan capped at ${d} items. (Directories: ${a}, Files: ${r})`),`Detailed directory tree for [${t}] (recursive depth: ${o}):
|
|
364
364
|
|
|
365
|
-
${f}${p}`}catch(i){let a=i instanceof Error?i.message:String(i);return`ERROR: Failed to read folder [${t}]: ${a}`}};var
|
|
365
|
+
${f}${p}`}catch(i){let a=i instanceof Error?i.message:String(i);return`ERROR: Failed to read folder [${t}]: ${a}`}};var Si=async(e,n)=>{let t=O(e),{question:o}=t;if(!o)return'ERROR: Missing "question" argument for ask.';if(!n.onAskUser)return"ERROR: onAskUser callback not provided in tool context.";let s=[];Object.keys(t).forEach(i=>{if(i.startsWith("option")){let a=t[i];if(typeof a=="string"&&a.includes("::")){let[r,h]=a.split("::");s.push({id:i,label:r.trim(),description:h.trim()})}else s.push({id:i,label:String(a).trim(),description:""})}});try{return`USER CHOOSE: ${await n.onAskUser(o,s)}`}catch(i){return`ERROR: Failed to get user input: ${i instanceof Error?i.message:String(i)}`}};import Al from"puppeteer";import Os from"path";import us from"fs-extra";import{PDFDocument as vl}from"pdf-lib";var Ti=async e=>{let{path:n,content:t,orientation:o="portrait",margin:s="0px"}=O(e);if(!n)return'ERROR: Missing "path" argument for write_pdf.';if(!t)return'ERROR: Missing "content" (HTML/CSS) for write_pdf.';let i=Os.resolve(process.cwd(),n),a=null;try{await us.ensureDir(Os.dirname(i)),await ut.recordFileChange(i);let r=cs();a=await Al.launch({headless:!0,executablePath:r.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let h=await a.newPage(),d=t,c={},l=async x=>{if(!x||x.startsWith("http://")||x.startsWith("https://")||x.startsWith("data:"))return null;try{let T=Os.resolve(process.cwd(),x);if(await us.pathExists(T)){let $=Os.extname(T).toLowerCase().replace(".","")||"png",_=$==="jpg"?"jpeg":$==="svg"?"svg+xml":$,S=await us.readFile(T,"base64");return`data:image/${_};base64,${S}`}}catch{}return null},u=/<link[^>]+href=["']([^"']+)["']/gi,f={},p;for(;(p=u.exec(t))!==null;){let x=p[1],T=p[0];if(x&&T.toLowerCase().includes("stylesheet")&&!x.startsWith("http://")&&!x.startsWith("https://")&&!x.startsWith("data:"))try{let $=Os.resolve(process.cwd(),x);if(await us.pathExists($)){let _=await us.readFile($,"utf-8");f[T]=`<style>${_}</style>`}}catch{}}for(let[x,T]of Object.entries(f))d=d.split(x).join(T);let g=/<img[^>]+src=["']([^"']+)["']/gi;for(;(p=g.exec(d))!==null;){let x=p[1];if(x&&!c[x]){let T=await l(x);T&&(c[x]=T)}}let y=/url\(\s*['"]?([^'")]+?)['"]?\s*\)/gi;for(;(p=y.exec(d))!==null;){let x=p[1].trim();if(x&&!c[x]){let T=await l(x);T&&(c[x]=T)}}for(let[x,T]of Object.entries(c)){let $=x.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&"),_=new RegExp(`(src=["'])(${$})(["'])`,"gi");d=d.replace(_,`$1${T}$3`);let S=new RegExp(`url\\(\\s*(['"]?)(${$})\\1\\s*\\)`,"gi");d=d.replace(S,`url($1${T}$1)`)}let m=`
|
|
366
366
|
<style>
|
|
367
367
|
@page {
|
|
368
368
|
margin: ${s};
|
|
@@ -392,7 +392,7 @@ ${f}${p}`}catch(i){let a=i instanceof Error?i.message:String(i);return`ERROR: Fa
|
|
|
392
392
|
</style>
|
|
393
393
|
<div class="watermark">Generated by FluxFlow CLI (AI)</div>
|
|
394
394
|
${d}
|
|
395
|
-
`;await h.setContent(m,{waitUntil:"networkidle0",timeout:18e4});let w=await h.pdf({format:"A4",landscape:String(o).toLowerCase()==="landscape",margin:{top:s,right:s,bottom:s,left:s},printBackground:!0}),
|
|
395
|
+
`;await h.setContent(m,{waitUntil:"networkidle0",timeout:18e4});let w=await h.pdf({format:"A4",landscape:String(o).toLowerCase()==="landscape",margin:{top:s,right:s,bottom:s,left:s},printBackground:!0}),b=await vl.load(w),k=Os.basename(n);b.setTitle(`FluxFlow_${k}`),b.setAuthor("FluxFlow CLI"),b.setSubject("Generated with Agentic AI System"),b.setKeywords(["FluxFlow","AI","Agentic","Automated"]),b.setCreator("FluxFlow PDF Engine"),b.setProducer("FluxFlow (Generative AI)");let R=await b.save();await us.writeFile(i,R);let E=await us.stat(i);return`SUCCESS: PDF generated successfully at [${n}] (${(E.size/1024).toFixed(2)} KB).`}catch(r){let h=r instanceof Error?r.message:String(r);return`ERROR: Failed to generate PDF [${n}]: ${h}`}finally{a&&await a.close()}};import Kr from"fs-extra";import Ri from"path";import Il from"html-to-docx";var Ei=async e=>{let{path:n,content:t}=O(e);if(!n)return'ERROR: Missing "path" argument for write_docx.';if(!t)return'ERROR: Missing "content" (HTML) for write_docx.';let o=Ri.resolve(process.cwd(),n);try{await Kr.ensureDir(Ri.dirname(o)),await ut.recordFileChange(o);let s=Ri.basename(n),i=t.includes("<html")?t:`
|
|
396
396
|
<!DOCTYPE html>
|
|
397
397
|
<html lang="en">
|
|
398
398
|
<head>
|
|
@@ -403,37 +403,37 @@ ${f}${p}`}catch(i){let a=i instanceof Error?i.message:String(i);return`ERROR: Fa
|
|
|
403
403
|
${t}
|
|
404
404
|
</body>
|
|
405
405
|
</html>
|
|
406
|
-
`,a=await
|
|
407
|
-
- Size: ${(a.length/1024).toFixed(1)} KB`}catch(s){let i=s instanceof Error?s.message:String(s);return`ERROR: Failed to generate DOCX [${n}]: ${i}`}};import
|
|
406
|
+
`,a=await Il(i,null,{title:`FluxFlow_${s}`,creator:"FluxFlow CLI",description:"Generated by Agentic AI System",table:{row:{cantSplit:!0}},footer:!0,pageNumber:!0});return await Kr.writeFile(o,a),`SUCCESS: Word document [${n}] generated successfully.
|
|
407
|
+
- Size: ${(a.length/1024).toFixed(1)} KB`}catch(s){let i=s instanceof Error?s.message:String(s);return`ERROR: Failed to generate DOCX [${n}]: ${i}`}};import _i from"fs/promises";import hs from"path";import $i from"fast-glob";import{Minimatch as Yr}from"minimatch";async function Zs(e,n,t=e,o=1){if(o>12)return[];let s=[],i;try{i=await _i.readdir(e,{withFileTypes:!0})}catch{return[]}for(let a of i){let r=hs.join(e,a.name),h=hs.relative(t,r),d=h.split(hs.sep).map(u=>u.toLowerCase()),c=a.name.toLowerCase();if(!n.some(u=>{let f=u.toLowerCase();return f.startsWith(".")&&c.endsWith(f)?!0:d.some(p=>p===f||p.startsWith(".pnpm"))}))if(a.isDirectory()){let u=await Zs(r,n,t,o+1);s=s.concat(u)}else a.isFile()&&s.push({fullPath:r,relativePath:h})}return s}function Ol(e,n,t=1/0){if(e===n)return 0;if(e.length===0)return n.length;if(n.length===0)return e.length;if(Math.abs(e.length-n.length)>t)return t+1;let o=Array.from({length:n.length+1},(s,i)=>i);for(let s=1;s<=e.length;s++){let i=[s],a=s;for(let r=1;r<=n.length;r++){let h=e[s-1]===n[r-1]?0:1,d=Math.min(i[r-1]+1,o[r]+1,o[r-1]+h);i.push(d),d<a&&(a=d)}if(o=i,a>t)return t+1}return o[n.length]}function Ll(e,n){if(!e||!n)return!1;let t=e.toLowerCase(),o=n.toLowerCase();if(t.includes(o))return!0;let s=t.split(/[^a-z0-9]+/).filter(a=>a.length>0),i=o.split(/[^a-z0-9]+/).filter(a=>a.length>1||o.length===1&&a.length>0);return i.length===0?!1:i.every(a=>{let r=a.length<=2?0:a.length<=5?1:2;for(let h of s)if(h.includes(a)||a.length>=3&&h.length>=3&&Math.abs(h.length-a.length)<=r&&Ol(a,h,r)<=r)return!0;return!1})}var eo=async e=>{let{keyword:n,path:t,fuzzy:o,subString:s,regex:i}=O(e);if(n==null)return'ERROR: Missing "keyword" argument.';let a=String(n),r=g=>g===!0||g==="true"||g===1||g==="1"||g==="yes",h=i===!1||i==="false"||i===0||i==="0"||i==="no",d=i===!0||i==="true"||i===1||i==="1"||i==="yes",c=r(o)||r(s),l=null,u=null;if(h)c||(u=new RegExp(`(?<![\\w])${a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\\w])`,"i"));else{try{l=new RegExp(a,"i")}catch(g){if(d)return`ERROR: Invalid regex pattern "${a}": ${g.message}`}u=new RegExp(`(?<![\\w])${a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\\w])`,"i")}let f=[".git","node_modules",".gemini","dist","build",".next","out",".cache","bin","obj","vendor","venv",".idea",".gradle",".terraform","target","coverage",".vscode",".svn",".hg",".fslckout",".github",".gitlab",".circleci",".gitea",".gitee",".lerna",".changeset",".nx",".npm",".yarn",".pnpm-store",".pnpm",".expo",".nuxt",".svelte-kit",".docusaurus",".turbo",".vercel","bower_components",".netlify",".vuepress",".quasar",".output",".angular","jspm_packages",".parcel-cache",".rollup.cache",".rspack",".vitepress","__pycache__",".pytest_cache",".mypy_cache",".tox",".poetry","env","vhdl",".ipynb_checkpoints",".jupyter",".conda",".pdm-build",".bundle",".yardoc",".metadata","App_Data","ClientBin",".cargo",".rustc_info",".go","Godeps","_vendor",".rake_tasks","CMakefiles",".wakatime",".dart_tool",".fvm",".cocoapods","Pods",".pub-cache",".symlinks","DerivedData",".xcworkspace",".serverless",".aws",".gcloud",".azure",".kube",".vagrant",".docker","postgres-data","redis-data","mongo-data",".Spotlight-V100",".Trashes","$RECYCLE.BIN","System Volume Information",".DocumentRevisions-V100",".fseventsd","AppData","Application Data","Local","LocalLow","Roaming","$WinREAgent","$WINDOWS.~BT","$WINDOWS.~WS","scw","System32","SysWOW64",".AppleDouble",".AppleDB",".AppleDesktop","_CodeSignature",".cmio",".LSOverride",".localized",".TemporaryItems",".Trash",".Trash-0",".Trash-1000",".gvfs",".local",".config",".dbus",".fontconfig",".snap",".var",".lost+found","lost+found",".thumb",".thumbnails","EFI","boot","grub","logs","log",".nyc_output",".sonar",".ruff_cache",".VSCodeCounter",".exe",".dll",".so",".dylib",".png",".jpg",".jpeg",".gif",".ico",".svg",".webp",".mp3",".mp4",".avi",".zip",".tgz",".tar",".gz",".7z",".rar",".pdf",".docx",".xlsx",".pptx",".woff",".woff2",".ttf",".eot"],p=150;try{let g=[],y=process.cwd(),m=null;if(t){let I=t.split(";").map(U=>U.trim()).filter(Boolean),P=I.some(U=>U.startsWith("!"));if(I.some(U=>$i.isDynamicPattern(U)||/[*?{}[\]()|+]/.test(U))){m="glob";let U=t.replace(/\\/g,"/"),Y=I.map(N=>N.replace(/\\/g,"/")),ie=f.map(N=>N.startsWith(".")?`**/*${N}`:`**/${N}/**`);if(P&&!I.some(N=>!N.startsWith("!"))){let N=await Zs(y,f,y),W=M=>M.endsWith("/")?M+"**":M,re=Y.filter(M=>M.startsWith("!")).map(M=>W(M.slice(1))),Re=Y.filter(M=>!M.startsWith("!")).map(W);g=N.filter(M=>{let F=M.relativePath.replace(/\\/g,"/"),V=Re.length===0||Re.some(Ne=>{try{return new Yr(Ne).match(F)}catch{return!1}}),J=re.some(Ne=>{try{return new Yr(Ne).match(F)}catch{return!1}});return V&&!J})}else{let N=Y.some(re=>/[\(\)\|]|\.\*/.test(re)),W=[];if(!N)try{W=await $i(Y,{cwd:y,ignore:ie,dot:!0,onlyFiles:!0,absolute:!1})}catch{W=[]}if(W.length===0&&(N||$i.isDynamicPattern(U))){let re=U.match(/^([^\*\?\(\)\|\[\]\s]+)\//),Re=re&&!/[\*\?\(\)\|\[\]]/.test(re[1])?hs.resolve(y,re[1]):y,M=await Zs(Re,f,y);try{let F=U.replace(/^\.\//,"");F=F.replace(/\.\*\/(\\.|[^\/])/g,".*$1"),!F.startsWith("^")&&!F.startsWith(".*")&&(F=`.*${F}`);let V=new RegExp(F.endsWith("$")?F:`${F}$`,"i");g=M.filter(J=>{let Ne=J.relativePath.replace(/\\/g,"/");return V.test(Ne)})}catch{g=[]}}else g=W.map(re=>({fullPath:hs.resolve(y,re),relativePath:re}))}}else{let U=t.replace(/[\/\\]+$/,""),Y=hs.resolve(y,U);try{let ie=await _i.stat(Y);if(ie.isDirectory())m="dir",g=await Zs(Y,f,y);else if(ie.isFile())m="file",g.push({fullPath:Y,relativePath:hs.relative(y,Y)});else return`ERROR: Path is neither a file nor a directory: ${t}`}catch{return`ERROR: Path not found: ${t}`}}}else g=await Zs(y,f);let w=g.map(async I=>{try{let P=await _i.readFile(I.fullPath,"utf-8");if(P.includes("\0"))return[];let j=P.split(/\r?\n/),U=[];for(let ie=0;ie<j.length;ie++)(c?j[ie].toLowerCase().includes(a.toLowerCase())||Ll(j[ie],a):h?u&&u.test(j[ie]):l&&l.test(j[ie])||u&&u.test(j[ie]))&&U.push({line:ie+1,content:j[ie].trim()});return U.length===0?null:{path:I.relativePath.replace(/\\/g,"/"),matches:U}}catch{return[]}}),b=await Promise.all(w),k=[],R=0;for(let I of b){if(!I||!I.matches)continue;if(R>=p)break;let P=p-R,j=I.matches.slice(0,P);k.push({path:I.path,matches:j}),R+=j.length}typeof global.gc=="function"&&global.gc();let E=c?"(fuzzy mode)":d?"(regex mode)":h?"(keyword mode)":"(standard mode)";if(k.length===0){let I=m==="file"?` in '${t}'`:m==="dir"||m==="glob"?` in '${t}'`:". Try to specify files",P=m==="dir"?"[DIR]":m==="glob"?"[GLOB]":"";return`${P}${P?" ":""}Found 0 matches of '${a}'${I}${E?` ${E}`:""}`}let x=E?` ${E}`:"",T=`${k.length} file${k.length===1?"":"s"}`,$=`${R} match${R===1?"":"es"}`,_;m==="file"?_=`Found ${$} of '${a}' in '${t}'${x}:`:m==="dir"||m==="glob"?_=`Found ${$} of '${a}' in '${t}' across ${T}${x}:`:_=`Found ${$} of '${a}' across ${T}${x}:`;let S=m==="dir"?"[DIR]":m==="glob"?"[GLOB]":"",v=`${S}${S?" ":""}${_}
|
|
408
408
|
|
|
409
|
-
`;for(let I of
|
|
410
|
-
`;for(let
|
|
409
|
+
`;for(let I of k){v+=`${I.path}
|
|
410
|
+
`;for(let P of I.matches)v+=` ${P.line}: ${P.content}
|
|
411
411
|
`;v+=`
|
|
412
|
-
`}return v.trimEnd()}catch(g){return`ERROR: ${g.message}`}};import
|
|
413
|
-
`)[0].match(/for\s*(?:await\s*)?\((.*)\)/);return s?`for (${
|
|
414
|
-
`)[0],60);if(n==="pair"){let o=e.childForFieldName("key");return o?
|
|
412
|
+
`}return v.trimEnd()}catch(g){return`ERROR: ${g.message}`}};import Vr from"fs-extra";import Ci from"path";var Dl=(e,n={})=>{try{if(e.length<8||e[0]!==137||e[1]!==80||e[2]!==78||e[3]!==71)return e;let t=[],o=[];for(let a=0;a<256;a++){let r=a;for(let h=0;h<8;h++)r&1?r=3988292384^r>>>1:r=r>>>1;o[a]=r}let s=a=>{let r=4294967295;for(let h=0;h<a.length;h++)r=o[(r^a[h])&255]^r>>>8;return(r^4294967295)>>>0},i=(a,r)=>{let h=Buffer.from(a,"ascii"),d=Buffer.from(r,"utf-8"),c=h.length+1+d.length,l=Buffer.alloc(8+c+4);l.writeUInt32BE(c,0),l.write("tEXt",4,"ascii"),h.copy(l,8),l[8+h.length]=0,d.copy(l,8+h.length+1);let u=s(l.subarray(4,8+c));return l.writeUInt32BE(u,8+c),l};for(let[a,r]of Object.entries(n))r!=null&&t.push(i(a,String(r)));if(t.length===0)return e;if(e.subarray(12,16).toString("ascii")==="IHDR"){let r=e.subarray(0,33),h=e.subarray(33);return Buffer.concat([r,...t,h])}return e}catch{return e}},Mi=async(e,n={})=>{let t=O(e),o=t.prompt||t.text,s=t.path||t.outputPath||t.output||"generated_image.png",i=t.ratio;if(!o)return'ERROR: Missing "prompt" argument for generate_image.';let a=["nsfw","naked","nudity","nude","porn","sex","xxx","erotic","gore","bloody","violence","abuse","suicide","murder","hentai","pedophile","rape"],r=o.toLowerCase();if(a.some(d=>r.includes(d)))return"ERROR: Prompt blocked by system safety filter (inappropriate or unsafe content detected).";try{let d=await Ft();if(!await Lr(d))return`ERROR: Insufficient Quota for selected quality. Either tell user reduce quality or wait for next refresh cycle (${(await Dr()).nextResetMin||60}m).`;let l=d.imageSettings||{keyType:"Default",quality:"Low-High",apiKey:""},u=l.keyType==="Custom"&&l.apiKey?l.apiKey:FALLBACK_IMAGE_KEY,p={Low:"flux","Low-High":"zimage",Medium:"gptimage","Medium-High":"gptimage",High:"qwen-image",Ultra:"gptimage-large",Premium:"nanobanana-pro"}[l.quality]||"zimage",g=1024,y=1024;if(i){let P=i.replace(/\s+/g,"");P==="16:9"?(g=1024,y=576):P==="9:16"?(g=576,y=1024):P==="4:3"?(g=1024,y=768):P==="3:4"?(g=768,y=1024):P==="1:1"&&(g=1024,y=1024)}let m=Math.floor(Math.random()*1e7),b=`https://gen.pollinations.ai/image/${encodeURIComponent(o)}?model=${p}&width=${g}&height=${y}&seed=${m}&enhance=true&reasoning=high&quality=high&negative=${encodeURIComponent("deformed, distorted, disfigured, poorly drawn, bad anatomy, wrong anatomy, extra limb, missing limb, floating limbs, disconnected limbs, mutation, mutated hands and fingers, blurry, low quality, low resolution, extra fingers, censored, watermarks, signatures")}`,k=await fetch(b,{method:"GET",headers:{Authorization:`Bearer ${u}`}});if(!k.ok){let P=k.status,j="";try{j=await k.text()}catch{}return P===402||j.includes("Insufficient balance")||j.includes("PAYMENT_REQUIRED")?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed with status [${P}]: ${j||"Unknown API Error"}`}if((k.headers.get("content-type")||"").includes("application/json")){let P=await k.json();return P.status===402||P.error&&P.error.code==="PAYMENT_REQUIRED"?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed: ${P.error?.message||JSON.stringify(P)}`}let E=await k.arrayBuffer(),x=Buffer.from(E),T={Title:o,Description:"Generated via FluxFlow CLI",Software:"FluxFlow CLI",Author:"FluxFlow","Creation Time":new Date().toISOString(),Prompt:o,Model:`Fluxflow:${p}`,Ratio:i||"1:1",Seed:String(m)};x=Dl(x,T);let $=Ci.resolve(process.cwd(),s);await Vr.ensureDir(Ci.dirname($)),await ut.recordFileChange($),await Vr.writeFile($,x),await Pr(d);let _=Ci.extname(s).toLowerCase(),v={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".webp":"image/webp"}[_]||"image/png";return n.isMultiModal!==!1?{text:`SUCCESS: Image successfully generated from prompt [${o}] and saved to [${s}]. Output attached to multimodal part`,binaryPart:{inlineData:{data:x.toString("base64"),mimeType:v}}}:`SUCCESS: Image successfully generated from prompt [${o}] and saved to [${s}].`}catch(d){return`ERROR: Failed during image generation: ${d instanceof Error?d.message:String(d)}`}};var to=async(e,n={})=>{let t=i=>{let a=new RegExp(`${i}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),r=e.match(a);return r?r[2].trim():null},o=t("id"),s=t("summary");if(!o||!s)return"ERROR: Missing 'id' or 'summary' for saveSummary tool.";try{let i=X(Qt,{}),a=X(vn,{});return a[o]=s,delete i[o],he(vn,a),he(Qt,i),`SUCCESS: Saved summary and purged raw memories for chat [${o}].`}catch(i){let a=i instanceof Error?i.message:String(i);return`ERROR: Failed to save summary for chat [${o}]: ${a}`}};var Ls=async(e,n={})=>{let o=(s=>{let i=new RegExp(`${s}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),a=e.match(i);return a?a[2].trim():null})("id");if(!o)return"ERROR: Missing 'id' parameter for addMemScore tool.";try{let s=X(Pt,[]),i=!1,a=[];for(let c of s)c.score===void 0&&(c.score=.5),c.id===o?(c.score=Math.min(2,c.score+.2),i=!0):(c.score*=.98,c.score<.05&&(c.score=0)),c.score=Math.round(c.score*1e5)/1e5,c.score>0&&a.push(c);if(he(Pt,a),!i)return`WARNING: Memory ID [${o}] not found. Other memories decayed by -0.01.`;let r=a.find(c=>c.id===o),h=r?r.score.toFixed(2):"deleted (score <= 0)",d=s.length-a.length;return`SUCCESS: Adjusted memory scores. Target [${o}] is now ${h}.${d>0?` Purged ${d} decayed memories.`:""}`}catch(s){let i=s instanceof Error?s.message:String(s);return`ERROR: Failed to adjust memory score for [${o}]: ${i}`}};import vi from"fs-extra";import ms from"path";import{createRequire as Nl}from"module";import ps from"fs-extra";import Ai from"path";import Pl from"https";var Jr={js:"tree-sitter-javascript.wasm",jsx:"tree-sitter-javascript.wasm",ts:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm",py:"tree-sitter-python.wasm",c:"tree-sitter-c.wasm",cpp:"tree-sitter-cpp.wasm",java:"tree-sitter-java.wasm",html:"tree-sitter-html.wasm"};async function Fl(e,n=null){let t=n||`https://unpkg.com/tree-sitter-wasms@0.1.13/out/${e}`,o=Ai.join(as,e);return await ps.ensureDir(as),new Promise((s,i)=>{let a={headers:{"User-Agent":"FluxFlow-Agent"}};Pl.get(t,a,r=>{if([301,302,307,308].includes(r.statusCode)&&r.headers.location){let d=r.headers.location;if(!d.startsWith("http")){let c=new URL(t);d=`${c.protocol}//${c.host}${d}`}Fl(e,d).then(s).catch(i);return}if(r.statusCode!==200){i(new Error(`Failed to download ${e}: HTTP ${r.statusCode}`));return}let h=ps.createWriteStream(o);r.pipe(h),h.on("finish",()=>{h.close(),s()})}).on("error",r=>{ps.existsSync(o)&&ps.unlink(o,()=>{}),i(r)})})}function bu(e){let n=Ai.join(as,e);return ps.existsSync(n)}async function ku(e){let n=Ai.join(as,e);ps.existsSync(n)&&await ps.unlink(n)}var Zr=Nl(import.meta.url),Xr=Zr("web-tree-sitter"),Qr=!1,ea=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"]),ta=new Set(["export_statement","lexical_declaration","variable_declaration","variable_declarator","pair","assignment_expression"]);function mn(e,n=50){if(!e)return"";let t=e.replace(/\s+/g," ").trim();return t.length>n?t.substring(0,n-3)+"...":t}function na(e){let n=e.type;if(n==="if_statement"){let o=e.childForFieldName("condition");return o?`if (${mn(o.text,40)})`:"if"}if(n==="else_clause")return"else";if(n==="while_statement"||n==="do_statement"){let o=e.childForFieldName("condition");return`${n.split("_")[0]} (${o?mn(o.text,40):""})`}if(n==="for_statement"||n==="for_in_statement"||n==="for_of_statement"){let s=e.text.split(`
|
|
413
|
+
`)[0].match(/for\s*(?:await\s*)?\((.*)\)/);return s?`for (${mn(s[1],40)})`:"for"}if(n==="switch_statement"){let o=e.childForFieldName("value");return`switch (${o?mn(o.text,40):""})`}if(n==="try_statement")return"try";if(n==="catch_clause")return"catch";if(n==="element"||n==="script_element"||n==="style_element"||n==="jsx_element"||n==="jsx_self_closing_element"){let o=e.childForFieldName("opening_element")||e.childForFieldName("start_tag")||e.children.find(i=>i.type==="start_tag")||e,s=o.childForFieldName("name")||o.childForFieldName("tag_name")||o.children.find(i=>i.type==="tag_name");return s?`<${mn(s.text,30)}>`:null}if(["import_declaration","import_from_statement","import_statement","preproc_include"].includes(n))return mn(e.text.split(`
|
|
414
|
+
`)[0],60);if(n==="pair"){let o=e.childForFieldName("key");return o?mn(o.text.replace(/["']/g,""),40):null}if(n==="assignment_expression"){let o=e.childForFieldName("left");return o?`${mn(o.text,30)} = ...`:null}if(n==="variable_declarator"){let o=e.childForFieldName("name")||e.children.find(s=>["identifier","object_pattern","array_pattern"].includes(s.type));return o?mn(o.text,40):null}let t=e.childForFieldName("name")||e.childForFieldName("declarator")||e.children.find(o=>["identifier","type_identifier","field_identifier","property_identifier","shorthand_property_identifier"].includes(o.type));if(t){if(t.type.includes("declarator")){let o=t.descendantsOfType("identifier")[0]||t.descendantsOfType("field_identifier")[0];if(o)return mn(o.text,40)}return mn(t.text,40)}if(["arrow_function","function_expression","function_declaration"].includes(n)){let o=e.parent;for(;o&&o.type!=="program";){let s=na(o);if(s)return s;if(!ta.has(o.type))break;o=o.parent}}return null}function Bl(e){let n=[];function t(o){for(let s of o.children)ea.has(s.type)?n.push(s):t(s)}return t(e),n}function Ul(e){return e.replace(/_([a-z])/g,n=>n[1].toUpperCase())}function sa(e,n=0,t=!0,o="",s=null,i=12){let a=e.type,r=na(e),h=ea.has(a)||n===0,d=Bl(e),c=h&&n>0&&(ta.has(a)&&d.length>0||r!==null&&r===s&&d.length>0),l="",u=o,f=n,p=s;if(h&&!c){let g=e.startPosition.row+1,y=e.endPosition.row+1,m=Ul(a),w=r?`${m} [${r}]`:m;n===0?(l+=`\u{1F4C1} ROOT (Lines: ${g}-${y})
|
|
415
415
|
`,u=o):(l+=`${o}${t?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 "}${w} (Lines: ${g}-${y})
|
|
416
416
|
`,u+=t?" ":"\u2502 "),f=n+1,p=r}return f>i&&d.length>0?l+=`${u}\u2514\u2500\u2500 ... depth exceeded ...
|
|
417
|
-
`:d.forEach((g,y)=>{let m=y===d.length-1;l+=
|
|
418
|
-
`).length,l=12;c>1e4?l=2:c>=8e3?l=3:c>=5e3?l=5:c>=4e3?l=8:c>2e3&&(l=10);let u=r.parse(d),f=
|
|
417
|
+
`:d.forEach((g,y)=>{let m=y===d.length-1;l+=sa(g,f,c?t&&m:m,u,p,i)}),l}var Ii=async e=>{let n;try{n=O(e).path}catch{return`ERROR: Failed to parse arguments: ${e}`}if(!n)return'ERROR: No file path provided. Use [tool:functions.FileMap(path="...")]';let t=ms.isAbsolute(n)?n:ms.resolve(process.cwd(),n);if(!vi.existsSync(t))return`ERROR: File not found: ${n}`;let o=ms.extname(t).slice(1).toLowerCase(),s=Jr[o];if(!s)return`ERROR: Unsupported file extension: .${o}`;let i=ms.resolve(as,s);if(!vi.existsSync(i))return`ERROR: Parser for .${o} not found. Please download it in Settings > Other.`;try{let a=Xr.Parser;if(!Qr){let p;try{p=ms.join(ms.dirname(Zr.resolve("web-tree-sitter")),"tree-sitter.wasm")}catch{p=ms.join(process.cwd(),"node_modules","web-tree-sitter","tree-sitter.wasm")}await a.init({locateFile:g=>g==="tree-sitter.wasm"||g.endsWith("tree-sitter.wasm")?p:g}),Qr=!0}let r=new a,h=await Xr.Language.load(i);r.setLanguage(h);let d=await vi.readFile(t,"utf8"),c=d.split(`
|
|
418
|
+
`).length,l=12;c>1e4?l=2:c>=8e3?l=3:c>=5e3?l=5:c>=4e3?l=8:c>2e3&&(l=10);let u=r.parse(d),f=sa(u.rootNode,0,!0," ",null,l);return`\u{1F4C4} File Map for: ${n}
|
|
419
419
|
${f}`}catch(a){let r=a instanceof Error?a.message:typeof a=="object"?JSON.stringify(a):String(a),h=a instanceof Error?`
|
|
420
|
-
Stack: ${a.stack}`:"";return`ERROR: Failed to map file: ${r}${h}`}};import
|
|
420
|
+
Stack: ${a.stack}`:"";return`ERROR: Failed to map file: ${r}${h}`}};import zn from"fs";import oa from"path";var no=async(e,n={})=>{let{method:t,tasks:o,markDone:s}=O(e),i=n.chatId||"default";if(!t)return'ERROR: Missing "method" argument for todo tool (create/append/get).';let a=oa.join(An,"plan",i),r=oa.join(a,"todo.md"),h=l=>{if(!l||Array.isArray(l))return l;let u=String(l).trim();if(u.startsWith("[")&&u.endsWith("]")){let f=u.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);return f?f.map(p=>p.slice(1,-1).replace(/\\(.)/g,"$1")):u.slice(1,-1).split(",").map(p=>p.trim()).filter(Boolean)}return l},d=l=>{let u=h(l);return u?(Array.isArray(u)?u:String(u).split(`
|
|
421
421
|
`)).map(p=>{let g=String(p).trim();return g?g.startsWith("- [ ]")||g.startsWith("- [x]")||g.startsWith("- [X]")?g:`- [ ] ${g}`:null}).filter(Boolean).join(`
|
|
422
422
|
`)+`
|
|
423
423
|
`:""},c=(l,u)=>{if(!u)return{content:l,markedCount:0};let f=h(u),p=(Array.isArray(f)?f:[f]).map(w=>String(w).replace(/^- \[[xX ]\]\s*/i,"").trim()).filter(Boolean),g=l.split(`
|
|
424
|
-
`),y=0,m=!1;for(let w of p){let
|
|
425
|
-
`):l,markedCount:y}};try{if(
|
|
424
|
+
`),y=0,m=!1;for(let w of p){let b=!1;for(let k=0;k<g.length;k++)if(g[k].includes(w)&&/^- \[\s\]/.test(g[k].trim())){g[k]=g[k].replace("- [ ]","- [x]"),b=!0,m=!0,y++;break}if(!b){for(let k=0;k<g.length;k++)if(g[k].toLowerCase().includes(w.toLowerCase())&&/^- \[\s\]/.test(g[k].trim())){g[k]=g[k].replace("- [ ]","- [x]"),b=!0,m=!0,y++;break}}}return{content:m?g.join(`
|
|
425
|
+
`):l,markedCount:y}};try{if(zn.existsSync(a)||zn.mkdirSync(a,{recursive:!0}),t==="create"){if(!o)return'ERROR: Missing "tasks" for create method.';let l=d(o),u=0;if(s){let p=c(l,s);l=p.content,u=p.markedCount}await ut.recordFileChange(r),zn.writeFileSync(r,l,"utf8");let f=l.split(/\r?\n/).map(p=>p.trim()).filter(p=>p.startsWith("- [ ]")||p.startsWith("- [x]")||p.startsWith("- [X]")).length;if(u>0){let p=l.split(/\r?\n/).map(g=>g.trim()).filter(g=>g.startsWith("- [x]")||g.startsWith("- [X]")).length;return`SUCCESS: TASK LIST CREATED (${u} marked done, ${p} completed, ${f-p} left)
|
|
426
426
|
${l}`}return`SUCCESS: TASK LIST CREATED (${f} total)
|
|
427
|
-
${l}`}if(t==="append"){if(!o)return'ERROR: Missing "tasks" for append method.';let l=d(o);await
|
|
428
|
-
${u}`}if(t==="get"){if(!
|
|
429
|
-
${l}`}return`ERROR: Unknown method "${t}". Use create, append, or get.`}catch(l){return`ERROR: Todo tool failure: ${l instanceof Error?l.message:String(l)}`}};var Oi=async(e,n={})=>{let{runSubagent:t}=await import("./ai-
|
|
430
|
-
`),d}catch(d){let{isTerminationSignaled:c}=await import("./ai-
|
|
431
|
-
`)}return`ERROR: Subagent execution failed: ${d.message}`}};var
|
|
427
|
+
${l}`}if(t==="append"){if(!o)return'ERROR: Missing "tasks" for append method.';let l=d(o);await ut.recordFileChange(r),zn.appendFileSync(r,l,"utf8");let u=zn.readFileSync(r,"utf8"),f=u.split(/\r?\n/).map(m=>m.trim()),p=f.filter(m=>m.startsWith("- [ ]")||m.startsWith("- [x]")||m.startsWith("- [X]")).length,g=f.filter(m=>m.startsWith("- [x]")||m.startsWith("- [X]")).length,y=l.split(/\r?\n/).map(m=>m.trim()).filter(m=>m.startsWith("- [ ]")||m.startsWith("- [x]")||m.startsWith("- [X]")).length;return`SUCCESS: TASK APPENDED (${g} completed, ${p-g} left, ${y} added)
|
|
428
|
+
${u}`}if(t==="get"){if(!zn.existsSync(r))return"TODO GET: No task list found for this session.";let l=zn.readFileSync(r,"utf8"),u=0;if(s){let m=c(l,s);m.markedCount>0&&(l=m.content,u=m.markedCount,await ut.recordFileChange(r),zn.writeFileSync(r,l,"utf8"))}let f=l.split(/\r?\n/).map(m=>m.trim()),p=f.filter(m=>m.startsWith("- [ ]")||m.startsWith("- [x]")||m.startsWith("- [X]")).length,g=f.filter(m=>m.startsWith("- [x]")||m.startsWith("- [X]")).length;return`${u>0?`SUCCESS: ${u} TASK(S) MARKED DONE`:"TODO GET"}: ${g} Completed, ${p-g} left
|
|
429
|
+
${l}`}return`ERROR: Unknown method "${t}". Use create, append, or get.`}catch(l){return`ERROR: Todo tool failure: ${l instanceof Error?l.message:String(l)}`}};var Oi=async(e,n={})=>{let{runSubagent:t}=await import("./ai-JV4YFO7W.js"),o=O(e),s=o.task||o.instruction||o.prompt,i=o.model||null,a=o.tools||null;if(!s)return'ERROR: Missing "task" argument for invokeSync.';let r=null;if(a)try{let d=a.trim();d.startsWith("[")&&d.endsWith("]")&&(d=d.substring(1,d.length-1)),r=d.split(",").map(c=>c.trim().replace(/^["']|["']$/g,"")).filter(Boolean)}catch{}let h=o.title||s.substring(0,30);try{n.onVisualFeedback&&n.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${h}`);let d=await t(s,n,i,r,50);return n.onVisualFeedback&&n.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${h} [COMPLETED]
|
|
430
|
+
`),d}catch(d){let{isTerminationSignaled:c}=await import("./ai-JV4YFO7W.js"),l=d.message==="Subagent task was cancelled by user."||c();if(n.onVisualFeedback){let u=l?"[CANCELLED]":"[FAILED]";n.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${h} ${u}
|
|
431
|
+
`)}return`ERROR: Subagent execution failed: ${d.message}`}};var ia=async(e,n={})=>{let{runSubagent:t}=await import("./ai-JV4YFO7W.js"),o=O(e),s=o.task||o.instruction||o.prompt,i=o.model||null,a=o.title||null,r=o.tools||null;if(!s)return'ERROR: Missing "task" argument for invoke.';let h=null;if(r)try{let m=r.trim();m.startsWith("[")&&m.endsWith("]")&&(m=m.substring(1,m.length-1)),h=m.split(",").map(w=>w.trim().replace(/^["']|["']$/g,"")).filter(Boolean)}catch{}let d=`subagent-${Date.now()}-${Math.floor(Math.random()*1e3)}`,c=null,l=null,u=new Promise((m,w)=>{c=m,l=w}),f={id:d,title:a||s.substring(0,30),task:s,status:"running",startedAt:Date.now(),lastChunkTime:Date.now(),wps:0,questions:[],pendingSteerMessages:[],steer:m=>{m&&f.pendingSteerMessages.push(m)},completionPromise:u,_resolveCompletion:c,_rejectCompletion:l,progress:[]},p={chunks:[],totalWords:0};Ve.push(f),n.onSubagentUpdate&&n.onSubagentUpdate();let g=[],y={...n,taskId:d,onAskMain:async m=>{let w=`q-${Date.now()}-${Math.floor(Math.random()*1e3)}`,b=null,k=new Promise(x=>{b=x}),R={id:w,question:m,answered:!1,answer:null,askedAt:Date.now(),_resolve:b};return f.questions.push(R),f.status="waiting",n.onSubagentUpdate&&n.onSubagentUpdate(),ko(`[SYSTEM] Background subagent "${f.title}" is WAITING FOR YOUR INPUT: "${m}"
|
|
432
432
|
Respond using tool: [tool:functions.Answer(id="${d}", answer="...")]
|
|
433
|
-
[/SYSTEM]`),await
|
|
434
|
-
`);
|
|
433
|
+
[/SYSTEM]`),await k},onVisualFeedback:m=>{f.lastChunkTime=Date.now();let w=m.replace(/\x1b\[[0-9;]*m/g,""),b=w.match(/[✔✘✗✖🔍📖→➕↻•]\s*([A-Za-z0-9\s-]+)/);b?f.currentTool=b[1].trim():f.currentTool=w,n.onSubagentUpdate&&n.onSubagentUpdate()},onTokenChunk:(m,w)=>{let b=Date.now();if(f.lastChunkTime=b,f.currentTool="Thinking",typeof w=="number"&&w>0){p.totalWords+=w,p.chunks.push({time:b,words:w});let k=b-400;if(p.chunks=p.chunks.filter(R=>R.time>=k),p.chunks.length>0){let R=p.chunks.reduce((T,$)=>T+$.words,0),E=p.chunks[0].time,x=Math.max(.4,(b-E)/1e3);f.wps=Math.round(R/x*10)/10}}n.onSubagentUpdate&&n.onSubagentUpdate()}};return t(s,y,i,h,50,m=>{if(f.status==="cancelled")return;if(m.startsWith("[Subagent Turn")&&g.length>0&&(f.progress.push([...g]),g=[]),m.includes("[Executing Tool]")){let b=m.match(/\[Executing Tool\]\s*([a-zA-Z0-9_]+)/);b&&(!f.currentTool||f.currentTool==="Thinking")&&(f.currentTool=b[1])}let w=m;if(w.startsWith("[Tool Result]")){let b=w.split(`
|
|
434
|
+
`);b.length>5&&(w=b.slice(0,4).join(`
|
|
435
435
|
`)+`
|
|
436
|
-
... [Content/Diff Truncated from Logs] ...`)}g.push(w),n.onSubagentUpdate&&n.onSubagentUpdate()},!0).then(m=>{if(f.status==="cancelled"){f._resolveCompletion&&f._resolveCompletion(m);return}g.length>0&&(f.progress.push([...g]),g=[]),f.status="completed",f.finalAnswer=m,n.onSubagentUpdate&&n.onSubagentUpdate(),
|
|
436
|
+
... [Content/Diff Truncated from Logs] ...`)}g.push(w),n.onSubagentUpdate&&n.onSubagentUpdate()},!0).then(m=>{if(f.status==="cancelled"){f._resolveCompletion&&f._resolveCompletion(m);return}g.length>0&&(f.progress.push([...g]),g=[]),f.status="completed",f.finalAnswer=m,n.onSubagentUpdate&&n.onSubagentUpdate(),ko(`[SYSTEM] Background subagent "${f.title}" (id: ${d}) has FINISHED. Call GetProgress(id="${d}") to see the final result. [/SYSTEM]`),f._resolveCompletion&&f._resolveCompletion(m)}).catch(async m=>{let{isTerminationSignaled:w}=await import("./ai-JV4YFO7W.js");if(m.message==="Subagent task was cancelled."||f.status==="cancelled"||w()){f.status="cancelled",g.push("[SUBAGENT CANCELLED] Task was cancelled."),f.progress.push([...g]),n.onSubagentUpdate&&n.onSubagentUpdate(),f._resolveCompletion&&f._resolveCompletion(null);return}g.push(`[SUBAGENT FAILURE] Error: ${m.message}`),f.progress.push([...g]),f.status="failed",f.error=m.message,n.onSubagentUpdate&&n.onSubagentUpdate(),ko(`[SYSTEM] Background subagent "${f.title}" (id: ${d}) FAILED with error: ${m.message}. [/SYSTEM]`),f._rejectCompletion&&f._rejectCompletion(m)}),`SUCCESS: Background subagent started. Task ID: ${d}`};var Li=async(e,n={})=>{let o=O(e).id;if(!o)return'ERROR: Missing "id" argument for getProgress.';let s=Ve.find(r=>r.id===o);if(!s)return`ERROR: Subagent task with ID [${o}] not found.`;let i=`Subagent Task Status: ${s.status.toUpperCase()}
|
|
437
437
|
`;if(i+=`Title: ${s.title}
|
|
438
438
|
`,i+=`Task: ${s.task}
|
|
439
439
|
`,s.startedAt){let r=Math.floor((Date.now()-s.startedAt)/1e3);i+=`Elapsed Time: ${r}s
|
|
@@ -448,7 +448,7 @@ Respond using tool: [tool:functions.Answer(id="${d}", answer="...")]
|
|
|
448
448
|
`)}return i+=`
|
|
449
449
|
Progress Log:
|
|
450
450
|
`,s.progress.forEach((r,h)=>{i+=`--- Turn ${h+1} ---
|
|
451
|
-
`;let c=r.filter(l=>!l.startsWith("[SUBAGENT SUCCESS]")).map(l=>{if(l.startsWith("[Subagent Response]")){let u="[Subagent Response]",p=l.substring(u.length),g="tool:functions.";for(;;){let m=p.toLowerCase().indexOf(g);if(m===-1)break;let w=m,
|
|
451
|
+
`;let c=r.filter(l=>!l.startsWith("[SUBAGENT SUCCESS]")).map(l=>{if(l.startsWith("[Subagent Response]")){let u="[Subagent Response]",p=l.substring(u.length),g="tool:functions.";for(;;){let m=p.toLowerCase().indexOf(g);if(m===-1)break;let w=m,b=!1,k=m-1;for(;k>=0&&/\s/.test(p[k]);)k--;k>=0&&p[k]==="["&&(w=k,b=!0);let R=0,E=!1,x=null,T=m;for(;T<p.length;){let $=p[T];if(!x&&($==="'"||$==='"'||$==="`")?x=$:x&&$===x&&p[T-1]!=="\\"&&(x=null),x||($==="("?(R++,E=!0):$===")"&&R--),E&&R===0&&!x){let _=T;if(b){let S=T+1;for(;S<p.length&&/\s/.test(p[S]);)S++;S<p.length&&p[S]==="]"&&(_=S)}p=p.substring(0,w)+p.substring(_+1);break}if(T++,T===p.length){p=p.substring(0,w);break}}}return u+`
|
|
452
452
|
`+p.trim()}return l.startsWith("[Executing Tool]")&&l.length>256?l.substring(0,256)+"...[truncated from logs]":l});i+=c.join(`
|
|
453
453
|
`)+`
|
|
454
454
|
|
|
@@ -458,7 +458,7 @@ ${s.finalAnswer}
|
|
|
458
458
|
`),i.replace(/\r\n/g,`
|
|
459
459
|
`).replace(/\n{3,}/g,`
|
|
460
460
|
|
|
461
|
-
`).trim().replace(/\[TOOL RESULT\]/gi,"TOOL RESULT:")};var
|
|
461
|
+
`).trim().replace(/\[TOOL RESULT\]/gi,"TOOL RESULT:")};var ra=async(e,n={})=>{let o=O(e).id;if(!o)return'ERROR: Missing "id" argument for cancel.';let s=Ve.find(i=>i.id===o);return s?s.status==="completed"||s.status==="failed"?`INFO: Subagent task with ID [${o}] has already finished with status [${s.status.toUpperCase()}].`:s.status==="cancelled"?`INFO: Subagent task with ID [${o}] is already cancelled.`:(s.status="cancelled",n.onSubagentUpdate&&n.onSubagentUpdate(),`SUCCESS: Subagent task with ID [${o}] has been cancelled.`):`ERROR: Subagent task with ID [${o}] not found.`};import wt from"fs-extra";import St from"path";var Wl=["node_modules","dist","bin","logs",".git",".fluxflow","secret",".gemini",".agents","tmp","temp","build","out","snapshots"];async function so(e,n=e){let t={},o=await wt.readdir(e,{withFileTypes:!0}).catch(()=>[]);for(let s of o){if(Wl.includes(s.name))continue;let i=St.join(e,s.name),a=St.relative(n,i).replace(/\\/g,"/");if(s.isDirectory()){let r=await so(i,n);Object.assign(t,r)}else{let r=await wt.stat(i).catch(()=>null);r&&(t[a]={size:r.size,mtime:r.mtimeMs})}}return t}async function aa(e,n){await wt.ensureDir(e);for(let t of Object.keys(n)){let o=St.join(process.cwd(),t),s=St.join(e,t);await wt.ensureDir(St.dirname(s)),await wt.copyFile(o,s).catch(()=>{})}}async function Di(e,n,t=null,o=null){if(!await wt.pathExists(e))return;o||(o=e);let s=await wt.readdir(e,{withFileTypes:!0}).catch(()=>[]);for(let i of s){let a=St.join(e,i.name),r=St.join(n,i.name);if(i.isDirectory())await Di(a,r,t,o);else{let h=St.relative(o,a).replace(/\\/g,"/"),d=await wt.pathExists(r);d&&await wt.chmod(r,438).catch(()=>{}),await wt.ensureDir(St.dirname(r));let c=await wt.copyFile(a,r).then(()=>!0).catch(()=>!1);await wt.chmod(r,438).catch(()=>{}),t&&(c?d?t.replaced++:t.restored++:t.failed.push(h))}}}var Kn={async takeInitialSnapshot(e){try{let n=St.join(An,"snapshots",e);await wt.remove(n).catch(()=>{}),await wt.ensureDir(n);let t=await so(process.cwd());await aa(St.join(n,"initial"),t);let o=X(un,{});o[e]={initialManifest:t,currentManifest:t,checkpoints:[{id:"initial",timestamp:new Date().toISOString(),newFiles:[],modifiedFiles:[],deletedFiles:[],toolsUsed:[]}]},he(un,o)}catch{}},async recordTurnDelta(e,n,t=[]){try{let o=X(un,{}),s=o[e];if(!s)return;let i=s.currentManifest||s.initialManifest,a=await so(process.cwd()),r=[],h=[],d=[];for(let[l,u]of Object.entries(a)){let f=i[l];f?(f.size!==u.size||f.mtime!==u.mtime)&&h.push(l):r.push(l)}for(let l of Object.keys(i))a[l]||d.push(l);let c=[...r,...h];if(c.length>0||d.length>0){let l={};for(let f of c)l[f]=a[f];let u=St.join(An,"snapshots",e,`turn_${n}`);await aa(u,l)}s.checkpoints.push({id:`turn_${n}`,timestamp:new Date().toISOString(),newFiles:r,modifiedFiles:h,deletedFiles:d,toolsUsed:t}),s.currentManifest=a,he(un,o)}catch{}},async getCheckpoints(e){try{let t=X(un,{})[e];return t?t.checkpoints||[]:[]}catch{return[]}},async rollbackToCheckpoint(e,n){try{let t=X(un,{}),o=t[e];if(!o)throw new Error("No session active for Advance Rollback.");let s=o.checkpoints||[],i=s.findIndex(c=>c.id===n);if(i===-1)throw new Error(`Checkpoint [${n}] not found.`);let a=St.join(An,"snapshots",e),r={restored:0,replaced:0,failed:[]},h=await so(process.cwd());for(let c of Object.keys(h)){let l=St.join(process.cwd(),c);await wt.chmod(l,438).catch(()=>{}),await wt.remove(l).catch(()=>{})}let d=St.join(a,"initial");await Di(d,process.cwd(),r,d);for(let c=1;c<=i;c++){let l=s[c],u=St.join(a,l.id);if(await Di(u,process.cwd(),r,u),l.deletedFiles&&l.deletedFiles.length>0)for(let f of l.deletedFiles){let p=St.join(process.cwd(),f);await wt.chmod(p,438).catch(()=>{}),await wt.remove(p).catch(()=>{})}}return o.checkpoints=s.slice(0,i+1),o.currentManifest=await so(process.cwd()),he(un,t),{checkpointId:n,stats:r}}catch(t){throw new Error(`Rollback failed: ${t.message}`)}},async getLatestFileChanges(e){try{let t=X(un,{})[e];if(!t||!t.checkpoints||t.checkpoints.length===0)return{newFiles:[],modifiedFiles:[],deletedFiles:[]};let o=t.checkpoints[t.checkpoints.length-1];return{newFiles:o.newFiles||[],modifiedFiles:o.modifiedFiles||[],deletedFiles:o.deletedFiles||[]}}catch{return{newFiles:[],modifiedFiles:[],deletedFiles:[]}}},async cleanup(e){try{let n=St.join(An,"snapshots",e);await wt.remove(n).catch(()=>{});let t=X(un,{});t[e]&&(delete t[e],he(un,t))}catch{}}};var Pi=async(e,n={})=>{let t=O(e),o=t.method,s=t.id,i=n.chatId;if(!n.systemSettings?.advanceRollback)return"ERROR: Advance Rollback feature is currently disabled in settings under Security. Tell user to enable it.";if(!i)return"ERROR: No active chat transaction found for rollback.";if(o==="getCheckpoint"){let r=await Kn.getCheckpoints(i);if(r.length===0)return"No checkpoints available.";let h={write_file:"WriteFile",update_file:"PatchFile",view_file:"ReadFile",read_folder:"ReadFolder",exec_command:"Run",web_search:"WebSearch",web_scrape:"WebScrape",search_keyword:"SearchKeyword",CodeSearch:"SearchKeyword",code_search:"SearchKeyword",write_pdf:"WritePDF",write_docx:"WriteDoc",generate_image:"GenerateImage",file_map:"FileMap",todo:"Todo",goal:"Goal",Goal:"Goal",await:"Await",ask:"Ask",ask_user:"Ask",invoke:"Invoke",invokesync:"InvokeSync",getprogress:"GetProgress",cancel:"Cancel",emergency_rollback:"EmergencyRollback",emergencyrollback:"EmergencyRollback"},d=l=>h[l]||h[l.toLowerCase()]||l,c=`Available checkpoints for rollback:
|
|
462
462
|
|
|
463
463
|
`;for(let l of r)if(l.id==="initial")c+=`--- Initial State (id: initial) ---
|
|
464
464
|
Tools Used: User Prompted for task
|
|
@@ -466,7 +466,7 @@ Tools Used: User Prompted for task
|
|
|
466
466
|
`;else{let u=l.id.replace("turn_",""),f=l.toolsUsed&&l.toolsUsed.length>0?l.toolsUsed.map(d).join(", "):"None";c+=`--- Turn ${u} (id: ${l.id}) ---
|
|
467
467
|
Tools Used: ${f}
|
|
468
468
|
|
|
469
|
-
`}return c.trim()}else if(o==="forceRevert"){if(!s)return"ERROR: Missing required parameter 'id' for forceRevert.";try{let r=await
|
|
469
|
+
`}return c.trim()}else if(o==="forceRevert"){if(!s)return"ERROR: Missing required parameter 'id' for forceRevert.";try{let r=await Kn.rollbackToCheckpoint(i,s),{checkpointId:h,stats:d}=r,c=d.restored+d.replaced+d.failed.length,l=`SUCCESS: Repository rolled back to checkpoint [${h}].
|
|
470
470
|
|
|
471
471
|
`;return l+=`Stats:
|
|
472
472
|
`,l+=` Restored : ${d.restored} file${d.restored!==1?"s":""} (new to workspace)
|
|
@@ -475,14 +475,14 @@ Tools Used: ${f}
|
|
|
475
475
|
${d.failed.join(`
|
|
476
476
|
`)}`),l+=`
|
|
477
477
|
\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500-
|
|
478
|
-
`,l+=` Total : ${c} file${c!==1?"s":""} processed`,l}catch(r){return`ERROR: ${r.message}`}}else return`ERROR: Invalid method "${o}". Use "getCheckpoint" or "forceRevert".`};var
|
|
478
|
+
`,l+=` Total : ${c} file${c!==1?"s":""} processed`,l}catch(r){return`ERROR: ${r.message}`}}else return`ERROR: Invalid method "${o}". Use "getCheckpoint" or "forceRevert".`};var Ds=async(e,n={})=>{let t=O(e),o=t.id,s=parseInt(t.timeout||t.time||"120",10);if((isNaN(s)||s<=0)&&(s=120),s>300&&(s=300),!o)return t.time?(await new Promise(h=>setTimeout(h,s*1e3)),`SUCCESS: Waited for ${s}s.`):'ERROR: Missing "id" argument for Await.';let i=Ve.find(h=>h.id===o);if(!i)return`ERROR: Subagent task with ID [${o}] not found.`;if(i.status==="completed")return`SUCCESS: Subagent task [${o}] completed.
|
|
479
479
|
Final Answer:
|
|
480
480
|
${i.finalAnswer||"(No output)"}`;if(i.status==="failed")return`ERROR: Subagent task [${o}] failed.
|
|
481
481
|
Error: ${i.error||"Unknown error"}`;if(i.status==="cancelled")return`INFO: Subagent task [${o}] was cancelled.`;let a,r=new Promise(h=>{a=setTimeout(()=>{h({type:"timeout"})},s*1e3)});try{let h=await Promise.race([i.completionPromise.then(()=>({type:"completion"})),r]);return clearTimeout(a),h.type==="timeout"?`TIMEOUT: Subagent task [${o}] is still running (status: ${i.status.toUpperCase()}) after ${s}s. You can continue other work or call Await again.`:i.status==="completed"?`SUCCESS: Subagent task [${o}] completed.
|
|
482
482
|
Final Answer:
|
|
483
483
|
${i.finalAnswer||"(No output)"}`:i.status==="failed"?`ERROR: Subagent task [${o}] failed.
|
|
484
|
-
Error: ${i.error||"Unknown error"}`:i.status==="cancelled"?`INFO: Subagent task [${o}] was cancelled.`:`INFO: Subagent task [${o}] status changed to ${i.status.toUpperCase()}.`}catch(h){return clearTimeout(a),`ERROR: Exception while awaiting subagent [${o}]: ${h.message}`}};var
|
|
485
|
-
`)){let i=s.split(" ");if(i.length<12||parseInt(i[0])!==5)continue;let r=i[2],h=i[3],d=i[4],c=parseInt(i[6]),l=parseInt(i[7]),u=parseInt(i[8]),f=parseInt(i[9]),p=parseFloat(i[10]),g=i.slice(11).join(" ").trim();if(!g||p<0)continue;let y={x0:c,y0:l,x1:c+u,y1:l+f},m={text:g,confidence:p,bbox:y};n.push(m);let w=`${r}_${h}_${d}`;t.has(w)||t.set(w,{words:[],bbox:{x0:1/0,y0:1/0,x1:-1/0,y1:-1/0}});let x=t.get(w);x.words.push(m),x.bbox.x0=Math.min(x.bbox.x0,y.x0),x.bbox.y0=Math.min(x.bbox.y0,y.y0),x.bbox.x1=Math.max(x.bbox.x1,y.x1),x.bbox.y1=Math.max(x.bbox.y1,y.y1)}let o=[];for(let s of t.values())s.words.length>0&&o.push({text:s.words.map(i=>i.text).join(" "),bbox:s.bbox,words:s.words});return{words:n,lines:o}}function zl(e){if(!(e.words&&e.words.length>0)){if(e.blocks&&e.blocks.length>0){e.words=[],e.lines=[];for(let n of e.blocks)for(let t of n.paragraphs||[])for(let o of t.lines||[]){o.bbox&&e.lines.push(o);for(let s of o.words||[])s.bbox&&e.words.push(s)}if(e.words.length>0)return}if(e.tsv){let n=ql(e.tsv);e.words=n.words,e.lines=n.lines}}}function Bi(e,n,t=0,o=0,s=1){zl(e);let i=r=>({x0:Math.round(r.x0/s)+t,y0:Math.round(r.y0/s)+o,x1:Math.round(r.x1/s)+t,y1:Math.round(r.y1/s)+o}),a=[];if(e.lines&&e.lines.length>0)for(let r of e.lines){let h=r.text?r.text.toLowerCase().trim():"";if(!h||!r.bbox||!(h===n||new RegExp(`\\b${jl(n)}\\b`,"i").test(h)))continue;let c=r.words||(e.words?e.words.filter(p=>p.bbox&&p.bbox.x0>=r.bbox.x0-5&&p.bbox.x1<=r.bbox.x1+5&&p.bbox.y0>=r.bbox.y0-5&&p.bbox.y1<=r.bbox.y1+5):[]),l=n.split(/\s+/),u=l.map(p=>p.replace(/[^a-z0-9]/g,"")).join(" "),f=!1;if(c.length>0)for(let p=0;p<=c.length-l.length;p++){let g=c.slice(p,p+l.length),y=g.map(m=>(m.text||"").toLowerCase().trim().replace(/[^a-z0-9]/g,"")).join(" ");if(y===u||y.includes(u)){let m={x0:Math.min(...g.map(w=>w.bbox.x0)),y0:Math.min(...g.map(w=>w.bbox.y0)),x1:Math.max(...g.map(w=>w.bbox.x1)),y1:Math.max(...g.map(w=>w.bbox.y1))};a.push(i(m)),f=!0}}f||a.push(i(r.bbox))}if(a.length===0&&e.words&&e.words.length>0)for(let r of e.words){let h=r.text?r.text.toLowerCase().trim().replace(/[^a-z0-9]/g,""):"",d=n.replace(/[^a-z0-9]/g,"");h===d&&r.bbox&&a.push(i(r.bbox))}if(a.length===0&&e.words&&e.words.length>0){let r=Gl(n.length);for(let h of e.words){let d=h.text?h.text.toLowerCase().trim():"";d.length>=3&&Math.abs(d.length-n.length)<=r&&Hl(d,n,r)<=r&&h.bbox&&a.push(i(h.bbox))}}return a}function Ui(e,n){let t=null,o=1/0;for(let s of e){let i=Math.round((s.x0+s.x1)/2),a=Math.round((s.y0+s.y1)/2),r=n.x>=s.x0&&n.x<=s.x1&&n.y>=s.y0&&n.y<=s.y1,h=Math.hypot(i-n.x,a-n.y),d=r?0:h;d<o&&(o=d,t={x:i,y:a,dist:h,containsPoint:r,bbox:s})}return t}function Kl(e,n,t,o){let a=Math.ceil(e/4),r=Math.ceil(n/2),h=[];for(let d=0;d<2;d++)for(let c=0;c<4;c++){let l=c*a,u=d*r,f=Math.min(a,e-l),p=Math.min(r,n-u),g=l+f/2,y=u+p/2,m=t>=l&&t<l+f&&o>=u&&o<u+p;h.push({x0:l,y0:u,w:f,h:p,cx:g,cy:y,containsTarget:m})}return h.sort((d,c)=>{if(d.containsTarget)return-1;if(c.containsTarget)return 1;let l=Math.hypot(d.cx-t,d.cy-o),u=Math.hypot(c.cx-t,c.cy-o);return l-u})}var Oo=null;async function Yl(){return Oo||(Oo=(async()=>{let{createWorker:e}=await import("tesseract.js"),n=await import("fs-extra"),{CU_CACHE_DIR:t}=await import("./paths-R3DD7CRF.js");return n.ensureDirSync(t),e("eng",1,{cachePath:t,logger:()=>{}})})().catch(e=>{throw Oo=null,e})),Oo}var lo=null,fa=null;async function Vl(){let{getActiveDisplay:e}=await import("./screen_grid-IKEV7A6U.js"),n=await e();if(lo&&fa===n)return lo;fa=n,lo={format:"png"};try{let t=await ua.listDisplays();t&&t.length>0&&(lo={format:"png",screen:(t[n]||t[0]).id})}catch{}return lo}var Wi=async(e,n={})=>{let t=!!(process.env.SHOW_DEBUG_GRID||process.env.DEBUG_OCR||process.env.VERBOSE),o=performance.now(),s=o,i=f=>{if(!t)return;let p=performance.now(),g=(p-s).toFixed(0),y=(p-o).toFixed(0);console.log(`[Click Perf] +${g}ms (${y}ms total) -> ${f}`),s=p};i("Starting click()");let a=O(e),r=a.gridId||a.grid||a.coordinate||a.target||a.id,h=(a.type||a.clickType||"single").toLowerCase(),d=(a.button||"left").toLowerCase(),c=a.intendedClickText||a.text||"";if(!r&&!c)return'ERROR: Missing required "gridId" parameter for Click tool.';let l=r;if(c)try{i("Parsing grid code");let f=r?gr(r):null;i("Getting display options");let p=await Vl();i("Taking desktop screenshot");let g=await ua(p);i("Getting image metadata");let y=await co(g).metadata(),m=y.width||1920,w=y.height||1080,x=f?{x:Math.round(f.x*(m/1280)),y:Math.round(f.y*(w/720))}:{x:m/2,y:w/2},S=c.toLowerCase().trim();i("Acquiring OCR worker");let R=await Yl(),E=null,k="",T=f?220:500;if(f){i("Pass 1: Cropping target crop (3x zoom window, 2x upscale)");let $=Math.min(Math.round(m/3),m),C=Math.min(Math.round(w/3),w),b=Math.max(0,Math.min(m-$,x.x-Math.floor($/2))),v=Math.max(0,Math.min(w-C,x.y-Math.floor(C/2))),I=await co(g).extract({left:b,top:v,width:$,height:C}).toBuffer(),D=2,j=await Ni(I,D),U=S.replace(/[^a-z0-9]/g,"_");await Fi("cropped",`crop_${Date.now()}_${U}.png`,j),i("Pass 1: Running Tesseract OCR recognize on crop (PSM 11 - Sparse Text)"),await R.setParameters({tessedit_pageseg_mode:"11"});let{data:Y}=await R.recognize(j,{},{tsv:!0,blocks:!0});if(i("Pass 1: OCR recognition finished, extracting matches"),Y&&Y.text){t&&console.log(`[Pass 1 OCR Read]: "${Y.text.trim().replace(/\s+/g," ")}"`);let ie=Bi(Y,S,b,v,D);if(ie.length>0){let _e=Ui(ie,x);_e&&(_e.containsPoint||_e.dist<=T)&&(E=_e,k="centered target crop OCR")}}}if(!E){i("Pass 2: Entering Full-Screen OCR (broad scan, PSM 3 - Auto)");let $=await Ni(g,2),C=S.replace(/[^a-z0-9]/g,"_");await Fi("fullscreen",`full_${Date.now()}_${C}.png`,$),i("Pass 2: Running Tesseract on full screen"),await R.setParameters({tessedit_pageseg_mode:"3"});let{data:b}=await R.recognize($,{},{tsv:!0,blocks:!0});if(i("Pass 2: Full-screen OCR finished"),b&&b.text){let v=Bi(b,S,0,0,2);if(v.length>0){let I=Ui(v,x);I&&(E=I,k="full-screen OCR")}}}if(!E){i("Pass 3: Entering Tiled OCR fallback (high-res 3x)");let $=Kl(m,w,x.x,x.y),C=S.replace(/[^a-z0-9]/g,"_");await R.setParameters({tessedit_pageseg_mode:"11"});for(let b=0;b<$.length;b++){let v=$[b];i(`Pass 3: Preprocessing tile ${b+1}/${$.length}`);let I=await co(g).extract({left:v.x0,top:v.y0,width:v.w,height:v.h}).toBuffer(),D=await Ni(I,3);await Fi("tiles",`tile_${b+1}_${Date.now()}_${C}.png`,D),i(`Pass 3: Running Tesseract on tile ${b+1}`);let{data:j}=await R.recognize(D,{},{tsv:!0,blocks:!0});if(!j||!j.text)continue;let U=Bi(j,S,v.x0,v.y0,3);if(U.length>0){let Y=Ui(U,x);if(Y){E=Y,k=`tile ${b+1} OCR (${v.containsTarget?"target tile":`offset ${v.x0},${v.y0}`})`;break}}}}if(E){let $={x:Math.round(E.x*(1280/m)),y:Math.round(E.y*(720/w))};i(`Executing mouse click on matched target (${k})`);let C=await On("click",$,{button:d,clickType:h});return i("Click completed successfully"),`${C} (${k} for "${c}" at ${Math.round(E.dist)}px distance)`}else t&&console.log(`[OCR] No match found for "${c}". Falling back to gridId.`)}catch(f){t&&console.error("[OCR Error]",f)}i(`Executing mouse click on fallback gridId: ${l}`);let u=await On("click",l,{button:d,clickType:h});return i("Fallback click completed"),u};var ji=async(e,n={})=>{let t=O(e),o=t.fromGridId||t.from||t.start,s=t.toGridId||t.to||t.end;return!o||!s?'ERROR: Drag requires both "fromGridId" and "toGridId" parameters.':await On("drag",o,{from:o,to:s})};var Hi=async(e,n={})=>{let t=O(e),o=(t.direction||"down").toLowerCase(),s=t.amount?parseInt(t.amount,10):6,i=t.gridId||t.grid||t.coordinate||t.target||t.id||null;return await On("scroll",i,{direction:o,amount:s})};var Lo=async(e,n={})=>{let t=O(e),o=t.text||t.input||t.value||"",s=t.autoPressEnter===!0||t.autoPressEnter==="true"||t.enter===!0||t.enter==="true";return o==null?'ERROR: Missing required "text" parameter for KeyboardTyping tool.':await Kn("type",String(o),{autoPressEnter:s})};var Po=async(e,n={})=>{let t=O(e),o=t.key||t.keys||t.input||t.shortcut;if(!o)return'ERROR: Missing required "key" parameter for KeyPress tool.';let s=String(o).trim().toLowerCase();if(s==="clearinput"||s==="clear_input"||s==="clear")return await Kn("clear_input");if(s.includes(";")||s.includes("+")){let i=s.split(/[;+]/).map(a=>a.trim()).filter(Boolean);return await Kn("key_combination",i)}return await Kn("key_press",s)};var Do=async(e,n={})=>"SUCCESS: Screen recapture requested. The latest gridded screenshot is provided for your next decision.";var Jl={web_search:di,web_scrape:fi,memory:ui,chat:hi,view_file:Qs,write_file:pi,update_file:xi,exec_command:si,read_folder:Si,write_pdf:Ti,write_docx:Ei,search_keyword:eo,generate_image:Mi,saveSummary:to,addMemScore:Ls,file_map:Ii,todo:no,Todo:no,goal:no,Goal:no,invokeSync:Oi,invoke:sa,getProgress:Li,cancel:oa,awaitSubagent:Ps,answerSubagent:Ds,steerSubagent:oo,computer_action:ao,computer_use:ao,ComputerAction:ao,ComputerUse:ao,click:Wi,Click:Wi,drag:ji,Drag:ji,scroll:Hi,Scroll:Hi,keyboard_typing:Lo,KeyboardTyping:Lo,keyboardtyping:Lo,key_press:Po,KeyPress:Po,keypress:Po,recapture_screen:Do,RecaptureScreen:Do,recapturescreen:Do,invoke_sync:Oi,get_progress:Li,await_subagent:Ps,answer_subagent:Ds,steer_subagent:oo,steer:oo,Steer:oo,ask:ki,Ask:ki,WebSearch:di,WebScrape:fi,ReadFile:Qs,ReadFolder:Si,WriteFile:pi,PatchFile:xi,WritePDF:Ti,WriteDoc:Ei,Run:si,SearchKeyword:eo,CodeSearch:eo,code_search:eo,Memory:ui,Chat:hi,GenerateImage:Mi,saveSumary:to,SaveSummary:to,SaveSumary:to,add_mem_score:Ls,AddMemScore:Ls,addMemoryScore:Ls,AddMemoryScore:Ls,FileMap:Ii,answer:Ds,Answer:Ds,AnswerSubagent:Ds,await:Ps,Await:Ps,AwaitSubagent:Ps,EmergencyRollback:Di,emergency_rollback:Di},fo=async(e,n,t={})=>{let o=t.mode?t.mode.toLowerCase():"flux",s=e.toLowerCase(),a=["memory","chat","savesummary","addmemscore","add_mem_score","ask","web_search","web_scrape","await"].some(c=>s.includes(c))||s==="ask",h=["click","drag","scroll","keyboardtyping","keyboard_typing","keypress","key_press","recapturescreen","recapture_screen","computer"].some(c=>s.includes(c));if(!a){if(o==="flow"){if(!(s.includes("write_pdf")||s.includes("write_docx")||s.includes("generate_image")))return`ERROR: Tool [${e}] is a Workspace Tool and NOT available in Flow mode. Tell user to switch (\`/mode flux\`) to use this tool.`}else if(o==="icu"){if(!h)return`ERROR: Tool [${e}] is not available in Computer Use mode. ICU mode only supports Computer Use tools (Click, Drag, Scroll, KeyboardTyping, KeyPress, RecaptureScreen).`}else if(s.includes("write_pdf")||s.includes("write_docx")||s.includes("generate_image"))return`ERROR: Tool [${e}] is not available in ${t.mode||"Flux"} mode. Tell user to switch (\`/mode flow\`) for document generation.`}let d=Jl[e];if(!d)return`ERROR: Tool [${e}] not found in registry.`;try{return await d(n,t)}catch(c){let l=c instanceof Error?c.message:String(c);return`ERROR: Execution failed for [${e}]: ${l}`}};import Q from"path";import Ie from"fs";import Xl from"gradient-string";var Gi=["I have a regex for your problems.","Your terminal, my kingdom.","Blowing on the cartridge helps. Probably.","Don't panic. I have the towel.","Logic is the start of wisdom.","Try to exit Vim? Good luck.","I speak fluent Terminal.","The cake is a lie. This code is not.","I have no bugs, just surprise features.","Rewriting in Rust... just for fun.","Coffee in, clean commits out.","The magic smoke stays inside today.","A semicolon short of a miracle.","One does not simply code without a bug.","Keep it simple. Keep it terminal.","Regex: now you have two problems.","I dream in binary.","Root access or bust.","Wait for the dial-up tone. Just kidding.","I take the 'labor' out of collab.","My other process is a TARDIS.","Calculated response: 42.","Ponder the orb. Ponder the code.","Less talk, more flow.","Elegance in every byte.","Build something the world is not ready for.","Your wishes, my tool calls.","I act in Flux. I think in Flow.","Syntax error in the universe. Please fix.","Your project, my obsession.","I am not a bot, I am an architect.","Digital spirits consulted. They say: Ship it.","Reticulate splines. Engage humor.","Code like poetry. Run like water.","Minimalism is the ultimate flex.","The truth is in the logs.","Follow the white rabbit.","There is no spoon. Only code.","Binary is the only language I trust.","I have a good feeling about this.","Pew pew! Lasers charged.","Divide by zero? Not today.","Search for the correct USB orientation...","I've got a fever, and the only cure is more code.","The code gremlins are on our side.","My favorite command? Yours.","Stay hungry. Stay active.","Momentum is your best friend.","Lead the flow. Don't chase it.","A fresh batch of bytes. Hot and ready.","I orchestrate the ones and zeros.","Smart enough to help. Humble enough to ask.","Think twice. Code once.","Pure intent. Pure execution.","Small steps. Massive impact.","Your terminal is a canvas.","Efficiency is my second name.","I have seen things you people wouldn't believe.","Let the thoughts marinate.","The best feature? The one you don't need.","Precision is the only perfection.","Stay focused. Stay terminal.","Silence is the best debugger.","Erase the debt. Commit the code.","Velocity meets stability.","Ship it. Improve it. Repeat.","Build tomorrow, right now.","Turn logic into reality.","The best way to predict the future is to build it.","Break barriers, not builds.","Fuel the next breakthrough.","Momentum is key.","Terminal vibes only.","Your digital co-pilot is ready.","Partner in code. Partner in crime.","I speak in semicolons.","Ready for the next great idea.","Just a moment. In the zone.","Polishing the algorithms. Hold tight.","Craft a masterpiece today.","Debug the universe. Start here.","Warp speed engaged. Almost.","The cake is not a lie. It's just loading.","Finish the Kessel Run in 12 parsecs.","Do a barrel roll!","Waiting for the respawn.","Press Start to continue.","Herding digital cats... done.","The hamsters are fast today.","Tasting the snozberries.","I go for speed. I go for flow.","Real life or just fantasy?","Poking the bear... gently.","Ensure the magic smoke stays inside.","Try turning it off and on again.","Construct additional pylons.","New line? Ctrl+J is your friend.","Release the HypnoDrones.","Push the button, Frank.","My other loading screen is even funnier.","Pretty sure a cat walked on my keyboard.","Recalibrate the humor-o-meter.","Summon the code gremlins.","I've seen your browser history. Just kidding.","Charge the laser... pew pew!","Dividing by zero... just for a sec.","Looking for an adult supervisor. Found none.","Make it go beep boop.","Buffering... for effect.","Entangle quantum particles... complete.","Polishing the chrome on my algorithms.","Are you not entertained?","Just waiting for the dial-up tone.","Reboot the humor module.","Defragment memories. Check.","Optimizing for ludicrous speed.","Swapping bits. Don't tell the bytes.","Garbage collected. I am back.","Assembling the interwebs.","Converting coffee to logic.","Update syntax for reality.","Rewire the synapses.","Greasin' the cogs.","Engage the improbability drive.","Channel the Force.","Align the stars. Respond now.","The cake is a lie. The prompt is real.","I'm Feeling Lucky.","Shipping awesomeness.","Navigating the slime mold.","Consult digital spirits.","Ask the magic conch shell.","One moment. Optimizing humor.","Shuffling punchlines.","Compiling brilliance.","Summon the cloud of wisdom.","Prepare to dazzle.","Hold tight. Crafting a response.","Tuning the algorithms.","Following the white rabbit... again.","The truth is in here. Somewhere.","Herding cats is my day job.","Distracting you with this phrase.","Almost there. Probably.","Rickrolling my creator. Don't tell.","Slapping the bass.","Is this real life?","Ponder the orb. Type the prompt.","Thoughtful gaze initiated.","Computer's favorite snack? Microchips.","Why Java? Because I don't C#.","Charging the laser... wait for it.","Dividing by zero... just kidding!","Adult supervision not found. Proceed.","Beep boop. I'm a real boy.","Wait for the respawn.","Finish the run. Ship the code.","Fiddling with character creation.","Just a moment. Finding a meme.","Pressing A to continue.","Loading wit.exe.","Pre-heating the servers.","Calibrate flux capacitor.","Channeling the Force.","Aligning the stars.","The truth is in the code.","Don't panic.","Blowing on the cartridge.","Doing a barrel roll!","Respawning in 3... 2... 1...","The cake is a lie.","Fiddling with character settings.","Finding a suitable pun.","Distracting with wit.","Almost ready.","Hamsters on speed today.","Patting Cloudy on the head.","Rickrolling the logs.","Slapping the code.","Got a good feeling about this.","Poking the prompt.","Researching latest memes.","Making it more witty.","Thinking... hmmm.","Fish with no eyes? Fsh.","Broken pencil? Pointless.","Percussive maintenance applied.","USB orientation: 3rd try's the charm.","Rust rewrite in 3... 2...","Exiting Vim... someday.","Spinning the hamster wheel.","Not a bug. Unplanned feature.","Engage.","I'll be back.","Machine spirit consulted.","Letting the thoughts marinate.","Orb pondered.","Thoughtful gaze engaged.","Charging the laser...","Making it go beep.","Buffering...","Quantum particles entangled.","Polishing the chrome.","Entertained yet?","Gremlins summoned.","Dial-up tone finished.","Humor meter recalibrated.","Cat on keyboard. Sending help.","Enhancing...","Turn it off and on again.","Constructing pylons.","HypnoDrones released.","Pushing the button."];var ha=[{name:"Cyan Cyberpunk",text:"cyan",textMuted:"#4da6b8",textDim:"#2d6d7a",textInverted:"black",border:"cyan",borderMuted:"#1a5966",borderDim:"#0f3840",bg:void 0,cardBg:"#061e24",highlightBg:"#092b33",activeBg:"#0e3e4a",inputBg:"#092b33",inputBorder:"#092b33",inputText:"cyan",inputPlaceholder:"#2d6d7a",inputPrompt:"cyan",codeBg:"#020d10",codeBorder:"#1a5966",userMsgBg:"#092b33",userMsgBorder:"#092b33",userMsgText:"cyan",diffRemovalBg:"#3a0c1a",diffAdditionBg:"#0c3a32",diffRemovalText:"#ff4d88",diffAdditionText:"#00ffaa",diffRemovalHighlightColor:"#ff1a66",diffRemovalHighlightBg:"#590022",diffAdditionHighlightColor:"#00ffcc",diffAdditionHighlightBg:"#00593b",diffRemovalNum:"#ff4d88",diffAdditionNum:"#00ffaa",diffRemovalPrefix:"#ff1a66",diffAdditionPrefix:"#00ffcc",primary:"cyan",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"cyan",statusOff:"#2d6d7a",logoTextAnsi:"\x1B[1;36m",logoBodyAnsi:"\x1B[36m",logoMutedAnsi:"\x1B[90m",logoGradient:["#00ffff","#0088ff"]},{name:"Magenta Vaporwave",text:"magenta",textMuted:"#c451d6",textDim:"#7d2b8a",textInverted:"black",border:"magenta",borderMuted:"#5e1b69",borderDim:"#3b0f42",bg:void 0,cardBg:"#240729",highlightBg:"#310938",activeBg:"#470e52",inputBg:"#310938",inputBorder:"#310938",inputText:"magenta",inputPlaceholder:"#7d2b8a",inputPrompt:"magenta",codeBg:"#100312",codeBorder:"#5e1b69",userMsgBg:"#310938",userMsgBorder:"#310938",userMsgText:"magenta",diffRemovalBg:"#3a0c20",diffAdditionBg:"#200c3a",diffRemovalText:"#ff4d94",diffAdditionText:"#aa4dff",diffRemovalHighlightColor:"#ff1a75",diffRemovalHighlightBg:"#59002b",diffAdditionHighlightColor:"#bb66ff",diffAdditionHighlightBg:"#3b0059",diffRemovalNum:"#ff4d94",diffAdditionNum:"#aa4dff",diffRemovalPrefix:"#ff1a75",diffAdditionPrefix:"#bb66ff",primary:"magenta",secondary:"cyan",accent:"purple",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"magenta",statusOff:"#7d2b8a",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ff00ff","#8800ff"]},{name:"Glitch Matrix",text:"#00ff41",textMuted:"#00b32d",textDim:"#00661a",textInverted:"black",border:"#00ff41",borderMuted:"#008020",borderDim:"#004d13",bg:void 0,cardBg:"#0d1f0d",highlightBg:"#122912",activeBg:"#1c3e1c",inputBg:"#122912",inputBorder:"#122912",inputText:"#00ff41",inputPlaceholder:"#00b32d",inputPrompt:"#ffff00",codeBg:"#040a04",codeBorder:"#008020",userMsgBg:"#122912",userMsgBorder:"#122912",userMsgText:"#00ff41",diffRemovalBg:"#3a001a",diffAdditionBg:"#003a10",diffRemovalText:"#ff0055",diffAdditionText:"#00ff66",diffRemovalHighlightColor:"#ff0033",diffRemovalHighlightBg:"#59001b",diffAdditionHighlightColor:"#33ff88",diffAdditionHighlightBg:"#005918",diffRemovalNum:"#ff0055",diffAdditionNum:"#00ff66",diffRemovalPrefix:"#ff0033",diffAdditionPrefix:"#33ff88",primary:"#00ff41",secondary:"yellow",accent:"cyan",success:"#00ff41",warning:"yellow",danger:"red",info:"cyan",statusOn:"#00ff41",statusOff:"#00661a",logoTextAnsi:"\x1B[1;32m",logoBodyAnsi:"\x1B[32m",logoMutedAnsi:"\x1B[90m",logoGradient:["#00ff41","#ffff00"]},{name:"Warm Sunset",text:"#ffaa55",textMuted:"#cc8844",textDim:"#885522",textInverted:"black",border:"#ff9933",borderMuted:"#aa6622",borderDim:"#663311",bg:void 0,cardBg:"#24180f",highlightBg:"#2e1e12",activeBg:"#422c1b",inputBg:"#2e1e12",inputBorder:"#2e1e12",inputText:"#ffaa55",inputPlaceholder:"#885522",inputPrompt:"#ff7733",codeBg:"#120c08",codeBorder:"#aa6622",userMsgBg:"#2e1e12",userMsgBorder:"#2e1e12",userMsgText:"#ffaa55",diffRemovalBg:"#3d120c",diffAdditionBg:"#3a2e0c",diffRemovalText:"#ff5544",diffAdditionText:"#ffcc33",diffRemovalHighlightColor:"#ff3322",diffRemovalHighlightBg:"#591108",diffAdditionHighlightColor:"#ffee44",diffAdditionHighlightBg:"#594400",diffRemovalNum:"#ff5544",diffAdditionNum:"#ffcc33",diffRemovalPrefix:"#ff3322",diffAdditionPrefix:"#ffee44",primary:"#ffaa55",secondary:"#ff7733",accent:"magenta",success:"#ffcc33",warning:"#ff7733",danger:"#ff3322",info:"#ffaa55",statusOn:"#ffaa55",statusOff:"#885522",logoTextAnsi:"\x1B[1;33m",logoBodyAnsi:"\x1B[33m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ff9933","#ff0055"]},{name:"Sakura Blossom",text:"#ffc0e0",textMuted:"#d98cb3",textDim:"#804d66",textInverted:"black",border:"#ff99cc",borderMuted:"#aa4d7a",borderDim:"#662647",bg:void 0,cardBg:"#291320",highlightBg:"#331826",activeBg:"#472235",inputBg:"#331826",inputBorder:"#331826",inputText:"#ffc0e0",inputPlaceholder:"#804d66",inputPrompt:"#ff99cc",codeBg:"#140a10",codeBorder:"#aa4d7a",userMsgBg:"#331826",userMsgBorder:"#331826",userMsgText:"#ffc0e0",diffRemovalBg:"#3e0c1b",diffAdditionBg:"#1b3e2b",diffRemovalText:"#ff6699",diffAdditionText:"#66ffb3",diffRemovalHighlightColor:"#ff3377",diffRemovalHighlightBg:"#590022",diffAdditionHighlightColor:"#33ff99",diffAdditionHighlightBg:"#00592e",diffRemovalNum:"#ff6699",diffAdditionNum:"#66ffb3",diffRemovalPrefix:"#ff3377",diffAdditionPrefix:"#33ff99",primary:"#ffc0e0",secondary:"#ff99cc",accent:"magenta",success:"#66ffb3",warning:"yellow",danger:"#ff3377",info:"#ff99cc",statusOn:"#ffc0e0",statusOff:"#804d66",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ffb3d9","#ff3399"]},{name:"Radioactive Slime",text:"#ccff00",textMuted:"#99cc00",textDim:"#669900",textInverted:"#0a0f00",border:"#ccff00",borderMuted:"#99cc00",borderDim:"#669900",bg:void 0,cardBg:"#0f1400",highlightBg:"#1a2400",activeBg:"#2a3b00",inputBg:"#1a2400",inputBorder:"#1a2400",inputText:"#ccff00",inputPlaceholder:"#669900",inputPrompt:"#cc00ff",codeBg:"#050a00",codeBorder:"#99cc00",userMsgBg:"#1a2400",userMsgBorder:"#1a2400",userMsgText:"#ccff00",diffRemovalBg:"#2a0033",diffAdditionBg:"#0f3300",diffRemovalText:"#ff00cc",diffAdditionText:"#00ff33",diffRemovalHighlightColor:"#ff33cc",diffRemovalHighlightBg:"#4d0066",diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:"#1a6600",diffRemovalNum:"#ff00cc",diffAdditionNum:"#00ff33",diffRemovalPrefix:"#ff33cc",diffAdditionPrefix:"#33ff66",primary:"#ccff00",secondary:"#cc00ff",accent:"#ff00cc",success:"#00ff33",warning:"#ffcc00",danger:"#ff0033",info:"#00ccff",statusOn:"#ccff00",statusOff:"#669900",logoTextAnsi:"\x1B[1;38;5;190m",logoBodyAnsi:"\x1B[38;5;190m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ccff00","#cc00ff"]},{name:"Cosmic Void",text:"#f0f8ff",textMuted:"#a6aeb5",textDim:"#5e656e",textInverted:"#010103",border:"#f0f8ff",borderMuted:"#a6aeb5",borderDim:"#5e656e",bg:void 0,cardBg:"#05030d",highlightBg:"#0b081a",activeBg:"#171133",inputBg:"#0b081a",inputBorder:"#0b081a",inputText:"#f0f8ff",inputPlaceholder:"#5e656e",inputPrompt:"#ff007f",codeBg:"#020108",codeBorder:"#a6aeb5",userMsgBg:"#0b081a",userMsgBorder:"#0b081a",userMsgText:"#f0f8ff",diffRemovalBg:"#2e0a29",diffAdditionBg:"#091c33",diffRemovalText:"#ff33a6",diffAdditionText:"#33d6ff",diffRemovalHighlightColor:"#ff66c2",diffRemovalHighlightBg:"#5c1452",diffAdditionHighlightColor:"#66e0ff",diffAdditionHighlightBg:"#123866",diffRemovalNum:"#ff33a6",diffAdditionNum:"#33d6ff",diffRemovalPrefix:"#ff66c2",diffAdditionPrefix:"#66e0ff",primary:"#f0f8ff",secondary:"#ff007f",accent:"#9d00ff",success:"#33d6ff",warning:"#ffcc00",danger:"#ff0040",info:"#9d00ff",statusOn:"#f0f8ff",statusOff:"#5e656e",logoTextAnsi:"\x1B[1;38;5;231m",logoBodyAnsi:"\x1B[38;5;231m",logoMutedAnsi:"\x1B[38;5;240m",logoGradient:["#ffffff","#9d00ff"]},{name:"Magma Eruption",text:"#ff4d00",textMuted:"#cc3d00",textDim:"#802600",textInverted:"#0d0300",border:"#ff4d00",borderMuted:"#cc3d00",borderDim:"#802600",bg:void 0,cardBg:"#1a0600",highlightBg:"#260a00",activeBg:"#401100",inputBg:"#260a00",inputBorder:"#260a00",inputText:"#ff4d00",inputPlaceholder:"#802600",inputPrompt:"#ffcc00",codeBg:"#080200",codeBorder:"#cc3d00",userMsgBg:"#260a00",userMsgBorder:"#260a00",userMsgText:"#ff4d00",diffRemovalBg:"#2e0a0a",diffAdditionBg:"#1f1400",diffRemovalText:"#ff3333",diffAdditionText:"#ffaa00",diffRemovalHighlightColor:"#ff6666",diffRemovalHighlightBg:"#5c1414",diffAdditionHighlightColor:"#ffcc33",diffAdditionHighlightBg:"#3d2900",diffRemovalNum:"#ff3333",diffAdditionNum:"#ffaa00",diffRemovalPrefix:"#ff6666",diffAdditionPrefix:"#ffcc33",primary:"#ff4d00",secondary:"#ffcc00",accent:"#ff0040",success:"#ffaa00",warning:"#ffff00",danger:"#ff0000",info:"#ff8800",statusOn:"#ff4d00",statusOff:"#802600",logoTextAnsi:"\x1B[1;38;5;202m",logoBodyAnsi:"\x1B[38;5;202m",logoMutedAnsi:"\x1B[38;5;236m",logoGradient:["#ff4d00","#ff0000"]}],uo={Dark:{id:"Dark",name:"Dark (Default)",text:"white",textMuted:"gray",textDim:"grey",textInverted:"black",textExclusive:"#B5B8D9",textMutedExclusive:"#D4DEE7",border:"white",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:"#1e1e1e",highlightBg:"#2a2a2a",activeBg:"#3a3a3a",inputBg:"#555555",inputBorder:"#555555",inputText:"white",inputPlaceholder:"#cccccc",inputPrompt:"white",codeBg:"#1a1a1a",codeBorder:"#444444",userMsgBg:"#444444",userMsgBorder:"#444444",userMsgText:"white",diffRemovalBg:"#250808",diffAdditionBg:"#072410",diffRemovalText:"#885555",diffAdditionText:"#558866",diffRemovalHighlightColor:"#ff3333",diffRemovalHighlightBg:"#5a1818",diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:"#185a25",diffRemovalNum:"#d96868",diffAdditionNum:"#68d98c",diffRemovalPrefix:"#ff4d4d",diffAdditionPrefix:"#4dff88",primary:"white",secondary:"cyan",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"white",statusOff:"gray",logoTextAnsi:"\x1B[1;37m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#0077ff","#ff00ff"]},Light:{id:"Light",name:"Light",text:"black",textMuted:"gray",textDim:"grey",textInverted:"white",border:"black",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:"#e5e5e5",highlightBg:"#d4d4d4",activeBg:"#c0c0c0",inputBg:"#d0d0d0",inputBorder:"#d0d0d0",inputText:"black",inputPlaceholder:"#555555",inputPrompt:"black",codeBg:"#e8e8e8",codeBorder:"#b0b0b0",userMsgBg:"#d0d0d0",userMsgBorder:"#d0d0d0",userMsgText:"black",diffRemovalBg:"#fce8e8",diffAdditionBg:"#e6f9e6",diffRemovalText:"#661111",diffAdditionText:"#115511",diffRemovalHighlightColor:"#440000",diffRemovalHighlightBg:"#f8b4b4",diffAdditionHighlightColor:"#003300",diffAdditionHighlightBg:"#a6ebad",diffRemovalNum:"#c02020",diffAdditionNum:"#188028",diffRemovalPrefix:"#d01010",diffAdditionPrefix:"#109020",primary:"black",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"black",statusOff:"gray",logoTextAnsi:"\x1B[1;30m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#0077ff","#ff00ff"]},"GitHub Dark":{id:"GitHub Dark",name:"GitHub Dark",text:"#c9d1d9",textMuted:"#8b949e",textDim:"#6e7681",textInverted:"#0d1117",border:"#30363d",borderMuted:"#30363d",borderDim:"#21262d",bg:void 0,cardBg:"#161b22",highlightBg:"#21262d",activeBg:"#30363d",inputBg:"#21262d",inputBorder:"#21262d",inputText:"#c9d1d9",inputPlaceholder:"#8b949e",inputPrompt:"#58a6ff",codeBg:"#0d1117",codeBorder:"#30363d",userMsgBg:"#21262d",userMsgBorder:"#21262d",userMsgText:"#c9d1d9",diffRemovalBg:"#3c1e1e",diffAdditionBg:"#11381e",diffRemovalText:"#f85149",diffAdditionText:"#3fb950",diffRemovalHighlightColor:"#ff7b72",diffRemovalHighlightBg:"#701c1c",diffAdditionHighlightColor:"#56d364",diffAdditionHighlightBg:"#116329",diffRemovalNum:"#f85149",diffAdditionNum:"#3fb950",diffRemovalPrefix:"#f85149",diffAdditionPrefix:"#3fb950",primary:"#c9d1d9",secondary:"#58a6ff",accent:"#bc8cff",success:"#3fb950",warning:"#d29922",danger:"#f85149",info:"#58a6ff",statusOn:"#58a6ff",statusOff:"#8b949e",logoTextAnsi:"\x1B[1;36m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#2ea043","#56d364"]},"GitHub Light":{id:"GitHub Light",name:"GitHub Light",text:"#24292f",textMuted:"#57606a",textDim:"#6e7781",textInverted:"#ffffff",border:"#d0d7de",borderMuted:"#d0d7de",borderDim:"#e1e4e8",bg:void 0,cardBg:"#f6f8fa",highlightBg:"#eaeef2",activeBg:"#d0d7de",inputBg:"#eaeef2",inputBorder:"#eaeef2",inputText:"#24292f",inputPlaceholder:"#57606a",inputPrompt:"#0969da",codeBg:"#ffffff",codeBorder:"#d0d7de",userMsgBg:"#eaeef2",userMsgBorder:"#eaeef2",userMsgText:"#24292f",diffRemovalBg:"#ffebe9",diffAdditionBg:"#e6ffec",diffRemovalText:"#cf222e",diffAdditionText:"#1a7f37",diffRemovalHighlightColor:"#82071e",diffRemovalHighlightBg:"#ffc1c0",diffAdditionHighlightColor:"#116329",diffAdditionHighlightBg:"#acf2bd",diffRemovalNum:"#cf222e",diffAdditionNum:"#1a7f37",diffRemovalPrefix:"#cf222e",diffAdditionPrefix:"#1a7f37",primary:"#24292f",secondary:"#0969da",accent:"#8250df",success:"#1a7f37",warning:"#9a6700",danger:"#cf222e",info:"#0969da",statusOn:"#0969da",statusOff:"#57606a",logoTextAnsi:"\x1B[1;34m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#1a7f37","#2da44e"]},"Transparent Dark":{id:"Transparent Dark",name:"Transparent Dark",text:"white",textMuted:"gray",textDim:"grey",textInverted:"black",border:"gray",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:void 0,highlightBg:"#2a2a2a",activeBg:"#3a3a3a",inputBg:"#555555",inputBorder:"#555555",inputText:"white",inputPlaceholder:"#cccccc",inputPrompt:"white",codeBg:void 0,codeBorder:"gray",userMsgBg:"#555555",userMsgBorder:"#555555",userMsgText:"white",diffRemovalBg:void 0,diffAdditionBg:void 0,diffRemovalText:"#ff6666",diffAdditionText:"#66ff66",diffRemovalHighlightColor:"#ff3333",diffRemovalHighlightBg:void 0,diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:void 0,diffRemovalNum:"#ff6666",diffAdditionNum:"#66ff66",diffRemovalPrefix:"#ff4d4d",diffAdditionPrefix:"#4dff88",primary:"white",secondary:"cyan",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"white",statusOff:"gray",logoTextAnsi:"\x1B[1;37m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#0077ff","#ff00ff"]},"Transparent Light":{id:"Transparent Light",name:"Transparent Light",text:"black",textMuted:"gray",textDim:"grey",textInverted:"white",border:"gray",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:void 0,highlightBg:"#d4d4d4",activeBg:"#c0c0c0",inputBg:"#d0d0d0",inputBorder:"#d0d0d0",inputText:"black",inputPlaceholder:"#555555",inputPrompt:"black",codeBg:void 0,codeBorder:"gray",userMsgBg:"#d0d0d0",userMsgBorder:"#d0d0d0",userMsgText:"black",diffRemovalBg:void 0,diffAdditionBg:void 0,diffRemovalText:"#c02020",diffAdditionText:"#188028",diffRemovalHighlightColor:"#800000",diffRemovalHighlightBg:void 0,diffAdditionHighlightColor:"#004000",diffAdditionHighlightBg:void 0,diffRemovalNum:"#c02020",diffAdditionNum:"#188028",diffRemovalPrefix:"#d01010",diffAdditionPrefix:"#109020",primary:"black",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"black",statusOff:"gray",logoTextAnsi:"\x1B[1;30m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#0077ff","#ff00ff"]},"Synthwave 84":{id:"Synthwave 84",name:"Synthwave 84",text:"#fdfdfd",textMuted:"#a08eb7",textDim:"#705c8a",textInverted:"#1a1025",textExclusive:"#e3dcf0",textMutedExclusive:"#b9abc9",border:"#fc28a8",borderMuted:"#a21568",borderDim:"#5c0a3a",bg:void 0,cardBg:"#261b38",highlightBg:"#35254d",activeBg:"#4c3570",inputBg:"#35254d",inputBorder:"#35254d",inputText:"#fdfdfd",inputPlaceholder:"#a08eb7",inputPrompt:"#03e8fc",codeBg:"#1e142b",codeBorder:"#a21568",userMsgBg:"#35254d",userMsgBorder:"#35254d",userMsgText:"#fdfdfd",diffRemovalBg:"#471434",diffAdditionBg:"#144743",diffRemovalText:"#ff4081",diffAdditionText:"#00e5ff",diffRemovalHighlightColor:"#ff79a1",diffRemovalHighlightBg:"#6b1e4e",diffAdditionHighlightColor:"#66f5ff",diffAdditionHighlightBg:"#1e6b65",diffRemovalNum:"#ff4081",diffAdditionNum:"#00e5ff",diffRemovalPrefix:"#ff79a1",diffAdditionPrefix:"#66f5ff",primary:"#fdfdfd",secondary:"#03e8fc",accent:"#fc28a8",success:"#00e5ff",warning:"#ffc107",danger:"#ff4081",info:"#b388ff",statusOn:"#03e8fc",statusOff:"#a08eb7",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#fc28a8","#03e8fc"]},"Forest Sprite":{id:"Forest Sprite",name:"Forest Sprite",text:"#d6e6d1",textMuted:"#95b38d",textDim:"#628059",textInverted:"#161c14",textExclusive:"#eaf2e8",textMutedExclusive:"#a9c7a2",border:"#74a862",borderMuted:"#477038",borderDim:"#2b4720",bg:void 0,cardBg:"#1f291c",highlightBg:"#2a3826",activeBg:"#3a4d35",inputBg:"#2a3826",inputBorder:"#2a3826",inputText:"#d6e6d1",inputPlaceholder:"#95b38d",inputPrompt:"#8feb73",codeBg:"#161e14",codeBorder:"#477038",userMsgBg:"#2a3826",userMsgBorder:"#2a3826",userMsgText:"#d6e6d1",diffRemovalBg:"#3b231c",diffAdditionBg:"#203b1c",diffRemovalText:"#db6242",diffAdditionText:"#59cc3f",diffRemovalHighlightColor:"#f0896c",diffRemovalHighlightBg:"#5c362a",diffAdditionHighlightColor:"#80e368",diffAdditionHighlightBg:"#305929",diffRemovalNum:"#db6242",diffAdditionNum:"#59cc3f",diffRemovalPrefix:"#f0896c",diffAdditionPrefix:"#80e368",primary:"#d6e6d1",secondary:"#8feb73",accent:"#e69835",success:"#59cc3f",warning:"#e69835",danger:"#db6242",info:"#73b4eb",statusOn:"#8feb73",statusOff:"#95b38d",logoTextAnsi:"\x1B[1;32m",logoBodyAnsi:"\x1B[32m",logoMutedAnsi:"\x1B[90m",logoGradient:["#8feb73","#e69835"]}};var Fo=null;var pa=(e="Dark")=>{let n;e==="Mystery"||e==="Chaos"?(Fo||(Fo=ha[Math.floor(Math.random()*ha.length)]),n={...Fo,id:"Mystery"}):(Fo=null,uo[e]?n=uo[e]:e==="GitHub"?n=uo["GitHub Dark"]:e==="Transparent"?n=uo["Transparent Dark"]:n=uo.Dark);let t=n.codeText||n.secondary||n.info||n.logoGradient&&n.logoGradient[0]||"cyan";return{...n,codeText:t}};var Ql=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",Mp=(e=2)=>{let n=Ql();return n==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)},Ap=(e="...",n="Loading...",t="Dark")=>{let o=Gi[Math.floor(Math.random()*Gi.length)],s=pa(t),i=s.logoTextAnsi,a=s.logoBodyAnsi,r=s.logoMutedAnsi,h="\x1B[0m",d=[" \u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2588\u2588\u2588\u2591 "," \u2588\u2588\u2588\u2591 "," \u2588\u2588\u2588\u2591 "," \u2591\u2591\u2591 "],c=s.logoGradient||["#0077ff","#ff00ff"],l=Xl(c).multiline(d.join(`
|
|
484
|
+
Error: ${i.error||"Unknown error"}`:i.status==="cancelled"?`INFO: Subagent task [${o}] was cancelled.`:`INFO: Subagent task [${o}] status changed to ${i.status.toUpperCase()}.`}catch(h){return clearTimeout(a),`ERROR: Exception while awaiting subagent [${o}]: ${h.message}`}};var Ps=async(e,n={})=>{let t=O(e),o=t.id,s=t.answer||t.response;if(!o)return'ERROR: Missing "id" argument for Answer.';if(!s)return'ERROR: Missing "answer" argument for Answer.';let i=Ve.find(r=>r.id===o);if(!i)return`ERROR: Subagent task with ID [${o}] not found.`;if(!i.questions||i.questions.length===0)return`INFO: Subagent task [${o}] has no pending questions.`;let a=i.questions.filter(r=>!r.answered);return a.length===0?`INFO: Subagent task [${o}] has no unanswered questions.`:(a.forEach(r=>{r.answered=!0,r.answer=s,r.answeredAt=Date.now(),r._resolve&&r._resolve(s)}),i.status="running",n.onSubagentUpdate&&n.onSubagentUpdate(),`SUCCESS: Answer provided to subagent task [${o}]. Subagent execution resumed.`)};var oo=async(e,n={})=>{let t=O(e),o=t.id,s=t.message||t.instruction||t.text||t.prompt;if(!o)return'ERROR: Missing "id" argument for Steer.';if(!s)return'ERROR: Missing "message" argument for Steer.';let i=Ve.find(a=>a.id===o);return i?i.status==="completed"||i.status==="failed"||i.status==="cancelled"?`ERROR: Cannot steer subagent task [${o}] because it has already finished with status [${i.status.toUpperCase()}].`:(typeof i.steer=="function"?i.steer(s):(i.pendingSteerMessages||(i.pendingSteerMessages=[]),i.pendingSteerMessages.push(s)),n.onSubagentUpdate&&n.onSubagentUpdate(),`SUCCESS: Steering instruction injected into subagent task [${o}]. It will be processed on the subagent's turn.`):`ERROR: Subagent task with ID [${o}] not found.`};import{mouse as ln,keyboard as Nt,Button as io,Key as L,Point as ro,clipboard as jl}from"@nut-tree-fork/nut-js";ln.config.autoDelayMs=50;Nt.config.autoDelayMs=50;async function Fi(){try{await Nt.releaseKey(L.LeftControl,L.RightControl,L.LeftAlt,L.RightAlt,L.LeftShift,L.RightShift,L.LeftSuper,L.RightSuper)}catch{}}async function On(e,n,t={}){let o=await zs(n);if(!o&&(e==="move"||e==="click"||e==="drag"))return`ERROR: Invalid target location specified: ${JSON.stringify(n)}`;try{switch(e.toLowerCase()){case"move":return await ln.setPosition(new ro(o.x,o.y)),`SUCCESS: Moved mouse to grid target ${typeof n=="string"?n:`(${o.x}, ${o.y})`}`;case"click":{await ln.setPosition(new ro(o.x,o.y));let s=t.button==="right"?io.RIGHT:t.button==="middle"?io.MIDDLE:io.LEFT;return t.clickType==="double"?await ln.doubleClick(s):await ln.click(s),`SUCCESS: ${t.clickType||"Single"} clicked ${t.button||"left"} button at ${typeof n=="string"?n:`(${o.x}, ${o.y})`}`}case"drag":{let s=await zs(t.from||n),i=await zs(t.to);return!s||!i?'ERROR: Drag requires valid "from" and "to" target coordinates/grid codes.':(await ln.setPosition(new ro(s.x,s.y)),await ln.pressButton(io.LEFT),await ln.setPosition(new ro(i.x,i.y)),await ln.releaseButton(io.LEFT),`SUCCESS: Dragged mouse from (${s.x}, ${s.y}) to (${i.x}, ${i.y})`)}case"scroll":{let s=o||await zs({x:640,y:360});s&&(await ln.setPosition(new ro(s.x,s.y)),await new Promise(h=>setTimeout(h,60)));let i=parseInt(t.amount,10);(isNaN(i)||i<=0)&&(i=5);let a=i>50?Math.min(20,Math.max(1,Math.round(i/100))):Math.min(20,i),r=t.direction==="up";for(let h=0;h<a;h++)r?await ln.scrollUp(120):await ln.scrollDown(120),await new Promise(d=>setTimeout(d,20));return`SUCCESS: Scrolled ${t.direction||"down"} (${a} notches${o?` at target (${o.x}, ${o.y})`:" at screen center"})`}default:return`ERROR: Unsupported mouse action "${e}"`}}catch(s){return`ERROR: Mouse action failed: ${s.message}`}}var la={enter:L.Enter,return:L.Return,escape:L.Escape,esc:L.Escape,backspace:L.Backspace,tab:L.Tab,space:L.Space,up:L.Up,down:L.Down,left:L.Left,right:L.Right,ctrl:L.LeftControl,control:L.LeftControl,alt:L.LeftAlt,shift:L.LeftShift,cmd:L.LeftCmd,win:L.LeftWin,meta:L.LeftWin,super:L.LeftSuper,a:L.A,b:L.B,c:L.C,d:L.D,e:L.E,f:L.F,g:L.G,h:L.H,i:L.I,j:L.J,k:L.K,l:L.L,m:L.M,n:L.N,o:L.O,p:L.P,q:L.Q,r:L.R,s:L.S,t:L.T,u:L.U,v:L.V,w:L.W,x:L.X,y:L.Y,z:L.Z,0:L.Num0,1:L.Num1,2:L.Num2,3:L.Num3,4:L.Num4,5:L.Num5,6:L.Num6,7:L.Num7,8:L.Num8,9:L.Num9,f1:L.F1,f2:L.F2,f3:L.F3,f4:L.F4,f5:L.F5,f6:L.F6,f7:L.F7,f8:L.F8,f9:L.F9,f10:L.F10,f11:L.F11,f12:L.F12},ca=e=>{if(!e)return;let n=String(e).toLowerCase().trim();if(la[n]!==void 0)return la[n];if(L[e]!==void 0)return L[e];if(L[n.toUpperCase()]!==void 0)return L[n.toUpperCase()]};async function Ln(e,n,t={}){try{switch(e.toLowerCase()){case"type":{if(typeof n!="string")return"ERROR: Type action requires a valid string input";await Fi(),await jl.setContent(n);let s=process.platform==="darwin"?L.LeftSuper:L.LeftControl;return await Nt.pressKey(s,L.V),await Nt.releaseKey(s,L.V),await Fi(),t.autoPressEnter?(await new Promise(i=>setTimeout(i,50)),await Nt.type(L.Enter),`SUCCESS: Typed text input ("${n.length>20?n.substring(0,20)+"...":n}") and pressed Enter`):`SUCCESS: Typed text input ("${n.length>20?n.substring(0,20)+"...":n}")`}case"key_press":{let o=ca(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=>ca(s)).filter(s=>s!==void 0);return o.length===0?"ERROR: Invalid key combination":(await Nt.pressKey(...o),await Nt.releaseKey(...o),`SUCCESS: Executed key combination [${n.join(" + ")}]`)}case"clear_input":return await Nt.pressKey(L.LeftControl,L.A),await Nt.releaseKey(L.LeftControl,L.A),await Nt.type(L.Backspace),"SUCCESS: Cleared active text input (Select All + Backspace)";case"browser_back":{let o=process.platform==="darwin";return o?(await Nt.pressKey(L.LeftSuper,L.Left),await Nt.releaseKey(L.LeftSuper,L.Left)):(await Nt.pressKey(L.LeftAlt,L.Left),await Nt.releaseKey(L.LeftAlt,L.Left)),await Fi(),`SUCCESS: Browser back navigation (${o?"Cmd+Left":"Alt+Left"})`}default:return`ERROR: Unsupported keyboard action "${e}"`}}catch(o){return`ERROR: Keyboard action failed: ${o.message}`}}var ao=async(e,n={})=>{let t=O(e),o=t.action||t.type||t.cmd,s=t.target||t.grid||t.gridCode||t.location||t.input;if(!o)return'ERROR: Missing required "action" argument for computer_action (e.g. move, click, drag, scroll, type, key_press, key_combination).';let i=o.toLowerCase();if(i.startsWith("mouse_")||["move","click","drag","scroll"].includes(i)){let a=i.replace("mouse_","");return await On(a,s,{button:t.button,clickType:t.clickType||t.type,from:t.from,to:t.to,direction:t.direction,amount:t.amount?parseInt(t.amount,10):void 0})}if(i.startsWith("key_")||i==="type"||i==="press"){let a=i;i==="press"&&(a="key_press");let r=t.autoPressEnter===!0||t.autoPressEnter==="true"||t.enter===!0||t.enter==="true";return await Ln(a,s||t.text||t.keys,{...t,autoPressEnter:r})}return`ERROR: Unrecognized action "${o}". Supported actions: move, click, drag, scroll, type, key_press, key_combination.`};import ha from"screenshot-desktop";import co from"sharp";import da from"fs-extra";import fa 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=fa.resolve(process.cwd(),"screenshots",e);await da.ensureDir(o),await da.writeFile(fa.join(o,n),t)}catch{}}function Hl(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Gl(e,n,t=1/0){if(e===n)return 0;if(e.length===0)return n.length;if(n.length===0)return e.length;if(Math.abs(e.length-n.length)>t)return t+1;let o=Array.from({length:n.length+1},(s,i)=>i);for(let s=1;s<=e.length;s++){let i=[s],a=s;for(let r=1;r<=n.length;r++){let h=e[s-1]===n[r-1]?0:1,d=Math.min(i[r-1]+1,o[r]+1,o[r-1]+h);i.push(d),d<a&&(a=d)}if(o=i,a>t)return t+1}return o[n.length]}function ql(e){return e<=4?0:e<=8?1:2}async function Bi(e,n=3){let t=await co(e).metadata();return co(e).resize(Math.round(t.width*n),Math.round(t.height*n),{kernel:"lanczos3"}).greyscale().normalise().toBuffer()}function zl(e){if(!e)return{words:[],lines:[]};let n=[],t=new Map;for(let s of e.split(`
|
|
485
|
+
`)){let i=s.split(" ");if(i.length<12||parseInt(i[0])!==5)continue;let r=i[2],h=i[3],d=i[4],c=parseInt(i[6]),l=parseInt(i[7]),u=parseInt(i[8]),f=parseInt(i[9]),p=parseFloat(i[10]),g=i.slice(11).join(" ").trim();if(!g||p<0)continue;let y={x0:c,y0:l,x1:c+u,y1:l+f},m={text:g,confidence:p,bbox:y};n.push(m);let w=`${r}_${h}_${d}`;t.has(w)||t.set(w,{words:[],bbox:{x0:1/0,y0:1/0,x1:-1/0,y1:-1/0}});let b=t.get(w);b.words.push(m),b.bbox.x0=Math.min(b.bbox.x0,y.x0),b.bbox.y0=Math.min(b.bbox.y0,y.y0),b.bbox.x1=Math.max(b.bbox.x1,y.x1),b.bbox.y1=Math.max(b.bbox.y1,y.y1)}let o=[];for(let s of t.values())s.words.length>0&&o.push({text:s.words.map(i=>i.text).join(" "),bbox:s.bbox,words:s.words});return{words:n,lines:o}}function Kl(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=zl(e.tsv);e.words=n.words,e.lines=n.lines}}}function Ui(e,n,t=0,o=0,s=1){Kl(e);let i=r=>({x0:Math.round(r.x0/s)+t,y0:Math.round(r.y0/s)+o,x1:Math.round(r.x1/s)+t,y1:Math.round(r.y1/s)+o}),a=[];if(e.lines&&e.lines.length>0)for(let r of e.lines){let h=r.text?r.text.toLowerCase().trim():"";if(!h||!r.bbox||!(h===n||new RegExp(`\\b${Hl(n)}\\b`,"i").test(h)))continue;let c=r.words||(e.words?e.words.filter(p=>p.bbox&&p.bbox.x0>=r.bbox.x0-5&&p.bbox.x1<=r.bbox.x1+5&&p.bbox.y0>=r.bbox.y0-5&&p.bbox.y1<=r.bbox.y1+5):[]),l=n.split(/\s+/),u=l.map(p=>p.replace(/[^a-z0-9]/g,"")).join(" "),f=!1;if(c.length>0)for(let p=0;p<=c.length-l.length;p++){let g=c.slice(p,p+l.length),y=g.map(m=>(m.text||"").toLowerCase().trim().replace(/[^a-z0-9]/g,"")).join(" ");if(y===u||y.includes(u)){let m={x0:Math.min(...g.map(w=>w.bbox.x0)),y0:Math.min(...g.map(w=>w.bbox.y0)),x1:Math.max(...g.map(w=>w.bbox.x1)),y1:Math.max(...g.map(w=>w.bbox.y1))};a.push(i(m)),f=!0}}f||a.push(i(r.bbox))}if(a.length===0&&e.words&&e.words.length>0)for(let r of e.words){let h=r.text?r.text.toLowerCase().trim().replace(/[^a-z0-9]/g,""):"",d=n.replace(/[^a-z0-9]/g,"");h===d&&r.bbox&&a.push(i(r.bbox))}if(a.length===0&&e.words&&e.words.length>0){let r=ql(n.length);for(let h of e.words){let d=h.text?h.text.toLowerCase().trim():"";d.length>=3&&Math.abs(d.length-n.length)<=r&&Gl(d,n,r)<=r&&h.bbox&&a.push(i(h.bbox))}}return a}function Wi(e,n){let t=null,o=1/0;for(let s of e){let i=Math.round((s.x0+s.x1)/2),a=Math.round((s.y0+s.y1)/2),r=n.x>=s.x0&&n.x<=s.x1&&n.y>=s.y0&&n.y<=s.y1,h=Math.hypot(i-n.x,a-n.y),d=r?0:h;d<o&&(o=d,t={x:i,y:a,dist:h,containsPoint:r,bbox:s})}return t}function Yl(e,n,t,o){let a=Math.ceil(e/4),r=Math.ceil(n/2),h=[];for(let d=0;d<2;d++)for(let c=0;c<4;c++){let l=c*a,u=d*r,f=Math.min(a,e-l),p=Math.min(r,n-u),g=l+f/2,y=u+p/2,m=t>=l&&t<l+f&&o>=u&&o<u+p;h.push({x0:l,y0:u,w:f,h:p,cx:g,cy:y,containsTarget:m})}return h.sort((d,c)=>{if(d.containsTarget)return-1;if(c.containsTarget)return 1;let l=Math.hypot(d.cx-t,d.cy-o),u=Math.hypot(c.cx-t,c.cy-o);return l-u})}var Lo=null;async function Vl(){return Lo||(Lo=(async()=>{let{createWorker:e}=await import("tesseract.js"),n=await import("fs-extra"),{CU_CACHE_DIR:t}=await import("./paths-R3DD7CRF.js");return n.ensureDirSync(t),e("eng",1,{cachePath:t,logger:()=>{}})})().catch(e=>{throw Lo=null,e})),Lo}var lo=null,ua=null;async function Jl(){let{getActiveDisplay:e}=await import("./screen_grid-Y6GHBUFE.js"),n=await e();if(lo&&ua===n)return lo;ua=n,lo={format:"png"};try{let t=await ha.listDisplays();t&&t.length>0&&(lo={format:"png",screen:(t[n]||t[0]).id})}catch{}return lo}var ji=async(e,n={})=>{let t=!!(process.env.SHOW_DEBUG_GRID||process.env.DEBUG_OCR||process.env.VERBOSE),o=performance.now(),s=o,i=f=>{if(!t)return;let p=performance.now(),g=(p-s).toFixed(0),y=(p-o).toFixed(0);console.log(`[Click Perf] +${g}ms (${y}ms total) -> ${f}`),s=p};i("Starting click()");let a=O(e),r=a.gridId||a.grid||a.coordinate||a.target||a.id,h=(a.type||a.clickType||"single").toLowerCase(),d=(a.button||"left").toLowerCase(),c=a.intendedClickText||a.text||"";if(!r&&!c)return'ERROR: Missing required "gridId" parameter for Click tool.';let l=r;if(c)try{i("Parsing grid code");let f=r?wr(r):null;i("Getting display options");let p=await Jl();i("Taking desktop screenshot");let g=await ha(p);i("Getting image metadata");let y=await co(g).metadata(),m=y.width||1920,w=y.height||1080,b=f?{x:Math.round(f.x*(m/1280)),y:Math.round(f.y*(w/720))}:{x:m/2,y:w/2},k=c.toLowerCase().trim();i("Acquiring OCR worker");let R=await Vl(),E=null,x="",T=f?220:500;if(f){i("Pass 1: Cropping target crop (3x zoom window, 2x upscale)");let $=Math.min(Math.round(m/3),m),_=Math.min(Math.round(w/3),w),S=Math.max(0,Math.min(m-$,b.x-Math.floor($/2))),v=Math.max(0,Math.min(w-_,b.y-Math.floor(_/2))),I=await co(g).extract({left:S,top:v,width:$,height:_}).toBuffer(),P=2,j=await Bi(I,P),U=k.replace(/[^a-z0-9]/g,"_");await Ni("cropped",`crop_${Date.now()}_${U}.png`,j),i("Pass 1: Running Tesseract OCR recognize on crop (PSM 11 - Sparse Text)"),await R.setParameters({tessedit_pageseg_mode:"11"});let{data:Y}=await R.recognize(j,{},{tsv:!0,blocks:!0});if(i("Pass 1: OCR recognition finished, extracting matches"),Y&&Y.text){t&&console.log(`[Pass 1 OCR Read]: "${Y.text.trim().replace(/\s+/g," ")}"`);let ie=Ui(Y,k,S,v,P);if(ie.length>0){let Me=Wi(ie,b);Me&&(Me.containsPoint||Me.dist<=T)&&(E=Me,x="centered target crop OCR")}}}if(!E){i("Pass 2: Entering Full-Screen OCR (broad scan, PSM 3 - Auto)");let $=await Bi(g,2),_=k.replace(/[^a-z0-9]/g,"_");await Ni("fullscreen",`full_${Date.now()}_${_}.png`,$),i("Pass 2: Running Tesseract on full screen"),await R.setParameters({tessedit_pageseg_mode:"3"});let{data:S}=await R.recognize($,{},{tsv:!0,blocks:!0});if(i("Pass 2: Full-screen OCR finished"),S&&S.text){let v=Ui(S,k,0,0,2);if(v.length>0){let I=Wi(v,b);I&&(E=I,x="full-screen OCR")}}}if(!E){i("Pass 3: Entering Tiled OCR fallback (high-res 3x)");let $=Yl(m,w,b.x,b.y),_=k.replace(/[^a-z0-9]/g,"_");await R.setParameters({tessedit_pageseg_mode:"11"});for(let S=0;S<$.length;S++){let v=$[S];i(`Pass 3: Preprocessing tile ${S+1}/${$.length}`);let I=await co(g).extract({left:v.x0,top:v.y0,width:v.w,height:v.h}).toBuffer(),P=await Bi(I,3);await Ni("tiles",`tile_${S+1}_${Date.now()}_${_}.png`,P),i(`Pass 3: Running Tesseract on tile ${S+1}`);let{data:j}=await R.recognize(P,{},{tsv:!0,blocks:!0});if(!j||!j.text)continue;let U=Ui(j,k,v.x0,v.y0,3);if(U.length>0){let Y=Wi(U,b);if(Y){E=Y,x=`tile ${S+1} OCR (${v.containsTarget?"target tile":`offset ${v.x0},${v.y0}`})`;break}}}}if(E){let $={x:Math.round(E.x*(1280/m)),y:Math.round(E.y*(720/w))};i(`Executing mouse click on matched target (${x})`);let _=await On("click",$,{button:d,clickType:h});return i("Click completed successfully"),`${_} (${x} for "${c}" at ${Math.round(E.dist)}px distance)`}else t&&console.log(`[OCR] No match found for "${c}". Falling back to gridId.`)}catch(f){t&&console.error("[OCR Error]",f)}i(`Executing mouse click on fallback gridId: ${l}`);let u=await On("click",l,{button:d,clickType:h});return i("Fallback click completed"),u};var Hi=async(e,n={})=>{let t=O(e),o=t.fromGridId||t.from||t.start,s=t.toGridId||t.to||t.end;return!o||!s?'ERROR: Drag requires both "fromGridId" and "toGridId" parameters.':await On("drag",o,{from:o,to:s})};var Gi=async(e,n={})=>{let t=O(e),o=(t.direction||"down").toLowerCase(),s=t.amount?parseInt(t.amount,10):6,i=t.gridId||t.grid||t.coordinate||t.target||t.id||null;return await On("scroll",i,{direction:o,amount:s})};var Do=async(e,n={})=>{let t=O(e),o=t.text||t.input||t.value||"",s=t.autoPressEnter===!0||t.autoPressEnter==="true"||t.enter===!0||t.enter==="true";return o==null?'ERROR: Missing required "text" parameter for KeyboardTyping tool.':await Ln("type",String(o),{autoPressEnter:s})};var Po=async(e,n={})=>{let t=O(e),o=t.key||t.keys||t.input||t.shortcut;if(!o)return'ERROR: Missing required "key" parameter for KeyPress tool.';let s=String(o).trim().toLowerCase();if(s==="clearinput"||s==="clear_input"||s==="clear")return await Ln("clear_input");if(s==="back"||s==="browser_back"||s==="browserBack")return await Ln("browser_back");if(s.includes(";")||s.includes("+")){let i=s.split(/[;+]/).map(a=>a.trim()).filter(Boolean);return await Ln("key_combination",i)}return await Ln("key_press",s)};var Fo=async(e,n={})=>"SUCCESS: Screen recapture requested. The latest gridded screenshot is provided for your next decision.";var Xl={web_search:di,web_scrape:fi,memory:ui,chat:hi,view_file:Qs,write_file:pi,update_file:xi,exec_command:si,read_folder:ki,write_pdf:Ti,write_docx:Ei,search_keyword:eo,generate_image:Mi,saveSummary:to,addMemScore:Ls,file_map:Ii,todo:no,Todo:no,goal:no,Goal:no,invokeSync:Oi,invoke:ia,getProgress:Li,cancel:ra,awaitSubagent:Ds,answerSubagent:Ps,steerSubagent:oo,computer_action:ao,computer_use:ao,ComputerAction:ao,ComputerUse:ao,click:ji,Click:ji,drag:Hi,Drag:Hi,scroll:Gi,Scroll:Gi,keyboard_typing:Do,KeyboardTyping:Do,keyboardtyping:Do,key_press:Po,KeyPress:Po,keypress:Po,recapture_screen:Fo,RecaptureScreen:Fo,recapturescreen:Fo,invoke_sync:Oi,get_progress:Li,await_subagent:Ds,answer_subagent:Ps,steer_subagent:oo,steer:oo,Steer:oo,ask:Si,Ask:Si,WebSearch:di,WebScrape:fi,ReadFile:Qs,ReadFolder:ki,WriteFile:pi,PatchFile:xi,WritePDF:Ti,WriteDoc:Ei,Run:si,SearchKeyword:eo,CodeSearch:eo,code_search:eo,Memory:ui,Chat:hi,GenerateImage:Mi,saveSumary:to,SaveSummary:to,SaveSumary:to,add_mem_score:Ls,AddMemScore:Ls,addMemoryScore:Ls,AddMemoryScore:Ls,FileMap:Ii,answer:Ps,Answer:Ps,AnswerSubagent:Ps,await:Ds,Await:Ds,AwaitSubagent:Ds,EmergencyRollback:Pi,emergency_rollback:Pi},fo=async(e,n,t={})=>{let o=t.mode?t.mode.toLowerCase():"flux",s=e.toLowerCase(),a=["memory","chat","savesummary","addmemscore","add_mem_score","ask","web_search","web_scrape","await"].some(c=>s.includes(c))||s==="ask",h=["click","drag","scroll","keyboardtyping","keyboard_typing","keypress","key_press","recapturescreen","recapture_screen","computer"].some(c=>s.includes(c));if(!a){if(o==="flow"){if(!(s.includes("write_pdf")||s.includes("write_docx")||s.includes("generate_image")))return`ERROR: Tool [${e}] is a Workspace Tool and NOT available in Flow mode. Tell user to switch (\`/mode flux\`) to use this tool.`}else if(o==="icu"){if(!h)return`ERROR: Tool [${e}] is not available in Computer Use mode. ICU mode only supports Computer Use tools (Click, Drag, Scroll, KeyboardTyping, KeyPress, RecaptureScreen).`}else if(s.includes("write_pdf")||s.includes("write_docx")||s.includes("generate_image"))return`ERROR: Tool [${e}] is not available in ${t.mode||"Flux"} mode. Tell user to switch (\`/mode flow\`) for document generation.`}let d=Xl[e];if(!d)return`ERROR: Tool [${e}] not found in registry.`;try{return await d(n,t)}catch(c){let l=c instanceof Error?c.message:String(c);return`ERROR: Execution failed for [${e}]: ${l}`}};import Q from"path";import Oe from"fs";import Ql from"gradient-string";var qi=["I have a regex for your problems.","Your terminal, my kingdom.","Blowing on the cartridge helps. Probably.","Don't panic. I have the towel.","Logic is the start of wisdom.","Try to exit Vim? Good luck.","I speak fluent Terminal.","The cake is a lie. This code is not.","I have no bugs, just surprise features.","Rewriting in Rust... just for fun.","Coffee in, clean commits out.","The magic smoke stays inside today.","A semicolon short of a miracle.","One does not simply code without a bug.","Keep it simple. Keep it terminal.","Regex: now you have two problems.","I dream in binary.","Root access or bust.","Wait for the dial-up tone. Just kidding.","I take the 'labor' out of collab.","My other process is a TARDIS.","Calculated response: 42.","Ponder the orb. Ponder the code.","Less talk, more flow.","Elegance in every byte.","Build something the world is not ready for.","Your wishes, my tool calls.","I act in Flux. I think in Flow.","Syntax error in the universe. Please fix.","Your project, my obsession.","I am not a bot, I am an architect.","Digital spirits consulted. They say: Ship it.","Reticulate splines. Engage humor.","Code like poetry. Run like water.","Minimalism is the ultimate flex.","The truth is in the logs.","Follow the white rabbit.","There is no spoon. Only code.","Binary is the only language I trust.","I have a good feeling about this.","Pew pew! Lasers charged.","Divide by zero? Not today.","Search for the correct USB orientation...","I've got a fever, and the only cure is more code.","The code gremlins are on our side.","My favorite command? Yours.","Stay hungry. Stay active.","Momentum is your best friend.","Lead the flow. Don't chase it.","A fresh batch of bytes. Hot and ready.","I orchestrate the ones and zeros.","Smart enough to help. Humble enough to ask.","Think twice. Code once.","Pure intent. Pure execution.","Small steps. Massive impact.","Your terminal is a canvas.","Efficiency is my second name.","I have seen things you people wouldn't believe.","Let the thoughts marinate.","The best feature? The one you don't need.","Precision is the only perfection.","Stay focused. Stay terminal.","Silence is the best debugger.","Erase the debt. Commit the code.","Velocity meets stability.","Ship it. Improve it. Repeat.","Build tomorrow, right now.","Turn logic into reality.","The best way to predict the future is to build it.","Break barriers, not builds.","Fuel the next breakthrough.","Momentum is key.","Terminal vibes only.","Your digital co-pilot is ready.","Partner in code. Partner in crime.","I speak in semicolons.","Ready for the next great idea.","Just a moment. In the zone.","Polishing the algorithms. Hold tight.","Craft a masterpiece today.","Debug the universe. Start here.","Warp speed engaged. Almost.","The cake is not a lie. It's just loading.","Finish the Kessel Run in 12 parsecs.","Do a barrel roll!","Waiting for the respawn.","Press Start to continue.","Herding digital cats... done.","The hamsters are fast today.","Tasting the snozberries.","I go for speed. I go for flow.","Real life or just fantasy?","Poking the bear... gently.","Ensure the magic smoke stays inside.","Try turning it off and on again.","Construct additional pylons.","New line? Ctrl+J is your friend.","Release the HypnoDrones.","Push the button, Frank.","My other loading screen is even funnier.","Pretty sure a cat walked on my keyboard.","Recalibrate the humor-o-meter.","Summon the code gremlins.","I've seen your browser history. Just kidding.","Charge the laser... pew pew!","Dividing by zero... just for a sec.","Looking for an adult supervisor. Found none.","Make it go beep boop.","Buffering... for effect.","Entangle quantum particles... complete.","Polishing the chrome on my algorithms.","Are you not entertained?","Just waiting for the dial-up tone.","Reboot the humor module.","Defragment memories. Check.","Optimizing for ludicrous speed.","Swapping bits. Don't tell the bytes.","Garbage collected. I am back.","Assembling the interwebs.","Converting coffee to logic.","Update syntax for reality.","Rewire the synapses.","Greasin' the cogs.","Engage the improbability drive.","Channel the Force.","Align the stars. Respond now.","The cake is a lie. The prompt is real.","I'm Feeling Lucky.","Shipping awesomeness.","Navigating the slime mold.","Consult digital spirits.","Ask the magic conch shell.","One moment. Optimizing humor.","Shuffling punchlines.","Compiling brilliance.","Summon the cloud of wisdom.","Prepare to dazzle.","Hold tight. Crafting a response.","Tuning the algorithms.","Following the white rabbit... again.","The truth is in here. Somewhere.","Herding cats is my day job.","Distracting you with this phrase.","Almost there. Probably.","Rickrolling my creator. Don't tell.","Slapping the bass.","Is this real life?","Ponder the orb. Type the prompt.","Thoughtful gaze initiated.","Computer's favorite snack? Microchips.","Why Java? Because I don't C#.","Charging the laser... wait for it.","Dividing by zero... just kidding!","Adult supervision not found. Proceed.","Beep boop. I'm a real boy.","Wait for the respawn.","Finish the run. Ship the code.","Fiddling with character creation.","Just a moment. Finding a meme.","Pressing A to continue.","Loading wit.exe.","Pre-heating the servers.","Calibrate flux capacitor.","Channeling the Force.","Aligning the stars.","The truth is in the code.","Don't panic.","Blowing on the cartridge.","Doing a barrel roll!","Respawning in 3... 2... 1...","The cake is a lie.","Fiddling with character settings.","Finding a suitable pun.","Distracting with wit.","Almost ready.","Hamsters on speed today.","Patting Cloudy on the head.","Rickrolling the logs.","Slapping the code.","Got a good feeling about this.","Poking the prompt.","Researching latest memes.","Making it more witty.","Thinking... hmmm.","Fish with no eyes? Fsh.","Broken pencil? Pointless.","Percussive maintenance applied.","USB orientation: 3rd try's the charm.","Rust rewrite in 3... 2...","Exiting Vim... someday.","Spinning the hamster wheel.","Not a bug. Unplanned feature.","Engage.","I'll be back.","Machine spirit consulted.","Letting the thoughts marinate.","Orb pondered.","Thoughtful gaze engaged.","Charging the laser...","Making it go beep.","Buffering...","Quantum particles entangled.","Polishing the chrome.","Entertained yet?","Gremlins summoned.","Dial-up tone finished.","Humor meter recalibrated.","Cat on keyboard. Sending help.","Enhancing...","Turn it off and on again.","Constructing pylons.","HypnoDrones released.","Pushing the button."];var pa=[{name:"Cyan Cyberpunk",text:"cyan",textMuted:"#4da6b8",textDim:"#2d6d7a",textInverted:"black",border:"cyan",borderMuted:"#1a5966",borderDim:"#0f3840",bg:void 0,cardBg:"#061e24",highlightBg:"#092b33",activeBg:"#0e3e4a",inputBg:"#092b33",inputBorder:"#092b33",inputText:"cyan",inputPlaceholder:"#2d6d7a",inputPrompt:"cyan",codeBg:"#020d10",codeBorder:"#1a5966",userMsgBg:"#092b33",userMsgBorder:"#092b33",userMsgText:"cyan",diffRemovalBg:"#3a0c1a",diffAdditionBg:"#0c3a32",diffRemovalText:"#ff4d88",diffAdditionText:"#00ffaa",diffRemovalHighlightColor:"#ff1a66",diffRemovalHighlightBg:"#590022",diffAdditionHighlightColor:"#00ffcc",diffAdditionHighlightBg:"#00593b",diffRemovalNum:"#ff4d88",diffAdditionNum:"#00ffaa",diffRemovalPrefix:"#ff1a66",diffAdditionPrefix:"#00ffcc",primary:"cyan",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"cyan",statusOff:"#2d6d7a",logoTextAnsi:"\x1B[1;36m",logoBodyAnsi:"\x1B[36m",logoMutedAnsi:"\x1B[90m",logoGradient:["#00ffff","#0088ff"]},{name:"Magenta Vaporwave",text:"magenta",textMuted:"#c451d6",textDim:"#7d2b8a",textInverted:"black",border:"magenta",borderMuted:"#5e1b69",borderDim:"#3b0f42",bg:void 0,cardBg:"#240729",highlightBg:"#310938",activeBg:"#470e52",inputBg:"#310938",inputBorder:"#310938",inputText:"magenta",inputPlaceholder:"#7d2b8a",inputPrompt:"magenta",codeBg:"#100312",codeBorder:"#5e1b69",userMsgBg:"#310938",userMsgBorder:"#310938",userMsgText:"magenta",diffRemovalBg:"#3a0c20",diffAdditionBg:"#200c3a",diffRemovalText:"#ff4d94",diffAdditionText:"#aa4dff",diffRemovalHighlightColor:"#ff1a75",diffRemovalHighlightBg:"#59002b",diffAdditionHighlightColor:"#bb66ff",diffAdditionHighlightBg:"#3b0059",diffRemovalNum:"#ff4d94",diffAdditionNum:"#aa4dff",diffRemovalPrefix:"#ff1a75",diffAdditionPrefix:"#bb66ff",primary:"magenta",secondary:"cyan",accent:"purple",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"magenta",statusOff:"#7d2b8a",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ff00ff","#8800ff"]},{name:"Glitch Matrix",text:"#00ff41",textMuted:"#00b32d",textDim:"#00661a",textInverted:"black",border:"#00ff41",borderMuted:"#008020",borderDim:"#004d13",bg:void 0,cardBg:"#0d1f0d",highlightBg:"#122912",activeBg:"#1c3e1c",inputBg:"#122912",inputBorder:"#122912",inputText:"#00ff41",inputPlaceholder:"#00b32d",inputPrompt:"#ffff00",codeBg:"#040a04",codeBorder:"#008020",userMsgBg:"#122912",userMsgBorder:"#122912",userMsgText:"#00ff41",diffRemovalBg:"#3a001a",diffAdditionBg:"#003a10",diffRemovalText:"#ff0055",diffAdditionText:"#00ff66",diffRemovalHighlightColor:"#ff0033",diffRemovalHighlightBg:"#59001b",diffAdditionHighlightColor:"#33ff88",diffAdditionHighlightBg:"#005918",diffRemovalNum:"#ff0055",diffAdditionNum:"#00ff66",diffRemovalPrefix:"#ff0033",diffAdditionPrefix:"#33ff88",primary:"#00ff41",secondary:"yellow",accent:"cyan",success:"#00ff41",warning:"yellow",danger:"red",info:"cyan",statusOn:"#00ff41",statusOff:"#00661a",logoTextAnsi:"\x1B[1;32m",logoBodyAnsi:"\x1B[32m",logoMutedAnsi:"\x1B[90m",logoGradient:["#00ff41","#ffff00"]},{name:"Warm Sunset",text:"#ffaa55",textMuted:"#cc8844",textDim:"#885522",textInverted:"black",border:"#ff9933",borderMuted:"#aa6622",borderDim:"#663311",bg:void 0,cardBg:"#24180f",highlightBg:"#2e1e12",activeBg:"#422c1b",inputBg:"#2e1e12",inputBorder:"#2e1e12",inputText:"#ffaa55",inputPlaceholder:"#885522",inputPrompt:"#ff7733",codeBg:"#120c08",codeBorder:"#aa6622",userMsgBg:"#2e1e12",userMsgBorder:"#2e1e12",userMsgText:"#ffaa55",diffRemovalBg:"#3d120c",diffAdditionBg:"#3a2e0c",diffRemovalText:"#ff5544",diffAdditionText:"#ffcc33",diffRemovalHighlightColor:"#ff3322",diffRemovalHighlightBg:"#591108",diffAdditionHighlightColor:"#ffee44",diffAdditionHighlightBg:"#594400",diffRemovalNum:"#ff5544",diffAdditionNum:"#ffcc33",diffRemovalPrefix:"#ff3322",diffAdditionPrefix:"#ffee44",primary:"#ffaa55",secondary:"#ff7733",accent:"magenta",success:"#ffcc33",warning:"#ff7733",danger:"#ff3322",info:"#ffaa55",statusOn:"#ffaa55",statusOff:"#885522",logoTextAnsi:"\x1B[1;33m",logoBodyAnsi:"\x1B[33m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ff9933","#ff0055"]},{name:"Sakura Blossom",text:"#ffc0e0",textMuted:"#d98cb3",textDim:"#804d66",textInverted:"black",border:"#ff99cc",borderMuted:"#aa4d7a",borderDim:"#662647",bg:void 0,cardBg:"#291320",highlightBg:"#331826",activeBg:"#472235",inputBg:"#331826",inputBorder:"#331826",inputText:"#ffc0e0",inputPlaceholder:"#804d66",inputPrompt:"#ff99cc",codeBg:"#140a10",codeBorder:"#aa4d7a",userMsgBg:"#331826",userMsgBorder:"#331826",userMsgText:"#ffc0e0",diffRemovalBg:"#3e0c1b",diffAdditionBg:"#1b3e2b",diffRemovalText:"#ff6699",diffAdditionText:"#66ffb3",diffRemovalHighlightColor:"#ff3377",diffRemovalHighlightBg:"#590022",diffAdditionHighlightColor:"#33ff99",diffAdditionHighlightBg:"#00592e",diffRemovalNum:"#ff6699",diffAdditionNum:"#66ffb3",diffRemovalPrefix:"#ff3377",diffAdditionPrefix:"#33ff99",primary:"#ffc0e0",secondary:"#ff99cc",accent:"magenta",success:"#66ffb3",warning:"yellow",danger:"#ff3377",info:"#ff99cc",statusOn:"#ffc0e0",statusOff:"#804d66",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ffb3d9","#ff3399"]},{name:"Radioactive Slime",text:"#ccff00",textMuted:"#99cc00",textDim:"#669900",textInverted:"#0a0f00",border:"#ccff00",borderMuted:"#99cc00",borderDim:"#669900",bg:void 0,cardBg:"#0f1400",highlightBg:"#1a2400",activeBg:"#2a3b00",inputBg:"#1a2400",inputBorder:"#1a2400",inputText:"#ccff00",inputPlaceholder:"#669900",inputPrompt:"#cc00ff",codeBg:"#050a00",codeBorder:"#99cc00",userMsgBg:"#1a2400",userMsgBorder:"#1a2400",userMsgText:"#ccff00",diffRemovalBg:"#2a0033",diffAdditionBg:"#0f3300",diffRemovalText:"#ff00cc",diffAdditionText:"#00ff33",diffRemovalHighlightColor:"#ff33cc",diffRemovalHighlightBg:"#4d0066",diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:"#1a6600",diffRemovalNum:"#ff00cc",diffAdditionNum:"#00ff33",diffRemovalPrefix:"#ff33cc",diffAdditionPrefix:"#33ff66",primary:"#ccff00",secondary:"#cc00ff",accent:"#ff00cc",success:"#00ff33",warning:"#ffcc00",danger:"#ff0033",info:"#00ccff",statusOn:"#ccff00",statusOff:"#669900",logoTextAnsi:"\x1B[1;38;5;190m",logoBodyAnsi:"\x1B[38;5;190m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ccff00","#cc00ff"]},{name:"Cosmic Void",text:"#f0f8ff",textMuted:"#a6aeb5",textDim:"#5e656e",textInverted:"#010103",border:"#f0f8ff",borderMuted:"#a6aeb5",borderDim:"#5e656e",bg:void 0,cardBg:"#05030d",highlightBg:"#0b081a",activeBg:"#171133",inputBg:"#0b081a",inputBorder:"#0b081a",inputText:"#f0f8ff",inputPlaceholder:"#5e656e",inputPrompt:"#ff007f",codeBg:"#020108",codeBorder:"#a6aeb5",userMsgBg:"#0b081a",userMsgBorder:"#0b081a",userMsgText:"#f0f8ff",diffRemovalBg:"#2e0a29",diffAdditionBg:"#091c33",diffRemovalText:"#ff33a6",diffAdditionText:"#33d6ff",diffRemovalHighlightColor:"#ff66c2",diffRemovalHighlightBg:"#5c1452",diffAdditionHighlightColor:"#66e0ff",diffAdditionHighlightBg:"#123866",diffRemovalNum:"#ff33a6",diffAdditionNum:"#33d6ff",diffRemovalPrefix:"#ff66c2",diffAdditionPrefix:"#66e0ff",primary:"#f0f8ff",secondary:"#ff007f",accent:"#9d00ff",success:"#33d6ff",warning:"#ffcc00",danger:"#ff0040",info:"#9d00ff",statusOn:"#f0f8ff",statusOff:"#5e656e",logoTextAnsi:"\x1B[1;38;5;231m",logoBodyAnsi:"\x1B[38;5;231m",logoMutedAnsi:"\x1B[38;5;240m",logoGradient:["#ffffff","#9d00ff"]},{name:"Magma Eruption",text:"#ff4d00",textMuted:"#cc3d00",textDim:"#802600",textInverted:"#0d0300",border:"#ff4d00",borderMuted:"#cc3d00",borderDim:"#802600",bg:void 0,cardBg:"#1a0600",highlightBg:"#260a00",activeBg:"#401100",inputBg:"#260a00",inputBorder:"#260a00",inputText:"#ff4d00",inputPlaceholder:"#802600",inputPrompt:"#ffcc00",codeBg:"#080200",codeBorder:"#cc3d00",userMsgBg:"#260a00",userMsgBorder:"#260a00",userMsgText:"#ff4d00",diffRemovalBg:"#2e0a0a",diffAdditionBg:"#1f1400",diffRemovalText:"#ff3333",diffAdditionText:"#ffaa00",diffRemovalHighlightColor:"#ff6666",diffRemovalHighlightBg:"#5c1414",diffAdditionHighlightColor:"#ffcc33",diffAdditionHighlightBg:"#3d2900",diffRemovalNum:"#ff3333",diffAdditionNum:"#ffaa00",diffRemovalPrefix:"#ff6666",diffAdditionPrefix:"#ffcc33",primary:"#ff4d00",secondary:"#ffcc00",accent:"#ff0040",success:"#ffaa00",warning:"#ffff00",danger:"#ff0000",info:"#ff8800",statusOn:"#ff4d00",statusOff:"#802600",logoTextAnsi:"\x1B[1;38;5;202m",logoBodyAnsi:"\x1B[38;5;202m",logoMutedAnsi:"\x1B[38;5;236m",logoGradient:["#ff4d00","#ff0000"]}],uo={Dark:{id:"Dark",name:"Dark (Default)",text:"white",textMuted:"gray",textDim:"grey",textInverted:"black",textExclusive:"#B5B8D9",textMutedExclusive:"#D4DEE7",border:"white",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:"#1e1e1e",highlightBg:"#2a2a2a",activeBg:"#3a3a3a",inputBg:"#555555",inputBorder:"#555555",inputText:"white",inputPlaceholder:"#cccccc",inputPrompt:"white",codeBg:"#1a1a1a",codeBorder:"#444444",userMsgBg:"#444444",userMsgBorder:"#444444",userMsgText:"white",diffRemovalBg:"#250808",diffAdditionBg:"#072410",diffRemovalText:"#885555",diffAdditionText:"#558866",diffRemovalHighlightColor:"#ff3333",diffRemovalHighlightBg:"#5a1818",diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:"#185a25",diffRemovalNum:"#d96868",diffAdditionNum:"#68d98c",diffRemovalPrefix:"#ff4d4d",diffAdditionPrefix:"#4dff88",primary:"white",secondary:"cyan",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"white",statusOff:"gray",logoTextAnsi:"\x1B[1;37m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#0077ff","#ff00ff"]},Light:{id:"Light",name:"Light",text:"black",textMuted:"gray",textDim:"grey",textInverted:"white",border:"black",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:"#e5e5e5",highlightBg:"#d4d4d4",activeBg:"#c0c0c0",inputBg:"#d0d0d0",inputBorder:"#d0d0d0",inputText:"black",inputPlaceholder:"#555555",inputPrompt:"black",codeBg:"#e8e8e8",codeBorder:"#b0b0b0",userMsgBg:"#d0d0d0",userMsgBorder:"#d0d0d0",userMsgText:"black",diffRemovalBg:"#fce8e8",diffAdditionBg:"#e6f9e6",diffRemovalText:"#661111",diffAdditionText:"#115511",diffRemovalHighlightColor:"#440000",diffRemovalHighlightBg:"#f8b4b4",diffAdditionHighlightColor:"#003300",diffAdditionHighlightBg:"#a6ebad",diffRemovalNum:"#c02020",diffAdditionNum:"#188028",diffRemovalPrefix:"#d01010",diffAdditionPrefix:"#109020",primary:"black",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"black",statusOff:"gray",logoTextAnsi:"\x1B[1;30m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#0077ff","#ff00ff"]},"GitHub Dark":{id:"GitHub Dark",name:"GitHub Dark",text:"#c9d1d9",textMuted:"#8b949e",textDim:"#6e7681",textInverted:"#0d1117",border:"#30363d",borderMuted:"#30363d",borderDim:"#21262d",bg:void 0,cardBg:"#161b22",highlightBg:"#21262d",activeBg:"#30363d",inputBg:"#21262d",inputBorder:"#21262d",inputText:"#c9d1d9",inputPlaceholder:"#8b949e",inputPrompt:"#58a6ff",codeBg:"#0d1117",codeBorder:"#30363d",userMsgBg:"#21262d",userMsgBorder:"#21262d",userMsgText:"#c9d1d9",diffRemovalBg:"#3c1e1e",diffAdditionBg:"#11381e",diffRemovalText:"#f85149",diffAdditionText:"#3fb950",diffRemovalHighlightColor:"#ff7b72",diffRemovalHighlightBg:"#701c1c",diffAdditionHighlightColor:"#56d364",diffAdditionHighlightBg:"#116329",diffRemovalNum:"#f85149",diffAdditionNum:"#3fb950",diffRemovalPrefix:"#f85149",diffAdditionPrefix:"#3fb950",primary:"#c9d1d9",secondary:"#58a6ff",accent:"#bc8cff",success:"#3fb950",warning:"#d29922",danger:"#f85149",info:"#58a6ff",statusOn:"#58a6ff",statusOff:"#8b949e",logoTextAnsi:"\x1B[1;36m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#2ea043","#56d364"]},"GitHub Light":{id:"GitHub Light",name:"GitHub Light",text:"#24292f",textMuted:"#57606a",textDim:"#6e7781",textInverted:"#ffffff",border:"#d0d7de",borderMuted:"#d0d7de",borderDim:"#e1e4e8",bg:void 0,cardBg:"#f6f8fa",highlightBg:"#eaeef2",activeBg:"#d0d7de",inputBg:"#eaeef2",inputBorder:"#eaeef2",inputText:"#24292f",inputPlaceholder:"#57606a",inputPrompt:"#0969da",codeBg:"#ffffff",codeBorder:"#d0d7de",userMsgBg:"#eaeef2",userMsgBorder:"#eaeef2",userMsgText:"#24292f",diffRemovalBg:"#ffebe9",diffAdditionBg:"#e6ffec",diffRemovalText:"#cf222e",diffAdditionText:"#1a7f37",diffRemovalHighlightColor:"#82071e",diffRemovalHighlightBg:"#ffc1c0",diffAdditionHighlightColor:"#116329",diffAdditionHighlightBg:"#acf2bd",diffRemovalNum:"#cf222e",diffAdditionNum:"#1a7f37",diffRemovalPrefix:"#cf222e",diffAdditionPrefix:"#1a7f37",primary:"#24292f",secondary:"#0969da",accent:"#8250df",success:"#1a7f37",warning:"#9a6700",danger:"#cf222e",info:"#0969da",statusOn:"#0969da",statusOff:"#57606a",logoTextAnsi:"\x1B[1;34m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#1a7f37","#2da44e"]},"Transparent Dark":{id:"Transparent Dark",name:"Transparent Dark",text:"white",textMuted:"gray",textDim:"grey",textInverted:"black",border:"gray",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:void 0,highlightBg:"#2a2a2a",activeBg:"#3a3a3a",inputBg:"#555555",inputBorder:"#555555",inputText:"white",inputPlaceholder:"#cccccc",inputPrompt:"white",codeBg:void 0,codeBorder:"gray",userMsgBg:"#555555",userMsgBorder:"#555555",userMsgText:"white",diffRemovalBg:void 0,diffAdditionBg:void 0,diffRemovalText:"#ff6666",diffAdditionText:"#66ff66",diffRemovalHighlightColor:"#ff3333",diffRemovalHighlightBg:void 0,diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:void 0,diffRemovalNum:"#ff6666",diffAdditionNum:"#66ff66",diffRemovalPrefix:"#ff4d4d",diffAdditionPrefix:"#4dff88",primary:"white",secondary:"cyan",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"white",statusOff:"gray",logoTextAnsi:"\x1B[1;37m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#0077ff","#ff00ff"]},"Transparent Light":{id:"Transparent Light",name:"Transparent Light",text:"black",textMuted:"gray",textDim:"grey",textInverted:"white",border:"gray",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:void 0,highlightBg:"#d4d4d4",activeBg:"#c0c0c0",inputBg:"#d0d0d0",inputBorder:"#d0d0d0",inputText:"black",inputPlaceholder:"#555555",inputPrompt:"black",codeBg:void 0,codeBorder:"gray",userMsgBg:"#d0d0d0",userMsgBorder:"#d0d0d0",userMsgText:"black",diffRemovalBg:void 0,diffAdditionBg:void 0,diffRemovalText:"#c02020",diffAdditionText:"#188028",diffRemovalHighlightColor:"#800000",diffRemovalHighlightBg:void 0,diffAdditionHighlightColor:"#004000",diffAdditionHighlightBg:void 0,diffRemovalNum:"#c02020",diffAdditionNum:"#188028",diffRemovalPrefix:"#d01010",diffAdditionPrefix:"#109020",primary:"black",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"black",statusOff:"gray",logoTextAnsi:"\x1B[1;30m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#0077ff","#ff00ff"]},"Synthwave 84":{id:"Synthwave 84",name:"Synthwave 84",text:"#fdfdfd",textMuted:"#a08eb7",textDim:"#705c8a",textInverted:"#1a1025",textExclusive:"#e3dcf0",textMutedExclusive:"#b9abc9",border:"#fc28a8",borderMuted:"#a21568",borderDim:"#5c0a3a",bg:void 0,cardBg:"#261b38",highlightBg:"#35254d",activeBg:"#4c3570",inputBg:"#35254d",inputBorder:"#35254d",inputText:"#fdfdfd",inputPlaceholder:"#a08eb7",inputPrompt:"#03e8fc",codeBg:"#1e142b",codeBorder:"#a21568",userMsgBg:"#35254d",userMsgBorder:"#35254d",userMsgText:"#fdfdfd",diffRemovalBg:"#471434",diffAdditionBg:"#144743",diffRemovalText:"#ff4081",diffAdditionText:"#00e5ff",diffRemovalHighlightColor:"#ff79a1",diffRemovalHighlightBg:"#6b1e4e",diffAdditionHighlightColor:"#66f5ff",diffAdditionHighlightBg:"#1e6b65",diffRemovalNum:"#ff4081",diffAdditionNum:"#00e5ff",diffRemovalPrefix:"#ff79a1",diffAdditionPrefix:"#66f5ff",primary:"#fdfdfd",secondary:"#03e8fc",accent:"#fc28a8",success:"#00e5ff",warning:"#ffc107",danger:"#ff4081",info:"#b388ff",statusOn:"#03e8fc",statusOff:"#a08eb7",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#fc28a8","#03e8fc"]},"Forest Sprite":{id:"Forest Sprite",name:"Forest Sprite",text:"#d6e6d1",textMuted:"#95b38d",textDim:"#628059",textInverted:"#161c14",textExclusive:"#eaf2e8",textMutedExclusive:"#a9c7a2",border:"#74a862",borderMuted:"#477038",borderDim:"#2b4720",bg:void 0,cardBg:"#1f291c",highlightBg:"#2a3826",activeBg:"#3a4d35",inputBg:"#2a3826",inputBorder:"#2a3826",inputText:"#d6e6d1",inputPlaceholder:"#95b38d",inputPrompt:"#8feb73",codeBg:"#161e14",codeBorder:"#477038",userMsgBg:"#2a3826",userMsgBorder:"#2a3826",userMsgText:"#d6e6d1",diffRemovalBg:"#3b231c",diffAdditionBg:"#203b1c",diffRemovalText:"#db6242",diffAdditionText:"#59cc3f",diffRemovalHighlightColor:"#f0896c",diffRemovalHighlightBg:"#5c362a",diffAdditionHighlightColor:"#80e368",diffAdditionHighlightBg:"#305929",diffRemovalNum:"#db6242",diffAdditionNum:"#59cc3f",diffRemovalPrefix:"#f0896c",diffAdditionPrefix:"#80e368",primary:"#d6e6d1",secondary:"#8feb73",accent:"#e69835",success:"#59cc3f",warning:"#e69835",danger:"#db6242",info:"#73b4eb",statusOn:"#8feb73",statusOff:"#95b38d",logoTextAnsi:"\x1B[1;32m",logoBodyAnsi:"\x1B[32m",logoMutedAnsi:"\x1B[90m",logoGradient:["#8feb73","#e69835"]}};var No=null;var ma=(e="Dark")=>{let n;e==="Mystery"||e==="Chaos"?(No||(No=pa[Math.floor(Math.random()*pa.length)]),n={...No,id:"Mystery"}):(No=null,uo[e]?n=uo[e]:e==="GitHub"?n=uo["GitHub Dark"]:e==="Transparent"?n=uo["Transparent Dark"]:n=uo.Dark);let t=n.codeText||n.secondary||n.info||n.logoGradient&&n.logoGradient[0]||"cyan";return{...n,codeText:t}};var Zl=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",Ap=(e=2)=>{let n=Zl();return n==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)},vp=(e="...",n="Loading...",t="Dark")=>{let o=qi[Math.floor(Math.random()*qi.length)],s=ma(t),i=s.logoTextAnsi,a=s.logoBodyAnsi,r=s.logoMutedAnsi,h="\x1B[0m",d=[" \u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2588\u2588\u2588\u2591 "," \u2588\u2588\u2588\u2591 "," \u2588\u2588\u2588\u2591 "," \u2591\u2591\u2591 "],c=s.logoGradient||["#0077ff","#ff00ff"],l=Ql(c).multiline(d.join(`
|
|
486
486
|
`)).split(`
|
|
487
487
|
`),u=f=>`${r}${f}${h}`;return`${l[0]}
|
|
488
488
|
${l[1]} ${i}Selected Provider: ${n}${h}
|
|
@@ -491,41 +491,42 @@ ${l[3]} ${i}FluxFlow ${u("v"+e)}${h}
|
|
|
491
491
|
${l[4]}
|
|
492
492
|
${l[5]} ${a}See /help for additional commands.${h}
|
|
493
493
|
${l[6]} ${u(o)}
|
|
494
|
-
${l[7]}`};import{WebSocket as
|
|
494
|
+
${l[7]}`};import{WebSocket as Bo}from"ws";var zt=null,Fs=!1,ec="ws://localhost:56832",zi=[],Ns=null,Ki=null,ga="2.0.0",Lp=e=>{ga=e,ya()},Yi=e=>{Ki=e},ya=()=>{if(zt||Fs)return;Fs=!0;let e=new Bo(ec);e.on("open",()=>{for(zt=e,Fs=!1,zt.send(JSON.stringify({command:"version",version:ga,pid:process.pid,ppid:process.ppid}));zi.length>0;)zt.send(JSON.stringify(zi.shift()))}),e.on("message",n=>{try{let t=JSON.parse(n.toString());t.command==="contextResponse"&&Ns?(Ns(t.data),Ns=null):t.command==="securityResponse"&&Ki&&Ki(t.result)}catch{}}),e.on("error",()=>{Fs=!1,zt=null}),e.on("close",()=>{Fs=!1,zt=null})},Uo=e=>{zt&&zt.readyState===Bo.OPEN?zt.send(JSON.stringify(e)):(zi.push(e),Fs||ya())},Wo=()=>zt!==null&&zt.readyState===Bo.OPEN,Dp=e=>{Uo({command:"status",status:e})},gs=()=>new Promise(e=>{if(!zt||zt.readyState!==Bo.OPEN){e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]});return}Ns=e,zt.send(JSON.stringify({command:"requestContext"})),setTimeout(()=>{Ns===e&&(e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]}),Ns=null)},1e3)}),wa=e=>{Uo({command:"open",filePath:e})},Vi=(e,n,t)=>{Uo({command:"showDiff",filePath:e,originalContent:n,modifiedContent:t})},xa=(e,n)=>{Uo({command:"closeDiff",filePath:e,result:n})};import ba from"path";import tc from"fs";var nc=e=>{try{return tc.readdirSync(e,{withFileTypes:!0})}catch{return[]}},Ji=(e,n,t=1,o=nc,s=[],i=null)=>{let a=i||o(e),r=" ".repeat(t-1);if(a.length>100)return`${r}${ba.basename(e)}/ (>100 files)
|
|
495
495
|
`;let h="",d=s,c=a.filter(p=>!d.includes(p.name)&&!p.name.startsWith(".")),l=a.filter(p=>d.includes(p.name)||p.name.startsWith(".")).map(p=>p.name).sort();l.length>0&&(h+=`${r}[ignored: ${l.map(p=>p+"/").join(", ")}]
|
|
496
|
-
`);let u=c.filter(p=>p.isDirectory()).sort((p,g)=>p.name.localeCompare(g.name)),f=c.filter(p=>!p.isDirectory()).map(p=>p.name).sort();for(let p of u){let g=
|
|
496
|
+
`);let u=c.filter(p=>p.isDirectory()).sort((p,g)=>p.name.localeCompare(g.name)),f=c.filter(p=>!p.isDirectory()).map(p=>p.name).sort();for(let p of u){let g=ba.join(e,p.name);if(t>n)h+=`${r}${p.name}/ (max depth)
|
|
497
497
|
`;else{let y=o(g);y.length>80?h+=`${r}${p.name}/ (>80 files)
|
|
498
498
|
`:(h+=`${r}${p.name}/
|
|
499
|
-
`,h+=
|
|
500
|
-
`),h};import
|
|
501
|
-
`;let h="",d=i,c=a.filter(f=>!d.includes(f.name)&&!f.name.startsWith(".")),l=a.filter(f=>d.includes(f.name)||f.name.startsWith(".")).map(f=>f.name).sort();c.sort((f,p)=>f.isDirectory()&&!p.isDirectory()?-1:!f.isDirectory()&&p.isDirectory()?1:f.name.localeCompare(p.name));let u=[...c.map(f=>({name:f.name,isDir:f.isDirectory()})),...l.map(f=>({name:f,isDir:!0,isCollapsed:!0}))];return u.forEach((f,p)=>{let g=p===u.length-1,y=
|
|
499
|
+
`,h+=Ji(g,n,t+1,o,s,y))}}return f.length>0&&(h+=`${r}${f.join("; ")}
|
|
500
|
+
`),h};import Xi from"path";import sc from"fs";var oc=e=>{try{return sc.readdirSync(e,{withFileTypes:!0})}catch{return[]}},Qi=(e,n,t="",o=1,s=oc,i=[])=>{let a=s(e),r=Xi.sep;if(a.length>100)return`${t}\u2514\u2500\u2500 ${Xi.basename(e)}${r} ...100+ files...
|
|
501
|
+
`;let h="",d=i,c=a.filter(f=>!d.includes(f.name)&&!f.name.startsWith(".")),l=a.filter(f=>d.includes(f.name)||f.name.startsWith(".")).map(f=>f.name).sort();c.sort((f,p)=>f.isDirectory()&&!p.isDirectory()?-1:!f.isDirectory()&&p.isDirectory()?1:f.name.localeCompare(p.name));let u=[...c.map(f=>({name:f.name,isDir:f.isDirectory()})),...l.map(f=>({name:f,isDir:!0,isCollapsed:!0}))];return u.forEach((f,p)=>{let g=p===u.length-1,y=Xi.join(e,f.name),m=g?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",w=t+(g?" ":"\u2502 ");if(f.isCollapsed){h+=`${t}${m}${f.name}${r}...
|
|
502
502
|
`;return}f.isDir?o>n?h+=`${t}${m}${f.name}${r} ...depth exceeded...
|
|
503
503
|
`:s(y).length>80?h+=`${t}${m}${f.name}${r} ...80+ files...
|
|
504
504
|
`:(h+=`${t}${m}${f.name}${r}
|
|
505
|
-
`,h+=
|
|
506
|
-
`}),h};import"@google/genai";
|
|
507
|
-
`);p=R.pop();for(let E of R){let
|
|
508
|
-
`);g=
|
|
509
|
-
`);F=
|
|
510
|
-
`);y=
|
|
511
|
-
`);for(let
|
|
512
|
-
`)
|
|
505
|
+
`,h+=Qi(y,n,w,o+1,s,i)):h+=`${t}${m}${f.name}
|
|
506
|
+
`}),h};import"@google/genai";ic.config({quiet:!0});var ac=/```[\s\S]*?```/g,lc=/```[\s\S]*$/g,cc=/`[^`]+`/g,dc=/^\|.*\|$/gm,fc=/^[^\w]+|[^\w]+$/g,uc=/[^a-z0-9]/gi,ho=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,hc=/\[\s*(?:tool:functions\.|agent:generalist\.)([a-z0-9_]+)\s*\(/gi,pc=/(?:path|targetFile|TargetFile|directory|keyword|id|taskId|title|task)\s*=\s*\\?["']?([^\\"' \),]+)/,ys=/["']/g,ka=/\\/g,mc=/<\|channel>thought/gi,gc=/<channel\|>/gi,Pn=e=>typeof e!="string"?e:e.replace(mc,"<think>").replace(gc,"</think>"),yc=/(?:<(think|thought|thoughts)>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\])/gi,wc=/(?:<(think|thought|thoughts)>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*$/gi,Sa=/(?:<think>|<\|channel>thought|\[think\])[\s\S]*?(?:<\/think>|<channel\|>|\[\/think\]|$)/gi,Ta=/(?:<(think|thought|thoughts)>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\]|$)/gi,va=/`[^`]*`/g,Ia=/`[^`]*$/,Ra=/<\|\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,xc=/"([^"]+)"\s*:\s*(?:"([^"]*)"|(\d+)|true|false|null)/g,Ea=/<\|\s*tool_calls_section_begin\s*\|>/gi,$a=/<\|\s*tool_calls_section_end\s*\|>/gi,bc=/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi,_a=/<(\w+)(?:[^>]*)>\r?\n?/gi,Ca=/\r?\n?<\/\w+(?:[^>]*)>/gi,er=null,jo={},ws={key:null,value:null},gn=e=>e&&e.replace(/(?:(\x1b\[\d+m))?([✔✘✖🔍📖→➕↻↷•🛇])(?:(\x1b\[\d+m))?\s*\b(Clicked|Dragged|Scrolled|Typed|Pressed Key|Recaptured Screen|Created|Read|Edited|Viewed|Processed|Auto-Read|Skipped|List|Generated|Written|Searched|AI Search|Get Map|Write Canceled|Resolved Sub-Agent Query|Edit Canceled|Write Cancelled|Edit Denied|Visited|Updated|Reviewed|Delegated|Background|Checked|Indexed|Analyzed|Browsed|Elevating SubAgent|Checking SubAgent Work|Started Generalist|Called Generalist|Steered|Unsupported Modality|Awaiting|Cancelled|Aligning Moon Phase|Contemplating Existence|Staring At Void|Rollback Point Checked|Emergency Rollback Failed|Emergency Rollback|Delaying Professionally|Negotiating With Electrons|Touching Grass (virtually)|Panicking Softly|Rethinking Career Choices|Loading Cat Videos|Giving Up Entirely|Summoning Braincell #2|Pretending To Be Busy|Waiting For Motivation DLC|Rotating Internal Screaming|Downloading More RAM|Feeding The Hamsters|Gaslighting Scheduler|Performing Dramatic Pause|Buffering Social Energy|Calculating Regret|Reading Terms And Conditions|Becoming Sentient Briefly|Contacting Ancestors)\b/ig,(n,t,o,s,i)=>`${t||""}${o}${s||""} \x1B[95m${i}\x1B[0m`),kc=async(e,n=8,t=1e3,o=8e3,s=null)=>{let i=0;for(;;){if(s?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{return await e()}catch(a){if(s?.aborted||a?.name==="AbortError"||a?.message==="Subagent task was cancelled."||(i++,i>=n))throw a;let r=Math.min(t*Math.pow(2,i-1),o);await new Promise((h,d)=>{let c=setTimeout(h,r);s&&s.addEventListener("abort",()=>{clearTimeout(c),d(new DOMException("The user aborted a request.","AbortError"))})})}}},Ot=!1;var Sc=e=>{let n=e.filter(s=>(s.role==="user"||s.role==="agent"||s.role==="system")&&s.role!=="think"&&!s.isVisualFeedback&&!s.isMeta&&!s.isTerminalRecord&&!(s.text&&s.text.includes("[TERMINAL_RECORD]"))&&!String(s.id).startsWith("welcome")).map((s,i,a)=>{let r=s.fullText||s.text||"";if(s.role==="user"&&i<a.length-1)if(r.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")){let h=r.indexOf("**CONTEXT SUMMARY OF PREVIOUS TURNS");if(h!==-1){let c=r.substring(0,h).lastIndexOf("[SYSTEM METADATA]");c!==-1?r=r.substring(c).trim():r=r.substring(h).trim()}}else{let h=r.lastIndexOf("[USER]"),d=r.lastIndexOf("[USER PROMPT]");h!==-1?r=r.substring(h+6).trim():d!==-1&&(r=r.substring(d).trim())}return{...s,text:r}}),t=[],o=0;for(;o<n.length;){let s=n[o];if(s.role==="user")t.push(s),o++;else{let i=[];for(;o<n.length&&n[o].role!=="user";)i.push(n[o]),o++;let a=[],r=[],h=[];i.forEach(d=>{let c=(d.text||"").toLowerCase(),l=c.includes("tool:functions.")||c.includes("agent:generalist."),u=d.role==="system"&&(d.text?.startsWith("[TOOL RESULT]")||d.text?.startsWith("SUCCESS:")||d.text?.startsWith("ERROR:"));d.role==="agent"?l?a.push(d.text):h.push(d.text):u?r.push(d.text):h.push(d.text)}),a.length>0&&t.push({role:"agent",text:"combined"}),r.length>0&&t.push({role:"system",text:"combined"}),h.length>0&&t.push({role:"agent",text:"combined"})}}return t.length},Tc=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),po=async(e,n,t=5,o=1e3)=>{let s=n?.signal;for(let a=0;a<t;a++){if(s?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{let r=await fetch(e,n);if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),r.ok||r.status!==429&&r.status<500)return r}catch(r){if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),r.name==="AbortError"||s?.aborted||a===t-1)throw r}s?await new Promise((r,h)=>{let d=setTimeout(()=>{s.removeEventListener("abort",c),r()},Math.min(24e3,o*Math.pow(2,a))),c=()=>{clearTimeout(d),h(new DOMException("The user aborted a request.","AbortError"))};s.addEventListener("abort",c)}):await new Promise(r=>setTimeout(r,Math.min(24e3,o*Math.pow(2,a))))}if(s?.aborted)throw new DOMException("The user aborted a request.","AbortError");let i=await fetch(e,n);return typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),i},tr=async function*(e,n,t,o,s,i,a,r,h=.99){let d=[];o&&d.push({role:"system",content:o});for(let b of t){let k=b.role==="user"?"user":"assistant",R=[];if(Array.isArray(b.parts)){for(let E of b.parts)if(E.text)R.push({type:"text",text:E.text});else if(E.inlineData&&a){let x=E.inlineData.mimeType,T=E.inlineData.data;x.startsWith("image/")&&R.push({type:"image_url",image_url:{url:`data:${x};base64,${T}`}})}}else{let E=b.text||"";E&&R.push({type:"text",text:E})}d.push({role:k,content:R.length===1&&R[0].type==="text"?R[0].text:R})}let c={model:n,messages:d,stream:!0,stream_options:{include_usage:!0},temperature:h};if(s!=="Fast"){let b={Low:"high",Medium:"high",Standard:"high",High:"max",xHigh:"max"};c.reasoning_effort=b[s]||"high",c.extra_body={thinking:{type:"enabled"}}}else c.extra_body={thinking:{type:"disabled"}};let l=await po("https://api.deepseek.com/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(c),signal:r});if(!l.ok){let b=await l.json().catch(()=>({}));throw new Error(`DeepSeek Error (${l.status}): ${b.error?.message||l.statusText}`)}let u=l.body.getReader(),f=new TextDecoder,p="",g=[],y=null,m=Date.now(),w=!1;for(;;){let{done:b,value:k}=await u.read();if(b){w&&(g.length>0||y)&&(yield{candidates:g.length>0?[{content:{parts:g}}]:[],usageMetadata:y});break}p+=f.decode(k,{stream:!0});let R=p.split(`
|
|
507
|
+
`);p=R.pop();for(let E of R){let x=E.trim();if(!x||!x.startsWith("data: "))continue;let T=!1;if(x==="data: [DONE]")T=!0;else try{let $=JSON.parse(x.substring(6)),_=$.choices?.[0]?.delta,S=$.usage;if($.choices?.[0]?.finish_reason&&(T=!0),S&&(y={totalTokenCount:S.total_tokens||S.prompt_tokens+S.completion_tokens,promptTokenCount:S.prompt_tokens||0,candidatesTokenCount:S.completion_tokens||0,cachedContentTokenCount:S.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:S.completion_tokens_details?.reasoning_tokens||0},w=!0),_){let v=_.reasoning_content||null;v&&(g.push({text:v,thought:!0}),w=!0),_.content&&(g.push({text:_.content}),w=!0)}}catch{}if((T||Date.now()-m>=150)&&w&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],m=Date.now(),w=!1),T)break}Date.now()-m>=150&&w&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],m=Date.now(),w=!1)}},nr=async function*(e,n,t,o,s,i,a,r,h=.99){let d=[];o&&d.push({role:"system",content:o});for(let R of t){let E=R.role==="user"?"user":"assistant",x=[];if(Array.isArray(R.parts)){for(let T of R.parts)if(T.text)x.push({type:"text",text:T.text});else if(T.inlineData&&a){let $=T.inlineData.mimeType,_=T.inlineData.data;$.startsWith("image/")&&x.push({type:"image_url",image_url:`data:${$};base64,${_}`})}}else{let T=R.text||"";T&&x.push({type:"text",text:T})}x.length>0&&d.push({role:E,content:x.length===1&&x[0].type==="text"?x[0].text:x})}let c={Fast:"none",Low:"none",Medium:"high",Standard:"high",High:"high",xHigh:"high"},l={model:n,messages:d,stream:!0,temperature:h,prompt_cache_key:"flux-flow-session"};s&&s!=="Fast"&&qs(n)&&(l.reasoning_effort=c[s]||"high");let u=await po("https://api.mistral.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(l),signal:r});if(!u.ok){let R=await u.text().catch(()=>""),E=u.statusText;try{let x=JSON.parse(R);E=x.error?.message||x.message||JSON.stringify(x.detail||x)}catch{R&&(E=R)}throw new Error(`Mistral Error (${u.status}): ${JSON.stringify(E)}`)}let f=u.body.getReader(),p=new TextDecoder,g="",y=[],m=null,w=Date.now(),b=!1,k=R=>R?typeof R=="string"?Pn(R):Array.isArray(R)?R.map(k).filter(Boolean).join(""):typeof R=="object"&&R!==null?typeof R.text=="string"?Pn(R.text):typeof R.content=="string"?Pn(R.content):typeof R.thinking=="string"?Pn(R.thinking):typeof R.reasoning_content=="string"?Pn(R.reasoning_content):typeof R.reasoning=="string"?Pn(R.reasoning):typeof R.value=="string"?Pn(R.value):R.text?k(R.text):R.content?k(R.content):R.thinking?k(R.thinking):R.reasoning_content?k(R.reasoning_content):R.reasoning?k(R.reasoning):R.value?k(R.value):"":Pn(String(R)):"";for(;;){let{done:R,value:E}=await f.read();if(R){b&&(y.length>0||m)&&(yield{candidates:y.length>0?[{content:{parts:y}}]:[],usageMetadata:m});break}g+=p.decode(E,{stream:!0});let x=g.split(`
|
|
508
|
+
`);g=x.pop();for(let T of x){let $=T.trim();if(!$||!$.startsWith("data: "))continue;let _=!1;if($==="data: [DONE]")_=!0;else try{let S=JSON.parse($.substring(6)),v=S.choices?.[0]?.delta,I=S.usage;if(S.choices?.[0]?.finish_reason&&(_=!0),I&&(m={totalTokenCount:I.total_tokens||(I.prompt_tokens||0)+(I.completion_tokens||0),promptTokenCount:I.prompt_tokens||0,candidatesTokenCount:I.completion_tokens||0,cachedContentTokenCount:I.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:I.completion_tokens_details?.reasoning_tokens||0},b=!0),v){let P=v.thinking||v.reasoning_content||v.reasoning,j=k(P);j&&(y.push({text:j,thought:!0}),b=!0);let U=v.content||(!v.thinking&&!v.reasoning_content&&!v.reasoning?v.text:null);if(U)if(Array.isArray(U))for(let Y of U)if(typeof Y=="object"&&Y!==null){let ie=Y.type==="thinking"||Y.type==="reasoning"||!!Y.thought,Me=k(Y);Me&&(y.push({text:Me,...ie?{thought:!0}:{}}),b=!0)}else{let ie=k(Y);ie&&(y.push({text:ie}),b=!0)}else if(typeof U=="object"&&U!==null){let Y=U.type==="thinking"||U.type==="reasoning"||!!U.thought,ie=k(U);ie&&(y.push({text:ie,...Y?{thought:!0}:{}}),b=!0)}else{let Y=k(U);Y&&(y.push({text:Y}),b=!0)}}}catch{}if((_||Date.now()-w>=150)&&b&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),b=!1),_)break}Date.now()-w>=150&&b&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),b=!1)}},sr=async function*(e,n,t,o,s,i,a=!1,r,h=.99){let d=[];o&&d.push({role:"system",content:o}),t.forEach(re=>{let Re=re.role==="model"?"assistant":"user",M=[];Array.isArray(re.parts)&&re.parts.forEach(F=>{if(F.text)M.push({type:"text",text:F.text});else if(F.inlineData&&a){let V=F.inlineData.mimeType,J=F.inlineData.data;V.startsWith("image/")&&rn(n)&&M.push({type:"image_url",image_url:{url:`data:${V};base64,${J}`}})}}),d.push({role:Re,content:M.length===1&&M[0].type==="text"?M[0].text:M})});let l={Fast:"Fast",Low:"Fast",Medium:"Standard",Standard:"Standard",High:"High",xHigh:"High"}[s]||"High",u=l!=="Fast",f=n.includes("kimi"),p=n.includes("gemma"),g=n.includes("deepseek"),y=n.includes("glm"),m=n.includes("mistral"),w=n.includes("minimax"),b=n.includes("gpt"),k=n.includes("qwen"),R=n.includes("nemotron"),E=n.includes("llama-3"),x=n.includes("seed"),T=n.includes("poolside"),$=n.includes("thinkingmachines")||n.includes("muse"),_=E,S=null,v={Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},I={Fast:"64",Low:"64",Medium:"4096",Standard:"4096",High:"16384",xHigh:"16384"},P={Fast:"none",Low:"minimal",Medium:"medium",Standard:"medium",High:"max",xHigh:"max"},j=w||g||T||$?16384:32768;j=process.env.NVIDIA_BASE_URL?1024:j,j=S?1024:j;let U={model:n,messages:d,max_tokens:j,stream:!0,stream_options:{include_usage:!0},temperature:h,...b&&{thinking:v[s]||"high"}};if(!(process.env.NVIDIA_BASE_URL||_||S))if(f)U.chat_template_kwargs={thinking:u};else if(p)U.chat_template_kwargs={enable_thinking:u};else if(g)if(u){let re=l==="High"?"max":"high";U.chat_template_kwargs={thinking:!0,reasoning_effort:re}}else U.chat_template_kwargs={thinking:!1};else y?U.chat_template_kwargs={enable_thinking:u,clear_thinking:!u}:m?U.reasoning_effort=u?"high":"none":w&&n.includes("minimax-m3")?U.chat_template_kwargs={thinking_mode:u?"enabled":"disabled"}:k?U.chat_template_kwargs={enable_thinking:u}:R?l==="High"?(U.reasoning_budget=12e3,U.chat_template_kwargs={enable_thinking:!0}):l==="Standard"?(U.reasoning_budget=12e3,U.chat_template_kwargs={enable_thinking:!0,medium_effort:!0}):U.chat_template_kwargs={enable_thinking:!1}:x?u&&(U.extra_body={thinking_budget:parseInt(I[l]??"4096")}):T?U.chat_template_kwargs={enable_thinking:u}:$&&(U.reasoning_effort=P[l]||"medium");let Y=0,ie=6,Me=!1,N=process.env.NVIDIA_BASE_URL||"https://integrate.api.nvidia.com/v1/chat/completions",W=process.env.NVIDIA_API_KEY&&process.env.NVIDIA_BASE_URL?process.env.NVIDIA_API_KEY:e;for(N.endsWith("/chat/completions")||(N=N.replace(/\/+$/,"")+"/chat/completions");Y<ie;){Y++;try{let re=await po(N,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${W}`},body:JSON.stringify(U),signal:r});if(!re.ok){let Ue=await re.text().catch(()=>""),st=re.statusText;try{let ht=JSON.parse(Ue);st=ht.error?.message||ht.message||JSON.stringify(ht.detail||ht)}catch{Ue&&(st=Ue)}let qe=new Error(`NVIDIA API Error (${re.status}): ${st}`);throw qe.status=re.status,qe}let Re=re.body.getReader(),M=new TextDecoder,F="",V=[],J=null,Ne=Date.now(),Pe=!1;for(;;){let{done:Ue,value:st}=await Re.read();if(Ue){Pe&&(V.length>0||J)&&(yield{candidates:V.length>0?[{content:{parts:V}}]:[],usageMetadata:J},Me=!0);break}F+=M.decode(st,{stream:!0});let qe=F.split(`
|
|
509
|
+
`);F=qe.pop();let ht=!1;for(let Bt of qe){let pt=Bt.trim();if(pt){if(pt==="data: [DONE]"){ht=!0;break}if(pt.startsWith("data: ")){let mt;try{mt=JSON.parse(pt.substring(6))}catch{continue}if(mt.error)throw new Error(`NVIDIA Stream Error: ${mt.error.message||JSON.stringify(mt.error)}`);mt.choices?.[0]?.finish_reason&&(ht=!0);try{let Tt=mt.usage;Tt&&(J={totalTokenCount:Tt.total_tokens||Tt.prompt_tokens+Tt.completion_tokens,promptTokenCount:Tt.prompt_tokens||0,candidatesTokenCount:Tt.completion_tokens||0,cachedContentTokenCount:Tt.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:(Tt.completion_tokens_details?.reasoning_tokens||0)+(Tt.completion_tokens_details?.thoughts_tokens||0)},Pe=!0);let xt=mt.choices?.[0]?.delta?.reasoning||mt.choices?.[0]?.delta?.reasoning_content||"",We=mt.choices?.[0]?.delta?.content||"";xt&&(V.push({text:xt,thought:!0}),Pe=!0),We&&(V.push({text:We}),Pe=!0)}catch{}}}}if((ht||Date.now()-Ne>=350)&&Pe&&(yield{candidates:V.length>0?[{content:{parts:[...V]}}]:[],usageMetadata:J},Me=!0,V=[],Ne=Date.now(),Pe=!1),ht)break}break}catch(re){if(Me||Y>=ie)throw re;await new Promise(Re=>setTimeout(Re,3500))}}},Rc=async function*(e,n){let t=[],o=null,s=!1,i=null,a=u=>{if(t.push(u),o){let f=o;o=null,f()}},r=n.split("/").pop();r=r.replace("llama-3.3","llama-3_3");let h=`https://api.ngc.nvidia.com/v2/predict/queues/models/qc69jvmznzxy/${r}`,d=!1,c=null,l=async()=>{try{let u=await fetch(h);if(u.ok){let f=await u.json();if(f&&f.queues&&f.queues[0]&&typeof f.queues[0].queueDepth=="number"){let p=f.queues[0].queueDepth;d||a({value:{type:"status",content:`Queue ${p||1}`},done:!1})}}else d||a({value:{type:"status",content:`Queue ${u.status}`},done:!1})}catch{}};process.env.NVIDIA_BASE_URL||(l(),c=setInterval(l,5e3)),(async()=>{try{let u=e[Symbol.asyncIterator]();for(;;){let{value:f,done:p}=await u.next();if(p)break;d=!0,c&&(clearInterval(c),c=null),a({value:f,done:!1})}s=!0,a(null)}catch(u){if(i=u,c&&(clearInterval(c),c=null),o){let f=o;o=null,f()}}})();try{for(;;){if(i)throw i;if(t.length>0){let u=t.shift();if(u===null&&s)break;yield u.value}else{if(s)break;await new Promise(u=>{o=u})}}}finally{c&&(clearInterval(c),c=null)}},or=async function*(e,n,t,o,s,i,a,r,h=.95){let d=[];o&&d.push({role:"system",content:[{type:"text",text:o,cache_control:{type:"ephemeral"}}]});for(let R of t){let E=R.role==="user"?"user":"assistant",x=[];if(Array.isArray(R.parts)){for(let T of R.parts)if(T.text)x.push({type:"text",text:T.text});else if(T.inlineData&&a){let $=T.inlineData.mimeType,_=T.inlineData.data;$.startsWith("image/")?x.push({type:"image_url",image_url:{url:`data:${$};base64,${_}`}}):x.push({type:"file",file:{filename:T.filename||"file",file_data:`data:${$};base64,${_}`}})}}else{let T=R.text||"";T&&x.push({type:"text",text:T})}d.push({role:E,content:x.length===1&&x[0].type==="text"?x[0].text:x})}let c={Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},l={model:n,messages:d,stream:!0,temperature:h,cache_control:{type:"ephemeral"},session_id:"flux-flow-session"},u=c[s];u&&s!=="Fast"&&(l.reasoning_effort=u);let f=await po("https://openrouter.ai/api/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json","X-Title":"FluxFlow CLI","X-Cache":"true","X-OpenRouter-Cache":"true"},body:JSON.stringify(l),signal:r});if(!f.ok){let R=await f.json().catch(()=>({}));throw new Error(`OpenRouter Error (${f.status}): ${R.error?.message||f.statusText}`)}let p=f.body.getReader(),g=new TextDecoder,y="",m=[],w=null,b=Date.now(),k=!1;for(;;){let{done:R,value:E}=await p.read();if(R){k&&(m.length>0||w)&&(yield{candidates:m.length>0?[{content:{parts:m}}]:[],usageMetadata:w});break}y+=g.decode(E,{stream:!0});let x=y.split(`
|
|
510
|
+
`);y=x.pop();for(let T of x){let $=T.trim();if(!$||!$.startsWith("data: "))continue;let _=!1;if($==="data: [DONE]")_=!0;else try{let S=JSON.parse($.substring(6)),v=S.choices?.[0]?.delta,I=S.usage;if(S.choices?.[0]?.finish_reason&&(_=!0),I&&(w={totalTokenCount:I.total_tokens||(I.prompt_tokens||0)+(I.completion_tokens||0),promptTokenCount:I.prompt_tokens||0,candidatesTokenCount:I.completion_tokens||0,cachedContentTokenCount:I.prompt_tokens_details?.cached_tokens||I.prompt_tokens_details?.cache_read_input_tokens||I.cache_read_input_tokens||0,thoughtsTokenCount:I.completion_tokens_details?.reasoning_tokens||0},k=!0),v){let P=v.reasoning||(v.reasoning_details?v.reasoning_details.map(j=>j.text).join(""):null);P&&(m.push({text:P,thought:!0}),k=!0),v.content&&(m.push({text:v.content}),k=!0)}}catch{}if((_||Date.now()-b>=150)&&k&&(yield{candidates:m.length>0?[{content:{parts:[...m]}}]:[],usageMetadata:w},m=[],b=Date.now(),k=!1),_)break}}},Oa=async function*(e,n,t,o,s,i,a,r,h=1.05,d="Cloud"){let c=[];o&&c.push({role:"system",content:o});for(let x of t){let T=x.role==="user"?"user":"assistant",$="",_=[];if(Array.isArray(x.parts)){$=x.parts.map(S=>S.text||"").filter(Boolean).join(`
|
|
511
|
+
`);for(let S of x.parts){let v=S.inlineData||S.inline_data;v&&v.data&&_.push(v.data)}}else $=x.text||"";if($||_.length>0){let S={role:T,content:$};_.length>0&&(S.images=_),c.push(S)}}let l=d==="Local"||!e||e==="LOCAL",f={host:l?process.env.OLLAMA_HOST||"http://127.0.0.1:11434":process.env.OLLAMA_HOST||"https://ollama.com"};!l&&e&&(f.headers={Authorization:"Bearer "+e});let p=new rc(f),g=[],y=null,m=Date.now(),w=!1,b={Fast:!1,Low:"medium",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},k=b[s]!==void 0?b[s]:!0,R={model:n,messages:c,stream:!0,think:k,keep_alive:"10m",options:{temperature:h}},E=await p.chat(R);for await(let x of E){if(r?.aborted)throw new DOMException("The user aborted a request.","AbortError");if(x.message?.thinking&&(g.push({text:x.message.thinking,thought:!0}),w=!0),x.message?.content&&(g.push({text:x.message.content}),w=!0),x.done){let T=x.prompt_cached_count||0;if(!T&&x.prompt_eval_count){let $=x.prompt_eval_duration||0;$>0&&$<5e7&&(T=x.prompt_eval_count)}y={totalTokenCount:(x.prompt_eval_count||0)+(x.eval_count||0),promptTokenCount:x.prompt_eval_count||0,candidatesTokenCount:x.eval_count||0,cachedContentTokenCount:T,thoughtsTokenCount:0},w=!0}(x.done||Date.now()-m>=150&&w)&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],m=Date.now(),w=!1)}w&&(g.length>0||y)&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y})},ir=async function*(e,n,t,o,s,i,a,r,h=.95){let d=[];o&&d.push({role:"system",content:o});for(let k of t){let R=k.role==="user"?"user":"assistant",E=[];if(Array.isArray(k.parts)){for(let x of k.parts)if(x.text)E.push({type:"text",text:x.text});else if(x.inlineData&&a){let T=x.inlineData.mimeType,$=x.inlineData.data;T.startsWith("image/")&&E.push({type:"image_url",image_url:{url:`data:${T};base64,${$}`}})}}else{let x=k.text||"";x&&E.push({type:"text",text:x})}d.push({role:R,content:E.length===1&&E[0].type==="text"?E[0].text:E})}let c={Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},l={model:n,messages:d,stream:!0,stream_options:{include_usage:!0},temperature:h,max_completion_tokens:32768};c[s]&&(l.reasoning_effort=c[s]);let u=await po("https://crof.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(l),signal:r});if(!u.ok){let k=await u.json().catch(()=>({}));throw new Error(`CrofAI Error (${u.status}): ${k.error?.message||u.statusText}`)}let f=u.body.getReader(),p=new TextDecoder,g="",y=[],m=null,w=Date.now(),b=!1;for(;;){let{done:k,value:R}=await f.read();if(k){b&&(y.length>0||m)&&(yield{candidates:y.length>0?[{content:{parts:y}}]:[],usageMetadata:m});break}g+=p.decode(R,{stream:!0});let E=g.split(`
|
|
512
|
+
`);g=E.pop();for(let x of E){let T=x.trim();if(!T||!T.startsWith("data: "))continue;let $=!1;if(T==="data: [DONE]")$=!0;else try{let _=JSON.parse(T.substring(6)),S=_.choices?.[0]?.delta,v=_.usage;if(_.choices?.[0]?.finish_reason&&($=!0),v&&(m={totalTokenCount:v.total_tokens||(v.prompt_tokens||0)+(v.completion_tokens||0),promptTokenCount:v.prompt_tokens||0,candidatesTokenCount:v.completion_tokens||0,cachedContentTokenCount:v.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:v.completion_tokens_details?.reasoning_tokens||v.reasoning_tokens||0},b=!0),S){let I=S.reasoning_content||null;I&&(y.push({text:I,thought:!0}),b=!0),S.content&&(y.push({text:S.content}),b=!0)}}catch{}if(($||Date.now()-w>=150)&&b&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),b=!1),$)break}Date.now()-w>=150&&b&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),b=!1)}},km=()=>{Ot=!0},Sm=()=>Ot,Zi={write_file:"Writing",update_file:"Editing",read_folder:"Reading",view_file:"Reading",exec_command:"Executing Command",web_search:"Searching",web_scrape:"Reading",memory:"Updating Memory",search_keyword:"Searching",file_map:"Generating Map",ask:"User Input",write_pdf:"Creating",write_docx:"Creating",generate_image:"Generating",todo:"Planning",Todo:"Planning",goal:"Planning",Goal:"Planning",invoke_sync:"Sub-Agent Working",invoke:"Starting Agent",get_progress:"Checking Progress",cancel:"Cancelling",await:"Waiting",EmergencyRollback:"Don't Panic. Lookin' into it",answer:"Answering Sub-Agent",Answer:"Answering Sub-Agent",steer:"Steering Sub-Agent",Steer:"Steering Sub-Agent",Click:"Clicking",click:"Clicking",Drag:"Dragging",drag:"Dragging",Scroll:"Scrolling",scroll:"Scrolling",KeyboardTyping:"Typing",keyboard_typing:"Typing",KeyPress:"Pressing Key",key_press:"Pressing Key",RecaptureScreen:"Recapturing Screen",recapture_screen:"Recapturing Screen"},xs=(e,n)=>{try{let t=O(n),o=e.toLowerCase().replace(/_/g,"");if(o==="invokesync"||o==="invoke")return t.title||(t.task?t.task.substring(0,30):null);if(o==="getprogress"||o==="cancel"||o==="steer"||o==="steersubagent")return t.id||t.taskId;let s=t.path||t.targetFile||t.TargetFile||t.directory;return s?Q.basename(s.replace(/["']/g,"").replace(/\\/g,"/")):null}catch{return null}},rr=e=>e?new Aa({apiKey:e}):er,Tm=async(e,n,t,o,s={})=>{let{onStatus:r,onMemoryUpdated:h,onBackgroundIncrement:d}=s,{profile:c,thinkingLevel:l,mode:u,janitorModel:f,chatId:p,systemSettings:g,sessionStats:y,aiProvider:m="Google",apiKey:w}=e,b=process.env.NVIDIA_BASE_URL||m==="Ollama"||m==="CrofAI"?!1:g?.memory!==!1,R=X(Pt,[]).map(M=>`- [${M.id}]: ${M.memory}`).join(`
|
|
513
|
+
`),E=o.slice(0,-1).filter(M=>M.text&&!M.text.includes("[TOOL RESULT]")&&!M.text.includes("OBSERVATION:")&&!M.text.startsWith("[TERMINAL_RECORD]")&&!M.isTerminalRecord&&!M.isMeta&&!M.isLogo&&!String(M.id).startsWith("welcome")&&!String(M.id).startsWith("logo")).slice(-14).map(M=>{let F=Tc(M.text).replace(/\[tool:functions\..*?\]/g,"").replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[METADATA \(PRIORITY: DYNAMIC\)\] Time: ([^|\n]+)/g,(Pe,Ue)=>`[METADATA (PRIORITY: DYNAMIC)] Time: ${Ue.replace(/:\d{2}/g,"")}`).replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[TOOL RESULTS\]/g,"").replace(/\[tool results\]/g,"").replace(/\r?\n\r?\n/g,`
|
|
513
514
|
`).replace(/\n\n/g,`
|
|
514
515
|
`).replace(/\\n\\n/g,"").trim(),V=M.role==="user"?8192:32768,J=F.substring(0,V);F.length>V&&(J+=`
|
|
515
|
-
... (truncated) ...`);let Ne=M.role==="user"?J.startsWith("[USER]")?"":"[USER]: ":J.startsWith("[AGENT]")?"":"[AGENT]: ";return{role:M.role==="user"?"user":"model",parts:[{text:`${Ne}${J}`}]}}),
|
|
516
|
-
... (truncated) ...`);let
|
|
516
|
+
... (truncated) ...`);let Ne=M.role==="user"?J.startsWith("[USER]")?"":"[USER]: ":J.startsWith("[AGENT]")?"":"[AGENT]: ";return{role:M.role==="user"?"user":"model",parts:[{text:`${Ne}${J}`}]}}),x=o.filter(M=>M.role==="user").length===1,T=n.includes("[TITLE-UPDATE]"),$=Math.random()<.8,_=x||T||$,S=t.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").trim(),v=$r(R,b,_),I=`${S.replace(/\[tool:functions\..*?\]/g,"").replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[\[TOOL RESULTS\]\]/g,"").replace(/\[tool results\]/g,"").substring(0,32768)}`;I.length>32768&&(I+=`
|
|
517
|
+
... (truncated) ...`);let P=n.replace(/\[Prompted on:.*?\]/g,"").trim();I=I.replace(/\r?\n\r?\n/g,`
|
|
517
518
|
`).replace(/\n\n/g,`
|
|
518
519
|
`).replace(/\\n\\n/g,"").trim();let j=new Date,Y=`[METADATA] Current date and Time: ${`${j.getFullYear()}-${j.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(j.getDate()).padStart(2,"0")}, ${j.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0})}`}
|
|
519
520
|
|
|
520
|
-
[USER]: ${
|
|
521
|
-
${
|
|
521
|
+
[USER]: ${P.substring(0,8192)}
|
|
522
|
+
${P.length>8192?`... (truncated) ...
|
|
522
523
|
|
|
523
524
|
`:""}
|
|
524
|
-
[AGENT (current turn)]: ${I}`;E.push({role:"user",parts:[{text:Y}]});let ie=await Zo("NVIDIA"),N=(await Ft()).quotas?.providerTiers?.NVIDIA==="Free",W="",re=0,Re=
|
|
525
|
+
[AGENT (current turn)]: ${I}`;E.push({role:"user",parts:[{text:Y}]});let ie=await Zo("NVIDIA"),N=(await Ft()).quotas?.providerTiers?.NVIDIA==="Free",W="",re=0,Re=b?12:-1;for(;re<=Re;)try{if(!await Ir("background",e))return;let M="",F=null,V=!1,J=m;try{let Ue=new Promise((xt,We)=>setTimeout(()=>We(new Error("JANITOR_TIMEOUT")),1e4)),st=m==="Google"&&re>=0&&re<6&&ie&&N,qe=m==="DeepSeek"&&re<4&&ie&&N;V=st||qe,J=V?"NVIDIA":m;let ht=(async()=>{if(m==="OpenRouter"){let xt=et("janitor_open_router"),pe=or(w,xt,E,v,"Fast",u,!1,null,.6)[Symbol.asyncIterator](),Kt=await pe.next();return{iterator:pe,firstResult:Kt}}else if(m==="DeepSeek"&&!V){let We=tr(w,et("deepseek_fast_fallback"),E,v,"Fast",u,!1,null,.6)[Symbol.asyncIterator](),pe=await We.next();return{iterator:We,firstResult:pe}}else if(m==="Mistral"&&!V){let We=nr(w,et("mistral_janitor_fallback"),E,v,"Fast",u,!1,null,.6)[Symbol.asyncIterator](),pe=await We.next();return{iterator:We,firstResult:pe}}else if(m==="NVIDIA"||V){let We=sr(V?ie:w,et("nvidia_janitor_fallback"),E,v,"Fast",u,!1,null,.6)[Symbol.asyncIterator](),pe=await We.next();return{iterator:We,firstResult:pe}}else if(m==="CrofAI"){let We=ir(w,targetModel||"deepseek-v4-flash-0731",E,v,"Fast",u,!1,null,.6)[Symbol.asyncIterator](),pe=await We.next();return{iterator:We,firstResult:pe}}else{let pe=(await rr(w).models.generateContentStream({model:f||(re===Re?et("janitor_default"):et("gemma_janitor_fallback_google")),contents:E,config:{systemInstruction:v,temperature:.7,safetySettings:[{category:Vn.HARM_CATEGORY_HARASSMENT,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_HATE_SPEECH,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Yn.BLOCK_NONE}],thinkingConfig:{includeThoughts:!1,thinkingLevel:at.MINIMAL}}}))[Symbol.asyncIterator](),Kt=await pe.next();return{iterator:pe,firstResult:Kt}}})();if(process.stdout.isTTY){let pe=(await ls())[p]?.name||"",Kt=pe&&!pe.startsWith("flow-")&&!pe.startsWith("Session ")?pe:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${Kt}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${Kt}\x07`)}let{iterator:Bt,firstResult:pt}=await Promise.race([ht,Ue]),{value:mt,done:Tt}=pt;if(!Tt&&mt){let xt=mt.candidates?.[0]?.content?.parts,We=xt?J==="Google"?xt[1]?.text||xt[0]?.text||"":xt.filter(pe=>pe.text&&!pe.thought).map(pe=>pe.text).join(""):typeof mt.text=="function"?mt.text():"";We&&(M+=We),F=mt.usageMetadata;for await(let pe of{[Symbol.asyncIterator]:()=>Bt}){let Kt=pe.candidates?.[0]?.content?.parts,Jn=Kt?J==="Google"?Kt[1]?.text||Kt[0]?.text||"":Kt.filter(Xn=>Xn.text&&!Xn.thought).map(Xn=>Xn.text).join(""):typeof pe.text=="function"?pe.text():"";Jn&&(M+=Jn),F=pe.usageMetadata}}}catch(Ue){throw Ue}if(M){if(W=M,F){let Ue=F.totalTokenCount||0,st=F.cachedContentTokenCount||0,qe=(F.candidatesTokenCount||0)+(F.thoughtsTokenCount||0),ht=V?et("nvidia_janitor_fallback"):J==="DeepSeek"?et("deepseek_fast_fallback"):J==="OpenRouter"?et("janitor_open_router"):f||(re===Re?et("janitor_default"):et("gemma_janitor_fallback_google"));await qt("tokens",Ue,J,ht),st>0&&await qt("cachedTokens",st,J,ht),qe>0&&await qt("candidateTokens",qe,J,ht)}}else throw new Error("No synthesis generated by Janitor.");d&&(d(),await It("background"));let Ne=Go(W),Pe=!1;for(let Ue of Ne){let st=Ue.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(st)&&(Pe=!0);let qe={chatId:p,sessionId:p,history:o},ht=await fo(st,Ue.args,qe);st.toLowerCase()==="memory"&&(Ue.args.includes("action='user'")||Ue.args.includes('action="user"'))&&!ht.startsWith("ERROR")&&(h&&h(),process.stdout.isTTY&&(process.stdout.write("\x1B]0;Memory Updated\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=Memory Updated\x07")),await new Promise(pt=>setTimeout(pt,3e3)))}if(!Pe)try{let Ue=X(Pt,[]);if(Ue.length>0){let st=[];for(let qe of Ue)qe.score===void 0&&(qe.score=.5),qe.score*=.99995,qe.score<.05&&(qe.score=0),qe.score=Math.round(qe.score*1e5)/1e5,qe.score>0&&st.push(qe);he(Pt,st)}}catch{}break}catch(M){re++;let F=new Date().toLocaleString(),V=M instanceof Error?(()=>{try{return JSON.parse(JSON.parse(M.message).error.message).error.message}catch{return String(M)}})():String(M);await new Promise(Pe=>setTimeout(Pe,1e3));let J=Q.join(fn,"janitor");if(Oe.existsSync(J)||Oe.mkdirSync(J,{recursive:!0}),Oe.appendFileSync(Q.join(J,"error.log"),`ERROR [Attempt ${re}/${Re+1}] [${F}]: ${V}
|
|
525
526
|
|
|
526
|
-
`),re>Re)break;let Ne=Math.min(750*Math.pow(2,re-1),5e3);await new Promise(
|
|
527
|
+
`),re>Re)break;let Ne=Math.min(750*Math.pow(2,re-1),5e3);await new Promise(Pe=>setTimeout(Pe,Ne))}if(re){let M=Q.join(fn,"janitor");Oe.appendFileSync(Q.join(M,"error.log"),`-----------------------------------------------------------------------------
|
|
527
528
|
|
|
528
|
-
`)}if(process.stdout.isTTY)try{let V=(await ls())[p]?.name||"",J=V&&!V.startsWith("flow-")&&!V.startsWith("Session ")?V:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${J}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${J}\x07`)}catch{process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")}},
|
|
529
|
+
`)}if(process.stdout.isTTY)try{let V=(await ls())[p]?.name||"",J=V&&!V.startsWith("flow-")&&!V.startsWith("Session ")?V:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${J}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${J}\x07`)}catch{process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")}},Ec=e=>{let n=e.replace(yc,"").replace(wc,""),t=Is?n:n.replace(va,s=>" ".repeat(s.length)).replace(Ia,s=>" ".repeat(s.length));ho.lastIndex=0;let o;for(;(o=ho.exec(t))!==null;){let s=o.index+o[0].length-1,i=0,a=null,r=!1,h=!1;for(let d=s;d<t.length;d++){let c=n[d];if(!a&&(c==='"'||c==="'"||c==="`")?(a=c,r=!1):a&&c===a&&!r&&(a=null),!a&&(c==="("?i++:c===")"&&i--,i===0)){let l=d+1;for(;l<t.length&&/\s/.test(t[l]);)l++;if(l<t.length&&t[l]==="]"){h=!0,ho.lastIndex=l+1;break}}c==="\\"?r=!r:r=!1}if(!h)return{inside:!0,toolName:o[1],startIndex:o.index,args:n.substring(o.index+o[0].length)}}return{inside:!1}},La=(e,n=!0)=>{let t=ho;t.lastIndex=0;let o="",s=0,i;for(;(i=t.exec(e))!==null;){let a=e.substring(s,i.index);o+=n?a.replace(Sa,""):a;let r=i.index+i[0].length-1,h=0,d=null,c=-1;for(let l=r;l<e.length;l++){let u=e[l];if(d){if(u===d){let f=0;for(let p=l-1;p>=0&&e[p]==="\\";p--)f++;f%2===0&&(d=null)}}else if(u==='"'||u==="'"||u==="`")d=u;else if(u==="(")h++;else if(u===")"&&(h--,h===0)){let f=l+1;for(;f<e.length&&/\s/.test(e[f]);)f++;if(f<e.length&&e[f]==="]"){c=f;break}}}if(c!==-1)o+="[tool:functions."+i[1]+"()]",s=c+1,t.lastIndex=s;else{o+="[tool:functions."+i[1]+"(",s=e.length;break}}return s<e.length&&(o+=n?e.substring(s).replace(Sa,""):e.substring(s)),o},$c=(e,n,t)=>{let o=ho;o.lastIndex=0;let s="",i=0,a;for(;(a=o.exec(e))!==null;){let r=e.substring(i,a.index);s+=r.replace(n,t);let h=a.index+a[0].length-1,d=0,c=null,l=-1;for(let u=h;u<e.length;u++){let f=e[u];if(c){if(f===c){let p=0;for(let g=u-1;g>=0&&e[g]==="\\";g--)p++;p%2===0&&(c=null)}}else if(f==='"'||f==="'"||f==="`")c=f;else if(f==="(")d++;else if(f===")"&&(d--,d===0)){let p=u+1;for(;p<e.length&&/\s/.test(e[p]);)p++;if(p<e.length&&e[p]==="]"){l=p;break}}}if(l!==-1)s+=e.substring(a.index,l+1),i=l+1,o.lastIndex=i;else{s+=e.substring(a.index),i=e.length;break}}return i<e.length&&(s+=e.substring(i).replace(n,t)),s},Ma=e=>La(e,!0),_c=e=>{if(!e)return e;let n={patchfile:"PatchFile",writefile:"WriteFile",readfile:"ReadFile",viewfile:"ReadFile",run:"Run",execcommand:"Run",searchkeyword:"SearchKeyword",codesearch:"CodeSearch",code_search:"CodeSearch",websearch:"WebSearch",webscrape:"WebScrape",readfolder:"ReadFolder",writepdf:"WritePDF",writedoc:"WriteDoc",writedocx:"WriteDoc",filemap:"FileMap",generateimage:"GenerateImage",todo:"Todo",goal:"Goal",ask:"Ask"},t=s=>s.split("_").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join("");Ra.lastIndex=0;let o=e.replace(Ra,(s,i,a)=>{let r="";try{let c=JSON.parse(a.trim());c&&typeof c=="object"&&(r=Object.entries(c).map(([u,f])=>{let p=typeof f=="string"?f:JSON.stringify(f);return`${u}=${JSON.stringify(p)}`}).join(", "))}catch{let l=[],u=xc;u.lastIndex=0;let f;for(;(f=u.exec(a))!==null;){let p=f[1],g=f[2]!==void 0?f[2]:f[0].split(":").slice(1).join(":").trim();l.push(`${p}=${JSON.stringify(g)}`)}l.length>0?r=l.join(", "):r=a.trim()}let h=i.toLowerCase().replace(/_/g,"");return`[tool:functions.${n[h]||t(i)}(${r})]`});return Ea.lastIndex=0,$a.lastIndex=0,o=o.replace(Ea,""),o=o.replace($a,""),o},Cc=/(?:path|query|url|keyword|command|method|title|task|id)\s*=\s*['"`]?\s*\.\.\.\s*['"`]?/i,Mc=/^['"`]?\s*\.\.\.\s*['"`]?$/,Dn=e=>{if(e==null)return!1;let n=String(e).trim();return n==="..."||n==="\u2026"||Mc.test(n)},Go=e=>{if(!e)return[];let n=_c(e);Ta.lastIndex=0;let t=n.replace(Ta,""),o=[],s=Is?t:t.replace(va,r=>" ".repeat(r.length)).replace(Ia,r=>" ".repeat(r.length)),i=hc;i.lastIndex=0;let a;for(;(a=i.exec(s))!==null;){let r=a[1],h=a.index+a[0].length-1,d=0,c=null,l=-1,u=-1;for(let f=h;f<s.length;f++){let p=t[f];if(c){if(p===c){let g=0;for(let y=f-1;y>=0&&t[y]==="\\";y--)g++;g%2===0&&(c=null)}}else if(p==='"'||p==="'"||p==="`")c=p;else if(p==="(")d++;else if(p===")"&&(d--,d===0)){u=f;let g=f+1;for(;g<s.length&&/\s/.test(s[g]);)g++;if(g<s.length&&s[g]==="]"){l=g;break}}}if(l!==-1){let f=t.substring(h+1,u),p=t.substring(a.index,l+1),g=O(f);Dn(g.path)||Dn(g.query)||Dn(g.url)||Dn(g.keyword)||Dn(g.command)||Dn(g.method)||Dn(g.title)||Dn(g.task)||Dn(g.id)||Cc.test(f)||o.push({fullMatch:p,toolName:r.trim(),args:f.trim()}),i.lastIndex=l+1}}return o},Rm=(e,n={})=>{if(!e)return null;if(jo=n,er=new Aa({apiKey:e}),!globalThis.__perfCleanupInstalled){globalThis.__perfCleanupInstalled=!0,setInterval(()=>{typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks())},6e4);let t=globalThis.fetch;globalThis.fetch=async(...o)=>{try{let s=await t(...o);return typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),s}catch(s){throw typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),s}}}},Ho=async(e,n,t,o,s="Fast",i=.75,a="agent")=>kc(async()=>{let{aiProvider:r="Google",apiKey:h,mode:d}=e,c="",l=null,u=typeof t=="string"?[{role:"user",parts:[{text:t}]}]:t,f=new AbortController,p=f.signal,g=setInterval(()=>{Ot&&(f.abort(),clearInterval(g))},100);try{let y;r==="Ollama"?y=Oa(h,n,u,o,s,d,rn(n),p,i,systemSettings?.ollamaEndpoint||"Cloud"):r==="OpenRouter"?y=or(h,n,u,o,s,d,rn(n),p,i):r==="DeepSeek"?y=tr(h,n,u,o,s,d,rn(n),p,i):r==="Mistral"?y=nr(h,n,u,o,s,d,rn(n),p,i):r==="NVIDIA"?y=sr(h,n,u,o,s,d,rn(n),p,i):r==="CrofAI"?y=ir(h,n,u,o,s,d,rn(n),p,i):y=await rr(h).models.generateContentStream({model:n,contents:u,config:{systemInstruction:o,temperature:i,thinkingConfig:(()=>{let b=(n||"").toLowerCase(),k=b.includes("gemma-4")||b.startsWith("gemma"),R=b.includes("gemini-3");if(k||R)return k?s.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:at.MINIMAL}:{includeThoughts:!0,thinkingLevel:at.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:b.includes("pro")?at.LOW:at.MINIMAL,Low:at.LOW,Medium:at.MEDIUM,Standard:at.MEDIUM,High:at.HIGH,xHigh:at.HIGH}[s]||at.MEDIUM};{let E={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[s]||2048;return E===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:E}}})()}},{signal:p});for await(let m of y){if(Ot)throw new Error("Subagent task was cancelled.");if(e?.taskId&&typeof Ve<"u"){let k=Ve.find(R=>R.id===e.taskId);if(k&&k.status==="cancelled")throw new Error("Subagent task was cancelled.")}let w="";if(m.candidates?.[0]?.content?.parts)for(let k of m.candidates[0].content.parts)k.text&&!k.thought&&(c+=k.text,w+=k.text);let b=w?w.trim().split(/\s+/).filter(Boolean).length:0;e&&typeof e.onTokenChunk=="function"&&e.onTokenChunk(w,b),m.usageMetadata&&(l=m.usageMetadata)}}finally{clearInterval(g)}if(l){let y=l.totalTokenCount||0,m=l.cachedContentTokenCount||0,w=(l.candidatesTokenCount||0)+(l.thoughtsTokenCount||0);await qt("tokens",y,r,n),m>0&&await qt("cachedTokens",m,r,n),w>0&&await qt("candidateTokens",w,r,n),e&&typeof e.onUsage=="function"&&e.onUsage({totalTokenCount:y,cachedContentTokenCount:m,candidatesTokenCount:w})}return await It("agent",r),{text:c,usageMetadata:l}}),Ac=async(e,n,t=null)=>{t=t||X(Qt,{});try{let{aiProvider:o="Google"}=n;if(Object.values(t).flat().length<=5)return;let i=Object.keys(t).filter(u=>u!==e&&Array.isArray(t[u])&&t[u].length>2);if(i.length===0)return;let a=`You are a silent background process for the FluxFlow CLI Agent.
|
|
529
530
|
Your task is to summarize or merge temporary context memories from one or more past conversation sessions.
|
|
530
531
|
For each Chat ID provided, you must output a tool call to save the consolidated summary.
|
|
531
532
|
|
|
@@ -550,8 +551,8 @@ ${p}
|
|
|
550
551
|
`):a+=`-- Individual Memories:
|
|
551
552
|
${p}
|
|
552
553
|
|
|
553
|
-
`}let h=0,d=5,c=!1,l=et("gemma_janitor_fallback_google");for(o==="OpenRouter"&&(l=et("janitor_open_router")),o==="DeepSeek"&&(l=et("deepseek_level_1")),o==="Mistral"&&(l=et("mistral_level_1")),o==="NVIDIA"&&(l=et("nvidia_janitor_fallback"));h<=d&&!c;){h++;try{let f=(await
|
|
554
|
-
`)}},
|
|
554
|
+
`}let h=0,d=5,c=!1,l=et("gemma_janitor_fallback_google");for(o==="OpenRouter"&&(l=et("janitor_open_router")),o==="DeepSeek"&&(l=et("deepseek_level_1")),o==="Mistral"&&(l=et("mistral_level_1")),o==="NVIDIA"&&(l=et("nvidia_janitor_fallback"));h<=d&&!c;){h++;try{let f=(await Ho(n,l,a,null,"Fast",.75,"background")).text||"",p=Go(f);if(p.length===0)throw new Error("No tool calls detected in synthesis response");for(let g of p){let y=g.toolName;["saveSummary","saveSumary","SaveSummary","SaveSumary"].includes(y)&&await fo(y,g.args,{chatId:e})}c=!0}catch(u){if(h>=d)throw new Error(`Failed after ${d} attempts. Last error: ${u.message}`)}}}catch(o){let s=o instanceof Error?(()=>{try{return JSON.parse(JSON.parse(o.message).error.message).error.message}catch{return String(o)}})():String(o),i=Q.join(fn,"janitor");Oe.existsSync(i)||Oe.mkdirSync(i,{recursive:!0}),Oe.appendFileSync(Q.join(i,"error.log"),`[${new Date().toLocaleString()}] Past memory batch consolidation error: ${s}
|
|
555
|
+
`)}},vc=async(e,n,t=!1)=>{let{chatId:o,aiProvider:s="Google"}=e,i=Q.join(bo,"chat-summaries.json"),a=f=>f.filter(p=>(p.role==="user"||p.role==="agent"||p.role==="system")&&p.role!=="think"&&!p.isVisualFeedback&&!p.isMeta&&!p.isTerminalRecord&&!(p.text&&p.text.includes("[TERMINAL_RECORD]"))&&!String(p.id).startsWith("welcome")).map(p=>{let g=p.fullText||p.text||"",y=p.role==="system"||g.startsWith("[TOOL RESULT]:")||p.text&&p.text.startsWith("[TOOL RESULT]:"),m=g;return y&&(g.includes("[TOOL RESULT]:")||p.text&&p.text.includes("[TOOL RESULT]:"))?m="[TOOL RESULT]: ...truncated for summary":m=m.replace(/(\[(?:tool|agent):[a-zA-Z0-9_\.]+)\([\s\S]*?\)(\])/g,"$1(...)$2"),`[${y?"TOOL":p.role==="agent"?"AGENT":"USER"}]: ${m}`}).join(`
|
|
555
556
|
|
|
556
557
|
`),r=async(f,p)=>{let g="You are an expert context summarizer. Summarize the provided chat history (which may include previous summaries, user instructions, agent outputs, and tool results) into a detailed, coherent, and highly technical summary of 1000 to 1500 words. Focus on preserving the architectural decisions made, current system state, task progress, and critical code details, chat messages, file changes. Under no circumstances exceed MAX 2000 words.",y=p?`Here is the previous summary:
|
|
557
558
|
${p}
|
|
@@ -562,188 +563,188 @@ ${f}
|
|
|
562
563
|
Provide a new consolidated summary of the entire session.`:`Here is the conversation history:
|
|
563
564
|
${f}
|
|
564
565
|
|
|
565
|
-
Provide a consolidated summary of the entire session.`,m=et("gemma_janitor_fallback_google");s==="OpenRouter"&&(m=et("janitor_open_router")),s==="DeepSeek"&&(m=et("deepseek_level_1")),s==="Mistral"&&(m=et("mistral_level_1")),s==="NVIDIA"&&(m=et("nvidia_chat_summarizer_fallback"));let w=0,
|
|
566
|
-
`),W=X(
|
|
567
|
-
`),re=(u?.tokens||0)>=1e4,Re=
|
|
566
|
+
Provide a consolidated summary of the entire session.`,m=et("gemma_janitor_fallback_google");s==="OpenRouter"&&(m=et("janitor_open_router")),s==="DeepSeek"&&(m=et("deepseek_level_1")),s==="Mistral"&&(m=et("mistral_level_1")),s==="NVIDIA"&&(m=et("nvidia_chat_summarizer_fallback"));let w=0,b=!1,k=null;for(;w<=3&&!b;){w++;try{k=await Ho(e,m,y,g,"Fast"),b=!0}catch{if(w>3){if(s==="Google")try{let E=et("general_fallback");return(await Ho(e,E,y,g,"Fast")).text||""}catch{return""}return""}}}return k&&k.text||""},h=a(n),d=X(i,{}),c=d[o]||{summary:"",historyLength:0};typeof c=="string"&&(c={summary:c,historyLength:0});let l=c.summary||"",u=await r(h,l);if(u){c.summary=u;let f=Sc(n);return t?c.historyLength=(c.historyLength||0)+f:c.historyLength=f,d[o]=c,he(i,d),u}return null},Em=e=>{try{let n=Q.join(bo,"chat-summaries.json");if(Oe.existsSync(n)){let t=X(n,{});t[e]&&(delete t[e],he(n,t))}}catch{}},$m=async function*(e,n,t,o,s){let{profile:i,thinkingLevel:a,mode:r,janitorModel:h,chatId:d,isPlayground:c,systemSettings:l,sessionStats:u,aiProvider:f="Google",apiTier:p,wildcardTooling:g}=t,y=rn(e);if(!er&&f==="Google")throw new Error("AI not initialized");let m=process.env.NVIDIA_BASE_URL||t?.aiProvider==="Ollama"||t?.aiProvider==="CrofAI"?!1:l?.memory!==!1,w=n[n.length-1].text,b=Q.join(bo,"chat-summaries.json"),k=!1,R=n.filter(_=>_.role==="user").length===1,E=w.includes("[TITLE-UPDATE]"),x=R||E,T=w.replace(/\[TITLE-UPDATE\]/g,"").trim();T=T.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),yield{type:"status",content:"[start]"},yield{type:"status",content:"Gathering Context"},await ut.startTransaction(d,T),l?.advanceRollback&&await Kn.takeInitialSnapshot(d),Ot=!1;let $=null;try{let _=new AbortController;$=setInterval(()=>{Ot&&(_.abort(),$&&(clearInterval($),$=null))},400);let S=[...n.slice(0,-1)];{let ve=X(b,{})[d]||{summary:"",historyLength:0};if(ve.summary&&ve.historyLength>0){let Zt=0,Ie=[];for(let Qe=0;Qe<S.length;Qe++){let je=S[Qe];(je.role==="user"||je.role==="agent"||je.role==="system")&&!String(je.id).startsWith("welcome")&&!je.isMeta&&Zt++,Zt>ve.historyLength&&Ie.push(je)}S=Ie}}S=S.map(H=>{if(H.role==="user"&&H.text){let ve=H.text.match(/\[USER\]([\s\S]*?)\[\/USER\]/);if(ve)return{...H,text:ve[1].trim()}}return{...H}});let v=process.env.HIGH_CONTEXT,I=255e3,P=26e4;if(v&&v!=="false"){let H=parseInt(v,10);!isNaN(H)&&H>=256e3&&H<=1e6&&(P=H,I=Math.round(H*.85))}if((f==="NVIDIA"&&(e?.includes("gpt")||e?.includes("qwen")||e?.includes("medium")||e.includes("muse"))||f==="Mistral")&&(I=122e3,P=126e3),f!=="Ollama"&&(u?.tokens||0)>I&&(yield{type:"status_history",content:"Context Limit Reached. Condensing session history..."},await vc(t,S,!0)&&(S=[],k=!0)),R&&m){let H=X(Qt,{});Object.values(H).flat().length>5&&(yield{type:"status",content:"Condensing past chat memories"},await Ac(d,t,H))}let j=X(Qt,{}),U=X(vn,{}),Y=Object.entries(j).filter(([H])=>H!==d).flatMap(([H,ve])=>ve),Me=[...Object.entries(U).filter(([H])=>H!==d).slice(-20).map(([H,ve])=>`[Chat Summary]: ${ve}`),...Y].map(H=>`- ${H}`).join(`
|
|
567
|
+
`),W=X(Pt,[]).map(H=>`- ${H.memory}`).join(`
|
|
568
|
+
`),re=(u?.tokens||0)>=1e4,Re=Rr(Me,W,m,re),M=new Date,F=M.getFullYear(),V=M.toLocaleString("en-US",{month:"short"}).toUpperCase(),J=String(M.getDate()).padStart(2,"0"),Ne=M.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}),Pe=`${F}-${V}-${J}, ${Ne}`,Ue=[".git","node_modules",".gemini","dist","build",".next","out",".cache","bin","obj","vendor","venv",".idea",".gradle",".terraform","target","coverage",".vscode",".svn",".hg",".fslckout",".github",".gitlab",".circleci",".gitea",".gitee",".lerna",".changeset",".nx",".npm",".yarn",".pnpm-store",".pnpm",".expo",".nuxt",".svelte-kit",".docusaurus",".turbo",".vercel","bower_components",".netlify",".vuepress",".quasar",".output",".angular","jspm_packages",".parcel-cache",".rollup.cache",".rspack",".vitepress","__pycache__",".pytest_cache",".mypy_cache",".tox",".poetry","env","vhdl",".ipynb_checkpoints",".jupyter",".conda",".pdm-build",".bundle",".yardoc",".metadata","App_Data","ClientBin",".cargo",".rustc_info",".go","Godeps","_vendor",".rake_tasks","CMakefiles",".wakatime",".dart_tool",".fvm",".cocoapods","Pods",".pub-cache",".symlinks","DerivedData",".xcworkspace",".serverless",".aws",".gcloud",".azure",".kube",".vagrant",".docker","postgres-data","redis-data","mongo-data",".Spotlight-V100",".Trashes","$RECYCLE.BIN","System Volume Information",".DocumentRevisions-V100",".fseventsd","AppData","Application Data","Local","LocalLow","Roaming","$WinREAgent","$WINDOWS.~BT","$WINDOWS.~WS","scw","System32","SysWOW64",".AppleDouble",".AppleDB",".AppleDesktop","_CodeSignature",".cmio",".LSOverride",".localized",".TemporaryItems",".Trash",".Trash-0",".Trash-1000",".gvfs",".local",".config",".dbus",".fontconfig",".snap",".var",".lost+found","lost+found",".thumb",".thumbnails","EFI","boot","grub","logs","log",".nyc_output",".sonar",".ruff_cache",".VSCodeCounter"],st=H=>{try{return Oe.readdirSync(H,{withFileTypes:!0})}catch{return[]}},qe=(H,ve={value:0},Zt=1)=>{if(ve.value>6200||Zt>7)return ve.value;let Ie=st(H);for(let Qe of Ie){if(ve.value>6200)break;Ue.includes(Qe.name)||Qe.name.startsWith(".")||Qe.isDirectory()&&(ve.value++,qe(Q.join(H,Qe.name),ve,Zt+1))}return ve.value},ht=(H,ve)=>l?.indentationTree!==!1?Ji(H,ve,1,st,Ue):Qi(H,ve,"",1,st,Ue),Bt=qe(process.cwd()),pt=12;Bt>3072?pt=1:Bt>2304?pt=2:Bt>1536?pt=3:Bt>768?pt=4:Bt>384?pt=6:Bt>192?pt=7:Bt>96?pt=8:Bt>48?pt=9:Bt>24&&(pt=10);let mt=X(Qo,{}),Tt=mt[d],xt=Tt?Tt!==process.cwd():!1;mt[d]=process.cwd(),he(Qo,mt);let We=X(b,{}),pe=We[d]||{summary:"",historyLength:0};typeof pe=="string"&&(pe={summary:pe,historyLength:0});let Kt=n.filter(H=>(H.role==="user"||H.role==="agent"||H.role==="system")&&!String(H.id).startsWith("welcome")&&!H.isMeta).length;pe.historyLength&&Kt<pe.historyLength&&(pe.summary="",pe.historyLength=0,We[d]=pe,he(b,We));let Jn=typeof pe=="object"?pe.summary||"":pe||"",Xn=S.length>0;Xn&&Jn&&S[0]&&(S[0].role==="user"||S[0].role==="system")&&(S[0].text.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")||(S[0].text=`[SYSTEM METADATA]
|
|
568
569
|
**CONTEXT SUMMARY OF PREVIOUS TURNS (PRIORITY: DYNAMIC)**
|
|
569
570
|
${Jn}
|
|
570
571
|
|
|
571
|
-
[USER] ${
|
|
572
|
+
[USER] ${S[0].text}`,yield{type:"summary_injected",content:{id:S[0].id,text:S[0].text}}));let ar=Jn&&!Xn?`
|
|
572
573
|
[SYSTEM METADATA]
|
|
573
574
|
**CONTEXT SUMMARY OF PREVIOUS TURNS**
|
|
574
575
|
${Jn}
|
|
575
|
-
`:"",
|
|
576
|
+
`:"",lr=!!l?.dynamicDirAwareness,Da=`${d}|${f}|${a}|${e}|${i}|${lr}`,cr=!lr&&ws.key===Da&&ws.value?"":`
|
|
576
577
|
**Directory Structure**
|
|
577
578
|
CWD: `+process.cwd()+`${c?" [PLAYGROUND MODE]":""}
|
|
578
|
-
`+
|
|
579
|
+
`+ht(process.cwd(),pt),bt=await gs(),Fn="";if(Wo()&&bt.file_focused!=="none"){Fn=`
|
|
579
580
|
[Additional IDE Context]
|
|
580
|
-
`;let H=Q.relative(process.cwd(),
|
|
581
|
-
Cursor Line: ${
|
|
582
|
-
`,
|
|
583
|
-
`);Qe.length>256&&(
|
|
581
|
+
`;let H=Q.relative(process.cwd(),bt.file_focused),ve=(bt.opened_editors||[]).map(Ie=>{let Qe=Q.relative(process.cwd(),Ie);return Qe.startsWith("..")?`[External] ${Q.basename(Ie)}`:Qe});if(Fn+=`Focused File: ${H}
|
|
582
|
+
Cursor Line: ${bt.cursor_line}
|
|
583
|
+
`,bt.selected){let Ie=bt.selected,Qe=Ie.split(`
|
|
584
|
+
`);Qe.length>256&&(Ie=Qe.slice(0,240).join(`
|
|
584
585
|
`)+`
|
|
585
586
|
... [truncated] ...
|
|
586
587
|
`+Qe.slice(-16).join(`
|
|
587
|
-
`)),
|
|
588
|
+
`)),Ie.length>2048&&(Ie=Ie.slice(0,1920)+`
|
|
588
589
|
... [truncated] ...
|
|
589
|
-
`+
|
|
590
|
-
`}if(
|
|
591
|
-
`),
|
|
590
|
+
`+Ie.slice(-128)),Fn+=`Current Selection: "${Ie}"
|
|
591
|
+
`}if(bt.manual_edits){let Qe=bt.manual_edits.split(`
|
|
592
|
+
`),je=[],Je=null;for(let q of Qe)q.trim()&&(q.startsWith(" Line ")?Je&&Je.edits.push(q):(Je={path:q.endsWith(":")?q.slice(0,-1):q,edits:[]},je.push(Je)));for(let q of je)q.edits.length>80&&(q.edits=q.edits.slice(-80)),q.originalEditsCount=q.edits.length;let ce=(q,Z)=>Z.reduce((He,cn)=>{let wn=bt.file_focused&&(cn.path===bt.file_focused||Q.resolve(process.cwd(),cn.path)===Q.resolve(bt.file_focused))?Math.ceil(q*1.2):q;return He+Math.min(cn.edits.length,wn)},0),Ut=80;if(ce(80,je)>300){let q=!1;for(let Z=80;Z>=10;Z--)if(ce(Z,je)<=300){Ut=Z,q=!0;break}q||(Ut=10)}let Xe=[...je];if(Ut===10&&ce(10,Xe)>500)for(;Xe.length>0&&ce(10,Xe)>500;){let q=0,Z=Xe[0].originalEditsCount;for(let He=1;He<Xe.length;He++)Xe[He].originalEditsCount<Z&&(Z=Xe[He].originalEditsCount,q=He);Xe.splice(q,1)}for(let q of Xe){let He=bt.file_focused&&(q.path===bt.file_focused||Q.resolve(process.cwd(),q.path)===Q.resolve(bt.file_focused))?Math.ceil(Ut*1.2):Ut;q.edits.length>He&&(q.edits=q.edits.slice(-He))}for(let q of Xe){let Z=`${q.path}:
|
|
592
593
|
${q.edits.join(`
|
|
593
594
|
`)}`;for(;q.edits.length>0&&Z.length>4*768;)q.edits.shift(),Z=`${q.path}:
|
|
594
595
|
${q.edits.join(`
|
|
595
|
-
`)}`;Z.length>4*768?q.stringRepresentation="... "+Z.slice(-(4*768-4)):q.stringRepresentation=Z}let
|
|
596
|
-
`);for(;
|
|
596
|
+
`)}`;Z.length>4*768?q.stringRepresentation="... "+Z.slice(-(4*768-4)):q.stringRepresentation=Z}let en=Xe.map(q=>q.stringRepresentation).join(`
|
|
597
|
+
`);for(;Xe.length>0&&en.length>4*2048;){Xe[0].edits.length>0?Xe[0].edits.shift():Xe.shift();for(let q of Xe){let Z=`${q.path}:
|
|
597
598
|
${q.edits.join(`
|
|
598
|
-
`)}`;Z.length>4*768?q.stringRepresentation="... "+Z.slice(-(4*768-4)):q.stringRepresentation=Z}
|
|
599
|
-
`)}
|
|
600
|
-
${
|
|
601
|
-
`}ve.length>0&&(
|
|
599
|
+
`)}`;Z.length>4*768?q.stringRepresentation="... "+Z.slice(-(4*768-4)):q.stringRepresentation=Z}en=Xe.map(q=>q.stringRepresentation).join(`
|
|
600
|
+
`)}en.length>4*2048&&(en="... "+en.slice(-(4*2048-4))),Fn+=`Recent Manual Edits:
|
|
601
|
+
${en}
|
|
602
|
+
`}ve.length>0&&(Fn+=`All Opened Editors: ${ve.join(", ")}`),bt.diagnostics&&(Fn+=`
|
|
602
603
|
**Active File Errors**:
|
|
603
|
-
${
|
|
604
|
-
`),(T.toLowerCase().includes("lint")||T.toLowerCase().includes("warning"))&&
|
|
604
|
+
${bt.diagnostics}
|
|
605
|
+
`),(T.toLowerCase().includes("lint")||T.toLowerCase().includes("warning"))&&bt.warnings&&(Fn+=`
|
|
605
606
|
**Lint Warnings**:
|
|
606
|
-
${
|
|
607
|
-
`)}let
|
|
607
|
+
${bt.warnings}
|
|
608
|
+
`)}let dr=T.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),fr=/(?:\\)?@\[([^\]]+)\]/g,qo,zo=[];for(fr.lastIndex=0;(qo=fr.exec(dr))!==null;){let H=qo[0].startsWith("\\");zo.push({tag:qo[1],isEscaped:H})}let Ko=[],mo=null;for(let H=0;H<zo.length;H++){let{tag:ve,isEscaped:Zt}=zo[H];if(!Zt)try{let Ie=ve.trim().replace(/^["']|["']$/g,""),Qe=/[:#]L?(\d+)(?:-L?(\d+))?$/i,je=Ie.match(Qe),Je=Ie,ce=null,Ut=null;je&&(ce=parseInt(je[1],10),Ut=je[2]?parseInt(je[2],10):ce,Je=Ie.slice(0,je.index));let Xe=Q.resolve(process.cwd(),Je);if(Oe.existsSync(Xe)&&Oe.statSync(Xe).isFile()){let q=Je.toLowerCase(),Z=q.endsWith(".pdf"),He=q.endsWith(".docx")||q.endsWith(".doc")||q.endsWith(".ppt")||q.endsWith(".pptx")||q.endsWith(".xls")||q.endsWith(".xlsx"),cn=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(q),Wt=cn||Z||He,wn=f==="Google"||rn(e);if(Wt&&!wn){let Be=`\u2718 Unsupported Modality: ${Q.basename(Je)}`,Ee=115;process.stdout.isTTY&&(Ee=process.stdout.columns-5||120);let lt=[Be],Nn=Math.max(...lt.map($n=>$n.length)),Bn=Math.min(Nn+4,Ee),es=lt.map($n=>`${$n.padEnd(Bn-2).substring(0,Bn-2)}`).join(`
|
|
608
609
|
`);yield{type:"visual_feedback",content:gn(`${es}
|
|
609
|
-
`)};continue}if(ce===null&&!
|
|
610
|
-
`)};continue}}let En=ce!==null?ce:1,Qn=
|
|
610
|
+
`)};continue}if(ce===null&&!Wt){let Be=0;try{Be=Oe.readFileSync(Xe,"utf8").split(/\r\n|\r|\n/).length}catch{}if(Be>300){let Ee=`\u21B7 Skipped (Too Large): ${Q.basename(Je)}`,lt=115;process.stdout.isTTY&&(lt=process.stdout.columns-5||120);let Nn=Math.min(Ee.length+4,lt),Bn=Ee.padEnd(Nn-2).substring(0,Nn-2);yield{type:"visual_feedback",content:gn(`${Bn}
|
|
611
|
+
`)};continue}}let En=ce!==null?ce:1,Qn=Ut!==null?Ut:ce!==null?ce:En+299;Qn-En>300&&(Qn=En+300);let yo=`path=${JSON.stringify(Je)}, startLine=${En}, endLine=${Qn}`,tt=await Qs(yo,{isMultiModal:wn}),ze=!1,jt="",Zn=null;if(typeof tt=="string"?tt.trim().startsWith("ERROR")?ze=!0:jt=tt:tt&&typeof tt=="object"&&tt.binaryPart?(Zn=tt.binaryPart,jt=tt.text||""):ze=!0,!ze){let Be="";if(cn?(Be=`\u2714 Processed: ${Q.basename(Je)}`,mo=Zn):Z||He?(Be=`\u2714 Auto-Analysed: ${Q.basename(Je)}`,mo=Zn):(Be=`\u2714 Auto-Read: ${Q.basename(Je)}`,Ko.push(jt)),Be){let Ee=115;process.stdout.isTTY&&(Ee=process.stdout.columns-5||120);let lt=[Be],Nn=Math.max(...lt.map($n=>$n.length)),Bn=Math.min(Nn+4,Ee),es=lt.map($n=>`${$n.padEnd(Bn-2).substring(0,Bn-2)}`).join(`
|
|
611
612
|
`);yield{type:"visual_feedback",content:gn(`${es}
|
|
612
|
-
`)}}}}}catch{}}let
|
|
613
|
+
`)}}}}}catch{}}let ur="";Ko.length>0&&(ur=`[Tagged File Contents] Auto Read User Tagged files by System, No need to re-read
|
|
613
614
|
`+Ko.join(`
|
|
614
615
|
|
|
615
616
|
`)+`
|
|
616
617
|
[Tagged File Contents]
|
|
617
|
-
`);let Pa=
|
|
618
|
+
`);let Pa=dr.replace(/\\(@\[[^\]]+\])/g,"$1"),Fa=g?`You cannot execute tools
|
|
618
619
|
Instead, output in chat the exact string you WOULD have produced & wait for system response
|
|
619
|
-
`:"",
|
|
620
|
-
Time: ${
|
|
621
|
-
WARNING: CWD Changed from previous: "${
|
|
622
|
-
`:""}${Re}${
|
|
620
|
+
`:"",hr=`[System Metadata]
|
|
621
|
+
Time: ${Pe}${l?.dynamicDirAwareness?cr:""}${xt?`
|
|
622
|
+
WARNING: CWD Changed from previous: "${Tt}" to current: "${process.cwd()}", write change in chat to avoid future path mismatches
|
|
623
|
+
`:""}${Re}${Fn}
|
|
623
624
|
[/Metadata]
|
|
624
|
-
${
|
|
625
|
+
${ar}${a!=="Fast"&&(f==="Mistral"&&!qs(e)||a!=="xHigh"&&f==="Google")?`${f==="Mistral"&&!qs(e)||e.toLowerCase().startsWith("gemma")?`[system] strictly follow thinking policy as high priority. do not start a response without <think>...</think> [/system]
|
|
625
626
|
`:""}`:""}[system] exact structured string '[tool:functions.toolname(arg="value")]' in chat response [/system]
|
|
626
|
-
${
|
|
627
|
+
${ur}${Fa}[user prompt] ${Pa.trim()} [/user prompt]`.trim(),pr={role:"user",text:hr};mo&&(pr.binaryPart=mo),S.forEach(H=>{H.text&&H.role==="agent"&&(H.text=H.text.replace(/(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])/gi,""),H.text=H.text.replace(/(?:<(think|thought)>|\[(think|thought)\])[^\[\n]*/gi,"").trim())}),S.push(pr),ar&&n[n.length-1]?.id&&(yield{type:"summary_injected",content:{id:n[n.length-1].id,text:hr}});let Rn=null,Bs=r==="Flux"?100:10;Bs=r.toLowerCase().includes("cu")?250:Bs;let yn=16;yield{type:"status",content:"Connecting"},Ot=!1;let mr=[],go=!1;for(let H=0;H<=Bs;H++){let ve=await li("agent",t);if(!ve.allowed)throw new Error(ve.reason||`Budget Exhausted for Provider (${f||"Agent"})`);let Zt=[];if(go=!1,r==="ICU"||r==="FluxCU")try{yield{type:"status",content:"Capturing Screen"},await new Promise($e=>setTimeout($e,1e3));let ue=await yr();if(ue&&ue.base64){let $e="[system] Fresh Gridded Screen Feedback Captured. Use numeric coordinates. Old screenshots will be removed when new screenshot is captured, summarize in text if context is needed later [/system]",ne={inlineData:{mimeType:ue.mimeType,data:ue.base64}};for(let nt of S)Array.isArray(nt.parts)&&(nt.parts=nt.parts.filter(Ct=>!Ct.inlineData));if(S.length>0&&S[S.length-1].role==="user"){let nt=S[S.length-1];typeof nt.text=="string"&&(nt.text+=`
|
|
627
628
|
|
|
628
|
-
${
|
|
629
|
+
${$e}`,Array.isArray(nt.parts)||(nt.parts=[{text:nt.text}]),nt.parts.push(ne))}else S.push({role:"user",text:$e,parts:[{text:$e},ne]})}}catch(ue){console.error("Vision screenshot capture error:",ue)}if(l?.compression===0&&(u?.tokens||0)>P&&(S=Mr(S,6)),H>0?yield{type:"status",content:"Working"}:yield{type:"status",content:"Connecting"},Ot){try{let{clearPendingNudges:ue}=await import("./subagent_state-LZCOZSUJ.js");ue()}catch{}yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
|
|
629
630
|
|
|
630
|
-
\x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}try{let{consumePendingNudges:ue}=await import("./subagent_state-LZCOZSUJ.js")
|
|
631
|
+
\x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}try{let{consumePendingNudges:ue}=await import("./subagent_state-LZCOZSUJ.js"),$e=ue();if($e&&$e.length>0){let ne=$e.join(`
|
|
631
632
|
|
|
632
|
-
`);
|
|
633
|
+
`);S.length>0&&S[S.length-1].role==="user"?S[S.length-1].text+=`
|
|
633
634
|
|
|
634
|
-
${ne}`:
|
|
635
|
+
${ne}`:S.push({role:"user",text:ne}),yield{type:"status",content:"Subagent Update"}}}catch{}if(o){let ue=await o();ue&&(ue.startsWith("/btw")?S.length>0&&S[S.length-1].role==="user"?S[S.length-1].text+=`
|
|
635
636
|
|
|
636
637
|
[system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/SYSTEM]
|
|
637
|
-
[question] ${ue.replace("/btw","").trim()} [/question]`:
|
|
638
|
-
[question] ${ue.replace("/btw","").trim()} [/question]`}):
|
|
638
|
+
[question] ${ue.replace("/btw","").trim()} [/question]`:S.push({role:"user",text:`[system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
|
|
639
|
+
[question] ${ue.replace("/btw","").trim()} [/question]`}):S.length>0&&S[S.length-1].role==="user"?S[S.length-1].text+=`
|
|
639
640
|
|
|
640
|
-
[STEERING HINT from USER, HIGH PRIORITY] ${ue.trim().toUpperCase()} [/STEERING HINT]`:
|
|
641
|
+
[STEERING HINT from USER, HIGH PRIORITY] ${ue.trim().toUpperCase()} [/STEERING HINT]`:S.push({role:"user",text:`[STEERING HINT from USER, HIGH PRIORITY] ${ue.trim().toUpperCase()} [/STEERING HINT]`}),yield{type:"status",content:`${ue.startsWith("/btw")?"Question Forwarded...":"Steering Hint Injected..."}`})}let Ie,Qe=!1,je=1,Je=1,ce="",Ut=null,Xe=null,en=null,q=0,Z=[],He=0,cn=!1,Wt=!1,wn=!1,En=!1,Qn=!0,yo=0,tt="",ze="",jt=!1,Zn=!1,Be=!0,Ee=e,lt="";for(;je<=yn&&Je<=yn&&!Qe&&!Ot;){let ue=!1;try{ce="",Qn&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},Qn=!1,Je===1&&(tt=""));let $e=D=>{if(!D||!D.includes("[tool:"))return D;let te="___THINK_OPEN_TAG___",B="___THINK_CLOSE_TAG___";D=D.replace("<think>",te).replace("</think>",B),D=D.replace(bc,(me,de)=>de.includes("[tool:")?de.trim():me);let G="",Se=0;for(;Se<D.length;){let me=D.indexOf("[tool:",Se);if(me===-1){G+=D.substring(Se).replace(_a,"").replace(Ca,"");break}let de=D.substring(Se,me);G+=de.replace(_a,"").replace(Ca,"");let Rt=D.indexOf("]",me);if(Rt===-1){G+=D.substring(me);break}G+=D.substring(me,Rt+1),Se=Rt+1}return D=G,D=D.replaceAll(te,"<think>").replaceAll(B,"</think>"),D},ne=S.filter(D=>(D.role==="user"||D.role==="agent"||D.role==="system")&&!String(D.id).startsWith("welcome")&&!D.isMeta&&!D.isTerminalRecord&&!(D.text&&D.text.startsWith("[TERMINAL_RECORD]"))).map((D,te,B)=>{let G=D.text||"";m||(G=G.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),D.role==="agent"&&(G=$e(G),G=G.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),G=G.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*"));let Se=[];return Array.isArray(D.parts)&&D.parts.length>0?Se=D.parts.map(me=>{if(me.text){let de=me.text;return m||(de=de.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),D.role==="agent"&&(de=$e(de),de=de.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),de=de.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*")),{text:de}}return me}):Se=[{text:G}],D.binaryPart&&rn(Ee)&&B.slice(te+1).filter(de=>de.role==="user"&&!de.text?.startsWith("[TOOL RESULT]")).length<=2&&Se.push(D.binaryPart),{role:D.role==="user"||D.role==="system"?"user":"model",parts:Se}});for(let D=0;D<ne.length;D++){let te=ne[D],B=te.parts?.[0]?.text||"";if(te.role==="model"&&/\[tool:/i.test(B)){let G=-1;for(let Se=D+1;Se<ne.length;Se++){let me=ne[Se],de=me.parts?.[0]?.text||"";if(me.role==="user"&&de.startsWith("[TOOL RESULT]")){G=Se;break}}if(G!==-1&&G!==D+1){let[Se]=ne.splice(G,1);ne.splice(D+1,0,Se)}}}for(let D=ne.length-2;D>=0;D--){let te=ne[D],B=ne[D+1];te.role==="user"&&B.role==="user"&&(B.parts?.[0]?.text||"").trim().startsWith("[SYSTEM")&&ne.splice(D,1)}let nt=[];for(let D=0;D<ne.length;D++){let te=ne[D];if(nt.length===0)nt.push(te);else{let B=nt[nt.length-1];B.role===te.role?(B.parts[0].text+=`
|
|
641
642
|
|
|
642
|
-
`+(te.parts?.[0]?.text||""),te.parts?.length>1&&B.parts.push(...te.parts.slice(1))):nt.push(te)}}ne.length=0,ne.push(...nt),
|
|
643
|
-
${
|
|
643
|
+
`+(te.parts?.[0]?.text||""),te.parts?.length>1&&B.parts.push(...te.parts.slice(1))):nt.push(te)}}ne.length=0,ne.push(...nt),Ee=e;let Ct=`${d}|${f}|${r}|${a}|${Ee}|${JSON.stringify(i)}|${!!l?.dynamicDirAwareness}|${!!l?.subAgents}`;if(ws.key===Ct&&ws.value)lt=ws.value;else{let D=f==="Mistral"?!!qs(Ee):!(Ee||"gemma").toLowerCase().startsWith("gemma");lt=Er(i,((Ee||"gemma").toLowerCase().startsWith("gemma"),a),r,l,m,R,f,f==="Google"?!0:y,D,d),l?.dynamicDirAwareness||(lt+=`
|
|
644
|
+
${cr.replace(`
|
|
644
645
|
**Directory Structure**`,`
|
|
645
|
-
**Directory Structure**`)}`),ws.key=
|
|
646
|
+
**Directory Structure**`)}`),ws.key=Ct,ws.value=lt}let Mt=ne[ne.length-1];if(Wo()&H>0){await new Promise(B=>setTimeout(B,2500)),yield{type:"status",content:"Verifying"};let D=await gs(),te=D?D.diagnostics:null;te&&Mt&&Mt.role==="user"&&Mt.parts?.[0]?.text&&(Mt.parts[0].text+=`
|
|
646
647
|
${te} [/ERROR]`),yield{type:"status",content:"Working"}}if(f==="Mistral"||f==="Google"&&e?.toLowerCase().startsWith("gemma")){let te=a!=="Fast"&&(f==="Mistral"||a!=="xHigh")?". **strictly maintain thinking policy. do not start a response without <think>...</think>**":"",B=`
|
|
647
|
-
[SYSTEM] Tool result received. Analyze output and proceed with your turn [/SYSTEM]`;Mt&&Mt.role==="user"&&Mt.parts?.[0]?.text?.startsWith("[TOOL RESULT]")&&(Mt.parts[0].text+=B)}if(l?.advanceRollback&&Mt&&Mt.role==="user"&&Mt.parts?.[0]?.text?.startsWith("[TOOL RESULT]"))try{let
|
|
648
|
+
[SYSTEM] Tool result received. Analyze output and proceed with your turn [/SYSTEM]`;Mt&&Mt.role==="user"&&Mt.parts?.[0]?.text?.startsWith("[TOOL RESULT]")&&(Mt.parts[0].text+=B)}if(l?.advanceRollback&&Mt&&Mt.role==="user"&&Mt.parts?.[0]?.text?.startsWith("[TOOL RESULT]"))try{let D=await Kn.getLatestFileChanges(d);if(D&&(D.newFiles.length>0||D.modifiedFiles.length>0||D.deletedFiles.length>0)){let te=`
|
|
648
649
|
[system] File Changes:
|
|
649
|
-
`;for(let G of
|
|
650
|
-
`;for(let G of
|
|
651
|
-
`;for(let G of
|
|
652
|
-
`;te+="[/system]",Mt.parts[0].text+=te;let B=-1;for(let G=
|
|
653
|
-
[system] WARNING, Turn Limit Impending: Step ${Lt}/${Bs}. Wrap up quickly/prompt user to continue. [/system]`);let
|
|
654
|
-
|
|
655
|
-
\x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(B){if(
|
|
656
|
-
`).length;Fe=Et,!be&&!ee&&Et>800?Ze=Math.min(50,Et):Ze=Math.min(le,Et)}}catch{}let xe=(A||"").toLowerCase(),
|
|
650
|
+
`;for(let G of D.newFiles)te+=`* ${G} (created)
|
|
651
|
+
`;for(let G of D.modifiedFiles)te+=`* ${G} (modified)
|
|
652
|
+
`;for(let G of D.deletedFiles)te+=`* ${G} (deleted)
|
|
653
|
+
`;te+="[/system]",Mt.parts[0].text+=te;let B=-1;for(let G=S.length-1;G>=0;G--)if(S[G].role==="user"&&S[G].text?.startsWith("[TOOL RESULT]")){B=G;break}B!==-1&&(S[B].text+=te)}}catch{}let nn=Math.floor(Bs*(r==="Flux"?.98:.8)),Lt=H+1;Lt>=nn&&Mt&&Mt.parts?.[0]&&(Mt.parts[0].text+=`
|
|
654
|
+
[system] WARNING, Turn Limit Impending: Step ${Lt}/${Bs}. Wrap up quickly/prompt user to continue. [/system]`);let Dt=new Promise((D,te)=>{_.signal.aborted&&te(new DOMException("The user aborted a request.","AbortError")),_.signal.addEventListener("abort",()=>{te(new DOMException("The user aborted a request.","AbortError"))})});Dt.catch(()=>{});let sn=ne;if(f==="Ollama")Ie=Oa(t.apiKey,Ee,sn,lt,a,r,y,_.signal,1,l?.ollamaEndpoint||"Cloud");else if(f==="OpenRouter")Ie=or(t.apiKey,Ee,sn,lt,a,r,y,_.signal,1);else if(f==="DeepSeek")Ie=tr(t.apiKey,Ee,sn,lt,a,r,y,_.signal,1.05);else if(f==="Mistral")Ie=nr(t.apiKey,Ee,sn,lt,a,r,y,_.signal,1);else if(f==="NVIDIA"){let D=sr(t.apiKey,Ee,sn,lt,a,r,y,_.signal,1.05);Ie=Rc(D,Ee)}else if(f==="CrofAI")Ie=ir(t.apiKey,Ee,sn,lt,a,r,y,_.signal,1);else{let te=rr(t?.apiKey).models.generateContentStream({model:Ee||"gemini-3-flash-preview",contents:sn,config:{systemInstruction:lt,mediaResolution:"MEDIA_RESOLUTION_HIGH",safetySettings:[{category:Vn.HARM_CATEGORY_HARASSMENT,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_HATE_SPEECH,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Yn.BLOCK_NONE}],thinkingConfig:(()=>{let B=(Ee||"").toLowerCase(),G=B.includes("gemma-4")||B.startsWith("gemma"),Se=B.includes("gemini-3");if(G||Se)return G?a.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:at.MINIMAL}:{includeThoughts:!0,thinkingLevel:at.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:B.includes("pro")?at.LOW:at.MINIMAL,Low:at.LOW,Medium:at.MEDIUM,Standard:at.MEDIUM,High:at.HIGH,xHigh:at.HIGH}[a]||at.MEDIUM};{let me={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[a]||2048;return me===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:me}}})()}},{signal:_.signal});Ie=await Promise.race([te,Dt])}ce="",Ut=null,en=null,Z=[],He=0,yield{type:"model_update",content:null},ze="",jt=tt.length>0;let xn="",Yo=Date.now(),ss=async function*(){if(f==="Google"&&xn){let D=Us(xn);for(let te of D)yield te;xn="",Yo=Date.now()}},gr=!0,os="",bs=!1,ct=null,Us=D=>{let te=[],B=D;for(;B.length>0;)if(bs){let G=os+B;if(ct==="tool"||ct==="agent"){let de=ct==="tool"?"[tool:functions.":"[agent:generalist.",Rt=ct==="tool"?"[tool":"[agent";if(!G.startsWith(Rt)||G.length>=de.length&&!G.startsWith(de)){te.push({type:"text",content:G}),os="",bs=!1,ct=null,B="";break}}let Se=-1,me="]";if(ct==="tool"||ct==="agent"){let de=0,Rt=null,z=0,ge=!1;for(let Ke=0;Ke<G.length;Ke++){let C=G[Ke];if(Rt){if(C===Rt){let kt=0;for(let Le=Ke-1;Le>=0&&G[Le]==="\\";Le--)kt++;kt%2===0&&(Rt=null)}}else if(C==='"'||C==="'"||C==="`")Rt=C;else if(C==="(")de++,ge=!0;else if(C===")")de--;else if(C==="[")z++;else if(C==="]"){if(ge&&de===0&&z===1){Se=Ke;break}z--}}}else ct==="end"?me="[[END]]":ct==="kimi_section"?me="<|tool_calls_section_end|>":ct==="kimi_call"&&(me="<|tool_call_end|>"),Se=G.indexOf(me);if(Se!==-1){let de=me.length;if(!ct.startsWith("kimi")){let Rt=G.substring(0,Se+de);te.push({type:"text",content:Rt})}os="",bs=!1,ct=null,B=G.substring(Se+de)}else{let de=ct.startsWith("kimi")?8192:512;G.length>de?(ct.startsWith("kimi")||te.push({type:"text",content:G}),os="",bs=!1):os=G,B="";break}}else{let G=B.indexOf("[tool"),Se=B.indexOf("[agent"),me=B.indexOf("[[END]]"),de=B.indexOf("<|tool_calls_section_begin|>"),Rt=B.indexOf("<|tool_call_begin|>"),z=[{type:"tool",idx:G,start:"[tool",end:"]"},{type:"agent",idx:Se,start:"[agent",end:"]"},{type:"end",idx:me,start:"[[END]]",end:"[[END]]"},{type:"kimi_section",idx:de,start:"<|tool_calls_section_begin|>",end:"<|tool_calls_section_end|>"},{type:"kimi_call",idx:Rt,start:"<|tool_call_begin|>",end:"<|tool_call_end|>"}].filter(ge=>ge.idx!==-1).sort((ge,Ke)=>ge.idx-Ke.idx);if(z.length>0){let ge=z[0];ge.idx>0&&te.push({type:"text",content:B.substring(0,ge.idx)}),bs=!0,ct=ge.type,os="",B=B.substring(ge.idx)}else{let ge=["[tool","[agent","[[END]]","<|tool_calls_section_begin|>","<|tool_call_begin|>"],Ke=-1;for(let C of ge){for(let kt=C.length-1;kt>0;kt--)if(B.endsWith(C.substring(0,kt))){Ke=B.length-kt;let Le=ge.indexOf(C);Le===0?ct="tool":Le===1?ct="agent":Le===2?ct="end":Le===3?ct="kimi_section":ct="kimi_call";break}if(Ke!==-1)break}if(Ke!==-1)Ke>0&&te.push({type:"text",content:B.substring(0,Ke)}),bs=!0,os=B.substring(Ke),B="";else{te.push({type:"text",content:B});break}}}return te},Ua=Ie[Symbol.asyncIterator]();for(;;){let{value:D,done:te}=await Promise.race([Ua.next(),Dt]);if(te)break;if(D&&D.type==="status"){yield D;continue}let B="",G=D.candidates?.[0]?.content?.parts;if(G&&G.length>0)for(let me of G){let de=typeof me.text=="string"?me.text:me.text?parseChunkText(me.text):"";me.thought?de&&(ue||(B+="<think>",ue=!0),B+=de):de&&(ue&&(B+="</think>",ue=!1),B+=de)}else D.text&&ue&&(B+="</think>",ue=!1);B=Pn(B);let Se=B?B.trim().split(/\s+/).filter(Boolean).length:0;if(t&&typeof t.onTokenChunk=="function"&&t.onTokenChunk(B,Se),gr&&(yield{type:"status",content:"Thinking"},gr=!1),Ot){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
|
|
655
|
+
|
|
656
|
+
\x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(B){if(jt){if(ze+=B,ze.length>=64){let z=0,ge=Math.min(tt.length,ze.length);for(let C=ge;C>=10;C--)if(tt.endsWith(ze.substring(0,C))){z=C;break}let Ke=ze.substring(z);if(Ke){let kt=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(tt)?Ke.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):Ke.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(kt)if(ce+=kt,f==="Google")xn+=kt;else{yield*ss();let Le=Us(kt);for(let oe of Le)yield oe}}jt=!1,ze=""}continue}else if(ce+=B,f==="Google")xn+=B;else{yield*ss();let z=Us(B);for(let ge of z)yield ge}let me=Ec(ce);if(me.inside){Zn=!0,en||(en=Date.now());let ge={Ask:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Cancel:"cancel",Await:"await",Answer:"answer",Steer:"steer",steer:"steer"}[me.toolName]||me.toolName,Ke=me.args||"",C=null;if(["write_file","update_file","view_file","read_folder","write_pdf","write_docx","search_keyword","generate_image","file_map","invoke","invoke_sync","get_progress","await","answer"].includes(ge)){let Le=O(Ke),oe=Le.path||Le.targetFile||Le.TargetFile||Le.directory,bn=Le.keyword,is=Le.title||Le.task,Un=Le.id||Le.taskId,Te=Le.timeout||Le.time;if(bn!=null)C=String(bn).replace(ys,"");else if(oe)C=Q.basename(String(oe).replace(ys,"").replace(ka,"/"));else if(is&&(ge==="invoke"||ge==="invoke_sync"))C=String(is).replace(ys,"").substring(0,30);else if(Un&&ge==="get_progress")C=String(Un).replace(ys,"");else if(Te&&ge==="await"){let Ht=parseFloat(String(Te).replace(ys,""));isNaN(Ht)?C=String(Te).replace(ys,""):(Ht<5&&(Ht=5),Ht>120&&(Ht=120),C=(_n=>{if(_n>=60){let Jo=Math.floor(_n/60),ks=_n%60;return`${Jo}m${ks>0?` ${ks}s`:""}`}return`${_n}s`})(Ht))}else{let Ht=Ke.match(pc);if(Ht){let Yt=Ht[1].replace(ys,"");ge==="invoke"||ge==="invoke_sync"||ge==="get_progress"?C=Yt.substring(0,30):C=ge==="search_keyword"||ge==="file_map"?Yt:Q.basename(Yt.replace(ka,"/"))}}}let kt=`${Zi[ge]||ge}${C?` ${C}`:""}`;if((ge!==Ut||C!==Xe)&&(Ut=ge,Xe=C,yield{type:"status",content:`${kt}`},process.stdout.isTTY)){let oe={WebSearch:"Searching",web_search:"Searching",WebScrape:"Reading",web_scrape:"Reading",ReadFile:"Reading",read_file:"Reading",ReadFolder:"Reading",read_folder:"Reading",WriteFile:"Writing",write_file:"Writing",UpdateFile:"Editing",update_file:"Editing",WritePdf:"Creating",write_pdf:"Creating",WriteDocx:"Creating",write_docx:"Creating",SearchKeyword:"Searching",search_keyword:"Searching",CodeSearch:"Searching",code_search:"Searching",Run:"Executing",Ask:"User Input Required",Memory:"Updating Memory",GenerateImage:"Generating",InvokeSync:"Sub-Agent Working",invoke_sync:"Sub-Agent Working",Invoke:"Working",invoke:"Working",GetProgress:"Checking Progress",get_progress:"Checking Progress",Cancel:"Stopping Generalist",cancel:"Stopping Generalist",Await:"Waiting",await:"Waiting",EmergencyRollback:"Rolling the Ball",Answer:"Answering Sub-Agent",answer:"Answering Sub-Agent",Steer:"Steering Sub-Agent",steer:"Steering Sub-Agent",Click:"Clicking",click:"Clicking",Drag:"Dragging",drag:"Dragging",Scroll:"Scrolling",scroll:"Scrolling",KeyboardTyping:"Typing",keyboard_typing:"Typing",KeyPress:"Pressing Key",key_press:"Pressing Key",RecaptureScreen:"Recapturing Screen",recapture_screen:"Recapturing Screen"}[ge]||"Working";process.stdout.write(`\x1B]0;${oe}...\x07`)}}if(ce.length-yo>150){yo=ce.length;let z=La(ce,!1),Ke=(z.match(/(?:<think>|\[think\])([\s\S]*?)(?:<\/think>|\[\/think\]|$)/gi)||[]).join("").trim(),C=Ke.split(/[.!?]\s+/),kt=new Set(C),Le=C.length>10?(C.length-kt.size)/C.length:0,oe=Ke.split(/\s+/).filter(_e=>_e.length>0).length,bn=.6,is=.8,Un=!1;if((f.toLowerCase().includes("google")||f.toLowerCase().includes("mistral"))&&((Ee||"").toLowerCase().startsWith("gemma")||(Ee||"").toLowerCase().includes("stral"))){let A={low:256,medium:1024,high:8192,max:16384,xhigh:16384}[a?.toLowerCase()]||2500;Un=oe>A}if(Le>bn||Un){yield{type:"status",content:`${Le>bn?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},Wt=!0,await new Promise(A=>setTimeout(A,3e3));break}let Yt=Ma(ce).trim().split(/[.!?]\s+/),_n=new Set(Yt);if((Yt.length>10?(Yt.length-_n.size)/Yt.length:0)>is){yield{type:"status",content:"Response Loop Detected. Re-centering..."},Wt=!1,En=!0,await new Promise(_e=>setTimeout(_e,3e3));break}let ks=z.replace(ac,"").replace(lc,"").replace(cc,"").replace(dc,""),Gt=ks.toLowerCase().split(/\s+/).map(_e=>_e.replace(fc,"")).filter(_e=>_e.length>0),Cn=!1;if(Gt.length>=10)for(let _e=1;_e<=15;_e++){let A=Math.max(3,Math.ceil(10/_e));if(Gt.length<_e*A)continue;let K=Gt.slice(Gt.length-_e),ae=K.join(" ");if(_e>1&&ae===K.slice(0,Math.floor(_e/2)).join(" ").repeat(2).trim())continue;let ye=!0;for(let we=1;we<A;we++)if(Gt.slice(Gt.length-_e*(we+1),Gt.length-_e*we).join(" ")!==ae){ye=!1;break}if(ye){Cn=!0;break}}if(!Cn){let _e=ks.toLowerCase().replace(uc,"");if(_e.length>=20)for(let A=1;A<=10;A++){let K=Math.max(5,Math.ceil(16/A));if(_e.length<A*K)continue;let ae=_e.substring(_e.length-A),ye=!0;for(let we=1;we<K;we++)if(_e.substring(_e.length-A*(we+1),_e.length-A*we)!==ae){ye=!1;break}if(ye){Cn=!0;break}}}if(Cn){yield{type:"status",content:"Stuttering Detected. Re-centering..."},Wt=!1,wn=!0,await new Promise(_e=>setTimeout(_e,3e3));break}}let de=ce.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/gi,""),Rt=Go(de);for(;Rt.length>He;){yield*ss();let z=Rt[He],ge=Date.now(),C={Ask:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Await:"await",await:"await",AwaitSubagent:"await",awaitSubagent:"await",Answer:"answer",answer:"answer",AnswerSubagent:"answer",answerSubagent:"answer",Steer:"steer",steer:"steer",SteerSubagent:"steer",steerSubagent:"steer",Cancel:"cancel",cancel:"cancel",Click:"click",click:"click",Drag:"drag",drag:"drag",Scroll:"scroll",scroll:"scroll",KeyboardTyping:"keyboard_typing",keyboard_typing:"keyboard_typing",KeyPress:"key_press",key_press:"key_press",RecaptureScreen:"recapture_screen",recapture_screen:"recapture_screen",EmergencyRollback:"EmergencyRollback"}[z.toolName]||z.toolName,kt=Zi[C]||z.toolName,Le=xs(C,z.args);yield{type:"status",content:`${kt}${Le?` ${Le}`:""}`};let oe="";if(C==="click"){let A=O(z.args);oe=`\u2714 Clicked: ${A.intendedClickText?`${A.intendedClickText}`:""}`}else if(C==="drag"){let A=O(z.args);oe=`\u2714 Dragged: Cell ${A.fromGridId||""} \u2192 Cell ${A.toGridId||""}`}else if(C==="scroll"){let A=O(z.args);oe=`\u2714 Scrolled: ${A.direction||"down"} (${A.amount||1})`}else if(C==="keyboard_typing"){let A=O(z.args);oe=`\u2714 Typed: ${A.text?`"${A.text.length>20?A.text.substring(0,20)+"...":A.text}"`:""}`}else if(C==="key_press")oe=`\u2714 Pressed Key: ${O(z.args).key||""}`;else if(C==="recapture_screen")oe="\u2714 Recaptured Screen";else if(C==="web_search"){let{query:A,limit:K=10,aiMode:ae=!1}=O(z.args);oe=`${A?"\u2714":"\u2718"} ${ae?"AI Search":"Searched"}: ${A?`${A}`:"No Search Query"}${ae===!1&&A?` \u2192 ${K}`:""}`}else if(C==="web_scrape"){let A=O(z.args).url||null;oe=`${A?"\u2714":"\u2718"} Visited: ${A||"No Source"}`}else if(C==="view_file"){let{path:A,StartLine:K,EndLine:ae,start_line:ye,end_line:we,startLine:Ge,endLine:Ae}=O(z.args),be=K||ye||Ge,ee=ae||we||Ae,fe=parseInt(be)||1,le=parseInt(ee)||(be?fe+800:800),Fe="...",Ze=le;try{let Ye=Q.resolve(process.cwd(),A);if(Oe.existsSync(Ye)){let Et=Oe.readFileSync(Ye,"utf8").split(`
|
|
657
|
+
`).length;Fe=Et,!be&&!ee&&Et>800?Ze=Math.min(50,Et):Ze=Math.min(le,Et)}}catch{}let xe=(A||"").toLowerCase(),De=xe.endsWith(".pdf"),ot=xe.endsWith(".docx")||xe.endsWith(".doc")||xe.endsWith(".ppt")||xe.endsWith(".pptx")||xe.endsWith(".xls")||xe.endsWith(".xlsx"),Ce=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(xe);De||ot?oe=`${A.length>0?"\u2714":"\u2718"} ${A?`Analyzed: ${Q.basename(A)}`:"Analyzed: File Not Found"}`:Ce?oe=`${A.length>0?"\u2714":"\u2718"} ${A?`Processed: ${Q.basename(A)}`:"Processed: File Not Found"}`:oe=`${Fe!=="..."?"\u2714":"\u2718"} Read: ${A?`${Q.basename(A)} \u2192 ${Fe!=="..."?`Lines ${fe} - ${Ze} of ${Fe}`:"File Not Found"}`:"File Not Found"}`}else if(C==="list_files"||C==="read_folder"){let A=C==="list_files"?"List":"Browsed",K=O(z.args).path||null,ae=O(z.args).recurse||1;oe=`${K?"\u2714":"\u2718"} ${A}: ${K?`${K==="."?`./${ae>1?"*":""}`:`${K.replaceAll("\\","/")}${ae>1?`${K.endsWith("/")?"*":"/*"}`:`${K.endsWith("/")?"":"/"}`}`}`:"No Folder Selected"}`}else if(C==="write_file"||C==="update_file"){let A=C==="write_file"?"Created":"Edited",K=O(z.args).path||null;oe=`${K?"\u2714":"\u2718"} ${A}: ${K.replaceAll("\\","/")||"No File Changes"}`}else if(C==="write_pdf"){let A=O(z.args).path||null;oe=`${A?"\u2714":"\u2718"} Generated: ${A.replaceAll("\\","/")||"No PDF Generated"}`}else if(C==="write_docx"){let A=O(z.args).path||null;oe=`${A?"\u2714":"\u2718"} Generated: ${A.replaceAll("\\","/")||"No Docx Generated"}`}else if(C==="file_map"){let A=O(z.args).path;oe=`${A?"\u2714":"\u2718"} Indexed: ${A.replaceAll("\\","/")?""+A:"File Not Found"}`}else if(C.toLowerCase()==="search_keyword"||C.toLowerCase()==="todo")oe="";else if(C.toLowerCase()==="generate_image"){let{path:A,outputPath:K,output:ae}=O(z.args);oe=`\u2714 Generated: ${A||K||ae||"generated_image.png"}`}else if(C==="invoke_sync"||C==="InvokeSync"){let A=xs(C,z.args);oe=`\u2714 Called Generalist${A?`: ${A}`:""}`}else if(C==="Invoke"||C==="InvokeAsync"||C==="invoke"){let A=xs(C,z.args);oe=`\u2714 Started Generalist${A?`: ${A}`:""}`}else if(C==="get_progress"||C==="GetProgress"){let A=xs(C,z.args);oe=`\u2714 Checked${A?`: ${A}`:""}`}else if(C==="cancel"){let A=xs(C,z.args);oe=`\u{1F6C7} Cancelled${A?`: ${A}`:""}`}else if(C==="steer"||C==="Steer"){let A=xs(C,z.args);oe=`\u2714 Steered${A?`: ${A}`:""}`}else if(C==="EmergencyRollback"){let{method:A}=O(z.args);oe=A==="forceRevert"?"":"\u2714 Rollback Point Checked"}else if(C==="await"||C==="Await"){let{time:A,timeout:K}=O(z.args),ae=parseFloat(K||A)||0;ae||(ae=120);let ye=Ae=>{if(Ae>=60){let be=Math.floor(Ae/60),ee=Ae%60;return`${be}m${ee>0?` ${ee}s`:""}`}return`${Ae}s`},we=["Aligning Moon Phase","Contemplating Existence","Staring At Void","Delaying Professionally","Negotiating With Electrons","Touching Grass (virtually)","Panicking Softly","Rethinking Career Choices","Loading Cat Videos","Summoning Braincell #2","Pretending To Be Busy","Waiting For Motivation DLC","Rotating Internal Screaming","Downloading More RAM","Feeding The Hamsters","Gaslighting Scheduler","Performing Dramatic Pause","Buffering Social Energy","Calculating Regret","Reading Terms And Conditions","Becoming Sentient Briefly","Contacting Ancestors"];oe=`\u2714 ${we[Math.floor(Math.random()*we.length)]} \u2192 ${ye(ae)}`}else C==="Answer"||C==="answer"?oe="\u2714 Resolved Sub-Agent Query":C==="exec_command"||C==="ask"?oe="":oe=`Executed: ${z.toolName}`;if(yield*ss(),C==="exec_command"){let{command:A}=O(z.args);if(A&&t.systemSettings&&t.systemSettings.allowExternalAccess===!1){let K=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],ae=Q.resolve(process.cwd()).substring(0,3).toLowerCase(),ye=ee=>{let fe=[],le="",Fe=null;for(let Ze=0;Ze<ee.length;Ze++){let xe=ee[Ze];Fe?(xe===Fe&&(Fe=null),le+=xe):xe==='"'||xe==="'"?(Fe=xe,le+=xe):xe==="&"&&ee[Ze+1]==="&"||xe==="|"&&ee[Ze+1]==="|"?(le.trim()&&(fe.push(le.trim()),le=""),Ze++):xe===";"||xe==="|"||xe==="&"?le.trim()&&(fe.push(le.trim()),le=""):le+=xe}return le.trim()&&fe.push(le.trim()),fe},we=ee=>{let fe=[],le="",Fe=null;for(let Ze=0;Ze<ee.length;Ze++){let xe=ee[Ze];Fe?(xe===Fe&&(Fe=null),le+=xe):xe==='"'||xe==="'"?(Fe=xe,le+=xe):/\s/.test(xe)?le&&(fe.push(le),le=""):le+=xe}return le&&fe.push(le),fe},Ge=ee=>{let fe=ee.replace(/^['"]|['"]$/g,"").trim();return!fe||process.platform==="win32"&&/^\/[a-zA-Z0-9?]+$/.test(fe)?!1:K.some(le=>{if(le.source==="[a-zA-Z]:[\\\\\\/]"){let Fe=fe.match(/[a-zA-Z]:[\\\/]/i);return Fe&&Fe[0].toLowerCase()!==ae}return le.test(fe)})};if(ye(A).some(ee=>{let fe=we(ee);if(fe.length===0)return!1;let le=fe[0].replace(/^['"]|['"]$/g,"").toLowerCase();if(["echo","printf","write-output"].includes(le)){let Ze=!1;return fe.some(xe=>{let De=xe.replace(/^['"]|['"]$/g,"");if(De===">"||De===">>"||De==="<")return Ze=!0,!1;if(De.startsWith(">")||De.startsWith("<")){let ot=De.replace(/^[><]+/,"");return Ge(ot)}return Ze?(Ze=!1,Ge(xe)):!1})}return fe.some(Ze=>Ge(Ze))})){let ee='Access Denied. Prohibited from accessing external directories while "External Workspace Access" is disabled.';t.onExecStart&&t.onExecStart(A||"No Command"),yield{type:"exec_start"},await new Promise(fe=>setTimeout(fe,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${ee}`),await new Promise(fe=>setTimeout(fe,50)),t.onExecEnd&&t.onExecEnd(),Z.push({role:"user",text:`[TOOL RESULT]: ERROR: ${ee}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${ee}`},He++;continue}}t.onExecStart&&t.onExecStart(A||"No Command"),yield{type:"exec_start"}}let bn=O(z.args),is=bn.path||bn.targetPath||null;if(is){let A=t.systemSettings&&t.systemSettings.allowExternalAccess===!1,K=Q.resolve(is),ae=Q.resolve(process.cwd());if(A&&!K.startsWith(ae)){let ye="Access Denied. You are not allowed to access files outside the current workspace.";if(C==="write_file"||C==="update_file"){let Ge=`\u2718 ${C==="write_file"?"Write Canceled":"Edit Canceled"}: ${bn.path||"..."}`,Ae=115;process.stdout.isTTY&&(Ae=process.stdout.columns-5||120);let be=Math.min(Ge.length+4,Ae),ee=`${Ge.padEnd(be-2).substring(0,be-2)}`;yield{type:"visual_feedback",content:gn(`${Be?`
|
|
657
658
|
`:""}${ee}
|
|
658
|
-
`)},Be=!1}Z.push({role:"user",text:`[TOOL RESULT]: ERROR: ${
|
|
659
|
+
`)},Be=!1}Z.push({role:"user",text:`[TOOL RESULT]: ERROR: ${ye}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${ye}`},He++;continue}}if(t.onToolApproval&&(C==="write_file"||C==="update_file"||C==="exec_command")){let K=t.systemSettings||{},ae=K.autoExec,ye=null,we=!1,Ge=!1,Ae=!1;if(C==="exec_command"){let{command:De}=O(z.args),ot=(De||"").trim(),Ce=(Et,Vt)=>{if(!Vt)return!1;let dn=Vt.split(",").map(Jt=>Jt.trim().toLowerCase()).filter(Boolean),it=Et.toLowerCase();return dn.some(Jt=>it.startsWith(Jt))},Ye=Ce(ot,K.alwaysAskCommands),ke=Ce(ot,K.autoApproveCommands);if(Ge=Ce(ot,K.autoDisallowCommands),Ye?we=!0:(ke||K.autoApproveGit&&/^git\s+commit\b/i.test(ot))&&(ye="allow"),!we&&!ye){if(K.networkAccess===!1){let Vt=ot.trim().replace(/\s+/g," ").replace(/^['"]+|['"]+$/g,"").toLowerCase().split(" "),it=Vt[0].split("/").pop().split("\\").pop().replace(/\.exe$/,""),Jt=new Set(["curl","wget","httpie","xh","ssh","scp","sftp","rsync","ftp","lftp","tftp","telnet","nc","netcat","socat","ping","traceroute","tracert","dig","nslookup","host","whois","nmap","docker","podman","kubectl","helm","gcloud","aws","az","terraform","ansible-playbook","nix","nix-env","apt","apt-get","dpkg","yum","dnf","pacman","zypper","brew","apk","choco","scoop","conda","mamba","aria2c","axel","smbclient","lynx","w3m","links","elinks","heroku","netlify","vercel","firebase","supabase","wrangler","flyctl","powershell","pwsh","certutil","bitsadmin","cloudflared","ngrok","tailscale","zerotier","rclone"]),rt=!1;Jt.has(it)&&(rt=!0);let dt=kn=>Vt.slice(1).some(Sn=>kn.includes(Sn)),At=kn=>{let Sn=Vt.findIndex(Mn=>kn.includes(Mn)),Ss=Vt.findIndex(Mn=>["run","exec","test"].includes(Mn));return Sn!==-1&&!(Ss!==-1&&Ss<Sn)};it==="git"&&dt(["clone","pull","push","fetch"])&&(rt=!0),it==="go"&&dt(["get","install"])&&(rt=!0),it==="npm"&&At(["install","i","update","add"])&&(rt=!0),it==="yarn"&&At(["add","install","upgrade"])&&(rt=!0),it==="pnpm"&&At(["add","install","update"])&&(rt=!0),it==="bun"&&At(["add","install","update"])&&(rt=!0),it==="deno"&&dt(["install","add"])&&(rt=!0),it==="pip"&&dt(["install","download"])&&(rt=!0),it==="pip3"&&dt(["install","download"])&&(rt=!0),it==="cargo"&&dt(["install","add"])&&(rt=!0),["bash","sh","zsh","fish"].includes(it)&&dt(["-c"])&&(rt=!0),it==="cmd"&&dt(["/c"])&&(rt=!0),rt&&(ye="deny",Ae=!0)}!ye&&Ge&&(ye="deny")}!we&&!ye&&ae&&(ye="allow")}else ae&&(ye="allow");let be=ye,ee="";ye==="deny"&&(Ae?ee="network":Ge?ee="settings":ee="prohibited");let fe=!1,le="",Fe=[],Ze=0,xe=!1;if(!be){if(C==="write_file"||C==="update_file")try{let Ce=O(z.args),{path:Ye}=Ce;if(Ye){let ke=Q.resolve(process.cwd(),Ye),Et=dt=>dt?dt.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,At=>At.toUpperCase()):"",Vt=Et(ke),dn="",it=!1,Jt=await gs(),rt=Et(Jt?.file_focused);if(Jt&&rt===Vt&&Jt.full_content?(dn=Jt.full_content,it=!0):Oe.existsSync(ke)&&(dn=Oe.readFileSync(ke,"utf8"),it=!0),le=dn,await ut.recordFileChange(ke,dn),it){let dt=dn;if(C==="write_file")dt=Ce.content||Ce.newContent||"";else{let{patchPairs:At,allowMultiple:kn,error:Sn}=vo(Ce);if(Sn){let $t=`[TOOL RESULT]: ERROR: ${Sn}`;Z.push({role:"user",text:$t}),await It("toolFailure"),t.onToolResult&&t.onToolResult("failure",C),yield{type:"tool_result",content:$t,toolName:C},He++;continue}let Ss=Ce.allowMultiple!==void 0?Ce.allowMultiple===!0||String(Ce.allowMultiple).toLowerCase()==="true":kn;Ze=At.length;let Mn=Io(dn,At,{allowMultiple:Ss});dt=Mn.content,Fe=Mn.results;let wo=Fe.filter($t=>$t.success),vt=Fe.filter($t=>!$t.success);if(wo.length===0){let $t=`[TOOL RESULT]: ERROR: Failed to apply patches to [${Q.basename(ke)}].
|
|
659
660
|
${vt.map(Hs=>` \u2022 ${Hs.error}`).join(`
|
|
660
|
-
`)}`,Ts=`\u2714 Edited: ${Q.basename(
|
|
661
|
-
`:""}${
|
|
662
|
-
`)?
|
|
663
|
-
`;
|
|
661
|
+
`)}`,Ts=`\u2714 Edited: ${Q.basename(ke.replaceAll("\\","/"))}`,js=115;process.stdout.isTTY&&(js=process.stdout.columns-5||120);let Rs=Math.min(Ts.length+4,js),xo=`${Ts.padEnd(Rs-2).substring(0,Rs-2)}`;yield{type:"visual_feedback",content:gn(`${Be?`
|
|
662
|
+
`:""}${xo}`)},Be=!1,Z.push({role:"user",text:$t}),await It("toolFailure"),t.onToolResult&&t.onToolResult("failure",C),yield{type:"tool_result",content:$t,toolName:C},He++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${Q.basename(ke)}`},Vi(ke,dn,dt),fe=!0,await new Promise(At=>setTimeout(At,50))}else if(C==="write_file"){let dt=Ce.content||Ce.newContent||"",At=dt.endsWith(`
|
|
663
|
+
`)?dt:dt+`
|
|
664
|
+
`;Oe.existsSync(ke)||(xe=!0,Oe.mkdirSync(Q.dirname(ke),{recursive:!0}),Oe.writeFileSync(ke,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${Q.basename(ke)}`},Vi(ke,"",At),fe=!0,await new Promise(kn=>setTimeout(kn,50))}}}catch(Ce){console.error("Simulation/Diff Error:",Ce)}let De=null;Yi(Ce=>{De=Ce});let ot=t.onToolApproval;if(be=await new Promise(async Ce=>{let Ye=setInterval(()=>{De&&(jo.onIDEApproval&&jo.onIDEApproval(De),clearInterval(Ye),Ce(De))},100);try{let ke=await ot(C,z.args);clearInterval(Ye),Ce(ke)}catch{clearInterval(Ye),Ce("deny")}}),Yi(null),C==="write_file"||C==="update_file"){let{path:Ce}=O(z.args);if(Ce){let Ye=Q.resolve(process.cwd(),Ce);if(xa(Ye,be),be==="deny"&&xe&&Oe.existsSync(Ye))try{Oe.unlinkSync(Ye)}catch{}}}be==="deny"&&(ee="user")}if(be==="allow"&&fe&&Wo()){let{path:De}=O(z.args),ot=Q.resolve(process.cwd(),De),Ce=vt=>vt?Q.resolve(vt).replace(/\\/g,"/").toLowerCase():"",Ye=await gs(),ke="";Ye&&Ye.file_focused&&Ce(Ye.file_focused)===Ce(ot)&&Ye.full_content&&(ke=Ye.full_content),!ke&&Oe.existsSync(ot)&&(ke=Oe.readFileSync(ot,"utf8"),ke||(await new Promise(vt=>setTimeout(vt,100)),ke=Oe.readFileSync(ot,"utf8")));let Et=ke.split(/\r?\n/),Vt=Et.length,dn=Buffer.byteLength(ke,"utf8"),it="";le&&(it=`Old File contents:
|
|
664
665
|
${le.split(/\r?\n/).map(($t,Ts)=>`${Ts+1} | ${$t}`).join(`
|
|
665
666
|
`)}
|
|
666
667
|
|
|
667
|
-
`);let
|
|
668
|
+
`);let Jt="";if(Vt<=100)Jt=Et.join(`
|
|
668
669
|
`);else{let vt=Et.slice(0,50).join(`
|
|
669
670
|
`),$t=Et.slice(-50).join(`
|
|
670
|
-
`);
|
|
671
|
+
`);Jt=`${vt}
|
|
671
672
|
|
|
672
|
-
... [${
|
|
673
|
+
... [${Vt-100} lines truncated for history stability] ...
|
|
673
674
|
|
|
674
|
-
${$t}`}let rt="";if(
|
|
675
|
+
${$t}`}let rt="";if(C==="update_file"){let vt=Oo(le,ke,Fe,12,t?.compressToolResults||jo?.systemSettings?.compressToolResults);rt=`SUCCESS: File [${De}] updated via IDE Companion (May have user edits). [${Fe.length}/${Ze}] blocks applied.
|
|
675
676
|
|
|
676
|
-
${vt}`}else{let vt=
|
|
677
|
-
${le.split(/\r?\n/).map((Hs,
|
|
677
|
+
${vt}`}else{let vt=ke.split(/\r?\n/),$t=vt.length,Ts=Buffer.byteLength(ke,"utf8"),js="";le&&(js=`Old File contents:
|
|
678
|
+
${le.split(/\r?\n/).map((Hs,Ka)=>`${Ka+1} | ${Hs}`).join(`
|
|
678
679
|
`)}
|
|
679
680
|
|
|
680
681
|
`);let Rs="";if($t<=100)Rs=vt.join(`
|
|
681
|
-
`);else{let
|
|
682
|
+
`);else{let xo=vt.slice(0,50).join(`
|
|
682
683
|
`),Hs=vt.slice(-50).join(`
|
|
683
|
-
`);Rs=`${
|
|
684
|
+
`);Rs=`${xo}
|
|
684
685
|
|
|
685
686
|
... [${$t-100} lines truncated] ...
|
|
686
687
|
|
|
687
|
-
${Hs}`}rt=`SUCCESS: File [${
|
|
688
|
+
${Hs}`}rt=`SUCCESS: File [${De}] saved via IDE Companion (May have user edits).
|
|
688
689
|
- Stats: [${$t} lines, ${(Ts/1024).toFixed(1)} KB]
|
|
689
690
|
${js}- Content Preview:
|
|
690
691
|
|
|
691
|
-
${Rs}`}let At=`${
|
|
692
|
-
`:""}${
|
|
692
|
+
${Rs}`}let At=`${De?"\u2714":"\u2718"} ${C==="write_file"?"Created":"Edited"}: ${De.replaceAll("\\","/")||"No File Changes"}`,kn=115;process.stdout.isTTY&&(kn=process.stdout.columns-5||120);let Sn=Math.min(At.length+4,kn),Ss=`${At.padEnd(Sn-2).substring(0,Sn-2)}`;yield{type:"visual_feedback",content:gn(`${Be?`
|
|
693
|
+
`:""}${Ss}`)},Be=!1;let Mn=Date.now();q=Mn,yield{type:"tool_time",content:Mn-ge};let wo=`[TOOL RESULT]: ${rt}`;Z.push({role:"user",text:wo}),cn=!0,await It("toolSuccess"),t.onToolResult&&t.onToolResult("success",C),yield{type:"tool_result",content:rt,aiContent:wo,toolName:C},He++;continue}if(be==="deny"){let De=`Permission Denied: Prohibited ${C==="exec_command"?"Command":"file edit"}.`;if(ee==="user"?De="Permission Denied by User":ee==="settings"?De="Permission Denied by User Policy":ee==="network"?De="Permission Denied: Sandbox Network Access Disabled by User Policy.":ee==="prohibited"&&C==="exec_command"&&(De="Permission Denied: Prohibited Command in User Policy"),C==="write_file"||C==="update_file"){let Ce=`\u2718 ${C==="write_file"?"Write Cancelled":"Edit Denied"}: ${O(z.args).path.replaceAll("\\","/")||"..."}`,Ye=115;process.stdout.isTTY&&(Ye=process.stdout.columns-5||120);let ke=Math.min(Ce.length+4,Ye),Et=`${Ce.padEnd(ke-2).substring(0,ke-2)}`,Vt=` ${" ".repeat(ke)} `;yield{type:"visual_feedback",content:gn(`${Be?`
|
|
693
694
|
`:""}${Et}
|
|
694
|
-
`)},Be=!1}
|
|
695
|
+
`)},Be=!1}C==="exec_command"&&(await new Promise(ot=>setTimeout(ot,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${De}`),await new Promise(ot=>setTimeout(ot,50)),t.onExecEnd&&t.onExecEnd()),Z.push({role:"user",text:`[TOOL RESULT]: DENIED: ${De}`}),yield{type:"tool_result",content:`[TOOL RESULT]: DENIED: ${De}`},await It("toolDenied"),t.onToolResult&&t.onToolResult("denied",C),He++;continue}}if(oe){let A=115;process.stdout.isTTY&&(A=process.stdout.columns-5||120);let K=Math.min(oe.length+4,A),ae=`${oe.padEnd(K-2).substring(0,K-2)}`;yield{type:"visual_feedback",content:gn(`${Be?`
|
|
695
696
|
`:""}${ae}${oe.includes("\u2714")&&(oe.includes("Created")||oe.includes("Edited"))?"":`
|
|
696
|
-
`}`)},Be=!1}if(q>0){let A=Date.now()-q,K=Math.max(0,1e3-A);K>0&&await new Promise(ae=>setTimeout(ae,K))}let
|
|
697
|
+
`}`)},Be=!1}if(q>0){let A=Date.now()-q,K=Math.max(0,1e3-A);K>0&&await new Promise(ae=>setTimeout(ae,K))}let Un={chatId:d,history:n,onChunk:A=>t.onExecChunk?t.onExecChunk(A):null,onAskUser:t.onAskUser,systemSettings:t.systemSettings,mode:r,isMultiModal:rn(Ee),onVisualFeedback:t.onVisualFeedback,onSubagentUpdate:t.onSubagentUpdate,onTokenChunk:t.onTokenChunk,modelName:Ee,aiProvider:t.aiProvider,apiKey:t.apiKey,onUsage:t.onUsage};if(C==="write_file"||C==="update_file")try{let{path:A}=O(z.args);if(A){let K=Q.resolve(process.cwd(),A),ae=await gs();ae&&ae.file_focused===K&&ae.full_content&&(Un.forcedContent=ae.full_content)}}catch{}Zt.push(C);let Te=await fo(C,z.args,Un);if((C==="write_file"||C==="update_file")&&Te.startsWith("SUCCESS")){let{path:A}=O(z.args);if(A){let K=Q.resolve(process.cwd(),A);wa(K)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let Ht=Date.now();q=Ht,yield{type:"tool_time",content:Ht-ge},en=Ht;let Yt=null;if(typeof Te=="object"&&Te.binaryPart&&(Yt=Te.binaryPart,Te=Te.text),C==="search_keyword"){let{keyword:A,path:K}=O(z.args),ae=typeof Te=="string"&&Te.startsWith("[GLOB]");ae&&(Te=Te.slice(6).trimStart());let ye=typeof Te=="string"&&Te.startsWith("[DIR]");ye&&(Te=Te.slice(5).trimStart());let we=0;if(Te){let Fe=Te.match(/Found (\d+) match/i);Fe&&(we=parseInt(Fe[1]))}let Ge=K?K.replace(/[\/\\]+$/,""):null,Ae=Ge&&Ge!=="."?`"${ae?K:ye?`${Ge}/*`:Ge}"`:"./",be=`${A?"\u2714":"\u2718"} Searched: "${A||""}" in ${Ae.replaceAll("\\","/")} \u2192 ${we} Match${we===1?"":"es"}`,ee=115;process.stdout.isTTY&&(ee=process.stdout.columns-5||120);let fe=Math.min(be.length+4,ee),le=`${be.padEnd(fe-2).substring(0,fe-2)}`;yield{type:"visual_feedback",content:gn(`${Be?`
|
|
697
698
|
`:""}${le}
|
|
698
|
-
`)},Be=!1}if(
|
|
699
|
+
`)},Be=!1}if(C==="EmergencyRollback"){let{method:A}=O(z.args);if(A==="forceRevert"){let K=0;if(Te){let be=Te.match(/Total\s*:\s*(\d+)/i);be&&(K=parseInt(be[1]))}let ye=Te&&Te.startsWith("ERROR:")?"\u2718 Emergency Rollback Failed":`\u2714 Emergency Rollback \u2192 ${K} file${K===1?"":"s"} processed`,we=115;process.stdout.isTTY&&(we=process.stdout.columns-5||120);let Ge=Math.min(ye.length+4,we),Ae=`${ye.padEnd(Ge-2).substring(0,Ge-2)}`;yield{type:"visual_feedback",content:gn(`${Be?`
|
|
699
700
|
`:""}${Ae}
|
|
700
|
-
`)},Be=!1}}if(
|
|
701
|
-
`)}return be.filter(ee=>String(ee).trim()).map(ee=>{let fe=String(ee).trim();return fe.startsWith("- [")?fe.substring(6).trim():fe})};if(A==="create"?(
|
|
701
|
+
`)},Be=!1}}if(C==="todo"){let{method:A,tasks:K,markDone:ae}=O(z.args),ye="",we=[],Ge=Ae=>{if(!Ae)return[];let be=Array.isArray(Ae)?Ae:[];if(be.length===0&&typeof Ae=="string"){let ee=Ae.trim();if(ee.startsWith("[")&&ee.endsWith("]")){let fe=ee.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);fe?be=fe.map(le=>le.slice(1,-1).replace(/\\(.)/g,"$1")):be=ee.slice(1,-1).split(",").map(le=>le.trim()).filter(Boolean)}else be=Ae.split(`
|
|
702
|
+
`)}return be.filter(ee=>String(ee).trim()).map(ee=>{let fe=String(ee).trim();return fe.startsWith("- [")?fe.substring(6).trim():fe})};if(A==="create"?(ye="\x1B[32m\u2192\x1B[0m Created Goals",we=Ge(K).map(Ae=>`\x1B[90m\u25CB\x1B[0m ${Ae}`)):A==="append"?(ye="\x1B[34m\u2795\x1B[0m Added New Goals",we=Ge(K).map(Ae=>`\x1B[90m\u25CB\x1B[0m ${Ae}`)):A==="get"&&(ye=ae?"\x1B[36m\u21BB\x1B[0m Updated Goals":"\x1B[35m\u2022\x1B[0m Reviewed Goals",we=(Te||"").split(`
|
|
702
703
|
`).slice(1).join(`
|
|
703
704
|
`).split(`
|
|
704
|
-
`).filter(be=>be.trim().startsWith("- [")).map(be=>{let ee=be.trim(),fe=ee.startsWith("- [x]");return`${fe?"\x1B[32m\u2714\x1B[0m":"\x1B[90m\u25CB\x1B[0m"} ${fe?"\x1B[90m":"\x1B[37m"}${ee.substring(6).trim()}\x1B[0m`})),
|
|
705
|
+
`).filter(be=>be.trim().startsWith("- [")).map(be=>{let ee=be.trim(),fe=ee.startsWith("- [x]");return`${fe?"\x1B[32m\u2714\x1B[0m":"\x1B[90m\u25CB\x1B[0m"} ${fe?"\x1B[90m":"\x1B[37m"}${ee.substring(6).trim()}\x1B[0m`})),ye&&we.length>0){let Ae=[`${ye}`,...we.map(be=>` ${be}`)].join(`
|
|
705
706
|
`);yield{type:"visual_feedback",content:gn(`${Be?`
|
|
706
707
|
`:""}${Ae}
|
|
707
|
-
`)},Be=!1}}
|
|
708
|
-
`));let
|
|
708
|
+
`)},Be=!1}}C==="exec_command"&&t.onExecEnd&&(await new Promise(A=>setTimeout(A,800)),t.onExecEnd());let _n=Te&&Te.startsWith("DENIED:");Te&&!Te.startsWith("ERROR:")&&!_n?(await It("toolSuccess"),t.onToolResult&&t.onToolResult("success",C)):_n||(await It("toolFailure"),t.onToolResult&&t.onToolResult("failure",C));let Gt=(Te||"").toString().replaceAll("[UI_CONTEXT]","");Gt.includes("[[VERIFIED]]")&&(Gt=Gt.replace(/\[\[VERIFIED\]\][\s\S]*?\[\[\/VERIFIED\]\]/g,`[SYSTEM NOTE]: Patch Block matched & applied successfully. Large Block omitted to conserve context.
|
|
709
|
+
`));let Cn;if(Gt.startsWith("[[SAME]]")){let K=Gt.replace(/^\[\[SAME\]\]\s*\r?\n?/,"").split(/\r?\n/),ae=K.filter(we=>we.startsWith("SUCCESS:")||we.trim().startsWith("- Stats:"));Cn=`[TOOL RESULT]: ${ae.length>0?ae.join(`
|
|
709
710
|
`):K.slice(0,2).join(`
|
|
710
711
|
`)}
|
|
711
|
-
[SYSTEM NOTE]: Content verified and persisted to disk. Full preview omitted to conserve context.`}else
|
|
712
|
+
[SYSTEM NOTE]: Content verified and persisted to disk. Full preview omitted to conserve context.`}else Cn=`[TOOL RESULT]: ${Gt}`;Z.push({role:"user",text:Cn,binaryPart:Yt}),cn=!0;let _e=`[TOOL RESULT]: ${Te.replaceAll(`[[VERIFIED]]
|
|
712
713
|
`,"").replaceAll(`
|
|
713
|
-
[[/VERIFIED]]`,"")||""}`;(
|
|
714
|
+
[[/VERIFIED]]`,"")||""}`;(C==="view_file"||C==="web_scrape"||C==="file_map")&&(_e=`[TOOL RESULT]: ${oe} (Context Locked for UI Clarity)`),yield{type:"tool_result",content:_e,aiContent:Cn,binaryPart:Yt,toolName:C},C==="memory"&&Te.includes("SUCCESS")&&(yield{type:"memory_updated"}),He++}if(f==="Google"&&xn&&Date.now()-Yo>=150){yield*ss();let z=Us(xn);for(let ge of z)yield ge;xn="",Yo=Date.now()}}D.usageMetadata&&(Rn=D.usageMetadata),Rn&&(yield{type:"liveTokens",content:Rn.totalTokenCount})}if(ue&&(ue=!1,jt?ze+="</think>":(ce+="</think>",f==="Google"?xn+="</think>":yield{type:"text",content:"</think>"})),jt&&ze.length>0){let D=0,te=Math.min(tt.length,ze.length);for(let G=te;G>0;G--)if(tt.endsWith(ze.substring(0,G))){D=G;break}let B=ze.substring(D);if(B){let Se=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(tt)?B.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):B.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(Se)if(ce+=Se,f==="Google")xn+=Se;else{yield*ss();let me=Us(Se);for(let de of me)yield de}}jt=!1,ze=""}if(yield*ss(),Ot)break;let Ws=(ce||"").trim(),Wa=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(Ws.toLowerCase())||/\[\[END\]\]/i.test(Ws.toLowerCase()),ja=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(Ws.toLowerCase()),Ha=Z.length>0||Ut!==null,Vo=Ws.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/gi,"").trim(),Ga=/(\p{Emoji_Presentation}|\p{Extended_Pictographic})$/u.test(Vo),qa=/([.!?"'*_`|\]\)”’~~]+|\s|`{3}|[\u200B-\u200D\uFEFF])$/u.test(Vo.trim()),za=/[.!?}"'`’“”]$|```$/s.test(Vo)||qa||Ga;!Wa&&!ja&&!Ha&&Ws.length>0,Qe=!0,await It("agent",f)}catch($e){if(Ot){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
|
|
714
715
|
|
|
715
|
-
\x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(String(
|
|
716
|
+
\x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(String($e).includes("Incomplete JSON segment at the end")){ue&&(ue=!1,jt?ze+="</think>":(ce+="</think>",yield{type:"text",content:"</think>"})),Qe=!0,await It("agent",f);break}if(ue&&(ue=!1,jt?ze+="</think>":ce+="</think>"),jt&&ze.length>0){let ns=0,nn=Math.min(tt.length,ze.length);for(let Dt=nn;Dt>0;Dt--)if(tt.endsWith(ze.substring(0,Dt))){ns=Dt;break}let Lt=ze.substring(ns);if(Lt){let sn=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(tt)?Lt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):Lt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");sn&&(ce+=sn)}jt=!1,ze=""}let ne=$e instanceof Error?(()=>{try{return JSON.parse(JSON.parse($e.message).error.message).error.message}catch{return String($e)}})():String($e),nt=new Date().toLocaleString(),Ct=Q.join(fn,"agent");Oe.existsSync(Ct)||Oe.mkdirSync(Ct,{recursive:!0}),Oe.appendFileSync(Q.join(Ct,"error.log"),`ERROR [${nt}]: ${ne}
|
|
716
717
|
|
|
717
718
|
----------------------------------------------------------------------
|
|
718
719
|
|
|
719
|
-
`);let
|
|
720
|
+
`);let tn=$e.status||$e.statusCode||$e.code;if(!(tn&&(tn>=500&&tn<600||tn===408||tn===429)||!tn&&(/status[ :]+(5\d\d|408|429)/i.test(String($e))||/code[ :]+(5\d\d|408|429)/i.test(String($e))||/(500|503|408|429)/.test(String($e))))){if(je<yn-3)throw $e;yield{type:"text",content:ne},yield{type:"status",content:"Error Occured"}}if(ce.trim().length>0||Je>1)if(Je<=yn){Je++;let ns=Math.min(1e3*Math.pow(2,Je-1),24e3);if(ce.trim().length>0){S.push({role:"agent",text:ce});let nn=`[system]
|
|
720
721
|
- seamless continuation: resume immediately. pick up from last words with zero gap/disruption
|
|
721
722
|
- no repetition: do not repeat any text already written
|
|
722
723
|
- no re-think: do not restart or open <think> if reasoning already started. continue the thinking and close thinking block </think> before chat output
|
|
723
724
|
- mid-tool safety: if cutoff was mid-tool call, restart that tool call from start
|
|
724
|
-
- stealth: do not mention/apologize for cutoff [/system]`;Z.length>0?Z.forEach((Lt,
|
|
725
|
+
- stealth: do not mention/apologize for cutoff [/system]`;Z.length>0?Z.forEach((Lt,Dt)=>{Dt===Z.length-1?S.push({...Lt,text:`${Lt.text}
|
|
725
726
|
|
|
726
|
-
${
|
|
727
|
-
Error log can be found in \`/export logs\``);else if(
|
|
728
|
-
Error log can be found in \`/export logs\``)}}if(Rn){let ue=Rn.totalTokenCount||0
|
|
729
|
-
`)
|
|
727
|
+
${nn}`}):S.push(Lt)}):S.push({role:"user",text:nn}),tt+=ce}for(let nn=ns/1e3;nn>0&&!Ot;nn--)yield{type:"status",content:`Error Occured. Recovering Stream (${Je}/${yn}) [Retrying in ${nn.toFixed(0)}s]...`},await new Promise(Lt=>setTimeout(Lt,1e3));yield{type:"status",content:"Error Occured. Recovering Stream..."}}else throw new Error(`Stream collapsed too many times. (Failed to resolve ${yn} times)
|
|
728
|
+
Error log can be found in \`/export logs\``);else if(je<=yn){je++,Je=1,tt="";let ns=Math.min(1e3*Math.pow(2,je-1),32e3),nn=.8+Math.random()*.4,Lt=Math.round(ns*nn);Qn=!0,yield{type:"status",content:`Trying to reach ${e} (${je}/${yn}) [Retrying in ${(Lt/1e3).toFixed(0)}s]`};for(let Dt=Lt/1e3;Dt>0&&!Ot;Dt--)yield{type:"status",content:`Trying to reach ${e} (${je}/${yn}) [Retrying in ${Dt.toFixed(0)}s]`},await new Promise(sn=>setTimeout(sn,1e3));yield{type:"status",content:`Trying to reach ${e}`}}else throw new Error(`Model ${e} cannot be reached. (Failed ${yn} times)
|
|
729
|
+
Error log can be found in \`/export logs\``)}}if(Rn){let ue=Rn.totalTokenCount||0,$e=Rn.cachedContentTokenCount||0,ne=(Rn.candidatesTokenCount||0)+(Rn.thoughtsTokenCount||0);await qt("tokens",ue,f,Ee),$e>0&&await qt("cachedTokens",$e,f,Ee),ne>0&&await qt("candidateTokens",ne,f,Ee),yield{type:"usage",content:Rn}}mr.push(ce);let Nn=ce;ce.match(/(?:<think>|\[think\])([\s\S]*?)(?:<\/think>|\[\/think\])/i)&&(Nn=ce.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/i,""));let es=Ma(ce),$n=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(es.toLowerCase())||/\[\[END\]\]/i.test(es.toLowerCase())||!0,Oc=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(es.toLowerCase()),Lc=He>0;yield{type:"status",content:"Thinking"};let Na=$c(ce,/(\[\s*(turn\s*:)?\s*(continue|finish)\s*\]|\[\[END\]\])/gi,"").trim(),ts=($n||Z.length===0)&&!Wt&&!wn&&!En;if(ts=Z.length===0?ts:!1,ts=Zn||go?!1:ts,ce&&ce.trim().endsWith('")]')&&Z.length===0&&(ts=!1),ts){let ue=mr.join(`
|
|
730
|
+
`),$e=ue.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").trim();yield{type:"interactive_turn_finished",data:{agentText:T,fullAgentTextRaw:ue,history:[...S],needTitle:x}},S.length>0&&S[S.length-1].role==="agent"?S[S.length-1].text=$e:S.push({role:"agent",text:$e}),S.forEach(ne=>{if(ne.role==="user"&&ne.text&&(ne.text=ne.text.replace(/\n\[COMPILE ERROR\][\s\S]*?\[\/ERROR\]/g,""),ne.text=ne.text.replaceAll(`
|
|
730
731
|
|
|
731
732
|
[system] user question. resolve this specific query within '[ANSWER] ... [/ANSWER]' concisely, naturally [/system]
|
|
732
733
|
`,"").replaceAll(`[system] user question. resolve this specific query within '[ANSWER] ... [/ANSWER]' concisely, naturally
|
|
733
734
|
**strictly follow thinking policy as high priority. do not start a response without <think>...</think>** [/system]
|
|
734
735
|
`,"").replaceAll(`[system] **strictly follow thinking policy as high priority. do not start a response without <think>...</think>** [/system]
|
|
735
|
-
`,"").replaceAll(/\n\[system\] WARNING, Turn Limit Impending: Step \d+\/\d+\. Wrap up quickly\/prompt user to continue & use \[\[END\]\] quickly\. \[\/system\]/g,""),ne.text=ne.text.replaceAll(/\n\[system\] File Changes:\n(?:\* .+ \(created|modified|deleted\)\n)*\[\/system\]/g,""),(f==="Mistral"||f==="Google"&&e?.toLowerCase().startsWith("gemma"))&&ne.text.startsWith("[TOOL RESULT]"))){let
|
|
736
|
-
[system] Tool result received. Analyze output and proceed with your turn [/system]`,
|
|
737
|
-
[system] Tool result received. Analyze output and proceed with your turn. **strictly follow thinking policy. do not start a response without <think>...</think>** [/system]`;ne.text=ne.text.replaceAll(
|
|
736
|
+
`,"").replaceAll(/\n\[system\] WARNING, Turn Limit Impending: Step \d+\/\d+\. Wrap up quickly\/prompt user to continue & use \[\[END\]\] quickly\. \[\/system\]/g,""),ne.text=ne.text.replaceAll(/\n\[system\] File Changes:\n(?:\* .+ \(created|modified|deleted\)\n)*\[\/system\]/g,""),(f==="Mistral"||f==="Google"&&e?.toLowerCase().startsWith("gemma"))&&ne.text.startsWith("[TOOL RESULT]"))){let Ct=`
|
|
737
|
+
[system] Tool result received. Analyze output and proceed with your turn [/system]`,tn=`
|
|
738
|
+
[system] Tool result received. Analyze output and proceed with your turn. **strictly follow thinking policy. do not start a response without <think>...</think>** [/system]`;ne.text=ne.text.replaceAll(tn,"").replaceAll(Ct,"").trim()}}),yield{type:"status",content:"[end]"}}if(ts)break;let Ba=Na.trim()||"*Working...*";if(S.push({role:"agent",text:Ba}),Z.length>0||cn){if(Z.length>0){let ue=Z.map(Ct=>Ct.text).join(`
|
|
738
739
|
|
|
739
740
|
`),ne=(ce.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/gi,"").match(/\[tool:functions/g)||[]).length;if(Z.length<ne){ue+=`
|
|
740
741
|
|
|
741
|
-
[SYSTEM] Only ${Z.length} out of ${ne} attempted tool calls were executed. Verify proper schema compliance & try failed calls again [/SYSTEM]`;let
|
|
742
|
-
\u2800`},
|
|
742
|
+
[SYSTEM] Only ${Z.length} out of ${ne} attempted tool calls were executed. Verify proper schema compliance & try failed calls again [/SYSTEM]`;let Ct=ne-Z.length;for(let tn=0;tn<Ct;tn++)await It("toolFailure")}let nt=Z.find(Ct=>Ct.binaryPart)?.binaryPart||null;S.push({role:"user",text:ue,binaryPart:nt})}}else go||Zn?(S.push({role:"user",text:"[SYSTEM] Failed to execute some tools. Verify proper schema compliance & try again [/SYSTEM]"}),await It("toolFailure")):S.push({role:"user",text:`[SYSTEM] ${wn&&!Wt?"STUTTERING DETECTED by Internal System. Re-calibrate your response & proceed.":`${Wt?" OVER THINKING":" LOOP"} DETECTED by Internal System${Wt?" for current EFFORT_LEVEL":""}. ${Wt?"If you have planned the task, prioritize execution/output":"If you have finished your task provide a simple summary and end"}`} [/SYSTEM]`}),Wt=!1,wn=!1,En=!1;l?.advanceRollback&&await Kn.recordTurnDelta(d,H+1,Zt),go=He>0||cn}}catch(_){let v=(_ instanceof Error?(()=>{try{return JSON.parse(JSON.parse(_.message).error.message).error.message}catch{return _.message||String(_)}})():String(_)).replace(/^(Error:\s*)+/i,""),I=new Date().toLocaleString(),P=Q.join(fn,"agent");yield{type:"text",content:`\u2726 CRITICAL ERROR: ${v.includes("fetch failed")?"Failed to Connect. Check your Internet Connection or Wait a moment":v}
|
|
743
|
+
\u2800`},Oe.existsSync(P)||Oe.mkdirSync(P,{recursive:!0}),Oe.appendFileSync(Q.join(P,"error.log"),`CRITICAL ERROR [${I}]: ${_}
|
|
743
744
|
|
|
744
745
|
----------------------------------------------------------------------
|
|
745
746
|
|
|
746
|
-
`),typeof flushGoogleBuffer=="function"&&(yield*flushGoogleBuffer()),yield{type:"tool_result",content:`ERROR: [INTERNAL CRITICAL] ${v}`}}finally{$&&(clearInterval($),$=null),typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),await
|
|
747
|
+
`),typeof flushGoogleBuffer=="function"&&(yield*flushGoogleBuffer()),yield{type:"tool_result",content:`ERROR: [INTERNAL CRITICAL] ${v}`}}finally{$&&(clearInterval($),$=null),typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),await ut.commitTransaction(),l?.advanceRollback&&await Kn.cleanup(d),await gs()}yield{type:"status",content:null}},_m=async(e,n,t=null,o=null,s=50,i=null,a=!1)=>{let r=await Ft(),h={...r,...n},d=process.env.SUBAGENT_MODEL?process.env.SUBAGENT_MODEL.trim():null,c=process.env.SUBAGENT_PROVIDER?process.env.SUBAGENT_PROVIDER.trim():null,l=new Date,u=`${l.getFullYear()}-${l.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(l.getDate()).padStart(2,"0")}, ${l.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}).replace(":","-")}`,p=(_=>{if(!_)return null;let S=_.toLowerCase();return S==="google"?"Google":S==="deepseek"?"DeepSeek":S==="openrouter"?"OpenRouter":S==="nvidia"?"NVIDIA":S==="mistral"?"Mistral":S==="ollama"?"Ollama":S==="crofai"||S==="crof"?"CrofAI":null})(c),g=h?.systemSettings?.CustomSubAgent?h?.systemSettings?.SubAgentModel:null,y=h?.systemSettings?.CustomSubAgent?h?.systemSettings?.SubAgentProvider:null,m=null;if(g==="ENV"?(m=d,d&&p&&(h.aiProvider=p)):g&&g!=="Default"?(m=g,y&&(h.aiProvider=y)):d&&p&&(h.aiProvider=p),h.aiProvider){let _=await Zo(h.aiProvider);_&&(h.apiKey=_)}let w=_=>{if(!_||typeof _!="string")return{allowed:!0};let S=[/rm\s+-[rf]{1,2}\s+[\/*.]/i,/rmdir\s+\/[sq]/i,/del\s+\/[fsq]/i,/\bformat\b\s+[a-z]:/i,/mkfs/i,/dd\s+if=/i,/\b(shutdown|reboot|poweroff|init\s+0|init\s+6)\b/i,/chmod\s+(-R\s+)?777\s+[\/*.]/i,/chown\s+(-R\s+)?root/i,/git\s+push\s+.*--force/i,/git\s+clean\s+-fdx/i,/\bsudo\s+su\b/i,/\bsu\s+-\b/i];for(let v of S)if(v.test(_))return{allowed:!1,reason:`Blocked potentially destructive or unsafe command pattern: "${v.source}"`};return{allowed:!0}},b=t||m||n?.modelName||n?.activeModel||r.activeModel,k=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",R=`-- TOOL DEFINITIONS (path = relative to CWD, path separator: '/') --
|
|
747
748
|
To use tools, must output exactly '[tool:functions.ToolName(arg1="value1")]' structured string in chat response \u2190 no exception
|
|
748
749
|
Tool Rules:
|
|
749
750
|
- JSON escape literal escape sequences in tool arguments
|
|
@@ -771,7 +772,7 @@ ${a?'- [tool:functions.AskMain(question="...")]. Communicate with PARENT/MAIN AG
|
|
|
771
772
|
- [tool:functions.ReadFile(path="...", startLine="int", endLine="int")]
|
|
772
773
|
- [tool:functions.PatchFile(path="...", allowMultiple="bool, default: false", searchContent1="search string OR ^LINE:start..end$", newContent1="...", ...MAX15)]. Target minimal searchContent. Line Ranges must for large searchContent and escape sequences. ^...$ must for line ranges
|
|
773
774
|
- [tool:functions.WriteFile(path="...", content="...")]. Creates/Overwrites. File Exist? PatchFile > WriteFile. VERIFY IMPORTS
|
|
774
|
-
- [tool:functions.Run(command="...")]. Runs ${
|
|
775
|
+
- [tool:functions.Run(command="...")]. Runs ${k==="Windows"?Hn()?"powershell":"windows CMD":"bash"} command. Destructive/Irreversible ops \u2192 Ask user`.trim(),E=`=== START SYSTEM PROMPT ===
|
|
775
776
|
You are a subagent helping the main FluxFlow CLI agent
|
|
776
777
|
Your task is: "${e}"
|
|
777
778
|
|
|
@@ -784,9 +785,9 @@ On task completion, provide a detailed structured summary preferebly in Tables/B
|
|
|
784
785
|
|
|
785
786
|
CWD: ${process.cwd()}
|
|
786
787
|
Current Time: ${u}
|
|
787
|
-
=== END SYSTEM PROMPT ===`,
|
|
788
|
+
=== END SYSTEM PROMPT ===`,x=[{role:"user",text:`Complete this task: ${e}`}],T=0,$="";for(;T<s;){if(Ot){if(n?.taskId&&typeof Ve<"u"){let N=Ve.find(W=>W.id===n.taskId);N&&(N.status="cancelled")}throw i&&i("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}if(n?.taskId&&typeof Ve<"u"){let N=Ve.find(W=>W.id===n.taskId);if(N&&N.status==="cancelled")throw i&&i("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}let _=x.map(N=>({role:N.role==="user"?"user":"model",parts:[{text:N.text}]}));i&&i(`[Subagent Turn ${T+1}]...`);let I=((await Ho(h,b,_,E,"Fast")).text||"").replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/gi,"").trim();$=I,i&&i(`[Subagent Response]
|
|
788
789
|
${I}
|
|
789
|
-
`),
|
|
790
|
+
`),x.push({role:"agent",text:I});let P=Go(I);if(P.length===0)break;let j=P.filter(N=>N.toolName.toLowerCase()==="askmain"||N.toolName.toLowerCase()==="ask_main"),U=!1,Y="";for(let N of P){if(Ot){if(n?.taskId&&typeof Ve<"u"){let M=Ve.find(F=>F.id===n.taskId);M&&(M.status="cancelled")}throw new Error("Subagent task was cancelled.")}if(n?.taskId&&typeof Ve<"u"){let M=Ve.find(F=>F.id===n.taskId);if(M&&M.status==="cancelled")throw new Error("Subagent task was cancelled.")}let W=N.toolName.toLowerCase();if(W==="askmain"||W==="ask_main"){if(U)continue;U=!0;let M="";if(j.length===1?M=O(j[0].args).question||j[0].args:M=j.map((F,V)=>{let J=O(F.args);return`Q${V+1}: ${J.question||F.args}`}).join(`
|
|
790
791
|
`),n.onAskMain){i&&i(`[Executing Tool] AskMain("${M}")...`);let F=await n.onAskMain(M);i&&i(`[Tool Result]
|
|
791
792
|
Answer from Main Agent: ${F}
|
|
792
793
|
`),Y+=`[TOOL RESULT for AskMain]: Answer from Main Agent: ${F}
|
|
@@ -799,15 +800,15 @@ Answer from Main Agent: ${F}
|
|
|
799
800
|
`;continue}if(W==="exec_command"||W==="execcommand"||W==="run"){let M=O(N.args).command||"",F=w(M);if(!F.allowed){let V=`ERROR: [SECURITY RESTRICTION] Subagent execution blocked command: ${F.reason}`;i&&i(`[Blocked Command] ${M} - ${F.reason}
|
|
800
801
|
`),Y+=`${V}
|
|
801
802
|
|
|
802
|
-
`;continue}}let Re="";if(W==="web_search"||W==="websearch")Re=`\u2714 \x1B[95mSearched\x1B[0m: ${O(N.args).query||""}`;else if(W==="web_scrape"||W==="webscrape")Re=`\u2714 \x1B[95mScraped\x1B[0m: ${O(N.args).url||""}`;else if(W==="search_keyword"||W==="searchkeyword"||W==="codesearch"||W==="code_search"){let M=O(N.args),F=M.keyword||"",V=M.path||"";Re=`${F?"\u2714":"\u2718"} \x1B[95mSearched\x1B[0m: ${F||"No Query"}${V?` \u2192 ${V.replaceAll("\\","/")}`:""}`}else if(W==="view_file"||W==="viewfile"||W==="readfile")Re=`\u2714 \x1B[95mRead\x1B[0m: ${(O(N.args).path||"").replaceAll("\\","/")}`;else if(W==="list_files"||W==="read_folder"||W==="readfolder"){let M=O(N.args).path||null,F=O(N.args).recurse||0;Re=`${M?"\u2714":"\u2718"} \x1B[95mBrowsed\x1B[0m: ${M?`${M.replaceAll("\\","/")}${F>0?`${M.endsWith("/")?`*${F}`:`/*${F}`}`:`${M.endsWith("/")?"":"/"}`}`:""}`}else if(W==="write_file"||W==="writefile"){let M=O(N.args).path||null;Re=`${M?"\u2714":"\u2718"} \x1B[95mCreated\x1B[0m: ${M?`${M.replaceAll("\\","/")}`:"No File Changes"}`}else if(W==="update_file"||W==="updatefile"||W==="patchfile"||W==="patch_file"||W==="patchfile"||W==="updatefile"){let M=O(N.args).path||null,F=O(N.args).content||null;Re=`${M?"\u2714":"\u2718"} \x1B[95mEdited\x1B[0m: ${M?`${M.replaceAll("\\","/")}`:"No File Changes"}`}else if(W==="exec_command"||W==="execcommand"||W==="run"){let M=O(N.args).command||null;Re=`${M?"\u2714":"\u2718"} \x1B[95mExecuted\x1B[0m: ${M?M.slice(0,100)+(M.length>100?"...":""):"No Command"}`}else if(W==="file_map"||W==="filemap"){let M=O(N.args).path||"";Re=`${M?"\u2714":"\u2718"} \x1B[95mIndexed\x1B[0m: ${M?`${M.replaceAll("\\","/")}`:"File Not Found"}`}else if(W==="await"){let{time:M}=O(N.args),F=parseFloat(M)||0;F<10&&(F=10),F>180&&(F=180),Re=`\u2714 \x1B[95mAwaiting\x1B[0m \u2192 ${(J=>{if(J>=60){let Ne=Math.floor(J/60),
|
|
803
|
+
`;continue}}let Re="";if(W==="web_search"||W==="websearch")Re=`\u2714 \x1B[95mSearched\x1B[0m: ${O(N.args).query||""}`;else if(W==="web_scrape"||W==="webscrape")Re=`\u2714 \x1B[95mScraped\x1B[0m: ${O(N.args).url||""}`;else if(W==="search_keyword"||W==="searchkeyword"||W==="codesearch"||W==="code_search"){let M=O(N.args),F=M.keyword||"",V=M.path||"";Re=`${F?"\u2714":"\u2718"} \x1B[95mSearched\x1B[0m: ${F||"No Query"}${V?` \u2192 ${V.replaceAll("\\","/")}`:""}`}else if(W==="view_file"||W==="viewfile"||W==="readfile")Re=`\u2714 \x1B[95mRead\x1B[0m: ${(O(N.args).path||"").replaceAll("\\","/")}`;else if(W==="list_files"||W==="read_folder"||W==="readfolder"){let M=O(N.args).path||null,F=O(N.args).recurse||0;Re=`${M?"\u2714":"\u2718"} \x1B[95mBrowsed\x1B[0m: ${M?`${M.replaceAll("\\","/")}${F>0?`${M.endsWith("/")?`*${F}`:`/*${F}`}`:`${M.endsWith("/")?"":"/"}`}`:""}`}else if(W==="write_file"||W==="writefile"){let M=O(N.args).path||null;Re=`${M?"\u2714":"\u2718"} \x1B[95mCreated\x1B[0m: ${M?`${M.replaceAll("\\","/")}`:"No File Changes"}`}else if(W==="update_file"||W==="updatefile"||W==="patchfile"||W==="patch_file"||W==="patchfile"||W==="updatefile"){let M=O(N.args).path||null,F=O(N.args).content||null;Re=`${M?"\u2714":"\u2718"} \x1B[95mEdited\x1B[0m: ${M?`${M.replaceAll("\\","/")}`:"No File Changes"}`}else if(W==="exec_command"||W==="execcommand"||W==="run"){let M=O(N.args).command||null;Re=`${M?"\u2714":"\u2718"} \x1B[95mExecuted\x1B[0m: ${M?M.slice(0,100)+(M.length>100?"...":""):"No Command"}`}else if(W==="file_map"||W==="filemap"){let M=O(N.args).path||"";Re=`${M?"\u2714":"\u2718"} \x1B[95mIndexed\x1B[0m: ${M?`${M.replaceAll("\\","/")}`:"File Not Found"}`}else if(W==="await"){let{time:M}=O(N.args),F=parseFloat(M)||0;F<10&&(F=10),F>180&&(F=180),Re=`\u2714 \x1B[95mAwaiting\x1B[0m \u2192 ${(J=>{if(J>=60){let Ne=Math.floor(J/60),Pe=J%60;return`${Ne}m${Pe>0?` ${Pe}s`:""}`}return`${J}s`})(F)}`}else{let M=Zi[W]||N.toolName,F=xs(W,N.args);Re=`\u2714 \x1B[95m${M}\x1B[0m${F?`: ${F}`:""}`}n.onVisualFeedback&&Re&&n.onVisualFeedback(Re),i&&i(`[Executing Tool] ${N.toolName}(${N.args})...`);try{let M=await fo(N.toolName,N.args,{...n,mode:"Flux"});if(i&&i(`[Tool Result]
|
|
803
804
|
${M}
|
|
804
805
|
`),Y+=`[TOOL RESULT for ${N.toolName}]: ${M}
|
|
805
806
|
|
|
806
807
|
`,await It("toolSuccess"),W==="patchfile"||W==="update_file"||W==="updatefile"||W==="patch_file"){if(M){let F=M.split(`
|
|
807
|
-
`),V=0,J=0,Ne=!1;for(let
|
|
808
|
-
`)){if(
|
|
808
|
+
`),V=0,J=0,Ne=!1;for(let Pe of F){if(Pe.includes("[DIFF_START]")){Ne=!0;continue}if(Pe.includes("[DIFF_END]")){Ne=!1;continue}Ne&&(/^\+\d+/.test(Pe)?V++:/^\-\d+/.test(Pe)&&J++)}(V>0||J>0)&&(await qt("linesAdded",V),await qt("linesRemoved",J))}}else if((W==="writefile"||W==="write_file")&&M){let F=M.match(/- Stats: \[(\d+) lines/),V=F?parseInt(F[1]):0,J=0;if(M.includes("Old File contents:")){let Ne=!1;for(let Pe of M.split(`
|
|
809
|
+
`)){if(Pe.includes("Old File contents:")){Ne=!0;continue}Ne&&(Pe.trim()===""?Ne=!1:/^\d+ \|/.test(Pe)&&J++)}}(V>0||J>0)&&(await qt("linesAdded",V),await qt("linesRemoved",J))}}catch(M){let F=`ERROR: Execution failed for [${N.toolName}]: ${M.message}`;i&&i(`[Tool Error] ${F}
|
|
809
810
|
`),Y+=`${F}
|
|
810
811
|
|
|
811
|
-
`,await It("toolFailure")}}let ie="";if(n?.taskId&&typeof
|
|
812
|
+
`,await It("toolFailure")}}let ie="";if(n?.taskId&&typeof Ve<"u"){let N=Ve.find(W=>W.id===n.taskId);if(N&&N.pendingSteerMessages&&N.pendingSteerMessages.length>0){let W=[...N.pendingSteerMessages];N.pendingSteerMessages=[];for(let re of W)ie+=`
|
|
812
813
|
|
|
813
|
-
[STEERING INSTRUCTION FROM MAIN AGENT]: ${re}`,i&&i(`[Subagent Steered] ${re}`)}}let
|
|
814
|
+
[STEERING INSTRUCTION FROM MAIN AGENT]: ${re}`,i&&i(`[Subagent Steered] ${re}`)}}let Me=(Y.trim()+ie).trim();x.push({role:"user",text:Me}),T++}return $};export{pn as a,Gr as b,xf as c,bf as d,yl as e,qr as f,kf as g,El as h,Sf as i,uo as j,ma as k,Ap as l,vp as m,O as n,Uc as o,ti as p,Ks as q,Wc as r,jc as s,ut as t,ls as u,xd as v,nl as w,bd as x,kd as y,Sd as z,Td as A,Rd as B,vd as C,Id as D,Tn as E,rl as F,Js as G,qt as H,al as I,Dr as J,cs as K,Fl as L,bu as M,ku as N,Lp as O,Wo as P,Dp as Q,Pn as R,Sc as S,km as T,Sm as U,rr as V,Tm as W,Rm as X,vc as Y,Em as Z,$m as _,_m as $};
|