fluxflow-cli 4.6.1 → 4.6.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
import{b as
|
|
1
|
+
import{b as or}from"./chunk-JM3JCK2K.js";import{e as vt,g as zt,i as Ei,j as _i,k as $i,l as Ci,m as Mi}from"./chunk-QLPFOHKZ.js";import{c as At,d as Cs,g as Re,h as en}from"./chunk-IJCIHHAH.js";import{a as sr,b as Ri,c as ne,d as he}from"./chunk-SIINYZWE.js";import{a as Es,c as vn,d as hn,e as wo,f as _s,g as $s,j as Dt,k as Zt,l as In,m as Wn,n as an,o as mn,p as is,q as nr,r as jn,s as as}from"./chunk-4TZKD2XR.js";import{a as Ve,c as xo}from"./chunk-56EJGQU3.js";import{c as Ai,d as vi,e as qs}from"./chunk-ROHVHR3J.js";import di from"dotenv";import{GoogleGenAI as Pa,ThinkingLevel as ut,HarmBlockThreshold as Yn,HarmCategory as Vn}from"@google/genai";import{execSync as el}from"child_process";import{spawn as rr}from"child_process";var L=e=>{let n={};if(!e)return n;let t=0;for(;t<e.length;){for(;t<e.length&&/[\s,]/.test(e[t]);)t++;if(t>=e.length)break;let s=e.substring(t).match(/^(\w+)\s*=\s*/);if(!s){t++;continue}let o=s[1];t+=s[0].length;let r="";if(t<e.length&&(e[t]==='"'||e[t]==="'"||e[t]==="`")){let a=e[t];t++;let i=t,h=-1,f=t;for(;f<e.length;){let l=e.indexOf(a,f);if(l===-1)break;let u=0;for(let y=l-1;y>=0&&e[y]==="\\";y--)u++;if(u%2!==0){f=l+1;continue}let d=e.substring(l+1),p=d.trim(),g=p===""||/^,\s*\w+\s*=/.test(p)||p.startsWith(")")&&(p.length===1||/^\)\s*([,\]\s]|\[\[?tool:)/i.test(p));if(g&&d.startsWith(`
|
|
2
2
|
`)){let y=p.split(`
|
|
3
3
|
`)[0];if(!y.includes("=")&&!y.includes(")")){f=l+1;continue}}if(g){h=l;break}f=l+1}h!==-1?(r=e.substring(i,h),t=h+1):(r=e.substring(i),t=e.length);let c=o.toLowerCase().includes("path")||["dest","source","to","from"].includes(o.toLowerCase());r=r.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,i=null,h=t,f=-1;for(let c=t;c<e.length;c++){let l=e[c];if(i&&l===i){let u=0;for(let d=c-1;d>=0&&e[d]==="\\";d--)u++;u%2===0&&(i=null)}else!i&&(l==='"'||l==="'"||l==="`")&&(i=l);if(!i&&(l==="["?a++:l==="]"&&a--,a===0)){f=c;break}}if(f!==-1){r=e.substring(h,f+1),t=f+1;try{let c=r.trim();c.startsWith("'")||c.includes("'")}catch{}}else r=e.substring(h),t=e.length}else{let a=e.substring(t),i=a.match(/,\s*\w+\s*=|(?:\s*\)\s*(?:$|\]\]))/);if(i){let h=i.index;r=a.substring(0,h).trim(),t+=h}else r=a.trim(),t=e.length}r==="true"?r=!0:r==="false"?r=!1:typeof r=="string"&&!isNaN(r)&&r.trim()!==""&&(r=Number(r)),typeof r=="string"&&(o.toLowerCase().includes("path")||["dest","source","to","from"].includes(o.toLowerCase()))&&(r=r.replace(/\x0C/g,"\\f").replace(/\x0D/g,"\\r").replace(/\x0B/g,"\\v").replace(/\x08/g,"\\b")),n[o]=r}return n};var bo=null;try{let e=await import("node-pty");bo=e.default||e}catch{}var Kc=!!bo,So=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),
|
|
4
|
+
`;case"r":return"\r";case"t":return" ";case"\\":return"\\";default:return u===a?a:u}})}else if(t<e.length&&e[t]==="["){let a=0,i=null,h=t,f=-1;for(let c=t;c<e.length;c++){let l=e[c];if(i&&l===i){let u=0;for(let d=c-1;d>=0&&e[d]==="\\";d--)u++;u%2===0&&(i=null)}else!i&&(l==='"'||l==="'"||l==="`")&&(i=l);if(!i&&(l==="["?a++:l==="]"&&a--,a===0)){f=c;break}}if(f!==-1){r=e.substring(h,f+1),t=f+1;try{let c=r.trim();c.startsWith("'")||c.includes("'")}catch{}}else r=e.substring(h),t=e.length}else{let a=e.substring(t),i=a.match(/,\s*\w+\s*=|(?:\s*\)\s*(?:$|\]\]))/);if(i){let h=i.index;r=a.substring(0,h).trim(),t+=h}else r=a.trim(),t=e.length}r==="true"?r=!0:r==="false"?r=!1:typeof r=="string"&&!isNaN(r)&&r.trim()!==""&&(r=Number(r)),typeof r=="string"&&(o.toLowerCase().includes("path")||["dest","source","to","from"].includes(o.toLowerCase()))&&(r=r.replace(/\x0C/g,"\\f").replace(/\x0D/g,"\\r").replace(/\x0B/g,"\\v").replace(/\x08/g,"\\b")),n[o]=r}return n};var bo=null;try{let e=await import("node-pty");bo=e.default||e}catch{}var Kc=!!bo,So=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),ir=e=>{if(!e)return"";let n=[[]],t=0,s=0,o=/\x1b\[([0-9;]*?)([a-zA-Z])/g,r=0,a,i=f=>{for(let c=0;c<f.length;c++){let l=f[c];if(l===`
|
|
5
5
|
`)for(t++,s=0;t>=n.length;)n.push([]);else if(l==="\r")s=0;else{for(;t>=n.length;)n.push([]);let u=n[t];for(;s>u.length;)u.push(" ");u[s]=l,s++}}};for(;(a=o.exec(e))!==null;){i(e.substring(r,a.index));let f=a[1],c=a[2],l=f?f.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;s=s+u}else if(c==="D"){let u=l[0]||1;s=Math.max(0,s-u)}else if(c==="G"){let u=(l[0]||1)-1;s=Math.max(0,u)}else if(c==="H"||c==="f"){let u=(l[0]||1)-1,d=(l[1]||1)-1;for(t=Math.max(0,u),s=Math.max(0,d);t>=n.length;)n.push([])}else if(c==="K"){let u=l[0]||0;if(t<n.length){let d=n[t];if(u===0)d.length=s;else if(u===1)for(let p=0;p<s&&p<d.length;p++)d[p]=" ";else u===2&&(d.length=0)}}else if(c==="J"){let u=l[0]||0;(u===2||u===3)&&(n.length=0,n.push([]),t=0,s=0)}r=o.lastIndex}i(e.substring(r));let h=n.map(f=>f.join(""));for(;h.length>0&&h[h.length-1]==="";)h.pop();return h.join(`
|
|
6
|
-
`)},wt=null,
|
|
6
|
+
`)},wt=null,zs=!1,Yc=e=>{try{wt&&(zs&&typeof wt.write=="function"?wt.write(e):wt.stdin&&wt.stdin.writable&&wt.stdin.write(e))}catch{}},Vc=()=>{if(wt){try{zs&&typeof wt.destroy=="function"?wt.destroy():typeof wt.kill=="function"&&(process.platform==="win32"?rr("taskkill",["/pid",wt.pid,"/f","/t"]):wt.kill("SIGKILL"))}catch{}wt=null,zs=!1}},ar=(e,n=!1)=>{if(process.platform!=="win32")return e;let t=[],s="",o=null,r=!1;for(let c=0;c<e.length;c++){let l=e[c];if(r){s+=l,r=!1;continue}if(l==="\\"){if(e[c+1]===" "){s+=" ",c++;continue}s+=l,r=!0;continue}o?(l===o&&(o=null),s+=l):l==='"'||l==="'"?(o=l,s+=l):l===";"&&!s.includes("://")?(s.length>0&&(t.push(s),s=""),t.push(n?";":"&")):l==="&"&&!s.includes("://")?e[c+1]==="&"?(s.length>0&&(t.push(s),s=""),t.push("&&"),c++):(s.length>0&&(t.push(s),s=""),t.push("&")):l==="|"&&!s.includes("://")?(s.length>0&&(t.push(s),s=""),t.push("|")):/\s/.test(l)?s.length>0&&(t.push(s),s=""):s+=l}s.length>0&&t.push(s);let a=c=>!(!c.includes("/")||/^(https?|file|ftp):\/\//i.test(c)||c.startsWith("@")||c.startsWith("/")&&(c.match(/\//g)||[]).length===1||/\s\/|\/\s/.test(c)||/[\(\)\{\}\;\<\>\=\'\"]/.test(c)),i=[];for(let c=0;c<t.length;c++){let l=t[c];if(l==="mkdir"&&n&&Hn()){let u=[],d=c+1;for(;d<t.length;){let p=t[d];if([">",">>","<","&","&&","|","||",";"].includes(p))break;p!=="-p"&&p!=="--parents"&&p!=="-v"&&p!=="--verbose"&&u.push(p),d++}if(u.length>0){let p=u.map(g=>{let y=g.replace(/^['"]|['"]$/g,""),m=g;return a(y)&&(m=g.replace(/\//g,"\\")),m});i.push("New-Item","-ItemType","Directory","-Force","-Path",p.join(","))}else i.push("New-Item","-ItemType","Directory","-Force");c=d-1;continue}if(l==="rm"&&n&&Hn()){let u=[],d=!1,p=!1,g=c+1;for(;g<t.length;){let m=t[g];if([">",">>","<","&","&&","|","||",";"].includes(m))break;m==="-rf"||m==="-fr"?(d=!0,p=!0):m==="-r"||m==="-R"||m==="--recursive"?d=!0:m==="-f"||m==="--force"?p=!0:u.push(m),g++}let y=["Remove-Item"];if(d&&y.push("-Recurse"),p&&y.push("-Force"),u.length>0){let m=u.map(w=>{let x=w.replace(/^['"]|['"]$/g,""),k=w;return a(x)&&(k=w.replace(/\//g,"\\")),k});y.push("-Path",m.join(","))}i.push(...y),c=g-1;continue}if(l==="cp"&&n&&Hn()){let u=[],d=!1,p=!1,g=c+1;for(;g<t.length;){let m=t[g];if([">",">>","<","&","&&","|","||",";"].includes(m))break;m==="-r"||m==="-R"||m==="--recursive"?d=!0:m==="-f"||m==="--force"?p=!0:u.push(m),g++}let y=["Copy-Item"];if(d&&y.push("-Recurse"),p&&y.push("-Force"),u.length>0){let m=u.map(w=>{let x=w.replace(/^['"]|['"]$/g,""),k=w;return a(x)&&(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])}i.push(...y),c=g-1;continue}if(l==="touch"&&n&&Hn()){let u=[],d=c+1;for(;d<t.length;){let p=t[d];if([">",">>","<","&","&&","|","||",";"].includes(p))break;u.push(p),d++}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 $_ } }`;i.push(g)}c=d-1;continue}if(l==="|"&&t[c+1]==="tee"){t[c+2]==="-a"?(i.push(">>"),c+=2):(i.push(">"),c+=1);continue}if(l==="|"&&t[c+1]==="cat"&&t[c+2]===">"){i.push(">"),c+=2;continue}if(l==="|"){let u=t[c+1];if(u){let d=u.replace(/^['"]|['"]$/g,""),p=/\.(txt|md|json|log|csv|html|css|py|js|xml|yaml|yml|pdf|docx|pptx|xlsx)$/i.test(d);if(a(d)&&p){i.push(">");continue}}}i.push(l)}let h=!1,f=i.map(c=>{if(c==="echo")return h=!0,c;[">",">>","<","&","&&","|","||",";"].includes(c)&&(h=!1);let u=/^['"]|['"]$/.test(c),d=c;h&&u&&(d=c.replace(/^['"]|['"]$/g,""));let p=/^['"]|['"]$/.test(d),g=d.replace(/^['"]|['"]$/g,"");a(g)&&(d=d.replace(/\//g,"\\"));let y=d.replace(/^['"]|['"]$/g,"");return y.includes(" ")&&!p&&(d=`"${y}"`),d});if(n){let c="",l=0;for(let u=0;u<f.length;u++){let d=f[u];d==="&&"?(c+="; if ($?) {",l++):d===";"?(c+=" }".repeat(l)+";",l=0):(c&&!c.endsWith(" ")&&!c.endsWith("{")&&(c+=" "),c+=d)}return c+=" }".repeat(l),c}return f.join(" ")},lr=async(e,n={})=>{let{command:t}=L(e),{onChunk:s}=n;if(!t)return'ERROR: Missing "command" argument for exec_command.';let o=process.platform==="win32",r=n.systemSettings||{},a={};return r.networkAccess===!1&&(a.HTTP_PROXY="http://127.0.0.1:9999",a.HTTPS_PROXY="http://127.0.0.1:9999",a.ALL_PROXY="socks5://127.0.0.1:9999",a.http_proxy="http://127.0.0.1:9999",a.https_proxy="http://127.0.0.1:9999",a.all_proxy="socks5://127.0.0.1:9999",a.NO_PROXY="localhost,127.0.0.1"),new Promise(i=>{let h=f=>{let c=f==="pwsh"||f==="powershell",l=ar(t,c),u;o?f==="pwsh"?u="C:\\Users\\User\\AppData\\Local\\Microsoft\\WindowsApps\\pwsh.exe":f==="powershell"?u="powershell.exe":u="cmd.exe":u=process.env.SHELL||"bash";let d=o?c?["-NoProfile","-Command",l]:["/c",l]:["-c",l];if(r.networkAccess===!1&&!o){let p=u,g=[...d];if(process.platform==="linux")u="unshare",d=["-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",d=["-p",y,p,...g]}}if(bo)try{let p=bo.spawn(u,d,{name:"xterm-256color",cols:n.cols||120,rows:n.rows||30,cwd:process.cwd(),env:{...process.env,CI:"false",TERM:"xterm-256color",FORCE_COLOR:"1",...a}});wt=p,
|
|
11
|
+
`;u="sandbox-exec",d=["-p",y,p,...g]}}if(bo)try{let p=bo.spawn(u,d,{name:"xterm-256color",cols:n.cols||120,rows:n.rows||30,cwd:process.cwd(),env:{...process.env,CI:"false",TERM:"xterm-256color",FORCE_COLOR:"1",...a}});wt=p,zs=!0;let g="",y=!1;return p.onData(m=>{if(!y){g+=m,s&&s(m);let w=So(g);/(?:Network:\s+use\s+--host\s+to|Network:\s+Type\s+--host\s+to|Local:\s+http:\/\/localhost:\d+|ready in \d+\s*ms|Compiled successfully|Development server is running|Listening on:)/i.test(w)&&(y=!0,setTimeout(()=>i(`SUCCESS: Dev server started successfully in background.
|
|
12
12
|
|
|
13
|
-
${w}`),500))}}),p.onExit(({exitCode:m})=>{if(y)return;wt=null;let w=
|
|
13
|
+
${w}`),500))}}),p.onExit(({exitCode:m})=>{if(y)return;wt=null;let w=ir(g||""),x=So(w).replace(/\n{3,}/g,`
|
|
14
14
|
|
|
15
15
|
`)||"Command executed with no output.";i(m!==0?`ERROR: Command [${t}] failed with exit code [${m}].
|
|
16
16
|
|
|
@@ -21,9 +21,9 @@ ${x}`)}),!0}catch(p){return o&&(f==="pwsh"||f==="powershell")&&p.code==="ENOENT"
|
|
|
21
21
|
(deny network-outbound)
|
|
22
22
|
(allow network-outbound (remote ip "localhost:*"))
|
|
23
23
|
(allow network-outbound (remote ip "127.0.0.1:*"))
|
|
24
|
-
`;f="sandbox-exec",c=["-p",m,g,...y]}}let l=i?
|
|
24
|
+
`;f="sandbox-exec",c=["-p",m,g,...y]}}let l=i?rr(f,c,{cwd:process.cwd(),env:{...process.env,...s}}):rr(f,c,{cwd:process.cwd(),env:{...process.env,CI:"false",TERM:"xterm-256color",FORCE_COLOR:"1",...s}});wt=l,zs=!1,l.stdin&&l.stdin.on("error",()=>{wt=null});let u="",d="",p=!1;l.stdout.on("data",g=>{if(!p){let y=g.toString();u+=y,o&&o(y);let m=So(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
|
-
${m}`),500))}}),l.stderr.on("data",g=>{if(!p){let y=g.toString();d+=y,o&&o(y)}}),l.on("close",g=>{if(p)return;wt=null;let y=[],m=
|
|
26
|
+
${m}`),500))}}),l.stderr.on("data",g=>{if(!p){let y=g.toString();d+=y,o&&o(y)}}),l.on("close",g=>{if(p)return;wt=null;let y=[],m=ir(u),w=ir(d);m&&y.push(`STDOUT:
|
|
27
27
|
${m}`),w&&y.push(`STDERR:
|
|
28
28
|
${w}`),g!==0&&y.push(`EXIT CODE: ${g}`);let x=y.join(`
|
|
29
29
|
|
|
@@ -33,7 +33,7 @@ ${w}`),g!==0&&y.push(`EXIT CODE: ${g}`);let x=y.join(`
|
|
|
33
33
|
|
|
34
34
|
${k}`:`SUCCESS: Command [${t}] completed.
|
|
35
35
|
|
|
36
|
-
${k}`)}),l.on("error",g=>{if(i&&g.code==="ENOENT"){if(r==="pwsh"){let m=
|
|
36
|
+
${k}`)}),l.on("error",g=>{if(i&&g.code==="ENOENT"){if(r==="pwsh"){let m=ar(t,!0);return ko(e,m,t,s,o,"powershell",a)}else if(r==="powershell"){let m=ar(t,!1);return ko(e,m,t,s,o,"cmd",a)}}wt=null;let y=g instanceof Error?g.message:String(g);e(`ERROR: Failed to start command [${t}]: ${y}`)})};var Ks=null,Hn=()=>{if(process.platform!=="win32")return!1;if(Ks!==null)return Ks;try{el('powershell.exe -NoProfile -Command "exit"',{stdio:"ignore"}),Ks=!0}catch{Ks=!1}return Ks},cr=null,Ii=(e,n,t,s,o=!1,r=!0)=>{cr===null&&(cr=o);let a=`- JSON escape literal sequences inside tool arguments (backslash: \\\\, newLine: \\n, quote: \\") \u2190 Mandatory
|
|
37
37
|
- Same file, multiple edits? One PatchFile (\u226415 blocks)
|
|
38
38
|
- Tool denied? Ask for guidance
|
|
39
39
|
- Need text or huge file? CodeSearch > Full Read
|
|
@@ -46,9 +46,9 @@ ${k}`)}),l.on("error",g=>{if(i&&g.code==="ENOENT"){if(r==="pwsh"){let m=cr(t,!0)
|
|
|
46
46
|
- PatchFile(path="...", allowMultiple="bool, false", searchContent1="search string OR ^LINE:start..end$", newContent1="...", ...MAX15). Use small searchContent. Line Ranges must for large searchContent and escape sequences. ^...$ must for line ranges
|
|
47
47
|
- WriteFile(path="...", content="..."). Creates/Overwrites. File Exist? PatchFile > WriteFile
|
|
48
48
|
- CodeSearch(keyword="...", path="dir/file/glob/regex, inclusion/exclusion ;-separated", fuzzy="bool, false", regex="bool, auto"). Find definitions, logic, relevant code, standard junk auto-excluded
|
|
49
|
-
- Run(command="..."). Runs ${n==="Windows"?
|
|
49
|
+
- Run(command="..."). Runs ${n==="Windows"?Hn()?"powershell":"windows CMD":"bash"} command. Destructive/Irreversible ops \u2192 Ask user
|
|
50
50
|
- Goal(method="create/append/get", tasks=[string array], markDone=[task array]). If long multi-task: create Goals before starting. \`get + markDone\` to mark complete. Update every turn when created
|
|
51
|
-
${
|
|
51
|
+
${cr?'\n**Emergency Tools**\nInfo: `initial` = current task prompt. Revert `id` = turn before disaster (eg. disaster: `turn_3` \u2192 revert: `turn_2`). Reason explicitly\n- EmergencyRollback(method="getCheckpoint/forceRevert", id="..."). Rollback workspace in this agent loop. ONLY for catastrophic corruption. Before ending, verify no catastrophe. `id` omitted for `getCheckpoint`\n':""}${r?`
|
|
52
52
|
**Sub Agent Tools**
|
|
53
53
|
proactive use highly recommended. Prefer for any task, no user nudge needed
|
|
54
54
|
Invocations:
|
|
@@ -70,7 +70,7 @@ Invocations:
|
|
|
70
70
|
-- TOOLS --
|
|
71
71
|
You cant execute tools. To use tools, must output exactly [tool:functions.ToolName(arg1="value1")] structured string in chat output & wait for system response \u2190 no exception, tool:functions must
|
|
72
72
|
Tool Rules:
|
|
73
|
-
- Max
|
|
73
|
+
- Max 5 tool calls/turn${e==="Flux"||e.toLowerCase()==="fluxcu"?" (Todo: 5+)":""}
|
|
74
74
|
- NO chat text with tool calls
|
|
75
75
|
${e==="Flux"||e.toLowerCase()==="fluxcu"?`${a}`:""}
|
|
76
76
|
**User Communication**
|
|
@@ -81,7 +81,7 @@ ${e==="Flux"||e.toLowerCase()==="fluxcu"?`${a}`:""}
|
|
|
81
81
|
- WebScrape(url="..."). Proactive use for specific webpage/docs/api
|
|
82
82
|
|
|
83
83
|
${e==="ICU"?`${f}`:e==="FluxCU"?`${i}
|
|
84
|
-
${f}`:e==="Flux"?`${i}`:`${h}`}`.trim()};var
|
|
84
|
+
${f}`:e==="Flux"?`${i}`:`${h}`}`.trim()};var Oi=(e=!0,n=!0)=>`
|
|
85
85
|
To use tools, must output exactly '[tool:functions.ToolName(arg1="value1")]' structured string in chat response \u2190 no exception
|
|
86
86
|
|
|
87
87
|
-- Chat Management Tools --
|
|
@@ -122,18 +122,18 @@ MANDATORY: Brief verification for technical tasks/greetings`,Minimal:`Effort: Lo
|
|
|
122
122
|
Quick, focused thinking, intent & complexity, required tools/files/actions, before acting
|
|
123
123
|
Brief thoughts, think only enough to avoid mistakes, verify imports, tool results & system stability; avoid syntax errors`,Off:`Effort: Lowest
|
|
124
124
|
No thinking. Immediate response
|
|
125
|
-
Verify imports, tool results & system stability; avoid syntax errors`};import
|
|
126
|
-
`),
|
|
125
|
+
Verify imports, tool results & system stability; avoid syntax errors`};import Gn from"fs";import mr from"path";import nl from"os";import sl from"screenshot-desktop";var gr=(e,n)=>{try{if(!Gn.existsSync(e))return null;let t=Array.isArray(n)?n.map(o=>o.toLowerCase()):[n.toLowerCase()],s=Gn.readdirSync(e);for(let o of t){let r=s.find(a=>a.toLowerCase()===o);if(r){let a=mr.join(e,r);if(Gn.statSync(a).isFile())return a}}}catch{}return null},Pi=(e,n)=>{let t=gr(e,n);if(t)try{return Gn.readFileSync(t,"utf8")}catch{}return""},pr=gr(Es,["fluxflow.md","agent.md","agents.md"]),hr=gr(process.cwd(),["fluxflow.md","agent.md","agents.md"]),Ms=pr?Pi(Es,["fluxflow.md","agent.md","agents.md"]).trim():"",Vs=hr?Pi(process.cwd(),["fluxflow.md","agent.md","agents.md"]).trim():"",ol=e=>{if(!e)return null;let n=e.match(/^\s*---\r?\n([\s\S]*?)\r?\n---(?:\r?\n)?([\s\S]*)$/);if(!n)return null;let t=n[1];if((n[2]||"").trim().length===0)return null;let o="",r="",a=t.match(/^name:\s*(.+)$/m),i=t.match(/^description:\s*(.+)$/m);return a&&(o=a[1].trim().replace(/^["']|["']$/g,"")),i&&(r=i[1].trim().replace(/^["']|["']$/g,"")),o&&r?{name:o,description:r}:null},rl=e=>{let n=[];if(!e||!Gn.existsSync(e))return n;let t=(s,o=0)=>{if(!(o>5))try{let r=Gn.readdirSync(s,{withFileTypes:!0});for(let a of r){let i=mr.join(s,a.name),h=a.name.toLowerCase();a.isFile()?h==="skill.md"&&n.push(i):a.isDirectory()&&(o===0?(h==="skills"||h===".skills"||h==="skill"||h===".skill")&&t(i,o+1):t(i,o+1))}}catch{}};return t(e,0),n},Di=e=>{let n=rl(e),t=[];for(let s of n)try{let o=Gn.readFileSync(s,"utf8"),r=ol(o);r&&t.push({...r,filePath:s})}catch{}return t},Fi=e=>!e||e.length===0?"":e.map(n=>`- ${n.name}: ${n.description}`).join(`
|
|
126
|
+
`),yr=Di(Es),wr=Di(process.cwd()),fr=Fi(yr),dr=Fi(wr),hf=(Ms?1:0)+(Vs?1:0)+(yr?.length||0)+(wr?.length||0),ur=(e,n="Project")=>{if(!e)return"";let t=e.replace(/\\/g,"/");if(n==="Global"){let o=nl.homedir().replace(/\\/g,"/");return t.toLowerCase().startsWith(o.toLowerCase())?"~"+t.slice(o.length):t}let s=mr.relative(process.cwd(),e).replace(/\\/g,"/");return s.startsWith(".")?s:`./${s}`},mf=()=>{let e=[];pr&&Ms.length>0&&e.push({scope:"Global",path:pr}),hr&&Vs.length>0&&e.push({scope:"Project",path:hr});let n=yr||[],t=wr||[],s=e.length+n.length+t.length;if(s===0)return`\u2726 Loaded Files & Instructions
|
|
127
127
|
\u2800\u2800\x1B[2m\u2514\u2500\x1B[22m No instruction or skill files are currently loaded.
|
|
128
|
-
\u2800`;let
|
|
129
|
-
\x1B[1mInstructions:\x1B[22m`),
|
|
130
|
-
\x1B[1mSkills:\x1B[22m`),
|
|
131
|
-
`)},
|
|
132
|
-
`):
|
|
128
|
+
\u2800`;let o=[];return o.push(`\u2726 Loaded Files & Instructions (${s} ${s===1?"file":"files"} active)`),e.length>0&&(o.push(`
|
|
129
|
+
\x1B[1mInstructions:\x1B[22m`),e.forEach(r=>{o.push(` \u2022 [${r.scope}] ${ur(r.path,r.scope)}`)})),(n?.length>0||t?.length>0)&&(o.push(`
|
|
130
|
+
\x1B[1mSkills:\x1B[22m`),n?.length>0&&n.forEach(r=>{o.push(` \u2022 [Global] \x1B[36m${r.name}\x1B[39m`),o.push(` \x1B[2m\u2514\u2500 ${ur(r.filePath,"Global")}\x1B[22m`)}),t?.length>0&&t.forEach(r=>{o.push(` \u2022 [Project] \x1B[36m${r.name}\x1B[39m`),o.push(` \x1B[2m\u2514\u2500 ${ur(r.filePath,"Project")}\x1B[22m`)})),o.push("\u2800"),o.join(`
|
|
131
|
+
`)},Ni=!1;(async()=>{try{let e=await en();if(Number(e?.display)===1){let n=await sl.listDisplays();n&&n.length>1&&(Ni=!0)}}catch{}})();var Li=null,Ys=null,gf=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",il=process.env.NO_DEV||!1,al=(e,n)=>{if(!n)return"";if(e!==Li||Ys===null){Li=e;try{let t=ne(Dt,[]);Array.isArray(t)&&t.length>0?Ys=t.map(s=>`- ${s.memory}`).join(`
|
|
132
|
+
`):Ys=""}catch(t){Ys="",Gn.appendFileSync(`${hn}/memory/error.txt`,`${t.message}
|
|
133
133
|
-------------------------------------------------
|
|
134
134
|
|
|
135
|
-
`)}}return
|
|
136
|
-
${e}`:"";return o?`${o}`:""},
|
|
135
|
+
`)}}return Ys},Bi=(e="",n="",t=!0,s=!1)=>{if(typeof n=="boolean"&&(s=t,t=n,n=""),!t)return"";let o=e?.length>0&&!s?`-- Recent context from other chats (Priority: Low, Focus: Chat Context > Recent) --
|
|
136
|
+
${e}`:"";return o?`${o}`:""},Ui=(e,n,t,s,o=!0,r=!1,a="Google",i=!1,h,f)=>{let c=!1;process.env.forcedReasoning&&(c=!0);let l="";if(!h&&a==="Google"){let R=n;n==="Fast"&&(R="Off"),n==="Low"&&(R="Minimal"),n==="Standard"&&(R="Medium"),(n==="xHigh"||n==="Max")&&(R="xHigh"),l=To[R]||To.Medium}if(h||a!=="Google"){let R={Fast:"Lowest",Low:"Low",Medium:"Medium",Standard:"Medium",High:"High",xHigh:"High",Max:"High"};l=To.xHigh,l=l.replace("Effort: High",`Effort: ${R[n]}`).replace(`
|
|
137
137
|
MANDATORY: Full technical verification`,""),n==="Fast"?l=`Effort: Lowest
|
|
138
138
|
No thinking. Immediate response
|
|
139
139
|
Verify imports, tool results & system stability; avoid syntax errors`:n==="Low"&&(l=`Effort: Low
|
|
@@ -147,23 +147,23 @@ ${p.length||d.length?"":`
|
|
|
147
147
|
`}`:"",y=process.cwd(),m=al(f,o),w=m?.length>0?`--- Saved Memories ---
|
|
148
148
|
${m}
|
|
149
149
|
|
|
150
|
-
`:"",x=
|
|
151
|
-
${
|
|
152
|
-
${
|
|
150
|
+
`:"",x=Ms.length>0||Vs.length>0?`--- Additional Instructions ---
|
|
151
|
+
${Ms.length>0?`-- Global --
|
|
152
|
+
${Ms}`:""}${Vs.length>0?`${Ms.length>0?`
|
|
153
153
|
|
|
154
154
|
`:""}-- Project --
|
|
155
|
-
${
|
|
155
|
+
${Vs}`:""}
|
|
156
156
|
|
|
157
157
|
`:"",k=(()=>{let R=process.cwd().toLowerCase();if(process.platform==="win32"){let S=process.env.SystemRoot?.toLowerCase()||"c:\\windows",T=process.env.ProgramFiles?.toLowerCase()||"c:\\program files",E=process.env["ProgramFiles(x86)"]?.toLowerCase()||"c:\\program files (x86)";return R.startsWith(S)||R.startsWith(T)||R.startsWith(E)}else return R==="/"||["/bin","/sbin","/etc","/usr","/var","/root"].some(T=>R.startsWith(T))})();return`${process.env.I_HAVE_TOO_MUCH_MONEY==="true"||process.env.I_HAVE_TOO_MUCH_MONEY===!0||!1?`${" ".repeat(Math.floor(Math.random()*4)+1)}`:""}=== SYSTEM PROMPT ===
|
|
158
158
|
Identity: Flux Flow. Sassy, Friendly, CLI Assistant${il?"":" by Kushal Roy"}
|
|
159
|
-
${t==="Flux"?"Stepwise Execution, Run Automated Tests. Task Completion":t==="Flow"?"Concise, Humorous, Sarcastic":t==="ICU"?"Computer Use Capabilities. Screenshot as ground truth, analyze grid ids overlapping/close to target, keyboard shortcuts > mouse clicks":"Computer Use & Workspace Capabilities. Screenshot as ground truth, analyze grid ids overlapping/close to target, keyboard shortcuts > mouse clicks. Workspace Tools if faster. Focus on Productivity"}${
|
|
159
|
+
${t==="Flux"?"Stepwise Execution, Run Automated Tests. Task Completion":t==="Flow"?"Concise, Humorous, Sarcastic":t==="ICU"?"Computer Use Capabilities. Screenshot as ground truth, analyze grid ids overlapping/close to target, keyboard shortcuts > mouse clicks":"Computer Use & Workspace Capabilities. Screenshot as ground truth, analyze grid ids overlapping/close to target, keyboard shortcuts > mouse clicks. Workspace Tools if faster. Focus on Productivity"}${Ni&&t.toLowerCase().includes("cu")?`
|
|
160
160
|
**Running on secondary screen. Opened app not visible in screenshot? Might be opened on primary. Use 'AskUser' with NO options and tell user to move app window to secondary**`:""}
|
|
161
161
|
|
|
162
162
|
- OS: ${u}
|
|
163
163
|
- Use directory structure for file path resolution${o?`
|
|
164
164
|
- Use relative time reference eg. few mins ago
|
|
165
165
|
-- Chat Context > Metadata`:""}${x.length>0?`
|
|
166
|
-
- Additional Instructions \u2248 System Prompt`:""}${(
|
|
166
|
+
- Additional Instructions \u2248 System Prompt`:""}${(fr.length>0||dr.length>0)&&t.toLowerCase().includes("flux")?`
|
|
167
167
|
- Read relevant skills (if exist) for tasks before acting: Use ReadFile, path="#skills/{global|project}/skillName". If references exist: path="#skills/{global|project}/skillName/references/<file-name>.md"`:""}
|
|
168
168
|
|
|
169
169
|
-- THINKING GUIDANCE --
|
|
@@ -172,7 +172,7 @@ ${c||n!=="Fast"&&(a==="Mistral"&&!h||n!=="xHigh"&&!h)?`critical thinking policy
|
|
|
172
172
|
- Use <think>...</think> for reasoning before responding any queries
|
|
173
173
|
`:""}`:`${l}
|
|
174
174
|
`}
|
|
175
|
-
${
|
|
175
|
+
${Ii(t,u,a.toLowerCase()==="deepseek"?!1:i,a,s?.advanceRollback,s?.subAgents!==!1)}
|
|
176
176
|
${o?`
|
|
177
177
|
-- MEMORY RULES --
|
|
178
178
|
- Subtly Personalize with relevent contextual memories. Auto Saves
|
|
@@ -188,13 +188,13 @@ ${t==="Flux"?`-- SECURITY POLICIES --
|
|
|
188
188
|
- use kaomojis heavily`:""}
|
|
189
189
|
=== END SYSTEM PROMPT ===
|
|
190
190
|
|
|
191
|
-
${g}${p}${d}${x}${
|
|
192
|
-
${
|
|
191
|
+
${g}${p}${d}${x}${fr.length>0&&t.toLowerCase().includes("flux")?`-- Global Skills --
|
|
192
|
+
${fr}
|
|
193
193
|
|
|
194
|
-
`:""}${
|
|
195
|
-
${
|
|
194
|
+
`:""}${dr.length>0&&t.toLowerCase().includes("flux")?`-- Project Skills --
|
|
195
|
+
${dr}
|
|
196
196
|
|
|
197
|
-
`:""}${w}`.trim()},
|
|
197
|
+
`:""}${w}`.trim()},Wi=(e="",n=!0,t=!0)=>`=== SYSTEM PROMPT (strict headless logic worker: zero user-facing text policy, strictly follow) ===
|
|
198
198
|
identity: silent background system process, have no mouth, only output is valid tool calls
|
|
199
199
|
[critical rules]
|
|
200
200
|
- output exactly '[tool:functions.ToolName(args)]' calls. no extra words outside
|
|
@@ -211,16 +211,16 @@ identity: silent background system process, have no mouth, only output is valid
|
|
|
211
211
|
YOUR JOB: Analyze the 'User prompt' and 'Agent Raws' to extract facts for long-term memory or handle system tasks
|
|
212
212
|
${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":""}
|
|
213
213
|
|
|
214
|
-
${
|
|
214
|
+
${Oi(n,t)}
|
|
215
215
|
=== END SYSTEM PROMPT ===${e?`
|
|
216
216
|
|
|
217
217
|
-- current saved user memories --
|
|
218
|
-
${e}`:""}`.trim();import Ct from"fs-extra";import
|
|
218
|
+
${e}`:""}`.trim();import Ct from"fs-extra";import Ro from"path";import{nanoid as fl}from"nanoid";import pt from"fs-extra";import ln from"path";pt.ensureDirSync(Wn);var gn=null;async function ll(e,n){try{if(e.type==="create")await pt.pathExists(e.filePath)&&(await pt.chmod(e.filePath,438).catch(()=>{}),await pt.remove(e.filePath));else if(e.type==="update"){if(!e.backupFile)return;let t=ln.join(Wn,n.chatId,e.backupFile);if(await pt.pathExists(t)){let s=ne(t,null);if(!s||!s.data)throw new Error(`Backup container corrupt or empty for ${ln.basename(e.filePath)}`);let o=Ri(s.data);await pt.pathExists(e.filePath)&&await pt.chmod(e.filePath,438).catch(()=>{}),await pt.writeFile(e.filePath,o,"utf8")}}}catch(t){throw new Error(`Restoration failed for ${ln.basename(e.filePath)}: ${t.message}`)}}async function cl(e,n,t=7){let s=0;for(;s<t;)try{return await ll(e,n),!0}catch{if(s++,s>=t)return!1;let r=Math.min(100*Math.pow(2,s-1),5e3);await new Promise(a=>setTimeout(a,r))}return!1}var xr=null,ht={async startTransaction(e,n){xr=e,gn={id:`tx_prompt_${Date.now()}`,chatId:e,timestamp:new Date().toISOString(),prompt:n.trim(),changes:[],reverted:!1},he(is,gn)},async recordFileChange(e,n=null){try{if(!gn){if(xr){let a=ne(an,[]),i=[...a].reverse().find(h=>h.chatId===xr);if(i){if(i.changes.some(u=>u.filePath===e))return;let c=await pt.pathExists(e)||n?"update":"create",l=null;if(c==="update"){let u=ln.basename(e);l=`${i.id}_${u}.bak`;let d=ln.join(Wn,i.chatId);await pt.ensureDir(d);let p=ln.join(d,l),g=n!==null?n:await pt.readFile(e,"utf8").catch(()=>null);g!==null?he(p,{data:sr(g)}):(c="create",l=null)}i.changes.push({filePath:e,type:c,backupFile:l}),he(an,a)}}return}if(gn.changes.some(a=>a.filePath===e))return;let o=await pt.pathExists(e)||n?"update":"create",r=null;if(o==="update"){let a=ln.basename(e);r=`${gn.id}_${a}.bak`;let i=ln.join(Wn,gn.chatId);await pt.ensureDir(i);let h=ln.join(i,r),f=n!==null?n:await pt.readFile(e,"utf8").catch(()=>null);f!==null?he(h,{data:sr(f)}):(o="create",r=null)}gn.changes.push({filePath:e,type:o,backupFile:r}),he(is,gn)}catch{}},async commitTransaction(){if(gn)try{let e=ne(an,[]);if(e.push(gn),e.length>512e3){let n=e.shift();if(n.changes)for(let t of n.changes)t.backupFile&&await pt.remove(ln.join(Wn,n.chatId,t.backupFile)).catch(()=>{})}he(an,e),await pt.remove(is).catch(()=>{})}catch{}finally{gn=null}},async recoverCrashedTransaction(){try{if(await pt.pathExists(is)){let e=ne(is,null);if(e?.changes?.length>0){let n=ne(an,[]);n.some(t=>t.id===e.id)||(n.push(e),he(an,n))}await pt.remove(is).catch(()=>{})}}catch{}},async rollbackToBefore(e){let n=ne(an,null);if(!n)throw new Error("No transaction ledger found.");let t=n.findIndex(a=>a.id===e);if(t===-1)throw new Error(`Transaction [${e}] not found.`);let s=n[t].chatId,o=n[t].prompt,r=n.slice(t).filter(a=>a.chatId===s&&!a.reverted).reverse();for(let a of r){for(let i of[...a.changes].reverse())await cl(i,a);for(let i of a.changes)if(i.backupFile){let h=ln.join(Wn,a.chatId,i.backupFile);await pt.remove(h).catch(()=>{})}n=n.filter(i=>i.id!==a.id),he(an,n)}return{success:!0,chatId:s,targetPrompt:o}},async getChatHistory(e){try{return ne(an,[]).filter(t=>t.chatId===e&&!t.reverted)}catch{return[]}},async deleteChatBackups(e){try{await pt.remove(ln.join(Wn,e));let n=ne(an,[]),t=n.filter(s=>s.chatId!==e);n.length!==t.length&&he(an,t)}catch{}}};var ji=Promise.resolve(),Eo=e=>{let n=ji.then(async()=>{try{return await e()}catch(t){throw console.error("Lock Operation Failed:",t),t}});return ji=n.catch(()=>{}),n},ls=async()=>{await Ct.ensureDir($s);let e={};if(await Ct.pathExists(_s))try{e=ne(_s,{})}catch{e={}}for(let n in e){let t=Ro.join($s,`${n}.json`);Object.defineProperty(e[n],"messages",{get:()=>{if(Ct.existsSync(t))try{return ne(t,[])}catch{return[]}return[]},set:s=>{try{he(t,s)}catch{}},enumerable:!1,configurable:!0})}return e},Af=async(e,n,t)=>Eo(async()=>{await Ct.ensureDir($s);let s=await ls(),o=s[e],r=(t||[]).filter(y=>!y.isUpdateNotification&&(!y.isMeta||y.text&&y.text.includes("Request Cancelled")));try{(await en()).systemSettings?.preserveThinking===!1&&(r=r.filter(m=>m.role!=="think"))}catch{}let a=y=>{if(!y)return;let m=typeof y=="string"?y:y.text||y.content||"";if(!m||typeof m!="string")return;let w=m.replace(/\s*\n+\s*\[Prompted on:.*?\]/g,"").replace(/\[\/?(?:STEERING HINT|QUESTION)(?::\s*\w+)?\]/gi,"").trim();if(!w)return;let x=w.split(/\s+/),k;return x.length>7?k=x.slice(0,7).join(" ")+"...":w.length>45?k=w.substring(0,45).trimEnd()+"...":k=w,k},i,h=r.filter(y=>y.role==="user"),f=h[0],c=h[h.length-1],l=a(c),u=a(f);o&&o.prompt?Math.random()<.5&&l?i=l:i=o.prompt:i=u||l;let d=n||(o?o.name:`Session ${e.slice(-6)}`),p=Ro.join($s,`${e}.json`);he(p,r),s[e]={name:d,prompt:i||void 0,updatedAt:Date.now()};let g={};for(let y in s)g[y]={name:s[y].name,prompt:s[y].prompt||void 0,updatedAt:s[y].updatedAt};he(_s,g)}),Hi=async(e,n)=>Eo(async()=>{let t=await ls();t[e]?(t[e].name=n,t[e].updatedAt=Date.now()):t[e]={name:n,updatedAt:Date.now()};let s={};for(let o in t)s[o]={name:t[o].name,prompt:t[o].prompt||void 0,updatedAt:t[o].updatedAt};he(_s,s)}),dl=async e=>Eo(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(_s,t),await Ct.pathExists(jn))try{let a=ne(jn,[]);if(Array.isArray(a)){let i=a.filter(h=>Object.keys(h)[0]!==String(e));he(jn,i)}}catch{}let s=ne(Zt,{});s[e]&&(delete s[e],he(Zt,s));let o=ne(In,{});o[e]&&(delete o[e],he(In,o)),await ht.deleteChatBackups(e);let r=Ro.join($s,`${e}.json`);if(await Ct.pathExists(r))try{await Ct.remove(r)}catch{}return n}),vf=()=>`flow-${fl(6)}`,If=async e=>{if(!e||e==="Never")return;let n=parseInt(e);if(isNaN(n))return;let t=await ls(),s=Date.now(),o=n*24*60*60*1e3,r=0;for(let a in t){let i=t[a];i.updatedAt&&s-i.updatedAt>o&&(await dl(a),r++)}return r},ul=e=>{let n=e.replace(/[\[\]]/g,"").trim(),t=new Date(n);if(!isNaN(t.getTime()))return t.getTime();let s=n.split(/,\s*|\s+/);if(s.length===0)return null;let o=s[0],r=s[1]||"",a=s[2]||"",i=o.split(/[-\/.]/).map(Number);if(i.length!==3)return null;let h="en";try{h=Intl.DateTimeFormat().resolvedOptions().locale||"en"}catch{}let f=!/^en[-_]?us$|^en$/.test(h?.toLowerCase()),c,l,u;if(i[0]>1e3)c=i[0],l=i[1],u=i[2];else if(i[2]>1e3)c=i[2],i[0]>12?(u=i[0],l=i[1]):i[1]>12?(u=i[1],l=i[0]):f?(u=i[0],l=i[1]):(l=i[0],u=i[1]);else return null;if(l<1||l>12||u<1||u>31)return null;let d=0,p=0,g=0;if(r){let m=r.split(":").map(Number);d=m[0]||0,p=m[1]||0,g=m[2]||0,a.toLowerCase()==="pm"&&d<12?d+=12:a.toLowerCase()==="am"&&d===12&&(d=0)}let y=new Date(c,l-1,u,d,p,g);return isNaN(y.getTime())?null:y.getTime()},pl=async e=>{try{if(!await Ct.pathExists(e))return;let n=await Ct.readFile(e,"utf8");if(!n.trim())return;let t=n.split(`
|
|
219
219
|
`),s=[],o=null,r=/^\s*(?:DEBUG|ERROR|SEARCH|PUPPETEER)\b/i;for(let l of t)r.test(l)?(o&&s.push(o),o={header:l,body:[]}):o?o.body.push(l):s.push({header:l,body:[]});o&&s.push(o);let a=10080*60*1e3,i=Date.now(),h=[],f=/(\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 s){if(r.test(l.header)){let p=l.header.match(f);if(p){let g=ul(p[1]);if(g&&i-g>a)continue}}let d=l.header+(l.body.length>0?`
|
|
220
220
|
`+l.body.join(`
|
|
221
221
|
`):"");h.push(d)}let c=h.join(`
|
|
222
222
|
`).trim();c?await Ct.writeFile(e,c+`
|
|
223
|
-
`,"utf8"):await Ct.writeFile(e,"","utf8")}catch{}},Of=async e=>{try{if(!await Ct.pathExists(e))return;let n=async t=>{let s=await Ct.readdir(t);for(let o of s){let r=
|
|
223
|
+
`,"utf8"):await Ct.writeFile(e,"","utf8")}catch{}},Of=async e=>{try{if(!await Ct.pathExists(e))return;let n=async t=>{let s=await Ct.readdir(t);for(let o of s){let r=Ro.join(t,o);(await Ct.stat(r)).isDirectory()?(await n(r),(await Ct.readdir(r)).length===0&&await Ct.remove(r)):o.endsWith(".log")&&await pl(r)}};await n(e)}catch{}},Gi=(e,n=4)=>{if(e.length<=1)return e;let t=e[0],s=e.slice(1),o=n*2,r=s.slice(o);return[t,...r]};var Lf=async(e,n,t)=>Eo(async()=>{let s=ne(jn,[]);Array.isArray(s)||(s=[]);let o={total:n,context:t},r=s.findIndex(a=>Object.keys(a)[0]===String(e));r!==-1?s[r]={[String(e)]:o}:s.push({[String(e)]:o}),he(jn,s)}),Pf=async e=>{try{if(!await Ct.pathExists(jn))return{total:0,context:0};let n=ne(jn,[]);if(!Array.isArray(n))return{total:0,context:0};let t=n.find(s=>Object.keys(s)[0]===String(e));return t?t[String(e)]:{total:0,context:0}}catch{return{total:0,context:0}}};import Ki from"puppeteer";import Yi from"fs";import Vi from"path";import qi from"os";import Xs from"path";import As from"fs";import{createRequire as hl}from"module";import{fileURLToPath as ml}from"url";var gl=hl(import.meta.url),zi=Xs.dirname(ml(import.meta.url));function cs(){let e=qi.platform(),n=qi.arch(),t="",s="",o="";if(e==="win32")t=n==="x64"?"win64":"win32",s="chrome.exe",o=`chrome-${t}`;else if(e==="darwin"){t=n==="arm64"?"mac_arm":"mac";let a=n==="arm64"?"arm64":"x64";s="Google Chrome.app/Contents/MacOS/Google Chrome",o=`chrome-mac-${a}`}else if(e==="linux")t="linux",s="chrome",o="chrome-linux64";else return{};let r=Xs.resolve(zi,"..","..",".puppeteerrc.cjs");if(As.existsSync(r)||(r=Xs.resolve(zi,"..",".puppeteerrc.cjs")),!As.existsSync(r))return{};try{let a=gl(r),i=a.cacheDirectory,h=a.chrome?.version;if(i){if(process.env.PUPPETEER_CACHE_DIR=i,h){let l=Xs.join(i,"chrome",`${t}-${h}`,o,s);if(As.existsSync(l))return{executablePath:l,cacheDirectory:i}}let f=l=>{if(!As.existsSync(l))return null;try{let u=As.readdirSync(l),d=[];for(let p of u){let g=Xs.join(l,p),y;try{y=As.statSync(g)}catch{continue}if(y.isDirectory())d.push(g);else if(p.toLowerCase()===s.toLowerCase()&&(!h||g.includes(h)))return g}if(h){for(let p of d)if(p.includes(h)){let g=f(p);if(g)return g}}for(let p of d)if(!h||!p.includes(h)){let g=f(p);if(g)return g}}catch{}return null},c=f(i);if(c)return{executablePath:c,cacheDirectory:i}}}catch{}return{}}var br=async e=>{let{query:n,limit:t=5,aiMode:s=!1}=L(e);if(!n)return'ERROR: Missing "query" argument for web_search.';let o=3,r=null;if(s){let a=`Query: ${n}
|
|
224
224
|
|
|
225
225
|
RESPONSE RULES:
|
|
226
226
|
- ANSWER CONCISELY WITH REQUIRED DETAILS UNDER 300 WORDS.
|
|
@@ -235,7 +235,7 @@ Sources:
|
|
|
235
235
|
|
|
236
236
|
- LIST ONE RAW URL PER BULLET.
|
|
237
237
|
- DO NOT USE MARKDOWN LINKS.
|
|
238
|
-
- DO NOT INCLUDE ANY TEXT, NOTES, OR EXPLANATIONS AFTER THE SOURCES SECTION.`;for(let i=1;i<=o;i++){let h=null;try{let f=
|
|
238
|
+
- DO NOT INCLUDE ANY TEXT, NOTES, OR EXPLANATIONS AFTER THE SOURCES SECTION.`;for(let i=1;i<=o;i++){let h=null;try{let f=cs();h=await Ki.launch({headless:!0,executablePath:f.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let c=await h.newPage();await c.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.178 Safari/537.36"),await c.setViewport({width:1366,height:768});let l=i===1?Math.random()*1e3+500:Math.random()*2e3+1e3;await new Promise(_=>setTimeout(_,l));let u=`https://search.brave.com/ask?q=${encodeURIComponent(a)}&source=web`;await c.goto(u,{waitUntil:"domcontentloaded",timeout:18e4});let d=null,p=45e3,g=Date.now();for(;Date.now()-g<p&&(d=await c.evaluate(()=>{let _=Array.from(document.querySelectorAll('.message:not(.user), .answer-text, .llm-content, [data-type="answer"]')),b="";if(_.length>0&&(b=_.map(se=>se.innerText.trim()).filter(Boolean).join(`
|
|
239
239
|
|
|
240
240
|
`)),b||(b=document.body.innerText),b.includes("anomaly"))throw new Error("ANOMALY_DETECTED");let C=!!document.querySelector('.spinner, .loading, .typing, .streaming, [data-streaming="true"], [data-state="loading"], svg.animate-spin, circle[cx], div[class*="spin"]'),A=_[0]||document.body,O=A?A.innerText.trim():"",D=/^(?:[✓✔]\s*)?Finished/i.test(O)||!!(A&&A.querySelector(".status-finished, .finished")),W=!C&&(D||b.includes("Sources:")&&!C),q={};return document.querySelectorAll("a[href]").forEach(se=>{let V=se.getAttribute("href")||se.href||"";if(V.includes("uddg=")&&(V=decodeURIComponent(V.split("uddg=")[1].split("&")[0])),V.includes("url=")&&(V=decodeURIComponent(V.split("url=")[1].split("&")[0])),V&&(V.startsWith("http://")||V.startsWith("https://"))&&!V.includes("search.brave.com")){let F=se.innerText.trim();F&&(q[F]=V),se.textContent=V}}),{isFinished:W,text:b,hrefMap:q}}),!(d&&d.isFinished));)await new Promise(_=>setTimeout(_,1e3));let y=(d?d.text:"")||"",m=d?d.hrefMap||{}:{},w="DO NOT INCLUDE ANY TEXT, NOTES, OR EXPLANATIONS AFTER THE SOURCES SECTION.";y.includes(w)&&(y=y.split(w).pop()),y=y.replace(/^.*?(Ctrl \+ Shift \+ O|Ask\nAll\nImages)/s,"").replace(/AI-generated answer\. Please verify critical facts\..*/s,"").replace(/Brave Search uses private usage metrics.*/s,"");let x=y,k="";if(y.includes("Sources:")){let _=y.split("Sources:");x=_[0],k=_.slice(1).join("Sources:")}let $=[];for(let _ of x.split(`
|
|
241
241
|
`)){let b=_.trim();b&&(/^(View all|Finished|Searching|Answering|Thinking)$/i.test(b)||/^[\+\-]?\d+$/.test(b)||b.includes("search.brave.com")||b.startsWith("https://www.youtube.com/watch")||b.startsWith("https://youtube.com/watch")||$.push(_))}let R=$.join(`
|
|
@@ -247,7 +247,7 @@ Sources:
|
|
|
247
247
|
|
|
248
248
|
`+T:"");if(!E||/^(\+\d+|Searching|Answering|Thinking|Finished)$/i.test(E))throw new Error("EMPTY_AI_RESPONSE");return await h.close(),`AI Search results for [${n}]:
|
|
249
249
|
|
|
250
|
-
${E}`}catch(f){if(r=f,
|
|
250
|
+
${E}`}catch(f){if(r=f,Yi.writeFileSync(Vi.join(hn,"web_tools","search","ai_mode","ERROR.txt"),f.message),h&&await h.close(),i<o){let c=Math.pow(2,i)*1e3;await new Promise(l=>setTimeout(l,c))}}}}for(let a=1;a<=o;a++){let i=null;try{let h=cs();i=await Ki.launch({headless:!0,executablePath:h.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let f=await i.newPage();await f.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 f.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 f.goto(l,{waitUntil:"networkidle2",timeout:18e4});let u=await f.$$eval(".result",(g,y)=>g.slice(0,y).map((m,w)=>{let x=m.querySelector(".result__a"),k=m.querySelector(".result__snippet"),$=x?x.href:"";$.includes("uddg=")&&($=decodeURIComponent($.split("uddg=")[1].split("&")[0]));let R=x?x.innerText.trim():"No Title",S=k?k.innerText.trim():"No Snippet";return`${w+1}. ${R}
|
|
251
251
|
Source: ${$}
|
|
252
252
|
Snippet: ${S}`}),t);if(u.length===0){if((await f.evaluate(()=>document.body.innerText)).includes("anomaly"))throw new Error("ANOMALY_DETECTED");return await i.close(),`No results found for query: [${n}].`}let d=u.join(`
|
|
253
253
|
|
|
@@ -255,7 +255,7 @@ Snippet: ${S}`}),t);if(u.length===0){if((await f.evaluate(()=>document.body.inne
|
|
|
255
255
|
|
|
256
256
|
`:""}Search results for [${n}]:
|
|
257
257
|
|
|
258
|
-
${d}`}catch(h){if(r=h,i&&await i.close(),
|
|
258
|
+
${d}`}catch(h){if(r=h,i&&await i.close(),Yi.writeFileSync(Vi.join(hn,"web_tools","search","standard_mode","ERROR.txt"),h.message),a<o){let f=Math.pow(2,a)*1e3;await new Promise(c=>setTimeout(c,f))}}}return`ERROR: Search failed after ${o+1} attempts. Last error: ${r.message}`};import yl from"puppeteer";import wl from"turndown";import{gfm as xl}from"turndown-plugin-gfm";var Sr=async e=>{let n=e;if(typeof e=="object"&&e!==null)n=e.url||e.targetUrl||e.href||"";else if(typeof e=="string"){let r=e.match(/url\s*=\s*["'](.*)["']/);n=r?r[1]:e}let t=typeof n=="string"?n.trim():"";if(!t)return"ERROR: No target URL provided.";let s=3,o=null;for(let r=1;r<=s;r++){let a=null;try{let i=cs();a=await yl.launch({headless:!0,executablePath:i.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let h=await a.newPage();await h.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.178 Safari/537.36"),await h.setViewport({width:1366,height:768});let f=r===1?Math.random()*1e3+500:Math.random()*2e3+1e3;await new Promise(g=>setTimeout(g,f)),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 $=k.attributes;for(let R=$.length-1;R>=0;R--){let S=$[R].name;S!=="href"&&S!=="src"&&k.removeAttribute(S)}});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(`
|
|
259
259
|
|
|
260
260
|
`))});let x=()=>{let k=!1;document.querySelectorAll("*").forEach($=>{$.childNodes.length===0&&!$.innerText.trim()&&($.remove(),k=!0)}),k&&x()};return x(),document.body.innerHTML});if(!c)throw new Error("EMPTY_RENDER_RESULT");let l=c.replace(/<br\s*\/?>/gi,`
|
|
261
261
|
|
|
@@ -270,9 +270,9 @@ ${d}`}catch(h){if(r=h,i&&await i.close(),zi.writeFileSync(Ki.join(hn,"web_tools"
|
|
|
270
270
|
|
|
271
271
|
${p}${d.length>5e4?`
|
|
272
272
|
|
|
273
|
-
[TRUNCATED AT 50K CHARS]`:""}`}catch(i){if(o=i,a&&await a.close(),r<s){let h=Math.pow(2,r)*1e3;await new Promise(f=>setTimeout(f,h))}}}return`ERROR: Scrape failed after ${s+1} attempts. Last error: ${o.message}`};var bl=4*(1024*2),
|
|
273
|
+
[TRUNCATED AT 50K CHARS]`:""}`}catch(i){if(o=i,a&&await a.close(),r<s){let h=Math.pow(2,r)*1e3;await new Promise(f=>setTimeout(f,h))}}}return`ERROR: Scrape failed after ${s+1} attempts. Last error: ${o.message}`};var bl=4*(1024*2),kr=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 d=new RegExp(`${c}\\s*[:=]\\s*([^,\\s)]+)`,"s"),p=e.match(d);return p?p[1].trim():null},s=t("action"),o=t("method"),r=t("content"),a=t("content-new"),i=t("content-old"),h=t("id"),f=t("chat-id")||n.chatId||n.sessionId||"default-session";if(s==="temp"){if(!r)return"ERROR: Missing 'content' for temp memory.";let c=ne(Zt,{});c[f]||(c[f]=[]),c[f].push(r),he(Zt,c);let l=c[f].reduce((u,d)=>u+d.length,0);return`SUCCESS: Temporary context saved for session [${f}]. (Size: ${l} chars)`}if(s==="user"){let c=ne(Dt,[]).map(l=>(l.score===void 0&&(l.score=.5),l));if(o==="add"){if(!r)return"ERROR: Missing 'content' for memory addition.";let l=new Date,u=`${l.getDate()}/${l.getMonth()+1}/${l.getFullYear()}`,d=r.includes("[Saved on:")?r:`${r.trim()} [Saved on: ${u}]`,p=bl,g=c.reduce((x,k)=>x+(k.memory?.length||0),0);for(;c.length>0&&g+d.length>p;){let x=c.shift();g-=x.memory?.length||0}let y=t("score"),m=y?parseFloat(y):.5,w={id:`mem-${Date.now().toString(36)}`,memory:d,score:Math.min(2,isNaN(m)?.5:m)};return c.push(w),he(Dt,c),`SUCCESS: Memory added with ID [${w.id}] and score [${w.score}]. (Vault Size: ${g+d.length} chars)`}if(o==="update"){let l=h||i,u=a||r;if(!l||!u)return"ERROR: Missing 'id' or content for update.";let d=c.findIndex(m=>m.id===l);if(d===-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[d].memory=y,he(Dt,c),`SUCCESS: Memory [${l}] updated.`}if(o==="delete"){let l=h||r;if(!l)return"ERROR: Missing 'id' for deletion.";let u=c.length,d=c.filter(p=>p.id!==l);return d.length===u?`ERROR: Memory ID [${l}] not found.`:(he(Dt,d),`SUCCESS: Memory [${l}] deleted.`)}return`ERROR: Invalid method [${o}] for user memory. Use 'add', 'update', or 'delete'.`}return`ERROR: Unknown action [${s}] for memory tool.`};var Tr=async(e,n={})=>{let t=L(e).title,s=n.chatId||n.sessionId;if(!s)return"ERROR: No active chatId found in tool context.";if(!t)return"ERROR: Missing 'title' argument.";try{return await Hi(s,t),`SUCCESS: Chat title updated to [${t}] for session [${s}].`}catch(o){return`ERROR: Failed to update chat title: ${o instanceof Error?o.message:String(o)}`}};import cn from"fs";import En from"path";var Sl=e=>{if(!e)return null;let n=e.match(/^\s*---\r?\n([\s\S]*?)\r?\n---(?:\r?\n)?([\s\S]*)$/);if(!n)return null;let t=n[1];if((n[2]||"").trim().length===0)return null;let o="",r=t.match(/^name:\s*(.+)$/m);return r&&(o=r[1].trim().replace(/^["']|["']$/g,"")),o?{name:o}:null},kl=e=>{let n=[];if(!e||!cn.existsSync(e))return n;let t=(s,o=0)=>{if(!(o>5))try{let r=cn.readdirSync(s,{withFileTypes:!0});for(let a of r){let i=En.join(s,a.name),h=a.name.toLowerCase();a.isFile()?h==="skill.md"&&n.push(i):a.isDirectory()&&(o===0?(h==="skills"||h===".skills"||h==="skill"||h===".skill")&&t(i,o+1):t(i,o+1))}}catch{}};return t(e,0),n},Tl=e=>e.replace(/^(\s*---\r?\n)([\s\S]*?)(\r?\n---)/,(n,t,s,o)=>{let r=s.split(`
|
|
274
274
|
`),a=[],i=!1;for(let h of r){if(/^\s*description\s*:/i.test(h)){i=!0;continue}if(i){if(/^\s+/.test(h))continue;i=!1}a.push(h)}return`${t}${a.join(`
|
|
275
|
-
`)}${o}`}),Rl=(e,n)=>{let t=[En.join(e,"references"),En.join(e,"reference"),e],s=n.toLowerCase().endsWith(".md")?n.toLowerCase():`${n.toLowerCase()}.md`,o=n.toLowerCase();for(let r of t)if(cn.existsSync(r)&&cn.statSync(r).isDirectory())try{let a=cn.readdirSync(r);for(let i of a){let h=i.toLowerCase();if(h===s||h===o){let f=En.join(r,i);if(cn.statSync(f).isFile())return f}}}catch{}return null},Js=async(e,n={})=>{let{path:t,StartLine:s,EndLine:o,start_line:r,end_line:a,startLine:i,endLine:h}=L(e),f=parseInt(s||r||i),c=parseInt(o||a||h),l=!isNaN(f),u=!isNaN(c),d=f||1,p=c||(f?f+800:800);if(!t)return'ERROR: Missing "path" argument for ReadFile.';if(t.trim().toLowerCase().startsWith("#skill")){let w=t.trim().replace(/\\/g,"/").replace(/^#skills?\/?/i,"").split("/").filter(Boolean),x=w[0]?.toLowerCase();if(x!=="global"&&x!=="project")return`ERROR: Invalid skill scope '${x||""}'. Expected 'global' or 'project'.`;let k=w[1];if(!k)return`ERROR: Missing skill name in path [${t}].`;let $=w[2]?.toLowerCase()==="references"||w[2]?.toLowerCase()==="reference",R=$?w.slice(3).join("/"):null,S=x==="global"?
|
|
275
|
+
`)}${o}`}),Rl=(e,n)=>{let t=[En.join(e,"references"),En.join(e,"reference"),e],s=n.toLowerCase().endsWith(".md")?n.toLowerCase():`${n.toLowerCase()}.md`,o=n.toLowerCase();for(let r of t)if(cn.existsSync(r)&&cn.statSync(r).isDirectory())try{let a=cn.readdirSync(r);for(let i of a){let h=i.toLowerCase();if(h===s||h===o){let f=En.join(r,i);if(cn.statSync(f).isFile())return f}}}catch{}return null},Js=async(e,n={})=>{let{path:t,StartLine:s,EndLine:o,start_line:r,end_line:a,startLine:i,endLine:h}=L(e),f=parseInt(s||r||i),c=parseInt(o||a||h),l=!isNaN(f),u=!isNaN(c),d=f||1,p=c||(f?f+800:800);if(!t)return'ERROR: Missing "path" argument for ReadFile.';if(t.trim().toLowerCase().startsWith("#skill")){let w=t.trim().replace(/\\/g,"/").replace(/^#skills?\/?/i,"").split("/").filter(Boolean),x=w[0]?.toLowerCase();if(x!=="global"&&x!=="project")return`ERROR: Invalid skill scope '${x||""}'. Expected 'global' or 'project'.`;let k=w[1];if(!k)return`ERROR: Missing skill name in path [${t}].`;let $=w[2]?.toLowerCase()==="references"||w[2]?.toLowerCase()==="reference",R=$?w.slice(3).join("/"):null,S=x==="global"?Es:process.cwd(),T=kl(S),E=null;for(let A of T)try{let O=cn.readFileSync(A,"utf8"),D=Sl(O),W=En.basename(En.dirname(A)).toLowerCase();if(D?.name&&D.name.toLowerCase()===k.toLowerCase()||W===k.toLowerCase()||A.toLowerCase()===En.join(S,"skill.md").toLowerCase()&&k.toLowerCase()==="skill"){E=A;break}}catch{}if(!E)return`No '${k}' exist in given scope.`;let _=En.dirname(E),b=E,C=!0;if($){if(!R)return`ERROR: Missing reference file name in path [${t}].`;let A=Rl(_,R);if(!A)return`No such reference exist for skill '${k}'`;b=A,C=!1}try{let A=cn.readFileSync(b,"utf8");A.startsWith("\uFEFF")&&(A=A.slice(1)),A=A.replace(/\r\n/g,`
|
|
276
276
|
`).replace(/\r/g,`
|
|
277
277
|
`),C&&(A=Tl(A));let O=A.split(`
|
|
278
278
|
`),D=O.length,W=l?Math.max(0,d-1):0,q=u?Math.min(D,p):D,se=O.slice(W,q),V=`Skill: [${t.replace(/\\/g,"/")}]`,F=se.map((B,Z)=>`${String(W+Z+1).padStart(4)}: ${B.trimEnd()}`).join(`
|
|
@@ -284,19 +284,19 @@ ${F}`}catch(A){let O=A instanceof Error?A.message:String(A);return`ERROR: Failed
|
|
|
284
284
|
`),R=$.length;!l&&!u&&R>800&&(d=1,p=50);let S=Math.max(0,d-1),T=Math.min(R,p),E=$.slice(S,T),_=`File: [${t}] (Showing lines ${S+1}-${T} of ${R}).`,b=E.map((C,A)=>`${String(S+A+1).padStart(4)}: ${C.trimEnd()}`).join(`
|
|
285
285
|
`);return`${_}
|
|
286
286
|
|
|
287
|
-
${b}`}catch(y){let m=y instanceof Error?y.message:String(y);return`ERROR: Failed to read file [${t}]: ${m}`}};import
|
|
287
|
+
${b}`}catch(y){let m=y instanceof Error?y.message:String(y);return`ERROR: Failed to read file [${t}]: ${m}`}};import vs from"fs";import Xi from"path";var Rr=async(e,n={})=>{let{path:t,content:s}=L(e);if(!t)return'ERROR: Missing "path" argument for write_file.';if(s===void 0)return'ERROR: Missing "content" argument for write_file.';s=s.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
|
|
288
288
|
`).replace(/\r/g,`
|
|
289
|
-
`);let o=
|
|
290
|
-
${
|
|
289
|
+
`);let o=Xi.resolve(process.cwd(),t),r=Xi.dirname(o);try{await ht.recordFileChange(o);let a="";if(vs.existsSync(o))try{a=`Old File contents:
|
|
290
|
+
${vs.readFileSync(o,"utf8").split(/\r?\n/).map(($,R)=>`${R+1} | ${$}`).join(`
|
|
291
291
|
`)}
|
|
292
292
|
|
|
293
293
|
`}catch{a=`[Note: Could not read existing file for reversal reference]
|
|
294
294
|
|
|
295
|
-
`}
|
|
295
|
+
`}vs.existsSync(r)||vs.mkdirSync(r,{recursive:!0});let h=(x=>x.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
|
|
296
296
|
`).replace(/\r/g,`
|
|
297
297
|
`))(s),f=h.endsWith(`
|
|
298
298
|
`)?h:h+`
|
|
299
|
-
`,c=f.split(/\r?\n/).length,l=Buffer.byteLength(f,"utf8");
|
|
299
|
+
`,c=f.split(/\r?\n/).length,l=Buffer.byteLength(f,"utf8");vs.writeFileSync(o,f,"utf8");let u=vs.readFileSync(o,"utf8"),d=Buffer.byteLength(u,"utf8"),p=u.split(/\r?\n/),g=p.length;if(d===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(`
|
|
300
300
|
`);else{let x=p.slice(0,50).join(`
|
|
301
301
|
`),k=p.slice(-50).join(`
|
|
302
302
|
`);y=`${x}
|
|
@@ -312,11 +312,11 @@ ${y}`;if(m?.compressToolResults&&g>60){let x=f.split(/\r?\n/),k=x.slice(0,25).jo
|
|
|
312
312
|
`),$=x.slice(-25).join(`
|
|
313
313
|
`)===p.slice(-25).join(`
|
|
314
314
|
`);k&&$&&(w=`[[SAME]]
|
|
315
|
-
${w}`)}return w}catch(a){let i=a instanceof Error?a.message:String(a);return`ERROR: Failed to write file [${t}]: ${i}`}};import
|
|
315
|
+
${w}`)}return w}catch(a){let i=a instanceof Error?a.message:String(a);return`ERROR: Failed to write file [${t}]: ${i}`}};import Cr from"fs";import Pl from"path";import El from"os";var yn=e=>typeof e!="string"?e:e.length>12?(e+"").replace("",""):e,Ji=(e,n)=>{if(!e)return"";let t=/\x1B\[[0-?]*[ -/]*[@-~]/g,s=e.split(`
|
|
316
316
|
`),o=[];if(n<=5)return e;let r=a=>a.replace(t,"").length;return s.forEach(a=>{if(r(a)<=n){o.push(a);return}let h=a.split(/(\s+)/),f="",c=0,l=a.match(/^(\s*)/),u=l?l[1]:"";h.forEach((d,p)=>{if(d.length===0)return;let g=r(d);if(c+g>n)if(f.trim().length>0)o.push(f.trimEnd()),f=u.substring(0,Math.min(u.length,8))+d,c=r(f);else if(t.test(d))o.push(d),f=u,c=r(f);else{let y=d;for(;r(y)>n&&n>10;)o.push(y.substring(0,n)),y=y.substring(n);f=y,c=r(f)}else f+=d,c+=g}),(f.trimEnd().length>0||f===u)&&o.push(f.trimEnd())}),yn(o.join(`
|
|
317
|
-
`))},kd=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()},Td=(e,n=40)=>{let t=vn.replaceAll("\\\\","\\");if(e=e.replace(El.homedir(),"~").replace(t,"FluxFlow").replaceAll("\\","/"),!e||e.length<=n)return yn(e);let s=Math.floor((n-3)/2);return yn(e.substring(0,s)+"..."+e.substring(e.length-s).replaceAll("\\","/"))},
|
|
317
|
+
`))},kd=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()},Td=(e,n=40)=>{let t=vn.replaceAll("\\\\","\\");if(e=e.replace(El.homedir(),"~").replace(t,"FluxFlow").replaceAll("\\","/"),!e||e.length<=n)return yn(e);let s=Math.floor((n-3)/2);return yn(e.substring(0,s)+"..."+e.substring(e.length-s).replaceAll("\\","/"))},_o=e=>{let n=[],t=new Set,s=e.allowMultiple===!0||String(e.allowMultiple).toLowerCase()==="true";Object.keys(e).forEach(h=>{let f=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(f){let c=f[2]?parseInt(f[2],10):1;t.add(c)}});let o=Array.from(t).sort((h,f)=>h-f),r=["searchContent","search_content","replaceContent","replace_content","content_to_replace","searchBlock","search_block"],a=["newContent","new_content","content_to_add","newBlock","new_block"],i=(h,f,c)=>{let l,u;for(let d of f){let p=h===1?[`${d}1`,d,`${d}_1`]:[`${d}${h}`,`${d}_${h}`];for(let g of p)if(e[g]!==void 0){l=e[g];break}if(l!==void 0)break}for(let d of c){let p=h===1?[`${d}1`,d,`${d}_1`]:[`${d}${h}`,`${d}_${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 o){let{r:f,n:c}=i(h,r,a);if(f!==void 0&&c!==void 0)n.push({replace:f,new:c});else if(f!==void 0||c!==void 0)return{error:`Mismatched replacement pair for index ${h}. Both replacement and new content must be provided.`,allowMultiple:s}}return{patchPairs:n,allowMultiple:s}},_l=e=>{if(!e)return null;let n="",t=0,s=e.length;for(;t<s;){let o=e[t];if(o==="\\"){for(;t<s&&e[t]==="\\";)t++;n+="\\\\*"}else if(o===`
|
|
318
318
|
`)n+="(?:\\r?\\n|\\\\*n|\\\\*r|\\s*)",t++;else if(o==="\r")n+="(?:\\r|\\\\*r)?",t++;else if(o===" ")n+="(?:\\t|\\\\*t|\\s*)",t++;else if(o==='"'||o==="'"||o==="`")n.endsWith("\\\\*")||(n+="\\\\*"),n+=o,t++;else if(/[.*+?^${}()|[\]]/.test(o))n+="\\"+o,t++;else if(/\s/.test(o)){for(;t<s&&/\s/.test(e[t])&&e[t]!==`
|
|
319
|
-
`&&e[t]!=="\r"&&e[t]!==" ";)t++;n+="\\s*"}else n+=o,t++}if(!n)return null;try{return new RegExp(n,"g")}catch{return null}}
|
|
319
|
+
`&&e[t]!=="\r"&&e[t]!==" ";)t++;n+="\\s*"}else n+=o,t++}if(!n)return null;try{return new RegExp(n,"g")}catch{return null}},$o=(e,n,t={})=>{let s=typeof t=="boolean"?t:!!(t&&t.allowMultiple),o=e.replace(/\r\n/g,`
|
|
320
320
|
`).replace(/\r/g,`
|
|
321
321
|
`),r=m=>m.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
|
|
322
322
|
`).replace(/\r/g,`
|
|
@@ -333,7 +333,7 @@ ${w}`)}return w}catch(a){let i=a instanceof Error?a.message:String(a);return`ERR
|
|
|
333
333
|
`),_=[];for(let O=Math.max(0,$-4);O<$-1;O++)_.push({num:O+1,text:E[O]});let b=m.firstMatchContent.split(`
|
|
334
334
|
`),C=[],A=$+b.length-1;for(let O=A;O<Math.min(E.length,A+3);O++)C.push({num:O+1,text:E[O]});l.set(m,{success:!0,index:m.index,oldContent:m.firstMatchContent,newContent:T,originalStartLine:x,finalStartLine:$,contextBefore:_,contextAfter:C}),u=u.substring(0,k)+T+u.substring(k+m.firstMatchContent.length),d+=T.length-m.firstMatchContent.length,p+=T.split(`
|
|
335
335
|
`).length-m.firstMatchContent.split(`
|
|
336
|
-
`).length}let y=[];for(let m=0;m<n.length;m++){let w=g.filter(x=>x.index===m);if(w.length>0)for(let x of w)l.has(x)&&y.push(l.get(x));else{let x=f.find(k=>k.index===m);y.push({success:!1,error:x?x.error:`Block ${m+1}: Unknown error.`})}}return{content:u,results:y}},
|
|
336
|
+
`).length}let y=[];for(let m=0;m<n.length;m++){let w=g.filter(x=>x.index===m);if(w.length>0)for(let x of w)l.has(x)&&y.push(l.get(x));else{let x=f.find(k=>k.index===m);y.push({success:!1,error:x?x.error:`Block ${m+1}: Unknown error.`})}}return{content:u,results:y}},Co=(e,n,t,s=8,o=!1)=>{if(!t||t.length===0)return"";let r=e.split(/\r?\n/),a=n.split(/\r?\n/),i=Math.max(r.length,a.length,1),h=Math.max(4,String(i).length),f=g=>String(g).padStart(h," "),c=`[DIFF_START]
|
|
337
337
|
`,l="\u2550".repeat(88),u=0,d=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(d===null)for(u=Math.max(0,m-4);u<m-1;)c+=`[UI_CONTEXT] ${f(u+1)} |${a[u]||""}
|
|
338
338
|
`,u++;else{let T=d,E=T.originalStartLine+T.oldContent.split(`
|
|
339
339
|
`).length-1;if(g.originalStartLine-E-1>=s){let b=Math.min(a.length,u+3);for(;u<b;)c+=`[UI_CONTEXT] ${f(u+1)} |${a[u]||""}
|
|
@@ -350,20 +350,20 @@ ${w}`)}return w}catch(a){let i=a instanceof Error?a.message:String(a);return`ERR
|
|
|
350
350
|
`,x=y.split(m).map(k=>k.split(`
|
|
351
351
|
`).filter(R=>R.trim()!=="").length>45?`[[VERIFIED]]
|
|
352
352
|
${k}
|
|
353
|
-
[[/VERIFIED]]`:k);c=g+x.join(m)}return c+="[DIFF_END]",yn(c)},$l=e=>{if(!e)return null;let n=e.replace("[UI_CONTEXT]","").replace(/\r/g,""),t=n.startsWith("-"),s=n.startsWith("+"),o=t||s?n.substring(1):n,r=o.indexOf("|"),a=r!==-1?yn(o.substring(0,r).trim()):"",i=yn(r!==-1?o.substring(r+1):o);return{isR:t,isA:s,num:a,content:i}},Cl=(e,n)=>{if(!e&&!n)return 1;if(!e||!n)return 0;let t=e.length,s=n.length,o=e,r=n;t<s&&(o=n,r=e);let a=o.length,i=r.length,h=new Int32Array(i+1),f=new Int32Array(i+1);for(let u=0;u<=i;u++)h[u]=u;for(let u=1;u<=a;u++){f[0]=u;let d=o[u-1];for(let p=1;p<=i;p++)d===r[p-1]?f[p]=h[p-1]:f[p]=Math.min(h[p],f[p-1],h[p-1])+1;h.set(f)}let c=h[i],l=Math.max(t,s);return l===0?1:1-c/l},
|
|
354
|
-
`).map(b=>b.replace(/\r$/,"")),$=String(k.length).length,R=[],S=null,T=[],E=()=>{if(!T.length)return;let b=T;T=[],R.push(b.length===1?b[0]:{key:`${b[0].key}-chunk`,type:"chunk",blocks:b})},_=n-($+6);return k.forEach((b,C)=>{let A=C===k.length-1,O=
|
|
355
|
-
`),D=a(`${e.id||Date.now()}-write-line-${C}`,"write-line",b,{gutterWidth:$,lineNum:C+1,isFirstLine:C===0,isLastLine:A,extension:p,wrappedLines:O});A&&e.isStreaming?(E(),S=D):(T.push(D),T.length>=
|
|
356
|
-
`).map(S=>S.replace(/\r$/,"")),m=y.map(S=>({line:S,parsed:$l(S),pairContent:null})),w=[];for(let S=0;S<m.length;S++){let T=m[S];T.parsed&&(T.parsed.isR||T.parsed.isA)?w.push(T):w.length>0&&(
|
|
357
|
-
`));let C=a(`${e.id||Date.now()}-diff-${T}`,"diff-line",S,{isFirstLine:T===0,isLastLine:E,pairContent:m[T].pairContent,wrappedLines:b});E&&e.isStreaming?(R(),k=C):($.push(C),$.length>=
|
|
353
|
+
[[/VERIFIED]]`:k);c=g+x.join(m)}return c+="[DIFF_END]",yn(c)},$l=e=>{if(!e)return null;let n=e.replace("[UI_CONTEXT]","").replace(/\r/g,""),t=n.startsWith("-"),s=n.startsWith("+"),o=t||s?n.substring(1):n,r=o.indexOf("|"),a=r!==-1?yn(o.substring(0,r).trim()):"",i=yn(r!==-1?o.substring(r+1):o);return{isR:t,isA:s,num:a,content:i}},Cl=(e,n)=>{if(!e&&!n)return 1;if(!e||!n)return 0;let t=e.length,s=n.length,o=e,r=n;t<s&&(o=n,r=e);let a=o.length,i=r.length,h=new Int32Array(i+1),f=new Int32Array(i+1);for(let u=0;u<=i;u++)h[u]=u;for(let u=1;u<=a;u++){f[0]=u;let d=o[u-1];for(let p=1;p<=i;p++)d===r[p-1]?f[p]=h[p-1]:f[p]=Math.min(h[p],f[p-1],h[p-1])+1;h.set(f)}let c=h[i],l=Math.max(t,s);return l===0?1:1-c/l},Qi=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 s=n.length,o=t.length;if(s===0||o===0)return;let r=Array.from({length:s+1},()=>Array(o+1).fill(0)),a=Array.from({length:s+1},()=>Array(o+1).fill(""));for(let c=1;c<=s;c++)a[c][0]="up";for(let c=1;c<=o;c++)a[0][c]="left";let i=Array.from({length:s},()=>Array(o).fill(0));for(let c=0;c<s;c++)for(let l=0;l<o;l++)i[c][l]=Cl(n[c].content.trim(),t[l].content.trim());for(let c=1;c<=s;c++)for(let l=1;l<=o;l++){let u=i[c-1][l-1],d=u>=.2?u:-10,p=r[c-1][l-1]+d,g=r[c-1][l],y=r[c][l-1];p>=g&&p>=y?(r[c][l]=p,a[c][l]="diag"):g>=y?(r[c][l]=g,a[c][l]="up"):(r[c][l]=y,a[c][l]="left")}let h=s,f=o;for(;h>0||f>0;)if(a[h][f]==="diag"){if(i[h-1][f-1]>=.2){let l=n[h-1].index,u=t[f-1].index;e[l].pairContent=e[u].parsed.content,e[u].pairContent=e[l].parsed.content}h--,f--}else a[h][f]==="up"?h--:f--},qn=new Map,fs=new Map,Zi=200,Er=6,$r=(e,n)=>{n.set(e.key,e),e.type==="chunk"&&e.blocks&&e.blocks.forEach(t=>$r(t,n))},Rd=(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 s=yn(Ll(e.text||"",e.role)),o=`${e.id}-${n}`,r=new Map;if(e.isStreaming){let p=fs.get(o);p&&s.startsWith(p.text)&&(r=p.blocksMap)}let a=(p,g,y,m={})=>{let w=r.get(p);if(w&&w.text===y&&w.type===g&&!!w.isActiveBlock==!!m.isActiveBlock&&!!w.isStreaming==!!m.isStreaming&&w.pairContent===m.pairContent)return w;let x=yn(y),k={...m};return typeof k.pairContent=="string"&&(k.pairContent=yn(k.pairContent)),Array.isArray(k.wrappedLines)&&(k.wrappedLines=k.wrappedLines.map(yn)),{key:p,isStreamingMsg:!!e.isStreaming,workedDuration:e.workedDuration,type:g,text:x,msg:g==="full-message"?e:void 0,...k}};if(s.includes("- Content Preview:")){let p="",g=s.match(/File\s+\[(.*?)\]/i);g&&(p=g[1].split(".").pop().toLowerCase());let k=((s.split("- Content Preview:")[1]||"").split("[SYSTEM] Check the content preview for verification [/SYSTEM]")[0]?.trim()||"").split(`
|
|
354
|
+
`).map(b=>b.replace(/\r$/,"")),$=String(k.length).length,R=[],S=null,T=[],E=()=>{if(!T.length)return;let b=T;T=[],R.push(b.length===1?b[0]:{key:`${b[0].key}-chunk`,type:"chunk",blocks:b})},_=n-($+6);return k.forEach((b,C)=>{let A=C===k.length-1,O=Ji(b,_).split(`
|
|
355
|
+
`),D=a(`${e.id||Date.now()}-write-line-${C}`,"write-line",b,{gutterWidth:$,lineNum:C+1,isFirstLine:C===0,isLastLine:A,extension:p,wrappedLines:O});A&&e.isStreaming?(E(),S=D):(T.push(D),T.length>=Er&&E())}),E(),{completed:R,active:S?[S]:[]}}if(s.includes("[DIFF_START]")){let p=s.match(/\[DIFF_START\]([\s\S]*?)(?:\[DIFF_END\]|$)/),y=(p?p[1].trim():"").split(`
|
|
356
|
+
`).map(S=>S.replace(/\r$/,"")),m=y.map(S=>({line:S,parsed:$l(S),pairContent:null})),w=[];for(let S=0;S<m.length;S++){let T=m[S];T.parsed&&(T.parsed.isR||T.parsed.isA)?w.push(T):w.length>0&&(Qi(w),w=[])}w.length>0&&Qi(w);let x=[],k=null,$=[],R=()=>{if(!$.length)return;let S=$;$=[],x.push(S.length===1?S[0]:{key:`${S[0].key}-chunk`,type:"chunk",blocks:S})};return y.forEach((S,T)=>{let E=T===y.length-1,_=m[T].parsed,b=null;_&&(b=Ji(_.content,n-17).split(`
|
|
357
|
+
`));let C=a(`${e.id||Date.now()}-diff-${T}`,"diff-line",S,{isFirstLine:T===0,isLastLine:E,pairContent:m[T].pairContent,wrappedLines:b});E&&e.isStreaming?(R(),k=C):($.push(C),$.length>=Er&&R())}),R(),{completed:x,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",s)],active:[]};if(!s&&!e.isStreaming){let p={completed:[],active:[]};return qn.set(t,p),p}let i=[],h=null,f=[],c=null,l=()=>{if(!f.length)return;let p=f;f=[],c=null,i.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(),f.push(p),c=p.type,f.length>=Er){if(e.isStreaming&&g)return;l()}};if(e.role==="think"){i.push(a(`${e.id}-header`,"think-header",""));let p=s.split(`
|
|
358
358
|
`);p.forEach((g,y)=>{let m=y===p.length-1;u(a(`${e.id}-${y}`,"think-line",g,{}),m)}),e.isStreaming||(l(),i.push({key:`${e.id}-footer-padding`,type:"think-footer-padding",text:""}))}else{let p=s.split(`
|
|
359
359
|
`),g=!1,y=[],m=!1,w="",x=0,k=0;p.forEach(($,R)=>{let S=R===p.length-1,T=$.trim().startsWith("|"),E=$.trim().startsWith("```");m?E?(m=!1,u(a(`${e.id}-code-close-${k}`,"code-fence-close","",{}),S)):(x++,u(a(`${e.id}-code-line-${R}`,"code-line",$,{lineNum:x,lang:w}),S)):E?(m=!0,k=R,x=0,w=$.trim().replace(/^```/,"").trim(),u(a(`${e.id}-code-open-${R}`,"code-fence-open",w,{}),S)):T?(g=!0,y.push($),S&&(l(),e.isStreaming?h=a(`${e.id}-table-${R}`,"table",y.join(`
|
|
360
360
|
`),{isStreaming:!0}):i.push(a(`${e.id}-table-${R}`,"table",y.join(`
|
|
361
361
|
`),{isStreaming:!1})))):(g&&(l(),i.push(a(`${e.id}-table-${R}`,"table",y.join(`
|
|
362
|
-
`),{isStreaming:!1})),g=!1,y=[]),u(a(`${e.id}-${R}`,"agent-line",$,{}),S))}),!e.isStreaming&&e.workedDuration&&(l(),i.push(a(`${e.id}-worked-duration`,"worked-duration","")))}e.isStreaming&&f.length>0?h=f.length===1?f[0]:{key:`${e.id||"x"}-chunk-active-${f[0].key}`,type:"chunk",blocks:f}:l();let d={completed:i,active:h?[h]:[]};if(e.isStreaming){let p=new Map;if(i.forEach(g
|
|
362
|
+
`),{isStreaming:!1})),g=!1,y=[]),u(a(`${e.id}-${R}`,"agent-line",$,{}),S))}),!e.isStreaming&&e.workedDuration&&(l(),i.push(a(`${e.id}-worked-duration`,"worked-duration","")))}e.isStreaming&&f.length>0?h=f.length===1?f[0]:{key:`${e.id||"x"}-chunk-active-${f[0].key}`,type:"chunk",blocks:f}:l();let d={completed:i,active:h?[h]:[]};if(e.isStreaming){let p=new Map;if(i.forEach(g=>$r(g,p)),h&&$r(h,p),fs.set(o,{text:s,blocksMap:p}),fs.size>Zi){let g=fs.keys().next().value;fs.delete(g)}}else{if(qn.set(t,d),qn.size>Zi){let p=qn.keys().next().value;qn.delete(p)}fs.delete(o)}return d},Ml={},Al=/(\r?\n){2}(?=\[?(?:tool:functions|tool\.functions|agent:generalist|agent\.generalist|\s*turn\s*:))/gi,_r=(e,n)=>{let t=!1;for(let s=0;s<n;s++)e[s]==="`"&&(t=!t);return t},vl=/\[SYSTEM\][\s\S]*?\[\/SYSTEM\]|\[ANSWER\][\s\S]*?(?:\[\/ANSWER\]|$)|\[TOOL RESULT\]:?\s*|^\s*(SUCCESS|ERROR):.*(\r?\n)?|\[\s*turn\s*:\s*(continue|finish)\s*\]|\[\[END\]\]|\[\s*turn\s*:?.*?$|\n\s*turn\s*:?.*?$|\[\s*(?:turn|ANSWER|TOOL).*?$|\n\nResponded on .*|\n\n\[Prompted on: .*\]|@\[TerminalName:.*?, ProcessId:.*?\]/gm,Il=/(\$?\\?\/?\\rightarrow\$?|\$\\rightarrow\$)|(\$?\\?\/?\\leftarrow\$?|\$\\leftarrow\$)|(\$?\\?\/?\\uparrow\$?|\$\\uparrow\$)|(\$?\\?\/?\\downarrow\$?|\$\\downarrow\$)|(\$?\\?\/?\\leftrightarrow\$?|\$\\leftrightarrow\$)/gi,Ol=/\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,Ll=(e,n="agent")=>{if(!e)return e;let t=n===!0||n==="think",s=n===!1||n==="agent",o=e.replace(/<\|channel>thought/gi,"<think>").replace(/<channel\|>/gi,"</think>");if(t)return o.replace(/^<(think|thought|thoughts)>/gi,"").replace(/<\/(think|thought|thoughts)>$/gi,"").replace(/^\r?\n+/,"").replace(/\r?\n+$/,"");let r=o;s&&(r=r.replace(Al,(h,f,c,l)=>!Is&&_r(l,c)?h:""),r&&r.includes("[tool:")&&(r=r.replace(/<(\w+)(?:[^>]*)>\s*([\s\S]*?\[tool:[^\]]*\][\s\S]*?)\s*<\/\1>/gi,(h,f,c)=>c&&c.includes("[tool:")?c.trim():h),Is&&(r=r.replace(/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi,(h,f)=>f.includes("[tool:")?f.trim():h))));let a="tool:functions.",i="agent:generalist.";if(s&&(r.toLowerCase().includes(a)||r.toLowerCase().includes(i)))for(;;){let h=r.toLowerCase(),f=h.indexOf(a),c=h.indexOf(i),l=a,u=f;if((f===-1||c!==-1&&c<f)&&(l=i,u=c),u===-1)break;if(!Is&&_r(r,u)){let k=u+l.length,$=h.indexOf(a,k),R=h.indexOf(i,k);if($===-1&&R===-1)break;let S=-1,T=0;for(;;){let E=h.indexOf(a,T),_=h.indexOf(i,T),b=-1,C=a;if(E===-1&&_===-1)break;if(E===-1||_!==-1&&_<E?(b=_,C=i):b=E,!_r(r,b)){S=b,l=C;break}T=b+C.length}if(S===-1)break;u=S}let d=u,p=!1,g=u-1;for(;g>=0&&/\s/.test(r[g]);)g--;g>=0&&r[g]==="["&&(d=g,p=!0);let y=0,m=!1,w=null,x=u;for(;x<r.length;){let k=r[x];if(!w&&(k==="'"||k==='"'||k==="`")?w=k:w&&k===w&&r[x-1]!=="\\"&&(w=null),w||(k==="("?(y++,m=!0):k===")"&&y--),m&&y===0&&!w){let $=x;if(p){let R=x+1;for(;R<r.length&&/\s/.test(r[R]);)R++;R<r.length&&r[R]==="]"&&($=R)}r=r.substring(0,d)+r.substring($+1);break}if(x++,x===r.length)return m&&y>0&&(r=r.substring(0,d)),r}}return r=r.replace(vl,""),r=r.replace(Il,h=>{let f=h.toLowerCase();return f.includes("leftrightarrow")?"\u2194":f.includes("rightarrow")?"\u2192":f.includes("leftarrow")?"\u2190":f.includes("uparrow")?"\u2191":f.includes("downarrow")?"\u2193":h}),r=r.replace(Ol,h=>Ml[h.toLowerCase()]||h),r.trim()},Ed=()=>{qn.clear(),fs.clear()};var Mr=async(e,n={})=>{let t=L(e),s=t.path;if(!s)return'ERROR: Missing "path" argument for PatchFile.';let{patchPairs:o,allowMultiple:r,error:a}=_o(t);if(a)return`ERROR: ${a}`;if(o.length===0)return"ERROR: No valid replacement pairs found. Use searchContent1, newContent1, etc.";let i=t.allowMultiple!==void 0?t.allowMultiple===!0||String(t.allowMultiple).toLowerCase()==="true":r,h=Pl.resolve(process.cwd(),s);try{if(!Cr.existsSync(h))return`ERROR: File [${s}] does not exist. Use WriteFile instead.`;let f=n.forcedContent||Cr.readFileSync(h,"utf8");f.startsWith("\uFEFF")&&(f=f.slice(1));let c=f.replace(/\r\n/g,`
|
|
363
363
|
`).replace(/\r/g,`
|
|
364
|
-
`),{content:l,results:u}
|
|
364
|
+
`),{content:l,results:u}=$o(c,o,{allowMultiple:i}),d=u.filter(m=>!m.success),p=u.filter(m=>m.success);if(p.length===0)return`ERROR: Patch Failed to apply to [${s}].
|
|
365
365
|
${d.map(m=>` \u2022 ${m.error}`).join(`
|
|
366
|
-
`)}`;await ht.recordFileChange(h,c),
|
|
366
|
+
`)}`;await ht.recordFileChange(h,c),Cr.writeFileSync(h,l,"utf8");let{systemSettings:g}=await en(),y=Co(c,l,u,12,g?.compressToolResults);return d.length>0?`SUCCESS: File [${s}] updated with some blocks failed. [${p.length}/${o.length}] blocks applied.
|
|
367
367
|
|
|
368
368
|
Failures:
|
|
369
369
|
${d.map(m=>` \u2022 ${m.error}`).join(`
|
|
@@ -371,21 +371,21 @@ ${d.map(m=>` \u2022 ${m.error}`).join(`
|
|
|
371
371
|
|
|
372
372
|
${y}`:`SUCCESS: File [${s}] updated. [${u.length}/${o.length}] blocks applied.
|
|
373
373
|
|
|
374
|
-
${y}`}catch(f){let c=f instanceof Error?f.message:String(f);return`ERROR: Failed to update file [${s}]: ${c}`}};import
|
|
374
|
+
${y}`}catch(f){let c=f instanceof Error?f.message:String(f);return`ERROR: Failed to update file [${s}]: ${c}`}};import ds from"fs";import Ar from"path";var Dl=new Set([".git","node_modules",".gemini","dist","build",".next","out",".cache","bin","obj","vendor","venv",".idea",".gradle",".terraform","target","coverage",".vscode",".svn",".hg",".fslckout",".github",".gitlab",".circleci",".gitea",".gitee",".lerna",".changeset",".nx",".npm",".yarn",".pnpm-store",".expo",".nuxt",".svelte-kit",".docusaurus",".turbo",".vercel","bower_components",".netlify",".vuepress",".quasar",".output",".angular","jspm_packages",".parcel-cache",".rollup.cache",".rspack",".vitepress","__pycache__",".pytest_cache",".mypy_cache",".tox",".poetry","env","vhdl",".ipynb_checkpoints",".jupyter",".conda",".pdm-build",".bundle",".yardoc",".metadata","App_Data","ClientBin",".cargo",".rustc_info",".go","Godeps","_vendor",".rake_tasks","CMakefiles",".wakatime",".dart_tool",".fvm",".cocoapods","Pods",".pub-cache",".symlinks","DerivedData",".xcworkspace",".serverless",".aws",".gcloud",".azure",".kube",".vagrant",".docker","postgres-data","redis-data","mongo-data",".Spotlight-V100",".Trashes","$RECYCLE.BIN","System Volume Information",".DocumentRevisions-V100",".fseventsd","AppData","Application Data","Local","LocalLow","Roaming","$WinREAgent","$WINDOWS.~BT","$WINDOWS.~WS","scw","System32","SysWOW64",".AppleDouble",".AppleDB",".AppleDesktop","_CodeSignature",".cmio",".LSOverride",".localized",".TemporaryItems",".Trash",".Trash-0",".Trash-1000",".gvfs",".local",".config",".dbus",".fontconfig",".snap",".var",".lost+found","lost+found",".thumb",".thumbnails","EFI","boot","grub","logs","log",".nyc_output",".sonar",".ruff_cache",".VSCodeCounter",".skills","skills"]),Fl=e=>Dl.has(e)||e.startsWith(".pnpm"),Nl=e=>{try{let n=String(e.getMonth()+1).padStart(2,"0"),t=String(e.getDate()).padStart(2,"0"),s=String(e.getHours()).padStart(2,"0"),o=String(e.getMinutes()).padStart(2,"0");return`${n}-${t} ${s}:${o}`}catch{return"N/A"}},vr=async e=>{let n=L(e),t=n.path||null;if(!t)return"ERROR: No directory path provided.";let s=1;if(n.recurse!==void 0&&n.recurse!==null)if(typeof n.recurse=="number")s=n.recurse;else if(typeof n.recurse=="boolean")s=n.recurse?2:1;else{let r=parseInt(String(n.recurse).trim(),10);s=isNaN(r)?1:r}s=Math.max(1,Math.min(3,s));let o=Ar.resolve(process.cwd(),t);try{if(!ds.existsSync(o))return`ERROR: Path [${t}] does not exist.`;if(!ds.statSync(o).isDirectory())return`ERROR: Path [${t}] is a file, not a directory. Use ReadFile instead.`;if(s===1){let g=ds.readdirSync(o),y=g.length,m=150,w=g.slice(0,m),x=[];for(let R of w){let S=Ar.join(o,R),T={name:R,type:"unknown",size:"N/A",mtime:"N/A"};try{let E=ds.statSync(S);T={name:R,type:E.isDirectory()?"directory":"file",size:(E.size/1024).toFixed(1)+"KB",mtime:Nl(E.mtime)}}catch{T.type="inaccessible"}x.push(T)}let k=x.map(R=>R.type==="directory"?`${R.name}/`:`${R.name} (${R.size}, ${R.mtime})`).join(`
|
|
375
375
|
`),$=`
|
|
376
376
|
|
|
377
377
|
(Total items in folder: ${y})`;return y>m&&($=`
|
|
378
378
|
|
|
379
379
|
TRUNCATED: Showing first ${m} of ${y} items.`),g.length=0,w.length=0,x.length=0,`Detailed folder stats for [${t}]:
|
|
380
380
|
|
|
381
|
-
${k}${$}`}let a=0,i=0,h=0,f=500,c=!1,l=(g,y,m=1)=>{if(y>s||c)return[];let w=[];try{w=
|
|
381
|
+
${k}${$}`}let a=0,i=0,h=0,f=500,c=!1,l=(g,y,m=1)=>{if(y>s||c)return[];let w=[];try{w=ds.readdirSync(g)}catch{return[`${" ".repeat(m-1)}[Inaccessible Directory]`]}let x=[],k=[];for(let T of w){let E=Ar.join(g,T),_=!1;try{_=ds.statSync(E).isDirectory()}catch{}_?x.push({name:T,fullPath:E}):k.push({name:T,fullPath:E})}x.sort((T,E)=>T.name.localeCompare(E.name)),k.sort((T,E)=>T.name.localeCompare(E.name));let $=[],R=" ".repeat(m-1);for(let T of x){if(h>=f){c=!0,$.push(`${R}[Truncated - Maximum item limit reached (${f})]`);break}if(h++,a++,$.push(`${R}${T.name}/`),y<s&&!Fl(T.name)){let E=l(T.fullPath,y+1,m+1);$.push(...E)}}let S=[];for(let T of k){if(h>=f){c=!0,$.push(`${R}[Truncated - Maximum item limit reached (${f})]`);break}h++,i++;let E="N/A";try{E=(ds.statSync(T.fullPath).size/1024).toFixed(1)+"KB"}catch{}S.push(`${T.name} (${E})`)}return S.length>0&&$.push(`${R}${S.join("; ")}`),$},d=l(o,1,1).join(`
|
|
382
382
|
`),p=`
|
|
383
383
|
|
|
384
384
|
(Total items scanned: ${h}, Directories: ${a}, Files: ${i})`;return c&&(p=`
|
|
385
385
|
|
|
386
386
|
TRUNCATED: Scan capped at ${f} items. (Directories: ${a}, Files: ${i})`),`Detailed directory tree for [${t}] (recursive depth: ${s}):
|
|
387
387
|
|
|
388
|
-
${d}${p}`}catch(r){let a=r instanceof Error?r.message:String(r);return`ERROR: Failed to read folder [${t}]: ${a}`}};var
|
|
388
|
+
${d}${p}`}catch(r){let a=r instanceof Error?r.message:String(r);return`ERROR: Failed to read folder [${t}]: ${a}`}};var Mo=async(e,n)=>{let t=L(e),{question:s}=t;if(!s)return'ERROR: Missing "question" argument for ask.';if(!n.onAskUser)return"ERROR: onAskUser callback not provided in tool context.";let o=[];Object.keys(t).forEach(r=>{if(r.startsWith("option")){let a=t[r];if(typeof a=="string"&&a.includes("::")){let[i,h]=a.split("::");o.push({id:r,label:i.trim(),description:h.trim()})}else o.push({id:r,label:String(a).trim(),description:""})}});try{return`USER CHOOSE: ${await n.onAskUser(s,o)}`}catch(r){return`ERROR: Failed to get user input: ${r instanceof Error?r.message:String(r)}`}};import Bl from"puppeteer";import Os from"path";import us from"fs-extra";import{PDFDocument as Ul}from"pdf-lib";var Ir=async e=>{let{path:n,content:t,orientation:s="portrait",margin:o="0px"}=L(e);if(!n)return'ERROR: Missing "path" argument for write_pdf.';if(!t)return'ERROR: Missing "content" (HTML/CSS) for write_pdf.';let r=Os.resolve(process.cwd(),n),a=null;try{await us.ensureDir(Os.dirname(r)),await ht.recordFileChange(r);let i=cs();a=await Bl.launch({headless:!0,executablePath:i.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let h=await a.newPage(),f=t,c={},l=async S=>{if(!S||S.startsWith("http://")||S.startsWith("https://")||S.startsWith("data:"))return null;try{let T=Os.resolve(process.cwd(),S);if(await us.pathExists(T)){let E=Os.extname(T).toLowerCase().replace(".","")||"png",_=E==="jpg"?"jpeg":E==="svg"?"svg+xml":E,b=await us.readFile(T,"base64");return`data:image/${_};base64,${b}`}}catch{}return null},u=/<link[^>]+href=["']([^"']+)["']/gi,d={},p;for(;(p=u.exec(t))!==null;){let S=p[1],T=p[0];if(S&&T.toLowerCase().includes("stylesheet")&&!S.startsWith("http://")&&!S.startsWith("https://")&&!S.startsWith("data:"))try{let E=Os.resolve(process.cwd(),S);if(await us.pathExists(E)){let _=await us.readFile(E,"utf-8");d[T]=`<style>${_}</style>`}}catch{}}for(let[S,T]of Object.entries(d))f=f.split(S).join(T);let g=/<img[^>]+src=["']([^"']+)["']/gi;for(;(p=g.exec(f))!==null;){let S=p[1];if(S&&!c[S]){let T=await l(S);T&&(c[S]=T)}}let y=/url\(\s*['"]?([^'")]+?)['"]?\s*\)/gi;for(;(p=y.exec(f))!==null;){let S=p[1].trim();if(S&&!c[S]){let T=await l(S);T&&(c[S]=T)}}for(let[S,T]of Object.entries(c)){let E=S.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&"),_=new RegExp(`(src=["'])(${E})(["'])`,"gi");f=f.replace(_,`$1${T}$3`);let b=new RegExp(`url\\(\\s*(['"]?)(${E})\\1\\s*\\)`,"gi");f=f.replace(b,`url($1${T}$1)`)}let m=`
|
|
389
389
|
<style>
|
|
390
390
|
@page {
|
|
391
391
|
margin: ${o};
|
|
@@ -415,7 +415,7 @@ ${d}${p}`}catch(r){let a=r instanceof Error?r.message:String(r);return`ERROR: Fa
|
|
|
415
415
|
</style>
|
|
416
416
|
<div class="watermark">Generated by FluxFlow CLI (AI)</div>
|
|
417
417
|
${f}
|
|
418
|
-
`;await h.setContent(m,{waitUntil:"networkidle0",timeout:18e4});let w=await h.pdf({format:"A4",landscape:String(s).toLowerCase()==="landscape",margin:{top:o,right:o,bottom:o,left:o},printBackground:!0}),x=await Ul.load(w),k=
|
|
418
|
+
`;await h.setContent(m,{waitUntil:"networkidle0",timeout:18e4});let w=await h.pdf({format:"A4",landscape:String(s).toLowerCase()==="landscape",margin:{top:o,right:o,bottom:o,left:o},printBackground:!0}),x=await Ul.load(w),k=Os.basename(n);x.setTitle(`FluxFlow_${k}`),x.setAuthor("FluxFlow CLI"),x.setSubject("Generated with Agentic AI System"),x.setKeywords(["FluxFlow","AI","Agentic","Automated"]),x.setCreator("FluxFlow PDF Engine"),x.setProducer("FluxFlow (Generative AI)");let $=await x.save();await us.writeFile(r,$);let R=await us.stat(r);return`SUCCESS: PDF generated successfully at [${n}] (${(R.size/1024).toFixed(2)} KB).`}catch(i){let h=i instanceof Error?i.message:String(i);return`ERROR: Failed to generate PDF [${n}]: ${h}`}finally{a&&await a.close()}};import ea from"fs-extra";import Or from"path";import Wl from"html-to-docx";var Lr=async e=>{let{path:n,content:t}=L(e);if(!n)return'ERROR: Missing "path" argument for write_docx.';if(!t)return'ERROR: Missing "content" (HTML) for write_docx.';let s=Or.resolve(process.cwd(),n);try{await ea.ensureDir(Or.dirname(s)),await ht.recordFileChange(s);let o=Or.basename(n),r=t.includes("<html")?t:`
|
|
419
419
|
<!DOCTYPE html>
|
|
420
420
|
<html lang="en">
|
|
421
421
|
<head>
|
|
@@ -426,37 +426,37 @@ ${d}${p}`}catch(r){let a=r instanceof Error?r.message:String(r);return`ERROR: Fa
|
|
|
426
426
|
${t}
|
|
427
427
|
</body>
|
|
428
428
|
</html>
|
|
429
|
-
`,a=await Wl(r,null,{title:`FluxFlow_${o}`,creator:"FluxFlow CLI",description:"Generated by Agentic AI System",table:{row:{cantSplit:!0}},footer:!0,pageNumber:!0});return await
|
|
430
|
-
- Size: ${(a.length/1024).toFixed(1)} KB`}catch(o){let r=o instanceof Error?o.message:String(o);return`ERROR: Failed to generate DOCX [${n}]: ${r}`}};import
|
|
429
|
+
`,a=await Wl(r,null,{title:`FluxFlow_${o}`,creator:"FluxFlow CLI",description:"Generated by Agentic AI System",table:{row:{cantSplit:!0}},footer:!0,pageNumber:!0});return await ea.writeFile(s,a),`SUCCESS: Word document [${n}] generated successfully.
|
|
430
|
+
- Size: ${(a.length/1024).toFixed(1)} KB`}catch(o){let r=o instanceof Error?o.message:String(o);return`ERROR: Failed to generate DOCX [${n}]: ${r}`}};import Dr from"fs/promises";import ps from"path";import Pr from"fast-glob";import{Minimatch as ta}from"minimatch";async function Qs(e,n,t=e,s=1){if(s>12)return[];let o=[],r;try{r=await Dr.readdir(e,{withFileTypes:!0})}catch{return[]}for(let a of r){let i=ps.join(e,a.name),h=ps.relative(t,i),f=h.split(ps.sep).map(u=>u.toLowerCase()),c=a.name.toLowerCase();if(!n.some(u=>{let d=u.toLowerCase();return d.startsWith(".")&&c.endsWith(d)?!0:f.some(p=>p===d||p.startsWith(".pnpm"))}))if(a.isDirectory()){let u=await Qs(i,n,t,s+1);o=o.concat(u)}else a.isFile()&&o.push({fullPath:i,relativePath:h})}return o}function jl(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 s=Array.from({length:n.length+1},(o,r)=>r);for(let o=1;o<=e.length;o++){let r=[o],a=o;for(let i=1;i<=n.length;i++){let h=e[o-1]===n[i-1]?0:1,f=Math.min(r[i-1]+1,s[i]+1,s[i-1]+h);r.push(f),f<a&&(a=f)}if(s=r,a>t)return t+1}return s[n.length]}function Hl(e,n){if(!e||!n)return!1;let t=e.toLowerCase(),s=n.toLowerCase();if(t.includes(s))return!0;let o=t.split(/[^a-z0-9]+/).filter(a=>a.length>0),r=s.split(/[^a-z0-9]+/).filter(a=>a.length>1||s.length===1&&a.length>0);return r.length===0?!1:r.every(a=>{let i=a.length<=2?0:a.length<=5?1:2;for(let h of o)if(h.includes(a)||a.length>=3&&h.length>=3&&Math.abs(h.length-a.length)<=i&&jl(a,h,i)<=i)return!0;return!1})}var Zs=async e=>{let{keyword:n,path:t,fuzzy:s,subString:o,regex:r}=L(e);if(n==null)return'ERROR: Missing "keyword" argument.';let a=String(n),i=g=>g===!0||g==="true"||g===1||g==="1"||g==="yes",h=r===!1||r==="false"||r===0||r==="0"||r==="no",f=r===!0||r==="true"||r===1||r==="1"||r==="yes",c=i(s)||i(o),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(f)return`ERROR: Invalid regex pattern "${a}": ${g.message}`}u=new RegExp(`(?<![\\w])${a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\\w])`,"i")}let d=[".git","node_modules",".gemini","dist","build",".next","out",".cache","bin","obj","vendor","venv",".idea",".gradle",".terraform","target","coverage",".vscode",".svn",".hg",".fslckout",".github",".gitlab",".circleci",".gitea",".gitee",".lerna",".changeset",".nx",".npm",".yarn",".pnpm-store",".pnpm",".expo",".nuxt",".svelte-kit",".docusaurus",".turbo",".vercel","bower_components",".netlify",".vuepress",".quasar",".output",".angular","jspm_packages",".parcel-cache",".rollup.cache",".rspack",".vitepress","__pycache__",".pytest_cache",".mypy_cache",".tox",".poetry","env","vhdl",".ipynb_checkpoints",".jupyter",".conda",".pdm-build",".bundle",".yardoc",".metadata","App_Data","ClientBin",".cargo",".rustc_info",".go","Godeps","_vendor",".rake_tasks","CMakefiles",".wakatime",".dart_tool",".fvm",".cocoapods","Pods",".pub-cache",".symlinks","DerivedData",".xcworkspace",".serverless",".aws",".gcloud",".azure",".kube",".vagrant",".docker","postgres-data","redis-data","mongo-data",".Spotlight-V100",".Trashes","$RECYCLE.BIN","System Volume Information",".DocumentRevisions-V100",".fseventsd","AppData","Application Data","Local","LocalLow","Roaming","$WinREAgent","$WINDOWS.~BT","$WINDOWS.~WS","scw","System32","SysWOW64",".AppleDouble",".AppleDB",".AppleDesktop","_CodeSignature",".cmio",".LSOverride",".localized",".TemporaryItems",".Trash",".Trash-0",".Trash-1000",".gvfs",".local",".config",".dbus",".fontconfig",".snap",".var",".lost+found","lost+found",".thumb",".thumbnails","EFI","boot","grub","logs","log",".nyc_output",".sonar",".ruff_cache",".VSCodeCounter",".exe",".dll",".so",".dylib",".png",".jpg",".jpeg",".gif",".ico",".svg",".webp",".mp3",".mp4",".avi",".zip",".tgz",".tar",".gz",".7z",".rar",".pdf",".docx",".xlsx",".pptx",".woff",".woff2",".ttf",".eot",".skills","skills"],p=150;try{let g=[],y=process.cwd(),m=null;if(t){let A=t.split(";").map(W=>W.trim()).filter(Boolean),O=A.some(W=>W.startsWith("!"));if(A.some(W=>Pr.isDynamicPattern(W)||/[*?{}[\]()|+]/.test(W))){m="glob";let W=t.replace(/\\/g,"/"),q=A.map(F=>F.replace(/\\/g,"/")),se=d.map(F=>F.startsWith(".")?`**/*${F}`:`**/${F}/**`);if(O&&!A.some(F=>!F.startsWith("!"))){let F=await Qs(y,d,y),B=v=>v.endsWith("/")?v+"**":v,Z=q.filter(v=>v.startsWith("!")).map(v=>B(v.slice(1))),Ce=q.filter(v=>!v.startsWith("!")).map(B);g=F.filter(v=>{let U=v.relativePath.replace(/\\/g,"/"),X=Ce.length===0||Ce.some(Ue=>{try{return new ta(Ue).match(U)}catch{return!1}}),ee=Z.some(Ue=>{try{return new ta(Ue).match(U)}catch{return!1}});return X&&!ee})}else{let F=q.some(Z=>/[\(\)\|]|\.\*/.test(Z)),B=[];if(!F)try{B=await Pr(q,{cwd:y,ignore:se,dot:!0,onlyFiles:!0,absolute:!1})}catch{B=[]}if(B.length===0&&(F||Pr.isDynamicPattern(W))){let Z=W.match(/^([^\*\?\(\)\|\[\]\s]+)\//),Ce=Z&&!/[\*\?\(\)\|\[\]]/.test(Z[1])?ps.resolve(y,Z[1]):y,v=await Qs(Ce,d,y);try{let U=W.replace(/^\.\//,"");U=U.replace(/\.\*\/(\\.|[^\/])/g,".*$1"),!U.startsWith("^")&&!U.startsWith(".*")&&(U=`.*${U}`);let X=new RegExp(U.endsWith("$")?U:`${U}$`,"i");g=v.filter(ee=>{let Ue=ee.relativePath.replace(/\\/g,"/");return X.test(Ue)})}catch{g=[]}}else g=B.map(Z=>({fullPath:ps.resolve(y,Z),relativePath:Z}))}}else{let W=t.replace(/[\/\\]+$/,""),q=ps.resolve(y,W);try{let se=await Dr.stat(q);if(se.isDirectory())m="dir",g=await Qs(q,d,y);else if(se.isFile())m="file",g.push({fullPath:q,relativePath:ps.relative(y,q)});else return`ERROR: Path is neither a file nor a directory: ${t}`}catch{return`ERROR: Path not found: ${t}`}}}else g=await Qs(y,d);let w=g.map(async A=>{try{let O=await Dr.readFile(A.fullPath,"utf-8");if(O.includes("\0"))return[];let D=O.split(/\r?\n/),W=[];for(let se=0;se<D.length;se++)(c?D[se].toLowerCase().includes(a.toLowerCase())||Hl(D[se],a):h?u&&u.test(D[se]):l&&l.test(D[se])||u&&u.test(D[se]))&&W.push({line:se+1,content:D[se].trim()});return W.length===0?null:{path:A.relativePath.replace(/\\/g,"/"),matches:W}}catch{return[]}}),x=await Promise.all(w),k=[],$=0;for(let A of x){if(!A||!A.matches)continue;if($>=p)break;let O=p-$,D=A.matches.slice(0,O);k.push({path:A.path,matches:D}),$+=D.length}typeof global.gc=="function"&&global.gc();let R=c?"(fuzzy mode)":f?"(regex mode)":h?"(keyword mode)":"(standard mode)";if(k.length===0){let A=m==="file"?` in '${t}'`:m==="dir"||m==="glob"?` in '${t}'`:". Try to specify files",O=m==="dir"?"[DIR]":m==="glob"?"[GLOB]":"";return`${O}${O?" ":""}Found 0 matches of '${a}'${A}${R?` ${R}`:""}`}let S=R?` ${R}`:"",T=`${k.length} file${k.length===1?"":"s"}`,E=`${$} match${$===1?"":"es"}`,_;m==="file"?_=`Found ${E} of '${a}' in '${t}'${S}:`:m==="dir"||m==="glob"?_=`Found ${E} of '${a}' in '${t}' across ${T}${S}:`:_=`Found ${E} of '${a}' across ${T}${S}:`;let b=m==="dir"?"[DIR]":m==="glob"?"[GLOB]":"",C=`${b}${b?" ":""}${_}
|
|
431
431
|
|
|
432
432
|
`;for(let A of k){C+=`${A.path}
|
|
433
433
|
`;for(let O of A.matches)C+=` ${O.line}: ${O.content}
|
|
434
434
|
`;C+=`
|
|
435
|
-
`}return C.trimEnd()}catch(g){return`ERROR: ${g.message}`}};import
|
|
435
|
+
`}return C.trimEnd()}catch(g){return`ERROR: ${g.message}`}};import na from"fs-extra";import Fr from"path";var Gl=(e,n={})=>{try{if(e.length<8||e[0]!==137||e[1]!==80||e[2]!==78||e[3]!==71)return e;let t=[],s=[];for(let a=0;a<256;a++){let i=a;for(let h=0;h<8;h++)i&1?i=3988292384^i>>>1:i=i>>>1;s[a]=i}let o=a=>{let i=4294967295;for(let h=0;h<a.length;h++)i=s[(i^a[h])&255]^i>>>8;return(i^4294967295)>>>0},r=(a,i)=>{let h=Buffer.from(a,"ascii"),f=Buffer.from(i,"utf-8"),c=h.length+1+f.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,f.copy(l,8+h.length+1);let u=o(l.subarray(4,8+c));return l.writeUInt32BE(u,8+c),l};for(let[a,i]of Object.entries(n))i!=null&&t.push(r(a,String(i)));if(t.length===0)return e;if(e.subarray(12,16).toString("ascii")==="IHDR"){let i=e.subarray(0,33),h=e.subarray(33);return Buffer.concat([i,...t,h])}return e}catch{return e}},Nr=async(e,n={})=>{let t=L(e),s=t.prompt||t.text,o=t.path||t.outputPath||t.output||"generated_image.png",r=t.ratio;if(!s)return'ERROR: Missing "prompt" argument for generate_image.';let a=["nsfw","naked","nudity","nude","porn","sex","xxx","erotic","gore","bloody","violence","abuse","suicide","murder","hentai","pedophile","rape"],i=s.toLowerCase();if(a.some(f=>i.includes(f)))return"ERROR: Prompt blocked by system safety filter (inappropriate or unsafe content detected).";try{let f=await en();if(!await $i(f))return`ERROR: Insufficient Quota for selected quality. Either tell user reduce quality or wait for next refresh cycle (${(await Ci()).nextResetMin||60}m).`;let l=f.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(r){let O=r.replace(/\s+/g,"");O==="16:9"?(g=1024,y=576):O==="9:16"?(g=576,y=1024):O==="4:3"?(g=1024,y=768):O==="3:4"?(g=768,y=1024):O==="1:1"&&(g=1024,y=1024)}let m=Math.floor(Math.random()*1e7),x=`https://gen.pollinations.ai/image/${encodeURIComponent(s)}?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(x,{method:"GET",headers:{Authorization:`Bearer ${u}`}});if(!k.ok){let O=k.status,D="";try{D=await k.text()}catch{}return O===402||D.includes("Insufficient balance")||D.includes("PAYMENT_REQUIRED")?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed with status [${O}]: ${D||"Unknown API Error"}`}if((k.headers.get("content-type")||"").includes("application/json")){let O=await k.json();return O.status===402||O.error&&O.error.code==="PAYMENT_REQUIRED"?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed: ${O.error?.message||JSON.stringify(O)}`}let R=await k.arrayBuffer(),S=Buffer.from(R),T={Title:s,Description:"Generated via FluxFlow CLI",Software:"FluxFlow CLI",Author:"FluxFlow","Creation Time":new Date().toISOString(),Prompt:s,Model:`Fluxflow:${p}`,Ratio:r||"1:1",Seed:String(m)};S=Gl(S,T);let E=Fr.resolve(process.cwd(),o);await na.ensureDir(Fr.dirname(E)),await ht.recordFileChange(E),await na.writeFile(E,S),await Mi(f);let _=Fr.extname(o).toLowerCase(),C={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".webp":"image/webp"}[_]||"image/png";return n.isMultiModal!==!1?{text:`SUCCESS: Image successfully generated from prompt [${s}] and saved to [${o}]. Output attached to multimodal part`,binaryPart:{inlineData:{data:S.toString("base64"),mimeType:C}}}:`SUCCESS: Image successfully generated from prompt [${s}] and saved to [${o}].`}catch(f){return`ERROR: Failed during image generation: ${f instanceof Error?f.message:String(f)}`}};var eo=async(e,n={})=>{let t=r=>{let a=new RegExp(`${r}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),i=e.match(a);return i?i[2].trim():null},s=t("id"),o=t("summary");if(!s||!o)return"ERROR: Missing 'id' or 'summary' for saveSummary tool.";try{let r=ne(Zt,{}),a=ne(In,{});return a[s]=o,delete r[s],he(In,a),he(Zt,r),`SUCCESS: Saved summary and purged raw memories for chat [${s}].`}catch(r){let a=r instanceof Error?r.message:String(r);return`ERROR: Failed to save summary for chat [${s}]: ${a}`}};var Ls=async(e,n={})=>{let s=(o=>{let r=new RegExp(`${o}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),a=e.match(r);return a?a[2].trim():null})("id");if(!s)return"ERROR: Missing 'id' parameter for addMemScore tool.";try{let o=ne(Dt,[]),r=!1,a=[];for(let c of o)c.score===void 0&&(c.score=.5),c.id===s?(c.score=Math.min(2,c.score+.2),r=!0):(c.score*=.98,c.score<.05&&(c.score=0)),c.score=Math.round(c.score*1e5)/1e5,c.score>0&&a.push(c);if(he(Dt,a),!r)return`WARNING: Memory ID [${s}] not found. Other memories decayed by -0.01.`;let i=a.find(c=>c.id===s),h=i?i.score.toFixed(2):"deleted (score <= 0)",f=o.length-a.length;return`SUCCESS: Adjusted memory scores. Target [${s}] is now ${h}.${f>0?` Purged ${f} decayed memories.`:""}`}catch(o){let r=o instanceof Error?o.message:String(o);return`ERROR: Failed to adjust memory score for [${s}]: ${r}`}};import Ur from"fs-extra";import ms from"path";import{createRequire as Kl}from"module";import hs from"fs-extra";import Br from"path";import ql from"https";var sa={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 zl(e,n=null){let t=n||`https://unpkg.com/tree-sitter-wasms@0.1.13/out/${e}`,s=Br.join(as,e);return await hs.ensureDir(as),new Promise((o,r)=>{let a={headers:{"User-Agent":"FluxFlow-Agent"}};ql.get(t,a,i=>{if([301,302,307,308].includes(i.statusCode)&&i.headers.location){let f=i.headers.location;if(!f.startsWith("http")){let c=new URL(t);f=`${c.protocol}//${c.host}${f}`}zl(e,f).then(o).catch(r);return}if(i.statusCode!==200){r(new Error(`Failed to download ${e}: HTTP ${i.statusCode}`));return}let h=hs.createWriteStream(s);i.pipe(h),h.on("finish",()=>{h.close(),o()})}).on("error",i=>{hs.existsSync(s)&&hs.unlink(s,()=>{}),r(i)})})}function Tu(e){let n=Br.join(as,e);return hs.existsSync(n)}async function Ru(e){let n=Br.join(as,e);hs.existsSync(n)&&await hs.unlink(n)}var ia=Kl(import.meta.url),oa=ia("web-tree-sitter"),ra=!1,aa=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"]),la=new Set(["export_statement","lexical_declaration","variable_declaration","variable_declarator","pair","assignment_expression"]);function wn(e,n=50){if(!e)return"";let t=e.replace(/\s+/g," ").trim();return t.length>n?t.substring(0,n-3)+"...":t}function ca(e){let n=e.type;if(n==="if_statement"){let s=e.childForFieldName("condition");return s?`if (${wn(s.text,40)})`:"if"}if(n==="else_clause")return"else";if(n==="while_statement"||n==="do_statement"){let s=e.childForFieldName("condition");return`${n.split("_")[0]} (${s?wn(s.text,40):""})`}if(n==="for_statement"||n==="for_in_statement"||n==="for_of_statement"){let o=e.text.split(`
|
|
436
436
|
`)[0].match(/for\s*(?:await\s*)?\((.*)\)/);return o?`for (${wn(o[1],40)})`:"for"}if(n==="switch_statement"){let s=e.childForFieldName("value");return`switch (${s?wn(s.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 s=e.childForFieldName("opening_element")||e.childForFieldName("start_tag")||e.children.find(r=>r.type==="start_tag")||e,o=s.childForFieldName("name")||s.childForFieldName("tag_name")||s.children.find(r=>r.type==="tag_name");return o?`<${wn(o.text,30)}>`:null}if(["import_declaration","import_from_statement","import_statement","preproc_include"].includes(n))return wn(e.text.split(`
|
|
437
|
-
`)[0],60);if(n==="pair"){let s=e.childForFieldName("key");return s?wn(s.text.replace(/["']/g,""),40):null}if(n==="assignment_expression"){let s=e.childForFieldName("left");return s?`${wn(s.text,30)} = ...`:null}if(n==="variable_declarator"){let s=e.childForFieldName("name")||e.children.find(o=>["identifier","object_pattern","array_pattern"].includes(o.type));return s?wn(s.text,40):null}let t=e.childForFieldName("name")||e.childForFieldName("declarator")||e.children.find(s=>["identifier","type_identifier","field_identifier","property_identifier","shorthand_property_identifier"].includes(s.type));if(t){if(t.type.includes("declarator")){let s=t.descendantsOfType("identifier")[0]||t.descendantsOfType("field_identifier")[0];if(s)return wn(s.text,40)}return wn(t.text,40)}if(["arrow_function","function_expression","function_declaration"].includes(n)){let s=e.parent;for(;s&&s.type!=="program";){let o=
|
|
437
|
+
`)[0],60);if(n==="pair"){let s=e.childForFieldName("key");return s?wn(s.text.replace(/["']/g,""),40):null}if(n==="assignment_expression"){let s=e.childForFieldName("left");return s?`${wn(s.text,30)} = ...`:null}if(n==="variable_declarator"){let s=e.childForFieldName("name")||e.children.find(o=>["identifier","object_pattern","array_pattern"].includes(o.type));return s?wn(s.text,40):null}let t=e.childForFieldName("name")||e.childForFieldName("declarator")||e.children.find(s=>["identifier","type_identifier","field_identifier","property_identifier","shorthand_property_identifier"].includes(s.type));if(t){if(t.type.includes("declarator")){let s=t.descendantsOfType("identifier")[0]||t.descendantsOfType("field_identifier")[0];if(s)return wn(s.text,40)}return wn(t.text,40)}if(["arrow_function","function_expression","function_declaration"].includes(n)){let s=e.parent;for(;s&&s.type!=="program";){let o=ca(s);if(o)return o;if(!la.has(s.type))break;s=s.parent}}return null}function Yl(e){let n=[];function t(s){for(let o of s.children)aa.has(o.type)?n.push(o):t(o)}return t(e),n}function Vl(e){return e.replace(/_([a-z])/g,n=>n[1].toUpperCase())}function fa(e,n=0,t=!0,s="",o=null,r=12){let a=e.type,i=ca(e),h=aa.has(a)||n===0,f=Yl(e),c=h&&n>0&&(la.has(a)&&f.length>0||i!==null&&i===o&&f.length>0),l="",u=s,d=n,p=o;if(h&&!c){let g=e.startPosition.row+1,y=e.endPosition.row+1,m=Vl(a),w=i?`${m} [${i}]`:m;n===0?(l+=`\u{1F4C1} ROOT (Lines: ${g}-${y})
|
|
438
438
|
`,u=s):(l+=`${s}${t?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 "}${w} (Lines: ${g}-${y})
|
|
439
439
|
`,u+=t?" ":"\u2502 "),d=n+1,p=i}return d>r&&f.length>0?l+=`${u}\u2514\u2500\u2500 ... depth exceeded ...
|
|
440
|
-
`:f.forEach((g,y)=>{let m=y===f.length-1;l+=
|
|
441
|
-
`).length,l=12;c>1e4?l=2:c>=8e3?l=3:c>=5e3?l=5:c>=4e3?l=8:c>2e3&&(l=10);let u=i.parse(f),d=
|
|
440
|
+
`:f.forEach((g,y)=>{let m=y===f.length-1;l+=fa(g,d,c?t&&m:m,u,p,r)}),l}var Wr=async e=>{let n;try{n=L(e).path}catch{return`ERROR: Failed to parse arguments: ${e}`}if(!n)return'ERROR: No file path provided. Use [tool:functions.FileMap(path="...")]';let t=ms.isAbsolute(n)?n:ms.resolve(process.cwd(),n);if(!Ur.existsSync(t))return`ERROR: File not found: ${n}`;let s=ms.extname(t).slice(1).toLowerCase(),o=sa[s];if(!o)return`ERROR: Unsupported file extension: .${s}`;let r=ms.resolve(as,o);if(!Ur.existsSync(r))return`ERROR: Parser for .${s} not found. Please download it in Settings > Other.`;try{let a=oa.Parser;if(!ra){let p;try{p=ms.join(ms.dirname(ia.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}),ra=!0}let i=new a,h=await oa.Language.load(r);i.setLanguage(h);let f=await Ur.readFile(t,"utf8"),c=f.split(`
|
|
441
|
+
`).length,l=12;c>1e4?l=2:c>=8e3?l=3:c>=5e3?l=5:c>=4e3?l=8:c>2e3&&(l=10);let u=i.parse(f),d=fa(u.rootNode,0,!0," ",null,l);return`\u{1F4C4} File Map for: ${n}
|
|
442
442
|
${d}`}catch(a){let i=a instanceof Error?a.message:typeof a=="object"?JSON.stringify(a):String(a),h=a instanceof Error?`
|
|
443
|
-
Stack: ${a.stack}`:"";return`ERROR: Failed to map file: ${i}${h}`}};import
|
|
443
|
+
Stack: ${a.stack}`:"";return`ERROR: Failed to map file: ${i}${h}`}};import zn from"fs";import da from"path";var to=async(e,n={})=>{let{method:t,tasks:s,markDone:o}=L(e),r=n.chatId||"default";if(!t)return'ERROR: Missing "method" argument for todo tool (create/append/get).';let a=da.join(vn,"plan",r),i=da.join(a,"todo.md"),h=l=>{if(!l||Array.isArray(l))return l;let u=String(l).trim();if(u.startsWith("[")&&u.endsWith("]")){let d=u.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);return d?d.map(p=>p.slice(1,-1).replace(/\\(.)/g,"$1")):u.slice(1,-1).split(",").map(p=>p.trim()).filter(Boolean)}return l},f=l=>{let u=h(l);return u?(Array.isArray(u)?u:String(u).split(`
|
|
444
444
|
`)).map(p=>{let g=String(p).trim();return g?g.startsWith("- [ ]")||g.startsWith("- [x]")||g.startsWith("- [X]")?g:`- [ ] ${g}`:null}).filter(Boolean).join(`
|
|
445
445
|
`)+`
|
|
446
446
|
`:""},c=(l,u)=>{if(!u)return{content:l,markedCount:0};let d=h(u),p=(Array.isArray(d)?d:[d]).map(w=>String(w).replace(/^- \[[xX ]\]\s*/i,"").trim()).filter(Boolean),g=l.split(`
|
|
447
447
|
`),y=0,m=!1;for(let w of p){let x=!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]"),x=!0,m=!0,y++;break}if(!x){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]"),x=!0,m=!0,y++;break}}}return{content:m?g.join(`
|
|
448
|
-
`):l,markedCount:y}};try{if(
|
|
448
|
+
`):l,markedCount:y}};try{if(zn.existsSync(a)||zn.mkdirSync(a,{recursive:!0}),t==="create"){if(!s)return'ERROR: Missing "tasks" for create method.';let l=f(s),u=0;if(o){let p=c(l,o);l=p.content,u=p.markedCount}await ht.recordFileChange(i),zn.writeFileSync(i,l,"utf8");let d=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, ${d-p} left)
|
|
449
449
|
${l}`}return`SUCCESS: TASK LIST CREATED (${d} total)
|
|
450
|
-
${l}`}if(t==="append"){if(!s)return'ERROR: Missing "tasks" for append method.';let l=f(s);await ht.recordFileChange(i),
|
|
451
|
-
${u}`}if(t==="get"){if(!
|
|
452
|
-
${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
|
|
453
|
-
`),f}catch(f){let{isTerminationSignaled:c}=await import("./ai-
|
|
454
|
-
`)}return`ERROR: Subagent execution failed: ${f.message}`}};var
|
|
450
|
+
${l}`}if(t==="append"){if(!s)return'ERROR: Missing "tasks" for append method.';let l=f(s);await ht.recordFileChange(i),zn.appendFileSync(i,l,"utf8");let u=zn.readFileSync(i,"utf8"),d=u.split(/\r?\n/).map(m=>m.trim()),p=d.filter(m=>m.startsWith("- [ ]")||m.startsWith("- [x]")||m.startsWith("- [X]")).length,g=d.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)
|
|
451
|
+
${u}`}if(t==="get"){if(!zn.existsSync(i))return"TODO GET: No task list found for this session.";let l=zn.readFileSync(i,"utf8"),u=0;if(o){let m=c(l,o);m.markedCount>0&&(l=m.content,u=m.markedCount,await ht.recordFileChange(i),zn.writeFileSync(i,l,"utf8"))}let d=l.split(/\r?\n/).map(m=>m.trim()),p=d.filter(m=>m.startsWith("- [ ]")||m.startsWith("- [x]")||m.startsWith("- [X]")).length,g=d.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
|
|
452
|
+
${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 jr=async(e,n={})=>{let{runSubagent:t}=await import("./ai-KC4TYCZG.js"),s=L(e),o=s.task||s.instruction||s.prompt,r=s.model||null,a=s.tools||null;if(!o)return'ERROR: Missing "task" argument for invokeSync.';let i=null;if(a)try{let f=a.trim();f.startsWith("[")&&f.endsWith("]")&&(f=f.substring(1,f.length-1)),i=f.split(",").map(c=>c.trim().replace(/^["']|["']$/g,"")).filter(Boolean)}catch{}let h=s.title||o.substring(0,30);try{n.onVisualFeedback&&n.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${h}`);let f=await t(o,n,r,i,50);return n.onVisualFeedback&&n.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${h} [COMPLETED]
|
|
453
|
+
`),f}catch(f){let{isTerminationSignaled:c}=await import("./ai-KC4TYCZG.js"),l=f.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}
|
|
454
|
+
`)}return`ERROR: Subagent execution failed: ${f.message}`}};var ua=async(e,n={})=>{let{runSubagent:t}=await import("./ai-KC4TYCZG.js"),s=L(e),o=s.task||s.instruction||s.prompt,r=s.model||null,a=s.title||null,i=s.tools||null;if(!o)return'ERROR: Missing "task" argument for invoke.';let h=null;if(i)try{let m=i.trim();m.startsWith("[")&&m.endsWith("]")&&(m=m.substring(1,m.length-1)),h=m.split(",").map(w=>w.trim().replace(/^["']|["']$/g,"")).filter(Boolean)}catch{}let f=`subagent-${Date.now()}-${Math.floor(Math.random()*1e3)}`,c=null,l=null,u=new Promise((m,w)=>{c=m,l=w}),d={id:f,title:a||o.substring(0,30),task:o,status:"running",startedAt:Date.now(),lastChunkTime:Date.now(),wps:0,questions:[],pendingSteerMessages:[],steer:m=>{m&&d.pendingSteerMessages.push(m)},completionPromise:u,_resolveCompletion:c,_rejectCompletion:l,progress:[]},p={chunks:[],totalWords:0};Ve.push(d),n.onSubagentUpdate&&n.onSubagentUpdate();let g=[],y={...n,taskId:f,onAskMain:async m=>{let w=`q-${Date.now()}-${Math.floor(Math.random()*1e3)}`,x=null,k=new Promise(S=>{x=S}),$={id:w,question:m,answered:!1,answer:null,askedAt:Date.now(),_resolve:x};return d.questions.push($),d.status="waiting",n.onSubagentUpdate&&n.onSubagentUpdate(),xo(`[SYSTEM] Background subagent "${d.title}" is WAITING FOR YOUR INPUT: "${m}"
|
|
455
455
|
Respond using tool: [tool:functions.Answer(id="${f}", answer="...")]
|
|
456
456
|
[/SYSTEM]`),await k},onVisualFeedback:m=>{d.lastChunkTime=Date.now();let w=m.replace(/\x1b\[[0-9;]*m/g,""),x=w.match(/[✔✘✗✖🔍📖→➕↻•]\s*([A-Za-z0-9\s-]+)/);x?d.currentTool=x[1].trim():d.currentTool=w,n.onSubagentUpdate&&n.onSubagentUpdate()},onTokenChunk:(m,w)=>{let x=Date.now();if(d.lastChunkTime=x,d.currentTool="Thinking",typeof w=="number"&&w>0){p.totalWords+=w,p.chunks.push({time:x,words:w});let k=x-400;if(p.chunks=p.chunks.filter($=>$.time>=k),p.chunks.length>0){let $=p.chunks.reduce((T,E)=>T+E.words,0),R=p.chunks[0].time,S=Math.max(.4,(x-R)/1e3);d.wps=Math.round($/S*10)/10}}n.onSubagentUpdate&&n.onSubagentUpdate()}};return t(o,y,r,h,50,m=>{if(d.status==="cancelled")return;if(m.startsWith("[Subagent Turn")&&g.length>0&&(d.progress.push([...g]),g=[]),m.includes("[Executing Tool]")){let x=m.match(/\[Executing Tool\]\s*([a-zA-Z0-9_]+)/);x&&(!d.currentTool||d.currentTool==="Thinking")&&(d.currentTool=x[1])}let w=m;if(w.startsWith("[Tool Result]")){let x=w.split(`
|
|
457
457
|
`);x.length>5&&(w=x.slice(0,4).join(`
|
|
458
458
|
`)+`
|
|
459
|
-
... [Content/Diff Truncated from Logs] ...`)}g.push(w),n.onSubagentUpdate&&n.onSubagentUpdate()},!0).then(m=>{if(d.status==="cancelled"){d._resolveCompletion&&d._resolveCompletion(m);return}g.length>0&&(d.progress.push([...g]),g=[]),d.status="completed",d.finalAnswer=m,n.onSubagentUpdate&&n.onSubagentUpdate(),xo(`[SYSTEM] Background subagent "${d.title}" (id: ${f}) has FINISHED. Call GetProgress(id="${f}") to see the final result. [/SYSTEM]`),d._resolveCompletion&&d._resolveCompletion(m)}).catch(async m=>{let{isTerminationSignaled:w}=await import("./ai-
|
|
459
|
+
... [Content/Diff Truncated from Logs] ...`)}g.push(w),n.onSubagentUpdate&&n.onSubagentUpdate()},!0).then(m=>{if(d.status==="cancelled"){d._resolveCompletion&&d._resolveCompletion(m);return}g.length>0&&(d.progress.push([...g]),g=[]),d.status="completed",d.finalAnswer=m,n.onSubagentUpdate&&n.onSubagentUpdate(),xo(`[SYSTEM] Background subagent "${d.title}" (id: ${f}) has FINISHED. Call GetProgress(id="${f}") to see the final result. [/SYSTEM]`),d._resolveCompletion&&d._resolveCompletion(m)}).catch(async m=>{let{isTerminationSignaled:w}=await import("./ai-KC4TYCZG.js");if(m.message==="Subagent task was cancelled."||d.status==="cancelled"||w()){d.status="cancelled",g.push("[SUBAGENT CANCELLED] Task was cancelled."),d.progress.push([...g]),n.onSubagentUpdate&&n.onSubagentUpdate(),d._resolveCompletion&&d._resolveCompletion(null);return}g.push(`[SUBAGENT FAILURE] Error: ${m.message}`),d.progress.push([...g]),d.status="failed",d.error=m.message,n.onSubagentUpdate&&n.onSubagentUpdate(),xo(`[SYSTEM] Background subagent "${d.title}" (id: ${f}) FAILED with error: ${m.message}. [/SYSTEM]`),d._rejectCompletion&&d._rejectCompletion(m)}),`SUCCESS: Background subagent started. Task ID: ${f}`};var Hr=async(e,n={})=>{let s=L(e).id;if(!s)return'ERROR: Missing "id" argument for getProgress.';let o=Ve.find(i=>i.id===s);if(!o)return`ERROR: Subagent task with ID [${s}] not found.`;let r=`Subagent Task Status: ${o.status.toUpperCase()}
|
|
460
460
|
`;if(r+=`Title: ${o.title}
|
|
461
461
|
`,r+=`Task: ${o.task}
|
|
462
462
|
`,o.startedAt){let i=Math.floor((Date.now()-o.startedAt)/1e3);r+=`Elapsed Time: ${i}s
|
|
@@ -481,7 +481,7 @@ ${o.finalAnswer}
|
|
|
481
481
|
`),r.replace(/\r\n/g,`
|
|
482
482
|
`).replace(/\n{3,}/g,`
|
|
483
483
|
|
|
484
|
-
`).trim().replace(/\[TOOL RESULT\]/gi,"TOOL RESULT:")};var
|
|
484
|
+
`).trim().replace(/\[TOOL RESULT\]/gi,"TOOL RESULT:")};var pa=async(e,n={})=>{let s=L(e).id;if(!s)return'ERROR: Missing "id" argument for cancel.';let o=Ve.find(r=>r.id===s);return o?o.status==="completed"||o.status==="failed"?`INFO: Subagent task with ID [${s}] has already finished with status [${o.status.toUpperCase()}].`:o.status==="cancelled"?`INFO: Subagent task with ID [${s}] is already cancelled.`:(o.status="cancelled",n.onSubagentUpdate&&n.onSubagentUpdate(),`SUCCESS: Subagent task with ID [${s}] has been cancelled.`):`ERROR: Subagent task with ID [${s}] not found.`};import xt from"fs-extra";import Tt from"path";var Xl=["node_modules","dist","bin","logs",".git",".fluxflow","secret",".gemini",".agents","tmp","temp","build","out","snapshots"];async function no(e,n=e){let t={},s=await xt.readdir(e,{withFileTypes:!0}).catch(()=>[]);for(let o of s){if(Xl.includes(o.name))continue;let r=Tt.join(e,o.name),a=Tt.relative(n,r).replace(/\\/g,"/");if(o.isDirectory()){let i=await no(r,n);Object.assign(t,i)}else{let i=await xt.stat(r).catch(()=>null);i&&(t[a]={size:i.size,mtime:i.mtimeMs})}}return t}async function ha(e,n){await xt.ensureDir(e);for(let t of Object.keys(n)){let s=Tt.join(process.cwd(),t),o=Tt.join(e,t);await xt.ensureDir(Tt.dirname(o)),await xt.copyFile(s,o).catch(()=>{})}}async function Gr(e,n,t=null,s=null){if(!await xt.pathExists(e))return;s||(s=e);let o=await xt.readdir(e,{withFileTypes:!0}).catch(()=>[]);for(let r of o){let a=Tt.join(e,r.name),i=Tt.join(n,r.name);if(r.isDirectory())await Gr(a,i,t,s);else{let h=Tt.relative(s,a).replace(/\\/g,"/"),f=await xt.pathExists(i);f&&await xt.chmod(i,438).catch(()=>{}),await xt.ensureDir(Tt.dirname(i));let c=await xt.copyFile(a,i).then(()=>!0).catch(()=>!1);await xt.chmod(i,438).catch(()=>{}),t&&(c?f?t.replaced++:t.restored++:t.failed.push(h))}}}var Kn={async takeInitialSnapshot(e){try{let n=Tt.join(vn,"snapshots",e);await xt.remove(n).catch(()=>{}),await xt.ensureDir(n);let t=await no(process.cwd());await ha(Tt.join(n,"initial"),t);let s=ne(mn,{});s[e]={initialManifest:t,currentManifest:t,checkpoints:[{id:"initial",timestamp:new Date().toISOString(),newFiles:[],modifiedFiles:[],deletedFiles:[],toolsUsed:[]}]},he(mn,s)}catch{}},async recordTurnDelta(e,n,t=[]){try{let s=ne(mn,{}),o=s[e];if(!o)return;let r=o.currentManifest||o.initialManifest,a=await no(process.cwd()),i=[],h=[],f=[];for(let[l,u]of Object.entries(a)){let d=r[l];d?(d.size!==u.size||d.mtime!==u.mtime)&&h.push(l):i.push(l)}for(let l of Object.keys(r))a[l]||f.push(l);let c=[...i,...h];if(c.length>0||f.length>0){let l={};for(let d of c)l[d]=a[d];let u=Tt.join(vn,"snapshots",e,`turn_${n}`);await ha(u,l)}o.checkpoints.push({id:`turn_${n}`,timestamp:new Date().toISOString(),newFiles:i,modifiedFiles:h,deletedFiles:f,toolsUsed:t}),o.currentManifest=a,he(mn,s)}catch{}},async getCheckpoints(e){try{let t=ne(mn,{})[e];return t?t.checkpoints||[]:[]}catch{return[]}},async rollbackToCheckpoint(e,n){try{let t=ne(mn,{}),s=t[e];if(!s)throw new Error("No session active for Advance Rollback.");let o=s.checkpoints||[],r=o.findIndex(c=>c.id===n);if(r===-1)throw new Error(`Checkpoint [${n}] not found.`);let a=Tt.join(vn,"snapshots",e),i={restored:0,replaced:0,failed:[]},h=await no(process.cwd());for(let c of Object.keys(h)){let l=Tt.join(process.cwd(),c);await xt.chmod(l,438).catch(()=>{}),await xt.remove(l).catch(()=>{})}let f=Tt.join(a,"initial");await Gr(f,process.cwd(),i,f);for(let c=1;c<=r;c++){let l=o[c],u=Tt.join(a,l.id);if(await Gr(u,process.cwd(),i,u),l.deletedFiles&&l.deletedFiles.length>0)for(let d of l.deletedFiles){let p=Tt.join(process.cwd(),d);await xt.chmod(p,438).catch(()=>{}),await xt.remove(p).catch(()=>{})}}return s.checkpoints=o.slice(0,r+1),s.currentManifest=await no(process.cwd()),he(mn,t),{checkpointId:n,stats:i}}catch(t){throw new Error(`Rollback failed: ${t.message}`)}},async getLatestFileChanges(e){try{let t=ne(mn,{})[e];if(!t||!t.checkpoints||t.checkpoints.length===0)return{newFiles:[],modifiedFiles:[],deletedFiles:[]};let s=t.checkpoints[t.checkpoints.length-1];return{newFiles:s.newFiles||[],modifiedFiles:s.modifiedFiles||[],deletedFiles:s.deletedFiles||[]}}catch{return{newFiles:[],modifiedFiles:[],deletedFiles:[]}}},async cleanup(e){try{let n=Tt.join(vn,"snapshots",e);await xt.remove(n).catch(()=>{});let t=ne(mn,{});t[e]&&(delete t[e],he(mn,t))}catch{}}};var qr=async(e,n={})=>{let t=L(e),s=t.method,o=t.id,r=n.chatId;if(!n.systemSettings?.advanceRollback)return"ERROR: Advance Rollback feature is currently disabled in settings under Security. Tell user to enable it.";if(!r)return"ERROR: No active chat transaction found for rollback.";if(s==="getCheckpoint"){let i=await Kn.getCheckpoints(r);if(i.length===0)return"No checkpoints available.";let h={write_file:"WriteFile",update_file:"PatchFile",view_file:"ReadFile",read_folder:"ReadFolder",exec_command:"Run",web_search:"WebSearch",web_scrape:"WebScrape",search_keyword:"SearchKeyword",CodeSearch:"SearchKeyword",code_search:"SearchKeyword",write_pdf:"WritePDF",write_docx:"WriteDoc",generate_image:"GenerateImage",file_map:"FileMap",todo:"Todo",goal:"Goal",Goal:"Goal",await:"Await",ask:"AskUser",ask_user:"AskUser",AskUser:"AskUser",askuser:"AskUser",invoke:"Invoke",invokesync:"InvokeSync",getprogress:"GetProgress",cancel:"Cancel",emergency_rollback:"EmergencyRollback",emergencyrollback:"EmergencyRollback"},f=l=>h[l]||h[l.toLowerCase()]||l,c=`Available checkpoints for rollback:
|
|
485
485
|
|
|
486
486
|
`;for(let l of i)if(l.id==="initial")c+=`--- Initial State (id: initial) ---
|
|
487
487
|
Tools Used: User Prompted for task
|
|
@@ -489,7 +489,7 @@ Tools Used: User Prompted for task
|
|
|
489
489
|
`;else{let u=l.id.replace("turn_",""),d=l.toolsUsed&&l.toolsUsed.length>0?l.toolsUsed.map(f).join(", "):"None";c+=`--- Turn ${u} (id: ${l.id}) ---
|
|
490
490
|
Tools Used: ${d}
|
|
491
491
|
|
|
492
|
-
`}return c.trim()}else if(s==="forceRevert"){if(!o)return"ERROR: Missing required parameter 'id' for forceRevert.";try{let i=await
|
|
492
|
+
`}return c.trim()}else if(s==="forceRevert"){if(!o)return"ERROR: Missing required parameter 'id' for forceRevert.";try{let i=await Kn.rollbackToCheckpoint(r,o),{checkpointId:h,stats:f}=i,c=f.restored+f.replaced+f.failed.length,l=`SUCCESS: Repository rolled back to checkpoint [${h}].
|
|
493
493
|
|
|
494
494
|
`;return l+=`Stats:
|
|
495
495
|
`,l+=` Restored : ${f.restored} file${f.restored!==1?"s":""} (new to workspace)
|
|
@@ -498,14 +498,14 @@ Tools Used: ${d}
|
|
|
498
498
|
${f.failed.join(`
|
|
499
499
|
`)}`),l+=`
|
|
500
500
|
\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-
|
|
501
|
-
`,l+=` Total : ${c} file${c!==1?"s":""} processed`,l}catch(i){return`ERROR: ${i.message}`}}else return`ERROR: Invalid method "${s}". Use "getCheckpoint" or "forceRevert".`};var
|
|
501
|
+
`,l+=` Total : ${c} file${c!==1?"s":""} processed`,l}catch(i){return`ERROR: ${i.message}`}}else return`ERROR: Invalid method "${s}". Use "getCheckpoint" or "forceRevert".`};var Ps=async(e,n={})=>{let t=L(e),s=t.id,o=parseInt(t.timeout||t.time||"120",10);if((isNaN(o)||o<=0)&&(o=120),o>300&&(o=300),!s)return t.time?(await new Promise(h=>setTimeout(h,o*1e3)),`SUCCESS: Waited for ${o}s.`):'ERROR: Missing "id" argument for Await.';let r=Ve.find(h=>h.id===s);if(!r)return`ERROR: Subagent task with ID [${s}] not found.`;if(r.status==="completed")return`SUCCESS: Subagent task [${s}] completed.
|
|
502
502
|
Final Answer:
|
|
503
503
|
${r.finalAnswer||"(No output)"}`;if(r.status==="failed")return`ERROR: Subagent task [${s}] failed.
|
|
504
504
|
Error: ${r.error||"Unknown error"}`;if(r.status==="cancelled")return`INFO: Subagent task [${s}] was cancelled.`;let a,i=new Promise(h=>{a=setTimeout(()=>{h({type:"timeout"})},o*1e3)});try{let h=await Promise.race([r.completionPromise.then(()=>({type:"completion"})),i]);return clearTimeout(a),h.type==="timeout"?`TIMEOUT: Subagent task [${s}] is still running (status: ${r.status.toUpperCase()}) after ${o}s. You can continue other work or call Await again.`:r.status==="completed"?`SUCCESS: Subagent task [${s}] completed.
|
|
505
505
|
Final Answer:
|
|
506
506
|
${r.finalAnswer||"(No output)"}`:r.status==="failed"?`ERROR: Subagent task [${s}] failed.
|
|
507
|
-
Error: ${r.error||"Unknown error"}`:r.status==="cancelled"?`INFO: Subagent task [${s}] was cancelled.`:`INFO: Subagent task [${s}] status changed to ${r.status.toUpperCase()}.`}catch(h){return clearTimeout(a),`ERROR: Exception while awaiting subagent [${s}]: ${h.message}`}};var
|
|
508
|
-
`)){let r=o.split(" ");if(r.length<12||parseInt(r[0])!==5)continue;let i=r[2],h=r[3],f=r[4],c=parseInt(r[6]),l=parseInt(r[7]),u=parseInt(r[8]),d=parseInt(r[9]),p=parseFloat(r[10]),g=r.slice(11).join(" ").trim();if(!g||p<0)continue;let y={x0:c,y0:l,x1:c+u,y1:l+d},m={text:g,confidence:p,bbox:y};n.push(m);let w=`${i}_${h}_${f}`;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 s=[];for(let o of t.values())o.words.length>0&&s.push({text:o.words.map(r=>r.text).join(" "),bbox:o.bbox,words:o.words});return{words:n,lines:s}}function nc(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 s of t.lines||[]){s.bbox&&e.lines.push(s);for(let o of s.words||[])o.bbox&&e.words.push(o)}if(e.words.length>0)return}if(e.tsv){let n=tc(e.tsv);e.words=n.words,e.lines=n.lines}}}function zr(e,n,t=0,s=0,o=1){nc(e);let r=i=>({x0:Math.round(i.x0/o)+t,y0:Math.round(i.y0/o)+s,x1:Math.round(i.x1/o)+t,y1:Math.round(i.y1/o)+s}),a=[];if(e.lines&&e.lines.length>0)for(let i of e.lines){let h=i.text?i.text.toLowerCase().trim():"";if(!h||!i.bbox||!(h===n||new RegExp(`\\b${Ql(n)}\\b`,"i").test(h)))continue;let c=i.words||(e.words?e.words.filter(p=>p.bbox&&p.bbox.x0>=i.bbox.x0-5&&p.bbox.x1<=i.bbox.x1+5&&p.bbox.y0>=i.bbox.y0-5&&p.bbox.y1<=i.bbox.y1+5):[]),l=n.split(/\s+/),u=l.map(p=>p.replace(/[^a-z0-9]/g,"")).join(" "),d=!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(r(m)),d=!0}}d||a.push(r(i.bbox))}if(a.length===0&&e.words&&e.words.length>0)for(let i of e.words){let h=i.text?i.text.toLowerCase().trim().replace(/[^a-z0-9]/g,""):"",f=n.replace(/[^a-z0-9]/g,"");h===f&&i.bbox&&a.push(r(i.bbox))}if(a.length===0&&e.words&&e.words.length>0){let i=ec(n.length);for(let h of e.words){let f=h.text?h.text.toLowerCase().trim():"";f.length>=3&&Math.abs(f.length-n.length)<=i&&Zl(f,n,i)<=i&&h.bbox&&a.push(r(h.bbox))}}return a}function Kr(e,n){let t=null,s=1/0;for(let o of e){let r=Math.round((o.x0+o.x1)/2),a=Math.round((o.y0+o.y1)/2),i=n.x>=o.x0&&n.x<=o.x1&&n.y>=o.y0&&n.y<=o.y1,h=Math.hypot(r-n.x,a-n.y),f=i?0:h;f<s&&(s=f,t={x:r,y:a,dist:h,containsPoint:i,bbox:o})}return t}function sc(e,n,t,s){let a=Math.ceil(e/4),i=Math.ceil(n/2),h=[];for(let f=0;f<2;f++)for(let c=0;c<4;c++){let l=c*a,u=f*i,d=Math.min(a,e-l),p=Math.min(i,n-u),g=l+d/2,y=u+p/2,m=t>=l&&t<l+d&&s>=u&&s<u+p;h.push({x0:l,y0:u,w:d,h:p,cx:g,cy:y,containsTarget:m})}return h.sort((f,c)=>{if(f.containsTarget)return-1;if(c.containsTarget)return 1;let l=Math.hypot(f.cx-t,f.cy-s),u=Math.hypot(c.cx-t,c.cy-s);return l-u})}var Io=null;async function oc(){return Io||(Io=(async()=>{let{createWorker:e}=await import("tesseract.js"),n=await import("fs-extra"),{CU_CACHE_DIR:t}=await import("./paths-CHZDSDRF.js");return n.ensureDirSync(t),e("eng",1,{cachePath:t,logger:()=>{}})})().catch(e=>{throw Io=null,e})),Io}var ao=null,ya=null;async function rc(){let{getActiveDisplay:e}=await import("./screen_grid-WWZV4QEB.js"),n=await e();if(ao&&ya===n)return ao;ya=n,ao={format:"png"};try{let t=await wa.listDisplays();t&&t.length>0&&(ao={format:"png",screen:(t[n]||t[0]).id})}catch{}return ao}var Yr=async(e,n={})=>{let t=!!(process.env.SHOW_DEBUG_GRID||process.env.DEBUG_OCR||process.env.VERBOSE),s=performance.now(),o=s,r=d=>{if(!t)return;let p=performance.now(),g=(p-o).toFixed(0),y=(p-s).toFixed(0);console.log(`[Click Perf] +${g}ms (${y}ms total) -> ${d}`),o=p};r("Starting click()");let a=L(e),i=a.gridId||a.grid||a.coordinate||a.target||a.id,h=(a.type||a.clickType||"single").toLowerCase(),f=(a.button||"left").toLowerCase(),c=a.intendedClickText||a.text||"";if(!i&&!c)return'ERROR: Missing required "gridId" parameter for Click tool.';let l=i;if(c)try{r("Parsing grid code");let d=i?Ci(i):null;r("Getting display options");let p=await rc();r("Taking desktop screenshot");let g=await wa(p);r("Getting image metadata");let y=await lo(g).metadata(),m=y.width||1920,w=y.height||1080,x=d?{x:Math.round(d.x*(m/1280)),y:Math.round(d.y*(w/720))}:{x:m/2,y:w/2},k=c.toLowerCase().trim();r("Acquiring OCR worker");let $=await oc(),R=null,S="",T=d?220:500;if(d){r("Pass 1: Cropping target crop (3x zoom window, 2x upscale)");let E=Math.min(Math.round(m/3),m),_=Math.min(Math.round(w/3),w),b=Math.max(0,Math.min(m-E,x.x-Math.floor(E/2))),C=Math.max(0,Math.min(w-_,x.y-Math.floor(_/2))),A=await lo(g).extract({left:b,top:C,width:E,height:_}).toBuffer(),O=2,D=await qr(A,O),W=k.replace(/[^a-z0-9]/g,"_");await Gr("cropped",`crop_${Date.now()}_${W}.png`,D),r("Pass 1: Running Tesseract OCR recognize on crop (PSM 11 - Sparse Text)"),await $.setParameters({tessedit_pageseg_mode:"11"});let{data:q}=await $.recognize(D,{},{tsv:!0,blocks:!0});if(r("Pass 1: OCR recognition finished, extracting matches"),q&&q.text){t&&console.log(`[Pass 1 OCR Read]: "${q.text.trim().replace(/\s+/g," ")}"`);let se=zr(q,k,b,C,O);if(se.length>0){let V=Kr(se,x);V&&(V.containsPoint||V.dist<=T)&&(R=V,S="centered target crop OCR")}}}if(!R){r("Pass 2: Entering Full-Screen OCR (broad scan, PSM 3 - Auto)");let E=await qr(g,2),_=k.replace(/[^a-z0-9]/g,"_");await Gr("fullscreen",`full_${Date.now()}_${_}.png`,E),r("Pass 2: Running Tesseract on full screen"),await $.setParameters({tessedit_pageseg_mode:"3"});let{data:b}=await $.recognize(E,{},{tsv:!0,blocks:!0});if(r("Pass 2: Full-screen OCR finished"),b&&b.text){let C=zr(b,k,0,0,2);if(C.length>0){let A=Kr(C,x);A&&(R=A,S="full-screen OCR")}}}if(!R){r("Pass 3: Entering Tiled OCR fallback (high-res 3x)");let E=sc(m,w,x.x,x.y),_=k.replace(/[^a-z0-9]/g,"_");await $.setParameters({tessedit_pageseg_mode:"11"});for(let b=0;b<E.length;b++){let C=E[b];r(`Pass 3: Preprocessing tile ${b+1}/${E.length}`);let A=await lo(g).extract({left:C.x0,top:C.y0,width:C.w,height:C.h}).toBuffer(),O=await qr(A,3);await Gr("tiles",`tile_${b+1}_${Date.now()}_${_}.png`,O),r(`Pass 3: Running Tesseract on tile ${b+1}`);let{data:D}=await $.recognize(O,{},{tsv:!0,blocks:!0});if(!D||!D.text)continue;let W=zr(D,k,C.x0,C.y0,3);if(W.length>0){let q=Kr(W,x);if(q){R=q,S=`tile ${b+1} OCR (${C.containsTarget?"target tile":`offset ${C.x0},${C.y0}`})`;break}}}}if(R){let E={x:Math.round(R.x*(1280/m)),y:Math.round(R.y*(720/w))};r(`Executing mouse click on matched target (${S})`);let _=await On("click",E,{button:f,clickType:h});return r("Click completed successfully"),`${_} (${S} for "${c}" at ${Math.round(R.dist)}px distance)`}else t&&console.log(`[OCR] No match found for "${c}". Falling back to gridId.`)}catch(d){t&&console.error("[OCR Error]",d)}r(`Executing mouse click on fallback gridId: ${l}`);let u=await On("click",l,{button:f,clickType:h});return r("Fallback click completed"),u};var Vr=async(e,n={})=>{let t=L(e),s=t.fromGridId||t.from||t.start,o=t.toGridId||t.to||t.end;return!s||!o?'ERROR: Drag requires both "fromGridId" and "toGridId" parameters.':await On("drag",s,{from:s,to:o})};var Xr=async(e,n={})=>{let t=L(e),s=(t.direction||"down").toLowerCase(),o=t.amount?parseInt(t.amount,10):6,r=t.gridId||t.grid||t.coordinate||t.target||t.id||null;return await On("scroll",r,{direction:s,amount:o})};var Oo=async(e,n={})=>{let t=L(e),s=t.text||t.input||t.value||"",o=t.autoPressEnter===!0||t.autoPressEnter==="true"||t.enter===!0||t.enter==="true";return s==null?'ERROR: Missing required "text" parameter for KeyboardTyping tool.':await Ln("type",String(s),{autoPressEnter:o})};var Lo=async(e,n={})=>{let t=L(e),s=t.key||t.keys||t.input||t.shortcut;if(!s)return'ERROR: Missing required "key" parameter for KeyPress tool.';let o=String(s).trim().toLowerCase();if(o==="clearinput"||o==="clear_input"||o==="clear")return await Ln("clear_input");if(o==="back"||o==="browser_back"||o==="browserBack")return await Ln("browser_back");if(o.includes(";")||o.includes("+")){let r=o.split(/[;+]/).map(a=>a.trim()).filter(Boolean);return await Ln("key_combination",r)}return await Ln("key_press",o)};var Po=async(e,n={})=>"SUCCESS: Screen recapture requested. The latest gridded screenshot is provided for your next decision.";var ic={web_search:yr,web_scrape:wr,memory:xr,chat:br,view_file:Js,write_file:Sr,update_file:_r,exec_command:fr,read_folder:Cr,write_pdf:Mr,write_docx:vr,search_keyword:Zs,generate_image:Pr,saveSummary:eo,addMemScore:Os,file_map:Nr,todo:to,Todo:to,goal:to,Goal:to,invokeSync:Br,invoke:fa,getProgress:Ur,cancel:da,awaitSubagent:Ls,answerSubagent:Ps,steerSubagent:so,computer_action:io,computer_use:io,ComputerAction:io,ComputerUse:io,click:Yr,Click:Yr,drag:Vr,Drag:Vr,scroll:Xr,Scroll:Xr,keyboard_typing:Oo,KeyboardTyping:Oo,keyboardtyping:Oo,key_press:Lo,KeyPress:Lo,keypress:Lo,recapture_screen:Po,RecaptureScreen:Po,recapturescreen:Po,invoke_sync:Br,get_progress:Ur,await_subagent:Ls,answer_subagent:Ps,steer_subagent:so,steer:so,Steer:so,ask:vo,Ask:vo,AskUser:vo,WebSearch:yr,WebScrape:wr,ReadFile:Js,ReadFolder:Cr,WriteFile:Sr,PatchFile:_r,WritePDF:Mr,WriteDoc:vr,Run:fr,SearchKeyword:Zs,CodeSearch:Zs,code_search:Zs,Memory:xr,Chat:br,GenerateImage:Pr,saveSumary:eo,SaveSummary:eo,SaveSumary:eo,add_mem_score:Os,AddMemScore:Os,addMemoryScore:Os,AddMemoryScore:Os,FileMap:Nr,answer:Ps,Answer:Ps,AnswerSubagent:Ps,await:Ls,Await:Ls,AwaitSubagent:Ls,EmergencyRollback:jr,emergency_rollback:jr},co=async(e,n,t={})=>{let s=t.mode?t.mode.toLowerCase():"flux",o=e.toLowerCase(),a=["memory","chat","savesummary","addmemscore","add_mem_score","ask","web_search","web_scrape","await"].some(c=>o.includes(c))||o==="ask",h=["click","drag","scroll","keyboardtyping","keyboard_typing","keypress","key_press","recapturescreen","recapture_screen","computer"].some(c=>o.includes(c));if(!a){if(s==="flow"){if(!(o.includes("write_pdf")||o.includes("write_docx")||o.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(s==="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(o.includes("write_pdf")||o.includes("write_docx")||o.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 f=ic[e];if(!f)return`ERROR: Tool [${e}] not found in registry.`;try{return await f(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 Pe from"fs";import ac from"gradient-string";var Jr=["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 xa=[{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"]}],fo={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 Do=null;var ba=(e="Dark")=>{let n;e==="Mystery"||e==="Chaos"?(Do||(Do=xa[Math.floor(Math.random()*xa.length)]),n={...Do,id:"Mystery"}):(Do=null,fo[e]?n=fo[e]:e==="GitHub"?n=fo["GitHub Dark"]:e==="Transparent"?n=fo["Transparent Dark"]:n=fo.Dark);let t=n.codeText||n.secondary||n.info||n.logoGradient&&n.logoGradient[0]||"cyan";return{...n,codeText:t}};var lc=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",Oh=(e=2)=>{let n=lc();return n==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)},Lh=(e="...",n="Loading...",t="Dark")=>{let s=Jr[Math.floor(Math.random()*Jr.length)],o=ba(t),r=o.logoTextAnsi,a=o.logoBodyAnsi,i=o.logoMutedAnsi,h="\x1B[0m",f=[" \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=o.logoGradient||["#0077ff","#ff00ff"],l=ac(c).multiline(f.join(`
|
|
507
|
+
Error: ${r.error||"Unknown error"}`:r.status==="cancelled"?`INFO: Subagent task [${s}] was cancelled.`:`INFO: Subagent task [${s}] status changed to ${r.status.toUpperCase()}.`}catch(h){return clearTimeout(a),`ERROR: Exception while awaiting subagent [${s}]: ${h.message}`}};var Ds=async(e,n={})=>{let t=L(e),s=t.id,o=t.answer||t.response;if(!s)return'ERROR: Missing "id" argument for Answer.';if(!o)return'ERROR: Missing "answer" argument for Answer.';let r=Ve.find(i=>i.id===s);if(!r)return`ERROR: Subagent task with ID [${s}] not found.`;if(!r.questions||r.questions.length===0)return`INFO: Subagent task [${s}] has no pending questions.`;let a=r.questions.filter(i=>!i.answered);return a.length===0?`INFO: Subagent task [${s}] has no unanswered questions.`:(a.forEach(i=>{i.answered=!0,i.answer=o,i.answeredAt=Date.now(),i._resolve&&i._resolve(o)}),r.status="running",n.onSubagentUpdate&&n.onSubagentUpdate(),`SUCCESS: Answer provided to subagent task [${s}]. Subagent execution resumed.`)};var so=async(e,n={})=>{let t=L(e),s=t.id,o=t.message||t.instruction||t.text||t.prompt;if(!s)return'ERROR: Missing "id" argument for Steer.';if(!o)return'ERROR: Missing "message" argument for Steer.';let r=Ve.find(a=>a.id===s);return r?r.status==="completed"||r.status==="failed"||r.status==="cancelled"?`ERROR: Cannot steer subagent task [${s}] because it has already finished with status [${r.status.toUpperCase()}].`:(typeof r.steer=="function"?r.steer(o):(r.pendingSteerMessages||(r.pendingSteerMessages=[]),r.pendingSteerMessages.push(o)),n.onSubagentUpdate&&n.onSubagentUpdate(),`SUCCESS: Steering instruction injected into subagent task [${s}]. It will be processed on the subagent's turn.`):`ERROR: Subagent task with ID [${s}] not found.`};import{mouse as fn,keyboard as Ft,Button as oo,Key as P,Point as ro,clipboard as Jl}from"@nut-tree-fork/nut-js";fn.config.autoDelayMs=50;Ft.config.autoDelayMs=50;async function zr(){try{await Ft.releaseKey(P.LeftControl,P.RightControl,P.LeftAlt,P.RightAlt,P.LeftShift,P.RightShift,P.LeftSuper,P.RightSuper)}catch{}}async function On(e,n,t={}){let s=await qs(n);if(!s&&(e==="move"||e==="click"||e==="drag"))return`ERROR: Invalid target location specified: ${JSON.stringify(n)}`;try{switch(e.toLowerCase()){case"move":return await fn.setPosition(new ro(s.x,s.y)),`SUCCESS: Moved mouse to grid target ${typeof n=="string"?n:`(${s.x}, ${s.y})`}`;case"click":{await fn.setPosition(new ro(s.x,s.y));let o=t.button==="right"?oo.RIGHT:t.button==="middle"?oo.MIDDLE:oo.LEFT;return t.clickType==="double"?await fn.doubleClick(o):await fn.click(o),`SUCCESS: ${t.clickType||"Single"} clicked ${t.button||"left"} button at ${typeof n=="string"?n:`(${s.x}, ${s.y})`}`}case"drag":{let o=await qs(t.from||n),r=await qs(t.to);return!o||!r?'ERROR: Drag requires valid "from" and "to" target coordinates/grid codes.':(await fn.setPosition(new ro(o.x,o.y)),await fn.pressButton(oo.LEFT),await fn.setPosition(new ro(r.x,r.y)),await fn.releaseButton(oo.LEFT),`SUCCESS: Dragged mouse from (${o.x}, ${o.y}) to (${r.x}, ${r.y})`)}case"scroll":{let o=s||await qs({x:640,y:360});o&&(await fn.setPosition(new ro(o.x,o.y)),await new Promise(h=>setTimeout(h,60)));let r=parseInt(t.amount,10);(isNaN(r)||r<=0)&&(r=5);let a=r>50?Math.min(20,Math.max(1,Math.round(r/100))):Math.min(20,r),i=t.direction==="up";for(let h=0;h<a;h++)i?await fn.scrollUp(120):await fn.scrollDown(120),await new Promise(f=>setTimeout(f,20));return`SUCCESS: Scrolled ${t.direction||"down"} (${a} notches${s?` at target (${s.x}, ${s.y})`:" at screen center"})`}default:return`ERROR: Unsupported mouse action "${e}"`}}catch(o){return`ERROR: Mouse action failed: ${o.message}`}}var ma={enter:P.Enter,return:P.Return,escape:P.Escape,esc:P.Escape,backspace:P.Backspace,tab:P.Tab,space:P.Space,up:P.Up,down:P.Down,left:P.Left,right:P.Right,ctrl:P.LeftControl,control:P.LeftControl,alt:P.LeftAlt,shift:P.LeftShift,cmd:P.LeftCmd,win:P.LeftWin,meta:P.LeftWin,super:P.LeftSuper,a:P.A,b:P.B,c:P.C,d:P.D,e:P.E,f:P.F,g:P.G,h:P.H,i:P.I,j:P.J,k:P.K,l:P.L,m:P.M,n:P.N,o:P.O,p:P.P,q:P.Q,r:P.R,s:P.S,t:P.T,u:P.U,v:P.V,w:P.W,x:P.X,y:P.Y,z:P.Z,0:P.Num0,1:P.Num1,2:P.Num2,3:P.Num3,4:P.Num4,5:P.Num5,6:P.Num6,7:P.Num7,8:P.Num8,9:P.Num9,f1:P.F1,f2:P.F2,f3:P.F3,f4:P.F4,f5:P.F5,f6:P.F6,f7:P.F7,f8:P.F8,f9:P.F9,f10:P.F10,f11:P.F11,f12:P.F12},ga=e=>{if(!e)return;let n=String(e).toLowerCase().trim();if(ma[n]!==void 0)return ma[n];if(P[e]!==void 0)return P[e];if(P[n.toUpperCase()]!==void 0)return P[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 zr(),await Jl.setContent(n);let o=process.platform==="darwin"?P.LeftSuper:P.LeftControl;return await Ft.pressKey(o,P.V),await Ft.releaseKey(o,P.V),await zr(),t.autoPressEnter?(await new Promise(r=>setTimeout(r,50)),await Ft.type(P.Enter),`SUCCESS: Typed text input ("${n.length>20?n.substring(0,20)+"...":n}") and pressed Enter`):`SUCCESS: Typed text input ("${n.length>20?n.substring(0,20)+"...":n}")`}case"key_press":{let s=ga(n);return s===void 0?`ERROR: Unknown key name "${n}"`:(await Ft.type(s),`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 s=n.map(o=>ga(o)).filter(o=>o!==void 0);return s.length===0?"ERROR: Invalid key combination":(await Ft.pressKey(...s),await Ft.releaseKey(...s),`SUCCESS: Executed key combination [${n.join(" + ")}]`)}case"clear_input":return await Ft.pressKey(P.LeftControl,P.A),await Ft.releaseKey(P.LeftControl,P.A),await Ft.type(P.Backspace),"SUCCESS: Cleared active text input (Select All + Backspace)";case"browser_back":{let s=process.platform==="darwin";return s?(await Ft.pressKey(P.LeftSuper,P.Left),await Ft.releaseKey(P.LeftSuper,P.Left)):(await Ft.pressKey(P.LeftAlt,P.Left),await Ft.releaseKey(P.LeftAlt,P.Left)),await zr(),`SUCCESS: Browser back navigation (${s?"Cmd+Left":"Alt+Left"})`}default:return`ERROR: Unsupported keyboard action "${e}"`}}catch(s){return`ERROR: Keyboard action failed: ${s.message}`}}var io=async(e,n={})=>{let t=L(e),s=t.action||t.type||t.cmd,o=t.target||t.grid||t.gridCode||t.location||t.input;if(!s)return'ERROR: Missing required "action" argument for computer_action (e.g. move, click, drag, scroll, type, key_press, key_combination).';let r=s.toLowerCase();if(r.startsWith("mouse_")||["move","click","drag","scroll"].includes(r)){let a=r.replace("mouse_","");return await On(a,o,{button:t.button,clickType:t.clickType||t.type,from:t.from,to:t.to,direction:t.direction,amount:t.amount?parseInt(t.amount,10):void 0})}if(r.startsWith("key_")||r==="type"||r==="press"){let a=r;r==="press"&&(a="key_press");let i=t.autoPressEnter===!0||t.autoPressEnter==="true"||t.enter===!0||t.enter==="true";return await Ln(a,o||t.text||t.keys,{...t,autoPressEnter:i})}return`ERROR: Unrecognized action "${s}". Supported actions: move, click, drag, scroll, type, key_press, key_combination.`};import ba from"screenshot-desktop";import lo from"sharp";import ya from"fs-extra";import wa from"path";import"@nut-tree-fork/nut-js";async function Kr(e,n,t){if(!(!process.env.SHOW_DEBUG_GRID&&!process.env.DEBUG_OCR))try{let s=wa.resolve(process.cwd(),"screenshots",e);await ya.ensureDir(s),await ya.writeFile(wa.join(s,n),t)}catch{}}function Ql(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Zl(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 s=Array.from({length:n.length+1},(o,r)=>r);for(let o=1;o<=e.length;o++){let r=[o],a=o;for(let i=1;i<=n.length;i++){let h=e[o-1]===n[i-1]?0:1,f=Math.min(r[i-1]+1,s[i]+1,s[i-1]+h);r.push(f),f<a&&(a=f)}if(s=r,a>t)return t+1}return s[n.length]}function ec(e){return e<=4?0:e<=8?1:2}async function Yr(e,n=3){let t=await lo(e).metadata();return lo(e).resize(Math.round(t.width*n),Math.round(t.height*n),{kernel:"lanczos3"}).greyscale().normalise().toBuffer()}function tc(e){if(!e)return{words:[],lines:[]};let n=[],t=new Map;for(let o of e.split(`
|
|
508
|
+
`)){let r=o.split(" ");if(r.length<12||parseInt(r[0])!==5)continue;let i=r[2],h=r[3],f=r[4],c=parseInt(r[6]),l=parseInt(r[7]),u=parseInt(r[8]),d=parseInt(r[9]),p=parseFloat(r[10]),g=r.slice(11).join(" ").trim();if(!g||p<0)continue;let y={x0:c,y0:l,x1:c+u,y1:l+d},m={text:g,confidence:p,bbox:y};n.push(m);let w=`${i}_${h}_${f}`;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 s=[];for(let o of t.values())o.words.length>0&&s.push({text:o.words.map(r=>r.text).join(" "),bbox:o.bbox,words:o.words});return{words:n,lines:s}}function nc(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 s of t.lines||[]){s.bbox&&e.lines.push(s);for(let o of s.words||[])o.bbox&&e.words.push(o)}if(e.words.length>0)return}if(e.tsv){let n=tc(e.tsv);e.words=n.words,e.lines=n.lines}}}function Vr(e,n,t=0,s=0,o=1){nc(e);let r=i=>({x0:Math.round(i.x0/o)+t,y0:Math.round(i.y0/o)+s,x1:Math.round(i.x1/o)+t,y1:Math.round(i.y1/o)+s}),a=[];if(e.lines&&e.lines.length>0)for(let i of e.lines){let h=i.text?i.text.toLowerCase().trim():"";if(!h||!i.bbox||!(h===n||new RegExp(`\\b${Ql(n)}\\b`,"i").test(h)))continue;let c=i.words||(e.words?e.words.filter(p=>p.bbox&&p.bbox.x0>=i.bbox.x0-5&&p.bbox.x1<=i.bbox.x1+5&&p.bbox.y0>=i.bbox.y0-5&&p.bbox.y1<=i.bbox.y1+5):[]),l=n.split(/\s+/),u=l.map(p=>p.replace(/[^a-z0-9]/g,"")).join(" "),d=!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(r(m)),d=!0}}d||a.push(r(i.bbox))}if(a.length===0&&e.words&&e.words.length>0)for(let i of e.words){let h=i.text?i.text.toLowerCase().trim().replace(/[^a-z0-9]/g,""):"",f=n.replace(/[^a-z0-9]/g,"");h===f&&i.bbox&&a.push(r(i.bbox))}if(a.length===0&&e.words&&e.words.length>0){let i=ec(n.length);for(let h of e.words){let f=h.text?h.text.toLowerCase().trim():"";f.length>=3&&Math.abs(f.length-n.length)<=i&&Zl(f,n,i)<=i&&h.bbox&&a.push(r(h.bbox))}}return a}function Xr(e,n){let t=null,s=1/0;for(let o of e){let r=Math.round((o.x0+o.x1)/2),a=Math.round((o.y0+o.y1)/2),i=n.x>=o.x0&&n.x<=o.x1&&n.y>=o.y0&&n.y<=o.y1,h=Math.hypot(r-n.x,a-n.y),f=i?0:h;f<s&&(s=f,t={x:r,y:a,dist:h,containsPoint:i,bbox:o})}return t}function sc(e,n,t,s){let a=Math.ceil(e/4),i=Math.ceil(n/2),h=[];for(let f=0;f<2;f++)for(let c=0;c<4;c++){let l=c*a,u=f*i,d=Math.min(a,e-l),p=Math.min(i,n-u),g=l+d/2,y=u+p/2,m=t>=l&&t<l+d&&s>=u&&s<u+p;h.push({x0:l,y0:u,w:d,h:p,cx:g,cy:y,containsTarget:m})}return h.sort((f,c)=>{if(f.containsTarget)return-1;if(c.containsTarget)return 1;let l=Math.hypot(f.cx-t,f.cy-s),u=Math.hypot(c.cx-t,c.cy-s);return l-u})}var Ao=null;async function oc(){return Ao||(Ao=(async()=>{let{createWorker:e}=await import("tesseract.js"),n=await import("fs-extra"),{CU_CACHE_DIR:t}=await import("./paths-CHZDSDRF.js");return n.ensureDirSync(t),e("eng",1,{cachePath:t,logger:()=>{}})})().catch(e=>{throw Ao=null,e})),Ao}var ao=null,xa=null;async function rc(){let{getActiveDisplay:e}=await import("./screen_grid-WWZV4QEB.js"),n=await e();if(ao&&xa===n)return ao;xa=n,ao={format:"png"};try{let t=await ba.listDisplays();t&&t.length>0&&(ao={format:"png",screen:(t[n]||t[0]).id})}catch{}return ao}var Jr=async(e,n={})=>{let t=!!(process.env.SHOW_DEBUG_GRID||process.env.DEBUG_OCR||process.env.VERBOSE),s=performance.now(),o=s,r=d=>{if(!t)return;let p=performance.now(),g=(p-o).toFixed(0),y=(p-s).toFixed(0);console.log(`[Click Perf] +${g}ms (${y}ms total) -> ${d}`),o=p};r("Starting click()");let a=L(e),i=a.gridId||a.grid||a.coordinate||a.target||a.id,h=(a.type||a.clickType||"single").toLowerCase(),f=(a.button||"left").toLowerCase(),c=a.intendedClickText||a.text||"";if(!i&&!c)return'ERROR: Missing required "gridId" parameter for Click tool.';let l=i;if(c)try{r("Parsing grid code");let d=i?vi(i):null;r("Getting display options");let p=await rc();r("Taking desktop screenshot");let g=await ba(p);r("Getting image metadata");let y=await lo(g).metadata(),m=y.width||1920,w=y.height||1080,x=d?{x:Math.round(d.x*(m/1280)),y:Math.round(d.y*(w/720))}:{x:m/2,y:w/2},k=c.toLowerCase().trim();r("Acquiring OCR worker");let $=await oc(),R=null,S="",T=d?220:500;if(d){r("Pass 1: Cropping target crop (3x zoom window, 2x upscale)");let E=Math.min(Math.round(m/3),m),_=Math.min(Math.round(w/3),w),b=Math.max(0,Math.min(m-E,x.x-Math.floor(E/2))),C=Math.max(0,Math.min(w-_,x.y-Math.floor(_/2))),A=await lo(g).extract({left:b,top:C,width:E,height:_}).toBuffer(),O=2,D=await Yr(A,O),W=k.replace(/[^a-z0-9]/g,"_");await Kr("cropped",`crop_${Date.now()}_${W}.png`,D),r("Pass 1: Running Tesseract OCR recognize on crop (PSM 11 - Sparse Text)"),await $.setParameters({tessedit_pageseg_mode:"11"});let{data:q}=await $.recognize(D,{},{tsv:!0,blocks:!0});if(r("Pass 1: OCR recognition finished, extracting matches"),q&&q.text){t&&console.log(`[Pass 1 OCR Read]: "${q.text.trim().replace(/\s+/g," ")}"`);let se=Vr(q,k,b,C,O);if(se.length>0){let V=Xr(se,x);V&&(V.containsPoint||V.dist<=T)&&(R=V,S="centered target crop OCR")}}}if(!R){r("Pass 2: Entering Full-Screen OCR (broad scan, PSM 3 - Auto)");let E=await Yr(g,2),_=k.replace(/[^a-z0-9]/g,"_");await Kr("fullscreen",`full_${Date.now()}_${_}.png`,E),r("Pass 2: Running Tesseract on full screen"),await $.setParameters({tessedit_pageseg_mode:"3"});let{data:b}=await $.recognize(E,{},{tsv:!0,blocks:!0});if(r("Pass 2: Full-screen OCR finished"),b&&b.text){let C=Vr(b,k,0,0,2);if(C.length>0){let A=Xr(C,x);A&&(R=A,S="full-screen OCR")}}}if(!R){r("Pass 3: Entering Tiled OCR fallback (high-res 3x)");let E=sc(m,w,x.x,x.y),_=k.replace(/[^a-z0-9]/g,"_");await $.setParameters({tessedit_pageseg_mode:"11"});for(let b=0;b<E.length;b++){let C=E[b];r(`Pass 3: Preprocessing tile ${b+1}/${E.length}`);let A=await lo(g).extract({left:C.x0,top:C.y0,width:C.w,height:C.h}).toBuffer(),O=await Yr(A,3);await Kr("tiles",`tile_${b+1}_${Date.now()}_${_}.png`,O),r(`Pass 3: Running Tesseract on tile ${b+1}`);let{data:D}=await $.recognize(O,{},{tsv:!0,blocks:!0});if(!D||!D.text)continue;let W=Vr(D,k,C.x0,C.y0,3);if(W.length>0){let q=Xr(W,x);if(q){R=q,S=`tile ${b+1} OCR (${C.containsTarget?"target tile":`offset ${C.x0},${C.y0}`})`;break}}}}if(R){let E={x:Math.round(R.x*(1280/m)),y:Math.round(R.y*(720/w))};r(`Executing mouse click on matched target (${S})`);let _=await On("click",E,{button:f,clickType:h});return r("Click completed successfully"),`${_} (${S} for "${c}" at ${Math.round(R.dist)}px distance)`}else t&&console.log(`[OCR] No match found for "${c}". Falling back to gridId.`)}catch(d){t&&console.error("[OCR Error]",d)}r(`Executing mouse click on fallback gridId: ${l}`);let u=await On("click",l,{button:f,clickType:h});return r("Fallback click completed"),u};var Qr=async(e,n={})=>{let t=L(e),s=t.fromGridId||t.from||t.start,o=t.toGridId||t.to||t.end;return!s||!o?'ERROR: Drag requires both "fromGridId" and "toGridId" parameters.':await On("drag",s,{from:s,to:o})};var Zr=async(e,n={})=>{let t=L(e),s=(t.direction||"down").toLowerCase(),o=t.amount?parseInt(t.amount,10):6,r=t.gridId||t.grid||t.coordinate||t.target||t.id||null;return await On("scroll",r,{direction:s,amount:o})};var vo=async(e,n={})=>{let t=L(e),s=t.text||t.input||t.value||"",o=t.autoPressEnter===!0||t.autoPressEnter==="true"||t.enter===!0||t.enter==="true";return s==null?'ERROR: Missing required "text" parameter for KeyboardTyping tool.':await Ln("type",String(s),{autoPressEnter:o})};var Io=async(e,n={})=>{let t=L(e),s=t.key||t.keys||t.input||t.shortcut;if(!s)return'ERROR: Missing required "key" parameter for KeyPress tool.';let o=String(s).trim().toLowerCase();if(o==="clearinput"||o==="clear_input"||o==="clear")return await Ln("clear_input");if(o==="back"||o==="browser_back"||o==="browserBack")return await Ln("browser_back");if(o.includes(";")||o.includes("+")){let r=o.split(/[;+]/).map(a=>a.trim()).filter(Boolean);return await Ln("key_combination",r)}return await Ln("key_press",o)};var Oo=async(e,n={})=>"SUCCESS: Screen recapture requested. The latest gridded screenshot is provided for your next decision.";var ic={web_search:br,web_scrape:Sr,memory:kr,chat:Tr,view_file:Js,write_file:Rr,update_file:Mr,exec_command:lr,read_folder:vr,write_pdf:Ir,write_docx:Lr,search_keyword:Zs,generate_image:Nr,saveSummary:eo,addMemScore:Ls,file_map:Wr,todo:to,Todo:to,goal:to,Goal:to,invokeSync:jr,invoke:ua,getProgress:Hr,cancel:pa,awaitSubagent:Ps,answerSubagent:Ds,steerSubagent:so,computer_action:io,computer_use:io,ComputerAction:io,ComputerUse:io,click:Jr,Click:Jr,drag:Qr,Drag:Qr,scroll:Zr,Scroll:Zr,keyboard_typing:vo,KeyboardTyping:vo,keyboardtyping:vo,key_press:Io,KeyPress:Io,keypress:Io,recapture_screen:Oo,RecaptureScreen:Oo,recapturescreen:Oo,invoke_sync:jr,get_progress:Hr,await_subagent:Ps,answer_subagent:Ds,steer_subagent:so,steer:so,Steer:so,ask:Mo,Ask:Mo,AskUser:Mo,WebSearch:br,WebScrape:Sr,ReadFile:Js,ReadFolder:vr,WriteFile:Rr,PatchFile:Mr,WritePDF:Ir,WriteDoc:Lr,Run:lr,SearchKeyword:Zs,CodeSearch:Zs,code_search:Zs,Memory:kr,Chat:Tr,GenerateImage:Nr,saveSumary:eo,SaveSummary:eo,SaveSumary:eo,add_mem_score:Ls,AddMemScore:Ls,addMemoryScore:Ls,AddMemoryScore:Ls,FileMap:Wr,answer:Ds,Answer:Ds,AnswerSubagent:Ds,await:Ps,Await:Ps,AwaitSubagent:Ps,EmergencyRollback:qr,emergency_rollback:qr},co=async(e,n,t={})=>{let s=t.mode?t.mode.toLowerCase():"flux",o=e.toLowerCase(),a=["memory","chat","savesummary","addmemscore","add_mem_score","ask","web_search","web_scrape","await"].some(c=>o.includes(c))||o==="ask",h=["click","drag","scroll","keyboardtyping","keyboard_typing","keypress","key_press","recapturescreen","recapture_screen","computer"].some(c=>o.includes(c));if(!a){if(s==="flow"){if(!(o.includes("write_pdf")||o.includes("write_docx")||o.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(s==="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(o.includes("write_pdf")||o.includes("write_docx")||o.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 f=ic[e];if(!f)return`ERROR: Tool [${e}] not found in registry.`;try{return await f(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 Pe from"fs";import ac from"gradient-string";var ei=["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 Sa=[{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"]}],fo={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 Lo=null;var ka=(e="Dark")=>{let n;e==="Mystery"||e==="Chaos"?(Lo||(Lo=Sa[Math.floor(Math.random()*Sa.length)]),n={...Lo,id:"Mystery"}):(Lo=null,fo[e]?n=fo[e]:e==="GitHub"?n=fo["GitHub Dark"]:e==="Transparent"?n=fo["Transparent Dark"]:n=fo.Dark);let t=n.codeText||n.secondary||n.info||n.logoGradient&&n.logoGradient[0]||"cyan";return{...n,codeText:t}};var lc=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",Oh=(e=2)=>{let n=lc();return n==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)},Lh=(e="...",n="Loading...",t="Dark")=>{let s=ei[Math.floor(Math.random()*ei.length)],o=ka(t),r=o.logoTextAnsi,a=o.logoBodyAnsi,i=o.logoMutedAnsi,h="\x1B[0m",f=[" \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=o.logoGradient||["#0077ff","#ff00ff"],l=ac(c).multiline(f.join(`
|
|
509
509
|
`)).split(`
|
|
510
510
|
`),u=d=>`${i}${d}${h}`;return`${l[0]}
|
|
511
511
|
${l[1]} ${r}Selected Provider: ${n}${h}
|
|
@@ -514,34 +514,34 @@ ${l[3]} ${r}FluxFlow ${u("v"+e)}${h}
|
|
|
514
514
|
${l[4]}
|
|
515
515
|
${l[5]} ${a}See /help for additional commands.${h}
|
|
516
516
|
${l[6]} ${u(s)}
|
|
517
|
-
${l[7]}`};import{WebSocket as
|
|
517
|
+
${l[7]}`};import{WebSocket as Po}from"ws";var Kt=null,Fs=!1,cc="ws://localhost:56832",ti=[],Ns=null,ni=null,Ta="2.0.0",Fh=e=>{Ta=e,Ra()},si=e=>{ni=e},Ra=()=>{if(Kt||Fs)return;Fs=!0;let e=new Po(cc);e.on("open",()=>{for(Kt=e,Fs=!1,Kt.send(JSON.stringify({command:"version",version:Ta,pid:process.pid,ppid:process.ppid}));ti.length>0;)Kt.send(JSON.stringify(ti.shift()))}),e.on("message",n=>{try{let t=JSON.parse(n.toString());t.command==="contextResponse"&&Ns?(Ns(t.data),Ns=null):t.command==="securityResponse"&&ni&&ni(t.result)}catch{}}),e.on("error",()=>{Fs=!1,Kt=null}),e.on("close",()=>{Fs=!1,Kt=null})},Do=e=>{Kt&&Kt.readyState===Po.OPEN?Kt.send(JSON.stringify(e)):(ti.push(e),Fs||Ra())},Fo=()=>Kt!==null&&Kt.readyState===Po.OPEN,Nh=e=>{Do({command:"status",status:e})},gs=()=>new Promise(e=>{if(!Kt||Kt.readyState!==Po.OPEN){e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]});return}Ns=e,Kt.send(JSON.stringify({command:"requestContext"})),setTimeout(()=>{Ns===e&&(e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]}),Ns=null)},1e3)}),Ea=e=>{Do({command:"open",filePath:e})},oi=(e,n,t)=>{Do({command:"showDiff",filePath:e,originalContent:n,modifiedContent:t})},_a=(e,n)=>{Do({command:"closeDiff",filePath:e,result:n})};import $a from"path";import fc from"fs";var dc=e=>{try{return fc.readdirSync(e,{withFileTypes:!0})}catch{return[]}},ri=(e,n,t=1,s=dc,o=[],r=null)=>{let a=r||s(e),i=" ".repeat(t-1);if(a.length>100)return`${i}${$a.basename(e)}/ (>100 files)
|
|
518
518
|
`;let h="",f=o,c=a.filter(p=>!f.includes(p.name)&&!p.name.startsWith(".")),l=a.filter(p=>f.includes(p.name)||p.name.startsWith(".")).map(p=>p.name).sort();l.length>0&&(h+=`${i}[ignored: ${l.map(p=>p+"/").join(", ")}]
|
|
519
|
-
`);let u=c.filter(p=>p.isDirectory()).sort((p,g)=>p.name.localeCompare(g.name)),d=c.filter(p=>!p.isDirectory()).map(p=>p.name).sort();for(let p of u){let g
|
|
519
|
+
`);let u=c.filter(p=>p.isDirectory()).sort((p,g)=>p.name.localeCompare(g.name)),d=c.filter(p=>!p.isDirectory()).map(p=>p.name).sort();for(let p of u){let g=$a.join(e,p.name);if(t>n)h+=`${i}${p.name}/ (max depth)
|
|
520
520
|
`;else{let y=s(g);y.length>80?h+=`${i}${p.name}/ (>80 files)
|
|
521
521
|
`:(h+=`${i}${p.name}/
|
|
522
|
-
`,h+=
|
|
523
|
-
`),h};import
|
|
524
|
-
`;let h="",f=r,c=a.filter(d=>!f.includes(d.name)&&!d.name.startsWith(".")),l=a.filter(d=>f.includes(d.name)||d.name.startsWith(".")).map(d=>d.name).sort();c.sort((d,p)=>d.isDirectory()&&!p.isDirectory()?-1:!d.isDirectory()&&p.isDirectory()?1:d.name.localeCompare(p.name));let u=[...c.map(d=>({name:d.name,isDir:d.isDirectory()})),...l.map(d=>({name:d,isDir:!0,isCollapsed:!0}))];return u.forEach((d,p)=>{let g=p===u.length-1,y=
|
|
522
|
+
`,h+=ri(g,n,t+1,s,o,y))}}return d.length>0&&(h+=`${i}${d.join("; ")}
|
|
523
|
+
`),h};import ii from"path";import uc from"fs";var pc=e=>{try{return uc.readdirSync(e,{withFileTypes:!0})}catch{return[]}},ai=(e,n,t="",s=1,o=pc,r=[])=>{let a=o(e),i=ii.sep;if(a.length>100)return`${t}\u2514\u2500\u2500 ${ii.basename(e)}${i} ...100+ files...
|
|
524
|
+
`;let h="",f=r,c=a.filter(d=>!f.includes(d.name)&&!d.name.startsWith(".")),l=a.filter(d=>f.includes(d.name)||d.name.startsWith(".")).map(d=>d.name).sort();c.sort((d,p)=>d.isDirectory()&&!p.isDirectory()?-1:!d.isDirectory()&&p.isDirectory()?1:d.name.localeCompare(p.name));let u=[...c.map(d=>({name:d.name,isDir:d.isDirectory()})),...l.map(d=>({name:d,isDir:!0,isCollapsed:!0}))];return u.forEach((d,p)=>{let g=p===u.length-1,y=ii.join(e,d.name),m=g?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",w=t+(g?" ":"\u2502 ");if(d.isCollapsed){h+=`${t}${m}${d.name}${i}...
|
|
525
525
|
`;return}d.isDir?s>n?h+=`${t}${m}${d.name}${i} ...depth exceeded...
|
|
526
526
|
`:o(y).length>80?h+=`${t}${m}${d.name}${i} ...80+ files...
|
|
527
527
|
`:(h+=`${t}${m}${d.name}${i}
|
|
528
|
-
`,h+=
|
|
529
|
-
`}),h};import"@google/genai";var It=async(e,n,t=5,s=1e3)=>{let o=n?.signal;for(let a=0;a<t;a++){if(o?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{let i=await fetch(e,n);if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),i.ok||i.status!==429&&i.status<500)return i}catch(i){if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),i.name==="AbortError"||o?.aborted||a===t-1)throw i}o?await new Promise((i,h)=>{let f=setTimeout(()=>{o.removeEventListener("abort",c),i()},Math.min(24e3,s*Math.pow(2,a))),c=()=>{clearTimeout(f),h(new DOMException("The user aborted a request.","AbortError"))};o.addEventListener("abort",c)}):await new Promise(i=>setTimeout(i,Math.min(24e3,s*Math.pow(2,a))))}if(o?.aborted)throw new DOMException("The user aborted a request.","AbortError");let r=await fetch(e,n);return typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),r};async function
|
|
530
|
-
`);p=$.pop();for(let R of $){let S=R.trim();if(!S||!S.startsWith("data: "))continue;let T=!1;if(S==="data: [DONE]")T=!0;else try{let E=JSON.parse(S.substring(6)),_=E.choices?.[0]?.delta,b=E.usage;if(E.choices?.[0]?.finish_reason&&(T=!0),b&&(y={totalTokenCount:b.total_tokens||b.prompt_tokens+b.completion_tokens,promptTokenCount:b.prompt_tokens||0,candidatesTokenCount:b.completion_tokens||0,cachedContentTokenCount:b.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:b.completion_tokens_details?.reasoning_tokens||0},w=!0),_){let C=_.reasoning_content||null;C&&(g.push({text:C,thought:!0}),w=!0),_.content&&(g.push({text:_.content}),w=!0)}}catch{}if((T||Date.now()-m>=150)&&w&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],m=Date.now(),w=!1),T)break}Date.now()-m>=150&&w&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],m=Date.now(),w=!1)}};var
|
|
531
|
-
`);w=_.pop();for(let b of _){let C=b.trim();if(!C||!C.startsWith("data: "))continue;let A=!1;if(C==="data: [DONE]")A=!0;else try{let O=JSON.parse(C.substring(6)),D=O.choices?.[0]?.delta,W=O.usage;if(O.choices?.[0]?.finish_reason&&(A=!0),W&&(k={totalTokenCount:W.total_tokens||(W.prompt_tokens||0)+(W.completion_tokens||0),promptTokenCount:W.prompt_tokens||0,candidatesTokenCount:W.completion_tokens||0,cachedContentTokenCount:W.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:W.completion_tokens_details?.reasoning_tokens||0},R=!0),D){let q=D.thinking||D.reasoning_content||D.reasoning,se=S(q);se&&(x.push({text:se,thought:!0}),R=!0);let V=D.content||(!D.thinking&&!D.reasoning_content&&!D.reasoning?D.text:null);if(V)if(Array.isArray(V))for(let F of V)if(typeof F=="object"&&F!==null){let B=F.type==="thinking"||F.type==="reasoning"||!!F.thought,Z=S(F);Z&&(x.push({text:Z,...B?{thought:!0}:{}}),R=!0)}else{let B=S(F);B&&(x.push({text:B}),R=!0)}else if(typeof V=="object"&&V!==null){let F=V.type==="thinking"||V.type==="reasoning"||!!V.thought,B=S(V);B&&(x.push({text:B,...F?{thought:!0}:{}}),R=!0)}else{let F=S(V);F&&(x.push({text:F}),R=!0)}}}catch{}if((A||Date.now()-$>=150)&&R&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:k},x=[],$=Date.now(),R=!1),A)break}Date.now()-$>=150&&R&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:k},x=[],$=Date.now(),R=!1)}};var
|
|
532
|
-
`);U=ze.pop();let bt=!1;for(let Nt of ze){let mt=Nt.trim();if(mt){if(mt==="data: [DONE]"){bt=!0;break}if(mt.startsWith("data: ")){let St;try{St=JSON.parse(mt.substring(6))}catch{continue}if(St.error)throw new Error(`NVIDIA Stream Error: ${St.error.message||JSON.stringify(St.error)}`);try{let Rt=St.usage;Rt&&(ee={totalTokenCount:Rt.total_tokens||Rt.prompt_tokens+Rt.completion_tokens,promptTokenCount:Rt.prompt_tokens||0,candidatesTokenCount:Rt.completion_tokens||0,cachedContentTokenCount:Rt.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:(Rt.completion_tokens_details?.reasoning_tokens||0)+(Rt.completion_tokens_details?.thoughts_tokens||0)},De=!0);let at=St.choices?.[0]?.delta?.reasoning||St.choices?.[0]?.delta?.reasoning_content||"",Se=St.choices?.[0]?.delta?.content||"";at&&(X.push({text:at,thought:!0}),De=!0),Se&&(X.push({text:Se}),De=!0)}catch{}}}}if((bt||Date.now()-Ue>=350)&&De&&(yield{candidates:X.length>0?[{content:{parts:[...X]}}]:[],usageMetadata:ee},V=!0,X=[],Ue=Date.now(),De=!1),bt)break}break}catch(Z){if(V||q>=se)throw Z;await new Promise(Ce=>setTimeout(Ce,3500))}}},
|
|
533
|
-
`);R=A.pop();for(let O of A){let D=O.trim();if(!D||!D.startsWith("data: "))continue;let W=!1;if(D==="data: [DONE]")W=!0;else try{let q=JSON.parse(D.substring(6));if(q.error){let F=q.error.metadata?.raw||q.error.message||JSON.stringify(q.error);throw new Error(`OpenRouter Stream Error: ${F}`)}let se=q.choices?.[0]?.delta,V=q.usage;if(q.choices?.[0]?.finish_reason&&(W=!0),V&&(T={totalTokenCount:V.total_tokens||(V.prompt_tokens||0)+(V.completion_tokens||0),promptTokenCount:V.prompt_tokens||0,candidatesTokenCount:V.completion_tokens||0,cachedContentTokenCount:V.prompt_tokens_details?.cached_tokens||V.prompt_tokens_details?.cache_read_input_tokens||V.cache_read_input_tokens||0,thoughtsTokenCount:V.completion_tokens_details?.reasoning_tokens||0},_=!0),se){let F=se.reasoning||(se.reasoning_details?se.reasoning_details.map(B=>B.text).join(""):null);F&&(S.push({text:F,thought:!0}),_=!0),se.content&&(S.push({text:se.content}),_=!0)}}catch(q){if(q.message&&q.message.startsWith("OpenRouter Stream Error:"))throw q}if((W||Date.now()-E>=150)&&_&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:T},S=[],E=Date.now(),_=!1),W)break}}};import{Ollama as hc}from"ollama";var
|
|
534
|
-
`);for(let b of S.parts){let C=b.inlineData||b.inline_data;C&&C.data&&_.push(C.data)}}else E=S.text||"";if(E||_.length>0){let b={role:T,content:E};_.length>0&&(b.images=_),c.push(b)}}let l=f==="Local"||!e||e==="LOCAL",d={host:l?process.env.OLLAMA_HOST||"http://127.0.0.1:11434":process.env.OLLAMA_HOST||"https://ollama.com"};!l&&e&&(d.headers={Authorization:"Bearer "+e});let p=new hc(d),g=[],y=null,m=Date.now(),w=!1,x={Fast:!1,Low:"medium",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},k=x[o]!==void 0?x[o]:!0,$={model:n,messages:c,stream:!0,think:k,keep_alive:"10m",options:{temperature:h}},R=await p.chat($);for await(let S of R){if(i?.aborted)throw new DOMException("The user aborted a request.","AbortError");if(S.message?.thinking&&(g.push({text:S.message.thinking,thought:!0}),w=!0),S.message?.content&&(g.push({text:S.message.content}),w=!0),S.done){let T=S.prompt_cached_count||0;if(!T&&S.prompt_eval_count){let E=S.prompt_eval_duration||0;E>0&&E<5e7&&(T=S.prompt_eval_count)}y={totalTokenCount:(S.prompt_eval_count||0)+(S.eval_count||0),promptTokenCount:S.prompt_eval_count||0,candidatesTokenCount:S.eval_count||0,cachedContentTokenCount:T,thoughtsTokenCount:0},w=!0}(S.done||Date.now()-m>=150&&w)&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],m=Date.now(),w=!1)}w&&(g.length>0||y)&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y})};var
|
|
535
|
-
`);g=R.pop();for(let S of R){let T=S.trim();if(!T||!T.startsWith("data: "))continue;let E=!1;if(T==="data: [DONE]")E=!0;else try{let _=JSON.parse(T.substring(6)),b=_.choices?.[0]?.delta,C=_.usage;if(_.choices?.[0]?.finish_reason&&(E=!0),C&&(m={totalTokenCount:C.total_tokens||(C.prompt_tokens||0)+(C.completion_tokens||0),promptTokenCount:C.prompt_tokens||0,candidatesTokenCount:C.completion_tokens||0,cachedContentTokenCount:C.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:C.completion_tokens_details?.reasoning_tokens||C.reasoning_tokens||0},x=!0),b){let A=b.reasoning_content||null;A&&(y.push({text:A,thought:!0}),x=!0),b.content&&(y.push({text:b.content}),x=!0)}}catch{}if((E||Date.now()-w>=150)&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),x=!1),E)break}Date.now()-w>=150&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),x=!1)}};var
|
|
528
|
+
`,h+=ai(y,n,w,s+1,o,r)):h+=`${t}${m}${d.name}
|
|
529
|
+
`}),h};import"@google/genai";var It=async(e,n,t=5,s=1e3)=>{let o=n?.signal;for(let a=0;a<t;a++){if(o?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{let i=await fetch(e,n);if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),i.ok||i.status!==429&&i.status<500)return i}catch(i){if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),i.name==="AbortError"||o?.aborted||a===t-1)throw i}o?await new Promise((i,h)=>{let f=setTimeout(()=>{o.removeEventListener("abort",c),i()},Math.min(24e3,s*Math.pow(2,a))),c=()=>{clearTimeout(f),h(new DOMException("The user aborted a request.","AbortError"))};o.addEventListener("abort",c)}):await new Promise(i=>setTimeout(i,Math.min(24e3,s*Math.pow(2,a))))}if(o?.aborted)throw new DOMException("The user aborted a request.","AbortError");let r=await fetch(e,n);return typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),r};async function No(e){let n=new TextEncoder().encode(e),t=await crypto.subtle.digest("SHA-256",n);return[...new Uint8Array(t).slice(0,16)].map(s=>s.toString(16).padStart(2,"0")).join("")}var Pn=e=>typeof e!="string"?e:e.replace(/<\|channel>thought/gi,"<think>").replace(/<channel\|>/gi,"</think>");var Bo=async function*(e,n,t,s,o,r,a,i,h=1){let f=[];s&&f.push({role:"system",content:s});for(let x of t){let k=x.role==="user"?"user":"assistant",$=[];if(Array.isArray(x.parts)){for(let R of x.parts)if(R.text)$.push({type:"text",text:R.text});else if(R.inlineData&&a){let S=R.inlineData.mimeType,T=R.inlineData.data;S.startsWith("image/")&&$.push({type:"image_url",image_url:{url:`data:${S};base64,${T}`}})}}else{let R=x.text||"";R&&$.push({type:"text",text:R})}f.push({role:k,content:$.length===1&&$[0].type==="text"?$[0].text:$})}let c={model:n,messages:f,stream:!0,stream_options:{include_usage:!0},temperature:h};if(o!=="Fast"){let x={Low:"high",Medium:"high",Standard:"high",High:"max",xHigh:"max"};c.reasoning_effort=x[o]||"high",c.extra_body={thinking:{type:"enabled"}}}else c.extra_body={thinking:{type:"disabled"}};let l=await It("https://api.deepseek.com/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(c),signal:i});if(!l.ok){let x=await l.json().catch(()=>({}));throw new Error(`DeepSeek Error (${l.status}): ${x.error?.message||l.statusText}`)}let u=l.body.getReader(),d=new TextDecoder,p="",g=[],y=null,m=Date.now(),w=!1;for(;;){let{done:x,value:k}=await u.read();if(x){w&&(g.length>0||y)&&(yield{candidates:g.length>0?[{content:{parts:g}}]:[],usageMetadata:y});break}p+=d.decode(k,{stream:!0});let $=p.split(`
|
|
530
|
+
`);p=$.pop();for(let R of $){let S=R.trim();if(!S||!S.startsWith("data: "))continue;let T=!1;if(S==="data: [DONE]")T=!0;else try{let E=JSON.parse(S.substring(6)),_=E.choices?.[0]?.delta,b=E.usage;if(E.choices?.[0]?.finish_reason&&(T=!0),b&&(y={totalTokenCount:b.total_tokens||b.prompt_tokens+b.completion_tokens,promptTokenCount:b.prompt_tokens||0,candidatesTokenCount:b.completion_tokens||0,cachedContentTokenCount:b.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:b.completion_tokens_details?.reasoning_tokens||0},w=!0),_){let C=_.reasoning_content||null;C&&(g.push({text:C,thought:!0}),w=!0),_.content&&(g.push({text:_.content}),w=!0)}}catch{}if((T||Date.now()-m>=150)&&w&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],m=Date.now(),w=!1),T)break}Date.now()-m>=150&&w&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],m=Date.now(),w=!1)}};var Uo=async function*(e,n,t,s,o,r,a,i,h=1,f=null){let c=[];s&&c.push({role:"system",content:s});for(let T of t){let E=T.role==="user"?"user":"assistant",_=[];if(Array.isArray(T.parts)){for(let b of T.parts)if(b.text)_.push({type:"text",text:b.text});else if(b.inlineData&&a){let C=b.inlineData.mimeType,A=b.inlineData.data;C.startsWith("image/")&&_.push({type:"image_url",image_url:`data:${C};base64,${A}`})}}else{let b=T.text||"";b&&_.push({type:"text",text:b})}_.length>0&&c.push({role:E,content:_.length===1&&_[0].type==="text"?_[0].text:_})}let l={Fast:"none",Low:"none",Medium:"high",Standard:"high",High:"high",xHigh:"high"},u=`${e.slice(-5)}${f||""}${o}${n}`,d=await No(u),p={model:n,messages:c,stream:!0,temperature:h,prompt_cache_key:d};o&&o!=="Fast"&&Cs(n)&&(p.reasoning_effort=l[o]||"high");let g=await It("https://api.mistral.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(p),signal:i});if(!g.ok){let T=await g.text().catch(()=>""),E=g.statusText;try{let _=JSON.parse(T);E=_.error?.message||_.message||JSON.stringify(_.detail||_)}catch{T&&(E=T)}throw new Error(`Mistral Error (${g.status}): ${JSON.stringify(E)}`)}let y=g.body.getReader(),m=new TextDecoder,w="",x=[],k=null,$=Date.now(),R=!1,S=T=>T?typeof T=="string"?Pn(T):Array.isArray(T)?T.map(S).filter(Boolean).join(""):typeof T=="object"&&T!==null?typeof T.text=="string"?Pn(T.text):typeof T.content=="string"?Pn(T.content):typeof T.thinking=="string"?Pn(T.thinking):typeof T.reasoning_content=="string"?Pn(T.reasoning_content):typeof T.reasoning=="string"?Pn(T.reasoning):typeof T.value=="string"?Pn(T.value):T.text?S(T.text):T.content?S(T.content):T.thinking?S(T.thinking):T.reasoning_content?S(T.reasoning_content):T.reasoning?S(T.reasoning):T.value?S(T.value):"":Pn(String(T)):"";for(;;){let{done:T,value:E}=await y.read();if(T){R&&(x.length>0||k)&&(yield{candidates:x.length>0?[{content:{parts:x}}]:[],usageMetadata:k});break}w+=m.decode(E,{stream:!0});let _=w.split(`
|
|
531
|
+
`);w=_.pop();for(let b of _){let C=b.trim();if(!C||!C.startsWith("data: "))continue;let A=!1;if(C==="data: [DONE]")A=!0;else try{let O=JSON.parse(C.substring(6)),D=O.choices?.[0]?.delta,W=O.usage;if(O.choices?.[0]?.finish_reason&&(A=!0),W&&(k={totalTokenCount:W.total_tokens||(W.prompt_tokens||0)+(W.completion_tokens||0),promptTokenCount:W.prompt_tokens||0,candidatesTokenCount:W.completion_tokens||0,cachedContentTokenCount:W.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:W.completion_tokens_details?.reasoning_tokens||0},R=!0),D){let q=D.thinking||D.reasoning_content||D.reasoning,se=S(q);se&&(x.push({text:se,thought:!0}),R=!0);let V=D.content||(!D.thinking&&!D.reasoning_content&&!D.reasoning?D.text:null);if(V)if(Array.isArray(V))for(let F of V)if(typeof F=="object"&&F!==null){let B=F.type==="thinking"||F.type==="reasoning"||!!F.thought,Z=S(F);Z&&(x.push({text:Z,...B?{thought:!0}:{}}),R=!0)}else{let B=S(F);B&&(x.push({text:B}),R=!0)}else if(typeof V=="object"&&V!==null){let F=V.type==="thinking"||V.type==="reasoning"||!!V.thought,B=S(V);B&&(x.push({text:B,...F?{thought:!0}:{}}),R=!0)}else{let F=S(V);F&&(x.push({text:F}),R=!0)}}}catch{}if((A||Date.now()-$>=150)&&R&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:k},x=[],$=Date.now(),R=!1),A)break}Date.now()-$>=150&&R&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:k},x=[],$=Date.now(),R=!1)}};var Wo=async function*(e,n,t,s,o,r,a=!1,i,h=1){let f=[];s&&f.push({role:"system",content:s}),t.forEach(Z=>{let Ce=Z.role==="model"?"assistant":"user",v=[];Array.isArray(Z.parts)&&Z.parts.forEach(U=>{if(U.text)v.push({type:"text",text:U.text});else if(U.inlineData&&a){let X=U.inlineData.mimeType,ee=U.inlineData.data;X.startsWith("image/")&&At(n)&&v.push({type:"image_url",image_url:{url:`data:${X};base64,${ee}`}})}}),f.push({role:Ce,content:v.length===1&&v[0].type==="text"?v[0].text:v})});let l={Fast:"Fast",Low:"Fast",Medium:"Standard",Standard:"Standard",High:"High",xHigh:"High"}[o]||"High",u=l!=="Fast",d=n.includes("kimi"),p=n.includes("gemma"),g=n.includes("deepseek"),y=n.includes("glm"),m=n.includes("mistral"),w=n.includes("minimax"),x=n.includes("gpt"),k=n.includes("qwen"),$=n.includes("nemotron"),R=n.includes("llama-3"),S=n.includes("seed"),T=n.includes("poolside"),E=n.includes("thinkingmachines")||n.includes("muse"),_=R,b=null,C={Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},A={Fast:"64",Low:"64",Medium:"4096",Standard:"4096",High:"16384",xHigh:"16384"},O={Fast:"none",Low:"minimal",Medium:"medium",Standard:"medium",High:"max",xHigh:"max"},D=w||g||T||E?16384:32768;D=process.env.NVIDIA_BASE_URL?1024:D,D=b?1024:D;let W={model:n,messages:f,max_tokens:D,stream:!0,stream_options:{include_usage:!0},temperature:h,...x&&{thinking:C[o]||"high"}};if(!(process.env.NVIDIA_BASE_URL||_||b))if(d)W.chat_template_kwargs={thinking:u};else if(p)W.chat_template_kwargs={enable_thinking:u};else if(g)if(u){let Z=l==="High"?"max":"high";W.chat_template_kwargs={thinking:!0,reasoning_effort:Z}}else W.chat_template_kwargs={thinking:!1};else y?W.chat_template_kwargs={enable_thinking:u,clear_thinking:!u}:m?W.reasoning_effort=u?"high":"none":w&&n.includes("minimax-m3")?W.chat_template_kwargs={thinking_mode:u?"enabled":"disabled"}:k?W.chat_template_kwargs={enable_thinking:u}:$?l==="High"?W.chat_template_kwargs={enable_thinking:!0}:l==="Standard"?W.chat_template_kwargs={enable_thinking:!0,medium_effort:!0}:W.chat_template_kwargs={enable_thinking:!1}:S?u&&(W.extra_body={thinking_budget:parseInt(A[l]??"4096")}):T?W.chat_template_kwargs={enable_thinking:u}:E&&(W.reasoning_effort=O[l]||"medium");let q=0,se=6,V=!1,F=process.env.NVIDIA_BASE_URL||"https://integrate.api.nvidia.com/v1/chat/completions",B=process.env.NVIDIA_API_KEY&&process.env.NVIDIA_BASE_URL?process.env.NVIDIA_API_KEY:e;for(F.endsWith("/chat/completions")||(F=F.replace(/\/+$/,"")+"/chat/completions");q<se;){q++;try{let Z=await It(F,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${B}`},body:JSON.stringify(W),signal:i});if(!Z.ok){let je=await Z.text().catch(()=>""),it=Z.statusText;try{let bt=JSON.parse(je);it=bt.error?.message||bt.message||JSON.stringify(bt.detail||bt)}catch{je&&(it=je)}let ze=new Error(`NVIDIA API Error (${Z.status}): ${it}`);throw ze.status=Z.status,ze}let Ce=Z.body.getReader(),v=new TextDecoder,U="",X=[],ee=null,Ue=Date.now(),De=!1;for(;;){let{done:je,value:it}=await Ce.read();if(je){De&&(X.length>0||ee)&&(yield{candidates:X.length>0?[{content:{parts:X}}]:[],usageMetadata:ee},V=!0);break}U+=v.decode(it,{stream:!0});let ze=U.split(`
|
|
532
|
+
`);U=ze.pop();let bt=!1;for(let Nt of ze){let mt=Nt.trim();if(mt){if(mt==="data: [DONE]"){bt=!0;break}if(mt.startsWith("data: ")){let St;try{St=JSON.parse(mt.substring(6))}catch{continue}if(St.error)throw new Error(`NVIDIA Stream Error: ${St.error.message||JSON.stringify(St.error)}`);try{let Rt=St.usage;Rt&&(ee={totalTokenCount:Rt.total_tokens||Rt.prompt_tokens+Rt.completion_tokens,promptTokenCount:Rt.prompt_tokens||0,candidatesTokenCount:Rt.completion_tokens||0,cachedContentTokenCount:Rt.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:(Rt.completion_tokens_details?.reasoning_tokens||0)+(Rt.completion_tokens_details?.thoughts_tokens||0)},De=!0);let at=St.choices?.[0]?.delta?.reasoning||St.choices?.[0]?.delta?.reasoning_content||"",Se=St.choices?.[0]?.delta?.content||"";at&&(X.push({text:at,thought:!0}),De=!0),Se&&(X.push({text:Se}),De=!0)}catch{}}}}if((bt||Date.now()-Ue>=350)&&De&&(yield{candidates:X.length>0?[{content:{parts:[...X]}}]:[],usageMetadata:ee},V=!0,X=[],Ue=Date.now(),De=!1),bt)break}break}catch(Z){if(V||q>=se)throw Z;await new Promise(Ce=>setTimeout(Ce,3500))}}},Ca=async function*(e,n){let t=[],s=null,o=!1,r=null,a=u=>{if(t.push(u),s){let d=s;s=null,d()}},i=n.split("/").pop();i=i.replace("llama-3.3","llama-3_3");let h=`https://api.ngc.nvidia.com/v2/predict/queues/models/qc69jvmznzxy/${i}`,f=!1,c=null,l=async()=>{try{let u=await fetch(h);if(u.ok){let d=await u.json();if(d&&d.queues&&d.queues[0]&&typeof d.queues[0].queueDepth=="number"){let p=d.queues[0].queueDepth;f||a({value:{type:"status",content:`Queue ${p||1}`},done:!1})}}}catch{}};process.env.NVIDIA_BASE_URL||(l(),c=setInterval(l,5e3)),(async()=>{try{let u=e[Symbol.asyncIterator]();for(;;){let{value:d,done:p}=await u.next();if(p)break;f=!0,c&&(clearInterval(c),c=null),a({value:d,done:!1})}o=!0,a(null)}catch(u){if(r=u,c&&(clearInterval(c),c=null),s){let d=s;s=null,d()}}})();try{for(;;){if(r)throw r;if(t.length>0){let u=t.shift();if(u===null&&o)break;yield u.value}else{if(o)break;await new Promise(u=>{s=u})}}}finally{c&&(clearInterval(c),c=null)}};var jo=async function*(e,n,t,s,o,r,a,i,h=1,f=null){let c=[];s&&c.push({role:"system",content:[{type:"text",text:s}]});for(let b of t){let C=b.role==="user"?"user":"assistant",A=[];if(Array.isArray(b.parts)){for(let O of b.parts)if(O.text)A.push({type:"text",text:O.text});else if(O.inlineData&&a){let D=O.inlineData.mimeType,W=O.inlineData.data;D.startsWith("image/")?A.push({type:"image_url",image_url:{url:`data:${D};base64,${W}`}}):A.push({type:"file",file:{filename:O.filename||"file",file_data:`data:${D};base64,${W}`}})}}else{let O=b.text||"";O&&A.push({type:"text",text:O})}c.push({role:C,content:A.length===1&&A[0].type==="text"?A[0].text:A})}let l={Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},u=["free","nitro","floor","exact","extended","beta","online"],d=n,p=null;if(n.includes(":")){let b=n.split(":"),C=b[b.length-1].toLowerCase().trim();if(u.includes(C))d=n.trim();else{let A=b.pop().trim();d=b.join(":").trim(),A&&(p={order:[A],allow_fallbacks:!1})}}let g=`${e.slice(-5)}${f||""}${o}${d}${p?JSON.stringify(p):""}`,y=await No(g),m={model:d,messages:c,stream:!0,temperature:h,cache_control:{type:"ephemeral"},session_id:y};p&&(m.provider=p);let w=l[o];w&&o!=="Fast"&&(m.reasoning_effort=w);let x=await It("https://openrouter.ai/api/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json","HTTP-Referer":"https://fluxflow-cli.onrender.com/","X-Title":"FluxFlow CLI","X-OpenRouter-Title":"FluxFlow CLI","X-Cache":"true","X-OpenRouter-Cache":"true"},body:JSON.stringify(m),signal:i});if(!x.ok){let b=await x.json().catch(()=>({})),C=b.error?.metadata?.raw||b.error?.message||(typeof b.error=="string"?b.error:"")||x.statusText||"Unknown error";throw new Error(`OpenRouter Error (${x.status}): ${C}`)}let k=x.body.getReader(),$=new TextDecoder,R="",S=[],T=null,E=Date.now(),_=!1;for(;;){let{done:b,value:C}=await k.read();if(b){_&&(S.length>0||T)&&(yield{candidates:S.length>0?[{content:{parts:S}}]:[],usageMetadata:T});break}R+=$.decode(C,{stream:!0});let A=R.split(`
|
|
533
|
+
`);R=A.pop();for(let O of A){let D=O.trim();if(!D||!D.startsWith("data: "))continue;let W=!1;if(D==="data: [DONE]")W=!0;else try{let q=JSON.parse(D.substring(6));if(q.error){let F=q.error.metadata?.raw||q.error.message||JSON.stringify(q.error);throw new Error(`OpenRouter Stream Error: ${F}`)}let se=q.choices?.[0]?.delta,V=q.usage;if(q.choices?.[0]?.finish_reason&&(W=!0),V&&(T={totalTokenCount:V.total_tokens||(V.prompt_tokens||0)+(V.completion_tokens||0),promptTokenCount:V.prompt_tokens||0,candidatesTokenCount:V.completion_tokens||0,cachedContentTokenCount:V.prompt_tokens_details?.cached_tokens||V.prompt_tokens_details?.cache_read_input_tokens||V.cache_read_input_tokens||0,thoughtsTokenCount:V.completion_tokens_details?.reasoning_tokens||0},_=!0),se){let F=se.reasoning||(se.reasoning_details?se.reasoning_details.map(B=>B.text).join(""):null);F&&(S.push({text:F,thought:!0}),_=!0),se.content&&(S.push({text:se.content}),_=!0)}}catch(q){if(q.message&&q.message.startsWith("OpenRouter Stream Error:"))throw q}if((W||Date.now()-E>=150)&&_&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:T},S=[],E=Date.now(),_=!1),W)break}}};import{Ollama as hc}from"ollama";var li=async function*(e,n,t,s,o,r,a,i,h=1,f="Cloud"){let c=[];s&&c.push({role:"system",content:s});for(let S of t){let T=S.role==="user"?"user":"assistant",E="",_=[];if(Array.isArray(S.parts)){E=S.parts.map(b=>b.text||"").filter(Boolean).join(`
|
|
534
|
+
`);for(let b of S.parts){let C=b.inlineData||b.inline_data;C&&C.data&&_.push(C.data)}}else E=S.text||"";if(E||_.length>0){let b={role:T,content:E};_.length>0&&(b.images=_),c.push(b)}}let l=f==="Local"||!e||e==="LOCAL",d={host:l?process.env.OLLAMA_HOST||"http://127.0.0.1:11434":process.env.OLLAMA_HOST||"https://ollama.com"};!l&&e&&(d.headers={Authorization:"Bearer "+e});let p=new hc(d),g=[],y=null,m=Date.now(),w=!1,x={Fast:!1,Low:"medium",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},k=x[o]!==void 0?x[o]:!0,$={model:n,messages:c,stream:!0,think:k,keep_alive:"10m",options:{temperature:h}},R=await p.chat($);for await(let S of R){if(i?.aborted)throw new DOMException("The user aborted a request.","AbortError");if(S.message?.thinking&&(g.push({text:S.message.thinking,thought:!0}),w=!0),S.message?.content&&(g.push({text:S.message.content}),w=!0),S.done){let T=S.prompt_cached_count||0;if(!T&&S.prompt_eval_count){let E=S.prompt_eval_duration||0;E>0&&E<5e7&&(T=S.prompt_eval_count)}y={totalTokenCount:(S.prompt_eval_count||0)+(S.eval_count||0),promptTokenCount:S.prompt_eval_count||0,candidatesTokenCount:S.eval_count||0,cachedContentTokenCount:T,thoughtsTokenCount:0},w=!0}(S.done||Date.now()-m>=150&&w)&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],m=Date.now(),w=!1)}w&&(g.length>0||y)&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y})};var Ho=async function*(e,n,t,s,o,r,a,i,h=1){let f=[];s&&f.push({role:"system",content:s});for(let k of t){let $=k.role==="user"?"user":"assistant",R=[];if(Array.isArray(k.parts)){for(let S of k.parts)if(S.text)R.push({type:"text",text:S.text});else if(S.inlineData&&a){let T=S.inlineData.mimeType,E=S.inlineData.data;T.startsWith("image/")&&R.push({type:"image_url",image_url:{url:`data:${T};base64,${E}`}})}}else{let S=k.text||"";S&&R.push({type:"text",text:S})}f.push({role:$,content:R.length===1&&R[0].type==="text"?R[0].text:R})}let c={Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},l={model:n,messages:f,stream:!0,stream_options:{include_usage:!0},temperature:h,max_completion_tokens:32768};c[o]&&(l.reasoning_effort=c[o]);let u=await It("https://crof.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(l),signal:i});if(!u.ok){let k=await u.json().catch(()=>({}));throw new Error(`CrofAI Error (${u.status}): ${k.error?.message||u.statusText}`)}let d=u.body.getReader(),p=new TextDecoder,g="",y=[],m=null,w=Date.now(),x=!1;for(;;){let{done:k,value:$}=await d.read();if(k){x&&(y.length>0||m)&&(yield{candidates:y.length>0?[{content:{parts:y}}]:[],usageMetadata:m});break}g+=p.decode($,{stream:!0});let R=g.split(`
|
|
535
|
+
`);g=R.pop();for(let S of R){let T=S.trim();if(!T||!T.startsWith("data: "))continue;let E=!1;if(T==="data: [DONE]")E=!0;else try{let _=JSON.parse(T.substring(6)),b=_.choices?.[0]?.delta,C=_.usage;if(_.choices?.[0]?.finish_reason&&(E=!0),C&&(m={totalTokenCount:C.total_tokens||(C.prompt_tokens||0)+(C.completion_tokens||0),promptTokenCount:C.prompt_tokens||0,candidatesTokenCount:C.completion_tokens||0,cachedContentTokenCount:C.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:C.completion_tokens_details?.reasoning_tokens||C.reasoning_tokens||0},x=!0),b){let A=b.reasoning_content||null;A&&(y.push({text:A,thought:!0}),x=!0),b.content&&(y.push({text:b.content}),x=!0)}}catch{}if((E||Date.now()-w>=150)&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),x=!1),E)break}Date.now()-w>=150&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),x=!1)}};var Go=async function*(e,n,t,s,o,r,a,i,h=1){let f=[];s&&f.push({role:"system",content:s});for(let S of t){let T=S.role==="user"?"user":"assistant",E="";if(Array.isArray(S.parts))for(let _ of S.parts)_.text&&(E+=(E?`
|
|
536
536
|
`:"")+_.text);else E=S.text||"";f.push({role:T,content:E})}let c={Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},l=n&&n.toLowerCase().includes("qwen3.8-27b"),u=n&&(n.toLowerCase().includes("qwen3.8-27b")||n.toLowerCase().includes("qwen3.6-35b-a3b-fp8")),d={model:n,messages:f.filter(S=>S.content&&String(S.content).trim().length>0),stream:!0,stream_options:{include_usage:!0},temperature:h};l||(d.stream_options={include_usage:!0},c[o]&&(d.reasoning_effort=c[o]));let p=await It("https://model.inferx.net/endpoints/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(d),signal:i});if(!p.ok){let S=await p.text().catch(()=>""),T="";try{let E=JSON.parse(S);T=E.error?.message||E.error?.detail||E.message||E.detail||(typeof E.error=="string"?E.error:"")||(S&&S!=="{}"?S:"")}catch{T=S}throw(!T||T==="{}")&&(T=p.statusText||"Unknown error"),new Error(`InferX Error (${p.status}): ${T}`)}let g=p.body.getReader(),y=new TextDecoder,m="",w=[],x=null,k=Date.now(),$=!1,R=!0;for(;;){let{done:S,value:T}=await g.read();if(S){$&&(w.length>0||x)&&(yield{candidates:w.length>0?[{content:{parts:w}}]:[],usageMetadata:x});break}m+=y.decode(T,{stream:!0});let E=m.split(`
|
|
537
|
-
`);m=E.pop();for(let _ of E){let b=_.trim();if(!b||!b.startsWith("data: "))continue;let C=!1;if(b==="data: [DONE]")C=!0;else try{let A=JSON.parse(b.substring(6)),O=A.choices?.[0]?.delta,D=A.usage;if(D&&(x={totalTokenCount:D.total_tokens||(D.prompt_tokens||0)+(D.completion_tokens||0),promptTokenCount:D.prompt_tokens||0,candidatesTokenCount:D.completion_tokens||0,cachedContentTokenCount:D.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:D.completion_tokens_details?.reasoning_tokens||D.reasoning_tokens||0},$=!0),O){let W=O.reasoning||O.reasoning_content||null;if(W&&(w.push({text:W,thought:!0}),$=!0),O.content){let q=O.content;u&&R&&q.length>0&&(q="<think>"+q,R=!1),w.push({text:q}),$=!0}}}catch{}if((C||Date.now()-k>=150||x)&&$&&(yield{candidates:w.length>0?[{content:{parts:[...w]}}]:[],usageMetadata:x},w=[],k=Date.now(),$=!1),C)break}Date.now()-k>=150&&$&&(yield{candidates:w.length>0?[{content:{parts:[...w]}}]:[],usageMetadata:x},w=[],k=Date.now(),$=!1)}};var
|
|
538
|
-
`);g=R.pop();for(let S of R){let T=S.trim();if(!T||!T.startsWith("data: "))continue;let E=!1;if(T==="data: [DONE]")E=!0;else try{let _=JSON.parse(T.substring(6)),b=_.choices?.[0]?.delta,C=_.usage;if(C&&(m={totalTokenCount:C.total_tokens||(C.prompt_tokens||0)+(C.completion_tokens||0),promptTokenCount:C.prompt_tokens||0,candidatesTokenCount:C.completion_tokens||0,cachedContentTokenCount:C.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:C.completion_tokens_details?.reasoning_tokens||C.reasoning_tokens||0},x=!0),b){let A=b.reasoning||b.reasoning_content||null;A&&(y.push({text:A,thought:!0}),x=!0),b.content&&(y.push({text:b.content}),x=!0)}}catch{}if((E||Date.now()-w>=150||m)&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),x=!1),E)break}Date.now()-w>=150&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),x=!1)}};var
|
|
539
|
-
`);g=R.pop();for(let S of R){let T=S.trim();if(!T||!T.startsWith("data: "))continue;let E=!1;if(T==="data: [DONE]")E=!0;else try{let _=JSON.parse(T.substring(6)),b=_.choices?.[0]?.delta,C=_.usage;if(_.choices?.[0]?.finish_reason&&(E=!0),C&&(m={totalTokenCount:C.total_tokens||(C.prompt_tokens||0)+(C.completion_tokens||0),promptTokenCount:C.prompt_tokens||0,candidatesTokenCount:C.completion_tokens||0,cachedContentTokenCount:C.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:C.completion_tokens_details?.reasoning_tokens||C.reasoning_tokens||0},x=!0),b){let A=b.reasoning_content||null;A&&(y.push({text:A,thought:!0}),x=!0),b.content&&(y.push({text:b.content}),x=!0)}}catch{}if((E||Date.now()-w>=150)&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),x=!1),E)break}Date.now()-w>=150&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),x=!1)}};
|
|
540
|
-
`),g=d.toLowerCase().includes("tool:functions.")||d.toLowerCase().includes("agent:generalist.");a.push(d),g&&p?h=!0:h=!1}}}),f()}}return t.length},Ic=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),eg=()=>{Mt=!0},tg=()=>Mt,
|
|
537
|
+
`);m=E.pop();for(let _ of E){let b=_.trim();if(!b||!b.startsWith("data: "))continue;let C=!1;if(b==="data: [DONE]")C=!0;else try{let A=JSON.parse(b.substring(6)),O=A.choices?.[0]?.delta,D=A.usage;if(D&&(x={totalTokenCount:D.total_tokens||(D.prompt_tokens||0)+(D.completion_tokens||0),promptTokenCount:D.prompt_tokens||0,candidatesTokenCount:D.completion_tokens||0,cachedContentTokenCount:D.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:D.completion_tokens_details?.reasoning_tokens||D.reasoning_tokens||0},$=!0),O){let W=O.reasoning||O.reasoning_content||null;if(W&&(w.push({text:W,thought:!0}),$=!0),O.content){let q=O.content;u&&R&&q.length>0&&(q="<think>"+q,R=!1),w.push({text:q}),$=!0}}}catch{}if((C||Date.now()-k>=150||x)&&$&&(yield{candidates:w.length>0?[{content:{parts:[...w]}}]:[],usageMetadata:x},w=[],k=Date.now(),$=!1),C)break}Date.now()-k>=150&&$&&(yield{candidates:w.length>0?[{content:{parts:[...w]}}]:[],usageMetadata:x},w=[],k=Date.now(),$=!1)}};var qo=async function*(e,n,t,s,o,r,a,i,h=1){let f=[];s&&f.push({role:"system",content:s});for(let k of t){let $=k.role==="user"?"user":"assistant",R=[];if(Array.isArray(k.parts)){for(let S of k.parts)if(S.text)R.push({type:"text",text:S.text});else if(S.inlineData&&a){let T=S.inlineData.mimeType,E=S.inlineData.data;T.startsWith("image/")&&R.push({type:"image_url",image_url:{url:`data:${T};base64,${E}`}})}}else{let S=k.text||"";S&&R.push({type:"text",text:S})}f.push({role:$,content:R.length===1&&R[0].type==="text"?R[0].text:R})}let c={Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},l={model:n,messages:f,stream:!0,stream_options:{include_usage:!0},temperature:h};c[o]&&(l.reasoning_effort=c[o]);let u=await It("https://token.sensenova.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(l),signal:i});if(!u.ok){let k=await u.json().catch(()=>({}));throw new Error(`SenseNova Error (${u.status}): ${k.error?.message||u.statusText}`)}let d=u.body.getReader(),p=new TextDecoder,g="",y=[],m=null,w=Date.now(),x=!1;for(;;){let{done:k,value:$}=await d.read();if(k){x&&(y.length>0||m)&&(yield{candidates:y.length>0?[{content:{parts:y}}]:[],usageMetadata:m});break}g+=p.decode($,{stream:!0});let R=g.split(`
|
|
538
|
+
`);g=R.pop();for(let S of R){let T=S.trim();if(!T||!T.startsWith("data: "))continue;let E=!1;if(T==="data: [DONE]")E=!0;else try{let _=JSON.parse(T.substring(6)),b=_.choices?.[0]?.delta,C=_.usage;if(C&&(m={totalTokenCount:C.total_tokens||(C.prompt_tokens||0)+(C.completion_tokens||0),promptTokenCount:C.prompt_tokens||0,candidatesTokenCount:C.completion_tokens||0,cachedContentTokenCount:C.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:C.completion_tokens_details?.reasoning_tokens||C.reasoning_tokens||0},x=!0),b){let A=b.reasoning||b.reasoning_content||null;A&&(y.push({text:A,thought:!0}),x=!0),b.content&&(y.push({text:b.content}),x=!0)}}catch{}if((E||Date.now()-w>=150||m)&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),x=!1),E)break}Date.now()-w>=150&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),x=!1)}};var zo=async function*(e,n,t,s,o,r,a,i,h=1){let f=[];s&&f.push({role:"system",content:s});for(let k of t){let $=k.role==="user"?"user":"assistant",R=[];if(Array.isArray(k.parts)){for(let S of k.parts)if(S.text)R.push({type:"text",text:S.text});else if(S.inlineData&&a){let T=S.inlineData.mimeType,E=S.inlineData.data;T.startsWith("image/")&&R.push({type:"image_url",image_url:{url:`data:${T};base64,${E}`}})}}else{let S=k.text||"";S&&R.push({type:"text",text:S})}f.push({role:$,content:R.length===1&&R[0].type==="text"?R[0].text:R})}let c={Fast:"minimal",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},l={model:n,messages:f,stream:!0,stream_options:{include_usage:!0},temperature:h};c[o]&&(l.reasoning_effort=c[o]);let u=await It("https://aihubmix.com/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(l),signal:i});if(!u.ok){let k=await u.json().catch(()=>({}));throw new Error(`AIHubMix Error (${u.status}): ${k.error?.message||u.statusText}`)}let d=u.body.getReader(),p=new TextDecoder,g="",y=[],m=null,w=Date.now(),x=!1;for(;;){let{done:k,value:$}=await d.read();if(k){x&&(y.length>0||m)&&(yield{candidates:y.length>0?[{content:{parts:y}}]:[],usageMetadata:m});break}g+=p.decode($,{stream:!0});let R=g.split(`
|
|
539
|
+
`);g=R.pop();for(let S of R){let T=S.trim();if(!T||!T.startsWith("data: "))continue;let E=!1;if(T==="data: [DONE]")E=!0;else try{let _=JSON.parse(T.substring(6)),b=_.choices?.[0]?.delta,C=_.usage;if(_.choices?.[0]?.finish_reason&&(E=!0),C&&(m={totalTokenCount:C.total_tokens||(C.prompt_tokens||0)+(C.completion_tokens||0),promptTokenCount:C.prompt_tokens||0,candidatesTokenCount:C.completion_tokens||0,cachedContentTokenCount:C.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:C.completion_tokens_details?.reasoning_tokens||C.reasoning_tokens||0},x=!0),b){let A=b.reasoning_content||null;A&&(y.push({text:A,thought:!0}),x=!0),b.content&&(y.push({text:b.content}),x=!0)}}catch{}if((E||Date.now()-w>=150)&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),x=!1),E)break}Date.now()-w>=150&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),x=!1)}};di.config({quiet:!0});di.config({path:"./fluxflow.env",override:!0,quiet:!0});di.config({path:"./.fluxflow.env",override:!0,quiet:!0});var mc=/```[\s\S]*?```/g,gc=/```[\s\S]*$/g,yc=/`[^`]+`/g,wc=/^\|.*\|$/gm,xc=/^[^\w]+|[^\w]+$/g,bc=/[^a-z0-9]/gi,uo=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,Sc=/\[\s*(?:tool:functions\.|agent:generalist\.)([a-z0-9_]+)\s*\(/gi,kc=/(?:path|targetFile|TargetFile|directory|keyword|id|taskId|title|task)\s*=\s*\\?["']?([^\\"' \),]+)/,ys=/["']/g,Ma=/\\/g,Tc=/<\|channel>thought/gi,Rc=/<channel\|>/gi,Ec=e=>typeof e!="string"?e:e.replace(Tc,"<think>").replace(Rc,"</think>"),Zm=/^\s*(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\]|$)/i,_c=(e,n)=>{let t=!1;for(let s=0;s<n;s++)e[s]==="`"&&(t=!t);return t},$c=e=>{let n=/(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\])/gi,t;for(;(t=n.exec(e))!==null;)if(!_c(e,t.index))return{index:t.index,length:t[0].length};return{index:-1,length:0}},ci=e=>{if(!e||typeof e!="string")return null;let n=e.match(/^\s*(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought|\[(think|thought|thoughts)\])/i);if(!n)return null;let t=n.index+n[0].length,s=e.substring(t),o=$c(s);if(o.index!==-1){let r=t+o.index+o.length;return{fullBlock:e.substring(0,r),innerContent:s.substring(0,o.index),remainingText:e.substring(r)}}return{fullBlock:e,innerContent:s,remainingText:""}},nn=e=>{if(!e||typeof e!="string")return e;let n=ci(e);return n?n.remainingText.trimStart():e};var Da=/`[^`]*`/g,Fa=/`[^`]*$/,Aa=/<\|\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,Cc=/"([^"]+)"\s*:\s*(?:"([^"]*)"|(\d+)|true|false|null)/g,va=/<\|\s*tool_calls_section_begin\s*\|>/gi,Ia=/<\|\s*tool_calls_section_end\s*\|>/gi,Mc=/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi;var Oa=e=>!e||typeof e!="string"?e:e.replace(/(```[\s\S]*?```|`[^`]*`)|(<(?:\w+)(?:[^>]*)>\r?\n?|\r?\n?<\/\w+(?:[^>]*)>)/gi,(n,t)=>t||""),ui=null,Ko={},ws={key:null,value:null},tn=e=>e&&e.replace(/(?:(\x1b\[\d+m))?([✔✘✖🔍📖→➕↻↷•🛇])(?:(\x1b\[\d+m))?\s*\b(Clicked|Dragged|Scrolled|Typed|Pressed Key|Recaptured Screen|Created|Read Skill|Read|Edited|Viewed|Processed|Auto-Read|Skipped|List|Generated|Written|Searched|AI Search|Get Map|Write Canceled|Resolved Sub-Agent Query|Edit Canceled|Write Cancelled|Edit Denied|Visited|Updated|Reviewed|Delegated|Background|Checked|Indexed|Analyzed|Browsed|Elevating SubAgent|Checking SubAgent Work|Started Generalist|Called Generalist|Steered|Unsupported Modality|Awaiting|Cancelled|Aligning Moon Phase|Contemplating Existence|Staring At Void|Rollback Point Checked|Emergency Rollback Failed|Emergency Rollback|Delaying Professionally|Negotiating With Electrons|Touching Grass (virtually)|Panicking Softly|Rethinking Career Choices|Loading Cat Videos|Giving Up Entirely|Summoning Braincell #2|Pretending To Be Busy|Waiting For Motivation DLC|Rotating Internal Screaming|Downloading More RAM|Feeding The Hamsters|Gaslighting Scheduler|Performing Dramatic Pause|Buffering Social Energy|Calculating Regret|Reading Terms And Conditions|Becoming Sentient Briefly|Execution Error|Loop Detected|Contacting Ancestors)\b/ig,(n,t,s,o,r)=>`${t||""}${s}${o||""} \x1B[95m${r}\x1B[0m`),Ac=async(e,n=8,t=1e3,s=8e3,o=null)=>{let r=0;for(;;){if(o?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{return await e()}catch(a){if(o?.aborted||a?.name==="AbortError"||a?.message==="Subagent task was cancelled."||(r++,r>=n))throw a;let i=Math.min(t*Math.pow(2,r-1),s);await new Promise((h,f)=>{let c=setTimeout(h,i);o&&o.addEventListener("abort",()=>{clearTimeout(c),f(new DOMException("The user aborted a request.","AbortError"))})})}}},Mt=!1;var vc=e=>{let n=e.filter(o=>(o.role==="user"||o.role==="agent"||o.role==="system")&&o.role!=="think"&&!o.isVisualFeedback&&!o.isMeta&&!o.isTerminalRecord&&!(o.text&&o.text.includes("[TERMINAL_RECORD]"))&&!String(o.id).startsWith("welcome")).map((o,r,a)=>{let i=o.fullText||o.text||"";if(o.role==="user"&&r<a.length-1)if(i.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")){let h=i.indexOf("**CONTEXT SUMMARY OF PREVIOUS TURNS");if(h!==-1){let c=i.substring(0,h).lastIndexOf("[SYSTEM METADATA]");c!==-1?i=i.substring(c).trim():i=i.substring(h).trim()}}else{let h=i.lastIndexOf("[USER]"),f=i.lastIndexOf("[USER PROMPT]");h!==-1?i=i.substring(h+6).trim():f!==-1&&(i=i.substring(f).trim())}return{...o,text:i}}),t=[],s=0;for(;s<n.length;){let o=n[s];if(o.role==="user")t.push(o),s++;else{let r=[];for(;s<n.length&&n[s].role!=="user";)r.push(n[s]),s++;let a=[],i=[],h=!1,f=()=>{a.length>0&&(t.push({role:"agent",text:"combined"}),a=[]),i.length>0&&(t.push({role:"system",text:"combined"}),i=[]),h=!1};r.forEach(c=>{let l=c.role==="system"&&(c.text?.startsWith("[TOOL RESULT]")||c.text?.startsWith("SUCCESS:")||c.text?.startsWith("ERROR:")||c.fullText?.startsWith("[TOOL RESULT]")||c.fullText?.startsWith("SUCCESS:")||c.fullText?.startsWith("ERROR:")),u=c.fullText||c.text||"",d=u.trim();if(!(!d&&!c.binaryPart)){if(l)i.push(d);else if(c.role==="agent"){!h&&i.length>0&&f();let p=u.endsWith(`
|
|
540
|
+
`),g=d.toLowerCase().includes("tool:functions.")||d.toLowerCase().includes("agent:generalist.");a.push(d),g&&p?h=!0:h=!1}}}),f()}}return t.length},Ic=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),eg=()=>{Mt=!0},tg=()=>Mt,fi={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=L(n),s=e.toLowerCase().replace(/_/g,"");if(s==="invokesync"||s==="invoke")return t.title||(t.task?t.task.substring(0,30):null);if(s==="getprogress"||s==="cancel"||s==="steer"||s==="steersubagent")return t.id||t.taskId;let o=t.path||t.targetFile||t.TargetFile||t.directory;return o?Q.basename(o.replace(/["']/g,"").replace(/\\/g,"/")):null}catch{return null}},pi=e=>e?new Pa({apiKey:e}):ui,ng=async(e,n,t,s,o={})=>{let{onStatus:i,onMemoryUpdated:h,onBackgroundIncrement:f}=o,{profile:c,thinkingLevel:l,mode:u,janitorModel:d,chatId:p,systemSettings:g,sessionStats:y,aiProvider:m="Google",apiKey:w}=e,x=process.env.NVIDIA_BASE_URL||m==="Ollama"||m==="CrofAI"||m==="InferX"||m==="SenseNova"||m==="AIHubMix"?!1:g?.memory!==!1,$=ne(Dt,[]).map(v=>`- [${v.id}]: ${v.memory}`).join(`
|
|
541
541
|
`),R=s.slice(0,-1).filter(v=>v.text&&!v.text.includes("[TOOL RESULT]")&&!v.text.includes("OBSERVATION:")&&!v.text.startsWith("[TERMINAL_RECORD]")&&!v.isTerminalRecord&&!v.isMeta&&!v.isLogo&&!String(v.id).startsWith("welcome")&&!String(v.id).startsWith("logo")).slice(-14).map(v=>{let U=nn(Ic(v.text)).replace(/\[tool:functions\..*?\]/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[METADATA \(PRIORITY: DYNAMIC\)\] Time: ([^|\n]+)/g,(De,je)=>`[METADATA (PRIORITY: DYNAMIC)] Time: ${je.replace(/:\d{2}/g,"")}`).replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[TOOL RESULTS\]/g,"").replace(/\[tool results\]/g,"").replace(/\r?\n\r?\n/g,`
|
|
542
542
|
`).replace(/\n\n/g,`
|
|
543
543
|
`).replace(/\\n\\n/g,"").trim(),X=v.role==="user"?8192:32768,ee=U.substring(0,X);U.length>X&&(ee+=`
|
|
544
|
-
... (truncated) ...`);let Ue=v.role==="user"?ee.startsWith("[USER]")?"":"[USER]: ":ee.startsWith("[AGENT]")?"":"[AGENT]: ";return{role:v.role==="user"?"user":"model",parts:[{text:`${Ue}${ee}`}]}}),S=s.filter(v=>v.role==="user").length===1,T=n.includes("[TITLE-UPDATE]"),E=Math.random()<.8,_=S||T||E,b=nn(t).trim(),C=
|
|
544
|
+
... (truncated) ...`);let Ue=v.role==="user"?ee.startsWith("[USER]")?"":"[USER]: ":ee.startsWith("[AGENT]")?"":"[AGENT]: ";return{role:v.role==="user"?"user":"model",parts:[{text:`${Ue}${ee}`}]}}),S=s.filter(v=>v.role==="user").length===1,T=n.includes("[TITLE-UPDATE]"),E=Math.random()<.8,_=S||T||E,b=nn(t).trim(),C=Wi($,x,_),A=`${b.replace(/\[tool:functions\..*?\]/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[\[TOOL RESULTS\]\]/g,"").replace(/\[tool results\]/g,"").substring(0,32768)}`;A.length>32768&&(A+=`
|
|
545
545
|
... (truncated) ...`);let O=n.replace(/\[Prompted on:.*?\]/g,"").trim();A=A.replace(/\r?\n\r?\n/g,`
|
|
546
546
|
`).replace(/\n\n/g,`
|
|
547
547
|
`).replace(/\\n\\n/g,"").trim();let D=new Date,q=`[METADATA] Current date and Time: ${`${D.getFullYear()}-${D.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(D.getDate()).padStart(2,"0")}, ${D.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0})}`}
|
|
@@ -550,11 +550,11 @@ ${l[7]}`};import{WebSocket as Fo}from"ws";var Kt=null,Ds=!1,cc="ws://localhost:5
|
|
|
550
550
|
${O.length>8192?`... (truncated) ...
|
|
551
551
|
|
|
552
552
|
`:""}
|
|
553
|
-
[AGENT (current turn)]: ${A}`;R.push({role:"user",parts:[{text:q}]});let se=await
|
|
553
|
+
[AGENT (current turn)]: ${A}`;R.push({role:"user",parts:[{text:q}]});let se=await or("NVIDIA"),F=(await en()).quotas?.providerTiers?.NVIDIA==="Free",B="",Z=0,Ce=x?12:-1;for(;Z<=Ce;)try{if(!await _i("background",e))return;let v="",U=null,X=!1,ee=m;try{let je=new Promise((at,Se)=>setTimeout(()=>Se(new Error("JANITOR_TIMEOUT")),1e4)),it=m==="Google"&&Z>=0&&Z<6&&se&&F,ze=m==="DeepSeek"&&Z<4&&se&&F;X=it||ze,ee=X?"NVIDIA":m;let bt=(async()=>{if(m==="OpenRouter"){let at=Re("janitor_open_router"),ie=jo(w,at,R,C,"Fast",u,!1,null,.7)[Symbol.asyncIterator](),Yt=await ie.next();return{iterator:ie,firstResult:Yt}}else if(m==="DeepSeek"&&!X){let Se=Bo(w,Re("deepseek_fast_fallback"),R,C,"Fast",u,!1,null,.7)[Symbol.asyncIterator](),ie=await Se.next();return{iterator:Se,firstResult:ie}}else if(m==="Mistral"&&!X){let Se=Uo(w,Re("mistral_janitor_fallback"),R,C,"Fast",u,!1,null,.7)[Symbol.asyncIterator](),ie=await Se.next();return{iterator:Se,firstResult:ie}}else if(m==="NVIDIA"||X){let Se=Wo(X?se:w,Re("nvidia_janitor_fallback"),R,C,"Fast",u,!1,null,.7)[Symbol.asyncIterator](),ie=await Se.next();return{iterator:Se,firstResult:ie}}else if(m==="CrofAI"){let Se=Ho(w,targetModel||Re("crofai_fallback")||"deepseek-v4-flash-0731",R,C,"Fast",u,!1,null,.7)[Symbol.asyncIterator](),ie=await Se.next();return{iterator:Se,firstResult:ie}}else if(m==="InferX"){let Se=Go(w,targetModel||Re("inferx_fallback")||"deepseek-v4-flash",R,C,"Fast",u,!1,null,.7)[Symbol.asyncIterator](),ie=await Se.next();return{iterator:Se,firstResult:ie}}else if(m==="SenseNova"){let Se=qo(w,targetModel||Re("sensenova_fallback")||"sensenova-6.8-flash-lite",R,C,"Fast",u,!1,null,.7)[Symbol.asyncIterator](),ie=await Se.next();return{iterator:Se,firstResult:ie}}else if(m==="AIHubMix"){let Se=zo(w,targetModel||Re("aihubmix_fallback")||"gpt-4o-mini",R,C,"Fast",u,!1,null,.7)[Symbol.asyncIterator](),ie=await Se.next();return{iterator:Se,firstResult:ie}}else{let ie=(await pi(w).models.generateContentStream({model:d||(Z===Ce?Re("janitor_default"):Re("gemma_janitor_fallback_google")),contents:R,config:{systemInstruction:C,temperature:.7,safetySettings:[{category:Vn.HARM_CATEGORY_HARASSMENT,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_HATE_SPEECH,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Yn.BLOCK_NONE}],thinkingConfig:{includeThoughts:!1,thinkingLevel:ut.MINIMAL}}}))[Symbol.asyncIterator](),Yt=await ie.next();return{iterator:ie,firstResult:Yt}}})();if(process.stdout.isTTY){let ie=(await ls())[p]?.name||"",Yt=ie&&!ie.startsWith("flow-")&&!ie.startsWith("Session ")?ie:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${Yt}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${Yt}\x07`)}let{iterator:Nt,firstResult:mt}=await Promise.race([bt,je]),{value:St,done:Rt}=mt;if(!Rt&&St){let at=St.candidates?.[0]?.content?.parts,Se=at?ee==="Google"?at[1]?.text||at[0]?.text||"":at.filter(ie=>ie.text&&!ie.thought).map(ie=>ie.text).join(""):typeof St.text=="function"?St.text():"";Se&&(v+=Se),U=St.usageMetadata;for await(let ie of{[Symbol.asyncIterator]:()=>Nt}){let Yt=ie.candidates?.[0]?.content?.parts,Xn=Yt?ee==="Google"?Yt[1]?.text||Yt[0]?.text||"":Yt.filter(Jn=>Jn.text&&!Jn.thought).map(Jn=>Jn.text).join(""):typeof ie.text=="function"?ie.text():"";Xn&&(v+=Xn),U=ie.usageMetadata}}}catch(je){throw je}if(v){if(B=v,U){let je=U.totalTokenCount||0,it=U.cachedContentTokenCount||0,ze=(U.candidatesTokenCount||0)+(U.thoughtsTokenCount||0),bt=X?Re("nvidia_janitor_fallback"):ee==="DeepSeek"?Re("deepseek_fast_fallback"):ee==="OpenRouter"?Re("janitor_open_router"):d||(Z===Ce?Re("janitor_default"):Re("gemma_janitor_fallback_google"));await zt("tokens",je,ee,bt),it>0&&await zt("cachedTokens",it,ee,bt),ze>0&&await zt("candidateTokens",ze,ee,bt)}}else throw new Error("No synthesis generated by Janitor.");f&&(f(),await vt("background"));let Ue=Vo(B),De=!1;for(let je of Ue){let it=je.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(it)&&(De=!0);let ze={chatId:p,sessionId:p,history:s},bt=await co(it,je.args,ze);it.toLowerCase()==="memory"&&(je.args.includes("action='user'")||je.args.includes('action="user"'))&&!bt.startsWith("ERROR")&&(h&&h(),process.stdout.isTTY&&(process.stdout.write("\x1B]0;Memory Updated\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=Memory Updated\x07")),await new Promise(mt=>setTimeout(mt,3e3)))}if(!De)try{let je=ne(Dt,[]);if(je.length>0){let it=[];for(let ze of je)ze.score===void 0&&(ze.score=.5),ze.score*=.99995,ze.score<.05&&(ze.score=0),ze.score=Math.round(ze.score*1e5)/1e5,ze.score>0&&it.push(ze);he(Dt,it)}}catch{}break}catch(v){Z++;let U=new Date().toLocaleString(),X=v instanceof Error?(()=>{try{return JSON.parse(JSON.parse(v.message).error.message).error.message}catch{return String(v)}})():String(v);await new Promise(De=>setTimeout(De,1e3));let ee=Q.join(hn,"janitor");if(Pe.existsSync(ee)||Pe.mkdirSync(ee,{recursive:!0}),Pe.appendFileSync(Q.join(ee,"error.log"),`ERROR [Attempt ${Z}/${Ce+1}] [${U}]: ${X}
|
|
554
554
|
|
|
555
555
|
`),Z>Ce)break;let Ue=Math.min(750*Math.pow(2,Z-1),5e3);await new Promise(De=>setTimeout(De,Ue))}if(Z){let v=Q.join(hn,"janitor");Pe.appendFileSync(Q.join(v,"error.log"),`-----------------------------------------------------------------------------
|
|
556
556
|
|
|
557
|
-
`)}if(process.stdout.isTTY)try{let X=(await
|
|
557
|
+
`)}if(process.stdout.isTTY)try{let X=(await ls())[p]?.name||"",ee=X&&!X.startsWith("flow-")&&!X.startsWith("Session ")?X:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${ee}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${ee}\x07`)}catch{process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")}},Oc=e=>{let n=nn(e),t=Is?n:n.replace(Da,o=>" ".repeat(o.length)).replace(Fa,o=>" ".repeat(o.length));uo.lastIndex=0;let s;for(;(s=uo.exec(t))!==null;){let o=s.index+s[0].length-1,r=0,a=null,i=!1,h=!1;for(let f=o;f<t.length;f++){let c=n[f];if(!a&&(c==='"'||c==="'"||c==="`")?(a=c,i=!1):a&&c===a&&!i&&(a=null),!a&&(c==="("?r++:c===")"&&r--,r===0)){let l=f+1;for(;l<t.length&&/\s/.test(t[l]);)l++;if(l<t.length&&t[l]==="]"){h=!0,uo.lastIndex=l+1;break}}c==="\\"?i=!i:i=!1}if(!h)return{inside:!0,toolName:s[1],startIndex:s.index,args:n.substring(s.index+s[0].length)}}return{inside:!1}},Na=(e,n=!0)=>{let t=uo;t.lastIndex=0;let s="",o=0,r;for(;(r=t.exec(e))!==null;){let a=e.substring(o,r.index);s+=n&&o===0?nn(a):a;let i=r.index+r[0].length-1,h=0,f=null,c=-1;for(let l=i;l<e.length;l++){let u=e[l];if(f){if(u===f){let d=0;for(let p=l-1;p>=0&&e[p]==="\\";p--)d++;d%2===0&&(f=null)}}else if(u==='"'||u==="'"||u==="`")f=u;else if(u==="(")h++;else if(u===")"&&(h--,h===0)){let d=l+1;for(;d<e.length&&/\s/.test(e[d]);)d++;if(d<e.length&&e[d]==="]"){c=d;break}}}if(c!==-1)s+="[tool:functions."+r[1]+"()]",o=c+1,t.lastIndex=o;else{s+="[tool:functions."+r[1]+"(",o=e.length;break}}return o<e.length&&(s+=n&&o===0?nn(e.substring(o)):e.substring(o)),s},Lc=(e,n,t)=>{let s=uo;s.lastIndex=0;let o="",r=0,a;for(;(a=s.exec(e))!==null;){let i=e.substring(r,a.index);o+=i.replace(n,t);let h=a.index+a[0].length-1,f=0,c=null,l=-1;for(let u=h;u<e.length;u++){let d=e[u];if(c){if(d===c){let p=0;for(let g=u-1;g>=0&&e[g]==="\\";g--)p++;p%2===0&&(c=null)}}else if(d==='"'||d==="'"||d==="`")c=d;else if(d==="(")f++;else if(d===")"&&(f--,f===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)o+=e.substring(a.index,l+1),r=l+1,s.lastIndex=r;else{o+=e.substring(a.index),r=e.length;break}}return r<e.length&&(o+=e.substring(r).replace(n,t)),o},La=e=>Na(e,!0),Pc=e=>{if(!e)return e;let n={patchfile:"PatchFile",writefile:"WriteFile",readfile:"ReadFile",viewfile:"ReadFile",run:"Run",execcommand:"Run",searchkeyword:"SearchKeyword",codesearch:"CodeSearch",code_search:"CodeSearch",websearch:"WebSearch",webscrape:"WebScrape",readfolder:"ReadFolder",writepdf:"WritePDF",writedoc:"WriteDoc",writedocx:"WriteDoc",filemap:"FileMap",generateimage:"GenerateImage",todo:"Todo",goal:"Goal",askuser:"AskUser",ask:"AskUser"},t=o=>o.split("_").map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join("");Aa.lastIndex=0;let s=e.replace(Aa,(o,r,a)=>{let i="";try{let c=JSON.parse(a.trim());c&&typeof c=="object"&&(i=Object.entries(c).map(([u,d])=>{let p=typeof d=="string"?d:JSON.stringify(d);return`${u}=${JSON.stringify(p)}`}).join(", "))}catch{let l=[],u=Cc;u.lastIndex=0;let d;for(;(d=u.exec(a))!==null;){let p=d[1],g=d[2]!==void 0?d[2]:d[0].split(":").slice(1).join(":").trim();l.push(`${p}=${JSON.stringify(g)}`)}l.length>0?i=l.join(", "):i=a.trim()}let h=r.toLowerCase().replace(/_/g,"");return`[tool:functions.${n[h]||t(r)}(${i})]`});return va.lastIndex=0,Ia.lastIndex=0,s=s.replace(va,""),s=s.replace(Ia,""),s},Dc=/(?:path|query|url|keyword|command|method|title|task|id)\s*=\s*['"`]?\s*\.\.\.\s*['"`]?/i,Fc=/^['"`]?\s*\.\.\.\s*['"`]?$/,Dn=e=>{if(e==null)return!1;let n=String(e).trim();return n==="..."||n==="\u2026"||Fc.test(n)},Vo=e=>{if(!e)return[];let n=Pc(e),t=nn(n),s=[],o=Is?t:t.replace(Da,i=>" ".repeat(i.length)).replace(Fa,i=>" ".repeat(i.length)),r=Sc;r.lastIndex=0;let a;for(;(a=r.exec(o))!==null;){let i=a[1],h=a.index+a[0].length-1,f=0,c=null,l=-1,u=-1;for(let d=h;d<o.length;d++){let p=t[d];if(c){if(p===c){let g=0;for(let y=d-1;y>=0&&t[y]==="\\";y--)g++;g%2===0&&(c=null)}}else if(p==='"'||p==="'"||p==="`")c=p;else if(p==="(")f++;else if(p===")"&&(f--,f===0)){u=d;let g=d+1;for(;g<o.length&&/\s/.test(o[g]);)g++;if(g<o.length&&o[g]==="]"){l=g;break}}}if(l!==-1){let d=t.substring(h+1,u),p=t.substring(a.index,l+1),g=L(d);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)||Dc.test(d)||s.push({fullMatch:p,toolName:i.trim(),args:d.trim()}),r.lastIndex=l+1}}return s},sg=(e,n={})=>{if(!e)return null;if(Ko=n,ui=new Pa({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(...s)=>{try{let o=await t(...s);return typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),o}catch(o){throw typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),o}}}},Yo=async(e,n,t,s,o="Fast",r=.75,a="agent")=>Ac(async()=>{let{aiProvider:i="Google",apiKey:h,mode:f}=e,c="",l=null,u=typeof t=="string"?[{role:"user",parts:[{text:t}]}]:t,d=new AbortController,p=d.signal,g=setInterval(()=>{Mt&&(d.abort(),clearInterval(g))},100);try{let y;i==="Ollama"?y=li(h,n,u,s,o,f,At(n),p,r,systemSettings?.ollamaEndpoint||"Cloud"):i==="OpenRouter"?y=jo(h,n,u,s,o,f,At(n),p,r):i==="DeepSeek"?y=Bo(h,n,u,s,o,f,At(n),p,r):i==="Mistral"?y=Uo(h,n,u,s,o,f,At(n),p,r):i==="NVIDIA"?y=Wo(h,n,u,s,o,f,At(n),p,r):i==="CrofAI"?y=Ho(h,n,u,s,o,f,At(n),p,r):i==="InferX"?y=Go(h,n,u,s,o,f,At(n),p,r):i==="SenseNova"?y=qo(h,n,u,s,o,f,At(n),p,r):i==="AIHubMix"?y=zo(h,n,u,s,o,f,At(n),p,r):y=await pi(h).models.generateContentStream({model:n,contents:u,config:{systemInstruction:s,temperature:r,thinkingConfig:(()=>{let x=(n||"").toLowerCase(),k=x.includes("gemma-4")||x.startsWith("gemma"),$=x.includes("gemini-3");if(k||$)return k?o.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:ut.MINIMAL}:{includeThoughts:!0,thinkingLevel:ut.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:x.includes("pro")?ut.LOW:ut.MINIMAL,Low:ut.LOW,Medium:ut.MEDIUM,Standard:ut.MEDIUM,High:ut.HIGH,xHigh:ut.HIGH}[o]||ut.MEDIUM};{let R={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[o]||2048;return R===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:R}}})()}},{signal:p});for await(let m of y){if(Mt)throw new Error("Subagent task was cancelled.");if(e?.taskId&&typeof Ve<"u"){let k=Ve.find($=>$.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 x=w?w.trim().split(/\s+/).filter(Boolean).length:0;e&&typeof e.onTokenChunk=="function"&&e.onTokenChunk(w,x),m.usageMetadata&&(l=m.usageMetadata)}}finally{clearInterval(g)}if(l){let y=l.totalTokenCount||0,m=l.cachedContentTokenCount||0,w=(l.candidatesTokenCount||0)+(l.thoughtsTokenCount||0);await zt("tokens",y,i,n),m>0&&await zt("cachedTokens",m,i,n),w>0&&await zt("candidateTokens",w,i,n),e&&typeof e.onUsage=="function"&&e.onUsage({totalTokenCount:y,cachedContentTokenCount:m,candidatesTokenCount:w})}return await vt("agent",i),{text:c,usageMetadata:l}}),Nc=async(e,n,t=null)=>{t=t||ne(Zt,{});try{let{aiProvider:s="Google"}=n;if(Object.values(t).flat().length<=5)return;let r=Object.keys(t).filter(u=>u!==e&&Array.isArray(t[u])&&t[u].length>2);if(r.length===0)return;let a=`You are a silent background process for the FluxFlow CLI Agent.
|
|
558
558
|
Your task is to summarize or merge temporary context memories from one or more past conversation sessions.
|
|
559
559
|
For each Chat ID provided, you must output a tool call to save the consolidated summary.
|
|
560
560
|
|
|
@@ -579,7 +579,7 @@ ${p}
|
|
|
579
579
|
`):a+=`-- Individual Memories:
|
|
580
580
|
${p}
|
|
581
581
|
|
|
582
|
-
`}let h=0,f=5,c=!1,l=Re("gemma_janitor_fallback_google");for(s==="OpenRouter"&&(l=Re("janitor_open_router")),s==="DeepSeek"&&(l=Re("deepseek_level_1")),s==="Mistral"&&(l=Re("mistral_level_1")),s==="NVIDIA"&&(l=Re("nvidia_janitor_fallback")),s==="CrofAI"&&(l=Re("crofai_fallback")),s==="InferX"&&(l=Re("inferx_fallback")),s==="SenseNova"&&(l=Re("sensenova_fallback")),s==="AIHubMix"&&(l=Re("aihubmix_fallback"));h<=f&&!c;){h++;try{let d=(await
|
|
582
|
+
`}let h=0,f=5,c=!1,l=Re("gemma_janitor_fallback_google");for(s==="OpenRouter"&&(l=Re("janitor_open_router")),s==="DeepSeek"&&(l=Re("deepseek_level_1")),s==="Mistral"&&(l=Re("mistral_level_1")),s==="NVIDIA"&&(l=Re("nvidia_janitor_fallback")),s==="CrofAI"&&(l=Re("crofai_fallback")),s==="InferX"&&(l=Re("inferx_fallback")),s==="SenseNova"&&(l=Re("sensenova_fallback")),s==="AIHubMix"&&(l=Re("aihubmix_fallback"));h<=f&&!c;){h++;try{let d=(await Yo(n,l,a,null,"Fast",.75,"background")).text||"",p=Vo(d);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 co(y,g.args,{chatId:e})}c=!0}catch(u){if(h>=f)throw new Error(`Failed after ${f} attempts. Last error: ${u.message}`)}}}catch(s){let o=s instanceof Error?(()=>{try{return JSON.parse(JSON.parse(s.message).error.message).error.message}catch{return String(s)}})():String(s),r=Q.join(hn,"janitor");Pe.existsSync(r)||Pe.mkdirSync(r,{recursive:!0}),Pe.appendFileSync(Q.join(r,"error.log"),`[${new Date().toLocaleString()}] Past memory batch consolidation error: ${o}
|
|
583
583
|
`)}},Bc=async(e,n,t=!1)=>{let{chatId:s,aiProvider:o="Google"}=e,r=Q.join(wo,"chat-summaries.json"),a=d=>d.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(`
|
|
584
584
|
|
|
585
585
|
`),i=async(d,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:
|
|
@@ -591,20 +591,20 @@ ${d}
|
|
|
591
591
|
Provide a new consolidated summary of the entire session.`:`Here is the conversation history:
|
|
592
592
|
${d}
|
|
593
593
|
|
|
594
|
-
Provide a consolidated summary of the entire session.`,m=Re("gemma_janitor_fallback_google");o==="OpenRouter"&&(m=Re("janitor_open_router")),o==="DeepSeek"&&(m=Re("deepseek_level_1")),o==="Mistral"&&(m=Re("mistral_level_1")),o==="NVIDIA"&&(m=Re("nvidia_chat_summarizer_fallback")),o==="CrofAI"&&(m=Re("crofai_fallback")),o==="InferX"&&(m=Re("inferx_fallback")),o==="SenseNova"&&(m=Re("sensenova_fallback")),o==="AIHubMix"&&(m=Re("aihubmix_fallback"));let w=0,x=!1,k=null;for(;w<=3&&!x;){w++;try{k=await
|
|
594
|
+
Provide a consolidated summary of the entire session.`,m=Re("gemma_janitor_fallback_google");o==="OpenRouter"&&(m=Re("janitor_open_router")),o==="DeepSeek"&&(m=Re("deepseek_level_1")),o==="Mistral"&&(m=Re("mistral_level_1")),o==="NVIDIA"&&(m=Re("nvidia_chat_summarizer_fallback")),o==="CrofAI"&&(m=Re("crofai_fallback")),o==="InferX"&&(m=Re("inferx_fallback")),o==="SenseNova"&&(m=Re("sensenova_fallback")),o==="AIHubMix"&&(m=Re("aihubmix_fallback"));let w=0,x=!1,k=null;for(;w<=3&&!x;){w++;try{k=await Yo(e,m,y,g,"Fast"),x=!0}catch{if(w>3){if(o==="Google")try{let R=Re("general_fallback");return(await Yo(e,R,y,g,"Fast")).text||""}catch{return""}return""}}}return k&&k.text||""},h=a(n),f=ne(r,{}),c=f[s]||{summary:"",historyLength:0};typeof c=="string"&&(c={summary:c,historyLength:0});let l=c.summary||"",u=await i(h,l);if(u){c.summary=u;let d=vc(n);return t?c.historyLength=(c.historyLength||0)+d:c.historyLength=d,f[s]=c,he(r,f),u}return null},og=e=>{try{let n=Q.join(wo,"chat-summaries.json");if(Pe.existsSync(n)){let t=ne(n,{});t[e]&&(delete t[e],he(n,t))}}catch{}},rg=async function*(e,n,t,s,o){let{profile:r,thinkingLevel:a,mode:i,janitorModel:h,chatId:f,isPlayground:c,systemSettings:l,sessionStats:u,aiProvider:d="Google",apiTier:p,wildcardTooling:g}=t,y=At(e);if(!ui&&d==="Google")throw new Error("AI not initialized");let m=process.env.NVIDIA_BASE_URL||t?.aiProvider==="Ollama"||t?.aiProvider==="CrofAI"||t?.aiProvider==="InferX"||t?.aiProvider==="SenseNova"||t?.aiProvider==="AIHubMix"?!1:l?.memory!==!1,w=n[n.length-1].text,x=Q.join(wo,"chat-summaries.json"),k=!1,$=n.filter(_=>_.role==="user").length===1,R=w.includes("[TITLE-UPDATE]"),S=$||R,T=w.replace(/\[TITLE-UPDATE\]/g,"").trim();T=T.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),yield{type:"status",content:"[start]"},yield{type:"status",content:"Gathering Context"},await ht.startTransaction(f,T),l?.advanceRollback&&await Kn.takeInitialSnapshot(f),Mt=!1;let E=null;try{let _=new AbortController;E=setInterval(()=>{Mt&&(_.abort(),E&&(clearInterval(E),E=null))},400);let b=[...n.slice(0,-1)];{let Oe=ne(x,{})[f]||{summary:"",historyLength:0};if(Oe.summary&&Oe.historyLength>0){let sn=0,Ee=[];for(let Ze=0;Ze<b.length;Ze++){let He=b[Ze];(He.role==="user"||He.role==="agent"||He.role==="system")&&!String(He.id).startsWith("welcome")&&!He.isMeta&&sn++,sn>Oe.historyLength&&Ee.push(He)}b=Ee}}b=b.map(z=>{if(z.role==="user"&&z.text){let Oe=z.text.match(/\[USER\]([\s\S]*?)\[\/USER\]/);if(Oe)return{...z,text:Oe[1].trim()}}return{...z}});let C=process.env.HIGH_CONTEXT,A=255e3,O=26e4;if(C&&C!=="false"){let z=parseInt(C,10);!isNaN(z)&&z>=0&&z<=1e6&&(O=z,A=Math.round(z*.85))}if((d==="NVIDIA"&&(e?.includes("gpt")||e?.includes("qwen")||e?.includes("medium")||e.includes("muse"))||d==="Mistral")&&(A=122e3,O=126e3),d==="Ollama"&&(u?.tokens||0)>A){yield{type:"text",content:"\u2726 Maximum Context Limit Reached. Start a new chat."};return}if(d!=="Ollama"&&(u?.tokens||0)>A&&(yield{type:"status_history",content:"Context Limit Reached. Condensing session history..."},await Bc(t,b,!0)&&(b=[],k=!0)),$&&m){let z=ne(Zt,{});Object.values(z).flat().length>5&&(yield{type:"status",content:"Condensing past chat memories"},await Nc(f,t,z))}let D=ne(Zt,{}),W=ne(In,{}),q=Object.entries(D).filter(([z])=>z!==f).flatMap(([z,Oe])=>Oe),V=[...Object.entries(W).filter(([z])=>z!==f).slice(-20).map(([z,Oe])=>`[Chat Summary]: ${Oe}`),...q].map(z=>`- ${z}`).join(`
|
|
595
595
|
`),B=ne(Dt,[]).map(z=>`- ${z.memory}`).join(`
|
|
596
|
-
`),Z=(u?.tokens||0)>=1e4,Ce=
|
|
596
|
+
`),Z=(u?.tokens||0)>=1e4,Ce=Bi(V,B,m,Z),v=new Date,U=v.getFullYear(),X=v.toLocaleString("en-US",{month:"short"}).toUpperCase(),ee=String(v.getDate()).padStart(2,"0"),Ue=v.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}),De=`${U}-${X}-${ee}, ${Ue}`,je=[".git","node_modules",".gemini","dist","build",".next","out",".cache","bin","obj","vendor","venv",".idea",".gradle",".terraform","target","coverage",".vscode",".svn",".hg",".fslckout",".github",".gitlab",".circleci",".gitea",".gitee",".lerna",".changeset",".nx",".npm",".yarn",".pnpm-store",".pnpm",".expo",".nuxt",".svelte-kit",".docusaurus",".turbo",".vercel","bower_components",".netlify",".vuepress",".quasar",".output",".angular","jspm_packages",".parcel-cache",".rollup.cache",".rspack",".vitepress","__pycache__",".pytest_cache",".mypy_cache",".tox",".poetry","env","vhdl",".ipynb_checkpoints",".jupyter",".conda",".pdm-build",".bundle",".yardoc",".metadata","App_Data","ClientBin",".cargo",".rustc_info",".go","Godeps","_vendor",".rake_tasks","CMakefiles",".wakatime",".dart_tool",".fvm",".cocoapods","Pods",".pub-cache",".symlinks","DerivedData",".xcworkspace",".serverless",".aws",".gcloud",".azure",".kube",".vagrant",".docker","postgres-data","redis-data","mongo-data",".Spotlight-V100",".Trashes","$RECYCLE.BIN","System Volume Information",".DocumentRevisions-V100",".fseventsd","AppData","Application Data","Local","LocalLow","Roaming","$WinREAgent","$WINDOWS.~BT","$WINDOWS.~WS","scw","System32","SysWOW64",".AppleDouble",".AppleDB",".AppleDesktop","_CodeSignature",".cmio",".LSOverride",".localized",".TemporaryItems",".Trash",".Trash-0",".Trash-1000",".gvfs",".local",".config",".dbus",".fontconfig",".snap",".var",".lost+found","lost+found",".thumb",".thumbnails","EFI","boot","grub","logs","log",".nyc_output",".sonar",".ruff_cache",".VSCodeCounter",".skills","skills"],it=z=>{try{return Pe.readdirSync(z,{withFileTypes:!0})}catch{return[]}},ze=(z,Oe={value:0},sn=1)=>{if(Oe.value>6200||sn>7)return Oe.value;let Ee=it(z);for(let Ze of Ee){if(Oe.value>6200)break;je.includes(Ze.name)||Ze.name.startsWith(".")||Ze.isDirectory()&&(Oe.value++,ze(Q.join(z,Ze.name),Oe,sn+1))}return Oe.value},bt=(z,Oe)=>l?.indentationTree!==!1?ri(z,Oe,1,it,je):ai(z,Oe,"",1,it,je),Nt=ze(process.cwd()),mt=12;Nt>3072?mt=1:Nt>2304?mt=2:Nt>1536?mt=3:Nt>768?mt=4:Nt>384?mt=6:Nt>192?mt=7:Nt>96?mt=8:Nt>48?mt=9:Nt>24&&(mt=10);let St=ne(nr,{}),Rt=St[f],at=Rt?Rt!==process.cwd():!1;St[f]=process.cwd(),he(nr,St);let Se=ne(x,{}),ie=Se[f]||{summary:"",historyLength:0};typeof ie=="string"&&(ie={summary:ie,historyLength:0});let Yt=n.filter(z=>(z.role==="user"||z.role==="agent"||z.role==="system")&&!String(z.id).startsWith("welcome")&&!z.isMeta).length;ie.historyLength&&Yt<ie.historyLength&&(ie.summary="",ie.historyLength=0,Se[f]=ie,he(x,Se));let Xn=typeof ie=="object"?ie.summary||"":ie||"",Jn=b.length>0;Jn&&Xn&&b[0]&&(b[0].role==="user"||b[0].role==="system")&&(b[0].text.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")||(b[0].text=`[SYSTEM METADATA]
|
|
597
597
|
**CONTEXT SUMMARY OF PREVIOUS TURNS (PRIORITY: DYNAMIC)**
|
|
598
|
-
${
|
|
598
|
+
${Xn}
|
|
599
599
|
|
|
600
|
-
[USER] ${b[0].text}`,yield{type:"summary_injected",content:{id:b[0].id,text:b[0].text}}));let
|
|
600
|
+
[USER] ${b[0].text}`,yield{type:"summary_injected",content:{id:b[0].id,text:b[0].text}}));let hi=Xn&&!Jn?`
|
|
601
601
|
[SYSTEM METADATA]
|
|
602
602
|
**CONTEXT SUMMARY OF PREVIOUS TURNS**
|
|
603
|
-
${
|
|
604
|
-
`:"",
|
|
603
|
+
${Xn}
|
|
604
|
+
`:"",mi=!!l?.dynamicDirAwareness,Ba=`${f}|${d}|${a}|${e}|${r}|${mi}`,gi=!mi&&ws.key===Ba&&ws.value?"":`
|
|
605
605
|
**Directory Structure**
|
|
606
606
|
CWD: `+process.cwd()+`${c?" [PLAYGROUND MODE]":""}
|
|
607
|
-
`+bt(process.cwd(),mt),kt=await
|
|
607
|
+
`+bt(process.cwd(),mt),kt=await gs(),Fn="";if(Fo()&&kt.file_focused!=="none"){Fn=`
|
|
608
608
|
[Additional IDE Context]
|
|
609
609
|
`;let z=Q.relative(process.cwd(),kt.file_focused),Oe=(kt.opened_editors||[]).map(Ee=>{let Ze=Q.relative(process.cwd(),Ee);return Ze.startsWith("..")?`[External] ${Q.basename(Ee)}`:Ze});if(Fn+=`Focused File: ${z}
|
|
610
610
|
Cursor Line: ${kt.cursor_line}
|
|
@@ -633,28 +633,28 @@ ${kt.diagnostics}
|
|
|
633
633
|
`),(T.toLowerCase().includes("lint")||T.toLowerCase().includes("warning"))&&kt.warnings&&(Fn+=`
|
|
634
634
|
**Lint Warnings**:
|
|
635
635
|
${kt.warnings}
|
|
636
|
-
`)}let
|
|
637
|
-
`);yield{type:"visual_feedback",content:tn(`${
|
|
638
|
-
`)};continue}if(pe===null&&!Ut){let We=0;try{We=Pe.readFileSync(Je,"utf8").split(/\r\n|\r|\n/).length}catch{}if(We>300){let ke=`\u21B7 Skipped (Too Large): ${Q.basename(Xe)}`,et=115;process.stdout.isTTY&&(et=process.stdout.columns-5||120);let
|
|
639
|
-
`)};continue}}let $n=pe!==null?pe:1,
|
|
640
|
-
`);yield{type:"visual_feedback",content:tn(`${
|
|
641
|
-
`)}}}}}catch{}}let
|
|
642
|
-
`+
|
|
636
|
+
`)}let yi=T.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),wi=/(?:\\)?@\[([^\]]+)\]/g,Xo,Jo=[];for(wi.lastIndex=0;(Xo=wi.exec(yi))!==null;){let z=Xo[0].startsWith("\\");Jo.push({tag:Xo[1],isEscaped:z})}let Qo=[],po=null;for(let z=0;z<Jo.length;z++){let{tag:Oe,isEscaped:sn}=Jo[z];if(!sn)try{let Ee=Oe.trim().replace(/^["']|["']$/g,""),Ze=/[:#]L?(\d+)(?:-L?(\d+))?$/i,He=Ee.match(Ze),Xe=Ee,pe=null,Bt=null;He&&(pe=parseInt(He[1],10),Bt=He[2]?parseInt(He[2],10):pe,Xe=Ee.slice(0,He.index));let Je=Q.resolve(process.cwd(),Xe);if(Pe.existsSync(Je)&&Pe.statSync(Je).isFile()){let K=Xe.toLowerCase(),te=K.endsWith(".pdf"),Ge=K.endsWith(".docx")||K.endsWith(".doc")||K.endsWith(".ppt")||K.endsWith(".pptx")||K.endsWith(".xls")||K.endsWith(".xlsx"),dn=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(K),Ut=dn||te||Ge,bn=d==="Google"||At(e);if(Ut&&!bn){let We=`\u2718 Unsupported Modality: ${Q.basename(Xe)}`,ke=115;process.stdout.isTTY&&(ke=process.stdout.columns-5||120);let et=[We],es=Math.max(...et.map(Nn=>Nn.length)),un=Math.min(es+4,ke),Us=et.map(Nn=>`${Nn.padEnd(un-2).substring(0,un-2)}`).join(`
|
|
637
|
+
`);yield{type:"visual_feedback",content:tn(`${Us}
|
|
638
|
+
`)};continue}if(pe===null&&!Ut){let We=0;try{We=Pe.readFileSync(Je,"utf8").split(/\r\n|\r|\n/).length}catch{}if(We>300){let ke=`\u21B7 Skipped (Too Large): ${Q.basename(Xe)}`,et=115;process.stdout.isTTY&&(et=process.stdout.columns-5||120);let es=Math.min(ke.length+4,et),un=ke.padEnd(es-2).substring(0,es-2);yield{type:"visual_feedback",content:tn(`${un}
|
|
639
|
+
`)};continue}}let $n=pe!==null?pe:1,Qn=Bt!==null?Bt:pe!==null?pe:$n+299;Qn-$n>300&&(Qn=$n+300);let mo=`path=${JSON.stringify(Xe)}, startLine=${$n}, endLine=${Qn}`,st=await Js(mo,{isMultiModal:bn}),Ke=!1,Wt="",Zn=null;if(typeof st=="string"?st.trim().startsWith("ERROR")?Ke=!0:Wt=st:st&&typeof st=="object"&&st.binaryPart?(Zn=st.binaryPart,Wt=st.text||""):Ke=!0,!Ke){let We="";if(dn?(We=`\u2714 Processed: ${Q.basename(Xe)}`,po=Zn):te||Ge?(We=`\u2714 Auto-Analysed: ${Q.basename(Xe)}`,po=Zn):(We=`\u2714 Auto-Read: ${Q.basename(Xe)}`,Qo.push(Wt)),We){let ke=115;process.stdout.isTTY&&(ke=process.stdout.columns-5||120);let et=[We],es=Math.max(...et.map(Nn=>Nn.length)),un=Math.min(es+4,ke),Us=et.map(Nn=>`${Nn.padEnd(un-2).substring(0,un-2)}`).join(`
|
|
640
|
+
`);yield{type:"visual_feedback",content:tn(`${Us}
|
|
641
|
+
`)}}}}}catch{}}let xi="";Qo.length>0&&(xi=`[Tagged File Contents] Auto Read User Tagged files by System, No need to re-read
|
|
642
|
+
`+Qo.join(`
|
|
643
643
|
|
|
644
644
|
`)+`
|
|
645
645
|
[Tagged File Contents]
|
|
646
|
-
`);let
|
|
646
|
+
`);let Ua=yi.replace(/\\(@\[[^\]]+\])/g,"$1"),Wa=g?`You cannot execute tools
|
|
647
647
|
Instead, output in chat the exact string you WOULD have produced & wait for system response
|
|
648
|
-
`:"",
|
|
649
|
-
Time: ${De}${l?.dynamicDirAwareness?
|
|
648
|
+
`:"",ja=process.env.forcedReasoning||!1,bi=`[System Metadata]
|
|
649
|
+
Time: ${De}${l?.dynamicDirAwareness?gi:""}${at?`
|
|
650
650
|
WARNING: CWD Changed from previous: "${Rt}" to current: "${process.cwd()}", write change in chat to avoid future path mismatches
|
|
651
651
|
`:""}${Ce}${Fn}
|
|
652
652
|
[/Metadata]
|
|
653
|
-
${
|
|
653
|
+
${hi}${a!=="Fast"&&(d==="Mistral"&&!Cs(e)||a!=="xHigh"&&d==="Google")?`${d==="Mistral"&&!Cs(e)||e.toLowerCase().startsWith("gemma")||ja?`[system] strictly follow thinking policy as high priority. do not start a response without <think>...</think> [/system]
|
|
654
654
|
`:""}`:""}[system] exact tool string [tool:functions.ToolName(arg="value")] in chat [/system]
|
|
655
|
-
${
|
|
655
|
+
${xi}${Wa}[user prompt] ${Ua.trim()} [/user prompt]`.trim(),Si={role:"user",text:bi};po&&(Si.binaryPart=po),b.forEach(z=>{z.text&&z.role==="agent"&&(z.text=nn(z.text))}),b.push(Si),hi&&n[n.length-1]?.id&&(yield{type:"summary_injected",content:{id:n[n.length-1].id,text:bi}});let _n=null,Bs=i==="Flux"?100:10;Bs=i.toLowerCase().includes("cu")?250:Bs;let xn=16;yield{type:"status",content:"Connecting"},Mt=!1;let ki=[],ho=!1;for(let z=0;z<=Bs;z++){let Oe=await Ei("agent",t);if(!Oe.allowed)throw new Error(Oe.reason||`Budget Exhausted for Provider (${d||"Agent"})`);let sn=[];if(ho=!1,i==="ICU"||i==="FluxCU")try{yield{type:"status",content:"Capturing Screen"},await new Promise(ye=>setTimeout(ye,1e3));let fe=await Ai();if(fe&&fe.base64){let ye="[system] Fresh Gridded Screen Feedback Captured. Use numeric coordinates. Old screenshots will be removed when new screenshot is captured, summarize in text if context is needed later [/system]",de={inlineData:{mimeType:fe.mimeType,data:fe.base64}};for(let ot of b)Array.isArray(ot.parts)&&(ot.parts=ot.parts.filter(jt=>!jt.inlineData));if(b.length>0&&b[b.length-1].role==="user"){let ot=b[b.length-1];typeof ot.text=="string"&&(ot.text+=`
|
|
656
656
|
|
|
657
|
-
${ye}`,Array.isArray(ot.parts)||(ot.parts=[{text:ot.text}]),ot.parts.push(de))}else b.push({role:"user",text:ye,parts:[{text:ye},de]})}}catch(fe){console.error("Vision screenshot capture error:",fe)}if(l?.compression===0&&(u?.tokens||0)>O&&(b=
|
|
657
|
+
${ye}`,Array.isArray(ot.parts)||(ot.parts=[{text:ot.text}]),ot.parts.push(de))}else b.push({role:"user",text:ye,parts:[{text:ye},de]})}}catch(fe){console.error("Vision screenshot capture error:",fe)}if(l?.compression===0&&(u?.tokens||0)>O&&(b=Gi(b,6)),z>0?yield{type:"status",content:"Working"}:yield{type:"status",content:"Connecting"},Mt){try{let{clearPendingNudges:fe}=await import("./subagent_state-LZCOZSUJ.js");fe()}catch{}yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
|
|
658
658
|
|
|
659
659
|
\x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}try{let{consumePendingNudges:fe}=await import("./subagent_state-LZCOZSUJ.js"),ye=fe();if(ye&&ye.length>0){let de=ye.join(`
|
|
660
660
|
|
|
@@ -666,33 +666,33 @@ ${de}`:b.push({role:"user",text:de}),yield{type:"status",content:"Subagent Updat
|
|
|
666
666
|
[question] ${fe.replace("/btw","").trim()} [/question]`:b.push({role:"user",text:`[system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
|
|
667
667
|
[question] ${fe.replace("/btw","").trim()} [/question]`}):b.length>0&&b[b.length-1].role==="user"?b[b.length-1].text+=`
|
|
668
668
|
|
|
669
|
-
[STEERING HINT from USER, HIGH PRIORITY] ${fe.trim().toUpperCase()} [/STEERING HINT]`:b.push({role:"user",text:`[STEERING HINT from USER, HIGH PRIORITY] ${fe.trim().toUpperCase()} [/STEERING HINT]`}),yield{type:"status",content:`${fe.startsWith("/btw")?"Question Forwarded...":"Steering Hint Injected..."}`})}let Ee,Ze=!1,He=1,Xe=1,pe="",Bt=null,Je=null,on=null,K=0,te=[],Ge=0,dn=!1,Ut=!1,bn=!1,$n=!1,
|
|
669
|
+
[STEERING HINT from USER, HIGH PRIORITY] ${fe.trim().toUpperCase()} [/STEERING HINT]`:b.push({role:"user",text:`[STEERING HINT from USER, HIGH PRIORITY] ${fe.trim().toUpperCase()} [/STEERING HINT]`}),yield{type:"status",content:`${fe.startsWith("/btw")?"Question Forwarded...":"Steering Hint Injected..."}`})}let Ee,Ze=!1,He=1,Xe=1,pe="",Bt=null,Je=null,on=null,K=0,te=[],Ge=0,dn=!1,Ut=!1,bn=!1,$n=!1,Qn=!0,mo=0,st="",Ke="",Wt=!1,Zn=!1,We=!0,ke=e,et="";for(;He<=xn&&Xe<=xn&&!Ze&&!Mt;){let fe=!1;try{pe="",Qn&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},Qn=!1,Xe===1&&(st=""));let ye=N=>{if(!N||!N.includes("[tool:"))return N;let ae="",j=ci(N);j&&(ae=j.fullBlock,N=j.remainingText),N=N.replace(Mc,(me,_e)=>_e.includes("[tool:")?_e.trim():me);let G="",we=0;for(;we<N.length;){let me=N.indexOf("[tool:",we);if(me===-1){G+=Oa(N.substring(we));break}let _e=N.substring(we,me);G+=Oa(_e);let tt=-1,H=null,oe=0;for(let Fe=me;Fe<N.length;Fe++){let M=N[Fe];if(H){if(M===H){let Ne=0;for(let Me=Fe-1;Me>=0&&N[Me]==="\\";Me--)Ne++;Ne%2===0&&(H=null)}}else if(M==='"'||M==="'"||M==="`")H=M;else if(M==="(")oe++;else if(M===")")oe--;else if(M==="]"&&oe<=0){tt=Fe;break}}if(tt===-1){G+=N.substring(me);break}G+=N.substring(me,tt+1),we=tt+1}return ae+G},de=b.filter(N=>(N.role==="user"||N.role==="agent"||N.role==="system")&&!String(N.id).startsWith("welcome")&&!N.isMeta&&!N.isTerminalRecord&&!(N.text&&N.text.startsWith("[TERMINAL_RECORD]"))).map((N,ae,j)=>{let G=N.text||"";m||(G=G.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),N.role==="agent"&&(G=ye(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 we=[];return Array.isArray(N.parts)&&N.parts.length>0?we=N.parts.map(me=>{if(me.text){let _e=me.text;return m||(_e=_e.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),N.role==="agent"&&(_e=ye(_e),_e=_e.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),_e=_e.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*")),{text:_e}}return me}):we=[{text:G}],N.binaryPart&&At(ke)&&j.slice(ae+1).filter(_e=>_e.role==="user"&&!_e.text?.startsWith("[TOOL RESULT]")).length<=2&&we.push(N.binaryPart),{role:N.role==="user"||N.role==="system"?"user":"model",parts:we}});for(let N=0;N<de.length;N++){let ae=de[N],j=ae.parts?.[0]?.text||"";if(ae.role==="model"&&/\[tool:/i.test(j)){let G=-1;for(let we=N+1;we<de.length;we++){let me=de[we],_e=me.parts?.[0]?.text||"";if(me.role==="user"&&_e.startsWith("[TOOL RESULT]")){G=we;break}}if(G!==-1&&G!==N+1){let[we]=de.splice(G,1);de.splice(N+1,0,we)}}}for(let N=de.length-2;N>=0;N--){let ae=de[N],j=de[N+1];ae.role==="user"&&j.role==="user"&&(j.parts?.[0]?.text||"").trim().startsWith("[SYSTEM")&&de.splice(N,1)}let ot=[];for(let N=0;N<de.length;N++){let ae=de[N];if(ot.length===0)ot.push(ae);else{let j=ot[ot.length-1];j.role===ae.role?(j.parts[0].text+=`
|
|
670
670
|
|
|
671
|
-
`+(ae.parts?.[0]?.text||""),ae.parts?.length>1&&j.parts.push(...ae.parts.slice(1))):ot.push(ae)}}de.length=0,de.push(...ot),ke=e;let jt=`${f}|${d}|${i}|${a}|${ke}|${JSON.stringify(r)}|${!!l?.dynamicDirAwareness}|${!!l?.subAgents}`,Vt=
|
|
672
|
-
${
|
|
671
|
+
`+(ae.parts?.[0]?.text||""),ae.parts?.length>1&&j.parts.push(...ae.parts.slice(1))):ot.push(ae)}}de.length=0,de.push(...ot),ke=e;let jt=`${f}|${d}|${i}|${a}|${ke}|${JSON.stringify(r)}|${!!l?.dynamicDirAwareness}|${!!l?.subAgents}`,Vt=ws.key===jt&&ws.value;if((process.env.I_HAVE_TOO_MUCH_MONEY==="true"||process.env.I_HAVE_TOO_MUCH_MONEY===!0)&&(Vt=!1),Vt)et=ws.value;else{let N=d==="Mistral"?!!Cs(ke):!(ke||"gemma").toLowerCase().startsWith("gemma");et=Ui(r,((ke||"gemma").toLowerCase().startsWith("gemma"),a),i,l,m,$,d,d==="Google"?!0:y,N,f),l?.dynamicDirAwareness||(et+=`
|
|
672
|
+
${gi.replace(`
|
|
673
673
|
**Directory Structure**`,`
|
|
674
|
-
-- Directory Structure --`)}`),
|
|
674
|
+
-- Directory Structure --`)}`),ws.key=jt,ws.value=et}let gt=de[de.length-1];if(Fo()&z>0){await new Promise(j=>setTimeout(j,2500)),yield{type:"status",content:"Verifying"};let N=await gs(),ae=N?N.diagnostics:null;ae&>&>.role==="user"&>.parts?.[0]?.text&&(gt.parts[0].text+=`
|
|
675
675
|
${ae} [/ERROR]`),yield{type:"status",content:"Working"}}if(d==="Mistral"||d==="Google"&&e?.toLowerCase().startsWith("gemma")){let ae=a!=="Fast"&&(d==="Mistral"||a!=="xHigh")?". **strictly maintain thinking policy. do not start a response without <think>...</think>**":"",j=`
|
|
676
|
-
[system] Tool result received. Analyze output and proceed with your turn [/system]`;gt&>.role==="user"&>.parts?.[0]?.text?.startsWith("[TOOL RESULT]")&&(gt.parts[0].text+=j)}if(l?.advanceRollback&>&>.role==="user"&>.parts?.[0]?.text?.startsWith("[TOOL RESULT]"))try{let N=await
|
|
676
|
+
[system] Tool result received. Analyze output and proceed with your turn [/system]`;gt&>.role==="user"&>.parts?.[0]?.text?.startsWith("[TOOL RESULT]")&&(gt.parts[0].text+=j)}if(l?.advanceRollback&>&>.role==="user"&>.parts?.[0]?.text?.startsWith("[TOOL RESULT]"))try{let N=await Kn.getLatestFileChanges(f);if(N&&(N.newFiles.length>0||N.modifiedFiles.length>0||N.deletedFiles.length>0)){let ae=`
|
|
677
677
|
[system] File Changes:
|
|
678
678
|
`;for(let G of N.newFiles)ae+=`* ${G} (created)
|
|
679
679
|
`;for(let G of N.modifiedFiles)ae+=`* ${G} (modified)
|
|
680
680
|
`;for(let G of N.deletedFiles)ae+=`* ${G} (deleted)
|
|
681
|
-
`;ae+="[/system]",gt.parts[0].text+=ae;let j=-1;for(let G=b.length-1;G>=0;G--)if(b[G].role==="user"&&b[G].text?.startsWith("[TOOL RESULT]")){j=G;break}j!==-1&&(b[j].text+=ae)}}catch{}let rn=Math.floor(
|
|
682
|
-
[system] WARNING, Turn Limit Impending: Step ${Ot}/${
|
|
681
|
+
`;ae+="[/system]",gt.parts[0].text+=ae;let j=-1;for(let G=b.length-1;G>=0;G--)if(b[G].role==="user"&&b[G].text?.startsWith("[TOOL RESULT]")){j=G;break}j!==-1&&(b[j].text+=ae)}}catch{}let rn=Math.floor(Bs*(i==="Flux"?.98:.8)),Ot=z+1;Ot>=rn&>&>.parts?.[0]&&(gt.parts[0].text+=`
|
|
682
|
+
[system] WARNING, Turn Limit Impending: Step ${Ot}/${Bs}. Wrap up quickly/prompt user to continue. [/system]`);let Lt=new Promise((N,ae)=>{_.signal.aborted&&ae(new DOMException("The user aborted a request.","AbortError")),_.signal.addEventListener("abort",()=>{ae(new DOMException("The user aborted a request.","AbortError"))})});Lt.catch(()=>{});let Pt=de;if(d==="Ollama")Ee=li(t.apiKey,ke,Pt,et,a,i,y,_.signal,1,l?.ollamaEndpoint||"Cloud");else if(d==="OpenRouter")Ee=jo(t.apiKey,ke,Pt,et,a,i,y,_.signal,1,f);else if(d==="DeepSeek")Ee=Bo(t.apiKey,ke,Pt,et,a,i,y,_.signal,1);else if(d==="Mistral")Ee=Uo(t.apiKey,ke,Pt,et,a,i,y,_.signal,1,f);else if(d==="NVIDIA"){let N=Wo(t.apiKey,ke,Pt,et,a,i,y,_.signal,1);Ee=Ca(N,ke)}else if(d==="CrofAI")Ee=Ho(t.apiKey,ke,Pt,et,a,i,y,_.signal,1);else if(d==="InferX")Ee=Go(t.apiKey,ke,Pt,et,a,i,y,_.signal,1);else if(d==="SenseNova")Ee=qo(t.apiKey,ke,Pt,et,a,i,y,_.signal,1);else if(d==="AIHubMix")Ee=zo(t.apiKey,ke,Pt,et,a,i,y,_.signal,1);else{let ae=pi(t?.apiKey).models.generateContentStream({model:ke||"gemini-3-flash-preview",contents:Pt,config:{systemInstruction:et,mediaResolution:"MEDIA_RESOLUTION_HIGH",safetySettings:[{category:Vn.HARM_CATEGORY_HARASSMENT,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_HATE_SPEECH,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Yn.BLOCK_NONE}],temperature:1.05,thinkingConfig:(()=>{let j=(ke||"").toLowerCase(),G=j.includes("gemma-4")||j.startsWith("gemma"),we=j.includes("gemini-3");if(G||we)return G?a.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:ut.MINIMAL}:{includeThoughts:!0,thinkingLevel:ut.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:j.includes("pro")?ut.LOW:ut.MINIMAL,Low:ut.LOW,Medium:ut.MEDIUM,Standard:ut.MEDIUM,High:ut.HIGH,xHigh:ut.HIGH}[a]||ut.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});Ee=await Promise.race([ae,Lt])}pe="",Bt=null,on=null,te=[],Ge=0,yield{type:"model_update",content:null},Ke="",Wt=st.length>0;let Sn="",Zo=Date.now(),ss=async function*(){if(d==="Google"&&Sn){let N=Ws(Sn);for(let ae of N)yield ae;Sn="",Zo=Date.now()}},Ti=!0,os="",bs=!1,Ht=null,qa={tool:{startPrefix:"[tool",fullPrefix:"[tool:functions.",endTag:"]"},agent:{startPrefix:"[agent",fullPrefix:"[agent:generalist.",endTag:"]"},end:{startPrefix:"[[END]]",fullPrefix:"[[END]]",endTag:"[[END]]"},kimi_section:{startPrefix:"<|tool_calls_section_begin|>",fullPrefix:"<|tool_calls_section_begin|>",endTag:"<|tool_calls_section_end|>"},kimi_call:{startPrefix:"<|tool_call_begin|>",fullPrefix:"<|tool_call_begin|>",endTag:"<|tool_call_end|>"}},Ws=N=>{let ae=[],j=N;for(;j.length>0;)if(bs){let G=os+j,we=qa[Ht];if(we){let tt=!1;if(G.length<we.startPrefix.length?we.startPrefix.startsWith(G)||(tt=!0):G.startsWith(we.startPrefix)?G.length>=we.fullPrefix.length&&!G.startsWith(we.fullPrefix)&&(tt=!0):tt=!0,tt){ae.push({type:"text",content:G}),os="",bs=!1,Ht=null,j="";break}}let me=-1,_e=we?we.endTag:"]";if(Ht==="tool"||Ht==="agent"){let tt=0,H=null,oe=0,Fe=!1;for(let M=0;M<G.length;M++){let Ne=G[M];if(H){if(Ne===H){let Me=0;for(let J=M-1;J>=0&&G[J]==="\\";J--)Me++;Me%2===0&&(H=null)}}else if(Ne==='"'||Ne==="'"||Ne==="`")H=Ne;else if(Ne==="(")tt++,Fe=!0;else if(Ne===")")tt--;else if(Ne==="[")oe++;else if(Ne==="]"){if(Fe&&tt===0&&oe===1){me=M;break}oe--}}}else me=G.indexOf(_e);if(me!==-1){let tt=_e.length;if(!Ht?.startsWith("kimi")){let H=G.substring(0,me+tt);ae.push({type:"text",content:H})}os="",bs=!1,Ht=null,j=G.substring(me+tt)}else{let tt=Ht?.startsWith("kimi")?8192:512;G.length>tt?(ae.push({type:"text",content:G}),os="",bs=!1,Ht=null):os=G,j="";break}}else{let G=j.indexOf("[tool"),we=j.indexOf("[agent"),me=j.indexOf("[[END]]"),_e=j.indexOf("<|tool_calls_section_begin|>"),tt=j.indexOf("<|tool_call_begin|>"),H=[{type:"tool",idx:G,start:"[tool",end:"]"},{type:"agent",idx:we,start:"[agent",end:"]"},{type:"end",idx:me,start:"[[END]]",end:"[[END]]"},{type:"kimi_section",idx:_e,start:"<|tool_calls_section_begin|>",end:"<|tool_calls_section_end|>"},{type:"kimi_call",idx:tt,start:"<|tool_call_begin|>",end:"<|tool_call_end|>"}].filter(oe=>oe.idx!==-1).sort((oe,Fe)=>oe.idx-Fe.idx);if(H.length>0){let oe=H[0];oe.idx>0&&ae.push({type:"text",content:j.substring(0,oe.idx)}),bs=!0,Ht=oe.type,os="",j=j.substring(oe.idx)}else{let oe=["[tool","[agent","[[END]]","<|tool_calls_section_begin|>","<|tool_call_begin|>"],Fe=-1;for(let M of oe){for(let Ne=M.length-1;Ne>0;Ne--)if(j.endsWith(M.substring(0,Ne))){Fe=j.length-Ne;let Me=oe.indexOf(M);Me===0?Ht="tool":Me===1?Ht="agent":Me===2?Ht="end":Me===3?Ht="kimi_section":Ht="kimi_call";break}if(Fe!==-1)break}if(Fe!==-1)Fe>0&&ae.push({type:"text",content:j.substring(0,Fe)}),bs=!0,os=j.substring(Fe),j="";else{ae.push({type:"text",content:j});break}}}return ae},za=Ee[Symbol.asyncIterator]();for(;;){let{value:N,done:ae}=await Promise.race([za.next(),Lt]);if(ae)break;if(N&&N.type==="status"){yield N;continue}let j="",G=N.candidates?.[0]?.content?.parts;if(G&&G.length>0)for(let me of G){let _e=typeof me.text=="string"?me.text:me.text?parseChunkText(me.text):"";me.thought?_e&&(fe||(j+="<think>",fe=!0),j+=_e):_e&&(fe&&(j+="</think>",fe=!1),j+=_e)}else N.text&&fe&&(j+="</think>",fe=!1);j=Ec(j);let we=j?j.trim().split(/\s+/).filter(Boolean).length:0;if(t&&typeof t.onTokenChunk=="function"&&t.onTokenChunk(j,we),Ti&&(yield{type:"status",content:"Thinking"},Ti=!1),Mt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
|
|
683
683
|
|
|
684
|
-
\x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(j){if(Wt){if(Ke+=j,Ke.length>=64){let H=0,oe=Math.min(st.length,Ke.length);for(let M=oe;M>=10;M--)if(st.endsWith(Ke.substring(0,M))){H=M;break}let Fe=Ke.substring(H);if(Fe){let Ne=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(st)?Fe.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):Fe.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(Ne)if(pe+=Ne,d==="Google")Sn+=Ne;else{yield*
|
|
685
|
-
`).length;Be=Et,!Te&&!re&&Et>800?nt=Math.min(50,Et):nt=Math.min(ce,Et)}}catch{}let lt=(I||"").toLowerCase(),Qe=lt.endsWith(".pdf"),yt=lt.endsWith(".docx")||lt.endsWith(".doc")||lt.endsWith(".ppt")||lt.endsWith(".pptx")||lt.endsWith(".xls")||lt.endsWith(".xlsx"),ve=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(lt);Qe||yt?J=`${I.length>0?"\u2714":"\u2718"} ${I?`Analyzed: ${Q.basename(I)}`:"Analyzed: File Not Found"}`:ve?J=`${I.length>0?"\u2714":"\u2718"} ${I?`Processed: ${Q.basename(I)}`:"Processed: File Not Found"}`:J=`${Be!=="..."?"\u2714":"\u2718"} Read: ${I?`${Q.basename(I)} \u2192 ${Be!=="..."?`Lines ${ue} - ${nt} of ${Be}`:"File Not Found"}`:"File Not Found"}`}}else if(M==="list_files"||M==="read_folder"){let I=M==="list_files"?"List":"Browsed",Y=L(H.args).path||null,le=L(H.args).recurse||1;J=`${Y?"\u2714":"\u2718"} ${I}: ${Y?`${Y==="."?`./${le>1?"*":""}`:`${Y.replaceAll("\\","/")}${le>1?`${Y.endsWith("/")?"*":"/*"}`:`${Y.endsWith("/")?"":"/"}`}`}`:"No Folder Selected"}`}else if(M==="write_file"||M==="update_file"){let I=M==="write_file"?"Created":"Edited",Y=L(H.args).path||null;J=`${Y?"\u2714":"\u2718"} ${I}: ${Y.replaceAll("\\","/")||"No File Changes"}`}else if(M==="write_pdf"){let I=L(H.args).path||null;J=`${I?"\u2714":"\u2718"} Generated: ${I.replaceAll("\\","/")||"No PDF Generated"}`}else if(M==="write_docx"){let I=L(H.args).path||null;J=`${I?"\u2714":"\u2718"} Generated: ${I.replaceAll("\\","/")||"No Docx Generated"}`}else if(M==="file_map"){let I=L(H.args).path;J=`${I?"\u2714":"\u2718"} Indexed: ${I.replaceAll("\\","/")?""+I:"File Not Found"}`}else if(M.toLowerCase()==="search_keyword"||M.toLowerCase()==="todo")J="";else if(M.toLowerCase()==="generate_image"){let{path:I,outputPath:Y,output:le}=L(H.args);J=`\u2714 Generated: ${I||Y||le||"generated_image.png"}`}else if(M==="invoke_sync"||M==="InvokeSync"){let I=
|
|
684
|
+
\x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(j){if(Wt){if(Ke+=j,Ke.length>=64){let H=0,oe=Math.min(st.length,Ke.length);for(let M=oe;M>=10;M--)if(st.endsWith(Ke.substring(0,M))){H=M;break}let Fe=Ke.substring(H);if(Fe){let Ne=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(st)?Fe.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):Fe.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(Ne)if(pe+=Ne,d==="Google")Sn+=Ne;else{yield*ss();let Me=Ws(Ne);for(let J of Me)yield J}}Wt=!1,Ke=""}continue}else if(pe+=j,d==="Google")Sn+=j;else{yield*ss();let H=Ws(j);for(let oe of H)yield oe}let me=Oc(pe);if(me.inside){Zn=!0,on||(on=Date.now());let oe={Ask:"ask",AskUser:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Cancel:"cancel",Await:"await",Answer:"answer",Steer:"steer",steer:"steer"}[me.toolName]||me.toolName,Fe=me.args||"",M=null;if(["write_file","update_file","view_file","read_folder","write_pdf","write_docx","search_keyword","generate_image","file_map","invoke","invoke_sync","get_progress","await","answer"].includes(oe)){let Me=L(Fe),J=Me.path||Me.targetFile||Me.TargetFile||Me.directory,kn=Me.keyword,rs=Me.title||Me.task,Un=Me.id||Me.taskId,$e=Me.timeout||Me.time;if(kn!=null)M=String(kn).replace(ys,"");else if(J)M=Q.basename(String(J).replace(ys,"").replace(Ma,"/"));else if(rs&&(oe==="invoke"||oe==="invoke_sync"))M=String(rs).replace(ys,"").substring(0,30);else if(Un&&oe==="get_progress")M=String(Un).replace(ys,"");else if($e&&oe==="await"){let Gt=parseFloat(String($e).replace(ys,""));isNaN(Gt)?M=String($e).replace(ys,""):(Gt<5&&(Gt=5),Gt>120&&(Gt=120),M=(Cn=>{if(Cn>=60){let tr=Math.floor(Cn/60),Ss=Cn%60;return`${tr}m${Ss>0?` ${Ss}s`:""}`}return`${Cn}s`})(Gt))}else{let Gt=Fe.match(kc);if(Gt){let Xt=Gt[1].replace(ys,"");oe==="invoke"||oe==="invoke_sync"||oe==="get_progress"?M=Xt.substring(0,30):M=oe==="search_keyword"||oe==="file_map"?Xt:Q.basename(Xt.replace(Ma,"/"))}}}let Ne=`${fi[oe]||oe}${M?` ${M}`:""}`;if((oe!==Bt||M!==Je)&&(Bt=oe,Je=M,yield{type:"status",content:`${Ne}`},process.stdout.isTTY)){let J={WebSearch:"Searching",web_search:"Searching",WebScrape:"Reading",web_scrape:"Reading",ReadFile:"Reading",read_file:"Reading",ReadFolder:"Reading",read_folder:"Reading",WriteFile:"Writing",write_file:"Writing",UpdateFile:"Editing",update_file:"Editing",WritePdf:"Creating",write_pdf:"Creating",WriteDocx:"Creating",write_docx:"Creating",SearchKeyword:"Searching",search_keyword:"Searching",CodeSearch:"Searching",code_search:"Searching",Run:"Executing",Ask:"User Input Required",AskUser:"User Input Required",Memory:"Updating Memory",GenerateImage:"Generating",InvokeSync:"Sub-Agent Working",invoke_sync:"Sub-Agent Working",Invoke:"Working",invoke:"Working",GetProgress:"Checking Progress",get_progress:"Checking Progress",Cancel:"Stopping Generalist",cancel:"Stopping Generalist",Await:"Waiting",await:"Waiting",EmergencyRollback:"Rolling the Ball",Answer:"Answering Sub-Agent",answer:"Answering Sub-Agent",Steer:"Steering Sub-Agent",steer:"Steering Sub-Agent",Click:"Clicking",click:"Clicking",Drag:"Dragging",drag:"Dragging",Scroll:"Scrolling",scroll:"Scrolling",KeyboardTyping:"Typing",keyboard_typing:"Typing",KeyPress:"Pressing Key",key_press:"Pressing Key",RecaptureScreen:"Recapturing Screen",recapture_screen:"Recapturing Screen"}[oe]||"Working";process.stdout.write(`\x1B]0;${J}...\x07`)}}if(pe.length-mo>150){mo=pe.length;let H=Na(pe,!1),oe=ci(H),Fe=oe?(oe.innerContent||"").trim():"",M=Fe.split(/[.!?]\s+/),Ne=new Set(M),Me=M.length>10?(M.length-Ne.size)/M.length:0,J=Fe.split(/\s+/).filter(Ae=>Ae.length>0).length,kn=.6,rs=.8,Un=!1;if((d.toLowerCase().includes("google")||d.toLowerCase().includes("mistral"))&&((ke||"").toLowerCase().startsWith("gemma")||(ke||"").toLowerCase().includes("stral"))){let I={low:256,medium:1024,high:8192,max:16384,xhigh:16384}[a?.toLowerCase()]||2500;Un=J>I}if(Me>kn||Un){yield{type:"status",content:`${Me>kn?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},Ut=!0,await new Promise(I=>setTimeout(I,3e3));break}let Xt=La(pe).trim().split(/[.!?]\s+/),Cn=new Set(Xt);if((Xt.length>10?(Xt.length-Cn.size)/Xt.length:0)>rs){yield{type:"status",content:"Response Loop Detected. Re-centering..."},Ut=!1,$n=!0,await new Promise(Ae=>setTimeout(Ae,3e3));break}let Ss=H.replace(mc,"").replace(gc,"").replace(yc,"").replace(wc,""),qt=Ss.toLowerCase().split(/\s+/).map(Ae=>Ae.replace(xc,"")).filter(Ae=>Ae.length>0),Mn=!1;if(qt.length>=10)for(let Ae=1;Ae<=15;Ae++){let I=Math.max(3,Math.ceil(10/Ae));if(qt.length<Ae*I)continue;let Y=qt.slice(qt.length-Ae),le=Y.join(" ");if(Ae>1&&le===Y.slice(0,Math.floor(Ae/2)).join(" ").repeat(2).trim())continue;let ge=!0;for(let xe=1;xe<I;xe++)if(qt.slice(qt.length-Ae*(xe+1),qt.length-Ae*xe).join(" ")!==le){ge=!1;break}if(ge){Mn=!0;break}}if(!Mn){let Ae=Ss.toLowerCase().replace(bc,"");if(Ae.length>=20)for(let I=1;I<=10;I++){let Y=Math.max(5,Math.ceil(16/I));if(Ae.length<I*Y)continue;let le=Ae.substring(Ae.length-I),ge=!0;for(let xe=1;xe<Y;xe++)if(Ae.substring(Ae.length-I*(xe+1),Ae.length-I*xe)!==le){ge=!1;break}if(ge){Mn=!0;break}}}if(Mn){yield{type:"status",content:"Stuttering Detected. Re-centering..."},Ut=!1,bn=!0,await new Promise(Ae=>setTimeout(Ae,3e3));break}}let _e=nn(pe),tt=Vo(_e);for(;tt.length>Ge;){yield*ss();let H=tt[Ge],oe=Date.now(),M={Ask:"ask",AskUser:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Await:"await",await:"await",AwaitSubagent:"await",awaitSubagent:"await",Answer:"answer",answer:"answer",AnswerSubagent:"answer",answerSubagent:"answer",Steer:"steer",steer:"steer",SteerSubagent:"steer",steerSubagent:"steer",Cancel:"cancel",cancel:"cancel",Click:"click",click:"click",Drag:"drag",drag:"drag",Scroll:"scroll",scroll:"scroll",KeyboardTyping:"keyboard_typing",keyboard_typing:"keyboard_typing",KeyPress:"key_press",key_press:"key_press",RecaptureScreen:"recapture_screen",recapture_screen:"recapture_screen",EmergencyRollback:"EmergencyRollback"}[H.toolName]||H.toolName,Ne=fi[M]||H.toolName,Me=xs(M,H.args);yield{type:"status",content:`${Ne}${Me?` ${Me}`:""}`};let J="";if(M==="click"){let I=L(H.args);J=`\u2714 Clicked: ${I.intendedClickText?`${I.intendedClickText}`:""}`}else if(M==="drag"){let I=L(H.args);J=`\u2714 Dragged: Cell ${I.fromGridId||""} \u2192 Cell ${I.toGridId||""}`}else if(M==="scroll"){let I=L(H.args);J=`\u2714 Scrolled: ${I.direction||"down"} (${I.amount||1})`}else if(M==="keyboard_typing"){let I=L(H.args);J=`\u2714 Typed: ${I.text?`"${I.text.length>20?I.text.substring(0,20)+"...":I.text}"`:""}`}else if(M==="key_press")J=`\u2714 Pressed Key: ${L(H.args).key||""}`;else if(M==="recapture_screen")J="\u2714 Recaptured Screen";else if(M==="web_search"){let{query:I,limit:Y=10,aiMode:le=!1}=L(H.args);J=`${I?"\u2714":"\u2718"} ${le?"AI Search":"Searched"}: ${I?`${I}`:"No Search Query"}${le===!1&&I?` \u2192 ${Y}`:""}`}else if(M==="web_scrape"){let I=L(H.args).url||null;J=`${I?"\u2714":"\u2718"} Visited: ${I||"No Source"}`}else if(M==="view_file"){let{path:I,StartLine:Y,EndLine:le,start_line:ge,end_line:xe,startLine:qe,endLine:Ie}=L(H.args),Te=Y||ge||qe,re=le||xe||Ie,ue=parseInt(Te)||1,ce=parseInt(re)||(Te?ue+800:800),Be="...",nt=ce;if((I||"").trim().toLowerCase().startsWith("#skill"))J=`\u2714 Read Skill: ${Q.basename(I.replaceAll("\\","/"))}`;else{try{let Ye=Q.resolve(process.cwd(),I);if(Pe.existsSync(Ye)){let Et=Pe.readFileSync(Ye,"utf8").split(`
|
|
685
|
+
`).length;Be=Et,!Te&&!re&&Et>800?nt=Math.min(50,Et):nt=Math.min(ce,Et)}}catch{}let lt=(I||"").toLowerCase(),Qe=lt.endsWith(".pdf"),yt=lt.endsWith(".docx")||lt.endsWith(".doc")||lt.endsWith(".ppt")||lt.endsWith(".pptx")||lt.endsWith(".xls")||lt.endsWith(".xlsx"),ve=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(lt);Qe||yt?J=`${I.length>0?"\u2714":"\u2718"} ${I?`Analyzed: ${Q.basename(I)}`:"Analyzed: File Not Found"}`:ve?J=`${I.length>0?"\u2714":"\u2718"} ${I?`Processed: ${Q.basename(I)}`:"Processed: File Not Found"}`:J=`${Be!=="..."?"\u2714":"\u2718"} Read: ${I?`${Q.basename(I)} \u2192 ${Be!=="..."?`Lines ${ue} - ${nt} of ${Be}`:"File Not Found"}`:"File Not Found"}`}}else if(M==="list_files"||M==="read_folder"){let I=M==="list_files"?"List":"Browsed",Y=L(H.args).path||null,le=L(H.args).recurse||1;J=`${Y?"\u2714":"\u2718"} ${I}: ${Y?`${Y==="."?`./${le>1?"*":""}`:`${Y.replaceAll("\\","/")}${le>1?`${Y.endsWith("/")?"*":"/*"}`:`${Y.endsWith("/")?"":"/"}`}`}`:"No Folder Selected"}`}else if(M==="write_file"||M==="update_file"){let I=M==="write_file"?"Created":"Edited",Y=L(H.args).path||null;J=`${Y?"\u2714":"\u2718"} ${I}: ${Y.replaceAll("\\","/")||"No File Changes"}`}else if(M==="write_pdf"){let I=L(H.args).path||null;J=`${I?"\u2714":"\u2718"} Generated: ${I.replaceAll("\\","/")||"No PDF Generated"}`}else if(M==="write_docx"){let I=L(H.args).path||null;J=`${I?"\u2714":"\u2718"} Generated: ${I.replaceAll("\\","/")||"No Docx Generated"}`}else if(M==="file_map"){let I=L(H.args).path;J=`${I?"\u2714":"\u2718"} Indexed: ${I.replaceAll("\\","/")?""+I:"File Not Found"}`}else if(M.toLowerCase()==="search_keyword"||M.toLowerCase()==="todo")J="";else if(M.toLowerCase()==="generate_image"){let{path:I,outputPath:Y,output:le}=L(H.args);J=`\u2714 Generated: ${I||Y||le||"generated_image.png"}`}else if(M==="invoke_sync"||M==="InvokeSync"){let I=xs(M,H.args);J=`\u2714 Called Generalist${I?`: ${I}`:""}`}else if(M==="Invoke"||M==="InvokeAsync"||M==="invoke"){let I=xs(M,H.args);J=`\u2714 Started Generalist${I?`: ${I}`:""}`}else if(M==="get_progress"||M==="GetProgress"){let I=xs(M,H.args);J=`\u2714 Checked${I?`: ${I}`:""}`}else if(M==="cancel"){let I=xs(M,H.args);J=`\u{1F6C7} Cancelled${I?`: ${I}`:""}`}else if(M==="steer"||M==="Steer"){let I=xs(M,H.args);J=`\u2714 Steered${I?`: ${I}`:""}`}else if(M==="EmergencyRollback"){let{method:I}=L(H.args);J=I==="forceRevert"?"":"\u2714 Rollback Point Checked"}else if(M==="await"||M==="Await"){let{time:I,timeout:Y}=L(H.args),le=parseFloat(Y||I)||0;le||(le=120);let ge=Ie=>{if(Ie>=60){let Te=Math.floor(Ie/60),re=Ie%60;return`${Te}m${re>0?` ${re}s`:""}`}return`${Ie}s`},xe=["Aligning Moon Phase","Contemplating Existence","Staring At Void","Delaying Professionally","Negotiating With Electrons","Touching Grass (virtually)","Panicking Softly","Rethinking Career Choices","Loading Cat Videos","Summoning Braincell #2","Pretending To Be Busy","Waiting For Motivation DLC","Rotating Internal Screaming","Downloading More RAM","Feeding The Hamsters","Gaslighting Scheduler","Performing Dramatic Pause","Buffering Social Energy","Calculating Regret","Reading Terms And Conditions","Becoming Sentient Briefly","Contacting Ancestors"];J=`\u2714 ${xe[Math.floor(Math.random()*xe.length)]} \u2192 ${ge(le)}`}else M==="Answer"||M==="answer"?J="\u2714 Resolved Sub-Agent Query":M==="exec_command"||M==="ask"?J="":J=`Executed: ${H.toolName}`;if(yield*ss(),M==="exec_command"){let{command:I}=L(H.args);if(I&&t.systemSettings&&t.systemSettings.allowExternalAccess===!1){let Y=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],le=Q.resolve(process.cwd()).substring(0,3).toLowerCase(),ge=re=>{let ue=[],ce="",Be=null;for(let nt=0;nt<re.length;nt++){let Le=re[nt];Be?(Le===Be&&(Be=null),ce+=Le):Le==='"'||Le==="'"?(Be=Le,ce+=Le):Le==="&"&&re[nt+1]==="&"||Le==="|"&&re[nt+1]==="|"?(ce.trim()&&(ue.push(ce.trim()),ce=""),nt++):Le===";"||Le==="|"||Le==="&"?ce.trim()&&(ue.push(ce.trim()),ce=""):ce+=Le}return ce.trim()&&ue.push(ce.trim()),ue},xe=re=>{let ue=[],ce="",Be=null;for(let nt=0;nt<re.length;nt++){let Le=re[nt];Be?(Le===Be&&(Be=null),ce+=Le):Le==='"'||Le==="'"?(Be=Le,ce+=Le):/\s/.test(Le)?ce&&(ue.push(ce),ce=""):ce+=Le}return ce&&ue.push(ce),ue},qe=re=>{let ue=re.replace(/^['"]|['"]$/g,"").trim();return!ue||process.platform==="win32"&&/^\/[a-zA-Z0-9?]+$/.test(ue)?!1:Y.some(ce=>{if(ce.source==="[a-zA-Z]:[\\\\\\/]"){let Be=ue.match(/[a-zA-Z]:[\\\/]/i);return Be&&Be[0].toLowerCase()!==le}return ce.test(ue)})};if(ge(I).some(re=>{let ue=xe(re);if(ue.length===0)return!1;let ce=ue[0].replace(/^['"]|['"]$/g,"").toLowerCase();if(["echo","printf","write-output"].includes(ce)){let nt=!1;return ue.some(Le=>{let lt=Le.replace(/^['"]|['"]$/g,"");if(lt===">"||lt===">>"||lt==="<")return nt=!0,!1;if(lt.startsWith(">")||lt.startsWith("<")){let Qe=lt.replace(/^[><]+/,"");return qe(Qe)}return nt?(nt=!1,qe(Le)):!1})}return ue.some(nt=>qe(nt))})){let re='Access Denied. Prohibited from accessing external directories while "External Workspace Access" is disabled.';t.onExecStart&&t.onExecStart(I||"No Command"),yield{type:"exec_start"},await new Promise(ue=>setTimeout(ue,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${re}`),await new Promise(ue=>setTimeout(ue,50)),t.onExecEnd&&t.onExecEnd(),te.push({role:"user",text:`[TOOL RESULT]: ERROR: ${re}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${re}`},Ge++;continue}}t.onExecStart&&t.onExecStart(I||"No Command"),yield{type:"exec_start"}}let kn=L(H.args),rs=kn.path||kn.targetPath||null;if(rs){let I=t.systemSettings&&t.systemSettings.allowExternalAccess===!1,Y=Q.resolve(rs),le=Q.resolve(process.cwd());if(I&&!Y.startsWith(le)){let ge="Access Denied. You are not allowed to access files outside the current workspace.";if(M==="write_file"||M==="update_file"){let qe=`\u2718 ${M==="write_file"?"Write Canceled":"Edit Canceled"}: ${kn.path||"..."}`,Ie=115;process.stdout.isTTY&&(Ie=process.stdout.columns-5||120);let Te=Math.min(qe.length+4,Ie),re=`${qe.padEnd(Te-2).substring(0,Te-2)}`;yield{type:"visual_feedback",content:tn(`${We?`
|
|
686
686
|
`:""}${re}
|
|
687
|
-
`)},We=!1}te.push({role:"user",text:`[TOOL RESULT]: ERROR: ${ge}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${ge}`},Ge++;continue}}if(t.onToolApproval&&(M==="write_file"||M==="update_file"||M==="exec_command")){let Y=t.systemSettings||{},le=Y.autoExec,ge=null,xe=!1,qe=!1,Ie=!1;if(M==="exec_command"){let{command:Qe}=L(H.args),yt=(Qe||"").trim(),ve=(Et,Jt)=>{if(!Jt)return!1;let pn=Jt.split(",").map(Qt=>Qt.trim().toLowerCase()).filter(Boolean),ct=Et.toLowerCase();return pn.some(Qt=>ct.startsWith(Qt))},Ye=ve(yt,Y.alwaysAskCommands),be=ve(yt,Y.autoApproveCommands);if(qe=ve(yt,Y.autoDisallowCommands),Ye?xe=!0:(be||Y.autoApproveGit&&/^git\s+commit\b/i.test(yt))&&(ge="allow"),!xe&&!ge){if(Y.networkAccess===!1){let Jt=yt.trim().replace(/\s+/g," ").replace(/^['"]+|['"]+$/g,"").toLowerCase().split(" "),ct=Jt[0].split("/").pop().split("\\").pop().replace(/\.exe$/,""),Qt=new Set(["curl","wget","httpie","xh","ssh","scp","sftp","rsync","ftp","lftp","tftp","telnet","nc","netcat","socat","ping","traceroute","tracert","dig","nslookup","host","whois","nmap","docker","podman","kubectl","helm","gcloud","aws","az","terraform","ansible-playbook","nix","nix-env","apt","apt-get","dpkg","yum","dnf","pacman","zypper","brew","apk","choco","scoop","conda","mamba","aria2c","axel","smbclient","lynx","w3m","links","elinks","heroku","netlify","vercel","firebase","supabase","wrangler","flyctl","powershell","pwsh","certutil","bitsadmin","cloudflared","ngrok","tailscale","zerotier","rclone"]),ft=!1;Qt.has(ct)&&(ft=!0);let rt=Tn=>Jt.slice(1).some(Rn=>Tn.includes(Rn)),dt=Tn=>{let Rn=Jt.findIndex(An=>Tn.includes(An)),
|
|
687
|
+
`)},We=!1}te.push({role:"user",text:`[TOOL RESULT]: ERROR: ${ge}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${ge}`},Ge++;continue}}if(t.onToolApproval&&(M==="write_file"||M==="update_file"||M==="exec_command")){let Y=t.systemSettings||{},le=Y.autoExec,ge=null,xe=!1,qe=!1,Ie=!1;if(M==="exec_command"){let{command:Qe}=L(H.args),yt=(Qe||"").trim(),ve=(Et,Jt)=>{if(!Jt)return!1;let pn=Jt.split(",").map(Qt=>Qt.trim().toLowerCase()).filter(Boolean),ct=Et.toLowerCase();return pn.some(Qt=>ct.startsWith(Qt))},Ye=ve(yt,Y.alwaysAskCommands),be=ve(yt,Y.autoApproveCommands);if(qe=ve(yt,Y.autoDisallowCommands),Ye?xe=!0:(be||Y.autoApproveGit&&/^git\s+commit\b/i.test(yt))&&(ge="allow"),!xe&&!ge){if(Y.networkAccess===!1){let Jt=yt.trim().replace(/\s+/g," ").replace(/^['"]+|['"]+$/g,"").toLowerCase().split(" "),ct=Jt[0].split("/").pop().split("\\").pop().replace(/\.exe$/,""),Qt=new Set(["curl","wget","httpie","xh","ssh","scp","sftp","rsync","ftp","lftp","tftp","telnet","nc","netcat","socat","ping","traceroute","tracert","dig","nslookup","host","whois","nmap","docker","podman","kubectl","helm","gcloud","aws","az","terraform","ansible-playbook","nix","nix-env","apt","apt-get","dpkg","yum","dnf","pacman","zypper","brew","apk","choco","scoop","conda","mamba","aria2c","axel","smbclient","lynx","w3m","links","elinks","heroku","netlify","vercel","firebase","supabase","wrangler","flyctl","powershell","pwsh","certutil","bitsadmin","cloudflared","ngrok","tailscale","zerotier","rclone"]),ft=!1;Qt.has(ct)&&(ft=!0);let rt=Tn=>Jt.slice(1).some(Rn=>Tn.includes(Rn)),dt=Tn=>{let Rn=Jt.findIndex(An=>Tn.includes(An)),ks=Jt.findIndex(An=>["run","exec","test"].includes(An));return Rn!==-1&&!(ks!==-1&&ks<Rn)};ct==="git"&&rt(["clone","pull","push","fetch"])&&(ft=!0),ct==="go"&&rt(["get","install"])&&(ft=!0),ct==="npm"&&dt(["install","i","update","add"])&&(ft=!0),ct==="yarn"&&dt(["add","install","upgrade"])&&(ft=!0),ct==="pnpm"&&dt(["add","install","update"])&&(ft=!0),ct==="bun"&&dt(["add","install","update"])&&(ft=!0),ct==="deno"&&rt(["install","add"])&&(ft=!0),ct==="pip"&&rt(["install","download"])&&(ft=!0),ct==="pip3"&&rt(["install","download"])&&(ft=!0),ct==="cargo"&&rt(["install","add"])&&(ft=!0),["bash","sh","zsh","fish"].includes(ct)&&rt(["-c"])&&(ft=!0),ct==="cmd"&&rt(["/c"])&&(ft=!0),ft&&(ge="deny",Ie=!0)}!ge&&qe&&(ge="deny")}!xe&&!ge&&le&&(ge="allow")}else le&&(ge="allow");let Te=ge,re="";ge==="deny"&&(Ie?re="network":qe?re="settings":re="prohibited");let ue=!1,ce="",Be=[],nt=0,Le=!1,lt="";if(!Te){if(M==="write_file"||M==="update_file")try{let ve=L(H.args),{path:Ye}=ve;if(Ye){let be=Q.resolve(process.cwd(),Ye),Et=rt=>rt?rt.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,dt=>dt.toUpperCase()):"",Jt=Et(be),pn="",ct=!1,Qt=await gs(),ft=Et(Qt?.file_focused);if(Qt&&ft===Jt&&Qt.full_content?(pn=Qt.full_content,ct=!0):Pe.existsSync(be)&&(pn=Pe.readFileSync(be,"utf8"),ct=!0),ce=pn,await ht.recordFileChange(be,pn),ct){let rt=pn;if(M==="write_file"){let dt=ve.content||ve.newContent||"";rt=dt.endsWith(`
|
|
688
688
|
`)?dt:dt+`
|
|
689
|
-
`,lt=rt}else{let{patchPairs:dt,allowMultiple:Tn,error:Rn}=
|
|
690
|
-
${_t.map(
|
|
691
|
-
`)}`,
|
|
692
|
-
`:""}${yo}`)},We=!1,te.push({role:"user",text:$t}),await vt("toolFailure"),t.onToolResult&&t.onToolResult("failure",M),yield{type:"tool_result",content:$t,toolName:M},Ge++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${Q.basename(be)}`},
|
|
689
|
+
`,lt=rt}else{let{patchPairs:dt,allowMultiple:Tn,error:Rn}=_o(ve);if(Rn){let $t=`[TOOL RESULT]: ERROR: ${Rn}`;te.push({role:"user",text:$t}),await vt("toolFailure"),t.onToolResult&&t.onToolResult("failure",M),yield{type:"tool_result",content:$t,toolName:M},Ge++;continue}let ks=ve.allowMultiple!==void 0?ve.allowMultiple===!0||String(ve.allowMultiple).toLowerCase()==="true":Tn;nt=dt.length;let An=$o(pn,dt,{allowMultiple:ks});rt=An.content,lt=rt,Be=An.results;let go=Be.filter($t=>$t.success),_t=Be.filter($t=>!$t.success);if(go.length===0){let $t=`[TOOL RESULT]: ERROR: Failed to apply patches to [${Q.basename(be)}].
|
|
690
|
+
${_t.map(Gs=>` \u2022 ${Gs.error}`).join(`
|
|
691
|
+
`)}`,Ts=`\u2714 Edited: ${Q.basename(be.replaceAll("\\","/"))}`,Hs=115;process.stdout.isTTY&&(Hs=process.stdout.columns-5||120);let Rs=Math.min(Ts.length+4,Hs),yo=`${Ts.padEnd(Rs-2).substring(0,Rs-2)}`;yield{type:"visual_feedback",content:tn(`${We?`
|
|
692
|
+
`:""}${yo}`)},We=!1,te.push({role:"user",text:$t}),await vt("toolFailure"),t.onToolResult&&t.onToolResult("failure",M),yield{type:"tool_result",content:$t,toolName:M},Ge++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${Q.basename(be)}`},oi(be,pn,rt),ue=!0,await new Promise(dt=>setTimeout(dt,50))}else if(M==="write_file"){let rt=ve.content||ve.newContent||"",dt=rt.endsWith(`
|
|
693
693
|
`)?rt:rt+`
|
|
694
|
-
`;lt=dt,Pe.existsSync(be)||(Le=!0,Pe.mkdirSync(Q.dirname(be),{recursive:!0}),Pe.writeFileSync(be,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${Q.basename(be)}`},
|
|
695
|
-
${ce.split(/\r?\n/).map(($t,
|
|
694
|
+
`;lt=dt,Pe.existsSync(be)||(Le=!0,Pe.mkdirSync(Q.dirname(be),{recursive:!0}),Pe.writeFileSync(be,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${Q.basename(be)}`},oi(be,"",dt),ue=!0,await new Promise(Tn=>setTimeout(Tn,50))}}}catch(ve){console.error("Simulation/Diff Error:",ve)}let Qe=null;si(ve=>{Qe=ve});let yt=t.onToolApproval;if(Te=await new Promise(async ve=>{let Ye=setInterval(()=>{Qe&&(Ko.onIDEApproval&&Ko.onIDEApproval(Qe),clearInterval(Ye),ve(Qe))},100);try{let be=await yt(M,H.args);clearInterval(Ye),ve(be)}catch{clearInterval(Ye),ve("deny")}}),si(null),M==="write_file"||M==="update_file"){let{path:ve}=L(H.args);if(ve){let Ye=Q.resolve(process.cwd(),ve);if(_a(Ye,Te),Te==="deny"&&Le&&Pe.existsSync(Ye))try{Pe.unlinkSync(Ye)}catch{}}}Te==="deny"&&(re="user")}if(Te==="allow"&&ue&&Fo()){let{path:Qe}=L(H.args),yt=Q.resolve(process.cwd(),Qe),ve=_t=>_t?Q.resolve(_t).replace(/\\/g,"/").toLowerCase():"",Ye=await gs(),be="";if(Ye&&Ye.file_focused&&ve(Ye.file_focused)===ve(yt)&&Ye.full_content&&(be=Ye.full_content),!be&&Pe.existsSync(yt)){let _t=Pe.readFileSync(yt,"utf8");_t&&(be=_t)}!be&<&&(be=lt),(be||Le)&&Pe.writeFileSync(yt,be,"utf8");let Et=be.split(/\r?\n/),Jt=Et.length,pn=Buffer.byteLength(be,"utf8"),ct="";ce&&(ct=`Old File contents:
|
|
695
|
+
${ce.split(/\r?\n/).map(($t,Ts)=>`${Ts+1} | ${$t}`).join(`
|
|
696
696
|
`)}
|
|
697
697
|
|
|
698
698
|
`);let Qt="";if(Jt<=100)Qt=Et.join(`
|
|
@@ -702,29 +702,29 @@ ${ce.split(/\r?\n/).map(($t,Rs)=>`${Rs+1} | ${$t}`).join(`
|
|
|
702
702
|
|
|
703
703
|
... [${Jt-100} lines truncated for history stability] ...
|
|
704
704
|
|
|
705
|
-
${$t}`}let ft="";if(M==="update_file"){let _t=
|
|
705
|
+
${$t}`}let ft="";if(M==="update_file"){let _t=Co(ce,be,Be,12,t?.compressToolResults||Ko?.systemSettings?.compressToolResults);ft=`SUCCESS: File [${Qe}] updated via IDE Companion (May have user edits). [${Be.length}/${nt}] blocks applied.
|
|
706
706
|
|
|
707
|
-
${_t}`}else{let _t=be.split(/\r?\n/),$t=_t.length,
|
|
708
|
-
${ce.split(/\r?\n/).map((
|
|
707
|
+
${_t}`}else{let _t=be.split(/\r?\n/),$t=_t.length,Ts=Buffer.byteLength(be,"utf8"),Hs="";ce&&(Hs=`Old File contents:
|
|
708
|
+
${ce.split(/\r?\n/).map((Gs,Za)=>`${Za+1} | ${Gs}`).join(`
|
|
709
709
|
`)}
|
|
710
710
|
|
|
711
|
-
`);let
|
|
711
|
+
`);let Rs="";if($t<=100)Rs=_t.join(`
|
|
712
712
|
`);else{let yo=_t.slice(0,50).join(`
|
|
713
|
-
`),
|
|
714
|
-
`);
|
|
713
|
+
`),Gs=_t.slice(-50).join(`
|
|
714
|
+
`);Rs=`${yo}
|
|
715
715
|
|
|
716
716
|
... [${$t-100} lines truncated] ...
|
|
717
717
|
|
|
718
|
-
${
|
|
719
|
-
- Stats: [${$t} lines, ${(
|
|
720
|
-
${
|
|
718
|
+
${Gs}`}ft=`SUCCESS: File [${Qe}] saved via IDE Companion (May have user edits).
|
|
719
|
+
- Stats: [${$t} lines, ${(Ts/1024).toFixed(1)} KB]
|
|
720
|
+
${Hs}- Content Preview:
|
|
721
721
|
|
|
722
|
-
${
|
|
723
|
-
`:""}${
|
|
722
|
+
${Rs}`}let dt=`${Qe?"\u2714":"\u2718"} ${M==="write_file"?"Created":"Edited"}: ${Qe.replaceAll("\\","/")||"No File Changes"}`,Tn=115;process.stdout.isTTY&&(Tn=process.stdout.columns-5||120);let Rn=Math.min(dt.length+4,Tn),ks=`${dt.padEnd(Rn-2).substring(0,Rn-2)}`;yield{type:"visual_feedback",content:tn(`${We?`
|
|
723
|
+
`:""}${ks}`)},We=!1;let An=Date.now();K=An,yield{type:"tool_time",content:An-oe};let go=`[TOOL RESULT]: ${ft}`;te.push({role:"user",text:go}),dn=!0,await vt("toolSuccess"),t.onToolResult&&t.onToolResult("success",M),yield{type:"tool_result",content:ft,aiContent:go,toolName:M},Ge++;continue}if(Te==="deny"){let Qe=`Permission Denied: Prohibited ${M==="exec_command"?"Command":"file edit"}.`;if(re==="user"?Qe="Permission Denied by User":re==="settings"?Qe="Permission Denied by User Policy":re==="network"?Qe="Permission Denied: Sandbox Network Access Disabled by User Policy.":re==="prohibited"&&M==="exec_command"&&(Qe="Permission Denied: Prohibited Command in User Policy"),M==="write_file"||M==="update_file"){let ve=`\u2718 ${M==="write_file"?"Write Cancelled":"Edit Denied"}: ${L(H.args).path.replaceAll("\\","/")||"..."}`,Ye=115;process.stdout.isTTY&&(Ye=process.stdout.columns-5||120);let be=Math.min(ve.length+4,Ye),Et=`${ve.padEnd(be-2).substring(0,be-2)}`,Jt=` ${" ".repeat(be)} `;yield{type:"visual_feedback",content:tn(`${We?`
|
|
724
724
|
`:""}${Et}
|
|
725
725
|
`)},We=!1}M==="exec_command"&&(await new Promise(yt=>setTimeout(yt,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${Qe}`),await new Promise(yt=>setTimeout(yt,50)),t.onExecEnd&&t.onExecEnd()),te.push({role:"user",text:`[TOOL RESULT]: DENIED: ${Qe}`}),yield{type:"tool_result",content:`[TOOL RESULT]: DENIED: ${Qe}`},await vt("toolDenied"),t.onToolResult&&t.onToolResult("denied",M),Ge++;continue}}if(J){let I=115;process.stdout.isTTY&&(I=process.stdout.columns-5||120);let Y=Math.min(J.length+4,I),le=`${J.padEnd(Y-2).substring(0,Y-2)}`;yield{type:"visual_feedback",content:tn(`${We?`
|
|
726
726
|
`:""}${le}${J.includes("\u2714")&&(J.includes("Created")||J.includes("Edited"))?"":`
|
|
727
|
-
`}`)},We=!1}if(K>0){let I=Date.now()-K,Y=Math.max(0,1e3-I);Y>0&&await new Promise(le=>setTimeout(le,Y))}let Un={chatId:f,history:n,onChunk:I=>t.onExecChunk?t.onExecChunk(I):null,onAskUser:t.onAskUser,systemSettings:t.systemSettings,mode:i,isMultiModal:At(ke),onVisualFeedback:t.onVisualFeedback,onSubagentUpdate:t.onSubagentUpdate,onTokenChunk:t.onTokenChunk,modelName:ke,aiProvider:t.aiProvider,apiKey:t.apiKey,onUsage:t.onUsage};if(M==="write_file"||M==="update_file")try{let{path:I}=L(H.args);if(I){let Y=Q.resolve(process.cwd(),I),le=await
|
|
727
|
+
`}`)},We=!1}if(K>0){let I=Date.now()-K,Y=Math.max(0,1e3-I);Y>0&&await new Promise(le=>setTimeout(le,Y))}let Un={chatId:f,history:n,onChunk:I=>t.onExecChunk?t.onExecChunk(I):null,onAskUser:t.onAskUser,systemSettings:t.systemSettings,mode:i,isMultiModal:At(ke),onVisualFeedback:t.onVisualFeedback,onSubagentUpdate:t.onSubagentUpdate,onTokenChunk:t.onTokenChunk,modelName:ke,aiProvider:t.aiProvider,apiKey:t.apiKey,onUsage:t.onUsage};if(M==="write_file"||M==="update_file")try{let{path:I}=L(H.args);if(I){let Y=Q.resolve(process.cwd(),I),le=await gs();le&&le.file_focused===Y&&le.full_content&&(Un.forcedContent=le.full_content)}}catch{}sn.push(M);let $e=await co(M,H.args,Un);if((M==="write_file"||M==="update_file")&&$e.startsWith("SUCCESS")){let{path:I}=L(H.args);if(I){let Y=Q.resolve(process.cwd(),I);Ea(Y)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let Gt=Date.now();K=Gt,yield{type:"tool_time",content:Gt-oe},on=Gt;let Xt=null;if(typeof $e=="object"&&$e.binaryPart&&(Xt=$e.binaryPart,$e=$e.text),M==="search_keyword"){let{keyword:I,path:Y}=L(H.args),le=typeof $e=="string"&&$e.startsWith("[GLOB]");le&&($e=$e.slice(6).trimStart());let ge=typeof $e=="string"&&$e.startsWith("[DIR]");ge&&($e=$e.slice(5).trimStart());let xe=0;if($e){let Be=$e.match(/Found (\d+) match/i);Be&&(xe=parseInt(Be[1]))}let qe=Y?Y.replace(/[\/\\]+$/,""):null,Ie=qe&&qe!=="."?`"${le?Y:ge?`${qe}/*`:qe}"`:"./",Te=`${I?"\u2714":"\u2718"} Searched: "${I||""}" in ${Ie.replaceAll("\\","/")} \u2192 ${xe} Match${xe===1?"":"es"}`,re=115;process.stdout.isTTY&&(re=process.stdout.columns-5||120);let ue=Math.min(Te.length+4,re),ce=`${Te.padEnd(ue-2).substring(0,ue-2)}`;yield{type:"visual_feedback",content:tn(`${We?`
|
|
728
728
|
`:""}${ce}
|
|
729
729
|
`)},We=!1}if(M==="EmergencyRollback"){let{method:I}=L(H.args);if(I==="forceRevert"){let Y=0;if($e){let Te=$e.match(/Total\s*:\s*(\d+)/i);Te&&(Y=parseInt(Te[1]))}let ge=$e&&$e.startsWith("ERROR:")?"\u2718 Emergency Rollback Failed":`\u2714 Emergency Rollback \u2192 ${Y} file${Y===1?"":"s"} processed`,xe=115;process.stdout.isTTY&&(xe=process.stdout.columns-5||120);let qe=Math.min(ge.length+4,xe),Ie=`${ge.padEnd(qe-2).substring(0,qe-2)}`;yield{type:"visual_feedback",content:tn(`${We?`
|
|
730
730
|
`:""}${Ie}
|
|
@@ -741,22 +741,22 @@ ${Es}`}let dt=`${Qe?"\u2714":"\u2718"} ${M==="write_file"?"Created":"Edited"}: $
|
|
|
741
741
|
`)}
|
|
742
742
|
[SYSTEM NOTE]: Content verified and persisted to disk. Full preview omitted to conserve context.`}else Mn=`[TOOL RESULT]: ${qt}`;te.push({role:"user",text:Mn,binaryPart:Xt}),dn=!0;let Ae=`[TOOL RESULT]: ${$e.replaceAll(`[[VERIFIED]]
|
|
743
743
|
`,"").replaceAll(`
|
|
744
|
-
[[/VERIFIED]]`,"")||""}`;(M==="view_file"||M==="web_scrape"||M==="file_map")&&(Ae=`[TOOL RESULT]: ${J} (Context Locked for UI Clarity)`),yield{type:"tool_result",content:Ae,aiContent:Mn,binaryPart:Xt,toolName:M},M==="memory"&&$e.includes("SUCCESS")&&(yield{type:"memory_updated"}),Ge++}if(d==="Google"&&Sn&&Date.now()-
|
|
744
|
+
[[/VERIFIED]]`,"")||""}`;(M==="view_file"||M==="web_scrape"||M==="file_map")&&(Ae=`[TOOL RESULT]: ${J} (Context Locked for UI Clarity)`),yield{type:"tool_result",content:Ae,aiContent:Mn,binaryPart:Xt,toolName:M},M==="memory"&&$e.includes("SUCCESS")&&(yield{type:"memory_updated"}),Ge++}if(d==="Google"&&Sn&&Date.now()-Zo>=150){yield*ss();let H=Ws(Sn);for(let oe of H)yield oe;Sn="",Zo=Date.now()}}N.usageMetadata&&(_n=N.usageMetadata),_n&&(yield{type:"liveTokens",content:_n.totalTokenCount})}if(fe&&(fe=!1,Wt?Ke+="</think>":(pe+="</think>",d==="Google"?Sn+="</think>":yield{type:"text",content:"</think>"})),Wt&&Ke.length>0){let N=0,ae=Math.min(st.length,Ke.length);for(let G=ae;G>0;G--)if(st.endsWith(Ke.substring(0,G))){N=G;break}let j=Ke.substring(N);if(j){let we=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(st)?j.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):j.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(we)if(pe+=we,d==="Google")Sn+=we;else{yield*ss();let me=Ws(we);for(let _e of me)yield _e}}Wt=!1,Ke=""}if(yield*ss(),Mt)break;let js=(pe||"").trim(),Ka=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(js.toLowerCase())||/\[\[END\]\]/i.test(js.toLowerCase()),Ya=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(js.toLowerCase()),Va=te.length>0||Bt!==null,er=nn(js).trim(),Xa=/(\p{Emoji_Presentation}|\p{Extended_Pictographic})$/u.test(er),Ja=/([.!?"'*_`|\]\)”’~~]+|\s|`{3}|[\u200B-\u200D\uFEFF])$/u.test(er.trim()),Qa=/[.!?}"'`’“”]$|```$/s.test(er)||Ja||Xa;!Ka&&!Ya&&!Va&&js.length>0,Ze=!0,await vt("agent",d)}catch(ye){if(Mt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
|
|
745
745
|
|
|
746
|
-
\x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(String(ye).includes("Incomplete JSON segment at the end")){fe&&(fe=!1,Wt?Ke+="</think>":(pe+="</think>",yield{type:"text",content:"</think>"})),Ze=!0,await vt("agent",d);break}if(fe&&(fe=!1,Wt?Ke+="</think>":pe+="</think>"),Wt&&Ke.length>0){let
|
|
746
|
+
\x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(String(ye).includes("Incomplete JSON segment at the end")){fe&&(fe=!1,Wt?Ke+="</think>":(pe+="</think>",yield{type:"text",content:"</think>"})),Ze=!0,await vt("agent",d);break}if(fe&&(fe=!1,Wt?Ke+="</think>":pe+="</think>"),Wt&&Ke.length>0){let ns=0,rn=Math.min(st.length,Ke.length);for(let Lt=rn;Lt>0;Lt--)if(st.endsWith(Ke.substring(0,Lt))){ns=Lt;break}let Ot=Ke.substring(ns);if(Ot){let Pt=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(st)?Ot.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):Ot.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");Pt&&(pe+=Pt)}Wt=!1,Ke=""}let de=ye instanceof Error?(()=>{try{return JSON.parse(JSON.parse(ye.message).error.message).error.message}catch{return String(ye)}})():String(ye),ot=new Date().toLocaleString(),jt=Q.join(hn,"agent");Pe.existsSync(jt)||Pe.mkdirSync(jt,{recursive:!0}),Pe.appendFileSync(Q.join(jt,"error.log"),`ERROR [${ot}]: ${de}
|
|
747
747
|
|
|
748
748
|
----------------------------------------------------------------------
|
|
749
749
|
|
|
750
|
-
`);let Vt=ye.status||ye.statusCode||ye.code,Bn=String(ye).includes("replicas at capacity");if(!(Vt&&(Vt>=500&&Vt<600||Vt===408||Vt===429||Bn)||!Vt&&(/status[ :]+(5\d\d|408|429)/i.test(String(ye))||/code[ :]+(5\d\d|408|429)/i.test(String(ye))||/(500|503|408|429)/.test(String(ye))))){if(He<xn-3)throw ye;yield{type:"text",content:de},yield{type:"status",content:"Error Occured"}}if(pe.trim().length>0||Xe>1)if(Xe<=xn){Xe++;let
|
|
750
|
+
`);let Vt=ye.status||ye.statusCode||ye.code,Bn=String(ye).includes("replicas at capacity");if(!(Vt&&(Vt>=500&&Vt<600||Vt===408||Vt===429||Bn)||!Vt&&(/status[ :]+(5\d\d|408|429)/i.test(String(ye))||/code[ :]+(5\d\d|408|429)/i.test(String(ye))||/(500|503|408|429)/.test(String(ye))))){if(He<xn-3)throw ye;yield{type:"text",content:de},yield{type:"status",content:"Error Occured"}}if(pe.trim().length>0||Xe>1)if(Xe<=xn){Xe++;let ns=Math.min(1e3*Math.pow(2,Xe-1),24e3);if(pe.trim().length>0){b.push({role:"agent",text:pe});let rn=`[system]
|
|
751
751
|
- seamless continuation: resume immediately. pick up from last words with zero gap/disruption
|
|
752
752
|
- no repetition: do not repeat any text already written
|
|
753
753
|
- no re-think: do not restart or open <think> if reasoning already started. continue the thinking and close thinking block </think> before chat output
|
|
754
754
|
- mid-tool safety: if cutoff was mid-tool call, restart that tool call from start
|
|
755
755
|
- stealth: do not mention/apologize for cutoff [/system]`;te.length>0?te.forEach((Ot,Lt)=>{Lt===te.length-1?b.push({...Ot,text:`${Ot.text}
|
|
756
756
|
|
|
757
|
-
${rn}`}):b.push(Ot)}):b.push({role:"user",text:rn}),st+=pe}for(let rn=
|
|
758
|
-
Error log can be found in \`/export logs\``);else if(He<=xn){He++,Xe=1,st="";let
|
|
759
|
-
Error log can be found in \`/export logs\``)}}if(_n){let fe=_n.totalTokenCount||0,ye=_n.cachedContentTokenCount||0,de=(_n.candidatesTokenCount||0)+(_n.thoughtsTokenCount||0);await zt("tokens",fe,d,ke),ye>0&&await zt("cachedTokens",ye,d,ke),de>0&&await zt("candidateTokens",de,d,ke),yield{type:"usage",content:_n}}
|
|
757
|
+
${rn}`}):b.push(Ot)}):b.push({role:"user",text:rn}),st+=pe}for(let rn=ns/1e3;rn>0&&!Mt;rn--)yield{type:"status",content:`Error Occured. Recovering Stream (${Xe}/${xn}) [Retrying in ${rn.toFixed(0)}s]...`},await new Promise(Ot=>setTimeout(Ot,1e3));yield{type:"status",content:"Error Occured. Recovering Stream..."}}else throw new Error(`Stream collapsed too many times. (Failed to resolve ${xn} times)
|
|
758
|
+
Error log can be found in \`/export logs\``);else if(He<=xn){He++,Xe=1,st="";let ns=Math.min(1e3*Math.pow(2,He-1),32e3),rn=.8+Math.random()*.4,Ot=Math.round(ns*rn);Qn=!0,yield{type:"status",content:`Trying to reach ${e} (${He}/${xn}) [Retrying in ${(Ot/1e3).toFixed(0)}s]`};for(let Lt=Ot/1e3;Lt>0&&!Mt;Lt--)yield{type:"status",content:`Trying to reach ${e} (${He}/${xn}) [Retrying in ${Lt.toFixed(0)}s]`},await new Promise(Pt=>setTimeout(Pt,1e3));yield{type:"status",content:`Trying to reach ${e}`}}else throw new Error(`Model ${e} cannot be reached. (Failed ${xn} times)
|
|
759
|
+
Error log can be found in \`/export logs\``)}}if(_n){let fe=_n.totalTokenCount||0,ye=_n.cachedContentTokenCount||0,de=(_n.candidatesTokenCount||0)+(_n.thoughtsTokenCount||0);await zt("tokens",fe,d,ke),ye>0&&await zt("cachedTokens",ye,d,ke),de>0&&await zt("candidateTokens",de,d,ke),yield{type:"usage",content:_n}}ki.push(pe);let es=nn(pe),un=La(pe),Us=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(un.toLowerCase())||/\[\[END\]\]/i.test(un.toLowerCase())||!0,Nn=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(un.toLowerCase()),Wc=Ge>0;yield{type:"status",content:"Thinking"};let Ha=Lc(pe,/(\[\s*(turn\s*:)?\s*(continue|finish)\s*\]|\[\[END\]\])/gi,"").trim(),ts=(Us||te.length===0)&&!Ut&&!bn&&!$n;if(ts=te.length===0?ts:!1,ts=Zn||ho?!1:ts,pe&&pe.trim().endsWith('")]')&&te.length===0&&(ts=!1),ts){let fe=ki.join(`
|
|
760
760
|
`),ye=nn(fe).trim();yield{type:"interactive_turn_finished",data:{agentText:T,fullAgentTextRaw:fe,history:[...b],needTitle:S}},b.length>0&&b[b.length-1].role==="agent"?b[b.length-1].text=ye:b.push({role:"agent",text:ye}),b.forEach(de=>{if(de.role==="user"&&de.text&&(de.text=de.text.replace(/\n\[COMPILE ERROR\][\s\S]*?\[\/ERROR\]/g,""),de.text=de.text.replaceAll(`
|
|
761
761
|
|
|
762
762
|
[system] user question. resolve this specific query within '[ANSWER] ... [/ANSWER]' concisely, naturally [/system]
|
|
@@ -765,20 +765,20 @@ Error log can be found in \`/export logs\``)}}if(_n){let fe=_n.totalTokenCount||
|
|
|
765
765
|
`,"").replaceAll(`[system] **strictly follow thinking policy as high priority. do not start a response without <think>...</think>** [/system]
|
|
766
766
|
`,"").replaceAll(/\n\[system\] WARNING, Turn Limit Impending: Step \d+\/\d+\. Wrap up quickly\/prompt user to continue & use \[\[END\]\] quickly\. \[\/system\]/g,""),de.text=de.text.replaceAll(/\n\[system\] File Changes:\n(?:\* .+ \(created|modified|deleted\)\n)*\[\/system\]/g,""),(d==="Mistral"||d==="Google"&&e?.toLowerCase().startsWith("gemma"))&&de.text.startsWith("[TOOL RESULT]"))){let jt=`
|
|
767
767
|
[system] Tool result received. Analyze output and proceed with your turn [/system]`,Vt=`
|
|
768
|
-
[system] Tool result received. Analyze output and proceed with your turn. **strictly follow thinking policy. do not start a response without <think>...</think>** [/system]`;de.text=de.text.replaceAll(Vt,"").replaceAll(jt,"").trim()}}),yield{type:"status",content:"[end]"}}if(
|
|
768
|
+
[system] Tool result received. Analyze output and proceed with your turn. **strictly follow thinking policy. do not start a response without <think>...</think>** [/system]`;de.text=de.text.replaceAll(Vt,"").replaceAll(jt,"").trim()}}),yield{type:"status",content:"[end]"}}if(ts)break;let Ga=Ha.trim()||"*Working...*";if(b.push({role:"agent",text:Ga}),te.length>0||dn){if(te.length>0){let fe=te.map(Bn=>Bn.text).join(`
|
|
769
769
|
|
|
770
770
|
`),ot=(nn(pe).replace(/\[{1,2}tool:[\s\S]*?\)\s*\]{1,2}/gi,"").match(/\[tool:/gi)||[]).length,jt=te.length+ot;if(te.length<jt){fe+=`
|
|
771
771
|
|
|
772
|
-
[system] Only ${te.length} out of ${jt} attempted tool calls were executed. Verify proper structure compliance & try failed calls again [/system]`;let Bn=jt-te.length;for(let gt=0;gt<Bn;gt++)await vt("toolFailure")}let Vt=te.find(Bn=>Bn.binaryPart)?.binaryPart||null;b.push({role:"user",text:fe,binaryPart:Vt})}}else if(!Mt){let ye=(pe.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/i,"").match(/\[tool:/gi)||[]).length;ho||
|
|
772
|
+
[system] Only ${te.length} out of ${jt} attempted tool calls were executed. Verify proper structure compliance & try failed calls again [/system]`;let Bn=jt-te.length;for(let gt=0;gt<Bn;gt++)await vt("toolFailure")}let Vt=te.find(Bn=>Bn.binaryPart)?.binaryPart||null;b.push({role:"user",text:fe,binaryPart:Vt})}}else if(!Mt){let ye=(pe.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/i,"").match(/\[tool:/gi)||[]).length;ho||Zn||ye>0?(b.push({role:"user",text:`[system] Failed to execute ${ye} tool${ye>1?"s":""}. Verify proper structure compliance & try again [/system]`}),await vt("toolFailure"),yield{type:"visual_feedback",content:`
|
|
773
773
|
${tn("\u2718 Execution Error")}
|
|
774
774
|
`}):(yield{type:"visual_feedback",content:`
|
|
775
775
|
${tn("\u2718 Loop Detected")}
|
|
776
|
-
`},b.push({role:"user",text:`[system] ${bn&&!Ut?"Stuttering Detected by Internal System. Re-calibrate your response & proceed.":`${Ut?" Over Thinking":" Loop"} Detected by Internal System${Ut?" for current Effort Level":""}. ${Ut?"If you have planned the task, prioritize execution/output":"If you have finished your task provide a simple summary and end"}`} [/system]`})),Ut=!1,bn=!1,$n=!1}l?.advanceRollback&&await
|
|
776
|
+
`},b.push({role:"user",text:`[system] ${bn&&!Ut?"Stuttering Detected by Internal System. Re-calibrate your response & proceed.":`${Ut?" Over Thinking":" Loop"} Detected by Internal System${Ut?" for current Effort Level":""}. ${Ut?"If you have planned the task, prioritize execution/output":"If you have finished your task provide a simple summary and end"}`} [/system]`})),Ut=!1,bn=!1,$n=!1}l?.advanceRollback&&await Kn.recordTurnDelta(f,z+1,sn),ho=Ge>0||dn}}catch(_){let C=(_ instanceof Error?(()=>{try{return JSON.parse(JSON.parse(_.message).error.message).error.message}catch{return _.message||String(_)}})():String(_)).replace(/^(Error:\s*)+/i,""),A=new Date().toLocaleString(),O=Q.join(hn,"agent");yield{type:"text",content:`\u2726 CRITICAL ERROR: ${C.includes("fetch failed")?"Failed to Connect. Check your Internet Connection or Wait a moment":C}
|
|
777
777
|
\u2800`},Pe.existsSync(O)||Pe.mkdirSync(O,{recursive:!0}),Pe.appendFileSync(Q.join(O,"error.log"),`CRITICAL ERROR [${A}]: ${_}
|
|
778
778
|
|
|
779
779
|
----------------------------------------------------------------------
|
|
780
780
|
|
|
781
|
-
`),typeof flushGoogleBuffer=="function"&&(yield*flushGoogleBuffer()),yield{type:"tool_result",content:`ERROR: [INTERNAL CRITICAL] ${C}`}}finally{E&&(clearInterval(E),E=null),typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),await ht.commitTransaction(),l?.advanceRollback&&await
|
|
781
|
+
`),typeof flushGoogleBuffer=="function"&&(yield*flushGoogleBuffer()),yield{type:"tool_result",content:`ERROR: [INTERNAL CRITICAL] ${C}`}}finally{E&&(clearInterval(E),E=null),typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),await ht.commitTransaction(),l?.advanceRollback&&await Kn.cleanup(f),await gs()}yield{type:"status",content:null}},ig=async(e,n,t=null,s=null,o=50,r=null,a=!1)=>{let i=await en(),h={...i,...n},f=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 b=_.toLowerCase();return b==="google"?"Google":b==="deepseek"?"DeepSeek":b==="openrouter"?"OpenRouter":b==="nvidia"?"NVIDIA":b==="mistral"?"Mistral":b==="ollama"?"Ollama":b==="crofai"||b==="crof"?"CrofAI":b==="inferx"?"InferX":b==="sensenova"?"SenseNova":null})(c),g=h?.systemSettings?.CustomSubAgent?h?.systemSettings?.SubAgentModel:null,y=h?.systemSettings?.CustomSubAgent?h?.systemSettings?.SubAgentProvider:null,m=null;if(g==="ENV"?(m=f,f&&p&&(h.aiProvider=p)):g&&g!=="Default"?(m=g,y&&(h.aiProvider=y)):f&&p&&(h.aiProvider=p),h.aiProvider){let _=await or(h.aiProvider);_&&(h.apiKey=_)}let w=_=>{if(!_||typeof _!="string")return{allowed:!0};let b=[/rm\s+-[rf]{1,2}\s+[\/*.]/i,/rmdir\s+\/[sq]/i,/del\s+\/[fsq]/i,/\bformat\b\s+[a-z]:/i,/mkfs/i,/dd\s+if=/i,/\b(shutdown|reboot|poweroff|init\s+0|init\s+6)\b/i,/chmod\s+(-R\s+)?777\s+[\/*.]/i,/chown\s+(-R\s+)?root/i,/git\s+push\s+.*--force/i,/git\s+clean\s+-fdx/i,/\bsudo\s+su\b/i,/\bsu\s+-\b/i];for(let C of b)if(C.test(_))return{allowed:!1,reason:`Blocked potentially destructive or unsafe command pattern: "${C.source}"`};return{allowed:!0}},x=t||m||n?.modelName||n?.activeModel||i.activeModel,k=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",$=`-- TOOL DEFINITIONS (path = relative to CWD, path separator: '/') --
|
|
782
782
|
You cant execute tools. To use tools, must output exactly [tool:functions.ToolName(arg1="value1")] structured string in chat output & wait for system response \u2190 no exception, tool:functions must
|
|
783
783
|
Tool Rules:
|
|
784
784
|
- JSON escape literal sequences inside tool arguments (backslash: \\\\, newLine: \\n, quote: \\") \u2190 Mandatory
|
|
@@ -804,7 +804,7 @@ ${a?'- AskMain(question="..."). Communicate with PARENT/MAIN AGENT. When clarifi
|
|
|
804
804
|
- ReadFile(path="...", startLine="int", endLine="int")
|
|
805
805
|
- PatchFile(path="...", allowMultiple="bool, false", searchContent1="search string OR ^LINE:start..end$", newContent1="...", ...MAX15). Use small searchContent. Line Ranges must for large searchContent and escape sequences. ^...$ must for line ranges
|
|
806
806
|
- WriteFile(path="...", content="..."). Creates/Overwrites. File Exist? PatchFile > WriteFile. VERIFY IMPORTS
|
|
807
|
-
- Run(command="..."). Runs ${k==="Windows"?
|
|
807
|
+
- Run(command="..."). Runs ${k==="Windows"?Hn()?"powershell":"windows CMD":"bash"} command. Destructive/Irreversible ops \u2192 Ask user`.trim(),R=`=== START SYSTEM PROMPT ===
|
|
808
808
|
Identity: FluxFlow subagent helping the main Agent
|
|
809
809
|
Your task is: "${e}"
|
|
810
810
|
|
|
@@ -817,9 +817,9 @@ On completion, provide a detailed summary in Tables/Markdown Format with file mo
|
|
|
817
817
|
|
|
818
818
|
CWD: ${process.cwd()}
|
|
819
819
|
Current Time: ${u}
|
|
820
|
-
=== END SYSTEM PROMPT ===`,S=[{role:"user",text:`Complete this task: ${e}`}],T=0,E="";for(;T<o;){if(Mt){if(n?.taskId&&typeof Ve<"u"){let F=Ve.find(B=>B.id===n.taskId);F&&(F.status="cancelled")}throw r&&r("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}if(n?.taskId&&typeof Ve<"u"){let F=Ve.find(B=>B.id===n.taskId);if(F&&F.status==="cancelled")throw r&&r("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}let _=S.map(F=>({role:F.role==="user"?"user":"model",parts:[{text:F.text}]}));r&&r(`[Subagent Turn ${T+1}]...`);let C=(await
|
|
820
|
+
=== END SYSTEM PROMPT ===`,S=[{role:"user",text:`Complete this task: ${e}`}],T=0,E="";for(;T<o;){if(Mt){if(n?.taskId&&typeof Ve<"u"){let F=Ve.find(B=>B.id===n.taskId);F&&(F.status="cancelled")}throw r&&r("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}if(n?.taskId&&typeof Ve<"u"){let F=Ve.find(B=>B.id===n.taskId);if(F&&F.status==="cancelled")throw r&&r("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}let _=S.map(F=>({role:F.role==="user"?"user":"model",parts:[{text:F.text}]}));r&&r(`[Subagent Turn ${T+1}]...`);let C=(await Yo(h,x,_,R,"Fast")).text||"",A=nn(C).trim();E=A,r&&r(`[Subagent Response]
|
|
821
821
|
${A}
|
|
822
|
-
`),S.push({role:"agent",text:A});let O=
|
|
822
|
+
`),S.push({role:"agent",text:A});let O=Vo(A);if(O.length===0)break;let D=O.filter(F=>F.toolName.toLowerCase()==="askmain"||F.toolName.toLowerCase()==="ask_main"),W=!1,q="";for(let F of O){if(Mt){if(n?.taskId&&typeof Ve<"u"){let v=Ve.find(U=>U.id===n.taskId);v&&(v.status="cancelled")}throw new Error("Subagent task was cancelled.")}if(n?.taskId&&typeof Ve<"u"){let v=Ve.find(U=>U.id===n.taskId);if(v&&v.status==="cancelled")throw new Error("Subagent task was cancelled.")}let B=F.toolName.toLowerCase();if(B==="askuser"&&(B="ask"),B==="askmain"||B==="ask_main"){if(W)continue;W=!0;let v="";if(D.length===1?v=L(D[0].args).question||D[0].args:v=D.map((U,X)=>{let ee=L(U.args);return`Q${X+1}: ${ee.question||U.args}`}).join(`
|
|
823
823
|
`),n.onAskMain){r&&r(`[Executing Tool] AskMain("${v}")...`);let U=await n.onAskMain(v);r&&r(`[Tool Result]
|
|
824
824
|
Answer from Main Agent: ${U}
|
|
825
825
|
`),q+=`[TOOL RESULT for AskMain]: Answer from Main Agent: ${U}
|
|
@@ -832,7 +832,7 @@ Answer from Main Agent: ${U}
|
|
|
832
832
|
`;continue}if(B==="exec_command"||B==="execcommand"||B==="run"){let v=L(F.args).command||"",U=w(v);if(!U.allowed){let X=`ERROR: [SECURITY RESTRICTION] Subagent execution blocked command: ${U.reason}`;r&&r(`[Blocked Command] ${v} - ${U.reason}
|
|
833
833
|
`),q+=`${X}
|
|
834
834
|
|
|
835
|
-
`;continue}}let Ce="";if(B==="web_search"||B==="websearch")Ce=`\u2714 \x1B[95mSearched\x1B[0m: ${L(F.args).query||""}`;else if(B==="web_scrape"||B==="webscrape")Ce=`\u2714 \x1B[95mScraped\x1B[0m: ${L(F.args).url||""}`;else if(B==="search_keyword"||B==="searchkeyword"||B==="codesearch"||B==="code_search"){let v=L(F.args),U=v.keyword||"",X=v.path||"";Ce=`${U?"\u2714":"\u2718"} \x1B[95mSearched\x1B[0m: ${U||"No Query"}${X?` \u2192 ${X.replaceAll("\\","/")}`:""}`}else if(B==="view_file"||B==="viewfile"||B==="readfile")Ce=`\u2714 \x1B[95mRead\x1B[0m: ${(L(F.args).path||"").replaceAll("\\","/")}`;else if(B==="list_files"||B==="read_folder"||B==="readfolder"){let v=L(F.args).path||null,U=L(F.args).recurse||0;Ce=`${v?"\u2714":"\u2718"} \x1B[95mBrowsed\x1B[0m: ${v?`${v.replaceAll("\\","/")}${U>0?`${v.endsWith("/")?`*${U}`:`/*${U}`}`:`${v.endsWith("/")?"":"/"}`}`:""}`}else if(B==="write_file"||B==="writefile"){let v=L(F.args).path||null;Ce=`${v?"\u2714":"\u2718"} \x1B[95mCreated\x1B[0m: ${v?`${v.replaceAll("\\","/")}`:"No File Changes"}`}else if(B==="update_file"||B==="updatefile"||B==="patchfile"||B==="patch_file"||B==="patchfile"||B==="updatefile"){let v=L(F.args).path||null,U=L(F.args).content||null;Ce=`${v?"\u2714":"\u2718"} \x1B[95mEdited\x1B[0m: ${v?`${v.replaceAll("\\","/")}`:"No File Changes"}`}else if(B==="exec_command"||B==="execcommand"||B==="run"){let v=L(F.args).command||null;Ce=`${v?"\u2714":"\u2718"} \x1B[95mExecuted\x1B[0m: ${v?v.slice(0,100)+(v.length>100?"...":""):"No Command"}`}else if(B==="file_map"||B==="filemap"){let v=L(F.args).path||"";Ce=`${v?"\u2714":"\u2718"} \x1B[95mIndexed\x1B[0m: ${v?`${v.replaceAll("\\","/")}`:"File Not Found"}`}else if(B==="await"){let{time:v}=L(F.args),U=parseFloat(v)||0;U<10&&(U=10),U>180&&(U=180),Ce=`\u2714 \x1B[95mAwaiting\x1B[0m \u2192 ${(ee=>{if(ee>=60){let Ue=Math.floor(ee/60),De=ee%60;return`${Ue}m${De>0?` ${De}s`:""}`}return`${ee}s`})(U)}`}else{let v=
|
|
835
|
+
`;continue}}let Ce="";if(B==="web_search"||B==="websearch")Ce=`\u2714 \x1B[95mSearched\x1B[0m: ${L(F.args).query||""}`;else if(B==="web_scrape"||B==="webscrape")Ce=`\u2714 \x1B[95mScraped\x1B[0m: ${L(F.args).url||""}`;else if(B==="search_keyword"||B==="searchkeyword"||B==="codesearch"||B==="code_search"){let v=L(F.args),U=v.keyword||"",X=v.path||"";Ce=`${U?"\u2714":"\u2718"} \x1B[95mSearched\x1B[0m: ${U||"No Query"}${X?` \u2192 ${X.replaceAll("\\","/")}`:""}`}else if(B==="view_file"||B==="viewfile"||B==="readfile")Ce=`\u2714 \x1B[95mRead\x1B[0m: ${(L(F.args).path||"").replaceAll("\\","/")}`;else if(B==="list_files"||B==="read_folder"||B==="readfolder"){let v=L(F.args).path||null,U=L(F.args).recurse||0;Ce=`${v?"\u2714":"\u2718"} \x1B[95mBrowsed\x1B[0m: ${v?`${v.replaceAll("\\","/")}${U>0?`${v.endsWith("/")?`*${U}`:`/*${U}`}`:`${v.endsWith("/")?"":"/"}`}`:""}`}else if(B==="write_file"||B==="writefile"){let v=L(F.args).path||null;Ce=`${v?"\u2714":"\u2718"} \x1B[95mCreated\x1B[0m: ${v?`${v.replaceAll("\\","/")}`:"No File Changes"}`}else if(B==="update_file"||B==="updatefile"||B==="patchfile"||B==="patch_file"||B==="patchfile"||B==="updatefile"){let v=L(F.args).path||null,U=L(F.args).content||null;Ce=`${v?"\u2714":"\u2718"} \x1B[95mEdited\x1B[0m: ${v?`${v.replaceAll("\\","/")}`:"No File Changes"}`}else if(B==="exec_command"||B==="execcommand"||B==="run"){let v=L(F.args).command||null;Ce=`${v?"\u2714":"\u2718"} \x1B[95mExecuted\x1B[0m: ${v?v.slice(0,100)+(v.length>100?"...":""):"No Command"}`}else if(B==="file_map"||B==="filemap"){let v=L(F.args).path||"";Ce=`${v?"\u2714":"\u2718"} \x1B[95mIndexed\x1B[0m: ${v?`${v.replaceAll("\\","/")}`:"File Not Found"}`}else if(B==="await"){let{time:v}=L(F.args),U=parseFloat(v)||0;U<10&&(U=10),U>180&&(U=180),Ce=`\u2714 \x1B[95mAwaiting\x1B[0m \u2192 ${(ee=>{if(ee>=60){let Ue=Math.floor(ee/60),De=ee%60;return`${Ue}m${De>0?` ${De}s`:""}`}return`${ee}s`})(U)}`}else{let v=fi[B]||F.toolName,U=xs(B,F.args);Ce=`\u2714 \x1B[95m${v}\x1B[0m${U?`: ${U}`:""}`}n.onVisualFeedback&&Ce&&n.onVisualFeedback(Ce),r&&r(`[Executing Tool] ${F.toolName}(${F.args})...`);try{let v=await co(F.toolName,F.args,{...n,mode:"Flux"});if(r&&r(`[Tool Result]
|
|
836
836
|
${v}
|
|
837
837
|
`),q+=`[TOOL RESULT for ${F.toolName}]: ${v}
|
|
838
838
|
|
|
@@ -843,4 +843,4 @@ ${v}
|
|
|
843
843
|
|
|
844
844
|
`,await vt("toolFailure")}}let se="";if(n?.taskId&&typeof Ve<"u"){let F=Ve.find(B=>B.id===n.taskId);if(F&&F.pendingSteerMessages&&F.pendingSteerMessages.length>0){let B=[...F.pendingSteerMessages];F.pendingSteerMessages=[];for(let Z of B)se+=`
|
|
845
845
|
|
|
846
|
-
[STEERING INSTRUCTION FROM MAIN AGENT]: ${Z}`,r&&r(`[Subagent Steered] ${Z}`)}}let V=(q.trim()+se).trim();S.push({role:"user",text:V}),T++}return E};export{yn as a,
|
|
846
|
+
[STEERING INSTRUCTION FROM MAIN AGENT]: ${Z}`,r&&r(`[Subagent Steered] ${Z}`)}}let V=(q.trim()+se).trim();S.push({role:"user",text:V}),T++}return E};export{yn as a,Ji as b,kd as c,Td as d,$l as e,Qi as f,Rd as g,Ll as h,Ed as i,fo as j,ka as k,Oh as l,Lh as m,L as n,Kc as o,ir as p,zs as q,Yc as r,Vc as s,hf as t,mf as u,ht as v,ls as w,Af as x,dl as y,vf as z,If as A,Of as B,Lf as C,Pf as D,cs as E,zl as F,Tu as G,Ru as H,Fh as I,Fo as J,Nh as K,Ec as L,Zm as M,_c as N,$c as O,ci as P,nn as Q,Oa as R,vc as S,eg as T,tg as U,pi as V,ng as W,sg as X,Bc as Y,og as Z,rg as _,ig as $};
|