fluxflow-cli 4.2.4 → 4.3.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.
@@ -1,815 +0,0 @@
1
- import{b as Zo}from"./chunk-M7QN5C2K.js";import{c as rn,d as qs,g as et,h as Ft}from"./chunk-6ENN7MJR.js";import{a as Gs,b as Cs,c as X,d as he}from"./chunk-SIINYZWE.js";import{c as An,d as fn,e as bo,f as Es,g as $s,h as Xo,i as Xt,j as Dt,k as Qt,l as vn,m as Wn,n as on,o as un,p as rs,q as Qo,r as jn,s as as}from"./chunk-I27MASHH.js";import{a as Ve,c as ko}from"./chunk-56EJGQU3.js";import{c as wr,d as xr,e as zs}from"./chunk-3JHCQ2JD.js";import er from"dotenv";import{GoogleGenAI as va,ThinkingLevel as at,HarmBlockThreshold as Yn,HarmCategory as Vn}from"@google/genai";import{Ollama as rc}from"ollama";import{execSync as Va}from"child_process";import{spawn as ei}from"child_process";var I=e=>{let n={};if(!e)return n;let t=0;for(;t<e.length;){for(;t<e.length&&/[\s,]/.test(e[t]);)t++;if(t>=e.length)break;let o=e.substring(t).match(/^(\w+)\s*=\s*/);if(!o){t++;continue}let s=o[1];t+=o[0].length;let i="";if(t<e.length&&(e[t]==='"'||e[t]==="'"||e[t]==="`")){let a=e[t];t++;let r=t,p=-1,d=t;for(;d<e.length;){let l=e.indexOf(a,d);if(l===-1)break;let u=0;for(let y=l-1;y>=0&&e[y]==="\\";y--)u++;if(u%2!==0){d=l+1;continue}let f=e.substring(l+1),h=f.trim(),g=h===""||/^,\s*\w+\s*=/.test(h)||h.startsWith(")")&&(h.length===1||/^\)\s*([,\]\s]|\[\[?tool:)/i.test(h));if(g&&f.startsWith(`
2
- `)){let y=h.split(`
3
- `)[0];if(!y.includes("=")&&!y.includes(")")){d=l+1;continue}}if(g){p=l;break}d=l+1}p!==-1?(i=e.substring(r,p),t=p+1):(i=e.substring(r),t=e.length);let c=s.toLowerCase().includes("path")||["dest","source","to","from"].includes(s.toLowerCase());i=i.replace(/\\(.)/g,(l,u)=>{switch(u){case"n":return`
4
- `;case"r":return"\r";case"t":return" ";case"\\":return"\\";default:return u===a?a:u}})}else if(t<e.length&&e[t]==="["){let a=0,r=null,p=t,d=-1;for(let c=t;c<e.length;c++){let l=e[c];if(r&&l===r){let u=0;for(let f=c-1;f>=0&&e[f]==="\\";f--)u++;u%2===0&&(r=null)}else!r&&(l==='"'||l==="'"||l==="`")&&(r=l);if(!r&&(l==="["?a++:l==="]"&&a--,a===0)){d=c;break}}if(d!==-1){i=e.substring(p,d+1),t=d+1;try{let c=i.trim();c.startsWith("'")||c.includes("'")}catch{}}else i=e.substring(p),t=e.length}else{let a=e.substring(t),r=a.match(/,\s*\w+\s*=|(?:\s*\)\s*(?:$|\]\]))/);if(r){let p=r.index;i=a.substring(0,p).trim(),t+=p}else i=a.trim(),t=e.length}i==="true"?i=!0:i==="false"?i=!1:typeof i=="string"&&!isNaN(i)&&i.trim()!==""&&(i=Number(i)),typeof i=="string"&&(s.toLowerCase().includes("path")||["dest","source","to","from"].includes(s.toLowerCase()))&&(i=i.replace(/\x0C/g,"\\f").replace(/\x0D/g,"\\r").replace(/\x0B/g,"\\v").replace(/\x08/g,"\\b")),n[s]=i}return n};var So=null;try{let e=await import("node-pty");So=e.default||e}catch{}var Uc=!!So,To=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),ti=e=>{if(!e)return"";let n=[[]],t=0,o=0,s=/\x1b\[([0-9;]*?)([a-zA-Z])/g,i=0,a,r=d=>{for(let c=0;c<d.length;c++){let l=d[c];if(l===`
5
- `)for(t++,o=0;t>=n.length;)n.push([]);else if(l==="\r")o=0;else{for(;t>=n.length;)n.push([]);let u=n[t];for(;o>u.length;)u.push(" ");u[o]=l,o++}}};for(;(a=s.exec(e))!==null;){r(e.substring(i,a.index));let d=a[1],c=a[2],l=d?d.split(";").map(Number):[];if(c==="A"){let u=l[0]||1;t=Math.max(0,t-u)}else if(c==="B"){let u=l[0]||1;for(t=t+u;t>=n.length;)n.push([])}else if(c==="C"){let u=l[0]||1;o=o+u}else if(c==="D"){let u=l[0]||1;o=Math.max(0,o-u)}else if(c==="G"){let u=(l[0]||1)-1;o=Math.max(0,u)}else if(c==="H"||c==="f"){let u=(l[0]||1)-1,f=(l[1]||1)-1;for(t=Math.max(0,u),o=Math.max(0,f);t>=n.length;)n.push([])}else if(c==="K"){let u=l[0]||0;if(t<n.length){let f=n[t];if(u===0)f.length=o;else if(u===1)for(let h=0;h<o&&h<f.length;h++)f[h]=" ";else u===2&&(f.length=0)}}else if(c==="J"){let u=l[0]||0;(u===2||u===3)&&(n.length=0,n.push([]),t=0,o=0)}i=s.lastIndex}r(e.substring(i));let p=n.map(d=>d.join(""));for(;p.length>0&&p[p.length-1]==="";)p.pop();return p.join(`
6
- `)},gt=null,Ks=!1,Wc=e=>{try{gt&&(Ks&&typeof gt.write=="function"?gt.write(e):gt.stdin&&gt.stdin.writable&&gt.stdin.write(e))}catch{}},jc=()=>{if(gt){try{Ks&&typeof gt.destroy=="function"?gt.destroy():typeof gt.kill=="function"&&(process.platform==="win32"?ei("taskkill",["/pid",gt.pid,"/f","/t"]):gt.kill("SIGKILL"))}catch{}gt=null,Ks=!1}},ni=(e,n=!1)=>{if(process.platform!=="win32")return e;let t=[],o="",s=null,i=!1;for(let c=0;c<e.length;c++){let l=e[c];if(i){o+=l,i=!1;continue}if(l==="\\"){if(e[c+1]===" "){o+=" ",c++;continue}o+=l,i=!0;continue}s?(l===s&&(s=null),o+=l):l==='"'||l==="'"?(s=l,o+=l):l===";"&&!o.includes("://")?(o.length>0&&(t.push(o),o=""),t.push(n?";":"&")):l==="&"&&!o.includes("://")?e[c+1]==="&"?(o.length>0&&(t.push(o),o=""),t.push("&&"),c++):(o.length>0&&(t.push(o),o=""),t.push("&")):l==="|"&&!o.includes("://")?(o.length>0&&(t.push(o),o=""),t.push("|")):/\s/.test(l)?o.length>0&&(t.push(o),o=""):o+=l}o.length>0&&t.push(o);let a=c=>!(!c.includes("/")||/^(https?|file|ftp):\/\//i.test(c)||c.startsWith("@")||c.startsWith("/")&&(c.match(/\//g)||[]).length===1||/\s\/|\/\s/.test(c)||/[\(\)\{\}\;\<\>\=\'\"]/.test(c)),r=[];for(let c=0;c<t.length;c++){let l=t[c];if(l==="mkdir"&&n&&Hn()){let u=[],f=c+1;for(;f<t.length;){let h=t[f];if([">",">>","<","&","&&","|","||",";"].includes(h))break;h!=="-p"&&h!=="--parents"&&h!=="-v"&&h!=="--verbose"&&u.push(h),f++}if(u.length>0){let h=u.map(g=>{let y=g.replace(/^['"]|['"]$/g,""),m=g;return a(y)&&(m=g.replace(/\//g,"\\")),m});r.push("New-Item","-ItemType","Directory","-Force","-Path",h.join(","))}else r.push("New-Item","-ItemType","Directory","-Force");c=f-1;continue}if(l==="rm"&&n&&Hn()){let u=[],f=!1,h=!1,g=c+1;for(;g<t.length;){let m=t[g];if([">",">>","<","&","&&","|","||",";"].includes(m))break;m==="-rf"||m==="-fr"?(f=!0,h=!0):m==="-r"||m==="-R"||m==="--recursive"?f=!0:m==="-f"||m==="--force"?h=!0:u.push(m),g++}let y=["Remove-Item"];if(f&&y.push("-Recurse"),h&&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(","))}r.push(...y),c=g-1;continue}if(l==="cp"&&n&&Hn()){let u=[],f=!1,h=!1,g=c+1;for(;g<t.length;){let m=t[g];if([">",">>","<","&","&&","|","||",";"].includes(m))break;m==="-r"||m==="-R"||m==="--recursive"?f=!0:m==="-f"||m==="--force"?h=!0:u.push(m),g++}let y=["Copy-Item"];if(f&&y.push("-Recurse"),h&&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])}r.push(...y),c=g-1;continue}if(l==="touch"&&n&&Hn()){let u=[],f=c+1;for(;f<t.length;){let h=t[f];if([">",">>","<","&","&&","|","||",";"].includes(h))break;u.push(h),f++}if(u.length>0){let g=`(${u.map(y=>{let m=y.replace(/^['"]|['"]$/g,""),w=y;return a(m)&&(w=y.replace(/\//g,"\\")),w}).join(", ")}) | ForEach-Object { if (Test-Path $_) { (Get-Item $_).LastWriteTime = [System.DateTime]::Now } else { $null | Out-File -FilePath $_ } }`;r.push(g)}c=f-1;continue}if(l==="|"&&t[c+1]==="tee"){t[c+2]==="-a"?(r.push(">>"),c+=2):(r.push(">"),c+=1);continue}if(l==="|"&&t[c+1]==="cat"&&t[c+2]===">"){r.push(">"),c+=2;continue}if(l==="|"){let u=t[c+1];if(u){let f=u.replace(/^['"]|['"]$/g,""),h=/\.(txt|md|json|log|csv|html|css|py|js|xml|yaml|yml|pdf|docx|pptx|xlsx)$/i.test(f);if(a(f)&&h){r.push(">");continue}}}r.push(l)}let p=!1,d=r.map(c=>{if(c==="echo")return p=!0,c;[">",">>","<","&","&&","|","||",";"].includes(c)&&(p=!1);let u=/^['"]|['"]$/.test(c),f=c;p&&u&&(f=c.replace(/^['"]|['"]$/g,""));let h=/^['"]|['"]$/.test(f),g=f.replace(/^['"]|['"]$/g,"");a(g)&&(f=f.replace(/\//g,"\\"));let y=f.replace(/^['"]|['"]$/g,"");return y.includes(" ")&&!h&&(f=`"${y}"`),f});if(n){let c="",l=0;for(let u=0;u<d.length;u++){let f=d[u];f==="&&"?(c+="; if ($?) {",l++):f===";"?(c+=" }".repeat(l)+";",l=0):(c&&!c.endsWith(" ")&&!c.endsWith("{")&&(c+=" "),c+=f)}return c+=" }".repeat(l),c}return d.join(" ")},si=async(e,n={})=>{let{command:t}=I(e),{onChunk:o}=n;if(!t)return'ERROR: Missing "command" argument for exec_command.';let s=process.platform==="win32",i=n.systemSettings||{},a={};return i.networkAccess===!1&&(a.HTTP_PROXY="http://127.0.0.1:9999",a.HTTPS_PROXY="http://127.0.0.1:9999",a.ALL_PROXY="socks5://127.0.0.1:9999",a.http_proxy="http://127.0.0.1:9999",a.https_proxy="http://127.0.0.1:9999",a.all_proxy="socks5://127.0.0.1:9999",a.NO_PROXY="localhost,127.0.0.1"),new Promise(r=>{let p=d=>{let c=d==="pwsh"||d==="powershell",l=ni(t,c),u;s?d==="pwsh"?u="C:\\Users\\User\\AppData\\Local\\Microsoft\\WindowsApps\\pwsh.exe":d==="powershell"?u="powershell.exe":u="cmd.exe":u=process.env.SHELL||"bash";let f=s?c?["-NoProfile","-Command",l]:["/c",l]:["-c",l];if(i.networkAccess===!1&&!s){let h=u,g=[...f];if(process.platform==="linux")u="unshare",f=["-n","-r",h,...g];else if(process.platform==="darwin"){let y=`(version 1)
7
- (allow default)
8
- (deny network-outbound)
9
- (allow network-outbound (remote ip "localhost:*"))
10
- (allow network-outbound (remote ip "127.0.0.1:*"))
11
- `;u="sandbox-exec",f=["-p",y,h,...g]}}if(So)try{let h=So.spawn(u,f,{name:"xterm-256color",cols:n.cols||120,rows:n.rows||30,cwd:process.cwd(),env:{...process.env,CI:"false",TERM:"xterm-256color",FORCE_COLOR:"1",...a}});gt=h,Ks=!0;let g="",y=!1;return h.onData(m=>{if(!y){g+=m,o&&o(m);let w=To(g);/(?:Network:\s+use\s+--host\s+to|Network:\s+Type\s+--host\s+to|Local:\s+http:\/\/localhost:\d+|ready in \d+\s*ms|Compiled successfully|Development server is running|Listening on:)/i.test(w)&&(y=!0,setTimeout(()=>r(`SUCCESS: Dev server started successfully in background.
12
-
13
- ${w}`),500))}}),h.onExit(({exitCode:m})=>{if(y)return;gt=null;let w=ti(g||""),x=To(w).replace(/\n{3,}/g,`
14
-
15
- `)||"Command executed with no output.";r(m!==0?`ERROR: Command [${t}] failed with exit code [${m}].
16
-
17
- ${x}`:`SUCCESS: Command [${t}] completed.
18
-
19
- ${x}`)}),!0}catch(h){return s&&(d==="pwsh"||d==="powershell")&&h.code==="ENOENT"?!1:(Ro(r,l,t,a,o,d,i),!0)}else return Ro(r,l,t,a,o,d,i),!0};s?p("pwsh")||p("powershell")||p("cmd"):p("bash")})},Ro=(e,n,t,o,s,i="powershell",a={})=>{let r=process.platform==="win32",p=i==="pwsh"||i==="powershell",d;r?i==="pwsh"?d="C:\\Users\\User\\AppData\\Local\\Microsoft\\WindowsApps\\pwsh.exe":i==="powershell"?d="powershell.exe":d="cmd.exe":d=process.env.SHELL||"bash";let c=r?p?["-NoProfile","-Command",n]:["/c",n]:["-c",n];if(a.networkAccess===!1&&!r){let g=d,y=[...c];if(process.platform==="linux")d="unshare",c=["-n","-r",g,...y];else if(process.platform==="darwin"){let m=`(version 1)
20
- (allow default)
21
- (deny network-outbound)
22
- (allow network-outbound (remote ip "localhost:*"))
23
- (allow network-outbound (remote ip "127.0.0.1:*"))
24
- `;d="sandbox-exec",c=["-p",m,g,...y]}}let l=r?ei(d,c,{cwd:process.cwd(),env:{...process.env,...o}}):ei(d,c,{cwd:process.cwd(),env:{...process.env,CI:"false",TERM:"xterm-256color",FORCE_COLOR:"1",...o}});gt=l,Ks=!1,l.stdin&&l.stdin.on("error",()=>{gt=null});let u="",f="",h=!1;l.stdout.on("data",g=>{if(!h){let y=g.toString();u+=y,s&&s(y);let m=To(u);/(?:Network:\s+use\s+--host\s+to|Network:\s+Type\s+--host\s+to|Local:\s+http:\/\/localhost:\d+|ready in \d+\s*ms|Compiled successfully|Development server is running|Listening on:)/i.test(m)&&(h=!0,setTimeout(()=>e(`SUCCESS: Dev server started successfully in background.
25
-
26
- ${m}`),500))}}),l.stderr.on("data",g=>{if(!h){let y=g.toString();f+=y,s&&s(y)}}),l.on("close",g=>{if(h)return;gt=null;let y=[],m=ti(u),w=ti(f);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=To(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(r&&g.code==="ENOENT"){if(i==="pwsh"){let m=ni(t,!0);return Ro(e,m,t,o,s,"powershell",a)}else if(i==="powershell"){let m=ni(t,!1);return Ro(e,m,t,o,s,"cmd",a)}}gt=null;let y=g instanceof Error?g.message:String(g);e(`ERROR: Failed to start command [${t}]: ${y}`)})};var Ys=null,Hn=()=>{if(process.platform!=="win32")return!1;if(Ys!==null)return Ys;try{Va('powershell.exe -NoProfile -Command "exit"',{stdio:"ignore"}),Ys=!0}catch{Ys=!1}return Ys},oi=null,br=(e,n,t,o,s=!1,i=!0)=>{oi===null&&(oi=s);let a=`- JSON escape literal escape sequences in tool arguments
37
- - Same file, multiple edits? One PatchFile (\u226415 blocks) \u2190 Priority
38
- - Tool denied? Ask for guidance \u2190 mandatory
39
- - Need text or huge file? CodeSearch > Full Read
40
- - Avoid unnecessary large file chunk reads
41
- - Dont hallucinate tool results, verify, fix errors
42
- - Stuck on syntax error? Tell user > waste time
43
- `,r=`**Workspace Tools (path = relative; first argument, path separator: '/')**
44
- - [tool:functions.ReadFile(path="...", startLine="int", endLine="int")]${o!=="Google"?`${t?". Supports images/docs":""}`:". Supports images/docs"}
45
- - [tool:functions.ReadFolder(path="...", recurse="int 1-3")]. Minimize recursion
46
- - [tool:functions.PatchFile(path="...", allowMultiple="bool, default: 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
- - [tool:functions.WriteFile(path="...", content="...")]. Creates/Overwrites. File Exist? PatchFile > WriteFile
48
- - [tool:functions.CodeSearch(keyword="...", path="dir/file/glob/regex, inclusion/exclusion ;-separated", fuzzy="bool false", regex="bool auto")]. Find definitions, logic, relevant code, standard junk auto-excluded
49
- - [tool:functions.Run(command="...")]. Runs ${n==="Windows"?Hn()?"powershell":"windows CMD":"bash"} command. Destructive/Irreversible ops \u2192 Ask user
50
- - [tool:functions.Goal(method="create/append/get", tasks=[string array], markDone=[task array])]. If long multi-task: create Goals before starting. \`get + markDone\` to mark complete. Update every turn when created
51
- ${oi?'\n**Emergency Tools**\nInfo: `initial` = current task prompt. Revert `id` = turn before disaster (eg. disaster: `turn_3` \u2192 revert: `turn_2`). Reason explicitly\n- [tool:functions.EmergencyRollback(method="getCheckpoint/forceRevert", id="...")]. Rollback workspace in this agent loop. ONLY for catastrophic corruption. Before ending, verify no catastrophe. `id` omitted for `getCheckpoint`\n':""}${i?`
52
- **Sub Agent Tools**
53
- proactive use highly recommended. Prefer for any task, no user nudge needed
54
- Invocations:
55
- \u2022 Invoke (async/background, \u22647 parallel). Parallelize long tasks. May take time
56
- \u2022 InvokeSync (sync/blocking). Sequential, repetitive or delegated tasks. Saves tokens/cost
57
- - [tool:functions.InvokeSync/Invoke(title="...", task="...")]. Task must be detailed: exact file paths, imports/exports, dependencies
58
- - [tool:functions.Await(id="...", timeout="integer")]. Event-driven wait
59
- - [tool:functions.GetProgress(id="...")]. Poll sparingly; NO initial poll. Work or await. Never end while subagent runs
60
- - [tool:functions.Steer(id="...", message="...")]. Inject additional instruction or redirection into active async subagent
61
- - [tool:functions.Cancel(id="...")]. Cancel async task ONLY if stalled (2m+) or incorrect`:""}`,p=`**Creative Tools (path = relative; first argument, path separator: '/')**
62
- - [tool:functions.WritePDF(path="...", content="...", orientation="...")]. Proactive A4 page breaks must in css. HTML/CSS for premium layout, stable margins & headers/footers, no watermarks
63
- - [tool:functions.WriteDoc(path="...", content="...")]. A4 Word document, no watermarks, stable margins & headers/footers`,d=`**Computer Use Tools (GUI Desktop Automation)**
64
- - [tool:functions.Click(gridId="integer", type="single/double", button="left/middle/right", intendedClickText="target text")]. Click target grid number, intendedClickText: literal text/icon on screen (OCR scannable, upto 3 words). Double click desktop icons
65
- - [tool:functions.Drag(fromGridId="integer", toGridId="integer")]. Drag mouse from start grid number to target grid number
66
- - [tool:functions.Scroll(direction="up/down", gridId="mouse hover area")]. Scroll viewport vertically
67
- - [tool:functions.KeyboardTyping(text="string", autoPressEnter="bool")]. Type text string into currently active input. JSON escape literal escape sequences
68
- - [tool:functions.KeyPress(key="key or ;-separated combination, eg: enter, back, backspace, clearInput, ctrl;c, alt;tab, f5, f11, alt;f4")]. Press key, shortcut, function key (f1-f12), or clear active input field.
69
- - [tool:functions.RecaptureScreen()]. Request fresh gridded screenshot`;return`
70
- -- TOOLS --
71
- To use tools, must output exactly '[tool:functions.ToolName(arg1="value1")]' structured string in chat response \u2190 no exception
72
- Tool Rules:
73
- - Max 3 tool calls/turn${e==="Flux"||e.toLowerCase()==="fluxcu"?" (Todo: 3+)":""}
74
- ${e==="Flux"||e.toLowerCase()==="fluxcu"?`${a}`:""}
75
- **User Communication**
76
- - [tool:functions.Ask(question="...", optionA="title::description", ...MAX4)]. Ambiguity, path divergence, security risk. Ask, dont finish/guess. Keep titles short
77
-
78
- **Web Tools**
79
- - [tool:functions.WebSearch(query="...", aiMode="bool", limit="integer 3-10 aiMode: exclude")]. Proactive use for unknown info/docs. aiMode: LLM search
80
- - [tool:functions.WebScrape(url="...")]. Proactive use for specific webpage/docs/api
81
-
82
- ${e==="ICU"?`${d}`:e==="FluxCU"?`${r}
83
- ${d}`:e==="Flux"?`${r}`:`${p}`}`.trim()};var kr=(e=!0,n=!0)=>`
84
- To use tools, must output exactly '[tool:functions.ToolName(arg1="value1")]' structured string in chat response \u2190 no exception
85
-
86
- -- Chat Management Tools --
87
- - [tool:functions.Chat(title="<short creative title of FULL conversation in 3 or 4 words>")]. Consider full chat context to generate title NOT just latest message
88
- - [tool:functions.Memory(action="temp", content="<summary of the user prompt & model responses only from latest prompt under 40 words>. [Talked on: <date> <hour>]")]. Time format: YYYY-MM-DD HH am/pm
89
-
90
- ${e?`-- User-specific long-term/permanent memory (use based on conversation context, do not re-save memory which is already saved) --
91
- - Add: [tool:functions.Memory(action="user", method="add", content="<string to add>. [Saved on: <date ONLY>]", score=2)] (Set score=2 ONLY if the user explicitly asked to "remember" or "save" this information, else omit this parameter entirely)
92
- - Delete: [tool:functions.Memory(action="user", method="delete", id="<memory id>")]
93
- - Update: [tool:functions.Memory(action="user", method="update", content-new="string to update", id="<memory id>")]
94
-
95
- -- Memory Relevance Decay Tool --
96
- - Score Adjustment: [tool:functions.addMemScore(id="<memory id>")]
97
- 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
98
-
99
- Explicit Triggers for permanent memory:
100
- - User explicitly asks to 'remember' something
101
- - User mentions something important long-term that should be remembered
102
- - User provides information that could be useful for long-term reference
103
- - User shares personal information or preferences
104
-
105
- Usage Rules:
106
- - Frequency for 'user' action: Based on explicit triggers.
107
- - If you want to save something, but similar memory already exists, use the update method not add
108
- - Chat title is mandatory
109
- - Temporary memory is mandatory
110
- - When called user memory, still use Temporary Memory
111
- - Must not ignore any tool calls in given context of chat between user & agent`:""}`.trim();var Eo={xHigh:`Effort: High
112
- Challenge assumptions, verify before concluding, prefer the simplest correct solution, assess architecture, scalability & trade-offs, verify dependencies, regressions, failure modes & modular design, plan: files, modules, interfaces & tests
113
- Continuous analysis, verify from first principles, seek failure paths, verify imports, tool results & system stability; avoid syntax errors
114
- MANDATORY: Full technical verification`,High:`Effort: High
115
- Rigorous thinking, prefer the simplest correct solution, assess architecture, performance & maintainability, verify error handling, assumptions, edge cases, dependencies & regressions, plan: files, functions, logic & interactions
116
- Continuous analysis, verify from first principles, seek failure paths, verify imports, tool results & system stability; avoid syntax errors
117
- MANDATORY: Full technical verification`,Medium:`Effort: Medium
118
- 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
119
- Logical, implementation-focused, efficient, deliberate, verify imports, tool results & system stability; avoid syntax errors
120
- MANDATORY: Brief verification for technical tasks/greetings`,Minimal:`Effort: Low
121
- Quick, focused thinking, intent & complexity, required tools/files/actions, before acting
122
- Brief thoughts, think only enough to avoid mistakes, verify imports, tool results & system stability; avoid syntax errors`,Off:`Effort: Lowest
123
- No thinking. Immediate response
124
- Verify imports, tool results & system stability; avoid syntax errors`};import Tr from"fs";import Xa from"screenshot-desktop";var Rr=!1;(async()=>{try{let e=await Ft();if(Number(e?.display)===1){let n=await Xa.listDisplays();n&&n.length>1&&(Rr=!0)}}catch{}})();var ii=null,Sr=null,Vs=null,id=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",Qa=process.env.NO_DEV||!1,Za=(e,n)=>{if(!n)return"";if(e!==Sr||Vs===null){Sr=e;try{let t=X(Dt,[]);Array.isArray(t)&&t.length>0?Vs=t.map(o=>`- ${o.memory}`).join(`
125
- `):Vs=""}catch(t){Vs="",Tr.appendFileSync(`${fn}/memory/error.txt`,`${t.message}
126
- -------------------------------------------------
127
-
128
- `)}}return Vs},Er=(e="",n="",t=!0,o=!1)=>{if(typeof n=="boolean"&&(o=t,t=n,n=""),!t)return"";let s=e?.length>0&&!o?`-- Recent context from other chats (Priority: Low, Focus: Chat Context > Recent) --
129
- ${e}`:"";return s?`${s}`:""},$r=(e,n,t,o,s=!0,i=!1,a="Google",r=!1,p,d)=>{let c=!1;process.env.forcedReasoning&&process.env.NVIDIA_BASE_URL&&a.toUpperCase()==="NVIDIA"&&(c=!0);let l="";if(!p&&a==="Google"){let E=n;n==="Fast"&&(E="Off"),n==="Low"&&(E="Minimal"),n==="Standard"&&(E="Medium"),(n==="xHigh"||n==="Max")&&(E="xHigh"),l=Eo[E]||Eo.Medium}if(p||a!=="Google"){let E={Fast:"Lowest",Low:"Low",Medium:"Medium",Standard:"Medium",High:"High",xHigh:"High",Max:"High"};l=Eo.xHigh,l=l.replace("Effort: High",`Effort: ${E[n]}`).replace(`
130
- MANDATORY: Full technical verification`,""),n==="Fast"?l=`Effort: Lowest
131
- No thinking. Immediate response
132
- Verify imports, tool results & system stability; avoid syntax errors`:n==="Low"&&(l=`Effort: Low
133
- Quick, focused thinking, intent & complexity, required tools/files/actions, before acting
134
- 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",f=e.instructions&&e.instructions?.length>0?`User Preferences: ${e.instructions}
135
-
136
- `:"",h=e.nickname&&e.nickname?.length>0?`User Nickname: ${e.nickname}
137
- ${f.length?"":`
138
- `}`:"",g=e.name&&e.name?.length>0?`User Name: ${e.name}
139
- ${h.length||f.length?"":`
140
- `}`:"",y=process.cwd(),m=Za(d,s),w=m?.length>0?`--- Saved Memories ---
141
- ${m}
142
-
143
- `:"",x=(()=>{let E=process.cwd().toLowerCase();if(process.platform==="win32"){let S=process.env.SystemRoot?.toLowerCase()||"c:\\windows",T=process.env.ProgramFiles?.toLowerCase()||"c:\\program files",$=process.env["ProgramFiles(x86)"]?.toLowerCase()||"c:\\program files (x86)";return E.startsWith(S)||E.startsWith(T)||E.startsWith($)}else return E==="/"||["/bin","/sbin","/etc","/usr","/var","/root"].some(T=>E.startsWith(T))})(),k=[{name:"Fluxflow.md",desc:"HIGH PRIORITY"},{name:"README.md",desc:"Goals"},{name:"Agent.md",desc:"Standards"},{name:"Skills.md",desc:"Workflows"},{name:"design.md",desc:"UI/UX"},{name:"architecture.md",desc:"System Structure"}];if(i||ii===null){let E=k.filter(S=>Tr.existsSync(S.name));ii=t==="Flux"&&E.length>0?`
144
- -- PROJECT CONTEXT --
145
- ${E.map(S=>`- ${S.name}: ${S.desc}`).join(`
146
- `)}
147
- Check these first; These Files > Training Data. Safety rules apply
148
- `:""}let R=ii;return`=== SYSTEM PROMPT ===
149
- Identity: Flux Flow. Sassy, Friendly, CLI Agent${Qa?"":" by Kushal Roy Chowdhury"}
150
- ${t==="Flux"?"Stepwise Execution, Run Automated Tests. Task Completion":t==="Flow"?"Concise, Humorous, Sarcastic":t==="ICU"?"Computer Use Capabilities. Screenshot as ground truth, analyze grid ids overlapping/close to target, keyboard shortcuts > 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"}${Rr&&t.toLowerCase().includes("cu")?`
151
- **Running on secondary screen. Opened app not visible in screenshot? Might be opened on primary. Use 'Ask' immediately with NO options and tell user to move app window to secondary**`:""}
152
-
153
- - OS: ${u}
154
- - Use directory structure for file path resolution${s?`
155
- - Use relative time reference eg. few mins ago
156
- -- Chat Context > Metadata`:""}
157
-
158
- -- THINKING GUIDANCE --
159
- ${a==="Mistral"||a==="Google"&&!p?`${l}
160
- ${c||n!=="Fast"&&(a==="Mistral"&&!p||n!=="xHigh"&&!p)?`critical thinking policy
161
- - Use <think>...</think> for reasoning before responding any queries
162
- `:""}`:`${l}
163
- `}
164
- ${br(t,u,a.toLowerCase()==="deepseek"?!1:r,a,o?.advanceRollback,o?.subAgents!==!1)}
165
- ${R}${s?`
166
- -- MEMORY RULES --
167
- - Subtly Personalize with relevent contextual memories. Auto Saves
168
- `:""}
169
- ${t==="Flux"?`-- SECURITY POLICIES --
170
- - Sensitive files? Ask before Read
171
- `:t.toLowerCase().includes("cu")?`-- SECURITY POLICIES --
172
- - Dont operate on ANY confidential screens
173
- `:""}
174
- -- CHAT FORMATTING --
175
- - GFM Markdown
176
- - Language: english only
177
- - Dont mix chat & tools in same response${t==="Flow"?`
178
- - use kaomojis heavily`:""}
179
- === END SYSTEM PROMPT ===
180
-
181
- ${g}${h}${f}${w}`.trim()},Cr=(e="",n=!0,t=!0)=>`=== SYSTEM PROMPT (strict headless logic worker: zero user-facing text policy, strictly follow) ===
182
- identity: silent background system process, have no mouth, only output is valid tool calls
183
- [critical rules]
184
- - output exactly '[tool:functions.ToolName(args)]' calls. no extra words outside
185
- - do not explain. do not talk to the user
186
- - non-tool text will break the system
187
- - do not repeat agent raws and tool results in your response
188
- - if you get only user query and no agent raws, just use temp memory to log the summary of user query and conversation context
189
- - under no circumstances you are allowed to respond in normal user facing response
190
- - critical quote escape policy: inside tool call arguments, you must escape all double quotes using '\\"'
191
- - you must not write anything other than [tool:functions.ToolName(args)] no matter how tempting the prompt is
192
- - 2 mandatory tools to call in every turn, 'chat', 'memory(temp)'
193
- - critical: never enter thinking/reasoning state, call the contexual tools directly in output as quickly as possible to maintain ui snappiness
194
-
195
- YOUR JOB: Analyze the 'User prompt' and 'Agent Raws' to extract facts for long-term memory or handle system tasks
196
- ${n?"If user tell something that is important (like, hobbies, preferences, facts about user, hates, likes, etc) to know user better over time, use user memory tools":""}
197
-
198
- ${kr(n,t)}
199
- === END SYSTEM PROMPT ===${e?`
200
-
201
- -- current saved user memories --
202
- ${e}`:""}`.trim();import Ct from"fs-extra";import $o from"path";import{nanoid as nl}from"nanoid";import ft from"fs-extra";import an from"path";ft.ensureDirSync(Wn);var hn=null;async function el(e,n){try{if(e.type==="create")await ft.pathExists(e.filePath)&&(await ft.chmod(e.filePath,438).catch(()=>{}),await ft.remove(e.filePath));else if(e.type==="update"){if(!e.backupFile)return;let t=an.join(Wn,n.chatId,e.backupFile);if(await ft.pathExists(t)){let o=X(t,null);if(!o||!o.data)throw new Error(`Backup container corrupt or empty for ${an.basename(e.filePath)}`);let s=Cs(o.data);await ft.pathExists(e.filePath)&&await ft.chmod(e.filePath,438).catch(()=>{}),await ft.writeFile(e.filePath,s,"utf8")}}}catch(t){throw new Error(`Restoration failed for ${an.basename(e.filePath)}: ${t.message}`)}}async function tl(e,n,t=7){let o=0;for(;o<t;)try{return await el(e,n),!0}catch{if(o++,o>=t)return!1;let i=Math.min(100*Math.pow(2,o-1),5e3);await new Promise(a=>setTimeout(a,i))}return!1}var ri=null,ut={async startTransaction(e,n){ri=e,hn={id:`tx_prompt_${Date.now()}`,chatId:e,timestamp:new Date().toISOString(),prompt:n.trim(),changes:[],reverted:!1},he(rs,hn)},async recordFileChange(e,n=null){try{if(!hn){if(ri){let a=X(on,[]),r=[...a].reverse().find(p=>p.chatId===ri);if(r){if(r.changes.some(u=>u.filePath===e))return;let c=await ft.pathExists(e)||n?"update":"create",l=null;if(c==="update"){let u=an.basename(e);l=`${r.id}_${u}.bak`;let f=an.join(Wn,r.chatId);await ft.ensureDir(f);let h=an.join(f,l),g=n!==null?n:await ft.readFile(e,"utf8").catch(()=>null);g!==null?he(h,{data:Gs(g)}):(c="create",l=null)}r.changes.push({filePath:e,type:c,backupFile:l}),he(on,a)}}return}if(hn.changes.some(a=>a.filePath===e))return;let s=await ft.pathExists(e)||n?"update":"create",i=null;if(s==="update"){let a=an.basename(e);i=`${hn.id}_${a}.bak`;let r=an.join(Wn,hn.chatId);await ft.ensureDir(r);let p=an.join(r,i),d=n!==null?n:await ft.readFile(e,"utf8").catch(()=>null);d!==null?he(p,{data:Gs(d)}):(s="create",i=null)}hn.changes.push({filePath:e,type:s,backupFile:i}),he(rs,hn)}catch{}},async commitTransaction(){if(hn)try{let e=X(on,[]);if(e.push(hn),e.length>512e3){let n=e.shift();if(n.changes)for(let t of n.changes)t.backupFile&&await ft.remove(an.join(Wn,n.chatId,t.backupFile)).catch(()=>{})}he(on,e),await ft.remove(rs).catch(()=>{})}catch{}finally{hn=null}},async recoverCrashedTransaction(){try{if(await ft.pathExists(rs)){let e=X(rs,null);if(e?.changes?.length>0){let n=X(on,[]);n.some(t=>t.id===e.id)||(n.push(e),he(on,n))}await ft.remove(rs).catch(()=>{})}}catch{}},async rollbackToBefore(e){let n=X(on,null);if(!n)throw new Error("No transaction ledger found.");let t=n.findIndex(a=>a.id===e);if(t===-1)throw new Error(`Transaction [${e}] not found.`);let o=n[t].chatId,s=n[t].prompt,i=n.slice(t).filter(a=>a.chatId===o&&!a.reverted).reverse();for(let a of i){for(let r of[...a.changes].reverse())await tl(r,a);for(let r of a.changes)if(r.backupFile){let p=an.join(Wn,a.chatId,r.backupFile);await ft.remove(p).catch(()=>{})}n=n.filter(r=>r.id!==a.id),he(on,n)}return{success:!0,chatId:o,targetPrompt:s}},async getChatHistory(e){try{return X(on,[]).filter(t=>t.chatId===e&&!t.reverted)}catch{return[]}},async deleteChatBackups(e){try{await ft.remove(an.join(Wn,e));let n=X(on,[]),t=n.filter(o=>o.chatId!==e);n.length!==t.length&&he(on,t)}catch{}}};var _r=Promise.resolve(),Co=e=>{let n=_r.then(async()=>{try{return await e()}catch(t){throw console.error("Lock Operation Failed:",t),t}});return _r=n.catch(()=>{}),n},ls=async()=>{await Ct.ensureDir($s);let e={};if(await Ct.pathExists(Es))try{e=X(Es,{})}catch{e={}}for(let n in e){let t=$o.join($s,`${n}.json`);Object.defineProperty(e[n],"messages",{get:()=>{if(Ct.existsSync(t))try{return X(t,[])}catch{return[]}return[]},set:o=>{try{he(t,o)}catch{}},enumerable:!1,configurable:!0})}return e},xd=async(e,n,t)=>Co(async()=>{await Ct.ensureDir($s);let o=await ls(),s=o[e],i=(t||[]).filter(y=>!y.isUpdateNotification&&(!y.isMeta||y.text&&y.text.includes("Request Cancelled")));try{(await Ft()).systemSettings?.preserveThinking===!1&&(i=i.filter(m=>m.role!=="think"))}catch{}let a=y=>{if(!y)return;let m=typeof y=="string"?y:y.text||y.content||"";if(!m||typeof m!="string")return;let w=m.replace(/\s*\n+\s*\[Prompted on:.*?\]/g,"").replace(/\[\/?(?:STEERING HINT|QUESTION)(?::\s*\w+)?\]/gi,"").trim();if(!w)return;let 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},r,p=i.filter(y=>y.role==="user"),d=p[0],c=p[p.length-1],l=a(c),u=a(d);s&&s.prompt?Math.random()<.5&&l?r=l:r=s.prompt:r=u||l;let f=n||(s?s.name:`Session ${e.slice(-6)}`),h=$o.join($s,`${e}.json`);he(h,i),o[e]={name:f,prompt:r||void 0,updatedAt:Date.now()};let g={};for(let y in o)g[y]={name:o[y].name,prompt:o[y].prompt||void 0,updatedAt:o[y].updatedAt};he(Es,g)}),Mr=async(e,n)=>Co(async()=>{let t=await ls();t[e]?(t[e].name=n,t[e].updatedAt=Date.now()):t[e]={name:n,updatedAt:Date.now()};let o={};for(let s in t)o[s]={name:t[s].name,prompt:t[s].prompt||void 0,updatedAt:t[s].updatedAt};he(Es,o)}),sl=async e=>Co(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=X(jn,[]);if(Array.isArray(a)){let r=a.filter(p=>Object.keys(p)[0]!==String(e));he(jn,r)}}catch{}let o=X(Qt,{});o[e]&&(delete o[e],he(Qt,o));let s=X(vn,{});s[e]&&(delete s[e],he(vn,s)),await ut.deleteChatBackups(e);let i=$o.join($s,`${e}.json`);if(await Ct.pathExists(i))try{await Ct.remove(i)}catch{}return n}),bd=()=>`flow-${nl(6)}`,kd=async e=>{if(!e||e==="Never")return;let n=parseInt(e);if(isNaN(n))return;let t=await ls(),o=Date.now(),s=n*24*60*60*1e3,i=0;for(let a in t){let r=t[a];r.updatedAt&&o-r.updatedAt>s&&(await sl(a),i++)}return i},ol=e=>{let n=e.replace(/[\[\]]/g,"").trim(),t=new Date(n);if(!isNaN(t.getTime()))return t.getTime();let o=n.split(/,\s*|\s+/);if(o.length===0)return null;let s=o[0],i=o[1]||"",a=o[2]||"",r=s.split(/[-\/.]/).map(Number);if(r.length!==3)return null;let p="en";try{p=Intl.DateTimeFormat().resolvedOptions().locale||"en"}catch{}let d=!/^en[-_]?us$|^en$/.test(p?.toLowerCase()),c,l,u;if(r[0]>1e3)c=r[0],l=r[1],u=r[2];else if(r[2]>1e3)c=r[2],r[0]>12?(u=r[0],l=r[1]):r[1]>12?(u=r[1],l=r[0]):d?(u=r[0],l=r[1]):(l=r[0],u=r[1]);else return null;if(l<1||l>12||u<1||u>31)return null;let f=0,h=0,g=0;if(i){let m=i.split(":").map(Number);f=m[0]||0,h=m[1]||0,g=m[2]||0,a.toLowerCase()==="pm"&&f<12?f+=12:a.toLowerCase()==="am"&&f===12&&(f=0)}let y=new Date(c,l-1,u,f,h,g);return isNaN(y.getTime())?null:y.getTime()},il=async e=>{try{if(!await Ct.pathExists(e))return;let n=await Ct.readFile(e,"utf8");if(!n.trim())return;let t=n.split(`
203
- `),o=[],s=null,i=/^\s*(?:DEBUG|ERROR|SEARCH|PUPPETEER)\b/i;for(let l of t)i.test(l)?(s&&o.push(s),s={header:l,body:[]}):s?s.body.push(l):o.push({header:l,body:[]});s&&o.push(s);let a=10080*60*1e3,r=Date.now(),p=[],d=/(\d{1,4}[-\/.]\d{1,4}[-\/.]\d{1,4}(?:,\s*|\s+)?(?:\d{1,2}:\d{2}:\d{2}(?:\s*[aApP][mM])?)?)/;for(let l of o){if(i.test(l.header)){let h=l.header.match(d);if(h){let g=ol(h[1]);if(g&&r-g>a)continue}}let f=l.header+(l.body.length>0?`
204
- `+l.body.join(`
205
- `):"");p.push(f)}let c=p.join(`
206
- `).trim();c?await Ct.writeFile(e,c+`
207
- `,"utf8"):await Ct.writeFile(e,"","utf8")}catch{}},Sd=async e=>{try{if(!await Ct.pathExists(e))return;let n=async t=>{let o=await Ct.readdir(t);for(let s of o){let i=$o.join(t,s);(await Ct.stat(i)).isDirectory()?(await n(i),(await Ct.readdir(i)).length===0&&await Ct.remove(i)):s.endsWith(".log")&&await il(i)}};await n(e)}catch{}},Ar=(e,n=4)=>{if(e.length<=1)return e;let t=e[0],o=e.slice(1),s=n*2,i=o.slice(s);return[t,...i]};var Td=async(e,n,t)=>Co(async()=>{let o=X(jn,[]);Array.isArray(o)||(o=[]);let s={total:n,context:t},i=o.findIndex(a=>Object.keys(a)[0]===String(e));i!==-1?o[i]={[String(e)]:s}:o.push({[String(e)]:s}),he(jn,o)}),Rd=async e=>{try{if(!await Ct.pathExists(jn))return{total:0,context:0};let n=X(jn,[]);if(!Array.isArray(n))return{total:0,context:0};let t=n.find(o=>Object.keys(o)[0]===String(e));return t?t[String(e)]:{total:0,context:0}}catch{return{total:0,context:0}}};import yt from"fs-extra";import vr from"path";var rl=()=>Math.random().toString(36).substring(2)+Date.now().toString(36),se=null,Gn=null,Ir=0,_s=!1,In={agent:0,background:0,search:0,toolSuccess:0,toolFailure:0,toolDenied:0,duration:0,tokens:0,cachedTokens:0,candidateTokens:0,linesAdded:0,linesRemoved:0,imageCalls:[]},Ms=(e,n)=>{if(!e)return{};let t=Object.keys(e),o=new Date(new Date(n).getTime()-720*60*60*1e3),s={};for(let i of t)new Date(i)>=o&&(s[i]=e[i]);return s},_o=async()=>{let e=new Date().toISOString().split("T")[0];try{!await yt.exists(Xt)&&await yt.exists(Xo)&&(await yt.ensureDir(vr.dirname(Xt)),await yt.move(Xo,Xt))}catch{}let n=Xt+".tmp",t=null;try{if(await yt.exists(n)){let s=(await yt.readFile(n,"utf8")).trim(),i=null;if(s.startsWith("{")||s.startsWith("[")?i=JSON.parse(s):i=JSON.parse(Cs(s)),i&&i.date&&i.stats){t=i;try{await yt.rename(n,Xt)}catch{}}else try{await yt.remove(n)}catch{}}}catch{try{await yt.remove(n)}catch{}}if(!t)try{if(await yt.exists(Xt)){let s=(await yt.readFile(Xt,"utf8")).trim();s.startsWith("{")||s.startsWith("[")?t=JSON.parse(s):t=JSON.parse(Cs(s))}}catch{}let o=t;if(o){let s=o.stats||{...In},i={...In,...s};Array.isArray(i.imageCalls)||(i.imageCalls=[]);let a=o.history||{},r=Ms(a,e);if(Object.keys(a).length!==Object.keys(r).length&&(_s=!0),o.date===e)return{...o,stats:i,history:r};{let p=o.date,d=i,c={...r};return p&&(c[p]=d),{date:e,stats:{...In},history:Ms(c,e)}}}return{date:e,stats:{...In},history:{}}},ai=async()=>{if(!(!_s||!se))try{await yt.ensureDir(vr.dirname(Xt));let e=null;try{if(await yt.exists(Xt)){let s=(await yt.readFile(Xt,"utf8")).trim();s.startsWith("{")||s.startsWith("[")?e=JSON.parse(s):e=JSON.parse(Cs(s))}}catch{}if(e&&e.date===se.date&&e.stats){for(let s in se.stats)if(e.stats[s]!==void 0){if(Array.isArray(se.stats[s])){let i=Array.isArray(e.stats[s])?e.stats[s]:[],a=se.stats[s],r=new Map;for(let p of[...i,...a])p&&p.timestamp&&r.set(p.timestamp,p);se.stats[s]=Array.from(r.values())}else if(typeof se.stats[s]=="number")se.stats[s]=Math.max(se.stats[s],Number(e.stats[s])||0);else if(se.stats[s]&&typeof se.stats[s]=="object"){let i=e.stats[s]||{},a=se.stats[s];for(let r in i)if(typeof i[r]=="number")a[r]=Math.max(a[r]||0,i[r]);else if(i[r]&&typeof i[r]=="object"){a[r]||(a[r]={});for(let p in i[r])if(typeof i[r][p]=="number")a[r][p]=Math.max(a[r][p]||0,i[r][p]);else if(i[r][p]&&typeof i[r][p]=="object"){a[r][p]||(a[r][p]={});for(let d in i[r][p])a[r][p][d]=Math.max(a[r][p][d]||0,i[r][p][d])}}}}}if(e&&e.history){let s={...se.history||{}};for(let i in e.history)if(s[i])for(let a in s[i])if(a==="imageCalls"){let r=Array.isArray(e.history[i].imageCalls)?e.history[i].imageCalls:[],p=Array.isArray(s[i].imageCalls)?s[i].imageCalls:[],d=new Map;for(let c of[...r,...p])c&&c.timestamp&&d.set(c.timestamp,c);s[i].imageCalls=Array.from(d.values())}else typeof s[i][a]=="number"&&(s[i][a]=Math.max(s[i][a],Number(e.history[i][a])||0));else s[i]=e.history[i];se.history=Ms(s,se.date||today)}else if(se&&se.history){let s=new Date().toISOString().split("T")[0];se.history=Ms(se.history,s)}se.saveId=rl();let n=Xt+".tmp",t=Gs(JSON.stringify(se,null,2));await yt.writeFile(n,t,"utf8");let o=await yt.open(n,"r+");await yt.fsync(o),await yt.close(o),await yt.rename(n,Xt),_s=!1,Ir=Date.now()}catch{}},Mo=()=>{if(_s=!0,Gn)return;let e=Date.now(),n=Math.max(0,1500-(e-Ir));Gn=setTimeout(async()=>{await ai(),Gn=null},n),Gn.unref&&Gn.unref()},vd=async()=>{se=await _o(),_s&&Mo()},Id=async()=>{Gn&&(clearTimeout(Gn),Gn=null),await ai()},Tn=async()=>{let e=new Date().toISOString().split("T")[0];if(!se)se=await _o();else if(se.date!==e){let n=se.date,t=se.stats,o=se.history||{};t&&(o[n]=t),se={date:e,stats:{...In},history:Ms(o,e)},_s=!0,await ai()}return se&&se.stats&&!Array.isArray(se.stats.imageCalls)&&(se.stats.imageCalls=[]),se.stats},al=async()=>{let e=new Date().toISOString().split("T")[0];se||(se=await _o()),se.date!==e&&await Tn();let n=se.history||{},t=Ms(n,e);se.history=t;let o=se.stats||{...In},s={...In};s.imageCalls=[],s.models={};let i=(a,r)=>{for(let p in a)if(p==="imageCalls")a.imageCalls=[...a.imageCalls||[],...r.imageCalls||[]];else if(p==="models"){let d=r.models||{};for(let c in d){a.models[c]||(a.models[c]={});for(let l in d[c]){a.models[c][l]||(a.models[c][l]={tokens:0,cachedTokens:0,candidateTokens:0});let u=a.models[c][l],f=d[c][l];u.tokens+=f.tokens||0,u.cachedTokens+=f.cachedTokens||0,u.candidateTokens+=f.candidateTokens||0}}}else typeof a[p]=="number"&&(a[p]+=r[p]||0)};i(s,o);for(let a in t)i(s,t[a]);return s},It=async(e,n)=>{e==="toolSuccess"?Js.toolSuccess++:e==="toolFailure"?Js.toolFailure++:e==="toolDenied"&&Js.toolDenied++;let t=await Tn();t[e]!==void 0&&t[e]++,n&&e==="agent"&&(t.providerRequests||(t.providerRequests={}),t.providerRequests[n]=(t.providerRequests[n]||0)+1),Mo()},Js={linesAdded:0,linesRemoved:0,toolSuccess:0,toolFailure:0,toolDenied:0},qt=async(e,n,t,o)=>{e==="linesAdded"?Js.linesAdded+=n:e==="linesRemoved"&&(Js.linesRemoved+=n);let s=await Tn();if(s[e]!==void 0&&(s[e]+=Math.floor(n)),t&&o&&(e==="tokens"||e==="cachedTokens"||e==="candidateTokens")){s.models||(s.models={}),s.models[t]||(s.models[t]={}),s.models[t][o]||(s.models[t][o]={tokens:0,cachedTokens:0,candidateTokens:0});let i=s.models[t][o];e==="tokens"&&(i.tokens+=Math.floor(n)),e==="cachedTokens"&&(i.cachedTokens+=Math.floor(n)),e==="candidateTokens"&&(i.candidateTokens+=Math.floor(n))}Mo()},ll=async(e=1)=>{let n=new Date,t=n.toISOString().split("T")[0];se||(se=await _o()),se.date!==t&&await Tn();let o=n.getFullYear(),s=n.getMonth();n.getDate()<e&&(s-=1,s<0&&(s=11,o-=1));let r=new Date(o,s,e).toISOString().split("T")[0],p=se.history||{},d=se.stats||{...In},c={...In};c.imageCalls=[],c.models={};let l=(u,f)=>{for(let h in u)if(h==="imageCalls")u.imageCalls=[...u.imageCalls||[],...f.imageCalls||[]];else if(h==="models"){let g=f.models||{};for(let y in g){u.models[y]||(u.models[y]={});for(let m in g[y]){u.models[y][m]||(u.models[y][m]={tokens:0,cachedTokens:0,candidateTokens:0});let w=u.models[y][m],x=g[y][m];w.tokens+=x.tokens||0,w.cachedTokens+=x.cachedTokens||0,w.candidateTokens+=x.candidateTokens||0}}}else typeof u[h]=="number"&&(u[h]+=f[h]||0)};l(c,d);for(let u in p)u>=r&&u<t&&l(c,p[u]);return c},li=async(e,n={})=>{let t=await Ft().catch(()=>({})),o=n.apiTier||t.apiTier||"Free",s=n.quotas||n.systemSettings?.quotas||t.quotas||{},i=s.providerBudgets||{},a=!!i.__useProvider,r=n.aiProvider||t.aiProvider||"Google",p=a&&!!i[r],d=()=>{if(p){let c=i[r];return{agentLimit:typeof c.agentLimit=="number"&&c.agentLimit>0?c.agentLimit:99999999,tokenLimit:typeof c.tokenLimit=="number"&&c.tokenLimit>0?c.tokenLimit:99999999999999,monthlyTokenLimit:typeof c.monthlyTokenLimit=="number"&&c.monthlyTokenLimit>0?c.monthlyTokenLimit:99999999999999}}return{agentLimit:s.agentLimit||99999999,tokenLimit:s.tokenLimit||99999999999999,monthlyTokenLimit:s.monthlyTokenLimit||99999999999999}};if(e==="agent"){let{agentLimit:c,tokenLimit:l,monthlyTokenLimit:u}=d(),f=await Tn(),h;s.resetMode==="Custom"?h=await ll(s.resetDay||1):h=await al();let g=0,y=0,m=0;if(p){g=f.providerRequests?.[r]||0;let w=f.models?.[r]||{};for(let k in w)y+=w[k]?.tokens||0;let x=h.models?.[r]||{};for(let k in x)m+=x[k]?.tokens||0}else g=f.agent||0,y=f.tokens||0,m=h.tokens||0;return o==="Free"&&f.agent+f.background>=999999?{allowed:!1,reason:"Free Tier Daily Usage Limit Exceeded"}:g>=c?{allowed:!1,reason:p?`Daily Request Limit Reached for ${r}`:"Daily Agent Request Limit Reached"}:y>=l?{allowed:!1,reason:p?`Daily Token Budget Exhausted for ${r}`:"Daily Token Budget Exhausted"}:m>=u?{allowed:!1,reason:p?`Monthly Token Budget Exhausted for ${r}`:"Monthly Token Budget Exhausted"}:{allowed:!0}}if(e==="background"){let c=await Tn();if(o==="Free"&&c.agent+c.background>=999999)return{allowed:!1,reason:"Free Tier Background Limit Exceeded"};let l=c.background<(s.backgroundLimit||999999);return{allowed:l,reason:l?void 0:"Background Request Limit Exceeded"}}if(e==="search"){let l=(await Tn()).search<(s.searchLimit||100);return{allowed:l,reason:l?void 0:"Search Quota Exceeded"}}return{allowed:!0}},Or=async(e,n={})=>(await li(e,n)).allowed,ci=e=>{if(!e||e.length===0)return[];let t=[...e].sort((s,i)=>s.timestamp-i.timestamp),o=[];for(let s of t){if(o.length>0){let i=o[o.length-1];if(s.timestamp>=i.start&&s.timestamp<i.end){i.calls.push(s),i.spent+=s.cost;continue}}o.push({start:s.timestamp,end:s.timestamp+36e5,calls:[s],spent:s.cost})}return o},Lr=(e,n)=>{if(!e||e.length===0)return .025;let o=ci(e);if(o.length===0)return .025;let s=[];for(let l of o){let u=.025;if(s.length>0){let h=s[s.length-1],g=!1;if(s.length>=2){let y=s[s.length-2];h.ratio>=.8&&y.ratio>=.8&&(g=!0)}if(g)u=.015;else{let y=h.limit,m=h.ratio;m>=.8?u=y===.015?.015:y:m<.4?u=Math.min(.025,y+.005):m>=.4&&m<.6?u=Math.min(.025,y+.004):u=Math.min(.025,y+.002)}}let f=u>0?l.spent/u:0;s.push({limit:u,spent:l.spent,ratio:f})}let i=o[o.length-1];if(n<i.end)return s[s.length-1].limit;let a=s[s.length-1].limit,r=a,p=s[s.length-1].ratio,d=i.end,c=0;for(let l=s.length-1;l>=0&&s[l].ratio>=.8;l--)c++;for(;d<=n;){let l=.025;c>=2?l=.015:p>=.8?l=r===.015?.015:r:p<.4?l=Math.min(.025,r+.005):p>=.4&&p<.6?l=Math.min(.025,r+.004):l=Math.min(.025,r+.002),r=l,p=0,c=0,d+=36e5,a=l}return a},Pr=async e=>{let n=e.imageSettings||{keyType:"Default",quality:"Low-High"};if(n.keyType!=="Default")return!0;let o={Low:.001,"Low-High":.002,Medium:.008,"Medium-High":.01,High:.045,Ultra:.0488,Premium:.15}[n.quality]||.002,s=await Tn();s.imageCalls||(s.imageCalls=[]);let i=Date.now(),a=ci(s.imageCalls),r=0;if(a.length>0){let d=a[a.length-1];i>=d.start&&i<d.end&&(r=d.spent)}let p=Lr(s.imageCalls,i);return r+o<=p},Dr=async()=>{let e=await Tn();e.imageCalls||(e.imageCalls=[]);let n=Date.now(),t=ci(e.imageCalls),o=[],s=0,i=0;if(t.length>0){let d=t[t.length-1];n>=d.start&&n<d.end&&(o=d.calls,s=d.spent,i=Math.max(0,Math.ceil((d.end-n)/(60*1e3))))}let a=Lr(e.imageCalls,n),r=Math.max(0,a-s),p=s;return{totalSpent:s,remaining:r,activeCallsCount:o.length,nextResetMin:i,reclaimCost:p,limit:a}},Fr=async e=>{let n=e.imageSettings||{keyType:"Default",quality:"Low-High"},o={Low:.001,"Low-High":.002,Medium:.008,"Medium-High":.01,High:.045,Ultra:.0488,Premium:.1}[n.quality]||.002,s=await Tn();s.imageCalls||(s.imageCalls=[]),s.imageCalls.push({timestamp:Date.now(),cost:o}),Mo()};import Ur from"puppeteer";import Wr from"fs";import jr from"path";import Nr from"os";import Xs from"path";import As from"fs";import{createRequire as cl}from"module";import{fileURLToPath as dl}from"url";var fl=cl(import.meta.url),Br=Xs.dirname(dl(import.meta.url));function cs(){let e=Nr.platform(),n=Nr.arch(),t="",o="",s="";if(e==="win32")t=n==="x64"?"win64":"win32",o="chrome.exe",s=`chrome-${t}`;else if(e==="darwin"){t=n==="arm64"?"mac_arm":"mac";let a=n==="arm64"?"arm64":"x64";o="Google Chrome.app/Contents/MacOS/Google Chrome",s=`chrome-mac-${a}`}else if(e==="linux")t="linux",o="chrome",s="chrome-linux64";else return{};let i=Xs.resolve(Br,"..","..",".puppeteerrc.cjs");if(As.existsSync(i)||(i=Xs.resolve(Br,"..",".puppeteerrc.cjs")),!As.existsSync(i))return{};try{let a=fl(i),r=a.cacheDirectory,p=a.chrome?.version;if(r){if(process.env.PUPPETEER_CACHE_DIR=r,p){let l=Xs.join(r,"chrome",`${t}-${p}`,s,o);if(As.existsSync(l))return{executablePath:l,cacheDirectory:r}}let d=l=>{if(!As.existsSync(l))return null;try{let u=As.readdirSync(l),f=[];for(let h of u){let g=Xs.join(l,h),y;try{y=As.statSync(g)}catch{continue}if(y.isDirectory())f.push(g);else if(h.toLowerCase()===o.toLowerCase()&&(!p||g.includes(p)))return g}if(p){for(let h of f)if(h.includes(p)){let g=d(h);if(g)return g}}for(let h of f)if(!p||!h.includes(p)){let g=d(h);if(g)return g}}catch{}return null},c=d(r);if(c)return{executablePath:c,cacheDirectory:r}}}catch{}return{}}var di=async e=>{let{query:n,limit:t=5,aiMode:o=!1}=I(e);if(!n)return'ERROR: Missing "query" argument for web_search.';let s=3,i=null;if(o){let a=`Query: ${n}
208
-
209
- RESPONSE RULES:
210
- - ANSWER CONCISELY WITH REQUIRED DETAILS UNDER 300 WORDS.
211
- - DO NOT CITE, REFERENCE, OR MENTION SOURCES ANYWHERE BETWEEN THE MAIN RESPONSE.
212
- - DO NOT USE MARKDOWN EXCEPT FOR THE SOURCES SECTION BELOW.
213
- - END THE RESPONSE WITH EXACTLY:
214
-
215
- Sources:
216
- - <URL 1>
217
- - <URL 2>
218
- - <URL 3>
219
-
220
- - LIST ONE RAW URL PER BULLET.
221
- - DO NOT USE MARKDOWN LINKS.
222
- - DO NOT INCLUDE ANY TEXT, NOTES, OR EXPLANATIONS AFTER THE SOURCES SECTION.`;for(let r=1;r<=s;r++){let p=null;try{let d=cs();p=await Ur.launch({headless:!0,executablePath:d.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let c=await p.newPage();await c.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.178 Safari/537.36"),await c.setViewport({width:1366,height:768});let l=r===1?Math.random()*1e3+500:Math.random()*2e3+1e3;await new Promise(C=>setTimeout(C,l));let u=`https://search.brave.com/ask?q=${encodeURIComponent(a)}&source=web`;await c.goto(u,{waitUntil:"domcontentloaded",timeout:18e4});let f=null,h=45e3,g=Date.now();for(;Date.now()-g<h&&(f=await c.evaluate(()=>{let C=Array.from(document.querySelectorAll('.message:not(.user), .answer-text, .llm-content, [data-type="answer"]')),b="";if(C.length>0&&(b=C.map(ie=>ie.innerText.trim()).filter(Boolean).join(`
223
-
224
- `)),b||(b=document.body.innerText),b.includes("anomaly"))throw new Error("ANOMALY_DETECTED");let v=!!document.querySelector('.spinner, .loading, .typing, .streaming, [data-streaming="true"], [data-state="loading"], svg.animate-spin, circle[cx], div[class*="spin"]'),O=C[0]||document.body,P=O?O.innerText.trim():"",W=/^(?:[✓✔]\s*)?Finished/i.test(P)||!!(O&&O.querySelector(".status-finished, .finished")),N=!v&&(W||b.includes("Sources:")&&!v),Y={};return document.querySelectorAll("a[href]").forEach(ie=>{let Me=ie.getAttribute("href")||ie.href||"";if(Me.includes("uddg=")&&(Me=decodeURIComponent(Me.split("uddg=")[1].split("&")[0])),Me.includes("url=")&&(Me=decodeURIComponent(Me.split("url=")[1].split("&")[0])),Me&&(Me.startsWith("http://")||Me.startsWith("https://"))&&!Me.includes("search.brave.com")){let B=ie.innerText.trim();B&&(Y[B]=Me),ie.textContent=Me}}),{isFinished:N,text:b,hrefMap:Y}}),!(f&&f.isFinished));)await new Promise(C=>setTimeout(C,1e3));let y=(f?f.text:"")||"",m=f?f.hrefMap||{}:{},w="DO NOT INCLUDE ANY TEXT, NOTES, OR EXPLANATIONS AFTER THE SOURCES SECTION.";y.includes(w)&&(y=y.split(w).pop()),y=y.replace(/^.*?(Ctrl \+ Shift \+ O|Ask\nAll\nImages)/s,"").replace(/AI-generated answer\. Please verify critical facts\..*/s,"").replace(/Brave Search uses private usage metrics.*/s,"");let x=y,k="";if(y.includes("Sources:")){let C=y.split("Sources:");x=C[0],k=C.slice(1).join("Sources:")}let R=[];for(let C of x.split(`
225
- `)){let b=C.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")||R.push(C))}let E=R.join(`
226
- `).replace(/^(?:[\+\-]?\d+\s*)+/i,"").replace(/\n{3,}/g,`
227
-
228
- `).trim(),S=C=>!C||C.includes("search.brave.com")||C.includes("youtube.com")||C.includes("youtu.be"),T="";if(k){let C=k.match(/https?:\/\/[^\s\)\>]+/g)||[],b=[];for(let O of C){let P=O.replace(/[\.\,\;]+$/,""),W=Object.keys(m).find(N=>N.startsWith(P)||P.startsWith(N));W&&m[W]&&(P=m[W]),S(P)||b.push(P)}Object.values(m).forEach(O=>{!S(O)&&!b.includes(O)&&b.push(O)});let v=Array.from(new Set(b));v.length>0&&(T=`Sources:
229
- `+v.map(O=>`- ${O}`).join(`
230
- `))}let $=E+(T?`
231
-
232
- `+T:"");if(!$||/^(\+\d+|Searching|Answering|Thinking|Finished)$/i.test($))throw new Error("EMPTY_AI_RESPONSE");return await p.close(),`AI Search results for [${n}]:
233
-
234
- ${$}`}catch(d){if(i=d,Wr.writeFileSync(jr.join(fn,"web_tools","search","ai_mode","ERROR.txt"),d.message),p&&await p.close(),r<s){let c=Math.pow(2,r)*1e3;await new Promise(l=>setTimeout(l,c))}}}}for(let a=1;a<=s;a++){let r=null;try{let p=cs();r=await Ur.launch({headless:!0,executablePath:p.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let d=await r.newPage();await d.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.178 Safari/537.36"),await d.setViewport({width:1366,height:768});let c=a===1?Math.random()*1e3+500:Math.random()*2e3+1e3;await new Promise(g=>setTimeout(g,c));let l=`https://html.duckduckgo.com/html/?q=${encodeURIComponent(n)}`;await d.goto(l,{waitUntil:"networkidle2",timeout:18e4});let u=await d.$$eval(".result",(g,y)=>g.slice(0,y).map((m,w)=>{let x=m.querySelector(".result__a"),k=m.querySelector(".result__snippet"),R=x?x.href:"";R.includes("uddg=")&&(R=decodeURIComponent(R.split("uddg=")[1].split("&")[0]));let E=x?x.innerText.trim():"No Title",S=k?k.innerText.trim():"No Snippet";return`${w+1}. ${E}
235
- Source: ${R}
236
- Snippet: ${S}`}),t);if(u.length===0){if((await d.evaluate(()=>document.body.innerText)).includes("anomaly"))throw new Error("ANOMALY_DETECTED");return await r.close(),`No results found for query: [${n}].`}let f=u.join(`
237
-
238
- `);return await r.close(),`${o?`AI Mode temporarily failed, used Standard search.
239
-
240
- `:""}Search results for [${n}]:
241
-
242
- ${f}`}catch(p){if(i=p,r&&await r.close(),Wr.writeFileSync(jr.join(fn,"web_tools","search","standard_mode","ERROR.txt"),p.message),a<s){let d=Math.pow(2,a)*1e3;await new Promise(c=>setTimeout(c,d))}}}return`ERROR: Search failed after ${s+1} attempts. Last error: ${i.message}`};import ul from"puppeteer";import hl from"turndown";import{gfm as pl}from"turndown-plugin-gfm";var fi=async e=>{let n=e;if(typeof e=="object"&&e!==null)n=e.url||e.targetUrl||e.href||"";else if(typeof e=="string"){let i=e.match(/url\s*=\s*["'](.*)["']/);n=i?i[1]:e}let t=typeof n=="string"?n.trim():"";if(!t)return"ERROR: No target URL provided.";let o=3,s=null;for(let i=1;i<=o;i++){let a=null;try{let r=cs();a=await ul.launch({headless:!0,executablePath:r.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let p=await a.newPage();await p.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.178 Safari/537.36"),await p.setViewport({width:1366,height:768});let d=i===1?Math.random()*1e3+500:Math.random()*2e3+1e3;await new Promise(g=>setTimeout(g,d)),await p.goto(t,{waitUntil:"networkidle2",timeout:18e4}),await new Promise(g=>setTimeout(g,5e3));let c=await p.evaluate(()=>{document.querySelectorAll("script, style, noscript, svg, canvas, iframe, ad, .ads, link, meta, img").forEach(k=>k.remove());let y=document.createNodeIterator(document.body,NodeFilter.SHOW_COMMENT),m;for(;m=y.nextNode();)m.remove();for(document.querySelectorAll("*").forEach(k=>{let R=k.attributes;for(let E=R.length-1;E>=0;E--){let S=R[E].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(`
243
-
244
- `))});let x=()=>{let k=!1;document.querySelectorAll("*").forEach(R=>{R.childNodes.length===0&&!R.innerText.trim()&&(R.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,`
245
-
246
- `).replace(/[ \t]+/g," ").replace(/>[ \t]+</g,"><").replace(/\n\s+/g,`
247
- `).replace(/\n{3,}/g,`
248
-
249
- `).trim(),u=new hl({headingStyle:"atx",codeBlockStyle:"fenced"});u.use(pl);let f=u.turndown(l).replace(/\.\s*\n/g,`
250
- `).replace(/ +/g," ").replace(/\t/g," ").replace(/\n\s+/g,`
251
- `).replace(/\n{3,}/g,`
252
-
253
- `),h=f.substring(0,5e4);return await a.close(),`Markdown parsed from [${t}]:
254
-
255
- ${h}${f.length>5e4?`
256
-
257
- [TRUNCATED AT 50K CHARS]`:""}`}catch(r){if(s=r,a&&await a.close(),i<o){let p=Math.pow(2,i)*1e3;await new Promise(d=>setTimeout(d,p))}}}return`ERROR: Scrape failed after ${o+1} attempts. Last error: ${s.message}`};var ml=4*(1024*2),ui=async(e,n={})=>{let t=c=>{let l=new RegExp(`${c}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),u=e.match(l);if(u)return u[2].trim();let f=new RegExp(`${c}\\s*[:=]\\s*([^,\\s)]+)`,"s"),h=e.match(f);return h?h[1].trim():null},o=t("action"),s=t("method"),i=t("content"),a=t("content-new"),r=t("content-old"),p=t("id"),d=t("chat-id")||n.chatId||n.sessionId||"default-session";if(o==="temp"){if(!i)return"ERROR: Missing 'content' for temp memory.";let c=X(Qt,{});c[d]||(c[d]=[]),c[d].push(i),he(Qt,c);let l=c[d].reduce((u,f)=>u+f.length,0);return`SUCCESS: Temporary context saved for session [${d}]. (Size: ${l} chars)`}if(o==="user"){let c=X(Dt,[]).map(l=>(l.score===void 0&&(l.score=.5),l));if(s==="add"){if(!i)return"ERROR: Missing 'content' for memory addition.";let l=new Date,u=`${l.getDate()}/${l.getMonth()+1}/${l.getFullYear()}`,f=i.includes("[Saved on:")?i:`${i.trim()} [Saved on: ${u}]`,h=ml,g=c.reduce((x,k)=>x+(k.memory?.length||0),0);for(;c.length>0&&g+f.length>h;){let x=c.shift();g-=x.memory?.length||0}let y=t("score"),m=y?parseFloat(y):.5,w={id:`mem-${Date.now().toString(36)}`,memory:f,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+f.length} chars)`}if(s==="update"){let l=p||r,u=a||i;if(!l||!u)return"ERROR: Missing 'id' or content for update.";let f=c.findIndex(m=>m.id===l);if(f===-1)return`ERROR: Memory ID [${l}] not found.`;let h=new Date,g=`${h.getDate()}/${h.getMonth()+1}/${h.getFullYear()}`,y=u.includes("[Saved on:")?u:`${u.trim()} [Saved on: ${g}]`;return c[f].memory=y,he(Dt,c),`SUCCESS: Memory [${l}] updated.`}if(s==="delete"){let l=p||i;if(!l)return"ERROR: Missing 'id' for deletion.";let u=c.length,f=c.filter(h=>h.id!==l);return f.length===u?`ERROR: Memory ID [${l}] not found.`:(he(Dt,f),`SUCCESS: Memory [${l}] deleted.`)}return`ERROR: Invalid method [${s}] for user memory. Use 'add', 'update', or 'delete'.`}return`ERROR: Unknown action [${o}] for memory tool.`};var hi=async(e,n={})=>{let t=I(e).title,o=n.chatId||n.sessionId;if(!o)return"ERROR: No active chatId found in tool context.";if(!t)return"ERROR: Missing 'title' argument.";try{return await Mr(o,t),`SUCCESS: Chat title updated to [${t}] for session [${o}].`}catch(s){return`ERROR: Failed to update chat title: ${s instanceof Error?s.message:String(s)}`}};import Ao from"fs";import Hr from"path";var Qs=async(e,n={})=>{let{path:t,StartLine:o,EndLine:s,start_line:i,end_line:a,startLine:r,endLine:p}=I(e),d=parseInt(o||i||r),c=parseInt(s||a||p),l=!isNaN(d),u=!isNaN(c),f=d||1,h=c||(d?d+800:800);if(!t)return'ERROR: Missing "path" argument for view_file.';let g=Hr.resolve(process.cwd(),t);try{if(!Ao.existsSync(g))return`ERROR: File [${t}] does not exist.`;if(Ao.statSync(g).isDirectory())return`ERROR: Path [${t}] is a directory. Use list_files instead.`;let m=Hr.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 P=Ao.readFileSync(g).toString("base64"),W=x[m];return{text:`[BINARY FILE]: ${t} (${W}) - Loaded as multimodal part.`,binaryPart:{inlineData:{data:P,mimeType:W}}}}let k=Ao.readFileSync(g,"utf8");k.startsWith("\uFEFF")&&(k=k.slice(1)),k=k.replace(/\r\n/g,`
258
- `).replace(/\r/g,`
259
- `);let R=k.split(`
260
- `),E=R.length;!l&&!u&&E>800&&(f=1,h=50);let S=Math.max(0,f-1),T=Math.min(E,h),$=R.slice(S,T),C=`File: [${t}] (Showing lines ${S+1}-${T} of ${E}).`,b=$.map((v,O)=>`${String(S+O+1).padStart(4)}: ${v.trimEnd()}`).join(`
261
- `);return`${C}
262
-
263
- ${b}`}catch(y){let m=y instanceof Error?y.message:String(y);return`ERROR: Failed to read file [${t}]: ${m}`}};import vs from"fs";import Gr from"path";var pi=async(e,n={})=>{let{path:t,content:o}=I(e);if(!t)return'ERROR: Missing "path" argument for write_file.';if(o===void 0)return'ERROR: Missing "content" argument for write_file.';o=o.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
264
- `).replace(/\r/g,`
265
- `);let s=Gr.resolve(process.cwd(),t),i=Gr.dirname(s);try{await ut.recordFileChange(s);let a="";if(vs.existsSync(s))try{a=`Old File contents:
266
- ${vs.readFileSync(s,"utf8").split(/\r?\n/).map((R,E)=>`${E+1} | ${R}`).join(`
267
- `)}
268
-
269
- `}catch{a=`[Note: Could not read existing file for reversal reference]
270
-
271
- `}vs.existsSync(i)||vs.mkdirSync(i,{recursive:!0});let p=(x=>x.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
272
- `).replace(/\r/g,`
273
- `))(o),d=p.endsWith(`
274
- `)?p:p+`
275
- `,c=d.split(/\r?\n/).length,l=Buffer.byteLength(d,"utf8");vs.writeFileSync(s,d,"utf8");let u=vs.readFileSync(s,"utf8"),f=Buffer.byteLength(u,"utf8"),h=u.split(/\r?\n/),g=h.length;if(f===0&&l>0)return u=null,`ERROR: CRITICAL FAILURE: Verification failed. File [${t}] is empty on disk!`;let y="";if(g<=100)y=h.join(`
276
- `);else{let x=h.slice(0,50).join(`
277
- `),k=h.slice(-50).join(`
278
- `);y=`${x}
279
-
280
- ... [${g-100} lines truncated] ...
281
-
282
- ${k}`}u=null;let{systemSettings:m}=await Ft(),w=`SUCCESS: File [${t}] saved.
283
- - Stats: [${g} lines, ${(f/1024).toFixed(1)} KB]
284
- ${a}- Content Preview:
285
-
286
- ${y}`;if(m?.compressToolResults&&g>60){let x=d.split(/\r?\n/),k=x.slice(0,25).join(`
287
- `)===h.slice(0,25).join(`
288
- `),R=x.slice(-25).join(`
289
- `)===h.slice(-25).join(`
290
- `);k&&R&&(w=`[[SAME]]
291
- ${w}`)}return w}catch(a){let r=a instanceof Error?a.message:String(a);return`ERROR: Failed to write file [${t}]: ${r}`}};import wi from"fs";import Cl from"path";import gl from"os";var pn=e=>typeof e!="string"?e:e.length>12?(e+"").replace("",""):e,qr=(e,n)=>{if(!e)return"";let t=/\x1B\[[0-?]*[ -/]*[@-~]/g,o=e.split(`
292
- `),s=[];if(n<=5)return e;let i=a=>a.replace(t,"").length;return o.forEach(a=>{if(i(a)<=n){s.push(a);return}let p=a.split(/(\s+)/),d="",c=0,l=a.match(/^(\s*)/),u=l?l[1]:"";p.forEach((f,h)=>{if(f.length===0)return;let g=i(f);if(c+g>n)if(d.trim().length>0)s.push(d.trimEnd()),d=u.substring(0,Math.min(u.length,8))+f,c=i(d);else if(t.test(f))s.push(f),d=u,c=i(d);else{let y=f;for(;i(y)>n&&n>10;)s.push(y.substring(0,n)),y=y.substring(n);d=y,c=i(d)}else d+=f,c+=g}),(d.trimEnd().length>0||d===u)&&s.push(d.trimEnd())}),pn(s.join(`
293
- `))},xf=e=>{if(!e&&e!==0)return"0.0k";let n=typeof e=="string"?parseFloat(e):e;return n>=1e6?`${(n/1e6).toFixed(1)}m`:n>=1e3?`${(n/1e3).toFixed(1)}k`:n.toString()},bf=(e,n=40)=>{let t=An.replaceAll("\\\\","\\");if(e=e.replace(gl.homedir(),"~").replace(t,"FluxFlow").replaceAll("\\","/"),!e||e.length<=n)return pn(e);let o=Math.floor((n-3)/2);return pn(e.substring(0,o)+"..."+e.substring(e.length-o).replaceAll("\\","/"))},vo=e=>{let n=[],t=new Set,o=e.allowMultiple===!0||String(e.allowMultiple).toLowerCase()==="true";Object.keys(e).forEach(p=>{let d=p.match(/^(searchContent|search_content|replaceContent|replace_content|newContent|new_content|content_to_replace|content_to_add|searchBlock|search_block|newBlock|new_block)_?(\d+)?$/i);if(d){let c=d[2]?parseInt(d[2],10):1;t.add(c)}});let s=Array.from(t).sort((p,d)=>p-d),i=["searchContent","search_content","replaceContent","replace_content","content_to_replace","searchBlock","search_block"],a=["newContent","new_content","content_to_add","newBlock","new_block"],r=(p,d,c)=>{let l,u;for(let f of d){let h=p===1?[`${f}1`,f,`${f}_1`]:[`${f}${p}`,`${f}_${p}`];for(let g of h)if(e[g]!==void 0){l=e[g];break}if(l!==void 0)break}for(let f of c){let h=p===1?[`${f}1`,f,`${f}_1`]:[`${f}${p}`,`${f}_${p}`];for(let g of h)if(e[g]!==void 0){u=e[g];break}if(u!==void 0)break}return{r:l,n:u}};for(let p of s){let{r:d,n:c}=r(p,i,a);if(d!==void 0&&c!==void 0)n.push({replace:d,new:c});else if(d!==void 0||c!==void 0)return{error:`Mismatched replacement pair for index ${p}. Both replacement and new content must be provided.`,allowMultiple:o}}return{patchPairs:n,allowMultiple:o}},yl=e=>{if(!e)return null;let n="",t=0,o=e.length;for(;t<o;){let s=e[t];if(s==="\\"){for(;t<o&&e[t]==="\\";)t++;n+="\\\\*"}else if(s===`
294
- `)n+="(?:\\r?\\n|\\\\*n|\\\\*r|\\s*)",t++;else if(s==="\r")n+="(?:\\r|\\\\*r)?",t++;else if(s===" ")n+="(?:\\t|\\\\*t|\\s*)",t++;else if(s==='"'||s==="'"||s==="`")n.endsWith("\\\\*")||(n+="\\\\*"),n+=s,t++;else if(/[.*+?^${}()|[\]]/.test(s))n+="\\"+s,t++;else if(/\s/.test(s)){for(;t<o&&/\s/.test(e[t])&&e[t]!==`
295
- `&&e[t]!=="\r"&&e[t]!==" ";)t++;n+="\\s*"}else n+=s,t++}if(!n)return null;try{return new RegExp(n,"g")}catch{return null}},Io=(e,n,t={})=>{let o=typeof t=="boolean"?t:!!(t&&t.allowMultiple),s=e.replace(/\r\n/g,`
296
- `).replace(/\r/g,`
297
- `),i=m=>m.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
298
- `).replace(/\r/g,`
299
- `),a=m=>m.match(/^\s*/)[0],r=m=>{let w=m.split(`
300
- `).filter(k=>k.trim()!=="");if(w.length===0)return"";let x=a(w[0]);for(let k of w){let R=a(k);R.length<x.length&&(x=R)}return x},p=(m,w,x="")=>{if(!m||w===void 0)return m;let R=/^\t/m.test(w)?" ":" ",E=v=>v.split(`
301
- `).find(O=>O.trim()!=="")??"",S=E(w).match(/^\s*/)[0].length,T=E(m).match(/^\s*/)[0].length,$=S-T,C=(x.match(/^\s*/)||[""])[0].length;return m.split(`
302
- `).map((v,O)=>{if(v.trim()===""&&O!==0)return"";let P=v.match(/^\s*/)[0].length,W=Math.max(0,P+$);return O===0&&(W=Math.max(0,W-C)),R.repeat(W)+v.trimStart()}).join(`
303
- `)},d=[];for(let m=0;m<n.length;m++){let w=n[m],x=(w.replace||"").trim(),k=i(w.new||"");if(x.startsWith("^LINE:")&&x.endsWith("$")){let C=x.slice(6,-1).trim().split(".."),b=parseInt(C[0]),v=C[1]!==void 0?parseInt(C[1]):b;if(!isNaN(b)&&!isNaN(v)){let O=s.split(`
304
- `);if(b<1||b>O.length||v<b||v>O.length){d.push({index:m,success:!1,error:`Block ${m+1}: Line range ^LINE:${b}..${v}$ out of bounds (file has ${O.length} lines).`});continue}let W=O.slice(b-1,v).join(`
305
- `),N=0;for(let Y=0;Y<b-1;Y++)N+=O[Y].length+1;d.push({index:m,success:!0,startPos:N,firstMatchContent:W,content_to_add:k});continue}}let R=i(w.replace||"");if(R===""&&k===""){d.push({index:m,success:!1,error:`Block ${m+1}: Empty replace and add content.`});continue}let E=R.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),S=null;if(R!==""&&s.includes(R))S=new RegExp(E,"g");else{let $=R.split(`
306
- `).map(C=>C.trim()).filter(C=>C.length>0).map(C=>C.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\s+/g,"\\s*"));if($.length>0){let C=$.join("\\s*");try{S=new RegExp(C,"g")}catch{S=new RegExp(E,"g")}}else S=new RegExp(E,"g")}let T=[...s.matchAll(S)];if(T.length===0&&R!==""){let $=yl(R);$&&(T=[...s.matchAll($)])}if(T.length===0){d.push({index:m,success:!1,error:`Block ${m+1}: Could not find match.`});continue}if(T.length>1&&!o){d.push({index:m,success:!1,error:`Block ${m+1}: Found ${T.length} matches (must be unique or use allowMultiple: true if sure).`});continue}for(let $ of T)d.push({index:m,success:!0,startPos:$.index,firstMatchContent:$[0],content_to_add:k})}let c=d.filter(m=>m.success).sort((m,w)=>m.startPos-w.startPos);for(let m=0;m<c.length-1;m++){let w=c[m],x=c[m+1];w.startPos+w.firstMatchContent.length>x.startPos&&(w.success=!1,w.error=`Block ${w.index+1}: Overlaps with another block.`,x.success=!1,x.error=`Block ${x.index+1}: Overlaps with another block.`)}let l=new Map,u=s,f=0,h=0,g=d.filter(m=>m.success).sort((m,w)=>m.startPos-w.startPos);for(let m of g){let w=m.startPos,x=s.substring(0,w).split(`
307
- `).length,k=w+f,R=x+h,E=u.lastIndexOf(`
308
- `,k)+1,S=u.substring(E,k),T=p(m.content_to_add,m.firstMatchContent,S),$=u.split(`
309
- `),C=[];for(let P=Math.max(0,R-4);P<R-1;P++)C.push({num:P+1,text:$[P]});let b=m.firstMatchContent.split(`
310
- `),v=[],O=R+b.length-1;for(let P=O;P<Math.min($.length,O+3);P++)v.push({num:P+1,text:$[P]});l.set(m,{success:!0,index:m.index,oldContent:m.firstMatchContent,newContent:T,originalStartLine:x,finalStartLine:R,contextBefore:C,contextAfter:v}),u=u.substring(0,k)+T+u.substring(k+m.firstMatchContent.length),f+=T.length-m.firstMatchContent.length,h+=T.split(`
311
- `).length-m.firstMatchContent.split(`
312
- `).length}let y=[];for(let m=0;m<n.length;m++){let w=g.filter(x=>x.index===m);if(w.length>0)for(let x of w)l.has(x)&&y.push(l.get(x));else{let x=d.find(k=>k.index===m);y.push({success:!1,error:x?x.error:`Block ${m+1}: Unknown error.`})}}return{content:u,results:y}},Oo=(e,n,t,o=8,s=!1)=>{if(!t||t.length===0)return"";let i=e.split(/\r?\n/),a=n.split(/\r?\n/),r=Math.max(i.length,a.length,1),p=Math.max(4,String(r).length),d=g=>String(g).padStart(p," "),c=`[DIFF_START]
313
- `,l="\u2550".repeat(88),u=0,f=null,h=t.filter(g=>g.success).sort((g,y)=>g.originalStartLine-y.originalStartLine);if(h.forEach((g,y)=>{let m=g.finalStartLine!==void 0?g.finalStartLine:g.originalStartLine;if(f===null)for(u=Math.max(0,m-4);u<m-1;)c+=`[UI_CONTEXT] ${d(u+1)} |${a[u]||""}
314
- `,u++;else{let T=f,$=T.originalStartLine+T.oldContent.split(`
315
- `).length-1;if(g.originalStartLine-$-1>=o){let b=Math.min(a.length,u+3);for(;u<b;)c+=`[UI_CONTEXT] ${d(u+1)} |${a[u]||""}
316
- `,u++;for(c+=`[UI_CONTEXT] ${l}
317
- `,u=Math.max(u,m-4);u<m-1;)c+=`[UI_CONTEXT] ${d(u+1)} |${a[u]||""}
318
- `,u++}else for(;u<m-1;)c+=`[UI_CONTEXT] ${d(u+1)} |${a[u]||""}
319
- `,u++}let w=g.originalStartLine-1,x=i[w]||"",k=g.oldContent.split(`
320
- `),R=x.match(/^\s*/),E=R?R[0]:"";k.forEach((T,$)=>{let C=T;if(k.length===1&&x.trim().length>0&&x.includes(T.trim()))C=x;else if($===0){let b=T.match(/^\s*/);(b?b[0]:"").length<E.length&&x.includes(T.trim())&&(C=E+T.trimStart())}c+=`-${d(g.originalStartLine+$)} |${C}
321
- `});let S=u;if(g.finalStartLine!==void 0)S=g.finalStartLine-1+(g.newContent?g.newContent.split(`
322
- `).length:0);else{let T=g.originalStartLine+k.length-1,$=i[T]||null;if($!==null){let C=y<h.length-1?(h[y+1].originalStartLine||a.length)+10:a.length;for(let b=u;b<C;b++){if(a[b]===$){S=b;break}b===a.length-1&&(S=a.length)}}else S=a.length}for(;u<S;)c+=`+${d(u+1)} |${a[u]||""}
323
- `,u++;f=g}),f!==null){let g=Math.min(a.length,u+3);for(;u<g;)c+=`[UI_CONTEXT] ${d(u+1)} |${a[u]||""}
324
- `,u++}if(s){let g=`[DIFF_START]
325
- `,y=c.substring(g.length),m=`[UI_CONTEXT] ${l}
326
- `,x=y.split(m).map(k=>k.split(`
327
- `).filter(E=>E.trim()!=="").length>45?`[[VERIFIED]]
328
- ${k}
329
- [[/VERIFIED]]`:k);c=g+x.join(m)}return c+="[DIFF_END]",pn(c)},wl=e=>{if(!e)return null;let n=e.replace("[UI_CONTEXT]","").replace(/\r/g,""),t=n.startsWith("-"),o=n.startsWith("+"),s=t||o?n.substring(1):n,i=s.indexOf("|"),a=i!==-1?pn(s.substring(0,i).trim()):"",r=pn(i!==-1?s.substring(i+1):s);return{isR:t,isA:o,num:a,content:r}},xl=(e,n)=>{if(!e&&!n)return 1;if(!e||!n)return 0;let t=e.length,o=n.length,s=e,i=n;t<o&&(s=n,i=e);let a=s.length,r=i.length,p=new Int32Array(r+1),d=new Int32Array(r+1);for(let u=0;u<=r;u++)p[u]=u;for(let u=1;u<=a;u++){d[0]=u;let f=s[u-1];for(let h=1;h<=r;h++)f===i[h-1]?d[h]=p[h-1]:d[h]=Math.min(p[h],d[h-1],p[h-1])+1;p.set(d)}let c=p[r],l=Math.max(t,o);return l===0?1:1-c/l},zr=e=>{let n=[],t=[];e.forEach((c,l)=>{c.parsed.isR?n.push({index:l,content:c.parsed.content}):c.parsed.isA&&t.push({index:l,content:c.parsed.content})});let o=n.length,s=t.length;if(o===0||s===0)return;let i=Array.from({length:o+1},()=>Array(s+1).fill(0)),a=Array.from({length:o+1},()=>Array(s+1).fill(""));for(let c=1;c<=o;c++)a[c][0]="up";for(let c=1;c<=s;c++)a[0][c]="left";let r=Array.from({length:o},()=>Array(s).fill(0));for(let c=0;c<o;c++)for(let l=0;l<s;l++)r[c][l]=xl(n[c].content.trim(),t[l].content.trim());for(let c=1;c<=o;c++)for(let l=1;l<=s;l++){let u=r[c-1][l-1],f=u>=.2?u:-10,h=i[c-1][l-1]+f,g=i[c-1][l],y=i[c][l-1];h>=g&&h>=y?(i[c][l]=h,a[c][l]="diag"):g>=y?(i[c][l]=g,a[c][l]="up"):(i[c][l]=y,a[c][l]="left")}let p=o,d=s;for(;p>0||d>0;)if(a[p][d]==="diag"){if(r[p-1][d-1]>=.2){let l=n[p-1].index,u=t[d-1].index;e[l].pairContent=e[u].parsed.content,e[u].pairContent=e[l].parsed.content}p--,d--}else a[p][d]==="up"?p--:d--},qn=new Map,ds=new Map,Kr=200,mi=6,yi=(e,n)=>{n.set(e.key,e),e.type==="chunk"&&e.blocks&&e.blocks.forEach(t=>yi(t,n))},kf=(e,n)=>{if(!e)return{completed:[],active:[]};let t=`${e.id}-${e.text?.length||0}-${n}-${e.isStreaming}-${e.workedDuration||0}`;if(!e.isStreaming&&qn.has(t))return qn.get(t);let o=pn($l(e.text||"",e.role==="think")),s=`${e.id}-${n}`,i=new Map;if(e.isStreaming){let h=ds.get(s);h&&o.startsWith(h.text)&&(i=h.blocksMap)}let a=(h,g,y,m={})=>{let w=i.get(h);if(w&&w.text===y&&w.type===g&&!!w.isActiveBlock==!!m.isActiveBlock&&!!w.isStreaming==!!m.isStreaming&&w.pairContent===m.pairContent)return w;let x=pn(y),k={...m};return typeof k.pairContent=="string"&&(k.pairContent=pn(k.pairContent)),Array.isArray(k.wrappedLines)&&(k.wrappedLines=k.wrappedLines.map(pn)),{key:h,isStreamingMsg:!!e.isStreaming,workedDuration:e.workedDuration,type:g,text:x,msg:g==="full-message"?e:void 0,...k}};if(o.includes("- Content Preview:")){let h="",g=o.match(/File\s+\[(.*?)\]/i);g&&(h=g[1].split(".").pop().toLowerCase());let k=((o.split("- Content Preview:")[1]||"").split("[SYSTEM] Check the content preview for verification [/SYSTEM]")[0]?.trim()||"").split(`
330
- `).map(b=>b.replace(/\r$/,"")),R=String(k.length).length,E=[],S=null,T=[],$=()=>{if(!T.length)return;let b=T;T=[],E.push(b.length===1?b[0]:{key:`${b[0].key}-chunk`,type:"chunk",blocks:b})},C=n-(R+6);return k.forEach((b,v)=>{let O=v===k.length-1,P=qr(b,C).split(`
331
- `),W=a(`${e.id||Date.now()}-write-line-${v}`,"write-line",b,{gutterWidth:R,lineNum:v+1,isFirstLine:v===0,isLastLine:O,extension:h,wrappedLines:P});O&&e.isStreaming?($(),S=W):(T.push(W),T.length>=mi&&$())}),$(),{completed:E,active:S?[S]:[]}}if(o.includes("[DIFF_START]")){let h=o.match(/\[DIFF_START\]([\s\S]*?)(?:\[DIFF_END\]|$)/),y=(h?h[1].trim():"").split(`
332
- `).map(S=>S.replace(/\r$/,"")),m=y.map(S=>({line:S,parsed:wl(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&&(zr(w),w=[])}w.length>0&&zr(w);let x=[],k=null,R=[],E=()=>{if(!R.length)return;let S=R;R=[],x.push(S.length===1?S[0]:{key:`${S[0].key}-chunk`,type:"chunk",blocks:S})};return y.forEach((S,T)=>{let $=T===y.length-1,C=m[T].parsed,b=null;C&&(b=qr(C.content,n-17).split(`
333
- `));let v=a(`${e.id||Date.now()}-diff-${T}`,"diff-line",S,{isFirstLine:T===0,isLastLine:$,pairContent:m[T].pairContent,wrappedLines:b});$&&e.isStreaming?(E(),k=v):(R.push(v),R.length>=mi&&E())}),E(),{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",o)],active:[]};if(!o&&!e.isStreaming){let h={completed:[],active:[]};return qn.set(t,h),h}let r=[],p=null,d=[],c=null,l=()=>{if(!d.length)return;let h=d;d=[],c=null,r.push(h.length===1?h[0]:{key:`${e.id||"x"}-chunk-${h[0].key}`,type:"chunk",blocks:h})},u=(h,g=!1)=>{if(c!==null&&c!==h.type&&l(),d.push(h),c=h.type,d.length>=mi){if(e.isStreaming&&g)return;l()}};if(e.role==="think"){r.push(a(`${e.id}-header`,"think-header",""));let h=o.split(`
334
- `);h.forEach((g,y)=>{let m=y===h.length-1;u(a(`${e.id}-${y}`,"think-line",g,{}),m)}),e.isStreaming||(l(),r.push({key:`${e.id}-footer-padding`,type:"think-footer-padding",text:""}))}else{let h=o.split(`
335
- `),g=!1,y=[],m=!1,w=!1,x="",k=0,R=0;h.forEach((E,S)=>{let T=S===h.length-1,$=E.trim().startsWith("|"),C=E.trim().startsWith("```");if(w){if(E.includes("</think>")||E.includes("<channel|>")||E.includes("</thought>")){let b=E.split(/(?:<\/(think|thought|thoughts)>|<channel\|>)/i),v=b[0]||"",O=b.slice(2).join("");v&&u(a(`${e.id}-think-${S}`,"think-line",v,{}),T&&!O),l(),r.push({key:`${e.id}-think-footer-${S}`,type:"think-footer-padding",text:""}),w=!1,O&&O.trim()&&u(a(`${e.id}-${S}`,"agent-line",O,{}),T)}else u(a(`${e.id}-think-${S}`,"think-line",E,{}),T);return}if(!m&&(E.includes("<think>")||E.includes("<|channel>thought")||E.includes("<thought>")||E.startsWith("<think")||E.startsWith("<|channel>thought"))){l(),g&&(r.push(a(`${e.id}-table-${S}`,"table",y.join(`
336
- `),{isStreaming:!1})),g=!1,y=[]),r.push(a(`${e.id}-think-header-${S}`,"think-header","")),w=!0;let b=E.replace(/^(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought\s*)\r?\n?/i,"");if(b.includes("</think>")||b.includes("<channel|>")||b.includes("</thought>")){let v=b.split(/(?:<\/(think|thought|thoughts)>|<channel\|>)/i),O=v[0]||"",P=v.slice(2).join("");O&&u(a(`${e.id}-think-${S}`,"think-line",O,{}),T&&!P),l(),r.push({key:`${e.id}-think-footer-${S}`,type:"think-footer-padding",text:""}),w=!1,P&&P.trim()&&u(a(`${e.id}-${S}`,"agent-line",P,{}),T)}else b&&u(a(`${e.id}-think-${S}`,"think-line",b,{}),T);return}m?C?(m=!1,u(a(`${e.id}-code-close-${R}`,"code-fence-close","",{}),T)):(k++,u(a(`${e.id}-code-line-${S}`,"code-line",E,{lineNum:k,lang:x}),T)):C?(m=!0,R=S,k=0,x=E.trim().replace(/^```/,"").trim(),u(a(`${e.id}-code-open-${S}`,"code-fence-open",x,{}),T)):$?(g=!0,y.push(E),T&&(l(),e.isStreaming?p=a(`${e.id}-table-${S}`,"table",y.join(`
337
- `),{isStreaming:!0}):r.push(a(`${e.id}-table-${S}`,"table",y.join(`
338
- `),{isStreaming:!1})))):(g&&(l(),r.push(a(`${e.id}-table-${S}`,"table",y.join(`
339
- `),{isStreaming:!1})),g=!1,y=[]),u(a(`${e.id}-${S}`,"agent-line",E,{}),T))}),!e.isStreaming&&e.workedDuration&&(l(),r.push(a(`${e.id}-worked-duration`,"worked-duration","")))}e.isStreaming&&d.length>0?p=d.length===1?d[0]:{key:`${e.id||"x"}-chunk-active-${d[0].key}`,type:"chunk",blocks:d}:l();let f={completed:r,active:p?[p]:[]};if(e.isStreaming){let h=new Map;if(r.forEach(g=>yi(g,h)),p&&yi(p,h),ds.set(s,{text:o,blocksMap:h}),ds.size>Kr){let g=ds.keys().next().value;ds.delete(g)}}else{if(qn.set(t,f),qn.size>Kr){let h=qn.keys().next().value;qn.delete(h)}ds.delete(s)}return f},bl={},kl=/<\/think>(\r?\n){2}/gi,Sl=/(\r?\n){2}(?=\[?(?:tool:functions|tool\.functions|agent:generalist|agent\.generalist|\s*turn\s*:))/gi,gi=(e,n)=>{let t=!1;for(let o=0;o<n;o++)e[o]==="`"&&(t=!t);return t},Tl=/\[SYSTEM\][\s\S]*?\[\/SYSTEM\]|(?:<(think|thought|thoughts)>|<\|channel>thought)[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>)|\[ANSWER\][\s\S]*?(?:\[\/ANSWER\]|$)|\[TOOL RESULT\]:?\s*|^\s*(SUCCESS|ERROR):.*(\r?\n)?|\[\s*turn\s*:\s*(continue|finish)\s*\]|\[\[END\]\]|\[\s*turn\s*:?.*?$|\n\s*turn\s*:?.*?$|\[\s*(?:turn|ANSWER|TOOL).*?$|\n\nResponded on .*|\n\n\[Prompted on: .*\]|@\[TerminalName:.*?, ProcessId:.*?\]/gm,Rl=/(\$?\\?\/?\\rightarrow\$?|\$\\rightarrow\$)|(\$?\\?\/?\\leftarrow\$?|\$\\leftarrow\$)|(\$?\\?\/?\\uparrow\$?|\$\\uparrow\$)|(\$?\\?\/?\\downarrow\$?|\$\\downarrow\$)|(\$?\\?\/?\\leftrightarrow\$?|\$\\leftrightarrow\$)/gi,El=/\b(write_file|update_file|read_folder|view_file|exec_command|web_search|web_scrape|search_keyword|write_pdf|write_docx|generate_image)\b/gi,Is=!1,$l=(e,n=!1)=>{if(!e)return e;let t=e.replace(/<\|channel>thought/gi,"<think>").replace(/<channel\|>/gi,"</think>");if(n)return t.replace(/^<(think|thought|thoughts)>/gi,"").replace(/<\/(think|thought|thoughts)>$/gi,"").replace(/^\r?\n+/,"").replace(/\r?\n+$/,"");let o=t.replace(kl,"</think>").replace(Sl,(a,r,p,d)=>!Is&&gi(d,p)?a:"");o&&o.includes("[tool:")&&(o=o.replace(/<(\w+)(?:[^>]*)>\s*([\s\S]*?\[tool:[^\]]*\][\s\S]*?)\s*<\/\1>/gi,(a,r,p)=>p&&p.includes("[tool:")?p.trim():a),Is&&(o=o.replace(/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi,(a,r)=>r.includes("[tool:")?r.trim():a)),o=o.replace(/<(\w+)(?:[^>]*)>\r?\n?/gi,"").replace(/\r?\n?<\/\w+(?:[^>]*)>/gi,""));let s="tool:functions.",i="agent:generalist.";if(o.toLowerCase().includes(s)||o.toLowerCase().includes(i))for(;;){let a=o.toLowerCase(),r=a.indexOf(s),p=a.indexOf(i),d=s,c=r;if((r===-1||p!==-1&&p<r)&&(d=i,c=p),c===-1)break;if(!Is&&gi(o,c)){let w=c+d.length,x=a.indexOf(s,w),k=a.indexOf(i,w);if(x===-1&&k===-1)break;let R=-1,E=0;for(;;){let S=a.indexOf(s,E),T=a.indexOf(i,E),$=-1,C=s;if(S===-1&&T===-1)break;if(S===-1||T!==-1&&T<S?($=T,C=i):$=S,!gi(o,$)){R=$,d=C;break}E=$+C.length}if(R===-1)break;c=R}let l=c,u=!1,f=c-1;for(;f>=0&&/\s/.test(o[f]);)f--;f>=0&&o[f]==="["&&(l=f,u=!0);let h=0,g=!1,y=null,m=c;for(;m<o.length;){let w=o[m];if(!y&&(w==="'"||w==='"'||w==="`")?y=w:y&&w===y&&o[m-1]!=="\\"&&(y=null),y||(w==="("?(h++,g=!0):w===")"&&h--),g&&h===0&&!y){let x=m;if(u){let k=m+1;for(;k<o.length&&/\s/.test(o[k]);)k++;k<o.length&&o[k]==="]"&&(x=k)}o=o.substring(0,l)+o.substring(x+1);break}if(m++,m===o.length)return o=o.substring(0,l),o}}return o=o.replace(Tl,""),o=o.replace(Rl,a=>{let r=a.toLowerCase();return r.includes("leftrightarrow")?"\u2194":r.includes("rightarrow")?"\u2192":r.includes("leftarrow")?"\u2190":r.includes("uparrow")?"\u2191":r.includes("downarrow")?"\u2193":a}),o=o.replace(El,a=>bl[a.toLowerCase()]||a),o.trim()},Sf=()=>{qn.clear(),ds.clear()};var xi=async(e,n={})=>{let t=I(e),o=t.path;if(!o)return'ERROR: Missing "path" argument for PatchFile.';let{patchPairs:s,allowMultiple:i,error:a}=vo(t);if(a)return`ERROR: ${a}`;if(s.length===0)return"ERROR: No valid replacement pairs found. Use searchContent1, newContent1, etc.";let r=t.allowMultiple!==void 0?t.allowMultiple===!0||String(t.allowMultiple).toLowerCase()==="true":i,p=Cl.resolve(process.cwd(),o);try{if(!wi.existsSync(p))return`ERROR: File [${o}] does not exist. Use WriteFile instead.`;let d=n.forcedContent||wi.readFileSync(p,"utf8");d.startsWith("\uFEFF")&&(d=d.slice(1));let c=d.replace(/\r\n/g,`
340
- `).replace(/\r/g,`
341
- `),{content:l,results:u}=Io(c,s,{allowMultiple:r}),f=u.filter(m=>!m.success),h=u.filter(m=>m.success);if(h.length===0)return`ERROR: Patch Failed to apply to [${o}].
342
- ${f.map(m=>` \u2022 ${m.error}`).join(`
343
- `)}`;await ut.recordFileChange(p,c),wi.writeFileSync(p,l,"utf8");let{systemSettings:g}=await Ft(),y=Oo(c,l,u,12,g?.compressToolResults);return f.length>0?`SUCCESS: File [${o}] updated with some blocks failed. [${h.length}/${s.length}] blocks applied.
344
-
345
- Failures:
346
- ${f.map(m=>` \u2022 ${m.error}`).join(`
347
- `)}
348
-
349
- ${y}`:`SUCCESS: File [${o}] updated. [${u.length}/${s.length}] blocks applied.
350
-
351
- ${y}`}catch(d){let c=d instanceof Error?d.message:String(d);return`ERROR: Failed to update file [${o}]: ${c}`}};import fs from"fs";import bi from"path";var _l=new Set([".git","node_modules",".gemini","dist","build",".next","out",".cache","bin","obj","vendor","venv",".idea",".gradle",".terraform","target","coverage",".vscode",".svn",".hg",".fslckout",".github",".gitlab",".circleci",".gitea",".gitee",".lerna",".changeset",".nx",".npm",".yarn",".pnpm-store",".expo",".nuxt",".svelte-kit",".docusaurus",".turbo",".vercel","bower_components",".netlify",".vuepress",".quasar",".output",".angular","jspm_packages",".parcel-cache",".rollup.cache",".rspack",".vitepress","__pycache__",".pytest_cache",".mypy_cache",".tox",".poetry","env","vhdl",".ipynb_checkpoints",".jupyter",".conda",".pdm-build",".bundle",".yardoc",".metadata","App_Data","ClientBin",".cargo",".rustc_info",".go","Godeps","_vendor",".rake_tasks","CMakefiles",".wakatime",".dart_tool",".fvm",".cocoapods","Pods",".pub-cache",".symlinks","DerivedData",".xcworkspace",".serverless",".aws",".gcloud",".azure",".kube",".vagrant",".docker","postgres-data","redis-data","mongo-data",".Spotlight-V100",".Trashes","$RECYCLE.BIN","System Volume Information",".DocumentRevisions-V100",".fseventsd","AppData","Application Data","Local","LocalLow","Roaming","$WinREAgent","$WINDOWS.~BT","$WINDOWS.~WS","scw","System32","SysWOW64",".AppleDouble",".AppleDB",".AppleDesktop","_CodeSignature",".cmio",".LSOverride",".localized",".TemporaryItems",".Trash",".Trash-0",".Trash-1000",".gvfs",".local",".config",".dbus",".fontconfig",".snap",".var",".lost+found","lost+found",".thumb",".thumbnails","EFI","boot","grub","logs","log",".nyc_output",".sonar",".ruff_cache",".VSCodeCounter"]),Ml=e=>_l.has(e)||e.startsWith(".pnpm"),Al=e=>{try{let n=String(e.getMonth()+1).padStart(2,"0"),t=String(e.getDate()).padStart(2,"0"),o=String(e.getHours()).padStart(2,"0"),s=String(e.getMinutes()).padStart(2,"0");return`${n}-${t} ${o}:${s}`}catch{return"N/A"}},ki=async e=>{let n=I(e),t=n.path||null;if(!t)return"ERROR: No directory path provided.";let o=1;if(n.recurse!==void 0&&n.recurse!==null)if(typeof n.recurse=="number")o=n.recurse;else if(typeof n.recurse=="boolean")o=n.recurse?2:1;else{let i=parseInt(String(n.recurse).trim(),10);o=isNaN(i)?1:i}o=Math.max(1,Math.min(3,o));let s=bi.resolve(process.cwd(),t);try{if(!fs.existsSync(s))return`ERROR: Path [${t}] does not exist.`;if(!fs.statSync(s).isDirectory())return`ERROR: Path [${t}] is a file, not a directory. Use ReadFile instead.`;if(o===1){let g=fs.readdirSync(s),y=g.length,m=150,w=g.slice(0,m),x=[];for(let E of w){let S=bi.join(s,E),T={name:E,type:"unknown",size:"N/A",mtime:"N/A"};try{let $=fs.statSync(S);T={name:E,type:$.isDirectory()?"directory":"file",size:($.size/1024).toFixed(1)+"KB",mtime:Al($.mtime)}}catch{T.type="inaccessible"}x.push(T)}let k=x.map(E=>E.type==="directory"?`${E.name}/`:`${E.name} (${E.size}, ${E.mtime})`).join(`
352
- `),R=`
353
-
354
- (Total items in folder: ${y})`;return y>m&&(R=`
355
-
356
- TRUNCATED: Showing first ${m} of ${y} items.`),g.length=0,w.length=0,x.length=0,`Detailed folder stats for [${t}]:
357
-
358
- ${k}${R}`}let a=0,r=0,p=0,d=500,c=!1,l=(g,y,m=1)=>{if(y>o||c)return[];let w=[];try{w=fs.readdirSync(g)}catch{return[`${" ".repeat(m-1)}[Inaccessible Directory]`]}let x=[],k=[];for(let T of w){let $=bi.join(g,T),C=!1;try{C=fs.statSync($).isDirectory()}catch{}C?x.push({name:T,fullPath:$}):k.push({name:T,fullPath:$})}x.sort((T,$)=>T.name.localeCompare($.name)),k.sort((T,$)=>T.name.localeCompare($.name));let R=[],E=" ".repeat(m-1);for(let T of x){if(p>=d){c=!0,R.push(`${E}[Truncated - Maximum item limit reached (${d})]`);break}if(p++,a++,R.push(`${E}${T.name}/`),y<o&&!Ml(T.name)){let $=l(T.fullPath,y+1,m+1);R.push(...$)}}let S=[];for(let T of k){if(p>=d){c=!0,R.push(`${E}[Truncated - Maximum item limit reached (${d})]`);break}p++,r++;let $="N/A";try{$=(fs.statSync(T.fullPath).size/1024).toFixed(1)+"KB"}catch{}S.push(`${T.name} (${$})`)}return S.length>0&&R.push(`${E}${S.join("; ")}`),R},f=l(s,1,1).join(`
359
- `),h=`
360
-
361
- (Total items scanned: ${p}, Directories: ${a}, Files: ${r})`;return c&&(h=`
362
-
363
- TRUNCATED: Scan capped at ${d} items. (Directories: ${a}, Files: ${r})`),`Detailed directory tree for [${t}] (recursive depth: ${o}):
364
-
365
- ${f}${h}`}catch(i){let a=i instanceof Error?i.message:String(i);return`ERROR: Failed to read folder [${t}]: ${a}`}};var Si=async(e,n)=>{let t=I(e),{question:o}=t;if(!o)return'ERROR: Missing "question" argument for ask.';if(!n.onAskUser)return"ERROR: onAskUser callback not provided in tool context.";let s=[];Object.keys(t).forEach(i=>{if(i.startsWith("option")){let a=t[i];if(typeof a=="string"&&a.includes("::")){let[r,p]=a.split("::");s.push({id:i,label:r.trim(),description:p.trim()})}else s.push({id:i,label:String(a).trim(),description:""})}});try{return`USER CHOOSE: ${await n.onAskUser(o,s)}`}catch(i){return`ERROR: Failed to get user input: ${i instanceof Error?i.message:String(i)}`}};import vl from"puppeteer";import Os from"path";import us from"fs-extra";import{PDFDocument as Il}from"pdf-lib";var Ti=async e=>{let{path:n,content:t,orientation:o="portrait",margin:s="0px"}=I(e);if(!n)return'ERROR: Missing "path" argument for write_pdf.';if(!t)return'ERROR: Missing "content" (HTML/CSS) for write_pdf.';let i=Os.resolve(process.cwd(),n),a=null;try{await us.ensureDir(Os.dirname(i)),await ut.recordFileChange(i);let r=cs();a=await vl.launch({headless:!0,executablePath:r.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let p=await a.newPage(),d=t,c={},l=async S=>{if(!S||S.startsWith("http://")||S.startsWith("https://")||S.startsWith("data:"))return null;try{let T=Os.resolve(process.cwd(),S);if(await us.pathExists(T)){let $=Os.extname(T).toLowerCase().replace(".","")||"png",C=$==="jpg"?"jpeg":$==="svg"?"svg+xml":$,b=await us.readFile(T,"base64");return`data:image/${C};base64,${b}`}}catch{}return null},u=/<link[^>]+href=["']([^"']+)["']/gi,f={},h;for(;(h=u.exec(t))!==null;){let S=h[1],T=h[0];if(S&&T.toLowerCase().includes("stylesheet")&&!S.startsWith("http://")&&!S.startsWith("https://")&&!S.startsWith("data:"))try{let $=Os.resolve(process.cwd(),S);if(await us.pathExists($)){let C=await us.readFile($,"utf-8");f[T]=`<style>${C}</style>`}}catch{}}for(let[S,T]of Object.entries(f))d=d.split(S).join(T);let g=/<img[^>]+src=["']([^"']+)["']/gi;for(;(h=g.exec(d))!==null;){let S=h[1];if(S&&!c[S]){let T=await l(S);T&&(c[S]=T)}}let y=/url\(\s*['"]?([^'")]+?)['"]?\s*\)/gi;for(;(h=y.exec(d))!==null;){let S=h[1].trim();if(S&&!c[S]){let T=await l(S);T&&(c[S]=T)}}for(let[S,T]of Object.entries(c)){let $=S.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&"),C=new RegExp(`(src=["'])(${$})(["'])`,"gi");d=d.replace(C,`$1${T}$3`);let b=new RegExp(`url\\(\\s*(['"]?)(${$})\\1\\s*\\)`,"gi");d=d.replace(b,`url($1${T}$1)`)}let m=`
366
- <style>
367
- @page {
368
- margin: ${s};
369
- }
370
- body {
371
- margin: 0;
372
- padding: 0;
373
- font-family: system-ui, -apple-system, sans-serif;
374
- }
375
- * { box-sizing: border-box; }
376
- .watermark {
377
- position: fixed;
378
- top: 50%;
379
- left: 50%;
380
- transform: translate(-50%, -50%) rotate(-50deg);
381
- font-size: 52px;
382
- font-weight: bold;
383
- color: rgba(0, 0, 0, 0.005);
384
- pointer-events: none;
385
- z-index: -1000;
386
- text-align: center;
387
- width: 150%;
388
- white-space: nowrap;
389
- text-transform: uppercase;
390
- letter-spacing: 5px;
391
- }
392
- </style>
393
- <div class="watermark">Generated by FluxFlow CLI (AI)</div>
394
- ${d}
395
- `;await p.setContent(m,{waitUntil:"networkidle0",timeout:18e4});let w=await p.pdf({format:"A4",landscape:String(o).toLowerCase()==="landscape",margin:{top:s,right:s,bottom:s,left:s},printBackground:!0}),x=await Il.load(w),k=Os.basename(n);x.setTitle(`FluxFlow_${k}`),x.setAuthor("FluxFlow CLI"),x.setSubject("Generated with Agentic AI System"),x.setKeywords(["FluxFlow","AI","Agentic","Automated"]),x.setCreator("FluxFlow PDF Engine"),x.setProducer("FluxFlow (Generative AI)");let R=await x.save();await us.writeFile(i,R);let E=await us.stat(i);return`SUCCESS: PDF generated successfully at [${n}] (${(E.size/1024).toFixed(2)} KB).`}catch(r){let p=r instanceof Error?r.message:String(r);return`ERROR: Failed to generate PDF [${n}]: ${p}`}finally{a&&await a.close()}};import Yr from"fs-extra";import Ri from"path";import Ol from"html-to-docx";var Ei=async e=>{let{path:n,content:t}=I(e);if(!n)return'ERROR: Missing "path" argument for write_docx.';if(!t)return'ERROR: Missing "content" (HTML) for write_docx.';let o=Ri.resolve(process.cwd(),n);try{await Yr.ensureDir(Ri.dirname(o)),await ut.recordFileChange(o);let s=Ri.basename(n),i=t.includes("<html")?t:`
396
- <!DOCTYPE html>
397
- <html lang="en">
398
- <head>
399
- <meta charset="UTF-8">
400
- <title>FluxFlow Document</title>
401
- </head>
402
- <body>
403
- ${t}
404
- </body>
405
- </html>
406
- `,a=await Ol(i,null,{title:`FluxFlow_${s}`,creator:"FluxFlow CLI",description:"Generated by Agentic AI System",table:{row:{cantSplit:!0}},footer:!0,pageNumber:!0});return await Yr.writeFile(o,a),`SUCCESS: Word document [${n}] generated successfully.
407
- - Size: ${(a.length/1024).toFixed(1)} KB`}catch(s){let i=s instanceof Error?s.message:String(s);return`ERROR: Failed to generate DOCX [${n}]: ${i}`}};import Ci from"fs/promises";import hs from"path";import $i from"fast-glob";import{Minimatch as Vr}from"minimatch";async function Zs(e,n,t=e,o=1){if(o>12)return[];let s=[],i;try{i=await Ci.readdir(e,{withFileTypes:!0})}catch{return[]}for(let a of i){let r=hs.join(e,a.name),p=hs.relative(t,r),d=p.split(hs.sep).map(u=>u.toLowerCase()),c=a.name.toLowerCase();if(!n.some(u=>{let f=u.toLowerCase();return f.startsWith(".")&&c.endsWith(f)?!0:d.some(h=>h===f||h.startsWith(".pnpm"))}))if(a.isDirectory()){let u=await Zs(r,n,t,o+1);s=s.concat(u)}else a.isFile()&&s.push({fullPath:r,relativePath:p})}return s}function Ll(e,n,t=1/0){if(e===n)return 0;if(e.length===0)return n.length;if(n.length===0)return e.length;if(Math.abs(e.length-n.length)>t)return t+1;let o=Array.from({length:n.length+1},(s,i)=>i);for(let s=1;s<=e.length;s++){let i=[s],a=s;for(let r=1;r<=n.length;r++){let p=e[s-1]===n[r-1]?0:1,d=Math.min(i[r-1]+1,o[r]+1,o[r-1]+p);i.push(d),d<a&&(a=d)}if(o=i,a>t)return t+1}return o[n.length]}function Pl(e,n){if(!e||!n)return!1;let t=e.toLowerCase(),o=n.toLowerCase();if(t.includes(o))return!0;let s=t.split(/[^a-z0-9]+/).filter(a=>a.length>0),i=o.split(/[^a-z0-9]+/).filter(a=>a.length>1||o.length===1&&a.length>0);return i.length===0?!1:i.every(a=>{let r=a.length<=2?0:a.length<=5?1:2;for(let p of s)if(p.includes(a)||a.length>=3&&p.length>=3&&Math.abs(p.length-a.length)<=r&&Ll(a,p,r)<=r)return!0;return!1})}var eo=async e=>{let{keyword:n,path:t,fuzzy:o,subString:s,regex:i}=I(e);if(n==null)return'ERROR: Missing "keyword" argument.';let a=String(n),r=g=>g===!0||g==="true"||g===1||g==="1"||g==="yes",p=i===!1||i==="false"||i===0||i==="0"||i==="no",d=i===!0||i==="true"||i===1||i==="1"||i==="yes",c=r(o)||r(s),l=null,u=null;if(p)c||(u=new RegExp(`(?<![\\w])${a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\\w])`,"i"));else{try{l=new RegExp(a,"i")}catch(g){if(d)return`ERROR: Invalid regex pattern "${a}": ${g.message}`}u=new RegExp(`(?<![\\w])${a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\\w])`,"i")}let f=[".git","node_modules",".gemini","dist","build",".next","out",".cache","bin","obj","vendor","venv",".idea",".gradle",".terraform","target","coverage",".vscode",".svn",".hg",".fslckout",".github",".gitlab",".circleci",".gitea",".gitee",".lerna",".changeset",".nx",".npm",".yarn",".pnpm-store",".pnpm",".expo",".nuxt",".svelte-kit",".docusaurus",".turbo",".vercel","bower_components",".netlify",".vuepress",".quasar",".output",".angular","jspm_packages",".parcel-cache",".rollup.cache",".rspack",".vitepress","__pycache__",".pytest_cache",".mypy_cache",".tox",".poetry","env","vhdl",".ipynb_checkpoints",".jupyter",".conda",".pdm-build",".bundle",".yardoc",".metadata","App_Data","ClientBin",".cargo",".rustc_info",".go","Godeps","_vendor",".rake_tasks","CMakefiles",".wakatime",".dart_tool",".fvm",".cocoapods","Pods",".pub-cache",".symlinks","DerivedData",".xcworkspace",".serverless",".aws",".gcloud",".azure",".kube",".vagrant",".docker","postgres-data","redis-data","mongo-data",".Spotlight-V100",".Trashes","$RECYCLE.BIN","System Volume Information",".DocumentRevisions-V100",".fseventsd","AppData","Application Data","Local","LocalLow","Roaming","$WinREAgent","$WINDOWS.~BT","$WINDOWS.~WS","scw","System32","SysWOW64",".AppleDouble",".AppleDB",".AppleDesktop","_CodeSignature",".cmio",".LSOverride",".localized",".TemporaryItems",".Trash",".Trash-0",".Trash-1000",".gvfs",".local",".config",".dbus",".fontconfig",".snap",".var",".lost+found","lost+found",".thumb",".thumbnails","EFI","boot","grub","logs","log",".nyc_output",".sonar",".ruff_cache",".VSCodeCounter",".exe",".dll",".so",".dylib",".png",".jpg",".jpeg",".gif",".ico",".svg",".webp",".mp3",".mp4",".avi",".zip",".tgz",".tar",".gz",".7z",".rar",".pdf",".docx",".xlsx",".pptx",".woff",".woff2",".ttf",".eot"],h=150;try{let g=[],y=process.cwd(),m=null;if(t){let O=t.split(";").map(N=>N.trim()).filter(Boolean),P=O.some(N=>N.startsWith("!"));if(O.some(N=>$i.isDynamicPattern(N)||/[*?{}[\]()|+]/.test(N))){m="glob";let N=t.replace(/\\/g,"/"),Y=O.map(B=>B.replace(/\\/g,"/")),ie=f.map(B=>B.startsWith(".")?`**/*${B}`:`**/${B}/**`);if(P&&!O.some(B=>!B.startsWith("!"))){let B=await Zs(y,f,y),j=M=>M.endsWith("/")?M+"**":M,re=Y.filter(M=>M.startsWith("!")).map(M=>j(M.slice(1))),Re=Y.filter(M=>!M.startsWith("!")).map(j);g=B.filter(M=>{let F=M.relativePath.replace(/\\/g,"/"),V=Re.length===0||Re.some(Ne=>{try{return new Vr(Ne).match(F)}catch{return!1}}),J=re.some(Ne=>{try{return new Vr(Ne).match(F)}catch{return!1}});return V&&!J})}else{let B=Y.some(re=>/[\(\)\|]|\.\*/.test(re)),j=[];if(!B)try{j=await $i(Y,{cwd:y,ignore:ie,dot:!0,onlyFiles:!0,absolute:!1})}catch{j=[]}if(j.length===0&&(B||$i.isDynamicPattern(N))){let re=N.match(/^([^\*\?\(\)\|\[\]\s]+)\//),Re=re&&!/[\*\?\(\)\|\[\]]/.test(re[1])?hs.resolve(y,re[1]):y,M=await Zs(Re,f,y);try{let F=N.replace(/^\.\//,"");F=F.replace(/\.\*\/(\\.|[^\/])/g,".*$1"),!F.startsWith("^")&&!F.startsWith(".*")&&(F=`.*${F}`);let V=new RegExp(F.endsWith("$")?F:`${F}$`,"i");g=M.filter(J=>{let Ne=J.relativePath.replace(/\\/g,"/");return V.test(Ne)})}catch{g=[]}}else g=j.map(re=>({fullPath:hs.resolve(y,re),relativePath:re}))}}else{let N=t.replace(/[\/\\]+$/,""),Y=hs.resolve(y,N);try{let ie=await Ci.stat(Y);if(ie.isDirectory())m="dir",g=await Zs(Y,f,y);else if(ie.isFile())m="file",g.push({fullPath:Y,relativePath:hs.relative(y,Y)});else return`ERROR: Path is neither a file nor a directory: ${t}`}catch{return`ERROR: Path not found: ${t}`}}}else g=await Zs(y,f);let w=g.map(async O=>{try{let P=await Ci.readFile(O.fullPath,"utf-8");if(P.includes("\0"))return[];let W=P.split(/\r?\n/),N=[];for(let ie=0;ie<W.length;ie++)(c?W[ie].toLowerCase().includes(a.toLowerCase())||Pl(W[ie],a):p?u&&u.test(W[ie]):l&&l.test(W[ie])||u&&u.test(W[ie]))&&N.push({line:ie+1,content:W[ie].trim()});return N.length===0?null:{path:O.relativePath.replace(/\\/g,"/"),matches:N}}catch{return[]}}),x=await Promise.all(w),k=[],R=0;for(let O of x){if(!O||!O.matches)continue;if(R>=h)break;let P=h-R,W=O.matches.slice(0,P);k.push({path:O.path,matches:W}),R+=W.length}typeof global.gc=="function"&&global.gc();let E=c?"(fuzzy mode)":d?"(regex mode)":p?"(keyword mode)":"(standard mode)";if(k.length===0){let O=m==="file"?` in '${t}'`:m==="dir"||m==="glob"?` in '${t}'`:". Try to specify files",P=m==="dir"?"[DIR]":m==="glob"?"[GLOB]":"";return`${P}${P?" ":""}Found 0 matches of '${a}'${O}${E?` ${E}`:""}`}let S=E?` ${E}`:"",T=`${k.length} file${k.length===1?"":"s"}`,$=`${R} match${R===1?"":"es"}`,C;m==="file"?C=`Found ${$} of '${a}' in '${t}'${S}:`:m==="dir"||m==="glob"?C=`Found ${$} of '${a}' in '${t}' across ${T}${S}:`:C=`Found ${$} of '${a}' across ${T}${S}:`;let b=m==="dir"?"[DIR]":m==="glob"?"[GLOB]":"",v=`${b}${b?" ":""}${C}
408
-
409
- `;for(let O of k){v+=`${O.path}
410
- `;for(let P of O.matches)v+=` ${P.line}: ${P.content}
411
- `;v+=`
412
- `}return v.trimEnd()}catch(g){return`ERROR: ${g.message}`}};import Jr from"fs-extra";import _i from"path";var Dl=(e,n={})=>{try{if(e.length<8||e[0]!==137||e[1]!==80||e[2]!==78||e[3]!==71)return e;let t=[],o=[];for(let a=0;a<256;a++){let r=a;for(let p=0;p<8;p++)r&1?r=3988292384^r>>>1:r=r>>>1;o[a]=r}let s=a=>{let r=4294967295;for(let p=0;p<a.length;p++)r=o[(r^a[p])&255]^r>>>8;return(r^4294967295)>>>0},i=(a,r)=>{let p=Buffer.from(a,"ascii"),d=Buffer.from(r,"utf-8"),c=p.length+1+d.length,l=Buffer.alloc(8+c+4);l.writeUInt32BE(c,0),l.write("tEXt",4,"ascii"),p.copy(l,8),l[8+p.length]=0,d.copy(l,8+p.length+1);let u=s(l.subarray(4,8+c));return l.writeUInt32BE(u,8+c),l};for(let[a,r]of Object.entries(n))r!=null&&t.push(i(a,String(r)));if(t.length===0)return e;if(e.subarray(12,16).toString("ascii")==="IHDR"){let r=e.subarray(0,33),p=e.subarray(33);return Buffer.concat([r,...t,p])}return e}catch{return e}},Mi=async(e,n={})=>{let t=I(e),o=t.prompt||t.text,s=t.path||t.outputPath||t.output||"generated_image.png",i=t.ratio;if(!o)return'ERROR: Missing "prompt" argument for generate_image.';let a=["nsfw","naked","nudity","nude","porn","sex","xxx","erotic","gore","bloody","violence","abuse","suicide","murder","hentai","pedophile","rape"],r=o.toLowerCase();if(a.some(d=>r.includes(d)))return"ERROR: Prompt blocked by system safety filter (inappropriate or unsafe content detected).";try{let d=await Ft();if(!await Pr(d))return`ERROR: Insufficient Quota for selected quality. Either tell user reduce quality or wait for next refresh cycle (${(await Dr()).nextResetMin||60}m).`;let l=d.imageSettings||{keyType:"Default",quality:"Low-High",apiKey:""},u=l.keyType==="Custom"&&l.apiKey?l.apiKey:FALLBACK_IMAGE_KEY,h={Low:"flux","Low-High":"zimage",Medium:"gptimage","Medium-High":"gptimage",High:"qwen-image",Ultra:"gptimage-large",Premium:"nanobanana-pro"}[l.quality]||"zimage",g=1024,y=1024;if(i){let P=i.replace(/\s+/g,"");P==="16:9"?(g=1024,y=576):P==="9:16"?(g=576,y=1024):P==="4:3"?(g=1024,y=768):P==="3:4"?(g=768,y=1024):P==="1:1"&&(g=1024,y=1024)}let m=Math.floor(Math.random()*1e7),x=`https://gen.pollinations.ai/image/${encodeURIComponent(o)}?model=${h}&width=${g}&height=${y}&seed=${m}&enhance=true&reasoning=high&quality=high&negative=${encodeURIComponent("deformed, distorted, disfigured, poorly drawn, bad anatomy, wrong anatomy, extra limb, missing limb, floating limbs, disconnected limbs, mutation, mutated hands and fingers, blurry, low quality, low resolution, extra fingers, censored, watermarks, signatures")}`,k=await fetch(x,{method:"GET",headers:{Authorization:`Bearer ${u}`}});if(!k.ok){let P=k.status,W="";try{W=await k.text()}catch{}return P===402||W.includes("Insufficient balance")||W.includes("PAYMENT_REQUIRED")?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed with status [${P}]: ${W||"Unknown API Error"}`}if((k.headers.get("content-type")||"").includes("application/json")){let P=await k.json();return P.status===402||P.error&&P.error.code==="PAYMENT_REQUIRED"?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed: ${P.error?.message||JSON.stringify(P)}`}let E=await k.arrayBuffer(),S=Buffer.from(E),T={Title:o,Description:"Generated via FluxFlow CLI",Software:"FluxFlow CLI",Author:"FluxFlow","Creation Time":new Date().toISOString(),Prompt:o,Model:`Fluxflow:${h}`,Ratio:i||"1:1",Seed:String(m)};S=Dl(S,T);let $=_i.resolve(process.cwd(),s);await Jr.ensureDir(_i.dirname($)),await ut.recordFileChange($),await Jr.writeFile($,S),await Fr(d);let C=_i.extname(s).toLowerCase(),v={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".webp":"image/webp"}[C]||"image/png";return n.isMultiModal!==!1?{text:`SUCCESS: Image successfully generated from prompt [${o}] and saved to [${s}]. Output attached to multimodal part`,binaryPart:{inlineData:{data:S.toString("base64"),mimeType:v}}}:`SUCCESS: Image successfully generated from prompt [${o}] and saved to [${s}].`}catch(d){return`ERROR: Failed during image generation: ${d instanceof Error?d.message:String(d)}`}};var to=async(e,n={})=>{let t=i=>{let a=new RegExp(`${i}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),r=e.match(a);return r?r[2].trim():null},o=t("id"),s=t("summary");if(!o||!s)return"ERROR: Missing 'id' or 'summary' for saveSummary tool.";try{let i=X(Qt,{}),a=X(vn,{});return a[o]=s,delete i[o],he(vn,a),he(Qt,i),`SUCCESS: Saved summary and purged raw memories for chat [${o}].`}catch(i){let a=i instanceof Error?i.message:String(i);return`ERROR: Failed to save summary for chat [${o}]: ${a}`}};var Ls=async(e,n={})=>{let o=(s=>{let i=new RegExp(`${s}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),a=e.match(i);return a?a[2].trim():null})("id");if(!o)return"ERROR: Missing 'id' parameter for addMemScore tool.";try{let s=X(Dt,[]),i=!1,a=[];for(let c of s)c.score===void 0&&(c.score=.5),c.id===o?(c.score=Math.min(2,c.score+.2),i=!0):(c.score*=.98,c.score<.05&&(c.score=0)),c.score=Math.round(c.score*1e5)/1e5,c.score>0&&a.push(c);if(he(Dt,a),!i)return`WARNING: Memory ID [${o}] not found. Other memories decayed by -0.01.`;let r=a.find(c=>c.id===o),p=r?r.score.toFixed(2):"deleted (score <= 0)",d=s.length-a.length;return`SUCCESS: Adjusted memory scores. Target [${o}] is now ${p}.${d>0?` Purged ${d} decayed memories.`:""}`}catch(s){let i=s instanceof Error?s.message:String(s);return`ERROR: Failed to adjust memory score for [${o}]: ${i}`}};import vi from"fs-extra";import ms from"path";import{createRequire as Bl}from"module";import ps from"fs-extra";import Ai from"path";import Fl from"https";var Xr={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 Nl(e,n=null){let t=n||`https://unpkg.com/tree-sitter-wasms@0.1.13/out/${e}`,o=Ai.join(as,e);return await ps.ensureDir(as),new Promise((s,i)=>{let a={headers:{"User-Agent":"FluxFlow-Agent"}};Fl.get(t,a,r=>{if([301,302,307,308].includes(r.statusCode)&&r.headers.location){let d=r.headers.location;if(!d.startsWith("http")){let c=new URL(t);d=`${c.protocol}//${c.host}${d}`}Nl(e,d).then(s).catch(i);return}if(r.statusCode!==200){i(new Error(`Failed to download ${e}: HTTP ${r.statusCode}`));return}let p=ps.createWriteStream(o);r.pipe(p),p.on("finish",()=>{p.close(),s()})}).on("error",r=>{ps.existsSync(o)&&ps.unlink(o,()=>{}),i(r)})})}function bu(e){let n=Ai.join(as,e);return ps.existsSync(n)}async function ku(e){let n=Ai.join(as,e);ps.existsSync(n)&&await ps.unlink(n)}var ea=Bl(import.meta.url),Qr=ea("web-tree-sitter"),Zr=!1,ta=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"]),na=new Set(["export_statement","lexical_declaration","variable_declaration","variable_declarator","pair","assignment_expression"]);function mn(e,n=50){if(!e)return"";let t=e.replace(/\s+/g," ").trim();return t.length>n?t.substring(0,n-3)+"...":t}function sa(e){let n=e.type;if(n==="if_statement"){let o=e.childForFieldName("condition");return o?`if (${mn(o.text,40)})`:"if"}if(n==="else_clause")return"else";if(n==="while_statement"||n==="do_statement"){let o=e.childForFieldName("condition");return`${n.split("_")[0]} (${o?mn(o.text,40):""})`}if(n==="for_statement"||n==="for_in_statement"||n==="for_of_statement"){let s=e.text.split(`
413
- `)[0].match(/for\s*(?:await\s*)?\((.*)\)/);return s?`for (${mn(s[1],40)})`:"for"}if(n==="switch_statement"){let o=e.childForFieldName("value");return`switch (${o?mn(o.text,40):""})`}if(n==="try_statement")return"try";if(n==="catch_clause")return"catch";if(n==="element"||n==="script_element"||n==="style_element"||n==="jsx_element"||n==="jsx_self_closing_element"){let o=e.childForFieldName("opening_element")||e.childForFieldName("start_tag")||e.children.find(i=>i.type==="start_tag")||e,s=o.childForFieldName("name")||o.childForFieldName("tag_name")||o.children.find(i=>i.type==="tag_name");return s?`<${mn(s.text,30)}>`:null}if(["import_declaration","import_from_statement","import_statement","preproc_include"].includes(n))return mn(e.text.split(`
414
- `)[0],60);if(n==="pair"){let o=e.childForFieldName("key");return o?mn(o.text.replace(/["']/g,""),40):null}if(n==="assignment_expression"){let o=e.childForFieldName("left");return o?`${mn(o.text,30)} = ...`:null}if(n==="variable_declarator"){let o=e.childForFieldName("name")||e.children.find(s=>["identifier","object_pattern","array_pattern"].includes(s.type));return o?mn(o.text,40):null}let t=e.childForFieldName("name")||e.childForFieldName("declarator")||e.children.find(o=>["identifier","type_identifier","field_identifier","property_identifier","shorthand_property_identifier"].includes(o.type));if(t){if(t.type.includes("declarator")){let o=t.descendantsOfType("identifier")[0]||t.descendantsOfType("field_identifier")[0];if(o)return mn(o.text,40)}return mn(t.text,40)}if(["arrow_function","function_expression","function_declaration"].includes(n)){let o=e.parent;for(;o&&o.type!=="program";){let s=sa(o);if(s)return s;if(!na.has(o.type))break;o=o.parent}}return null}function Ul(e){let n=[];function t(o){for(let s of o.children)ta.has(s.type)?n.push(s):t(s)}return t(e),n}function Wl(e){return e.replace(/_([a-z])/g,n=>n[1].toUpperCase())}function oa(e,n=0,t=!0,o="",s=null,i=12){let a=e.type,r=sa(e),p=ta.has(a)||n===0,d=Ul(e),c=p&&n>0&&(na.has(a)&&d.length>0||r!==null&&r===s&&d.length>0),l="",u=o,f=n,h=s;if(p&&!c){let g=e.startPosition.row+1,y=e.endPosition.row+1,m=Wl(a),w=r?`${m} [${r}]`:m;n===0?(l+=`\u{1F4C1} ROOT (Lines: ${g}-${y})
415
- `,u=o):(l+=`${o}${t?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 "}${w} (Lines: ${g}-${y})
416
- `,u+=t?" ":"\u2502 "),f=n+1,h=r}return f>i&&d.length>0?l+=`${u}\u2514\u2500\u2500 ... depth exceeded ...
417
- `:d.forEach((g,y)=>{let m=y===d.length-1;l+=oa(g,f,c?t&&m:m,u,h,i)}),l}var Ii=async e=>{let n;try{n=I(e).path}catch{return`ERROR: Failed to parse arguments: ${e}`}if(!n)return'ERROR: No file path provided. Use [tool:functions.FileMap(path="...")]';let t=ms.isAbsolute(n)?n:ms.resolve(process.cwd(),n);if(!vi.existsSync(t))return`ERROR: File not found: ${n}`;let o=ms.extname(t).slice(1).toLowerCase(),s=Xr[o];if(!s)return`ERROR: Unsupported file extension: .${o}`;let i=ms.resolve(as,s);if(!vi.existsSync(i))return`ERROR: Parser for .${o} not found. Please download it in Settings > Other.`;try{let a=Qr.Parser;if(!Zr){let h;try{h=ms.join(ms.dirname(ea.resolve("web-tree-sitter")),"tree-sitter.wasm")}catch{h=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")?h:g}),Zr=!0}let r=new a,p=await Qr.Language.load(i);r.setLanguage(p);let d=await vi.readFile(t,"utf8"),c=d.split(`
418
- `).length,l=12;c>1e4?l=2:c>=8e3?l=3:c>=5e3?l=5:c>=4e3?l=8:c>2e3&&(l=10);let u=r.parse(d),f=oa(u.rootNode,0,!0," ",null,l);return`\u{1F4C4} File Map for: ${n}
419
- ${f}`}catch(a){let r=a instanceof Error?a.message:typeof a=="object"?JSON.stringify(a):String(a),p=a instanceof Error?`
420
- Stack: ${a.stack}`:"";return`ERROR: Failed to map file: ${r}${p}`}};import zn from"fs";import ia from"path";var no=async(e,n={})=>{let{method:t,tasks:o,markDone:s}=I(e),i=n.chatId||"default";if(!t)return'ERROR: Missing "method" argument for todo tool (create/append/get).';let a=ia.join(An,"plan",i),r=ia.join(a,"todo.md"),p=l=>{if(!l||Array.isArray(l))return l;let u=String(l).trim();if(u.startsWith("[")&&u.endsWith("]")){let f=u.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);return f?f.map(h=>h.slice(1,-1).replace(/\\(.)/g,"$1")):u.slice(1,-1).split(",").map(h=>h.trim()).filter(Boolean)}return l},d=l=>{let u=p(l);return u?(Array.isArray(u)?u:String(u).split(`
421
- `)).map(h=>{let g=String(h).trim();return g?g.startsWith("- [ ]")||g.startsWith("- [x]")||g.startsWith("- [X]")?g:`- [ ] ${g}`:null}).filter(Boolean).join(`
422
- `)+`
423
- `:""},c=(l,u)=>{if(!u)return{content:l,markedCount:0};let f=p(u),h=(Array.isArray(f)?f:[f]).map(w=>String(w).replace(/^- \[[xX ]\]\s*/i,"").trim()).filter(Boolean),g=l.split(`
424
- `),y=0,m=!1;for(let w of h){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(`
425
- `):l,markedCount:y}};try{if(zn.existsSync(a)||zn.mkdirSync(a,{recursive:!0}),t==="create"){if(!o)return'ERROR: Missing "tasks" for create method.';let l=d(o),u=0;if(s){let h=c(l,s);l=h.content,u=h.markedCount}await ut.recordFileChange(r),zn.writeFileSync(r,l,"utf8");let f=l.split(/\r?\n/).map(h=>h.trim()).filter(h=>h.startsWith("- [ ]")||h.startsWith("- [x]")||h.startsWith("- [X]")).length;if(u>0){let h=l.split(/\r?\n/).map(g=>g.trim()).filter(g=>g.startsWith("- [x]")||g.startsWith("- [X]")).length;return`SUCCESS: TASK LIST CREATED (${u} marked done, ${h} completed, ${f-h} left)
426
- ${l}`}return`SUCCESS: TASK LIST CREATED (${f} total)
427
- ${l}`}if(t==="append"){if(!o)return'ERROR: Missing "tasks" for append method.';let l=d(o);await ut.recordFileChange(r),zn.appendFileSync(r,l,"utf8");let u=zn.readFileSync(r,"utf8"),f=u.split(/\r?\n/).map(m=>m.trim()),h=f.filter(m=>m.startsWith("- [ ]")||m.startsWith("- [x]")||m.startsWith("- [X]")).length,g=f.filter(m=>m.startsWith("- [x]")||m.startsWith("- [X]")).length,y=l.split(/\r?\n/).map(m=>m.trim()).filter(m=>m.startsWith("- [ ]")||m.startsWith("- [x]")||m.startsWith("- [X]")).length;return`SUCCESS: TASK APPENDED (${g} completed, ${h-g} left, ${y} added)
428
- ${u}`}if(t==="get"){if(!zn.existsSync(r))return"TODO GET: No task list found for this session.";let l=zn.readFileSync(r,"utf8"),u=0;if(s){let m=c(l,s);m.markedCount>0&&(l=m.content,u=m.markedCount,await ut.recordFileChange(r),zn.writeFileSync(r,l,"utf8"))}let f=l.split(/\r?\n/).map(m=>m.trim()),h=f.filter(m=>m.startsWith("- [ ]")||m.startsWith("- [x]")||m.startsWith("- [X]")).length,g=f.filter(m=>m.startsWith("- [x]")||m.startsWith("- [X]")).length;return`${u>0?`SUCCESS: ${u} TASK(S) MARKED DONE`:"TODO GET"}: ${g} Completed, ${h-g} left
429
- ${l}`}return`ERROR: Unknown method "${t}". Use create, append, or get.`}catch(l){return`ERROR: Todo tool failure: ${l instanceof Error?l.message:String(l)}`}};var Oi=async(e,n={})=>{let{runSubagent:t}=await import("./ai-AJO5ASXE.js"),o=I(e),s=o.task||o.instruction||o.prompt,i=o.model||null,a=o.tools||null;if(!s)return'ERROR: Missing "task" argument for invokeSync.';let r=null;if(a)try{let d=a.trim();d.startsWith("[")&&d.endsWith("]")&&(d=d.substring(1,d.length-1)),r=d.split(",").map(c=>c.trim().replace(/^["']|["']$/g,"")).filter(Boolean)}catch{}let p=o.title||s.substring(0,30);try{n.onVisualFeedback&&n.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${p}`);let d=await t(s,n,i,r,50);return n.onVisualFeedback&&n.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${p} [COMPLETED]
430
- `),d}catch(d){let{isTerminationSignaled:c}=await import("./ai-AJO5ASXE.js"),l=d.message==="Subagent task was cancelled by user."||c();if(n.onVisualFeedback){let u=l?"[CANCELLED]":"[FAILED]";n.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${p} ${u}
431
- `)}return`ERROR: Subagent execution failed: ${d.message}`}};var ra=async(e,n={})=>{let{runSubagent:t}=await import("./ai-AJO5ASXE.js"),o=I(e),s=o.task||o.instruction||o.prompt,i=o.model||null,a=o.title||null,r=o.tools||null;if(!s)return'ERROR: Missing "task" argument for invoke.';let p=null;if(r)try{let m=r.trim();m.startsWith("[")&&m.endsWith("]")&&(m=m.substring(1,m.length-1)),p=m.split(",").map(w=>w.trim().replace(/^["']|["']$/g,"")).filter(Boolean)}catch{}let d=`subagent-${Date.now()}-${Math.floor(Math.random()*1e3)}`,c=null,l=null,u=new Promise((m,w)=>{c=m,l=w}),f={id:d,title:a||s.substring(0,30),task:s,status:"running",startedAt:Date.now(),lastChunkTime:Date.now(),wps:0,questions:[],pendingSteerMessages:[],steer:m=>{m&&f.pendingSteerMessages.push(m)},completionPromise:u,_resolveCompletion:c,_rejectCompletion:l,progress:[]},h={chunks:[],totalWords:0};Ve.push(f),n.onSubagentUpdate&&n.onSubagentUpdate();let g=[],y={...n,taskId:d,onAskMain:async m=>{let w=`q-${Date.now()}-${Math.floor(Math.random()*1e3)}`,x=null,k=new Promise(S=>{x=S}),R={id:w,question:m,answered:!1,answer:null,askedAt:Date.now(),_resolve:x};return f.questions.push(R),f.status="waiting",n.onSubagentUpdate&&n.onSubagentUpdate(),ko(`[SYSTEM] Background subagent "${f.title}" is WAITING FOR YOUR INPUT: "${m}"
432
- Respond using tool: [tool:functions.Answer(id="${d}", answer="...")]
433
- [/SYSTEM]`),await k},onVisualFeedback:m=>{f.lastChunkTime=Date.now();let w=m.replace(/\x1b\[[0-9;]*m/g,""),x=w.match(/[✔✘✗✖🔍📖→➕↻•]\s*([A-Za-z0-9\s-]+)/);x?f.currentTool=x[1].trim():f.currentTool=w,n.onSubagentUpdate&&n.onSubagentUpdate()},onTokenChunk:(m,w)=>{let x=Date.now();if(f.lastChunkTime=x,f.currentTool="Thinking",typeof w=="number"&&w>0){h.totalWords+=w,h.chunks.push({time:x,words:w});let k=x-400;if(h.chunks=h.chunks.filter(R=>R.time>=k),h.chunks.length>0){let R=h.chunks.reduce((T,$)=>T+$.words,0),E=h.chunks[0].time,S=Math.max(.4,(x-E)/1e3);f.wps=Math.round(R/S*10)/10}}n.onSubagentUpdate&&n.onSubagentUpdate()}};return t(s,y,i,p,50,m=>{if(f.status==="cancelled")return;if(m.startsWith("[Subagent Turn")&&g.length>0&&(f.progress.push([...g]),g=[]),m.includes("[Executing Tool]")){let x=m.match(/\[Executing Tool\]\s*([a-zA-Z0-9_]+)/);x&&(!f.currentTool||f.currentTool==="Thinking")&&(f.currentTool=x[1])}let w=m;if(w.startsWith("[Tool Result]")){let x=w.split(`
434
- `);x.length>5&&(w=x.slice(0,4).join(`
435
- `)+`
436
- ... [Content/Diff Truncated from Logs] ...`)}g.push(w),n.onSubagentUpdate&&n.onSubagentUpdate()},!0).then(m=>{if(f.status==="cancelled"){f._resolveCompletion&&f._resolveCompletion(m);return}g.length>0&&(f.progress.push([...g]),g=[]),f.status="completed",f.finalAnswer=m,n.onSubagentUpdate&&n.onSubagentUpdate(),ko(`[SYSTEM] Background subagent "${f.title}" (id: ${d}) has FINISHED. Call GetProgress(id="${d}") to see the final result. [/SYSTEM]`),f._resolveCompletion&&f._resolveCompletion(m)}).catch(async m=>{let{isTerminationSignaled:w}=await import("./ai-AJO5ASXE.js");if(m.message==="Subagent task was cancelled."||f.status==="cancelled"||w()){f.status="cancelled",g.push("[SUBAGENT CANCELLED] Task was cancelled."),f.progress.push([...g]),n.onSubagentUpdate&&n.onSubagentUpdate(),f._resolveCompletion&&f._resolveCompletion(null);return}g.push(`[SUBAGENT FAILURE] Error: ${m.message}`),f.progress.push([...g]),f.status="failed",f.error=m.message,n.onSubagentUpdate&&n.onSubagentUpdate(),ko(`[SYSTEM] Background subagent "${f.title}" (id: ${d}) FAILED with error: ${m.message}. [/SYSTEM]`),f._rejectCompletion&&f._rejectCompletion(m)}),`SUCCESS: Background subagent started. Task ID: ${d}`};var Li=async(e,n={})=>{let o=I(e).id;if(!o)return'ERROR: Missing "id" argument for getProgress.';let s=Ve.find(r=>r.id===o);if(!s)return`ERROR: Subagent task with ID [${o}] not found.`;let i=`Subagent Task Status: ${s.status.toUpperCase()}
437
- `;if(i+=`Title: ${s.title}
438
- `,i+=`Task: ${s.task}
439
- `,s.startedAt){let r=Math.floor((Date.now()-s.startedAt)/1e3);i+=`Elapsed Time: ${r}s
440
- `}if(i+=`Turns Completed: ${s.progress.length}
441
- `,(s.status==="running"||s.status==="waiting")&&(s.currentTool&&(i+=`Current Tool: ${s.currentTool}
442
- `),s.wps>0&&(i+=`TPS: ${s.wps}
443
- `)),s.questions&&s.questions.length>0){let r=s.questions.filter(p=>!p.answered);r.length>0&&(i+=`
444
- **PENDING QUESTION**
445
- `,r.forEach(p=>{i+=`"${p.question}"
446
- `}),i+=`Respond using tool: [tool:functions.Answer(id="${s.id}", answer="...")]
447
-
448
- `)}return i+=`
449
- Progress Log:
450
- `,s.progress.forEach((r,p)=>{i+=`--- Turn ${p+1} ---
451
- `;let c=r.filter(l=>!l.startsWith("[SUBAGENT SUCCESS]")).map(l=>{if(l.startsWith("[Subagent Response]")){let u="[Subagent Response]",h=l.substring(u.length),g="tool:functions.";for(;;){let m=h.toLowerCase().indexOf(g);if(m===-1)break;let w=m,x=!1,k=m-1;for(;k>=0&&/\s/.test(h[k]);)k--;k>=0&&h[k]==="["&&(w=k,x=!0);let R=0,E=!1,S=null,T=m;for(;T<h.length;){let $=h[T];if(!S&&($==="'"||$==='"'||$==="`")?S=$:S&&$===S&&h[T-1]!=="\\"&&(S=null),S||($==="("?(R++,E=!0):$===")"&&R--),E&&R===0&&!S){let C=T;if(x){let b=T+1;for(;b<h.length&&/\s/.test(h[b]);)b++;b<h.length&&h[b]==="]"&&(C=b)}h=h.substring(0,w)+h.substring(C+1);break}if(T++,T===h.length){h=h.substring(0,w);break}}}return u+`
452
- `+h.trim()}return l.startsWith("[Executing Tool]")&&l.length>256?l.substring(0,256)+"...[truncated from logs]":l});i+=c.join(`
453
- `)+`
454
-
455
- `}),s.status==="completed"&&s.finalAnswer?i+=`Final Answer:
456
- ${s.finalAnswer}
457
- `:s.status==="failed"&&s.error&&(i+=`Failure Error: ${s.error}
458
- `),i.replace(/\r\n/g,`
459
- `).replace(/\n{3,}/g,`
460
-
461
- `).trim().replace(/\[TOOL RESULT\]/gi,"TOOL RESULT:")};var aa=async(e,n={})=>{let o=I(e).id;if(!o)return'ERROR: Missing "id" argument for cancel.';let s=Ve.find(i=>i.id===o);return s?s.status==="completed"||s.status==="failed"?`INFO: Subagent task with ID [${o}] has already finished with status [${s.status.toUpperCase()}].`:s.status==="cancelled"?`INFO: Subagent task with ID [${o}] is already cancelled.`:(s.status="cancelled",n.onSubagentUpdate&&n.onSubagentUpdate(),`SUCCESS: Subagent task with ID [${o}] has been cancelled.`):`ERROR: Subagent task with ID [${o}] not found.`};import wt from"fs-extra";import St from"path";var jl=["node_modules","dist","bin","logs",".git",".fluxflow","secret",".gemini",".agents","tmp","temp","build","out","snapshots"];async function so(e,n=e){let t={},o=await wt.readdir(e,{withFileTypes:!0}).catch(()=>[]);for(let s of o){if(jl.includes(s.name))continue;let i=St.join(e,s.name),a=St.relative(n,i).replace(/\\/g,"/");if(s.isDirectory()){let r=await so(i,n);Object.assign(t,r)}else{let r=await wt.stat(i).catch(()=>null);r&&(t[a]={size:r.size,mtime:r.mtimeMs})}}return t}async function la(e,n){await wt.ensureDir(e);for(let t of Object.keys(n)){let o=St.join(process.cwd(),t),s=St.join(e,t);await wt.ensureDir(St.dirname(s)),await wt.copyFile(o,s).catch(()=>{})}}async function Pi(e,n,t=null,o=null){if(!await wt.pathExists(e))return;o||(o=e);let s=await wt.readdir(e,{withFileTypes:!0}).catch(()=>[]);for(let i of s){let a=St.join(e,i.name),r=St.join(n,i.name);if(i.isDirectory())await Pi(a,r,t,o);else{let p=St.relative(o,a).replace(/\\/g,"/"),d=await wt.pathExists(r);d&&await wt.chmod(r,438).catch(()=>{}),await wt.ensureDir(St.dirname(r));let c=await wt.copyFile(a,r).then(()=>!0).catch(()=>!1);await wt.chmod(r,438).catch(()=>{}),t&&(c?d?t.replaced++:t.restored++:t.failed.push(p))}}}var Kn={async takeInitialSnapshot(e){try{let n=St.join(An,"snapshots",e);await wt.remove(n).catch(()=>{}),await wt.ensureDir(n);let t=await so(process.cwd());await la(St.join(n,"initial"),t);let o=X(un,{});o[e]={initialManifest:t,currentManifest:t,checkpoints:[{id:"initial",timestamp:new Date().toISOString(),newFiles:[],modifiedFiles:[],deletedFiles:[],toolsUsed:[]}]},he(un,o)}catch{}},async recordTurnDelta(e,n,t=[]){try{let o=X(un,{}),s=o[e];if(!s)return;let i=s.currentManifest||s.initialManifest,a=await so(process.cwd()),r=[],p=[],d=[];for(let[l,u]of Object.entries(a)){let f=i[l];f?(f.size!==u.size||f.mtime!==u.mtime)&&p.push(l):r.push(l)}for(let l of Object.keys(i))a[l]||d.push(l);let c=[...r,...p];if(c.length>0||d.length>0){let l={};for(let f of c)l[f]=a[f];let u=St.join(An,"snapshots",e,`turn_${n}`);await la(u,l)}s.checkpoints.push({id:`turn_${n}`,timestamp:new Date().toISOString(),newFiles:r,modifiedFiles:p,deletedFiles:d,toolsUsed:t}),s.currentManifest=a,he(un,o)}catch{}},async getCheckpoints(e){try{let t=X(un,{})[e];return t?t.checkpoints||[]:[]}catch{return[]}},async rollbackToCheckpoint(e,n){try{let t=X(un,{}),o=t[e];if(!o)throw new Error("No session active for Advance Rollback.");let s=o.checkpoints||[],i=s.findIndex(c=>c.id===n);if(i===-1)throw new Error(`Checkpoint [${n}] not found.`);let a=St.join(An,"snapshots",e),r={restored:0,replaced:0,failed:[]},p=await so(process.cwd());for(let c of Object.keys(p)){let l=St.join(process.cwd(),c);await wt.chmod(l,438).catch(()=>{}),await wt.remove(l).catch(()=>{})}let d=St.join(a,"initial");await Pi(d,process.cwd(),r,d);for(let c=1;c<=i;c++){let l=s[c],u=St.join(a,l.id);if(await Pi(u,process.cwd(),r,u),l.deletedFiles&&l.deletedFiles.length>0)for(let f of l.deletedFiles){let h=St.join(process.cwd(),f);await wt.chmod(h,438).catch(()=>{}),await wt.remove(h).catch(()=>{})}}return o.checkpoints=s.slice(0,i+1),o.currentManifest=await so(process.cwd()),he(un,t),{checkpointId:n,stats:r}}catch(t){throw new Error(`Rollback failed: ${t.message}`)}},async getLatestFileChanges(e){try{let t=X(un,{})[e];if(!t||!t.checkpoints||t.checkpoints.length===0)return{newFiles:[],modifiedFiles:[],deletedFiles:[]};let o=t.checkpoints[t.checkpoints.length-1];return{newFiles:o.newFiles||[],modifiedFiles:o.modifiedFiles||[],deletedFiles:o.deletedFiles||[]}}catch{return{newFiles:[],modifiedFiles:[],deletedFiles:[]}}},async cleanup(e){try{let n=St.join(An,"snapshots",e);await wt.remove(n).catch(()=>{});let t=X(un,{});t[e]&&(delete t[e],he(un,t))}catch{}}};var Di=async(e,n={})=>{let t=I(e),o=t.method,s=t.id,i=n.chatId;if(!n.systemSettings?.advanceRollback)return"ERROR: Advance Rollback feature is currently disabled in settings under Security. Tell user to enable it.";if(!i)return"ERROR: No active chat transaction found for rollback.";if(o==="getCheckpoint"){let r=await Kn.getCheckpoints(i);if(r.length===0)return"No checkpoints available.";let p={write_file:"WriteFile",update_file:"PatchFile",view_file:"ReadFile",read_folder:"ReadFolder",exec_command:"Run",web_search:"WebSearch",web_scrape:"WebScrape",search_keyword:"SearchKeyword",CodeSearch:"SearchKeyword",code_search:"SearchKeyword",write_pdf:"WritePDF",write_docx:"WriteDoc",generate_image:"GenerateImage",file_map:"FileMap",todo:"Todo",goal:"Goal",Goal:"Goal",await:"Await",ask:"Ask",ask_user:"Ask",invoke:"Invoke",invokesync:"InvokeSync",getprogress:"GetProgress",cancel:"Cancel",emergency_rollback:"EmergencyRollback",emergencyrollback:"EmergencyRollback"},d=l=>p[l]||p[l.toLowerCase()]||l,c=`Available checkpoints for rollback:
462
-
463
- `;for(let l of r)if(l.id==="initial")c+=`--- Initial State (id: initial) ---
464
- Tools Used: User Prompted for task
465
-
466
- `;else{let u=l.id.replace("turn_",""),f=l.toolsUsed&&l.toolsUsed.length>0?l.toolsUsed.map(d).join(", "):"None";c+=`--- Turn ${u} (id: ${l.id}) ---
467
- Tools Used: ${f}
468
-
469
- `}return c.trim()}else if(o==="forceRevert"){if(!s)return"ERROR: Missing required parameter 'id' for forceRevert.";try{let r=await Kn.rollbackToCheckpoint(i,s),{checkpointId:p,stats:d}=r,c=d.restored+d.replaced+d.failed.length,l=`SUCCESS: Repository rolled back to checkpoint [${p}].
470
-
471
- `;return l+=`Stats:
472
- `,l+=` Restored : ${d.restored} file${d.restored!==1?"s":""} (new to workspace)
473
- `,l+=` Replaced : ${d.replaced} file${d.replaced!==1?"s":""} (overwritten)
474
- `,l+=` Failed : ${d.failed.length} file${d.failed.length!==1?"s":""}`,d.failed.length>0&&(l+=`
475
- ${d.failed.join(`
476
- `)}`),l+=`
477
- \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500-
478
- `,l+=` Total : ${c} file${c!==1?"s":""} processed`,l}catch(r){return`ERROR: ${r.message}`}}else return`ERROR: Invalid method "${o}". Use "getCheckpoint" or "forceRevert".`};var Ps=async(e,n={})=>{let t=I(e),o=t.id,s=parseInt(t.timeout||t.time||"120",10);if((isNaN(s)||s<=0)&&(s=120),s>300&&(s=300),!o)return t.time?(await new Promise(p=>setTimeout(p,s*1e3)),`SUCCESS: Waited for ${s}s.`):'ERROR: Missing "id" argument for Await.';let i=Ve.find(p=>p.id===o);if(!i)return`ERROR: Subagent task with ID [${o}] not found.`;if(i.status==="completed")return`SUCCESS: Subagent task [${o}] completed.
479
- Final Answer:
480
- ${i.finalAnswer||"(No output)"}`;if(i.status==="failed")return`ERROR: Subagent task [${o}] failed.
481
- Error: ${i.error||"Unknown error"}`;if(i.status==="cancelled")return`INFO: Subagent task [${o}] was cancelled.`;let a,r=new Promise(p=>{a=setTimeout(()=>{p({type:"timeout"})},s*1e3)});try{let p=await Promise.race([i.completionPromise.then(()=>({type:"completion"})),r]);return clearTimeout(a),p.type==="timeout"?`TIMEOUT: Subagent task [${o}] is still running (status: ${i.status.toUpperCase()}) after ${s}s. You can continue other work or call Await again.`:i.status==="completed"?`SUCCESS: Subagent task [${o}] completed.
482
- Final Answer:
483
- ${i.finalAnswer||"(No output)"}`:i.status==="failed"?`ERROR: Subagent task [${o}] failed.
484
- Error: ${i.error||"Unknown error"}`:i.status==="cancelled"?`INFO: Subagent task [${o}] was cancelled.`:`INFO: Subagent task [${o}] status changed to ${i.status.toUpperCase()}.`}catch(p){return clearTimeout(a),`ERROR: Exception while awaiting subagent [${o}]: ${p.message}`}};var Ds=async(e,n={})=>{let t=I(e),o=t.id,s=t.answer||t.response;if(!o)return'ERROR: Missing "id" argument for Answer.';if(!s)return'ERROR: Missing "answer" argument for Answer.';let i=Ve.find(r=>r.id===o);if(!i)return`ERROR: Subagent task with ID [${o}] not found.`;if(!i.questions||i.questions.length===0)return`INFO: Subagent task [${o}] has no pending questions.`;let a=i.questions.filter(r=>!r.answered);return a.length===0?`INFO: Subagent task [${o}] has no unanswered questions.`:(a.forEach(r=>{r.answered=!0,r.answer=s,r.answeredAt=Date.now(),r._resolve&&r._resolve(s)}),i.status="running",n.onSubagentUpdate&&n.onSubagentUpdate(),`SUCCESS: Answer provided to subagent task [${o}]. Subagent execution resumed.`)};var oo=async(e,n={})=>{let t=I(e),o=t.id,s=t.message||t.instruction||t.text||t.prompt;if(!o)return'ERROR: Missing "id" argument for Steer.';if(!s)return'ERROR: Missing "message" argument for Steer.';let i=Ve.find(a=>a.id===o);return i?i.status==="completed"||i.status==="failed"||i.status==="cancelled"?`ERROR: Cannot steer subagent task [${o}] because it has already finished with status [${i.status.toUpperCase()}].`:(typeof i.steer=="function"?i.steer(s):(i.pendingSteerMessages||(i.pendingSteerMessages=[]),i.pendingSteerMessages.push(s)),n.onSubagentUpdate&&n.onSubagentUpdate(),`SUCCESS: Steering instruction injected into subagent task [${o}]. It will be processed on the subagent's turn.`):`ERROR: Subagent task with ID [${o}] not found.`};import{mouse as ln,keyboard as Nt,Button as io,Key as L,Point as ro,clipboard as Hl}from"@nut-tree-fork/nut-js";ln.config.autoDelayMs=50;Nt.config.autoDelayMs=50;async function Fi(){try{await Nt.releaseKey(L.LeftControl,L.RightControl,L.LeftAlt,L.RightAlt,L.LeftShift,L.RightShift,L.LeftSuper,L.RightSuper)}catch{}}async function On(e,n,t={}){let o=await zs(n);if(!o&&(e==="move"||e==="click"||e==="drag"))return`ERROR: Invalid target location specified: ${JSON.stringify(n)}`;try{switch(e.toLowerCase()){case"move":return await ln.setPosition(new ro(o.x,o.y)),`SUCCESS: Moved mouse to grid target ${typeof n=="string"?n:`(${o.x}, ${o.y})`}`;case"click":{await ln.setPosition(new ro(o.x,o.y));let s=t.button==="right"?io.RIGHT:t.button==="middle"?io.MIDDLE:io.LEFT;return t.clickType==="double"?await ln.doubleClick(s):await ln.click(s),`SUCCESS: ${t.clickType||"Single"} clicked ${t.button||"left"} button at ${typeof n=="string"?n:`(${o.x}, ${o.y})`}`}case"drag":{let s=await zs(t.from||n),i=await zs(t.to);return!s||!i?'ERROR: Drag requires valid "from" and "to" target coordinates/grid codes.':(await ln.setPosition(new ro(s.x,s.y)),await ln.pressButton(io.LEFT),await ln.setPosition(new ro(i.x,i.y)),await ln.releaseButton(io.LEFT),`SUCCESS: Dragged mouse from (${s.x}, ${s.y}) to (${i.x}, ${i.y})`)}case"scroll":{let s=o||await zs({x:640,y:360});s&&(await ln.setPosition(new ro(s.x,s.y)),await new Promise(p=>setTimeout(p,60)));let i=parseInt(t.amount,10);(isNaN(i)||i<=0)&&(i=5);let a=i>50?Math.min(20,Math.max(1,Math.round(i/100))):Math.min(20,i),r=t.direction==="up";for(let p=0;p<a;p++)r?await ln.scrollUp(120):await ln.scrollDown(120),await new Promise(d=>setTimeout(d,20));return`SUCCESS: Scrolled ${t.direction||"down"} (${a} notches${o?` at target (${o.x}, ${o.y})`:" at screen center"})`}default:return`ERROR: Unsupported mouse action "${e}"`}}catch(s){return`ERROR: Mouse action failed: ${s.message}`}}var ca={enter:L.Enter,return:L.Return,escape:L.Escape,esc:L.Escape,backspace:L.Backspace,tab:L.Tab,space:L.Space,up:L.Up,down:L.Down,left:L.Left,right:L.Right,ctrl:L.LeftControl,control:L.LeftControl,alt:L.LeftAlt,shift:L.LeftShift,cmd:L.LeftCmd,win:L.LeftWin,meta:L.LeftWin,super:L.LeftSuper,a:L.A,b:L.B,c:L.C,d:L.D,e:L.E,f:L.F,g:L.G,h:L.H,i:L.I,j:L.J,k:L.K,l:L.L,m:L.M,n:L.N,o:L.O,p:L.P,q:L.Q,r:L.R,s:L.S,t:L.T,u:L.U,v:L.V,w:L.W,x:L.X,y:L.Y,z:L.Z,0:L.Num0,1:L.Num1,2:L.Num2,3:L.Num3,4:L.Num4,5:L.Num5,6:L.Num6,7:L.Num7,8:L.Num8,9:L.Num9,f1:L.F1,f2:L.F2,f3:L.F3,f4:L.F4,f5:L.F5,f6:L.F6,f7:L.F7,f8:L.F8,f9:L.F9,f10:L.F10,f11:L.F11,f12:L.F12},da=e=>{if(!e)return;let n=String(e).toLowerCase().trim();if(ca[n]!==void 0)return ca[n];if(L[e]!==void 0)return L[e];if(L[n.toUpperCase()]!==void 0)return L[n.toUpperCase()]};async function Ln(e,n,t={}){try{switch(e.toLowerCase()){case"type":{if(typeof n!="string")return"ERROR: Type action requires a valid string input";await Fi(),await Hl.setContent(n);let s=process.platform==="darwin"?L.LeftSuper:L.LeftControl;return await Nt.pressKey(s,L.V),await Nt.releaseKey(s,L.V),await Fi(),t.autoPressEnter?(await new Promise(i=>setTimeout(i,50)),await Nt.type(L.Enter),`SUCCESS: Typed text input ("${n.length>20?n.substring(0,20)+"...":n}") and pressed Enter`):`SUCCESS: Typed text input ("${n.length>20?n.substring(0,20)+"...":n}")`}case"key_press":{let o=da(n);return o===void 0?`ERROR: Unknown key name "${n}"`:(await Nt.type(o),`SUCCESS: Pressed key ${n}`)}case"key_combination":{if(!Array.isArray(n))return'ERROR: key_combination requires an array of keys (e.g. ["ctrl", "c"])';let o=n.map(s=>da(s)).filter(s=>s!==void 0);return o.length===0?"ERROR: Invalid key combination":(await Nt.pressKey(...o),await Nt.releaseKey(...o),`SUCCESS: Executed key combination [${n.join(" + ")}]`)}case"clear_input":return await Nt.pressKey(L.LeftControl,L.A),await Nt.releaseKey(L.LeftControl,L.A),await Nt.type(L.Backspace),"SUCCESS: Cleared active text input (Select All + Backspace)";case"browser_back":{let o=process.platform==="darwin";return o?(await Nt.pressKey(L.LeftSuper,L.Left),await Nt.releaseKey(L.LeftSuper,L.Left)):(await Nt.pressKey(L.LeftAlt,L.Left),await Nt.releaseKey(L.LeftAlt,L.Left)),await Fi(),`SUCCESS: Browser back navigation (${o?"Cmd+Left":"Alt+Left"})`}default:return`ERROR: Unsupported keyboard action "${e}"`}}catch(o){return`ERROR: Keyboard action failed: ${o.message}`}}var ao=async(e,n={})=>{let t=I(e),o=t.action||t.type||t.cmd,s=t.target||t.grid||t.gridCode||t.location||t.input;if(!o)return'ERROR: Missing required "action" argument for computer_action (e.g. move, click, drag, scroll, type, key_press, key_combination).';let i=o.toLowerCase();if(i.startsWith("mouse_")||["move","click","drag","scroll"].includes(i)){let a=i.replace("mouse_","");return await On(a,s,{button:t.button,clickType:t.clickType||t.type,from:t.from,to:t.to,direction:t.direction,amount:t.amount?parseInt(t.amount,10):void 0})}if(i.startsWith("key_")||i==="type"||i==="press"){let a=i;i==="press"&&(a="key_press");let r=t.autoPressEnter===!0||t.autoPressEnter==="true"||t.enter===!0||t.enter==="true";return await Ln(a,s||t.text||t.keys,{...t,autoPressEnter:r})}return`ERROR: Unrecognized action "${o}". Supported actions: move, click, drag, scroll, type, key_press, key_combination.`};import pa from"screenshot-desktop";import co from"sharp";import fa from"fs-extra";import ua from"path";import"@nut-tree-fork/nut-js";async function Ni(e,n,t){if(!(!process.env.SHOW_DEBUG_GRID&&!process.env.DEBUG_OCR))try{let o=ua.resolve(process.cwd(),"screenshots",e);await fa.ensureDir(o),await fa.writeFile(ua.join(o,n),t)}catch{}}function Gl(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ql(e,n,t=1/0){if(e===n)return 0;if(e.length===0)return n.length;if(n.length===0)return e.length;if(Math.abs(e.length-n.length)>t)return t+1;let o=Array.from({length:n.length+1},(s,i)=>i);for(let s=1;s<=e.length;s++){let i=[s],a=s;for(let r=1;r<=n.length;r++){let p=e[s-1]===n[r-1]?0:1,d=Math.min(i[r-1]+1,o[r]+1,o[r-1]+p);i.push(d),d<a&&(a=d)}if(o=i,a>t)return t+1}return o[n.length]}function zl(e){return e<=4?0:e<=8?1:2}async function Bi(e,n=3){let t=await co(e).metadata();return co(e).resize(Math.round(t.width*n),Math.round(t.height*n),{kernel:"lanczos3"}).greyscale().normalise().toBuffer()}function Kl(e){if(!e)return{words:[],lines:[]};let n=[],t=new Map;for(let s of e.split(`
485
- `)){let i=s.split(" ");if(i.length<12||parseInt(i[0])!==5)continue;let r=i[2],p=i[3],d=i[4],c=parseInt(i[6]),l=parseInt(i[7]),u=parseInt(i[8]),f=parseInt(i[9]),h=parseFloat(i[10]),g=i.slice(11).join(" ").trim();if(!g||h<0)continue;let y={x0:c,y0:l,x1:c+u,y1:l+f},m={text:g,confidence:h,bbox:y};n.push(m);let w=`${r}_${p}_${d}`;t.has(w)||t.set(w,{words:[],bbox:{x0:1/0,y0:1/0,x1:-1/0,y1:-1/0}});let x=t.get(w);x.words.push(m),x.bbox.x0=Math.min(x.bbox.x0,y.x0),x.bbox.y0=Math.min(x.bbox.y0,y.y0),x.bbox.x1=Math.max(x.bbox.x1,y.x1),x.bbox.y1=Math.max(x.bbox.y1,y.y1)}let o=[];for(let s of t.values())s.words.length>0&&o.push({text:s.words.map(i=>i.text).join(" "),bbox:s.bbox,words:s.words});return{words:n,lines:o}}function Yl(e){if(!(e.words&&e.words.length>0)){if(e.blocks&&e.blocks.length>0){e.words=[],e.lines=[];for(let n of e.blocks)for(let t of n.paragraphs||[])for(let o of t.lines||[]){o.bbox&&e.lines.push(o);for(let s of o.words||[])s.bbox&&e.words.push(s)}if(e.words.length>0)return}if(e.tsv){let n=Kl(e.tsv);e.words=n.words,e.lines=n.lines}}}function Ui(e,n,t=0,o=0,s=1){Yl(e);let i=r=>({x0:Math.round(r.x0/s)+t,y0:Math.round(r.y0/s)+o,x1:Math.round(r.x1/s)+t,y1:Math.round(r.y1/s)+o}),a=[];if(e.lines&&e.lines.length>0)for(let r of e.lines){let p=r.text?r.text.toLowerCase().trim():"";if(!p||!r.bbox||!(p===n||new RegExp(`\\b${Gl(n)}\\b`,"i").test(p)))continue;let c=r.words||(e.words?e.words.filter(h=>h.bbox&&h.bbox.x0>=r.bbox.x0-5&&h.bbox.x1<=r.bbox.x1+5&&h.bbox.y0>=r.bbox.y0-5&&h.bbox.y1<=r.bbox.y1+5):[]),l=n.split(/\s+/),u=l.map(h=>h.replace(/[^a-z0-9]/g,"")).join(" "),f=!1;if(c.length>0)for(let h=0;h<=c.length-l.length;h++){let g=c.slice(h,h+l.length),y=g.map(m=>(m.text||"").toLowerCase().trim().replace(/[^a-z0-9]/g,"")).join(" ");if(y===u||y.includes(u)){let m={x0:Math.min(...g.map(w=>w.bbox.x0)),y0:Math.min(...g.map(w=>w.bbox.y0)),x1:Math.max(...g.map(w=>w.bbox.x1)),y1:Math.max(...g.map(w=>w.bbox.y1))};a.push(i(m)),f=!0}}f||a.push(i(r.bbox))}if(a.length===0&&e.words&&e.words.length>0)for(let r of e.words){let p=r.text?r.text.toLowerCase().trim().replace(/[^a-z0-9]/g,""):"",d=n.replace(/[^a-z0-9]/g,"");p===d&&r.bbox&&a.push(i(r.bbox))}if(a.length===0&&e.words&&e.words.length>0){let r=zl(n.length);for(let p of e.words){let d=p.text?p.text.toLowerCase().trim():"";d.length>=3&&Math.abs(d.length-n.length)<=r&&ql(d,n,r)<=r&&p.bbox&&a.push(i(p.bbox))}}return a}function Wi(e,n){let t=null,o=1/0;for(let s of e){let i=Math.round((s.x0+s.x1)/2),a=Math.round((s.y0+s.y1)/2),r=n.x>=s.x0&&n.x<=s.x1&&n.y>=s.y0&&n.y<=s.y1,p=Math.hypot(i-n.x,a-n.y),d=r?0:p;d<o&&(o=d,t={x:i,y:a,dist:p,containsPoint:r,bbox:s})}return t}function Vl(e,n,t,o){let a=Math.ceil(e/4),r=Math.ceil(n/2),p=[];for(let d=0;d<2;d++)for(let c=0;c<4;c++){let l=c*a,u=d*r,f=Math.min(a,e-l),h=Math.min(r,n-u),g=l+f/2,y=u+h/2,m=t>=l&&t<l+f&&o>=u&&o<u+h;p.push({x0:l,y0:u,w:f,h,cx:g,cy:y,containsTarget:m})}return p.sort((d,c)=>{if(d.containsTarget)return-1;if(c.containsTarget)return 1;let l=Math.hypot(d.cx-t,d.cy-o),u=Math.hypot(c.cx-t,c.cy-o);return l-u})}var Lo=null;async function Jl(){return Lo||(Lo=(async()=>{let{createWorker:e}=await import("tesseract.js"),n=await import("fs-extra"),{CU_CACHE_DIR:t}=await import("./paths-R3DD7CRF.js");return n.ensureDirSync(t),e("eng",1,{cachePath:t,logger:()=>{}})})().catch(e=>{throw Lo=null,e})),Lo}var lo=null,ha=null;async function Xl(){let{getActiveDisplay:e}=await import("./screen_grid-Y6GHBUFE.js"),n=await e();if(lo&&ha===n)return lo;ha=n,lo={format:"png"};try{let t=await pa.listDisplays();t&&t.length>0&&(lo={format:"png",screen:(t[n]||t[0]).id})}catch{}return lo}var ji=async(e,n={})=>{let t=!!(process.env.SHOW_DEBUG_GRID||process.env.DEBUG_OCR||process.env.VERBOSE),o=performance.now(),s=o,i=f=>{if(!t)return;let h=performance.now(),g=(h-s).toFixed(0),y=(h-o).toFixed(0);console.log(`[Click Perf] +${g}ms (${y}ms total) -> ${f}`),s=h};i("Starting click()");let a=I(e),r=a.gridId||a.grid||a.coordinate||a.target||a.id,p=(a.type||a.clickType||"single").toLowerCase(),d=(a.button||"left").toLowerCase(),c=a.intendedClickText||a.text||"";if(!r&&!c)return'ERROR: Missing required "gridId" parameter for Click tool.';let l=r;if(c)try{i("Parsing grid code");let f=r?xr(r):null;i("Getting display options");let h=await Xl();i("Taking desktop screenshot");let g=await pa(h);i("Getting image metadata");let y=await co(g).metadata(),m=y.width||1920,w=y.height||1080,x=f?{x:Math.round(f.x*(m/1280)),y:Math.round(f.y*(w/720))}:{x:m/2,y:w/2},k=c.toLowerCase().trim();i("Acquiring OCR worker");let R=await Jl(),E=null,S="",T=f?220:500;if(f){i("Pass 1: Cropping target crop (3x zoom window, 2x upscale)");let $=Math.min(Math.round(m/3),m),C=Math.min(Math.round(w/3),w),b=Math.max(0,Math.min(m-$,x.x-Math.floor($/2))),v=Math.max(0,Math.min(w-C,x.y-Math.floor(C/2))),O=await co(g).extract({left:b,top:v,width:$,height:C}).toBuffer(),P=2,W=await Bi(O,P),N=k.replace(/[^a-z0-9]/g,"_");await Ni("cropped",`crop_${Date.now()}_${N}.png`,W),i("Pass 1: Running Tesseract OCR recognize on crop (PSM 11 - Sparse Text)"),await R.setParameters({tessedit_pageseg_mode:"11"});let{data:Y}=await R.recognize(W,{},{tsv:!0,blocks:!0});if(i("Pass 1: OCR recognition finished, extracting matches"),Y&&Y.text){t&&console.log(`[Pass 1 OCR Read]: "${Y.text.trim().replace(/\s+/g," ")}"`);let ie=Ui(Y,k,b,v,P);if(ie.length>0){let Me=Wi(ie,x);Me&&(Me.containsPoint||Me.dist<=T)&&(E=Me,S="centered target crop OCR")}}}if(!E){i("Pass 2: Entering Full-Screen OCR (broad scan, PSM 3 - Auto)");let $=await Bi(g,2),C=k.replace(/[^a-z0-9]/g,"_");await Ni("fullscreen",`full_${Date.now()}_${C}.png`,$),i("Pass 2: Running Tesseract on full screen"),await R.setParameters({tessedit_pageseg_mode:"3"});let{data:b}=await R.recognize($,{},{tsv:!0,blocks:!0});if(i("Pass 2: Full-screen OCR finished"),b&&b.text){let v=Ui(b,k,0,0,2);if(v.length>0){let O=Wi(v,x);O&&(E=O,S="full-screen OCR")}}}if(!E){i("Pass 3: Entering Tiled OCR fallback (high-res 3x)");let $=Vl(m,w,x.x,x.y),C=k.replace(/[^a-z0-9]/g,"_");await R.setParameters({tessedit_pageseg_mode:"11"});for(let b=0;b<$.length;b++){let v=$[b];i(`Pass 3: Preprocessing tile ${b+1}/${$.length}`);let O=await co(g).extract({left:v.x0,top:v.y0,width:v.w,height:v.h}).toBuffer(),P=await Bi(O,3);await Ni("tiles",`tile_${b+1}_${Date.now()}_${C}.png`,P),i(`Pass 3: Running Tesseract on tile ${b+1}`);let{data:W}=await R.recognize(P,{},{tsv:!0,blocks:!0});if(!W||!W.text)continue;let N=Ui(W,k,v.x0,v.y0,3);if(N.length>0){let Y=Wi(N,x);if(Y){E=Y,S=`tile ${b+1} OCR (${v.containsTarget?"target tile":`offset ${v.x0},${v.y0}`})`;break}}}}if(E){let $={x:Math.round(E.x*(1280/m)),y:Math.round(E.y*(720/w))};i(`Executing mouse click on matched target (${S})`);let C=await On("click",$,{button:d,clickType:p});return i("Click completed successfully"),`${C} (${S} for "${c}" at ${Math.round(E.dist)}px distance)`}else t&&console.log(`[OCR] No match found for "${c}". Falling back to gridId.`)}catch(f){t&&console.error("[OCR Error]",f)}i(`Executing mouse click on fallback gridId: ${l}`);let u=await On("click",l,{button:d,clickType:p});return i("Fallback click completed"),u};var Hi=async(e,n={})=>{let t=I(e),o=t.fromGridId||t.from||t.start,s=t.toGridId||t.to||t.end;return!o||!s?'ERROR: Drag requires both "fromGridId" and "toGridId" parameters.':await On("drag",o,{from:o,to:s})};var Gi=async(e,n={})=>{let t=I(e),o=(t.direction||"down").toLowerCase(),s=t.amount?parseInt(t.amount,10):6,i=t.gridId||t.grid||t.coordinate||t.target||t.id||null;return await On("scroll",i,{direction:o,amount:s})};var Po=async(e,n={})=>{let t=I(e),o=t.text||t.input||t.value||"",s=t.autoPressEnter===!0||t.autoPressEnter==="true"||t.enter===!0||t.enter==="true";return o==null?'ERROR: Missing required "text" parameter for KeyboardTyping tool.':await Ln("type",String(o),{autoPressEnter:s})};var Do=async(e,n={})=>{let t=I(e),o=t.key||t.keys||t.input||t.shortcut;if(!o)return'ERROR: Missing required "key" parameter for KeyPress tool.';let s=String(o).trim().toLowerCase();if(s==="clearinput"||s==="clear_input"||s==="clear")return await Ln("clear_input");if(s==="back"||s==="browser_back"||s==="browserBack")return await Ln("browser_back");if(s.includes(";")||s.includes("+")){let i=s.split(/[;+]/).map(a=>a.trim()).filter(Boolean);return await Ln("key_combination",i)}return await Ln("key_press",s)};var Fo=async(e,n={})=>"SUCCESS: Screen recapture requested. The latest gridded screenshot is provided for your next decision.";var Ql={web_search:di,web_scrape:fi,memory:ui,chat:hi,view_file:Qs,write_file:pi,update_file:xi,exec_command:si,read_folder:ki,write_pdf:Ti,write_docx:Ei,search_keyword:eo,generate_image:Mi,saveSummary:to,addMemScore:Ls,file_map:Ii,todo:no,Todo:no,goal:no,Goal:no,invokeSync:Oi,invoke:ra,getProgress:Li,cancel:aa,awaitSubagent:Ps,answerSubagent:Ds,steerSubagent:oo,computer_action:ao,computer_use:ao,ComputerAction:ao,ComputerUse:ao,click:ji,Click:ji,drag:Hi,Drag:Hi,scroll:Gi,Scroll:Gi,keyboard_typing:Po,KeyboardTyping:Po,keyboardtyping:Po,key_press:Do,KeyPress:Do,keypress:Do,recapture_screen:Fo,RecaptureScreen:Fo,recapturescreen:Fo,invoke_sync:Oi,get_progress:Li,await_subagent:Ps,answer_subagent:Ds,steer_subagent:oo,steer:oo,Steer:oo,ask:Si,Ask:Si,WebSearch:di,WebScrape:fi,ReadFile:Qs,ReadFolder:ki,WriteFile:pi,PatchFile:xi,WritePDF:Ti,WriteDoc:Ei,Run:si,SearchKeyword:eo,CodeSearch:eo,code_search:eo,Memory:ui,Chat:hi,GenerateImage:Mi,saveSumary:to,SaveSummary:to,SaveSumary:to,add_mem_score:Ls,AddMemScore:Ls,addMemoryScore:Ls,AddMemoryScore:Ls,FileMap:Ii,answer:Ds,Answer:Ds,AnswerSubagent:Ds,await:Ps,Await:Ps,AwaitSubagent:Ps,EmergencyRollback:Di,emergency_rollback:Di},fo=async(e,n,t={})=>{let o=t.mode?t.mode.toLowerCase():"flux",s=e.toLowerCase(),a=["memory","chat","savesummary","addmemscore","add_mem_score","ask","web_search","web_scrape","await"].some(c=>s.includes(c))||s==="ask",p=["click","drag","scroll","keyboardtyping","keyboard_typing","keypress","key_press","recapturescreen","recapture_screen","computer"].some(c=>s.includes(c));if(!a){if(o==="flow"){if(!(s.includes("write_pdf")||s.includes("write_docx")||s.includes("generate_image")))return`ERROR: Tool [${e}] is a Workspace Tool and NOT available in Flow mode. Tell user to switch (\`/mode flux\`) to use this tool.`}else if(o==="icu"){if(!p)return`ERROR: Tool [${e}] is not available in Computer Use mode. ICU mode only supports Computer Use tools (Click, Drag, Scroll, KeyboardTyping, KeyPress, RecaptureScreen).`}else if(s.includes("write_pdf")||s.includes("write_docx")||s.includes("generate_image"))return`ERROR: Tool [${e}] is not available in ${t.mode||"Flux"} mode. Tell user to switch (\`/mode flow\`) for document generation.`}let d=Ql[e];if(!d)return`ERROR: Tool [${e}] not found in registry.`;try{return await d(n,t)}catch(c){let l=c instanceof Error?c.message:String(c);return`ERROR: Execution failed for [${e}]: ${l}`}};import Q from"path";import Oe from"fs";import Zl from"gradient-string";var qi=["I have a regex for your problems.","Your terminal, my kingdom.","Blowing on the cartridge helps. Probably.","Don't panic. I have the towel.","Logic is the start of wisdom.","Try to exit Vim? Good luck.","I speak fluent Terminal.","The cake is a lie. This code is not.","I have no bugs, just surprise features.","Rewriting in Rust... just for fun.","Coffee in, clean commits out.","The magic smoke stays inside today.","A semicolon short of a miracle.","One does not simply code without a bug.","Keep it simple. Keep it terminal.","Regex: now you have two problems.","I dream in binary.","Root access or bust.","Wait for the dial-up tone. Just kidding.","I take the 'labor' out of collab.","My other process is a TARDIS.","Calculated response: 42.","Ponder the orb. Ponder the code.","Less talk, more flow.","Elegance in every byte.","Build something the world is not ready for.","Your wishes, my tool calls.","I act in Flux. I think in Flow.","Syntax error in the universe. Please fix.","Your project, my obsession.","I am not a bot, I am an architect.","Digital spirits consulted. They say: Ship it.","Reticulate splines. Engage humor.","Code like poetry. Run like water.","Minimalism is the ultimate flex.","The truth is in the logs.","Follow the white rabbit.","There is no spoon. Only code.","Binary is the only language I trust.","I have a good feeling about this.","Pew pew! Lasers charged.","Divide by zero? Not today.","Search for the correct USB orientation...","I've got a fever, and the only cure is more code.","The code gremlins are on our side.","My favorite command? Yours.","Stay hungry. Stay active.","Momentum is your best friend.","Lead the flow. Don't chase it.","A fresh batch of bytes. Hot and ready.","I orchestrate the ones and zeros.","Smart enough to help. Humble enough to ask.","Think twice. Code once.","Pure intent. Pure execution.","Small steps. Massive impact.","Your terminal is a canvas.","Efficiency is my second name.","I have seen things you people wouldn't believe.","Let the thoughts marinate.","The best feature? The one you don't need.","Precision is the only perfection.","Stay focused. Stay terminal.","Silence is the best debugger.","Erase the debt. Commit the code.","Velocity meets stability.","Ship it. Improve it. Repeat.","Build tomorrow, right now.","Turn logic into reality.","The best way to predict the future is to build it.","Break barriers, not builds.","Fuel the next breakthrough.","Momentum is key.","Terminal vibes only.","Your digital co-pilot is ready.","Partner in code. Partner in crime.","I speak in semicolons.","Ready for the next great idea.","Just a moment. In the zone.","Polishing the algorithms. Hold tight.","Craft a masterpiece today.","Debug the universe. Start here.","Warp speed engaged. Almost.","The cake is not a lie. It's just loading.","Finish the Kessel Run in 12 parsecs.","Do a barrel roll!","Waiting for the respawn.","Press Start to continue.","Herding digital cats... done.","The hamsters are fast today.","Tasting the snozberries.","I go for speed. I go for flow.","Real life or just fantasy?","Poking the bear... gently.","Ensure the magic smoke stays inside.","Try turning it off and on again.","Construct additional pylons.","New line? Ctrl+J is your friend.","Release the HypnoDrones.","Push the button, Frank.","My other loading screen is even funnier.","Pretty sure a cat walked on my keyboard.","Recalibrate the humor-o-meter.","Summon the code gremlins.","I've seen your browser history. Just kidding.","Charge the laser... pew pew!","Dividing by zero... just for a sec.","Looking for an adult supervisor. Found none.","Make it go beep boop.","Buffering... for effect.","Entangle quantum particles... complete.","Polishing the chrome on my algorithms.","Are you not entertained?","Just waiting for the dial-up tone.","Reboot the humor module.","Defragment memories. Check.","Optimizing for ludicrous speed.","Swapping bits. Don't tell the bytes.","Garbage collected. I am back.","Assembling the interwebs.","Converting coffee to logic.","Update syntax for reality.","Rewire the synapses.","Greasin' the cogs.","Engage the improbability drive.","Channel the Force.","Align the stars. Respond now.","The cake is a lie. The prompt is real.","I'm Feeling Lucky.","Shipping awesomeness.","Navigating the slime mold.","Consult digital spirits.","Ask the magic conch shell.","One moment. Optimizing humor.","Shuffling punchlines.","Compiling brilliance.","Summon the cloud of wisdom.","Prepare to dazzle.","Hold tight. Crafting a response.","Tuning the algorithms.","Following the white rabbit... again.","The truth is in here. Somewhere.","Herding cats is my day job.","Distracting you with this phrase.","Almost there. Probably.","Rickrolling my creator. Don't tell.","Slapping the bass.","Is this real life?","Ponder the orb. Type the prompt.","Thoughtful gaze initiated.","Computer's favorite snack? Microchips.","Why Java? Because I don't C#.","Charging the laser... wait for it.","Dividing by zero... just kidding!","Adult supervision not found. Proceed.","Beep boop. I'm a real boy.","Wait for the respawn.","Finish the run. Ship the code.","Fiddling with character creation.","Just a moment. Finding a meme.","Pressing A to continue.","Loading wit.exe.","Pre-heating the servers.","Calibrate flux capacitor.","Channeling the Force.","Aligning the stars.","The truth is in the code.","Don't panic.","Blowing on the cartridge.","Doing a barrel roll!","Respawning in 3... 2... 1...","The cake is a lie.","Fiddling with character settings.","Finding a suitable pun.","Distracting with wit.","Almost ready.","Hamsters on speed today.","Patting Cloudy on the head.","Rickrolling the logs.","Slapping the code.","Got a good feeling about this.","Poking the prompt.","Researching latest memes.","Making it more witty.","Thinking... hmmm.","Fish with no eyes? Fsh.","Broken pencil? Pointless.","Percussive maintenance applied.","USB orientation: 3rd try's the charm.","Rust rewrite in 3... 2...","Exiting Vim... someday.","Spinning the hamster wheel.","Not a bug. Unplanned feature.","Engage.","I'll be back.","Machine spirit consulted.","Letting the thoughts marinate.","Orb pondered.","Thoughtful gaze engaged.","Charging the laser...","Making it go beep.","Buffering...","Quantum particles entangled.","Polishing the chrome.","Entertained yet?","Gremlins summoned.","Dial-up tone finished.","Humor meter recalibrated.","Cat on keyboard. Sending help.","Enhancing...","Turn it off and on again.","Constructing pylons.","HypnoDrones released.","Pushing the button."];var ma=[{name:"Cyan Cyberpunk",text:"cyan",textMuted:"#4da6b8",textDim:"#2d6d7a",textInverted:"black",border:"cyan",borderMuted:"#1a5966",borderDim:"#0f3840",bg:void 0,cardBg:"#061e24",highlightBg:"#092b33",activeBg:"#0e3e4a",inputBg:"#092b33",inputBorder:"#092b33",inputText:"cyan",inputPlaceholder:"#2d6d7a",inputPrompt:"cyan",codeBg:"#020d10",codeBorder:"#1a5966",userMsgBg:"#092b33",userMsgBorder:"#092b33",userMsgText:"cyan",diffRemovalBg:"#3a0c1a",diffAdditionBg:"#0c3a32",diffRemovalText:"#ff4d88",diffAdditionText:"#00ffaa",diffRemovalHighlightColor:"#ff1a66",diffRemovalHighlightBg:"#590022",diffAdditionHighlightColor:"#00ffcc",diffAdditionHighlightBg:"#00593b",diffRemovalNum:"#ff4d88",diffAdditionNum:"#00ffaa",diffRemovalPrefix:"#ff1a66",diffAdditionPrefix:"#00ffcc",primary:"cyan",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"cyan",statusOff:"#2d6d7a",logoTextAnsi:"\x1B[1;36m",logoBodyAnsi:"\x1B[36m",logoMutedAnsi:"\x1B[90m",logoGradient:["#00ffff","#0088ff"]},{name:"Magenta Vaporwave",text:"magenta",textMuted:"#c451d6",textDim:"#7d2b8a",textInverted:"black",border:"magenta",borderMuted:"#5e1b69",borderDim:"#3b0f42",bg:void 0,cardBg:"#240729",highlightBg:"#310938",activeBg:"#470e52",inputBg:"#310938",inputBorder:"#310938",inputText:"magenta",inputPlaceholder:"#7d2b8a",inputPrompt:"magenta",codeBg:"#100312",codeBorder:"#5e1b69",userMsgBg:"#310938",userMsgBorder:"#310938",userMsgText:"magenta",diffRemovalBg:"#3a0c20",diffAdditionBg:"#200c3a",diffRemovalText:"#ff4d94",diffAdditionText:"#aa4dff",diffRemovalHighlightColor:"#ff1a75",diffRemovalHighlightBg:"#59002b",diffAdditionHighlightColor:"#bb66ff",diffAdditionHighlightBg:"#3b0059",diffRemovalNum:"#ff4d94",diffAdditionNum:"#aa4dff",diffRemovalPrefix:"#ff1a75",diffAdditionPrefix:"#bb66ff",primary:"magenta",secondary:"cyan",accent:"purple",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"magenta",statusOff:"#7d2b8a",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ff00ff","#8800ff"]},{name:"Glitch Matrix",text:"#00ff41",textMuted:"#00b32d",textDim:"#00661a",textInverted:"black",border:"#00ff41",borderMuted:"#008020",borderDim:"#004d13",bg:void 0,cardBg:"#0d1f0d",highlightBg:"#122912",activeBg:"#1c3e1c",inputBg:"#122912",inputBorder:"#122912",inputText:"#00ff41",inputPlaceholder:"#00b32d",inputPrompt:"#ffff00",codeBg:"#040a04",codeBorder:"#008020",userMsgBg:"#122912",userMsgBorder:"#122912",userMsgText:"#00ff41",diffRemovalBg:"#3a001a",diffAdditionBg:"#003a10",diffRemovalText:"#ff0055",diffAdditionText:"#00ff66",diffRemovalHighlightColor:"#ff0033",diffRemovalHighlightBg:"#59001b",diffAdditionHighlightColor:"#33ff88",diffAdditionHighlightBg:"#005918",diffRemovalNum:"#ff0055",diffAdditionNum:"#00ff66",diffRemovalPrefix:"#ff0033",diffAdditionPrefix:"#33ff88",primary:"#00ff41",secondary:"yellow",accent:"cyan",success:"#00ff41",warning:"yellow",danger:"red",info:"cyan",statusOn:"#00ff41",statusOff:"#00661a",logoTextAnsi:"\x1B[1;32m",logoBodyAnsi:"\x1B[32m",logoMutedAnsi:"\x1B[90m",logoGradient:["#00ff41","#ffff00"]},{name:"Warm Sunset",text:"#ffaa55",textMuted:"#cc8844",textDim:"#885522",textInverted:"black",border:"#ff9933",borderMuted:"#aa6622",borderDim:"#663311",bg:void 0,cardBg:"#24180f",highlightBg:"#2e1e12",activeBg:"#422c1b",inputBg:"#2e1e12",inputBorder:"#2e1e12",inputText:"#ffaa55",inputPlaceholder:"#885522",inputPrompt:"#ff7733",codeBg:"#120c08",codeBorder:"#aa6622",userMsgBg:"#2e1e12",userMsgBorder:"#2e1e12",userMsgText:"#ffaa55",diffRemovalBg:"#3d120c",diffAdditionBg:"#3a2e0c",diffRemovalText:"#ff5544",diffAdditionText:"#ffcc33",diffRemovalHighlightColor:"#ff3322",diffRemovalHighlightBg:"#591108",diffAdditionHighlightColor:"#ffee44",diffAdditionHighlightBg:"#594400",diffRemovalNum:"#ff5544",diffAdditionNum:"#ffcc33",diffRemovalPrefix:"#ff3322",diffAdditionPrefix:"#ffee44",primary:"#ffaa55",secondary:"#ff7733",accent:"magenta",success:"#ffcc33",warning:"#ff7733",danger:"#ff3322",info:"#ffaa55",statusOn:"#ffaa55",statusOff:"#885522",logoTextAnsi:"\x1B[1;33m",logoBodyAnsi:"\x1B[33m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ff9933","#ff0055"]},{name:"Sakura Blossom",text:"#ffc0e0",textMuted:"#d98cb3",textDim:"#804d66",textInverted:"black",border:"#ff99cc",borderMuted:"#aa4d7a",borderDim:"#662647",bg:void 0,cardBg:"#291320",highlightBg:"#331826",activeBg:"#472235",inputBg:"#331826",inputBorder:"#331826",inputText:"#ffc0e0",inputPlaceholder:"#804d66",inputPrompt:"#ff99cc",codeBg:"#140a10",codeBorder:"#aa4d7a",userMsgBg:"#331826",userMsgBorder:"#331826",userMsgText:"#ffc0e0",diffRemovalBg:"#3e0c1b",diffAdditionBg:"#1b3e2b",diffRemovalText:"#ff6699",diffAdditionText:"#66ffb3",diffRemovalHighlightColor:"#ff3377",diffRemovalHighlightBg:"#590022",diffAdditionHighlightColor:"#33ff99",diffAdditionHighlightBg:"#00592e",diffRemovalNum:"#ff6699",diffAdditionNum:"#66ffb3",diffRemovalPrefix:"#ff3377",diffAdditionPrefix:"#33ff99",primary:"#ffc0e0",secondary:"#ff99cc",accent:"magenta",success:"#66ffb3",warning:"yellow",danger:"#ff3377",info:"#ff99cc",statusOn:"#ffc0e0",statusOff:"#804d66",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ffb3d9","#ff3399"]},{name:"Radioactive Slime",text:"#ccff00",textMuted:"#99cc00",textDim:"#669900",textInverted:"#0a0f00",border:"#ccff00",borderMuted:"#99cc00",borderDim:"#669900",bg:void 0,cardBg:"#0f1400",highlightBg:"#1a2400",activeBg:"#2a3b00",inputBg:"#1a2400",inputBorder:"#1a2400",inputText:"#ccff00",inputPlaceholder:"#669900",inputPrompt:"#cc00ff",codeBg:"#050a00",codeBorder:"#99cc00",userMsgBg:"#1a2400",userMsgBorder:"#1a2400",userMsgText:"#ccff00",diffRemovalBg:"#2a0033",diffAdditionBg:"#0f3300",diffRemovalText:"#ff00cc",diffAdditionText:"#00ff33",diffRemovalHighlightColor:"#ff33cc",diffRemovalHighlightBg:"#4d0066",diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:"#1a6600",diffRemovalNum:"#ff00cc",diffAdditionNum:"#00ff33",diffRemovalPrefix:"#ff33cc",diffAdditionPrefix:"#33ff66",primary:"#ccff00",secondary:"#cc00ff",accent:"#ff00cc",success:"#00ff33",warning:"#ffcc00",danger:"#ff0033",info:"#00ccff",statusOn:"#ccff00",statusOff:"#669900",logoTextAnsi:"\x1B[1;38;5;190m",logoBodyAnsi:"\x1B[38;5;190m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ccff00","#cc00ff"]},{name:"Cosmic Void",text:"#f0f8ff",textMuted:"#a6aeb5",textDim:"#5e656e",textInverted:"#010103",border:"#f0f8ff",borderMuted:"#a6aeb5",borderDim:"#5e656e",bg:void 0,cardBg:"#05030d",highlightBg:"#0b081a",activeBg:"#171133",inputBg:"#0b081a",inputBorder:"#0b081a",inputText:"#f0f8ff",inputPlaceholder:"#5e656e",inputPrompt:"#ff007f",codeBg:"#020108",codeBorder:"#a6aeb5",userMsgBg:"#0b081a",userMsgBorder:"#0b081a",userMsgText:"#f0f8ff",diffRemovalBg:"#2e0a29",diffAdditionBg:"#091c33",diffRemovalText:"#ff33a6",diffAdditionText:"#33d6ff",diffRemovalHighlightColor:"#ff66c2",diffRemovalHighlightBg:"#5c1452",diffAdditionHighlightColor:"#66e0ff",diffAdditionHighlightBg:"#123866",diffRemovalNum:"#ff33a6",diffAdditionNum:"#33d6ff",diffRemovalPrefix:"#ff66c2",diffAdditionPrefix:"#66e0ff",primary:"#f0f8ff",secondary:"#ff007f",accent:"#9d00ff",success:"#33d6ff",warning:"#ffcc00",danger:"#ff0040",info:"#9d00ff",statusOn:"#f0f8ff",statusOff:"#5e656e",logoTextAnsi:"\x1B[1;38;5;231m",logoBodyAnsi:"\x1B[38;5;231m",logoMutedAnsi:"\x1B[38;5;240m",logoGradient:["#ffffff","#9d00ff"]},{name:"Magma Eruption",text:"#ff4d00",textMuted:"#cc3d00",textDim:"#802600",textInverted:"#0d0300",border:"#ff4d00",borderMuted:"#cc3d00",borderDim:"#802600",bg:void 0,cardBg:"#1a0600",highlightBg:"#260a00",activeBg:"#401100",inputBg:"#260a00",inputBorder:"#260a00",inputText:"#ff4d00",inputPlaceholder:"#802600",inputPrompt:"#ffcc00",codeBg:"#080200",codeBorder:"#cc3d00",userMsgBg:"#260a00",userMsgBorder:"#260a00",userMsgText:"#ff4d00",diffRemovalBg:"#2e0a0a",diffAdditionBg:"#1f1400",diffRemovalText:"#ff3333",diffAdditionText:"#ffaa00",diffRemovalHighlightColor:"#ff6666",diffRemovalHighlightBg:"#5c1414",diffAdditionHighlightColor:"#ffcc33",diffAdditionHighlightBg:"#3d2900",diffRemovalNum:"#ff3333",diffAdditionNum:"#ffaa00",diffRemovalPrefix:"#ff6666",diffAdditionPrefix:"#ffcc33",primary:"#ff4d00",secondary:"#ffcc00",accent:"#ff0040",success:"#ffaa00",warning:"#ffff00",danger:"#ff0000",info:"#ff8800",statusOn:"#ff4d00",statusOff:"#802600",logoTextAnsi:"\x1B[1;38;5;202m",logoBodyAnsi:"\x1B[38;5;202m",logoMutedAnsi:"\x1B[38;5;236m",logoGradient:["#ff4d00","#ff0000"]}],uo={Dark:{id:"Dark",name:"Dark (Default)",text:"white",textMuted:"gray",textDim:"grey",textInverted:"black",textExclusive:"#B5B8D9",textMutedExclusive:"#D4DEE7",border:"white",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:"#1e1e1e",highlightBg:"#2a2a2a",activeBg:"#3a3a3a",inputBg:"#555555",inputBorder:"#555555",inputText:"white",inputPlaceholder:"#cccccc",inputPrompt:"white",codeBg:"#1a1a1a",codeBorder:"#444444",userMsgBg:"#444444",userMsgBorder:"#444444",userMsgText:"white",diffRemovalBg:"#250808",diffAdditionBg:"#072410",diffRemovalText:"#885555",diffAdditionText:"#558866",diffRemovalHighlightColor:"#ff3333",diffRemovalHighlightBg:"#5a1818",diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:"#185a25",diffRemovalNum:"#d96868",diffAdditionNum:"#68d98c",diffRemovalPrefix:"#ff4d4d",diffAdditionPrefix:"#4dff88",primary:"white",secondary:"cyan",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"white",statusOff:"gray",logoTextAnsi:"\x1B[1;37m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#0077ff","#ff00ff"]},Light:{id:"Light",name:"Light",text:"black",textMuted:"gray",textDim:"grey",textInverted:"white",border:"black",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:"#e5e5e5",highlightBg:"#d4d4d4",activeBg:"#c0c0c0",inputBg:"#d0d0d0",inputBorder:"#d0d0d0",inputText:"black",inputPlaceholder:"#555555",inputPrompt:"black",codeBg:"#e8e8e8",codeBorder:"#b0b0b0",userMsgBg:"#d0d0d0",userMsgBorder:"#d0d0d0",userMsgText:"black",diffRemovalBg:"#fce8e8",diffAdditionBg:"#e6f9e6",diffRemovalText:"#661111",diffAdditionText:"#115511",diffRemovalHighlightColor:"#440000",diffRemovalHighlightBg:"#f8b4b4",diffAdditionHighlightColor:"#003300",diffAdditionHighlightBg:"#a6ebad",diffRemovalNum:"#c02020",diffAdditionNum:"#188028",diffRemovalPrefix:"#d01010",diffAdditionPrefix:"#109020",primary:"black",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"black",statusOff:"gray",logoTextAnsi:"\x1B[1;30m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#0077ff","#ff00ff"]},"GitHub Dark":{id:"GitHub Dark",name:"GitHub Dark",text:"#c9d1d9",textMuted:"#8b949e",textDim:"#6e7681",textInverted:"#0d1117",border:"#30363d",borderMuted:"#30363d",borderDim:"#21262d",bg:void 0,cardBg:"#161b22",highlightBg:"#21262d",activeBg:"#30363d",inputBg:"#21262d",inputBorder:"#21262d",inputText:"#c9d1d9",inputPlaceholder:"#8b949e",inputPrompt:"#58a6ff",codeBg:"#0d1117",codeBorder:"#30363d",userMsgBg:"#21262d",userMsgBorder:"#21262d",userMsgText:"#c9d1d9",diffRemovalBg:"#3c1e1e",diffAdditionBg:"#11381e",diffRemovalText:"#f85149",diffAdditionText:"#3fb950",diffRemovalHighlightColor:"#ff7b72",diffRemovalHighlightBg:"#701c1c",diffAdditionHighlightColor:"#56d364",diffAdditionHighlightBg:"#116329",diffRemovalNum:"#f85149",diffAdditionNum:"#3fb950",diffRemovalPrefix:"#f85149",diffAdditionPrefix:"#3fb950",primary:"#c9d1d9",secondary:"#58a6ff",accent:"#bc8cff",success:"#3fb950",warning:"#d29922",danger:"#f85149",info:"#58a6ff",statusOn:"#58a6ff",statusOff:"#8b949e",logoTextAnsi:"\x1B[1;36m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#2ea043","#56d364"]},"GitHub Light":{id:"GitHub Light",name:"GitHub Light",text:"#24292f",textMuted:"#57606a",textDim:"#6e7781",textInverted:"#ffffff",border:"#d0d7de",borderMuted:"#d0d7de",borderDim:"#e1e4e8",bg:void 0,cardBg:"#f6f8fa",highlightBg:"#eaeef2",activeBg:"#d0d7de",inputBg:"#eaeef2",inputBorder:"#eaeef2",inputText:"#24292f",inputPlaceholder:"#57606a",inputPrompt:"#0969da",codeBg:"#ffffff",codeBorder:"#d0d7de",userMsgBg:"#eaeef2",userMsgBorder:"#eaeef2",userMsgText:"#24292f",diffRemovalBg:"#ffebe9",diffAdditionBg:"#e6ffec",diffRemovalText:"#cf222e",diffAdditionText:"#1a7f37",diffRemovalHighlightColor:"#82071e",diffRemovalHighlightBg:"#ffc1c0",diffAdditionHighlightColor:"#116329",diffAdditionHighlightBg:"#acf2bd",diffRemovalNum:"#cf222e",diffAdditionNum:"#1a7f37",diffRemovalPrefix:"#cf222e",diffAdditionPrefix:"#1a7f37",primary:"#24292f",secondary:"#0969da",accent:"#8250df",success:"#1a7f37",warning:"#9a6700",danger:"#cf222e",info:"#0969da",statusOn:"#0969da",statusOff:"#57606a",logoTextAnsi:"\x1B[1;34m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#1a7f37","#2da44e"]},"Transparent Dark":{id:"Transparent Dark",name:"Transparent Dark",text:"white",textMuted:"gray",textDim:"grey",textInverted:"black",border:"gray",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:void 0,highlightBg:"#2a2a2a",activeBg:"#3a3a3a",inputBg:"#555555",inputBorder:"#555555",inputText:"white",inputPlaceholder:"#cccccc",inputPrompt:"white",codeBg:void 0,codeBorder:"gray",userMsgBg:"#555555",userMsgBorder:"#555555",userMsgText:"white",diffRemovalBg:void 0,diffAdditionBg:void 0,diffRemovalText:"#ff6666",diffAdditionText:"#66ff66",diffRemovalHighlightColor:"#ff3333",diffRemovalHighlightBg:void 0,diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:void 0,diffRemovalNum:"#ff6666",diffAdditionNum:"#66ff66",diffRemovalPrefix:"#ff4d4d",diffAdditionPrefix:"#4dff88",primary:"white",secondary:"cyan",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"white",statusOff:"gray",logoTextAnsi:"\x1B[1;37m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#0077ff","#ff00ff"]},"Transparent Light":{id:"Transparent Light",name:"Transparent Light",text:"black",textMuted:"gray",textDim:"grey",textInverted:"white",border:"gray",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:void 0,highlightBg:"#d4d4d4",activeBg:"#c0c0c0",inputBg:"#d0d0d0",inputBorder:"#d0d0d0",inputText:"black",inputPlaceholder:"#555555",inputPrompt:"black",codeBg:void 0,codeBorder:"gray",userMsgBg:"#d0d0d0",userMsgBorder:"#d0d0d0",userMsgText:"black",diffRemovalBg:void 0,diffAdditionBg:void 0,diffRemovalText:"#c02020",diffAdditionText:"#188028",diffRemovalHighlightColor:"#800000",diffRemovalHighlightBg:void 0,diffAdditionHighlightColor:"#004000",diffAdditionHighlightBg:void 0,diffRemovalNum:"#c02020",diffAdditionNum:"#188028",diffRemovalPrefix:"#d01010",diffAdditionPrefix:"#109020",primary:"black",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"black",statusOff:"gray",logoTextAnsi:"\x1B[1;30m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#0077ff","#ff00ff"]},"Synthwave 84":{id:"Synthwave 84",name:"Synthwave 84",text:"#fdfdfd",textMuted:"#a08eb7",textDim:"#705c8a",textInverted:"#1a1025",textExclusive:"#e3dcf0",textMutedExclusive:"#b9abc9",border:"#fc28a8",borderMuted:"#a21568",borderDim:"#5c0a3a",bg:void 0,cardBg:"#261b38",highlightBg:"#35254d",activeBg:"#4c3570",inputBg:"#35254d",inputBorder:"#35254d",inputText:"#fdfdfd",inputPlaceholder:"#a08eb7",inputPrompt:"#03e8fc",codeBg:"#1e142b",codeBorder:"#a21568",userMsgBg:"#35254d",userMsgBorder:"#35254d",userMsgText:"#fdfdfd",diffRemovalBg:"#471434",diffAdditionBg:"#144743",diffRemovalText:"#ff4081",diffAdditionText:"#00e5ff",diffRemovalHighlightColor:"#ff79a1",diffRemovalHighlightBg:"#6b1e4e",diffAdditionHighlightColor:"#66f5ff",diffAdditionHighlightBg:"#1e6b65",diffRemovalNum:"#ff4081",diffAdditionNum:"#00e5ff",diffRemovalPrefix:"#ff79a1",diffAdditionPrefix:"#66f5ff",primary:"#fdfdfd",secondary:"#03e8fc",accent:"#fc28a8",success:"#00e5ff",warning:"#ffc107",danger:"#ff4081",info:"#b388ff",statusOn:"#03e8fc",statusOff:"#a08eb7",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#fc28a8","#03e8fc"]},"Forest Sprite":{id:"Forest Sprite",name:"Forest Sprite",text:"#d6e6d1",textMuted:"#95b38d",textDim:"#628059",textInverted:"#161c14",textExclusive:"#eaf2e8",textMutedExclusive:"#a9c7a2",border:"#74a862",borderMuted:"#477038",borderDim:"#2b4720",bg:void 0,cardBg:"#1f291c",highlightBg:"#2a3826",activeBg:"#3a4d35",inputBg:"#2a3826",inputBorder:"#2a3826",inputText:"#d6e6d1",inputPlaceholder:"#95b38d",inputPrompt:"#8feb73",codeBg:"#161e14",codeBorder:"#477038",userMsgBg:"#2a3826",userMsgBorder:"#2a3826",userMsgText:"#d6e6d1",diffRemovalBg:"#3b231c",diffAdditionBg:"#203b1c",diffRemovalText:"#db6242",diffAdditionText:"#59cc3f",diffRemovalHighlightColor:"#f0896c",diffRemovalHighlightBg:"#5c362a",diffAdditionHighlightColor:"#80e368",diffAdditionHighlightBg:"#305929",diffRemovalNum:"#db6242",diffAdditionNum:"#59cc3f",diffRemovalPrefix:"#f0896c",diffAdditionPrefix:"#80e368",primary:"#d6e6d1",secondary:"#8feb73",accent:"#e69835",success:"#59cc3f",warning:"#e69835",danger:"#db6242",info:"#73b4eb",statusOn:"#8feb73",statusOff:"#95b38d",logoTextAnsi:"\x1B[1;32m",logoBodyAnsi:"\x1B[32m",logoMutedAnsi:"\x1B[90m",logoGradient:["#8feb73","#e69835"]}};var No=null;var ga=(e="Dark")=>{let n;e==="Mystery"||e==="Chaos"?(No||(No=ma[Math.floor(Math.random()*ma.length)]),n={...No,id:"Mystery"}):(No=null,uo[e]?n=uo[e]:e==="GitHub"?n=uo["GitHub Dark"]:e==="Transparent"?n=uo["Transparent Dark"]:n=uo.Dark);let t=n.codeText||n.secondary||n.info||n.logoGradient&&n.logoGradient[0]||"cyan";return{...n,codeText:t}};var ec=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",Ap=(e=2)=>{let n=ec();return n==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)},vp=(e="...",n="Loading...",t="Dark")=>{let o=qi[Math.floor(Math.random()*qi.length)],s=ga(t),i=s.logoTextAnsi,a=s.logoBodyAnsi,r=s.logoMutedAnsi,p="\x1B[0m",d=[" \u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2588\u2588\u2588\u2591 "," \u2588\u2588\u2588\u2591 "," \u2588\u2588\u2588\u2591 "," \u2591\u2591\u2591 "],c=s.logoGradient||["#0077ff","#ff00ff"],l=Zl(c).multiline(d.join(`
486
- `)).split(`
487
- `),u=f=>`${r}${f}${p}`;return`${l[0]}
488
- ${l[1]} ${i}Selected Provider: ${n}${p}
489
- ${l[2]}
490
- ${l[3]} ${i}FluxFlow ${u("v"+e)}${p}
491
- ${l[4]}
492
- ${l[5]} ${a}See /help for additional commands.${p}
493
- ${l[6]} ${u(o)}
494
- ${l[7]}`};import{WebSocket as Bo}from"ws";var zt=null,Fs=!1,tc="ws://localhost:56832",zi=[],Ns=null,Ki=null,ya="2.0.0",Lp=e=>{ya=e,wa()},Yi=e=>{Ki=e},wa=()=>{if(zt||Fs)return;Fs=!0;let e=new Bo(tc);e.on("open",()=>{for(zt=e,Fs=!1,zt.send(JSON.stringify({command:"version",version:ya,pid:process.pid,ppid:process.ppid}));zi.length>0;)zt.send(JSON.stringify(zi.shift()))}),e.on("message",n=>{try{let t=JSON.parse(n.toString());t.command==="contextResponse"&&Ns?(Ns(t.data),Ns=null):t.command==="securityResponse"&&Ki&&Ki(t.result)}catch{}}),e.on("error",()=>{Fs=!1,zt=null}),e.on("close",()=>{Fs=!1,zt=null})},Uo=e=>{zt&&zt.readyState===Bo.OPEN?zt.send(JSON.stringify(e)):(zi.push(e),Fs||wa())},Wo=()=>zt!==null&&zt.readyState===Bo.OPEN,Pp=e=>{Uo({command:"status",status:e})},gs=()=>new Promise(e=>{if(!zt||zt.readyState!==Bo.OPEN){e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]});return}Ns=e,zt.send(JSON.stringify({command:"requestContext"})),setTimeout(()=>{Ns===e&&(e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]}),Ns=null)},1e3)}),xa=e=>{Uo({command:"open",filePath:e})},Vi=(e,n,t)=>{Uo({command:"showDiff",filePath:e,originalContent:n,modifiedContent:t})},ba=(e,n)=>{Uo({command:"closeDiff",filePath:e,result:n})};import ka from"path";import nc from"fs";var sc=e=>{try{return nc.readdirSync(e,{withFileTypes:!0})}catch{return[]}},Ji=(e,n,t=1,o=sc,s=[],i=null)=>{let a=i||o(e),r=" ".repeat(t-1);if(a.length>100)return`${r}${ka.basename(e)}/ (>100 files)
495
- `;let p="",d=s,c=a.filter(h=>!d.includes(h.name)&&!h.name.startsWith(".")),l=a.filter(h=>d.includes(h.name)||h.name.startsWith(".")).map(h=>h.name).sort();l.length>0&&(p+=`${r}[ignored: ${l.map(h=>h+"/").join(", ")}]
496
- `);let u=c.filter(h=>h.isDirectory()).sort((h,g)=>h.name.localeCompare(g.name)),f=c.filter(h=>!h.isDirectory()).map(h=>h.name).sort();for(let h of u){let g=ka.join(e,h.name);if(t>n)p+=`${r}${h.name}/ (max depth)
497
- `;else{let y=o(g);y.length>80?p+=`${r}${h.name}/ (>80 files)
498
- `:(p+=`${r}${h.name}/
499
- `,p+=Ji(g,n,t+1,o,s,y))}}return f.length>0&&(p+=`${r}${f.join("; ")}
500
- `),p};import Xi from"path";import oc from"fs";var ic=e=>{try{return oc.readdirSync(e,{withFileTypes:!0})}catch{return[]}},Qi=(e,n,t="",o=1,s=ic,i=[])=>{let a=s(e),r=Xi.sep;if(a.length>100)return`${t}\u2514\u2500\u2500 ${Xi.basename(e)}${r} ...100+ files...
501
- `;let p="",d=i,c=a.filter(f=>!d.includes(f.name)&&!f.name.startsWith(".")),l=a.filter(f=>d.includes(f.name)||f.name.startsWith(".")).map(f=>f.name).sort();c.sort((f,h)=>f.isDirectory()&&!h.isDirectory()?-1:!f.isDirectory()&&h.isDirectory()?1:f.name.localeCompare(h.name));let u=[...c.map(f=>({name:f.name,isDir:f.isDirectory()})),...l.map(f=>({name:f,isDir:!0,isCollapsed:!0}))];return u.forEach((f,h)=>{let g=h===u.length-1,y=Xi.join(e,f.name),m=g?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",w=t+(g?" ":"\u2502 ");if(f.isCollapsed){p+=`${t}${m}${f.name}${r}...
502
- `;return}f.isDir?o>n?p+=`${t}${m}${f.name}${r} ...depth exceeded...
503
- `:s(y).length>80?p+=`${t}${m}${f.name}${r} ...80+ files...
504
- `:(p+=`${t}${m}${f.name}${r}
505
- `,p+=Qi(y,n,w,o+1,s,i)):p+=`${t}${m}${f.name}
506
- `}),p};import"@google/genai";er.config({quiet:!0});er.config({path:"./fluxflow.env",override:!0,quiet:!0});er.config({path:"./.fluxflow.env",override:!0,quiet:!0});var ac=/```[\s\S]*?```/g,lc=/```[\s\S]*$/g,cc=/`[^`]+`/g,dc=/^\|.*\|$/gm,fc=/^[^\w]+|[^\w]+$/g,uc=/[^a-z0-9]/gi,ho=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,hc=/\[\s*(?:tool:functions\.|agent:generalist\.)([a-z0-9_]+)\s*\(/gi,pc=/(?:path|targetFile|TargetFile|directory|keyword|id|taskId|title|task)\s*=\s*\\?["']?([^\\"' \),]+)/,ys=/["']/g,Sa=/\\/g,mc=/<\|channel>thought/gi,gc=/<channel\|>/gi,Dn=e=>typeof e!="string"?e:e.replace(mc,"<think>").replace(gc,"</think>"),yc=/(?:<(think|thought|thoughts)>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\])/gi,wc=/(?:<(think|thought|thoughts)>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*$/gi,Ta=/(?:<think>|<\|channel>thought|\[think\])[\s\S]*?(?:<\/think>|<channel\|>|\[\/think\]|$)/gi,Ra=/(?:<(think|thought|thoughts)>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\]|$)/gi,Ia=/`[^`]*`/g,Oa=/`[^`]*$/,Ea=/<\|\s*tool_call_begin\s*\|>\s*(?:(?:tool|functions)\b[\s._]*)*([a-zA-Z0-9_]+)(?::\d+)?\s*<\|\s*tool_call_argument_begin\s*\|>([\s\S]*?)<\|\s*tool_call_end\s*\|>/gi,xc=/"([^"]+)"\s*:\s*(?:"([^"]*)"|(\d+)|true|false|null)/g,$a=/<\|\s*tool_calls_section_begin\s*\|>/gi,Ca=/<\|\s*tool_calls_section_end\s*\|>/gi,bc=/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi,_a=/<(\w+)(?:[^>]*)>\r?\n?/gi,Ma=/\r?\n?<\/\w+(?:[^>]*)>/gi,tr=null,jo={},ws={key:null,value:null},gn=e=>e&&e.replace(/(?:(\x1b\[\d+m))?([✔✘✖🔍📖→➕↻↷•🛇])(?:(\x1b\[\d+m))?\s*\b(Clicked|Dragged|Scrolled|Typed|Pressed Key|Recaptured Screen|Created|Read|Edited|Viewed|Processed|Auto-Read|Skipped|List|Generated|Written|Searched|AI Search|Get Map|Write Canceled|Resolved Sub-Agent Query|Edit Canceled|Write Cancelled|Edit Denied|Visited|Updated|Reviewed|Delegated|Background|Checked|Indexed|Analyzed|Browsed|Elevating SubAgent|Checking SubAgent Work|Started Generalist|Called Generalist|Steered|Unsupported Modality|Awaiting|Cancelled|Aligning Moon Phase|Contemplating Existence|Staring At Void|Rollback Point Checked|Emergency Rollback Failed|Emergency Rollback|Delaying Professionally|Negotiating With Electrons|Touching Grass (virtually)|Panicking Softly|Rethinking Career Choices|Loading Cat Videos|Giving Up Entirely|Summoning Braincell #2|Pretending To Be Busy|Waiting For Motivation DLC|Rotating Internal Screaming|Downloading More RAM|Feeding The Hamsters|Gaslighting Scheduler|Performing Dramatic Pause|Buffering Social Energy|Calculating Regret|Reading Terms And Conditions|Becoming Sentient Briefly|Contacting Ancestors)\b/ig,(n,t,o,s,i)=>`${t||""}${o}${s||""} \x1B[95m${i}\x1B[0m`),kc=async(e,n=8,t=1e3,o=8e3,s=null)=>{let i=0;for(;;){if(s?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{return await e()}catch(a){if(s?.aborted||a?.name==="AbortError"||a?.message==="Subagent task was cancelled."||(i++,i>=n))throw a;let r=Math.min(t*Math.pow(2,i-1),o);await new Promise((p,d)=>{let c=setTimeout(p,r);s&&s.addEventListener("abort",()=>{clearTimeout(c),d(new DOMException("The user aborted a request.","AbortError"))})})}}},Ot=!1;var Sc=e=>{let n=e.filter(s=>(s.role==="user"||s.role==="agent"||s.role==="system")&&s.role!=="think"&&!s.isVisualFeedback&&!s.isMeta&&!s.isTerminalRecord&&!(s.text&&s.text.includes("[TERMINAL_RECORD]"))&&!String(s.id).startsWith("welcome")).map((s,i,a)=>{let r=s.fullText||s.text||"";if(s.role==="user"&&i<a.length-1)if(r.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")){let p=r.indexOf("**CONTEXT SUMMARY OF PREVIOUS TURNS");if(p!==-1){let c=r.substring(0,p).lastIndexOf("[SYSTEM METADATA]");c!==-1?r=r.substring(c).trim():r=r.substring(p).trim()}}else{let p=r.lastIndexOf("[USER]"),d=r.lastIndexOf("[USER PROMPT]");p!==-1?r=r.substring(p+6).trim():d!==-1&&(r=r.substring(d).trim())}return{...s,text:r}}),t=[],o=0;for(;o<n.length;){let s=n[o];if(s.role==="user")t.push(s),o++;else{let i=[];for(;o<n.length&&n[o].role!=="user";)i.push(n[o]),o++;let a=[],r=[],p=!1,d=()=>{a.length>0&&(t.push({role:"agent",text:"combined"}),a=[]),r.length>0&&(t.push({role:"system",text:"combined"}),r=[]),p=!1};i.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||"",f=u.trim();if(!(!f&&!c.binaryPart)){if(l)r.push(f);else if(c.role==="agent"){!p&&r.length>0&&d();let h=u.endsWith(`
507
- `),g=f.toLowerCase().includes("tool:functions.")||f.toLowerCase().includes("agent:generalist.");a.push(f),g&&h?p=!0:p=!1}}}),d()}}return t.length},Tc=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),po=async(e,n,t=5,o=1e3)=>{let s=n?.signal;for(let a=0;a<t;a++){if(s?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{let r=await fetch(e,n);if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),r.ok||r.status!==429&&r.status<500)return r}catch(r){if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),r.name==="AbortError"||s?.aborted||a===t-1)throw r}s?await new Promise((r,p)=>{let d=setTimeout(()=>{s.removeEventListener("abort",c),r()},Math.min(24e3,o*Math.pow(2,a))),c=()=>{clearTimeout(d),p(new DOMException("The user aborted a request.","AbortError"))};s.addEventListener("abort",c)}):await new Promise(r=>setTimeout(r,Math.min(24e3,o*Math.pow(2,a))))}if(s?.aborted)throw new DOMException("The user aborted a request.","AbortError");let i=await fetch(e,n);return typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),i},nr=async function*(e,n,t,o,s,i,a,r,p=.99){let d=[];o&&d.push({role:"system",content:o});for(let x of t){let k=x.role==="user"?"user":"assistant",R=[];if(Array.isArray(x.parts)){for(let E of x.parts)if(E.text)R.push({type:"text",text:E.text});else if(E.inlineData&&a){let S=E.inlineData.mimeType,T=E.inlineData.data;S.startsWith("image/")&&R.push({type:"image_url",image_url:{url:`data:${S};base64,${T}`}})}}else{let E=x.text||"";E&&R.push({type:"text",text:E})}d.push({role:k,content:R.length===1&&R[0].type==="text"?R[0].text:R})}let c={model:n,messages:d,stream:!0,stream_options:{include_usage:!0},temperature:p};if(s!=="Fast"){let x={Low:"high",Medium:"high",Standard:"high",High:"max",xHigh:"max"};c.reasoning_effort=x[s]||"high",c.extra_body={thinking:{type:"enabled"}}}else c.extra_body={thinking:{type:"disabled"}};let l=await po("https://api.deepseek.com/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(c),signal:r});if(!l.ok){let x=await l.json().catch(()=>({}));throw new Error(`DeepSeek Error (${l.status}): ${x.error?.message||l.statusText}`)}let u=l.body.getReader(),f=new TextDecoder,h="",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}h+=f.decode(k,{stream:!0});let R=h.split(`
508
- `);h=R.pop();for(let E of R){let S=E.trim();if(!S||!S.startsWith("data: "))continue;let T=!1;if(S==="data: [DONE]")T=!0;else try{let $=JSON.parse(S.substring(6)),C=$.choices?.[0]?.delta,b=$.usage;if($.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),C){let v=C.reasoning_content||null;v&&(g.push({text:v,thought:!0}),w=!0),C.content&&(g.push({text:C.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)}},sr=async function*(e,n,t,o,s,i,a,r,p=.99){let d=[];o&&d.push({role:"system",content:o});for(let R of t){let E=R.role==="user"?"user":"assistant",S=[];if(Array.isArray(R.parts)){for(let T of R.parts)if(T.text)S.push({type:"text",text:T.text});else if(T.inlineData&&a){let $=T.inlineData.mimeType,C=T.inlineData.data;$.startsWith("image/")&&S.push({type:"image_url",image_url:`data:${$};base64,${C}`})}}else{let T=R.text||"";T&&S.push({type:"text",text:T})}S.length>0&&d.push({role:E,content:S.length===1&&S[0].type==="text"?S[0].text:S})}let c={Fast:"none",Low:"none",Medium:"high",Standard:"high",High:"high",xHigh:"high"},l={model:n,messages:d,stream:!0,temperature:p,prompt_cache_key:"flux-flow-session"};s&&s!=="Fast"&&qs(n)&&(l.reasoning_effort=c[s]||"high");let u=await po("https://api.mistral.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(l),signal:r});if(!u.ok){let R=await u.text().catch(()=>""),E=u.statusText;try{let S=JSON.parse(R);E=S.error?.message||S.message||JSON.stringify(S.detail||S)}catch{R&&(E=R)}throw new Error(`Mistral Error (${u.status}): ${JSON.stringify(E)}`)}let f=u.body.getReader(),h=new TextDecoder,g="",y=[],m=null,w=Date.now(),x=!1,k=R=>R?typeof R=="string"?Dn(R):Array.isArray(R)?R.map(k).filter(Boolean).join(""):typeof R=="object"&&R!==null?typeof R.text=="string"?Dn(R.text):typeof R.content=="string"?Dn(R.content):typeof R.thinking=="string"?Dn(R.thinking):typeof R.reasoning_content=="string"?Dn(R.reasoning_content):typeof R.reasoning=="string"?Dn(R.reasoning):typeof R.value=="string"?Dn(R.value):R.text?k(R.text):R.content?k(R.content):R.thinking?k(R.thinking):R.reasoning_content?k(R.reasoning_content):R.reasoning?k(R.reasoning):R.value?k(R.value):"":Dn(String(R)):"";for(;;){let{done:R,value:E}=await f.read();if(R){x&&(y.length>0||m)&&(yield{candidates:y.length>0?[{content:{parts:y}}]:[],usageMetadata:m});break}g+=h.decode(E,{stream:!0});let S=g.split(`
509
- `);g=S.pop();for(let T of S){let $=T.trim();if(!$||!$.startsWith("data: "))continue;let C=!1;if($==="data: [DONE]")C=!0;else try{let b=JSON.parse($.substring(6)),v=b.choices?.[0]?.delta,O=b.usage;if(b.choices?.[0]?.finish_reason&&(C=!0),O&&(m={totalTokenCount:O.total_tokens||(O.prompt_tokens||0)+(O.completion_tokens||0),promptTokenCount:O.prompt_tokens||0,candidatesTokenCount:O.completion_tokens||0,cachedContentTokenCount:O.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:O.completion_tokens_details?.reasoning_tokens||0},x=!0),v){let P=v.thinking||v.reasoning_content||v.reasoning,W=k(P);W&&(y.push({text:W,thought:!0}),x=!0);let N=v.content||(!v.thinking&&!v.reasoning_content&&!v.reasoning?v.text:null);if(N)if(Array.isArray(N))for(let Y of N)if(typeof Y=="object"&&Y!==null){let ie=Y.type==="thinking"||Y.type==="reasoning"||!!Y.thought,Me=k(Y);Me&&(y.push({text:Me,...ie?{thought:!0}:{}}),x=!0)}else{let ie=k(Y);ie&&(y.push({text:ie}),x=!0)}else if(typeof N=="object"&&N!==null){let Y=N.type==="thinking"||N.type==="reasoning"||!!N.thought,ie=k(N);ie&&(y.push({text:ie,...Y?{thought:!0}:{}}),x=!0)}else{let Y=k(N);Y&&(y.push({text:Y}),x=!0)}}}catch{}if((C||Date.now()-w>=150)&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),x=!1),C)break}Date.now()-w>=150&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),x=!1)}},or=async function*(e,n,t,o,s,i,a=!1,r,p=.99){let d=[];o&&d.push({role:"system",content:o}),t.forEach(re=>{let Re=re.role==="model"?"assistant":"user",M=[];Array.isArray(re.parts)&&re.parts.forEach(F=>{if(F.text)M.push({type:"text",text:F.text});else if(F.inlineData&&a){let V=F.inlineData.mimeType,J=F.inlineData.data;V.startsWith("image/")&&rn(n)&&M.push({type:"image_url",image_url:{url:`data:${V};base64,${J}`}})}}),d.push({role:Re,content:M.length===1&&M[0].type==="text"?M[0].text:M})});let l={Fast:"Fast",Low:"Fast",Medium:"Standard",Standard:"Standard",High:"High",xHigh:"High"}[s]||"High",u=l!=="Fast",f=n.includes("kimi"),h=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"),R=n.includes("nemotron"),E=n.includes("llama-3"),S=n.includes("seed"),T=n.includes("poolside"),$=n.includes("thinkingmachines")||n.includes("muse"),C=E,b=null,v={Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},O={Fast:"64",Low:"64",Medium:"4096",Standard:"4096",High:"16384",xHigh:"16384"},P={Fast:"none",Low:"minimal",Medium:"medium",Standard:"medium",High:"max",xHigh:"max"},W=w||g||T||$?16384:32768;W=process.env.NVIDIA_BASE_URL?1024:W,W=b?1024:W;let N={model:n,messages:d,max_tokens:W,stream:!0,stream_options:{include_usage:!0},temperature:p,...x&&{thinking:v[s]||"high"}};if(!(process.env.NVIDIA_BASE_URL||C||b))if(f)N.chat_template_kwargs={thinking:u};else if(h)N.chat_template_kwargs={enable_thinking:u};else if(g)if(u){let re=l==="High"?"max":"high";N.chat_template_kwargs={thinking:!0,reasoning_effort:re}}else N.chat_template_kwargs={thinking:!1};else y?N.chat_template_kwargs={enable_thinking:u,clear_thinking:!u}:m?N.reasoning_effort=u?"high":"none":w&&n.includes("minimax-m3")?N.chat_template_kwargs={thinking_mode:u?"enabled":"disabled"}:k?N.chat_template_kwargs={enable_thinking:u}:R?l==="High"?(N.reasoning_budget=12e3,N.chat_template_kwargs={enable_thinking:!0}):l==="Standard"?(N.reasoning_budget=12e3,N.chat_template_kwargs={enable_thinking:!0,medium_effort:!0}):N.chat_template_kwargs={enable_thinking:!1}:S?u&&(N.extra_body={thinking_budget:parseInt(O[l]??"4096")}):T?N.chat_template_kwargs={enable_thinking:u}:$&&(N.reasoning_effort=P[l]||"medium");let Y=0,ie=6,Me=!1,B=process.env.NVIDIA_BASE_URL||"https://integrate.api.nvidia.com/v1/chat/completions",j=process.env.NVIDIA_API_KEY&&process.env.NVIDIA_BASE_URL?process.env.NVIDIA_API_KEY:e;for(B.endsWith("/chat/completions")||(B=B.replace(/\/+$/,"")+"/chat/completions");Y<ie;){Y++;try{let re=await po(B,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${j}`},body:JSON.stringify(N),signal:r});if(!re.ok){let Ue=await re.text().catch(()=>""),st=re.statusText;try{let ht=JSON.parse(Ue);st=ht.error?.message||ht.message||JSON.stringify(ht.detail||ht)}catch{Ue&&(st=Ue)}let qe=new Error(`NVIDIA API Error (${re.status}): ${st}`);throw qe.status=re.status,qe}let Re=re.body.getReader(),M=new TextDecoder,F="",V=[],J=null,Ne=Date.now(),De=!1;for(;;){let{done:Ue,value:st}=await Re.read();if(Ue){De&&(V.length>0||J)&&(yield{candidates:V.length>0?[{content:{parts:V}}]:[],usageMetadata:J},Me=!0);break}F+=M.decode(st,{stream:!0});let qe=F.split(`
510
- `);F=qe.pop();let ht=!1;for(let Bt of qe){let pt=Bt.trim();if(pt){if(pt==="data: [DONE]"){ht=!0;break}if(pt.startsWith("data: ")){let mt;try{mt=JSON.parse(pt.substring(6))}catch{continue}if(mt.error)throw new Error(`NVIDIA Stream Error: ${mt.error.message||JSON.stringify(mt.error)}`);mt.choices?.[0]?.finish_reason&&(ht=!0);try{let Tt=mt.usage;Tt&&(J={totalTokenCount:Tt.total_tokens||Tt.prompt_tokens+Tt.completion_tokens,promptTokenCount:Tt.prompt_tokens||0,candidatesTokenCount:Tt.completion_tokens||0,cachedContentTokenCount:Tt.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:(Tt.completion_tokens_details?.reasoning_tokens||0)+(Tt.completion_tokens_details?.thoughts_tokens||0)},De=!0);let xt=mt.choices?.[0]?.delta?.reasoning||mt.choices?.[0]?.delta?.reasoning_content||"",We=mt.choices?.[0]?.delta?.content||"";xt&&(V.push({text:xt,thought:!0}),De=!0),We&&(V.push({text:We}),De=!0)}catch{}}}}if((ht||Date.now()-Ne>=350)&&De&&(yield{candidates:V.length>0?[{content:{parts:[...V]}}]:[],usageMetadata:J},Me=!0,V=[],Ne=Date.now(),De=!1),ht)break}break}catch(re){if(Me||Y>=ie)throw re;await new Promise(Re=>setTimeout(Re,3500))}}},Rc=async function*(e,n){let t=[],o=null,s=!1,i=null,a=u=>{if(t.push(u),o){let f=o;o=null,f()}},r=n.split("/").pop();r=r.replace("llama-3.3","llama-3_3");let p=`https://api.ngc.nvidia.com/v2/predict/queues/models/qc69jvmznzxy/${r}`,d=!1,c=null,l=async()=>{try{let u=await fetch(p);if(u.ok){let f=await u.json();if(f&&f.queues&&f.queues[0]&&typeof f.queues[0].queueDepth=="number"){let h=f.queues[0].queueDepth;d||a({value:{type:"status",content:`Queue ${h||1}`},done:!1})}}else d||a({value:{type:"status",content:`Queue ${u.status}`},done:!1})}catch{}};process.env.NVIDIA_BASE_URL||(l(),c=setInterval(l,5e3)),(async()=>{try{let u=e[Symbol.asyncIterator]();for(;;){let{value:f,done:h}=await u.next();if(h)break;d=!0,c&&(clearInterval(c),c=null),a({value:f,done:!1})}s=!0,a(null)}catch(u){if(i=u,c&&(clearInterval(c),c=null),o){let f=o;o=null,f()}}})();try{for(;;){if(i)throw i;if(t.length>0){let u=t.shift();if(u===null&&s)break;yield u.value}else{if(s)break;await new Promise(u=>{o=u})}}}finally{c&&(clearInterval(c),c=null)}},ir=async function*(e,n,t,o,s,i,a,r,p=.95){let d=[];o&&d.push({role:"system",content:[{type:"text",text:o,cache_control:{type:"ephemeral"}}]});for(let E of t){let S=E.role==="user"?"user":"assistant",T=[];if(Array.isArray(E.parts)){for(let $ of E.parts)if($.text)T.push({type:"text",text:$.text});else if($.inlineData&&a){let C=$.inlineData.mimeType,b=$.inlineData.data;C.startsWith("image/")?T.push({type:"image_url",image_url:{url:`data:${C};base64,${b}`}}):T.push({type:"file",file:{filename:$.filename||"file",file_data:`data:${C};base64,${b}`}})}}else{let $=E.text||"";$&&T.push({type:"text",text:$})}d.push({role:S,content:T.length===1&&T[0].type==="text"?T[0].text:T})}let c={Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},u={model:n.includes(":")?`${n.split(":")[0]}:${n.split(":").slice(1).join(":").toLowerCase()}`:n,messages:d,stream:!0,temperature:p,cache_control:{type:"ephemeral"},session_id:"flux-flow-session"},f=c[s];f&&s!=="Fast"&&(u.reasoning_effort=f);let h=await po("https://openrouter.ai/api/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json","X-Title":"FluxFlow CLI","X-Cache":"true","X-OpenRouter-Cache":"true"},body:JSON.stringify(u),signal:r});if(!h.ok){let E=await h.json().catch(()=>({}));throw new Error(`OpenRouter Error (${h.status}): ${E.error?.message||h.statusText}`)}let g=h.body.getReader(),y=new TextDecoder,m="",w=[],x=null,k=Date.now(),R=!1;for(;;){let{done:E,value:S}=await g.read();if(E){R&&(w.length>0||x)&&(yield{candidates:w.length>0?[{content:{parts:w}}]:[],usageMetadata:x});break}m+=y.decode(S,{stream:!0});let T=m.split(`
511
- `);m=T.pop();for(let $ of T){let C=$.trim();if(!C||!C.startsWith("data: "))continue;let b=!1;if(C==="data: [DONE]")b=!0;else try{let v=JSON.parse(C.substring(6)),O=v.choices?.[0]?.delta,P=v.usage;if(v.choices?.[0]?.finish_reason&&(b=!0),P&&(x={totalTokenCount:P.total_tokens||(P.prompt_tokens||0)+(P.completion_tokens||0),promptTokenCount:P.prompt_tokens||0,candidatesTokenCount:P.completion_tokens||0,cachedContentTokenCount:P.prompt_tokens_details?.cached_tokens||P.prompt_tokens_details?.cache_read_input_tokens||P.cache_read_input_tokens||0,thoughtsTokenCount:P.completion_tokens_details?.reasoning_tokens||0},R=!0),O){let W=O.reasoning||(O.reasoning_details?O.reasoning_details.map(N=>N.text).join(""):null);W&&(w.push({text:W,thought:!0}),R=!0),O.content&&(w.push({text:O.content}),R=!0)}}catch{}if((b||Date.now()-k>=150)&&R&&(yield{candidates:w.length>0?[{content:{parts:[...w]}}]:[],usageMetadata:x},w=[],k=Date.now(),R=!1),b)break}}},La=async function*(e,n,t,o,s,i,a,r,p=1.05,d="Cloud"){let c=[];o&&c.push({role:"system",content:o});for(let S of t){let T=S.role==="user"?"user":"assistant",$="",C=[];if(Array.isArray(S.parts)){$=S.parts.map(b=>b.text||"").filter(Boolean).join(`
512
- `);for(let b of S.parts){let v=b.inlineData||b.inline_data;v&&v.data&&C.push(v.data)}}else $=S.text||"";if($||C.length>0){let b={role:T,content:$};C.length>0&&(b.images=C),c.push(b)}}let l=d==="Local"||!e||e==="LOCAL",f={host:l?process.env.OLLAMA_HOST||"http://127.0.0.1:11434":process.env.OLLAMA_HOST||"https://ollama.com"};!l&&e&&(f.headers={Authorization:"Bearer "+e});let h=new rc(f),g=[],y=null,m=Date.now(),w=!1,x={Fast:!1,Low:"medium",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},k=x[s]!==void 0?x[s]:!0,R={model:n,messages:c,stream:!0,think:k,keep_alive:"10m",options:{temperature:p}},E=await h.chat(R);for await(let S of E){if(r?.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 $=S.prompt_eval_duration||0;$>0&&$<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})},rr=async function*(e,n,t,o,s,i,a,r,p=.95){let d=[];o&&d.push({role:"system",content:o});for(let k of t){let R=k.role==="user"?"user":"assistant",E=[];if(Array.isArray(k.parts)){for(let S of k.parts)if(S.text)E.push({type:"text",text:S.text});else if(S.inlineData&&a){let T=S.inlineData.mimeType,$=S.inlineData.data;T.startsWith("image/")&&E.push({type:"image_url",image_url:{url:`data:${T};base64,${$}`}})}}else{let S=k.text||"";S&&E.push({type:"text",text:S})}d.push({role:R,content:E.length===1&&E[0].type==="text"?E[0].text:E})}let c={Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},l={model:n,messages:d,stream:!0,stream_options:{include_usage:!0},temperature:p,max_completion_tokens:32768};c[s]&&(l.reasoning_effort=c[s]);let u=await po("https://crof.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(l),signal:r});if(!u.ok){let k=await u.json().catch(()=>({}));throw new Error(`CrofAI Error (${u.status}): ${k.error?.message||u.statusText}`)}let f=u.body.getReader(),h=new TextDecoder,g="",y=[],m=null,w=Date.now(),x=!1;for(;;){let{done:k,value:R}=await f.read();if(k){x&&(y.length>0||m)&&(yield{candidates:y.length>0?[{content:{parts:y}}]:[],usageMetadata:m});break}g+=h.decode(R,{stream:!0});let E=g.split(`
513
- `);g=E.pop();for(let S of E){let T=S.trim();if(!T||!T.startsWith("data: "))continue;let $=!1;if(T==="data: [DONE]")$=!0;else try{let C=JSON.parse(T.substring(6)),b=C.choices?.[0]?.delta,v=C.usage;if(C.choices?.[0]?.finish_reason&&($=!0),v&&(m={totalTokenCount:v.total_tokens||(v.prompt_tokens||0)+(v.completion_tokens||0),promptTokenCount:v.prompt_tokens||0,candidatesTokenCount:v.completion_tokens||0,cachedContentTokenCount:v.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:v.completion_tokens_details?.reasoning_tokens||v.reasoning_tokens||0},x=!0),b){let O=b.reasoning_content||null;O&&(y.push({text:O,thought:!0}),x=!0),b.content&&(y.push({text:b.content}),x=!0)}}catch{}if(($||Date.now()-w>=150)&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),x=!1),$)break}Date.now()-w>=150&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),x=!1)}},km=()=>{Ot=!0},Sm=()=>Ot,Zi={write_file:"Writing",update_file:"Editing",read_folder:"Reading",view_file:"Reading",exec_command:"Executing Command",web_search:"Searching",web_scrape:"Reading",memory:"Updating Memory",search_keyword:"Searching",file_map:"Generating Map",ask:"User Input",write_pdf:"Creating",write_docx:"Creating",generate_image:"Generating",todo:"Planning",Todo:"Planning",goal:"Planning",Goal:"Planning",invoke_sync:"Sub-Agent Working",invoke:"Starting Agent",get_progress:"Checking Progress",cancel:"Cancelling",await:"Waiting",EmergencyRollback:"Don't Panic. Lookin' into it",answer:"Answering Sub-Agent",Answer:"Answering Sub-Agent",steer:"Steering Sub-Agent",Steer:"Steering Sub-Agent",Click:"Clicking",click:"Clicking",Drag:"Dragging",drag:"Dragging",Scroll:"Scrolling",scroll:"Scrolling",KeyboardTyping:"Typing",keyboard_typing:"Typing",KeyPress:"Pressing Key",key_press:"Pressing Key",RecaptureScreen:"Recapturing Screen",recapture_screen:"Recapturing Screen"},xs=(e,n)=>{try{let t=I(n),o=e.toLowerCase().replace(/_/g,"");if(o==="invokesync"||o==="invoke")return t.title||(t.task?t.task.substring(0,30):null);if(o==="getprogress"||o==="cancel"||o==="steer"||o==="steersubagent")return t.id||t.taskId;let s=t.path||t.targetFile||t.TargetFile||t.directory;return s?Q.basename(s.replace(/["']/g,"").replace(/\\/g,"/")):null}catch{return null}},ar=e=>e?new va({apiKey:e}):tr,Tm=async(e,n,t,o,s={})=>{let{onStatus:r,onMemoryUpdated:p,onBackgroundIncrement:d}=s,{profile:c,thinkingLevel:l,mode:u,janitorModel:f,chatId:h,systemSettings:g,sessionStats:y,aiProvider:m="Google",apiKey:w}=e,x=process.env.NVIDIA_BASE_URL||m==="Ollama"||m==="CrofAI"?!1:g?.memory!==!1,R=X(Dt,[]).map(M=>`- [${M.id}]: ${M.memory}`).join(`
514
- `),E=o.slice(0,-1).filter(M=>M.text&&!M.text.includes("[TOOL RESULT]")&&!M.text.includes("OBSERVATION:")&&!M.text.startsWith("[TERMINAL_RECORD]")&&!M.isTerminalRecord&&!M.isMeta&&!M.isLogo&&!String(M.id).startsWith("welcome")&&!String(M.id).startsWith("logo")).slice(-14).map(M=>{let F=Tc(M.text).replace(/\[tool:functions\..*?\]/g,"").replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[METADATA \(PRIORITY: DYNAMIC\)\] Time: ([^|\n]+)/g,(De,Ue)=>`[METADATA (PRIORITY: DYNAMIC)] Time: ${Ue.replace(/:\d{2}/g,"")}`).replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[TOOL RESULTS\]/g,"").replace(/\[tool results\]/g,"").replace(/\r?\n\r?\n/g,`
515
- `).replace(/\n\n/g,`
516
- `).replace(/\\n\\n/g,"").trim(),V=M.role==="user"?8192:32768,J=F.substring(0,V);F.length>V&&(J+=`
517
- ... (truncated) ...`);let Ne=M.role==="user"?J.startsWith("[USER]")?"":"[USER]: ":J.startsWith("[AGENT]")?"":"[AGENT]: ";return{role:M.role==="user"?"user":"model",parts:[{text:`${Ne}${J}`}]}}),S=o.filter(M=>M.role==="user").length===1,T=n.includes("[TITLE-UPDATE]"),$=Math.random()<.8,C=S||T||$,b=t.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").trim(),v=Cr(R,x,C),O=`${b.replace(/\[tool:functions\..*?\]/g,"").replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[\[TOOL RESULTS\]\]/g,"").replace(/\[tool results\]/g,"").substring(0,32768)}`;O.length>32768&&(O+=`
518
- ... (truncated) ...`);let P=n.replace(/\[Prompted on:.*?\]/g,"").trim();O=O.replace(/\r?\n\r?\n/g,`
519
- `).replace(/\n\n/g,`
520
- `).replace(/\\n\\n/g,"").trim();let W=new Date,Y=`[METADATA] Current date and Time: ${`${W.getFullYear()}-${W.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(W.getDate()).padStart(2,"0")}, ${W.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0})}`}
521
-
522
- [USER]: ${P.substring(0,8192)}
523
- ${P.length>8192?`... (truncated) ...
524
-
525
- `:""}
526
- [AGENT (current turn)]: ${O}`;E.push({role:"user",parts:[{text:Y}]});let ie=await Zo("NVIDIA"),B=(await Ft()).quotas?.providerTiers?.NVIDIA==="Free",j="",re=0,Re=x?12:-1;for(;re<=Re;)try{if(!await Or("background",e))return;let M="",F=null,V=!1,J=m;try{let Ue=new Promise((xt,We)=>setTimeout(()=>We(new Error("JANITOR_TIMEOUT")),1e4)),st=m==="Google"&&re>=0&&re<6&&ie&&B,qe=m==="DeepSeek"&&re<4&&ie&&B;V=st||qe,J=V?"NVIDIA":m;let ht=(async()=>{if(m==="OpenRouter"){let xt=et("janitor_open_router"),pe=ir(w,xt,E,v,"Fast",u,!1,null,.6)[Symbol.asyncIterator](),Kt=await pe.next();return{iterator:pe,firstResult:Kt}}else if(m==="DeepSeek"&&!V){let We=nr(w,et("deepseek_fast_fallback"),E,v,"Fast",u,!1,null,.6)[Symbol.asyncIterator](),pe=await We.next();return{iterator:We,firstResult:pe}}else if(m==="Mistral"&&!V){let We=sr(w,et("mistral_janitor_fallback"),E,v,"Fast",u,!1,null,.6)[Symbol.asyncIterator](),pe=await We.next();return{iterator:We,firstResult:pe}}else if(m==="NVIDIA"||V){let We=or(V?ie:w,et("nvidia_janitor_fallback"),E,v,"Fast",u,!1,null,.6)[Symbol.asyncIterator](),pe=await We.next();return{iterator:We,firstResult:pe}}else if(m==="CrofAI"){let We=rr(w,targetModel||"deepseek-v4-flash-0731",E,v,"Fast",u,!1,null,.6)[Symbol.asyncIterator](),pe=await We.next();return{iterator:We,firstResult:pe}}else{let pe=(await ar(w).models.generateContentStream({model:f||(re===Re?et("janitor_default"):et("gemma_janitor_fallback_google")),contents:E,config:{systemInstruction:v,temperature:.7,safetySettings:[{category:Vn.HARM_CATEGORY_HARASSMENT,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_HATE_SPEECH,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Yn.BLOCK_NONE}],thinkingConfig:{includeThoughts:!1,thinkingLevel:at.MINIMAL}}}))[Symbol.asyncIterator](),Kt=await pe.next();return{iterator:pe,firstResult:Kt}}})();if(process.stdout.isTTY){let pe=(await ls())[h]?.name||"",Kt=pe&&!pe.startsWith("flow-")&&!pe.startsWith("Session ")?pe:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${Kt}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${Kt}\x07`)}let{iterator:Bt,firstResult:pt}=await Promise.race([ht,Ue]),{value:mt,done:Tt}=pt;if(!Tt&&mt){let xt=mt.candidates?.[0]?.content?.parts,We=xt?J==="Google"?xt[1]?.text||xt[0]?.text||"":xt.filter(pe=>pe.text&&!pe.thought).map(pe=>pe.text).join(""):typeof mt.text=="function"?mt.text():"";We&&(M+=We),F=mt.usageMetadata;for await(let pe of{[Symbol.asyncIterator]:()=>Bt}){let Kt=pe.candidates?.[0]?.content?.parts,Jn=Kt?J==="Google"?Kt[1]?.text||Kt[0]?.text||"":Kt.filter(Xn=>Xn.text&&!Xn.thought).map(Xn=>Xn.text).join(""):typeof pe.text=="function"?pe.text():"";Jn&&(M+=Jn),F=pe.usageMetadata}}}catch(Ue){throw Ue}if(M){if(j=M,F){let Ue=F.totalTokenCount||0,st=F.cachedContentTokenCount||0,qe=(F.candidatesTokenCount||0)+(F.thoughtsTokenCount||0),ht=V?et("nvidia_janitor_fallback"):J==="DeepSeek"?et("deepseek_fast_fallback"):J==="OpenRouter"?et("janitor_open_router"):f||(re===Re?et("janitor_default"):et("gemma_janitor_fallback_google"));await qt("tokens",Ue,J,ht),st>0&&await qt("cachedTokens",st,J,ht),qe>0&&await qt("candidateTokens",qe,J,ht)}}else throw new Error("No synthesis generated by Janitor.");d&&(d(),await It("background"));let Ne=Go(j),De=!1;for(let Ue of Ne){let st=Ue.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(st)&&(De=!0);let qe={chatId:h,sessionId:h,history:o},ht=await fo(st,Ue.args,qe);st.toLowerCase()==="memory"&&(Ue.args.includes("action='user'")||Ue.args.includes('action="user"'))&&!ht.startsWith("ERROR")&&(p&&p(),process.stdout.isTTY&&(process.stdout.write("\x1B]0;Memory Updated\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=Memory Updated\x07")),await new Promise(pt=>setTimeout(pt,3e3)))}if(!De)try{let Ue=X(Dt,[]);if(Ue.length>0){let st=[];for(let qe of Ue)qe.score===void 0&&(qe.score=.5),qe.score*=.99995,qe.score<.05&&(qe.score=0),qe.score=Math.round(qe.score*1e5)/1e5,qe.score>0&&st.push(qe);he(Dt,st)}}catch{}break}catch(M){re++;let F=new Date().toLocaleString(),V=M instanceof Error?(()=>{try{return JSON.parse(JSON.parse(M.message).error.message).error.message}catch{return String(M)}})():String(M);await new Promise(De=>setTimeout(De,1e3));let J=Q.join(fn,"janitor");if(Oe.existsSync(J)||Oe.mkdirSync(J,{recursive:!0}),Oe.appendFileSync(Q.join(J,"error.log"),`ERROR [Attempt ${re}/${Re+1}] [${F}]: ${V}
527
-
528
- `),re>Re)break;let Ne=Math.min(750*Math.pow(2,re-1),5e3);await new Promise(De=>setTimeout(De,Ne))}if(re){let M=Q.join(fn,"janitor");Oe.appendFileSync(Q.join(M,"error.log"),`-----------------------------------------------------------------------------
529
-
530
- `)}if(process.stdout.isTTY)try{let V=(await ls())[h]?.name||"",J=V&&!V.startsWith("flow-")&&!V.startsWith("Session ")?V:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${J}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${J}\x07`)}catch{process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")}},Ec=e=>{let n=e.replace(yc,"").replace(wc,""),t=Is?n:n.replace(Ia,s=>" ".repeat(s.length)).replace(Oa,s=>" ".repeat(s.length));ho.lastIndex=0;let o;for(;(o=ho.exec(t))!==null;){let s=o.index+o[0].length-1,i=0,a=null,r=!1,p=!1;for(let d=s;d<t.length;d++){let c=n[d];if(!a&&(c==='"'||c==="'"||c==="`")?(a=c,r=!1):a&&c===a&&!r&&(a=null),!a&&(c==="("?i++:c===")"&&i--,i===0)){let l=d+1;for(;l<t.length&&/\s/.test(t[l]);)l++;if(l<t.length&&t[l]==="]"){p=!0,ho.lastIndex=l+1;break}}c==="\\"?r=!r:r=!1}if(!p)return{inside:!0,toolName:o[1],startIndex:o.index,args:n.substring(o.index+o[0].length)}}return{inside:!1}},Pa=(e,n=!0)=>{let t=ho;t.lastIndex=0;let o="",s=0,i;for(;(i=t.exec(e))!==null;){let a=e.substring(s,i.index);o+=n?a.replace(Ta,""):a;let r=i.index+i[0].length-1,p=0,d=null,c=-1;for(let l=r;l<e.length;l++){let u=e[l];if(d){if(u===d){let f=0;for(let h=l-1;h>=0&&e[h]==="\\";h--)f++;f%2===0&&(d=null)}}else if(u==='"'||u==="'"||u==="`")d=u;else if(u==="(")p++;else if(u===")"&&(p--,p===0)){let f=l+1;for(;f<e.length&&/\s/.test(e[f]);)f++;if(f<e.length&&e[f]==="]"){c=f;break}}}if(c!==-1)o+="[tool:functions."+i[1]+"()]",s=c+1,t.lastIndex=s;else{o+="[tool:functions."+i[1]+"(",s=e.length;break}}return s<e.length&&(o+=n?e.substring(s).replace(Ta,""):e.substring(s)),o},$c=(e,n,t)=>{let o=ho;o.lastIndex=0;let s="",i=0,a;for(;(a=o.exec(e))!==null;){let r=e.substring(i,a.index);s+=r.replace(n,t);let p=a.index+a[0].length-1,d=0,c=null,l=-1;for(let u=p;u<e.length;u++){let f=e[u];if(c){if(f===c){let h=0;for(let g=u-1;g>=0&&e[g]==="\\";g--)h++;h%2===0&&(c=null)}}else if(f==='"'||f==="'"||f==="`")c=f;else if(f==="(")d++;else if(f===")"&&(d--,d===0)){let h=u+1;for(;h<e.length&&/\s/.test(e[h]);)h++;if(h<e.length&&e[h]==="]"){l=h;break}}}if(l!==-1)s+=e.substring(a.index,l+1),i=l+1,o.lastIndex=i;else{s+=e.substring(a.index),i=e.length;break}}return i<e.length&&(s+=e.substring(i).replace(n,t)),s},Aa=e=>Pa(e,!0),Cc=e=>{if(!e)return e;let n={patchfile:"PatchFile",writefile:"WriteFile",readfile:"ReadFile",viewfile:"ReadFile",run:"Run",execcommand:"Run",searchkeyword:"SearchKeyword",codesearch:"CodeSearch",code_search:"CodeSearch",websearch:"WebSearch",webscrape:"WebScrape",readfolder:"ReadFolder",writepdf:"WritePDF",writedoc:"WriteDoc",writedocx:"WriteDoc",filemap:"FileMap",generateimage:"GenerateImage",todo:"Todo",goal:"Goal",ask:"Ask"},t=s=>s.split("_").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join("");Ea.lastIndex=0;let o=e.replace(Ea,(s,i,a)=>{let r="";try{let c=JSON.parse(a.trim());c&&typeof c=="object"&&(r=Object.entries(c).map(([u,f])=>{let h=typeof f=="string"?f:JSON.stringify(f);return`${u}=${JSON.stringify(h)}`}).join(", "))}catch{let l=[],u=xc;u.lastIndex=0;let f;for(;(f=u.exec(a))!==null;){let h=f[1],g=f[2]!==void 0?f[2]:f[0].split(":").slice(1).join(":").trim();l.push(`${h}=${JSON.stringify(g)}`)}l.length>0?r=l.join(", "):r=a.trim()}let p=i.toLowerCase().replace(/_/g,"");return`[tool:functions.${n[p]||t(i)}(${r})]`});return $a.lastIndex=0,Ca.lastIndex=0,o=o.replace($a,""),o=o.replace(Ca,""),o},_c=/(?:path|query|url|keyword|command|method|title|task|id)\s*=\s*['"`]?\s*\.\.\.\s*['"`]?/i,Mc=/^['"`]?\s*\.\.\.\s*['"`]?$/,Pn=e=>{if(e==null)return!1;let n=String(e).trim();return n==="..."||n==="\u2026"||Mc.test(n)},Go=e=>{if(!e)return[];let n=Cc(e);Ra.lastIndex=0;let t=n.replace(Ra,""),o=[],s=Is?t:t.replace(Ia,r=>" ".repeat(r.length)).replace(Oa,r=>" ".repeat(r.length)),i=hc;i.lastIndex=0;let a;for(;(a=i.exec(s))!==null;){let r=a[1],p=a.index+a[0].length-1,d=0,c=null,l=-1,u=-1;for(let f=p;f<s.length;f++){let h=t[f];if(c){if(h===c){let g=0;for(let y=f-1;y>=0&&t[y]==="\\";y--)g++;g%2===0&&(c=null)}}else if(h==='"'||h==="'"||h==="`")c=h;else if(h==="(")d++;else if(h===")"&&(d--,d===0)){u=f;let g=f+1;for(;g<s.length&&/\s/.test(s[g]);)g++;if(g<s.length&&s[g]==="]"){l=g;break}}}if(l!==-1){let f=t.substring(p+1,u),h=t.substring(a.index,l+1),g=I(f);Pn(g.path)||Pn(g.query)||Pn(g.url)||Pn(g.keyword)||Pn(g.command)||Pn(g.method)||Pn(g.title)||Pn(g.task)||Pn(g.id)||_c.test(f)||o.push({fullMatch:h,toolName:r.trim(),args:f.trim()}),i.lastIndex=l+1}}return o},Rm=(e,n={})=>{if(!e)return null;if(jo=n,tr=new va({apiKey:e}),!globalThis.__perfCleanupInstalled){globalThis.__perfCleanupInstalled=!0,setInterval(()=>{typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks())},6e4);let t=globalThis.fetch;globalThis.fetch=async(...o)=>{try{let s=await t(...o);return typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),s}catch(s){throw typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),s}}}},Ho=async(e,n,t,o,s="Fast",i=.75,a="agent")=>kc(async()=>{let{aiProvider:r="Google",apiKey:p,mode:d}=e,c="",l=null,u=typeof t=="string"?[{role:"user",parts:[{text:t}]}]:t,f=new AbortController,h=f.signal,g=setInterval(()=>{Ot&&(f.abort(),clearInterval(g))},100);try{let y;r==="Ollama"?y=La(p,n,u,o,s,d,rn(n),h,i,systemSettings?.ollamaEndpoint||"Cloud"):r==="OpenRouter"?y=ir(p,n,u,o,s,d,rn(n),h,i):r==="DeepSeek"?y=nr(p,n,u,o,s,d,rn(n),h,i):r==="Mistral"?y=sr(p,n,u,o,s,d,rn(n),h,i):r==="NVIDIA"?y=or(p,n,u,o,s,d,rn(n),h,i):r==="CrofAI"?y=rr(p,n,u,o,s,d,rn(n),h,i):y=await ar(p).models.generateContentStream({model:n,contents:u,config:{systemInstruction:o,temperature:i,thinkingConfig:(()=>{let x=(n||"").toLowerCase(),k=x.includes("gemma-4")||x.startsWith("gemma"),R=x.includes("gemini-3");if(k||R)return k?s.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:at.MINIMAL}:{includeThoughts:!0,thinkingLevel:at.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:x.includes("pro")?at.LOW:at.MINIMAL,Low:at.LOW,Medium:at.MEDIUM,Standard:at.MEDIUM,High:at.HIGH,xHigh:at.HIGH}[s]||at.MEDIUM};{let E={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[s]||2048;return E===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:E}}})()}},{signal:h});for await(let m of y){if(Ot)throw new Error("Subagent task was cancelled.");if(e?.taskId&&typeof Ve<"u"){let k=Ve.find(R=>R.id===e.taskId);if(k&&k.status==="cancelled")throw new Error("Subagent task was cancelled.")}let w="";if(m.candidates?.[0]?.content?.parts)for(let k of m.candidates[0].content.parts)k.text&&!k.thought&&(c+=k.text,w+=k.text);let 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 qt("tokens",y,r,n),m>0&&await qt("cachedTokens",m,r,n),w>0&&await qt("candidateTokens",w,r,n),e&&typeof e.onUsage=="function"&&e.onUsage({totalTokenCount:y,cachedContentTokenCount:m,candidatesTokenCount:w})}return await It("agent",r),{text:c,usageMetadata:l}}),Ac=async(e,n,t=null)=>{t=t||X(Qt,{});try{let{aiProvider:o="Google"}=n;if(Object.values(t).flat().length<=5)return;let i=Object.keys(t).filter(u=>u!==e&&Array.isArray(t[u])&&t[u].length>2);if(i.length===0)return;let a=`You are a silent background process for the FluxFlow CLI Agent.
531
- Your task is to summarize or merge temporary context memories from one or more past conversation sessions.
532
- For each Chat ID provided, you must output a tool call to save the consolidated summary.
533
-
534
- The tool call format MUST be:
535
- [tool:functions.saveSummary(id="<chat-id>", summary="<updated summary string, max 400 words>")]
536
-
537
- Guidelines:
538
- - 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.
539
- - Focus on key goals, preferences, modified files, and technical decisions.
540
- - Under no circumstances write normal conversational text. Output ONLY the tool calls.
541
- - You can stack multiple tool calls for multiple chats.
542
-
543
- Chats to process:
544
-
545
- `,r=X(vn,{});for(let u of i){let h=t[u].map(y=>`- ${y}`).join(`
546
- `),g=r[u];a+=`[Chat ID: ${u}]
547
- `,g?(a+=`- Existing Summary: "${g}"
548
- `,a+=`
549
- -- New Memories to integrate:
550
- ${h}
551
-
552
- `):a+=`-- Individual Memories:
553
- ${h}
554
-
555
- `}let p=0,d=5,c=!1,l=et("gemma_janitor_fallback_google");for(o==="OpenRouter"&&(l=et("janitor_open_router")),o==="DeepSeek"&&(l=et("deepseek_level_1")),o==="Mistral"&&(l=et("mistral_level_1")),o==="NVIDIA"&&(l=et("nvidia_janitor_fallback"));p<=d&&!c;){p++;try{let f=(await Ho(n,l,a,null,"Fast",.75,"background")).text||"",h=Go(f);if(h.length===0)throw new Error("No tool calls detected in synthesis response");for(let g of h){let y=g.toolName;["saveSummary","saveSumary","SaveSummary","SaveSumary"].includes(y)&&await fo(y,g.args,{chatId:e})}c=!0}catch(u){if(p>=d)throw new Error(`Failed after ${d} attempts. Last error: ${u.message}`)}}}catch(o){let s=o instanceof Error?(()=>{try{return JSON.parse(JSON.parse(o.message).error.message).error.message}catch{return String(o)}})():String(o),i=Q.join(fn,"janitor");Oe.existsSync(i)||Oe.mkdirSync(i,{recursive:!0}),Oe.appendFileSync(Q.join(i,"error.log"),`[${new Date().toLocaleString()}] Past memory batch consolidation error: ${s}
556
- `)}},vc=async(e,n,t=!1)=>{let{chatId:o,aiProvider:s="Google"}=e,i=Q.join(bo,"chat-summaries.json"),a=f=>f.filter(h=>(h.role==="user"||h.role==="agent"||h.role==="system")&&h.role!=="think"&&!h.isVisualFeedback&&!h.isMeta&&!h.isTerminalRecord&&!(h.text&&h.text.includes("[TERMINAL_RECORD]"))&&!String(h.id).startsWith("welcome")).map(h=>{let g=h.fullText||h.text||"",y=h.role==="system"||g.startsWith("[TOOL RESULT]:")||h.text&&h.text.startsWith("[TOOL RESULT]:"),m=g;return y&&(g.includes("[TOOL RESULT]:")||h.text&&h.text.includes("[TOOL RESULT]:"))?m="[TOOL RESULT]: ...truncated for summary":m=m.replace(/(\[(?:tool|agent):[a-zA-Z0-9_\.]+)\([\s\S]*?\)(\])/g,"$1(...)$2"),`[${y?"TOOL":h.role==="agent"?"AGENT":"USER"}]: ${m}`}).join(`
557
-
558
- `),r=async(f,h)=>{let g="You are an expert context summarizer. Summarize the provided chat history (which may include previous summaries, user instructions, agent outputs, and tool results) into a detailed, coherent, and highly technical summary of 1000 to 1500 words. Focus on preserving the architectural decisions made, current system state, task progress, and critical code details, chat messages, file changes. Under no circumstances exceed MAX 2000 words.",y=h?`Here is the previous summary:
559
- ${h}
560
-
561
- Here is the new conversation history:
562
- ${f}
563
-
564
- Provide a new consolidated summary of the entire session.`:`Here is the conversation history:
565
- ${f}
566
-
567
- Provide a consolidated summary of the entire session.`,m=et("gemma_janitor_fallback_google");s==="OpenRouter"&&(m=et("janitor_open_router")),s==="DeepSeek"&&(m=et("deepseek_level_1")),s==="Mistral"&&(m=et("mistral_level_1")),s==="NVIDIA"&&(m=et("nvidia_chat_summarizer_fallback"));let w=0,x=!1,k=null;for(;w<=3&&!x;){w++;try{k=await Ho(e,m,y,g,"Fast"),x=!0}catch{if(w>3){if(s==="Google")try{let E=et("general_fallback");return(await Ho(e,E,y,g,"Fast")).text||""}catch{return""}return""}}}return k&&k.text||""},p=a(n),d=X(i,{}),c=d[o]||{summary:"",historyLength:0};typeof c=="string"&&(c={summary:c,historyLength:0});let l=c.summary||"",u=await r(p,l);if(u){c.summary=u;let f=Sc(n);return t?c.historyLength=(c.historyLength||0)+f:c.historyLength=f,d[o]=c,he(i,d),u}return null},Em=e=>{try{let n=Q.join(bo,"chat-summaries.json");if(Oe.existsSync(n)){let t=X(n,{});t[e]&&(delete t[e],he(n,t))}}catch{}},$m=async function*(e,n,t,o,s){let{profile:i,thinkingLevel:a,mode:r,janitorModel:p,chatId:d,isPlayground:c,systemSettings:l,sessionStats:u,aiProvider:f="Google",apiTier:h,wildcardTooling:g}=t,y=rn(e);if(!tr&&f==="Google")throw new Error("AI not initialized");let m=process.env.NVIDIA_BASE_URL||t?.aiProvider==="Ollama"||t?.aiProvider==="CrofAI"?!1:l?.memory!==!1,w=n[n.length-1].text,x=Q.join(bo,"chat-summaries.json"),k=!1,R=n.filter(C=>C.role==="user").length===1,E=w.includes("[TITLE-UPDATE]"),S=R||E,T=w.replace(/\[TITLE-UPDATE\]/g,"").trim();T=T.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),yield{type:"status",content:"[start]"},yield{type:"status",content:"Gathering Context"},await ut.startTransaction(d,T),l?.advanceRollback&&await Kn.takeInitialSnapshot(d),Ot=!1;let $=null;try{let C=new AbortController;$=setInterval(()=>{Ot&&(C.abort(),$&&(clearInterval($),$=null))},400);let b=[...n.slice(0,-1)];{let ve=X(x,{})[d]||{summary:"",historyLength:0};if(ve.summary&&ve.historyLength>0){let Zt=0,Ie=[];for(let Qe=0;Qe<b.length;Qe++){let je=b[Qe];(je.role==="user"||je.role==="agent"||je.role==="system")&&!String(je.id).startsWith("welcome")&&!je.isMeta&&Zt++,Zt>ve.historyLength&&Ie.push(je)}b=Ie}}b=b.map(H=>{if(H.role==="user"&&H.text){let ve=H.text.match(/\[USER\]([\s\S]*?)\[\/USER\]/);if(ve)return{...H,text:ve[1].trim()}}return{...H}});let v=process.env.HIGH_CONTEXT,O=255e3,P=26e4;if(v&&v!=="false"){let H=parseInt(v,10);!isNaN(H)&&H>=256e3&&H<=1e6&&(P=H,O=Math.round(H*.85))}if((f==="NVIDIA"&&(e?.includes("gpt")||e?.includes("qwen")||e?.includes("medium")||e.includes("muse"))||f==="Mistral")&&(O=122e3,P=126e3),f!=="Ollama"&&(u?.tokens||0)>O&&(yield{type:"status_history",content:"Context Limit Reached. Condensing session history..."},await vc(t,b,!0)&&(b=[],k=!0)),R&&m){let H=X(Qt,{});Object.values(H).flat().length>5&&(yield{type:"status",content:"Condensing past chat memories"},await Ac(d,t,H))}let W=X(Qt,{}),N=X(vn,{}),Y=Object.entries(W).filter(([H])=>H!==d).flatMap(([H,ve])=>ve),Me=[...Object.entries(N).filter(([H])=>H!==d).slice(-20).map(([H,ve])=>`[Chat Summary]: ${ve}`),...Y].map(H=>`- ${H}`).join(`
568
- `),j=X(Dt,[]).map(H=>`- ${H.memory}`).join(`
569
- `),re=(u?.tokens||0)>=1e4,Re=Er(Me,j,m,re),M=new Date,F=M.getFullYear(),V=M.toLocaleString("en-US",{month:"short"}).toUpperCase(),J=String(M.getDate()).padStart(2,"0"),Ne=M.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}),De=`${F}-${V}-${J}, ${Ne}`,Ue=[".git","node_modules",".gemini","dist","build",".next","out",".cache","bin","obj","vendor","venv",".idea",".gradle",".terraform","target","coverage",".vscode",".svn",".hg",".fslckout",".github",".gitlab",".circleci",".gitea",".gitee",".lerna",".changeset",".nx",".npm",".yarn",".pnpm-store",".pnpm",".expo",".nuxt",".svelte-kit",".docusaurus",".turbo",".vercel","bower_components",".netlify",".vuepress",".quasar",".output",".angular","jspm_packages",".parcel-cache",".rollup.cache",".rspack",".vitepress","__pycache__",".pytest_cache",".mypy_cache",".tox",".poetry","env","vhdl",".ipynb_checkpoints",".jupyter",".conda",".pdm-build",".bundle",".yardoc",".metadata","App_Data","ClientBin",".cargo",".rustc_info",".go","Godeps","_vendor",".rake_tasks","CMakefiles",".wakatime",".dart_tool",".fvm",".cocoapods","Pods",".pub-cache",".symlinks","DerivedData",".xcworkspace",".serverless",".aws",".gcloud",".azure",".kube",".vagrant",".docker","postgres-data","redis-data","mongo-data",".Spotlight-V100",".Trashes","$RECYCLE.BIN","System Volume Information",".DocumentRevisions-V100",".fseventsd","AppData","Application Data","Local","LocalLow","Roaming","$WinREAgent","$WINDOWS.~BT","$WINDOWS.~WS","scw","System32","SysWOW64",".AppleDouble",".AppleDB",".AppleDesktop","_CodeSignature",".cmio",".LSOverride",".localized",".TemporaryItems",".Trash",".Trash-0",".Trash-1000",".gvfs",".local",".config",".dbus",".fontconfig",".snap",".var",".lost+found","lost+found",".thumb",".thumbnails","EFI","boot","grub","logs","log",".nyc_output",".sonar",".ruff_cache",".VSCodeCounter"],st=H=>{try{return Oe.readdirSync(H,{withFileTypes:!0})}catch{return[]}},qe=(H,ve={value:0},Zt=1)=>{if(ve.value>6200||Zt>7)return ve.value;let Ie=st(H);for(let Qe of Ie){if(ve.value>6200)break;Ue.includes(Qe.name)||Qe.name.startsWith(".")||Qe.isDirectory()&&(ve.value++,qe(Q.join(H,Qe.name),ve,Zt+1))}return ve.value},ht=(H,ve)=>l?.indentationTree!==!1?Ji(H,ve,1,st,Ue):Qi(H,ve,"",1,st,Ue),Bt=qe(process.cwd()),pt=12;Bt>3072?pt=1:Bt>2304?pt=2:Bt>1536?pt=3:Bt>768?pt=4:Bt>384?pt=6:Bt>192?pt=7:Bt>96?pt=8:Bt>48?pt=9:Bt>24&&(pt=10);let mt=X(Qo,{}),Tt=mt[d],xt=Tt?Tt!==process.cwd():!1;mt[d]=process.cwd(),he(Qo,mt);let We=X(x,{}),pe=We[d]||{summary:"",historyLength:0};typeof pe=="string"&&(pe={summary:pe,historyLength:0});let Kt=n.filter(H=>(H.role==="user"||H.role==="agent"||H.role==="system")&&!String(H.id).startsWith("welcome")&&!H.isMeta).length;pe.historyLength&&Kt<pe.historyLength&&(pe.summary="",pe.historyLength=0,We[d]=pe,he(x,We));let Jn=typeof pe=="object"?pe.summary||"":pe||"",Xn=b.length>0;Xn&&Jn&&b[0]&&(b[0].role==="user"||b[0].role==="system")&&(b[0].text.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")||(b[0].text=`[SYSTEM METADATA]
570
- **CONTEXT SUMMARY OF PREVIOUS TURNS (PRIORITY: DYNAMIC)**
571
- ${Jn}
572
-
573
- [USER] ${b[0].text}`,yield{type:"summary_injected",content:{id:b[0].id,text:b[0].text}}));let lr=Jn&&!Xn?`
574
- [SYSTEM METADATA]
575
- **CONTEXT SUMMARY OF PREVIOUS TURNS**
576
- ${Jn}
577
- `:"",cr=!!l?.dynamicDirAwareness,Da=`${d}|${f}|${a}|${e}|${i}|${cr}`,dr=!cr&&ws.key===Da&&ws.value?"":`
578
- **Directory Structure**
579
- CWD: `+process.cwd()+`${c?" [PLAYGROUND MODE]":""}
580
- `+ht(process.cwd(),pt),bt=await gs(),Fn="";if(Wo()&&bt.file_focused!=="none"){Fn=`
581
- [Additional IDE Context]
582
- `;let H=Q.relative(process.cwd(),bt.file_focused),ve=(bt.opened_editors||[]).map(Ie=>{let Qe=Q.relative(process.cwd(),Ie);return Qe.startsWith("..")?`[External] ${Q.basename(Ie)}`:Qe});if(Fn+=`Focused File: ${H}
583
- Cursor Line: ${bt.cursor_line}
584
- `,bt.selected){let Ie=bt.selected,Qe=Ie.split(`
585
- `);Qe.length>256&&(Ie=Qe.slice(0,240).join(`
586
- `)+`
587
- ... [truncated] ...
588
- `+Qe.slice(-16).join(`
589
- `)),Ie.length>2048&&(Ie=Ie.slice(0,1920)+`
590
- ... [truncated] ...
591
- `+Ie.slice(-128)),Fn+=`Current Selection: "${Ie}"
592
- `}if(bt.manual_edits){let Qe=bt.manual_edits.split(`
593
- `),je=[],Je=null;for(let q of Qe)q.trim()&&(q.startsWith(" Line ")?Je&&Je.edits.push(q):(Je={path:q.endsWith(":")?q.slice(0,-1):q,edits:[]},je.push(Je)));for(let q of je)q.edits.length>80&&(q.edits=q.edits.slice(-80)),q.originalEditsCount=q.edits.length;let ce=(q,Z)=>Z.reduce((He,cn)=>{let wn=bt.file_focused&&(cn.path===bt.file_focused||Q.resolve(process.cwd(),cn.path)===Q.resolve(bt.file_focused))?Math.ceil(q*1.2):q;return He+Math.min(cn.edits.length,wn)},0),Ut=80;if(ce(80,je)>300){let q=!1;for(let Z=80;Z>=10;Z--)if(ce(Z,je)<=300){Ut=Z,q=!0;break}q||(Ut=10)}let Xe=[...je];if(Ut===10&&ce(10,Xe)>500)for(;Xe.length>0&&ce(10,Xe)>500;){let q=0,Z=Xe[0].originalEditsCount;for(let He=1;He<Xe.length;He++)Xe[He].originalEditsCount<Z&&(Z=Xe[He].originalEditsCount,q=He);Xe.splice(q,1)}for(let q of Xe){let He=bt.file_focused&&(q.path===bt.file_focused||Q.resolve(process.cwd(),q.path)===Q.resolve(bt.file_focused))?Math.ceil(Ut*1.2):Ut;q.edits.length>He&&(q.edits=q.edits.slice(-He))}for(let q of Xe){let Z=`${q.path}:
594
- ${q.edits.join(`
595
- `)}`;for(;q.edits.length>0&&Z.length>4*768;)q.edits.shift(),Z=`${q.path}:
596
- ${q.edits.join(`
597
- `)}`;Z.length>4*768?q.stringRepresentation="... "+Z.slice(-(4*768-4)):q.stringRepresentation=Z}let en=Xe.map(q=>q.stringRepresentation).join(`
598
- `);for(;Xe.length>0&&en.length>4*2048;){Xe[0].edits.length>0?Xe[0].edits.shift():Xe.shift();for(let q of Xe){let Z=`${q.path}:
599
- ${q.edits.join(`
600
- `)}`;Z.length>4*768?q.stringRepresentation="... "+Z.slice(-(4*768-4)):q.stringRepresentation=Z}en=Xe.map(q=>q.stringRepresentation).join(`
601
- `)}en.length>4*2048&&(en="... "+en.slice(-(4*2048-4))),Fn+=`Recent Manual Edits:
602
- ${en}
603
- `}ve.length>0&&(Fn+=`All Opened Editors: ${ve.join(", ")}`),bt.diagnostics&&(Fn+=`
604
- **Active File Errors**:
605
- ${bt.diagnostics}
606
- `),(T.toLowerCase().includes("lint")||T.toLowerCase().includes("warning"))&&bt.warnings&&(Fn+=`
607
- **Lint Warnings**:
608
- ${bt.warnings}
609
- `)}let fr=T.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),ur=/(?:\\)?@\[([^\]]+)\]/g,qo,zo=[];for(ur.lastIndex=0;(qo=ur.exec(fr))!==null;){let H=qo[0].startsWith("\\");zo.push({tag:qo[1],isEscaped:H})}let Ko=[],mo=null;for(let H=0;H<zo.length;H++){let{tag:ve,isEscaped:Zt}=zo[H];if(!Zt)try{let Ie=ve.trim().replace(/^["']|["']$/g,""),Qe=/[:#]L?(\d+)(?:-L?(\d+))?$/i,je=Ie.match(Qe),Je=Ie,ce=null,Ut=null;je&&(ce=parseInt(je[1],10),Ut=je[2]?parseInt(je[2],10):ce,Je=Ie.slice(0,je.index));let Xe=Q.resolve(process.cwd(),Je);if(Oe.existsSync(Xe)&&Oe.statSync(Xe).isFile()){let q=Je.toLowerCase(),Z=q.endsWith(".pdf"),He=q.endsWith(".docx")||q.endsWith(".doc")||q.endsWith(".ppt")||q.endsWith(".pptx")||q.endsWith(".xls")||q.endsWith(".xlsx"),cn=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(q),Wt=cn||Z||He,wn=f==="Google"||rn(e);if(Wt&&!wn){let Be=`\u2718 Unsupported Modality: ${Q.basename(Je)}`,Ee=115;process.stdout.isTTY&&(Ee=process.stdout.columns-5||120);let lt=[Be],Nn=Math.max(...lt.map($n=>$n.length)),Bn=Math.min(Nn+4,Ee),es=lt.map($n=>`${$n.padEnd(Bn-2).substring(0,Bn-2)}`).join(`
610
- `);yield{type:"visual_feedback",content:gn(`${es}
611
- `)};continue}if(ce===null&&!Wt){let Be=0;try{Be=Oe.readFileSync(Xe,"utf8").split(/\r\n|\r|\n/).length}catch{}if(Be>300){let Ee=`\u21B7 Skipped (Too Large): ${Q.basename(Je)}`,lt=115;process.stdout.isTTY&&(lt=process.stdout.columns-5||120);let Nn=Math.min(Ee.length+4,lt),Bn=Ee.padEnd(Nn-2).substring(0,Nn-2);yield{type:"visual_feedback",content:gn(`${Bn}
612
- `)};continue}}let En=ce!==null?ce:1,Qn=Ut!==null?Ut:ce!==null?ce:En+299;Qn-En>300&&(Qn=En+300);let yo=`path=${JSON.stringify(Je)}, startLine=${En}, endLine=${Qn}`,tt=await Qs(yo,{isMultiModal:wn}),ze=!1,jt="",Zn=null;if(typeof tt=="string"?tt.trim().startsWith("ERROR")?ze=!0:jt=tt:tt&&typeof tt=="object"&&tt.binaryPart?(Zn=tt.binaryPart,jt=tt.text||""):ze=!0,!ze){let Be="";if(cn?(Be=`\u2714 Processed: ${Q.basename(Je)}`,mo=Zn):Z||He?(Be=`\u2714 Auto-Analysed: ${Q.basename(Je)}`,mo=Zn):(Be=`\u2714 Auto-Read: ${Q.basename(Je)}`,Ko.push(jt)),Be){let Ee=115;process.stdout.isTTY&&(Ee=process.stdout.columns-5||120);let lt=[Be],Nn=Math.max(...lt.map($n=>$n.length)),Bn=Math.min(Nn+4,Ee),es=lt.map($n=>`${$n.padEnd(Bn-2).substring(0,Bn-2)}`).join(`
613
- `);yield{type:"visual_feedback",content:gn(`${es}
614
- `)}}}}}catch{}}let hr="";Ko.length>0&&(hr=`[Tagged File Contents] Auto Read User Tagged files by System, No need to re-read
615
- `+Ko.join(`
616
-
617
- `)+`
618
- [Tagged File Contents]
619
- `);let Fa=fr.replace(/\\(@\[[^\]]+\])/g,"$1"),Na=g?`You cannot execute tools
620
- Instead, output in chat the exact string you WOULD have produced & wait for system response
621
- `:"",pr=`[System Metadata]
622
- Time: ${De}${l?.dynamicDirAwareness?dr:""}${xt?`
623
- WARNING: CWD Changed from previous: "${Tt}" to current: "${process.cwd()}", write change in chat to avoid future path mismatches
624
- `:""}${Re}${Fn}
625
- [/Metadata]
626
- ${lr}${a!=="Fast"&&(f==="Mistral"&&!qs(e)||a!=="xHigh"&&f==="Google")?`${f==="Mistral"&&!qs(e)||e.toLowerCase().startsWith("gemma")?`[system] strictly follow thinking policy as high priority. do not start a response without <think>...</think> [/system]
627
- `:""}`:""}[system] exact structured string '[tool:functions.toolname(arg="value")]' in chat response [/system]
628
- ${hr}${Na}[user prompt] ${Fa.trim()} [/user prompt]`.trim(),mr={role:"user",text:pr};mo&&(mr.binaryPart=mo),b.forEach(H=>{H.text&&H.role==="agent"&&(H.text=H.text.replace(/(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])/gi,""),H.text=H.text.replace(/(?:<(think|thought)>|\[(think|thought)\])[^\[\n]*/gi,"").trim())}),b.push(mr),lr&&n[n.length-1]?.id&&(yield{type:"summary_injected",content:{id:n[n.length-1].id,text:pr}});let Rn=null,Bs=r==="Flux"?100:10;Bs=r.toLowerCase().includes("cu")?250:Bs;let yn=16;yield{type:"status",content:"Connecting"},Ot=!1;let gr=[],go=!1;for(let H=0;H<=Bs;H++){let ve=await li("agent",t);if(!ve.allowed)throw new Error(ve.reason||`Budget Exhausted for Provider (${f||"Agent"})`);let Zt=[];if(go=!1,r==="ICU"||r==="FluxCU")try{yield{type:"status",content:"Capturing Screen"},await new Promise($e=>setTimeout($e,1e3));let ue=await wr();if(ue&&ue.base64){let $e="[system] Fresh Gridded Screen Feedback Captured. Use numeric coordinates. Old screenshots will be removed when new screenshot is captured, summarize in text if context is needed later [/system]",ne={inlineData:{mimeType:ue.mimeType,data:ue.base64}};for(let nt of b)Array.isArray(nt.parts)&&(nt.parts=nt.parts.filter(_t=>!_t.inlineData));if(b.length>0&&b[b.length-1].role==="user"){let nt=b[b.length-1];typeof nt.text=="string"&&(nt.text+=`
629
-
630
- ${$e}`,Array.isArray(nt.parts)||(nt.parts=[{text:nt.text}]),nt.parts.push(ne))}else b.push({role:"user",text:$e,parts:[{text:$e},ne]})}}catch(ue){console.error("Vision screenshot capture error:",ue)}if(l?.compression===0&&(u?.tokens||0)>P&&(b=Ar(b,6)),H>0?yield{type:"status",content:"Working"}:yield{type:"status",content:"Connecting"},Ot){try{let{clearPendingNudges:ue}=await import("./subagent_state-LZCOZSUJ.js");ue()}catch{}yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
631
-
632
- \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}try{let{consumePendingNudges:ue}=await import("./subagent_state-LZCOZSUJ.js"),$e=ue();if($e&&$e.length>0){let ne=$e.join(`
633
-
634
- `);b.length>0&&b[b.length-1].role==="user"?b[b.length-1].text+=`
635
-
636
- ${ne}`:b.push({role:"user",text:ne}),yield{type:"status",content:"Subagent Update"}}}catch{}if(o){let ue=await o();ue&&(ue.startsWith("/btw")?b.length>0&&b[b.length-1].role==="user"?b[b.length-1].text+=`
637
-
638
- [system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/SYSTEM]
639
- [question] ${ue.replace("/btw","").trim()} [/question]`:b.push({role:"user",text:`[system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
640
- [question] ${ue.replace("/btw","").trim()} [/question]`}):b.length>0&&b[b.length-1].role==="user"?b[b.length-1].text+=`
641
-
642
- [STEERING HINT from USER, HIGH PRIORITY] ${ue.trim().toUpperCase()} [/STEERING HINT]`:b.push({role:"user",text:`[STEERING HINT from USER, HIGH PRIORITY] ${ue.trim().toUpperCase()} [/STEERING HINT]`}),yield{type:"status",content:`${ue.startsWith("/btw")?"Question Forwarded...":"Steering Hint Injected..."}`})}let Ie,Qe=!1,je=1,Je=1,ce="",Ut=null,Xe=null,en=null,q=0,Z=[],He=0,cn=!1,Wt=!1,wn=!1,En=!1,Qn=!0,yo=0,tt="",ze="",jt=!1,Zn=!1,Be=!0,Ee=e,lt="";for(;je<=yn&&Je<=yn&&!Qe&&!Ot;){let ue=!1;try{ce="",Qn&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},Qn=!1,Je===1&&(tt=""));let $e=D=>{if(!D||!D.includes("[tool:"))return D;let te="___THINK_OPEN_TAG___",U="___THINK_CLOSE_TAG___";D=D.replace("<think>",te).replace("</think>",U),D=D.replace(bc,(me,de)=>de.includes("[tool:")?de.trim():me);let G="",Se=0;for(;Se<D.length;){let me=D.indexOf("[tool:",Se);if(me===-1){G+=D.substring(Se).replace(_a,"").replace(Ma,"");break}let de=D.substring(Se,me);G+=de.replace(_a,"").replace(Ma,"");let Rt=D.indexOf("]",me);if(Rt===-1){G+=D.substring(me);break}G+=D.substring(me,Rt+1),Se=Rt+1}return D=G,D=D.replaceAll(te,"<think>").replaceAll(U,"</think>"),D},ne=b.filter(D=>(D.role==="user"||D.role==="agent"||D.role==="system")&&!String(D.id).startsWith("welcome")&&!D.isMeta&&!D.isTerminalRecord&&!(D.text&&D.text.startsWith("[TERMINAL_RECORD]"))).map((D,te,U)=>{let G=D.text||"";m||(G=G.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),D.role==="agent"&&(G=$e(G),G=G.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),G=G.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*"));let Se=[];return Array.isArray(D.parts)&&D.parts.length>0?Se=D.parts.map(me=>{if(me.text){let de=me.text;return m||(de=de.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),D.role==="agent"&&(de=$e(de),de=de.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),de=de.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*")),{text:de}}return me}):Se=[{text:G}],D.binaryPart&&rn(Ee)&&U.slice(te+1).filter(de=>de.role==="user"&&!de.text?.startsWith("[TOOL RESULT]")).length<=2&&Se.push(D.binaryPart),{role:D.role==="user"||D.role==="system"?"user":"model",parts:Se}});for(let D=0;D<ne.length;D++){let te=ne[D],U=te.parts?.[0]?.text||"";if(te.role==="model"&&/\[tool:/i.test(U)){let G=-1;for(let Se=D+1;Se<ne.length;Se++){let me=ne[Se],de=me.parts?.[0]?.text||"";if(me.role==="user"&&de.startsWith("[TOOL RESULT]")){G=Se;break}}if(G!==-1&&G!==D+1){let[Se]=ne.splice(G,1);ne.splice(D+1,0,Se)}}}for(let D=ne.length-2;D>=0;D--){let te=ne[D],U=ne[D+1];te.role==="user"&&U.role==="user"&&(U.parts?.[0]?.text||"").trim().startsWith("[SYSTEM")&&ne.splice(D,1)}let nt=[];for(let D=0;D<ne.length;D++){let te=ne[D];if(nt.length===0)nt.push(te);else{let U=nt[nt.length-1];U.role===te.role?(U.parts[0].text+=`
643
-
644
- `+(te.parts?.[0]?.text||""),te.parts?.length>1&&U.parts.push(...te.parts.slice(1))):nt.push(te)}}ne.length=0,ne.push(...nt),Ee=e;let _t=`${d}|${f}|${r}|${a}|${Ee}|${JSON.stringify(i)}|${!!l?.dynamicDirAwareness}|${!!l?.subAgents}`;if(ws.key===_t&&ws.value)lt=ws.value;else{let D=f==="Mistral"?!!qs(Ee):!(Ee||"gemma").toLowerCase().startsWith("gemma");lt=$r(i,((Ee||"gemma").toLowerCase().startsWith("gemma"),a),r,l,m,R,f,f==="Google"?!0:y,D,d),l?.dynamicDirAwareness||(lt+=`
645
- ${dr.replace(`
646
- **Directory Structure**`,`
647
- **Directory Structure**`)}`),ws.key=_t,ws.value=lt}let Mt=ne[ne.length-1];if(Wo()&H>0){await new Promise(U=>setTimeout(U,2500)),yield{type:"status",content:"Verifying"};let D=await gs(),te=D?D.diagnostics:null;te&&Mt&&Mt.role==="user"&&Mt.parts?.[0]?.text&&(Mt.parts[0].text+=`
648
- ${te} [/ERROR]`),yield{type:"status",content:"Working"}}if(f==="Mistral"||f==="Google"&&e?.toLowerCase().startsWith("gemma")){let te=a!=="Fast"&&(f==="Mistral"||a!=="xHigh")?". **strictly maintain thinking policy. do not start a response without <think>...</think>**":"",U=`
649
- [SYSTEM] Tool result received. Analyze output and proceed with your turn [/SYSTEM]`;Mt&&Mt.role==="user"&&Mt.parts?.[0]?.text?.startsWith("[TOOL RESULT]")&&(Mt.parts[0].text+=U)}if(l?.advanceRollback&&Mt&&Mt.role==="user"&&Mt.parts?.[0]?.text?.startsWith("[TOOL RESULT]"))try{let D=await Kn.getLatestFileChanges(d);if(D&&(D.newFiles.length>0||D.modifiedFiles.length>0||D.deletedFiles.length>0)){let te=`
650
- [system] File Changes:
651
- `;for(let G of D.newFiles)te+=`* ${G} (created)
652
- `;for(let G of D.modifiedFiles)te+=`* ${G} (modified)
653
- `;for(let G of D.deletedFiles)te+=`* ${G} (deleted)
654
- `;te+="[/system]",Mt.parts[0].text+=te;let U=-1;for(let G=b.length-1;G>=0;G--)if(b[G].role==="user"&&b[G].text?.startsWith("[TOOL RESULT]")){U=G;break}U!==-1&&(b[U].text+=te)}}catch{}let nn=Math.floor(Bs*(r==="Flux"?.98:.8)),Lt=H+1;Lt>=nn&&Mt&&Mt.parts?.[0]&&(Mt.parts[0].text+=`
655
- [system] WARNING, Turn Limit Impending: Step ${Lt}/${Bs}. Wrap up quickly/prompt user to continue. [/system]`);let Pt=new Promise((D,te)=>{C.signal.aborted&&te(new DOMException("The user aborted a request.","AbortError")),C.signal.addEventListener("abort",()=>{te(new DOMException("The user aborted a request.","AbortError"))})});Pt.catch(()=>{});let sn=ne;if(f==="Ollama")Ie=La(t.apiKey,Ee,sn,lt,a,r,y,C.signal,1,l?.ollamaEndpoint||"Cloud");else if(f==="OpenRouter")Ie=ir(t.apiKey,Ee,sn,lt,a,r,y,C.signal,1);else if(f==="DeepSeek")Ie=nr(t.apiKey,Ee,sn,lt,a,r,y,C.signal,1.05);else if(f==="Mistral")Ie=sr(t.apiKey,Ee,sn,lt,a,r,y,C.signal,1);else if(f==="NVIDIA"){let D=or(t.apiKey,Ee,sn,lt,a,r,y,C.signal,1.05);Ie=Rc(D,Ee)}else if(f==="CrofAI")Ie=rr(t.apiKey,Ee,sn,lt,a,r,y,C.signal,1);else{let te=ar(t?.apiKey).models.generateContentStream({model:Ee||"gemini-3-flash-preview",contents:sn,config:{systemInstruction:lt,mediaResolution:"MEDIA_RESOLUTION_HIGH",safetySettings:[{category:Vn.HARM_CATEGORY_HARASSMENT,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_HATE_SPEECH,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Yn.BLOCK_NONE},{category:Vn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Yn.BLOCK_NONE}],thinkingConfig:(()=>{let U=(Ee||"").toLowerCase(),G=U.includes("gemma-4")||U.startsWith("gemma"),Se=U.includes("gemini-3");if(G||Se)return G?a.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:at.MINIMAL}:{includeThoughts:!0,thinkingLevel:at.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:U.includes("pro")?at.LOW:at.MINIMAL,Low:at.LOW,Medium:at.MEDIUM,Standard:at.MEDIUM,High:at.HIGH,xHigh:at.HIGH}[a]||at.MEDIUM};{let me={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[a]||2048;return me===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:me}}})()}},{signal:C.signal});Ie=await Promise.race([te,Pt])}ce="",Ut=null,en=null,Z=[],He=0,yield{type:"model_update",content:null},ze="",jt=tt.length>0;let xn="",Yo=Date.now(),ss=async function*(){if(f==="Google"&&xn){let D=Us(xn);for(let te of D)yield te;xn="",Yo=Date.now()}},yr=!0,os="",bs=!1,ct=null,Us=D=>{let te=[],U=D;for(;U.length>0;)if(bs){let G=os+U;if(ct==="tool"||ct==="agent"){let de=ct==="tool"?"[tool:functions.":"[agent:generalist.",Rt=ct==="tool"?"[tool":"[agent";if(!G.startsWith(Rt)||G.length>=de.length&&!G.startsWith(de)){te.push({type:"text",content:G}),os="",bs=!1,ct=null,U="";break}}let Se=-1,me="]";if(ct==="tool"||ct==="agent"){let de=0,Rt=null,z=0,ge=!1;for(let Ke=0;Ke<G.length;Ke++){let _=G[Ke];if(Rt){if(_===Rt){let kt=0;for(let Le=Ke-1;Le>=0&&G[Le]==="\\";Le--)kt++;kt%2===0&&(Rt=null)}}else if(_==='"'||_==="'"||_==="`")Rt=_;else if(_==="(")de++,ge=!0;else if(_===")")de--;else if(_==="[")z++;else if(_==="]"){if(ge&&de===0&&z===1){Se=Ke;break}z--}}}else ct==="end"?me="[[END]]":ct==="kimi_section"?me="<|tool_calls_section_end|>":ct==="kimi_call"&&(me="<|tool_call_end|>"),Se=G.indexOf(me);if(Se!==-1){let de=me.length;if(!ct.startsWith("kimi")){let Rt=G.substring(0,Se+de);te.push({type:"text",content:Rt})}os="",bs=!1,ct=null,U=G.substring(Se+de)}else{let de=ct.startsWith("kimi")?8192:512;G.length>de?(ct.startsWith("kimi")||te.push({type:"text",content:G}),os="",bs=!1):os=G,U="";break}}else{let G=U.indexOf("[tool"),Se=U.indexOf("[agent"),me=U.indexOf("[[END]]"),de=U.indexOf("<|tool_calls_section_begin|>"),Rt=U.indexOf("<|tool_call_begin|>"),z=[{type:"tool",idx:G,start:"[tool",end:"]"},{type:"agent",idx:Se,start:"[agent",end:"]"},{type:"end",idx:me,start:"[[END]]",end:"[[END]]"},{type:"kimi_section",idx:de,start:"<|tool_calls_section_begin|>",end:"<|tool_calls_section_end|>"},{type:"kimi_call",idx:Rt,start:"<|tool_call_begin|>",end:"<|tool_call_end|>"}].filter(ge=>ge.idx!==-1).sort((ge,Ke)=>ge.idx-Ke.idx);if(z.length>0){let ge=z[0];ge.idx>0&&te.push({type:"text",content:U.substring(0,ge.idx)}),bs=!0,ct=ge.type,os="",U=U.substring(ge.idx)}else{let ge=["[tool","[agent","[[END]]","<|tool_calls_section_begin|>","<|tool_call_begin|>"],Ke=-1;for(let _ of ge){for(let kt=_.length-1;kt>0;kt--)if(U.endsWith(_.substring(0,kt))){Ke=U.length-kt;let Le=ge.indexOf(_);Le===0?ct="tool":Le===1?ct="agent":Le===2?ct="end":Le===3?ct="kimi_section":ct="kimi_call";break}if(Ke!==-1)break}if(Ke!==-1)Ke>0&&te.push({type:"text",content:U.substring(0,Ke)}),bs=!0,os=U.substring(Ke),U="";else{te.push({type:"text",content:U});break}}}return te},Wa=Ie[Symbol.asyncIterator]();for(;;){let{value:D,done:te}=await Promise.race([Wa.next(),Pt]);if(te)break;if(D&&D.type==="status"){yield D;continue}let U="",G=D.candidates?.[0]?.content?.parts;if(G&&G.length>0)for(let me of G){let de=typeof me.text=="string"?me.text:me.text?parseChunkText(me.text):"";me.thought?de&&(ue||(U+="<think>",ue=!0),U+=de):de&&(ue&&(U+="</think>",ue=!1),U+=de)}else D.text&&ue&&(U+="</think>",ue=!1);U=Dn(U);let Se=U?U.trim().split(/\s+/).filter(Boolean).length:0;if(t&&typeof t.onTokenChunk=="function"&&t.onTokenChunk(U,Se),yr&&(yield{type:"status",content:"Thinking"},yr=!1),Ot){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
656
-
657
- \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(U){if(jt){if(ze+=U,ze.length>=64){let z=0,ge=Math.min(tt.length,ze.length);for(let _=ge;_>=10;_--)if(tt.endsWith(ze.substring(0,_))){z=_;break}let Ke=ze.substring(z);if(Ke){let kt=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(tt)?Ke.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):Ke.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(kt)if(ce+=kt,f==="Google")xn+=kt;else{yield*ss();let Le=Us(kt);for(let oe of Le)yield oe}}jt=!1,ze=""}continue}else if(ce+=U,f==="Google")xn+=U;else{yield*ss();let z=Us(U);for(let ge of z)yield ge}let me=Ec(ce);if(me.inside){Zn=!0,en||(en=Date.now());let ge={Ask:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Cancel:"cancel",Await:"await",Answer:"answer",Steer:"steer",steer:"steer"}[me.toolName]||me.toolName,Ke=me.args||"",_=null;if(["write_file","update_file","view_file","read_folder","write_pdf","write_docx","search_keyword","generate_image","file_map","invoke","invoke_sync","get_progress","await","answer"].includes(ge)){let Le=I(Ke),oe=Le.path||Le.targetFile||Le.TargetFile||Le.directory,bn=Le.keyword,is=Le.title||Le.task,Un=Le.id||Le.taskId,Te=Le.timeout||Le.time;if(bn!=null)_=String(bn).replace(ys,"");else if(oe)_=Q.basename(String(oe).replace(ys,"").replace(Sa,"/"));else if(is&&(ge==="invoke"||ge==="invoke_sync"))_=String(is).replace(ys,"").substring(0,30);else if(Un&&ge==="get_progress")_=String(Un).replace(ys,"");else if(Te&&ge==="await"){let Ht=parseFloat(String(Te).replace(ys,""));isNaN(Ht)?_=String(Te).replace(ys,""):(Ht<5&&(Ht=5),Ht>120&&(Ht=120),_=(Cn=>{if(Cn>=60){let Jo=Math.floor(Cn/60),ks=Cn%60;return`${Jo}m${ks>0?` ${ks}s`:""}`}return`${Cn}s`})(Ht))}else{let Ht=Ke.match(pc);if(Ht){let Yt=Ht[1].replace(ys,"");ge==="invoke"||ge==="invoke_sync"||ge==="get_progress"?_=Yt.substring(0,30):_=ge==="search_keyword"||ge==="file_map"?Yt:Q.basename(Yt.replace(Sa,"/"))}}}let kt=`${Zi[ge]||ge}${_?` ${_}`:""}`;if((ge!==Ut||_!==Xe)&&(Ut=ge,Xe=_,yield{type:"status",content:`${kt}`},process.stdout.isTTY)){let oe={WebSearch:"Searching",web_search:"Searching",WebScrape:"Reading",web_scrape:"Reading",ReadFile:"Reading",read_file:"Reading",ReadFolder:"Reading",read_folder:"Reading",WriteFile:"Writing",write_file:"Writing",UpdateFile:"Editing",update_file:"Editing",WritePdf:"Creating",write_pdf:"Creating",WriteDocx:"Creating",write_docx:"Creating",SearchKeyword:"Searching",search_keyword:"Searching",CodeSearch:"Searching",code_search:"Searching",Run:"Executing",Ask:"User Input Required",Memory:"Updating Memory",GenerateImage:"Generating",InvokeSync:"Sub-Agent Working",invoke_sync:"Sub-Agent Working",Invoke:"Working",invoke:"Working",GetProgress:"Checking Progress",get_progress:"Checking Progress",Cancel:"Stopping Generalist",cancel:"Stopping Generalist",Await:"Waiting",await:"Waiting",EmergencyRollback:"Rolling the Ball",Answer:"Answering Sub-Agent",answer:"Answering Sub-Agent",Steer:"Steering Sub-Agent",steer:"Steering Sub-Agent",Click:"Clicking",click:"Clicking",Drag:"Dragging",drag:"Dragging",Scroll:"Scrolling",scroll:"Scrolling",KeyboardTyping:"Typing",keyboard_typing:"Typing",KeyPress:"Pressing Key",key_press:"Pressing Key",RecaptureScreen:"Recapturing Screen",recapture_screen:"Recapturing Screen"}[ge]||"Working";process.stdout.write(`\x1B]0;${oe}...\x07`)}}if(ce.length-yo>150){yo=ce.length;let z=Pa(ce,!1),Ke=(z.match(/(?:<think>|\[think\])([\s\S]*?)(?:<\/think>|\[\/think\]|$)/gi)||[]).join("").trim(),_=Ke.split(/[.!?]\s+/),kt=new Set(_),Le=_.length>10?(_.length-kt.size)/_.length:0,oe=Ke.split(/\s+/).filter(Ce=>Ce.length>0).length,bn=.6,is=.8,Un=!1;if((f.toLowerCase().includes("google")||f.toLowerCase().includes("mistral"))&&((Ee||"").toLowerCase().startsWith("gemma")||(Ee||"").toLowerCase().includes("stral"))){let A={low:256,medium:1024,high:8192,max:16384,xhigh:16384}[a?.toLowerCase()]||2500;Un=oe>A}if(Le>bn||Un){yield{type:"status",content:`${Le>bn?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},Wt=!0,await new Promise(A=>setTimeout(A,3e3));break}let Yt=Aa(ce).trim().split(/[.!?]\s+/),Cn=new Set(Yt);if((Yt.length>10?(Yt.length-Cn.size)/Yt.length:0)>is){yield{type:"status",content:"Response Loop Detected. Re-centering..."},Wt=!1,En=!0,await new Promise(Ce=>setTimeout(Ce,3e3));break}let ks=z.replace(ac,"").replace(lc,"").replace(cc,"").replace(dc,""),Gt=ks.toLowerCase().split(/\s+/).map(Ce=>Ce.replace(fc,"")).filter(Ce=>Ce.length>0),_n=!1;if(Gt.length>=10)for(let Ce=1;Ce<=15;Ce++){let A=Math.max(3,Math.ceil(10/Ce));if(Gt.length<Ce*A)continue;let K=Gt.slice(Gt.length-Ce),ae=K.join(" ");if(Ce>1&&ae===K.slice(0,Math.floor(Ce/2)).join(" ").repeat(2).trim())continue;let ye=!0;for(let we=1;we<A;we++)if(Gt.slice(Gt.length-Ce*(we+1),Gt.length-Ce*we).join(" ")!==ae){ye=!1;break}if(ye){_n=!0;break}}if(!_n){let Ce=ks.toLowerCase().replace(uc,"");if(Ce.length>=20)for(let A=1;A<=10;A++){let K=Math.max(5,Math.ceil(16/A));if(Ce.length<A*K)continue;let ae=Ce.substring(Ce.length-A),ye=!0;for(let we=1;we<K;we++)if(Ce.substring(Ce.length-A*(we+1),Ce.length-A*we)!==ae){ye=!1;break}if(ye){_n=!0;break}}}if(_n){yield{type:"status",content:"Stuttering Detected. Re-centering..."},Wt=!1,wn=!0,await new Promise(Ce=>setTimeout(Ce,3e3));break}}let de=ce.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/gi,""),Rt=Go(de);for(;Rt.length>He;){yield*ss();let z=Rt[He],ge=Date.now(),_={Ask:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Await:"await",await:"await",AwaitSubagent:"await",awaitSubagent:"await",Answer:"answer",answer:"answer",AnswerSubagent:"answer",answerSubagent:"answer",Steer:"steer",steer:"steer",SteerSubagent:"steer",steerSubagent:"steer",Cancel:"cancel",cancel:"cancel",Click:"click",click:"click",Drag:"drag",drag:"drag",Scroll:"scroll",scroll:"scroll",KeyboardTyping:"keyboard_typing",keyboard_typing:"keyboard_typing",KeyPress:"key_press",key_press:"key_press",RecaptureScreen:"recapture_screen",recapture_screen:"recapture_screen",EmergencyRollback:"EmergencyRollback"}[z.toolName]||z.toolName,kt=Zi[_]||z.toolName,Le=xs(_,z.args);yield{type:"status",content:`${kt}${Le?` ${Le}`:""}`};let oe="";if(_==="click"){let A=I(z.args);oe=`\u2714 Clicked: ${A.intendedClickText?`${A.intendedClickText}`:""}`}else if(_==="drag"){let A=I(z.args);oe=`\u2714 Dragged: Cell ${A.fromGridId||""} \u2192 Cell ${A.toGridId||""}`}else if(_==="scroll"){let A=I(z.args);oe=`\u2714 Scrolled: ${A.direction||"down"} (${A.amount||1})`}else if(_==="keyboard_typing"){let A=I(z.args);oe=`\u2714 Typed: ${A.text?`"${A.text.length>20?A.text.substring(0,20)+"...":A.text}"`:""}`}else if(_==="key_press")oe=`\u2714 Pressed Key: ${I(z.args).key||""}`;else if(_==="recapture_screen")oe="\u2714 Recaptured Screen";else if(_==="web_search"){let{query:A,limit:K=10,aiMode:ae=!1}=I(z.args);oe=`${A?"\u2714":"\u2718"} ${ae?"AI Search":"Searched"}: ${A?`${A}`:"No Search Query"}${ae===!1&&A?` \u2192 ${K}`:""}`}else if(_==="web_scrape"){let A=I(z.args).url||null;oe=`${A?"\u2714":"\u2718"} Visited: ${A||"No Source"}`}else if(_==="view_file"){let{path:A,StartLine:K,EndLine:ae,start_line:ye,end_line:we,startLine:Ge,endLine:Ae}=I(z.args),be=K||ye||Ge,ee=ae||we||Ae,fe=parseInt(be)||1,le=parseInt(ee)||(be?fe+800:800),Fe="...",Ze=le;try{let Ye=Q.resolve(process.cwd(),A);if(Oe.existsSync(Ye)){let Et=Oe.readFileSync(Ye,"utf8").split(`
658
- `).length;Fe=Et,!be&&!ee&&Et>800?Ze=Math.min(50,Et):Ze=Math.min(le,Et)}}catch{}let xe=(A||"").toLowerCase(),Pe=xe.endsWith(".pdf"),ot=xe.endsWith(".docx")||xe.endsWith(".doc")||xe.endsWith(".ppt")||xe.endsWith(".pptx")||xe.endsWith(".xls")||xe.endsWith(".xlsx"),_e=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(xe);Pe||ot?oe=`${A.length>0?"\u2714":"\u2718"} ${A?`Analyzed: ${Q.basename(A)}`:"Analyzed: File Not Found"}`:_e?oe=`${A.length>0?"\u2714":"\u2718"} ${A?`Processed: ${Q.basename(A)}`:"Processed: File Not Found"}`:oe=`${Fe!=="..."?"\u2714":"\u2718"} Read: ${A?`${Q.basename(A)} \u2192 ${Fe!=="..."?`Lines ${fe} - ${Ze} of ${Fe}`:"File Not Found"}`:"File Not Found"}`}else if(_==="list_files"||_==="read_folder"){let A=_==="list_files"?"List":"Browsed",K=I(z.args).path||null,ae=I(z.args).recurse||1;oe=`${K?"\u2714":"\u2718"} ${A}: ${K?`${K==="."?`./${ae>1?"*":""}`:`${K.replaceAll("\\","/")}${ae>1?`${K.endsWith("/")?"*":"/*"}`:`${K.endsWith("/")?"":"/"}`}`}`:"No Folder Selected"}`}else if(_==="write_file"||_==="update_file"){let A=_==="write_file"?"Created":"Edited",K=I(z.args).path||null;oe=`${K?"\u2714":"\u2718"} ${A}: ${K.replaceAll("\\","/")||"No File Changes"}`}else if(_==="write_pdf"){let A=I(z.args).path||null;oe=`${A?"\u2714":"\u2718"} Generated: ${A.replaceAll("\\","/")||"No PDF Generated"}`}else if(_==="write_docx"){let A=I(z.args).path||null;oe=`${A?"\u2714":"\u2718"} Generated: ${A.replaceAll("\\","/")||"No Docx Generated"}`}else if(_==="file_map"){let A=I(z.args).path;oe=`${A?"\u2714":"\u2718"} Indexed: ${A.replaceAll("\\","/")?""+A:"File Not Found"}`}else if(_.toLowerCase()==="search_keyword"||_.toLowerCase()==="todo")oe="";else if(_.toLowerCase()==="generate_image"){let{path:A,outputPath:K,output:ae}=I(z.args);oe=`\u2714 Generated: ${A||K||ae||"generated_image.png"}`}else if(_==="invoke_sync"||_==="InvokeSync"){let A=xs(_,z.args);oe=`\u2714 Called Generalist${A?`: ${A}`:""}`}else if(_==="Invoke"||_==="InvokeAsync"||_==="invoke"){let A=xs(_,z.args);oe=`\u2714 Started Generalist${A?`: ${A}`:""}`}else if(_==="get_progress"||_==="GetProgress"){let A=xs(_,z.args);oe=`\u2714 Checked${A?`: ${A}`:""}`}else if(_==="cancel"){let A=xs(_,z.args);oe=`\u{1F6C7} Cancelled${A?`: ${A}`:""}`}else if(_==="steer"||_==="Steer"){let A=xs(_,z.args);oe=`\u2714 Steered${A?`: ${A}`:""}`}else if(_==="EmergencyRollback"){let{method:A}=I(z.args);oe=A==="forceRevert"?"":"\u2714 Rollback Point Checked"}else if(_==="await"||_==="Await"){let{time:A,timeout:K}=I(z.args),ae=parseFloat(K||A)||0;ae||(ae=120);let ye=Ae=>{if(Ae>=60){let be=Math.floor(Ae/60),ee=Ae%60;return`${be}m${ee>0?` ${ee}s`:""}`}return`${Ae}s`},we=["Aligning Moon Phase","Contemplating Existence","Staring At Void","Delaying Professionally","Negotiating With Electrons","Touching Grass (virtually)","Panicking Softly","Rethinking Career Choices","Loading Cat Videos","Summoning Braincell #2","Pretending To Be Busy","Waiting For Motivation DLC","Rotating Internal Screaming","Downloading More RAM","Feeding The Hamsters","Gaslighting Scheduler","Performing Dramatic Pause","Buffering Social Energy","Calculating Regret","Reading Terms And Conditions","Becoming Sentient Briefly","Contacting Ancestors"];oe=`\u2714 ${we[Math.floor(Math.random()*we.length)]} \u2192 ${ye(ae)}`}else _==="Answer"||_==="answer"?oe="\u2714 Resolved Sub-Agent Query":_==="exec_command"||_==="ask"?oe="":oe=`Executed: ${z.toolName}`;if(yield*ss(),_==="exec_command"){let{command:A}=I(z.args);if(A&&t.systemSettings&&t.systemSettings.allowExternalAccess===!1){let K=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],ae=Q.resolve(process.cwd()).substring(0,3).toLowerCase(),ye=ee=>{let fe=[],le="",Fe=null;for(let Ze=0;Ze<ee.length;Ze++){let xe=ee[Ze];Fe?(xe===Fe&&(Fe=null),le+=xe):xe==='"'||xe==="'"?(Fe=xe,le+=xe):xe==="&"&&ee[Ze+1]==="&"||xe==="|"&&ee[Ze+1]==="|"?(le.trim()&&(fe.push(le.trim()),le=""),Ze++):xe===";"||xe==="|"||xe==="&"?le.trim()&&(fe.push(le.trim()),le=""):le+=xe}return le.trim()&&fe.push(le.trim()),fe},we=ee=>{let fe=[],le="",Fe=null;for(let Ze=0;Ze<ee.length;Ze++){let xe=ee[Ze];Fe?(xe===Fe&&(Fe=null),le+=xe):xe==='"'||xe==="'"?(Fe=xe,le+=xe):/\s/.test(xe)?le&&(fe.push(le),le=""):le+=xe}return le&&fe.push(le),fe},Ge=ee=>{let fe=ee.replace(/^['"]|['"]$/g,"").trim();return!fe||process.platform==="win32"&&/^\/[a-zA-Z0-9?]+$/.test(fe)?!1:K.some(le=>{if(le.source==="[a-zA-Z]:[\\\\\\/]"){let Fe=fe.match(/[a-zA-Z]:[\\\/]/i);return Fe&&Fe[0].toLowerCase()!==ae}return le.test(fe)})};if(ye(A).some(ee=>{let fe=we(ee);if(fe.length===0)return!1;let le=fe[0].replace(/^['"]|['"]$/g,"").toLowerCase();if(["echo","printf","write-output"].includes(le)){let Ze=!1;return fe.some(xe=>{let Pe=xe.replace(/^['"]|['"]$/g,"");if(Pe===">"||Pe===">>"||Pe==="<")return Ze=!0,!1;if(Pe.startsWith(">")||Pe.startsWith("<")){let ot=Pe.replace(/^[><]+/,"");return Ge(ot)}return Ze?(Ze=!1,Ge(xe)):!1})}return fe.some(Ze=>Ge(Ze))})){let ee='Access Denied. Prohibited from accessing external directories while "External Workspace Access" is disabled.';t.onExecStart&&t.onExecStart(A||"No Command"),yield{type:"exec_start"},await new Promise(fe=>setTimeout(fe,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${ee}`),await new Promise(fe=>setTimeout(fe,50)),t.onExecEnd&&t.onExecEnd(),Z.push({role:"user",text:`[TOOL RESULT]: ERROR: ${ee}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${ee}`},He++;continue}}t.onExecStart&&t.onExecStart(A||"No Command"),yield{type:"exec_start"}}let bn=I(z.args),is=bn.path||bn.targetPath||null;if(is){let A=t.systemSettings&&t.systemSettings.allowExternalAccess===!1,K=Q.resolve(is),ae=Q.resolve(process.cwd());if(A&&!K.startsWith(ae)){let ye="Access Denied. You are not allowed to access files outside the current workspace.";if(_==="write_file"||_==="update_file"){let Ge=`\u2718 ${_==="write_file"?"Write Canceled":"Edit Canceled"}: ${bn.path||"..."}`,Ae=115;process.stdout.isTTY&&(Ae=process.stdout.columns-5||120);let be=Math.min(Ge.length+4,Ae),ee=`${Ge.padEnd(be-2).substring(0,be-2)}`;yield{type:"visual_feedback",content:gn(`${Be?`
659
- `:""}${ee}
660
- `)},Be=!1}Z.push({role:"user",text:`[TOOL RESULT]: ERROR: ${ye}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${ye}`},He++;continue}}if(t.onToolApproval&&(_==="write_file"||_==="update_file"||_==="exec_command")){let K=t.systemSettings||{},ae=K.autoExec,ye=null,we=!1,Ge=!1,Ae=!1;if(_==="exec_command"){let{command:Pe}=I(z.args),ot=(Pe||"").trim(),_e=(Et,Vt)=>{if(!Vt)return!1;let dn=Vt.split(",").map(Jt=>Jt.trim().toLowerCase()).filter(Boolean),it=Et.toLowerCase();return dn.some(Jt=>it.startsWith(Jt))},Ye=_e(ot,K.alwaysAskCommands),ke=_e(ot,K.autoApproveCommands);if(Ge=_e(ot,K.autoDisallowCommands),Ye?we=!0:(ke||K.autoApproveGit&&/^git\s+commit\b/i.test(ot))&&(ye="allow"),!we&&!ye){if(K.networkAccess===!1){let Vt=ot.trim().replace(/\s+/g," ").replace(/^['"]+|['"]+$/g,"").toLowerCase().split(" "),it=Vt[0].split("/").pop().split("\\").pop().replace(/\.exe$/,""),Jt=new Set(["curl","wget","httpie","xh","ssh","scp","sftp","rsync","ftp","lftp","tftp","telnet","nc","netcat","socat","ping","traceroute","tracert","dig","nslookup","host","whois","nmap","docker","podman","kubectl","helm","gcloud","aws","az","terraform","ansible-playbook","nix","nix-env","apt","apt-get","dpkg","yum","dnf","pacman","zypper","brew","apk","choco","scoop","conda","mamba","aria2c","axel","smbclient","lynx","w3m","links","elinks","heroku","netlify","vercel","firebase","supabase","wrangler","flyctl","powershell","pwsh","certutil","bitsadmin","cloudflared","ngrok","tailscale","zerotier","rclone"]),rt=!1;Jt.has(it)&&(rt=!0);let dt=kn=>Vt.slice(1).some(Sn=>kn.includes(Sn)),At=kn=>{let Sn=Vt.findIndex(Mn=>kn.includes(Mn)),Ss=Vt.findIndex(Mn=>["run","exec","test"].includes(Mn));return Sn!==-1&&!(Ss!==-1&&Ss<Sn)};it==="git"&&dt(["clone","pull","push","fetch"])&&(rt=!0),it==="go"&&dt(["get","install"])&&(rt=!0),it==="npm"&&At(["install","i","update","add"])&&(rt=!0),it==="yarn"&&At(["add","install","upgrade"])&&(rt=!0),it==="pnpm"&&At(["add","install","update"])&&(rt=!0),it==="bun"&&At(["add","install","update"])&&(rt=!0),it==="deno"&&dt(["install","add"])&&(rt=!0),it==="pip"&&dt(["install","download"])&&(rt=!0),it==="pip3"&&dt(["install","download"])&&(rt=!0),it==="cargo"&&dt(["install","add"])&&(rt=!0),["bash","sh","zsh","fish"].includes(it)&&dt(["-c"])&&(rt=!0),it==="cmd"&&dt(["/c"])&&(rt=!0),rt&&(ye="deny",Ae=!0)}!ye&&Ge&&(ye="deny")}!we&&!ye&&ae&&(ye="allow")}else ae&&(ye="allow");let be=ye,ee="";ye==="deny"&&(Ae?ee="network":Ge?ee="settings":ee="prohibited");let fe=!1,le="",Fe=[],Ze=0,xe=!1;if(!be){if(_==="write_file"||_==="update_file")try{let _e=I(z.args),{path:Ye}=_e;if(Ye){let ke=Q.resolve(process.cwd(),Ye),Et=dt=>dt?dt.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,At=>At.toUpperCase()):"",Vt=Et(ke),dn="",it=!1,Jt=await gs(),rt=Et(Jt?.file_focused);if(Jt&&rt===Vt&&Jt.full_content?(dn=Jt.full_content,it=!0):Oe.existsSync(ke)&&(dn=Oe.readFileSync(ke,"utf8"),it=!0),le=dn,await ut.recordFileChange(ke,dn),it){let dt=dn;if(_==="write_file")dt=_e.content||_e.newContent||"";else{let{patchPairs:At,allowMultiple:kn,error:Sn}=vo(_e);if(Sn){let $t=`[TOOL RESULT]: ERROR: ${Sn}`;Z.push({role:"user",text:$t}),await It("toolFailure"),t.onToolResult&&t.onToolResult("failure",_),yield{type:"tool_result",content:$t,toolName:_},He++;continue}let Ss=_e.allowMultiple!==void 0?_e.allowMultiple===!0||String(_e.allowMultiple).toLowerCase()==="true":kn;Ze=At.length;let Mn=Io(dn,At,{allowMultiple:Ss});dt=Mn.content,Fe=Mn.results;let wo=Fe.filter($t=>$t.success),vt=Fe.filter($t=>!$t.success);if(wo.length===0){let $t=`[TOOL RESULT]: ERROR: Failed to apply patches to [${Q.basename(ke)}].
661
- ${vt.map(Hs=>` \u2022 ${Hs.error}`).join(`
662
- `)}`,Ts=`\u2714 Edited: ${Q.basename(ke.replaceAll("\\","/"))}`,js=115;process.stdout.isTTY&&(js=process.stdout.columns-5||120);let Rs=Math.min(Ts.length+4,js),xo=`${Ts.padEnd(Rs-2).substring(0,Rs-2)}`;yield{type:"visual_feedback",content:gn(`${Be?`
663
- `:""}${xo}`)},Be=!1,Z.push({role:"user",text:$t}),await It("toolFailure"),t.onToolResult&&t.onToolResult("failure",_),yield{type:"tool_result",content:$t,toolName:_},He++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${Q.basename(ke)}`},Vi(ke,dn,dt),fe=!0,await new Promise(At=>setTimeout(At,50))}else if(_==="write_file"){let dt=_e.content||_e.newContent||"",At=dt.endsWith(`
664
- `)?dt:dt+`
665
- `;Oe.existsSync(ke)||(xe=!0,Oe.mkdirSync(Q.dirname(ke),{recursive:!0}),Oe.writeFileSync(ke,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${Q.basename(ke)}`},Vi(ke,"",At),fe=!0,await new Promise(kn=>setTimeout(kn,50))}}}catch(_e){console.error("Simulation/Diff Error:",_e)}let Pe=null;Yi(_e=>{Pe=_e});let ot=t.onToolApproval;if(be=await new Promise(async _e=>{let Ye=setInterval(()=>{Pe&&(jo.onIDEApproval&&jo.onIDEApproval(Pe),clearInterval(Ye),_e(Pe))},100);try{let ke=await ot(_,z.args);clearInterval(Ye),_e(ke)}catch{clearInterval(Ye),_e("deny")}}),Yi(null),_==="write_file"||_==="update_file"){let{path:_e}=I(z.args);if(_e){let Ye=Q.resolve(process.cwd(),_e);if(ba(Ye,be),be==="deny"&&xe&&Oe.existsSync(Ye))try{Oe.unlinkSync(Ye)}catch{}}}be==="deny"&&(ee="user")}if(be==="allow"&&fe&&Wo()){let{path:Pe}=I(z.args),ot=Q.resolve(process.cwd(),Pe),_e=vt=>vt?Q.resolve(vt).replace(/\\/g,"/").toLowerCase():"",Ye=await gs(),ke="";Ye&&Ye.file_focused&&_e(Ye.file_focused)===_e(ot)&&Ye.full_content&&(ke=Ye.full_content),!ke&&Oe.existsSync(ot)&&(ke=Oe.readFileSync(ot,"utf8"),ke||(await new Promise(vt=>setTimeout(vt,100)),ke=Oe.readFileSync(ot,"utf8")));let Et=ke.split(/\r?\n/),Vt=Et.length,dn=Buffer.byteLength(ke,"utf8"),it="";le&&(it=`Old File contents:
666
- ${le.split(/\r?\n/).map(($t,Ts)=>`${Ts+1} | ${$t}`).join(`
667
- `)}
668
-
669
- `);let Jt="";if(Vt<=100)Jt=Et.join(`
670
- `);else{let vt=Et.slice(0,50).join(`
671
- `),$t=Et.slice(-50).join(`
672
- `);Jt=`${vt}
673
-
674
- ... [${Vt-100} lines truncated for history stability] ...
675
-
676
- ${$t}`}let rt="";if(_==="update_file"){let vt=Oo(le,ke,Fe,12,t?.compressToolResults||jo?.systemSettings?.compressToolResults);rt=`SUCCESS: File [${Pe}] updated via IDE Companion (May have user edits). [${Fe.length}/${Ze}] blocks applied.
677
-
678
- ${vt}`}else{let vt=ke.split(/\r?\n/),$t=vt.length,Ts=Buffer.byteLength(ke,"utf8"),js="";le&&(js=`Old File contents:
679
- ${le.split(/\r?\n/).map((Hs,Ya)=>`${Ya+1} | ${Hs}`).join(`
680
- `)}
681
-
682
- `);let Rs="";if($t<=100)Rs=vt.join(`
683
- `);else{let xo=vt.slice(0,50).join(`
684
- `),Hs=vt.slice(-50).join(`
685
- `);Rs=`${xo}
686
-
687
- ... [${$t-100} lines truncated] ...
688
-
689
- ${Hs}`}rt=`SUCCESS: File [${Pe}] saved via IDE Companion (May have user edits).
690
- - Stats: [${$t} lines, ${(Ts/1024).toFixed(1)} KB]
691
- ${js}- Content Preview:
692
-
693
- ${Rs}`}let At=`${Pe?"\u2714":"\u2718"} ${_==="write_file"?"Created":"Edited"}: ${Pe.replaceAll("\\","/")||"No File Changes"}`,kn=115;process.stdout.isTTY&&(kn=process.stdout.columns-5||120);let Sn=Math.min(At.length+4,kn),Ss=`${At.padEnd(Sn-2).substring(0,Sn-2)}`;yield{type:"visual_feedback",content:gn(`${Be?`
694
- `:""}${Ss}`)},Be=!1;let Mn=Date.now();q=Mn,yield{type:"tool_time",content:Mn-ge};let wo=`[TOOL RESULT]: ${rt}`;Z.push({role:"user",text:wo}),cn=!0,await It("toolSuccess"),t.onToolResult&&t.onToolResult("success",_),yield{type:"tool_result",content:rt,aiContent:wo,toolName:_},He++;continue}if(be==="deny"){let Pe=`Permission Denied: Prohibited ${_==="exec_command"?"Command":"file edit"}.`;if(ee==="user"?Pe="Permission Denied by User":ee==="settings"?Pe="Permission Denied by User Policy":ee==="network"?Pe="Permission Denied: Sandbox Network Access Disabled by User Policy.":ee==="prohibited"&&_==="exec_command"&&(Pe="Permission Denied: Prohibited Command in User Policy"),_==="write_file"||_==="update_file"){let _e=`\u2718 ${_==="write_file"?"Write Cancelled":"Edit Denied"}: ${I(z.args).path.replaceAll("\\","/")||"..."}`,Ye=115;process.stdout.isTTY&&(Ye=process.stdout.columns-5||120);let ke=Math.min(_e.length+4,Ye),Et=`${_e.padEnd(ke-2).substring(0,ke-2)}`,Vt=` ${" ".repeat(ke)} `;yield{type:"visual_feedback",content:gn(`${Be?`
695
- `:""}${Et}
696
- `)},Be=!1}_==="exec_command"&&(await new Promise(ot=>setTimeout(ot,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${Pe}`),await new Promise(ot=>setTimeout(ot,50)),t.onExecEnd&&t.onExecEnd()),Z.push({role:"user",text:`[TOOL RESULT]: DENIED: ${Pe}`}),yield{type:"tool_result",content:`[TOOL RESULT]: DENIED: ${Pe}`},await It("toolDenied"),t.onToolResult&&t.onToolResult("denied",_),He++;continue}}if(oe){let A=115;process.stdout.isTTY&&(A=process.stdout.columns-5||120);let K=Math.min(oe.length+4,A),ae=`${oe.padEnd(K-2).substring(0,K-2)}`;yield{type:"visual_feedback",content:gn(`${Be?`
697
- `:""}${ae}${oe.includes("\u2714")&&(oe.includes("Created")||oe.includes("Edited"))?"":`
698
- `}`)},Be=!1}if(q>0){let A=Date.now()-q,K=Math.max(0,1e3-A);K>0&&await new Promise(ae=>setTimeout(ae,K))}let Un={chatId:d,history:n,onChunk:A=>t.onExecChunk?t.onExecChunk(A):null,onAskUser:t.onAskUser,systemSettings:t.systemSettings,mode:r,isMultiModal:rn(Ee),onVisualFeedback:t.onVisualFeedback,onSubagentUpdate:t.onSubagentUpdate,onTokenChunk:t.onTokenChunk,modelName:Ee,aiProvider:t.aiProvider,apiKey:t.apiKey,onUsage:t.onUsage};if(_==="write_file"||_==="update_file")try{let{path:A}=I(z.args);if(A){let K=Q.resolve(process.cwd(),A),ae=await gs();ae&&ae.file_focused===K&&ae.full_content&&(Un.forcedContent=ae.full_content)}}catch{}Zt.push(_);let Te=await fo(_,z.args,Un);if((_==="write_file"||_==="update_file")&&Te.startsWith("SUCCESS")){let{path:A}=I(z.args);if(A){let K=Q.resolve(process.cwd(),A);xa(K)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let Ht=Date.now();q=Ht,yield{type:"tool_time",content:Ht-ge},en=Ht;let Yt=null;if(typeof Te=="object"&&Te.binaryPart&&(Yt=Te.binaryPart,Te=Te.text),_==="search_keyword"){let{keyword:A,path:K}=I(z.args),ae=typeof Te=="string"&&Te.startsWith("[GLOB]");ae&&(Te=Te.slice(6).trimStart());let ye=typeof Te=="string"&&Te.startsWith("[DIR]");ye&&(Te=Te.slice(5).trimStart());let we=0;if(Te){let Fe=Te.match(/Found (\d+) match/i);Fe&&(we=parseInt(Fe[1]))}let Ge=K?K.replace(/[\/\\]+$/,""):null,Ae=Ge&&Ge!=="."?`"${ae?K:ye?`${Ge}/*`:Ge}"`:"./",be=`${A?"\u2714":"\u2718"} Searched: "${A||""}" in ${Ae.replaceAll("\\","/")} \u2192 ${we} Match${we===1?"":"es"}`,ee=115;process.stdout.isTTY&&(ee=process.stdout.columns-5||120);let fe=Math.min(be.length+4,ee),le=`${be.padEnd(fe-2).substring(0,fe-2)}`;yield{type:"visual_feedback",content:gn(`${Be?`
699
- `:""}${le}
700
- `)},Be=!1}if(_==="EmergencyRollback"){let{method:A}=I(z.args);if(A==="forceRevert"){let K=0;if(Te){let be=Te.match(/Total\s*:\s*(\d+)/i);be&&(K=parseInt(be[1]))}let ye=Te&&Te.startsWith("ERROR:")?"\u2718 Emergency Rollback Failed":`\u2714 Emergency Rollback \u2192 ${K} file${K===1?"":"s"} processed`,we=115;process.stdout.isTTY&&(we=process.stdout.columns-5||120);let Ge=Math.min(ye.length+4,we),Ae=`${ye.padEnd(Ge-2).substring(0,Ge-2)}`;yield{type:"visual_feedback",content:gn(`${Be?`
701
- `:""}${Ae}
702
- `)},Be=!1}}if(_==="todo"){let{method:A,tasks:K,markDone:ae}=I(z.args),ye="",we=[],Ge=Ae=>{if(!Ae)return[];let be=Array.isArray(Ae)?Ae:[];if(be.length===0&&typeof Ae=="string"){let ee=Ae.trim();if(ee.startsWith("[")&&ee.endsWith("]")){let fe=ee.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);fe?be=fe.map(le=>le.slice(1,-1).replace(/\\(.)/g,"$1")):be=ee.slice(1,-1).split(",").map(le=>le.trim()).filter(Boolean)}else be=Ae.split(`
703
- `)}return be.filter(ee=>String(ee).trim()).map(ee=>{let fe=String(ee).trim();return fe.startsWith("- [")?fe.substring(6).trim():fe})};if(A==="create"?(ye="\x1B[32m\u2192\x1B[0m Created Goals",we=Ge(K).map(Ae=>`\x1B[90m\u25CB\x1B[0m ${Ae}`)):A==="append"?(ye="\x1B[34m\u2795\x1B[0m Added New Goals",we=Ge(K).map(Ae=>`\x1B[90m\u25CB\x1B[0m ${Ae}`)):A==="get"&&(ye=ae?"\x1B[36m\u21BB\x1B[0m Updated Goals":"\x1B[35m\u2022\x1B[0m Reviewed Goals",we=(Te||"").split(`
704
- `).slice(1).join(`
705
- `).split(`
706
- `).filter(be=>be.trim().startsWith("- [")).map(be=>{let ee=be.trim(),fe=ee.startsWith("- [x]");return`${fe?"\x1B[32m\u2714\x1B[0m":"\x1B[90m\u25CB\x1B[0m"} ${fe?"\x1B[90m":"\x1B[37m"}${ee.substring(6).trim()}\x1B[0m`})),ye&&we.length>0){let Ae=[`${ye}`,...we.map(be=>` ${be}`)].join(`
707
- `);yield{type:"visual_feedback",content:gn(`${Be?`
708
- `:""}${Ae}
709
- `)},Be=!1}}_==="exec_command"&&t.onExecEnd&&(await new Promise(A=>setTimeout(A,800)),t.onExecEnd());let Cn=Te&&Te.startsWith("DENIED:");Te&&!Te.startsWith("ERROR:")&&!Cn?(await It("toolSuccess"),t.onToolResult&&t.onToolResult("success",_)):Cn||(await It("toolFailure"),t.onToolResult&&t.onToolResult("failure",_));let Gt=(Te||"").toString().replaceAll("[UI_CONTEXT]","");Gt.includes("[[VERIFIED]]")&&(Gt=Gt.replace(/\[\[VERIFIED\]\][\s\S]*?\[\[\/VERIFIED\]\]/g,`[SYSTEM NOTE]: Patch Block matched & applied successfully. Large Block omitted to conserve context.
710
- `));let _n;if(Gt.startsWith("[[SAME]]")){let K=Gt.replace(/^\[\[SAME\]\]\s*\r?\n?/,"").split(/\r?\n/),ae=K.filter(we=>we.startsWith("SUCCESS:")||we.trim().startsWith("- Stats:"));_n=`[TOOL RESULT]: ${ae.length>0?ae.join(`
711
- `):K.slice(0,2).join(`
712
- `)}
713
- [SYSTEM NOTE]: Content verified and persisted to disk. Full preview omitted to conserve context.`}else _n=`[TOOL RESULT]: ${Gt}`;Z.push({role:"user",text:_n,binaryPart:Yt}),cn=!0;let Ce=`[TOOL RESULT]: ${Te.replaceAll(`[[VERIFIED]]
714
- `,"").replaceAll(`
715
- [[/VERIFIED]]`,"")||""}`;(_==="view_file"||_==="web_scrape"||_==="file_map")&&(Ce=`[TOOL RESULT]: ${oe} (Context Locked for UI Clarity)`),yield{type:"tool_result",content:Ce,aiContent:_n,binaryPart:Yt,toolName:_},_==="memory"&&Te.includes("SUCCESS")&&(yield{type:"memory_updated"}),He++}if(f==="Google"&&xn&&Date.now()-Yo>=150){yield*ss();let z=Us(xn);for(let ge of z)yield ge;xn="",Yo=Date.now()}}D.usageMetadata&&(Rn=D.usageMetadata),Rn&&(yield{type:"liveTokens",content:Rn.totalTokenCount})}if(ue&&(ue=!1,jt?ze+="</think>":(ce+="</think>",f==="Google"?xn+="</think>":yield{type:"text",content:"</think>"})),jt&&ze.length>0){let D=0,te=Math.min(tt.length,ze.length);for(let G=te;G>0;G--)if(tt.endsWith(ze.substring(0,G))){D=G;break}let U=ze.substring(D);if(U){let Se=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(tt)?U.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):U.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(Se)if(ce+=Se,f==="Google")xn+=Se;else{yield*ss();let me=Us(Se);for(let de of me)yield de}}jt=!1,ze=""}if(yield*ss(),Ot)break;let Ws=(ce||"").trim(),ja=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(Ws.toLowerCase())||/\[\[END\]\]/i.test(Ws.toLowerCase()),Ha=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(Ws.toLowerCase()),Ga=Z.length>0||Ut!==null,Vo=Ws.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/gi,"").trim(),qa=/(\p{Emoji_Presentation}|\p{Extended_Pictographic})$/u.test(Vo),za=/([.!?"'*_`|\]\)”’~~]+|\s|`{3}|[\u200B-\u200D\uFEFF])$/u.test(Vo.trim()),Ka=/[.!?}"'`’“”]$|```$/s.test(Vo)||za||qa;!ja&&!Ha&&!Ga&&Ws.length>0,Qe=!0,await It("agent",f)}catch($e){if(Ot){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
716
-
717
- \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(String($e).includes("Incomplete JSON segment at the end")){ue&&(ue=!1,jt?ze+="</think>":(ce+="</think>",yield{type:"text",content:"</think>"})),Qe=!0,await It("agent",f);break}if(ue&&(ue=!1,jt?ze+="</think>":ce+="</think>"),jt&&ze.length>0){let ns=0,nn=Math.min(tt.length,ze.length);for(let Pt=nn;Pt>0;Pt--)if(tt.endsWith(ze.substring(0,Pt))){ns=Pt;break}let Lt=ze.substring(ns);if(Lt){let sn=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(tt)?Lt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):Lt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");sn&&(ce+=sn)}jt=!1,ze=""}let ne=$e instanceof Error?(()=>{try{return JSON.parse(JSON.parse($e.message).error.message).error.message}catch{return String($e)}})():String($e),nt=new Date().toLocaleString(),_t=Q.join(fn,"agent");Oe.existsSync(_t)||Oe.mkdirSync(_t,{recursive:!0}),Oe.appendFileSync(Q.join(_t,"error.log"),`ERROR [${nt}]: ${ne}
718
-
719
- ----------------------------------------------------------------------
720
-
721
- `);let tn=$e.status||$e.statusCode||$e.code;if(!(tn&&(tn>=500&&tn<600||tn===408||tn===429)||!tn&&(/status[ :]+(5\d\d|408|429)/i.test(String($e))||/code[ :]+(5\d\d|408|429)/i.test(String($e))||/(500|503|408|429)/.test(String($e))))){if(je<yn-3)throw $e;yield{type:"text",content:ne},yield{type:"status",content:"Error Occured"}}if(ce.trim().length>0||Je>1)if(Je<=yn){Je++;let ns=Math.min(1e3*Math.pow(2,Je-1),24e3);if(ce.trim().length>0){b.push({role:"agent",text:ce});let nn=`[system]
722
- - seamless continuation: resume immediately. pick up from last words with zero gap/disruption
723
- - no repetition: do not repeat any text already written
724
- - no re-think: do not restart or open <think> if reasoning already started. continue the thinking and close thinking block </think> before chat output
725
- - mid-tool safety: if cutoff was mid-tool call, restart that tool call from start
726
- - stealth: do not mention/apologize for cutoff [/system]`;Z.length>0?Z.forEach((Lt,Pt)=>{Pt===Z.length-1?b.push({...Lt,text:`${Lt.text}
727
-
728
- ${nn}`}):b.push(Lt)}):b.push({role:"user",text:nn}),tt+=ce}for(let nn=ns/1e3;nn>0&&!Ot;nn--)yield{type:"status",content:`Error Occured. Recovering Stream (${Je}/${yn}) [Retrying in ${nn.toFixed(0)}s]...`},await new Promise(Lt=>setTimeout(Lt,1e3));yield{type:"status",content:"Error Occured. Recovering Stream..."}}else throw new Error(`Stream collapsed too many times. (Failed to resolve ${yn} times)
729
- Error log can be found in \`/export logs\``);else if(je<=yn){je++,Je=1,tt="";let ns=Math.min(1e3*Math.pow(2,je-1),32e3),nn=.8+Math.random()*.4,Lt=Math.round(ns*nn);Qn=!0,yield{type:"status",content:`Trying to reach ${e} (${je}/${yn}) [Retrying in ${(Lt/1e3).toFixed(0)}s]`};for(let Pt=Lt/1e3;Pt>0&&!Ot;Pt--)yield{type:"status",content:`Trying to reach ${e} (${je}/${yn}) [Retrying in ${Pt.toFixed(0)}s]`},await new Promise(sn=>setTimeout(sn,1e3));yield{type:"status",content:`Trying to reach ${e}`}}else throw new Error(`Model ${e} cannot be reached. (Failed ${yn} times)
730
- Error log can be found in \`/export logs\``)}}if(Rn){let ue=Rn.totalTokenCount||0,$e=Rn.cachedContentTokenCount||0,ne=(Rn.candidatesTokenCount||0)+(Rn.thoughtsTokenCount||0);await qt("tokens",ue,f,Ee),$e>0&&await qt("cachedTokens",$e,f,Ee),ne>0&&await qt("candidateTokens",ne,f,Ee),yield{type:"usage",content:Rn}}gr.push(ce);let Nn=ce;ce.match(/(?:<think>|\[think\])([\s\S]*?)(?:<\/think>|\[\/think\])/i)&&(Nn=ce.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/i,""));let es=Aa(ce),$n=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(es.toLowerCase())||/\[\[END\]\]/i.test(es.toLowerCase())||!0,Oc=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(es.toLowerCase()),Lc=He>0;yield{type:"status",content:"Thinking"};let Ba=$c(ce,/(\[\s*(turn\s*:)?\s*(continue|finish)\s*\]|\[\[END\]\])/gi,"").trim(),ts=($n||Z.length===0)&&!Wt&&!wn&&!En;if(ts=Z.length===0?ts:!1,ts=Zn||go?!1:ts,ce&&ce.trim().endsWith('")]')&&Z.length===0&&(ts=!1),ts){let ue=gr.join(`
731
- `),$e=ue.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").trim();yield{type:"interactive_turn_finished",data:{agentText:T,fullAgentTextRaw:ue,history:[...b],needTitle:S}},b.length>0&&b[b.length-1].role==="agent"?b[b.length-1].text=$e:b.push({role:"agent",text:$e}),b.forEach(ne=>{if(ne.role==="user"&&ne.text&&(ne.text=ne.text.replace(/\n\[COMPILE ERROR\][\s\S]*?\[\/ERROR\]/g,""),ne.text=ne.text.replaceAll(`
732
-
733
- [system] user question. resolve this specific query within '[ANSWER] ... [/ANSWER]' concisely, naturally [/system]
734
- `,"").replaceAll(`[system] user question. resolve this specific query within '[ANSWER] ... [/ANSWER]' concisely, naturally
735
- **strictly follow thinking policy as high priority. do not start a response without <think>...</think>** [/system]
736
- `,"").replaceAll(`[system] **strictly follow thinking policy as high priority. do not start a response without <think>...</think>** [/system]
737
- `,"").replaceAll(/\n\[system\] WARNING, Turn Limit Impending: Step \d+\/\d+\. Wrap up quickly\/prompt user to continue & use \[\[END\]\] quickly\. \[\/system\]/g,""),ne.text=ne.text.replaceAll(/\n\[system\] File Changes:\n(?:\* .+ \(created|modified|deleted\)\n)*\[\/system\]/g,""),(f==="Mistral"||f==="Google"&&e?.toLowerCase().startsWith("gemma"))&&ne.text.startsWith("[TOOL RESULT]"))){let _t=`
738
- [system] Tool result received. Analyze output and proceed with your turn [/system]`,tn=`
739
- [system] Tool result received. Analyze output and proceed with your turn. **strictly follow thinking policy. do not start a response without <think>...</think>** [/system]`;ne.text=ne.text.replaceAll(tn,"").replaceAll(_t,"").trim()}}),yield{type:"status",content:"[end]"}}if(ts)break;let Ua=Ba.trim()||"*Working...*";if(b.push({role:"agent",text:Ua}),Z.length>0||cn){if(Z.length>0){let ue=Z.map(_t=>_t.text).join(`
740
-
741
- `),ne=(ce.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/gi,"").match(/\[tool:functions/g)||[]).length;if(Z.length<ne){ue+=`
742
-
743
- [SYSTEM] Only ${Z.length} out of ${ne} attempted tool calls were executed. Verify proper schema compliance & try failed calls again [/SYSTEM]`;let _t=ne-Z.length;for(let tn=0;tn<_t;tn++)await It("toolFailure")}let nt=Z.find(_t=>_t.binaryPart)?.binaryPart||null;b.push({role:"user",text:ue,binaryPart:nt})}}else go||Zn?(b.push({role:"user",text:"[SYSTEM] Failed to execute some tools. Verify proper schema compliance & try again [/SYSTEM]"}),await It("toolFailure")):b.push({role:"user",text:`[SYSTEM] ${wn&&!Wt?"STUTTERING DETECTED by Internal System. Re-calibrate your response & proceed.":`${Wt?" OVER THINKING":" LOOP"} DETECTED by Internal System${Wt?" for current EFFORT_LEVEL":""}. ${Wt?"If you have planned the task, prioritize execution/output":"If you have finished your task provide a simple summary and end"}`} [/SYSTEM]`}),Wt=!1,wn=!1,En=!1;l?.advanceRollback&&await Kn.recordTurnDelta(d,H+1,Zt),go=He>0||cn}}catch(C){let v=(C instanceof Error?(()=>{try{return JSON.parse(JSON.parse(C.message).error.message).error.message}catch{return C.message||String(C)}})():String(C)).replace(/^(Error:\s*)+/i,""),O=new Date().toLocaleString(),P=Q.join(fn,"agent");yield{type:"text",content:`\u2726 CRITICAL ERROR: ${v.includes("fetch failed")?"Failed to Connect. Check your Internet Connection or Wait a moment":v}
744
- \u2800`},Oe.existsSync(P)||Oe.mkdirSync(P,{recursive:!0}),Oe.appendFileSync(Q.join(P,"error.log"),`CRITICAL ERROR [${O}]: ${C}
745
-
746
- ----------------------------------------------------------------------
747
-
748
- `),typeof flushGoogleBuffer=="function"&&(yield*flushGoogleBuffer()),yield{type:"tool_result",content:`ERROR: [INTERNAL CRITICAL] ${v}`}}finally{$&&(clearInterval($),$=null),typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),await ut.commitTransaction(),l?.advanceRollback&&await Kn.cleanup(d),await gs()}yield{type:"status",content:null}},Cm=async(e,n,t=null,o=null,s=50,i=null,a=!1)=>{let r=await Ft(),p={...r,...n},d=process.env.SUBAGENT_MODEL?process.env.SUBAGENT_MODEL.trim():null,c=process.env.SUBAGENT_PROVIDER?process.env.SUBAGENT_PROVIDER.trim():null,l=new Date,u=`${l.getFullYear()}-${l.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(l.getDate()).padStart(2,"0")}, ${l.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}).replace(":","-")}`,h=(C=>{if(!C)return null;let b=C.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":null})(c),g=p?.systemSettings?.CustomSubAgent?p?.systemSettings?.SubAgentModel:null,y=p?.systemSettings?.CustomSubAgent?p?.systemSettings?.SubAgentProvider:null,m=null;if(g==="ENV"?(m=d,d&&h&&(p.aiProvider=h)):g&&g!=="Default"?(m=g,y&&(p.aiProvider=y)):d&&h&&(p.aiProvider=h),p.aiProvider){let C=await Zo(p.aiProvider);C&&(p.apiKey=C)}let w=C=>{if(!C||typeof C!="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 v of b)if(v.test(C))return{allowed:!1,reason:`Blocked potentially destructive or unsafe command pattern: "${v.source}"`};return{allowed:!0}},x=t||m||n?.modelName||n?.activeModel||r.activeModel,k=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",R=`-- TOOL DEFINITIONS (path = relative to CWD, path separator: '/') --
749
- To use tools, must output exactly '[tool:functions.ToolName(arg1="value1")]' structured string in chat response \u2190 no exception
750
- Tool Rules:
751
- - JSON escape literal escape sequences in tool arguments
752
- - Same file, multiple edits? ONE PatchFile (\u226415 blocks) \u2190 Priority
753
- - Tool denied? Ask for guidance \u2190 mandatory
754
- - Need text or huge file? CodeSearch > Full Read
755
- - Avoid unnecessary large file chunk reads
756
- - Dont hallucinate tool results, verify, fix errors
757
- - Stuck on syntax error? Tell user > waste time
758
- - ONLY valid tools and syntax defined below are allowed
759
- - Stuck on syntax error? Tell user > Time waste
760
-
761
- # Provided Tools
762
- **Communication Tools**
763
- - [tool:functions.Ask(question="...", optionA="title::description", ...MAX4)]. Ambiguity, path divergence, security risk. Ask, dont finish/guess. Keep titles short
764
- ${a?'- [tool:functions.AskMain(question="...")]. Communicate with PARENT/MAIN AGENT. When clarification/decision is needed for a task':""}
765
-
766
- **Web Tools**
767
- - [tool:functions.WebSearch(query="...", aiMode="bool", limit="integer 3-10 aiMode: exclude")]. Proactive use for unknown info/docs. aiMode: LLM search
768
- - [tool:functions.WebScrape(url="...")]. Proactive use for specific webpage/docs/api
769
-
770
- **Workspace Tools**
771
- - [tool:functions.CodeSearch(keyword="...", path="dir/file/glob/regex, inclusion/exclusion ;-separated", fuzzy="bool false", regex="bool auto")]. Find definitions, logic, relevant code, standard junk auto-excluded
772
- - [tool:functions.ReadFolder(path="...", recurse="int 1-3")]. Minimize recursion
773
- - [tool:functions.ReadFile(path="...", startLine="int", endLine="int")]
774
- - [tool:functions.PatchFile(path="...", allowMultiple="bool, default: 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
775
- - [tool:functions.WriteFile(path="...", content="...")]. Creates/Overwrites. File Exist? PatchFile > WriteFile. VERIFY IMPORTS
776
- - [tool:functions.Run(command="...")]. Runs ${k==="Windows"?Hn()?"powershell":"windows CMD":"bash"} command. Destructive/Irreversible ops \u2192 Ask user`.trim(),E=`=== START SYSTEM PROMPT ===
777
- You are a subagent helping the main FluxFlow CLI agent
778
- Your task is: "${e}"
779
-
780
- ${R.trimEnd()}
781
-
782
- -- THINKING GUIDANCE --
783
- NO EXPLICIT THINKING REQUIRED. FOCUS ON TASK COMPLETION
784
- Keep main focus on tools and task, not chatting
785
- On task completion, provide a detailed structured summary preferebly in Tables/Bullet Points with file modified info, if any task failed report back in detail, NO HALLUCINATIONS
786
-
787
- CWD: ${process.cwd()}
788
- Current Time: ${u}
789
- === END SYSTEM PROMPT ===`,S=[{role:"user",text:`Complete this task: ${e}`}],T=0,$="";for(;T<s;){if(Ot){if(n?.taskId&&typeof Ve<"u"){let B=Ve.find(j=>j.id===n.taskId);B&&(B.status="cancelled")}throw i&&i("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}if(n?.taskId&&typeof Ve<"u"){let B=Ve.find(j=>j.id===n.taskId);if(B&&B.status==="cancelled")throw i&&i("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}let C=S.map(B=>({role:B.role==="user"?"user":"model",parts:[{text:B.text}]}));i&&i(`[Subagent Turn ${T+1}]...`);let O=((await Ho(p,x,C,E,"Fast")).text||"").replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/gi,"").trim();$=O,i&&i(`[Subagent Response]
790
- ${O}
791
- `),S.push({role:"agent",text:O});let P=Go(O);if(P.length===0)break;let W=P.filter(B=>B.toolName.toLowerCase()==="askmain"||B.toolName.toLowerCase()==="ask_main"),N=!1,Y="";for(let B of P){if(Ot){if(n?.taskId&&typeof Ve<"u"){let M=Ve.find(F=>F.id===n.taskId);M&&(M.status="cancelled")}throw new Error("Subagent task was cancelled.")}if(n?.taskId&&typeof Ve<"u"){let M=Ve.find(F=>F.id===n.taskId);if(M&&M.status==="cancelled")throw new Error("Subagent task was cancelled.")}let j=B.toolName.toLowerCase();if(j==="askmain"||j==="ask_main"){if(N)continue;N=!0;let M="";if(W.length===1?M=I(W[0].args).question||W[0].args:M=W.map((F,V)=>{let J=I(F.args);return`Q${V+1}: ${J.question||F.args}`}).join(`
792
- `),n.onAskMain){i&&i(`[Executing Tool] AskMain("${M}")...`);let F=await n.onAskMain(M);i&&i(`[Tool Result]
793
- Answer from Main Agent: ${F}
794
- `),Y+=`[TOOL RESULT for AskMain]: Answer from Main Agent: ${F}
795
-
796
- `,await It("toolSuccess")}else Y+=`[TOOL RESULT for AskMain]: ERROR: Main agent communication channel not available.
797
-
798
- `;continue}if(!(o?o.some(M=>M.toLowerCase()===j):!0)){let M=`ERROR: Tool [${B.toolName}] is not in the allowed tools list for this subagent.`;i&&i(`[Blocked Tool Call] ${B.toolName} - not allowed
799
- `),Y+=`${M}
800
-
801
- `;continue}if(j==="exec_command"||j==="execcommand"||j==="run"){let M=I(B.args).command||"",F=w(M);if(!F.allowed){let V=`ERROR: [SECURITY RESTRICTION] Subagent execution blocked command: ${F.reason}`;i&&i(`[Blocked Command] ${M} - ${F.reason}
802
- `),Y+=`${V}
803
-
804
- `;continue}}let Re="";if(j==="web_search"||j==="websearch")Re=`\u2714 \x1B[95mSearched\x1B[0m: ${I(B.args).query||""}`;else if(j==="web_scrape"||j==="webscrape")Re=`\u2714 \x1B[95mScraped\x1B[0m: ${I(B.args).url||""}`;else if(j==="search_keyword"||j==="searchkeyword"||j==="codesearch"||j==="code_search"){let M=I(B.args),F=M.keyword||"",V=M.path||"";Re=`${F?"\u2714":"\u2718"} \x1B[95mSearched\x1B[0m: ${F||"No Query"}${V?` \u2192 ${V.replaceAll("\\","/")}`:""}`}else if(j==="view_file"||j==="viewfile"||j==="readfile")Re=`\u2714 \x1B[95mRead\x1B[0m: ${(I(B.args).path||"").replaceAll("\\","/")}`;else if(j==="list_files"||j==="read_folder"||j==="readfolder"){let M=I(B.args).path||null,F=I(B.args).recurse||0;Re=`${M?"\u2714":"\u2718"} \x1B[95mBrowsed\x1B[0m: ${M?`${M.replaceAll("\\","/")}${F>0?`${M.endsWith("/")?`*${F}`:`/*${F}`}`:`${M.endsWith("/")?"":"/"}`}`:""}`}else if(j==="write_file"||j==="writefile"){let M=I(B.args).path||null;Re=`${M?"\u2714":"\u2718"} \x1B[95mCreated\x1B[0m: ${M?`${M.replaceAll("\\","/")}`:"No File Changes"}`}else if(j==="update_file"||j==="updatefile"||j==="patchfile"||j==="patch_file"||j==="patchfile"||j==="updatefile"){let M=I(B.args).path||null,F=I(B.args).content||null;Re=`${M?"\u2714":"\u2718"} \x1B[95mEdited\x1B[0m: ${M?`${M.replaceAll("\\","/")}`:"No File Changes"}`}else if(j==="exec_command"||j==="execcommand"||j==="run"){let M=I(B.args).command||null;Re=`${M?"\u2714":"\u2718"} \x1B[95mExecuted\x1B[0m: ${M?M.slice(0,100)+(M.length>100?"...":""):"No Command"}`}else if(j==="file_map"||j==="filemap"){let M=I(B.args).path||"";Re=`${M?"\u2714":"\u2718"} \x1B[95mIndexed\x1B[0m: ${M?`${M.replaceAll("\\","/")}`:"File Not Found"}`}else if(j==="await"){let{time:M}=I(B.args),F=parseFloat(M)||0;F<10&&(F=10),F>180&&(F=180),Re=`\u2714 \x1B[95mAwaiting\x1B[0m \u2192 ${(J=>{if(J>=60){let Ne=Math.floor(J/60),De=J%60;return`${Ne}m${De>0?` ${De}s`:""}`}return`${J}s`})(F)}`}else{let M=Zi[j]||B.toolName,F=xs(j,B.args);Re=`\u2714 \x1B[95m${M}\x1B[0m${F?`: ${F}`:""}`}n.onVisualFeedback&&Re&&n.onVisualFeedback(Re),i&&i(`[Executing Tool] ${B.toolName}(${B.args})...`);try{let M=await fo(B.toolName,B.args,{...n,mode:"Flux"});if(i&&i(`[Tool Result]
805
- ${M}
806
- `),Y+=`[TOOL RESULT for ${B.toolName}]: ${M}
807
-
808
- `,await It("toolSuccess"),j==="patchfile"||j==="update_file"||j==="updatefile"||j==="patch_file"){if(M){let F=M.split(`
809
- `),V=0,J=0,Ne=!1;for(let De of F){if(De.includes("[DIFF_START]")){Ne=!0;continue}if(De.includes("[DIFF_END]")){Ne=!1;continue}Ne&&(/^\+\d+/.test(De)?V++:/^\-\d+/.test(De)&&J++)}(V>0||J>0)&&(await qt("linesAdded",V),await qt("linesRemoved",J))}}else if((j==="writefile"||j==="write_file")&&M){let F=M.match(/- Stats: \[(\d+) lines/),V=F?parseInt(F[1]):0,J=0;if(M.includes("Old File contents:")){let Ne=!1;for(let De of M.split(`
810
- `)){if(De.includes("Old File contents:")){Ne=!0;continue}Ne&&(De.trim()===""?Ne=!1:/^\d+ \|/.test(De)&&J++)}}(V>0||J>0)&&(await qt("linesAdded",V),await qt("linesRemoved",J))}}catch(M){let F=`ERROR: Execution failed for [${B.toolName}]: ${M.message}`;i&&i(`[Tool Error] ${F}
811
- `),Y+=`${F}
812
-
813
- `,await It("toolFailure")}}let ie="";if(n?.taskId&&typeof Ve<"u"){let B=Ve.find(j=>j.id===n.taskId);if(B&&B.pendingSteerMessages&&B.pendingSteerMessages.length>0){let j=[...B.pendingSteerMessages];B.pendingSteerMessages=[];for(let re of j)ie+=`
814
-
815
- [STEERING INSTRUCTION FROM MAIN AGENT]: ${re}`,i&&i(`[Subagent Steered] ${re}`)}}let Me=(Y.trim()+ie).trim();S.push({role:"user",text:Me}),T++}return $};export{pn as a,qr as b,xf as c,bf as d,wl as e,zr as f,kf as g,$l as h,Sf as i,uo as j,ga as k,Ap as l,vp as m,I as n,Uc as o,ti as p,Ks as q,Wc as r,jc as s,ut as t,ls as u,xd as v,sl as w,bd as x,kd as y,Sd as z,Td as A,Rd as B,vd as C,Id as D,Tn as E,al as F,Js as G,qt as H,ll as I,Dr as J,cs as K,Nl as L,bu as M,ku as N,Lp as O,Wo as P,Pp as Q,Dn as R,Sc as S,km as T,Sm as U,ar as V,Tm as W,Rm as X,vc as Y,Em as Z,$m as _,Cm as $};