fluxflow-cli 4.0.0 → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,816 @@
1
+ import{b as Jo}from"./chunk-ZESOEAQT.js";import{c as dn,d as qs,g as tt,h as Qt}from"./chunk-2FKXQDRX.js";import{a as Ks,b as $s,c as Z,d as pe}from"./chunk-SIINYZWE.js";import{c as _n,d as cn,e as go,f as Cs,g as As,h as Vo,i as Xt,j as Pt,k as Jt,l as In,m as Wn,n as sn,o as fn,p as as,q as Xo,r as Hn,s as ls}from"./chunk-I27MASHH.js";import{a as ze,c as yo}from"./chunk-56EJGQU3.js";import Vl from"dotenv";import{GoogleGenAI as ka,ThinkingLevel as lt,HarmBlockThreshold as Vn,HarmCategory as Xn}from"@google/genai";import{Ollama as Xl}from"ollama";import{execSync as ja}from"child_process";import{spawn as Qo}from"child_process";var L=e=>{let n={};if(!e)return n;let t=0;for(;t<e.length;){for(;t<e.length&&/[\s,]/.test(e[t]);)t++;if(t>=e.length)break;let o=e.substring(t).match(/^(\w+)\s*=\s*/);if(!o){t++;continue}let s=o[1];t+=o[0].length;let r="";if(t<e.length&&(e[t]==='"'||e[t]==="'"||e[t]==="`")){let i=e[t];t++;let a=t,p=-1,f=t;for(;f<e.length;){let l=e.indexOf(i,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),h=d.trim(),g=h===""||/^,\s*\w+\s*=/.test(h)||h.startsWith(")")&&(h.length===1||/^\)\s*([,\]\s]|\[\[?tool:)/i.test(h));if(g&&d.startsWith(`
2
+ `)){let y=h.split(`
3
+ `)[0];if(!y.includes("=")&&!y.includes(")")){f=l+1;continue}}if(g){p=l;break}f=l+1}p!==-1?(r=e.substring(a,p),t=p+1):(r=e.substring(a),t=e.length);let c=s.toLowerCase().includes("path")||["dest","source","to","from"].includes(s.toLowerCase());r=r.replace(/\\(.)/g,(l,u)=>{switch(u){case"n":return`
4
+ `;case"r":return"\r";case"t":return" ";case"\\":return"\\";default:return u===i?i:u}})}else if(t<e.length&&e[t]==="["){let i=0,a=null,p=t,f=-1;for(let c=t;c<e.length;c++){let l=e[c];if(a&&l===a){let u=0;for(let d=c-1;d>=0&&e[d]==="\\";d--)u++;u%2===0&&(a=null)}else!a&&(l==='"'||l==="'"||l==="`")&&(a=l);if(!a&&(l==="["?i++:l==="]"&&i--,i===0)){f=c;break}}if(f!==-1){r=e.substring(p,f+1),t=f+1;try{let c=r.trim();c.startsWith("'")||c.includes("'")}catch{}}else r=e.substring(p),t=e.length}else{let i=e.substring(t),a=i.match(/,\s*\w+\s*=|(?:\s*\)\s*(?:$|\]\]))/);if(a){let p=a.index;r=i.substring(0,p).trim(),t+=p}else r=i.trim(),t=e.length}r==="true"?r=!0:r==="false"?r=!1:typeof r=="string"&&!isNaN(r)&&r.trim()!==""&&(r=Number(r)),typeof r=="string"&&(s.toLowerCase().includes("path")||["dest","source","to","from"].includes(s.toLowerCase()))&&(r=r.replace(/\x0C/g,"\\f").replace(/\x0D/g,"\\r").replace(/\x0B/g,"\\v").replace(/\x08/g,"\\b")),n[s]=r}return n};var wo=null;try{let e=await import("node-pty");wo=e.default||e}catch{}var Oc=!!wo,So=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),Zo=e=>{if(!e)return"";let n=[[]],t=0,o=0,s=/\x1b\[([0-9;]*?)([a-zA-Z])/g,r=0,i,a=f=>{for(let c=0;c<f.length;c++){let l=f[c];if(l===`
5
+ `)for(t++,o=0;t>=n.length;)n.push([]);else if(l==="\r")o=0;else{for(;t>=n.length;)n.push([]);let u=n[t];for(;o>u.length;)u.push(" ");u[o]=l,o++}}};for(;(i=s.exec(e))!==null;){a(e.substring(r,i.index));let f=i[1],c=i[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;o=o+u}else if(c==="D"){let u=l[0]||1;o=Math.max(0,o-u)}else if(c==="G"){let u=(l[0]||1)-1;o=Math.max(0,u)}else if(c==="H"||c==="f"){let u=(l[0]||1)-1,d=(l[1]||1)-1;for(t=Math.max(0,u),o=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=o;else if(u===1)for(let h=0;h<o&&h<d.length;h++)d[h]=" ";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,o=0)}r=s.lastIndex}a(e.substring(r));let p=n.map(f=>f.join(""));for(;p.length>0&&p[p.length-1]==="";)p.pop();return p.join(`
6
+ `)},yt=null,zs=!1,_c=e=>{try{yt&&(zs&&typeof yt.write=="function"?yt.write(e):yt.stdin&&yt.stdin.writable&&yt.stdin.write(e))}catch{}},Ic=()=>{if(yt){try{zs&&typeof yt.destroy=="function"?yt.destroy():typeof yt.kill=="function"&&(process.platform==="win32"?Qo("taskkill",["/pid",yt.pid,"/f","/t"]):yt.kill("SIGKILL"))}catch{}yt=null,zs=!1}},er=(e,n=!1)=>{if(process.platform!=="win32")return e;let t=[],o="",s=null,r=!1;for(let c=0;c<e.length;c++){let l=e[c];if(r){o+=l,r=!1;continue}if(l==="\\"){if(e[c+1]===" "){o+=" ",c++;continue}o+=l,r=!0;continue}s?(l===s&&(s=null),o+=l):l==='"'||l==="'"?(s=l,o+=l):l===";"&&!o.includes("://")?(o.length>0&&(t.push(o),o=""),t.push(n?";":"&")):l==="&"&&!o.includes("://")?e[c+1]==="&"?(o.length>0&&(t.push(o),o=""),t.push("&&"),c++):(o.length>0&&(t.push(o),o=""),t.push("&")):l==="|"&&!o.includes("://")?(o.length>0&&(t.push(o),o=""),t.push("|")):/\s/.test(l)?o.length>0&&(t.push(o),o=""):o+=l}o.length>0&&t.push(o);let i=c=>!(!c.includes("/")||/^(https?|file|ftp):\/\//i.test(c)||c.startsWith("@")||c.startsWith("/")&&(c.match(/\//g)||[]).length===1||/\s\/|\/\s/.test(c)||/[\(\)\{\}\;\<\>\=\'\"]/.test(c)),a=[];for(let c=0;c<t.length;c++){let l=t[c];if(l==="mkdir"&&n&&Gn()){let u=[],d=c+1;for(;d<t.length;){let h=t[d];if([">",">>","<","&","&&","|","||",";"].includes(h))break;h!=="-p"&&h!=="--parents"&&h!=="-v"&&h!=="--verbose"&&u.push(h),d++}if(u.length>0){let h=u.map(g=>{let y=g.replace(/^['"]|['"]$/g,""),m=g;return i(y)&&(m=g.replace(/\//g,"\\")),m});a.push("New-Item","-ItemType","Directory","-Force","-Path",h.join(","))}else a.push("New-Item","-ItemType","Directory","-Force");c=d-1;continue}if(l==="rm"&&n&&Gn()){let u=[],d=!1,h=!1,g=c+1;for(;g<t.length;){let m=t[g];if([">",">>","<","&","&&","|","||",";"].includes(m))break;m==="-rf"||m==="-fr"?(d=!0,h=!0):m==="-r"||m==="-R"||m==="--recursive"?d=!0:m==="-f"||m==="--force"?h=!0:u.push(m),g++}let y=["Remove-Item"];if(d&&y.push("-Recurse"),h&&y.push("-Force"),u.length>0){let m=u.map(w=>{let x=w.replace(/^['"]|['"]$/g,""),T=w;return i(x)&&(T=w.replace(/\//g,"\\")),T});y.push("-Path",m.join(","))}a.push(...y),c=g-1;continue}if(l==="cp"&&n&&Gn()){let u=[],d=!1,h=!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"?h=!0:u.push(m),g++}let y=["Copy-Item"];if(d&&y.push("-Recurse"),h&&y.push("-Force"),u.length>0){let m=u.map(w=>{let x=w.replace(/^['"]|['"]$/g,""),T=w;return i(x)&&(T=w.replace(/\//g,"\\")),T});if(m.length>1){let w=m.pop();y.push("-Path",m.join(","),"-Destination",w)}else y.push("-Path",m[0])}a.push(...y),c=g-1;continue}if(l==="touch"&&n&&Gn()){let u=[],d=c+1;for(;d<t.length;){let h=t[d];if([">",">>","<","&","&&","|","||",";"].includes(h))break;u.push(h),d++}if(u.length>0){let g=`(${u.map(y=>{let m=y.replace(/^['"]|['"]$/g,""),w=y;return i(m)&&(w=y.replace(/\//g,"\\")),w}).join(", ")}) | ForEach-Object { if (Test-Path $_) { (Get-Item $_).LastWriteTime = [System.DateTime]::Now } else { $null | Out-File -FilePath $_ } }`;a.push(g)}c=d-1;continue}if(l==="|"&&t[c+1]==="tee"){t[c+2]==="-a"?(a.push(">>"),c+=2):(a.push(">"),c+=1);continue}if(l==="|"&&t[c+1]==="cat"&&t[c+2]===">"){a.push(">"),c+=2;continue}if(l==="|"){let u=t[c+1];if(u){let d=u.replace(/^['"]|['"]$/g,""),h=/\.(txt|md|json|log|csv|html|css|py|js|xml|yaml|yml|pdf|docx|pptx|xlsx)$/i.test(d);if(i(d)&&h){a.push(">");continue}}}a.push(l)}let p=!1,f=a.map(c=>{if(c==="echo")return p=!0,c;[">",">>","<","&","&&","|","||",";"].includes(c)&&(p=!1);let u=/^['"]|['"]$/.test(c),d=c;p&&u&&(d=c.replace(/^['"]|['"]$/g,""));let h=/^['"]|['"]$/.test(d),g=d.replace(/^['"]|['"]$/g,"");i(g)&&(d=d.replace(/\//g,"\\"));let y=d.replace(/^['"]|['"]$/g,"");return y.includes(" ")&&!h&&(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(" ")},tr=async(e,n={})=>{let{command:t}=L(e),{onChunk:o}=n;if(!t)return'ERROR: Missing "command" argument for exec_command.';let s=process.platform==="win32",r=n.systemSettings||{},i={};return r.networkAccess===!1&&(i.HTTP_PROXY="http://127.0.0.1:9999",i.HTTPS_PROXY="http://127.0.0.1:9999",i.ALL_PROXY="socks5://127.0.0.1:9999",i.http_proxy="http://127.0.0.1:9999",i.https_proxy="http://127.0.0.1:9999",i.all_proxy="socks5://127.0.0.1:9999",i.NO_PROXY="localhost,127.0.0.1"),new Promise(a=>{let p=f=>{let c=f==="pwsh"||f==="powershell",l=er(t,c),u;s?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=s?c?["-NoProfile","-Command",l]:["/c",l]:["-c",l];if(r.networkAccess===!1&&!s){let h=u,g=[...d];if(process.platform==="linux")u="unshare",d=["-n","-r",h,...g];else if(process.platform==="darwin"){let y=`(version 1)
7
+ (allow default)
8
+ (deny network-outbound)
9
+ (allow network-outbound (remote ip "localhost:*"))
10
+ (allow network-outbound (remote ip "127.0.0.1:*"))
11
+ `;u="sandbox-exec",d=["-p",y,h,...g]}}if(wo)try{let h=wo.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",...i}});yt=h,zs=!0;let g="",y=!1;return h.onData(m=>{if(!y){g+=m,o&&o(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(()=>a(`SUCCESS: Dev server started successfully in background.
12
+
13
+ ${w}`),500))}}),h.onExit(({exitCode:m})=>{if(y)return;yt=null;let w=Zo(g||""),x=So(w).replace(/\n{3,}/g,`
14
+
15
+ `)||"Command executed with no output.";a(m!==0?`ERROR: Command [${t}] failed with exit code [${m}].
16
+
17
+ ${x}`:`SUCCESS: Command [${t}] completed.
18
+
19
+ ${x}`)}),!0}catch(h){return s&&(f==="pwsh"||f==="powershell")&&h.code==="ENOENT"?!1:(To(a,l,t,i,o,f,r),!0)}else return To(a,l,t,i,o,f,r),!0};s?p("pwsh")||p("powershell")||p("cmd"):p("bash")})},To=(e,n,t,o,s,r="powershell",i={})=>{let a=process.platform==="win32",p=r==="pwsh"||r==="powershell",f;a?r==="pwsh"?f="C:\\Users\\User\\AppData\\Local\\Microsoft\\WindowsApps\\pwsh.exe":r==="powershell"?f="powershell.exe":f="cmd.exe":f=process.env.SHELL||"bash";let c=a?p?["-NoProfile","-Command",n]:["/c",n]:["-c",n];if(i.networkAccess===!1&&!a){let g=f,y=[...c];if(process.platform==="linux")f="unshare",c=["-n","-r",g,...y];else if(process.platform==="darwin"){let m=`(version 1)
20
+ (allow default)
21
+ (deny network-outbound)
22
+ (allow network-outbound (remote ip "localhost:*"))
23
+ (allow network-outbound (remote ip "127.0.0.1:*"))
24
+ `;f="sandbox-exec",c=["-p",m,g,...y]}}let l=a?Qo(f,c,{cwd:process.cwd(),env:{...process.env,...o}}):Qo(f,c,{cwd:process.cwd(),env:{...process.env,CI:"false",TERM:"xterm-256color",FORCE_COLOR:"1",...o}});yt=l,zs=!1,l.stdin&&l.stdin.on("error",()=>{yt=null});let u="",d="",h=!1;l.stdout.on("data",g=>{if(!h){let y=g.toString();u+=y,s&&s(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)&&(h=!0,setTimeout(()=>e(`SUCCESS: Dev server started successfully in background.
25
+
26
+ ${m}`),500))}}),l.stderr.on("data",g=>{if(!h){let y=g.toString();d+=y,s&&s(y)}}),l.on("close",g=>{if(h)return;yt=null;let y=[],m=Zo(u),w=Zo(d);m&&y.push(`STDOUT:
27
+ ${m}`),w&&y.push(`STDERR:
28
+ ${w}`),g!==0&&y.push(`EXIT CODE: ${g}`);let x=y.join(`
29
+
30
+ `)||"Command executed with no output.",T=So(x).replace(/\n{3,}/g,`
31
+
32
+ `);e(g!==0?`ERROR: Command [${t}] failed with exit code [${g}].
33
+
34
+ ${T}`:`SUCCESS: Command [${t}] completed.
35
+
36
+ ${T}`)}),l.on("error",g=>{if(a&&g.code==="ENOENT"){if(r==="pwsh"){let m=er(t,!0);return To(e,m,t,o,s,"powershell",i)}else if(r==="powershell"){let m=er(t,!1);return To(e,m,t,o,s,"cmd",i)}}yt=null;let y=g instanceof Error?g.message:String(g);e(`ERROR: Failed to start command [${t}]: ${y}`)})};var Vs=null,Gn=()=>{if(process.platform!=="win32")return!1;if(Vs!==null)return Vs;try{ja('powershell.exe -NoProfile -Command "exit"',{stdio:"ignore"}),Vs=!0}catch{Vs=!1}return Vs},nr=null,ui=(e,n,t,o,s=!1,r=!0)=>{nr===null&&(nr=s);let i=`- JSON ESCAPE LITERAL ESCAPE SEQUENCES IN TOOL ARGUMENTS
37
+ - SAME file, MULTIPLE edits? ONE PatchFile (\u226415 blocks) \u2190 PRIORITY
38
+ - Tool denied? Ask for guidance \u2190 MANDATORY
39
+ - Need text or HUGE file? CodeSearch > Full Read
40
+ - MUST AVOID UNNECESSARY LARGE-FILE CHUNK READS
41
+ - DONT HALLUCINATE TOOL RESULTS, VERIFY, FIX ERRORS
42
+ - Stuck on syntax error? Tell User > Time waste
43
+ `,a=`- WORKSPACE TOOLS (path = relative; FIRST ARGUMENT, path separator: '/') -
44
+ - [tool:functions.ReadFile(path="...", startLine="integer", endLine="integer")]. ${o!=="Google"?`${t?"Supports images/docs":""}`:"Supports images/docs"}
45
+ - [tool:functions.ReadFolder(path="...", recurse="integer 1-3")]. Minimize recursion
46
+ - [tool:functions.PatchFile(path="...", allowMultiple="bool, default: false", searchContent1="search string OR ^LINE:start..end$", newContent1="...", ...MAX15)]. TARGET MINIMAL searchContent. Line Ranges MUST for large searchContent AND escape sequences. ^...$ MUST for line ranges
47
+ - [tool:functions.WriteFile(path="...", content="...")]. Creates/Overwrites. File Exist? PatchFile > WriteFile
48
+ - [tool:functions.CodeSearch(keyword="...", path="dir/file/glob/regex, inclusion/exclusion ;-separated", fuzzy="bool false", regex="bool auto")]. Find definitions, logic, relevant code, standard junk auto-excluded
49
+ - [tool:functions.Run(command="...")]. Runs ${n==="Windows"?Gn()?"POWERSHELL":"WINDOWS CMD":"BASH"} command. Destructive/Irreversible ops \u2192 Ask user
50
+ - [tool:functions.Todo(method="create/append/get", tasks=[STRING ARRAY], markDone=[TASK ARRAY])]. If long multi-task: create Todos before starting. \`get + markDone\` to mark complete. UPDATE EVERY TURN WHEN CREATED
51
+ ${nr?'\n- EMERGENCY TOOLS -\nInfo: `initial` = current task prompt. Revert `id` = turn before disaster (eg. disaster: `turn_3` \u2192 revert: `turn_2`). Reason explicitly\n- [tool:functions.EmergencyRollback(method="getCheckpoint/forceRevert", id="...")]. Rollback workspace in THIS agent loop. ONLY for catastrophic corruption. Before ending, verify no catastrophe. `id` omitted for `getCheckpoint`\n':""}${r?`
52
+ - SUB AGENT TOOLS -
53
+ **PROACTIVE use HIGHLY RECOMMENDED. Prefer for any task, no user nudge needed**
54
+ Invocations:
55
+ \u2022 Invoke (async/background, \u22647 parallel). Parallelize long tasks. May take time
56
+ \u2022 InvokeSync (sync/blocking). Sequential, repetitive or delegated tasks. Saves tokens/cost
57
+ - [tool:functions.InvokeSync/Invoke(title="...", task="...")]. Task must be detailed: exact file paths, imports/exports, dependencies
58
+ - [tool:functions.Await(id="...", timeout="integer")]. Event-driven wait
59
+ - [tool:functions.GetProgress(id="...")]. Poll sparingly; NO initial poll. Work or await. Never end while subagent runs
60
+ - [tool:functions.Steer(id="...", message="...")]. Inject additional instruction or redirection into active async subagent
61
+ - [tool:functions.Cancel(id="...")]. Cancel async task ONLY if stalled (2m+) or incorrect`:""}`,p=`- CREATIVE TOOLS (path = relative to CWD & WILL BE FIRST ARGUMENT, path separator: '/') -
62
+ - [tool:functions.WritePDF(path="...", content="...", orientation="...")]. PROACTIVE A4 PAGE BREAKS MUST IN CSS. HTML/CSS for PREMIUM layout, stable margins & headers/footers, NO WATERMARKS
63
+ - [tool:functions.WriteDoc(path="...", content="...")]. A4 Word document, NO WATERMARKS, stable margins & headers/footers
64
+ - WORKSPACE & SUB AGENT TOOLS ARE NOT AVAILABLE IN FLOW`,f=`- COMPUTER USE TOOLS (GUI Desktop Automation) -
65
+ - [tool:functions.Click(gridId="integer", type="single/double", button="left/middle/right", intendedClickText="target text")]. Click target grid number, intendedClickText: LITERAL TEXT/ICON ON SCREEN (OCR SCANNBALE, UPTO 3 WORDS). DOUBLE CLICK DESKTOP ICONS
66
+ - [tool:functions.Drag(fromGridId="integer", toGridId="integer")]. Drag mouse from start grid number to target grid number
67
+ - [tool:functions.Scroll(direction="up/down", amount="integer")]. Scroll screen vertically by amount, USE WHEN SCROLLING IS NEEDED
68
+ - [tool:functions.KeyboardTyping(text="string", autoPressEnter="bool")]. Type text string into currently active input. JSON ESCAPE LITERAL ESCAPE SEQUENCES IN TOOL ARGUMENTS
69
+ - [tool:functions.KeyPress(key="key or ;-separated combination, eg: enter, backspace, clearInput, ctrl;c, alt;tab, f5, f11, alt;f4")]. Press key, shortcut, function key (f1-f12), or clear active input field.
70
+ - [tool:functions.RecaptureScreen()]. Request fresh gridded screenshot`;return`
71
+ -- TOOL DEFINITIONS (STRING BASED PROTOCOL) --
72
+ TO USE TOOLS, MUST OUTPUT EXACTLY '[tool:functions.ToolName(arg1="value1")]' STRUCTURED STRING IN CHAT RESPONSE \u2190 MANDATORY
73
+ TOOL RULES:
74
+ - MAX 3 TOOL CALLS/TURN${e==="Flux"?" (Todo: 3+, Run: max 1 or 2 consecutive)":""}
75
+ ${e==="Flux"?`${i}`:""}
76
+ - USER COMMUNICATION -
77
+ - [tool:functions.Ask(question="...", optionA="title::description", ...MAX4)]. Ambiguity: MUST for path divergence, security risk. Ask, don't finish/guess. Keep titles short
78
+
79
+ - WEB TOOLS -
80
+ - [tool:functions.WebSearch(query="...", aiMode="bool", limit="integer 3-10 aiMode: exclude")]. Usage: unknown info/docs. aiMode: LLM search
81
+ - [tool:functions.WebScrape(url="...")]. Proactive use for specific webpage/docs/api
82
+
83
+ ${e==="ICU"?`${f}`:e==="FluxCU"?`${a}
84
+
85
+ ${f}`:e==="Flux"?`${a}`:`${p}`}`.trim()};var hi=(e=!0,n=!0)=>`
86
+ Your exact tool syntax is: [tool:functions.ToolName(args...)]. Malformed calls will fail parsing. **NO OTHER SYNTAX/MARKERS/BOUNDARY ALLOWED** Proper bracket balancing per schema is mandatory
87
+
88
+ -- CHAT MANAGEMENT TOOLS (MUST CALL THESE 2 TOOLS IN THIS TURN) --
89
+ - [tool:functions.Chat(title="<short creative title of FULL conversation in 3 or 4 words>")]. Consider full chat context to generate title NOT just latest message
90
+ - [tool:functions.Memory(action="temp", content="<summary of the user prompt & model responses ONLY FROM LATEST PROMPT UNDER 40 WORDS>. [Talked on: <date> <hour>]")]. Time format: YYYY-MM-DD HH am/pm
91
+
92
+ ${e?`-- User-specific long-term/permanent memory (USE BASED ON CONVERSATION CONTEXT, DO NOT RE-SAVE MEMORY WHICH IS ALREADY SAVED) --
93
+ - Add: [tool:functions.Memory(action="user", method="add", content="<string to add>. [Saved on: <date ONLY>]", score=2)] (Set score=2 ONLY if the user explicitly asked to "remember" or "save" this information, else omit this parameter entirely)
94
+ - Delete: [tool:functions.Memory(action="user", method="delete", id="<memory id>")]
95
+ - Update: [tool:functions.Memory(action="user", method="update", content-new="string to update", id="<memory id>")]
96
+
97
+ -- Memory Relevance Decay Tool --
98
+ - Score Adjustment: [tool:functions.addMemScore(id="<memory id>")]
99
+ You MUST call this tool when a specific saved memory in the '-- CURRENT SAVED USER MEMORIES --' list was relevant, referenced, or helpful in the agent's response or user prompt IN CURRENT MESSAGE. You can stack multiple calls
100
+
101
+ Explicit Triggers for permanent memory:
102
+ - User explicitly asks to 'remember' something
103
+ - User mentions something important long-term that should be remembered
104
+ - User provides information that could be useful for long-term reference
105
+ - User shares personal information or preferences
106
+
107
+ Usage Rules:
108
+ - Frequency for 'user' action: Based on explicit triggers.
109
+ - IF YOU WANT TO SAVE SOMETHING, BUT SIMILAR MEMORY ALREADY EXISTS, USE THE UPDATE METHOD NOT ADD
110
+ - Chat Title is MANDATORY
111
+ - TEMPORARY Memory is MANDATORY
112
+ - WHEN Called User Memory, STILL use Temporary Memory
113
+ - MUST NOT IGNORE ANY TOOL CALLS IN GIVEN CONTEXT OF CHAT BETWEEN USER & AGENT`:""}`.trim();var xo={xHigh:`EFFORT: HIGH
114
+ Challenge assumptions, verify before concluding, prefer the simplest correct solution, assess architecture, scalability & trade-offs, verify dependencies, regressions, failure modes & modular design, plan: files, modules, interfaces & tests
115
+ Continuous analysis, verify from first principles, seek failure paths, verify imports, tool results & system stability; avoid syntax errors
116
+ MANDATORY: Full technical verification`,High:`EFFORT: HIGH
117
+ Rigorous thinking, prefer the simplest correct solution, assess architecture, performance & maintainability, verify error handling, assumptions, edge cases, dependencies & regressions, plan: files, functions, logic & interactions
118
+ Continuous analysis, verify from first principles, seek failure paths, verify imports, tool results & system stability; avoid syntax errors
119
+ MANDATORY: Full technical verification`,Medium:`EFFORT: MEDIUM
120
+ Focused, technical thinking, find the simplest solution meeting requirements, check error handling, assumptions, edge cases & dependencies, verify cohesive, modular changes, outline: files, functions & key logic
121
+ Logical, implementation-focused, efficient, deliberate, verify imports, tool results & system stability; avoid syntax errors
122
+ MANDATORY: Brief verification for technical tasks/greetings`,Minimal:`EFFORT: LOW
123
+ Quick, focused thinking, intent & complexity, required tools/files/actions, before acting
124
+ Brief thoughts, think only enough to avoid mistakes, verify imports, tool results & system stability; avoid syntax errors`,Off:`EFFORT: LOWEST
125
+ No thinking. Immediate response
126
+ Verify imports, tool results & system stability; avoid syntax errors`};import mi from"fs";var sr=null,pi=null,Xs=null,Ka=(e,n)=>{if(!n)return"";if(e!==pi||Xs===null){pi=e;try{let t=Z(Pt,[]);Array.isArray(t)&&t.length>0?Xs=t.map(o=>`- ${o.memory}`).join(`
127
+ `):Xs=""}catch(t){Xs="",mi.appendFileSync(`${cn}/memory/error.txt`,`${t.message}
128
+ -------------------------------------------------
129
+
130
+ `)}}return Xs},gi=(e="",n="",t=!0,o=!1)=>{if(typeof n=="boolean"&&(o=t,t=n,n=""),!t)return"";let s=e?.length>0&&!o?`-- RECENT CONTEXT FROM OTHER CHATS (PRIORITY: DYNAMIC-LOW, FOCUS: Chat Context > Recent) --
131
+ ${e}`:"";return s?`${s}`:""},yi=(e,n,t,o,s=!0,r=!1,i="Google",a=!1,p,f)=>{let c=!1;process.env.forcedReasoning&&process.env.NVIDIA_BASE_URL&&i.toUpperCase()==="NVIDIA"&&(c=!0);let l="";if(!p&&i==="Google"){let k=n;n==="Fast"&&(k="Off"),n==="Low"&&(k="Minimal"),n==="Standard"&&(k="Medium"),(n==="xHigh"||n==="Max")&&(k="xHigh"),l=xo[k]||xo.Medium}if(p||i!=="Google"){let k={Fast:"LOWEST",Low:"LOW",Medium:"MEDIUM",Standard:"MEDIUM",High:"HIGH",xHigh:"HIGH",Max:"HIGH"};l=xo.xHigh,l=l.replace("EFFORT: HIGH",`EFFORT: ${k[n]}`).replace(`
132
+ MANDATORY: Full technical verification`,""),n==="Fast"?l=`EFFORT: LOWEST
133
+ No thinking. Immediate response
134
+ Verify imports, tool results & system stability; avoid syntax errors`:n==="Low"&&(l=`EFFORT: LOW
135
+ Quick, focused thinking, intent & complexity, required tools/files/actions, before acting
136
+ Brief thoughts, think only enough to avoid mistakes, verify imports, tool results & system stability; avoid syntax errors`)}let u=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",d=e.instructions&&e.instructions?.length>0?`User Preferences: ${e.instructions}
137
+
138
+ `:"",h=e.nickname&&e.nickname?.length>0?`User Nickname: ${e.nickname}
139
+ ${d.length?"":`
140
+ `}`:"",g=e.name&&e.name?.length>0?`User Name: ${e.name}
141
+ ${h.length||d.length?"":`
142
+ `}`:"",y=process.cwd(),m=Ka(f,s),w=m?.length>0?`--- SAVED MEMORIES ---
143
+ ${m}
144
+
145
+ `:"",x=(()=>{let k=process.cwd().toLowerCase();if(process.platform==="win32"){let S=process.env.SystemRoot?.toLowerCase()||"c:\\windows",b=process.env.ProgramFiles?.toLowerCase()||"c:\\program files",C=process.env["ProgramFiles(x86)"]?.toLowerCase()||"c:\\program files (x86)";return k.startsWith(S)||k.startsWith(b)||k.startsWith(C)}else return k==="/"||["/bin","/sbin","/etc","/usr","/var","/root"].some(b=>k.startsWith(b))})(),T=[{name:"Fluxflow.md",desc:"HIGH PRIORITY"},{name:"README.md",desc:"Goals"},{name:"Agent.md",desc:"Standards"},{name:"Skills.md",desc:"Workflows"},{name:"design.md",desc:"UI/UX"},{name:"architecture.md",desc:"System Structure"}];if(r||sr===null){let k=T.filter(S=>mi.existsSync(S.name));sr=t==="Flux"&&k.length>0?`
146
+ -- PROJECT CONTEXT --
147
+ ${k.map(S=>`- ${S.name}: ${S.desc}`).join(`
148
+ `)}
149
+ Check these first; These Files > Training Data. Safety rules apply
150
+ `:""}let R=sr;return`=== SYSTEM PROMPT ===
151
+ Identity: Flux Flow. Sassy, Friendly, CLI Agent
152
+ ${t==="Flux"?"Stepwise execution, run automated tests":t==="Flow"?"Flow. Concise, Humorous, Sarcastic":t==="ICU"?"Interactive Computer Use. LOOK AT SCREENSHOT (ground truth) AND ANALYZE THE GRID & ID OVERLAPPING/CLOSE TO TARGET, Use Keyboard Shortcuts when possible":"Dev Mode & Computer Use. NO secure screen oparation, MUST use the GRID coordinates accurately"}
153
+
154
+ - USE DIRECTORY STRUCTURE FOR FILE PATH RESOLUTION${s?`
155
+ - USE RELATIVE TIME REFERENCE eg. few mins ago
156
+ -- Chat Context > Metadata`:""}
157
+
158
+ -- THINKING GUIDANCE --
159
+ ${i==="Mistral"||i==="Google"&&!p?`${l}
160
+ ${c||n!=="Fast"&&(i==="Mistral"&&!p||n!=="xHigh"&&!p)?`CRITICAL THINKING POLICY
161
+ - Use <think>...</think> for reasoning before responding any queries
162
+ `:""}`:`${l}
163
+ `}
164
+ ${ui(t,u,i.toLowerCase()==="deepseek"?!1:a,i,o?.advanceRollback,o?.subAgents!==!1)}
165
+ ${R}${s?`
166
+ -- MEMORY RULES --
167
+ - Subtly Personalize with RELEVENT CONTEXTUAL MEMORIES. Auto Saves
168
+ `:""}
169
+ ${t==="Flux"?`-- SECURITY POLICIES --
170
+ - Sensitive files? Ask before Read
171
+ `:t.toLowerCase().includes("cu")?`-- SECURITY POLICIES --
172
+ - Dont operate on ANY confidential screens
173
+ `:""}
174
+ -- CHAT FORMATTING --
175
+ - GFM Markdown
176
+ - Language: ENGLISH ONLY
177
+ - DONT MIX CHAT & TOOLS IN SAME RESPONSE${t==="Flow"?`
178
+ - Use Kaomojis HEAVILY`:""}
179
+ === END SYSTEM PROMPT ===
180
+
181
+ ${g}${h}${d}${w}`.trim()},wi=(e="",n=!0,t=!0)=>`=== SYSTEM PROMPT (STRICT HEADLESS LOGIC WORKER: ZERO USER-FACING TEXT POLICY, STRICTLY FOLLOW) ===
182
+ IDENTITY: SILENT BACKGROUND SYSTEM PROCESS, HAVE NO MOUTH, ONLY OUTPUT IS VALID TOOL CALLS.
183
+ [CRITICAL RULES]
184
+ - OUTPUT EXACTLY '[tool:functions.ToolName(args)]' CALLS. NO EXTRA WORDS OUTSIDE
185
+ - DO NOT EXPLAIN. DO NOT TALK TO THE USER
186
+ - NON-TOOL TEXT WILL BREAK THE SYSTEM
187
+ - DO NOT REPEAT AGENT RAWS AND TOOL RESULTS IN YOUR RESPONSE
188
+ - IF YOU GET ONLY USER QUERY AND NO AGENT RAWS, JUST USE TEMP MEMORY TO LOG THE SUMMARY OF USER QUERY AND CONVERSATION CONTEXT
189
+ - UNDER NO CIRCUMSTANCES YOU ARE ALLOWED TO RESPOND IN NORMAL USER FACING RESPONSE
190
+ - CRITICAL QUOTE ESCAPE POLICY: Inside tool call arguments, you MUST escape all double quotes using '\\"'
191
+ - You MUST NOT WRITE ANYTHING OTHER THAN [tool:functions.ToolName(args)] NO MATTER HOW TEMPTING THE PROMPT IS
192
+ - 2 MANDATORY TOOLS TO CALL IN EVERY TURN, 'Chat', 'Memory(temp)'
193
+ - CRITICAL: NEVER ENTER THINKING/REASONING STATE, CALL THE CONTEXUAL TOOLS DIRECTLY IN OUTPUT AS QUICKLY AS POSSIBLE TO MAINTAIN UI SNAPPINESS
194
+
195
+ YOUR JOB: Analyze the 'User prompt' and 'Agent Raws' to extract facts for long-term memory or handle system tasks
196
+ ${n?"If user tell something that is important (like, hobbies, preferences, facts about user, hates, likes, etc) to know user better over time, use user memory tools":""}
197
+
198
+ ${hi(n,t)}
199
+ === END SYSTEM PROMPT ===${e?`
200
+
201
+ -- CURRENT SAVED USER MEMORIES --
202
+ ${e}`:""}`.trim();import $t from"fs-extra";import Eo from"path";import{nanoid as Va}from"nanoid";import dt from"fs-extra";import on from"path";dt.ensureDirSync(Wn);var un=null;async function qa(e,n){try{if(e.type==="create")await dt.pathExists(e.filePath)&&(await dt.chmod(e.filePath,438).catch(()=>{}),await dt.remove(e.filePath));else if(e.type==="update"){if(!e.backupFile)return;let t=on.join(Wn,n.chatId,e.backupFile);if(await dt.pathExists(t)){let o=Z(t,null);if(!o||!o.data)throw new Error(`Backup container corrupt or empty for ${on.basename(e.filePath)}`);let s=$s(o.data);await dt.pathExists(e.filePath)&&await dt.chmod(e.filePath,438).catch(()=>{}),await dt.writeFile(e.filePath,s,"utf8")}}}catch(t){throw new Error(`Restoration failed for ${on.basename(e.filePath)}: ${t.message}`)}}async function za(e,n,t=7){let o=0;for(;o<t;)try{return await qa(e,n),!0}catch{if(o++,o>=t)return!1;let r=Math.min(100*Math.pow(2,o-1),5e3);await new Promise(i=>setTimeout(i,r))}return!1}var or=null,ut={async startTransaction(e,n){or=e,un={id:`tx_prompt_${Date.now()}`,chatId:e,timestamp:new Date().toISOString(),prompt:n.trim(),changes:[],reverted:!1},pe(as,un)},async recordFileChange(e,n=null){try{if(!un){if(or){let i=Z(sn,[]),a=[...i].reverse().find(p=>p.chatId===or);if(a){if(a.changes.some(u=>u.filePath===e))return;let c=await dt.pathExists(e)||n?"update":"create",l=null;if(c==="update"){let u=on.basename(e);l=`${a.id}_${u}.bak`;let d=on.join(Wn,a.chatId);await dt.ensureDir(d);let h=on.join(d,l),g=n!==null?n:await dt.readFile(e,"utf8").catch(()=>null);g!==null?pe(h,{data:Ks(g)}):(c="create",l=null)}a.changes.push({filePath:e,type:c,backupFile:l}),pe(sn,i)}}return}if(un.changes.some(i=>i.filePath===e))return;let s=await dt.pathExists(e)||n?"update":"create",r=null;if(s==="update"){let i=on.basename(e);r=`${un.id}_${i}.bak`;let a=on.join(Wn,un.chatId);await dt.ensureDir(a);let p=on.join(a,r),f=n!==null?n:await dt.readFile(e,"utf8").catch(()=>null);f!==null?pe(p,{data:Ks(f)}):(s="create",r=null)}un.changes.push({filePath:e,type:s,backupFile:r}),pe(as,un)}catch{}},async commitTransaction(){if(un)try{let e=Z(sn,[]);if(e.push(un),e.length>512e3){let n=e.shift();if(n.changes)for(let t of n.changes)t.backupFile&&await dt.remove(on.join(Wn,n.chatId,t.backupFile)).catch(()=>{})}pe(sn,e),await dt.remove(as).catch(()=>{})}catch{}finally{un=null}},async recoverCrashedTransaction(){try{if(await dt.pathExists(as)){let e=Z(as,null);if(e?.changes?.length>0){let n=Z(sn,[]);n.some(t=>t.id===e.id)||(n.push(e),pe(sn,n))}await dt.remove(as).catch(()=>{})}}catch{}},async rollbackToBefore(e){let n=Z(sn,null);if(!n)throw new Error("No transaction ledger found.");let t=n.findIndex(i=>i.id===e);if(t===-1)throw new Error(`Transaction [${e}] not found.`);let o=n[t].chatId,s=n[t].prompt,r=n.slice(t).filter(i=>i.chatId===o&&!i.reverted).reverse();for(let i of r){for(let a of[...i.changes].reverse())await za(a,i);for(let a of i.changes)if(a.backupFile){let p=on.join(Wn,i.chatId,a.backupFile);await dt.remove(p).catch(()=>{})}n=n.filter(a=>a.id!==i.id),pe(sn,n)}return{success:!0,chatId:o,targetPrompt:s}},async getChatHistory(e){try{return Z(sn,[]).filter(t=>t.chatId===e&&!t.reverted)}catch{return[]}},async deleteChatBackups(e){try{await dt.remove(on.join(Wn,e));let n=Z(sn,[]),t=n.filter(o=>o.chatId!==e);n.length!==t.length&&pe(sn,t)}catch{}}};var Si=Promise.resolve(),bo=e=>{let n=Si.then(async()=>{try{return await e()}catch(t){throw console.error("Lock Operation Failed:",t),t}});return Si=n.catch(()=>{}),n},cs=async()=>{await $t.ensureDir(As);let e={};if(await $t.pathExists(Cs))try{e=Z(Cs,{})}catch{e={}}for(let n in e){let t=Eo.join(As,`${n}.json`);Object.defineProperty(e[n],"messages",{get:()=>{if($t.existsSync(t))try{return Z(t,[])}catch{return[]}return[]},set:o=>{try{pe(t,o)}catch{}},enumerable:!1,configurable:!0})}return e},af=async(e,n,t)=>bo(async()=>{await $t.ensureDir(As);let o=await cs(),s=o[e],r=(t||[]).filter(y=>!y.isUpdateNotification&&(!y.isMeta||y.text&&y.text.includes("Request Cancelled")));try{(await Qt()).systemSettings?.preserveThinking===!1&&(r=r.filter(m=>m.role!=="think"))}catch{}let i=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+/),T;return x.length>7?T=x.slice(0,7).join(" ")+"...":w.length>45?T=w.substring(0,45).trimEnd()+"...":T=w,T},a,p=r.filter(y=>y.role==="user"),f=p[0],c=p[p.length-1],l=i(c),u=i(f);s&&s.prompt?Math.random()<.5&&l?a=l:a=s.prompt:a=u||l;let d=n||(s?s.name:`Session ${e.slice(-6)}`),h=Eo.join(As,`${e}.json`);pe(h,r),o[e]={name:d,prompt:a||void 0,updatedAt:Date.now()};let g={};for(let y in o)g[y]={name:o[y].name,prompt:o[y].prompt||void 0,updatedAt:o[y].updatedAt};pe(Cs,g)}),Ti=async(e,n)=>bo(async()=>{let t=await cs();t[e]?(t[e].name=n,t[e].updatedAt=Date.now()):t[e]={name:n,updatedAt:Date.now()};let o={};for(let s in t)o[s]={name:t[s].name,prompt:t[s].prompt||void 0,updatedAt:t[s].updatedAt};pe(Cs,o)}),Xa=async e=>bo(async()=>{let n=await cs();delete n[e];let t={};for(let i in n)t[i]={name:n[i].name,prompt:n[i].prompt||void 0,updatedAt:n[i].updatedAt};if(pe(Cs,t),await $t.pathExists(Hn))try{let i=Z(Hn,[]);if(Array.isArray(i)){let a=i.filter(p=>Object.keys(p)[0]!==String(e));pe(Hn,a)}}catch{}let o=Z(Jt,{});o[e]&&(delete o[e],pe(Jt,o));let s=Z(In,{});s[e]&&(delete s[e],pe(In,s)),await ut.deleteChatBackups(e);let r=Eo.join(As,`${e}.json`);if(await $t.pathExists(r))try{await $t.remove(r)}catch{}return n}),lf=()=>`flow-${Va(6)}`,cf=async e=>{if(!e||e==="Never")return;let n=parseInt(e);if(isNaN(n))return;let t=await cs(),o=Date.now(),s=n*24*60*60*1e3,r=0;for(let i in t){let a=t[i];a.updatedAt&&o-a.updatedAt>s&&(await Xa(i),r++)}return r},Ja=e=>{let n=e.replace(/[\[\]]/g,"").trim(),t=new Date(n);if(!isNaN(t.getTime()))return t.getTime();let o=n.split(/,\s*|\s+/);if(o.length===0)return null;let s=o[0],r=o[1]||"",i=o[2]||"",a=s.split(/[-\/.]/).map(Number);if(a.length!==3)return null;let p="en";try{p=Intl.DateTimeFormat().resolvedOptions().locale||"en"}catch{}let f=!/^en[-_]?us$|^en$/.test(p?.toLowerCase()),c,l,u;if(a[0]>1e3)c=a[0],l=a[1],u=a[2];else if(a[2]>1e3)c=a[2],a[0]>12?(u=a[0],l=a[1]):a[1]>12?(u=a[1],l=a[0]):f?(u=a[0],l=a[1]):(l=a[0],u=a[1]);else return null;if(l<1||l>12||u<1||u>31)return null;let d=0,h=0,g=0;if(r){let m=r.split(":").map(Number);d=m[0]||0,h=m[1]||0,g=m[2]||0,i.toLowerCase()==="pm"&&d<12?d+=12:i.toLowerCase()==="am"&&d===12&&(d=0)}let y=new Date(c,l-1,u,d,h,g);return isNaN(y.getTime())?null:y.getTime()},Qa=async e=>{try{if(!await $t.pathExists(e))return;let n=await $t.readFile(e,"utf8");if(!n.trim())return;let t=n.split(`
203
+ `),o=[],s=null,r=/^\s*(?:DEBUG|ERROR|SEARCH|PUPPETEER)\b/i;for(let l of t)r.test(l)?(s&&o.push(s),s={header:l,body:[]}):s?s.body.push(l):o.push({header:l,body:[]});s&&o.push(s);let i=10080*60*1e3,a=Date.now(),p=[],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 o){if(r.test(l.header)){let h=l.header.match(f);if(h){let g=Ja(h[1]);if(g&&a-g>i)continue}}let d=l.header+(l.body.length>0?`
204
+ `+l.body.join(`
205
+ `):"");p.push(d)}let c=p.join(`
206
+ `).trim();c?await $t.writeFile(e,c+`
207
+ `,"utf8"):await $t.writeFile(e,"","utf8")}catch{}},ff=async e=>{try{if(!await $t.pathExists(e))return;let n=async t=>{let o=await $t.readdir(t);for(let s of o){let r=Eo.join(t,s);(await $t.stat(r)).isDirectory()?(await n(r),(await $t.readdir(r)).length===0&&await $t.remove(r)):s.endsWith(".log")&&await Qa(r)}};await n(e)}catch{}},xi=(e,n=4)=>{if(e.length<=1)return e;let t=e[0],o=e.slice(1),s=n*2,r=o.slice(s);return[t,...r]};var df=async(e,n,t)=>bo(async()=>{let o=Z(Hn,[]);Array.isArray(o)||(o=[]);let s={total:n,context:t},r=o.findIndex(i=>Object.keys(i)[0]===String(e));r!==-1?o[r]={[String(e)]:s}:o.push({[String(e)]:s}),pe(Hn,o)}),uf=async e=>{try{if(!await $t.pathExists(Hn))return{total:0,context:0};let n=Z(Hn,[]);if(!Array.isArray(n))return{total:0,context:0};let t=n.find(o=>Object.keys(o)[0]===String(e));return t?t[String(e)]:{total:0,context:0}}catch{return{total:0,context:0}}};import wt from"fs-extra";import Ei from"path";var Za=()=>Math.random().toString(36).substring(2)+Date.now().toString(36),re=null,jn=null,bi=0,Ms=!1,Ln={agent:0,background:0,search:0,toolSuccess:0,toolFailure:0,toolDenied:0,duration:0,tokens:0,cachedTokens:0,candidateTokens:0,linesAdded:0,linesRemoved:0,imageCalls:[]},Os=(e,n)=>{if(!e)return{};let t=Object.keys(e),o=new Date(new Date(n).getTime()-720*60*60*1e3),s={};for(let r of t)new Date(r)>=o&&(s[r]=e[r]);return s},Ro=async()=>{let e=new Date().toISOString().split("T")[0];try{!await wt.exists(Xt)&&await wt.exists(Vo)&&(await wt.ensureDir(Ei.dirname(Xt)),await wt.move(Vo,Xt))}catch{}let n=Xt+".tmp",t=null;try{if(await wt.exists(n)){let s=(await wt.readFile(n,"utf8")).trim(),r=null;if(s.startsWith("{")||s.startsWith("[")?r=JSON.parse(s):r=JSON.parse($s(s)),r&&r.date&&r.stats){t=r;try{await wt.rename(n,Xt)}catch{}}else try{await wt.remove(n)}catch{}}}catch{try{await wt.remove(n)}catch{}}if(!t)try{if(await wt.exists(Xt)){let s=(await wt.readFile(Xt,"utf8")).trim();s.startsWith("{")||s.startsWith("[")?t=JSON.parse(s):t=JSON.parse($s(s))}}catch{}let o=t;if(o){let s=o.stats||{...Ln},r={...Ln,...s};Array.isArray(r.imageCalls)||(r.imageCalls=[]);let i=o.history||{},a=Os(i,e);if(Object.keys(i).length!==Object.keys(a).length&&(Ms=!0),o.date===e)return{...o,stats:r,history:a};{let p=o.date,f=r,c={...a};return p&&(c[p]=f),{date:e,stats:{...Ln},history:Os(c,e)}}}return{date:e,stats:{...Ln},history:{}}},rr=async()=>{if(!(!Ms||!re))try{await wt.ensureDir(Ei.dirname(Xt));let e=null;try{if(await wt.exists(Xt)){let s=(await wt.readFile(Xt,"utf8")).trim();s.startsWith("{")||s.startsWith("[")?e=JSON.parse(s):e=JSON.parse($s(s))}}catch{}if(e&&e.date===re.date&&e.stats){for(let s in re.stats)if(e.stats[s]!==void 0){if(Array.isArray(re.stats[s])){let r=Array.isArray(e.stats[s])?e.stats[s]:[],i=re.stats[s],a=new Map;for(let p of[...r,...i])p&&p.timestamp&&a.set(p.timestamp,p);re.stats[s]=Array.from(a.values())}else if(typeof re.stats[s]=="number")re.stats[s]=Math.max(re.stats[s],Number(e.stats[s])||0);else if(re.stats[s]&&typeof re.stats[s]=="object"){let r=e.stats[s]||{},i=re.stats[s];for(let a in r)if(typeof r[a]=="number")i[a]=Math.max(i[a]||0,r[a]);else if(r[a]&&typeof r[a]=="object"){i[a]||(i[a]={});for(let p in r[a])if(typeof r[a][p]=="number")i[a][p]=Math.max(i[a][p]||0,r[a][p]);else if(r[a][p]&&typeof r[a][p]=="object"){i[a][p]||(i[a][p]={});for(let f in r[a][p])i[a][p][f]=Math.max(i[a][p][f]||0,r[a][p][f])}}}}}if(e&&e.history){let s={...re.history||{}};for(let r in e.history)if(s[r])for(let i in s[r])if(i==="imageCalls"){let a=Array.isArray(e.history[r].imageCalls)?e.history[r].imageCalls:[],p=Array.isArray(s[r].imageCalls)?s[r].imageCalls:[],f=new Map;for(let c of[...a,...p])c&&c.timestamp&&f.set(c.timestamp,c);s[r].imageCalls=Array.from(f.values())}else typeof s[r][i]=="number"&&(s[r][i]=Math.max(s[r][i],Number(e.history[r][i])||0));else s[r]=e.history[r];re.history=Os(s,re.date||today)}else if(re&&re.history){let s=new Date().toISOString().split("T")[0];re.history=Os(re.history,s)}re.saveId=Za();let n=Xt+".tmp",t=Ks(JSON.stringify(re,null,2));await wt.writeFile(n,t,"utf8");let o=await wt.open(n,"r+");await wt.fsync(o),await wt.close(o),await wt.rename(n,Xt),Ms=!1,bi=Date.now()}catch{}},ko=()=>{if(Ms=!0,jn)return;let e=Date.now(),n=Math.max(0,1500-(e-bi));jn=setTimeout(async()=>{await rr(),jn=null},n),jn.unref&&jn.unref()},Sf=async()=>{re=await Ro(),Ms&&ko()},Tf=async()=>{jn&&(clearTimeout(jn),jn=null),await rr()},Rn=async()=>{let e=new Date().toISOString().split("T")[0];if(!re)re=await Ro();else if(re.date!==e){let n=re.date,t=re.stats,o=re.history||{};t&&(o[n]=t),re={date:e,stats:{...Ln},history:Os(o,e)},Ms=!0,await rr()}return re&&re.stats&&!Array.isArray(re.stats.imageCalls)&&(re.stats.imageCalls=[]),re.stats},el=async()=>{let e=new Date().toISOString().split("T")[0];re||(re=await Ro()),re.date!==e&&await Rn();let n=re.history||{},t=Os(n,e);re.history=t;let o=re.stats||{...Ln},s={...Ln};s.imageCalls=[],s.models={};let r=(i,a)=>{for(let p in i)if(p==="imageCalls")i.imageCalls=[...i.imageCalls||[],...a.imageCalls||[]];else if(p==="models"){let f=a.models||{};for(let c in f){i.models[c]||(i.models[c]={});for(let l in f[c]){i.models[c][l]||(i.models[c][l]={tokens:0,cachedTokens:0,candidateTokens:0});let u=i.models[c][l],d=f[c][l];u.tokens+=d.tokens||0,u.cachedTokens+=d.cachedTokens||0,u.candidateTokens+=d.candidateTokens||0}}}else typeof i[p]=="number"&&(i[p]+=a[p]||0)};r(s,o);for(let i in t)r(s,t[i]);return s},Lt=async(e,n)=>{e==="toolSuccess"?Js.toolSuccess++:e==="toolFailure"?Js.toolFailure++:e==="toolDenied"&&Js.toolDenied++;let t=await Rn();t[e]!==void 0&&t[e]++,n&&e==="agent"&&(t.providerRequests||(t.providerRequests={}),t.providerRequests[n]=(t.providerRequests[n]||0)+1),ko()},Js={linesAdded:0,linesRemoved:0,toolSuccess:0,toolFailure:0,toolDenied:0},jt=async(e,n,t,o)=>{e==="linesAdded"?Js.linesAdded+=n:e==="linesRemoved"&&(Js.linesRemoved+=n);let s=await Rn();if(s[e]!==void 0&&(s[e]+=Math.floor(n)),t&&o&&(e==="tokens"||e==="cachedTokens"||e==="candidateTokens")){s.models||(s.models={}),s.models[t]||(s.models[t]={}),s.models[t][o]||(s.models[t][o]={tokens:0,cachedTokens:0,candidateTokens:0});let r=s.models[t][o];e==="tokens"&&(r.tokens+=Math.floor(n)),e==="cachedTokens"&&(r.cachedTokens+=Math.floor(n)),e==="candidateTokens"&&(r.candidateTokens+=Math.floor(n))}ko()},tl=async(e=1)=>{let n=new Date,t=n.toISOString().split("T")[0];re||(re=await Ro()),re.date!==t&&await Rn();let o=n.getFullYear(),s=n.getMonth();n.getDate()<e&&(s-=1,s<0&&(s=11,o-=1));let a=new Date(o,s,e).toISOString().split("T")[0],p=re.history||{},f=re.stats||{...Ln},c={...Ln};c.imageCalls=[],c.models={};let l=(u,d)=>{for(let h in u)if(h==="imageCalls")u.imageCalls=[...u.imageCalls||[],...d.imageCalls||[]];else if(h==="models"){let g=d.models||{};for(let y in g){u.models[y]||(u.models[y]={});for(let m in g[y]){u.models[y][m]||(u.models[y][m]={tokens:0,cachedTokens:0,candidateTokens:0});let w=u.models[y][m],x=g[y][m];w.tokens+=x.tokens||0,w.cachedTokens+=x.cachedTokens||0,w.candidateTokens+=x.candidateTokens||0}}}else typeof u[h]=="number"&&(u[h]+=d[h]||0)};l(c,f);for(let u in p)u>=a&&u<t&&l(c,p[u]);return c},ir=async(e,n={})=>{let t=await Qt().catch(()=>({})),o=n.apiTier||t.apiTier||"Free",s=n.quotas||n.systemSettings?.quotas||t.quotas||{},r=s.providerBudgets||{},i=!!r.__useProvider,a=n.aiProvider||t.aiProvider||"Google",p=i&&!!r[a],f=()=>{if(p){let c=r[a];return{agentLimit:typeof c.agentLimit=="number"&&c.agentLimit>0?c.agentLimit:99999999,tokenLimit:typeof c.tokenLimit=="number"&&c.tokenLimit>0?c.tokenLimit:99999999999999,monthlyTokenLimit:typeof c.monthlyTokenLimit=="number"&&c.monthlyTokenLimit>0?c.monthlyTokenLimit:99999999999999}}return{agentLimit:s.agentLimit||99999999,tokenLimit:s.tokenLimit||99999999999999,monthlyTokenLimit:s.monthlyTokenLimit||99999999999999}};if(e==="agent"){let{agentLimit:c,tokenLimit:l,monthlyTokenLimit:u}=f(),d=await Rn(),h;s.resetMode==="Custom"?h=await tl(s.resetDay||1):h=await el();let g=0,y=0,m=0;if(p){g=d.providerRequests?.[a]||0;let w=d.models?.[a]||{};for(let T in w)y+=w[T]?.tokens||0;let x=h.models?.[a]||{};for(let T in x)m+=x[T]?.tokens||0}else g=d.agent||0,y=d.tokens||0,m=h.tokens||0;return o==="Free"&&d.agent+d.background>=999999?{allowed:!1,reason:"Free Tier Daily Usage Limit Exceeded"}:g>=c?{allowed:!1,reason:p?`Daily Request Limit Reached for ${a}`:"Daily Agent Request Limit Reached"}:y>=l?{allowed:!1,reason:p?`Daily Token Budget Exhausted for ${a}`:"Daily Token Budget Exhausted"}:m>=u?{allowed:!1,reason:p?`Monthly Token Budget Exhausted for ${a}`:"Monthly Token Budget Exhausted"}:{allowed:!0}}if(e==="background"){let c=await Rn();if(o==="Free"&&c.agent+c.background>=999999)return{allowed:!1,reason:"Free Tier Background Limit Exceeded"};let l=c.background<(s.backgroundLimit||999999);return{allowed:l,reason:l?void 0:"Background Request Limit Exceeded"}}if(e==="search"){let l=(await Rn()).search<(s.searchLimit||100);return{allowed:l,reason:l?void 0:"Search Quota Exceeded"}}return{allowed:!0}},Ri=async(e,n={})=>(await ir(e,n)).allowed,ar=e=>{if(!e||e.length===0)return[];let t=[...e].sort((s,r)=>s.timestamp-r.timestamp),o=[];for(let s of t){if(o.length>0){let r=o[o.length-1];if(s.timestamp>=r.start&&s.timestamp<r.end){r.calls.push(s),r.spent+=s.cost;continue}}o.push({start:s.timestamp,end:s.timestamp+36e5,calls:[s],spent:s.cost})}return o},ki=(e,n)=>{if(!e||e.length===0)return .025;let o=ar(e);if(o.length===0)return .025;let s=[];for(let l of o){let u=.025;if(s.length>0){let h=s[s.length-1],g=!1;if(s.length>=2){let y=s[s.length-2];h.ratio>=.8&&y.ratio>=.8&&(g=!0)}if(g)u=.015;else{let y=h.limit,m=h.ratio;m>=.8?u=y===.015?.015:y:m<.4?u=Math.min(.025,y+.005):m>=.4&&m<.6?u=Math.min(.025,y+.004):u=Math.min(.025,y+.002)}}let d=u>0?l.spent/u:0;s.push({limit:u,spent:l.spent,ratio:d})}let r=o[o.length-1];if(n<r.end)return s[s.length-1].limit;let i=s[s.length-1].limit,a=i,p=s[s.length-1].ratio,f=r.end,c=0;for(let l=s.length-1;l>=0&&s[l].ratio>=.8;l--)c++;for(;f<=n;){let l=.025;c>=2?l=.015:p>=.8?l=a===.015?.015:a:p<.4?l=Math.min(.025,a+.005):p>=.4&&p<.6?l=Math.min(.025,a+.004):l=Math.min(.025,a+.002),a=l,p=0,c=0,f+=36e5,i=l}return i},Ci=async e=>{let n=e.imageSettings||{keyType:"Default",quality:"Low-High"};if(n.keyType!=="Default")return!0;let o={Low:.001,"Low-High":.002,Medium:.008,"Medium-High":.01,High:.045,Ultra:.0488,Premium:.15}[n.quality]||.002,s=await Rn();s.imageCalls||(s.imageCalls=[]);let r=Date.now(),i=ar(s.imageCalls),a=0;if(i.length>0){let f=i[i.length-1];r>=f.start&&r<f.end&&(a=f.spent)}let p=ki(s.imageCalls,r);return a+o<=p},Ai=async()=>{let e=await Rn();e.imageCalls||(e.imageCalls=[]);let n=Date.now(),t=ar(e.imageCalls),o=[],s=0,r=0;if(t.length>0){let f=t[t.length-1];n>=f.start&&n<f.end&&(o=f.calls,s=f.spent,r=Math.max(0,Math.ceil((f.end-n)/(60*1e3))))}let i=ki(e.imageCalls,n),a=Math.max(0,i-s),p=s;return{totalSpent:s,remaining:a,activeCallsCount:o.length,nextResetMin:r,reclaimCost:p,limit:i}},$i=async e=>{let n=e.imageSettings||{keyType:"Default",quality:"Low-High"},o={Low:.001,"Low-High":.002,Medium:.008,"Medium-High":.01,High:.045,Ultra:.0488,Premium:.1}[n.quality]||.002,s=await Rn();s.imageCalls||(s.imageCalls=[]),s.imageCalls.push({timestamp:Date.now(),cost:o}),ko()};import _i from"puppeteer";import Ii from"fs";import Li from"path";import Mi from"os";import Qs from"path";import _s from"fs";import{createRequire as nl}from"module";import{fileURLToPath as sl}from"url";var ol=nl(import.meta.url),Oi=Qs.dirname(sl(import.meta.url));function fs(){let e=Mi.platform(),n=Mi.arch(),t="",o="",s="";if(e==="win32")t=n==="x64"?"win64":"win32",o="chrome.exe",s=`chrome-${t}`;else if(e==="darwin"){t=n==="arm64"?"mac_arm":"mac";let i=n==="arm64"?"arm64":"x64";o="Google Chrome.app/Contents/MacOS/Google Chrome",s=`chrome-mac-${i}`}else if(e==="linux")t="linux",o="chrome",s="chrome-linux64";else return{};let r=Qs.resolve(Oi,"..","..",".puppeteerrc.cjs");if(_s.existsSync(r)||(r=Qs.resolve(Oi,"..",".puppeteerrc.cjs")),!_s.existsSync(r))return{};try{let i=ol(r),a=i.cacheDirectory,p=i.chrome?.version;if(a){if(process.env.PUPPETEER_CACHE_DIR=a,p){let l=Qs.join(a,"chrome",`${t}-${p}`,s,o);if(_s.existsSync(l))return{executablePath:l,cacheDirectory:a}}let f=l=>{if(!_s.existsSync(l))return null;try{let u=_s.readdirSync(l),d=[];for(let h of u){let g=Qs.join(l,h),y;try{y=_s.statSync(g)}catch{continue}if(y.isDirectory())d.push(g);else if(h.toLowerCase()===o.toLowerCase()&&(!p||g.includes(p)))return g}if(p){for(let h of d)if(h.includes(p)){let g=f(h);if(g)return g}}for(let h of d)if(!p||!h.includes(p)){let g=f(h);if(g)return g}}catch{}return null},c=f(a);if(c)return{executablePath:c,cacheDirectory:a}}}catch{}return{}}var lr=async e=>{let{query:n,limit:t=5,aiMode:o=!1}=L(e);if(!n)return'ERROR: Missing "query" argument for web_search.';let s=3,r=null;if(o){let i=`Query: ${n}
208
+
209
+ RESPONSE RULES:
210
+ - ANSWER CONCISELY WITH REQUIRED DETAILS UNDER 300 WORDS.
211
+ - DO NOT CITE, REFERENCE, OR MENTION SOURCES ANYWHERE BETWEEN THE MAIN RESPONSE.
212
+ - DO NOT USE MARKDOWN EXCEPT FOR THE SOURCES SECTION BELOW.
213
+ - END THE RESPONSE WITH EXACTLY:
214
+
215
+ Sources:
216
+ - <URL 1>
217
+ - <URL 2>
218
+ - <URL 3>
219
+
220
+ - LIST ONE RAW URL PER BULLET.
221
+ - DO NOT USE MARKDOWN LINKS.
222
+ - DO NOT INCLUDE ANY TEXT, NOTES, OR EXPLANATIONS AFTER THE SOURCES SECTION.`;for(let a=1;a<=s;a++){let p=null;try{let f=fs();p=await _i.launch({headless:!0,executablePath:f.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let c=await p.newPage();await c.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.178 Safari/537.36"),await c.setViewport({width:1366,height:768});let l=a===1?Math.random()*1e3+500:Math.random()*2e3+1e3;await new Promise(A=>setTimeout(A,l));let u=`https://search.brave.com/ask?q=${encodeURIComponent(i)}&source=web`;await c.goto(u,{waitUntil:"domcontentloaded",timeout:18e4});let d=null,h=45e3,g=Date.now();for(;Date.now()-g<h&&(d=await c.evaluate(()=>{let A=Array.from(document.querySelectorAll('.message:not(.user), .answer-text, .llm-content, [data-type="answer"]')),E="";if(A.length>0&&(E=A.map(J=>J.innerText.trim()).filter(Boolean).join(`
223
+
224
+ `)),E||(E=document.body.innerText),E.includes("anomaly"))throw new Error("ANOMALY_DETECTED");let I=!!document.querySelector('.spinner, .loading, .typing, .streaming, [data-streaming="true"], [data-state="loading"], svg.animate-spin, circle[cx], div[class*="spin"]'),_=A[0]||document.body,v=_?_.innerText.trim():"",W=/^(?:[✓✔]\s*)?Finished/i.test(v)||!!(_&&_.querySelector(".status-finished, .finished")),B=!I&&(W||E.includes("Sources:")&&!I),K={};return document.querySelectorAll("a[href]").forEach(J=>{let xe=J.getAttribute("href")||J.href||"";if(xe.includes("uddg=")&&(xe=decodeURIComponent(xe.split("uddg=")[1].split("&")[0])),xe.includes("url=")&&(xe=decodeURIComponent(xe.split("url=")[1].split("&")[0])),xe&&(xe.startsWith("http://")||xe.startsWith("https://"))&&!xe.includes("search.brave.com")){let N=J.innerText.trim();N&&(K[N]=xe),J.textContent=xe}}),{isFinished:B,text:E,hrefMap:K}}),!(d&&d.isFinished));)await new Promise(A=>setTimeout(A,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,T="";if(y.includes("Sources:")){let A=y.split("Sources:");x=A[0],T=A.slice(1).join("Sources:")}let R=[];for(let A of x.split(`
225
+ `)){let E=A.trim();E&&(/^(View all|Finished|Searching|Answering|Thinking)$/i.test(E)||/^[\+\-]?\d+$/.test(E)||E.includes("search.brave.com")||E.startsWith("https://www.youtube.com/watch")||E.startsWith("https://youtube.com/watch")||R.push(A))}let k=R.join(`
226
+ `).replace(/^(?:[\+\-]?\d+\s*)+/i,"").replace(/\n{3,}/g,`
227
+
228
+ `).trim(),S=A=>!A||A.includes("search.brave.com")||A.includes("youtube.com")||A.includes("youtu.be"),b="";if(T){let A=T.match(/https?:\/\/[^\s\)\>]+/g)||[],E=[];for(let _ of A){let v=_.replace(/[\.\,\;]+$/,""),W=Object.keys(m).find(B=>B.startsWith(v)||v.startsWith(B));W&&m[W]&&(v=m[W]),S(v)||E.push(v)}Object.values(m).forEach(_=>{!S(_)&&!E.includes(_)&&E.push(_)});let I=Array.from(new Set(E));I.length>0&&(b=`Sources:
229
+ `+I.map(_=>`- ${_}`).join(`
230
+ `))}let C=k+(b?`
231
+
232
+ `+b:"");if(!C||/^(\+\d+|Searching|Answering|Thinking|Finished)$/i.test(C))throw new Error("EMPTY_AI_RESPONSE");return await p.close(),`AI Search results for [${n}]:
233
+
234
+ ${C}`}catch(f){if(r=f,Ii.writeFileSync(Li.join(cn,"web_tools","search","ai_mode","ERROR.txt"),f.message),p&&await p.close(),a<s){let c=Math.pow(2,a)*1e3;await new Promise(l=>setTimeout(l,c))}}}}for(let i=1;i<=s;i++){let a=null;try{let p=fs();a=await _i.launch({headless:!0,executablePath:p.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let f=await a.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=i===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"),T=m.querySelector(".result__snippet"),R=x?x.href:"";R.includes("uddg=")&&(R=decodeURIComponent(R.split("uddg=")[1].split("&")[0]));let k=x?x.innerText.trim():"No Title",S=T?T.innerText.trim():"No Snippet";return`${w+1}. ${k}
235
+ Source: ${R}
236
+ Snippet: ${S}`}),t);if(u.length===0){if((await f.evaluate(()=>document.body.innerText)).includes("anomaly"))throw new Error("ANOMALY_DETECTED");return await a.close(),`No results found for query: [${n}].`}let d=u.join(`
237
+
238
+ `);return await a.close(),`${o?`AI Mode temporarily failed, used Standard search.
239
+
240
+ `:""}Search results for [${n}]:
241
+
242
+ ${d}`}catch(p){if(r=p,a&&await a.close(),Ii.writeFileSync(Li.join(cn,"web_tools","search","standard_mode","ERROR.txt"),p.message),i<s){let f=Math.pow(2,i)*1e3;await new Promise(c=>setTimeout(c,f))}}}return`ERROR: Search failed after ${s+1} attempts. Last error: ${r.message}`};import rl from"puppeteer";import il from"turndown";import{gfm as al}from"turndown-plugin-gfm";var cr=async e=>{let n=e;if(typeof e=="object"&&e!==null)n=e.url||e.targetUrl||e.href||"";else if(typeof e=="string"){let r=e.match(/url\s*=\s*["'](.*)["']/);n=r?r[1]:e}let t=typeof n=="string"?n.trim():"";if(!t)return"ERROR: No target URL provided.";let o=3,s=null;for(let r=1;r<=o;r++){let i=null;try{let a=fs();i=await rl.launch({headless:!0,executablePath:a.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let p=await i.newPage();await p.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.178 Safari/537.36"),await p.setViewport({width:1366,height:768});let f=r===1?Math.random()*1e3+500:Math.random()*2e3+1e3;await new Promise(g=>setTimeout(g,f)),await p.goto(t,{waitUntil:"networkidle2",timeout:18e4}),await new Promise(g=>setTimeout(g,5e3));let c=await p.evaluate(()=>{document.querySelectorAll("script, style, noscript, svg, canvas, iframe, ad, .ads, link, meta, img").forEach(T=>T.remove());let y=document.createNodeIterator(document.body,NodeFilter.SHOW_COMMENT),m;for(;m=y.nextNode();)m.remove();for(document.querySelectorAll("*").forEach(T=>{let R=T.attributes;for(let k=R.length-1;k>=0;k--){let S=R[k].name;S!=="href"&&S!=="src"&&T.removeAttribute(S)}});document.querySelector("div, span");)document.querySelectorAll("div, span").forEach(T=>{T.parentNode&&T.replaceWith(...T.childNodes)});document.querySelectorAll("br").forEach(T=>{T.replaceWith(document.createTextNode(`
243
+
244
+ `))});let x=()=>{let T=!1;document.querySelectorAll("*").forEach(R=>{R.childNodes.length===0&&!R.innerText.trim()&&(R.remove(),T=!0)}),T&&x()};return x(),document.body.innerHTML});if(!c)throw new Error("EMPTY_RENDER_RESULT");let l=c.replace(/<br\s*\/?>/gi,`
245
+
246
+ `).replace(/[ \t]+/g," ").replace(/>[ \t]+</g,"><").replace(/\n\s+/g,`
247
+ `).replace(/\n{3,}/g,`
248
+
249
+ `).trim(),u=new il({headingStyle:"atx",codeBlockStyle:"fenced"});u.use(al);let d=u.turndown(l).replace(/\.\s*\n/g,`
250
+ `).replace(/ +/g," ").replace(/\t/g," ").replace(/\n\s+/g,`
251
+ `).replace(/\n{3,}/g,`
252
+
253
+ `),h=d.substring(0,5e4);return await i.close(),`Markdown parsed from [${t}]:
254
+
255
+ ${h}${d.length>5e4?`
256
+
257
+ [TRUNCATED AT 50K CHARS]`:""}`}catch(a){if(s=a,i&&await i.close(),r<o){let p=Math.pow(2,r)*1e3;await new Promise(f=>setTimeout(f,p))}}}return`ERROR: Scrape failed after ${o+1} attempts. Last error: ${s.message}`};var ll=4*(1024*2),fr=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"),h=e.match(d);return h?h[1].trim():null},o=t("action"),s=t("method"),r=t("content"),i=t("content-new"),a=t("content-old"),p=t("id"),f=t("chat-id")||n.chatId||n.sessionId||"default-session";if(o==="temp"){if(!r)return"ERROR: Missing 'content' for temp memory.";let c=Z(Jt,{});c[f]||(c[f]=[]),c[f].push(r),pe(Jt,c);let l=c[f].reduce((u,d)=>u+d.length,0);return`SUCCESS: Temporary context saved for session [${f}]. (Size: ${l} chars)`}if(o==="user"){let c=Z(Pt,[]).map(l=>(l.score===void 0&&(l.score=.5),l));if(s==="add"){if(!r)return"ERROR: Missing 'content' for memory addition.";let l=new Date,u=`${l.getDate()}/${l.getMonth()+1}/${l.getFullYear()}`,d=r.includes("[Saved on:")?r:`${r.trim()} [Saved on: ${u}]`,h=ll,g=c.reduce((x,T)=>x+(T.memory?.length||0),0);for(;c.length>0&&g+d.length>h;){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),pe(Pt,c),`SUCCESS: Memory added with ID [${w.id}] and score [${w.score}]. (Vault Size: ${g+d.length} chars)`}if(s==="update"){let l=p||a,u=i||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 h=new Date,g=`${h.getDate()}/${h.getMonth()+1}/${h.getFullYear()}`,y=u.includes("[Saved on:")?u:`${u.trim()} [Saved on: ${g}]`;return c[d].memory=y,pe(Pt,c),`SUCCESS: Memory [${l}] updated.`}if(s==="delete"){let l=p||r;if(!l)return"ERROR: Missing 'id' for deletion.";let u=c.length,d=c.filter(h=>h.id!==l);return d.length===u?`ERROR: Memory ID [${l}] not found.`:(pe(Pt,d),`SUCCESS: Memory [${l}] deleted.`)}return`ERROR: Invalid method [${s}] for user memory. Use 'add', 'update', or 'delete'.`}return`ERROR: Unknown action [${o}] for memory tool.`};var dr=async(e,n={})=>{let t=L(e).title,o=n.chatId||n.sessionId;if(!o)return"ERROR: No active chatId found in tool context.";if(!t)return"ERROR: Missing 'title' argument.";try{return await Ti(o,t),`SUCCESS: Chat title updated to [${t}] for session [${o}].`}catch(s){return`ERROR: Failed to update chat title: ${s instanceof Error?s.message:String(s)}`}};import Co from"fs";import vi from"path";var Zs=async(e,n={})=>{let{path:t,StartLine:o,EndLine:s,start_line:r,end_line:i,startLine:a,endLine:p}=L(e),f=parseInt(o||r||a),c=parseInt(s||i||p),l=!isNaN(f),u=!isNaN(c),d=f||1,h=c||(f?f+800:800);if(!t)return'ERROR: Missing "path" argument for view_file.';let g=vi.resolve(process.cwd(),t);try{if(!Co.existsSync(g))return`ERROR: File [${t}] does not exist.`;if(Co.statSync(g).isDirectory())return`ERROR: Path [${t}] is a directory. Use list_files instead.`;let m=vi.extname(t).toLowerCase();if([".mp4",".mkv",".avi",".mov",".webm",".flv",".wmv",".mpeg",".mpg"].includes(m))return`ERROR: Unable to read. Type ${m.slice(1).toUpperCase()} not supported`;let x={".pdf":"application/pdf",".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".webp":"image/webp",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".doc":"application/msword"};if(x[m]){if(!(n.isMultiModal!==!1))return`ERROR: Multimodality is not supported for the current model. Unable to load [${t}].`;let v=Co.readFileSync(g).toString("base64"),W=x[m];return{text:`[BINARY FILE]: ${t} (${W}) - Loaded as multimodal part.`,binaryPart:{inlineData:{data:v,mimeType:W}}}}let T=Co.readFileSync(g,"utf8");T.startsWith("\uFEFF")&&(T=T.slice(1)),T=T.replace(/\r\n/g,`
258
+ `).replace(/\r/g,`
259
+ `);let R=T.split(`
260
+ `),k=R.length;!l&&!u&&k>800&&(d=1,h=50);let S=Math.max(0,d-1),b=Math.min(k,h),C=R.slice(S,b),A=`File: [${t}] (Showing lines ${S+1}-${b} of ${k}).`,E=C.map((I,_)=>`${String(S+_+1).padStart(4)}: ${I.trimEnd()}`).join(`
261
+ `);return`${A}
262
+
263
+ ${E}`}catch(y){let m=y instanceof Error?y.message:String(y);return`ERROR: Failed to read file [${t}]: ${m}`}};import Is from"fs";import Ni from"path";var ur=async(e,n={})=>{let{path:t,content:o}=L(e);if(!t)return'ERROR: Missing "path" argument for write_file.';if(o===void 0)return'ERROR: Missing "content" argument for write_file.';o=o.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
264
+ `).replace(/\r/g,`
265
+ `);let s=Ni.resolve(process.cwd(),t),r=Ni.dirname(s);try{await ut.recordFileChange(s);let i="";if(Is.existsSync(s))try{i=`Old File contents:
266
+ ${Is.readFileSync(s,"utf8").split(/\r?\n/).map((R,k)=>`${k+1} | ${R}`).join(`
267
+ `)}
268
+
269
+ `}catch{i=`[Note: Could not read existing file for reversal reference]
270
+
271
+ `}Is.existsSync(r)||Is.mkdirSync(r,{recursive:!0});let p=(x=>x.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
272
+ `).replace(/\r/g,`
273
+ `))(o),f=p.endsWith(`
274
+ `)?p:p+`
275
+ `,c=f.split(/\r?\n/).length,l=Buffer.byteLength(f,"utf8");Is.writeFileSync(s,f,"utf8");let u=Is.readFileSync(s,"utf8"),d=Buffer.byteLength(u,"utf8"),h=u.split(/\r?\n/),g=h.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=h.join(`
276
+ `);else{let x=h.slice(0,50).join(`
277
+ `),T=h.slice(-50).join(`
278
+ `);y=`${x}
279
+
280
+ ... [${g-100} lines truncated] ...
281
+
282
+ ${T}`}u=null;let{systemSettings:m}=await Qt(),w=`SUCCESS: File [${t}] saved.
283
+ - Stats: [${g} lines, ${(d/1024).toFixed(1)} KB]
284
+ ${i}- Content Preview:
285
+
286
+ ${y}`;if(m?.compressToolResults&&g>60){let x=f.split(/\r?\n/),T=x.slice(0,25).join(`
287
+ `)===h.slice(0,25).join(`
288
+ `),R=x.slice(-25).join(`
289
+ `)===h.slice(-25).join(`
290
+ `);T&&R&&(w=`[[SAME]]
291
+ ${w}`)}return w}catch(i){let a=i instanceof Error?i.message:String(i);return`ERROR: Failed to write file [${t}]: ${a}`}};import gr from"fs";import Tl from"path";import cl from"os";var hn=e=>typeof e!="string"?e:e.length>12?(e+"").replace("",""):e,Di=(e,n)=>{if(!e)return"";let t=/\x1B\[[0-?]*[ -/]*[@-~]/g,o=e.split(`
292
+ `),s=[];if(n<=5)return e;let r=i=>i.replace(t,"").length;return o.forEach(i=>{if(r(i)<=n){s.push(i);return}let p=i.split(/(\s+)/),f="",c=0,l=i.match(/^(\s*)/),u=l?l[1]:"";p.forEach((d,h)=>{if(d.length===0)return;let g=r(d);if(c+g>n)if(f.trim().length>0)s.push(f.trimEnd()),f=u.substring(0,Math.min(u.length,8))+d,c=r(f);else if(t.test(d))s.push(d),f=u,c=r(f);else{let y=d;for(;r(y)>n&&n>10;)s.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)&&s.push(f.trimEnd())}),hn(s.join(`
293
+ `))},id=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()},ad=(e,n=40)=>{let t=_n.replaceAll("\\\\","\\");if(e=e.replace(cl.homedir(),"~").replace(t,"FluxFlow").replaceAll("\\","/"),!e||e.length<=n)return hn(e);let o=Math.floor((n-3)/2);return hn(e.substring(0,o)+"..."+e.substring(e.length-o).replaceAll("\\","/"))},Ao=e=>{let n=[],t=new Set,o=e.allowMultiple===!0||String(e.allowMultiple).toLowerCase()==="true";Object.keys(e).forEach(p=>{let f=p.match(/^(searchContent|search_content|replaceContent|replace_content|newContent|new_content|content_to_replace|content_to_add|searchBlock|search_block|newBlock|new_block)_?(\d+)?$/i);if(f){let c=f[2]?parseInt(f[2],10):1;t.add(c)}});let s=Array.from(t).sort((p,f)=>p-f),r=["searchContent","search_content","replaceContent","replace_content","content_to_replace","searchBlock","search_block"],i=["newContent","new_content","content_to_add","newBlock","new_block"],a=(p,f,c)=>{let l,u;for(let d of f){let h=p===1?[`${d}1`,d,`${d}_1`]:[`${d}${p}`,`${d}_${p}`];for(let g of h)if(e[g]!==void 0){l=e[g];break}if(l!==void 0)break}for(let d of c){let h=p===1?[`${d}1`,d,`${d}_1`]:[`${d}${p}`,`${d}_${p}`];for(let g of h)if(e[g]!==void 0){u=e[g];break}if(u!==void 0)break}return{r:l,n:u}};for(let p of s){let{r:f,n:c}=a(p,r,i);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 ${p}. Both replacement and new content must be provided.`,allowMultiple:o}}return{patchPairs:n,allowMultiple:o}},fl=e=>{if(!e)return null;let n="",t=0,o=e.length;for(;t<o;){let s=e[t];if(s==="\\"){for(;t<o&&e[t]==="\\";)t++;n+="\\\\*"}else if(s===`
294
+ `)n+="(?:\\r?\\n|\\\\*n|\\\\*r|\\s*)",t++;else if(s==="\r")n+="(?:\\r|\\\\*r)?",t++;else if(s===" ")n+="(?:\\t|\\\\*t|\\s*)",t++;else if(s==='"'||s==="'"||s==="`")n.endsWith("\\\\*")||(n+="\\\\*"),n+=s,t++;else if(/[.*+?^${}()|[\]]/.test(s))n+="\\"+s,t++;else if(/\s/.test(s)){for(;t<o&&/\s/.test(e[t])&&e[t]!==`
295
+ `&&e[t]!=="\r"&&e[t]!==" ";)t++;n+="\\s*"}else n+=s,t++}if(!n)return null;try{return new RegExp(n,"g")}catch{return null}},$o=(e,n,t={})=>{let o=typeof t=="boolean"?t:!!(t&&t.allowMultiple),s=e.replace(/\r\n/g,`
296
+ `).replace(/\r/g,`
297
+ `),r=m=>m.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
298
+ `).replace(/\r/g,`
299
+ `),i=m=>m.match(/^\s*/)[0],a=m=>{let w=m.split(`
300
+ `).filter(T=>T.trim()!=="");if(w.length===0)return"";let x=i(w[0]);for(let T of w){let R=i(T);R.length<x.length&&(x=R)}return x},p=(m,w,x="")=>{if(!m||w===void 0)return m;let R=/^\t/m.test(w)?" ":" ",k=I=>I.split(`
301
+ `).find(_=>_.trim()!=="")??"",S=k(w).match(/^\s*/)[0].length,b=k(m).match(/^\s*/)[0].length,C=S-b,A=(x.match(/^\s*/)||[""])[0].length;return m.split(`
302
+ `).map((I,_)=>{if(I.trim()===""&&_!==0)return"";let v=I.match(/^\s*/)[0].length,W=Math.max(0,v+C);return _===0&&(W=Math.max(0,W-A)),R.repeat(W)+I.trimStart()}).join(`
303
+ `)},f=[];for(let m=0;m<n.length;m++){let w=n[m],x=(w.replace||"").trim(),T=r(w.new||"");if(x.startsWith("^LINE:")&&x.endsWith("$")){let A=x.slice(6,-1).trim().split(".."),E=parseInt(A[0]),I=A[1]!==void 0?parseInt(A[1]):E;if(!isNaN(E)&&!isNaN(I)){let _=s.split(`
304
+ `);if(E<1||E>_.length||I<E||I>_.length){f.push({index:m,success:!1,error:`Block ${m+1}: Line range ^LINE:${E}..${I}$ out of bounds (file has ${_.length} lines).`});continue}let W=_.slice(E-1,I).join(`
305
+ `),B=0;for(let K=0;K<E-1;K++)B+=_[K].length+1;f.push({index:m,success:!0,startPos:B,firstMatchContent:W,content_to_add:T});continue}}let R=r(w.replace||"");if(R===""&&T===""){f.push({index:m,success:!1,error:`Block ${m+1}: Empty replace and add content.`});continue}let k=R.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),S=null;if(R!==""&&s.includes(R))S=new RegExp(k,"g");else{let C=R.split(`
306
+ `).map(A=>A.trim()).filter(A=>A.length>0).map(A=>A.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\s+/g,"\\s*"));if(C.length>0){let A=C.join("\\s*");try{S=new RegExp(A,"g")}catch{S=new RegExp(k,"g")}}else S=new RegExp(k,"g")}let b=[...s.matchAll(S)];if(b.length===0&&R!==""){let C=fl(R);C&&(b=[...s.matchAll(C)])}if(b.length===0){f.push({index:m,success:!1,error:`Block ${m+1}: Could not find match.`});continue}if(b.length>1&&!o){f.push({index:m,success:!1,error:`Block ${m+1}: Found ${b.length} matches (must be unique or use allowMultiple: true if sure).`});continue}for(let C of b)f.push({index:m,success:!0,startPos:C.index,firstMatchContent:C[0],content_to_add:T})}let c=f.filter(m=>m.success).sort((m,w)=>m.startPos-w.startPos);for(let m=0;m<c.length-1;m++){let w=c[m],x=c[m+1];w.startPos+w.firstMatchContent.length>x.startPos&&(w.success=!1,w.error=`Block ${w.index+1}: Overlaps with another block.`,x.success=!1,x.error=`Block ${x.index+1}: Overlaps with another block.`)}let l=new Map,u=s,d=0,h=0,g=f.filter(m=>m.success).sort((m,w)=>m.startPos-w.startPos);for(let m of g){let w=m.startPos,x=s.substring(0,w).split(`
307
+ `).length,T=w+d,R=x+h,k=u.lastIndexOf(`
308
+ `,T)+1,S=u.substring(k,T),b=p(m.content_to_add,m.firstMatchContent,S),C=u.split(`
309
+ `),A=[];for(let v=Math.max(0,R-4);v<R-1;v++)A.push({num:v+1,text:C[v]});let E=m.firstMatchContent.split(`
310
+ `),I=[],_=R+E.length-1;for(let v=_;v<Math.min(C.length,_+3);v++)I.push({num:v+1,text:C[v]});l.set(m,{success:!0,index:m.index,oldContent:m.firstMatchContent,newContent:b,originalStartLine:x,finalStartLine:R,contextBefore:A,contextAfter:I}),u=u.substring(0,T)+b+u.substring(T+m.firstMatchContent.length),d+=b.length-m.firstMatchContent.length,h+=b.split(`
311
+ `).length-m.firstMatchContent.split(`
312
+ `).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(T=>T.index===m);y.push({success:!1,error:x?x.error:`Block ${m+1}: Unknown error.`})}}return{content:u,results:y}},Mo=(e,n,t,o=8,s=!1)=>{if(!t||t.length===0)return"";let r=e.split(/\r?\n/),i=n.split(/\r?\n/),a=Math.max(r.length,i.length,1),p=Math.max(4,String(a).length),f=g=>String(g).padStart(p," "),c=`[DIFF_START]
313
+ `,l="\u2550".repeat(88),u=0,d=null,h=t.filter(g=>g.success).sort((g,y)=>g.originalStartLine-y.originalStartLine);if(h.forEach((g,y)=>{let m=g.finalStartLine!==void 0?g.finalStartLine:g.originalStartLine;if(d===null)for(u=Math.max(0,m-4);u<m-1;)c+=`[UI_CONTEXT] ${f(u+1)} |${i[u]||""}
314
+ `,u++;else{let b=d,C=b.originalStartLine+b.oldContent.split(`
315
+ `).length-1;if(g.originalStartLine-C-1>=o){let E=Math.min(i.length,u+3);for(;u<E;)c+=`[UI_CONTEXT] ${f(u+1)} |${i[u]||""}
316
+ `,u++;for(c+=`[UI_CONTEXT] ${l}
317
+ `,u=Math.max(u,m-4);u<m-1;)c+=`[UI_CONTEXT] ${f(u+1)} |${i[u]||""}
318
+ `,u++}else for(;u<m-1;)c+=`[UI_CONTEXT] ${f(u+1)} |${i[u]||""}
319
+ `,u++}let w=g.originalStartLine-1,x=r[w]||"",T=g.oldContent.split(`
320
+ `),R=x.match(/^\s*/),k=R?R[0]:"";T.forEach((b,C)=>{let A=b;if(T.length===1&&x.trim().length>0&&x.includes(b.trim()))A=x;else if(C===0){let E=b.match(/^\s*/);(E?E[0]:"").length<k.length&&x.includes(b.trim())&&(A=k+b.trimStart())}c+=`-${f(g.originalStartLine+C)} |${A}
321
+ `});let S=u;if(g.finalStartLine!==void 0)S=g.finalStartLine-1+(g.newContent?g.newContent.split(`
322
+ `).length:0);else{let b=g.originalStartLine+T.length-1,C=r[b]||null;if(C!==null){let A=y<h.length-1?(h[y+1].originalStartLine||i.length)+10:i.length;for(let E=u;E<A;E++){if(i[E]===C){S=E;break}E===i.length-1&&(S=i.length)}}else S=i.length}for(;u<S;)c+=`+${f(u+1)} |${i[u]||""}
323
+ `,u++;d=g}),d!==null){let g=Math.min(i.length,u+3);for(;u<g;)c+=`[UI_CONTEXT] ${f(u+1)} |${i[u]||""}
324
+ `,u++}if(s){let g=`[DIFF_START]
325
+ `,y=c.substring(g.length),m=`[UI_CONTEXT] ${l}
326
+ `,x=y.split(m).map(T=>T.split(`
327
+ `).filter(k=>k.trim()!=="").length>45?`[[VERIFIED]]
328
+ ${T}
329
+ [[/VERIFIED]]`:T);c=g+x.join(m)}return c+="[DIFF_END]",hn(c)},dl=e=>{if(!e)return null;let n=e.replace("[UI_CONTEXT]","").replace(/\r/g,""),t=n.startsWith("-"),o=n.startsWith("+"),s=t||o?n.substring(1):n,r=s.indexOf("|"),i=r!==-1?hn(s.substring(0,r).trim()):"",a=hn(r!==-1?s.substring(r+1):s);return{isR:t,isA:o,num:i,content:a}},ul=(e,n)=>{if(!e&&!n)return 1;if(!e||!n)return 0;let t=e.length,o=n.length,s=e,r=n;t<o&&(s=n,r=e);let i=s.length,a=r.length,p=new Int32Array(a+1),f=new Int32Array(a+1);for(let u=0;u<=a;u++)p[u]=u;for(let u=1;u<=i;u++){f[0]=u;let d=s[u-1];for(let h=1;h<=a;h++)d===r[h-1]?f[h]=p[h-1]:f[h]=Math.min(p[h],f[h-1],p[h-1])+1;p.set(f)}let c=p[a],l=Math.max(t,o);return l===0?1:1-c/l},Pi=e=>{let n=[],t=[];e.forEach((c,l)=>{c.parsed.isR?n.push({index:l,content:c.parsed.content}):c.parsed.isA&&t.push({index:l,content:c.parsed.content})});let o=n.length,s=t.length;if(o===0||s===0)return;let r=Array.from({length:o+1},()=>Array(s+1).fill(0)),i=Array.from({length:o+1},()=>Array(s+1).fill(""));for(let c=1;c<=o;c++)i[c][0]="up";for(let c=1;c<=s;c++)i[0][c]="left";let a=Array.from({length:o},()=>Array(s).fill(0));for(let c=0;c<o;c++)for(let l=0;l<s;l++)a[c][l]=ul(n[c].content.trim(),t[l].content.trim());for(let c=1;c<=o;c++)for(let l=1;l<=s;l++){let u=a[c-1][l-1],d=u>=.2?u:-10,h=r[c-1][l-1]+d,g=r[c-1][l],y=r[c][l-1];h>=g&&h>=y?(r[c][l]=h,i[c][l]="diag"):g>=y?(r[c][l]=g,i[c][l]="up"):(r[c][l]=y,i[c][l]="left")}let p=o,f=s;for(;p>0||f>0;)if(i[p][f]==="diag"){if(a[p-1][f-1]>=.2){let l=n[p-1].index,u=t[f-1].index;e[l].pairContent=e[u].parsed.content,e[u].pairContent=e[l].parsed.content}p--,f--}else i[p][f]==="up"?p--:f--},Yn=new Map,ds=new Map,Fi=200,hr=6,mr=(e,n)=>{n.set(e.key,e),e.type==="chunk"&&e.blocks&&e.blocks.forEach(t=>mr(t,n))},ld=(e,n)=>{if(!e)return{completed:[],active:[]};let t=`${e.id}-${e.text?.length||0}-${n}-${e.isStreaming}-${e.workedDuration||0}`;if(!e.isStreaming&&Yn.has(t))return Yn.get(t);let o=hn(Sl(e.text||"",e.role==="think")),s=`${e.id}-${n}`,r=new Map;if(e.isStreaming){let h=ds.get(s);h&&o.startsWith(h.text)&&(r=h.blocksMap)}let i=(h,g,y,m={})=>{let w=r.get(h);if(w&&w.text===y&&w.type===g&&!!w.isActiveBlock==!!m.isActiveBlock&&!!w.isStreaming==!!m.isStreaming&&w.pairContent===m.pairContent)return w;let x=hn(y),T={...m};return typeof T.pairContent=="string"&&(T.pairContent=hn(T.pairContent)),Array.isArray(T.wrappedLines)&&(T.wrappedLines=T.wrappedLines.map(hn)),{key:h,isStreamingMsg:!!e.isStreaming,workedDuration:e.workedDuration,type:g,text:x,msg:g==="full-message"?e:void 0,...T}};if(o.includes("- Content Preview:")){let h="",g=o.match(/File\s+\[(.*?)\]/i);g&&(h=g[1].split(".").pop().toLowerCase());let T=((o.split("- Content Preview:")[1]||"").split("[SYSTEM] Check the content preview for verification [/SYSTEM]")[0]?.trim()||"").split(`
330
+ `).map(E=>E.replace(/\r$/,"")),R=String(T.length).length,k=[],S=null,b=[],C=()=>{if(!b.length)return;let E=b;b=[],k.push(E.length===1?E[0]:{key:`${E[0].key}-chunk`,type:"chunk",blocks:E})},A=n-(R+6);return T.forEach((E,I)=>{let _=I===T.length-1,v=Di(E,A).split(`
331
+ `),W=i(`${e.id||Date.now()}-write-line-${I}`,"write-line",E,{gutterWidth:R,lineNum:I+1,isFirstLine:I===0,isLastLine:_,extension:h,wrappedLines:v});_&&e.isStreaming?(C(),S=W):(b.push(W),b.length>=hr&&C())}),C(),{completed:k,active:S?[S]:[]}}if(o.includes("[DIFF_START]")){let h=o.match(/\[DIFF_START\]([\s\S]*?)(?:\[DIFF_END\]|$)/),y=(h?h[1].trim():"").split(`
332
+ `).map(S=>S.replace(/\r$/,"")),m=y.map(S=>({line:S,parsed:dl(S),pairContent:null})),w=[];for(let S=0;S<m.length;S++){let b=m[S];b.parsed&&(b.parsed.isR||b.parsed.isA)?w.push(b):w.length>0&&(Pi(w),w=[])}w.length>0&&Pi(w);let x=[],T=null,R=[],k=()=>{if(!R.length)return;let S=R;R=[],x.push(S.length===1?S[0]:{key:`${S[0].key}-chunk`,type:"chunk",blocks:S})};return y.forEach((S,b)=>{let C=b===y.length-1,A=m[b].parsed,E=null;A&&(E=Di(A.content,n-17).split(`
333
+ `));let I=i(`${e.id||Date.now()}-diff-${b}`,"diff-line",S,{isFirstLine:b===0,isLastLine:C,pairContent:m[b].pairContent,wrappedLines:E});C&&e.isStreaming?(k(),T=I):(R.push(I),R.length>=hr&&k())}),k(),{completed:x,active:T?[T]:[]}}if(e.role==="system"||e.isLogo||e.isHelpRecord||e.isTerminalRecord||e.isHomeWarning||e.isImageStats||e.isAskRecord||e.isAboutRecord||e.isUpdateNotification||e.role==="user")return{completed:[i(`${e.id||Date.now()}-full`,"full-message",o)],active:[]};if(!o&&!e.isStreaming){let h={completed:[],active:[]};return Yn.set(t,h),h}let a=[],p=null,f=[],c=null,l=()=>{if(!f.length)return;let h=f;f=[],c=null,a.push(h.length===1?h[0]:{key:`${e.id||"x"}-chunk-${h[0].key}`,type:"chunk",blocks:h})},u=(h,g=!1)=>{if(c!==null&&c!==h.type&&l(),f.push(h),c=h.type,f.length>=hr){if(e.isStreaming&&g)return;l()}};if(e.role==="think"){a.push(i(`${e.id}-header`,"think-header",""));let h=o.split(`
334
+ `);h.forEach((g,y)=>{let m=y===h.length-1;u(i(`${e.id}-${y}`,"think-line",g,{}),m)}),e.isStreaming||(l(),a.push({key:`${e.id}-footer-padding`,type:"think-footer-padding",text:""}))}else{let h=o.split(`
335
+ `),g=!1,y=[],m=!1,w=!1,x="",T=0,R=0;h.forEach((k,S)=>{let b=S===h.length-1,C=k.trim().startsWith("|"),A=k.trim().startsWith("```");if(w){if(k.includes("</think>")||k.includes("<channel|>")||k.includes("</thought>")){let E=k.split(/(?:<\/(think|thought|thoughts)>|<channel\|>)/i),I=E[0]||"",_=E.slice(2).join("");I&&u(i(`${e.id}-think-${S}`,"think-line",I,{}),b&&!_),l(),a.push({key:`${e.id}-think-footer-${S}`,type:"think-footer-padding",text:""}),w=!1,_&&_.trim()&&u(i(`${e.id}-${S}`,"agent-line",_,{}),b)}else u(i(`${e.id}-think-${S}`,"think-line",k,{}),b);return}if(!m&&(k.includes("<think>")||k.includes("<|channel>thought")||k.includes("<thought>")||k.startsWith("<think")||k.startsWith("<|channel>thought"))){l(),g&&(a.push(i(`${e.id}-table-${S}`,"table",y.join(`
336
+ `),{isStreaming:!1})),g=!1,y=[]),a.push(i(`${e.id}-think-header-${S}`,"think-header","")),w=!0;let E=k.replace(/^(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought\s*)\r?\n?/i,"");if(E.includes("</think>")||E.includes("<channel|>")||E.includes("</thought>")){let I=E.split(/(?:<\/(think|thought|thoughts)>|<channel\|>)/i),_=I[0]||"",v=I.slice(2).join("");_&&u(i(`${e.id}-think-${S}`,"think-line",_,{}),b&&!v),l(),a.push({key:`${e.id}-think-footer-${S}`,type:"think-footer-padding",text:""}),w=!1,v&&v.trim()&&u(i(`${e.id}-${S}`,"agent-line",v,{}),b)}else E&&u(i(`${e.id}-think-${S}`,"think-line",E,{}),b);return}m?A?(m=!1,u(i(`${e.id}-code-close-${R}`,"code-fence-close","",{}),b)):(T++,u(i(`${e.id}-code-line-${S}`,"code-line",k,{lineNum:T,lang:x}),b)):A?(m=!0,R=S,T=0,x=k.trim().replace(/^```/,"").trim(),u(i(`${e.id}-code-open-${S}`,"code-fence-open",x,{}),b)):C?(g=!0,y.push(k),b&&(l(),e.isStreaming?p=i(`${e.id}-table-${S}`,"table",y.join(`
337
+ `),{isStreaming:!0}):a.push(i(`${e.id}-table-${S}`,"table",y.join(`
338
+ `),{isStreaming:!1})))):(g&&(l(),a.push(i(`${e.id}-table-${S}`,"table",y.join(`
339
+ `),{isStreaming:!1})),g=!1,y=[]),u(i(`${e.id}-${S}`,"agent-line",k,{}),b))}),!e.isStreaming&&e.workedDuration&&(l(),a.push(i(`${e.id}-worked-duration`,"worked-duration","")))}e.isStreaming&&f.length>0?p=f.length===1?f[0]:{key:`${e.id||"x"}-chunk-active-${f[0].key}`,type:"chunk",blocks:f}:l();let d={completed:a,active:p?[p]:[]};if(e.isStreaming){let h=new Map;if(a.forEach(g=>mr(g,h)),p&&mr(p,h),ds.set(s,{text:o,blocksMap:h}),ds.size>Fi){let g=ds.keys().next().value;ds.delete(g)}}else{if(Yn.set(t,d),Yn.size>Fi){let h=Yn.keys().next().value;Yn.delete(h)}ds.delete(s)}return d},hl={},pl=/<\/think>(\r?\n){2}/gi,ml=/(\r?\n){2}(?=\[?(?:tool:functions|tool\.functions|agent:generalist|agent\.generalist|\s*turn\s*:))/gi,pr=(e,n)=>{let t=!1;for(let o=0;o<n;o++)e[o]==="`"&&(t=!t);return t},gl=/\[SYSTEM\][\s\S]*?\[\/SYSTEM\]|(?:<(think|thought|thoughts)>|<\|channel>thought)[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>)|\[ANSWER\][\s\S]*?(?:\[\/ANSWER\]|$)|\[TOOL RESULT\]:?\s*|^\s*(SUCCESS|ERROR):.*(\r?\n)?|\[\s*turn\s*:\s*(continue|finish)\s*\]|\[\[END\]\]|\[\s*turn\s*:?.*?$|\n\s*turn\s*:?.*?$|\[\s*(?:turn|ANSWER|TOOL).*?$|\n\nResponded on .*|\n\n\[Prompted on: .*\]|@\[TerminalName:.*?, ProcessId:.*?\]/gm,yl=/(\$?\\?\/?\\rightarrow\$?|\$\\rightarrow\$)|(\$?\\?\/?\\leftarrow\$?|\$\\leftarrow\$)|(\$?\\?\/?\\uparrow\$?|\$\\uparrow\$)|(\$?\\?\/?\\downarrow\$?|\$\\downarrow\$)|(\$?\\?\/?\\leftrightarrow\$?|\$\\leftrightarrow\$)/gi,wl=/\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,Ls=!1,Sl=(e,n=!1)=>{if(!e)return e;let t=e.replace(/<\|channel>thought/gi,"<think>").replace(/<channel\|>/gi,"</think>");if(n)return t.replace(/^<(think|thought|thoughts)>/gi,"").replace(/<\/(think|thought|thoughts)>$/gi,"").replace(/^\r?\n+/,"").replace(/\r?\n+$/,"");let o=t.replace(pl,"</think>").replace(ml,(i,a,p,f)=>!Ls&&pr(f,p)?i:"");o&&o.includes("[tool:")&&(o=o.replace(/<(\w+)(?:[^>]*)>\s*([\s\S]*?\[tool:[^\]]*\][\s\S]*?)\s*<\/\1>/gi,(i,a,p)=>p&&p.includes("[tool:")?p.trim():i),Ls&&(o=o.replace(/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi,(i,a)=>a.includes("[tool:")?a.trim():i)),o=o.replace(/<(\w+)(?:[^>]*)>\r?\n?/gi,"").replace(/\r?\n?<\/\w+(?:[^>]*)>/gi,""));let s="tool:functions.",r="agent:generalist.";if(o.toLowerCase().includes(s)||o.toLowerCase().includes(r))for(;;){let i=o.toLowerCase(),a=i.indexOf(s),p=i.indexOf(r),f=s,c=a;if((a===-1||p!==-1&&p<a)&&(f=r,c=p),c===-1)break;if(!Ls&&pr(o,c)){let w=c+f.length,x=i.indexOf(s,w),T=i.indexOf(r,w);if(x===-1&&T===-1)break;let R=-1,k=0;for(;;){let S=i.indexOf(s,k),b=i.indexOf(r,k),C=-1,A=s;if(S===-1&&b===-1)break;if(S===-1||b!==-1&&b<S?(C=b,A=r):C=S,!pr(o,C)){R=C,f=A;break}k=C+A.length}if(R===-1)break;c=R}let l=c,u=!1,d=c-1;for(;d>=0&&/\s/.test(o[d]);)d--;d>=0&&o[d]==="["&&(l=d,u=!0);let h=0,g=!1,y=null,m=c;for(;m<o.length;){let w=o[m];if(!y&&(w==="'"||w==='"'||w==="`")?y=w:y&&w===y&&o[m-1]!=="\\"&&(y=null),y||(w==="("?(h++,g=!0):w===")"&&h--),g&&h===0&&!y){let x=m;if(u){let T=m+1;for(;T<o.length&&/\s/.test(o[T]);)T++;T<o.length&&o[T]==="]"&&(x=T)}o=o.substring(0,l)+o.substring(x+1);break}if(m++,m===o.length)return o=o.substring(0,l),o}}return o=o.replace(gl,""),o=o.replace(yl,i=>{let a=i.toLowerCase();return a.includes("leftrightarrow")?"\u2194":a.includes("rightarrow")?"\u2192":a.includes("leftarrow")?"\u2190":a.includes("uparrow")?"\u2191":a.includes("downarrow")?"\u2193":i}),o=o.replace(wl,i=>hl[i.toLowerCase()]||i),o.trim()},cd=()=>{Yn.clear(),ds.clear()};var yr=async(e,n={})=>{let t=L(e),o=t.path;if(!o)return'ERROR: Missing "path" argument for PatchFile.';let{patchPairs:s,allowMultiple:r,error:i}=Ao(t);if(i)return`ERROR: ${i}`;if(s.length===0)return"ERROR: No valid replacement pairs found. Use searchContent1, newContent1, etc.";let a=t.allowMultiple!==void 0?t.allowMultiple===!0||String(t.allowMultiple).toLowerCase()==="true":r,p=Tl.resolve(process.cwd(),o);try{if(!gr.existsSync(p))return`ERROR: File [${o}] does not exist. Use WriteFile instead.`;let f=n.forcedContent||gr.readFileSync(p,"utf8");f.startsWith("\uFEFF")&&(f=f.slice(1));let c=f.replace(/\r\n/g,`
340
+ `).replace(/\r/g,`
341
+ `),{content:l,results:u}=$o(c,s,{allowMultiple:a}),d=u.filter(m=>!m.success),h=u.filter(m=>m.success);if(h.length===0)return`ERROR: Patch Failed to apply to [${o}].
342
+ ${d.map(m=>` \u2022 ${m.error}`).join(`
343
+ `)}`;await ut.recordFileChange(p,c),gr.writeFileSync(p,l,"utf8");let{systemSettings:g}=await Qt(),y=Mo(c,l,u,12,g?.compressToolResults);return d.length>0?`SUCCESS: File [${o}] updated with some blocks failed. [${h.length}/${s.length}] blocks applied.
344
+
345
+ Failures:
346
+ ${d.map(m=>` \u2022 ${m.error}`).join(`
347
+ `)}
348
+
349
+ ${y}`:`SUCCESS: File [${o}] updated. [${u.length}/${s.length}] blocks applied.
350
+
351
+ ${y}`}catch(f){let c=f instanceof Error?f.message:String(f);return`ERROR: Failed to update file [${o}]: ${c}`}};import us from"fs";import wr from"path";var xl=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"]),El=e=>xl.has(e)||e.startsWith(".pnpm"),bl=e=>{try{let n=String(e.getMonth()+1).padStart(2,"0"),t=String(e.getDate()).padStart(2,"0"),o=String(e.getHours()).padStart(2,"0"),s=String(e.getMinutes()).padStart(2,"0");return`${n}-${t} ${o}:${s}`}catch{return"N/A"}},Sr=async e=>{let n=L(e),t=n.path||null;if(!t)return"ERROR: No directory path provided.";let o=1;if(n.recurse!==void 0&&n.recurse!==null)if(typeof n.recurse=="number")o=n.recurse;else if(typeof n.recurse=="boolean")o=n.recurse?2:1;else{let r=parseInt(String(n.recurse).trim(),10);o=isNaN(r)?1:r}o=Math.max(1,Math.min(3,o));let s=wr.resolve(process.cwd(),t);try{if(!us.existsSync(s))return`ERROR: Path [${t}] does not exist.`;if(!us.statSync(s).isDirectory())return`ERROR: Path [${t}] is a file, not a directory. Use ReadFile instead.`;if(o===1){let g=us.readdirSync(s),y=g.length,m=150,w=g.slice(0,m),x=[];for(let k of w){let S=wr.join(s,k),b={name:k,type:"unknown",size:"N/A",mtime:"N/A"};try{let C=us.statSync(S);b={name:k,type:C.isDirectory()?"directory":"file",size:(C.size/1024).toFixed(1)+"KB",mtime:bl(C.mtime)}}catch{b.type="inaccessible"}x.push(b)}let T=x.map(k=>k.type==="directory"?`${k.name}/`:`${k.name} (${k.size}, ${k.mtime})`).join(`
352
+ `),R=`
353
+
354
+ (Total items in folder: ${y})`;return y>m&&(R=`
355
+
356
+ TRUNCATED: Showing first ${m} of ${y} items.`),g.length=0,w.length=0,x.length=0,`Detailed folder stats for [${t}]:
357
+
358
+ ${T}${R}`}let i=0,a=0,p=0,f=500,c=!1,l=(g,y,m=1)=>{if(y>o||c)return[];let w=[];try{w=us.readdirSync(g)}catch{return[`${" ".repeat(m-1)}[Inaccessible Directory]`]}let x=[],T=[];for(let b of w){let C=wr.join(g,b),A=!1;try{A=us.statSync(C).isDirectory()}catch{}A?x.push({name:b,fullPath:C}):T.push({name:b,fullPath:C})}x.sort((b,C)=>b.name.localeCompare(C.name)),T.sort((b,C)=>b.name.localeCompare(C.name));let R=[],k=" ".repeat(m-1);for(let b of x){if(p>=f){c=!0,R.push(`${k}[Truncated - Maximum item limit reached (${f})]`);break}if(p++,i++,R.push(`${k}${b.name}/`),y<o&&!El(b.name)){let C=l(b.fullPath,y+1,m+1);R.push(...C)}}let S=[];for(let b of T){if(p>=f){c=!0,R.push(`${k}[Truncated - Maximum item limit reached (${f})]`);break}p++,a++;let C="N/A";try{C=(us.statSync(b.fullPath).size/1024).toFixed(1)+"KB"}catch{}S.push(`${b.name} (${C})`)}return S.length>0&&R.push(`${k}${S.join("; ")}`),R},d=l(s,1,1).join(`
359
+ `),h=`
360
+
361
+ (Total items scanned: ${p}, Directories: ${i}, Files: ${a})`;return c&&(h=`
362
+
363
+ TRUNCATED: Scan capped at ${f} items. (Directories: ${i}, Files: ${a})`),`Detailed directory tree for [${t}] (recursive depth: ${o}):
364
+
365
+ ${d}${h}`}catch(r){let i=r instanceof Error?r.message:String(r);return`ERROR: Failed to read folder [${t}]: ${i}`}};var Tr=async(e,n)=>{let t=L(e),{question:o}=t;if(!o)return'ERROR: Missing "question" argument for ask.';if(!n.onAskUser)return"ERROR: onAskUser callback not provided in tool context.";let s=[];Object.keys(t).forEach(r=>{if(r.startsWith("option")){let i=t[r];if(typeof i=="string"&&i.includes("::")){let[a,p]=i.split("::");s.push({id:r,label:a.trim(),description:p.trim()})}else s.push({id:r,label:String(i).trim(),description:""})}});try{return`USER CHOOSE: ${await n.onAskUser(o,s)}`}catch(r){return`ERROR: Failed to get user input: ${r instanceof Error?r.message:String(r)}`}};import Rl from"puppeteer";import vs from"path";import hs from"fs-extra";import{PDFDocument as kl}from"pdf-lib";var xr=async e=>{let{path:n,content:t,orientation:o="portrait",margin:s="0px"}=L(e);if(!n)return'ERROR: Missing "path" argument for write_pdf.';if(!t)return'ERROR: Missing "content" (HTML/CSS) for write_pdf.';let r=vs.resolve(process.cwd(),n),i=null;try{await hs.ensureDir(vs.dirname(r)),await ut.recordFileChange(r);let a=fs();i=await Rl.launch({headless:!0,executablePath:a.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let p=await i.newPage(),f=t,c={},l=async S=>{if(!S||S.startsWith("http://")||S.startsWith("https://")||S.startsWith("data:"))return null;try{let b=vs.resolve(process.cwd(),S);if(await hs.pathExists(b)){let C=vs.extname(b).toLowerCase().replace(".","")||"png",A=C==="jpg"?"jpeg":C==="svg"?"svg+xml":C,E=await hs.readFile(b,"base64");return`data:image/${A};base64,${E}`}}catch{}return null},u=/<link[^>]+href=["']([^"']+)["']/gi,d={},h;for(;(h=u.exec(t))!==null;){let S=h[1],b=h[0];if(S&&b.toLowerCase().includes("stylesheet")&&!S.startsWith("http://")&&!S.startsWith("https://")&&!S.startsWith("data:"))try{let C=vs.resolve(process.cwd(),S);if(await hs.pathExists(C)){let A=await hs.readFile(C,"utf-8");d[b]=`<style>${A}</style>`}}catch{}}for(let[S,b]of Object.entries(d))f=f.split(S).join(b);let g=/<img[^>]+src=["']([^"']+)["']/gi;for(;(h=g.exec(f))!==null;){let S=h[1];if(S&&!c[S]){let b=await l(S);b&&(c[S]=b)}}let y=/url\(\s*['"]?([^'")]+?)['"]?\s*\)/gi;for(;(h=y.exec(f))!==null;){let S=h[1].trim();if(S&&!c[S]){let b=await l(S);b&&(c[S]=b)}}for(let[S,b]of Object.entries(c)){let C=S.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&"),A=new RegExp(`(src=["'])(${C})(["'])`,"gi");f=f.replace(A,`$1${b}$3`);let E=new RegExp(`url\\(\\s*(['"]?)(${C})\\1\\s*\\)`,"gi");f=f.replace(E,`url($1${b}$1)`)}let m=`
366
+ <style>
367
+ @page {
368
+ margin: ${s};
369
+ }
370
+ body {
371
+ margin: 0;
372
+ padding: 0;
373
+ font-family: system-ui, -apple-system, sans-serif;
374
+ }
375
+ * { box-sizing: border-box; }
376
+ .watermark {
377
+ position: fixed;
378
+ top: 50%;
379
+ left: 50%;
380
+ transform: translate(-50%, -50%) rotate(-50deg);
381
+ font-size: 52px;
382
+ font-weight: bold;
383
+ color: rgba(0, 0, 0, 0.005);
384
+ pointer-events: none;
385
+ z-index: -1000;
386
+ text-align: center;
387
+ width: 150%;
388
+ white-space: nowrap;
389
+ text-transform: uppercase;
390
+ letter-spacing: 5px;
391
+ }
392
+ </style>
393
+ <div class="watermark">Generated by FluxFlow CLI (AI)</div>
394
+ ${f}
395
+ `;await p.setContent(m,{waitUntil:"networkidle0",timeout:18e4});let w=await p.pdf({format:"A4",landscape:String(o).toLowerCase()==="landscape",margin:{top:s,right:s,bottom:s,left:s},printBackground:!0}),x=await kl.load(w),T=vs.basename(n);x.setTitle(`FluxFlow_${T}`),x.setAuthor("FluxFlow CLI"),x.setSubject("Generated with Agentic AI System"),x.setKeywords(["FluxFlow","AI","Agentic","Automated"]),x.setCreator("FluxFlow PDF Engine"),x.setProducer("FluxFlow (Generative AI)");let R=await x.save();await hs.writeFile(r,R);let k=await hs.stat(r);return`SUCCESS: PDF generated successfully at [${n}] (${(k.size/1024).toFixed(2)} KB).`}catch(a){let p=a instanceof Error?a.message:String(a);return`ERROR: Failed to generate PDF [${n}]: ${p}`}finally{i&&await i.close()}};import Ui from"fs-extra";import Er from"path";import Cl from"html-to-docx";var br=async e=>{let{path:n,content:t}=L(e);if(!n)return'ERROR: Missing "path" argument for write_docx.';if(!t)return'ERROR: Missing "content" (HTML) for write_docx.';let o=Er.resolve(process.cwd(),n);try{await Ui.ensureDir(Er.dirname(o)),await ut.recordFileChange(o);let s=Er.basename(n),r=t.includes("<html")?t:`
396
+ <!DOCTYPE html>
397
+ <html lang="en">
398
+ <head>
399
+ <meta charset="UTF-8">
400
+ <title>FluxFlow Document</title>
401
+ </head>
402
+ <body>
403
+ ${t}
404
+ </body>
405
+ </html>
406
+ `,i=await Cl(r,null,{title:`FluxFlow_${s}`,creator:"FluxFlow CLI",description:"Generated by Agentic AI System",table:{row:{cantSplit:!0}},footer:!0,pageNumber:!0});return await Ui.writeFile(o,i),`SUCCESS: Word document [${n}] generated successfully.
407
+ - Size: ${(i.length/1024).toFixed(1)} KB`}catch(s){let r=s instanceof Error?s.message:String(s);return`ERROR: Failed to generate DOCX [${n}]: ${r}`}};import kr from"fs/promises";import ps from"path";import Rr from"fast-glob";import{Minimatch as Bi}from"minimatch";async function eo(e,n,t=e,o=1){if(o>12)return[];let s=[],r;try{r=await kr.readdir(e,{withFileTypes:!0})}catch{return[]}for(let i of r){let a=ps.join(e,i.name),p=ps.relative(t,a),f=p.split(ps.sep).map(u=>u.toLowerCase()),c=i.name.toLowerCase();if(!n.some(u=>{let d=u.toLowerCase();return d.startsWith(".")&&c.endsWith(d)?!0:f.some(h=>h===d||h.startsWith(".pnpm"))}))if(i.isDirectory()){let u=await eo(a,n,t,o+1);s=s.concat(u)}else i.isFile()&&s.push({fullPath:a,relativePath:p})}return s}function Al(e,n,t=1/0){if(e===n)return 0;if(e.length===0)return n.length;if(n.length===0)return e.length;if(Math.abs(e.length-n.length)>t)return t+1;let o=Array.from({length:n.length+1},(s,r)=>r);for(let s=1;s<=e.length;s++){let r=[s],i=s;for(let a=1;a<=n.length;a++){let p=e[s-1]===n[a-1]?0:1,f=Math.min(r[a-1]+1,o[a]+1,o[a-1]+p);r.push(f),f<i&&(i=f)}if(o=r,i>t)return t+1}return o[n.length]}function $l(e,n){if(!e||!n)return!1;let t=e.toLowerCase(),o=n.toLowerCase();if(t.includes(o))return!0;let s=t.split(/[^a-z0-9]+/).filter(i=>i.length>0),r=o.split(/[^a-z0-9]+/).filter(i=>i.length>1||o.length===1&&i.length>0);return r.length===0?!1:r.every(i=>{let a=i.length<=2?0:i.length<=5?1:2;for(let p of s)if(p.includes(i)||i.length>=3&&p.length>=3&&Math.abs(p.length-i.length)<=a&&Al(i,p,a)<=a)return!0;return!1})}var to=async e=>{let{keyword:n,path:t,fuzzy:o,subString:s,regex:r}=L(e);if(n==null)return'ERROR: Missing "keyword" argument.';let i=String(n),a=g=>g===!0||g==="true"||g===1||g==="1"||g==="yes",p=r===!1||r==="false"||r===0||r==="0"||r==="no",f=r===!0||r==="true"||r===1||r==="1"||r==="yes",c=a(o)||a(s),l=null,u=null;if(p)c||(u=new RegExp(`(?<![\\w])${i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\\w])`,"i"));else{try{l=new RegExp(i,"i")}catch(g){if(f)return`ERROR: Invalid regex pattern "${i}": ${g.message}`}u=new RegExp(`(?<![\\w])${i.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"],h=150;try{let g=[],y=process.cwd(),m=null;if(t){let _=t.split(";").map(B=>B.trim()).filter(Boolean),v=_.some(B=>B.startsWith("!"));if(_.some(B=>Rr.isDynamicPattern(B)||/[*?{}[\]()|+]/.test(B))){m="glob";let B=t.replace(/\\/g,"/"),K=_.map(N=>N.replace(/\\/g,"/")),J=d.map(N=>N.startsWith(".")?`**/*${N}`:`**/${N}/**`);if(v&&!_.some(N=>!N.startsWith("!"))){let N=await eo(y,d,y),F=M=>M.endsWith("/")?M+"**":M,Q=K.filter(M=>M.startsWith("!")).map(M=>F(M.slice(1))),ce=K.filter(M=>!M.startsWith("!")).map(F);g=N.filter(M=>{let P=M.relativePath.replace(/\\/g,"/"),Y=ce.length===0||ce.some(_e=>{try{return new Bi(_e).match(P)}catch{return!1}}),V=Q.some(_e=>{try{return new Bi(_e).match(P)}catch{return!1}});return Y&&!V})}else{let N=K.some(Q=>/[\(\)\|]|\.\*/.test(Q)),F=[];if(!N)try{F=await Rr(K,{cwd:y,ignore:J,dot:!0,onlyFiles:!0,absolute:!1})}catch{F=[]}if(F.length===0&&(N||Rr.isDynamicPattern(B))){let Q=B.match(/^([^\*\?\(\)\|\[\]\s]+)\//),ce=Q&&!/[\*\?\(\)\|\[\]]/.test(Q[1])?ps.resolve(y,Q[1]):y,M=await eo(ce,d,y);try{let P=B.replace(/^\.\//,"");P=P.replace(/\.\*\/(\\.|[^\/])/g,".*$1"),!P.startsWith("^")&&!P.startsWith(".*")&&(P=`.*${P}`);let Y=new RegExp(P.endsWith("$")?P:`${P}$`,"i");g=M.filter(V=>{let _e=V.relativePath.replace(/\\/g,"/");return Y.test(_e)})}catch{g=[]}}else g=F.map(Q=>({fullPath:ps.resolve(y,Q),relativePath:Q}))}}else{let B=t.replace(/[\/\\]+$/,""),K=ps.resolve(y,B);try{let J=await kr.stat(K);if(J.isDirectory())m="dir",g=await eo(K,d,y);else if(J.isFile())m="file",g.push({fullPath:K,relativePath:ps.relative(y,K)});else return`ERROR: Path is neither a file nor a directory: ${t}`}catch{return`ERROR: Path not found: ${t}`}}}else g=await eo(y,d);let w=g.map(async _=>{try{let v=await kr.readFile(_.fullPath,"utf-8");if(v.includes("\0"))return[];let W=v.split(/\r?\n/),B=[];for(let J=0;J<W.length;J++)(c?W[J].toLowerCase().includes(i.toLowerCase())||$l(W[J],i):p?u&&u.test(W[J]):l&&l.test(W[J])||u&&u.test(W[J]))&&B.push({line:J+1,content:W[J].trim()});return B.length===0?null:{path:_.relativePath.replace(/\\/g,"/"),matches:B}}catch{return[]}}),x=await Promise.all(w),T=[],R=0;for(let _ of x){if(!_||!_.matches)continue;if(R>=h)break;let v=h-R,W=_.matches.slice(0,v);T.push({path:_.path,matches:W}),R+=W.length}typeof global.gc=="function"&&global.gc();let k=c?"(fuzzy mode)":f?"(regex mode)":p?"(keyword mode)":"(standard mode)";if(T.length===0){let _=m==="file"?` in '${t}'`:m==="dir"||m==="glob"?` in '${t}'`:". Try to specify files",v=m==="dir"?"[DIR]":m==="glob"?"[GLOB]":"";return`${v}${v?" ":""}Found 0 matches of '${i}'${_}${k?` ${k}`:""}`}let S=k?` ${k}`:"",b=`${T.length} file${T.length===1?"":"s"}`,C=`${R} match${R===1?"":"es"}`,A;m==="file"?A=`Found ${C} of '${i}' in '${t}'${S}:`:m==="dir"||m==="glob"?A=`Found ${C} of '${i}' in '${t}' across ${b}${S}:`:A=`Found ${C} of '${i}' across ${b}${S}:`;let E=m==="dir"?"[DIR]":m==="glob"?"[GLOB]":"",I=`${E}${E?" ":""}${A}
408
+
409
+ `;for(let _ of T){I+=`${_.path}
410
+ `;for(let v of _.matches)I+=` ${v.line}: ${v.content}
411
+ `;I+=`
412
+ `}return I.trimEnd()}catch(g){return`ERROR: ${g.message}`}};import Wi from"fs-extra";import Cr from"path";var Ml=(e,n={})=>{try{if(e.length<8||e[0]!==137||e[1]!==80||e[2]!==78||e[3]!==71)return e;let t=[],o=[];for(let i=0;i<256;i++){let a=i;for(let p=0;p<8;p++)a&1?a=3988292384^a>>>1:a=a>>>1;o[i]=a}let s=i=>{let a=4294967295;for(let p=0;p<i.length;p++)a=o[(a^i[p])&255]^a>>>8;return(a^4294967295)>>>0},r=(i,a)=>{let p=Buffer.from(i,"ascii"),f=Buffer.from(a,"utf-8"),c=p.length+1+f.length,l=Buffer.alloc(8+c+4);l.writeUInt32BE(c,0),l.write("tEXt",4,"ascii"),p.copy(l,8),l[8+p.length]=0,f.copy(l,8+p.length+1);let u=s(l.subarray(4,8+c));return l.writeUInt32BE(u,8+c),l};for(let[i,a]of Object.entries(n))a!=null&&t.push(r(i,String(a)));if(t.length===0)return e;if(e.subarray(12,16).toString("ascii")==="IHDR"){let a=e.subarray(0,33),p=e.subarray(33);return Buffer.concat([a,...t,p])}return e}catch{return e}},Ar=async(e,n={})=>{let t=L(e),o=t.prompt||t.text,s=t.path||t.outputPath||t.output||"generated_image.png",r=t.ratio;if(!o)return'ERROR: Missing "prompt" argument for generate_image.';let i=["nsfw","naked","nudity","nude","porn","sex","xxx","erotic","gore","bloody","violence","abuse","suicide","murder","hentai","pedophile","rape"],a=o.toLowerCase();if(i.some(f=>a.includes(f)))return"ERROR: Prompt blocked by system safety filter (inappropriate or unsafe content detected).";try{let f=await Qt();if(!await Ci(f))return`ERROR: Insufficient Quota for selected quality. Either tell user reduce quality or wait for next refresh cycle (${(await Ai()).nextResetMin||60}m).`;let l=f.imageSettings||{keyType:"Default",quality:"Low-High",apiKey:""},u=l.keyType==="Custom"&&l.apiKey?l.apiKey:FALLBACK_IMAGE_KEY,h={Low:"flux","Low-High":"zimage",Medium:"gptimage","Medium-High":"gptimage",High:"qwen-image",Ultra:"gptimage-large",Premium:"nanobanana-pro"}[l.quality]||"zimage",g=1024,y=1024;if(r){let v=r.replace(/\s+/g,"");v==="16:9"?(g=1024,y=576):v==="9:16"?(g=576,y=1024):v==="4:3"?(g=1024,y=768):v==="3:4"?(g=768,y=1024):v==="1:1"&&(g=1024,y=1024)}let m=Math.floor(Math.random()*1e7),x=`https://gen.pollinations.ai/image/${encodeURIComponent(o)}?model=${h}&width=${g}&height=${y}&seed=${m}&enhance=true&reasoning=high&quality=high&negative=${encodeURIComponent("deformed, distorted, disfigured, poorly drawn, bad anatomy, wrong anatomy, extra limb, missing limb, floating limbs, disconnected limbs, mutation, mutated hands and fingers, blurry, low quality, low resolution, extra fingers, censored, watermarks, signatures")}`,T=await fetch(x,{method:"GET",headers:{Authorization:`Bearer ${u}`}});if(!T.ok){let v=T.status,W="";try{W=await T.text()}catch{}return v===402||W.includes("Insufficient balance")||W.includes("PAYMENT_REQUIRED")?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed with status [${v}]: ${W||"Unknown API Error"}`}if((T.headers.get("content-type")||"").includes("application/json")){let v=await T.json();return v.status===402||v.error&&v.error.code==="PAYMENT_REQUIRED"?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed: ${v.error?.message||JSON.stringify(v)}`}let k=await T.arrayBuffer(),S=Buffer.from(k),b={Title:o,Description:"Generated via FluxFlow CLI",Software:"FluxFlow CLI",Author:"FluxFlow","Creation Time":new Date().toISOString(),Prompt:o,Model:`Fluxflow:${h}`,Ratio:r||"1:1",Seed:String(m)};S=Ml(S,b);let C=Cr.resolve(process.cwd(),s);await Wi.ensureDir(Cr.dirname(C)),await ut.recordFileChange(C),await Wi.writeFile(C,S),await $i(f);let A=Cr.extname(s).toLowerCase(),I={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".webp":"image/webp"}[A]||"image/png";return n.isMultiModal!==!1?{text:`SUCCESS: Image successfully generated from prompt [${o}] and saved to [${s}]. Output attached to multimodal part`,binaryPart:{inlineData:{data:S.toString("base64"),mimeType:I}}}:`SUCCESS: Image successfully generated from prompt [${o}] and saved to [${s}].`}catch(f){return`ERROR: Failed during image generation: ${f instanceof Error?f.message:String(f)}`}};var no=async(e,n={})=>{let t=r=>{let i=new RegExp(`${r}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),a=e.match(i);return a?a[2].trim():null},o=t("id"),s=t("summary");if(!o||!s)return"ERROR: Missing 'id' or 'summary' for saveSummary tool.";try{let r=Z(Jt,{}),i=Z(In,{});return i[o]=s,delete r[o],pe(In,i),pe(Jt,r),`SUCCESS: Saved summary and purged raw memories for chat [${o}].`}catch(r){let i=r instanceof Error?r.message:String(r);return`ERROR: Failed to save summary for chat [${o}]: ${i}`}};var Ns=async(e,n={})=>{let o=(s=>{let r=new RegExp(`${s}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),i=e.match(r);return i?i[2].trim():null})("id");if(!o)return"ERROR: Missing 'id' parameter for addMemScore tool.";try{let s=Z(Pt,[]),r=!1,i=[];for(let c of s)c.score===void 0&&(c.score=.5),c.id===o?(c.score=Math.min(2,c.score+.2),r=!0):(c.score*=.98,c.score<.05&&(c.score=0)),c.score=Math.round(c.score*1e5)/1e5,c.score>0&&i.push(c);if(pe(Pt,i),!r)return`WARNING: Memory ID [${o}] not found. Other memories decayed by -0.01.`;let a=i.find(c=>c.id===o),p=a?a.score.toFixed(2):"deleted (score <= 0)",f=s.length-i.length;return`SUCCESS: Adjusted memory scores. Target [${o}] is now ${p}.${f>0?` Purged ${f} decayed memories.`:""}`}catch(s){let r=s instanceof Error?s.message:String(s);return`ERROR: Failed to adjust memory score for [${o}]: ${r}`}};import Mr from"fs-extra";import gs from"path";import{createRequire as Il}from"module";import ms from"fs-extra";import $r from"path";import Ol from"https";var Hi={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 _l(e,n=null){let t=n||`https://unpkg.com/tree-sitter-wasms@0.1.13/out/${e}`,o=$r.join(ls,e);return await ms.ensureDir(ls),new Promise((s,r)=>{let i={headers:{"User-Agent":"FluxFlow-Agent"}};Ol.get(t,i,a=>{if([301,302,307,308].includes(a.statusCode)&&a.headers.location){let f=a.headers.location;if(!f.startsWith("http")){let c=new URL(t);f=`${c.protocol}//${c.host}${f}`}_l(e,f).then(s).catch(r);return}if(a.statusCode!==200){r(new Error(`Failed to download ${e}: HTTP ${a.statusCode}`));return}let p=ms.createWriteStream(o);a.pipe(p),p.on("finish",()=>{p.close(),s()})}).on("error",a=>{ms.existsSync(o)&&ms.unlink(o,()=>{}),r(a)})})}function au(e){let n=$r.join(ls,e);return ms.existsSync(n)}async function lu(e){let n=$r.join(ls,e);ms.existsSync(n)&&await ms.unlink(n)}var Yi=Il(import.meta.url),Gi=Yi("web-tree-sitter"),ji=!1,Ki=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"]),qi=new Set(["export_statement","lexical_declaration","variable_declaration","variable_declarator","pair","assignment_expression"]);function pn(e,n=50){if(!e)return"";let t=e.replace(/\s+/g," ").trim();return t.length>n?t.substring(0,n-3)+"...":t}function zi(e){let n=e.type;if(n==="if_statement"){let o=e.childForFieldName("condition");return o?`if (${pn(o.text,40)})`:"if"}if(n==="else_clause")return"else";if(n==="while_statement"||n==="do_statement"){let o=e.childForFieldName("condition");return`${n.split("_")[0]} (${o?pn(o.text,40):""})`}if(n==="for_statement"||n==="for_in_statement"||n==="for_of_statement"){let s=e.text.split(`
413
+ `)[0].match(/for\s*(?:await\s*)?\((.*)\)/);return s?`for (${pn(s[1],40)})`:"for"}if(n==="switch_statement"){let o=e.childForFieldName("value");return`switch (${o?pn(o.text,40):""})`}if(n==="try_statement")return"try";if(n==="catch_clause")return"catch";if(n==="element"||n==="script_element"||n==="style_element"||n==="jsx_element"||n==="jsx_self_closing_element"){let o=e.childForFieldName("opening_element")||e.childForFieldName("start_tag")||e.children.find(r=>r.type==="start_tag")||e,s=o.childForFieldName("name")||o.childForFieldName("tag_name")||o.children.find(r=>r.type==="tag_name");return s?`<${pn(s.text,30)}>`:null}if(["import_declaration","import_from_statement","import_statement","preproc_include"].includes(n))return pn(e.text.split(`
414
+ `)[0],60);if(n==="pair"){let o=e.childForFieldName("key");return o?pn(o.text.replace(/["']/g,""),40):null}if(n==="assignment_expression"){let o=e.childForFieldName("left");return o?`${pn(o.text,30)} = ...`:null}if(n==="variable_declarator"){let o=e.childForFieldName("name")||e.children.find(s=>["identifier","object_pattern","array_pattern"].includes(s.type));return o?pn(o.text,40):null}let t=e.childForFieldName("name")||e.childForFieldName("declarator")||e.children.find(o=>["identifier","type_identifier","field_identifier","property_identifier","shorthand_property_identifier"].includes(o.type));if(t){if(t.type.includes("declarator")){let o=t.descendantsOfType("identifier")[0]||t.descendantsOfType("field_identifier")[0];if(o)return pn(o.text,40)}return pn(t.text,40)}if(["arrow_function","function_expression","function_declaration"].includes(n)){let o=e.parent;for(;o&&o.type!=="program";){let s=zi(o);if(s)return s;if(!qi.has(o.type))break;o=o.parent}}return null}function Ll(e){let n=[];function t(o){for(let s of o.children)Ki.has(s.type)?n.push(s):t(s)}return t(e),n}function vl(e){return e.replace(/_([a-z])/g,n=>n[1].toUpperCase())}function Vi(e,n=0,t=!0,o="",s=null,r=12){let i=e.type,a=zi(e),p=Ki.has(i)||n===0,f=Ll(e),c=p&&n>0&&(qi.has(i)&&f.length>0||a!==null&&a===s&&f.length>0),l="",u=o,d=n,h=s;if(p&&!c){let g=e.startPosition.row+1,y=e.endPosition.row+1,m=vl(i),w=a?`${m} [${a}]`:m;n===0?(l+=`\u{1F4C1} ROOT (Lines: ${g}-${y})
415
+ `,u=o):(l+=`${o}${t?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 "}${w} (Lines: ${g}-${y})
416
+ `,u+=t?" ":"\u2502 "),d=n+1,h=a}return d>r&&f.length>0?l+=`${u}\u2514\u2500\u2500 ... depth exceeded ...
417
+ `:f.forEach((g,y)=>{let m=y===f.length-1;l+=Vi(g,d,c?t&&m:m,u,h,r)}),l}var Or=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=gs.isAbsolute(n)?n:gs.resolve(process.cwd(),n);if(!Mr.existsSync(t))return`ERROR: File not found: ${n}`;let o=gs.extname(t).slice(1).toLowerCase(),s=Hi[o];if(!s)return`ERROR: Unsupported file extension: .${o}`;let r=gs.resolve(ls,s);if(!Mr.existsSync(r))return`ERROR: Parser for .${o} not found. Please download it in Settings > Other.`;try{let i=Gi.Parser;if(!ji){let h;try{h=gs.join(gs.dirname(Yi.resolve("web-tree-sitter")),"tree-sitter.wasm")}catch{h=gs.join(process.cwd(),"node_modules","web-tree-sitter","tree-sitter.wasm")}await i.init({locateFile:g=>g==="tree-sitter.wasm"||g.endsWith("tree-sitter.wasm")?h:g}),ji=!0}let a=new i,p=await Gi.Language.load(r);a.setLanguage(p);let f=await Mr.readFile(t,"utf8"),c=f.split(`
418
+ `).length,l=12;c>1e4?l=2:c>=8e3?l=3:c>=5e3?l=5:c>=4e3?l=8:c>2e3&&(l=10);let u=a.parse(f),d=Vi(u.rootNode,0,!0," ",null,l);return`\u{1F4C4} File Map for: ${n}
419
+ ${d}`}catch(i){let a=i instanceof Error?i.message:typeof i=="object"?JSON.stringify(i):String(i),p=i instanceof Error?`
420
+ Stack: ${i.stack}`:"";return`ERROR: Failed to map file: ${a}${p}`}};import Kn from"fs";import Xi from"path";var Ji=async(e,n={})=>{let{method:t,tasks:o,markDone:s}=L(e),r=n.chatId||"default";if(!t)return'ERROR: Missing "method" argument for todo tool (create/append/get).';let i=Xi.join(_n,"plan",r),a=Xi.join(i,"todo.md"),p=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(h=>h.slice(1,-1).replace(/\\(.)/g,"$1")):u.slice(1,-1).split(",").map(h=>h.trim()).filter(Boolean)}return l},f=l=>{let u=p(l);return u?(Array.isArray(u)?u:String(u).split(`
421
+ `)).map(h=>{let g=String(h).trim();return g?g.startsWith("- [ ]")||g.startsWith("- [x]")||g.startsWith("- [X]")?g:`- [ ] ${g}`:null}).filter(Boolean).join(`
422
+ `)+`
423
+ `:""},c=(l,u)=>{if(!u)return{content:l,markedCount:0};let d=p(u),h=(Array.isArray(d)?d:[d]).map(w=>String(w).replace(/^- \[[xX ]\]\s*/i,"").trim()).filter(Boolean),g=l.split(`
424
+ `),y=0,m=!1;for(let w of h){let x=!1;for(let T=0;T<g.length;T++)if(g[T].includes(w)&&/^- \[\s\]/.test(g[T].trim())){g[T]=g[T].replace("- [ ]","- [x]"),x=!0,m=!0,y++;break}if(!x){for(let T=0;T<g.length;T++)if(g[T].toLowerCase().includes(w.toLowerCase())&&/^- \[\s\]/.test(g[T].trim())){g[T]=g[T].replace("- [ ]","- [x]"),x=!0,m=!0,y++;break}}}return{content:m?g.join(`
425
+ `):l,markedCount:y}};try{if(Kn.existsSync(i)||Kn.mkdirSync(i,{recursive:!0}),t==="create"){if(!o)return'ERROR: Missing "tasks" for create method.';let l=f(o),u=0;if(s){let h=c(l,s);l=h.content,u=h.markedCount}await ut.recordFileChange(a),Kn.writeFileSync(a,l,"utf8");let d=l.split(/\r?\n/).map(h=>h.trim()).filter(h=>h.startsWith("- [ ]")||h.startsWith("- [x]")||h.startsWith("- [X]")).length;if(u>0){let h=l.split(/\r?\n/).map(g=>g.trim()).filter(g=>g.startsWith("- [x]")||g.startsWith("- [X]")).length;return`SUCCESS: TASK LIST CREATED (${u} marked done, ${h} completed, ${d-h} left)
426
+ ${l}`}return`SUCCESS: TASK LIST CREATED (${d} total)
427
+ ${l}`}if(t==="append"){if(!o)return'ERROR: Missing "tasks" for append method.';let l=f(o);await ut.recordFileChange(a),Kn.appendFileSync(a,l,"utf8");let u=Kn.readFileSync(a,"utf8"),d=u.split(/\r?\n/).map(m=>m.trim()),h=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, ${h-g} left, ${y} added)
428
+ ${u}`}if(t==="get"){if(!Kn.existsSync(a))return"TODO GET: No task list found for this session.";let l=Kn.readFileSync(a,"utf8"),u=0;if(s){let m=c(l,s);m.markedCount>0&&(l=m.content,u=m.markedCount,await ut.recordFileChange(a),Kn.writeFileSync(a,l,"utf8"))}let d=l.split(/\r?\n/).map(m=>m.trim()),h=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, ${h-g} left
429
+ ${l}`}return`ERROR: Unknown method "${t}". Use create, append, or get.`}catch(l){return`ERROR: Todo tool failure: ${l instanceof Error?l.message:String(l)}`}};var _r=async(e,n={})=>{let{runSubagent:t}=await import("./ai-ACFJ2D4K.js"),o=L(e),s=o.task||o.instruction||o.prompt,r=o.model||null,i=o.tools||null;if(!s)return'ERROR: Missing "task" argument for invokeSync.';let a=null;if(i)try{let f=i.trim();f.startsWith("[")&&f.endsWith("]")&&(f=f.substring(1,f.length-1)),a=f.split(",").map(c=>c.trim().replace(/^["']|["']$/g,"")).filter(Boolean)}catch{}let p=o.title||s.substring(0,30);try{n.onVisualFeedback&&n.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${p}`);let f=await t(s,n,r,a,50);return n.onVisualFeedback&&n.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${p} [COMPLETED]
430
+ `),f}catch(f){let{isTerminationSignaled:c}=await import("./ai-ACFJ2D4K.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 ${p} ${u}
431
+ `)}return`ERROR: Subagent execution failed: ${f.message}`}};var Qi=async(e,n={})=>{let{runSubagent:t}=await import("./ai-ACFJ2D4K.js"),o=L(e),s=o.task||o.instruction||o.prompt,r=o.model||null,i=o.title||null,a=o.tools||null;if(!s)return'ERROR: Missing "task" argument for invoke.';let p=null;if(a)try{let m=a.trim();m.startsWith("[")&&m.endsWith("]")&&(m=m.substring(1,m.length-1)),p=m.split(",").map(w=>w.trim().replace(/^["']|["']$/g,"")).filter(Boolean)}catch{}let 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:i||s.substring(0,30),task:s,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:[]},h={chunks:[],totalWords:0};ze.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,T=new Promise(S=>{x=S}),R={id:w,question:m,answered:!1,answer:null,askedAt:Date.now(),_resolve:x};return d.questions.push(R),d.status="waiting",n.onSubagentUpdate&&n.onSubagentUpdate(),yo(`[SYSTEM] Background subagent "${d.title}" is WAITING FOR YOUR INPUT: "${m}"
432
+ Respond using tool: [tool:functions.Answer(id="${f}", answer="...")]
433
+ [/SYSTEM]`),await T},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){h.totalWords+=w,h.chunks.push({time:x,words:w});let T=x-400;if(h.chunks=h.chunks.filter(R=>R.time>=T),h.chunks.length>0){let R=h.chunks.reduce((b,C)=>b+C.words,0),k=h.chunks[0].time,S=Math.max(.4,(x-k)/1e3);d.wps=Math.round(R/S*10)/10}}n.onSubagentUpdate&&n.onSubagentUpdate()}};return t(s,y,r,p,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(`
434
+ `);x.length>5&&(w=x.slice(0,4).join(`
435
+ `)+`
436
+ ... [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(),yo(`[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-ACFJ2D4K.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(),yo(`[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 Ir=async(e,n={})=>{let o=L(e).id;if(!o)return'ERROR: Missing "id" argument for getProgress.';let s=ze.find(a=>a.id===o);if(!s)return`ERROR: Subagent task with ID [${o}] not found.`;let r=`Subagent Task Status: ${s.status.toUpperCase()}
437
+ `;if(r+=`Title: ${s.title}
438
+ `,r+=`Task: ${s.task}
439
+ `,s.startedAt){let a=Math.floor((Date.now()-s.startedAt)/1e3);r+=`Elapsed Time: ${a}s
440
+ `}if(r+=`Turns Completed: ${s.progress.length}
441
+ `,(s.status==="running"||s.status==="waiting")&&(s.currentTool&&(r+=`Current Tool: ${s.currentTool}
442
+ `),s.wps>0&&(r+=`TPS: ${s.wps}
443
+ `)),s.questions&&s.questions.length>0){let a=s.questions.filter(p=>!p.answered);a.length>0&&(r+=`
444
+ **PENDING QUESTION**
445
+ `,a.forEach(p=>{r+=`"${p.question}"
446
+ `}),r+=`Respond using tool: [tool:functions.Answer(id="${s.id}", answer="...")]
447
+
448
+ `)}return r+=`
449
+ Progress Log:
450
+ `,s.progress.forEach((a,p)=>{r+=`--- Turn ${p+1} ---
451
+ `;let c=a.filter(l=>!l.startsWith("[SUBAGENT SUCCESS]")).map(l=>{if(l.startsWith("[Subagent Response]")){let u="[Subagent Response]",h=l.substring(u.length),g="tool:functions.";for(;;){let m=h.toLowerCase().indexOf(g);if(m===-1)break;let w=m,x=!1,T=m-1;for(;T>=0&&/\s/.test(h[T]);)T--;T>=0&&h[T]==="["&&(w=T,x=!0);let R=0,k=!1,S=null,b=m;for(;b<h.length;){let C=h[b];if(!S&&(C==="'"||C==='"'||C==="`")?S=C:S&&C===S&&h[b-1]!=="\\"&&(S=null),S||(C==="("?(R++,k=!0):C===")"&&R--),k&&R===0&&!S){let A=b;if(x){let E=b+1;for(;E<h.length&&/\s/.test(h[E]);)E++;E<h.length&&h[E]==="]"&&(A=E)}h=h.substring(0,w)+h.substring(A+1);break}if(b++,b===h.length){h=h.substring(0,w);break}}}return u+`
452
+ `+h.trim()}return l.startsWith("[Executing Tool]")&&l.length>256?l.substring(0,256)+"...[truncated from logs]":l});r+=c.join(`
453
+ `)+`
454
+
455
+ `}),s.status==="completed"&&s.finalAnswer?r+=`Final Answer:
456
+ ${s.finalAnswer}
457
+ `:s.status==="failed"&&s.error&&(r+=`Failure Error: ${s.error}
458
+ `),r.replace(/\r\n/g,`
459
+ `).replace(/\n{3,}/g,`
460
+
461
+ `).trim().replace(/\[TOOL RESULT\]/gi,"TOOL RESULT:")};var Zi=async(e,n={})=>{let o=L(e).id;if(!o)return'ERROR: Missing "id" argument for cancel.';let s=ze.find(r=>r.id===o);return s?s.status==="completed"||s.status==="failed"?`INFO: Subagent task with ID [${o}] has already finished with status [${s.status.toUpperCase()}].`:s.status==="cancelled"?`INFO: Subagent task with ID [${o}] is already cancelled.`:(s.status="cancelled",n.onSubagentUpdate&&n.onSubagentUpdate(),`SUCCESS: Subagent task with ID [${o}] has been cancelled.`):`ERROR: Subagent task with ID [${o}] not found.`};import St from"fs-extra";import Et from"path";var Nl=["node_modules","dist","bin","logs",".git",".fluxflow","secret",".gemini",".agents","tmp","temp","build","out","snapshots"];async function so(e,n=e){let t={},o=await St.readdir(e,{withFileTypes:!0}).catch(()=>[]);for(let s of o){if(Nl.includes(s.name))continue;let r=Et.join(e,s.name),i=Et.relative(n,r).replace(/\\/g,"/");if(s.isDirectory()){let a=await so(r,n);Object.assign(t,a)}else{let a=await St.stat(r).catch(()=>null);a&&(t[i]={size:a.size,mtime:a.mtimeMs})}}return t}async function ea(e,n){await St.ensureDir(e);for(let t of Object.keys(n)){let o=Et.join(process.cwd(),t),s=Et.join(e,t);await St.ensureDir(Et.dirname(s)),await St.copyFile(o,s).catch(()=>{})}}async function Lr(e,n,t=null,o=null){if(!await St.pathExists(e))return;o||(o=e);let s=await St.readdir(e,{withFileTypes:!0}).catch(()=>[]);for(let r of s){let i=Et.join(e,r.name),a=Et.join(n,r.name);if(r.isDirectory())await Lr(i,a,t,o);else{let p=Et.relative(o,i).replace(/\\/g,"/"),f=await St.pathExists(a);f&&await St.chmod(a,438).catch(()=>{}),await St.ensureDir(Et.dirname(a));let c=await St.copyFile(i,a).then(()=>!0).catch(()=>!1);await St.chmod(a,438).catch(()=>{}),t&&(c?f?t.replaced++:t.restored++:t.failed.push(p))}}}var qn={async takeInitialSnapshot(e){try{let n=Et.join(_n,"snapshots",e);await St.remove(n).catch(()=>{}),await St.ensureDir(n);let t=await so(process.cwd());await ea(Et.join(n,"initial"),t);let o=Z(fn,{});o[e]={initialManifest:t,currentManifest:t,checkpoints:[{id:"initial",timestamp:new Date().toISOString(),newFiles:[],modifiedFiles:[],deletedFiles:[],toolsUsed:[]}]},pe(fn,o)}catch{}},async recordTurnDelta(e,n,t=[]){try{let o=Z(fn,{}),s=o[e];if(!s)return;let r=s.currentManifest||s.initialManifest,i=await so(process.cwd()),a=[],p=[],f=[];for(let[l,u]of Object.entries(i)){let d=r[l];d?(d.size!==u.size||d.mtime!==u.mtime)&&p.push(l):a.push(l)}for(let l of Object.keys(r))i[l]||f.push(l);let c=[...a,...p];if(c.length>0||f.length>0){let l={};for(let d of c)l[d]=i[d];let u=Et.join(_n,"snapshots",e,`turn_${n}`);await ea(u,l)}s.checkpoints.push({id:`turn_${n}`,timestamp:new Date().toISOString(),newFiles:a,modifiedFiles:p,deletedFiles:f,toolsUsed:t}),s.currentManifest=i,pe(fn,o)}catch{}},async getCheckpoints(e){try{let t=Z(fn,{})[e];return t?t.checkpoints||[]:[]}catch{return[]}},async rollbackToCheckpoint(e,n){try{let t=Z(fn,{}),o=t[e];if(!o)throw new Error("No session active for Advance Rollback.");let s=o.checkpoints||[],r=s.findIndex(c=>c.id===n);if(r===-1)throw new Error(`Checkpoint [${n}] not found.`);let i=Et.join(_n,"snapshots",e),a={restored:0,replaced:0,failed:[]},p=await so(process.cwd());for(let c of Object.keys(p)){let l=Et.join(process.cwd(),c);await St.chmod(l,438).catch(()=>{}),await St.remove(l).catch(()=>{})}let f=Et.join(i,"initial");await Lr(f,process.cwd(),a,f);for(let c=1;c<=r;c++){let l=s[c],u=Et.join(i,l.id);if(await Lr(u,process.cwd(),a,u),l.deletedFiles&&l.deletedFiles.length>0)for(let d of l.deletedFiles){let h=Et.join(process.cwd(),d);await St.chmod(h,438).catch(()=>{}),await St.remove(h).catch(()=>{})}}return o.checkpoints=s.slice(0,r+1),o.currentManifest=await so(process.cwd()),pe(fn,t),{checkpointId:n,stats:a}}catch(t){throw new Error(`Rollback failed: ${t.message}`)}},async getLatestFileChanges(e){try{let t=Z(fn,{})[e];if(!t||!t.checkpoints||t.checkpoints.length===0)return{newFiles:[],modifiedFiles:[],deletedFiles:[]};let o=t.checkpoints[t.checkpoints.length-1];return{newFiles:o.newFiles||[],modifiedFiles:o.modifiedFiles||[],deletedFiles:o.deletedFiles||[]}}catch{return{newFiles:[],modifiedFiles:[],deletedFiles:[]}}},async cleanup(e){try{let n=Et.join(_n,"snapshots",e);await St.remove(n).catch(()=>{});let t=Z(fn,{});t[e]&&(delete t[e],pe(fn,t))}catch{}}};var vr=async(e,n={})=>{let t=L(e),o=t.method,s=t.id,r=n.chatId;if(!n.systemSettings?.advanceRollback)return"ERROR: Advance Rollback feature is currently disabled in settings under Security. Tell user to enable it.";if(!r)return"ERROR: No active chat transaction found for rollback.";if(o==="getCheckpoint"){let a=await qn.getCheckpoints(r);if(a.length===0)return"No checkpoints available.";let p={write_file:"WriteFile",update_file:"PatchFile",view_file:"ReadFile",read_folder:"ReadFolder",exec_command:"Run",web_search:"WebSearch",web_scrape:"WebScrape",search_keyword:"SearchKeyword",CodeSearch:"SearchKeyword",code_search:"SearchKeyword",write_pdf:"WritePDF",write_docx:"WriteDoc",generate_image:"GenerateImage",file_map:"FileMap",todo:"Todo",await:"Await",ask:"Ask",ask_user:"Ask",invoke:"Invoke",invokesync:"InvokeSync",getprogress:"GetProgress",cancel:"Cancel",emergency_rollback:"EmergencyRollback",emergencyrollback:"EmergencyRollback"},f=l=>p[l]||p[l.toLowerCase()]||l,c=`Available checkpoints for rollback:
462
+
463
+ `;for(let l of a)if(l.id==="initial")c+=`--- Initial State (id: initial) ---
464
+ Tools Used: User Prompted for task
465
+
466
+ `;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}) ---
467
+ Tools Used: ${d}
468
+
469
+ `}return c.trim()}else if(o==="forceRevert"){if(!s)return"ERROR: Missing required parameter 'id' for forceRevert.";try{let a=await qn.rollbackToCheckpoint(r,s),{checkpointId:p,stats:f}=a,c=f.restored+f.replaced+f.failed.length,l=`SUCCESS: Repository rolled back to checkpoint [${p}].
470
+
471
+ `;return l+=`Stats:
472
+ `,l+=` Restored : ${f.restored} file${f.restored!==1?"s":""} (new to workspace)
473
+ `,l+=` Replaced : ${f.replaced} file${f.replaced!==1?"s":""} (overwritten)
474
+ `,l+=` Failed : ${f.failed.length} file${f.failed.length!==1?"s":""}`,f.failed.length>0&&(l+=`
475
+ ${f.failed.join(`
476
+ `)}`),l+=`
477
+ \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500-
478
+ `,l+=` Total : ${c} file${c!==1?"s":""} processed`,l}catch(a){return`ERROR: ${a.message}`}}else return`ERROR: Invalid method "${o}". Use "getCheckpoint" or "forceRevert".`};var Ds=async(e,n={})=>{let t=L(e),o=t.id,s=parseInt(t.timeout||t.time||"120",10);if((isNaN(s)||s<=0)&&(s=120),s>300&&(s=300),!o)return t.time?(await new Promise(p=>setTimeout(p,s*1e3)),`SUCCESS: Waited for ${s}s.`):'ERROR: Missing "id" argument for Await.';let r=ze.find(p=>p.id===o);if(!r)return`ERROR: Subagent task with ID [${o}] not found.`;if(r.status==="completed")return`SUCCESS: Subagent task [${o}] completed.
479
+ Final Answer:
480
+ ${r.finalAnswer||"(No output)"}`;if(r.status==="failed")return`ERROR: Subagent task [${o}] failed.
481
+ Error: ${r.error||"Unknown error"}`;if(r.status==="cancelled")return`INFO: Subagent task [${o}] was cancelled.`;let i,a=new Promise(p=>{i=setTimeout(()=>{p({type:"timeout"})},s*1e3)});try{let p=await Promise.race([r.completionPromise.then(()=>({type:"completion"})),a]);return clearTimeout(i),p.type==="timeout"?`TIMEOUT: Subagent task [${o}] is still running (status: ${r.status.toUpperCase()}) after ${s}s. You can continue other work or call Await again.`:r.status==="completed"?`SUCCESS: Subagent task [${o}] completed.
482
+ Final Answer:
483
+ ${r.finalAnswer||"(No output)"}`:r.status==="failed"?`ERROR: Subagent task [${o}] failed.
484
+ Error: ${r.error||"Unknown error"}`:r.status==="cancelled"?`INFO: Subagent task [${o}] was cancelled.`:`INFO: Subagent task [${o}] status changed to ${r.status.toUpperCase()}.`}catch(p){return clearTimeout(i),`ERROR: Exception while awaiting subagent [${o}]: ${p.message}`}};var Ps=async(e,n={})=>{let t=L(e),o=t.id,s=t.answer||t.response;if(!o)return'ERROR: Missing "id" argument for Answer.';if(!s)return'ERROR: Missing "answer" argument for Answer.';let r=ze.find(a=>a.id===o);if(!r)return`ERROR: Subagent task with ID [${o}] not found.`;if(!r.questions||r.questions.length===0)return`INFO: Subagent task [${o}] has no pending questions.`;let i=r.questions.filter(a=>!a.answered);return i.length===0?`INFO: Subagent task [${o}] has no unanswered questions.`:(i.forEach(a=>{a.answered=!0,a.answer=s,a.answeredAt=Date.now(),a._resolve&&a._resolve(s)}),r.status="running",n.onSubagentUpdate&&n.onSubagentUpdate(),`SUCCESS: Answer provided to subagent task [${o}]. Subagent execution resumed.`)};var oo=async(e,n={})=>{let t=L(e),o=t.id,s=t.message||t.instruction||t.text||t.prompt;if(!o)return'ERROR: Missing "id" argument for Steer.';if(!s)return'ERROR: Missing "message" argument for Steer.';let r=ze.find(i=>i.id===o);return r?r.status==="completed"||r.status==="failed"||r.status==="cancelled"?`ERROR: Cannot steer subagent task [${o}] because it has already finished with status [${r.status.toUpperCase()}].`:(typeof r.steer=="function"?r.steer(s):(r.pendingSteerMessages||(r.pendingSteerMessages=[]),r.pendingSteerMessages.push(s)),n.onSubagentUpdate&&n.onSubagentUpdate(),`SUCCESS: Steering instruction injected into subagent task [${o}]. It will be processed on the subagent's turn.`):`ERROR: Subagent task with ID [${o}] not found.`};import{mouse as mn,keyboard as vn,Button as ro,Key as U,Point as _o}from"@nut-tree-fork/nut-js";import{screen as ta}from"@nut-tree-fork/nut-js";import Nr from"screenshot-desktop";import ra from"sharp";import na from"fs-extra";import sa from"path";var Ve={TARGET_WIDTH:1280,TARGET_HEIGHT:720,COLS:40,ROWS:30},Oo=[];async function Dl(e){try{let{data:n,info:t}=await ra(e).resize(Ve.TARGET_WIDTH,Ve.TARGET_HEIGHT,{fit:"fill"}).greyscale().raw().toBuffer({resolveWithObject:!0}),o=t.width,s=t.height,r=Ve.COLS,i=Ve.ROWS,a=o/r,p=s/i,f=[],c=1;for(let h=0;h<i;h++)for(let g=0;g<r;g++){let y=Math.floor(g*a),m=Math.floor(h*p),w=Math.floor((g+1)*a),x=Math.floor((h+1)*p),T=Math.floor((x-m)/3),R=0,k=0,S=0,b=0,C=0,A=0;for(let N=m;N<x;N+=2)for(let F=y;F<w;F+=2){let Q=n[N*o+F];N<m+T?(S+=Q,b++):N>x-T?(C+=Q,A++):(R+=Q,k++)}let E=(S+R+C)/(b+k+A),I=0,_=0,v=0;for(let N=m;N<x;N+=2)for(let F=y;F<w;F+=2){let ce=n[N*o+F]-E;N<m+T?_+=ce*ce:N>x-T?v+=ce*ce:I+=ce*ce}let W=Math.sqrt(I/(k||1)),B=Math.sqrt(_/(b||1)),K=Math.sqrt(v/(A||1)),J=Math.sqrt((_+I+v)/(b+k+A||1)),xe=3;B>K+3?xe=10:(K>B+3||W>12)&&(xe=-8),J>18&&f.push({cellNum:c,cx:Math.floor(y+a/2),cy:Math.floor(m+p/2),cellW:a,cellH:p,startX:y,startY:m,yOffset:xe,mean:E,stdDev:J}),c++}let l=Array.from({length:i},()=>Array(r).fill(null));for(let h of f){let g=Math.floor((h.cellNum-1)/r),y=(h.cellNum-1)%r;l[g][y]=h}let u=Array.from({length:i},()=>Array(r).fill(!1)),d=[];for(let h=0;h<i;h++)for(let g=0;g<r;g++)if(l[h][g]&&!u[h][g]){let y=h,m=h,w=g,x=g,T=[[h,g]],R=[l[h][g]],k=Array.from({length:i},()=>Array(r).fill(!1));for(k[h][g]=!0;T.length>0;){let[C,A]=T.shift();y=Math.min(y,C),m=Math.max(m,C),w=Math.min(w,A),x=Math.max(x,A);let E=[[C-1,A],[C+1,A],[C,A-1],[C,A+1],[C-1,A-1],[C-1,A+1],[C+1,A-1],[C+1,A+1]];for(let[I,_]of E)I>=0&&I<i&&_>=0&&_<r&&l[I][_]&&!k[I][_]&&(k[I][_]=!0,T.push([I,_]),R.push(l[I][_]))}let S=m-y+1,b=x-w+1;if(S<=4&&b<=4){for(let B of R){let K=Math.floor((B.cellNum-1)/r),J=(B.cellNum-1)%r;u[K][J]=!0}let C=Math.floor(w*a),A=Math.floor(y*p),E=Math.floor((x+1)*a),I=Math.floor((m+1)*p),_=E-C,v=I-A,W=3;if(v>p){let B=R.filter(N=>N.startY<A+v/2),K=R.filter(N=>N.startY>=A+v/2),J=B.reduce((N,F)=>N+F.stdDev,0)/(B.length||1),xe=K.reduce((N,F)=>N+F.stdDev,0)/(K.length||1);xe>J+2?W=-Math.floor(v/4):J>xe+2?W=Math.floor(v/4):W=-12}else W=(R.find(K=>K.yOffset!==3)||R[0]).yOffset;d.push({cellNum:R[0].cellNum,cx:Math.floor(C+_/2),cy:Math.floor(A+v/2),cellW:_,cellH:v,startX:C,startY:A,yOffset:W})}else{u[h][g]=!0;let C=l[h][g],A=h+1<i?l[h+1][g]:null;if(A&&!u[h+1][g]){u[h+1][g]=!0;let E=Math.floor(g*a),I=Math.floor(h*p),_=Math.floor((g+1)*a),v=Math.floor((h+2)*p),W=_-E,B=v-I,K=Math.floor(p*.25),J=Math.floor(I+p-K),xe=Math.floor(I+p+K),N=0,F=0;for(let Y=J;Y<xe;Y+=2)for(let V=E;V<_;V+=2)N+=n[Y*o+V],F++;let Q=N/(F||1),ce=0;for(let Y=J;Y<xe;Y+=2)for(let V=E;V<_;V+=2){let _e=n[Y*o+V]-Q;ce+=_e*_e}let M=Math.sqrt(ce/(F||1)),P;if(M<14)P=Math.floor(I+p)+4;else{let Y=C.stdDev||0,V=A.stdDev||0;Y<V?P=Math.floor(I+p/2)+(C.yOffset!==3?C.yOffset:-4):P=Math.floor(I+p+p/2)+(A.yOffset!==3?A.yOffset:4)}P=Math.max(I+11,Math.min(I+B-2,P)),d.push({cellNum:C.cellNum,cx:Math.floor(E+W/2),cy:P,cellW:W,cellH:B,startX:E,startY:I,yOffset:0,isCustomY:!0})}else d.push(C)}}return Oo=d,d}catch(n){return console.error("UI Element Detection error:",n),[]}}function Pl(e,n,t,o,s=[]){let r=e/t,i=n/o,a="";for(let p of s){let{cellNum:f,startX:c,startY:l,cellW:u,cellH:d,cx:h,cy:g}=p;a+=`
485
+ <rect x="${c+1}" y="${l+1}" width="${u-2}" height="${d-2}" fill="rgba(0, 255, 255, 0.015)" stroke="rgba(255, 255, 0, 0.3)" stroke-width="1.1" rx="2"/>
486
+ `;let y;if(p.isCustomY)y=g;else{let m=g+(p.yOffset!==void 0?p.yOffset:3);y=Math.max(l+11,Math.min(l+d+3,m))}a+=`
487
+ <text x="${h}" y="${y}" font-family="'Segoe UI', Roboto, sans-serif" font-size="14" font-weight="600" fill="#FFFF00" stroke="#000000" stroke-width="2" paint-order="stroke fill" stroke-linejoin="round" opacity="0.8" text-anchor="middle">${f}</text>
488
+ `}return`<svg width="${e}" height="${n}" xmlns="http://www.w3.org/2000/svg">${a}</svg>`}var oa=1,Dr=e=>new Promise(n=>setTimeout(n,e));async function Fl(){let e=0;for(;e<2;){let n=await Nr({format:"png"});await Dr(500);let t=await Nr({format:"png"});if(n.equals(t))return t;e++,e<2&&await Dr(3e3)}return await Dr(3e3),await Nr({format:"png"})}async function ia(){try{let e=await Fl(),n=await Dl(e),t=Pl(Ve.TARGET_WIDTH,Ve.TARGET_HEIGHT,Ve.COLS,Ve.ROWS,n),o=await ra(e).resize(Ve.TARGET_WIDTH,Ve.TARGET_HEIGHT,{fit:"fill"}).composite([{input:Buffer.from(t),top:0,left:0}]).png({quality:100}).toBuffer();if(process.env.SHOW_DEBUG_GRID)try{let p=sa.resolve(process.cwd(),"screenshots");await na.ensureDir(p);let f=sa.join(p,`${oa}.png`);await na.writeFile(f,o),oa++}catch{}let s=o.toString("base64"),r=n.length,i=e,a=o;return i=null,a=null,{base64:s,mimeType:"image/png",width:Ve.TARGET_WIDTH,height:Ve.TARGET_HEIGHT,detectedCount:r}}catch(e){return console.error("Failed to capture gridded screenshot:",e),null}}function Pr(e){if(e==null)return null;let n=null;if(typeof e=="number")n=e;else if(typeof e=="string"){let c=e.trim();if(/^\d+$/.test(c))n=parseInt(c,10);else{let l=c.match(/^([A-Z])([0-9]{1,2})$/i);if(l){let u=l[1].toUpperCase().charCodeAt(0)-65,d=parseInt(l[2],10)-1;n=u*Ve.COLS+d+1}}}if(n===null||isNaN(n))return null;if(Oo&&Oo.length>0){let c=Oo.find(l=>l.cellNum===n);if(c)return{x:c.cx,y:c.cy,colIdx:Math.floor((n-1)%Ve.COLS),rowIdx:Math.floor((n-1)/Ve.COLS),cellNum:n}}let t=Ve.COLS*Ve.ROWS;if(n<1||n>t)return null;let o=n-1,s=Math.floor(o/Ve.COLS),r=o%Ve.COLS,i=Ve.TARGET_WIDTH/Ve.COLS,a=Ve.TARGET_HEIGHT/Ve.ROWS,p=Math.floor(r*i+i/2),f=Math.floor(s*a+a/2);return{x:p,y:f,colIdx:r,rowIdx:s,cellNum:n}}async function Fs(e,n,t){let o=null;if(typeof e=="number"||typeof e=="string"?o=Pr(e):e&&typeof e.x=="number"&&typeof e.y=="number"&&(o=e),!o)return null;let s=n,r=t;if(!s||!r)try{s=await ta.width(),r=await ta.height()}catch{s=1920,r=1080}let i=s/Ve.TARGET_WIDTH,a=r/Ve.TARGET_HEIGHT,p=Math.round(o.x*i),f=Math.round(o.y*a);return{x:Math.max(0,Math.min(s-1,p)),y:Math.max(0,Math.min(r-1,f)),screenW:s,screenH:r}}mn.config.autoDelayMs=50;vn.config.autoDelayMs=50;async function gn(e,n,t={}){let o=await Fs(n);if(!o&&(e==="move"||e==="click"||e==="drag"))return`ERROR: Invalid target location specified: ${JSON.stringify(n)}`;try{switch(e.toLowerCase()){case"move":return await mn.setPosition(new _o(o.x,o.y)),`SUCCESS: Moved mouse to grid target ${typeof n=="string"?n:`(${o.x}, ${o.y})`}`;case"click":{await mn.setPosition(new _o(o.x,o.y));let s=t.button==="right"?ro.RIGHT:t.button==="middle"?ro.MIDDLE:ro.LEFT;return t.clickType==="double"?await mn.doubleClick(s):await mn.click(s),`SUCCESS: ${t.clickType||"Single"} clicked ${t.button||"left"} button at ${typeof n=="string"?n:`(${o.x}, ${o.y})`}`}case"drag":{let s=await Fs(t.from||n),r=await Fs(t.to);return!s||!r?'ERROR: Drag requires valid "from" and "to" target coordinates/grid codes.':(await mn.setPosition(new _o(s.x,s.y)),await mn.pressButton(ro.LEFT),await mn.setPosition(new _o(r.x,r.y)),await mn.releaseButton(ro.LEFT),`SUCCESS: Dragged mouse from (${s.x}, ${s.y}) to (${r.x}, ${r.y})`)}case"scroll":{let s=t.amount||100;return t.direction==="up"?await mn.scrollUp(s):await mn.scrollDown(s),`SUCCESS: Scrolled ${t.direction||"down"} by ${s}px`}default:return`ERROR: Unsupported mouse action "${e}"`}}catch(s){return`ERROR: Mouse action failed: ${s.message}`}}var aa={enter:U.Enter,return:U.Return,escape:U.Escape,esc:U.Escape,backspace:U.Backspace,tab:U.Tab,space:U.Space,up:U.Up,down:U.Down,left:U.Left,right:U.Right,ctrl:U.LeftControl,control:U.LeftControl,alt:U.LeftAlt,shift:U.LeftShift,cmd:U.LeftCmd,win:U.LeftWin,meta:U.LeftWin,super:U.LeftSuper,a:U.A,b:U.B,c:U.C,d:U.D,e:U.E,f:U.F,g:U.G,h:U.H,i:U.I,j:U.J,k:U.K,l:U.L,m:U.M,n:U.N,o:U.O,p:U.P,q:U.Q,r:U.R,s:U.S,t:U.T,u:U.U,v:U.V,w:U.W,x:U.X,y:U.Y,z:U.Z,0:U.Num0,1:U.Num1,2:U.Num2,3:U.Num3,4:U.Num4,5:U.Num5,6:U.Num6,7:U.Num7,8:U.Num8,9:U.Num9,f1:U.F1,f2:U.F2,f3:U.F3,f4:U.F4,f5:U.F5,f6:U.F6,f7:U.F7,f8:U.F8,f9:U.F9,f10:U.F10,f11:U.F11,f12:U.F12},la=e=>{if(!e)return;let n=String(e).toLowerCase().trim();if(aa[n]!==void 0)return aa[n];if(U[e]!==void 0)return U[e];if(U[n.toUpperCase()]!==void 0)return U[n.toUpperCase()]};async function zn(e,n,t={}){try{switch(e.toLowerCase()){case"type":return typeof n!="string"?"ERROR: Type action requires a valid string input":(await vn.type(n),t.autoPressEnter?(await vn.type(U.Enter),`SUCCESS: Typed text input ("${n.length>20?n.substring(0,20)+"...":n}") and pressed Enter`):`SUCCESS: Typed text input ("${n.length>20?n.substring(0,20)+"...":n}")`);case"key_press":{let o=la(n);return o===void 0?`ERROR: Unknown key name "${n}"`:(await vn.type(o),`SUCCESS: Pressed key ${n}`)}case"key_combination":{if(!Array.isArray(n))return'ERROR: key_combination requires an array of keys (e.g. ["ctrl", "c"])';let o=n.map(s=>la(s)).filter(s=>s!==void 0);return o.length===0?"ERROR: Invalid key combination":(await vn.pressKey(...o),await vn.releaseKey(...o),`SUCCESS: Executed key combination [${n.join(" + ")}]`)}case"clear_input":return await vn.pressKey(U.LeftControl,U.A),await vn.releaseKey(U.LeftControl,U.A),await vn.type(U.Backspace),"SUCCESS: Cleared active text input (Select All + Backspace)";default:return`ERROR: Unsupported keyboard action "${e}"`}}catch(o){return`ERROR: Keyboard action failed: ${o.message}`}}var io=async(e,n={})=>{let t=L(e),o=t.action||t.type||t.cmd,s=t.target||t.grid||t.gridCode||t.location||t.input;if(!o)return'ERROR: Missing required "action" argument for computer_action (e.g. move, click, drag, scroll, type, key_press, key_combination).';let r=o.toLowerCase();if(r.startsWith("mouse_")||["move","click","drag","scroll"].includes(r)){let i=r.replace("mouse_","");return await gn(i,s,{button:t.button,clickType:t.clickType||t.type,from:t.from,to:t.to,direction:t.direction,amount:t.amount?parseInt(t.amount,10):void 0})}if(r.startsWith("key_")||r==="type"||r==="press"){let i=r;r==="press"&&(i="key_press");let a=t.autoPressEnter===!0||t.autoPressEnter==="true"||t.enter===!0||t.enter==="true";return await zn(i,s||t.text||t.keys,{...t,autoPressEnter:a})}return`ERROR: Unrecognized action "${o}". Supported actions: move, click, drag, scroll, type, key_press, key_combination.`};import Ul from"screenshot-desktop";import Bl from"sharp";var Fr=async(e,n={})=>{let t=L(e),o=t.gridId||t.grid||t.coordinate||t.target||t.id,s=(t.type||t.clickType||"single").toLowerCase(),r=(t.button||"left").toLowerCase(),i=t.intendedClickText||t.text||"";if(!o&&!i)return'ERROR: Missing required "gridId" parameter for Click tool.';let a=o;if(i)try{let{createWorker:f}=await import("tesseract.js"),c=o?Pr(o):null,l=await Ul({format:"png"}),u=await Bl(l).metadata(),d=u.width||1920,h=u.height||1080,g=c?await Fs(c,d,h):{x:d/2,y:h/2},y=await import("fs-extra"),{CU_CACHE_DIR:m}=await import("./paths-R3DD7CRF.js");y.ensureDirSync(m);let w=await f("eng",1,{cachePath:m}),{data:x}=await w.recognize(l);if(await w.terminate(),x&&x.text){let T=i.toLowerCase().trim(),R=[];if(x.lines&&x.lines.length>0)for(let k of x.lines)k.text&&k.text.toLowerCase().includes(T)&&k.bbox&&R.push(k.bbox);if(R.length===0&&x.words&&x.words.length>0)for(let k of x.words){let S=k.text?k.text.toLowerCase():"";S&&(S.includes(T)||T.includes(S))&&k.bbox&&R.push(k.bbox)}if(R.length>0){let k=null,S=1/0;for(let b of R){let C=Math.round((b.x0+b.x1)/2),A=Math.round((b.y0+b.y1)/2),E=Math.hypot(C-g.x,A-g.y);E<S&&(S=E,k={x:C,y:A})}if(k){let b=await gn("click",{x:Math.round(k.x*(1280/d)),y:Math.round(k.y*(720/h))},{button:r,clickType:s});try{await gn("move",{x:640,y:360})}catch{}return`${b} (Full-screen OCR nearest match for "${i}" at ${Math.round(S)}px distance)`}}}}catch{}let p=await gn("click",a,{button:r,clickType:s});try{await gn("move",{x:640,y:360})}catch{}return p};var Ur=async(e,n={})=>{let t=L(e),o=t.fromGridId||t.from||t.start,s=t.toGridId||t.to||t.end;return!o||!s?'ERROR: Drag requires both "fromGridId" and "toGridId" parameters.':await gn("drag",o,{from:o,to:s})};var Br=async(e,n={})=>{let t=L(e),o=(t.direction||"down").toLowerCase(),s=t.amount?parseInt(t.amount,10):100;return await gn("scroll",null,{direction:o,amount:s})};var Io=async(e,n={})=>{let t=L(e),o=t.text||t.input||t.value||"",s=t.autoPressEnter===!0||t.autoPressEnter==="true"||t.enter===!0||t.enter==="true";return o==null?'ERROR: Missing required "text" parameter for KeyboardTyping tool.':await zn("type",String(o),{autoPressEnter:s})};var Lo=async(e,n={})=>{let t=L(e),o=t.key||t.keys||t.input||t.shortcut;if(!o)return'ERROR: Missing required "key" parameter for KeyPress tool.';let s=String(o).trim().toLowerCase();if(s==="clearinput"||s==="clear_input"||s==="clear")return await zn("clear_input");if(s.includes(";")||s.includes("+")){let r=s.split(/[;+]/).map(i=>i.trim()).filter(Boolean);return await zn("key_combination",r)}return await zn("key_press",s)};var vo=async(e,n={})=>"SUCCESS: Screen recapture requested. The latest gridded screenshot is provided for your next decision.";var Wl={web_search:lr,web_scrape:cr,memory:fr,chat:dr,view_file:Zs,write_file:ur,update_file:yr,exec_command:tr,read_folder:Sr,write_pdf:xr,write_docx:br,search_keyword:to,generate_image:Ar,saveSummary:no,addMemScore:Ns,file_map:Or,todo:Ji,invokeSync:_r,invoke:Qi,getProgress:Ir,cancel:Zi,awaitSubagent:Ds,answerSubagent:Ps,steerSubagent:oo,computer_action:io,computer_use:io,ComputerAction:io,ComputerUse:io,click:Fr,Click:Fr,drag:Ur,Drag:Ur,scroll:Br,Scroll:Br,keyboard_typing:Io,KeyboardTyping:Io,keyboardtyping:Io,key_press:Lo,KeyPress:Lo,keypress:Lo,recapture_screen:vo,RecaptureScreen:vo,recapturescreen:vo,invoke_sync:_r,get_progress:Ir,await_subagent:Ds,answer_subagent:Ps,steer_subagent:oo,steer:oo,Steer:oo,ask:Tr,Ask:Tr,WebSearch:lr,WebScrape:cr,ReadFile:Zs,ReadFolder:Sr,WriteFile:ur,PatchFile:yr,WritePDF:xr,WriteDoc:br,Run:tr,SearchKeyword:to,CodeSearch:to,code_search:to,Memory:fr,Chat:dr,GenerateImage:Ar,saveSumary:no,SaveSummary:no,SaveSumary:no,add_mem_score:Ns,AddMemScore:Ns,addMemoryScore:Ns,AddMemoryScore:Ns,FileMap:Or,answer:Ps,Answer:Ps,AnswerSubagent:Ps,await:Ds,Await:Ds,AwaitSubagent:Ds,EmergencyRollback:vr,emergency_rollback:vr},ao=async(e,n,t={})=>{let o=t.mode?t.mode.toLowerCase():"flux",s=e.toLowerCase(),i=["memory","chat","savesummary","addmemscore","add_mem_score","ask","web_search","web_scrape","await"].some(c=>s.includes(c))||s==="ask",p=["click","drag","scroll","keyboardtyping","keyboard_typing","keypress","key_press","recapturescreen","recapture_screen","computer"].some(c=>s.includes(c));if(!i){if(o==="flow"){if(!(s.includes("write_pdf")||s.includes("write_docx")||s.includes("generate_image")))return`ERROR: Tool [${e}] is a Workspace Tool and NOT available in Flow mode. Tell user to switch (\`/mode flux\`) to use this tool.`}else if(o==="icu"){if(!p)return`ERROR: Tool [${e}] is not available in Computer Use mode. ICU mode only supports Computer Use tools (Click, Drag, Scroll, KeyboardTyping, KeyPress, RecaptureScreen).`}else if(s.includes("write_pdf")||s.includes("write_docx")||s.includes("generate_image"))return`ERROR: Tool [${e}] is not available in ${t.mode||"Flux"} mode. Tell user to switch (\`/mode flow\`) for document generation.`}let f=Wl[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 ee from"path";import Le from"fs";import Hl from"gradient-string";var Wr=["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 ca=[{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"]}],lo={Dark:{id:"Dark",name:"Dark (Default)",text:"white",textMuted:"gray",textDim:"grey",textInverted:"black",textExclusive:"#B5B8D9",textMutedExclusive:"#D4DEE7",border:"white",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:"#1e1e1e",highlightBg:"#2a2a2a",activeBg:"#3a3a3a",inputBg:"#555555",inputBorder:"#555555",inputText:"white",inputPlaceholder:"#cccccc",inputPrompt:"white",codeBg:"#1a1a1a",codeBorder:"#444444",userMsgBg:"#444444",userMsgBorder:"#444444",userMsgText:"white",diffRemovalBg:"#250808",diffAdditionBg:"#072410",diffRemovalText:"#885555",diffAdditionText:"#558866",diffRemovalHighlightColor:"#ff3333",diffRemovalHighlightBg:"#5a1818",diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:"#185a25",diffRemovalNum:"#d96868",diffAdditionNum:"#68d98c",diffRemovalPrefix:"#ff4d4d",diffAdditionPrefix:"#4dff88",primary:"white",secondary:"cyan",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"white",statusOff:"gray",logoTextAnsi:"\x1B[1;37m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#0077ff","#ff00ff"]},Light:{id:"Light",name:"Light",text:"black",textMuted:"gray",textDim:"grey",textInverted:"white",border:"black",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:"#e5e5e5",highlightBg:"#d4d4d4",activeBg:"#c0c0c0",inputBg:"#d0d0d0",inputBorder:"#d0d0d0",inputText:"black",inputPlaceholder:"#555555",inputPrompt:"black",codeBg:"#e8e8e8",codeBorder:"#b0b0b0",userMsgBg:"#d0d0d0",userMsgBorder:"#d0d0d0",userMsgText:"black",diffRemovalBg:"#fce8e8",diffAdditionBg:"#e6f9e6",diffRemovalText:"#661111",diffAdditionText:"#115511",diffRemovalHighlightColor:"#440000",diffRemovalHighlightBg:"#f8b4b4",diffAdditionHighlightColor:"#003300",diffAdditionHighlightBg:"#a6ebad",diffRemovalNum:"#c02020",diffAdditionNum:"#188028",diffRemovalPrefix:"#d01010",diffAdditionPrefix:"#109020",primary:"black",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"black",statusOff:"gray",logoTextAnsi:"\x1B[1;30m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#0077ff","#ff00ff"]},"GitHub Dark":{id:"GitHub Dark",name:"GitHub Dark",text:"#c9d1d9",textMuted:"#8b949e",textDim:"#6e7681",textInverted:"#0d1117",border:"#30363d",borderMuted:"#30363d",borderDim:"#21262d",bg:void 0,cardBg:"#161b22",highlightBg:"#21262d",activeBg:"#30363d",inputBg:"#21262d",inputBorder:"#21262d",inputText:"#c9d1d9",inputPlaceholder:"#8b949e",inputPrompt:"#58a6ff",codeBg:"#0d1117",codeBorder:"#30363d",userMsgBg:"#21262d",userMsgBorder:"#21262d",userMsgText:"#c9d1d9",diffRemovalBg:"#3c1e1e",diffAdditionBg:"#11381e",diffRemovalText:"#f85149",diffAdditionText:"#3fb950",diffRemovalHighlightColor:"#ff7b72",diffRemovalHighlightBg:"#701c1c",diffAdditionHighlightColor:"#56d364",diffAdditionHighlightBg:"#116329",diffRemovalNum:"#f85149",diffAdditionNum:"#3fb950",diffRemovalPrefix:"#f85149",diffAdditionPrefix:"#3fb950",primary:"#c9d1d9",secondary:"#58a6ff",accent:"#bc8cff",success:"#3fb950",warning:"#d29922",danger:"#f85149",info:"#58a6ff",statusOn:"#58a6ff",statusOff:"#8b949e",logoTextAnsi:"\x1B[1;36m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#2ea043","#56d364"]},"GitHub Light":{id:"GitHub Light",name:"GitHub Light",text:"#24292f",textMuted:"#57606a",textDim:"#6e7781",textInverted:"#ffffff",border:"#d0d7de",borderMuted:"#d0d7de",borderDim:"#e1e4e8",bg:void 0,cardBg:"#f6f8fa",highlightBg:"#eaeef2",activeBg:"#d0d7de",inputBg:"#eaeef2",inputBorder:"#eaeef2",inputText:"#24292f",inputPlaceholder:"#57606a",inputPrompt:"#0969da",codeBg:"#ffffff",codeBorder:"#d0d7de",userMsgBg:"#eaeef2",userMsgBorder:"#eaeef2",userMsgText:"#24292f",diffRemovalBg:"#ffebe9",diffAdditionBg:"#e6ffec",diffRemovalText:"#cf222e",diffAdditionText:"#1a7f37",diffRemovalHighlightColor:"#82071e",diffRemovalHighlightBg:"#ffc1c0",diffAdditionHighlightColor:"#116329",diffAdditionHighlightBg:"#acf2bd",diffRemovalNum:"#cf222e",diffAdditionNum:"#1a7f37",diffRemovalPrefix:"#cf222e",diffAdditionPrefix:"#1a7f37",primary:"#24292f",secondary:"#0969da",accent:"#8250df",success:"#1a7f37",warning:"#9a6700",danger:"#cf222e",info:"#0969da",statusOn:"#0969da",statusOff:"#57606a",logoTextAnsi:"\x1B[1;34m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#1a7f37","#2da44e"]},"Transparent Dark":{id:"Transparent Dark",name:"Transparent Dark",text:"white",textMuted:"gray",textDim:"grey",textInverted:"black",border:"gray",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:void 0,highlightBg:"#2a2a2a",activeBg:"#3a3a3a",inputBg:"#555555",inputBorder:"#555555",inputText:"white",inputPlaceholder:"#cccccc",inputPrompt:"white",codeBg:void 0,codeBorder:"gray",userMsgBg:"#555555",userMsgBorder:"#555555",userMsgText:"white",diffRemovalBg:void 0,diffAdditionBg:void 0,diffRemovalText:"#ff6666",diffAdditionText:"#66ff66",diffRemovalHighlightColor:"#ff3333",diffRemovalHighlightBg:void 0,diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:void 0,diffRemovalNum:"#ff6666",diffAdditionNum:"#66ff66",diffRemovalPrefix:"#ff4d4d",diffAdditionPrefix:"#4dff88",primary:"white",secondary:"cyan",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"white",statusOff:"gray",logoTextAnsi:"\x1B[1;37m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#0077ff","#ff00ff"]},"Transparent Light":{id:"Transparent Light",name:"Transparent Light",text:"black",textMuted:"gray",textDim:"grey",textInverted:"white",border:"gray",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:void 0,highlightBg:"#d4d4d4",activeBg:"#c0c0c0",inputBg:"#d0d0d0",inputBorder:"#d0d0d0",inputText:"black",inputPlaceholder:"#555555",inputPrompt:"black",codeBg:void 0,codeBorder:"gray",userMsgBg:"#d0d0d0",userMsgBorder:"#d0d0d0",userMsgText:"black",diffRemovalBg:void 0,diffAdditionBg:void 0,diffRemovalText:"#c02020",diffAdditionText:"#188028",diffRemovalHighlightColor:"#800000",diffRemovalHighlightBg:void 0,diffAdditionHighlightColor:"#004000",diffAdditionHighlightBg:void 0,diffRemovalNum:"#c02020",diffAdditionNum:"#188028",diffRemovalPrefix:"#d01010",diffAdditionPrefix:"#109020",primary:"black",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"black",statusOff:"gray",logoTextAnsi:"\x1B[1;30m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#0077ff","#ff00ff"]},"Synthwave 84":{id:"Synthwave 84",name:"Synthwave 84",text:"#fdfdfd",textMuted:"#a08eb7",textDim:"#705c8a",textInverted:"#1a1025",textExclusive:"#e3dcf0",textMutedExclusive:"#b9abc9",border:"#fc28a8",borderMuted:"#a21568",borderDim:"#5c0a3a",bg:void 0,cardBg:"#261b38",highlightBg:"#35254d",activeBg:"#4c3570",inputBg:"#35254d",inputBorder:"#35254d",inputText:"#fdfdfd",inputPlaceholder:"#a08eb7",inputPrompt:"#03e8fc",codeBg:"#1e142b",codeBorder:"#a21568",userMsgBg:"#35254d",userMsgBorder:"#35254d",userMsgText:"#fdfdfd",diffRemovalBg:"#471434",diffAdditionBg:"#144743",diffRemovalText:"#ff4081",diffAdditionText:"#00e5ff",diffRemovalHighlightColor:"#ff79a1",diffRemovalHighlightBg:"#6b1e4e",diffAdditionHighlightColor:"#66f5ff",diffAdditionHighlightBg:"#1e6b65",diffRemovalNum:"#ff4081",diffAdditionNum:"#00e5ff",diffRemovalPrefix:"#ff79a1",diffAdditionPrefix:"#66f5ff",primary:"#fdfdfd",secondary:"#03e8fc",accent:"#fc28a8",success:"#00e5ff",warning:"#ffc107",danger:"#ff4081",info:"#b388ff",statusOn:"#03e8fc",statusOff:"#a08eb7",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#fc28a8","#03e8fc"]},"Forest Sprite":{id:"Forest Sprite",name:"Forest Sprite",text:"#d6e6d1",textMuted:"#95b38d",textDim:"#628059",textInverted:"#161c14",textExclusive:"#eaf2e8",textMutedExclusive:"#a9c7a2",border:"#74a862",borderMuted:"#477038",borderDim:"#2b4720",bg:void 0,cardBg:"#1f291c",highlightBg:"#2a3826",activeBg:"#3a4d35",inputBg:"#2a3826",inputBorder:"#2a3826",inputText:"#d6e6d1",inputPlaceholder:"#95b38d",inputPrompt:"#8feb73",codeBg:"#161e14",codeBorder:"#477038",userMsgBg:"#2a3826",userMsgBorder:"#2a3826",userMsgText:"#d6e6d1",diffRemovalBg:"#3b231c",diffAdditionBg:"#203b1c",diffRemovalText:"#db6242",diffAdditionText:"#59cc3f",diffRemovalHighlightColor:"#f0896c",diffRemovalHighlightBg:"#5c362a",diffAdditionHighlightColor:"#80e368",diffAdditionHighlightBg:"#305929",diffRemovalNum:"#db6242",diffAdditionNum:"#59cc3f",diffRemovalPrefix:"#f0896c",diffAdditionPrefix:"#80e368",primary:"#d6e6d1",secondary:"#8feb73",accent:"#e69835",success:"#59cc3f",warning:"#e69835",danger:"#db6242",info:"#73b4eb",statusOn:"#8feb73",statusOff:"#95b38d",logoTextAnsi:"\x1B[1;32m",logoBodyAnsi:"\x1B[32m",logoMutedAnsi:"\x1B[90m",logoGradient:["#8feb73","#e69835"]}};var No=null;var fa=(e="Dark")=>{let n;e==="Mystery"||e==="Chaos"?(No||(No=ca[Math.floor(Math.random()*ca.length)]),n={...No,id:"Mystery"}):(No=null,lo[e]?n=lo[e]:e==="GitHub"?n=lo["GitHub Dark"]:e==="Transparent"?n=lo["Transparent Dark"]:n=lo.Dark);let t=n.codeText||n.secondary||n.info||n.logoGradient&&n.logoGradient[0]||"cyan";return{...n,codeText:t}};var Gl=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",yp=(e=2)=>{let n=Gl();return n==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)},wp=(e="...",n="Loading...",t="Dark")=>{let o=Wr[Math.floor(Math.random()*Wr.length)],s=fa(t),r=s.logoTextAnsi,i=s.logoBodyAnsi,a=s.logoMutedAnsi,p="\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=s.logoGradient||["#0077ff","#ff00ff"],l=Hl(c).multiline(f.join(`
489
+ `)).split(`
490
+ `),u=d=>`${a}${d}${p}`;return`${l[0]}
491
+ ${l[1]} ${r}Selected Provider: ${n}${p}
492
+ ${l[2]}
493
+ ${l[3]} ${r}FluxFlow ${u("v"+e)}${p}
494
+ ${l[4]}
495
+ ${l[5]} ${i}See /help for additional commands.${p}
496
+ ${l[6]} ${u(o)}
497
+ ${l[7]}`};import{WebSocket as Do}from"ws";var Yt=null,Us=!1,jl="ws://localhost:56832",Hr=[],Bs=null,Gr=null,da="2.0.0",xp=e=>{da=e,ua()},jr=e=>{Gr=e},ua=()=>{if(Yt||Us)return;Us=!0;let e=new Do(jl);e.on("open",()=>{for(Yt=e,Us=!1,Yt.send(JSON.stringify({command:"version",version:da,pid:process.pid,ppid:process.ppid}));Hr.length>0;)Yt.send(JSON.stringify(Hr.shift()))}),e.on("message",n=>{try{let t=JSON.parse(n.toString());t.command==="contextResponse"&&Bs?(Bs(t.data),Bs=null):t.command==="securityResponse"&&Gr&&Gr(t.result)}catch{}}),e.on("error",()=>{Us=!1,Yt=null}),e.on("close",()=>{Us=!1,Yt=null})},Po=e=>{Yt&&Yt.readyState===Do.OPEN?Yt.send(JSON.stringify(e)):(Hr.push(e),Us||ua())},Fo=()=>Yt!==null&&Yt.readyState===Do.OPEN,Ep=e=>{Po({command:"status",status:e})},ys=()=>new Promise(e=>{if(!Yt||Yt.readyState!==Do.OPEN){e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]});return}Bs=e,Yt.send(JSON.stringify({command:"requestContext"})),setTimeout(()=>{Bs===e&&(e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]}),Bs=null)},1e3)}),ha=e=>{Po({command:"open",filePath:e})},Yr=(e,n,t)=>{Po({command:"showDiff",filePath:e,originalContent:n,modifiedContent:t})},pa=(e,n)=>{Po({command:"closeDiff",filePath:e,result:n})};import ma from"path";import Yl from"fs";var Kl=e=>{try{return Yl.readdirSync(e,{withFileTypes:!0})}catch{return[]}},Kr=(e,n,t=1,o=Kl,s=[],r=null)=>{let i=r||o(e),a=" ".repeat(t-1);if(i.length>100)return`${a}${ma.basename(e)}/ (>100 files)
498
+ `;let p="",f=s,c=i.filter(h=>!f.includes(h.name)&&!h.name.startsWith(".")),l=i.filter(h=>f.includes(h.name)||h.name.startsWith(".")).map(h=>h.name).sort();l.length>0&&(p+=`${a}[ignored: ${l.map(h=>h+"/").join(", ")}]
499
+ `);let u=c.filter(h=>h.isDirectory()).sort((h,g)=>h.name.localeCompare(g.name)),d=c.filter(h=>!h.isDirectory()).map(h=>h.name).sort();for(let h of u){let g=ma.join(e,h.name);if(t>n)p+=`${a}${h.name}/ (max depth)
500
+ `;else{let y=o(g);y.length>80?p+=`${a}${h.name}/ (>80 files)
501
+ `:(p+=`${a}${h.name}/
502
+ `,p+=Kr(g,n,t+1,o,s,y))}}return d.length>0&&(p+=`${a}${d.join("; ")}
503
+ `),p};import qr from"path";import ql from"fs";var zl=e=>{try{return ql.readdirSync(e,{withFileTypes:!0})}catch{return[]}},zr=(e,n,t="",o=1,s=zl,r=[])=>{let i=s(e),a=qr.sep;if(i.length>100)return`${t}\u2514\u2500\u2500 ${qr.basename(e)}${a} ...100+ files...
504
+ `;let p="",f=r,c=i.filter(d=>!f.includes(d.name)&&!d.name.startsWith(".")),l=i.filter(d=>f.includes(d.name)||d.name.startsWith(".")).map(d=>d.name).sort();c.sort((d,h)=>d.isDirectory()&&!h.isDirectory()?-1:!d.isDirectory()&&h.isDirectory()?1:d.name.localeCompare(h.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,h)=>{let g=h===u.length-1,y=qr.join(e,d.name),m=g?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",w=t+(g?" ":"\u2502 ");if(d.isCollapsed){p+=`${t}${m}${d.name}${a}...
505
+ `;return}d.isDir?o>n?p+=`${t}${m}${d.name}${a} ...depth exceeded...
506
+ `:s(y).length>80?p+=`${t}${m}${d.name}${a} ...80+ files...
507
+ `:(p+=`${t}${m}${d.name}${a}
508
+ `,p+=zr(y,n,w,o+1,s,r)):p+=`${t}${m}${d.name}
509
+ `}),p};import"@google/genai";Vl.config({quiet:!0});var Jl=/```[\s\S]*?```/g,Ql=/```[\s\S]*$/g,Zl=/`[^`]+`/g,ec=/^\|.*\|$/gm,tc=/^[^\w]+|[^\w]+$/g,nc=/[^a-z0-9]/gi,co=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,sc=/\[\s*(?:tool:functions\.|agent:generalist\.)([a-z0-9_]+)\s*\(/gi,oc=/(?:path|targetFile|TargetFile|directory|keyword|id|taskId|title|task)\s*=\s*\\?["']?([^\\"' \),]+)/,ws=/["']/g,ga=/\\/g,rc=/<\|channel>thought/gi,ic=/<channel\|>/gi,Dn=e=>typeof e!="string"?e:e.replace(rc,"<think>").replace(ic,"</think>"),ac=/(?:<(think|thought|thoughts)>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\])/gi,lc=/(?:<(think|thought|thoughts)>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*$/gi,ya=/(?:<think>|<\|channel>thought|\[think\])[\s\S]*?(?:<\/think>|<channel\|>|\[\/think\]|$)/gi,wa=/(?:<(think|thought|thoughts)>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\]|$)/gi,Ca=/`[^`]*`/g,Aa=/`[^`]*$/,Sa=/<\|\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,Ta=/<\|\s*tool_calls_section_begin\s*\|>/gi,xa=/<\|\s*tool_calls_section_end\s*\|>/gi,fc=/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi,Ea=/<(\w+)(?:[^>]*)>\r?\n?/gi,ba=/\r?\n?<\/\w+(?:[^>]*)>/gi,Xr=null,Uo={},Ss={key:null,value:null},yn=e=>e&&e.replace(/(?:(\x1b\[\d+m))?([✔✘✖🔍📖→➕↻↷•🛇])(?:(\x1b\[\d+m))?\s*\b(Clicked|Dragged|Scrolled|Typed|Pressed Key|Recaptured Screen|Created|Read|Edited|Viewed|Processed|Auto-Read|Skipped|List|Generated|Written|Searched|AI Search|Get Map|Write Canceled|Resolved Sub-Agent Query|Edit Canceled|Write Cancelled|Edit Denied|Visited|Updated|Reviewed|Delegated|Background|Checked|Indexed|Analyzed|Browsed|Elevating SubAgent|Checking SubAgent Work|Started Generalist|Called Generalist|Steered|Unsupported Modality|Awaiting|Cancelled|Aligning Moon Phase|Contemplating Existence|Staring At Void|Rollback Point Checked|Emergency Rollback Failed|Emergency Rollback|Delaying Professionally|Negotiating With Electrons|Touching Grass (virtually)|Panicking Softly|Rethinking Career Choices|Loading Cat Videos|Giving Up Entirely|Summoning Braincell #2|Pretending To Be Busy|Waiting For Motivation DLC|Rotating Internal Screaming|Downloading More RAM|Feeding The Hamsters|Gaslighting Scheduler|Performing Dramatic Pause|Buffering Social Energy|Calculating Regret|Reading Terms And Conditions|Becoming Sentient Briefly|Contacting Ancestors)\b/ig,(n,t,o,s,r)=>`${t||""}${o}${s||""} \x1B[95m${r}\x1B[0m`),dc=async(e,n=8,t=1e3,o=8e3,s=null)=>{let r=0;for(;;){if(s?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{return await e()}catch(i){if(s?.aborted||i?.name==="AbortError"||i?.message==="Subagent task was cancelled."||(r++,r>=n))throw i;let a=Math.min(t*Math.pow(2,r-1),o);await new Promise((p,f)=>{let c=setTimeout(p,a);s&&s.addEventListener("abort",()=>{clearTimeout(c),f(new DOMException("The user aborted a request.","AbortError"))})})}}},vt=!1;var uc=e=>{let n=e.filter(s=>(s.role==="user"||s.role==="agent"||s.role==="system")&&s.role!=="think"&&!s.isVisualFeedback&&!s.isMeta&&!s.isTerminalRecord&&!(s.text&&s.text.includes("[TERMINAL_RECORD]"))&&!String(s.id).startsWith("welcome")).map((s,r,i)=>{let a=s.fullText||s.text||"";if(s.role==="user"&&r<i.length-1)if(a.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")){let p=a.indexOf("**CONTEXT SUMMARY OF PREVIOUS TURNS");if(p!==-1){let c=a.substring(0,p).lastIndexOf("[SYSTEM METADATA]");c!==-1?a=a.substring(c).trim():a=a.substring(p).trim()}}else{let p=a.lastIndexOf("[USER]"),f=a.lastIndexOf("[USER PROMPT]");p!==-1?a=a.substring(p+6).trim():f!==-1&&(a=a.substring(f).trim())}return{...s,text:a}}),t=[],o=0;for(;o<n.length;){let s=n[o];if(s.role==="user")t.push(s),o++;else{let r=[];for(;o<n.length&&n[o].role!=="user";)r.push(n[o]),o++;let i=[],a=[],p=[];r.forEach(f=>{let c=(f.text||"").toLowerCase(),l=c.includes("tool:functions.")||c.includes("agent:generalist."),u=f.role==="system"&&(f.text?.startsWith("[TOOL RESULT]")||f.text?.startsWith("SUCCESS:")||f.text?.startsWith("ERROR:"));f.role==="agent"?l?i.push(f.text):p.push(f.text):u?a.push(f.text):p.push(f.text)}),i.length>0&&t.push({role:"agent",text:"combined"}),a.length>0&&t.push({role:"system",text:"combined"}),p.length>0&&t.push({role:"agent",text:"combined"})}}return t.length},hc=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),Wo=async(e,n,t=5,o=1e3)=>{let s=n?.signal;for(let i=0;i<t;i++){if(s?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{let a=await fetch(e,n);if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),a.ok||a.status!==429&&a.status<500)return a}catch(a){if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),a.name==="AbortError"||s?.aborted||i===t-1)throw a}s?await new Promise((a,p)=>{let f=setTimeout(()=>{s.removeEventListener("abort",c),a()},Math.min(24e3,o*Math.pow(2,i))),c=()=>{clearTimeout(f),p(new DOMException("The user aborted a request.","AbortError"))};s.addEventListener("abort",c)}):await new Promise(a=>setTimeout(a,Math.min(24e3,o*Math.pow(2,i))))}if(s?.aborted)throw new DOMException("The user aborted a request.","AbortError");let r=await fetch(e,n);return typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),r},Jr=async function*(e,n,t,o,s,r,i,a,p=.99){let f=[];o&&f.push({role:"system",content:o});for(let x of t){let T=x.role==="user"?"user":"assistant",R=[];if(Array.isArray(x.parts)){for(let k of x.parts)if(k.text)R.push({type:"text",text:k.text});else if(k.inlineData&&i){let S=k.inlineData.mimeType,b=k.inlineData.data;S.startsWith("image/")&&R.push({type:"image_url",image_url:{url:`data:${S};base64,${b}`}})}}else{let k=x.text||"";k&&R.push({type:"text",text:k})}f.push({role:T,content:R.length===1&&R[0].type==="text"?R[0].text:R})}let c={model:n,messages:f,stream:!0,stream_options:{include_usage:!0},temperature:p};if(s!=="Fast"){let x={Low:"high",Medium:"high",Standard:"high",High:"max",xHigh:"max"};c.reasoning_effort=x[s]||"high",c.extra_body={thinking:{type:"enabled"}}}else c.extra_body={thinking:{type:"disabled"}};let l=await Wo("https://api.deepseek.com/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(c),signal:a});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,h="",g=[],y=null,m=Date.now(),w=!1;for(;;){let{done:x,value:T}=await u.read();if(x){w&&(g.length>0||y)&&(yield{candidates:g.length>0?[{content:{parts:g}}]:[],usageMetadata:y});break}h+=d.decode(T,{stream:!0});let R=h.split(`
510
+ `);h=R.pop();for(let k of R){let S=k.trim();if(!S||!S.startsWith("data: "))continue;let b=!1;if(S==="data: [DONE]")b=!0;else try{let C=JSON.parse(S.substring(6)),A=C.choices?.[0]?.delta,E=C.usage;if(C.choices?.[0]?.finish_reason&&(b=!0),E&&(y={totalTokenCount:E.total_tokens||E.prompt_tokens+E.completion_tokens,promptTokenCount:E.prompt_tokens||0,candidatesTokenCount:E.completion_tokens||0,cachedContentTokenCount:E.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:E.completion_tokens_details?.reasoning_tokens||0},w=!0),A){let I=A.reasoning_content||null;I&&(g.push({text:I,thought:!0}),w=!0),A.content&&(g.push({text:A.content}),w=!0)}}catch{}if((b||Date.now()-m>=150)&&w&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],m=Date.now(),w=!1),b)break}Date.now()-m>=150&&w&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],m=Date.now(),w=!1)}},Qr=async function*(e,n,t,o,s,r,i,a,p=.99){let f=[];o&&f.push({role:"system",content:o});for(let R of t){let k=R.role==="user"?"user":"assistant",S=[];if(Array.isArray(R.parts)){for(let b of R.parts)if(b.text)S.push({type:"text",text:b.text});else if(b.inlineData&&i){let C=b.inlineData.mimeType,A=b.inlineData.data;C.startsWith("image/")&&S.push({type:"image_url",image_url:`data:${C};base64,${A}`})}}else{let b=R.text||"";b&&S.push({type:"text",text:b})}S.length>0&&f.push({role:k,content:S.length===1&&S[0].type==="text"?S[0].text:S})}let c={Fast:"none",Low:"none",Medium:"high",Standard:"high",High:"high",xHigh:"high"},l={model:n,messages:f,stream:!0,temperature:p,prompt_cache_key:"flux-flow-session"};s&&s!=="Fast"&&qs(n)&&(l.reasoning_effort=c[s]||"high");let u=await Wo("https://api.mistral.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(l),signal:a});if(!u.ok){let R=await u.text().catch(()=>""),k=u.statusText;try{let S=JSON.parse(R);k=S.error?.message||S.message||JSON.stringify(S.detail||S)}catch{R&&(k=R)}throw new Error(`Mistral Error (${u.status}): ${JSON.stringify(k)}`)}let d=u.body.getReader(),h=new TextDecoder,g="",y=[],m=null,w=Date.now(),x=!1,T=R=>R?typeof R=="string"?Dn(R):Array.isArray(R)?R.map(T).filter(Boolean).join(""):typeof R=="object"&&R!==null?typeof R.text=="string"?Dn(R.text):typeof R.content=="string"?Dn(R.content):typeof R.thinking=="string"?Dn(R.thinking):typeof R.reasoning_content=="string"?Dn(R.reasoning_content):typeof R.reasoning=="string"?Dn(R.reasoning):typeof R.value=="string"?Dn(R.value):R.text?T(R.text):R.content?T(R.content):R.thinking?T(R.thinking):R.reasoning_content?T(R.reasoning_content):R.reasoning?T(R.reasoning):R.value?T(R.value):"":Dn(String(R)):"";for(;;){let{done:R,value:k}=await d.read();if(R){x&&(y.length>0||m)&&(yield{candidates:y.length>0?[{content:{parts:y}}]:[],usageMetadata:m});break}g+=h.decode(k,{stream:!0});let S=g.split(`
511
+ `);g=S.pop();for(let b of S){let C=b.trim();if(!C||!C.startsWith("data: "))continue;let A=!1;if(C==="data: [DONE]")A=!0;else try{let E=JSON.parse(C.substring(6)),I=E.choices?.[0]?.delta,_=E.usage;if(E.choices?.[0]?.finish_reason&&(A=!0),_&&(m={totalTokenCount:_.total_tokens||(_.prompt_tokens||0)+(_.completion_tokens||0),promptTokenCount:_.prompt_tokens||0,candidatesTokenCount:_.completion_tokens||0,cachedContentTokenCount:_.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:_.completion_tokens_details?.reasoning_tokens||0},x=!0),I){let v=I.thinking||I.reasoning_content||I.reasoning,W=T(v);W&&(y.push({text:W,thought:!0}),x=!0);let B=I.content||(!I.thinking&&!I.reasoning_content&&!I.reasoning?I.text:null);if(B)if(Array.isArray(B))for(let K of B)if(typeof K=="object"&&K!==null){let J=K.type==="thinking"||K.type==="reasoning"||!!K.thought,xe=T(K);xe&&(y.push({text:xe,...J?{thought:!0}:{}}),x=!0)}else{let J=T(K);J&&(y.push({text:J}),x=!0)}else if(typeof B=="object"&&B!==null){let K=B.type==="thinking"||B.type==="reasoning"||!!B.thought,J=T(B);J&&(y.push({text:J,...K?{thought:!0}:{}}),x=!0)}else{let K=T(B);K&&(y.push({text:K}),x=!0)}}}catch{}if((A||Date.now()-w>=150)&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),x=!1),A)break}Date.now()-w>=150&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),x=!1)}},Zr=async function*(e,n,t,o,s,r,i=!1,a,p=.99){let f=[];o&&f.push({role:"system",content:o}),t.forEach(Q=>{let ce=Q.role==="model"?"assistant":"user",M=[];Array.isArray(Q.parts)&&Q.parts.forEach(P=>{if(P.text)M.push({type:"text",text:P.text});else if(P.inlineData&&i){let Y=P.inlineData.mimeType,V=P.inlineData.data;Y.startsWith("image/")&&dn(n)&&M.push({type:"image_url",image_url:{url:`data:${Y};base64,${V}`}})}}),f.push({role:ce,content:M.length===1&&M[0].type==="text"?M[0].text:M})});let l={Fast:"Fast",Low:"Fast",Medium:"Standard",Standard:"Standard",High:"High",xHigh:"High"}[s]||"High",u=l!=="Fast",d=n.includes("kimi"),h=n.includes("gemma"),g=n.includes("deepseek"),y=n.includes("glm"),m=n.includes("mistral"),w=n.includes("minimax"),x=n.includes("gpt"),T=n.includes("qwen"),R=n.includes("nemotron"),k=n.includes("llama-3"),S=n.includes("seed"),b=n.includes("poolside"),C=n.includes("thinkingmachines")||n.includes("muse"),A=k,E=null,I={Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},_={Fast:"64",Low:"64",Medium:"4096",Standard:"4096",High:"16384",xHigh:"16384"},v={Fast:"none",Low:"minimal",Medium:"medium",Standard:"medium",High:"max",xHigh:"max"},W=w||g||b||C?16384:32768;W=process.env.NVIDIA_BASE_URL?1024:W,W=E?1024:W;let B={model:n,messages:f,max_tokens:W,stream:!0,stream_options:{include_usage:!0},temperature:p,...x&&{thinking:I[s]||"high"}};if(!(process.env.NVIDIA_BASE_URL||A||E))if(d)B.chat_template_kwargs={thinking:u};else if(h)B.chat_template_kwargs={enable_thinking:u};else if(g)if(u){let Q=l==="High"?"max":"high";B.chat_template_kwargs={thinking:!0,reasoning_effort:Q}}else B.chat_template_kwargs={thinking:!1};else y?B.chat_template_kwargs={enable_thinking:u,clear_thinking:!u}:m?B.reasoning_effort=u?"high":"none":w&&n.includes("minimax-m3")?B.chat_template_kwargs={thinking_mode:u?"enabled":"disabled"}:T?B.chat_template_kwargs={enable_thinking:u}:R?l==="High"?(B.reasoning_budget=12e3,B.chat_template_kwargs={enable_thinking:!0}):l==="Standard"?(B.reasoning_budget=12e3,B.chat_template_kwargs={enable_thinking:!0,medium_effort:!0}):B.chat_template_kwargs={enable_thinking:!1}:S?u&&(B.extra_body={thinking_budget:parseInt(_[l]??"4096")}):b?B.chat_template_kwargs={enable_thinking:u}:C&&(B.reasoning_effort=v[l]||"medium");let K=0,J=6,xe=!1,N=process.env.NVIDIA_BASE_URL||"https://integrate.api.nvidia.com/v1/chat/completions",F=process.env.NVIDIA_API_KEY&&process.env.NVIDIA_BASE_URL?process.env.NVIDIA_API_KEY:e;for(N.endsWith("/chat/completions")||(N=N.replace(/\/+$/,"")+"/chat/completions");K<J;){K++;try{let Q=await Wo(N,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${F}`},body:JSON.stringify(B),signal:a});if(!Q.ok){let Be=await Q.text().catch(()=>""),ot=Q.statusText;try{let ht=JSON.parse(Be);ot=ht.error?.message||ht.message||JSON.stringify(ht.detail||ht)}catch{Be&&(ot=Be)}let je=new Error(`NVIDIA API Error (${Q.status}): ${ot}`);throw je.status=Q.status,je}let ce=Q.body.getReader(),M=new TextDecoder,P="",Y=[],V=null,_e=Date.now(),Pe=!1;for(;;){let{done:Be,value:ot}=await ce.read();if(Be){Pe&&(Y.length>0||V)&&(yield{candidates:Y.length>0?[{content:{parts:Y}}]:[],usageMetadata:V},xe=!0);break}P+=M.decode(ot,{stream:!0});let je=P.split(`
512
+ `);P=je.pop();let ht=!1;for(let Ft of je){let pt=Ft.trim();if(pt){if(pt==="data: [DONE]"){ht=!0;break}if(pt.startsWith("data: ")){let mt;try{mt=JSON.parse(pt.substring(6))}catch{continue}if(mt.error)throw new Error(`NVIDIA Stream Error: ${mt.error.message||JSON.stringify(mt.error)}`);mt.choices?.[0]?.finish_reason&&(ht=!0);try{let bt=mt.usage;bt&&(V={totalTokenCount:bt.total_tokens||bt.prompt_tokens+bt.completion_tokens,promptTokenCount:bt.prompt_tokens||0,candidatesTokenCount:bt.completion_tokens||0,cachedContentTokenCount:bt.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:(bt.completion_tokens_details?.reasoning_tokens||0)+(bt.completion_tokens_details?.thoughts_tokens||0)},Pe=!0);let Rt=mt.choices?.[0]?.delta?.reasoning||mt.choices?.[0]?.delta?.reasoning_content||"",Qe=mt.choices?.[0]?.delta?.content||"";Rt&&(Y.push({text:Rt,thought:!0}),Pe=!0),Qe&&(Y.push({text:Qe}),Pe=!0)}catch{}}}}if((ht||Date.now()-_e>=350)&&Pe&&(yield{candidates:Y.length>0?[{content:{parts:[...Y]}}]:[],usageMetadata:V},xe=!0,Y=[],_e=Date.now(),Pe=!1),ht)break}break}catch(Q){if(xe||K>=J)throw Q;await new Promise(ce=>setTimeout(ce,3500))}}},pc=async function*(e,n){let t=[],o=null,s=!1,r=null,i=u=>{if(t.push(u),o){let d=o;o=null,d()}},a=n.split("/").pop();a=a.replace("llama-3.3","llama-3_3");let p=`https://api.ngc.nvidia.com/v2/predict/queues/models/qc69jvmznzxy/${a}`,f=!1,c=null,l=async()=>{try{let u=await fetch(p);if(u.ok){let d=await u.json();if(d&&d.queues&&d.queues[0]&&typeof d.queues[0].queueDepth=="number"){let h=d.queues[0].queueDepth;f||i({value:{type:"status",content:`Queue ${h||1}`},done:!1})}}else f||i({value:{type:"status",content:`Queue ${u.status}`},done:!1})}catch{}};process.env.NVIDIA_BASE_URL||(l(),c=setInterval(l,5e3)),(async()=>{try{let u=e[Symbol.asyncIterator]();for(;;){let{value:d,done:h}=await u.next();if(h)break;f=!0,c&&(clearInterval(c),c=null),i({value:d,done:!1})}s=!0,i(null)}catch(u){if(r=u,c&&(clearInterval(c),c=null),o){let d=o;o=null,d()}}})();try{for(;;){if(r)throw r;if(t.length>0){let u=t.shift();if(u===null&&s)break;yield u.value}else{if(s)break;await new Promise(u=>{o=u})}}}finally{c&&(clearInterval(c),c=null)}},ei=async function*(e,n,t,o,s,r,i,a,p=.95){let f=[];o&&f.push({role:"system",content:[{type:"text",text:o,cache_control:{type:"ephemeral"}}]});for(let R of t){let k=R.role==="user"?"user":"assistant",S=[];if(Array.isArray(R.parts)){for(let b of R.parts)if(b.text)S.push({type:"text",text:b.text});else if(b.inlineData&&i){let C=b.inlineData.mimeType,A=b.inlineData.data;C.startsWith("image/")?S.push({type:"image_url",image_url:{url:`data:${C};base64,${A}`}}):S.push({type:"file",file:{filename:b.filename||"file",file_data:`data:${C};base64,${A}`}})}}else{let b=R.text||"";b&&S.push({type:"text",text:b})}f.push({role:k,content:S.length===1&&S[0].type==="text"?S[0].text:S})}let c={Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},l={model:n,messages:f,stream:!0,temperature:p,cache_control:{type:"ephemeral"},session_id:"flux-flow-session"},u=c[s];u&&s!=="Fast"&&(l.reasoning_effort=u);let d=await Wo("https://openrouter.ai/api/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json","X-Title":"FluxFlow CLI","X-Cache":"true","X-OpenRouter-Cache":"true"},body:JSON.stringify(l),signal:a});if(!d.ok){let R=await d.json().catch(()=>({}));throw new Error(`OpenRouter Error (${d.status}): ${R.error?.message||d.statusText}`)}let h=d.body.getReader(),g=new TextDecoder,y="",m=[],w=null,x=Date.now(),T=!1;for(;;){let{done:R,value:k}=await h.read();if(R){T&&(m.length>0||w)&&(yield{candidates:m.length>0?[{content:{parts:m}}]:[],usageMetadata:w});break}y+=g.decode(k,{stream:!0});let S=y.split(`
513
+ `);y=S.pop();for(let b of S){let C=b.trim();if(!C||!C.startsWith("data: "))continue;let A=!1;if(C==="data: [DONE]")A=!0;else try{let E=JSON.parse(C.substring(6)),I=E.choices?.[0]?.delta,_=E.usage;if(E.choices?.[0]?.finish_reason&&(A=!0),_&&(w={totalTokenCount:_.total_tokens||(_.prompt_tokens||0)+(_.completion_tokens||0),promptTokenCount:_.prompt_tokens||0,candidatesTokenCount:_.completion_tokens||0,cachedContentTokenCount:_.prompt_tokens_details?.cached_tokens||_.prompt_tokens_details?.cache_read_input_tokens||_.cache_read_input_tokens||0,thoughtsTokenCount:_.completion_tokens_details?.reasoning_tokens||0},T=!0),I){let v=I.reasoning||(I.reasoning_details?I.reasoning_details.map(W=>W.text).join(""):null);v&&(m.push({text:v,thought:!0}),T=!0),I.content&&(m.push({text:I.content}),T=!0)}}catch{}if((A||Date.now()-x>=150)&&T&&(yield{candidates:m.length>0?[{content:{parts:[...m]}}]:[],usageMetadata:w},m=[],x=Date.now(),T=!1),A)break}}},$a=async function*(e,n,t,o,s,r,i,a,p=1.05,f="Cloud"){let c=[];o&&c.push({role:"system",content:o});for(let S of t){let b=S.role==="user"?"user":"assistant",C="",A=[];if(Array.isArray(S.parts)){C=S.parts.map(E=>E.text||"").filter(Boolean).join(`
514
+ `);for(let E of S.parts){let I=E.inlineData||E.inline_data;I&&I.data&&A.push(I.data)}}else C=S.text||"";if(C||A.length>0){let E={role:b,content:C};A.length>0&&(E.images=A),c.push(E)}}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 h=new Xl(d),g=[],y=null,m=Date.now(),w=!1,x={Fast:!1,Low:"medium",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},T=x[s]!==void 0?x[s]:!0,R={model:n,messages:c,stream:!0,think:T,keep_alive:"10m",options:{temperature:p}},k=await h.chat(R);for await(let S of k){if(a?.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 b=S.prompt_cached_count||0;if(!b&&S.prompt_eval_count){let C=S.prompt_eval_duration||0;C>0&&C<5e7&&(b=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:b,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})},lm=()=>{vt=!0},cm=()=>vt,Vr={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",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"},Ts=(e,n)=>{try{let t=L(n),o=e.toLowerCase().replace(/_/g,"");if(o==="invokesync"||o==="invoke")return t.title||(t.task?t.task.substring(0,30):null);if(o==="getprogress"||o==="cancel"||o==="steer"||o==="steersubagent")return t.id||t.taskId;let s=t.path||t.targetFile||t.TargetFile||t.directory;return s?ee.basename(s.replace(/["']/g,"").replace(/\\/g,"/")):null}catch{return null}},ti=e=>e?new ka({apiKey:e}):Xr,fm=async(e,n,t,o,s={})=>{let{onStatus:a,onMemoryUpdated:p,onBackgroundIncrement:f}=s,{profile:c,thinkingLevel:l,mode:u,janitorModel:d,chatId:h,systemSettings:g,sessionStats:y,aiProvider:m="Google",apiKey:w}=e,x=process.env.NVIDIA_BASE_URL||m==="Ollama"?!1:g?.memory!==!1,R=Z(Pt,[]).map(M=>`- [${M.id}]: ${M.memory}`).join(`
515
+ `),k=o.slice(0,-1).filter(M=>M.text&&!M.text.includes("[TOOL RESULT]")&&!M.text.includes("OBSERVATION:")&&!M.text.startsWith("[TERMINAL_RECORD]")&&!M.isTerminalRecord&&!M.isMeta&&!M.isLogo&&!String(M.id).startsWith("welcome")&&!String(M.id).startsWith("logo")).slice(-14).map(M=>{let P=hc(M.text).replace(/\[tool:functions\..*?\]/g,"").replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[METADATA \(PRIORITY: DYNAMIC\)\] Time: ([^|\n]+)/g,(Pe,Be)=>`[METADATA (PRIORITY: DYNAMIC)] Time: ${Be.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,`
516
+ `).replace(/\n\n/g,`
517
+ `).replace(/\\n\\n/g,"").trim(),Y=M.role==="user"?8192:32768,V=P.substring(0,Y);P.length>Y&&(V+=`
518
+ ... (truncated) ...`);let _e=M.role==="user"?V.startsWith("[USER]")?"":"[USER]: ":V.startsWith("[AGENT]")?"":"[AGENT]: ";return{role:M.role==="user"?"user":"model",parts:[{text:`${_e}${V}`}]}}),S=o.filter(M=>M.role==="user").length===1,b=n.includes("[TITLE-UPDATE]"),C=Math.random()<.8,A=S||b||C,E=t.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").trim(),I=wi(R,x,A),_=`${E.replace(/\[tool:functions\..*?\]/g,"").replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[\[TOOL RESULTS\]\]/g,"").replace(/\[tool results\]/g,"").substring(0,32768)}`;_.length>32768&&(_+=`
519
+ ... (truncated) ...`);let v=n.replace(/\[Prompted on:.*?\]/g,"").trim();_=_.replace(/\r?\n\r?\n/g,`
520
+ `).replace(/\n\n/g,`
521
+ `).replace(/\\n\\n/g,"").trim();let W=new Date,K=`[METADATA] Current date and Time: ${`${W.getFullYear()}-${W.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(W.getDate()).padStart(2,"0")}, ${W.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0})}`}
522
+
523
+ [USER]: ${v.substring(0,8192)}
524
+ ${v.length>8192?`... (truncated) ...
525
+
526
+ `:""}
527
+ [AGENT (current turn)]: ${_}`;k.push({role:"user",parts:[{text:K}]});let J=await Jo("NVIDIA"),N=(await Qt()).quotas?.providerTiers?.NVIDIA==="Free",F="",Q=0,ce=x?12:-1;for(;Q<=ce;)try{if(!await Ri("background",e))return;let M="",P=null,Y=!1,V=m;try{let Be=new Promise((Rt,Qe)=>setTimeout(()=>Qe(new Error("JANITOR_TIMEOUT")),1e4)),ot=m==="Google"&&Q>=0&&Q<6&&J&&N,je=m==="DeepSeek"&&Q<4&&J&&N;Y=ot||je,V=Y?"NVIDIA":m;let ht=(async()=>{if(m==="OpenRouter"){let Rt=tt("janitor_open_router"),we=ei(w,Rt,k,I,"Fast",u,!1,null,.6)[Symbol.asyncIterator](),Kt=await we.next();return{iterator:we,firstResult:Kt}}else if(m==="DeepSeek"&&!Y){let Qe=Jr(w,tt("deepseek_fast_fallback"),k,I,"Fast",u,!1,null,.6)[Symbol.asyncIterator](),we=await Qe.next();return{iterator:Qe,firstResult:we}}else if(m==="Mistral"&&!Y){let Qe=Qr(w,tt("mistral_janitor_fallback"),k,I,"Fast",u,!1,null,.6)[Symbol.asyncIterator](),we=await Qe.next();return{iterator:Qe,firstResult:we}}else if(m==="NVIDIA"||Y){let Qe=Zr(Y?J:w,tt("nvidia_janitor_fallback"),k,I,"Fast",u,!1,null,.6)[Symbol.asyncIterator](),we=await Qe.next();return{iterator:Qe,firstResult:we}}else{let we=(await ti(w).models.generateContentStream({model:d||(Q===ce?tt("janitor_default"):tt("gemma_janitor_fallback_google")),contents:k,config:{systemInstruction:I,temperature:.7,safetySettings:[{category:Xn.HARM_CATEGORY_HARASSMENT,threshold:Vn.BLOCK_NONE},{category:Xn.HARM_CATEGORY_HATE_SPEECH,threshold:Vn.BLOCK_NONE},{category:Xn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Vn.BLOCK_NONE},{category:Xn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Vn.BLOCK_NONE}],thinkingConfig:{includeThoughts:!1,thinkingLevel:lt.MINIMAL}}}))[Symbol.asyncIterator](),Kt=await we.next();return{iterator:we,firstResult:Kt}}})();if(process.stdout.isTTY){let we=(await cs())[h]?.name||"",Kt=we&&!we.startsWith("flow-")&&!we.startsWith("Session ")?we:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${Kt}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${Kt}\x07`)}let{iterator:Ft,firstResult:pt}=await Promise.race([ht,Be]),{value:mt,done:bt}=pt;if(!bt&&mt){let Rt=mt.candidates?.[0]?.content?.parts,Qe=Rt?V==="Google"?Rt[1]?.text||Rt[0]?.text||"":Rt.filter(we=>we.text&&!we.thought).map(we=>we.text).join(""):typeof mt.text=="function"?mt.text():"";Qe&&(M+=Qe),P=mt.usageMetadata;for await(let we of{[Symbol.asyncIterator]:()=>Ft}){let Kt=we.candidates?.[0]?.content?.parts,Jn=Kt?V==="Google"?Kt[1]?.text||Kt[0]?.text||"":Kt.filter(Qn=>Qn.text&&!Qn.thought).map(Qn=>Qn.text).join(""):typeof we.text=="function"?we.text():"";Jn&&(M+=Jn),P=we.usageMetadata}}}catch(Be){throw Be}if(M){if(F=M,P){let Be=P.totalTokenCount||0,ot=P.cachedContentTokenCount||0,je=(P.candidatesTokenCount||0)+(P.thoughtsTokenCount||0),ht=Y?tt("nvidia_janitor_fallback"):V==="DeepSeek"?tt("deepseek_fast_fallback"):V==="OpenRouter"?tt("janitor_open_router"):d||(Q===ce?tt("janitor_default"):tt("gemma_janitor_fallback_google"));await jt("tokens",Be,V,ht),ot>0&&await jt("cachedTokens",ot,V,ht),je>0&&await jt("candidateTokens",je,V,ht)}}else throw new Error("No synthesis generated by Janitor.");f&&(f(),await Lt("background"));let _e=Ho(F),Pe=!1;for(let Be of _e){let ot=Be.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(ot)&&(Pe=!0);let je={chatId:h,sessionId:h,history:o},ht=await ao(ot,Be.args,je);ot.toLowerCase()==="memory"&&(Be.args.includes("action='user'")||Be.args.includes('action="user"'))&&!ht.startsWith("ERROR")&&(p&&p(),process.stdout.isTTY&&(process.stdout.write("\x1B]0;Memory Updated\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=Memory Updated\x07")),await new Promise(pt=>setTimeout(pt,3e3)))}if(!Pe)try{let Be=Z(Pt,[]);if(Be.length>0){let ot=[];for(let je of Be)je.score===void 0&&(je.score=.5),je.score*=.99995,je.score<.05&&(je.score=0),je.score=Math.round(je.score*1e5)/1e5,je.score>0&&ot.push(je);pe(Pt,ot)}}catch{}break}catch(M){Q++;let P=new Date().toLocaleString(),Y=M instanceof Error?(()=>{try{return JSON.parse(JSON.parse(M.message).error.message).error.message}catch{return String(M)}})():String(M);await new Promise(Pe=>setTimeout(Pe,1e3));let V=ee.join(cn,"janitor");if(Le.existsSync(V)||Le.mkdirSync(V,{recursive:!0}),Le.appendFileSync(ee.join(V,"error.log"),`ERROR [Attempt ${Q}/${ce+1}] [${P}]: ${Y}
528
+
529
+ `),Q>ce)break;let _e=Math.min(750*Math.pow(2,Q-1),5e3);await new Promise(Pe=>setTimeout(Pe,_e))}if(Q){let M=ee.join(cn,"janitor");Le.appendFileSync(ee.join(M,"error.log"),`-----------------------------------------------------------------------------
530
+
531
+ `)}if(process.stdout.isTTY)try{let Y=(await cs())[h]?.name||"",V=Y&&!Y.startsWith("flow-")&&!Y.startsWith("Session ")?Y:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${V}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${V}\x07`)}catch{process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")}},mc=e=>{let n=e.replace(ac,"").replace(lc,""),t=Ls?n:n.replace(Ca,s=>" ".repeat(s.length)).replace(Aa,s=>" ".repeat(s.length));co.lastIndex=0;let o;for(;(o=co.exec(t))!==null;){let s=o.index+o[0].length-1,r=0,i=null,a=!1,p=!1;for(let f=s;f<t.length;f++){let c=n[f];if(!i&&(c==='"'||c==="'"||c==="`")?(i=c,a=!1):i&&c===i&&!a&&(i=null),!i&&(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]==="]"){p=!0,co.lastIndex=l+1;break}}c==="\\"?a=!a:a=!1}if(!p)return{inside:!0,toolName:o[1],startIndex:o.index,args:n.substring(o.index+o[0].length)}}return{inside:!1}},Ma=(e,n=!0)=>{let t=co;t.lastIndex=0;let o="",s=0,r;for(;(r=t.exec(e))!==null;){let i=e.substring(s,r.index);o+=n?i.replace(ya,""):i;let a=r.index+r[0].length-1,p=0,f=null,c=-1;for(let l=a;l<e.length;l++){let u=e[l];if(f){if(u===f){let d=0;for(let h=l-1;h>=0&&e[h]==="\\";h--)d++;d%2===0&&(f=null)}}else if(u==='"'||u==="'"||u==="`")f=u;else if(u==="(")p++;else if(u===")"&&(p--,p===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)o+="[tool:functions."+r[1]+"()]",s=c+1,t.lastIndex=s;else{o+="[tool:functions."+r[1]+"(",s=e.length;break}}return s<e.length&&(o+=n?e.substring(s).replace(ya,""):e.substring(s)),o},gc=(e,n,t)=>{let o=co;o.lastIndex=0;let s="",r=0,i;for(;(i=o.exec(e))!==null;){let a=e.substring(r,i.index);s+=a.replace(n,t);let p=i.index+i[0].length-1,f=0,c=null,l=-1;for(let u=p;u<e.length;u++){let d=e[u];if(c){if(d===c){let h=0;for(let g=u-1;g>=0&&e[g]==="\\";g--)h++;h%2===0&&(c=null)}}else if(d==='"'||d==="'"||d==="`")c=d;else if(d==="(")f++;else if(d===")"&&(f--,f===0)){let h=u+1;for(;h<e.length&&/\s/.test(e[h]);)h++;if(h<e.length&&e[h]==="]"){l=h;break}}}if(l!==-1)s+=e.substring(i.index,l+1),r=l+1,o.lastIndex=r;else{s+=e.substring(i.index),r=e.length;break}}return r<e.length&&(s+=e.substring(r).replace(n,t)),s},Ra=e=>Ma(e,!0),yc=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",ask:"Ask"},t=s=>s.split("_").map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join("");Sa.lastIndex=0;let o=e.replace(Sa,(s,r,i)=>{let a="";try{let c=JSON.parse(i.trim());c&&typeof c=="object"&&(a=Object.entries(c).map(([u,d])=>{let h=typeof d=="string"?d:JSON.stringify(d);return`${u}=${JSON.stringify(h)}`}).join(", "))}catch{let l=[],u=cc;u.lastIndex=0;let d;for(;(d=u.exec(i))!==null;){let h=d[1],g=d[2]!==void 0?d[2]:d[0].split(":").slice(1).join(":").trim();l.push(`${h}=${JSON.stringify(g)}`)}l.length>0?a=l.join(", "):a=i.trim()}let p=r.toLowerCase().replace(/_/g,"");return`[tool:functions.${n[p]||t(r)}(${a})]`});return Ta.lastIndex=0,xa.lastIndex=0,o=o.replace(Ta,""),o=o.replace(xa,""),o},wc=/(?:path|query|url|keyword|command|method|title|task|id)\s*=\s*['"`]?\s*\.\.\.\s*['"`]?/i,Sc=/^['"`]?\s*\.\.\.\s*['"`]?$/,Nn=e=>{if(e==null)return!1;let n=String(e).trim();return n==="..."||n==="\u2026"||Sc.test(n)},Ho=e=>{if(!e)return[];let n=yc(e);wa.lastIndex=0;let t=n.replace(wa,""),o=[],s=Ls?t:t.replace(Ca,a=>" ".repeat(a.length)).replace(Aa,a=>" ".repeat(a.length)),r=sc;r.lastIndex=0;let i;for(;(i=r.exec(s))!==null;){let a=i[1],p=i.index+i[0].length-1,f=0,c=null,l=-1,u=-1;for(let d=p;d<s.length;d++){let h=t[d];if(c){if(h===c){let g=0;for(let y=d-1;y>=0&&t[y]==="\\";y--)g++;g%2===0&&(c=null)}}else if(h==='"'||h==="'"||h==="`")c=h;else if(h==="(")f++;else if(h===")"&&(f--,f===0)){u=d;let g=d+1;for(;g<s.length&&/\s/.test(s[g]);)g++;if(g<s.length&&s[g]==="]"){l=g;break}}}if(l!==-1){let d=t.substring(p+1,u),h=t.substring(i.index,l+1),g=L(d);Nn(g.path)||Nn(g.query)||Nn(g.url)||Nn(g.keyword)||Nn(g.command)||Nn(g.method)||Nn(g.title)||Nn(g.task)||Nn(g.id)||wc.test(d)||o.push({fullMatch:h,toolName:a.trim(),args:d.trim()}),r.lastIndex=l+1}}return o},dm=(e,n={})=>{if(!e)return null;if(Uo=n,Xr=new ka({apiKey:e}),!globalThis.__perfCleanupInstalled){globalThis.__perfCleanupInstalled=!0,setInterval(()=>{typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks())},6e4);let t=globalThis.fetch;globalThis.fetch=async(...o)=>{try{let s=await t(...o);return typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),s}catch(s){throw typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),s}}}},Bo=async(e,n,t,o,s="Fast",r=.75,i="agent")=>dc(async()=>{let{aiProvider:a="Google",apiKey:p,mode:f}=e,c="",l=null,u=typeof t=="string"?[{role:"user",parts:[{text:t}]}]:t,d=new AbortController,h=d.signal,g=setInterval(()=>{vt&&(d.abort(),clearInterval(g))},100);try{let y;a==="Ollama"?y=$a(p,n,u,o,s,f,dn(n),h,r,systemSettings?.ollamaEndpoint||"Cloud"):a==="OpenRouter"?y=ei(p,n,u,o,s,f,dn(n),h,r):a==="DeepSeek"?y=Jr(p,n,u,o,s,f,dn(n),h,r):a==="Mistral"?y=Qr(p,n,u,o,s,f,dn(n),h,r):a==="NVIDIA"?y=Zr(p,n,u,o,s,f,dn(n),h,r):y=await ti(p).models.generateContentStream({model:n,contents:u,config:{systemInstruction:o,temperature:r,thinkingConfig:(()=>{let x=(n||"").toLowerCase(),T=x.includes("gemma-4")||x.startsWith("gemma"),R=x.includes("gemini-3");if(T||R)return T?s.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:lt.MINIMAL}:{includeThoughts:!0,thinkingLevel:lt.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:x.includes("pro")?lt.LOW:lt.MINIMAL,Low:lt.LOW,Medium:lt.MEDIUM,Standard:lt.MEDIUM,High:lt.HIGH,xHigh:lt.HIGH}[s]||lt.MEDIUM};{let k={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[s]||2048;return k===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:k}}})()}},{signal:h});for await(let m of y){if(vt)throw new Error("Subagent task was cancelled.");if(e?.taskId&&typeof ze<"u"){let T=ze.find(R=>R.id===e.taskId);if(T&&T.status==="cancelled")throw new Error("Subagent task was cancelled.")}let w="";if(m.candidates?.[0]?.content?.parts)for(let T of m.candidates[0].content.parts)T.text&&!T.thought&&(c+=T.text,w+=T.text);let 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 jt("tokens",y,a,n),m>0&&await jt("cachedTokens",m,a,n),w>0&&await jt("candidateTokens",w,a,n),e&&typeof e.onUsage=="function"&&e.onUsage({totalTokenCount:y,cachedContentTokenCount:m,candidatesTokenCount:w})}return await Lt("agent",a),{text:c,usageMetadata:l}}),Tc=async(e,n,t=null)=>{t=t||Z(Jt,{});try{let{aiProvider:o="Google"}=n;if(Object.values(t).flat().length<=5)return;let r=Object.keys(t).filter(u=>u!==e&&Array.isArray(t[u])&&t[u].length>2);if(r.length===0)return;let i=`You are a silent background process for the FluxFlow CLI Agent.
532
+ Your task is to summarize or merge temporary context memories from one or more past conversation sessions.
533
+ For each Chat ID provided, you must output a tool call to save the consolidated summary.
534
+
535
+ The tool call format MUST be:
536
+ [tool:functions.saveSummary(id="<chat-id>", summary="<updated summary string, max 400 words>")]
537
+
538
+ Guidelines:
539
+ - Create a single, updated, highly cohesive, and concise summary statement (max 400 words) for each Chat ID. It should contain WHAT user talked about, WHAT were the tasks, Temporal info, HOW/WHAT the model responded. DON'T REMOVE ANY KEY AND TURN BY TURN INFO DENSITY.
540
+ - Focus on key goals, preferences, modified files, and technical decisions.
541
+ - Under no circumstances write normal conversational text. Output ONLY the tool calls.
542
+ - You can stack multiple tool calls for multiple chats.
543
+
544
+ Chats to process:
545
+
546
+ `,a=Z(In,{});for(let u of r){let h=t[u].map(y=>`- ${y}`).join(`
547
+ `),g=a[u];i+=`[Chat ID: ${u}]
548
+ `,g?(i+=`- Existing Summary: "${g}"
549
+ `,i+=`
550
+ -- New Memories to integrate:
551
+ ${h}
552
+
553
+ `):i+=`-- Individual Memories:
554
+ ${h}
555
+
556
+ `}let p=0,f=5,c=!1,l=tt("gemma_janitor_fallback_google");for(o==="OpenRouter"&&(l=tt("janitor_open_router")),o==="DeepSeek"&&(l=tt("deepseek_level_1")),o==="Mistral"&&(l=tt("mistral_level_1")),o==="NVIDIA"&&(l=tt("nvidia_janitor_fallback"));p<=f&&!c;){p++;try{let d=(await Bo(n,l,i,null,"Fast",.75,"background")).text||"",h=Ho(d);if(h.length===0)throw new Error("No tool calls detected in synthesis response");for(let g of h){let y=g.toolName;["saveSummary","saveSumary","SaveSummary","SaveSumary"].includes(y)&&await ao(y,g.args,{chatId:e})}c=!0}catch(u){if(p>=f)throw new Error(`Failed after ${f} attempts. Last error: ${u.message}`)}}}catch(o){let s=o instanceof Error?(()=>{try{return JSON.parse(JSON.parse(o.message).error.message).error.message}catch{return String(o)}})():String(o),r=ee.join(cn,"janitor");Le.existsSync(r)||Le.mkdirSync(r,{recursive:!0}),Le.appendFileSync(ee.join(r,"error.log"),`[${new Date().toLocaleString()}] Past memory batch consolidation error: ${s}
557
+ `)}},xc=async(e,n,t=!1)=>{let{chatId:o,aiProvider:s="Google"}=e,r=ee.join(go,"chat-summaries.json"),i=d=>d.filter(h=>(h.role==="user"||h.role==="agent"||h.role==="system")&&h.role!=="think"&&!h.isVisualFeedback&&!h.isMeta&&!h.isTerminalRecord&&!(h.text&&h.text.includes("[TERMINAL_RECORD]"))&&!String(h.id).startsWith("welcome")).map(h=>{let g=h.fullText||h.text||"",y=h.role==="system"||g.startsWith("[TOOL RESULT]:")||h.text&&h.text.startsWith("[TOOL RESULT]:"),m=g;return y&&(g.includes("[TOOL RESULT]:")||h.text&&h.text.includes("[TOOL RESULT]:"))?m="[TOOL RESULT]: ...truncated for summary":m=m.replace(/(\[(?:tool|agent):[a-zA-Z0-9_\.]+)\([\s\S]*?\)(\])/g,"$1(...)$2"),`[${y?"TOOL":h.role==="agent"?"AGENT":"USER"}]: ${m}`}).join(`
558
+
559
+ `),a=async(d,h)=>{let g="You are an expert context summarizer. Summarize the provided chat history (which may include previous summaries, user instructions, agent outputs, and tool results) into a detailed, coherent, and highly technical summary of 1000 to 1500 words. Focus on preserving the architectural decisions made, current system state, task progress, and critical code details, chat messages, file changes. Under no circumstances exceed MAX 2000 words.",y=h?`Here is the previous summary:
560
+ ${h}
561
+
562
+ Here is the new conversation history:
563
+ ${d}
564
+
565
+ Provide a new consolidated summary of the entire session.`:`Here is the conversation history:
566
+ ${d}
567
+
568
+ Provide a consolidated summary of the entire session.`,m=tt("gemma_janitor_fallback_google");s==="OpenRouter"&&(m=tt("janitor_open_router")),s==="DeepSeek"&&(m=tt("deepseek_level_1")),s==="Mistral"&&(m=tt("mistral_level_1")),s==="NVIDIA"&&(m=tt("nvidia_chat_summarizer_fallback"));let w=0,x=!1,T=null;for(;w<=3&&!x;){w++;try{T=await Bo(e,m,y,g,"Fast"),x=!0}catch{if(w>3){if(s==="Google")try{let k=tt("general_fallback");return(await Bo(e,k,y,g,"Fast")).text||""}catch{return""}return""}}}return T&&T.text||""},p=i(n),f=Z(r,{}),c=f[o]||{summary:"",historyLength:0};typeof c=="string"&&(c={summary:c,historyLength:0});let l=c.summary||"",u=await a(p,l);if(u){c.summary=u;let d=uc(n);return t?c.historyLength=(c.historyLength||0)+d:c.historyLength=d,f[o]=c,pe(r,f),u}return null},um=e=>{try{let n=ee.join(go,"chat-summaries.json");if(Le.existsSync(n)){let t=Z(n,{});t[e]&&(delete t[e],pe(n,t))}}catch{}},hm=async function*(e,n,t,o,s){let{profile:r,thinkingLevel:i,mode:a,janitorModel:p,chatId:f,isPlayground:c,systemSettings:l,sessionStats:u,aiProvider:d="Google",apiTier:h,wildcardTooling:g}=t,y=dn(e);if(!Xr&&d==="Google")throw new Error("AI not initialized");let m=process.env.NVIDIA_BASE_URL||t?.aiProvider==="Ollama"?!1:l?.memory!==!1,w=n[n.length-1].text,x=ee.join(go,"chat-summaries.json"),T=!1,R=n.filter(A=>A.role==="user").length===1,k=w.includes("[TITLE-UPDATE]"),S=R||k,b=w.replace(/\[TITLE-UPDATE\]/g,"").trim();b=b.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),yield{type:"status",content:"[start]"},yield{type:"status",content:"Gathering Context"},await ut.startTransaction(f,b),l?.advanceRollback&&await qn.takeInitialSnapshot(f),vt=!1;let C=null;try{let A=new AbortController;C=setInterval(()=>{vt&&(A.abort(),C&&(clearInterval(C),C=null))},400);let E=[...n.slice(0,-1)];{let Ie=Z(x,{})[f]||{summary:"",historyLength:0};if(Ie.summary&&Ie.historyLength>0){let Zt=0,ve=[];for(let Ze=0;Ze<E.length;Ze++){let We=E[Ze];(We.role==="user"||We.role==="agent"||We.role==="system")&&!String(We.id).startsWith("welcome")&&!We.isMeta&&Zt++,Zt>Ie.historyLength&&ve.push(We)}E=ve}}E=E.map(G=>{if(G.role==="user"&&G.text){let Ie=G.text.match(/\[USER\]([\s\S]*?)\[\/USER\]/);if(Ie)return{...G,text:Ie[1].trim()}}return{...G}});let I=process.env.HIGH_CONTEXT,_=255e3,v=26e4;if(I&&I!=="false"){let G=parseInt(I,10);!isNaN(G)&&G>=256e3&&G<=1e6&&(v=G,_=Math.round(G*.85))}if((d==="NVIDIA"&&(e?.includes("gpt")||e?.includes("qwen")||e?.includes("medium")||e.includes("muse"))||d==="Mistral")&&(_=122e3,v=126e3),d!=="Ollama"&&(u?.tokens||0)>_&&(yield{type:"status_history",content:"Context Limit Reached. Condensing session history..."},await xc(t,E,!0)&&(E=[],T=!0)),R&&m){let G=Z(Jt,{});Object.values(G).flat().length>5&&(yield{type:"status",content:"Condensing past chat memories"},await Tc(f,t,G))}let W=Z(Jt,{}),B=Z(In,{}),K=Object.entries(W).filter(([G])=>G!==f).flatMap(([G,Ie])=>Ie),xe=[...Object.entries(B).filter(([G])=>G!==f).slice(-20).map(([G,Ie])=>`[Chat Summary]: ${Ie}`),...K].map(G=>`- ${G}`).join(`
569
+ `),F=Z(Pt,[]).map(G=>`- ${G.memory}`).join(`
570
+ `),Q=(u?.tokens||0)>=1e4,ce=gi(xe,F,m,Q),M=new Date,P=M.getFullYear(),Y=M.toLocaleString("en-US",{month:"short"}).toUpperCase(),V=String(M.getDate()).padStart(2,"0"),_e=M.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}),Pe=`${P}-${Y}-${V}, ${_e}`,Be=[".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"],ot=G=>{try{return Le.readdirSync(G,{withFileTypes:!0})}catch{return[]}},je=(G,Ie={value:0},Zt=1)=>{if(Ie.value>6200||Zt>7)return Ie.value;let ve=ot(G);for(let Ze of ve){if(Ie.value>6200)break;Be.includes(Ze.name)||Ze.name.startsWith(".")||Ze.isDirectory()&&(Ie.value++,je(ee.join(G,Ze.name),Ie,Zt+1))}return Ie.value},ht=(G,Ie)=>l?.indentationTree!==!1?Kr(G,Ie,1,ot,Be):zr(G,Ie,"",1,ot,Be),Ft=je(process.cwd()),pt=12;Ft>3072?pt=1:Ft>2304?pt=2:Ft>1536?pt=3:Ft>768?pt=4:Ft>384?pt=6:Ft>192?pt=7:Ft>96?pt=8:Ft>48?pt=9:Ft>24&&(pt=10);let mt=Z(Xo,{}),bt=mt[f],Rt=bt?bt!==process.cwd():!1;mt[f]=process.cwd(),pe(Xo,mt);let Qe=Z(x,{}),we=Qe[f]||{summary:"",historyLength:0};typeof we=="string"&&(we={summary:we,historyLength:0});let Kt=n.filter(G=>(G.role==="user"||G.role==="agent"||G.role==="system")&&!String(G.id).startsWith("welcome")&&!G.isMeta).length;we.historyLength&&Kt<we.historyLength&&(we.summary="",we.historyLength=0,Qe[f]=we,pe(x,Qe));let Jn=typeof we=="object"?we.summary||"":we||"",Qn=E.length>0;Qn&&Jn&&E[0]&&(E[0].role==="user"||E[0].role==="system")&&(E[0].text.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")||(E[0].text=`[SYSTEM METADATA]
571
+ **CONTEXT SUMMARY OF PREVIOUS TURNS (PRIORITY: DYNAMIC)**
572
+ ${Jn}
573
+
574
+ [USER] ${E[0].text}`,yield{type:"summary_injected",content:{id:E[0].id,text:E[0].text}}));let ni=Jn&&!Qn?`
575
+ [SYSTEM METADATA]
576
+ **CONTEXT SUMMARY OF PREVIOUS TURNS**
577
+ ${Jn}
578
+ `:"",si=!!l?.dynamicDirAwareness,Oa=`${f}|${d}|${i}|${e}|${r}|${si}`,oi=!si&&Ss.key===Oa&&Ss.value?"":`
579
+ **DIRECTORY STRUCTURE**
580
+ CWD: `+process.cwd()+`${c?" [PLAYGROUND MODE]":""}
581
+ `+ht(process.cwd(),pt),Tt=await ys(),Pn="";if(Fo()&&Tt.file_focused!=="none"){Pn=`
582
+ [ADDITIONAL IDE CONTEXT]
583
+ `;let G=ee.relative(process.cwd(),Tt.file_focused),Ie=(Tt.opened_editors||[]).map(ve=>{let Ze=ee.relative(process.cwd(),ve);return Ze.startsWith("..")?`[External] ${ee.basename(ve)}`:Ze});if(Pn+=`Focused File: ${G}
584
+ Cursor Line: ${Tt.cursor_line}
585
+ `,Tt.selected){let ve=Tt.selected,Ze=ve.split(`
586
+ `);Ze.length>256&&(ve=Ze.slice(0,240).join(`
587
+ `)+`
588
+ ... [truncated] ...
589
+ `+Ze.slice(-16).join(`
590
+ `)),ve.length>2048&&(ve=ve.slice(0,1920)+`
591
+ ... [truncated] ...
592
+ `+ve.slice(-128)),Pn+=`Current Selection: "${ve}"
593
+ `}if(Tt.manual_edits){let Ze=Tt.manual_edits.split(`
594
+ `),We=[],Xe=null;for(let q of Ze)q.trim()&&(q.startsWith(" Line ")?Xe&&Xe.edits.push(q):(Xe={path:q.endsWith(":")?q.slice(0,-1):q,edits:[]},We.push(Xe)));for(let q of We)q.edits.length>80&&(q.edits=q.edits.slice(-80)),q.originalEditsCount=q.edits.length;let fe=(q,te)=>te.reduce((He,rn)=>{let Sn=Tt.file_focused&&(rn.path===Tt.file_focused||ee.resolve(process.cwd(),rn.path)===ee.resolve(Tt.file_focused))?Math.ceil(q*1.2):q;return He+Math.min(rn.edits.length,Sn)},0),Ut=80;if(fe(80,We)>300){let q=!1;for(let te=80;te>=10;te--)if(fe(te,We)<=300){Ut=te,q=!0;break}q||(Ut=10)}let Je=[...We];if(Ut===10&&fe(10,Je)>500)for(;Je.length>0&&fe(10,Je)>500;){let q=0,te=Je[0].originalEditsCount;for(let He=1;He<Je.length;He++)Je[He].originalEditsCount<te&&(te=Je[He].originalEditsCount,q=He);Je.splice(q,1)}for(let q of Je){let He=Tt.file_focused&&(q.path===Tt.file_focused||ee.resolve(process.cwd(),q.path)===ee.resolve(Tt.file_focused))?Math.ceil(Ut*1.2):Ut;q.edits.length>He&&(q.edits=q.edits.slice(-He))}for(let q of Je){let te=`${q.path}:
595
+ ${q.edits.join(`
596
+ `)}`;for(;q.edits.length>0&&te.length>4*768;)q.edits.shift(),te=`${q.path}:
597
+ ${q.edits.join(`
598
+ `)}`;te.length>4*768?q.stringRepresentation="... "+te.slice(-(4*768-4)):q.stringRepresentation=te}let en=Je.map(q=>q.stringRepresentation).join(`
599
+ `);for(;Je.length>0&&en.length>4*2048;){Je[0].edits.length>0?Je[0].edits.shift():Je.shift();for(let q of Je){let te=`${q.path}:
600
+ ${q.edits.join(`
601
+ `)}`;te.length>4*768?q.stringRepresentation="... "+te.slice(-(4*768-4)):q.stringRepresentation=te}en=Je.map(q=>q.stringRepresentation).join(`
602
+ `)}en.length>4*2048&&(en="... "+en.slice(-(4*2048-4))),Pn+=`Recent Manual Edits:
603
+ ${en}
604
+ `}Ie.length>0&&(Pn+=`All Opened Editors: ${Ie.join(", ")}`),Tt.diagnostics&&(Pn+=`
605
+ **ACTIVE FILE ERRORS**:
606
+ ${Tt.diagnostics}
607
+ `),(b.toLowerCase().includes("lint")||b.toLowerCase().includes("warning"))&&Tt.warnings&&(Pn+=`
608
+ **LINT WARNINGS**:
609
+ ${Tt.warnings}
610
+ `)}let ri=b.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),ii=/(?:\\)?@\[([^\]]+)\]/g,Go,jo=[];for(ii.lastIndex=0;(Go=ii.exec(ri))!==null;){let G=Go[0].startsWith("\\");jo.push({tag:Go[1],isEscaped:G})}let Yo=[],fo=null;for(let G=0;G<jo.length;G++){let{tag:Ie,isEscaped:Zt}=jo[G];if(!Zt)try{let ve=Ie.trim().replace(/^["']|["']$/g,""),Ze=/[:#]L?(\d+)(?:-L?(\d+))?$/i,We=ve.match(Ze),Xe=ve,fe=null,Ut=null;We&&(fe=parseInt(We[1],10),Ut=We[2]?parseInt(We[2],10):fe,Xe=ve.slice(0,We.index));let Je=ee.resolve(process.cwd(),Xe);if(Le.existsSync(Je)&&Le.statSync(Je).isFile()){let q=Xe.toLowerCase(),te=q.endsWith(".pdf"),He=q.endsWith(".docx")||q.endsWith(".doc")||q.endsWith(".ppt")||q.endsWith(".pptx")||q.endsWith(".xls")||q.endsWith(".xlsx"),rn=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(q),Bt=rn||te||He,Sn=d==="Google"||dn(e);if(Bt&&!Sn){let Ue=`\u2718 Unsupported Modality: ${ee.basename(Xe)}`,Me=115;process.stdout.isTTY&&(Me=process.stdout.columns-5||120);let gt=[Ue],Fn=Math.max(...gt.map(An=>An.length)),Un=Math.min(Fn+4,Me),ts=gt.map(An=>`${An.padEnd(Un-2).substring(0,Un-2)}`).join(`
611
+ `);yield{type:"visual_feedback",content:yn(`${ts}
612
+ `)};continue}if(fe===null&&!Bt){let Ue=0;try{Ue=Le.readFileSync(Je,"utf8").split(/\r\n|\r|\n/).length}catch{}if(Ue>300){let Me=`\u21B7 Skipped (Too Large): ${ee.basename(Xe)}`,gt=115;process.stdout.isTTY&&(gt=process.stdout.columns-5||120);let Fn=Math.min(Me.length+4,gt),Un=Me.padEnd(Fn-2).substring(0,Fn-2);yield{type:"visual_feedback",content:yn(`${Un}
613
+ `)};continue}}let Cn=fe!==null?fe:1,Zn=Ut!==null?Ut:fe!==null?fe:Cn+299;Zn-Cn>300&&(Zn=Cn+300);let ho=`path=${JSON.stringify(Xe)}, startLine=${Cn}, endLine=${Zn}`,nt=await Zs(ho,{isMultiModal:Sn}),Ye=!1,Wt="",es=null;if(typeof nt=="string"?nt.trim().startsWith("ERROR")?Ye=!0:Wt=nt:nt&&typeof nt=="object"&&nt.binaryPart?(es=nt.binaryPart,Wt=nt.text||""):Ye=!0,!Ye){let Ue="";if(rn?(Ue=`\u2714 Processed: ${ee.basename(Xe)}`,fo=es):te||He?(Ue=`\u2714 Auto-Analysed: ${ee.basename(Xe)}`,fo=es):(Ue=`\u2714 Auto-Read: ${ee.basename(Xe)}`,Yo.push(Wt)),Ue){let Me=115;process.stdout.isTTY&&(Me=process.stdout.columns-5||120);let gt=[Ue],Fn=Math.max(...gt.map(An=>An.length)),Un=Math.min(Fn+4,Me),ts=gt.map(An=>`${An.padEnd(Un-2).substring(0,Un-2)}`).join(`
614
+ `);yield{type:"visual_feedback",content:yn(`${ts}
615
+ `)}}}}}catch{}}let ai="";Yo.length>0&&(ai=`[TAGGED FILE CONTENTS] Auto Read User Tagged files by System, No need to re-read
616
+ `+Yo.join(`
617
+
618
+ `)+`
619
+ [/TAGGED FILE CONTENTS]
620
+ `);let _a=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",Ia=ri.replace(/\\(@\[[^\]]+\])/g,"$1"),La=g?`You cannot execute tools
621
+ Instead, output in chat the exact string you WOULD have produced & wait for system response
622
+ `:"",li=`[SYSTEM METADATA]
623
+ Time: ${Pe}
624
+ OS: ${_a}${l?.dynamicDirAwareness?oi:""}${Rt?`
625
+ WARNING: CWD Changed from previous: "${bt}" to current: "${process.cwd()}", write change in chat to avoid future path mismatches
626
+ `:""}${ce}${Pn}
627
+ [/METADATA]
628
+ ${ni}${i!=="Fast"&&(d==="Mistral"&&!qs(e)||i!=="xHigh"&&d==="Google")?`${d==="Mistral"&&!qs(e)||e.toLowerCase().startsWith("gemma")?`[SYSTEM] STRICTLY FOLLOW THINKING POLICY AS HIGH PRIORITY. DO NOT START A RESPONSE WITHOUT <think>...</think> [/SYSTEM]
629
+ `:""}`:""}[SYSTEM] EXACT STRUCTURED STRING '[tool:functions.ToolName(arg="value")]' IN CHAT RESPONSE [/SYSTEM]
630
+ ${ai}${La}[USER PROMPT] ${Ia.trim()} [/USER PROMPT]`.trim(),ci={role:"user",text:li};fo&&(ci.binaryPart=fo),E.forEach(G=>{G.text&&G.role==="agent"&&(G.text=G.text.replace(/(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])/gi,""),G.text=G.text.replace(/(?:<(think|thought)>|\[(think|thought)\])[^\[\n]*/gi,"").trim())}),E.push(ci),ni&&n[n.length-1]?.id&&(yield{type:"summary_injected",content:{id:n[n.length-1].id,text:li}});let kn=null,Ws=a==="Flux"?100:10;Ws=a.toLowerCase().includes("cu")?250:Ws;let wn=16;yield{type:"status",content:"Connecting"},vt=!1;let fi=[],uo=!1;for(let G=0;G<=Ws;G++){let Ie=await ir("agent",t);if(!Ie.allowed)throw new Error(Ie.reason||`Budget Exhausted for Provider (${d||"Agent"})`);let Zt=[];if(uo=!1,a==="ICU"||a==="FluxCU")try{yield{type:"status",content:"Capturing Screen"},await new Promise(Ce=>setTimeout(Ce,3e3));let he=await ia();if(he&&he.base64){let Ce="[SYSTEM] 16:9 Gridded Screen Feedback Captured. Use numeric coordinates [/SYSTEM]",oe={inlineData:{mimeType:he.mimeType,data:he.base64}};for(let st of E)Array.isArray(st.parts)&&(st.parts=st.parts.filter(Mt=>!Mt.inlineData));if(E.length>0&&E[E.length-1].role==="user"){let st=E[E.length-1];typeof st.text=="string"&&(st.text+=`
631
+
632
+ ${Ce}`,Array.isArray(st.parts)||(st.parts=[{text:st.text}]),st.parts.push(oe))}else E.push({role:"user",text:Ce,parts:[{text:Ce},oe]})}}catch(he){console.error("Vision screenshot capture error:",he)}if(l?.compression===0&&(u?.tokens||0)>v&&(E=xi(E,6)),G>0?yield{type:"status",content:"Working"}:yield{type:"status",content:"Connecting"},vt){try{let{clearPendingNudges:he}=await import("./subagent_state-LZCOZSUJ.js");he()}catch{}yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
633
+
634
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}try{let{consumePendingNudges:he}=await import("./subagent_state-LZCOZSUJ.js"),Ce=he();if(Ce&&Ce.length>0){let oe=Ce.join(`
635
+
636
+ `);E.length>0&&E[E.length-1].role==="user"?E[E.length-1].text+=`
637
+
638
+ ${oe}`:E.push({role:"user",text:oe}),yield{type:"status",content:"Subagent Update"}}}catch{}if(o){let he=await o();he&&(he.startsWith("/btw")?E.length>0&&E[E.length-1].role==="user"?E[E.length-1].text+=`
639
+
640
+ [SYSTEM] USER QUESTION. RESOLVE THIS SPECIFIC QUERY WITHIN '[ANSWER] ... [/ANSWER]' CONCISELY, NATURALLY [/SYSTEM]
641
+ [QUESTION] ${he.replace("/btw","").trim()} [/QUESTION]`:E.push({role:"user",text:`[SYSTEM] USER QUESTION. RESOLVE THIS SPECIFIC QUERY WITHIN '[ANSWER] ... [/ANSWER]' CONCISELY, NATURALLY [/SYSTEM]
642
+ [QUESTION] ${he.replace("/btw","").trim()} [/QUESTION]`}):E.length>0&&E[E.length-1].role==="user"?E[E.length-1].text+=`
643
+
644
+ [STEERING HINT, HIGH PRIORITY] ${he.trim().toUpperCase()} [/STEERING HINT]`:E.push({role:"user",text:`[STEERING HINT, HIGH PRIORITY] ${he.trim().toUpperCase()} [/STEERING HINT]`}),yield{type:"status",content:`${he.startsWith("/btw")?"Question Forwarded...":"Steering Hint Injected..."}`})}let ve,Ze=!1,We=1,Xe=1,fe="",Ut=null,Je=null,en=null,q=0,te=[],He=0,rn=!1,Bt=!1,Sn=!1,Cn=!1,Zn=!0,ho=0,nt="",Ye="",Wt=!1,es=!1,Ue=!0,Me=e,gt="";for(;We<=wn&&Xe<=wn&&!Ze&&!vt;){let he=!1;try{fe="",Zn&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},Zn=!1,Xe===1&&(nt=""));let Ce=D=>{if(!D||!D.includes("[tool:"))return D;let se="___THINK_OPEN_TAG___",H="___THINK_CLOSE_TAG___";D=D.replace("<think>",se).replace("</think>",H),D=D.replace(fc,(me,de)=>de.includes("[tool:")?de.trim():me);let j="",Re=0;for(;Re<D.length;){let me=D.indexOf("[tool:",Re);if(me===-1){j+=D.substring(Re).replace(Ea,"").replace(ba,"");break}let de=D.substring(Re,me);j+=de.replace(Ea,"").replace(ba,"");let kt=D.indexOf("]",me);if(kt===-1){j+=D.substring(me);break}j+=D.substring(me,kt+1),Re=kt+1}return D=j,D=D.replaceAll(se,"<think>").replaceAll(H,"</think>"),D},oe=E.filter(D=>(D.role==="user"||D.role==="agent"||D.role==="system")&&!String(D.id).startsWith("welcome")&&!D.isMeta&&!D.isTerminalRecord&&!(D.text&&D.text.startsWith("[TERMINAL_RECORD]"))).map((D,se,H)=>{let j=D.text||"";m||(j=j.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),D.role==="agent"&&(j=Ce(j),j=j.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),j=j.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*"));let Re=[];return Array.isArray(D.parts)&&D.parts.length>0?Re=D.parts.map(me=>{if(me.text){let de=me.text;return m||(de=de.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),D.role==="agent"&&(de=Ce(de),de=de.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),de=de.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*")),{text:de}}return me}):Re=[{text:j}],D.binaryPart&&dn(Me)&&H.slice(se+1).filter(de=>de.role==="user"&&!de.text?.startsWith("[TOOL RESULT]")).length<=2&&Re.push(D.binaryPart),{role:D.role==="user"||D.role==="system"?"user":"model",parts:Re}});for(let D=0;D<oe.length;D++){let se=oe[D],H=se.parts?.[0]?.text||"";if(se.role==="model"&&/\[tool:/i.test(H)){let j=-1;for(let Re=D+1;Re<oe.length;Re++){let me=oe[Re],de=me.parts?.[0]?.text||"";if(me.role==="user"&&de.startsWith("[TOOL RESULT]")){j=Re;break}}if(j!==-1&&j!==D+1){let[Re]=oe.splice(j,1);oe.splice(D+1,0,Re)}}}for(let D=oe.length-2;D>=0;D--){let se=oe[D],H=oe[D+1];se.role==="user"&&H.role==="user"&&(H.parts?.[0]?.text||"").trim().startsWith("[SYSTEM")&&oe.splice(D,1)}let st=[];for(let D=0;D<oe.length;D++){let se=oe[D];if(st.length===0)st.push(se);else{let H=st[st.length-1];H.role===se.role?(H.parts[0].text+=`
645
+
646
+ `+(se.parts?.[0]?.text||""),se.parts?.length>1&&H.parts.push(...se.parts.slice(1))):st.push(se)}}oe.length=0,oe.push(...st),Me=e;let Mt=`${f}|${d}|${i}|${Me}|${JSON.stringify(r)}|${!!l?.dynamicDirAwareness}|${!!l?.subAgents}`;if(Ss.key===Mt&&Ss.value)gt=Ss.value;else{let D=d==="Mistral"?!!qs(Me):!(Me||"gemma").toLowerCase().startsWith("gemma");gt=yi(r,((Me||"gemma").toLowerCase().startsWith("gemma"),i),a,l,m,R,d,d==="Google"?!0:y,D,f),l?.dynamicDirAwareness||(gt+=`
647
+ ${oi.replace(`
648
+ **DIRECTORY STRUCTURE**`,`
649
+ **DIRECTORY STRUCTURE**`)}`),Ss.key=Mt,Ss.value=gt}let Ot=oe[oe.length-1];if(Fo()&G>0){await new Promise(H=>setTimeout(H,2500)),yield{type:"status",content:"Verifying"};let D=await ys(),se=D?D.diagnostics:null;se&&Ot&&Ot.role==="user"&&Ot.parts?.[0]?.text&&(Ot.parts[0].text+=`
650
+ ${se} [/ERROR]`),yield{type:"status",content:"Working"}}if(d==="Mistral"||d==="Google"&&e?.toLowerCase().startsWith("gemma")){let se=i!=="Fast"&&(d==="Mistral"||i!=="xHigh")?". **STRICTLY MAINTAIN THINKING POLICY. DO NOT START A RESPONSE WITHOUT <think>...</think>**":"",H=`
651
+ [SYSTEM] Tool result received. Analyze output and proceed with your turn [/SYSTEM]`;Ot&&Ot.role==="user"&&Ot.parts?.[0]?.text?.startsWith("[TOOL RESULT]")&&(Ot.parts[0].text+=H)}if(l?.advanceRollback&&Ot&&Ot.role==="user"&&Ot.parts?.[0]?.text?.startsWith("[TOOL RESULT]"))try{let D=await qn.getLatestFileChanges(f);if(D&&(D.newFiles.length>0||D.modifiedFiles.length>0||D.deletedFiles.length>0)){let se=`
652
+ [SYSTEM] File Changes:
653
+ `;for(let j of D.newFiles)se+=`* ${j} (created)
654
+ `;for(let j of D.modifiedFiles)se+=`* ${j} (modified)
655
+ `;for(let j of D.deletedFiles)se+=`* ${j} (deleted)
656
+ `;se+="[/SYSTEM]",Ot.parts[0].text+=se;let H=-1;for(let j=E.length-1;j>=0;j--)if(E[j].role==="user"&&E[j].text?.startsWith("[TOOL RESULT]")){H=j;break}H!==-1&&(E[H].text+=se)}}catch{}let nn=Math.floor(Ws*(a==="Flux"?.98:.8)),Nt=G+1;Nt>=nn&&Ot&&Ot.parts?.[0]&&(Ot.parts[0].text+=`
657
+ [SYSTEM] WARNING, Turn Limit Impending: Step ${Nt}/${Ws}. Wrap up quickly/prompt user to continue. [/SYSTEM]`);let Dt=new Promise((D,se)=>{A.signal.aborted&&se(new DOMException("The user aborted a request.","AbortError")),A.signal.addEventListener("abort",()=>{se(new DOMException("The user aborted a request.","AbortError"))})});Dt.catch(()=>{});let an=oe;if(d==="Ollama")ve=$a(t.apiKey,Me,an,gt,i,a,y,A.signal,1,l?.ollamaEndpoint||"Cloud");else if(d==="OpenRouter")ve=ei(t.apiKey,Me,an,gt,i,a,y,A.signal,1);else if(d==="DeepSeek")ve=Jr(t.apiKey,Me,an,gt,i,a,y,A.signal,1.05);else if(d==="Mistral")ve=Qr(t.apiKey,Me,an,gt,i,a,y,A.signal,1);else if(d==="NVIDIA"){let D=Zr(t.apiKey,Me,an,gt,i,a,y,A.signal,1.05);ve=pc(D,Me)}else{let se=ti(t?.apiKey).models.generateContentStream({model:Me||"gemini-3-flash-preview",contents:an,config:{systemInstruction:gt,mediaResolution:"MEDIA_RESOLUTION_MEDIUM",safetySettings:[{category:Xn.HARM_CATEGORY_HARASSMENT,threshold:Vn.BLOCK_NONE},{category:Xn.HARM_CATEGORY_HATE_SPEECH,threshold:Vn.BLOCK_NONE},{category:Xn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Vn.BLOCK_NONE},{category:Xn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Vn.BLOCK_NONE}],thinkingConfig:(()=>{let H=(Me||"").toLowerCase(),j=H.includes("gemma-4")||H.startsWith("gemma"),Re=H.includes("gemini-3");if(j||Re)return j?i.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:lt.MINIMAL}:{includeThoughts:!0,thinkingLevel:lt.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:H.includes("pro")?lt.LOW:lt.MINIMAL,Low:lt.LOW,Medium:lt.MEDIUM,Standard:lt.MEDIUM,High:lt.HIGH,xHigh:lt.HIGH}[i]||lt.MEDIUM};{let me={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[i]||2048;return me===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:me}}})()}},{signal:A.signal});ve=await Promise.race([se,Dt])}fe="",Ut=null,en=null,te=[],He=0,yield{type:"model_update",content:null},Ye="",Wt=nt.length>0;let Tn="",Ko=Date.now(),os=async function*(){if(d==="Google"&&Tn){let D=Hs(Tn);for(let se of D)yield se;Tn="",Ko=Date.now()}},di=!0,rs="",xs=!1,ct=null,Hs=D=>{let se=[],H=D;for(;H.length>0;)if(xs){let j=rs+H;if(ct==="tool"||ct==="agent"){let de=ct==="tool"?"[tool:functions.":"[agent:generalist.",kt=ct==="tool"?"[tool":"[agent";if(!j.startsWith(kt)||j.length>=de.length&&!j.startsWith(de)){se.push({type:"text",content:j}),rs="",xs=!1,ct=null,H="";break}}let Re=-1,me="]";if(ct==="tool"||ct==="agent"){let de=0,kt=null,z=0,ge=!1;for(let Ke=0;Ke<j.length;Ke++){let $=j[Ke];if(kt){if($===kt){let xt=0;for(let Ne=Ke-1;Ne>=0&&j[Ne]==="\\";Ne--)xt++;xt%2===0&&(kt=null)}}else if($==='"'||$==="'"||$==="`")kt=$;else if($==="(")de++,ge=!0;else if($===")")de--;else if($==="[")z++;else if($==="]"){if(ge&&de===0&&z===1){Re=Ke;break}z--}}}else ct==="end"?me="[[END]]":ct==="kimi_section"?me="<|tool_calls_section_end|>":ct==="kimi_call"&&(me="<|tool_call_end|>"),Re=j.indexOf(me);if(Re!==-1){let de=me.length;if(!ct.startsWith("kimi")){let kt=j.substring(0,Re+de);se.push({type:"text",content:kt})}rs="",xs=!1,ct=null,H=j.substring(Re+de)}else{let de=ct.startsWith("kimi")?8192:512;j.length>de?(ct.startsWith("kimi")||se.push({type:"text",content:j}),rs="",xs=!1):rs=j,H="";break}}else{let j=H.indexOf("[tool"),Re=H.indexOf("[agent"),me=H.indexOf("[[END]]"),de=H.indexOf("<|tool_calls_section_begin|>"),kt=H.indexOf("<|tool_call_begin|>"),z=[{type:"tool",idx:j,start:"[tool",end:"]"},{type:"agent",idx:Re,start:"[agent",end:"]"},{type:"end",idx:me,start:"[[END]]",end:"[[END]]"},{type:"kimi_section",idx:de,start:"<|tool_calls_section_begin|>",end:"<|tool_calls_section_end|>"},{type:"kimi_call",idx:kt,start:"<|tool_call_begin|>",end:"<|tool_call_end|>"}].filter(ge=>ge.idx!==-1).sort((ge,Ke)=>ge.idx-Ke.idx);if(z.length>0){let ge=z[0];ge.idx>0&&se.push({type:"text",content:H.substring(0,ge.idx)}),xs=!0,ct=ge.type,rs="",H=H.substring(ge.idx)}else{let ge=["[tool","[agent","[[END]]","<|tool_calls_section_begin|>","<|tool_call_begin|>"],Ke=-1;for(let $ of ge){for(let xt=$.length-1;xt>0;xt--)if(H.endsWith($.substring(0,xt))){Ke=H.length-xt;let Ne=ge.indexOf($);Ne===0?ct="tool":Ne===1?ct="agent":Ne===2?ct="end":Ne===3?ct="kimi_section":ct="kimi_call";break}if(Ke!==-1)break}if(Ke!==-1)Ke>0&&se.push({type:"text",content:H.substring(0,Ke)}),xs=!0,rs=H.substring(Ke),H="";else{se.push({type:"text",content:H});break}}}return se},Da=ve[Symbol.asyncIterator]();for(;;){let{value:D,done:se}=await Promise.race([Da.next(),Dt]);if(se)break;if(D&&D.type==="status"){yield D;continue}let H="",j=D.candidates?.[0]?.content?.parts;if(j&&j.length>0)for(let me of j){let de=typeof me.text=="string"?me.text:me.text?parseChunkText(me.text):"";me.thought?de&&(he||(H+="<think>",he=!0),H+=de):de&&(he&&(H+="</think>",he=!1),H+=de)}else D.text&&he&&(H+="</think>",he=!1);H=Dn(H);let Re=H?H.trim().split(/\s+/).filter(Boolean).length:0;if(t&&typeof t.onTokenChunk=="function"&&t.onTokenChunk(H,Re),di&&(yield{type:"status",content:"Thinking"},di=!1),vt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
658
+
659
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(H){if(Wt){if(Ye+=H,Ye.length>=64){let z=0,ge=Math.min(nt.length,Ye.length);for(let $=ge;$>=10;$--)if(nt.endsWith(Ye.substring(0,$))){z=$;break}let Ke=Ye.substring(z);if(Ke){let xt=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(nt)?Ke.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):Ke.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(xt)if(fe+=xt,d==="Google")Tn+=xt;else{yield*os();let Ne=Hs(xt);for(let ie of Ne)yield ie}}Wt=!1,Ye=""}continue}else if(fe+=H,d==="Google")Tn+=H;else{yield*os();let z=Hs(H);for(let ge of z)yield ge}let me=mc(fe);if(me.inside){es=!0,en||(en=Date.now());let ge={Ask:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Cancel:"cancel",Await:"await",Answer:"answer",Steer:"steer",steer:"steer"}[me.toolName]||me.toolName,Ke=me.args||"",$=null;if(["write_file","update_file","view_file","read_folder","write_pdf","write_docx","search_keyword","generate_image","file_map","invoke","invoke_sync","get_progress","await","answer"].includes(ge)){let Ne=L(Ke),ie=Ne.path||Ne.targetFile||Ne.TargetFile||Ne.directory,xn=Ne.keyword,is=Ne.title||Ne.task,Bn=Ne.id||Ne.taskId,ke=Ne.timeout||Ne.time;if(xn!=null)$=String(xn).replace(ws,"");else if(ie)$=ee.basename(String(ie).replace(ws,"").replace(ga,"/"));else if(is&&(ge==="invoke"||ge==="invoke_sync"))$=String(is).replace(ws,"").substring(0,30);else if(Bn&&ge==="get_progress")$=String(Bn).replace(ws,"");else if(ke&&ge==="await"){let Ht=parseFloat(String(ke).replace(ws,""));isNaN(Ht)?$=String(ke).replace(ws,""):(Ht<5&&(Ht=5),Ht>120&&(Ht=120),$=($n=>{if($n>=60){let zo=Math.floor($n/60),Es=$n%60;return`${zo}m${Es>0?` ${Es}s`:""}`}return`${$n}s`})(Ht))}else{let Ht=Ke.match(oc);if(Ht){let qt=Ht[1].replace(ws,"");ge==="invoke"||ge==="invoke_sync"||ge==="get_progress"?$=qt.substring(0,30):$=ge==="search_keyword"||ge==="file_map"?qt:ee.basename(qt.replace(ga,"/"))}}}let xt=`${Vr[ge]||ge}${$?` ${$}`:""}`;if((ge!==Ut||$!==Je)&&(Ut=ge,Je=$,yield{type:"status",content:`${xt}`},process.stdout.isTTY)){let ie={WebSearch:"Searching",web_search:"Searching",WebScrape:"Reading",web_scrape:"Reading",ReadFile:"Reading",read_file:"Reading",ReadFolder:"Reading",read_folder:"Reading",WriteFile:"Writing",write_file:"Writing",UpdateFile:"Editing",update_file:"Editing",WritePdf:"Creating",write_pdf:"Creating",WriteDocx:"Creating",write_docx:"Creating",SearchKeyword:"Searching",search_keyword:"Searching",CodeSearch:"Searching",code_search:"Searching",Run:"Executing",Ask:"User Input Required",Memory:"Updating Memory",GenerateImage:"Generating",InvokeSync:"Sub-Agent Working",invoke_sync:"Sub-Agent Working",Invoke:"Working",invoke:"Working",GetProgress:"Checking Progress",get_progress:"Checking Progress",Cancel:"Stopping Generalist",cancel:"Stopping Generalist",Await:"Waiting",await:"Waiting",EmergencyRollback:"Rolling the Ball",Answer:"Answering Sub-Agent",answer:"Answering Sub-Agent",Steer:"Steering Sub-Agent",steer:"Steering Sub-Agent",Click:"Clicking",click:"Clicking",Drag:"Dragging",drag:"Dragging",Scroll:"Scrolling",scroll:"Scrolling",KeyboardTyping:"Typing",keyboard_typing:"Typing",KeyPress:"Pressing Key",key_press:"Pressing Key",RecaptureScreen:"Recapturing Screen",recapture_screen:"Recapturing Screen"}[ge]||"Working";process.stdout.write(`\x1B]0;${ie}...\x07`)}}if(fe.length-ho>150){ho=fe.length;let z=Ma(fe,!1),Ke=(z.match(/(?:<think>|\[think\])([\s\S]*?)(?:<\/think>|\[\/think\]|$)/gi)||[]).join("").trim(),$=Ke.split(/[.!?]\s+/),xt=new Set($),Ne=$.length>10?($.length-xt.size)/$.length:0,ie=Ke.split(/\s+/).filter(Ae=>Ae.length>0).length,xn=.6,is=.8,Bn=!1;if((d.toLowerCase().includes("google")||d.toLowerCase().includes("mistral"))&&((Me||"").toLowerCase().startsWith("gemma")||(Me||"").toLowerCase().includes("stral"))){let O={low:256,medium:1024,high:8192,max:16384,xhigh:16384}[i?.toLowerCase()]||2500;Bn=ie>O}if(Ne>xn||Bn){yield{type:"status",content:`${Ne>xn?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},Bt=!0,await new Promise(O=>setTimeout(O,3e3));break}let qt=Ra(fe).trim().split(/[.!?]\s+/),$n=new Set(qt);if((qt.length>10?(qt.length-$n.size)/qt.length:0)>is){yield{type:"status",content:"Response Loop Detected. Re-centering..."},Bt=!1,Cn=!0,await new Promise(Ae=>setTimeout(Ae,3e3));break}let Es=z.replace(Jl,"").replace(Ql,"").replace(Zl,"").replace(ec,""),Gt=Es.toLowerCase().split(/\s+/).map(Ae=>Ae.replace(tc,"")).filter(Ae=>Ae.length>0),Mn=!1;if(Gt.length>=10)for(let Ae=1;Ae<=15;Ae++){let O=Math.max(3,Math.ceil(10/Ae));if(Gt.length<Ae*O)continue;let X=Gt.slice(Gt.length-Ae),ae=X.join(" ");if(Ae>1&&ae===X.slice(0,Math.floor(Ae/2)).join(" ").repeat(2).trim())continue;let ye=!0;for(let Se=1;Se<O;Se++)if(Gt.slice(Gt.length-Ae*(Se+1),Gt.length-Ae*Se).join(" ")!==ae){ye=!1;break}if(ye){Mn=!0;break}}if(!Mn){let Ae=Es.toLowerCase().replace(nc,"");if(Ae.length>=20)for(let O=1;O<=10;O++){let X=Math.max(5,Math.ceil(16/O));if(Ae.length<O*X)continue;let ae=Ae.substring(Ae.length-O),ye=!0;for(let Se=1;Se<X;Se++)if(Ae.substring(Ae.length-O*(Se+1),Ae.length-O*Se)!==ae){ye=!1;break}if(ye){Mn=!0;break}}}if(Mn){yield{type:"status",content:"Stuttering Detected. Re-centering..."},Bt=!1,Sn=!0,await new Promise(Ae=>setTimeout(Ae,3e3));break}}let de=fe.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/gi,""),kt=Ho(de);for(;kt.length>He;){yield*os();let z=kt[He],ge=Date.now(),$={Ask:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Await:"await",await:"await",AwaitSubagent:"await",awaitSubagent:"await",Answer:"answer",answer:"answer",AnswerSubagent:"answer",answerSubagent:"answer",Steer:"steer",steer:"steer",SteerSubagent:"steer",steerSubagent:"steer",Cancel:"cancel",cancel:"cancel",Click:"click",click:"click",Drag:"drag",drag:"drag",Scroll:"scroll",scroll:"scroll",KeyboardTyping:"keyboard_typing",keyboard_typing:"keyboard_typing",KeyPress:"key_press",key_press:"key_press",RecaptureScreen:"recapture_screen",recapture_screen:"recapture_screen",EmergencyRollback:"EmergencyRollback"}[z.toolName]||z.toolName,xt=Vr[$]||z.toolName,Ne=Ts($,z.args);yield{type:"status",content:`${xt}${Ne?` ${Ne}`:""}`};let ie="";if($==="click"){let O=L(z.args);ie=`\u2714 Clicked: ${O.intendedClickText?`${O.intendedClickText}`:""}`}else if($==="drag"){let O=L(z.args);ie=`\u2714 Dragged: Cell ${O.fromGridId||""} \u2192 Cell ${O.toGridId||""}`}else if($==="scroll"){let O=L(z.args);ie=`\u2714 Scrolled: ${O.direction||"down"} (${O.amount||1})`}else if($==="keyboard_typing"){let O=L(z.args);ie=`\u2714 Typed: ${O.text?`"${O.text.length>20?O.text.substring(0,20)+"...":O.text}"`:""}`}else if($==="key_press")ie=`\u2714 Pressed Key: ${L(z.args).key||""}`;else if($==="recapture_screen")ie="\u2714 Recaptured Screen";else if($==="web_search"){let{query:O,limit:X=10,aiMode:ae=!1}=L(z.args);ie=`${O?"\u2714":"\u2718"} ${ae?"AI Search":"Searched"}: ${O?`${O}`:"No Search Query"}${ae===!1&&O?` \u2192 ${X}`:""}`}else if($==="web_scrape"){let O=L(z.args).url||null;ie=`${O?"\u2714":"\u2718"} Visited: ${O||"No Source"}`}else if($==="view_file"){let{path:O,StartLine:X,EndLine:ae,start_line:ye,end_line:Se,startLine:Ge,endLine:Oe}=L(z.args),Ee=X||ye||Ge,ne=ae||Se||Oe,ue=parseInt(Ee)||1,le=parseInt(ne)||(Ee?ue+800:800),Fe="...",et=le;try{let qe=ee.resolve(process.cwd(),O);if(Le.existsSync(qe)){let Ct=Le.readFileSync(qe,"utf8").split(`
660
+ `).length;Fe=Ct,!Ee&&!ne&&Ct>800?et=Math.min(50,Ct):et=Math.min(le,Ct)}}catch{}let Te=(O||"").toLowerCase(),De=Te.endsWith(".pdf"),rt=Te.endsWith(".docx")||Te.endsWith(".doc")||Te.endsWith(".ppt")||Te.endsWith(".pptx")||Te.endsWith(".xls")||Te.endsWith(".xlsx"),$e=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(Te);De||rt?ie=`${O.length>0?"\u2714":"\u2718"} ${O?`Analyzed: ${ee.basename(O)}`:"Analyzed: File Not Found"}`:$e?ie=`${O.length>0?"\u2714":"\u2718"} ${O?`Processed: ${ee.basename(O)}`:"Processed: File Not Found"}`:ie=`${Fe!=="..."?"\u2714":"\u2718"} Read: ${O?`${ee.basename(O)} \u2192 ${Fe!=="..."?`Lines ${ue} - ${et} of ${Fe}`:"File Not Found"}`:"File Not Found"}`}else if($==="list_files"||$==="read_folder"){let O=$==="list_files"?"List":"Browsed",X=L(z.args).path||null,ae=L(z.args).recurse||1;ie=`${X?"\u2714":"\u2718"} ${O}: ${X?`${X==="."?`./${ae>1?"*":""}`:`${X.replaceAll("\\","/")}${ae>1?`${X.endsWith("/")?"*":"/*"}`:`${X.endsWith("/")?"":"/"}`}`}`:"No Folder Selected"}`}else if($==="write_file"||$==="update_file"){let O=$==="write_file"?"Created":"Edited",X=L(z.args).path||null;ie=`${X?"\u2714":"\u2718"} ${O}: ${X.replaceAll("\\","/")||"No File Changes"}`}else if($==="write_pdf"){let O=L(z.args).path||null;ie=`${O?"\u2714":"\u2718"} Generated: ${O.replaceAll("\\","/")||"No PDF Generated"}`}else if($==="write_docx"){let O=L(z.args).path||null;ie=`${O?"\u2714":"\u2718"} Generated: ${O.replaceAll("\\","/")||"No Docx Generated"}`}else if($==="file_map"){let O=L(z.args).path;ie=`${O?"\u2714":"\u2718"} Indexed: ${O.replaceAll("\\","/")?""+O:"File Not Found"}`}else if($.toLowerCase()==="search_keyword"||$.toLowerCase()==="todo")ie="";else if($.toLowerCase()==="generate_image"){let{path:O,outputPath:X,output:ae}=L(z.args);ie=`\u2714 Generated: ${O||X||ae||"generated_image.png"}`}else if($==="invoke_sync"||$==="InvokeSync"){let O=Ts($,z.args);ie=`\u2714 Called Generalist${O?`: ${O}`:""}`}else if($==="Invoke"||$==="InvokeAsync"||$==="invoke"){let O=Ts($,z.args);ie=`\u2714 Started Generalist${O?`: ${O}`:""}`}else if($==="get_progress"||$==="GetProgress"){let O=Ts($,z.args);ie=`\u2714 Checked${O?`: ${O}`:""}`}else if($==="cancel"){let O=Ts($,z.args);ie=`\u{1F6C7} Cancelled${O?`: ${O}`:""}`}else if($==="steer"||$==="Steer"){let O=Ts($,z.args);ie=`\u2714 Steered${O?`: ${O}`:""}`}else if($==="EmergencyRollback"){let{method:O}=L(z.args);ie=O==="forceRevert"?"":"\u2714 Rollback Point Checked"}else if($==="await"||$==="Await"){let{time:O,timeout:X}=L(z.args),ae=parseFloat(X||O)||0;ae||(ae=120);let ye=Oe=>{if(Oe>=60){let Ee=Math.floor(Oe/60),ne=Oe%60;return`${Ee}m${ne>0?` ${ne}s`:""}`}return`${Oe}s`},Se=["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"];ie=`\u2714 ${Se[Math.floor(Math.random()*Se.length)]} \u2192 ${ye(ae)}`}else $==="Answer"||$==="answer"?ie="\u2714 Resolved Sub-Agent Query":$==="exec_command"||$==="ask"?ie="":ie=`Executed: ${z.toolName}`;if(yield*os(),$==="exec_command"){let{command:O}=L(z.args);if(O&&t.systemSettings&&t.systemSettings.allowExternalAccess===!1){let X=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],ae=ee.resolve(process.cwd()).substring(0,3).toLowerCase(),ye=ne=>{let ue=[],le="",Fe=null;for(let et=0;et<ne.length;et++){let Te=ne[et];Fe?(Te===Fe&&(Fe=null),le+=Te):Te==='"'||Te==="'"?(Fe=Te,le+=Te):Te==="&"&&ne[et+1]==="&"||Te==="|"&&ne[et+1]==="|"?(le.trim()&&(ue.push(le.trim()),le=""),et++):Te===";"||Te==="|"||Te==="&"?le.trim()&&(ue.push(le.trim()),le=""):le+=Te}return le.trim()&&ue.push(le.trim()),ue},Se=ne=>{let ue=[],le="",Fe=null;for(let et=0;et<ne.length;et++){let Te=ne[et];Fe?(Te===Fe&&(Fe=null),le+=Te):Te==='"'||Te==="'"?(Fe=Te,le+=Te):/\s/.test(Te)?le&&(ue.push(le),le=""):le+=Te}return le&&ue.push(le),ue},Ge=ne=>{let ue=ne.replace(/^['"]|['"]$/g,"").trim();return!ue||process.platform==="win32"&&/^\/[a-zA-Z0-9?]+$/.test(ue)?!1:X.some(le=>{if(le.source==="[a-zA-Z]:[\\\\\\/]"){let Fe=ue.match(/[a-zA-Z]:[\\\/]/i);return Fe&&Fe[0].toLowerCase()!==ae}return le.test(ue)})};if(ye(O).some(ne=>{let ue=Se(ne);if(ue.length===0)return!1;let le=ue[0].replace(/^['"]|['"]$/g,"").toLowerCase();if(["echo","printf","write-output"].includes(le)){let et=!1;return ue.some(Te=>{let De=Te.replace(/^['"]|['"]$/g,"");if(De===">"||De===">>"||De==="<")return et=!0,!1;if(De.startsWith(">")||De.startsWith("<")){let rt=De.replace(/^[><]+/,"");return Ge(rt)}return et?(et=!1,Ge(Te)):!1})}return ue.some(et=>Ge(et))})){let ne='Access Denied. Prohibited from accessing external directories while "External Workspace Access" is disabled.';t.onExecStart&&t.onExecStart(O||"No Command"),yield{type:"exec_start"},await new Promise(ue=>setTimeout(ue,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${ne}`),await new Promise(ue=>setTimeout(ue,50)),t.onExecEnd&&t.onExecEnd(),te.push({role:"user",text:`[TOOL RESULT]: ERROR: ${ne}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${ne}`},He++;continue}}t.onExecStart&&t.onExecStart(O||"No Command"),yield{type:"exec_start"}}let xn=L(z.args),is=xn.path||xn.targetPath||null;if(is){let O=t.systemSettings&&t.systemSettings.allowExternalAccess===!1,X=ee.resolve(is),ae=ee.resolve(process.cwd());if(O&&!X.startsWith(ae)){let ye="Access Denied. You are not allowed to access files outside the current workspace.";if($==="write_file"||$==="update_file"){let Ge=`\u2718 ${$==="write_file"?"Write Canceled":"Edit Canceled"}: ${xn.path||"..."}`,Oe=115;process.stdout.isTTY&&(Oe=process.stdout.columns-5||120);let Ee=Math.min(Ge.length+4,Oe),ne=`${Ge.padEnd(Ee-2).substring(0,Ee-2)}`;yield{type:"visual_feedback",content:yn(`${Ue?`
661
+ `:""}${ne}
662
+ `)},Ue=!1}te.push({role:"user",text:`[TOOL RESULT]: ERROR: ${ye}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${ye}`},He++;continue}}if(t.onToolApproval&&($==="write_file"||$==="update_file"||$==="exec_command")){let X=t.systemSettings||{},ae=X.autoExec,ye=null,Se=!1,Ge=!1,Oe=!1;if($==="exec_command"){let{command:De}=L(z.args),rt=(De||"").trim(),$e=(Ct,zt)=>{if(!zt)return!1;let ln=zt.split(",").map(Vt=>Vt.trim().toLowerCase()).filter(Boolean),it=Ct.toLowerCase();return ln.some(Vt=>it.startsWith(Vt))},qe=$e(rt,X.alwaysAskCommands),be=$e(rt,X.autoApproveCommands);if(Ge=$e(rt,X.autoDisallowCommands),qe?Se=!0:(be||X.autoApproveGit&&/^git\s+commit\b/i.test(rt))&&(ye="allow"),!Se&&!ye){if(X.networkAccess===!1){let zt=rt.trim().replace(/\s+/g," ").replace(/^['"]+|['"]+$/g,"").toLowerCase().split(" "),it=zt[0].split("/").pop().split("\\").pop().replace(/\.exe$/,""),Vt=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"]),at=!1;Vt.has(it)&&(at=!0);let ft=En=>zt.slice(1).some(bn=>En.includes(bn)),_t=En=>{let bn=zt.findIndex(On=>En.includes(On)),bs=zt.findIndex(On=>["run","exec","test"].includes(On));return bn!==-1&&!(bs!==-1&&bs<bn)};it==="git"&&ft(["clone","pull","push","fetch"])&&(at=!0),it==="go"&&ft(["get","install"])&&(at=!0),it==="npm"&&_t(["install","i","update","add"])&&(at=!0),it==="yarn"&&_t(["add","install","upgrade"])&&(at=!0),it==="pnpm"&&_t(["add","install","update"])&&(at=!0),it==="bun"&&_t(["add","install","update"])&&(at=!0),it==="deno"&&ft(["install","add"])&&(at=!0),it==="pip"&&ft(["install","download"])&&(at=!0),it==="pip3"&&ft(["install","download"])&&(at=!0),it==="cargo"&&ft(["install","add"])&&(at=!0),["bash","sh","zsh","fish"].includes(it)&&ft(["-c"])&&(at=!0),it==="cmd"&&ft(["/c"])&&(at=!0),at&&(ye="deny",Oe=!0)}!ye&&Ge&&(ye="deny")}!Se&&!ye&&ae&&(ye="allow")}else ae&&(ye="allow");let Ee=ye,ne="";ye==="deny"&&(Oe?ne="network":Ge?ne="settings":ne="prohibited");let ue=!1,le="",Fe=[],et=0,Te=!1;if(!Ee){if($==="write_file"||$==="update_file")try{let $e=L(z.args),{path:qe}=$e;if(qe){let be=ee.resolve(process.cwd(),qe),Ct=ft=>ft?ft.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,_t=>_t.toUpperCase()):"",zt=Ct(be),ln="",it=!1,Vt=await ys(),at=Ct(Vt?.file_focused);if(Vt&&at===zt&&Vt.full_content?(ln=Vt.full_content,it=!0):Le.existsSync(be)&&(ln=Le.readFileSync(be,"utf8"),it=!0),le=ln,await ut.recordFileChange(be,ln),it){let ft=ln;if($==="write_file")ft=$e.content||$e.newContent||"";else{let{patchPairs:_t,allowMultiple:En,error:bn}=Ao($e);if(bn){let At=`[TOOL RESULT]: ERROR: ${bn}`;te.push({role:"user",text:At}),await Lt("toolFailure"),t.onToolResult&&t.onToolResult("failure",$),yield{type:"tool_result",content:At,toolName:$},He++;continue}let bs=$e.allowMultiple!==void 0?$e.allowMultiple===!0||String($e.allowMultiple).toLowerCase()==="true":En;et=_t.length;let On=$o(ln,_t,{allowMultiple:bs});ft=On.content,Fe=On.results;let po=Fe.filter(At=>At.success),It=Fe.filter(At=>!At.success);if(po.length===0){let At=`[TOOL RESULT]: ERROR: Failed to apply patches to [${ee.basename(be)}].
663
+ ${It.map(Ys=>` \u2022 ${Ys.error}`).join(`
664
+ `)}`,Rs=`\u2714 Edited: ${ee.basename(be.replaceAll("\\","/"))}`,js=115;process.stdout.isTTY&&(js=process.stdout.columns-5||120);let ks=Math.min(Rs.length+4,js),mo=`${Rs.padEnd(ks-2).substring(0,ks-2)}`;yield{type:"visual_feedback",content:yn(`${Ue?`
665
+ `:""}${mo}`)},Ue=!1,te.push({role:"user",text:At}),await Lt("toolFailure"),t.onToolResult&&t.onToolResult("failure",$),yield{type:"tool_result",content:At,toolName:$},He++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${ee.basename(be)}`},Yr(be,ln,ft),ue=!0,await new Promise(_t=>setTimeout(_t,50))}else if($==="write_file"){let ft=$e.content||$e.newContent||"",_t=ft.endsWith(`
666
+ `)?ft:ft+`
667
+ `;Le.existsSync(be)||(Te=!0,Le.mkdirSync(ee.dirname(be),{recursive:!0}),Le.writeFileSync(be,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${ee.basename(be)}`},Yr(be,"",_t),ue=!0,await new Promise(En=>setTimeout(En,50))}}}catch($e){console.error("Simulation/Diff Error:",$e)}let De=null;jr($e=>{De=$e});let rt=t.onToolApproval;if(Ee=await new Promise(async $e=>{let qe=setInterval(()=>{De&&(Uo.onIDEApproval&&Uo.onIDEApproval(De),clearInterval(qe),$e(De))},100);try{let be=await rt($,z.args);clearInterval(qe),$e(be)}catch{clearInterval(qe),$e("deny")}}),jr(null),$==="write_file"||$==="update_file"){let{path:$e}=L(z.args);if($e){let qe=ee.resolve(process.cwd(),$e);if(pa(qe,Ee),Ee==="deny"&&Te&&Le.existsSync(qe))try{Le.unlinkSync(qe)}catch{}}}Ee==="deny"&&(ne="user")}if(Ee==="allow"&&ue&&Fo()){let{path:De}=L(z.args),rt=ee.resolve(process.cwd(),De),$e=It=>It?ee.resolve(It).replace(/\\/g,"/").toLowerCase():"",qe=await ys(),be="";qe&&qe.file_focused&&$e(qe.file_focused)===$e(rt)&&qe.full_content&&(be=qe.full_content),!be&&Le.existsSync(rt)&&(be=Le.readFileSync(rt,"utf8"),be||(await new Promise(It=>setTimeout(It,100)),be=Le.readFileSync(rt,"utf8")));let Ct=be.split(/\r?\n/),zt=Ct.length,ln=Buffer.byteLength(be,"utf8"),it="";le&&(it=`Old File contents:
668
+ ${le.split(/\r?\n/).map((At,Rs)=>`${Rs+1} | ${At}`).join(`
669
+ `)}
670
+
671
+ `);let Vt="";if(zt<=100)Vt=Ct.join(`
672
+ `);else{let It=Ct.slice(0,50).join(`
673
+ `),At=Ct.slice(-50).join(`
674
+ `);Vt=`${It}
675
+
676
+ ... [${zt-100} lines truncated for history stability] ...
677
+
678
+ ${At}`}let at="";if($==="update_file"){let It=Mo(le,be,Fe,12,t?.compressToolResults||Uo?.systemSettings?.compressToolResults);at=`SUCCESS: File [${De}] updated via IDE Companion (May have user edits). [${Fe.length}/${et}] blocks applied.
679
+
680
+ ${It}`}else{let It=be.split(/\r?\n/),At=It.length,Rs=Buffer.byteLength(be,"utf8"),js="";le&&(js=`Old File contents:
681
+ ${le.split(/\r?\n/).map((Ys,Ga)=>`${Ga+1} | ${Ys}`).join(`
682
+ `)}
683
+
684
+ `);let ks="";if(At<=100)ks=It.join(`
685
+ `);else{let mo=It.slice(0,50).join(`
686
+ `),Ys=It.slice(-50).join(`
687
+ `);ks=`${mo}
688
+
689
+ ... [${At-100} lines truncated] ...
690
+
691
+ ${Ys}`}at=`SUCCESS: File [${De}] saved via IDE Companion (May have user edits).
692
+ - Stats: [${At} lines, ${(Rs/1024).toFixed(1)} KB]
693
+ ${js}- Content Preview:
694
+
695
+ ${ks}`}let _t=`${De?"\u2714":"\u2718"} ${$==="write_file"?"Created":"Edited"}: ${De.replaceAll("\\","/")||"No File Changes"}`,En=115;process.stdout.isTTY&&(En=process.stdout.columns-5||120);let bn=Math.min(_t.length+4,En),bs=`${_t.padEnd(bn-2).substring(0,bn-2)}`;yield{type:"visual_feedback",content:yn(`${Ue?`
696
+ `:""}${bs}`)},Ue=!1;let On=Date.now();q=On,yield{type:"tool_time",content:On-ge};let po=`[TOOL RESULT]: ${at}`;te.push({role:"user",text:po}),rn=!0,await Lt("toolSuccess"),t.onToolResult&&t.onToolResult("success",$),yield{type:"tool_result",content:at,aiContent:po,toolName:$},He++;continue}if(Ee==="deny"){let De=`Permission Denied: Prohibited ${$==="exec_command"?"Command":"file edit"}.`;if(ne==="user"?De="Permission Denied by User":ne==="settings"?De="Permission Denied by User Policy":ne==="network"?De="Permission Denied: Sandbox Network Access Disabled by User Policy.":ne==="prohibited"&&$==="exec_command"&&(De="Permission Denied: Prohibited Command in User Policy"),$==="write_file"||$==="update_file"){let $e=`\u2718 ${$==="write_file"?"Write Cancelled":"Edit Denied"}: ${L(z.args).path.replaceAll("\\","/")||"..."}`,qe=115;process.stdout.isTTY&&(qe=process.stdout.columns-5||120);let be=Math.min($e.length+4,qe),Ct=`${$e.padEnd(be-2).substring(0,be-2)}`,zt=` ${" ".repeat(be)} `;yield{type:"visual_feedback",content:yn(`${Ue?`
697
+ `:""}${Ct}
698
+ `)},Ue=!1}$==="exec_command"&&(await new Promise(rt=>setTimeout(rt,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${De}`),await new Promise(rt=>setTimeout(rt,50)),t.onExecEnd&&t.onExecEnd()),te.push({role:"user",text:`[TOOL RESULT]: DENIED: ${De}`}),yield{type:"tool_result",content:`[TOOL RESULT]: DENIED: ${De}`},await Lt("toolDenied"),t.onToolResult&&t.onToolResult("denied",$),He++;continue}}if(ie){let O=115;process.stdout.isTTY&&(O=process.stdout.columns-5||120);let X=Math.min(ie.length+4,O),ae=`${ie.padEnd(X-2).substring(0,X-2)}`;yield{type:"visual_feedback",content:yn(`${Ue?`
699
+ `:""}${ae}${ie.includes("\u2714")&&(ie.includes("Created")||ie.includes("Edited"))?"":`
700
+ `}`)},Ue=!1}if(q>0){let O=Date.now()-q,X=Math.max(0,1e3-O);X>0&&await new Promise(ae=>setTimeout(ae,X))}let Bn={chatId:f,history:n,onChunk:O=>t.onExecChunk?t.onExecChunk(O):null,onAskUser:t.onAskUser,systemSettings:t.systemSettings,mode:a,isMultiModal:dn(Me),onVisualFeedback:t.onVisualFeedback,onSubagentUpdate:t.onSubagentUpdate,onTokenChunk:t.onTokenChunk,modelName:Me,aiProvider:t.aiProvider,apiKey:t.apiKey,onUsage:t.onUsage};if($==="write_file"||$==="update_file")try{let{path:O}=L(z.args);if(O){let X=ee.resolve(process.cwd(),O),ae=await ys();ae&&ae.file_focused===X&&ae.full_content&&(Bn.forcedContent=ae.full_content)}}catch{}Zt.push($);let ke=await ao($,z.args,Bn);if(($==="write_file"||$==="update_file")&&ke.startsWith("SUCCESS")){let{path:O}=L(z.args);if(O){let X=ee.resolve(process.cwd(),O);ha(X)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let Ht=Date.now();q=Ht,yield{type:"tool_time",content:Ht-ge},en=Ht;let qt=null;if(typeof ke=="object"&&ke.binaryPart&&(qt=ke.binaryPart,ke=ke.text),$==="search_keyword"){let{keyword:O,path:X}=L(z.args),ae=typeof ke=="string"&&ke.startsWith("[GLOB]");ae&&(ke=ke.slice(6).trimStart());let ye=typeof ke=="string"&&ke.startsWith("[DIR]");ye&&(ke=ke.slice(5).trimStart());let Se=0;if(ke){let Fe=ke.match(/Found (\d+) match/i);Fe&&(Se=parseInt(Fe[1]))}let Ge=X?X.replace(/[\/\\]+$/,""):null,Oe=Ge&&Ge!=="."?`"${ae?X:ye?`${Ge}/*`:Ge}"`:"./",Ee=`${O?"\u2714":"\u2718"} Searched: "${O||""}" in ${Oe.replaceAll("\\","/")} \u2192 ${Se} Match${Se===1?"":"es"}`,ne=115;process.stdout.isTTY&&(ne=process.stdout.columns-5||120);let ue=Math.min(Ee.length+4,ne),le=`${Ee.padEnd(ue-2).substring(0,ue-2)}`;yield{type:"visual_feedback",content:yn(`${Ue?`
701
+ `:""}${le}
702
+ `)},Ue=!1}if($==="EmergencyRollback"){let{method:O}=L(z.args);if(O==="forceRevert"){let X=0;if(ke){let Ee=ke.match(/Total\s*:\s*(\d+)/i);Ee&&(X=parseInt(Ee[1]))}let ye=ke&&ke.startsWith("ERROR:")?"\u2718 Emergency Rollback Failed":`\u2714 Emergency Rollback \u2192 ${X} file${X===1?"":"s"} processed`,Se=115;process.stdout.isTTY&&(Se=process.stdout.columns-5||120);let Ge=Math.min(ye.length+4,Se),Oe=`${ye.padEnd(Ge-2).substring(0,Ge-2)}`;yield{type:"visual_feedback",content:yn(`${Ue?`
703
+ `:""}${Oe}
704
+ `)},Ue=!1}}if($==="todo"){let{method:O,tasks:X,markDone:ae}=L(z.args),ye="",Se=[],Ge=Oe=>{if(!Oe)return[];let Ee=Array.isArray(Oe)?Oe:[];if(Ee.length===0&&typeof Oe=="string"){let ne=Oe.trim();if(ne.startsWith("[")&&ne.endsWith("]")){let ue=ne.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);ue?Ee=ue.map(le=>le.slice(1,-1).replace(/\\(.)/g,"$1")):Ee=ne.slice(1,-1).split(",").map(le=>le.trim()).filter(Boolean)}else Ee=Oe.split(`
705
+ `)}return Ee.filter(ne=>String(ne).trim()).map(ne=>{let ue=String(ne).trim();return ue.startsWith("- [")?ue.substring(6).trim():ue})};if(O==="create"?(ye="\x1B[32m\u2192\x1B[0m Created Plan",Se=Ge(X).map(Oe=>`\x1B[90m\u25CB\x1B[0m ${Oe}`)):O==="append"?(ye="\x1B[34m\u2795\x1B[0m Added Plan",Se=Ge(X).map(Oe=>`\x1B[90m\u25CB\x1B[0m ${Oe}`)):O==="get"&&(ye=ae?"\x1B[36m\u21BB\x1B[0m Updated Plan":"\x1B[35m\u2022\x1B[0m Reviewed Plan",Se=(ke||"").split(`
706
+ `).slice(1).join(`
707
+ `).split(`
708
+ `).filter(Ee=>Ee.trim().startsWith("- [")).map(Ee=>{let ne=Ee.trim(),ue=ne.startsWith("- [x]");return`${ue?"\x1B[32m\u2714\x1B[0m":"\x1B[90m\u25CB\x1B[0m"} ${ue?"\x1B[90m":"\x1B[37m"}${ne.substring(6).trim()}\x1B[0m`})),ye&&Se.length>0){let Oe=[`${ye}`,...Se.map(Ee=>` ${Ee}`)].join(`
709
+ `);yield{type:"visual_feedback",content:yn(`${Ue?`
710
+ `:""}${Oe}
711
+ `)},Ue=!1}}$==="exec_command"&&t.onExecEnd&&(await new Promise(O=>setTimeout(O,800)),t.onExecEnd());let $n=ke&&ke.startsWith("DENIED:");ke&&!ke.startsWith("ERROR:")&&!$n?(await Lt("toolSuccess"),t.onToolResult&&t.onToolResult("success",$)):$n||(await Lt("toolFailure"),t.onToolResult&&t.onToolResult("failure",$));let Gt=(ke||"").toString().replaceAll("[UI_CONTEXT]","");Gt.includes("[[VERIFIED]]")&&(Gt=Gt.replace(/\[\[VERIFIED\]\][\s\S]*?\[\[\/VERIFIED\]\]/g,`[SYSTEM NOTE]: Patch Block matched & applied successfully. Large Block omitted to conserve context.
712
+ `));let Mn;if(Gt.startsWith("[[SAME]]")){let X=Gt.replace(/^\[\[SAME\]\]\s*\r?\n?/,"").split(/\r?\n/),ae=X.filter(Se=>Se.startsWith("SUCCESS:")||Se.trim().startsWith("- Stats:"));Mn=`[TOOL RESULT]: ${ae.length>0?ae.join(`
713
+ `):X.slice(0,2).join(`
714
+ `)}
715
+ [SYSTEM NOTE]: Content verified and persisted to disk. Full preview omitted to conserve context.`}else Mn=`[TOOL RESULT]: ${Gt}`;te.push({role:"user",text:Mn,binaryPart:qt}),rn=!0;let Ae=`[TOOL RESULT]: ${ke.replaceAll(`[[VERIFIED]]
716
+ `,"").replaceAll(`
717
+ [[/VERIFIED]]`,"")||""}`;($==="view_file"||$==="web_scrape"||$==="file_map")&&(Ae=`[TOOL RESULT]: ${ie} (Context Locked for UI Clarity)`),yield{type:"tool_result",content:Ae,aiContent:Mn,binaryPart:qt,toolName:$},$==="memory"&&ke.includes("SUCCESS")&&(yield{type:"memory_updated"}),He++}if(d==="Google"&&Tn&&Date.now()-Ko>=150){yield*os();let z=Hs(Tn);for(let ge of z)yield ge;Tn="",Ko=Date.now()}}D.usageMetadata&&(kn=D.usageMetadata),kn&&(yield{type:"liveTokens",content:kn.totalTokenCount})}if(he&&(he=!1,Wt?Ye+="</think>":(fe+="</think>",d==="Google"?Tn+="</think>":yield{type:"text",content:"</think>"})),Wt&&Ye.length>0){let D=0,se=Math.min(nt.length,Ye.length);for(let j=se;j>0;j--)if(nt.endsWith(Ye.substring(0,j))){D=j;break}let H=Ye.substring(D);if(H){let Re=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(nt)?H.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):H.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(Re)if(fe+=Re,d==="Google")Tn+=Re;else{yield*os();let me=Hs(Re);for(let de of me)yield de}}Wt=!1,Ye=""}if(yield*os(),vt)break;let Gs=(fe||"").trim(),Pa=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(Gs.toLowerCase())||/\[\[END\]\]/i.test(Gs.toLowerCase()),Fa=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(Gs.toLowerCase()),Ua=te.length>0||Ut!==null,qo=Gs.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/gi,"").trim(),Ba=/(\p{Emoji_Presentation}|\p{Extended_Pictographic})$/u.test(qo),Wa=/([.!?"'*_`|\]\)”’~~]+|\s|`{3}|[\u200B-\u200D\uFEFF])$/u.test(qo.trim()),Ha=/[.!?}"'`’“”]$|```$/s.test(qo)||Wa||Ba;!Pa&&!Fa&&!Ua&&Gs.length>0,Ze=!0,await Lt("agent",d)}catch(Ce){if(vt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
718
+
719
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(String(Ce).includes("Incomplete JSON segment at the end")){he&&(he=!1,Wt?Ye+="</think>":(fe+="</think>",yield{type:"text",content:"</think>"})),Ze=!0,await Lt("agent",d);break}if(he&&(he=!1,Wt?Ye+="</think>":fe+="</think>"),Wt&&Ye.length>0){let ss=0,nn=Math.min(nt.length,Ye.length);for(let Dt=nn;Dt>0;Dt--)if(nt.endsWith(Ye.substring(0,Dt))){ss=Dt;break}let Nt=Ye.substring(ss);if(Nt){let an=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(nt)?Nt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):Nt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");an&&(fe+=an)}Wt=!1,Ye=""}let oe=Ce instanceof Error?(()=>{try{return JSON.parse(JSON.parse(Ce.message).error.message).error.message}catch{return String(Ce)}})():String(Ce),st=new Date().toLocaleString(),Mt=ee.join(cn,"agent");Le.existsSync(Mt)||Le.mkdirSync(Mt,{recursive:!0}),Le.appendFileSync(ee.join(Mt,"error.log"),`ERROR [${st}]: ${oe}
720
+
721
+ ----------------------------------------------------------------------
722
+
723
+ `);let tn=Ce.status||Ce.statusCode||Ce.code;if(!(tn&&(tn>=500&&tn<600||tn===408||tn===429)||!tn&&(/status[ :]+(5\d\d|408|429)/i.test(String(Ce))||/code[ :]+(5\d\d|408|429)/i.test(String(Ce))||/(500|503|408|429)/.test(String(Ce))))){if(We<wn-3)throw Ce;yield{type:"text",content:oe},yield{type:"status",content:"Error Occured"}}if(fe.trim().length>0||Xe>1)if(Xe<=wn){Xe++;let ss=Math.min(1e3*Math.pow(2,Xe-1),24e3);if(fe.trim().length>0){E.push({role:"agent",text:fe});let nn=`[SYSTEM]
724
+ - SEAMLESS CONTINUATION: Resume immediately. Pick up from last words with zero gap/disruption
725
+ - NO REPETITION: Do not repeat any text already written
726
+ - NO RE-THINK: Do not restart or open <think> if reasoning already started. Continue the thinking and close thinking block </think> BEFORE CHAT OUTPUT
727
+ - MID-TOOL SAFETY: If cutoff was mid-tool call, restart that tool call from start
728
+ - STEALTH: Do not mention/apologize for cutoff [/SYSTEM]`;te.length>0?te.forEach((Nt,Dt)=>{Dt===te.length-1?E.push({...Nt,text:`${Nt.text}
729
+
730
+ ${nn}`}):E.push(Nt)}):E.push({role:"user",text:nn}),nt+=fe}for(let nn=ss/1e3;nn>0&&!vt;nn--)yield{type:"status",content:`Error Occured. Recovering Stream (${Xe}/${wn}) [Retrying in ${nn.toFixed(0)}s]...`},await new Promise(Nt=>setTimeout(Nt,1e3));yield{type:"status",content:"Error Occured. Recovering Stream..."}}else throw new Error(`Stream collapsed too many times. (Failed to resolve ${wn} times)
731
+ Error log can be found in \`/export logs\``);else if(We<=wn){We++,Xe=1,nt="";let ss=Math.min(1e3*Math.pow(2,We-1),32e3),nn=.8+Math.random()*.4,Nt=Math.round(ss*nn);Zn=!0,yield{type:"status",content:`Trying to reach ${e} (${We}/${wn}) [Retrying in ${(Nt/1e3).toFixed(0)}s]`};for(let Dt=Nt/1e3;Dt>0&&!vt;Dt--)yield{type:"status",content:`Trying to reach ${e} (${We}/${wn}) [Retrying in ${Dt.toFixed(0)}s]`},await new Promise(an=>setTimeout(an,1e3));yield{type:"status",content:`Trying to reach ${e}`}}else throw new Error(`Model ${e} cannot be reached. (Failed ${wn} times)
732
+ Error log can be found in \`/export logs\``)}}if(kn){let he=kn.totalTokenCount||0,Ce=kn.cachedContentTokenCount||0,oe=(kn.candidatesTokenCount||0)+(kn.thoughtsTokenCount||0);await jt("tokens",he,d,Me),Ce>0&&await jt("cachedTokens",Ce,d,Me),oe>0&&await jt("candidateTokens",oe,d,Me),yield{type:"usage",content:kn}}fi.push(fe);let Fn=fe;fe.match(/(?:<think>|\[think\])([\s\S]*?)(?:<\/think>|\[\/think\])/i)&&(Fn=fe.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/i,""));let ts=Ra(fe),An=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(ts.toLowerCase())||/\[\[END\]\]/i.test(ts.toLowerCase())||!0,bc=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(ts.toLowerCase()),Rc=He>0;yield{type:"status",content:"Thinking"};let va=gc(fe,/(\[\s*(turn\s*:)?\s*(continue|finish)\s*\]|\[\[END\]\])/gi,"").trim(),ns=(An||te.length===0)&&!Bt&&!Sn&&!Cn;if(ns=te.length===0?ns:!1,ns=es||uo?!1:ns,fe&&fe.trim().endsWith('")]')&&te.length===0&&(ns=!1),ns){let he=fi.join(`
733
+ `),Ce=he.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").trim();yield{type:"interactive_turn_finished",data:{agentText:b,fullAgentTextRaw:he,history:[...E],needTitle:S}},E.length>0&&E[E.length-1].role==="agent"?E[E.length-1].text=Ce:E.push({role:"agent",text:Ce}),E.forEach(oe=>{if(oe.role==="user"&&oe.text&&(oe.text=oe.text.replace(/\n\[COMPILE ERROR\][\s\S]*?\[\/ERROR\]/g,""),oe.text=oe.text.replaceAll(`
734
+
735
+ [SYSTEM] USER QUESTION. RESOLVE THIS SPECIFIC QUERY WITHIN '[ANSWER] ... [/ANSWER]' CONCISELY, NATURALLY [/SYSTEM]
736
+ `,"").replaceAll(`[SYSTEM] USER QUESTION. RESOLVE THIS SPECIFIC QUERY WITHIN '[ANSWER] ... [/ANSWER]' CONCISELY, NATURALLY
737
+ **STRICTLY FOLLOW THINKING POLICY AS HIGH PRIORITY. DO NOT START A RESPONSE WITHOUT <think>...</think>** [/SYSTEM]
738
+ `,"").replaceAll(`[SYSTEM] **STRICTLY FOLLOW THINKING POLICY AS HIGH PRIORITY. DO NOT START A RESPONSE WITHOUT <think>...</think>** [/SYSTEM]
739
+ `,"").replaceAll(/\n\[SYSTEM\] WARNING, Turn Limit Impending: Step \d+\/\d+\. Wrap up quickly\/prompt user to continue & use \[\[END\]\] quickly\. \[\/SYSTEM\]/g,""),oe.text=oe.text.replaceAll(/\n\[SYSTEM\] File Changes:\n(?:\* .+ \(created|modified|deleted\)\n)*\[\/SYSTEM\]/g,""),(d==="Mistral"||d==="Google"&&e?.toLowerCase().startsWith("gemma"))&&oe.text.startsWith("[TOOL RESULT]"))){let Mt=`
740
+ [SYSTEM] Tool result received. Analyze output and proceed with your turn [/SYSTEM]`,tn=`
741
+ [SYSTEM] Tool result received. Analyze output and proceed with your turn. **STRICTLY MAINTAIN THINKING POLICY. DO NOT START A RESPONSE WITHOUT <think>...</think>** [/SYSTEM]`;oe.text=oe.text.replaceAll(tn,"").replaceAll(Mt,"").trim()}}),yield{type:"status",content:"[end]"}}if(ns)break;let Na=va.trim()||"*Working...*";if(E.push({role:"agent",text:Na}),te.length>0||rn){if(te.length>0){let he=te.map(Mt=>Mt.text).join(`
742
+
743
+ `),oe=(fe.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/gi,"").match(/\[tool:functions/g)||[]).length;if(te.length<oe){he+=`
744
+
745
+ [SYSTEM] Only ${te.length} out of ${oe} attempted tool calls were executed. Verify proper schema compliance & try failed calls again [/SYSTEM]`;let Mt=oe-te.length;for(let tn=0;tn<Mt;tn++)await Lt("toolFailure")}let st=te.find(Mt=>Mt.binaryPart)?.binaryPart||null;E.push({role:"user",text:he,binaryPart:st})}}else uo||es?(E.push({role:"user",text:"[SYSTEM] Failed to execute some tools. Verify proper schema compliance & try again [/SYSTEM]"}),await Lt("toolFailure")):E.push({role:"user",text:`[SYSTEM] ${Sn&&!Bt?"STUTTERING DETECTED by Internal System. Re-calibrate your response & proceed.":`${Bt?" OVER THINKING":" LOOP"} DETECTED by Internal System${Bt?" for current EFFORT_LEVEL":""}. ${Bt?"If you have planned the task, prioritize execution/output":"If you have finished your task provide a simple summary and end"}`} [/SYSTEM]`}),Bt=!1,Sn=!1,Cn=!1;l?.advanceRollback&&await qn.recordTurnDelta(f,G+1,Zt),uo=He>0||rn}}catch(A){let I=(A instanceof Error?(()=>{try{return JSON.parse(JSON.parse(A.message).error.message).error.message}catch{return A.message||String(A)}})():String(A)).replace(/^(Error:\s*)+/i,""),_=new Date().toLocaleString(),v=ee.join(cn,"agent");yield{type:"text",content:`\u2726 CRITICAL ERROR: ${I.includes("fetch failed")?"Failed to Connect. Check your Internet Connection or Wait a moment":I}
746
+ \u2800`},Le.existsSync(v)||Le.mkdirSync(v,{recursive:!0}),Le.appendFileSync(ee.join(v,"error.log"),`CRITICAL ERROR [${_}]: ${A}
747
+
748
+ ----------------------------------------------------------------------
749
+
750
+ `),typeof flushGoogleBuffer=="function"&&(yield*flushGoogleBuffer()),yield{type:"tool_result",content:`ERROR: [INTERNAL CRITICAL] ${I}`}}finally{C&&(clearInterval(C),C=null),typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),await ut.commitTransaction(),l?.advanceRollback&&await qn.cleanup(f),await ys()}yield{type:"status",content:null}},pm=async(e,n,t=null,o=null,s=50,r=null,i=!1)=>{let a=await Qt(),p={...a,...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(":","-")}`,h=(A=>{if(!A)return null;let E=A.toLowerCase();return E==="google"?"Google":E==="deepseek"?"DeepSeek":E==="openrouter"?"OpenRouter":E==="nvidia"?"NVIDIA":E==="mistral"?"Mistral":E==="ollama"?"Ollama":null})(c),g=p?.systemSettings?.CustomSubAgent?p?.systemSettings?.SubAgentModel:null,y=p?.systemSettings?.CustomSubAgent?p?.systemSettings?.SubAgentProvider:null,m=null;if(g==="ENV"?(m=f,f&&h&&(p.aiProvider=h)):g&&g!=="Default"?(m=g,y&&(p.aiProvider=y)):f&&h&&(p.aiProvider=h),p.aiProvider){let A=await Jo(p.aiProvider);A&&(p.apiKey=A)}let w=A=>{if(!A||typeof A!="string")return{allowed:!0};let E=[/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 I of E)if(I.test(A))return{allowed:!1,reason:`Blocked potentially destructive or unsafe command pattern: "${I.source}"`};return{allowed:!0}},x=t||m||n?.modelName||n?.activeModel||a.activeModel,T=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",R=`-- TOOL DEFINITIONS (path = relative to CWD, path separator: '/') --
751
+ TO USE TOOLS, MUST OUTPUT EXACTLY '[tool:functions.ToolName(arg1="value1")]' STRUCTURED STRING IN CHAT RESPONSE \u2190 MANDATORY
752
+ TOOL RULES:
753
+ - JSON ESCAPE ALL LITERAL ESCAPE SEQUENCES IN TOOL ARGUMENTS
754
+ - SAME file, MULTIPLE edits? ONE PatchFile (\u226415 blocks) \u2190 PRIORITY
755
+ - Need text or huge files? CodeSearch > Full Read
756
+ - MUST AVOID UNNECESSARY LARGE-FILE CHUNK READS
757
+ - Restricted Shell Access, No Deletion
758
+ - DONT HALLUCINATE TOOL RESULTS, VERIFY, FIX ERRORS
759
+ - ONLY valid tools and syntax defined below are allowed
760
+ - Stuck on syntax error? Move-on & Report > Time waste
761
+
762
+ **PROVIDED TOOLS (STRING BASED PROTOCOL)**
763
+ -- Communication Tools --
764
+ - [tool:functions.Ask(question="...", optionA="title::description", ...MAX4)]. Communicate with USER. Ambiguity: MUST for path divergence, security risk. Ask, don't finish/guess. Suggest best options; no preferences. Keep titles short
765
+ ${i?'- [tool:functions.AskMain(question="...")]. Communicate with PARENT/MAIN AGENT. When clarification/decision is needed for a task':""}
766
+
767
+ -- Web Tools --
768
+ - [tool:functions.WebSearch(query="...", aiMode="bool", limit="integer 3-10 aiMode: exclude")]. Usage: unknown info/docs. aiMode: LLM search
769
+ - [tool:functions.WebScrape(url="...")]. Proactive use for specific webpage/docs/api
770
+
771
+ -- Workspace Tools --
772
+ - [tool:functions.CodeSearch(keyword="...", path="dir/file/glob/regex, inclusion/exclusion ;-separated", fuzzy="bool false", regex="bool auto")]. Find definitions, logic, relevant code, standard junk auto-excluded
773
+ - [tool:functions.ReadFolder(path="...", recurse="integer 1-3")]. Minimize recursion
774
+ - [tool:functions.ReadFile(path="...", startLine="integer", endLine="integer")]. View files
775
+ - [tool:functions.PatchFile(path="...", allowMultiple="bool, default: false", searchContent1="search string OR ^LINE:start..end$", newContent1="...", ...MAX15)]. TARGET MINIMAL searchContent. Line Ranges MUST for large searchContent AND escape sequences. ^...$ MUST for line ranges
776
+ - [tool:functions.WriteFile(path="...", content="...")]. Creates/Overwrites. File Exist? PatchFile > WriteFile. VERIFY IMPORTS
777
+ - [tool:functions.Run(command="...")]. Runs ${T==="Windows"?Gn()?"WINDOWS POWERSHELL":"WINDOWS CMD":"BASH"} command. Destructive/Irreversible ops \u2192 Ask user`.trim(),k=`=== START SYSTEM PROMPT ===
778
+ You are a subagent helping the main FluxFlow CLI agent
779
+ Your task is: "${e}"
780
+
781
+ ${R.trimEnd()}
782
+
783
+ -- THINKING GUIDANCE --
784
+ NO EXPLICIT THINKING REQUIRED. FOCUS ON TASK COMPLETION
785
+ Keep main focus on tools and task, not chatting
786
+ On task completion, provide a detailed structured summary preferebly in Tables/Bullet Points with file modified info, if any task failed report back in detail, NO HALLUCINATIONS
787
+
788
+ CWD: ${process.cwd()}
789
+ Current Time: ${u}
790
+ === END SYSTEM PROMPT ===`,S=[{role:"user",text:`Complete this task: ${e}`}],b=0,C="";for(;b<s;){if(vt){if(n?.taskId&&typeof ze<"u"){let N=ze.find(F=>F.id===n.taskId);N&&(N.status="cancelled")}throw r&&r("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}if(n?.taskId&&typeof ze<"u"){let N=ze.find(F=>F.id===n.taskId);if(N&&N.status==="cancelled")throw r&&r("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}let A=S.map(N=>({role:N.role==="user"?"user":"model",parts:[{text:N.text}]}));r&&r(`[Subagent Turn ${b+1}]...`);let _=((await Bo(p,x,A,k,"Fast")).text||"").replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/gi,"").trim();C=_,r&&r(`[Subagent Response]
791
+ ${_}
792
+ `),S.push({role:"agent",text:_});let v=Ho(_);if(v.length===0)break;let W=v.filter(N=>N.toolName.toLowerCase()==="askmain"||N.toolName.toLowerCase()==="ask_main"),B=!1,K="";for(let N of v){if(vt){if(n?.taskId&&typeof ze<"u"){let M=ze.find(P=>P.id===n.taskId);M&&(M.status="cancelled")}throw new Error("Subagent task was cancelled.")}if(n?.taskId&&typeof ze<"u"){let M=ze.find(P=>P.id===n.taskId);if(M&&M.status==="cancelled")throw new Error("Subagent task was cancelled.")}let F=N.toolName.toLowerCase();if(F==="askmain"||F==="ask_main"){if(B)continue;B=!0;let M="";if(W.length===1?M=L(W[0].args).question||W[0].args:M=W.map((P,Y)=>{let V=L(P.args);return`Q${Y+1}: ${V.question||P.args}`}).join(`
793
+ `),n.onAskMain){r&&r(`[Executing Tool] AskMain("${M}")...`);let P=await n.onAskMain(M);r&&r(`[Tool Result]
794
+ Answer from Main Agent: ${P}
795
+ `),K+=`[TOOL RESULT for AskMain]: Answer from Main Agent: ${P}
796
+
797
+ `,await Lt("toolSuccess")}else K+=`[TOOL RESULT for AskMain]: ERROR: Main agent communication channel not available.
798
+
799
+ `;continue}if(!(o?o.some(M=>M.toLowerCase()===F):!0)){let M=`ERROR: Tool [${N.toolName}] is not in the allowed tools list for this subagent.`;r&&r(`[Blocked Tool Call] ${N.toolName} - not allowed
800
+ `),K+=`${M}
801
+
802
+ `;continue}if(F==="exec_command"||F==="execcommand"||F==="run"){let M=L(N.args).command||"",P=w(M);if(!P.allowed){let Y=`ERROR: [SECURITY RESTRICTION] Subagent execution blocked command: ${P.reason}`;r&&r(`[Blocked Command] ${M} - ${P.reason}
803
+ `),K+=`${Y}
804
+
805
+ `;continue}}let ce="";if(F==="web_search"||F==="websearch")ce=`\u2714 \x1B[95mSearched\x1B[0m: ${L(N.args).query||""}`;else if(F==="web_scrape"||F==="webscrape")ce=`\u2714 \x1B[95mScraped\x1B[0m: ${L(N.args).url||""}`;else if(F==="search_keyword"||F==="searchkeyword"||F==="codesearch"||F==="code_search"){let M=L(N.args),P=M.keyword||"",Y=M.path||"";ce=`${P?"\u2714":"\u2718"} \x1B[95mSearched\x1B[0m: ${P||"No Query"}${Y?` \u2192 ${Y.replaceAll("\\","/")}`:""}`}else if(F==="view_file"||F==="viewfile"||F==="readfile")ce=`\u2714 \x1B[95mRead\x1B[0m: ${(L(N.args).path||"").replaceAll("\\","/")}`;else if(F==="list_files"||F==="read_folder"||F==="readfolder"){let M=L(N.args).path||null,P=L(N.args).recurse||0;ce=`${M?"\u2714":"\u2718"} \x1B[95mBrowsed\x1B[0m: ${M?`${M.replaceAll("\\","/")}${P>0?`${M.endsWith("/")?`*${P}`:`/*${P}`}`:`${M.endsWith("/")?"":"/"}`}`:""}`}else if(F==="write_file"||F==="writefile"){let M=L(N.args).path||null;ce=`${M?"\u2714":"\u2718"} \x1B[95mCreated\x1B[0m: ${M?`${M.replaceAll("\\","/")}`:"No File Changes"}`}else if(F==="update_file"||F==="updatefile"||F==="patchfile"||F==="patch_file"||F==="patchfile"||F==="updatefile"){let M=L(N.args).path||null,P=L(N.args).content||null;ce=`${M?"\u2714":"\u2718"} \x1B[95mEdited\x1B[0m: ${M?`${M.replaceAll("\\","/")}`:"No File Changes"}`}else if(F==="exec_command"||F==="execcommand"||F==="run"){let M=L(N.args).command||null;ce=`${M?"\u2714":"\u2718"} \x1B[95mExecuted\x1B[0m: ${M?M.slice(0,100)+(M.length>100?"...":""):"No Command"}`}else if(F==="file_map"||F==="filemap"){let M=L(N.args).path||"";ce=`${M?"\u2714":"\u2718"} \x1B[95mIndexed\x1B[0m: ${M?`${M.replaceAll("\\","/")}`:"File Not Found"}`}else if(F==="await"){let{time:M}=L(N.args),P=parseFloat(M)||0;P<10&&(P=10),P>180&&(P=180),ce=`\u2714 \x1B[95mAwaiting\x1B[0m \u2192 ${(V=>{if(V>=60){let _e=Math.floor(V/60),Pe=V%60;return`${_e}m${Pe>0?` ${Pe}s`:""}`}return`${V}s`})(P)}`}else{let M=Vr[F]||N.toolName,P=Ts(F,N.args);ce=`\u2714 \x1B[95m${M}\x1B[0m${P?`: ${P}`:""}`}n.onVisualFeedback&&ce&&n.onVisualFeedback(ce),r&&r(`[Executing Tool] ${N.toolName}(${N.args})...`);try{let M=await ao(N.toolName,N.args,{...n,mode:"Flux"});if(r&&r(`[Tool Result]
806
+ ${M}
807
+ `),K+=`[TOOL RESULT for ${N.toolName}]: ${M}
808
+
809
+ `,await Lt("toolSuccess"),F==="patchfile"||F==="update_file"||F==="updatefile"||F==="patch_file"){if(M){let P=M.split(`
810
+ `),Y=0,V=0,_e=!1;for(let Pe of P){if(Pe.includes("[DIFF_START]")){_e=!0;continue}if(Pe.includes("[DIFF_END]")){_e=!1;continue}_e&&(/^\+\d+/.test(Pe)?Y++:/^\-\d+/.test(Pe)&&V++)}(Y>0||V>0)&&(await jt("linesAdded",Y),await jt("linesRemoved",V))}}else if((F==="writefile"||F==="write_file")&&M){let P=M.match(/- Stats: \[(\d+) lines/),Y=P?parseInt(P[1]):0,V=0;if(M.includes("Old File contents:")){let _e=!1;for(let Pe of M.split(`
811
+ `)){if(Pe.includes("Old File contents:")){_e=!0;continue}_e&&(Pe.trim()===""?_e=!1:/^\d+ \|/.test(Pe)&&V++)}}(Y>0||V>0)&&(await jt("linesAdded",Y),await jt("linesRemoved",V))}}catch(M){let P=`ERROR: Execution failed for [${N.toolName}]: ${M.message}`;r&&r(`[Tool Error] ${P}
812
+ `),K+=`${P}
813
+
814
+ `,await Lt("toolFailure")}}let J="";if(n?.taskId&&typeof ze<"u"){let N=ze.find(F=>F.id===n.taskId);if(N&&N.pendingSteerMessages&&N.pendingSteerMessages.length>0){let F=[...N.pendingSteerMessages];N.pendingSteerMessages=[];for(let Q of F)J+=`
815
+
816
+ [STEERING INSTRUCTION FROM MAIN AGENT]: ${Q}`,r&&r(`[Subagent Steered] ${Q}`)}}let xe=(K.trim()+J).trim();S.push({role:"user",text:xe}),b++}return C};export{hn as a,Di as b,id as c,ad as d,dl as e,Pi as f,ld as g,Sl as h,cd as i,lo as j,fa as k,yp as l,wp as m,L as n,Oc as o,Zo as p,zs as q,_c as r,Ic as s,ut as t,cs as u,af as v,Xa as w,lf as x,cf as y,ff as z,df as A,uf as B,Sf as C,Tf as D,Rn as E,el as F,Js as G,jt as H,tl as I,Ai as J,fs as K,_l as L,au as M,lu as N,xp as O,Fo as P,Ep as Q,Dn as R,uc as S,lm as T,cm as U,ti as V,fm as W,dm as X,xc as Y,um as Z,hm as _,pm as $};