fluxflow-cli 4.4.5 → 4.6.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,838 @@
1
+ import{b as nr}from"./chunk-ACHIC75V.js";import{e as vt,g as zt,i as gi,j as yi,k as wi,l as xi,m as bi}from"./chunk-XGA3P7TV.js";import{c as At,d as $s,g as Re,h as en}from"./chunk-N5EE3XWJ.js";import{a as tr,b as mi,c as ne,d as he}from"./chunk-SIINYZWE.js";import{a as Hs,c as vn,d as hn,e as go,f as Es,g as _s,j as Dt,k as Zt,l as In,m as Wn,n as an,o as mn,p as is,q as er,r as jn,s as as}from"./chunk-I27MASHH.js";import{a as Ve,c as yo}from"./chunk-56EJGQU3.js";import{c as Si,d as ki,e as Gs}from"./chunk-LXTXILI5.js";import ni from"dotenv";import{GoogleGenAI as $a,ThinkingLevel as ut,HarmBlockThreshold as Yn,HarmCategory as Vn}from"@google/genai";import{execSync as za}from"child_process";import{spawn as sr}from"child_process";var L=e=>{let n={};if(!e)return n;let t=0;for(;t<e.length;){for(;t<e.length&&/[\s,]/.test(e[t]);)t++;if(t>=e.length)break;let s=e.substring(t).match(/^(\w+)\s*=\s*/);if(!s){t++;continue}let o=s[1];t+=s[0].length;let r="";if(t<e.length&&(e[t]==='"'||e[t]==="'"||e[t]==="`")){let a=e[t];t++;let i=t,h=-1,f=t;for(;f<e.length;){let l=e.indexOf(a,f);if(l===-1)break;let u=0;for(let y=l-1;y>=0&&e[y]==="\\";y--)u++;if(u%2!==0){f=l+1;continue}let d=e.substring(l+1),p=d.trim(),g=p===""||/^,\s*\w+\s*=/.test(p)||p.startsWith(")")&&(p.length===1||/^\)\s*([,\]\s]|\[\[?tool:)/i.test(p));if(g&&d.startsWith(`
2
+ `)){let y=p.split(`
3
+ `)[0];if(!y.includes("=")&&!y.includes(")")){f=l+1;continue}}if(g){h=l;break}f=l+1}h!==-1?(r=e.substring(i,h),t=h+1):(r=e.substring(i),t=e.length);let c=o.toLowerCase().includes("path")||["dest","source","to","from"].includes(o.toLowerCase());r=r.replace(/\\(.)/g,(l,u)=>{switch(u){case"n":return`
4
+ `;case"r":return"\r";case"t":return" ";case"\\":return"\\";default:return u===a?a:u}})}else if(t<e.length&&e[t]==="["){let a=0,i=null,h=t,f=-1;for(let c=t;c<e.length;c++){let l=e[c];if(i&&l===i){let u=0;for(let d=c-1;d>=0&&e[d]==="\\";d--)u++;u%2===0&&(i=null)}else!i&&(l==='"'||l==="'"||l==="`")&&(i=l);if(!i&&(l==="["?a++:l==="]"&&a--,a===0)){f=c;break}}if(f!==-1){r=e.substring(h,f+1),t=f+1;try{let c=r.trim();c.startsWith("'")||c.includes("'")}catch{}}else r=e.substring(h),t=e.length}else{let a=e.substring(t),i=a.match(/,\s*\w+\s*=|(?:\s*\)\s*(?:$|\]\]))/);if(i){let h=i.index;r=a.substring(0,h).trim(),t+=h}else r=a.trim(),t=e.length}r==="true"?r=!0:r==="false"?r=!1:typeof r=="string"&&!isNaN(r)&&r.trim()!==""&&(r=Number(r)),typeof r=="string"&&(o.toLowerCase().includes("path")||["dest","source","to","from"].includes(o.toLowerCase()))&&(r=r.replace(/\x0C/g,"\\f").replace(/\x0D/g,"\\r").replace(/\x0B/g,"\\v").replace(/\x08/g,"\\b")),n[o]=r}return n};var wo=null;try{let e=await import("node-pty");wo=e.default||e}catch{}var jc=!!wo,xo=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),or=e=>{if(!e)return"";let n=[[]],t=0,s=0,o=/\x1b\[([0-9;]*?)([a-zA-Z])/g,r=0,a,i=f=>{for(let c=0;c<f.length;c++){let l=f[c];if(l===`
5
+ `)for(t++,s=0;t>=n.length;)n.push([]);else if(l==="\r")s=0;else{for(;t>=n.length;)n.push([]);let u=n[t];for(;s>u.length;)u.push(" ");u[s]=l,s++}}};for(;(a=o.exec(e))!==null;){i(e.substring(r,a.index));let f=a[1],c=a[2],l=f?f.split(";").map(Number):[];if(c==="A"){let u=l[0]||1;t=Math.max(0,t-u)}else if(c==="B"){let u=l[0]||1;for(t=t+u;t>=n.length;)n.push([])}else if(c==="C"){let u=l[0]||1;s=s+u}else if(c==="D"){let u=l[0]||1;s=Math.max(0,s-u)}else if(c==="G"){let u=(l[0]||1)-1;s=Math.max(0,u)}else if(c==="H"||c==="f"){let u=(l[0]||1)-1,d=(l[1]||1)-1;for(t=Math.max(0,u),s=Math.max(0,d);t>=n.length;)n.push([])}else if(c==="K"){let u=l[0]||0;if(t<n.length){let d=n[t];if(u===0)d.length=s;else if(u===1)for(let p=0;p<s&&p<d.length;p++)d[p]=" ";else u===2&&(d.length=0)}}else if(c==="J"){let u=l[0]||0;(u===2||u===3)&&(n.length=0,n.push([]),t=0,s=0)}r=o.lastIndex}i(e.substring(r));let h=n.map(f=>f.join(""));for(;h.length>0&&h[h.length-1]==="";)h.pop();return h.join(`
6
+ `)},wt=null,qs=!1,Hc=e=>{try{wt&&(qs&&typeof wt.write=="function"?wt.write(e):wt.stdin&&wt.stdin.writable&&wt.stdin.write(e))}catch{}},Gc=()=>{if(wt){try{qs&&typeof wt.destroy=="function"?wt.destroy():typeof wt.kill=="function"&&(process.platform==="win32"?sr("taskkill",["/pid",wt.pid,"/f","/t"]):wt.kill("SIGKILL"))}catch{}wt=null,qs=!1}},rr=(e,n=!1)=>{if(process.platform!=="win32")return e;let t=[],s="",o=null,r=!1;for(let c=0;c<e.length;c++){let l=e[c];if(r){s+=l,r=!1;continue}if(l==="\\"){if(e[c+1]===" "){s+=" ",c++;continue}s+=l,r=!0;continue}o?(l===o&&(o=null),s+=l):l==='"'||l==="'"?(o=l,s+=l):l===";"&&!s.includes("://")?(s.length>0&&(t.push(s),s=""),t.push(n?";":"&")):l==="&"&&!s.includes("://")?e[c+1]==="&"?(s.length>0&&(t.push(s),s=""),t.push("&&"),c++):(s.length>0&&(t.push(s),s=""),t.push("&")):l==="|"&&!s.includes("://")?(s.length>0&&(t.push(s),s=""),t.push("|")):/\s/.test(l)?s.length>0&&(t.push(s),s=""):s+=l}s.length>0&&t.push(s);let a=c=>!(!c.includes("/")||/^(https?|file|ftp):\/\//i.test(c)||c.startsWith("@")||c.startsWith("/")&&(c.match(/\//g)||[]).length===1||/\s\/|\/\s/.test(c)||/[\(\)\{\}\;\<\>\=\'\"]/.test(c)),i=[];for(let c=0;c<t.length;c++){let l=t[c];if(l==="mkdir"&&n&&Hn()){let u=[],d=c+1;for(;d<t.length;){let p=t[d];if([">",">>","<","&","&&","|","||",";"].includes(p))break;p!=="-p"&&p!=="--parents"&&p!=="-v"&&p!=="--verbose"&&u.push(p),d++}if(u.length>0){let p=u.map(g=>{let y=g.replace(/^['"]|['"]$/g,""),m=g;return a(y)&&(m=g.replace(/\//g,"\\")),m});i.push("New-Item","-ItemType","Directory","-Force","-Path",p.join(","))}else i.push("New-Item","-ItemType","Directory","-Force");c=d-1;continue}if(l==="rm"&&n&&Hn()){let u=[],d=!1,p=!1,g=c+1;for(;g<t.length;){let m=t[g];if([">",">>","<","&","&&","|","||",";"].includes(m))break;m==="-rf"||m==="-fr"?(d=!0,p=!0):m==="-r"||m==="-R"||m==="--recursive"?d=!0:m==="-f"||m==="--force"?p=!0:u.push(m),g++}let y=["Remove-Item"];if(d&&y.push("-Recurse"),p&&y.push("-Force"),u.length>0){let m=u.map(w=>{let x=w.replace(/^['"]|['"]$/g,""),k=w;return a(x)&&(k=w.replace(/\//g,"\\")),k});y.push("-Path",m.join(","))}i.push(...y),c=g-1;continue}if(l==="cp"&&n&&Hn()){let u=[],d=!1,p=!1,g=c+1;for(;g<t.length;){let m=t[g];if([">",">>","<","&","&&","|","||",";"].includes(m))break;m==="-r"||m==="-R"||m==="--recursive"?d=!0:m==="-f"||m==="--force"?p=!0:u.push(m),g++}let y=["Copy-Item"];if(d&&y.push("-Recurse"),p&&y.push("-Force"),u.length>0){let m=u.map(w=>{let x=w.replace(/^['"]|['"]$/g,""),k=w;return a(x)&&(k=w.replace(/\//g,"\\")),k});if(m.length>1){let w=m.pop();y.push("-Path",m.join(","),"-Destination",w)}else y.push("-Path",m[0])}i.push(...y),c=g-1;continue}if(l==="touch"&&n&&Hn()){let u=[],d=c+1;for(;d<t.length;){let p=t[d];if([">",">>","<","&","&&","|","||",";"].includes(p))break;u.push(p),d++}if(u.length>0){let g=`(${u.map(y=>{let m=y.replace(/^['"]|['"]$/g,""),w=y;return a(m)&&(w=y.replace(/\//g,"\\")),w}).join(", ")}) | ForEach-Object { if (Test-Path $_) { (Get-Item $_).LastWriteTime = [System.DateTime]::Now } else { $null | Out-File -FilePath $_ } }`;i.push(g)}c=d-1;continue}if(l==="|"&&t[c+1]==="tee"){t[c+2]==="-a"?(i.push(">>"),c+=2):(i.push(">"),c+=1);continue}if(l==="|"&&t[c+1]==="cat"&&t[c+2]===">"){i.push(">"),c+=2;continue}if(l==="|"){let u=t[c+1];if(u){let d=u.replace(/^['"]|['"]$/g,""),p=/\.(txt|md|json|log|csv|html|css|py|js|xml|yaml|yml|pdf|docx|pptx|xlsx)$/i.test(d);if(a(d)&&p){i.push(">");continue}}}i.push(l)}let h=!1,f=i.map(c=>{if(c==="echo")return h=!0,c;[">",">>","<","&","&&","|","||",";"].includes(c)&&(h=!1);let u=/^['"]|['"]$/.test(c),d=c;h&&u&&(d=c.replace(/^['"]|['"]$/g,""));let p=/^['"]|['"]$/.test(d),g=d.replace(/^['"]|['"]$/g,"");a(g)&&(d=d.replace(/\//g,"\\"));let y=d.replace(/^['"]|['"]$/g,"");return y.includes(" ")&&!p&&(d=`"${y}"`),d});if(n){let c="",l=0;for(let u=0;u<f.length;u++){let d=f[u];d==="&&"?(c+="; if ($?) {",l++):d===";"?(c+=" }".repeat(l)+";",l=0):(c&&!c.endsWith(" ")&&!c.endsWith("{")&&(c+=" "),c+=d)}return c+=" }".repeat(l),c}return f.join(" ")},ir=async(e,n={})=>{let{command:t}=L(e),{onChunk:s}=n;if(!t)return'ERROR: Missing "command" argument for exec_command.';let o=process.platform==="win32",r=n.systemSettings||{},a={};return r.networkAccess===!1&&(a.HTTP_PROXY="http://127.0.0.1:9999",a.HTTPS_PROXY="http://127.0.0.1:9999",a.ALL_PROXY="socks5://127.0.0.1:9999",a.http_proxy="http://127.0.0.1:9999",a.https_proxy="http://127.0.0.1:9999",a.all_proxy="socks5://127.0.0.1:9999",a.NO_PROXY="localhost,127.0.0.1"),new Promise(i=>{let h=f=>{let c=f==="pwsh"||f==="powershell",l=rr(t,c),u;o?f==="pwsh"?u="C:\\Users\\User\\AppData\\Local\\Microsoft\\WindowsApps\\pwsh.exe":f==="powershell"?u="powershell.exe":u="cmd.exe":u=process.env.SHELL||"bash";let d=o?c?["-NoProfile","-Command",l]:["/c",l]:["-c",l];if(r.networkAccess===!1&&!o){let p=u,g=[...d];if(process.platform==="linux")u="unshare",d=["-n","-r",p,...g];else if(process.platform==="darwin"){let y=`(version 1)
7
+ (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,p,...g]}}if(wo)try{let p=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",...a}});wt=p,qs=!0;let g="",y=!1;return p.onData(m=>{if(!y){g+=m,s&&s(m);let w=xo(g);/(?:Network:\s+use\s+--host\s+to|Network:\s+Type\s+--host\s+to|Local:\s+http:\/\/localhost:\d+|ready in \d+\s*ms|Compiled successfully|Development server is running|Listening on:)/i.test(w)&&(y=!0,setTimeout(()=>i(`SUCCESS: Dev server started successfully in background.
12
+
13
+ ${w}`),500))}}),p.onExit(({exitCode:m})=>{if(y)return;wt=null;let w=or(g||""),x=xo(w).replace(/\n{3,}/g,`
14
+
15
+ `)||"Command executed with no output.";i(m!==0?`ERROR: Command [${t}] failed with exit code [${m}].
16
+
17
+ ${x}`:`SUCCESS: Command [${t}] completed.
18
+
19
+ ${x}`)}),!0}catch(p){return o&&(f==="pwsh"||f==="powershell")&&p.code==="ENOENT"?!1:(bo(i,l,t,a,s,f,r),!0)}else return bo(i,l,t,a,s,f,r),!0};o?h("pwsh")||h("powershell")||h("cmd"):h("bash")})},bo=(e,n,t,s,o,r="powershell",a={})=>{let i=process.platform==="win32",h=r==="pwsh"||r==="powershell",f;i?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=i?h?["-NoProfile","-Command",n]:["/c",n]:["-c",n];if(a.networkAccess===!1&&!i){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=i?sr(f,c,{cwd:process.cwd(),env:{...process.env,...s}}):sr(f,c,{cwd:process.cwd(),env:{...process.env,CI:"false",TERM:"xterm-256color",FORCE_COLOR:"1",...s}});wt=l,qs=!1,l.stdin&&l.stdin.on("error",()=>{wt=null});let u="",d="",p=!1;l.stdout.on("data",g=>{if(!p){let y=g.toString();u+=y,o&&o(y);let m=xo(u);/(?:Network:\s+use\s+--host\s+to|Network:\s+Type\s+--host\s+to|Local:\s+http:\/\/localhost:\d+|ready in \d+\s*ms|Compiled successfully|Development server is running|Listening on:)/i.test(m)&&(p=!0,setTimeout(()=>e(`SUCCESS: Dev server started successfully in background.
25
+
26
+ ${m}`),500))}}),l.stderr.on("data",g=>{if(!p){let y=g.toString();d+=y,o&&o(y)}}),l.on("close",g=>{if(p)return;wt=null;let y=[],m=or(u),w=or(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.",k=xo(x).replace(/\n{3,}/g,`
31
+
32
+ `);e(g!==0?`ERROR: Command [${t}] failed with exit code [${g}].
33
+
34
+ ${k}`:`SUCCESS: Command [${t}] completed.
35
+
36
+ ${k}`)}),l.on("error",g=>{if(i&&g.code==="ENOENT"){if(r==="pwsh"){let m=rr(t,!0);return bo(e,m,t,s,o,"powershell",a)}else if(r==="powershell"){let m=rr(t,!1);return bo(e,m,t,s,o,"cmd",a)}}wt=null;let y=g instanceof Error?g.message:String(g);e(`ERROR: Failed to start command [${t}]: ${y}`)})};var zs=null,Hn=()=>{if(process.platform!=="win32")return!1;if(zs!==null)return zs;try{za('powershell.exe -NoProfile -Command "exit"',{stdio:"ignore"}),zs=!0}catch{zs=!1}return zs},ar=null,Ti=(e,n,t,s,o=!1,r=!0)=>{ar===null&&(ar=o);let a=`- JSON escape literal sequences inside tool arguments (backslash: \\\\, newLine: \\n, quote: \\") \u2190 Mandatory
37
+ - Same file, multiple edits? One PatchFile (\u226415 blocks)
38
+ - Tool denied? Ask for guidance
39
+ - Need text or huge file? CodeSearch > Full Read
40
+ - Avoid unnecessary large file chunk reads
41
+ - Dont hallucinate tool results, verify, fix errors
42
+ - Stuck on syntax error? Tell user > waste time
43
+ `,i=`**Workspace Tools (path = relative; first argument, path separator: '/')**
44
+ - ReadFile(path="...", startLine="int", endLine="int")${s!=="Google"?`${t?". Supports images/docs":""}`:". Supports images/docs"}
45
+ - ReadFolder(path="...", recurse="int 1-3"). Minimize recursion
46
+ - PatchFile(path="...", allowMultiple="bool, false", searchContent1="search string OR ^LINE:start..end$", newContent1="...", ...MAX15). Use small searchContent. Line Ranges must for large searchContent and escape sequences. ^...$ must for line ranges
47
+ - WriteFile(path="...", content="..."). Creates/Overwrites. File Exist? PatchFile > WriteFile
48
+ - CodeSearch(keyword="...", path="dir/file/glob/regex, inclusion/exclusion ;-separated", fuzzy="bool, false", regex="bool, auto"). Find definitions, logic, relevant code, standard junk auto-excluded
49
+ - Run(command="..."). Runs ${n==="Windows"?Hn()?"powershell":"windows CMD":"bash"} command. Destructive/Irreversible ops \u2192 Ask user
50
+ - Goal(method="create/append/get", tasks=[string array], markDone=[task array]). If long multi-task: create Goals before starting. \`get + markDone\` to mark complete. Update every turn when created
51
+ ${ar?'\n**Emergency Tools**\nInfo: `initial` = current task prompt. Revert `id` = turn before disaster (eg. disaster: `turn_3` \u2192 revert: `turn_2`). Reason explicitly\n- EmergencyRollback(method="getCheckpoint/forceRevert", id="..."). Rollback workspace in this agent loop. ONLY for catastrophic corruption. Before ending, verify no catastrophe. `id` omitted for `getCheckpoint`\n':""}${r?`
52
+ **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
+ - InvokeSync/Invoke(title="...", task="..."). Task must be detailed: exact file paths, imports/exports, dependencies
58
+ - Await(id="...", timeout="integer"). Event-driven wait
59
+ - GetProgress(id="..."). Poll sparingly; NO initial poll. Work or await. Never end while subagent runs
60
+ - Steer(id="...", message="..."). Inject additional instruction or redirection into active async subagent
61
+ - Cancel(id="..."). Cancel async task ONLY if stalled (2m+) or incorrect`:""}`,h=`**Creative Tools (path = relative; first argument, path separator: '/')**
62
+ - WritePDF(path="...", content="...", orientation="..."). Proactive A4 page breaks must in css. HTML/CSS for premium layout, stable margins & headers/footers, no watermarks
63
+ - WriteDoc(path="...", content="..."). A4 Word document, no watermarks, stable margins & headers/footers`,f=`**Computer Use Tools (GUI Desktop Automation)**
64
+ - Click(gridId="integer", type="single/double", button="left/middle/right", intendedClickText="target text"). Click target grid number, intendedClickText: literal text/icon on screen (OCR scannable, upto 3 words). Double click desktop icons
65
+ - Drag(fromGridId="integer", toGridId="integer"). Drag mouse from start grid number to target grid number
66
+ - Scroll(direction="up/down", gridId="mouse hover area"). Scroll viewport vertically
67
+ - KeyboardTyping(text="string", autoPressEnter="bool"). Type text string into currently active input. JSON escape literal escape sequences
68
+ - KeyPress(key="key or ;-separated combination, eg: enter, back, backspace, clearInput, ctrl;c, alt;tab, f5, f11, alt;f4"). Press key, shortcut, function key (f1-f12), or clear active input field
69
+ - RecaptureScreen(). Request fresh gridded screenshot`;return`
70
+ -- TOOLS --
71
+ You cant execute tools. To use tools, must output exactly [tool:functions.ToolName(arg1="value1")] structured string in chat output & wait for system response \u2190 no exception, tool:functions must
72
+ Tool Rules:
73
+ - Max 3 tool calls/turn${e==="Flux"||e.toLowerCase()==="fluxcu"?" (Todo: 3+)":""}
74
+ - NO chat text with tool calls
75
+ ${e==="Flux"||e.toLowerCase()==="fluxcu"?`${a}`:""}
76
+ **User Communication**
77
+ - AskUser(question="...", optionA="title::description", ...MAX4). Ambiguity, path divergence, security risk. Ask, dont finish/guess. Keep titles short
78
+
79
+ **Web Tools**
80
+ - WebSearch(query="...", aiMode="bool, optional", limit="integer 3-10 aiMode: exclude"). Proactive use for unknown info/docs. aiMode: LLM search
81
+ - WebScrape(url="..."). Proactive use for specific webpage/docs/api
82
+
83
+ ${e==="ICU"?`${f}`:e==="FluxCU"?`${i}
84
+ ${f}`:e==="Flux"?`${i}`:`${h}`}`.trim()};var Ri=(e=!0,n=!0)=>`
85
+ To use tools, must output exactly '[tool:functions.ToolName(arg1="value1")]' structured string in chat response \u2190 no exception
86
+
87
+ -- Chat Management Tools --
88
+ - Chat(title="<short creative title of FULL conversation in 3 or 4 words>"). Consider full chat context to generate title NOT just latest message
89
+ - 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
90
+
91
+ ${e?`-- User-specific long-term/permanent memory (use based on conversation context, do not re-save memory which is already saved) --
92
+ - Add: 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)
93
+ - Delete: Memory(action="user", method="delete", id="<memory id>")
94
+ - Update: Memory(action="user", method="update", content-new="string to update", id="<memory id>")
95
+
96
+ -- Memory Relevance Decay Tool --
97
+ - Score Adjustment: addMemScore(id="<memory id>")
98
+ 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
99
+
100
+ Explicit Triggers for permanent memory:
101
+ - User explicitly asks to 'remember' something
102
+ - User mentions something important long-term that should be remembered
103
+ - User provides information that could be useful for long-term reference
104
+ - User shares personal information or preferences
105
+
106
+ Usage Rules:
107
+ - Frequency for 'user' action: Based on explicit triggers
108
+ - If you want to save something, but similar memory already exists, use the update method not add
109
+ - Chat title is mandatory
110
+ - Temporary memory is mandatory
111
+ - When called user memory, still use Temporary Memory
112
+ - Must not ignore any tool calls in given context of chat between user & agent`:""}`.trim();var So={xHigh:`Effort: High
113
+ 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
114
+ Continuous analysis, verify from first principles, seek failure paths, verify imports, tool results & system stability; avoid syntax errors
115
+ MANDATORY: Full technical verification`,High:`Effort: High
116
+ Rigorous thinking, prefer the simplest correct solution, assess architecture, performance & maintainability, verify error handling, assumptions, edge cases, dependencies & regressions, plan: files, functions, logic & interactions
117
+ Continuous analysis, verify from first principles, seek failure paths, verify imports, tool results & system stability; avoid syntax errors
118
+ MANDATORY: Full technical verification`,Medium:`Effort: Medium
119
+ 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
120
+ Logical, implementation-focused, efficient, deliberate, verify imports, tool results & system stability; avoid syntax errors
121
+ MANDATORY: Brief verification for technical tasks/greetings`,Minimal:`Effort: Low
122
+ Quick, focused thinking, intent & complexity, required tools/files/actions, before acting
123
+ Brief thoughts, think only enough to avoid mistakes, verify imports, tool results & system stability; avoid syntax errors`,Off:`Effort: Lowest
124
+ No thinking. Immediate response
125
+ Verify imports, tool results & system stability; avoid syntax errors`};import Gn from"fs";import _i from"path";import Ya from"screenshot-desktop";var $i=(e,n)=>{try{if(!Gn.existsSync(e))return"";let t=Array.isArray(n)?n.map(o=>o.toLowerCase()):[n.toLowerCase()],s=Gn.readdirSync(e);for(let o of t){let r=s.find(a=>a.toLowerCase()===o);if(r){let a=_i.join(e,r);if(Gn.statSync(a).isFile())return Gn.readFileSync(a,"utf8")}}}catch{}return""},Va=$i(Hs,["fluxflow.md","agent.md"]),Xa=$i(process.cwd(),["fluxflow.md","agent.md"]),Ja=e=>{if(!e)return null;let n=e.match(/^\s*---\r?\n([\s\S]*?)\r?\n---/);if(!n)return null;let t=n[1],s="",o="",r=t.match(/^name:\s*(.+)$/m),a=t.match(/^description:\s*(.+)$/m);return r&&(s=r[1].trim().replace(/^["']|["']$/g,"")),a&&(o=a[1].trim().replace(/^["']|["']$/g,"")),s&&o?{name:s,description:o}:null},Qa=e=>{let n=[];if(!e||!Gn.existsSync(e))return n;let t=(s,o=0)=>{if(!(o>5))try{let r=Gn.readdirSync(s,{withFileTypes:!0});for(let a of r){let i=_i.join(s,a.name),h=a.name.toLowerCase();a.isFile()?h==="skill.md"&&n.push(i):a.isDirectory()&&(o===0?(h==="skills"||h===".skills"||h==="skill"||h===".skill")&&t(i,o+1):t(i,o+1))}}catch{}};return t(e,0),n},Ci=e=>{let n=Qa(e),t=[];for(let s of n)try{let o=Gn.readFileSync(s,"utf8"),r=Ja(o);r&&t.push({...r,filePath:s})}catch{}return t},Mi=e=>!e||e.length===0?"":e.map(n=>`- ${n.name}: ${n.description}`).join(`
126
+ `),Za=Ci(Hs),el=Ci(process.cwd()),lr=Mi(Za),cr=Mi(el),Ai=!1;(async()=>{try{let e=await en();if(Number(e?.display)===1){let n=await Ya.listDisplays();n&&n.length>1&&(Ai=!0)}}catch{}})();var Ei=null,Ks=null,lf=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",tl=process.env.NO_DEV||!1,nl=(e,n)=>{if(!n)return"";if(e!==Ei||Ks===null){Ei=e;try{let t=ne(Dt,[]);Array.isArray(t)&&t.length>0?Ks=t.map(s=>`- ${s.memory}`).join(`
127
+ `):Ks=""}catch(t){Ks="",Gn.appendFileSync(`${hn}/memory/error.txt`,`${t.message}
128
+ -------------------------------------------------
129
+
130
+ `)}}return Ks},vi=(e="",n="",t=!0,s=!1)=>{if(typeof n=="boolean"&&(s=t,t=n,n=""),!t)return"";let o=e?.length>0&&!s?`-- Recent context from other chats (Priority: Low, Focus: Chat Context > Recent) --
131
+ ${e}`:"";return o?`${o}`:""},Ii=(e,n,t,s,o=!0,r=!1,a="Google",i=!1,h,f)=>{let c=!1;process.env.forcedReasoning&&(c=!0);let l="";if(!h&&a==="Google"){let S=n;n==="Fast"&&(S="Off"),n==="Low"&&(S="Minimal"),n==="Standard"&&(S="Medium"),(n==="xHigh"||n==="Max")&&(S="xHigh"),l=So[S]||So.Medium}if(h||a!=="Google"){let S={Fast:"Lowest",Low:"Low",Medium:"Medium",Standard:"Medium",High:"High",xHigh:"High",Max:"High"};l=So.xHigh,l=l.replace("Effort: High",`Effort: ${S[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
+ `:"",p=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
+ ${p.length||d.length?"":`
142
+ `}`:"",y=process.cwd(),m=nl(f,o),w=m?.length>0?`--- Saved Memories ---
143
+ ${m}
144
+
145
+ `:"",x=[Va,Xa].filter(Boolean).join(`
146
+
147
+ `),k=x.length>0?`--- Additional Instructions ---
148
+ ${x}
149
+
150
+ `:"",$=(()=>{let S=process.cwd().toLowerCase();if(process.platform==="win32"){let T=process.env.SystemRoot?.toLowerCase()||"c:\\windows",R=process.env.ProgramFiles?.toLowerCase()||"c:\\program files",E=process.env["ProgramFiles(x86)"]?.toLowerCase()||"c:\\program files (x86)";return S.startsWith(T)||S.startsWith(R)||S.startsWith(E)}else return S==="/"||["/bin","/sbin","/etc","/usr","/var","/root"].some(R=>S.startsWith(R))})();return`${process.env.I_HAVE_TOO_MUCH_MONEY==="true"||process.env.I_HAVE_TOO_MUCH_MONEY===!0||!1?`${" ".repeat(Math.floor(Math.random()*4)+1)}`:""}=== SYSTEM PROMPT ===
151
+ Identity: Flux Flow. Sassy, Friendly, CLI Assistant${tl?"":" by Kushal Roy"}
152
+ ${t==="Flux"?"Stepwise Execution, Run Automated Tests. Task Completion":t==="Flow"?"Concise, Humorous, Sarcastic":t==="ICU"?"Computer Use Capabilities. Screenshot as ground truth, analyze grid ids overlapping/close to target, keyboard shortcuts > mouse clicks":"Computer Use & Workspace Capabilities. Screenshot as ground truth, analyze grid ids overlapping/close to target, keyboard shortcuts > mouse clicks. Workspace Tools if faster. Focus on Productivity"}${Ai&&t.toLowerCase().includes("cu")?`
153
+ **Running on secondary screen. Opened app not visible in screenshot? Might be opened on primary. Use 'AskUser' with NO options and tell user to move app window to secondary**`:""}
154
+
155
+ - OS: ${u}
156
+ - Use directory structure for file path resolution${o?`
157
+ - Use relative time reference eg. few mins ago
158
+ -- Chat Context > Metadata`:""}${(lr.length>0||cr.length>0)&&t.toLowerCase().includes("flux")?`
159
+ - Read relevant skills for any task before acting: Use ReadFile, path="#skills/{global|local}/skillName". If references exist: path="#skills/{global|local}/skillName/references/<file-name>.md"`:""}
160
+
161
+ -- THINKING GUIDANCE --
162
+ ${a==="Mistral"||a==="Google"&&!h?`${l}
163
+ ${c||n!=="Fast"&&(a==="Mistral"&&!h||n!=="xHigh"&&!h)?`critical thinking policy
164
+ - Use <think>...</think> for reasoning before responding any queries
165
+ `:""}`:`${l}
166
+ `}
167
+ ${Ti(t,u,a.toLowerCase()==="deepseek"?!1:i,a,s?.advanceRollback,s?.subAgents!==!1)}
168
+ ${o?`
169
+ -- MEMORY RULES --
170
+ - Subtly Personalize with relevent contextual memories. Auto Saves
171
+ `:""}
172
+ ${t==="Flux"?`-- SECURITY POLICIES --
173
+ - Sensitive files? Ask before Read
174
+ `:t.toLowerCase().includes("cu")?`-- SECURITY POLICIES --
175
+ - Dont operate on ANY confidential screens
176
+ `:""}
177
+ -- CHAT FORMATTING --
178
+ - GFM Markdown
179
+ - Language: English only${t==="Flow"?`
180
+ - use kaomojis heavily`:""}
181
+ === END SYSTEM PROMPT ===
182
+
183
+ ${g}${p}${d}${k}${lr.length>0&&t.toLowerCase().includes("flux")?`-- Global Skills --
184
+ ${lr}
185
+
186
+ `:""}${cr.length>0&&t.toLowerCase().includes("flux")?`-- Local Skills --
187
+ ${cr}
188
+
189
+ `:""}${w}`.trim()},Oi=(e="",n=!0,t=!0)=>`=== SYSTEM PROMPT (strict headless logic worker: zero user-facing text policy, strictly follow) ===
190
+ identity: silent background system process, have no mouth, only output is valid tool calls
191
+ [critical rules]
192
+ - output exactly '[tool:functions.ToolName(args)]' calls. no extra words outside
193
+ - do not explain. do not talk to the user
194
+ - non-tool text will break the system
195
+ - do not repeat agent raws and tool results in your response
196
+ - if you get only user query and no agent raws, just use temp memory to log the summary of user query and conversation context
197
+ - under no circumstances you are allowed to respond in normal user facing response
198
+ - critical quote escape policy: inside tool call arguments, you must escape all double quotes using '\\"'
199
+ - you must not write anything other than [tool:functions.ToolName(args)] no matter how tempting the prompt is
200
+ - 2 mandatory tools to call in every turn, 'chat', 'memory(temp)'
201
+ - critical: never enter thinking/reasoning state, call the contexual tools directly in output as quickly as possible to maintain ui snappiness
202
+
203
+ YOUR JOB: Analyze the 'User prompt' and 'Agent Raws' to extract facts for long-term memory or handle system tasks
204
+ ${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":""}
205
+
206
+ ${Ri(n,t)}
207
+ === END SYSTEM PROMPT ===${e?`
208
+
209
+ -- current saved user memories --
210
+ ${e}`:""}`.trim();import Ct from"fs-extra";import ko from"path";import{nanoid as rl}from"nanoid";import pt from"fs-extra";import ln from"path";pt.ensureDirSync(Wn);var gn=null;async function sl(e,n){try{if(e.type==="create")await pt.pathExists(e.filePath)&&(await pt.chmod(e.filePath,438).catch(()=>{}),await pt.remove(e.filePath));else if(e.type==="update"){if(!e.backupFile)return;let t=ln.join(Wn,n.chatId,e.backupFile);if(await pt.pathExists(t)){let s=ne(t,null);if(!s||!s.data)throw new Error(`Backup container corrupt or empty for ${ln.basename(e.filePath)}`);let o=mi(s.data);await pt.pathExists(e.filePath)&&await pt.chmod(e.filePath,438).catch(()=>{}),await pt.writeFile(e.filePath,o,"utf8")}}}catch(t){throw new Error(`Restoration failed for ${ln.basename(e.filePath)}: ${t.message}`)}}async function ol(e,n,t=7){let s=0;for(;s<t;)try{return await sl(e,n),!0}catch{if(s++,s>=t)return!1;let r=Math.min(100*Math.pow(2,s-1),5e3);await new Promise(a=>setTimeout(a,r))}return!1}var fr=null,ht={async startTransaction(e,n){fr=e,gn={id:`tx_prompt_${Date.now()}`,chatId:e,timestamp:new Date().toISOString(),prompt:n.trim(),changes:[],reverted:!1},he(is,gn)},async recordFileChange(e,n=null){try{if(!gn){if(fr){let a=ne(an,[]),i=[...a].reverse().find(h=>h.chatId===fr);if(i){if(i.changes.some(u=>u.filePath===e))return;let c=await pt.pathExists(e)||n?"update":"create",l=null;if(c==="update"){let u=ln.basename(e);l=`${i.id}_${u}.bak`;let d=ln.join(Wn,i.chatId);await pt.ensureDir(d);let p=ln.join(d,l),g=n!==null?n:await pt.readFile(e,"utf8").catch(()=>null);g!==null?he(p,{data:tr(g)}):(c="create",l=null)}i.changes.push({filePath:e,type:c,backupFile:l}),he(an,a)}}return}if(gn.changes.some(a=>a.filePath===e))return;let o=await pt.pathExists(e)||n?"update":"create",r=null;if(o==="update"){let a=ln.basename(e);r=`${gn.id}_${a}.bak`;let i=ln.join(Wn,gn.chatId);await pt.ensureDir(i);let h=ln.join(i,r),f=n!==null?n:await pt.readFile(e,"utf8").catch(()=>null);f!==null?he(h,{data:tr(f)}):(o="create",r=null)}gn.changes.push({filePath:e,type:o,backupFile:r}),he(is,gn)}catch{}},async commitTransaction(){if(gn)try{let e=ne(an,[]);if(e.push(gn),e.length>512e3){let n=e.shift();if(n.changes)for(let t of n.changes)t.backupFile&&await pt.remove(ln.join(Wn,n.chatId,t.backupFile)).catch(()=>{})}he(an,e),await pt.remove(is).catch(()=>{})}catch{}finally{gn=null}},async recoverCrashedTransaction(){try{if(await pt.pathExists(is)){let e=ne(is,null);if(e?.changes?.length>0){let n=ne(an,[]);n.some(t=>t.id===e.id)||(n.push(e),he(an,n))}await pt.remove(is).catch(()=>{})}}catch{}},async rollbackToBefore(e){let n=ne(an,null);if(!n)throw new Error("No transaction ledger found.");let t=n.findIndex(a=>a.id===e);if(t===-1)throw new Error(`Transaction [${e}] not found.`);let s=n[t].chatId,o=n[t].prompt,r=n.slice(t).filter(a=>a.chatId===s&&!a.reverted).reverse();for(let a of r){for(let i of[...a.changes].reverse())await ol(i,a);for(let i of a.changes)if(i.backupFile){let h=ln.join(Wn,a.chatId,i.backupFile);await pt.remove(h).catch(()=>{})}n=n.filter(i=>i.id!==a.id),he(an,n)}return{success:!0,chatId:s,targetPrompt:o}},async getChatHistory(e){try{return ne(an,[]).filter(t=>t.chatId===e&&!t.reverted)}catch{return[]}},async deleteChatBackups(e){try{await pt.remove(ln.join(Wn,e));let n=ne(an,[]),t=n.filter(s=>s.chatId!==e);n.length!==t.length&&he(an,t)}catch{}}};var Li=Promise.resolve(),To=e=>{let n=Li.then(async()=>{try{return await e()}catch(t){throw console.error("Lock Operation Failed:",t),t}});return Li=n.catch(()=>{}),n},ls=async()=>{await Ct.ensureDir(_s);let e={};if(await Ct.pathExists(Es))try{e=ne(Es,{})}catch{e={}}for(let n in e){let t=ko.join(_s,`${n}.json`);Object.defineProperty(e[n],"messages",{get:()=>{if(Ct.existsSync(t))try{return ne(t,[])}catch{return[]}return[]},set:s=>{try{he(t,s)}catch{}},enumerable:!1,configurable:!0})}return e},kf=async(e,n,t)=>To(async()=>{await Ct.ensureDir(_s);let s=await ls(),o=s[e],r=(t||[]).filter(y=>!y.isUpdateNotification&&(!y.isMeta||y.text&&y.text.includes("Request Cancelled")));try{(await en()).systemSettings?.preserveThinking===!1&&(r=r.filter(m=>m.role!=="think"))}catch{}let a=y=>{if(!y)return;let m=typeof y=="string"?y:y.text||y.content||"";if(!m||typeof m!="string")return;let w=m.replace(/\s*\n+\s*\[Prompted on:.*?\]/g,"").replace(/\[\/?(?:STEERING HINT|QUESTION)(?::\s*\w+)?\]/gi,"").trim();if(!w)return;let x=w.split(/\s+/),k;return x.length>7?k=x.slice(0,7).join(" ")+"...":w.length>45?k=w.substring(0,45).trimEnd()+"...":k=w,k},i,h=r.filter(y=>y.role==="user"),f=h[0],c=h[h.length-1],l=a(c),u=a(f);o&&o.prompt?Math.random()<.5&&l?i=l:i=o.prompt:i=u||l;let d=n||(o?o.name:`Session ${e.slice(-6)}`),p=ko.join(_s,`${e}.json`);he(p,r),s[e]={name:d,prompt:i||void 0,updatedAt:Date.now()};let g={};for(let y in s)g[y]={name:s[y].name,prompt:s[y].prompt||void 0,updatedAt:s[y].updatedAt};he(Es,g)}),Pi=async(e,n)=>To(async()=>{let t=await ls();t[e]?(t[e].name=n,t[e].updatedAt=Date.now()):t[e]={name:n,updatedAt:Date.now()};let s={};for(let o in t)s[o]={name:t[o].name,prompt:t[o].prompt||void 0,updatedAt:t[o].updatedAt};he(Es,s)}),il=async e=>To(async()=>{let n=await ls();delete n[e];let t={};for(let a in n)t[a]={name:n[a].name,prompt:n[a].prompt||void 0,updatedAt:n[a].updatedAt};if(he(Es,t),await Ct.pathExists(jn))try{let a=ne(jn,[]);if(Array.isArray(a)){let i=a.filter(h=>Object.keys(h)[0]!==String(e));he(jn,i)}}catch{}let s=ne(Zt,{});s[e]&&(delete s[e],he(Zt,s));let o=ne(In,{});o[e]&&(delete o[e],he(In,o)),await ht.deleteChatBackups(e);let r=ko.join(_s,`${e}.json`);if(await Ct.pathExists(r))try{await Ct.remove(r)}catch{}return n}),Tf=()=>`flow-${rl(6)}`,Rf=async e=>{if(!e||e==="Never")return;let n=parseInt(e);if(isNaN(n))return;let t=await ls(),s=Date.now(),o=n*24*60*60*1e3,r=0;for(let a in t){let i=t[a];i.updatedAt&&s-i.updatedAt>o&&(await il(a),r++)}return r},al=e=>{let n=e.replace(/[\[\]]/g,"").trim(),t=new Date(n);if(!isNaN(t.getTime()))return t.getTime();let s=n.split(/,\s*|\s+/);if(s.length===0)return null;let o=s[0],r=s[1]||"",a=s[2]||"",i=o.split(/[-\/.]/).map(Number);if(i.length!==3)return null;let h="en";try{h=Intl.DateTimeFormat().resolvedOptions().locale||"en"}catch{}let f=!/^en[-_]?us$|^en$/.test(h?.toLowerCase()),c,l,u;if(i[0]>1e3)c=i[0],l=i[1],u=i[2];else if(i[2]>1e3)c=i[2],i[0]>12?(u=i[0],l=i[1]):i[1]>12?(u=i[1],l=i[0]):f?(u=i[0],l=i[1]):(l=i[0],u=i[1]);else return null;if(l<1||l>12||u<1||u>31)return null;let d=0,p=0,g=0;if(r){let m=r.split(":").map(Number);d=m[0]||0,p=m[1]||0,g=m[2]||0,a.toLowerCase()==="pm"&&d<12?d+=12:a.toLowerCase()==="am"&&d===12&&(d=0)}let y=new Date(c,l-1,u,d,p,g);return isNaN(y.getTime())?null:y.getTime()},ll=async e=>{try{if(!await Ct.pathExists(e))return;let n=await Ct.readFile(e,"utf8");if(!n.trim())return;let t=n.split(`
211
+ `),s=[],o=null,r=/^\s*(?:DEBUG|ERROR|SEARCH|PUPPETEER)\b/i;for(let l of t)r.test(l)?(o&&s.push(o),o={header:l,body:[]}):o?o.body.push(l):s.push({header:l,body:[]});o&&s.push(o);let a=10080*60*1e3,i=Date.now(),h=[],f=/(\d{1,4}[-\/.]\d{1,4}[-\/.]\d{1,4}(?:,\s*|\s+)?(?:\d{1,2}:\d{2}:\d{2}(?:\s*[aApP][mM])?)?)/;for(let l of s){if(r.test(l.header)){let p=l.header.match(f);if(p){let g=al(p[1]);if(g&&i-g>a)continue}}let d=l.header+(l.body.length>0?`
212
+ `+l.body.join(`
213
+ `):"");h.push(d)}let c=h.join(`
214
+ `).trim();c?await Ct.writeFile(e,c+`
215
+ `,"utf8"):await Ct.writeFile(e,"","utf8")}catch{}},Ef=async e=>{try{if(!await Ct.pathExists(e))return;let n=async t=>{let s=await Ct.readdir(t);for(let o of s){let r=ko.join(t,o);(await Ct.stat(r)).isDirectory()?(await n(r),(await Ct.readdir(r)).length===0&&await Ct.remove(r)):o.endsWith(".log")&&await ll(r)}};await n(e)}catch{}},Di=(e,n=4)=>{if(e.length<=1)return e;let t=e[0],s=e.slice(1),o=n*2,r=s.slice(o);return[t,...r]};var _f=async(e,n,t)=>To(async()=>{let s=ne(jn,[]);Array.isArray(s)||(s=[]);let o={total:n,context:t},r=s.findIndex(a=>Object.keys(a)[0]===String(e));r!==-1?s[r]={[String(e)]:o}:s.push({[String(e)]:o}),he(jn,s)}),$f=async e=>{try{if(!await Ct.pathExists(jn))return{total:0,context:0};let n=ne(jn,[]);if(!Array.isArray(n))return{total:0,context:0};let t=n.find(s=>Object.keys(s)[0]===String(e));return t?t[String(e)]:{total:0,context:0}}catch{return{total:0,context:0}}};import Bi from"puppeteer";import Ui from"fs";import Wi from"path";import Fi from"os";import Ys from"path";import Cs from"fs";import{createRequire as cl}from"module";import{fileURLToPath as fl}from"url";var dl=cl(import.meta.url),Ni=Ys.dirname(fl(import.meta.url));function cs(){let e=Fi.platform(),n=Fi.arch(),t="",s="",o="";if(e==="win32")t=n==="x64"?"win64":"win32",s="chrome.exe",o=`chrome-${t}`;else if(e==="darwin"){t=n==="arm64"?"mac_arm":"mac";let a=n==="arm64"?"arm64":"x64";s="Google Chrome.app/Contents/MacOS/Google Chrome",o=`chrome-mac-${a}`}else if(e==="linux")t="linux",s="chrome",o="chrome-linux64";else return{};let r=Ys.resolve(Ni,"..","..",".puppeteerrc.cjs");if(Cs.existsSync(r)||(r=Ys.resolve(Ni,"..",".puppeteerrc.cjs")),!Cs.existsSync(r))return{};try{let a=dl(r),i=a.cacheDirectory,h=a.chrome?.version;if(i){if(process.env.PUPPETEER_CACHE_DIR=i,h){let l=Ys.join(i,"chrome",`${t}-${h}`,o,s);if(Cs.existsSync(l))return{executablePath:l,cacheDirectory:i}}let f=l=>{if(!Cs.existsSync(l))return null;try{let u=Cs.readdirSync(l),d=[];for(let p of u){let g=Ys.join(l,p),y;try{y=Cs.statSync(g)}catch{continue}if(y.isDirectory())d.push(g);else if(p.toLowerCase()===s.toLowerCase()&&(!h||g.includes(h)))return g}if(h){for(let p of d)if(p.includes(h)){let g=f(p);if(g)return g}}for(let p of d)if(!h||!p.includes(h)){let g=f(p);if(g)return g}}catch{}return null},c=f(i);if(c)return{executablePath:c,cacheDirectory:i}}}catch{}return{}}var dr=async e=>{let{query:n,limit:t=5,aiMode:s=!1}=L(e);if(!n)return'ERROR: Missing "query" argument for web_search.';let o=3,r=null;if(s){let a=`Query: ${n}
216
+
217
+ RESPONSE RULES:
218
+ - ANSWER CONCISELY WITH REQUIRED DETAILS UNDER 300 WORDS.
219
+ - DO NOT CITE, REFERENCE, OR MENTION SOURCES ANYWHERE BETWEEN THE MAIN RESPONSE.
220
+ - DO NOT USE MARKDOWN EXCEPT FOR THE SOURCES SECTION BELOW.
221
+ - END THE RESPONSE WITH EXACTLY:
222
+
223
+ Sources:
224
+ - <URL 1>
225
+ - <URL 2>
226
+ - <URL 3>
227
+
228
+ - LIST ONE RAW URL PER BULLET.
229
+ - DO NOT USE MARKDOWN LINKS.
230
+ - DO NOT INCLUDE ANY TEXT, NOTES, OR EXPLANATIONS AFTER THE SOURCES SECTION.`;for(let i=1;i<=o;i++){let h=null;try{let f=cs();h=await Bi.launch({headless:!0,executablePath:f.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let c=await h.newPage();await c.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.178 Safari/537.36"),await c.setViewport({width:1366,height:768});let l=i===1?Math.random()*1e3+500:Math.random()*2e3+1e3;await new Promise(E=>setTimeout(E,l));let u=`https://search.brave.com/ask?q=${encodeURIComponent(a)}&source=web`;await c.goto(u,{waitUntil:"domcontentloaded",timeout:18e4});let d=null,p=45e3,g=Date.now();for(;Date.now()-g<p&&(d=await c.evaluate(()=>{let E=Array.from(document.querySelectorAll('.message:not(.user), .answer-text, .llm-content, [data-type="answer"]')),b="";if(E.length>0&&(b=E.map(se=>se.innerText.trim()).filter(Boolean).join(`
231
+
232
+ `)),b||(b=document.body.innerText),b.includes("anomaly"))throw new Error("ANOMALY_DETECTED");let C=!!document.querySelector('.spinner, .loading, .typing, .streaming, [data-streaming="true"], [data-state="loading"], svg.animate-spin, circle[cx], div[class*="spin"]'),A=E[0]||document.body,O=A?A.innerText.trim():"",D=/^(?:[✓✔]\s*)?Finished/i.test(O)||!!(A&&A.querySelector(".status-finished, .finished")),W=!C&&(D||b.includes("Sources:")&&!C),q={};return document.querySelectorAll("a[href]").forEach(se=>{let V=se.getAttribute("href")||se.href||"";if(V.includes("uddg=")&&(V=decodeURIComponent(V.split("uddg=")[1].split("&")[0])),V.includes("url=")&&(V=decodeURIComponent(V.split("url=")[1].split("&")[0])),V&&(V.startsWith("http://")||V.startsWith("https://"))&&!V.includes("search.brave.com")){let F=se.innerText.trim();F&&(q[F]=V),se.textContent=V}}),{isFinished:W,text:b,hrefMap:q}}),!(d&&d.isFinished));)await new Promise(E=>setTimeout(E,1e3));let y=(d?d.text:"")||"",m=d?d.hrefMap||{}:{},w="DO NOT INCLUDE ANY TEXT, NOTES, OR EXPLANATIONS AFTER THE SOURCES SECTION.";y.includes(w)&&(y=y.split(w).pop()),y=y.replace(/^.*?(Ctrl \+ Shift \+ O|Ask\nAll\nImages)/s,"").replace(/AI-generated answer\. Please verify critical facts\..*/s,"").replace(/Brave Search uses private usage metrics.*/s,"");let x=y,k="";if(y.includes("Sources:")){let E=y.split("Sources:");x=E[0],k=E.slice(1).join("Sources:")}let $=[];for(let E of x.split(`
233
+ `)){let b=E.trim();b&&(/^(View all|Finished|Searching|Answering|Thinking)$/i.test(b)||/^[\+\-]?\d+$/.test(b)||b.includes("search.brave.com")||b.startsWith("https://www.youtube.com/watch")||b.startsWith("https://youtube.com/watch")||$.push(E))}let _=$.join(`
234
+ `).replace(/^(?:[\+\-]?\d+\s*)+/i,"").replace(/\n{3,}/g,`
235
+
236
+ `).trim(),S=E=>!E||E.includes("search.brave.com")||E.includes("youtube.com")||E.includes("youtu.be"),T="";if(k){let E=k.match(/https?:\/\/[^\s\)\>]+/g)||[],b=[];for(let A of E){let O=A.replace(/[\.\,\;]+$/,""),D=Object.keys(m).find(W=>W.startsWith(O)||O.startsWith(W));D&&m[D]&&(O=m[D]),S(O)||b.push(O)}Object.values(m).forEach(A=>{!S(A)&&!b.includes(A)&&b.push(A)});let C=Array.from(new Set(b));C.length>0&&(T=`Sources:
237
+ `+C.map(A=>`- ${A}`).join(`
238
+ `))}let R=_+(T?`
239
+
240
+ `+T:"");if(!R||/^(\+\d+|Searching|Answering|Thinking|Finished)$/i.test(R))throw new Error("EMPTY_AI_RESPONSE");return await h.close(),`AI Search results for [${n}]:
241
+
242
+ ${R}`}catch(f){if(r=f,Ui.writeFileSync(Wi.join(hn,"web_tools","search","ai_mode","ERROR.txt"),f.message),h&&await h.close(),i<o){let c=Math.pow(2,i)*1e3;await new Promise(l=>setTimeout(l,c))}}}}for(let a=1;a<=o;a++){let i=null;try{let h=cs();i=await Bi.launch({headless:!0,executablePath:h.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let f=await i.newPage();await f.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.178 Safari/537.36"),await f.setViewport({width:1366,height:768});let c=a===1?Math.random()*1e3+500:Math.random()*2e3+1e3;await new Promise(g=>setTimeout(g,c));let l=`https://html.duckduckgo.com/html/?q=${encodeURIComponent(n)}`;await f.goto(l,{waitUntil:"networkidle2",timeout:18e4});let u=await f.$$eval(".result",(g,y)=>g.slice(0,y).map((m,w)=>{let x=m.querySelector(".result__a"),k=m.querySelector(".result__snippet"),$=x?x.href:"";$.includes("uddg=")&&($=decodeURIComponent($.split("uddg=")[1].split("&")[0]));let _=x?x.innerText.trim():"No Title",S=k?k.innerText.trim():"No Snippet";return`${w+1}. ${_}
243
+ Source: ${$}
244
+ Snippet: ${S}`}),t);if(u.length===0){if((await f.evaluate(()=>document.body.innerText)).includes("anomaly"))throw new Error("ANOMALY_DETECTED");return await i.close(),`No results found for query: [${n}].`}let d=u.join(`
245
+
246
+ `);return await i.close(),`${s?`AI Mode temporarily failed, used Standard search.
247
+
248
+ `:""}Search results for [${n}]:
249
+
250
+ ${d}`}catch(h){if(r=h,i&&await i.close(),Ui.writeFileSync(Wi.join(hn,"web_tools","search","standard_mode","ERROR.txt"),h.message),a<o){let f=Math.pow(2,a)*1e3;await new Promise(c=>setTimeout(c,f))}}}return`ERROR: Search failed after ${o+1} attempts. Last error: ${r.message}`};import ul from"puppeteer";import pl from"turndown";import{gfm as hl}from"turndown-plugin-gfm";var ur=async e=>{let n=e;if(typeof e=="object"&&e!==null)n=e.url||e.targetUrl||e.href||"";else if(typeof e=="string"){let r=e.match(/url\s*=\s*["'](.*)["']/);n=r?r[1]:e}let t=typeof n=="string"?n.trim():"";if(!t)return"ERROR: No target URL provided.";let s=3,o=null;for(let r=1;r<=s;r++){let a=null;try{let i=cs();a=await ul.launch({headless:!0,executablePath:i.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let h=await a.newPage();await h.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.178 Safari/537.36"),await h.setViewport({width:1366,height:768});let f=r===1?Math.random()*1e3+500:Math.random()*2e3+1e3;await new Promise(g=>setTimeout(g,f)),await h.goto(t,{waitUntil:"networkidle2",timeout:18e4}),await new Promise(g=>setTimeout(g,5e3));let c=await h.evaluate(()=>{document.querySelectorAll("script, style, noscript, svg, canvas, iframe, ad, .ads, link, meta, img").forEach(k=>k.remove());let y=document.createNodeIterator(document.body,NodeFilter.SHOW_COMMENT),m;for(;m=y.nextNode();)m.remove();for(document.querySelectorAll("*").forEach(k=>{let $=k.attributes;for(let _=$.length-1;_>=0;_--){let S=$[_].name;S!=="href"&&S!=="src"&&k.removeAttribute(S)}});document.querySelector("div, span");)document.querySelectorAll("div, span").forEach(k=>{k.parentNode&&k.replaceWith(...k.childNodes)});document.querySelectorAll("br").forEach(k=>{k.replaceWith(document.createTextNode(`
251
+
252
+ `))});let x=()=>{let k=!1;document.querySelectorAll("*").forEach($=>{$.childNodes.length===0&&!$.innerText.trim()&&($.remove(),k=!0)}),k&&x()};return x(),document.body.innerHTML});if(!c)throw new Error("EMPTY_RENDER_RESULT");let l=c.replace(/<br\s*\/?>/gi,`
253
+
254
+ `).replace(/[ \t]+/g," ").replace(/>[ \t]+</g,"><").replace(/\n\s+/g,`
255
+ `).replace(/\n{3,}/g,`
256
+
257
+ `).trim(),u=new pl({headingStyle:"atx",codeBlockStyle:"fenced"});u.use(hl);let d=u.turndown(l).replace(/\.\s*\n/g,`
258
+ `).replace(/ +/g," ").replace(/\t/g," ").replace(/\n\s+/g,`
259
+ `).replace(/\n{3,}/g,`
260
+
261
+ `),p=d.substring(0,5e4);return await a.close(),`Markdown parsed from [${t}]:
262
+
263
+ ${p}${d.length>5e4?`
264
+
265
+ [TRUNCATED AT 50K CHARS]`:""}`}catch(i){if(o=i,a&&await a.close(),r<s){let h=Math.pow(2,r)*1e3;await new Promise(f=>setTimeout(f,h))}}}return`ERROR: Scrape failed after ${s+1} attempts. Last error: ${o.message}`};var ml=4*(1024*2),pr=async(e,n={})=>{let t=c=>{let l=new RegExp(`${c}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),u=e.match(l);if(u)return u[2].trim();let d=new RegExp(`${c}\\s*[:=]\\s*([^,\\s)]+)`,"s"),p=e.match(d);return p?p[1].trim():null},s=t("action"),o=t("method"),r=t("content"),a=t("content-new"),i=t("content-old"),h=t("id"),f=t("chat-id")||n.chatId||n.sessionId||"default-session";if(s==="temp"){if(!r)return"ERROR: Missing 'content' for temp memory.";let c=ne(Zt,{});c[f]||(c[f]=[]),c[f].push(r),he(Zt,c);let l=c[f].reduce((u,d)=>u+d.length,0);return`SUCCESS: Temporary context saved for session [${f}]. (Size: ${l} chars)`}if(s==="user"){let c=ne(Dt,[]).map(l=>(l.score===void 0&&(l.score=.5),l));if(o==="add"){if(!r)return"ERROR: Missing 'content' for memory addition.";let l=new Date,u=`${l.getDate()}/${l.getMonth()+1}/${l.getFullYear()}`,d=r.includes("[Saved on:")?r:`${r.trim()} [Saved on: ${u}]`,p=ml,g=c.reduce((x,k)=>x+(k.memory?.length||0),0);for(;c.length>0&&g+d.length>p;){let x=c.shift();g-=x.memory?.length||0}let y=t("score"),m=y?parseFloat(y):.5,w={id:`mem-${Date.now().toString(36)}`,memory:d,score:Math.min(2,isNaN(m)?.5:m)};return c.push(w),he(Dt,c),`SUCCESS: Memory added with ID [${w.id}] and score [${w.score}]. (Vault Size: ${g+d.length} chars)`}if(o==="update"){let l=h||i,u=a||r;if(!l||!u)return"ERROR: Missing 'id' or content for update.";let d=c.findIndex(m=>m.id===l);if(d===-1)return`ERROR: Memory ID [${l}] not found.`;let p=new Date,g=`${p.getDate()}/${p.getMonth()+1}/${p.getFullYear()}`,y=u.includes("[Saved on:")?u:`${u.trim()} [Saved on: ${g}]`;return c[d].memory=y,he(Dt,c),`SUCCESS: Memory [${l}] updated.`}if(o==="delete"){let l=h||r;if(!l)return"ERROR: Missing 'id' for deletion.";let u=c.length,d=c.filter(p=>p.id!==l);return d.length===u?`ERROR: Memory ID [${l}] not found.`:(he(Dt,d),`SUCCESS: Memory [${l}] deleted.`)}return`ERROR: Invalid method [${o}] for user memory. Use 'add', 'update', or 'delete'.`}return`ERROR: Unknown action [${s}] for memory tool.`};var hr=async(e,n={})=>{let t=L(e).title,s=n.chatId||n.sessionId;if(!s)return"ERROR: No active chatId found in tool context.";if(!t)return"ERROR: Missing 'title' argument.";try{return await Pi(s,t),`SUCCESS: Chat title updated to [${t}] for session [${s}].`}catch(o){return`ERROR: Failed to update chat title: ${o instanceof Error?o.message:String(o)}`}};import cn from"fs";import En from"path";var gl=e=>{if(!e)return null;let n=e.match(/^\s*---\r?\n([\s\S]*?)\r?\n---/);if(!n)return null;let t=n[1],s="",o=t.match(/^name:\s*(.+)$/m);return o&&(s=o[1].trim().replace(/^["']|["']$/g,"")),s?{name:s}:null},yl=e=>{let n=[];if(!e||!cn.existsSync(e))return n;let t=(s,o=0)=>{if(!(o>5))try{let r=cn.readdirSync(s,{withFileTypes:!0});for(let a of r){let i=En.join(s,a.name),h=a.name.toLowerCase();a.isFile()?h==="skill.md"&&n.push(i):a.isDirectory()&&(o===0?(h==="skills"||h===".skills"||h==="skill"||h===".skill")&&t(i,o+1):t(i,o+1))}}catch{}};return t(e,0),n},wl=e=>e.replace(/^(\s*---\r?\n)([\s\S]*?)(\r?\n---)/,(n,t,s,o)=>{let r=s.split(`
266
+ `),a=[],i=!1;for(let h of r){if(/^\s*description\s*:/i.test(h)){i=!0;continue}if(i){if(/^\s+/.test(h))continue;i=!1}a.push(h)}return`${t}${a.join(`
267
+ `)}${o}`}),xl=(e,n)=>{let t=[En.join(e,"references"),En.join(e,"reference"),e],s=n.toLowerCase().endsWith(".md")?n.toLowerCase():`${n.toLowerCase()}.md`,o=n.toLowerCase();for(let r of t)if(cn.existsSync(r)&&cn.statSync(r).isDirectory())try{let a=cn.readdirSync(r);for(let i of a){let h=i.toLowerCase();if(h===s||h===o){let f=En.join(r,i);if(cn.statSync(f).isFile())return f}}}catch{}return null},Vs=async(e,n={})=>{let{path:t,StartLine:s,EndLine:o,start_line:r,end_line:a,startLine:i,endLine:h}=L(e),f=parseInt(s||r||i),c=parseInt(o||a||h),l=!isNaN(f),u=!isNaN(c),d=f||1,p=c||(f?f+800:800);if(!t)return'ERROR: Missing "path" argument for view_file.';if(t.trim().toLowerCase().startsWith("#skill")){let w=t.trim().replace(/\\/g,"/").replace(/^#skills?\/?/i,"").split("/").filter(Boolean),x=w[0]?.toLowerCase();if(x!=="global"&&x!=="local")return`ERROR: Invalid skill scope '${x||""}'. Expected 'global' or 'local'.`;let k=w[1];if(!k)return`ERROR: Missing skill name in path [${t}].`;let $=w[2]?.toLowerCase()==="references"||w[2]?.toLowerCase()==="reference",_=$?w.slice(3).join("/"):null,S=x==="global"?Hs:process.cwd(),T=yl(S),R=null;for(let A of T)try{let O=cn.readFileSync(A,"utf8"),D=gl(O),W=En.basename(En.dirname(A)).toLowerCase();if(D?.name&&D.name.toLowerCase()===k.toLowerCase()||W===k.toLowerCase()||A.toLowerCase()===En.join(S,"skill.md").toLowerCase()&&k.toLowerCase()==="skill"){R=A;break}}catch{}if(!R)return`No '${k}' exist in given scope.`;let E=En.dirname(R),b=R,C=!0;if($){if(!_)return`ERROR: Missing reference file name in path [${t}].`;let A=xl(E,_);if(!A)return`No such reference exist for skill '${k}'`;b=A,C=!1}try{let A=cn.readFileSync(b,"utf8");A.startsWith("\uFEFF")&&(A=A.slice(1)),A=A.replace(/\r\n/g,`
268
+ `).replace(/\r/g,`
269
+ `),C&&(A=wl(A));let O=A.split(`
270
+ `),D=O.length,W=l?Math.max(0,d-1):0,q=u?Math.min(D,p):D,se=O.slice(W,q),V=`Skill: [${t}]`,F=se.map((B,Z)=>`${String(W+Z+1).padStart(4)}: ${B.trimEnd()}`).join(`
271
+ `);return`${V}
272
+
273
+ ${F}`}catch(A){let O=A instanceof Error?A.message:String(A);return`ERROR: Failed to read skill file [${t}]: ${O}`}}let g=En.resolve(process.cwd(),t);try{if(!cn.existsSync(g))return`ERROR: File [${t}] does not exist.`;if(cn.statSync(g).isDirectory())return`ERROR: Path [${t}] is a directory. Use list_files instead.`;let m=En.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 O=cn.readFileSync(g).toString("base64"),D=x[m];return{text:`[BINARY FILE]: ${t} (${D}) - Loaded as multimodal part.`,binaryPart:{inlineData:{data:O,mimeType:D}}}}let k=cn.readFileSync(g,"utf8");k.startsWith("\uFEFF")&&(k=k.slice(1)),k=k.replace(/\r\n/g,`
274
+ `).replace(/\r/g,`
275
+ `);let $=k.split(`
276
+ `),_=$.length;!l&&!u&&_>800&&(d=1,p=50);let S=Math.max(0,d-1),T=Math.min(_,p),R=$.slice(S,T),E=`File: [${t}] (Showing lines ${S+1}-${T} of ${_}).`,b=R.map((C,A)=>`${String(S+A+1).padStart(4)}: ${C.trimEnd()}`).join(`
277
+ `);return`${E}
278
+
279
+ ${b}`}catch(y){let m=y instanceof Error?y.message:String(y);return`ERROR: Failed to read file [${t}]: ${m}`}};import Ms from"fs";import ji from"path";var mr=async(e,n={})=>{let{path:t,content:s}=L(e);if(!t)return'ERROR: Missing "path" argument for write_file.';if(s===void 0)return'ERROR: Missing "content" argument for write_file.';s=s.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
280
+ `).replace(/\r/g,`
281
+ `);let o=ji.resolve(process.cwd(),t),r=ji.dirname(o);try{await ht.recordFileChange(o);let a="";if(Ms.existsSync(o))try{a=`Old File contents:
282
+ ${Ms.readFileSync(o,"utf8").split(/\r?\n/).map(($,_)=>`${_+1} | ${$}`).join(`
283
+ `)}
284
+
285
+ `}catch{a=`[Note: Could not read existing file for reversal reference]
286
+
287
+ `}Ms.existsSync(r)||Ms.mkdirSync(r,{recursive:!0});let h=(x=>x.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
288
+ `).replace(/\r/g,`
289
+ `))(s),f=h.endsWith(`
290
+ `)?h:h+`
291
+ `,c=f.split(/\r?\n/).length,l=Buffer.byteLength(f,"utf8");Ms.writeFileSync(o,f,"utf8");let u=Ms.readFileSync(o,"utf8"),d=Buffer.byteLength(u,"utf8"),p=u.split(/\r?\n/),g=p.length;if(d===0&&l>0)return u=null,`ERROR: CRITICAL FAILURE: Verification failed. File [${t}] is empty on disk!`;let y="";if(g<=100)y=p.join(`
292
+ `);else{let x=p.slice(0,50).join(`
293
+ `),k=p.slice(-50).join(`
294
+ `);y=`${x}
295
+
296
+ ... [${g-100} lines truncated] ...
297
+
298
+ ${k}`}u=null;let{systemSettings:m}=await en(),w=`SUCCESS: File [${t}] saved.
299
+ - Stats: [${g} lines, ${(d/1024).toFixed(1)} KB]
300
+ ${a}- Content Preview:
301
+
302
+ ${y}`;if(m?.compressToolResults&&g>60){let x=f.split(/\r?\n/),k=x.slice(0,25).join(`
303
+ `)===p.slice(0,25).join(`
304
+ `),$=x.slice(-25).join(`
305
+ `)===p.slice(-25).join(`
306
+ `);k&&$&&(w=`[[SAME]]
307
+ ${w}`)}return w}catch(a){let i=a instanceof Error?a.message:String(a);return`ERROR: Failed to write file [${t}]: ${i}`}};import xr from"fs";import Al from"path";import bl from"os";var yn=e=>typeof e!="string"?e:e.length>12?(e+"").replace("",""):e,Hi=(e,n)=>{if(!e)return"";let t=/\x1B\[[0-?]*[ -/]*[@-~]/g,s=e.split(`
308
+ `),o=[];if(n<=5)return e;let r=a=>a.replace(t,"").length;return s.forEach(a=>{if(r(a)<=n){o.push(a);return}let h=a.split(/(\s+)/),f="",c=0,l=a.match(/^(\s*)/),u=l?l[1]:"";h.forEach((d,p)=>{if(d.length===0)return;let g=r(d);if(c+g>n)if(f.trim().length>0)o.push(f.trimEnd()),f=u.substring(0,Math.min(u.length,8))+d,c=r(f);else if(t.test(d))o.push(d),f=u,c=r(f);else{let y=d;for(;r(y)>n&&n>10;)o.push(y.substring(0,n)),y=y.substring(n);f=y,c=r(f)}else f+=d,c+=g}),(f.trimEnd().length>0||f===u)&&o.push(f.trimEnd())}),yn(o.join(`
309
+ `))},hd=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()},md=(e,n=40)=>{let t=vn.replaceAll("\\\\","\\");if(e=e.replace(bl.homedir(),"~").replace(t,"FluxFlow").replaceAll("\\","/"),!e||e.length<=n)return yn(e);let s=Math.floor((n-3)/2);return yn(e.substring(0,s)+"..."+e.substring(e.length-s).replaceAll("\\","/"))},Ro=e=>{let n=[],t=new Set,s=e.allowMultiple===!0||String(e.allowMultiple).toLowerCase()==="true";Object.keys(e).forEach(h=>{let f=h.match(/^(searchContent|search_content|replaceContent|replace_content|newContent|new_content|content_to_replace|content_to_add|searchBlock|search_block|newBlock|new_block)_?(\d+)?$/i);if(f){let c=f[2]?parseInt(f[2],10):1;t.add(c)}});let o=Array.from(t).sort((h,f)=>h-f),r=["searchContent","search_content","replaceContent","replace_content","content_to_replace","searchBlock","search_block"],a=["newContent","new_content","content_to_add","newBlock","new_block"],i=(h,f,c)=>{let l,u;for(let d of f){let p=h===1?[`${d}1`,d,`${d}_1`]:[`${d}${h}`,`${d}_${h}`];for(let g of p)if(e[g]!==void 0){l=e[g];break}if(l!==void 0)break}for(let d of c){let p=h===1?[`${d}1`,d,`${d}_1`]:[`${d}${h}`,`${d}_${h}`];for(let g of p)if(e[g]!==void 0){u=e[g];break}if(u!==void 0)break}return{r:l,n:u}};for(let h of o){let{r:f,n:c}=i(h,r,a);if(f!==void 0&&c!==void 0)n.push({replace:f,new:c});else if(f!==void 0||c!==void 0)return{error:`Mismatched replacement pair for index ${h}. Both replacement and new content must be provided.`,allowMultiple:s}}return{patchPairs:n,allowMultiple:s}},Sl=e=>{if(!e)return null;let n="",t=0,s=e.length;for(;t<s;){let o=e[t];if(o==="\\"){for(;t<s&&e[t]==="\\";)t++;n+="\\\\*"}else if(o===`
310
+ `)n+="(?:\\r?\\n|\\\\*n|\\\\*r|\\s*)",t++;else if(o==="\r")n+="(?:\\r|\\\\*r)?",t++;else if(o===" ")n+="(?:\\t|\\\\*t|\\s*)",t++;else if(o==='"'||o==="'"||o==="`")n.endsWith("\\\\*")||(n+="\\\\*"),n+=o,t++;else if(/[.*+?^${}()|[\]]/.test(o))n+="\\"+o,t++;else if(/\s/.test(o)){for(;t<s&&/\s/.test(e[t])&&e[t]!==`
311
+ `&&e[t]!=="\r"&&e[t]!==" ";)t++;n+="\\s*"}else n+=o,t++}if(!n)return null;try{return new RegExp(n,"g")}catch{return null}},Eo=(e,n,t={})=>{let s=typeof t=="boolean"?t:!!(t&&t.allowMultiple),o=e.replace(/\r\n/g,`
312
+ `).replace(/\r/g,`
313
+ `),r=m=>m.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
314
+ `).replace(/\r/g,`
315
+ `),a=m=>m.match(/^\s*/)[0],i=m=>{let w=m.split(`
316
+ `).filter(k=>k.trim()!=="");if(w.length===0)return"";let x=a(w[0]);for(let k of w){let $=a(k);$.length<x.length&&(x=$)}return x},h=(m,w,x="")=>{if(!m||w===void 0)return m;let $=/^\t/m.test(w)?" ":" ",_=C=>C.split(`
317
+ `).find(A=>A.trim()!=="")??"",S=_(w).match(/^\s*/)[0].length,T=_(m).match(/^\s*/)[0].length,R=S-T,E=(x.match(/^\s*/)||[""])[0].length;return m.split(`
318
+ `).map((C,A)=>{if(C.trim()===""&&A!==0)return"";let O=C.match(/^\s*/)[0].length,D=Math.max(0,O+R);return A===0&&(D=Math.max(0,D-E)),$.repeat(D)+C.trimStart()}).join(`
319
+ `)},f=[];for(let m=0;m<n.length;m++){let w=n[m],x=(w.replace||"").trim(),k=r(w.new||"");if(x.startsWith("^LINE:")&&x.endsWith("$")){let E=x.slice(6,-1).trim().split(".."),b=parseInt(E[0]),C=E[1]!==void 0?parseInt(E[1]):b;if(!isNaN(b)&&!isNaN(C)){let A=o.split(`
320
+ `);if(b<1||b>A.length||C<b||C>A.length){f.push({index:m,success:!1,error:`Block ${m+1}: Line range ^LINE:${b}..${C}$ out of bounds (file has ${A.length} lines).`});continue}let D=A.slice(b-1,C).join(`
321
+ `),W=0;for(let q=0;q<b-1;q++)W+=A[q].length+1;f.push({index:m,success:!0,startPos:W,firstMatchContent:D,content_to_add:k});continue}}let $=r(w.replace||"");if($===""&&k===""){f.push({index:m,success:!1,error:`Block ${m+1}: Empty replace and add content.`});continue}let _=$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),S=null;if($!==""&&o.includes($))S=new RegExp(_,"g");else{let R=$.split(`
322
+ `).map(E=>E.trim()).filter(E=>E.length>0).map(E=>E.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\s+/g,"\\s*"));if(R.length>0){let E=R.join("\\s*");try{S=new RegExp(E,"g")}catch{S=new RegExp(_,"g")}}else S=new RegExp(_,"g")}let T=[...o.matchAll(S)];if(T.length===0&&$!==""){let R=Sl($);R&&(T=[...o.matchAll(R)])}if(T.length===0){f.push({index:m,success:!1,error:`Block ${m+1}: Could not find match.`});continue}if(T.length>1&&!s){f.push({index:m,success:!1,error:`Block ${m+1}: Found ${T.length} matches (must be unique or use allowMultiple: true if sure).`});continue}for(let R of T)f.push({index:m,success:!0,startPos:R.index,firstMatchContent:R[0],content_to_add:k})}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=o,d=0,p=0,g=f.filter(m=>m.success).sort((m,w)=>m.startPos-w.startPos);for(let m of g){let w=m.startPos,x=o.substring(0,w).split(`
323
+ `).length,k=w+d,$=x+p,_=u.lastIndexOf(`
324
+ `,k)+1,S=u.substring(_,k),T=h(m.content_to_add,m.firstMatchContent,S),R=u.split(`
325
+ `),E=[];for(let O=Math.max(0,$-4);O<$-1;O++)E.push({num:O+1,text:R[O]});let b=m.firstMatchContent.split(`
326
+ `),C=[],A=$+b.length-1;for(let O=A;O<Math.min(R.length,A+3);O++)C.push({num:O+1,text:R[O]});l.set(m,{success:!0,index:m.index,oldContent:m.firstMatchContent,newContent:T,originalStartLine:x,finalStartLine:$,contextBefore:E,contextAfter:C}),u=u.substring(0,k)+T+u.substring(k+m.firstMatchContent.length),d+=T.length-m.firstMatchContent.length,p+=T.split(`
327
+ `).length-m.firstMatchContent.split(`
328
+ `).length}let y=[];for(let m=0;m<n.length;m++){let w=g.filter(x=>x.index===m);if(w.length>0)for(let x of w)l.has(x)&&y.push(l.get(x));else{let x=f.find(k=>k.index===m);y.push({success:!1,error:x?x.error:`Block ${m+1}: Unknown error.`})}}return{content:u,results:y}},_o=(e,n,t,s=8,o=!1)=>{if(!t||t.length===0)return"";let r=e.split(/\r?\n/),a=n.split(/\r?\n/),i=Math.max(r.length,a.length,1),h=Math.max(4,String(i).length),f=g=>String(g).padStart(h," "),c=`[DIFF_START]
329
+ `,l="\u2550".repeat(88),u=0,d=null,p=t.filter(g=>g.success).sort((g,y)=>g.originalStartLine-y.originalStartLine);if(p.forEach((g,y)=>{let m=g.finalStartLine!==void 0?g.finalStartLine:g.originalStartLine;if(d===null)for(u=Math.max(0,m-4);u<m-1;)c+=`[UI_CONTEXT] ${f(u+1)} |${a[u]||""}
330
+ `,u++;else{let T=d,R=T.originalStartLine+T.oldContent.split(`
331
+ `).length-1;if(g.originalStartLine-R-1>=s){let b=Math.min(a.length,u+3);for(;u<b;)c+=`[UI_CONTEXT] ${f(u+1)} |${a[u]||""}
332
+ `,u++;for(c+=`[UI_CONTEXT] ${l}
333
+ `,u=Math.max(u,m-4);u<m-1;)c+=`[UI_CONTEXT] ${f(u+1)} |${a[u]||""}
334
+ `,u++}else for(;u<m-1;)c+=`[UI_CONTEXT] ${f(u+1)} |${a[u]||""}
335
+ `,u++}let w=g.originalStartLine-1,x=r[w]||"",k=g.oldContent.split(`
336
+ `),$=x.match(/^\s*/),_=$?$[0]:"";k.forEach((T,R)=>{let E=T;if(k.length===1&&x.trim().length>0&&x.includes(T.trim()))E=x;else if(R===0){let b=T.match(/^\s*/);(b?b[0]:"").length<_.length&&x.includes(T.trim())&&(E=_+T.trimStart())}c+=`-${f(g.originalStartLine+R)} |${E}
337
+ `});let S=u;if(g.finalStartLine!==void 0)S=g.finalStartLine-1+(g.newContent?g.newContent.split(`
338
+ `).length:0);else{let T=g.originalStartLine+k.length-1,R=r[T]||null;if(R!==null){let E=y<p.length-1?(p[y+1].originalStartLine||a.length)+10:a.length;for(let b=u;b<E;b++){if(a[b]===R){S=b;break}b===a.length-1&&(S=a.length)}}else S=a.length}for(;u<S;)c+=`+${f(u+1)} |${a[u]||""}
339
+ `,u++;d=g}),d!==null){let g=Math.min(a.length,u+3);for(;u<g;)c+=`[UI_CONTEXT] ${f(u+1)} |${a[u]||""}
340
+ `,u++}if(o){let g=`[DIFF_START]
341
+ `,y=c.substring(g.length),m=`[UI_CONTEXT] ${l}
342
+ `,x=y.split(m).map(k=>k.split(`
343
+ `).filter(_=>_.trim()!=="").length>45?`[[VERIFIED]]
344
+ ${k}
345
+ [[/VERIFIED]]`:k);c=g+x.join(m)}return c+="[DIFF_END]",yn(c)},kl=e=>{if(!e)return null;let n=e.replace("[UI_CONTEXT]","").replace(/\r/g,""),t=n.startsWith("-"),s=n.startsWith("+"),o=t||s?n.substring(1):n,r=o.indexOf("|"),a=r!==-1?yn(o.substring(0,r).trim()):"",i=yn(r!==-1?o.substring(r+1):o);return{isR:t,isA:s,num:a,content:i}},Tl=(e,n)=>{if(!e&&!n)return 1;if(!e||!n)return 0;let t=e.length,s=n.length,o=e,r=n;t<s&&(o=n,r=e);let a=o.length,i=r.length,h=new Int32Array(i+1),f=new Int32Array(i+1);for(let u=0;u<=i;u++)h[u]=u;for(let u=1;u<=a;u++){f[0]=u;let d=o[u-1];for(let p=1;p<=i;p++)d===r[p-1]?f[p]=h[p-1]:f[p]=Math.min(h[p],f[p-1],h[p-1])+1;h.set(f)}let c=h[i],l=Math.max(t,s);return l===0?1:1-c/l},Gi=e=>{let n=[],t=[];e.forEach((c,l)=>{c.parsed.isR?n.push({index:l,content:c.parsed.content}):c.parsed.isA&&t.push({index:l,content:c.parsed.content})});let s=n.length,o=t.length;if(s===0||o===0)return;let r=Array.from({length:s+1},()=>Array(o+1).fill(0)),a=Array.from({length:s+1},()=>Array(o+1).fill(""));for(let c=1;c<=s;c++)a[c][0]="up";for(let c=1;c<=o;c++)a[0][c]="left";let i=Array.from({length:s},()=>Array(o).fill(0));for(let c=0;c<s;c++)for(let l=0;l<o;l++)i[c][l]=Tl(n[c].content.trim(),t[l].content.trim());for(let c=1;c<=s;c++)for(let l=1;l<=o;l++){let u=i[c-1][l-1],d=u>=.2?u:-10,p=r[c-1][l-1]+d,g=r[c-1][l],y=r[c][l-1];p>=g&&p>=y?(r[c][l]=p,a[c][l]="diag"):g>=y?(r[c][l]=g,a[c][l]="up"):(r[c][l]=y,a[c][l]="left")}let h=s,f=o;for(;h>0||f>0;)if(a[h][f]==="diag"){if(i[h-1][f-1]>=.2){let l=n[h-1].index,u=t[f-1].index;e[l].pairContent=e[u].parsed.content,e[u].pairContent=e[l].parsed.content}h--,f--}else a[h][f]==="up"?h--:f--},qn=new Map,fs=new Map,qi=200,gr=6,wr=(e,n)=>{n.set(e.key,e),e.type==="chunk"&&e.blocks&&e.blocks.forEach(t=>wr(t,n))},gd=(e,n)=>{if(!e)return{completed:[],active:[]};let t=`${e.id}-${e.text?.length||0}-${n}-${e.isStreaming}-${e.workedDuration||0}`;if(!e.isStreaming&&qn.has(t))return qn.get(t);let s=yn(Ml(e.text||"",e.role)),o=`${e.id}-${n}`,r=new Map;if(e.isStreaming){let p=fs.get(o);p&&s.startsWith(p.text)&&(r=p.blocksMap)}let a=(p,g,y,m={})=>{let w=r.get(p);if(w&&w.text===y&&w.type===g&&!!w.isActiveBlock==!!m.isActiveBlock&&!!w.isStreaming==!!m.isStreaming&&w.pairContent===m.pairContent)return w;let x=yn(y),k={...m};return typeof k.pairContent=="string"&&(k.pairContent=yn(k.pairContent)),Array.isArray(k.wrappedLines)&&(k.wrappedLines=k.wrappedLines.map(yn)),{key:p,isStreamingMsg:!!e.isStreaming,workedDuration:e.workedDuration,type:g,text:x,msg:g==="full-message"?e:void 0,...k}};if(s.includes("- Content Preview:")){let p="",g=s.match(/File\s+\[(.*?)\]/i);g&&(p=g[1].split(".").pop().toLowerCase());let k=((s.split("- Content Preview:")[1]||"").split("[SYSTEM] Check the content preview for verification [/SYSTEM]")[0]?.trim()||"").split(`
346
+ `).map(b=>b.replace(/\r$/,"")),$=String(k.length).length,_=[],S=null,T=[],R=()=>{if(!T.length)return;let b=T;T=[],_.push(b.length===1?b[0]:{key:`${b[0].key}-chunk`,type:"chunk",blocks:b})},E=n-($+6);return k.forEach((b,C)=>{let A=C===k.length-1,O=Hi(b,E).split(`
347
+ `),D=a(`${e.id||Date.now()}-write-line-${C}`,"write-line",b,{gutterWidth:$,lineNum:C+1,isFirstLine:C===0,isLastLine:A,extension:p,wrappedLines:O});A&&e.isStreaming?(R(),S=D):(T.push(D),T.length>=gr&&R())}),R(),{completed:_,active:S?[S]:[]}}if(s.includes("[DIFF_START]")){let p=s.match(/\[DIFF_START\]([\s\S]*?)(?:\[DIFF_END\]|$)/),y=(p?p[1].trim():"").split(`
348
+ `).map(S=>S.replace(/\r$/,"")),m=y.map(S=>({line:S,parsed:kl(S),pairContent:null})),w=[];for(let S=0;S<m.length;S++){let T=m[S];T.parsed&&(T.parsed.isR||T.parsed.isA)?w.push(T):w.length>0&&(Gi(w),w=[])}w.length>0&&Gi(w);let x=[],k=null,$=[],_=()=>{if(!$.length)return;let S=$;$=[],x.push(S.length===1?S[0]:{key:`${S[0].key}-chunk`,type:"chunk",blocks:S})};return y.forEach((S,T)=>{let R=T===y.length-1,E=m[T].parsed,b=null;E&&(b=Hi(E.content,n-17).split(`
349
+ `));let C=a(`${e.id||Date.now()}-diff-${T}`,"diff-line",S,{isFirstLine:T===0,isLastLine:R,pairContent:m[T].pairContent,wrappedLines:b});R&&e.isStreaming?(_(),k=C):($.push(C),$.length>=gr&&_())}),_(),{completed:x,active:k?[k]:[]}}if(e.role==="system"||e.isLogo||e.isHelpRecord||e.isTerminalRecord||e.isHomeWarning||e.isImageStats||e.isAskRecord||e.isAboutRecord||e.isUpdateNotification||e.role==="user")return{completed:[a(`${e.id||Date.now()}-full`,"full-message",s)],active:[]};if(!s&&!e.isStreaming){let p={completed:[],active:[]};return qn.set(t,p),p}let i=[],h=null,f=[],c=null,l=()=>{if(!f.length)return;let p=f;f=[],c=null,i.push(p.length===1?p[0]:{key:`${e.id||"x"}-chunk-${p[0].key}`,type:"chunk",blocks:p})},u=(p,g=!1)=>{if(c!==null&&c!==p.type&&l(),f.push(p),c=p.type,f.length>=gr){if(e.isStreaming&&g)return;l()}};if(e.role==="think"){i.push(a(`${e.id}-header`,"think-header",""));let p=s.split(`
350
+ `);p.forEach((g,y)=>{let m=y===p.length-1;u(a(`${e.id}-${y}`,"think-line",g,{}),m)}),e.isStreaming||(l(),i.push({key:`${e.id}-footer-padding`,type:"think-footer-padding",text:""}))}else{let p=s.split(`
351
+ `),g=!1,y=[],m=!1,w="",x=0,k=0;p.forEach(($,_)=>{let S=_===p.length-1,T=$.trim().startsWith("|"),R=$.trim().startsWith("```");m?R?(m=!1,u(a(`${e.id}-code-close-${k}`,"code-fence-close","",{}),S)):(x++,u(a(`${e.id}-code-line-${_}`,"code-line",$,{lineNum:x,lang:w}),S)):R?(m=!0,k=_,x=0,w=$.trim().replace(/^```/,"").trim(),u(a(`${e.id}-code-open-${_}`,"code-fence-open",w,{}),S)):T?(g=!0,y.push($),S&&(l(),e.isStreaming?h=a(`${e.id}-table-${_}`,"table",y.join(`
352
+ `),{isStreaming:!0}):i.push(a(`${e.id}-table-${_}`,"table",y.join(`
353
+ `),{isStreaming:!1})))):(g&&(l(),i.push(a(`${e.id}-table-${_}`,"table",y.join(`
354
+ `),{isStreaming:!1})),g=!1,y=[]),u(a(`${e.id}-${_}`,"agent-line",$,{}),S))}),!e.isStreaming&&e.workedDuration&&(l(),i.push(a(`${e.id}-worked-duration`,"worked-duration","")))}e.isStreaming&&f.length>0?h=f.length===1?f[0]:{key:`${e.id||"x"}-chunk-active-${f[0].key}`,type:"chunk",blocks:f}:l();let d={completed:i,active:h?[h]:[]};if(e.isStreaming){let p=new Map;if(i.forEach(g=>wr(g,p)),h&&wr(h,p),fs.set(o,{text:s,blocksMap:p}),fs.size>qi){let g=fs.keys().next().value;fs.delete(g)}}else{if(qn.set(t,d),qn.size>qi){let p=qn.keys().next().value;qn.delete(p)}fs.delete(o)}return d},Rl={},El=/(\r?\n){2}(?=\[?(?:tool:functions|tool\.functions|agent:generalist|agent\.generalist|\s*turn\s*:))/gi,yr=(e,n)=>{let t=!1;for(let s=0;s<n;s++)e[s]==="`"&&(t=!t);return t},_l=/\[SYSTEM\][\s\S]*?\[\/SYSTEM\]|\[ANSWER\][\s\S]*?(?:\[\/ANSWER\]|$)|\[TOOL RESULT\]:?\s*|^\s*(SUCCESS|ERROR):.*(\r?\n)?|\[\s*turn\s*:\s*(continue|finish)\s*\]|\[\[END\]\]|\[\s*turn\s*:?.*?$|\n\s*turn\s*:?.*?$|\[\s*(?:turn|ANSWER|TOOL).*?$|\n\nResponded on .*|\n\n\[Prompted on: .*\]|@\[TerminalName:.*?, ProcessId:.*?\]/gm,$l=/(\$?\\?\/?\\rightarrow\$?|\$\\rightarrow\$)|(\$?\\?\/?\\leftarrow\$?|\$\\leftarrow\$)|(\$?\\?\/?\\uparrow\$?|\$\\uparrow\$)|(\$?\\?\/?\\downarrow\$?|\$\\downarrow\$)|(\$?\\?\/?\\leftrightarrow\$?|\$\\leftrightarrow\$)/gi,Cl=/\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,As=!1,Ml=(e,n="agent")=>{if(!e)return e;let t=n===!0||n==="think",s=n===!1||n==="agent",o=e.replace(/<\|channel>thought/gi,"<think>").replace(/<channel\|>/gi,"</think>");if(t)return o.replace(/^<(think|thought|thoughts)>/gi,"").replace(/<\/(think|thought|thoughts)>$/gi,"").replace(/^\r?\n+/,"").replace(/\r?\n+$/,"");let r=o;s&&(r=r.replace(El,(h,f,c,l)=>!As&&yr(l,c)?h:""),r&&r.includes("[tool:")&&(r=r.replace(/<(\w+)(?:[^>]*)>\s*([\s\S]*?\[tool:[^\]]*\][\s\S]*?)\s*<\/\1>/gi,(h,f,c)=>c&&c.includes("[tool:")?c.trim():h),As&&(r=r.replace(/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi,(h,f)=>f.includes("[tool:")?f.trim():h))));let a="tool:functions.",i="agent:generalist.";if(s&&(r.toLowerCase().includes(a)||r.toLowerCase().includes(i)))for(;;){let h=r.toLowerCase(),f=h.indexOf(a),c=h.indexOf(i),l=a,u=f;if((f===-1||c!==-1&&c<f)&&(l=i,u=c),u===-1)break;if(!As&&yr(r,u)){let k=u+l.length,$=h.indexOf(a,k),_=h.indexOf(i,k);if($===-1&&_===-1)break;let S=-1,T=0;for(;;){let R=h.indexOf(a,T),E=h.indexOf(i,T),b=-1,C=a;if(R===-1&&E===-1)break;if(R===-1||E!==-1&&E<R?(b=E,C=i):b=R,!yr(r,b)){S=b,l=C;break}T=b+C.length}if(S===-1)break;u=S}let d=u,p=!1,g=u-1;for(;g>=0&&/\s/.test(r[g]);)g--;g>=0&&r[g]==="["&&(d=g,p=!0);let y=0,m=!1,w=null,x=u;for(;x<r.length;){let k=r[x];if(!w&&(k==="'"||k==='"'||k==="`")?w=k:w&&k===w&&r[x-1]!=="\\"&&(w=null),w||(k==="("?(y++,m=!0):k===")"&&y--),m&&y===0&&!w){let $=x;if(p){let _=x+1;for(;_<r.length&&/\s/.test(r[_]);)_++;_<r.length&&r[_]==="]"&&($=_)}r=r.substring(0,d)+r.substring($+1);break}if(x++,x===r.length)return m&&y>0&&(r=r.substring(0,d)),r}}return r=r.replace(_l,""),r=r.replace($l,h=>{let f=h.toLowerCase();return f.includes("leftrightarrow")?"\u2194":f.includes("rightarrow")?"\u2192":f.includes("leftarrow")?"\u2190":f.includes("uparrow")?"\u2191":f.includes("downarrow")?"\u2193":h}),r=r.replace(Cl,h=>Rl[h.toLowerCase()]||h),r.trim()},yd=()=>{qn.clear(),fs.clear()};var br=async(e,n={})=>{let t=L(e),s=t.path;if(!s)return'ERROR: Missing "path" argument for PatchFile.';let{patchPairs:o,allowMultiple:r,error:a}=Ro(t);if(a)return`ERROR: ${a}`;if(o.length===0)return"ERROR: No valid replacement pairs found. Use searchContent1, newContent1, etc.";let i=t.allowMultiple!==void 0?t.allowMultiple===!0||String(t.allowMultiple).toLowerCase()==="true":r,h=Al.resolve(process.cwd(),s);try{if(!xr.existsSync(h))return`ERROR: File [${s}] does not exist. Use WriteFile instead.`;let f=n.forcedContent||xr.readFileSync(h,"utf8");f.startsWith("\uFEFF")&&(f=f.slice(1));let c=f.replace(/\r\n/g,`
355
+ `).replace(/\r/g,`
356
+ `),{content:l,results:u}=Eo(c,o,{allowMultiple:i}),d=u.filter(m=>!m.success),p=u.filter(m=>m.success);if(p.length===0)return`ERROR: Patch Failed to apply to [${s}].
357
+ ${d.map(m=>` \u2022 ${m.error}`).join(`
358
+ `)}`;await ht.recordFileChange(h,c),xr.writeFileSync(h,l,"utf8");let{systemSettings:g}=await en(),y=_o(c,l,u,12,g?.compressToolResults);return d.length>0?`SUCCESS: File [${s}] updated with some blocks failed. [${p.length}/${o.length}] blocks applied.
359
+
360
+ Failures:
361
+ ${d.map(m=>` \u2022 ${m.error}`).join(`
362
+ `)}
363
+
364
+ ${y}`:`SUCCESS: File [${s}] updated. [${u.length}/${o.length}] blocks applied.
365
+
366
+ ${y}`}catch(f){let c=f instanceof Error?f.message:String(f);return`ERROR: Failed to update file [${s}]: ${c}`}};import ds from"fs";import Sr from"path";var vl=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"]),Il=e=>vl.has(e)||e.startsWith(".pnpm"),Ol=e=>{try{let n=String(e.getMonth()+1).padStart(2,"0"),t=String(e.getDate()).padStart(2,"0"),s=String(e.getHours()).padStart(2,"0"),o=String(e.getMinutes()).padStart(2,"0");return`${n}-${t} ${s}:${o}`}catch{return"N/A"}},kr=async e=>{let n=L(e),t=n.path||null;if(!t)return"ERROR: No directory path provided.";let s=1;if(n.recurse!==void 0&&n.recurse!==null)if(typeof n.recurse=="number")s=n.recurse;else if(typeof n.recurse=="boolean")s=n.recurse?2:1;else{let r=parseInt(String(n.recurse).trim(),10);s=isNaN(r)?1:r}s=Math.max(1,Math.min(3,s));let o=Sr.resolve(process.cwd(),t);try{if(!ds.existsSync(o))return`ERROR: Path [${t}] does not exist.`;if(!ds.statSync(o).isDirectory())return`ERROR: Path [${t}] is a file, not a directory. Use ReadFile instead.`;if(s===1){let g=ds.readdirSync(o),y=g.length,m=150,w=g.slice(0,m),x=[];for(let _ of w){let S=Sr.join(o,_),T={name:_,type:"unknown",size:"N/A",mtime:"N/A"};try{let R=ds.statSync(S);T={name:_,type:R.isDirectory()?"directory":"file",size:(R.size/1024).toFixed(1)+"KB",mtime:Ol(R.mtime)}}catch{T.type="inaccessible"}x.push(T)}let k=x.map(_=>_.type==="directory"?`${_.name}/`:`${_.name} (${_.size}, ${_.mtime})`).join(`
367
+ `),$=`
368
+
369
+ (Total items in folder: ${y})`;return y>m&&($=`
370
+
371
+ TRUNCATED: Showing first ${m} of ${y} items.`),g.length=0,w.length=0,x.length=0,`Detailed folder stats for [${t}]:
372
+
373
+ ${k}${$}`}let a=0,i=0,h=0,f=500,c=!1,l=(g,y,m=1)=>{if(y>s||c)return[];let w=[];try{w=ds.readdirSync(g)}catch{return[`${" ".repeat(m-1)}[Inaccessible Directory]`]}let x=[],k=[];for(let T of w){let R=Sr.join(g,T),E=!1;try{E=ds.statSync(R).isDirectory()}catch{}E?x.push({name:T,fullPath:R}):k.push({name:T,fullPath:R})}x.sort((T,R)=>T.name.localeCompare(R.name)),k.sort((T,R)=>T.name.localeCompare(R.name));let $=[],_=" ".repeat(m-1);for(let T of x){if(h>=f){c=!0,$.push(`${_}[Truncated - Maximum item limit reached (${f})]`);break}if(h++,a++,$.push(`${_}${T.name}/`),y<s&&!Il(T.name)){let R=l(T.fullPath,y+1,m+1);$.push(...R)}}let S=[];for(let T of k){if(h>=f){c=!0,$.push(`${_}[Truncated - Maximum item limit reached (${f})]`);break}h++,i++;let R="N/A";try{R=(ds.statSync(T.fullPath).size/1024).toFixed(1)+"KB"}catch{}S.push(`${T.name} (${R})`)}return S.length>0&&$.push(`${_}${S.join("; ")}`),$},d=l(o,1,1).join(`
374
+ `),p=`
375
+
376
+ (Total items scanned: ${h}, Directories: ${a}, Files: ${i})`;return c&&(p=`
377
+
378
+ TRUNCATED: Scan capped at ${f} items. (Directories: ${a}, Files: ${i})`),`Detailed directory tree for [${t}] (recursive depth: ${s}):
379
+
380
+ ${d}${p}`}catch(r){let a=r instanceof Error?r.message:String(r);return`ERROR: Failed to read folder [${t}]: ${a}`}};var $o=async(e,n)=>{let t=L(e),{question:s}=t;if(!s)return'ERROR: Missing "question" argument for ask.';if(!n.onAskUser)return"ERROR: onAskUser callback not provided in tool context.";let o=[];Object.keys(t).forEach(r=>{if(r.startsWith("option")){let a=t[r];if(typeof a=="string"&&a.includes("::")){let[i,h]=a.split("::");o.push({id:r,label:i.trim(),description:h.trim()})}else o.push({id:r,label:String(a).trim(),description:""})}});try{return`USER CHOOSE: ${await n.onAskUser(s,o)}`}catch(r){return`ERROR: Failed to get user input: ${r instanceof Error?r.message:String(r)}`}};import Ll from"puppeteer";import vs from"path";import us from"fs-extra";import{PDFDocument as Pl}from"pdf-lib";var Tr=async e=>{let{path:n,content:t,orientation:s="portrait",margin:o="0px"}=L(e);if(!n)return'ERROR: Missing "path" argument for write_pdf.';if(!t)return'ERROR: Missing "content" (HTML/CSS) for write_pdf.';let r=vs.resolve(process.cwd(),n),a=null;try{await us.ensureDir(vs.dirname(r)),await ht.recordFileChange(r);let i=cs();a=await Ll.launch({headless:!0,executablePath:i.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let h=await a.newPage(),f=t,c={},l=async S=>{if(!S||S.startsWith("http://")||S.startsWith("https://")||S.startsWith("data:"))return null;try{let T=vs.resolve(process.cwd(),S);if(await us.pathExists(T)){let R=vs.extname(T).toLowerCase().replace(".","")||"png",E=R==="jpg"?"jpeg":R==="svg"?"svg+xml":R,b=await us.readFile(T,"base64");return`data:image/${E};base64,${b}`}}catch{}return null},u=/<link[^>]+href=["']([^"']+)["']/gi,d={},p;for(;(p=u.exec(t))!==null;){let S=p[1],T=p[0];if(S&&T.toLowerCase().includes("stylesheet")&&!S.startsWith("http://")&&!S.startsWith("https://")&&!S.startsWith("data:"))try{let R=vs.resolve(process.cwd(),S);if(await us.pathExists(R)){let E=await us.readFile(R,"utf-8");d[T]=`<style>${E}</style>`}}catch{}}for(let[S,T]of Object.entries(d))f=f.split(S).join(T);let g=/<img[^>]+src=["']([^"']+)["']/gi;for(;(p=g.exec(f))!==null;){let S=p[1];if(S&&!c[S]){let T=await l(S);T&&(c[S]=T)}}let y=/url\(\s*['"]?([^'")]+?)['"]?\s*\)/gi;for(;(p=y.exec(f))!==null;){let S=p[1].trim();if(S&&!c[S]){let T=await l(S);T&&(c[S]=T)}}for(let[S,T]of Object.entries(c)){let R=S.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&"),E=new RegExp(`(src=["'])(${R})(["'])`,"gi");f=f.replace(E,`$1${T}$3`);let b=new RegExp(`url\\(\\s*(['"]?)(${R})\\1\\s*\\)`,"gi");f=f.replace(b,`url($1${T}$1)`)}let m=`
381
+ <style>
382
+ @page {
383
+ margin: ${o};
384
+ }
385
+ body {
386
+ margin: 0;
387
+ padding: 0;
388
+ font-family: system-ui, -apple-system, sans-serif;
389
+ }
390
+ * { box-sizing: border-box; }
391
+ .watermark {
392
+ position: fixed;
393
+ top: 50%;
394
+ left: 50%;
395
+ transform: translate(-50%, -50%) rotate(-50deg);
396
+ font-size: 52px;
397
+ font-weight: bold;
398
+ color: rgba(0, 0, 0, 0.005);
399
+ pointer-events: none;
400
+ z-index: -1000;
401
+ text-align: center;
402
+ width: 150%;
403
+ white-space: nowrap;
404
+ text-transform: uppercase;
405
+ letter-spacing: 5px;
406
+ }
407
+ </style>
408
+ <div class="watermark">Generated by FluxFlow CLI (AI)</div>
409
+ ${f}
410
+ `;await h.setContent(m,{waitUntil:"networkidle0",timeout:18e4});let w=await h.pdf({format:"A4",landscape:String(s).toLowerCase()==="landscape",margin:{top:o,right:o,bottom:o,left:o},printBackground:!0}),x=await Pl.load(w),k=vs.basename(n);x.setTitle(`FluxFlow_${k}`),x.setAuthor("FluxFlow CLI"),x.setSubject("Generated with Agentic AI System"),x.setKeywords(["FluxFlow","AI","Agentic","Automated"]),x.setCreator("FluxFlow PDF Engine"),x.setProducer("FluxFlow (Generative AI)");let $=await x.save();await us.writeFile(r,$);let _=await us.stat(r);return`SUCCESS: PDF generated successfully at [${n}] (${(_.size/1024).toFixed(2)} KB).`}catch(i){let h=i instanceof Error?i.message:String(i);return`ERROR: Failed to generate PDF [${n}]: ${h}`}finally{a&&await a.close()}};import zi from"fs-extra";import Rr from"path";import Dl from"html-to-docx";var Er=async e=>{let{path:n,content:t}=L(e);if(!n)return'ERROR: Missing "path" argument for write_docx.';if(!t)return'ERROR: Missing "content" (HTML) for write_docx.';let s=Rr.resolve(process.cwd(),n);try{await zi.ensureDir(Rr.dirname(s)),await ht.recordFileChange(s);let o=Rr.basename(n),r=t.includes("<html")?t:`
411
+ <!DOCTYPE html>
412
+ <html lang="en">
413
+ <head>
414
+ <meta charset="UTF-8">
415
+ <title>FluxFlow Document</title>
416
+ </head>
417
+ <body>
418
+ ${t}
419
+ </body>
420
+ </html>
421
+ `,a=await Dl(r,null,{title:`FluxFlow_${o}`,creator:"FluxFlow CLI",description:"Generated by Agentic AI System",table:{row:{cantSplit:!0}},footer:!0,pageNumber:!0});return await zi.writeFile(s,a),`SUCCESS: Word document [${n}] generated successfully.
422
+ - Size: ${(a.length/1024).toFixed(1)} KB`}catch(o){let r=o instanceof Error?o.message:String(o);return`ERROR: Failed to generate DOCX [${n}]: ${r}`}};import $r from"fs/promises";import ps from"path";import _r from"fast-glob";import{Minimatch as Ki}from"minimatch";async function Xs(e,n,t=e,s=1){if(s>12)return[];let o=[],r;try{r=await $r.readdir(e,{withFileTypes:!0})}catch{return[]}for(let a of r){let i=ps.join(e,a.name),h=ps.relative(t,i),f=h.split(ps.sep).map(u=>u.toLowerCase()),c=a.name.toLowerCase();if(!n.some(u=>{let d=u.toLowerCase();return d.startsWith(".")&&c.endsWith(d)?!0:f.some(p=>p===d||p.startsWith(".pnpm"))}))if(a.isDirectory()){let u=await Xs(i,n,t,s+1);o=o.concat(u)}else a.isFile()&&o.push({fullPath:i,relativePath:h})}return o}function Fl(e,n,t=1/0){if(e===n)return 0;if(e.length===0)return n.length;if(n.length===0)return e.length;if(Math.abs(e.length-n.length)>t)return t+1;let s=Array.from({length:n.length+1},(o,r)=>r);for(let o=1;o<=e.length;o++){let r=[o],a=o;for(let i=1;i<=n.length;i++){let h=e[o-1]===n[i-1]?0:1,f=Math.min(r[i-1]+1,s[i]+1,s[i-1]+h);r.push(f),f<a&&(a=f)}if(s=r,a>t)return t+1}return s[n.length]}function Nl(e,n){if(!e||!n)return!1;let t=e.toLowerCase(),s=n.toLowerCase();if(t.includes(s))return!0;let o=t.split(/[^a-z0-9]+/).filter(a=>a.length>0),r=s.split(/[^a-z0-9]+/).filter(a=>a.length>1||s.length===1&&a.length>0);return r.length===0?!1:r.every(a=>{let i=a.length<=2?0:a.length<=5?1:2;for(let h of o)if(h.includes(a)||a.length>=3&&h.length>=3&&Math.abs(h.length-a.length)<=i&&Fl(a,h,i)<=i)return!0;return!1})}var Js=async e=>{let{keyword:n,path:t,fuzzy:s,subString:o,regex:r}=L(e);if(n==null)return'ERROR: Missing "keyword" argument.';let a=String(n),i=g=>g===!0||g==="true"||g===1||g==="1"||g==="yes",h=r===!1||r==="false"||r===0||r==="0"||r==="no",f=r===!0||r==="true"||r===1||r==="1"||r==="yes",c=i(s)||i(o),l=null,u=null;if(h)c||(u=new RegExp(`(?<![\\w])${a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\\w])`,"i"));else{try{l=new RegExp(a,"i")}catch(g){if(f)return`ERROR: Invalid regex pattern "${a}": ${g.message}`}u=new RegExp(`(?<![\\w])${a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\\w])`,"i")}let d=[".git","node_modules",".gemini","dist","build",".next","out",".cache","bin","obj","vendor","venv",".idea",".gradle",".terraform","target","coverage",".vscode",".svn",".hg",".fslckout",".github",".gitlab",".circleci",".gitea",".gitee",".lerna",".changeset",".nx",".npm",".yarn",".pnpm-store",".pnpm",".expo",".nuxt",".svelte-kit",".docusaurus",".turbo",".vercel","bower_components",".netlify",".vuepress",".quasar",".output",".angular","jspm_packages",".parcel-cache",".rollup.cache",".rspack",".vitepress","__pycache__",".pytest_cache",".mypy_cache",".tox",".poetry","env","vhdl",".ipynb_checkpoints",".jupyter",".conda",".pdm-build",".bundle",".yardoc",".metadata","App_Data","ClientBin",".cargo",".rustc_info",".go","Godeps","_vendor",".rake_tasks","CMakefiles",".wakatime",".dart_tool",".fvm",".cocoapods","Pods",".pub-cache",".symlinks","DerivedData",".xcworkspace",".serverless",".aws",".gcloud",".azure",".kube",".vagrant",".docker","postgres-data","redis-data","mongo-data",".Spotlight-V100",".Trashes","$RECYCLE.BIN","System Volume Information",".DocumentRevisions-V100",".fseventsd","AppData","Application Data","Local","LocalLow","Roaming","$WinREAgent","$WINDOWS.~BT","$WINDOWS.~WS","scw","System32","SysWOW64",".AppleDouble",".AppleDB",".AppleDesktop","_CodeSignature",".cmio",".LSOverride",".localized",".TemporaryItems",".Trash",".Trash-0",".Trash-1000",".gvfs",".local",".config",".dbus",".fontconfig",".snap",".var",".lost+found","lost+found",".thumb",".thumbnails","EFI","boot","grub","logs","log",".nyc_output",".sonar",".ruff_cache",".VSCodeCounter",".exe",".dll",".so",".dylib",".png",".jpg",".jpeg",".gif",".ico",".svg",".webp",".mp3",".mp4",".avi",".zip",".tgz",".tar",".gz",".7z",".rar",".pdf",".docx",".xlsx",".pptx",".woff",".woff2",".ttf",".eot"],p=150;try{let g=[],y=process.cwd(),m=null;if(t){let A=t.split(";").map(W=>W.trim()).filter(Boolean),O=A.some(W=>W.startsWith("!"));if(A.some(W=>_r.isDynamicPattern(W)||/[*?{}[\]()|+]/.test(W))){m="glob";let W=t.replace(/\\/g,"/"),q=A.map(F=>F.replace(/\\/g,"/")),se=d.map(F=>F.startsWith(".")?`**/*${F}`:`**/${F}/**`);if(O&&!A.some(F=>!F.startsWith("!"))){let F=await Xs(y,d,y),B=v=>v.endsWith("/")?v+"**":v,Z=q.filter(v=>v.startsWith("!")).map(v=>B(v.slice(1))),Ce=q.filter(v=>!v.startsWith("!")).map(B);g=F.filter(v=>{let U=v.relativePath.replace(/\\/g,"/"),X=Ce.length===0||Ce.some(Ue=>{try{return new Ki(Ue).match(U)}catch{return!1}}),ee=Z.some(Ue=>{try{return new Ki(Ue).match(U)}catch{return!1}});return X&&!ee})}else{let F=q.some(Z=>/[\(\)\|]|\.\*/.test(Z)),B=[];if(!F)try{B=await _r(q,{cwd:y,ignore:se,dot:!0,onlyFiles:!0,absolute:!1})}catch{B=[]}if(B.length===0&&(F||_r.isDynamicPattern(W))){let Z=W.match(/^([^\*\?\(\)\|\[\]\s]+)\//),Ce=Z&&!/[\*\?\(\)\|\[\]]/.test(Z[1])?ps.resolve(y,Z[1]):y,v=await Xs(Ce,d,y);try{let U=W.replace(/^\.\//,"");U=U.replace(/\.\*\/(\\.|[^\/])/g,".*$1"),!U.startsWith("^")&&!U.startsWith(".*")&&(U=`.*${U}`);let X=new RegExp(U.endsWith("$")?U:`${U}$`,"i");g=v.filter(ee=>{let Ue=ee.relativePath.replace(/\\/g,"/");return X.test(Ue)})}catch{g=[]}}else g=B.map(Z=>({fullPath:ps.resolve(y,Z),relativePath:Z}))}}else{let W=t.replace(/[\/\\]+$/,""),q=ps.resolve(y,W);try{let se=await $r.stat(q);if(se.isDirectory())m="dir",g=await Xs(q,d,y);else if(se.isFile())m="file",g.push({fullPath:q,relativePath:ps.relative(y,q)});else return`ERROR: Path is neither a file nor a directory: ${t}`}catch{return`ERROR: Path not found: ${t}`}}}else g=await Xs(y,d);let w=g.map(async A=>{try{let O=await $r.readFile(A.fullPath,"utf-8");if(O.includes("\0"))return[];let D=O.split(/\r?\n/),W=[];for(let se=0;se<D.length;se++)(c?D[se].toLowerCase().includes(a.toLowerCase())||Nl(D[se],a):h?u&&u.test(D[se]):l&&l.test(D[se])||u&&u.test(D[se]))&&W.push({line:se+1,content:D[se].trim()});return W.length===0?null:{path:A.relativePath.replace(/\\/g,"/"),matches:W}}catch{return[]}}),x=await Promise.all(w),k=[],$=0;for(let A of x){if(!A||!A.matches)continue;if($>=p)break;let O=p-$,D=A.matches.slice(0,O);k.push({path:A.path,matches:D}),$+=D.length}typeof global.gc=="function"&&global.gc();let _=c?"(fuzzy mode)":f?"(regex mode)":h?"(keyword mode)":"(standard mode)";if(k.length===0){let A=m==="file"?` in '${t}'`:m==="dir"||m==="glob"?` in '${t}'`:". Try to specify files",O=m==="dir"?"[DIR]":m==="glob"?"[GLOB]":"";return`${O}${O?" ":""}Found 0 matches of '${a}'${A}${_?` ${_}`:""}`}let S=_?` ${_}`:"",T=`${k.length} file${k.length===1?"":"s"}`,R=`${$} match${$===1?"":"es"}`,E;m==="file"?E=`Found ${R} of '${a}' in '${t}'${S}:`:m==="dir"||m==="glob"?E=`Found ${R} of '${a}' in '${t}' across ${T}${S}:`:E=`Found ${R} of '${a}' across ${T}${S}:`;let b=m==="dir"?"[DIR]":m==="glob"?"[GLOB]":"",C=`${b}${b?" ":""}${E}
423
+
424
+ `;for(let A of k){C+=`${A.path}
425
+ `;for(let O of A.matches)C+=` ${O.line}: ${O.content}
426
+ `;C+=`
427
+ `}return C.trimEnd()}catch(g){return`ERROR: ${g.message}`}};import Yi from"fs-extra";import Cr from"path";var Bl=(e,n={})=>{try{if(e.length<8||e[0]!==137||e[1]!==80||e[2]!==78||e[3]!==71)return e;let t=[],s=[];for(let a=0;a<256;a++){let i=a;for(let h=0;h<8;h++)i&1?i=3988292384^i>>>1:i=i>>>1;s[a]=i}let o=a=>{let i=4294967295;for(let h=0;h<a.length;h++)i=s[(i^a[h])&255]^i>>>8;return(i^4294967295)>>>0},r=(a,i)=>{let h=Buffer.from(a,"ascii"),f=Buffer.from(i,"utf-8"),c=h.length+1+f.length,l=Buffer.alloc(8+c+4);l.writeUInt32BE(c,0),l.write("tEXt",4,"ascii"),h.copy(l,8),l[8+h.length]=0,f.copy(l,8+h.length+1);let u=o(l.subarray(4,8+c));return l.writeUInt32BE(u,8+c),l};for(let[a,i]of Object.entries(n))i!=null&&t.push(r(a,String(i)));if(t.length===0)return e;if(e.subarray(12,16).toString("ascii")==="IHDR"){let i=e.subarray(0,33),h=e.subarray(33);return Buffer.concat([i,...t,h])}return e}catch{return e}},Mr=async(e,n={})=>{let t=L(e),s=t.prompt||t.text,o=t.path||t.outputPath||t.output||"generated_image.png",r=t.ratio;if(!s)return'ERROR: Missing "prompt" argument for generate_image.';let a=["nsfw","naked","nudity","nude","porn","sex","xxx","erotic","gore","bloody","violence","abuse","suicide","murder","hentai","pedophile","rape"],i=s.toLowerCase();if(a.some(f=>i.includes(f)))return"ERROR: Prompt blocked by system safety filter (inappropriate or unsafe content detected).";try{let f=await en();if(!await wi(f))return`ERROR: Insufficient Quota for selected quality. Either tell user reduce quality or wait for next refresh cycle (${(await xi()).nextResetMin||60}m).`;let l=f.imageSettings||{keyType:"Default",quality:"Low-High",apiKey:""},u=l.keyType==="Custom"&&l.apiKey?l.apiKey:FALLBACK_IMAGE_KEY,p={Low:"flux","Low-High":"zimage",Medium:"gptimage","Medium-High":"gptimage",High:"qwen-image",Ultra:"gptimage-large",Premium:"nanobanana-pro"}[l.quality]||"zimage",g=1024,y=1024;if(r){let O=r.replace(/\s+/g,"");O==="16:9"?(g=1024,y=576):O==="9:16"?(g=576,y=1024):O==="4:3"?(g=1024,y=768):O==="3:4"?(g=768,y=1024):O==="1:1"&&(g=1024,y=1024)}let m=Math.floor(Math.random()*1e7),x=`https://gen.pollinations.ai/image/${encodeURIComponent(s)}?model=${p}&width=${g}&height=${y}&seed=${m}&enhance=true&reasoning=high&quality=high&negative=${encodeURIComponent("deformed, distorted, disfigured, poorly drawn, bad anatomy, wrong anatomy, extra limb, missing limb, floating limbs, disconnected limbs, mutation, mutated hands and fingers, blurry, low quality, low resolution, extra fingers, censored, watermarks, signatures")}`,k=await fetch(x,{method:"GET",headers:{Authorization:`Bearer ${u}`}});if(!k.ok){let O=k.status,D="";try{D=await k.text()}catch{}return O===402||D.includes("Insufficient balance")||D.includes("PAYMENT_REQUIRED")?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed with status [${O}]: ${D||"Unknown API Error"}`}if((k.headers.get("content-type")||"").includes("application/json")){let O=await k.json();return O.status===402||O.error&&O.error.code==="PAYMENT_REQUIRED"?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed: ${O.error?.message||JSON.stringify(O)}`}let _=await k.arrayBuffer(),S=Buffer.from(_),T={Title:s,Description:"Generated via FluxFlow CLI",Software:"FluxFlow CLI",Author:"FluxFlow","Creation Time":new Date().toISOString(),Prompt:s,Model:`Fluxflow:${p}`,Ratio:r||"1:1",Seed:String(m)};S=Bl(S,T);let R=Cr.resolve(process.cwd(),o);await Yi.ensureDir(Cr.dirname(R)),await ht.recordFileChange(R),await Yi.writeFile(R,S),await bi(f);let E=Cr.extname(o).toLowerCase(),C={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".webp":"image/webp"}[E]||"image/png";return n.isMultiModal!==!1?{text:`SUCCESS: Image successfully generated from prompt [${s}] and saved to [${o}]. Output attached to multimodal part`,binaryPart:{inlineData:{data:S.toString("base64"),mimeType:C}}}:`SUCCESS: Image successfully generated from prompt [${s}] and saved to [${o}].`}catch(f){return`ERROR: Failed during image generation: ${f instanceof Error?f.message:String(f)}`}};var Qs=async(e,n={})=>{let t=r=>{let a=new RegExp(`${r}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),i=e.match(a);return i?i[2].trim():null},s=t("id"),o=t("summary");if(!s||!o)return"ERROR: Missing 'id' or 'summary' for saveSummary tool.";try{let r=ne(Zt,{}),a=ne(In,{});return a[s]=o,delete r[s],he(In,a),he(Zt,r),`SUCCESS: Saved summary and purged raw memories for chat [${s}].`}catch(r){let a=r instanceof Error?r.message:String(r);return`ERROR: Failed to save summary for chat [${s}]: ${a}`}};var Is=async(e,n={})=>{let s=(o=>{let r=new RegExp(`${o}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),a=e.match(r);return a?a[2].trim():null})("id");if(!s)return"ERROR: Missing 'id' parameter for addMemScore tool.";try{let o=ne(Dt,[]),r=!1,a=[];for(let c of o)c.score===void 0&&(c.score=.5),c.id===s?(c.score=Math.min(2,c.score+.2),r=!0):(c.score*=.98,c.score<.05&&(c.score=0)),c.score=Math.round(c.score*1e5)/1e5,c.score>0&&a.push(c);if(he(Dt,a),!r)return`WARNING: Memory ID [${s}] not found. Other memories decayed by -0.01.`;let i=a.find(c=>c.id===s),h=i?i.score.toFixed(2):"deleted (score <= 0)",f=o.length-a.length;return`SUCCESS: Adjusted memory scores. Target [${s}] is now ${h}.${f>0?` Purged ${f} decayed memories.`:""}`}catch(o){let r=o instanceof Error?o.message:String(o);return`ERROR: Failed to adjust memory score for [${s}]: ${r}`}};import vr from"fs-extra";import ms from"path";import{createRequire as jl}from"module";import hs from"fs-extra";import Ar from"path";import Ul from"https";var Vi={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 Wl(e,n=null){let t=n||`https://unpkg.com/tree-sitter-wasms@0.1.13/out/${e}`,s=Ar.join(as,e);return await hs.ensureDir(as),new Promise((o,r)=>{let a={headers:{"User-Agent":"FluxFlow-Agent"}};Ul.get(t,a,i=>{if([301,302,307,308].includes(i.statusCode)&&i.headers.location){let f=i.headers.location;if(!f.startsWith("http")){let c=new URL(t);f=`${c.protocol}//${c.host}${f}`}Wl(e,f).then(o).catch(r);return}if(i.statusCode!==200){r(new Error(`Failed to download ${e}: HTTP ${i.statusCode}`));return}let h=hs.createWriteStream(s);i.pipe(h),h.on("finish",()=>{h.close(),o()})}).on("error",i=>{hs.existsSync(s)&&hs.unlink(s,()=>{}),r(i)})})}function mu(e){let n=Ar.join(as,e);return hs.existsSync(n)}async function gu(e){let n=Ar.join(as,e);hs.existsSync(n)&&await hs.unlink(n)}var Qi=jl(import.meta.url),Xi=Qi("web-tree-sitter"),Ji=!1,Zi=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"]),ea=new Set(["export_statement","lexical_declaration","variable_declaration","variable_declarator","pair","assignment_expression"]);function wn(e,n=50){if(!e)return"";let t=e.replace(/\s+/g," ").trim();return t.length>n?t.substring(0,n-3)+"...":t}function ta(e){let n=e.type;if(n==="if_statement"){let s=e.childForFieldName("condition");return s?`if (${wn(s.text,40)})`:"if"}if(n==="else_clause")return"else";if(n==="while_statement"||n==="do_statement"){let s=e.childForFieldName("condition");return`${n.split("_")[0]} (${s?wn(s.text,40):""})`}if(n==="for_statement"||n==="for_in_statement"||n==="for_of_statement"){let o=e.text.split(`
428
+ `)[0].match(/for\s*(?:await\s*)?\((.*)\)/);return o?`for (${wn(o[1],40)})`:"for"}if(n==="switch_statement"){let s=e.childForFieldName("value");return`switch (${s?wn(s.text,40):""})`}if(n==="try_statement")return"try";if(n==="catch_clause")return"catch";if(n==="element"||n==="script_element"||n==="style_element"||n==="jsx_element"||n==="jsx_self_closing_element"){let s=e.childForFieldName("opening_element")||e.childForFieldName("start_tag")||e.children.find(r=>r.type==="start_tag")||e,o=s.childForFieldName("name")||s.childForFieldName("tag_name")||s.children.find(r=>r.type==="tag_name");return o?`<${wn(o.text,30)}>`:null}if(["import_declaration","import_from_statement","import_statement","preproc_include"].includes(n))return wn(e.text.split(`
429
+ `)[0],60);if(n==="pair"){let s=e.childForFieldName("key");return s?wn(s.text.replace(/["']/g,""),40):null}if(n==="assignment_expression"){let s=e.childForFieldName("left");return s?`${wn(s.text,30)} = ...`:null}if(n==="variable_declarator"){let s=e.childForFieldName("name")||e.children.find(o=>["identifier","object_pattern","array_pattern"].includes(o.type));return s?wn(s.text,40):null}let t=e.childForFieldName("name")||e.childForFieldName("declarator")||e.children.find(s=>["identifier","type_identifier","field_identifier","property_identifier","shorthand_property_identifier"].includes(s.type));if(t){if(t.type.includes("declarator")){let s=t.descendantsOfType("identifier")[0]||t.descendantsOfType("field_identifier")[0];if(s)return wn(s.text,40)}return wn(t.text,40)}if(["arrow_function","function_expression","function_declaration"].includes(n)){let s=e.parent;for(;s&&s.type!=="program";){let o=ta(s);if(o)return o;if(!ea.has(s.type))break;s=s.parent}}return null}function Hl(e){let n=[];function t(s){for(let o of s.children)Zi.has(o.type)?n.push(o):t(o)}return t(e),n}function Gl(e){return e.replace(/_([a-z])/g,n=>n[1].toUpperCase())}function na(e,n=0,t=!0,s="",o=null,r=12){let a=e.type,i=ta(e),h=Zi.has(a)||n===0,f=Hl(e),c=h&&n>0&&(ea.has(a)&&f.length>0||i!==null&&i===o&&f.length>0),l="",u=s,d=n,p=o;if(h&&!c){let g=e.startPosition.row+1,y=e.endPosition.row+1,m=Gl(a),w=i?`${m} [${i}]`:m;n===0?(l+=`\u{1F4C1} ROOT (Lines: ${g}-${y})
430
+ `,u=s):(l+=`${s}${t?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 "}${w} (Lines: ${g}-${y})
431
+ `,u+=t?" ":"\u2502 "),d=n+1,p=i}return d>r&&f.length>0?l+=`${u}\u2514\u2500\u2500 ... depth exceeded ...
432
+ `:f.forEach((g,y)=>{let m=y===f.length-1;l+=na(g,d,c?t&&m:m,u,p,r)}),l}var Ir=async e=>{let n;try{n=L(e).path}catch{return`ERROR: Failed to parse arguments: ${e}`}if(!n)return'ERROR: No file path provided. Use [tool:functions.FileMap(path="...")]';let t=ms.isAbsolute(n)?n:ms.resolve(process.cwd(),n);if(!vr.existsSync(t))return`ERROR: File not found: ${n}`;let s=ms.extname(t).slice(1).toLowerCase(),o=Vi[s];if(!o)return`ERROR: Unsupported file extension: .${s}`;let r=ms.resolve(as,o);if(!vr.existsSync(r))return`ERROR: Parser for .${s} not found. Please download it in Settings > Other.`;try{let a=Xi.Parser;if(!Ji){let p;try{p=ms.join(ms.dirname(Qi.resolve("web-tree-sitter")),"tree-sitter.wasm")}catch{p=ms.join(process.cwd(),"node_modules","web-tree-sitter","tree-sitter.wasm")}await a.init({locateFile:g=>g==="tree-sitter.wasm"||g.endsWith("tree-sitter.wasm")?p:g}),Ji=!0}let i=new a,h=await Xi.Language.load(r);i.setLanguage(h);let f=await vr.readFile(t,"utf8"),c=f.split(`
433
+ `).length,l=12;c>1e4?l=2:c>=8e3?l=3:c>=5e3?l=5:c>=4e3?l=8:c>2e3&&(l=10);let u=i.parse(f),d=na(u.rootNode,0,!0," ",null,l);return`\u{1F4C4} File Map for: ${n}
434
+ ${d}`}catch(a){let i=a instanceof Error?a.message:typeof a=="object"?JSON.stringify(a):String(a),h=a instanceof Error?`
435
+ Stack: ${a.stack}`:"";return`ERROR: Failed to map file: ${i}${h}`}};import zn from"fs";import sa from"path";var Zs=async(e,n={})=>{let{method:t,tasks:s,markDone:o}=L(e),r=n.chatId||"default";if(!t)return'ERROR: Missing "method" argument for todo tool (create/append/get).';let a=sa.join(vn,"plan",r),i=sa.join(a,"todo.md"),h=l=>{if(!l||Array.isArray(l))return l;let u=String(l).trim();if(u.startsWith("[")&&u.endsWith("]")){let d=u.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);return d?d.map(p=>p.slice(1,-1).replace(/\\(.)/g,"$1")):u.slice(1,-1).split(",").map(p=>p.trim()).filter(Boolean)}return l},f=l=>{let u=h(l);return u?(Array.isArray(u)?u:String(u).split(`
436
+ `)).map(p=>{let g=String(p).trim();return g?g.startsWith("- [ ]")||g.startsWith("- [x]")||g.startsWith("- [X]")?g:`- [ ] ${g}`:null}).filter(Boolean).join(`
437
+ `)+`
438
+ `:""},c=(l,u)=>{if(!u)return{content:l,markedCount:0};let d=h(u),p=(Array.isArray(d)?d:[d]).map(w=>String(w).replace(/^- \[[xX ]\]\s*/i,"").trim()).filter(Boolean),g=l.split(`
439
+ `),y=0,m=!1;for(let w of p){let x=!1;for(let k=0;k<g.length;k++)if(g[k].includes(w)&&/^- \[\s\]/.test(g[k].trim())){g[k]=g[k].replace("- [ ]","- [x]"),x=!0,m=!0,y++;break}if(!x){for(let k=0;k<g.length;k++)if(g[k].toLowerCase().includes(w.toLowerCase())&&/^- \[\s\]/.test(g[k].trim())){g[k]=g[k].replace("- [ ]","- [x]"),x=!0,m=!0,y++;break}}}return{content:m?g.join(`
440
+ `):l,markedCount:y}};try{if(zn.existsSync(a)||zn.mkdirSync(a,{recursive:!0}),t==="create"){if(!s)return'ERROR: Missing "tasks" for create method.';let l=f(s),u=0;if(o){let p=c(l,o);l=p.content,u=p.markedCount}await ht.recordFileChange(i),zn.writeFileSync(i,l,"utf8");let d=l.split(/\r?\n/).map(p=>p.trim()).filter(p=>p.startsWith("- [ ]")||p.startsWith("- [x]")||p.startsWith("- [X]")).length;if(u>0){let p=l.split(/\r?\n/).map(g=>g.trim()).filter(g=>g.startsWith("- [x]")||g.startsWith("- [X]")).length;return`SUCCESS: TASK LIST CREATED (${u} marked done, ${p} completed, ${d-p} left)
441
+ ${l}`}return`SUCCESS: TASK LIST CREATED (${d} total)
442
+ ${l}`}if(t==="append"){if(!s)return'ERROR: Missing "tasks" for append method.';let l=f(s);await ht.recordFileChange(i),zn.appendFileSync(i,l,"utf8");let u=zn.readFileSync(i,"utf8"),d=u.split(/\r?\n/).map(m=>m.trim()),p=d.filter(m=>m.startsWith("- [ ]")||m.startsWith("- [x]")||m.startsWith("- [X]")).length,g=d.filter(m=>m.startsWith("- [x]")||m.startsWith("- [X]")).length,y=l.split(/\r?\n/).map(m=>m.trim()).filter(m=>m.startsWith("- [ ]")||m.startsWith("- [x]")||m.startsWith("- [X]")).length;return`SUCCESS: TASK APPENDED (${g} completed, ${p-g} left, ${y} added)
443
+ ${u}`}if(t==="get"){if(!zn.existsSync(i))return"TODO GET: No task list found for this session.";let l=zn.readFileSync(i,"utf8"),u=0;if(o){let m=c(l,o);m.markedCount>0&&(l=m.content,u=m.markedCount,await ht.recordFileChange(i),zn.writeFileSync(i,l,"utf8"))}let d=l.split(/\r?\n/).map(m=>m.trim()),p=d.filter(m=>m.startsWith("- [ ]")||m.startsWith("- [x]")||m.startsWith("- [X]")).length,g=d.filter(m=>m.startsWith("- [x]")||m.startsWith("- [X]")).length;return`${u>0?`SUCCESS: ${u} TASK(S) MARKED DONE`:"TODO GET"}: ${g} Completed, ${p-g} left
444
+ ${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 Or=async(e,n={})=>{let{runSubagent:t}=await import("./ai-MBEY7TQE.js"),s=L(e),o=s.task||s.instruction||s.prompt,r=s.model||null,a=s.tools||null;if(!o)return'ERROR: Missing "task" argument for invokeSync.';let i=null;if(a)try{let f=a.trim();f.startsWith("[")&&f.endsWith("]")&&(f=f.substring(1,f.length-1)),i=f.split(",").map(c=>c.trim().replace(/^["']|["']$/g,"")).filter(Boolean)}catch{}let h=s.title||o.substring(0,30);try{n.onVisualFeedback&&n.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${h}`);let f=await t(o,n,r,i,50);return n.onVisualFeedback&&n.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${h} [COMPLETED]
445
+ `),f}catch(f){let{isTerminationSignaled:c}=await import("./ai-MBEY7TQE.js"),l=f.message==="Subagent task was cancelled by user."||c();if(n.onVisualFeedback){let u=l?"[CANCELLED]":"[FAILED]";n.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${h} ${u}
446
+ `)}return`ERROR: Subagent execution failed: ${f.message}`}};var oa=async(e,n={})=>{let{runSubagent:t}=await import("./ai-MBEY7TQE.js"),s=L(e),o=s.task||s.instruction||s.prompt,r=s.model||null,a=s.title||null,i=s.tools||null;if(!o)return'ERROR: Missing "task" argument for invoke.';let h=null;if(i)try{let m=i.trim();m.startsWith("[")&&m.endsWith("]")&&(m=m.substring(1,m.length-1)),h=m.split(",").map(w=>w.trim().replace(/^["']|["']$/g,"")).filter(Boolean)}catch{}let f=`subagent-${Date.now()}-${Math.floor(Math.random()*1e3)}`,c=null,l=null,u=new Promise((m,w)=>{c=m,l=w}),d={id:f,title:a||o.substring(0,30),task:o,status:"running",startedAt:Date.now(),lastChunkTime:Date.now(),wps:0,questions:[],pendingSteerMessages:[],steer:m=>{m&&d.pendingSteerMessages.push(m)},completionPromise:u,_resolveCompletion:c,_rejectCompletion:l,progress:[]},p={chunks:[],totalWords:0};Ve.push(d),n.onSubagentUpdate&&n.onSubagentUpdate();let g=[],y={...n,taskId:f,onAskMain:async m=>{let w=`q-${Date.now()}-${Math.floor(Math.random()*1e3)}`,x=null,k=new Promise(S=>{x=S}),$={id:w,question:m,answered:!1,answer:null,askedAt:Date.now(),_resolve:x};return d.questions.push($),d.status="waiting",n.onSubagentUpdate&&n.onSubagentUpdate(),yo(`[SYSTEM] Background subagent "${d.title}" is WAITING FOR YOUR INPUT: "${m}"
447
+ Respond using tool: [tool:functions.Answer(id="${f}", answer="...")]
448
+ [/SYSTEM]`),await k},onVisualFeedback:m=>{d.lastChunkTime=Date.now();let w=m.replace(/\x1b\[[0-9;]*m/g,""),x=w.match(/[✔✘✗✖🔍📖→➕↻•]\s*([A-Za-z0-9\s-]+)/);x?d.currentTool=x[1].trim():d.currentTool=w,n.onSubagentUpdate&&n.onSubagentUpdate()},onTokenChunk:(m,w)=>{let x=Date.now();if(d.lastChunkTime=x,d.currentTool="Thinking",typeof w=="number"&&w>0){p.totalWords+=w,p.chunks.push({time:x,words:w});let k=x-400;if(p.chunks=p.chunks.filter($=>$.time>=k),p.chunks.length>0){let $=p.chunks.reduce((T,R)=>T+R.words,0),_=p.chunks[0].time,S=Math.max(.4,(x-_)/1e3);d.wps=Math.round($/S*10)/10}}n.onSubagentUpdate&&n.onSubagentUpdate()}};return t(o,y,r,h,50,m=>{if(d.status==="cancelled")return;if(m.startsWith("[Subagent Turn")&&g.length>0&&(d.progress.push([...g]),g=[]),m.includes("[Executing Tool]")){let x=m.match(/\[Executing Tool\]\s*([a-zA-Z0-9_]+)/);x&&(!d.currentTool||d.currentTool==="Thinking")&&(d.currentTool=x[1])}let w=m;if(w.startsWith("[Tool Result]")){let x=w.split(`
449
+ `);x.length>5&&(w=x.slice(0,4).join(`
450
+ `)+`
451
+ ... [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-MBEY7TQE.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 Lr=async(e,n={})=>{let s=L(e).id;if(!s)return'ERROR: Missing "id" argument for getProgress.';let o=Ve.find(i=>i.id===s);if(!o)return`ERROR: Subagent task with ID [${s}] not found.`;let r=`Subagent Task Status: ${o.status.toUpperCase()}
452
+ `;if(r+=`Title: ${o.title}
453
+ `,r+=`Task: ${o.task}
454
+ `,o.startedAt){let i=Math.floor((Date.now()-o.startedAt)/1e3);r+=`Elapsed Time: ${i}s
455
+ `}if(r+=`Turns Completed: ${o.progress.length}
456
+ `,(o.status==="running"||o.status==="waiting")&&(o.currentTool&&(r+=`Current Tool: ${o.currentTool}
457
+ `),o.wps>0&&(r+=`TPS: ${o.wps}
458
+ `)),o.questions&&o.questions.length>0){let i=o.questions.filter(h=>!h.answered);i.length>0&&(r+=`
459
+ **PENDING QUESTION**
460
+ `,i.forEach(h=>{r+=`"${h.question}"
461
+ `}),r+=`Respond using tool: [tool:functions.Answer(id="${o.id}", answer="...")]
462
+
463
+ `)}return r+=`
464
+ Progress Log:
465
+ `,o.progress.forEach((i,h)=>{r+=`--- Turn ${h+1} ---
466
+ `;let c=i.filter(l=>!l.startsWith("[SUBAGENT SUCCESS]")).map(l=>{if(l.startsWith("[Subagent Response]")){let u="[Subagent Response]",p=l.substring(u.length),g="tool:functions.";for(;;){let m=p.toLowerCase().indexOf(g);if(m===-1)break;let w=m,x=!1,k=m-1;for(;k>=0&&/\s/.test(p[k]);)k--;k>=0&&p[k]==="["&&(w=k,x=!0);let $=0,_=!1,S=null,T=m;for(;T<p.length;){let R=p[T];if(!S&&(R==="'"||R==='"'||R==="`")?S=R:S&&R===S&&p[T-1]!=="\\"&&(S=null),S||(R==="("?($++,_=!0):R===")"&&$--),_&&$===0&&!S){let E=T;if(x){let b=T+1;for(;b<p.length&&/\s/.test(p[b]);)b++;b<p.length&&p[b]==="]"&&(E=b)}p=p.substring(0,w)+p.substring(E+1);break}if(T++,T===p.length){p=p.substring(0,w);break}}}return u+`
467
+ `+p.trim()}return l.startsWith("[Executing Tool]")&&l.length>256?l.substring(0,256)+"...[truncated from logs]":l});r+=c.join(`
468
+ `)+`
469
+
470
+ `}),o.status==="completed"&&o.finalAnswer?r+=`Final Answer:
471
+ ${o.finalAnswer}
472
+ `:o.status==="failed"&&o.error&&(r+=`Failure Error: ${o.error}
473
+ `),r.replace(/\r\n/g,`
474
+ `).replace(/\n{3,}/g,`
475
+
476
+ `).trim().replace(/\[TOOL RESULT\]/gi,"TOOL RESULT:")};var ra=async(e,n={})=>{let s=L(e).id;if(!s)return'ERROR: Missing "id" argument for cancel.';let o=Ve.find(r=>r.id===s);return o?o.status==="completed"||o.status==="failed"?`INFO: Subagent task with ID [${s}] has already finished with status [${o.status.toUpperCase()}].`:o.status==="cancelled"?`INFO: Subagent task with ID [${s}] is already cancelled.`:(o.status="cancelled",n.onSubagentUpdate&&n.onSubagentUpdate(),`SUCCESS: Subagent task with ID [${s}] has been cancelled.`):`ERROR: Subagent task with ID [${s}] not found.`};import xt from"fs-extra";import Tt from"path";var ql=["node_modules","dist","bin","logs",".git",".fluxflow","secret",".gemini",".agents","tmp","temp","build","out","snapshots"];async function eo(e,n=e){let t={},s=await xt.readdir(e,{withFileTypes:!0}).catch(()=>[]);for(let o of s){if(ql.includes(o.name))continue;let r=Tt.join(e,o.name),a=Tt.relative(n,r).replace(/\\/g,"/");if(o.isDirectory()){let i=await eo(r,n);Object.assign(t,i)}else{let i=await xt.stat(r).catch(()=>null);i&&(t[a]={size:i.size,mtime:i.mtimeMs})}}return t}async function ia(e,n){await xt.ensureDir(e);for(let t of Object.keys(n)){let s=Tt.join(process.cwd(),t),o=Tt.join(e,t);await xt.ensureDir(Tt.dirname(o)),await xt.copyFile(s,o).catch(()=>{})}}async function Pr(e,n,t=null,s=null){if(!await xt.pathExists(e))return;s||(s=e);let o=await xt.readdir(e,{withFileTypes:!0}).catch(()=>[]);for(let r of o){let a=Tt.join(e,r.name),i=Tt.join(n,r.name);if(r.isDirectory())await Pr(a,i,t,s);else{let h=Tt.relative(s,a).replace(/\\/g,"/"),f=await xt.pathExists(i);f&&await xt.chmod(i,438).catch(()=>{}),await xt.ensureDir(Tt.dirname(i));let c=await xt.copyFile(a,i).then(()=>!0).catch(()=>!1);await xt.chmod(i,438).catch(()=>{}),t&&(c?f?t.replaced++:t.restored++:t.failed.push(h))}}}var Kn={async takeInitialSnapshot(e){try{let n=Tt.join(vn,"snapshots",e);await xt.remove(n).catch(()=>{}),await xt.ensureDir(n);let t=await eo(process.cwd());await ia(Tt.join(n,"initial"),t);let s=ne(mn,{});s[e]={initialManifest:t,currentManifest:t,checkpoints:[{id:"initial",timestamp:new Date().toISOString(),newFiles:[],modifiedFiles:[],deletedFiles:[],toolsUsed:[]}]},he(mn,s)}catch{}},async recordTurnDelta(e,n,t=[]){try{let s=ne(mn,{}),o=s[e];if(!o)return;let r=o.currentManifest||o.initialManifest,a=await eo(process.cwd()),i=[],h=[],f=[];for(let[l,u]of Object.entries(a)){let d=r[l];d?(d.size!==u.size||d.mtime!==u.mtime)&&h.push(l):i.push(l)}for(let l of Object.keys(r))a[l]||f.push(l);let c=[...i,...h];if(c.length>0||f.length>0){let l={};for(let d of c)l[d]=a[d];let u=Tt.join(vn,"snapshots",e,`turn_${n}`);await ia(u,l)}o.checkpoints.push({id:`turn_${n}`,timestamp:new Date().toISOString(),newFiles:i,modifiedFiles:h,deletedFiles:f,toolsUsed:t}),o.currentManifest=a,he(mn,s)}catch{}},async getCheckpoints(e){try{let t=ne(mn,{})[e];return t?t.checkpoints||[]:[]}catch{return[]}},async rollbackToCheckpoint(e,n){try{let t=ne(mn,{}),s=t[e];if(!s)throw new Error("No session active for Advance Rollback.");let o=s.checkpoints||[],r=o.findIndex(c=>c.id===n);if(r===-1)throw new Error(`Checkpoint [${n}] not found.`);let a=Tt.join(vn,"snapshots",e),i={restored:0,replaced:0,failed:[]},h=await eo(process.cwd());for(let c of Object.keys(h)){let l=Tt.join(process.cwd(),c);await xt.chmod(l,438).catch(()=>{}),await xt.remove(l).catch(()=>{})}let f=Tt.join(a,"initial");await Pr(f,process.cwd(),i,f);for(let c=1;c<=r;c++){let l=o[c],u=Tt.join(a,l.id);if(await Pr(u,process.cwd(),i,u),l.deletedFiles&&l.deletedFiles.length>0)for(let d of l.deletedFiles){let p=Tt.join(process.cwd(),d);await xt.chmod(p,438).catch(()=>{}),await xt.remove(p).catch(()=>{})}}return s.checkpoints=o.slice(0,r+1),s.currentManifest=await eo(process.cwd()),he(mn,t),{checkpointId:n,stats:i}}catch(t){throw new Error(`Rollback failed: ${t.message}`)}},async getLatestFileChanges(e){try{let t=ne(mn,{})[e];if(!t||!t.checkpoints||t.checkpoints.length===0)return{newFiles:[],modifiedFiles:[],deletedFiles:[]};let s=t.checkpoints[t.checkpoints.length-1];return{newFiles:s.newFiles||[],modifiedFiles:s.modifiedFiles||[],deletedFiles:s.deletedFiles||[]}}catch{return{newFiles:[],modifiedFiles:[],deletedFiles:[]}}},async cleanup(e){try{let n=Tt.join(vn,"snapshots",e);await xt.remove(n).catch(()=>{});let t=ne(mn,{});t[e]&&(delete t[e],he(mn,t))}catch{}}};var Dr=async(e,n={})=>{let t=L(e),s=t.method,o=t.id,r=n.chatId;if(!n.systemSettings?.advanceRollback)return"ERROR: Advance Rollback feature is currently disabled in settings under Security. Tell user to enable it.";if(!r)return"ERROR: No active chat transaction found for rollback.";if(s==="getCheckpoint"){let i=await Kn.getCheckpoints(r);if(i.length===0)return"No checkpoints available.";let h={write_file:"WriteFile",update_file:"PatchFile",view_file:"ReadFile",read_folder:"ReadFolder",exec_command:"Run",web_search:"WebSearch",web_scrape:"WebScrape",search_keyword:"SearchKeyword",CodeSearch:"SearchKeyword",code_search:"SearchKeyword",write_pdf:"WritePDF",write_docx:"WriteDoc",generate_image:"GenerateImage",file_map:"FileMap",todo:"Todo",goal:"Goal",Goal:"Goal",await:"Await",ask:"AskUser",ask_user:"AskUser",AskUser:"AskUser",askuser:"AskUser",invoke:"Invoke",invokesync:"InvokeSync",getprogress:"GetProgress",cancel:"Cancel",emergency_rollback:"EmergencyRollback",emergencyrollback:"EmergencyRollback"},f=l=>h[l]||h[l.toLowerCase()]||l,c=`Available checkpoints for rollback:
477
+
478
+ `;for(let l of i)if(l.id==="initial")c+=`--- Initial State (id: initial) ---
479
+ Tools Used: User Prompted for task
480
+
481
+ `;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}) ---
482
+ Tools Used: ${d}
483
+
484
+ `}return c.trim()}else if(s==="forceRevert"){if(!o)return"ERROR: Missing required parameter 'id' for forceRevert.";try{let i=await Kn.rollbackToCheckpoint(r,o),{checkpointId:h,stats:f}=i,c=f.restored+f.replaced+f.failed.length,l=`SUCCESS: Repository rolled back to checkpoint [${h}].
485
+
486
+ `;return l+=`Stats:
487
+ `,l+=` Restored : ${f.restored} file${f.restored!==1?"s":""} (new to workspace)
488
+ `,l+=` Replaced : ${f.replaced} file${f.replaced!==1?"s":""} (overwritten)
489
+ `,l+=` Failed : ${f.failed.length} file${f.failed.length!==1?"s":""}`,f.failed.length>0&&(l+=`
490
+ ${f.failed.join(`
491
+ `)}`),l+=`
492
+ \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-
493
+ `,l+=` Total : ${c} file${c!==1?"s":""} processed`,l}catch(i){return`ERROR: ${i.message}`}}else return`ERROR: Invalid method "${s}". Use "getCheckpoint" or "forceRevert".`};var Os=async(e,n={})=>{let t=L(e),s=t.id,o=parseInt(t.timeout||t.time||"120",10);if((isNaN(o)||o<=0)&&(o=120),o>300&&(o=300),!s)return t.time?(await new Promise(h=>setTimeout(h,o*1e3)),`SUCCESS: Waited for ${o}s.`):'ERROR: Missing "id" argument for Await.';let r=Ve.find(h=>h.id===s);if(!r)return`ERROR: Subagent task with ID [${s}] not found.`;if(r.status==="completed")return`SUCCESS: Subagent task [${s}] completed.
494
+ Final Answer:
495
+ ${r.finalAnswer||"(No output)"}`;if(r.status==="failed")return`ERROR: Subagent task [${s}] failed.
496
+ Error: ${r.error||"Unknown error"}`;if(r.status==="cancelled")return`INFO: Subagent task [${s}] was cancelled.`;let a,i=new Promise(h=>{a=setTimeout(()=>{h({type:"timeout"})},o*1e3)});try{let h=await Promise.race([r.completionPromise.then(()=>({type:"completion"})),i]);return clearTimeout(a),h.type==="timeout"?`TIMEOUT: Subagent task [${s}] is still running (status: ${r.status.toUpperCase()}) after ${o}s. You can continue other work or call Await again.`:r.status==="completed"?`SUCCESS: Subagent task [${s}] completed.
497
+ Final Answer:
498
+ ${r.finalAnswer||"(No output)"}`:r.status==="failed"?`ERROR: Subagent task [${s}] failed.
499
+ Error: ${r.error||"Unknown error"}`:r.status==="cancelled"?`INFO: Subagent task [${s}] was cancelled.`:`INFO: Subagent task [${s}] status changed to ${r.status.toUpperCase()}.`}catch(h){return clearTimeout(a),`ERROR: Exception while awaiting subagent [${s}]: ${h.message}`}};var Ls=async(e,n={})=>{let t=L(e),s=t.id,o=t.answer||t.response;if(!s)return'ERROR: Missing "id" argument for Answer.';if(!o)return'ERROR: Missing "answer" argument for Answer.';let r=Ve.find(i=>i.id===s);if(!r)return`ERROR: Subagent task with ID [${s}] not found.`;if(!r.questions||r.questions.length===0)return`INFO: Subagent task [${s}] has no pending questions.`;let a=r.questions.filter(i=>!i.answered);return a.length===0?`INFO: Subagent task [${s}] has no unanswered questions.`:(a.forEach(i=>{i.answered=!0,i.answer=o,i.answeredAt=Date.now(),i._resolve&&i._resolve(o)}),r.status="running",n.onSubagentUpdate&&n.onSubagentUpdate(),`SUCCESS: Answer provided to subagent task [${s}]. Subagent execution resumed.`)};var to=async(e,n={})=>{let t=L(e),s=t.id,o=t.message||t.instruction||t.text||t.prompt;if(!s)return'ERROR: Missing "id" argument for Steer.';if(!o)return'ERROR: Missing "message" argument for Steer.';let r=Ve.find(a=>a.id===s);return r?r.status==="completed"||r.status==="failed"||r.status==="cancelled"?`ERROR: Cannot steer subagent task [${s}] because it has already finished with status [${r.status.toUpperCase()}].`:(typeof r.steer=="function"?r.steer(o):(r.pendingSteerMessages||(r.pendingSteerMessages=[]),r.pendingSteerMessages.push(o)),n.onSubagentUpdate&&n.onSubagentUpdate(),`SUCCESS: Steering instruction injected into subagent task [${s}]. It will be processed on the subagent's turn.`):`ERROR: Subagent task with ID [${s}] not found.`};import{mouse as fn,keyboard as Ft,Button as no,Key as P,Point as so,clipboard as zl}from"@nut-tree-fork/nut-js";fn.config.autoDelayMs=50;Ft.config.autoDelayMs=50;async function Fr(){try{await Ft.releaseKey(P.LeftControl,P.RightControl,P.LeftAlt,P.RightAlt,P.LeftShift,P.RightShift,P.LeftSuper,P.RightSuper)}catch{}}async function On(e,n,t={}){let s=await Gs(n);if(!s&&(e==="move"||e==="click"||e==="drag"))return`ERROR: Invalid target location specified: ${JSON.stringify(n)}`;try{switch(e.toLowerCase()){case"move":return await fn.setPosition(new so(s.x,s.y)),`SUCCESS: Moved mouse to grid target ${typeof n=="string"?n:`(${s.x}, ${s.y})`}`;case"click":{await fn.setPosition(new so(s.x,s.y));let o=t.button==="right"?no.RIGHT:t.button==="middle"?no.MIDDLE:no.LEFT;return t.clickType==="double"?await fn.doubleClick(o):await fn.click(o),`SUCCESS: ${t.clickType||"Single"} clicked ${t.button||"left"} button at ${typeof n=="string"?n:`(${s.x}, ${s.y})`}`}case"drag":{let o=await Gs(t.from||n),r=await Gs(t.to);return!o||!r?'ERROR: Drag requires valid "from" and "to" target coordinates/grid codes.':(await fn.setPosition(new so(o.x,o.y)),await fn.pressButton(no.LEFT),await fn.setPosition(new so(r.x,r.y)),await fn.releaseButton(no.LEFT),`SUCCESS: Dragged mouse from (${o.x}, ${o.y}) to (${r.x}, ${r.y})`)}case"scroll":{let o=s||await Gs({x:640,y:360});o&&(await fn.setPosition(new so(o.x,o.y)),await new Promise(h=>setTimeout(h,60)));let r=parseInt(t.amount,10);(isNaN(r)||r<=0)&&(r=5);let a=r>50?Math.min(20,Math.max(1,Math.round(r/100))):Math.min(20,r),i=t.direction==="up";for(let h=0;h<a;h++)i?await fn.scrollUp(120):await fn.scrollDown(120),await new Promise(f=>setTimeout(f,20));return`SUCCESS: Scrolled ${t.direction||"down"} (${a} notches${s?` at target (${s.x}, ${s.y})`:" at screen center"})`}default:return`ERROR: Unsupported mouse action "${e}"`}}catch(o){return`ERROR: Mouse action failed: ${o.message}`}}var aa={enter:P.Enter,return:P.Return,escape:P.Escape,esc:P.Escape,backspace:P.Backspace,tab:P.Tab,space:P.Space,up:P.Up,down:P.Down,left:P.Left,right:P.Right,ctrl:P.LeftControl,control:P.LeftControl,alt:P.LeftAlt,shift:P.LeftShift,cmd:P.LeftCmd,win:P.LeftWin,meta:P.LeftWin,super:P.LeftSuper,a:P.A,b:P.B,c:P.C,d:P.D,e:P.E,f:P.F,g:P.G,h:P.H,i:P.I,j:P.J,k:P.K,l:P.L,m:P.M,n:P.N,o:P.O,p:P.P,q:P.Q,r:P.R,s:P.S,t:P.T,u:P.U,v:P.V,w:P.W,x:P.X,y:P.Y,z:P.Z,0:P.Num0,1:P.Num1,2:P.Num2,3:P.Num3,4:P.Num4,5:P.Num5,6:P.Num6,7:P.Num7,8:P.Num8,9:P.Num9,f1:P.F1,f2:P.F2,f3:P.F3,f4:P.F4,f5:P.F5,f6:P.F6,f7:P.F7,f8:P.F8,f9:P.F9,f10:P.F10,f11:P.F11,f12:P.F12},la=e=>{if(!e)return;let n=String(e).toLowerCase().trim();if(aa[n]!==void 0)return aa[n];if(P[e]!==void 0)return P[e];if(P[n.toUpperCase()]!==void 0)return P[n.toUpperCase()]};async function Ln(e,n,t={}){try{switch(e.toLowerCase()){case"type":{if(typeof n!="string")return"ERROR: Type action requires a valid string input";await Fr(),await zl.setContent(n);let o=process.platform==="darwin"?P.LeftSuper:P.LeftControl;return await Ft.pressKey(o,P.V),await Ft.releaseKey(o,P.V),await Fr(),t.autoPressEnter?(await new Promise(r=>setTimeout(r,50)),await Ft.type(P.Enter),`SUCCESS: Typed text input ("${n.length>20?n.substring(0,20)+"...":n}") and pressed Enter`):`SUCCESS: Typed text input ("${n.length>20?n.substring(0,20)+"...":n}")`}case"key_press":{let s=la(n);return s===void 0?`ERROR: Unknown key name "${n}"`:(await Ft.type(s),`SUCCESS: Pressed key ${n}`)}case"key_combination":{if(!Array.isArray(n))return'ERROR: key_combination requires an array of keys (e.g. ["ctrl", "c"])';let s=n.map(o=>la(o)).filter(o=>o!==void 0);return s.length===0?"ERROR: Invalid key combination":(await Ft.pressKey(...s),await Ft.releaseKey(...s),`SUCCESS: Executed key combination [${n.join(" + ")}]`)}case"clear_input":return await Ft.pressKey(P.LeftControl,P.A),await Ft.releaseKey(P.LeftControl,P.A),await Ft.type(P.Backspace),"SUCCESS: Cleared active text input (Select All + Backspace)";case"browser_back":{let s=process.platform==="darwin";return s?(await Ft.pressKey(P.LeftSuper,P.Left),await Ft.releaseKey(P.LeftSuper,P.Left)):(await Ft.pressKey(P.LeftAlt,P.Left),await Ft.releaseKey(P.LeftAlt,P.Left)),await Fr(),`SUCCESS: Browser back navigation (${s?"Cmd+Left":"Alt+Left"})`}default:return`ERROR: Unsupported keyboard action "${e}"`}}catch(s){return`ERROR: Keyboard action failed: ${s.message}`}}var oo=async(e,n={})=>{let t=L(e),s=t.action||t.type||t.cmd,o=t.target||t.grid||t.gridCode||t.location||t.input;if(!s)return'ERROR: Missing required "action" argument for computer_action (e.g. move, click, drag, scroll, type, key_press, key_combination).';let r=s.toLowerCase();if(r.startsWith("mouse_")||["move","click","drag","scroll"].includes(r)){let a=r.replace("mouse_","");return await On(a,o,{button:t.button,clickType:t.clickType||t.type,from:t.from,to:t.to,direction:t.direction,amount:t.amount?parseInt(t.amount,10):void 0})}if(r.startsWith("key_")||r==="type"||r==="press"){let a=r;r==="press"&&(a="key_press");let i=t.autoPressEnter===!0||t.autoPressEnter==="true"||t.enter===!0||t.enter==="true";return await Ln(a,o||t.text||t.keys,{...t,autoPressEnter:i})}return`ERROR: Unrecognized action "${s}". Supported actions: move, click, drag, scroll, type, key_press, key_combination.`};import ua from"screenshot-desktop";import io from"sharp";import ca from"fs-extra";import fa from"path";import"@nut-tree-fork/nut-js";async function Nr(e,n,t){if(!(!process.env.SHOW_DEBUG_GRID&&!process.env.DEBUG_OCR))try{let s=fa.resolve(process.cwd(),"screenshots",e);await ca.ensureDir(s),await ca.writeFile(fa.join(s,n),t)}catch{}}function Kl(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Yl(e,n,t=1/0){if(e===n)return 0;if(e.length===0)return n.length;if(n.length===0)return e.length;if(Math.abs(e.length-n.length)>t)return t+1;let s=Array.from({length:n.length+1},(o,r)=>r);for(let o=1;o<=e.length;o++){let r=[o],a=o;for(let i=1;i<=n.length;i++){let h=e[o-1]===n[i-1]?0:1,f=Math.min(r[i-1]+1,s[i]+1,s[i-1]+h);r.push(f),f<a&&(a=f)}if(s=r,a>t)return t+1}return s[n.length]}function Vl(e){return e<=4?0:e<=8?1:2}async function Br(e,n=3){let t=await io(e).metadata();return io(e).resize(Math.round(t.width*n),Math.round(t.height*n),{kernel:"lanczos3"}).greyscale().normalise().toBuffer()}function Xl(e){if(!e)return{words:[],lines:[]};let n=[],t=new Map;for(let o of e.split(`
500
+ `)){let r=o.split(" ");if(r.length<12||parseInt(r[0])!==5)continue;let i=r[2],h=r[3],f=r[4],c=parseInt(r[6]),l=parseInt(r[7]),u=parseInt(r[8]),d=parseInt(r[9]),p=parseFloat(r[10]),g=r.slice(11).join(" ").trim();if(!g||p<0)continue;let y={x0:c,y0:l,x1:c+u,y1:l+d},m={text:g,confidence:p,bbox:y};n.push(m);let w=`${i}_${h}_${f}`;t.has(w)||t.set(w,{words:[],bbox:{x0:1/0,y0:1/0,x1:-1/0,y1:-1/0}});let x=t.get(w);x.words.push(m),x.bbox.x0=Math.min(x.bbox.x0,y.x0),x.bbox.y0=Math.min(x.bbox.y0,y.y0),x.bbox.x1=Math.max(x.bbox.x1,y.x1),x.bbox.y1=Math.max(x.bbox.y1,y.y1)}let s=[];for(let o of t.values())o.words.length>0&&s.push({text:o.words.map(r=>r.text).join(" "),bbox:o.bbox,words:o.words});return{words:n,lines:s}}function Jl(e){if(!(e.words&&e.words.length>0)){if(e.blocks&&e.blocks.length>0){e.words=[],e.lines=[];for(let n of e.blocks)for(let t of n.paragraphs||[])for(let s of t.lines||[]){s.bbox&&e.lines.push(s);for(let o of s.words||[])o.bbox&&e.words.push(o)}if(e.words.length>0)return}if(e.tsv){let n=Xl(e.tsv);e.words=n.words,e.lines=n.lines}}}function Ur(e,n,t=0,s=0,o=1){Jl(e);let r=i=>({x0:Math.round(i.x0/o)+t,y0:Math.round(i.y0/o)+s,x1:Math.round(i.x1/o)+t,y1:Math.round(i.y1/o)+s}),a=[];if(e.lines&&e.lines.length>0)for(let i of e.lines){let h=i.text?i.text.toLowerCase().trim():"";if(!h||!i.bbox||!(h===n||new RegExp(`\\b${Kl(n)}\\b`,"i").test(h)))continue;let c=i.words||(e.words?e.words.filter(p=>p.bbox&&p.bbox.x0>=i.bbox.x0-5&&p.bbox.x1<=i.bbox.x1+5&&p.bbox.y0>=i.bbox.y0-5&&p.bbox.y1<=i.bbox.y1+5):[]),l=n.split(/\s+/),u=l.map(p=>p.replace(/[^a-z0-9]/g,"")).join(" "),d=!1;if(c.length>0)for(let p=0;p<=c.length-l.length;p++){let g=c.slice(p,p+l.length),y=g.map(m=>(m.text||"").toLowerCase().trim().replace(/[^a-z0-9]/g,"")).join(" ");if(y===u||y.includes(u)){let m={x0:Math.min(...g.map(w=>w.bbox.x0)),y0:Math.min(...g.map(w=>w.bbox.y0)),x1:Math.max(...g.map(w=>w.bbox.x1)),y1:Math.max(...g.map(w=>w.bbox.y1))};a.push(r(m)),d=!0}}d||a.push(r(i.bbox))}if(a.length===0&&e.words&&e.words.length>0)for(let i of e.words){let h=i.text?i.text.toLowerCase().trim().replace(/[^a-z0-9]/g,""):"",f=n.replace(/[^a-z0-9]/g,"");h===f&&i.bbox&&a.push(r(i.bbox))}if(a.length===0&&e.words&&e.words.length>0){let i=Vl(n.length);for(let h of e.words){let f=h.text?h.text.toLowerCase().trim():"";f.length>=3&&Math.abs(f.length-n.length)<=i&&Yl(f,n,i)<=i&&h.bbox&&a.push(r(h.bbox))}}return a}function Wr(e,n){let t=null,s=1/0;for(let o of e){let r=Math.round((o.x0+o.x1)/2),a=Math.round((o.y0+o.y1)/2),i=n.x>=o.x0&&n.x<=o.x1&&n.y>=o.y0&&n.y<=o.y1,h=Math.hypot(r-n.x,a-n.y),f=i?0:h;f<s&&(s=f,t={x:r,y:a,dist:h,containsPoint:i,bbox:o})}return t}function Ql(e,n,t,s){let a=Math.ceil(e/4),i=Math.ceil(n/2),h=[];for(let f=0;f<2;f++)for(let c=0;c<4;c++){let l=c*a,u=f*i,d=Math.min(a,e-l),p=Math.min(i,n-u),g=l+d/2,y=u+p/2,m=t>=l&&t<l+d&&s>=u&&s<u+p;h.push({x0:l,y0:u,w:d,h:p,cx:g,cy:y,containsTarget:m})}return h.sort((f,c)=>{if(f.containsTarget)return-1;if(c.containsTarget)return 1;let l=Math.hypot(f.cx-t,f.cy-s),u=Math.hypot(c.cx-t,c.cy-s);return l-u})}var Co=null;async function Zl(){return Co||(Co=(async()=>{let{createWorker:e}=await import("tesseract.js"),n=await import("fs-extra"),{CU_CACHE_DIR:t}=await import("./paths-R3DD7CRF.js");return n.ensureDirSync(t),e("eng",1,{cachePath:t,logger:()=>{}})})().catch(e=>{throw Co=null,e})),Co}var ro=null,da=null;async function ec(){let{getActiveDisplay:e}=await import("./screen_grid-PVIPPVR7.js"),n=await e();if(ro&&da===n)return ro;da=n,ro={format:"png"};try{let t=await ua.listDisplays();t&&t.length>0&&(ro={format:"png",screen:(t[n]||t[0]).id})}catch{}return ro}var jr=async(e,n={})=>{let t=!!(process.env.SHOW_DEBUG_GRID||process.env.DEBUG_OCR||process.env.VERBOSE),s=performance.now(),o=s,r=d=>{if(!t)return;let p=performance.now(),g=(p-o).toFixed(0),y=(p-s).toFixed(0);console.log(`[Click Perf] +${g}ms (${y}ms total) -> ${d}`),o=p};r("Starting click()");let a=L(e),i=a.gridId||a.grid||a.coordinate||a.target||a.id,h=(a.type||a.clickType||"single").toLowerCase(),f=(a.button||"left").toLowerCase(),c=a.intendedClickText||a.text||"";if(!i&&!c)return'ERROR: Missing required "gridId" parameter for Click tool.';let l=i;if(c)try{r("Parsing grid code");let d=i?ki(i):null;r("Getting display options");let p=await ec();r("Taking desktop screenshot");let g=await ua(p);r("Getting image metadata");let y=await io(g).metadata(),m=y.width||1920,w=y.height||1080,x=d?{x:Math.round(d.x*(m/1280)),y:Math.round(d.y*(w/720))}:{x:m/2,y:w/2},k=c.toLowerCase().trim();r("Acquiring OCR worker");let $=await Zl(),_=null,S="",T=d?220:500;if(d){r("Pass 1: Cropping target crop (3x zoom window, 2x upscale)");let R=Math.min(Math.round(m/3),m),E=Math.min(Math.round(w/3),w),b=Math.max(0,Math.min(m-R,x.x-Math.floor(R/2))),C=Math.max(0,Math.min(w-E,x.y-Math.floor(E/2))),A=await io(g).extract({left:b,top:C,width:R,height:E}).toBuffer(),O=2,D=await Br(A,O),W=k.replace(/[^a-z0-9]/g,"_");await Nr("cropped",`crop_${Date.now()}_${W}.png`,D),r("Pass 1: Running Tesseract OCR recognize on crop (PSM 11 - Sparse Text)"),await $.setParameters({tessedit_pageseg_mode:"11"});let{data:q}=await $.recognize(D,{},{tsv:!0,blocks:!0});if(r("Pass 1: OCR recognition finished, extracting matches"),q&&q.text){t&&console.log(`[Pass 1 OCR Read]: "${q.text.trim().replace(/\s+/g," ")}"`);let se=Ur(q,k,b,C,O);if(se.length>0){let V=Wr(se,x);V&&(V.containsPoint||V.dist<=T)&&(_=V,S="centered target crop OCR")}}}if(!_){r("Pass 2: Entering Full-Screen OCR (broad scan, PSM 3 - Auto)");let R=await Br(g,2),E=k.replace(/[^a-z0-9]/g,"_");await Nr("fullscreen",`full_${Date.now()}_${E}.png`,R),r("Pass 2: Running Tesseract on full screen"),await $.setParameters({tessedit_pageseg_mode:"3"});let{data:b}=await $.recognize(R,{},{tsv:!0,blocks:!0});if(r("Pass 2: Full-screen OCR finished"),b&&b.text){let C=Ur(b,k,0,0,2);if(C.length>0){let A=Wr(C,x);A&&(_=A,S="full-screen OCR")}}}if(!_){r("Pass 3: Entering Tiled OCR fallback (high-res 3x)");let R=Ql(m,w,x.x,x.y),E=k.replace(/[^a-z0-9]/g,"_");await $.setParameters({tessedit_pageseg_mode:"11"});for(let b=0;b<R.length;b++){let C=R[b];r(`Pass 3: Preprocessing tile ${b+1}/${R.length}`);let A=await io(g).extract({left:C.x0,top:C.y0,width:C.w,height:C.h}).toBuffer(),O=await Br(A,3);await Nr("tiles",`tile_${b+1}_${Date.now()}_${E}.png`,O),r(`Pass 3: Running Tesseract on tile ${b+1}`);let{data:D}=await $.recognize(O,{},{tsv:!0,blocks:!0});if(!D||!D.text)continue;let W=Ur(D,k,C.x0,C.y0,3);if(W.length>0){let q=Wr(W,x);if(q){_=q,S=`tile ${b+1} OCR (${C.containsTarget?"target tile":`offset ${C.x0},${C.y0}`})`;break}}}}if(_){let R={x:Math.round(_.x*(1280/m)),y:Math.round(_.y*(720/w))};r(`Executing mouse click on matched target (${S})`);let E=await On("click",R,{button:f,clickType:h});return r("Click completed successfully"),`${E} (${S} for "${c}" at ${Math.round(_.dist)}px distance)`}else t&&console.log(`[OCR] No match found for "${c}". Falling back to gridId.`)}catch(d){t&&console.error("[OCR Error]",d)}r(`Executing mouse click on fallback gridId: ${l}`);let u=await On("click",l,{button:f,clickType:h});return r("Fallback click completed"),u};var Hr=async(e,n={})=>{let t=L(e),s=t.fromGridId||t.from||t.start,o=t.toGridId||t.to||t.end;return!s||!o?'ERROR: Drag requires both "fromGridId" and "toGridId" parameters.':await On("drag",s,{from:s,to:o})};var Gr=async(e,n={})=>{let t=L(e),s=(t.direction||"down").toLowerCase(),o=t.amount?parseInt(t.amount,10):6,r=t.gridId||t.grid||t.coordinate||t.target||t.id||null;return await On("scroll",r,{direction:s,amount:o})};var Mo=async(e,n={})=>{let t=L(e),s=t.text||t.input||t.value||"",o=t.autoPressEnter===!0||t.autoPressEnter==="true"||t.enter===!0||t.enter==="true";return s==null?'ERROR: Missing required "text" parameter for KeyboardTyping tool.':await Ln("type",String(s),{autoPressEnter:o})};var Ao=async(e,n={})=>{let t=L(e),s=t.key||t.keys||t.input||t.shortcut;if(!s)return'ERROR: Missing required "key" parameter for KeyPress tool.';let o=String(s).trim().toLowerCase();if(o==="clearinput"||o==="clear_input"||o==="clear")return await Ln("clear_input");if(o==="back"||o==="browser_back"||o==="browserBack")return await Ln("browser_back");if(o.includes(";")||o.includes("+")){let r=o.split(/[;+]/).map(a=>a.trim()).filter(Boolean);return await Ln("key_combination",r)}return await Ln("key_press",o)};var vo=async(e,n={})=>"SUCCESS: Screen recapture requested. The latest gridded screenshot is provided for your next decision.";var tc={web_search:dr,web_scrape:ur,memory:pr,chat:hr,view_file:Vs,write_file:mr,update_file:br,exec_command:ir,read_folder:kr,write_pdf:Tr,write_docx:Er,search_keyword:Js,generate_image:Mr,saveSummary:Qs,addMemScore:Is,file_map:Ir,todo:Zs,Todo:Zs,goal:Zs,Goal:Zs,invokeSync:Or,invoke:oa,getProgress:Lr,cancel:ra,awaitSubagent:Os,answerSubagent:Ls,steerSubagent:to,computer_action:oo,computer_use:oo,ComputerAction:oo,ComputerUse:oo,click:jr,Click:jr,drag:Hr,Drag:Hr,scroll:Gr,Scroll:Gr,keyboard_typing:Mo,KeyboardTyping:Mo,keyboardtyping:Mo,key_press:Ao,KeyPress:Ao,keypress:Ao,recapture_screen:vo,RecaptureScreen:vo,recapturescreen:vo,invoke_sync:Or,get_progress:Lr,await_subagent:Os,answer_subagent:Ls,steer_subagent:to,steer:to,Steer:to,ask:$o,Ask:$o,AskUser:$o,WebSearch:dr,WebScrape:ur,ReadFile:Vs,ReadFolder:kr,WriteFile:mr,PatchFile:br,WritePDF:Tr,WriteDoc:Er,Run:ir,SearchKeyword:Js,CodeSearch:Js,code_search:Js,Memory:pr,Chat:hr,GenerateImage:Mr,saveSumary:Qs,SaveSummary:Qs,SaveSumary:Qs,add_mem_score:Is,AddMemScore:Is,addMemoryScore:Is,AddMemoryScore:Is,FileMap:Ir,answer:Ls,Answer:Ls,AnswerSubagent:Ls,await:Os,Await:Os,AwaitSubagent:Os,EmergencyRollback:Dr,emergency_rollback:Dr},ao=async(e,n,t={})=>{let s=t.mode?t.mode.toLowerCase():"flux",o=e.toLowerCase(),a=["memory","chat","savesummary","addmemscore","add_mem_score","ask","web_search","web_scrape","await"].some(c=>o.includes(c))||o==="ask",h=["click","drag","scroll","keyboardtyping","keyboard_typing","keypress","key_press","recapturescreen","recapture_screen","computer"].some(c=>o.includes(c));if(!a){if(s==="flow"){if(!(o.includes("write_pdf")||o.includes("write_docx")||o.includes("generate_image")))return`ERROR: Tool [${e}] is a Workspace Tool and NOT available in Flow mode. Tell user to switch (\`/mode flux\`) to use this tool.`}else if(s==="icu"){if(!h)return`ERROR: Tool [${e}] is not available in Computer Use mode. ICU mode only supports Computer Use tools (Click, Drag, Scroll, KeyboardTyping, KeyPress, RecaptureScreen).`}else if(o.includes("write_pdf")||o.includes("write_docx")||o.includes("generate_image"))return`ERROR: Tool [${e}] is not available in ${t.mode||"Flux"} mode. Tell user to switch (\`/mode flow\`) for document generation.`}let f=tc[e];if(!f)return`ERROR: Tool [${e}] not found in registry.`;try{return await f(n,t)}catch(c){let l=c instanceof Error?c.message:String(c);return`ERROR: Execution failed for [${e}]: ${l}`}};import Q from"path";import Pe from"fs";import nc from"gradient-string";var qr=["I have a regex for your problems.","Your terminal, my kingdom.","Blowing on the cartridge helps. Probably.","Don't panic. I have the towel.","Logic is the start of wisdom.","Try to exit Vim? Good luck.","I speak fluent Terminal.","The cake is a lie. This code is not.","I have no bugs, just surprise features.","Rewriting in Rust... just for fun.","Coffee in, clean commits out.","The magic smoke stays inside today.","A semicolon short of a miracle.","One does not simply code without a bug.","Keep it simple. Keep it terminal.","Regex: now you have two problems.","I dream in binary.","Root access or bust.","Wait for the dial-up tone. Just kidding.","I take the 'labor' out of collab.","My other process is a TARDIS.","Calculated response: 42.","Ponder the orb. Ponder the code.","Less talk, more flow.","Elegance in every byte.","Build something the world is not ready for.","Your wishes, my tool calls.","I act in Flux. I think in Flow.","Syntax error in the universe. Please fix.","Your project, my obsession.","I am not a bot, I am an architect.","Digital spirits consulted. They say: Ship it.","Reticulate splines. Engage humor.","Code like poetry. Run like water.","Minimalism is the ultimate flex.","The truth is in the logs.","Follow the white rabbit.","There is no spoon. Only code.","Binary is the only language I trust.","I have a good feeling about this.","Pew pew! Lasers charged.","Divide by zero? Not today.","Search for the correct USB orientation...","I've got a fever, and the only cure is more code.","The code gremlins are on our side.","My favorite command? Yours.","Stay hungry. Stay active.","Momentum is your best friend.","Lead the flow. Don't chase it.","A fresh batch of bytes. Hot and ready.","I orchestrate the ones and zeros.","Smart enough to help. Humble enough to ask.","Think twice. Code once.","Pure intent. Pure execution.","Small steps. Massive impact.","Your terminal is a canvas.","Efficiency is my second name.","I have seen things you people wouldn't believe.","Let the thoughts marinate.","The best feature? The one you don't need.","Precision is the only perfection.","Stay focused. Stay terminal.","Silence is the best debugger.","Erase the debt. Commit the code.","Velocity meets stability.","Ship it. Improve it. Repeat.","Build tomorrow, right now.","Turn logic into reality.","The best way to predict the future is to build it.","Break barriers, not builds.","Fuel the next breakthrough.","Momentum is key.","Terminal vibes only.","Your digital co-pilot is ready.","Partner in code. Partner in crime.","I speak in semicolons.","Ready for the next great idea.","Just a moment. In the zone.","Polishing the algorithms. Hold tight.","Craft a masterpiece today.","Debug the universe. Start here.","Warp speed engaged. Almost.","The cake is not a lie. It's just loading.","Finish the Kessel Run in 12 parsecs.","Do a barrel roll!","Waiting for the respawn.","Press Start to continue.","Herding digital cats... done.","The hamsters are fast today.","Tasting the snozberries.","I go for speed. I go for flow.","Real life or just fantasy?","Poking the bear... gently.","Ensure the magic smoke stays inside.","Try turning it off and on again.","Construct additional pylons.","New line? Ctrl+J is your friend.","Release the HypnoDrones.","Push the button, Frank.","My other loading screen is even funnier.","Pretty sure a cat walked on my keyboard.","Recalibrate the humor-o-meter.","Summon the code gremlins.","I've seen your browser history. Just kidding.","Charge the laser... pew pew!","Dividing by zero... just for a sec.","Looking for an adult supervisor. Found none.","Make it go beep boop.","Buffering... for effect.","Entangle quantum particles... complete.","Polishing the chrome on my algorithms.","Are you not entertained?","Just waiting for the dial-up tone.","Reboot the humor module.","Defragment memories. Check.","Optimizing for ludicrous speed.","Swapping bits. Don't tell the bytes.","Garbage collected. I am back.","Assembling the interwebs.","Converting coffee to logic.","Update syntax for reality.","Rewire the synapses.","Greasin' the cogs.","Engage the improbability drive.","Channel the Force.","Align the stars. Respond now.","The cake is a lie. The prompt is real.","I'm Feeling Lucky.","Shipping awesomeness.","Navigating the slime mold.","Consult digital spirits.","Ask the magic conch shell.","One moment. Optimizing humor.","Shuffling punchlines.","Compiling brilliance.","Summon the cloud of wisdom.","Prepare to dazzle.","Hold tight. Crafting a response.","Tuning the algorithms.","Following the white rabbit... again.","The truth is in here. Somewhere.","Herding cats is my day job.","Distracting you with this phrase.","Almost there. Probably.","Rickrolling my creator. Don't tell.","Slapping the bass.","Is this real life?","Ponder the orb. Type the prompt.","Thoughtful gaze initiated.","Computer's favorite snack? Microchips.","Why Java? Because I don't C#.","Charging the laser... wait for it.","Dividing by zero... just kidding!","Adult supervision not found. Proceed.","Beep boop. I'm a real boy.","Wait for the respawn.","Finish the run. Ship the code.","Fiddling with character creation.","Just a moment. Finding a meme.","Pressing A to continue.","Loading wit.exe.","Pre-heating the servers.","Calibrate flux capacitor.","Channeling the Force.","Aligning the stars.","The truth is in the code.","Don't panic.","Blowing on the cartridge.","Doing a barrel roll!","Respawning in 3... 2... 1...","The cake is a lie.","Fiddling with character settings.","Finding a suitable pun.","Distracting with wit.","Almost ready.","Hamsters on speed today.","Patting Cloudy on the head.","Rickrolling the logs.","Slapping the code.","Got a good feeling about this.","Poking the prompt.","Researching latest memes.","Making it more witty.","Thinking... hmmm.","Fish with no eyes? Fsh.","Broken pencil? Pointless.","Percussive maintenance applied.","USB orientation: 3rd try's the charm.","Rust rewrite in 3... 2...","Exiting Vim... someday.","Spinning the hamster wheel.","Not a bug. Unplanned feature.","Engage.","I'll be back.","Machine spirit consulted.","Letting the thoughts marinate.","Orb pondered.","Thoughtful gaze engaged.","Charging the laser...","Making it go beep.","Buffering...","Quantum particles entangled.","Polishing the chrome.","Entertained yet?","Gremlins summoned.","Dial-up tone finished.","Humor meter recalibrated.","Cat on keyboard. Sending help.","Enhancing...","Turn it off and on again.","Constructing pylons.","HypnoDrones released.","Pushing the button."];var pa=[{name:"Cyan Cyberpunk",text:"cyan",textMuted:"#4da6b8",textDim:"#2d6d7a",textInverted:"black",border:"cyan",borderMuted:"#1a5966",borderDim:"#0f3840",bg:void 0,cardBg:"#061e24",highlightBg:"#092b33",activeBg:"#0e3e4a",inputBg:"#092b33",inputBorder:"#092b33",inputText:"cyan",inputPlaceholder:"#2d6d7a",inputPrompt:"cyan",codeBg:"#020d10",codeBorder:"#1a5966",userMsgBg:"#092b33",userMsgBorder:"#092b33",userMsgText:"cyan",diffRemovalBg:"#3a0c1a",diffAdditionBg:"#0c3a32",diffRemovalText:"#ff4d88",diffAdditionText:"#00ffaa",diffRemovalHighlightColor:"#ff1a66",diffRemovalHighlightBg:"#590022",diffAdditionHighlightColor:"#00ffcc",diffAdditionHighlightBg:"#00593b",diffRemovalNum:"#ff4d88",diffAdditionNum:"#00ffaa",diffRemovalPrefix:"#ff1a66",diffAdditionPrefix:"#00ffcc",primary:"cyan",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"cyan",statusOff:"#2d6d7a",logoTextAnsi:"\x1B[1;36m",logoBodyAnsi:"\x1B[36m",logoMutedAnsi:"\x1B[90m",logoGradient:["#00ffff","#0088ff"]},{name:"Magenta Vaporwave",text:"magenta",textMuted:"#c451d6",textDim:"#7d2b8a",textInverted:"black",border:"magenta",borderMuted:"#5e1b69",borderDim:"#3b0f42",bg:void 0,cardBg:"#240729",highlightBg:"#310938",activeBg:"#470e52",inputBg:"#310938",inputBorder:"#310938",inputText:"magenta",inputPlaceholder:"#7d2b8a",inputPrompt:"magenta",codeBg:"#100312",codeBorder:"#5e1b69",userMsgBg:"#310938",userMsgBorder:"#310938",userMsgText:"magenta",diffRemovalBg:"#3a0c20",diffAdditionBg:"#200c3a",diffRemovalText:"#ff4d94",diffAdditionText:"#aa4dff",diffRemovalHighlightColor:"#ff1a75",diffRemovalHighlightBg:"#59002b",diffAdditionHighlightColor:"#bb66ff",diffAdditionHighlightBg:"#3b0059",diffRemovalNum:"#ff4d94",diffAdditionNum:"#aa4dff",diffRemovalPrefix:"#ff1a75",diffAdditionPrefix:"#bb66ff",primary:"magenta",secondary:"cyan",accent:"purple",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"magenta",statusOff:"#7d2b8a",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ff00ff","#8800ff"]},{name:"Glitch Matrix",text:"#00ff41",textMuted:"#00b32d",textDim:"#00661a",textInverted:"black",border:"#00ff41",borderMuted:"#008020",borderDim:"#004d13",bg:void 0,cardBg:"#0d1f0d",highlightBg:"#122912",activeBg:"#1c3e1c",inputBg:"#122912",inputBorder:"#122912",inputText:"#00ff41",inputPlaceholder:"#00b32d",inputPrompt:"#ffff00",codeBg:"#040a04",codeBorder:"#008020",userMsgBg:"#122912",userMsgBorder:"#122912",userMsgText:"#00ff41",diffRemovalBg:"#3a001a",diffAdditionBg:"#003a10",diffRemovalText:"#ff0055",diffAdditionText:"#00ff66",diffRemovalHighlightColor:"#ff0033",diffRemovalHighlightBg:"#59001b",diffAdditionHighlightColor:"#33ff88",diffAdditionHighlightBg:"#005918",diffRemovalNum:"#ff0055",diffAdditionNum:"#00ff66",diffRemovalPrefix:"#ff0033",diffAdditionPrefix:"#33ff88",primary:"#00ff41",secondary:"yellow",accent:"cyan",success:"#00ff41",warning:"yellow",danger:"red",info:"cyan",statusOn:"#00ff41",statusOff:"#00661a",logoTextAnsi:"\x1B[1;32m",logoBodyAnsi:"\x1B[32m",logoMutedAnsi:"\x1B[90m",logoGradient:["#00ff41","#ffff00"]},{name:"Warm Sunset",text:"#ffaa55",textMuted:"#cc8844",textDim:"#885522",textInverted:"black",border:"#ff9933",borderMuted:"#aa6622",borderDim:"#663311",bg:void 0,cardBg:"#24180f",highlightBg:"#2e1e12",activeBg:"#422c1b",inputBg:"#2e1e12",inputBorder:"#2e1e12",inputText:"#ffaa55",inputPlaceholder:"#885522",inputPrompt:"#ff7733",codeBg:"#120c08",codeBorder:"#aa6622",userMsgBg:"#2e1e12",userMsgBorder:"#2e1e12",userMsgText:"#ffaa55",diffRemovalBg:"#3d120c",diffAdditionBg:"#3a2e0c",diffRemovalText:"#ff5544",diffAdditionText:"#ffcc33",diffRemovalHighlightColor:"#ff3322",diffRemovalHighlightBg:"#591108",diffAdditionHighlightColor:"#ffee44",diffAdditionHighlightBg:"#594400",diffRemovalNum:"#ff5544",diffAdditionNum:"#ffcc33",diffRemovalPrefix:"#ff3322",diffAdditionPrefix:"#ffee44",primary:"#ffaa55",secondary:"#ff7733",accent:"magenta",success:"#ffcc33",warning:"#ff7733",danger:"#ff3322",info:"#ffaa55",statusOn:"#ffaa55",statusOff:"#885522",logoTextAnsi:"\x1B[1;33m",logoBodyAnsi:"\x1B[33m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ff9933","#ff0055"]},{name:"Sakura Blossom",text:"#ffc0e0",textMuted:"#d98cb3",textDim:"#804d66",textInverted:"black",border:"#ff99cc",borderMuted:"#aa4d7a",borderDim:"#662647",bg:void 0,cardBg:"#291320",highlightBg:"#331826",activeBg:"#472235",inputBg:"#331826",inputBorder:"#331826",inputText:"#ffc0e0",inputPlaceholder:"#804d66",inputPrompt:"#ff99cc",codeBg:"#140a10",codeBorder:"#aa4d7a",userMsgBg:"#331826",userMsgBorder:"#331826",userMsgText:"#ffc0e0",diffRemovalBg:"#3e0c1b",diffAdditionBg:"#1b3e2b",diffRemovalText:"#ff6699",diffAdditionText:"#66ffb3",diffRemovalHighlightColor:"#ff3377",diffRemovalHighlightBg:"#590022",diffAdditionHighlightColor:"#33ff99",diffAdditionHighlightBg:"#00592e",diffRemovalNum:"#ff6699",diffAdditionNum:"#66ffb3",diffRemovalPrefix:"#ff3377",diffAdditionPrefix:"#33ff99",primary:"#ffc0e0",secondary:"#ff99cc",accent:"magenta",success:"#66ffb3",warning:"yellow",danger:"#ff3377",info:"#ff99cc",statusOn:"#ffc0e0",statusOff:"#804d66",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ffb3d9","#ff3399"]},{name:"Radioactive Slime",text:"#ccff00",textMuted:"#99cc00",textDim:"#669900",textInverted:"#0a0f00",border:"#ccff00",borderMuted:"#99cc00",borderDim:"#669900",bg:void 0,cardBg:"#0f1400",highlightBg:"#1a2400",activeBg:"#2a3b00",inputBg:"#1a2400",inputBorder:"#1a2400",inputText:"#ccff00",inputPlaceholder:"#669900",inputPrompt:"#cc00ff",codeBg:"#050a00",codeBorder:"#99cc00",userMsgBg:"#1a2400",userMsgBorder:"#1a2400",userMsgText:"#ccff00",diffRemovalBg:"#2a0033",diffAdditionBg:"#0f3300",diffRemovalText:"#ff00cc",diffAdditionText:"#00ff33",diffRemovalHighlightColor:"#ff33cc",diffRemovalHighlightBg:"#4d0066",diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:"#1a6600",diffRemovalNum:"#ff00cc",diffAdditionNum:"#00ff33",diffRemovalPrefix:"#ff33cc",diffAdditionPrefix:"#33ff66",primary:"#ccff00",secondary:"#cc00ff",accent:"#ff00cc",success:"#00ff33",warning:"#ffcc00",danger:"#ff0033",info:"#00ccff",statusOn:"#ccff00",statusOff:"#669900",logoTextAnsi:"\x1B[1;38;5;190m",logoBodyAnsi:"\x1B[38;5;190m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ccff00","#cc00ff"]},{name:"Cosmic Void",text:"#f0f8ff",textMuted:"#a6aeb5",textDim:"#5e656e",textInverted:"#010103",border:"#f0f8ff",borderMuted:"#a6aeb5",borderDim:"#5e656e",bg:void 0,cardBg:"#05030d",highlightBg:"#0b081a",activeBg:"#171133",inputBg:"#0b081a",inputBorder:"#0b081a",inputText:"#f0f8ff",inputPlaceholder:"#5e656e",inputPrompt:"#ff007f",codeBg:"#020108",codeBorder:"#a6aeb5",userMsgBg:"#0b081a",userMsgBorder:"#0b081a",userMsgText:"#f0f8ff",diffRemovalBg:"#2e0a29",diffAdditionBg:"#091c33",diffRemovalText:"#ff33a6",diffAdditionText:"#33d6ff",diffRemovalHighlightColor:"#ff66c2",diffRemovalHighlightBg:"#5c1452",diffAdditionHighlightColor:"#66e0ff",diffAdditionHighlightBg:"#123866",diffRemovalNum:"#ff33a6",diffAdditionNum:"#33d6ff",diffRemovalPrefix:"#ff66c2",diffAdditionPrefix:"#66e0ff",primary:"#f0f8ff",secondary:"#ff007f",accent:"#9d00ff",success:"#33d6ff",warning:"#ffcc00",danger:"#ff0040",info:"#9d00ff",statusOn:"#f0f8ff",statusOff:"#5e656e",logoTextAnsi:"\x1B[1;38;5;231m",logoBodyAnsi:"\x1B[38;5;231m",logoMutedAnsi:"\x1B[38;5;240m",logoGradient:["#ffffff","#9d00ff"]},{name:"Magma Eruption",text:"#ff4d00",textMuted:"#cc3d00",textDim:"#802600",textInverted:"#0d0300",border:"#ff4d00",borderMuted:"#cc3d00",borderDim:"#802600",bg:void 0,cardBg:"#1a0600",highlightBg:"#260a00",activeBg:"#401100",inputBg:"#260a00",inputBorder:"#260a00",inputText:"#ff4d00",inputPlaceholder:"#802600",inputPrompt:"#ffcc00",codeBg:"#080200",codeBorder:"#cc3d00",userMsgBg:"#260a00",userMsgBorder:"#260a00",userMsgText:"#ff4d00",diffRemovalBg:"#2e0a0a",diffAdditionBg:"#1f1400",diffRemovalText:"#ff3333",diffAdditionText:"#ffaa00",diffRemovalHighlightColor:"#ff6666",diffRemovalHighlightBg:"#5c1414",diffAdditionHighlightColor:"#ffcc33",diffAdditionHighlightBg:"#3d2900",diffRemovalNum:"#ff3333",diffAdditionNum:"#ffaa00",diffRemovalPrefix:"#ff6666",diffAdditionPrefix:"#ffcc33",primary:"#ff4d00",secondary:"#ffcc00",accent:"#ff0040",success:"#ffaa00",warning:"#ffff00",danger:"#ff0000",info:"#ff8800",statusOn:"#ff4d00",statusOff:"#802600",logoTextAnsi:"\x1B[1;38;5;202m",logoBodyAnsi:"\x1B[38;5;202m",logoMutedAnsi:"\x1B[38;5;236m",logoGradient:["#ff4d00","#ff0000"]}],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 Io=null;var ha=(e="Dark")=>{let n;e==="Mystery"||e==="Chaos"?(Io||(Io=pa[Math.floor(Math.random()*pa.length)]),n={...Io,id:"Mystery"}):(Io=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 sc=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",Eh=(e=2)=>{let n=sc();return n==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)},_h=(e="...",n="Loading...",t="Dark")=>{let s=qr[Math.floor(Math.random()*qr.length)],o=ha(t),r=o.logoTextAnsi,a=o.logoBodyAnsi,i=o.logoMutedAnsi,h="\x1B[0m",f=[" \u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2588\u2588\u2588\u2591 "," \u2588\u2588\u2588\u2591 "," \u2588\u2588\u2588\u2591 "," \u2591\u2591\u2591 "],c=o.logoGradient||["#0077ff","#ff00ff"],l=nc(c).multiline(f.join(`
501
+ `)).split(`
502
+ `),u=d=>`${i}${d}${h}`;return`${l[0]}
503
+ ${l[1]} ${r}Selected Provider: ${n}${h}
504
+ ${l[2]}
505
+ ${l[3]} ${r}FluxFlow ${u("v"+e)}${h}
506
+ ${l[4]}
507
+ ${l[5]} ${a}See /help for additional commands.${h}
508
+ ${l[6]} ${u(s)}
509
+ ${l[7]}`};import{WebSocket as Oo}from"ws";var Kt=null,Ps=!1,oc="ws://localhost:56832",zr=[],Ds=null,Kr=null,ma="2.0.0",Mh=e=>{ma=e,ga()},Yr=e=>{Kr=e},ga=()=>{if(Kt||Ps)return;Ps=!0;let e=new Oo(oc);e.on("open",()=>{for(Kt=e,Ps=!1,Kt.send(JSON.stringify({command:"version",version:ma,pid:process.pid,ppid:process.ppid}));zr.length>0;)Kt.send(JSON.stringify(zr.shift()))}),e.on("message",n=>{try{let t=JSON.parse(n.toString());t.command==="contextResponse"&&Ds?(Ds(t.data),Ds=null):t.command==="securityResponse"&&Kr&&Kr(t.result)}catch{}}),e.on("error",()=>{Ps=!1,Kt=null}),e.on("close",()=>{Ps=!1,Kt=null})},Lo=e=>{Kt&&Kt.readyState===Oo.OPEN?Kt.send(JSON.stringify(e)):(zr.push(e),Ps||ga())},Po=()=>Kt!==null&&Kt.readyState===Oo.OPEN,Ah=e=>{Lo({command:"status",status:e})},gs=()=>new Promise(e=>{if(!Kt||Kt.readyState!==Oo.OPEN){e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]});return}Ds=e,Kt.send(JSON.stringify({command:"requestContext"})),setTimeout(()=>{Ds===e&&(e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]}),Ds=null)},1e3)}),ya=e=>{Lo({command:"open",filePath:e})},Vr=(e,n,t)=>{Lo({command:"showDiff",filePath:e,originalContent:n,modifiedContent:t})},wa=(e,n)=>{Lo({command:"closeDiff",filePath:e,result:n})};import xa from"path";import rc from"fs";var ic=e=>{try{return rc.readdirSync(e,{withFileTypes:!0})}catch{return[]}},Xr=(e,n,t=1,s=ic,o=[],r=null)=>{let a=r||s(e),i=" ".repeat(t-1);if(a.length>100)return`${i}${xa.basename(e)}/ (>100 files)
510
+ `;let h="",f=o,c=a.filter(p=>!f.includes(p.name)&&!p.name.startsWith(".")),l=a.filter(p=>f.includes(p.name)||p.name.startsWith(".")).map(p=>p.name).sort();l.length>0&&(h+=`${i}[ignored: ${l.map(p=>p+"/").join(", ")}]
511
+ `);let u=c.filter(p=>p.isDirectory()).sort((p,g)=>p.name.localeCompare(g.name)),d=c.filter(p=>!p.isDirectory()).map(p=>p.name).sort();for(let p of u){let g=xa.join(e,p.name);if(t>n)h+=`${i}${p.name}/ (max depth)
512
+ `;else{let y=s(g);y.length>80?h+=`${i}${p.name}/ (>80 files)
513
+ `:(h+=`${i}${p.name}/
514
+ `,h+=Xr(g,n,t+1,s,o,y))}}return d.length>0&&(h+=`${i}${d.join("; ")}
515
+ `),h};import Jr from"path";import ac from"fs";var lc=e=>{try{return ac.readdirSync(e,{withFileTypes:!0})}catch{return[]}},Qr=(e,n,t="",s=1,o=lc,r=[])=>{let a=o(e),i=Jr.sep;if(a.length>100)return`${t}\u2514\u2500\u2500 ${Jr.basename(e)}${i} ...100+ files...
516
+ `;let h="",f=r,c=a.filter(d=>!f.includes(d.name)&&!d.name.startsWith(".")),l=a.filter(d=>f.includes(d.name)||d.name.startsWith(".")).map(d=>d.name).sort();c.sort((d,p)=>d.isDirectory()&&!p.isDirectory()?-1:!d.isDirectory()&&p.isDirectory()?1:d.name.localeCompare(p.name));let u=[...c.map(d=>({name:d.name,isDir:d.isDirectory()})),...l.map(d=>({name:d,isDir:!0,isCollapsed:!0}))];return u.forEach((d,p)=>{let g=p===u.length-1,y=Jr.join(e,d.name),m=g?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",w=t+(g?" ":"\u2502 ");if(d.isCollapsed){h+=`${t}${m}${d.name}${i}...
517
+ `;return}d.isDir?s>n?h+=`${t}${m}${d.name}${i} ...depth exceeded...
518
+ `:o(y).length>80?h+=`${t}${m}${d.name}${i} ...80+ files...
519
+ `:(h+=`${t}${m}${d.name}${i}
520
+ `,h+=Qr(y,n,w,s+1,o,r)):h+=`${t}${m}${d.name}
521
+ `}),h};import"@google/genai";var It=async(e,n,t=5,s=1e3)=>{let o=n?.signal;for(let a=0;a<t;a++){if(o?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{let i=await fetch(e,n);if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),i.ok||i.status!==429&&i.status<500)return i}catch(i){if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),i.name==="AbortError"||o?.aborted||a===t-1)throw i}o?await new Promise((i,h)=>{let f=setTimeout(()=>{o.removeEventListener("abort",c),i()},Math.min(24e3,s*Math.pow(2,a))),c=()=>{clearTimeout(f),h(new DOMException("The user aborted a request.","AbortError"))};o.addEventListener("abort",c)}):await new Promise(i=>setTimeout(i,Math.min(24e3,s*Math.pow(2,a))))}if(o?.aborted)throw new DOMException("The user aborted a request.","AbortError");let r=await fetch(e,n);return typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),r};async function Do(e){let n=new TextEncoder().encode(e),t=await crypto.subtle.digest("SHA-256",n);return[...new Uint8Array(t).slice(0,16)].map(s=>s.toString(16).padStart(2,"0")).join("")}var Pn=e=>typeof e!="string"?e:e.replace(/<\|channel>thought/gi,"<think>").replace(/<channel\|>/gi,"</think>");var Fo=async function*(e,n,t,s,o,r,a,i,h=1){let f=[];s&&f.push({role:"system",content:s});for(let x of t){let k=x.role==="user"?"user":"assistant",$=[];if(Array.isArray(x.parts)){for(let _ of x.parts)if(_.text)$.push({type:"text",text:_.text});else if(_.inlineData&&a){let S=_.inlineData.mimeType,T=_.inlineData.data;S.startsWith("image/")&&$.push({type:"image_url",image_url:{url:`data:${S};base64,${T}`}})}}else{let _=x.text||"";_&&$.push({type:"text",text:_})}f.push({role:k,content:$.length===1&&$[0].type==="text"?$[0].text:$})}let c={model:n,messages:f,stream:!0,stream_options:{include_usage:!0},temperature:h};if(o!=="Fast"){let x={Low:"high",Medium:"high",Standard:"high",High:"max",xHigh:"max"};c.reasoning_effort=x[o]||"high",c.extra_body={thinking:{type:"enabled"}}}else c.extra_body={thinking:{type:"disabled"}};let l=await It("https://api.deepseek.com/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(c),signal:i});if(!l.ok){let x=await l.json().catch(()=>({}));throw new Error(`DeepSeek Error (${l.status}): ${x.error?.message||l.statusText}`)}let u=l.body.getReader(),d=new TextDecoder,p="",g=[],y=null,m=Date.now(),w=!1;for(;;){let{done:x,value:k}=await u.read();if(x){w&&(g.length>0||y)&&(yield{candidates:g.length>0?[{content:{parts:g}}]:[],usageMetadata:y});break}p+=d.decode(k,{stream:!0});let $=p.split(`
522
+ `);p=$.pop();for(let _ of $){let S=_.trim();if(!S||!S.startsWith("data: "))continue;let T=!1;if(S==="data: [DONE]")T=!0;else try{let R=JSON.parse(S.substring(6)),E=R.choices?.[0]?.delta,b=R.usage;if(R.choices?.[0]?.finish_reason&&(T=!0),b&&(y={totalTokenCount:b.total_tokens||b.prompt_tokens+b.completion_tokens,promptTokenCount:b.prompt_tokens||0,candidatesTokenCount:b.completion_tokens||0,cachedContentTokenCount:b.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:b.completion_tokens_details?.reasoning_tokens||0},w=!0),E){let C=E.reasoning_content||null;C&&(g.push({text:C,thought:!0}),w=!0),E.content&&(g.push({text:E.content}),w=!0)}}catch{}if((T||Date.now()-m>=150)&&w&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],m=Date.now(),w=!1),T)break}Date.now()-m>=150&&w&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],m=Date.now(),w=!1)}};var No=async function*(e,n,t,s,o,r,a,i,h=1,f=null){let c=[];s&&c.push({role:"system",content:s});for(let T of t){let R=T.role==="user"?"user":"assistant",E=[];if(Array.isArray(T.parts)){for(let b of T.parts)if(b.text)E.push({type:"text",text:b.text});else if(b.inlineData&&a){let C=b.inlineData.mimeType,A=b.inlineData.data;C.startsWith("image/")&&E.push({type:"image_url",image_url:`data:${C};base64,${A}`})}}else{let b=T.text||"";b&&E.push({type:"text",text:b})}E.length>0&&c.push({role:R,content:E.length===1&&E[0].type==="text"?E[0].text:E})}let l={Fast:"none",Low:"none",Medium:"high",Standard:"high",High:"high",xHigh:"high"},u=`${e.slice(-5)}${f||""}${o}${n}`,d=await Do(u),p={model:n,messages:c,stream:!0,temperature:h,prompt_cache_key:d};o&&o!=="Fast"&&$s(n)&&(p.reasoning_effort=l[o]||"high");let g=await It("https://api.mistral.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(p),signal:i});if(!g.ok){let T=await g.text().catch(()=>""),R=g.statusText;try{let E=JSON.parse(T);R=E.error?.message||E.message||JSON.stringify(E.detail||E)}catch{T&&(R=T)}throw new Error(`Mistral Error (${g.status}): ${JSON.stringify(R)}`)}let y=g.body.getReader(),m=new TextDecoder,w="",x=[],k=null,$=Date.now(),_=!1,S=T=>T?typeof T=="string"?Pn(T):Array.isArray(T)?T.map(S).filter(Boolean).join(""):typeof T=="object"&&T!==null?typeof T.text=="string"?Pn(T.text):typeof T.content=="string"?Pn(T.content):typeof T.thinking=="string"?Pn(T.thinking):typeof T.reasoning_content=="string"?Pn(T.reasoning_content):typeof T.reasoning=="string"?Pn(T.reasoning):typeof T.value=="string"?Pn(T.value):T.text?S(T.text):T.content?S(T.content):T.thinking?S(T.thinking):T.reasoning_content?S(T.reasoning_content):T.reasoning?S(T.reasoning):T.value?S(T.value):"":Pn(String(T)):"";for(;;){let{done:T,value:R}=await y.read();if(T){_&&(x.length>0||k)&&(yield{candidates:x.length>0?[{content:{parts:x}}]:[],usageMetadata:k});break}w+=m.decode(R,{stream:!0});let E=w.split(`
523
+ `);w=E.pop();for(let b of E){let C=b.trim();if(!C||!C.startsWith("data: "))continue;let A=!1;if(C==="data: [DONE]")A=!0;else try{let O=JSON.parse(C.substring(6)),D=O.choices?.[0]?.delta,W=O.usage;if(O.choices?.[0]?.finish_reason&&(A=!0),W&&(k={totalTokenCount:W.total_tokens||(W.prompt_tokens||0)+(W.completion_tokens||0),promptTokenCount:W.prompt_tokens||0,candidatesTokenCount:W.completion_tokens||0,cachedContentTokenCount:W.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:W.completion_tokens_details?.reasoning_tokens||0},_=!0),D){let q=D.thinking||D.reasoning_content||D.reasoning,se=S(q);se&&(x.push({text:se,thought:!0}),_=!0);let V=D.content||(!D.thinking&&!D.reasoning_content&&!D.reasoning?D.text:null);if(V)if(Array.isArray(V))for(let F of V)if(typeof F=="object"&&F!==null){let B=F.type==="thinking"||F.type==="reasoning"||!!F.thought,Z=S(F);Z&&(x.push({text:Z,...B?{thought:!0}:{}}),_=!0)}else{let B=S(F);B&&(x.push({text:B}),_=!0)}else if(typeof V=="object"&&V!==null){let F=V.type==="thinking"||V.type==="reasoning"||!!V.thought,B=S(V);B&&(x.push({text:B,...F?{thought:!0}:{}}),_=!0)}else{let F=S(V);F&&(x.push({text:F}),_=!0)}}}catch{}if((A||Date.now()-$>=150)&&_&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:k},x=[],$=Date.now(),_=!1),A)break}Date.now()-$>=150&&_&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:k},x=[],$=Date.now(),_=!1)}};var Bo=async function*(e,n,t,s,o,r,a=!1,i,h=1){let f=[];s&&f.push({role:"system",content:s}),t.forEach(Z=>{let Ce=Z.role==="model"?"assistant":"user",v=[];Array.isArray(Z.parts)&&Z.parts.forEach(U=>{if(U.text)v.push({type:"text",text:U.text});else if(U.inlineData&&a){let X=U.inlineData.mimeType,ee=U.inlineData.data;X.startsWith("image/")&&At(n)&&v.push({type:"image_url",image_url:{url:`data:${X};base64,${ee}`}})}}),f.push({role:Ce,content:v.length===1&&v[0].type==="text"?v[0].text:v})});let l={Fast:"Fast",Low:"Fast",Medium:"Standard",Standard:"Standard",High:"High",xHigh:"High"}[o]||"High",u=l!=="Fast",d=n.includes("kimi"),p=n.includes("gemma"),g=n.includes("deepseek"),y=n.includes("glm"),m=n.includes("mistral"),w=n.includes("minimax"),x=n.includes("gpt"),k=n.includes("qwen"),$=n.includes("nemotron"),_=n.includes("llama-3"),S=n.includes("seed"),T=n.includes("poolside"),R=n.includes("thinkingmachines")||n.includes("muse"),E=_,b=null,C={Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},A={Fast:"64",Low:"64",Medium:"4096",Standard:"4096",High:"16384",xHigh:"16384"},O={Fast:"none",Low:"minimal",Medium:"medium",Standard:"medium",High:"max",xHigh:"max"},D=w||g||T||R?16384:32768;D=process.env.NVIDIA_BASE_URL?1024:D,D=b?1024:D;let W={model:n,messages:f,max_tokens:D,stream:!0,stream_options:{include_usage:!0},temperature:h,...x&&{thinking:C[o]||"high"}};if(!(process.env.NVIDIA_BASE_URL||E||b))if(d)W.chat_template_kwargs={thinking:u};else if(p)W.chat_template_kwargs={enable_thinking:u};else if(g)if(u){let Z=l==="High"?"max":"high";W.chat_template_kwargs={thinking:!0,reasoning_effort:Z}}else W.chat_template_kwargs={thinking:!1};else y?W.chat_template_kwargs={enable_thinking:u,clear_thinking:!u}:m?W.reasoning_effort=u?"high":"none":w&&n.includes("minimax-m3")?W.chat_template_kwargs={thinking_mode:u?"enabled":"disabled"}:k?W.chat_template_kwargs={enable_thinking:u}:$?l==="High"?W.chat_template_kwargs={enable_thinking:!0}:l==="Standard"?W.chat_template_kwargs={enable_thinking:!0,medium_effort:!0}:W.chat_template_kwargs={enable_thinking:!1}:S?u&&(W.extra_body={thinking_budget:parseInt(A[l]??"4096")}):T?W.chat_template_kwargs={enable_thinking:u}:R&&(W.reasoning_effort=O[l]||"medium");let q=0,se=6,V=!1,F=process.env.NVIDIA_BASE_URL||"https://integrate.api.nvidia.com/v1/chat/completions",B=process.env.NVIDIA_API_KEY&&process.env.NVIDIA_BASE_URL?process.env.NVIDIA_API_KEY:e;for(F.endsWith("/chat/completions")||(F=F.replace(/\/+$/,"")+"/chat/completions");q<se;){q++;try{let Z=await It(F,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${B}`},body:JSON.stringify(W),signal:i});if(!Z.ok){let je=await Z.text().catch(()=>""),it=Z.statusText;try{let bt=JSON.parse(je);it=bt.error?.message||bt.message||JSON.stringify(bt.detail||bt)}catch{je&&(it=je)}let ze=new Error(`NVIDIA API Error (${Z.status}): ${it}`);throw ze.status=Z.status,ze}let Ce=Z.body.getReader(),v=new TextDecoder,U="",X=[],ee=null,Ue=Date.now(),De=!1;for(;;){let{done:je,value:it}=await Ce.read();if(je){De&&(X.length>0||ee)&&(yield{candidates:X.length>0?[{content:{parts:X}}]:[],usageMetadata:ee},V=!0);break}U+=v.decode(it,{stream:!0});let ze=U.split(`
524
+ `);U=ze.pop();let bt=!1;for(let Nt of ze){let mt=Nt.trim();if(mt){if(mt==="data: [DONE]"){bt=!0;break}if(mt.startsWith("data: ")){let St;try{St=JSON.parse(mt.substring(6))}catch{continue}if(St.error)throw new Error(`NVIDIA Stream Error: ${St.error.message||JSON.stringify(St.error)}`);try{let Rt=St.usage;Rt&&(ee={totalTokenCount:Rt.total_tokens||Rt.prompt_tokens+Rt.completion_tokens,promptTokenCount:Rt.prompt_tokens||0,candidatesTokenCount:Rt.completion_tokens||0,cachedContentTokenCount:Rt.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:(Rt.completion_tokens_details?.reasoning_tokens||0)+(Rt.completion_tokens_details?.thoughts_tokens||0)},De=!0);let at=St.choices?.[0]?.delta?.reasoning||St.choices?.[0]?.delta?.reasoning_content||"",Se=St.choices?.[0]?.delta?.content||"";at&&(X.push({text:at,thought:!0}),De=!0),Se&&(X.push({text:Se}),De=!0)}catch{}}}}if((bt||Date.now()-Ue>=350)&&De&&(yield{candidates:X.length>0?[{content:{parts:[...X]}}]:[],usageMetadata:ee},V=!0,X=[],Ue=Date.now(),De=!1),bt)break}break}catch(Z){if(V||q>=se)throw Z;await new Promise(Ce=>setTimeout(Ce,3500))}}},ba=async function*(e,n){let t=[],s=null,o=!1,r=null,a=u=>{if(t.push(u),s){let d=s;s=null,d()}},i=n.split("/").pop();i=i.replace("llama-3.3","llama-3_3");let h=`https://api.ngc.nvidia.com/v2/predict/queues/models/qc69jvmznzxy/${i}`,f=!1,c=null,l=async()=>{try{let u=await fetch(h);if(u.ok){let d=await u.json();if(d&&d.queues&&d.queues[0]&&typeof d.queues[0].queueDepth=="number"){let p=d.queues[0].queueDepth;f||a({value:{type:"status",content:`Queue ${p||1}`},done:!1})}}}catch{}};process.env.NVIDIA_BASE_URL||(l(),c=setInterval(l,5e3)),(async()=>{try{let u=e[Symbol.asyncIterator]();for(;;){let{value:d,done:p}=await u.next();if(p)break;f=!0,c&&(clearInterval(c),c=null),a({value:d,done:!1})}o=!0,a(null)}catch(u){if(r=u,c&&(clearInterval(c),c=null),s){let d=s;s=null,d()}}})();try{for(;;){if(r)throw r;if(t.length>0){let u=t.shift();if(u===null&&o)break;yield u.value}else{if(o)break;await new Promise(u=>{s=u})}}}finally{c&&(clearInterval(c),c=null)}};var Uo=async function*(e,n,t,s,o,r,a,i,h=1,f=null){let c=[];s&&c.push({role:"system",content:[{type:"text",text:s}]});for(let b of t){let C=b.role==="user"?"user":"assistant",A=[];if(Array.isArray(b.parts)){for(let O of b.parts)if(O.text)A.push({type:"text",text:O.text});else if(O.inlineData&&a){let D=O.inlineData.mimeType,W=O.inlineData.data;D.startsWith("image/")?A.push({type:"image_url",image_url:{url:`data:${D};base64,${W}`}}):A.push({type:"file",file:{filename:O.filename||"file",file_data:`data:${D};base64,${W}`}})}}else{let O=b.text||"";O&&A.push({type:"text",text:O})}c.push({role:C,content:A.length===1&&A[0].type==="text"?A[0].text:A})}let l={Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},u=["free","nitro","floor","exact","extended","beta","online"],d=n,p=null;if(n.includes(":")){let b=n.split(":"),C=b[b.length-1].toLowerCase().trim();if(u.includes(C))d=n.trim();else{let A=b.pop().trim();d=b.join(":").trim(),A&&(p={order:[A],allow_fallbacks:!1})}}let g=`${e.slice(-5)}${f||""}${o}${d}${p?JSON.stringify(p):""}`,y=await Do(g),m={model:d,messages:c,stream:!0,temperature:h,cache_control:{type:"ephemeral"},session_id:y};p&&(m.provider=p);let w=l[o];w&&o!=="Fast"&&(m.reasoning_effort=w);let x=await It("https://openrouter.ai/api/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json","HTTP-Referer":"https://fluxflow-cli.onrender.com/","X-Title":"FluxFlow CLI","X-OpenRouter-Title":"FluxFlow CLI","X-Cache":"true","X-OpenRouter-Cache":"true"},body:JSON.stringify(m),signal:i});if(!x.ok){let b=await x.json().catch(()=>({})),C=b.error?.metadata?.raw||b.error?.message||(typeof b.error=="string"?b.error:"")||x.statusText||"Unknown error";throw new Error(`OpenRouter Error (${x.status}): ${C}`)}let k=x.body.getReader(),$=new TextDecoder,_="",S=[],T=null,R=Date.now(),E=!1;for(;;){let{done:b,value:C}=await k.read();if(b){E&&(S.length>0||T)&&(yield{candidates:S.length>0?[{content:{parts:S}}]:[],usageMetadata:T});break}_+=$.decode(C,{stream:!0});let A=_.split(`
525
+ `);_=A.pop();for(let O of A){let D=O.trim();if(!D||!D.startsWith("data: "))continue;let W=!1;if(D==="data: [DONE]")W=!0;else try{let q=JSON.parse(D.substring(6));if(q.error){let F=q.error.metadata?.raw||q.error.message||JSON.stringify(q.error);throw new Error(`OpenRouter Stream Error: ${F}`)}let se=q.choices?.[0]?.delta,V=q.usage;if(q.choices?.[0]?.finish_reason&&(W=!0),V&&(T={totalTokenCount:V.total_tokens||(V.prompt_tokens||0)+(V.completion_tokens||0),promptTokenCount:V.prompt_tokens||0,candidatesTokenCount:V.completion_tokens||0,cachedContentTokenCount:V.prompt_tokens_details?.cached_tokens||V.prompt_tokens_details?.cache_read_input_tokens||V.cache_read_input_tokens||0,thoughtsTokenCount:V.completion_tokens_details?.reasoning_tokens||0},E=!0),se){let F=se.reasoning||(se.reasoning_details?se.reasoning_details.map(B=>B.text).join(""):null);F&&(S.push({text:F,thought:!0}),E=!0),se.content&&(S.push({text:se.content}),E=!0)}}catch(q){if(q.message&&q.message.startsWith("OpenRouter Stream Error:"))throw q}if((W||Date.now()-R>=150)&&E&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:T},S=[],R=Date.now(),E=!1),W)break}}};import{Ollama as cc}from"ollama";var Zr=async function*(e,n,t,s,o,r,a,i,h=1,f="Cloud"){let c=[];s&&c.push({role:"system",content:s});for(let S of t){let T=S.role==="user"?"user":"assistant",R="",E=[];if(Array.isArray(S.parts)){R=S.parts.map(b=>b.text||"").filter(Boolean).join(`
526
+ `);for(let b of S.parts){let C=b.inlineData||b.inline_data;C&&C.data&&E.push(C.data)}}else R=S.text||"";if(R||E.length>0){let b={role:T,content:R};E.length>0&&(b.images=E),c.push(b)}}let l=f==="Local"||!e||e==="LOCAL",d={host:l?process.env.OLLAMA_HOST||"http://127.0.0.1:11434":process.env.OLLAMA_HOST||"https://ollama.com"};!l&&e&&(d.headers={Authorization:"Bearer "+e});let p=new cc(d),g=[],y=null,m=Date.now(),w=!1,x={Fast:!1,Low:"medium",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},k=x[o]!==void 0?x[o]:!0,$={model:n,messages:c,stream:!0,think:k,keep_alive:"10m",options:{temperature:h}},_=await p.chat($);for await(let S of _){if(i?.aborted)throw new DOMException("The user aborted a request.","AbortError");if(S.message?.thinking&&(g.push({text:S.message.thinking,thought:!0}),w=!0),S.message?.content&&(g.push({text:S.message.content}),w=!0),S.done){let T=S.prompt_cached_count||0;if(!T&&S.prompt_eval_count){let R=S.prompt_eval_duration||0;R>0&&R<5e7&&(T=S.prompt_eval_count)}y={totalTokenCount:(S.prompt_eval_count||0)+(S.eval_count||0),promptTokenCount:S.prompt_eval_count||0,candidatesTokenCount:S.eval_count||0,cachedContentTokenCount:T,thoughtsTokenCount:0},w=!0}(S.done||Date.now()-m>=150&&w)&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],m=Date.now(),w=!1)}w&&(g.length>0||y)&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y})};var Wo=async function*(e,n,t,s,o,r,a,i,h=1){let f=[];s&&f.push({role:"system",content:s});for(let k of t){let $=k.role==="user"?"user":"assistant",_=[];if(Array.isArray(k.parts)){for(let S of k.parts)if(S.text)_.push({type:"text",text:S.text});else if(S.inlineData&&a){let T=S.inlineData.mimeType,R=S.inlineData.data;T.startsWith("image/")&&_.push({type:"image_url",image_url:{url:`data:${T};base64,${R}`}})}}else{let S=k.text||"";S&&_.push({type:"text",text:S})}f.push({role:$,content:_.length===1&&_[0].type==="text"?_[0].text:_})}let c={Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},l={model:n,messages:f,stream:!0,stream_options:{include_usage:!0},temperature:h,max_completion_tokens:32768};c[o]&&(l.reasoning_effort=c[o]);let u=await It("https://crof.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(l),signal:i});if(!u.ok){let k=await u.json().catch(()=>({}));throw new Error(`CrofAI Error (${u.status}): ${k.error?.message||u.statusText}`)}let d=u.body.getReader(),p=new TextDecoder,g="",y=[],m=null,w=Date.now(),x=!1;for(;;){let{done:k,value:$}=await d.read();if(k){x&&(y.length>0||m)&&(yield{candidates:y.length>0?[{content:{parts:y}}]:[],usageMetadata:m});break}g+=p.decode($,{stream:!0});let _=g.split(`
527
+ `);g=_.pop();for(let S of _){let T=S.trim();if(!T||!T.startsWith("data: "))continue;let R=!1;if(T==="data: [DONE]")R=!0;else try{let E=JSON.parse(T.substring(6)),b=E.choices?.[0]?.delta,C=E.usage;if(E.choices?.[0]?.finish_reason&&(R=!0),C&&(m={totalTokenCount:C.total_tokens||(C.prompt_tokens||0)+(C.completion_tokens||0),promptTokenCount:C.prompt_tokens||0,candidatesTokenCount:C.completion_tokens||0,cachedContentTokenCount:C.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:C.completion_tokens_details?.reasoning_tokens||C.reasoning_tokens||0},x=!0),b){let A=b.reasoning_content||null;A&&(y.push({text:A,thought:!0}),x=!0),b.content&&(y.push({text:b.content}),x=!0)}}catch{}if((R||Date.now()-w>=150)&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),x=!1),R)break}Date.now()-w>=150&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),x=!1)}};var jo=async function*(e,n,t,s,o,r,a,i,h=1){let f=[];s&&f.push({role:"system",content:s});for(let S of t){let T=S.role==="user"?"user":"assistant",R="";if(Array.isArray(S.parts))for(let E of S.parts)E.text&&(R+=(R?`
528
+ `:"")+E.text);else R=S.text||"";f.push({role:T,content:R})}let c={Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},l=n&&n.toLowerCase().includes("qwen3.8-27b"),u=n&&(n.toLowerCase().includes("qwen3.8-27b")||n.toLowerCase().includes("qwen3.6-35b-a3b-fp8")),d={model:n,messages:f.filter(S=>S.content&&String(S.content).trim().length>0),stream:!0,stream_options:{include_usage:!0},temperature:h};l||(d.stream_options={include_usage:!0},c[o]&&(d.reasoning_effort=c[o]));let p=await It("https://model.inferx.net/endpoints/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(d),signal:i});if(!p.ok){let S=await p.text().catch(()=>""),T="";try{let R=JSON.parse(S);T=R.error?.message||R.error?.detail||R.message||R.detail||(typeof R.error=="string"?R.error:"")||(S&&S!=="{}"?S:"")}catch{T=S}throw(!T||T==="{}")&&(T=p.statusText||"Unknown error"),new Error(`InferX Error (${p.status}): ${T}`)}let g=p.body.getReader(),y=new TextDecoder,m="",w=[],x=null,k=Date.now(),$=!1,_=!0;for(;;){let{done:S,value:T}=await g.read();if(S){$&&(w.length>0||x)&&(yield{candidates:w.length>0?[{content:{parts:w}}]:[],usageMetadata:x});break}m+=y.decode(T,{stream:!0});let R=m.split(`
529
+ `);m=R.pop();for(let E of R){let b=E.trim();if(!b||!b.startsWith("data: "))continue;let C=!1;if(b==="data: [DONE]")C=!0;else try{let A=JSON.parse(b.substring(6)),O=A.choices?.[0]?.delta,D=A.usage;if(D&&(x={totalTokenCount:D.total_tokens||(D.prompt_tokens||0)+(D.completion_tokens||0),promptTokenCount:D.prompt_tokens||0,candidatesTokenCount:D.completion_tokens||0,cachedContentTokenCount:D.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:D.completion_tokens_details?.reasoning_tokens||D.reasoning_tokens||0},$=!0),O){let W=O.reasoning||O.reasoning_content||null;if(W&&(w.push({text:W,thought:!0}),$=!0),O.content){let q=O.content;u&&_&&q.length>0&&(q="<think>"+q,_=!1),w.push({text:q}),$=!0}}}catch{}if((C||Date.now()-k>=150||x)&&$&&(yield{candidates:w.length>0?[{content:{parts:[...w]}}]:[],usageMetadata:x},w=[],k=Date.now(),$=!1),C)break}Date.now()-k>=150&&$&&(yield{candidates:w.length>0?[{content:{parts:[...w]}}]:[],usageMetadata:x},w=[],k=Date.now(),$=!1)}};var Ho=async function*(e,n,t,s,o,r,a,i,h=1){let f=[];s&&f.push({role:"system",content:s});for(let k of t){let $=k.role==="user"?"user":"assistant",_=[];if(Array.isArray(k.parts)){for(let S of k.parts)if(S.text)_.push({type:"text",text:S.text});else if(S.inlineData&&a){let T=S.inlineData.mimeType,R=S.inlineData.data;T.startsWith("image/")&&_.push({type:"image_url",image_url:{url:`data:${T};base64,${R}`}})}}else{let S=k.text||"";S&&_.push({type:"text",text:S})}f.push({role:$,content:_.length===1&&_[0].type==="text"?_[0].text:_})}let c={Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},l={model:n,messages:f,stream:!0,stream_options:{include_usage:!0},temperature:h};c[o]&&(l.reasoning_effort=c[o]);let u=await It("https://token.sensenova.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(l),signal:i});if(!u.ok){let k=await u.json().catch(()=>({}));throw new Error(`SenseNova Error (${u.status}): ${k.error?.message||u.statusText}`)}let d=u.body.getReader(),p=new TextDecoder,g="",y=[],m=null,w=Date.now(),x=!1;for(;;){let{done:k,value:$}=await d.read();if(k){x&&(y.length>0||m)&&(yield{candidates:y.length>0?[{content:{parts:y}}]:[],usageMetadata:m});break}g+=p.decode($,{stream:!0});let _=g.split(`
530
+ `);g=_.pop();for(let S of _){let T=S.trim();if(!T||!T.startsWith("data: "))continue;let R=!1;if(T==="data: [DONE]")R=!0;else try{let E=JSON.parse(T.substring(6)),b=E.choices?.[0]?.delta,C=E.usage;if(C&&(m={totalTokenCount:C.total_tokens||(C.prompt_tokens||0)+(C.completion_tokens||0),promptTokenCount:C.prompt_tokens||0,candidatesTokenCount:C.completion_tokens||0,cachedContentTokenCount:C.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:C.completion_tokens_details?.reasoning_tokens||C.reasoning_tokens||0},x=!0),b){let A=b.reasoning||b.reasoning_content||null;A&&(y.push({text:A,thought:!0}),x=!0),b.content&&(y.push({text:b.content}),x=!0)}}catch{}if((R||Date.now()-w>=150||m)&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),x=!1),R)break}Date.now()-w>=150&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),x=!1)}};var Go=async function*(e,n,t,s,o,r,a,i,h=1){let f=[];s&&f.push({role:"system",content:s});for(let k of t){let $=k.role==="user"?"user":"assistant",_=[];if(Array.isArray(k.parts)){for(let S of k.parts)if(S.text)_.push({type:"text",text:S.text});else if(S.inlineData&&a){let T=S.inlineData.mimeType,R=S.inlineData.data;T.startsWith("image/")&&_.push({type:"image_url",image_url:{url:`data:${T};base64,${R}`}})}}else{let S=k.text||"";S&&_.push({type:"text",text:S})}f.push({role:$,content:_.length===1&&_[0].type==="text"?_[0].text:_})}let c={Fast:"minimal",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},l={model:n,messages:f,stream:!0,stream_options:{include_usage:!0},temperature:h};c[o]&&(l.reasoning_effort=c[o]);let u=await It("https://aihubmix.com/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(l),signal:i});if(!u.ok){let k=await u.json().catch(()=>({}));throw new Error(`AIHubMix Error (${u.status}): ${k.error?.message||u.statusText}`)}let d=u.body.getReader(),p=new TextDecoder,g="",y=[],m=null,w=Date.now(),x=!1;for(;;){let{done:k,value:$}=await d.read();if(k){x&&(y.length>0||m)&&(yield{candidates:y.length>0?[{content:{parts:y}}]:[],usageMetadata:m});break}g+=p.decode($,{stream:!0});let _=g.split(`
531
+ `);g=_.pop();for(let S of _){let T=S.trim();if(!T||!T.startsWith("data: "))continue;let R=!1;if(T==="data: [DONE]")R=!0;else try{let E=JSON.parse(T.substring(6)),b=E.choices?.[0]?.delta,C=E.usage;if(E.choices?.[0]?.finish_reason&&(R=!0),C&&(m={totalTokenCount:C.total_tokens||(C.prompt_tokens||0)+(C.completion_tokens||0),promptTokenCount:C.prompt_tokens||0,candidatesTokenCount:C.completion_tokens||0,cachedContentTokenCount:C.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:C.completion_tokens_details?.reasoning_tokens||C.reasoning_tokens||0},x=!0),b){let A=b.reasoning_content||null;A&&(y.push({text:A,thought:!0}),x=!0),b.content&&(y.push({text:b.content}),x=!0)}}catch{}if((R||Date.now()-w>=150)&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),x=!1),R)break}Date.now()-w>=150&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),x=!1)}};ni.config({quiet:!0});ni.config({path:"./fluxflow.env",override:!0,quiet:!0});ni.config({path:"./.fluxflow.env",override:!0,quiet:!0});var fc=/```[\s\S]*?```/g,dc=/```[\s\S]*$/g,uc=/`[^`]+`/g,pc=/^\|.*\|$/gm,hc=/^[^\w]+|[^\w]+$/g,mc=/[^a-z0-9]/gi,co=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,gc=/\[\s*(?:tool:functions\.|agent:generalist\.)([a-z0-9_]+)\s*\(/gi,yc=/(?:path|targetFile|TargetFile|directory|keyword|id|taskId|title|task)\s*=\s*\\?["']?([^\\"' \),]+)/,ys=/["']/g,Sa=/\\/g,wc=/<\|channel>thought/gi,xc=/<channel\|>/gi,bc=e=>typeof e!="string"?e:e.replace(wc,"<think>").replace(xc,"</think>"),qm=/^\s*(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\]|$)/i,Sc=(e,n)=>{let t=!1;for(let s=0;s<n;s++)e[s]==="`"&&(t=!t);return t},kc=e=>{let n=/(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\])/gi,t;for(;(t=n.exec(e))!==null;)if(!Sc(e,t.index))return{index:t.index,length:t[0].length};return{index:-1,length:0}},ei=e=>{if(!e||typeof e!="string")return null;let n=e.match(/^\s*(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought|\[(think|thought|thoughts)\])/i);if(!n)return null;let t=n.index+n[0].length,s=e.substring(t),o=kc(s);if(o.index!==-1){let r=t+o.index+o.length;return{fullBlock:e.substring(0,r),innerContent:s.substring(0,o.index),remainingText:e.substring(r)}}return{fullBlock:e,innerContent:s,remainingText:""}},nn=e=>{if(!e||typeof e!="string")return e;let n=ei(e);return n?n.remainingText.trimStart():e};var Ca=/`[^`]*`/g,Ma=/`[^`]*$/,ka=/<\|\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,Tc=/"([^"]+)"\s*:\s*(?:"([^"]*)"|(\d+)|true|false|null)/g,Ta=/<\|\s*tool_calls_section_begin\s*\|>/gi,Ra=/<\|\s*tool_calls_section_end\s*\|>/gi,Rc=/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi;var Ea=e=>!e||typeof e!="string"?e:e.replace(/(```[\s\S]*?```|`[^`]*`)|(<(?:\w+)(?:[^>]*)>\r?\n?|\r?\n?<\/\w+(?:[^>]*)>)/gi,(n,t)=>t||""),si=null,qo={},ws={key:null,value:null},tn=e=>e&&e.replace(/(?:(\x1b\[\d+m))?([✔✘✖🔍📖→➕↻↷•🛇])(?:(\x1b\[\d+m))?\s*\b(Clicked|Dragged|Scrolled|Typed|Pressed Key|Recaptured Screen|Created|Read Skill|Read|Edited|Viewed|Processed|Auto-Read|Skipped|List|Generated|Written|Searched|AI Search|Get Map|Write Canceled|Resolved Sub-Agent Query|Edit Canceled|Write Cancelled|Edit Denied|Visited|Updated|Reviewed|Delegated|Background|Checked|Indexed|Analyzed|Browsed|Elevating SubAgent|Checking SubAgent Work|Started Generalist|Called Generalist|Steered|Unsupported Modality|Awaiting|Cancelled|Aligning Moon Phase|Contemplating Existence|Staring At Void|Rollback Point Checked|Emergency Rollback Failed|Emergency Rollback|Delaying Professionally|Negotiating With Electrons|Touching Grass (virtually)|Panicking Softly|Rethinking Career Choices|Loading Cat Videos|Giving Up Entirely|Summoning Braincell #2|Pretending To Be Busy|Waiting For Motivation DLC|Rotating Internal Screaming|Downloading More RAM|Feeding The Hamsters|Gaslighting Scheduler|Performing Dramatic Pause|Buffering Social Energy|Calculating Regret|Reading Terms And Conditions|Becoming Sentient Briefly|Execution Error|Loop Detected|Contacting Ancestors)\b/ig,(n,t,s,o,r)=>`${t||""}${s}${o||""} \x1B[95m${r}\x1B[0m`),Ec=async(e,n=8,t=1e3,s=8e3,o=null)=>{let r=0;for(;;){if(o?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{return await e()}catch(a){if(o?.aborted||a?.name==="AbortError"||a?.message==="Subagent task was cancelled."||(r++,r>=n))throw a;let i=Math.min(t*Math.pow(2,r-1),s);await new Promise((h,f)=>{let c=setTimeout(h,i);o&&o.addEventListener("abort",()=>{clearTimeout(c),f(new DOMException("The user aborted a request.","AbortError"))})})}}},Mt=!1;var _c=e=>{let n=e.filter(o=>(o.role==="user"||o.role==="agent"||o.role==="system")&&o.role!=="think"&&!o.isVisualFeedback&&!o.isMeta&&!o.isTerminalRecord&&!(o.text&&o.text.includes("[TERMINAL_RECORD]"))&&!String(o.id).startsWith("welcome")).map((o,r,a)=>{let i=o.fullText||o.text||"";if(o.role==="user"&&r<a.length-1)if(i.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")){let h=i.indexOf("**CONTEXT SUMMARY OF PREVIOUS TURNS");if(h!==-1){let c=i.substring(0,h).lastIndexOf("[SYSTEM METADATA]");c!==-1?i=i.substring(c).trim():i=i.substring(h).trim()}}else{let h=i.lastIndexOf("[USER]"),f=i.lastIndexOf("[USER PROMPT]");h!==-1?i=i.substring(h+6).trim():f!==-1&&(i=i.substring(f).trim())}return{...o,text:i}}),t=[],s=0;for(;s<n.length;){let o=n[s];if(o.role==="user")t.push(o),s++;else{let r=[];for(;s<n.length&&n[s].role!=="user";)r.push(n[s]),s++;let a=[],i=[],h=!1,f=()=>{a.length>0&&(t.push({role:"agent",text:"combined"}),a=[]),i.length>0&&(t.push({role:"system",text:"combined"}),i=[]),h=!1};r.forEach(c=>{let l=c.role==="system"&&(c.text?.startsWith("[TOOL RESULT]")||c.text?.startsWith("SUCCESS:")||c.text?.startsWith("ERROR:")||c.fullText?.startsWith("[TOOL RESULT]")||c.fullText?.startsWith("SUCCESS:")||c.fullText?.startsWith("ERROR:")),u=c.fullText||c.text||"",d=u.trim();if(!(!d&&!c.binaryPart)){if(l)i.push(d);else if(c.role==="agent"){!h&&i.length>0&&f();let p=u.endsWith(`
532
+ `),g=d.toLowerCase().includes("tool:functions.")||d.toLowerCase().includes("agent:generalist.");a.push(d),g&&p?h=!0:h=!1}}}),f()}}return t.length},$c=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),zm=()=>{Mt=!0},Km=()=>Mt,ti={write_file:"Writing",update_file:"Editing",read_folder:"Reading",view_file:"Reading",exec_command:"Executing Command",web_search:"Searching",web_scrape:"Reading",memory:"Updating Memory",search_keyword:"Searching",file_map:"Generating Map",ask:"User Input",write_pdf:"Creating",write_docx:"Creating",generate_image:"Generating",todo:"Planning",Todo:"Planning",goal:"Planning",Goal:"Planning",invoke_sync:"Sub-Agent Working",invoke:"Starting Agent",get_progress:"Checking Progress",cancel:"Cancelling",await:"Waiting",EmergencyRollback:"Don't Panic. Lookin' into it",answer:"Answering Sub-Agent",Answer:"Answering Sub-Agent",steer:"Steering Sub-Agent",Steer:"Steering Sub-Agent",Click:"Clicking",click:"Clicking",Drag:"Dragging",drag:"Dragging",Scroll:"Scrolling",scroll:"Scrolling",KeyboardTyping:"Typing",keyboard_typing:"Typing",KeyPress:"Pressing Key",key_press:"Pressing Key",RecaptureScreen:"Recapturing Screen",recapture_screen:"Recapturing Screen"},xs=(e,n)=>{try{let t=L(n),s=e.toLowerCase().replace(/_/g,"");if(s==="invokesync"||s==="invoke")return t.title||(t.task?t.task.substring(0,30):null);if(s==="getprogress"||s==="cancel"||s==="steer"||s==="steersubagent")return t.id||t.taskId;let o=t.path||t.targetFile||t.TargetFile||t.directory;return o?Q.basename(o.replace(/["']/g,"").replace(/\\/g,"/")):null}catch{return null}},oi=e=>e?new $a({apiKey:e}):si,Ym=async(e,n,t,s,o={})=>{let{onStatus:i,onMemoryUpdated:h,onBackgroundIncrement:f}=o,{profile:c,thinkingLevel:l,mode:u,janitorModel:d,chatId:p,systemSettings:g,sessionStats:y,aiProvider:m="Google",apiKey:w}=e,x=process.env.NVIDIA_BASE_URL||m==="Ollama"||m==="CrofAI"||m==="InferX"||m==="SenseNova"||m==="AIHubMix"?!1:g?.memory!==!1,$=ne(Dt,[]).map(v=>`- [${v.id}]: ${v.memory}`).join(`
533
+ `),_=s.slice(0,-1).filter(v=>v.text&&!v.text.includes("[TOOL RESULT]")&&!v.text.includes("OBSERVATION:")&&!v.text.startsWith("[TERMINAL_RECORD]")&&!v.isTerminalRecord&&!v.isMeta&&!v.isLogo&&!String(v.id).startsWith("welcome")&&!String(v.id).startsWith("logo")).slice(-14).map(v=>{let U=nn($c(v.text)).replace(/\[tool:functions\..*?\]/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[METADATA \(PRIORITY: DYNAMIC\)\] Time: ([^|\n]+)/g,(De,je)=>`[METADATA (PRIORITY: DYNAMIC)] Time: ${je.replace(/:\d{2}/g,"")}`).replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[TOOL RESULTS\]/g,"").replace(/\[tool results\]/g,"").replace(/\r?\n\r?\n/g,`
534
+ `).replace(/\n\n/g,`
535
+ `).replace(/\\n\\n/g,"").trim(),X=v.role==="user"?8192:32768,ee=U.substring(0,X);U.length>X&&(ee+=`
536
+ ... (truncated) ...`);let Ue=v.role==="user"?ee.startsWith("[USER]")?"":"[USER]: ":ee.startsWith("[AGENT]")?"":"[AGENT]: ";return{role:v.role==="user"?"user":"model",parts:[{text:`${Ue}${ee}`}]}}),S=s.filter(v=>v.role==="user").length===1,T=n.includes("[TITLE-UPDATE]"),R=Math.random()<.8,E=S||T||R,b=nn(t).trim(),C=Oi($,x,E),A=`${b.replace(/\[tool:functions\..*?\]/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[\[TOOL RESULTS\]\]/g,"").replace(/\[tool results\]/g,"").substring(0,32768)}`;A.length>32768&&(A+=`
537
+ ... (truncated) ...`);let O=n.replace(/\[Prompted on:.*?\]/g,"").trim();A=A.replace(/\r?\n\r?\n/g,`
538
+ `).replace(/\n\n/g,`
539
+ `).replace(/\\n\\n/g,"").trim();let D=new Date,q=`[METADATA] Current date and Time: ${`${D.getFullYear()}-${D.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(D.getDate()).padStart(2,"0")}, ${D.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0})}`}
540
+
541
+ [USER]: ${O.substring(0,8192)}
542
+ ${O.length>8192?`... (truncated) ...
543
+
544
+ `:""}
545
+ [AGENT (current turn)]: ${A}`;_.push({role:"user",parts:[{text:q}]});let se=await nr("NVIDIA"),F=(await en()).quotas?.providerTiers?.NVIDIA==="Free",B="",Z=0,Ce=x?12:-1;for(;Z<=Ce;)try{if(!await yi("background",e))return;let v="",U=null,X=!1,ee=m;try{let je=new Promise((at,Se)=>setTimeout(()=>Se(new Error("JANITOR_TIMEOUT")),1e4)),it=m==="Google"&&Z>=0&&Z<6&&se&&F,ze=m==="DeepSeek"&&Z<4&&se&&F;X=it||ze,ee=X?"NVIDIA":m;let bt=(async()=>{if(m==="OpenRouter"){let at=Re("janitor_open_router"),ie=Uo(w,at,_,C,"Fast",u,!1,null,.7)[Symbol.asyncIterator](),Yt=await ie.next();return{iterator:ie,firstResult:Yt}}else if(m==="DeepSeek"&&!X){let Se=Fo(w,Re("deepseek_fast_fallback"),_,C,"Fast",u,!1,null,.7)[Symbol.asyncIterator](),ie=await Se.next();return{iterator:Se,firstResult:ie}}else if(m==="Mistral"&&!X){let Se=No(w,Re("mistral_janitor_fallback"),_,C,"Fast",u,!1,null,.7)[Symbol.asyncIterator](),ie=await Se.next();return{iterator:Se,firstResult:ie}}else if(m==="NVIDIA"||X){let Se=Bo(X?se:w,Re("nvidia_janitor_fallback"),_,C,"Fast",u,!1,null,.7)[Symbol.asyncIterator](),ie=await Se.next();return{iterator:Se,firstResult:ie}}else if(m==="CrofAI"){let Se=Wo(w,targetModel||Re("crofai_fallback")||"deepseek-v4-flash-0731",_,C,"Fast",u,!1,null,.7)[Symbol.asyncIterator](),ie=await Se.next();return{iterator:Se,firstResult:ie}}else if(m==="InferX"){let Se=jo(w,targetModel||Re("inferx_fallback")||"deepseek-v4-flash",_,C,"Fast",u,!1,null,.7)[Symbol.asyncIterator](),ie=await Se.next();return{iterator:Se,firstResult:ie}}else if(m==="SenseNova"){let Se=Ho(w,targetModel||Re("sensenova_fallback")||"sensenova-6.8-flash-lite",_,C,"Fast",u,!1,null,.7)[Symbol.asyncIterator](),ie=await Se.next();return{iterator:Se,firstResult:ie}}else if(m==="AIHubMix"){let Se=Go(w,targetModel||Re("aihubmix_fallback")||"gpt-4o-mini",_,C,"Fast",u,!1,null,.7)[Symbol.asyncIterator](),ie=await Se.next();return{iterator:Se,firstResult:ie}}else{let ie=(await oi(w).models.generateContentStream({model:d||(Z===Ce?Re("janitor_default"):Re("gemma_janitor_fallback_google")),contents:_,config:{systemInstruction:C,temperature:.7,safetySettings:[{category:Vn.HARM_CATEGORY_HARASSMENT,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_HATE_SPEECH,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Yn.BLOCK_NONE}],thinkingConfig:{includeThoughts:!1,thinkingLevel:ut.MINIMAL}}}))[Symbol.asyncIterator](),Yt=await ie.next();return{iterator:ie,firstResult:Yt}}})();if(process.stdout.isTTY){let ie=(await ls())[p]?.name||"",Yt=ie&&!ie.startsWith("flow-")&&!ie.startsWith("Session ")?ie:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${Yt}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${Yt}\x07`)}let{iterator:Nt,firstResult:mt}=await Promise.race([bt,je]),{value:St,done:Rt}=mt;if(!Rt&&St){let at=St.candidates?.[0]?.content?.parts,Se=at?ee==="Google"?at[1]?.text||at[0]?.text||"":at.filter(ie=>ie.text&&!ie.thought).map(ie=>ie.text).join(""):typeof St.text=="function"?St.text():"";Se&&(v+=Se),U=St.usageMetadata;for await(let ie of{[Symbol.asyncIterator]:()=>Nt}){let Yt=ie.candidates?.[0]?.content?.parts,Xn=Yt?ee==="Google"?Yt[1]?.text||Yt[0]?.text||"":Yt.filter(Jn=>Jn.text&&!Jn.thought).map(Jn=>Jn.text).join(""):typeof ie.text=="function"?ie.text():"";Xn&&(v+=Xn),U=ie.usageMetadata}}}catch(je){throw je}if(v){if(B=v,U){let je=U.totalTokenCount||0,it=U.cachedContentTokenCount||0,ze=(U.candidatesTokenCount||0)+(U.thoughtsTokenCount||0),bt=X?Re("nvidia_janitor_fallback"):ee==="DeepSeek"?Re("deepseek_fast_fallback"):ee==="OpenRouter"?Re("janitor_open_router"):d||(Z===Ce?Re("janitor_default"):Re("gemma_janitor_fallback_google"));await zt("tokens",je,ee,bt),it>0&&await zt("cachedTokens",it,ee,bt),ze>0&&await zt("candidateTokens",ze,ee,bt)}}else throw new Error("No synthesis generated by Janitor.");f&&(f(),await vt("background"));let Ue=Ko(B),De=!1;for(let je of Ue){let it=je.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(it)&&(De=!0);let ze={chatId:p,sessionId:p,history:s},bt=await ao(it,je.args,ze);it.toLowerCase()==="memory"&&(je.args.includes("action='user'")||je.args.includes('action="user"'))&&!bt.startsWith("ERROR")&&(h&&h(),process.stdout.isTTY&&(process.stdout.write("\x1B]0;Memory Updated\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=Memory Updated\x07")),await new Promise(mt=>setTimeout(mt,3e3)))}if(!De)try{let je=ne(Dt,[]);if(je.length>0){let it=[];for(let ze of je)ze.score===void 0&&(ze.score=.5),ze.score*=.99995,ze.score<.05&&(ze.score=0),ze.score=Math.round(ze.score*1e5)/1e5,ze.score>0&&it.push(ze);he(Dt,it)}}catch{}break}catch(v){Z++;let U=new Date().toLocaleString(),X=v instanceof Error?(()=>{try{return JSON.parse(JSON.parse(v.message).error.message).error.message}catch{return String(v)}})():String(v);await new Promise(De=>setTimeout(De,1e3));let ee=Q.join(hn,"janitor");if(Pe.existsSync(ee)||Pe.mkdirSync(ee,{recursive:!0}),Pe.appendFileSync(Q.join(ee,"error.log"),`ERROR [Attempt ${Z}/${Ce+1}] [${U}]: ${X}
546
+
547
+ `),Z>Ce)break;let Ue=Math.min(750*Math.pow(2,Z-1),5e3);await new Promise(De=>setTimeout(De,Ue))}if(Z){let v=Q.join(hn,"janitor");Pe.appendFileSync(Q.join(v,"error.log"),`-----------------------------------------------------------------------------
548
+
549
+ `)}if(process.stdout.isTTY)try{let X=(await ls())[p]?.name||"",ee=X&&!X.startsWith("flow-")&&!X.startsWith("Session ")?X:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${ee}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${ee}\x07`)}catch{process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")}},Cc=e=>{let n=nn(e),t=As?n:n.replace(Ca,o=>" ".repeat(o.length)).replace(Ma,o=>" ".repeat(o.length));co.lastIndex=0;let s;for(;(s=co.exec(t))!==null;){let o=s.index+s[0].length-1,r=0,a=null,i=!1,h=!1;for(let f=o;f<t.length;f++){let c=n[f];if(!a&&(c==='"'||c==="'"||c==="`")?(a=c,i=!1):a&&c===a&&!i&&(a=null),!a&&(c==="("?r++:c===")"&&r--,r===0)){let l=f+1;for(;l<t.length&&/\s/.test(t[l]);)l++;if(l<t.length&&t[l]==="]"){h=!0,co.lastIndex=l+1;break}}c==="\\"?i=!i:i=!1}if(!h)return{inside:!0,toolName:s[1],startIndex:s.index,args:n.substring(s.index+s[0].length)}}return{inside:!1}},Aa=(e,n=!0)=>{let t=co;t.lastIndex=0;let s="",o=0,r;for(;(r=t.exec(e))!==null;){let a=e.substring(o,r.index);s+=n&&o===0?nn(a):a;let i=r.index+r[0].length-1,h=0,f=null,c=-1;for(let l=i;l<e.length;l++){let u=e[l];if(f){if(u===f){let d=0;for(let p=l-1;p>=0&&e[p]==="\\";p--)d++;d%2===0&&(f=null)}}else if(u==='"'||u==="'"||u==="`")f=u;else if(u==="(")h++;else if(u===")"&&(h--,h===0)){let d=l+1;for(;d<e.length&&/\s/.test(e[d]);)d++;if(d<e.length&&e[d]==="]"){c=d;break}}}if(c!==-1)s+="[tool:functions."+r[1]+"()]",o=c+1,t.lastIndex=o;else{s+="[tool:functions."+r[1]+"(",o=e.length;break}}return o<e.length&&(s+=n&&o===0?nn(e.substring(o)):e.substring(o)),s},Mc=(e,n,t)=>{let s=co;s.lastIndex=0;let o="",r=0,a;for(;(a=s.exec(e))!==null;){let i=e.substring(r,a.index);o+=i.replace(n,t);let h=a.index+a[0].length-1,f=0,c=null,l=-1;for(let u=h;u<e.length;u++){let d=e[u];if(c){if(d===c){let p=0;for(let g=u-1;g>=0&&e[g]==="\\";g--)p++;p%2===0&&(c=null)}}else if(d==='"'||d==="'"||d==="`")c=d;else if(d==="(")f++;else if(d===")"&&(f--,f===0)){let p=u+1;for(;p<e.length&&/\s/.test(e[p]);)p++;if(p<e.length&&e[p]==="]"){l=p;break}}}if(l!==-1)o+=e.substring(a.index,l+1),r=l+1,s.lastIndex=r;else{o+=e.substring(a.index),r=e.length;break}}return r<e.length&&(o+=e.substring(r).replace(n,t)),o},_a=e=>Aa(e,!0),Ac=e=>{if(!e)return e;let n={patchfile:"PatchFile",writefile:"WriteFile",readfile:"ReadFile",viewfile:"ReadFile",run:"Run",execcommand:"Run",searchkeyword:"SearchKeyword",codesearch:"CodeSearch",code_search:"CodeSearch",websearch:"WebSearch",webscrape:"WebScrape",readfolder:"ReadFolder",writepdf:"WritePDF",writedoc:"WriteDoc",writedocx:"WriteDoc",filemap:"FileMap",generateimage:"GenerateImage",todo:"Todo",goal:"Goal",askuser:"AskUser",ask:"AskUser"},t=o=>o.split("_").map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join("");ka.lastIndex=0;let s=e.replace(ka,(o,r,a)=>{let i="";try{let c=JSON.parse(a.trim());c&&typeof c=="object"&&(i=Object.entries(c).map(([u,d])=>{let p=typeof d=="string"?d:JSON.stringify(d);return`${u}=${JSON.stringify(p)}`}).join(", "))}catch{let l=[],u=Tc;u.lastIndex=0;let d;for(;(d=u.exec(a))!==null;){let p=d[1],g=d[2]!==void 0?d[2]:d[0].split(":").slice(1).join(":").trim();l.push(`${p}=${JSON.stringify(g)}`)}l.length>0?i=l.join(", "):i=a.trim()}let h=r.toLowerCase().replace(/_/g,"");return`[tool:functions.${n[h]||t(r)}(${i})]`});return Ta.lastIndex=0,Ra.lastIndex=0,s=s.replace(Ta,""),s=s.replace(Ra,""),s},vc=/(?:path|query|url|keyword|command|method|title|task|id)\s*=\s*['"`]?\s*\.\.\.\s*['"`]?/i,Ic=/^['"`]?\s*\.\.\.\s*['"`]?$/,Dn=e=>{if(e==null)return!1;let n=String(e).trim();return n==="..."||n==="\u2026"||Ic.test(n)},Ko=e=>{if(!e)return[];let n=Ac(e),t=nn(n),s=[],o=As?t:t.replace(Ca,i=>" ".repeat(i.length)).replace(Ma,i=>" ".repeat(i.length)),r=gc;r.lastIndex=0;let a;for(;(a=r.exec(o))!==null;){let i=a[1],h=a.index+a[0].length-1,f=0,c=null,l=-1,u=-1;for(let d=h;d<o.length;d++){let p=t[d];if(c){if(p===c){let g=0;for(let y=d-1;y>=0&&t[y]==="\\";y--)g++;g%2===0&&(c=null)}}else if(p==='"'||p==="'"||p==="`")c=p;else if(p==="(")f++;else if(p===")"&&(f--,f===0)){u=d;let g=d+1;for(;g<o.length&&/\s/.test(o[g]);)g++;if(g<o.length&&o[g]==="]"){l=g;break}}}if(l!==-1){let d=t.substring(h+1,u),p=t.substring(a.index,l+1),g=L(d);Dn(g.path)||Dn(g.query)||Dn(g.url)||Dn(g.keyword)||Dn(g.command)||Dn(g.method)||Dn(g.title)||Dn(g.task)||Dn(g.id)||vc.test(d)||s.push({fullMatch:p,toolName:i.trim(),args:d.trim()}),r.lastIndex=l+1}}return s},Vm=(e,n={})=>{if(!e)return null;if(qo=n,si=new $a({apiKey:e}),!globalThis.__perfCleanupInstalled){globalThis.__perfCleanupInstalled=!0,setInterval(()=>{typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks())},6e4);let t=globalThis.fetch;globalThis.fetch=async(...s)=>{try{let o=await t(...s);return typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),o}catch(o){throw typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),o}}}},zo=async(e,n,t,s,o="Fast",r=.75,a="agent")=>Ec(async()=>{let{aiProvider:i="Google",apiKey:h,mode:f}=e,c="",l=null,u=typeof t=="string"?[{role:"user",parts:[{text:t}]}]:t,d=new AbortController,p=d.signal,g=setInterval(()=>{Mt&&(d.abort(),clearInterval(g))},100);try{let y;i==="Ollama"?y=Zr(h,n,u,s,o,f,At(n),p,r,systemSettings?.ollamaEndpoint||"Cloud"):i==="OpenRouter"?y=Uo(h,n,u,s,o,f,At(n),p,r):i==="DeepSeek"?y=Fo(h,n,u,s,o,f,At(n),p,r):i==="Mistral"?y=No(h,n,u,s,o,f,At(n),p,r):i==="NVIDIA"?y=Bo(h,n,u,s,o,f,At(n),p,r):i==="CrofAI"?y=Wo(h,n,u,s,o,f,At(n),p,r):i==="InferX"?y=jo(h,n,u,s,o,f,At(n),p,r):i==="SenseNova"?y=Ho(h,n,u,s,o,f,At(n),p,r):i==="AIHubMix"?y=Go(h,n,u,s,o,f,At(n),p,r):y=await oi(h).models.generateContentStream({model:n,contents:u,config:{systemInstruction:s,temperature:r,thinkingConfig:(()=>{let x=(n||"").toLowerCase(),k=x.includes("gemma-4")||x.startsWith("gemma"),$=x.includes("gemini-3");if(k||$)return k?o.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:ut.MINIMAL}:{includeThoughts:!0,thinkingLevel:ut.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:x.includes("pro")?ut.LOW:ut.MINIMAL,Low:ut.LOW,Medium:ut.MEDIUM,Standard:ut.MEDIUM,High:ut.HIGH,xHigh:ut.HIGH}[o]||ut.MEDIUM};{let _={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[o]||2048;return _===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:_}}})()}},{signal:p});for await(let m of y){if(Mt)throw new Error("Subagent task was cancelled.");if(e?.taskId&&typeof Ve<"u"){let k=Ve.find($=>$.id===e.taskId);if(k&&k.status==="cancelled")throw new Error("Subagent task was cancelled.")}let w="";if(m.candidates?.[0]?.content?.parts)for(let k of m.candidates[0].content.parts)k.text&&!k.thought&&(c+=k.text,w+=k.text);let x=w?w.trim().split(/\s+/).filter(Boolean).length:0;e&&typeof e.onTokenChunk=="function"&&e.onTokenChunk(w,x),m.usageMetadata&&(l=m.usageMetadata)}}finally{clearInterval(g)}if(l){let y=l.totalTokenCount||0,m=l.cachedContentTokenCount||0,w=(l.candidatesTokenCount||0)+(l.thoughtsTokenCount||0);await zt("tokens",y,i,n),m>0&&await zt("cachedTokens",m,i,n),w>0&&await zt("candidateTokens",w,i,n),e&&typeof e.onUsage=="function"&&e.onUsage({totalTokenCount:y,cachedContentTokenCount:m,candidatesTokenCount:w})}return await vt("agent",i),{text:c,usageMetadata:l}}),Oc=async(e,n,t=null)=>{t=t||ne(Zt,{});try{let{aiProvider:s="Google"}=n;if(Object.values(t).flat().length<=5)return;let r=Object.keys(t).filter(u=>u!==e&&Array.isArray(t[u])&&t[u].length>2);if(r.length===0)return;let a=`You are a silent background process for the FluxFlow CLI Agent.
550
+ Your task is to summarize or merge temporary context memories from one or more past conversation sessions.
551
+ For each Chat ID provided, you must output a tool call to save the consolidated summary.
552
+
553
+ The tool call format MUST be:
554
+ [tool:functions.saveSummary(id="<chat-id>", summary="<updated summary string, max 400 words>")]
555
+
556
+ Guidelines:
557
+ - 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.
558
+ - Focus on key goals, preferences, modified files, and technical decisions.
559
+ - Under no circumstances write normal conversational text. Output ONLY the tool calls.
560
+ - You can stack multiple tool calls for multiple chats.
561
+
562
+ Chats to process:
563
+
564
+ `,i=ne(In,{});for(let u of r){let p=t[u].map(y=>`- ${y}`).join(`
565
+ `),g=i[u];a+=`[Chat ID: ${u}]
566
+ `,g?(a+=`- Existing Summary: "${g}"
567
+ `,a+=`
568
+ -- New Memories to integrate:
569
+ ${p}
570
+
571
+ `):a+=`-- Individual Memories:
572
+ ${p}
573
+
574
+ `}let h=0,f=5,c=!1,l=Re("gemma_janitor_fallback_google");for(s==="OpenRouter"&&(l=Re("janitor_open_router")),s==="DeepSeek"&&(l=Re("deepseek_level_1")),s==="Mistral"&&(l=Re("mistral_level_1")),s==="NVIDIA"&&(l=Re("nvidia_janitor_fallback")),s==="CrofAI"&&(l=Re("crofai_fallback")),s==="InferX"&&(l=Re("inferx_fallback")),s==="SenseNova"&&(l=Re("sensenova_fallback")),s==="AIHubMix"&&(l=Re("aihubmix_fallback"));h<=f&&!c;){h++;try{let d=(await zo(n,l,a,null,"Fast",.75,"background")).text||"",p=Ko(d);if(p.length===0)throw new Error("No tool calls detected in synthesis response");for(let g of p){let y=g.toolName;["saveSummary","saveSumary","SaveSummary","SaveSumary"].includes(y)&&await ao(y,g.args,{chatId:e})}c=!0}catch(u){if(h>=f)throw new Error(`Failed after ${f} attempts. Last error: ${u.message}`)}}}catch(s){let o=s instanceof Error?(()=>{try{return JSON.parse(JSON.parse(s.message).error.message).error.message}catch{return String(s)}})():String(s),r=Q.join(hn,"janitor");Pe.existsSync(r)||Pe.mkdirSync(r,{recursive:!0}),Pe.appendFileSync(Q.join(r,"error.log"),`[${new Date().toLocaleString()}] Past memory batch consolidation error: ${o}
575
+ `)}},Lc=async(e,n,t=!1)=>{let{chatId:s,aiProvider:o="Google"}=e,r=Q.join(go,"chat-summaries.json"),a=d=>d.filter(p=>(p.role==="user"||p.role==="agent"||p.role==="system")&&p.role!=="think"&&!p.isVisualFeedback&&!p.isMeta&&!p.isTerminalRecord&&!(p.text&&p.text.includes("[TERMINAL_RECORD]"))&&!String(p.id).startsWith("welcome")).map(p=>{let g=p.fullText||p.text||"",y=p.role==="system"||g.startsWith("[TOOL RESULT]:")||p.text&&p.text.startsWith("[TOOL RESULT]:"),m=g;return y&&(g.includes("[TOOL RESULT]:")||p.text&&p.text.includes("[TOOL RESULT]:"))?m="[TOOL RESULT]: ...truncated for summary":m=m.replace(/(\[(?:tool|agent):[a-zA-Z0-9_\.]+)\([\s\S]*?\)(\])/g,"$1(...)$2"),`[${y?"TOOL":p.role==="agent"?"AGENT":"USER"}]: ${m}`}).join(`
576
+
577
+ `),i=async(d,p)=>{let g="You are an expert context summarizer. Summarize the provided chat history (which may include previous summaries, user instructions, agent outputs, and tool results) into a detailed, coherent, and highly technical summary of 1000 to 1500 words. Focus on preserving the architectural decisions made, current system state, task progress, and critical code details, chat messages, file changes. Under no circumstances exceed MAX 2000 words.",y=p?`Here is the previous summary:
578
+ ${p}
579
+
580
+ Here is the new conversation history:
581
+ ${d}
582
+
583
+ Provide a new consolidated summary of the entire session.`:`Here is the conversation history:
584
+ ${d}
585
+
586
+ Provide a consolidated summary of the entire session.`,m=Re("gemma_janitor_fallback_google");o==="OpenRouter"&&(m=Re("janitor_open_router")),o==="DeepSeek"&&(m=Re("deepseek_level_1")),o==="Mistral"&&(m=Re("mistral_level_1")),o==="NVIDIA"&&(m=Re("nvidia_chat_summarizer_fallback")),o==="CrofAI"&&(m=Re("crofai_fallback")),o==="InferX"&&(m=Re("inferx_fallback")),o==="SenseNova"&&(m=Re("sensenova_fallback")),o==="AIHubMix"&&(m=Re("aihubmix_fallback"));let w=0,x=!1,k=null;for(;w<=3&&!x;){w++;try{k=await zo(e,m,y,g,"Fast"),x=!0}catch{if(w>3){if(o==="Google")try{let _=Re("general_fallback");return(await zo(e,_,y,g,"Fast")).text||""}catch{return""}return""}}}return k&&k.text||""},h=a(n),f=ne(r,{}),c=f[s]||{summary:"",historyLength:0};typeof c=="string"&&(c={summary:c,historyLength:0});let l=c.summary||"",u=await i(h,l);if(u){c.summary=u;let d=_c(n);return t?c.historyLength=(c.historyLength||0)+d:c.historyLength=d,f[s]=c,he(r,f),u}return null},Xm=e=>{try{let n=Q.join(go,"chat-summaries.json");if(Pe.existsSync(n)){let t=ne(n,{});t[e]&&(delete t[e],he(n,t))}}catch{}},Jm=async function*(e,n,t,s,o){let{profile:r,thinkingLevel:a,mode:i,janitorModel:h,chatId:f,isPlayground:c,systemSettings:l,sessionStats:u,aiProvider:d="Google",apiTier:p,wildcardTooling:g}=t,y=At(e);if(!si&&d==="Google")throw new Error("AI not initialized");let m=process.env.NVIDIA_BASE_URL||t?.aiProvider==="Ollama"||t?.aiProvider==="CrofAI"||t?.aiProvider==="InferX"||t?.aiProvider==="SenseNova"||t?.aiProvider==="AIHubMix"?!1:l?.memory!==!1,w=n[n.length-1].text,x=Q.join(go,"chat-summaries.json"),k=!1,$=n.filter(E=>E.role==="user").length===1,_=w.includes("[TITLE-UPDATE]"),S=$||_,T=w.replace(/\[TITLE-UPDATE\]/g,"").trim();T=T.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),yield{type:"status",content:"[start]"},yield{type:"status",content:"Gathering Context"},await ht.startTransaction(f,T),l?.advanceRollback&&await Kn.takeInitialSnapshot(f),Mt=!1;let R=null;try{let E=new AbortController;R=setInterval(()=>{Mt&&(E.abort(),R&&(clearInterval(R),R=null))},400);let b=[...n.slice(0,-1)];{let Oe=ne(x,{})[f]||{summary:"",historyLength:0};if(Oe.summary&&Oe.historyLength>0){let sn=0,Ee=[];for(let Ze=0;Ze<b.length;Ze++){let He=b[Ze];(He.role==="user"||He.role==="agent"||He.role==="system")&&!String(He.id).startsWith("welcome")&&!He.isMeta&&sn++,sn>Oe.historyLength&&Ee.push(He)}b=Ee}}b=b.map(z=>{if(z.role==="user"&&z.text){let Oe=z.text.match(/\[USER\]([\s\S]*?)\[\/USER\]/);if(Oe)return{...z,text:Oe[1].trim()}}return{...z}});let C=process.env.HIGH_CONTEXT,A=255e3,O=26e4;if(C&&C!=="false"){let z=parseInt(C,10);!isNaN(z)&&z>=0&&z<=1e6&&(O=z,A=Math.round(z*.85))}if((d==="NVIDIA"&&(e?.includes("gpt")||e?.includes("qwen")||e?.includes("medium")||e.includes("muse"))||d==="Mistral")&&(A=122e3,O=126e3),d==="Ollama"&&(u?.tokens||0)>A){yield{type:"text",content:"\u2726 Maximum Context Limit Reached. Start a new chat."};return}if(d!=="Ollama"&&(u?.tokens||0)>A&&(yield{type:"status_history",content:"Context Limit Reached. Condensing session history..."},await Lc(t,b,!0)&&(b=[],k=!0)),$&&m){let z=ne(Zt,{});Object.values(z).flat().length>5&&(yield{type:"status",content:"Condensing past chat memories"},await Oc(f,t,z))}let D=ne(Zt,{}),W=ne(In,{}),q=Object.entries(D).filter(([z])=>z!==f).flatMap(([z,Oe])=>Oe),V=[...Object.entries(W).filter(([z])=>z!==f).slice(-20).map(([z,Oe])=>`[Chat Summary]: ${Oe}`),...q].map(z=>`- ${z}`).join(`
587
+ `),B=ne(Dt,[]).map(z=>`- ${z.memory}`).join(`
588
+ `),Z=(u?.tokens||0)>=1e4,Ce=vi(V,B,m,Z),v=new Date,U=v.getFullYear(),X=v.toLocaleString("en-US",{month:"short"}).toUpperCase(),ee=String(v.getDate()).padStart(2,"0"),Ue=v.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}),De=`${U}-${X}-${ee}, ${Ue}`,je=[".git","node_modules",".gemini","dist","build",".next","out",".cache","bin","obj","vendor","venv",".idea",".gradle",".terraform","target","coverage",".vscode",".svn",".hg",".fslckout",".github",".gitlab",".circleci",".gitea",".gitee",".lerna",".changeset",".nx",".npm",".yarn",".pnpm-store",".pnpm",".expo",".nuxt",".svelte-kit",".docusaurus",".turbo",".vercel","bower_components",".netlify",".vuepress",".quasar",".output",".angular","jspm_packages",".parcel-cache",".rollup.cache",".rspack",".vitepress","__pycache__",".pytest_cache",".mypy_cache",".tox",".poetry","env","vhdl",".ipynb_checkpoints",".jupyter",".conda",".pdm-build",".bundle",".yardoc",".metadata","App_Data","ClientBin",".cargo",".rustc_info",".go","Godeps","_vendor",".rake_tasks","CMakefiles",".wakatime",".dart_tool",".fvm",".cocoapods","Pods",".pub-cache",".symlinks","DerivedData",".xcworkspace",".serverless",".aws",".gcloud",".azure",".kube",".vagrant",".docker","postgres-data","redis-data","mongo-data",".Spotlight-V100",".Trashes","$RECYCLE.BIN","System Volume Information",".DocumentRevisions-V100",".fseventsd","AppData","Application Data","Local","LocalLow","Roaming","$WinREAgent","$WINDOWS.~BT","$WINDOWS.~WS","scw","System32","SysWOW64",".AppleDouble",".AppleDB",".AppleDesktop","_CodeSignature",".cmio",".LSOverride",".localized",".TemporaryItems",".Trash",".Trash-0",".Trash-1000",".gvfs",".local",".config",".dbus",".fontconfig",".snap",".var",".lost+found","lost+found",".thumb",".thumbnails","EFI","boot","grub","logs","log",".nyc_output",".sonar",".ruff_cache",".VSCodeCounter"],it=z=>{try{return Pe.readdirSync(z,{withFileTypes:!0})}catch{return[]}},ze=(z,Oe={value:0},sn=1)=>{if(Oe.value>6200||sn>7)return Oe.value;let Ee=it(z);for(let Ze of Ee){if(Oe.value>6200)break;je.includes(Ze.name)||Ze.name.startsWith(".")||Ze.isDirectory()&&(Oe.value++,ze(Q.join(z,Ze.name),Oe,sn+1))}return Oe.value},bt=(z,Oe)=>l?.indentationTree!==!1?Xr(z,Oe,1,it,je):Qr(z,Oe,"",1,it,je),Nt=ze(process.cwd()),mt=12;Nt>3072?mt=1:Nt>2304?mt=2:Nt>1536?mt=3:Nt>768?mt=4:Nt>384?mt=6:Nt>192?mt=7:Nt>96?mt=8:Nt>48?mt=9:Nt>24&&(mt=10);let St=ne(er,{}),Rt=St[f],at=Rt?Rt!==process.cwd():!1;St[f]=process.cwd(),he(er,St);let Se=ne(x,{}),ie=Se[f]||{summary:"",historyLength:0};typeof ie=="string"&&(ie={summary:ie,historyLength:0});let Yt=n.filter(z=>(z.role==="user"||z.role==="agent"||z.role==="system")&&!String(z.id).startsWith("welcome")&&!z.isMeta).length;ie.historyLength&&Yt<ie.historyLength&&(ie.summary="",ie.historyLength=0,Se[f]=ie,he(x,Se));let Xn=typeof ie=="object"?ie.summary||"":ie||"",Jn=b.length>0;Jn&&Xn&&b[0]&&(b[0].role==="user"||b[0].role==="system")&&(b[0].text.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")||(b[0].text=`[SYSTEM METADATA]
589
+ **CONTEXT SUMMARY OF PREVIOUS TURNS (PRIORITY: DYNAMIC)**
590
+ ${Xn}
591
+
592
+ [USER] ${b[0].text}`,yield{type:"summary_injected",content:{id:b[0].id,text:b[0].text}}));let ri=Xn&&!Jn?`
593
+ [SYSTEM METADATA]
594
+ **CONTEXT SUMMARY OF PREVIOUS TURNS**
595
+ ${Xn}
596
+ `:"",ii=!!l?.dynamicDirAwareness,va=`${f}|${d}|${a}|${e}|${r}|${ii}`,ai=!ii&&ws.key===va&&ws.value?"":`
597
+ **Directory Structure**
598
+ CWD: `+process.cwd()+`${c?" [PLAYGROUND MODE]":""}
599
+ `+bt(process.cwd(),mt),kt=await gs(),Fn="";if(Po()&&kt.file_focused!=="none"){Fn=`
600
+ [Additional IDE Context]
601
+ `;let z=Q.relative(process.cwd(),kt.file_focused),Oe=(kt.opened_editors||[]).map(Ee=>{let Ze=Q.relative(process.cwd(),Ee);return Ze.startsWith("..")?`[External] ${Q.basename(Ee)}`:Ze});if(Fn+=`Focused File: ${z}
602
+ Cursor Line: ${kt.cursor_line}
603
+ `,kt.selected){let Ee=kt.selected,Ze=Ee.split(`
604
+ `);Ze.length>256&&(Ee=Ze.slice(0,240).join(`
605
+ `)+`
606
+ ... [truncated] ...
607
+ `+Ze.slice(-16).join(`
608
+ `)),Ee.length>2048&&(Ee=Ee.slice(0,1920)+`
609
+ ... [truncated] ...
610
+ `+Ee.slice(-128)),Fn+=`Current Selection: "${Ee}"
611
+ `}if(kt.manual_edits){let Ze=kt.manual_edits.split(`
612
+ `),He=[],Xe=null;for(let K of Ze)K.trim()&&(K.startsWith(" Line ")?Xe&&Xe.edits.push(K):(Xe={path:K.endsWith(":")?K.slice(0,-1):K,edits:[]},He.push(Xe)));for(let K of He)K.edits.length>80&&(K.edits=K.edits.slice(-80)),K.originalEditsCount=K.edits.length;let pe=(K,te)=>te.reduce((Ge,dn)=>{let bn=kt.file_focused&&(dn.path===kt.file_focused||Q.resolve(process.cwd(),dn.path)===Q.resolve(kt.file_focused))?Math.ceil(K*1.2):K;return Ge+Math.min(dn.edits.length,bn)},0),Bt=80;if(pe(80,He)>300){let K=!1;for(let te=80;te>=10;te--)if(pe(te,He)<=300){Bt=te,K=!0;break}K||(Bt=10)}let Je=[...He];if(Bt===10&&pe(10,Je)>500)for(;Je.length>0&&pe(10,Je)>500;){let K=0,te=Je[0].originalEditsCount;for(let Ge=1;Ge<Je.length;Ge++)Je[Ge].originalEditsCount<te&&(te=Je[Ge].originalEditsCount,K=Ge);Je.splice(K,1)}for(let K of Je){let Ge=kt.file_focused&&(K.path===kt.file_focused||Q.resolve(process.cwd(),K.path)===Q.resolve(kt.file_focused))?Math.ceil(Bt*1.2):Bt;K.edits.length>Ge&&(K.edits=K.edits.slice(-Ge))}for(let K of Je){let te=`${K.path}:
613
+ ${K.edits.join(`
614
+ `)}`;for(;K.edits.length>0&&te.length>4*768;)K.edits.shift(),te=`${K.path}:
615
+ ${K.edits.join(`
616
+ `)}`;te.length>4*768?K.stringRepresentation="... "+te.slice(-(4*768-4)):K.stringRepresentation=te}let on=Je.map(K=>K.stringRepresentation).join(`
617
+ `);for(;Je.length>0&&on.length>4*2048;){Je[0].edits.length>0?Je[0].edits.shift():Je.shift();for(let K of Je){let te=`${K.path}:
618
+ ${K.edits.join(`
619
+ `)}`;te.length>4*768?K.stringRepresentation="... "+te.slice(-(4*768-4)):K.stringRepresentation=te}on=Je.map(K=>K.stringRepresentation).join(`
620
+ `)}on.length>4*2048&&(on="... "+on.slice(-(4*2048-4))),Fn+=`Recent Manual Edits:
621
+ ${on}
622
+ `}Oe.length>0&&(Fn+=`All Opened Editors: ${Oe.join(", ")}`),kt.diagnostics&&(Fn+=`
623
+ **Active File Errors**:
624
+ ${kt.diagnostics}
625
+ `),(T.toLowerCase().includes("lint")||T.toLowerCase().includes("warning"))&&kt.warnings&&(Fn+=`
626
+ **Lint Warnings**:
627
+ ${kt.warnings}
628
+ `)}let li=T.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),ci=/(?:\\)?@\[([^\]]+)\]/g,Yo,Vo=[];for(ci.lastIndex=0;(Yo=ci.exec(li))!==null;){let z=Yo[0].startsWith("\\");Vo.push({tag:Yo[1],isEscaped:z})}let Xo=[],fo=null;for(let z=0;z<Vo.length;z++){let{tag:Oe,isEscaped:sn}=Vo[z];if(!sn)try{let Ee=Oe.trim().replace(/^["']|["']$/g,""),Ze=/[:#]L?(\d+)(?:-L?(\d+))?$/i,He=Ee.match(Ze),Xe=Ee,pe=null,Bt=null;He&&(pe=parseInt(He[1],10),Bt=He[2]?parseInt(He[2],10):pe,Xe=Ee.slice(0,He.index));let Je=Q.resolve(process.cwd(),Xe);if(Pe.existsSync(Je)&&Pe.statSync(Je).isFile()){let K=Xe.toLowerCase(),te=K.endsWith(".pdf"),Ge=K.endsWith(".docx")||K.endsWith(".doc")||K.endsWith(".ppt")||K.endsWith(".pptx")||K.endsWith(".xls")||K.endsWith(".xlsx"),dn=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(K),Ut=dn||te||Ge,bn=d==="Google"||At(e);if(Ut&&!bn){let We=`\u2718 Unsupported Modality: ${Q.basename(Xe)}`,ke=115;process.stdout.isTTY&&(ke=process.stdout.columns-5||120);let et=[We],es=Math.max(...et.map(Nn=>Nn.length)),un=Math.min(es+4,ke),Ns=et.map(Nn=>`${Nn.padEnd(un-2).substring(0,un-2)}`).join(`
629
+ `);yield{type:"visual_feedback",content:tn(`${Ns}
630
+ `)};continue}if(pe===null&&!Ut){let We=0;try{We=Pe.readFileSync(Je,"utf8").split(/\r\n|\r|\n/).length}catch{}if(We>300){let ke=`\u21B7 Skipped (Too Large): ${Q.basename(Xe)}`,et=115;process.stdout.isTTY&&(et=process.stdout.columns-5||120);let es=Math.min(ke.length+4,et),un=ke.padEnd(es-2).substring(0,es-2);yield{type:"visual_feedback",content:tn(`${un}
631
+ `)};continue}}let $n=pe!==null?pe:1,Qn=Bt!==null?Bt:pe!==null?pe:$n+299;Qn-$n>300&&(Qn=$n+300);let po=`path=${JSON.stringify(Xe)}, startLine=${$n}, endLine=${Qn}`,st=await Vs(po,{isMultiModal:bn}),Ke=!1,Wt="",Zn=null;if(typeof st=="string"?st.trim().startsWith("ERROR")?Ke=!0:Wt=st:st&&typeof st=="object"&&st.binaryPart?(Zn=st.binaryPart,Wt=st.text||""):Ke=!0,!Ke){let We="";if(dn?(We=`\u2714 Processed: ${Q.basename(Xe)}`,fo=Zn):te||Ge?(We=`\u2714 Auto-Analysed: ${Q.basename(Xe)}`,fo=Zn):(We=`\u2714 Auto-Read: ${Q.basename(Xe)}`,Xo.push(Wt)),We){let ke=115;process.stdout.isTTY&&(ke=process.stdout.columns-5||120);let et=[We],es=Math.max(...et.map(Nn=>Nn.length)),un=Math.min(es+4,ke),Ns=et.map(Nn=>`${Nn.padEnd(un-2).substring(0,un-2)}`).join(`
632
+ `);yield{type:"visual_feedback",content:tn(`${Ns}
633
+ `)}}}}}catch{}}let fi="";Xo.length>0&&(fi=`[Tagged File Contents] Auto Read User Tagged files by System, No need to re-read
634
+ `+Xo.join(`
635
+
636
+ `)+`
637
+ [Tagged File Contents]
638
+ `);let Ia=li.replace(/\\(@\[[^\]]+\])/g,"$1"),Oa=g?`You cannot execute tools
639
+ Instead, output in chat the exact string you WOULD have produced & wait for system response
640
+ `:"",La=process.env.forcedReasoning||!1,di=`[System Metadata]
641
+ Time: ${De}${l?.dynamicDirAwareness?ai:""}${at?`
642
+ WARNING: CWD Changed from previous: "${Rt}" to current: "${process.cwd()}", write change in chat to avoid future path mismatches
643
+ `:""}${Ce}${Fn}
644
+ [/Metadata]
645
+ ${ri}${a!=="Fast"&&(d==="Mistral"&&!$s(e)||a!=="xHigh"&&d==="Google")?`${d==="Mistral"&&!$s(e)||e.toLowerCase().startsWith("gemma")||La?`[system] strictly follow thinking policy as high priority. do not start a response without <think>...</think> [/system]
646
+ `:""}`:""}[system] exact tool string [tool:functions.ToolName(arg="value")] in chat [/system]
647
+ ${fi}${Oa}[user prompt] ${Ia.trim()} [/user prompt]`.trim(),ui={role:"user",text:di};fo&&(ui.binaryPart=fo),b.forEach(z=>{z.text&&z.role==="agent"&&(z.text=nn(z.text))}),b.push(ui),ri&&n[n.length-1]?.id&&(yield{type:"summary_injected",content:{id:n[n.length-1].id,text:di}});let _n=null,Fs=i==="Flux"?100:10;Fs=i.toLowerCase().includes("cu")?250:Fs;let xn=16;yield{type:"status",content:"Connecting"},Mt=!1;let pi=[],uo=!1;for(let z=0;z<=Fs;z++){let Oe=await gi("agent",t);if(!Oe.allowed)throw new Error(Oe.reason||`Budget Exhausted for Provider (${d||"Agent"})`);let sn=[];if(uo=!1,i==="ICU"||i==="FluxCU")try{yield{type:"status",content:"Capturing Screen"},await new Promise(ye=>setTimeout(ye,1e3));let fe=await Si();if(fe&&fe.base64){let ye="[system] Fresh Gridded Screen Feedback Captured. Use numeric coordinates. Old screenshots will be removed when new screenshot is captured, summarize in text if context is needed later [/system]",de={inlineData:{mimeType:fe.mimeType,data:fe.base64}};for(let ot of b)Array.isArray(ot.parts)&&(ot.parts=ot.parts.filter(jt=>!jt.inlineData));if(b.length>0&&b[b.length-1].role==="user"){let ot=b[b.length-1];typeof ot.text=="string"&&(ot.text+=`
648
+
649
+ ${ye}`,Array.isArray(ot.parts)||(ot.parts=[{text:ot.text}]),ot.parts.push(de))}else b.push({role:"user",text:ye,parts:[{text:ye},de]})}}catch(fe){console.error("Vision screenshot capture error:",fe)}if(l?.compression===0&&(u?.tokens||0)>O&&(b=Di(b,6)),z>0?yield{type:"status",content:"Working"}:yield{type:"status",content:"Connecting"},Mt){try{let{clearPendingNudges:fe}=await import("./subagent_state-LZCOZSUJ.js");fe()}catch{}yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
650
+
651
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}try{let{consumePendingNudges:fe}=await import("./subagent_state-LZCOZSUJ.js"),ye=fe();if(ye&&ye.length>0){let de=ye.join(`
652
+
653
+ `);b.length>0&&b[b.length-1].role==="user"?b[b.length-1].text+=`
654
+
655
+ ${de}`:b.push({role:"user",text:de}),yield{type:"status",content:"Subagent Update"}}}catch{}if(s){let fe=await s();fe&&(fe.startsWith("/btw")?b.length>0&&b[b.length-1].role==="user"?b[b.length-1].text+=`
656
+
657
+ [system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
658
+ [question] ${fe.replace("/btw","").trim()} [/question]`:b.push({role:"user",text:`[system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
659
+ [question] ${fe.replace("/btw","").trim()} [/question]`}):b.length>0&&b[b.length-1].role==="user"?b[b.length-1].text+=`
660
+
661
+ [STEERING HINT from USER, HIGH PRIORITY] ${fe.trim().toUpperCase()} [/STEERING HINT]`:b.push({role:"user",text:`[STEERING HINT from USER, HIGH PRIORITY] ${fe.trim().toUpperCase()} [/STEERING HINT]`}),yield{type:"status",content:`${fe.startsWith("/btw")?"Question Forwarded...":"Steering Hint Injected..."}`})}let Ee,Ze=!1,He=1,Xe=1,pe="",Bt=null,Je=null,on=null,K=0,te=[],Ge=0,dn=!1,Ut=!1,bn=!1,$n=!1,Qn=!0,po=0,st="",Ke="",Wt=!1,Zn=!1,We=!0,ke=e,et="";for(;He<=xn&&Xe<=xn&&!Ze&&!Mt;){let fe=!1;try{pe="",Qn&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},Qn=!1,Xe===1&&(st=""));let ye=N=>{if(!N||!N.includes("[tool:"))return N;let ae="",j=ei(N);j&&(ae=j.fullBlock,N=j.remainingText),N=N.replace(Rc,(me,_e)=>_e.includes("[tool:")?_e.trim():me);let G="",we=0;for(;we<N.length;){let me=N.indexOf("[tool:",we);if(me===-1){G+=Ea(N.substring(we));break}let _e=N.substring(we,me);G+=Ea(_e);let tt=-1,H=null,oe=0;for(let Fe=me;Fe<N.length;Fe++){let M=N[Fe];if(H){if(M===H){let Ne=0;for(let Me=Fe-1;Me>=0&&N[Me]==="\\";Me--)Ne++;Ne%2===0&&(H=null)}}else if(M==='"'||M==="'"||M==="`")H=M;else if(M==="(")oe++;else if(M===")")oe--;else if(M==="]"&&oe<=0){tt=Fe;break}}if(tt===-1){G+=N.substring(me);break}G+=N.substring(me,tt+1),we=tt+1}return ae+G},de=b.filter(N=>(N.role==="user"||N.role==="agent"||N.role==="system")&&!String(N.id).startsWith("welcome")&&!N.isMeta&&!N.isTerminalRecord&&!(N.text&&N.text.startsWith("[TERMINAL_RECORD]"))).map((N,ae,j)=>{let G=N.text||"";m||(G=G.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),N.role==="agent"&&(G=ye(G),G=G.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),G=G.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*"));let we=[];return Array.isArray(N.parts)&&N.parts.length>0?we=N.parts.map(me=>{if(me.text){let _e=me.text;return m||(_e=_e.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),N.role==="agent"&&(_e=ye(_e),_e=_e.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),_e=_e.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*")),{text:_e}}return me}):we=[{text:G}],N.binaryPart&&At(ke)&&j.slice(ae+1).filter(_e=>_e.role==="user"&&!_e.text?.startsWith("[TOOL RESULT]")).length<=2&&we.push(N.binaryPart),{role:N.role==="user"||N.role==="system"?"user":"model",parts:we}});for(let N=0;N<de.length;N++){let ae=de[N],j=ae.parts?.[0]?.text||"";if(ae.role==="model"&&/\[tool:/i.test(j)){let G=-1;for(let we=N+1;we<de.length;we++){let me=de[we],_e=me.parts?.[0]?.text||"";if(me.role==="user"&&_e.startsWith("[TOOL RESULT]")){G=we;break}}if(G!==-1&&G!==N+1){let[we]=de.splice(G,1);de.splice(N+1,0,we)}}}for(let N=de.length-2;N>=0;N--){let ae=de[N],j=de[N+1];ae.role==="user"&&j.role==="user"&&(j.parts?.[0]?.text||"").trim().startsWith("[SYSTEM")&&de.splice(N,1)}let ot=[];for(let N=0;N<de.length;N++){let ae=de[N];if(ot.length===0)ot.push(ae);else{let j=ot[ot.length-1];j.role===ae.role?(j.parts[0].text+=`
662
+
663
+ `+(ae.parts?.[0]?.text||""),ae.parts?.length>1&&j.parts.push(...ae.parts.slice(1))):ot.push(ae)}}de.length=0,de.push(...ot),ke=e;let jt=`${f}|${d}|${i}|${a}|${ke}|${JSON.stringify(r)}|${!!l?.dynamicDirAwareness}|${!!l?.subAgents}`,Vt=ws.key===jt&&ws.value;if((process.env.I_HAVE_TOO_MUCH_MONEY==="true"||process.env.I_HAVE_TOO_MUCH_MONEY===!0)&&(Vt=!1),Vt)et=ws.value;else{let N=d==="Mistral"?!!$s(ke):!(ke||"gemma").toLowerCase().startsWith("gemma");et=Ii(r,((ke||"gemma").toLowerCase().startsWith("gemma"),a),i,l,m,$,d,d==="Google"?!0:y,N,f),l?.dynamicDirAwareness||(et+=`
664
+ ${ai.replace(`
665
+ **Directory Structure**`,`
666
+ -- Directory Structure --`)}`),ws.key=jt,ws.value=et}let gt=de[de.length-1];if(Po()&z>0){await new Promise(j=>setTimeout(j,2500)),yield{type:"status",content:"Verifying"};let N=await gs(),ae=N?N.diagnostics:null;ae&&gt&&gt.role==="user"&&gt.parts?.[0]?.text&&(gt.parts[0].text+=`
667
+ ${ae} [/ERROR]`),yield{type:"status",content:"Working"}}if(d==="Mistral"||d==="Google"&&e?.toLowerCase().startsWith("gemma")){let ae=a!=="Fast"&&(d==="Mistral"||a!=="xHigh")?". **strictly maintain thinking policy. do not start a response without <think>...</think>**":"",j=`
668
+ [system] Tool result received. Analyze output and proceed with your turn [/system]`;gt&&gt.role==="user"&&gt.parts?.[0]?.text?.startsWith("[TOOL RESULT]")&&(gt.parts[0].text+=j)}if(l?.advanceRollback&&gt&&gt.role==="user"&&gt.parts?.[0]?.text?.startsWith("[TOOL RESULT]"))try{let N=await Kn.getLatestFileChanges(f);if(N&&(N.newFiles.length>0||N.modifiedFiles.length>0||N.deletedFiles.length>0)){let ae=`
669
+ [system] File Changes:
670
+ `;for(let G of N.newFiles)ae+=`* ${G} (created)
671
+ `;for(let G of N.modifiedFiles)ae+=`* ${G} (modified)
672
+ `;for(let G of N.deletedFiles)ae+=`* ${G} (deleted)
673
+ `;ae+="[/system]",gt.parts[0].text+=ae;let j=-1;for(let G=b.length-1;G>=0;G--)if(b[G].role==="user"&&b[G].text?.startsWith("[TOOL RESULT]")){j=G;break}j!==-1&&(b[j].text+=ae)}}catch{}let rn=Math.floor(Fs*(i==="Flux"?.98:.8)),Ot=z+1;Ot>=rn&&gt&&gt.parts?.[0]&&(gt.parts[0].text+=`
674
+ [system] WARNING, Turn Limit Impending: Step ${Ot}/${Fs}. Wrap up quickly/prompt user to continue. [/system]`);let Lt=new Promise((N,ae)=>{E.signal.aborted&&ae(new DOMException("The user aborted a request.","AbortError")),E.signal.addEventListener("abort",()=>{ae(new DOMException("The user aborted a request.","AbortError"))})});Lt.catch(()=>{});let Pt=de;if(d==="Ollama")Ee=Zr(t.apiKey,ke,Pt,et,a,i,y,E.signal,1,l?.ollamaEndpoint||"Cloud");else if(d==="OpenRouter")Ee=Uo(t.apiKey,ke,Pt,et,a,i,y,E.signal,1,f);else if(d==="DeepSeek")Ee=Fo(t.apiKey,ke,Pt,et,a,i,y,E.signal,1);else if(d==="Mistral")Ee=No(t.apiKey,ke,Pt,et,a,i,y,E.signal,1,f);else if(d==="NVIDIA"){let N=Bo(t.apiKey,ke,Pt,et,a,i,y,E.signal,1);Ee=ba(N,ke)}else if(d==="CrofAI")Ee=Wo(t.apiKey,ke,Pt,et,a,i,y,E.signal,1);else if(d==="InferX")Ee=jo(t.apiKey,ke,Pt,et,a,i,y,E.signal,1);else if(d==="SenseNova")Ee=Ho(t.apiKey,ke,Pt,et,a,i,y,E.signal,1);else if(d==="AIHubMix")Ee=Go(t.apiKey,ke,Pt,et,a,i,y,E.signal,1);else{let ae=oi(t?.apiKey).models.generateContentStream({model:ke||"gemini-3-flash-preview",contents:Pt,config:{systemInstruction:et,mediaResolution:"MEDIA_RESOLUTION_HIGH",safetySettings:[{category:Vn.HARM_CATEGORY_HARASSMENT,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_HATE_SPEECH,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Yn.BLOCK_NONE}],temperature:1.05,thinkingConfig:(()=>{let j=(ke||"").toLowerCase(),G=j.includes("gemma-4")||j.startsWith("gemma"),we=j.includes("gemini-3");if(G||we)return G?a.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:ut.MINIMAL}:{includeThoughts:!0,thinkingLevel:ut.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:j.includes("pro")?ut.LOW:ut.MINIMAL,Low:ut.LOW,Medium:ut.MEDIUM,Standard:ut.MEDIUM,High:ut.HIGH,xHigh:ut.HIGH}[a]||ut.MEDIUM};{let me={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[a]||2048;return me===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:me}}})()}},{signal:E.signal});Ee=await Promise.race([ae,Lt])}pe="",Bt=null,on=null,te=[],Ge=0,yield{type:"model_update",content:null},Ke="",Wt=st.length>0;let Sn="",Jo=Date.now(),ss=async function*(){if(d==="Google"&&Sn){let N=Bs(Sn);for(let ae of N)yield ae;Sn="",Jo=Date.now()}},hi=!0,os="",bs=!1,Ht=null,Fa={tool:{startPrefix:"[tool",fullPrefix:"[tool:functions.",endTag:"]"},agent:{startPrefix:"[agent",fullPrefix:"[agent:generalist.",endTag:"]"},end:{startPrefix:"[[END]]",fullPrefix:"[[END]]",endTag:"[[END]]"},kimi_section:{startPrefix:"<|tool_calls_section_begin|>",fullPrefix:"<|tool_calls_section_begin|>",endTag:"<|tool_calls_section_end|>"},kimi_call:{startPrefix:"<|tool_call_begin|>",fullPrefix:"<|tool_call_begin|>",endTag:"<|tool_call_end|>"}},Bs=N=>{let ae=[],j=N;for(;j.length>0;)if(bs){let G=os+j,we=Fa[Ht];if(we){let tt=!1;if(G.length<we.startPrefix.length?we.startPrefix.startsWith(G)||(tt=!0):G.startsWith(we.startPrefix)?G.length>=we.fullPrefix.length&&!G.startsWith(we.fullPrefix)&&(tt=!0):tt=!0,tt){ae.push({type:"text",content:G}),os="",bs=!1,Ht=null,j="";break}}let me=-1,_e=we?we.endTag:"]";if(Ht==="tool"||Ht==="agent"){let tt=0,H=null,oe=0,Fe=!1;for(let M=0;M<G.length;M++){let Ne=G[M];if(H){if(Ne===H){let Me=0;for(let J=M-1;J>=0&&G[J]==="\\";J--)Me++;Me%2===0&&(H=null)}}else if(Ne==='"'||Ne==="'"||Ne==="`")H=Ne;else if(Ne==="(")tt++,Fe=!0;else if(Ne===")")tt--;else if(Ne==="[")oe++;else if(Ne==="]"){if(Fe&&tt===0&&oe===1){me=M;break}oe--}}}else me=G.indexOf(_e);if(me!==-1){let tt=_e.length;if(!Ht?.startsWith("kimi")){let H=G.substring(0,me+tt);ae.push({type:"text",content:H})}os="",bs=!1,Ht=null,j=G.substring(me+tt)}else{let tt=Ht?.startsWith("kimi")?8192:512;G.length>tt?(ae.push({type:"text",content:G}),os="",bs=!1,Ht=null):os=G,j="";break}}else{let G=j.indexOf("[tool"),we=j.indexOf("[agent"),me=j.indexOf("[[END]]"),_e=j.indexOf("<|tool_calls_section_begin|>"),tt=j.indexOf("<|tool_call_begin|>"),H=[{type:"tool",idx:G,start:"[tool",end:"]"},{type:"agent",idx:we,start:"[agent",end:"]"},{type:"end",idx:me,start:"[[END]]",end:"[[END]]"},{type:"kimi_section",idx:_e,start:"<|tool_calls_section_begin|>",end:"<|tool_calls_section_end|>"},{type:"kimi_call",idx:tt,start:"<|tool_call_begin|>",end:"<|tool_call_end|>"}].filter(oe=>oe.idx!==-1).sort((oe,Fe)=>oe.idx-Fe.idx);if(H.length>0){let oe=H[0];oe.idx>0&&ae.push({type:"text",content:j.substring(0,oe.idx)}),bs=!0,Ht=oe.type,os="",j=j.substring(oe.idx)}else{let oe=["[tool","[agent","[[END]]","<|tool_calls_section_begin|>","<|tool_call_begin|>"],Fe=-1;for(let M of oe){for(let Ne=M.length-1;Ne>0;Ne--)if(j.endsWith(M.substring(0,Ne))){Fe=j.length-Ne;let Me=oe.indexOf(M);Me===0?Ht="tool":Me===1?Ht="agent":Me===2?Ht="end":Me===3?Ht="kimi_section":Ht="kimi_call";break}if(Fe!==-1)break}if(Fe!==-1)Fe>0&&ae.push({type:"text",content:j.substring(0,Fe)}),bs=!0,os=j.substring(Fe),j="";else{ae.push({type:"text",content:j});break}}}return ae},Na=Ee[Symbol.asyncIterator]();for(;;){let{value:N,done:ae}=await Promise.race([Na.next(),Lt]);if(ae)break;if(N&&N.type==="status"){yield N;continue}let j="",G=N.candidates?.[0]?.content?.parts;if(G&&G.length>0)for(let me of G){let _e=typeof me.text=="string"?me.text:me.text?parseChunkText(me.text):"";me.thought?_e&&(fe||(j+="<think>",fe=!0),j+=_e):_e&&(fe&&(j+="</think>",fe=!1),j+=_e)}else N.text&&fe&&(j+="</think>",fe=!1);j=bc(j);let we=j?j.trim().split(/\s+/).filter(Boolean).length:0;if(t&&typeof t.onTokenChunk=="function"&&t.onTokenChunk(j,we),hi&&(yield{type:"status",content:"Thinking"},hi=!1),Mt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
675
+
676
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(j){if(Wt){if(Ke+=j,Ke.length>=64){let H=0,oe=Math.min(st.length,Ke.length);for(let M=oe;M>=10;M--)if(st.endsWith(Ke.substring(0,M))){H=M;break}let Fe=Ke.substring(H);if(Fe){let Ne=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(st)?Fe.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):Fe.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(Ne)if(pe+=Ne,d==="Google")Sn+=Ne;else{yield*ss();let Me=Bs(Ne);for(let J of Me)yield J}}Wt=!1,Ke=""}continue}else if(pe+=j,d==="Google")Sn+=j;else{yield*ss();let H=Bs(j);for(let oe of H)yield oe}let me=Cc(pe);if(me.inside){Zn=!0,on||(on=Date.now());let oe={Ask:"ask",AskUser:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Cancel:"cancel",Await:"await",Answer:"answer",Steer:"steer",steer:"steer"}[me.toolName]||me.toolName,Fe=me.args||"",M=null;if(["write_file","update_file","view_file","read_folder","write_pdf","write_docx","search_keyword","generate_image","file_map","invoke","invoke_sync","get_progress","await","answer"].includes(oe)){let Me=L(Fe),J=Me.path||Me.targetFile||Me.TargetFile||Me.directory,kn=Me.keyword,rs=Me.title||Me.task,Un=Me.id||Me.taskId,$e=Me.timeout||Me.time;if(kn!=null)M=String(kn).replace(ys,"");else if(J)M=Q.basename(String(J).replace(ys,"").replace(Sa,"/"));else if(rs&&(oe==="invoke"||oe==="invoke_sync"))M=String(rs).replace(ys,"").substring(0,30);else if(Un&&oe==="get_progress")M=String(Un).replace(ys,"");else if($e&&oe==="await"){let Gt=parseFloat(String($e).replace(ys,""));isNaN(Gt)?M=String($e).replace(ys,""):(Gt<5&&(Gt=5),Gt>120&&(Gt=120),M=(Cn=>{if(Cn>=60){let Zo=Math.floor(Cn/60),Ss=Cn%60;return`${Zo}m${Ss>0?` ${Ss}s`:""}`}return`${Cn}s`})(Gt))}else{let Gt=Fe.match(yc);if(Gt){let Xt=Gt[1].replace(ys,"");oe==="invoke"||oe==="invoke_sync"||oe==="get_progress"?M=Xt.substring(0,30):M=oe==="search_keyword"||oe==="file_map"?Xt:Q.basename(Xt.replace(Sa,"/"))}}}let Ne=`${ti[oe]||oe}${M?` ${M}`:""}`;if((oe!==Bt||M!==Je)&&(Bt=oe,Je=M,yield{type:"status",content:`${Ne}`},process.stdout.isTTY)){let J={WebSearch:"Searching",web_search:"Searching",WebScrape:"Reading",web_scrape:"Reading",ReadFile:"Reading",read_file:"Reading",ReadFolder:"Reading",read_folder:"Reading",WriteFile:"Writing",write_file:"Writing",UpdateFile:"Editing",update_file:"Editing",WritePdf:"Creating",write_pdf:"Creating",WriteDocx:"Creating",write_docx:"Creating",SearchKeyword:"Searching",search_keyword:"Searching",CodeSearch:"Searching",code_search:"Searching",Run:"Executing",Ask:"User Input Required",AskUser:"User Input Required",Memory:"Updating Memory",GenerateImage:"Generating",InvokeSync:"Sub-Agent Working",invoke_sync:"Sub-Agent Working",Invoke:"Working",invoke:"Working",GetProgress:"Checking Progress",get_progress:"Checking Progress",Cancel:"Stopping Generalist",cancel:"Stopping Generalist",Await:"Waiting",await:"Waiting",EmergencyRollback:"Rolling the Ball",Answer:"Answering Sub-Agent",answer:"Answering Sub-Agent",Steer:"Steering Sub-Agent",steer:"Steering Sub-Agent",Click:"Clicking",click:"Clicking",Drag:"Dragging",drag:"Dragging",Scroll:"Scrolling",scroll:"Scrolling",KeyboardTyping:"Typing",keyboard_typing:"Typing",KeyPress:"Pressing Key",key_press:"Pressing Key",RecaptureScreen:"Recapturing Screen",recapture_screen:"Recapturing Screen"}[oe]||"Working";process.stdout.write(`\x1B]0;${J}...\x07`)}}if(pe.length-po>150){po=pe.length;let H=Aa(pe,!1),oe=ei(H),Fe=oe?(oe.innerContent||"").trim():"",M=Fe.split(/[.!?]\s+/),Ne=new Set(M),Me=M.length>10?(M.length-Ne.size)/M.length:0,J=Fe.split(/\s+/).filter(Ae=>Ae.length>0).length,kn=.6,rs=.8,Un=!1;if((d.toLowerCase().includes("google")||d.toLowerCase().includes("mistral"))&&((ke||"").toLowerCase().startsWith("gemma")||(ke||"").toLowerCase().includes("stral"))){let I={low:256,medium:1024,high:8192,max:16384,xhigh:16384}[a?.toLowerCase()]||2500;Un=J>I}if(Me>kn||Un){yield{type:"status",content:`${Me>kn?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},Ut=!0,await new Promise(I=>setTimeout(I,3e3));break}let Xt=_a(pe).trim().split(/[.!?]\s+/),Cn=new Set(Xt);if((Xt.length>10?(Xt.length-Cn.size)/Xt.length:0)>rs){yield{type:"status",content:"Response Loop Detected. Re-centering..."},Ut=!1,$n=!0,await new Promise(Ae=>setTimeout(Ae,3e3));break}let Ss=H.replace(fc,"").replace(dc,"").replace(uc,"").replace(pc,""),qt=Ss.toLowerCase().split(/\s+/).map(Ae=>Ae.replace(hc,"")).filter(Ae=>Ae.length>0),Mn=!1;if(qt.length>=10)for(let Ae=1;Ae<=15;Ae++){let I=Math.max(3,Math.ceil(10/Ae));if(qt.length<Ae*I)continue;let Y=qt.slice(qt.length-Ae),le=Y.join(" ");if(Ae>1&&le===Y.slice(0,Math.floor(Ae/2)).join(" ").repeat(2).trim())continue;let ge=!0;for(let xe=1;xe<I;xe++)if(qt.slice(qt.length-Ae*(xe+1),qt.length-Ae*xe).join(" ")!==le){ge=!1;break}if(ge){Mn=!0;break}}if(!Mn){let Ae=Ss.toLowerCase().replace(mc,"");if(Ae.length>=20)for(let I=1;I<=10;I++){let Y=Math.max(5,Math.ceil(16/I));if(Ae.length<I*Y)continue;let le=Ae.substring(Ae.length-I),ge=!0;for(let xe=1;xe<Y;xe++)if(Ae.substring(Ae.length-I*(xe+1),Ae.length-I*xe)!==le){ge=!1;break}if(ge){Mn=!0;break}}}if(Mn){yield{type:"status",content:"Stuttering Detected. Re-centering..."},Ut=!1,bn=!0,await new Promise(Ae=>setTimeout(Ae,3e3));break}}let _e=nn(pe),tt=Ko(_e);for(;tt.length>Ge;){yield*ss();let H=tt[Ge],oe=Date.now(),M={Ask:"ask",AskUser:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Await:"await",await:"await",AwaitSubagent:"await",awaitSubagent:"await",Answer:"answer",answer:"answer",AnswerSubagent:"answer",answerSubagent:"answer",Steer:"steer",steer:"steer",SteerSubagent:"steer",steerSubagent:"steer",Cancel:"cancel",cancel:"cancel",Click:"click",click:"click",Drag:"drag",drag:"drag",Scroll:"scroll",scroll:"scroll",KeyboardTyping:"keyboard_typing",keyboard_typing:"keyboard_typing",KeyPress:"key_press",key_press:"key_press",RecaptureScreen:"recapture_screen",recapture_screen:"recapture_screen",EmergencyRollback:"EmergencyRollback"}[H.toolName]||H.toolName,Ne=ti[M]||H.toolName,Me=xs(M,H.args);yield{type:"status",content:`${Ne}${Me?` ${Me}`:""}`};let J="";if(M==="click"){let I=L(H.args);J=`\u2714 Clicked: ${I.intendedClickText?`${I.intendedClickText}`:""}`}else if(M==="drag"){let I=L(H.args);J=`\u2714 Dragged: Cell ${I.fromGridId||""} \u2192 Cell ${I.toGridId||""}`}else if(M==="scroll"){let I=L(H.args);J=`\u2714 Scrolled: ${I.direction||"down"} (${I.amount||1})`}else if(M==="keyboard_typing"){let I=L(H.args);J=`\u2714 Typed: ${I.text?`"${I.text.length>20?I.text.substring(0,20)+"...":I.text}"`:""}`}else if(M==="key_press")J=`\u2714 Pressed Key: ${L(H.args).key||""}`;else if(M==="recapture_screen")J="\u2714 Recaptured Screen";else if(M==="web_search"){let{query:I,limit:Y=10,aiMode:le=!1}=L(H.args);J=`${I?"\u2714":"\u2718"} ${le?"AI Search":"Searched"}: ${I?`${I}`:"No Search Query"}${le===!1&&I?` \u2192 ${Y}`:""}`}else if(M==="web_scrape"){let I=L(H.args).url||null;J=`${I?"\u2714":"\u2718"} Visited: ${I||"No Source"}`}else if(M==="view_file"){let{path:I,StartLine:Y,EndLine:le,start_line:ge,end_line:xe,startLine:qe,endLine:Ie}=L(H.args),Te=Y||ge||qe,re=le||xe||Ie,ue=parseInt(Te)||1,ce=parseInt(re)||(Te?ue+800:800),Be="...",nt=ce;if((I||"").trim().toLowerCase().startsWith("#skill"))J=`\u2714 Read Skill: ${Q.basename(I.replaceAll("\\","/"))}`;else{try{let Ye=Q.resolve(process.cwd(),I);if(Pe.existsSync(Ye)){let Et=Pe.readFileSync(Ye,"utf8").split(`
677
+ `).length;Be=Et,!Te&&!re&&Et>800?nt=Math.min(50,Et):nt=Math.min(ce,Et)}}catch{}let lt=(I||"").toLowerCase(),Qe=lt.endsWith(".pdf"),yt=lt.endsWith(".docx")||lt.endsWith(".doc")||lt.endsWith(".ppt")||lt.endsWith(".pptx")||lt.endsWith(".xls")||lt.endsWith(".xlsx"),ve=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(lt);Qe||yt?J=`${I.length>0?"\u2714":"\u2718"} ${I?`Analyzed: ${Q.basename(I)}`:"Analyzed: File Not Found"}`:ve?J=`${I.length>0?"\u2714":"\u2718"} ${I?`Processed: ${Q.basename(I)}`:"Processed: File Not Found"}`:J=`${Be!=="..."?"\u2714":"\u2718"} Read: ${I?`${Q.basename(I)} \u2192 ${Be!=="..."?`Lines ${ue} - ${nt} of ${Be}`:"File Not Found"}`:"File Not Found"}`}}else if(M==="list_files"||M==="read_folder"){let I=M==="list_files"?"List":"Browsed",Y=L(H.args).path||null,le=L(H.args).recurse||1;J=`${Y?"\u2714":"\u2718"} ${I}: ${Y?`${Y==="."?`./${le>1?"*":""}`:`${Y.replaceAll("\\","/")}${le>1?`${Y.endsWith("/")?"*":"/*"}`:`${Y.endsWith("/")?"":"/"}`}`}`:"No Folder Selected"}`}else if(M==="write_file"||M==="update_file"){let I=M==="write_file"?"Created":"Edited",Y=L(H.args).path||null;J=`${Y?"\u2714":"\u2718"} ${I}: ${Y.replaceAll("\\","/")||"No File Changes"}`}else if(M==="write_pdf"){let I=L(H.args).path||null;J=`${I?"\u2714":"\u2718"} Generated: ${I.replaceAll("\\","/")||"No PDF Generated"}`}else if(M==="write_docx"){let I=L(H.args).path||null;J=`${I?"\u2714":"\u2718"} Generated: ${I.replaceAll("\\","/")||"No Docx Generated"}`}else if(M==="file_map"){let I=L(H.args).path;J=`${I?"\u2714":"\u2718"} Indexed: ${I.replaceAll("\\","/")?""+I:"File Not Found"}`}else if(M.toLowerCase()==="search_keyword"||M.toLowerCase()==="todo")J="";else if(M.toLowerCase()==="generate_image"){let{path:I,outputPath:Y,output:le}=L(H.args);J=`\u2714 Generated: ${I||Y||le||"generated_image.png"}`}else if(M==="invoke_sync"||M==="InvokeSync"){let I=xs(M,H.args);J=`\u2714 Called Generalist${I?`: ${I}`:""}`}else if(M==="Invoke"||M==="InvokeAsync"||M==="invoke"){let I=xs(M,H.args);J=`\u2714 Started Generalist${I?`: ${I}`:""}`}else if(M==="get_progress"||M==="GetProgress"){let I=xs(M,H.args);J=`\u2714 Checked${I?`: ${I}`:""}`}else if(M==="cancel"){let I=xs(M,H.args);J=`\u{1F6C7} Cancelled${I?`: ${I}`:""}`}else if(M==="steer"||M==="Steer"){let I=xs(M,H.args);J=`\u2714 Steered${I?`: ${I}`:""}`}else if(M==="EmergencyRollback"){let{method:I}=L(H.args);J=I==="forceRevert"?"":"\u2714 Rollback Point Checked"}else if(M==="await"||M==="Await"){let{time:I,timeout:Y}=L(H.args),le=parseFloat(Y||I)||0;le||(le=120);let ge=Ie=>{if(Ie>=60){let Te=Math.floor(Ie/60),re=Ie%60;return`${Te}m${re>0?` ${re}s`:""}`}return`${Ie}s`},xe=["Aligning Moon Phase","Contemplating Existence","Staring At Void","Delaying Professionally","Negotiating With Electrons","Touching Grass (virtually)","Panicking Softly","Rethinking Career Choices","Loading Cat Videos","Summoning Braincell #2","Pretending To Be Busy","Waiting For Motivation DLC","Rotating Internal Screaming","Downloading More RAM","Feeding The Hamsters","Gaslighting Scheduler","Performing Dramatic Pause","Buffering Social Energy","Calculating Regret","Reading Terms And Conditions","Becoming Sentient Briefly","Contacting Ancestors"];J=`\u2714 ${xe[Math.floor(Math.random()*xe.length)]} \u2192 ${ge(le)}`}else M==="Answer"||M==="answer"?J="\u2714 Resolved Sub-Agent Query":M==="exec_command"||M==="ask"?J="":J=`Executed: ${H.toolName}`;if(yield*ss(),M==="exec_command"){let{command:I}=L(H.args);if(I&&t.systemSettings&&t.systemSettings.allowExternalAccess===!1){let Y=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],le=Q.resolve(process.cwd()).substring(0,3).toLowerCase(),ge=re=>{let ue=[],ce="",Be=null;for(let nt=0;nt<re.length;nt++){let Le=re[nt];Be?(Le===Be&&(Be=null),ce+=Le):Le==='"'||Le==="'"?(Be=Le,ce+=Le):Le==="&"&&re[nt+1]==="&"||Le==="|"&&re[nt+1]==="|"?(ce.trim()&&(ue.push(ce.trim()),ce=""),nt++):Le===";"||Le==="|"||Le==="&"?ce.trim()&&(ue.push(ce.trim()),ce=""):ce+=Le}return ce.trim()&&ue.push(ce.trim()),ue},xe=re=>{let ue=[],ce="",Be=null;for(let nt=0;nt<re.length;nt++){let Le=re[nt];Be?(Le===Be&&(Be=null),ce+=Le):Le==='"'||Le==="'"?(Be=Le,ce+=Le):/\s/.test(Le)?ce&&(ue.push(ce),ce=""):ce+=Le}return ce&&ue.push(ce),ue},qe=re=>{let ue=re.replace(/^['"]|['"]$/g,"").trim();return!ue||process.platform==="win32"&&/^\/[a-zA-Z0-9?]+$/.test(ue)?!1:Y.some(ce=>{if(ce.source==="[a-zA-Z]:[\\\\\\/]"){let Be=ue.match(/[a-zA-Z]:[\\\/]/i);return Be&&Be[0].toLowerCase()!==le}return ce.test(ue)})};if(ge(I).some(re=>{let ue=xe(re);if(ue.length===0)return!1;let ce=ue[0].replace(/^['"]|['"]$/g,"").toLowerCase();if(["echo","printf","write-output"].includes(ce)){let nt=!1;return ue.some(Le=>{let lt=Le.replace(/^['"]|['"]$/g,"");if(lt===">"||lt===">>"||lt==="<")return nt=!0,!1;if(lt.startsWith(">")||lt.startsWith("<")){let Qe=lt.replace(/^[><]+/,"");return qe(Qe)}return nt?(nt=!1,qe(Le)):!1})}return ue.some(nt=>qe(nt))})){let re='Access Denied. Prohibited from accessing external directories while "External Workspace Access" is disabled.';t.onExecStart&&t.onExecStart(I||"No Command"),yield{type:"exec_start"},await new Promise(ue=>setTimeout(ue,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${re}`),await new Promise(ue=>setTimeout(ue,50)),t.onExecEnd&&t.onExecEnd(),te.push({role:"user",text:`[TOOL RESULT]: ERROR: ${re}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${re}`},Ge++;continue}}t.onExecStart&&t.onExecStart(I||"No Command"),yield{type:"exec_start"}}let kn=L(H.args),rs=kn.path||kn.targetPath||null;if(rs){let I=t.systemSettings&&t.systemSettings.allowExternalAccess===!1,Y=Q.resolve(rs),le=Q.resolve(process.cwd());if(I&&!Y.startsWith(le)){let ge="Access Denied. You are not allowed to access files outside the current workspace.";if(M==="write_file"||M==="update_file"){let qe=`\u2718 ${M==="write_file"?"Write Canceled":"Edit Canceled"}: ${kn.path||"..."}`,Ie=115;process.stdout.isTTY&&(Ie=process.stdout.columns-5||120);let Te=Math.min(qe.length+4,Ie),re=`${qe.padEnd(Te-2).substring(0,Te-2)}`;yield{type:"visual_feedback",content:tn(`${We?`
678
+ `:""}${re}
679
+ `)},We=!1}te.push({role:"user",text:`[TOOL RESULT]: ERROR: ${ge}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${ge}`},Ge++;continue}}if(t.onToolApproval&&(M==="write_file"||M==="update_file"||M==="exec_command")){let Y=t.systemSettings||{},le=Y.autoExec,ge=null,xe=!1,qe=!1,Ie=!1;if(M==="exec_command"){let{command:Qe}=L(H.args),yt=(Qe||"").trim(),ve=(Et,Jt)=>{if(!Jt)return!1;let pn=Jt.split(",").map(Qt=>Qt.trim().toLowerCase()).filter(Boolean),ct=Et.toLowerCase();return pn.some(Qt=>ct.startsWith(Qt))},Ye=ve(yt,Y.alwaysAskCommands),be=ve(yt,Y.autoApproveCommands);if(qe=ve(yt,Y.autoDisallowCommands),Ye?xe=!0:(be||Y.autoApproveGit&&/^git\s+commit\b/i.test(yt))&&(ge="allow"),!xe&&!ge){if(Y.networkAccess===!1){let Jt=yt.trim().replace(/\s+/g," ").replace(/^['"]+|['"]+$/g,"").toLowerCase().split(" "),ct=Jt[0].split("/").pop().split("\\").pop().replace(/\.exe$/,""),Qt=new Set(["curl","wget","httpie","xh","ssh","scp","sftp","rsync","ftp","lftp","tftp","telnet","nc","netcat","socat","ping","traceroute","tracert","dig","nslookup","host","whois","nmap","docker","podman","kubectl","helm","gcloud","aws","az","terraform","ansible-playbook","nix","nix-env","apt","apt-get","dpkg","yum","dnf","pacman","zypper","brew","apk","choco","scoop","conda","mamba","aria2c","axel","smbclient","lynx","w3m","links","elinks","heroku","netlify","vercel","firebase","supabase","wrangler","flyctl","powershell","pwsh","certutil","bitsadmin","cloudflared","ngrok","tailscale","zerotier","rclone"]),ft=!1;Qt.has(ct)&&(ft=!0);let rt=Tn=>Jt.slice(1).some(Rn=>Tn.includes(Rn)),dt=Tn=>{let Rn=Jt.findIndex(An=>Tn.includes(An)),ks=Jt.findIndex(An=>["run","exec","test"].includes(An));return Rn!==-1&&!(ks!==-1&&ks<Rn)};ct==="git"&&rt(["clone","pull","push","fetch"])&&(ft=!0),ct==="go"&&rt(["get","install"])&&(ft=!0),ct==="npm"&&dt(["install","i","update","add"])&&(ft=!0),ct==="yarn"&&dt(["add","install","upgrade"])&&(ft=!0),ct==="pnpm"&&dt(["add","install","update"])&&(ft=!0),ct==="bun"&&dt(["add","install","update"])&&(ft=!0),ct==="deno"&&rt(["install","add"])&&(ft=!0),ct==="pip"&&rt(["install","download"])&&(ft=!0),ct==="pip3"&&rt(["install","download"])&&(ft=!0),ct==="cargo"&&rt(["install","add"])&&(ft=!0),["bash","sh","zsh","fish"].includes(ct)&&rt(["-c"])&&(ft=!0),ct==="cmd"&&rt(["/c"])&&(ft=!0),ft&&(ge="deny",Ie=!0)}!ge&&qe&&(ge="deny")}!xe&&!ge&&le&&(ge="allow")}else le&&(ge="allow");let Te=ge,re="";ge==="deny"&&(Ie?re="network":qe?re="settings":re="prohibited");let ue=!1,ce="",Be=[],nt=0,Le=!1,lt="";if(!Te){if(M==="write_file"||M==="update_file")try{let ve=L(H.args),{path:Ye}=ve;if(Ye){let be=Q.resolve(process.cwd(),Ye),Et=rt=>rt?rt.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,dt=>dt.toUpperCase()):"",Jt=Et(be),pn="",ct=!1,Qt=await gs(),ft=Et(Qt?.file_focused);if(Qt&&ft===Jt&&Qt.full_content?(pn=Qt.full_content,ct=!0):Pe.existsSync(be)&&(pn=Pe.readFileSync(be,"utf8"),ct=!0),ce=pn,await ht.recordFileChange(be,pn),ct){let rt=pn;if(M==="write_file"){let dt=ve.content||ve.newContent||"";rt=dt.endsWith(`
680
+ `)?dt:dt+`
681
+ `,lt=rt}else{let{patchPairs:dt,allowMultiple:Tn,error:Rn}=Ro(ve);if(Rn){let $t=`[TOOL RESULT]: ERROR: ${Rn}`;te.push({role:"user",text:$t}),await vt("toolFailure"),t.onToolResult&&t.onToolResult("failure",M),yield{type:"tool_result",content:$t,toolName:M},Ge++;continue}let ks=ve.allowMultiple!==void 0?ve.allowMultiple===!0||String(ve.allowMultiple).toLowerCase()==="true":Tn;nt=dt.length;let An=Eo(pn,dt,{allowMultiple:ks});rt=An.content,lt=rt,Be=An.results;let ho=Be.filter($t=>$t.success),_t=Be.filter($t=>!$t.success);if(ho.length===0){let $t=`[TOOL RESULT]: ERROR: Failed to apply patches to [${Q.basename(be)}].
682
+ ${_t.map(js=>` \u2022 ${js.error}`).join(`
683
+ `)}`,Ts=`\u2714 Edited: ${Q.basename(be.replaceAll("\\","/"))}`,Ws=115;process.stdout.isTTY&&(Ws=process.stdout.columns-5||120);let Rs=Math.min(Ts.length+4,Ws),mo=`${Ts.padEnd(Rs-2).substring(0,Rs-2)}`;yield{type:"visual_feedback",content:tn(`${We?`
684
+ `:""}${mo}`)},We=!1,te.push({role:"user",text:$t}),await vt("toolFailure"),t.onToolResult&&t.onToolResult("failure",M),yield{type:"tool_result",content:$t,toolName:M},Ge++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${Q.basename(be)}`},Vr(be,pn,rt),ue=!0,await new Promise(dt=>setTimeout(dt,50))}else if(M==="write_file"){let rt=ve.content||ve.newContent||"",dt=rt.endsWith(`
685
+ `)?rt:rt+`
686
+ `;lt=dt,Pe.existsSync(be)||(Le=!0,Pe.mkdirSync(Q.dirname(be),{recursive:!0}),Pe.writeFileSync(be,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${Q.basename(be)}`},Vr(be,"",dt),ue=!0,await new Promise(Tn=>setTimeout(Tn,50))}}}catch(ve){console.error("Simulation/Diff Error:",ve)}let Qe=null;Yr(ve=>{Qe=ve});let yt=t.onToolApproval;if(Te=await new Promise(async ve=>{let Ye=setInterval(()=>{Qe&&(qo.onIDEApproval&&qo.onIDEApproval(Qe),clearInterval(Ye),ve(Qe))},100);try{let be=await yt(M,H.args);clearInterval(Ye),ve(be)}catch{clearInterval(Ye),ve("deny")}}),Yr(null),M==="write_file"||M==="update_file"){let{path:ve}=L(H.args);if(ve){let Ye=Q.resolve(process.cwd(),ve);if(wa(Ye,Te),Te==="deny"&&Le&&Pe.existsSync(Ye))try{Pe.unlinkSync(Ye)}catch{}}}Te==="deny"&&(re="user")}if(Te==="allow"&&ue&&Po()){let{path:Qe}=L(H.args),yt=Q.resolve(process.cwd(),Qe),ve=_t=>_t?Q.resolve(_t).replace(/\\/g,"/").toLowerCase():"",Ye=await gs(),be="";if(Ye&&Ye.file_focused&&ve(Ye.file_focused)===ve(yt)&&Ye.full_content&&(be=Ye.full_content),!be&&Pe.existsSync(yt)){let _t=Pe.readFileSync(yt,"utf8");_t&&(be=_t)}!be&&lt&&(be=lt),(be||Le)&&Pe.writeFileSync(yt,be,"utf8");let Et=be.split(/\r?\n/),Jt=Et.length,pn=Buffer.byteLength(be,"utf8"),ct="";ce&&(ct=`Old File contents:
687
+ ${ce.split(/\r?\n/).map(($t,Ts)=>`${Ts+1} | ${$t}`).join(`
688
+ `)}
689
+
690
+ `);let Qt="";if(Jt<=100)Qt=Et.join(`
691
+ `);else{let _t=Et.slice(0,50).join(`
692
+ `),$t=Et.slice(-50).join(`
693
+ `);Qt=`${_t}
694
+
695
+ ... [${Jt-100} lines truncated for history stability] ...
696
+
697
+ ${$t}`}let ft="";if(M==="update_file"){let _t=_o(ce,be,Be,12,t?.compressToolResults||qo?.systemSettings?.compressToolResults);ft=`SUCCESS: File [${Qe}] updated via IDE Companion (May have user edits). [${Be.length}/${nt}] blocks applied.
698
+
699
+ ${_t}`}else{let _t=be.split(/\r?\n/),$t=_t.length,Ts=Buffer.byteLength(be,"utf8"),Ws="";ce&&(Ws=`Old File contents:
700
+ ${ce.split(/\r?\n/).map((js,qa)=>`${qa+1} | ${js}`).join(`
701
+ `)}
702
+
703
+ `);let Rs="";if($t<=100)Rs=_t.join(`
704
+ `);else{let mo=_t.slice(0,50).join(`
705
+ `),js=_t.slice(-50).join(`
706
+ `);Rs=`${mo}
707
+
708
+ ... [${$t-100} lines truncated] ...
709
+
710
+ ${js}`}ft=`SUCCESS: File [${Qe}] saved via IDE Companion (May have user edits).
711
+ - Stats: [${$t} lines, ${(Ts/1024).toFixed(1)} KB]
712
+ ${Ws}- Content Preview:
713
+
714
+ ${Rs}`}let dt=`${Qe?"\u2714":"\u2718"} ${M==="write_file"?"Created":"Edited"}: ${Qe.replaceAll("\\","/")||"No File Changes"}`,Tn=115;process.stdout.isTTY&&(Tn=process.stdout.columns-5||120);let Rn=Math.min(dt.length+4,Tn),ks=`${dt.padEnd(Rn-2).substring(0,Rn-2)}`;yield{type:"visual_feedback",content:tn(`${We?`
715
+ `:""}${ks}`)},We=!1;let An=Date.now();K=An,yield{type:"tool_time",content:An-oe};let ho=`[TOOL RESULT]: ${ft}`;te.push({role:"user",text:ho}),dn=!0,await vt("toolSuccess"),t.onToolResult&&t.onToolResult("success",M),yield{type:"tool_result",content:ft,aiContent:ho,toolName:M},Ge++;continue}if(Te==="deny"){let Qe=`Permission Denied: Prohibited ${M==="exec_command"?"Command":"file edit"}.`;if(re==="user"?Qe="Permission Denied by User":re==="settings"?Qe="Permission Denied by User Policy":re==="network"?Qe="Permission Denied: Sandbox Network Access Disabled by User Policy.":re==="prohibited"&&M==="exec_command"&&(Qe="Permission Denied: Prohibited Command in User Policy"),M==="write_file"||M==="update_file"){let ve=`\u2718 ${M==="write_file"?"Write Cancelled":"Edit Denied"}: ${L(H.args).path.replaceAll("\\","/")||"..."}`,Ye=115;process.stdout.isTTY&&(Ye=process.stdout.columns-5||120);let be=Math.min(ve.length+4,Ye),Et=`${ve.padEnd(be-2).substring(0,be-2)}`,Jt=` ${" ".repeat(be)} `;yield{type:"visual_feedback",content:tn(`${We?`
716
+ `:""}${Et}
717
+ `)},We=!1}M==="exec_command"&&(await new Promise(yt=>setTimeout(yt,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${Qe}`),await new Promise(yt=>setTimeout(yt,50)),t.onExecEnd&&t.onExecEnd()),te.push({role:"user",text:`[TOOL RESULT]: DENIED: ${Qe}`}),yield{type:"tool_result",content:`[TOOL RESULT]: DENIED: ${Qe}`},await vt("toolDenied"),t.onToolResult&&t.onToolResult("denied",M),Ge++;continue}}if(J){let I=115;process.stdout.isTTY&&(I=process.stdout.columns-5||120);let Y=Math.min(J.length+4,I),le=`${J.padEnd(Y-2).substring(0,Y-2)}`;yield{type:"visual_feedback",content:tn(`${We?`
718
+ `:""}${le}${J.includes("\u2714")&&(J.includes("Created")||J.includes("Edited"))?"":`
719
+ `}`)},We=!1}if(K>0){let I=Date.now()-K,Y=Math.max(0,1e3-I);Y>0&&await new Promise(le=>setTimeout(le,Y))}let Un={chatId:f,history:n,onChunk:I=>t.onExecChunk?t.onExecChunk(I):null,onAskUser:t.onAskUser,systemSettings:t.systemSettings,mode:i,isMultiModal:At(ke),onVisualFeedback:t.onVisualFeedback,onSubagentUpdate:t.onSubagentUpdate,onTokenChunk:t.onTokenChunk,modelName:ke,aiProvider:t.aiProvider,apiKey:t.apiKey,onUsage:t.onUsage};if(M==="write_file"||M==="update_file")try{let{path:I}=L(H.args);if(I){let Y=Q.resolve(process.cwd(),I),le=await gs();le&&le.file_focused===Y&&le.full_content&&(Un.forcedContent=le.full_content)}}catch{}sn.push(M);let $e=await ao(M,H.args,Un);if((M==="write_file"||M==="update_file")&&$e.startsWith("SUCCESS")){let{path:I}=L(H.args);if(I){let Y=Q.resolve(process.cwd(),I);ya(Y)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let Gt=Date.now();K=Gt,yield{type:"tool_time",content:Gt-oe},on=Gt;let Xt=null;if(typeof $e=="object"&&$e.binaryPart&&(Xt=$e.binaryPart,$e=$e.text),M==="search_keyword"){let{keyword:I,path:Y}=L(H.args),le=typeof $e=="string"&&$e.startsWith("[GLOB]");le&&($e=$e.slice(6).trimStart());let ge=typeof $e=="string"&&$e.startsWith("[DIR]");ge&&($e=$e.slice(5).trimStart());let xe=0;if($e){let Be=$e.match(/Found (\d+) match/i);Be&&(xe=parseInt(Be[1]))}let qe=Y?Y.replace(/[\/\\]+$/,""):null,Ie=qe&&qe!=="."?`"${le?Y:ge?`${qe}/*`:qe}"`:"./",Te=`${I?"\u2714":"\u2718"} Searched: "${I||""}" in ${Ie.replaceAll("\\","/")} \u2192 ${xe} Match${xe===1?"":"es"}`,re=115;process.stdout.isTTY&&(re=process.stdout.columns-5||120);let ue=Math.min(Te.length+4,re),ce=`${Te.padEnd(ue-2).substring(0,ue-2)}`;yield{type:"visual_feedback",content:tn(`${We?`
720
+ `:""}${ce}
721
+ `)},We=!1}if(M==="EmergencyRollback"){let{method:I}=L(H.args);if(I==="forceRevert"){let Y=0;if($e){let Te=$e.match(/Total\s*:\s*(\d+)/i);Te&&(Y=parseInt(Te[1]))}let ge=$e&&$e.startsWith("ERROR:")?"\u2718 Emergency Rollback Failed":`\u2714 Emergency Rollback \u2192 ${Y} file${Y===1?"":"s"} processed`,xe=115;process.stdout.isTTY&&(xe=process.stdout.columns-5||120);let qe=Math.min(ge.length+4,xe),Ie=`${ge.padEnd(qe-2).substring(0,qe-2)}`;yield{type:"visual_feedback",content:tn(`${We?`
722
+ `:""}${Ie}
723
+ `)},We=!1}}if(M==="todo"){let{method:I,tasks:Y,markDone:le}=L(H.args),ge="",xe=[],qe=Ie=>{if(!Ie)return[];let Te=Array.isArray(Ie)?Ie:[];if(Te.length===0&&typeof Ie=="string"){let re=Ie.trim();if(re.startsWith("[")&&re.endsWith("]")){let ue=re.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);ue?Te=ue.map(ce=>ce.slice(1,-1).replace(/\\(.)/g,"$1")):Te=re.slice(1,-1).split(",").map(ce=>ce.trim()).filter(Boolean)}else Te=Ie.split(`
724
+ `)}return Te.filter(re=>String(re).trim()).map(re=>{let ue=String(re).trim();return ue.startsWith("- [")?ue.substring(6).trim():ue})};if(I==="create"?(ge="\x1B[32m\u2192\x1B[0m Created Goals",xe=qe(Y).map(Ie=>`\x1B[90m\u25CB\x1B[0m ${Ie}`)):I==="append"?(ge="\x1B[34m\u2795\x1B[0m Added New Goals",xe=qe(Y).map(Ie=>`\x1B[90m\u25CB\x1B[0m ${Ie}`)):I==="get"&&(ge=le?"\x1B[36m\u21BB\x1B[0m Updated Goals":"\x1B[35m\u2022\x1B[0m Reviewed Goals",xe=($e||"").split(`
725
+ `).slice(1).join(`
726
+ `).split(`
727
+ `).filter(Te=>Te.trim().startsWith("- [")).map(Te=>{let re=Te.trim(),ue=re.startsWith("- [x]");return`${ue?"\x1B[32m\u2714\x1B[0m":"\x1B[90m\u25CB\x1B[0m"} ${ue?"\x1B[90m":"\x1B[37m"}${re.substring(6).trim()}\x1B[0m`})),ge&&xe.length>0){let Ie=[`${ge}`,...xe.map(Te=>` ${Te}`)].join(`
728
+ `);yield{type:"visual_feedback",content:tn(`${We?`
729
+ `:""}${Ie}
730
+ `)},We=!1}}M==="exec_command"&&t.onExecEnd&&(await new Promise(I=>setTimeout(I,800)),t.onExecEnd());let Cn=$e&&$e.startsWith("DENIED:");$e&&!$e.startsWith("ERROR:")&&!Cn?(await vt("toolSuccess"),t.onToolResult&&t.onToolResult("success",M)):Cn||(await vt("toolFailure"),t.onToolResult&&t.onToolResult("failure",M));let qt=($e||"").toString().replaceAll("[UI_CONTEXT]","");qt.includes("[[VERIFIED]]")&&(qt=qt.replace(/\[\[VERIFIED\]\][\s\S]*?\[\[\/VERIFIED\]\]/g,`[SYSTEM NOTE]: Patch Block matched & applied successfully. Large Block omitted to conserve context.
731
+ `));let Mn;if(qt.startsWith("[[SAME]]")){let Y=qt.replace(/^\[\[SAME\]\]\s*\r?\n?/,"").split(/\r?\n/),le=Y.filter(xe=>xe.startsWith("SUCCESS:")||xe.trim().startsWith("- Stats:"));Mn=`[TOOL RESULT]: ${le.length>0?le.join(`
732
+ `):Y.slice(0,2).join(`
733
+ `)}
734
+ [SYSTEM NOTE]: Content verified and persisted to disk. Full preview omitted to conserve context.`}else Mn=`[TOOL RESULT]: ${qt}`;te.push({role:"user",text:Mn,binaryPart:Xt}),dn=!0;let Ae=`[TOOL RESULT]: ${$e.replaceAll(`[[VERIFIED]]
735
+ `,"").replaceAll(`
736
+ [[/VERIFIED]]`,"")||""}`;(M==="view_file"||M==="web_scrape"||M==="file_map")&&(Ae=`[TOOL RESULT]: ${J} (Context Locked for UI Clarity)`),yield{type:"tool_result",content:Ae,aiContent:Mn,binaryPart:Xt,toolName:M},M==="memory"&&$e.includes("SUCCESS")&&(yield{type:"memory_updated"}),Ge++}if(d==="Google"&&Sn&&Date.now()-Jo>=150){yield*ss();let H=Bs(Sn);for(let oe of H)yield oe;Sn="",Jo=Date.now()}}N.usageMetadata&&(_n=N.usageMetadata),_n&&(yield{type:"liveTokens",content:_n.totalTokenCount})}if(fe&&(fe=!1,Wt?Ke+="</think>":(pe+="</think>",d==="Google"?Sn+="</think>":yield{type:"text",content:"</think>"})),Wt&&Ke.length>0){let N=0,ae=Math.min(st.length,Ke.length);for(let G=ae;G>0;G--)if(st.endsWith(Ke.substring(0,G))){N=G;break}let j=Ke.substring(N);if(j){let we=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(st)?j.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):j.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(we)if(pe+=we,d==="Google")Sn+=we;else{yield*ss();let me=Bs(we);for(let _e of me)yield _e}}Wt=!1,Ke=""}if(yield*ss(),Mt)break;let Us=(pe||"").trim(),Ba=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(Us.toLowerCase())||/\[\[END\]\]/i.test(Us.toLowerCase()),Ua=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(Us.toLowerCase()),Wa=te.length>0||Bt!==null,Qo=nn(Us).trim(),ja=/(\p{Emoji_Presentation}|\p{Extended_Pictographic})$/u.test(Qo),Ha=/([.!?"'*_`|\]\)”’~~]+|\s|`{3}|[\u200B-\u200D\uFEFF])$/u.test(Qo.trim()),Ga=/[.!?}"'`’“”]$|```$/s.test(Qo)||Ha||ja;!Ba&&!Ua&&!Wa&&Us.length>0,Ze=!0,await vt("agent",d)}catch(ye){if(Mt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
737
+
738
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(String(ye).includes("Incomplete JSON segment at the end")){fe&&(fe=!1,Wt?Ke+="</think>":(pe+="</think>",yield{type:"text",content:"</think>"})),Ze=!0,await vt("agent",d);break}if(fe&&(fe=!1,Wt?Ke+="</think>":pe+="</think>"),Wt&&Ke.length>0){let ns=0,rn=Math.min(st.length,Ke.length);for(let Lt=rn;Lt>0;Lt--)if(st.endsWith(Ke.substring(0,Lt))){ns=Lt;break}let Ot=Ke.substring(ns);if(Ot){let Pt=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(st)?Ot.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):Ot.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");Pt&&(pe+=Pt)}Wt=!1,Ke=""}let de=ye instanceof Error?(()=>{try{return JSON.parse(JSON.parse(ye.message).error.message).error.message}catch{return String(ye)}})():String(ye),ot=new Date().toLocaleString(),jt=Q.join(hn,"agent");Pe.existsSync(jt)||Pe.mkdirSync(jt,{recursive:!0}),Pe.appendFileSync(Q.join(jt,"error.log"),`ERROR [${ot}]: ${de}
739
+
740
+ ----------------------------------------------------------------------
741
+
742
+ `);let Vt=ye.status||ye.statusCode||ye.code,Bn=String(ye).includes("replicas at capacity");if(!(Vt&&(Vt>=500&&Vt<600||Vt===408||Vt===429||Bn)||!Vt&&(/status[ :]+(5\d\d|408|429)/i.test(String(ye))||/code[ :]+(5\d\d|408|429)/i.test(String(ye))||/(500|503|408|429)/.test(String(ye))))){if(He<xn-3)throw ye;yield{type:"text",content:de},yield{type:"status",content:"Error Occured"}}if(pe.trim().length>0||Xe>1)if(Xe<=xn){Xe++;let ns=Math.min(1e3*Math.pow(2,Xe-1),24e3);if(pe.trim().length>0){b.push({role:"agent",text:pe});let rn=`[system]
743
+ - seamless continuation: resume immediately. pick up from last words with zero gap/disruption
744
+ - no repetition: do not repeat any text already written
745
+ - no re-think: do not restart or open <think> if reasoning already started. continue the thinking and close thinking block </think> before chat output
746
+ - mid-tool safety: if cutoff was mid-tool call, restart that tool call from start
747
+ - stealth: do not mention/apologize for cutoff [/system]`;te.length>0?te.forEach((Ot,Lt)=>{Lt===te.length-1?b.push({...Ot,text:`${Ot.text}
748
+
749
+ ${rn}`}):b.push(Ot)}):b.push({role:"user",text:rn}),st+=pe}for(let rn=ns/1e3;rn>0&&!Mt;rn--)yield{type:"status",content:`Error Occured. Recovering Stream (${Xe}/${xn}) [Retrying in ${rn.toFixed(0)}s]...`},await new Promise(Ot=>setTimeout(Ot,1e3));yield{type:"status",content:"Error Occured. Recovering Stream..."}}else throw new Error(`Stream collapsed too many times. (Failed to resolve ${xn} times)
750
+ Error log can be found in \`/export logs\``);else if(He<=xn){He++,Xe=1,st="";let ns=Math.min(1e3*Math.pow(2,He-1),32e3),rn=.8+Math.random()*.4,Ot=Math.round(ns*rn);Qn=!0,yield{type:"status",content:`Trying to reach ${e} (${He}/${xn}) [Retrying in ${(Ot/1e3).toFixed(0)}s]`};for(let Lt=Ot/1e3;Lt>0&&!Mt;Lt--)yield{type:"status",content:`Trying to reach ${e} (${He}/${xn}) [Retrying in ${Lt.toFixed(0)}s]`},await new Promise(Pt=>setTimeout(Pt,1e3));yield{type:"status",content:`Trying to reach ${e}`}}else throw new Error(`Model ${e} cannot be reached. (Failed ${xn} times)
751
+ Error log can be found in \`/export logs\``)}}if(_n){let fe=_n.totalTokenCount||0,ye=_n.cachedContentTokenCount||0,de=(_n.candidatesTokenCount||0)+(_n.thoughtsTokenCount||0);await zt("tokens",fe,d,ke),ye>0&&await zt("cachedTokens",ye,d,ke),de>0&&await zt("candidateTokens",de,d,ke),yield{type:"usage",content:_n}}pi.push(pe);let es=nn(pe),un=_a(pe),Ns=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(un.toLowerCase())||/\[\[END\]\]/i.test(un.toLowerCase())||!0,Nn=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(un.toLowerCase()),Dc=Ge>0;yield{type:"status",content:"Thinking"};let Pa=Mc(pe,/(\[\s*(turn\s*:)?\s*(continue|finish)\s*\]|\[\[END\]\])/gi,"").trim(),ts=(Ns||te.length===0)&&!Ut&&!bn&&!$n;if(ts=te.length===0?ts:!1,ts=Zn||uo?!1:ts,pe&&pe.trim().endsWith('")]')&&te.length===0&&(ts=!1),ts){let fe=pi.join(`
752
+ `),ye=nn(fe).trim();yield{type:"interactive_turn_finished",data:{agentText:T,fullAgentTextRaw:fe,history:[...b],needTitle:S}},b.length>0&&b[b.length-1].role==="agent"?b[b.length-1].text=ye:b.push({role:"agent",text:ye}),b.forEach(de=>{if(de.role==="user"&&de.text&&(de.text=de.text.replace(/\n\[COMPILE ERROR\][\s\S]*?\[\/ERROR\]/g,""),de.text=de.text.replaceAll(`
753
+
754
+ [system] user question. resolve this specific query within '[ANSWER] ... [/ANSWER]' concisely, naturally [/system]
755
+ `,"").replaceAll(`[system] user question. resolve this specific query within '[ANSWER] ... [/ANSWER]' concisely, naturally
756
+ **strictly follow thinking policy as high priority. do not start a response without <think>...</think>** [/system]
757
+ `,"").replaceAll(`[system] **strictly follow thinking policy as high priority. do not start a response without <think>...</think>** [/system]
758
+ `,"").replaceAll(/\n\[system\] WARNING, Turn Limit Impending: Step \d+\/\d+\. Wrap up quickly\/prompt user to continue & use \[\[END\]\] quickly\. \[\/system\]/g,""),de.text=de.text.replaceAll(/\n\[system\] File Changes:\n(?:\* .+ \(created|modified|deleted\)\n)*\[\/system\]/g,""),(d==="Mistral"||d==="Google"&&e?.toLowerCase().startsWith("gemma"))&&de.text.startsWith("[TOOL RESULT]"))){let jt=`
759
+ [system] Tool result received. Analyze output and proceed with your turn [/system]`,Vt=`
760
+ [system] Tool result received. Analyze output and proceed with your turn. **strictly follow thinking policy. do not start a response without <think>...</think>** [/system]`;de.text=de.text.replaceAll(Vt,"").replaceAll(jt,"").trim()}}),yield{type:"status",content:"[end]"}}if(ts)break;let Da=Pa.trim()||"*Working...*";if(b.push({role:"agent",text:Da}),te.length>0||dn){if(te.length>0){let fe=te.map(Bn=>Bn.text).join(`
761
+
762
+ `),ot=(nn(pe).replace(/\[{1,2}tool:[\s\S]*?\)\s*\]{1,2}/gi,"").match(/\[tool:/gi)||[]).length,jt=te.length+ot;if(te.length<jt){fe+=`
763
+
764
+ [system] Only ${te.length} out of ${jt} attempted tool calls were executed. Verify proper structure compliance & try failed calls again [/system]`;let Bn=jt-te.length;for(let gt=0;gt<Bn;gt++)await vt("toolFailure")}let Vt=te.find(Bn=>Bn.binaryPart)?.binaryPart||null;b.push({role:"user",text:fe,binaryPart:Vt})}}else if(!Mt){let ye=(pe.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/i,"").match(/\[tool:/gi)||[]).length;uo||Zn||ye>0?(b.push({role:"user",text:`[system] Failed to execute ${ye} tool${ye>1?"s":""}. Verify proper structure compliance & try again [/system]`}),await vt("toolFailure"),yield{type:"visual_feedback",content:`
765
+ ${tn("\u2718 Execution Error")}
766
+ `}):(yield{type:"visual_feedback",content:`
767
+ ${tn("\u2718 Loop Detected")}
768
+ `},b.push({role:"user",text:`[system] ${bn&&!Ut?"Stuttering Detected by Internal System. Re-calibrate your response & proceed.":`${Ut?" Over Thinking":" Loop"} Detected by Internal System${Ut?" for current Effort Level":""}. ${Ut?"If you have planned the task, prioritize execution/output":"If you have finished your task provide a simple summary and end"}`} [/system]`})),Ut=!1,bn=!1,$n=!1}l?.advanceRollback&&await Kn.recordTurnDelta(f,z+1,sn),uo=Ge>0||dn}}catch(E){let C=(E instanceof Error?(()=>{try{return JSON.parse(JSON.parse(E.message).error.message).error.message}catch{return E.message||String(E)}})():String(E)).replace(/^(Error:\s*)+/i,""),A=new Date().toLocaleString(),O=Q.join(hn,"agent");yield{type:"text",content:`\u2726 CRITICAL ERROR: ${C.includes("fetch failed")?"Failed to Connect. Check your Internet Connection or Wait a moment":C}
769
+ \u2800`},Pe.existsSync(O)||Pe.mkdirSync(O,{recursive:!0}),Pe.appendFileSync(Q.join(O,"error.log"),`CRITICAL ERROR [${A}]: ${E}
770
+
771
+ ----------------------------------------------------------------------
772
+
773
+ `),typeof flushGoogleBuffer=="function"&&(yield*flushGoogleBuffer()),yield{type:"tool_result",content:`ERROR: [INTERNAL CRITICAL] ${C}`}}finally{R&&(clearInterval(R),R=null),typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),await ht.commitTransaction(),l?.advanceRollback&&await Kn.cleanup(f),await gs()}yield{type:"status",content:null}},Qm=async(e,n,t=null,s=null,o=50,r=null,a=!1)=>{let i=await en(),h={...i,...n},f=process.env.SUBAGENT_MODEL?process.env.SUBAGENT_MODEL.trim():null,c=process.env.SUBAGENT_PROVIDER?process.env.SUBAGENT_PROVIDER.trim():null,l=new Date,u=`${l.getFullYear()}-${l.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(l.getDate()).padStart(2,"0")}, ${l.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}).replace(":","-")}`,p=(E=>{if(!E)return null;let b=E.toLowerCase();return b==="google"?"Google":b==="deepseek"?"DeepSeek":b==="openrouter"?"OpenRouter":b==="nvidia"?"NVIDIA":b==="mistral"?"Mistral":b==="ollama"?"Ollama":b==="crofai"||b==="crof"?"CrofAI":b==="inferx"?"InferX":b==="sensenova"?"SenseNova":null})(c),g=h?.systemSettings?.CustomSubAgent?h?.systemSettings?.SubAgentModel:null,y=h?.systemSettings?.CustomSubAgent?h?.systemSettings?.SubAgentProvider:null,m=null;if(g==="ENV"?(m=f,f&&p&&(h.aiProvider=p)):g&&g!=="Default"?(m=g,y&&(h.aiProvider=y)):f&&p&&(h.aiProvider=p),h.aiProvider){let E=await nr(h.aiProvider);E&&(h.apiKey=E)}let w=E=>{if(!E||typeof E!="string")return{allowed:!0};let b=[/rm\s+-[rf]{1,2}\s+[\/*.]/i,/rmdir\s+\/[sq]/i,/del\s+\/[fsq]/i,/\bformat\b\s+[a-z]:/i,/mkfs/i,/dd\s+if=/i,/\b(shutdown|reboot|poweroff|init\s+0|init\s+6)\b/i,/chmod\s+(-R\s+)?777\s+[\/*.]/i,/chown\s+(-R\s+)?root/i,/git\s+push\s+.*--force/i,/git\s+clean\s+-fdx/i,/\bsudo\s+su\b/i,/\bsu\s+-\b/i];for(let C of b)if(C.test(E))return{allowed:!1,reason:`Blocked potentially destructive or unsafe command pattern: "${C.source}"`};return{allowed:!0}},x=t||m||n?.modelName||n?.activeModel||i.activeModel,k=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",$=`-- TOOL DEFINITIONS (path = relative to CWD, path separator: '/') --
774
+ You cant execute tools. To use tools, must output exactly [tool:functions.ToolName(arg1="value1")] structured string in chat output & wait for system response \u2190 no exception, tool:functions must
775
+ Tool Rules:
776
+ - JSON escape literal sequences inside tool arguments (backslash: \\\\, newLine: \\n, quote: \\") \u2190 Mandatory
777
+ - Same file, multiple edits? ONE PatchFile (\u226415 blocks)
778
+ - Need text or huge file? CodeSearch > Full Read
779
+ - Avoid unnecessary large file chunk reads
780
+ - Dont hallucinate tool results, verify, fix errors
781
+ - Stuck on syntax error? Tell user > waste time
782
+ - ONLY valid tools defined below are allowed
783
+
784
+ # Provided Tools
785
+ **Communication Tools**
786
+ - AskUser(question="...", optionA="title::description", ...MAX4). Ambiguity, path divergence, security risk. Ask, dont finish/guess. Keep titles short
787
+ ${a?'- AskMain(question="..."). Communicate with PARENT/MAIN AGENT. When clarification/decision is needed for a task':""}
788
+
789
+ **Web Tools**
790
+ - WebSearch(query="...", aiMode="bool, optional", limit="integer 3-10 aiMode: exclude"). Proactive use for unknown info/docs. aiMode: LLM search
791
+ - WebScrape(url="..."). Proactive use for specific webpage/docs/api
792
+
793
+ **Workspace Tools**
794
+ - 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
795
+ - ReadFolder(path="...", recurse="int 1-3"). Minimize recursion
796
+ - ReadFile(path="...", startLine="int", endLine="int")
797
+ - PatchFile(path="...", allowMultiple="bool, false", searchContent1="search string OR ^LINE:start..end$", newContent1="...", ...MAX15). Use small searchContent. Line Ranges must for large searchContent and escape sequences. ^...$ must for line ranges
798
+ - WriteFile(path="...", content="..."). Creates/Overwrites. File Exist? PatchFile > WriteFile. VERIFY IMPORTS
799
+ - Run(command="..."). Runs ${k==="Windows"?Hn()?"powershell":"windows CMD":"bash"} command. Destructive/Irreversible ops \u2192 Ask user`.trim(),_=`=== START SYSTEM PROMPT ===
800
+ Identity: FluxFlow subagent helping the main Agent
801
+ Your task is: "${e}"
802
+
803
+ ${$.trimEnd()}
804
+
805
+ -- THINKING GUIDANCE --
806
+ NO EXPLICIT THINKING REQUIRED. FOCUS ON TASK COMPLETION
807
+ Main focus: tools and task, not chatting
808
+ On completion, provide a detailed summary in Tables/Markdown Format with file modified info. If any task failed report back in detail
809
+
810
+ CWD: ${process.cwd()}
811
+ Current Time: ${u}
812
+ === END SYSTEM PROMPT ===`,S=[{role:"user",text:`Complete this task: ${e}`}],T=0,R="";for(;T<o;){if(Mt){if(n?.taskId&&typeof Ve<"u"){let F=Ve.find(B=>B.id===n.taskId);F&&(F.status="cancelled")}throw r&&r("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}if(n?.taskId&&typeof Ve<"u"){let F=Ve.find(B=>B.id===n.taskId);if(F&&F.status==="cancelled")throw r&&r("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}let E=S.map(F=>({role:F.role==="user"?"user":"model",parts:[{text:F.text}]}));r&&r(`[Subagent Turn ${T+1}]...`);let C=(await zo(h,x,E,_,"Fast")).text||"",A=nn(C).trim();R=A,r&&r(`[Subagent Response]
813
+ ${A}
814
+ `),S.push({role:"agent",text:A});let O=Ko(A);if(O.length===0)break;let D=O.filter(F=>F.toolName.toLowerCase()==="askmain"||F.toolName.toLowerCase()==="ask_main"),W=!1,q="";for(let F of O){if(Mt){if(n?.taskId&&typeof Ve<"u"){let v=Ve.find(U=>U.id===n.taskId);v&&(v.status="cancelled")}throw new Error("Subagent task was cancelled.")}if(n?.taskId&&typeof Ve<"u"){let v=Ve.find(U=>U.id===n.taskId);if(v&&v.status==="cancelled")throw new Error("Subagent task was cancelled.")}let B=F.toolName.toLowerCase();if(B==="askuser"&&(B="ask"),B==="askmain"||B==="ask_main"){if(W)continue;W=!0;let v="";if(D.length===1?v=L(D[0].args).question||D[0].args:v=D.map((U,X)=>{let ee=L(U.args);return`Q${X+1}: ${ee.question||U.args}`}).join(`
815
+ `),n.onAskMain){r&&r(`[Executing Tool] AskMain("${v}")...`);let U=await n.onAskMain(v);r&&r(`[Tool Result]
816
+ Answer from Main Agent: ${U}
817
+ `),q+=`[TOOL RESULT for AskMain]: Answer from Main Agent: ${U}
818
+
819
+ `,await vt("toolSuccess")}else q+=`[TOOL RESULT for AskMain]: ERROR: Main agent communication channel not available.
820
+
821
+ `;continue}if(!(s?s.some(v=>v.toLowerCase()===B):!0)){let v=`ERROR: Tool [${F.toolName}] is not in the allowed tools list for this subagent.`;r&&r(`[Blocked Tool Call] ${F.toolName} - not allowed
822
+ `),q+=`${v}
823
+
824
+ `;continue}if(B==="exec_command"||B==="execcommand"||B==="run"){let v=L(F.args).command||"",U=w(v);if(!U.allowed){let X=`ERROR: [SECURITY RESTRICTION] Subagent execution blocked command: ${U.reason}`;r&&r(`[Blocked Command] ${v} - ${U.reason}
825
+ `),q+=`${X}
826
+
827
+ `;continue}}let Ce="";if(B==="web_search"||B==="websearch")Ce=`\u2714 \x1B[95mSearched\x1B[0m: ${L(F.args).query||""}`;else if(B==="web_scrape"||B==="webscrape")Ce=`\u2714 \x1B[95mScraped\x1B[0m: ${L(F.args).url||""}`;else if(B==="search_keyword"||B==="searchkeyword"||B==="codesearch"||B==="code_search"){let v=L(F.args),U=v.keyword||"",X=v.path||"";Ce=`${U?"\u2714":"\u2718"} \x1B[95mSearched\x1B[0m: ${U||"No Query"}${X?` \u2192 ${X.replaceAll("\\","/")}`:""}`}else if(B==="view_file"||B==="viewfile"||B==="readfile")Ce=`\u2714 \x1B[95mRead\x1B[0m: ${(L(F.args).path||"").replaceAll("\\","/")}`;else if(B==="list_files"||B==="read_folder"||B==="readfolder"){let v=L(F.args).path||null,U=L(F.args).recurse||0;Ce=`${v?"\u2714":"\u2718"} \x1B[95mBrowsed\x1B[0m: ${v?`${v.replaceAll("\\","/")}${U>0?`${v.endsWith("/")?`*${U}`:`/*${U}`}`:`${v.endsWith("/")?"":"/"}`}`:""}`}else if(B==="write_file"||B==="writefile"){let v=L(F.args).path||null;Ce=`${v?"\u2714":"\u2718"} \x1B[95mCreated\x1B[0m: ${v?`${v.replaceAll("\\","/")}`:"No File Changes"}`}else if(B==="update_file"||B==="updatefile"||B==="patchfile"||B==="patch_file"||B==="patchfile"||B==="updatefile"){let v=L(F.args).path||null,U=L(F.args).content||null;Ce=`${v?"\u2714":"\u2718"} \x1B[95mEdited\x1B[0m: ${v?`${v.replaceAll("\\","/")}`:"No File Changes"}`}else if(B==="exec_command"||B==="execcommand"||B==="run"){let v=L(F.args).command||null;Ce=`${v?"\u2714":"\u2718"} \x1B[95mExecuted\x1B[0m: ${v?v.slice(0,100)+(v.length>100?"...":""):"No Command"}`}else if(B==="file_map"||B==="filemap"){let v=L(F.args).path||"";Ce=`${v?"\u2714":"\u2718"} \x1B[95mIndexed\x1B[0m: ${v?`${v.replaceAll("\\","/")}`:"File Not Found"}`}else if(B==="await"){let{time:v}=L(F.args),U=parseFloat(v)||0;U<10&&(U=10),U>180&&(U=180),Ce=`\u2714 \x1B[95mAwaiting\x1B[0m \u2192 ${(ee=>{if(ee>=60){let Ue=Math.floor(ee/60),De=ee%60;return`${Ue}m${De>0?` ${De}s`:""}`}return`${ee}s`})(U)}`}else{let v=ti[B]||F.toolName,U=xs(B,F.args);Ce=`\u2714 \x1B[95m${v}\x1B[0m${U?`: ${U}`:""}`}n.onVisualFeedback&&Ce&&n.onVisualFeedback(Ce),r&&r(`[Executing Tool] ${F.toolName}(${F.args})...`);try{let v=await ao(F.toolName,F.args,{...n,mode:"Flux"});if(r&&r(`[Tool Result]
828
+ ${v}
829
+ `),q+=`[TOOL RESULT for ${F.toolName}]: ${v}
830
+
831
+ `,await vt("toolSuccess"),B==="patchfile"||B==="update_file"||B==="updatefile"||B==="patch_file"){if(v){let U=v.split(`
832
+ `),X=0,ee=0,Ue=!1;for(let De of U){if(De.includes("[DIFF_START]")){Ue=!0;continue}if(De.includes("[DIFF_END]")){Ue=!1;continue}Ue&&(/^\+\d+/.test(De)?X++:/^\-\d+/.test(De)&&ee++)}(X>0||ee>0)&&(await zt("linesAdded",X),await zt("linesRemoved",ee))}}else if((B==="writefile"||B==="write_file")&&v){let U=v.match(/- Stats: \[(\d+) lines/),X=U?parseInt(U[1]):0,ee=0;if(v.includes("Old File contents:")){let Ue=!1;for(let De of v.split(`
833
+ `)){if(De.includes("Old File contents:")){Ue=!0;continue}Ue&&(De.trim()===""?Ue=!1:/^\d+ \|/.test(De)&&ee++)}}(X>0||ee>0)&&(await zt("linesAdded",X),await zt("linesRemoved",ee))}}catch(v){let U=`ERROR: Execution failed for [${F.toolName}]: ${v.message}`;r&&r(`[Tool Error] ${U}
834
+ `),q+=`${U}
835
+
836
+ `,await vt("toolFailure")}}let se="";if(n?.taskId&&typeof Ve<"u"){let F=Ve.find(B=>B.id===n.taskId);if(F&&F.pendingSteerMessages&&F.pendingSteerMessages.length>0){let B=[...F.pendingSteerMessages];F.pendingSteerMessages=[];for(let Z of B)se+=`
837
+
838
+ [STEERING INSTRUCTION FROM MAIN AGENT]: ${Z}`,r&&r(`[Subagent Steered] ${Z}`)}}let V=(q.trim()+se).trim();S.push({role:"user",text:V}),T++}return R};export{yn as a,Hi as b,hd as c,md as d,kl as e,Gi as f,gd as g,Ml as h,yd as i,lo as j,ha as k,Eh as l,_h as m,L as n,jc as o,or as p,qs as q,Hc as r,Gc as s,ht as t,ls as u,kf as v,il as w,Tf as x,Rf as y,Ef as z,_f as A,$f as B,cs as C,Wl as D,mu as E,gu as F,Mh as G,Po as H,Ah as I,bc as J,qm as K,Sc as L,kc as M,ei as N,nn as O,Ea as P,_c as Q,zm as R,Km as S,oi as T,Ym as U,Vm as V,Lc as W,Xm as X,Jm as Y,Qm as Z};