fluxflow-cli 4.46.0 → 4.47.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/dist/chunks/{ai-ES7GEGZ2.js → ai-IQMYBYU6.js} +1 -1
  2. package/dist/chunks/app-IPNLGJWQ.js +333 -0
  3. package/dist/chunks/{auto_completion-ZGT6WREW.js → auto_completion-HIR5DVL5.js} +1 -1
  4. package/dist/chunks/{chunk-MAXLHC7A.js → chunk-45DLFA4C.js} +1 -1
  5. package/dist/chunks/chunk-AMFNIFF3.js +44 -0
  6. package/dist/chunks/{chunk-2ZGSUC4G.js → chunk-ER3SNTS7.js} +1 -1
  7. package/dist/chunks/{chunk-TQOQHYJ6.js → chunk-GM5VNNTU.js} +1 -1
  8. package/dist/chunks/{chunk-JPJB2SJL.js → chunk-MS33ZWST.js} +1 -1
  9. package/dist/chunks/{chunk-FXGGSOXY.js → chunk-OSSZ4LIE.js} +1 -1
  10. package/dist/chunks/chunk-U2GX6WT2.js +1 -0
  11. package/dist/chunks/{chunk-KYQFLMZE.js → chunk-UIL6OCU4.js} +3 -3
  12. package/dist/chunks/{chunk-BKGKMEQ4.js → chunk-UNOUKPFA.js} +185 -184
  13. package/dist/chunks/chunk-XDY4KWTM.js +1 -0
  14. package/dist/chunks/{click-ZZBBIP7F.js → click-R35XTYKT.js} +2 -2
  15. package/dist/chunks/{computer_action-5SW7LW5R.js → computer_action-WNXZNAIZ.js} +1 -1
  16. package/dist/chunks/custom_openai-YS5EV6DG.js +3 -0
  17. package/dist/chunks/{drag-OBMCSGER.js → drag-IB5WSI6F.js} +1 -1
  18. package/dist/chunks/{exec_command-BDFXJQZJ.js → exec_command-6V5SM6WI.js} +1 -1
  19. package/dist/chunks/{generate_image-ALAAHL2E.js → generate_image-VW5VG6VI.js} +1 -1
  20. package/dist/chunks/{invoke-DCX72AHI.js → invoke-QXYLLM2W.js} +2 -2
  21. package/dist/chunks/{invokeSync-GQPUH52H.js → invokeSync-UYRKSUNO.js} +2 -2
  22. package/dist/chunks/{key_press-65GEUW4K.js → key_press-XDYBP7DW.js} +1 -1
  23. package/dist/chunks/{keyboard_typing-GCMJCV7O.js → keyboard_typing-YHYH7O66.js} +1 -1
  24. package/dist/chunks/ollama-QB7WX7VD.js +2 -0
  25. package/dist/chunks/{recapture_screen-QB65V5CM.js → recapture_screen-F6ZPZU56.js} +1 -1
  26. package/dist/chunks/{screen_grid-M5K7ZHKD.js → screen_grid-IWNA3DA2.js} +1 -1
  27. package/dist/chunks/{scroll-LTWDNSC6.js → scroll-GIP2J2QN.js} +1 -1
  28. package/dist/chunks/{search_keyword-GT5GEEJW.js → search_keyword-O52M65TB.js} +1 -1
  29. package/dist/chunks/secrets-YIWFP4S2.js +1 -0
  30. package/dist/chunks/secrets_v2-TEUFHDI7.js +1 -0
  31. package/dist/chunks/{settings-4RNTQJ75.js → settings-HSQ2K6DN.js} +1 -1
  32. package/dist/chunks/{update_file-ALQM76Y4.js → update_file-QKDDZKOX.js} +1 -1
  33. package/dist/chunks/{usage-67IZJXM2.js → usage-6V4XZT3Q.js} +1 -1
  34. package/dist/chunks/{usageServer-HBVYDUQK.js → usageServer-4XHUFY7X.js} +1 -1
  35. package/dist/chunks/{write_file-XHSRFBMF.js → write_file-D7QA2LB2.js} +1 -1
  36. package/dist/cli.js +5 -5
  37. package/dist/package.json +88 -88
  38. package/package.json +88 -88
  39. package/dist/chunks/app-FR7775JT.js +0 -333
  40. package/dist/chunks/chunk-7D7IG3AG.js +0 -1
  41. package/dist/chunks/chunk-MKC4AVAL.js +0 -44
  42. package/dist/chunks/chunk-MXADZLMH.js +0 -1
  43. package/dist/chunks/custom_openai-XMDYE7NM.js +0 -3
  44. package/dist/chunks/ollama-4PI2BDMM.js +0 -2
  45. package/dist/chunks/secrets-HSGGFVG5.js +0 -1
  46. package/dist/chunks/secrets_v2-YV7YCUN7.js +0 -1
@@ -1,4 +1,4 @@
1
- import{a as Ds}from"./chunk-HFTI3R3Q.js";import{a as Ro}from"./chunk-52STSLCN.js";import{a as en}from"./chunk-56EJGQU3.js";import{a as Bs}from"./chunk-4BLSASW6.js";import{c as Ni,g as Di,h as Ps,i as Os}from"./chunk-MKC4AVAL.js";import{b as Ls,c as $s,d as Fi,f as Ns}from"./chunk-KYQFLMZE.js";import{b as Bi,h as Fs}from"./chunk-Z5D4VQSG.js";import{a as ti}from"./chunk-6EYQQ7GQ.js";import{a as j}from"./chunk-Y5JU726N.js";import{b as Li}from"./chunk-7D7IG3AG.js";import{u as Oi}from"./chunk-MXADZLMH.js";import{f as Co,l as Lt,n as At,p as $i,q as Ms}from"./chunk-FXGGSOXY.js";import{b as Eo}from"./chunk-MAXLHC7A.js";import{l as lt,m as ei,q as ae}from"./chunk-HTOLY3HR.js";import{c as Ot,d as co,e as Zo}from"./chunk-P5HBJA23.js";import{a as Un,b as Xo,d as wn,e as Jo,k as Xn,l as Qo,m as Mi,r as Pi,w as To,x as Ao,y as Is}from"./chunk-26BQ45XP.js";import{GoogleGenAI as ia,ThinkingLevel as Ye,HarmBlockThreshold as Gn,HarmCategory as Hn}from"@google/genai";var Us=(e=!0,n=!0)=>`
1
+ import{a as Ds}from"./chunk-HFTI3R3Q.js";import{a as Ro}from"./chunk-52STSLCN.js";import{a as en}from"./chunk-56EJGQU3.js";import{a as Bs}from"./chunk-4BLSASW6.js";import{c as Di,g as Fi,h as Ps,i as Os}from"./chunk-AMFNIFF3.js";import{b as Ls,c as $s,d as Bi,f as Ns}from"./chunk-UIL6OCU4.js";import{b as Ui,h as Fs}from"./chunk-Z5D4VQSG.js";import{a as ti}from"./chunk-6EYQQ7GQ.js";import{a as j}from"./chunk-Y5JU726N.js";import{b as $i}from"./chunk-XDY4KWTM.js";import{y as Li}from"./chunk-U2GX6WT2.js";import{f as Co,l as Lt,n as At,p as Ni,q as Ms}from"./chunk-OSSZ4LIE.js";import{b as Eo}from"./chunk-45DLFA4C.js";import{l as lt,m as ei,q as ae}from"./chunk-HTOLY3HR.js";import{c as Ot,d as co,e as Zo}from"./chunk-P5HBJA23.js";import{a as Un,b as Xo,d as wn,e as Jo,k as Jn,l as Qo,m as Pi,r as Oi,w as To,x as Ao,y as Is}from"./chunk-26BQ45XP.js";import{GoogleGenAI as ia,ThinkingLevel as Ye,HarmBlockThreshold as Gn,HarmCategory as Hn}from"@google/genai";var Us=(e=!0,n=!0)=>`
2
2
  To use tools, must output exactly '[action:ActionName(arg1="value1")]' structured string in chat response \u2190 no exception
3
3
 
4
4
  -- Chat Management Tools --
@@ -25,7 +25,7 @@ Usage Rules:
25
25
  - Chat title is mandatory
26
26
  - Temporary memory is mandatory
27
27
  - When called user memory, still use Temporary Memory
28
- - Must not ignore any tool calls in given context of chat between user & agent`:""}`.trim();var ni={xHigh:"Use minimal reasoning. Prefer simplest path; avoid branching; waste NO tokens overthinking",High:"Use minimal reasoning. Prefer simplest path; avoid branching; waste NO tokens overthinking",Medium:"Use minimal reasoning. Prefer simplest path; avoid branching; waste NO tokens overthinking",Minimal:"Use minimal reasoning. Prefer simplest path; avoid branching; waste NO tokens overthinking",Off:"NO thinking. Immediate response. Verify imports, tool results & system stability"};import ln from"fs";import an from"path";import La from"os";import Sn from"fs";import Wn from"path";import Zs from"fs";import Ui from"path";import{execSync as er}from"child_process";import{fileURLToPath as Ma}from"url";var Ws=`# FluxFlow CLI Startup & Flags Reference
28
+ - Must not ignore any tool calls in given context of chat between user & agent`:""}`.trim();var ni={xHigh:"Use minimal reasoning. Prefer simplest path; avoid branching; waste NO tokens overthinking",High:"Use minimal reasoning. Prefer simplest path; avoid branching; waste NO tokens overthinking",Medium:"Use minimal reasoning. Prefer simplest path; avoid branching; waste NO tokens overthinking",Minimal:"Use minimal reasoning. Prefer simplest path; avoid branching; waste NO tokens overthinking",Off:"NO thinking. Immediate response. Verify imports, tool results & system stability"};import ln from"fs";import an from"path";import $a from"os";import Sn from"fs";import Wn from"path";import Zs from"fs";import Wi from"path";import{execSync as er}from"child_process";import{fileURLToPath as Pa}from"url";var Ws=`# FluxFlow CLI Startup & Flags Reference
29
29
 
30
30
  Launch command syntax:
31
31
  fluxflow [options]
@@ -448,7 +448,7 @@ Instruction for this model ID across all providers.
448
448
 
449
449
  * On-Demand Reference System:
450
450
  * Reference: Offload deep/contexual specs to **/{SKILL.md,skill-reference-folder/*.md} & reference in SKILL.md. Saves tokens
451
- `;var oi="v4";try{let e=Ui.dirname(Ma(import.meta.url)),n=[Ui.join(e,"../../package.json"),Ui.join(e,"../package.json")],t=!1;for(let i of n)if(Zs.existsSync(i)){let o=JSON.parse(Zs.readFileSync(i,"utf8"));if(o.version){oi=o.version,t=!0;break}}if(!t)try{let i=er("fluxflow -v",{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"],timeout:2e3}).trim();i&&(i.startsWith("v")||/^\d+\.\d+/.test(i))&&(oi=i,t=!0)}catch{}if(!t)try{let i=er("curl -s --max-time 3 https://raw.githubusercontent.com/KushalRoyChowdhury/fluxflow-cli/main/package.json",{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"]}),o=JSON.parse(i);o.version&&(oi=o.version)}catch{}}catch{}var Wi={"SKILL.md":`---
451
+ `;var oi="v4";try{let e=Wi.dirname(Pa(import.meta.url)),n=[Wi.join(e,"../../package.json"),Wi.join(e,"../package.json")],t=!1;for(let i of n)if(Zs.existsSync(i)){let o=JSON.parse(Zs.readFileSync(i,"utf8"));if(o.version){oi=o.version,t=!0;break}}if(!t)try{let i=er("fluxflow -v",{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"],timeout:2e3}).trim();i&&(i.startsWith("v")||/^\d+\.\d+/.test(i))&&(oi=i,t=!0)}catch{}if(!t)try{let i=er("curl -s --max-time 3 https://raw.githubusercontent.com/KushalRoyChowdhury/fluxflow-cli/main/package.json",{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"]}),o=JSON.parse(i);o.version&&(oi=o.version)}catch{}}catch{}var Gi={"SKILL.md":`---
452
452
  name: fluxflow
453
453
  description: System Generated Documentation. Read this if asked anything regarding FluxFlow Harness
454
454
  ---
@@ -475,24 +475,24 @@ Public Docs: https://fluxflow-cli.onrender.com
475
475
 
476
476
  Default Context Length: 256k Tokens. Can be changed via ENV/In-app Settings \u2192 references/{SETTINGS,ENV}.md
477
477
 
478
- Docs missing required info? Say you are not sure enough to answer. Dont give wrong info`,"references/MODES.md":Xs,"references/PROVIDERS.md":Js,"references/PLUGINS.md":Qs,"references/STARTUP.md":Ws,"references/ENV.md":Gs,"references/COMMANDS.md":Hs,"references/SETTINGS.md":js,"references/TOOLS.md":Ks,"references/ARCHITECTURE.md":Vs,"references/SUB_AGENTS.md":Ys,"references/SECURITY.md":zs,"references/IDE.md":qs};var tr=()=>{try{let e=Wn.join(Un,"skills","fluxflow"),n=Wn.join(e,"references");if(process.env.NO_DEV==="true"||process.env.NO_DEV==="1"||process.env.NO_DEV===!0||process.env.NO_INS==="true"||process.env.NO_INS==="1"||process.env.NO_INS==="true"||!1){Sn.existsSync(e)&&Sn.rmSync(e,{recursive:!0,force:!0});return}let i=new Set(Object.keys(Wi).map(o=>Wn.normalize(o)));for(let[o,r]of Object.entries(Wi)){let c=Wn.join(e,o),a=Wn.dirname(c);Sn.existsSync(a)||Sn.mkdirSync(a,{recursive:!0});let u=r.trim()+`
479
- `,h=null;Sn.existsSync(c)&&(h=Sn.readFileSync(c,"utf8")),h!==u&&Sn.writeFileSync(c,u,"utf8")}if(Sn.existsSync(n)){let o=Sn.readdirSync(n);for(let r of o){let c=Wn.normalize(Wn.join("references",r));if(!i.has(c)){let a=Wn.join(n,r);try{Sn.rmSync(a,{recursive:!0,force:!0})}catch{}}}}}catch{}};import{WebSocket as ii}from"ws";var Ht=null,fo=!1,Pa="ws://localhost:56832",Gi=[],uo=null,Hi=null,ji=null,nr="2.0.0",dc=e=>{nr=e,or()},Ki=e=>{Hi=e},fc=e=>{ji=e},or=()=>{if(Ht||fo)return;fo=!0;let e=new ii(Pa);e.on("open",()=>{for(Ht=e,fo=!1,Ht.send(JSON.stringify({command:"version",version:nr,pid:process.pid,ppid:process.ppid,cwd:process.cwd()}));Gi.length>0;)Ht.send(JSON.stringify(Gi.shift()))}),e.on("message",n=>{try{let t=JSON.parse(n.toString());t.command==="contextResponse"&&uo?(uo(t.data),uo=null):t.command==="securityResponse"&&Hi?Hi(t.result):t.command==="inlineComplete"?Oa(t):t.command==="connectionRejected"&&ji&&ji(t)}catch{}}),e.on("error",()=>{fo=!1,Ht=null}),e.on("close",()=>{fo=!1,Ht=null})},_o=e=>{Ht&&Ht.readyState===ii.OPEN?Ht.send(JSON.stringify(e)):(Gi.push(e),fo||or())},go=()=>Ht!==null&&Ht.readyState===ii.OPEN,Oa=async e=>{let n="";try{let{generateAutoCompletion:t}=await import("./auto_completion-ZGT6WREW.js");n=await t({prefix:e.prefix||"",suffix:e.suffix||"",fileName:e.fileName||"",language:e.language||"",recentChanges:e.recentChanges||"",clipboard:e.clipboard||""})}catch{n=""}_o({command:"inlineCompleteResponse",requestId:e.requestId,completion:n||""})},uc=e=>{_o({command:"status",status:e})},Jn=()=>new Promise(e=>{if(!Ht||Ht.readyState!==ii.OPEN){e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]});return}uo=e,Ht.send(JSON.stringify({command:"requestContext"})),setTimeout(()=>{uo===e&&(e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]}),uo=null)},1e3)}),ir=e=>{_o({command:"open",filePath:e})},Vi=(e,n,t)=>{_o({command:"showDiff",filePath:e,originalContent:n,modifiedContent:t})},sr=(e,n)=>{_o({command:"closeDiff",filePath:e,result:n})};var $o=(e,n)=>{try{if(!ln.existsSync(e))return null;let t=Array.isArray(n)?n.map(o=>o.toLowerCase()):[n.toLowerCase()],i=ln.readdirSync(e);for(let o of t){let r=i.find(c=>c.toLowerCase()===o);if(r){let c=an.join(e,r);if(ln.statSync(c).isFile())return c}}}catch{}return null},Ji=(e,n)=>{let t=$o(e,n);if(t)try{return ln.readFileSync(t,"utf8")}catch{}return""},rr=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",".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",".skills","skills"]),Qi=(e=process.cwd(),n=0,t=8)=>{let i=[];if(n>t)return i;try{if(!ln.existsSync(e))return i;let o=ln.readdirSync(e,{withFileTypes:!0});for(let r of o){let c=r.name,a=an.join(e,c);if(r.isDirectory())!rr.has(c)&&!rr.has(c.toLowerCase())&&i.push(...Qi(a,n+1,t));else if(r.isFile()){let u=c.toLowerCase();(u==="agents.md"||u==="agent.md")&&i.push(a)}}}catch{}return i},ar=(e,n=2)=>{if(!e)return"";let t=" ".repeat(n);return e.split(/\r?\n/).map(i=>t+i).join(`
480
- `)},ur=()=>$o(Un,["agents.md","agent.md"]),gr=()=>$o(process.cwd(),["agents.md","agent.md"]),mr=()=>$o(Un,["fluxflow.md"]),pr=()=>$o(process.cwd(),["fluxflow.md"]),Io=ur(),si=gr(),kn=Qi(),Mo=mr(),Po=pr(),lr=null,Xi="",hr=!1,$a=e=>{if(!e||!/^<<<[\s\S]*?Identity:/m.test(e))return e;let n=e.match(/^<<<\s*\r?\n([\s\S]*?)\r?\n>>>\s*(?:\r?\n)?([\s\S]*)$/);if(!n)return e;let t=n[1],i=n[2],o=t.match(/^Identity:\s*([\s\S]*?)(?=\r?\n\s*(?:<><|>>>)|$)/m);return o&&(Xi=o[1].trim(),process.env.NO_INS=!0),/<><\s*NO_INS/.test(t)&&(hr=!0),i.trim()},Na=()=>{Io=ur();let e=Io?Ji(Un,["agents.md","agent.md"]).trim():"";return e.length===0?(Io=null,""):e},Da=()=>{if(kn=Qi(),si=gr(),!kn||kn.length===0)return"";let e=process.cwd(),n=[...kn].sort((o,r)=>{let c=an.relative(e,o).replace(/\\/g,"/"),a=an.relative(e,r).replace(/\\/g,"/"),u=!c.includes("/"),h=!a.includes("/");return u&&!h?-1:!u&&h?1:c.localeCompare(a)}),t=[],i=[];for(let o of n)try{let r=ln.readFileSync(o,"utf8").trim();if(!r||r.length===0)continue;t.push(o);let c=an.relative(e,o).replace(/\\/g,"/");if(!c.includes("/"))i.push(ar(r,2));else{let u=an.dirname(c)+"/:";i.push(`${u}
478
+ Docs missing required info? Say you are not sure enough to answer. Dont give wrong info`,"references/MODES.md":Xs,"references/PROVIDERS.md":Js,"references/PLUGINS.md":Qs,"references/STARTUP.md":Ws,"references/ENV.md":Gs,"references/COMMANDS.md":Hs,"references/SETTINGS.md":js,"references/TOOLS.md":Ks,"references/ARCHITECTURE.md":Vs,"references/SUB_AGENTS.md":Ys,"references/SECURITY.md":zs,"references/IDE.md":qs};var tr=()=>{try{let e=Wn.join(Un,"skills","fluxflow"),n=Wn.join(e,"references");if(process.env.NO_DEV==="true"||process.env.NO_DEV==="1"||process.env.NO_DEV===!0||process.env.NO_INS==="true"||process.env.NO_INS==="1"||process.env.NO_INS==="true"||!1){Sn.existsSync(e)&&Sn.rmSync(e,{recursive:!0,force:!0});return}let i=new Set(Object.keys(Gi).map(o=>Wn.normalize(o)));for(let[o,r]of Object.entries(Gi)){let d=Wn.join(e,o),a=Wn.dirname(d);Sn.existsSync(a)||Sn.mkdirSync(a,{recursive:!0});let u=r.trim()+`
479
+ `,h=null;Sn.existsSync(d)&&(h=Sn.readFileSync(d,"utf8")),h!==u&&Sn.writeFileSync(d,u,"utf8")}if(Sn.existsSync(n)){let o=Sn.readdirSync(n);for(let r of o){let d=Wn.normalize(Wn.join("references",r));if(!i.has(d)){let a=Wn.join(n,r);try{Sn.rmSync(a,{recursive:!0,force:!0})}catch{}}}}}catch{}};import{WebSocket as ii}from"ws";var jt=null,fo=!1,Oa="ws://localhost:56832",Hi=[],uo=null,ji=null,Ki=null,nr="2.0.0",fc=e=>{nr=e,or()},Vi=e=>{ji=e},uc=e=>{Ki=e},or=()=>{if(jt||fo)return;fo=!0;let e=new ii(Oa);e.on("open",()=>{for(jt=e,fo=!1,jt.send(JSON.stringify({command:"version",version:nr,pid:process.pid,ppid:process.ppid,cwd:process.cwd()}));Hi.length>0;)jt.send(JSON.stringify(Hi.shift()))}),e.on("message",n=>{try{let t=JSON.parse(n.toString());t.command==="contextResponse"&&uo?(uo(t.data),uo=null):t.command==="securityResponse"&&ji?ji(t.result):t.command==="inlineComplete"?La(t):t.command==="connectionRejected"&&Ki&&Ki(t)}catch{}}),e.on("error",()=>{fo=!1,jt=null}),e.on("close",()=>{fo=!1,jt=null})},_o=e=>{jt&&jt.readyState===ii.OPEN?jt.send(JSON.stringify(e)):(Hi.push(e),fo||or())},go=()=>jt!==null&&jt.readyState===ii.OPEN,La=async e=>{let n="";try{let{generateAutoCompletion:t}=await import("./auto_completion-HIR5DVL5.js");n=await t({prefix:e.prefix||"",suffix:e.suffix||"",fileName:e.fileName||"",language:e.language||"",recentChanges:e.recentChanges||"",clipboard:e.clipboard||""})}catch{n=""}_o({command:"inlineCompleteResponse",requestId:e.requestId,completion:n||""})},gc=e=>{_o({command:"status",status:e})},Qn=()=>new Promise(e=>{if(!jt||jt.readyState!==ii.OPEN){e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]});return}uo=e,jt.send(JSON.stringify({command:"requestContext"})),setTimeout(()=>{uo===e&&(e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]}),uo=null)},1e3)}),ir=e=>{_o({command:"open",filePath:e})},Yi=(e,n,t)=>{_o({command:"showDiff",filePath:e,originalContent:n,modifiedContent:t})},sr=(e,n)=>{_o({command:"closeDiff",filePath:e,result:n})};var $o=(e,n)=>{try{if(!ln.existsSync(e))return null;let t=Array.isArray(n)?n.map(o=>o.toLowerCase()):[n.toLowerCase()],i=ln.readdirSync(e);for(let o of t){let r=i.find(d=>d.toLowerCase()===o);if(r){let d=an.join(e,r);if(ln.statSync(d).isFile())return d}}}catch{}return null},Qi=(e,n)=>{let t=$o(e,n);if(t)try{return ln.readFileSync(t,"utf8")}catch{}return""},rr=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",".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",".skills","skills"]),Zi=(e=process.cwd(),n=0,t=8)=>{let i=[];if(n>t)return i;try{if(!ln.existsSync(e))return i;let o=ln.readdirSync(e,{withFileTypes:!0});for(let r of o){let d=r.name,a=an.join(e,d);if(r.isDirectory())!rr.has(d)&&!rr.has(d.toLowerCase())&&i.push(...Zi(a,n+1,t));else if(r.isFile()){let u=d.toLowerCase();(u==="agents.md"||u==="agent.md")&&i.push(a)}}}catch{}return i},ar=(e,n=2)=>{if(!e)return"";let t=" ".repeat(n);return e.split(/\r?\n/).map(i=>t+i).join(`
480
+ `)},ur=()=>$o(Un,["agents.md","agent.md"]),gr=()=>$o(process.cwd(),["agents.md","agent.md"]),mr=()=>$o(Un,["fluxflow.md"]),pr=()=>$o(process.cwd(),["fluxflow.md"]),Io=ur(),si=gr(),kn=Zi(),Mo=mr(),Po=pr(),lr=null,Ji="",hr=!1,Na=e=>{if(!e||!/^<<<[\s\S]*?Identity:/m.test(e))return e;let n=e.match(/^<<<\s*\r?\n([\s\S]*?)\r?\n>>>\s*(?:\r?\n)?([\s\S]*)$/);if(!n)return e;let t=n[1],i=n[2],o=t.match(/^Identity:\s*([\s\S]*?)(?=\r?\n\s*(?:<><|>>>)|$)/m);return o&&(Ji=o[1].trim(),process.env.NO_INS=!0),/<><\s*NO_INS/.test(t)&&(hr=!0),i.trim()},Da=()=>{Io=ur();let e=Io?Qi(Un,["agents.md","agent.md"]).trim():"";return e.length===0?(Io=null,""):e},Fa=()=>{if(kn=Zi(),si=gr(),!kn||kn.length===0)return"";let e=process.cwd(),n=[...kn].sort((o,r)=>{let d=an.relative(e,o).replace(/\\/g,"/"),a=an.relative(e,r).replace(/\\/g,"/"),u=!d.includes("/"),h=!a.includes("/");return u&&!h?-1:!u&&h?1:d.localeCompare(a)}),t=[],i=[];for(let o of n)try{let r=ln.readFileSync(o,"utf8").trim();if(!r||r.length===0)continue;t.push(o);let d=an.relative(e,o).replace(/\\/g,"/");if(!d.includes("/"))i.push(ar(r,2));else{let u=an.dirname(d)+"/:";i.push(`${u}
481
481
  ${ar(r,2)}`)}}catch{}return kn=t,kn.length===0&&(si=null),i.join(`
482
482
 
483
- `).trim()},Zi=()=>{Mo=mr();let e=Mo?Ji(Un,["fluxflow.md"]).trim():"",n=$a(e)?.trim()||"";return n.length===0?(Mo=null,""):n},es=()=>{Po=pr();let e=Po?Ji(process.cwd(),["fluxflow.md"]).trim():"";return e.length===0?(Po=null,""):e},ts=Na(),ri=Da(),Oo=Zi(),Lo=es(),cr=(e,n="",t="")=>{if(!e)return"";let i=t.toLowerCase().trim(),o=n.toLowerCase().trim(),r=an.posix.basename(o),c=i&&o?`${i}@${o}`:"",a=i&&r?`${i}@${r}`:"",u=x=>!x||!o?!1:x===o||x===r||x===c||x===a,h=[];return e.replace(/<start_provider_([^>\r\n]+)>([\s\S]*?)<end_provider_([^>\r\n]+)>/gi,(x,p,f,s)=>{if(i&&p.trim().toLowerCase()===s.trim().toLowerCase()&&p.trim().toLowerCase()===i){let k=f.replace(/<start_model_([^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n]+)>/gi,(he,y,E,D)=>{if(y.trim().toLowerCase()===D.trim().toLowerCase()){let K=y.trim().toLowerCase();if(u(K)){let O=E.trim();O&&h.push(O)}}return""}).trim();k&&h.push(k)}return""}),e.replace(/<start_model_([^>\r\n@]+@[^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n@]+@[^>\r\n]+)>/gi,(x,p,f,s)=>{if(p.trim().toLowerCase()===s.trim().toLowerCase()){let g=p.trim().toLowerCase();if(u(g)){let k=f.trim();k&&h.push(k)}}return""}),e.replace(/<start_model_([^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n]+)>/gi,(x,p,f,s)=>{if(p.includes("@"))return"";if(p.trim().toLowerCase()===s.trim().toLowerCase()){let g=p.trim().toLowerCase();if(o&&(g===o||g===r)){let k=f.trim();k&&h.push(k)}}return""}),h.join(`
483
+ `).trim()},es=()=>{Mo=mr();let e=Mo?Qi(Un,["fluxflow.md"]).trim():"",n=Na(e)?.trim()||"";return n.length===0?(Mo=null,""):n},ts=()=>{Po=pr();let e=Po?Qi(process.cwd(),["fluxflow.md"]).trim():"";return e.length===0?(Po=null,""):e},ns=Da(),ri=Fa(),Oo=es(),Lo=ts(),cr=(e,n="",t="")=>{if(!e)return"";let i=t.toLowerCase().trim(),o=n.toLowerCase().trim(),r=an.posix.basename(o),d=i&&o?`${i}@${o}`:"",a=i&&r?`${i}@${r}`:"",u=x=>!x||!o?!1:x===o||x===r||x===d||x===a,h=[];return e.replace(/<start_provider_([^>\r\n]+)>([\s\S]*?)<end_provider_([^>\r\n]+)>/gi,(x,p,f,s)=>{if(i&&p.trim().toLowerCase()===s.trim().toLowerCase()&&p.trim().toLowerCase()===i){let k=f.replace(/<start_model_([^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n]+)>/gi,(he,y,E,D)=>{if(y.trim().toLowerCase()===D.trim().toLowerCase()){let K=y.trim().toLowerCase();if(u(K)){let L=E.trim();L&&h.push(L)}}return""}).trim();k&&h.push(k)}return""}),e.replace(/<start_model_([^>\r\n@]+@[^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n@]+@[^>\r\n]+)>/gi,(x,p,f,s)=>{if(p.trim().toLowerCase()===s.trim().toLowerCase()){let g=p.trim().toLowerCase();if(u(g)){let k=f.trim();k&&h.push(k)}}return""}),e.replace(/<start_model_([^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n]+)>/gi,(x,p,f,s)=>{if(p.includes("@"))return"";if(p.trim().toLowerCase()===s.trim().toLowerCase()){let g=p.trim().toLowerCase();if(o&&(g===o||g===r)){let k=f.trim();k&&h.push(k)}}return""}),h.join(`
484
484
 
485
- `).trim()},Fa=(e="",n="")=>{let t=`${e||""}@${n||""}`.toLowerCase().trim();lr!==t&&(lr=t,Oo=Zi(),Lo=es())};tr();var Ba=e=>{if(!e)return null;let n=e.match(/^\s*---\r?\n([\s\S]*?)\r?\n---(?:\r?\n)?([\s\S]*)$/);if(!n)return null;let t=n[1];if((n[2]||"").trim().length===0)return null;let o="",r="",c=t.match(/^name:\s*(.+)$/m),a=t.match(/^description:\s*(.+)$/m);return c&&(o=c[1].trim().replace(/^["']|["']$/g,"")),a&&(r=a[1].trim().replace(/^["']|["']$/g,"")),o&&r?{name:o,description:r}:null},Ua=e=>{let n=[];if(!e||!ln.existsSync(e))return n;let t=(i,o=0)=>{if(!(o>5))try{let r=ln.readdirSync(i,{withFileTypes:!0});for(let c of r){let a=an.join(i,c.name),u=c.name.toLowerCase();c.isFile()?u==="skill.md"&&n.push(a):c.isDirectory()&&(o===0?(u==="skills"||u===".skills"||u==="skill"||u===".skill")&&t(a,o+1):t(a,o+1))}}catch{}};return t(e,0),n},yr=e=>{let n=Ua(e),t=[];for(let i of n)try{let o=ln.readFileSync(i,"utf8"),r=Ba(o);r&&t.push({...r,filePath:i})}catch{}return t},xr=e=>!e||e.length===0?"":e.map(n=>`- ${n.name}: ${n.description}`).join(`
486
- `),br=yr(Un),wr=yr(process.cwd()),Yi=xr(br),zi=xr(wr),Sr=e=>{if(!e)return!1;let n=(e.filePath||"").replace(/\\/g,"/").toLowerCase();return n.includes("/skills/fluxflow/skill.md")||n.includes("/skills/about-fluxflow/skill.md")||e.name?.toLowerCase()==="fluxflow"},kr=()=>(br||[]).filter(e=>!Sr(e)),Tr=()=>(wr||[]).filter(e=>!Sr(e)),Rc=(ts?.length>0?1:0)+(ri?.length>0?kn.length:0)+(Oo?.length>0?1:0)+(Lo?.length>0?1:0)+kr().length+Tr().length,qi=(e,n="Project")=>{if(!e)return"";let t=e.replace(/\\/g,"/");if(n==="Global"){let o=La.homedir().replace(/\\/g,"/");return t.toLowerCase().startsWith(o.toLowerCase())?"~"+t.slice(o.length):t}let i=an.relative(process.cwd(),e).replace(/\\/g,"/");return i.startsWith(".")?i:`./${i}`},_c=()=>{Oo=Zi(),Lo=es();let e=[];Io&&ts.length>0&&e.push({scope:"Global",path:Io}),kn&&kn.length>0&&ri.length>0?kn.forEach(r=>{e.push({scope:"Project",path:r})}):si&&ri.length>0&&e.push({scope:"Project",path:si}),Mo&&Oo.length>0&&e.push({scope:"Global",path:Mo}),Po&&Lo.length>0&&e.push({scope:"Project",path:Po});let n=kr(),t=Tr(),i=e.length+n.length+t.length;if(i===0)return`\u2726 Loaded Files & Instructions
485
+ `).trim()},Ba=(e="",n="")=>{let t=`${e||""}@${n||""}`.toLowerCase().trim();lr!==t&&(lr=t,Oo=es(),Lo=ts())};tr();var Ua=e=>{if(!e)return null;let n=e.match(/^\s*---\r?\n([\s\S]*?)\r?\n---(?:\r?\n)?([\s\S]*)$/);if(!n)return null;let t=n[1];if((n[2]||"").trim().length===0)return null;let o="",r="",d=t.match(/^name:\s*(.+)$/m),a=t.match(/^description:\s*(.+)$/m);return d&&(o=d[1].trim().replace(/^["']|["']$/g,"")),a&&(r=a[1].trim().replace(/^["']|["']$/g,"")),o&&r?{name:o,description:r}:null},Wa=e=>{let n=[];if(!e||!ln.existsSync(e))return n;let t=(i,o=0)=>{if(!(o>5))try{let r=ln.readdirSync(i,{withFileTypes:!0});for(let d of r){let a=an.join(i,d.name),u=d.name.toLowerCase();d.isFile()?u==="skill.md"&&n.push(a):d.isDirectory()&&(o===0?(u==="skills"||u===".skills"||u==="skill"||u===".skill")&&t(a,o+1):t(a,o+1))}}catch{}};return t(e,0),n},yr=e=>{let n=Wa(e),t=[];for(let i of n)try{let o=ln.readFileSync(i,"utf8"),r=Ua(o);r&&t.push({...r,filePath:i})}catch{}return t},xr=e=>!e||e.length===0?"":e.map(n=>`- ${n.name}: ${n.description}`).join(`
486
+ `),br=yr(Un),wr=yr(process.cwd()),zi=xr(br),qi=xr(wr),Sr=e=>{if(!e)return!1;let n=(e.filePath||"").replace(/\\/g,"/").toLowerCase();return n.includes("/skills/fluxflow/skill.md")||n.includes("/skills/about-fluxflow/skill.md")||e.name?.toLowerCase()==="fluxflow"},kr=()=>(br||[]).filter(e=>!Sr(e)),Tr=()=>(wr||[]).filter(e=>!Sr(e)),_c=(ns?.length>0?1:0)+(ri?.length>0?kn.length:0)+(Oo?.length>0?1:0)+(Lo?.length>0?1:0)+kr().length+Tr().length,Xi=(e,n="Project")=>{if(!e)return"";let t=e.replace(/\\/g,"/");if(n==="Global"){let o=$a.homedir().replace(/\\/g,"/");return t.toLowerCase().startsWith(o.toLowerCase())?"~"+t.slice(o.length):t}let i=an.relative(process.cwd(),e).replace(/\\/g,"/");return i.startsWith(".")?i:`./${i}`},vc=()=>{Oo=es(),Lo=ts();let e=[];Io&&ns.length>0&&e.push({scope:"Global",path:Io}),kn&&kn.length>0&&ri.length>0?kn.forEach(r=>{e.push({scope:"Project",path:r})}):si&&ri.length>0&&e.push({scope:"Project",path:si}),Mo&&Oo.length>0&&e.push({scope:"Global",path:Mo}),Po&&Lo.length>0&&e.push({scope:"Project",path:Po});let n=kr(),t=Tr(),i=e.length+n.length+t.length;if(i===0)return`\u2726 Loaded Files & Instructions
487
487
  \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m No instruction or skill files are currently loaded.
488
488
  \u2800`;let o=[];return o.push(`\u2726 Loaded Files & Instructions (${i} ${i===1?"file":"files"} active)`),e.length>0&&(o.push(`
489
- \x1B[1mInstructions:\x1B[22m`),e.forEach(r=>{o.push(` \u2022 [${r.scope}] ${qi(r.path,r.scope)}`)})),(n?.length>0||t?.length>0)&&(o.push(`
490
- \x1B[1mSkills:\x1B[22m`),n?.length>0&&n.forEach(r=>{o.push(` \u2022 [Global] \x1B[36m${r.name}\x1B[39m`),o.push(` \x1B[2m\u2514\u2500 ${qi(r.filePath,"Global")}\x1B[22m`)}),t?.length>0&&t.forEach(r=>{o.push(` \u2022 [Project] \x1B[36m${r.name}\x1B[39m`),o.push(` \x1B[2m\u2514\u2500 ${qi(r.filePath,"Project")}\x1B[22m`)})),o.push("\u2800"),o.join(`
491
- `)},Ar=!1;(async()=>{try{let e=await Eo();if(Number(e?.display)===1){let{default:n}=await import("screenshot-desktop"),t=await n.listDisplays();t&&t.length>1&&(Ar=!0)}}catch{}})();var dr=null,vo=null,fr=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",vc=process.env.NO_DEV||!1,Wa=(e,n)=>{if(!n)return"";if(e!==dr||vo===null){dr=e;try{let t=Ot(Xn,[]);Array.isArray(t)&&t.length>0?vo=t.map(i=>`- ${i.memory}`).join(`
489
+ \x1B[1mInstructions:\x1B[22m`),e.forEach(r=>{o.push(` \u2022 [${r.scope}] ${Xi(r.path,r.scope)}`)})),(n?.length>0||t?.length>0)&&(o.push(`
490
+ \x1B[1mSkills:\x1B[22m`),n?.length>0&&n.forEach(r=>{o.push(` \u2022 [Global] \x1B[36m${r.name}\x1B[39m`),o.push(` \x1B[2m\u2514\u2500 ${Xi(r.filePath,"Global")}\x1B[22m`)}),t?.length>0&&t.forEach(r=>{o.push(` \u2022 [Project] \x1B[36m${r.name}\x1B[39m`),o.push(` \x1B[2m\u2514\u2500 ${Xi(r.filePath,"Project")}\x1B[22m`)})),o.push("\u2800"),o.join(`
491
+ `)},Ar=!1;(async()=>{try{let e=await Eo();if(Number(e?.display)===1){let{default:n}=await import("screenshot-desktop"),t=await n.listDisplays();t&&t.length>1&&(Ar=!0)}}catch{}})();var dr=null,vo=null,fr=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",Ic=process.env.NO_DEV||!1,Ga=(e,n)=>{if(!n)return"";if(e!==dr||vo===null){dr=e;try{let t=Ot(Jn,[]);Array.isArray(t)&&t.length>0?vo=t.map(i=>`- ${i.memory}`).join(`
492
492
  `):vo=""}catch(t){vo="";try{ln.mkdirSync(an.join(wn,"memory"),{recursive:!0}),ln.appendFileSync(an.join(wn,"memory","error.txt"),`${t.message}
493
493
  -------------------------------------------------
494
494
 
495
- `)}catch{}}}return vo};var Er=(e,n,t,i,o=!0,r=!1,c="Google",a=!1,u,h,x=!1,p="")=>{let f=!1;process.env.forcedReasoning&&(f=!0);let s="";if(!u&&c==="Google"){let Y=n;n==="Fast"&&(Y="Off"),n==="Low"&&(Y="Minimal"),n==="Standard"&&(Y="Medium"),(n==="xHigh"||n==="Max")&&(Y="xHigh"),s=ni[Y]||ni.Medium}(u||c!=="Google")&&(s=ni.xHigh,n==="Fast"?s=`No thinking. Immediate response
495
+ `)}catch{}}}return vo};var Er=(e,n,t,i,o=!0,r=!1,d="Google",a=!1,u,h,x=!1,p="")=>{let f=!1;process.env.forcedReasoning&&(f=!0);let s="";if(!u&&d==="Google"){let V=n;n==="Fast"&&(V="Off"),n==="Low"&&(V="Minimal"),n==="Standard"&&(V="Medium"),(n==="xHigh"||n==="Max")&&(V="xHigh"),s=ni[V]||ni.Medium}(u||d!=="Google")&&(s=ni.xHigh,n==="Fast"?s=`No thinking. Immediate response
496
496
  Verify imports, tool results & system stability`:n.toLowerCase()==="max"&&(s=`Effort: Max
497
497
  Plan step by step`));let g=e.instructions&&e.instructions?.length>0?`User Preferences: ${e.instructions}
498
498
 
@@ -500,12 +500,12 @@ Plan step by step`));let g=e.instructions&&e.instructions?.length>0?`User Prefer
500
500
  ${g.length?"":`
501
501
  `}`:"",he=e.name&&e.name?.length>0?`User Name: ${e.name}
502
502
  ${k.length||g.length?"":`
503
- `}`:"",y=process.cwd(),E=e.preset,K={Sassy:"Sassy",Friendly:"Sassy, Warm & Chatty",Playful:"Playful",Efficient:"Quick, Concise & Efficient",Professional:"Professional"}[E]||null,O=Wa(h,o),T=O?.length>0?`--- Saved Memories ---
504
- ${O}
503
+ `}`:"",y=process.cwd(),E=e.preset,K={Sassy:"Sassy",Friendly:"Sassy, Warm & Chatty",Playful:"Playful",Efficient:"Quick, Concise & Efficient",Professional:"Professional"}[E]||null,L=Ga(h,o),T=L?.length>0?`--- Saved Memories ---
504
+ ${L}
505
505
 
506
- `:"";Fa(c,p);let Se=cr(Oo,p,c).trim(),Me=[ts,Se].filter(Y=>Y&&Y.length>0).join(`
506
+ `:"";Ba(d,p);let Se=cr(Oo,p,d).trim(),Me=[ns,Se].filter(V=>V&&V.length>0).join(`
507
507
 
508
- `).trim(),Je=cr(Lo,p,c).trim(),b=[ri,Je].filter(Y=>Y&&Y.length>0).join(`
508
+ `).trim(),Je=cr(Lo,p,d).trim(),b=[ri,Je].filter(V=>V&&V.length>0).join(`
509
509
 
510
510
  `).trim(),ht=Me.length>0||b.length>0?`--- Additional Instructions ---
511
511
  ${Me.length>0?`-- Global --
@@ -514,8 +514,8 @@ ${Me}`:""}${b.length>0?`${Me.length>0?`
514
514
  `:""}-- Project --
515
515
  ${b}`:""}
516
516
 
517
- `:"",fe=(()=>{let Y=process.cwd().toLowerCase();if(process.platform==="win32"){let H=process.env.SystemRoot?.toLowerCase()||"c:\\windows",_=process.env.ProgramFiles?.toLowerCase()||"c:\\program files",Qe=process.env["ProgramFiles(x86)"]?.toLowerCase()||"c:\\program files (x86)";return Y.startsWith(H)||Y.startsWith(_)||Y.startsWith(Qe)}else return Y==="/"||["/bin","/sbin","/etc","/usr","/var","/root"].some(_=>Y.startsWith(_))})(),q=new Date,tn=q.getFullYear(),Vt=q.toLocaleString("en-US",{month:"short"}).toUpperCase(),cn=String(q.getDate()).padStart(2,"0"),po=`${tn}-${Vt}-${cn}`,Pn=process.env.I_HAVE_TOO_MUCH_MONEY==="true"||!1,dn=process.env.HALLOWEEN_EEGG==="true"||!1,yt=dn&&Vt.includes("OCT")&&(cn.includes("30")||cn.includes("31")),Yt=(p||"").replace(/^.*::/,"").split(":")[0].replace(/\/free$/,"").trim(),ue=an.basename(Yt).replace(/-free$/,"").replace(/_free$/,"").replace(/^free_/,"").replaceAll("-"," ").replaceAll("_"," ").replace(/\b\w/g,Y=>Y.toUpperCase().trim()),Be=process.env.NO_DEV==="true"||!1,Pe=!1;try{Pe=go()}catch{Pe=!1}return`${Pn?`${" ".repeat(Math.floor(Math.random()*4)+1)}`:""}=== SYSTEM PROMPT ===
518
- ${`Identity: ${Xi.length>1?Xi.trim():`Flux Flow.${K?` ${K}`:""} CLI Assistant${dn?`. ${yt?"Peak ":""}Halloween Themed, Spooky`:""}`}
517
+ `:"",fe=(()=>{let V=process.cwd().toLowerCase();if(process.platform==="win32"){let G=process.env.SystemRoot?.toLowerCase()||"c:\\windows",_=process.env.ProgramFiles?.toLowerCase()||"c:\\program files",Qe=process.env["ProgramFiles(x86)"]?.toLowerCase()||"c:\\program files (x86)";return V.startsWith(G)||V.startsWith(_)||V.startsWith(Qe)}else return V==="/"||["/bin","/sbin","/etc","/usr","/var","/root"].some(_=>V.startsWith(_))})(),z=new Date,tn=z.getFullYear(),Vt=z.toLocaleString("en-US",{month:"short"}).toUpperCase(),cn=String(z.getDate()).padStart(2,"0"),po=`${tn}-${Vt}-${cn}`,Pn=process.env.I_HAVE_TOO_MUCH_MONEY==="true"||!1,dn=process.env.HALLOWEEN_EEGG==="true"||!1,yt=dn&&Vt.includes("OCT")&&(cn.includes("30")||cn.includes("31")),Yt=(p||"").replace(/^.*::/,"").split(":")[0].replace(/\/free$/,"").trim(),ue=an.basename(Yt).replace(/-free$/,"").replace(/_free$/,"").replace(/^free_/,"").replaceAll("-"," ").replaceAll("_"," ").replace(/\b\w/g,V=>V.toUpperCase().trim()),Be=process.env.NO_DEV==="true"||!1,Pe=!1;try{Pe=go()}catch{Pe=!1}return`${Pn?`${" ".repeat(Math.floor(Math.random()*4)+1)}`:""}=== SYSTEM PROMPT ===
518
+ ${`Identity: ${Ji.length>1?Ji.trim():`Flux Flow.${K?` ${K}`:""} CLI Assistant${dn?`. ${yt?"Peak ":""}Halloween Themed, Spooky`:""}`}
519
519
  ${hr?"":`${t==="Flux"?"":t==="Flow"?"Concise, Humorous, Sarcastic":t==="ICU"?"Computer Use Capabilities. Screenshot as ground truth, analyze grid ids of target. Keyboard shortcuts > mouse clicks":"Computer Use & Workspace Capabilities. Screenshot as ground truth, analyze grid ids of target. Keyboard shortcuts > mouse clicks. Workspace Actions when faster. Focus on Productivity"}`}${Ar&&t.toLowerCase().includes("cu")?`
520
520
  - Running on secondary screen. Opened app not visible in screenshot? Might be opened on primary. Use 'AskUser' with NO options and tell user to move app window to secondary`:""}`.trimEnd()}
521
521
 
@@ -524,27 +524,27 @@ ${hr?"":`${t==="Flux"?"":t==="Flow"?"Concise, Humorous, Sarcastic":t==="ICU"?"Co
524
524
  - Date: ${po}
525
525
 
526
526
  -- REASONING GUIDANCE --
527
- ${c==="Mistral"||c==="Google"&&!u||f?`${s.trimEnd()}${f||n!=="Fast"&&(c==="Mistral"&&n==="Low"&&!u||n!=="High"&&!u)?`
527
+ ${d==="Mistral"||d==="Google"&&!u||f?`${s.trimEnd()}${f||n!=="Fast"&&(d==="Mistral"&&n==="Low"&&!u||n!=="High"&&!u)?`
528
528
  Critical Thinking Policy
529
529
  Use <think_fluxflow>...</think_fluxflow> for reasoning before responding any queries`:""}`:`${s.trimEnd()}`}${x?"":`
530
530
  Before actions, provide user facing summary of findings & decisions IN detail
531
531
  `}
532
- ${Ns(t,fr,a,c,i?.advanceRollback,i?.subAgents!==!1,!!i?.autoExec,!!i?.disableTodo,i?.preferBash!==!1)}${t==="Flux"?"":t.toLowerCase().includes("cu")?`
532
+ ${Ns(t,fr,a,d,i?.advanceRollback,i?.subAgents!==!1,!!i?.autoExec,!!i?.disableTodo,i?.preferBash!==!1)}${t==="Flux"?"":t.toLowerCase().includes("cu")?`
533
533
 
534
534
  -- SECURITY POLICIES --
535
535
  - Dont operate on ANY confidential screens/captcha \u2192 AskUser`:""}${Pe?`
536
536
 
537
537
  Reference files as ./file:start..end`:""}
538
- === END SYSTEM PROMPT ===${(Yi.length>0||zi.length>0)&&t.toLowerCase().includes("flux")?`
538
+ === END SYSTEM PROMPT ===${(zi.length>0||qi.length>0)&&t.toLowerCase().includes("flux")?`
539
539
 
540
540
  - Read relevant skills before tasks, scope: global/project: Use ReadFile, path="#skills/scope?/skillName". In-skill references: path="#skills/scope?/skillName/reference-folder/*.md"`:""}
541
541
 
542
- ${k}${g}${ht}${Yi.length>0&&t.toLowerCase().includes("flux")?`-- Global Skills --
543
- ${Yi}
544
-
545
- `:""}${zi.length>0&&t.toLowerCase().includes("flux")?`-- Project Skills --
542
+ ${k}${g}${ht}${zi.length>0&&t.toLowerCase().includes("flux")?`-- Global Skills --
546
543
  ${zi}
547
544
 
545
+ `:""}${qi.length>0&&t.toLowerCase().includes("flux")?`-- Project Skills --
546
+ ${qi}
547
+
548
548
  `:""}${T}`.trim()},Cr=(e="",n=!0,t=!0)=>`=== SYSTEM PROMPT (strict headless logic worker: zero user-facing text policy, strictly follow) ===
549
549
  identity: silent background system process, have no mouth, only output is valid tool calls
550
550
  [critical rules]
@@ -566,50 +566,49 @@ ${Us(n,t)}
566
566
  === END SYSTEM PROMPT ===${e?`
567
567
 
568
568
  -- current saved user memories --
569
- ${e}`:""}`.trim();var Rr=()=>import("./web_search-KBGH67IV.js").then(e=>e.web_search),_r=()=>import("./web_scrape-J3PL2PXT.js").then(e=>e.web_scrape),vr=()=>import("./memory-7YOYCOXE.js").then(e=>e.memory),Ir=()=>import("./chat-BA72I6O3.js").then(e=>e.chat),Mr=()=>import("./view_file-I77KYUO5.js").then(e=>e.view_file),Pr=()=>import("./write_file-XHSRFBMF.js").then(e=>e.write_file),Or=()=>import("./update_file-ALQM76Y4.js").then(e=>e.update_file),Lr=()=>import("./exec_command-BDFXJQZJ.js").then(e=>e.exec_command),$r=()=>import("./read_folder-EI2CNHNS.js").then(e=>e.read_folder),ns=()=>import("./ask_user-K2DLZF6H.js").then(e=>e.ask_user),Nr=()=>import("./write_pdf-TPGUF4VT.js").then(e=>e.write_pdf),Dr=()=>import("./write_docx-E3MTFXTQ.js").then(e=>e.write_docx),ai=()=>import("./search_keyword-GT5GEEJW.js").then(e=>e.search_keyword),Fr=()=>import("./generate_image-ALAAHL2E.js").then(e=>e.generate_image),li=()=>import("./saveSummary-W2JMDVZJ.js").then(e=>e.saveSummary),No=()=>import("./addMemScore-PBVNSFPN.js").then(e=>e.addMemScore),Br=()=>import("./file_map-UA4BA5OH.js").then(e=>e.file_map),ci=()=>import("./todo-CJLWLWJB.js").then(e=>e.todo),Ur=()=>import("./invokeSync-GQPUH52H.js").then(e=>e.invokeSync),Ga=()=>import("./invoke-DCX72AHI.js").then(e=>e.invoke),Wr=()=>import("./getProgress-J34K43Y7.js").then(e=>e.getProgress),Ha=()=>import("./cancel-F3ZOEBKW.js").then(e=>e.cancel),Gr=()=>import("./emergency_rollback-ZHQXCIHW.js").then(e=>e.emergency_rollback),Do=()=>import("./awaitSubagent-JKQ2EHVY.js").then(e=>e.awaitSubagent),Fo=()=>import("./answerSubagent-BPNNJXPC.js").then(e=>e.answerSubagent),di=()=>import("./steerSubagent-UETXH2CB.js").then(e=>e.steerSubagent),fi=()=>import("./computer_action-5SW7LW5R.js").then(e=>e.computer_action),Hr=()=>import("./click-ZZBBIP7F.js").then(e=>e.click),jr=()=>import("./drag-OBMCSGER.js").then(e=>e.drag),Kr=()=>import("./scroll-LTWDNSC6.js").then(e=>e.scroll),os=()=>import("./keyboard_typing-GCMJCV7O.js").then(e=>e.keyboard_typing),is=()=>import("./key_press-65GEUW4K.js").then(e=>e.key_press),ss=()=>import("./recapture_screen-QB65V5CM.js").then(e=>e.recapture_screen),ui=()=>import("./find_file-HYHHFHUJ.js").then(e=>e.find_file),Vr=()=>import("./wait-TJR6LAR4.js").then(e=>e.wait),Yr={web_search:Rr,web_scrape:_r,memory:vr,chat:Ir,view_file:Mr,write_file:Pr,update_file:Or,exec_command:Lr,read_folder:$r,write_pdf:Nr,write_docx:Dr,search_keyword:ai,generate_image:Fr,saveSummary:li,addMemScore:No,file_map:Br,todo:ci,Todo:ci,goal:ci,Goal:ci,invokeSync:Ur,invoke:Ga,getProgress:Wr,cancel:Ha,awaitSubagent:Do,answerSubagent:Fo,steerSubagent:di,computer_action:fi,computer_use:fi,ComputerAction:fi,ComputerUse:fi,click:Hr,Click:Hr,drag:jr,Drag:jr,scroll:Kr,Scroll:Kr,keyboard_typing:os,KeyboardTyping:os,keyboardtyping:os,key_press:is,KeyPress:is,keypress:is,recapture_screen:ss,RecaptureScreen:ss,recapturescreen:ss,invoke_sync:Ur,get_progress:Wr,await_subagent:Do,answer_subagent:Fo,steer_subagent:di,steer:di,Steer:di,ask:ns,Ask:ns,AskUser:ns,WebSearch:Rr,WebScrape:_r,ReadFile:Mr,ReadFolder:$r,WriteFile:Pr,PatchFile:Or,WritePDF:Nr,WriteDoc:Dr,Run:Lr,SearchKeyword:ai,CodeSearch:ai,code_search:ai,Memory:vr,Chat:Ir,GenerateImage:Fr,saveSumary:li,SaveSummary:li,SaveSumary:li,add_mem_score:No,AddMemScore:No,addMemoryScore:No,AddMemoryScore:No,FileMap:Br,answer:Fo,Answer:Fo,AnswerSubagent:Fo,await:Do,Await:Do,AwaitSubagent:Do,EmergencyRollback:Gr,emergency_rollback:Gr,find_file:ui,findFile:ui,FindFile:ui,findfile:ui,wait:Vr,Wait:Vr},Bo=async(e,n,t={})=>{let i=t.mode?t.mode.toLowerCase():"flux",o=e.toLowerCase(),c=["memory","chat","savesummary","addmemscore","add_mem_score","ask","web_search","web_scrape","await","wait"].some(x=>o.includes(x))||o==="ask",u=["click","drag","scroll","keyboardtyping","keyboard_typing","keypress","key_press","recapturescreen","recapture_screen","computer","wait"].some(x=>o.includes(x));if(!c){if(i==="flow"){if(!(o.includes("write_pdf")||o.includes("write_docx")||o.includes("generate_image")))return`ERROR: Action [${e}] is a Workspace Tool and NOT available in Flow mode. Tell user to switch (\`/mode flux\`) to use this tool.`}else if(i==="icu"){if(!u)return`ERROR: Action [${e}] is not available in Computer Use mode. ICU mode only supports Computer Use tools (Click, Drag, Scroll, KeyboardTyping, KeyPress, RecaptureScreen).`}else if(o.includes("write_pdf")||o.includes("write_docx")||o.includes("generate_image"))return`ERROR: Action [${e}] is not available in ${t.mode||"Flux"} mode. Tell user to switch (\`/mode flow\`) for document generation.`}let h=Yr[e];if(!h){let x=["ReadFile","ReadFolder","FindFile","PatchFile","WriteFile","CodeSearch","Run","Goal","AskUser","WebSearch","WebScrape","WritePDF","WriteDoc","Click","Drag","Scroll","KeyboardTyping","KeyPress","RecaptureScreen","Wait","Invoke","InvokeSync","Await","GetProgress","Steer","Cancel","EmergencyRollback","Chat","Memory"],p={read:"ReadFile",view:"ReadFile",viewfile:"ReadFile",write:"WriteFile",edit:"PatchFile",patch:"PatchFile",update:"PatchFile",updatefile:"PatchFile",exec:"Run",command:"Run",bash:"Run",shell:"Run",powershell:"Run",search:"CodeSearch",grep:"CodeSearch",find:"FindFile",findfile:"FindFile",searchkeyword:"CodeSearch",folder:"ReadFolder",ls:"ReadFolder",dir:"ReadFolder",list:"ReadFolder",ask:"AskUser",question:"AskUser",pdf:"WritePDF",docx:"WriteDoc",doc:"WriteDoc",word:"WriteDoc",screenshot:"RecaptureScreen",screen:"RecaptureScreen",recapture:"RecaptureScreen",type:"KeyboardTyping",typing:"KeyboardTyping",keyboard:"KeyboardTyping",press:"KeyPress",key:"KeyPress",todo:"Goal",task:"Goal",subagent:"Invoke",agent:"Invoke"},f=o.replace(/[^a-z0-9]/g,""),s=p[f]||null;if(!s){let k=0,he=E=>{let D=new Set;for(let K=0;K<E.length-1;K++)D.add(E.slice(K,K+2));return D},y=he(f);for(let E of x){let D=E.toLowerCase().replace(/[^a-z0-9]/g,"");if(f===D){s=E;break}let K=0;(D.includes(f)||f.includes(D))&&(K+=.6);let O=he(D),T=0;for(let Ce of y)O.has(Ce)&&T++;let Se=2*T/(y.size+O.size||1);K=Math.max(K,Se),K>k&&K>=.35&&(k=K,s=E)}}let g=s?` Do you mean '${s}'?`:"";return`ERROR: Action [${e}] not found in registry.${g}`}try{return await(await h())(n,t)}catch(x){let p=x instanceof Error?x.message:String(x);return`ERROR: Execution failed for [${e}]: ${p}`}};var gi=e=>{if(!e||typeof e!="string")return!1;let n=e.trim().toLowerCase();return Object.keys(Yr).some(t=>t.toLowerCase()===n)};import W from"path";import Ae from"fs";import{execSync as fs}from"child_process";import ja 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 qr=["Beware the phantom processes.","A ghost in the shell has taken the wheel.","Blowing on the haunted cartridge...","Seven minutes in Raccoon City.","Wind's howling... in the terminal fans.","Slender Man was spotted in line 404.","The cake is a lie. The curse is real.","Don't look behind the server rack.","Exorcising memory leaks at 3 AM.","Pyramid Head reorganized your commit history.","It's dangerous to go alone! Take this flashlight.","YOU DIED. Respawning terminal session...","The Necronomicon evaluated to true.","Something wicked this way compiles.","Haunting your localhost with good vibes.","A full moon has risen over Git main.","Double, double toil and trouble; code fire burn.","Clickers heard in the directory tree.","Checking camera 2B for rogue animatronics.","The call is coming from inside the container.","Isaac Clarke is stomping on stubborn bugs.","Luigi vacuumed the ghosts out of RAM.","Trick or treat, give me clean code to greet.","Whispering incantations to the garbage collector.","Klaatu barada necktie... close enough.","Resurrecting deprecated APIs from the crypt.","The headless horseman forgot the return statement.","Castlevania whip cracking against network latency.","Slime mold crawling through the motherboard.","Carving a pixelated pumpkin into terminal history.","Burying undefined pointers in the pet sematary.","Spilling pumpkin spice on the CPU.","A vampire bat is draining system battery life.","Don't fall asleep at the keyboard tonight.","Silent Hill sirens sounding in the console.","Poltergeists rearranging terminal tabs.","Lighting the Black Flame Candle for autoExec.","Dusting cobwebs off legacy dependencies.","Here's Johnny! ...just checking build health.","Blood, sweat, and zero warnings.","The spirit box whispers: 'GIT PUSH FORCE'.","They're heeeere... in the stack trace.","It's alive! IT'S ALIVEEEE!","No merge conflicts in the graveyard.","Frankenstein's monster patched this logic.","Surviving Five Nights at Flux Flow.","Doom Slayer loading buckshot into cache.","The grim reaper spared your unused imports.","Candy corn lodged in mechanical switches.","May your latency be low and your crypt be quiet."];var Xr=[{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"]}],mo={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"],toolFeedbackAnsi:"\x1B[95m"},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"],toolFeedbackAnsi:"\x1B[95m"},"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"],toolFeedbackAnsi:"\x1B[95m"},"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"],toolFeedbackAnsi:"\x1B[95m"},"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:"#3a1414",diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:"#143a14",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"],toolFeedbackAnsi:"\x1B[95m"},"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:"#f5d0d0",diffAdditionHighlightColor:"#004000",diffAdditionHighlightBg:"#cceccc",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"],toolFeedbackAnsi:"\x1B[95m"},"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"],toolFeedbackAnsi:"\x1B[38;2;3;232;252m"},"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"],toolFeedbackAnsi:"\x1B[38;2;143;235;115m"},Spookfest:{id:"Spookfest",name:"Spookfest \u{1F383}",text:"#ffeedd",textMuted:"#e09858",textDim:"#a6622b",textInverted:"#0d0702",textExclusive:"#fff3e6",textMutedExclusive:"#d4a276",border:"#ff7518",borderMuted:"#994409",borderDim:"#592502",bg:void 0,cardBg:"#1a0c02",highlightBg:"#2a1403",activeBg:"#3d1d05",inputBg:"#261203",inputBorder:"#261203",inputText:"#ffeedd",inputPlaceholder:"#a6622b",inputPrompt:"#ff7518",codeBg:"#120701",codeBorder:"#592502",userMsgBg:"#261203",userMsgBorder:"#261203",userMsgText:"#ffeedd",diffRemovalBg:"#3d0a0a",diffAdditionBg:"#1a330a",diffRemovalText:"#ff5555",diffAdditionText:"#73e639",diffRemovalHighlightColor:"#ff2222",diffRemovalHighlightBg:"#590e0e",diffAdditionHighlightColor:"#88ff3b",diffAdditionHighlightBg:"#244d0a",diffRemovalNum:"#ff5555",diffAdditionNum:"#73e639",diffRemovalPrefix:"#ff3333",diffAdditionPrefix:"#88ff3b",primary:"#ff7518",secondary:"#a855f7",accent:"#22c55e",success:"#22c55e",warning:"#f59e0b",danger:"#ef4444",info:"#a855f7",statusOn:"#ff7518",statusOff:"#703a08",logoTextAnsi:"\x1B[1;38;2;255;117;24m",logoBodyAnsi:"\x1B[38;2;255;140;26m",logoMutedAnsi:"\x1B[38;2;168;85;247m",logoGradient:["#ff7518","#a855f7"],toolFeedbackAnsi:"\x1B[38;2;255;117;24m"}};var mi=null;var pi=(e="Dark")=>{let n;e==="Mystery"||e==="Chaos"?(mi||(mi=Xr[Math.floor(Math.random()*Xr.length)]),n={...mi,id:"Mystery"}):(mi=null,mo[e]?n=mo[e]:e==="Halloween"?n=mo.Spookfest:e==="GitHub"?n=mo["GitHub Dark"]:e==="Transparent"?n=mo["Transparent Dark"]:n=mo.Dark);let t=n.codeText||n.secondary||n.info||n.logoGradient&&n.logoGradient[0]||"cyan",i=n.toolFeedbackAnsi||"\x1B[95m";return{...n,codeText:t,toolFeedbackAnsi:i}};var Ka=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",Wc=(e=2)=>{let n=Ka();return n==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)},Jr=new Date,Uo=Jr.getMonth(),Wo=Jr.getDate(),Va=Uo===9&&Wo>=15||Uo===10&&Wo<=1,rs=null;(process.env.SPOOKFEST==="true"||Va)&&(rs=await import("./halloween-MX3VNQRW.js"));var Gc=(e="...",n="Loading...",t="Dark")=>{let i=pi(t),o=n;if(n==="c_openai"||n==="Custom (OpenAI)")try{let K=Zo(Xo,{})?.systemSettings?.customOpenAIBaseUrl;K&&(o=K)}catch{}let r=i.logoTextAnsi,c=i.logoBodyAnsi,a=i.logoMutedAnsi,u="\x1B[0m",h=[" \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 "],x=t==="Spookfest"||i.id==="Spookfest"||t==="Halloween"||i.id==="Halloween",p=Uo===9&&Wo>=15||Uo===10&&Wo<=1,f=x&&p||process.env.SPOOKFEST==="true"&&x,s=h;if(f&&rs){process.env.HALLOWEEN_EEGG="true";let{halloweenArtSide:D,halloweenBat:K,halloweenArtUser:O}=rs;s=Math.random()>.9&&Uo===9&&Wo>=30?K:Math.random()>.5?D:O}else process.env.HALLOWEEN_EEGG="false";let g=f?qr:zr,k=g[Math.floor(Math.random()*g.length)],he=i.logoGradient||["#0077ff","#ff00ff"],y=ja(he).multiline(s.join(`
569
+ ${e}`:""}`.trim();var Rr=()=>import("./web_search-KBGH67IV.js").then(e=>e.web_search),_r=()=>import("./web_scrape-J3PL2PXT.js").then(e=>e.web_scrape),vr=()=>import("./memory-7YOYCOXE.js").then(e=>e.memory),Ir=()=>import("./chat-BA72I6O3.js").then(e=>e.chat),Mr=()=>import("./view_file-I77KYUO5.js").then(e=>e.view_file),Pr=()=>import("./write_file-D7QA2LB2.js").then(e=>e.write_file),Or=()=>import("./update_file-QKDDZKOX.js").then(e=>e.update_file),Lr=()=>import("./exec_command-6V5SM6WI.js").then(e=>e.exec_command),$r=()=>import("./read_folder-EI2CNHNS.js").then(e=>e.read_folder),os=()=>import("./ask_user-K2DLZF6H.js").then(e=>e.ask_user),Nr=()=>import("./write_pdf-TPGUF4VT.js").then(e=>e.write_pdf),Dr=()=>import("./write_docx-E3MTFXTQ.js").then(e=>e.write_docx),ai=()=>import("./search_keyword-O52M65TB.js").then(e=>e.search_keyword),Fr=()=>import("./generate_image-VW5VG6VI.js").then(e=>e.generate_image),li=()=>import("./saveSummary-W2JMDVZJ.js").then(e=>e.saveSummary),No=()=>import("./addMemScore-PBVNSFPN.js").then(e=>e.addMemScore),Br=()=>import("./file_map-UA4BA5OH.js").then(e=>e.file_map),ci=()=>import("./todo-CJLWLWJB.js").then(e=>e.todo),Ur=()=>import("./invokeSync-UYRKSUNO.js").then(e=>e.invokeSync),Ha=()=>import("./invoke-QXYLLM2W.js").then(e=>e.invoke),Wr=()=>import("./getProgress-J34K43Y7.js").then(e=>e.getProgress),ja=()=>import("./cancel-F3ZOEBKW.js").then(e=>e.cancel),Gr=()=>import("./emergency_rollback-ZHQXCIHW.js").then(e=>e.emergency_rollback),Do=()=>import("./awaitSubagent-JKQ2EHVY.js").then(e=>e.awaitSubagent),Fo=()=>import("./answerSubagent-BPNNJXPC.js").then(e=>e.answerSubagent),di=()=>import("./steerSubagent-UETXH2CB.js").then(e=>e.steerSubagent),fi=()=>import("./computer_action-WNXZNAIZ.js").then(e=>e.computer_action),Hr=()=>import("./click-R35XTYKT.js").then(e=>e.click),jr=()=>import("./drag-IB5WSI6F.js").then(e=>e.drag),Kr=()=>import("./scroll-GIP2J2QN.js").then(e=>e.scroll),is=()=>import("./keyboard_typing-YHYH7O66.js").then(e=>e.keyboard_typing),ss=()=>import("./key_press-XDYBP7DW.js").then(e=>e.key_press),rs=()=>import("./recapture_screen-F6ZPZU56.js").then(e=>e.recapture_screen),ui=()=>import("./find_file-HYHHFHUJ.js").then(e=>e.find_file),Vr=()=>import("./wait-TJR6LAR4.js").then(e=>e.wait),Yr={web_search:Rr,web_scrape:_r,memory:vr,chat:Ir,view_file:Mr,write_file:Pr,update_file:Or,exec_command:Lr,read_folder:$r,write_pdf:Nr,write_docx:Dr,search_keyword:ai,generate_image:Fr,saveSummary:li,addMemScore:No,file_map:Br,todo:ci,Todo:ci,goal:ci,Goal:ci,invokeSync:Ur,invoke:Ha,getProgress:Wr,cancel:ja,awaitSubagent:Do,answerSubagent:Fo,steerSubagent:di,computer_action:fi,computer_use:fi,ComputerAction:fi,ComputerUse:fi,click:Hr,Click:Hr,drag:jr,Drag:jr,scroll:Kr,Scroll:Kr,keyboard_typing:is,KeyboardTyping:is,keyboardtyping:is,key_press:ss,KeyPress:ss,keypress:ss,recapture_screen:rs,RecaptureScreen:rs,recapturescreen:rs,invoke_sync:Ur,get_progress:Wr,await_subagent:Do,answer_subagent:Fo,steer_subagent:di,steer:di,Steer:di,ask:os,Ask:os,AskUser:os,WebSearch:Rr,WebScrape:_r,ReadFile:Mr,ReadFolder:$r,WriteFile:Pr,PatchFile:Or,WritePDF:Nr,WriteDoc:Dr,Run:Lr,SearchKeyword:ai,CodeSearch:ai,code_search:ai,Memory:vr,Chat:Ir,GenerateImage:Fr,saveSumary:li,SaveSummary:li,SaveSumary:li,add_mem_score:No,AddMemScore:No,addMemoryScore:No,AddMemoryScore:No,FileMap:Br,answer:Fo,Answer:Fo,AnswerSubagent:Fo,await:Do,Await:Do,AwaitSubagent:Do,EmergencyRollback:Gr,emergency_rollback:Gr,find_file:ui,findFile:ui,FindFile:ui,findfile:ui,wait:Vr,Wait:Vr},Bo=async(e,n,t={})=>{let i=t.mode?t.mode.toLowerCase():"flux",o=e.toLowerCase(),d=["memory","chat","savesummary","addmemscore","add_mem_score","ask","web_search","web_scrape","await","wait"].some(x=>o.includes(x))||o==="ask",u=["click","drag","scroll","keyboardtyping","keyboard_typing","keypress","key_press","recapturescreen","recapture_screen","computer","wait"].some(x=>o.includes(x));if(!d){if(i==="flow"){if(!(o.includes("write_pdf")||o.includes("write_docx")||o.includes("generate_image")))return`ERROR: Action [${e}] is a Workspace Tool and NOT available in Flow mode. Tell user to switch (\`/mode flux\`) to use this tool.`}else if(i==="icu"){if(!u)return`ERROR: Action [${e}] is not available in Computer Use mode. ICU mode only supports Computer Use tools (Click, Drag, Scroll, KeyboardTyping, KeyPress, RecaptureScreen).`}else if(o.includes("write_pdf")||o.includes("write_docx")||o.includes("generate_image"))return`ERROR: Action [${e}] is not available in ${t.mode||"Flux"} mode. Tell user to switch (\`/mode flow\`) for document generation.`}let h=Yr[e];if(!h){let x=["ReadFile","ReadFolder","FindFile","PatchFile","WriteFile","CodeSearch","Run","Goal","AskUser","WebSearch","WebScrape","WritePDF","WriteDoc","Click","Drag","Scroll","KeyboardTyping","KeyPress","RecaptureScreen","Wait","Invoke","InvokeSync","Await","GetProgress","Steer","Cancel","EmergencyRollback","Chat","Memory"],p={read:"ReadFile",view:"ReadFile",viewfile:"ReadFile",write:"WriteFile",edit:"PatchFile",patch:"PatchFile",update:"PatchFile",updatefile:"PatchFile",exec:"Run",command:"Run",bash:"Run",shell:"Run",powershell:"Run",search:"CodeSearch",grep:"CodeSearch",find:"FindFile",findfile:"FindFile",searchkeyword:"CodeSearch",folder:"ReadFolder",ls:"ReadFolder",dir:"ReadFolder",list:"ReadFolder",ask:"AskUser",question:"AskUser",pdf:"WritePDF",docx:"WriteDoc",doc:"WriteDoc",word:"WriteDoc",screenshot:"RecaptureScreen",screen:"RecaptureScreen",recapture:"RecaptureScreen",type:"KeyboardTyping",typing:"KeyboardTyping",keyboard:"KeyboardTyping",press:"KeyPress",key:"KeyPress",todo:"Goal",task:"Goal",subagent:"Invoke",agent:"Invoke"},f=o.replace(/[^a-z0-9]/g,""),s=p[f]||null;if(!s){let k=0,he=E=>{let D=new Set;for(let K=0;K<E.length-1;K++)D.add(E.slice(K,K+2));return D},y=he(f);for(let E of x){let D=E.toLowerCase().replace(/[^a-z0-9]/g,"");if(f===D){s=E;break}let K=0;(D.includes(f)||f.includes(D))&&(K+=.6);let L=he(D),T=0;for(let Ce of y)L.has(Ce)&&T++;let Se=2*T/(y.size+L.size||1);K=Math.max(K,Se),K>k&&K>=.35&&(k=K,s=E)}}let g=s?` Do you mean '${s}'?`:"";return`ERROR: Action [${e}] not found in registry.${g}`}try{return await(await h())(n,t)}catch(x){let p=x instanceof Error?x.message:String(x);return`ERROR: Execution failed for [${e}]: ${p}`}};var gi=e=>{if(!e||typeof e!="string")return!1;let n=e.trim().toLowerCase();return Object.keys(Yr).some(t=>t.toLowerCase()===n)};import U from"path";import Ae from"fs";import{execSync as us}from"child_process";import Ka 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 qr=["Beware the phantom processes.","A ghost in the shell has taken the wheel.","Blowing on the haunted cartridge...","Seven minutes in Raccoon City.","Wind's howling... in the terminal fans.","Slender Man was spotted in line 404.","The cake is a lie. The curse is real.","Don't look behind the server rack.","Exorcising memory leaks at 3 AM.","Pyramid Head reorganized your commit history.","It's dangerous to go alone! Take this flashlight.","YOU DIED. Respawning terminal session...","The Necronomicon evaluated to true.","Something wicked this way compiles.","Haunting your localhost with good vibes.","A full moon has risen over Git main.","Double, double toil and trouble; code fire burn.","Clickers heard in the directory tree.","Checking camera 2B for rogue animatronics.","The call is coming from inside the container.","Isaac Clarke is stomping on stubborn bugs.","Luigi vacuumed the ghosts out of RAM.","Trick or treat, give me clean code to greet.","Whispering incantations to the garbage collector.","Klaatu barada necktie... close enough.","Resurrecting deprecated APIs from the crypt.","The headless horseman forgot the return statement.","Castlevania whip cracking against network latency.","Slime mold crawling through the motherboard.","Carving a pixelated pumpkin into terminal history.","Burying undefined pointers in the pet sematary.","Spilling pumpkin spice on the CPU.","A vampire bat is draining system battery life.","Don't fall asleep at the keyboard tonight.","Silent Hill sirens sounding in the console.","Poltergeists rearranging terminal tabs.","Lighting the Black Flame Candle for autoExec.","Dusting cobwebs off legacy dependencies.","Here's Johnny! ...just checking build health.","Blood, sweat, and zero warnings.","The spirit box whispers: 'GIT PUSH FORCE'.","They're heeeere... in the stack trace.","It's alive! IT'S ALIVEEEE!","No merge conflicts in the graveyard.","Frankenstein's monster patched this logic.","Surviving Five Nights at Flux Flow.","Doom Slayer loading buckshot into cache.","The grim reaper spared your unused imports.","Candy corn lodged in mechanical switches.","May your latency be low and your crypt be quiet."];var Xr=[{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"]}],mo={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"],toolFeedbackAnsi:"\x1B[95m"},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"],toolFeedbackAnsi:"\x1B[95m"},"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"],toolFeedbackAnsi:"\x1B[95m"},"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"],toolFeedbackAnsi:"\x1B[95m"},"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:"#3a1414",diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:"#143a14",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"],toolFeedbackAnsi:"\x1B[95m"},"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:"#f5d0d0",diffAdditionHighlightColor:"#004000",diffAdditionHighlightBg:"#cceccc",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"],toolFeedbackAnsi:"\x1B[95m"},"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"],toolFeedbackAnsi:"\x1B[38;2;3;232;252m"},"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"],toolFeedbackAnsi:"\x1B[38;2;143;235;115m"},Spookfest:{id:"Spookfest",name:"Spookfest \u{1F383}",text:"#ffeedd",textMuted:"#e09858",textDim:"#a6622b",textInverted:"#0d0702",textExclusive:"#fff3e6",textMutedExclusive:"#d4a276",border:"#ff7518",borderMuted:"#994409",borderDim:"#592502",bg:void 0,cardBg:"#1a0c02",highlightBg:"#2a1403",activeBg:"#3d1d05",inputBg:"#261203",inputBorder:"#261203",inputText:"#ffeedd",inputPlaceholder:"#a6622b",inputPrompt:"#ff7518",codeBg:"#120701",codeBorder:"#592502",userMsgBg:"#261203",userMsgBorder:"#261203",userMsgText:"#ffeedd",diffRemovalBg:"#3d0a0a",diffAdditionBg:"#1a330a",diffRemovalText:"#ff5555",diffAdditionText:"#73e639",diffRemovalHighlightColor:"#ff2222",diffRemovalHighlightBg:"#590e0e",diffAdditionHighlightColor:"#88ff3b",diffAdditionHighlightBg:"#244d0a",diffRemovalNum:"#ff5555",diffAdditionNum:"#73e639",diffRemovalPrefix:"#ff3333",diffAdditionPrefix:"#88ff3b",primary:"#ff7518",secondary:"#a855f7",accent:"#22c55e",success:"#22c55e",warning:"#f59e0b",danger:"#ef4444",info:"#a855f7",statusOn:"#ff7518",statusOff:"#703a08",logoTextAnsi:"\x1B[1;38;2;255;117;24m",logoBodyAnsi:"\x1B[38;2;255;140;26m",logoMutedAnsi:"\x1B[38;2;168;85;247m",logoGradient:["#ff7518","#a855f7"],toolFeedbackAnsi:"\x1B[38;2;255;117;24m"}};var mi=null;var pi=(e="Dark")=>{let n;e==="Mystery"||e==="Chaos"?(mi||(mi=Xr[Math.floor(Math.random()*Xr.length)]),n={...mi,id:"Mystery"}):(mi=null,mo[e]?n=mo[e]:e==="Halloween"?n=mo.Spookfest:e==="GitHub"?n=mo["GitHub Dark"]:e==="Transparent"?n=mo["Transparent Dark"]:n=mo.Dark);let t=n.codeText||n.secondary||n.info||n.logoGradient&&n.logoGradient[0]||"cyan",i=n.toolFeedbackAnsi||"\x1B[95m";return{...n,codeText:t,toolFeedbackAnsi:i}};var Va=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",Gc=(e=2)=>{let n=Va();return n==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)},Jr=new Date,Uo=Jr.getMonth(),Wo=Jr.getDate(),Ya=Uo===9&&Wo>=15||Uo===10&&Wo<=1,as=null;(process.env.SPOOKFEST==="true"||Ya)&&(as=await import("./halloween-MX3VNQRW.js"));var Hc=(e="...",n="Loading...",t="Dark")=>{let i=pi(t),o=n;if(n==="c_openai"||n==="Custom (OpenAI)")try{let K=Zo(Xo,{})?.systemSettings?.customOpenAIBaseUrl;K&&(o=K)}catch{}let r=i.logoTextAnsi,d=i.logoBodyAnsi,a=i.logoMutedAnsi,u="\x1B[0m",h=[" \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 "],x=t==="Spookfest"||i.id==="Spookfest"||t==="Halloween"||i.id==="Halloween",p=Uo===9&&Wo>=15||Uo===10&&Wo<=1,f=x&&p||process.env.SPOOKFEST==="true"&&x,s=h;if(f&&as){process.env.HALLOWEEN_EEGG="true";let{halloweenArtSide:D,halloweenBat:K,halloweenArtUser:L}=as;s=Math.random()>.9&&Uo===9&&Wo>=30?K:Math.random()>.5?D:L}else process.env.HALLOWEEN_EEGG="false";let g=f?qr:zr,k=g[Math.floor(Math.random()*g.length)],he=i.logoGradient||["#0077ff","#ff00ff"],y=Ka(he).multiline(s.join(`
570
570
  `)).split(`
571
571
  `),E=D=>`${a}${D}${u}`;return`${y[0]}
572
572
  ${y[1]} ${r}Selected ${f?"Pumpkin":"Provider"}: ${o}${u}
573
573
  ${y[2]}
574
574
  ${y[3]} ${r}FluxFlow${f?": Spookfest":""} ${E("v"+e)}${u}
575
575
  ${y[4]}
576
- ${y[5]} ${c}See /help for additional commands.${u}
576
+ ${y[5]} ${d}See /help for additional commands.${u}
577
577
  ${y[6]} ${E(k)}
578
578
  ${y[7]}
579
- `};import{structuredPatch as Ja}from"diff";import as from"path";import Ya from"fs";var za=e=>{try{return Ya.readdirSync(e,{withFileTypes:!0})}catch{return[]}},ls=(e,n=4,t=1,i=za,o=[],r=null)=>{let c=r||i(e),a=" ".repeat(t-1),u=t===1?new Set([...To,...o,...Ao(e),...Ao(process.cwd())]):o instanceof Set?o:new Set([...To,...o]),h=O=>u.has(O),x=c.filter(O=>!h(O.name)),p=c.filter(O=>h(O.name)).length,f=x.filter(O=>!O.isDirectory()).map(O=>O.name).sort(),s=x.filter(O=>O.isDirectory()).sort((O,T)=>O.name.localeCompare(T.name)),g=O=>{let T=O.length;if(T===0)return"no files";let Se=Array.from(new Set(O.map(Me=>{let Je=typeof Me=="string"?Me:Me.name;return as.extname(Je).slice(1)}).filter(Boolean))).sort(),Ce="*";return Se.length===1?Ce=`*.${Se[0]}`:Se.length>1&&(Ce=`*.{${Se.join(", ")}}`),T===1?Ce:`${Ce} ${T} files`},k="";if(t===1){let O=f.join(", "),T=p>0?` [${p} ignored]`:"";(O||T)&&(k+=`${a}${O?O+(T?`${T}`:""):T.trim()}
579
+ `};import{structuredPatch as Qa}from"diff";import ls from"path";import za from"fs";var qa=e=>{try{return za.readdirSync(e,{withFileTypes:!0})}catch{return[]}},cs=(e,n=4,t=1,i=qa,o=[],r=null)=>{let d=r||i(e),a=" ".repeat(t-1),u=t===1?new Set([...To,...o,...Ao(e),...Ao(process.cwd())]):o instanceof Set?o:new Set([...To,...o]),h=L=>u.has(L),x=d.filter(L=>!h(L.name)),p=d.filter(L=>h(L.name)).length,f=x.filter(L=>!L.isDirectory()).map(L=>L.name).sort(),s=x.filter(L=>L.isDirectory()).sort((L,T)=>L.name.localeCompare(T.name)),g=L=>{let T=L.length;if(T===0)return"no files";let Se=Array.from(new Set(L.map(Me=>{let Je=typeof Me=="string"?Me:Me.name;return ls.extname(Je).slice(1)}).filter(Boolean))).sort(),Ce="*";return Se.length===1?Ce=`*.${Se[0]}`:Se.length>1&&(Ce=`*.{${Se.join(", ")}}`),T===1?Ce:`${Ce} ${T} files`},k="";if(t===1){let L=f.join(", "),T=p>0?` [${p} ignored]`:"";(L||T)&&(k+=`${a}${L?L+(T?`${T}`:""):T.trim()}
580
580
  `)}else f.length>0&&(k+=`${a}[${g(f)}]
581
- `);let he=10,y=s.slice(0,he),E=s.length>he,D=[],K=[];for(let O of y){let T=as.join(e,O.name),Se=O.name,Ce=t,Me=i(T),Je=Me.filter(fe=>!h(fe.name)),G=Je.filter(fe=>fe.isDirectory()),b=Je.filter(fe=>!fe.isDirectory());for(;b.length===0&&G.length===1&&Ce<n;)Se=`${Se}/${G[0].name}`,T=as.join(T,G[0].name),Ce++,Me=i(T),Je=Me.filter(fe=>!h(fe.name)),G=Je.filter(fe=>fe.isDirectory()),b=Je.filter(fe=>!fe.isDirectory());let ht=G.length>0;if(ht&&Ce<n)K.push({displayName:Se,subDirPath:T,subEntries:Me,nextDepth:Ce+1});else{let fe=g(b),q=ht&&Ce>=n?" ...max scan depth":"";D.push(`${Se}/${fe}${q}`)}}D.length>0&&(k+=`${a}${D.join(", ")}
582
- `);for(let{displayName:O,subDirPath:T,subEntries:Se,nextDepth:Ce}of K)k+=`${a}${O}/
583
- `,k+=ls(T,n,Ce,i,u,Se);return E&&(k+=`${a}...max scan width, ReadFolder if needed
584
- `),k};import cs from"path";import qa from"fs";var Xa=e=>{try{return qa.readdirSync(e,{withFileTypes:!0})}catch{return[]}},ds=(e,n,t="",i=1,o=Xa,r=[])=>{let c=o(e),a=cs.sep;if(c.length>100)return`${t}\u2514\u2500\u2500 ${cs.basename(e)}${a} ...100+ files...
585
- `;let u="",h=r,x=c.filter(s=>!h.includes(s.name)&&!s.name.startsWith(".")),p=c.filter(s=>h.includes(s.name)||s.name.startsWith(".")).map(s=>s.name).sort();x.sort((s,g)=>s.isDirectory()&&!g.isDirectory()?-1:!s.isDirectory()&&g.isDirectory()?1:s.name.localeCompare(g.name));let f=[...x.map(s=>({name:s.name,isDir:s.isDirectory()})),...p.map(s=>({name:s,isDir:!0,isCollapsed:!0}))];return f.forEach((s,g)=>{let k=g===f.length-1,he=cs.join(e,s.name),y=k?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",E=t+(k?" ":"\u2502 ");if(s.isCollapsed){u+=`${t}${y}${s.name}${a}...
581
+ `);let he=10,y=s.slice(0,he),E=s.length>he,D=[],K=[];for(let L of y){let T=ls.join(e,L.name),Se=L.name,Ce=t,Me=i(T),Je=Me.filter(fe=>!h(fe.name)),W=Je.filter(fe=>fe.isDirectory()),b=Je.filter(fe=>!fe.isDirectory());for(;b.length===0&&W.length===1&&Ce<n;)Se=`${Se}/${W[0].name}`,T=ls.join(T,W[0].name),Ce++,Me=i(T),Je=Me.filter(fe=>!h(fe.name)),W=Je.filter(fe=>fe.isDirectory()),b=Je.filter(fe=>!fe.isDirectory());let ht=W.length>0;if(ht&&Ce<n)K.push({displayName:Se,subDirPath:T,subEntries:Me,nextDepth:Ce+1});else{let fe=g(b),z=ht&&Ce>=n?" ...max scan depth":"";D.push(`${Se}/${fe}${z}`)}}D.length>0&&(k+=`${a}${D.join(", ")}
582
+ `);for(let{displayName:L,subDirPath:T,subEntries:Se,nextDepth:Ce}of K)k+=`${a}${L}/
583
+ `,k+=cs(T,n,Ce,i,u,Se);return E&&(k+=`${a}...max scan width, ReadFolder if needed
584
+ `),k};import ds from"path";import Xa from"fs";var Ja=e=>{try{return Xa.readdirSync(e,{withFileTypes:!0})}catch{return[]}},fs=(e,n,t="",i=1,o=Ja,r=[])=>{let d=o(e),a=ds.sep;if(d.length>100)return`${t}\u2514\u2500\u2500 ${ds.basename(e)}${a} ...100+ files...
585
+ `;let u="",h=r,x=d.filter(s=>!h.includes(s.name)&&!s.name.startsWith(".")),p=d.filter(s=>h.includes(s.name)||s.name.startsWith(".")).map(s=>s.name).sort();x.sort((s,g)=>s.isDirectory()&&!g.isDirectory()?-1:!s.isDirectory()&&g.isDirectory()?1:s.name.localeCompare(g.name));let f=[...x.map(s=>({name:s.name,isDir:s.isDirectory()})),...p.map(s=>({name:s,isDir:!0,isCollapsed:!0}))];return f.forEach((s,g)=>{let k=g===f.length-1,he=ds.join(e,s.name),y=k?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",E=t+(k?" ":"\u2502 ");if(s.isCollapsed){u+=`${t}${y}${s.name}${a}...
586
586
  `;return}s.isDir?i>n?u+=`${t}${y}${s.name}${a} ...depth exceeded...
587
587
  `:o(he).length>80?u+=`${t}${y}${s.name}${a} ...80+ files...
588
588
  `:(u+=`${t}${y}${s.name}${a}
589
- `,u+=ds(he,n,E,i+1,o,r)):u+=`${t}${y}${s.name}
590
- `}),u};var Qa={Ollama:()=>import("./ollama-4PI2BDMM.js").then(e=>e.getOllamaStream),OpenRouter:()=>import("./openrouter-6MRG4RT6.js").then(e=>e.getOpenRouterStream),DeepSeek:()=>import("./deepseek-WNWZJTNE.js").then(e=>e.getDeepSeekStream),Mistral:()=>import("./mistral-YTTOZB2J.js").then(e=>e.getMistralStream),NVIDIA:()=>import("./nvidia-ON4Q6Q26.js").then(e=>e.getNVIDIAStream),NVIDIA_wrap:()=>import("./nvidia-ON4Q6Q26.js").then(e=>e.wrapNvidiaStreamWithQueueDepth),InferX:()=>import("./inferx-HP5AGET3.js").then(e=>e.getInferXStream),SenseNova:()=>import("./sensenova-3K44URJQ.js").then(e=>e.getSenseNovaStream),AIHubMix:()=>import("./aihubmix-TETL5QYQ.js").then(e=>e.getAIHubMixStream),Poolside:()=>import("./poolside-ODFAIK4C.js").then(e=>e.getPoolsideStream),NineRouter:()=>import("./9router-LRFKCJF4.js").then(e=>e.getNineRouterStream),ExpLabs:()=>import("./explabs-XHHXTERB.js").then(e=>e.getExpLabsStream),TokenHarbor:()=>import("./tokenharbor-YV2GV2LM.js").then(e=>e.getTokenHarborStream),Infron:()=>import("./infron-ULXG7VDA.js").then(e=>e.getInfronStream),APInex:()=>import("./apinex-FAYOPQSL.js").then(e=>e.getAPInexStream),xKiro:()=>import("./xkiro-B2LYGZTF.js").then(e=>e.getXKiroStream),c_openai:()=>import("./custom_openai-XMDYE7NM.js").then(e=>e.getCustomOpenAIStream)},us={},ce=async e=>(us[e]||(us[e]=await Qa[e]()),us[e]),Za=/```[\s\S]*?```/g,el=/```[\s\S]*$/g,tl=/`[^`]+`/g,nl=/^\|.*\|$/gm,ol=/^[^\w]+|[^\w]+$/g,il=/[^a-z0-9]/gi,Go=/\[\s*(?:tool|action):(?:functions\.)?([a-z0-9_]+)\s*\(/gi,sl=/\[\s*(?:tool:(?:functions\.)?|action:(?:functions\.)?|action:)([a-z0-9_]+)\s*\(/gi,rl=/(?:path|targetFile|TargetFile|directory|keyword|id|taskId|title|task)\s*=\s*\\?["']?([^\\"' \),]+)/,Mn=/["']/g,Qr=/\\/g,al=/<\|channel>thought/gi,ll=/<channel\|>/gi,cl=e=>typeof e!="string"?e:e.replace(al,"<think_fluxflow>").replace(ll,"</think_fluxflow>"),Md=/^\s*(?:<think_fluxflow[^>]*>|<\|channel>thought|\[think_fluxflow\])[\s\S]*?(?:<\/think_fluxflow>|<channel\|>|\[\/think_fluxflow\]|$)/i,dl=(e,n,t=1)=>{let i=n>0?e[n-1]:"",o=n+t<e.length?e[n+t]:"";return i==="`"&&o==="`"},fl=e=>{let n=/(?:<\/think_fluxflow>|<channel\|>|\[\/think_fluxflow\])/gi,t;for(;(t=n.exec(e))!==null;)if(!dl(e,t.index,t[0].length))return{index:t.index,length:t[0].length};return{index:-1,length:0}},gs=e=>{if(!e||typeof e!="string")return null;let n=e.match(/^\s*(?:<think_fluxflow[^>]*>|<\|channel>thought|\[think_fluxflow\])/i);if(!n)return null;let t=n.index+n[0].length,i=e.substring(t),o=fl(i);if(o.index!==-1){let r=t+o.index+o.length;return{fullBlock:e.substring(0,r),innerContent:i.substring(0,o.index),remainingText:e.substring(r)}}return{fullBlock:e,innerContent:i,remainingText:""}},Kt=e=>{if(!e||typeof e!="string")return e;let n=gs(e);return n?n.remainingText.trimStart():e};var Zr=/<\|\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,ul=/"([^"]+)"\s*:\s*(?:"([^"]*)"|(\d+)|true|false|null)/g,ea=/<\|\s*tool_calls_section_begin\s*\|>/gi,ta=/<\|\s*tool_calls_section_end\s*\|>/gi,gl=/```(?:tool|action|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi;var hi=e=>!e||typeof e!="string"?e:e.replace(/(```[\s\S]*?```|`[^`]*`)|(<(?:\w+)(?:[^>]*)>\r?\n?|\r?\n?<\/\w+(?:[^>]*)>)/gi,(n,t)=>t||""),sa=e=>{if(!e||typeof e!="string")return e;let n=eo(e);if(!n||n.length===0)return e;let t=n[n.length-1];if(!t.fullMatch)return e;let i=e.lastIndexOf(t.fullMatch);if(i===-1)return e;let o=i+t.fullMatch.length,r=e.substring(o);return/\[\s*(?:tool|action):/i.test(r)?e.trimEnd():e.substring(0,o).trimEnd()},ps=null,Ho={},Qn={key:null,value:null},jt=e=>{if(!e)return e;let n=Ho?.theme;if(!n)try{n=Zo(Xo,{})?.systemSettings?.theme}catch{}let i=pi(n||"Dark").toolFeedbackAnsi||"\x1B[95m";return e.replace(/(?:(\x1b\[\d+m))?([✔✘✖🔍📖→➕↻↷•🛇])(?:(\x1b\[\d+m))?\s*\b(Clicked Screen|Clicked|Located|Dragged|Scrolled|Typed|Entered|Pressed Key|Recaptured Screen|Created|Read Skill|Read Documentation|Executed|Searched Documentation|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|Model produced malformed tool call|Loop Detected|Contacting Ancestors)\b/ig,(o,r,c,a,u)=>`${r||""}${c}${a||""} ${i}${u}\x1B[0m`)},ml=async(e,n=8,t=1e3,i=8e3,o=null)=>{let r=0;for(;;){if(o?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{return await e()}catch(c){if(o?.aborted||c?.name==="AbortError"||c?.message==="Subagent task was cancelled."||(r++,r>=n))throw c;let a=Math.min(t*Math.pow(2,r-1),i);await new Promise((u,h)=>{let x=setTimeout(u,a);o&&o.addEventListener("abort",()=>{clearTimeout(x),h(new DOMException("The user aborted a request.","AbortError"))})})}}},Et=!1;var pl=e=>{let n=e.filter(o=>(o.role==="user"||o.role==="agent"||o.role==="system")&&o.role!=="think"&&!o.isVisualFeedback&&!o.isMeta&&!o.isTerminalRecord&&!(o.text&&o.text.includes("[TERMINAL_RECORD]"))&&!String(o.id).startsWith("welcome")).map((o,r,c)=>{let a=o.fullText||o.text||"";if(o.role==="user"&&r<c.length-1)if(a.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")){let u=a.indexOf("**CONTEXT SUMMARY OF PREVIOUS TURNS");if(u!==-1){let x=a.substring(0,u).lastIndexOf("[SYSTEM METADATA]");x!==-1?a=a.substring(x).trim():a=a.substring(u).trim()}}else{let u=a.lastIndexOf("[USER]"),h=a.lastIndexOf("[USER PROMPT]");u!==-1?a=a.substring(u+6).trim():h!==-1&&(a=a.substring(h).trim())}return{...o,text:a}}),t=[],i=0;for(;i<n.length;){let o=n[i];if(o.role==="user")t.push(o),i++;else{let r=[];for(;i<n.length&&n[i].role!=="user";)r.push(n[i]),i++;let c=[],a=[],u=!1,h=()=>{c.length>0&&(t.push({role:"agent",text:"combined"}),c=[]),a.length>0&&(t.push({role:"system",text:"combined"}),a=[]),u=!1};r.forEach(x=>{let p=x.role==="system"&&(x.text?.startsWith("[ACTION RESULT]")||x.text?.startsWith("[TOOL RESULT]")||x.text?.startsWith("SUCCESS:")||x.text?.startsWith("ERROR:")||x.fullText?.startsWith("[ACTION RESULT]")||x.fullText?.startsWith("[TOOL RESULT]")||x.fullText?.startsWith("SUCCESS:")||x.fullText?.startsWith("ERROR:")),f=x.fullText||x.text||"",s=f.trim();if(!(!s&&!x.binaryPart)){if(p)a.push(s);else if(x.role==="agent"){!u&&a.length>0&&h();let g=f.endsWith(`
591
- `),k=s.toLowerCase().includes("tool:")||s.toLowerCase().includes("action:");c.push(s),k&&g?u=!0:u=!1}}}),h()}}return t.length},hl=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),Pd=()=>{Et=!0},Od=()=>Et,ms={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",find_file:"Finding File",findFile:"Finding File",FindFile:"Finding File",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",wait:"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"},Zn=(e,n)=>{try{let t=j(n),i=e.toLowerCase().replace(/_/g,"");if(i==="invokesync"||i==="invoke")return t.title||(t.task?t.task.substring(0,30):null);if(i==="getprogress"||i==="cancel"||i==="steer"||i==="steersubagent")return t.id||t.taskId;let o=t.name||t.path||t.targetFile||t.TargetFile||t.directory||t.file||t.query;return o?W.basename(o.replace(/["']/g,"").replace(/\\/g,"/")):null}catch{return null}},hs=e=>e?new ia({apiKey:e}):ps,Ld=async(e,n,t,i,o={})=>{let{onStatus:a,onMemoryUpdated:u,onBackgroundIncrement:h}=o,{profile:x,thinkingLevel:p,mode:f,janitorModel:s,chatId:g,systemSettings:k,sessionStats:he,aiProvider:y="Google",apiKey:E}=e,D=process.env.NVIDIA_BASE_URL||y==="Ollama"||y==="InferX"||y==="SenseNova"||y==="AIHubMix"||y==="Poolside"||y==="9router"||y==="ExpLabs"||y==="ExperientialLabs"||y==="c_openai"||y==="Custom (OpenAI)"?!1:k?.memory!==!1,O=Ot(Xn,[]).map(ue=>`- [${ue.id}]: ${ue.memory}`).join(`
592
- `),T=i.slice(0,-1).filter(ue=>ue.text&&!ue.text.includes("[ACTION RESULT]")&&!ue.text.includes("[TOOL RESULT]")&&!ue.text.includes("OBSERVATION:")&&!ue.text.startsWith("[TERMINAL_RECORD]")&&!ue.isTerminalRecord&&!ue.isMeta&&!ue.isLogo&&!String(ue.id).startsWith("welcome")&&!String(ue.id).startsWith("logo")).slice(-14).map(ue=>{let Be=Kt(hl(ue.text)).replace(/\[(?:tool|action):(?:functions\.)?.*?\]/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[METADATA \(PRIORITY: DYNAMIC\)\] Time: ([^|\n]+)/g,(_,Qe)=>`[METADATA (PRIORITY: DYNAMIC)] Time: ${Qe.replace(/:\d{2}/g,"")}`).replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[\[(?:TOOL|ACTION) RESULTS\]\]/gi,"").replace(/\[(?:TOOL|ACTION) RESULTS?\]/gi,"").replace(/\[(?:tool|action) results\]/gi,"").replace(/\r?\n\r?\n/g,`
589
+ `,u+=fs(he,n,E,i+1,o,r)):u+=`${t}${y}${s.name}
590
+ `}),u};var Za={Ollama:()=>import("./ollama-QB7WX7VD.js").then(e=>e.getOllamaStream),OpenRouter:()=>import("./openrouter-6MRG4RT6.js").then(e=>e.getOpenRouterStream),DeepSeek:()=>import("./deepseek-WNWZJTNE.js").then(e=>e.getDeepSeekStream),Mistral:()=>import("./mistral-YTTOZB2J.js").then(e=>e.getMistralStream),NVIDIA:()=>import("./nvidia-ON4Q6Q26.js").then(e=>e.getNVIDIAStream),NVIDIA_wrap:()=>import("./nvidia-ON4Q6Q26.js").then(e=>e.wrapNvidiaStreamWithQueueDepth),InferX:()=>import("./inferx-HP5AGET3.js").then(e=>e.getInferXStream),SenseNova:()=>import("./sensenova-3K44URJQ.js").then(e=>e.getSenseNovaStream),AIHubMix:()=>import("./aihubmix-TETL5QYQ.js").then(e=>e.getAIHubMixStream),Poolside:()=>import("./poolside-ODFAIK4C.js").then(e=>e.getPoolsideStream),NineRouter:()=>import("./9router-LRFKCJF4.js").then(e=>e.getNineRouterStream),ExpLabs:()=>import("./explabs-XHHXTERB.js").then(e=>e.getExpLabsStream),TokenHarbor:()=>import("./tokenharbor-YV2GV2LM.js").then(e=>e.getTokenHarborStream),Infron:()=>import("./infron-ULXG7VDA.js").then(e=>e.getInfronStream),APInex:()=>import("./apinex-FAYOPQSL.js").then(e=>e.getAPInexStream),xKiro:()=>import("./xkiro-B2LYGZTF.js").then(e=>e.getXKiroStream),c_openai:()=>import("./custom_openai-YS5EV6DG.js").then(e=>e.getCustomOpenAIStream)},gs={},ce=async e=>(gs[e]||(gs[e]=await Za[e]()),gs[e]),el=/```[\s\S]*?```/g,tl=/```[\s\S]*$/g,nl=/`[^`]+`/g,ol=/^\|.*\|$/gm,il=/^[^\w]+|[^\w]+$/g,sl=/[^a-z0-9]/gi,Go=/\[\s*(?:tool|action):(?:functions\.)?([a-z0-9_]+)\s*\(/gi,rl=/\[\s*(?:tool:(?:functions\.)?|action:(?:functions\.)?|action:)([a-z0-9_]+)\s*\(/gi,al=/(?:path|targetFile|TargetFile|directory|keyword|id|taskId|title|task)\s*=\s*\\?["']?([^\\"' \),]+)/,Mn=/["']/g,Qr=/\\/g,ll=/<\|channel>thought/gi,cl=/<channel\|>/gi,dl=e=>typeof e!="string"?e:e.replace(ll,"<think_fluxflow>").replace(cl,"</think_fluxflow>"),Pd=/^\s*(?:<think_fluxflow[^>]*>|<\|channel>thought|\[think_fluxflow\])[\s\S]*?(?:<\/think_fluxflow>|<channel\|>|\[\/think_fluxflow\]|$)/i,fl=(e,n,t=1)=>{let i=n>0?e[n-1]:"",o=n+t<e.length?e[n+t]:"";return i==="`"&&o==="`"},ul=e=>{let n=/(?:<\/think_fluxflow>|<channel\|>|\[\/think_fluxflow\])/gi,t;for(;(t=n.exec(e))!==null;)if(!fl(e,t.index,t[0].length))return{index:t.index,length:t[0].length};return{index:-1,length:0}},ms=e=>{if(!e||typeof e!="string")return null;let n=e.match(/^\s*(?:<think_fluxflow[^>]*>|<\|channel>thought|\[think_fluxflow\])/i);if(!n)return null;let t=n.index+n[0].length,i=e.substring(t),o=ul(i);if(o.index!==-1){let r=t+o.index+o.length;return{fullBlock:e.substring(0,r),innerContent:i.substring(0,o.index),remainingText:e.substring(r)}}return{fullBlock:e,innerContent:i,remainingText:""}},Bt=e=>{if(!e||typeof e!="string")return e;let n=ms(e);return n?n.remainingText.trimStart():e};var Zr=/<\|\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,gl=/"([^"]+)"\s*:\s*(?:"([^"]*)"|(\d+)|true|false|null)/g,ea=/<\|\s*tool_calls_section_begin\s*\|>/gi,ta=/<\|\s*tool_calls_section_end\s*\|>/gi,ml=/```(?:tool|action|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi;var hi=e=>!e||typeof e!="string"?e:e.replace(/(```[\s\S]*?```|`[^`]*`)|(<(?:\w+)(?:[^>]*)>\r?\n?|\r?\n?<\/\w+(?:[^>]*)>)/gi,(n,t)=>t||""),sa=e=>{if(!e||typeof e!="string")return e;let n=jn(e);if(!n||n.length===0)return e;let t=n[n.length-1];if(!t.fullMatch)return e;let i=e.lastIndexOf(t.fullMatch);if(i===-1)return e;let o=i+t.fullMatch.length,r=e.substring(o);return/\[\s*(?:tool|action):/i.test(r)?e.trimEnd():e.substring(0,o).trimEnd()},hs=null,Ho={},Zn={key:null,value:null},Kt=e=>{if(!e)return e;let n=Ho?.theme;if(!n)try{n=Zo(Xo,{})?.systemSettings?.theme}catch{}let i=pi(n||"Dark").toolFeedbackAnsi||"\x1B[95m";return e.replace(/(?:(\x1b\[\d+m))?([✔✘✖🔍📖→➕↻↷•🛇])(?:(\x1b\[\d+m))?\s*\b(Clicked Screen|Clicked|Located|Dragged|Scrolled|Typed|Entered|Pressed Key|Recaptured Screen|Created|Read Skill|Read Documentation|Executed|Searched Documentation|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|Model produced malformed tool call|Loop Detected|Contacting Ancestors)\b/ig,(o,r,d,a,u)=>`${r||""}${d}${a||""} ${i}${u}\x1B[0m`)},pl=async(e,n=8,t=1e3,i=8e3,o=null)=>{let r=0;for(;;){if(o?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{return await e()}catch(d){if(o?.aborted||d?.name==="AbortError"||d?.message==="Subagent task was cancelled."||(r++,r>=n))throw d;let a=Math.min(t*Math.pow(2,r-1),i);await new Promise((u,h)=>{let x=setTimeout(u,a);o&&o.addEventListener("abort",()=>{clearTimeout(x),h(new DOMException("The user aborted a request.","AbortError"))})})}}},Et=!1;var hl=e=>{let n=e.filter(o=>(o.role==="user"||o.role==="agent"||o.role==="system")&&o.role!=="think"&&!o.isVisualFeedback&&!o.isMeta&&!o.isTerminalRecord&&!(o.text&&o.text.includes("[TERMINAL_RECORD]"))&&!String(o.id).startsWith("welcome")).map((o,r,d)=>{let a=o.fullText||o.text||"";if(o.role==="user"&&r<d.length-1)if(a.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")){let u=a.indexOf("**CONTEXT SUMMARY OF PREVIOUS TURNS");if(u!==-1){let x=a.substring(0,u).lastIndexOf("[SYSTEM METADATA]");x!==-1?a=a.substring(x).trim():a=a.substring(u).trim()}}else{let u=a.lastIndexOf("[USER]"),h=a.lastIndexOf("[USER PROMPT]");u!==-1?a=a.substring(u+6).trim():h!==-1&&(a=a.substring(h).trim())}return{...o,text:a}}),t=[],i=0;for(;i<n.length;){let o=n[i];if(o.role==="user")t.push(o),i++;else{let r=[];for(;i<n.length&&n[i].role!=="user";)r.push(n[i]),i++;let d=[],a=[],u=!1,h=()=>{d.length>0&&(t.push({role:"agent",text:"combined"}),d=[]),a.length>0&&(t.push({role:"system",text:"combined"}),a=[]),u=!1};r.forEach(x=>{let p=x.role==="system"&&(x.text?.startsWith("[ACTION RESULT]")||x.text?.startsWith("[TOOL RESULT]")||x.text?.startsWith("SUCCESS:")||x.text?.startsWith("ERROR:")||x.fullText?.startsWith("[ACTION RESULT]")||x.fullText?.startsWith("[TOOL RESULT]")||x.fullText?.startsWith("SUCCESS:")||x.fullText?.startsWith("ERROR:")),f=x.fullText||x.text||"",s=f.trim();if(!(!s&&!x.binaryPart)){if(p)a.push(s);else if(x.role==="agent"){!u&&a.length>0&&h();let g=f.endsWith(`
591
+ `),k=s.toLowerCase().includes("tool:")||s.toLowerCase().includes("action:");d.push(s),k&&g?u=!0:u=!1}}}),h()}}return t.length},yl=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),Od=()=>{Et=!0},Ld=()=>Et,ps={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",find_file:"Finding File",findFile:"Finding File",FindFile:"Finding File",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",wait:"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"},eo=(e,n)=>{try{let t=j(n),i=e.toLowerCase().replace(/_/g,"");if(i==="invokesync"||i==="invoke")return t.title||(t.task?t.task.substring(0,30):null);if(i==="getprogress"||i==="cancel"||i==="steer"||i==="steersubagent")return t.id||t.taskId;let o=t.name||t.path||t.targetFile||t.TargetFile||t.directory||t.file||t.query;return o?U.basename(o.replace(/["']/g,"").replace(/\\/g,"/")):null}catch{return null}},ys=e=>e?new ia({apiKey:e}):hs,$d=async(e,n,t,i,o={})=>{let{onStatus:a,onMemoryUpdated:u,onBackgroundIncrement:h}=o,{profile:x,thinkingLevel:p,mode:f,janitorModel:s,chatId:g,systemSettings:k,sessionStats:he,aiProvider:y="Google",apiKey:E}=e,D=process.env.NVIDIA_BASE_URL||y==="Ollama"||y==="InferX"||y==="SenseNova"||y==="AIHubMix"||y==="Poolside"||y==="9router"||y==="ExpLabs"||y==="ExperientialLabs"||y==="c_openai"||y==="Custom (OpenAI)"?!1:k?.memory!==!1,L=Ot(Jn,[]).map(ue=>`- [${ue.id}]: ${ue.memory}`).join(`
592
+ `),T=i.slice(0,-1).filter(ue=>ue.text&&!ue.text.includes("[ACTION RESULT]")&&!ue.text.includes("[TOOL RESULT]")&&!ue.text.includes("OBSERVATION:")&&!ue.text.startsWith("[TERMINAL_RECORD]")&&!ue.isTerminalRecord&&!ue.isMeta&&!ue.isLogo&&!String(ue.id).startsWith("welcome")&&!String(ue.id).startsWith("logo")).slice(-14).map(ue=>{let Be=Bt(yl(ue.text)).replace(/\[(?:tool|action):(?:functions\.)?.*?\]/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[METADATA \(PRIORITY: DYNAMIC\)\] Time: ([^|\n]+)/g,(_,Qe)=>`[METADATA (PRIORITY: DYNAMIC)] Time: ${Qe.replace(/:\d{2}/g,"")}`).replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[\[(?:TOOL|ACTION) RESULTS\]\]/gi,"").replace(/\[(?:TOOL|ACTION) RESULTS?\]/gi,"").replace(/\[(?:tool|action) results\]/gi,"").replace(/\r?\n\r?\n/g,`
593
593
  `).replace(/\n\n/g,`
594
- `).replace(/\\n\\n/g,"").trim(),Pe=ue.role==="user"?8192:32768,Y=Be.substring(0,Pe);Be.length>Pe&&(Y+=`
595
- ... (truncated) ...`);let H=ue.role==="user"?Y.startsWith("[USER]")?"":"[USER]: ":Y.startsWith("[AGENT]")?"":"[AGENT]: ";return{role:ue.role==="user"?"user":"model",parts:[{text:`${H}${Y}`}]}}),Se=i.filter(ue=>ue.role==="user").length===1,Ce=n.includes("[TITLE-UPDATE]"),Me=Math.random()<.8,Je=Se||Ce||Me,G=Kt(t).trim(),b=Cr(O,D,Je),ht=`${G.replace(/\[(?:tool|action):(?:functions\.)?.*?\]/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[\[(?:TOOL|ACTION) RESULTS\]\]/gi,"").replace(/\[(?:TOOL|ACTION) RESULTS?\]/gi,"").replace(/\[(?:tool|action) results\]/gi,"").substring(0,32768)}`;ht.length>32768&&(ht+=`
594
+ `).replace(/\\n\\n/g,"").trim(),Pe=ue.role==="user"?8192:32768,V=Be.substring(0,Pe);Be.length>Pe&&(V+=`
595
+ ... (truncated) ...`);let G=ue.role==="user"?V.startsWith("[USER]")?"":"[USER]: ":V.startsWith("[AGENT]")?"":"[AGENT]: ";return{role:ue.role==="user"?"user":"model",parts:[{text:`${G}${V}`}]}}),Se=i.filter(ue=>ue.role==="user").length===1,Ce=n.includes("[TITLE-UPDATE]"),Me=Math.random()<.8,Je=Se||Ce||Me,W=Bt(t).trim(),b=Cr(L,D,Je),ht=`${W.replace(/\[(?:tool|action):(?:functions\.)?.*?\]/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[\[(?:TOOL|ACTION) RESULTS\]\]/gi,"").replace(/\[(?:TOOL|ACTION) RESULTS?\]/gi,"").replace(/\[(?:tool|action) results\]/gi,"").substring(0,32768)}`;ht.length>32768&&(ht+=`
596
596
  ... (truncated) ...`);let fe=n.replace(/\[Prompted on:.*?\]/g,"").trim();ht=ht.replace(/\r?\n\r?\n/g,`
597
597
  `).replace(/\n\n/g,`
598
- `).replace(/\\n\\n/g,"").trim();let q=new Date,Vt=`[METADATA] Current date and Time: ${`${q.getFullYear()}-${q.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(q.getDate()).padStart(2,"0")}, ${q.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0})}`}
598
+ `).replace(/\\n\\n/g,"").trim();let z=new Date,Vt=`[METADATA] Current date and Time: ${`${z.getFullYear()}-${z.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(z.getDate()).padStart(2,"0")}, ${z.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0})}`}
599
599
 
600
600
  [USER]: ${fe.substring(0,8192)}
601
601
  ${fe.length>8192?`... (truncated) ...
602
602
 
603
603
  `:""}
604
- [AGENT (current turn)]: ${ht}`;T.push({role:"user",parts:[{text:Vt}]});let cn=await Li("NVIDIA"),Pn=(await Eo()).quotas?.providerTiers?.NVIDIA==="Free",dn="",yt=0,Yt=D?12:-1;for(;yt<=Yt;)try{if(!await Ms("background",e))return;let ue="",Be=null,Pe=!1,Y=y;try{let Qe=new Promise((dt,ge)=>setTimeout(()=>ge(new Error("JANITOR_TIMEOUT")),1e4)),Oe=y==="Google"&&yt>=0&&yt<6&&cn&&Pn,S=y==="DeepSeek"&&yt<4&&cn&&Pn;Pe=Oe||S,Y=Pe?"NVIDIA":y;let L=Date.now(),ct=null,ze=(async()=>{if(y==="OpenRouter"){let dt=ae("janitor_open_router"),de=(await ce("OpenRouter"))(E,dt,T,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),$t=await de.next();return{iterator:de,firstResult:$t}}else if(y==="DeepSeek"&&!Pe){let ge=(await ce("DeepSeek"))(E,ae("deepseek_fast_fallback"),T,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),de=await ge.next();return{iterator:ge,firstResult:de}}else if(y==="Mistral"&&!Pe){let ge=(await ce("Mistral"))(E,ae("mistral_janitor_fallback"),T,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),de=await ge.next();return{iterator:ge,firstResult:de}}else if(y==="NVIDIA"||Pe){let ge=(await ce("NVIDIA"))(Pe?cn:E,ae("nvidia_janitor_fallback"),T,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),de=await ge.next();return{iterator:ge,firstResult:de}}else if(y==="InferX"){let ge=(await ce("InferX"))(E,targetModel||ae("inferx_fallback")||"deepseek-v4-flash",T,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),de=await ge.next();return{iterator:ge,firstResult:de}}else if(y==="SenseNova"){let ge=(await ce("SenseNova"))(E,targetModel||ae("sensenova_fallback")||"sensenova-6.8-flash-lite",T,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),de=await ge.next();return{iterator:ge,firstResult:de}}else if(y==="AIHubMix"){let ge=(await ce("AIHubMix"))(E,targetModel||ae("aihubmix_fallback")||"gpt-4o-mini",T,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),de=await ge.next();return{iterator:ge,firstResult:de}}else if(y==="Poolside"){let ge=(await ce("Poolside"))(E,targetModel||ae("poolside_fallback")||"poolside/laguna-s-2.1",T,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),de=await ge.next();return{iterator:ge,firstResult:de}}else if(y==="9router"||y==="9Router"){let ge=(await ce("NineRouter"))(E,targetModel||ae("9router_fallback")||"z-ai/glm-5.3-flash",T,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),de=await ge.next();return{iterator:ge,firstResult:de}}else if(y==="ExpLabs"||y==="ExperientialLabs"){let ge=(await ce("ExpLabs"))(E,targetModel||ae("explabs_fallback")||"deepseek-v4-pro-0813",T,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),de=await ge.next();return{iterator:ge,firstResult:de}}else{let de=(await hs(E).models.generateContentStream({model:s||(yt===Yt?ae("janitor_default"):ae("gemma_janitor_fallback_google")),contents:T,config:{systemInstruction:b,temperature:.7,safetySettings:[{category:Hn.HARM_CATEGORY_HARASSMENT,threshold:Gn.BLOCK_NONE},{category:Hn.HARM_CATEGORY_HATE_SPEECH,threshold:Gn.BLOCK_NONE},{category:Hn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Gn.BLOCK_NONE},{category:Hn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Gn.BLOCK_NONE}],thinkingConfig:{includeThoughts:!1,thinkingLevel:Ye.MINIMAL},serviceTier:"flex"}}))[Symbol.asyncIterator](),$t=await de.next();return{iterator:de,firstResult:$t}}})();if(process.stdout.isTTY){let de=(await Bi())[g]?.name||"",$t=de&&!de.startsWith("flow-")&&!de.startsWith("Session ")?de:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${$t}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${$t}\x07`)}let{iterator:Ct,firstResult:it}=await Promise.race([ze,Qe]);ct=Date.now()-L;let{value:Tn,done:zt}=it;if(!zt&&Tn){let dt=Tn.candidates?.[0]?.content?.parts,ge=dt?Y==="Google"?dt[1]?.text||dt[0]?.text||"":dt.filter(de=>de.text&&!de.thought).map(de=>de.text).join(""):typeof Tn.text=="function"?Tn.text():"";ge&&(ue+=ge),Be=Tn.usageMetadata;for await(let de of{[Symbol.asyncIterator]:()=>Ct}){let $t=de.candidates?.[0]?.content?.parts,ho=$t?Y==="Google"?$t[1]?.text||$t[0]?.text||"":$t.filter(to=>to.text&&!to.thought).map(to=>to.text).join(""):typeof de.text=="function"?de.text():"";ho&&(ue+=ho),Be=de.usageMetadata}}}catch(Qe){throw Qe}if(ue){if(dn=ue,Be){let Qe=Be.totalTokenCount||0,Oe=Be.cachedContentTokenCount||0,S=(Be.candidatesTokenCount||0)+(Y==="Google"&&Be.thoughtsTokenCount||0),L=Pe?ae("nvidia_janitor_fallback"):Y==="DeepSeek"?ae("deepseek_fast_fallback"):Y==="ExpLabs"||Y==="ExperientialLabs"?ae("explabs_fallback")||"deepseek-v4-pro-0813":Y==="OpenRouter"?ae("janitor_open_router"):s||(yt===Yt?ae("janitor_default"):ae("gemma_janitor_fallback_google"));await At("tokens",Qe,Y,L),Oe>0&&await At("cachedTokens",Oe,Y,L),S>0&&await At("candidateTokens",S,Y,L),janitorTtft!==null&&janitorTtft>0&&await At("ttft",janitorTtft,Y,L),Co({provider:Y,model:L,prompt:Be.promptTokenCount||0,cached:Oe,output:S,reasoning:Be.thoughtsTokenCount||0,ttft:janitorTtft})}}else throw new Error("No synthesis generated by Janitor.");h&&(h(),await Lt("background"));let H=eo(dn),_=!1;for(let Qe of H){let Oe=Qe.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(Oe)&&(_=!0);let S={chatId:g,sessionId:g,history:i},L=await Bo(Oe,Qe.args,S);Oe.toLowerCase()==="memory"&&(Qe.args.includes("action='user'")||Qe.args.includes('action="user"'))&&!L.startsWith("ERROR")&&(u&&u(),process.stdout.isTTY&&(process.stdout.write("\x1B]0;Memory Updated\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=Memory Updated\x07")),await new Promise(ze=>setTimeout(ze,3e3)))}if(!_)try{let Qe=Ot(Xn,[]);if(Qe.length>0){let Oe=[];for(let S of Qe)S.score===void 0&&(S.score=.5),S.score*=.99995,S.score<.05&&(S.score=0),S.score=Math.round(S.score*1e5)/1e5,S.score>0&&Oe.push(S);co(Xn,Oe)}}catch{}break}catch(ue){yt++;let Be=new Date().toLocaleString(),Pe=ue instanceof Error?(()=>{try{return JSON.parse(JSON.parse(ue.message).error.message).error.message}catch{return String(ue)}})():String(ue);await new Promise(_=>setTimeout(_,1e3));let Y=W.join(wn,"janitor");if(Ae.existsSync(Y)||Ae.mkdirSync(Y,{recursive:!0}),Ae.appendFileSync(W.join(Y,"error.log"),`ERROR [Attempt ${yt}/${Yt+1}] [${Be}]: ${Pe}
604
+ [AGENT (current turn)]: ${ht}`;T.push({role:"user",parts:[{text:Vt}]});let cn=await $i("NVIDIA"),Pn=(await Eo()).quotas?.providerTiers?.NVIDIA==="Free",dn="",yt=0,Yt=D?12:-1;for(;yt<=Yt;)try{if(!await Ms("background",e))return;let ue="",Be=null,Pe=!1,V=y;try{let Qe=new Promise((dt,ge)=>setTimeout(()=>ge(new Error("JANITOR_TIMEOUT")),1e4)),Oe=y==="Google"&&yt>=0&&yt<6&&cn&&Pn,S=y==="DeepSeek"&&yt<4&&cn&&Pn;Pe=Oe||S,V=Pe?"NVIDIA":y;let $=Date.now(),ct=null,ze=(async()=>{if(y==="OpenRouter"){let dt=ae("janitor_open_router"),de=(await ce("OpenRouter"))(E,dt,T,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),$t=await de.next();return{iterator:de,firstResult:$t}}else if(y==="DeepSeek"&&!Pe){let ge=(await ce("DeepSeek"))(E,ae("deepseek_fast_fallback"),T,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),de=await ge.next();return{iterator:ge,firstResult:de}}else if(y==="Mistral"&&!Pe){let ge=(await ce("Mistral"))(E,ae("mistral_janitor_fallback"),T,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),de=await ge.next();return{iterator:ge,firstResult:de}}else if(y==="NVIDIA"||Pe){let ge=(await ce("NVIDIA"))(Pe?cn:E,ae("nvidia_janitor_fallback"),T,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),de=await ge.next();return{iterator:ge,firstResult:de}}else if(y==="InferX"){let ge=(await ce("InferX"))(E,targetModel||ae("inferx_fallback")||"deepseek-v4-flash",T,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),de=await ge.next();return{iterator:ge,firstResult:de}}else if(y==="SenseNova"){let ge=(await ce("SenseNova"))(E,targetModel||ae("sensenova_fallback")||"sensenova-6.8-flash-lite",T,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),de=await ge.next();return{iterator:ge,firstResult:de}}else if(y==="AIHubMix"){let ge=(await ce("AIHubMix"))(E,targetModel||ae("aihubmix_fallback")||"gpt-4o-mini",T,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),de=await ge.next();return{iterator:ge,firstResult:de}}else if(y==="Poolside"){let ge=(await ce("Poolside"))(E,targetModel||ae("poolside_fallback")||"poolside/laguna-s-2.1",T,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),de=await ge.next();return{iterator:ge,firstResult:de}}else if(y==="9router"||y==="9Router"){let ge=(await ce("NineRouter"))(E,targetModel||ae("9router_fallback")||"z-ai/glm-5.3-flash",T,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),de=await ge.next();return{iterator:ge,firstResult:de}}else if(y==="ExpLabs"||y==="ExperientialLabs"){let ge=(await ce("ExpLabs"))(E,targetModel||ae("explabs_fallback")||"deepseek-v4-pro-0813",T,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),de=await ge.next();return{iterator:ge,firstResult:de}}else{let de=(await ys(E).models.generateContentStream({model:s||(yt===Yt?ae("janitor_default"):ae("gemma_janitor_fallback_google")),contents:T,config:{systemInstruction:b,temperature:.7,safetySettings:[{category:Hn.HARM_CATEGORY_HARASSMENT,threshold:Gn.BLOCK_NONE},{category:Hn.HARM_CATEGORY_HATE_SPEECH,threshold:Gn.BLOCK_NONE},{category:Hn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Gn.BLOCK_NONE},{category:Hn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Gn.BLOCK_NONE}],thinkingConfig:{includeThoughts:!1,thinkingLevel:Ye.MINIMAL},serviceTier:"flex"}}))[Symbol.asyncIterator](),$t=await de.next();return{iterator:de,firstResult:$t}}})();if(process.stdout.isTTY){let de=(await Ui())[g]?.name||"",$t=de&&!de.startsWith("flow-")&&!de.startsWith("Session ")?de:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${$t}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${$t}\x07`)}let{iterator:Ct,firstResult:it}=await Promise.race([ze,Qe]);ct=Date.now()-$;let{value:Tn,done:zt}=it;if(!zt&&Tn){let dt=Tn.candidates?.[0]?.content?.parts,ge=dt?V==="Google"?dt[1]?.text||dt[0]?.text||"":dt.filter(de=>de.text&&!de.thought).map(de=>de.text).join(""):typeof Tn.text=="function"?Tn.text():"";ge&&(ue+=ge),Be=Tn.usageMetadata;for await(let de of{[Symbol.asyncIterator]:()=>Ct}){let $t=de.candidates?.[0]?.content?.parts,ho=$t?V==="Google"?$t[1]?.text||$t[0]?.text||"":$t.filter(to=>to.text&&!to.thought).map(to=>to.text).join(""):typeof de.text=="function"?de.text():"";ho&&(ue+=ho),Be=de.usageMetadata}}}catch(Qe){throw Qe}if(ue){if(dn=ue,Be){let Qe=Be.totalTokenCount||0,Oe=Be.cachedContentTokenCount||0,S=(Be.candidatesTokenCount||0)+(V==="Google"&&Be.thoughtsTokenCount||0),$=Pe?ae("nvidia_janitor_fallback"):V==="DeepSeek"?ae("deepseek_fast_fallback"):V==="ExpLabs"||V==="ExperientialLabs"?ae("explabs_fallback")||"deepseek-v4-pro-0813":V==="OpenRouter"?ae("janitor_open_router"):s||(yt===Yt?ae("janitor_default"):ae("gemma_janitor_fallback_google"));await At("tokens",Qe,V,$),Oe>0&&await At("cachedTokens",Oe,V,$),S>0&&await At("candidateTokens",S,V,$),janitorTtft!==null&&janitorTtft>0&&await At("ttft",janitorTtft,V,$),Co({provider:V,model:$,prompt:Be.promptTokenCount||0,cached:Oe,output:S,reasoning:Be.thoughtsTokenCount||0,ttft:janitorTtft})}}else throw new Error("No synthesis generated by Janitor.");h&&(h(),await Lt("background"));let G=jn(dn),_=!1;for(let Qe of G){let Oe=Qe.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(Oe)&&(_=!0);let S={chatId:g,sessionId:g,history:i},$=await Bo(Oe,Qe.args,S);Oe.toLowerCase()==="memory"&&(Qe.args.includes("action='user'")||Qe.args.includes('action="user"'))&&!$.startsWith("ERROR")&&(u&&u(),process.stdout.isTTY&&(process.stdout.write("\x1B]0;Memory Updated\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=Memory Updated\x07")),await new Promise(ze=>setTimeout(ze,3e3)))}if(!_)try{let Qe=Ot(Jn,[]);if(Qe.length>0){let Oe=[];for(let S of Qe)S.score===void 0&&(S.score=.5),S.score*=.99995,S.score<.05&&(S.score=0),S.score=Math.round(S.score*1e5)/1e5,S.score>0&&Oe.push(S);co(Jn,Oe)}}catch{}break}catch(ue){yt++;let Be=new Date().toLocaleString(),Pe=ue instanceof Error?(()=>{try{return JSON.parse(JSON.parse(ue.message).error.message).error.message}catch{return String(ue)}})():String(ue);await new Promise(_=>setTimeout(_,1e3));let V=U.join(wn,"janitor");if(Ae.existsSync(V)||Ae.mkdirSync(V,{recursive:!0}),Ae.appendFileSync(U.join(V,"error.log"),`ERROR [Attempt ${yt}/${Yt+1}] [${Be}]: ${Pe}
605
605
 
606
- `),yt>Yt)break;let H=Math.min(750*Math.pow(2,yt-1),5e3);await new Promise(_=>setTimeout(_,H))}if(yt){let ue=W.join(wn,"janitor");Ae.appendFileSync(W.join(ue,"error.log"),`-----------------------------------------------------------------------------
606
+ `),yt>Yt)break;let G=Math.min(750*Math.pow(2,yt-1),5e3);await new Promise(_=>setTimeout(_,G))}if(yt){let ue=U.join(wn,"janitor");Ae.appendFileSync(U.join(ue,"error.log"),`-----------------------------------------------------------------------------
607
607
 
608
- `)}if(process.stdout.isTTY)try{let Pe=(await Bi())[g]?.name||"",Y=Pe&&!Pe.startsWith("flow-")&&!Pe.startsWith("Session ")?Pe:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${Y}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${Y}\x07`)}catch{process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")}},ys=e=>{if(!e||typeof e!="string")return e;let n=e.split(""),t=!1,i=!1,o=0;for(;o<n.length;){if(n[o]==="`"&&n[o+1]==="`"&&n[o+2]==="`"){t?(n[o]=" ",n[o+1]=" ",n[o+2]=" ",t=!1):(n[o]=" ",n[o+1]=" ",n[o+2]=" ",t=!0),o+=3;continue}if(t){n[o]!==`
609
- `&&n[o]!=="\r"&&(n[o]=" "),o++;continue}if(n[o]==="`")if(i){i=!1,n[o]=" ",o++;continue}else{let r=!1;for(let c=o+1;c<n.length&&!(n[c]===`
610
- `||n[c]==="\r");c++)if(n[c]==="`"&&(c===0||n[c-1]!=="\\")){r=!0;break}if(r){i=!0,n[o]=" ",o++;continue}}if(i){n[o]===`
611
- `||n[o]==="\r"?i=!1:n[o]=" ",o++;continue}o++}return n.join("")},yl=e=>{let n=Kt(e),t=ys(n);Go.lastIndex=0;let i;for(;(i=Go.exec(t))!==null;){let o=i.index+i[0].length-1,r=0,c=null,a=!1,u=!1;for(let h=o;h<t.length;h++){let x=t[h];if(!c&&(x==='"'||x==="'"||x==="`")?(c=x,a=!1):c&&x===c&&!a&&(c=null),!c&&(x==="("?r++:x===")"&&r--,r===0)){let p=h+1;for(;p<t.length&&/\s/.test(t[p]);)p++;if(p<t.length&&t[p]==="]"){u=!0,Go.lastIndex=p+1;break}}x==="\\"?a=!a:a=!1}if(!u)return{inside:!0,toolName:i[1],startIndex:i.index,args:n.substring(i.index+i[0].length)}}return{inside:!1}},ra=(e,n=!0)=>{let t=Go;t.lastIndex=0;let i="",o=0,r;for(;(r=t.exec(e))!==null;){let c=e.substring(o,r.index);i+=n&&o===0?Kt(c):c;let a=r.index+r[0].length-1,u=0,h=null,x=-1;for(let p=a;p<e.length;p++){let f=e[p];if(h){if(f===h){let s=0;for(let g=p-1;g>=0&&e[g]==="\\";g--)s++;s%2===0&&(h=null)}}else if(f==='"'||f==="'"||f==="`")h=f;else if(f==="(")u++;else if(f===")"&&(u--,u===0)){let s=p+1;for(;s<e.length&&/\s/.test(e[s]);)s++;if(s<e.length&&e[s]==="]"){x=s;break}}}if(x!==-1)i+="[tool:functions."+r[1]+"()]",o=x+1,t.lastIndex=o;else{i+="[tool:functions."+r[1]+"(",o=e.length;break}}return o<e.length&&(i+=n&&o===0?Kt(e.substring(o)):e.substring(o)),i},xl=(e,n,t)=>{let i=Go;i.lastIndex=0;let o="",r=0,c;for(;(c=i.exec(e))!==null;){let a=e.substring(r,c.index);o+=a.replace(n,t);let u=c.index+c[0].length-1,h=0,x=null,p=-1;for(let f=u;f<e.length;f++){let s=e[f];if(x){if(s===x){let g=0;for(let k=f-1;k>=0&&e[k]==="\\";k--)g++;g%2===0&&(x=null)}}else if(s==='"'||s==="'"||s==="`")x=s;else if(s==="(")h++;else if(s===")"&&(h--,h===0)){let g=f+1;for(;g<e.length&&/\s/.test(e[g]);)g++;if(g<e.length&&e[g]==="]"){p=g;break}}}if(p!==-1)o+=e.substring(c.index,p+1),r=p+1,i.lastIndex=r;else{o+=e.substring(c.index),r=e.length;break}}return r<e.length&&(o+=e.substring(r).replace(n,t)),o},na=e=>ra(e,!0),bl=e=>{if(!e)return e;let n={patchfile:"PatchFile",writefile:"WriteFile",readfile:"ReadFile",viewfile:"ReadFile",run:"Run",execcommand:"Run",searchkeyword:"SearchKeyword",codesearch:"CodeSearch",code_search:"CodeSearch",websearch:"WebSearch",webscrape:"WebScrape",readfolder:"ReadFolder",writepdf:"WritePDF",writedoc:"WriteDoc",writedocx:"WriteDoc",filemap:"FileMap",generateimage:"GenerateImage",todo:"Todo",goal:"Goal",askuser:"AskUser",ask:"AskUser"},t=o=>o.split("_").map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join("");Zr.lastIndex=0;let i=e.replace(Zr,(o,r,c)=>{let a="";try{let x=JSON.parse(c.trim());x&&typeof x=="object"&&(a=Object.entries(x).map(([f,s])=>{let g=typeof s=="string"?s:JSON.stringify(s);return`${f}=${JSON.stringify(g)}`}).join(", "))}catch{let p=[],f=ul;f.lastIndex=0;let s;for(;(s=f.exec(c))!==null;){let g=s[1],k=s[2]!==void 0?s[2]:s[0].split(":").slice(1).join(":").trim();p.push(`${g}=${JSON.stringify(k)}`)}p.length>0?a=p.join(", "):a=c.trim()}let u=r.toLowerCase().replace(/_/g,"");return`[tool:functions.${n[u]||t(r)}(${a})]`});return ea.lastIndex=0,ta.lastIndex=0,i=i.replace(ea,""),i=i.replace(ta,""),i},eo=e=>{if(!e)return[];let n=bl(e),t=Kt(n),i=[],o=ys(t),r=sl;r.lastIndex=0;let c;for(;(c=r.exec(o))!==null;){let a=c[1],u=c.index+c[0].length-1,h=0,x=null,p=-1,f=-1;for(let s=u;s<o.length;s++){let g=o[s];if(x){if(g===x){let k=0;for(let he=s-1;he>=0&&o[he]==="\\";he--)k++;k%2===0&&(x=null)}}else{if(s>u&&(o.substring(s).startsWith("[action:")||o.substring(s).startsWith("[tool:")))break;if(g==='"'||g==="'"||g==="`")x=g;else if(g==="(")h++;else if(g===")"&&(h--,h===0)){f=s;let k=s+1;for(;k<o.length&&/\s/.test(o[k]);)k++;if(k<o.length&&o[k]==="]"){p=k;break}}}}if(p!==-1){let s=t.substring(u+1,f),g=t.substring(c.index,p+1);i.push({fullMatch:g,toolName:a.trim(),args:s.trim()}),r.lastIndex=p+1}}return i},oa=e=>{if(!e)return null;let n=Kt(e),t=[],i=/\[\s*(?:tool:(?:functions\.)?|action:(?:functions\.)?|action:)([a-zA-Z0-9_]+)\s*\(/gi,o=[],r;for(;(r=i.exec(n))!==null;)o.push({toolName:r[1],index:r.index,parenIndex:r.index+r[0].length-1});for(let f=0;f<o.length;f++){let s=o[f],g=f+1<o.length?o[f+1].index:n.length,k=n.substring(s.index,g),he=k.indexOf("("),y=he!==-1?k.substring(he+1):"",E=0,D=null,K=!1;for(let O=0;O<y.length;O++){let T=y[O];if(D){if(T===D){let Se=0;for(let Ce=O-1;Ce>=0&&y[Ce]==="\\";Ce--)Se++;Se%2===0&&(D=null)}}else if(T==='"'||T==="'"||T==="`")D=T;else if(T==="(")E++;else if(T===")")if(E>0)E--;else{let Se=O+1;for(;Se<y.length&&/\s/.test(y[Se]);)Se++;if(Se<y.length&&y[Se]==="]"){K=!0;break}}}if(!K){let O=k.trim(),T="";D?T=`Unclosed quote string (${D}) inside arguments`:O.endsWith("]")?T=`Missing closing ')' before ']' (e.g. found "...]")`:O.endsWith(")")?T=`Missing closing ']' after ')' (e.g. found "...)" instead of "...)]")`:!O.includes(")")&&!O.includes("]")?T="Missing closing delimiter ')]'":T="Malformed or unclosed call syntax (missing ')]')",t.push(`\u2022 [action:${s.toolName}(...)]: ${T}. Expected: [action:${s.toolName}(arg1="...", arg2="...")]`)}}let c=/(?:^|[^\w\[])(?:tool|action):(?:functions\.)?([a-zA-Z0-9_]+)\s*\(/gi,a;for(;(a=c.exec(n))!==null;){let f=a[1],s=a.index+(a[0].indexOf(":")-(a[0].startsWith("action")||a[0].startsWith("tool")?0:1));(s>0?n[s-1]:"")!=="["&&gi(f)&&t.push(`\u2022 action:${f}(...): Missing opening bracket '['. Expected: [action:${f}(...)]`)}let u=/\[\s*(?:functions\.)?([a-zA-Z0-9_]+)\s*\(/g,h;for(;(h=u.exec(n))!==null;){let f=h[1];f!=="action"&&f!=="tool"&&gi(f)&&t.push(`\u2022 [${f}(...)]: Missing 'action:' prefix. Expected: [action:${f}(...)]`)}let x=/\[\s*(?:tool|action)\s*:\s*(?:functions\.)?([a-zA-Z0-9_]+)(?!\s*\()/gi,p;for(;(p=x.exec(n))!==null;){let f=p[1];gi(f)&&t.push(`\u2022 [action:${f}...]: Missing opening '(' for tool arguments. Expected: [action:${f}(...)]`)}return t.length>0?t.join(`
612
- `):null},$d=(e,n={})=>{if(!e)return null;if(Ho=n,ps=new ia({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(...i)=>{try{let o=await t(...i);return typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),o}catch(o){throw typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),o}}}},aa=e=>{if(!e)return{serviceTier:void 0,cleanModel:e};let n=e.toLowerCase();return n.endsWith(":flex")?{serviceTier:"flex",cleanModel:e.slice(0,-5)}:n.endsWith(":priority")?{serviceTier:"priority",cleanModel:e.slice(0,-9)}:{serviceTier:void 0,cleanModel:e}},yi=async(e,n,t,i,o="Fast",r=.75,c="agent")=>ml(async()=>{let{aiProvider:a="Google",apiKey:u,mode:h}=e,x="",p=null,f=typeof t=="string"?[{role:"user",parts:[{text:t}]}]:t,s=new AbortController,g=s.signal,k=setInterval(()=>{Et&&(s.abort(),clearInterval(k))},100),he=Date.now(),y=null;try{let E;if(a==="Ollama")E=(await ce("Ollama"))(u,n,f,i,o,h,lt(n),g,r,e.systemSettings?.ollamaEndpoint||"Cloud");else if(a==="OpenRouter")E=(await ce("OpenRouter"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="DeepSeek")E=(await ce("DeepSeek"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="Mistral")E=(await ce("Mistral"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="NVIDIA")E=(await ce("NVIDIA"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="InferX")E=(await ce("InferX"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="SenseNova")E=(await ce("SenseNova"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="AIHubMix")E=(await ce("AIHubMix"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="Poolside")E=(await ce("Poolside"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="9router"||a==="9Router")E=(await ce("NineRouter"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="ExpLabs"||a==="ExperientialLabs")E=(await ce("ExpLabs"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="Infron"||a==="infron")E=(await ce("Infron"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="TokenHarbor"||a==="Token Harbor"||a==="tokenharbor"||a==="token_harbor"||a==="thk")E=(await ce("TokenHarbor"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="APInex"||a==="apinex"||a==="apx")E=(await ce("APInex"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="xKiro"||a==="xkiro"||a==="kiro")E=(await ce("xKiro"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="c_openai"||a==="Custom (OpenAI)"){let D=e.systemSettings?.customOpenAIBaseUrl||"";try{D=await Oi("c_openai")||D}catch{}E=(await ce("c_openai"))(u,n,f,i,o,h,lt(n),g,r,D)}else{let D=hs(u),{serviceTier:K,cleanModel:O}=aa(n),T={systemInstruction:i,temperature:r,thinkingConfig:(()=>{let Ce=(n||"").toLowerCase(),Me=Ce.includes("gemma-4")||Ce.startsWith("gemma"),Je=Ce.includes("gemini-3");if(Me||Je)return Me?o.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:Ye.MINIMAL}:{includeThoughts:!0,thinkingLevel:Ye.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:Ce.includes("pro")?Ye.LOW:Ye.MINIMAL,Low:Ye.LOW,Medium:Ye.MEDIUM,Standard:Ye.MEDIUM,High:Ye.HIGH,xHigh:Ye.HIGH}[o]||Ye.MEDIUM};{let G={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[o]||2048;return G===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:G}}})()};K&&(T.serviceTier=K),E=await D.models.generateContentStream({model:O,contents:f,config:T},{signal:g})}for await(let D of E){if(Et)throw new Error("Subagent task was cancelled.");if(e?.taskId&&typeof en<"u"){let T=en.find(Se=>Se.id===e.taskId);if(T&&T.status==="cancelled")throw new Error("Subagent task was cancelled.")}y===null&&(D.candidates?.[0]?.content?.parts||D.text)&&(y=Date.now()-he);let K="";if(D.candidates?.[0]?.content?.parts)for(let T of D.candidates[0].content.parts)T.text&&!T.thought&&(x+=T.text,K+=T.text);let O=K?Ni(K):0;e&&typeof e.onTokenChunk=="function"&&e.onTokenChunk(K,O),D.usageMetadata&&(p=D.usageMetadata)}}finally{clearInterval(k)}if(p){let E=p.totalTokenCount||0,D=p.cachedContentTokenCount||0,K=(p.candidatesTokenCount||0)+(a==="Google"&&p.thoughtsTokenCount||0);await At("tokens",E,a,n),D>0&&await At("cachedTokens",D,a,n),K>0&&await At("candidateTokens",K,a,n),y!==null&&y>0&&await At("ttft",y,a,n),Co({provider:a,model:n,prompt:p.promptTokenCount||0,cached:D,output:K,reasoning:p.thoughtsTokenCount||0,ttft:y}),e&&typeof e.onUsage=="function"&&e.onUsage({totalTokenCount:E,cachedContentTokenCount:D,candidatesTokenCount:K})}return await Lt("agent",a),{text:x,usageMetadata:p}}),wl=async(e,n,t=null)=>{t=t||Ot(Qo,{});try{let{aiProvider:i="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 c=`You are a silent background process for the FluxFlow CLI Agent.
608
+ `)}if(process.stdout.isTTY)try{let Pe=(await Ui())[g]?.name||"",V=Pe&&!Pe.startsWith("flow-")&&!Pe.startsWith("Session ")?Pe:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${V}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${V}\x07`)}catch{process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")}},yi=e=>{if(!e||typeof e!="string")return e;let n=e.split(""),t=!1,i=!1,o=0;for(;o<n.length;){if(n[o]==="`"&&n[o+1]==="`"&&n[o+2]==="`"){t?(n[o]=" ",n[o+1]=" ",n[o+2]=" ",t=!1):(n[o]=" ",n[o+1]=" ",n[o+2]=" ",t=!0),o+=3;continue}if(t){n[o]!==`
609
+ `&&n[o]!=="\r"&&(n[o]=" "),o++;continue}if(n[o]==="`")if(i){i=!1,n[o]=" ",o++;continue}else{i=!0,n[o]=" ",o++;continue}if(i){n[o]===`
610
+ `||n[o]==="\r"?i=!1:n[o]=" ",o++;continue}o++}return n.join("")},xl=e=>{let n=Bt(e),t=yi(n);Go.lastIndex=0;let i;for(;(i=Go.exec(t))!==null;){let o=i.index+i[0].length-1,r=0,d=null,a=!1,u=!1;for(let h=o;h<t.length;h++){let x=t[h];if(!d&&(x==='"'||x==="'"||x==="`")?(d=x,a=!1):d&&x===d&&!a&&(d=null),!d&&(x==="("?r++:x===")"&&r--,r===0)){let p=h+1;for(;p<t.length&&/\s/.test(t[p]);)p++;if(p<t.length&&t[p]==="]"){u=!0,Go.lastIndex=p+1;break}}x==="\\"?a=!a:a=!1}if(!u)return{inside:!0,toolName:i[1],startIndex:i.index,args:n.substring(i.index+i[0].length)}}return{inside:!1}},ra=(e,n=!0)=>{let t=Go;t.lastIndex=0;let i="",o=0,r;for(;(r=t.exec(e))!==null;){let d=e.substring(o,r.index);i+=n&&o===0?Bt(d):d;let a=r.index+r[0].length-1,u=0,h=null,x=-1;for(let p=a;p<e.length;p++){let f=e[p];if(h){if(f===h){let s=0;for(let g=p-1;g>=0&&e[g]==="\\";g--)s++;s%2===0&&(h=null)}}else if(f==='"'||f==="'"||f==="`")h=f;else if(f==="(")u++;else if(f===")"&&(u--,u===0)){let s=p+1;for(;s<e.length&&/\s/.test(e[s]);)s++;if(s<e.length&&e[s]==="]"){x=s;break}}}if(x!==-1)i+="[tool:functions."+r[1]+"()]",o=x+1,t.lastIndex=o;else{i+="[tool:functions."+r[1]+"(",o=e.length;break}}return o<e.length&&(i+=n&&o===0?Bt(e.substring(o)):e.substring(o)),i},bl=(e,n,t)=>{let i=Go;i.lastIndex=0;let o="",r=0,d;for(;(d=i.exec(e))!==null;){let a=e.substring(r,d.index);o+=a.replace(n,t);let u=d.index+d[0].length-1,h=0,x=null,p=-1;for(let f=u;f<e.length;f++){let s=e[f];if(x){if(s===x){let g=0;for(let k=f-1;k>=0&&e[k]==="\\";k--)g++;g%2===0&&(x=null)}}else if(s==='"'||s==="'"||s==="`")x=s;else if(s==="(")h++;else if(s===")"&&(h--,h===0)){let g=f+1;for(;g<e.length&&/\s/.test(e[g]);)g++;if(g<e.length&&e[g]==="]"){p=g;break}}}if(p!==-1)o+=e.substring(d.index,p+1),r=p+1,i.lastIndex=r;else{o+=e.substring(d.index),r=e.length;break}}return r<e.length&&(o+=e.substring(r).replace(n,t)),o},na=e=>ra(e,!0),wl=e=>{if(!e)return e;let n={patchfile:"PatchFile",writefile:"WriteFile",readfile:"ReadFile",viewfile:"ReadFile",run:"Run",execcommand:"Run",searchkeyword:"SearchKeyword",codesearch:"CodeSearch",code_search:"CodeSearch",websearch:"WebSearch",webscrape:"WebScrape",readfolder:"ReadFolder",writepdf:"WritePDF",writedoc:"WriteDoc",writedocx:"WriteDoc",filemap:"FileMap",generateimage:"GenerateImage",todo:"Todo",goal:"Goal",askuser:"AskUser",ask:"AskUser"},t=o=>o.split("_").map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join("");Zr.lastIndex=0;let i=e.replace(Zr,(o,r,d)=>{let a="";try{let x=JSON.parse(d.trim());x&&typeof x=="object"&&(a=Object.entries(x).map(([f,s])=>{let g=typeof s=="string"?s:JSON.stringify(s);return`${f}=${JSON.stringify(g)}`}).join(", "))}catch{let p=[],f=gl;f.lastIndex=0;let s;for(;(s=f.exec(d))!==null;){let g=s[1],k=s[2]!==void 0?s[2]:s[0].split(":").slice(1).join(":").trim();p.push(`${g}=${JSON.stringify(k)}`)}p.length>0?a=p.join(", "):a=d.trim()}let u=r.toLowerCase().replace(/_/g,"");return`[tool:functions.${n[u]||t(r)}(${a})]`});return ea.lastIndex=0,ta.lastIndex=0,i=i.replace(ea,""),i=i.replace(ta,""),i},jn=e=>{if(!e)return[];let n=wl(e),t=Bt(n),i=[],o=yi(t),r=rl;r.lastIndex=0;let d;for(;(d=r.exec(o))!==null;){let a=d[1],u=d.index+d[0].length-1,h=0,x=null,p=-1,f=-1;for(let s=u;s<o.length;s++){let g=o[s];if(x){if(g===x){let k=0;for(let he=s-1;he>=0&&o[he]==="\\";he--)k++;k%2===0&&(x=null)}}else{if(s>u&&(o.substring(s).startsWith("[action:")||o.substring(s).startsWith("[tool:")))break;if(g==='"'||g==="'"||g==="`")x=g;else if(g==="(")h++;else if(g===")"&&(h--,h===0)){f=s;let k=s+1;for(;k<o.length&&/\s/.test(o[k]);)k++;if(k<o.length&&o[k]==="]"){p=k;break}}}}if(p!==-1){let s=t.substring(u+1,f),g=t.substring(d.index,p+1);i.push({fullMatch:g,toolName:a.trim(),args:s.trim()}),r.lastIndex=p+1}}return i},oa=e=>{if(!e)return null;let n=Bt(e),t=[],i=/\[\s*(?:tool:(?:functions\.)?|action:(?:functions\.)?|action:)([a-zA-Z0-9_]+)\s*\(/gi,o=[],r;for(;(r=i.exec(n))!==null;)o.push({toolName:r[1],index:r.index,parenIndex:r.index+r[0].length-1});for(let f=0;f<o.length;f++){let s=o[f],g=f+1<o.length?o[f+1].index:n.length,k=n.substring(s.index,g),he=k.indexOf("("),y=he!==-1?k.substring(he+1):"",E=0,D=null,K=!1;for(let L=0;L<y.length;L++){let T=y[L];if(D){if(T===D){let Se=0;for(let Ce=L-1;Ce>=0&&y[Ce]==="\\";Ce--)Se++;Se%2===0&&(D=null)}}else if(T==='"'||T==="'"||T==="`")D=T;else if(T==="(")E++;else if(T===")")if(E>0)E--;else{let Se=L+1;for(;Se<y.length&&/\s/.test(y[Se]);)Se++;if(Se<y.length&&y[Se]==="]"){K=!0;break}}}if(!K){let L=k.trim(),T="";D?T=`Unclosed quote string (${D}) inside arguments`:L.endsWith("]")?T=`Missing closing ')' before ']' (e.g. found "...]")`:L.endsWith(")")?T=`Missing closing ']' after ')' (e.g. found "...)" instead of "...)]")`:!L.includes(")")&&!L.includes("]")?T="Missing closing delimiter ')]'":T="Malformed or unclosed call syntax (missing ')]')",t.push(`\u2022 [action:${s.toolName}(...)]: ${T}. Expected: [action:${s.toolName}(arg1="...", arg2="...")]`)}}let d=/(?:^|[^\w\[])(?:tool|action):(?:functions\.)?([a-zA-Z0-9_]+)\s*\(/gi,a;for(;(a=d.exec(n))!==null;){let f=a[1],s=a.index+(a[0].indexOf(":")-(a[0].startsWith("action")||a[0].startsWith("tool")?0:1));(s>0?n[s-1]:"")!=="["&&gi(f)&&t.push(`\u2022 action:${f}(...): Missing opening bracket '['. Expected: [action:${f}(...)]`)}let u=/\[\s*(?:functions\.)?([a-zA-Z0-9_]+)\s*\(/g,h;for(;(h=u.exec(n))!==null;){let f=h[1];f!=="action"&&f!=="tool"&&gi(f)&&t.push(`\u2022 [${f}(...)]: Missing 'action:' prefix. Expected: [action:${f}(...)]`)}let x=/\[\s*(?:tool|action)\s*:\s*(?:functions\.)?([a-zA-Z0-9_]+)(?!\s*\()/gi,p;for(;(p=x.exec(n))!==null;){let f=p[1];gi(f)&&t.push(`\u2022 [action:${f}...]: Missing opening '(' for tool arguments. Expected: [action:${f}(...)]`)}return t.length>0?t.join(`
611
+ `):null},Nd=(e,n={})=>{if(!e)return null;if(Ho=n,hs=new ia({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(...i)=>{try{let o=await t(...i);return typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),o}catch(o){throw typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),o}}}},aa=e=>{if(!e)return{serviceTier:void 0,cleanModel:e};let n=e.toLowerCase();return n.endsWith(":flex")?{serviceTier:"flex",cleanModel:e.slice(0,-5)}:n.endsWith(":priority")?{serviceTier:"priority",cleanModel:e.slice(0,-9)}:{serviceTier:void 0,cleanModel:e}},xi=async(e,n,t,i,o="Fast",r=.75,d="agent")=>pl(async()=>{let{aiProvider:a="Google",apiKey:u,mode:h}=e,x="",p=null,f=typeof t=="string"?[{role:"user",parts:[{text:t}]}]:t,s=new AbortController,g=s.signal,k=setInterval(()=>{Et&&(s.abort(),clearInterval(k))},100),he=Date.now(),y=null;try{let E;if(a==="Ollama")E=(await ce("Ollama"))(u,n,f,i,o,h,lt(n),g,r,e.systemSettings?.ollamaEndpoint||"Cloud");else if(a==="OpenRouter")E=(await ce("OpenRouter"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="DeepSeek")E=(await ce("DeepSeek"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="Mistral")E=(await ce("Mistral"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="NVIDIA")E=(await ce("NVIDIA"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="InferX")E=(await ce("InferX"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="SenseNova")E=(await ce("SenseNova"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="AIHubMix")E=(await ce("AIHubMix"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="Poolside")E=(await ce("Poolside"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="9router"||a==="9Router")E=(await ce("NineRouter"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="ExpLabs"||a==="ExperientialLabs")E=(await ce("ExpLabs"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="Infron"||a==="infron")E=(await ce("Infron"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="TokenHarbor"||a==="Token Harbor"||a==="tokenharbor"||a==="token_harbor"||a==="thk")E=(await ce("TokenHarbor"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="APInex"||a==="apinex"||a==="apx")E=(await ce("APInex"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="xKiro"||a==="xkiro"||a==="kiro")E=(await ce("xKiro"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="c_openai"||a==="Custom (OpenAI)"){let D=e.systemSettings?.customOpenAIBaseUrl||"";try{D=await Li("c_openai")||D}catch{}E=(await ce("c_openai"))(u,n,f,i,o,h,lt(n),g,r,D)}else{let D=ys(u),{serviceTier:K,cleanModel:L}=aa(n),T={systemInstruction:i,temperature:r,thinkingConfig:(()=>{let Ce=(n||"").toLowerCase(),Me=Ce.includes("gemma-4")||Ce.startsWith("gemma"),Je=Ce.includes("gemini-3");if(Me||Je)return Me?o.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:Ye.MINIMAL}:{includeThoughts:!0,thinkingLevel:Ye.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:Ce.includes("pro")?Ye.LOW:Ye.MINIMAL,Low:Ye.LOW,Medium:Ye.MEDIUM,Standard:Ye.MEDIUM,High:Ye.HIGH,xHigh:Ye.HIGH}[o]||Ye.MEDIUM};{let W={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[o]||2048;return W===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:W}}})()};K&&(T.serviceTier=K),E=await D.models.generateContentStream({model:L,contents:f,config:T},{signal:g})}for await(let D of E){if(Et)throw new Error("Subagent task was cancelled.");if(e?.taskId&&typeof en<"u"){let T=en.find(Se=>Se.id===e.taskId);if(T&&T.status==="cancelled")throw new Error("Subagent task was cancelled.")}y===null&&(D.candidates?.[0]?.content?.parts||D.text)&&(y=Date.now()-he);let K="";if(D.candidates?.[0]?.content?.parts)for(let T of D.candidates[0].content.parts)T.text&&!T.thought&&(x+=T.text,K+=T.text);let L=K?Di(K):0;e&&typeof e.onTokenChunk=="function"&&e.onTokenChunk(K,L),D.usageMetadata&&(p=D.usageMetadata)}}finally{clearInterval(k)}if(p){let E=p.totalTokenCount||0,D=p.cachedContentTokenCount||0,K=(p.candidatesTokenCount||0)+(a==="Google"&&p.thoughtsTokenCount||0);await At("tokens",E,a,n),D>0&&await At("cachedTokens",D,a,n),K>0&&await At("candidateTokens",K,a,n),y!==null&&y>0&&await At("ttft",y,a,n),Co({provider:a,model:n,prompt:p.promptTokenCount||0,cached:D,output:K,reasoning:p.thoughtsTokenCount||0,ttft:y}),e&&typeof e.onUsage=="function"&&e.onUsage({totalTokenCount:E,cachedContentTokenCount:D,candidatesTokenCount:K})}return await Lt("agent",a),{text:x,usageMetadata:p}}),Sl=async(e,n,t=null)=>{t=t||Ot(Qo,{});try{let{aiProvider:i="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 d=`You are a silent background process for the FluxFlow CLI Agent.
613
612
  Your task is to summarize or merge temporary context memories from one or more past conversation sessions.
614
613
  For each Chat ID provided, you must output a tool call to save the consolidated summary.
615
614
 
@@ -624,18 +623,18 @@ Guidelines:
624
623
 
625
624
  Chats to process:
626
625
 
627
- `,a=Ot(Mi,{});for(let f of r){let g=t[f].map(he=>`- ${he}`).join(`
628
- `),k=a[f];c+=`[Chat ID: ${f}]
629
- `,k?(c+=`- Existing Summary: "${k}"
630
- `,c+=`
626
+ `,a=Ot(Pi,{});for(let f of r){let g=t[f].map(he=>`- ${he}`).join(`
627
+ `),k=a[f];d+=`[Chat ID: ${f}]
628
+ `,k?(d+=`- Existing Summary: "${k}"
629
+ `,d+=`
631
630
  -- New Memories to integrate:
632
631
  ${g}
633
632
 
634
- `):c+=`-- Individual Memories:
633
+ `):d+=`-- Individual Memories:
635
634
  ${g}
636
635
 
637
- `}let u=0,h=5,x=!1,p=ae("gemma_janitor_fallback_google");for(i==="OpenRouter"&&(p=ae("janitor_open_router")),i==="DeepSeek"&&(p=ae("deepseek_level_1")),i==="Mistral"&&(p=ae("mistral_level_1")),i==="NVIDIA"&&(p=ae("nvidia_janitor_fallback")),i==="InferX"&&(p=ae("inferx_fallback")),i==="SenseNova"&&(p=ae("sensenova_fallback")),i==="AIHubMix"&&(p=ae("aihubmix_fallback")),i==="Poolside"&&(p=ae("poolside_fallback")),(i==="9router"||i==="9Router")&&(p=ae("9router_fallback"));u<=h&&!x;){u++;try{let s=(await yi(n,p,c,null,"Fast",.75,"background")).text||"",g=eo(s);if(g.length===0)throw new Error("No tool calls detected in synthesis response");for(let k of g){let he=k.toolName;["saveSummary","saveSumary","SaveSummary","SaveSumary"].includes(he)&&await Bo(he,k.args,{chatId:e})}x=!0}catch(f){if(u>=h)throw new Error(`Failed after ${h} attempts. Last error: ${f.message}`)}}}catch(i){let o=i instanceof Error?(()=>{try{return JSON.parse(JSON.parse(i.message).error.message).error.message}catch{return String(i)}})():String(i),r=W.join(wn,"janitor");Ae.existsSync(r)||Ae.mkdirSync(r,{recursive:!0}),Ae.appendFileSync(W.join(r,"error.log"),`[${new Date().toLocaleString()}] Past memory batch consolidation error: ${o}
638
- `)}},Nd=async(e,n,t=!1)=>{let{chatId:i,aiProvider:o="Google"}=e,r=W.join(Jo,"chat-summaries.json"),c=s=>s.filter(g=>(g.role==="user"||g.role==="agent"||g.role==="system")&&g.role!=="think"&&!g.isVisualFeedback&&!g.isMeta&&!g.isTerminalRecord&&!(g.text&&g.text.includes("[TERMINAL_RECORD]"))&&!String(g.id).startsWith("welcome")).map(g=>{let k=g.fullText||g.text||"",he=g.role==="system"||k.startsWith("[ACTION RESULT]:")||k.startsWith("[TOOL RESULT]:")||g.text&&(g.text.startsWith("[ACTION RESULT]:")||g.text.startsWith("[TOOL RESULT]:")),y=k;return he&&(k.includes("[ACTION RESULT]:")||k.includes("[TOOL RESULT]:")||g.text&&(g.text.includes("[ACTION RESULT]:")||g.text.includes("[TOOL RESULT]:")))?y="[ACTION RESULT]: ...truncated for summary":y=y.replace(/(\[(?:tool|action):[a-zA-Z0-9_\.]+)\([\s\S]*?\)(\])/g,"$1(...)$2"),`[${he?"ACTION":g.role==="agent"?"AGENT":"USER"}]: ${y}`}).join(`
636
+ `}let u=0,h=5,x=!1,p=ae("gemma_janitor_fallback_google");for(i==="OpenRouter"&&(p=ae("janitor_open_router")),i==="DeepSeek"&&(p=ae("deepseek_level_1")),i==="Mistral"&&(p=ae("mistral_level_1")),i==="NVIDIA"&&(p=ae("nvidia_janitor_fallback")),i==="InferX"&&(p=ae("inferx_fallback")),i==="SenseNova"&&(p=ae("sensenova_fallback")),i==="AIHubMix"&&(p=ae("aihubmix_fallback")),i==="Poolside"&&(p=ae("poolside_fallback")),(i==="9router"||i==="9Router")&&(p=ae("9router_fallback"));u<=h&&!x;){u++;try{let s=(await xi(n,p,d,null,"Fast",.75,"background")).text||"",g=jn(s);if(g.length===0)throw new Error("No tool calls detected in synthesis response");for(let k of g){let he=k.toolName;["saveSummary","saveSumary","SaveSummary","SaveSumary"].includes(he)&&await Bo(he,k.args,{chatId:e})}x=!0}catch(f){if(u>=h)throw new Error(`Failed after ${h} attempts. Last error: ${f.message}`)}}}catch(i){let o=i instanceof Error?(()=>{try{return JSON.parse(JSON.parse(i.message).error.message).error.message}catch{return String(i)}})():String(i),r=U.join(wn,"janitor");Ae.existsSync(r)||Ae.mkdirSync(r,{recursive:!0}),Ae.appendFileSync(U.join(r,"error.log"),`[${new Date().toLocaleString()}] Past memory batch consolidation error: ${o}
637
+ `)}},Dd=async(e,n,t=!1)=>{let{chatId:i,aiProvider:o="Google"}=e,r=U.join(Jo,"chat-summaries.json"),d=s=>s.filter(g=>(g.role==="user"||g.role==="agent"||g.role==="system")&&g.role!=="think"&&!g.isVisualFeedback&&!g.isMeta&&!g.isTerminalRecord&&!(g.text&&g.text.includes("[TERMINAL_RECORD]"))&&!String(g.id).startsWith("welcome")).map(g=>{let k=g.fullText||g.text||"",he=g.role==="system"||k.startsWith("[ACTION RESULT]:")||k.startsWith("[TOOL RESULT]:")||g.text&&(g.text.startsWith("[ACTION RESULT]:")||g.text.startsWith("[TOOL RESULT]:")),y=k;return he&&(k.includes("[ACTION RESULT]:")||k.includes("[TOOL RESULT]:")||g.text&&(g.text.includes("[ACTION RESULT]:")||g.text.includes("[TOOL RESULT]:")))?y="[ACTION RESULT]: ...truncated for summary":y=y.replace(/(\[(?:tool|action):[a-zA-Z0-9_\.]+)\([\s\S]*?\)(\])/g,"$1(...)$2"),`[${he?"ACTION":g.role==="agent"?"AGENT":"USER"}]: ${y}`}).join(`
639
638
 
640
639
  `),a=async(s,g)=>{let k="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.",he=g?`Here is the previous summary:
641
640
  ${g}
@@ -646,9 +645,9 @@ ${s}
646
645
  Provide a new consolidated summary of the entire session.`:`Here is the conversation history:
647
646
  ${s}
648
647
 
649
- Provide a consolidated summary of the entire session.`,y=ae("gemma_janitor_fallback_google");o==="OpenRouter"&&(y=ae("janitor_open_router")),o==="DeepSeek"&&(y=ae("deepseek_level_1")),o==="Mistral"&&(y=ae("mistral_level_1")),o==="NVIDIA"&&(y=ae("nvidia_chat_summarizer_fallback")),o==="InferX"&&(y=ae("inferx_fallback")),o==="SenseNova"&&(y=ae("sensenova_fallback")),o==="AIHubMix"&&(y=ae("aihubmix_fallback")),o==="Poolside"&&(y=ae("poolside_fallback")),(o==="9router"||o==="9Router")&&(y=ae("9router_fallback")),(o==="ExpLabs"||o==="ExperientialLabs")&&(y=ae("explabs_fallback")||"deepseek-v4-pro-0813"),(o==="TokenHarbor"||o==="Token Harbor"||o==="tokenharbor"||o==="token_harbor"||o==="thk")&&(y=ae("tokenharbor_fallback")||"deepseek-v4.1-flash:free"),(o==="Infron"||o==="infron")&&(y=ae("infron_fallback")),(o==="xKiro"||o==="xkiro"||o==="kiro")&&(y=ae("xkiro_fallback")||"openai/gpt-5.6-sol");let E=0,D=!1,K=null;for(;E<=3&&!D;){E++;try{K=await yi(e,y,he,k,"Fast"),D=!0}catch{if(E>3){if(o==="Google")try{let T=ae("general_fallback");return(await yi(e,T,he,k,"Fast")).text||""}catch{return""}return""}}}return K&&K.text||""},u=c(n),h=Ot(r,{}),x=h[i]||{summary:"",historyLength:0};typeof x=="string"&&(x={summary:x,historyLength:0});let p=x.summary||"",f=await a(u,p);if(f){x.summary=f;let s=pl(n);return t?x.historyLength=(x.historyLength||0)+s:x.historyLength=s,h[i]=x,co(r,h),f}return null},Dd=e=>{try{let n=W.join(Jo,"chat-summaries.json");if(Ae.existsSync(n)){let t=Ot(n,{});t[e]&&(delete t[e],co(n,t))}}catch{}},Fd=async function*(e,n,t,i,o){let{profile:r,thinkingLevel:c,mode:a,janitorModel:u,chatId:h,isPlayground:x,systemSettings:p,sessionStats:f,aiProvider:s="Google",apiTier:g,wildcardTooling:k,wildercardTooling:he}=t,y=lt(e);if(!ps&&s==="Google")throw new Error("AI not initialized");let E=process.env.NVIDIA_BASE_URL||t?.aiProvider==="Ollama"||t?.aiProvider==="InferX"||t?.aiProvider==="SenseNova"||t?.aiProvider==="AIHubMix"||t?.aiProvider==="Poolside"||t?.aiProvider==="9router"||t?.aiProvider==="ExpLabs"||t?.aiProvider==="ExperientialLabs"||t?.aiProvider==="TokenHarbor"||t?.aiProvider==="Token Harbor"||t?.aiProvider==="tokenharbor"||t?.aiProvider==="token_harbor"||t?.aiProvider==="thk"||t?.aiProvider==="APInex"||t?.aiProvider==="apinex"||t?.aiProvider==="apx"||t?.aiProvider==="xKiro"||t?.aiProvider==="xkiro"||t?.aiProvider==="kiro"||t?.aiProvider==="Infron"||t?.aiProvider==="infron"||t?.aiProvider==="c_openai"||t?.aiProvider==="Custom (OpenAI)"?!1:p?.memory!==!1,D=n[n.length-1].text,K=W.join(Jo,"chat-summaries.json"),O=!1,T=n.filter(G=>G.role==="user").length===1,Se=D.includes("[TITLE-UPDATE]"),Ce=T||Se,Me=D.replace(/\[TITLE-UPDATE\]/g,"").trim();Me=Me.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),yield{type:"status",content:"[start]"},yield{type:"status",content:"Gathering Context"},await ti.startTransaction(h,Me),p?.advanceRollback&&await Ro.takeInitialSnapshot(h),Et=!1;let Je=null;try{let G=new AbortController;Je=setInterval(()=>{Et&&(G.abort(),Je&&(clearInterval(Je),Je=null))},400);let b=[...n.slice(0,-1)];{let _e=Ot(K,{})[h]||{summary:"",historyLength:0};if(_e.summary&&_e.historyLength>0){let qt=0,Ie=[];for(let me=0;me<b.length;me++){let Ue=b[me];(Ue.role==="user"||Ue.role==="agent"||Ue.role==="system")&&!String(Ue.id).startsWith("welcome")&&!Ue.isMeta&&qt++,qt>_e.historyLength&&Ie.push(Ue)}b=Ie}}b=b.map(v=>{if(v.role==="user"&&v.text){let _e=v.text.match(/\[USER\]([\s\S]*?)\[\/USER\]/);if(_e)return{...v,text:_e[1].trim()}}return{...v}});let ht=process.env.HIGH_CONTEXT,fe=process.env.GOOGLE_GEMMA_NONSENSE==="true"||process.env.GOOGLE_GEMMA_NONSENSE===!0||!1,Vt={"16k":16e3,"32k":32e3,"64k":64e3,"128k":128e3,"256k":256e3,"512k":512e3,"1M":1e6}[p?.contextLength]||256e3;if(ht&&ht!=="false"){let v=parseInt(ht,10);!isNaN(v)&&v>=0&&v<=1e6&&(Vt=v)}if((s==="NVIDIA"&&(e?.includes("gpt")||e?.includes("qwen")||e?.includes("medium")||e.includes("muse"))||s==="Mistral")&&(Vt=126e3),s==="Google"&&e?.includes("gemma")&&fe&&(Vt=16e3),(f?.tokens||0)>Vt){yield{type:"text",content:"\u2726 Maximum Context Limit Reached. Start a new chat."};return}if(T&&E){let v=Ot(Qo,{});Object.values(v).flat().length>5&&(yield{type:"status",content:"Condensing past chat memories"},await wl(h,t,v))}let cn=Ot(Qo,{}),po=Ot(Mi,{}),Pn=Object.entries(cn).filter(([v])=>v!==h).flatMap(([v,_e])=>_e),yt=[...Object.entries(po).filter(([v])=>v!==h).slice(-20).map(([v,_e])=>`[Chat Summary]: ${_e}`),...Pn].map(v=>`- ${v}`).join(`
650
- `),ue=Ot(Xn,[]).map(v=>`- ${v.memory}`).join(`
651
- `),Be=(f?.tokens||0)>=1e4,Pe=new Date,Y=Pe.getFullYear(),H=Pe.toLocaleString("en-US",{month:"short"}).toUpperCase(),_=String(Pe.getDate()).padStart(2,"0"),Oe=`${Pe.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0})}`,S=v=>{try{return Ae.readdirSync(v,{withFileTypes:!0})}catch{return[]}},L=Array.from(new Set([...To,...Ao(process.cwd())])),ct=(v,_e=6)=>p?.indentationTree!==!1?ls(v,_e,1,S,L):ds(v,_e,"",1,S,L),ze=Ot(Pi,{}),Ct=ze[h],it=Ct?Ct!==process.cwd():!1;ze[h]=process.cwd(),co(Pi,ze);let Tn=Ot(K,{}),zt=Tn[h]||{summary:"",historyLength:0};typeof zt=="string"&&(zt={summary:zt,historyLength:0});let dt=n.filter(v=>(v.role==="user"||v.role==="agent"||v.role==="system")&&!String(v.id).startsWith("welcome")&&!v.isMeta).length;zt.historyLength&&dt<zt.historyLength&&(zt.summary="",zt.historyLength=0,Tn[h]=zt,co(K,Tn));let ge=typeof zt=="object"?zt.summary||"":zt||"",de=b.length>0;de&&ge&&b[0]&&(b[0].role==="user"||b[0].role==="system")&&(b[0].text.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")||(b[0].text=`[SYSTEM METADATA]
648
+ Provide a consolidated summary of the entire session.`,y=ae("gemma_janitor_fallback_google");o==="OpenRouter"&&(y=ae("janitor_open_router")),o==="DeepSeek"&&(y=ae("deepseek_level_1")),o==="Mistral"&&(y=ae("mistral_level_1")),o==="NVIDIA"&&(y=ae("nvidia_chat_summarizer_fallback")),o==="InferX"&&(y=ae("inferx_fallback")),o==="SenseNova"&&(y=ae("sensenova_fallback")),o==="AIHubMix"&&(y=ae("aihubmix_fallback")),o==="Poolside"&&(y=ae("poolside_fallback")),(o==="9router"||o==="9Router")&&(y=ae("9router_fallback")),(o==="ExpLabs"||o==="ExperientialLabs")&&(y=ae("explabs_fallback")||"deepseek-v4-pro-0813"),(o==="TokenHarbor"||o==="Token Harbor"||o==="tokenharbor"||o==="token_harbor"||o==="thk")&&(y=ae("tokenharbor_fallback")||"deepseek-v4.1-flash:free"),(o==="Infron"||o==="infron")&&(y=ae("infron_fallback")),(o==="xKiro"||o==="xkiro"||o==="kiro")&&(y=ae("xkiro_fallback")||"openai/gpt-5.6-sol");let E=0,D=!1,K=null;for(;E<=3&&!D;){E++;try{K=await xi(e,y,he,k,"Fast"),D=!0}catch{if(E>3){if(o==="Google")try{let T=ae("general_fallback");return(await xi(e,T,he,k,"Fast")).text||""}catch{return""}return""}}}return K&&K.text||""},u=d(n),h=Ot(r,{}),x=h[i]||{summary:"",historyLength:0};typeof x=="string"&&(x={summary:x,historyLength:0});let p=x.summary||"",f=await a(u,p);if(f){x.summary=f;let s=hl(n);return t?x.historyLength=(x.historyLength||0)+s:x.historyLength=s,h[i]=x,co(r,h),f}return null},Fd=e=>{try{let n=U.join(Jo,"chat-summaries.json");if(Ae.existsSync(n)){let t=Ot(n,{});t[e]&&(delete t[e],co(n,t))}}catch{}},Bd=async function*(e,n,t,i,o){let{profile:r,thinkingLevel:d,mode:a,janitorModel:u,chatId:h,isPlayground:x,systemSettings:p,sessionStats:f,aiProvider:s="Google",apiTier:g,wildcardTooling:k,wildercardTooling:he}=t,y=lt(e);if(!hs&&s==="Google")throw new Error("AI not initialized");let E=process.env.NVIDIA_BASE_URL||t?.aiProvider==="Ollama"||t?.aiProvider==="InferX"||t?.aiProvider==="SenseNova"||t?.aiProvider==="AIHubMix"||t?.aiProvider==="Poolside"||t?.aiProvider==="9router"||t?.aiProvider==="ExpLabs"||t?.aiProvider==="ExperientialLabs"||t?.aiProvider==="TokenHarbor"||t?.aiProvider==="Token Harbor"||t?.aiProvider==="tokenharbor"||t?.aiProvider==="token_harbor"||t?.aiProvider==="thk"||t?.aiProvider==="APInex"||t?.aiProvider==="apinex"||t?.aiProvider==="apx"||t?.aiProvider==="xKiro"||t?.aiProvider==="xkiro"||t?.aiProvider==="kiro"||t?.aiProvider==="Infron"||t?.aiProvider==="infron"||t?.aiProvider==="c_openai"||t?.aiProvider==="Custom (OpenAI)"?!1:p?.memory!==!1,D=n[n.length-1].text,K=U.join(Jo,"chat-summaries.json"),L=!1,T=n.filter(W=>W.role==="user").length===1,Se=D.includes("[TITLE-UPDATE]"),Ce=T||Se,Me=D.replace(/\[TITLE-UPDATE\]/g,"").trim();Me=Me.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),yield{type:"status",content:"[start]"},yield{type:"status",content:"Gathering Context"},await ti.startTransaction(h,Me),p?.advanceRollback&&await Ro.takeInitialSnapshot(h),Et=!1;let Je=null;try{let W=new AbortController;Je=setInterval(()=>{Et&&(W.abort(),Je&&(clearInterval(Je),Je=null))},400);let b=[...n.slice(0,-1)];{let _e=Ot(K,{})[h]||{summary:"",historyLength:0};if(_e.summary&&_e.historyLength>0){let qt=0,Ie=[];for(let me=0;me<b.length;me++){let Ue=b[me];(Ue.role==="user"||Ue.role==="agent"||Ue.role==="system")&&!String(Ue.id).startsWith("welcome")&&!Ue.isMeta&&qt++,qt>_e.historyLength&&Ie.push(Ue)}b=Ie}}b=b.map(I=>{if(I.role==="user"&&I.text){let _e=I.text.match(/\[USER\]([\s\S]*?)\[\/USER\]/);if(_e)return{...I,text:_e[1].trim()}}return{...I}});let ht=process.env.HIGH_CONTEXT,fe=process.env.GOOGLE_GEMMA_NONSENSE==="true"||process.env.GOOGLE_GEMMA_NONSENSE===!0||!1,Vt={"16k":16e3,"32k":32e3,"64k":64e3,"128k":128e3,"256k":256e3,"512k":512e3,"1M":1e6}[p?.contextLength]||256e3;if(ht&&ht!=="false"){let I=parseInt(ht,10);!isNaN(I)&&I>=0&&I<=1e6&&(Vt=I)}if((s==="NVIDIA"&&(e?.includes("gpt")||e?.includes("qwen")||e?.includes("medium")||e.includes("muse"))||s==="Mistral")&&(Vt=126e3),s==="Google"&&e?.includes("gemma")&&fe&&(Vt=16e3),(f?.tokens||0)>Vt){yield{type:"text",content:"\u2726 Maximum Context Limit Reached. Start a new chat."};return}if(T&&E){let I=Ot(Qo,{});Object.values(I).flat().length>5&&(yield{type:"status",content:"Condensing past chat memories"},await Sl(h,t,I))}let cn=Ot(Qo,{}),po=Ot(Pi,{}),Pn=Object.entries(cn).filter(([I])=>I!==h).flatMap(([I,_e])=>_e),yt=[...Object.entries(po).filter(([I])=>I!==h).slice(-20).map(([I,_e])=>`[Chat Summary]: ${_e}`),...Pn].map(I=>`- ${I}`).join(`
649
+ `),ue=Ot(Jn,[]).map(I=>`- ${I.memory}`).join(`
650
+ `),Be=(f?.tokens||0)>=1e4,Pe=new Date,V=Pe.getFullYear(),G=Pe.toLocaleString("en-US",{month:"short"}).toUpperCase(),_=String(Pe.getDate()).padStart(2,"0"),Oe=`${Pe.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0})}`,S=I=>{try{return Ae.readdirSync(I,{withFileTypes:!0})}catch{return[]}},$=Array.from(new Set([...To,...Ao(process.cwd())])),ct=(I,_e=6)=>p?.indentationTree!==!1?cs(I,_e,1,S,$):fs(I,_e,"",1,S,$),ze=Ot(Oi,{}),Ct=ze[h],it=Ct?Ct!==process.cwd():!1;ze[h]=process.cwd(),co(Oi,ze);let Tn=Ot(K,{}),zt=Tn[h]||{summary:"",historyLength:0};typeof zt=="string"&&(zt={summary:zt,historyLength:0});let dt=n.filter(I=>(I.role==="user"||I.role==="agent"||I.role==="system")&&!String(I.id).startsWith("welcome")&&!I.isMeta).length;zt.historyLength&&dt<zt.historyLength&&(zt.summary="",zt.historyLength=0,Tn[h]=zt,co(K,Tn));let ge=typeof zt=="object"?zt.summary||"":zt||"",de=b.length>0;de&&ge&&b[0]&&(b[0].role==="user"||b[0].role==="system")&&(b[0].text.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")||(b[0].text=`[SYSTEM METADATA]
652
651
  **CONTEXT SUMMARY OF PREVIOUS TURNS (PRIORITY: DYNAMIC)**
653
652
  ${ge}
654
653
 
@@ -656,13 +655,13 @@ ${ge}
656
655
  [SYSTEM METADATA]
657
656
  **CONTEXT SUMMARY OF PREVIOUS TURNS**
658
657
  ${ge}
659
- `:"",ho=!!p?.dynamicDirAwareness,to=`${h}|${s}|${c}|${e}|${r}|${ho}`,la=!ho&&Qn.key===to&&Qn.value?"":`
658
+ `:"",ho=!!p?.dynamicDirAwareness,to=`${h}|${s}|${d}|${e}|${r}|${ho}`,la=!ho&&Zn.key===to&&Zn.value?"":`
660
659
  **Directory**
661
660
  CWD: `+process.cwd()+`${x?" [PLAYGROUND MODE]":""}
662
- `+ct(process.cwd(),6),ft=go()?await Jn():null,xs=v=>{if(!v||!Array.isArray(v)||v.length===0)return null;let _e=new Map;for(let Ie of v){let me=Ie.relPath||(Ie.file?W.relative(process.cwd(),Ie.file):"unknown");_e.has(me)||_e.set(me,[]),_e.get(me).push(Ie)}let qt=[];for(let[Ie,me]of _e.entries()){qt.push(`- ${Ie}:`);for(let Ue of me){let qe=(Ue.snippet||"").trim().replace(/\r?\n/g," "),Ze=Ue.line||1,Nt=(Ue.text||"").trim().replace(/\r?\n+/g,". "),Te=Nt?` [${Nt}]`:"";qt.push(` ~L${Ze}${Te}`)}}return qt.join(`
663
- `)},xi=xs(ft?.comments),An="";if(ft&&ft.file_focused!=="none"){An=`
661
+ `+ct(process.cwd(),6),ft=go()?await Qn():null,xs=I=>{if(!I||!Array.isArray(I)||I.length===0)return null;let _e=new Map;for(let Ie of I){let me=Ie.relPath||(Ie.file?U.relative(process.cwd(),Ie.file):"unknown");_e.has(me)||_e.set(me,[]),_e.get(me).push(Ie)}let qt=[];for(let[Ie,me]of _e.entries()){qt.push(`- ${Ie}:`);for(let Ue of me){let qe=(Ue.snippet||"").trim().replace(/\r?\n/g," "),Ze=Ue.line||1,Nt=(Ue.text||"").trim().replace(/\r?\n+/g,". "),Te=Nt?` [${Nt}]`:"";qt.push(` ~L${Ze}${Te}`)}}return qt.join(`
662
+ `)},bi=xs(ft?.comments),An="";if(ft&&ft.file_focused!=="none"){An=`
664
663
  [Additional IDE Context]
665
- `;let v=W.relative(process.cwd(),ft.file_focused),_e=(ft.opened_editors||[]).map(Ie=>{let me=W.relative(process.cwd(),Ie);return me.startsWith("..")?`[External] ${W.basename(Ie)}`:me});if(An+=`Focused File: ${v}
664
+ `;let I=U.relative(process.cwd(),ft.file_focused),_e=(ft.opened_editors||[]).map(Ie=>{let me=U.relative(process.cwd(),Ie);return me.startsWith("..")?`[External] ${U.basename(Ie)}`:me});if(An+=`Focused File: ${I}
666
665
  Cursor Line: ${ft.cursor_line}
667
666
  `,ft.selected){let Ie=ft.selected,me=Ie.split(`
668
667
  `);me.length>256&&(Ie=me.slice(0,240).join(`
@@ -673,14 +672,14 @@ Cursor Line: ${ft.cursor_line}
673
672
  ... [truncated] ...
674
673
  `+Ie.slice(-128)),An+=`Current Selection: "${Ie}"
675
674
  `}if(ft.manual_edits){let me=ft.manual_edits.split(`
676
- `),Ue=[],qe=null;for(let P of me)P.trim()&&(P.startsWith(" Line ")?qe&&qe.edits.push(P):(qe={path:P.endsWith(":")?P.slice(0,-1):P,edits:[]},Ue.push(qe)));for(let P of Ue)P.edits.length>80&&(P.edits=P.edits.slice(-80)),P.originalEditsCount=P.edits.length;let Ze=(P,De)=>De.reduce((xt,un)=>{let Rt=ft.file_focused&&(un.path===ft.file_focused||W.resolve(process.cwd(),un.path)===W.resolve(ft.file_focused))?Math.ceil(P*1.2):P;return xt+Math.min(un.edits.length,Rt)},0),Nt=80;if(Ze(80,Ue)>300){let P=!1;for(let De=80;De>=10;De--)if(Ze(De,Ue)<=300){Nt=De,P=!0;break}P||(Nt=10)}let Te=[...Ue];if(Nt===10&&Ze(10,Te)>500)for(;Te.length>0&&Ze(10,Te)>500;){let P=0,De=Te[0].originalEditsCount;for(let xt=1;xt<Te.length;xt++)Te[xt].originalEditsCount<De&&(De=Te[xt].originalEditsCount,P=xt);Te.splice(P,1)}for(let P of Te){let xt=ft.file_focused&&(P.path===ft.file_focused||W.resolve(process.cwd(),P.path)===W.resolve(ft.file_focused))?Math.ceil(Nt*1.2):Nt;P.edits.length>xt&&(P.edits=P.edits.slice(-xt))}for(let P of Te){let De=`${P.path}:
677
- ${P.edits.join(`
678
- `)}`;for(;P.edits.length>0&&De.length>4*768;)P.edits.shift(),De=`${P.path}:
679
- ${P.edits.join(`
680
- `)}`;De.length>4*768?P.stringRepresentation="... "+De.slice(-(4*768-4)):P.stringRepresentation=De}let pe=Te.map(P=>P.stringRepresentation).join(`
681
- `);for(;Te.length>0&&pe.length>4*2048;){Te[0].edits.length>0?Te[0].edits.shift():Te.shift();for(let P of Te){let De=`${P.path}:
682
- ${P.edits.join(`
683
- `)}`;De.length>4*768?P.stringRepresentation="... "+De.slice(-(4*768-4)):P.stringRepresentation=De}pe=Te.map(P=>P.stringRepresentation).join(`
675
+ `),Ue=[],qe=null;for(let O of me)O.trim()&&(O.startsWith(" Line ")?qe&&qe.edits.push(O):(qe={path:O.endsWith(":")?O.slice(0,-1):O,edits:[]},Ue.push(qe)));for(let O of Ue)O.edits.length>80&&(O.edits=O.edits.slice(-80)),O.originalEditsCount=O.edits.length;let Ze=(O,Fe)=>Fe.reduce((xt,un)=>{let Rt=ft.file_focused&&(un.path===ft.file_focused||U.resolve(process.cwd(),un.path)===U.resolve(ft.file_focused))?Math.ceil(O*1.2):O;return xt+Math.min(un.edits.length,Rt)},0),Nt=80;if(Ze(80,Ue)>300){let O=!1;for(let Fe=80;Fe>=10;Fe--)if(Ze(Fe,Ue)<=300){Nt=Fe,O=!0;break}O||(Nt=10)}let Te=[...Ue];if(Nt===10&&Ze(10,Te)>500)for(;Te.length>0&&Ze(10,Te)>500;){let O=0,Fe=Te[0].originalEditsCount;for(let xt=1;xt<Te.length;xt++)Te[xt].originalEditsCount<Fe&&(Fe=Te[xt].originalEditsCount,O=xt);Te.splice(O,1)}for(let O of Te){let xt=ft.file_focused&&(O.path===ft.file_focused||U.resolve(process.cwd(),O.path)===U.resolve(ft.file_focused))?Math.ceil(Nt*1.2):Nt;O.edits.length>xt&&(O.edits=O.edits.slice(-xt))}for(let O of Te){let Fe=`${O.path}:
676
+ ${O.edits.join(`
677
+ `)}`;for(;O.edits.length>0&&Fe.length>4*768;)O.edits.shift(),Fe=`${O.path}:
678
+ ${O.edits.join(`
679
+ `)}`;Fe.length>4*768?O.stringRepresentation="... "+Fe.slice(-(4*768-4)):O.stringRepresentation=Fe}let pe=Te.map(O=>O.stringRepresentation).join(`
680
+ `);for(;Te.length>0&&pe.length>4*2048;){Te[0].edits.length>0?Te[0].edits.shift():Te.shift();for(let O of Te){let Fe=`${O.path}:
681
+ ${O.edits.join(`
682
+ `)}`;Fe.length>4*768?O.stringRepresentation="... "+Fe.slice(-(4*768-4)):O.stringRepresentation=Fe}pe=Te.map(O=>O.stringRepresentation).join(`
684
683
  `)}pe.length>4*2048&&(pe="... "+pe.slice(-(4*2048-4))),An+=`Recent Manual Edits:
685
684
  ${pe}
686
685
  `}_e.length>0&&(An+=`All Opened Editors: ${_e.join(", ")}`),ft.diagnostics&&(An+=`
@@ -689,84 +688,84 @@ ${ft.diagnostics}
689
688
  `),(Me.toLowerCase().includes("lint")||Me.toLowerCase().includes("warning"))&&ft.warnings&&(An+=`
690
689
  **Lint Warnings**:
691
690
  ${ft.warnings}
692
- `)}let bs=Me.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),ws=/(?:\\)?@\[([^\]]+)\]/g,bi,wi=[];for(ws.lastIndex=0;(bi=ws.exec(bs))!==null;){let v=bi[0].startsWith("\\");wi.push({tag:bi[1],isEscaped:v})}let Si=[],jo=null;for(let v=0;v<wi.length;v++){let{tag:_e,isEscaped:qt}=wi[v];if(!qt)try{let Ie=_e.trim().replace(/^["']|["']$/g,""),me=/[:#]L?(\d+)(?:-L?(\d+))?$/i,Ue=Ie.match(me),qe=Ie,Ze=null,Nt=null;Ue&&(Ze=parseInt(Ue[1],10),Nt=Ue[2]?parseInt(Ue[2],10):Ze,qe=Ie.slice(0,Ue.index));let Te=W.resolve(process.cwd(),qe);if(Ae.existsSync(Te)&&Ae.statSync(Te).isFile()){let P=qe.toLowerCase(),De=P.endsWith(".pdf"),xt=P.endsWith(".docx")||P.endsWith(".doc")||P.endsWith(".ppt")||P.endsWith(".pptx")||P.endsWith(".xls")||P.endsWith(".xlsx"),un=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(P),He=un||De||xt,Rt=s==="Google"||lt(e);if(He&&!Rt){let ve=`\u2718 Unsupported Modality: ${W.basename(qe)}`,ut=115;process.stdout.isTTY&&(ut=process.stdout.columns-5||120);let nn=[ve],je=Math.max(...nn.map(gn=>gn.length)),ne=Math.min(je+4,ut),We=nn.map(gn=>`${gn.padEnd(ne-2).substring(0,ne-2)}`).join(`
693
- `);yield{type:"visual_feedback",content:jt(`${We}
694
- `)};continue}if(Ze===null&&!He){let ve=0;try{ve=Ae.readFileSync(Te,"utf8").split(/\r\n|\r|\n/).length}catch{}if(ve>300){let ut=`\u21B7 Skipped (Too Large): ${W.basename(qe)}`,nn=115;process.stdout.isTTY&&(nn=process.stdout.columns-5||120);let je=Math.min(ut.length+4,nn),ne=ut.padEnd(je-2).substring(0,je-2);yield{type:"visual_feedback",content:jt(`${ne}
695
- `)};continue}}let En=Ze!==null?Ze:1,Bt=Nt!==null?Nt:Ze!==null?Ze:En+299;Bt-En>300&&(Bt=En+300);let Kn=`path=${JSON.stringify(qe)}, startLine=${En}, endLine=${Bt}`,Xt=await Bs(Kn,{isMultiModal:Rt}),Ln=!1,oo="",_t=null;if(typeof Xt=="string"?Xt.trim().startsWith("ERROR")?Ln=!0:oo=Xt:Xt&&typeof Xt=="object"&&Xt.binaryPart?(_t=Xt.binaryPart,oo=Xt.text||""):Ln=!0,!Ln){let ve="";if(un?(ve=`\u2714 Processed: ${W.basename(qe)}`,jo=_t):De||xt?(ve=`\u2714 Auto-Analysed: ${W.basename(qe)}`,jo=_t):(ve=`\u2714 Auto-Read: ${W.basename(qe)}`,Si.push(oo)),ve){let ut=115;process.stdout.isTTY&&(ut=process.stdout.columns-5||120);let nn=[ve],je=Math.max(...nn.map(gn=>gn.length)),ne=Math.min(je+4,ut),We=nn.map(gn=>`${gn.padEnd(ne-2).substring(0,ne-2)}`).join(`
696
- `);yield{type:"visual_feedback",content:jt(`${We}
697
- `)}}}}}catch{}}let ki="";Si.length>0&&(ki=`
691
+ `)}let bs=Me.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),ws=/(?:\\)?@\[([^\]]+)\]/g,wi,Si=[];for(ws.lastIndex=0;(wi=ws.exec(bs))!==null;){let I=wi[0].startsWith("\\");Si.push({tag:wi[1],isEscaped:I})}let ki=[],jo=null;for(let I=0;I<Si.length;I++){let{tag:_e,isEscaped:qt}=Si[I];if(!qt)try{let Ie=_e.trim().replace(/^["']|["']$/g,""),me=/[:#]L?(\d+)(?:-L?(\d+))?$/i,Ue=Ie.match(me),qe=Ie,Ze=null,Nt=null;Ue&&(Ze=parseInt(Ue[1],10),Nt=Ue[2]?parseInt(Ue[2],10):Ze,qe=Ie.slice(0,Ue.index));let Te=U.resolve(process.cwd(),qe);if(Ae.existsSync(Te)&&Ae.statSync(Te).isFile()){let O=qe.toLowerCase(),Fe=O.endsWith(".pdf"),xt=O.endsWith(".docx")||O.endsWith(".doc")||O.endsWith(".ppt")||O.endsWith(".pptx")||O.endsWith(".xls")||O.endsWith(".xlsx"),un=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(O),We=un||Fe||xt,Rt=s==="Google"||lt(e);if(We&&!Rt){let ve=`\u2718 Unsupported Modality: ${U.basename(qe)}`,ut=115;process.stdout.isTTY&&(ut=process.stdout.columns-5||120);let nn=[ve],je=Math.max(...nn.map(gn=>gn.length)),ne=Math.min(je+4,ut),Ge=nn.map(gn=>`${gn.padEnd(ne-2).substring(0,ne-2)}`).join(`
692
+ `);yield{type:"visual_feedback",content:Kt(`${Ge}
693
+ `)};continue}if(Ze===null&&!We){let ve=0;try{ve=Ae.readFileSync(Te,"utf8").split(/\r\n|\r|\n/).length}catch{}if(ve>300){let ut=`\u21B7 Skipped (Too Large): ${U.basename(qe)}`,nn=115;process.stdout.isTTY&&(nn=process.stdout.columns-5||120);let je=Math.min(ut.length+4,nn),ne=ut.padEnd(je-2).substring(0,je-2);yield{type:"visual_feedback",content:Kt(`${ne}
694
+ `)};continue}}let En=Ze!==null?Ze:1,Ut=Nt!==null?Nt:Ze!==null?Ze:En+299;Ut-En>300&&(Ut=En+300);let Vn=`path=${JSON.stringify(qe)}, startLine=${En}, endLine=${Ut}`,Xt=await Bs(Vn,{isMultiModal:Rt}),Ln=!1,oo="",_t=null;if(typeof Xt=="string"?Xt.trim().startsWith("ERROR")?Ln=!0:oo=Xt:Xt&&typeof Xt=="object"&&Xt.binaryPart?(_t=Xt.binaryPart,oo=Xt.text||""):Ln=!0,!Ln){let ve="";if(un?(ve=`\u2714 Processed: ${U.basename(qe)}`,jo=_t):Fe||xt?(ve=`\u2714 Auto-Analysed: ${U.basename(qe)}`,jo=_t):(ve=`\u2714 Auto-Read: ${U.basename(qe)}`,ki.push(oo)),ve){let ut=115;process.stdout.isTTY&&(ut=process.stdout.columns-5||120);let nn=[ve],je=Math.max(...nn.map(gn=>gn.length)),ne=Math.min(je+4,ut),Ge=nn.map(gn=>`${gn.padEnd(ne-2).substring(0,ne-2)}`).join(`
695
+ `);yield{type:"visual_feedback",content:Kt(`${Ge}
696
+ `)}}}}}catch{}}let Ti="";ki.length>0&&(Ti=`
698
697
  [Tagged File Contents] Auto Read User Tagged files by System, No need to re-read
699
- `+Si.join(`
698
+ `+ki.join(`
700
699
 
701
700
  `)+`
702
701
  [Tagged File Contents]
703
702
  `);let Ss=bs.replace(/\\(@\[[^\]]+\])/g,"$1"),ks=k?`You cannot execute tools. Instead write the action string in chat you WOULD have written
704
- `:"",ca=process.env.forcedReasoning||!1,Ts=c!=="Fast"&&(s==="Mistral"&&!ei(e)||c!=="High"&&s==="Google")?`${s==="Mistral"&&!ei(e)||e.toLowerCase().startsWith("gemma")||ca?`[system] strictly follow thinking policy as high priority. do not start a response without <think_fluxflow>...</think_fluxflow> [/system]
705
- `:""}`:"",no="";if(p?.clipboardContext)try{process.platform==="win32"?no=fs("powershell.exe -NoProfile -Command Get-Clipboard",{encoding:"utf8",stdio:["pipe","pipe","ignore"],timeout:1500}).replace(/\r?\n$/,""):process.platform==="darwin"?no=fs("pbpaste",{encoding:"utf8",stdio:["pipe","pipe","ignore"],timeout:1500}).replace(/\r?\n$/,""):no=fs("xclip -selection clipboard -o || xsel --clipboard --output",{encoding:"utf8",shell:!0,stdio:["pipe","pipe","ignore"],timeout:1500}).replace(/\r?\n$/,"")}catch{no=""}let Ko="",da=!!p?.autoExcludeMetadata,fa=!!(An||ki||ks||$t||Ts||it||p?.dynamicDirAwareness||p?.autoTruncateResults);da&&!fa?Ko=Ss.trim():Ko=`[System Metadata] Time: ${Oe}${it?`
703
+ `:"",ca=process.env.forcedReasoning||!1,Ts=d!=="Fast"&&(s==="Mistral"&&!ei(e)||d!=="High"&&s==="Google")?`${s==="Mistral"&&!ei(e)||e.toLowerCase().startsWith("gemma")||ca?`[system] strictly follow thinking policy as high priority. do not start a response without <think_fluxflow>...</think_fluxflow> [/system]
704
+ `:""}`:"",no="";if(p?.clipboardContext)try{process.platform==="win32"?no=us("powershell.exe -NoProfile -Command Get-Clipboard",{encoding:"utf8",stdio:["pipe","pipe","ignore"],timeout:1500}).replace(/\r?\n$/,""):process.platform==="darwin"?no=us("pbpaste",{encoding:"utf8",stdio:["pipe","pipe","ignore"],timeout:1500}).replace(/\r?\n$/,""):no=us("xclip -selection clipboard -o || xsel --clipboard --output",{encoding:"utf8",shell:!0,stdio:["pipe","pipe","ignore"],timeout:1500}).replace(/\r?\n$/,"")}catch{no=""}let Ko="",da=!!p?.autoExcludeMetadata,fa=!!(An||Ti||ks||$t||Ts||it||p?.dynamicDirAwareness||p?.autoTruncateResults);da&&!fa?Ko=Ss.trim():Ko=`[System Metadata] Time: ${Oe}${it?`
706
705
  WARNING: CWD Changed from previous: "${Ct}" to current: "${process.cwd()}", write change in chat to avoid future path mismatches
707
706
  `:""}${An}
708
707
  ${no.trim().length>0?`[Clipboard Context]
709
708
  - ${no.trim()}
710
- `:""}${xi?`[Additional Comments]
711
- ${xi.trimEnd()}
709
+ `:""}${bi?`[Additional Comments]
710
+ ${bi.trimEnd()}
712
711
  `:""}Action format: [action:ActionName(...)]
713
712
  [/Metadata]
714
- ${$t}${Ts}${ki}${ks}[user prompt] ${Ss.trim()} [/user prompt]`.trim();let As={role:"user",text:Ko};jo&&(As.binaryPart=jo),b.forEach(v=>{v.text&&v.role==="agent"&&(v.text=Kt(v.text))}),b.push(As),$t&&n[n.length-1]?.id&&(yield{type:"summary_injected",content:{id:n[n.length-1].id,text:Ko}});let fn=null,On=a==="Flux"?50:15;On=a.toLowerCase().includes("cu")?75:On;let ua=Math.floor(On/2),Es=0,xn=16;yield{type:"status",content:process.env.HALLOWEEN_EEGG==="true"?"Consulting the spirits":"Connecting"},Et=!1;let Ti=[],Vo=!1,Cs=!1,jn=[],Ai=!1;for(let v=0;v<=On;v++){let _e=Math.floor(On*.95);if(v>=_e&&Es<_e&&typeof t?.onAskUser=="function"){Es=_e;try{let X="Agent has been running for a long time. Do you want to continue execution?",B=[{id:"continue",label:"Continue",description:"Add few more steps"},{id:"cancel",label:"Cancel",description:"Stop extending and finish current turn limit"}],$=await t.onAskUser(X,B);$&&($.toLowerCase().includes("continue")||$==="Continue")&&(On+=ua)}catch{}}if(jn.length>=10&&typeof t?.onAskUser=="function"){let X={},B=null;for(let $ of jn)if(X[$]=(X[$]||0)+1,X[$]>=10){B=$;break}if(B)try{let $="Agent seems stuck in a tool loop. You can prompt it to steer or break the loop:",pt=[{id:"continue",label:"Continue Anyway",description:"Ignore warning and let it proceed"},{id:"stop",label:"Stop Loop",description:"Force agent to summarize progress and stop repeating"}],Fe=await t.onAskUser($,pt);if(Fe){let Ke="";typeof Fe=="string"&&(Fe.toLowerCase()==="stop"||Fe.includes("Stop Loop"))?Ke="STOP REPEATING THE SAME TOOL CALL. Acknowledge what failed or succeeded, summarize your current findings, and conclude.":typeof Fe=="string"&&(Fe.toLowerCase()==="continue"||Fe.includes("Continue Anyway"))?jn=jn.filter(It=>It!==B):Ke=typeof Fe=="string"?Fe:Fe?.label||Fe?.id||"",Ke&&(b.length>0&&b[b.length-1].role==="user"?b[b.length-1].text+=`
713
+ ${$t}${Ts}${Ti}${ks}[user prompt] ${Ss.trim()} [/user prompt]`.trim();let As={role:"user",text:Ko};jo&&(As.binaryPart=jo),b.forEach(I=>{I.text&&I.role==="agent"&&(I.text=Bt(I.text))}),b.push(As),$t&&n[n.length-1]?.id&&(yield{type:"summary_injected",content:{id:n[n.length-1].id,text:Ko}});let fn=null,On=a==="Flux"?50:15;On=a.toLowerCase().includes("cu")?75:On;let ua=Math.floor(On/2),Es=0,bn=16;yield{type:"status",content:process.env.HALLOWEEN_EEGG==="true"?"Consulting the spirits":"Connecting"},Et=!1;let Ai=[],Vo=!1,Cs=!1,Kn=[],Ei=!1;for(let I=0;I<=On;I++){let _e=Math.floor(On*.95);if(I>=_e&&Es<_e&&typeof t?.onAskUser=="function"){Es=_e;try{let q="Agent has been running for a long time. Do you want to continue execution?",ee=[{id:"continue",label:"Continue",description:"Add few more steps"},{id:"cancel",label:"Cancel",description:"Stop extending and finish current turn limit"}],M=await t.onAskUser(q,ee);M&&(M.toLowerCase().includes("continue")||M==="Continue")&&(On+=ua)}catch{}}if(Kn.length>=10&&typeof t?.onAskUser=="function"){let q={},ee=null;for(let M of Kn)if(q[M]=(q[M]||0)+1,q[M]>=10){ee=M;break}if(ee)try{let M="Agent seems stuck in a tool loop. You can prompt it to steer or break the loop:",gt=[{id:"continue",label:"Continue Anyway",description:"Ignore warning and let it proceed"},{id:"stop",label:"Stop Loop",description:"Force agent to summarize progress and stop repeating"}],Le=await t.onAskUser(M,gt);if(Le){let Ke="";typeof Le=="string"&&(Le.toLowerCase()==="stop"||Le.includes("Stop Loop"))?Ke="STOP REPEATING THE SAME TOOL CALL. Acknowledge what failed or succeeded, summarize your current findings, and conclude.":typeof Le=="string"&&(Le.toLowerCase()==="continue"||Le.includes("Continue Anyway"))?Kn=Kn.filter(It=>It!==ee):Ke=typeof Le=="string"?Le:Le?.label||Le?.id||"",Ke&&(b.length>0&&b[b.length-1].role==="user"?b[b.length-1].text+=`
715
714
 
716
- [STEERING HINT from USER, High Priority] ${Ke.trim()} [/STEERING HINT]`:b.push({role:"user",text:`[STEERING HINT from USER, High Priority] ${Ke.trim()} [/STEERING HINT]`}),yield{type:"status",content:"Steering Hint Injected..."},jn=jn.filter(It=>It!==B))}}catch{}}let qt=await $i("agent",t);if(!qt.allowed)throw new Error(qt.reason||`Budget Exhausted for Provider (${s||"Agent"})`);let Ie=[];if(Vo=!1,(a==="ICU"||a==="FluxCU")&&!Ai)try{yield{type:"status",content:"Capturing Screen"},await new Promise($=>setTimeout($,1e3));let{captureGriddedScreenshot:X}=await import("./screen_grid-M5K7ZHKD.js"),B=await X();if(B&&B.base64){let $="[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]",pt={inlineData:{mimeType:B.mimeType,data:B.base64}},Fe=p?.imageHistoryCU||"Standard",Ke=Fe==="Low"?3:Fe==="Extended"?10:Fe==="Max"?999:5,It=b.filter(Ee=>Array.isArray(Ee.parts)&&Ee.parts.some(vt=>vt.inlineData));if(It.length>=Ke){let Ee=It.length-Ke+1;for(let vt=0;vt<Ee;vt++){let gt=It[vt];Array.isArray(gt.parts)&&(gt.parts=gt.parts.filter(bt=>!bt.inlineData))}}if(b.length>0&&b[b.length-1].role==="user"){let Ee=b[b.length-1];typeof Ee.text=="string"&&(Ee.text+=`
715
+ [STEERING HINT from USER, High Priority] ${Ke.trim()} [/STEERING HINT]`:b.push({role:"user",text:`[STEERING HINT from USER, High Priority] ${Ke.trim()} [/STEERING HINT]`}),yield{type:"status",content:"Steering Hint Injected..."},Kn=Kn.filter(It=>It!==ee))}}catch{}}let qt=await Ni("agent",t);if(!qt.allowed)throw new Error(qt.reason||`Budget Exhausted for Provider (${s||"Agent"})`);let Ie=[];if(Vo=!1,(a==="ICU"||a==="FluxCU")&&!Ei)try{yield{type:"status",content:"Capturing Screen"},await new Promise(M=>setTimeout(M,1e3));let{captureGriddedScreenshot:q}=await import("./screen_grid-IWNA3DA2.js"),ee=await q();if(ee&&ee.base64){let M="[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]",gt={inlineData:{mimeType:ee.mimeType,data:ee.base64}},Le=p?.imageHistoryCU||"Standard",Ke=Le==="Low"?3:Le==="Extended"?10:Le==="Max"?999:5,It=b.filter(Ee=>Array.isArray(Ee.parts)&&Ee.parts.some(vt=>vt.inlineData));if(It.length>=Ke){let Ee=It.length-Ke+1;for(let vt=0;vt<Ee;vt++){let mt=It[vt];Array.isArray(mt.parts)&&(mt.parts=mt.parts.filter(bt=>!bt.inlineData))}}if(b.length>0&&b[b.length-1].role==="user"){let Ee=b[b.length-1];typeof Ee.text=="string"&&(Ee.text+=`
717
716
 
718
- ${$}`,Array.isArray(Ee.parts)||(Ee.parts=[{text:Ee.text}]),Ee.parts.push(pt))}else b.push({role:"user",text:$,parts:[{text:$},pt]})}}catch(X){console.error("Vision screenshot capture error:",X)}if(Ai=!1,p?.compression===0&&(f?.tokens||0)>Vt&&(b=Fs(b,6)),v>0?yield{type:"status",content:process.env.HALLOWEEN_EEGG==="true"?"Haunting":"Working"}:yield{type:"status",content:process.env.HALLOWEEN_EEGG==="true"?"Consulting the spirits":"Connecting"},Et){try{let{clearPendingNudges:X}=await import("./subagent_state-LZCOZSUJ.js");X()}catch{}yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
717
+ ${M}`,Array.isArray(Ee.parts)||(Ee.parts=[{text:Ee.text}]),Ee.parts.push(gt))}else b.push({role:"user",text:M,parts:[{text:M},gt]})}}catch(q){console.error("Vision screenshot capture error:",q)}if(Ei=!1,p?.compression===0&&(f?.tokens||0)>Vt&&(b=Fs(b,6)),I>0?yield{type:"status",content:process.env.HALLOWEEN_EEGG==="true"?"Haunting":"Working"}:yield{type:"status",content:process.env.HALLOWEEN_EEGG==="true"?"Consulting the spirits":"Connecting"},Et){try{let{clearPendingNudges:q}=await import("./subagent_state-LZCOZSUJ.js");q()}catch{}yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
719
718
 
720
- \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}try{let{consumePendingNudges:X}=await import("./subagent_state-LZCOZSUJ.js"),B=X();if(B&&B.length>0){let $=B.join(`
719
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}try{let{consumePendingNudges:q}=await import("./subagent_state-LZCOZSUJ.js"),ee=q();if(ee&&ee.length>0){let M=ee.join(`
721
720
 
722
721
  `);b.length>0&&b[b.length-1].role==="user"?b[b.length-1].text+=`
723
722
 
724
- ${$}`:b.push({role:"user",text:$}),yield{type:"status",content:"Subagent Update"}}}catch{}if(i){let X=await i();X&&(X.startsWith("/btw")?b.length>0&&b[b.length-1].role==="user"?b[b.length-1].text+=`
723
+ ${M}`:b.push({role:"user",text:M}),yield{type:"status",content:"Subagent Update"}}}catch{}if(i){let q=await i();q&&(q.startsWith("/btw")?b.length>0&&b[b.length-1].role==="user"?b[b.length-1].text+=`
725
724
 
726
725
  [system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
727
- [question] ${X.replace("/btw","").trim()} [/question]`:b.push({role:"user",text:`[system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
728
- [question] ${X.replace("/btw","").trim()} [/question]`}):b.length>0&&b[b.length-1].role==="user"?b[b.length-1].text+=`
726
+ [question] ${q.replace("/btw","").trim()} [/question]`:b.push({role:"user",text:`[system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
727
+ [question] ${q.replace("/btw","").trim()} [/question]`}):b.length>0&&b[b.length-1].role==="user"?b[b.length-1].text+=`
729
728
 
730
- [STEERING HINT from USER, High Priority] ${X.trim()} [/STEERING HINT]`:b.push({role:"user",text:`[STEERING HINT from USER, High Priority] ${X.trim()} [/STEERING HINT]`}),yield{type:"status",content:`${X.startsWith("/btw")?"Question Forwarded...":"Steering Hint Injected..."}`})}let me,Ue=!1,qe=1,Ze=1,Nt=Date.now(),Te=null,pe="",P=null,De=null,xt=null,un=0,He=[],Rt=0,En=!1,Bt=!1,Kn=!1,Xt=!1,Ln=!0,oo=0,_t="",ve="",ut=!1,nn=!1,je=!0,ne=e,We="",gn=c;for(c=c.toLowerCase()==="max"?"High":c;qe<=xn&&Ze<=xn&&!Ue&&!Et;){let X=!1;try{pe="",Ln&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},Ln=!1,Ze===1&&(_t=""));let B=m=>{if(!m||typeof m!="string")return m;let A="",C=gs(m);if(C&&(A=C.fullBlock,m=C.remainingText),!m.includes("[tool:")&&!m.includes("[action:"))return(p?.keepReasoningContext?A:"")+m;if(eo(m).length===0){let w=hi(m);return(p?.keepReasoningContext?A:"")+w}m=m.replace(gl,(w,R)=>R.includes("[tool:")||R.includes("[action:")?R.trim():w);let le="",F=0,Q=[],St="";for(;F<m.length;){let w=m.indexOf("[tool:",F),R=m.indexOf("[action:",F),oe=-1;if(w!==-1&&R!==-1?oe=Math.min(w,R):w!==-1?oe=w:oe=R,oe===-1){Q.length===0&&(le+=hi(m.substring(F)));break}if((oe>0?m[oe-1]:"")==="`"){le+=hi(m.substring(F,oe+1)),F=oe+1;continue}Q.length===0&&(St=hi(m.substring(F,oe)));let Z=-1,M=null,kt=0;for(let Wt=oe;Wt<m.length;Wt++){let ie=m[Wt];if(M){if(ie===M){let Xe=0;for(let Tt=Wt-1;Tt>=0&&m[Tt]==="\\";Tt--)Xe++;Xe%2===0&&(M=null)}}else if(ie==='"'||ie==="'"||ie==="`")M=ie;else if(ie==="(")kt++;else if(ie===")")kt--;else if(ie==="]"&&kt<=0){Z=Wt;break}}if(Z===-1){Q.length===0&&(le+=m.substring(oe));break}let Rn=m.substring(oe,Z+1);Q.push(Rn),F=Z+1}return Q.length>0&&(le=St.trimEnd()?St.trimEnd()+`
729
+ [STEERING HINT from USER, High Priority] ${q.trim()} [/STEERING HINT]`:b.push({role:"user",text:`[STEERING HINT from USER, High Priority] ${q.trim()} [/STEERING HINT]`}),yield{type:"status",content:`${q.startsWith("/btw")?"Question Forwarded...":"Steering Hint Injected..."}`})}let me,Ue=!1,qe=1,Ze=1,Nt=Date.now(),Te=null,pe="",O=null,Fe=null,xt=null,un=0,We=[],Rt=0,En=!1,Ut=!1,Vn=!1,Xt=!1,Ln=!0,oo=0,_t="",ve="",ut=!1,nn=!1,je=!0,ne=e,Ge="",gn=d;for(d=d.toLowerCase()==="max"?"High":d;qe<=bn&&Ze<=bn&&!Ue&&!Et;){let q=!1;try{pe="",Ln&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},Ln=!1,Ze===1&&(_t=""));let ee=m=>{if(!m||typeof m!="string")return m;let A="",C=ms(m);if(C&&(A=C.fullBlock,m=C.remainingText),!m.includes("[tool:")&&!m.includes("[action:"))return(p?.keepReasoningContext?A:"")+m;if(jn(m).length===0){let w=hi(m);return(p?.keepReasoningContext?A:"")+w}m=m.replace(ml,(w,R)=>R.includes("[tool:")||R.includes("[action:")?R.trim():w);let le="",F=0,J=[],St="";for(;F<m.length;){let w=m.indexOf("[tool:",F),R=m.indexOf("[action:",F),oe=-1;if(w!==-1&&R!==-1?oe=Math.min(w,R):w!==-1?oe=w:oe=R,oe===-1){J.length===0&&(le+=hi(m.substring(F)));break}if((oe>0?m[oe-1]:"")==="`"){le+=hi(m.substring(F,oe+1)),F=oe+1;continue}J.length===0&&(St=hi(m.substring(F,oe)));let Q=-1,P=null,kt=0;for(let Gt=oe;Gt<m.length;Gt++){let ie=m[Gt];if(P){if(ie===P){let Xe=0;for(let Tt=Gt-1;Tt>=0&&m[Tt]==="\\";Tt--)Xe++;Xe%2===0&&(P=null)}}else if(ie==='"'||ie==="'"||ie==="`")P=ie;else if(ie==="(")kt++;else if(ie===")")kt--;else if(ie==="]"&&kt<=0){Q=Gt;break}}if(Q===-1){J.length===0&&(le+=m.substring(oe));break}let Rn=m.substring(oe,Q+1);J.push(Rn),F=Q+1}return J.length>0&&(le=St.trimEnd()?St.trimEnd()+`
731
730
 
732
- `+Q.join(`
731
+ `+J.join(`
733
732
 
734
- `):Q.join(`
733
+ `):J.join(`
735
734
 
736
- `)),(p?.keepReasoningContext?A:"")+le},$=b.filter(m=>(m.role==="user"||m.role==="agent"||m.role==="system")&&!String(m.id).startsWith("welcome")&&!m.isMeta&&!m.isTerminalRecord&&!(m.text&&m.text.startsWith("[TERMINAL_RECORD]"))).map((m,A,C)=>{let J=m.text||"";E||(J=J.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),m.role==="agent"&&(J=B(J),J=J.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),J=J.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*"));let le=[];return Array.isArray(m.parts)&&m.parts.length>0?le=m.parts.map(F=>{if(F.text){let Q=F.text;return E||(Q=Q.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),m.role==="agent"&&(Q=B(Q),Q=Q.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),Q=Q.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*")),{text:Q}}return F}):le=[{text:J}],m.binaryPart&&lt(ne)&&C.slice(A+1).filter(Q=>Q.role==="user"&&!Q.text?.startsWith("[ACTION RESULT]")&&!Q.text?.startsWith("[TOOL RESULT]")).length<=2&&le.push(m.binaryPart),{role:m.role==="user"||m.role==="system"?"user":"model",parts:le}});for(let m=$.length-2;m>=0;m--){let A=$[m],C=$[m+1];A.role==="user"&&C.role==="user"&&(C.parts?.[0]?.text||"").trim().startsWith("[SYSTEM")&&$.splice(m,1)}let pt=[];for(let m=0;m<$.length;m++){let A=$[m];if(pt.length===0)pt.push(A);else{let C=pt[pt.length-1];C.role===A.role?(C.parts[0].text+=`
735
+ `)),(p?.keepReasoningContext?A:"")+le},M=b.filter(m=>(m.role==="user"||m.role==="agent"||m.role==="system")&&!String(m.id).startsWith("welcome")&&!m.isMeta&&!m.isTerminalRecord&&!(m.text&&m.text.startsWith("[TERMINAL_RECORD]"))).map((m,A,C)=>{let X=m.text||"";E||(X=X.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),m.role==="agent"&&(X=ee(X),X=X.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),X=X.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*"));let le=[];return Array.isArray(m.parts)&&m.parts.length>0?le=m.parts.map(F=>{if(F.text){let J=F.text;return E||(J=J.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),m.role==="agent"&&(J=ee(J),J=J.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),J=J.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*")),{text:J}}return F}):le=[{text:X}],m.binaryPart&&lt(ne)&&C.slice(A+1).filter(J=>J.role==="user"&&!J.text?.startsWith("[ACTION RESULT]")&&!J.text?.startsWith("[TOOL RESULT]")).length<=2&&le.push(m.binaryPart),{role:m.role==="user"||m.role==="system"?"user":"model",parts:le}});for(let m=M.length-2;m>=0;m--){let A=M[m],C=M[m+1];A.role==="user"&&C.role==="user"&&(C.parts?.[0]?.text||"").trim().startsWith("[SYSTEM")&&M.splice(m,1)}let gt=[];for(let m=0;m<M.length;m++){let A=M[m];if(gt.length===0)gt.push(A);else{let C=gt[gt.length-1];C.role===A.role?(C.parts[0].text+=`
737
736
 
738
- `+(A.parts?.[0]?.text||""),A.parts?.length>1&&C.parts.push(...A.parts.slice(1))):pt.push(A)}}for(let m of pt)for(let A of m.parts||[])A&&typeof A.text=="string"&&(A.text.includes("[action:")||A.text.includes("[tool:"))&&(A.text=A.text.replace(/```(?:[a-zA-Z0-9_-]+)?\s*\n?(\[(?:action|tool):[\s\S]*?\)\s*\])\n?```/gi,"$1"),A.text=A.text.replace(/`(\[(?:action|tool):[\s\S]*?\)\s*\])`/gi,"$1"));$.length=0,$.push(...pt),ne=e;let Fe=`${h}|${s}|${a}|${c}|${gn}|${ne}|${JSON.stringify(r)}|${!!p?.dynamicDirAwareness}|${!!p?.subAgents}`,Ke=Qn.key===Fe&&Qn.value;if((process.env.I_HAVE_TOO_MUCH_MONEY==="true"||process.env.I_HAVE_TOO_MUCH_MONEY===!0)&&(Ke=!1),Ke)We=Qn.value;else{let m=s==="Mistral"?!!ei(ne):!(ne||"gemma").toLowerCase().startsWith("gemma");We=Er(r,((ne||"gemma").toLowerCase().startsWith("gemma"),gn),a,p,E,T,s,s==="Google"?!0:y,m,h,!!p?.keepReasoningContext,ne),p?.dynamicDirAwareness||(We+=`
737
+ `+(A.parts?.[0]?.text||""),A.parts?.length>1&&C.parts.push(...A.parts.slice(1))):gt.push(A)}}for(let m of gt)for(let A of m.parts||[])A&&typeof A.text=="string"&&(A.text.includes("[action:")||A.text.includes("[tool:"))&&(A.text=A.text.replace(/```(?:[a-zA-Z0-9_-]+)?\s*\n?(\[(?:action|tool):[\s\S]*?\)\s*\])\n?```/gi,"$1"),A.text=A.text.replace(/`(\[(?:action|tool):[\s\S]*?\)\s*\])`/gi,"$1"));M.length=0,M.push(...gt),ne=e;let Le=`${h}|${s}|${a}|${d}|${gn}|${ne}|${JSON.stringify(r)}|${!!p?.dynamicDirAwareness}|${!!p?.subAgents}`,Ke=Zn.key===Le&&Zn.value;if((process.env.I_HAVE_TOO_MUCH_MONEY==="true"||process.env.I_HAVE_TOO_MUCH_MONEY===!0)&&(Ke=!1),Ke)Ge=Zn.value;else{let m=s==="Mistral"?!!ei(ne):!(ne||"gemma").toLowerCase().startsWith("gemma");Ge=Er(r,((ne||"gemma").toLowerCase().startsWith("gemma"),gn),a,p,E,T,s,s==="Google"?!0:y,m,h,!!p?.keepReasoningContext,ne),p?.dynamicDirAwareness||(Ge+=`
739
738
  ${la.replace(`
740
739
  **Directory**`,`
741
- -- Directory --`)}`),Qn.key=Fe,Qn.value=We}let Ee=$[$.length-1];if(go()&v>0){await new Promise(J=>setTimeout(J,2500)),yield{type:"status",content:"Verifying"};let m=await Jn(),A=m?m.diagnostics:null,C=xs(m?.comments);A&&Ee&&Ee.role==="user"&&Ee.parts?.[0]?.text&&(Ee.parts[0].text+=`
740
+ -- Directory --`)}`),Zn.key=Le,Zn.value=Ge}let Ee=M[M.length-1];if(go()&I>0){await new Promise(X=>setTimeout(X,2500)),yield{type:"status",content:"Verifying"};let m=await Qn(),A=m?m.diagnostics:null,C=xs(m?.comments);A&&Ee&&Ee.role==="user"&&Ee.parts?.[0]?.text&&(Ee.parts[0].text+=`
742
741
 
743
- ${A}`),xi&&Ee&&Ee.role==="user"&&Ee.parts?.[0]?.text&&(Ee.parts[0].text+=`
742
+ ${A}`),bi&&Ee&&Ee.role==="user"&&Ee.parts?.[0]?.text&&(Ee.parts[0].text+=`
744
743
 
745
744
  [Additional Comments]
746
745
  ${C}`),yield{type:"status",content:"Working"}}let vt=s==="Mistral"||s==="Google"&&e?.toLowerCase().startsWith("gemma");if(p?.advanceRollback&&Ee&&Ee.role==="user"&&(Ee.parts?.[0]?.text?.startsWith("[ACTION RESULT]")||Ee.parts?.[0]?.text?.startsWith("[TOOL RESULT]")))try{let m=await Ro.getLatestFileChanges(h);if(m&&(m.newFiles.length>0||m.modifiedFiles.length>0||m.deletedFiles.length>0)){let A=`
747
746
  [system] File Changes:
748
- `;for(let J of m.newFiles)A+=`* ${J} (created)
749
- `;for(let J of m.modifiedFiles)A+=`* ${J} (modified)
750
- `;for(let J of m.deletedFiles)A+=`* ${J} (deleted)
751
- `;A+="[/system]",Ee.parts[0].text+=A;let C=-1;for(let J=b.length-1;J>=0;J--)if(b[J].role==="user"&&(b[J].text?.startsWith("[ACTION RESULT]")||b[J].text?.startsWith("[TOOL RESULT]"))){C=J;break}C!==-1&&(b[C].text+=A)}}catch{}let gt=Math.floor(On*.99),bt=v+1;if(bt>=gt&&Ee&&Ee.parts?.[0]&&(Ee.parts[0].text+=`
752
- [system] WARNING, Turn Limit Impending: Step ${bt}/${On}. Wrap up quickly/prompt user to continue. [/system]`),process.env.LOG_CHAT==="true"||process.env.LOG_CHAT==="1"||process.env.LOG_CHAT===!0||!1){let m=W.join(wn,"chats",String(h));Ae.existsSync(m)||Ae.mkdirSync(m,{recursive:!0}),Ae.writeFileSync(W.join(m,"context.json"),JSON.stringify({contents:$},null,2)),Ae.writeFileSync(W.join(m,"system.md"),`${Ke?"CACHED":"NOT CACHED"}
753
- Key: ${Fe}
747
+ `;for(let X of m.newFiles)A+=`* ${X} (created)
748
+ `;for(let X of m.modifiedFiles)A+=`* ${X} (modified)
749
+ `;for(let X of m.deletedFiles)A+=`* ${X} (deleted)
750
+ `;A+="[/system]",Ee.parts[0].text+=A;let C=-1;for(let X=b.length-1;X>=0;X--)if(b[X].role==="user"&&(b[X].text?.startsWith("[ACTION RESULT]")||b[X].text?.startsWith("[TOOL RESULT]"))){C=X;break}C!==-1&&(b[C].text+=A)}}catch{}let mt=Math.floor(On*.99),bt=I+1;if(bt>=mt&&Ee&&Ee.parts?.[0]&&(Ee.parts[0].text+=`
751
+ [system] WARNING, Turn Limit Impending: Step ${bt}/${On}. Wrap up quickly/prompt user to continue. [/system]`),process.env.LOG_CHAT==="true"||process.env.LOG_CHAT==="1"||process.env.LOG_CHAT===!0||!1){let m=U.join(wn,"chats",String(h));Ae.existsSync(m)||Ae.mkdirSync(m,{recursive:!0}),Ae.writeFileSync(U.join(m,"context.json"),JSON.stringify({contents:M},null,2)),Ae.writeFileSync(U.join(m,"system.md"),`${Ke?"CACHED":"NOT CACHED"}
752
+ Key: ${Le}
754
753
  --------------------------------------------------------------------
755
754
 
756
- ${We}`)}let Dt=new Promise((m,A)=>{G.signal.aborted&&A(new DOMException("The user aborted a request.","AbortError")),G.signal.addEventListener("abort",()=>{A(new DOMException("The user aborted a request.","AbortError"))})});Dt.catch(()=>{});let Ge=$;if(Nt=Date.now(),s==="Ollama")me=(await ce("Ollama"))(t.apiKey,ne,Ge,We,c,a,y,G.signal,1,p?.ollamaEndpoint||"Cloud");else if(s==="OpenRouter")me=(await ce("OpenRouter"))(t.apiKey,ne,Ge,We,c,a,y,G.signal,1,h);else if(s==="DeepSeek")me=(await ce("DeepSeek"))(t.apiKey,ne,Ge,We,c,a,y,G.signal,1);else if(s==="Mistral")me=(await ce("Mistral"))(t.apiKey,ne,Ge,We,c,a,y,G.signal,1,h);else if(s==="NVIDIA"){let m=(await ce("NVIDIA"))(t.apiKey,ne,Ge,We,c,a,y,G.signal,1);me=(await ce("NVIDIA_wrap"))(m,ne)}else if(s==="InferX")me=(await ce("InferX"))(t.apiKey,ne,Ge,We,c,a,y,G.signal,1);else if(s==="SenseNova")me=(await ce("SenseNova"))(t.apiKey,ne,Ge,We,c,a,y,G.signal,1);else if(s==="AIHubMix")me=(await ce("AIHubMix"))(t.apiKey,ne,Ge,We,c,a,y,G.signal,1);else if(s==="Poolside")me=(await ce("Poolside"))(t.apiKey,ne,Ge,We,c,a,y,G.signal,1);else if(s==="9router"||s==="9Router")me=(await ce("NineRouter"))(t.apiKey,ne,Ge,We,c,a,y,G.signal,1);else if(s==="ExpLabs"||s==="ExperientialLabs")me=(await ce("ExpLabs"))(t.apiKey,ne,Ge,We,c,a,y,G.signal,1);else if(s==="Infron"||s==="infron")me=(await ce("Infron"))(t.apiKey,ne,Ge,We,c,a,y,G.signal,1);else if(s==="TokenHarbor"||s==="Token Harbor"||s==="tokenharbor"||s==="token_harbor"||s==="thk")me=(await ce("TokenHarbor"))(t.apiKey,ne,Ge,We,c,a,y,G.signal,1);else if(s==="APInex"||s==="apinex"||s==="apx")me=(await ce("APInex"))(t.apiKey,ne,Ge,We,c,a,y,G.signal,1);else if(s==="xKiro"||s==="xkiro"||s==="kiro")me=(await ce("xKiro"))(t.apiKey,ne,Ge,We,c,a,y,G.signal,1);else if(s==="c_openai"||s==="Custom (OpenAI)"){let m=p?.customOpenAIBaseUrl||"";try{m=await Oi("c_openai")||m}catch{}me=(await ce("c_openai"))(t.apiKey,ne,Ge,We,c,a,y,G.signal,1,m)}else{let m=hs(t?.apiKey),{serviceTier:A,cleanModel:C}=aa(ne),J={systemInstruction:We,mediaResolution:"MEDIA_RESOLUTION_HIGH",safetySettings:[{category:Hn.HARM_CATEGORY_HARASSMENT,threshold:Gn.BLOCK_NONE},{category:Hn.HARM_CATEGORY_HATE_SPEECH,threshold:Gn.BLOCK_NONE},{category:Hn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Gn.BLOCK_NONE},{category:Hn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Gn.BLOCK_NONE}],temperature:1.05,thinkingConfig:(()=>{let F=Ds("Google",ne||"gemini-3-flash-preview",c);if(F!==null){if(typeof F=="object")return F;if(F===!1||F==="false"||F==="none"||F===0||F==="0")return{includeThoughts:!1};if(typeof F=="number")return{includeThoughts:!0,thinkingBudget:F};if(typeof F=="string"){let R=F.toLowerCase();if(R==="minimal")return{includeThoughts:!0,thinkingLevel:Ye.MINIMAL};if(R==="low")return{includeThoughts:!0,thinkingLevel:Ye.LOW};if(R==="medium")return{includeThoughts:!0,thinkingLevel:Ye.MEDIUM};if(R==="high")return{includeThoughts:!0,thinkingLevel:Ye.HIGH};let oe=Number(F);if(!isNaN(oe))return{includeThoughts:!0,thinkingBudget:oe}}}let Q=(ne||"").toLowerCase(),St=Q.includes("gemma-4")||Q.startsWith("gemma"),w=Q.includes("gemini-3");if(St||w)return St?c.toLowerCase()!=="high"?{includeThoughts:!1,thinkingLevel:Ye.MINIMAL}:{includeThoughts:!0,thinkingLevel:Ye.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:Q.includes("pro")?Ye.LOW:Ye.MINIMAL,Low:Ye.LOW,Medium:Ye.MEDIUM,Standard:Ye.MEDIUM,High:Ye.HIGH,xHigh:Ye.HIGH}[c]||Ye.MEDIUM};{let R={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[c]||2048;return R===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:R}}})()};A&&(J.serviceTier=A);let le=m.models.generateContentStream({model:C||"gemini-3-flash-preview",contents:Ge,config:J},{signal:G.signal});me=await Promise.race([le,Dt])}pe="",P=null,xt=null,He=[],Rt=0,yield{type:"model_update",content:null},ve="",ut=_t.length>0;let Ut="",io=Date.now(),Yn=async function*(){if(s==="Google"&&Ut){let m=xo(Ut);for(let A of m)yield A;Ut="",io=Date.now()}},Rs=!0,Cn="",so=!1,wt=null,_s=!1,zn=!1,ro=!1,Yo=!1,$n=!1,yo=m=>{let A=0;for(;A+2<m.length;)m[A]==="`"&&m[A+1]==="`"&&m[A+2]==="`"?(Yo=!Yo,A+=3):A++},vs=m=>{if(!m)return;let A=/(?:<(\/?)think_fluxflow[^>]*>|\[(\/?)think_fluxflow\]|<\/?channel\|?>|<\|channel>thought)/gi,C;for(;(C=A.exec(m))!==null;){let J=C[0].toLowerCase();J.startsWith("</")||J.startsWith("[/")||J==="<channel|>"?$n=!1:$n=!0}},ha={tool:{startPrefix:"[tool",fullPrefix:"[tool:",endTag:"]"},action:{startPrefix:"[action",fullPrefix:"[action:",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|>"}},xo=m=>{let A=[],C=m,J=le=>{if(!le)return;if(!_s){A.push({type:"text",content:le}),yo(le),vs(le);return}let F=/(?:<(\/?)think_fluxflow[^>]*>|\[(\/?)think_fluxflow\]|<\/?channel\|?>|<\|channel>thought)/gi,Q=0,St;for(;(St=F.exec(le))!==null;){let R=le.substring(Q,St.index);if(R)if(yo(R),$n)A.push({type:"text",content:R});else{let Le=R.replace(/[^\r\n]/g,"");Le&&A.push({type:"text",content:Le})}let oe=St[0];yo(oe);let l=oe.toLowerCase();l.startsWith("</")||l.startsWith("[/")||l==="<channel|>"?$n=!1:$n=!0,A.push({type:"text",content:oe}),Q=F.lastIndex}let w=le.substring(Q);if(w)if(yo(w),$n)A.push({type:"text",content:w});else{let R=w.replace(/[^\r\n]/g,"");R&&A.push({type:"text",content:R})}};for(;C.length>0;)if(so){let le=Cn+C,F=ha[wt];if(F){let w=!1;if(le.length<F.startPrefix.length?F.startPrefix.startsWith(le)||(w=!0):le.startsWith(F.startPrefix)?le.length>=F.fullPrefix.length&&!le.startsWith(F.fullPrefix)&&(w=!0):w=!0,w){J(le),Cn="",so=!1,wt=null,zn=!1,ro=!1,C="";break}}let Q=-1,St=F?F.endTag:"]";if(wt==="tool"||wt==="action"){let w=0,R=null,oe=0,l=!1;for(let Le=0;Le<le.length;Le++){let Z=le[Le];if(R){if(Z===R){let M=0;for(let kt=Le-1;kt>=0&&le[kt]==="\\";kt--)M++;M%2===0&&(R=null)}}else if(Z==='"'||Z==="'")R=Z;else if(Z==="`")if(zn){Q=Le;break}else R=Z;else if(Z==="(")w++,l=!0;else if(Z===")")w--;else if(Z==="]"&&l&&w===0){Q=Le;break}}}else Q=le.indexOf(St);if(Q!==-1){let w=St.length,R=le.substring(0,Q+w);wt?.startsWith("kimi")||A.push({type:"text",content:R}),yo(R),vs(R),(wt==="tool"||wt==="action"||wt?.startsWith("kimi"))&&!zn&&!ro&&(_s=!0,jn.push(R.trim())),zn=!1,ro=!1,Cn="",so=!1,wt=null,C=le.substring(Q+w)}else{Cn=le,C="";break}}else{let le=C.indexOf("[tool"),F=C.indexOf("[action"),Q=C.indexOf("[[END]]"),St=C.indexOf("<|tool_calls_section_begin|>"),w=C.indexOf("<|tool_call_begin|>"),R=[{type:"tool",idx:le,start:"[tool",end:"]"},{type:"action",idx:F,start:"[action",end:"]"},{type:"end",idx:Q,start:"[[END]]",end:"[[END]]"},{type:"kimi_section",idx:St,start:"<|tool_calls_section_begin|>",end:"<|tool_calls_section_end|>"},{type:"kimi_call",idx:w,start:"<|tool_call_begin|>",end:"<|tool_call_end|>"}].filter(oe=>oe.idx!==-1).sort((oe,l)=>oe.idx-l.idx);if(R.length>0){let oe=R[0],l=C.substring(0,oe.idx);oe.idx>0&&J(l);let Le=oe.idx>0?C[oe.idx-1]:"";zn=Yo||Le==="`",ro=$n,so=!0,wt=oe.type,Cn="",C=C.substring(oe.idx)}else{let oe=["[tool","[action","[[END]]","<|tool_calls_section_begin|>","<|tool_call_begin|>"],l=-1;for(let Le of oe){for(let Z=Le.length-1;Z>0;Z--)if(C.endsWith(Le.substring(0,Z))){l=C.length-Z;let M=oe.indexOf(Le);M===0?wt="tool":M===1?wt="action":M===2?wt="end":M===3?wt="kimi_section":wt="kimi_call";break}if(l!==-1)break}if(l!==-1){if(l>0){let Z=C.substring(0,l);J(Z)}let Le=l>0?C[l-1]:"";zn=Yo||Le==="`",ro=$n,so=!0,Cn=C.substring(l),C=""}else{J(C);break}}}return A},ya=me[Symbol.asyncIterator]();for(;;){let{value:m,done:A}=await Promise.race([ya.next(),Dt]);if(A)break;if(m&&m.type==="status"){yield m;continue}let C="",J=m.candidates?.[0]?.content?.parts;if(J&&J.length>0)for(let F of J){let Q=typeof F.text=="string"?F.text:F.text?parseChunkText(F.text):"";F.thought?Q&&(X||(C+="<think_fluxflow>",X=!0),C+=Q):Q&&(X&&(C+="</think_fluxflow>",X=!1),C+=Q)}else m.text&&X&&(C+="</think_fluxflow>",X=!1);C=cl(C);let le=C?Ni(C):0;if(t&&typeof t.onTokenChunk=="function"&&t.onTokenChunk(C,le),Rs&&(Te===null&&(Te=Date.now()-Nt),yield{type:"status",content:process.env.HALLOWEEN_EEGG==="true"?"Performing dark ritual":"Thinking"},Rs=!1),Et){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
757
-
758
- \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(C){if(ut){if(ve+=C,ve.length>=64){let w=0,R=Math.min(_t.length,ve.length);for(let l=R;l>=10;l--)if(_t.endsWith(ve.substring(0,l))){w=l;break}let oe=ve.substring(w);if(oe){let Le=/(?:<think_fluxflow>|\[think_fluxflow\])(?:(?!(?:<\/think_fluxflow>|\[\/think_fluxflow\]))[\s\S])*$/i.test(_t)?oe.replace(/^\s*(?:<think_fluxflow>|\[think_fluxflow\])\s*/gi,""):oe.replace(/^\s*(?:<think_fluxflow>|\[think_fluxflow\])[\s\S]*?(?:<\/think_fluxflow>|\[\/think_fluxflow\])\s*/gi,"").replace(/^\s*(?:<think_fluxflow>|\[think_fluxflow\])\s*/gi,"");if(Le)if(pe+=Le,s==="Google")Ut+=Le;else{yield*Yn();let Z=xo(Le);for(let M of Z)yield M}}ut=!1,ve=""}continue}else if(pe+=C,s==="Google")Ut+=C;else{yield*Yn();let w=xo(C);for(let R of w)yield R}let F=yl(pe);if(F.inside){nn=!0,xt||(xt=Date.now());let R={Ask:"ask",AskUser:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",FindFile:"find_file",find_file:"find_file",findfile:"find_file",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",wait:"wait",Answer:"answer",Steer:"steer",steer:"steer"}[F.toolName]||F.toolName,oe=F.args||"",l=null;if(["write_file","update_file","view_file","read_folder","find_file","write_pdf","write_docx","search_keyword","generate_image","file_map","invoke","invoke_sync","get_progress","await","wait","answer"].includes(R)){let Z=j(oe),M=Z.basename||Z.name||Z.path||Z.targetFile||Z.TargetFile||Z.directory||Z.file,kt=Z.keyword,Rn=Z.title||Z.task,Wt=Z.id||Z.taskId,ie=Z.timeout||Z.time||Z.seconds||Z.sec;if(kt!=null)l=String(kt).replace(Mn,"");else if(M)l=W.basename(String(M).replace(Mn,"").replace(Qr,"/"));else if(Rn&&(R==="invoke"||R==="invoke_sync"))l=String(Rn).replace(Mn,"").substring(0,30);else if(Wt&&R==="get_progress")l=String(Wt).replace(Mn,"");else if(ie&&R==="await"){let Xe=parseFloat(String(ie).replace(Mn,""));isNaN(Xe)?l=String(ie).replace(Mn,""):(Xe<5&&(Xe=5),Xe>120&&(Xe=180),l=(Gt=>{if(Gt>=60){let wo=Math.floor(Gt/60),_n=Gt%60;return`${wo}m${_n>0?` ${_n}s`:""}`}return`${Gt}s`})(Xe))}else if(ie&&R==="wait"){let Xe=parseFloat(String(ie).replace(Mn,""));isNaN(Xe)?l=String(ie).replace(Mn,""):(Xe<10&&(Xe=10),Xe>120&&(Xe=120),l=(Gt=>{if(Gt>=60){let wo=Math.floor(Gt/60),_n=Gt%60;return`${wo}m${_n>0?` ${_n}s`:""}`}return`${Gt}s`})(Xe))}else{let Xe=oe.match(rl);if(Xe){let Tt=Xe[1].replace(Mn,"");R==="invoke"||R==="invoke_sync"||R==="get_progress"?l=Tt.substring(0,30):l=R==="search_keyword"||R==="file_map"?Tt:W.basename(Tt.replace(Qr,"/"))}}}let Le=`${ms[R]||R}${l?` ${l}`:""}`;if((R!==P||l!==De)&&(P=R,De=l,yield{type:"status",content:`${Le}`},process.stdout.isTTY)){let M={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",FindFile:"Finding File",find_file:"Finding File",Run:"Executing",Ask:"User Input Required",AskUser:"User Input Required",Memory:"Updating Memory",GenerateImage:"Generating",InvokeSync:"Sub-Agent Working",invoke_sync:"Sub-Agent Working",Invoke:"Working",invoke:"Working",GetProgress:"Checking Progress",get_progress:"Checking Progress",Cancel:"Stopping Generalist",cancel:"Stopping Generalist",Await:"Waiting",await:"Waiting",wait:"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"}[R]||"Working";process.stdout.write(`\x1B]0;${M}...\x07`)}}if(pe.length-oo>800){oo=pe.length;let w=ra(pe,!1),R=gs(w),oe=R?(R.innerContent||"").trim():"",l=oe.split(/[.!?]\s+/).filter(be=>be.trim().length>10),Le=new Set(l),Z=l.length>25?(l.length-Le.size)/l.length:0,M=oe.split(/\s+/).filter(be=>be.length>0).length,kt=.9,Rn=.92,Wt=!1;if(s.toLowerCase().includes("google")&&(ne||"").toLowerCase().startsWith("gemma")){let d={low:2048,medium:4096,high:32768,max:65536,xhigh:65536}[c?.toLowerCase()]||16e3;Wt=M>d}if(Z>kt||Wt){yield{type:"status",content:`${Z>kt?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},Bt=!0,await new Promise(d=>setTimeout(d,3e3));break}let Tt=na(pe).trim().split(/[.!?]\s+/).filter(be=>be.trim().length>10),Gt=new Set(Tt);if((Tt.length>25?(Tt.length-Gt.size)/Tt.length:0)>Rn){yield{type:"status",content:"Response Loop Detected. Re-centering..."},Bt=!1,Xt=!0,await new Promise(be=>setTimeout(be,3e3));break}let _n=w.replace(Za,"").replace(el,"").replace(tl,"").replace(nl,""),Mt=_n.toLowerCase().split(/\s+/).map(be=>be.replace(ol,"")).filter(be=>be.length>0),bn=!1;if(Mt.length>=40)for(let be=1;be<=15;be++){let d=Math.max(8,Math.ceil(25/be));if(Mt.length<be*d)continue;let I=Mt.slice(Mt.length-be),V=I.join(" ");if(be>1&&V===I.slice(0,Math.floor(be/2)).join(" ").repeat(2).trim())continue;let ye=!0;for(let se=1;se<d;se++)if(Mt.slice(Mt.length-be*(se+1),Mt.length-be*se).join(" ")!==V){ye=!1;break}if(ye){bn=!0;break}}if(!bn){let be=_n.toLowerCase().replace(il,"");if(be.length>=80)for(let d=1;d<=10;d++){let I=Math.max(15,Math.ceil(45/d));if(be.length<d*I)continue;let V=be.substring(be.length-d),ye=!0;for(let se=1;se<I;se++)if(be.substring(be.length-d*(se+1),be.length-d*se)!==V){ye=!1;break}if(ye){bn=!0;break}}}if(bn){yield{type:"status",content:"Stuttering Detected. Re-centering..."},Bt=!1,Kn=!0,await new Promise(be=>setTimeout(be,3e3));break}}let Q=Kt(pe),St=eo(Q);for(;St.length>Rt;){yield*Yn();let w=St[Rt],R=Date.now(),l={Ask:"ask",AskUser:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",FindFile:"find_file",find_file:"find_file",findfile:"find_file",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",Wait:"wait",wait:"wait",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"}[w.toolName]||w.toolName,Le=ms[l]||w.toolName,Z=Zn(l,w.args);yield{type:"status",content:`${Le}${Z?` ${Z}`:""}`};let M="";if(l==="click"){let d=j(w.args);M=`\u2714 Clicked ${d.intendedClickText?`: ${d.intendedClickText}`:"Screen"}`}else if(l==="drag"){let d=j(w.args);M=`\u2714 Dragged: Cell ${d.fromGridId||""} \u2192 Cell ${d.toGridId||""}`}else if(l==="scroll"){let d=j(w.args);M=`\u2714 Scrolled: ${d.direction||"down"} (${d.amount||1})`}else if(l==="keyboard_typing"){let d=j(w.args);M=`\u2714 ${d.autoPressEnter?"Entered":"Typed"}: ${d.text?`"${d.text.length>20?d.text.substring(0,20)+"...":d.text}"`:""}`}else if(l==="key_press")M=`\u2714 Pressed Key: ${j(w.args).key||""}`;else if(l==="recapture_screen")M="\u2714 Recaptured Screen";else if(l==="web_search"){let{query:d,limit:I=10,aiMode:V=!1}=j(w.args);M=`${d?"\u2714":"\u2718"} ${V?"AI Search":"Searched"}: ${d?`${d}`:"No Search Query"}${V===!1&&d?` \u2192 ${I}`:""}`}else if(l==="web_scrape"){let d=j(w.args).url||null;M=`${d?"\u2714":"\u2718"} Visited: ${d||"No Source"}`}else if(l==="view_file"){let{path:d,StartLine:I,EndLine:V,start_line:ye,end_line:se,startLine:te,endLine:we}=j(w.args),ke=I||ye||te,ee=V||se||we,N=parseInt(ke)||1,z=parseInt(ee)||(ke?N+800:800),$e="...",Re=z,re=(d||"").trim().toLowerCase().replaceAll("\\","/");if(re.startsWith("#skill"))re.startsWith("#skill/global/fluxflow")||re.startsWith("#skills/global/fluxflow")||re.includes("#skill/fluxflow")||re.includes("#skills/fluxflow")?M="\u2714 Read Documentation":M=`\u2714 Read Skill: ${W.basename(d.replaceAll("\\","/"))}`;else{try{let xe=W.resolve(process.cwd(),d);if(Ae.existsSync(xe)){let U=Ae.readFileSync(xe,"utf8").split(`
759
- `).length;$e=U,!ke&&!ee&&U>800?Re=Math.min(50,U):Re=Math.min(z,U)}}catch{}let Pt=(d||"").toLowerCase(),on=Pt.endsWith(".pdf"),Ne=Pt.endsWith(".docx")||Pt.endsWith(".doc")||Pt.endsWith(".ppt")||Pt.endsWith(".pptx")||Pt.endsWith(".xls")||Pt.endsWith(".xlsx"),et=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(Pt);on||Ne?M=`${d.length>0?"\u2714":"\u2718"} ${d?`Analyzed: ${W.basename(d)}`:"Analyzed: File Not Found"}`:et?M=`${d.length>0?"\u2714":"\u2718"} ${d?`Processed: ${W.basename(d)}`:"Processed: File Not Found"}`:M=`${$e!=="..."?"\u2714":"\u2718"} Read: ${d?`${W.basename(d)} \u2192 ${$e!=="..."?`Lines ${N} - ${Re} of ${$e}`:"File Not Found"}`:"File Not Found"}`}}else if(l==="list_files"||l==="read_folder"){let d=l==="list_files"?"List":"Browsed",I=j(w.args).path||null,V=j(w.args).recurse||1;M=`${I?"\u2714":"\u2718"} ${d}: ${I?`${I==="."?`./${V>1?"*":""}`:`${I.replaceAll("\\","/")}${V>1?`${I.endsWith("/")?"*":"/*"}`:`${I.endsWith("/")?"":"/"}`}`}`:"No Folder Selected"}`}else if(l==="find_file"){let d=j(w.args),I=d.basename||d.name||d.path||d.file||d.query||"";M=`${I?"\u2714":"\u2718"} Located: ${I||"No Query"}`}else if(l==="write_file"||l==="update_file"){let d=l==="write_file"?"Created":"Edited",I=j(w.args),V=I.path||null,se=Object.entries(I).some(([te,we])=>te.startsWith("searchContent")&&typeof we=="string"&&we.startsWith("^LINE:"))?"\u1361":":";M=`${V?"\u2714":"\u2718"} ${d}${se} ${V?V.replaceAll("\\","/"):"No File Changes"}`}else if(l==="write_pdf"){let d=j(w.args).path||null;M=`${d?"\u2714":"\u2718"} Generated: ${d.replaceAll("\\","/")||"No PDF Generated"}`}else if(l==="write_docx"){let d=j(w.args).path||null;M=`${d?"\u2714":"\u2718"} Generated: ${d.replaceAll("\\","/")||"No Docx Generated"}`}else if(l==="file_map"){let d=j(w.args).path;M=`${d?"\u2714":"\u2718"} Indexed: ${d.replaceAll("\\","/")?""+d:"File Not Found"}`}else if(l.toLowerCase()==="search_keyword"||l.toLowerCase()==="todo")M="";else if(l.toLowerCase()==="generate_image"){let{path:d,outputPath:I,output:V}=j(w.args);M=`\u2714 Generated: ${d||I||V||"generated_image.png"}`}else if(l==="invoke_sync"||l==="InvokeSync"){let d=Zn(l,w.args);M=`\u2714 Called Generalist${d?`: ${d}`:""}`}else if(l==="Invoke"||l==="InvokeAsync"||l==="invoke"){let d=Zn(l,w.args);M=`\u2714 Started Generalist${d?`: ${d}`:""}`}else if(l==="get_progress"||l==="GetProgress"){let d=Zn(l,w.args);M=`\u2714 Checked${d?`: ${d}`:""}`}else if(l==="cancel"){let d=Zn(l,w.args);M=`\u{1F6C7} Cancelled${d?`: ${d}`:""}`}else if(l==="steer"||l==="Steer"){let d=Zn(l,w.args);M=`\u2714 Steered${d?`: ${d}`:""}`}else if(l==="EmergencyRollback"){let{method:d}=j(w.args);M=d==="forceRevert"?"":"\u2714 Rollback Point Checked"}else if(l==="await"||l==="Await"||l==="wait"||l==="Wait"){let{time:d,timeout:I,seconds:V,sec:ye}=j(w.args),se=parseFloat(V||ye||I||d)||45,te=l==="wait"||l==="Wait"?120:180;se<10&&(se=10),se>te&&(se=te);let we=N=>{if(N>=60){let z=Math.floor(N/60),$e=N%60;return`${z}m${$e>0?` ${$e}s`:""}`}return`${N}s`},ke=["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"];M=`\u2714 ${ke[Math.floor(Math.random()*ke.length)]} \u2192 ${we(se)}`}else l==="Answer"||l==="answer"?M="\u2714 Resolved Sub-Agent Query":l==="exec_command"||l==="ask"?M="":M=`Executed: ${w.toolName}`;if(yield*Yn(),l==="exec_command"){let{command:d}=j(w.args);if(d&&t.systemSettings&&t.systemSettings.allowExternalAccess===!1){let I=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],V=W.resolve(process.cwd()).substring(0,3).toLowerCase(),ye=ee=>{let N=[],z="",$e=null;for(let Re=0;Re<ee.length;Re++){let re=ee[Re];$e?(re===$e&&($e=null),z+=re):re==='"'||re==="'"?($e=re,z+=re):re==="&"&&ee[Re+1]==="&"||re==="|"&&ee[Re+1]==="|"?(z.trim()&&(N.push(z.trim()),z=""),Re++):re===";"||re==="|"||re==="&"?z.trim()&&(N.push(z.trim()),z=""):z+=re}return z.trim()&&N.push(z.trim()),N},se=ee=>{let N=[],z="",$e=null;for(let Re=0;Re<ee.length;Re++){let re=ee[Re];$e?(re===$e&&($e=null),z+=re):re==='"'||re==="'"?($e=re,z+=re):/\s/.test(re)?z&&(N.push(z),z=""):z+=re}return z&&N.push(z),N},te=ee=>{let N=ee.replace(/^['"]|['"]$/g,"").trim();return!N||process.platform==="win32"&&/^\/[a-zA-Z0-9?]+$/.test(N)?!1:I.some(z=>{if(z.source==="[a-zA-Z]:[\\\\\\/]"){let $e=N.match(/[a-zA-Z]:[\\\/]/i);return $e&&$e[0].toLowerCase()!==V}return z.test(N)})};if(ye(d).some(ee=>{let N=se(ee);if(N.length===0)return!1;let z=N[0].replace(/^['"]|['"]$/g,"").toLowerCase();if(["echo","printf","write-output"].includes(z)){let Re=!1;return N.some(re=>{let Ft=re.replace(/^['"]|['"]$/g,"");if(Ft===">"||Ft===">>"||Ft==="<")return Re=!0,!1;if(Ft.startsWith(">")||Ft.startsWith("<")){let Pt=Ft.replace(/^[><]+/,"");return te(Pt)}return Re?(Re=!1,te(re)):!1})}return N.some(Re=>te(Re))})){let ee='Access Denied. Prohibited from accessing external directories while "External Workspace Access" is disabled.';t.onExecStart&&t.onExecStart(d||"No Command"),yield{type:"exec_start"},await new Promise(N=>setTimeout(N,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${ee}`),await new Promise(N=>setTimeout(N,50)),t.onExecEnd&&t.onExecEnd(),He.push({role:"user",text:`[ACTION RESULT]: ERROR: ${ee}`}),yield{type:"tool_result",content:`[ACTION RESULT]: ERROR: ${ee}`},Rt++;continue}}t.onExecStart&&t.onExecStart(d||"No Command"),yield{type:"exec_start"}}let kt=j(w.args),Rn=kt.path||kt.targetPath||null;if(Rn){let d=t.systemSettings&&t.systemSettings.allowExternalAccess===!1,I=W.resolve(Rn),V=W.resolve(process.cwd());if(d&&!I.startsWith(V)){let ye="Access Denied. You are not allowed to access files outside the current workspace.";if(l==="write_file"||l==="update_file"){let te=`\u2718 ${l==="write_file"?"Write Canceled":"Edit Canceled"}: ${kt.path||"..."}`,we=115;process.stdout.isTTY&&(we=process.stdout.columns-5||120);let ke=Math.min(te.length+4,we),ee=`${te.padEnd(ke-2).substring(0,ke-2)}`;yield{type:"visual_feedback",content:jt(`${je?`
760
- `:""}${ee}
761
- `)},je=!1}He.push({role:"user",text:`[ACTION RESULT]: ERROR: ${ye}`}),yield{type:"tool_result",content:`[ACTION RESULT]: ERROR: ${ye}`},Rt++;continue}}if(t.onToolApproval){let d=t.systemSettings||{},I=d.autoExec,V=!1,ye="";if(l==="view_file"){let te=j(w.args);if(ye=te.path||te.targetPath||te.file||"",ye){let we=d.alwaysAskFiles||".env, .env.*, *.env";Is(ye,we)&&(V=!0)}}if(l==="write_file"||l==="update_file"||l==="exec_command"||V){let te=null,we=!1,ke=!1,ee=!1;if(V)we=!0,te=null;else if(l==="exec_command"){let{command:Ne}=j(w.args),et=(Ne||"").trim(),xe=(sn,Jt)=>{if(!Jt)return!1;let mn=Jt.split(",").map(Qt=>Qt.trim().toLowerCase()).filter(Boolean),st=sn.toLowerCase();return mn.some(Qt=>st.startsWith(Qt))},Ve=xe(et,d.alwaysAskCommands),U=xe(et,d.autoApproveCommands);if(ke=xe(et,d.autoDisallowCommands),Ve?we=!0:(U||d.autoApproveGit&&/^git\s+commit\b/i.test(et))&&(te="allow"),!we&&!te){if(d.networkAccess===!1){let Jt=et.trim().replace(/\s+/g," ").replace(/^['"]+|['"]+$/g,"").toLowerCase().split(" "),st=Jt[0].split("/").pop().split("\\").pop().replace(/\.exe$/,""),Qt=new Set(["curl","wget","httpie","xh","ssh","scp","sftp","rsync","ftp","lftp","tftp","telnet","nc","netcat","socat","ping","traceroute","tracert","dig","nslookup","host","whois","nmap","docker","podman","kubectl","helm","gcloud","aws","az","terraform","ansible-playbook","nix","nix-env","apt","apt-get","dpkg","yum","dnf","pacman","zypper","brew","apk","choco","scoop","conda","mamba","aria2c","axel","smbclient","lynx","w3m","links","elinks","heroku","netlify","vercel","firebase","supabase","wrangler","flyctl","powershell","pwsh","certutil","bitsadmin","cloudflared","ngrok","tailscale","zerotier","rclone"]),rt=!1;Qt.has(st)&&(rt=!0);let tt=Nn=>Jt.slice(1).some(vn=>Nn.includes(vn)),mt=Nn=>{let vn=Jt.findIndex(In=>Nn.includes(In)),qn=Jt.findIndex(In=>["run","exec","test"].includes(In));return vn!==-1&&!(qn!==-1&&qn<vn)};st==="git"&&tt(["clone","pull","push","fetch"])&&(rt=!0),st==="go"&&tt(["get","install"])&&(rt=!0),st==="npm"&&mt(["install","i","update","add"])&&(rt=!0),st==="yarn"&&mt(["add","install","upgrade"])&&(rt=!0),st==="pnpm"&&mt(["add","install","update"])&&(rt=!0),st==="bun"&&mt(["add","install","update"])&&(rt=!0),st==="deno"&&tt(["install","add"])&&(rt=!0),st==="pip"&&tt(["install","download"])&&(rt=!0),st==="pip3"&&tt(["install","download"])&&(rt=!0),st==="cargo"&&tt(["install","add"])&&(rt=!0),["bash","sh","zsh","fish"].includes(st)&&tt(["-c"])&&(rt=!0),st==="cmd"&&tt(["/c"])&&(rt=!0),rt&&(te="deny",ee=!0)}!te&&ke&&(te="deny")}!we&&!te&&I&&(te="allow")}else(l==="write_file"||l==="update_file")&&I&&(te="allow");let N=te,z="";te==="deny"&&(ee?z="network":ke?z="settings":z="prohibited");let $e=!1,Re="",re=[],Ft=0,Pt=!1,on="";if(!N&&t.onToolApproval)try{let Ne=await t.onToolApproval(l,w.args,{checkOnly:!0});(Ne==="allow"||Ne==="deny")&&(N=Ne,N==="deny"&&(z="user"))}catch{}if(!N){if(l==="write_file"||l==="update_file")try{let xe=j(w.args),{path:Ve}=xe;if(Ve){let U=W.resolve(process.cwd(),Ve),sn=tt=>tt?tt.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,mt=>mt.toUpperCase()):"",Jt=sn(U),mn="",st=!1,Qt=await Jn(),rt=sn(Qt?.file_focused);if(Qt&&rt===Jt&&Qt.full_content?(mn=Qt.full_content,st=!0):Ae.existsSync(U)&&(mn=Ae.readFileSync(U,"utf8"),st=!0),Re=mn,await ti.recordFileChange(U,mn),st){let tt=mn;if(l==="write_file"){let mt=xe.content||xe.newContent||"";tt=mt.endsWith(`
762
- `)?mt:mt+`
763
- `,on=tt}else{let{patchPairs:mt,allowMultiple:Nn,error:vn}=Di(xe);if(vn){let rn=`[ACTION RESULT]: ERROR: ${vn}`;He.push({role:"user",text:rn}),await Lt("toolFailure"),t.onToolResult&&t.onToolResult("failure",l),yield{type:"tool_result",content:rn,toolName:l},Rt++;continue}let qn=xe.allowMultiple!==void 0?xe.allowMultiple===!0||String(xe.allowMultiple).toLowerCase()==="true":Nn;Ft=mt.length;let In=Ps(mn,mt,{allowMultiple:qn});tt=In.content,on=tt,re=In.results;let zo=re.filter(rn=>rn.success),Ri=re.filter(rn=>!rn.success);if(zo.length===0){let rn=`[ACTION RESULT]: ERROR: Failed to apply patches to [${W.basename(U)}].
764
- ${Ri.map(nt=>` \u2022 ${nt.error}`).join(`
765
- `)}`,_i=`\u2714 Edited: ${W.basename(U.replaceAll("\\","/"))}`,pn=115;process.stdout.isTTY&&(pn=process.stdout.columns-5||120);let Dn=Math.min(_i.length+4,pn),at=`${_i.padEnd(Dn-2).substring(0,Dn-2)}`;yield{type:"visual_feedback",content:jt(`${je?`
766
- `:""}${at}`)},je=!1,He.push({role:"user",text:rn}),await Lt("toolFailure"),t.onToolResult&&t.onToolResult("failure",l),yield{type:"tool_result",content:rn,toolName:l},Rt++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${W.basename(U)}`},Vi(U,mn,tt),$e=!0,await new Promise(mt=>setTimeout(mt,50))}else if(l==="write_file"){let tt=xe.content||xe.newContent||"",mt=tt.endsWith(`
755
+ ${Ge}`)}let Dt=new Promise((m,A)=>{W.signal.aborted&&A(new DOMException("The user aborted a request.","AbortError")),W.signal.addEventListener("abort",()=>{A(new DOMException("The user aborted a request.","AbortError"))})});Dt.catch(()=>{});let He=M;if(Nt=Date.now(),s==="Ollama")me=(await ce("Ollama"))(t.apiKey,ne,He,Ge,d,a,y,W.signal,1,p?.ollamaEndpoint||"Cloud");else if(s==="OpenRouter")me=(await ce("OpenRouter"))(t.apiKey,ne,He,Ge,d,a,y,W.signal,1,h);else if(s==="DeepSeek")me=(await ce("DeepSeek"))(t.apiKey,ne,He,Ge,d,a,y,W.signal,1);else if(s==="Mistral")me=(await ce("Mistral"))(t.apiKey,ne,He,Ge,d,a,y,W.signal,1,h);else if(s==="NVIDIA"){let m=(await ce("NVIDIA"))(t.apiKey,ne,He,Ge,d,a,y,W.signal,1);me=(await ce("NVIDIA_wrap"))(m,ne)}else if(s==="InferX")me=(await ce("InferX"))(t.apiKey,ne,He,Ge,d,a,y,W.signal,1);else if(s==="SenseNova")me=(await ce("SenseNova"))(t.apiKey,ne,He,Ge,d,a,y,W.signal,1);else if(s==="AIHubMix")me=(await ce("AIHubMix"))(t.apiKey,ne,He,Ge,d,a,y,W.signal,1);else if(s==="Poolside")me=(await ce("Poolside"))(t.apiKey,ne,He,Ge,d,a,y,W.signal,1);else if(s==="9router"||s==="9Router")me=(await ce("NineRouter"))(t.apiKey,ne,He,Ge,d,a,y,W.signal,1);else if(s==="ExpLabs"||s==="ExperientialLabs")me=(await ce("ExpLabs"))(t.apiKey,ne,He,Ge,d,a,y,W.signal,1);else if(s==="Infron"||s==="infron")me=(await ce("Infron"))(t.apiKey,ne,He,Ge,d,a,y,W.signal,1);else if(s==="TokenHarbor"||s==="Token Harbor"||s==="tokenharbor"||s==="token_harbor"||s==="thk")me=(await ce("TokenHarbor"))(t.apiKey,ne,He,Ge,d,a,y,W.signal,1);else if(s==="APInex"||s==="apinex"||s==="apx")me=(await ce("APInex"))(t.apiKey,ne,He,Ge,d,a,y,W.signal,1);else if(s==="xKiro"||s==="xkiro"||s==="kiro")me=(await ce("xKiro"))(t.apiKey,ne,He,Ge,d,a,y,W.signal,1);else if(s==="c_openai"||s==="Custom (OpenAI)"){let m=p?.customOpenAIBaseUrl||"";try{m=await Li("c_openai")||m}catch{}me=(await ce("c_openai"))(t.apiKey,ne,He,Ge,d,a,y,W.signal,1,m)}else{let m=ys(t?.apiKey),{serviceTier:A,cleanModel:C}=aa(ne),X={systemInstruction:Ge,mediaResolution:"MEDIA_RESOLUTION_HIGH",safetySettings:[{category:Hn.HARM_CATEGORY_HARASSMENT,threshold:Gn.BLOCK_NONE},{category:Hn.HARM_CATEGORY_HATE_SPEECH,threshold:Gn.BLOCK_NONE},{category:Hn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Gn.BLOCK_NONE},{category:Hn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Gn.BLOCK_NONE}],temperature:1.05,thinkingConfig:(()=>{let F=Ds("Google",ne||"gemini-3-flash-preview",d);if(F!==null){if(typeof F=="object")return F;if(F===!1||F==="false"||F==="none"||F===0||F==="0")return{includeThoughts:!1};if(typeof F=="number")return{includeThoughts:!0,thinkingBudget:F};if(typeof F=="string"){let R=F.toLowerCase();if(R==="minimal")return{includeThoughts:!0,thinkingLevel:Ye.MINIMAL};if(R==="low")return{includeThoughts:!0,thinkingLevel:Ye.LOW};if(R==="medium")return{includeThoughts:!0,thinkingLevel:Ye.MEDIUM};if(R==="high")return{includeThoughts:!0,thinkingLevel:Ye.HIGH};let oe=Number(F);if(!isNaN(oe))return{includeThoughts:!0,thinkingBudget:oe}}}let J=(ne||"").toLowerCase(),St=J.includes("gemma-4")||J.startsWith("gemma"),w=J.includes("gemini-3");if(St||w)return St?d.toLowerCase()!=="high"?{includeThoughts:!1,thinkingLevel:Ye.MINIMAL}:{includeThoughts:!0,thinkingLevel:Ye.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:J.includes("pro")?Ye.LOW:Ye.MINIMAL,Low:Ye.LOW,Medium:Ye.MEDIUM,Standard:Ye.MEDIUM,High:Ye.HIGH,xHigh:Ye.HIGH}[d]||Ye.MEDIUM};{let R={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[d]||2048;return R===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:R}}})()};A&&(X.serviceTier=A);let le=m.models.generateContentStream({model:C||"gemini-3-flash-preview",contents:He,config:X},{signal:W.signal});me=await Promise.race([le,Dt])}pe="",O=null,xt=null,We=[],Rt=0,yield{type:"model_update",content:null},ve="",ut=_t.length>0;let Wt="",io=Date.now(),zn=async function*(){if(s==="Google"&&Wt){let m=xo(Wt);for(let A of m)yield A;Wt="",io=Date.now()}},Rs=!0,Cn="",so=!1,wt=null,_s=!1,qn=!1,ro=!1,Yo=!1,$n=!1,yo=m=>{let A=0;for(;A+2<m.length;)m[A]==="`"&&m[A+1]==="`"&&m[A+2]==="`"?(Yo=!Yo,A+=3):A++},vs=m=>{if(!m)return;let A=/(?:<(\/?)think_fluxflow[^>]*>|\[(\/?)think_fluxflow\]|<\/?channel\|?>|<\|channel>thought)/gi,C;for(;(C=A.exec(m))!==null;){let X=C[0].toLowerCase();X.startsWith("</")||X.startsWith("[/")||X==="<channel|>"?$n=!1:$n=!0}},ya={tool:{startPrefix:"[tool",fullPrefix:"[tool:",endTag:"]"},action:{startPrefix:"[action",fullPrefix:"[action:",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|>"}},xo=m=>{let A=[],C=m,X=le=>{if(!le)return;if(!_s){A.push({type:"text",content:le}),yo(le),vs(le);return}let F=/(?:<(\/?)think_fluxflow[^>]*>|\[(\/?)think_fluxflow\]|<\/?channel\|?>|<\|channel>thought)/gi,J=0,St;for(;(St=F.exec(le))!==null;){let R=le.substring(J,St.index);if(R)if(yo(R),$n)A.push({type:"text",content:R});else{let $e=R.replace(/[^\r\n]/g,"");$e&&A.push({type:"text",content:$e})}let oe=St[0];yo(oe);let l=oe.toLowerCase();l.startsWith("</")||l.startsWith("[/")||l==="<channel|>"?$n=!1:$n=!0,A.push({type:"text",content:oe}),J=F.lastIndex}let w=le.substring(J);if(w)if(yo(w),$n)A.push({type:"text",content:w});else{let R=w.replace(/[^\r\n]/g,"");R&&A.push({type:"text",content:R})}};for(;C.length>0;)if(so){let le=Cn+C,F=ya[wt];if(F){let w=!1;if(le.length<F.startPrefix.length?F.startPrefix.startsWith(le)||(w=!0):le.startsWith(F.startPrefix)?le.length>=F.fullPrefix.length&&!le.startsWith(F.fullPrefix)&&(w=!0):w=!0,w){X(le),Cn="",so=!1,wt=null,qn=!1,ro=!1,C="";break}}let J=-1,St=F?F.endTag:"]";if(wt==="tool"||wt==="action"){let w=0,R=null,oe=0,l=!1;for(let $e=0;$e<le.length;$e++){let Q=le[$e];if(R){if(Q===R){let P=0;for(let kt=$e-1;kt>=0&&le[kt]==="\\";kt--)P++;P%2===0&&(R=null)}}else if(Q==='"'||Q==="'")R=Q;else if(Q==="`")if(qn){J=$e;break}else R=Q;else if(Q==="(")w++,l=!0;else if(Q===")")w--;else if(Q==="]"&&l&&w===0){J=$e;break}}}else J=le.indexOf(St);if(J!==-1){let w=St.length,R=le.substring(0,J+w);wt?.startsWith("kimi")||A.push({type:"text",content:R}),yo(R),vs(R),(wt==="tool"||wt==="action"||wt?.startsWith("kimi"))&&!qn&&!ro&&(_s=!0,Kn.push(R.trim())),qn=!1,ro=!1,Cn="",so=!1,wt=null,C=le.substring(J+w)}else{Cn=le,C="";break}}else{let le=C.indexOf("[tool"),F=C.indexOf("[action"),J=C.indexOf("[[END]]"),St=C.indexOf("<|tool_calls_section_begin|>"),w=C.indexOf("<|tool_call_begin|>"),R=[{type:"tool",idx:le,start:"[tool",end:"]"},{type:"action",idx:F,start:"[action",end:"]"},{type:"end",idx:J,start:"[[END]]",end:"[[END]]"},{type:"kimi_section",idx:St,start:"<|tool_calls_section_begin|>",end:"<|tool_calls_section_end|>"},{type:"kimi_call",idx:w,start:"<|tool_call_begin|>",end:"<|tool_call_end|>"}].filter(oe=>oe.idx!==-1).sort((oe,l)=>oe.idx-l.idx);if(R.length>0){let oe=R[0],l=C.substring(0,oe.idx);oe.idx>0&&X(l);let $e=oe.idx>0?C[oe.idx-1]:"";qn=Yo||$e==="`",ro=$n,so=!0,wt=oe.type,Cn="",C=C.substring(oe.idx)}else{let oe=["[tool","[action","[[END]]","<|tool_calls_section_begin|>","<|tool_call_begin|>"],l=-1;for(let $e of oe){for(let Q=$e.length-1;Q>0;Q--)if(C.endsWith($e.substring(0,Q))){l=C.length-Q;let P=oe.indexOf($e);P===0?wt="tool":P===1?wt="action":P===2?wt="end":P===3?wt="kimi_section":wt="kimi_call";break}if(l!==-1)break}if(l!==-1){if(l>0){let Q=C.substring(0,l);X(Q)}let $e=l>0?C[l-1]:"";qn=Yo||$e==="`",ro=$n,so=!0,Cn=C.substring(l),C=""}else{X(C);break}}}return A},xa=me[Symbol.asyncIterator]();for(;;){let{value:m,done:A}=await Promise.race([xa.next(),Dt]);if(A)break;if(m&&m.type==="status"){yield m;continue}let C="",X=m.candidates?.[0]?.content?.parts;if(X&&X.length>0)for(let F of X){let J=typeof F.text=="string"?F.text:F.text?parseChunkText(F.text):"";F.thought?J&&(q||(C+="<think_fluxflow>",q=!0),C+=J):J&&(q&&(C+="</think_fluxflow>",q=!1),C+=J)}else m.text&&q&&(C+="</think_fluxflow>",q=!1);C=dl(C);let le=C?Di(C):0;if(t&&typeof t.onTokenChunk=="function"&&t.onTokenChunk(C,le),Rs&&(Te===null&&(Te=Date.now()-Nt),yield{type:"status",content:process.env.HALLOWEEN_EEGG==="true"?"Performing dark ritual":"Thinking"},Rs=!1),Et){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
756
+
757
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(C){if(ut){if(ve+=C,ve.length>=64){let w=0,R=Math.min(_t.length,ve.length);for(let l=R;l>=10;l--)if(_t.endsWith(ve.substring(0,l))){w=l;break}let oe=ve.substring(w);if(oe){let $e=/(?:<think_fluxflow>|\[think_fluxflow\])(?:(?!(?:<\/think_fluxflow>|\[\/think_fluxflow\]))[\s\S])*$/i.test(_t)?oe.replace(/^\s*(?:<think_fluxflow>|\[think_fluxflow\])\s*/gi,""):oe.replace(/^\s*(?:<think_fluxflow>|\[think_fluxflow\])[\s\S]*?(?:<\/think_fluxflow>|\[\/think_fluxflow\])\s*/gi,"").replace(/^\s*(?:<think_fluxflow>|\[think_fluxflow\])\s*/gi,"");if($e)if(pe+=$e,s==="Google")Wt+=$e;else{yield*zn();let Q=xo($e);for(let P of Q)yield P}}ut=!1,ve=""}continue}else if(pe+=C,s==="Google")Wt+=C;else{yield*zn();let w=xo(C);for(let R of w)yield R}let F=xl(pe);if(F.inside){nn=!0,xt||(xt=Date.now());let R={Ask:"ask",AskUser:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",FindFile:"find_file",find_file:"find_file",findfile:"find_file",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",wait:"wait",Answer:"answer",Steer:"steer",steer:"steer"}[F.toolName]||F.toolName,oe=F.args||"",l=null;if(["write_file","update_file","view_file","read_folder","find_file","write_pdf","write_docx","search_keyword","generate_image","file_map","invoke","invoke_sync","get_progress","await","wait","answer"].includes(R)){let Q=j(oe),P=Q.basename||Q.name||Q.path||Q.targetFile||Q.TargetFile||Q.directory||Q.file,kt=Q.keyword,Rn=Q.title||Q.task,Gt=Q.id||Q.taskId,ie=Q.timeout||Q.time||Q.seconds||Q.sec;if(kt!=null)l=String(kt).replace(Mn,"");else if(P)l=U.basename(String(P).replace(Mn,"").replace(Qr,"/"));else if(Rn&&(R==="invoke"||R==="invoke_sync"))l=String(Rn).replace(Mn,"").substring(0,30);else if(Gt&&R==="get_progress")l=String(Gt).replace(Mn,"");else if(ie&&R==="await"){let Xe=parseFloat(String(ie).replace(Mn,""));isNaN(Xe)?l=String(ie).replace(Mn,""):(Xe<5&&(Xe=5),Xe>120&&(Xe=180),l=(Ht=>{if(Ht>=60){let wo=Math.floor(Ht/60),_n=Ht%60;return`${wo}m${_n>0?` ${_n}s`:""}`}return`${Ht}s`})(Xe))}else if(ie&&R==="wait"){let Xe=parseFloat(String(ie).replace(Mn,""));isNaN(Xe)?l=String(ie).replace(Mn,""):(Xe<10&&(Xe=10),Xe>120&&(Xe=120),l=(Ht=>{if(Ht>=60){let wo=Math.floor(Ht/60),_n=Ht%60;return`${wo}m${_n>0?` ${_n}s`:""}`}return`${Ht}s`})(Xe))}else{let Xe=oe.match(al);if(Xe){let Tt=Xe[1].replace(Mn,"");R==="invoke"||R==="invoke_sync"||R==="get_progress"?l=Tt.substring(0,30):l=R==="search_keyword"||R==="file_map"?Tt:U.basename(Tt.replace(Qr,"/"))}}}let $e=`${ps[R]||R}${l?` ${l}`:""}`;if((R!==O||l!==Fe)&&(O=R,Fe=l,yield{type:"status",content:`${$e}`},process.stdout.isTTY)){let P={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",FindFile:"Finding File",find_file:"Finding File",Run:"Executing",Ask:"User Input Required",AskUser:"User Input Required",Memory:"Updating Memory",GenerateImage:"Generating",InvokeSync:"Sub-Agent Working",invoke_sync:"Sub-Agent Working",Invoke:"Working",invoke:"Working",GetProgress:"Checking Progress",get_progress:"Checking Progress",Cancel:"Stopping Generalist",cancel:"Stopping Generalist",Await:"Waiting",await:"Waiting",wait:"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"}[R]||"Working";process.stdout.write(`\x1B]0;${P}...\x07`)}}if(pe.length-oo>800){oo=pe.length;let w=ra(pe,!1),R=ms(w),oe=R?(R.innerContent||"").trim():"",l=oe.split(/[.!?]\s+/).filter(be=>be.trim().length>10),$e=new Set(l),Q=l.length>25?(l.length-$e.size)/l.length:0,P=oe.split(/\s+/).filter(be=>be.length>0).length,kt=.9,Rn=.92,Gt=!1;if(s.toLowerCase().includes("google")&&(ne||"").toLowerCase().startsWith("gemma")){let c={low:2048,medium:4096,high:32768,max:65536,xhigh:65536}[d?.toLowerCase()]||16e3;Gt=P>c}if(Q>kt||Gt){yield{type:"status",content:`${Q>kt?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},Ut=!0,await new Promise(c=>setTimeout(c,3e3));break}let Tt=na(pe).trim().split(/[.!?]\s+/).filter(be=>be.trim().length>10),Ht=new Set(Tt);if((Tt.length>25?(Tt.length-Ht.size)/Tt.length:0)>Rn){yield{type:"status",content:"Response Loop Detected. Re-centering..."},Ut=!1,Xt=!0,await new Promise(be=>setTimeout(be,3e3));break}let _n=w.replace(el,"").replace(tl,"").replace(nl,"").replace(ol,""),Mt=_n.toLowerCase().split(/\s+/).map(be=>be.replace(il,"")).filter(be=>be.length>0),mn=!1;if(Mt.length>=40)for(let be=1;be<=15;be++){let c=Math.max(8,Math.ceil(25/be));if(Mt.length<be*c)continue;let v=Mt.slice(Mt.length-be),H=v.join(" ");if(be>1&&H===v.slice(0,Math.floor(be/2)).join(" ").repeat(2).trim())continue;let ye=!0;for(let se=1;se<c;se++)if(Mt.slice(Mt.length-be*(se+1),Mt.length-be*se).join(" ")!==H){ye=!1;break}if(ye){mn=!0;break}}if(!mn){let be=_n.toLowerCase().replace(sl,"");if(be.length>=80)for(let c=1;c<=10;c++){let v=Math.max(15,Math.ceil(45/c));if(be.length<c*v)continue;let H=be.substring(be.length-c),ye=!0;for(let se=1;se<v;se++)if(be.substring(be.length-c*(se+1),be.length-c*se)!==H){ye=!1;break}if(ye){mn=!0;break}}}if(mn){yield{type:"status",content:"Stuttering Detected. Re-centering..."},Ut=!1,Vn=!0,await new Promise(be=>setTimeout(be,3e3));break}}let J=Bt(pe),St=jn(J);for(;St.length>Rt;){yield*zn();let w=St[Rt],R=Date.now(),l={Ask:"ask",AskUser:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",FindFile:"find_file",find_file:"find_file",findfile:"find_file",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",Wait:"wait",wait:"wait",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"}[w.toolName]||w.toolName,$e=ps[l]||w.toolName,Q=eo(l,w.args);yield{type:"status",content:`${$e}${Q?` ${Q}`:""}`};let P="";if(l==="click"){let c=j(w.args);P=`\u2714 Clicked ${c.intendedClickText?`: ${c.intendedClickText}`:"Screen"}`}else if(l==="drag"){let c=j(w.args);P=`\u2714 Dragged: Cell ${c.fromGridId||""} \u2192 Cell ${c.toGridId||""}`}else if(l==="scroll"){let c=j(w.args);P=`\u2714 Scrolled: ${c.direction||"down"} (${c.amount||1})`}else if(l==="keyboard_typing"){let c=j(w.args);P=`\u2714 ${c.autoPressEnter?"Entered":"Typed"}: ${c.text?`"${c.text.length>20?c.text.substring(0,20)+"...":c.text}"`:""}`}else if(l==="key_press")P=`\u2714 Pressed Key: ${j(w.args).key||""}`;else if(l==="recapture_screen")P="\u2714 Recaptured Screen";else if(l==="web_search"){let{query:c,limit:v=10,aiMode:H=!1}=j(w.args);P=`${c?"\u2714":"\u2718"} ${H?"AI Search":"Searched"}: ${c?`${c}`:"No Search Query"}${H===!1&&c?` \u2192 ${v}`:""}`}else if(l==="web_scrape"){let c=j(w.args).url||null;P=`${c?"\u2714":"\u2718"} Visited: ${c||"No Source"}`}else if(l==="view_file"){let{path:c,StartLine:v,EndLine:H,start_line:ye,end_line:se,startLine:te,endLine:we}=j(w.args),ke=v||ye||te,Z=H||se||we,N=parseInt(ke)||1,Y=parseInt(Z)||(ke?N+800:800),Ne="...",Re=Y,re=(c||"").trim().toLowerCase().replaceAll("\\","/");if(re.startsWith("#skill"))re.startsWith("#skill/global/fluxflow")||re.startsWith("#skills/global/fluxflow")||re.includes("#skill/fluxflow")||re.includes("#skills/fluxflow")?P="\u2714 Read Documentation":P=`\u2714 Read Skill: ${U.basename(c.replaceAll("\\","/"))}`;else{try{let xe=U.resolve(process.cwd(),c);if(Ae.existsSync(xe)){let B=Ae.readFileSync(xe,"utf8").split(`
758
+ `).length;Ne=B,!ke&&!Z&&B>800?Re=Math.min(50,B):Re=Math.min(Y,B)}}catch{}let Pt=(c||"").toLowerCase(),on=Pt.endsWith(".pdf"),De=Pt.endsWith(".docx")||Pt.endsWith(".doc")||Pt.endsWith(".ppt")||Pt.endsWith(".pptx")||Pt.endsWith(".xls")||Pt.endsWith(".xlsx"),et=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(Pt);on||De?P=`${c.length>0?"\u2714":"\u2718"} ${c?`Analyzed: ${U.basename(c)}`:"Analyzed: File Not Found"}`:et?P=`${c.length>0?"\u2714":"\u2718"} ${c?`Processed: ${U.basename(c)}`:"Processed: File Not Found"}`:P=`${Ne!=="..."?"\u2714":"\u2718"} Read: ${c?`${U.basename(c)} \u2192 ${Ne!=="..."?`Lines ${N} - ${Re} of ${Ne}`:"File Not Found"}`:"File Not Found"}`}}else if(l==="list_files"||l==="read_folder"){let c=l==="list_files"?"List":"Browsed",v=j(w.args).path||null,H=j(w.args).recurse||1;P=`${v?"\u2714":"\u2718"} ${c}: ${v?`${v==="."?`./${H>1?"*":""}`:`${v.replaceAll("\\","/")}${H>1?`${v.endsWith("/")?"*":"/*"}`:`${v.endsWith("/")?"":"/"}`}`}`:"No Folder Selected"}`}else if(l==="find_file"){let c=j(w.args),v=c.basename||c.name||c.path||c.file||c.query||"";P=`${v?"\u2714":"\u2718"} Located: ${v||"No Query"}`}else if(l==="write_file"||l==="update_file"){let c=l==="write_file"?"Created":"Edited",v=j(w.args),H=v.path||null,se=Object.entries(v).some(([te,we])=>te.startsWith("searchContent")&&typeof we=="string"&&we.startsWith("^LINE:"))?"\u1361":":";P=`${H?"\u2714":"\u2718"} ${c}${se} ${H?H.replaceAll("\\","/"):"No File Changes"}`}else if(l==="write_pdf"){let c=j(w.args).path||null;P=`${c?"\u2714":"\u2718"} Generated: ${c.replaceAll("\\","/")||"No PDF Generated"}`}else if(l==="write_docx"){let c=j(w.args).path||null;P=`${c?"\u2714":"\u2718"} Generated: ${c.replaceAll("\\","/")||"No Docx Generated"}`}else if(l==="file_map"){let c=j(w.args).path;P=`${c?"\u2714":"\u2718"} Indexed: ${c.replaceAll("\\","/")?""+c:"File Not Found"}`}else if(l.toLowerCase()==="search_keyword"||l.toLowerCase()==="todo")P="";else if(l.toLowerCase()==="generate_image"){let{path:c,outputPath:v,output:H}=j(w.args);P=`\u2714 Generated: ${c||v||H||"generated_image.png"}`}else if(l==="invoke_sync"||l==="InvokeSync"){let c=eo(l,w.args);P=`\u2714 Called Generalist${c?`: ${c}`:""}`}else if(l==="Invoke"||l==="InvokeAsync"||l==="invoke"){let c=eo(l,w.args);P=`\u2714 Started Generalist${c?`: ${c}`:""}`}else if(l==="get_progress"||l==="GetProgress"){let c=eo(l,w.args);P=`\u2714 Checked${c?`: ${c}`:""}`}else if(l==="cancel"){let c=eo(l,w.args);P=`\u{1F6C7} Cancelled${c?`: ${c}`:""}`}else if(l==="steer"||l==="Steer"){let c=eo(l,w.args);P=`\u2714 Steered${c?`: ${c}`:""}`}else if(l==="EmergencyRollback"){let{method:c}=j(w.args);P=c==="forceRevert"?"":"\u2714 Rollback Point Checked"}else if(l==="await"||l==="Await"||l==="wait"||l==="Wait"){let{time:c,timeout:v,seconds:H,sec:ye}=j(w.args),se=parseFloat(H||ye||v||c)||45,te=l==="wait"||l==="Wait"?120:180;se<10&&(se=10),se>te&&(se=te);let we=N=>{if(N>=60){let Y=Math.floor(N/60),Ne=N%60;return`${Y}m${Ne>0?` ${Ne}s`:""}`}return`${N}s`},ke=["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"];P=`\u2714 ${ke[Math.floor(Math.random()*ke.length)]} \u2192 ${we(se)}`}else l==="Answer"||l==="answer"?P="\u2714 Resolved Sub-Agent Query":l==="exec_command"||l==="ask"?P="":P=`Executed: ${w.toolName}`;if(yield*zn(),l==="exec_command"){let{command:c}=j(w.args);if(c&&t.systemSettings&&t.systemSettings.allowExternalAccess===!1){let v=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],H=U.resolve(process.cwd()).substring(0,3).toLowerCase(),ye=Z=>{let N=[],Y="",Ne=null;for(let Re=0;Re<Z.length;Re++){let re=Z[Re];Ne?(re===Ne&&(Ne=null),Y+=re):re==='"'||re==="'"?(Ne=re,Y+=re):re==="&"&&Z[Re+1]==="&"||re==="|"&&Z[Re+1]==="|"?(Y.trim()&&(N.push(Y.trim()),Y=""),Re++):re===";"||re==="|"||re==="&"?Y.trim()&&(N.push(Y.trim()),Y=""):Y+=re}return Y.trim()&&N.push(Y.trim()),N},se=Z=>{let N=[],Y="",Ne=null;for(let Re=0;Re<Z.length;Re++){let re=Z[Re];Ne?(re===Ne&&(Ne=null),Y+=re):re==='"'||re==="'"?(Ne=re,Y+=re):/\s/.test(re)?Y&&(N.push(Y),Y=""):Y+=re}return Y&&N.push(Y),N},te=Z=>{let N=Z.replace(/^['"]|['"]$/g,"").trim();return!N||process.platform==="win32"&&/^\/[a-zA-Z0-9?]+$/.test(N)?!1:v.some(Y=>{if(Y.source==="[a-zA-Z]:[\\\\\\/]"){let Ne=N.match(/[a-zA-Z]:[\\\/]/i);return Ne&&Ne[0].toLowerCase()!==H}return Y.test(N)})};if(ye(c).some(Z=>{let N=se(Z);if(N.length===0)return!1;let Y=N[0].replace(/^['"]|['"]$/g,"").toLowerCase();if(["echo","printf","write-output"].includes(Y)){let Re=!1;return N.some(re=>{let Ft=re.replace(/^['"]|['"]$/g,"");if(Ft===">"||Ft===">>"||Ft==="<")return Re=!0,!1;if(Ft.startsWith(">")||Ft.startsWith("<")){let Pt=Ft.replace(/^[><]+/,"");return te(Pt)}return Re?(Re=!1,te(re)):!1})}return N.some(Re=>te(Re))})){let Z='Access Denied. Prohibited from accessing external directories while "External Workspace Access" is disabled.';t.onExecStart&&t.onExecStart(c||"No Command"),yield{type:"exec_start"},await new Promise(N=>setTimeout(N,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${Z}`),await new Promise(N=>setTimeout(N,50)),t.onExecEnd&&t.onExecEnd(),We.push({role:"user",text:`[ACTION RESULT]: ERROR: ${Z}`}),yield{type:"tool_result",content:`[ACTION RESULT]: ERROR: ${Z}`},Rt++;continue}}t.onExecStart&&t.onExecStart(c||"No Command"),yield{type:"exec_start"}}let kt=j(w.args),Rn=kt.path||kt.targetPath||null;if(Rn){let c=t.systemSettings&&t.systemSettings.allowExternalAccess===!1,v=U.resolve(Rn),H=U.resolve(process.cwd());if(c&&!v.startsWith(H)){let ye="Access Denied. You are not allowed to access files outside the current workspace.";if(l==="write_file"||l==="update_file"){let te=`\u2718 ${l==="write_file"?"Write Canceled":"Edit Canceled"}: ${kt.path||"..."}`,we=115;process.stdout.isTTY&&(we=process.stdout.columns-5||120);let ke=Math.min(te.length+4,we),Z=`${te.padEnd(ke-2).substring(0,ke-2)}`;yield{type:"visual_feedback",content:Kt(`${je?`
759
+ `:""}${Z}
760
+ `)},je=!1}We.push({role:"user",text:`[ACTION RESULT]: ERROR: ${ye}`}),yield{type:"tool_result",content:`[ACTION RESULT]: ERROR: ${ye}`},Rt++;continue}}if(t.onToolApproval){let c=t.systemSettings||{},v=c.autoExec,H=!1,ye="";if(l==="view_file"){let te=j(w.args);if(ye=te.path||te.targetPath||te.file||"",ye){let we=c.alwaysAskFiles||".env, .env.*, *.env";Is(ye,we)&&(H=!0)}}if(l==="write_file"||l==="update_file"||l==="exec_command"||H){let te=null,we=!1,ke=!1,Z=!1;if(H)we=!0,te=null;else if(l==="exec_command"){let{command:De}=j(w.args),et=(De||"").trim(),xe=(sn,Jt)=>{if(!Jt)return!1;let pn=Jt.split(",").map(Qt=>Qt.trim().toLowerCase()).filter(Boolean),st=sn.toLowerCase();return pn.some(Qt=>st.startsWith(Qt))},Ve=xe(et,c.alwaysAskCommands),B=xe(et,c.autoApproveCommands);if(ke=xe(et,c.autoDisallowCommands),Ve?we=!0:(B||c.autoApproveGit&&/^git\s+commit\b/i.test(et))&&(te="allow"),!we&&!te){if(c.networkAccess===!1){let Jt=et.trim().replace(/\s+/g," ").replace(/^['"]+|['"]+$/g,"").toLowerCase().split(" "),st=Jt[0].split("/").pop().split("\\").pop().replace(/\.exe$/,""),Qt=new Set(["curl","wget","httpie","xh","ssh","scp","sftp","rsync","ftp","lftp","tftp","telnet","nc","netcat","socat","ping","traceroute","tracert","dig","nslookup","host","whois","nmap","docker","podman","kubectl","helm","gcloud","aws","az","terraform","ansible-playbook","nix","nix-env","apt","apt-get","dpkg","yum","dnf","pacman","zypper","brew","apk","choco","scoop","conda","mamba","aria2c","axel","smbclient","lynx","w3m","links","elinks","heroku","netlify","vercel","firebase","supabase","wrangler","flyctl","powershell","pwsh","certutil","bitsadmin","cloudflared","ngrok","tailscale","zerotier","rclone"]),rt=!1;Qt.has(st)&&(rt=!0);let tt=Nn=>Jt.slice(1).some(vn=>Nn.includes(vn)),pt=Nn=>{let vn=Jt.findIndex(In=>Nn.includes(In)),Xn=Jt.findIndex(In=>["run","exec","test"].includes(In));return vn!==-1&&!(Xn!==-1&&Xn<vn)};st==="git"&&tt(["clone","pull","push","fetch"])&&(rt=!0),st==="go"&&tt(["get","install"])&&(rt=!0),st==="npm"&&pt(["install","i","update","add"])&&(rt=!0),st==="yarn"&&pt(["add","install","upgrade"])&&(rt=!0),st==="pnpm"&&pt(["add","install","update"])&&(rt=!0),st==="bun"&&pt(["add","install","update"])&&(rt=!0),st==="deno"&&tt(["install","add"])&&(rt=!0),st==="pip"&&tt(["install","download"])&&(rt=!0),st==="pip3"&&tt(["install","download"])&&(rt=!0),st==="cargo"&&tt(["install","add"])&&(rt=!0),["bash","sh","zsh","fish"].includes(st)&&tt(["-c"])&&(rt=!0),st==="cmd"&&tt(["/c"])&&(rt=!0),rt&&(te="deny",Z=!0)}!te&&ke&&(te="deny")}!we&&!te&&v&&(te="allow")}else(l==="write_file"||l==="update_file")&&v&&(te="allow");let N=te,Y="";te==="deny"&&(Z?Y="network":ke?Y="settings":Y="prohibited");let Ne=!1,Re="",re=[],Ft=0,Pt=!1,on="";if(!N&&t.onToolApproval)try{let De=await t.onToolApproval(l,w.args,{checkOnly:!0});(De==="allow"||De==="deny")&&(N=De,N==="deny"&&(Y="user"))}catch{}if(!N){if(l==="write_file"||l==="update_file")try{let xe=j(w.args),{path:Ve}=xe;if(Ve){let B=U.resolve(process.cwd(),Ve),sn=tt=>tt?tt.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,pt=>pt.toUpperCase()):"",Jt=sn(B),pn="",st=!1,Qt=await Qn(),rt=sn(Qt?.file_focused);if(Qt&&rt===Jt&&Qt.full_content?(pn=Qt.full_content,st=!0):Ae.existsSync(B)&&(pn=Ae.readFileSync(B,"utf8"),st=!0),Re=pn,await ti.recordFileChange(B,pn),st){let tt=pn;if(l==="write_file"){let pt=xe.content||xe.newContent||"";tt=pt.endsWith(`
761
+ `)?pt:pt+`
762
+ `,on=tt}else{let{patchPairs:pt,allowMultiple:Nn,error:vn}=Fi(xe);if(vn){let rn=`[ACTION RESULT]: ERROR: ${vn}`;We.push({role:"user",text:rn}),await Lt("toolFailure"),t.onToolResult&&t.onToolResult("failure",l),yield{type:"tool_result",content:rn,toolName:l},Rt++;continue}let Xn=xe.allowMultiple!==void 0?xe.allowMultiple===!0||String(xe.allowMultiple).toLowerCase()==="true":Nn;Ft=pt.length;let In=Ps(pn,pt,{allowMultiple:Xn});tt=In.content,on=tt,re=In.results;let zo=re.filter(rn=>rn.success),_i=re.filter(rn=>!rn.success);if(zo.length===0){let rn=`[ACTION RESULT]: ERROR: Failed to apply patches to [${U.basename(B)}].
763
+ ${_i.map(nt=>` \u2022 ${nt.error}`).join(`
764
+ `)}`,vi=`\u2714 Edited: ${U.basename(B.replaceAll("\\","/"))}`,hn=115;process.stdout.isTTY&&(hn=process.stdout.columns-5||120);let Dn=Math.min(vi.length+4,hn),at=`${vi.padEnd(Dn-2).substring(0,Dn-2)}`;yield{type:"visual_feedback",content:Kt(`${je?`
765
+ `:""}${at}`)},je=!1,We.push({role:"user",text:rn}),await Lt("toolFailure"),t.onToolResult&&t.onToolResult("failure",l),yield{type:"tool_result",content:rn,toolName:l},Rt++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${U.basename(B)}`},Yi(B,pn,tt),Ne=!0,await new Promise(pt=>setTimeout(pt,50))}else if(l==="write_file"){let tt=xe.content||xe.newContent||"",pt=tt.endsWith(`
767
766
  `)?tt:tt+`
768
- `;on=mt,Ae.existsSync(U)||(Pt=!0,Ae.mkdirSync(W.dirname(U),{recursive:!0}),Ae.writeFileSync(U,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${W.basename(U)}`},Vi(U,"",mt),$e=!0,await new Promise(Nn=>setTimeout(Nn,50))}}}catch(xe){console.error("Simulation/Diff Error:",xe)}let Ne=null;Ki(xe=>{Ne=xe});let et=t.onToolApproval;if(N=await new Promise(async xe=>{let Ve=setInterval(()=>{if(Ne){let U=t.onIDEApproval||Ho&&Ho.onIDEApproval;U&&U(Ne),clearInterval(Ve),xe(Ne)}},100);try{let U=await et(l,w.args);clearInterval(Ve),xe(U)}catch{clearInterval(Ve),xe("deny")}}),Ki(null),l==="write_file"||l==="update_file"){let{path:xe}=j(w.args);if(xe){let Ve=W.resolve(process.cwd(),xe);if(sr(Ve,N),N==="deny"&&Pt&&Ae.existsSync(Ve))try{Ae.unlinkSync(Ve)}catch{}}}N==="deny"&&(z="user")}if(N==="allow"&&$e&&go()){let{path:Ne}=j(w.args),et=W.resolve(process.cwd(),Ne),xe=at=>at?W.resolve(at).replace(/\\/g,"/").toLowerCase():"",Ve=await Jn(),U="";if(Ve&&Ve.file_focused&&xe(Ve.file_focused)===xe(et)&&Ve.full_content&&(U=Ve.full_content),!U&&Ae.existsSync(et)){let at=Ae.readFileSync(et,"utf8");at&&(U=at)}!U&&on&&(U=on),(U||Pt)&&Ae.writeFileSync(et,U,"utf8");let sn=U.split(/\r?\n/),Jt=sn.length,mn=Buffer.byteLength(U,"utf8"),st="";Re&&(st=`Old File contents:
769
- ${Re.split(/\r?\n/).map((nt,hn)=>`${hn+1} | ${nt}`).join(`
767
+ `;on=pt,Ae.existsSync(B)||(Pt=!0,Ae.mkdirSync(U.dirname(B),{recursive:!0}),Ae.writeFileSync(B,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${U.basename(B)}`},Yi(B,"",pt),Ne=!0,await new Promise(Nn=>setTimeout(Nn,50))}}}catch(xe){console.error("Simulation/Diff Error:",xe)}let De=null;Vi(xe=>{De=xe});let et=t.onToolApproval;if(N=await new Promise(async xe=>{let Ve=setInterval(()=>{if(De){let B=t.onIDEApproval||Ho&&Ho.onIDEApproval;B&&B(De),clearInterval(Ve),xe(De)}},100);try{let B=await et(l,w.args);clearInterval(Ve),xe(B)}catch{clearInterval(Ve),xe("deny")}}),Vi(null),l==="write_file"||l==="update_file"){let{path:xe}=j(w.args);if(xe){let Ve=U.resolve(process.cwd(),xe);if(sr(Ve,N),N==="deny"&&Pt&&Ae.existsSync(Ve))try{Ae.unlinkSync(Ve)}catch{}}}N==="deny"&&(Y="user")}if(N==="allow"&&Ne&&go()){let{path:De}=j(w.args),et=U.resolve(process.cwd(),De),xe=at=>at?U.resolve(at).replace(/\\/g,"/").toLowerCase():"",Ve=await Qn(),B="";if(Ve&&Ve.file_focused&&xe(Ve.file_focused)===xe(et)&&Ve.full_content&&(B=Ve.full_content),!B&&Ae.existsSync(et)){let at=Ae.readFileSync(et,"utf8");at&&(B=at)}!B&&on&&(B=on),(B||Pt)&&Ae.writeFileSync(et,B,"utf8");let sn=B.split(/\r?\n/),Jt=sn.length,pn=Buffer.byteLength(B,"utf8"),st="";Re&&(st=`Old File contents:
768
+ ${Re.split(/\r?\n/).map((nt,yn)=>`${yn+1} | ${nt}`).join(`
770
769
  `)}
771
770
 
772
771
  `);let Qt="";if(Jt<=100)Qt=sn.join(`
@@ -776,13 +775,13 @@ ${Re.split(/\r?\n/).map((nt,hn)=>`${hn+1} | ${nt}`).join(`
776
775
 
777
776
  ... [${Jt-100} lines truncated for history stability] ...
778
777
 
779
- ${nt}`}let rt="";if(l==="update_file"){let at=Os(Re,U,re,12,t?.compressToolResults||Ho?.systemSettings?.compressToolResults),{patchPairs:nt}=Di(j(w.args)),hn=nt?.length||Ft||1,Fn=0,Zt=0,ao=[];nt&&nt.length>0?nt.forEach((lo,vi)=>{let qo=lo.replace||"",yn=lo.new||"",Ii=qo.trim(),ko=yn.trim(),Ca=!!on&&U===on,Ra=ko?U.includes(yn)||U.includes(ko):!0,_a=yn?Re.includes(yn)||!!ko&&Re.includes(ko):!1,va=Ii?U.includes(qo)||U.includes(Ii):!1;Ca||!!yn&&Ra&&(!_a||!va||Ii===ko)?Fn++:(Zt++,ao.push(` \u2022 Block ${vi+1}: not applied (reverted or rejected in IDE).`))}):Fn=Ft||0;let Bn=0;if(on&&U!==on){let lo=Ja("","",on||"",U||"","","",{context:0});if(lo&&lo.hunks)for(let vi of lo.hunks){let qo=vi.lines.filter(yn=>yn.startsWith("+")).map(yn=>yn.slice(1).trim()).filter(Boolean);for(let yn of qo)Re.includes(yn)||Bn++}}let So=[`[${Fn}/${hn}] applied`];Zt>0&&So.push(`${Zt} rejected by user`),Bn>0&&So.push(`${Bn} manual ${Bn===1?"modification":"modifications"} by user`);let Aa=So.join(", "),Ea=ao.length>0?`
778
+ ${nt}`}let rt="";if(l==="update_file"){let at=Os(Re,B,re,12,t?.compressToolResults||Ho?.systemSettings?.compressToolResults),{patchPairs:nt}=Fi(j(w.args)),yn=nt?.length||Ft||1,Fn=0,Zt=0,ao=[];nt&&nt.length>0?nt.forEach((lo,Ii)=>{let qo=lo.replace||"",xn=lo.new||"",Mi=qo.trim(),ko=xn.trim(),Ra=!!on&&B===on,_a=ko?B.includes(xn)||B.includes(ko):!0,va=xn?Re.includes(xn)||!!ko&&Re.includes(ko):!1,Ia=Mi?B.includes(qo)||B.includes(Mi):!1;Ra||!!xn&&_a&&(!va||!Ia||Mi===ko)?Fn++:(Zt++,ao.push(` \u2022 Block ${Ii+1}: not applied (reverted or rejected in IDE).`))}):Fn=Ft||0;let Bn=0;if(on&&B!==on){let lo=Qa("","",on||"",B||"","","",{context:0});if(lo&&lo.hunks)for(let Ii of lo.hunks){let qo=Ii.lines.filter(xn=>xn.startsWith("+")).map(xn=>xn.slice(1).trim()).filter(Boolean);for(let xn of qo)Re.includes(xn)||Bn++}}let So=[`[${Fn}/${yn}] applied`];Zt>0&&So.push(`${Zt} rejected by user`),Bn>0&&So.push(`${Bn} manual ${Bn===1?"modification":"modifications"} by user`);let Ea=So.join(", "),Ca=ao.length>0?`
780
779
 
781
780
  User Review Details:
782
781
  ${ao.join(`
783
- `)}`:"";rt=`File [${Ne}] updated via IDE Companion. ${Aa}.${Ea}
782
+ `)}`:"";rt=`File [${De}] updated via IDE Companion. ${Ea}.${Ca}
784
783
 
785
- ${at}`}else{let at=U.split(/\r?\n/),nt=at.length,hn=Buffer.byteLength(U,"utf8"),Fn="";Re&&(Fn=`Old File contents:
784
+ ${at}`}else{let at=B.split(/\r?\n/),nt=at.length,yn=Buffer.byteLength(B,"utf8"),Fn="";Re&&(Fn=`Old File contents:
786
785
  ${Re.split(/\r?\n/).map((Bn,So)=>`${So+1} | ${Bn}`).join(`
787
786
  `)}
788
787
 
@@ -793,91 +792,93 @@ ${Re.split(/\r?\n/).map((Bn,So)=>`${So+1} | ${Bn}`).join(`
793
792
 
794
793
  ... [${nt-100} lines truncated] ...
795
794
 
796
- ${Bn}`}rt=`File [${Ne}] saved via IDE Companion (May have user edits).
797
- - Stats: [${nt} lines, ${(hn/1024).toFixed(1)} KB]
795
+ ${Bn}`}rt=`File [${De}] saved via IDE Companion (May have user edits).
796
+ - Stats: [${nt} lines, ${(yn/1024).toFixed(1)} KB]
798
797
  ${Fn}- Content Preview:
799
798
 
800
- ${Zt}`}let tt=l==="write_file"?"Created":"Edited",mt=j(w.args),vn=Object.entries(mt).some(([at,nt])=>at.startsWith("searchContent")&&typeof nt=="string"&&nt.startsWith("^LINE:"))?"\u1361":":",qn=`${Ne?"\u2714":"\u2718"} ${tt}${vn} ${Ne?Ne.replaceAll("\\","/"):"No File Changes"}`,In=115;process.stdout.isTTY&&(In=process.stdout.columns-5||120);let zo=Math.min(qn.length+4,In),Ri=`${qn.padEnd(zo-2).substring(0,zo-2)}`;yield{type:"visual_feedback",content:jt(`${je?`
801
- `:""}${Ri}`)},je=!1;let rn=Date.now();un=rn,yield{type:"tool_time",content:rn-R};let pn=(rt||"").toString().replaceAll("\u2550".repeat(88),"=".repeat(35)).replaceAll("[UI_CONTEXT]","");pn.includes("[[VERIFIED]]")&&(pn=pn.replace(/\[\[VERIFIED\]\][\s\S]*?\[\[\/VERIFIED\]\]/g,`[SYSTEM NOTE]: Patch Block matched & applied successfully. Large Block omitted to conserve context.
802
- `));let Dn;if(l==="write_file"&&!pn.startsWith("ERROR:")){let nt=pn.replace(/^\[\[SAME\]\]\s*\r?\n?/,"").split(/\r?\n/),hn=nt.filter(Zt=>Zt.startsWith("File ")||Zt.trim().startsWith("- Stats:"));Dn=`[ACTION RESULT]: ${hn.length>0?hn.join(`
799
+ ${Zt}`}let tt=l==="write_file"?"Created":"Edited",pt=j(w.args),vn=Object.entries(pt).some(([at,nt])=>at.startsWith("searchContent")&&typeof nt=="string"&&nt.startsWith("^LINE:"))?"\u1361":":",Xn=`${De?"\u2714":"\u2718"} ${tt}${vn} ${De?De.replaceAll("\\","/"):"No File Changes"}`,In=115;process.stdout.isTTY&&(In=process.stdout.columns-5||120);let zo=Math.min(Xn.length+4,In),_i=`${Xn.padEnd(zo-2).substring(0,zo-2)}`;yield{type:"visual_feedback",content:Kt(`${je?`
800
+ `:""}${_i}`)},je=!1;let rn=Date.now();un=rn,yield{type:"tool_time",content:rn-R};let hn=(rt||"").toString().replaceAll("\u2550".repeat(88),"=".repeat(35)).replaceAll("[UI_CONTEXT]","");hn.includes("[[VERIFIED]]")&&(hn=hn.replace(/\[\[VERIFIED\]\][\s\S]*?\[\[\/VERIFIED\]\]/g,`[SYSTEM NOTE]: Patch Block matched & applied successfully. Large Block omitted to conserve context.
801
+ `));let Dn;if(l==="write_file"&&!hn.startsWith("ERROR:")){let nt=hn.replace(/^\[\[SAME\]\]\s*\r?\n?/,"").split(/\r?\n/),yn=nt.filter(Zt=>Zt.startsWith("File ")||Zt.trim().startsWith("- Stats:"));Dn=`[ACTION RESULT]: ${yn.length>0?yn.join(`
803
802
  `):nt.slice(0,2).join(`
804
- `)}`}else if(pn.startsWith("[[SAME]]")){let nt=pn.replace(/^\[\[SAME\]\]\s*\r?\n?/,"").split(/\r?\n/),hn=nt.filter(Zt=>Zt.startsWith("File ")||Zt.trim().startsWith("- Stats:"));Dn=`[ACTION RESULT]: ${hn.length>0?hn.join(`
803
+ `)}`}else if(hn.startsWith("[[SAME]]")){let nt=hn.replace(/^\[\[SAME\]\]\s*\r?\n?/,"").split(/\r?\n/),yn=nt.filter(Zt=>Zt.startsWith("File ")||Zt.trim().startsWith("- Stats:"));Dn=`[ACTION RESULT]: ${yn.length>0?yn.join(`
805
804
  `):nt.slice(0,2).join(`
806
- `)}`}else Dn=`[ACTION RESULT]: ${pn}`;He.push({role:"user",text:Dn}),En=!0,await Lt("toolSuccess"),t.onToolResult&&t.onToolResult("success",l),yield{type:"tool_result",content:rt,aiContent:Dn,toolName:l},Rt++;continue}if(N==="deny"){let Ne=`Permission Denied: Prohibited ${l==="exec_command"?"Command":"file edit"}.`;if(V?Ne=`User denied reading ${W.basename(ye||".env")}`:z==="user"?Ne="Permission Denied by User":z==="settings"?Ne="Permission Denied by User Policy":z==="network"?Ne="Permission Denied: Sandbox Network Access Disabled by User Policy.":z==="prohibited"&&l==="exec_command"&&(Ne="Permission Denied: Prohibited Command in User Policy"),l==="view_file"){let et=`\u2718 Read Denied: ${j(w.args).path?.replaceAll("\\","/")||".env"}`,xe=115;process.stdout.isTTY&&(xe=process.stdout.columns-5||120);let Ve=Math.min(et.length+4,xe),U=`${et.padEnd(Ve-2).substring(0,Ve-2)}`;yield{type:"visual_feedback",content:jt(`${je?`
807
- `:""}${U}
808
- `)},je=!1}else if(l==="write_file"||l==="update_file"){let xe=`\u2718 ${l==="write_file"?"Write Cancelled":"Edit Denied"}: ${j(w.args).path.replaceAll("\\","/")||"..."}`,Ve=115;process.stdout.isTTY&&(Ve=process.stdout.columns-5||120);let U=Math.min(xe.length+4,Ve),sn=`${xe.padEnd(U-2).substring(0,U-2)}`,Jt=` ${" ".repeat(U)} `;yield{type:"visual_feedback",content:jt(`${je?`
805
+ `)}`}else Dn=`[ACTION RESULT]: ${hn}`;We.push({role:"user",text:Dn}),En=!0,await Lt("toolSuccess"),t.onToolResult&&t.onToolResult("success",l),yield{type:"tool_result",content:rt,aiContent:Dn,toolName:l},Rt++;continue}if(N==="deny"){let De=`Permission Denied: Prohibited ${l==="exec_command"?"Command":"file edit"}.`;if(H?De=`User denied reading ${U.basename(ye||".env")}`:Y==="user"?De="Permission Denied by User":Y==="settings"?De="Permission Denied by User Policy":Y==="network"?De="Permission Denied: Sandbox Network Access Disabled by User Policy.":Y==="prohibited"&&l==="exec_command"&&(De="Permission Denied: Prohibited Command in User Policy"),l==="view_file"){let et=`\u2718 Read Denied: ${j(w.args).path?.replaceAll("\\","/")||".env"}`,xe=115;process.stdout.isTTY&&(xe=process.stdout.columns-5||120);let Ve=Math.min(et.length+4,xe),B=`${et.padEnd(Ve-2).substring(0,Ve-2)}`;yield{type:"visual_feedback",content:Kt(`${je?`
806
+ `:""}${B}
807
+ `)},je=!1}else if(l==="write_file"||l==="update_file"){let xe=`\u2718 ${l==="write_file"?"Write Cancelled":"Edit Denied"}: ${j(w.args).path.replaceAll("\\","/")||"..."}`,Ve=115;process.stdout.isTTY&&(Ve=process.stdout.columns-5||120);let B=Math.min(xe.length+4,Ve),sn=`${xe.padEnd(B-2).substring(0,B-2)}`,Jt=` ${" ".repeat(B)} `;yield{type:"visual_feedback",content:Kt(`${je?`
809
808
  `:""}${sn}
810
- `)},je=!1}l==="exec_command"&&(await new Promise(et=>setTimeout(et,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${Ne}`),await new Promise(et=>setTimeout(et,50)),t.onExecEnd&&t.onExecEnd()),He.push({role:"user",text:`[ACTION RESULT]: DENIED: ${Ne}`}),yield{type:"tool_result",content:`[ACTION RESULT]: DENIED: ${Ne}`},await Lt("toolDenied"),t.onToolResult&&t.onToolResult("denied",l),Rt++;continue}}}if(M){let d=115;process.stdout.isTTY&&(d=process.stdout.columns-5||120);let I=await i(),V=!1;I&&(V=I.trim().length>0);let ye=Math.min(M.length+4,d),se=`${M.padEnd(ye-2).substring(0,ye-2)}`;yield{type:"visual_feedback",content:jt(`${je?`
811
- `:""}${se}${M.includes("\u2714")&&(M.includes("Created")||M.includes("Edited"))?"":`${V?"":`
812
- `}`}`)},je=!1}if(un>0){let d=Date.now()-un,I=Math.max(0,1e3-d);I>0&&await new Promise(V=>setTimeout(V,I))}let Wt={chatId:h,history:n,onChunk:d=>t.onExecChunk?t.onExecChunk(d):null,onAskUser:t.onAskUser,systemSettings:t.systemSettings,mode:a,isMultiModal:lt(ne),onVisualFeedback:t.onVisualFeedback,onSubagentUpdate:t.onSubagentUpdate,onTokenChunk:t.onTokenChunk,modelName:ne,aiProvider:t.aiProvider,apiKey:t.apiKey,onUsage:t.onUsage};if(l==="write_file"||l==="update_file")try{let{path:d}=j(w.args);if(d){let I=W.resolve(process.cwd(),d),V=await Jn();V&&V.file_focused===I&&V.full_content&&(Wt.forcedContent=V.full_content)}}catch{}Ie.push(l);let ie=await Bo(l,w.args,Wt);if((l==="write_file"||l==="update_file")&&!ie.startsWith("ERROR:")){let{path:d}=j(w.args);if(d){let I=W.resolve(process.cwd(),d);ir(I)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let Xe=Date.now();un=Xe,yield{type:"tool_time",content:Xe-R},xt=Xe;let Tt=null;if(typeof ie=="object"&&ie.binaryPart&&(Tt=ie.binaryPart,ie=ie.text),l==="search_keyword"){let{keyword:d,path:I}=j(w.args),V=typeof ie=="string"&&ie.startsWith("[GLOB]");V&&(ie=ie.slice(6).trimStart());let ye=typeof ie=="string"&&ie.startsWith("[DIR]");ye&&(ie=ie.slice(5).trimStart());let se=0;if(ie){let re=ie.match(/Found (\d+) match/i);re&&(se=parseInt(re[1]))}let te=(I||"").trim().toLowerCase().replaceAll("\\","/"),we=te==="#doc"||te==="#docs"||te==="#documentation"||te.includes("#skill/global/fluxflow")||te.includes("#skill/fluxflow")||te.includes("#skills/fluxflow")||te.includes("#skills/global/fluxflow"),ke,ee=115;process.stdout.isTTY&&(ee=process.stdout.columns-5||120);let N=Math.max(10,(ee+5)/3),z=Math.max(10,(ee+5)/4);if(we)ke=`${d?"\u2714":"\u2718"} Searched Documentation`;else{let re=I?I.replace(/[\/\\]+$/,""):null,Ft=re&&re!=="."?`${V?I:ye?`${re}/*`:re}`:"./",Pt=Ft.length>z?`${Ft.slice(0,z)}...`:Ft;ke=`${d?"\u2714":"\u2718"} Searched: "${d?d.length>ee/3?`${d.slice(0,N)}...`:d:""}" in "${Pt.replaceAll("\\","/")}" \u2192 ${se} Match${se===1?"":"es"}`}let $e=Math.min(ke.length+4,ee),Re=`${ke.padEnd($e-2).substring(0,$e-2)}`;yield{type:"visual_feedback",content:jt(`${je?`
809
+ `)},je=!1}l==="exec_command"&&(await new Promise(et=>setTimeout(et,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${De}`),await new Promise(et=>setTimeout(et,50)),t.onExecEnd&&t.onExecEnd()),We.push({role:"user",text:`[ACTION RESULT]: DENIED: ${De}`}),yield{type:"tool_result",content:`[ACTION RESULT]: DENIED: ${De}`},await Lt("toolDenied"),t.onToolResult&&t.onToolResult("denied",l),Rt++;continue}}}if(P){let c=115;process.stdout.isTTY&&(c=process.stdout.columns-5||120);let v=await i(),H=!1;v&&(H=v.trim().length>0);let ye=Math.min(P.length+4,c),se=`${P.padEnd(ye-2).substring(0,ye-2)}`;yield{type:"visual_feedback",content:Kt(`${je?`
810
+ `:""}${se}${P.includes("\u2714")&&(P.includes("Created")||P.includes("Edited"))?"":`${H?"":`
811
+ `}`}`)},je=!1}if(un>0){let c=Date.now()-un,v=Math.max(0,1e3-c);v>0&&await new Promise(H=>setTimeout(H,v))}let Gt={chatId:h,history:n,onChunk:c=>t.onExecChunk?t.onExecChunk(c):null,onAskUser:t.onAskUser,systemSettings:t.systemSettings,mode:a,isMultiModal:lt(ne),onVisualFeedback:t.onVisualFeedback,onSubagentUpdate:t.onSubagentUpdate,onTokenChunk:t.onTokenChunk,modelName:ne,aiProvider:t.aiProvider,apiKey:t.apiKey,onUsage:t.onUsage};if(l==="write_file"||l==="update_file")try{let{path:c}=j(w.args);if(c){let v=U.resolve(process.cwd(),c),H=await Qn();H&&H.file_focused===v&&H.full_content&&(Gt.forcedContent=H.full_content)}}catch{}Ie.push(l);let ie=await Bo(l,w.args,Gt);if((l==="write_file"||l==="update_file")&&!ie.startsWith("ERROR:")){let{path:c}=j(w.args);if(c){let v=U.resolve(process.cwd(),c);ir(v)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let Xe=Date.now();un=Xe,yield{type:"tool_time",content:Xe-R},xt=Xe;let Tt=null;if(typeof ie=="object"&&ie.binaryPart&&(Tt=ie.binaryPart,ie=ie.text),l==="search_keyword"){let{keyword:c,path:v}=j(w.args),H=typeof ie=="string"&&ie.startsWith("[GLOB]");H&&(ie=ie.slice(6).trimStart());let ye=typeof ie=="string"&&ie.startsWith("[DIR]");ye&&(ie=ie.slice(5).trimStart());let se=0;if(ie){let re=ie.match(/Found (\d+) match/i);re&&(se=parseInt(re[1]))}let te=(v||"").trim().toLowerCase().replaceAll("\\","/"),we=te==="#doc"||te==="#docs"||te==="#documentation"||te.includes("#skill/global/fluxflow")||te.includes("#skill/fluxflow")||te.includes("#skills/fluxflow")||te.includes("#skills/global/fluxflow"),ke,Z=115;process.stdout.isTTY&&(Z=process.stdout.columns-5||120);let N=Math.max(10,(Z+5)/3),Y=Math.max(10,(Z+5)/4);if(we)ke=`${c?"\u2714":"\u2718"} Searched Documentation`;else{let re=v?v.replace(/[\/\\]+$/,""):null,Ft=re&&re!=="."?`${H?v:ye?`${re}/*`:re}`:"./",Pt=Ft.length>Y?`${Ft.slice(0,Y)}...`:Ft;ke=`${c?"\u2714":"\u2718"} Searched: "${c?c.length>Z/3?`${c.slice(0,N)}...`:c:""}" in "${Pt.replaceAll("\\","/")}" \u2192 ${se} Match${se===1?"":"es"}`}let Ne=Math.min(ke.length+4,Z),Re=`${ke.padEnd(Ne-2).substring(0,Ne-2)}`;yield{type:"visual_feedback",content:Kt(`${je?`
813
812
  `:""}${Re}
814
- `)},je=!1}if(l==="EmergencyRollback"){let{method:d}=j(w.args);if(d==="forceRevert"){let I=0;if(ie){let N=ie.match(/Total\s*:\s*(\d+)/i);N&&(I=parseInt(N[1]))}let ye=ie&&ie.startsWith("ERROR:")?"\u2718 Emergency Rollback Failed":`\u2714 Emergency Rollback \u2192 ${I} file${I===1?"":"s"} processed`,se=115;process.stdout.isTTY&&(se=process.stdout.columns-5||120);let te=await i(),we=!1;te&&(we=te.trim().length>0);let ke=Math.min(ye.length+4,se),ee=`${ye.padEnd(ke-2).substring(0,ke-2)}`;yield{type:"visual_feedback",content:jt(`${je?`
815
- `:""}${ee}${we?"":`
816
- `}`)},je=!1}}if(l==="todo"){let{method:d,tasks:I,markDone:V}=j(w.args),ye="",se=[],te=we=>{if(!we)return[];let ke=Array.isArray(we)?we:[];if(ke.length===0&&typeof we=="string"){let ee=we.trim();if(ee.startsWith("[")&&ee.endsWith("]")){let N=ee.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);N?ke=N.map(z=>z.slice(1,-1).replace(/\\(.)/g,"$1")):ke=ee.slice(1,-1).split(",").map(z=>z.trim()).filter(Boolean)}else ke=we.split(`
817
- `)}return ke.filter(ee=>String(ee).trim()).map(ee=>{let N=String(ee).trim();return N.startsWith("- [")?N.substring(6).trim():N})};if(d==="create"?(ye="\x1B[32m\u2192\x1B[0m Created Goals",se=te(I).map(we=>`\x1B[90m\u25CB\x1B[0m ${we}`)):d==="append"?(ye="\x1B[34m\u2795\x1B[0m Added New Goals",se=te(I).map(we=>`\x1B[90m\u25CB\x1B[0m ${we}`)):d==="get"&&(ye=V?"\x1B[36m\u21BB\x1B[0m Updated Goals":"\x1B[35m\u2022\x1B[0m Reviewed Goals",se=(ie||"").split(`
813
+ `)},je=!1}if(l==="EmergencyRollback"){let{method:c}=j(w.args);if(c==="forceRevert"){let v=0;if(ie){let N=ie.match(/Total\s*:\s*(\d+)/i);N&&(v=parseInt(N[1]))}let ye=ie&&ie.startsWith("ERROR:")?"\u2718 Emergency Rollback Failed":`\u2714 Emergency Rollback \u2192 ${v} file${v===1?"":"s"} processed`,se=115;process.stdout.isTTY&&(se=process.stdout.columns-5||120);let te=await i(),we=!1;te&&(we=te.trim().length>0);let ke=Math.min(ye.length+4,se),Z=`${ye.padEnd(ke-2).substring(0,ke-2)}`;yield{type:"visual_feedback",content:Kt(`${je?`
814
+ `:""}${Z}${we?"":`
815
+ `}`)},je=!1}}if(l==="todo"){let{method:c,tasks:v,markDone:H}=j(w.args),ye="",se=[],te=we=>{if(!we)return[];let ke=Array.isArray(we)?we:[];if(ke.length===0&&typeof we=="string"){let Z=we.trim();if(Z.startsWith("[")&&Z.endsWith("]")){let N=Z.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);N?ke=N.map(Y=>Y.slice(1,-1).replace(/\\(.)/g,"$1")):ke=Z.slice(1,-1).split(",").map(Y=>Y.trim()).filter(Boolean)}else ke=we.split(`
816
+ `)}return ke.filter(Z=>String(Z).trim()).map(Z=>{let N=String(Z).trim();return N.startsWith("- [")?N.substring(6).trim():N})};if(c==="create"?(ye="\x1B[32m\u2192\x1B[0m Created Goals",se=te(v).map(we=>`\x1B[90m\u25CB\x1B[0m ${we}`)):c==="append"?(ye="\x1B[34m\u2795\x1B[0m Added New Goals",se=te(v).map(we=>`\x1B[90m\u25CB\x1B[0m ${we}`)):c==="get"&&(ye=H?"\x1B[36m\u21BB\x1B[0m Updated Goals":"\x1B[35m\u2022\x1B[0m Reviewed Goals",se=(ie||"").split(`
818
817
  `).slice(1).join(`
819
818
  `).split(`
820
- `).filter(ke=>ke.trim().startsWith("- [")).map(ke=>{let ee=ke.trim(),N=ee.startsWith("- [x]");return`${N?"\x1B[32m\u2714\x1B[0m":"\x1B[90m\u25CB\x1B[0m"} ${N?"\x1B[90m":"\x1B[37m"}${ee.substring(6).trim()}\x1B[0m`})),ye&&se.length>0){let we=[`${ye}`,...se.map(N=>` ${N}`)].join(`
821
- `),ke=await i(),ee=!1;ke&&(ee=ke.trim().length>0),yield{type:"visual_feedback",content:jt(`${je?`
822
- `:""}${we}${ee?"":`
823
- `}`)},je=!1}}l==="exec_command"&&t.onExecEnd&&(await new Promise(d=>setTimeout(d,800)),t.onExecEnd());let Gt=ie&&ie.startsWith("DENIED:");ie&&!ie.startsWith("ERROR:")&&!Gt?(await Lt("toolSuccess"),t.onToolResult&&t.onToolResult("success",l)):Gt||(await Lt("toolFailure"),t.onToolResult&&t.onToolResult("failure",l));let Mt=(ie||"").toString().replaceAll("\u2550".repeat(88),"=".repeat(35)).replaceAll("[UI_CONTEXT]","");Mt.includes("[[VERIFIED]]")&&(Mt=Mt.replace(/\[\[VERIFIED\]\][\s\S]*?\[\[\/VERIFIED\]\]/g,`[SYSTEM NOTE]: Patch Block matched & applied successfully. Large Block omitted to save tokens.
824
- `));let bn;if(l==="write_file"&&!Mt.startsWith("ERROR:")){let I=Mt.replace(/^\[\[SAME\]\]\s*\r?\n?/,"").split(/\r?\n/),V=I.filter(se=>se.startsWith("File ")||se.trim().startsWith("- Stats:"));bn=`[ACTION RESULT]: ${V.length>0?V.join(`
825
- `):I.slice(0,2).join(`
826
- `)}`}else if(Mt.startsWith("[[SAME]]")){let I=Mt.replace(/^\[\[SAME\]\]\s*\r?\n?/,"").split(/\r?\n/),V=I.filter(se=>se.startsWith("File ")||se.trim().startsWith("- Stats:"));bn=`[ACTION RESULT]: ${V.length>0?V.join(`
827
- `):I.slice(0,2).join(`
828
- `)}`}else bn=`[ACTION RESULT]: ${Mt}`;He.push({role:"user",text:bn,binaryPart:Tt}),En=!0;let be=`[ACTION RESULT]: ${ie.replaceAll(`[[VERIFIED]]
819
+ `).filter(ke=>ke.trim().startsWith("- [")).map(ke=>{let Z=ke.trim(),N=Z.startsWith("- [x]");return`${N?"\x1B[32m\u2714\x1B[0m":"\x1B[90m\u25CB\x1B[0m"} ${N?"\x1B[90m":"\x1B[37m"}${Z.substring(6).trim()}\x1B[0m`})),ye&&se.length>0){let we=[`${ye}`,...se.map(N=>` ${N}`)].join(`
820
+ `),ke=await i(),Z=!1;ke&&(Z=ke.trim().length>0),yield{type:"visual_feedback",content:Kt(`${je?`
821
+ `:""}${we}${Z?"":`
822
+ `}`)},je=!1}}l==="exec_command"&&t.onExecEnd&&(await new Promise(c=>setTimeout(c,800)),t.onExecEnd());let Ht=ie&&ie.startsWith("DENIED:");ie&&!ie.startsWith("ERROR:")&&!Ht?(await Lt("toolSuccess"),t.onToolResult&&t.onToolResult("success",l)):Ht||(await Lt("toolFailure"),t.onToolResult&&t.onToolResult("failure",l));let Mt=(ie||"").toString().replaceAll("\u2550".repeat(88),"=".repeat(35)).replaceAll("[UI_CONTEXT]","");Mt.includes("[[VERIFIED]]")&&(Mt=Mt.replace(/\[\[VERIFIED\]\][\s\S]*?\[\[\/VERIFIED\]\]/g,`[SYSTEM NOTE]: Patch Block matched & applied successfully. Large Block omitted to save tokens.
823
+ `));let mn;if(l==="write_file"&&!Mt.startsWith("ERROR:")){let c=Mt.replace(/^\[\[SAME\]\]\s*\r?\n?/,"");if(/- Stats:.*\r?\nOld File contents:/s.test(c)){let v=c.search(/^- Content Preview:/m);mn=`[ACTION RESULT]: ${v!==-1?c.slice(0,v).trimEnd():c}
824
+
825
+ [Old file content for reversal reference. Replaced with new write request]`}else{let v=c.split(/\r?\n/),H=v.filter(se=>se.startsWith("File ")||se.trim().startsWith("- Stats:"));mn=`[ACTION RESULT]: ${H.length>0?H.join(`
826
+ `):v.slice(0,2).join(`
827
+ `)}`}}else if(Mt.startsWith("[[SAME]]")){let v=Mt.replace(/^\[\[SAME\]\]\s*\r?\n?/,"").split(/\r?\n/),H=v.filter(se=>se.startsWith("File ")||se.trim().startsWith("- Stats:"));mn=`[ACTION RESULT]: ${H.length>0?H.join(`
828
+ `):v.slice(0,2).join(`
829
+ `)}`}else mn=`[ACTION RESULT]: ${Mt}`;We.push({role:"user",text:mn,binaryPart:Tt}),En=!0;let be=`[ACTION RESULT]: ${ie.replaceAll(`[[VERIFIED]]
829
830
  `,"").replaceAll(`
830
- [[/VERIFIED]]`,"")||""}`;(l==="view_file"||l==="web_scrape"||l==="file_map"||l==="search_keyword"||l==="get_progress"||l==="getprogress")&&(be=`[ACTION RESULT]: ${M} (Context Locked for UI Clarity)`),yield{type:"tool_result",content:be,aiContent:bn,binaryPart:Tt,toolName:l},l==="memory"&&!ie.startsWith("ERROR:")&&(yield{type:"memory_updated"}),Rt++}if(s==="Google"&&Ut&&Date.now()-io>=150){yield*Yn();let w=xo(Ut);for(let R of w)yield R;Ut="",io=Date.now()}}m.usageMetadata&&(fn=m.usageMetadata),fn&&(yield{type:"liveTokens",content:fn.totalTokenCount})}if(X&&(X=!1,ut?ve+="</think_fluxflow>":(pe+="</think_fluxflow>",s==="Google"?Ut+="</think_fluxflow>":yield{type:"text",content:"</think_fluxflow>"})),ut&&ve.length>0){let m=0,A=Math.min(_t.length,ve.length);for(let J=A;J>0;J--)if(_t.endsWith(ve.substring(0,J))){m=J;break}let C=ve.substring(m);if(C){let le=/(?:<think_fluxflow>|\[think_fluxflow\])(?:(?!(?:<\/think_fluxflow>|\[\/think_fluxflow\]))[\s\S])*$/i.test(_t)?C.replace(/^\s*(?:<think_fluxflow>|\[think_fluxflow\])\s*/gi,""):C.replace(/^\s*(?:<think_fluxflow>|\[think_fluxflow\])[\s\S]*?(?:<\/think_fluxflow>|\[\/think_fluxflow\])\s*/gi,"").replace(/^\s*(?:<think_fluxflow>|\[think_fluxflow\])\s*/gi,"");if(le)if(pe+=le,s==="Google")Ut+=le;else{yield*Yn();let F=xo(le);for(let Q of F)yield Q}}ut=!1,ve=""}if(Cn){let m=Cn,A=(wt==="tool"||wt==="action")&&(m.startsWith("[tool:")||m.startsWith("[action:"));Cn="",so=!1,wt=null,zn=!1,ro=!1,A||(s==="Google"?Ut+=m:yield{type:"text",content:m})}if(yield*Yn(),Et)break;let bo=(pe||"").trim(),xa=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(bo.toLowerCase())||/\[\[END\]\]/i.test(bo.toLowerCase()),ba=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(bo.toLowerCase()),wa=He.length>0||P!==null,Ci=Kt(bo).trim(),Sa=/(\p{Emoji_Presentation}|\p{Extended_Pictographic})$/u.test(Ci),ka=/([.!?"'*_`|\]\)”’~~]+|\s|`{3}|[\u200B-\u200D\uFEFF])$/u.test(Ci.trim()),Ta=/[.!?}"'`’“”]$|```$/s.test(Ci)||ka||Sa;!xa&&!ba&&!wa&&bo.length>0,Ue=!0,await Lt("agent",s)}catch(B){if(Et){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
831
+ [[/VERIFIED]]`,"")||""}`;(l==="view_file"||l==="web_scrape"||l==="file_map"||l==="search_keyword"||l==="get_progress"||l==="getprogress")&&(be=`[ACTION RESULT]: ${P} (Context Locked for UI Clarity)`),yield{type:"tool_result",content:be,aiContent:mn,binaryPart:Tt,toolName:l},l==="memory"&&!ie.startsWith("ERROR:")&&(yield{type:"memory_updated"}),Rt++}if(s==="Google"&&Wt&&Date.now()-io>=150){yield*zn();let w=xo(Wt);for(let R of w)yield R;Wt="",io=Date.now()}}m.usageMetadata&&(fn=m.usageMetadata),fn&&(yield{type:"liveTokens",content:fn.totalTokenCount})}if(q&&(q=!1,ut?ve+="</think_fluxflow>":(pe+="</think_fluxflow>",s==="Google"?Wt+="</think_fluxflow>":yield{type:"text",content:"</think_fluxflow>"})),ut&&ve.length>0){let m=0,A=Math.min(_t.length,ve.length);for(let X=A;X>0;X--)if(_t.endsWith(ve.substring(0,X))){m=X;break}let C=ve.substring(m);if(C){let le=/(?:<think_fluxflow>|\[think_fluxflow\])(?:(?!(?:<\/think_fluxflow>|\[\/think_fluxflow\]))[\s\S])*$/i.test(_t)?C.replace(/^\s*(?:<think_fluxflow>|\[think_fluxflow\])\s*/gi,""):C.replace(/^\s*(?:<think_fluxflow>|\[think_fluxflow\])[\s\S]*?(?:<\/think_fluxflow>|\[\/think_fluxflow\])\s*/gi,"").replace(/^\s*(?:<think_fluxflow>|\[think_fluxflow\])\s*/gi,"");if(le)if(pe+=le,s==="Google")Wt+=le;else{yield*zn();let F=xo(le);for(let J of F)yield J}}ut=!1,ve=""}if(Cn){let m=Cn,A=(wt==="tool"||wt==="action")&&(m.startsWith("[tool:")||m.startsWith("[action:"));Cn="",so=!1,wt=null,qn=!1,ro=!1,A||(s==="Google"?Wt+=m:yield{type:"text",content:m})}if(yield*zn(),Et)break;let bo=(pe||"").trim(),ba=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(bo.toLowerCase())||/\[\[END\]\]/i.test(bo.toLowerCase()),wa=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(bo.toLowerCase()),Sa=We.length>0||O!==null,Ri=Bt(bo).trim(),ka=/(\p{Emoji_Presentation}|\p{Extended_Pictographic})$/u.test(Ri),Ta=/([.!?"'*_`|\]\)”’~~]+|\s|`{3}|[\u200B-\u200D\uFEFF])$/u.test(Ri.trim()),Aa=/[.!?}"'`’“”]$|```$/s.test(Ri)||Ta||ka;!ba&&!wa&&!Sa&&bo.length>0,Ue=!0,await Lt("agent",s)}catch(ee){if(Et){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
831
832
 
832
- \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(String(B).includes("Incomplete JSON segment at the end")){X&&(X=!1,ut?ve+="</think_fluxflow>":(pe+="</think_fluxflow>",yield{type:"text",content:"</think_fluxflow>"})),Ue=!0,await Lt("agent",s);break}if(X&&(X=!1,ut?ve+="</think_fluxflow>":pe+="</think_fluxflow>"),ut&&ve.length>0){let vt=0,gt=Math.min(_t.length,ve.length);for(let ot=gt;ot>0;ot--)if(_t.endsWith(ve.substring(0,ot))){vt=ot;break}let bt=ve.substring(vt);if(bt){let Dt=/(?:<think_fluxflow>|\[think_fluxflow\])(?:(?!(?:<\/think_fluxflow>|\[\/think_fluxflow\]))[\s\S])*$/i.test(_t)?bt.replace(/^\s*(?:<think_fluxflow>|\[think_fluxflow\])\s*/gi,""):bt.replace(/^\s*(?:<think_fluxflow>|\[think_fluxflow\])[\s\S]*?(?:<\/think_fluxflow>|\[\/think_fluxflow\])\s*/gi,"").replace(/^\s*(?:<think_fluxflow>|\[think_fluxflow\])\s*/gi,"");Dt&&(pe+=Dt)}ut=!1,ve=""}let $=B instanceof Error?(()=>{try{return JSON.parse(JSON.parse(B.message).error.message).error.message}catch{return String(B)}})():String(B),pt=new Date().toLocaleString(),Fe=W.join(wn,"agent");Ae.existsSync(Fe)||Ae.mkdirSync(Fe,{recursive:!0}),Ae.appendFileSync(W.join(Fe,"error.log"),`ERROR [${pt}]: ${$}
833
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(String(ee).includes("Incomplete JSON segment at the end")){q&&(q=!1,ut?ve+="</think_fluxflow>":(pe+="</think_fluxflow>",yield{type:"text",content:"</think_fluxflow>"})),Ue=!0,await Lt("agent",s);break}if(q&&(q=!1,ut?ve+="</think_fluxflow>":pe+="</think_fluxflow>"),ut&&ve.length>0){let vt=0,mt=Math.min(_t.length,ve.length);for(let ot=mt;ot>0;ot--)if(_t.endsWith(ve.substring(0,ot))){vt=ot;break}let bt=ve.substring(vt);if(bt){let Dt=/(?:<think_fluxflow>|\[think_fluxflow\])(?:(?!(?:<\/think_fluxflow>|\[\/think_fluxflow\]))[\s\S])*$/i.test(_t)?bt.replace(/^\s*(?:<think_fluxflow>|\[think_fluxflow\])\s*/gi,""):bt.replace(/^\s*(?:<think_fluxflow>|\[think_fluxflow\])[\s\S]*?(?:<\/think_fluxflow>|\[\/think_fluxflow\])\s*/gi,"").replace(/^\s*(?:<think_fluxflow>|\[think_fluxflow\])\s*/gi,"");Dt&&(pe+=Dt)}ut=!1,ve=""}let M=ee instanceof Error?(()=>{try{return JSON.parse(JSON.parse(ee.message).error.message).error.message}catch{return String(ee)}})():String(ee),gt=new Date().toLocaleString(),Le=U.join(wn,"agent");Ae.existsSync(Le)||Ae.mkdirSync(Le,{recursive:!0}),Ae.appendFileSync(U.join(Le,"error.log"),`ERROR [${gt}]: ${M}
833
834
 
834
835
  ----------------------------------------------------------------------
835
836
 
836
- `);let Ke=B.status||B.statusCode||B.code,It=String(B).includes("replicas at capacity");if(!(Ke&&(Ke>=500&&Ke<600||Ke===408||Ke===429||It)||!Ke&&(/status[ :]+(5\d\d|408|429)/i.test(String(B))||/code[ :]+(5\d\d|408|429)/i.test(String(B))||/(500|503|408|429)/.test(String(B))))){if(qe<xn-3)throw B;yield{type:"text",content:$},yield{type:"status",content:"Error Occured"}}if(pe.trim().length>0||Ze>1)if(Ze<=xn){Ze++;let vt=Math.min(1e3*Math.pow(2,Ze-1),24e3);if(pe.trim().length>0){b.push({role:"agent",text:pe});let gt=`[system]
837
+ `);let Ke=ee.status||ee.statusCode||ee.code,It=String(ee).includes("replicas at capacity");if(!(Ke&&(Ke>=500&&Ke<600||Ke===408||Ke===429||It)||!Ke&&(/status[ :]+(5\d\d|408|429)/i.test(String(ee))||/code[ :]+(5\d\d|408|429)/i.test(String(ee))||/(500|503|408|429)/.test(String(ee))))){if(qe<bn-3)throw ee;yield{type:"text",content:M},yield{type:"status",content:"Error Occured"}}if(pe.trim().length>0||Ze>1)if(Ze<=bn){Ze++;let vt=Math.min(1e3*Math.pow(2,Ze-1),24e3);if(pe.trim().length>0){b.push({role:"agent",text:pe});let mt=`[system]
837
838
  - seamless continuation: resume immediately. pick up from last words with zero gap/disruption
838
839
  - no repetition: do not repeat any text already written
839
840
  - no re-think: do not restart or open <think_fluxflow> if reasoning already started. continue the thinking and close thinking block </think_fluxflow> before chat output
840
841
  - mid-tool safety: if cutoff was mid-tool call, restart that tool call from start
841
- - stealth: do not mention/apologize for cutoff [/system]`;He.length>0?He.forEach((bt,ot)=>{ot===He.length-1?b.push({...bt,text:`${bt.text}
842
+ - stealth: do not mention/apologize for cutoff [/system]`;We.length>0?We.forEach((bt,ot)=>{ot===We.length-1?b.push({...bt,text:`${bt.text}
842
843
 
843
- ${gt}`}):b.push(bt)}):b.push({role:"user",text:gt}),_t+=pe}for(let gt=vt/1e3;gt>0&&!Et;gt--)yield{type:"status",content:`Error Occured. Recovering Stream (${Ze}/${xn}) [Retrying in ${gt.toFixed(0)}s]...`},await new Promise(bt=>setTimeout(bt,1e3));yield{type:"status",content:"Error Occured. Recovering Stream..."}}else throw new Error(`Stream collapsed too many times. (Failed to resolve ${xn} times)
844
- Error log can be found in \`/export logs\``);else{let gt=e.split("/").slice(e.endsWith("/free")?-2:-1).join("/");if(qe<=xn){qe++,Ze=1,_t="";let bt=Math.min(1e3*Math.pow(2,qe-1),32e3),ot=.8+Math.random()*.4,Dt=Math.round(bt*ot);Ln=!0,yield{type:"status",content:`Trying to reach ${gt} (${qe}/${xn}) [Retrying in ${(Dt/1e3).toFixed(0)}s]`};for(let Ge=Dt/1e3;Ge>0&&!Et;Ge--)yield{type:"status",content:`Trying to reach ${gt} (${qe}/${xn}) [Retrying in ${Ge.toFixed(0)}s]`},await new Promise(Ut=>setTimeout(Ut,1e3));yield{type:"status",content:`Trying to reach ${gt}`}}else throw new Error(`Model ${e} cannot be reached. (Failed ${xn} times)
845
- Error log can be found in \`/export logs\``)}}}if(fn){let X=fn.totalTokenCount||0,B=fn.cachedContentTokenCount||0,$=(fn.candidatesTokenCount||0)+(s==="Google"&&fn.thoughtsTokenCount||0);await At("tokens",X,s,ne),B>0&&await At("cachedTokens",B,s,ne),$>0&&await At("candidateTokens",$,s,ne),Te!==null&&Te>0&&await At("ttft",Te,s,ne),Co({provider:s,model:ne,prompt:fn.promptTokenCount||0,cached:B,output:$,reasoning:fn.thoughtsTokenCount||0,ttft:Te}),yield{type:"usage",content:fn}}else Te!==null&&Te>0&&(await At("ttft",Te,s,ne),Co({provider:s,model:ne,prompt:0,cached:0,output:0,reasoning:0,ttft:Te}));pe=sa(pe),Ti.push(pe);let kl=Kt(pe),Ei=na(pe),ga=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(Ei.toLowerCase())||/\[\[END\]\]/i.test(Ei.toLowerCase())||!0,Tl=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(Ei.toLowerCase()),Al=Rt>0;yield{type:"status",content:process.env.HALLOWEEN_EEGG==="true"?"Performing dark ritual":"Thinking"};let ma=xl(pe,/(\[\s*(turn\s*:)?\s*(continue|finish)\s*\]|\[\[END\]\])/gi,"").trim(),Vn=(ga||He.length===0)&&!Bt&&!Kn&&!Xt;if(Vn=He.length===0?Vn:!1,Vn=nn||Vo?!1:Vn,pe&&pe.trim().endsWith('")]')&&He.length===0&&(Vn=!1),Vn){Cs=!0;let X=Ti.join(`
846
- `),B=Kt(X).trim();yield{type:"interactive_turn_finished",data:{agentText:Me,fullAgentTextRaw:X,history:[...b],needTitle:Ce}},b.length>0&&b[b.length-1].role==="agent"?b[b.length-1].text=B:b.push({role:"agent",text:B}),b.forEach($=>{if($.role==="user"&&$.text&&($.text=$.text.replace(/\n\[COMPILE ERROR\][\s\S]*?\[\/ERROR\]/g,""),$.text=$.text.replaceAll(`
844
+ ${mt}`}):b.push(bt)}):b.push({role:"user",text:mt}),_t+=pe}for(let mt=vt/1e3;mt>0&&!Et;mt--)yield{type:"status",content:`Error Occured. Recovering Stream (${Ze}/${bn}) [Retrying in ${mt.toFixed(0)}s]...`},await new Promise(bt=>setTimeout(bt,1e3));yield{type:"status",content:"Error Occured. Recovering Stream..."}}else throw new Error(`Stream collapsed too many times. (Failed to resolve ${bn} times)
845
+ Error log can be found in \`/export logs\``);else{let mt=e.split("/").slice(e.endsWith("/free")?-2:-1).join("/");if(qe<=bn){qe++,Ze=1,_t="";let bt=Math.min(1e3*Math.pow(2,qe-1),32e3),ot=.8+Math.random()*.4,Dt=Math.round(bt*ot);Ln=!0,yield{type:"status",content:`Trying to reach ${mt} (${qe}/${bn}) [Retrying in ${(Dt/1e3).toFixed(0)}s]`};for(let He=Dt/1e3;He>0&&!Et;He--)yield{type:"status",content:`Trying to reach ${mt} (${qe}/${bn}) [Retrying in ${He.toFixed(0)}s]`},await new Promise(Wt=>setTimeout(Wt,1e3));yield{type:"status",content:`Trying to reach ${mt}`}}else throw new Error(`Model ${e} cannot be reached. (Failed ${bn} times)
846
+ Error log can be found in \`/export logs\``)}}}if(fn){let q=fn.totalTokenCount||0,ee=fn.cachedContentTokenCount||0,M=(fn.candidatesTokenCount||0)+(s==="Google"&&fn.thoughtsTokenCount||0);await At("tokens",q,s,ne),ee>0&&await At("cachedTokens",ee,s,ne),M>0&&await At("candidateTokens",M,s,ne),Te!==null&&Te>0&&await At("ttft",Te,s,ne),Co({provider:s,model:ne,prompt:fn.promptTokenCount||0,cached:ee,output:M,reasoning:fn.thoughtsTokenCount||0,ttft:Te}),yield{type:"usage",content:fn}}else Te!==null&&Te>0&&(await At("ttft",Te,s,ne),Co({provider:s,model:ne,prompt:0,cached:0,output:0,reasoning:0,ttft:Te}));pe=sa(pe),Ai.push(pe);let Tl=Bt(pe),Ci=na(pe),ga=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(Ci.toLowerCase())||/\[\[END\]\]/i.test(Ci.toLowerCase())||!0,Al=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(Ci.toLowerCase()),El=Rt>0;yield{type:"status",content:process.env.HALLOWEEN_EEGG==="true"?"Performing dark ritual":"Thinking"};let ma=bl(pe,/(\[\s*(turn\s*:)?\s*(continue|finish)\s*\]|\[\[END\]\])/gi,"").trim(),pa=We.length>0||jn(Bt(pe)).length>0,Yn=(ga||We.length===0)&&!Ut&&!Vn&&!Xt;if(Yn=We.length===0?Yn:!1,Yn=pa&&nn||Vo?!1:Yn,pe&&pe.trim().endsWith('")]')&&We.length===0&&(Yn=!1),Yn){Cs=!0;let q=Ai.join(`
847
+ `),ee=Bt(q).trim();yield{type:"interactive_turn_finished",data:{agentText:Me,fullAgentTextRaw:q,history:[...b],needTitle:Ce}},b.length>0&&b[b.length-1].role==="agent"?b[b.length-1].text=ee:b.push({role:"agent",text:ee}),b.forEach(M=>{if(M.role==="user"&&M.text&&(M.text=M.text.replace(/\n\[COMPILE ERROR\][\s\S]*?\[\/ERROR\]/g,""),M.text=M.text.replaceAll(`
847
848
 
848
849
  [system] user question. resolve this specific query within '[ANSWER] ... [/ANSWER]' concisely, naturally [/system]
849
850
  `,"").replaceAll(`[system] user question. resolve this specific query within '[ANSWER] ... [/ANSWER]' concisely, naturally
850
851
  **strictly follow thinking policy as high priority. do not start a response without <think_fluxflow>...</think_fluxflow>** [/system]
851
852
  `,"").replaceAll(`[system] **strictly follow thinking policy as high priority. do not start a response without <think_fluxflow>...</think_fluxflow>** [/system]
852
- `,"").replaceAll(/\n\[system\] WARNING, Turn Limit Impending: Step \d+\/\d+\. Wrap up quickly\/prompt user to continue & use \[\[END\]\] quickly\. \[\/system\]/g,""),$.text=$.text.replaceAll(/\n\[system\] File Changes:\n(?:\* .+ \(created|modified|deleted\)\n)*\[\/system\]/g,""),(s==="Mistral"||s==="Google"&&e?.toLowerCase().startsWith("gemma"))&&($.text.startsWith("[ACTION RESULT]")||$.text.startsWith("[TOOL RESULT]")))){let Fe=`
853
+ `,"").replaceAll(/\n\[system\] WARNING, Turn Limit Impending: Step \d+\/\d+\. Wrap up quickly\/prompt user to continue & use \[\[END\]\] quickly\. \[\/system\]/g,""),M.text=M.text.replaceAll(/\n\[system\] File Changes:\n(?:\* .+ \(created|modified|deleted\)\n)*\[\/system\]/g,""),(s==="Mistral"||s==="Google"&&e?.toLowerCase().startsWith("gemma"))&&(M.text.startsWith("[ACTION RESULT]")||M.text.startsWith("[TOOL RESULT]")))){let Le=`
853
854
  [system] Action result received. Analyze output and proceed with your turn [/system]`,Ke=`
854
- [system] Action result received. Analyze output and proceed with your turn. **strictly follow thinking policy. do not start a response without <think_fluxflow>...</think_fluxflow>** [/system]`;$.text=$.text.replaceAll(Ke,"").replaceAll(Fe,"").trim()}}),yield{type:"status",content:"[end]"}}if(Vn)break;let pa=ma.trim()||"*Working...*";if(b.push({role:"agent",text:pa}),He.length>0||En){if(He.length>0){let X=He.map(ot=>ot.text).join(`
855
+ [system] Action result received. Analyze output and proceed with your turn. **strictly follow thinking policy. do not start a response without <think_fluxflow>...</think_fluxflow>** [/system]`;M.text=M.text.replaceAll(Ke,"").replaceAll(Le,"").trim()}}),yield{type:"status",content:"[end]"}}if(Yn)break;let ha=ma.trim()||"*Working...*";if(b.push({role:"agent",text:ha}),We.length>0||En){if(We.length>0){let q=We.map(ot=>ot.text).join(`
855
856
 
856
- `),B=Kt(pe),$=ys(B),pt=eo(B),Fe=/\[\s*(?:tool:(?:functions\.)?|action:(?:functions\.)?|action:)([a-zA-Z0-9_]+)\s*\(/gi,Ke=[],It=[],Ee;for(;(Ee=Fe.exec($))!==null;)It.push({index:Ee.index,toolName:Ee[1]});for(let ot=0;ot<It.length;ot++){let Dt=It[ot],Ge=ot+1<It.length?It[ot+1].index:B.length;pt.some(io=>io.fullMatch&&B.startsWith(io.fullMatch,Dt.index))||Ke.push(B.substring(Dt.index,Ge))}let vt=Ke.length,gt=He.length+vt;if(vt>0){let ot=Ke.join(`
857
- `),Dt=oa(ot);X+=`
857
+ `),ee=Bt(pe),M=yi(ee),gt=jn(ee),Le=/\[\s*(?:tool:(?:functions\.)?|action:(?:functions\.)?|action:)([a-zA-Z0-9_]+)\s*\(/gi,Ke=[],It=[],Ee;for(;(Ee=Le.exec(M))!==null;)It.push({index:Ee.index,toolName:Ee[1]});for(let ot=0;ot<It.length;ot++){let Dt=It[ot],He=ot+1<It.length?It[ot+1].index:ee.length;gt.some(io=>io.fullMatch&&ee.startsWith(io.fullMatch,Dt.index))||Ke.push(ee.substring(Dt.index,He))}let vt=Ke.length,mt=We.length+vt;if(vt>0){let ot=Ke.join(`
858
+ `),Dt=oa(ot);q+=`
858
859
 
859
- [system] Only ${He.length} out of ${gt} attempted tool calls were executed.
860
+ [system] Only ${We.length} out of ${mt} attempted tool calls were executed.
860
861
  ${Dt?`Parsing Issues Detected:
861
862
  ${Dt}
862
- `:""}Verify proper structure compliance [action:ActionName(arg="value")] & try failed calls again [/system]`;for(let Ge=0;Ge<vt;Ge++)await Lt("toolFailure")}let bt=He.find(ot=>ot.binaryPart)?.binaryPart||null;b.push({role:"user",text:X,binaryPart:bt})}}else if(!Et){let X=pe.replace(/(?:<think_fluxflow>|\[think_fluxflow\])[\s\S]*?(?:<\/think_fluxflow>|\[\/think_fluxflow\]|$)/i,""),B=(X.match(/\[(?:tool|action):/gi)||[]).length;if(Vo||nn||B>0){let $=oa(X),pt=$?`[system] Failed to execute ${B>0?B:1} tool call${B>1?"s":""} due to syntax/structure issues:
863
- ${$} [/system]`:`[system] Failed to execute ${B>0?B:1} tool${B>1?"s":""}. Verify proper structure compliance [action:ActionName(arg="value")] & try again [/system]`;b.push({role:"user",text:pt}),await Lt("toolFailure"),yield{type:"visual_feedback",content:`
864
- ${jt("\u2718 Model produced malformed tool call")}
863
+ `:""}Verify proper structure compliance [action:ActionName(arg="value")] & try failed calls again [/system]`;for(let He=0;He<vt;He++)await Lt("toolFailure")}let bt=We.find(ot=>ot.binaryPart)?.binaryPart||null;b.push({role:"user",text:q,binaryPart:bt})}}else if(!Et){let q=pe.replace(/(?:<think_fluxflow>|\[think_fluxflow\])[\s\S]*?(?:<\/think_fluxflow>|\[\/think_fluxflow\]|$)/i,""),M=(yi(q).match(/\[\s*(?:tool:(?:functions\.)?|action:(?:functions\.)?|action:)([a-zA-Z0-9_]+)\s*\(/gi)||[]).length;if(Vo||nn&&M>0||M>0){let gt=oa(q),Le=gt?`[system] Failed to execute ${M>0?M:1} tool call${M>1?"s":""} due to syntax/structure issues:
864
+ ${gt} [/system]`:`[system] Failed to execute ${M>0?M:1} tool${M>1?"s":""}. Verify proper structure compliance [action:ActionName(arg="value")] & try again [/system]`;b.push({role:"user",text:Le}),await Lt("toolFailure"),yield{type:"visual_feedback",content:`
865
+ ${Kt("\u2718 Model produced malformed tool call")}
865
866
  `}}else yield{type:"visual_feedback",content:`
866
- ${jt("\u2718 Loop Detected")}
867
- `},b.push({role:"user",text:`[system] ${Kn&&!Bt?"Stuttering Detected by Internal System. Re-calibrate your response & proceed.":`${Bt?" Over Thinking":" Loop"} Detected by Internal System${Bt?" for current Effort Level":""}. ${Bt?"If you have planned the task, prioritize execution/output":"If you have finished your task provide a simple summary and end"}`} [/system]`});Bt=!1,Kn=!1,Xt=!1}p?.advanceRollback&&await Ro.recordTurnDelta(h,v+1,Ie),Ai=Ie.includes("recapture_screen"),Vo=Rt>0||En}if(!Cs&&!Et){let v="\u2726 Turn safety limit reached. Stopping execution.";yield{type:"text",content:`
867
+ ${Kt("\u2718 Loop Detected")}
868
+ `},b.push({role:"user",text:`[system] ${Vn&&!Ut?"Stuttering Detected by Internal System. Re-calibrate your response & proceed.":`${Ut?" Over Thinking":" Loop"} Detected by Internal System${Ut?" for current Effort Level":""}. ${Ut?"If you have planned the task, prioritize execution/output":"If you have finished your task provide a simple summary and end"}`} [/system]`});Ut=!1,Vn=!1,Xt=!1}p?.advanceRollback&&await Ro.recordTurnDelta(h,I+1,Ie),Ei=Ie.includes("recapture_screen"),Vo=Rt>0||En}if(!Cs&&!Et){let I="\u2726 Turn safety limit reached. Stopping execution.";yield{type:"text",content:`
868
869
 
869
- ${v}
870
- `};let _e=(Ti.join(`
870
+ ${I}
871
+ `};let _e=(Ai.join(`
871
872
  `)+`
872
- ${v}`).trim();yield{type:"interactive_turn_finished",data:{agentText:Me,fullAgentTextRaw:_e,history:[...b],needTitle:Ce}},yield{type:"status",content:"[end]"}}}catch(G){let b=G?.cause?` (Cause: ${G.cause?.message||String(G.cause)})`:"",fe=(G instanceof Error?(()=>{try{return JSON.parse(JSON.parse(G.message).error.message).error.message}catch{return(G.message?`${G.message}${b}`:"")||String(G)}})():String(G)).replace(/^(Error:\s*)+/i,"");s==="Google"&&!/^[A-Z0-9_\-\s]+ ERROR:/i.test(fe)&&(fe=`GEMINI ERROR: ${fe}`);let q=new Date().toLocaleString(),tn=W.join(wn,"agent");yield{type:"text",content:`
873
+ ${I}`).trim();yield{type:"interactive_turn_finished",data:{agentText:Me,fullAgentTextRaw:_e,history:[...b],needTitle:Ce}},yield{type:"status",content:"[end]"}}}catch(W){let b=W?.cause?` (Cause: ${W.cause?.message||String(W.cause)})`:"",fe=(W instanceof Error?(()=>{try{return JSON.parse(JSON.parse(W.message).error.message).error.message}catch{return(W.message?`${W.message}${b}`:"")||String(W)}})():String(W)).replace(/^(Error:\s*)+/i,"");s==="Google"&&!/^[A-Z0-9_\-\s]+ ERROR:/i.test(fe)&&(fe=`GEMINI ERROR: ${fe}`);let z=new Date().toLocaleString(),tn=U.join(wn,"agent");yield{type:"text",content:`
873
874
 
874
875
  \u2726 CRITICAL ERROR: ${fe.includes("fetch failed")?"Failed to Connect. Check your Internet Connection or Wait a moment":fe}
875
- \u2800`},Ae.existsSync(tn)||Ae.mkdirSync(tn,{recursive:!0}),Ae.appendFileSync(W.join(tn,"error.log"),`CRITICAL ERROR [${q}]: ${G}${G?.cause?`
876
- CAUSE: ${G.cause?.stack||G.cause}`:""}
876
+ \u2800`},Ae.existsSync(tn)||Ae.mkdirSync(tn,{recursive:!0}),Ae.appendFileSync(U.join(tn,"error.log"),`CRITICAL ERROR [${z}]: ${W}${W?.cause?`
877
+ CAUSE: ${W.cause?.stack||W.cause}`:""}
877
878
 
878
879
  ----------------------------------------------------------------------
879
880
 
880
- `),typeof flushGoogleBuffer=="function"&&(yield*flushGoogleBuffer()),yield{type:"tool_result",content:`ERROR: [INTERNAL CRITICAL] ${fe}`}}finally{Je&&(clearInterval(Je),Je=null),typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),await ti.commitTransaction(),p?.advanceRollback&&await Ro.cleanup(h),await Jn()}yield{type:"status",content:null}},Bd=async(e,n,t=null,i=null,o=50,r=null,c=!1)=>{let a=await Eo(),u={...a,...n},h=process.env.SUBAGENT_MODEL?process.env.SUBAGENT_MODEL.trim():null,x=process.env.SUBAGENT_PROVIDER?process.env.SUBAGENT_PROVIDER.trim():null,p=new Date,f=`${p.getFullYear()}-${p.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(p.getDate()).padStart(2,"0")}, ${p.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}).replace(":","-")}`,g=(fe=>{if(!fe)return null;let q=fe.toLowerCase();return q==="google"?"Google":q==="deepseek"?"DeepSeek":q==="openrouter"?"OpenRouter":q==="nvidia"?"NVIDIA":q==="mistral"?"Mistral":q==="ollama"?"Ollama":q==="inferx"?"InferX":q==="sensenova"?"SenseNova":q==="poolside"?"Poolside":q==="9router"||q==="9Router"?"9router":q==="aihubmix"||q==="aihub"?"AIHubMix":q==="explabs"||q==="experientiallabs"||q==="experimentallabs"?"ExpLabs":q==="tokenharbor"||q==="token harbor"||q==="token_harbor"||q==="thk"?"TokenHarbor":q==="infron"?"Infron":q==="apinex"||q==="apx"?"APInex":q==="xkiro"||q==="kiro"?"xKiro":q==="c_openai"||q==="custom_openai"||q==="custom (openai)"||q==="custom"?"c_openai":null})(x),k=u?.systemSettings?.CustomSubAgent?u?.systemSettings?.SubAgentModel:null,he=u?.systemSettings?.CustomSubAgent?u?.systemSettings?.SubAgentProvider:null,y=null;if(k==="ENV"?(y=h,h&&g&&(u.aiProvider=g)):k&&k!=="Default"?(y=k,he&&(u.aiProvider=he)):h&&g&&(u.aiProvider=g),u.aiProvider){let fe=await Li(u.aiProvider);fe&&(u.apiKey=fe)}let E=fe=>{if(!fe||typeof fe!="string")return{allowed:!0};let q=[/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 tn of q)if(tn.test(fe))return{allowed:!1,reason:`Blocked potentially destructive or unsafe command pattern: "${tn.source}"`};return{allowed:!0}},D=t||y||n?.modelName||n?.activeModel||a.activeModel,O=(process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux")==="Windows",T=O&&u?.systemSettings?.preferBash!==!1&&Ls(),Se="Run(command=string)",Ce=`Runs ${O?Fi()?"powershell":"windows CMD":"bash"} command`;T&&(Se=`Run(command=string, ${$s()||Fi()?"forcePowershell?=bool:false":"forceCwd?=bool:false"})`,Ce="Runs in git bash. Or force native shell");let Me=`-- ACTIONS (path = relative to CWD, path separator: '/') --
881
+ `),typeof flushGoogleBuffer=="function"&&(yield*flushGoogleBuffer()),yield{type:"tool_result",content:`ERROR: [INTERNAL CRITICAL] ${fe}`}}finally{Je&&(clearInterval(Je),Je=null),typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),await ti.commitTransaction(),p?.advanceRollback&&await Ro.cleanup(h),await Qn()}yield{type:"status",content:null}},Ud=async(e,n,t=null,i=null,o=50,r=null,d=!1)=>{let a=await Eo(),u={...a,...n},h=process.env.SUBAGENT_MODEL?process.env.SUBAGENT_MODEL.trim():null,x=process.env.SUBAGENT_PROVIDER?process.env.SUBAGENT_PROVIDER.trim():null,p=new Date,f=`${p.getFullYear()}-${p.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(p.getDate()).padStart(2,"0")}, ${p.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}).replace(":","-")}`,g=(fe=>{if(!fe)return null;let z=fe.toLowerCase();return z==="google"?"Google":z==="deepseek"?"DeepSeek":z==="openrouter"?"OpenRouter":z==="nvidia"?"NVIDIA":z==="mistral"?"Mistral":z==="ollama"?"Ollama":z==="inferx"?"InferX":z==="sensenova"?"SenseNova":z==="poolside"?"Poolside":z==="9router"||z==="9Router"?"9router":z==="aihubmix"||z==="aihub"?"AIHubMix":z==="explabs"||z==="experientiallabs"||z==="experimentallabs"?"ExpLabs":z==="tokenharbor"||z==="token harbor"||z==="token_harbor"||z==="thk"?"TokenHarbor":z==="infron"?"Infron":z==="apinex"||z==="apx"?"APInex":z==="xkiro"||z==="kiro"?"xKiro":z==="c_openai"||z==="custom_openai"||z==="custom (openai)"||z==="custom"?"c_openai":null})(x),k=u?.systemSettings?.CustomSubAgent?u?.systemSettings?.SubAgentModel:null,he=u?.systemSettings?.CustomSubAgent?u?.systemSettings?.SubAgentProvider:null,y=null;if(k==="ENV"?(y=h,h&&g&&(u.aiProvider=g)):k&&k!=="Default"?(y=k,he&&(u.aiProvider=he)):h&&g&&(u.aiProvider=g),u.aiProvider){let fe=await $i(u.aiProvider);fe&&(u.apiKey=fe)}let E=fe=>{if(!fe||typeof fe!="string")return{allowed:!0};let z=[/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 tn of z)if(tn.test(fe))return{allowed:!1,reason:`Blocked potentially destructive or unsafe command pattern: "${tn.source}"`};return{allowed:!0}},D=t||y||n?.modelName||n?.activeModel||a.activeModel,L=(process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux")==="Windows",T=L&&u?.systemSettings?.preferBash!==!1&&Ls(),Se="Run(command=string)",Ce=`Runs ${L?Bi()?"powershell":"windows CMD":"bash"} command`;T&&(Se=`Run(command=string, ${$s()||Bi()?"forcePowershell?=bool:false":"forceCwd?=bool:false"})`,Ce="Runs in git bash. Or force native shell");let Me=`-- ACTIONS (path = relative to CWD, path separator: '/') --
881
882
  In chat output the format \`[action:ActionName(arg1="value1")]\` in NEW line
882
883
  Rules:
883
884
  - JSON escape literal sequences, backslash: \\\\, newLine: \\ n
@@ -888,11 +889,11 @@ Rules:
888
889
  # Provided Actions
889
890
  **Communication**
890
891
  - AskUser(question=string, optionA?="title::description", ...MAX4). Any Ambiguity
891
- ${c?"- AskMain(question=string). Communicate with PARENT/MAIN AGENT. When clarification/decision is needed for a task":""}
892
+ ${d?"- AskMain(question=string). Communicate with PARENT/MAIN AGENT. When clarification/decision is needed for a task":""}
892
893
 
893
894
  **Web**
894
- - WebSearch(query=string, aiMode?=bool:false, limit?=int[3..10]). Proactive use for unknown/latest info
895
- - WebScrape(url=string). Proactive use for specific webpage/docs
895
+ - WebSearch(query=string, aiMode?=bool:false, limit?=int[3..10]). For unknown topics, time sensitive, fact checking
896
+ - WebScrape(url=string). JS supported
896
897
 
897
898
  **Workspace**
898
899
  - CodeSearch(keyword=string, path?="file/glob, inclusion !exclusion ;-separated", regex?=bool:auto)
@@ -914,30 +915,30 @@ Main focus: actions and task, not chatting
914
915
  On completion, provide a detailed summary in Tables/Markdown Format with file modified info. If any task failed report back in detail
915
916
 
916
917
  Current Time: ${f}
917
- === END SYSTEM PROMPT ===`,G=[{role:"user",text:`Complete this task: ${e}`}],b=0,ht="";for(;b<o;){let fe=await $i("subagent",u);if(!fe.allowed)throw new Error(fe.reason||`Budget Exhausted for Provider (${u?.aiProvider||"Subagent"})`);if(Et){if(n?.taskId&&typeof en<"u"){let H=en.find(_=>_.id===n.taskId);H&&(H.status="cancelled")}throw r&&r("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}if(n?.taskId&&typeof en<"u"){let H=en.find(_=>_.id===n.taskId);if(H&&H.status==="cancelled")throw r&&r("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}let q=G.map(H=>({role:H.role==="user"?"user":"model",parts:[{text:H.text}]}));r&&r(`[Subagent Turn ${b+1}]...`);let tn=["Fast","Low","Medium","High"],Vt=process.env.SUBAGENT_THINKING,cn=tn.includes(Vt)?Vt:"Low",Pn=(await yi(u,D,q,Je,cn)).text||"",dn=sa(Kt(Pn).trim());ht=dn,r&&r(`[Subagent Response]
918
+ === END SYSTEM PROMPT ===`,W=[{role:"user",text:`Complete this task: ${e}`}],b=0,ht="";for(;b<o;){let fe=await Ni("subagent",u);if(!fe.allowed)throw new Error(fe.reason||`Budget Exhausted for Provider (${u?.aiProvider||"Subagent"})`);if(Et){if(n?.taskId&&typeof en<"u"){let G=en.find(_=>_.id===n.taskId);G&&(G.status="cancelled")}throw r&&r("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}if(n?.taskId&&typeof en<"u"){let G=en.find(_=>_.id===n.taskId);if(G&&G.status==="cancelled")throw r&&r("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}let z=W.map(G=>({role:G.role==="user"?"user":"model",parts:[{text:G.text}]}));r&&r(`[Subagent Turn ${b+1}]...`);let tn=["Fast","Low","Medium","High"],Vt=process.env.SUBAGENT_THINKING,cn=tn.includes(Vt)?Vt:"Low",Pn=(await xi(u,D,z,Je,cn)).text||"",dn=sa(Bt(Pn).trim());ht=dn,r&&r(`[Subagent Response]
918
919
  ${dn}
919
- `),G.push({role:"agent",text:dn});let yt=eo(dn);if(yt.length===0)break;let Yt=yt.filter(H=>H.toolName.toLowerCase()==="askmain"||H.toolName.toLowerCase()==="ask_main"),ue=!1,Be="";for(let H of yt){if(Et){if(n?.taskId&&typeof en<"u"){let S=en.find(L=>L.id===n.taskId);S&&(S.status="cancelled")}throw new Error("Subagent task was cancelled.")}if(n?.taskId&&typeof en<"u"){let S=en.find(L=>L.id===n.taskId);if(S&&S.status==="cancelled")throw new Error("Subagent task was cancelled.")}let _=H.toolName.toLowerCase();if(_==="askuser"&&(_="ask"),_==="askmain"||_==="ask_main"){if(ue)continue;ue=!0;let S="";if(Yt.length===1?S=j(Yt[0].args).question||Yt[0].args:S=Yt.map((L,ct)=>{let ze=j(L.args);return`Q${ct+1}: ${ze.question||L.args}`}).join(`
920
- `),n.onAskMain){r&&r(`[Executing Tool] AskMain("${S}")...`);let L=await n.onAskMain(S);r&&r(`[Action Result]
921
- Answer from Main Agent: ${L}
922
- `),Be+=`[ACTION RESULT for AskMain]: Answer from Main Agent: ${L}
920
+ `),W.push({role:"agent",text:dn});let yt=jn(dn);if(yt.length===0)break;let Yt=yt.filter(G=>G.toolName.toLowerCase()==="askmain"||G.toolName.toLowerCase()==="ask_main"),ue=!1,Be="";for(let G of yt){if(Et){if(n?.taskId&&typeof en<"u"){let S=en.find($=>$.id===n.taskId);S&&(S.status="cancelled")}throw new Error("Subagent task was cancelled.")}if(n?.taskId&&typeof en<"u"){let S=en.find($=>$.id===n.taskId);if(S&&S.status==="cancelled")throw new Error("Subagent task was cancelled.")}let _=G.toolName.toLowerCase();if(_==="askuser"&&(_="ask"),_==="askmain"||_==="ask_main"){if(ue)continue;ue=!0;let S="";if(Yt.length===1?S=j(Yt[0].args).question||Yt[0].args:S=Yt.map(($,ct)=>{let ze=j($.args);return`Q${ct+1}: ${ze.question||$.args}`}).join(`
921
+ `),n.onAskMain){r&&r(`[Executing Tool] AskMain("${S}")...`);let $=await n.onAskMain(S);r&&r(`[Action Result]
922
+ Answer from Main Agent: ${$}
923
+ `),Be+=`[ACTION RESULT for AskMain]: Answer from Main Agent: ${$}
923
924
 
924
925
  `,await Lt("toolSuccess")}else Be+=`[ACTION RESULT for AskMain]: ERROR: Main agent communication channel not available.
925
926
 
926
- `;continue}if(!(i?i.some(S=>S.toLowerCase()===_):!0)){let S=`ERROR: Tool [${H.toolName}] is not in the allowed tools list for this subagent.`;r&&r(`[Blocked Tool Call] ${H.toolName} - not allowed
927
+ `;continue}if(!(i?i.some(S=>S.toLowerCase()===_):!0)){let S=`ERROR: Tool [${G.toolName}] is not in the allowed tools list for this subagent.`;r&&r(`[Blocked Tool Call] ${G.toolName} - not allowed
927
928
  `),Be+=`${S}
928
929
 
929
- `;continue}if(_==="exec_command"||_==="execcommand"||_==="run"){let S=j(H.args).command||"",L=E(S);if(!L.allowed){let ct=`ERROR: [SECURITY RESTRICTION] Subagent execution blocked command: ${L.reason}`;r&&r(`[Blocked Command] ${S} - ${L.reason}
930
+ `;continue}if(_==="exec_command"||_==="execcommand"||_==="run"){let S=j(G.args).command||"",$=E(S);if(!$.allowed){let ct=`ERROR: [SECURITY RESTRICTION] Subagent execution blocked command: ${$.reason}`;r&&r(`[Blocked Command] ${S} - ${$.reason}
930
931
  `),Be+=`${ct}
931
932
 
932
- `;continue}}let Oe="";if(_==="web_search"||_==="websearch")Oe=`\u2714 \x1B[95mSearched\x1B[0m: ${j(H.args).query||""}`;else if(_==="web_scrape"||_==="webscrape")Oe=`\u2714 \x1B[95mScraped\x1B[0m: ${j(H.args).url||""}`;else if(_==="search_keyword"||_==="searchkeyword"||_==="codesearch"||_==="code_search"){let S=j(H.args),L=S.keyword||"",ct=S.path||"";Oe=`${L?"\u2714":"\u2718"} \x1B[95mSearched\x1B[0m: ${L||"No Query"}${ct?` \u2192 ${ct.replaceAll("\\","/")}`:""}`}else if(_==="view_file"||_==="viewfile"||_==="readfile")Oe=`\u2714 \x1B[95mRead\x1B[0m: ${(j(H.args).path||"").replaceAll("\\","/")}`;else if(_==="find_file"||_==="findfile"){let S=j(H.args),L=S.basename||S.name||S.path||S.file||S.query||"";Oe=`${L?"\u2714":"\u2718"} \x1B[95mLocated\x1B[0m: ${L||"No Query"}`}else if(_==="list_files"||_==="read_folder"||_==="readfolder"){let S=j(H.args).path||null,L=j(H.args).recurse||0;Oe=`${S?"\u2714":"\u2718"} \x1B[95mBrowsed\x1B[0m: ${S?`${S.replaceAll("\\","/")}${L>0?`${S.endsWith("/")?`*${L}`:`/*${L}`}`:`${S.endsWith("/")?"":"/"}`}`:""}`}else if(_==="write_file"||_==="writefile"){let S=j(H.args).path||null;Oe=`${S?"\u2714":"\u2718"} \x1B[95mCreated\x1B[0m: ${S?`${S.replaceAll("\\","/")}`:"No File Changes"}`}else if(_==="update_file"||_==="updatefile"||_==="patchfile"||_==="patch_file"){let S=j(H.args),L=S.path||null,ze=Object.entries(S).some(([Ct,it])=>Ct.startsWith("searchContent")&&typeof it=="string"&&it.startsWith("^LINE:"))?"\u1361":":";Oe=`${L?"\u2714":"\u2718"} \x1B[95mEdited\x1B[0m${ze} ${L?`${L.replaceAll("\\","/")}`:"No File Changes"}`}else if(_==="exec_command"||_==="execcommand"||_==="run"){let S=j(H.args).command||null;Oe=`${S?"\u2714":"\u2718"} \x1B[95mExecuted\x1B[0m: ${S?S.slice(0,100)+(S.length>100?"...":""):"No Command"}`}else if(_==="file_map"||_==="filemap"){let S=j(H.args).path||"";Oe=`${S?"\u2714":"\u2718"} \x1B[95mIndexed\x1B[0m: ${S?`${S.replaceAll("\\","/")}`:"File Not Found"}`}else if(_==="await"){let{time:S}=j(H.args),L=parseFloat(S)||0;L<10&&(L=10),L>180&&(L=180),Oe=`\u2714 \x1B[95mAwaiting\x1B[0m \u2192 ${(ze=>{if(ze>=60){let Ct=Math.floor(ze/60),it=ze%60;return`${Ct}m${it>0?` ${it}s`:""}`}return`${ze}s`})(L)}`}else{let S=ms[_]||H.toolName,L=Zn(_,H.args);Oe=`\u2714 \x1B[95m${S}\x1B[0m${L?`: ${L}`:""}`}n.onVisualFeedback&&Oe&&n.onVisualFeedback(Oe),r&&r(`[Executing Tool] ${H.toolName}(${H.args})...`);try{let S=await Bo(H.toolName,H.args,{...n,mode:"Flux"});if(r&&r(`[Action Result]
933
+ `;continue}}let Oe="";if(_==="web_search"||_==="websearch")Oe=`\u2714 \x1B[95mSearched\x1B[0m: ${j(G.args).query||""}`;else if(_==="web_scrape"||_==="webscrape")Oe=`\u2714 \x1B[95mScraped\x1B[0m: ${j(G.args).url||""}`;else if(_==="search_keyword"||_==="searchkeyword"||_==="codesearch"||_==="code_search"){let S=j(G.args),$=S.keyword||"",ct=S.path||"";Oe=`${$?"\u2714":"\u2718"} \x1B[95mSearched\x1B[0m: ${$||"No Query"}${ct?` \u2192 ${ct.replaceAll("\\","/")}`:""}`}else if(_==="view_file"||_==="viewfile"||_==="readfile")Oe=`\u2714 \x1B[95mRead\x1B[0m: ${(j(G.args).path||"").replaceAll("\\","/")}`;else if(_==="find_file"||_==="findfile"){let S=j(G.args),$=S.basename||S.name||S.path||S.file||S.query||"";Oe=`${$?"\u2714":"\u2718"} \x1B[95mLocated\x1B[0m: ${$||"No Query"}`}else if(_==="list_files"||_==="read_folder"||_==="readfolder"){let S=j(G.args).path||null,$=j(G.args).recurse||0;Oe=`${S?"\u2714":"\u2718"} \x1B[95mBrowsed\x1B[0m: ${S?`${S.replaceAll("\\","/")}${$>0?`${S.endsWith("/")?`*${$}`:`/*${$}`}`:`${S.endsWith("/")?"":"/"}`}`:""}`}else if(_==="write_file"||_==="writefile"){let S=j(G.args).path||null;Oe=`${S?"\u2714":"\u2718"} \x1B[95mCreated\x1B[0m: ${S?`${S.replaceAll("\\","/")}`:"No File Changes"}`}else if(_==="update_file"||_==="updatefile"||_==="patchfile"||_==="patch_file"){let S=j(G.args),$=S.path||null,ze=Object.entries(S).some(([Ct,it])=>Ct.startsWith("searchContent")&&typeof it=="string"&&it.startsWith("^LINE:"))?"\u1361":":";Oe=`${$?"\u2714":"\u2718"} \x1B[95mEdited\x1B[0m${ze} ${$?`${$.replaceAll("\\","/")}`:"No File Changes"}`}else if(_==="exec_command"||_==="execcommand"||_==="run"){let S=j(G.args).command||null;Oe=`${S?"\u2714":"\u2718"} \x1B[95mExecuted\x1B[0m: ${S?S.slice(0,100)+(S.length>100?"...":""):"No Command"}`}else if(_==="file_map"||_==="filemap"){let S=j(G.args).path||"";Oe=`${S?"\u2714":"\u2718"} \x1B[95mIndexed\x1B[0m: ${S?`${S.replaceAll("\\","/")}`:"File Not Found"}`}else if(_==="await"){let{time:S}=j(G.args),$=parseFloat(S)||0;$<10&&($=10),$>180&&($=180),Oe=`\u2714 \x1B[95mAwaiting\x1B[0m \u2192 ${(ze=>{if(ze>=60){let Ct=Math.floor(ze/60),it=ze%60;return`${Ct}m${it>0?` ${it}s`:""}`}return`${ze}s`})($)}`}else{let S=ps[_]||G.toolName,$=eo(_,G.args);Oe=`\u2714 \x1B[95m${S}\x1B[0m${$?`: ${$}`:""}`}n.onVisualFeedback&&Oe&&n.onVisualFeedback(Oe),r&&r(`[Executing Tool] ${G.toolName}(${G.args})...`);try{let S=await Bo(G.toolName,G.args,{...n,mode:"Flux"});if(r&&r(`[Action Result]
933
934
  ${S}
934
- `),Be+=`[ACTION RESULT for ${H.toolName}]: ${S}
935
+ `),Be+=`[ACTION RESULT for ${G.toolName}]: ${S}
935
936
 
936
- `,await Lt("toolSuccess"),_==="patchfile"||_==="update_file"||_==="updatefile"||_==="patch_file"){if(S){let L=S.split(`
937
- `),ct=0,ze=0,Ct=!1;for(let it of L){if(it.includes("[DIFF_START]")){Ct=!0;continue}if(it.includes("[DIFF_END]")){Ct=!1;continue}Ct&&(/^\+\s*\d+/.test(it)?ct++:/^\-\s*\d+/.test(it)&&ze++)}(ct>0||ze>0)&&(await At("linesAdded",ct),await At("linesRemoved",ze))}}else if((_==="writefile"||_==="write_file")&&S){let L=S.match(/- Stats: \[(\d+) lines/),ct=L?parseInt(L[1]):0,ze=0;if(S.includes("Old File contents:")){let Ct=!1;for(let it of S.split(`
938
- `)){if(it.includes("Old File contents:")){Ct=!0;continue}Ct&&(it.startsWith("- Content Preview:")||it.trim()===""&&!/^\s*\d+\s*\|/.test(it)?Ct=!1:/^\s*\d+\s*\|/.test(it)&&ze++)}}(ct>0||ze>0)&&(await At("linesAdded",ct),await At("linesRemoved",ze))}}catch(S){let L=`ERROR: Execution failed for [${H.toolName}]: ${S.message}`;r&&r(`[Tool Error] ${L}
939
- `),Be+=`${L}
937
+ `,await Lt("toolSuccess"),_==="patchfile"||_==="update_file"||_==="updatefile"||_==="patch_file"){if(S){let $=S.split(`
938
+ `),ct=0,ze=0,Ct=!1;for(let it of $){if(it.includes("[DIFF_START]")){Ct=!0;continue}if(it.includes("[DIFF_END]")){Ct=!1;continue}Ct&&(/^\+\s*\d+/.test(it)?ct++:/^\-\s*\d+/.test(it)&&ze++)}(ct>0||ze>0)&&(await At("linesAdded",ct),await At("linesRemoved",ze))}}else if((_==="writefile"||_==="write_file")&&S){let $=S.match(/- Stats: \[(\d+) lines/),ct=$?parseInt($[1]):0,ze=0;if(S.includes("Old File contents:")){let Ct=!1;for(let it of S.split(`
939
+ `)){if(it.includes("Old File contents:")){Ct=!0;continue}Ct&&(it.startsWith("- Content Preview:")||it.trim()===""&&!/^\s*\d+\s*\|/.test(it)?Ct=!1:/^\s*\d+\s*\|/.test(it)&&ze++)}}(ct>0||ze>0)&&(await At("linesAdded",ct),await At("linesRemoved",ze))}}catch(S){let $=`ERROR: Execution failed for [${G.toolName}]: ${S.message}`;r&&r(`[Tool Error] ${$}
940
+ `),Be+=`${$}
940
941
 
941
- `,await Lt("toolFailure")}}let Pe="";if(n?.taskId&&typeof en<"u"){let H=en.find(_=>_.id===n.taskId);if(H&&H.pendingSteerMessages&&H.pendingSteerMessages.length>0){let _=[...H.pendingSteerMessages];H.pendingSteerMessages=[];for(let Qe of _)Pe+=`
942
+ `,await Lt("toolFailure")}}let Pe="";if(n?.taskId&&typeof en<"u"){let G=en.find(_=>_.id===n.taskId);if(G&&G.pendingSteerMessages&&G.pendingSteerMessages.length>0){let _=[...G.pendingSteerMessages];G.pendingSteerMessages=[];for(let Qe of _)Pe+=`
942
943
 
943
- [STEERING INSTRUCTION FROM MAIN AGENT]: ${Qe}`,r&&r(`[Subagent Steered] ${Qe}`)}}let Y=(Be.trim()+Pe).trim();G.push({role:"user",text:Y}),b++}return ht};export{mo as a,pi as b,Wc as c,Gc as d,dc as e,fc as f,go as g,uc as h,Rc as i,_c as j,cl as k,Md as l,dl as m,fl as n,gs as o,Kt as p,hi as q,sa as r,pl as s,Pd as t,Od as u,hs as v,Ld as w,ys as x,yl as y,eo as z,$d as A,yi as B,Nd as C,Dd as D,Fd as E,Bd as F};
944
+ [STEERING INSTRUCTION FROM MAIN AGENT]: ${Qe}`,r&&r(`[Subagent Steered] ${Qe}`)}}let V=(Be.trim()+Pe).trim();W.push({role:"user",text:V}),b++}return ht};export{mo as a,pi as b,Gc as c,Hc as d,fc as e,uc as f,go as g,gc as h,_c as i,vc as j,dl as k,Pd as l,fl as m,ul as n,ms as o,Bt as p,hi as q,sa as r,hl as s,Od as t,Ld as u,ys as v,$d as w,yi as x,xl as y,jn as z,Nd as A,xi as B,Dd as C,Fd as D,Bd as E,Ud as F};