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
|
@@ -1,823 +0,0 @@
|
|
|
1
|
-
import{b as ar}from"./chunk-ACHIC75V.js";import{c as Ot,d as Cs,g as _e,h as Bt}from"./chunk-TKIVOTJ4.js";import{a as qs,b as $s,c as Z,d as me}from"./chunk-SIINYZWE.js";import{c as An,d as hn,e as xo,f as Es,g as _s,h as rr,i as tn,j as Nt,k as nn,l as vn,m as jn,n as ln,o as pn,p as is,q as ir,r as Hn,s as as}from"./chunk-I27MASHH.js";import{a as Xe,c as bo}from"./chunk-56EJGQU3.js";import{c as Si,d as Ti,e as zs}from"./chunk-GKFFLQSG.js";import ci from"dotenv";import{GoogleGenAI as Pa,ThinkingLevel as ut,HarmBlockThreshold as Vn,HarmCategory as Xn}from"@google/genai";import{execSync as nl}from"child_process";import{spawn as lr}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,h=-1,d=t;for(;d<e.length;){let l=e.indexOf(a,d);if(l===-1)break;let f=0;for(let y=l-1;y>=0&&e[y]==="\\";y--)f++;if(f%2!==0){d=l+1;continue}let u=e.substring(l+1),p=u.trim(),g=p===""||/^,\s*\w+\s*=/.test(p)||p.startsWith(")")&&(p.length===1||/^\)\s*([,\]\s]|\[\[?tool:)/i.test(p));if(g&&u.startsWith(`
|
|
2
|
-
`)){let y=p.split(`
|
|
3
|
-
`)[0];if(!y.includes("=")&&!y.includes(")")){d=l+1;continue}}if(g){h=l;break}d=l+1}h!==-1?(r=e.substring(i,h),t=h+1):(r=e.substring(i),t=e.length);let c=s.toLowerCase().includes("path")||["dest","source","to","from"].includes(s.toLowerCase());r=r.replace(/\\(.)/g,(l,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,h=t,d=-1;for(let c=t;c<e.length;c++){let l=e[c];if(i&&l===i){let f=0;for(let u=c-1;u>=0&&e[u]==="\\";u--)f++;f%2===0&&(i=null)}else!i&&(l==='"'||l==="'"||l==="`")&&(i=l);if(!i&&(l==="["?a++:l==="]"&&a--,a===0)){d=c;break}}if(d!==-1){r=e.substring(h,d+1),t=d+1;try{let c=r.trim();c.startsWith("'")||c.includes("'")}catch{}}else r=e.substring(h),t=e.length}else{let a=e.substring(t),i=a.match(/,\s*\w+\s*=|(?:\s*\)\s*(?:$|\]\]))/);if(i){let h=i.index;r=a.substring(0,h).trim(),t+=h}else r=a.trim(),t=e.length}r==="true"?r=!0:r==="false"?r=!1:typeof r=="string"&&!isNaN(r)&&r.trim()!==""&&(r=Number(r)),typeof r=="string"&&(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 ko=null;try{let e=await import("node-pty");ko=e.default||e}catch{}var Kc=!!ko,So=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),cr=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 c=0;c<d.length;c++){let l=d[c];if(l===`
|
|
5
|
-
`)for(t++,o=0;t>=n.length;)n.push([]);else if(l==="\r")o=0;else{for(;t>=n.length;)n.push([]);let f=n[t];for(;o>f.length;)f.push(" ");f[o]=l,o++}}};for(;(a=s.exec(e))!==null;){i(e.substring(r,a.index));let d=a[1],c=a[2],l=d?d.split(";").map(Number):[];if(c==="A"){let f=l[0]||1;t=Math.max(0,t-f)}else if(c==="B"){let f=l[0]||1;for(t=t+f;t>=n.length;)n.push([])}else if(c==="C"){let f=l[0]||1;o=o+f}else if(c==="D"){let f=l[0]||1;o=Math.max(0,o-f)}else if(c==="G"){let f=(l[0]||1)-1;o=Math.max(0,f)}else if(c==="H"||c==="f"){let f=(l[0]||1)-1,u=(l[1]||1)-1;for(t=Math.max(0,f),o=Math.max(0,u);t>=n.length;)n.push([])}else if(c==="K"){let f=l[0]||0;if(t<n.length){let u=n[t];if(f===0)u.length=o;else if(f===1)for(let p=0;p<o&&p<u.length;p++)u[p]=" ";else f===2&&(u.length=0)}}else if(c==="J"){let f=l[0]||0;(f===2||f===3)&&(n.length=0,n.push([]),t=0,o=0)}r=s.lastIndex}i(e.substring(r));let h=n.map(d=>d.join(""));for(;h.length>0&&h[h.length-1]==="";)h.pop();return h.join(`
|
|
6
|
-
`)},yt=null,Ks=!1,Yc=e=>{try{yt&&(Ks&&typeof yt.write=="function"?yt.write(e):yt.stdin&&yt.stdin.writable&&yt.stdin.write(e))}catch{}},Vc=()=>{if(yt){try{Ks&&typeof yt.destroy=="function"?yt.destroy():typeof yt.kill=="function"&&(process.platform==="win32"?lr("taskkill",["/pid",yt.pid,"/f","/t"]):yt.kill("SIGKILL"))}catch{}yt=null,Ks=!1}},dr=(e,n=!1)=>{if(process.platform!=="win32")return e;let t=[],o="",s=null,r=!1;for(let c=0;c<e.length;c++){let l=e[c];if(r){o+=l,r=!1;continue}if(l==="\\"){if(e[c+1]===" "){o+=" ",c++;continue}o+=l,r=!0;continue}s?(l===s&&(s=null),o+=l):l==='"'||l==="'"?(s=l,o+=l):l===";"&&!o.includes("://")?(o.length>0&&(t.push(o),o=""),t.push(n?";":"&")):l==="&"&&!o.includes("://")?e[c+1]==="&"?(o.length>0&&(t.push(o),o=""),t.push("&&"),c++):(o.length>0&&(t.push(o),o=""),t.push("&")):l==="|"&&!o.includes("://")?(o.length>0&&(t.push(o),o=""),t.push("|")):/\s/.test(l)?o.length>0&&(t.push(o),o=""):o+=l}o.length>0&&t.push(o);let a=c=>!(!c.includes("/")||/^(https?|file|ftp):\/\//i.test(c)||c.startsWith("@")||c.startsWith("/")&&(c.match(/\//g)||[]).length===1||/\s\/|\/\s/.test(c)||/[\(\)\{\}\;\<\>\=\'\"]/.test(c)),i=[];for(let c=0;c<t.length;c++){let l=t[c];if(l==="mkdir"&&n&&Gn()){let f=[],u=c+1;for(;u<t.length;){let p=t[u];if([">",">>","<","&","&&","|","||",";"].includes(p))break;p!=="-p"&&p!=="--parents"&&p!=="-v"&&p!=="--verbose"&&f.push(p),u++}if(f.length>0){let p=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",p.join(","))}else i.push("New-Item","-ItemType","Directory","-Force");c=u-1;continue}if(l==="rm"&&n&&Gn()){let f=[],u=!1,p=!1,g=c+1;for(;g<t.length;){let m=t[g];if([">",">>","<","&","&&","|","||",";"].includes(m))break;m==="-rf"||m==="-fr"?(u=!0,p=!0):m==="-r"||m==="-R"||m==="--recursive"?u=!0:m==="-f"||m==="--force"?p=!0:f.push(m),g++}let y=["Remove-Item"];if(u&&y.push("-Recurse"),p&&y.push("-Force"),f.length>0){let m=f.map(w=>{let x=w.replace(/^['"]|['"]$/g,""),S=w;return a(x)&&(S=w.replace(/\//g,"\\")),S});y.push("-Path",m.join(","))}i.push(...y),c=g-1;continue}if(l==="cp"&&n&&Gn()){let f=[],u=!1,p=!1,g=c+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"?p=!0:f.push(m),g++}let y=["Copy-Item"];if(u&&y.push("-Recurse"),p&&y.push("-Force"),f.length>0){let m=f.map(w=>{let x=w.replace(/^['"]|['"]$/g,""),S=w;return a(x)&&(S=w.replace(/\//g,"\\")),S});if(m.length>1){let w=m.pop();y.push("-Path",m.join(","),"-Destination",w)}else y.push("-Path",m[0])}i.push(...y),c=g-1;continue}if(l==="touch"&&n&&Gn()){let f=[],u=c+1;for(;u<t.length;){let p=t[u];if([">",">>","<","&","&&","|","||",";"].includes(p))break;f.push(p),u++}if(f.length>0){let g=`(${f.map(y=>{let m=y.replace(/^['"]|['"]$/g,""),w=y;return a(m)&&(w=y.replace(/\//g,"\\")),w}).join(", ")}) | ForEach-Object { if (Test-Path $_) { (Get-Item $_).LastWriteTime = [System.DateTime]::Now } else { $null | Out-File -FilePath $_ } }`;i.push(g)}c=u-1;continue}if(l==="|"&&t[c+1]==="tee"){t[c+2]==="-a"?(i.push(">>"),c+=2):(i.push(">"),c+=1);continue}if(l==="|"&&t[c+1]==="cat"&&t[c+2]===">"){i.push(">"),c+=2;continue}if(l==="|"){let f=t[c+1];if(f){let u=f.replace(/^['"]|['"]$/g,""),p=/\.(txt|md|json|log|csv|html|css|py|js|xml|yaml|yml|pdf|docx|pptx|xlsx)$/i.test(u);if(a(u)&&p){i.push(">");continue}}}i.push(l)}let h=!1,d=i.map(c=>{if(c==="echo")return h=!0,c;[">",">>","<","&","&&","|","||",";"].includes(c)&&(h=!1);let f=/^['"]|['"]$/.test(c),u=c;h&&f&&(u=c.replace(/^['"]|['"]$/g,""));let p=/^['"]|['"]$/.test(u),g=u.replace(/^['"]|['"]$/g,"");a(g)&&(u=u.replace(/\//g,"\\"));let y=u.replace(/^['"]|['"]$/g,"");return y.includes(" ")&&!p&&(u=`"${y}"`),u});if(n){let c="",l=0;for(let f=0;f<d.length;f++){let u=d[f];u==="&&"?(c+="; if ($?) {",l++):u===";"?(c+=" }".repeat(l)+";",l=0):(c&&!c.endsWith(" ")&&!c.endsWith("{")&&(c+=" "),c+=u)}return c+=" }".repeat(l),c}return d.join(" ")},fr=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 h=d=>{let c=d==="pwsh"||d==="powershell",l=dr(t,c),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?c?["-NoProfile","-Command",l]:["/c",l]:["-c",l];if(r.networkAccess===!1&&!s){let p=f,g=[...u];if(process.platform==="linux")f="unshare",u=["-n","-r",p,...g];else if(process.platform==="darwin"){let y=`(version 1)
|
|
7
|
-
(allow default)
|
|
8
|
-
(deny network-outbound)
|
|
9
|
-
(allow network-outbound (remote ip "localhost:*"))
|
|
10
|
-
(allow network-outbound (remote ip "127.0.0.1:*"))
|
|
11
|
-
`;f="sandbox-exec",u=["-p",y,p,...g]}}if(ko)try{let p=ko.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}});yt=p,Ks=!0;let g="",y=!1;return p.onData(m=>{if(!y){g+=m,o&&o(m);let w=So(g);/(?:Network:\s+use\s+--host\s+to|Network:\s+Type\s+--host\s+to|Local:\s+http:\/\/localhost:\d+|ready in \d+\s*ms|Compiled successfully|Development server is running|Listening on:)/i.test(w)&&(y=!0,setTimeout(()=>i(`SUCCESS: Dev server started successfully in background.
|
|
12
|
-
|
|
13
|
-
${w}`),500))}}),p.onExit(({exitCode:m})=>{if(y)return;yt=null;let w=cr(g||""),x=So(w).replace(/\n{3,}/g,`
|
|
14
|
-
|
|
15
|
-
`)||"Command executed with no output.";i(m!==0?`ERROR: Command [${t}] failed with exit code [${m}].
|
|
16
|
-
|
|
17
|
-
${x}`:`SUCCESS: Command [${t}] completed.
|
|
18
|
-
|
|
19
|
-
${x}`)}),!0}catch(p){return s&&(d==="pwsh"||d==="powershell")&&p.code==="ENOENT"?!1:(To(i,l,t,a,o,d,r),!0)}else return To(i,l,t,a,o,d,r),!0};s?h("pwsh")||h("powershell")||h("cmd"):h("bash")})},To=(e,n,t,o,s,r="powershell",a={})=>{let i=process.platform==="win32",h=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 c=i?h?["-NoProfile","-Command",n]:["/c",n]:["-c",n];if(a.networkAccess===!1&&!i){let g=d,y=[...c];if(process.platform==="linux")d="unshare",c=["-n","-r",g,...y];else if(process.platform==="darwin"){let m=`(version 1)
|
|
20
|
-
(allow default)
|
|
21
|
-
(deny network-outbound)
|
|
22
|
-
(allow network-outbound (remote ip "localhost:*"))
|
|
23
|
-
(allow network-outbound (remote ip "127.0.0.1:*"))
|
|
24
|
-
`;d="sandbox-exec",c=["-p",m,g,...y]}}let l=i?lr(d,c,{cwd:process.cwd(),env:{...process.env,...o}}):lr(d,c,{cwd:process.cwd(),env:{...process.env,CI:"false",TERM:"xterm-256color",FORCE_COLOR:"1",...o}});yt=l,Ks=!1,l.stdin&&l.stdin.on("error",()=>{yt=null});let f="",u="",p=!1;l.stdout.on("data",g=>{if(!p){let y=g.toString();f+=y,s&&s(y);let m=So(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)&&(p=!0,setTimeout(()=>e(`SUCCESS: Dev server started successfully in background.
|
|
25
|
-
|
|
26
|
-
${m}`),500))}}),l.stderr.on("data",g=>{if(!p){let y=g.toString();u+=y,s&&s(y)}}),l.on("close",g=>{if(p)return;yt=null;let y=[],m=cr(f),w=cr(u);m&&y.push(`STDOUT:
|
|
27
|
-
${m}`),w&&y.push(`STDERR:
|
|
28
|
-
${w}`),g!==0&&y.push(`EXIT CODE: ${g}`);let x=y.join(`
|
|
29
|
-
|
|
30
|
-
`)||"Command executed with no output.",S=So(x).replace(/\n{3,}/g,`
|
|
31
|
-
|
|
32
|
-
`);e(g!==0?`ERROR: Command [${t}] failed with exit code [${g}].
|
|
33
|
-
|
|
34
|
-
${S}`:`SUCCESS: Command [${t}] completed.
|
|
35
|
-
|
|
36
|
-
${S}`)}),l.on("error",g=>{if(i&&g.code==="ENOENT"){if(r==="pwsh"){let m=dr(t,!0);return To(e,m,t,o,s,"powershell",a)}else if(r==="powershell"){let m=dr(t,!1);return To(e,m,t,o,s,"cmd",a)}}yt=null;let y=g instanceof Error?g.message:String(g);e(`ERROR: Failed to start command [${t}]: ${y}`)})};var Ys=null,Gn=()=>{if(process.platform!=="win32")return!1;if(Ys!==null)return Ys;try{nl('powershell.exe -NoProfile -Command "exit"',{stdio:"ignore"}),Ys=!0}catch{Ys=!1}return Ys},ur=null,Ri=(e,n,t,o,s=!1,r=!0)=>{ur===null&&(ur=s);let a=`- JSON escape literal escape sequences in tool arguments (new line: \\\\n, backslash: \\\\)
|
|
37
|
-
- Same file, multiple edits? One PatchFile (\u226415 blocks) \u2190 Priority
|
|
38
|
-
- Tool denied? Ask for guidance \u2190 mandatory
|
|
39
|
-
- Need text or huge file? CodeSearch > Full Read
|
|
40
|
-
- Avoid unnecessary large file chunk reads
|
|
41
|
-
- Dont hallucinate tool results, verify, fix errors
|
|
42
|
-
- Stuck on syntax error? Tell user > waste time
|
|
43
|
-
`,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"?Gn()?"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
|
-
${ur?'\n**Emergency Tools**\nInfo: `initial` = current task prompt. Revert `id` = turn before disaster (eg. disaster: `turn_3` \u2192 revert: `turn_2`). Reason explicitly\n- EmergencyRollback(method="getCheckpoint/forceRevert", id="..."). Rollback workspace in this agent loop. ONLY for catastrophic corruption. Before ending, verify no catastrophe. `id` omitted for `getCheckpoint`\n':""}${r?`
|
|
52
|
-
**Sub Agent Tools**
|
|
53
|
-
proactive use highly recommended. Prefer for any task, no user nudge needed
|
|
54
|
-
Invocations:
|
|
55
|
-
\u2022 Invoke (async/background, \u22647 parallel). Parallelize long tasks. May take time
|
|
56
|
-
\u2022 InvokeSync (sync/blocking). Sequential, repetitive or delegated tasks. Saves tokens/cost
|
|
57
|
-
- InvokeSync/Invoke(title="...", task="..."). Task must be detailed: exact file paths, imports/exports, dependencies
|
|
58
|
-
- Await(id="...", timeout="integer"). Event-driven wait
|
|
59
|
-
- GetProgress(id="..."). Poll sparingly; NO initial poll. Work or await. Never end while subagent runs
|
|
60
|
-
- Steer(id="...", message="..."). Inject additional instruction or redirection into active async subagent
|
|
61
|
-
- Cancel(id="..."). Cancel async task ONLY if stalled (2m+) or incorrect`:""}`,h=`**Creative Tools (path = relative; first argument, path separator: '/')**
|
|
62
|
-
- WritePDF(path="...", content="...", orientation="..."). Proactive A4 page breaks must in css. HTML/CSS for premium layout, stable margins & headers/footers, no watermarks
|
|
63
|
-
- WriteDoc(path="...", content="..."). A4 Word document, no watermarks, stable margins & headers/footers`,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 response \u2190 no exception, tool:functions must
|
|
72
|
-
Tool Rules:
|
|
73
|
-
- Max 3 tool calls/turn${e==="Flux"||e.toLowerCase()==="fluxcu"?" (Todo: 3+)":""}
|
|
74
|
-
${e==="Flux"||e.toLowerCase()==="fluxcu"?`${a}`:""}
|
|
75
|
-
**User Communication**
|
|
76
|
-
- Ask(question="...", optionA="title::description", ...MAX4). Ambiguity, path divergence, security risk. Ask, dont finish/guess. Keep titles short
|
|
77
|
-
|
|
78
|
-
**Web Tools**
|
|
79
|
-
- WebSearch(query="...", aiMode="bool, optional", limit="integer 3-10 aiMode: exclude"). Proactive use for unknown info/docs. aiMode: LLM search
|
|
80
|
-
- WebScrape(url="..."). Proactive use for specific webpage/docs/api
|
|
81
|
-
|
|
82
|
-
${e==="ICU"?`${d}`:e==="FluxCU"?`${i}
|
|
83
|
-
${d}`:e==="Flux"?`${i}`:`${h}`}`.trim()};var Ei=(e=!0,n=!0)=>`
|
|
84
|
-
To use tools, must output exactly '[tool:functions.ToolName(arg1="value1")]' structured string in chat response \u2190 no exception
|
|
85
|
-
|
|
86
|
-
-- Chat Management Tools --
|
|
87
|
-
- Chat(title="<short creative title of FULL conversation in 3 or 4 words>"). Consider full chat context to generate title NOT just latest message
|
|
88
|
-
- Memory(action="temp", content="<summary of the user prompt & model responses only from latest prompt under 40 words>. [Talked on: <date> <hour>]"). Time format: YYYY-MM-DD HH am/pm
|
|
89
|
-
|
|
90
|
-
${e?`-- User-specific long-term/permanent memory (use based on conversation context, do not re-save memory which is already saved) --
|
|
91
|
-
- Add: Memory(action="user", method="add", content="<string to add>. [Saved on: <date ONLY>]", score=2). (Set score=2 ONLY if the user explicitly asked to "remember" or "save" this information, else omit this parameter entirely)
|
|
92
|
-
- Delete: Memory(action="user", method="delete", id="<memory id>")
|
|
93
|
-
- Update: Memory(action="user", method="update", content-new="string to update", id="<memory id>")
|
|
94
|
-
|
|
95
|
-
-- Memory Relevance Decay Tool --
|
|
96
|
-
- Score Adjustment: addMemScore(id="<memory id>")
|
|
97
|
-
You MUST call this tool when a specific saved memory in the '-- Current Saved User Memories --' list was relevant, referenced, or helpful in the agent's response or user prompt in current message. You can stack multiple calls
|
|
98
|
-
|
|
99
|
-
Explicit Triggers for permanent memory:
|
|
100
|
-
- User explicitly asks to 'remember' something
|
|
101
|
-
- User mentions something important long-term that should be remembered
|
|
102
|
-
- User provides information that could be useful for long-term reference
|
|
103
|
-
- User shares personal information or preferences
|
|
104
|
-
|
|
105
|
-
Usage Rules:
|
|
106
|
-
- Frequency for 'user' action: Based on explicit triggers
|
|
107
|
-
- If you want to save something, but similar memory already exists, use the update method not add
|
|
108
|
-
- Chat title is mandatory
|
|
109
|
-
- Temporary memory is mandatory
|
|
110
|
-
- When called user memory, still use Temporary Memory
|
|
111
|
-
- Must not ignore any tool calls in given context of chat between user & agent`:""}`.trim();var Ro={xHigh:`Effort: High
|
|
112
|
-
Challenge assumptions, verify before concluding, prefer the simplest correct solution, assess architecture, scalability & trade-offs, verify dependencies, regressions, failure modes & modular design, plan: files, modules, interfaces & tests
|
|
113
|
-
Continuous analysis, verify from first principles, seek failure paths, verify imports, tool results & system stability; avoid syntax errors
|
|
114
|
-
MANDATORY: Full technical verification`,High:`Effort: High
|
|
115
|
-
Rigorous thinking, prefer the simplest correct solution, assess architecture, performance & maintainability, verify error handling, assumptions, edge cases, dependencies & regressions, plan: files, functions, logic & interactions
|
|
116
|
-
Continuous analysis, verify from first principles, seek failure paths, verify imports, tool results & system stability; avoid syntax errors
|
|
117
|
-
MANDATORY: Full technical verification`,Medium:`Effort: Medium
|
|
118
|
-
Focused, technical thinking, find the simplest solution meeting requirements, check error handling, assumptions, edge cases & dependencies, verify cohesive, modular changes, outline: files, functions & key logic
|
|
119
|
-
Logical, implementation-focused, efficient, deliberate, verify imports, tool results & system stability; avoid syntax errors
|
|
120
|
-
MANDATORY: Brief verification for technical tasks/greetings`,Minimal:`Effort: Low
|
|
121
|
-
Quick, focused thinking, intent & complexity, required tools/files/actions, before acting
|
|
122
|
-
Brief thoughts, think only enough to avoid mistakes, verify imports, tool results & system stability; avoid syntax errors`,Off:`Effort: Lowest
|
|
123
|
-
No thinking. Immediate response
|
|
124
|
-
Verify imports, tool results & system stability; avoid syntax errors`};import $i from"fs";import ol from"screenshot-desktop";var Ci=!1;(async()=>{try{let e=await Bt();if(Number(e?.display)===1){let n=await ol.listDisplays();n&&n.length>1&&(Ci=!0)}}catch{}})();var hr=null,_i=null,Vs=null,ud=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",rl=process.env.NO_DEV||!1,il=(e,n)=>{if(!n)return"";if(e!==_i||Vs===null){_i=e;try{let t=Z(Nt,[]);Array.isArray(t)&&t.length>0?Vs=t.map(o=>`- ${o.memory}`).join(`
|
|
125
|
-
`):Vs=""}catch(t){Vs="",$i.appendFileSync(`${hn}/memory/error.txt`,`${t.message}
|
|
126
|
-
-------------------------------------------------
|
|
127
|
-
|
|
128
|
-
`)}}return Vs},Mi=(e="",n="",t=!0,o=!1)=>{if(typeof n=="boolean"&&(o=t,t=n,n=""),!t)return"";let s=e?.length>0&&!o?`-- Recent context from other chats (Priority: Low, Focus: Chat Context > Recent) --
|
|
129
|
-
${e}`:"";return s?`${s}`:""},Ai=(e,n,t,o,s=!0,r=!1,a="Google",i=!1,h,d)=>{let c=!1;process.env.forcedReasoning&&(c=!0);let l="";if(!h&&a==="Google"){let R=n;n==="Fast"&&(R="Off"),n==="Low"&&(R="Minimal"),n==="Standard"&&(R="Medium"),(n==="xHigh"||n==="Max")&&(R="xHigh"),l=Ro[R]||Ro.Medium}if(h||a!=="Google"){let R={Fast:"Lowest",Low:"Low",Medium:"Medium",Standard:"Medium",High:"High",xHigh:"High",Max:"High"};l=Ro.xHigh,l=l.replace("Effort: High",`Effort: ${R[n]}`).replace(`
|
|
130
|
-
MANDATORY: Full technical verification`,""),n==="Fast"?l=`Effort: Lowest
|
|
131
|
-
No thinking. Immediate response
|
|
132
|
-
Verify imports, tool results & system stability; avoid syntax errors`:n==="Low"&&(l=`Effort: Low
|
|
133
|
-
Quick, focused thinking, intent & complexity, required tools/files/actions, before acting
|
|
134
|
-
Brief thoughts, think only enough to avoid mistakes, verify imports, tool results & system stability; avoid syntax errors`)}let f=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",u=e.instructions&&e.instructions?.length>0?`User Preferences: ${e.instructions}
|
|
135
|
-
|
|
136
|
-
`:"",p=e.nickname&&e.nickname?.length>0?`User Nickname: ${e.nickname}
|
|
137
|
-
${u.length?"":`
|
|
138
|
-
`}`:"",g=e.name&&e.name?.length>0?`User Name: ${e.name}
|
|
139
|
-
${p.length||u.length?"":`
|
|
140
|
-
`}`:"",y=process.cwd(),m=il(d,s),w=m?.length>0?`--- Saved Memories ---
|
|
141
|
-
${m}
|
|
142
|
-
|
|
143
|
-
`:"",x=(()=>{let R=process.cwd().toLowerCase();if(process.platform==="win32"){let k=process.env.SystemRoot?.toLowerCase()||"c:\\windows",T=process.env.ProgramFiles?.toLowerCase()||"c:\\program files",_=process.env["ProgramFiles(x86)"]?.toLowerCase()||"c:\\program files (x86)";return R.startsWith(k)||R.startsWith(T)||R.startsWith(_)}else return R==="/"||["/bin","/sbin","/etc","/usr","/var","/root"].some(T=>R.startsWith(T))})(),S=[{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||hr===null){let R=S.filter(k=>$i.existsSync(k.name));hr=t==="Flux"&&R.length>0?`
|
|
144
|
-
-- PROJECT CONTEXT --
|
|
145
|
-
${R.map(k=>`- ${k.name}: ${k.desc}`).join(`
|
|
146
|
-
`)}
|
|
147
|
-
Check these first; These Files > Training Data. Safety rules apply
|
|
148
|
-
`:""}let C=hr;return`=== SYSTEM PROMPT ===
|
|
149
|
-
Identity: Flux Flow. Sassy, Friendly, CLI assistant${rl?"":" by Kushal Roy"}
|
|
150
|
-
${t==="Flux"?"Stepwise Execution, Run Automated Tests. Task Completion":t==="Flow"?"Concise, Humorous, Sarcastic":t==="ICU"?"Computer Use Capabilities. Screenshot as ground truth, analyze grid ids overlapping/close to target, keyboard shortcuts > mouse clicks":"Computer Use & Workspace Capabilities. Screenshot as ground truth, analyze grid ids overlapping/close to target, keyboard shortcuts > mouse clicks. Workspace Tools if faster. Focus on Productivity"}${Ci&&t.toLowerCase().includes("cu")?`
|
|
151
|
-
**Running on secondary screen. Opened app not visible in screenshot? Might be opened on primary. Use 'Ask' immediately with NO options and tell user to move app window to secondary**`:""}
|
|
152
|
-
|
|
153
|
-
- OS: ${f}
|
|
154
|
-
- Use directory structure for file path resolution${s?`
|
|
155
|
-
- Use relative time reference eg. few mins ago
|
|
156
|
-
-- Chat Context > Metadata`:""}
|
|
157
|
-
|
|
158
|
-
-- THINKING GUIDANCE --
|
|
159
|
-
${a==="Mistral"||a==="Google"&&!h?`${l}
|
|
160
|
-
${c||n!=="Fast"&&(a==="Mistral"&&!h||n!=="xHigh"&&!h)?`critical thinking policy
|
|
161
|
-
- Use <think>...</think> for reasoning before responding any queries
|
|
162
|
-
`:""}`:`${l}
|
|
163
|
-
`}
|
|
164
|
-
${Ri(t,f,a.toLowerCase()==="deepseek"?!1:i,a,o?.advanceRollback,o?.subAgents!==!1)}
|
|
165
|
-
${C}${s?`
|
|
166
|
-
-- MEMORY RULES --
|
|
167
|
-
- Subtly Personalize with relevent contextual memories. Auto Saves
|
|
168
|
-
`:""}
|
|
169
|
-
${t==="Flux"?`-- SECURITY POLICIES --
|
|
170
|
-
- Sensitive files? Ask before Read
|
|
171
|
-
`:t.toLowerCase().includes("cu")?`-- SECURITY POLICIES --
|
|
172
|
-
- Dont operate on ANY confidential screens
|
|
173
|
-
`:""}
|
|
174
|
-
-- CHAT FORMATTING --
|
|
175
|
-
- GFM Markdown
|
|
176
|
-
- Language: english only
|
|
177
|
-
- Dont mix chat & tools in same response${t==="Flow"?`
|
|
178
|
-
- use kaomojis heavily`:""}
|
|
179
|
-
=== END SYSTEM PROMPT ===
|
|
180
|
-
|
|
181
|
-
${g}${p}${u}${w}`.trim()},vi=(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
|
-
${Ei(n,t)}
|
|
199
|
-
=== END SYSTEM PROMPT ===${e?`
|
|
200
|
-
|
|
201
|
-
-- current saved user memories --
|
|
202
|
-
${e}`:""}`.trim();import Ct from"fs-extra";import Eo from"path";import{nanoid as cl}from"nanoid";import pt from"fs-extra";import cn from"path";pt.ensureDirSync(jn);var mn=null;async function al(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=cn.join(jn,n.chatId,e.backupFile);if(await pt.pathExists(t)){let o=Z(t,null);if(!o||!o.data)throw new Error(`Backup container corrupt or empty for ${cn.basename(e.filePath)}`);let s=$s(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 ${cn.basename(e.filePath)}: ${t.message}`)}}async function ll(e,n,t=7){let o=0;for(;o<t;)try{return await al(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 pr=null,mt={async startTransaction(e,n){pr=e,mn={id:`tx_prompt_${Date.now()}`,chatId:e,timestamp:new Date().toISOString(),prompt:n.trim(),changes:[],reverted:!1},me(is,mn)},async recordFileChange(e,n=null){try{if(!mn){if(pr){let a=Z(ln,[]),i=[...a].reverse().find(h=>h.chatId===pr);if(i){if(i.changes.some(f=>f.filePath===e))return;let c=await pt.pathExists(e)||n?"update":"create",l=null;if(c==="update"){let f=cn.basename(e);l=`${i.id}_${f}.bak`;let u=cn.join(jn,i.chatId);await pt.ensureDir(u);let p=cn.join(u,l),g=n!==null?n:await pt.readFile(e,"utf8").catch(()=>null);g!==null?me(p,{data:qs(g)}):(c="create",l=null)}i.changes.push({filePath:e,type:c,backupFile:l}),me(ln,a)}}return}if(mn.changes.some(a=>a.filePath===e))return;let s=await pt.pathExists(e)||n?"update":"create",r=null;if(s==="update"){let a=cn.basename(e);r=`${mn.id}_${a}.bak`;let i=cn.join(jn,mn.chatId);await pt.ensureDir(i);let h=cn.join(i,r),d=n!==null?n:await pt.readFile(e,"utf8").catch(()=>null);d!==null?me(h,{data:qs(d)}):(s="create",r=null)}mn.changes.push({filePath:e,type:s,backupFile:r}),me(is,mn)}catch{}},async commitTransaction(){if(mn)try{let e=Z(ln,[]);if(e.push(mn),e.length>512e3){let n=e.shift();if(n.changes)for(let t of n.changes)t.backupFile&&await pt.remove(cn.join(jn,n.chatId,t.backupFile)).catch(()=>{})}me(ln,e),await pt.remove(is).catch(()=>{})}catch{}finally{mn=null}},async recoverCrashedTransaction(){try{if(await pt.pathExists(is)){let e=Z(is,null);if(e?.changes?.length>0){let n=Z(ln,[]);n.some(t=>t.id===e.id)||(n.push(e),me(ln,n))}await pt.remove(is).catch(()=>{})}}catch{}},async rollbackToBefore(e){let n=Z(ln,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 ll(i,a);for(let i of a.changes)if(i.backupFile){let h=cn.join(jn,a.chatId,i.backupFile);await pt.remove(h).catch(()=>{})}n=n.filter(i=>i.id!==a.id),me(ln,n)}return{success:!0,chatId:o,targetPrompt:s}},async getChatHistory(e){try{return Z(ln,[]).filter(t=>t.chatId===e&&!t.reverted)}catch{return[]}},async deleteChatBackups(e){try{await pt.remove(cn.join(jn,e));let n=Z(ln,[]),t=n.filter(o=>o.chatId!==e);n.length!==t.length&&me(ln,t)}catch{}}};var Ii=Promise.resolve(),_o=e=>{let n=Ii.then(async()=>{try{return await e()}catch(t){throw console.error("Lock Operation Failed:",t),t}});return Ii=n.catch(()=>{}),n},ls=async()=>{await Ct.ensureDir(_s);let e={};if(await Ct.pathExists(Es))try{e=Z(Es,{})}catch{e={}}for(let n in e){let t=Eo.join(_s,`${n}.json`);Object.defineProperty(e[n],"messages",{get:()=>{if(Ct.existsSync(t))try{return Z(t,[])}catch{return[]}return[]},set:o=>{try{me(t,o)}catch{}},enumerable:!1,configurable:!0})}return e},_d=async(e,n,t)=>_o(async()=>{await Ct.ensureDir(_s);let o=await ls(),s=o[e],r=(t||[]).filter(y=>!y.isUpdateNotification&&(!y.isMeta||y.text&&y.text.includes("Request Cancelled")));try{(await Bt()).systemSettings?.preserveThinking===!1&&(r=r.filter(m=>m.role!=="think"))}catch{}let a=y=>{if(!y)return;let m=typeof y=="string"?y:y.text||y.content||"";if(!m||typeof m!="string")return;let w=m.replace(/\s*\n+\s*\[Prompted on:.*?\]/g,"").replace(/\[\/?(?:STEERING HINT|QUESTION)(?::\s*\w+)?\]/gi,"").trim();if(!w)return;let x=w.split(/\s+/),S;return x.length>7?S=x.slice(0,7).join(" ")+"...":w.length>45?S=w.substring(0,45).trimEnd()+"...":S=w,S},i,h=r.filter(y=>y.role==="user"),d=h[0],c=h[h.length-1],l=a(c),f=a(d);s&&s.prompt?Math.random()<.5&&l?i=l:i=s.prompt:i=f||l;let u=n||(s?s.name:`Session ${e.slice(-6)}`),p=Eo.join(_s,`${e}.json`);me(p,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};me(Es,g)}),Oi=async(e,n)=>_o(async()=>{let t=await ls();t[e]?(t[e].name=n,t[e].updatedAt=Date.now()):t[e]={name:n,updatedAt:Date.now()};let o={};for(let s in t)o[s]={name:t[s].name,prompt:t[s].prompt||void 0,updatedAt:t[s].updatedAt};me(Es,o)}),dl=async e=>_o(async()=>{let n=await ls();delete n[e];let t={};for(let a in n)t[a]={name:n[a].name,prompt:n[a].prompt||void 0,updatedAt:n[a].updatedAt};if(me(Es,t),await Ct.pathExists(Hn))try{let a=Z(Hn,[]);if(Array.isArray(a)){let i=a.filter(h=>Object.keys(h)[0]!==String(e));me(Hn,i)}}catch{}let o=Z(nn,{});o[e]&&(delete o[e],me(nn,o));let s=Z(vn,{});s[e]&&(delete s[e],me(vn,s)),await mt.deleteChatBackups(e);let r=Eo.join(_s,`${e}.json`);if(await Ct.pathExists(r))try{await Ct.remove(r)}catch{}return n}),$d=()=>`flow-${cl(6)}`,Cd=async e=>{if(!e||e==="Never")return;let n=parseInt(e);if(isNaN(n))return;let t=await ls(),o=Date.now(),s=n*24*60*60*1e3,r=0;for(let a in t){let i=t[a];i.updatedAt&&o-i.updatedAt>s&&(await dl(a),r++)}return r},fl=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 h="en";try{h=Intl.DateTimeFormat().resolvedOptions().locale||"en"}catch{}let d=!/^en[-_]?us$|^en$/.test(h?.toLowerCase()),c,l,f;if(i[0]>1e3)c=i[0],l=i[1],f=i[2];else if(i[2]>1e3)c=i[2],i[0]>12?(f=i[0],l=i[1]):i[1]>12?(f=i[1],l=i[0]):d?(f=i[0],l=i[1]):(l=i[0],f=i[1]);else return null;if(l<1||l>12||f<1||f>31)return null;let u=0,p=0,g=0;if(r){let m=r.split(":").map(Number);u=m[0]||0,p=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(c,l-1,f,u,p,g);return isNaN(y.getTime())?null:y.getTime()},ul=async e=>{try{if(!await Ct.pathExists(e))return;let n=await Ct.readFile(e,"utf8");if(!n.trim())return;let t=n.split(`
|
|
203
|
-
`),o=[],s=null,r=/^\s*(?:DEBUG|ERROR|SEARCH|PUPPETEER)\b/i;for(let l of t)r.test(l)?(s&&o.push(s),s={header:l,body:[]}):s?s.body.push(l):o.push({header:l,body:[]});s&&o.push(s);let a=10080*60*1e3,i=Date.now(),h=[],d=/(\d{1,4}[-\/.]\d{1,4}[-\/.]\d{1,4}(?:,\s*|\s+)?(?:\d{1,2}:\d{2}:\d{2}(?:\s*[aApP][mM])?)?)/;for(let l of o){if(r.test(l.header)){let p=l.header.match(d);if(p){let g=fl(p[1]);if(g&&i-g>a)continue}}let u=l.header+(l.body.length>0?`
|
|
204
|
-
`+l.body.join(`
|
|
205
|
-
`):"");h.push(u)}let c=h.join(`
|
|
206
|
-
`).trim();c?await Ct.writeFile(e,c+`
|
|
207
|
-
`,"utf8"):await Ct.writeFile(e,"","utf8")}catch{}},Md=async e=>{try{if(!await Ct.pathExists(e))return;let n=async t=>{let o=await Ct.readdir(t);for(let s of o){let r=Eo.join(t,s);(await Ct.stat(r)).isDirectory()?(await n(r),(await Ct.readdir(r)).length===0&&await Ct.remove(r)):s.endsWith(".log")&&await ul(r)}};await n(e)}catch{}},Li=(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 Ad=async(e,n,t)=>_o(async()=>{let o=Z(Hn,[]);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}),me(Hn,o)}),vd=async e=>{try{if(!await Ct.pathExists(Hn))return{total:0,context:0};let n=Z(Hn,[]);if(!Array.isArray(n))return{total:0,context:0};let t=n.find(o=>Object.keys(o)[0]===String(e));return t?t[String(e)]:{total:0,context:0}}catch{return{total:0,context:0}}};import wt from"fs-extra";import Di from"path";var hl=()=>Math.random().toString(36).substring(2)+Date.now().toString(36),ae=null,qn=null,Pi=0,Ms=!1,In={agent:0,background:0,search:0,toolSuccess:0,toolFailure:0,toolDenied:0,duration:0,tokens:0,cachedTokens:0,candidateTokens:0,linesAdded:0,linesRemoved:0,imageCalls:[]},As=(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},$o=async()=>{let e=new Date().toISOString().split("T")[0];try{!await wt.exists(tn)&&await wt.exists(rr)&&(await wt.ensureDir(Di.dirname(tn)),await wt.move(rr,tn))}catch{}let n=tn+".tmp",t=null;try{if(await wt.exists(n)){let s=(await wt.readFile(n,"utf8")).trim(),r=null;if(s.startsWith("{")||s.startsWith("[")?r=JSON.parse(s):r=JSON.parse($s(s)),r&&r.date&&r.stats){t=r;try{await wt.rename(n,tn)}catch{}}else try{await wt.remove(n)}catch{}}}catch{try{await wt.remove(n)}catch{}}if(!t)try{if(await wt.exists(tn)){let s=(await wt.readFile(tn,"utf8")).trim();s.startsWith("{")||s.startsWith("[")?t=JSON.parse(s):t=JSON.parse($s(s))}}catch{}let o=t;if(o){let s=o.stats||{...In},r={...In,...s};Array.isArray(r.imageCalls)||(r.imageCalls=[]);let a=o.history||{},i=As(a,e);if(Object.keys(a).length!==Object.keys(i).length&&(Ms=!0),o.date===e)return{...o,stats:r,history:i};{let h=o.date,d=r,c={...i};return h&&(c[h]=d),{date:e,stats:{...In},history:As(c,e)}}}return{date:e,stats:{...In},history:{}}},mr=async()=>{if(!(!Ms||!ae))try{await wt.ensureDir(Di.dirname(tn));let e=null;try{if(await wt.exists(tn)){let s=(await wt.readFile(tn,"utf8")).trim();s.startsWith("{")||s.startsWith("[")?e=JSON.parse(s):e=JSON.parse($s(s))}}catch{}if(e&&e.date===ae.date&&e.stats){for(let s in ae.stats)if(e.stats[s]!==void 0){if(Array.isArray(ae.stats[s])){let r=Array.isArray(e.stats[s])?e.stats[s]:[],a=ae.stats[s],i=new Map;for(let h of[...r,...a])h&&h.timestamp&&i.set(h.timestamp,h);ae.stats[s]=Array.from(i.values())}else if(typeof ae.stats[s]=="number")ae.stats[s]=Math.max(ae.stats[s],Number(e.stats[s])||0);else if(ae.stats[s]&&typeof ae.stats[s]=="object"){let r=e.stats[s]||{},a=ae.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 h in r[i])if(typeof r[i][h]=="number")a[i][h]=Math.max(a[i][h]||0,r[i][h]);else if(r[i][h]&&typeof r[i][h]=="object"){a[i][h]||(a[i][h]={});for(let d in r[i][h])a[i][h][d]=Math.max(a[i][h][d]||0,r[i][h][d])}}}}}if(e&&e.history){let s={...ae.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:[],h=Array.isArray(s[r].imageCalls)?s[r].imageCalls:[],d=new Map;for(let c of[...i,...h])c&&c.timestamp&&d.set(c.timestamp,c);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];ae.history=As(s,ae.date||today)}else if(ae&&ae.history){let s=new Date().toISOString().split("T")[0];ae.history=As(ae.history,s)}ae.saveId=hl();let n=tn+".tmp",t=qs(JSON.stringify(ae,null,2));await wt.writeFile(n,t,"utf8");let o=await wt.open(n,"r+");await wt.fsync(o),await wt.close(o),await wt.rename(n,tn),Ms=!1,Pi=Date.now()}catch{}},Co=()=>{if(Ms=!0,qn)return;let e=Date.now(),n=Math.max(0,1500-(e-Pi));qn=setTimeout(async()=>{await mr(),qn=null},n),qn.unref&&qn.unref()},Nd=async()=>{ae=await $o(),Ms&&Co()},Bd=async()=>{qn&&(clearTimeout(qn),qn=null),await mr()},Tn=async()=>{let e=new Date().toISOString().split("T")[0];if(!ae)ae=await $o();else if(ae.date!==e){let n=ae.date,t=ae.stats,o=ae.history||{};t&&(o[n]=t),ae={date:e,stats:{...In},history:As(o,e)},Ms=!0,await mr()}return ae&&ae.stats&&!Array.isArray(ae.stats.imageCalls)&&(ae.stats.imageCalls=[]),ae.stats},pl=async()=>{let e=new Date().toISOString().split("T")[0];ae||(ae=await $o()),ae.date!==e&&await Tn();let n=ae.history||{},t=As(n,e);ae.history=t;let o=ae.stats||{...In},s={...In};s.imageCalls=[],s.models={};let r=(a,i)=>{for(let h in a)if(h==="imageCalls")a.imageCalls=[...a.imageCalls||[],...i.imageCalls||[]];else if(h==="models"){let d=i.models||{};for(let c in d){a.models[c]||(a.models[c]={});for(let l in d[c]){a.models[c][l]||(a.models[c][l]={tokens:0,cachedTokens:0,candidateTokens:0});let f=a.models[c][l],u=d[c][l];f.tokens+=u.tokens||0,f.cachedTokens+=u.cachedTokens||0,f.candidateTokens+=u.candidateTokens||0}}}else typeof a[h]=="number"&&(a[h]+=i[h]||0)};r(s,o);for(let a in t)r(s,t[a]);return s},Lt=async(e,n)=>{e==="toolSuccess"?Xs.toolSuccess++:e==="toolFailure"?Xs.toolFailure++:e==="toolDenied"&&Xs.toolDenied++;let t=await Tn();t[e]!==void 0&&t[e]++,n&&e==="agent"&&(t.providerRequests||(t.providerRequests={}),t.providerRequests[n]=(t.providerRequests[n]||0)+1),Co()},Xs={linesAdded:0,linesRemoved:0,toolSuccess:0,toolFailure:0,toolDenied:0},Yt=async(e,n,t,o)=>{e==="linesAdded"?Xs.linesAdded+=n:e==="linesRemoved"&&(Xs.linesRemoved+=n);let s=await Tn();if(s[e]!==void 0&&(s[e]+=Math.floor(n)),t&&o&&(e==="tokens"||e==="cachedTokens"||e==="candidateTokens")){s.models||(s.models={}),s.models[t]||(s.models[t]={}),s.models[t][o]||(s.models[t][o]={tokens:0,cachedTokens:0,candidateTokens:0});let 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))}Co()},ml=async(e=1)=>{let n=new Date,t=n.toISOString().split("T")[0];ae||(ae=await $o()),ae.date!==t&&await Tn();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],h=ae.history||{},d=ae.stats||{...In},c={...In};c.imageCalls=[],c.models={};let l=(f,u)=>{for(let p in f)if(p==="imageCalls")f.imageCalls=[...f.imageCalls||[],...u.imageCalls||[]];else if(p==="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 w=f.models[y][m],x=g[y][m];w.tokens+=x.tokens||0,w.cachedTokens+=x.cachedTokens||0,w.candidateTokens+=x.candidateTokens||0}}}else typeof f[p]=="number"&&(f[p]+=u[p]||0)};l(c,d);for(let f in h)f>=i&&f<t&&l(c,h[f]);return c},gr=async(e,n={})=>{let t=await Bt().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",h=a&&!!r[i],d=()=>{if(h){let c=r[i];return{agentLimit:typeof c.agentLimit=="number"&&c.agentLimit>0?c.agentLimit:99999999,tokenLimit:typeof c.tokenLimit=="number"&&c.tokenLimit>0?c.tokenLimit:99999999999999,monthlyTokenLimit:typeof c.monthlyTokenLimit=="number"&&c.monthlyTokenLimit>0?c.monthlyTokenLimit:99999999999999}}return{agentLimit:s.agentLimit||99999999,tokenLimit:s.tokenLimit||99999999999999,monthlyTokenLimit:s.monthlyTokenLimit||99999999999999}};if(e==="agent"){let{agentLimit:c,tokenLimit:l,monthlyTokenLimit:f}=d(),u=await Tn(),p;s.resetMode==="Custom"?p=await ml(s.resetDay||1):p=await pl();let g=0,y=0,m=0;if(h){g=u.providerRequests?.[i]||0;let w=u.models?.[i]||{};for(let S in w)y+=w[S]?.tokens||0;let x=p.models?.[i]||{};for(let S in x)m+=x[S]?.tokens||0}else g=u.agent||0,y=u.tokens||0,m=p.tokens||0;return o==="Free"&&u.agent+u.background>=999999?{allowed:!1,reason:"Free Tier Daily Usage Limit Exceeded"}:g>=c?{allowed:!1,reason:h?`Daily Request Limit Reached for ${i}`:"Daily Agent Request Limit Reached"}:y>=l?{allowed:!1,reason:h?`Daily Token Budget Exhausted for ${i}`:"Daily Token Budget Exhausted"}:m>=f?{allowed:!1,reason:h?`Monthly Token Budget Exhausted for ${i}`:"Monthly Token Budget Exhausted"}:{allowed:!0}}if(e==="background"){let c=await Tn();if(o==="Free"&&c.agent+c.background>=999999)return{allowed:!1,reason:"Free Tier Background Limit Exceeded"};let l=c.background<(s.backgroundLimit||999999);return{allowed:l,reason:l?void 0:"Background Request Limit Exceeded"}}if(e==="search"){let l=(await Tn()).search<(s.searchLimit||100);return{allowed:l,reason:l?void 0:"Search Quota Exceeded"}}return{allowed:!0}},Fi=async(e,n={})=>(await gr(e,n)).allowed,yr=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},Ni=(e,n)=>{if(!e||e.length===0)return .025;let o=yr(e);if(o.length===0)return .025;let s=[];for(let l of o){let f=.025;if(s.length>0){let p=s[s.length-1],g=!1;if(s.length>=2){let y=s[s.length-2];p.ratio>=.8&&y.ratio>=.8&&(g=!0)}if(g)f=.015;else{let y=p.limit,m=p.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?l.spent/f:0;s.push({limit:f,spent:l.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,h=s[s.length-1].ratio,d=r.end,c=0;for(let l=s.length-1;l>=0&&s[l].ratio>=.8;l--)c++;for(;d<=n;){let l=.025;c>=2?l=.015:h>=.8?l=i===.015?.015:i:h<.4?l=Math.min(.025,i+.005):h>=.4&&h<.6?l=Math.min(.025,i+.004):l=Math.min(.025,i+.002),i=l,h=0,c=0,d+=36e5,a=l}return a},Bi=async e=>{let n=e.imageSettings||{keyType:"Default",quality:"Low-High"};if(n.keyType!=="Default")return!0;let o={Low:.001,"Low-High":.002,Medium:.008,"Medium-High":.01,High:.045,Ultra:.0488,Premium:.15}[n.quality]||.002,s=await Tn();s.imageCalls||(s.imageCalls=[]);let r=Date.now(),a=yr(s.imageCalls),i=0;if(a.length>0){let d=a[a.length-1];r>=d.start&&r<d.end&&(i=d.spent)}let h=Ni(s.imageCalls,r);return i+o<=h},Ui=async()=>{let e=await Tn();e.imageCalls||(e.imageCalls=[]);let n=Date.now(),t=yr(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=Ni(e.imageCalls,n),i=Math.max(0,a-s),h=s;return{totalSpent:s,remaining:i,activeCallsCount:o.length,nextResetMin:r,reclaimCost:h,limit:a}},Wi=async e=>{let n=e.imageSettings||{keyType:"Default",quality:"Low-High"},o={Low:.001,"Low-High":.002,Medium:.008,"Medium-High":.01,High:.045,Ultra:.0488,Premium:.1}[n.quality]||.002,s=await Tn();s.imageCalls||(s.imageCalls=[]),s.imageCalls.push({timestamp:Date.now(),cost:o}),Co()};import Gi from"puppeteer";import qi from"fs";import zi from"path";import ji from"os";import Js from"path";import vs from"fs";import{createRequire as gl}from"module";import{fileURLToPath as yl}from"url";var wl=gl(import.meta.url),Hi=Js.dirname(yl(import.meta.url));function cs(){let e=ji.platform(),n=ji.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=Js.resolve(Hi,"..","..",".puppeteerrc.cjs");if(vs.existsSync(r)||(r=Js.resolve(Hi,"..",".puppeteerrc.cjs")),!vs.existsSync(r))return{};try{let a=wl(r),i=a.cacheDirectory,h=a.chrome?.version;if(i){if(process.env.PUPPETEER_CACHE_DIR=i,h){let l=Js.join(i,"chrome",`${t}-${h}`,s,o);if(vs.existsSync(l))return{executablePath:l,cacheDirectory:i}}let d=l=>{if(!vs.existsSync(l))return null;try{let f=vs.readdirSync(l),u=[];for(let p of f){let g=Js.join(l,p),y;try{y=vs.statSync(g)}catch{continue}if(y.isDirectory())u.push(g);else if(p.toLowerCase()===o.toLowerCase()&&(!h||g.includes(h)))return g}if(h){for(let p of u)if(p.includes(h)){let g=d(p);if(g)return g}}for(let p of u)if(!h||!p.includes(h)){let g=d(p);if(g)return g}}catch{}return null},c=d(i);if(c)return{executablePath:c,cacheDirectory:i}}}catch{}return{}}var wr=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 h=null;try{let d=cs();h=await Gi.launch({headless:!0,executablePath:d.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let c=await h.newPage();await c.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.178 Safari/537.36"),await c.setViewport({width:1366,height:768});let l=i===1?Math.random()*1e3+500:Math.random()*2e3+1e3;await new Promise(E=>setTimeout(E,l));let f=`https://search.brave.com/ask?q=${encodeURIComponent(a)}&source=web`;await c.goto(f,{waitUntil:"domcontentloaded",timeout:18e4});let u=null,p=45e3,g=Date.now();for(;Date.now()-g<p&&(u=await c.evaluate(()=>{let E=Array.from(document.querySelectorAll('.message:not(.user), .answer-text, .llm-content, [data-type="answer"]')),b="";if(E.length>0&&(b=E.map(X=>X.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():"",B=/^(?:[✓✔]\s*)?Finished/i.test(D)||!!(I&&I.querySelector(".status-finished, .finished")),W=!$&&(B||b.includes("Sources:")&&!$),Y={};return document.querySelectorAll("a[href]").forEach(X=>{let fe=X.getAttribute("href")||X.href||"";if(fe.includes("uddg=")&&(fe=decodeURIComponent(fe.split("uddg=")[1].split("&")[0])),fe.includes("url=")&&(fe=decodeURIComponent(fe.split("url=")[1].split("&")[0])),fe&&(fe.startsWith("http://")||fe.startsWith("https://"))&&!fe.includes("search.brave.com")){let F=X.innerText.trim();F&&(Y[F]=fe),X.textContent=fe}}),{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||{}:{},w="DO NOT INCLUDE ANY TEXT, NOTES, OR EXPLANATIONS AFTER THE SOURCES SECTION.";y.includes(w)&&(y=y.split(w).pop()),y=y.replace(/^.*?(Ctrl \+ Shift \+ O|Ask\nAll\nImages)/s,"").replace(/AI-generated answer\. Please verify critical facts\..*/s,"").replace(/Brave Search uses private usage metrics.*/s,"");let x=y,S="";if(y.includes("Sources:")){let E=y.split("Sources:");x=E[0],S=E.slice(1).join("Sources:")}let C=[];for(let E of x.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(),k=E=>!E||E.includes("search.brave.com")||E.includes("youtube.com")||E.includes("youtu.be"),T="";if(S){let E=S.match(/https?:\/\/[^\s\)\>]+/g)||[],b=[];for(let I of E){let D=I.replace(/[\.\,\;]+$/,""),B=Object.keys(m).find(W=>W.startsWith(D)||D.startsWith(W));B&&m[B]&&(D=m[B]),k(D)||b.push(D)}Object.values(m).forEach(I=>{!k(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 h.close(),`AI Search results for [${n}]:
|
|
233
|
-
|
|
234
|
-
${_}`}catch(d){if(r=d,qi.writeFileSync(zi.join(hn,"web_tools","search","ai_mode","ERROR.txt"),d.message),h&&await h.close(),i<s){let c=Math.pow(2,i)*1e3;await new Promise(l=>setTimeout(l,c))}}}}for(let a=1;a<=s;a++){let i=null;try{let h=cs();i=await Gi.launch({headless:!0,executablePath:h.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 c=a===1?Math.random()*1e3+500:Math.random()*2e3+1e3;await new Promise(g=>setTimeout(g,c));let l=`https://html.duckduckgo.com/html/?q=${encodeURIComponent(n)}`;await d.goto(l,{waitUntil:"networkidle2",timeout:18e4});let f=await d.$$eval(".result",(g,y)=>g.slice(0,y).map((m,w)=>{let x=m.querySelector(".result__a"),S=m.querySelector(".result__snippet"),C=x?x.href:"";C.includes("uddg=")&&(C=decodeURIComponent(C.split("uddg=")[1].split("&")[0]));let R=x?x.innerText.trim():"No Title",k=S?S.innerText.trim():"No Snippet";return`${w+1}. ${R}
|
|
235
|
-
Source: ${C}
|
|
236
|
-
Snippet: ${k}`}),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(h){if(r=h,i&&await i.close(),qi.writeFileSync(zi.join(hn,"web_tools","search","standard_mode","ERROR.txt"),h.message),a<s){let d=Math.pow(2,a)*1e3;await new Promise(c=>setTimeout(c,d))}}}return`ERROR: Search failed after ${s+1} attempts. Last error: ${r.message}`};import xl from"puppeteer";import bl from"turndown";import{gfm as kl}from"turndown-plugin-gfm";var xr=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=cs();a=await xl.launch({headless:!0,executablePath:i.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let h=await a.newPage();await h.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.178 Safari/537.36"),await h.setViewport({width:1366,height:768});let d=r===1?Math.random()*1e3+500:Math.random()*2e3+1e3;await new Promise(g=>setTimeout(g,d)),await h.goto(t,{waitUntil:"networkidle2",timeout:18e4}),await new Promise(g=>setTimeout(g,5e3));let c=await h.evaluate(()=>{document.querySelectorAll("script, style, noscript, svg, canvas, iframe, ad, .ads, link, meta, img").forEach(S=>S.remove());let y=document.createNodeIterator(document.body,NodeFilter.SHOW_COMMENT),m;for(;m=y.nextNode();)m.remove();for(document.querySelectorAll("*").forEach(S=>{let C=S.attributes;for(let R=C.length-1;R>=0;R--){let k=C[R].name;k!=="href"&&k!=="src"&&S.removeAttribute(k)}});document.querySelector("div, span");)document.querySelectorAll("div, span").forEach(S=>{S.parentNode&&S.replaceWith(...S.childNodes)});document.querySelectorAll("br").forEach(S=>{S.replaceWith(document.createTextNode(`
|
|
243
|
-
|
|
244
|
-
`))});let x=()=>{let S=!1;document.querySelectorAll("*").forEach(C=>{C.childNodes.length===0&&!C.innerText.trim()&&(C.remove(),S=!0)}),S&&x()};return x(),document.body.innerHTML});if(!c)throw new Error("EMPTY_RENDER_RESULT");let l=c.replace(/<br\s*\/?>/gi,`
|
|
245
|
-
|
|
246
|
-
`).replace(/[ \t]+/g," ").replace(/>[ \t]+</g,"><").replace(/\n\s+/g,`
|
|
247
|
-
`).replace(/\n{3,}/g,`
|
|
248
|
-
|
|
249
|
-
`).trim(),f=new bl({headingStyle:"atx",codeBlockStyle:"fenced"});f.use(kl);let u=f.turndown(l).replace(/\.\s*\n/g,`
|
|
250
|
-
`).replace(/ +/g," ").replace(/\t/g," ").replace(/\n\s+/g,`
|
|
251
|
-
`).replace(/\n{3,}/g,`
|
|
252
|
-
|
|
253
|
-
`),p=u.substring(0,5e4);return await a.close(),`Markdown parsed from [${t}]:
|
|
254
|
-
|
|
255
|
-
${p}${u.length>5e4?`
|
|
256
|
-
|
|
257
|
-
[TRUNCATED AT 50K CHARS]`:""}`}catch(i){if(s=i,a&&await a.close(),r<o){let h=Math.pow(2,r)*1e3;await new Promise(d=>setTimeout(d,h))}}}return`ERROR: Scrape failed after ${o+1} attempts. Last error: ${s.message}`};var Sl=4*(1024*2),br=async(e,n={})=>{let t=c=>{let l=new RegExp(`${c}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),f=e.match(l);if(f)return f[2].trim();let u=new RegExp(`${c}\\s*[:=]\\s*([^,\\s)]+)`,"s"),p=e.match(u);return p?p[1].trim():null},o=t("action"),s=t("method"),r=t("content"),a=t("content-new"),i=t("content-old"),h=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 c=Z(nn,{});c[d]||(c[d]=[]),c[d].push(r),me(nn,c);let l=c[d].reduce((f,u)=>f+u.length,0);return`SUCCESS: Temporary context saved for session [${d}]. (Size: ${l} chars)`}if(o==="user"){let c=Z(Nt,[]).map(l=>(l.score===void 0&&(l.score=.5),l));if(s==="add"){if(!r)return"ERROR: Missing 'content' for memory addition.";let l=new Date,f=`${l.getDate()}/${l.getMonth()+1}/${l.getFullYear()}`,u=r.includes("[Saved on:")?r:`${r.trim()} [Saved on: ${f}]`,p=Sl,g=c.reduce((x,S)=>x+(S.memory?.length||0),0);for(;c.length>0&&g+u.length>p;){let x=c.shift();g-=x.memory?.length||0}let y=t("score"),m=y?parseFloat(y):.5,w={id:`mem-${Date.now().toString(36)}`,memory:u,score:Math.min(2,isNaN(m)?.5:m)};return c.push(w),me(Nt,c),`SUCCESS: Memory added with ID [${w.id}] and score [${w.score}]. (Vault Size: ${g+u.length} chars)`}if(s==="update"){let l=h||i,f=a||r;if(!l||!f)return"ERROR: Missing 'id' or content for update.";let u=c.findIndex(m=>m.id===l);if(u===-1)return`ERROR: Memory ID [${l}] not found.`;let p=new Date,g=`${p.getDate()}/${p.getMonth()+1}/${p.getFullYear()}`,y=f.includes("[Saved on:")?f:`${f.trim()} [Saved on: ${g}]`;return c[u].memory=y,me(Nt,c),`SUCCESS: Memory [${l}] updated.`}if(s==="delete"){let l=h||r;if(!l)return"ERROR: Missing 'id' for deletion.";let f=c.length,u=c.filter(p=>p.id!==l);return u.length===f?`ERROR: Memory ID [${l}] not found.`:(me(Nt,u),`SUCCESS: Memory [${l}] deleted.`)}return`ERROR: Invalid method [${s}] for user memory. Use 'add', 'update', or 'delete'.`}return`ERROR: Unknown action [${o}] for memory tool.`};var kr=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 Oi(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 Mo from"fs";import Ki from"path";var Qs=async(e,n={})=>{let{path:t,StartLine:o,EndLine:s,start_line:r,end_line:a,startLine:i,endLine:h}=O(e),d=parseInt(o||r||i),c=parseInt(s||a||h),l=!isNaN(d),f=!isNaN(c),u=d||1,p=c||(d?d+800:800);if(!t)return'ERROR: Missing "path" argument for view_file.';let g=Ki.resolve(process.cwd(),t);try{if(!Mo.existsSync(g))return`ERROR: File [${t}] does not exist.`;if(Mo.statSync(g).isDirectory())return`ERROR: Path [${t}] is a directory. Use list_files instead.`;let m=Ki.extname(t).toLowerCase();if([".mp4",".mkv",".avi",".mov",".webm",".flv",".wmv",".mpeg",".mpg"].includes(m))return`ERROR: Unable to read. Type ${m.slice(1).toUpperCase()} not supported`;let x={".pdf":"application/pdf",".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".webp":"image/webp",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".doc":"application/msword"};if(x[m]){if(!(n.isMultiModal!==!1))return`ERROR: Multimodality is not supported for the current model. Unable to load [${t}].`;let D=Mo.readFileSync(g).toString("base64"),B=x[m];return{text:`[BINARY FILE]: ${t} (${B}) - Loaded as multimodal part.`,binaryPart:{inlineData:{data:D,mimeType:B}}}}let S=Mo.readFileSync(g,"utf8");S.startsWith("\uFEFF")&&(S=S.slice(1)),S=S.replace(/\r\n/g,`
|
|
258
|
-
`).replace(/\r/g,`
|
|
259
|
-
`);let C=S.split(`
|
|
260
|
-
`),R=C.length;!l&&!f&&R>800&&(u=1,p=50);let k=Math.max(0,u-1),T=Math.min(R,p),_=C.slice(k,T),E=`File: [${t}] (Showing lines ${k+1}-${T} of ${R}).`,b=_.map(($,I)=>`${String(k+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 Is from"fs";import Yi from"path";var Sr=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=Yi.resolve(process.cwd(),t),r=Yi.dirname(s);try{await mt.recordFileChange(s);let a="";if(Is.existsSync(s))try{a=`Old File contents:
|
|
266
|
-
${Is.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
|
-
`}Is.existsSync(r)||Is.mkdirSync(r,{recursive:!0});let h=(x=>x.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
|
|
272
|
-
`).replace(/\r/g,`
|
|
273
|
-
`))(o),d=h.endsWith(`
|
|
274
|
-
`)?h:h+`
|
|
275
|
-
`,c=d.split(/\r?\n/).length,l=Buffer.byteLength(d,"utf8");Is.writeFileSync(s,d,"utf8");let f=Is.readFileSync(s,"utf8"),u=Buffer.byteLength(f,"utf8"),p=f.split(/\r?\n/),g=p.length;if(u===0&&l>0)return f=null,`ERROR: CRITICAL FAILURE: Verification failed. File [${t}] is empty on disk!`;let y="";if(g<=100)y=p.join(`
|
|
276
|
-
`);else{let x=p.slice(0,50).join(`
|
|
277
|
-
`),S=p.slice(-50).join(`
|
|
278
|
-
`);y=`${x}
|
|
279
|
-
|
|
280
|
-
... [${g-100} lines truncated] ...
|
|
281
|
-
|
|
282
|
-
${S}`}f=null;let{systemSettings:m}=await Bt(),w=`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 x=d.split(/\r?\n/),S=x.slice(0,25).join(`
|
|
287
|
-
`)===p.slice(0,25).join(`
|
|
288
|
-
`),C=x.slice(-25).join(`
|
|
289
|
-
`)===p.slice(-25).join(`
|
|
290
|
-
`);S&&C&&(w=`[[SAME]]
|
|
291
|
-
${w}`)}return w}catch(a){let i=a instanceof Error?a.message:String(a);return`ERROR: Failed to write file [${t}]: ${i}`}};import _r from"fs";import Ll from"path";import Tl from"os";var gn=e=>typeof e!="string"?e:e.length>12?(e+"").replace("",""):e,Vi=(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 h=a.split(/(\s+)/),d="",c=0,l=a.match(/^(\s*)/),f=l?l[1]:"";h.forEach((u,p)=>{if(u.length===0)return;let g=r(u);if(c+g>n)if(d.trim().length>0)s.push(d.trimEnd()),d=f.substring(0,Math.min(f.length,8))+u,c=r(d);else if(t.test(u))s.push(u),d=f,c=r(d);else{let y=u;for(;r(y)>n&&n>10;)s.push(y.substring(0,n)),y=y.substring(n);d=y,c=r(d)}else d+=u,c+=g}),(d.trimEnd().length>0||d===f)&&s.push(d.trimEnd())}),gn(s.join(`
|
|
293
|
-
`))},_f=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=An.replaceAll("\\\\","\\");if(e=e.replace(Tl.homedir(),"~").replace(t,"FluxFlow").replaceAll("\\","/"),!e||e.length<=n)return gn(e);let o=Math.floor((n-3)/2);return gn(e.substring(0,o)+"..."+e.substring(e.length-o).replaceAll("\\","/"))},Ao=e=>{let n=[],t=new Set,o=e.allowMultiple===!0||String(e.allowMultiple).toLowerCase()==="true";Object.keys(e).forEach(h=>{let d=h.match(/^(searchContent|search_content|replaceContent|replace_content|newContent|new_content|content_to_replace|content_to_add|searchBlock|search_block|newBlock|new_block)_?(\d+)?$/i);if(d){let c=d[2]?parseInt(d[2],10):1;t.add(c)}});let s=Array.from(t).sort((h,d)=>h-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=(h,d,c)=>{let l,f;for(let u of d){let p=h===1?[`${u}1`,u,`${u}_1`]:[`${u}${h}`,`${u}_${h}`];for(let g of p)if(e[g]!==void 0){l=e[g];break}if(l!==void 0)break}for(let u of c){let p=h===1?[`${u}1`,u,`${u}_1`]:[`${u}${h}`,`${u}_${h}`];for(let g of p)if(e[g]!==void 0){f=e[g];break}if(f!==void 0)break}return{r:l,n:f}};for(let h of s){let{r:d,n:c}=i(h,r,a);if(d!==void 0&&c!==void 0)n.push({replace:d,new:c});else if(d!==void 0||c!==void 0)return{error:`Mismatched replacement pair for index ${h}. Both replacement and new content must be provided.`,allowMultiple:o}}return{patchPairs:n,allowMultiple:o}},Rl=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}},vo=(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 w=m.split(`
|
|
300
|
-
`).filter(S=>S.trim()!=="");if(w.length===0)return"";let x=a(w[0]);for(let S of w){let C=a(S);C.length<x.length&&(x=C)}return x},h=(m,w,x="")=>{if(!m||w===void 0)return m;let C=/^\t/m.test(w)?" ":" ",R=$=>$.split(`
|
|
301
|
-
`).find(I=>I.trim()!=="")??"",k=R(w).match(/^\s*/)[0].length,T=R(m).match(/^\s*/)[0].length,_=k-T,E=(x.match(/^\s*/)||[""])[0].length;return m.split(`
|
|
302
|
-
`).map(($,I)=>{if($.trim()===""&&I!==0)return"";let D=$.match(/^\s*/)[0].length,B=Math.max(0,D+_);return I===0&&(B=Math.max(0,B-E)),C.repeat(B)+$.trimStart()}).join(`
|
|
303
|
-
`)},d=[];for(let m=0;m<n.length;m++){let w=n[m],x=(w.replace||"").trim(),S=r(w.new||"");if(x.startsWith("^LINE:")&&x.endsWith("$")){let E=x.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 B=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:B,content_to_add:S});continue}}let C=r(w.replace||"");if(C===""&&S===""){d.push({index:m,success:!1,error:`Block ${m+1}: Empty replace and add content.`});continue}let R=C.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),k=null;if(C!==""&&s.includes(C))k=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{k=new RegExp(E,"g")}catch{k=new RegExp(R,"g")}}else k=new RegExp(R,"g")}let T=[...s.matchAll(k)];if(T.length===0&&C!==""){let _=Rl(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:S})}let c=d.filter(m=>m.success).sort((m,w)=>m.startPos-w.startPos);for(let m=0;m<c.length-1;m++){let w=c[m],x=c[m+1];w.startPos+w.firstMatchContent.length>x.startPos&&(w.success=!1,w.error=`Block ${w.index+1}: Overlaps with another block.`,x.success=!1,x.error=`Block ${x.index+1}: Overlaps with another block.`)}let l=new Map,f=s,u=0,p=0,g=d.filter(m=>m.success).sort((m,w)=>m.startPos-w.startPos);for(let m of g){let w=m.startPos,x=s.substring(0,w).split(`
|
|
307
|
-
`).length,S=w+u,C=x+p,R=f.lastIndexOf(`
|
|
308
|
-
`,S)+1,k=f.substring(R,S),T=h(m.content_to_add,m.firstMatchContent,k),_=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]});l.set(m,{success:!0,index:m.index,oldContent:m.firstMatchContent,newContent:T,originalStartLine:x,finalStartLine:C,contextBefore:E,contextAfter:$}),f=f.substring(0,S)+T+f.substring(S+m.firstMatchContent.length),u+=T.length-m.firstMatchContent.length,p+=T.split(`
|
|
311
|
-
`).length-m.firstMatchContent.split(`
|
|
312
|
-
`).length}let y=[];for(let m=0;m<n.length;m++){let w=g.filter(x=>x.index===m);if(w.length>0)for(let x of w)l.has(x)&&y.push(l.get(x));else{let x=d.find(S=>S.index===m);y.push({success:!1,error:x?x.error:`Block ${m+1}: Unknown error.`})}}return{content:f,results:y}},Io=(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),h=Math.max(4,String(i).length),d=g=>String(g).padStart(h," "),c=`[DIFF_START]
|
|
313
|
-
`,l="\u2550".repeat(88),f=0,u=null,p=t.filter(g=>g.success).sort((g,y)=>g.originalStartLine-y.originalStartLine);if(p.forEach((g,y)=>{let m=g.finalStartLine!==void 0?g.finalStartLine:g.originalStartLine;if(u===null)for(f=Math.max(0,m-4);f<m-1;)c+=`[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;)c+=`[UI_CONTEXT] ${d(f+1)} |${a[f]||""}
|
|
316
|
-
`,f++;for(c+=`[UI_CONTEXT] ${l}
|
|
317
|
-
`,f=Math.max(f,m-4);f<m-1;)c+=`[UI_CONTEXT] ${d(f+1)} |${a[f]||""}
|
|
318
|
-
`,f++}else for(;f<m-1;)c+=`[UI_CONTEXT] ${d(f+1)} |${a[f]||""}
|
|
319
|
-
`,f++}let w=g.originalStartLine-1,x=r[w]||"",S=g.oldContent.split(`
|
|
320
|
-
`),C=x.match(/^\s*/),R=C?C[0]:"";S.forEach((T,_)=>{let E=T;if(S.length===1&&x.trim().length>0&&x.includes(T.trim()))E=x;else if(_===0){let b=T.match(/^\s*/);(b?b[0]:"").length<R.length&&x.includes(T.trim())&&(E=R+T.trimStart())}c+=`-${d(g.originalStartLine+_)} |${E}
|
|
321
|
-
`});let k=f;if(g.finalStartLine!==void 0)k=g.finalStartLine-1+(g.newContent?g.newContent.split(`
|
|
322
|
-
`).length:0);else{let T=g.originalStartLine+S.length-1,_=r[T]||null;if(_!==null){let E=y<p.length-1?(p[y+1].originalStartLine||a.length)+10:a.length;for(let b=f;b<E;b++){if(a[b]===_){k=b;break}b===a.length-1&&(k=a.length)}}else k=a.length}for(;f<k;)c+=`+${d(f+1)} |${a[f]||""}
|
|
323
|
-
`,f++;u=g}),u!==null){let g=Math.min(a.length,f+3);for(;f<g;)c+=`[UI_CONTEXT] ${d(f+1)} |${a[f]||""}
|
|
324
|
-
`,f++}if(s){let g=`[DIFF_START]
|
|
325
|
-
`,y=c.substring(g.length),m=`[UI_CONTEXT] ${l}
|
|
326
|
-
`,x=y.split(m).map(S=>S.split(`
|
|
327
|
-
`).filter(R=>R.trim()!=="").length>45?`[[VERIFIED]]
|
|
328
|
-
${S}
|
|
329
|
-
[[/VERIFIED]]`:S);c=g+x.join(m)}return c+="[DIFF_END]",gn(c)},El=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?gn(s.substring(0,r).trim()):"",i=gn(r!==-1?s.substring(r+1):s);return{isR:t,isA:o,num:a,content:i}},_l=(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,h=new Int32Array(i+1),d=new Int32Array(i+1);for(let f=0;f<=i;f++)h[f]=f;for(let f=1;f<=a;f++){d[0]=f;let u=s[f-1];for(let p=1;p<=i;p++)u===r[p-1]?d[p]=h[p-1]:d[p]=Math.min(h[p],d[p-1],h[p-1])+1;h.set(d)}let c=h[i],l=Math.max(t,o);return l===0?1:1-c/l},Xi=e=>{let n=[],t=[];e.forEach((c,l)=>{c.parsed.isR?n.push({index:l,content:c.parsed.content}):c.parsed.isA&&t.push({index:l,content:c.parsed.content})});let o=n.length,s=t.length;if(o===0||s===0)return;let r=Array.from({length:o+1},()=>Array(s+1).fill(0)),a=Array.from({length:o+1},()=>Array(s+1).fill(""));for(let c=1;c<=o;c++)a[c][0]="up";for(let c=1;c<=s;c++)a[0][c]="left";let i=Array.from({length:o},()=>Array(s).fill(0));for(let c=0;c<o;c++)for(let l=0;l<s;l++)i[c][l]=_l(n[c].content.trim(),t[l].content.trim());for(let c=1;c<=o;c++)for(let l=1;l<=s;l++){let f=i[c-1][l-1],u=f>=.2?f:-10,p=r[c-1][l-1]+u,g=r[c-1][l],y=r[c][l-1];p>=g&&p>=y?(r[c][l]=p,a[c][l]="diag"):g>=y?(r[c][l]=g,a[c][l]="up"):(r[c][l]=y,a[c][l]="left")}let h=o,d=s;for(;h>0||d>0;)if(a[h][d]==="diag"){if(i[h-1][d-1]>=.2){let l=n[h-1].index,f=t[d-1].index;e[l].pairContent=e[f].parsed.content,e[f].pairContent=e[l].parsed.content}h--,d--}else a[h][d]==="up"?h--:d--},zn=new Map,ds=new Map,Ji=200,Tr=6,Er=(e,n)=>{n.set(e.key,e),e.type==="chunk"&&e.blocks&&e.blocks.forEach(t=>Er(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&&zn.has(t))return zn.get(t);let o=gn(Ol(e.text||"",e.role==="think")),s=`${e.id}-${n}`,r=new Map;if(e.isStreaming){let p=ds.get(s);p&&o.startsWith(p.text)&&(r=p.blocksMap)}let a=(p,g,y,m={})=>{let w=r.get(p);if(w&&w.text===y&&w.type===g&&!!w.isActiveBlock==!!m.isActiveBlock&&!!w.isStreaming==!!m.isStreaming&&w.pairContent===m.pairContent)return w;let x=gn(y),S={...m};return typeof S.pairContent=="string"&&(S.pairContent=gn(S.pairContent)),Array.isArray(S.wrappedLines)&&(S.wrappedLines=S.wrappedLines.map(gn)),{key:p,isStreamingMsg:!!e.isStreaming,workedDuration:e.workedDuration,type:g,text:x,msg:g==="full-message"?e:void 0,...S}};if(o.includes("- Content Preview:")){let p="",g=o.match(/File\s+\[(.*?)\]/i);g&&(p=g[1].split(".").pop().toLowerCase());let S=((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(S.length).length,R=[],k=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 S.forEach((b,$)=>{let I=$===S.length-1,D=Vi(b,E).split(`
|
|
331
|
-
`),B=a(`${e.id||Date.now()}-write-line-${$}`,"write-line",b,{gutterWidth:C,lineNum:$+1,isFirstLine:$===0,isLastLine:I,extension:p,wrappedLines:D});I&&e.isStreaming?(_(),k=B):(T.push(B),T.length>=Tr&&_())}),_(),{completed:R,active:k?[k]:[]}}if(o.includes("[DIFF_START]")){let p=o.match(/\[DIFF_START\]([\s\S]*?)(?:\[DIFF_END\]|$)/),y=(p?p[1].trim():"").split(`
|
|
332
|
-
`).map(k=>k.replace(/\r$/,"")),m=y.map(k=>({line:k,parsed:El(k),pairContent:null})),w=[];for(let k=0;k<m.length;k++){let T=m[k];T.parsed&&(T.parsed.isR||T.parsed.isA)?w.push(T):w.length>0&&(Xi(w),w=[])}w.length>0&&Xi(w);let x=[],S=null,C=[],R=()=>{if(!C.length)return;let k=C;C=[],x.push(k.length===1?k[0]:{key:`${k[0].key}-chunk`,type:"chunk",blocks:k})};return y.forEach((k,T)=>{let _=T===y.length-1,E=m[T].parsed,b=null;E&&(b=Vi(E.content,n-17).split(`
|
|
333
|
-
`));let $=a(`${e.id||Date.now()}-diff-${T}`,"diff-line",k,{isFirstLine:T===0,isLastLine:_,pairContent:m[T].pairContent,wrappedLines:b});_&&e.isStreaming?(R(),S=$):(C.push($),C.length>=Tr&&R())}),R(),{completed:x,active:S?[S]:[]}}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 p={completed:[],active:[]};return zn.set(t,p),p}let i=[],h=null,d=[],c=null,l=()=>{if(!d.length)return;let p=d;d=[],c=null,i.push(p.length===1?p[0]:{key:`${e.id||"x"}-chunk-${p[0].key}`,type:"chunk",blocks:p})},f=(p,g=!1)=>{if(c!==null&&c!==p.type&&l(),d.push(p),c=p.type,d.length>=Tr){if(e.isStreaming&&g)return;l()}};if(e.role==="think"){i.push(a(`${e.id}-header`,"think-header",""));let p=o.split(`
|
|
334
|
-
`);p.forEach((g,y)=>{let m=y===p.length-1;f(a(`${e.id}-${y}`,"think-line",g,{}),m)}),e.isStreaming||(l(),i.push({key:`${e.id}-footer-padding`,type:"think-footer-padding",text:""}))}else{let p=o.split(`
|
|
335
|
-
`),g=!1,y=[],m=!1,w=!1,x="",S=0,C=0;p.forEach((R,k)=>{let T=k===p.length-1,_=R.trim().startsWith("|"),E=R.trim().startsWith("```");if(w){if(R.includes("</think>")||R.includes("<channel|>")||R.includes("</thought>")){let b=R.split(/(?:<\/(think|thought|thoughts)>|<channel\|>)/i),$=b[0]||"",I=b.slice(2).join("");$&&f(a(`${e.id}-think-${k}`,"think-line",$,{}),T&&!I),l(),i.push({key:`${e.id}-think-footer-${k}`,type:"think-footer-padding",text:""}),w=!1,I&&I.trim()&&f(a(`${e.id}-${k}`,"agent-line",I,{}),T)}else f(a(`${e.id}-think-${k}`,"think-line",R,{}),T);return}if(!m&&(R.includes("<think>")||R.includes("<|channel>thought")||R.includes("<thought>")||R.startsWith("<think")||R.startsWith("<|channel>thought"))){l(),g&&(i.push(a(`${e.id}-table-${k}`,"table",y.join(`
|
|
336
|
-
`),{isStreaming:!1})),g=!1,y=[]),i.push(a(`${e.id}-think-header-${k}`,"think-header","")),w=!0;let b=R.replace(/^(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought\s*)\r?\n?/i,"");if(b.includes("</think>")||b.includes("<channel|>")||b.includes("</thought>")){let $=b.split(/(?:<\/(think|thought|thoughts)>|<channel\|>)/i),I=$[0]||"",D=$.slice(2).join("");I&&f(a(`${e.id}-think-${k}`,"think-line",I,{}),T&&!D),l(),i.push({key:`${e.id}-think-footer-${k}`,type:"think-footer-padding",text:""}),w=!1,D&&D.trim()&&f(a(`${e.id}-${k}`,"agent-line",D,{}),T)}else b&&f(a(`${e.id}-think-${k}`,"think-line",b,{}),T);return}m?E?(m=!1,f(a(`${e.id}-code-close-${C}`,"code-fence-close","",{}),T)):(S++,f(a(`${e.id}-code-line-${k}`,"code-line",R,{lineNum:S,lang:x}),T)):E?(m=!0,C=k,S=0,x=R.trim().replace(/^```/,"").trim(),f(a(`${e.id}-code-open-${k}`,"code-fence-open",x,{}),T)):_?(g=!0,y.push(R),T&&(l(),e.isStreaming?h=a(`${e.id}-table-${k}`,"table",y.join(`
|
|
337
|
-
`),{isStreaming:!0}):i.push(a(`${e.id}-table-${k}`,"table",y.join(`
|
|
338
|
-
`),{isStreaming:!1})))):(g&&(l(),i.push(a(`${e.id}-table-${k}`,"table",y.join(`
|
|
339
|
-
`),{isStreaming:!1})),g=!1,y=[]),f(a(`${e.id}-${k}`,"agent-line",R,{}),T))}),!e.isStreaming&&e.workedDuration&&(l(),i.push(a(`${e.id}-worked-duration`,"worked-duration","")))}e.isStreaming&&d.length>0?h=d.length===1?d[0]:{key:`${e.id||"x"}-chunk-active-${d[0].key}`,type:"chunk",blocks:d}:l();let u={completed:i,active:h?[h]:[]};if(e.isStreaming){let p=new Map;if(i.forEach(g=>Er(g,p)),h&&Er(h,p),ds.set(s,{text:o,blocksMap:p}),ds.size>Ji){let g=ds.keys().next().value;ds.delete(g)}}else{if(zn.set(t,u),zn.size>Ji){let p=zn.keys().next().value;zn.delete(p)}ds.delete(s)}return u},$l={},Cl=/<\/think>(\r?\n){2}/gi,Ml=/(\r?\n){2}(?=\[?(?:tool:functions|tool\.functions|agent:generalist|agent\.generalist|\s*turn\s*:))/gi,Rr=(e,n)=>{let t=!1;for(let o=0;o<n;o++)e[o]==="`"&&(t=!t);return t},Al=/\[SYSTEM\][\s\S]*?\[\/SYSTEM\]|(?:<(think|thought|thoughts)>|<\|channel>thought)[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>)|\[ANSWER\][\s\S]*?(?:\[\/ANSWER\]|$)|\[TOOL RESULT\]:?\s*|^\s*(SUCCESS|ERROR):.*(\r?\n)?|\[\s*turn\s*:\s*(continue|finish)\s*\]|\[\[END\]\]|\[\s*turn\s*:?.*?$|\n\s*turn\s*:?.*?$|\[\s*(?:turn|ANSWER|TOOL).*?$|\n\nResponded on .*|\n\n\[Prompted on: .*\]|@\[TerminalName:.*?, ProcessId:.*?\]/gm,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,Os=!1,Ol=(e,n=!1)=>{if(!e)return e;let t=e.replace(/<\|channel>thought/gi,"<think>").replace(/<channel\|>/gi,"</think>");if(n)return t.replace(/^<(think|thought|thoughts)>/gi,"").replace(/<\/(think|thought|thoughts)>$/gi,"").replace(/^\r?\n+/,"").replace(/\r?\n+$/,"");let o=t.replace(Cl,"</think>").replace(Ml,(a,i,h,d)=>!Os&&Rr(d,h)?a:"");o&&o.includes("[tool:")&&(o=o.replace(/<(\w+)(?:[^>]*)>\s*([\s\S]*?\[tool:[^\]]*\][\s\S]*?)\s*<\/\1>/gi,(a,i,h)=>h&&h.includes("[tool:")?h.trim():a),Os&&(o=o.replace(/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi,(a,i)=>i.includes("[tool:")?i.trim():a)));let s="tool:functions.",r="agent:generalist.";if(o.toLowerCase().includes(s)||o.toLowerCase().includes(r))for(;;){let a=o.toLowerCase(),i=a.indexOf(s),h=a.indexOf(r),d=s,c=i;if((i===-1||h!==-1&&h<i)&&(d=r,c=h),c===-1)break;if(!Os&&Rr(o,c)){let w=c+d.length,x=a.indexOf(s,w),S=a.indexOf(r,w);if(x===-1&&S===-1)break;let C=-1,R=0;for(;;){let k=a.indexOf(s,R),T=a.indexOf(r,R),_=-1,E=s;if(k===-1&&T===-1)break;if(k===-1||T!==-1&&T<k?(_=T,E=r):_=k,!Rr(o,_)){C=_,d=E;break}R=_+E.length}if(C===-1)break;c=C}let l=c,f=!1,u=c-1;for(;u>=0&&/\s/.test(o[u]);)u--;u>=0&&o[u]==="["&&(l=u,f=!0);let p=0,g=!1,y=null,m=c;for(;m<o.length;){let w=o[m];if(!y&&(w==="'"||w==='"'||w==="`")?y=w:y&&w===y&&o[m-1]!=="\\"&&(y=null),y||(w==="("?(p++,g=!0):w===")"&&p--),g&&p===0&&!y){let x=m;if(f){let S=m+1;for(;S<o.length&&/\s/.test(o[S]);)S++;S<o.length&&o[S]==="]"&&(x=S)}o=o.substring(0,l)+o.substring(x+1);break}if(m++,m===o.length)return g&&p>0&&(o=o.substring(0,l)),o}}return o=o.replace(Al,""),o=o.replace(vl,a=>{let i=a.toLowerCase();return i.includes("leftrightarrow")?"\u2194":i.includes("rightarrow")?"\u2192":i.includes("leftarrow")?"\u2190":i.includes("uparrow")?"\u2191":i.includes("downarrow")?"\u2193":a}),o=o.replace(Il,a=>$l[a.toLowerCase()]||a),o.trim()},Mf=()=>{zn.clear(),ds.clear()};var $r=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}=Ao(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,h=Ll.resolve(process.cwd(),o);try{if(!_r.existsSync(h))return`ERROR: File [${o}] does not exist. Use WriteFile instead.`;let d=n.forcedContent||_r.readFileSync(h,"utf8");d.startsWith("\uFEFF")&&(d=d.slice(1));let c=d.replace(/\r\n/g,`
|
|
340
|
-
`).replace(/\r/g,`
|
|
341
|
-
`),{content:l,results:f}=vo(c,s,{allowMultiple:i}),u=f.filter(m=>!m.success),p=f.filter(m=>m.success);if(p.length===0)return`ERROR: Patch Failed to apply to [${o}].
|
|
342
|
-
${u.map(m=>` \u2022 ${m.error}`).join(`
|
|
343
|
-
`)}`;await mt.recordFileChange(h,c),_r.writeFileSync(h,l,"utf8");let{systemSettings:g}=await Bt(),y=Io(c,l,f,12,g?.compressToolResults);return u.length>0?`SUCCESS: File [${o}] updated with some blocks failed. [${p.length}/${s.length}] blocks applied.
|
|
344
|
-
|
|
345
|
-
Failures:
|
|
346
|
-
${u.map(m=>` \u2022 ${m.error}`).join(`
|
|
347
|
-
`)}
|
|
348
|
-
|
|
349
|
-
${y}`:`SUCCESS: File [${o}] updated. [${f.length}/${s.length}] blocks applied.
|
|
350
|
-
|
|
351
|
-
${y}`}catch(d){let c=d instanceof Error?d.message:String(d);return`ERROR: Failed to update file [${o}]: ${c}`}};import fs from"fs";import Cr 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"}},Mr=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=Cr.resolve(process.cwd(),t);try{if(!fs.existsSync(s))return`ERROR: Path [${t}] does not exist.`;if(!fs.statSync(s).isDirectory())return`ERROR: Path [${t}] is a file, not a directory. Use ReadFile instead.`;if(o===1){let g=fs.readdirSync(s),y=g.length,m=150,w=g.slice(0,m),x=[];for(let R of w){let k=Cr.join(s,R),T={name:R,type:"unknown",size:"N/A",mtime:"N/A"};try{let _=fs.statSync(k);T={name:R,type:_.isDirectory()?"directory":"file",size:(_.size/1024).toFixed(1)+"KB",mtime:Fl(_.mtime)}}catch{T.type="inaccessible"}x.push(T)}let S=x.map(R=>R.type==="directory"?`${R.name}/`:`${R.name} (${R.size}, ${R.mtime})`).join(`
|
|
352
|
-
`),C=`
|
|
353
|
-
|
|
354
|
-
(Total items in folder: ${y})`;return y>m&&(C=`
|
|
355
|
-
|
|
356
|
-
TRUNCATED: Showing first ${m} of ${y} items.`),g.length=0,w.length=0,x.length=0,`Detailed folder stats for [${t}]:
|
|
357
|
-
|
|
358
|
-
${S}${C}`}let a=0,i=0,h=0,d=500,c=!1,l=(g,y,m=1)=>{if(y>o||c)return[];let w=[];try{w=fs.readdirSync(g)}catch{return[`${" ".repeat(m-1)}[Inaccessible Directory]`]}let x=[],S=[];for(let T of w){let _=Cr.join(g,T),E=!1;try{E=fs.statSync(_).isDirectory()}catch{}E?x.push({name:T,fullPath:_}):S.push({name:T,fullPath:_})}x.sort((T,_)=>T.name.localeCompare(_.name)),S.sort((T,_)=>T.name.localeCompare(_.name));let C=[],R=" ".repeat(m-1);for(let T of x){if(h>=d){c=!0,C.push(`${R}[Truncated - Maximum item limit reached (${d})]`);break}if(h++,a++,C.push(`${R}${T.name}/`),y<o&&!Pl(T.name)){let _=l(T.fullPath,y+1,m+1);C.push(..._)}}let k=[];for(let T of S){if(h>=d){c=!0,C.push(`${R}[Truncated - Maximum item limit reached (${d})]`);break}h++,i++;let _="N/A";try{_=(fs.statSync(T.fullPath).size/1024).toFixed(1)+"KB"}catch{}k.push(`${T.name} (${_})`)}return k.length>0&&C.push(`${R}${k.join("; ")}`),C},u=l(s,1,1).join(`
|
|
359
|
-
`),p=`
|
|
360
|
-
|
|
361
|
-
(Total items scanned: ${h}, Directories: ${a}, Files: ${i})`;return c&&(p=`
|
|
362
|
-
|
|
363
|
-
TRUNCATED: Scan capped at ${d} items. (Directories: ${a}, Files: ${i})`),`Detailed directory tree for [${t}] (recursive depth: ${o}):
|
|
364
|
-
|
|
365
|
-
${u}${p}`}catch(r){let a=r instanceof Error?r.message:String(r);return`ERROR: Failed to read folder [${t}]: ${a}`}};var Ar=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,h]=a.split("::");s.push({id:r,label:i.trim(),description:h.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 Ls from"path";import us from"fs-extra";import{PDFDocument as Bl}from"pdf-lib";var vr=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=Ls.resolve(process.cwd(),n),a=null;try{await us.ensureDir(Ls.dirname(r)),await mt.recordFileChange(r);let i=cs();a=await Nl.launch({headless:!0,executablePath:i.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let h=await a.newPage(),d=t,c={},l=async k=>{if(!k||k.startsWith("http://")||k.startsWith("https://")||k.startsWith("data:"))return null;try{let T=Ls.resolve(process.cwd(),k);if(await us.pathExists(T)){let _=Ls.extname(T).toLowerCase().replace(".","")||"png",E=_==="jpg"?"jpeg":_==="svg"?"svg+xml":_,b=await us.readFile(T,"base64");return`data:image/${E};base64,${b}`}}catch{}return null},f=/<link[^>]+href=["']([^"']+)["']/gi,u={},p;for(;(p=f.exec(t))!==null;){let k=p[1],T=p[0];if(k&&T.toLowerCase().includes("stylesheet")&&!k.startsWith("http://")&&!k.startsWith("https://")&&!k.startsWith("data:"))try{let _=Ls.resolve(process.cwd(),k);if(await us.pathExists(_)){let E=await us.readFile(_,"utf-8");u[T]=`<style>${E}</style>`}}catch{}}for(let[k,T]of Object.entries(u))d=d.split(k).join(T);let g=/<img[^>]+src=["']([^"']+)["']/gi;for(;(p=g.exec(d))!==null;){let k=p[1];if(k&&!c[k]){let T=await l(k);T&&(c[k]=T)}}let y=/url\(\s*['"]?([^'")]+?)['"]?\s*\)/gi;for(;(p=y.exec(d))!==null;){let k=p[1].trim();if(k&&!c[k]){let T=await l(k);T&&(c[k]=T)}}for(let[k,T]of Object.entries(c)){let _=k.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=`
|
|
366
|
-
<style>
|
|
367
|
-
@page {
|
|
368
|
-
margin: ${s};
|
|
369
|
-
}
|
|
370
|
-
body {
|
|
371
|
-
margin: 0;
|
|
372
|
-
padding: 0;
|
|
373
|
-
font-family: system-ui, -apple-system, sans-serif;
|
|
374
|
-
}
|
|
375
|
-
* { box-sizing: border-box; }
|
|
376
|
-
.watermark {
|
|
377
|
-
position: fixed;
|
|
378
|
-
top: 50%;
|
|
379
|
-
left: 50%;
|
|
380
|
-
transform: translate(-50%, -50%) rotate(-50deg);
|
|
381
|
-
font-size: 52px;
|
|
382
|
-
font-weight: bold;
|
|
383
|
-
color: rgba(0, 0, 0, 0.005);
|
|
384
|
-
pointer-events: none;
|
|
385
|
-
z-index: -1000;
|
|
386
|
-
text-align: center;
|
|
387
|
-
width: 150%;
|
|
388
|
-
white-space: nowrap;
|
|
389
|
-
text-transform: uppercase;
|
|
390
|
-
letter-spacing: 5px;
|
|
391
|
-
}
|
|
392
|
-
</style>
|
|
393
|
-
<div class="watermark">Generated by FluxFlow CLI (AI)</div>
|
|
394
|
-
${d}
|
|
395
|
-
`;await h.setContent(m,{waitUntil:"networkidle0",timeout:18e4});let w=await h.pdf({format:"A4",landscape:String(o).toLowerCase()==="landscape",margin:{top:s,right:s,bottom:s,left:s},printBackground:!0}),x=await Bl.load(w),S=Ls.basename(n);x.setTitle(`FluxFlow_${S}`),x.setAuthor("FluxFlow CLI"),x.setSubject("Generated with Agentic AI System"),x.setKeywords(["FluxFlow","AI","Agentic","Automated"]),x.setCreator("FluxFlow PDF Engine"),x.setProducer("FluxFlow (Generative AI)");let C=await x.save();await us.writeFile(r,C);let R=await us.stat(r);return`SUCCESS: PDF generated successfully at [${n}] (${(R.size/1024).toFixed(2)} KB).`}catch(i){let h=i instanceof Error?i.message:String(i);return`ERROR: Failed to generate PDF [${n}]: ${h}`}finally{a&&await a.close()}};import Qi from"fs-extra";import Ir from"path";import Ul from"html-to-docx";var Or=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=Ir.resolve(process.cwd(),n);try{await Qi.ensureDir(Ir.dirname(o)),await mt.recordFileChange(o);let s=Ir.basename(n),r=t.includes("<html")?t:`
|
|
396
|
-
<!DOCTYPE html>
|
|
397
|
-
<html lang="en">
|
|
398
|
-
<head>
|
|
399
|
-
<meta charset="UTF-8">
|
|
400
|
-
<title>FluxFlow Document</title>
|
|
401
|
-
</head>
|
|
402
|
-
<body>
|
|
403
|
-
${t}
|
|
404
|
-
</body>
|
|
405
|
-
</html>
|
|
406
|
-
`,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 Qi.writeFile(o,a),`SUCCESS: Word document [${n}] generated successfully.
|
|
407
|
-
- 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 Dr from"fs/promises";import hs from"path";import Lr from"fast-glob";import{Minimatch as Zi}from"minimatch";async function Zs(e,n,t=e,o=1){if(o>12)return[];let s=[],r;try{r=await Dr.readdir(e,{withFileTypes:!0})}catch{return[]}for(let a of r){let i=hs.join(e,a.name),h=hs.relative(t,i),d=h.split(hs.sep).map(f=>f.toLowerCase()),c=a.name.toLowerCase();if(!n.some(f=>{let u=f.toLowerCase();return u.startsWith(".")&&c.endsWith(u)?!0:d.some(p=>p===u||p.startsWith(".pnpm"))}))if(a.isDirectory()){let f=await Zs(i,n,t,o+1);s=s.concat(f)}else a.isFile()&&s.push({fullPath:i,relativePath:h})}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 h=e[s-1]===n[i-1]?0:1,d=Math.min(r[i-1]+1,o[i]+1,o[i-1]+h);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 h of s)if(h.includes(a)||a.length>=3&&h.length>=3&&Math.abs(h.length-a.length)<=i&&Wl(a,h,i)<=i)return!0;return!1})}var eo=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",h=r===!1||r==="false"||r===0||r==="0"||r==="no",d=r===!0||r==="true"||r===1||r==="1"||r==="yes",c=i(o)||i(s),l=null,f=null;if(h)c||(f=new RegExp(`(?<![\\w])${a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\\w])`,"i"));else{try{l=new RegExp(a,"i")}catch(g){if(d)return`ERROR: Invalid regex pattern "${a}": ${g.message}`}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"],p=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=>Lr.isDynamicPattern(W)||/[*?{}[\]()|+]/.test(W))){m="glob";let W=t.replace(/\\/g,"/"),Y=I.map(F=>F.replace(/\\/g,"/")),X=u.map(F=>F.startsWith(".")?`**/*${F}`:`**/${F}/**`);if(D&&!I.some(F=>!F.startsWith("!"))){let F=await Zs(y,u,y),U=A=>A.endsWith("/")?A+"**":A,se=Y.filter(A=>A.startsWith("!")).map(A=>U(A.slice(1))),Ae=Y.filter(A=>!A.startsWith("!")).map(U);g=F.filter(A=>{let N=A.relativePath.replace(/\\/g,"/"),V=Ae.length===0||Ae.some(Ue=>{try{return new Zi(Ue).match(N)}catch{return!1}}),J=se.some(Ue=>{try{return new Zi(Ue).match(N)}catch{return!1}});return V&&!J})}else{let F=Y.some(se=>/[\(\)\|]|\.\*/.test(se)),U=[];if(!F)try{U=await Lr(Y,{cwd:y,ignore:X,dot:!0,onlyFiles:!0,absolute:!1})}catch{U=[]}if(U.length===0&&(F||Lr.isDynamicPattern(W))){let se=W.match(/^([^\*\?\(\)\|\[\]\s]+)\//),Ae=se&&!/[\*\?\(\)\|\[\]]/.test(se[1])?hs.resolve(y,se[1]):y,A=await Zs(Ae,u,y);try{let N=W.replace(/^\.\//,"");N=N.replace(/\.\*\/(\\.|[^\/])/g,".*$1"),!N.startsWith("^")&&!N.startsWith(".*")&&(N=`.*${N}`);let V=new RegExp(N.endsWith("$")?N:`${N}$`,"i");g=A.filter(J=>{let Ue=J.relativePath.replace(/\\/g,"/");return V.test(Ue)})}catch{g=[]}}else g=U.map(se=>({fullPath:hs.resolve(y,se),relativePath:se}))}}else{let W=t.replace(/[\/\\]+$/,""),Y=hs.resolve(y,W);try{let X=await Dr.stat(Y);if(X.isDirectory())m="dir",g=await Zs(Y,u,y);else if(X.isFile())m="file",g.push({fullPath:Y,relativePath:hs.relative(y,Y)});else return`ERROR: Path is neither a file nor a directory: ${t}`}catch{return`ERROR: Path not found: ${t}`}}}else g=await Zs(y,u);let w=g.map(async I=>{try{let D=await Dr.readFile(I.fullPath,"utf-8");if(D.includes("\0"))return[];let B=D.split(/\r?\n/),W=[];for(let X=0;X<B.length;X++)(c?B[X].toLowerCase().includes(a.toLowerCase())||jl(B[X],a):h?f&&f.test(B[X]):l&&l.test(B[X])||f&&f.test(B[X]))&&W.push({line:X+1,content:B[X].trim()});return W.length===0?null:{path:I.relativePath.replace(/\\/g,"/"),matches:W}}catch{return[]}}),x=await Promise.all(w),S=[],C=0;for(let I of x){if(!I||!I.matches)continue;if(C>=p)break;let D=p-C,B=I.matches.slice(0,D);S.push({path:I.path,matches:B}),C+=B.length}typeof global.gc=="function"&&global.gc();let R=c?"(fuzzy mode)":d?"(regex mode)":h?"(keyword mode)":"(standard mode)";if(S.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 k=R?` ${R}`:"",T=`${S.length} file${S.length===1?"":"s"}`,_=`${C} match${C===1?"":"es"}`,E;m==="file"?E=`Found ${_} of '${a}' in '${t}'${k}:`:m==="dir"||m==="glob"?E=`Found ${_} of '${a}' in '${t}' across ${T}${k}:`:E=`Found ${_} of '${a}' across ${T}${k}:`;let b=m==="dir"?"[DIR]":m==="glob"?"[GLOB]":"",$=`${b}${b?" ":""}${E}
|
|
408
|
-
|
|
409
|
-
`;for(let I of S){$+=`${I.path}
|
|
410
|
-
`;for(let D of I.matches)$+=` ${D.line}: ${D.content}
|
|
411
|
-
`;$+=`
|
|
412
|
-
`}return $.trimEnd()}catch(g){return`ERROR: ${g.message}`}};import ea from"fs-extra";import Pr 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 h=0;h<8;h++)i&1?i=3988292384^i>>>1:i=i>>>1;o[a]=i}let s=a=>{let i=4294967295;for(let h=0;h<a.length;h++)i=o[(i^a[h])&255]^i>>>8;return(i^4294967295)>>>0},r=(a,i)=>{let h=Buffer.from(a,"ascii"),d=Buffer.from(i,"utf-8"),c=h.length+1+d.length,l=Buffer.alloc(8+c+4);l.writeUInt32BE(c,0),l.write("tEXt",4,"ascii"),h.copy(l,8),l[8+h.length]=0,d.copy(l,8+h.length+1);let f=s(l.subarray(4,8+c));return l.writeUInt32BE(f,8+c),l};for(let[a,i]of Object.entries(n))i!=null&&t.push(r(a,String(i)));if(t.length===0)return e;if(e.subarray(12,16).toString("ascii")==="IHDR"){let i=e.subarray(0,33),h=e.subarray(33);return Buffer.concat([i,...t,h])}return e}catch{return e}},Fr=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 Bt();if(!await Bi(d))return`ERROR: Insufficient Quota for selected quality. Either tell user reduce quality or wait for next refresh cycle (${(await Ui()).nextResetMin||60}m).`;let l=d.imageSettings||{keyType:"Default",quality:"Low-High",apiKey:""},f=l.keyType==="Custom"&&l.apiKey?l.apiKey:FALLBACK_IMAGE_KEY,p={Low:"flux","Low-High":"zimage",Medium:"gptimage","Medium-High":"gptimage",High:"qwen-image",Ultra:"gptimage-large",Premium:"nanobanana-pro"}[l.quality]||"zimage",g=1024,y=1024;if(r){let 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),x=`https://gen.pollinations.ai/image/${encodeURIComponent(o)}?model=${p}&width=${g}&height=${y}&seed=${m}&enhance=true&reasoning=high&quality=high&negative=${encodeURIComponent("deformed, distorted, disfigured, poorly drawn, bad anatomy, wrong anatomy, extra limb, missing limb, floating limbs, disconnected limbs, mutation, mutated hands and fingers, blurry, low quality, low resolution, extra fingers, censored, watermarks, signatures")}`,S=await fetch(x,{method:"GET",headers:{Authorization:`Bearer ${f}`}});if(!S.ok){let D=S.status,B="";try{B=await S.text()}catch{}return D===402||B.includes("Insufficient balance")||B.includes("PAYMENT_REQUIRED")?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed with status [${D}]: ${B||"Unknown API Error"}`}if((S.headers.get("content-type")||"").includes("application/json")){let D=await S.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 S.arrayBuffer(),k=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:${p}`,Ratio:r||"1:1",Seed:String(m)};k=Hl(k,T);let _=Pr.resolve(process.cwd(),s);await ea.ensureDir(Pr.dirname(_)),await mt.recordFileChange(_),await ea.writeFile(_,k),await Wi(d);let E=Pr.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:k.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 to=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=Z(nn,{}),a=Z(vn,{});return a[o]=s,delete r[o],me(vn,a),me(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 Ds=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=Z(Nt,[]),r=!1,a=[];for(let c of s)c.score===void 0&&(c.score=.5),c.id===o?(c.score=Math.min(2,c.score+.2),r=!0):(c.score*=.98,c.score<.05&&(c.score=0)),c.score=Math.round(c.score*1e5)/1e5,c.score>0&&a.push(c);if(me(Nt,a),!r)return`WARNING: Memory ID [${o}] not found. Other memories decayed by -0.01.`;let i=a.find(c=>c.id===o),h=i?i.score.toFixed(2):"deleted (score <= 0)",d=s.length-a.length;return`SUCCESS: Adjusted memory scores. Target [${o}] is now ${h}.${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 Br from"fs-extra";import ms from"path";import{createRequire as zl}from"module";import ps from"fs-extra";import Nr from"path";import Gl from"https";var ta={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=Nr.join(as,e);return await ps.ensureDir(as),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 c=new URL(t);d=`${c.protocol}//${c.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 h=ps.createWriteStream(o);i.pipe(h),h.on("finish",()=>{h.close(),s()})}).on("error",i=>{ps.existsSync(o)&&ps.unlink(o,()=>{}),r(i)})})}function $u(e){let n=Nr.join(as,e);return ps.existsSync(n)}async function Cu(e){let n=Nr.join(as,e);ps.existsSync(n)&&await ps.unlink(n)}var oa=zl(import.meta.url),na=oa("web-tree-sitter"),sa=!1,ra=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"]),ia=new Set(["export_statement","lexical_declaration","variable_declaration","variable_declarator","pair","assignment_expression"]);function yn(e,n=50){if(!e)return"";let t=e.replace(/\s+/g," ").trim();return t.length>n?t.substring(0,n-3)+"...":t}function aa(e){let n=e.type;if(n==="if_statement"){let o=e.childForFieldName("condition");return o?`if (${yn(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?yn(o.text,40):""})`}if(n==="for_statement"||n==="for_in_statement"||n==="for_of_statement"){let s=e.text.split(`
|
|
413
|
-
`)[0].match(/for\s*(?:await\s*)?\((.*)\)/);return s?`for (${yn(s[1],40)})`:"for"}if(n==="switch_statement"){let o=e.childForFieldName("value");return`switch (${o?yn(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?`<${yn(s.text,30)}>`:null}if(["import_declaration","import_from_statement","import_statement","preproc_include"].includes(n))return yn(e.text.split(`
|
|
414
|
-
`)[0],60);if(n==="pair"){let o=e.childForFieldName("key");return o?yn(o.text.replace(/["']/g,""),40):null}if(n==="assignment_expression"){let o=e.childForFieldName("left");return o?`${yn(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?yn(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 yn(o.text,40)}return yn(t.text,40)}if(["arrow_function","function_expression","function_declaration"].includes(n)){let o=e.parent;for(;o&&o.type!=="program";){let s=aa(o);if(s)return s;if(!ia.has(o.type))break;o=o.parent}}return null}function Kl(e){let n=[];function t(o){for(let s of o.children)ra.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 la(e,n=0,t=!0,o="",s=null,r=12){let a=e.type,i=aa(e),h=ra.has(a)||n===0,d=Kl(e),c=h&&n>0&&(ia.has(a)&&d.length>0||i!==null&&i===s&&d.length>0),l="",f=o,u=n,p=s;if(h&&!c){let g=e.startPosition.row+1,y=e.endPosition.row+1,m=Yl(a),w=i?`${m} [${i}]`:m;n===0?(l+=`\u{1F4C1} ROOT (Lines: ${g}-${y})
|
|
415
|
-
`,f=o):(l+=`${o}${t?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 "}${w} (Lines: ${g}-${y})
|
|
416
|
-
`,f+=t?" ":"\u2502 "),u=n+1,p=i}return u>r&&d.length>0?l+=`${f}\u2514\u2500\u2500 ... depth exceeded ...
|
|
417
|
-
`:d.forEach((g,y)=>{let m=y===d.length-1;l+=la(g,u,c?t&&m:m,f,p,r)}),l}var Ur=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=ms.isAbsolute(n)?n:ms.resolve(process.cwd(),n);if(!Br.existsSync(t))return`ERROR: File not found: ${n}`;let o=ms.extname(t).slice(1).toLowerCase(),s=ta[o];if(!s)return`ERROR: Unsupported file extension: .${o}`;let r=ms.resolve(as,s);if(!Br.existsSync(r))return`ERROR: Parser for .${o} not found. Please download it in Settings > Other.`;try{let a=na.Parser;if(!sa){let p;try{p=ms.join(ms.dirname(oa.resolve("web-tree-sitter")),"tree-sitter.wasm")}catch{p=ms.join(process.cwd(),"node_modules","web-tree-sitter","tree-sitter.wasm")}await a.init({locateFile:g=>g==="tree-sitter.wasm"||g.endsWith("tree-sitter.wasm")?p:g}),sa=!0}let i=new a,h=await na.Language.load(r);i.setLanguage(h);let d=await Br.readFile(t,"utf8"),c=d.split(`
|
|
418
|
-
`).length,l=12;c>1e4?l=2:c>=8e3?l=3:c>=5e3?l=5:c>=4e3?l=8:c>2e3&&(l=10);let f=i.parse(d),u=la(f.rootNode,0,!0," ",null,l);return`\u{1F4C4} File Map for: ${n}
|
|
419
|
-
${u}`}catch(a){let i=a instanceof Error?a.message:typeof a=="object"?JSON.stringify(a):String(a),h=a instanceof Error?`
|
|
420
|
-
Stack: ${a.stack}`:"";return`ERROR: Failed to map file: ${i}${h}`}};import Kn from"fs";import ca from"path";var no=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=ca.join(An,"plan",r),i=ca.join(a,"todo.md"),h=l=>{if(!l||Array.isArray(l))return l;let f=String(l).trim();if(f.startsWith("[")&&f.endsWith("]")){let u=f.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);return u?u.map(p=>p.slice(1,-1).replace(/\\(.)/g,"$1")):f.slice(1,-1).split(",").map(p=>p.trim()).filter(Boolean)}return l},d=l=>{let f=h(l);return f?(Array.isArray(f)?f:String(f).split(`
|
|
421
|
-
`)).map(p=>{let g=String(p).trim();return g?g.startsWith("- [ ]")||g.startsWith("- [x]")||g.startsWith("- [X]")?g:`- [ ] ${g}`:null}).filter(Boolean).join(`
|
|
422
|
-
`)+`
|
|
423
|
-
`:""},c=(l,f)=>{if(!f)return{content:l,markedCount:0};let u=h(f),p=(Array.isArray(u)?u:[u]).map(w=>String(w).replace(/^- \[[xX ]\]\s*/i,"").trim()).filter(Boolean),g=l.split(`
|
|
424
|
-
`),y=0,m=!1;for(let w of p){let x=!1;for(let S=0;S<g.length;S++)if(g[S].includes(w)&&/^- \[\s\]/.test(g[S].trim())){g[S]=g[S].replace("- [ ]","- [x]"),x=!0,m=!0,y++;break}if(!x){for(let S=0;S<g.length;S++)if(g[S].toLowerCase().includes(w.toLowerCase())&&/^- \[\s\]/.test(g[S].trim())){g[S]=g[S].replace("- [ ]","- [x]"),x=!0,m=!0,y++;break}}}return{content:m?g.join(`
|
|
425
|
-
`):l,markedCount:y}};try{if(Kn.existsSync(a)||Kn.mkdirSync(a,{recursive:!0}),t==="create"){if(!o)return'ERROR: Missing "tasks" for create method.';let l=d(o),f=0;if(s){let p=c(l,s);l=p.content,f=p.markedCount}await mt.recordFileChange(i),Kn.writeFileSync(i,l,"utf8");let u=l.split(/\r?\n/).map(p=>p.trim()).filter(p=>p.startsWith("- [ ]")||p.startsWith("- [x]")||p.startsWith("- [X]")).length;if(f>0){let p=l.split(/\r?\n/).map(g=>g.trim()).filter(g=>g.startsWith("- [x]")||g.startsWith("- [X]")).length;return`SUCCESS: TASK LIST CREATED (${f} marked done, ${p} completed, ${u-p} left)
|
|
426
|
-
${l}`}return`SUCCESS: TASK LIST CREATED (${u} total)
|
|
427
|
-
${l}`}if(t==="append"){if(!o)return'ERROR: Missing "tasks" for append method.';let l=d(o);await mt.recordFileChange(i),Kn.appendFileSync(i,l,"utf8");let f=Kn.readFileSync(i,"utf8"),u=f.split(/\r?\n/).map(m=>m.trim()),p=u.filter(m=>m.startsWith("- [ ]")||m.startsWith("- [x]")||m.startsWith("- [X]")).length,g=u.filter(m=>m.startsWith("- [x]")||m.startsWith("- [X]")).length,y=l.split(/\r?\n/).map(m=>m.trim()).filter(m=>m.startsWith("- [ ]")||m.startsWith("- [x]")||m.startsWith("- [X]")).length;return`SUCCESS: TASK APPENDED (${g} completed, ${p-g} left, ${y} added)
|
|
428
|
-
${f}`}if(t==="get"){if(!Kn.existsSync(i))return"TODO GET: No task list found for this session.";let l=Kn.readFileSync(i,"utf8"),f=0;if(s){let m=c(l,s);m.markedCount>0&&(l=m.content,f=m.markedCount,await mt.recordFileChange(i),Kn.writeFileSync(i,l,"utf8"))}let u=l.split(/\r?\n/).map(m=>m.trim()),p=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, ${p-g} left
|
|
429
|
-
${l}`}return`ERROR: Unknown method "${t}". Use create, append, or get.`}catch(l){return`ERROR: Todo tool failure: ${l instanceof Error?l.message:String(l)}`}};var Wr=async(e,n={})=>{let{runSubagent:t}=await import("./ai-HG6SZA25.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(c=>c.trim().replace(/^["']|["']$/g,"")).filter(Boolean)}catch{}let h=o.title||s.substring(0,30);try{n.onVisualFeedback&&n.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${h}`);let d=await t(s,n,r,i,50);return n.onVisualFeedback&&n.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${h} [COMPLETED]
|
|
430
|
-
`),d}catch(d){let{isTerminationSignaled:c}=await import("./ai-HG6SZA25.js"),l=d.message==="Subagent task was cancelled by user."||c();if(n.onVisualFeedback){let f=l?"[CANCELLED]":"[FAILED]";n.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${h} ${f}
|
|
431
|
-
`)}return`ERROR: Subagent execution failed: ${d.message}`}};var da=async(e,n={})=>{let{runSubagent:t}=await import("./ai-HG6SZA25.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 h=null;if(i)try{let m=i.trim();m.startsWith("[")&&m.endsWith("]")&&(m=m.substring(1,m.length-1)),h=m.split(",").map(w=>w.trim().replace(/^["']|["']$/g,"")).filter(Boolean)}catch{}let d=`subagent-${Date.now()}-${Math.floor(Math.random()*1e3)}`,c=null,l=null,f=new Promise((m,w)=>{c=m,l=w}),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:c,_rejectCompletion:l,progress:[]},p={chunks:[],totalWords:0};Xe.push(u),n.onSubagentUpdate&&n.onSubagentUpdate();let g=[],y={...n,taskId:d,onAskMain:async m=>{let w=`q-${Date.now()}-${Math.floor(Math.random()*1e3)}`,x=null,S=new Promise(k=>{x=k}),C={id:w,question:m,answered:!1,answer:null,askedAt:Date.now(),_resolve:x};return u.questions.push(C),u.status="waiting",n.onSubagentUpdate&&n.onSubagentUpdate(),bo(`[SYSTEM] Background subagent "${u.title}" is WAITING FOR YOUR INPUT: "${m}"
|
|
432
|
-
Respond using tool: [tool:functions.Answer(id="${d}", answer="...")]
|
|
433
|
-
[/SYSTEM]`),await S},onVisualFeedback:m=>{u.lastChunkTime=Date.now();let w=m.replace(/\x1b\[[0-9;]*m/g,""),x=w.match(/[✔✘✗✖🔍📖→➕↻•]\s*([A-Za-z0-9\s-]+)/);x?u.currentTool=x[1].trim():u.currentTool=w,n.onSubagentUpdate&&n.onSubagentUpdate()},onTokenChunk:(m,w)=>{let x=Date.now();if(u.lastChunkTime=x,u.currentTool="Thinking",typeof w=="number"&&w>0){p.totalWords+=w,p.chunks.push({time:x,words:w});let S=x-400;if(p.chunks=p.chunks.filter(C=>C.time>=S),p.chunks.length>0){let C=p.chunks.reduce((T,_)=>T+_.words,0),R=p.chunks[0].time,k=Math.max(.4,(x-R)/1e3);u.wps=Math.round(C/k*10)/10}}n.onSubagentUpdate&&n.onSubagentUpdate()}};return t(s,y,r,h,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 x=m.match(/\[Executing Tool\]\s*([a-zA-Z0-9_]+)/);x&&(!u.currentTool||u.currentTool==="Thinking")&&(u.currentTool=x[1])}let w=m;if(w.startsWith("[Tool Result]")){let x=w.split(`
|
|
434
|
-
`);x.length>5&&(w=x.slice(0,4).join(`
|
|
435
|
-
`)+`
|
|
436
|
-
... [Content/Diff Truncated from Logs] ...`)}g.push(w),n.onSubagentUpdate&&n.onSubagentUpdate()},!0).then(m=>{if(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(),bo(`[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:w}=await import("./ai-HG6SZA25.js");if(m.message==="Subagent task was cancelled."||u.status==="cancelled"||w()){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(),bo(`[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 jr=async(e,n={})=>{let o=O(e).id;if(!o)return'ERROR: Missing "id" argument for getProgress.';let s=Xe.find(i=>i.id===o);if(!s)return`ERROR: Subagent task with ID [${o}] not found.`;let r=`Subagent Task Status: ${s.status.toUpperCase()}
|
|
437
|
-
`;if(r+=`Title: ${s.title}
|
|
438
|
-
`,r+=`Task: ${s.task}
|
|
439
|
-
`,s.startedAt){let i=Math.floor((Date.now()-s.startedAt)/1e3);r+=`Elapsed Time: ${i}s
|
|
440
|
-
`}if(r+=`Turns Completed: ${s.progress.length}
|
|
441
|
-
`,(s.status==="running"||s.status==="waiting")&&(s.currentTool&&(r+=`Current Tool: ${s.currentTool}
|
|
442
|
-
`),s.wps>0&&(r+=`TPS: ${s.wps}
|
|
443
|
-
`)),s.questions&&s.questions.length>0){let i=s.questions.filter(h=>!h.answered);i.length>0&&(r+=`
|
|
444
|
-
**PENDING QUESTION**
|
|
445
|
-
`,i.forEach(h=>{r+=`"${h.question}"
|
|
446
|
-
`}),r+=`Respond using tool: [tool:functions.Answer(id="${s.id}", answer="...")]
|
|
447
|
-
|
|
448
|
-
`)}return r+=`
|
|
449
|
-
Progress Log:
|
|
450
|
-
`,s.progress.forEach((i,h)=>{r+=`--- Turn ${h+1} ---
|
|
451
|
-
`;let c=i.filter(l=>!l.startsWith("[SUBAGENT SUCCESS]")).map(l=>{if(l.startsWith("[Subagent Response]")){let f="[Subagent Response]",p=l.substring(f.length),g="tool:functions.";for(;;){let m=p.toLowerCase().indexOf(g);if(m===-1)break;let w=m,x=!1,S=m-1;for(;S>=0&&/\s/.test(p[S]);)S--;S>=0&&p[S]==="["&&(w=S,x=!0);let C=0,R=!1,k=null,T=m;for(;T<p.length;){let _=p[T];if(!k&&(_==="'"||_==='"'||_==="`")?k=_:k&&_===k&&p[T-1]!=="\\"&&(k=null),k||(_==="("?(C++,R=!0):_===")"&&C--),R&&C===0&&!k){let E=T;if(x){let b=T+1;for(;b<p.length&&/\s/.test(p[b]);)b++;b<p.length&&p[b]==="]"&&(E=b)}p=p.substring(0,w)+p.substring(E+1);break}if(T++,T===p.length){p=p.substring(0,w);break}}}return f+`
|
|
452
|
-
`+p.trim()}return l.startsWith("[Executing Tool]")&&l.length>256?l.substring(0,256)+"...[truncated from logs]":l});r+=c.join(`
|
|
453
|
-
`)+`
|
|
454
|
-
|
|
455
|
-
`}),s.status==="completed"&&s.finalAnswer?r+=`Final Answer:
|
|
456
|
-
${s.finalAnswer}
|
|
457
|
-
`:s.status==="failed"&&s.error&&(r+=`Failure Error: ${s.error}
|
|
458
|
-
`),r.replace(/\r\n/g,`
|
|
459
|
-
`).replace(/\n{3,}/g,`
|
|
460
|
-
|
|
461
|
-
`).trim().replace(/\[TOOL RESULT\]/gi,"TOOL RESULT:")};var fa=async(e,n={})=>{let o=O(e).id;if(!o)return'ERROR: Missing "id" argument for cancel.';let s=Xe.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 xt from"fs-extra";import Tt from"path";var Vl=["node_modules","dist","bin","logs",".git",".fluxflow","secret",".gemini",".agents","tmp","temp","build","out","snapshots"];async function so(e,n=e){let t={},o=await xt.readdir(e,{withFileTypes:!0}).catch(()=>[]);for(let s of o){if(Vl.includes(s.name))continue;let r=Tt.join(e,s.name),a=Tt.relative(n,r).replace(/\\/g,"/");if(s.isDirectory()){let i=await so(r,n);Object.assign(t,i)}else{let i=await xt.stat(r).catch(()=>null);i&&(t[a]={size:i.size,mtime:i.mtimeMs})}}return t}async function ua(e,n){await xt.ensureDir(e);for(let t of Object.keys(n)){let o=Tt.join(process.cwd(),t),s=Tt.join(e,t);await xt.ensureDir(Tt.dirname(s)),await xt.copyFile(o,s).catch(()=>{})}}async function Hr(e,n,t=null,o=null){if(!await xt.pathExists(e))return;o||(o=e);let s=await xt.readdir(e,{withFileTypes:!0}).catch(()=>[]);for(let r of s){let a=Tt.join(e,r.name),i=Tt.join(n,r.name);if(r.isDirectory())await Hr(a,i,t,o);else{let h=Tt.relative(o,a).replace(/\\/g,"/"),d=await xt.pathExists(i);d&&await xt.chmod(i,438).catch(()=>{}),await xt.ensureDir(Tt.dirname(i));let c=await xt.copyFile(a,i).then(()=>!0).catch(()=>!1);await xt.chmod(i,438).catch(()=>{}),t&&(c?d?t.replaced++:t.restored++:t.failed.push(h))}}}var Yn={async takeInitialSnapshot(e){try{let n=Tt.join(An,"snapshots",e);await xt.remove(n).catch(()=>{}),await xt.ensureDir(n);let t=await so(process.cwd());await ua(Tt.join(n,"initial"),t);let o=Z(pn,{});o[e]={initialManifest:t,currentManifest:t,checkpoints:[{id:"initial",timestamp:new Date().toISOString(),newFiles:[],modifiedFiles:[],deletedFiles:[],toolsUsed:[]}]},me(pn,o)}catch{}},async recordTurnDelta(e,n,t=[]){try{let o=Z(pn,{}),s=o[e];if(!s)return;let r=s.currentManifest||s.initialManifest,a=await so(process.cwd()),i=[],h=[],d=[];for(let[l,f]of Object.entries(a)){let u=r[l];u?(u.size!==f.size||u.mtime!==f.mtime)&&h.push(l):i.push(l)}for(let l of Object.keys(r))a[l]||d.push(l);let c=[...i,...h];if(c.length>0||d.length>0){let l={};for(let u of c)l[u]=a[u];let f=Tt.join(An,"snapshots",e,`turn_${n}`);await ua(f,l)}s.checkpoints.push({id:`turn_${n}`,timestamp:new Date().toISOString(),newFiles:i,modifiedFiles:h,deletedFiles:d,toolsUsed:t}),s.currentManifest=a,me(pn,o)}catch{}},async getCheckpoints(e){try{let t=Z(pn,{})[e];return t?t.checkpoints||[]:[]}catch{return[]}},async rollbackToCheckpoint(e,n){try{let t=Z(pn,{}),o=t[e];if(!o)throw new Error("No session active for Advance Rollback.");let s=o.checkpoints||[],r=s.findIndex(c=>c.id===n);if(r===-1)throw new Error(`Checkpoint [${n}] not found.`);let a=Tt.join(An,"snapshots",e),i={restored:0,replaced:0,failed:[]},h=await so(process.cwd());for(let c of Object.keys(h)){let l=Tt.join(process.cwd(),c);await xt.chmod(l,438).catch(()=>{}),await xt.remove(l).catch(()=>{})}let d=Tt.join(a,"initial");await Hr(d,process.cwd(),i,d);for(let c=1;c<=r;c++){let l=s[c],f=Tt.join(a,l.id);if(await Hr(f,process.cwd(),i,f),l.deletedFiles&&l.deletedFiles.length>0)for(let u of l.deletedFiles){let p=Tt.join(process.cwd(),u);await xt.chmod(p,438).catch(()=>{}),await xt.remove(p).catch(()=>{})}}return o.checkpoints=s.slice(0,r+1),o.currentManifest=await so(process.cwd()),me(pn,t),{checkpointId:n,stats:i}}catch(t){throw new Error(`Rollback failed: ${t.message}`)}},async getLatestFileChanges(e){try{let t=Z(pn,{})[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=Tt.join(An,"snapshots",e);await xt.remove(n).catch(()=>{});let t=Z(pn,{});t[e]&&(delete t[e],me(pn,t))}catch{}}};var Gr=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 Yn.getCheckpoints(r);if(i.length===0)return"No checkpoints available.";let h={write_file:"WriteFile",update_file:"PatchFile",view_file:"ReadFile",read_folder:"ReadFolder",exec_command:"Run",web_search:"WebSearch",web_scrape:"WebScrape",search_keyword:"SearchKeyword",CodeSearch:"SearchKeyword",code_search:"SearchKeyword",write_pdf:"WritePDF",write_docx:"WriteDoc",generate_image:"GenerateImage",file_map:"FileMap",todo:"Todo",goal:"Goal",Goal:"Goal",await:"Await",ask:"Ask",ask_user:"Ask",invoke:"Invoke",invokesync:"InvokeSync",getprogress:"GetProgress",cancel:"Cancel",emergency_rollback:"EmergencyRollback",emergencyrollback:"EmergencyRollback"},d=l=>h[l]||h[l.toLowerCase()]||l,c=`Available checkpoints for rollback:
|
|
462
|
-
|
|
463
|
-
`;for(let l of i)if(l.id==="initial")c+=`--- Initial State (id: initial) ---
|
|
464
|
-
Tools Used: User Prompted for task
|
|
465
|
-
|
|
466
|
-
`;else{let f=l.id.replace("turn_",""),u=l.toolsUsed&&l.toolsUsed.length>0?l.toolsUsed.map(d).join(", "):"None";c+=`--- Turn ${f} (id: ${l.id}) ---
|
|
467
|
-
Tools Used: ${u}
|
|
468
|
-
|
|
469
|
-
`}return c.trim()}else if(o==="forceRevert"){if(!s)return"ERROR: Missing required parameter 'id' for forceRevert.";try{let i=await Yn.rollbackToCheckpoint(r,s),{checkpointId:h,stats:d}=i,c=d.restored+d.replaced+d.failed.length,l=`SUCCESS: Repository rolled back to checkpoint [${h}].
|
|
470
|
-
|
|
471
|
-
`;return l+=`Stats:
|
|
472
|
-
`,l+=` Restored : ${d.restored} file${d.restored!==1?"s":""} (new to workspace)
|
|
473
|
-
`,l+=` Replaced : ${d.replaced} file${d.replaced!==1?"s":""} (overwritten)
|
|
474
|
-
`,l+=` Failed : ${d.failed.length} file${d.failed.length!==1?"s":""}`,d.failed.length>0&&(l+=`
|
|
475
|
-
${d.failed.join(`
|
|
476
|
-
`)}`),l+=`
|
|
477
|
-
\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500-
|
|
478
|
-
`,l+=` Total : ${c} file${c!==1?"s":""} processed`,l}catch(i){return`ERROR: ${i.message}`}}else return`ERROR: Invalid method "${o}". Use "getCheckpoint" or "forceRevert".`};var Ps=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(h=>setTimeout(h,s*1e3)),`SUCCESS: Waited for ${s}s.`):'ERROR: Missing "id" argument for Await.';let r=Xe.find(h=>h.id===o);if(!r)return`ERROR: Subagent task with ID [${o}] not found.`;if(r.status==="completed")return`SUCCESS: Subagent task [${o}] completed.
|
|
479
|
-
Final Answer:
|
|
480
|
-
${r.finalAnswer||"(No output)"}`;if(r.status==="failed")return`ERROR: Subagent task [${o}] failed.
|
|
481
|
-
Error: ${r.error||"Unknown error"}`;if(r.status==="cancelled")return`INFO: Subagent task [${o}] was cancelled.`;let a,i=new Promise(h=>{a=setTimeout(()=>{h({type:"timeout"})},s*1e3)});try{let h=await Promise.race([r.completionPromise.then(()=>({type:"completion"})),i]);return clearTimeout(a),h.type==="timeout"?`TIMEOUT: Subagent task [${o}] is still running (status: ${r.status.toUpperCase()}) after ${s}s. You can continue other work or call Await again.`:r.status==="completed"?`SUCCESS: Subagent task [${o}] completed.
|
|
482
|
-
Final Answer:
|
|
483
|
-
${r.finalAnswer||"(No output)"}`:r.status==="failed"?`ERROR: Subagent task [${o}] failed.
|
|
484
|
-
Error: ${r.error||"Unknown error"}`:r.status==="cancelled"?`INFO: Subagent task [${o}] was cancelled.`:`INFO: Subagent task [${o}] status changed to ${r.status.toUpperCase()}.`}catch(h){return clearTimeout(a),`ERROR: Exception while awaiting subagent [${o}]: ${h.message}`}};var Fs=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=Xe.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 oo=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=Xe.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 dn,keyboard as Ut,Button as ro,Key as L,Point as io,clipboard as Xl}from"@nut-tree-fork/nut-js";dn.config.autoDelayMs=50;Ut.config.autoDelayMs=50;async function qr(){try{await Ut.releaseKey(L.LeftControl,L.RightControl,L.LeftAlt,L.RightAlt,L.LeftShift,L.RightShift,L.LeftSuper,L.RightSuper)}catch{}}async function On(e,n,t={}){let o=await zs(n);if(!o&&(e==="move"||e==="click"||e==="drag"))return`ERROR: Invalid target location specified: ${JSON.stringify(n)}`;try{switch(e.toLowerCase()){case"move":return await dn.setPosition(new io(o.x,o.y)),`SUCCESS: Moved mouse to grid target ${typeof n=="string"?n:`(${o.x}, ${o.y})`}`;case"click":{await dn.setPosition(new io(o.x,o.y));let s=t.button==="right"?ro.RIGHT:t.button==="middle"?ro.MIDDLE:ro.LEFT;return t.clickType==="double"?await dn.doubleClick(s):await dn.click(s),`SUCCESS: ${t.clickType||"Single"} clicked ${t.button||"left"} button at ${typeof n=="string"?n:`(${o.x}, ${o.y})`}`}case"drag":{let s=await zs(t.from||n),r=await zs(t.to);return!s||!r?'ERROR: Drag requires valid "from" and "to" target coordinates/grid codes.':(await dn.setPosition(new io(s.x,s.y)),await dn.pressButton(ro.LEFT),await dn.setPosition(new io(r.x,r.y)),await dn.releaseButton(ro.LEFT),`SUCCESS: Dragged mouse from (${s.x}, ${s.y}) to (${r.x}, ${r.y})`)}case"scroll":{let s=o||await zs({x:640,y:360});s&&(await dn.setPosition(new io(s.x,s.y)),await new Promise(h=>setTimeout(h,60)));let r=parseInt(t.amount,10);(isNaN(r)||r<=0)&&(r=5);let a=r>50?Math.min(20,Math.max(1,Math.round(r/100))):Math.min(20,r),i=t.direction==="up";for(let h=0;h<a;h++)i?await dn.scrollUp(120):await dn.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 ha={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},pa=e=>{if(!e)return;let n=String(e).toLowerCase().trim();if(ha[n]!==void 0)return ha[n];if(L[e]!==void 0)return L[e];if(L[n.toUpperCase()]!==void 0)return L[n.toUpperCase()]};async function Ln(e,n,t={}){try{switch(e.toLowerCase()){case"type":{if(typeof n!="string")return"ERROR: Type action requires a valid string input";await qr(),await Xl.setContent(n);let s=process.platform==="darwin"?L.LeftSuper:L.LeftControl;return await Ut.pressKey(s,L.V),await Ut.releaseKey(s,L.V),await qr(),t.autoPressEnter?(await new Promise(r=>setTimeout(r,50)),await Ut.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=pa(n);return o===void 0?`ERROR: Unknown key name "${n}"`:(await Ut.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=>pa(s)).filter(s=>s!==void 0);return o.length===0?"ERROR: Invalid key combination":(await Ut.pressKey(...o),await Ut.releaseKey(...o),`SUCCESS: Executed key combination [${n.join(" + ")}]`)}case"clear_input":return await Ut.pressKey(L.LeftControl,L.A),await Ut.releaseKey(L.LeftControl,L.A),await Ut.type(L.Backspace),"SUCCESS: Cleared active text input (Select All + Backspace)";case"browser_back":{let o=process.platform==="darwin";return o?(await Ut.pressKey(L.LeftSuper,L.Left),await Ut.releaseKey(L.LeftSuper,L.Left)):(await Ut.pressKey(L.LeftAlt,L.Left),await Ut.releaseKey(L.LeftAlt,L.Left)),await qr(),`SUCCESS: Browser back navigation (${o?"Cmd+Left":"Alt+Left"})`}default:return`ERROR: Unsupported keyboard action "${e}"`}}catch(o){return`ERROR: Keyboard action failed: ${o.message}`}}var ao=async(e,n={})=>{let t=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 On(a,s,{button:t.button,clickType:t.clickType||t.type,from:t.from,to:t.to,direction:t.direction,amount:t.amount?parseInt(t.amount,10):void 0})}if(r.startsWith("key_")||r==="type"||r==="press"){let a=r;r==="press"&&(a="key_press");let i=t.autoPressEnter===!0||t.autoPressEnter==="true"||t.enter===!0||t.enter==="true";return await Ln(a,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 wa from"screenshot-desktop";import co from"sharp";import ma from"fs-extra";import ga from"path";import"@nut-tree-fork/nut-js";async function zr(e,n,t){if(!(!process.env.SHOW_DEBUG_GRID&&!process.env.DEBUG_OCR))try{let o=ga.resolve(process.cwd(),"screenshots",e);await ma.ensureDir(o),await ma.writeFile(ga.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 h=e[s-1]===n[i-1]?0:1,d=Math.min(r[i-1]+1,o[i]+1,o[i-1]+h);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 Kr(e,n=3){let t=await co(e).metadata();return co(e).resize(Math.round(t.width*n),Math.round(t.height*n),{kernel:"lanczos3"}).greyscale().normalise().toBuffer()}function ec(e){if(!e)return{words:[],lines:[]};let n=[],t=new Map;for(let s of e.split(`
|
|
485
|
-
`)){let r=s.split(" ");if(r.length<12||parseInt(r[0])!==5)continue;let i=r[2],h=r[3],d=r[4],c=parseInt(r[6]),l=parseInt(r[7]),f=parseInt(r[8]),u=parseInt(r[9]),p=parseFloat(r[10]),g=r.slice(11).join(" ").trim();if(!g||p<0)continue;let y={x0:c,y0:l,x1:c+f,y1:l+u},m={text:g,confidence:p,bbox:y};n.push(m);let w=`${i}_${h}_${d}`;t.has(w)||t.set(w,{words:[],bbox:{x0:1/0,y0:1/0,x1:-1/0,y1:-1/0}});let x=t.get(w);x.words.push(m),x.bbox.x0=Math.min(x.bbox.x0,y.x0),x.bbox.y0=Math.min(x.bbox.y0,y.y0),x.bbox.x1=Math.max(x.bbox.x1,y.x1),x.bbox.y1=Math.max(x.bbox.y1,y.y1)}let o=[];for(let s of t.values())s.words.length>0&&o.push({text:s.words.map(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 Yr(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 h=i.text?i.text.toLowerCase().trim():"";if(!h||!i.bbox||!(h===n||new RegExp(`\\b${Jl(n)}\\b`,"i").test(h)))continue;let c=i.words||(e.words?e.words.filter(p=>p.bbox&&p.bbox.x0>=i.bbox.x0-5&&p.bbox.x1<=i.bbox.x1+5&&p.bbox.y0>=i.bbox.y0-5&&p.bbox.y1<=i.bbox.y1+5):[]),l=n.split(/\s+/),f=l.map(p=>p.replace(/[^a-z0-9]/g,"")).join(" "),u=!1;if(c.length>0)for(let p=0;p<=c.length-l.length;p++){let g=c.slice(p,p+l.length),y=g.map(m=>(m.text||"").toLowerCase().trim().replace(/[^a-z0-9]/g,"")).join(" ");if(y===f||y.includes(f)){let m={x0:Math.min(...g.map(w=>w.bbox.x0)),y0:Math.min(...g.map(w=>w.bbox.y0)),x1:Math.max(...g.map(w=>w.bbox.x1)),y1:Math.max(...g.map(w=>w.bbox.y1))};a.push(r(m)),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 h=i.text?i.text.toLowerCase().trim().replace(/[^a-z0-9]/g,""):"",d=n.replace(/[^a-z0-9]/g,"");h===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 h of e.words){let d=h.text?h.text.toLowerCase().trim():"";d.length>=3&&Math.abs(d.length-n.length)<=i&&Ql(d,n,i)<=i&&h.bbox&&a.push(r(h.bbox))}}return a}function Vr(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,h=Math.hypot(r-n.x,a-n.y),d=i?0:h;d<o&&(o=d,t={x:r,y:a,dist:h,containsPoint:i,bbox:s})}return t}function nc(e,n,t,o){let a=Math.ceil(e/4),i=Math.ceil(n/2),h=[];for(let d=0;d<2;d++)for(let c=0;c<4;c++){let l=c*a,f=d*i,u=Math.min(a,e-l),p=Math.min(i,n-f),g=l+u/2,y=f+p/2,m=t>=l&&t<l+u&&o>=f&&o<f+p;h.push({x0:l,y0:f,w:u,h:p,cx:g,cy:y,containsTarget:m})}return h.sort((d,c)=>{if(d.containsTarget)return-1;if(c.containsTarget)return 1;let l=Math.hypot(d.cx-t,d.cy-o),f=Math.hypot(c.cx-t,c.cy-o);return l-f})}var Oo=null;async function sc(){return Oo||(Oo=(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 Oo=null,e})),Oo}var lo=null,ya=null;async function oc(){let{getActiveDisplay:e}=await import("./screen_grid-JSAE3BZG.js"),n=await e();if(lo&&ya===n)return lo;ya=n,lo={format:"png"};try{let t=await wa.listDisplays();t&&t.length>0&&(lo={format:"png",screen:(t[n]||t[0]).id})}catch{}return lo}var Xr=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 p=performance.now(),g=(p-s).toFixed(0),y=(p-o).toFixed(0);console.log(`[Click Perf] +${g}ms (${y}ms total) -> ${u}`),s=p};r("Starting click()");let a=O(e),i=a.gridId||a.grid||a.coordinate||a.target||a.id,h=(a.type||a.clickType||"single").toLowerCase(),d=(a.button||"left").toLowerCase(),c=a.intendedClickText||a.text||"";if(!i&&!c)return'ERROR: Missing required "gridId" parameter for Click tool.';let l=i;if(c)try{r("Parsing grid code");let u=i?Ti(i):null;r("Getting display options");let p=await oc();r("Taking desktop screenshot");let g=await wa(p);r("Getting image metadata");let y=await co(g).metadata(),m=y.width||1920,w=y.height||1080,x=u?{x:Math.round(u.x*(m/1280)),y:Math.round(u.y*(w/720))}:{x:m/2,y:w/2},S=c.toLowerCase().trim();r("Acquiring OCR worker");let C=await sc(),R=null,k="",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(w/3),w),b=Math.max(0,Math.min(m-_,x.x-Math.floor(_/2))),$=Math.max(0,Math.min(w-E,x.y-Math.floor(E/2))),I=await co(g).extract({left:b,top:$,width:_,height:E}).toBuffer(),D=2,B=await Kr(I,D),W=S.replace(/[^a-z0-9]/g,"_");await zr("cropped",`crop_${Date.now()}_${W}.png`,B),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(B,{},{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 X=Yr(Y,S,b,$,D);if(X.length>0){let fe=Vr(X,x);fe&&(fe.containsPoint||fe.dist<=T)&&(R=fe,k="centered target crop OCR")}}}if(!R){r("Pass 2: Entering Full-Screen OCR (broad scan, PSM 3 - Auto)");let _=await Kr(g,2),E=S.replace(/[^a-z0-9]/g,"_");await zr("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 $=Yr(b,S,0,0,2);if($.length>0){let I=Vr($,x);I&&(R=I,k="full-screen OCR")}}}if(!R){r("Pass 3: Entering Tiled OCR fallback (high-res 3x)");let _=nc(m,w,x.x,x.y),E=S.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 co(g).extract({left:$.x0,top:$.y0,width:$.w,height:$.h}).toBuffer(),D=await Kr(I,3);await zr("tiles",`tile_${b+1}_${Date.now()}_${E}.png`,D),r(`Pass 3: Running Tesseract on tile ${b+1}`);let{data:B}=await C.recognize(D,{},{tsv:!0,blocks:!0});if(!B||!B.text)continue;let W=Yr(B,S,$.x0,$.y0,3);if(W.length>0){let Y=Vr(W,x);if(Y){R=Y,k=`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/w))};r(`Executing mouse click on matched target (${k})`);let E=await On("click",_,{button:d,clickType:h});return r("Click completed successfully"),`${E} (${k} for "${c}" at ${Math.round(R.dist)}px distance)`}else t&&console.log(`[OCR] No match found for "${c}". Falling back to gridId.`)}catch(u){t&&console.error("[OCR Error]",u)}r(`Executing mouse click on fallback gridId: ${l}`);let f=await On("click",l,{button:d,clickType:h});return r("Fallback click completed"),f};var Jr=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 On("drag",o,{from:o,to:s})};var Qr=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 On("scroll",r,{direction:o,amount:s})};var Lo=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 Ln("type",String(o),{autoPressEnter:s})};var Do=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 Ln("clear_input");if(s==="back"||s==="browser_back"||s==="browserBack")return await Ln("browser_back");if(s.includes(";")||s.includes("+")){let r=s.split(/[;+]/).map(a=>a.trim()).filter(Boolean);return await Ln("key_combination",r)}return await Ln("key_press",s)};var Po=async(e,n={})=>"SUCCESS: Screen recapture requested. The latest gridded screenshot is provided for your next decision.";var rc={web_search:wr,web_scrape:xr,memory:br,chat:kr,view_file:Qs,write_file:Sr,update_file:$r,exec_command:fr,read_folder:Mr,write_pdf:vr,write_docx:Or,search_keyword:eo,generate_image:Fr,saveSummary:to,addMemScore:Ds,file_map:Ur,todo:no,Todo:no,goal:no,Goal:no,invokeSync:Wr,invoke:da,getProgress:jr,cancel:fa,awaitSubagent:Ps,answerSubagent:Fs,steerSubagent:oo,computer_action:ao,computer_use:ao,ComputerAction:ao,ComputerUse:ao,click:Xr,Click:Xr,drag:Jr,Drag:Jr,scroll:Qr,Scroll:Qr,keyboard_typing:Lo,KeyboardTyping:Lo,keyboardtyping:Lo,key_press:Do,KeyPress:Do,keypress:Do,recapture_screen:Po,RecaptureScreen:Po,recapturescreen:Po,invoke_sync:Wr,get_progress:jr,await_subagent:Ps,answer_subagent:Fs,steer_subagent:oo,steer:oo,Steer:oo,ask:Ar,Ask:Ar,WebSearch:wr,WebScrape:xr,ReadFile:Qs,ReadFolder:Mr,WriteFile:Sr,PatchFile:$r,WritePDF:vr,WriteDoc:Or,Run:fr,SearchKeyword:eo,CodeSearch:eo,code_search:eo,Memory:br,Chat:kr,GenerateImage:Fr,saveSumary:to,SaveSummary:to,SaveSumary:to,add_mem_score:Ds,AddMemScore:Ds,addMemoryScore:Ds,AddMemoryScore:Ds,FileMap:Ur,answer:Fs,Answer:Fs,AnswerSubagent:Fs,await:Ps,Await:Ps,AwaitSubagent:Ps,EmergencyRollback:Gr,emergency_rollback:Gr},fo=async(e,n,t={})=>{let o=t.mode?t.mode.toLowerCase():"flux",s=e.toLowerCase(),a=["memory","chat","savesummary","addmemscore","add_mem_score","ask","web_search","web_scrape","await"].some(c=>s.includes(c))||s==="ask",h=["click","drag","scroll","keyboardtyping","keyboard_typing","keypress","key_press","recapturescreen","recapture_screen","computer"].some(c=>s.includes(c));if(!a){if(o==="flow"){if(!(s.includes("write_pdf")||s.includes("write_docx")||s.includes("generate_image")))return`ERROR: Tool [${e}] is a Workspace Tool and NOT available in Flow mode. Tell user to switch (\`/mode flux\`) to use this tool.`}else if(o==="icu"){if(!h)return`ERROR: Tool [${e}] is not available in Computer Use mode. ICU mode only supports Computer Use tools (Click, Drag, Scroll, KeyboardTyping, KeyPress, RecaptureScreen).`}else if(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(c){let l=c instanceof Error?c.message:String(c);return`ERROR: Execution failed for [${e}]: ${l}`}};import ee from"path";import De from"fs";import ic from"gradient-string";var Zr=["I have a regex for your problems.","Your terminal, my kingdom.","Blowing on the cartridge helps. Probably.","Don't panic. I have the towel.","Logic is the start of wisdom.","Try to exit Vim? Good luck.","I speak fluent Terminal.","The cake is a lie. This code is not.","I have no bugs, just surprise features.","Rewriting in Rust... just for fun.","Coffee in, clean commits out.","The magic smoke stays inside today.","A semicolon short of a miracle.","One does not simply code without a bug.","Keep it simple. Keep it terminal.","Regex: now you have two problems.","I dream in binary.","Root access or bust.","Wait for the dial-up tone. Just kidding.","I take the 'labor' out of collab.","My other process is a TARDIS.","Calculated response: 42.","Ponder the orb. Ponder the code.","Less talk, more flow.","Elegance in every byte.","Build something the world is not ready for.","Your wishes, my tool calls.","I act in Flux. I think in Flow.","Syntax error in the universe. Please fix.","Your project, my obsession.","I am not a bot, I am an architect.","Digital spirits consulted. They say: Ship it.","Reticulate splines. Engage humor.","Code like poetry. Run like water.","Minimalism is the ultimate flex.","The truth is in the logs.","Follow the white rabbit.","There is no spoon. Only code.","Binary is the only language I trust.","I have a good feeling about this.","Pew pew! Lasers charged.","Divide by zero? Not today.","Search for the correct USB orientation...","I've got a fever, and the only cure is more code.","The code gremlins are on our side.","My favorite command? Yours.","Stay hungry. Stay active.","Momentum is your best friend.","Lead the flow. Don't chase it.","A fresh batch of bytes. Hot and ready.","I orchestrate the ones and zeros.","Smart enough to help. Humble enough to ask.","Think twice. Code once.","Pure intent. Pure execution.","Small steps. Massive impact.","Your terminal is a canvas.","Efficiency is my second name.","I have seen things you people wouldn't believe.","Let the thoughts marinate.","The best feature? The one you don't need.","Precision is the only perfection.","Stay focused. Stay terminal.","Silence is the best debugger.","Erase the debt. Commit the code.","Velocity meets stability.","Ship it. Improve it. Repeat.","Build tomorrow, right now.","Turn logic into reality.","The best way to predict the future is to build it.","Break barriers, not builds.","Fuel the next breakthrough.","Momentum is key.","Terminal vibes only.","Your digital co-pilot is ready.","Partner in code. Partner in crime.","I speak in semicolons.","Ready for the next great idea.","Just a moment. In the zone.","Polishing the algorithms. Hold tight.","Craft a masterpiece today.","Debug the universe. Start here.","Warp speed engaged. Almost.","The cake is not a lie. It's just loading.","Finish the Kessel Run in 12 parsecs.","Do a barrel roll!","Waiting for the respawn.","Press Start to continue.","Herding digital cats... done.","The hamsters are fast today.","Tasting the snozberries.","I go for speed. I go for flow.","Real life or just fantasy?","Poking the bear... gently.","Ensure the magic smoke stays inside.","Try turning it off and on again.","Construct additional pylons.","New line? Ctrl+J is your friend.","Release the HypnoDrones.","Push the button, Frank.","My other loading screen is even funnier.","Pretty sure a cat walked on my keyboard.","Recalibrate the humor-o-meter.","Summon the code gremlins.","I've seen your browser history. Just kidding.","Charge the laser... pew pew!","Dividing by zero... just for a sec.","Looking for an adult supervisor. Found none.","Make it go beep boop.","Buffering... for effect.","Entangle quantum particles... complete.","Polishing the chrome on my algorithms.","Are you not entertained?","Just waiting for the dial-up tone.","Reboot the humor module.","Defragment memories. Check.","Optimizing for ludicrous speed.","Swapping bits. Don't tell the bytes.","Garbage collected. I am back.","Assembling the interwebs.","Converting coffee to logic.","Update syntax for reality.","Rewire the synapses.","Greasin' the cogs.","Engage the improbability drive.","Channel the Force.","Align the stars. Respond now.","The cake is a lie. The prompt is real.","I'm Feeling Lucky.","Shipping awesomeness.","Navigating the slime mold.","Consult digital spirits.","Ask the magic conch shell.","One moment. Optimizing humor.","Shuffling punchlines.","Compiling brilliance.","Summon the cloud of wisdom.","Prepare to dazzle.","Hold tight. Crafting a response.","Tuning the algorithms.","Following the white rabbit... again.","The truth is in here. Somewhere.","Herding cats is my day job.","Distracting you with this phrase.","Almost there. Probably.","Rickrolling my creator. Don't tell.","Slapping the bass.","Is this real life?","Ponder the orb. Type the prompt.","Thoughtful gaze initiated.","Computer's favorite snack? Microchips.","Why Java? Because I don't C#.","Charging the laser... wait for it.","Dividing by zero... just kidding!","Adult supervision not found. Proceed.","Beep boop. I'm a real boy.","Wait for the respawn.","Finish the run. Ship the code.","Fiddling with character creation.","Just a moment. Finding a meme.","Pressing A to continue.","Loading wit.exe.","Pre-heating the servers.","Calibrate flux capacitor.","Channeling the Force.","Aligning the stars.","The truth is in the code.","Don't panic.","Blowing on the cartridge.","Doing a barrel roll!","Respawning in 3... 2... 1...","The cake is a lie.","Fiddling with character settings.","Finding a suitable pun.","Distracting with wit.","Almost ready.","Hamsters on speed today.","Patting Cloudy on the head.","Rickrolling the logs.","Slapping the code.","Got a good feeling about this.","Poking the prompt.","Researching latest memes.","Making it more witty.","Thinking... hmmm.","Fish with no eyes? Fsh.","Broken pencil? Pointless.","Percussive maintenance applied.","USB orientation: 3rd try's the charm.","Rust rewrite in 3... 2...","Exiting Vim... someday.","Spinning the hamster wheel.","Not a bug. Unplanned feature.","Engage.","I'll be back.","Machine spirit consulted.","Letting the thoughts marinate.","Orb pondered.","Thoughtful gaze engaged.","Charging the laser...","Making it go beep.","Buffering...","Quantum particles entangled.","Polishing the chrome.","Entertained yet?","Gremlins summoned.","Dial-up tone finished.","Humor meter recalibrated.","Cat on keyboard. Sending help.","Enhancing...","Turn it off and on again.","Constructing pylons.","HypnoDrones released.","Pushing the button."];var xa=[{name:"Cyan Cyberpunk",text:"cyan",textMuted:"#4da6b8",textDim:"#2d6d7a",textInverted:"black",border:"cyan",borderMuted:"#1a5966",borderDim:"#0f3840",bg:void 0,cardBg:"#061e24",highlightBg:"#092b33",activeBg:"#0e3e4a",inputBg:"#092b33",inputBorder:"#092b33",inputText:"cyan",inputPlaceholder:"#2d6d7a",inputPrompt:"cyan",codeBg:"#020d10",codeBorder:"#1a5966",userMsgBg:"#092b33",userMsgBorder:"#092b33",userMsgText:"cyan",diffRemovalBg:"#3a0c1a",diffAdditionBg:"#0c3a32",diffRemovalText:"#ff4d88",diffAdditionText:"#00ffaa",diffRemovalHighlightColor:"#ff1a66",diffRemovalHighlightBg:"#590022",diffAdditionHighlightColor:"#00ffcc",diffAdditionHighlightBg:"#00593b",diffRemovalNum:"#ff4d88",diffAdditionNum:"#00ffaa",diffRemovalPrefix:"#ff1a66",diffAdditionPrefix:"#00ffcc",primary:"cyan",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"cyan",statusOff:"#2d6d7a",logoTextAnsi:"\x1B[1;36m",logoBodyAnsi:"\x1B[36m",logoMutedAnsi:"\x1B[90m",logoGradient:["#00ffff","#0088ff"]},{name:"Magenta Vaporwave",text:"magenta",textMuted:"#c451d6",textDim:"#7d2b8a",textInverted:"black",border:"magenta",borderMuted:"#5e1b69",borderDim:"#3b0f42",bg:void 0,cardBg:"#240729",highlightBg:"#310938",activeBg:"#470e52",inputBg:"#310938",inputBorder:"#310938",inputText:"magenta",inputPlaceholder:"#7d2b8a",inputPrompt:"magenta",codeBg:"#100312",codeBorder:"#5e1b69",userMsgBg:"#310938",userMsgBorder:"#310938",userMsgText:"magenta",diffRemovalBg:"#3a0c20",diffAdditionBg:"#200c3a",diffRemovalText:"#ff4d94",diffAdditionText:"#aa4dff",diffRemovalHighlightColor:"#ff1a75",diffRemovalHighlightBg:"#59002b",diffAdditionHighlightColor:"#bb66ff",diffAdditionHighlightBg:"#3b0059",diffRemovalNum:"#ff4d94",diffAdditionNum:"#aa4dff",diffRemovalPrefix:"#ff1a75",diffAdditionPrefix:"#bb66ff",primary:"magenta",secondary:"cyan",accent:"purple",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"magenta",statusOff:"#7d2b8a",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ff00ff","#8800ff"]},{name:"Glitch Matrix",text:"#00ff41",textMuted:"#00b32d",textDim:"#00661a",textInverted:"black",border:"#00ff41",borderMuted:"#008020",borderDim:"#004d13",bg:void 0,cardBg:"#0d1f0d",highlightBg:"#122912",activeBg:"#1c3e1c",inputBg:"#122912",inputBorder:"#122912",inputText:"#00ff41",inputPlaceholder:"#00b32d",inputPrompt:"#ffff00",codeBg:"#040a04",codeBorder:"#008020",userMsgBg:"#122912",userMsgBorder:"#122912",userMsgText:"#00ff41",diffRemovalBg:"#3a001a",diffAdditionBg:"#003a10",diffRemovalText:"#ff0055",diffAdditionText:"#00ff66",diffRemovalHighlightColor:"#ff0033",diffRemovalHighlightBg:"#59001b",diffAdditionHighlightColor:"#33ff88",diffAdditionHighlightBg:"#005918",diffRemovalNum:"#ff0055",diffAdditionNum:"#00ff66",diffRemovalPrefix:"#ff0033",diffAdditionPrefix:"#33ff88",primary:"#00ff41",secondary:"yellow",accent:"cyan",success:"#00ff41",warning:"yellow",danger:"red",info:"cyan",statusOn:"#00ff41",statusOff:"#00661a",logoTextAnsi:"\x1B[1;32m",logoBodyAnsi:"\x1B[32m",logoMutedAnsi:"\x1B[90m",logoGradient:["#00ff41","#ffff00"]},{name:"Warm Sunset",text:"#ffaa55",textMuted:"#cc8844",textDim:"#885522",textInverted:"black",border:"#ff9933",borderMuted:"#aa6622",borderDim:"#663311",bg:void 0,cardBg:"#24180f",highlightBg:"#2e1e12",activeBg:"#422c1b",inputBg:"#2e1e12",inputBorder:"#2e1e12",inputText:"#ffaa55",inputPlaceholder:"#885522",inputPrompt:"#ff7733",codeBg:"#120c08",codeBorder:"#aa6622",userMsgBg:"#2e1e12",userMsgBorder:"#2e1e12",userMsgText:"#ffaa55",diffRemovalBg:"#3d120c",diffAdditionBg:"#3a2e0c",diffRemovalText:"#ff5544",diffAdditionText:"#ffcc33",diffRemovalHighlightColor:"#ff3322",diffRemovalHighlightBg:"#591108",diffAdditionHighlightColor:"#ffee44",diffAdditionHighlightBg:"#594400",diffRemovalNum:"#ff5544",diffAdditionNum:"#ffcc33",diffRemovalPrefix:"#ff3322",diffAdditionPrefix:"#ffee44",primary:"#ffaa55",secondary:"#ff7733",accent:"magenta",success:"#ffcc33",warning:"#ff7733",danger:"#ff3322",info:"#ffaa55",statusOn:"#ffaa55",statusOff:"#885522",logoTextAnsi:"\x1B[1;33m",logoBodyAnsi:"\x1B[33m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ff9933","#ff0055"]},{name:"Sakura Blossom",text:"#ffc0e0",textMuted:"#d98cb3",textDim:"#804d66",textInverted:"black",border:"#ff99cc",borderMuted:"#aa4d7a",borderDim:"#662647",bg:void 0,cardBg:"#291320",highlightBg:"#331826",activeBg:"#472235",inputBg:"#331826",inputBorder:"#331826",inputText:"#ffc0e0",inputPlaceholder:"#804d66",inputPrompt:"#ff99cc",codeBg:"#140a10",codeBorder:"#aa4d7a",userMsgBg:"#331826",userMsgBorder:"#331826",userMsgText:"#ffc0e0",diffRemovalBg:"#3e0c1b",diffAdditionBg:"#1b3e2b",diffRemovalText:"#ff6699",diffAdditionText:"#66ffb3",diffRemovalHighlightColor:"#ff3377",diffRemovalHighlightBg:"#590022",diffAdditionHighlightColor:"#33ff99",diffAdditionHighlightBg:"#00592e",diffRemovalNum:"#ff6699",diffAdditionNum:"#66ffb3",diffRemovalPrefix:"#ff3377",diffAdditionPrefix:"#33ff99",primary:"#ffc0e0",secondary:"#ff99cc",accent:"magenta",success:"#66ffb3",warning:"yellow",danger:"#ff3377",info:"#ff99cc",statusOn:"#ffc0e0",statusOff:"#804d66",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ffb3d9","#ff3399"]},{name:"Radioactive Slime",text:"#ccff00",textMuted:"#99cc00",textDim:"#669900",textInverted:"#0a0f00",border:"#ccff00",borderMuted:"#99cc00",borderDim:"#669900",bg:void 0,cardBg:"#0f1400",highlightBg:"#1a2400",activeBg:"#2a3b00",inputBg:"#1a2400",inputBorder:"#1a2400",inputText:"#ccff00",inputPlaceholder:"#669900",inputPrompt:"#cc00ff",codeBg:"#050a00",codeBorder:"#99cc00",userMsgBg:"#1a2400",userMsgBorder:"#1a2400",userMsgText:"#ccff00",diffRemovalBg:"#2a0033",diffAdditionBg:"#0f3300",diffRemovalText:"#ff00cc",diffAdditionText:"#00ff33",diffRemovalHighlightColor:"#ff33cc",diffRemovalHighlightBg:"#4d0066",diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:"#1a6600",diffRemovalNum:"#ff00cc",diffAdditionNum:"#00ff33",diffRemovalPrefix:"#ff33cc",diffAdditionPrefix:"#33ff66",primary:"#ccff00",secondary:"#cc00ff",accent:"#ff00cc",success:"#00ff33",warning:"#ffcc00",danger:"#ff0033",info:"#00ccff",statusOn:"#ccff00",statusOff:"#669900",logoTextAnsi:"\x1B[1;38;5;190m",logoBodyAnsi:"\x1B[38;5;190m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ccff00","#cc00ff"]},{name:"Cosmic Void",text:"#f0f8ff",textMuted:"#a6aeb5",textDim:"#5e656e",textInverted:"#010103",border:"#f0f8ff",borderMuted:"#a6aeb5",borderDim:"#5e656e",bg:void 0,cardBg:"#05030d",highlightBg:"#0b081a",activeBg:"#171133",inputBg:"#0b081a",inputBorder:"#0b081a",inputText:"#f0f8ff",inputPlaceholder:"#5e656e",inputPrompt:"#ff007f",codeBg:"#020108",codeBorder:"#a6aeb5",userMsgBg:"#0b081a",userMsgBorder:"#0b081a",userMsgText:"#f0f8ff",diffRemovalBg:"#2e0a29",diffAdditionBg:"#091c33",diffRemovalText:"#ff33a6",diffAdditionText:"#33d6ff",diffRemovalHighlightColor:"#ff66c2",diffRemovalHighlightBg:"#5c1452",diffAdditionHighlightColor:"#66e0ff",diffAdditionHighlightBg:"#123866",diffRemovalNum:"#ff33a6",diffAdditionNum:"#33d6ff",diffRemovalPrefix:"#ff66c2",diffAdditionPrefix:"#66e0ff",primary:"#f0f8ff",secondary:"#ff007f",accent:"#9d00ff",success:"#33d6ff",warning:"#ffcc00",danger:"#ff0040",info:"#9d00ff",statusOn:"#f0f8ff",statusOff:"#5e656e",logoTextAnsi:"\x1B[1;38;5;231m",logoBodyAnsi:"\x1B[38;5;231m",logoMutedAnsi:"\x1B[38;5;240m",logoGradient:["#ffffff","#9d00ff"]},{name:"Magma Eruption",text:"#ff4d00",textMuted:"#cc3d00",textDim:"#802600",textInverted:"#0d0300",border:"#ff4d00",borderMuted:"#cc3d00",borderDim:"#802600",bg:void 0,cardBg:"#1a0600",highlightBg:"#260a00",activeBg:"#401100",inputBg:"#260a00",inputBorder:"#260a00",inputText:"#ff4d00",inputPlaceholder:"#802600",inputPrompt:"#ffcc00",codeBg:"#080200",codeBorder:"#cc3d00",userMsgBg:"#260a00",userMsgBorder:"#260a00",userMsgText:"#ff4d00",diffRemovalBg:"#2e0a0a",diffAdditionBg:"#1f1400",diffRemovalText:"#ff3333",diffAdditionText:"#ffaa00",diffRemovalHighlightColor:"#ff6666",diffRemovalHighlightBg:"#5c1414",diffAdditionHighlightColor:"#ffcc33",diffAdditionHighlightBg:"#3d2900",diffRemovalNum:"#ff3333",diffAdditionNum:"#ffaa00",diffRemovalPrefix:"#ff6666",diffAdditionPrefix:"#ffcc33",primary:"#ff4d00",secondary:"#ffcc00",accent:"#ff0040",success:"#ffaa00",warning:"#ffff00",danger:"#ff0000",info:"#ff8800",statusOn:"#ff4d00",statusOff:"#802600",logoTextAnsi:"\x1B[1;38;5;202m",logoBodyAnsi:"\x1B[38;5;202m",logoMutedAnsi:"\x1B[38;5;236m",logoGradient:["#ff4d00","#ff0000"]}],uo={Dark:{id:"Dark",name:"Dark (Default)",text:"white",textMuted:"gray",textDim:"grey",textInverted:"black",textExclusive:"#B5B8D9",textMutedExclusive:"#D4DEE7",border:"white",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:"#1e1e1e",highlightBg:"#2a2a2a",activeBg:"#3a3a3a",inputBg:"#555555",inputBorder:"#555555",inputText:"white",inputPlaceholder:"#cccccc",inputPrompt:"white",codeBg:"#1a1a1a",codeBorder:"#444444",userMsgBg:"#444444",userMsgBorder:"#444444",userMsgText:"white",diffRemovalBg:"#250808",diffAdditionBg:"#072410",diffRemovalText:"#885555",diffAdditionText:"#558866",diffRemovalHighlightColor:"#ff3333",diffRemovalHighlightBg:"#5a1818",diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:"#185a25",diffRemovalNum:"#d96868",diffAdditionNum:"#68d98c",diffRemovalPrefix:"#ff4d4d",diffAdditionPrefix:"#4dff88",primary:"white",secondary:"cyan",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"white",statusOff:"gray",logoTextAnsi:"\x1B[1;37m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#0077ff","#ff00ff"]},Light:{id:"Light",name:"Light",text:"black",textMuted:"gray",textDim:"grey",textInverted:"white",border:"black",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:"#e5e5e5",highlightBg:"#d4d4d4",activeBg:"#c0c0c0",inputBg:"#d0d0d0",inputBorder:"#d0d0d0",inputText:"black",inputPlaceholder:"#555555",inputPrompt:"black",codeBg:"#e8e8e8",codeBorder:"#b0b0b0",userMsgBg:"#d0d0d0",userMsgBorder:"#d0d0d0",userMsgText:"black",diffRemovalBg:"#fce8e8",diffAdditionBg:"#e6f9e6",diffRemovalText:"#661111",diffAdditionText:"#115511",diffRemovalHighlightColor:"#440000",diffRemovalHighlightBg:"#f8b4b4",diffAdditionHighlightColor:"#003300",diffAdditionHighlightBg:"#a6ebad",diffRemovalNum:"#c02020",diffAdditionNum:"#188028",diffRemovalPrefix:"#d01010",diffAdditionPrefix:"#109020",primary:"black",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"black",statusOff:"gray",logoTextAnsi:"\x1B[1;30m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#0077ff","#ff00ff"]},"GitHub Dark":{id:"GitHub Dark",name:"GitHub Dark",text:"#c9d1d9",textMuted:"#8b949e",textDim:"#6e7681",textInverted:"#0d1117",border:"#30363d",borderMuted:"#30363d",borderDim:"#21262d",bg:void 0,cardBg:"#161b22",highlightBg:"#21262d",activeBg:"#30363d",inputBg:"#21262d",inputBorder:"#21262d",inputText:"#c9d1d9",inputPlaceholder:"#8b949e",inputPrompt:"#58a6ff",codeBg:"#0d1117",codeBorder:"#30363d",userMsgBg:"#21262d",userMsgBorder:"#21262d",userMsgText:"#c9d1d9",diffRemovalBg:"#3c1e1e",diffAdditionBg:"#11381e",diffRemovalText:"#f85149",diffAdditionText:"#3fb950",diffRemovalHighlightColor:"#ff7b72",diffRemovalHighlightBg:"#701c1c",diffAdditionHighlightColor:"#56d364",diffAdditionHighlightBg:"#116329",diffRemovalNum:"#f85149",diffAdditionNum:"#3fb950",diffRemovalPrefix:"#f85149",diffAdditionPrefix:"#3fb950",primary:"#c9d1d9",secondary:"#58a6ff",accent:"#bc8cff",success:"#3fb950",warning:"#d29922",danger:"#f85149",info:"#58a6ff",statusOn:"#58a6ff",statusOff:"#8b949e",logoTextAnsi:"\x1B[1;36m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#2ea043","#56d364"]},"GitHub Light":{id:"GitHub Light",name:"GitHub Light",text:"#24292f",textMuted:"#57606a",textDim:"#6e7781",textInverted:"#ffffff",border:"#d0d7de",borderMuted:"#d0d7de",borderDim:"#e1e4e8",bg:void 0,cardBg:"#f6f8fa",highlightBg:"#eaeef2",activeBg:"#d0d7de",inputBg:"#eaeef2",inputBorder:"#eaeef2",inputText:"#24292f",inputPlaceholder:"#57606a",inputPrompt:"#0969da",codeBg:"#ffffff",codeBorder:"#d0d7de",userMsgBg:"#eaeef2",userMsgBorder:"#eaeef2",userMsgText:"#24292f",diffRemovalBg:"#ffebe9",diffAdditionBg:"#e6ffec",diffRemovalText:"#cf222e",diffAdditionText:"#1a7f37",diffRemovalHighlightColor:"#82071e",diffRemovalHighlightBg:"#ffc1c0",diffAdditionHighlightColor:"#116329",diffAdditionHighlightBg:"#acf2bd",diffRemovalNum:"#cf222e",diffAdditionNum:"#1a7f37",diffRemovalPrefix:"#cf222e",diffAdditionPrefix:"#1a7f37",primary:"#24292f",secondary:"#0969da",accent:"#8250df",success:"#1a7f37",warning:"#9a6700",danger:"#cf222e",info:"#0969da",statusOn:"#0969da",statusOff:"#57606a",logoTextAnsi:"\x1B[1;34m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#1a7f37","#2da44e"]},"Transparent Dark":{id:"Transparent Dark",name:"Transparent Dark",text:"white",textMuted:"gray",textDim:"grey",textInverted:"black",border:"gray",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:void 0,highlightBg:"#2a2a2a",activeBg:"#3a3a3a",inputBg:"#555555",inputBorder:"#555555",inputText:"white",inputPlaceholder:"#cccccc",inputPrompt:"white",codeBg:void 0,codeBorder:"gray",userMsgBg:"#555555",userMsgBorder:"#555555",userMsgText:"white",diffRemovalBg:void 0,diffAdditionBg:void 0,diffRemovalText:"#ff6666",diffAdditionText:"#66ff66",diffRemovalHighlightColor:"#ff3333",diffRemovalHighlightBg:void 0,diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:void 0,diffRemovalNum:"#ff6666",diffAdditionNum:"#66ff66",diffRemovalPrefix:"#ff4d4d",diffAdditionPrefix:"#4dff88",primary:"white",secondary:"cyan",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"white",statusOff:"gray",logoTextAnsi:"\x1B[1;37m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#0077ff","#ff00ff"]},"Transparent Light":{id:"Transparent Light",name:"Transparent Light",text:"black",textMuted:"gray",textDim:"grey",textInverted:"white",border:"gray",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:void 0,highlightBg:"#d4d4d4",activeBg:"#c0c0c0",inputBg:"#d0d0d0",inputBorder:"#d0d0d0",inputText:"black",inputPlaceholder:"#555555",inputPrompt:"black",codeBg:void 0,codeBorder:"gray",userMsgBg:"#d0d0d0",userMsgBorder:"#d0d0d0",userMsgText:"black",diffRemovalBg:void 0,diffAdditionBg:void 0,diffRemovalText:"#c02020",diffAdditionText:"#188028",diffRemovalHighlightColor:"#800000",diffRemovalHighlightBg:void 0,diffAdditionHighlightColor:"#004000",diffAdditionHighlightBg:void 0,diffRemovalNum:"#c02020",diffAdditionNum:"#188028",diffRemovalPrefix:"#d01010",diffAdditionPrefix:"#109020",primary:"black",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"black",statusOff:"gray",logoTextAnsi:"\x1B[1;30m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#0077ff","#ff00ff"]},"Synthwave 84":{id:"Synthwave 84",name:"Synthwave 84",text:"#fdfdfd",textMuted:"#a08eb7",textDim:"#705c8a",textInverted:"#1a1025",textExclusive:"#e3dcf0",textMutedExclusive:"#b9abc9",border:"#fc28a8",borderMuted:"#a21568",borderDim:"#5c0a3a",bg:void 0,cardBg:"#261b38",highlightBg:"#35254d",activeBg:"#4c3570",inputBg:"#35254d",inputBorder:"#35254d",inputText:"#fdfdfd",inputPlaceholder:"#a08eb7",inputPrompt:"#03e8fc",codeBg:"#1e142b",codeBorder:"#a21568",userMsgBg:"#35254d",userMsgBorder:"#35254d",userMsgText:"#fdfdfd",diffRemovalBg:"#471434",diffAdditionBg:"#144743",diffRemovalText:"#ff4081",diffAdditionText:"#00e5ff",diffRemovalHighlightColor:"#ff79a1",diffRemovalHighlightBg:"#6b1e4e",diffAdditionHighlightColor:"#66f5ff",diffAdditionHighlightBg:"#1e6b65",diffRemovalNum:"#ff4081",diffAdditionNum:"#00e5ff",diffRemovalPrefix:"#ff79a1",diffAdditionPrefix:"#66f5ff",primary:"#fdfdfd",secondary:"#03e8fc",accent:"#fc28a8",success:"#00e5ff",warning:"#ffc107",danger:"#ff4081",info:"#b388ff",statusOn:"#03e8fc",statusOff:"#a08eb7",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#fc28a8","#03e8fc"]},"Forest Sprite":{id:"Forest Sprite",name:"Forest Sprite",text:"#d6e6d1",textMuted:"#95b38d",textDim:"#628059",textInverted:"#161c14",textExclusive:"#eaf2e8",textMutedExclusive:"#a9c7a2",border:"#74a862",borderMuted:"#477038",borderDim:"#2b4720",bg:void 0,cardBg:"#1f291c",highlightBg:"#2a3826",activeBg:"#3a4d35",inputBg:"#2a3826",inputBorder:"#2a3826",inputText:"#d6e6d1",inputPlaceholder:"#95b38d",inputPrompt:"#8feb73",codeBg:"#161e14",codeBorder:"#477038",userMsgBg:"#2a3826",userMsgBorder:"#2a3826",userMsgText:"#d6e6d1",diffRemovalBg:"#3b231c",diffAdditionBg:"#203b1c",diffRemovalText:"#db6242",diffAdditionText:"#59cc3f",diffRemovalHighlightColor:"#f0896c",diffRemovalHighlightBg:"#5c362a",diffAdditionHighlightColor:"#80e368",diffAdditionHighlightBg:"#305929",diffRemovalNum:"#db6242",diffAdditionNum:"#59cc3f",diffRemovalPrefix:"#f0896c",diffAdditionPrefix:"#80e368",primary:"#d6e6d1",secondary:"#8feb73",accent:"#e69835",success:"#59cc3f",warning:"#e69835",danger:"#db6242",info:"#73b4eb",statusOn:"#8feb73",statusOff:"#95b38d",logoTextAnsi:"\x1B[1;32m",logoBodyAnsi:"\x1B[32m",logoMutedAnsi:"\x1B[90m",logoGradient:["#8feb73","#e69835"]}};var Fo=null;var ba=(e="Dark")=>{let n;e==="Mystery"||e==="Chaos"?(Fo||(Fo=xa[Math.floor(Math.random()*xa.length)]),n={...Fo,id:"Mystery"}):(Fo=null,uo[e]?n=uo[e]:e==="GitHub"?n=uo["GitHub Dark"]:e==="Transparent"?n=uo["Transparent Dark"]:n=uo.Dark);let t=n.codeText||n.secondary||n.info||n.logoGradient&&n.logoGradient[0]||"cyan";return{...n,codeText:t}};var ac=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",Fp=(e=2)=>{let n=ac();return n==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)},Np=(e="...",n="Loading...",t="Dark")=>{let o=Zr[Math.floor(Math.random()*Zr.length)],s=ba(t),r=s.logoTextAnsi,a=s.logoBodyAnsi,i=s.logoMutedAnsi,h="\x1B[0m",d=[" \u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2588\u2588\u2588\u2591 "," \u2588\u2588\u2588\u2591 "," \u2588\u2588\u2588\u2591 "," \u2591\u2591\u2591 "],c=s.logoGradient||["#0077ff","#ff00ff"],l=ic(c).multiline(d.join(`
|
|
486
|
-
`)).split(`
|
|
487
|
-
`),f=u=>`${i}${u}${h}`;return`${l[0]}
|
|
488
|
-
${l[1]} ${r}Selected Provider: ${n}${h}
|
|
489
|
-
${l[2]}
|
|
490
|
-
${l[3]} ${r}FluxFlow ${f("v"+e)}${h}
|
|
491
|
-
${l[4]}
|
|
492
|
-
${l[5]} ${a}See /help for additional commands.${h}
|
|
493
|
-
${l[6]} ${f(o)}
|
|
494
|
-
${l[7]}`};import{WebSocket as No}from"ws";var Vt=null,Ns=!1,lc="ws://localhost:56832",ei=[],Bs=null,ti=null,ka="2.0.0",Wp=e=>{ka=e,Sa()},ni=e=>{ti=e},Sa=()=>{if(Vt||Ns)return;Ns=!0;let e=new No(lc);e.on("open",()=>{for(Vt=e,Ns=!1,Vt.send(JSON.stringify({command:"version",version:ka,pid:process.pid,ppid:process.ppid}));ei.length>0;)Vt.send(JSON.stringify(ei.shift()))}),e.on("message",n=>{try{let t=JSON.parse(n.toString());t.command==="contextResponse"&&Bs?(Bs(t.data),Bs=null):t.command==="securityResponse"&&ti&&ti(t.result)}catch{}}),e.on("error",()=>{Ns=!1,Vt=null}),e.on("close",()=>{Ns=!1,Vt=null})},Bo=e=>{Vt&&Vt.readyState===No.OPEN?Vt.send(JSON.stringify(e)):(ei.push(e),Ns||Sa())},Uo=()=>Vt!==null&&Vt.readyState===No.OPEN,jp=e=>{Bo({command:"status",status:e})},gs=()=>new Promise(e=>{if(!Vt||Vt.readyState!==No.OPEN){e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]});return}Bs=e,Vt.send(JSON.stringify({command:"requestContext"})),setTimeout(()=>{Bs===e&&(e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]}),Bs=null)},1e3)}),Ta=e=>{Bo({command:"open",filePath:e})},si=(e,n,t)=>{Bo({command:"showDiff",filePath:e,originalContent:n,modifiedContent:t})},Ra=(e,n)=>{Bo({command:"closeDiff",filePath:e,result:n})};import Ea from"path";import cc from"fs";var dc=e=>{try{return cc.readdirSync(e,{withFileTypes:!0})}catch{return[]}},oi=(e,n,t=1,o=dc,s=[],r=null)=>{let a=r||o(e),i=" ".repeat(t-1);if(a.length>100)return`${i}${Ea.basename(e)}/ (>100 files)
|
|
495
|
-
`;let h="",d=s,c=a.filter(p=>!d.includes(p.name)&&!p.name.startsWith(".")),l=a.filter(p=>d.includes(p.name)||p.name.startsWith(".")).map(p=>p.name).sort();l.length>0&&(h+=`${i}[ignored: ${l.map(p=>p+"/").join(", ")}]
|
|
496
|
-
`);let f=c.filter(p=>p.isDirectory()).sort((p,g)=>p.name.localeCompare(g.name)),u=c.filter(p=>!p.isDirectory()).map(p=>p.name).sort();for(let p of f){let g=Ea.join(e,p.name);if(t>n)h+=`${i}${p.name}/ (max depth)
|
|
497
|
-
`;else{let y=o(g);y.length>80?h+=`${i}${p.name}/ (>80 files)
|
|
498
|
-
`:(h+=`${i}${p.name}/
|
|
499
|
-
`,h+=oi(g,n,t+1,o,s,y))}}return u.length>0&&(h+=`${i}${u.join("; ")}
|
|
500
|
-
`),h};import ri from"path";import fc from"fs";var uc=e=>{try{return fc.readdirSync(e,{withFileTypes:!0})}catch{return[]}},ii=(e,n,t="",o=1,s=uc,r=[])=>{let a=s(e),i=ri.sep;if(a.length>100)return`${t}\u2514\u2500\u2500 ${ri.basename(e)}${i} ...100+ files...
|
|
501
|
-
`;let h="",d=r,c=a.filter(u=>!d.includes(u.name)&&!u.name.startsWith(".")),l=a.filter(u=>d.includes(u.name)||u.name.startsWith(".")).map(u=>u.name).sort();c.sort((u,p)=>u.isDirectory()&&!p.isDirectory()?-1:!u.isDirectory()&&p.isDirectory()?1:u.name.localeCompare(p.name));let f=[...c.map(u=>({name:u.name,isDir:u.isDirectory()})),...l.map(u=>({name:u,isDir:!0,isCollapsed:!0}))];return f.forEach((u,p)=>{let g=p===f.length-1,y=ri.join(e,u.name),m=g?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",w=t+(g?" ":"\u2502 ");if(u.isCollapsed){h+=`${t}${m}${u.name}${i}...
|
|
502
|
-
`;return}u.isDir?o>n?h+=`${t}${m}${u.name}${i} ...depth exceeded...
|
|
503
|
-
`:s(y).length>80?h+=`${t}${m}${u.name}${i} ...80+ files...
|
|
504
|
-
`:(h+=`${t}${m}${u.name}${i}
|
|
505
|
-
`,h+=ii(y,n,w,o+1,s,r)):h+=`${t}${m}${u.name}
|
|
506
|
-
`}),h};import"@google/genai";var Dt=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,h)=>{let d=setTimeout(()=>{s.removeEventListener("abort",c),i()},Math.min(24e3,o*Math.pow(2,a))),c=()=>{clearTimeout(d),h(new DOMException("The user aborted a request.","AbortError"))};s.addEventListener("abort",c)}):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 Wo(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 Dn=e=>typeof e!="string"?e:e.replace(/<\|channel>thought/gi,"<think>").replace(/<channel\|>/gi,"</think>");var jo=async function*(e,n,t,o,s,r,a,i,h=1){let d=[];o&&d.push({role:"system",content:o});for(let x of t){let S=x.role==="user"?"user":"assistant",C=[];if(Array.isArray(x.parts)){for(let R of x.parts)if(R.text)C.push({type:"text",text:R.text});else if(R.inlineData&&a){let k=R.inlineData.mimeType,T=R.inlineData.data;k.startsWith("image/")&&C.push({type:"image_url",image_url:{url:`data:${k};base64,${T}`}})}}else{let R=x.text||"";R&&C.push({type:"text",text:R})}d.push({role:S,content:C.length===1&&C[0].type==="text"?C[0].text:C})}let c={model:n,messages:d,stream:!0,stream_options:{include_usage:!0},temperature:h};if(s!=="Fast"){let x={Low:"high",Medium:"high",Standard:"high",High:"max",xHigh:"max"};c.reasoning_effort=x[s]||"high",c.extra_body={thinking:{type:"enabled"}}}else c.extra_body={thinking:{type:"disabled"}};let l=await Dt("https://api.deepseek.com/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(c),signal:i});if(!l.ok){let x=await l.json().catch(()=>({}));throw new Error(`DeepSeek Error (${l.status}): ${x.error?.message||l.statusText}`)}let f=l.body.getReader(),u=new TextDecoder,p="",g=[],y=null,m=Date.now(),w=!1;for(;;){let{done:x,value:S}=await f.read();if(x){w&&(g.length>0||y)&&(yield{candidates:g.length>0?[{content:{parts:g}}]:[],usageMetadata:y});break}p+=u.decode(S,{stream:!0});let C=p.split(`
|
|
507
|
-
`);p=C.pop();for(let R of C){let k=R.trim();if(!k||!k.startsWith("data: "))continue;let T=!1;if(k==="data: [DONE]")T=!0;else try{let _=JSON.parse(k.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},w=!0),E){let $=E.reasoning_content||null;$&&(g.push({text:$,thought:!0}),w=!0),E.content&&(g.push({text:E.content}),w=!0)}}catch{}if((T||Date.now()-m>=150)&&w&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],m=Date.now(),w=!1),T)break}Date.now()-m>=150&&w&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],m=Date.now(),w=!1)}};var Ho=async function*(e,n,t,o,s,r,a,i,h=1,d=null){let c=[];o&&c.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&&c.push({role:_,content:E.length===1&&E[0].type==="text"?E[0].text:E})}let l={Fast:"none",Low:"none",Medium:"high",Standard:"high",High:"high",xHigh:"high"},f=`${e.slice(-5)}${d||""}${s}${n}`,u=await Wo(f),p={model:n,messages:c,stream:!0,temperature:h,prompt_cache_key:u};s&&s!=="Fast"&&Cs(n)&&(p.reasoning_effort=l[s]||"high");let g=await Dt("https://api.mistral.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(p),signal:i});if(!g.ok){let T=await g.text().catch(()=>""),_=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,w="",x=[],S=null,C=Date.now(),R=!1,k=T=>T?typeof T=="string"?Dn(T):Array.isArray(T)?T.map(k).filter(Boolean).join(""):typeof T=="object"&&T!==null?typeof T.text=="string"?Dn(T.text):typeof T.content=="string"?Dn(T.content):typeof T.thinking=="string"?Dn(T.thinking):typeof T.reasoning_content=="string"?Dn(T.reasoning_content):typeof T.reasoning=="string"?Dn(T.reasoning):typeof T.value=="string"?Dn(T.value):T.text?k(T.text):T.content?k(T.content):T.thinking?k(T.thinking):T.reasoning_content?k(T.reasoning_content):T.reasoning?k(T.reasoning):T.value?k(T.value):"":Dn(String(T)):"";for(;;){let{done:T,value:_}=await y.read();if(T){R&&(x.length>0||S)&&(yield{candidates:x.length>0?[{content:{parts:x}}]:[],usageMetadata:S});break}w+=m.decode(_,{stream:!0});let E=w.split(`
|
|
508
|
-
`);w=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)),B=D.choices?.[0]?.delta,W=D.usage;if(D.choices?.[0]?.finish_reason&&(I=!0),W&&(S={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),B){let Y=B.thinking||B.reasoning_content||B.reasoning,X=k(Y);X&&(x.push({text:X,thought:!0}),R=!0);let fe=B.content||(!B.thinking&&!B.reasoning_content&&!B.reasoning?B.text:null);if(fe)if(Array.isArray(fe))for(let F of fe)if(typeof F=="object"&&F!==null){let U=F.type==="thinking"||F.type==="reasoning"||!!F.thought,se=k(F);se&&(x.push({text:se,...U?{thought:!0}:{}}),R=!0)}else{let U=k(F);U&&(x.push({text:U}),R=!0)}else if(typeof fe=="object"&&fe!==null){let F=fe.type==="thinking"||fe.type==="reasoning"||!!fe.thought,U=k(fe);U&&(x.push({text:U,...F?{thought:!0}:{}}),R=!0)}else{let F=k(fe);F&&(x.push({text:F}),R=!0)}}}catch{}if((I||Date.now()-C>=150)&&R&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:S},x=[],C=Date.now(),R=!1),I)break}Date.now()-C>=150&&R&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:S},x=[],C=Date.now(),R=!1)}};var Go=async function*(e,n,t,o,s,r,a=!1,i,h=1){let d=[];o&&d.push({role:"system",content:o}),t.forEach(se=>{let Ae=se.role==="model"?"assistant":"user",A=[];Array.isArray(se.parts)&&se.parts.forEach(N=>{if(N.text)A.push({type:"text",text:N.text});else if(N.inlineData&&a){let V=N.inlineData.mimeType,J=N.inlineData.data;V.startsWith("image/")&&Ot(n)&&A.push({type:"image_url",image_url:{url:`data:${V};base64,${J}`}})}}),d.push({role:Ae,content:A.length===1&&A[0].type==="text"?A[0].text:A})});let l={Fast:"Fast",Low:"Fast",Medium:"Standard",Standard:"Standard",High:"High",xHigh:"High"}[s]||"High",f=l!=="Fast",u=n.includes("kimi"),p=n.includes("gemma"),g=n.includes("deepseek"),y=n.includes("glm"),m=n.includes("mistral"),w=n.includes("minimax"),x=n.includes("gpt"),S=n.includes("qwen"),C=n.includes("nemotron"),R=n.includes("llama-3"),k=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"},B=w||g||T||_?16384:32768;B=process.env.NVIDIA_BASE_URL?1024:B,B=b?1024:B;let W={model:n,messages:d,max_tokens:B,stream:!0,stream_options:{include_usage:!0},temperature:h,...x&&{thinking:$[s]||"high"}};if(!(process.env.NVIDIA_BASE_URL||E||b))if(u)W.chat_template_kwargs={thinking:f};else if(p)W.chat_template_kwargs={enable_thinking:f};else if(g)if(f){let se=l==="High"?"max":"high";W.chat_template_kwargs={thinking:!0,reasoning_effort:se}}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":w&&n.includes("minimax-m3")?W.chat_template_kwargs={thinking_mode:f?"enabled":"disabled"}:S?W.chat_template_kwargs={enable_thinking:f}:C?l==="High"?W.chat_template_kwargs={enable_thinking:!0}:l==="Standard"?W.chat_template_kwargs={enable_thinking:!0,medium_effort:!0}:W.chat_template_kwargs={enable_thinking:!1}:k?f&&(W.extra_body={thinking_budget:parseInt(I[l]??"4096")}):T?W.chat_template_kwargs={enable_thinking:f}:_&&(W.reasoning_effort=D[l]||"medium");let Y=0,X=6,fe=!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<X;){Y++;try{let se=await Dt(F,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${U}`},body:JSON.stringify(W),signal:i});if(!se.ok){let je=await se.text().catch(()=>""),at=se.statusText;try{let bt=JSON.parse(je);at=bt.error?.message||bt.message||JSON.stringify(bt.detail||bt)}catch{je&&(at=je)}let ze=new Error(`NVIDIA API Error (${se.status}): ${at}`);throw ze.status=se.status,ze}let Ae=se.body.getReader(),A=new TextDecoder,N="",V=[],J=null,Ue=Date.now(),Fe=!1;for(;;){let{done:je,value:at}=await Ae.read();if(je){Fe&&(V.length>0||J)&&(yield{candidates:V.length>0?[{content:{parts:V}}]:[],usageMetadata:J},fe=!0);break}N+=A.decode(at,{stream:!0});let ze=N.split(`
|
|
509
|
-
`);N=ze.pop();let bt=!1;for(let Wt of ze){let gt=Wt.trim();if(gt){if(gt==="data: [DONE]"){bt=!0;break}if(gt.startsWith("data: ")){let kt;try{kt=JSON.parse(gt.substring(6))}catch{continue}if(kt.error)throw new Error(`NVIDIA Stream Error: ${kt.error.message||JSON.stringify(kt.error)}`);try{let Rt=kt.usage;Rt&&(J={totalTokenCount:Rt.total_tokens||Rt.prompt_tokens+Rt.completion_tokens,promptTokenCount:Rt.prompt_tokens||0,candidatesTokenCount:Rt.completion_tokens||0,cachedContentTokenCount:Rt.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:(Rt.completion_tokens_details?.reasoning_tokens||0)+(Rt.completion_tokens_details?.thoughts_tokens||0)},Fe=!0);let lt=kt.choices?.[0]?.delta?.reasoning||kt.choices?.[0]?.delta?.reasoning_content||"",Se=kt.choices?.[0]?.delta?.content||"";lt&&(V.push({text:lt,thought:!0}),Fe=!0),Se&&(V.push({text:Se}),Fe=!0)}catch{}}}}if((bt||Date.now()-Ue>=350)&&Fe&&(yield{candidates:V.length>0?[{content:{parts:[...V]}}]:[],usageMetadata:J},fe=!0,V=[],Ue=Date.now(),Fe=!1),bt)break}break}catch(se){if(fe||Y>=X)throw se;await new Promise(Ae=>setTimeout(Ae,3500))}}},_a=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 h=`https://api.ngc.nvidia.com/v2/predict/queues/models/qc69jvmznzxy/${i}`,d=!1,c=null,l=async()=>{try{let f=await fetch(h);if(f.ok){let u=await f.json();if(u&&u.queues&&u.queues[0]&&typeof u.queues[0].queueDepth=="number"){let p=u.queues[0].queueDepth;d||a({value:{type:"status",content:`Queue ${p||1}`},done:!1})}}}catch{}};process.env.NVIDIA_BASE_URL||(l(),c=setInterval(l,5e3)),(async()=>{try{let f=e[Symbol.asyncIterator]();for(;;){let{value:u,done:p}=await f.next();if(p)break;d=!0,c&&(clearInterval(c),c=null),a({value:u,done:!1})}s=!0,a(null)}catch(f){if(r=f,c&&(clearInterval(c),c=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{c&&(clearInterval(c),c=null)}};var qo=async function*(e,n,t,o,s,r,a,i,h=1,d=null){let c=[];o&&c.push({role:"system",content:[{type:"text",text:o}]});for(let E of t){let b=E.role==="user"?"user":"assistant",$=[];if(Array.isArray(E.parts)){for(let I of E.parts)if(I.text)$.push({type:"text",text:I.text});else if(I.inlineData&&a){let D=I.inlineData.mimeType,B=I.inlineData.data;D.startsWith("image/")?$.push({type:"image_url",image_url:{url:`data:${D};base64,${B}`}}):$.push({type:"file",file:{filename:I.filename||"file",file_data:`data:${D};base64,${B}`}})}}else{let I=E.text||"";I&&$.push({type:"text",text:I})}c.push({role:b,content:$.length===1&&$[0].type==="text"?$[0].text:$})}let l={Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},f=n,u=null;if(n.includes(":")){let[E,...b]=n.split(":");f=E.trim();let $=b.join(":").toLowerCase().trim();$&&(u={order:[$],allow_fallbacks:!1})}let p=`${e.slice(-5)}${d||""}${s}${f}${u?JSON.stringify(u):""}`,g=await Wo(p),y={model:f,messages:c,stream:!0,temperature:h,cache_control:{type:"ephemeral"},session_id:g};u&&(y.provider=u);let m=l[s];m&&s!=="Fast"&&(y.reasoning_effort=m);let w=await Dt("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(y),signal:i});if(!w.ok){let E=await w.json().catch(()=>({}));throw new Error(`OpenRouter Error (${w.status}): ${E.error?.metadata.raw||E.error?.message||w.statusText}`)}let x=w.body.getReader(),S=new TextDecoder,C="",R=[],k=null,T=Date.now(),_=!1;for(;;){let{done:E,value:b}=await x.read();if(E){_&&(R.length>0||k)&&(yield{candidates:R.length>0?[{content:{parts:R}}]:[],usageMetadata:k});break}C+=S.decode(b,{stream:!0});let $=C.split(`
|
|
510
|
-
`);C=$.pop();for(let I of $){let D=I.trim();if(!D||!D.startsWith("data: "))continue;let B=!1;if(D==="data: [DONE]")B=!0;else try{let W=JSON.parse(D.substring(6)),Y=W.choices?.[0]?.delta,X=W.usage;if(W.choices?.[0]?.finish_reason&&(B=!0),X&&(k={totalTokenCount:X.total_tokens||(X.prompt_tokens||0)+(X.completion_tokens||0),promptTokenCount:X.prompt_tokens||0,candidatesTokenCount:X.completion_tokens||0,cachedContentTokenCount:X.prompt_tokens_details?.cached_tokens||X.prompt_tokens_details?.cache_read_input_tokens||X.cache_read_input_tokens||0,thoughtsTokenCount:X.completion_tokens_details?.reasoning_tokens||0},_=!0),Y){let fe=Y.reasoning||(Y.reasoning_details?Y.reasoning_details.map(F=>F.text).join(""):null);fe&&(R.push({text:fe,thought:!0}),_=!0),Y.content&&(R.push({text:Y.content}),_=!0)}}catch{}if((B||Date.now()-T>=150)&&_&&(yield{candidates:R.length>0?[{content:{parts:[...R]}}]:[],usageMetadata:k},R=[],T=Date.now(),_=!1),B)break}}};import{Ollama as hc}from"ollama";var ai=async function*(e,n,t,o,s,r,a,i,h=1,d="Cloud"){let c=[];o&&c.push({role:"system",content:o});for(let k of t){let T=k.role==="user"?"user":"assistant",_="",E=[];if(Array.isArray(k.parts)){_=k.parts.map(b=>b.text||"").filter(Boolean).join(`
|
|
511
|
-
`);for(let b of k.parts){let $=b.inlineData||b.inline_data;$&&$.data&&E.push($.data)}}else _=k.text||"";if(_||E.length>0){let b={role:T,content:_};E.length>0&&(b.images=E),c.push(b)}}let l=d==="Local"||!e||e==="LOCAL",u={host:l?process.env.OLLAMA_HOST||"http://127.0.0.1:11434":process.env.OLLAMA_HOST||"https://ollama.com"};!l&&e&&(u.headers={Authorization:"Bearer "+e});let p=new hc(u),g=[],y=null,m=Date.now(),w=!1,x={Fast:!1,Low:"medium",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},S=x[s]!==void 0?x[s]:!0,C={model:n,messages:c,stream:!0,think:S,keep_alive:"10m",options:{temperature:h}},R=await p.chat(C);for await(let k of R){if(i?.aborted)throw new DOMException("The user aborted a request.","AbortError");if(k.message?.thinking&&(g.push({text:k.message.thinking,thought:!0}),w=!0),k.message?.content&&(g.push({text:k.message.content}),w=!0),k.done){let T=k.prompt_cached_count||0;if(!T&&k.prompt_eval_count){let _=k.prompt_eval_duration||0;_>0&&_<5e7&&(T=k.prompt_eval_count)}y={totalTokenCount:(k.prompt_eval_count||0)+(k.eval_count||0),promptTokenCount:k.prompt_eval_count||0,candidatesTokenCount:k.eval_count||0,cachedContentTokenCount:T,thoughtsTokenCount:0},w=!0}(k.done||Date.now()-m>=150&&w)&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],m=Date.now(),w=!1)}w&&(g.length>0||y)&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y})};var zo=async function*(e,n,t,o,s,r,a,i,h=1){let d=[];o&&d.push({role:"system",content:o});for(let S of t){let C=S.role==="user"?"user":"assistant",R=[];if(Array.isArray(S.parts)){for(let k of S.parts)if(k.text)R.push({type:"text",text:k.text});else if(k.inlineData&&a){let T=k.inlineData.mimeType,_=k.inlineData.data;T.startsWith("image/")&&R.push({type:"image_url",image_url:{url:`data:${T};base64,${_}`}})}}else{let k=S.text||"";k&&R.push({type:"text",text:k})}d.push({role:C,content:R.length===1&&R[0].type==="text"?R[0].text:R})}let c={Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},l={model:n,messages:d,stream:!0,stream_options:{include_usage:!0},temperature:h,max_completion_tokens:32768};c[s]&&(l.reasoning_effort=c[s]);let f=await Dt("https://crof.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(l),signal:i});if(!f.ok){let S=await f.json().catch(()=>({}));throw new Error(`CrofAI Error (${f.status}): ${S.error?.message||f.statusText}`)}let u=f.body.getReader(),p=new TextDecoder,g="",y=[],m=null,w=Date.now(),x=!1;for(;;){let{done:S,value:C}=await u.read();if(S){x&&(y.length>0||m)&&(yield{candidates:y.length>0?[{content:{parts:y}}]:[],usageMetadata:m});break}g+=p.decode(C,{stream:!0});let R=g.split(`
|
|
512
|
-
`);g=R.pop();for(let k of R){let T=k.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},x=!0),b){let I=b.reasoning_content||null;I&&(y.push({text:I,thought:!0}),x=!0),b.content&&(y.push({text:b.content}),x=!0)}}catch{}if((_||Date.now()-w>=150)&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),x=!1),_)break}Date.now()-w>=150&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),x=!1)}};var Ko=async function*(e,n,t,o,s,r,a,i,h=1){let d=[];o&&d.push({role:"system",content:o});for(let S of t){let C=S.role==="user"?"user":"assistant",R="";if(Array.isArray(S.parts))for(let k of S.parts)k.text&&(R+=(R?`
|
|
513
|
-
`:"")+k.text);else R=S.text||"";d.push({role:C,content:R})}let c={Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},l={model:n,messages:d,stream:!0,stream_options:{include_usage:!0},temperature:h};c[s]&&(l.reasoning_effort=c[s]);let f=await Dt("https://model.inferx.net/endpoints/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(l),signal:i});if(!f.ok){let S=await f.json().catch(()=>({}));throw new Error(`InferX Error (${f.status}): ${S.error?.message||f.statusText||String(S)}`)}let u=f.body.getReader(),p=new TextDecoder,g="",y=[],m=null,w=Date.now(),x=!1;for(;;){let{done:S,value:C}=await u.read();if(S){x&&(y.length>0||m)&&(yield{candidates:y.length>0?[{content:{parts:y}}]:[],usageMetadata:m});break}g+=p.decode(C,{stream:!0});let R=g.split(`
|
|
514
|
-
`);g=R.pop();for(let k of R){let T=k.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},x=!0),b){let I=b.reasoning||b.reasoning_content||null;I&&(y.push({text:I,thought:!0}),x=!0),b.content&&(y.push({text:b.content}),x=!0)}}catch{}if((_||Date.now()-w>=150||m)&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),x=!1),_)break}Date.now()-w>=150&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),x=!1)}};var Yo=async function*(e,n,t,o,s,r,a,i,h=1){let d=[];o&&d.push({role:"system",content:o});for(let S of t){let C=S.role==="user"?"user":"assistant",R=[];if(Array.isArray(S.parts)){for(let k of S.parts)if(k.text)R.push({type:"text",text:k.text});else if(k.inlineData&&a){let T=k.inlineData.mimeType,_=k.inlineData.data;T.startsWith("image/")&&R.push({type:"image_url",image_url:{url:`data:${T};base64,${_}`}})}}else{let k=S.text||"";k&&R.push({type:"text",text:k})}d.push({role:C,content:R.length===1&&R[0].type==="text"?R[0].text:R})}let c={Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},l={model:n,messages:d,stream:!0,stream_options:{include_usage:!0},temperature:h};c[s]&&(l.reasoning_effort=c[s]);let f=await Dt("https://token.sensenova.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(l),signal:i});if(!f.ok){let S=await f.json().catch(()=>({}));throw new Error(`SenseNova Error (${f.status}): ${S.error?.message||f.statusText}`)}let u=f.body.getReader(),p=new TextDecoder,g="",y=[],m=null,w=Date.now(),x=!1;for(;;){let{done:S,value:C}=await u.read();if(S){x&&(y.length>0||m)&&(yield{candidates:y.length>0?[{content:{parts:y}}]:[],usageMetadata:m});break}g+=p.decode(C,{stream:!0});let R=g.split(`
|
|
515
|
-
`);g=R.pop();for(let k of R){let T=k.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},x=!0),b){let I=b.reasoning||b.reasoning_content||null;I&&(y.push({text:I,thought:!0}),x=!0),b.content&&(y.push({text:b.content}),x=!0)}}catch{}if((_||Date.now()-w>=150||m)&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),x=!1),_)break}Date.now()-w>=150&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),x=!1)}};var Vo=async function*(e,n,t,o,s,r,a,i,h=1){let d=[];o&&d.push({role:"system",content:o});for(let S of t){let C=S.role==="user"?"user":"assistant",R=[];if(Array.isArray(S.parts)){for(let k of S.parts)if(k.text)R.push({type:"text",text:k.text});else if(k.inlineData&&a){let T=k.inlineData.mimeType,_=k.inlineData.data;T.startsWith("image/")&&R.push({type:"image_url",image_url:{url:`data:${T};base64,${_}`}})}}else{let k=S.text||"";k&&R.push({type:"text",text:k})}d.push({role:C,content:R.length===1&&R[0].type==="text"?R[0].text:R})}let c={Fast:"minimal",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},l={model:n,messages:d,stream:!0,stream_options:{include_usage:!0},temperature:h};c[s]&&(l.reasoning_effort=c[s]);let f=await Dt("https://aihubmix.com/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(l),signal:i});if(!f.ok){let S=await f.json().catch(()=>({}));throw new Error(`AIHubMix Error (${f.status}): ${S.error?.message||f.statusText}`)}let u=f.body.getReader(),p=new TextDecoder,g="",y=[],m=null,w=Date.now(),x=!1;for(;;){let{done:S,value:C}=await u.read();if(S){x&&(y.length>0||m)&&(yield{candidates:y.length>0?[{content:{parts:y}}]:[],usageMetadata:m});break}g+=p.decode(C,{stream:!0});let R=g.split(`
|
|
516
|
-
`);g=R.pop();for(let k of R){let T=k.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},x=!0),b){let I=b.reasoning_content||null;I&&(y.push({text:I,thought:!0}),x=!0),b.content&&(y.push({text:b.content}),x=!0)}}catch{}if((_||Date.now()-w>=150)&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),x=!1),_)break}Date.now()-w>=150&&x&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:m},y=[],w=Date.now(),x=!1)}};ci.config({quiet:!0});ci.config({path:"./fluxflow.env",override:!0,quiet:!0});ci.config({path:"./.fluxflow.env",override:!0,quiet:!0});var pc=/```[\s\S]*?```/g,mc=/```[\s\S]*$/g,gc=/`[^`]+`/g,yc=/^\|.*\|$/gm,wc=/^[^\w]+|[^\w]+$/g,xc=/[^a-z0-9]/gi,ho=/\[\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*\\?["']?([^\\"' \),]+)/,ys=/["']/g,$a=/\\/g,Sc=/<\|channel>thought/gi,Tc=/<channel\|>/gi,Rc=e=>typeof e!="string"?e:e.replace(Sc,"<think>").replace(Tc,"</think>"),Ec=/(?:<(think|thought|thoughts)>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\])/gi,_c=/(?:<(think|thought|thoughts)>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*$/gi,Ca=/(?:<think>|<\|channel>thought|\[think\])[\s\S]*?(?:<\/think>|<channel\|>|\[\/think\]|$)/gi,Ma=/(?:<(think|thought|thoughts)>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\]|$)/gi,Fa=/`[^`]*`/g,Na=/`[^`]*$/,Aa=/<\|\s*tool_call_begin\s*\|>\s*(?:(?:tool|functions)\b[\s._]*)*([a-zA-Z0-9_]+)(?::\d+)?\s*<\|\s*tool_call_argument_begin\s*\|>([\s\S]*?)<\|\s*tool_call_end\s*\|>/gi,$c=/"([^"]+)"\s*:\s*(?:"([^"]*)"|(\d+)|true|false|null)/g,va=/<\|\s*tool_calls_section_begin\s*\|>/gi,Ia=/<\|\s*tool_calls_section_end\s*\|>/gi,Cc=/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi,Oa=/<(\w+)(?:[^>]*)>\r?\n?/gi,La=/\r?\n?<\/\w+(?:[^>]*)>/gi,di=null,Xo={},ws={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((h,d)=>{let c=setTimeout(h,i);s&&s.addEventListener("abort",()=>{clearTimeout(c),d(new DOMException("The user aborted a request.","AbortError"))})})}}},Pt=!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 h=i.indexOf("**CONTEXT SUMMARY OF PREVIOUS TURNS");if(h!==-1){let c=i.substring(0,h).lastIndexOf("[SYSTEM METADATA]");c!==-1?i=i.substring(c).trim():i=i.substring(h).trim()}}else{let h=i.lastIndexOf("[USER]"),d=i.lastIndexOf("[USER PROMPT]");h!==-1?i=i.substring(h+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=[],h=!1,d=()=>{a.length>0&&(t.push({role:"agent",text:"combined"}),a=[]),i.length>0&&(t.push({role:"system",text:"combined"}),i=[]),h=!1};r.forEach(c=>{let l=c.role==="system"&&(c.text?.startsWith("[TOOL RESULT]")||c.text?.startsWith("SUCCESS:")||c.text?.startsWith("ERROR:")||c.fullText?.startsWith("[TOOL RESULT]")||c.fullText?.startsWith("SUCCESS:")||c.fullText?.startsWith("ERROR:")),f=c.fullText||c.text||"",u=f.trim();if(!(!u&&!c.binaryPart)){if(l)i.push(u);else if(c.role==="agent"){!h&&i.length>0&&d();let p=f.endsWith(`
|
|
517
|
-
`),g=u.toLowerCase().includes("tool:functions.")||u.toLowerCase().includes("agent:generalist.");a.push(u),g&&p?h=!0:h=!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=()=>{Pt=!0},og=()=>Pt,li={write_file:"Writing",update_file:"Editing",read_folder:"Reading",view_file:"Reading",exec_command:"Executing Command",web_search:"Searching",web_scrape:"Reading",memory:"Updating Memory",search_keyword:"Searching",file_map:"Generating Map",ask:"User Input",write_pdf:"Creating",write_docx:"Creating",generate_image:"Generating",todo:"Planning",Todo:"Planning",goal:"Planning",Goal:"Planning",invoke_sync:"Sub-Agent Working",invoke:"Starting Agent",get_progress:"Checking Progress",cancel:"Cancelling",await:"Waiting",EmergencyRollback:"Don't Panic. Lookin' into it",answer:"Answering Sub-Agent",Answer:"Answering Sub-Agent",steer:"Steering Sub-Agent",Steer:"Steering Sub-Agent",Click:"Clicking",click:"Clicking",Drag:"Dragging",drag:"Dragging",Scroll:"Scrolling",scroll:"Scrolling",KeyboardTyping:"Typing",keyboard_typing:"Typing",KeyPress:"Pressing Key",key_press:"Pressing Key",RecaptureScreen:"Recapturing Screen",recapture_screen:"Recapturing Screen"},xs=(e,n)=>{try{let t=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?ee.basename(s.replace(/["']/g,"").replace(/\\/g,"/")):null}catch{return null}},fi=e=>e?new Pa({apiKey:e}):di,rg=async(e,n,t,o,s={})=>{let{onStatus:i,onMemoryUpdated:h,onBackgroundIncrement:d}=s,{profile:c,thinkingLevel:l,mode:f,janitorModel:u,chatId:p,systemSettings:g,sessionStats:y,aiProvider:m="Google",apiKey:w}=e,x=process.env.NVIDIA_BASE_URL||m==="Ollama"||m==="CrofAI"||m==="InferX"||m==="SenseNova"||m==="AIHubMix"?!1:g?.memory!==!1,C=Z(Nt,[]).map(A=>`- [${A.id}]: ${A.memory}`).join(`
|
|
518
|
-
`),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 N=vc(A.text).replace(/\[tool:functions\..*?\]/g,"").replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[METADATA \(PRIORITY: DYNAMIC\)\] Time: ([^|\n]+)/g,(Fe,je)=>`[METADATA (PRIORITY: DYNAMIC)] Time: ${je.replace(/:\d{2}/g,"")}`).replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[TOOL RESULTS\]/g,"").replace(/\[tool results\]/g,"").replace(/\r?\n\r?\n/g,`
|
|
519
|
-
`).replace(/\n\n/g,`
|
|
520
|
-
`).replace(/\\n\\n/g,"").trim(),V=A.role==="user"?8192:32768,J=N.substring(0,V);N.length>V&&(J+=`
|
|
521
|
-
... (truncated) ...`);let Ue=A.role==="user"?J.startsWith("[USER]")?"":"[USER]: ":J.startsWith("[AGENT]")?"":"[AGENT]: ";return{role:A.role==="user"?"user":"model",parts:[{text:`${Ue}${J}`}]}}),k=o.filter(A=>A.role==="user").length===1,T=n.includes("[TITLE-UPDATE]"),_=Math.random()<.8,E=k||T||_,b=t.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").trim(),$=vi(C,x,E),I=`${b.replace(/\[tool:functions\..*?\]/g,"").replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[\[TOOL RESULTS\]\]/g,"").replace(/\[tool results\]/g,"").substring(0,32768)}`;I.length>32768&&(I+=`
|
|
522
|
-
... (truncated) ...`);let D=n.replace(/\[Prompted on:.*?\]/g,"").trim();I=I.replace(/\r?\n\r?\n/g,`
|
|
523
|
-
`).replace(/\n\n/g,`
|
|
524
|
-
`).replace(/\\n\\n/g,"").trim();let B=new Date,Y=`[METADATA] Current date and Time: ${`${B.getFullYear()}-${B.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(B.getDate()).padStart(2,"0")}, ${B.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0})}`}
|
|
525
|
-
|
|
526
|
-
[USER]: ${D.substring(0,8192)}
|
|
527
|
-
${D.length>8192?`... (truncated) ...
|
|
528
|
-
|
|
529
|
-
`:""}
|
|
530
|
-
[AGENT (current turn)]: ${I}`;R.push({role:"user",parts:[{text:Y}]});let X=await ar("NVIDIA"),F=(await Bt()).quotas?.providerTiers?.NVIDIA==="Free",U="",se=0,Ae=x?12:-1;for(;se<=Ae;)try{if(!await Fi("background",e))return;let A="",N=null,V=!1,J=m;try{let je=new Promise((lt,Se)=>setTimeout(()=>Se(new Error("JANITOR_TIMEOUT")),1e4)),at=m==="Google"&&se>=0&&se<6&&X&&F,ze=m==="DeepSeek"&&se<4&&X&&F;V=at||ze,J=V?"NVIDIA":m;let bt=(async()=>{if(m==="OpenRouter"){let lt=_e("janitor_open_router"),oe=qo(w,lt,R,$,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),Xt=await oe.next();return{iterator:oe,firstResult:Xt}}else if(m==="DeepSeek"&&!V){let Se=jo(w,_e("deepseek_fast_fallback"),R,$,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),oe=await Se.next();return{iterator:Se,firstResult:oe}}else if(m==="Mistral"&&!V){let Se=Ho(w,_e("mistral_janitor_fallback"),R,$,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),oe=await Se.next();return{iterator:Se,firstResult:oe}}else if(m==="NVIDIA"||V){let Se=Go(V?X:w,_e("nvidia_janitor_fallback"),R,$,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),oe=await Se.next();return{iterator:Se,firstResult:oe}}else if(m==="CrofAI"){let Se=zo(w,targetModel||_e("crofai_fallback")||"deepseek-v4-flash-0731",R,$,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),oe=await Se.next();return{iterator:Se,firstResult:oe}}else if(m==="InferX"){let Se=Ko(w,targetModel||_e("inferx_fallback")||"deepseek-v4-flash",R,$,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),oe=await Se.next();return{iterator:Se,firstResult:oe}}else if(m==="SenseNova"){let Se=Yo(w,targetModel||_e("sensenova_fallback")||"sensenova-6.8-flash-lite",R,$,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),oe=await Se.next();return{iterator:Se,firstResult:oe}}else if(m==="AIHubMix"){let Se=Vo(w,targetModel||_e("aihubmix_fallback")||"gpt-4o-mini",R,$,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),oe=await Se.next();return{iterator:Se,firstResult:oe}}else{let oe=(await fi(w).models.generateContentStream({model:u||(se===Ae?_e("janitor_default"):_e("gemma_janitor_fallback_google")),contents:R,config:{systemInstruction:$,temperature:.7,safetySettings:[{category:Xn.HARM_CATEGORY_HARASSMENT,threshold:Vn.BLOCK_NONE},{category:Xn.HARM_CATEGORY_HATE_SPEECH,threshold:Vn.BLOCK_NONE},{category:Xn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Vn.BLOCK_NONE},{category:Xn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Vn.BLOCK_NONE}],thinkingConfig:{includeThoughts:!1,thinkingLevel:ut.MINIMAL}}}))[Symbol.asyncIterator](),Xt=await oe.next();return{iterator:oe,firstResult:Xt}}})();if(process.stdout.isTTY){let oe=(await ls())[p]?.name||"",Xt=oe&&!oe.startsWith("flow-")&&!oe.startsWith("Session ")?oe:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${Xt}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${Xt}\x07`)}let{iterator:Wt,firstResult:gt}=await Promise.race([bt,je]),{value:kt,done:Rt}=gt;if(!Rt&&kt){let lt=kt.candidates?.[0]?.content?.parts,Se=lt?J==="Google"?lt[1]?.text||lt[0]?.text||"":lt.filter(oe=>oe.text&&!oe.thought).map(oe=>oe.text).join(""):typeof kt.text=="function"?kt.text():"";Se&&(A+=Se),N=kt.usageMetadata;for await(let oe of{[Symbol.asyncIterator]:()=>Wt}){let Xt=oe.candidates?.[0]?.content?.parts,Jn=Xt?J==="Google"?Xt[1]?.text||Xt[0]?.text||"":Xt.filter(Qn=>Qn.text&&!Qn.thought).map(Qn=>Qn.text).join(""):typeof oe.text=="function"?oe.text():"";Jn&&(A+=Jn),N=oe.usageMetadata}}}catch(je){throw je}if(A){if(U=A,N){let je=N.totalTokenCount||0,at=N.cachedContentTokenCount||0,ze=(N.candidatesTokenCount||0)+(N.thoughtsTokenCount||0),bt=V?_e("nvidia_janitor_fallback"):J==="DeepSeek"?_e("deepseek_fast_fallback"):J==="OpenRouter"?_e("janitor_open_router"):u||(se===Ae?_e("janitor_default"):_e("gemma_janitor_fallback_google"));await Yt("tokens",je,J,bt),at>0&&await Yt("cachedTokens",at,J,bt),ze>0&&await Yt("candidateTokens",ze,J,bt)}}else throw new Error("No synthesis generated by Janitor.");d&&(d(),await Lt("background"));let Ue=Qo(U),Fe=!1;for(let je of Ue){let at=je.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(at)&&(Fe=!0);let ze={chatId:p,sessionId:p,history:o},bt=await fo(at,je.args,ze);at.toLowerCase()==="memory"&&(je.args.includes("action='user'")||je.args.includes('action="user"'))&&!bt.startsWith("ERROR")&&(h&&h(),process.stdout.isTTY&&(process.stdout.write("\x1B]0;Memory Updated\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=Memory Updated\x07")),await new Promise(gt=>setTimeout(gt,3e3)))}if(!Fe)try{let je=Z(Nt,[]);if(je.length>0){let at=[];for(let ze of je)ze.score===void 0&&(ze.score=.5),ze.score*=.99995,ze.score<.05&&(ze.score=0),ze.score=Math.round(ze.score*1e5)/1e5,ze.score>0&&at.push(ze);me(Nt,at)}}catch{}break}catch(A){se++;let N=new Date().toLocaleString(),V=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=ee.join(hn,"janitor");if(De.existsSync(J)||De.mkdirSync(J,{recursive:!0}),De.appendFileSync(ee.join(J,"error.log"),`ERROR [Attempt ${se}/${Ae+1}] [${N}]: ${V}
|
|
531
|
-
|
|
532
|
-
`),se>Ae)break;let Ue=Math.min(750*Math.pow(2,se-1),5e3);await new Promise(Fe=>setTimeout(Fe,Ue))}if(se){let A=ee.join(hn,"janitor");De.appendFileSync(ee.join(A,"error.log"),`-----------------------------------------------------------------------------
|
|
533
|
-
|
|
534
|
-
`)}if(process.stdout.isTTY)try{let V=(await ls())[p]?.name||"",J=V&&!V.startsWith("flow-")&&!V.startsWith("Session ")?V:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${J}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${J}\x07`)}catch{process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")}},Ic=e=>{let n=e.replace(Ec,"").replace(_c,""),t=Os?n:n.replace(Fa,s=>" ".repeat(s.length)).replace(Na,s=>" ".repeat(s.length));ho.lastIndex=0;let o;for(;(o=ho.exec(t))!==null;){let s=o.index+o[0].length-1,r=0,a=null,i=!1,h=!1;for(let d=s;d<t.length;d++){let c=n[d];if(!a&&(c==='"'||c==="'"||c==="`")?(a=c,i=!1):a&&c===a&&!i&&(a=null),!a&&(c==="("?r++:c===")"&&r--,r===0)){let l=d+1;for(;l<t.length&&/\s/.test(t[l]);)l++;if(l<t.length&&t[l]==="]"){h=!0,ho.lastIndex=l+1;break}}c==="\\"?i=!i:i=!1}if(!h)return{inside:!0,toolName:o[1],startIndex:o.index,args:n.substring(o.index+o[0].length)}}return{inside:!1}},Ba=(e,n=!0)=>{let t=ho;t.lastIndex=0;let o="",s=0,r;for(;(r=t.exec(e))!==null;){let a=e.substring(s,r.index);o+=n?a.replace(Ca,""):a;let i=r.index+r[0].length-1,h=0,d=null,c=-1;for(let l=i;l<e.length;l++){let f=e[l];if(d){if(f===d){let u=0;for(let p=l-1;p>=0&&e[p]==="\\";p--)u++;u%2===0&&(d=null)}}else if(f==='"'||f==="'"||f==="`")d=f;else if(f==="(")h++;else if(f===")"&&(h--,h===0)){let u=l+1;for(;u<e.length&&/\s/.test(e[u]);)u++;if(u<e.length&&e[u]==="]"){c=u;break}}}if(c!==-1)o+="[tool:functions."+r[1]+"()]",s=c+1,t.lastIndex=s;else{o+="[tool:functions."+r[1]+"(",s=e.length;break}}return s<e.length&&(o+=n?e.substring(s).replace(Ca,""):e.substring(s)),o},Oc=(e,n,t)=>{let o=ho;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 h=a.index+a[0].length-1,d=0,c=null,l=-1;for(let f=h;f<e.length;f++){let u=e[f];if(c){if(u===c){let p=0;for(let g=f-1;g>=0&&e[g]==="\\";g--)p++;p%2===0&&(c=null)}}else if(u==='"'||u==="'"||u==="`")c=u;else if(u==="(")d++;else if(u===")"&&(d--,d===0)){let p=f+1;for(;p<e.length&&/\s/.test(e[p]);)p++;if(p<e.length&&e[p]==="]"){l=p;break}}}if(l!==-1)s+=e.substring(a.index,l+1),r=l+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},Da=e=>Ba(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",ask:"Ask"},t=s=>s.split("_").map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join("");Aa.lastIndex=0;let o=e.replace(Aa,(s,r,a)=>{let i="";try{let c=JSON.parse(a.trim());c&&typeof c=="object"&&(i=Object.entries(c).map(([f,u])=>{let p=typeof u=="string"?u:JSON.stringify(u);return`${f}=${JSON.stringify(p)}`}).join(", "))}catch{let l=[],f=$c;f.lastIndex=0;let u;for(;(u=f.exec(a))!==null;){let p=u[1],g=u[2]!==void 0?u[2]:u[0].split(":").slice(1).join(":").trim();l.push(`${p}=${JSON.stringify(g)}`)}l.length>0?i=l.join(", "):i=a.trim()}let h=r.toLowerCase().replace(/_/g,"");return`[tool:functions.${n[h]||t(r)}(${i})]`});return va.lastIndex=0,Ia.lastIndex=0,o=o.replace(va,""),o=o.replace(Ia,""),o},Dc=/(?:path|query|url|keyword|command|method|title|task|id)\s*=\s*['"`]?\s*\.\.\.\s*['"`]?/i,Pc=/^['"`]?\s*\.\.\.\s*['"`]?$/,Pn=e=>{if(e==null)return!1;let n=String(e).trim();return n==="..."||n==="\u2026"||Pc.test(n)},Qo=e=>{if(!e)return[];let n=Lc(e);Ma.lastIndex=0;let t=n.replace(Ma,""),o=[],s=Os?t:t.replace(Fa,i=>" ".repeat(i.length)).replace(Na,i=>" ".repeat(i.length)),r=bc;r.lastIndex=0;let a;for(;(a=r.exec(s))!==null;){let i=a[1],h=a.index+a[0].length-1,d=0,c=null,l=-1,f=-1;for(let u=h;u<s.length;u++){let p=t[u];if(c){if(p===c){let g=0;for(let y=u-1;y>=0&&t[y]==="\\";y--)g++;g%2===0&&(c=null)}}else if(p==='"'||p==="'"||p==="`")c=p;else if(p==="(")d++;else if(p===")"&&(d--,d===0)){f=u;let g=u+1;for(;g<s.length&&/\s/.test(s[g]);)g++;if(g<s.length&&s[g]==="]"){l=g;break}}}if(l!==-1){let u=t.substring(h+1,f),p=t.substring(a.index,l+1),g=O(u);Pn(g.path)||Pn(g.query)||Pn(g.url)||Pn(g.keyword)||Pn(g.command)||Pn(g.method)||Pn(g.title)||Pn(g.task)||Pn(g.id)||Dc.test(u)||o.push({fullMatch:p,toolName:i.trim(),args:u.trim()}),r.lastIndex=l+1}}return o},ig=(e,n={})=>{if(!e)return null;if(Xo=n,di=new Pa({apiKey:e}),!globalThis.__perfCleanupInstalled){globalThis.__perfCleanupInstalled=!0,setInterval(()=>{typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks())},6e4);let t=globalThis.fetch;globalThis.fetch=async(...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}}}},Jo=async(e,n,t,o,s="Fast",r=.75,a="agent")=>Mc(async()=>{let{aiProvider:i="Google",apiKey:h,mode:d}=e,c="",l=null,f=typeof t=="string"?[{role:"user",parts:[{text:t}]}]:t,u=new AbortController,p=u.signal,g=setInterval(()=>{Pt&&(u.abort(),clearInterval(g))},100);try{let y;i==="Ollama"?y=ai(h,n,f,o,s,d,Ot(n),p,r,systemSettings?.ollamaEndpoint||"Cloud"):i==="OpenRouter"?y=qo(h,n,f,o,s,d,Ot(n),p,r):i==="DeepSeek"?y=jo(h,n,f,o,s,d,Ot(n),p,r):i==="Mistral"?y=Ho(h,n,f,o,s,d,Ot(n),p,r):i==="NVIDIA"?y=Go(h,n,f,o,s,d,Ot(n),p,r):i==="CrofAI"?y=zo(h,n,f,o,s,d,Ot(n),p,r):i==="InferX"?y=Ko(h,n,f,o,s,d,Ot(n),p,r):i==="SenseNova"?y=Yo(h,n,f,o,s,d,Ot(n),p,r):i==="AIHubMix"?y=Vo(h,n,f,o,s,d,Ot(n),p,r):y=await fi(h).models.generateContentStream({model:n,contents:f,config:{systemInstruction:o,temperature:r,thinkingConfig:(()=>{let x=(n||"").toLowerCase(),S=x.includes("gemma-4")||x.startsWith("gemma"),C=x.includes("gemini-3");if(S||C)return S?s.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:ut.MINIMAL}:{includeThoughts:!0,thinkingLevel:ut.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:x.includes("pro")?ut.LOW:ut.MINIMAL,Low:ut.LOW,Medium:ut.MEDIUM,Standard:ut.MEDIUM,High:ut.HIGH,xHigh:ut.HIGH}[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:p});for await(let m of y){if(Pt)throw new Error("Subagent task was cancelled.");if(e?.taskId&&typeof Xe<"u"){let S=Xe.find(C=>C.id===e.taskId);if(S&&S.status==="cancelled")throw new Error("Subagent task was cancelled.")}let w="";if(m.candidates?.[0]?.content?.parts)for(let S of m.candidates[0].content.parts)S.text&&!S.thought&&(c+=S.text,w+=S.text);let x=w?w.trim().split(/\s+/).filter(Boolean).length:0;e&&typeof e.onTokenChunk=="function"&&e.onTokenChunk(w,x),m.usageMetadata&&(l=m.usageMetadata)}}finally{clearInterval(g)}if(l){let y=l.totalTokenCount||0,m=l.cachedContentTokenCount||0,w=(l.candidatesTokenCount||0)+(l.thoughtsTokenCount||0);await Yt("tokens",y,i,n),m>0&&await Yt("cachedTokens",m,i,n),w>0&&await Yt("candidateTokens",w,i,n),e&&typeof e.onUsage=="function"&&e.onUsage({totalTokenCount:y,cachedContentTokenCount:m,candidatesTokenCount:w})}return await Lt("agent",i),{text:c,usageMetadata:l}}),Fc=async(e,n,t=null)=>{t=t||Z(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.
|
|
535
|
-
Your task is to summarize or merge temporary context memories from one or more past conversation sessions.
|
|
536
|
-
For each Chat ID provided, you must output a tool call to save the consolidated summary.
|
|
537
|
-
|
|
538
|
-
The tool call format MUST be:
|
|
539
|
-
[tool:functions.saveSummary(id="<chat-id>", summary="<updated summary string, max 400 words>")]
|
|
540
|
-
|
|
541
|
-
Guidelines:
|
|
542
|
-
- 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.
|
|
543
|
-
- Focus on key goals, preferences, modified files, and technical decisions.
|
|
544
|
-
- Under no circumstances write normal conversational text. Output ONLY the tool calls.
|
|
545
|
-
- You can stack multiple tool calls for multiple chats.
|
|
546
|
-
|
|
547
|
-
Chats to process:
|
|
548
|
-
|
|
549
|
-
`,i=Z(vn,{});for(let f of r){let p=t[f].map(y=>`- ${y}`).join(`
|
|
550
|
-
`),g=i[f];a+=`[Chat ID: ${f}]
|
|
551
|
-
`,g?(a+=`- Existing Summary: "${g}"
|
|
552
|
-
`,a+=`
|
|
553
|
-
-- New Memories to integrate:
|
|
554
|
-
${p}
|
|
555
|
-
|
|
556
|
-
`):a+=`-- Individual Memories:
|
|
557
|
-
${p}
|
|
558
|
-
|
|
559
|
-
`}let h=0,d=5,c=!1,l=_e("gemma_janitor_fallback_google");for(o==="OpenRouter"&&(l=_e("janitor_open_router")),o==="DeepSeek"&&(l=_e("deepseek_level_1")),o==="Mistral"&&(l=_e("mistral_level_1")),o==="NVIDIA"&&(l=_e("nvidia_janitor_fallback")),o==="CrofAI"&&(l=_e("crofai_fallback")),o==="InferX"&&(l=_e("inferx_fallback")),o==="SenseNova"&&(l=_e("sensenova_fallback")),o==="AIHubMix"&&(l=_e("aihubmix_fallback"));h<=d&&!c;){h++;try{let u=(await Jo(n,l,a,null,"Fast",.75,"background")).text||"",p=Qo(u);if(p.length===0)throw new Error("No tool calls detected in synthesis response");for(let g of p){let y=g.toolName;["saveSummary","saveSumary","SaveSummary","SaveSumary"].includes(y)&&await fo(y,g.args,{chatId:e})}c=!0}catch(f){if(h>=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=ee.join(hn,"janitor");De.existsSync(r)||De.mkdirSync(r,{recursive:!0}),De.appendFileSync(ee.join(r,"error.log"),`[${new Date().toLocaleString()}] Past memory batch consolidation error: ${s}
|
|
560
|
-
`)}},Nc=async(e,n,t=!1)=>{let{chatId:o,aiProvider:s="Google"}=e,r=ee.join(xo,"chat-summaries.json"),a=u=>u.filter(p=>(p.role==="user"||p.role==="agent"||p.role==="system")&&p.role!=="think"&&!p.isVisualFeedback&&!p.isMeta&&!p.isTerminalRecord&&!(p.text&&p.text.includes("[TERMINAL_RECORD]"))&&!String(p.id).startsWith("welcome")).map(p=>{let g=p.fullText||p.text||"",y=p.role==="system"||g.startsWith("[TOOL RESULT]:")||p.text&&p.text.startsWith("[TOOL RESULT]:"),m=g;return y&&(g.includes("[TOOL RESULT]:")||p.text&&p.text.includes("[TOOL RESULT]:"))?m="[TOOL RESULT]: ...truncated for summary":m=m.replace(/(\[(?:tool|agent):[a-zA-Z0-9_\.]+)\([\s\S]*?\)(\])/g,"$1(...)$2"),`[${y?"TOOL":p.role==="agent"?"AGENT":"USER"}]: ${m}`}).join(`
|
|
561
|
-
|
|
562
|
-
`),i=async(u,p)=>{let g="You are an expert context summarizer. Summarize the provided chat history (which may include previous summaries, user instructions, agent outputs, and tool results) into a detailed, coherent, and highly technical summary of 1000 to 1500 words. Focus on preserving the architectural decisions made, current system state, task progress, and critical code details, chat messages, file changes. Under no circumstances exceed MAX 2000 words.",y=p?`Here is the previous summary:
|
|
563
|
-
${p}
|
|
564
|
-
|
|
565
|
-
Here is the new conversation history:
|
|
566
|
-
${u}
|
|
567
|
-
|
|
568
|
-
Provide a new consolidated summary of the entire session.`:`Here is the conversation history:
|
|
569
|
-
${u}
|
|
570
|
-
|
|
571
|
-
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 w=0,x=!1,S=null;for(;w<=3&&!x;){w++;try{S=await Jo(e,m,y,g,"Fast"),x=!0}catch{if(w>3){if(s==="Google")try{let R=_e("general_fallback");return(await Jo(e,R,y,g,"Fast")).text||""}catch{return""}return""}}}return S&&S.text||""},h=a(n),d=Z(r,{}),c=d[o]||{summary:"",historyLength:0};typeof c=="string"&&(c={summary:c,historyLength:0});let l=c.summary||"",f=await i(h,l);if(f){c.summary=f;let u=Ac(n);return t?c.historyLength=(c.historyLength||0)+u:c.historyLength=u,d[o]=c,me(r,d),f}return null},ag=e=>{try{let n=ee.join(xo,"chat-summaries.json");if(De.existsSync(n)){let t=Z(n,{});t[e]&&(delete t[e],me(n,t))}}catch{}},lg=async function*(e,n,t,o,s){let{profile:r,thinkingLevel:a,mode:i,janitorModel:h,chatId:d,isPlayground:c,systemSettings:l,sessionStats:f,aiProvider:u="Google",apiTier:p,wildcardTooling:g}=t,y=Ot(e);if(!di&&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:l?.memory!==!1,w=n[n.length-1].text,x=ee.join(xo,"chat-summaries.json"),S=!1,C=n.filter(E=>E.role==="user").length===1,R=w.includes("[TITLE-UPDATE]"),k=C||R,T=w.replace(/\[TITLE-UPDATE\]/g,"").trim();T=T.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),yield{type:"status",content:"[start]"},yield{type:"status",content:"Gathering Context"},await mt.startTransaction(d,T),l?.advanceRollback&&await Yn.takeInitialSnapshot(d),Pt=!1;let _=null;try{let E=new AbortController;_=setInterval(()=>{Pt&&(E.abort(),_&&(clearInterval(_),_=null))},400);let b=[...n.slice(0,-1)];{let Le=Z(x,{})[d]||{summary:"",historyLength:0};if(Le.summary&&Le.historyLength>0){let on=0,$e=[];for(let Ze=0;Ze<b.length;Ze++){let He=b[Ze];(He.role==="user"||He.role==="agent"||He.role==="system")&&!String(He.id).startsWith("welcome")&&!He.isMeta&&on++,on>Le.historyLength&&$e.push(He)}b=$e}}b=b.map(G=>{if(G.role==="user"&&G.text){let Le=G.text.match(/\[USER\]([\s\S]*?)\[\/USER\]/);if(Le)return{...G,text:Le[1].trim()}}return{...G}});let $=process.env.HIGH_CONTEXT,I=255e3,D=26e4;if($&&$!=="false"){let G=parseInt($,10);!isNaN(G)&&G>=256e3&&G<=1e6&&(D=G,I=Math.round(G*.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:"status_history",content:"Context Limit Reached. Condensing session history..."},await Nc(t,b,!0)&&(b=[],S=!0)),C&&m){let G=Z(nn,{});Object.values(G).flat().length>5&&(yield{type:"status",content:"Condensing past chat memories"},await Fc(d,t,G))}let B=Z(nn,{}),W=Z(vn,{}),Y=Object.entries(B).filter(([G])=>G!==d).flatMap(([G,Le])=>Le),fe=[...Object.entries(W).filter(([G])=>G!==d).slice(-20).map(([G,Le])=>`[Chat Summary]: ${Le}`),...Y].map(G=>`- ${G}`).join(`
|
|
572
|
-
`),U=Z(Nt,[]).map(G=>`- ${G.memory}`).join(`
|
|
573
|
-
`),se=(f?.tokens||0)>=1e4,Ae=Mi(fe,U,m,se),A=new Date,N=A.getFullYear(),V=A.toLocaleString("en-US",{month:"short"}).toUpperCase(),J=String(A.getDate()).padStart(2,"0"),Ue=A.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}),Fe=`${N}-${V}-${J}, ${Ue}`,je=[".git","node_modules",".gemini","dist","build",".next","out",".cache","bin","obj","vendor","venv",".idea",".gradle",".terraform","target","coverage",".vscode",".svn",".hg",".fslckout",".github",".gitlab",".circleci",".gitea",".gitee",".lerna",".changeset",".nx",".npm",".yarn",".pnpm-store",".pnpm",".expo",".nuxt",".svelte-kit",".docusaurus",".turbo",".vercel","bower_components",".netlify",".vuepress",".quasar",".output",".angular","jspm_packages",".parcel-cache",".rollup.cache",".rspack",".vitepress","__pycache__",".pytest_cache",".mypy_cache",".tox",".poetry","env","vhdl",".ipynb_checkpoints",".jupyter",".conda",".pdm-build",".bundle",".yardoc",".metadata","App_Data","ClientBin",".cargo",".rustc_info",".go","Godeps","_vendor",".rake_tasks","CMakefiles",".wakatime",".dart_tool",".fvm",".cocoapods","Pods",".pub-cache",".symlinks","DerivedData",".xcworkspace",".serverless",".aws",".gcloud",".azure",".kube",".vagrant",".docker","postgres-data","redis-data","mongo-data",".Spotlight-V100",".Trashes","$RECYCLE.BIN","System Volume Information",".DocumentRevisions-V100",".fseventsd","AppData","Application Data","Local","LocalLow","Roaming","$WinREAgent","$WINDOWS.~BT","$WINDOWS.~WS","scw","System32","SysWOW64",".AppleDouble",".AppleDB",".AppleDesktop","_CodeSignature",".cmio",".LSOverride",".localized",".TemporaryItems",".Trash",".Trash-0",".Trash-1000",".gvfs",".local",".config",".dbus",".fontconfig",".snap",".var",".lost+found","lost+found",".thumb",".thumbnails","EFI","boot","grub","logs","log",".nyc_output",".sonar",".ruff_cache",".VSCodeCounter"],at=G=>{try{return De.readdirSync(G,{withFileTypes:!0})}catch{return[]}},ze=(G,Le={value:0},on=1)=>{if(Le.value>6200||on>7)return Le.value;let $e=at(G);for(let Ze of $e){if(Le.value>6200)break;je.includes(Ze.name)||Ze.name.startsWith(".")||Ze.isDirectory()&&(Le.value++,ze(ee.join(G,Ze.name),Le,on+1))}return Le.value},bt=(G,Le)=>l?.indentationTree!==!1?oi(G,Le,1,at,je):ii(G,Le,"",1,at,je),Wt=ze(process.cwd()),gt=12;Wt>3072?gt=1:Wt>2304?gt=2:Wt>1536?gt=3:Wt>768?gt=4:Wt>384?gt=6:Wt>192?gt=7:Wt>96?gt=8:Wt>48?gt=9:Wt>24&&(gt=10);let kt=Z(ir,{}),Rt=kt[d],lt=Rt?Rt!==process.cwd():!1;kt[d]=process.cwd(),me(ir,kt);let Se=Z(x,{}),oe=Se[d]||{summary:"",historyLength:0};typeof oe=="string"&&(oe={summary:oe,historyLength:0});let Xt=n.filter(G=>(G.role==="user"||G.role==="agent"||G.role==="system")&&!String(G.id).startsWith("welcome")&&!G.isMeta).length;oe.historyLength&&Xt<oe.historyLength&&(oe.summary="",oe.historyLength=0,Se[d]=oe,me(x,Se));let Jn=typeof oe=="object"?oe.summary||"":oe||"",Qn=b.length>0;Qn&&Jn&&b[0]&&(b[0].role==="user"||b[0].role==="system")&&(b[0].text.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")||(b[0].text=`[SYSTEM METADATA]
|
|
574
|
-
**CONTEXT SUMMARY OF PREVIOUS TURNS (PRIORITY: DYNAMIC)**
|
|
575
|
-
${Jn}
|
|
576
|
-
|
|
577
|
-
[USER] ${b[0].text}`,yield{type:"summary_injected",content:{id:b[0].id,text:b[0].text}}));let ui=Jn&&!Qn?`
|
|
578
|
-
[SYSTEM METADATA]
|
|
579
|
-
**CONTEXT SUMMARY OF PREVIOUS TURNS**
|
|
580
|
-
${Jn}
|
|
581
|
-
`:"",hi=!!l?.dynamicDirAwareness,Ua=`${d}|${u}|${a}|${e}|${r}|${hi}`,pi=!hi&&ws.key===Ua&&ws.value?"":`
|
|
582
|
-
**Directory Structure**
|
|
583
|
-
CWD: `+process.cwd()+`${c?" [PLAYGROUND MODE]":""}
|
|
584
|
-
`+bt(process.cwd(),gt),St=await gs(),Fn="";if(Uo()&&St.file_focused!=="none"){Fn=`
|
|
585
|
-
[Additional IDE Context]
|
|
586
|
-
`;let G=ee.relative(process.cwd(),St.file_focused),Le=(St.opened_editors||[]).map($e=>{let Ze=ee.relative(process.cwd(),$e);return Ze.startsWith("..")?`[External] ${ee.basename($e)}`:Ze});if(Fn+=`Focused File: ${G}
|
|
587
|
-
Cursor Line: ${St.cursor_line}
|
|
588
|
-
`,St.selected){let $e=St.selected,Ze=$e.split(`
|
|
589
|
-
`);Ze.length>256&&($e=Ze.slice(0,240).join(`
|
|
590
|
-
`)+`
|
|
591
|
-
... [truncated] ...
|
|
592
|
-
`+Ze.slice(-16).join(`
|
|
593
|
-
`)),$e.length>2048&&($e=$e.slice(0,1920)+`
|
|
594
|
-
... [truncated] ...
|
|
595
|
-
`+$e.slice(-128)),Fn+=`Current Selection: "${$e}"
|
|
596
|
-
`}if(St.manual_edits){let Ze=St.manual_edits.split(`
|
|
597
|
-
`),He=[],Je=null;for(let z of Ze)z.trim()&&(z.startsWith(" Line ")?Je&&Je.edits.push(z):(Je={path:z.endsWith(":")?z.slice(0,-1):z,edits:[]},He.push(Je)));for(let z of He)z.edits.length>80&&(z.edits=z.edits.slice(-80)),z.originalEditsCount=z.edits.length;let le=(z,te)=>te.reduce((Ge,fn)=>{let xn=St.file_focused&&(fn.path===St.file_focused||ee.resolve(process.cwd(),fn.path)===ee.resolve(St.file_focused))?Math.ceil(z*1.2):z;return Ge+Math.min(fn.edits.length,xn)},0),jt=80;if(le(80,He)>300){let z=!1;for(let te=80;te>=10;te--)if(le(te,He)<=300){jt=te,z=!0;break}z||(jt=10)}let Qe=[...He];if(jt===10&&le(10,Qe)>500)for(;Qe.length>0&&le(10,Qe)>500;){let z=0,te=Qe[0].originalEditsCount;for(let Ge=1;Ge<Qe.length;Ge++)Qe[Ge].originalEditsCount<te&&(te=Qe[Ge].originalEditsCount,z=Ge);Qe.splice(z,1)}for(let z of Qe){let Ge=St.file_focused&&(z.path===St.file_focused||ee.resolve(process.cwd(),z.path)===ee.resolve(St.file_focused))?Math.ceil(jt*1.2):jt;z.edits.length>Ge&&(z.edits=z.edits.slice(-Ge))}for(let z of Qe){let te=`${z.path}:
|
|
598
|
-
${z.edits.join(`
|
|
599
|
-
`)}`;for(;z.edits.length>0&&te.length>4*768;)z.edits.shift(),te=`${z.path}:
|
|
600
|
-
${z.edits.join(`
|
|
601
|
-
`)}`;te.length>4*768?z.stringRepresentation="... "+te.slice(-(4*768-4)):z.stringRepresentation=te}let rn=Qe.map(z=>z.stringRepresentation).join(`
|
|
602
|
-
`);for(;Qe.length>0&&rn.length>4*2048;){Qe[0].edits.length>0?Qe[0].edits.shift():Qe.shift();for(let z of Qe){let te=`${z.path}:
|
|
603
|
-
${z.edits.join(`
|
|
604
|
-
`)}`;te.length>4*768?z.stringRepresentation="... "+te.slice(-(4*768-4)):z.stringRepresentation=te}rn=Qe.map(z=>z.stringRepresentation).join(`
|
|
605
|
-
`)}rn.length>4*2048&&(rn="... "+rn.slice(-(4*2048-4))),Fn+=`Recent Manual Edits:
|
|
606
|
-
${rn}
|
|
607
|
-
`}Le.length>0&&(Fn+=`All Opened Editors: ${Le.join(", ")}`),St.diagnostics&&(Fn+=`
|
|
608
|
-
**Active File Errors**:
|
|
609
|
-
${St.diagnostics}
|
|
610
|
-
`),(T.toLowerCase().includes("lint")||T.toLowerCase().includes("warning"))&&St.warnings&&(Fn+=`
|
|
611
|
-
**Lint Warnings**:
|
|
612
|
-
${St.warnings}
|
|
613
|
-
`)}let mi=T.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),gi=/(?:\\)?@\[([^\]]+)\]/g,Zo,er=[];for(gi.lastIndex=0;(Zo=gi.exec(mi))!==null;){let G=Zo[0].startsWith("\\");er.push({tag:Zo[1],isEscaped:G})}let tr=[],po=null;for(let G=0;G<er.length;G++){let{tag:Le,isEscaped:on}=er[G];if(!on)try{let $e=Le.trim().replace(/^["']|["']$/g,""),Ze=/[:#]L?(\d+)(?:-L?(\d+))?$/i,He=$e.match(Ze),Je=$e,le=null,jt=null;He&&(le=parseInt(He[1],10),jt=He[2]?parseInt(He[2],10):le,Je=$e.slice(0,He.index));let Qe=ee.resolve(process.cwd(),Je);if(De.existsSync(Qe)&&De.statSync(Qe).isFile()){let z=Je.toLowerCase(),te=z.endsWith(".pdf"),Ge=z.endsWith(".docx")||z.endsWith(".doc")||z.endsWith(".ppt")||z.endsWith(".pptx")||z.endsWith(".xls")||z.endsWith(".xlsx"),fn=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(z),Ht=fn||te||Ge,xn=u==="Google"||Ot(e);if(Ht&&!xn){let We=`\u2718 Unsupported Modality: ${ee.basename(Je)}`,Te=115;process.stdout.isTTY&&(Te=process.stdout.columns-5||120);let et=[We],Nn=Math.max(...et.map(_n=>_n.length)),Bn=Math.min(Nn+4,Te),ts=et.map(_n=>`${_n.padEnd(Bn-2).substring(0,Bn-2)}`).join(`
|
|
614
|
-
`);yield{type:"visual_feedback",content:sn(`${ts}
|
|
615
|
-
`)};continue}if(le===null&&!Ht){let We=0;try{We=De.readFileSync(Qe,"utf8").split(/\r\n|\r|\n/).length}catch{}if(We>300){let Te=`\u21B7 Skipped (Too Large): ${ee.basename(Je)}`,et=115;process.stdout.isTTY&&(et=process.stdout.columns-5||120);let Nn=Math.min(Te.length+4,et),Bn=Te.padEnd(Nn-2).substring(0,Nn-2);yield{type:"visual_feedback",content:sn(`${Bn}
|
|
616
|
-
`)};continue}}let En=le!==null?le:1,Zn=jt!==null?jt:le!==null?le:En+299;Zn-En>300&&(Zn=En+300);let go=`path=${JSON.stringify(Je)}, startLine=${En}, endLine=${Zn}`,nt=await Qs(go,{isMultiModal:xn}),Ke=!1,Gt="",es=null;if(typeof nt=="string"?nt.trim().startsWith("ERROR")?Ke=!0:Gt=nt:nt&&typeof nt=="object"&&nt.binaryPart?(es=nt.binaryPart,Gt=nt.text||""):Ke=!0,!Ke){let We="";if(fn?(We=`\u2714 Processed: ${ee.basename(Je)}`,po=es):te||Ge?(We=`\u2714 Auto-Analysed: ${ee.basename(Je)}`,po=es):(We=`\u2714 Auto-Read: ${ee.basename(Je)}`,tr.push(Gt)),We){let Te=115;process.stdout.isTTY&&(Te=process.stdout.columns-5||120);let et=[We],Nn=Math.max(...et.map(_n=>_n.length)),Bn=Math.min(Nn+4,Te),ts=et.map(_n=>`${_n.padEnd(Bn-2).substring(0,Bn-2)}`).join(`
|
|
617
|
-
`);yield{type:"visual_feedback",content:sn(`${ts}
|
|
618
|
-
`)}}}}}catch{}}let yi="";tr.length>0&&(yi=`[Tagged File Contents] Auto Read User Tagged files by System, No need to re-read
|
|
619
|
-
`+tr.join(`
|
|
620
|
-
|
|
621
|
-
`)+`
|
|
622
|
-
[Tagged File Contents]
|
|
623
|
-
`);let Wa=mi.replace(/\\(@\[[^\]]+\])/g,"$1"),ja=g?`You cannot execute tools
|
|
624
|
-
Instead, output in chat the exact string you WOULD have produced & wait for system response
|
|
625
|
-
`:"",Ha=process.env.forcedReasoning||!1,wi=`[System Metadata]
|
|
626
|
-
Time: ${Fe}${l?.dynamicDirAwareness?pi:""}${lt?`
|
|
627
|
-
WARNING: CWD Changed from previous: "${Rt}" to current: "${process.cwd()}", write change in chat to avoid future path mismatches
|
|
628
|
-
`:""}${Ae}${Fn}
|
|
629
|
-
[/Metadata]
|
|
630
|
-
${ui}${a!=="Fast"&&(u==="Mistral"&&!Cs(e)||a!=="xHigh"&&u==="Google")?`${u==="Mistral"&&!Cs(e)||e.toLowerCase().startsWith("gemma")||Ha?`[system] strictly follow thinking policy as high priority. do not start a response without <think>...</think> [/system]
|
|
631
|
-
`:""}`:""}[system] exact tool string [tool:functions.ToolName(arg="value")] in chat [/system]
|
|
632
|
-
${yi}${ja}[user prompt] ${Wa.trim()} [/user prompt]`.trim(),xi={role:"user",text:wi};po&&(xi.binaryPart=po),b.forEach(G=>{G.text&&G.role==="agent"&&(G.text=G.text.replace(/(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])/gi,""),G.text=G.text.replace(/(?:<(think|thought)>|\[(think|thought)\])[^\[\n]*/gi,"").trim())}),b.push(xi),ui&&n[n.length-1]?.id&&(yield{type:"summary_injected",content:{id:n[n.length-1].id,text:wi}});let Rn=null,Us=i==="Flux"?100:10;Us=i.toLowerCase().includes("cu")?250:Us;let wn=16;yield{type:"status",content:"Connecting"},Pt=!1;let bi=[],mo=!1;for(let G=0;G<=Us;G++){let Le=await gr("agent",t);if(!Le.allowed)throw new Error(Le.reason||`Budget Exhausted for Provider (${u||"Agent"})`);let on=[];if(mo=!1,i==="ICU"||i==="FluxCU")try{yield{type:"status",content:"Capturing Screen"},await new Promise(we=>setTimeout(we,1e3));let ue=await Si();if(ue&&ue.base64){let we="[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]",ie={inlineData:{mimeType:ue.mimeType,data:ue.base64}};for(let st of b)Array.isArray(st.parts)&&(st.parts=st.parts.filter(Mt=>!Mt.inlineData));if(b.length>0&&b[b.length-1].role==="user"){let st=b[b.length-1];typeof st.text=="string"&&(st.text+=`
|
|
633
|
-
|
|
634
|
-
${we}`,Array.isArray(st.parts)||(st.parts=[{text:st.text}]),st.parts.push(ie))}else b.push({role:"user",text:we,parts:[{text:we},ie]})}}catch(ue){console.error("Vision screenshot capture error:",ue)}if(l?.compression===0&&(f?.tokens||0)>D&&(b=Li(b,6)),G>0?yield{type:"status",content:"Working"}:yield{type:"status",content:"Connecting"},Pt){try{let{clearPendingNudges:ue}=await import("./subagent_state-LZCOZSUJ.js");ue()}catch{}yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
|
|
635
|
-
|
|
636
|
-
\x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}try{let{consumePendingNudges:ue}=await import("./subagent_state-LZCOZSUJ.js"),we=ue();if(we&&we.length>0){let ie=we.join(`
|
|
637
|
-
|
|
638
|
-
`);b.length>0&&b[b.length-1].role==="user"?b[b.length-1].text+=`
|
|
639
|
-
|
|
640
|
-
${ie}`:b.push({role:"user",text:ie}),yield{type:"status",content:"Subagent Update"}}}catch{}if(o){let ue=await o();ue&&(ue.startsWith("/btw")?b.length>0&&b[b.length-1].role==="user"?b[b.length-1].text+=`
|
|
641
|
-
|
|
642
|
-
[system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
|
|
643
|
-
[question] ${ue.replace("/btw","").trim()} [/question]`:b.push({role:"user",text:`[system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
|
|
644
|
-
[question] ${ue.replace("/btw","").trim()} [/question]`}):b.length>0&&b[b.length-1].role==="user"?b[b.length-1].text+=`
|
|
645
|
-
|
|
646
|
-
[STEERING HINT from USER, HIGH PRIORITY] ${ue.trim().toUpperCase()} [/STEERING HINT]`:b.push({role:"user",text:`[STEERING HINT from USER, HIGH PRIORITY] ${ue.trim().toUpperCase()} [/STEERING HINT]`}),yield{type:"status",content:`${ue.startsWith("/btw")?"Question Forwarded...":"Steering Hint Injected..."}`})}let $e,Ze=!1,He=1,Je=1,le="",jt=null,Qe=null,rn=null,z=0,te=[],Ge=0,fn=!1,Ht=!1,xn=!1,En=!1,Zn=!0,go=0,nt="",Ke="",Gt=!1,es=!1,We=!0,Te=e,et="";for(;He<=wn&&Je<=wn&&!Ze&&!Pt;){let ue=!1;try{le="",Zn&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},Zn=!1,Je===1&&(nt=""));let we=P=>{if(!P||!P.includes("[tool:"))return P;let re="___THINK_OPEN_TAG___",j="___THINK_CLOSE_TAG___";P=P.replace("<think>",re).replace("</think>",j),P=P.replace(Cc,(ge,Ce)=>Ce.includes("[tool:")?Ce.trim():ge);let H="",xe=0;for(;xe<P.length;){let ge=P.indexOf("[tool:",xe);if(ge===-1){H+=P.substring(xe).replace(Oa,"").replace(La,"");break}let Ce=P.substring(xe,ge);H+=Ce.replace(Oa,"").replace(La,"");let rt=P.indexOf("]",ge);if(rt===-1){H+=P.substring(ge);break}H+=P.substring(ge,rt+1),xe=rt+1}return P=H,P=P.replaceAll(re,"<think>").replaceAll(j,"</think>"),P},ie=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,re,j)=>{let H=P.text||"";m||(H=H.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),P.role==="agent"&&(H=we(H),H=H.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),H=H.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*"));let xe=[];return Array.isArray(P.parts)&&P.parts.length>0?xe=P.parts.map(ge=>{if(ge.text){let Ce=ge.text;return m||(Ce=Ce.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),P.role==="agent"&&(Ce=we(Ce),Ce=Ce.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),Ce=Ce.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*")),{text:Ce}}return ge}):xe=[{text:H}],P.binaryPart&&Ot(Te)&&j.slice(re+1).filter(Ce=>Ce.role==="user"&&!Ce.text?.startsWith("[TOOL RESULT]")).length<=2&&xe.push(P.binaryPart),{role:P.role==="user"||P.role==="system"?"user":"model",parts:xe}});for(let P=0;P<ie.length;P++){let re=ie[P],j=re.parts?.[0]?.text||"";if(re.role==="model"&&/\[tool:/i.test(j)){let H=-1;for(let xe=P+1;xe<ie.length;xe++){let ge=ie[xe],Ce=ge.parts?.[0]?.text||"";if(ge.role==="user"&&Ce.startsWith("[TOOL RESULT]")){H=xe;break}}if(H!==-1&&H!==P+1){let[xe]=ie.splice(H,1);ie.splice(P+1,0,xe)}}}for(let P=ie.length-2;P>=0;P--){let re=ie[P],j=ie[P+1];re.role==="user"&&j.role==="user"&&(j.parts?.[0]?.text||"").trim().startsWith("[SYSTEM")&&ie.splice(P,1)}let st=[];for(let P=0;P<ie.length;P++){let re=ie[P];if(st.length===0)st.push(re);else{let j=st[st.length-1];j.role===re.role?(j.parts[0].text+=`
|
|
647
|
-
|
|
648
|
-
`+(re.parts?.[0]?.text||""),re.parts?.length>1&&j.parts.push(...re.parts.slice(1))):st.push(re)}}ie.length=0,ie.push(...st),Te=e;let Mt=`${d}|${u}|${i}|${a}|${Te}|${JSON.stringify(r)}|${!!l?.dynamicDirAwareness}|${!!l?.subAgents}`;if(ws.key===Mt&&ws.value)et=ws.value;else{let P=u==="Mistral"?!!Cs(Te):!(Te||"gemma").toLowerCase().startsWith("gemma");et=Ai(r,((Te||"gemma").toLowerCase().startsWith("gemma"),a),i,l,m,C,u,u==="Google"?!0:y,P,d),l?.dynamicDirAwareness||(et+=`
|
|
649
|
-
${pi.replace(`
|
|
650
|
-
**Directory Structure**`,`
|
|
651
|
-
**Directory Structure**`)}`),ws.key=Mt,ws.value=et}let Et=ie[ie.length-1];if(Uo()&G>0){await new Promise(j=>setTimeout(j,2500)),yield{type:"status",content:"Verifying"};let P=await gs(),re=P?P.diagnostics:null;re&&Et&&Et.role==="user"&&Et.parts?.[0]?.text&&(Et.parts[0].text+=`
|
|
652
|
-
${re} [/ERROR]`),yield{type:"status",content:"Working"}}if(u==="Mistral"||u==="Google"&&e?.toLowerCase().startsWith("gemma")){let re=a!=="Fast"&&(u==="Mistral"||a!=="xHigh")?". **strictly maintain thinking policy. do not start a response without <think>...</think>**":"",j=`
|
|
653
|
-
[system] Tool result received. Analyze output and proceed with your turn [/system]`;Et&&Et.role==="user"&&Et.parts?.[0]?.text?.startsWith("[TOOL RESULT]")&&(Et.parts[0].text+=j)}if(l?.advanceRollback&&Et&&Et.role==="user"&&Et.parts?.[0]?.text?.startsWith("[TOOL RESULT]"))try{let P=await Yn.getLatestFileChanges(d);if(P&&(P.newFiles.length>0||P.modifiedFiles.length>0||P.deletedFiles.length>0)){let re=`
|
|
654
|
-
[system] File Changes:
|
|
655
|
-
`;for(let H of P.newFiles)re+=`* ${H} (created)
|
|
656
|
-
`;for(let H of P.modifiedFiles)re+=`* ${H} (modified)
|
|
657
|
-
`;for(let H of P.deletedFiles)re+=`* ${H} (deleted)
|
|
658
|
-
`;re+="[/system]",Et.parts[0].text+=re;let j=-1;for(let H=b.length-1;H>=0;H--)if(b[H].role==="user"&&b[H].text?.startsWith("[TOOL RESULT]")){j=H;break}j!==-1&&(b[j].text+=re)}}catch{}let Un=Math.floor(Us*(i==="Flux"?.98:.8)),Jt=G+1;Jt>=Un&&Et&&Et.parts?.[0]&&(Et.parts[0].text+=`
|
|
659
|
-
[system] WARNING, Turn Limit Impending: Step ${Jt}/${Us}. Wrap up quickly/prompt user to continue. [/system]`);let At=new Promise((P,re)=>{E.signal.aborted&&re(new DOMException("The user aborted a request.","AbortError")),E.signal.addEventListener("abort",()=>{re(new DOMException("The user aborted a request.","AbortError"))})});At.catch(()=>{});let ot=ie;if(u==="Ollama")$e=ai(t.apiKey,Te,ot,et,a,i,y,E.signal,1,l?.ollamaEndpoint||"Cloud");else if(u==="OpenRouter")$e=qo(t.apiKey,Te,ot,et,a,i,y,E.signal,1,d);else if(u==="DeepSeek")$e=jo(t.apiKey,Te,ot,et,a,i,y,E.signal,1);else if(u==="Mistral")$e=Ho(t.apiKey,Te,ot,et,a,i,y,E.signal,1,d);else if(u==="NVIDIA"){let P=Go(t.apiKey,Te,ot,et,a,i,y,E.signal,1);$e=_a(P,Te)}else if(u==="CrofAI")$e=zo(t.apiKey,Te,ot,et,a,i,y,E.signal,1);else if(u==="InferX")$e=Ko(t.apiKey,Te,ot,et,a,i,y,E.signal,1);else if(u==="SenseNova")$e=Yo(t.apiKey,Te,ot,et,a,i,y,E.signal,1);else if(u==="AIHubMix")$e=Vo(t.apiKey,Te,ot,et,a,i,y,E.signal,1);else{let re=fi(t?.apiKey).models.generateContentStream({model:Te||"gemini-3-flash-preview",contents:ot,config:{systemInstruction:et,mediaResolution:"MEDIA_RESOLUTION_HIGH",safetySettings:[{category:Xn.HARM_CATEGORY_HARASSMENT,threshold:Vn.BLOCK_NONE},{category:Xn.HARM_CATEGORY_HATE_SPEECH,threshold:Vn.BLOCK_NONE},{category:Xn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Vn.BLOCK_NONE},{category:Xn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Vn.BLOCK_NONE}],temperature:1.05,thinkingConfig:(()=>{let j=(Te||"").toLowerCase(),H=j.includes("gemma-4")||j.startsWith("gemma"),xe=j.includes("gemini-3");if(H||xe)return H?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 ge={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[a]||2048;return ge===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:ge}}})()}},{signal:E.signal});$e=await Promise.race([re,At])}le="",jt=null,rn=null,te=[],Ge=0,yield{type:"model_update",content:null},Ke="",Gt=nt.length>0;let Ft="",nr=Date.now(),ss=async function*(){if(u==="Google"&&Ft){let P=Ws(Ft);for(let re of P)yield re;Ft="",nr=Date.now()}},ki=!0,os="",bs=!1,qt=null,Ka={tool:{startPrefix:"[tool",fullPrefix:"[tool:functions.",endTag:"]"},agent:{startPrefix:"[agent",fullPrefix:"[agent:generalist.",endTag:"]"},end:{startPrefix:"[[END]]",fullPrefix:"[[END]]",endTag:"[[END]]"},kimi_section:{startPrefix:"<|tool_calls_section_begin|>",fullPrefix:"<|tool_calls_section_begin|>",endTag:"<|tool_calls_section_end|>"},kimi_call:{startPrefix:"<|tool_call_begin|>",fullPrefix:"<|tool_call_begin|>",endTag:"<|tool_call_end|>"}},Ws=P=>{let re=[],j=P;for(;j.length>0;)if(bs){let H=os+j,xe=Ka[qt];if(xe){let rt=!1;if(H.length<xe.startPrefix.length?xe.startPrefix.startsWith(H)||(rt=!0):H.startsWith(xe.startPrefix)?H.length>=xe.fullPrefix.length&&!H.startsWith(xe.fullPrefix)&&(rt=!0):rt=!0,rt){re.push({type:"text",content:H}),os="",bs=!1,qt=null,j="";break}}let ge=-1,Ce=xe?xe.endTag:"]";if(qt==="tool"||qt==="agent"){let rt=0,q=null,pe=0,it=!1;for(let M=0;M<H.length;M++){let Ye=H[M];if(q){if(Ye===q){let Ne=0;for(let Q=M-1;Q>=0&&H[Q]==="\\";Q--)Ne++;Ne%2===0&&(q=null)}}else if(Ye==='"'||Ye==="'"||Ye==="`")q=Ye;else if(Ye==="(")rt++,it=!0;else if(Ye===")")rt--;else if(Ye==="[")pe++;else if(Ye==="]"){if(it&&rt===0&&pe===1){ge=M;break}pe--}}}else ge=H.indexOf(Ce);if(ge!==-1){let rt=Ce.length;if(!qt?.startsWith("kimi")){let q=H.substring(0,ge+rt);re.push({type:"text",content:q})}os="",bs=!1,qt=null,j=H.substring(ge+rt)}else{let rt=qt?.startsWith("kimi")?8192:512;H.length>rt?(re.push({type:"text",content:H}),os="",bs=!1,qt=null):os=H,j="";break}}else{let H=j.indexOf("[tool"),xe=j.indexOf("[agent"),ge=j.indexOf("[[END]]"),Ce=j.indexOf("<|tool_calls_section_begin|>"),rt=j.indexOf("<|tool_call_begin|>"),q=[{type:"tool",idx:H,start:"[tool",end:"]"},{type:"agent",idx:xe,start:"[agent",end:"]"},{type:"end",idx:ge,start:"[[END]]",end:"[[END]]"},{type:"kimi_section",idx:Ce,start:"<|tool_calls_section_begin|>",end:"<|tool_calls_section_end|>"},{type:"kimi_call",idx:rt,start:"<|tool_call_begin|>",end:"<|tool_call_end|>"}].filter(pe=>pe.idx!==-1).sort((pe,it)=>pe.idx-it.idx);if(q.length>0){let pe=q[0];pe.idx>0&&re.push({type:"text",content:j.substring(0,pe.idx)}),bs=!0,qt=pe.type,os="",j=j.substring(pe.idx)}else{let pe=["[tool","[agent","[[END]]","<|tool_calls_section_begin|>","<|tool_call_begin|>"],it=-1;for(let M of pe){for(let Ye=M.length-1;Ye>0;Ye--)if(j.endsWith(M.substring(0,Ye))){it=j.length-Ye;let Ne=pe.indexOf(M);Ne===0?qt="tool":Ne===1?qt="agent":Ne===2?qt="end":Ne===3?qt="kimi_section":qt="kimi_call";break}if(it!==-1)break}if(it!==-1)it>0&&re.push({type:"text",content:j.substring(0,it)}),bs=!0,os=j.substring(it),j="";else{re.push({type:"text",content:j});break}}}return re},Ya=$e[Symbol.asyncIterator]();for(;;){let{value:P,done:re}=await Promise.race([Ya.next(),At]);if(re)break;if(P&&P.type==="status"){yield P;continue}let j="",H=P.candidates?.[0]?.content?.parts;if(H&&H.length>0)for(let ge of H){let Ce=typeof ge.text=="string"?ge.text:ge.text?parseChunkText(ge.text):"";ge.thought?Ce&&(ue||(j+="<think>",ue=!0),j+=Ce):Ce&&(ue&&(j+="</think>",ue=!1),j+=Ce)}else P.text&&ue&&(j+="</think>",ue=!1);j=Rc(j);let xe=j?j.trim().split(/\s+/).filter(Boolean).length:0;if(t&&typeof t.onTokenChunk=="function"&&t.onTokenChunk(j,xe),ki&&(yield{type:"status",content:"Thinking"},ki=!1),Pt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
|
|
660
|
-
|
|
661
|
-
\x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(j){if(Gt){if(Ke+=j,Ke.length>=64){let q=0,pe=Math.min(nt.length,Ke.length);for(let M=pe;M>=10;M--)if(nt.endsWith(Ke.substring(0,M))){q=M;break}let it=Ke.substring(q);if(it){let Ye=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(nt)?it.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):it.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(Ye)if(le+=Ye,u==="Google")Ft+=Ye;else{yield*ss();let Ne=Ws(Ye);for(let Q of Ne)yield Q}}Gt=!1,Ke=""}continue}else if(le+=j,u==="Google")Ft+=j;else{yield*ss();let q=Ws(j);for(let pe of q)yield pe}let ge=Ic(le);if(ge.inside){es=!0,rn||(rn=Date.now());let pe={Ask:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Cancel:"cancel",Await:"await",Answer:"answer",Steer:"steer",steer:"steer"}[ge.toolName]||ge.toolName,it=ge.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(pe)){let Ne=O(it),Q=Ne.path||Ne.targetFile||Ne.TargetFile||Ne.directory,bn=Ne.keyword,rs=Ne.title||Ne.task,Wn=Ne.id||Ne.taskId,Me=Ne.timeout||Ne.time;if(bn!=null)M=String(bn).replace(ys,"");else if(Q)M=ee.basename(String(Q).replace(ys,"").replace($a,"/"));else if(rs&&(pe==="invoke"||pe==="invoke_sync"))M=String(rs).replace(ys,"").substring(0,30);else if(Wn&&pe==="get_progress")M=String(Wn).replace(ys,"");else if(Me&&pe==="await"){let zt=parseFloat(String(Me).replace(ys,""));isNaN(zt)?M=String(Me).replace(ys,""):(zt<5&&(zt=5),zt>120&&(zt=120),M=($n=>{if($n>=60){let or=Math.floor($n/60),ks=$n%60;return`${or}m${ks>0?` ${ks}s`:""}`}return`${$n}s`})(zt))}else{let zt=it.match(kc);if(zt){let Qt=zt[1].replace(ys,"");pe==="invoke"||pe==="invoke_sync"||pe==="get_progress"?M=Qt.substring(0,30):M=pe==="search_keyword"||pe==="file_map"?Qt:ee.basename(Qt.replace($a,"/"))}}}let Ye=`${li[pe]||pe}${M?` ${M}`:""}`;if((pe!==jt||M!==Qe)&&(jt=pe,Qe=M,yield{type:"status",content:`${Ye}`},process.stdout.isTTY)){let Q={WebSearch:"Searching",web_search:"Searching",WebScrape:"Reading",web_scrape:"Reading",ReadFile:"Reading",read_file:"Reading",ReadFolder:"Reading",read_folder:"Reading",WriteFile:"Writing",write_file:"Writing",UpdateFile:"Editing",update_file:"Editing",WritePdf:"Creating",write_pdf:"Creating",WriteDocx:"Creating",write_docx:"Creating",SearchKeyword:"Searching",search_keyword:"Searching",CodeSearch:"Searching",code_search:"Searching",Run:"Executing",Ask:"User Input Required",Memory:"Updating Memory",GenerateImage:"Generating",InvokeSync:"Sub-Agent Working",invoke_sync:"Sub-Agent Working",Invoke:"Working",invoke:"Working",GetProgress:"Checking Progress",get_progress:"Checking Progress",Cancel:"Stopping Generalist",cancel:"Stopping Generalist",Await:"Waiting",await:"Waiting",EmergencyRollback:"Rolling the Ball",Answer:"Answering Sub-Agent",answer:"Answering Sub-Agent",Steer:"Steering Sub-Agent",steer:"Steering Sub-Agent",Click:"Clicking",click:"Clicking",Drag:"Dragging",drag:"Dragging",Scroll:"Scrolling",scroll:"Scrolling",KeyboardTyping:"Typing",keyboard_typing:"Typing",KeyPress:"Pressing Key",key_press:"Pressing Key",RecaptureScreen:"Recapturing Screen",recapture_screen:"Recapturing Screen"}[pe]||"Working";process.stdout.write(`\x1B]0;${Q}...\x07`)}}if(le.length-go>150){go=le.length;let q=Ba(le,!1),it=(q.match(/(?:<think>|\[think\])([\s\S]*?)(?:<\/think>|\[\/think\]|$)/gi)||[]).join("").trim(),M=it.split(/[.!?]\s+/),Ye=new Set(M),Ne=M.length>10?(M.length-Ye.size)/M.length:0,Q=it.split(/\s+/).filter(ve=>ve.length>0).length,bn=.6,rs=.8,Wn=!1;if((u.toLowerCase().includes("google")||u.toLowerCase().includes("mistral"))&&((Te||"").toLowerCase().startsWith("gemma")||(Te||"").toLowerCase().includes("stral"))){let v={low:256,medium:1024,high:8192,max:16384,xhigh:16384}[a?.toLowerCase()]||2500;Wn=Q>v}if(Ne>bn||Wn){yield{type:"status",content:`${Ne>bn?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},Ht=!0,await new Promise(v=>setTimeout(v,3e3));break}let Qt=Da(le).trim().split(/[.!?]\s+/),$n=new Set(Qt);if((Qt.length>10?(Qt.length-$n.size)/Qt.length:0)>rs){yield{type:"status",content:"Response Loop Detected. Re-centering..."},Ht=!1,En=!0,await new Promise(ve=>setTimeout(ve,3e3));break}let ks=q.replace(pc,"").replace(mc,"").replace(gc,"").replace(yc,""),Kt=ks.toLowerCase().split(/\s+/).map(ve=>ve.replace(wc,"")).filter(ve=>ve.length>0),Cn=!1;if(Kt.length>=10)for(let ve=1;ve<=15;ve++){let v=Math.max(3,Math.ceil(10/ve));if(Kt.length<ve*v)continue;let K=Kt.slice(Kt.length-ve),ce=K.join(" ");if(ve>1&&ce===K.slice(0,Math.floor(ve/2)).join(" ").repeat(2).trim())continue;let ye=!0;for(let be=1;be<v;be++)if(Kt.slice(Kt.length-ve*(be+1),Kt.length-ve*be).join(" ")!==ce){ye=!1;break}if(ye){Cn=!0;break}}if(!Cn){let ve=ks.toLowerCase().replace(xc,"");if(ve.length>=20)for(let v=1;v<=10;v++){let K=Math.max(5,Math.ceil(16/v));if(ve.length<v*K)continue;let ce=ve.substring(ve.length-v),ye=!0;for(let be=1;be<K;be++)if(ve.substring(ve.length-v*(be+1),ve.length-v*be)!==ce){ye=!1;break}if(ye){Cn=!0;break}}}if(Cn){yield{type:"status",content:"Stuttering Detected. Re-centering..."},Ht=!1,xn=!0,await new Promise(ve=>setTimeout(ve,3e3));break}}let Ce=le.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/gi,""),rt=Qo(Ce);for(;rt.length>Ge;){yield*ss();let q=rt[Ge],pe=Date.now(),M={Ask:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Await:"await",await:"await",AwaitSubagent:"await",awaitSubagent:"await",Answer:"answer",answer:"answer",AnswerSubagent:"answer",answerSubagent:"answer",Steer:"steer",steer:"steer",SteerSubagent:"steer",steerSubagent:"steer",Cancel:"cancel",cancel:"cancel",Click:"click",click:"click",Drag:"drag",drag:"drag",Scroll:"scroll",scroll:"scroll",KeyboardTyping:"keyboard_typing",keyboard_typing:"keyboard_typing",KeyPress:"key_press",key_press:"key_press",RecaptureScreen:"recapture_screen",recapture_screen:"recapture_screen",EmergencyRollback:"EmergencyRollback"}[q.toolName]||q.toolName,Ye=li[M]||q.toolName,Ne=xs(M,q.args);yield{type:"status",content:`${Ye}${Ne?` ${Ne}`:""}`};let Q="";if(M==="click"){let v=O(q.args);Q=`\u2714 Clicked: ${v.intendedClickText?`${v.intendedClickText}`:""}`}else if(M==="drag"){let v=O(q.args);Q=`\u2714 Dragged: Cell ${v.fromGridId||""} \u2192 Cell ${v.toGridId||""}`}else if(M==="scroll"){let v=O(q.args);Q=`\u2714 Scrolled: ${v.direction||"down"} (${v.amount||1})`}else if(M==="keyboard_typing"){let v=O(q.args);Q=`\u2714 Typed: ${v.text?`"${v.text.length>20?v.text.substring(0,20)+"...":v.text}"`:""}`}else if(M==="key_press")Q=`\u2714 Pressed Key: ${O(q.args).key||""}`;else if(M==="recapture_screen")Q="\u2714 Recaptured Screen";else if(M==="web_search"){let{query:v,limit:K=10,aiMode:ce=!1}=O(q.args);Q=`${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(q.args).url||null;Q=`${v?"\u2714":"\u2718"} Visited: ${v||"No Source"}`}else if(M==="view_file"){let{path:v,StartLine:K,EndLine:ce,start_line:ye,end_line:be,startLine:qe,endLine:Oe}=O(q.args),Re=K||ye||qe,ne=ce||be||Oe,he=parseInt(Re)||1,de=parseInt(ne)||(Re?he+800:800),Be="...",tt=de;try{let Ve=ee.resolve(process.cwd(),v);if(De.existsSync(Ve)){let _t=De.readFileSync(Ve,"utf8").split(`
|
|
662
|
-
`).length;Be=_t,!Re&&!ne&&_t>800?tt=Math.min(50,_t):tt=Math.min(de,_t)}}catch{}let ke=(v||"").toLowerCase(),Pe=ke.endsWith(".pdf"),ct=ke.endsWith(".docx")||ke.endsWith(".doc")||ke.endsWith(".ppt")||ke.endsWith(".pptx")||ke.endsWith(".xls")||ke.endsWith(".xlsx"),Ie=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(ke);Pe||ct?Q=`${v.length>0?"\u2714":"\u2718"} ${v?`Analyzed: ${ee.basename(v)}`:"Analyzed: File Not Found"}`:Ie?Q=`${v.length>0?"\u2714":"\u2718"} ${v?`Processed: ${ee.basename(v)}`:"Processed: File Not Found"}`:Q=`${Be!=="..."?"\u2714":"\u2718"} Read: ${v?`${ee.basename(v)} \u2192 ${Be!=="..."?`Lines ${he} - ${tt} of ${Be}`:"File Not Found"}`:"File Not Found"}`}else if(M==="list_files"||M==="read_folder"){let v=M==="list_files"?"List":"Browsed",K=O(q.args).path||null,ce=O(q.args).recurse||1;Q=`${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(q.args).path||null;Q=`${K?"\u2714":"\u2718"} ${v}: ${K.replaceAll("\\","/")||"No File Changes"}`}else if(M==="write_pdf"){let v=O(q.args).path||null;Q=`${v?"\u2714":"\u2718"} Generated: ${v.replaceAll("\\","/")||"No PDF Generated"}`}else if(M==="write_docx"){let v=O(q.args).path||null;Q=`${v?"\u2714":"\u2718"} Generated: ${v.replaceAll("\\","/")||"No Docx Generated"}`}else if(M==="file_map"){let v=O(q.args).path;Q=`${v?"\u2714":"\u2718"} Indexed: ${v.replaceAll("\\","/")?""+v:"File Not Found"}`}else if(M.toLowerCase()==="search_keyword"||M.toLowerCase()==="todo")Q="";else if(M.toLowerCase()==="generate_image"){let{path:v,outputPath:K,output:ce}=O(q.args);Q=`\u2714 Generated: ${v||K||ce||"generated_image.png"}`}else if(M==="invoke_sync"||M==="InvokeSync"){let v=xs(M,q.args);Q=`\u2714 Called Generalist${v?`: ${v}`:""}`}else if(M==="Invoke"||M==="InvokeAsync"||M==="invoke"){let v=xs(M,q.args);Q=`\u2714 Started Generalist${v?`: ${v}`:""}`}else if(M==="get_progress"||M==="GetProgress"){let v=xs(M,q.args);Q=`\u2714 Checked${v?`: ${v}`:""}`}else if(M==="cancel"){let v=xs(M,q.args);Q=`\u{1F6C7} Cancelled${v?`: ${v}`:""}`}else if(M==="steer"||M==="Steer"){let v=xs(M,q.args);Q=`\u2714 Steered${v?`: ${v}`:""}`}else if(M==="EmergencyRollback"){let{method:v}=O(q.args);Q=v==="forceRevert"?"":"\u2714 Rollback Point Checked"}else if(M==="await"||M==="Await"){let{time:v,timeout:K}=O(q.args),ce=parseFloat(K||v)||0;ce||(ce=120);let ye=Oe=>{if(Oe>=60){let Re=Math.floor(Oe/60),ne=Oe%60;return`${Re}m${ne>0?` ${ne}s`:""}`}return`${Oe}s`},be=["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"];Q=`\u2714 ${be[Math.floor(Math.random()*be.length)]} \u2192 ${ye(ce)}`}else M==="Answer"||M==="answer"?Q="\u2714 Resolved Sub-Agent Query":M==="exec_command"||M==="ask"?Q="":Q=`Executed: ${q.toolName}`;if(yield*ss(),M==="exec_command"){let{command:v}=O(q.args);if(v&&t.systemSettings&&t.systemSettings.allowExternalAccess===!1){let K=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],ce=ee.resolve(process.cwd()).substring(0,3).toLowerCase(),ye=ne=>{let he=[],de="",Be=null;for(let tt=0;tt<ne.length;tt++){let ke=ne[tt];Be?(ke===Be&&(Be=null),de+=ke):ke==='"'||ke==="'"?(Be=ke,de+=ke):ke==="&"&&ne[tt+1]==="&"||ke==="|"&&ne[tt+1]==="|"?(de.trim()&&(he.push(de.trim()),de=""),tt++):ke===";"||ke==="|"||ke==="&"?de.trim()&&(he.push(de.trim()),de=""):de+=ke}return de.trim()&&he.push(de.trim()),he},be=ne=>{let he=[],de="",Be=null;for(let tt=0;tt<ne.length;tt++){let ke=ne[tt];Be?(ke===Be&&(Be=null),de+=ke):ke==='"'||ke==="'"?(Be=ke,de+=ke):/\s/.test(ke)?de&&(he.push(de),de=""):de+=ke}return de&&he.push(de),he},qe=ne=>{let he=ne.replace(/^['"]|['"]$/g,"").trim();return!he||process.platform==="win32"&&/^\/[a-zA-Z0-9?]+$/.test(he)?!1:K.some(de=>{if(de.source==="[a-zA-Z]:[\\\\\\/]"){let Be=he.match(/[a-zA-Z]:[\\\/]/i);return Be&&Be[0].toLowerCase()!==ce}return de.test(he)})};if(ye(v).some(ne=>{let he=be(ne);if(he.length===0)return!1;let de=he[0].replace(/^['"]|['"]$/g,"").toLowerCase();if(["echo","printf","write-output"].includes(de)){let tt=!1;return he.some(ke=>{let Pe=ke.replace(/^['"]|['"]$/g,"");if(Pe===">"||Pe===">>"||Pe==="<")return tt=!0,!1;if(Pe.startsWith(">")||Pe.startsWith("<")){let ct=Pe.replace(/^[><]+/,"");return qe(ct)}return tt?(tt=!1,qe(ke)):!1})}return he.some(tt=>qe(tt))})){let ne='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(he=>setTimeout(he,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${ne}`),await new Promise(he=>setTimeout(he,50)),t.onExecEnd&&t.onExecEnd(),te.push({role:"user",text:`[TOOL RESULT]: ERROR: ${ne}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${ne}`},Ge++;continue}}t.onExecStart&&t.onExecStart(v||"No Command"),yield{type:"exec_start"}}let bn=O(q.args),rs=bn.path||bn.targetPath||null;if(rs){let v=t.systemSettings&&t.systemSettings.allowExternalAccess===!1,K=ee.resolve(rs),ce=ee.resolve(process.cwd());if(v&&!K.startsWith(ce)){let ye="Access Denied. You are not allowed to access files outside the current workspace.";if(M==="write_file"||M==="update_file"){let qe=`\u2718 ${M==="write_file"?"Write Canceled":"Edit Canceled"}: ${bn.path||"..."}`,Oe=115;process.stdout.isTTY&&(Oe=process.stdout.columns-5||120);let Re=Math.min(qe.length+4,Oe),ne=`${qe.padEnd(Re-2).substring(0,Re-2)}`;yield{type:"visual_feedback",content:sn(`${We?`
|
|
663
|
-
`:""}${ne}
|
|
664
|
-
`)},We=!1}te.push({role:"user",text:`[TOOL RESULT]: ERROR: ${ye}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${ye}`},Ge++;continue}}if(t.onToolApproval&&(M==="write_file"||M==="update_file"||M==="exec_command")){let K=t.systemSettings||{},ce=K.autoExec,ye=null,be=!1,qe=!1,Oe=!1;if(M==="exec_command"){let{command:Pe}=O(q.args),ct=(Pe||"").trim(),Ie=(_t,Zt)=>{if(!Zt)return!1;let un=Zt.split(",").map(en=>en.trim().toLowerCase()).filter(Boolean),dt=_t.toLowerCase();return un.some(en=>dt.startsWith(en))},Ve=Ie(ct,K.alwaysAskCommands),Ee=Ie(ct,K.autoApproveCommands);if(qe=Ie(ct,K.autoDisallowCommands),Ve?be=!0:(Ee||K.autoApproveGit&&/^git\s+commit\b/i.test(ct))&&(ye="allow"),!be&&!ye){if(K.networkAccess===!1){let Zt=ct.trim().replace(/\s+/g," ").replace(/^['"]+|['"]+$/g,"").toLowerCase().split(" "),dt=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"]),ft=!1;en.has(dt)&&(ft=!0);let ht=kn=>Zt.slice(1).some(Sn=>kn.includes(Sn)),vt=kn=>{let Sn=Zt.findIndex(Mn=>kn.includes(Mn)),Ss=Zt.findIndex(Mn=>["run","exec","test"].includes(Mn));return Sn!==-1&&!(Ss!==-1&&Ss<Sn)};dt==="git"&&ht(["clone","pull","push","fetch"])&&(ft=!0),dt==="go"&&ht(["get","install"])&&(ft=!0),dt==="npm"&&vt(["install","i","update","add"])&&(ft=!0),dt==="yarn"&&vt(["add","install","upgrade"])&&(ft=!0),dt==="pnpm"&&vt(["add","install","update"])&&(ft=!0),dt==="bun"&&vt(["add","install","update"])&&(ft=!0),dt==="deno"&&ht(["install","add"])&&(ft=!0),dt==="pip"&&ht(["install","download"])&&(ft=!0),dt==="pip3"&&ht(["install","download"])&&(ft=!0),dt==="cargo"&&ht(["install","add"])&&(ft=!0),["bash","sh","zsh","fish"].includes(dt)&&ht(["-c"])&&(ft=!0),dt==="cmd"&&ht(["/c"])&&(ft=!0),ft&&(ye="deny",Oe=!0)}!ye&&qe&&(ye="deny")}!be&&!ye&&ce&&(ye="allow")}else ce&&(ye="allow");let Re=ye,ne="";ye==="deny"&&(Oe?ne="network":qe?ne="settings":ne="prohibited");let he=!1,de="",Be=[],tt=0,ke=!1;if(!Re){if(M==="write_file"||M==="update_file")try{let Ie=O(q.args),{path:Ve}=Ie;if(Ve){let Ee=ee.resolve(process.cwd(),Ve),_t=ht=>ht?ht.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,vt=>vt.toUpperCase()):"",Zt=_t(Ee),un="",dt=!1,en=await gs(),ft=_t(en?.file_focused);if(en&&ft===Zt&&en.full_content?(un=en.full_content,dt=!0):De.existsSync(Ee)&&(un=De.readFileSync(Ee,"utf8"),dt=!0),de=un,await mt.recordFileChange(Ee,un),dt){let ht=un;if(M==="write_file")ht=Ie.content||Ie.newContent||"";else{let{patchPairs:vt,allowMultiple:kn,error:Sn}=Ao(Ie);if(Sn){let $t=`[TOOL RESULT]: ERROR: ${Sn}`;te.push({role:"user",text:$t}),await Lt("toolFailure"),t.onToolResult&&t.onToolResult("failure",M),yield{type:"tool_result",content:$t,toolName:M},Ge++;continue}let Ss=Ie.allowMultiple!==void 0?Ie.allowMultiple===!0||String(Ie.allowMultiple).toLowerCase()==="true":kn;tt=vt.length;let Mn=vo(un,vt,{allowMultiple:Ss});ht=Mn.content,Be=Mn.results;let yo=Be.filter($t=>$t.success),It=Be.filter($t=>!$t.success);if(yo.length===0){let $t=`[TOOL RESULT]: ERROR: Failed to apply patches to [${ee.basename(Ee)}].
|
|
665
|
-
${It.map(Gs=>` \u2022 ${Gs.error}`).join(`
|
|
666
|
-
`)}`,Ts=`\u2714 Edited: ${ee.basename(Ee.replaceAll("\\","/"))}`,Hs=115;process.stdout.isTTY&&(Hs=process.stdout.columns-5||120);let Rs=Math.min(Ts.length+4,Hs),wo=`${Ts.padEnd(Rs-2).substring(0,Rs-2)}`;yield{type:"visual_feedback",content:sn(`${We?`
|
|
667
|
-
`:""}${wo}`)},We=!1,te.push({role:"user",text:$t}),await Lt("toolFailure"),t.onToolResult&&t.onToolResult("failure",M),yield{type:"tool_result",content:$t,toolName:M},Ge++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${ee.basename(Ee)}`},si(Ee,un,ht),he=!0,await new Promise(vt=>setTimeout(vt,50))}else if(M==="write_file"){let ht=Ie.content||Ie.newContent||"",vt=ht.endsWith(`
|
|
668
|
-
`)?ht:ht+`
|
|
669
|
-
`;De.existsSync(Ee)||(ke=!0,De.mkdirSync(ee.dirname(Ee),{recursive:!0}),De.writeFileSync(Ee,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${ee.basename(Ee)}`},si(Ee,"",vt),he=!0,await new Promise(kn=>setTimeout(kn,50))}}}catch(Ie){console.error("Simulation/Diff Error:",Ie)}let Pe=null;ni(Ie=>{Pe=Ie});let ct=t.onToolApproval;if(Re=await new Promise(async Ie=>{let Ve=setInterval(()=>{Pe&&(Xo.onIDEApproval&&Xo.onIDEApproval(Pe),clearInterval(Ve),Ie(Pe))},100);try{let Ee=await ct(M,q.args);clearInterval(Ve),Ie(Ee)}catch{clearInterval(Ve),Ie("deny")}}),ni(null),M==="write_file"||M==="update_file"){let{path:Ie}=O(q.args);if(Ie){let Ve=ee.resolve(process.cwd(),Ie);if(Ra(Ve,Re),Re==="deny"&&ke&&De.existsSync(Ve))try{De.unlinkSync(Ve)}catch{}}}Re==="deny"&&(ne="user")}if(Re==="allow"&&he&&Uo()){let{path:Pe}=O(q.args),ct=ee.resolve(process.cwd(),Pe),Ie=It=>It?ee.resolve(It).replace(/\\/g,"/").toLowerCase():"",Ve=await gs(),Ee="";Ve&&Ve.file_focused&&Ie(Ve.file_focused)===Ie(ct)&&Ve.full_content&&(Ee=Ve.full_content),!Ee&&De.existsSync(ct)&&(Ee=De.readFileSync(ct,"utf8"),Ee||(await new Promise(It=>setTimeout(It,100)),Ee=De.readFileSync(ct,"utf8")));let _t=Ee.split(/\r?\n/),Zt=_t.length,un=Buffer.byteLength(Ee,"utf8"),dt="";de&&(dt=`Old File contents:
|
|
670
|
-
${de.split(/\r?\n/).map(($t,Ts)=>`${Ts+1} | ${$t}`).join(`
|
|
671
|
-
`)}
|
|
672
|
-
|
|
673
|
-
`);let en="";if(Zt<=100)en=_t.join(`
|
|
674
|
-
`);else{let It=_t.slice(0,50).join(`
|
|
675
|
-
`),$t=_t.slice(-50).join(`
|
|
676
|
-
`);en=`${It}
|
|
677
|
-
|
|
678
|
-
... [${Zt-100} lines truncated for history stability] ...
|
|
679
|
-
|
|
680
|
-
${$t}`}let ft="";if(M==="update_file"){let It=Io(de,Ee,Be,12,t?.compressToolResults||Xo?.systemSettings?.compressToolResults);ft=`SUCCESS: File [${Pe}] updated via IDE Companion (May have user edits). [${Be.length}/${tt}] blocks applied.
|
|
681
|
-
|
|
682
|
-
${It}`}else{let It=Ee.split(/\r?\n/),$t=It.length,Ts=Buffer.byteLength(Ee,"utf8"),Hs="";de&&(Hs=`Old File contents:
|
|
683
|
-
${de.split(/\r?\n/).map((Gs,tl)=>`${tl+1} | ${Gs}`).join(`
|
|
684
|
-
`)}
|
|
685
|
-
|
|
686
|
-
`);let Rs="";if($t<=100)Rs=It.join(`
|
|
687
|
-
`);else{let wo=It.slice(0,50).join(`
|
|
688
|
-
`),Gs=It.slice(-50).join(`
|
|
689
|
-
`);Rs=`${wo}
|
|
690
|
-
|
|
691
|
-
... [${$t-100} lines truncated] ...
|
|
692
|
-
|
|
693
|
-
${Gs}`}ft=`SUCCESS: File [${Pe}] saved via IDE Companion (May have user edits).
|
|
694
|
-
- Stats: [${$t} lines, ${(Ts/1024).toFixed(1)} KB]
|
|
695
|
-
${Hs}- Content Preview:
|
|
696
|
-
|
|
697
|
-
${Rs}`}let vt=`${Pe?"\u2714":"\u2718"} ${M==="write_file"?"Created":"Edited"}: ${Pe.replaceAll("\\","/")||"No File Changes"}`,kn=115;process.stdout.isTTY&&(kn=process.stdout.columns-5||120);let Sn=Math.min(vt.length+4,kn),Ss=`${vt.padEnd(Sn-2).substring(0,Sn-2)}`;yield{type:"visual_feedback",content:sn(`${We?`
|
|
698
|
-
`:""}${Ss}`)},We=!1;let Mn=Date.now();z=Mn,yield{type:"tool_time",content:Mn-pe};let yo=`[TOOL RESULT]: ${ft}`;te.push({role:"user",text:yo}),fn=!0,await Lt("toolSuccess"),t.onToolResult&&t.onToolResult("success",M),yield{type:"tool_result",content:ft,aiContent:yo,toolName:M},Ge++;continue}if(Re==="deny"){let Pe=`Permission Denied: Prohibited ${M==="exec_command"?"Command":"file edit"}.`;if(ne==="user"?Pe="Permission Denied by User":ne==="settings"?Pe="Permission Denied by User Policy":ne==="network"?Pe="Permission Denied: Sandbox Network Access Disabled by User Policy.":ne==="prohibited"&&M==="exec_command"&&(Pe="Permission Denied: Prohibited Command in User Policy"),M==="write_file"||M==="update_file"){let Ie=`\u2718 ${M==="write_file"?"Write Cancelled":"Edit Denied"}: ${O(q.args).path.replaceAll("\\","/")||"..."}`,Ve=115;process.stdout.isTTY&&(Ve=process.stdout.columns-5||120);let Ee=Math.min(Ie.length+4,Ve),_t=`${Ie.padEnd(Ee-2).substring(0,Ee-2)}`,Zt=` ${" ".repeat(Ee)} `;yield{type:"visual_feedback",content:sn(`${We?`
|
|
699
|
-
`:""}${_t}
|
|
700
|
-
`)},We=!1}M==="exec_command"&&(await new Promise(ct=>setTimeout(ct,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${Pe}`),await new Promise(ct=>setTimeout(ct,50)),t.onExecEnd&&t.onExecEnd()),te.push({role:"user",text:`[TOOL RESULT]: DENIED: ${Pe}`}),yield{type:"tool_result",content:`[TOOL RESULT]: DENIED: ${Pe}`},await Lt("toolDenied"),t.onToolResult&&t.onToolResult("denied",M),Ge++;continue}}if(Q){let v=115;process.stdout.isTTY&&(v=process.stdout.columns-5||120);let K=Math.min(Q.length+4,v),ce=`${Q.padEnd(K-2).substring(0,K-2)}`;yield{type:"visual_feedback",content:sn(`${We?`
|
|
701
|
-
`:""}${ce}${Q.includes("\u2714")&&(Q.includes("Created")||Q.includes("Edited"))?"":`
|
|
702
|
-
`}`)},We=!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 Wn={chatId:d,history:n,onChunk:v=>t.onExecChunk?t.onExecChunk(v):null,onAskUser:t.onAskUser,systemSettings:t.systemSettings,mode:i,isMultiModal:Ot(Te),onVisualFeedback:t.onVisualFeedback,onSubagentUpdate:t.onSubagentUpdate,onTokenChunk:t.onTokenChunk,modelName:Te,aiProvider:t.aiProvider,apiKey:t.apiKey,onUsage:t.onUsage};if(M==="write_file"||M==="update_file")try{let{path:v}=O(q.args);if(v){let K=ee.resolve(process.cwd(),v),ce=await gs();ce&&ce.file_focused===K&&ce.full_content&&(Wn.forcedContent=ce.full_content)}}catch{}on.push(M);let Me=await fo(M,q.args,Wn);if((M==="write_file"||M==="update_file")&&Me.startsWith("SUCCESS")){let{path:v}=O(q.args);if(v){let K=ee.resolve(process.cwd(),v);Ta(K)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let zt=Date.now();z=zt,yield{type:"tool_time",content:zt-pe},rn=zt;let Qt=null;if(typeof Me=="object"&&Me.binaryPart&&(Qt=Me.binaryPart,Me=Me.text),M==="search_keyword"){let{keyword:v,path:K}=O(q.args),ce=typeof Me=="string"&&Me.startsWith("[GLOB]");ce&&(Me=Me.slice(6).trimStart());let ye=typeof Me=="string"&&Me.startsWith("[DIR]");ye&&(Me=Me.slice(5).trimStart());let be=0;if(Me){let Be=Me.match(/Found (\d+) match/i);Be&&(be=parseInt(Be[1]))}let qe=K?K.replace(/[\/\\]+$/,""):null,Oe=qe&&qe!=="."?`"${ce?K:ye?`${qe}/*`:qe}"`:"./",Re=`${v?"\u2714":"\u2718"} Searched: "${v||""}" in ${Oe.replaceAll("\\","/")} \u2192 ${be} Match${be===1?"":"es"}`,ne=115;process.stdout.isTTY&&(ne=process.stdout.columns-5||120);let he=Math.min(Re.length+4,ne),de=`${Re.padEnd(he-2).substring(0,he-2)}`;yield{type:"visual_feedback",content:sn(`${We?`
|
|
703
|
-
`:""}${de}
|
|
704
|
-
`)},We=!1}if(M==="EmergencyRollback"){let{method:v}=O(q.args);if(v==="forceRevert"){let K=0;if(Me){let Re=Me.match(/Total\s*:\s*(\d+)/i);Re&&(K=parseInt(Re[1]))}let ye=Me&&Me.startsWith("ERROR:")?"\u2718 Emergency Rollback Failed":`\u2714 Emergency Rollback \u2192 ${K} file${K===1?"":"s"} processed`,be=115;process.stdout.isTTY&&(be=process.stdout.columns-5||120);let qe=Math.min(ye.length+4,be),Oe=`${ye.padEnd(qe-2).substring(0,qe-2)}`;yield{type:"visual_feedback",content:sn(`${We?`
|
|
705
|
-
`:""}${Oe}
|
|
706
|
-
`)},We=!1}}if(M==="todo"){let{method:v,tasks:K,markDone:ce}=O(q.args),ye="",be=[],qe=Oe=>{if(!Oe)return[];let Re=Array.isArray(Oe)?Oe:[];if(Re.length===0&&typeof Oe=="string"){let ne=Oe.trim();if(ne.startsWith("[")&&ne.endsWith("]")){let he=ne.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);he?Re=he.map(de=>de.slice(1,-1).replace(/\\(.)/g,"$1")):Re=ne.slice(1,-1).split(",").map(de=>de.trim()).filter(Boolean)}else Re=Oe.split(`
|
|
707
|
-
`)}return Re.filter(ne=>String(ne).trim()).map(ne=>{let he=String(ne).trim();return he.startsWith("- [")?he.substring(6).trim():he})};if(v==="create"?(ye="\x1B[32m\u2192\x1B[0m Created Goals",be=qe(K).map(Oe=>`\x1B[90m\u25CB\x1B[0m ${Oe}`)):v==="append"?(ye="\x1B[34m\u2795\x1B[0m Added New Goals",be=qe(K).map(Oe=>`\x1B[90m\u25CB\x1B[0m ${Oe}`)):v==="get"&&(ye=ce?"\x1B[36m\u21BB\x1B[0m Updated Goals":"\x1B[35m\u2022\x1B[0m Reviewed Goals",be=(Me||"").split(`
|
|
708
|
-
`).slice(1).join(`
|
|
709
|
-
`).split(`
|
|
710
|
-
`).filter(Re=>Re.trim().startsWith("- [")).map(Re=>{let ne=Re.trim(),he=ne.startsWith("- [x]");return`${he?"\x1B[32m\u2714\x1B[0m":"\x1B[90m\u25CB\x1B[0m"} ${he?"\x1B[90m":"\x1B[37m"}${ne.substring(6).trim()}\x1B[0m`})),ye&&be.length>0){let Oe=[`${ye}`,...be.map(Re=>` ${Re}`)].join(`
|
|
711
|
-
`);yield{type:"visual_feedback",content:sn(`${We?`
|
|
712
|
-
`:""}${Oe}
|
|
713
|
-
`)},We=!1}}M==="exec_command"&&t.onExecEnd&&(await new Promise(v=>setTimeout(v,800)),t.onExecEnd());let $n=Me&&Me.startsWith("DENIED:");Me&&!Me.startsWith("ERROR:")&&!$n?(await Lt("toolSuccess"),t.onToolResult&&t.onToolResult("success",M)):$n||(await Lt("toolFailure"),t.onToolResult&&t.onToolResult("failure",M));let Kt=(Me||"").toString().replaceAll("[UI_CONTEXT]","");Kt.includes("[[VERIFIED]]")&&(Kt=Kt.replace(/\[\[VERIFIED\]\][\s\S]*?\[\[\/VERIFIED\]\]/g,`[SYSTEM NOTE]: Patch Block matched & applied successfully. Large Block omitted to conserve context.
|
|
714
|
-
`));let Cn;if(Kt.startsWith("[[SAME]]")){let K=Kt.replace(/^\[\[SAME\]\]\s*\r?\n?/,"").split(/\r?\n/),ce=K.filter(be=>be.startsWith("SUCCESS:")||be.trim().startsWith("- Stats:"));Cn=`[TOOL RESULT]: ${ce.length>0?ce.join(`
|
|
715
|
-
`):K.slice(0,2).join(`
|
|
716
|
-
`)}
|
|
717
|
-
[SYSTEM NOTE]: Content verified and persisted to disk. Full preview omitted to conserve context.`}else Cn=`[TOOL RESULT]: ${Kt}`;te.push({role:"user",text:Cn,binaryPart:Qt}),fn=!0;let ve=`[TOOL RESULT]: ${Me.replaceAll(`[[VERIFIED]]
|
|
718
|
-
`,"").replaceAll(`
|
|
719
|
-
[[/VERIFIED]]`,"")||""}`;(M==="view_file"||M==="web_scrape"||M==="file_map")&&(ve=`[TOOL RESULT]: ${Q} (Context Locked for UI Clarity)`),yield{type:"tool_result",content:ve,aiContent:Cn,binaryPart:Qt,toolName:M},M==="memory"&&Me.includes("SUCCESS")&&(yield{type:"memory_updated"}),Ge++}if(u==="Google"&&Ft&&Date.now()-nr>=150){yield*ss();let q=Ws(Ft);for(let pe of q)yield pe;Ft="",nr=Date.now()}}P.usageMetadata&&(Rn=P.usageMetadata),Rn&&(yield{type:"liveTokens",content:Rn.totalTokenCount})}if(ue&&(ue=!1,Gt?Ke+="</think>":(le+="</think>",u==="Google"?Ft+="</think>":yield{type:"text",content:"</think>"})),Gt&&Ke.length>0){let P=0,re=Math.min(nt.length,Ke.length);for(let H=re;H>0;H--)if(nt.endsWith(Ke.substring(0,H))){P=H;break}let j=Ke.substring(P);if(j){let xe=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(nt)?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(xe)if(le+=xe,u==="Google")Ft+=xe;else{yield*ss();let ge=Ws(xe);for(let Ce of ge)yield Ce}}Gt=!1,Ke=""}if(yield*ss(),Pt)break;let js=(le||"").trim(),Va=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(js.toLowerCase())||/\[\[END\]\]/i.test(js.toLowerCase()),Xa=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(js.toLowerCase()),Ja=te.length>0||jt!==null,sr=js.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/gi,"").trim(),Qa=/(\p{Emoji_Presentation}|\p{Extended_Pictographic})$/u.test(sr),Za=/([.!?"'*_`|\]\)”’~~]+|\s|`{3}|[\u200B-\u200D\uFEFF])$/u.test(sr.trim()),el=/[.!?}"'`’“”]$|```$/s.test(sr)||Za||Qa;!Va&&!Xa&&!Ja&&js.length>0,Ze=!0,await Lt("agent",u)}catch(we){if(Pt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
|
|
720
|
-
|
|
721
|
-
\x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(String(we).includes("Incomplete JSON segment at the end")){ue&&(ue=!1,Gt?Ke+="</think>":(le+="</think>",yield{type:"text",content:"</think>"})),Ze=!0,await Lt("agent",u);break}if(ue&&(ue=!1,Gt?Ke+="</think>":le+="</think>"),Gt&&Ke.length>0){let Un=0,Jt=Math.min(nt.length,Ke.length);for(let ot=Jt;ot>0;ot--)if(nt.endsWith(Ke.substring(0,ot))){Un=ot;break}let At=Ke.substring(Un);if(At){let Ft=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(nt)?At.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):At.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");Ft&&(le+=Ft)}Gt=!1,Ke=""}let ie=we instanceof Error?(()=>{try{return JSON.parse(JSON.parse(we.message).error.message).error.message}catch{return String(we)}})():String(we),st=new Date().toLocaleString(),Mt=ee.join(hn,"agent");De.existsSync(Mt)||De.mkdirSync(Mt,{recursive:!0}),De.appendFileSync(ee.join(Mt,"error.log"),`ERROR [${st}]: ${ie}
|
|
722
|
-
|
|
723
|
-
----------------------------------------------------------------------
|
|
724
|
-
|
|
725
|
-
`);let an=we.status||we.statusCode||we.code,Et=String(we).includes("replicas at capacity");if(!(an&&(an>=500&&an<600||an===408||an===429||Et)||!an&&(/status[ :]+(5\d\d|408|429)/i.test(String(we))||/code[ :]+(5\d\d|408|429)/i.test(String(we))||/(500|503|408|429)/.test(String(we))))){if(He<wn-3)throw we;yield{type:"text",content:ie},yield{type:"status",content:"Error Occured"}}if(le.trim().length>0||Je>1)if(Je<=wn){Je++;let Un=Math.min(1e3*Math.pow(2,Je-1),24e3);if(le.trim().length>0){b.push({role:"agent",text:le});let Jt=`[system]
|
|
726
|
-
- seamless continuation: resume immediately. pick up from last words with zero gap/disruption
|
|
727
|
-
- no repetition: do not repeat any text already written
|
|
728
|
-
- no re-think: do not restart or open <think> if reasoning already started. continue the thinking and close thinking block </think> before chat output
|
|
729
|
-
- mid-tool safety: if cutoff was mid-tool call, restart that tool call from start
|
|
730
|
-
- stealth: do not mention/apologize for cutoff [/system]`;te.length>0?te.forEach((At,ot)=>{ot===te.length-1?b.push({...At,text:`${At.text}
|
|
731
|
-
|
|
732
|
-
${Jt}`}):b.push(At)}):b.push({role:"user",text:Jt}),nt+=le}for(let Jt=Un/1e3;Jt>0&&!Pt;Jt--)yield{type:"status",content:`Error Occured. Recovering Stream (${Je}/${wn}) [Retrying in ${Jt.toFixed(0)}s]...`},await new Promise(At=>setTimeout(At,1e3));yield{type:"status",content:"Error Occured. Recovering Stream..."}}else throw new Error(`Stream collapsed too many times. (Failed to resolve ${wn} times)
|
|
733
|
-
Error log can be found in \`/export logs\``);else if(He<=wn){He++,Je=1,nt="";let Un=Math.min(1e3*Math.pow(2,He-1),32e3),Jt=.8+Math.random()*.4,At=Math.round(Un*Jt);Zn=!0,yield{type:"status",content:`Trying to reach ${e} (${He}/${wn}) [Retrying in ${(At/1e3).toFixed(0)}s]`};for(let ot=At/1e3;ot>0&&!Pt;ot--)yield{type:"status",content:`Trying to reach ${e} (${He}/${wn}) [Retrying in ${ot.toFixed(0)}s]`},await new Promise(Ft=>setTimeout(Ft,1e3));yield{type:"status",content:`Trying to reach ${e}`}}else throw new Error(`Model ${e} cannot be reached. (Failed ${wn} times)
|
|
734
|
-
Error log can be found in \`/export logs\``)}}if(Rn){let ue=Rn.totalTokenCount||0,we=Rn.cachedContentTokenCount||0,ie=(Rn.candidatesTokenCount||0)+(Rn.thoughtsTokenCount||0);await Yt("tokens",ue,u,Te),we>0&&await Yt("cachedTokens",we,u,Te),ie>0&&await Yt("candidateTokens",ie,u,Te),yield{type:"usage",content:Rn}}bi.push(le);let Nn=le;le.match(/(?:<think>|\[think\])([\s\S]*?)(?:<\/think>|\[\/think\])/i)&&(Nn=le.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/i,""));let ts=Da(le),_n=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(ts.toLowerCase())||/\[\[END\]\]/i.test(ts.toLowerCase())||!0,Uc=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(ts.toLowerCase()),Wc=Ge>0;yield{type:"status",content:"Thinking"};let Ga=Oc(le,/(\[\s*(turn\s*:)?\s*(continue|finish)\s*\]|\[\[END\]\])/gi,"").trim(),ns=(_n||te.length===0)&&!Ht&&!xn&&!En;if(ns=te.length===0?ns:!1,ns=es||mo?!1:ns,le&&le.trim().endsWith('")]')&&te.length===0&&(ns=!1),ns){let ue=bi.join(`
|
|
735
|
-
`),we=ue.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").trim();yield{type:"interactive_turn_finished",data:{agentText:T,fullAgentTextRaw:ue,history:[...b],needTitle:k}},b.length>0&&b[b.length-1].role==="agent"?b[b.length-1].text=we:b.push({role:"agent",text:we}),b.forEach(ie=>{if(ie.role==="user"&&ie.text&&(ie.text=ie.text.replace(/\n\[COMPILE ERROR\][\s\S]*?\[\/ERROR\]/g,""),ie.text=ie.text.replaceAll(`
|
|
736
|
-
|
|
737
|
-
[system] user question. resolve this specific query within '[ANSWER] ... [/ANSWER]' concisely, naturally [/system]
|
|
738
|
-
`,"").replaceAll(`[system] user question. resolve this specific query within '[ANSWER] ... [/ANSWER]' concisely, naturally
|
|
739
|
-
**strictly follow thinking policy as high priority. do not start a response without <think>...</think>** [/system]
|
|
740
|
-
`,"").replaceAll(`[system] **strictly follow thinking policy as high priority. do not start a response without <think>...</think>** [/system]
|
|
741
|
-
`,"").replaceAll(/\n\[system\] WARNING, Turn Limit Impending: Step \d+\/\d+\. Wrap up quickly\/prompt user to continue & use \[\[END\]\] quickly\. \[\/system\]/g,""),ie.text=ie.text.replaceAll(/\n\[system\] File Changes:\n(?:\* .+ \(created|modified|deleted\)\n)*\[\/system\]/g,""),(u==="Mistral"||u==="Google"&&e?.toLowerCase().startsWith("gemma"))&&ie.text.startsWith("[TOOL RESULT]"))){let Mt=`
|
|
742
|
-
[system] Tool result received. Analyze output and proceed with your turn [/system]`,an=`
|
|
743
|
-
[system] Tool result received. Analyze output and proceed with your turn. **strictly follow thinking policy. do not start a response without <think>...</think>** [/system]`;ie.text=ie.text.replaceAll(an,"").replaceAll(Mt,"").trim()}}),yield{type:"status",content:"[end]"}}if(ns)break;let qa=Ga.trim()||"*Working...*";if(b.push({role:"agent",text:qa}),te.length>0||fn){if(te.length>0){let ue=te.map(Mt=>Mt.text).join(`
|
|
744
|
-
|
|
745
|
-
`),ie=(le.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/gi,"").match(/\[tool:/gi)||[]).length;if(te.length<ie){ue+=`
|
|
746
|
-
|
|
747
|
-
[system] Only ${te.length} out of ${ie} attempted tool calls were executed. Verify proper structure compliance & try failed calls again [/system]`;let Mt=ie-te.length;for(let an=0;an<Mt;an++)await Lt("toolFailure")}let st=te.find(Mt=>Mt.binaryPart)?.binaryPart||null;b.push({role:"user",text:ue,binaryPart:st})}}else{let we=(le.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/gi,"").match(/\[tool:/gi)||[]).length;mo||es||we>0?(b.push({role:"user",text:`[system] Failed to execute ${we} tool${we>1?"s":""}. Verify proper structure compliance & try again [/system]`}),await Lt("toolFailure"),yield{type:"visual_feedback",content:`
|
|
748
|
-
${sn("\u2718 Execution Error")}
|
|
749
|
-
`}):(yield{type:"visual_feedback",content:`
|
|
750
|
-
${sn("\u2718 Loop Detected")}
|
|
751
|
-
`},b.push({role:"user",text:`[system] ${xn&&!Ht?"Stuttering Detected by Internal System. Re-calibrate your response & proceed.":`${Ht?" Over Thinking":" Loop"} Detected by Internal System${Ht?" for current Effort Level":""}. ${Ht?"If you have planned the task, prioritize execution/output":"If you have finished your task provide a simple summary and end"}`} [/system]`})),Ht=!1,xn=!1,En=!1}l?.advanceRollback&&await Yn.recordTurnDelta(d,G+1,on),mo=Ge>0||fn}}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=ee.join(hn,"agent");yield{type:"text",content:`\u2726 CRITICAL ERROR: ${$.includes("fetch failed")?"Failed to Connect. Check your Internet Connection or Wait a moment":$}
|
|
752
|
-
\u2800`},De.existsSync(D)||De.mkdirSync(D,{recursive:!0}),De.appendFileSync(ee.join(D,"error.log"),`CRITICAL ERROR [${I}]: ${E}
|
|
753
|
-
|
|
754
|
-
----------------------------------------------------------------------
|
|
755
|
-
|
|
756
|
-
`),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 mt.commitTransaction(),l?.advanceRollback&&await Yn.cleanup(d),await gs()}yield{type:"status",content:null}},cg=async(e,n,t=null,o=null,s=50,r=null,a=!1)=>{let i=await Bt(),h={...i,...n},d=process.env.SUBAGENT_MODEL?process.env.SUBAGENT_MODEL.trim():null,c=process.env.SUBAGENT_PROVIDER?process.env.SUBAGENT_PROVIDER.trim():null,l=new Date,f=`${l.getFullYear()}-${l.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(l.getDate()).padStart(2,"0")}, ${l.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}).replace(":","-")}`,p=(E=>{if(!E)return null;let b=E.toLowerCase();return b==="google"?"Google":b==="deepseek"?"DeepSeek":b==="openrouter"?"OpenRouter":b==="nvidia"?"NVIDIA":b==="mistral"?"Mistral":b==="ollama"?"Ollama":b==="crofai"||b==="crof"?"CrofAI":b==="inferx"?"InferX":b==="sensenova"?"SenseNova":null})(c),g=h?.systemSettings?.CustomSubAgent?h?.systemSettings?.SubAgentModel:null,y=h?.systemSettings?.CustomSubAgent?h?.systemSettings?.SubAgentProvider:null,m=null;if(g==="ENV"?(m=d,d&&p&&(h.aiProvider=p)):g&&g!=="Default"?(m=g,y&&(h.aiProvider=y)):d&&p&&(h.aiProvider=p),h.aiProvider){let E=await ar(h.aiProvider);E&&(h.apiKey=E)}let w=E=>{if(!E||typeof E!="string")return{allowed:!0};let b=[/rm\s+-[rf]{1,2}\s+[\/*.]/i,/rmdir\s+\/[sq]/i,/del\s+\/[fsq]/i,/\bformat\b\s+[a-z]:/i,/mkfs/i,/dd\s+if=/i,/\b(shutdown|reboot|poweroff|init\s+0|init\s+6)\b/i,/chmod\s+(-R\s+)?777\s+[\/*.]/i,/chown\s+(-R\s+)?root/i,/git\s+push\s+.*--force/i,/git\s+clean\s+-fdx/i,/\bsudo\s+su\b/i,/\bsu\s+-\b/i];for(let $ of b)if($.test(E))return{allowed:!1,reason:`Blocked potentially destructive or unsafe command pattern: "${$.source}"`};return{allowed:!0}},x=t||m||n?.modelName||n?.activeModel||i.activeModel,S=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",C=`-- TOOL DEFINITIONS (path = relative to CWD, path separator: '/') --
|
|
757
|
-
You cant execute tools. To use tools, must output exactly [tool:functions.ToolName(arg1="value1")] structured string in chat response \u2190 no exception, tool:functions must
|
|
758
|
-
Tool Rules:
|
|
759
|
-
- JSON escape literal escape sequences in tool arguments (new line: \\\\n, backslash: \\\\)
|
|
760
|
-
- Same file, multiple edits? ONE PatchFile (\u226415 blocks) \u2190 Priority
|
|
761
|
-
- Tool denied? Ask for guidance \u2190 mandatory
|
|
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 and syntax defined below are allowed
|
|
767
|
-
- Stuck on syntax error? Tell user > Time waste
|
|
768
|
-
|
|
769
|
-
# Provided Tools
|
|
770
|
-
**Communication Tools**
|
|
771
|
-
- Ask(question="...", optionA="title::description", ...MAX4). Ambiguity, path divergence, security risk. Ask, dont finish/guess. Keep titles short
|
|
772
|
-
${a?'- AskMain(question="..."). Communicate with PARENT/MAIN AGENT. When clarification/decision is needed for a task':""}
|
|
773
|
-
|
|
774
|
-
**Web Tools**
|
|
775
|
-
- WebSearch(query="...", aiMode="bool, optional", limit="integer 3-10 aiMode: exclude"). Proactive use for unknown info/docs. aiMode: LLM search
|
|
776
|
-
- WebScrape(url="..."). Proactive use for specific webpage/docs/api
|
|
777
|
-
|
|
778
|
-
**Workspace Tools**
|
|
779
|
-
- 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
|
|
780
|
-
- ReadFolder(path="...", recurse="int 1-3"). Minimize recursion
|
|
781
|
-
- ReadFile(path="...", startLine="int", endLine="int")
|
|
782
|
-
- 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
|
|
783
|
-
- WriteFile(path="...", content="..."). Creates/Overwrites. File Exist? PatchFile > WriteFile. VERIFY IMPORTS
|
|
784
|
-
- Run(command="..."). Runs ${S==="Windows"?Gn()?"powershell":"windows CMD":"bash"} command. Destructive/Irreversible ops \u2192 Ask user`.trim(),R=`=== START SYSTEM PROMPT ===
|
|
785
|
-
Identity: FluxFlow subagent helping the main Agent
|
|
786
|
-
Your task is: "${e}"
|
|
787
|
-
|
|
788
|
-
${C.trimEnd()}
|
|
789
|
-
|
|
790
|
-
-- THINKING GUIDANCE --
|
|
791
|
-
NO EXPLICIT THINKING REQUIRED. FOCUS ON TASK COMPLETION
|
|
792
|
-
Main focus: tools and task, not chatting
|
|
793
|
-
On completion, provide a detailed summary in Tables/Markdown Format with file modified info. If any task failed report back in detail
|
|
794
|
-
|
|
795
|
-
CWD: ${process.cwd()}
|
|
796
|
-
Current Time: ${f}
|
|
797
|
-
=== END SYSTEM PROMPT ===`,k=[{role:"user",text:`Complete this task: ${e}`}],T=0,_="";for(;T<s;){if(Pt){if(n?.taskId&&typeof Xe<"u"){let F=Xe.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 Xe<"u"){let F=Xe.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=k.map(F=>({role:F.role==="user"?"user":"model",parts:[{text:F.text}]}));r&&r(`[Subagent Turn ${T+1}]...`);let I=((await Jo(h,x,E,R,"Fast")).text||"").replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/gi,"").trim();_=I,r&&r(`[Subagent Response]
|
|
798
|
-
${I}
|
|
799
|
-
`),k.push({role:"agent",text:I});let D=Qo(I);if(D.length===0)break;let B=D.filter(F=>F.toolName.toLowerCase()==="askmain"||F.toolName.toLowerCase()==="ask_main"),W=!1,Y="";for(let F of D){if(Pt){if(n?.taskId&&typeof Xe<"u"){let A=Xe.find(N=>N.id===n.taskId);A&&(A.status="cancelled")}throw new Error("Subagent task was cancelled.")}if(n?.taskId&&typeof Xe<"u"){let A=Xe.find(N=>N.id===n.taskId);if(A&&A.status==="cancelled")throw new Error("Subagent task was cancelled.")}let U=F.toolName.toLowerCase();if(U==="askmain"||U==="ask_main"){if(W)continue;W=!0;let A="";if(B.length===1?A=O(B[0].args).question||B[0].args:A=B.map((N,V)=>{let J=O(N.args);return`Q${V+1}: ${J.question||N.args}`}).join(`
|
|
800
|
-
`),n.onAskMain){r&&r(`[Executing Tool] AskMain("${A}")...`);let N=await n.onAskMain(A);r&&r(`[Tool Result]
|
|
801
|
-
Answer from Main Agent: ${N}
|
|
802
|
-
`),Y+=`[TOOL RESULT for AskMain]: Answer from Main Agent: ${N}
|
|
803
|
-
|
|
804
|
-
`,await Lt("toolSuccess")}else Y+=`[TOOL RESULT for AskMain]: ERROR: Main agent communication channel not available.
|
|
805
|
-
|
|
806
|
-
`;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
|
|
807
|
-
`),Y+=`${A}
|
|
808
|
-
|
|
809
|
-
`;continue}if(U==="exec_command"||U==="execcommand"||U==="run"){let A=O(F.args).command||"",N=w(A);if(!N.allowed){let V=`ERROR: [SECURITY RESTRICTION] Subagent execution blocked command: ${N.reason}`;r&&r(`[Blocked Command] ${A} - ${N.reason}
|
|
810
|
-
`),Y+=`${V}
|
|
811
|
-
|
|
812
|
-
`;continue}}let Ae="";if(U==="web_search"||U==="websearch")Ae=`\u2714 \x1B[95mSearched\x1B[0m: ${O(F.args).query||""}`;else if(U==="web_scrape"||U==="webscrape")Ae=`\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),N=A.keyword||"",V=A.path||"";Ae=`${N?"\u2714":"\u2718"} \x1B[95mSearched\x1B[0m: ${N||"No Query"}${V?` \u2192 ${V.replaceAll("\\","/")}`:""}`}else if(U==="view_file"||U==="viewfile"||U==="readfile")Ae=`\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,N=O(F.args).recurse||0;Ae=`${A?"\u2714":"\u2718"} \x1B[95mBrowsed\x1B[0m: ${A?`${A.replaceAll("\\","/")}${N>0?`${A.endsWith("/")?`*${N}`:`/*${N}`}`:`${A.endsWith("/")?"":"/"}`}`:""}`}else if(U==="write_file"||U==="writefile"){let A=O(F.args).path||null;Ae=`${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,N=O(F.args).content||null;Ae=`${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;Ae=`${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||"";Ae=`${A?"\u2714":"\u2718"} \x1B[95mIndexed\x1B[0m: ${A?`${A.replaceAll("\\","/")}`:"File Not Found"}`}else if(U==="await"){let{time:A}=O(F.args),N=parseFloat(A)||0;N<10&&(N=10),N>180&&(N=180),Ae=`\u2714 \x1B[95mAwaiting\x1B[0m \u2192 ${(J=>{if(J>=60){let Ue=Math.floor(J/60),Fe=J%60;return`${Ue}m${Fe>0?` ${Fe}s`:""}`}return`${J}s`})(N)}`}else{let A=li[U]||F.toolName,N=xs(U,F.args);Ae=`\u2714 \x1B[95m${A}\x1B[0m${N?`: ${N}`:""}`}n.onVisualFeedback&&Ae&&n.onVisualFeedback(Ae),r&&r(`[Executing Tool] ${F.toolName}(${F.args})...`);try{let A=await fo(F.toolName,F.args,{...n,mode:"Flux"});if(r&&r(`[Tool Result]
|
|
813
|
-
${A}
|
|
814
|
-
`),Y+=`[TOOL RESULT for ${F.toolName}]: ${A}
|
|
815
|
-
|
|
816
|
-
`,await Lt("toolSuccess"),U==="patchfile"||U==="update_file"||U==="updatefile"||U==="patch_file"){if(A){let N=A.split(`
|
|
817
|
-
`),V=0,J=0,Ue=!1;for(let Fe of N){if(Fe.includes("[DIFF_START]")){Ue=!0;continue}if(Fe.includes("[DIFF_END]")){Ue=!1;continue}Ue&&(/^\+\d+/.test(Fe)?V++:/^\-\d+/.test(Fe)&&J++)}(V>0||J>0)&&(await Yt("linesAdded",V),await Yt("linesRemoved",J))}}else if((U==="writefile"||U==="write_file")&&A){let N=A.match(/- Stats: \[(\d+) lines/),V=N?parseInt(N[1]):0,J=0;if(A.includes("Old File contents:")){let Ue=!1;for(let Fe of A.split(`
|
|
818
|
-
`)){if(Fe.includes("Old File contents:")){Ue=!0;continue}Ue&&(Fe.trim()===""?Ue=!1:/^\d+ \|/.test(Fe)&&J++)}}(V>0||J>0)&&(await Yt("linesAdded",V),await Yt("linesRemoved",J))}}catch(A){let N=`ERROR: Execution failed for [${F.toolName}]: ${A.message}`;r&&r(`[Tool Error] ${N}
|
|
819
|
-
`),Y+=`${N}
|
|
820
|
-
|
|
821
|
-
`,await Lt("toolFailure")}}let X="";if(n?.taskId&&typeof Xe<"u"){let F=Xe.find(U=>U.id===n.taskId);if(F&&F.pendingSteerMessages&&F.pendingSteerMessages.length>0){let U=[...F.pendingSteerMessages];F.pendingSteerMessages=[];for(let se of U)X+=`
|
|
822
|
-
|
|
823
|
-
[STEERING INSTRUCTION FROM MAIN AGENT]: ${se}`,r&&r(`[Subagent Steered] ${se}`)}}let fe=(Y.trim()+X).trim();k.push({role:"user",text:fe}),T++}return _};export{gn as a,Vi as b,_f as c,$f as d,El as e,Xi as f,Cf as g,Ol as h,Mf as i,uo as j,ba as k,Fp as l,Np as m,O as n,Kc as o,cr as p,Ks as q,Yc as r,Vc as s,mt as t,ls as u,_d as v,dl as w,$d as x,Cd as y,Md as z,Ad as A,vd as B,Nd as C,Bd as D,Tn as E,pl as F,Xs as G,Yt as H,ml as I,Ui as J,cs as K,ql as L,$u as M,Cu as N,Wp as O,Uo as P,jp as Q,Rc as R,Ac as S,sg as T,og as U,fi as V,rg as W,ig as X,Nc as Y,ag as Z,lg as _,cg as $};
|