fluxflow-cli 4.4.3 → 4.4.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -3
- package/dist/chunks/ai-MUATXJWY.js +1 -0
- package/dist/chunks/app-EDFWPGE6.js +231 -0
- package/dist/chunks/chunk-7LA2RQEK.js +822 -0
- package/dist/chunks/{chunk-GKFFLQSG.js → chunk-LXTXILI5.js} +1 -1
- package/dist/chunks/{chunk-TKIVOTJ4.js → chunk-N5EE3XWJ.js} +2 -2
- package/dist/chunks/{screen_grid-JSAE3BZG.js → screen_grid-PVIPPVR7.js} +1 -1
- package/dist/chunks/{settings-NKBYU2YV.js → settings-TAIBP5U4.js} +1 -1
- package/dist/cli.js +1 -1
- package/dist/package.json +4 -3
- package/package.json +4 -3
- package/surprise.js +140 -0
- package/dist/chunks/ai-HG6SZA25.js +0 -1
- package/dist/chunks/app-PXVLYL2U.js +0 -231
- package/dist/chunks/chunk-4DTVMZ35.js +0 -823
|
@@ -0,0 +1,822 @@
|
|
|
1
|
+
import{b as ur}from"./chunk-ACHIC75V.js";import{c as At,d as vs,g as _e,h as Ft}from"./chunk-N5EE3XWJ.js";import{a as Vs,b as As,c as ee,d as ge}from"./chunk-SIINYZWE.js";import{c as On,d as gn,e as To,f as $s,g as Ms,h as dr,i as tn,j as Pt,k as nn,l as Ln,m as Gn,n as dn,o as yn,p as cs,q as fr,r as qn,s as ds}from"./chunk-I27MASHH.js";import{a as Ve,c as Ro}from"./chunk-56EJGQU3.js";import{c as Ci,d as $i,e as Xs}from"./chunk-LXTXILI5.js";import hi from"dotenv";import{GoogleGenAI as Na,ThinkingLevel as ut,HarmBlockThreshold as Jn,HarmCategory as Qn}from"@google/genai";import{execSync as sl}from"child_process";import{spawn as pr}from"child_process";var O=e=>{let n={};if(!e)return n;let t=0;for(;t<e.length;){for(;t<e.length&&/[\s,]/.test(e[t]);)t++;if(t>=e.length)break;let o=e.substring(t).match(/^(\w+)\s*=\s*/);if(!o){t++;continue}let s=o[1];t+=o[0].length;let r="";if(t<e.length&&(e[t]==='"'||e[t]==="'"||e[t]==="`")){let a=e[t];t++;let i=t,p=-1,d=t;for(;d<e.length;){let c=e.indexOf(a,d);if(c===-1)break;let f=0;for(let y=c-1;y>=0&&e[y]==="\\";y--)f++;if(f%2!==0){d=c+1;continue}let u=e.substring(c+1),h=u.trim(),g=h===""||/^,\s*\w+\s*=/.test(h)||h.startsWith(")")&&(h.length===1||/^\)\s*([,\]\s]|\[\[?tool:)/i.test(h));if(g&&u.startsWith(`
|
|
2
|
+
`)){let y=h.split(`
|
|
3
|
+
`)[0];if(!y.includes("=")&&!y.includes(")")){d=c+1;continue}}if(g){p=c;break}d=c+1}p!==-1?(r=e.substring(i,p),t=p+1):(r=e.substring(i),t=e.length);let l=s.toLowerCase().includes("path")||["dest","source","to","from"].includes(s.toLowerCase());r=r.replace(/\\(.)/g,(c,f)=>{switch(f){case"n":return`
|
|
4
|
+
`;case"r":return"\r";case"t":return" ";case"\\":return"\\";default:return f===a?a:f}})}else if(t<e.length&&e[t]==="["){let a=0,i=null,p=t,d=-1;for(let l=t;l<e.length;l++){let c=e[l];if(i&&c===i){let f=0;for(let u=l-1;u>=0&&e[u]==="\\";u--)f++;f%2===0&&(i=null)}else!i&&(c==='"'||c==="'"||c==="`")&&(i=c);if(!i&&(c==="["?a++:c==="]"&&a--,a===0)){d=l;break}}if(d!==-1){r=e.substring(p,d+1),t=d+1;try{let l=r.trim();l.startsWith("'")||l.includes("'")}catch{}}else r=e.substring(p),t=e.length}else{let a=e.substring(t),i=a.match(/,\s*\w+\s*=|(?:\s*\)\s*(?:$|\]\]))/);if(i){let p=i.index;r=a.substring(0,p).trim(),t+=p}else r=a.trim(),t=e.length}r==="true"?r=!0:r==="false"?r=!1:typeof r=="string"&&!isNaN(r)&&r.trim()!==""&&(r=Number(r)),typeof r=="string"&&(s.toLowerCase().includes("path")||["dest","source","to","from"].includes(s.toLowerCase()))&&(r=r.replace(/\x0C/g,"\\f").replace(/\x0D/g,"\\r").replace(/\x0B/g,"\\v").replace(/\x08/g,"\\b")),n[s]=r}return n};var Eo=null;try{let e=await import("node-pty");Eo=e.default||e}catch{}var zc=!!Eo,_o=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),hr=e=>{if(!e)return"";let n=[[]],t=0,o=0,s=/\x1b\[([0-9;]*?)([a-zA-Z])/g,r=0,a,i=d=>{for(let l=0;l<d.length;l++){let c=d[l];if(c===`
|
|
5
|
+
`)for(t++,o=0;t>=n.length;)n.push([]);else if(c==="\r")o=0;else{for(;t>=n.length;)n.push([]);let f=n[t];for(;o>f.length;)f.push(" ");f[o]=c,o++}}};for(;(a=s.exec(e))!==null;){i(e.substring(r,a.index));let d=a[1],l=a[2],c=d?d.split(";").map(Number):[];if(l==="A"){let f=c[0]||1;t=Math.max(0,t-f)}else if(l==="B"){let f=c[0]||1;for(t=t+f;t>=n.length;)n.push([])}else if(l==="C"){let f=c[0]||1;o=o+f}else if(l==="D"){let f=c[0]||1;o=Math.max(0,o-f)}else if(l==="G"){let f=(c[0]||1)-1;o=Math.max(0,f)}else if(l==="H"||l==="f"){let f=(c[0]||1)-1,u=(c[1]||1)-1;for(t=Math.max(0,f),o=Math.max(0,u);t>=n.length;)n.push([])}else if(l==="K"){let f=c[0]||0;if(t<n.length){let u=n[t];if(f===0)u.length=o;else if(f===1)for(let h=0;h<o&&h<u.length;h++)u[h]=" ";else f===2&&(u.length=0)}}else if(l==="J"){let f=c[0]||0;(f===2||f===3)&&(n.length=0,n.push([]),t=0,o=0)}r=s.lastIndex}i(e.substring(r));let p=n.map(d=>d.join(""));for(;p.length>0&&p[p.length-1]==="";)p.pop();return p.join(`
|
|
6
|
+
`)},wt=null,Js=!1,Kc=e=>{try{wt&&(Js&&typeof wt.write=="function"?wt.write(e):wt.stdin&&wt.stdin.writable&&wt.stdin.write(e))}catch{}},Yc=()=>{if(wt){try{Js&&typeof wt.destroy=="function"?wt.destroy():typeof wt.kill=="function"&&(process.platform==="win32"?pr("taskkill",["/pid",wt.pid,"/f","/t"]):wt.kill("SIGKILL"))}catch{}wt=null,Js=!1}},mr=(e,n=!1)=>{if(process.platform!=="win32")return e;let t=[],o="",s=null,r=!1;for(let l=0;l<e.length;l++){let c=e[l];if(r){o+=c,r=!1;continue}if(c==="\\"){if(e[l+1]===" "){o+=" ",l++;continue}o+=c,r=!0;continue}s?(c===s&&(s=null),o+=c):c==='"'||c==="'"?(s=c,o+=c):c===";"&&!o.includes("://")?(o.length>0&&(t.push(o),o=""),t.push(n?";":"&")):c==="&"&&!o.includes("://")?e[l+1]==="&"?(o.length>0&&(t.push(o),o=""),t.push("&&"),l++):(o.length>0&&(t.push(o),o=""),t.push("&")):c==="|"&&!o.includes("://")?(o.length>0&&(t.push(o),o=""),t.push("|")):/\s/.test(c)?o.length>0&&(t.push(o),o=""):o+=c}o.length>0&&t.push(o);let a=l=>!(!l.includes("/")||/^(https?|file|ftp):\/\//i.test(l)||l.startsWith("@")||l.startsWith("/")&&(l.match(/\//g)||[]).length===1||/\s\/|\/\s/.test(l)||/[\(\)\{\}\;\<\>\=\'\"]/.test(l)),i=[];for(let l=0;l<t.length;l++){let c=t[l];if(c==="mkdir"&&n&&zn()){let f=[],u=l+1;for(;u<t.length;){let h=t[u];if([">",">>","<","&","&&","|","||",";"].includes(h))break;h!=="-p"&&h!=="--parents"&&h!=="-v"&&h!=="--verbose"&&f.push(h),u++}if(f.length>0){let h=f.map(g=>{let y=g.replace(/^['"]|['"]$/g,""),m=g;return a(y)&&(m=g.replace(/\//g,"\\")),m});i.push("New-Item","-ItemType","Directory","-Force","-Path",h.join(","))}else i.push("New-Item","-ItemType","Directory","-Force");l=u-1;continue}if(c==="rm"&&n&&zn()){let f=[],u=!1,h=!1,g=l+1;for(;g<t.length;){let m=t[g];if([">",">>","<","&","&&","|","||",";"].includes(m))break;m==="-rf"||m==="-fr"?(u=!0,h=!0):m==="-r"||m==="-R"||m==="--recursive"?u=!0:m==="-f"||m==="--force"?h=!0:f.push(m),g++}let y=["Remove-Item"];if(u&&y.push("-Recurse"),h&&y.push("-Force"),f.length>0){let m=f.map(x=>{let w=x.replace(/^['"]|['"]$/g,""),k=x;return a(w)&&(k=x.replace(/\//g,"\\")),k});y.push("-Path",m.join(","))}i.push(...y),l=g-1;continue}if(c==="cp"&&n&&zn()){let f=[],u=!1,h=!1,g=l+1;for(;g<t.length;){let m=t[g];if([">",">>","<","&","&&","|","||",";"].includes(m))break;m==="-r"||m==="-R"||m==="--recursive"?u=!0:m==="-f"||m==="--force"?h=!0:f.push(m),g++}let y=["Copy-Item"];if(u&&y.push("-Recurse"),h&&y.push("-Force"),f.length>0){let m=f.map(x=>{let w=x.replace(/^['"]|['"]$/g,""),k=x;return a(w)&&(k=x.replace(/\//g,"\\")),k});if(m.length>1){let x=m.pop();y.push("-Path",m.join(","),"-Destination",x)}else y.push("-Path",m[0])}i.push(...y),l=g-1;continue}if(c==="touch"&&n&&zn()){let f=[],u=l+1;for(;u<t.length;){let h=t[u];if([">",">>","<","&","&&","|","||",";"].includes(h))break;f.push(h),u++}if(f.length>0){let g=`(${f.map(y=>{let m=y.replace(/^['"]|['"]$/g,""),x=y;return a(m)&&(x=y.replace(/\//g,"\\")),x}).join(", ")}) | ForEach-Object { if (Test-Path $_) { (Get-Item $_).LastWriteTime = [System.DateTime]::Now } else { $null | Out-File -FilePath $_ } }`;i.push(g)}l=u-1;continue}if(c==="|"&&t[l+1]==="tee"){t[l+2]==="-a"?(i.push(">>"),l+=2):(i.push(">"),l+=1);continue}if(c==="|"&&t[l+1]==="cat"&&t[l+2]===">"){i.push(">"),l+=2;continue}if(c==="|"){let f=t[l+1];if(f){let u=f.replace(/^['"]|['"]$/g,""),h=/\.(txt|md|json|log|csv|html|css|py|js|xml|yaml|yml|pdf|docx|pptx|xlsx)$/i.test(u);if(a(u)&&h){i.push(">");continue}}}i.push(c)}let p=!1,d=i.map(l=>{if(l==="echo")return p=!0,l;[">",">>","<","&","&&","|","||",";"].includes(l)&&(p=!1);let f=/^['"]|['"]$/.test(l),u=l;p&&f&&(u=l.replace(/^['"]|['"]$/g,""));let h=/^['"]|['"]$/.test(u),g=u.replace(/^['"]|['"]$/g,"");a(g)&&(u=u.replace(/\//g,"\\"));let y=u.replace(/^['"]|['"]$/g,"");return y.includes(" ")&&!h&&(u=`"${y}"`),u});if(n){let l="",c=0;for(let f=0;f<d.length;f++){let u=d[f];u==="&&"?(l+="; if ($?) {",c++):u===";"?(l+=" }".repeat(c)+";",c=0):(l&&!l.endsWith(" ")&&!l.endsWith("{")&&(l+=" "),l+=u)}return l+=" }".repeat(c),l}return d.join(" ")},gr=async(e,n={})=>{let{command:t}=O(e),{onChunk:o}=n;if(!t)return'ERROR: Missing "command" argument for exec_command.';let s=process.platform==="win32",r=n.systemSettings||{},a={};return r.networkAccess===!1&&(a.HTTP_PROXY="http://127.0.0.1:9999",a.HTTPS_PROXY="http://127.0.0.1:9999",a.ALL_PROXY="socks5://127.0.0.1:9999",a.http_proxy="http://127.0.0.1:9999",a.https_proxy="http://127.0.0.1:9999",a.all_proxy="socks5://127.0.0.1:9999",a.NO_PROXY="localhost,127.0.0.1"),new Promise(i=>{let p=d=>{let l=d==="pwsh"||d==="powershell",c=mr(t,l),f;s?d==="pwsh"?f="C:\\Users\\User\\AppData\\Local\\Microsoft\\WindowsApps\\pwsh.exe":d==="powershell"?f="powershell.exe":f="cmd.exe":f=process.env.SHELL||"bash";let u=s?l?["-NoProfile","-Command",c]:["/c",c]:["-c",c];if(r.networkAccess===!1&&!s){let h=f,g=[...u];if(process.platform==="linux")f="unshare",u=["-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
|
+
`;f="sandbox-exec",u=["-p",y,h,...g]}}if(Eo)try{let h=Eo.spawn(f,u,{name:"xterm-256color",cols:n.cols||120,rows:n.rows||30,cwd:process.cwd(),env:{...process.env,CI:"false",TERM:"xterm-256color",FORCE_COLOR:"1",...a}});wt=h,Js=!0;let g="",y=!1;return h.onData(m=>{if(!y){g+=m,o&&o(m);let x=_o(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(x)&&(y=!0,setTimeout(()=>i(`SUCCESS: Dev server started successfully in background.
|
|
12
|
+
|
|
13
|
+
${x}`),500))}}),h.onExit(({exitCode:m})=>{if(y)return;wt=null;let x=hr(g||""),w=_o(x).replace(/\n{3,}/g,`
|
|
14
|
+
|
|
15
|
+
`)||"Command executed with no output.";i(m!==0?`ERROR: Command [${t}] failed with exit code [${m}].
|
|
16
|
+
|
|
17
|
+
${w}`:`SUCCESS: Command [${t}] completed.
|
|
18
|
+
|
|
19
|
+
${w}`)}),!0}catch(h){return s&&(d==="pwsh"||d==="powershell")&&h.code==="ENOENT"?!1:(Co(i,c,t,a,o,d,r),!0)}else return Co(i,c,t,a,o,d,r),!0};s?p("pwsh")||p("powershell")||p("cmd"):p("bash")})},Co=(e,n,t,o,s,r="powershell",a={})=>{let i=process.platform==="win32",p=r==="pwsh"||r==="powershell",d;i?r==="pwsh"?d="C:\\Users\\User\\AppData\\Local\\Microsoft\\WindowsApps\\pwsh.exe":r==="powershell"?d="powershell.exe":d="cmd.exe":d=process.env.SHELL||"bash";let l=i?p?["-NoProfile","-Command",n]:["/c",n]:["-c",n];if(a.networkAccess===!1&&!i){let g=d,y=[...l];if(process.platform==="linux")d="unshare",l=["-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",l=["-p",m,g,...y]}}let c=i?pr(d,l,{cwd:process.cwd(),env:{...process.env,...o}}):pr(d,l,{cwd:process.cwd(),env:{...process.env,CI:"false",TERM:"xterm-256color",FORCE_COLOR:"1",...o}});wt=c,Js=!1,c.stdin&&c.stdin.on("error",()=>{wt=null});let f="",u="",h=!1;c.stdout.on("data",g=>{if(!h){let y=g.toString();f+=y,s&&s(y);let m=_o(f);/(?: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))}}),c.stderr.on("data",g=>{if(!h){let y=g.toString();u+=y,s&&s(y)}}),c.on("close",g=>{if(h)return;wt=null;let y=[],m=hr(f),x=hr(u);m&&y.push(`STDOUT:
|
|
27
|
+
${m}`),x&&y.push(`STDERR:
|
|
28
|
+
${x}`),g!==0&&y.push(`EXIT CODE: ${g}`);let w=y.join(`
|
|
29
|
+
|
|
30
|
+
`)||"Command executed with no output.",k=_o(w).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}`)}),c.on("error",g=>{if(i&&g.code==="ENOENT"){if(r==="pwsh"){let m=mr(t,!0);return Co(e,m,t,o,s,"powershell",a)}else if(r==="powershell"){let m=mr(t,!1);return Co(e,m,t,o,s,"cmd",a)}}wt=null;let y=g instanceof Error?g.message:String(g);e(`ERROR: Failed to start command [${t}]: ${y}`)})};var Qs=null,zn=()=>{if(process.platform!=="win32")return!1;if(Qs!==null)return Qs;try{sl('powershell.exe -NoProfile -Command "exit"',{stdio:"ignore"}),Qs=!0}catch{Qs=!1}return Qs},yr=null,Mi=(e,n,t,o,s=!1,r=!0)=>{yr===null&&(yr=s);let a=`- JSON escape literal sequences inside tool arguments (backslash: \\\\, newLine: \\n, quote: \\") \u2190 Mandatory
|
|
37
|
+
- Same file, multiple edits? One PatchFile (\u226415 blocks)
|
|
38
|
+
- Tool denied? Ask for guidance
|
|
39
|
+
- Need text or huge file? CodeSearch > Full Read
|
|
40
|
+
- Avoid unnecessary large file chunk reads
|
|
41
|
+
- Dont hallucinate tool results, verify, fix errors
|
|
42
|
+
- Stuck on syntax error? Tell user > waste time
|
|
43
|
+
`,i=`**Workspace Tools (path = relative; first argument, path separator: '/')**
|
|
44
|
+
- ReadFile(path="...", startLine="int", endLine="int")${o!=="Google"?`${t?". Supports images/docs":""}`:". Supports images/docs"}
|
|
45
|
+
- ReadFolder(path="...", recurse="int 1-3"). Minimize recursion
|
|
46
|
+
- PatchFile(path="...", allowMultiple="bool, false", searchContent1="search string OR ^LINE:start..end$", newContent1="...", ...MAX15). Use small searchContent. Line Ranges must for large searchContent and escape sequences. ^...$ must for line ranges
|
|
47
|
+
- WriteFile(path="...", content="..."). Creates/Overwrites. File Exist? PatchFile > WriteFile
|
|
48
|
+
- CodeSearch(keyword="...", path="dir/file/glob/regex, inclusion/exclusion ;-separated", fuzzy="bool, false", regex="bool, auto"). Find definitions, logic, relevant code, standard junk auto-excluded
|
|
49
|
+
- Run(command="..."). Runs ${n==="Windows"?zn()?"powershell":"windows CMD":"bash"} command. Destructive/Irreversible ops \u2192 Ask user
|
|
50
|
+
- Goal(method="create/append/get", tasks=[string array], markDone=[task array]). If long multi-task: create Goals before starting. \`get + markDone\` to mark complete. Update every turn when created
|
|
51
|
+
${yr?'\n**Emergency Tools**\nInfo: `initial` = current task prompt. Revert `id` = turn before disaster (eg. disaster: `turn_3` \u2192 revert: `turn_2`). Reason explicitly\n- EmergencyRollback(method="getCheckpoint/forceRevert", id="..."). Rollback workspace in this agent loop. ONLY for catastrophic corruption. Before ending, verify no catastrophe. `id` omitted for `getCheckpoint`\n':""}${r?`
|
|
52
|
+
**Sub Agent Tools**
|
|
53
|
+
proactive use highly recommended. Prefer for any task, no user nudge needed
|
|
54
|
+
Invocations:
|
|
55
|
+
\u2022 Invoke (async/background, \u22647 parallel). Parallelize long tasks. May take time
|
|
56
|
+
\u2022 InvokeSync (sync/blocking). Sequential, repetitive or delegated tasks. Saves tokens/cost
|
|
57
|
+
- InvokeSync/Invoke(title="...", task="..."). Task must be detailed: exact file paths, imports/exports, dependencies
|
|
58
|
+
- Await(id="...", timeout="integer"). Event-driven wait
|
|
59
|
+
- GetProgress(id="..."). Poll sparingly; NO initial poll. Work or await. Never end while subagent runs
|
|
60
|
+
- Steer(id="...", message="..."). Inject additional instruction or redirection into active async subagent
|
|
61
|
+
- Cancel(id="..."). Cancel async task ONLY if stalled (2m+) or incorrect`:""}`,p=`**Creative Tools (path = relative; first argument, path separator: '/')**
|
|
62
|
+
- WritePDF(path="...", content="...", orientation="..."). Proactive A4 page breaks must in css. HTML/CSS for premium layout, stable margins & headers/footers, no watermarks
|
|
63
|
+
- WriteDoc(path="...", content="..."). A4 Word document, no watermarks, stable margins & headers/footers`,d=`**Computer Use Tools (GUI Desktop Automation)**
|
|
64
|
+
- Click(gridId="integer", type="single/double", button="left/middle/right", intendedClickText="target text"). Click target grid number, intendedClickText: literal text/icon on screen (OCR scannable, upto 3 words). Double click desktop icons
|
|
65
|
+
- Drag(fromGridId="integer", toGridId="integer"). Drag mouse from start grid number to target grid number
|
|
66
|
+
- Scroll(direction="up/down", gridId="mouse hover area"). Scroll viewport vertically
|
|
67
|
+
- KeyboardTyping(text="string", autoPressEnter="bool"). Type text string into currently active input. JSON escape literal escape sequences
|
|
68
|
+
- KeyPress(key="key or ;-separated combination, eg: enter, back, backspace, clearInput, ctrl;c, alt;tab, f5, f11, alt;f4"). Press key, shortcut, function key (f1-f12), or clear active input field
|
|
69
|
+
- RecaptureScreen(). Request fresh gridded screenshot`;return`
|
|
70
|
+
-- TOOLS --
|
|
71
|
+
You cant execute tools. To use tools, must output exactly [tool:functions.ToolName(arg1="value1")] structured string in chat output & wait for system response \u2190 no exception, tool:functions must
|
|
72
|
+
Tool Rules:
|
|
73
|
+
- Max 3 tool calls/turn${e==="Flux"||e.toLowerCase()==="fluxcu"?" (Todo: 3+)":""}
|
|
74
|
+
- NO chat text with tool calls
|
|
75
|
+
${e==="Flux"||e.toLowerCase()==="fluxcu"?`${a}`:""}
|
|
76
|
+
**User Communication**
|
|
77
|
+
- AskUser(question="...", optionA="title::description", ...MAX4). Ambiguity, path divergence, security risk. Ask, dont finish/guess. Keep titles short
|
|
78
|
+
|
|
79
|
+
**Web Tools**
|
|
80
|
+
- WebSearch(query="...", aiMode="bool, optional", limit="integer 3-10 aiMode: exclude"). Proactive use for unknown info/docs. aiMode: LLM search
|
|
81
|
+
- WebScrape(url="..."). Proactive use for specific webpage/docs/api
|
|
82
|
+
|
|
83
|
+
${e==="ICU"?`${d}`:e==="FluxCU"?`${i}
|
|
84
|
+
${d}`:e==="Flux"?`${i}`:`${p}`}`.trim()};var Ai=(e=!0,n=!0)=>`
|
|
85
|
+
To use tools, must output exactly '[tool:functions.ToolName(arg1="value1")]' structured string in chat response \u2190 no exception
|
|
86
|
+
|
|
87
|
+
-- Chat Management Tools --
|
|
88
|
+
- Chat(title="<short creative title of FULL conversation in 3 or 4 words>"). Consider full chat context to generate title NOT just latest message
|
|
89
|
+
- Memory(action="temp", content="<summary of the user prompt & model responses only from latest prompt under 40 words>. [Talked on: <date> <hour>]"). Time format: YYYY-MM-DD HH am/pm
|
|
90
|
+
|
|
91
|
+
${e?`-- User-specific long-term/permanent memory (use based on conversation context, do not re-save memory which is already saved) --
|
|
92
|
+
- Add: Memory(action="user", method="add", content="<string to add>. [Saved on: <date ONLY>]", score=2). (Set score=2 ONLY if the user explicitly asked to "remember" or "save" this information, else omit this parameter entirely)
|
|
93
|
+
- Delete: Memory(action="user", method="delete", id="<memory id>")
|
|
94
|
+
- Update: Memory(action="user", method="update", content-new="string to update", id="<memory id>")
|
|
95
|
+
|
|
96
|
+
-- Memory Relevance Decay Tool --
|
|
97
|
+
- Score Adjustment: addMemScore(id="<memory id>")
|
|
98
|
+
You MUST call this tool when a specific saved memory in the '-- Current Saved User Memories --' list was relevant, referenced, or helpful in the agent's response or user prompt in current message. You can stack multiple calls
|
|
99
|
+
|
|
100
|
+
Explicit Triggers for permanent memory:
|
|
101
|
+
- User explicitly asks to 'remember' something
|
|
102
|
+
- User mentions something important long-term that should be remembered
|
|
103
|
+
- User provides information that could be useful for long-term reference
|
|
104
|
+
- User shares personal information or preferences
|
|
105
|
+
|
|
106
|
+
Usage Rules:
|
|
107
|
+
- Frequency for 'user' action: Based on explicit triggers
|
|
108
|
+
- If you want to save something, but similar memory already exists, use the update method not add
|
|
109
|
+
- Chat title is mandatory
|
|
110
|
+
- Temporary memory is mandatory
|
|
111
|
+
- When called user memory, still use Temporary Memory
|
|
112
|
+
- Must not ignore any tool calls in given context of chat between user & agent`:""}`.trim();var $o={xHigh:`Effort: High
|
|
113
|
+
Challenge assumptions, verify before concluding, prefer the simplest correct solution, assess architecture, scalability & trade-offs, verify dependencies, regressions, failure modes & modular design, plan: files, modules, interfaces & tests
|
|
114
|
+
Continuous analysis, verify from first principles, seek failure paths, verify imports, tool results & system stability; avoid syntax errors
|
|
115
|
+
MANDATORY: Full technical verification`,High:`Effort: High
|
|
116
|
+
Rigorous thinking, prefer the simplest correct solution, assess architecture, performance & maintainability, verify error handling, assumptions, edge cases, dependencies & regressions, plan: files, functions, logic & interactions
|
|
117
|
+
Continuous analysis, verify from first principles, seek failure paths, verify imports, tool results & system stability; avoid syntax errors
|
|
118
|
+
MANDATORY: Full technical verification`,Medium:`Effort: Medium
|
|
119
|
+
Focused, technical thinking, find the simplest solution meeting requirements, check error handling, assumptions, edge cases & dependencies, verify cohesive, modular changes, outline: files, functions & key logic
|
|
120
|
+
Logical, implementation-focused, efficient, deliberate, verify imports, tool results & system stability; avoid syntax errors
|
|
121
|
+
MANDATORY: Brief verification for technical tasks/greetings`,Minimal:`Effort: Low
|
|
122
|
+
Quick, focused thinking, intent & complexity, required tools/files/actions, before acting
|
|
123
|
+
Brief thoughts, think only enough to avoid mistakes, verify imports, tool results & system stability; avoid syntax errors`,Off:`Effort: Lowest
|
|
124
|
+
No thinking. Immediate response
|
|
125
|
+
Verify imports, tool results & system stability; avoid syntax errors`};import Ii from"fs";import rl from"screenshot-desktop";var Oi=!1;(async()=>{try{let e=await Ft();if(Number(e?.display)===1){let n=await rl.listDisplays();n&&n.length>1&&(Oi=!0)}}catch{}})();var wr=null,vi=null,Zs=null,fd=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",il=process.env.NO_DEV||!1,al=(e,n)=>{if(!n)return"";if(e!==vi||Zs===null){vi=e;try{let t=ee(Pt,[]);Array.isArray(t)&&t.length>0?Zs=t.map(o=>`- ${o.memory}`).join(`
|
|
126
|
+
`):Zs=""}catch(t){Zs="",Ii.appendFileSync(`${gn}/memory/error.txt`,`${t.message}
|
|
127
|
+
-------------------------------------------------
|
|
128
|
+
|
|
129
|
+
`)}}return Zs},Li=(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) --
|
|
130
|
+
${e}`:"";return s?`${s}`:""},Di=(e,n,t,o,s=!0,r=!1,a="Google",i=!1,p,d)=>{let l=!1;process.env.forcedReasoning&&(l=!0);let c="";if(!p&&a==="Google"){let S=n;n==="Fast"&&(S="Off"),n==="Low"&&(S="Minimal"),n==="Standard"&&(S="Medium"),(n==="xHigh"||n==="Max")&&(S="xHigh"),c=$o[S]||$o.Medium}if(p||a!=="Google"){let S={Fast:"Lowest",Low:"Low",Medium:"Medium",Standard:"Medium",High:"High",xHigh:"High",Max:"High"};c=$o.xHigh,c=c.replace("Effort: High",`Effort: ${S[n]}`).replace(`
|
|
131
|
+
MANDATORY: Full technical verification`,""),n==="Fast"?c=`Effort: Lowest
|
|
132
|
+
No thinking. Immediate response
|
|
133
|
+
Verify imports, tool results & system stability; avoid syntax errors`:n==="Low"&&(c=`Effort: Low
|
|
134
|
+
Quick, focused thinking, intent & complexity, required tools/files/actions, before acting
|
|
135
|
+
Brief thoughts, think only enough to avoid mistakes, verify imports, tool results & system stability; avoid syntax errors`)}let f=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",u=e.instructions&&e.instructions?.length>0?`User Preferences: ${e.instructions}
|
|
136
|
+
|
|
137
|
+
`:"",h=e.nickname&&e.nickname?.length>0?`User Nickname: ${e.nickname}
|
|
138
|
+
${u.length?"":`
|
|
139
|
+
`}`:"",g=e.name&&e.name?.length>0?`User Name: ${e.name}
|
|
140
|
+
${h.length||u.length?"":`
|
|
141
|
+
`}`:"",y=process.cwd(),m=al(d,s),x=m?.length>0?`--- Saved Memories ---
|
|
142
|
+
${m}
|
|
143
|
+
|
|
144
|
+
`:"",w=(()=>{let S=process.cwd().toLowerCase();if(process.platform==="win32"){let T=process.env.SystemRoot?.toLowerCase()||"c:\\windows",_=process.env.ProgramFiles?.toLowerCase()||"c:\\program files",E=process.env["ProgramFiles(x86)"]?.toLowerCase()||"c:\\program files (x86)";return S.startsWith(T)||S.startsWith(_)||S.startsWith(E)}else return S==="/"||["/bin","/sbin","/etc","/usr","/var","/root"].some(_=>S.startsWith(_))})(),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(r||wr===null){let S=k.filter(T=>Ii.existsSync(T.name));wr=t==="Flux"&&S.length>0?`
|
|
145
|
+
-- PROJECT CONTEXT --
|
|
146
|
+
${S.map(T=>`- ${T.name}: ${T.desc}`).join(`
|
|
147
|
+
`)}
|
|
148
|
+
Check these first; These Files > Training Data. Safety rules apply
|
|
149
|
+
`:""}let C=wr;return`${process.env.I_HAVE_TOO_MUCH_MONEY==="true"||process.env.I_HAVE_TOO_MUCH_MONEY===!0||!1?`${" ".repeat(Math.floor(Math.random()*4)+1)}`:""}=== SYSTEM PROMPT ===
|
|
150
|
+
Identity: Flux Flow. Sassy, Friendly, CLI Assistant${il?"":" by Kushal Roy"}
|
|
151
|
+
${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"}${Oi&&t.toLowerCase().includes("cu")?`
|
|
152
|
+
**Running on secondary screen. Opened app not visible in screenshot? Might be opened on primary. Use 'AskUser' with NO options and tell user to move app window to secondary**`:""}
|
|
153
|
+
|
|
154
|
+
- OS: ${f}
|
|
155
|
+
- Use directory structure for file path resolution${s?`
|
|
156
|
+
- Use relative time reference eg. few mins ago
|
|
157
|
+
-- Chat Context > Metadata`:""}
|
|
158
|
+
|
|
159
|
+
-- THINKING GUIDANCE --
|
|
160
|
+
${a==="Mistral"||a==="Google"&&!p?`${c}
|
|
161
|
+
${l||n!=="Fast"&&(a==="Mistral"&&!p||n!=="xHigh"&&!p)?`critical thinking policy
|
|
162
|
+
- Use <think>...</think> for reasoning before responding any queries
|
|
163
|
+
`:""}`:`${c}
|
|
164
|
+
`}
|
|
165
|
+
${Mi(t,f,a.toLowerCase()==="deepseek"?!1:i,a,o?.advanceRollback,o?.subAgents!==!1)}
|
|
166
|
+
${C}${s?`
|
|
167
|
+
-- MEMORY RULES --
|
|
168
|
+
- Subtly Personalize with relevent contextual memories. Auto Saves
|
|
169
|
+
`:""}
|
|
170
|
+
${t==="Flux"?`-- SECURITY POLICIES --
|
|
171
|
+
- Sensitive files? Ask before Read
|
|
172
|
+
`:t.toLowerCase().includes("cu")?`-- SECURITY POLICIES --
|
|
173
|
+
- Dont operate on ANY confidential screens
|
|
174
|
+
`:""}
|
|
175
|
+
-- CHAT FORMATTING --
|
|
176
|
+
- GFM Markdown
|
|
177
|
+
- Language: English only${t==="Flow"?`
|
|
178
|
+
- use kaomojis heavily`:""}
|
|
179
|
+
=== END SYSTEM PROMPT ===
|
|
180
|
+
|
|
181
|
+
${g}${h}${u}${x}`.trim()},Pi=(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
|
+
${Ai(n,t)}
|
|
199
|
+
=== END SYSTEM PROMPT ===${e?`
|
|
200
|
+
|
|
201
|
+
-- current saved user memories --
|
|
202
|
+
${e}`:""}`.trim();import $t from"fs-extra";import Mo from"path";import{nanoid as dl}from"nanoid";import pt from"fs-extra";import fn from"path";pt.ensureDirSync(Gn);var wn=null;async function ll(e,n){try{if(e.type==="create")await pt.pathExists(e.filePath)&&(await pt.chmod(e.filePath,438).catch(()=>{}),await pt.remove(e.filePath));else if(e.type==="update"){if(!e.backupFile)return;let t=fn.join(Gn,n.chatId,e.backupFile);if(await pt.pathExists(t)){let o=ee(t,null);if(!o||!o.data)throw new Error(`Backup container corrupt or empty for ${fn.basename(e.filePath)}`);let s=As(o.data);await pt.pathExists(e.filePath)&&await pt.chmod(e.filePath,438).catch(()=>{}),await pt.writeFile(e.filePath,s,"utf8")}}}catch(t){throw new Error(`Restoration failed for ${fn.basename(e.filePath)}: ${t.message}`)}}async function cl(e,n,t=7){let o=0;for(;o<t;)try{return await ll(e,n),!0}catch{if(o++,o>=t)return!1;let r=Math.min(100*Math.pow(2,o-1),5e3);await new Promise(a=>setTimeout(a,r))}return!1}var xr=null,ht={async startTransaction(e,n){xr=e,wn={id:`tx_prompt_${Date.now()}`,chatId:e,timestamp:new Date().toISOString(),prompt:n.trim(),changes:[],reverted:!1},ge(cs,wn)},async recordFileChange(e,n=null){try{if(!wn){if(xr){let a=ee(dn,[]),i=[...a].reverse().find(p=>p.chatId===xr);if(i){if(i.changes.some(f=>f.filePath===e))return;let l=await pt.pathExists(e)||n?"update":"create",c=null;if(l==="update"){let f=fn.basename(e);c=`${i.id}_${f}.bak`;let u=fn.join(Gn,i.chatId);await pt.ensureDir(u);let h=fn.join(u,c),g=n!==null?n:await pt.readFile(e,"utf8").catch(()=>null);g!==null?ge(h,{data:Vs(g)}):(l="create",c=null)}i.changes.push({filePath:e,type:l,backupFile:c}),ge(dn,a)}}return}if(wn.changes.some(a=>a.filePath===e))return;let s=await pt.pathExists(e)||n?"update":"create",r=null;if(s==="update"){let a=fn.basename(e);r=`${wn.id}_${a}.bak`;let i=fn.join(Gn,wn.chatId);await pt.ensureDir(i);let p=fn.join(i,r),d=n!==null?n:await pt.readFile(e,"utf8").catch(()=>null);d!==null?ge(p,{data:Vs(d)}):(s="create",r=null)}wn.changes.push({filePath:e,type:s,backupFile:r}),ge(cs,wn)}catch{}},async commitTransaction(){if(wn)try{let e=ee(dn,[]);if(e.push(wn),e.length>512e3){let n=e.shift();if(n.changes)for(let t of n.changes)t.backupFile&&await pt.remove(fn.join(Gn,n.chatId,t.backupFile)).catch(()=>{})}ge(dn,e),await pt.remove(cs).catch(()=>{})}catch{}finally{wn=null}},async recoverCrashedTransaction(){try{if(await pt.pathExists(cs)){let e=ee(cs,null);if(e?.changes?.length>0){let n=ee(dn,[]);n.some(t=>t.id===e.id)||(n.push(e),ge(dn,n))}await pt.remove(cs).catch(()=>{})}}catch{}},async rollbackToBefore(e){let n=ee(dn,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,r=n.slice(t).filter(a=>a.chatId===o&&!a.reverted).reverse();for(let a of r){for(let i of[...a.changes].reverse())await cl(i,a);for(let i of a.changes)if(i.backupFile){let p=fn.join(Gn,a.chatId,i.backupFile);await pt.remove(p).catch(()=>{})}n=n.filter(i=>i.id!==a.id),ge(dn,n)}return{success:!0,chatId:o,targetPrompt:s}},async getChatHistory(e){try{return ee(dn,[]).filter(t=>t.chatId===e&&!t.reverted)}catch{return[]}},async deleteChatBackups(e){try{await pt.remove(fn.join(Gn,e));let n=ee(dn,[]),t=n.filter(o=>o.chatId!==e);n.length!==t.length&&ge(dn,t)}catch{}}};var Fi=Promise.resolve(),Ao=e=>{let n=Fi.then(async()=>{try{return await e()}catch(t){throw console.error("Lock Operation Failed:",t),t}});return Fi=n.catch(()=>{}),n},fs=async()=>{await $t.ensureDir(Ms);let e={};if(await $t.pathExists($s))try{e=ee($s,{})}catch{e={}}for(let n in e){let t=Mo.join(Ms,`${n}.json`);Object.defineProperty(e[n],"messages",{get:()=>{if($t.existsSync(t))try{return ee(t,[])}catch{return[]}return[]},set:o=>{try{ge(t,o)}catch{}},enumerable:!1,configurable:!0})}return e},Ed=async(e,n,t)=>Ao(async()=>{await $t.ensureDir(Ms);let o=await fs(),s=o[e],r=(t||[]).filter(y=>!y.isUpdateNotification&&(!y.isMeta||y.text&&y.text.includes("Request Cancelled")));try{(await Ft()).systemSettings?.preserveThinking===!1&&(r=r.filter(m=>m.role!=="think"))}catch{}let a=y=>{if(!y)return;let m=typeof y=="string"?y:y.text||y.content||"";if(!m||typeof m!="string")return;let x=m.replace(/\s*\n+\s*\[Prompted on:.*?\]/g,"").replace(/\[\/?(?:STEERING HINT|QUESTION)(?::\s*\w+)?\]/gi,"").trim();if(!x)return;let w=x.split(/\s+/),k;return w.length>7?k=w.slice(0,7).join(" ")+"...":x.length>45?k=x.substring(0,45).trimEnd()+"...":k=x,k},i,p=r.filter(y=>y.role==="user"),d=p[0],l=p[p.length-1],c=a(l),f=a(d);s&&s.prompt?Math.random()<.5&&c?i=c:i=s.prompt:i=f||c;let u=n||(s?s.name:`Session ${e.slice(-6)}`),h=Mo.join(Ms,`${e}.json`);ge(h,r),o[e]={name:u,prompt:i||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};ge($s,g)}),Ni=async(e,n)=>Ao(async()=>{let t=await fs();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};ge($s,o)}),fl=async e=>Ao(async()=>{let n=await fs();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(ge($s,t),await $t.pathExists(qn))try{let a=ee(qn,[]);if(Array.isArray(a)){let i=a.filter(p=>Object.keys(p)[0]!==String(e));ge(qn,i)}}catch{}let o=ee(nn,{});o[e]&&(delete o[e],ge(nn,o));let s=ee(Ln,{});s[e]&&(delete s[e],ge(Ln,s)),await ht.deleteChatBackups(e);let r=Mo.join(Ms,`${e}.json`);if(await $t.pathExists(r))try{await $t.remove(r)}catch{}return n}),_d=()=>`flow-${dl(6)}`,Cd=async e=>{if(!e||e==="Never")return;let n=parseInt(e);if(isNaN(n))return;let t=await fs(),o=Date.now(),s=n*24*60*60*1e3,r=0;for(let a in t){let i=t[a];i.updatedAt&&o-i.updatedAt>s&&(await fl(a),r++)}return r},ul=e=>{let n=e.replace(/[\[\]]/g,"").trim(),t=new Date(n);if(!isNaN(t.getTime()))return t.getTime();let o=n.split(/,\s*|\s+/);if(o.length===0)return null;let s=o[0],r=o[1]||"",a=o[2]||"",i=s.split(/[-\/.]/).map(Number);if(i.length!==3)return null;let p="en";try{p=Intl.DateTimeFormat().resolvedOptions().locale||"en"}catch{}let d=!/^en[-_]?us$|^en$/.test(p?.toLowerCase()),l,c,f;if(i[0]>1e3)l=i[0],c=i[1],f=i[2];else if(i[2]>1e3)l=i[2],i[0]>12?(f=i[0],c=i[1]):i[1]>12?(f=i[1],c=i[0]):d?(f=i[0],c=i[1]):(c=i[0],f=i[1]);else return null;if(c<1||c>12||f<1||f>31)return null;let u=0,h=0,g=0;if(r){let m=r.split(":").map(Number);u=m[0]||0,h=m[1]||0,g=m[2]||0,a.toLowerCase()==="pm"&&u<12?u+=12:a.toLowerCase()==="am"&&u===12&&(u=0)}let y=new Date(l,c-1,f,u,h,g);return isNaN(y.getTime())?null:y.getTime()},pl=async e=>{try{if(!await $t.pathExists(e))return;let n=await $t.readFile(e,"utf8");if(!n.trim())return;let t=n.split(`
|
|
203
|
+
`),o=[],s=null,r=/^\s*(?:DEBUG|ERROR|SEARCH|PUPPETEER)\b/i;for(let c of t)r.test(c)?(s&&o.push(s),s={header:c,body:[]}):s?s.body.push(c):o.push({header:c,body:[]});s&&o.push(s);let a=10080*60*1e3,i=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 c of o){if(r.test(c.header)){let h=c.header.match(d);if(h){let g=ul(h[1]);if(g&&i-g>a)continue}}let u=c.header+(c.body.length>0?`
|
|
204
|
+
`+c.body.join(`
|
|
205
|
+
`):"");p.push(u)}let l=p.join(`
|
|
206
|
+
`).trim();l?await $t.writeFile(e,l+`
|
|
207
|
+
`,"utf8"):await $t.writeFile(e,"","utf8")}catch{}},$d=async e=>{try{if(!await $t.pathExists(e))return;let n=async t=>{let o=await $t.readdir(t);for(let s of o){let r=Mo.join(t,s);(await $t.stat(r)).isDirectory()?(await n(r),(await $t.readdir(r)).length===0&&await $t.remove(r)):s.endsWith(".log")&&await pl(r)}};await n(e)}catch{}},Bi=(e,n=4)=>{if(e.length<=1)return e;let t=e[0],o=e.slice(1),s=n*2,r=o.slice(s);return[t,...r]};var Md=async(e,n,t)=>Ao(async()=>{let o=ee(qn,[]);Array.isArray(o)||(o=[]);let s={total:n,context:t},r=o.findIndex(a=>Object.keys(a)[0]===String(e));r!==-1?o[r]={[String(e)]:s}:o.push({[String(e)]:s}),ge(qn,o)}),Ad=async e=>{try{if(!await $t.pathExists(qn))return{total:0,context:0};let n=ee(qn,[]);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 xt from"fs-extra";import Ui from"path";var hl=()=>Math.random().toString(36).substring(2)+Date.now().toString(36),le=null,Kn=null,Wi=0,Is=!1,Dn={agent:0,background:0,search:0,toolSuccess:0,toolFailure:0,toolDenied:0,duration:0,tokens:0,cachedTokens:0,candidateTokens:0,linesAdded:0,linesRemoved:0,imageCalls:[]},Os=(e,n)=>{if(!e)return{};let t=Object.keys(e),o=new Date(new Date(n).getTime()-720*60*60*1e3),s={};for(let r of t)new Date(r)>=o&&(s[r]=e[r]);return s},vo=async()=>{let e=new Date().toISOString().split("T")[0];try{!await xt.exists(tn)&&await xt.exists(dr)&&(await xt.ensureDir(Ui.dirname(tn)),await xt.move(dr,tn))}catch{}let n=tn+".tmp",t=null;try{if(await xt.exists(n)){let s=(await xt.readFile(n,"utf8")).trim(),r=null;if(s.startsWith("{")||s.startsWith("[")?r=JSON.parse(s):r=JSON.parse(As(s)),r&&r.date&&r.stats){t=r;try{await xt.rename(n,tn)}catch{}}else try{await xt.remove(n)}catch{}}}catch{try{await xt.remove(n)}catch{}}if(!t)try{if(await xt.exists(tn)){let s=(await xt.readFile(tn,"utf8")).trim();s.startsWith("{")||s.startsWith("[")?t=JSON.parse(s):t=JSON.parse(As(s))}}catch{}let o=t;if(o){let s=o.stats||{...Dn},r={...Dn,...s};Array.isArray(r.imageCalls)||(r.imageCalls=[]);let a=o.history||{},i=Os(a,e);if(Object.keys(a).length!==Object.keys(i).length&&(Is=!0),o.date===e)return{...o,stats:r,history:i};{let p=o.date,d=r,l={...i};return p&&(l[p]=d),{date:e,stats:{...Dn},history:Os(l,e)}}}return{date:e,stats:{...Dn},history:{}}},br=async()=>{if(!(!Is||!le))try{await xt.ensureDir(Ui.dirname(tn));let e=null;try{if(await xt.exists(tn)){let s=(await xt.readFile(tn,"utf8")).trim();s.startsWith("{")||s.startsWith("[")?e=JSON.parse(s):e=JSON.parse(As(s))}}catch{}if(e&&e.date===le.date&&e.stats){for(let s in le.stats)if(e.stats[s]!==void 0){if(Array.isArray(le.stats[s])){let r=Array.isArray(e.stats[s])?e.stats[s]:[],a=le.stats[s],i=new Map;for(let p of[...r,...a])p&&p.timestamp&&i.set(p.timestamp,p);le.stats[s]=Array.from(i.values())}else if(typeof le.stats[s]=="number")le.stats[s]=Math.max(le.stats[s],Number(e.stats[s])||0);else if(le.stats[s]&&typeof le.stats[s]=="object"){let r=e.stats[s]||{},a=le.stats[s];for(let i in r)if(typeof r[i]=="number")a[i]=Math.max(a[i]||0,r[i]);else if(r[i]&&typeof r[i]=="object"){a[i]||(a[i]={});for(let p in r[i])if(typeof r[i][p]=="number")a[i][p]=Math.max(a[i][p]||0,r[i][p]);else if(r[i][p]&&typeof r[i][p]=="object"){a[i][p]||(a[i][p]={});for(let d in r[i][p])a[i][p][d]=Math.max(a[i][p][d]||0,r[i][p][d])}}}}}if(e&&e.history){let s={...le.history||{}};for(let r in e.history)if(s[r])for(let a in s[r])if(a==="imageCalls"){let i=Array.isArray(e.history[r].imageCalls)?e.history[r].imageCalls:[],p=Array.isArray(s[r].imageCalls)?s[r].imageCalls:[],d=new Map;for(let l of[...i,...p])l&&l.timestamp&&d.set(l.timestamp,l);s[r].imageCalls=Array.from(d.values())}else typeof s[r][a]=="number"&&(s[r][a]=Math.max(s[r][a],Number(e.history[r][a])||0));else s[r]=e.history[r];le.history=Os(s,le.date||today)}else if(le&&le.history){let s=new Date().toISOString().split("T")[0];le.history=Os(le.history,s)}le.saveId=hl();let n=tn+".tmp",t=Vs(JSON.stringify(le,null,2));await xt.writeFile(n,t,"utf8");let o=await xt.open(n,"r+");await xt.fsync(o),await xt.close(o),await xt.rename(n,tn),Is=!1,Wi=Date.now()}catch{}},Io=()=>{if(Is=!0,Kn)return;let e=Date.now(),n=Math.max(0,1500-(e-Wi));Kn=setTimeout(async()=>{await br(),Kn=null},n),Kn.unref&&Kn.unref()},Fd=async()=>{le=await vo(),Is&&Io()},Nd=async()=>{Kn&&(clearTimeout(Kn),Kn=null),await br()},Cn=async()=>{let e=new Date().toISOString().split("T")[0];if(!le)le=await vo();else if(le.date!==e){let n=le.date,t=le.stats,o=le.history||{};t&&(o[n]=t),le={date:e,stats:{...Dn},history:Os(o,e)},Is=!0,await br()}return le&&le.stats&&!Array.isArray(le.stats.imageCalls)&&(le.stats.imageCalls=[]),le.stats},ml=async()=>{let e=new Date().toISOString().split("T")[0];le||(le=await vo()),le.date!==e&&await Cn();let n=le.history||{},t=Os(n,e);le.history=t;let o=le.stats||{...Dn},s={...Dn};s.imageCalls=[],s.models={};let r=(a,i)=>{for(let p in a)if(p==="imageCalls")a.imageCalls=[...a.imageCalls||[],...i.imageCalls||[]];else if(p==="models"){let d=i.models||{};for(let l in d){a.models[l]||(a.models[l]={});for(let c in d[l]){a.models[l][c]||(a.models[l][c]={tokens:0,cachedTokens:0,candidateTokens:0});let f=a.models[l][c],u=d[l][c];f.tokens+=u.tokens||0,f.cachedTokens+=u.cachedTokens||0,f.candidateTokens+=u.candidateTokens||0}}}else typeof a[p]=="number"&&(a[p]+=i[p]||0)};r(s,o);for(let a in t)r(s,t[a]);return s},vt=async(e,n)=>{e==="toolSuccess"?eo.toolSuccess++:e==="toolFailure"?eo.toolFailure++:e==="toolDenied"&&eo.toolDenied++;let t=await Cn();t[e]!==void 0&&t[e]++,n&&e==="agent"&&(t.providerRequests||(t.providerRequests={}),t.providerRequests[n]=(t.providerRequests[n]||0)+1),Io()},eo={linesAdded:0,linesRemoved:0,toolSuccess:0,toolFailure:0,toolDenied:0},Yt=async(e,n,t,o)=>{e==="linesAdded"?eo.linesAdded+=n:e==="linesRemoved"&&(eo.linesRemoved+=n);let s=await Cn();if(s[e]!==void 0&&(s[e]+=Math.floor(n)),t&&o&&(e==="tokens"||e==="cachedTokens"||e==="candidateTokens")){s.models||(s.models={}),s.models[t]||(s.models[t]={}),s.models[t][o]||(s.models[t][o]={tokens:0,cachedTokens:0,candidateTokens:0});let r=s.models[t][o];e==="tokens"&&(r.tokens+=Math.floor(n)),e==="cachedTokens"&&(r.cachedTokens+=Math.floor(n)),e==="candidateTokens"&&(r.candidateTokens+=Math.floor(n))}Io()},gl=async(e=1)=>{let n=new Date,t=n.toISOString().split("T")[0];le||(le=await vo()),le.date!==t&&await Cn();let o=n.getFullYear(),s=n.getMonth();n.getDate()<e&&(s-=1,s<0&&(s=11,o-=1));let i=new Date(o,s,e).toISOString().split("T")[0],p=le.history||{},d=le.stats||{...Dn},l={...Dn};l.imageCalls=[],l.models={};let c=(f,u)=>{for(let h in f)if(h==="imageCalls")f.imageCalls=[...f.imageCalls||[],...u.imageCalls||[]];else if(h==="models"){let g=u.models||{};for(let y in g){f.models[y]||(f.models[y]={});for(let m in g[y]){f.models[y][m]||(f.models[y][m]={tokens:0,cachedTokens:0,candidateTokens:0});let x=f.models[y][m],w=g[y][m];x.tokens+=w.tokens||0,x.cachedTokens+=w.cachedTokens||0,x.candidateTokens+=w.candidateTokens||0}}}else typeof f[h]=="number"&&(f[h]+=u[h]||0)};c(l,d);for(let f in p)f>=i&&f<t&&c(l,p[f]);return l},kr=async(e,n={})=>{let t=await Ft().catch(()=>({})),o=n.apiTier||t.apiTier||"Free",s=n.quotas||n.systemSettings?.quotas||t.quotas||{},r=s.providerBudgets||{},a=!!r.__useProvider,i=n.aiProvider||t.aiProvider||"Google",p=a&&!!r[i],d=()=>{if(p){let l=r[i];return{agentLimit:typeof l.agentLimit=="number"&&l.agentLimit>0?l.agentLimit:99999999,tokenLimit:typeof l.tokenLimit=="number"&&l.tokenLimit>0?l.tokenLimit:99999999999999,monthlyTokenLimit:typeof l.monthlyTokenLimit=="number"&&l.monthlyTokenLimit>0?l.monthlyTokenLimit:99999999999999}}return{agentLimit:s.agentLimit||99999999,tokenLimit:s.tokenLimit||99999999999999,monthlyTokenLimit:s.monthlyTokenLimit||99999999999999}};if(e==="agent"){let{agentLimit:l,tokenLimit:c,monthlyTokenLimit:f}=d(),u=await Cn(),h;s.resetMode==="Custom"?h=await gl(s.resetDay||1):h=await ml();let g=0,y=0,m=0;if(p){g=u.providerRequests?.[i]||0;let x=u.models?.[i]||{};for(let k in x)y+=x[k]?.tokens||0;let w=h.models?.[i]||{};for(let k in w)m+=w[k]?.tokens||0}else g=u.agent||0,y=u.tokens||0,m=h.tokens||0;return o==="Free"&&u.agent+u.background>=999999?{allowed:!1,reason:"Free Tier Daily Usage Limit Exceeded"}:g>=l?{allowed:!1,reason:p?`Daily Request Limit Reached for ${i}`:"Daily Agent Request Limit Reached"}:y>=c?{allowed:!1,reason:p?`Daily Token Budget Exhausted for ${i}`:"Daily Token Budget Exhausted"}:m>=f?{allowed:!1,reason:p?`Monthly Token Budget Exhausted for ${i}`:"Monthly Token Budget Exhausted"}:{allowed:!0}}if(e==="background"){let l=await Cn();if(o==="Free"&&l.agent+l.background>=999999)return{allowed:!1,reason:"Free Tier Background Limit Exceeded"};let c=l.background<(s.backgroundLimit||999999);return{allowed:c,reason:c?void 0:"Background Request Limit Exceeded"}}if(e==="search"){let c=(await Cn()).search<(s.searchLimit||100);return{allowed:c,reason:c?void 0:"Search Quota Exceeded"}}return{allowed:!0}},ji=async(e,n={})=>(await kr(e,n)).allowed,Sr=e=>{if(!e||e.length===0)return[];let t=[...e].sort((s,r)=>s.timestamp-r.timestamp),o=[];for(let s of t){if(o.length>0){let r=o[o.length-1];if(s.timestamp>=r.start&&s.timestamp<r.end){r.calls.push(s),r.spent+=s.cost;continue}}o.push({start:s.timestamp,end:s.timestamp+36e5,calls:[s],spent:s.cost})}return o},Hi=(e,n)=>{if(!e||e.length===0)return .025;let o=Sr(e);if(o.length===0)return .025;let s=[];for(let c of o){let f=.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)f=.015;else{let y=h.limit,m=h.ratio;m>=.8?f=y===.015?.015:y:m<.4?f=Math.min(.025,y+.005):m>=.4&&m<.6?f=Math.min(.025,y+.004):f=Math.min(.025,y+.002)}}let u=f>0?c.spent/f:0;s.push({limit:f,spent:c.spent,ratio:u})}let r=o[o.length-1];if(n<r.end)return s[s.length-1].limit;let a=s[s.length-1].limit,i=a,p=s[s.length-1].ratio,d=r.end,l=0;for(let c=s.length-1;c>=0&&s[c].ratio>=.8;c--)l++;for(;d<=n;){let c=.025;l>=2?c=.015:p>=.8?c=i===.015?.015:i:p<.4?c=Math.min(.025,i+.005):p>=.4&&p<.6?c=Math.min(.025,i+.004):c=Math.min(.025,i+.002),i=c,p=0,l=0,d+=36e5,a=c}return a},Gi=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 Cn();s.imageCalls||(s.imageCalls=[]);let r=Date.now(),a=Sr(s.imageCalls),i=0;if(a.length>0){let d=a[a.length-1];r>=d.start&&r<d.end&&(i=d.spent)}let p=Hi(s.imageCalls,r);return i+o<=p},qi=async()=>{let e=await Cn();e.imageCalls||(e.imageCalls=[]);let n=Date.now(),t=Sr(e.imageCalls),o=[],s=0,r=0;if(t.length>0){let d=t[t.length-1];n>=d.start&&n<d.end&&(o=d.calls,s=d.spent,r=Math.max(0,Math.ceil((d.end-n)/(60*1e3))))}let a=Hi(e.imageCalls,n),i=Math.max(0,a-s),p=s;return{totalSpent:s,remaining:i,activeCallsCount:o.length,nextResetMin:r,reclaimCost:p,limit:a}},zi=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 Cn();s.imageCalls||(s.imageCalls=[]),s.imageCalls.push({timestamp:Date.now(),cost:o}),Io()};import Vi from"puppeteer";import Xi from"fs";import Ji from"path";import Ki from"os";import to from"path";import Ls from"fs";import{createRequire as yl}from"module";import{fileURLToPath as wl}from"url";var xl=yl(import.meta.url),Yi=to.dirname(wl(import.meta.url));function us(){let e=Ki.platform(),n=Ki.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 r=to.resolve(Yi,"..","..",".puppeteerrc.cjs");if(Ls.existsSync(r)||(r=to.resolve(Yi,"..",".puppeteerrc.cjs")),!Ls.existsSync(r))return{};try{let a=xl(r),i=a.cacheDirectory,p=a.chrome?.version;if(i){if(process.env.PUPPETEER_CACHE_DIR=i,p){let c=to.join(i,"chrome",`${t}-${p}`,s,o);if(Ls.existsSync(c))return{executablePath:c,cacheDirectory:i}}let d=c=>{if(!Ls.existsSync(c))return null;try{let f=Ls.readdirSync(c),u=[];for(let h of f){let g=to.join(c,h),y;try{y=Ls.statSync(g)}catch{continue}if(y.isDirectory())u.push(g);else if(h.toLowerCase()===o.toLowerCase()&&(!p||g.includes(p)))return g}if(p){for(let h of u)if(h.includes(p)){let g=d(h);if(g)return g}}for(let h of u)if(!p||!h.includes(p)){let g=d(h);if(g)return g}}catch{}return null},l=d(i);if(l)return{executablePath:l,cacheDirectory:i}}}catch{}return{}}var Tr=async e=>{let{query:n,limit:t=5,aiMode:o=!1}=O(e);if(!n)return'ERROR: Missing "query" argument for web_search.';let s=3,r=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 i=1;i<=s;i++){let p=null;try{let d=us();p=await Vi.launch({headless:!0,executablePath:d.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let l=await p.newPage();await l.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 l.setViewport({width:1366,height:768});let c=i===1?Math.random()*1e3+500:Math.random()*2e3+1e3;await new Promise(E=>setTimeout(E,c));let f=`https://search.brave.com/ask?q=${encodeURIComponent(a)}&source=web`;await l.goto(f,{waitUntil:"domcontentloaded",timeout:18e4});let u=null,h=45e3,g=Date.now();for(;Date.now()-g<h&&(u=await l.evaluate(()=>{let E=Array.from(document.querySelectorAll('.message:not(.user), .answer-text, .llm-content, [data-type="answer"]')),b="";if(E.length>0&&(b=E.map(ae=>ae.innerText.trim()).filter(Boolean).join(`
|
|
223
|
+
|
|
224
|
+
`)),b||(b=document.body.innerText),b.includes("anomaly"))throw new Error("ANOMALY_DETECTED");let $=!!document.querySelector('.spinner, .loading, .typing, .streaming, [data-streaming="true"], [data-state="loading"], svg.animate-spin, circle[cx], div[class*="spin"]'),I=E[0]||document.body,D=I?I.innerText.trim():"",N=/^(?:[✓✔]\s*)?Finished/i.test(D)||!!(I&&I.querySelector(".status-finished, .finished")),W=!$&&(N||b.includes("Sources:")&&!$),Y={};return document.querySelectorAll("a[href]").forEach(ae=>{let V=ae.getAttribute("href")||ae.href||"";if(V.includes("uddg=")&&(V=decodeURIComponent(V.split("uddg=")[1].split("&")[0])),V.includes("url=")&&(V=decodeURIComponent(V.split("url=")[1].split("&")[0])),V&&(V.startsWith("http://")||V.startsWith("https://"))&&!V.includes("search.brave.com")){let F=ae.innerText.trim();F&&(Y[F]=V),ae.textContent=V}}),{isFinished:W,text:b,hrefMap:Y}}),!(u&&u.isFinished));)await new Promise(E=>setTimeout(E,1e3));let y=(u?u.text:"")||"",m=u?u.hrefMap||{}:{},x="DO NOT INCLUDE ANY TEXT, NOTES, OR EXPLANATIONS AFTER THE SOURCES SECTION.";y.includes(x)&&(y=y.split(x).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 w=y,k="";if(y.includes("Sources:")){let E=y.split("Sources:");w=E[0],k=E.slice(1).join("Sources:")}let C=[];for(let E of w.split(`
|
|
225
|
+
`)){let b=E.trim();b&&(/^(View all|Finished|Searching|Answering|Thinking)$/i.test(b)||/^[\+\-]?\d+$/.test(b)||b.includes("search.brave.com")||b.startsWith("https://www.youtube.com/watch")||b.startsWith("https://youtube.com/watch")||C.push(E))}let R=C.join(`
|
|
226
|
+
`).replace(/^(?:[\+\-]?\d+\s*)+/i,"").replace(/\n{3,}/g,`
|
|
227
|
+
|
|
228
|
+
`).trim(),S=E=>!E||E.includes("search.brave.com")||E.includes("youtube.com")||E.includes("youtu.be"),T="";if(k){let E=k.match(/https?:\/\/[^\s\)\>]+/g)||[],b=[];for(let I of E){let D=I.replace(/[\.\,\;]+$/,""),N=Object.keys(m).find(W=>W.startsWith(D)||D.startsWith(W));N&&m[N]&&(D=m[N]),S(D)||b.push(D)}Object.values(m).forEach(I=>{!S(I)&&!b.includes(I)&&b.push(I)});let $=Array.from(new Set(b));$.length>0&&(T=`Sources:
|
|
229
|
+
`+$.map(I=>`- ${I}`).join(`
|
|
230
|
+
`))}let _=R+(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(r=d,Xi.writeFileSync(Ji.join(gn,"web_tools","search","ai_mode","ERROR.txt"),d.message),p&&await p.close(),i<s){let l=Math.pow(2,i)*1e3;await new Promise(c=>setTimeout(c,l))}}}}for(let a=1;a<=s;a++){let i=null;try{let p=us();i=await Vi.launch({headless:!0,executablePath:p.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let d=await i.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 l=a===1?Math.random()*1e3+500:Math.random()*2e3+1e3;await new Promise(g=>setTimeout(g,l));let c=`https://html.duckduckgo.com/html/?q=${encodeURIComponent(n)}`;await d.goto(c,{waitUntil:"networkidle2",timeout:18e4});let f=await d.$$eval(".result",(g,y)=>g.slice(0,y).map((m,x)=>{let w=m.querySelector(".result__a"),k=m.querySelector(".result__snippet"),C=w?w.href:"";C.includes("uddg=")&&(C=decodeURIComponent(C.split("uddg=")[1].split("&")[0]));let R=w?w.innerText.trim():"No Title",S=k?k.innerText.trim():"No Snippet";return`${x+1}. ${R}
|
|
235
|
+
Source: ${C}
|
|
236
|
+
Snippet: ${S}`}),t);if(f.length===0){if((await d.evaluate(()=>document.body.innerText)).includes("anomaly"))throw new Error("ANOMALY_DETECTED");return await i.close(),`No results found for query: [${n}].`}let u=f.join(`
|
|
237
|
+
|
|
238
|
+
`);return await i.close(),`${o?`AI Mode temporarily failed, used Standard search.
|
|
239
|
+
|
|
240
|
+
`:""}Search results for [${n}]:
|
|
241
|
+
|
|
242
|
+
${u}`}catch(p){if(r=p,i&&await i.close(),Xi.writeFileSync(Ji.join(gn,"web_tools","search","standard_mode","ERROR.txt"),p.message),a<s){let d=Math.pow(2,a)*1e3;await new Promise(l=>setTimeout(l,d))}}}return`ERROR: Search failed after ${s+1} attempts. Last error: ${r.message}`};import bl from"puppeteer";import kl from"turndown";import{gfm as Sl}from"turndown-plugin-gfm";var Rr=async e=>{let n=e;if(typeof e=="object"&&e!==null)n=e.url||e.targetUrl||e.href||"";else if(typeof e=="string"){let r=e.match(/url\s*=\s*["'](.*)["']/);n=r?r[1]:e}let t=typeof n=="string"?n.trim():"";if(!t)return"ERROR: No target URL provided.";let o=3,s=null;for(let r=1;r<=o;r++){let a=null;try{let i=us();a=await bl.launch({headless:!0,executablePath:i.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=r===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 l=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 C=k.attributes;for(let R=C.length-1;R>=0;R--){let S=C[R].name;S!=="href"&&S!=="src"&&k.removeAttribute(S)}});document.querySelector("div, span");)document.querySelectorAll("div, span").forEach(k=>{k.parentNode&&k.replaceWith(...k.childNodes)});document.querySelectorAll("br").forEach(k=>{k.replaceWith(document.createTextNode(`
|
|
243
|
+
|
|
244
|
+
`))});let w=()=>{let k=!1;document.querySelectorAll("*").forEach(C=>{C.childNodes.length===0&&!C.innerText.trim()&&(C.remove(),k=!0)}),k&&w()};return w(),document.body.innerHTML});if(!l)throw new Error("EMPTY_RENDER_RESULT");let c=l.replace(/<br\s*\/?>/gi,`
|
|
245
|
+
|
|
246
|
+
`).replace(/[ \t]+/g," ").replace(/>[ \t]+</g,"><").replace(/\n\s+/g,`
|
|
247
|
+
`).replace(/\n{3,}/g,`
|
|
248
|
+
|
|
249
|
+
`).trim(),f=new kl({headingStyle:"atx",codeBlockStyle:"fenced"});f.use(Sl);let u=f.turndown(c).replace(/\.\s*\n/g,`
|
|
250
|
+
`).replace(/ +/g," ").replace(/\t/g," ").replace(/\n\s+/g,`
|
|
251
|
+
`).replace(/\n{3,}/g,`
|
|
252
|
+
|
|
253
|
+
`),h=u.substring(0,5e4);return await a.close(),`Markdown parsed from [${t}]:
|
|
254
|
+
|
|
255
|
+
${h}${u.length>5e4?`
|
|
256
|
+
|
|
257
|
+
[TRUNCATED AT 50K CHARS]`:""}`}catch(i){if(s=i,a&&await a.close(),r<o){let p=Math.pow(2,r)*1e3;await new Promise(d=>setTimeout(d,p))}}}return`ERROR: Scrape failed after ${o+1} attempts. Last error: ${s.message}`};var Tl=4*(1024*2),Er=async(e,n={})=>{let t=l=>{let c=new RegExp(`${l}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),f=e.match(c);if(f)return f[2].trim();let u=new RegExp(`${l}\\s*[:=]\\s*([^,\\s)]+)`,"s"),h=e.match(u);return h?h[1].trim():null},o=t("action"),s=t("method"),r=t("content"),a=t("content-new"),i=t("content-old"),p=t("id"),d=t("chat-id")||n.chatId||n.sessionId||"default-session";if(o==="temp"){if(!r)return"ERROR: Missing 'content' for temp memory.";let l=ee(nn,{});l[d]||(l[d]=[]),l[d].push(r),ge(nn,l);let c=l[d].reduce((f,u)=>f+u.length,0);return`SUCCESS: Temporary context saved for session [${d}]. (Size: ${c} chars)`}if(o==="user"){let l=ee(Pt,[]).map(c=>(c.score===void 0&&(c.score=.5),c));if(s==="add"){if(!r)return"ERROR: Missing 'content' for memory addition.";let c=new Date,f=`${c.getDate()}/${c.getMonth()+1}/${c.getFullYear()}`,u=r.includes("[Saved on:")?r:`${r.trim()} [Saved on: ${f}]`,h=Tl,g=l.reduce((w,k)=>w+(k.memory?.length||0),0);for(;l.length>0&&g+u.length>h;){let w=l.shift();g-=w.memory?.length||0}let y=t("score"),m=y?parseFloat(y):.5,x={id:`mem-${Date.now().toString(36)}`,memory:u,score:Math.min(2,isNaN(m)?.5:m)};return l.push(x),ge(Pt,l),`SUCCESS: Memory added with ID [${x.id}] and score [${x.score}]. (Vault Size: ${g+u.length} chars)`}if(s==="update"){let c=p||i,f=a||r;if(!c||!f)return"ERROR: Missing 'id' or content for update.";let u=l.findIndex(m=>m.id===c);if(u===-1)return`ERROR: Memory ID [${c}] not found.`;let h=new Date,g=`${h.getDate()}/${h.getMonth()+1}/${h.getFullYear()}`,y=f.includes("[Saved on:")?f:`${f.trim()} [Saved on: ${g}]`;return l[u].memory=y,ge(Pt,l),`SUCCESS: Memory [${c}] updated.`}if(s==="delete"){let c=p||r;if(!c)return"ERROR: Missing 'id' for deletion.";let f=l.length,u=l.filter(h=>h.id!==c);return u.length===f?`ERROR: Memory ID [${c}] not found.`:(ge(Pt,u),`SUCCESS: Memory [${c}] deleted.`)}return`ERROR: Invalid method [${s}] for user memory. Use 'add', 'update', or 'delete'.`}return`ERROR: Unknown action [${o}] for memory tool.`};var _r=async(e,n={})=>{let t=O(e).title,o=n.chatId||n.sessionId;if(!o)return"ERROR: No active chatId found in tool context.";if(!t)return"ERROR: Missing 'title' argument.";try{return await Ni(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 Oo from"fs";import Qi from"path";var no=async(e,n={})=>{let{path:t,StartLine:o,EndLine:s,start_line:r,end_line:a,startLine:i,endLine:p}=O(e),d=parseInt(o||r||i),l=parseInt(s||a||p),c=!isNaN(d),f=!isNaN(l),u=d||1,h=l||(d?d+800:800);if(!t)return'ERROR: Missing "path" argument for view_file.';let g=Qi.resolve(process.cwd(),t);try{if(!Oo.existsSync(g))return`ERROR: File [${t}] does not exist.`;if(Oo.statSync(g).isDirectory())return`ERROR: Path [${t}] is a directory. Use list_files instead.`;let m=Qi.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 w={".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(w[m]){if(!(n.isMultiModal!==!1))return`ERROR: Multimodality is not supported for the current model. Unable to load [${t}].`;let D=Oo.readFileSync(g).toString("base64"),N=w[m];return{text:`[BINARY FILE]: ${t} (${N}) - Loaded as multimodal part.`,binaryPart:{inlineData:{data:D,mimeType:N}}}}let k=Oo.readFileSync(g,"utf8");k.startsWith("\uFEFF")&&(k=k.slice(1)),k=k.replace(/\r\n/g,`
|
|
258
|
+
`).replace(/\r/g,`
|
|
259
|
+
`);let C=k.split(`
|
|
260
|
+
`),R=C.length;!c&&!f&&R>800&&(u=1,h=50);let S=Math.max(0,u-1),T=Math.min(R,h),_=C.slice(S,T),E=`File: [${t}] (Showing lines ${S+1}-${T} of ${R}).`,b=_.map(($,I)=>`${String(S+I+1).padStart(4)}: ${$.trimEnd()}`).join(`
|
|
261
|
+
`);return`${E}
|
|
262
|
+
|
|
263
|
+
${b}`}catch(y){let m=y instanceof Error?y.message:String(y);return`ERROR: Failed to read file [${t}]: ${m}`}};import Ds from"fs";import Zi from"path";var Cr=async(e,n={})=>{let{path:t,content:o}=O(e);if(!t)return'ERROR: Missing "path" argument for write_file.';if(o===void 0)return'ERROR: Missing "content" argument for write_file.';o=o.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
|
|
264
|
+
`).replace(/\r/g,`
|
|
265
|
+
`);let s=Zi.resolve(process.cwd(),t),r=Zi.dirname(s);try{await ht.recordFileChange(s);let a="";if(Ds.existsSync(s))try{a=`Old File contents:
|
|
266
|
+
${Ds.readFileSync(s,"utf8").split(/\r?\n/).map((C,R)=>`${R+1} | ${C}`).join(`
|
|
267
|
+
`)}
|
|
268
|
+
|
|
269
|
+
`}catch{a=`[Note: Could not read existing file for reversal reference]
|
|
270
|
+
|
|
271
|
+
`}Ds.existsSync(r)||Ds.mkdirSync(r,{recursive:!0});let p=(w=>w.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
|
|
272
|
+
`).replace(/\r/g,`
|
|
273
|
+
`))(o),d=p.endsWith(`
|
|
274
|
+
`)?p:p+`
|
|
275
|
+
`,l=d.split(/\r?\n/).length,c=Buffer.byteLength(d,"utf8");Ds.writeFileSync(s,d,"utf8");let f=Ds.readFileSync(s,"utf8"),u=Buffer.byteLength(f,"utf8"),h=f.split(/\r?\n/),g=h.length;if(u===0&&c>0)return f=null,`ERROR: CRITICAL FAILURE: Verification failed. File [${t}] is empty on disk!`;let y="";if(g<=100)y=h.join(`
|
|
276
|
+
`);else{let w=h.slice(0,50).join(`
|
|
277
|
+
`),k=h.slice(-50).join(`
|
|
278
|
+
`);y=`${w}
|
|
279
|
+
|
|
280
|
+
... [${g-100} lines truncated] ...
|
|
281
|
+
|
|
282
|
+
${k}`}f=null;let{systemSettings:m}=await Ft(),x=`SUCCESS: File [${t}] saved.
|
|
283
|
+
- Stats: [${g} lines, ${(u/1024).toFixed(1)} KB]
|
|
284
|
+
${a}- Content Preview:
|
|
285
|
+
|
|
286
|
+
${y}`;if(m?.compressToolResults&&g>60){let w=d.split(/\r?\n/),k=w.slice(0,25).join(`
|
|
287
|
+
`)===h.slice(0,25).join(`
|
|
288
|
+
`),C=w.slice(-25).join(`
|
|
289
|
+
`)===h.slice(-25).join(`
|
|
290
|
+
`);k&&C&&(x=`[[SAME]]
|
|
291
|
+
${x}`)}return x}catch(a){let i=a instanceof Error?a.message:String(a);return`ERROR: Failed to write file [${t}]: ${i}`}};import vr from"fs";import Ll from"path";import Rl from"os";var xn=e=>typeof e!="string"?e:e.length>12?(e+"").replace("",""):e,ea=(e,n)=>{if(!e)return"";let t=/\x1B\[[0-?]*[ -/]*[@-~]/g,o=e.split(`
|
|
292
|
+
`),s=[];if(n<=5)return e;let r=a=>a.replace(t,"").length;return o.forEach(a=>{if(r(a)<=n){s.push(a);return}let p=a.split(/(\s+)/),d="",l=0,c=a.match(/^(\s*)/),f=c?c[1]:"";p.forEach((u,h)=>{if(u.length===0)return;let g=r(u);if(l+g>n)if(d.trim().length>0)s.push(d.trimEnd()),d=f.substring(0,Math.min(f.length,8))+u,l=r(d);else if(t.test(u))s.push(u),d=f,l=r(d);else{let y=u;for(;r(y)>n&&n>10;)s.push(y.substring(0,n)),y=y.substring(n);d=y,l=r(d)}else d+=u,l+=g}),(d.trimEnd().length>0||d===f)&&s.push(d.trimEnd())}),xn(s.join(`
|
|
293
|
+
`))},Ef=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()},_f=(e,n=40)=>{let t=On.replaceAll("\\\\","\\");if(e=e.replace(Rl.homedir(),"~").replace(t,"FluxFlow").replaceAll("\\","/"),!e||e.length<=n)return xn(e);let o=Math.floor((n-3)/2);return xn(e.substring(0,o)+"..."+e.substring(e.length-o).replaceAll("\\","/"))},Lo=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 l=d[2]?parseInt(d[2],10):1;t.add(l)}});let s=Array.from(t).sort((p,d)=>p-d),r=["searchContent","search_content","replaceContent","replace_content","content_to_replace","searchBlock","search_block"],a=["newContent","new_content","content_to_add","newBlock","new_block"],i=(p,d,l)=>{let c,f;for(let u of d){let h=p===1?[`${u}1`,u,`${u}_1`]:[`${u}${p}`,`${u}_${p}`];for(let g of h)if(e[g]!==void 0){c=e[g];break}if(c!==void 0)break}for(let u of l){let h=p===1?[`${u}1`,u,`${u}_1`]:[`${u}${p}`,`${u}_${p}`];for(let g of h)if(e[g]!==void 0){f=e[g];break}if(f!==void 0)break}return{r:c,n:f}};for(let p of s){let{r:d,n:l}=i(p,r,a);if(d!==void 0&&l!==void 0)n.push({replace:d,new:l});else if(d!==void 0||l!==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}},El=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}},Do=(e,n,t={})=>{let o=typeof t=="boolean"?t:!!(t&&t.allowMultiple),s=e.replace(/\r\n/g,`
|
|
296
|
+
`).replace(/\r/g,`
|
|
297
|
+
`),r=m=>m.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
|
|
298
|
+
`).replace(/\r/g,`
|
|
299
|
+
`),a=m=>m.match(/^\s*/)[0],i=m=>{let x=m.split(`
|
|
300
|
+
`).filter(k=>k.trim()!=="");if(x.length===0)return"";let w=a(x[0]);for(let k of x){let C=a(k);C.length<w.length&&(w=C)}return w},p=(m,x,w="")=>{if(!m||x===void 0)return m;let C=/^\t/m.test(x)?" ":" ",R=$=>$.split(`
|
|
301
|
+
`).find(I=>I.trim()!=="")??"",S=R(x).match(/^\s*/)[0].length,T=R(m).match(/^\s*/)[0].length,_=S-T,E=(w.match(/^\s*/)||[""])[0].length;return m.split(`
|
|
302
|
+
`).map(($,I)=>{if($.trim()===""&&I!==0)return"";let D=$.match(/^\s*/)[0].length,N=Math.max(0,D+_);return I===0&&(N=Math.max(0,N-E)),C.repeat(N)+$.trimStart()}).join(`
|
|
303
|
+
`)},d=[];for(let m=0;m<n.length;m++){let x=n[m],w=(x.replace||"").trim(),k=r(x.new||"");if(w.startsWith("^LINE:")&&w.endsWith("$")){let E=w.slice(6,-1).trim().split(".."),b=parseInt(E[0]),$=E[1]!==void 0?parseInt(E[1]):b;if(!isNaN(b)&&!isNaN($)){let I=s.split(`
|
|
304
|
+
`);if(b<1||b>I.length||$<b||$>I.length){d.push({index:m,success:!1,error:`Block ${m+1}: Line range ^LINE:${b}..${$}$ out of bounds (file has ${I.length} lines).`});continue}let N=I.slice(b-1,$).join(`
|
|
305
|
+
`),W=0;for(let Y=0;Y<b-1;Y++)W+=I[Y].length+1;d.push({index:m,success:!0,startPos:W,firstMatchContent:N,content_to_add:k});continue}}let C=r(x.replace||"");if(C===""&&k===""){d.push({index:m,success:!1,error:`Block ${m+1}: Empty replace and add content.`});continue}let R=C.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),S=null;if(C!==""&&s.includes(C))S=new RegExp(R,"g");else{let _=C.split(`
|
|
306
|
+
`).map(E=>E.trim()).filter(E=>E.length>0).map(E=>E.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\s+/g,"\\s*"));if(_.length>0){let E=_.join("\\s*");try{S=new RegExp(E,"g")}catch{S=new RegExp(R,"g")}}else S=new RegExp(R,"g")}let T=[...s.matchAll(S)];if(T.length===0&&C!==""){let _=El(C);_&&(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 l=d.filter(m=>m.success).sort((m,x)=>m.startPos-x.startPos);for(let m=0;m<l.length-1;m++){let x=l[m],w=l[m+1];x.startPos+x.firstMatchContent.length>w.startPos&&(x.success=!1,x.error=`Block ${x.index+1}: Overlaps with another block.`,w.success=!1,w.error=`Block ${w.index+1}: Overlaps with another block.`)}let c=new Map,f=s,u=0,h=0,g=d.filter(m=>m.success).sort((m,x)=>m.startPos-x.startPos);for(let m of g){let x=m.startPos,w=s.substring(0,x).split(`
|
|
307
|
+
`).length,k=x+u,C=w+h,R=f.lastIndexOf(`
|
|
308
|
+
`,k)+1,S=f.substring(R,k),T=p(m.content_to_add,m.firstMatchContent,S),_=f.split(`
|
|
309
|
+
`),E=[];for(let D=Math.max(0,C-4);D<C-1;D++)E.push({num:D+1,text:_[D]});let b=m.firstMatchContent.split(`
|
|
310
|
+
`),$=[],I=C+b.length-1;for(let D=I;D<Math.min(_.length,I+3);D++)$.push({num:D+1,text:_[D]});c.set(m,{success:!0,index:m.index,oldContent:m.firstMatchContent,newContent:T,originalStartLine:w,finalStartLine:C,contextBefore:E,contextAfter:$}),f=f.substring(0,k)+T+f.substring(k+m.firstMatchContent.length),u+=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 x=g.filter(w=>w.index===m);if(x.length>0)for(let w of x)c.has(w)&&y.push(c.get(w));else{let w=d.find(k=>k.index===m);y.push({success:!1,error:w?w.error:`Block ${m+1}: Unknown error.`})}}return{content:f,results:y}},Po=(e,n,t,o=8,s=!1)=>{if(!t||t.length===0)return"";let r=e.split(/\r?\n/),a=n.split(/\r?\n/),i=Math.max(r.length,a.length,1),p=Math.max(4,String(i).length),d=g=>String(g).padStart(p," "),l=`[DIFF_START]
|
|
313
|
+
`,c="\u2550".repeat(88),f=0,u=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(u===null)for(f=Math.max(0,m-4);f<m-1;)l+=`[UI_CONTEXT] ${d(f+1)} |${a[f]||""}
|
|
314
|
+
`,f++;else{let T=u,_=T.originalStartLine+T.oldContent.split(`
|
|
315
|
+
`).length-1;if(g.originalStartLine-_-1>=o){let b=Math.min(a.length,f+3);for(;f<b;)l+=`[UI_CONTEXT] ${d(f+1)} |${a[f]||""}
|
|
316
|
+
`,f++;for(l+=`[UI_CONTEXT] ${c}
|
|
317
|
+
`,f=Math.max(f,m-4);f<m-1;)l+=`[UI_CONTEXT] ${d(f+1)} |${a[f]||""}
|
|
318
|
+
`,f++}else for(;f<m-1;)l+=`[UI_CONTEXT] ${d(f+1)} |${a[f]||""}
|
|
319
|
+
`,f++}let x=g.originalStartLine-1,w=r[x]||"",k=g.oldContent.split(`
|
|
320
|
+
`),C=w.match(/^\s*/),R=C?C[0]:"";k.forEach((T,_)=>{let E=T;if(k.length===1&&w.trim().length>0&&w.includes(T.trim()))E=w;else if(_===0){let b=T.match(/^\s*/);(b?b[0]:"").length<R.length&&w.includes(T.trim())&&(E=R+T.trimStart())}l+=`-${d(g.originalStartLine+_)} |${E}
|
|
321
|
+
`});let S=f;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,_=r[T]||null;if(_!==null){let E=y<h.length-1?(h[y+1].originalStartLine||a.length)+10:a.length;for(let b=f;b<E;b++){if(a[b]===_){S=b;break}b===a.length-1&&(S=a.length)}}else S=a.length}for(;f<S;)l+=`+${d(f+1)} |${a[f]||""}
|
|
323
|
+
`,f++;u=g}),u!==null){let g=Math.min(a.length,f+3);for(;f<g;)l+=`[UI_CONTEXT] ${d(f+1)} |${a[f]||""}
|
|
324
|
+
`,f++}if(s){let g=`[DIFF_START]
|
|
325
|
+
`,y=l.substring(g.length),m=`[UI_CONTEXT] ${c}
|
|
326
|
+
`,w=y.split(m).map(k=>k.split(`
|
|
327
|
+
`).filter(R=>R.trim()!=="").length>45?`[[VERIFIED]]
|
|
328
|
+
${k}
|
|
329
|
+
[[/VERIFIED]]`:k);l=g+w.join(m)}return l+="[DIFF_END]",xn(l)},_l=e=>{if(!e)return null;let n=e.replace("[UI_CONTEXT]","").replace(/\r/g,""),t=n.startsWith("-"),o=n.startsWith("+"),s=t||o?n.substring(1):n,r=s.indexOf("|"),a=r!==-1?xn(s.substring(0,r).trim()):"",i=xn(r!==-1?s.substring(r+1):s);return{isR:t,isA:o,num:a,content:i}},Cl=(e,n)=>{if(!e&&!n)return 1;if(!e||!n)return 0;let t=e.length,o=n.length,s=e,r=n;t<o&&(s=n,r=e);let a=s.length,i=r.length,p=new Int32Array(i+1),d=new Int32Array(i+1);for(let f=0;f<=i;f++)p[f]=f;for(let f=1;f<=a;f++){d[0]=f;let u=s[f-1];for(let h=1;h<=i;h++)u===r[h-1]?d[h]=p[h-1]:d[h]=Math.min(p[h],d[h-1],p[h-1])+1;p.set(d)}let l=p[i],c=Math.max(t,o);return c===0?1:1-l/c},ta=e=>{let n=[],t=[];e.forEach((l,c)=>{l.parsed.isR?n.push({index:c,content:l.parsed.content}):l.parsed.isA&&t.push({index:c,content:l.parsed.content})});let o=n.length,s=t.length;if(o===0||s===0)return;let r=Array.from({length:o+1},()=>Array(s+1).fill(0)),a=Array.from({length:o+1},()=>Array(s+1).fill(""));for(let l=1;l<=o;l++)a[l][0]="up";for(let l=1;l<=s;l++)a[0][l]="left";let i=Array.from({length:o},()=>Array(s).fill(0));for(let l=0;l<o;l++)for(let c=0;c<s;c++)i[l][c]=Cl(n[l].content.trim(),t[c].content.trim());for(let l=1;l<=o;l++)for(let c=1;c<=s;c++){let f=i[l-1][c-1],u=f>=.2?f:-10,h=r[l-1][c-1]+u,g=r[l-1][c],y=r[l][c-1];h>=g&&h>=y?(r[l][c]=h,a[l][c]="diag"):g>=y?(r[l][c]=g,a[l][c]="up"):(r[l][c]=y,a[l][c]="left")}let p=o,d=s;for(;p>0||d>0;)if(a[p][d]==="diag"){if(i[p-1][d-1]>=.2){let c=n[p-1].index,f=t[d-1].index;e[c].pairContent=e[f].parsed.content,e[f].pairContent=e[c].parsed.content}p--,d--}else a[p][d]==="up"?p--:d--},Yn=new Map,ps=new Map,na=200,$r=6,Ar=(e,n)=>{n.set(e.key,e),e.type==="chunk"&&e.blocks&&e.blocks.forEach(t=>Ar(t,n))},Cf=(e,n)=>{if(!e)return{completed:[],active:[]};let t=`${e.id}-${e.text?.length||0}-${n}-${e.isStreaming}-${e.workedDuration||0}`;if(!e.isStreaming&&Yn.has(t))return Yn.get(t);let o=xn(Ol(e.text||"",e.role)),s=`${e.id}-${n}`,r=new Map;if(e.isStreaming){let h=ps.get(s);h&&o.startsWith(h.text)&&(r=h.blocksMap)}let a=(h,g,y,m={})=>{let x=r.get(h);if(x&&x.text===y&&x.type===g&&!!x.isActiveBlock==!!m.isActiveBlock&&!!x.isStreaming==!!m.isStreaming&&x.pairContent===m.pairContent)return x;let w=xn(y),k={...m};return typeof k.pairContent=="string"&&(k.pairContent=xn(k.pairContent)),Array.isArray(k.wrappedLines)&&(k.wrappedLines=k.wrappedLines.map(xn)),{key:h,isStreamingMsg:!!e.isStreaming,workedDuration:e.workedDuration,type:g,text:w,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$/,"")),C=String(k.length).length,R=[],S=null,T=[],_=()=>{if(!T.length)return;let b=T;T=[],R.push(b.length===1?b[0]:{key:`${b[0].key}-chunk`,type:"chunk",blocks:b})},E=n-(C+6);return k.forEach((b,$)=>{let I=$===k.length-1,D=ea(b,E).split(`
|
|
331
|
+
`),N=a(`${e.id||Date.now()}-write-line-${$}`,"write-line",b,{gutterWidth:C,lineNum:$+1,isFirstLine:$===0,isLastLine:I,extension:h,wrappedLines:D});I&&e.isStreaming?(_(),S=N):(T.push(N),T.length>=$r&&_())}),_(),{completed:R,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:_l(S),pairContent:null})),x=[];for(let S=0;S<m.length;S++){let T=m[S];T.parsed&&(T.parsed.isR||T.parsed.isA)?x.push(T):x.length>0&&(ta(x),x=[])}x.length>0&&ta(x);let w=[],k=null,C=[],R=()=>{if(!C.length)return;let S=C;C=[],w.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,E=m[T].parsed,b=null;E&&(b=ea(E.content,n-17).split(`
|
|
333
|
+
`));let $=a(`${e.id||Date.now()}-diff-${T}`,"diff-line",S,{isFirstLine:T===0,isLastLine:_,pairContent:m[T].pairContent,wrappedLines:b});_&&e.isStreaming?(R(),k=$):(C.push($),C.length>=$r&&R())}),R(),{completed:w,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 Yn.set(t,h),h}let i=[],p=null,d=[],l=null,c=()=>{if(!d.length)return;let h=d;d=[],l=null,i.push(h.length===1?h[0]:{key:`${e.id||"x"}-chunk-${h[0].key}`,type:"chunk",blocks:h})},f=(h,g=!1)=>{if(l!==null&&l!==h.type&&c(),d.push(h),l=h.type,d.length>=$r){if(e.isStreaming&&g)return;c()}};if(e.role==="think"){i.push(a(`${e.id}-header`,"think-header",""));let h=o.split(`
|
|
334
|
+
`);h.forEach((g,y)=>{let m=y===h.length-1;f(a(`${e.id}-${y}`,"think-line",g,{}),m)}),e.isStreaming||(c(),i.push({key:`${e.id}-footer-padding`,type:"think-footer-padding",text:""}))}else{let h=o.split(`
|
|
335
|
+
`),g=!1,y=[],m=!1,x="",w=0,k=0;h.forEach((C,R)=>{let S=R===h.length-1,T=C.trim().startsWith("|"),_=C.trim().startsWith("```");m?_?(m=!1,f(a(`${e.id}-code-close-${k}`,"code-fence-close","",{}),S)):(w++,f(a(`${e.id}-code-line-${R}`,"code-line",C,{lineNum:w,lang:x}),S)):_?(m=!0,k=R,w=0,x=C.trim().replace(/^```/,"").trim(),f(a(`${e.id}-code-open-${R}`,"code-fence-open",x,{}),S)):T?(g=!0,y.push(C),S&&(c(),e.isStreaming?p=a(`${e.id}-table-${R}`,"table",y.join(`
|
|
336
|
+
`),{isStreaming:!0}):i.push(a(`${e.id}-table-${R}`,"table",y.join(`
|
|
337
|
+
`),{isStreaming:!1})))):(g&&(c(),i.push(a(`${e.id}-table-${R}`,"table",y.join(`
|
|
338
|
+
`),{isStreaming:!1})),g=!1,y=[]),f(a(`${e.id}-${R}`,"agent-line",C,{}),S))}),!e.isStreaming&&e.workedDuration&&(c(),i.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}:c();let u={completed:i,active:p?[p]:[]};if(e.isStreaming){let h=new Map;if(i.forEach(g=>Ar(g,h)),p&&Ar(p,h),ps.set(s,{text:o,blocksMap:h}),ps.size>na){let g=ps.keys().next().value;ps.delete(g)}}else{if(Yn.set(t,u),Yn.size>na){let h=Yn.keys().next().value;Yn.delete(h)}ps.delete(s)}return u},$l={},Ml=/(\r?\n){2}(?=\[?(?:tool:functions|tool\.functions|agent:generalist|agent\.generalist|\s*turn\s*:))/gi,Mr=(e,n)=>{let t=!1;for(let o=0;o<n;o++)e[o]==="`"&&(t=!t);return t},Al=/\[SYSTEM\][\s\S]*?\[\/SYSTEM\]|\[ANSWER\][\s\S]*?(?:\[\/ANSWER\]|$)|\[TOOL RESULT\]:?\s*|^\s*(SUCCESS|ERROR):.*(\r?\n)?|\[\s*turn\s*:\s*(continue|finish)\s*\]|\[\[END\]\]|\[\s*turn\s*:?.*?$|\n\s*turn\s*:?.*?$|\[\s*(?:turn|ANSWER|TOOL).*?$|\n\nResponded on .*|\n\n\[Prompted on: .*\]|@\[TerminalName:.*?, ProcessId:.*?\]/gm,vl=/(\$?\\?\/?\\rightarrow\$?|\$\\rightarrow\$)|(\$?\\?\/?\\leftarrow\$?|\$\\leftarrow\$)|(\$?\\?\/?\\uparrow\$?|\$\\uparrow\$)|(\$?\\?\/?\\downarrow\$?|\$\\downarrow\$)|(\$?\\?\/?\\leftrightarrow\$?|\$\\leftrightarrow\$)/gi,Il=/\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,Ps=!1,Ol=(e,n="agent")=>{if(!e)return e;let t=n===!0||n==="think",o=n===!1||n==="agent",s=e.replace(/<\|channel>thought/gi,"<think>").replace(/<channel\|>/gi,"</think>");if(t)return s.replace(/^<(think|thought|thoughts)>/gi,"").replace(/<\/(think|thought|thoughts)>$/gi,"").replace(/^\r?\n+/,"").replace(/\r?\n+$/,"");let r=s;o&&(r=r.replace(Ml,(p,d,l,c)=>!Ps&&Mr(c,l)?p:""),r&&r.includes("[tool:")&&(r=r.replace(/<(\w+)(?:[^>]*)>\s*([\s\S]*?\[tool:[^\]]*\][\s\S]*?)\s*<\/\1>/gi,(p,d,l)=>l&&l.includes("[tool:")?l.trim():p),Ps&&(r=r.replace(/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi,(p,d)=>d.includes("[tool:")?d.trim():p))));let a="tool:functions.",i="agent:generalist.";if(o&&(r.toLowerCase().includes(a)||r.toLowerCase().includes(i)))for(;;){let p=r.toLowerCase(),d=p.indexOf(a),l=p.indexOf(i),c=a,f=d;if((d===-1||l!==-1&&l<d)&&(c=i,f=l),f===-1)break;if(!Ps&&Mr(r,f)){let k=f+c.length,C=p.indexOf(a,k),R=p.indexOf(i,k);if(C===-1&&R===-1)break;let S=-1,T=0;for(;;){let _=p.indexOf(a,T),E=p.indexOf(i,T),b=-1,$=a;if(_===-1&&E===-1)break;if(_===-1||E!==-1&&E<_?(b=E,$=i):b=_,!Mr(r,b)){S=b,c=$;break}T=b+$.length}if(S===-1)break;f=S}let u=f,h=!1,g=f-1;for(;g>=0&&/\s/.test(r[g]);)g--;g>=0&&r[g]==="["&&(u=g,h=!0);let y=0,m=!1,x=null,w=f;for(;w<r.length;){let k=r[w];if(!x&&(k==="'"||k==='"'||k==="`")?x=k:x&&k===x&&r[w-1]!=="\\"&&(x=null),x||(k==="("?(y++,m=!0):k===")"&&y--),m&&y===0&&!x){let C=w;if(h){let R=w+1;for(;R<r.length&&/\s/.test(r[R]);)R++;R<r.length&&r[R]==="]"&&(C=R)}r=r.substring(0,u)+r.substring(C+1);break}if(w++,w===r.length)return m&&y>0&&(r=r.substring(0,u)),r}}return r=r.replace(Al,""),r=r.replace(vl,p=>{let d=p.toLowerCase();return d.includes("leftrightarrow")?"\u2194":d.includes("rightarrow")?"\u2192":d.includes("leftarrow")?"\u2190":d.includes("uparrow")?"\u2191":d.includes("downarrow")?"\u2193":p}),r=r.replace(Il,p=>$l[p.toLowerCase()]||p),r.trim()},$f=()=>{Yn.clear(),ps.clear()};var Ir=async(e,n={})=>{let t=O(e),o=t.path;if(!o)return'ERROR: Missing "path" argument for PatchFile.';let{patchPairs:s,allowMultiple:r,error:a}=Lo(t);if(a)return`ERROR: ${a}`;if(s.length===0)return"ERROR: No valid replacement pairs found. Use searchContent1, newContent1, etc.";let i=t.allowMultiple!==void 0?t.allowMultiple===!0||String(t.allowMultiple).toLowerCase()==="true":r,p=Ll.resolve(process.cwd(),o);try{if(!vr.existsSync(p))return`ERROR: File [${o}] does not exist. Use WriteFile instead.`;let d=n.forcedContent||vr.readFileSync(p,"utf8");d.startsWith("\uFEFF")&&(d=d.slice(1));let l=d.replace(/\r\n/g,`
|
|
339
|
+
`).replace(/\r/g,`
|
|
340
|
+
`),{content:c,results:f}=Do(l,s,{allowMultiple:i}),u=f.filter(m=>!m.success),h=f.filter(m=>m.success);if(h.length===0)return`ERROR: Patch Failed to apply to [${o}].
|
|
341
|
+
${u.map(m=>` \u2022 ${m.error}`).join(`
|
|
342
|
+
`)}`;await ht.recordFileChange(p,l),vr.writeFileSync(p,c,"utf8");let{systemSettings:g}=await Ft(),y=Po(l,c,f,12,g?.compressToolResults);return u.length>0?`SUCCESS: File [${o}] updated with some blocks failed. [${h.length}/${s.length}] blocks applied.
|
|
343
|
+
|
|
344
|
+
Failures:
|
|
345
|
+
${u.map(m=>` \u2022 ${m.error}`).join(`
|
|
346
|
+
`)}
|
|
347
|
+
|
|
348
|
+
${y}`:`SUCCESS: File [${o}] updated. [${f.length}/${s.length}] blocks applied.
|
|
349
|
+
|
|
350
|
+
${y}`}catch(d){let l=d instanceof Error?d.message:String(d);return`ERROR: Failed to update file [${o}]: ${l}`}};import hs from"fs";import Or from"path";var Dl=new Set([".git","node_modules",".gemini","dist","build",".next","out",".cache","bin","obj","vendor","venv",".idea",".gradle",".terraform","target","coverage",".vscode",".svn",".hg",".fslckout",".github",".gitlab",".circleci",".gitea",".gitee",".lerna",".changeset",".nx",".npm",".yarn",".pnpm-store",".expo",".nuxt",".svelte-kit",".docusaurus",".turbo",".vercel","bower_components",".netlify",".vuepress",".quasar",".output",".angular","jspm_packages",".parcel-cache",".rollup.cache",".rspack",".vitepress","__pycache__",".pytest_cache",".mypy_cache",".tox",".poetry","env","vhdl",".ipynb_checkpoints",".jupyter",".conda",".pdm-build",".bundle",".yardoc",".metadata","App_Data","ClientBin",".cargo",".rustc_info",".go","Godeps","_vendor",".rake_tasks","CMakefiles",".wakatime",".dart_tool",".fvm",".cocoapods","Pods",".pub-cache",".symlinks","DerivedData",".xcworkspace",".serverless",".aws",".gcloud",".azure",".kube",".vagrant",".docker","postgres-data","redis-data","mongo-data",".Spotlight-V100",".Trashes","$RECYCLE.BIN","System Volume Information",".DocumentRevisions-V100",".fseventsd","AppData","Application Data","Local","LocalLow","Roaming","$WinREAgent","$WINDOWS.~BT","$WINDOWS.~WS","scw","System32","SysWOW64",".AppleDouble",".AppleDB",".AppleDesktop","_CodeSignature",".cmio",".LSOverride",".localized",".TemporaryItems",".Trash",".Trash-0",".Trash-1000",".gvfs",".local",".config",".dbus",".fontconfig",".snap",".var",".lost+found","lost+found",".thumb",".thumbnails","EFI","boot","grub","logs","log",".nyc_output",".sonar",".ruff_cache",".VSCodeCounter"]),Pl=e=>Dl.has(e)||e.startsWith(".pnpm"),Fl=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"}},Lr=async e=>{let n=O(e),t=n.path||null;if(!t)return"ERROR: No directory path provided.";let o=1;if(n.recurse!==void 0&&n.recurse!==null)if(typeof n.recurse=="number")o=n.recurse;else if(typeof n.recurse=="boolean")o=n.recurse?2:1;else{let r=parseInt(String(n.recurse).trim(),10);o=isNaN(r)?1:r}o=Math.max(1,Math.min(3,o));let s=Or.resolve(process.cwd(),t);try{if(!hs.existsSync(s))return`ERROR: Path [${t}] does not exist.`;if(!hs.statSync(s).isDirectory())return`ERROR: Path [${t}] is a file, not a directory. Use ReadFile instead.`;if(o===1){let g=hs.readdirSync(s),y=g.length,m=150,x=g.slice(0,m),w=[];for(let R of x){let S=Or.join(s,R),T={name:R,type:"unknown",size:"N/A",mtime:"N/A"};try{let _=hs.statSync(S);T={name:R,type:_.isDirectory()?"directory":"file",size:(_.size/1024).toFixed(1)+"KB",mtime:Fl(_.mtime)}}catch{T.type="inaccessible"}w.push(T)}let k=w.map(R=>R.type==="directory"?`${R.name}/`:`${R.name} (${R.size}, ${R.mtime})`).join(`
|
|
351
|
+
`),C=`
|
|
352
|
+
|
|
353
|
+
(Total items in folder: ${y})`;return y>m&&(C=`
|
|
354
|
+
|
|
355
|
+
TRUNCATED: Showing first ${m} of ${y} items.`),g.length=0,x.length=0,w.length=0,`Detailed folder stats for [${t}]:
|
|
356
|
+
|
|
357
|
+
${k}${C}`}let a=0,i=0,p=0,d=500,l=!1,c=(g,y,m=1)=>{if(y>o||l)return[];let x=[];try{x=hs.readdirSync(g)}catch{return[`${" ".repeat(m-1)}[Inaccessible Directory]`]}let w=[],k=[];for(let T of x){let _=Or.join(g,T),E=!1;try{E=hs.statSync(_).isDirectory()}catch{}E?w.push({name:T,fullPath:_}):k.push({name:T,fullPath:_})}w.sort((T,_)=>T.name.localeCompare(_.name)),k.sort((T,_)=>T.name.localeCompare(_.name));let C=[],R=" ".repeat(m-1);for(let T of w){if(p>=d){l=!0,C.push(`${R}[Truncated - Maximum item limit reached (${d})]`);break}if(p++,a++,C.push(`${R}${T.name}/`),y<o&&!Pl(T.name)){let _=c(T.fullPath,y+1,m+1);C.push(..._)}}let S=[];for(let T of k){if(p>=d){l=!0,C.push(`${R}[Truncated - Maximum item limit reached (${d})]`);break}p++,i++;let _="N/A";try{_=(hs.statSync(T.fullPath).size/1024).toFixed(1)+"KB"}catch{}S.push(`${T.name} (${_})`)}return S.length>0&&C.push(`${R}${S.join("; ")}`),C},u=c(s,1,1).join(`
|
|
358
|
+
`),h=`
|
|
359
|
+
|
|
360
|
+
(Total items scanned: ${p}, Directories: ${a}, Files: ${i})`;return l&&(h=`
|
|
361
|
+
|
|
362
|
+
TRUNCATED: Scan capped at ${d} items. (Directories: ${a}, Files: ${i})`),`Detailed directory tree for [${t}] (recursive depth: ${o}):
|
|
363
|
+
|
|
364
|
+
${u}${h}`}catch(r){let a=r instanceof Error?r.message:String(r);return`ERROR: Failed to read folder [${t}]: ${a}`}};var Fo=async(e,n)=>{let t=O(e),{question:o}=t;if(!o)return'ERROR: Missing "question" argument for ask.';if(!n.onAskUser)return"ERROR: onAskUser callback not provided in tool context.";let s=[];Object.keys(t).forEach(r=>{if(r.startsWith("option")){let a=t[r];if(typeof a=="string"&&a.includes("::")){let[i,p]=a.split("::");s.push({id:r,label:i.trim(),description:p.trim()})}else s.push({id:r,label:String(a).trim(),description:""})}});try{return`USER CHOOSE: ${await n.onAskUser(o,s)}`}catch(r){return`ERROR: Failed to get user input: ${r instanceof Error?r.message:String(r)}`}};import Nl from"puppeteer";import Fs from"path";import ms from"fs-extra";import{PDFDocument as Bl}from"pdf-lib";var Dr=async e=>{let{path:n,content:t,orientation:o="portrait",margin:s="0px"}=O(e);if(!n)return'ERROR: Missing "path" argument for write_pdf.';if(!t)return'ERROR: Missing "content" (HTML/CSS) for write_pdf.';let r=Fs.resolve(process.cwd(),n),a=null;try{await ms.ensureDir(Fs.dirname(r)),await ht.recordFileChange(r);let i=us();a=await Nl.launch({headless:!0,executablePath:i.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let p=await a.newPage(),d=t,l={},c=async S=>{if(!S||S.startsWith("http://")||S.startsWith("https://")||S.startsWith("data:"))return null;try{let T=Fs.resolve(process.cwd(),S);if(await ms.pathExists(T)){let _=Fs.extname(T).toLowerCase().replace(".","")||"png",E=_==="jpg"?"jpeg":_==="svg"?"svg+xml":_,b=await ms.readFile(T,"base64");return`data:image/${E};base64,${b}`}}catch{}return null},f=/<link[^>]+href=["']([^"']+)["']/gi,u={},h;for(;(h=f.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 _=Fs.resolve(process.cwd(),S);if(await ms.pathExists(_)){let E=await ms.readFile(_,"utf-8");u[T]=`<style>${E}</style>`}}catch{}}for(let[S,T]of Object.entries(u))d=d.split(S).join(T);let g=/<img[^>]+src=["']([^"']+)["']/gi;for(;(h=g.exec(d))!==null;){let S=h[1];if(S&&!l[S]){let T=await c(S);T&&(l[S]=T)}}let y=/url\(\s*['"]?([^'")]+?)['"]?\s*\)/gi;for(;(h=y.exec(d))!==null;){let S=h[1].trim();if(S&&!l[S]){let T=await c(S);T&&(l[S]=T)}}for(let[S,T]of Object.entries(l)){let _=S.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&"),E=new RegExp(`(src=["'])(${_})(["'])`,"gi");d=d.replace(E,`$1${T}$3`);let b=new RegExp(`url\\(\\s*(['"]?)(${_})\\1\\s*\\)`,"gi");d=d.replace(b,`url($1${T}$1)`)}let m=`
|
|
365
|
+
<style>
|
|
366
|
+
@page {
|
|
367
|
+
margin: ${s};
|
|
368
|
+
}
|
|
369
|
+
body {
|
|
370
|
+
margin: 0;
|
|
371
|
+
padding: 0;
|
|
372
|
+
font-family: system-ui, -apple-system, sans-serif;
|
|
373
|
+
}
|
|
374
|
+
* { box-sizing: border-box; }
|
|
375
|
+
.watermark {
|
|
376
|
+
position: fixed;
|
|
377
|
+
top: 50%;
|
|
378
|
+
left: 50%;
|
|
379
|
+
transform: translate(-50%, -50%) rotate(-50deg);
|
|
380
|
+
font-size: 52px;
|
|
381
|
+
font-weight: bold;
|
|
382
|
+
color: rgba(0, 0, 0, 0.005);
|
|
383
|
+
pointer-events: none;
|
|
384
|
+
z-index: -1000;
|
|
385
|
+
text-align: center;
|
|
386
|
+
width: 150%;
|
|
387
|
+
white-space: nowrap;
|
|
388
|
+
text-transform: uppercase;
|
|
389
|
+
letter-spacing: 5px;
|
|
390
|
+
}
|
|
391
|
+
</style>
|
|
392
|
+
<div class="watermark">Generated by FluxFlow CLI (AI)</div>
|
|
393
|
+
${d}
|
|
394
|
+
`;await p.setContent(m,{waitUntil:"networkidle0",timeout:18e4});let x=await p.pdf({format:"A4",landscape:String(o).toLowerCase()==="landscape",margin:{top:s,right:s,bottom:s,left:s},printBackground:!0}),w=await Bl.load(x),k=Fs.basename(n);w.setTitle(`FluxFlow_${k}`),w.setAuthor("FluxFlow CLI"),w.setSubject("Generated with Agentic AI System"),w.setKeywords(["FluxFlow","AI","Agentic","Automated"]),w.setCreator("FluxFlow PDF Engine"),w.setProducer("FluxFlow (Generative AI)");let C=await w.save();await ms.writeFile(r,C);let R=await ms.stat(r);return`SUCCESS: PDF generated successfully at [${n}] (${(R.size/1024).toFixed(2)} KB).`}catch(i){let p=i instanceof Error?i.message:String(i);return`ERROR: Failed to generate PDF [${n}]: ${p}`}finally{a&&await a.close()}};import sa from"fs-extra";import Pr from"path";import Ul from"html-to-docx";var Fr=async e=>{let{path:n,content:t}=O(e);if(!n)return'ERROR: Missing "path" argument for write_docx.';if(!t)return'ERROR: Missing "content" (HTML) for write_docx.';let o=Pr.resolve(process.cwd(),n);try{await sa.ensureDir(Pr.dirname(o)),await ht.recordFileChange(o);let s=Pr.basename(n),r=t.includes("<html")?t:`
|
|
395
|
+
<!DOCTYPE html>
|
|
396
|
+
<html lang="en">
|
|
397
|
+
<head>
|
|
398
|
+
<meta charset="UTF-8">
|
|
399
|
+
<title>FluxFlow Document</title>
|
|
400
|
+
</head>
|
|
401
|
+
<body>
|
|
402
|
+
${t}
|
|
403
|
+
</body>
|
|
404
|
+
</html>
|
|
405
|
+
`,a=await Ul(r,null,{title:`FluxFlow_${s}`,creator:"FluxFlow CLI",description:"Generated by Agentic AI System",table:{row:{cantSplit:!0}},footer:!0,pageNumber:!0});return await sa.writeFile(o,a),`SUCCESS: Word document [${n}] generated successfully.
|
|
406
|
+
- Size: ${(a.length/1024).toFixed(1)} KB`}catch(s){let r=s instanceof Error?s.message:String(s);return`ERROR: Failed to generate DOCX [${n}]: ${r}`}};import Br from"fs/promises";import gs from"path";import Nr from"fast-glob";import{Minimatch as oa}from"minimatch";async function so(e,n,t=e,o=1){if(o>12)return[];let s=[],r;try{r=await Br.readdir(e,{withFileTypes:!0})}catch{return[]}for(let a of r){let i=gs.join(e,a.name),p=gs.relative(t,i),d=p.split(gs.sep).map(f=>f.toLowerCase()),l=a.name.toLowerCase();if(!n.some(f=>{let u=f.toLowerCase();return u.startsWith(".")&&l.endsWith(u)?!0:d.some(h=>h===u||h.startsWith(".pnpm"))}))if(a.isDirectory()){let f=await so(i,n,t,o+1);s=s.concat(f)}else a.isFile()&&s.push({fullPath:i,relativePath:p})}return s}function Wl(e,n,t=1/0){if(e===n)return 0;if(e.length===0)return n.length;if(n.length===0)return e.length;if(Math.abs(e.length-n.length)>t)return t+1;let o=Array.from({length:n.length+1},(s,r)=>r);for(let s=1;s<=e.length;s++){let r=[s],a=s;for(let i=1;i<=n.length;i++){let p=e[s-1]===n[i-1]?0:1,d=Math.min(r[i-1]+1,o[i]+1,o[i-1]+p);r.push(d),d<a&&(a=d)}if(o=r,a>t)return t+1}return o[n.length]}function jl(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),r=o.split(/[^a-z0-9]+/).filter(a=>a.length>1||o.length===1&&a.length>0);return r.length===0?!1:r.every(a=>{let i=a.length<=2?0:a.length<=5?1:2;for(let p of s)if(p.includes(a)||a.length>=3&&p.length>=3&&Math.abs(p.length-a.length)<=i&&Wl(a,p,i)<=i)return!0;return!1})}var oo=async e=>{let{keyword:n,path:t,fuzzy:o,subString:s,regex:r}=O(e);if(n==null)return'ERROR: Missing "keyword" argument.';let a=String(n),i=g=>g===!0||g==="true"||g===1||g==="1"||g==="yes",p=r===!1||r==="false"||r===0||r==="0"||r==="no",d=r===!0||r==="true"||r===1||r==="1"||r==="yes",l=i(o)||i(s),c=null,f=null;if(p)l||(f=new RegExp(`(?<![\\w])${a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\\w])`,"i"));else{try{c=new RegExp(a,"i")}catch(g){if(d)return`ERROR: Invalid regex pattern "${a}": ${g.message}`}f=new RegExp(`(?<![\\w])${a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\\w])`,"i")}let u=[".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 I=t.split(";").map(W=>W.trim()).filter(Boolean),D=I.some(W=>W.startsWith("!"));if(I.some(W=>Nr.isDynamicPattern(W)||/[*?{}[\]()|+]/.test(W))){m="glob";let W=t.replace(/\\/g,"/"),Y=I.map(F=>F.replace(/\\/g,"/")),ae=u.map(F=>F.startsWith(".")?`**/*${F}`:`**/${F}/**`);if(D&&!I.some(F=>!F.startsWith("!"))){let F=await so(y,u,y),U=A=>A.endsWith("/")?A+"**":A,oe=Y.filter(A=>A.startsWith("!")).map(A=>U(A.slice(1))),ve=Y.filter(A=>!A.startsWith("!")).map(U);g=F.filter(A=>{let B=A.relativePath.replace(/\\/g,"/"),X=ve.length===0||ve.some(We=>{try{return new oa(We).match(B)}catch{return!1}}),J=oe.some(We=>{try{return new oa(We).match(B)}catch{return!1}});return X&&!J})}else{let F=Y.some(oe=>/[\(\)\|]|\.\*/.test(oe)),U=[];if(!F)try{U=await Nr(Y,{cwd:y,ignore:ae,dot:!0,onlyFiles:!0,absolute:!1})}catch{U=[]}if(U.length===0&&(F||Nr.isDynamicPattern(W))){let oe=W.match(/^([^\*\?\(\)\|\[\]\s]+)\//),ve=oe&&!/[\*\?\(\)\|\[\]]/.test(oe[1])?gs.resolve(y,oe[1]):y,A=await so(ve,u,y);try{let B=W.replace(/^\.\//,"");B=B.replace(/\.\*\/(\\.|[^\/])/g,".*$1"),!B.startsWith("^")&&!B.startsWith(".*")&&(B=`.*${B}`);let X=new RegExp(B.endsWith("$")?B:`${B}$`,"i");g=A.filter(J=>{let We=J.relativePath.replace(/\\/g,"/");return X.test(We)})}catch{g=[]}}else g=U.map(oe=>({fullPath:gs.resolve(y,oe),relativePath:oe}))}}else{let W=t.replace(/[\/\\]+$/,""),Y=gs.resolve(y,W);try{let ae=await Br.stat(Y);if(ae.isDirectory())m="dir",g=await so(Y,u,y);else if(ae.isFile())m="file",g.push({fullPath:Y,relativePath:gs.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 so(y,u);let x=g.map(async I=>{try{let D=await Br.readFile(I.fullPath,"utf-8");if(D.includes("\0"))return[];let N=D.split(/\r?\n/),W=[];for(let ae=0;ae<N.length;ae++)(l?N[ae].toLowerCase().includes(a.toLowerCase())||jl(N[ae],a):p?f&&f.test(N[ae]):c&&c.test(N[ae])||f&&f.test(N[ae]))&&W.push({line:ae+1,content:N[ae].trim()});return W.length===0?null:{path:I.relativePath.replace(/\\/g,"/"),matches:W}}catch{return[]}}),w=await Promise.all(x),k=[],C=0;for(let I of w){if(!I||!I.matches)continue;if(C>=h)break;let D=h-C,N=I.matches.slice(0,D);k.push({path:I.path,matches:N}),C+=N.length}typeof global.gc=="function"&&global.gc();let R=l?"(fuzzy mode)":d?"(regex mode)":p?"(keyword mode)":"(standard mode)";if(k.length===0){let I=m==="file"?` in '${t}'`:m==="dir"||m==="glob"?` in '${t}'`:". Try to specify files",D=m==="dir"?"[DIR]":m==="glob"?"[GLOB]":"";return`${D}${D?" ":""}Found 0 matches of '${a}'${I}${R?` ${R}`:""}`}let S=R?` ${R}`:"",T=`${k.length} file${k.length===1?"":"s"}`,_=`${C} match${C===1?"":"es"}`,E;m==="file"?E=`Found ${_} of '${a}' in '${t}'${S}:`:m==="dir"||m==="glob"?E=`Found ${_} of '${a}' in '${t}' across ${T}${S}:`:E=`Found ${_} of '${a}' across ${T}${S}:`;let b=m==="dir"?"[DIR]":m==="glob"?"[GLOB]":"",$=`${b}${b?" ":""}${E}
|
|
407
|
+
|
|
408
|
+
`;for(let I of k){$+=`${I.path}
|
|
409
|
+
`;for(let D of I.matches)$+=` ${D.line}: ${D.content}
|
|
410
|
+
`;$+=`
|
|
411
|
+
`}return $.trimEnd()}catch(g){return`ERROR: ${g.message}`}};import ra from"fs-extra";import Ur from"path";var Hl=(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 i=a;for(let p=0;p<8;p++)i&1?i=3988292384^i>>>1:i=i>>>1;o[a]=i}let s=a=>{let i=4294967295;for(let p=0;p<a.length;p++)i=o[(i^a[p])&255]^i>>>8;return(i^4294967295)>>>0},r=(a,i)=>{let p=Buffer.from(a,"ascii"),d=Buffer.from(i,"utf-8"),l=p.length+1+d.length,c=Buffer.alloc(8+l+4);c.writeUInt32BE(l,0),c.write("tEXt",4,"ascii"),p.copy(c,8),c[8+p.length]=0,d.copy(c,8+p.length+1);let f=s(c.subarray(4,8+l));return c.writeUInt32BE(f,8+l),c};for(let[a,i]of Object.entries(n))i!=null&&t.push(r(a,String(i)));if(t.length===0)return e;if(e.subarray(12,16).toString("ascii")==="IHDR"){let i=e.subarray(0,33),p=e.subarray(33);return Buffer.concat([i,...t,p])}return e}catch{return e}},Wr=async(e,n={})=>{let t=O(e),o=t.prompt||t.text,s=t.path||t.outputPath||t.output||"generated_image.png",r=t.ratio;if(!o)return'ERROR: Missing "prompt" argument for generate_image.';let a=["nsfw","naked","nudity","nude","porn","sex","xxx","erotic","gore","bloody","violence","abuse","suicide","murder","hentai","pedophile","rape"],i=o.toLowerCase();if(a.some(d=>i.includes(d)))return"ERROR: Prompt blocked by system safety filter (inappropriate or unsafe content detected).";try{let d=await Ft();if(!await Gi(d))return`ERROR: Insufficient Quota for selected quality. Either tell user reduce quality or wait for next refresh cycle (${(await qi()).nextResetMin||60}m).`;let c=d.imageSettings||{keyType:"Default",quality:"Low-High",apiKey:""},f=c.keyType==="Custom"&&c.apiKey?c.apiKey:FALLBACK_IMAGE_KEY,h={Low:"flux","Low-High":"zimage",Medium:"gptimage","Medium-High":"gptimage",High:"qwen-image",Ultra:"gptimage-large",Premium:"nanobanana-pro"}[c.quality]||"zimage",g=1024,y=1024;if(r){let D=r.replace(/\s+/g,"");D==="16:9"?(g=1024,y=576):D==="9:16"?(g=576,y=1024):D==="4:3"?(g=1024,y=768):D==="3:4"?(g=768,y=1024):D==="1:1"&&(g=1024,y=1024)}let m=Math.floor(Math.random()*1e7),w=`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(w,{method:"GET",headers:{Authorization:`Bearer ${f}`}});if(!k.ok){let D=k.status,N="";try{N=await k.text()}catch{}return D===402||N.includes("Insufficient balance")||N.includes("PAYMENT_REQUIRED")?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed with status [${D}]: ${N||"Unknown API Error"}`}if((k.headers.get("content-type")||"").includes("application/json")){let D=await k.json();return D.status===402||D.error&&D.error.code==="PAYMENT_REQUIRED"?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed: ${D.error?.message||JSON.stringify(D)}`}let R=await k.arrayBuffer(),S=Buffer.from(R),T={Title:o,Description:"Generated via FluxFlow CLI",Software:"FluxFlow CLI",Author:"FluxFlow","Creation Time":new Date().toISOString(),Prompt:o,Model:`Fluxflow:${h}`,Ratio:r||"1:1",Seed:String(m)};S=Hl(S,T);let _=Ur.resolve(process.cwd(),s);await ra.ensureDir(Ur.dirname(_)),await ht.recordFileChange(_),await ra.writeFile(_,S),await zi(d);let E=Ur.extname(s).toLowerCase(),$={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".webp":"image/webp"}[E]||"image/png";return n.isMultiModal!==!1?{text:`SUCCESS: Image successfully generated from prompt [${o}] and saved to [${s}]. Output attached to multimodal part`,binaryPart:{inlineData:{data:S.toString("base64"),mimeType:$}}}:`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 ro=async(e,n={})=>{let t=r=>{let a=new RegExp(`${r}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),i=e.match(a);return i?i[2].trim():null},o=t("id"),s=t("summary");if(!o||!s)return"ERROR: Missing 'id' or 'summary' for saveSummary tool.";try{let r=ee(nn,{}),a=ee(Ln,{});return a[o]=s,delete r[o],ge(Ln,a),ge(nn,r),`SUCCESS: Saved summary and purged raw memories for chat [${o}].`}catch(r){let a=r instanceof Error?r.message:String(r);return`ERROR: Failed to save summary for chat [${o}]: ${a}`}};var Ns=async(e,n={})=>{let o=(s=>{let r=new RegExp(`${s}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),a=e.match(r);return a?a[2].trim():null})("id");if(!o)return"ERROR: Missing 'id' parameter for addMemScore tool.";try{let s=ee(Pt,[]),r=!1,a=[];for(let l of s)l.score===void 0&&(l.score=.5),l.id===o?(l.score=Math.min(2,l.score+.2),r=!0):(l.score*=.98,l.score<.05&&(l.score=0)),l.score=Math.round(l.score*1e5)/1e5,l.score>0&&a.push(l);if(ge(Pt,a),!r)return`WARNING: Memory ID [${o}] not found. Other memories decayed by -0.01.`;let i=a.find(l=>l.id===o),p=i?i.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 r=s instanceof Error?s.message:String(s);return`ERROR: Failed to adjust memory score for [${o}]: ${r}`}};import Hr from"fs-extra";import ws from"path";import{createRequire as zl}from"module";import ys from"fs-extra";import jr from"path";import Gl from"https";var ia={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 ql(e,n=null){let t=n||`https://unpkg.com/tree-sitter-wasms@0.1.13/out/${e}`,o=jr.join(ds,e);return await ys.ensureDir(ds),new Promise((s,r)=>{let a={headers:{"User-Agent":"FluxFlow-Agent"}};Gl.get(t,a,i=>{if([301,302,307,308].includes(i.statusCode)&&i.headers.location){let d=i.headers.location;if(!d.startsWith("http")){let l=new URL(t);d=`${l.protocol}//${l.host}${d}`}ql(e,d).then(s).catch(r);return}if(i.statusCode!==200){r(new Error(`Failed to download ${e}: HTTP ${i.statusCode}`));return}let p=ys.createWriteStream(o);i.pipe(p),p.on("finish",()=>{p.close(),s()})}).on("error",i=>{ys.existsSync(o)&&ys.unlink(o,()=>{}),r(i)})})}function _u(e){let n=jr.join(ds,e);return ys.existsSync(n)}async function Cu(e){let n=jr.join(ds,e);ys.existsSync(n)&&await ys.unlink(n)}var ca=zl(import.meta.url),aa=ca("web-tree-sitter"),la=!1,da=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"]),fa=new Set(["export_statement","lexical_declaration","variable_declaration","variable_declarator","pair","assignment_expression"]);function bn(e,n=50){if(!e)return"";let t=e.replace(/\s+/g," ").trim();return t.length>n?t.substring(0,n-3)+"...":t}function ua(e){let n=e.type;if(n==="if_statement"){let o=e.childForFieldName("condition");return o?`if (${bn(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?bn(o.text,40):""})`}if(n==="for_statement"||n==="for_in_statement"||n==="for_of_statement"){let s=e.text.split(`
|
|
412
|
+
`)[0].match(/for\s*(?:await\s*)?\((.*)\)/);return s?`for (${bn(s[1],40)})`:"for"}if(n==="switch_statement"){let o=e.childForFieldName("value");return`switch (${o?bn(o.text,40):""})`}if(n==="try_statement")return"try";if(n==="catch_clause")return"catch";if(n==="element"||n==="script_element"||n==="style_element"||n==="jsx_element"||n==="jsx_self_closing_element"){let o=e.childForFieldName("opening_element")||e.childForFieldName("start_tag")||e.children.find(r=>r.type==="start_tag")||e,s=o.childForFieldName("name")||o.childForFieldName("tag_name")||o.children.find(r=>r.type==="tag_name");return s?`<${bn(s.text,30)}>`:null}if(["import_declaration","import_from_statement","import_statement","preproc_include"].includes(n))return bn(e.text.split(`
|
|
413
|
+
`)[0],60);if(n==="pair"){let o=e.childForFieldName("key");return o?bn(o.text.replace(/["']/g,""),40):null}if(n==="assignment_expression"){let o=e.childForFieldName("left");return o?`${bn(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?bn(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 bn(o.text,40)}return bn(t.text,40)}if(["arrow_function","function_expression","function_declaration"].includes(n)){let o=e.parent;for(;o&&o.type!=="program";){let s=ua(o);if(s)return s;if(!fa.has(o.type))break;o=o.parent}}return null}function Kl(e){let n=[];function t(o){for(let s of o.children)da.has(s.type)?n.push(s):t(s)}return t(e),n}function Yl(e){return e.replace(/_([a-z])/g,n=>n[1].toUpperCase())}function pa(e,n=0,t=!0,o="",s=null,r=12){let a=e.type,i=ua(e),p=da.has(a)||n===0,d=Kl(e),l=p&&n>0&&(fa.has(a)&&d.length>0||i!==null&&i===s&&d.length>0),c="",f=o,u=n,h=s;if(p&&!l){let g=e.startPosition.row+1,y=e.endPosition.row+1,m=Yl(a),x=i?`${m} [${i}]`:m;n===0?(c+=`\u{1F4C1} ROOT (Lines: ${g}-${y})
|
|
414
|
+
`,f=o):(c+=`${o}${t?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 "}${x} (Lines: ${g}-${y})
|
|
415
|
+
`,f+=t?" ":"\u2502 "),u=n+1,h=i}return u>r&&d.length>0?c+=`${f}\u2514\u2500\u2500 ... depth exceeded ...
|
|
416
|
+
`:d.forEach((g,y)=>{let m=y===d.length-1;c+=pa(g,u,l?t&&m:m,f,h,r)}),c}var Gr=async e=>{let n;try{n=O(e).path}catch{return`ERROR: Failed to parse arguments: ${e}`}if(!n)return'ERROR: No file path provided. Use [tool:functions.FileMap(path="...")]';let t=ws.isAbsolute(n)?n:ws.resolve(process.cwd(),n);if(!Hr.existsSync(t))return`ERROR: File not found: ${n}`;let o=ws.extname(t).slice(1).toLowerCase(),s=ia[o];if(!s)return`ERROR: Unsupported file extension: .${o}`;let r=ws.resolve(ds,s);if(!Hr.existsSync(r))return`ERROR: Parser for .${o} not found. Please download it in Settings > Other.`;try{let a=aa.Parser;if(!la){let h;try{h=ws.join(ws.dirname(ca.resolve("web-tree-sitter")),"tree-sitter.wasm")}catch{h=ws.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}),la=!0}let i=new a,p=await aa.Language.load(r);i.setLanguage(p);let d=await Hr.readFile(t,"utf8"),l=d.split(`
|
|
417
|
+
`).length,c=12;l>1e4?c=2:l>=8e3?c=3:l>=5e3?c=5:l>=4e3?c=8:l>2e3&&(c=10);let f=i.parse(d),u=pa(f.rootNode,0,!0," ",null,c);return`\u{1F4C4} File Map for: ${n}
|
|
418
|
+
${u}`}catch(a){let i=a instanceof Error?a.message:typeof a=="object"?JSON.stringify(a):String(a),p=a instanceof Error?`
|
|
419
|
+
Stack: ${a.stack}`:"";return`ERROR: Failed to map file: ${i}${p}`}};import Vn from"fs";import ha from"path";var io=async(e,n={})=>{let{method:t,tasks:o,markDone:s}=O(e),r=n.chatId||"default";if(!t)return'ERROR: Missing "method" argument for todo tool (create/append/get).';let a=ha.join(On,"plan",r),i=ha.join(a,"todo.md"),p=c=>{if(!c||Array.isArray(c))return c;let f=String(c).trim();if(f.startsWith("[")&&f.endsWith("]")){let u=f.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);return u?u.map(h=>h.slice(1,-1).replace(/\\(.)/g,"$1")):f.slice(1,-1).split(",").map(h=>h.trim()).filter(Boolean)}return c},d=c=>{let f=p(c);return f?(Array.isArray(f)?f:String(f).split(`
|
|
420
|
+
`)).map(h=>{let g=String(h).trim();return g?g.startsWith("- [ ]")||g.startsWith("- [x]")||g.startsWith("- [X]")?g:`- [ ] ${g}`:null}).filter(Boolean).join(`
|
|
421
|
+
`)+`
|
|
422
|
+
`:""},l=(c,f)=>{if(!f)return{content:c,markedCount:0};let u=p(f),h=(Array.isArray(u)?u:[u]).map(x=>String(x).replace(/^- \[[xX ]\]\s*/i,"").trim()).filter(Boolean),g=c.split(`
|
|
423
|
+
`),y=0,m=!1;for(let x of h){let w=!1;for(let k=0;k<g.length;k++)if(g[k].includes(x)&&/^- \[\s\]/.test(g[k].trim())){g[k]=g[k].replace("- [ ]","- [x]"),w=!0,m=!0,y++;break}if(!w){for(let k=0;k<g.length;k++)if(g[k].toLowerCase().includes(x.toLowerCase())&&/^- \[\s\]/.test(g[k].trim())){g[k]=g[k].replace("- [ ]","- [x]"),w=!0,m=!0,y++;break}}}return{content:m?g.join(`
|
|
424
|
+
`):c,markedCount:y}};try{if(Vn.existsSync(a)||Vn.mkdirSync(a,{recursive:!0}),t==="create"){if(!o)return'ERROR: Missing "tasks" for create method.';let c=d(o),f=0;if(s){let h=l(c,s);c=h.content,f=h.markedCount}await ht.recordFileChange(i),Vn.writeFileSync(i,c,"utf8");let u=c.split(/\r?\n/).map(h=>h.trim()).filter(h=>h.startsWith("- [ ]")||h.startsWith("- [x]")||h.startsWith("- [X]")).length;if(f>0){let h=c.split(/\r?\n/).map(g=>g.trim()).filter(g=>g.startsWith("- [x]")||g.startsWith("- [X]")).length;return`SUCCESS: TASK LIST CREATED (${f} marked done, ${h} completed, ${u-h} left)
|
|
425
|
+
${c}`}return`SUCCESS: TASK LIST CREATED (${u} total)
|
|
426
|
+
${c}`}if(t==="append"){if(!o)return'ERROR: Missing "tasks" for append method.';let c=d(o);await ht.recordFileChange(i),Vn.appendFileSync(i,c,"utf8");let f=Vn.readFileSync(i,"utf8"),u=f.split(/\r?\n/).map(m=>m.trim()),h=u.filter(m=>m.startsWith("- [ ]")||m.startsWith("- [x]")||m.startsWith("- [X]")).length,g=u.filter(m=>m.startsWith("- [x]")||m.startsWith("- [X]")).length,y=c.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)
|
|
427
|
+
${f}`}if(t==="get"){if(!Vn.existsSync(i))return"TODO GET: No task list found for this session.";let c=Vn.readFileSync(i,"utf8"),f=0;if(s){let m=l(c,s);m.markedCount>0&&(c=m.content,f=m.markedCount,await ht.recordFileChange(i),Vn.writeFileSync(i,c,"utf8"))}let u=c.split(/\r?\n/).map(m=>m.trim()),h=u.filter(m=>m.startsWith("- [ ]")||m.startsWith("- [x]")||m.startsWith("- [X]")).length,g=u.filter(m=>m.startsWith("- [x]")||m.startsWith("- [X]")).length;return`${f>0?`SUCCESS: ${f} TASK(S) MARKED DONE`:"TODO GET"}: ${g} Completed, ${h-g} left
|
|
428
|
+
${c}`}return`ERROR: Unknown method "${t}". Use create, append, or get.`}catch(c){return`ERROR: Todo tool failure: ${c instanceof Error?c.message:String(c)}`}};var qr=async(e,n={})=>{let{runSubagent:t}=await import("./ai-MUATXJWY.js"),o=O(e),s=o.task||o.instruction||o.prompt,r=o.model||null,a=o.tools||null;if(!s)return'ERROR: Missing "task" argument for invokeSync.';let i=null;if(a)try{let d=a.trim();d.startsWith("[")&&d.endsWith("]")&&(d=d.substring(1,d.length-1)),i=d.split(",").map(l=>l.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,r,i,50);return n.onVisualFeedback&&n.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${p} [COMPLETED]
|
|
429
|
+
`),d}catch(d){let{isTerminationSignaled:l}=await import("./ai-MUATXJWY.js"),c=d.message==="Subagent task was cancelled by user."||l();if(n.onVisualFeedback){let f=c?"[CANCELLED]":"[FAILED]";n.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${p} ${f}
|
|
430
|
+
`)}return`ERROR: Subagent execution failed: ${d.message}`}};var ma=async(e,n={})=>{let{runSubagent:t}=await import("./ai-MUATXJWY.js"),o=O(e),s=o.task||o.instruction||o.prompt,r=o.model||null,a=o.title||null,i=o.tools||null;if(!s)return'ERROR: Missing "task" argument for invoke.';let p=null;if(i)try{let m=i.trim();m.startsWith("[")&&m.endsWith("]")&&(m=m.substring(1,m.length-1)),p=m.split(",").map(x=>x.trim().replace(/^["']|["']$/g,"")).filter(Boolean)}catch{}let d=`subagent-${Date.now()}-${Math.floor(Math.random()*1e3)}`,l=null,c=null,f=new Promise((m,x)=>{l=m,c=x}),u={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&&u.pendingSteerMessages.push(m)},completionPromise:f,_resolveCompletion:l,_rejectCompletion:c,progress:[]},h={chunks:[],totalWords:0};Ve.push(u),n.onSubagentUpdate&&n.onSubagentUpdate();let g=[],y={...n,taskId:d,onAskMain:async m=>{let x=`q-${Date.now()}-${Math.floor(Math.random()*1e3)}`,w=null,k=new Promise(S=>{w=S}),C={id:x,question:m,answered:!1,answer:null,askedAt:Date.now(),_resolve:w};return u.questions.push(C),u.status="waiting",n.onSubagentUpdate&&n.onSubagentUpdate(),Ro(`[SYSTEM] Background subagent "${u.title}" is WAITING FOR YOUR INPUT: "${m}"
|
|
431
|
+
Respond using tool: [tool:functions.Answer(id="${d}", answer="...")]
|
|
432
|
+
[/SYSTEM]`),await k},onVisualFeedback:m=>{u.lastChunkTime=Date.now();let x=m.replace(/\x1b\[[0-9;]*m/g,""),w=x.match(/[✔✘✗✖🔍📖→➕↻•]\s*([A-Za-z0-9\s-]+)/);w?u.currentTool=w[1].trim():u.currentTool=x,n.onSubagentUpdate&&n.onSubagentUpdate()},onTokenChunk:(m,x)=>{let w=Date.now();if(u.lastChunkTime=w,u.currentTool="Thinking",typeof x=="number"&&x>0){h.totalWords+=x,h.chunks.push({time:w,words:x});let k=w-400;if(h.chunks=h.chunks.filter(C=>C.time>=k),h.chunks.length>0){let C=h.chunks.reduce((T,_)=>T+_.words,0),R=h.chunks[0].time,S=Math.max(.4,(w-R)/1e3);u.wps=Math.round(C/S*10)/10}}n.onSubagentUpdate&&n.onSubagentUpdate()}};return t(s,y,r,p,50,m=>{if(u.status==="cancelled")return;if(m.startsWith("[Subagent Turn")&&g.length>0&&(u.progress.push([...g]),g=[]),m.includes("[Executing Tool]")){let w=m.match(/\[Executing Tool\]\s*([a-zA-Z0-9_]+)/);w&&(!u.currentTool||u.currentTool==="Thinking")&&(u.currentTool=w[1])}let x=m;if(x.startsWith("[Tool Result]")){let w=x.split(`
|
|
433
|
+
`);w.length>5&&(x=w.slice(0,4).join(`
|
|
434
|
+
`)+`
|
|
435
|
+
... [Content/Diff Truncated from Logs] ...`)}g.push(x),n.onSubagentUpdate&&n.onSubagentUpdate()},!0).then(m=>{if(u.status==="cancelled"){u._resolveCompletion&&u._resolveCompletion(m);return}g.length>0&&(u.progress.push([...g]),g=[]),u.status="completed",u.finalAnswer=m,n.onSubagentUpdate&&n.onSubagentUpdate(),Ro(`[SYSTEM] Background subagent "${u.title}" (id: ${d}) has FINISHED. Call GetProgress(id="${d}") to see the final result. [/SYSTEM]`),u._resolveCompletion&&u._resolveCompletion(m)}).catch(async m=>{let{isTerminationSignaled:x}=await import("./ai-MUATXJWY.js");if(m.message==="Subagent task was cancelled."||u.status==="cancelled"||x()){u.status="cancelled",g.push("[SUBAGENT CANCELLED] Task was cancelled."),u.progress.push([...g]),n.onSubagentUpdate&&n.onSubagentUpdate(),u._resolveCompletion&&u._resolveCompletion(null);return}g.push(`[SUBAGENT FAILURE] Error: ${m.message}`),u.progress.push([...g]),u.status="failed",u.error=m.message,n.onSubagentUpdate&&n.onSubagentUpdate(),Ro(`[SYSTEM] Background subagent "${u.title}" (id: ${d}) FAILED with error: ${m.message}. [/SYSTEM]`),u._rejectCompletion&&u._rejectCompletion(m)}),`SUCCESS: Background subagent started. Task ID: ${d}`};var zr=async(e,n={})=>{let o=O(e).id;if(!o)return'ERROR: Missing "id" argument for getProgress.';let s=Ve.find(i=>i.id===o);if(!s)return`ERROR: Subagent task with ID [${o}] not found.`;let r=`Subagent Task Status: ${s.status.toUpperCase()}
|
|
436
|
+
`;if(r+=`Title: ${s.title}
|
|
437
|
+
`,r+=`Task: ${s.task}
|
|
438
|
+
`,s.startedAt){let i=Math.floor((Date.now()-s.startedAt)/1e3);r+=`Elapsed Time: ${i}s
|
|
439
|
+
`}if(r+=`Turns Completed: ${s.progress.length}
|
|
440
|
+
`,(s.status==="running"||s.status==="waiting")&&(s.currentTool&&(r+=`Current Tool: ${s.currentTool}
|
|
441
|
+
`),s.wps>0&&(r+=`TPS: ${s.wps}
|
|
442
|
+
`)),s.questions&&s.questions.length>0){let i=s.questions.filter(p=>!p.answered);i.length>0&&(r+=`
|
|
443
|
+
**PENDING QUESTION**
|
|
444
|
+
`,i.forEach(p=>{r+=`"${p.question}"
|
|
445
|
+
`}),r+=`Respond using tool: [tool:functions.Answer(id="${s.id}", answer="...")]
|
|
446
|
+
|
|
447
|
+
`)}return r+=`
|
|
448
|
+
Progress Log:
|
|
449
|
+
`,s.progress.forEach((i,p)=>{r+=`--- Turn ${p+1} ---
|
|
450
|
+
`;let l=i.filter(c=>!c.startsWith("[SUBAGENT SUCCESS]")).map(c=>{if(c.startsWith("[Subagent Response]")){let f="[Subagent Response]",h=c.substring(f.length),g="tool:functions.";for(;;){let m=h.toLowerCase().indexOf(g);if(m===-1)break;let x=m,w=!1,k=m-1;for(;k>=0&&/\s/.test(h[k]);)k--;k>=0&&h[k]==="["&&(x=k,w=!0);let C=0,R=!1,S=null,T=m;for(;T<h.length;){let _=h[T];if(!S&&(_==="'"||_==='"'||_==="`")?S=_:S&&_===S&&h[T-1]!=="\\"&&(S=null),S||(_==="("?(C++,R=!0):_===")"&&C--),R&&C===0&&!S){let E=T;if(w){let b=T+1;for(;b<h.length&&/\s/.test(h[b]);)b++;b<h.length&&h[b]==="]"&&(E=b)}h=h.substring(0,x)+h.substring(E+1);break}if(T++,T===h.length){h=h.substring(0,x);break}}}return f+`
|
|
451
|
+
`+h.trim()}return c.startsWith("[Executing Tool]")&&c.length>256?c.substring(0,256)+"...[truncated from logs]":c});r+=l.join(`
|
|
452
|
+
`)+`
|
|
453
|
+
|
|
454
|
+
`}),s.status==="completed"&&s.finalAnswer?r+=`Final Answer:
|
|
455
|
+
${s.finalAnswer}
|
|
456
|
+
`:s.status==="failed"&&s.error&&(r+=`Failure Error: ${s.error}
|
|
457
|
+
`),r.replace(/\r\n/g,`
|
|
458
|
+
`).replace(/\n{3,}/g,`
|
|
459
|
+
|
|
460
|
+
`).trim().replace(/\[TOOL RESULT\]/gi,"TOOL RESULT:")};var ga=async(e,n={})=>{let o=O(e).id;if(!o)return'ERROR: Missing "id" argument for cancel.';let s=Ve.find(r=>r.id===o);return s?s.status==="completed"||s.status==="failed"?`INFO: Subagent task with ID [${o}] has already finished with status [${s.status.toUpperCase()}].`:s.status==="cancelled"?`INFO: Subagent task with ID [${o}] is already cancelled.`:(s.status="cancelled",n.onSubagentUpdate&&n.onSubagentUpdate(),`SUCCESS: Subagent task with ID [${o}] has been cancelled.`):`ERROR: Subagent task with ID [${o}] not found.`};import bt from"fs-extra";import Rt from"path";var Vl=["node_modules","dist","bin","logs",".git",".fluxflow","secret",".gemini",".agents","tmp","temp","build","out","snapshots"];async function ao(e,n=e){let t={},o=await bt.readdir(e,{withFileTypes:!0}).catch(()=>[]);for(let s of o){if(Vl.includes(s.name))continue;let r=Rt.join(e,s.name),a=Rt.relative(n,r).replace(/\\/g,"/");if(s.isDirectory()){let i=await ao(r,n);Object.assign(t,i)}else{let i=await bt.stat(r).catch(()=>null);i&&(t[a]={size:i.size,mtime:i.mtimeMs})}}return t}async function ya(e,n){await bt.ensureDir(e);for(let t of Object.keys(n)){let o=Rt.join(process.cwd(),t),s=Rt.join(e,t);await bt.ensureDir(Rt.dirname(s)),await bt.copyFile(o,s).catch(()=>{})}}async function Kr(e,n,t=null,o=null){if(!await bt.pathExists(e))return;o||(o=e);let s=await bt.readdir(e,{withFileTypes:!0}).catch(()=>[]);for(let r of s){let a=Rt.join(e,r.name),i=Rt.join(n,r.name);if(r.isDirectory())await Kr(a,i,t,o);else{let p=Rt.relative(o,a).replace(/\\/g,"/"),d=await bt.pathExists(i);d&&await bt.chmod(i,438).catch(()=>{}),await bt.ensureDir(Rt.dirname(i));let l=await bt.copyFile(a,i).then(()=>!0).catch(()=>!1);await bt.chmod(i,438).catch(()=>{}),t&&(l?d?t.replaced++:t.restored++:t.failed.push(p))}}}var Xn={async takeInitialSnapshot(e){try{let n=Rt.join(On,"snapshots",e);await bt.remove(n).catch(()=>{}),await bt.ensureDir(n);let t=await ao(process.cwd());await ya(Rt.join(n,"initial"),t);let o=ee(yn,{});o[e]={initialManifest:t,currentManifest:t,checkpoints:[{id:"initial",timestamp:new Date().toISOString(),newFiles:[],modifiedFiles:[],deletedFiles:[],toolsUsed:[]}]},ge(yn,o)}catch{}},async recordTurnDelta(e,n,t=[]){try{let o=ee(yn,{}),s=o[e];if(!s)return;let r=s.currentManifest||s.initialManifest,a=await ao(process.cwd()),i=[],p=[],d=[];for(let[c,f]of Object.entries(a)){let u=r[c];u?(u.size!==f.size||u.mtime!==f.mtime)&&p.push(c):i.push(c)}for(let c of Object.keys(r))a[c]||d.push(c);let l=[...i,...p];if(l.length>0||d.length>0){let c={};for(let u of l)c[u]=a[u];let f=Rt.join(On,"snapshots",e,`turn_${n}`);await ya(f,c)}s.checkpoints.push({id:`turn_${n}`,timestamp:new Date().toISOString(),newFiles:i,modifiedFiles:p,deletedFiles:d,toolsUsed:t}),s.currentManifest=a,ge(yn,o)}catch{}},async getCheckpoints(e){try{let t=ee(yn,{})[e];return t?t.checkpoints||[]:[]}catch{return[]}},async rollbackToCheckpoint(e,n){try{let t=ee(yn,{}),o=t[e];if(!o)throw new Error("No session active for Advance Rollback.");let s=o.checkpoints||[],r=s.findIndex(l=>l.id===n);if(r===-1)throw new Error(`Checkpoint [${n}] not found.`);let a=Rt.join(On,"snapshots",e),i={restored:0,replaced:0,failed:[]},p=await ao(process.cwd());for(let l of Object.keys(p)){let c=Rt.join(process.cwd(),l);await bt.chmod(c,438).catch(()=>{}),await bt.remove(c).catch(()=>{})}let d=Rt.join(a,"initial");await Kr(d,process.cwd(),i,d);for(let l=1;l<=r;l++){let c=s[l],f=Rt.join(a,c.id);if(await Kr(f,process.cwd(),i,f),c.deletedFiles&&c.deletedFiles.length>0)for(let u of c.deletedFiles){let h=Rt.join(process.cwd(),u);await bt.chmod(h,438).catch(()=>{}),await bt.remove(h).catch(()=>{})}}return o.checkpoints=s.slice(0,r+1),o.currentManifest=await ao(process.cwd()),ge(yn,t),{checkpointId:n,stats:i}}catch(t){throw new Error(`Rollback failed: ${t.message}`)}},async getLatestFileChanges(e){try{let t=ee(yn,{})[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=Rt.join(On,"snapshots",e);await bt.remove(n).catch(()=>{});let t=ee(yn,{});t[e]&&(delete t[e],ge(yn,t))}catch{}}};var Yr=async(e,n={})=>{let t=O(e),o=t.method,s=t.id,r=n.chatId;if(!n.systemSettings?.advanceRollback)return"ERROR: Advance Rollback feature is currently disabled in settings under Security. Tell user to enable it.";if(!r)return"ERROR: No active chat transaction found for rollback.";if(o==="getCheckpoint"){let i=await Xn.getCheckpoints(r);if(i.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:"AskUser",ask_user:"AskUser",AskUser:"AskUser",askuser:"AskUser",invoke:"Invoke",invokesync:"InvokeSync",getprogress:"GetProgress",cancel:"Cancel",emergency_rollback:"EmergencyRollback",emergencyrollback:"EmergencyRollback"},d=c=>p[c]||p[c.toLowerCase()]||c,l=`Available checkpoints for rollback:
|
|
461
|
+
|
|
462
|
+
`;for(let c of i)if(c.id==="initial")l+=`--- Initial State (id: initial) ---
|
|
463
|
+
Tools Used: User Prompted for task
|
|
464
|
+
|
|
465
|
+
`;else{let f=c.id.replace("turn_",""),u=c.toolsUsed&&c.toolsUsed.length>0?c.toolsUsed.map(d).join(", "):"None";l+=`--- Turn ${f} (id: ${c.id}) ---
|
|
466
|
+
Tools Used: ${u}
|
|
467
|
+
|
|
468
|
+
`}return l.trim()}else if(o==="forceRevert"){if(!s)return"ERROR: Missing required parameter 'id' for forceRevert.";try{let i=await Xn.rollbackToCheckpoint(r,s),{checkpointId:p,stats:d}=i,l=d.restored+d.replaced+d.failed.length,c=`SUCCESS: Repository rolled back to checkpoint [${p}].
|
|
469
|
+
|
|
470
|
+
`;return c+=`Stats:
|
|
471
|
+
`,c+=` Restored : ${d.restored} file${d.restored!==1?"s":""} (new to workspace)
|
|
472
|
+
`,c+=` Replaced : ${d.replaced} file${d.replaced!==1?"s":""} (overwritten)
|
|
473
|
+
`,c+=` Failed : ${d.failed.length} file${d.failed.length!==1?"s":""}`,d.failed.length>0&&(c+=`
|
|
474
|
+
${d.failed.join(`
|
|
475
|
+
`)}`),c+=`
|
|
476
|
+
\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-
|
|
477
|
+
`,c+=` Total : ${l} file${l!==1?"s":""} processed`,c}catch(i){return`ERROR: ${i.message}`}}else return`ERROR: Invalid method "${o}". Use "getCheckpoint" or "forceRevert".`};var Bs=async(e,n={})=>{let t=O(e),o=t.id,s=parseInt(t.timeout||t.time||"120",10);if((isNaN(s)||s<=0)&&(s=120),s>300&&(s=300),!o)return t.time?(await new Promise(p=>setTimeout(p,s*1e3)),`SUCCESS: Waited for ${s}s.`):'ERROR: Missing "id" argument for Await.';let r=Ve.find(p=>p.id===o);if(!r)return`ERROR: Subagent task with ID [${o}] not found.`;if(r.status==="completed")return`SUCCESS: Subagent task [${o}] completed.
|
|
478
|
+
Final Answer:
|
|
479
|
+
${r.finalAnswer||"(No output)"}`;if(r.status==="failed")return`ERROR: Subagent task [${o}] failed.
|
|
480
|
+
Error: ${r.error||"Unknown error"}`;if(r.status==="cancelled")return`INFO: Subagent task [${o}] was cancelled.`;let a,i=new Promise(p=>{a=setTimeout(()=>{p({type:"timeout"})},s*1e3)});try{let p=await Promise.race([r.completionPromise.then(()=>({type:"completion"})),i]);return clearTimeout(a),p.type==="timeout"?`TIMEOUT: Subagent task [${o}] is still running (status: ${r.status.toUpperCase()}) after ${s}s. You can continue other work or call Await again.`:r.status==="completed"?`SUCCESS: Subagent task [${o}] completed.
|
|
481
|
+
Final Answer:
|
|
482
|
+
${r.finalAnswer||"(No output)"}`:r.status==="failed"?`ERROR: Subagent task [${o}] failed.
|
|
483
|
+
Error: ${r.error||"Unknown error"}`:r.status==="cancelled"?`INFO: Subagent task [${o}] was cancelled.`:`INFO: Subagent task [${o}] status changed to ${r.status.toUpperCase()}.`}catch(p){return clearTimeout(a),`ERROR: Exception while awaiting subagent [${o}]: ${p.message}`}};var Us=async(e,n={})=>{let t=O(e),o=t.id,s=t.answer||t.response;if(!o)return'ERROR: Missing "id" argument for Answer.';if(!s)return'ERROR: Missing "answer" argument for Answer.';let r=Ve.find(i=>i.id===o);if(!r)return`ERROR: Subagent task with ID [${o}] not found.`;if(!r.questions||r.questions.length===0)return`INFO: Subagent task [${o}] has no pending questions.`;let a=r.questions.filter(i=>!i.answered);return a.length===0?`INFO: Subagent task [${o}] has no unanswered questions.`:(a.forEach(i=>{i.answered=!0,i.answer=s,i.answeredAt=Date.now(),i._resolve&&i._resolve(s)}),r.status="running",n.onSubagentUpdate&&n.onSubagentUpdate(),`SUCCESS: Answer provided to subagent task [${o}]. Subagent execution resumed.`)};var lo=async(e,n={})=>{let t=O(e),o=t.id,s=t.message||t.instruction||t.text||t.prompt;if(!o)return'ERROR: Missing "id" argument for Steer.';if(!s)return'ERROR: Missing "message" argument for Steer.';let r=Ve.find(a=>a.id===o);return r?r.status==="completed"||r.status==="failed"||r.status==="cancelled"?`ERROR: Cannot steer subagent task [${o}] because it has already finished with status [${r.status.toUpperCase()}].`:(typeof r.steer=="function"?r.steer(s):(r.pendingSteerMessages||(r.pendingSteerMessages=[]),r.pendingSteerMessages.push(s)),n.onSubagentUpdate&&n.onSubagentUpdate(),`SUCCESS: Steering instruction injected into subagent task [${o}]. It will be processed on the subagent's turn.`):`ERROR: Subagent task with ID [${o}] not found.`};import{mouse as un,keyboard as Nt,Button as co,Key as L,Point as fo,clipboard as Xl}from"@nut-tree-fork/nut-js";un.config.autoDelayMs=50;Nt.config.autoDelayMs=50;async function Vr(){try{await Nt.releaseKey(L.LeftControl,L.RightControl,L.LeftAlt,L.RightAlt,L.LeftShift,L.RightShift,L.LeftSuper,L.RightSuper)}catch{}}async function Pn(e,n,t={}){let o=await Xs(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 un.setPosition(new fo(o.x,o.y)),`SUCCESS: Moved mouse to grid target ${typeof n=="string"?n:`(${o.x}, ${o.y})`}`;case"click":{await un.setPosition(new fo(o.x,o.y));let s=t.button==="right"?co.RIGHT:t.button==="middle"?co.MIDDLE:co.LEFT;return t.clickType==="double"?await un.doubleClick(s):await un.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 Xs(t.from||n),r=await Xs(t.to);return!s||!r?'ERROR: Drag requires valid "from" and "to" target coordinates/grid codes.':(await un.setPosition(new fo(s.x,s.y)),await un.pressButton(co.LEFT),await un.setPosition(new fo(r.x,r.y)),await un.releaseButton(co.LEFT),`SUCCESS: Dragged mouse from (${s.x}, ${s.y}) to (${r.x}, ${r.y})`)}case"scroll":{let s=o||await Xs({x:640,y:360});s&&(await un.setPosition(new fo(s.x,s.y)),await new Promise(p=>setTimeout(p,60)));let r=parseInt(t.amount,10);(isNaN(r)||r<=0)&&(r=5);let a=r>50?Math.min(20,Math.max(1,Math.round(r/100))):Math.min(20,r),i=t.direction==="up";for(let p=0;p<a;p++)i?await un.scrollUp(120):await un.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 wa={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},xa=e=>{if(!e)return;let n=String(e).toLowerCase().trim();if(wa[n]!==void 0)return wa[n];if(L[e]!==void 0)return L[e];if(L[n.toUpperCase()]!==void 0)return L[n.toUpperCase()]};async function Fn(e,n,t={}){try{switch(e.toLowerCase()){case"type":{if(typeof n!="string")return"ERROR: Type action requires a valid string input";await Vr(),await Xl.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 Vr(),t.autoPressEnter?(await new Promise(r=>setTimeout(r,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=xa(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=>xa(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 Vr(),`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 uo=async(e,n={})=>{let t=O(e),o=t.action||t.type||t.cmd,s=t.target||t.grid||t.gridCode||t.location||t.input;if(!o)return'ERROR: Missing required "action" argument for computer_action (e.g. move, click, drag, scroll, type, key_press, key_combination).';let r=o.toLowerCase();if(r.startsWith("mouse_")||["move","click","drag","scroll"].includes(r)){let a=r.replace("mouse_","");return await Pn(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(r.startsWith("key_")||r==="type"||r==="press"){let a=r;r==="press"&&(a="key_press");let i=t.autoPressEnter===!0||t.autoPressEnter==="true"||t.enter===!0||t.enter==="true";return await Fn(a,s||t.text||t.keys,{...t,autoPressEnter:i})}return`ERROR: Unrecognized action "${o}". Supported actions: move, click, drag, scroll, type, key_press, key_combination.`};import Ta from"screenshot-desktop";import ho from"sharp";import ba from"fs-extra";import ka from"path";import"@nut-tree-fork/nut-js";async function Xr(e,n,t){if(!(!process.env.SHOW_DEBUG_GRID&&!process.env.DEBUG_OCR))try{let o=ka.resolve(process.cwd(),"screenshots",e);await ba.ensureDir(o),await ba.writeFile(ka.join(o,n),t)}catch{}}function Jl(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,r)=>r);for(let s=1;s<=e.length;s++){let r=[s],a=s;for(let i=1;i<=n.length;i++){let p=e[s-1]===n[i-1]?0:1,d=Math.min(r[i-1]+1,o[i]+1,o[i-1]+p);r.push(d),d<a&&(a=d)}if(o=r,a>t)return t+1}return o[n.length]}function Zl(e){return e<=4?0:e<=8?1:2}async function Jr(e,n=3){let t=await ho(e).metadata();return ho(e).resize(Math.round(t.width*n),Math.round(t.height*n),{kernel:"lanczos3"}).greyscale().normalise().toBuffer()}function ec(e){if(!e)return{words:[],lines:[]};let n=[],t=new Map;for(let s of e.split(`
|
|
484
|
+
`)){let r=s.split(" ");if(r.length<12||parseInt(r[0])!==5)continue;let i=r[2],p=r[3],d=r[4],l=parseInt(r[6]),c=parseInt(r[7]),f=parseInt(r[8]),u=parseInt(r[9]),h=parseFloat(r[10]),g=r.slice(11).join(" ").trim();if(!g||h<0)continue;let y={x0:l,y0:c,x1:l+f,y1:c+u},m={text:g,confidence:h,bbox:y};n.push(m);let x=`${i}_${p}_${d}`;t.has(x)||t.set(x,{words:[],bbox:{x0:1/0,y0:1/0,x1:-1/0,y1:-1/0}});let w=t.get(x);w.words.push(m),w.bbox.x0=Math.min(w.bbox.x0,y.x0),w.bbox.y0=Math.min(w.bbox.y0,y.y0),w.bbox.x1=Math.max(w.bbox.x1,y.x1),w.bbox.y1=Math.max(w.bbox.y1,y.y1)}let o=[];for(let s of t.values())s.words.length>0&&o.push({text:s.words.map(r=>r.text).join(" "),bbox:s.bbox,words:s.words});return{words:n,lines:o}}function tc(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=ec(e.tsv);e.words=n.words,e.lines=n.lines}}}function Qr(e,n,t=0,o=0,s=1){tc(e);let r=i=>({x0:Math.round(i.x0/s)+t,y0:Math.round(i.y0/s)+o,x1:Math.round(i.x1/s)+t,y1:Math.round(i.y1/s)+o}),a=[];if(e.lines&&e.lines.length>0)for(let i of e.lines){let p=i.text?i.text.toLowerCase().trim():"";if(!p||!i.bbox||!(p===n||new RegExp(`\\b${Jl(n)}\\b`,"i").test(p)))continue;let l=i.words||(e.words?e.words.filter(h=>h.bbox&&h.bbox.x0>=i.bbox.x0-5&&h.bbox.x1<=i.bbox.x1+5&&h.bbox.y0>=i.bbox.y0-5&&h.bbox.y1<=i.bbox.y1+5):[]),c=n.split(/\s+/),f=c.map(h=>h.replace(/[^a-z0-9]/g,"")).join(" "),u=!1;if(l.length>0)for(let h=0;h<=l.length-c.length;h++){let g=l.slice(h,h+c.length),y=g.map(m=>(m.text||"").toLowerCase().trim().replace(/[^a-z0-9]/g,"")).join(" ");if(y===f||y.includes(f)){let m={x0:Math.min(...g.map(x=>x.bbox.x0)),y0:Math.min(...g.map(x=>x.bbox.y0)),x1:Math.max(...g.map(x=>x.bbox.x1)),y1:Math.max(...g.map(x=>x.bbox.y1))};a.push(r(m)),u=!0}}u||a.push(r(i.bbox))}if(a.length===0&&e.words&&e.words.length>0)for(let i of e.words){let p=i.text?i.text.toLowerCase().trim().replace(/[^a-z0-9]/g,""):"",d=n.replace(/[^a-z0-9]/g,"");p===d&&i.bbox&&a.push(r(i.bbox))}if(a.length===0&&e.words&&e.words.length>0){let i=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)<=i&&Ql(d,n,i)<=i&&p.bbox&&a.push(r(p.bbox))}}return a}function Zr(e,n){let t=null,o=1/0;for(let s of e){let r=Math.round((s.x0+s.x1)/2),a=Math.round((s.y0+s.y1)/2),i=n.x>=s.x0&&n.x<=s.x1&&n.y>=s.y0&&n.y<=s.y1,p=Math.hypot(r-n.x,a-n.y),d=i?0:p;d<o&&(o=d,t={x:r,y:a,dist:p,containsPoint:i,bbox:s})}return t}function nc(e,n,t,o){let a=Math.ceil(e/4),i=Math.ceil(n/2),p=[];for(let d=0;d<2;d++)for(let l=0;l<4;l++){let c=l*a,f=d*i,u=Math.min(a,e-c),h=Math.min(i,n-f),g=c+u/2,y=f+h/2,m=t>=c&&t<c+u&&o>=f&&o<f+h;p.push({x0:c,y0:f,w:u,h,cx:g,cy:y,containsTarget:m})}return p.sort((d,l)=>{if(d.containsTarget)return-1;if(l.containsTarget)return 1;let c=Math.hypot(d.cx-t,d.cy-o),f=Math.hypot(l.cx-t,l.cy-o);return c-f})}var No=null;async function sc(){return No||(No=(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 No=null,e})),No}var po=null,Sa=null;async function oc(){let{getActiveDisplay:e}=await import("./screen_grid-PVIPPVR7.js"),n=await e();if(po&&Sa===n)return po;Sa=n,po={format:"png"};try{let t=await Ta.listDisplays();t&&t.length>0&&(po={format:"png",screen:(t[n]||t[0]).id})}catch{}return po}var ei=async(e,n={})=>{let t=!!(process.env.SHOW_DEBUG_GRID||process.env.DEBUG_OCR||process.env.VERBOSE),o=performance.now(),s=o,r=u=>{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) -> ${u}`),s=h};r("Starting click()");let a=O(e),i=a.gridId||a.grid||a.coordinate||a.target||a.id,p=(a.type||a.clickType||"single").toLowerCase(),d=(a.button||"left").toLowerCase(),l=a.intendedClickText||a.text||"";if(!i&&!l)return'ERROR: Missing required "gridId" parameter for Click tool.';let c=i;if(l)try{r("Parsing grid code");let u=i?$i(i):null;r("Getting display options");let h=await oc();r("Taking desktop screenshot");let g=await Ta(h);r("Getting image metadata");let y=await ho(g).metadata(),m=y.width||1920,x=y.height||1080,w=u?{x:Math.round(u.x*(m/1280)),y:Math.round(u.y*(x/720))}:{x:m/2,y:x/2},k=l.toLowerCase().trim();r("Acquiring OCR worker");let C=await sc(),R=null,S="",T=u?220:500;if(u){r("Pass 1: Cropping target crop (3x zoom window, 2x upscale)");let _=Math.min(Math.round(m/3),m),E=Math.min(Math.round(x/3),x),b=Math.max(0,Math.min(m-_,w.x-Math.floor(_/2))),$=Math.max(0,Math.min(x-E,w.y-Math.floor(E/2))),I=await ho(g).extract({left:b,top:$,width:_,height:E}).toBuffer(),D=2,N=await Jr(I,D),W=k.replace(/[^a-z0-9]/g,"_");await Xr("cropped",`crop_${Date.now()}_${W}.png`,N),r("Pass 1: Running Tesseract OCR recognize on crop (PSM 11 - Sparse Text)"),await C.setParameters({tessedit_pageseg_mode:"11"});let{data:Y}=await C.recognize(N,{},{tsv:!0,blocks:!0});if(r("Pass 1: OCR recognition finished, extracting matches"),Y&&Y.text){t&&console.log(`[Pass 1 OCR Read]: "${Y.text.trim().replace(/\s+/g," ")}"`);let ae=Qr(Y,k,b,$,D);if(ae.length>0){let V=Zr(ae,w);V&&(V.containsPoint||V.dist<=T)&&(R=V,S="centered target crop OCR")}}}if(!R){r("Pass 2: Entering Full-Screen OCR (broad scan, PSM 3 - Auto)");let _=await Jr(g,2),E=k.replace(/[^a-z0-9]/g,"_");await Xr("fullscreen",`full_${Date.now()}_${E}.png`,_),r("Pass 2: Running Tesseract on full screen"),await C.setParameters({tessedit_pageseg_mode:"3"});let{data:b}=await C.recognize(_,{},{tsv:!0,blocks:!0});if(r("Pass 2: Full-screen OCR finished"),b&&b.text){let $=Qr(b,k,0,0,2);if($.length>0){let I=Zr($,w);I&&(R=I,S="full-screen OCR")}}}if(!R){r("Pass 3: Entering Tiled OCR fallback (high-res 3x)");let _=nc(m,x,w.x,w.y),E=k.replace(/[^a-z0-9]/g,"_");await C.setParameters({tessedit_pageseg_mode:"11"});for(let b=0;b<_.length;b++){let $=_[b];r(`Pass 3: Preprocessing tile ${b+1}/${_.length}`);let I=await ho(g).extract({left:$.x0,top:$.y0,width:$.w,height:$.h}).toBuffer(),D=await Jr(I,3);await Xr("tiles",`tile_${b+1}_${Date.now()}_${E}.png`,D),r(`Pass 3: Running Tesseract on tile ${b+1}`);let{data:N}=await C.recognize(D,{},{tsv:!0,blocks:!0});if(!N||!N.text)continue;let W=Qr(N,k,$.x0,$.y0,3);if(W.length>0){let Y=Zr(W,w);if(Y){R=Y,S=`tile ${b+1} OCR (${$.containsTarget?"target tile":`offset ${$.x0},${$.y0}`})`;break}}}}if(R){let _={x:Math.round(R.x*(1280/m)),y:Math.round(R.y*(720/x))};r(`Executing mouse click on matched target (${S})`);let E=await Pn("click",_,{button:d,clickType:p});return r("Click completed successfully"),`${E} (${S} for "${l}" at ${Math.round(R.dist)}px distance)`}else t&&console.log(`[OCR] No match found for "${l}". Falling back to gridId.`)}catch(u){t&&console.error("[OCR Error]",u)}r(`Executing mouse click on fallback gridId: ${c}`);let f=await Pn("click",c,{button:d,clickType:p});return r("Fallback click completed"),f};var ti=async(e,n={})=>{let t=O(e),o=t.fromGridId||t.from||t.start,s=t.toGridId||t.to||t.end;return!o||!s?'ERROR: Drag requires both "fromGridId" and "toGridId" parameters.':await Pn("drag",o,{from:o,to:s})};var ni=async(e,n={})=>{let t=O(e),o=(t.direction||"down").toLowerCase(),s=t.amount?parseInt(t.amount,10):6,r=t.gridId||t.grid||t.coordinate||t.target||t.id||null;return await Pn("scroll",r,{direction:o,amount:s})};var Bo=async(e,n={})=>{let t=O(e),o=t.text||t.input||t.value||"",s=t.autoPressEnter===!0||t.autoPressEnter==="true"||t.enter===!0||t.enter==="true";return o==null?'ERROR: Missing required "text" parameter for KeyboardTyping tool.':await Fn("type",String(o),{autoPressEnter:s})};var Uo=async(e,n={})=>{let t=O(e),o=t.key||t.keys||t.input||t.shortcut;if(!o)return'ERROR: Missing required "key" parameter for KeyPress tool.';let s=String(o).trim().toLowerCase();if(s==="clearinput"||s==="clear_input"||s==="clear")return await Fn("clear_input");if(s==="back"||s==="browser_back"||s==="browserBack")return await Fn("browser_back");if(s.includes(";")||s.includes("+")){let r=s.split(/[;+]/).map(a=>a.trim()).filter(Boolean);return await Fn("key_combination",r)}return await Fn("key_press",s)};var Wo=async(e,n={})=>"SUCCESS: Screen recapture requested. The latest gridded screenshot is provided for your next decision.";var rc={web_search:Tr,web_scrape:Rr,memory:Er,chat:_r,view_file:no,write_file:Cr,update_file:Ir,exec_command:gr,read_folder:Lr,write_pdf:Dr,write_docx:Fr,search_keyword:oo,generate_image:Wr,saveSummary:ro,addMemScore:Ns,file_map:Gr,todo:io,Todo:io,goal:io,Goal:io,invokeSync:qr,invoke:ma,getProgress:zr,cancel:ga,awaitSubagent:Bs,answerSubagent:Us,steerSubagent:lo,computer_action:uo,computer_use:uo,ComputerAction:uo,ComputerUse:uo,click:ei,Click:ei,drag:ti,Drag:ti,scroll:ni,Scroll:ni,keyboard_typing:Bo,KeyboardTyping:Bo,keyboardtyping:Bo,key_press:Uo,KeyPress:Uo,keypress:Uo,recapture_screen:Wo,RecaptureScreen:Wo,recapturescreen:Wo,invoke_sync:qr,get_progress:zr,await_subagent:Bs,answer_subagent:Us,steer_subagent:lo,steer:lo,Steer:lo,ask:Fo,Ask:Fo,AskUser:Fo,WebSearch:Tr,WebScrape:Rr,ReadFile:no,ReadFolder:Lr,WriteFile:Cr,PatchFile:Ir,WritePDF:Dr,WriteDoc:Fr,Run:gr,SearchKeyword:oo,CodeSearch:oo,code_search:oo,Memory:Er,Chat:_r,GenerateImage:Wr,saveSumary:ro,SaveSummary:ro,SaveSumary:ro,add_mem_score:Ns,AddMemScore:Ns,addMemoryScore:Ns,AddMemoryScore:Ns,FileMap:Gr,answer:Us,Answer:Us,AnswerSubagent:Us,await:Bs,Await:Bs,AwaitSubagent:Bs,EmergencyRollback:Yr,emergency_rollback:Yr},mo=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(l=>s.includes(l))||s==="ask",p=["click","drag","scroll","keyboardtyping","keyboard_typing","keypress","key_press","recapturescreen","recapture_screen","computer"].some(l=>s.includes(l));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=rc[e];if(!d)return`ERROR: Tool [${e}] not found in registry.`;try{return await d(n,t)}catch(l){let c=l instanceof Error?l.message:String(l);return`ERROR: Execution failed for [${e}]: ${c}`}};import te from"path";import Pe from"fs";import ic from"gradient-string";var si=["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 Ra=[{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"]}],go={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 jo=null;var Ea=(e="Dark")=>{let n;e==="Mystery"||e==="Chaos"?(jo||(jo=Ra[Math.floor(Math.random()*Ra.length)]),n={...jo,id:"Mystery"}):(jo=null,go[e]?n=go[e]:e==="GitHub"?n=go["GitHub Dark"]:e==="Transparent"?n=go["Transparent Dark"]:n=go.Dark);let t=n.codeText||n.secondary||n.info||n.logoGradient&&n.logoGradient[0]||"cyan";return{...n,codeText:t}};var ac=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",Ph=(e=2)=>{let n=ac();return n==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)},Fh=(e="...",n="Loading...",t="Dark")=>{let o=si[Math.floor(Math.random()*si.length)],s=Ea(t),r=s.logoTextAnsi,a=s.logoBodyAnsi,i=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 "],l=s.logoGradient||["#0077ff","#ff00ff"],c=ic(l).multiline(d.join(`
|
|
485
|
+
`)).split(`
|
|
486
|
+
`),f=u=>`${i}${u}${p}`;return`${c[0]}
|
|
487
|
+
${c[1]} ${r}Selected Provider: ${n}${p}
|
|
488
|
+
${c[2]}
|
|
489
|
+
${c[3]} ${r}FluxFlow ${f("v"+e)}${p}
|
|
490
|
+
${c[4]}
|
|
491
|
+
${c[5]} ${a}See /help for additional commands.${p}
|
|
492
|
+
${c[6]} ${f(o)}
|
|
493
|
+
${c[7]}`};import{WebSocket as Ho}from"ws";var Vt=null,Ws=!1,lc="ws://localhost:56832",oi=[],js=null,ri=null,_a="2.0.0",Uh=e=>{_a=e,Ca()},ii=e=>{ri=e},Ca=()=>{if(Vt||Ws)return;Ws=!0;let e=new Ho(lc);e.on("open",()=>{for(Vt=e,Ws=!1,Vt.send(JSON.stringify({command:"version",version:_a,pid:process.pid,ppid:process.ppid}));oi.length>0;)Vt.send(JSON.stringify(oi.shift()))}),e.on("message",n=>{try{let t=JSON.parse(n.toString());t.command==="contextResponse"&&js?(js(t.data),js=null):t.command==="securityResponse"&&ri&&ri(t.result)}catch{}}),e.on("error",()=>{Ws=!1,Vt=null}),e.on("close",()=>{Ws=!1,Vt=null})},Go=e=>{Vt&&Vt.readyState===Ho.OPEN?Vt.send(JSON.stringify(e)):(oi.push(e),Ws||Ca())},qo=()=>Vt!==null&&Vt.readyState===Ho.OPEN,Wh=e=>{Go({command:"status",status:e})},xs=()=>new Promise(e=>{if(!Vt||Vt.readyState!==Ho.OPEN){e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]});return}js=e,Vt.send(JSON.stringify({command:"requestContext"})),setTimeout(()=>{js===e&&(e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]}),js=null)},1e3)}),$a=e=>{Go({command:"open",filePath:e})},ai=(e,n,t)=>{Go({command:"showDiff",filePath:e,originalContent:n,modifiedContent:t})},Ma=(e,n)=>{Go({command:"closeDiff",filePath:e,result:n})};import Aa from"path";import cc from"fs";var dc=e=>{try{return cc.readdirSync(e,{withFileTypes:!0})}catch{return[]}},li=(e,n,t=1,o=dc,s=[],r=null)=>{let a=r||o(e),i=" ".repeat(t-1);if(a.length>100)return`${i}${Aa.basename(e)}/ (>100 files)
|
|
494
|
+
`;let p="",d=s,l=a.filter(h=>!d.includes(h.name)&&!h.name.startsWith(".")),c=a.filter(h=>d.includes(h.name)||h.name.startsWith(".")).map(h=>h.name).sort();c.length>0&&(p+=`${i}[ignored: ${c.map(h=>h+"/").join(", ")}]
|
|
495
|
+
`);let f=l.filter(h=>h.isDirectory()).sort((h,g)=>h.name.localeCompare(g.name)),u=l.filter(h=>!h.isDirectory()).map(h=>h.name).sort();for(let h of f){let g=Aa.join(e,h.name);if(t>n)p+=`${i}${h.name}/ (max depth)
|
|
496
|
+
`;else{let y=o(g);y.length>80?p+=`${i}${h.name}/ (>80 files)
|
|
497
|
+
`:(p+=`${i}${h.name}/
|
|
498
|
+
`,p+=li(g,n,t+1,o,s,y))}}return u.length>0&&(p+=`${i}${u.join("; ")}
|
|
499
|
+
`),p};import ci from"path";import fc from"fs";var uc=e=>{try{return fc.readdirSync(e,{withFileTypes:!0})}catch{return[]}},di=(e,n,t="",o=1,s=uc,r=[])=>{let a=s(e),i=ci.sep;if(a.length>100)return`${t}\u2514\u2500\u2500 ${ci.basename(e)}${i} ...100+ files...
|
|
500
|
+
`;let p="",d=r,l=a.filter(u=>!d.includes(u.name)&&!u.name.startsWith(".")),c=a.filter(u=>d.includes(u.name)||u.name.startsWith(".")).map(u=>u.name).sort();l.sort((u,h)=>u.isDirectory()&&!h.isDirectory()?-1:!u.isDirectory()&&h.isDirectory()?1:u.name.localeCompare(h.name));let f=[...l.map(u=>({name:u.name,isDir:u.isDirectory()})),...c.map(u=>({name:u,isDir:!0,isCollapsed:!0}))];return f.forEach((u,h)=>{let g=h===f.length-1,y=ci.join(e,u.name),m=g?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",x=t+(g?" ":"\u2502 ");if(u.isCollapsed){p+=`${t}${m}${u.name}${i}...
|
|
501
|
+
`;return}u.isDir?o>n?p+=`${t}${m}${u.name}${i} ...depth exceeded...
|
|
502
|
+
`:s(y).length>80?p+=`${t}${m}${u.name}${i} ...80+ files...
|
|
503
|
+
`:(p+=`${t}${m}${u.name}${i}
|
|
504
|
+
`,p+=di(y,n,x,o+1,s,r)):p+=`${t}${m}${u.name}
|
|
505
|
+
`}),p};import"@google/genai";var It=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 i=await fetch(e,n);if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),i.ok||i.status!==429&&i.status<500)return i}catch(i){if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),i.name==="AbortError"||s?.aborted||a===t-1)throw i}s?await new Promise((i,p)=>{let d=setTimeout(()=>{s.removeEventListener("abort",l),i()},Math.min(24e3,o*Math.pow(2,a))),l=()=>{clearTimeout(d),p(new DOMException("The user aborted a request.","AbortError"))};s.addEventListener("abort",l)}):await new Promise(i=>setTimeout(i,Math.min(24e3,o*Math.pow(2,a))))}if(s?.aborted)throw new DOMException("The user aborted a request.","AbortError");let r=await fetch(e,n);return typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),r};async function zo(e){let n=new TextEncoder().encode(e),t=await crypto.subtle.digest("SHA-256",n);return[...new Uint8Array(t).slice(0,16)].map(o=>o.toString(16).padStart(2,"0")).join("")}var Nn=e=>typeof e!="string"?e:e.replace(/<\|channel>thought/gi,"<think>").replace(/<channel\|>/gi,"</think>");var Ko=async function*(e,n,t,o,s,r,a,i,p=1){let d=[];o&&d.push({role:"system",content:o});for(let w of t){let k=w.role==="user"?"user":"assistant",C=[];if(Array.isArray(w.parts)){for(let R of w.parts)if(R.text)C.push({type:"text",text:R.text});else if(R.inlineData&&a){let S=R.inlineData.mimeType,T=R.inlineData.data;S.startsWith("image/")&&C.push({type:"image_url",image_url:{url:`data:${S};base64,${T}`}})}}else{let R=w.text||"";R&&C.push({type:"text",text:R})}d.push({role:k,content:C.length===1&&C[0].type==="text"?C[0].text:C})}let l={model:n,messages:d,stream:!0,stream_options:{include_usage:!0},temperature:p};if(s!=="Fast"){let w={Low:"high",Medium:"high",Standard:"high",High:"max",xHigh:"max"};l.reasoning_effort=w[s]||"high",l.extra_body={thinking:{type:"enabled"}}}else l.extra_body={thinking:{type:"disabled"}};let c=await It("https://api.deepseek.com/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(l),signal:i});if(!c.ok){let w=await c.json().catch(()=>({}));throw new Error(`DeepSeek Error (${c.status}): ${w.error?.message||c.statusText}`)}let f=c.body.getReader(),u=new TextDecoder,h="",g=[],y=null,m=Date.now(),x=!1;for(;;){let{done:w,value:k}=await f.read();if(w){x&&(g.length>0||y)&&(yield{candidates:g.length>0?[{content:{parts:g}}]:[],usageMetadata:y});break}h+=u.decode(k,{stream:!0});let C=h.split(`
|
|
506
|
+
`);h=C.pop();for(let R of C){let S=R.trim();if(!S||!S.startsWith("data: "))continue;let T=!1;if(S==="data: [DONE]")T=!0;else try{let _=JSON.parse(S.substring(6)),E=_.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},x=!0),E){let $=E.reasoning_content||null;$&&(g.push({text:$,thought:!0}),x=!0),E.content&&(g.push({text:E.content}),x=!0)}}catch{}if((T||Date.now()-m>=150)&&x&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],m=Date.now(),x=!1),T)break}Date.now()-m>=150&&x&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],m=Date.now(),x=!1)}};var Yo=async function*(e,n,t,o,s,r,a,i,p=1,d=null){let l=[];o&&l.push({role:"system",content:o});for(let T of t){let _=T.role==="user"?"user":"assistant",E=[];if(Array.isArray(T.parts)){for(let b of T.parts)if(b.text)E.push({type:"text",text:b.text});else if(b.inlineData&&a){let $=b.inlineData.mimeType,I=b.inlineData.data;$.startsWith("image/")&&E.push({type:"image_url",image_url:`data:${$};base64,${I}`})}}else{let b=T.text||"";b&&E.push({type:"text",text:b})}E.length>0&&l.push({role:_,content:E.length===1&&E[0].type==="text"?E[0].text:E})}let c={Fast:"none",Low:"none",Medium:"high",Standard:"high",High:"high",xHigh:"high"},f=`${e.slice(-5)}${d||""}${s}${n}`,u=await zo(f),h={model:n,messages:l,stream:!0,temperature:p,prompt_cache_key:u};s&&s!=="Fast"&&vs(n)&&(h.reasoning_effort=c[s]||"high");let g=await It("https://api.mistral.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(h),signal:i});if(!g.ok){let T=await g.text().catch(()=>""),_=g.statusText;try{let E=JSON.parse(T);_=E.error?.message||E.message||JSON.stringify(E.detail||E)}catch{T&&(_=T)}throw new Error(`Mistral Error (${g.status}): ${JSON.stringify(_)}`)}let y=g.body.getReader(),m=new TextDecoder,x="",w=[],k=null,C=Date.now(),R=!1,S=T=>T?typeof T=="string"?Nn(T):Array.isArray(T)?T.map(S).filter(Boolean).join(""):typeof T=="object"&&T!==null?typeof T.text=="string"?Nn(T.text):typeof T.content=="string"?Nn(T.content):typeof T.thinking=="string"?Nn(T.thinking):typeof T.reasoning_content=="string"?Nn(T.reasoning_content):typeof T.reasoning=="string"?Nn(T.reasoning):typeof T.value=="string"?Nn(T.value):T.text?S(T.text):T.content?S(T.content):T.thinking?S(T.thinking):T.reasoning_content?S(T.reasoning_content):T.reasoning?S(T.reasoning):T.value?S(T.value):"":Nn(String(T)):"";for(;;){let{done:T,value:_}=await y.read();if(T){R&&(w.length>0||k)&&(yield{candidates:w.length>0?[{content:{parts:w}}]:[],usageMetadata:k});break}x+=m.decode(_,{stream:!0});let E=x.split(`
|
|
507
|
+
`);x=E.pop();for(let b of E){let $=b.trim();if(!$||!$.startsWith("data: "))continue;let I=!1;if($==="data: [DONE]")I=!0;else try{let D=JSON.parse($.substring(6)),N=D.choices?.[0]?.delta,W=D.usage;if(D.choices?.[0]?.finish_reason&&(I=!0),W&&(k={totalTokenCount:W.total_tokens||(W.prompt_tokens||0)+(W.completion_tokens||0),promptTokenCount:W.prompt_tokens||0,candidatesTokenCount:W.completion_tokens||0,cachedContentTokenCount:W.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:W.completion_tokens_details?.reasoning_tokens||0},R=!0),N){let Y=N.thinking||N.reasoning_content||N.reasoning,ae=S(Y);ae&&(w.push({text:ae,thought:!0}),R=!0);let V=N.content||(!N.thinking&&!N.reasoning_content&&!N.reasoning?N.text:null);if(V)if(Array.isArray(V))for(let F of V)if(typeof F=="object"&&F!==null){let U=F.type==="thinking"||F.type==="reasoning"||!!F.thought,oe=S(F);oe&&(w.push({text:oe,...U?{thought:!0}:{}}),R=!0)}else{let U=S(F);U&&(w.push({text:U}),R=!0)}else if(typeof V=="object"&&V!==null){let F=V.type==="thinking"||V.type==="reasoning"||!!V.thought,U=S(V);U&&(w.push({text:U,...F?{thought:!0}:{}}),R=!0)}else{let F=S(V);F&&(w.push({text:F}),R=!0)}}}catch{}if((I||Date.now()-C>=150)&&R&&(yield{candidates:w.length>0?[{content:{parts:[...w]}}]:[],usageMetadata:k},w=[],C=Date.now(),R=!1),I)break}Date.now()-C>=150&&R&&(yield{candidates:w.length>0?[{content:{parts:[...w]}}]:[],usageMetadata:k},w=[],C=Date.now(),R=!1)}};var Vo=async function*(e,n,t,o,s,r,a=!1,i,p=1){let d=[];o&&d.push({role:"system",content:o}),t.forEach(oe=>{let ve=oe.role==="model"?"assistant":"user",A=[];Array.isArray(oe.parts)&&oe.parts.forEach(B=>{if(B.text)A.push({type:"text",text:B.text});else if(B.inlineData&&a){let X=B.inlineData.mimeType,J=B.inlineData.data;X.startsWith("image/")&&At(n)&&A.push({type:"image_url",image_url:{url:`data:${X};base64,${J}`}})}}),d.push({role:ve,content:A.length===1&&A[0].type==="text"?A[0].text:A})});let c={Fast:"Fast",Low:"Fast",Medium:"Standard",Standard:"Standard",High:"High",xHigh:"High"}[s]||"High",f=c!=="Fast",u=n.includes("kimi"),h=n.includes("gemma"),g=n.includes("deepseek"),y=n.includes("glm"),m=n.includes("mistral"),x=n.includes("minimax"),w=n.includes("gpt"),k=n.includes("qwen"),C=n.includes("nemotron"),R=n.includes("llama-3"),S=n.includes("seed"),T=n.includes("poolside"),_=n.includes("thinkingmachines")||n.includes("muse"),E=R,b=null,$={Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},I={Fast:"64",Low:"64",Medium:"4096",Standard:"4096",High:"16384",xHigh:"16384"},D={Fast:"none",Low:"minimal",Medium:"medium",Standard:"medium",High:"max",xHigh:"max"},N=x||g||T||_?16384:32768;N=process.env.NVIDIA_BASE_URL?1024:N,N=b?1024:N;let W={model:n,messages:d,max_tokens:N,stream:!0,stream_options:{include_usage:!0},temperature:p,...w&&{thinking:$[s]||"high"}};if(!(process.env.NVIDIA_BASE_URL||E||b))if(u)W.chat_template_kwargs={thinking:f};else if(h)W.chat_template_kwargs={enable_thinking:f};else if(g)if(f){let oe=c==="High"?"max":"high";W.chat_template_kwargs={thinking:!0,reasoning_effort:oe}}else W.chat_template_kwargs={thinking:!1};else y?W.chat_template_kwargs={enable_thinking:f,clear_thinking:!f}:m?W.reasoning_effort=f?"high":"none":x&&n.includes("minimax-m3")?W.chat_template_kwargs={thinking_mode:f?"enabled":"disabled"}:k?W.chat_template_kwargs={enable_thinking:f}:C?c==="High"?W.chat_template_kwargs={enable_thinking:!0}:c==="Standard"?W.chat_template_kwargs={enable_thinking:!0,medium_effort:!0}:W.chat_template_kwargs={enable_thinking:!1}:S?f&&(W.extra_body={thinking_budget:parseInt(I[c]??"4096")}):T?W.chat_template_kwargs={enable_thinking:f}:_&&(W.reasoning_effort=D[c]||"medium");let Y=0,ae=6,V=!1,F=process.env.NVIDIA_BASE_URL||"https://integrate.api.nvidia.com/v1/chat/completions",U=process.env.NVIDIA_API_KEY&&process.env.NVIDIA_BASE_URL?process.env.NVIDIA_API_KEY:e;for(F.endsWith("/chat/completions")||(F=F.replace(/\/+$/,"")+"/chat/completions");Y<ae;){Y++;try{let oe=await It(F,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${U}`},body:JSON.stringify(W),signal:i});if(!oe.ok){let He=await oe.text().catch(()=>""),at=oe.statusText;try{let kt=JSON.parse(He);at=kt.error?.message||kt.message||JSON.stringify(kt.detail||kt)}catch{He&&(at=He)}let Ke=new Error(`NVIDIA API Error (${oe.status}): ${at}`);throw Ke.status=oe.status,Ke}let ve=oe.body.getReader(),A=new TextDecoder,B="",X=[],J=null,We=Date.now(),Fe=!1;for(;;){let{done:He,value:at}=await ve.read();if(He){Fe&&(X.length>0||J)&&(yield{candidates:X.length>0?[{content:{parts:X}}]:[],usageMetadata:J},V=!0);break}B+=A.decode(at,{stream:!0});let Ke=B.split(`
|
|
508
|
+
`);B=Ke.pop();let kt=!1;for(let Bt of Ke){let mt=Bt.trim();if(mt){if(mt==="data: [DONE]"){kt=!0;break}if(mt.startsWith("data: ")){let St;try{St=JSON.parse(mt.substring(6))}catch{continue}if(St.error)throw new Error(`NVIDIA Stream Error: ${St.error.message||JSON.stringify(St.error)}`);try{let Et=St.usage;Et&&(J={totalTokenCount:Et.total_tokens||Et.prompt_tokens+Et.completion_tokens,promptTokenCount:Et.prompt_tokens||0,candidatesTokenCount:Et.completion_tokens||0,cachedContentTokenCount:Et.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:(Et.completion_tokens_details?.reasoning_tokens||0)+(Et.completion_tokens_details?.thoughts_tokens||0)},Fe=!0);let lt=St.choices?.[0]?.delta?.reasoning||St.choices?.[0]?.delta?.reasoning_content||"",Te=St.choices?.[0]?.delta?.content||"";lt&&(X.push({text:lt,thought:!0}),Fe=!0),Te&&(X.push({text:Te}),Fe=!0)}catch{}}}}if((kt||Date.now()-We>=350)&&Fe&&(yield{candidates:X.length>0?[{content:{parts:[...X]}}]:[],usageMetadata:J},V=!0,X=[],We=Date.now(),Fe=!1),kt)break}break}catch(oe){if(V||Y>=ae)throw oe;await new Promise(ve=>setTimeout(ve,3500))}}},va=async function*(e,n){let t=[],o=null,s=!1,r=null,a=f=>{if(t.push(f),o){let u=o;o=null,u()}},i=n.split("/").pop();i=i.replace("llama-3.3","llama-3_3");let p=`https://api.ngc.nvidia.com/v2/predict/queues/models/qc69jvmznzxy/${i}`,d=!1,l=null,c=async()=>{try{let f=await fetch(p);if(f.ok){let u=await f.json();if(u&&u.queues&&u.queues[0]&&typeof u.queues[0].queueDepth=="number"){let h=u.queues[0].queueDepth;d||a({value:{type:"status",content:`Queue ${h||1}`},done:!1})}}}catch{}};process.env.NVIDIA_BASE_URL||(c(),l=setInterval(c,5e3)),(async()=>{try{let f=e[Symbol.asyncIterator]();for(;;){let{value:u,done:h}=await f.next();if(h)break;d=!0,l&&(clearInterval(l),l=null),a({value:u,done:!1})}s=!0,a(null)}catch(f){if(r=f,l&&(clearInterval(l),l=null),o){let u=o;o=null,u()}}})();try{for(;;){if(r)throw r;if(t.length>0){let f=t.shift();if(f===null&&s)break;yield f.value}else{if(s)break;await new Promise(f=>{o=f})}}}finally{l&&(clearInterval(l),l=null)}};var Xo=async function*(e,n,t,o,s,r,a,i,p=1,d=null){let l=[];o&&l.push({role:"system",content:[{type:"text",text:o}]});for(let b of t){let $=b.role==="user"?"user":"assistant",I=[];if(Array.isArray(b.parts)){for(let D of b.parts)if(D.text)I.push({type:"text",text:D.text});else if(D.inlineData&&a){let N=D.inlineData.mimeType,W=D.inlineData.data;N.startsWith("image/")?I.push({type:"image_url",image_url:{url:`data:${N};base64,${W}`}}):I.push({type:"file",file:{filename:D.filename||"file",file_data:`data:${N};base64,${W}`}})}}else{let D=b.text||"";D&&I.push({type:"text",text:D})}l.push({role:$,content:I.length===1&&I[0].type==="text"?I[0].text:I})}let c={Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},f=["free","nitro","floor","exact","extended","beta","online"],u=n,h=null;if(n.includes(":")){let b=n.split(":"),$=b[b.length-1].toLowerCase().trim();if(f.includes($))u=n.trim();else{let I=b.pop().trim();u=b.join(":").trim(),I&&(h={order:[I],allow_fallbacks:!1})}}let g=`${e.slice(-5)}${d||""}${s}${u}${h?JSON.stringify(h):""}`,y=await zo(g),m={model:u,messages:l,stream:!0,temperature:p,cache_control:{type:"ephemeral"},session_id:y};h&&(m.provider=h);let x=c[s];x&&s!=="Fast"&&(m.reasoning_effort=x);let w=await It("https://openrouter.ai/api/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json","HTTP-Referer":"https://fluxflow-cli.onrender.com/","X-Title":"FluxFlow CLI","X-OpenRouter-Title":"FluxFlow CLI","X-Cache":"true","X-OpenRouter-Cache":"true"},body:JSON.stringify(m),signal:i});if(!w.ok){let b=await w.json().catch(()=>({})),$=b.error?.metadata?.raw||b.error?.message||(typeof b.error=="string"?b.error:"")||w.statusText||"Unknown error";throw new Error(`OpenRouter Error (${w.status}): ${$}`)}let k=w.body.getReader(),C=new TextDecoder,R="",S=[],T=null,_=Date.now(),E=!1;for(;;){let{done:b,value:$}=await k.read();if(b){E&&(S.length>0||T)&&(yield{candidates:S.length>0?[{content:{parts:S}}]:[],usageMetadata:T});break}R+=C.decode($,{stream:!0});let I=R.split(`
|
|
509
|
+
`);R=I.pop();for(let D of I){let N=D.trim();if(!N||!N.startsWith("data: "))continue;let W=!1;if(N==="data: [DONE]")W=!0;else try{let Y=JSON.parse(N.substring(6));if(Y.error){let F=Y.error.metadata?.raw||Y.error.message||JSON.stringify(Y.error);throw new Error(`OpenRouter Stream Error: ${F}`)}let ae=Y.choices?.[0]?.delta,V=Y.usage;if(Y.choices?.[0]?.finish_reason&&(W=!0),V&&(T={totalTokenCount:V.total_tokens||(V.prompt_tokens||0)+(V.completion_tokens||0),promptTokenCount:V.prompt_tokens||0,candidatesTokenCount:V.completion_tokens||0,cachedContentTokenCount:V.prompt_tokens_details?.cached_tokens||V.prompt_tokens_details?.cache_read_input_tokens||V.cache_read_input_tokens||0,thoughtsTokenCount:V.completion_tokens_details?.reasoning_tokens||0},E=!0),ae){let F=ae.reasoning||(ae.reasoning_details?ae.reasoning_details.map(U=>U.text).join(""):null);F&&(S.push({text:F,thought:!0}),E=!0),ae.content&&(S.push({text:ae.content}),E=!0)}}catch(Y){if(Y.message&&Y.message.startsWith("OpenRouter Stream Error:"))throw Y}if((W||Date.now()-_>=150)&&E&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:T},S=[],_=Date.now(),E=!1),W)break}}};import{Ollama as pc}from"ollama";var fi=async function*(e,n,t,o,s,r,a,i,p=1,d="Cloud"){let l=[];o&&l.push({role:"system",content:o});for(let S of t){let T=S.role==="user"?"user":"assistant",_="",E=[];if(Array.isArray(S.parts)){_=S.parts.map(b=>b.text||"").filter(Boolean).join(`
|
|
510
|
+
`);for(let b of S.parts){let $=b.inlineData||b.inline_data;$&&$.data&&E.push($.data)}}else _=S.text||"";if(_||E.length>0){let b={role:T,content:_};E.length>0&&(b.images=E),l.push(b)}}let c=d==="Local"||!e||e==="LOCAL",u={host:c?process.env.OLLAMA_HOST||"http://127.0.0.1:11434":process.env.OLLAMA_HOST||"https://ollama.com"};!c&&e&&(u.headers={Authorization:"Bearer "+e});let h=new pc(u),g=[],y=null,m=Date.now(),x=!1,w={Fast:!1,Low:"medium",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},k=w[s]!==void 0?w[s]:!0,C={model:n,messages:l,stream:!0,think:k,keep_alive:"10m",options:{temperature:p}},R=await h.chat(C);for await(let S of R){if(i?.aborted)throw new DOMException("The user aborted a request.","AbortError");if(S.message?.thinking&&(g.push({text:S.message.thinking,thought:!0}),x=!0),S.message?.content&&(g.push({text:S.message.content}),x=!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},x=!0}(S.done||Date.now()-m>=150&&x)&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],m=Date.now(),x=!1)}x&&(g.length>0||y)&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y})};var Jo=async function*(e,n,t,o,s,r,a,i,p=1){let d=[];o&&d.push({role:"system",content:o});for(let k of t){let C=k.role==="user"?"user":"assistant",R=[];if(Array.isArray(k.parts)){for(let S of k.parts)if(S.text)R.push({type:"text",text:S.text});else if(S.inlineData&&a){let T=S.inlineData.mimeType,_=S.inlineData.data;T.startsWith("image/")&&R.push({type:"image_url",image_url:{url:`data:${T};base64,${_}`}})}}else{let S=k.text||"";S&&R.push({type:"text",text:S})}d.push({role:C,content:R.length===1&&R[0].type==="text"?R[0].text:R})}let l={Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},c={model:n,messages:d,stream:!0,stream_options:{include_usage:!0},temperature:p,max_completion_tokens:32768};l[s]&&(c.reasoning_effort=l[s]);let f=await It("https://crof.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(c),signal:i});if(!f.ok){let k=await f.json().catch(()=>({}));throw new Error(`CrofAI Error (${f.status}): ${k.error?.message||f.statusText}`)}let u=f.body.getReader(),h=new TextDecoder,g="",y=[],m=null,x=Date.now(),w=!1;for(;;){let{done:k,value:C}=await u.read();if(k){w&&(y.length>0||m)&&(yield{candidates:y.length>0?[{content:{parts:y}}]:[],usageMetadata:m});break}g+=h.decode(C,{stream:!0});let R=g.split(`
|
|
511
|
+
`);g=R.pop();for(let S of R){let T=S.trim();if(!T||!T.startsWith("data: "))continue;let _=!1;if(T==="data: [DONE]")_=!0;else try{let E=JSON.parse(T.substring(6)),b=E.choices?.[0]?.delta,$=E.usage;if(E.choices?.[0]?.finish_reason&&(_=!0),$&&(m={totalTokenCount:$.total_tokens||($.prompt_tokens||0)+($.completion_tokens||0),promptTokenCount:$.prompt_tokens||0,candidatesTokenCount:$.completion_tokens||0,cachedContentTokenCount:$.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:$.completion_tokens_details?.reasoning_tokens||$.reasoning_tokens||0},w=!0),b){let I=b.reasoning_content||null;I&&(y.push({text:I,thought:!0}),w=!0),b.content&&(y.push({text:b.content}),w=!0)}}catch{}if((_||Date.now()-x>=150)&&w&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],x=Date.now(),w=!1),_)break}Date.now()-x>=150&&w&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],x=Date.now(),w=!1)}};var Qo=async function*(e,n,t,o,s,r,a,i,p=1){let d=[];o&&d.push({role:"system",content:o});for(let k of t){let C=k.role==="user"?"user":"assistant",R="";if(Array.isArray(k.parts))for(let S of k.parts)S.text&&(R+=(R?`
|
|
512
|
+
`:"")+S.text);else R=k.text||"";d.push({role:C,content:R})}let l={Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},c={model:n,messages:d,stream:!0,stream_options:{include_usage:!0},temperature:p};l[s]&&(c.reasoning_effort=l[s]);let f=await It("https://model.inferx.net/endpoints/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(c),signal:i});if(!f.ok){let k=await f.json().catch(()=>({}));throw new Error(`InferX Error (${f.status}): ${k.error?.message||f.statusText||String(k)}`)}let u=f.body.getReader(),h=new TextDecoder,g="",y=[],m=null,x=Date.now(),w=!1;for(;;){let{done:k,value:C}=await u.read();if(k){w&&(y.length>0||m)&&(yield{candidates:y.length>0?[{content:{parts:y}}]:[],usageMetadata:m});break}g+=h.decode(C,{stream:!0});let R=g.split(`
|
|
513
|
+
`);g=R.pop();for(let S of R){let T=S.trim();if(!T||!T.startsWith("data: "))continue;let _=!1;if(T==="data: [DONE]")_=!0;else try{let E=JSON.parse(T.substring(6)),b=E.choices?.[0]?.delta,$=E.usage;if($&&(m={totalTokenCount:$.total_tokens||($.prompt_tokens||0)+($.completion_tokens||0),promptTokenCount:$.prompt_tokens||0,candidatesTokenCount:$.completion_tokens||0,cachedContentTokenCount:$.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:$.completion_tokens_details?.reasoning_tokens||$.reasoning_tokens||0},w=!0),b){let I=b.reasoning||b.reasoning_content||null;I&&(y.push({text:I,thought:!0}),w=!0),b.content&&(y.push({text:b.content}),w=!0)}}catch{}if((_||Date.now()-x>=150||m)&&w&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],x=Date.now(),w=!1),_)break}Date.now()-x>=150&&w&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],x=Date.now(),w=!1)}};var Zo=async function*(e,n,t,o,s,r,a,i,p=1){let d=[];o&&d.push({role:"system",content:o});for(let k of t){let C=k.role==="user"?"user":"assistant",R=[];if(Array.isArray(k.parts)){for(let S of k.parts)if(S.text)R.push({type:"text",text:S.text});else if(S.inlineData&&a){let T=S.inlineData.mimeType,_=S.inlineData.data;T.startsWith("image/")&&R.push({type:"image_url",image_url:{url:`data:${T};base64,${_}`}})}}else{let S=k.text||"";S&&R.push({type:"text",text:S})}d.push({role:C,content:R.length===1&&R[0].type==="text"?R[0].text:R})}let l={Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},c={model:n,messages:d,stream:!0,stream_options:{include_usage:!0},temperature:p};l[s]&&(c.reasoning_effort=l[s]);let f=await It("https://token.sensenova.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(c),signal:i});if(!f.ok){let k=await f.json().catch(()=>({}));throw new Error(`SenseNova Error (${f.status}): ${k.error?.message||f.statusText}`)}let u=f.body.getReader(),h=new TextDecoder,g="",y=[],m=null,x=Date.now(),w=!1;for(;;){let{done:k,value:C}=await u.read();if(k){w&&(y.length>0||m)&&(yield{candidates:y.length>0?[{content:{parts:y}}]:[],usageMetadata:m});break}g+=h.decode(C,{stream:!0});let R=g.split(`
|
|
514
|
+
`);g=R.pop();for(let S of R){let T=S.trim();if(!T||!T.startsWith("data: "))continue;let _=!1;if(T==="data: [DONE]")_=!0;else try{let E=JSON.parse(T.substring(6)),b=E.choices?.[0]?.delta,$=E.usage;if($&&(m={totalTokenCount:$.total_tokens||($.prompt_tokens||0)+($.completion_tokens||0),promptTokenCount:$.prompt_tokens||0,candidatesTokenCount:$.completion_tokens||0,cachedContentTokenCount:$.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:$.completion_tokens_details?.reasoning_tokens||$.reasoning_tokens||0},w=!0),b){let I=b.reasoning||b.reasoning_content||null;I&&(y.push({text:I,thought:!0}),w=!0),b.content&&(y.push({text:b.content}),w=!0)}}catch{}if((_||Date.now()-x>=150||m)&&w&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],x=Date.now(),w=!1),_)break}Date.now()-x>=150&&w&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],x=Date.now(),w=!1)}};var er=async function*(e,n,t,o,s,r,a,i,p=1){let d=[];o&&d.push({role:"system",content:o});for(let k of t){let C=k.role==="user"?"user":"assistant",R=[];if(Array.isArray(k.parts)){for(let S of k.parts)if(S.text)R.push({type:"text",text:S.text});else if(S.inlineData&&a){let T=S.inlineData.mimeType,_=S.inlineData.data;T.startsWith("image/")&&R.push({type:"image_url",image_url:{url:`data:${T};base64,${_}`}})}}else{let S=k.text||"";S&&R.push({type:"text",text:S})}d.push({role:C,content:R.length===1&&R[0].type==="text"?R[0].text:R})}let l={Fast:"minimal",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},c={model:n,messages:d,stream:!0,stream_options:{include_usage:!0},temperature:p};l[s]&&(c.reasoning_effort=l[s]);let f=await It("https://aihubmix.com/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(c),signal:i});if(!f.ok){let k=await f.json().catch(()=>({}));throw new Error(`AIHubMix Error (${f.status}): ${k.error?.message||f.statusText}`)}let u=f.body.getReader(),h=new TextDecoder,g="",y=[],m=null,x=Date.now(),w=!1;for(;;){let{done:k,value:C}=await u.read();if(k){w&&(y.length>0||m)&&(yield{candidates:y.length>0?[{content:{parts:y}}]:[],usageMetadata:m});break}g+=h.decode(C,{stream:!0});let R=g.split(`
|
|
515
|
+
`);g=R.pop();for(let S of R){let T=S.trim();if(!T||!T.startsWith("data: "))continue;let _=!1;if(T==="data: [DONE]")_=!0;else try{let E=JSON.parse(T.substring(6)),b=E.choices?.[0]?.delta,$=E.usage;if(E.choices?.[0]?.finish_reason&&(_=!0),$&&(m={totalTokenCount:$.total_tokens||($.prompt_tokens||0)+($.completion_tokens||0),promptTokenCount:$.prompt_tokens||0,candidatesTokenCount:$.completion_tokens||0,cachedContentTokenCount:$.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:$.completion_tokens_details?.reasoning_tokens||$.reasoning_tokens||0},w=!0),b){let I=b.reasoning_content||null;I&&(y.push({text:I,thought:!0}),w=!0),b.content&&(y.push({text:b.content}),w=!0)}}catch{}if((_||Date.now()-x>=150)&&w&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],x=Date.now(),w=!1),_)break}Date.now()-x>=150&&w&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],x=Date.now(),w=!1)}};hi.config({quiet:!0});hi.config({path:"./fluxflow.env",override:!0,quiet:!0});hi.config({path:"./.fluxflow.env",override:!0,quiet:!0});var hc=/```[\s\S]*?```/g,mc=/```[\s\S]*$/g,gc=/`[^`]+`/g,yc=/^\|.*\|$/gm,wc=/^[^\w]+|[^\w]+$/g,xc=/[^a-z0-9]/gi,yo=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,bc=/\[\s*(?:tool:functions\.|agent:generalist\.)([a-z0-9_]+)\s*\(/gi,kc=/(?:path|targetFile|TargetFile|directory|keyword|id|taskId|title|task)\s*=\s*\\?["']?([^\\"' \),]+)/,bs=/["']/g,Ia=/\\/g,Sc=/<\|channel>thought/gi,Tc=/<channel\|>/gi,Rc=e=>typeof e!="string"?e:e.replace(Sc,"<think>").replace(Tc,"</think>"),ng=/^\s*(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\]|$)/i,Ec=(e,n)=>{let t=!1;for(let o=0;o<n;o++)e[o]==="`"&&(t=!t);return t},_c=e=>{let n=/(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\])/gi,t;for(;(t=n.exec(e))!==null;)if(!Ec(e,t.index))return{index:t.index,length:t[0].length};return{index:-1,length:0}},ui=e=>{if(!e||typeof e!="string")return null;let n=e.match(/^\s*(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought|\[(think|thought|thoughts)\])/i);if(!n)return null;let t=n.index+n[0].length,o=e.substring(t),s=_c(o);if(s.index!==-1){let r=t+s.index+s.length;return{fullBlock:e.substring(0,r),innerContent:o.substring(0,s.index),remainingText:e.substring(r)}}return{fullBlock:e,innerContent:o,remainingText:""}},on=e=>{if(!e||typeof e!="string")return e;let n=ui(e);return n?n.remainingText.trimStart():e};var Ba=/`[^`]*`/g,Ua=/`[^`]*$/,Oa=/<\|\s*tool_call_begin\s*\|>\s*(?:(?:tool|functions)\b[\s._]*)*([a-zA-Z0-9_]+)(?::\d+)?\s*<\|\s*tool_call_argument_begin\s*\|>([\s\S]*?)<\|\s*tool_call_end\s*\|>/gi,Cc=/"([^"]+)"\s*:\s*(?:"([^"]*)"|(\d+)|true|false|null)/g,La=/<\|\s*tool_calls_section_begin\s*\|>/gi,Da=/<\|\s*tool_calls_section_end\s*\|>/gi,$c=/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi;var Pa=e=>!e||typeof e!="string"?e:e.replace(/(```[\s\S]*?```|`[^`]*`)|(<(?:\w+)(?:[^>]*)>\r?\n?|\r?\n?<\/\w+(?:[^>]*)>)/gi,(n,t)=>t||""),mi=null,tr={},ks={key:null,value:null},sn=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|Execution Error|Loop Detected|Contacting Ancestors)\b/ig,(n,t,o,s,r)=>`${t||""}${o}${s||""} \x1B[95m${r}\x1B[0m`),Mc=async(e,n=8,t=1e3,o=8e3,s=null)=>{let r=0;for(;;){if(s?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{return await e()}catch(a){if(s?.aborted||a?.name==="AbortError"||a?.message==="Subagent task was cancelled."||(r++,r>=n))throw a;let i=Math.min(t*Math.pow(2,r-1),o);await new Promise((p,d)=>{let l=setTimeout(p,i);s&&s.addEventListener("abort",()=>{clearTimeout(l),d(new DOMException("The user aborted a request.","AbortError"))})})}}},Mt=!1;var Ac=e=>{let n=e.filter(s=>(s.role==="user"||s.role==="agent"||s.role==="system")&&s.role!=="think"&&!s.isVisualFeedback&&!s.isMeta&&!s.isTerminalRecord&&!(s.text&&s.text.includes("[TERMINAL_RECORD]"))&&!String(s.id).startsWith("welcome")).map((s,r,a)=>{let i=s.fullText||s.text||"";if(s.role==="user"&&r<a.length-1)if(i.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")){let p=i.indexOf("**CONTEXT SUMMARY OF PREVIOUS TURNS");if(p!==-1){let l=i.substring(0,p).lastIndexOf("[SYSTEM METADATA]");l!==-1?i=i.substring(l).trim():i=i.substring(p).trim()}}else{let p=i.lastIndexOf("[USER]"),d=i.lastIndexOf("[USER PROMPT]");p!==-1?i=i.substring(p+6).trim():d!==-1&&(i=i.substring(d).trim())}return{...s,text:i}}),t=[],o=0;for(;o<n.length;){let s=n[o];if(s.role==="user")t.push(s),o++;else{let r=[];for(;o<n.length&&n[o].role!=="user";)r.push(n[o]),o++;let a=[],i=[],p=!1,d=()=>{a.length>0&&(t.push({role:"agent",text:"combined"}),a=[]),i.length>0&&(t.push({role:"system",text:"combined"}),i=[]),p=!1};r.forEach(l=>{let c=l.role==="system"&&(l.text?.startsWith("[TOOL RESULT]")||l.text?.startsWith("SUCCESS:")||l.text?.startsWith("ERROR:")||l.fullText?.startsWith("[TOOL RESULT]")||l.fullText?.startsWith("SUCCESS:")||l.fullText?.startsWith("ERROR:")),f=l.fullText||l.text||"",u=f.trim();if(!(!u&&!l.binaryPart)){if(c)i.push(u);else if(l.role==="agent"){!p&&i.length>0&&d();let h=f.endsWith(`
|
|
516
|
+
`),g=u.toLowerCase().includes("tool:functions.")||u.toLowerCase().includes("agent:generalist.");a.push(u),g&&h?p=!0:p=!1}}}),d()}}return t.length},vc=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),sg=()=>{Mt=!0},og=()=>Mt,pi={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"},Ss=(e,n)=>{try{let t=O(n),o=e.toLowerCase().replace(/_/g,"");if(o==="invokesync"||o==="invoke")return t.title||(t.task?t.task.substring(0,30):null);if(o==="getprogress"||o==="cancel"||o==="steer"||o==="steersubagent")return t.id||t.taskId;let s=t.path||t.targetFile||t.TargetFile||t.directory;return s?te.basename(s.replace(/["']/g,"").replace(/\\/g,"/")):null}catch{return null}},gi=e=>e?new Na({apiKey:e}):mi,rg=async(e,n,t,o,s={})=>{let{onStatus:i,onMemoryUpdated:p,onBackgroundIncrement:d}=s,{profile:l,thinkingLevel:c,mode:f,janitorModel:u,chatId:h,systemSettings:g,sessionStats:y,aiProvider:m="Google",apiKey:x}=e,w=process.env.NVIDIA_BASE_URL||m==="Ollama"||m==="CrofAI"||m==="InferX"||m==="SenseNova"||m==="AIHubMix"?!1:g?.memory!==!1,C=ee(Pt,[]).map(A=>`- [${A.id}]: ${A.memory}`).join(`
|
|
517
|
+
`),R=o.slice(0,-1).filter(A=>A.text&&!A.text.includes("[TOOL RESULT]")&&!A.text.includes("OBSERVATION:")&&!A.text.startsWith("[TERMINAL_RECORD]")&&!A.isTerminalRecord&&!A.isMeta&&!A.isLogo&&!String(A.id).startsWith("welcome")&&!String(A.id).startsWith("logo")).slice(-14).map(A=>{let B=on(vc(A.text)).replace(/\[tool:functions\..*?\]/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[METADATA \(PRIORITY: DYNAMIC\)\] Time: ([^|\n]+)/g,(Fe,He)=>`[METADATA (PRIORITY: DYNAMIC)] Time: ${He.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,`
|
|
518
|
+
`).replace(/\n\n/g,`
|
|
519
|
+
`).replace(/\\n\\n/g,"").trim(),X=A.role==="user"?8192:32768,J=B.substring(0,X);B.length>X&&(J+=`
|
|
520
|
+
... (truncated) ...`);let We=A.role==="user"?J.startsWith("[USER]")?"":"[USER]: ":J.startsWith("[AGENT]")?"":"[AGENT]: ";return{role:A.role==="user"?"user":"model",parts:[{text:`${We}${J}`}]}}),S=o.filter(A=>A.role==="user").length===1,T=n.includes("[TITLE-UPDATE]"),_=Math.random()<.8,E=S||T||_,b=on(t).trim(),$=Pi(C,w,E),I=`${b.replace(/\[tool:functions\..*?\]/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[\[TOOL RESULTS\]\]/g,"").replace(/\[tool results\]/g,"").substring(0,32768)}`;I.length>32768&&(I+=`
|
|
521
|
+
... (truncated) ...`);let D=n.replace(/\[Prompted on:.*?\]/g,"").trim();I=I.replace(/\r?\n\r?\n/g,`
|
|
522
|
+
`).replace(/\n\n/g,`
|
|
523
|
+
`).replace(/\\n\\n/g,"").trim();let N=new Date,Y=`[METADATA] Current date and Time: ${`${N.getFullYear()}-${N.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(N.getDate()).padStart(2,"0")}, ${N.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0})}`}
|
|
524
|
+
|
|
525
|
+
[USER]: ${D.substring(0,8192)}
|
|
526
|
+
${D.length>8192?`... (truncated) ...
|
|
527
|
+
|
|
528
|
+
`:""}
|
|
529
|
+
[AGENT (current turn)]: ${I}`;R.push({role:"user",parts:[{text:Y}]});let ae=await ur("NVIDIA"),F=(await Ft()).quotas?.providerTiers?.NVIDIA==="Free",U="",oe=0,ve=w?12:-1;for(;oe<=ve;)try{if(!await ji("background",e))return;let A="",B=null,X=!1,J=m;try{let He=new Promise((lt,Te)=>setTimeout(()=>Te(new Error("JANITOR_TIMEOUT")),1e4)),at=m==="Google"&&oe>=0&&oe<6&&ae&&F,Ke=m==="DeepSeek"&&oe<4&&ae&&F;X=at||Ke,J=X?"NVIDIA":m;let kt=(async()=>{if(m==="OpenRouter"){let lt=_e("janitor_open_router"),re=Xo(x,lt,R,$,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),Xt=await re.next();return{iterator:re,firstResult:Xt}}else if(m==="DeepSeek"&&!X){let Te=Ko(x,_e("deepseek_fast_fallback"),R,$,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),re=await Te.next();return{iterator:Te,firstResult:re}}else if(m==="Mistral"&&!X){let Te=Yo(x,_e("mistral_janitor_fallback"),R,$,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),re=await Te.next();return{iterator:Te,firstResult:re}}else if(m==="NVIDIA"||X){let Te=Vo(X?ae:x,_e("nvidia_janitor_fallback"),R,$,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),re=await Te.next();return{iterator:Te,firstResult:re}}else if(m==="CrofAI"){let Te=Jo(x,targetModel||_e("crofai_fallback")||"deepseek-v4-flash-0731",R,$,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),re=await Te.next();return{iterator:Te,firstResult:re}}else if(m==="InferX"){let Te=Qo(x,targetModel||_e("inferx_fallback")||"deepseek-v4-flash",R,$,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),re=await Te.next();return{iterator:Te,firstResult:re}}else if(m==="SenseNova"){let Te=Zo(x,targetModel||_e("sensenova_fallback")||"sensenova-6.8-flash-lite",R,$,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),re=await Te.next();return{iterator:Te,firstResult:re}}else if(m==="AIHubMix"){let Te=er(x,targetModel||_e("aihubmix_fallback")||"gpt-4o-mini",R,$,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),re=await Te.next();return{iterator:Te,firstResult:re}}else{let re=(await gi(x).models.generateContentStream({model:u||(oe===ve?_e("janitor_default"):_e("gemma_janitor_fallback_google")),contents:R,config:{systemInstruction:$,temperature:.7,safetySettings:[{category:Qn.HARM_CATEGORY_HARASSMENT,threshold:Jn.BLOCK_NONE},{category:Qn.HARM_CATEGORY_HATE_SPEECH,threshold:Jn.BLOCK_NONE},{category:Qn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Jn.BLOCK_NONE},{category:Qn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Jn.BLOCK_NONE}],thinkingConfig:{includeThoughts:!1,thinkingLevel:ut.MINIMAL}}}))[Symbol.asyncIterator](),Xt=await re.next();return{iterator:re,firstResult:Xt}}})();if(process.stdout.isTTY){let re=(await fs())[h]?.name||"",Xt=re&&!re.startsWith("flow-")&&!re.startsWith("Session ")?re:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${Xt}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${Xt}\x07`)}let{iterator:Bt,firstResult:mt}=await Promise.race([kt,He]),{value:St,done:Et}=mt;if(!Et&&St){let lt=St.candidates?.[0]?.content?.parts,Te=lt?J==="Google"?lt[1]?.text||lt[0]?.text||"":lt.filter(re=>re.text&&!re.thought).map(re=>re.text).join(""):typeof St.text=="function"?St.text():"";Te&&(A+=Te),B=St.usageMetadata;for await(let re of{[Symbol.asyncIterator]:()=>Bt}){let Xt=re.candidates?.[0]?.content?.parts,Zn=Xt?J==="Google"?Xt[1]?.text||Xt[0]?.text||"":Xt.filter(es=>es.text&&!es.thought).map(es=>es.text).join(""):typeof re.text=="function"?re.text():"";Zn&&(A+=Zn),B=re.usageMetadata}}}catch(He){throw He}if(A){if(U=A,B){let He=B.totalTokenCount||0,at=B.cachedContentTokenCount||0,Ke=(B.candidatesTokenCount||0)+(B.thoughtsTokenCount||0),kt=X?_e("nvidia_janitor_fallback"):J==="DeepSeek"?_e("deepseek_fast_fallback"):J==="OpenRouter"?_e("janitor_open_router"):u||(oe===ve?_e("janitor_default"):_e("gemma_janitor_fallback_google"));await Yt("tokens",He,J,kt),at>0&&await Yt("cachedTokens",at,J,kt),Ke>0&&await Yt("candidateTokens",Ke,J,kt)}}else throw new Error("No synthesis generated by Janitor.");d&&(d(),await vt("background"));let We=sr(U),Fe=!1;for(let He of We){let at=He.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(at)&&(Fe=!0);let Ke={chatId:h,sessionId:h,history:o},kt=await mo(at,He.args,Ke);at.toLowerCase()==="memory"&&(He.args.includes("action='user'")||He.args.includes('action="user"'))&&!kt.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(mt=>setTimeout(mt,3e3)))}if(!Fe)try{let He=ee(Pt,[]);if(He.length>0){let at=[];for(let Ke of He)Ke.score===void 0&&(Ke.score=.5),Ke.score*=.99995,Ke.score<.05&&(Ke.score=0),Ke.score=Math.round(Ke.score*1e5)/1e5,Ke.score>0&&at.push(Ke);ge(Pt,at)}}catch{}break}catch(A){oe++;let B=new Date().toLocaleString(),X=A instanceof Error?(()=>{try{return JSON.parse(JSON.parse(A.message).error.message).error.message}catch{return String(A)}})():String(A);await new Promise(Fe=>setTimeout(Fe,1e3));let J=te.join(gn,"janitor");if(Pe.existsSync(J)||Pe.mkdirSync(J,{recursive:!0}),Pe.appendFileSync(te.join(J,"error.log"),`ERROR [Attempt ${oe}/${ve+1}] [${B}]: ${X}
|
|
530
|
+
|
|
531
|
+
`),oe>ve)break;let We=Math.min(750*Math.pow(2,oe-1),5e3);await new Promise(Fe=>setTimeout(Fe,We))}if(oe){let A=te.join(gn,"janitor");Pe.appendFileSync(te.join(A,"error.log"),`-----------------------------------------------------------------------------
|
|
532
|
+
|
|
533
|
+
`)}if(process.stdout.isTTY)try{let X=(await fs())[h]?.name||"",J=X&&!X.startsWith("flow-")&&!X.startsWith("Session ")?X:"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")}},Ic=e=>{let n=on(e),t=Ps?n:n.replace(Ba,s=>" ".repeat(s.length)).replace(Ua,s=>" ".repeat(s.length));yo.lastIndex=0;let o;for(;(o=yo.exec(t))!==null;){let s=o.index+o[0].length-1,r=0,a=null,i=!1,p=!1;for(let d=s;d<t.length;d++){let l=n[d];if(!a&&(l==='"'||l==="'"||l==="`")?(a=l,i=!1):a&&l===a&&!i&&(a=null),!a&&(l==="("?r++:l===")"&&r--,r===0)){let c=d+1;for(;c<t.length&&/\s/.test(t[c]);)c++;if(c<t.length&&t[c]==="]"){p=!0,yo.lastIndex=c+1;break}}l==="\\"?i=!i:i=!1}if(!p)return{inside:!0,toolName:o[1],startIndex:o.index,args:n.substring(o.index+o[0].length)}}return{inside:!1}},Wa=(e,n=!0)=>{let t=yo;t.lastIndex=0;let o="",s=0,r;for(;(r=t.exec(e))!==null;){let a=e.substring(s,r.index);o+=n&&s===0?on(a):a;let i=r.index+r[0].length-1,p=0,d=null,l=-1;for(let c=i;c<e.length;c++){let f=e[c];if(d){if(f===d){let u=0;for(let h=c-1;h>=0&&e[h]==="\\";h--)u++;u%2===0&&(d=null)}}else if(f==='"'||f==="'"||f==="`")d=f;else if(f==="(")p++;else if(f===")"&&(p--,p===0)){let u=c+1;for(;u<e.length&&/\s/.test(e[u]);)u++;if(u<e.length&&e[u]==="]"){l=u;break}}}if(l!==-1)o+="[tool:functions."+r[1]+"()]",s=l+1,t.lastIndex=s;else{o+="[tool:functions."+r[1]+"(",s=e.length;break}}return s<e.length&&(o+=n&&s===0?on(e.substring(s)):e.substring(s)),o},Oc=(e,n,t)=>{let o=yo;o.lastIndex=0;let s="",r=0,a;for(;(a=o.exec(e))!==null;){let i=e.substring(r,a.index);s+=i.replace(n,t);let p=a.index+a[0].length-1,d=0,l=null,c=-1;for(let f=p;f<e.length;f++){let u=e[f];if(l){if(u===l){let h=0;for(let g=f-1;g>=0&&e[g]==="\\";g--)h++;h%2===0&&(l=null)}}else if(u==='"'||u==="'"||u==="`")l=u;else if(u==="(")d++;else if(u===")"&&(d--,d===0)){let h=f+1;for(;h<e.length&&/\s/.test(e[h]);)h++;if(h<e.length&&e[h]==="]"){c=h;break}}}if(c!==-1)s+=e.substring(a.index,c+1),r=c+1,o.lastIndex=r;else{s+=e.substring(a.index),r=e.length;break}}return r<e.length&&(s+=e.substring(r).replace(n,t)),s},Fa=e=>Wa(e,!0),Lc=e=>{if(!e)return e;let n={patchfile:"PatchFile",writefile:"WriteFile",readfile:"ReadFile",viewfile:"ReadFile",run:"Run",execcommand:"Run",searchkeyword:"SearchKeyword",codesearch:"CodeSearch",code_search:"CodeSearch",websearch:"WebSearch",webscrape:"WebScrape",readfolder:"ReadFolder",writepdf:"WritePDF",writedoc:"WriteDoc",writedocx:"WriteDoc",filemap:"FileMap",generateimage:"GenerateImage",todo:"Todo",goal:"Goal",askuser:"AskUser",ask:"AskUser"},t=s=>s.split("_").map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join("");Oa.lastIndex=0;let o=e.replace(Oa,(s,r,a)=>{let i="";try{let l=JSON.parse(a.trim());l&&typeof l=="object"&&(i=Object.entries(l).map(([f,u])=>{let h=typeof u=="string"?u:JSON.stringify(u);return`${f}=${JSON.stringify(h)}`}).join(", "))}catch{let c=[],f=Cc;f.lastIndex=0;let u;for(;(u=f.exec(a))!==null;){let h=u[1],g=u[2]!==void 0?u[2]:u[0].split(":").slice(1).join(":").trim();c.push(`${h}=${JSON.stringify(g)}`)}c.length>0?i=c.join(", "):i=a.trim()}let p=r.toLowerCase().replace(/_/g,"");return`[tool:functions.${n[p]||t(r)}(${i})]`});return La.lastIndex=0,Da.lastIndex=0,o=o.replace(La,""),o=o.replace(Da,""),o},Dc=/(?:path|query|url|keyword|command|method|title|task|id)\s*=\s*['"`]?\s*\.\.\.\s*['"`]?/i,Pc=/^['"`]?\s*\.\.\.\s*['"`]?$/,Bn=e=>{if(e==null)return!1;let n=String(e).trim();return n==="..."||n==="\u2026"||Pc.test(n)},sr=e=>{if(!e)return[];let n=Lc(e),t=on(n),o=[],s=Ps?t:t.replace(Ba,i=>" ".repeat(i.length)).replace(Ua,i=>" ".repeat(i.length)),r=bc;r.lastIndex=0;let a;for(;(a=r.exec(s))!==null;){let i=a[1],p=a.index+a[0].length-1,d=0,l=null,c=-1,f=-1;for(let u=p;u<s.length;u++){let h=t[u];if(l){if(h===l){let g=0;for(let y=u-1;y>=0&&t[y]==="\\";y--)g++;g%2===0&&(l=null)}}else if(h==='"'||h==="'"||h==="`")l=h;else if(h==="(")d++;else if(h===")"&&(d--,d===0)){f=u;let g=u+1;for(;g<s.length&&/\s/.test(s[g]);)g++;if(g<s.length&&s[g]==="]"){c=g;break}}}if(c!==-1){let u=t.substring(p+1,f),h=t.substring(a.index,c+1),g=O(u);Bn(g.path)||Bn(g.query)||Bn(g.url)||Bn(g.keyword)||Bn(g.command)||Bn(g.method)||Bn(g.title)||Bn(g.task)||Bn(g.id)||Dc.test(u)||o.push({fullMatch:h,toolName:i.trim(),args:u.trim()}),r.lastIndex=c+1}}return o},ig=(e,n={})=>{if(!e)return null;if(tr=n,mi=new Na({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}}}},nr=async(e,n,t,o,s="Fast",r=.75,a="agent")=>Mc(async()=>{let{aiProvider:i="Google",apiKey:p,mode:d}=e,l="",c=null,f=typeof t=="string"?[{role:"user",parts:[{text:t}]}]:t,u=new AbortController,h=u.signal,g=setInterval(()=>{Mt&&(u.abort(),clearInterval(g))},100);try{let y;i==="Ollama"?y=fi(p,n,f,o,s,d,At(n),h,r,systemSettings?.ollamaEndpoint||"Cloud"):i==="OpenRouter"?y=Xo(p,n,f,o,s,d,At(n),h,r):i==="DeepSeek"?y=Ko(p,n,f,o,s,d,At(n),h,r):i==="Mistral"?y=Yo(p,n,f,o,s,d,At(n),h,r):i==="NVIDIA"?y=Vo(p,n,f,o,s,d,At(n),h,r):i==="CrofAI"?y=Jo(p,n,f,o,s,d,At(n),h,r):i==="InferX"?y=Qo(p,n,f,o,s,d,At(n),h,r):i==="SenseNova"?y=Zo(p,n,f,o,s,d,At(n),h,r):i==="AIHubMix"?y=er(p,n,f,o,s,d,At(n),h,r):y=await gi(p).models.generateContentStream({model:n,contents:f,config:{systemInstruction:o,temperature:r,thinkingConfig:(()=>{let w=(n||"").toLowerCase(),k=w.includes("gemma-4")||w.startsWith("gemma"),C=w.includes("gemini-3");if(k||C)return k?s.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:ut.MINIMAL}:{includeThoughts:!0,thinkingLevel:ut.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:w.includes("pro")?ut.LOW:ut.MINIMAL,Low:ut.LOW,Medium:ut.MEDIUM,Standard:ut.MEDIUM,High:ut.HIGH,xHigh:ut.HIGH}[s]||ut.MEDIUM};{let R={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[s]||2048;return R===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:R}}})()}},{signal:h});for await(let m of y){if(Mt)throw new Error("Subagent task was cancelled.");if(e?.taskId&&typeof Ve<"u"){let k=Ve.find(C=>C.id===e.taskId);if(k&&k.status==="cancelled")throw new Error("Subagent task was cancelled.")}let x="";if(m.candidates?.[0]?.content?.parts)for(let k of m.candidates[0].content.parts)k.text&&!k.thought&&(l+=k.text,x+=k.text);let w=x?x.trim().split(/\s+/).filter(Boolean).length:0;e&&typeof e.onTokenChunk=="function"&&e.onTokenChunk(x,w),m.usageMetadata&&(c=m.usageMetadata)}}finally{clearInterval(g)}if(c){let y=c.totalTokenCount||0,m=c.cachedContentTokenCount||0,x=(c.candidatesTokenCount||0)+(c.thoughtsTokenCount||0);await Yt("tokens",y,i,n),m>0&&await Yt("cachedTokens",m,i,n),x>0&&await Yt("candidateTokens",x,i,n),e&&typeof e.onUsage=="function"&&e.onUsage({totalTokenCount:y,cachedContentTokenCount:m,candidatesTokenCount:x})}return await vt("agent",i),{text:l,usageMetadata:c}}),Fc=async(e,n,t=null)=>{t=t||ee(nn,{});try{let{aiProvider:o="Google"}=n;if(Object.values(t).flat().length<=5)return;let r=Object.keys(t).filter(f=>f!==e&&Array.isArray(t[f])&&t[f].length>2);if(r.length===0)return;let a=`You are a silent background process for the FluxFlow CLI Agent.
|
|
534
|
+
Your task is to summarize or merge temporary context memories from one or more past conversation sessions.
|
|
535
|
+
For each Chat ID provided, you must output a tool call to save the consolidated summary.
|
|
536
|
+
|
|
537
|
+
The tool call format MUST be:
|
|
538
|
+
[tool:functions.saveSummary(id="<chat-id>", summary="<updated summary string, max 400 words>")]
|
|
539
|
+
|
|
540
|
+
Guidelines:
|
|
541
|
+
- 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.
|
|
542
|
+
- Focus on key goals, preferences, modified files, and technical decisions.
|
|
543
|
+
- Under no circumstances write normal conversational text. Output ONLY the tool calls.
|
|
544
|
+
- You can stack multiple tool calls for multiple chats.
|
|
545
|
+
|
|
546
|
+
Chats to process:
|
|
547
|
+
|
|
548
|
+
`,i=ee(Ln,{});for(let f of r){let h=t[f].map(y=>`- ${y}`).join(`
|
|
549
|
+
`),g=i[f];a+=`[Chat ID: ${f}]
|
|
550
|
+
`,g?(a+=`- Existing Summary: "${g}"
|
|
551
|
+
`,a+=`
|
|
552
|
+
-- New Memories to integrate:
|
|
553
|
+
${h}
|
|
554
|
+
|
|
555
|
+
`):a+=`-- Individual Memories:
|
|
556
|
+
${h}
|
|
557
|
+
|
|
558
|
+
`}let p=0,d=5,l=!1,c=_e("gemma_janitor_fallback_google");for(o==="OpenRouter"&&(c=_e("janitor_open_router")),o==="DeepSeek"&&(c=_e("deepseek_level_1")),o==="Mistral"&&(c=_e("mistral_level_1")),o==="NVIDIA"&&(c=_e("nvidia_janitor_fallback")),o==="CrofAI"&&(c=_e("crofai_fallback")),o==="InferX"&&(c=_e("inferx_fallback")),o==="SenseNova"&&(c=_e("sensenova_fallback")),o==="AIHubMix"&&(c=_e("aihubmix_fallback"));p<=d&&!l;){p++;try{let u=(await nr(n,c,a,null,"Fast",.75,"background")).text||"",h=sr(u);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 mo(y,g.args,{chatId:e})}l=!0}catch(f){if(p>=d)throw new Error(`Failed after ${d} attempts. Last error: ${f.message}`)}}}catch(o){let s=o instanceof Error?(()=>{try{return JSON.parse(JSON.parse(o.message).error.message).error.message}catch{return String(o)}})():String(o),r=te.join(gn,"janitor");Pe.existsSync(r)||Pe.mkdirSync(r,{recursive:!0}),Pe.appendFileSync(te.join(r,"error.log"),`[${new Date().toLocaleString()}] Past memory batch consolidation error: ${s}
|
|
559
|
+
`)}},Nc=async(e,n,t=!1)=>{let{chatId:o,aiProvider:s="Google"}=e,r=te.join(To,"chat-summaries.json"),a=u=>u.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(`
|
|
560
|
+
|
|
561
|
+
`),i=async(u,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:
|
|
562
|
+
${h}
|
|
563
|
+
|
|
564
|
+
Here is the new conversation history:
|
|
565
|
+
${u}
|
|
566
|
+
|
|
567
|
+
Provide a new consolidated summary of the entire session.`:`Here is the conversation history:
|
|
568
|
+
${u}
|
|
569
|
+
|
|
570
|
+
Provide a consolidated summary of the entire session.`,m=_e("gemma_janitor_fallback_google");s==="OpenRouter"&&(m=_e("janitor_open_router")),s==="DeepSeek"&&(m=_e("deepseek_level_1")),s==="Mistral"&&(m=_e("mistral_level_1")),s==="NVIDIA"&&(m=_e("nvidia_chat_summarizer_fallback")),s==="CrofAI"&&(m=_e("crofai_fallback")),s==="InferX"&&(m=_e("inferx_fallback")),s==="SenseNova"&&(m=_e("sensenova_fallback")),s==="AIHubMix"&&(m=_e("aihubmix_fallback"));let x=0,w=!1,k=null;for(;x<=3&&!w;){x++;try{k=await nr(e,m,y,g,"Fast"),w=!0}catch{if(x>3){if(s==="Google")try{let R=_e("general_fallback");return(await nr(e,R,y,g,"Fast")).text||""}catch{return""}return""}}}return k&&k.text||""},p=a(n),d=ee(r,{}),l=d[o]||{summary:"",historyLength:0};typeof l=="string"&&(l={summary:l,historyLength:0});let c=l.summary||"",f=await i(p,c);if(f){l.summary=f;let u=Ac(n);return t?l.historyLength=(l.historyLength||0)+u:l.historyLength=u,d[o]=l,ge(r,d),f}return null},ag=e=>{try{let n=te.join(To,"chat-summaries.json");if(Pe.existsSync(n)){let t=ee(n,{});t[e]&&(delete t[e],ge(n,t))}}catch{}},lg=async function*(e,n,t,o,s){let{profile:r,thinkingLevel:a,mode:i,janitorModel:p,chatId:d,isPlayground:l,systemSettings:c,sessionStats:f,aiProvider:u="Google",apiTier:h,wildcardTooling:g}=t,y=At(e);if(!mi&&u==="Google")throw new Error("AI not initialized");let m=process.env.NVIDIA_BASE_URL||t?.aiProvider==="Ollama"||t?.aiProvider==="CrofAI"||t?.aiProvider==="InferX"||t?.aiProvider==="SenseNova"||t?.aiProvider==="AIHubMix"?!1:c?.memory!==!1,x=n[n.length-1].text,w=te.join(To,"chat-summaries.json"),k=!1,C=n.filter(E=>E.role==="user").length===1,R=x.includes("[TITLE-UPDATE]"),S=C||R,T=x.replace(/\[TITLE-UPDATE\]/g,"").trim();T=T.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),yield{type:"status",content:"[start]"},yield{type:"status",content:"Gathering Context"},await ht.startTransaction(d,T),c?.advanceRollback&&await Xn.takeInitialSnapshot(d),Mt=!1;let _=null;try{let E=new AbortController;_=setInterval(()=>{Mt&&(E.abort(),_&&(clearInterval(_),_=null))},400);let b=[...n.slice(0,-1)];{let De=ee(w,{})[d]||{summary:"",historyLength:0};if(De.summary&&De.historyLength>0){let rn=0,$e=[];for(let Ze=0;Ze<b.length;Ze++){let Ge=b[Ze];(Ge.role==="user"||Ge.role==="agent"||Ge.role==="system")&&!String(Ge.id).startsWith("welcome")&&!Ge.isMeta&&rn++,rn>De.historyLength&&$e.push(Ge)}b=$e}}b=b.map(q=>{if(q.role==="user"&&q.text){let De=q.text.match(/\[USER\]([\s\S]*?)\[\/USER\]/);if(De)return{...q,text:De[1].trim()}}return{...q}});let $=process.env.HIGH_CONTEXT,I=255e3,D=26e4;if($&&$!=="false"){let q=parseInt($,10);!isNaN(q)&&q>=0&&q<=1e6&&(D=q,I=Math.round(q*.85))}if((u==="NVIDIA"&&(e?.includes("gpt")||e?.includes("qwen")||e?.includes("medium")||e.includes("muse"))||u==="Mistral")&&(I=122e3,D=126e3),u==="Ollama"&&(f?.tokens||0)>I){yield{type:"text",content:"\u2726 Maximum Context Limit Reached. Start a new chat."};return}if(u!=="Ollama"&&(f?.tokens||0)>I&&(yield{type:"status_history",content:"Context Limit Reached. Condensing session history..."},await Nc(t,b,!0)&&(b=[],k=!0)),C&&m){let q=ee(nn,{});Object.values(q).flat().length>5&&(yield{type:"status",content:"Condensing past chat memories"},await Fc(d,t,q))}let N=ee(nn,{}),W=ee(Ln,{}),Y=Object.entries(N).filter(([q])=>q!==d).flatMap(([q,De])=>De),V=[...Object.entries(W).filter(([q])=>q!==d).slice(-20).map(([q,De])=>`[Chat Summary]: ${De}`),...Y].map(q=>`- ${q}`).join(`
|
|
571
|
+
`),U=ee(Pt,[]).map(q=>`- ${q.memory}`).join(`
|
|
572
|
+
`),oe=(f?.tokens||0)>=1e4,ve=Li(V,U,m,oe),A=new Date,B=A.getFullYear(),X=A.toLocaleString("en-US",{month:"short"}).toUpperCase(),J=String(A.getDate()).padStart(2,"0"),We=A.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}),Fe=`${B}-${X}-${J}, ${We}`,He=[".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"],at=q=>{try{return Pe.readdirSync(q,{withFileTypes:!0})}catch{return[]}},Ke=(q,De={value:0},rn=1)=>{if(De.value>6200||rn>7)return De.value;let $e=at(q);for(let Ze of $e){if(De.value>6200)break;He.includes(Ze.name)||Ze.name.startsWith(".")||Ze.isDirectory()&&(De.value++,Ke(te.join(q,Ze.name),De,rn+1))}return De.value},kt=(q,De)=>c?.indentationTree!==!1?li(q,De,1,at,He):di(q,De,"",1,at,He),Bt=Ke(process.cwd()),mt=12;Bt>3072?mt=1:Bt>2304?mt=2:Bt>1536?mt=3:Bt>768?mt=4:Bt>384?mt=6:Bt>192?mt=7:Bt>96?mt=8:Bt>48?mt=9:Bt>24&&(mt=10);let St=ee(fr,{}),Et=St[d],lt=Et?Et!==process.cwd():!1;St[d]=process.cwd(),ge(fr,St);let Te=ee(w,{}),re=Te[d]||{summary:"",historyLength:0};typeof re=="string"&&(re={summary:re,historyLength:0});let Xt=n.filter(q=>(q.role==="user"||q.role==="agent"||q.role==="system")&&!String(q.id).startsWith("welcome")&&!q.isMeta).length;re.historyLength&&Xt<re.historyLength&&(re.summary="",re.historyLength=0,Te[d]=re,ge(w,Te));let Zn=typeof re=="object"?re.summary||"":re||"",es=b.length>0;es&&Zn&&b[0]&&(b[0].role==="user"||b[0].role==="system")&&(b[0].text.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")||(b[0].text=`[SYSTEM METADATA]
|
|
573
|
+
**CONTEXT SUMMARY OF PREVIOUS TURNS (PRIORITY: DYNAMIC)**
|
|
574
|
+
${Zn}
|
|
575
|
+
|
|
576
|
+
[USER] ${b[0].text}`,yield{type:"summary_injected",content:{id:b[0].id,text:b[0].text}}));let yi=Zn&&!es?`
|
|
577
|
+
[SYSTEM METADATA]
|
|
578
|
+
**CONTEXT SUMMARY OF PREVIOUS TURNS**
|
|
579
|
+
${Zn}
|
|
580
|
+
`:"",wi=!!c?.dynamicDirAwareness,ja=`${d}|${u}|${a}|${e}|${r}|${wi}`,xi=!wi&&ks.key===ja&&ks.value?"":`
|
|
581
|
+
**Directory Structure**
|
|
582
|
+
CWD: `+process.cwd()+`${l?" [PLAYGROUND MODE]":""}
|
|
583
|
+
`+kt(process.cwd(),mt),Tt=await xs(),Un="";if(qo()&&Tt.file_focused!=="none"){Un=`
|
|
584
|
+
[Additional IDE Context]
|
|
585
|
+
`;let q=te.relative(process.cwd(),Tt.file_focused),De=(Tt.opened_editors||[]).map($e=>{let Ze=te.relative(process.cwd(),$e);return Ze.startsWith("..")?`[External] ${te.basename($e)}`:Ze});if(Un+=`Focused File: ${q}
|
|
586
|
+
Cursor Line: ${Tt.cursor_line}
|
|
587
|
+
`,Tt.selected){let $e=Tt.selected,Ze=$e.split(`
|
|
588
|
+
`);Ze.length>256&&($e=Ze.slice(0,240).join(`
|
|
589
|
+
`)+`
|
|
590
|
+
... [truncated] ...
|
|
591
|
+
`+Ze.slice(-16).join(`
|
|
592
|
+
`)),$e.length>2048&&($e=$e.slice(0,1920)+`
|
|
593
|
+
... [truncated] ...
|
|
594
|
+
`+$e.slice(-128)),Un+=`Current Selection: "${$e}"
|
|
595
|
+
`}if(Tt.manual_edits){let Ze=Tt.manual_edits.split(`
|
|
596
|
+
`),Ge=[],Xe=null;for(let z of Ze)z.trim()&&(z.startsWith(" Line ")?Xe&&Xe.edits.push(z):(Xe={path:z.endsWith(":")?z.slice(0,-1):z,edits:[]},Ge.push(Xe)));for(let z of Ge)z.edits.length>80&&(z.edits=z.edits.slice(-80)),z.originalEditsCount=z.edits.length;let he=(z,Q)=>Q.reduce((qe,pn)=>{let Sn=Tt.file_focused&&(pn.path===Tt.file_focused||te.resolve(process.cwd(),pn.path)===te.resolve(Tt.file_focused))?Math.ceil(z*1.2):z;return qe+Math.min(pn.edits.length,Sn)},0),Ut=80;if(he(80,Ge)>300){let z=!1;for(let Q=80;Q>=10;Q--)if(he(Q,Ge)<=300){Ut=Q,z=!0;break}z||(Ut=10)}let Je=[...Ge];if(Ut===10&&he(10,Je)>500)for(;Je.length>0&&he(10,Je)>500;){let z=0,Q=Je[0].originalEditsCount;for(let qe=1;qe<Je.length;qe++)Je[qe].originalEditsCount<Q&&(Q=Je[qe].originalEditsCount,z=qe);Je.splice(z,1)}for(let z of Je){let qe=Tt.file_focused&&(z.path===Tt.file_focused||te.resolve(process.cwd(),z.path)===te.resolve(Tt.file_focused))?Math.ceil(Ut*1.2):Ut;z.edits.length>qe&&(z.edits=z.edits.slice(-qe))}for(let z of Je){let Q=`${z.path}:
|
|
597
|
+
${z.edits.join(`
|
|
598
|
+
`)}`;for(;z.edits.length>0&&Q.length>4*768;)z.edits.shift(),Q=`${z.path}:
|
|
599
|
+
${z.edits.join(`
|
|
600
|
+
`)}`;Q.length>4*768?z.stringRepresentation="... "+Q.slice(-(4*768-4)):z.stringRepresentation=Q}let an=Je.map(z=>z.stringRepresentation).join(`
|
|
601
|
+
`);for(;Je.length>0&&an.length>4*2048;){Je[0].edits.length>0?Je[0].edits.shift():Je.shift();for(let z of Je){let Q=`${z.path}:
|
|
602
|
+
${z.edits.join(`
|
|
603
|
+
`)}`;Q.length>4*768?z.stringRepresentation="... "+Q.slice(-(4*768-4)):z.stringRepresentation=Q}an=Je.map(z=>z.stringRepresentation).join(`
|
|
604
|
+
`)}an.length>4*2048&&(an="... "+an.slice(-(4*2048-4))),Un+=`Recent Manual Edits:
|
|
605
|
+
${an}
|
|
606
|
+
`}De.length>0&&(Un+=`All Opened Editors: ${De.join(", ")}`),Tt.diagnostics&&(Un+=`
|
|
607
|
+
**Active File Errors**:
|
|
608
|
+
${Tt.diagnostics}
|
|
609
|
+
`),(T.toLowerCase().includes("lint")||T.toLowerCase().includes("warning"))&&Tt.warnings&&(Un+=`
|
|
610
|
+
**Lint Warnings**:
|
|
611
|
+
${Tt.warnings}
|
|
612
|
+
`)}let bi=T.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),ki=/(?:\\)?@\[([^\]]+)\]/g,or,rr=[];for(ki.lastIndex=0;(or=ki.exec(bi))!==null;){let q=or[0].startsWith("\\");rr.push({tag:or[1],isEscaped:q})}let ir=[],wo=null;for(let q=0;q<rr.length;q++){let{tag:De,isEscaped:rn}=rr[q];if(!rn)try{let $e=De.trim().replace(/^["']|["']$/g,""),Ze=/[:#]L?(\d+)(?:-L?(\d+))?$/i,Ge=$e.match(Ze),Xe=$e,he=null,Ut=null;Ge&&(he=parseInt(Ge[1],10),Ut=Ge[2]?parseInt(Ge[2],10):he,Xe=$e.slice(0,Ge.index));let Je=te.resolve(process.cwd(),Xe);if(Pe.existsSync(Je)&&Pe.statSync(Je).isFile()){let z=Xe.toLowerCase(),Q=z.endsWith(".pdf"),qe=z.endsWith(".docx")||z.endsWith(".doc")||z.endsWith(".ppt")||z.endsWith(".pptx")||z.endsWith(".xls")||z.endsWith(".xlsx"),pn=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(z),Wt=pn||Q||qe,Sn=u==="Google"||At(e);if(Wt&&!Sn){let je=`\u2718 Unsupported Modality: ${te.basename(Xe)}`,Re=115;process.stdout.isTTY&&(Re=process.stdout.columns-5||120);let et=[je],ss=Math.max(...et.map(Wn=>Wn.length)),hn=Math.min(ss+4,Re),Gs=et.map(Wn=>`${Wn.padEnd(hn-2).substring(0,hn-2)}`).join(`
|
|
613
|
+
`);yield{type:"visual_feedback",content:sn(`${Gs}
|
|
614
|
+
`)};continue}if(he===null&&!Wt){let je=0;try{je=Pe.readFileSync(Je,"utf8").split(/\r\n|\r|\n/).length}catch{}if(je>300){let Re=`\u21B7 Skipped (Too Large): ${te.basename(Xe)}`,et=115;process.stdout.isTTY&&(et=process.stdout.columns-5||120);let ss=Math.min(Re.length+4,et),hn=Re.padEnd(ss-2).substring(0,ss-2);yield{type:"visual_feedback",content:sn(`${hn}
|
|
615
|
+
`)};continue}}let Mn=he!==null?he:1,ts=Ut!==null?Ut:he!==null?he:Mn+299;ts-Mn>300&&(ts=Mn+300);let bo=`path=${JSON.stringify(Xe)}, startLine=${Mn}, endLine=${ts}`,st=await no(bo,{isMultiModal:Sn}),Ye=!1,jt="",ns=null;if(typeof st=="string"?st.trim().startsWith("ERROR")?Ye=!0:jt=st:st&&typeof st=="object"&&st.binaryPart?(ns=st.binaryPart,jt=st.text||""):Ye=!0,!Ye){let je="";if(pn?(je=`\u2714 Processed: ${te.basename(Xe)}`,wo=ns):Q||qe?(je=`\u2714 Auto-Analysed: ${te.basename(Xe)}`,wo=ns):(je=`\u2714 Auto-Read: ${te.basename(Xe)}`,ir.push(jt)),je){let Re=115;process.stdout.isTTY&&(Re=process.stdout.columns-5||120);let et=[je],ss=Math.max(...et.map(Wn=>Wn.length)),hn=Math.min(ss+4,Re),Gs=et.map(Wn=>`${Wn.padEnd(hn-2).substring(0,hn-2)}`).join(`
|
|
616
|
+
`);yield{type:"visual_feedback",content:sn(`${Gs}
|
|
617
|
+
`)}}}}}catch{}}let Si="";ir.length>0&&(Si=`[Tagged File Contents] Auto Read User Tagged files by System, No need to re-read
|
|
618
|
+
`+ir.join(`
|
|
619
|
+
|
|
620
|
+
`)+`
|
|
621
|
+
[Tagged File Contents]
|
|
622
|
+
`);let Ha=bi.replace(/\\(@\[[^\]]+\])/g,"$1"),Ga=g?`You cannot execute tools
|
|
623
|
+
Instead, output in chat the exact string you WOULD have produced & wait for system response
|
|
624
|
+
`:"",qa=process.env.forcedReasoning||!1,Ti=`[System Metadata]
|
|
625
|
+
Time: ${Fe}${c?.dynamicDirAwareness?xi:""}${lt?`
|
|
626
|
+
WARNING: CWD Changed from previous: "${Et}" to current: "${process.cwd()}", write change in chat to avoid future path mismatches
|
|
627
|
+
`:""}${ve}${Un}
|
|
628
|
+
[/Metadata]
|
|
629
|
+
${yi}${a!=="Fast"&&(u==="Mistral"&&!vs(e)||a!=="xHigh"&&u==="Google")?`${u==="Mistral"&&!vs(e)||e.toLowerCase().startsWith("gemma")||qa?`[system] strictly follow thinking policy as high priority. do not start a response without <think>...</think> [/system]
|
|
630
|
+
`:""}`:""}[system] exact tool string [tool:functions.ToolName(arg="value")] in chat [/system]
|
|
631
|
+
${Si}${Ga}[user prompt] ${Ha.trim()} [/user prompt]`.trim(),Ri={role:"user",text:Ti};wo&&(Ri.binaryPart=wo),b.forEach(q=>{q.text&&q.role==="agent"&&(q.text=on(q.text))}),b.push(Ri),yi&&n[n.length-1]?.id&&(yield{type:"summary_injected",content:{id:n[n.length-1].id,text:Ti}});let $n=null,Hs=i==="Flux"?100:10;Hs=i.toLowerCase().includes("cu")?250:Hs;let kn=16;yield{type:"status",content:"Connecting"},Mt=!1;let Ei=[],xo=!1;for(let q=0;q<=Hs;q++){let De=await kr("agent",t);if(!De.allowed)throw new Error(De.reason||`Budget Exhausted for Provider (${u||"Agent"})`);let rn=[];if(xo=!1,i==="ICU"||i==="FluxCU")try{yield{type:"status",content:"Capturing Screen"},await new Promise(be=>setTimeout(be,1e3));let fe=await Ci();if(fe&&fe.base64){let be="[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]",ue={inlineData:{mimeType:fe.mimeType,data:fe.base64}};for(let ot of b)Array.isArray(ot.parts)&&(ot.parts=ot.parts.filter(Ht=>!Ht.inlineData));if(b.length>0&&b[b.length-1].role==="user"){let ot=b[b.length-1];typeof ot.text=="string"&&(ot.text+=`
|
|
632
|
+
|
|
633
|
+
${be}`,Array.isArray(ot.parts)||(ot.parts=[{text:ot.text}]),ot.parts.push(ue))}else b.push({role:"user",text:be,parts:[{text:be},ue]})}}catch(fe){console.error("Vision screenshot capture error:",fe)}if(c?.compression===0&&(f?.tokens||0)>D&&(b=Bi(b,6)),q>0?yield{type:"status",content:"Working"}:yield{type:"status",content:"Connecting"},Mt){try{let{clearPendingNudges:fe}=await import("./subagent_state-LZCOZSUJ.js");fe()}catch{}yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
|
|
634
|
+
|
|
635
|
+
\x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}try{let{consumePendingNudges:fe}=await import("./subagent_state-LZCOZSUJ.js"),be=fe();if(be&&be.length>0){let ue=be.join(`
|
|
636
|
+
|
|
637
|
+
`);b.length>0&&b[b.length-1].role==="user"?b[b.length-1].text+=`
|
|
638
|
+
|
|
639
|
+
${ue}`:b.push({role:"user",text:ue}),yield{type:"status",content:"Subagent Update"}}}catch{}if(o){let fe=await o();fe&&(fe.startsWith("/btw")?b.length>0&&b[b.length-1].role==="user"?b[b.length-1].text+=`
|
|
640
|
+
|
|
641
|
+
[system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
|
|
642
|
+
[question] ${fe.replace("/btw","").trim()} [/question]`:b.push({role:"user",text:`[system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
|
|
643
|
+
[question] ${fe.replace("/btw","").trim()} [/question]`}):b.length>0&&b[b.length-1].role==="user"?b[b.length-1].text+=`
|
|
644
|
+
|
|
645
|
+
[STEERING HINT from USER, HIGH PRIORITY] ${fe.trim().toUpperCase()} [/STEERING HINT]`:b.push({role:"user",text:`[STEERING HINT from USER, HIGH PRIORITY] ${fe.trim().toUpperCase()} [/STEERING HINT]`}),yield{type:"status",content:`${fe.startsWith("/btw")?"Question Forwarded...":"Steering Hint Injected..."}`})}let $e,Ze=!1,Ge=1,Xe=1,he="",Ut=null,Je=null,an=null,z=0,Q=[],qe=0,pn=!1,Wt=!1,Sn=!1,Mn=!1,ts=!0,bo=0,st="",Ye="",jt=!1,ns=!1,je=!0,Re=e,et="";for(;Ge<=kn&&Xe<=kn&&!Ze&&!Mt;){let fe=!1;try{he="",ts&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},ts=!1,Xe===1&&(st=""));let be=P=>{if(!P||!P.includes("[tool:"))return P;let ie="",j=ui(P);j&&(ie=j.fullBlock,P=j.remainingText),P=P.replace($c,(ye,Me)=>Me.includes("[tool:")?Me.trim():ye);let G="",ke=0;for(;ke<P.length;){let ye=P.indexOf("[tool:",ke);if(ye===-1){G+=Pa(P.substring(ke));break}let Me=P.substring(ke,ye);G+=Pa(Me);let tt=-1,H=null,ne=0;for(let Ne=ye;Ne<P.length;Ne++){let M=P[Ne];if(H){if(M===H){let Be=0;for(let Ie=Ne-1;Ie>=0&&P[Ie]==="\\";Ie--)Be++;Be%2===0&&(H=null)}}else if(M==='"'||M==="'"||M==="`")H=M;else if(M==="(")ne++;else if(M===")")ne--;else if(M==="]"&&ne<=0){tt=Ne;break}}if(tt===-1){G+=P.substring(ye);break}G+=P.substring(ye,tt+1),ke=tt+1}return ie+G},ue=b.filter(P=>(P.role==="user"||P.role==="agent"||P.role==="system")&&!String(P.id).startsWith("welcome")&&!P.isMeta&&!P.isTerminalRecord&&!(P.text&&P.text.startsWith("[TERMINAL_RECORD]"))).map((P,ie,j)=>{let G=P.text||"";m||(G=G.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),P.role==="agent"&&(G=be(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 ke=[];return Array.isArray(P.parts)&&P.parts.length>0?ke=P.parts.map(ye=>{if(ye.text){let Me=ye.text;return m||(Me=Me.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),P.role==="agent"&&(Me=be(Me),Me=Me.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),Me=Me.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*")),{text:Me}}return ye}):ke=[{text:G}],P.binaryPart&&At(Re)&&j.slice(ie+1).filter(Me=>Me.role==="user"&&!Me.text?.startsWith("[TOOL RESULT]")).length<=2&&ke.push(P.binaryPart),{role:P.role==="user"||P.role==="system"?"user":"model",parts:ke}});for(let P=0;P<ue.length;P++){let ie=ue[P],j=ie.parts?.[0]?.text||"";if(ie.role==="model"&&/\[tool:/i.test(j)){let G=-1;for(let ke=P+1;ke<ue.length;ke++){let ye=ue[ke],Me=ye.parts?.[0]?.text||"";if(ye.role==="user"&&Me.startsWith("[TOOL RESULT]")){G=ke;break}}if(G!==-1&&G!==P+1){let[ke]=ue.splice(G,1);ue.splice(P+1,0,ke)}}}for(let P=ue.length-2;P>=0;P--){let ie=ue[P],j=ue[P+1];ie.role==="user"&&j.role==="user"&&(j.parts?.[0]?.text||"").trim().startsWith("[SYSTEM")&&ue.splice(P,1)}let ot=[];for(let P=0;P<ue.length;P++){let ie=ue[P];if(ot.length===0)ot.push(ie);else{let j=ot[ot.length-1];j.role===ie.role?(j.parts[0].text+=`
|
|
646
|
+
|
|
647
|
+
`+(ie.parts?.[0]?.text||""),ie.parts?.length>1&&j.parts.push(...ie.parts.slice(1))):ot.push(ie)}}ue.length=0,ue.push(...ot),Re=e;let Ht=`${d}|${u}|${i}|${a}|${Re}|${JSON.stringify(r)}|${!!c?.dynamicDirAwareness}|${!!c?.subAgents}`,Jt=ks.key===Ht&&ks.value;if((process.env.I_HAVE_TOO_MUCH_MONEY==="true"||process.env.I_HAVE_TOO_MUCH_MONEY===!0)&&(Jt=!1),Jt)et=ks.value;else{let P=u==="Mistral"?!!vs(Re):!(Re||"gemma").toLowerCase().startsWith("gemma");et=Di(r,((Re||"gemma").toLowerCase().startsWith("gemma"),a),i,c,m,C,u,u==="Google"?!0:y,P,d),c?.dynamicDirAwareness||(et+=`
|
|
648
|
+
${xi.replace(`
|
|
649
|
+
**Directory Structure**`,`
|
|
650
|
+
**Directory Structure**`)}`),ks.key=Ht,ks.value=et}let gt=ue[ue.length-1];if(qo()&q>0){await new Promise(j=>setTimeout(j,2500)),yield{type:"status",content:"Verifying"};let P=await xs(),ie=P?P.diagnostics:null;ie&>&>.role==="user"&>.parts?.[0]?.text&&(gt.parts[0].text+=`
|
|
651
|
+
${ie} [/ERROR]`),yield{type:"status",content:"Working"}}if(u==="Mistral"||u==="Google"&&e?.toLowerCase().startsWith("gemma")){let ie=a!=="Fast"&&(u==="Mistral"||a!=="xHigh")?". **strictly maintain thinking policy. do not start a response without <think>...</think>**":"",j=`
|
|
652
|
+
[system] Tool result received. Analyze output and proceed with your turn [/system]`;gt&>.role==="user"&>.parts?.[0]?.text?.startsWith("[TOOL RESULT]")&&(gt.parts[0].text+=j)}if(c?.advanceRollback&>&>.role==="user"&>.parts?.[0]?.text?.startsWith("[TOOL RESULT]"))try{let P=await Xn.getLatestFileChanges(d);if(P&&(P.newFiles.length>0||P.modifiedFiles.length>0||P.deletedFiles.length>0)){let ie=`
|
|
653
|
+
[system] File Changes:
|
|
654
|
+
`;for(let G of P.newFiles)ie+=`* ${G} (created)
|
|
655
|
+
`;for(let G of P.modifiedFiles)ie+=`* ${G} (modified)
|
|
656
|
+
`;for(let G of P.deletedFiles)ie+=`* ${G} (deleted)
|
|
657
|
+
`;ie+="[/system]",gt.parts[0].text+=ie;let j=-1;for(let G=b.length-1;G>=0;G--)if(b[G].role==="user"&&b[G].text?.startsWith("[TOOL RESULT]")){j=G;break}j!==-1&&(b[j].text+=ie)}}catch{}let ln=Math.floor(Hs*(i==="Flux"?.98:.8)),Ot=q+1;Ot>=ln&>&>.parts?.[0]&&(gt.parts[0].text+=`
|
|
658
|
+
[system] WARNING, Turn Limit Impending: Step ${Ot}/${Hs}. Wrap up quickly/prompt user to continue. [/system]`);let Lt=new Promise((P,ie)=>{E.signal.aborted&&ie(new DOMException("The user aborted a request.","AbortError")),E.signal.addEventListener("abort",()=>{ie(new DOMException("The user aborted a request.","AbortError"))})});Lt.catch(()=>{});let Dt=ue;if(u==="Ollama")$e=fi(t.apiKey,Re,Dt,et,a,i,y,E.signal,1,c?.ollamaEndpoint||"Cloud");else if(u==="OpenRouter")$e=Xo(t.apiKey,Re,Dt,et,a,i,y,E.signal,1,d);else if(u==="DeepSeek")$e=Ko(t.apiKey,Re,Dt,et,a,i,y,E.signal,1);else if(u==="Mistral")$e=Yo(t.apiKey,Re,Dt,et,a,i,y,E.signal,1,d);else if(u==="NVIDIA"){let P=Vo(t.apiKey,Re,Dt,et,a,i,y,E.signal,1);$e=va(P,Re)}else if(u==="CrofAI")$e=Jo(t.apiKey,Re,Dt,et,a,i,y,E.signal,1);else if(u==="InferX")$e=Qo(t.apiKey,Re,Dt,et,a,i,y,E.signal,1);else if(u==="SenseNova")$e=Zo(t.apiKey,Re,Dt,et,a,i,y,E.signal,1);else if(u==="AIHubMix")$e=er(t.apiKey,Re,Dt,et,a,i,y,E.signal,1);else{let ie=gi(t?.apiKey).models.generateContentStream({model:Re||"gemini-3-flash-preview",contents:Dt,config:{systemInstruction:et,mediaResolution:"MEDIA_RESOLUTION_HIGH",safetySettings:[{category:Qn.HARM_CATEGORY_HARASSMENT,threshold:Jn.BLOCK_NONE},{category:Qn.HARM_CATEGORY_HATE_SPEECH,threshold:Jn.BLOCK_NONE},{category:Qn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Jn.BLOCK_NONE},{category:Qn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Jn.BLOCK_NONE}],temperature:1.05,thinkingConfig:(()=>{let j=(Re||"").toLowerCase(),G=j.includes("gemma-4")||j.startsWith("gemma"),ke=j.includes("gemini-3");if(G||ke)return G?a.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:ut.MINIMAL}:{includeThoughts:!0,thinkingLevel:ut.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:j.includes("pro")?ut.LOW:ut.MINIMAL,Low:ut.LOW,Medium:ut.MEDIUM,Standard:ut.MEDIUM,High:ut.HIGH,xHigh:ut.HIGH}[a]||ut.MEDIUM};{let ye={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[a]||2048;return ye===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:ye}}})()}},{signal:E.signal});$e=await Promise.race([ie,Lt])}he="",Ut=null,an=null,Q=[],qe=0,yield{type:"model_update",content:null},Ye="",jt=st.length>0;let Tn="",ar=Date.now(),is=async function*(){if(u==="Google"&&Tn){let P=qs(Tn);for(let ie of P)yield ie;Tn="",ar=Date.now()}},_i=!0,as="",Ts=!1,Gt=null,Ya={tool:{startPrefix:"[tool",fullPrefix:"[tool:functions.",endTag:"]"},agent:{startPrefix:"[agent",fullPrefix:"[agent:generalist.",endTag:"]"},end:{startPrefix:"[[END]]",fullPrefix:"[[END]]",endTag:"[[END]]"},kimi_section:{startPrefix:"<|tool_calls_section_begin|>",fullPrefix:"<|tool_calls_section_begin|>",endTag:"<|tool_calls_section_end|>"},kimi_call:{startPrefix:"<|tool_call_begin|>",fullPrefix:"<|tool_call_begin|>",endTag:"<|tool_call_end|>"}},qs=P=>{let ie=[],j=P;for(;j.length>0;)if(Ts){let G=as+j,ke=Ya[Gt];if(ke){let tt=!1;if(G.length<ke.startPrefix.length?ke.startPrefix.startsWith(G)||(tt=!0):G.startsWith(ke.startPrefix)?G.length>=ke.fullPrefix.length&&!G.startsWith(ke.fullPrefix)&&(tt=!0):tt=!0,tt){ie.push({type:"text",content:G}),as="",Ts=!1,Gt=null,j="";break}}let ye=-1,Me=ke?ke.endTag:"]";if(Gt==="tool"||Gt==="agent"){let tt=0,H=null,ne=0,Ne=!1;for(let M=0;M<G.length;M++){let Be=G[M];if(H){if(Be===H){let Ie=0;for(let Z=M-1;Z>=0&&G[Z]==="\\";Z--)Ie++;Ie%2===0&&(H=null)}}else if(Be==='"'||Be==="'"||Be==="`")H=Be;else if(Be==="(")tt++,Ne=!0;else if(Be===")")tt--;else if(Be==="[")ne++;else if(Be==="]"){if(Ne&&tt===0&&ne===1){ye=M;break}ne--}}}else ye=G.indexOf(Me);if(ye!==-1){let tt=Me.length;if(!Gt?.startsWith("kimi")){let H=G.substring(0,ye+tt);ie.push({type:"text",content:H})}as="",Ts=!1,Gt=null,j=G.substring(ye+tt)}else{let tt=Gt?.startsWith("kimi")?8192:512;G.length>tt?(ie.push({type:"text",content:G}),as="",Ts=!1,Gt=null):as=G,j="";break}}else{let G=j.indexOf("[tool"),ke=j.indexOf("[agent"),ye=j.indexOf("[[END]]"),Me=j.indexOf("<|tool_calls_section_begin|>"),tt=j.indexOf("<|tool_call_begin|>"),H=[{type:"tool",idx:G,start:"[tool",end:"]"},{type:"agent",idx:ke,start:"[agent",end:"]"},{type:"end",idx:ye,start:"[[END]]",end:"[[END]]"},{type:"kimi_section",idx:Me,start:"<|tool_calls_section_begin|>",end:"<|tool_calls_section_end|>"},{type:"kimi_call",idx:tt,start:"<|tool_call_begin|>",end:"<|tool_call_end|>"}].filter(ne=>ne.idx!==-1).sort((ne,Ne)=>ne.idx-Ne.idx);if(H.length>0){let ne=H[0];ne.idx>0&&ie.push({type:"text",content:j.substring(0,ne.idx)}),Ts=!0,Gt=ne.type,as="",j=j.substring(ne.idx)}else{let ne=["[tool","[agent","[[END]]","<|tool_calls_section_begin|>","<|tool_call_begin|>"],Ne=-1;for(let M of ne){for(let Be=M.length-1;Be>0;Be--)if(j.endsWith(M.substring(0,Be))){Ne=j.length-Be;let Ie=ne.indexOf(M);Ie===0?Gt="tool":Ie===1?Gt="agent":Ie===2?Gt="end":Ie===3?Gt="kimi_section":Gt="kimi_call";break}if(Ne!==-1)break}if(Ne!==-1)Ne>0&&ie.push({type:"text",content:j.substring(0,Ne)}),Ts=!0,as=j.substring(Ne),j="";else{ie.push({type:"text",content:j});break}}}return ie},Va=$e[Symbol.asyncIterator]();for(;;){let{value:P,done:ie}=await Promise.race([Va.next(),Lt]);if(ie)break;if(P&&P.type==="status"){yield P;continue}let j="",G=P.candidates?.[0]?.content?.parts;if(G&&G.length>0)for(let ye of G){let Me=typeof ye.text=="string"?ye.text:ye.text?parseChunkText(ye.text):"";ye.thought?Me&&(fe||(j+="<think>",fe=!0),j+=Me):Me&&(fe&&(j+="</think>",fe=!1),j+=Me)}else P.text&&fe&&(j+="</think>",fe=!1);j=Rc(j);let ke=j?j.trim().split(/\s+/).filter(Boolean).length:0;if(t&&typeof t.onTokenChunk=="function"&&t.onTokenChunk(j,ke),_i&&(yield{type:"status",content:"Thinking"},_i=!1),Mt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
|
|
659
|
+
|
|
660
|
+
\x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(j){if(jt){if(Ye+=j,Ye.length>=64){let H=0,ne=Math.min(st.length,Ye.length);for(let M=ne;M>=10;M--)if(st.endsWith(Ye.substring(0,M))){H=M;break}let Ne=Ye.substring(H);if(Ne){let Be=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(st)?Ne.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):Ne.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(Be)if(he+=Be,u==="Google")Tn+=Be;else{yield*is();let Ie=qs(Be);for(let Z of Ie)yield Z}}jt=!1,Ye=""}continue}else if(he+=j,u==="Google")Tn+=j;else{yield*is();let H=qs(j);for(let ne of H)yield ne}let ye=Ic(he);if(ye.inside){ns=!0,an||(an=Date.now());let ne={Ask:"ask",AskUser:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Cancel:"cancel",Await:"await",Answer:"answer",Steer:"steer",steer:"steer"}[ye.toolName]||ye.toolName,Ne=ye.args||"",M=null;if(["write_file","update_file","view_file","read_folder","write_pdf","write_docx","search_keyword","generate_image","file_map","invoke","invoke_sync","get_progress","await","answer"].includes(ne)){let Ie=O(Ne),Z=Ie.path||Ie.targetFile||Ie.TargetFile||Ie.directory,Rn=Ie.keyword,ls=Ie.title||Ie.task,Hn=Ie.id||Ie.taskId,Ae=Ie.timeout||Ie.time;if(Rn!=null)M=String(Rn).replace(bs,"");else if(Z)M=te.basename(String(Z).replace(bs,"").replace(Ia,"/"));else if(ls&&(ne==="invoke"||ne==="invoke_sync"))M=String(ls).replace(bs,"").substring(0,30);else if(Hn&&ne==="get_progress")M=String(Hn).replace(bs,"");else if(Ae&&ne==="await"){let qt=parseFloat(String(Ae).replace(bs,""));isNaN(qt)?M=String(Ae).replace(bs,""):(qt<5&&(qt=5),qt>120&&(qt=120),M=(An=>{if(An>=60){let cr=Math.floor(An/60),Rs=An%60;return`${cr}m${Rs>0?` ${Rs}s`:""}`}return`${An}s`})(qt))}else{let qt=Ne.match(kc);if(qt){let Qt=qt[1].replace(bs,"");ne==="invoke"||ne==="invoke_sync"||ne==="get_progress"?M=Qt.substring(0,30):M=ne==="search_keyword"||ne==="file_map"?Qt:te.basename(Qt.replace(Ia,"/"))}}}let Be=`${pi[ne]||ne}${M?` ${M}`:""}`;if((ne!==Ut||M!==Je)&&(Ut=ne,Je=M,yield{type:"status",content:`${Be}`},process.stdout.isTTY)){let Z={WebSearch:"Searching",web_search:"Searching",WebScrape:"Reading",web_scrape:"Reading",ReadFile:"Reading",read_file:"Reading",ReadFolder:"Reading",read_folder:"Reading",WriteFile:"Writing",write_file:"Writing",UpdateFile:"Editing",update_file:"Editing",WritePdf:"Creating",write_pdf:"Creating",WriteDocx:"Creating",write_docx:"Creating",SearchKeyword:"Searching",search_keyword:"Searching",CodeSearch:"Searching",code_search:"Searching",Run:"Executing",Ask:"User Input Required",AskUser:"User Input Required",Memory:"Updating Memory",GenerateImage:"Generating",InvokeSync:"Sub-Agent Working",invoke_sync:"Sub-Agent Working",Invoke:"Working",invoke:"Working",GetProgress:"Checking Progress",get_progress:"Checking Progress",Cancel:"Stopping Generalist",cancel:"Stopping Generalist",Await:"Waiting",await:"Waiting",EmergencyRollback:"Rolling the Ball",Answer:"Answering Sub-Agent",answer:"Answering Sub-Agent",Steer:"Steering Sub-Agent",steer:"Steering Sub-Agent",Click:"Clicking",click:"Clicking",Drag:"Dragging",drag:"Dragging",Scroll:"Scrolling",scroll:"Scrolling",KeyboardTyping:"Typing",keyboard_typing:"Typing",KeyPress:"Pressing Key",key_press:"Pressing Key",RecaptureScreen:"Recapturing Screen",recapture_screen:"Recapturing Screen"}[ne]||"Working";process.stdout.write(`\x1B]0;${Z}...\x07`)}}if(he.length-bo>150){bo=he.length;let H=Wa(he,!1),ne=ui(H),Ne=ne?(ne.innerContent||"").trim():"",M=Ne.split(/[.!?]\s+/),Be=new Set(M),Ie=M.length>10?(M.length-Be.size)/M.length:0,Z=Ne.split(/\s+/).filter(Oe=>Oe.length>0).length,Rn=.6,ls=.8,Hn=!1;if((u.toLowerCase().includes("google")||u.toLowerCase().includes("mistral"))&&((Re||"").toLowerCase().startsWith("gemma")||(Re||"").toLowerCase().includes("stral"))){let v={low:256,medium:1024,high:8192,max:16384,xhigh:16384}[a?.toLowerCase()]||2500;Hn=Z>v}if(Ie>Rn||Hn){yield{type:"status",content:`${Ie>Rn?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},Wt=!0,await new Promise(v=>setTimeout(v,3e3));break}let Qt=Fa(he).trim().split(/[.!?]\s+/),An=new Set(Qt);if((Qt.length>10?(Qt.length-An.size)/Qt.length:0)>ls){yield{type:"status",content:"Response Loop Detected. Re-centering..."},Wt=!1,Mn=!0,await new Promise(Oe=>setTimeout(Oe,3e3));break}let Rs=H.replace(hc,"").replace(mc,"").replace(gc,"").replace(yc,""),zt=Rs.toLowerCase().split(/\s+/).map(Oe=>Oe.replace(wc,"")).filter(Oe=>Oe.length>0),vn=!1;if(zt.length>=10)for(let Oe=1;Oe<=15;Oe++){let v=Math.max(3,Math.ceil(10/Oe));if(zt.length<Oe*v)continue;let K=zt.slice(zt.length-Oe),ce=K.join(" ");if(Oe>1&&ce===K.slice(0,Math.floor(Oe/2)).join(" ").repeat(2).trim())continue;let we=!0;for(let Se=1;Se<v;Se++)if(zt.slice(zt.length-Oe*(Se+1),zt.length-Oe*Se).join(" ")!==ce){we=!1;break}if(we){vn=!0;break}}if(!vn){let Oe=Rs.toLowerCase().replace(xc,"");if(Oe.length>=20)for(let v=1;v<=10;v++){let K=Math.max(5,Math.ceil(16/v));if(Oe.length<v*K)continue;let ce=Oe.substring(Oe.length-v),we=!0;for(let Se=1;Se<K;Se++)if(Oe.substring(Oe.length-v*(Se+1),Oe.length-v*Se)!==ce){we=!1;break}if(we){vn=!0;break}}}if(vn){yield{type:"status",content:"Stuttering Detected. Re-centering..."},Wt=!1,Sn=!0,await new Promise(Oe=>setTimeout(Oe,3e3));break}}let Me=on(he),tt=sr(Me);for(;tt.length>qe;){yield*is();let H=tt[qe],ne=Date.now(),M={Ask:"ask",AskUser:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Await:"await",await:"await",AwaitSubagent:"await",awaitSubagent:"await",Answer:"answer",answer:"answer",AnswerSubagent:"answer",answerSubagent:"answer",Steer:"steer",steer:"steer",SteerSubagent:"steer",steerSubagent:"steer",Cancel:"cancel",cancel:"cancel",Click:"click",click:"click",Drag:"drag",drag:"drag",Scroll:"scroll",scroll:"scroll",KeyboardTyping:"keyboard_typing",keyboard_typing:"keyboard_typing",KeyPress:"key_press",key_press:"key_press",RecaptureScreen:"recapture_screen",recapture_screen:"recapture_screen",EmergencyRollback:"EmergencyRollback"}[H.toolName]||H.toolName,Be=pi[M]||H.toolName,Ie=Ss(M,H.args);yield{type:"status",content:`${Be}${Ie?` ${Ie}`:""}`};let Z="";if(M==="click"){let v=O(H.args);Z=`\u2714 Clicked: ${v.intendedClickText?`${v.intendedClickText}`:""}`}else if(M==="drag"){let v=O(H.args);Z=`\u2714 Dragged: Cell ${v.fromGridId||""} \u2192 Cell ${v.toGridId||""}`}else if(M==="scroll"){let v=O(H.args);Z=`\u2714 Scrolled: ${v.direction||"down"} (${v.amount||1})`}else if(M==="keyboard_typing"){let v=O(H.args);Z=`\u2714 Typed: ${v.text?`"${v.text.length>20?v.text.substring(0,20)+"...":v.text}"`:""}`}else if(M==="key_press")Z=`\u2714 Pressed Key: ${O(H.args).key||""}`;else if(M==="recapture_screen")Z="\u2714 Recaptured Screen";else if(M==="web_search"){let{query:v,limit:K=10,aiMode:ce=!1}=O(H.args);Z=`${v?"\u2714":"\u2718"} ${ce?"AI Search":"Searched"}: ${v?`${v}`:"No Search Query"}${ce===!1&&v?` \u2192 ${K}`:""}`}else if(M==="web_scrape"){let v=O(H.args).url||null;Z=`${v?"\u2714":"\u2718"} Visited: ${v||"No Source"}`}else if(M==="view_file"){let{path:v,StartLine:K,EndLine:ce,start_line:we,end_line:Se,startLine:ze,endLine:Le}=O(H.args),Ee=K||we||ze,se=ce||Se||Le,pe=parseInt(Ee)||1,de=parseInt(se)||(Ee?pe+800:800),Ue="...",nt=de;try{let Ce=te.resolve(process.cwd(),v);if(Pe.existsSync(Ce)){let me=Pe.readFileSync(Ce,"utf8").split(`
|
|
661
|
+
`).length;Ue=me,!Ee&&!se&&me>800?nt=Math.min(50,me):nt=Math.min(de,me)}}catch{}let xe=(v||"").toLowerCase(),Kt=xe.endsWith(".pdf"),Qe=xe.endsWith(".docx")||xe.endsWith(".doc")||xe.endsWith(".ppt")||xe.endsWith(".pptx")||xe.endsWith(".xls")||xe.endsWith(".xlsx"),yt=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(xe);Kt||Qe?Z=`${v.length>0?"\u2714":"\u2718"} ${v?`Analyzed: ${te.basename(v)}`:"Analyzed: File Not Found"}`:yt?Z=`${v.length>0?"\u2714":"\u2718"} ${v?`Processed: ${te.basename(v)}`:"Processed: File Not Found"}`:Z=`${Ue!=="..."?"\u2714":"\u2718"} Read: ${v?`${te.basename(v)} \u2192 ${Ue!=="..."?`Lines ${pe} - ${nt} of ${Ue}`:"File Not Found"}`:"File Not Found"}`}else if(M==="list_files"||M==="read_folder"){let v=M==="list_files"?"List":"Browsed",K=O(H.args).path||null,ce=O(H.args).recurse||1;Z=`${K?"\u2714":"\u2718"} ${v}: ${K?`${K==="."?`./${ce>1?"*":""}`:`${K.replaceAll("\\","/")}${ce>1?`${K.endsWith("/")?"*":"/*"}`:`${K.endsWith("/")?"":"/"}`}`}`:"No Folder Selected"}`}else if(M==="write_file"||M==="update_file"){let v=M==="write_file"?"Created":"Edited",K=O(H.args).path||null;Z=`${K?"\u2714":"\u2718"} ${v}: ${K.replaceAll("\\","/")||"No File Changes"}`}else if(M==="write_pdf"){let v=O(H.args).path||null;Z=`${v?"\u2714":"\u2718"} Generated: ${v.replaceAll("\\","/")||"No PDF Generated"}`}else if(M==="write_docx"){let v=O(H.args).path||null;Z=`${v?"\u2714":"\u2718"} Generated: ${v.replaceAll("\\","/")||"No Docx Generated"}`}else if(M==="file_map"){let v=O(H.args).path;Z=`${v?"\u2714":"\u2718"} Indexed: ${v.replaceAll("\\","/")?""+v:"File Not Found"}`}else if(M.toLowerCase()==="search_keyword"||M.toLowerCase()==="todo")Z="";else if(M.toLowerCase()==="generate_image"){let{path:v,outputPath:K,output:ce}=O(H.args);Z=`\u2714 Generated: ${v||K||ce||"generated_image.png"}`}else if(M==="invoke_sync"||M==="InvokeSync"){let v=Ss(M,H.args);Z=`\u2714 Called Generalist${v?`: ${v}`:""}`}else if(M==="Invoke"||M==="InvokeAsync"||M==="invoke"){let v=Ss(M,H.args);Z=`\u2714 Started Generalist${v?`: ${v}`:""}`}else if(M==="get_progress"||M==="GetProgress"){let v=Ss(M,H.args);Z=`\u2714 Checked${v?`: ${v}`:""}`}else if(M==="cancel"){let v=Ss(M,H.args);Z=`\u{1F6C7} Cancelled${v?`: ${v}`:""}`}else if(M==="steer"||M==="Steer"){let v=Ss(M,H.args);Z=`\u2714 Steered${v?`: ${v}`:""}`}else if(M==="EmergencyRollback"){let{method:v}=O(H.args);Z=v==="forceRevert"?"":"\u2714 Rollback Point Checked"}else if(M==="await"||M==="Await"){let{time:v,timeout:K}=O(H.args),ce=parseFloat(K||v)||0;ce||(ce=120);let we=Le=>{if(Le>=60){let Ee=Math.floor(Le/60),se=Le%60;return`${Ee}m${se>0?` ${se}s`:""}`}return`${Le}s`},Se=["Aligning Moon Phase","Contemplating Existence","Staring At Void","Delaying Professionally","Negotiating With Electrons","Touching Grass (virtually)","Panicking Softly","Rethinking Career Choices","Loading Cat Videos","Summoning Braincell #2","Pretending To Be Busy","Waiting For Motivation DLC","Rotating Internal Screaming","Downloading More RAM","Feeding The Hamsters","Gaslighting Scheduler","Performing Dramatic Pause","Buffering Social Energy","Calculating Regret","Reading Terms And Conditions","Becoming Sentient Briefly","Contacting Ancestors"];Z=`\u2714 ${Se[Math.floor(Math.random()*Se.length)]} \u2192 ${we(ce)}`}else M==="Answer"||M==="answer"?Z="\u2714 Resolved Sub-Agent Query":M==="exec_command"||M==="ask"?Z="":Z=`Executed: ${H.toolName}`;if(yield*is(),M==="exec_command"){let{command:v}=O(H.args);if(v&&t.systemSettings&&t.systemSettings.allowExternalAccess===!1){let K=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],ce=te.resolve(process.cwd()).substring(0,3).toLowerCase(),we=se=>{let pe=[],de="",Ue=null;for(let nt=0;nt<se.length;nt++){let xe=se[nt];Ue?(xe===Ue&&(Ue=null),de+=xe):xe==='"'||xe==="'"?(Ue=xe,de+=xe):xe==="&"&&se[nt+1]==="&"||xe==="|"&&se[nt+1]==="|"?(de.trim()&&(pe.push(de.trim()),de=""),nt++):xe===";"||xe==="|"||xe==="&"?de.trim()&&(pe.push(de.trim()),de=""):de+=xe}return de.trim()&&pe.push(de.trim()),pe},Se=se=>{let pe=[],de="",Ue=null;for(let nt=0;nt<se.length;nt++){let xe=se[nt];Ue?(xe===Ue&&(Ue=null),de+=xe):xe==='"'||xe==="'"?(Ue=xe,de+=xe):/\s/.test(xe)?de&&(pe.push(de),de=""):de+=xe}return de&&pe.push(de),pe},ze=se=>{let pe=se.replace(/^['"]|['"]$/g,"").trim();return!pe||process.platform==="win32"&&/^\/[a-zA-Z0-9?]+$/.test(pe)?!1:K.some(de=>{if(de.source==="[a-zA-Z]:[\\\\\\/]"){let Ue=pe.match(/[a-zA-Z]:[\\\/]/i);return Ue&&Ue[0].toLowerCase()!==ce}return de.test(pe)})};if(we(v).some(se=>{let pe=Se(se);if(pe.length===0)return!1;let de=pe[0].replace(/^['"]|['"]$/g,"").toLowerCase();if(["echo","printf","write-output"].includes(de)){let nt=!1;return pe.some(xe=>{let Kt=xe.replace(/^['"]|['"]$/g,"");if(Kt===">"||Kt===">>"||Kt==="<")return nt=!0,!1;if(Kt.startsWith(">")||Kt.startsWith("<")){let Qe=Kt.replace(/^[><]+/,"");return ze(Qe)}return nt?(nt=!1,ze(xe)):!1})}return pe.some(nt=>ze(nt))})){let se='Access Denied. Prohibited from accessing external directories while "External Workspace Access" is disabled.';t.onExecStart&&t.onExecStart(v||"No Command"),yield{type:"exec_start"},await new Promise(pe=>setTimeout(pe,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${se}`),await new Promise(pe=>setTimeout(pe,50)),t.onExecEnd&&t.onExecEnd(),Q.push({role:"user",text:`[TOOL RESULT]: ERROR: ${se}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${se}`},qe++;continue}}t.onExecStart&&t.onExecStart(v||"No Command"),yield{type:"exec_start"}}let Rn=O(H.args),ls=Rn.path||Rn.targetPath||null;if(ls){let v=t.systemSettings&&t.systemSettings.allowExternalAccess===!1,K=te.resolve(ls),ce=te.resolve(process.cwd());if(v&&!K.startsWith(ce)){let we="Access Denied. You are not allowed to access files outside the current workspace.";if(M==="write_file"||M==="update_file"){let ze=`\u2718 ${M==="write_file"?"Write Canceled":"Edit Canceled"}: ${Rn.path||"..."}`,Le=115;process.stdout.isTTY&&(Le=process.stdout.columns-5||120);let Ee=Math.min(ze.length+4,Le),se=`${ze.padEnd(Ee-2).substring(0,Ee-2)}`;yield{type:"visual_feedback",content:sn(`${je?`
|
|
662
|
+
`:""}${se}
|
|
663
|
+
`)},je=!1}Q.push({role:"user",text:`[TOOL RESULT]: ERROR: ${we}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${we}`},qe++;continue}}if(t.onToolApproval&&(M==="write_file"||M==="update_file"||M==="exec_command")){let K=t.systemSettings||{},ce=K.autoExec,we=null,Se=!1,ze=!1,Le=!1;if(M==="exec_command"){let{command:Qe}=O(H.args),yt=(Qe||"").trim(),Ce=(cn,Zt)=>{if(!Zt)return!1;let mn=Zt.split(",").map(en=>en.trim().toLowerCase()).filter(Boolean),ct=cn.toLowerCase();return mn.some(en=>ct.startsWith(en))},rt=Ce(yt,K.alwaysAskCommands),me=Ce(yt,K.autoApproveCommands);if(ze=Ce(yt,K.autoDisallowCommands),rt?Se=!0:(me||K.autoApproveGit&&/^git\s+commit\b/i.test(yt))&&(we="allow"),!Se&&!we){if(K.networkAccess===!1){let Zt=yt.trim().replace(/\s+/g," ").replace(/^['"]+|['"]+$/g,"").toLowerCase().split(" "),ct=Zt[0].split("/").pop().split("\\").pop().replace(/\.exe$/,""),en=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"]),dt=!1;en.has(ct)&&(dt=!0);let it=En=>Zt.slice(1).some(_n=>En.includes(_n)),ft=En=>{let _n=Zt.findIndex(In=>En.includes(In)),Es=Zt.findIndex(In=>["run","exec","test"].includes(In));return _n!==-1&&!(Es!==-1&&Es<_n)};ct==="git"&&it(["clone","pull","push","fetch"])&&(dt=!0),ct==="go"&&it(["get","install"])&&(dt=!0),ct==="npm"&&ft(["install","i","update","add"])&&(dt=!0),ct==="yarn"&&ft(["add","install","upgrade"])&&(dt=!0),ct==="pnpm"&&ft(["add","install","update"])&&(dt=!0),ct==="bun"&&ft(["add","install","update"])&&(dt=!0),ct==="deno"&&it(["install","add"])&&(dt=!0),ct==="pip"&&it(["install","download"])&&(dt=!0),ct==="pip3"&&it(["install","download"])&&(dt=!0),ct==="cargo"&&it(["install","add"])&&(dt=!0),["bash","sh","zsh","fish"].includes(ct)&&it(["-c"])&&(dt=!0),ct==="cmd"&&it(["/c"])&&(dt=!0),dt&&(we="deny",Le=!0)}!we&&ze&&(we="deny")}!Se&&!we&&ce&&(we="allow")}else ce&&(we="allow");let Ee=we,se="";we==="deny"&&(Le?se="network":ze?se="settings":se="prohibited");let pe=!1,de="",Ue=[],nt=0,xe=!1,Kt="";if(!Ee){if(M==="write_file"||M==="update_file")try{let Ce=O(H.args),{path:rt}=Ce;if(rt){let me=te.resolve(process.cwd(),rt),cn=it=>it?it.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,ft=>ft.toUpperCase()):"",Zt=cn(me),mn="",ct=!1,en=await xs(),dt=cn(en?.file_focused);if(en&&dt===Zt&&en.full_content?(mn=en.full_content,ct=!0):Pe.existsSync(me)&&(mn=Pe.readFileSync(me,"utf8"),ct=!0),de=mn,await ht.recordFileChange(me,mn),ct){let it=mn;if(M==="write_file"){let ft=Ce.content||Ce.newContent||"";it=ft.endsWith(`
|
|
664
|
+
`)?ft:ft+`
|
|
665
|
+
`,Kt=it}else{let{patchPairs:ft,allowMultiple:En,error:_n}=Lo(Ce);if(_n){let Ct=`[TOOL RESULT]: ERROR: ${_n}`;Q.push({role:"user",text:Ct}),await vt("toolFailure"),t.onToolResult&&t.onToolResult("failure",M),yield{type:"tool_result",content:Ct,toolName:M},qe++;continue}let Es=Ce.allowMultiple!==void 0?Ce.allowMultiple===!0||String(Ce.allowMultiple).toLowerCase()==="true":En;nt=ft.length;let In=Do(mn,ft,{allowMultiple:Es});it=In.content,Kt=it,Ue=In.results;let ko=Ue.filter(Ct=>Ct.success),_t=Ue.filter(Ct=>!Ct.success);if(ko.length===0){let Ct=`[TOOL RESULT]: ERROR: Failed to apply patches to [${te.basename(me)}].
|
|
666
|
+
${_t.map(Ys=>` \u2022 ${Ys.error}`).join(`
|
|
667
|
+
`)}`,_s=`\u2714 Edited: ${te.basename(me.replaceAll("\\","/"))}`,Ks=115;process.stdout.isTTY&&(Ks=process.stdout.columns-5||120);let Cs=Math.min(_s.length+4,Ks),So=`${_s.padEnd(Cs-2).substring(0,Cs-2)}`;yield{type:"visual_feedback",content:sn(`${je?`
|
|
668
|
+
`:""}${So}`)},je=!1,Q.push({role:"user",text:Ct}),await vt("toolFailure"),t.onToolResult&&t.onToolResult("failure",M),yield{type:"tool_result",content:Ct,toolName:M},qe++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${te.basename(me)}`},ai(me,mn,it),pe=!0,await new Promise(ft=>setTimeout(ft,50))}else if(M==="write_file"){let it=Ce.content||Ce.newContent||"",ft=it.endsWith(`
|
|
669
|
+
`)?it:it+`
|
|
670
|
+
`;Kt=ft,Pe.existsSync(me)||(xe=!0,Pe.mkdirSync(te.dirname(me),{recursive:!0}),Pe.writeFileSync(me,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${te.basename(me)}`},ai(me,"",ft),pe=!0,await new Promise(En=>setTimeout(En,50))}}}catch(Ce){console.error("Simulation/Diff Error:",Ce)}let Qe=null;ii(Ce=>{Qe=Ce});let yt=t.onToolApproval;if(Ee=await new Promise(async Ce=>{let rt=setInterval(()=>{Qe&&(tr.onIDEApproval&&tr.onIDEApproval(Qe),clearInterval(rt),Ce(Qe))},100);try{let me=await yt(M,H.args);clearInterval(rt),Ce(me)}catch{clearInterval(rt),Ce("deny")}}),ii(null),M==="write_file"||M==="update_file"){let{path:Ce}=O(H.args);if(Ce){let rt=te.resolve(process.cwd(),Ce);if(Ma(rt,Ee),Ee==="deny"&&xe&&Pe.existsSync(rt))try{Pe.unlinkSync(rt)}catch{}}}Ee==="deny"&&(se="user")}if(Ee==="allow"&&pe&&qo()){let{path:Qe}=O(H.args),yt=te.resolve(process.cwd(),Qe),Ce=_t=>_t?te.resolve(_t).replace(/\\/g,"/").toLowerCase():"",rt=await xs(),me="";if(rt&&rt.file_focused&&Ce(rt.file_focused)===Ce(yt)&&rt.full_content&&(me=rt.full_content),!me&&Pe.existsSync(yt)){let _t=Pe.readFileSync(yt,"utf8");_t&&(me=_t)}!me&&Kt&&(me=Kt),(me||xe)&&Pe.writeFileSync(yt,me,"utf8");let cn=me.split(/\r?\n/),Zt=cn.length,mn=Buffer.byteLength(me,"utf8"),ct="";de&&(ct=`Old File contents:
|
|
671
|
+
${de.split(/\r?\n/).map((Ct,_s)=>`${_s+1} | ${Ct}`).join(`
|
|
672
|
+
`)}
|
|
673
|
+
|
|
674
|
+
`);let en="";if(Zt<=100)en=cn.join(`
|
|
675
|
+
`);else{let _t=cn.slice(0,50).join(`
|
|
676
|
+
`),Ct=cn.slice(-50).join(`
|
|
677
|
+
`);en=`${_t}
|
|
678
|
+
|
|
679
|
+
... [${Zt-100} lines truncated for history stability] ...
|
|
680
|
+
|
|
681
|
+
${Ct}`}let dt="";if(M==="update_file"){let _t=Po(de,me,Ue,12,t?.compressToolResults||tr?.systemSettings?.compressToolResults);dt=`SUCCESS: File [${Qe}] updated via IDE Companion (May have user edits). [${Ue.length}/${nt}] blocks applied.
|
|
682
|
+
|
|
683
|
+
${_t}`}else{let _t=me.split(/\r?\n/),Ct=_t.length,_s=Buffer.byteLength(me,"utf8"),Ks="";de&&(Ks=`Old File contents:
|
|
684
|
+
${de.split(/\r?\n/).map((Ys,nl)=>`${nl+1} | ${Ys}`).join(`
|
|
685
|
+
`)}
|
|
686
|
+
|
|
687
|
+
`);let Cs="";if(Ct<=100)Cs=_t.join(`
|
|
688
|
+
`);else{let So=_t.slice(0,50).join(`
|
|
689
|
+
`),Ys=_t.slice(-50).join(`
|
|
690
|
+
`);Cs=`${So}
|
|
691
|
+
|
|
692
|
+
... [${Ct-100} lines truncated] ...
|
|
693
|
+
|
|
694
|
+
${Ys}`}dt=`SUCCESS: File [${Qe}] saved via IDE Companion (May have user edits).
|
|
695
|
+
- Stats: [${Ct} lines, ${(_s/1024).toFixed(1)} KB]
|
|
696
|
+
${Ks}- Content Preview:
|
|
697
|
+
|
|
698
|
+
${Cs}`}let ft=`${Qe?"\u2714":"\u2718"} ${M==="write_file"?"Created":"Edited"}: ${Qe.replaceAll("\\","/")||"No File Changes"}`,En=115;process.stdout.isTTY&&(En=process.stdout.columns-5||120);let _n=Math.min(ft.length+4,En),Es=`${ft.padEnd(_n-2).substring(0,_n-2)}`;yield{type:"visual_feedback",content:sn(`${je?`
|
|
699
|
+
`:""}${Es}`)},je=!1;let In=Date.now();z=In,yield{type:"tool_time",content:In-ne};let ko=`[TOOL RESULT]: ${dt}`;Q.push({role:"user",text:ko}),pn=!0,await vt("toolSuccess"),t.onToolResult&&t.onToolResult("success",M),yield{type:"tool_result",content:dt,aiContent:ko,toolName:M},qe++;continue}if(Ee==="deny"){let Qe=`Permission Denied: Prohibited ${M==="exec_command"?"Command":"file edit"}.`;if(se==="user"?Qe="Permission Denied by User":se==="settings"?Qe="Permission Denied by User Policy":se==="network"?Qe="Permission Denied: Sandbox Network Access Disabled by User Policy.":se==="prohibited"&&M==="exec_command"&&(Qe="Permission Denied: Prohibited Command in User Policy"),M==="write_file"||M==="update_file"){let Ce=`\u2718 ${M==="write_file"?"Write Cancelled":"Edit Denied"}: ${O(H.args).path.replaceAll("\\","/")||"..."}`,rt=115;process.stdout.isTTY&&(rt=process.stdout.columns-5||120);let me=Math.min(Ce.length+4,rt),cn=`${Ce.padEnd(me-2).substring(0,me-2)}`,Zt=` ${" ".repeat(me)} `;yield{type:"visual_feedback",content:sn(`${je?`
|
|
700
|
+
`:""}${cn}
|
|
701
|
+
`)},je=!1}M==="exec_command"&&(await new Promise(yt=>setTimeout(yt,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${Qe}`),await new Promise(yt=>setTimeout(yt,50)),t.onExecEnd&&t.onExecEnd()),Q.push({role:"user",text:`[TOOL RESULT]: DENIED: ${Qe}`}),yield{type:"tool_result",content:`[TOOL RESULT]: DENIED: ${Qe}`},await vt("toolDenied"),t.onToolResult&&t.onToolResult("denied",M),qe++;continue}}if(Z){let v=115;process.stdout.isTTY&&(v=process.stdout.columns-5||120);let K=Math.min(Z.length+4,v),ce=`${Z.padEnd(K-2).substring(0,K-2)}`;yield{type:"visual_feedback",content:sn(`${je?`
|
|
702
|
+
`:""}${ce}${Z.includes("\u2714")&&(Z.includes("Created")||Z.includes("Edited"))?"":`
|
|
703
|
+
`}`)},je=!1}if(z>0){let v=Date.now()-z,K=Math.max(0,1e3-v);K>0&&await new Promise(ce=>setTimeout(ce,K))}let Hn={chatId:d,history:n,onChunk:v=>t.onExecChunk?t.onExecChunk(v):null,onAskUser:t.onAskUser,systemSettings:t.systemSettings,mode:i,isMultiModal:At(Re),onVisualFeedback:t.onVisualFeedback,onSubagentUpdate:t.onSubagentUpdate,onTokenChunk:t.onTokenChunk,modelName:Re,aiProvider:t.aiProvider,apiKey:t.apiKey,onUsage:t.onUsage};if(M==="write_file"||M==="update_file")try{let{path:v}=O(H.args);if(v){let K=te.resolve(process.cwd(),v),ce=await xs();ce&&ce.file_focused===K&&ce.full_content&&(Hn.forcedContent=ce.full_content)}}catch{}rn.push(M);let Ae=await mo(M,H.args,Hn);if((M==="write_file"||M==="update_file")&&Ae.startsWith("SUCCESS")){let{path:v}=O(H.args);if(v){let K=te.resolve(process.cwd(),v);$a(K)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let qt=Date.now();z=qt,yield{type:"tool_time",content:qt-ne},an=qt;let Qt=null;if(typeof Ae=="object"&&Ae.binaryPart&&(Qt=Ae.binaryPart,Ae=Ae.text),M==="search_keyword"){let{keyword:v,path:K}=O(H.args),ce=typeof Ae=="string"&&Ae.startsWith("[GLOB]");ce&&(Ae=Ae.slice(6).trimStart());let we=typeof Ae=="string"&&Ae.startsWith("[DIR]");we&&(Ae=Ae.slice(5).trimStart());let Se=0;if(Ae){let Ue=Ae.match(/Found (\d+) match/i);Ue&&(Se=parseInt(Ue[1]))}let ze=K?K.replace(/[\/\\]+$/,""):null,Le=ze&&ze!=="."?`"${ce?K:we?`${ze}/*`:ze}"`:"./",Ee=`${v?"\u2714":"\u2718"} Searched: "${v||""}" in ${Le.replaceAll("\\","/")} \u2192 ${Se} Match${Se===1?"":"es"}`,se=115;process.stdout.isTTY&&(se=process.stdout.columns-5||120);let pe=Math.min(Ee.length+4,se),de=`${Ee.padEnd(pe-2).substring(0,pe-2)}`;yield{type:"visual_feedback",content:sn(`${je?`
|
|
704
|
+
`:""}${de}
|
|
705
|
+
`)},je=!1}if(M==="EmergencyRollback"){let{method:v}=O(H.args);if(v==="forceRevert"){let K=0;if(Ae){let Ee=Ae.match(/Total\s*:\s*(\d+)/i);Ee&&(K=parseInt(Ee[1]))}let we=Ae&&Ae.startsWith("ERROR:")?"\u2718 Emergency Rollback Failed":`\u2714 Emergency Rollback \u2192 ${K} file${K===1?"":"s"} processed`,Se=115;process.stdout.isTTY&&(Se=process.stdout.columns-5||120);let ze=Math.min(we.length+4,Se),Le=`${we.padEnd(ze-2).substring(0,ze-2)}`;yield{type:"visual_feedback",content:sn(`${je?`
|
|
706
|
+
`:""}${Le}
|
|
707
|
+
`)},je=!1}}if(M==="todo"){let{method:v,tasks:K,markDone:ce}=O(H.args),we="",Se=[],ze=Le=>{if(!Le)return[];let Ee=Array.isArray(Le)?Le:[];if(Ee.length===0&&typeof Le=="string"){let se=Le.trim();if(se.startsWith("[")&&se.endsWith("]")){let pe=se.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);pe?Ee=pe.map(de=>de.slice(1,-1).replace(/\\(.)/g,"$1")):Ee=se.slice(1,-1).split(",").map(de=>de.trim()).filter(Boolean)}else Ee=Le.split(`
|
|
708
|
+
`)}return Ee.filter(se=>String(se).trim()).map(se=>{let pe=String(se).trim();return pe.startsWith("- [")?pe.substring(6).trim():pe})};if(v==="create"?(we="\x1B[32m\u2192\x1B[0m Created Goals",Se=ze(K).map(Le=>`\x1B[90m\u25CB\x1B[0m ${Le}`)):v==="append"?(we="\x1B[34m\u2795\x1B[0m Added New Goals",Se=ze(K).map(Le=>`\x1B[90m\u25CB\x1B[0m ${Le}`)):v==="get"&&(we=ce?"\x1B[36m\u21BB\x1B[0m Updated Goals":"\x1B[35m\u2022\x1B[0m Reviewed Goals",Se=(Ae||"").split(`
|
|
709
|
+
`).slice(1).join(`
|
|
710
|
+
`).split(`
|
|
711
|
+
`).filter(Ee=>Ee.trim().startsWith("- [")).map(Ee=>{let se=Ee.trim(),pe=se.startsWith("- [x]");return`${pe?"\x1B[32m\u2714\x1B[0m":"\x1B[90m\u25CB\x1B[0m"} ${pe?"\x1B[90m":"\x1B[37m"}${se.substring(6).trim()}\x1B[0m`})),we&&Se.length>0){let Le=[`${we}`,...Se.map(Ee=>` ${Ee}`)].join(`
|
|
712
|
+
`);yield{type:"visual_feedback",content:sn(`${je?`
|
|
713
|
+
`:""}${Le}
|
|
714
|
+
`)},je=!1}}M==="exec_command"&&t.onExecEnd&&(await new Promise(v=>setTimeout(v,800)),t.onExecEnd());let An=Ae&&Ae.startsWith("DENIED:");Ae&&!Ae.startsWith("ERROR:")&&!An?(await vt("toolSuccess"),t.onToolResult&&t.onToolResult("success",M)):An||(await vt("toolFailure"),t.onToolResult&&t.onToolResult("failure",M));let zt=(Ae||"").toString().replaceAll("[UI_CONTEXT]","");zt.includes("[[VERIFIED]]")&&(zt=zt.replace(/\[\[VERIFIED\]\][\s\S]*?\[\[\/VERIFIED\]\]/g,`[SYSTEM NOTE]: Patch Block matched & applied successfully. Large Block omitted to conserve context.
|
|
715
|
+
`));let vn;if(zt.startsWith("[[SAME]]")){let K=zt.replace(/^\[\[SAME\]\]\s*\r?\n?/,"").split(/\r?\n/),ce=K.filter(Se=>Se.startsWith("SUCCESS:")||Se.trim().startsWith("- Stats:"));vn=`[TOOL RESULT]: ${ce.length>0?ce.join(`
|
|
716
|
+
`):K.slice(0,2).join(`
|
|
717
|
+
`)}
|
|
718
|
+
[SYSTEM NOTE]: Content verified and persisted to disk. Full preview omitted to conserve context.`}else vn=`[TOOL RESULT]: ${zt}`;Q.push({role:"user",text:vn,binaryPart:Qt}),pn=!0;let Oe=`[TOOL RESULT]: ${Ae.replaceAll(`[[VERIFIED]]
|
|
719
|
+
`,"").replaceAll(`
|
|
720
|
+
[[/VERIFIED]]`,"")||""}`;(M==="view_file"||M==="web_scrape"||M==="file_map")&&(Oe=`[TOOL RESULT]: ${Z} (Context Locked for UI Clarity)`),yield{type:"tool_result",content:Oe,aiContent:vn,binaryPart:Qt,toolName:M},M==="memory"&&Ae.includes("SUCCESS")&&(yield{type:"memory_updated"}),qe++}if(u==="Google"&&Tn&&Date.now()-ar>=150){yield*is();let H=qs(Tn);for(let ne of H)yield ne;Tn="",ar=Date.now()}}P.usageMetadata&&($n=P.usageMetadata),$n&&(yield{type:"liveTokens",content:$n.totalTokenCount})}if(fe&&(fe=!1,jt?Ye+="</think>":(he+="</think>",u==="Google"?Tn+="</think>":yield{type:"text",content:"</think>"})),jt&&Ye.length>0){let P=0,ie=Math.min(st.length,Ye.length);for(let G=ie;G>0;G--)if(st.endsWith(Ye.substring(0,G))){P=G;break}let j=Ye.substring(P);if(j){let ke=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(st)?j.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):j.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(ke)if(he+=ke,u==="Google")Tn+=ke;else{yield*is();let ye=qs(ke);for(let Me of ye)yield Me}}jt=!1,Ye=""}if(yield*is(),Mt)break;let zs=(he||"").trim(),Xa=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(zs.toLowerCase())||/\[\[END\]\]/i.test(zs.toLowerCase()),Ja=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(zs.toLowerCase()),Qa=Q.length>0||Ut!==null,lr=on(zs).trim(),Za=/(\p{Emoji_Presentation}|\p{Extended_Pictographic})$/u.test(lr),el=/([.!?"'*_`|\]\)”’~~]+|\s|`{3}|[\u200B-\u200D\uFEFF])$/u.test(lr.trim()),tl=/[.!?}"'`’“”]$|```$/s.test(lr)||el||Za;!Xa&&!Ja&&!Qa&&zs.length>0,Ze=!0,await vt("agent",u)}catch(be){if(Mt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
|
|
721
|
+
|
|
722
|
+
\x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(String(be).includes("Incomplete JSON segment at the end")){fe&&(fe=!1,jt?Ye+="</think>":(he+="</think>",yield{type:"text",content:"</think>"})),Ze=!0,await vt("agent",u);break}if(fe&&(fe=!1,jt?Ye+="</think>":he+="</think>"),jt&&Ye.length>0){let rs=0,ln=Math.min(st.length,Ye.length);for(let Lt=ln;Lt>0;Lt--)if(st.endsWith(Ye.substring(0,Lt))){rs=Lt;break}let Ot=Ye.substring(rs);if(Ot){let Dt=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(st)?Ot.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):Ot.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");Dt&&(he+=Dt)}jt=!1,Ye=""}let ue=be instanceof Error?(()=>{try{return JSON.parse(JSON.parse(be.message).error.message).error.message}catch{return String(be)}})():String(be),ot=new Date().toLocaleString(),Ht=te.join(gn,"agent");Pe.existsSync(Ht)||Pe.mkdirSync(Ht,{recursive:!0}),Pe.appendFileSync(te.join(Ht,"error.log"),`ERROR [${ot}]: ${ue}
|
|
723
|
+
|
|
724
|
+
----------------------------------------------------------------------
|
|
725
|
+
|
|
726
|
+
`);let Jt=be.status||be.statusCode||be.code,jn=String(be).includes("replicas at capacity");if(!(Jt&&(Jt>=500&&Jt<600||Jt===408||Jt===429||jn)||!Jt&&(/status[ :]+(5\d\d|408|429)/i.test(String(be))||/code[ :]+(5\d\d|408|429)/i.test(String(be))||/(500|503|408|429)/.test(String(be))))){if(Ge<kn-3)throw be;yield{type:"text",content:ue},yield{type:"status",content:"Error Occured"}}if(he.trim().length>0||Xe>1)if(Xe<=kn){Xe++;let rs=Math.min(1e3*Math.pow(2,Xe-1),24e3);if(he.trim().length>0){b.push({role:"agent",text:he});let ln=`[system]
|
|
727
|
+
- seamless continuation: resume immediately. pick up from last words with zero gap/disruption
|
|
728
|
+
- no repetition: do not repeat any text already written
|
|
729
|
+
- no re-think: do not restart or open <think> if reasoning already started. continue the thinking and close thinking block </think> before chat output
|
|
730
|
+
- mid-tool safety: if cutoff was mid-tool call, restart that tool call from start
|
|
731
|
+
- stealth: do not mention/apologize for cutoff [/system]`;Q.length>0?Q.forEach((Ot,Lt)=>{Lt===Q.length-1?b.push({...Ot,text:`${Ot.text}
|
|
732
|
+
|
|
733
|
+
${ln}`}):b.push(Ot)}):b.push({role:"user",text:ln}),st+=he}for(let ln=rs/1e3;ln>0&&!Mt;ln--)yield{type:"status",content:`Error Occured. Recovering Stream (${Xe}/${kn}) [Retrying in ${ln.toFixed(0)}s]...`},await new Promise(Ot=>setTimeout(Ot,1e3));yield{type:"status",content:"Error Occured. Recovering Stream..."}}else throw new Error(`Stream collapsed too many times. (Failed to resolve ${kn} times)
|
|
734
|
+
Error log can be found in \`/export logs\``);else if(Ge<=kn){Ge++,Xe=1,st="";let rs=Math.min(1e3*Math.pow(2,Ge-1),32e3),ln=.8+Math.random()*.4,Ot=Math.round(rs*ln);ts=!0,yield{type:"status",content:`Trying to reach ${e} (${Ge}/${kn}) [Retrying in ${(Ot/1e3).toFixed(0)}s]`};for(let Lt=Ot/1e3;Lt>0&&!Mt;Lt--)yield{type:"status",content:`Trying to reach ${e} (${Ge}/${kn}) [Retrying in ${Lt.toFixed(0)}s]`},await new Promise(Dt=>setTimeout(Dt,1e3));yield{type:"status",content:`Trying to reach ${e}`}}else throw new Error(`Model ${e} cannot be reached. (Failed ${kn} times)
|
|
735
|
+
Error log can be found in \`/export logs\``)}}if($n){let fe=$n.totalTokenCount||0,be=$n.cachedContentTokenCount||0,ue=($n.candidatesTokenCount||0)+($n.thoughtsTokenCount||0);await Yt("tokens",fe,u,Re),be>0&&await Yt("cachedTokens",be,u,Re),ue>0&&await Yt("candidateTokens",ue,u,Re),yield{type:"usage",content:$n}}Ei.push(he);let ss=on(he),hn=Fa(he),Gs=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(hn.toLowerCase())||/\[\[END\]\]/i.test(hn.toLowerCase())||!0,Wn=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(hn.toLowerCase()),Uc=qe>0;yield{type:"status",content:"Thinking"};let za=Oc(he,/(\[\s*(turn\s*:)?\s*(continue|finish)\s*\]|\[\[END\]\])/gi,"").trim(),os=(Gs||Q.length===0)&&!Wt&&!Sn&&!Mn;if(os=Q.length===0?os:!1,os=ns||xo?!1:os,he&&he.trim().endsWith('")]')&&Q.length===0&&(os=!1),os){let fe=Ei.join(`
|
|
736
|
+
`),be=on(fe).trim();yield{type:"interactive_turn_finished",data:{agentText:T,fullAgentTextRaw:fe,history:[...b],needTitle:S}},b.length>0&&b[b.length-1].role==="agent"?b[b.length-1].text=be:b.push({role:"agent",text:be}),b.forEach(ue=>{if(ue.role==="user"&&ue.text&&(ue.text=ue.text.replace(/\n\[COMPILE ERROR\][\s\S]*?\[\/ERROR\]/g,""),ue.text=ue.text.replaceAll(`
|
|
737
|
+
|
|
738
|
+
[system] user question. resolve this specific query within '[ANSWER] ... [/ANSWER]' concisely, naturally [/system]
|
|
739
|
+
`,"").replaceAll(`[system] user question. resolve this specific query within '[ANSWER] ... [/ANSWER]' concisely, naturally
|
|
740
|
+
**strictly follow thinking policy as high priority. do not start a response without <think>...</think>** [/system]
|
|
741
|
+
`,"").replaceAll(`[system] **strictly follow thinking policy as high priority. do not start a response without <think>...</think>** [/system]
|
|
742
|
+
`,"").replaceAll(/\n\[system\] WARNING, Turn Limit Impending: Step \d+\/\d+\. Wrap up quickly\/prompt user to continue & use \[\[END\]\] quickly\. \[\/system\]/g,""),ue.text=ue.text.replaceAll(/\n\[system\] File Changes:\n(?:\* .+ \(created|modified|deleted\)\n)*\[\/system\]/g,""),(u==="Mistral"||u==="Google"&&e?.toLowerCase().startsWith("gemma"))&&ue.text.startsWith("[TOOL RESULT]"))){let Ht=`
|
|
743
|
+
[system] Tool result received. Analyze output and proceed with your turn [/system]`,Jt=`
|
|
744
|
+
[system] Tool result received. Analyze output and proceed with your turn. **strictly follow thinking policy. do not start a response without <think>...</think>** [/system]`;ue.text=ue.text.replaceAll(Jt,"").replaceAll(Ht,"").trim()}}),yield{type:"status",content:"[end]"}}if(os)break;let Ka=za.trim()||"*Working...*";if(b.push({role:"agent",text:Ka}),Q.length>0||pn){if(Q.length>0){let fe=Q.map(jn=>jn.text).join(`
|
|
745
|
+
|
|
746
|
+
`),ot=(on(he).replace(/\[{1,2}tool:[\s\S]*?\)\s*\]{1,2}/gi,"").match(/\[tool:/gi)||[]).length,Ht=Q.length+ot;if(Q.length<Ht){fe+=`
|
|
747
|
+
|
|
748
|
+
[system] Only ${Q.length} out of ${Ht} attempted tool calls were executed. Verify proper structure compliance & try failed calls again [/system]`;let jn=Ht-Q.length;for(let gt=0;gt<jn;gt++)await vt("toolFailure")}let Jt=Q.find(jn=>jn.binaryPart)?.binaryPart||null;b.push({role:"user",text:fe,binaryPart:Jt})}}else if(!Mt){let be=(he.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/i,"").match(/\[tool:/gi)||[]).length;xo||ns||be>0?(b.push({role:"user",text:`[system] Failed to execute ${be} tool${be>1?"s":""}. Verify proper structure compliance & try again [/system]`}),await vt("toolFailure"),yield{type:"visual_feedback",content:`
|
|
749
|
+
${sn("\u2718 Execution Error")}
|
|
750
|
+
`}):(yield{type:"visual_feedback",content:`
|
|
751
|
+
${sn("\u2718 Loop Detected")}
|
|
752
|
+
`},b.push({role:"user",text:`[system] ${Sn&&!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,Sn=!1,Mn=!1}c?.advanceRollback&&await Xn.recordTurnDelta(d,q+1,rn),xo=qe>0||pn}}catch(E){let $=(E instanceof Error?(()=>{try{return JSON.parse(JSON.parse(E.message).error.message).error.message}catch{return E.message||String(E)}})():String(E)).replace(/^(Error:\s*)+/i,""),I=new Date().toLocaleString(),D=te.join(gn,"agent");yield{type:"text",content:`\u2726 CRITICAL ERROR: ${$.includes("fetch failed")?"Failed to Connect. Check your Internet Connection or Wait a moment":$}
|
|
753
|
+
\u2800`},Pe.existsSync(D)||Pe.mkdirSync(D,{recursive:!0}),Pe.appendFileSync(te.join(D,"error.log"),`CRITICAL ERROR [${I}]: ${E}
|
|
754
|
+
|
|
755
|
+
----------------------------------------------------------------------
|
|
756
|
+
|
|
757
|
+
`),typeof flushGoogleBuffer=="function"&&(yield*flushGoogleBuffer()),yield{type:"tool_result",content:`ERROR: [INTERNAL CRITICAL] ${$}`}}finally{_&&(clearInterval(_),_=null),typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),await ht.commitTransaction(),c?.advanceRollback&&await Xn.cleanup(d),await xs()}yield{type:"status",content:null}},cg=async(e,n,t=null,o=null,s=50,r=null,a=!1)=>{let i=await Ft(),p={...i,...n},d=process.env.SUBAGENT_MODEL?process.env.SUBAGENT_MODEL.trim():null,l=process.env.SUBAGENT_PROVIDER?process.env.SUBAGENT_PROVIDER.trim():null,c=new Date,f=`${c.getFullYear()}-${c.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(c.getDate()).padStart(2,"0")}, ${c.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}).replace(":","-")}`,h=(E=>{if(!E)return null;let b=E.toLowerCase();return b==="google"?"Google":b==="deepseek"?"DeepSeek":b==="openrouter"?"OpenRouter":b==="nvidia"?"NVIDIA":b==="mistral"?"Mistral":b==="ollama"?"Ollama":b==="crofai"||b==="crof"?"CrofAI":b==="inferx"?"InferX":b==="sensenova"?"SenseNova":null})(l),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 E=await ur(p.aiProvider);E&&(p.apiKey=E)}let x=E=>{if(!E||typeof E!="string")return{allowed:!0};let b=[/rm\s+-[rf]{1,2}\s+[\/*.]/i,/rmdir\s+\/[sq]/i,/del\s+\/[fsq]/i,/\bformat\b\s+[a-z]:/i,/mkfs/i,/dd\s+if=/i,/\b(shutdown|reboot|poweroff|init\s+0|init\s+6)\b/i,/chmod\s+(-R\s+)?777\s+[\/*.]/i,/chown\s+(-R\s+)?root/i,/git\s+push\s+.*--force/i,/git\s+clean\s+-fdx/i,/\bsudo\s+su\b/i,/\bsu\s+-\b/i];for(let $ of b)if($.test(E))return{allowed:!1,reason:`Blocked potentially destructive or unsafe command pattern: "${$.source}"`};return{allowed:!0}},w=t||m||n?.modelName||n?.activeModel||i.activeModel,k=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",C=`-- TOOL DEFINITIONS (path = relative to CWD, path separator: '/') --
|
|
758
|
+
You cant execute tools. To use tools, must output exactly [tool:functions.ToolName(arg1="value1")] structured string in chat output & wait for system response \u2190 no exception, tool:functions must
|
|
759
|
+
Tool Rules:
|
|
760
|
+
- JSON escape literal sequences inside tool arguments (backslash: \\\\, newLine: \\n, quote: \\") \u2190 Mandatory
|
|
761
|
+
- Same file, multiple edits? ONE PatchFile (\u226415 blocks)
|
|
762
|
+
- Need text or huge file? CodeSearch > Full Read
|
|
763
|
+
- Avoid unnecessary large file chunk reads
|
|
764
|
+
- Dont hallucinate tool results, verify, fix errors
|
|
765
|
+
- Stuck on syntax error? Tell user > waste time
|
|
766
|
+
- ONLY valid tools defined below are allowed
|
|
767
|
+
|
|
768
|
+
# Provided Tools
|
|
769
|
+
**Communication Tools**
|
|
770
|
+
- AskUser(question="...", optionA="title::description", ...MAX4). Ambiguity, path divergence, security risk. Ask, dont finish/guess. Keep titles short
|
|
771
|
+
${a?'- AskMain(question="..."). Communicate with PARENT/MAIN AGENT. When clarification/decision is needed for a task':""}
|
|
772
|
+
|
|
773
|
+
**Web Tools**
|
|
774
|
+
- WebSearch(query="...", aiMode="bool, optional", limit="integer 3-10 aiMode: exclude"). Proactive use for unknown info/docs. aiMode: LLM search
|
|
775
|
+
- WebScrape(url="..."). Proactive use for specific webpage/docs/api
|
|
776
|
+
|
|
777
|
+
**Workspace Tools**
|
|
778
|
+
- 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
|
|
779
|
+
- ReadFolder(path="...", recurse="int 1-3"). Minimize recursion
|
|
780
|
+
- ReadFile(path="...", startLine="int", endLine="int")
|
|
781
|
+
- PatchFile(path="...", allowMultiple="bool, false", searchContent1="search string OR ^LINE:start..end$", newContent1="...", ...MAX15). Use small searchContent. Line Ranges must for large searchContent and escape sequences. ^...$ must for line ranges
|
|
782
|
+
- WriteFile(path="...", content="..."). Creates/Overwrites. File Exist? PatchFile > WriteFile. VERIFY IMPORTS
|
|
783
|
+
- Run(command="..."). Runs ${k==="Windows"?zn()?"powershell":"windows CMD":"bash"} command. Destructive/Irreversible ops \u2192 Ask user`.trim(),R=`=== START SYSTEM PROMPT ===
|
|
784
|
+
Identity: FluxFlow subagent helping the main Agent
|
|
785
|
+
Your task is: "${e}"
|
|
786
|
+
|
|
787
|
+
${C.trimEnd()}
|
|
788
|
+
|
|
789
|
+
-- THINKING GUIDANCE --
|
|
790
|
+
NO EXPLICIT THINKING REQUIRED. FOCUS ON TASK COMPLETION
|
|
791
|
+
Main focus: tools and task, not chatting
|
|
792
|
+
On completion, provide a detailed summary in Tables/Markdown Format with file modified info. If any task failed report back in detail
|
|
793
|
+
|
|
794
|
+
CWD: ${process.cwd()}
|
|
795
|
+
Current Time: ${f}
|
|
796
|
+
=== END SYSTEM PROMPT ===`,S=[{role:"user",text:`Complete this task: ${e}`}],T=0,_="";for(;T<s;){if(Mt){if(n?.taskId&&typeof Ve<"u"){let F=Ve.find(U=>U.id===n.taskId);F&&(F.status="cancelled")}throw r&&r("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}if(n?.taskId&&typeof Ve<"u"){let F=Ve.find(U=>U.id===n.taskId);if(F&&F.status==="cancelled")throw r&&r("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}let E=S.map(F=>({role:F.role==="user"?"user":"model",parts:[{text:F.text}]}));r&&r(`[Subagent Turn ${T+1}]...`);let $=(await nr(p,w,E,R,"Fast")).text||"",I=on($).trim();_=I,r&&r(`[Subagent Response]
|
|
797
|
+
${I}
|
|
798
|
+
`),S.push({role:"agent",text:I});let D=sr(I);if(D.length===0)break;let N=D.filter(F=>F.toolName.toLowerCase()==="askmain"||F.toolName.toLowerCase()==="ask_main"),W=!1,Y="";for(let F of D){if(Mt){if(n?.taskId&&typeof Ve<"u"){let A=Ve.find(B=>B.id===n.taskId);A&&(A.status="cancelled")}throw new Error("Subagent task was cancelled.")}if(n?.taskId&&typeof Ve<"u"){let A=Ve.find(B=>B.id===n.taskId);if(A&&A.status==="cancelled")throw new Error("Subagent task was cancelled.")}let U=F.toolName.toLowerCase();if(U==="askuser"&&(U="ask"),U==="askmain"||U==="ask_main"){if(W)continue;W=!0;let A="";if(N.length===1?A=O(N[0].args).question||N[0].args:A=N.map((B,X)=>{let J=O(B.args);return`Q${X+1}: ${J.question||B.args}`}).join(`
|
|
799
|
+
`),n.onAskMain){r&&r(`[Executing Tool] AskMain("${A}")...`);let B=await n.onAskMain(A);r&&r(`[Tool Result]
|
|
800
|
+
Answer from Main Agent: ${B}
|
|
801
|
+
`),Y+=`[TOOL RESULT for AskMain]: Answer from Main Agent: ${B}
|
|
802
|
+
|
|
803
|
+
`,await vt("toolSuccess")}else Y+=`[TOOL RESULT for AskMain]: ERROR: Main agent communication channel not available.
|
|
804
|
+
|
|
805
|
+
`;continue}if(!(o?o.some(A=>A.toLowerCase()===U):!0)){let A=`ERROR: Tool [${F.toolName}] is not in the allowed tools list for this subagent.`;r&&r(`[Blocked Tool Call] ${F.toolName} - not allowed
|
|
806
|
+
`),Y+=`${A}
|
|
807
|
+
|
|
808
|
+
`;continue}if(U==="exec_command"||U==="execcommand"||U==="run"){let A=O(F.args).command||"",B=x(A);if(!B.allowed){let X=`ERROR: [SECURITY RESTRICTION] Subagent execution blocked command: ${B.reason}`;r&&r(`[Blocked Command] ${A} - ${B.reason}
|
|
809
|
+
`),Y+=`${X}
|
|
810
|
+
|
|
811
|
+
`;continue}}let ve="";if(U==="web_search"||U==="websearch")ve=`\u2714 \x1B[95mSearched\x1B[0m: ${O(F.args).query||""}`;else if(U==="web_scrape"||U==="webscrape")ve=`\u2714 \x1B[95mScraped\x1B[0m: ${O(F.args).url||""}`;else if(U==="search_keyword"||U==="searchkeyword"||U==="codesearch"||U==="code_search"){let A=O(F.args),B=A.keyword||"",X=A.path||"";ve=`${B?"\u2714":"\u2718"} \x1B[95mSearched\x1B[0m: ${B||"No Query"}${X?` \u2192 ${X.replaceAll("\\","/")}`:""}`}else if(U==="view_file"||U==="viewfile"||U==="readfile")ve=`\u2714 \x1B[95mRead\x1B[0m: ${(O(F.args).path||"").replaceAll("\\","/")}`;else if(U==="list_files"||U==="read_folder"||U==="readfolder"){let A=O(F.args).path||null,B=O(F.args).recurse||0;ve=`${A?"\u2714":"\u2718"} \x1B[95mBrowsed\x1B[0m: ${A?`${A.replaceAll("\\","/")}${B>0?`${A.endsWith("/")?`*${B}`:`/*${B}`}`:`${A.endsWith("/")?"":"/"}`}`:""}`}else if(U==="write_file"||U==="writefile"){let A=O(F.args).path||null;ve=`${A?"\u2714":"\u2718"} \x1B[95mCreated\x1B[0m: ${A?`${A.replaceAll("\\","/")}`:"No File Changes"}`}else if(U==="update_file"||U==="updatefile"||U==="patchfile"||U==="patch_file"||U==="patchfile"||U==="updatefile"){let A=O(F.args).path||null,B=O(F.args).content||null;ve=`${A?"\u2714":"\u2718"} \x1B[95mEdited\x1B[0m: ${A?`${A.replaceAll("\\","/")}`:"No File Changes"}`}else if(U==="exec_command"||U==="execcommand"||U==="run"){let A=O(F.args).command||null;ve=`${A?"\u2714":"\u2718"} \x1B[95mExecuted\x1B[0m: ${A?A.slice(0,100)+(A.length>100?"...":""):"No Command"}`}else if(U==="file_map"||U==="filemap"){let A=O(F.args).path||"";ve=`${A?"\u2714":"\u2718"} \x1B[95mIndexed\x1B[0m: ${A?`${A.replaceAll("\\","/")}`:"File Not Found"}`}else if(U==="await"){let{time:A}=O(F.args),B=parseFloat(A)||0;B<10&&(B=10),B>180&&(B=180),ve=`\u2714 \x1B[95mAwaiting\x1B[0m \u2192 ${(J=>{if(J>=60){let We=Math.floor(J/60),Fe=J%60;return`${We}m${Fe>0?` ${Fe}s`:""}`}return`${J}s`})(B)}`}else{let A=pi[U]||F.toolName,B=Ss(U,F.args);ve=`\u2714 \x1B[95m${A}\x1B[0m${B?`: ${B}`:""}`}n.onVisualFeedback&&ve&&n.onVisualFeedback(ve),r&&r(`[Executing Tool] ${F.toolName}(${F.args})...`);try{let A=await mo(F.toolName,F.args,{...n,mode:"Flux"});if(r&&r(`[Tool Result]
|
|
812
|
+
${A}
|
|
813
|
+
`),Y+=`[TOOL RESULT for ${F.toolName}]: ${A}
|
|
814
|
+
|
|
815
|
+
`,await vt("toolSuccess"),U==="patchfile"||U==="update_file"||U==="updatefile"||U==="patch_file"){if(A){let B=A.split(`
|
|
816
|
+
`),X=0,J=0,We=!1;for(let Fe of B){if(Fe.includes("[DIFF_START]")){We=!0;continue}if(Fe.includes("[DIFF_END]")){We=!1;continue}We&&(/^\+\d+/.test(Fe)?X++:/^\-\d+/.test(Fe)&&J++)}(X>0||J>0)&&(await Yt("linesAdded",X),await Yt("linesRemoved",J))}}else if((U==="writefile"||U==="write_file")&&A){let B=A.match(/- Stats: \[(\d+) lines/),X=B?parseInt(B[1]):0,J=0;if(A.includes("Old File contents:")){let We=!1;for(let Fe of A.split(`
|
|
817
|
+
`)){if(Fe.includes("Old File contents:")){We=!0;continue}We&&(Fe.trim()===""?We=!1:/^\d+ \|/.test(Fe)&&J++)}}(X>0||J>0)&&(await Yt("linesAdded",X),await Yt("linesRemoved",J))}}catch(A){let B=`ERROR: Execution failed for [${F.toolName}]: ${A.message}`;r&&r(`[Tool Error] ${B}
|
|
818
|
+
`),Y+=`${B}
|
|
819
|
+
|
|
820
|
+
`,await vt("toolFailure")}}let ae="";if(n?.taskId&&typeof Ve<"u"){let F=Ve.find(U=>U.id===n.taskId);if(F&&F.pendingSteerMessages&&F.pendingSteerMessages.length>0){let U=[...F.pendingSteerMessages];F.pendingSteerMessages=[];for(let oe of U)ae+=`
|
|
821
|
+
|
|
822
|
+
[STEERING INSTRUCTION FROM MAIN AGENT]: ${oe}`,r&&r(`[Subagent Steered] ${oe}`)}}let V=(Y.trim()+ae).trim();S.push({role:"user",text:V}),T++}return _};export{xn as a,ea as b,Ef as c,_f as d,_l as e,ta as f,Cf as g,Ol as h,$f as i,go as j,Ea as k,Ph as l,Fh as m,O as n,zc as o,hr as p,Js as q,Kc as r,Yc as s,ht as t,fs as u,Ed as v,fl as w,_d as x,Cd as y,$d as z,Md as A,Ad as B,Fd as C,Nd as D,Cn as E,ml as F,eo as G,Yt as H,gl as I,qi as J,us as K,ql as L,_u as M,Cu as N,Uh as O,qo as P,Wh as Q,Rc as R,ng as S,Ec as T,_c as U,ui as V,on as W,Pa as X,Ac as Y,sg as Z,og as _,gi as $,rg as aa,ig as ba,Nc as ca,ag as da,lg as ea,cg as fa};
|