fluxflow-cli 4.24.8 → 4.25.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 (27) hide show
  1. package/dist/chunks/{ai-GKU62P7B.js → ai-IHT7BYEA.js} +1 -1
  2. package/dist/chunks/{app-UBBTQ7FY.js → app-FPNTVYSV.js} +2 -2
  3. package/dist/chunks/chunk-A73HW6DI.js +5 -0
  4. package/dist/chunks/{chunk-7M3AFLUN.js → chunk-NQTRYK6U.js} +1 -1
  5. package/dist/chunks/chunk-NYIPDIEQ.js +31 -0
  6. package/dist/chunks/{chunk-DYIWPH2W.js → chunk-RTT7P5KS.js} +1 -1
  7. package/dist/chunks/{chunk-VB5NDACN.js → chunk-S5MJT3L5.js} +75 -76
  8. package/dist/chunks/{chunk-LQHSNXBM.js → chunk-U2NRX2PX.js} +4 -4
  9. package/dist/chunks/click-NULWZ3IK.js +2 -0
  10. package/dist/chunks/{computer_action-2XHXRO56.js → computer_action-OQ3CWQU3.js} +1 -1
  11. package/dist/chunks/{drag-UYQLP2NB.js → drag-RLRC6JFF.js} +1 -1
  12. package/dist/chunks/{exec_command-THB36X3Y.js → exec_command-J23EG77W.js} +1 -1
  13. package/dist/chunks/{export-DEFENSGY.js → export-GPCAD6JI.js} +1 -1
  14. package/dist/chunks/{invoke-X747MSTY.js → invoke-AYPOVSTU.js} +2 -2
  15. package/dist/chunks/{invokeSync-XXYD7O2F.js → invokeSync-XW4AQKZ3.js} +2 -2
  16. package/dist/chunks/{key_press-IN6BOWVJ.js → key_press-7F6CAPZD.js} +1 -1
  17. package/dist/chunks/{keyboard_typing-YEMPELE2.js → keyboard_typing-RPPKNVTA.js} +1 -1
  18. package/dist/chunks/screen_grid-3F55Z22R.js +1 -0
  19. package/dist/chunks/{scroll-C7SG5G2G.js → scroll-QVQD7I6A.js} +1 -1
  20. package/dist/chunks/ui_detector_onnx-YGGFMOK5.js +1 -0
  21. package/dist/cli.js +5 -5
  22. package/dist/package.json +4 -3
  23. package/package.json +4 -3
  24. package/dist/chunks/chunk-6AWSJNXE.js +0 -31
  25. package/dist/chunks/chunk-KNCL7AK2.js +0 -5
  26. package/dist/chunks/click-2HXMMZIS.js +0 -2
  27. package/dist/chunks/screen_grid-GBIGOR5Q.js +0 -1
@@ -1,4 +1,4 @@
1
- import{a as Vt}from"./chunk-56EJGQU3.js";import{a as lo}from"./chunk-7SFAWGE2.js";import{a as Ai,c as Ei}from"./chunk-LQHSNXBM.js";import{a as Cs,g as Ci}from"./chunk-VYTQ6J56.js";import{a as Ri}from"./chunk-RZTZPIC5.js";import{c as As,g as Ti,h as Si,i as _i,m as Es}from"./chunk-ZRP6USHC.js";import{a as Oo}from"./chunk-FQBBOFNP.js";import{a as ne}from"./chunk-Y5JU726N.js";import{b as Ss}from"./chunk-3CZWTXIR.js";import{d as Do,i as Rt,k as Bt,m as _s,n as ki}from"./chunk-4XXLWMY6.js";import{a as ao}from"./chunk-GRQ7JZZP.js";import{k as ft,l as Io,o as pe}from"./chunk-OSDQRSY6.js";import{c as Ct,d as Xn}from"./chunk-L3W2X74K.js";import{a as en,d as Cn,e as Ro,k as Wn,l as vo,m as ks,r as Ts,v as Mo,w as io,x as ro}from"./chunk-DSVLWYIT.js";import{GoogleGenAI as Kr,ThinkingLevel as Xe,HarmBlockThreshold as Mn,HarmCategory as In}from"@google/genai";var vi=(e=!0,t=!0)=>`
1
+ import{a as Vt}from"./chunk-56EJGQU3.js";import{a as lo}from"./chunk-7SFAWGE2.js";import{a as Ai,c as Ei}from"./chunk-U2NRX2PX.js";import{a as Cs,g as Ci}from"./chunk-VYTQ6J56.js";import{a as Ri}from"./chunk-RZTZPIC5.js";import{c as As,g as Ti,h as Si,i as _i,m as Es}from"./chunk-ZRP6USHC.js";import{a as Oo}from"./chunk-FQBBOFNP.js";import{a as ne}from"./chunk-Y5JU726N.js";import{b as Ss}from"./chunk-3CZWTXIR.js";import{d as Do,i as Rt,k as Bt,m as _s,n as ki}from"./chunk-4XXLWMY6.js";import{a as ao}from"./chunk-GRQ7JZZP.js";import{k as ft,l as Io,o as me}from"./chunk-OSDQRSY6.js";import{c as Ct,d as Xn}from"./chunk-L3W2X74K.js";import{a as en,d as Cn,e as Ro,k as Wn,l as vo,m as ks,r as Ts,v as Mo,w as io,x as ro}from"./chunk-DSVLWYIT.js";import{GoogleGenAI as Kr,ThinkingLevel as Xe,HarmBlockThreshold as Mn,HarmCategory as In}from"@google/genai";var vi=(e=!0,t=!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 --
@@ -35,7 +35,7 @@ During reasoning: prefer direct deduction; avoid unnecessary branching`,Minimal:
35
35
  Prefer simplest correct solution, verify from first principles
36
36
  During reasoning: prefer direct deduction; avoid unnecessary branching`,Off:`Effort: Lowest
37
37
  No thinking. Immediate response
38
- Verify imports, tool results & system stability`};import co from"fs";var yn=null,Rs=()=>{try{if(co.existsSync(Mo)){let e=co.readFileSync(Mo,"utf-8"),t=JSON.parse(e);if(t&&typeof t=="object")return yn=t,yn}}catch{}return yn=yn||{},yn},Mi=e=>{try{return co.existsSync(en)||co.mkdirSync(en,{recursive:!0}),co.writeFileSync(Mo,JSON.stringify(e,null,2),"utf-8"),yn=e,!0}catch{return!1}},He=(e,t,n)=>{if(!e||!t||!n)return null;let s=yn||Rs(),o=`${e}::${t}`,c=s[o];if(c&&typeof c=="object"){let f=n.toLowerCase();if(c[f]!==void 0&&c[f]!==null)return c[f];for(let[l,k]of Object.entries(c))if(l.toLowerCase()===f)return k}return null},ul=(e,t,n,s)=>{if(!e||!t||!n||!s)return{success:!1,reason:"Invalid arguments"};let o=yn||Rs(),c=`${e}::${t}`;return(!o[c]||typeof o[c]!="object")&&(o[c]={}),o[c][n.toLowerCase()]=s,{success:Mi(o)}},gl=(e,t,n)=>{if(!e||!t)return{success:!1,reason:"Invalid arguments"};let s=yn||Rs(),o=`${e}::${t}`;return s[o]&&(n?(delete s[o][n.toLowerCase()],Object.keys(s[o]).length===0&&delete s[o]):delete s[o],Mi(s)),{success:!0}};import tn from"fs";import cn from"path";import ma from"os";import ln from"fs";import Rn from"path";import Gi from"fs";import vs from"path";import{execSync as ji}from"child_process";import{fileURLToPath as ha}from"url";var Ii=`# FluxFlow CLI Startup & Flags Reference
38
+ Verify imports, tool results & system stability`};import co from"fs";var yn=null,Rs=()=>{try{if(co.existsSync(Mo)){let e=co.readFileSync(Mo,"utf-8"),t=JSON.parse(e);if(t&&typeof t=="object")return yn=t,yn}}catch{}return yn=yn||{},yn},Mi=e=>{try{return co.existsSync(en)||co.mkdirSync(en,{recursive:!0}),co.writeFileSync(Mo,JSON.stringify(e,null,2),"utf-8"),yn=e,!0}catch{return!1}},He=(e,t,n)=>{if(!e||!t||!n)return null;let s=yn||Rs(),o=`${e}::${t}`,c=s[o];if(c&&typeof c=="object"){let f=n.toLowerCase();if(c[f]!==void 0&&c[f]!==null)return c[f];for(let[l,k]of Object.entries(c))if(l.toLowerCase()===f)return k}return null},ul=(e,t,n,s)=>{if(!e||!t||!n||!s)return{success:!1,reason:"Invalid arguments"};let o=yn||Rs(),c=`${e}::${t}`;return(!o[c]||typeof o[c]!="object")&&(o[c]={}),o[c][n.toLowerCase()]=s,{success:Mi(o)}},gl=(e,t,n)=>{if(!e||!t)return{success:!1,reason:"Invalid arguments"};let s=yn||Rs(),o=`${e}::${t}`;return s[o]&&(n?(delete s[o][n.toLowerCase()],Object.keys(s[o]).length===0&&delete s[o]):delete s[o],Mi(s)),{success:!0}};import tn from"fs";import cn from"path";import pa from"os";import ln from"fs";import Rn from"path";import Gi from"fs";import vs from"path";import{execSync as ji}from"child_process";import{fileURLToPath as ha}from"url";var Ii=`# FluxFlow CLI Startup & Flags Reference
39
39
 
40
40
  Launch command syntax:
41
41
  fluxflow [options]
@@ -181,8 +181,7 @@ Open in chat via /settings
181
181
  ### 6. Miscellaneous
182
182
  * Sub-Agents \u2192 Enable sub-agent delegation
183
183
  * Sub-Agent Model \u2192 Dedicated model/provider for sub-agents
184
- * Dynamic Directory Awareness \u2192 Dynamic tracking of workspace directory tree
185
- * Directory Tree Design \u2192 Directory visual styling. Modern (Saves Tokens) | Classic (More Tokens, No extra benefit)
184
+ * Directory Tree Design \u2192 Directory visual styling. Modern (Saves Tokens) | Legacy (More Tokens, No extra benefit)
186
185
  * Compact Large Tool Results \u2192 Compress large tool outputs to save tokens (model might miss subtle indentation/syntax errors)
187
186
  * Context Length \u2192 Set usable context window size in FluxFlow. 16k, 32k, 64k, 128k, 256k, 512k, 1M. After Limit reached: Start new chat
188
187
  * Auto Truncate Results \u2192 Auto-truncate tool results after task finished to save token and improve caching
@@ -192,13 +191,13 @@ Open in chat via /settings
192
191
  * Disable Todo \u2192 Disables Todo/Goal tool for Agent. Doesnt necessarily affect modern models
193
192
 
194
193
  -- Recomended Settings Preset --
195
- - Best for Cost Saving: Subagents (off), dynamic directory awareness (off), directory tree design (modern), compact large results (on), auto exclue metadata (on), Image History (Low), Keep reasoning content (off), Emergency Recovery (off), Auto truncate results (on), Memory (off), No FluxFlow IDE Companion
194
+ - Best for Cost Saving: Subagents (off), directory tree design (modern), compact large results (on), auto exclue metadata (on), Image History (Low), Keep reasoning content (off), Emergency Recovery (off), Auto truncate results (on), Memory (off), No FluxFlow IDE Companion
196
195
 
197
- - Best for General Use: Subagents (on), dynamic directory awareness (off), compact large results (off), auto exclue metadata (off), Image History (Standard), Keep reasoning content (off), Emergency Recovery (off), Auto truncate results (on), Memory (off), FluxFlow IDE Companion
196
+ - Best for General Use: Subagents (on), compact large results (off), auto exclue metadata (off), Image History (Standard), Keep reasoning content (off), Emergency Recovery (off), Auto truncate results (on), Memory (off), FluxFlow IDE Companion
198
197
 
199
- - Best for Luxurious Experience: Subagents (on), dynamic directory awareness (on), compact large results (off), auto exclue metadata (off), Image History (Extended), Keep reasoning content (on), Emergency Recovery (on), Auto truncate results (off), Memory (on), Security Preset (Autonomous), FluxFlow IDE Companion
198
+ - Best for Luxurious Experience: Subagents (on), compact large results (off), auto exclue metadata (off), Image History (Extended), Keep reasoning content (on), Emergency Recovery (on), Auto truncate results (off), Memory (on), Security Preset (Autonomous), FluxFlow IDE Companion
200
199
 
201
- - Max Cache Hit: Subagents (off), dynamic directory awareness (off), compact large results (on), auto exclue metadata (on), Image History (Low), Keep reasoning content (off), Emergency Recovery (off), Auto truncate results (off), Memory (off), No FluxFlow IDE Companion
200
+ - Max Cache Hit: Subagents (off), compact large results (on), auto exclue metadata (on), Image History (Low), Keep reasoning content (off), Emergency Recovery (off), Auto truncate results (off), Memory (off), No FluxFlow IDE Companion
202
201
  `;var Pi=`# FluxFlow Tool Reference
203
202
 
204
203
  ## Protocol: [tool:ToolName(arg1="val")]
@@ -388,7 +387,7 @@ Route sub-agent workloads to faster/cheaper models independently of the main age
388
387
  ## Setup: 9Router
389
388
  1. Install NPM Package (9router)
390
389
  2. Set ENV ENABLE_9ROUTER=true
391
- * NINEROUTER_URL = https://.../v1/chat/completions Support external openai compatible endpoints too
390
+ * NINEROUTER_URL = https://.../v1/chat/completions Support external openai compatible endpoints too, for direct URL changes no need for 9router package. But 9router package gives better reliability and Anthropic stye endpoint support
392
391
  * NINEROUTER_KEY = If any needed
393
392
  `;var Hi=`# Fluxflow Instructions & Skills System
394
393
 
@@ -462,14 +461,14 @@ Public Docs: https://fluxflow-cli.onrender.com
462
461
  Default Context Length: 256k Tokens. Can be changed via ENV/In-app Settings \u2192 references/{SETTINGS,ENV}.md
463
462
 
464
463
  Docs missing required info? Say you are not sure enough to answer. Dont give wrong info`,"references/MODES.md":Ui,"references/PROVIDERS.md":Wi,"references/PLUGINS.md":Hi,"references/STARTUP.md":Ii,"references/ENV.md":Di,"references/COMMANDS.md":Oi,"references/SETTINGS.md":Li,"references/TOOLS.md":Pi,"references/ARCHITECTURE.md":$i,"references/SUB_AGENTS.md":Ni,"references/SECURITY.md":Fi,"references/IDE.md":Bi};var Ki=()=>{try{let e=Rn.join(en,"skills","fluxflow"),t=Rn.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===!0||!1){ln.existsSync(e)&&ln.rmSync(e,{recursive:!0,force:!0});return}let s=new Set(Object.keys(Ms).map(o=>Rn.normalize(o)));for(let[o,c]of Object.entries(Ms)){let f=Rn.join(e,o),l=Rn.dirname(f);ln.existsSync(l)||ln.mkdirSync(l,{recursive:!0});let k=c.trim()+`
465
- `,p=null;ln.existsSync(f)&&(p=ln.readFileSync(f,"utf8")),p!==k&&ln.writeFileSync(f,k,"utf8")}if(ln.existsSync(t)){let o=ln.readdirSync(t);for(let c of o){let f=Rn.normalize(Rn.join("references",c));if(!s.has(f)){let l=Rn.join(t,c);try{ln.rmSync(l,{recursive:!0,force:!0})}catch{}}}}}catch{}};var ho=(e,t)=>{try{if(!tn.existsSync(e))return null;let n=Array.isArray(t)?t.map(o=>o.toLowerCase()):[t.toLowerCase()],s=tn.readdirSync(e);for(let o of n){let c=s.find(f=>f.toLowerCase()===o);if(c){let f=cn.join(e,c);if(tn.statSync(f).isFile())return f}}}catch{}return null},$s=(e,t)=>{let n=ho(e,t);if(n)try{return tn.readFileSync(n,"utf8")}catch{}return""},Vi=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"]),Ns=(e=process.cwd(),t=0,n=8)=>{let s=[];if(t>n)return s;try{if(!tn.existsSync(e))return s;let o=tn.readdirSync(e,{withFileTypes:!0});for(let c of o){let f=c.name,l=cn.join(e,f);if(c.isDirectory())!Vi.has(f)&&!Vi.has(f.toLowerCase())&&s.push(...Ns(l,t+1,n));else if(c.isFile()){let k=f.toLowerCase();(k==="agents.md"||k==="agent.md")&&s.push(l)}}}catch{}return s},Yi=(e,t=2)=>{if(!e)return"";let n=" ".repeat(t);return e.split(/\r?\n/).map(s=>n+s).join(`
466
- `)},Qi=()=>ho(en,["agents.md","agent.md"]),Zi=()=>ho(process.cwd(),["agents.md","agent.md"]),er=()=>ho(en,["fluxflow.md"]),tr=()=>ho(process.cwd(),["fluxflow.md"]),$o=Qi(),Ls=Zi(),vn=Ns(),No=er(),Fo=tr(),qi=null,Ps="",nr=!1,pa=e=>{if(!e||!/^<<<[\s\S]*?Identity:/m.test(e))return e;let t=e.match(/^<<<\s*\r?\n([\s\S]*?)\r?\n>>>\s*(?:\r?\n)?([\s\S]*)$/);if(!t)return e;let n=t[1],s=t[2],o=n.match(/^Identity:\s*([\s\S]*?)(?=\r?\n\s*(?:<><|>>>)|$)/m);return o&&(Ps=o[1].trim(),process.env.NO_INS=!0),/<><\s*NO_INS/.test(n)&&(nr=!0),s.trim()},ya=()=>($o=Qi(),$o?$s(en,["agents.md","agent.md"]).trim():""),xa=()=>{if(vn=Ns(),Ls=Zi(),!vn||vn.length===0)return"";let e=process.cwd(),t=[...vn].sort((s,o)=>{let c=cn.relative(e,s).replace(/\\/g,"/"),f=cn.relative(e,o).replace(/\\/g,"/"),l=!c.includes("/"),k=!f.includes("/");return l&&!k?-1:!l&&k?1:c.localeCompare(f)}),n=[];for(let s of t)try{let o=tn.readFileSync(s,"utf8").trim();if(!o)continue;let c=cn.relative(e,s).replace(/\\/g,"/");if(!c.includes("/"))n.push(Yi(o,2));else{let l=cn.dirname(c)+"/:";n.push(`${l}
464
+ `,m=null;ln.existsSync(f)&&(m=ln.readFileSync(f,"utf8")),m!==k&&ln.writeFileSync(f,k,"utf8")}if(ln.existsSync(t)){let o=ln.readdirSync(t);for(let c of o){let f=Rn.normalize(Rn.join("references",c));if(!s.has(f)){let l=Rn.join(t,c);try{ln.rmSync(l,{recursive:!0,force:!0})}catch{}}}}}catch{}};var ho=(e,t)=>{try{if(!tn.existsSync(e))return null;let n=Array.isArray(t)?t.map(o=>o.toLowerCase()):[t.toLowerCase()],s=tn.readdirSync(e);for(let o of n){let c=s.find(f=>f.toLowerCase()===o);if(c){let f=cn.join(e,c);if(tn.statSync(f).isFile())return f}}}catch{}return null},$s=(e,t)=>{let n=ho(e,t);if(n)try{return tn.readFileSync(n,"utf8")}catch{}return""},Vi=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"]),Ns=(e=process.cwd(),t=0,n=8)=>{let s=[];if(t>n)return s;try{if(!tn.existsSync(e))return s;let o=tn.readdirSync(e,{withFileTypes:!0});for(let c of o){let f=c.name,l=cn.join(e,f);if(c.isDirectory())!Vi.has(f)&&!Vi.has(f.toLowerCase())&&s.push(...Ns(l,t+1,n));else if(c.isFile()){let k=f.toLowerCase();(k==="agents.md"||k==="agent.md")&&s.push(l)}}}catch{}return s},Yi=(e,t=2)=>{if(!e)return"";let n=" ".repeat(t);return e.split(/\r?\n/).map(s=>n+s).join(`
465
+ `)},Qi=()=>ho(en,["agents.md","agent.md"]),Zi=()=>ho(process.cwd(),["agents.md","agent.md"]),er=()=>ho(en,["fluxflow.md"]),tr=()=>ho(process.cwd(),["fluxflow.md"]),$o=Qi(),Ls=Zi(),vn=Ns(),No=er(),Fo=tr(),qi=null,Ps="",nr=!1,ma=e=>{if(!e||!/^<<<[\s\S]*?Identity:/m.test(e))return e;let t=e.match(/^<<<\s*\r?\n([\s\S]*?)\r?\n>>>\s*(?:\r?\n)?([\s\S]*)$/);if(!t)return e;let n=t[1],s=t[2],o=n.match(/^Identity:\s*([\s\S]*?)(?=\r?\n\s*(?:<><|>>>)|$)/m);return o&&(Ps=o[1].trim(),process.env.NO_INS=!0),/<><\s*NO_INS/.test(n)&&(nr=!0),s.trim()},ya=()=>($o=Qi(),$o?$s(en,["agents.md","agent.md"]).trim():""),xa=()=>{if(vn=Ns(),Ls=Zi(),!vn||vn.length===0)return"";let e=process.cwd(),t=[...vn].sort((s,o)=>{let c=cn.relative(e,s).replace(/\\/g,"/"),f=cn.relative(e,o).replace(/\\/g,"/"),l=!c.includes("/"),k=!f.includes("/");return l&&!k?-1:!l&&k?1:c.localeCompare(f)}),n=[];for(let s of t)try{let o=tn.readFileSync(s,"utf8").trim();if(!o)continue;let c=cn.relative(e,s).replace(/\\/g,"/");if(!c.includes("/"))n.push(Yi(o,2));else{let l=cn.dirname(c)+"/:";n.push(`${l}
467
466
  ${Yi(o,2)}`)}}catch{}return n.join(`
468
467
 
469
- `).trim()},Fs=()=>{No=er();let e=No?$s(en,["fluxflow.md"]).trim():"";return pa(e)},Bs=()=>(Fo=tr(),Fo?$s(process.cwd(),["fluxflow.md"]).trim():""),Us=ya(),Bo=xa(),uo=Fs(),go=Bs(),zi=(e,t="",n="")=>{if(!e)return"";let s=n.toLowerCase().trim(),o=t.toLowerCase().trim(),c=cn.posix.basename(o),f=s&&o?`${s}::${o}`:"",l=s&&c?`${s}::${c}`:"",k=g=>!g||!o?!1:g===o||g===c||g===f||g===l,p=[];return e.replace(/<start_provider_([^>\r\n]+)>([\s\S]*?)<end_provider_([^>\r\n]+)>/gi,(g,T,m,i)=>{if(s&&T.trim().toLowerCase()===i.trim().toLowerCase()&&T.trim().toLowerCase()===s){let w=m.replace(/<start_model_([^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n]+)>/gi,(I,h,A,$)=>{if(h.trim().toLowerCase()===$.trim().toLowerCase()){let C=h.trim().toLowerCase();if(k(C)){let x=A.trim();x&&p.push(x)}}return""}).trim();w&&p.push(w)}return""}),e.replace(/<start_model_([^>\r\n]+::[^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n]+::[^>\r\n]+)>/gi,(g,T,m,i)=>{if(T.trim().toLowerCase()===i.trim().toLowerCase()){let u=T.trim().toLowerCase();if(f&&(u===f||l&&u===l)){let w=m.trim();w&&p.push(w)}}return""}),e.replace(/<start_model_([^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n]+)>/gi,(g,T,m,i)=>{if(T.includes("::"))return"";if(T.trim().toLowerCase()===i.trim().toLowerCase()){let u=T.trim().toLowerCase();if(o&&(u===o||u===c)){let w=m.trim();w&&p.push(w)}}return""}),p.join(`
468
+ `).trim()},Fs=()=>{No=er();let e=No?$s(en,["fluxflow.md"]).trim():"";return ma(e)},Bs=()=>(Fo=tr(),Fo?$s(process.cwd(),["fluxflow.md"]).trim():""),Us=ya(),Bo=xa(),uo=Fs(),go=Bs(),zi=(e,t="",n="")=>{if(!e)return"";let s=n.toLowerCase().trim(),o=t.toLowerCase().trim(),c=cn.posix.basename(o),f=s&&o?`${s}::${o}`:"",l=s&&c?`${s}::${c}`:"",k=g=>!g||!o?!1:g===o||g===c||g===f||g===l,m=[];return e.replace(/<start_provider_([^>\r\n]+)>([\s\S]*?)<end_provider_([^>\r\n]+)>/gi,(g,T,p,i)=>{if(s&&T.trim().toLowerCase()===i.trim().toLowerCase()&&T.trim().toLowerCase()===s){let w=p.replace(/<start_model_([^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n]+)>/gi,(I,h,A,$)=>{if(h.trim().toLowerCase()===$.trim().toLowerCase()){let C=h.trim().toLowerCase();if(k(C)){let x=A.trim();x&&m.push(x)}}return""}).trim();w&&m.push(w)}return""}),e.replace(/<start_model_([^>\r\n]+::[^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n]+::[^>\r\n]+)>/gi,(g,T,p,i)=>{if(T.trim().toLowerCase()===i.trim().toLowerCase()){let u=T.trim().toLowerCase();if(f&&(u===f||l&&u===l)){let w=p.trim();w&&m.push(w)}}return""}),e.replace(/<start_model_([^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n]+)>/gi,(g,T,p,i)=>{if(T.includes("::"))return"";if(T.trim().toLowerCase()===i.trim().toLowerCase()){let u=T.trim().toLowerCase();if(o&&(u===o||u===c)){let w=p.trim();w&&m.push(w)}}return""}),m.join(`
470
469
 
471
470
  `).trim()},ba=(e="",t="")=>{let n=`${e||""}::${t||""}`.toLowerCase().trim();qi!==n&&(qi=n,uo=Fs(),go=Bs())};Ki();var wa=e=>{if(!e)return null;let t=e.match(/^\s*---\r?\n([\s\S]*?)\r?\n---(?:\r?\n)?([\s\S]*)$/);if(!t)return null;let n=t[1];if((t[2]||"").trim().length===0)return null;let o="",c="",f=n.match(/^name:\s*(.+)$/m),l=n.match(/^description:\s*(.+)$/m);return f&&(o=f[1].trim().replace(/^["']|["']$/g,"")),l&&(c=l[1].trim().replace(/^["']|["']$/g,"")),o&&c?{name:o,description:c}:null},ka=e=>{let t=[];if(!e||!tn.existsSync(e))return t;let n=(s,o=0)=>{if(!(o>5))try{let c=tn.readdirSync(s,{withFileTypes:!0});for(let f of c){let l=cn.join(s,f.name),k=f.name.toLowerCase();f.isFile()?k==="skill.md"&&t.push(l):f.isDirectory()&&(o===0?(k==="skills"||k===".skills"||k==="skill"||k===".skill")&&n(l,o+1):n(l,o+1))}}catch{}};return n(e,0),t},or=e=>{let t=ka(e),n=[];for(let s of t)try{let o=tn.readFileSync(s,"utf8"),c=wa(o);c&&n.push({...c,filePath:s})}catch{}return n},sr=e=>!e||e.length===0?"":e.map(t=>`- ${t.name}: ${t.description}`).join(`
472
- `),ir=or(en),rr=or(process.cwd()),Is=sr(ir),Ds=sr(rr),ar=e=>{if(!e)return!1;let t=(e.filePath||"").replace(/\\/g,"/").toLowerCase();return t.includes("/skills/fluxflow/skill.md")||t.includes("/skills/about-fluxflow/skill.md")||e.name?.toLowerCase()==="fluxflow"},lr=()=>(ir||[]).filter(e=>!ar(e)),cr=()=>(rr||[]).filter(e=>!ar(e)),ac=(Us?1:0)+(vn?.length||(Bo?1:0))+(uo?1:0)+(go?1:0)+lr().length+cr().length,Os=(e,t="Project")=>{if(!e)return"";let n=e.replace(/\\/g,"/");if(t==="Global"){let o=ma.homedir().replace(/\\/g,"/");return n.toLowerCase().startsWith(o.toLowerCase())?"~"+n.slice(o.length):n}let s=cn.relative(process.cwd(),e).replace(/\\/g,"/");return s.startsWith(".")?s:`./${s}`},lc=()=>{uo=Fs(),go=Bs();let e=[];$o&&Us.length>0&&e.push({scope:"Global",path:$o}),vn&&vn.length>0&&Bo.length>0?vn.forEach(c=>{e.push({scope:"Project",path:c})}):Ls&&Bo.length>0&&e.push({scope:"Project",path:Ls}),No&&uo.length>0&&e.push({scope:"Global",path:No}),Fo&&go.length>0&&e.push({scope:"Project",path:Fo});let t=lr(),n=cr(),s=e.length+t.length+n.length;if(s===0)return`\u2726 Loaded Files & Instructions
471
+ `),ir=or(en),rr=or(process.cwd()),Is=sr(ir),Ds=sr(rr),ar=e=>{if(!e)return!1;let t=(e.filePath||"").replace(/\\/g,"/").toLowerCase();return t.includes("/skills/fluxflow/skill.md")||t.includes("/skills/about-fluxflow/skill.md")||e.name?.toLowerCase()==="fluxflow"},lr=()=>(ir||[]).filter(e=>!ar(e)),cr=()=>(rr||[]).filter(e=>!ar(e)),ac=(Us?1:0)+(vn?.length||(Bo?1:0))+(uo?1:0)+(go?1:0)+lr().length+cr().length,Os=(e,t="Project")=>{if(!e)return"";let n=e.replace(/\\/g,"/");if(t==="Global"){let o=pa.homedir().replace(/\\/g,"/");return n.toLowerCase().startsWith(o.toLowerCase())?"~"+n.slice(o.length):n}let s=cn.relative(process.cwd(),e).replace(/\\/g,"/");return s.startsWith(".")?s:`./${s}`},lc=()=>{uo=Fs(),go=Bs();let e=[];$o&&Us.length>0&&e.push({scope:"Global",path:$o}),vn&&vn.length>0&&Bo.length>0?vn.forEach(c=>{e.push({scope:"Project",path:c})}):Ls&&Bo.length>0&&e.push({scope:"Project",path:Ls}),No&&uo.length>0&&e.push({scope:"Global",path:No}),Fo&&go.length>0&&e.push({scope:"Project",path:Fo});let t=lr(),n=cr(),s=e.length+t.length+n.length;if(s===0)return`\u2726 Loaded Files & Instructions
473
472
  \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m No instruction or skill files are currently loaded.
474
473
  \u2800`;let o=[];return o.push(`\u2726 Loaded Files & Instructions (${s} ${s===1?"file":"files"} active)`),e.length>0&&(o.push(`
475
474
  \x1B[1mInstructions:\x1B[22m`),e.forEach(c=>{o.push(` \u2022 [${c.scope}] ${Os(c.path,c.scope)}`)})),(t?.length>0||n?.length>0)&&(o.push(`
@@ -478,7 +477,7 @@ ${Yi(o,2)}`)}}catch{}return n.join(`
478
477
  `):fo=""}catch(n){fo="",tn.appendFileSync(`${Cn}/memory/error.txt`,`${n.message}
479
478
  -------------------------------------------------
480
479
 
481
- `)}}return fo};var fr=(e,t,n,s,o=!0,c=!1,f="Google",l=!1,k,p,g=!1,T="")=>{let m=!1;process.env.forcedReasoning&&(m=!0);let i="";if(!k&&f==="Google"){let Q=t;t==="Fast"&&(Q="Off"),t==="Low"&&(Q="Minimal"),t==="Standard"&&(Q="Medium"),(t==="xHigh"||t==="Max")&&(Q="xHigh"),i=Lo[Q]||Lo.Medium}if(k||f!=="Google"){let Q={Fast:"Lowest",Low:"Low",Medium:"Medium",Standard:"Medium",High:"High",xHigh:"High",Max:"High"};i=Lo.xHigh,i=i.replace("Effort: High",`Effort: ${Q[t]}`),t==="Fast"?i=`Effort: Lowest
480
+ `)}}return fo};var fr=(e,t,n,s,o=!0,c=!1,f="Google",l=!1,k,m,g=!1,T="")=>{let p=!1;process.env.forcedReasoning&&(p=!0);let i="";if(!k&&f==="Google"){let Q=t;t==="Fast"&&(Q="Off"),t==="Low"&&(Q="Minimal"),t==="Standard"&&(Q="Medium"),(t==="xHigh"||t==="Max")&&(Q="xHigh"),i=Lo[Q]||Lo.Medium}if(k||f!=="Google"){let Q={Fast:"Lowest",Low:"Low",Medium:"Medium",Standard:"Medium",High:"High",xHigh:"High",Max:"High"};i=Lo.xHigh,i=i.replace("Effort: High",`Effort: ${Q[t]}`),t==="Fast"?i=`Effort: Lowest
482
481
  No thinking. Immediate response
483
482
  Verify imports, tool results & system stability; avoid syntax errors`:t==="Low"&&(i=`Effort: Low
484
483
  Quick, focused thinking, required tools/files/actions
@@ -489,7 +488,7 @@ Verify imports, tool results & system stability; avoid syntax errors`)}let u=e.i
489
488
  ${u.length?"":`
490
489
  `}`:"",I=e.name&&e.name?.length>0?`User Name: ${e.name}
491
490
  ${w.length||u.length?"":`
492
- `}`:"",h=process.cwd(),A=Ta(p,o),$=A?.length>0?`--- Saved Memories ---
491
+ `}`:"",h=process.cwd(),A=Ta(m,o),$=A?.length>0?`--- Saved Memories ---
493
492
  ${A}
494
493
 
495
494
  `:"";ba(f,T);let C=zi(uo,T,f).trim(),_=[Us,C].filter(Q=>Q&&Q.length>0).join(`
@@ -513,7 +512,7 @@ ${nr?"":`${n==="Flux"?"Run Automated Tests":n==="Flow"?"Concise, Humorous, Sarca
513
512
  - Date: ${O}`:""}
514
513
 
515
514
  -- REASONING GUIDANCE --
516
- ${f==="Mistral"||f==="Google"&&!k?`${i.trimEnd()}${m||t!=="Fast"&&(f==="Mistral"&&t==="Low"&&!k||t!=="High"&&!k)?`
515
+ ${f==="Mistral"||f==="Google"&&!k?`${i.trimEnd()}${p||t!=="Fast"&&(f==="Mistral"&&t==="Low"&&!k||t!=="High"&&!k)?`
517
516
  Critical Thinking Policy
518
517
 
519
518
  Use <think>...</think> for reasoning before responding any queries
@@ -555,43 +554,43 @@ ${vi(t,n)}
555
554
  === END SYSTEM PROMPT ===${e?`
556
555
 
557
556
  -- current saved user memories --
558
- ${e}`:""}`.trim();var gr=()=>import("./web_search-2PFIJKIL.js").then(e=>e.web_search),hr=()=>import("./web_scrape-BHSQTMX4.js").then(e=>e.web_scrape),mr=()=>import("./memory-M7ASUB6J.js").then(e=>e.memory),pr=()=>import("./chat-MELTWDZ3.js").then(e=>e.chat),yr=()=>import("./view_file-2THVIMD6.js").then(e=>e.view_file),xr=()=>import("./write_file-7X2GQFWK.js").then(e=>e.write_file),br=()=>import("./update_file-PXZHSSGS.js").then(e=>e.update_file),wr=()=>import("./exec_command-THB36X3Y.js").then(e=>e.exec_command),kr=()=>import("./read_folder-EI2CNHNS.js").then(e=>e.read_folder),Ws=()=>import("./ask_user-K2DLZF6H.js").then(e=>e.ask_user),Tr=()=>import("./write_pdf-N2Q4Z3YP.js").then(e=>e.write_pdf),Sr=()=>import("./write_docx-4Y43QJUV.js").then(e=>e.write_docx),Uo=()=>import("./search_keyword-CSRQFPHQ.js").then(e=>e.search_keyword),_r=()=>import("./generate_image-4LIDEIYO.js").then(e=>e.generate_image),Wo=()=>import("./saveSummary-UGNDVNI5.js").then(e=>e.saveSummary),mo=()=>import("./addMemScore-BCPTSMKD.js").then(e=>e.addMemScore),Ar=()=>import("./file_map-KS6Y7BP3.js").then(e=>e.file_map),Ho=()=>import("./todo-GFMPH2JV.js").then(e=>e.todo),Er=()=>import("./invokeSync-XXYD7O2F.js").then(e=>e.invokeSync),Sa=()=>import("./invoke-X747MSTY.js").then(e=>e.invoke),Cr=()=>import("./getProgress-A2TW34Q7.js").then(e=>e.getProgress),_a=()=>import("./cancel-F3ZOEBKW.js").then(e=>e.cancel),Rr=()=>import("./emergency_rollback-6X27LZE4.js").then(e=>e.emergency_rollback),po=()=>import("./awaitSubagent-JKQ2EHVY.js").then(e=>e.awaitSubagent),yo=()=>import("./answerSubagent-BPNNJXPC.js").then(e=>e.answerSubagent),Go=()=>import("./steerSubagent-UETXH2CB.js").then(e=>e.steerSubagent),jo=()=>import("./computer_action-2XHXRO56.js").then(e=>e.computer_action),vr=()=>import("./click-2HXMMZIS.js").then(e=>e.click),Mr=()=>import("./drag-UYQLP2NB.js").then(e=>e.drag),Ir=()=>import("./scroll-C7SG5G2G.js").then(e=>e.scroll),Hs=()=>import("./keyboard_typing-YEMPELE2.js").then(e=>e.keyboard_typing),Gs=()=>import("./key_press-IN6BOWVJ.js").then(e=>e.key_press),js=()=>import("./recapture_screen-PPT2E3CK.js").then(e=>e.recapture_screen),Ko=()=>import("./find_file-A6NYLQJS.js").then(e=>e.find_file),Aa={web_search:gr,web_scrape:hr,memory:mr,chat:pr,view_file:yr,write_file:xr,update_file:br,exec_command:wr,read_folder:kr,write_pdf:Tr,write_docx:Sr,search_keyword:Uo,generate_image:_r,saveSummary:Wo,addMemScore:mo,file_map:Ar,todo:Ho,Todo:Ho,goal:Ho,Goal:Ho,invokeSync:Er,invoke:Sa,getProgress:Cr,cancel:_a,awaitSubagent:po,answerSubagent:yo,steerSubagent:Go,computer_action:jo,computer_use:jo,ComputerAction:jo,ComputerUse:jo,click:vr,Click:vr,drag:Mr,Drag:Mr,scroll:Ir,Scroll:Ir,keyboard_typing:Hs,KeyboardTyping:Hs,keyboardtyping:Hs,key_press:Gs,KeyPress:Gs,keypress:Gs,recapture_screen:js,RecaptureScreen:js,recapturescreen:js,invoke_sync:Er,get_progress:Cr,await_subagent:po,answer_subagent:yo,steer_subagent:Go,steer:Go,Steer:Go,ask:Ws,Ask:Ws,AskUser:Ws,WebSearch:gr,WebScrape:hr,ReadFile:yr,ReadFolder:kr,WriteFile:xr,PatchFile:br,WritePDF:Tr,WriteDoc:Sr,Run:wr,SearchKeyword:Uo,CodeSearch:Uo,code_search:Uo,Memory:mr,Chat:pr,GenerateImage:_r,saveSumary:Wo,SaveSummary:Wo,SaveSumary:Wo,add_mem_score:mo,AddMemScore:mo,addMemoryScore:mo,AddMemoryScore:mo,FileMap:Ar,answer:yo,Answer:yo,AnswerSubagent:yo,await:po,Await:po,AwaitSubagent:po,EmergencyRollback:Rr,emergency_rollback:Rr,find_file:Ko,findFile:Ko,FindFile:Ko,findfile:Ko},xo=async(e,t,n={})=>{let s=n.mode?n.mode.toLowerCase():"flux",o=e.toLowerCase(),f=["memory","chat","savesummary","addmemscore","add_mem_score","ask","web_search","web_scrape","await"].some(g=>o.includes(g))||o==="ask",k=["click","drag","scroll","keyboardtyping","keyboard_typing","keypress","key_press","recapturescreen","recapture_screen","computer"].some(g=>o.includes(g));if(!f){if(s==="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(s==="icu"){if(!k)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 ${n.mode||"Flux"} mode. Tell user to switch (\`/mode flow\`) for document generation.`}let p=Aa[e];if(!p){let g=["ReadFile","ReadFolder","FindFile","PatchFile","WriteFile","CodeSearch","Run","Goal","AskUser","WebSearch","WebScrape","WritePDF","WriteDoc","Click","Drag","Scroll","KeyboardTyping","KeyPress","RecaptureScreen","Invoke","InvokeSync","Await","GetProgress","Steer","Cancel","EmergencyRollback","Chat","Memory"],T={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"},m=o.replace(/[^a-z0-9]/g,""),i=T[m]||null;if(!i){let w=0,I=A=>{let $=new Set;for(let C=0;C<A.length-1;C++)$.add(A.slice(C,C+2));return $},h=I(m);for(let A of g){let $=A.toLowerCase().replace(/[^a-z0-9]/g,"");if(m===$){i=A;break}let C=0;($.includes(m)||m.includes($))&&(C+=.6);let x=I($),_=0;for(let y of h)x.has(y)&&_++;let M=2*_/(h.size+x.size||1);C=Math.max(C,M),C>w&&C>=.35&&(w=C,i=A)}}let u=i?` Do you mean '${i}'?`:"";return`ERROR: Action [${e}] not found in registry.${u}`}try{return await(await p())(t,n)}catch(g){let T=g instanceof Error?g.message:String(g);return`ERROR: Execution failed for [${e}]: ${T}`}};import ie from"path";import Ue from"fs";import Ea from"gradient-string";var Ks=["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 Dr=[{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"]}],bo={Dark:{id:"Dark",name:"Dark (Default)",text:"white",textMuted:"gray",textDim:"grey",textInverted:"black",textExclusive:"#B5B8D9",textMutedExclusive:"#D4DEE7",border:"white",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:"#1e1e1e",highlightBg:"#2a2a2a",activeBg:"#3a3a3a",inputBg:"#555555",inputBorder:"#555555",inputText:"white",inputPlaceholder:"#cccccc",inputPrompt:"white",codeBg:"#1a1a1a",codeBorder:"#444444",userMsgBg:"#444444",userMsgBorder:"#444444",userMsgText:"white",diffRemovalBg:"#250808",diffAdditionBg:"#072410",diffRemovalText:"#885555",diffAdditionText:"#558866",diffRemovalHighlightColor:"#ff3333",diffRemovalHighlightBg:"#5a1818",diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:"#185a25",diffRemovalNum:"#d96868",diffAdditionNum:"#68d98c",diffRemovalPrefix:"#ff4d4d",diffAdditionPrefix:"#4dff88",primary:"white",secondary:"cyan",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"white",statusOff:"gray",logoTextAnsi:"\x1B[1;37m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#0077ff","#ff00ff"]},Light:{id:"Light",name:"Light",text:"black",textMuted:"gray",textDim:"grey",textInverted:"white",border:"black",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:"#e5e5e5",highlightBg:"#d4d4d4",activeBg:"#c0c0c0",inputBg:"#d0d0d0",inputBorder:"#d0d0d0",inputText:"black",inputPlaceholder:"#555555",inputPrompt:"black",codeBg:"#e8e8e8",codeBorder:"#b0b0b0",userMsgBg:"#d0d0d0",userMsgBorder:"#d0d0d0",userMsgText:"black",diffRemovalBg:"#fce8e8",diffAdditionBg:"#e6f9e6",diffRemovalText:"#661111",diffAdditionText:"#115511",diffRemovalHighlightColor:"#440000",diffRemovalHighlightBg:"#f8b4b4",diffAdditionHighlightColor:"#003300",diffAdditionHighlightBg:"#a6ebad",diffRemovalNum:"#c02020",diffAdditionNum:"#188028",diffRemovalPrefix:"#d01010",diffAdditionPrefix:"#109020",primary:"black",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"black",statusOff:"gray",logoTextAnsi:"\x1B[1;30m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#0077ff","#ff00ff"]},"GitHub Dark":{id:"GitHub Dark",name:"GitHub Dark",text:"#c9d1d9",textMuted:"#8b949e",textDim:"#6e7681",textInverted:"#0d1117",border:"#30363d",borderMuted:"#30363d",borderDim:"#21262d",bg:void 0,cardBg:"#161b22",highlightBg:"#21262d",activeBg:"#30363d",inputBg:"#21262d",inputBorder:"#21262d",inputText:"#c9d1d9",inputPlaceholder:"#8b949e",inputPrompt:"#58a6ff",codeBg:"#0d1117",codeBorder:"#30363d",userMsgBg:"#21262d",userMsgBorder:"#21262d",userMsgText:"#c9d1d9",diffRemovalBg:"#3c1e1e",diffAdditionBg:"#11381e",diffRemovalText:"#f85149",diffAdditionText:"#3fb950",diffRemovalHighlightColor:"#ff7b72",diffRemovalHighlightBg:"#701c1c",diffAdditionHighlightColor:"#56d364",diffAdditionHighlightBg:"#116329",diffRemovalNum:"#f85149",diffAdditionNum:"#3fb950",diffRemovalPrefix:"#f85149",diffAdditionPrefix:"#3fb950",primary:"#c9d1d9",secondary:"#58a6ff",accent:"#bc8cff",success:"#3fb950",warning:"#d29922",danger:"#f85149",info:"#58a6ff",statusOn:"#58a6ff",statusOff:"#8b949e",logoTextAnsi:"\x1B[1;36m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#2ea043","#56d364"]},"GitHub Light":{id:"GitHub Light",name:"GitHub Light",text:"#24292f",textMuted:"#57606a",textDim:"#6e7781",textInverted:"#ffffff",border:"#d0d7de",borderMuted:"#d0d7de",borderDim:"#e1e4e8",bg:void 0,cardBg:"#f6f8fa",highlightBg:"#eaeef2",activeBg:"#d0d7de",inputBg:"#eaeef2",inputBorder:"#eaeef2",inputText:"#24292f",inputPlaceholder:"#57606a",inputPrompt:"#0969da",codeBg:"#ffffff",codeBorder:"#d0d7de",userMsgBg:"#eaeef2",userMsgBorder:"#eaeef2",userMsgText:"#24292f",diffRemovalBg:"#ffebe9",diffAdditionBg:"#e6ffec",diffRemovalText:"#cf222e",diffAdditionText:"#1a7f37",diffRemovalHighlightColor:"#82071e",diffRemovalHighlightBg:"#ffc1c0",diffAdditionHighlightColor:"#116329",diffAdditionHighlightBg:"#acf2bd",diffRemovalNum:"#cf222e",diffAdditionNum:"#1a7f37",diffRemovalPrefix:"#cf222e",diffAdditionPrefix:"#1a7f37",primary:"#24292f",secondary:"#0969da",accent:"#8250df",success:"#1a7f37",warning:"#9a6700",danger:"#cf222e",info:"#0969da",statusOn:"#0969da",statusOff:"#57606a",logoTextAnsi:"\x1B[1;34m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#1a7f37","#2da44e"]},"Transparent Dark":{id:"Transparent Dark",name:"Transparent Dark",text:"white",textMuted:"gray",textDim:"grey",textInverted:"black",border:"gray",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:void 0,highlightBg:"#2a2a2a",activeBg:"#3a3a3a",inputBg:"#555555",inputBorder:"#555555",inputText:"white",inputPlaceholder:"#cccccc",inputPrompt:"white",codeBg:void 0,codeBorder:"gray",userMsgBg:"#555555",userMsgBorder:"#555555",userMsgText:"white",diffRemovalBg:void 0,diffAdditionBg:void 0,diffRemovalText:"#ff6666",diffAdditionText:"#66ff66",diffRemovalHighlightColor:"#ff3333",diffRemovalHighlightBg:void 0,diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:void 0,diffRemovalNum:"#ff6666",diffAdditionNum:"#66ff66",diffRemovalPrefix:"#ff4d4d",diffAdditionPrefix:"#4dff88",primary:"white",secondary:"cyan",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"white",statusOff:"gray",logoTextAnsi:"\x1B[1;37m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#0077ff","#ff00ff"]},"Transparent Light":{id:"Transparent Light",name:"Transparent Light",text:"black",textMuted:"gray",textDim:"grey",textInverted:"white",border:"gray",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:void 0,highlightBg:"#d4d4d4",activeBg:"#c0c0c0",inputBg:"#d0d0d0",inputBorder:"#d0d0d0",inputText:"black",inputPlaceholder:"#555555",inputPrompt:"black",codeBg:void 0,codeBorder:"gray",userMsgBg:"#d0d0d0",userMsgBorder:"#d0d0d0",userMsgText:"black",diffRemovalBg:void 0,diffAdditionBg:void 0,diffRemovalText:"#c02020",diffAdditionText:"#188028",diffRemovalHighlightColor:"#800000",diffRemovalHighlightBg:void 0,diffAdditionHighlightColor:"#004000",diffAdditionHighlightBg:void 0,diffRemovalNum:"#c02020",diffAdditionNum:"#188028",diffRemovalPrefix:"#d01010",diffAdditionPrefix:"#109020",primary:"black",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"black",statusOff:"gray",logoTextAnsi:"\x1B[1;30m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#0077ff","#ff00ff"]},"Synthwave 84":{id:"Synthwave 84",name:"Synthwave 84",text:"#fdfdfd",textMuted:"#a08eb7",textDim:"#705c8a",textInverted:"#1a1025",textExclusive:"#e3dcf0",textMutedExclusive:"#b9abc9",border:"#fc28a8",borderMuted:"#a21568",borderDim:"#5c0a3a",bg:void 0,cardBg:"#261b38",highlightBg:"#35254d",activeBg:"#4c3570",inputBg:"#35254d",inputBorder:"#35254d",inputText:"#fdfdfd",inputPlaceholder:"#a08eb7",inputPrompt:"#03e8fc",codeBg:"#1e142b",codeBorder:"#a21568",userMsgBg:"#35254d",userMsgBorder:"#35254d",userMsgText:"#fdfdfd",diffRemovalBg:"#471434",diffAdditionBg:"#144743",diffRemovalText:"#ff4081",diffAdditionText:"#00e5ff",diffRemovalHighlightColor:"#ff79a1",diffRemovalHighlightBg:"#6b1e4e",diffAdditionHighlightColor:"#66f5ff",diffAdditionHighlightBg:"#1e6b65",diffRemovalNum:"#ff4081",diffAdditionNum:"#00e5ff",diffRemovalPrefix:"#ff79a1",diffAdditionPrefix:"#66f5ff",primary:"#fdfdfd",secondary:"#03e8fc",accent:"#fc28a8",success:"#00e5ff",warning:"#ffc107",danger:"#ff4081",info:"#b388ff",statusOn:"#03e8fc",statusOff:"#a08eb7",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#fc28a8","#03e8fc"]},"Forest Sprite":{id:"Forest Sprite",name:"Forest Sprite",text:"#d6e6d1",textMuted:"#95b38d",textDim:"#628059",textInverted:"#161c14",textExclusive:"#eaf2e8",textMutedExclusive:"#a9c7a2",border:"#74a862",borderMuted:"#477038",borderDim:"#2b4720",bg:void 0,cardBg:"#1f291c",highlightBg:"#2a3826",activeBg:"#3a4d35",inputBg:"#2a3826",inputBorder:"#2a3826",inputText:"#d6e6d1",inputPlaceholder:"#95b38d",inputPrompt:"#8feb73",codeBg:"#161e14",codeBorder:"#477038",userMsgBg:"#2a3826",userMsgBorder:"#2a3826",userMsgText:"#d6e6d1",diffRemovalBg:"#3b231c",diffAdditionBg:"#203b1c",diffRemovalText:"#db6242",diffAdditionText:"#59cc3f",diffRemovalHighlightColor:"#f0896c",diffRemovalHighlightBg:"#5c362a",diffAdditionHighlightColor:"#80e368",diffAdditionHighlightBg:"#305929",diffRemovalNum:"#db6242",diffAdditionNum:"#59cc3f",diffRemovalPrefix:"#f0896c",diffAdditionPrefix:"#80e368",primary:"#d6e6d1",secondary:"#8feb73",accent:"#e69835",success:"#59cc3f",warning:"#e69835",danger:"#db6242",info:"#73b4eb",statusOn:"#8feb73",statusOff:"#95b38d",logoTextAnsi:"\x1B[1;32m",logoBodyAnsi:"\x1B[32m",logoMutedAnsi:"\x1B[90m",logoGradient:["#8feb73","#e69835"]}};var Vo=null;var Or=(e="Dark")=>{let t;e==="Mystery"||e==="Chaos"?(Vo||(Vo=Dr[Math.floor(Math.random()*Dr.length)]),t={...Vo,id:"Mystery"}):(Vo=null,bo[e]?t=bo[e]:e==="GitHub"?t=bo["GitHub Dark"]:e==="Transparent"?t=bo["Transparent Dark"]:t=bo.Dark);let n=t.codeText||t.secondary||t.info||t.logoGradient&&t.logoGradient[0]||"cyan";return{...t,codeText:n}};var Ca=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",yc=(e=2)=>{let t=Ca();return t==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)},xc=(e="...",t="Loading...",n="Dark")=>{let s=Ks[Math.floor(Math.random()*Ks.length)],o=Or(n),c=o.logoTextAnsi,f=o.logoBodyAnsi,l=o.logoMutedAnsi,k="\x1B[0m",p=[" \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 "],g=o.logoGradient||["#0077ff","#ff00ff"],T=Ea(g).multiline(p.join(`
557
+ ${e}`:""}`.trim();var gr=()=>import("./web_search-2PFIJKIL.js").then(e=>e.web_search),hr=()=>import("./web_scrape-BHSQTMX4.js").then(e=>e.web_scrape),pr=()=>import("./memory-M7ASUB6J.js").then(e=>e.memory),mr=()=>import("./chat-MELTWDZ3.js").then(e=>e.chat),yr=()=>import("./view_file-2THVIMD6.js").then(e=>e.view_file),xr=()=>import("./write_file-7X2GQFWK.js").then(e=>e.write_file),br=()=>import("./update_file-PXZHSSGS.js").then(e=>e.update_file),wr=()=>import("./exec_command-J23EG77W.js").then(e=>e.exec_command),kr=()=>import("./read_folder-EI2CNHNS.js").then(e=>e.read_folder),Ws=()=>import("./ask_user-K2DLZF6H.js").then(e=>e.ask_user),Tr=()=>import("./write_pdf-N2Q4Z3YP.js").then(e=>e.write_pdf),Sr=()=>import("./write_docx-4Y43QJUV.js").then(e=>e.write_docx),Uo=()=>import("./search_keyword-CSRQFPHQ.js").then(e=>e.search_keyword),_r=()=>import("./generate_image-4LIDEIYO.js").then(e=>e.generate_image),Wo=()=>import("./saveSummary-UGNDVNI5.js").then(e=>e.saveSummary),po=()=>import("./addMemScore-BCPTSMKD.js").then(e=>e.addMemScore),Ar=()=>import("./file_map-KS6Y7BP3.js").then(e=>e.file_map),Ho=()=>import("./todo-GFMPH2JV.js").then(e=>e.todo),Er=()=>import("./invokeSync-XW4AQKZ3.js").then(e=>e.invokeSync),Sa=()=>import("./invoke-AYPOVSTU.js").then(e=>e.invoke),Cr=()=>import("./getProgress-A2TW34Q7.js").then(e=>e.getProgress),_a=()=>import("./cancel-F3ZOEBKW.js").then(e=>e.cancel),Rr=()=>import("./emergency_rollback-6X27LZE4.js").then(e=>e.emergency_rollback),mo=()=>import("./awaitSubagent-JKQ2EHVY.js").then(e=>e.awaitSubagent),yo=()=>import("./answerSubagent-BPNNJXPC.js").then(e=>e.answerSubagent),Go=()=>import("./steerSubagent-UETXH2CB.js").then(e=>e.steerSubagent),jo=()=>import("./computer_action-OQ3CWQU3.js").then(e=>e.computer_action),vr=()=>import("./click-NULWZ3IK.js").then(e=>e.click),Mr=()=>import("./drag-RLRC6JFF.js").then(e=>e.drag),Ir=()=>import("./scroll-QVQD7I6A.js").then(e=>e.scroll),Hs=()=>import("./keyboard_typing-RPPKNVTA.js").then(e=>e.keyboard_typing),Gs=()=>import("./key_press-7F6CAPZD.js").then(e=>e.key_press),js=()=>import("./recapture_screen-PPT2E3CK.js").then(e=>e.recapture_screen),Ko=()=>import("./find_file-A6NYLQJS.js").then(e=>e.find_file),Aa={web_search:gr,web_scrape:hr,memory:pr,chat:mr,view_file:yr,write_file:xr,update_file:br,exec_command:wr,read_folder:kr,write_pdf:Tr,write_docx:Sr,search_keyword:Uo,generate_image:_r,saveSummary:Wo,addMemScore:po,file_map:Ar,todo:Ho,Todo:Ho,goal:Ho,Goal:Ho,invokeSync:Er,invoke:Sa,getProgress:Cr,cancel:_a,awaitSubagent:mo,answerSubagent:yo,steerSubagent:Go,computer_action:jo,computer_use:jo,ComputerAction:jo,ComputerUse:jo,click:vr,Click:vr,drag:Mr,Drag:Mr,scroll:Ir,Scroll:Ir,keyboard_typing:Hs,KeyboardTyping:Hs,keyboardtyping:Hs,key_press:Gs,KeyPress:Gs,keypress:Gs,recapture_screen:js,RecaptureScreen:js,recapturescreen:js,invoke_sync:Er,get_progress:Cr,await_subagent:mo,answer_subagent:yo,steer_subagent:Go,steer:Go,Steer:Go,ask:Ws,Ask:Ws,AskUser:Ws,WebSearch:gr,WebScrape:hr,ReadFile:yr,ReadFolder:kr,WriteFile:xr,PatchFile:br,WritePDF:Tr,WriteDoc:Sr,Run:wr,SearchKeyword:Uo,CodeSearch:Uo,code_search:Uo,Memory:pr,Chat:mr,GenerateImage:_r,saveSumary:Wo,SaveSummary:Wo,SaveSumary:Wo,add_mem_score:po,AddMemScore:po,addMemoryScore:po,AddMemoryScore:po,FileMap:Ar,answer:yo,Answer:yo,AnswerSubagent:yo,await:mo,Await:mo,AwaitSubagent:mo,EmergencyRollback:Rr,emergency_rollback:Rr,find_file:Ko,findFile:Ko,FindFile:Ko,findfile:Ko},xo=async(e,t,n={})=>{let s=n.mode?n.mode.toLowerCase():"flux",o=e.toLowerCase(),f=["memory","chat","savesummary","addmemscore","add_mem_score","ask","web_search","web_scrape","await"].some(g=>o.includes(g))||o==="ask",k=["click","drag","scroll","keyboardtyping","keyboard_typing","keypress","key_press","recapturescreen","recapture_screen","computer"].some(g=>o.includes(g));if(!f){if(s==="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(s==="icu"){if(!k)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 ${n.mode||"Flux"} mode. Tell user to switch (\`/mode flow\`) for document generation.`}let m=Aa[e];if(!m){let g=["ReadFile","ReadFolder","FindFile","PatchFile","WriteFile","CodeSearch","Run","Goal","AskUser","WebSearch","WebScrape","WritePDF","WriteDoc","Click","Drag","Scroll","KeyboardTyping","KeyPress","RecaptureScreen","Invoke","InvokeSync","Await","GetProgress","Steer","Cancel","EmergencyRollback","Chat","Memory"],T={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"},p=o.replace(/[^a-z0-9]/g,""),i=T[p]||null;if(!i){let w=0,I=A=>{let $=new Set;for(let C=0;C<A.length-1;C++)$.add(A.slice(C,C+2));return $},h=I(p);for(let A of g){let $=A.toLowerCase().replace(/[^a-z0-9]/g,"");if(p===$){i=A;break}let C=0;($.includes(p)||p.includes($))&&(C+=.6);let x=I($),_=0;for(let y of h)x.has(y)&&_++;let M=2*_/(h.size+x.size||1);C=Math.max(C,M),C>w&&C>=.35&&(w=C,i=A)}}let u=i?` Do you mean '${i}'?`:"";return`ERROR: Action [${e}] not found in registry.${u}`}try{return await(await m())(t,n)}catch(g){let T=g instanceof Error?g.message:String(g);return`ERROR: Execution failed for [${e}]: ${T}`}};import ie from"path";import Ue from"fs";import Ea from"gradient-string";var Ks=["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 Dr=[{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"]}],bo={Dark:{id:"Dark",name:"Dark (Default)",text:"white",textMuted:"gray",textDim:"grey",textInverted:"black",textExclusive:"#B5B8D9",textMutedExclusive:"#D4DEE7",border:"white",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:"#1e1e1e",highlightBg:"#2a2a2a",activeBg:"#3a3a3a",inputBg:"#555555",inputBorder:"#555555",inputText:"white",inputPlaceholder:"#cccccc",inputPrompt:"white",codeBg:"#1a1a1a",codeBorder:"#444444",userMsgBg:"#444444",userMsgBorder:"#444444",userMsgText:"white",diffRemovalBg:"#250808",diffAdditionBg:"#072410",diffRemovalText:"#885555",diffAdditionText:"#558866",diffRemovalHighlightColor:"#ff3333",diffRemovalHighlightBg:"#5a1818",diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:"#185a25",diffRemovalNum:"#d96868",diffAdditionNum:"#68d98c",diffRemovalPrefix:"#ff4d4d",diffAdditionPrefix:"#4dff88",primary:"white",secondary:"cyan",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"white",statusOff:"gray",logoTextAnsi:"\x1B[1;37m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#0077ff","#ff00ff"]},Light:{id:"Light",name:"Light",text:"black",textMuted:"gray",textDim:"grey",textInverted:"white",border:"black",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:"#e5e5e5",highlightBg:"#d4d4d4",activeBg:"#c0c0c0",inputBg:"#d0d0d0",inputBorder:"#d0d0d0",inputText:"black",inputPlaceholder:"#555555",inputPrompt:"black",codeBg:"#e8e8e8",codeBorder:"#b0b0b0",userMsgBg:"#d0d0d0",userMsgBorder:"#d0d0d0",userMsgText:"black",diffRemovalBg:"#fce8e8",diffAdditionBg:"#e6f9e6",diffRemovalText:"#661111",diffAdditionText:"#115511",diffRemovalHighlightColor:"#440000",diffRemovalHighlightBg:"#f8b4b4",diffAdditionHighlightColor:"#003300",diffAdditionHighlightBg:"#a6ebad",diffRemovalNum:"#c02020",diffAdditionNum:"#188028",diffRemovalPrefix:"#d01010",diffAdditionPrefix:"#109020",primary:"black",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"black",statusOff:"gray",logoTextAnsi:"\x1B[1;30m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#0077ff","#ff00ff"]},"GitHub Dark":{id:"GitHub Dark",name:"GitHub Dark",text:"#c9d1d9",textMuted:"#8b949e",textDim:"#6e7681",textInverted:"#0d1117",border:"#30363d",borderMuted:"#30363d",borderDim:"#21262d",bg:void 0,cardBg:"#161b22",highlightBg:"#21262d",activeBg:"#30363d",inputBg:"#21262d",inputBorder:"#21262d",inputText:"#c9d1d9",inputPlaceholder:"#8b949e",inputPrompt:"#58a6ff",codeBg:"#0d1117",codeBorder:"#30363d",userMsgBg:"#21262d",userMsgBorder:"#21262d",userMsgText:"#c9d1d9",diffRemovalBg:"#3c1e1e",diffAdditionBg:"#11381e",diffRemovalText:"#f85149",diffAdditionText:"#3fb950",diffRemovalHighlightColor:"#ff7b72",diffRemovalHighlightBg:"#701c1c",diffAdditionHighlightColor:"#56d364",diffAdditionHighlightBg:"#116329",diffRemovalNum:"#f85149",diffAdditionNum:"#3fb950",diffRemovalPrefix:"#f85149",diffAdditionPrefix:"#3fb950",primary:"#c9d1d9",secondary:"#58a6ff",accent:"#bc8cff",success:"#3fb950",warning:"#d29922",danger:"#f85149",info:"#58a6ff",statusOn:"#58a6ff",statusOff:"#8b949e",logoTextAnsi:"\x1B[1;36m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#2ea043","#56d364"]},"GitHub Light":{id:"GitHub Light",name:"GitHub Light",text:"#24292f",textMuted:"#57606a",textDim:"#6e7781",textInverted:"#ffffff",border:"#d0d7de",borderMuted:"#d0d7de",borderDim:"#e1e4e8",bg:void 0,cardBg:"#f6f8fa",highlightBg:"#eaeef2",activeBg:"#d0d7de",inputBg:"#eaeef2",inputBorder:"#eaeef2",inputText:"#24292f",inputPlaceholder:"#57606a",inputPrompt:"#0969da",codeBg:"#ffffff",codeBorder:"#d0d7de",userMsgBg:"#eaeef2",userMsgBorder:"#eaeef2",userMsgText:"#24292f",diffRemovalBg:"#ffebe9",diffAdditionBg:"#e6ffec",diffRemovalText:"#cf222e",diffAdditionText:"#1a7f37",diffRemovalHighlightColor:"#82071e",diffRemovalHighlightBg:"#ffc1c0",diffAdditionHighlightColor:"#116329",diffAdditionHighlightBg:"#acf2bd",diffRemovalNum:"#cf222e",diffAdditionNum:"#1a7f37",diffRemovalPrefix:"#cf222e",diffAdditionPrefix:"#1a7f37",primary:"#24292f",secondary:"#0969da",accent:"#8250df",success:"#1a7f37",warning:"#9a6700",danger:"#cf222e",info:"#0969da",statusOn:"#0969da",statusOff:"#57606a",logoTextAnsi:"\x1B[1;34m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#1a7f37","#2da44e"]},"Transparent Dark":{id:"Transparent Dark",name:"Transparent Dark",text:"white",textMuted:"gray",textDim:"grey",textInverted:"black",border:"gray",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:void 0,highlightBg:"#2a2a2a",activeBg:"#3a3a3a",inputBg:"#555555",inputBorder:"#555555",inputText:"white",inputPlaceholder:"#cccccc",inputPrompt:"white",codeBg:void 0,codeBorder:"gray",userMsgBg:"#555555",userMsgBorder:"#555555",userMsgText:"white",diffRemovalBg:void 0,diffAdditionBg:void 0,diffRemovalText:"#ff6666",diffAdditionText:"#66ff66",diffRemovalHighlightColor:"#ff3333",diffRemovalHighlightBg:void 0,diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:void 0,diffRemovalNum:"#ff6666",diffAdditionNum:"#66ff66",diffRemovalPrefix:"#ff4d4d",diffAdditionPrefix:"#4dff88",primary:"white",secondary:"cyan",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"white",statusOff:"gray",logoTextAnsi:"\x1B[1;37m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#0077ff","#ff00ff"]},"Transparent Light":{id:"Transparent Light",name:"Transparent Light",text:"black",textMuted:"gray",textDim:"grey",textInverted:"white",border:"gray",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:void 0,highlightBg:"#d4d4d4",activeBg:"#c0c0c0",inputBg:"#d0d0d0",inputBorder:"#d0d0d0",inputText:"black",inputPlaceholder:"#555555",inputPrompt:"black",codeBg:void 0,codeBorder:"gray",userMsgBg:"#d0d0d0",userMsgBorder:"#d0d0d0",userMsgText:"black",diffRemovalBg:void 0,diffAdditionBg:void 0,diffRemovalText:"#c02020",diffAdditionText:"#188028",diffRemovalHighlightColor:"#800000",diffRemovalHighlightBg:void 0,diffAdditionHighlightColor:"#004000",diffAdditionHighlightBg:void 0,diffRemovalNum:"#c02020",diffAdditionNum:"#188028",diffRemovalPrefix:"#d01010",diffAdditionPrefix:"#109020",primary:"black",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"black",statusOff:"gray",logoTextAnsi:"\x1B[1;30m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#0077ff","#ff00ff"]},"Synthwave 84":{id:"Synthwave 84",name:"Synthwave 84",text:"#fdfdfd",textMuted:"#a08eb7",textDim:"#705c8a",textInverted:"#1a1025",textExclusive:"#e3dcf0",textMutedExclusive:"#b9abc9",border:"#fc28a8",borderMuted:"#a21568",borderDim:"#5c0a3a",bg:void 0,cardBg:"#261b38",highlightBg:"#35254d",activeBg:"#4c3570",inputBg:"#35254d",inputBorder:"#35254d",inputText:"#fdfdfd",inputPlaceholder:"#a08eb7",inputPrompt:"#03e8fc",codeBg:"#1e142b",codeBorder:"#a21568",userMsgBg:"#35254d",userMsgBorder:"#35254d",userMsgText:"#fdfdfd",diffRemovalBg:"#471434",diffAdditionBg:"#144743",diffRemovalText:"#ff4081",diffAdditionText:"#00e5ff",diffRemovalHighlightColor:"#ff79a1",diffRemovalHighlightBg:"#6b1e4e",diffAdditionHighlightColor:"#66f5ff",diffAdditionHighlightBg:"#1e6b65",diffRemovalNum:"#ff4081",diffAdditionNum:"#00e5ff",diffRemovalPrefix:"#ff79a1",diffAdditionPrefix:"#66f5ff",primary:"#fdfdfd",secondary:"#03e8fc",accent:"#fc28a8",success:"#00e5ff",warning:"#ffc107",danger:"#ff4081",info:"#b388ff",statusOn:"#03e8fc",statusOff:"#a08eb7",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#fc28a8","#03e8fc"]},"Forest Sprite":{id:"Forest Sprite",name:"Forest Sprite",text:"#d6e6d1",textMuted:"#95b38d",textDim:"#628059",textInverted:"#161c14",textExclusive:"#eaf2e8",textMutedExclusive:"#a9c7a2",border:"#74a862",borderMuted:"#477038",borderDim:"#2b4720",bg:void 0,cardBg:"#1f291c",highlightBg:"#2a3826",activeBg:"#3a4d35",inputBg:"#2a3826",inputBorder:"#2a3826",inputText:"#d6e6d1",inputPlaceholder:"#95b38d",inputPrompt:"#8feb73",codeBg:"#161e14",codeBorder:"#477038",userMsgBg:"#2a3826",userMsgBorder:"#2a3826",userMsgText:"#d6e6d1",diffRemovalBg:"#3b231c",diffAdditionBg:"#203b1c",diffRemovalText:"#db6242",diffAdditionText:"#59cc3f",diffRemovalHighlightColor:"#f0896c",diffRemovalHighlightBg:"#5c362a",diffAdditionHighlightColor:"#80e368",diffAdditionHighlightBg:"#305929",diffRemovalNum:"#db6242",diffAdditionNum:"#59cc3f",diffRemovalPrefix:"#f0896c",diffAdditionPrefix:"#80e368",primary:"#d6e6d1",secondary:"#8feb73",accent:"#e69835",success:"#59cc3f",warning:"#e69835",danger:"#db6242",info:"#73b4eb",statusOn:"#8feb73",statusOff:"#95b38d",logoTextAnsi:"\x1B[1;32m",logoBodyAnsi:"\x1B[32m",logoMutedAnsi:"\x1B[90m",logoGradient:["#8feb73","#e69835"]}};var Vo=null;var Or=(e="Dark")=>{let t;e==="Mystery"||e==="Chaos"?(Vo||(Vo=Dr[Math.floor(Math.random()*Dr.length)]),t={...Vo,id:"Mystery"}):(Vo=null,bo[e]?t=bo[e]:e==="GitHub"?t=bo["GitHub Dark"]:e==="Transparent"?t=bo["Transparent Dark"]:t=bo.Dark);let n=t.codeText||t.secondary||t.info||t.logoGradient&&t.logoGradient[0]||"cyan";return{...t,codeText:n}};var Ca=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",yc=(e=2)=>{let t=Ca();return t==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)},xc=(e="...",t="Loading...",n="Dark")=>{let s=Ks[Math.floor(Math.random()*Ks.length)],o=Or(n),c=o.logoTextAnsi,f=o.logoBodyAnsi,l=o.logoMutedAnsi,k="\x1B[0m",m=[" \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 "],g=o.logoGradient||["#0077ff","#ff00ff"],T=Ea(g).multiline(m.join(`
559
558
  `)).split(`
560
- `),m=i=>`${l}${i}${k}`;return`${T[0]}
559
+ `),p=i=>`${l}${i}${k}`;return`${T[0]}
561
560
  ${T[1]} ${c}Selected Provider: ${t}${k}
562
561
  ${T[2]}
563
- ${T[3]} ${c}FluxFlow ${m("v"+e)}${k}
562
+ ${T[3]} ${c}FluxFlow ${p("v"+e)}${k}
564
563
  ${T[4]}
565
564
  ${T[5]} ${f}See /help for additional commands.${k}
566
- ${T[6]} ${m(s)}
565
+ ${T[6]} ${p(s)}
567
566
  ${T[7]}
568
- `};import{WebSocket as Yo}from"ws";var Ut=null,Jn=!1,Ra="ws://localhost:56832",Vs=[],Qn=null,Ys=null,Lr="2.0.0",kc=e=>{Lr=e,Pr()},qs=e=>{Ys=e},Pr=()=>{if(Ut||Jn)return;Jn=!0;let e=new Yo(Ra);e.on("open",()=>{for(Ut=e,Jn=!1,Ut.send(JSON.stringify({command:"version",version:Lr,pid:process.pid,ppid:process.ppid}));Vs.length>0;)Ut.send(JSON.stringify(Vs.shift()))}),e.on("message",t=>{try{let n=JSON.parse(t.toString());n.command==="contextResponse"&&Qn?(Qn(n.data),Qn=null):n.command==="securityResponse"&&Ys&&Ys(n.result)}catch{}}),e.on("error",()=>{Jn=!1,Ut=null}),e.on("close",()=>{Jn=!1,Ut=null})},qo=e=>{Ut&&Ut.readyState===Yo.OPEN?Ut.send(JSON.stringify(e)):(Vs.push(e),Jn||Pr())},zo=()=>Ut!==null&&Ut.readyState===Yo.OPEN,Tc=e=>{qo({command:"status",status:e})},Hn=()=>new Promise(e=>{if(!Ut||Ut.readyState!==Yo.OPEN){e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]});return}Qn=e,Ut.send(JSON.stringify({command:"requestContext"})),setTimeout(()=>{Qn===e&&(e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]}),Qn=null)},1e3)}),$r=e=>{qo({command:"open",filePath:e})},zs=(e,t,n)=>{qo({command:"showDiff",filePath:e,originalContent:t,modifiedContent:n})},Nr=(e,t)=>{qo({command:"closeDiff",filePath:e,result:t})};import Xs from"path";import va from"fs";var Ma=e=>{try{return va.readdirSync(e,{withFileTypes:!0})}catch{return[]}},Js=(e,t=4,n=1,s=Ma,o=[],c=null)=>{let f=c||s(e),l=" ".repeat(n-1),k=n===1?new Set([...io,...o,...ro(e),...ro(process.cwd())]):o instanceof Set?o:new Set([...io,...o]),p=x=>k.has(x),g=f.filter(x=>!p(x.name)),T=f.filter(x=>p(x.name)).length,m=g.filter(x=>!x.isDirectory()).map(x=>x.name).sort(),i=g.filter(x=>x.isDirectory()).sort((x,_)=>x.name.localeCompare(_.name)),u=x=>{let _=x.length;if(_===0)return"no files";let M=Array.from(new Set(x.map(a=>{let R=typeof a=="string"?a:a.name;return Xs.extname(R).slice(1)}).filter(Boolean))).sort(),y="*";return M.length===1?y=`*.${M[0]}`:M.length>1&&(y=`*.{${M.join(", ")}}`),_===1?y:`${y} ${_} files`},w="";if(n===1){let x=m.join(", "),_=T>0?` [${T} ignored]`:"";(x||_)&&(w+=`${l}${x?x+(_?`${_}`:""):_.trim()}
569
- `)}else m.length>0&&(w+=`${l}[${u(m)}]
570
- `);let I=10,h=i.slice(0,I),A=i.length>I,$=[],C=[];for(let x of h){let _=Xs.join(e,x.name),M=x.name,y=n,a=s(_),R=a.filter(v=>!p(v.name)),d=R.filter(v=>v.isDirectory()),r=R.filter(v=>!v.isDirectory());for(;r.length===0&&d.length===1&&y<t;)M=`${M}/${d[0].name}`,_=Xs.join(_,d[0].name),y++,a=s(_),R=a.filter(v=>!p(v.name)),d=R.filter(v=>v.isDirectory()),r=R.filter(v=>!v.isDirectory());let E=d.length>0;if(E&&y<t)C.push({displayName:M,subDirPath:_,subEntries:a,nextDepth:y+1});else{let v=u(r),U=E&&y>=t?" ...max scan depth":"";$.push(`${M}/${v}${U}`)}}$.length>0&&(w+=`${l}${$.join(", ")}
567
+ `};import{WebSocket as Yo}from"ws";var Ut=null,Jn=!1,Ra="ws://localhost:56832",Vs=[],Qn=null,Ys=null,Lr="2.0.0",kc=e=>{Lr=e,Pr()},qs=e=>{Ys=e},Pr=()=>{if(Ut||Jn)return;Jn=!0;let e=new Yo(Ra);e.on("open",()=>{for(Ut=e,Jn=!1,Ut.send(JSON.stringify({command:"version",version:Lr,pid:process.pid,ppid:process.ppid}));Vs.length>0;)Ut.send(JSON.stringify(Vs.shift()))}),e.on("message",t=>{try{let n=JSON.parse(t.toString());n.command==="contextResponse"&&Qn?(Qn(n.data),Qn=null):n.command==="securityResponse"&&Ys&&Ys(n.result)}catch{}}),e.on("error",()=>{Jn=!1,Ut=null}),e.on("close",()=>{Jn=!1,Ut=null})},qo=e=>{Ut&&Ut.readyState===Yo.OPEN?Ut.send(JSON.stringify(e)):(Vs.push(e),Jn||Pr())},zo=()=>Ut!==null&&Ut.readyState===Yo.OPEN,Tc=e=>{qo({command:"status",status:e})},Hn=()=>new Promise(e=>{if(!Ut||Ut.readyState!==Yo.OPEN){e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]});return}Qn=e,Ut.send(JSON.stringify({command:"requestContext"})),setTimeout(()=>{Qn===e&&(e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]}),Qn=null)},1e3)}),$r=e=>{qo({command:"open",filePath:e})},zs=(e,t,n)=>{qo({command:"showDiff",filePath:e,originalContent:t,modifiedContent:n})},Nr=(e,t)=>{qo({command:"closeDiff",filePath:e,result:t})};import Xs from"path";import va from"fs";var Ma=e=>{try{return va.readdirSync(e,{withFileTypes:!0})}catch{return[]}},Js=(e,t=4,n=1,s=Ma,o=[],c=null)=>{let f=c||s(e),l=" ".repeat(n-1),k=n===1?new Set([...io,...o,...ro(e),...ro(process.cwd())]):o instanceof Set?o:new Set([...io,...o]),m=x=>k.has(x),g=f.filter(x=>!m(x.name)),T=f.filter(x=>m(x.name)).length,p=g.filter(x=>!x.isDirectory()).map(x=>x.name).sort(),i=g.filter(x=>x.isDirectory()).sort((x,_)=>x.name.localeCompare(_.name)),u=x=>{let _=x.length;if(_===0)return"no files";let M=Array.from(new Set(x.map(a=>{let R=typeof a=="string"?a:a.name;return Xs.extname(R).slice(1)}).filter(Boolean))).sort(),y="*";return M.length===1?y=`*.${M[0]}`:M.length>1&&(y=`*.{${M.join(", ")}}`),_===1?y:`${y} ${_} files`},w="";if(n===1){let x=p.join(", "),_=T>0?` [${T} ignored]`:"";(x||_)&&(w+=`${l}${x?x+(_?`${_}`:""):_.trim()}
568
+ `)}else p.length>0&&(w+=`${l}[${u(p)}]
569
+ `);let I=10,h=i.slice(0,I),A=i.length>I,$=[],C=[];for(let x of h){let _=Xs.join(e,x.name),M=x.name,y=n,a=s(_),R=a.filter(v=>!m(v.name)),d=R.filter(v=>v.isDirectory()),r=R.filter(v=>!v.isDirectory());for(;r.length===0&&d.length===1&&y<t;)M=`${M}/${d[0].name}`,_=Xs.join(_,d[0].name),y++,a=s(_),R=a.filter(v=>!m(v.name)),d=R.filter(v=>v.isDirectory()),r=R.filter(v=>!v.isDirectory());let E=d.length>0;if(E&&y<t)C.push({displayName:M,subDirPath:_,subEntries:a,nextDepth:y+1});else{let v=u(r),U=E&&y>=t?" ...max scan depth":"";$.push(`${M}/${v}${U}`)}}$.length>0&&(w+=`${l}${$.join(", ")}
571
570
  `);for(let{displayName:x,subDirPath:_,subEntries:M,nextDepth:y}of C)w+=`${l}${x}/
572
571
  `,w+=Js(_,t,y,s,k,M);return A&&(w+=`${l}...max scan width, ReadFolder if needed
573
572
  `),w};import Qs from"path";import Ia from"fs";var Da=e=>{try{return Ia.readdirSync(e,{withFileTypes:!0})}catch{return[]}},Zs=(e,t,n="",s=1,o=Da,c=[])=>{let f=o(e),l=Qs.sep;if(f.length>100)return`${n}\u2514\u2500\u2500 ${Qs.basename(e)}${l} ...100+ files...
574
- `;let k="",p=c,g=f.filter(i=>!p.includes(i.name)&&!i.name.startsWith(".")),T=f.filter(i=>p.includes(i.name)||i.name.startsWith(".")).map(i=>i.name).sort();g.sort((i,u)=>i.isDirectory()&&!u.isDirectory()?-1:!i.isDirectory()&&u.isDirectory()?1:i.name.localeCompare(u.name));let m=[...g.map(i=>({name:i.name,isDir:i.isDirectory()})),...T.map(i=>({name:i,isDir:!0,isCollapsed:!0}))];return m.forEach((i,u)=>{let w=u===m.length-1,I=Qs.join(e,i.name),h=w?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",A=n+(w?" ":"\u2502 ");if(i.isCollapsed){k+=`${n}${h}${i.name}${l}...
573
+ `;let k="",m=c,g=f.filter(i=>!m.includes(i.name)&&!i.name.startsWith(".")),T=f.filter(i=>m.includes(i.name)||i.name.startsWith(".")).map(i=>i.name).sort();g.sort((i,u)=>i.isDirectory()&&!u.isDirectory()?-1:!i.isDirectory()&&u.isDirectory()?1:i.name.localeCompare(u.name));let p=[...g.map(i=>({name:i.name,isDir:i.isDirectory()})),...T.map(i=>({name:i,isDir:!0,isCollapsed:!0}))];return p.forEach((i,u)=>{let w=u===p.length-1,I=Qs.join(e,i.name),h=w?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",A=n+(w?" ":"\u2502 ");if(i.isCollapsed){k+=`${n}${h}${i.name}${l}...
575
574
  `;return}i.isDir?s>t?k+=`${n}${h}${i.name}${l} ...depth exceeded...
576
575
  `:o(I).length>80?k+=`${n}${h}${i.name}${l} ...80+ files...
577
576
  `:(k+=`${n}${h}${i.name}${l}
578
577
  `,k+=Zs(I,t,A,s+1,o,c)):k+=`${n}${h}${i.name}
579
- `}),k};var Ze=async(e,t,n=5,s=1e3)=>{let o=t?.signal;for(let f=0;f<n;f++){if(o?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{let l=await fetch(e,t);if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),l.ok||l.status!==429&&l.status<500)return l}catch(l){if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),l.name==="AbortError"||o?.aborted||f===n-1)throw l}o?await new Promise((l,k)=>{let p=setTimeout(()=>{o.removeEventListener("abort",g),l()},Math.min(24e3,s*Math.pow(2,f))),g=()=>{clearTimeout(p),k(new DOMException("The user aborted a request.","AbortError"))};o.addEventListener("abort",g)}):await new Promise(l=>setTimeout(l,Math.min(24e3,s*Math.pow(2,f))))}if(o?.aborted)throw new DOMException("The user aborted a request.","AbortError");let c=await fetch(e,t);return typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),c};async function Xo(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",t);return[...new Uint8Array(n).slice(0,16)].map(s=>s.toString(16).padStart(2,"0")).join("")}var xn=e=>typeof e!="string"?e:e.replace(/<\|channel>thought/gi,"<think>").replace(/<channel\|>/gi,"</think>");var Jo=async function*(e,t,n,s,o,c,f,l,k=1){let p=[];s&&p.push({role:"system",content:s});for(let _ of n){let M=_.role==="user"?"user":"assistant",y=[];if(Array.isArray(_.parts)){for(let a of _.parts)if(a.text)y.push({type:"text",text:a.text});else if((a.inlineData||a.inline_data)&&f){let R=a.inlineData||a.inline_data,d=R.mimeType||R.mime_type||"image/jpeg",r=R.data;d.startsWith("image/")&&y.push({type:"image_url",image_url:{url:`data:${d};base64,${r}`}})}}else{let a=_.text||"";a&&y.push({type:"text",text:a})}p.push({role:M,content:y.length===1&&y[0].type==="text"?y[0].text:y})}let g={model:t,messages:p,stream:!0,stream_options:{include_usage:!0},temperature:k,tools:[],tool_choice:"none"},T=He("DeepSeek",t,o),i=T!==null?T:o!=="Fast"?{Low:"low",Medium:"high",Standard:"high",High:"max",xHigh:"max"}[o]||"high":null;i&&i!=="disabled"&&i!=="none"&&i!=="false"&&i!==!1?(g.reasoning_effort=i,g.extra_body={thinking:{type:"enabled"}}):g.extra_body={thinking:{type:"disabled"}};let u=await Ze("https://api.deepseek.com/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(g),signal:l});if(!u.ok){let _=await u.json().catch(()=>({}));throw new Error(`DeepSeek Error (${u.status}): ${_.error?.message||u.statusText}`)}let w=u.body.getReader(),I=new TextDecoder,h="",A=[],$=null,C=Date.now(),x=!1;for(;;){let{done:_,value:M}=await w.read();if(_){x&&(A.length>0||$)&&(yield{candidates:A.length>0?[{content:{parts:A}}]:[],usageMetadata:$});break}h+=I.decode(M,{stream:!0});let y=h.split(`
580
- `);h=y.pop();for(let a of y){let R=a.trim();if(!R||!R.startsWith("data: "))continue;let d=!1;if(R==="data: [DONE]")d=!0;else try{let r=JSON.parse(R.substring(6)),E=r.choices?.[0]?.delta,v=r.usage;if(r.choices?.[0]?.finish_reason&&(d=!0),v&&($={totalTokenCount:v.total_tokens||v.prompt_tokens+v.completion_tokens,promptTokenCount:v.prompt_tokens||0,candidatesTokenCount:v.completion_tokens||0,cachedContentTokenCount:v.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:v.completion_tokens_details?.reasoning_tokens||0},x=!0),E){let U=E.reasoning_content||null;U&&(A.push({text:U,thought:!0}),x=!0),E.content&&(A.push({text:E.content}),x=!0)}}catch{}if((d||Date.now()-C>=150)&&x&&(yield{candidates:A.length>0?[{content:{parts:[...A]}}]:[],usageMetadata:$},A=[],C=Date.now(),x=!1),d)break}Date.now()-C>=150&&x&&(yield{candidates:A.length>0?[{content:{parts:[...A]}}]:[],usageMetadata:$},A=[],C=Date.now(),x=!1)}};var Qo=async function*(e,t,n,s,o,c,f,l,k=1,p=null){let g=[];s&&g.push({role:"system",content:s});for(let a of n){let R=a.role==="user"?"user":"assistant",d=[];if(Array.isArray(a.parts)){for(let r of a.parts)if(r.text)d.push({type:"text",text:r.text});else if(r.inlineData&&f){let E=r.inlineData.mimeType,v=r.inlineData.data;E.startsWith("image/")&&d.push({type:"image_url",image_url:`data:${E};base64,${v}`})}}else{let r=a.text||"";r&&d.push({type:"text",text:r})}d.length>0&&g.push({role:R,content:d.length===1&&d[0].type==="text"?d[0].text:d})}let T={Fast:"none",Low:"none",Medium:"high",Standard:"high",High:"high",xHigh:"high"},m=`${e.slice(-5)}${p||""}${o}${t}`,i=await Xo(m),u={model:t,messages:g,stream:!0,temperature:k,prompt_cache_key:i,tools:[],tool_choice:"none"},w=He("Mistral",t,o);w!==null&&w!=="none"?w&&w!=="none"&&w!=="disabled"&&w!==!1&&(u.reasoning_effort=w):o&&T[o]!=="none"&&(u.reasoning_effort=T[o]||"high");let I=await Ze("https://api.mistral.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(u),signal:l});if(!I.ok){let a=await I.text().catch(()=>""),R=I.statusText;try{let d=JSON.parse(a);R=d.error?.message||d.message||JSON.stringify(d.detail||d)}catch{a&&(R=a)}throw new Error(`Mistral Error (${I.status}): ${JSON.stringify(R)}`)}let h=I.body.getReader(),A=new TextDecoder,$="",C=[],x=null,_=Date.now(),M=!1,y=a=>a?typeof a=="string"?xn(a):Array.isArray(a)?a.map(y).filter(Boolean).join(""):typeof a=="object"&&a!==null?typeof a.text=="string"?xn(a.text):typeof a.content=="string"?xn(a.content):typeof a.thinking=="string"?xn(a.thinking):typeof a.reasoning_content=="string"?xn(a.reasoning_content):typeof a.reasoning=="string"?xn(a.reasoning):typeof a.value=="string"?xn(a.value):a.text?y(a.text):a.content?y(a.content):a.thinking?y(a.thinking):a.reasoning_content?y(a.reasoning_content):a.reasoning?y(a.reasoning):a.value?y(a.value):"":xn(String(a)):"";for(;;){let{done:a,value:R}=await h.read();if(a){M&&(C.length>0||x)&&(yield{candidates:C.length>0?[{content:{parts:C}}]:[],usageMetadata:x});break}$+=A.decode(R,{stream:!0});let d=$.split(`
581
- `);$=d.pop();for(let r of d){let E=r.trim();if(!E||!E.startsWith("data: "))continue;let v=!1;if(E==="data: [DONE]")v=!0;else try{let U=JSON.parse(E.substring(6)),O=U.choices?.[0]?.delta,P=U.usage;if(U.choices?.[0]?.finish_reason&&(v=!0),P&&(x={totalTokenCount:P.total_tokens||(P.prompt_tokens||0)+(P.completion_tokens||0),promptTokenCount:P.prompt_tokens||0,candidatesTokenCount:P.completion_tokens||0,cachedContentTokenCount:P.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:P.completion_tokens_details?.reasoning_tokens||0},M=!0),O){let re=O.thinking||O.reasoning_content||O.reasoning,de=y(re);de&&(C.push({text:de,thought:!0}),M=!0);let Q=O.content||(!O.thinking&&!O.reasoning_content&&!O.reasoning?O.text:null);if(Q)if(Array.isArray(Q))for(let ke of Q)if(typeof ke=="object"&&ke!==null){let ae=ke.type==="thinking"||ke.type==="reasoning"||!!ke.thought,it=y(ke);it&&(C.push({text:it,...ae?{thought:!0}:{}}),M=!0)}else{let ae=y(ke);ae&&(C.push({text:ae}),M=!0)}else if(typeof Q=="object"&&Q!==null){let ke=Q.type==="thinking"||Q.type==="reasoning"||!!Q.thought,ae=y(Q);ae&&(C.push({text:ae,...ke?{thought:!0}:{}}),M=!0)}else{let ke=y(Q);ke&&(C.push({text:ke}),M=!0)}}}catch{}if((v||Date.now()-_>=150)&&M&&(yield{candidates:C.length>0?[{content:{parts:[...C]}}]:[],usageMetadata:x},C=[],_=Date.now(),M=!1),v)break}Date.now()-_>=150&&M&&(yield{candidates:C.length>0?[{content:{parts:[...C]}}]:[],usageMetadata:x},C=[],_=Date.now(),M=!1)}};var Zo=async function*(e,t,n,s,o,c,f=!1,l,k=1){let p=[];s&&p.push({role:"system",content:s}),n.forEach(ae=>{let it=ae.role==="model"?"assistant":"user",L=[];Array.isArray(ae.parts)&&ae.parts.forEach(F=>{if(F.text)L.push({type:"text",text:F.text});else if(F.inlineData&&f){let Ee=F.inlineData.mimeType,oe=F.inlineData.data;Ee.startsWith("image/")&&ft(t)&&L.push({type:"image_url",image_url:{url:`data:${Ee};base64,${oe}`}})}}),p.push({role:it,content:L.length===1&&L[0].type==="text"?L[0].text:L})});let g=He("NVIDIA",t,o),m=g!==null?g:{Fast:"Fast",Low:"Fast",Medium:"Standard",Standard:"Standard",High:"High",xHigh:"High"}[o]||"High",i=m!=="Fast"&&m!=="none"&&m!=="disabled"&&m!==!1,u=t.includes("kimi"),w=t.includes("gemma"),I=t.includes("deepseek"),h=t.includes("glm"),A=t.includes("mistral"),$=t.includes("minimax"),C=t.includes("gpt"),x=t.includes("qwen"),_=t.includes("nemotron"),M=t.includes("llama-3"),y=t.includes("seed"),a=t.includes("poolside"),R=t.includes("thinkingmachines")||t.includes("muse"),d=M,r={Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},E={Fast:"64",Low:"64",Medium:"4096",Standard:"4096",High:"16384",xHigh:"16384"},v={Fast:"none",Low:"minimal",Medium:"medium",Standard:"medium",High:"max",xHigh:"max"},U=$||I||a||R?16384:32768;U=process.env.NVIDIA_BASE_URL?1024:U;let O={model:t,messages:p,max_tokens:U,stream:!0,stream_options:{include_usage:!0},temperature:k,tools:[],tool_choice:"none",...C&&{thinking:r[o]||"high"}};if(!(process.env.NVIDIA_BASE_URL||d))if(u)O.chat_template_kwargs={thinking:i};else if(w)O.chat_template_kwargs={enable_thinking:i};else if(I)if(i){let ae=m==="High"?"max":"high";O.chat_template_kwargs={thinking:!0,reasoning_effort:ae}}else O.chat_template_kwargs={thinking:!1};else h?O.chat_template_kwargs={enable_thinking:i,clear_thinking:!i}:A?O.reasoning_effort=i?"high":"none":$&&t.includes("minimax-m3")?O.chat_template_kwargs={thinking_mode:i?"enabled":"disabled"}:x?O.chat_template_kwargs={enable_thinking:i}:_?m==="High"?O.chat_template_kwargs={enable_thinking:!0}:m==="Standard"?O.chat_template_kwargs={enable_thinking:!0,medium_effort:!0}:O.chat_template_kwargs={enable_thinking:!1}:y?i&&(O.extra_body={thinking_budget:parseInt(E[m]??"4096")}):a?O.chat_template_kwargs={enable_thinking:i}:R&&(O.reasoning_effort=v[m]||"medium");let P=0,re=6,de=!1,Q=process.env.NVIDIA_BASE_URL||"https://integrate.api.nvidia.com/v1/chat/completions",ke=process.env.NVIDIA_API_KEY&&process.env.NVIDIA_BASE_URL?process.env.NVIDIA_API_KEY:e;for(Q.endsWith("/chat/completions")||(Q=Q.replace(/\/+$/,"")+"/chat/completions");P<re;){P++;try{let ae=await Ze(Q,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${ke}`},body:JSON.stringify(O),signal:l});if(!ae.ok){let ye=await ae.text().catch(()=>""),Re=ae.statusText;try{let Ie=JSON.parse(ye);Re=Ie.error?.message||Ie.message||JSON.stringify(Ie.detail||Ie)}catch{ye&&(Re=ye)}let ve=new Error(`NVIDIA API Error (${ae.status}): ${Re}`);throw ve.status=ae.status,ve}let it=ae.body.getReader(),L=new TextDecoder,F="",Ee=[],oe=null,B=Date.now(),G=!1;for(;;){let{done:ye,value:Re}=await it.read();if(ye){G&&(Ee.length>0||oe)&&(yield{candidates:Ee.length>0?[{content:{parts:Ee}}]:[],usageMetadata:oe},de=!0);break}F+=L.decode(Re,{stream:!0});let ve=F.split(`
582
- `);F=ve.pop();let Ie=!1;for(let Dn of ve){let nn=Dn.trim();if(nn){if(nn==="data: [DONE]"){Ie=!0;break}if(nn.startsWith("data: ")){let pt;try{pt=JSON.parse(nn.substring(6))}catch{continue}if(pt.error)throw new Error(`NVIDIA Stream Error: ${pt.error.message||JSON.stringify(pt.error)}`);try{let kt=pt.usage;kt&&(oe={totalTokenCount:kt.total_tokens||kt.prompt_tokens+kt.completion_tokens,promptTokenCount:kt.prompt_tokens||0,candidatesTokenCount:kt.completion_tokens||0,cachedContentTokenCount:kt.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:(kt.completion_tokens_details?.reasoning_tokens||0)+(kt.completion_tokens_details?.thoughts_tokens||0)},G=!0);let Je=pt.choices?.[0]?.delta?.reasoning||pt.choices?.[0]?.delta?.reasoning_content||"",xe=pt.choices?.[0]?.delta?.content||"";Je&&(Ee.push({text:Je,thought:!0}),G=!0),xe&&(Ee.push({text:xe}),G=!0)}catch{}}}}if((Ie||Date.now()-B>=350)&&G&&(yield{candidates:Ee.length>0?[{content:{parts:[...Ee]}}]:[],usageMetadata:oe},de=!0,Ee=[],B=Date.now(),G=!1),Ie)break}break}catch(ae){if(de||P>=re)throw ae;await new Promise(it=>setTimeout(it,3500))}}},Fr=async function*(e,t){let n=[],s=null,o=!1,c=null,f=u=>{if(n.push(u),s){let w=s;s=null,w()}},l=t.split("/").pop(),k=Array.from(new Set([l,l.replace(/\./g,"-"),l.replace(/\./g,"_")])),g=["https://buildapi.ngc.nvidia.com/v2/predict/queues/models/qc69jvmznzxy","https://api.ngc.nvidia.com/v2/predict/queues/models/qc69jvmznzxy"].flatMap(u=>k.map(w=>`${u}/${w}`)),T=!1,m=null,i=async()=>{try{let w=await(await Promise.any(g.map(async I=>{let h=await fetch(I);if(!h.ok)throw new Error(`HTTP ${h.status}`);return h}))).json();if(w&&w.queues&&w.queues[0]&&typeof w.queues[0].queueDepth=="number"){let I=w.queues[0].queueDepth;T||f({value:{type:"status",content:`Queue ${I||1}`},done:!1})}}catch{}};process.env.NVIDIA_BASE_URL||(i(),m=setInterval(i,5e3)),(async()=>{try{let u=e[Symbol.asyncIterator]();for(;;){let{value:w,done:I}=await u.next();if(I)break;T=!0,m&&(clearInterval(m),m=null),f({value:w,done:!1})}o=!0,f(null)}catch(u){if(c=u,m&&(clearInterval(m),m=null),s){let w=s;s=null,w()}}})();try{for(;;){if(c)throw c;if(n.length>0){let u=n.shift();if(u===null&&o)break;yield u.value}else{if(o)break;await new Promise(u=>{s=u})}}}finally{m&&(clearInterval(m),m=null)}};var es=async function*(e,t,n,s,o,c,f,l,k=1,p=null){let g=[];s&&g.push({role:"system",content:[{type:"text",text:s}]});for(let E of n){let v=E.role==="user"?"user":"assistant",U=[];if(Array.isArray(E.parts)){for(let O of E.parts)if(O.text)U.push({type:"text",text:O.text});else if(O.inlineData&&f){let P=O.inlineData.mimeType,re=O.inlineData.data;P.startsWith("image/")?U.push({type:"image_url",image_url:{url:`data:${P};base64,${re}`}}):U.push({type:"file",file:{filename:O.filename||"file",file_data:`data:${P};base64,${re}`}})}}else{let O=E.text||"";O&&U.push({type:"text",text:O})}g.push({role:v,content:U.length===1&&U[0].type==="text"?U[0].text:U})}let T={Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},m=["free","nitro","floor","exacto"],i=t,u=null,w=null;if(t.includes(":")){let E=t.split(":");if(E.length>1){let v=E[E.length-1].toLowerCase().trim();(v==="flex"||v==="priority")&&(w=v,E.pop())}if(E.length>1){let v=E[E.length-1].toLowerCase().trim();if(!m.includes(v)){let U=E.pop().trim();U&&(u={only:[U],allow_fallbacks:!1})}}i=E.join(":").trim()}let I=`${e.slice(-5)}${p||""}${o}${i}${w||""}${u?JSON.stringify(u):""}`,h=await Xo(I),A={model:i,messages:g,stream:!0,temperature:k,cache_control:{type:"ephemeral"},tools:[],tool_choice:"none",session_id:h};w&&(A.service_tier=w),u&&(A.provider=u);let $=He("OpenRouter",t,o),C=$!==null?$:T[o];C&&C!=="none"&&($!==null||o!=="Fast")&&(A.reasoning_effort=C);let x=await Ze("https://openrouter.ai/api/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json","HTTP-Referer":"https://fluxflow-cli.onrender.com/","X-Title":"FluxFlow CLI","X-OpenRouter-Title":"FluxFlow CLI","X-Cache":"true","X-OpenRouter-Cache":"true"},body:JSON.stringify(A),signal:l});if(!x.ok){let E=await x.json().catch(()=>({})),v=E.error?.metadata?.raw||E.error?.message||(typeof E.error=="string"?E.error:"")||x.statusText||"Unknown error";throw new Error(`OpenRouter Error (${x.status}): ${v}`)}let _=x.body.getReader(),M=new TextDecoder,y="",a=[],R=null,d=Date.now(),r=!1;for(;;){let{done:E,value:v}=await _.read();if(E){r&&(a.length>0||R)&&(yield{candidates:a.length>0?[{content:{parts:a}}]:[],usageMetadata:R});break}y+=M.decode(v,{stream:!0});let U=y.split(`
583
- `);y=U.pop();for(let O of U){let P=O.trim();if(!P||!P.startsWith("data: "))continue;let re=!1;if(P==="data: [DONE]")re=!0;else try{let de=JSON.parse(P.substring(6));if(de.error){let ae=de.error.metadata?.raw||de.error.message||JSON.stringify(de.error);throw new Error(`OpenRouter Stream Error: ${ae}`)}let Q=de.choices?.[0]?.delta,ke=de.usage;if(de.choices?.[0]?.finish_reason&&(re=!0),ke&&(R={totalTokenCount:ke.total_tokens||(ke.prompt_tokens||0)+(ke.completion_tokens||0),promptTokenCount:ke.prompt_tokens||0,candidatesTokenCount:ke.completion_tokens||0,cachedContentTokenCount:ke.prompt_tokens_details?.cached_tokens||ke.prompt_tokens_details?.cache_read_input_tokens||ke.cache_read_input_tokens||0,thoughtsTokenCount:ke.completion_tokens_details?.reasoning_tokens||0},r=!0),Q){let ae=Q.reasoning||(Q.reasoning_details?Q.reasoning_details.map(it=>it.text).join(""):null);ae&&(a.push({text:ae,thought:!0}),r=!0),Q.content&&(a.push({text:Q.content}),r=!0)}}catch(de){if(de.message&&de.message.startsWith("OpenRouter Stream Error:"))throw de}if((re||Date.now()-d>=150)&&r&&(yield{candidates:a.length>0?[{content:{parts:[...a]}}]:[],usageMetadata:R},a=[],d=Date.now(),r=!1),re)break}}};import{Ollama as Oa}from"ollama";var ei=async function*(e,t,n,s,o,c,f,l,k=1,p="Cloud"){let g=[];s&&g.push({role:"system",content:s});for(let y of n){let a=y.role==="user"?"user":"assistant",R="",d=[];if(Array.isArray(y.parts)){R=y.parts.map(r=>r.text||"").filter(Boolean).join(`
584
- `);for(let r of y.parts){let E=r.inlineData||r.inline_data;E&&E.data&&d.push(E.data)}}else R=y.text||"";if(R||d.length>0){let r={role:a,content:R};d.length>0&&(r.images=d),g.push(r)}}let T=p==="Local"||!e||e==="LOCAL",i={host:T?process.env.OLLAMA_HOST||"http://127.0.0.1:11434":process.env.OLLAMA_HOST||"https://ollama.com"};!T&&e&&(i.headers={Authorization:"Bearer "+e});let u=new Oa(i),w=[],I=null,h=Date.now(),A=!1,$=He("Ollama",t,o),C={Fast:!1,Low:"medium",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},x=$!==null?$==="false"||$===!1?!1:$==="true"||$===!0?!0:$:C[o]!==void 0?C[o]:!0,_={model:t,messages:g,stream:!0,think:x,keep_alive:"10m",tools:[],tool_choice:"none",options:{temperature:k}},M=await u.chat(_);for await(let y of M){if(l?.aborted)throw new DOMException("The user aborted a request.","AbortError");if(y.message?.thinking&&(w.push({text:y.message.thinking,thought:!0}),A=!0),y.message?.content&&(w.push({text:y.message.content}),A=!0),y.done){let a=y.prompt_cached_count||0;if(!a&&y.prompt_eval_count){let R=y.prompt_eval_duration||0;R>0&&R<5e7&&(a=y.prompt_eval_count)}I={totalTokenCount:(y.prompt_eval_count||0)+(y.eval_count||0),promptTokenCount:y.prompt_eval_count||0,candidatesTokenCount:y.eval_count||0,cachedContentTokenCount:a,thoughtsTokenCount:0},A=!0}(y.done||Date.now()-h>=150&&A)&&(yield{candidates:w.length>0?[{content:{parts:[...w]}}]:[],usageMetadata:I},w=[],h=Date.now(),A=!1)}A&&(w.length>0||I)&&(yield{candidates:w.length>0?[{content:{parts:[...w]}}]:[],usageMetadata:I})};var ts=async function*(e,t,n,s,o,c,f,l,k=1){let p=[];s&&p.push({role:"system",content:s});for(let a of n){let R=a.role==="user"?"user":"assistant",d="";if(Array.isArray(a.parts))for(let r of a.parts)r.text&&(d+=(d?`
585
- `:"")+r.text);else d=a.text||"";p.push({role:R,content:d})}let g=He("InferX",t,o),m=g!==null?g:{Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i=t&&t.toLowerCase().includes("qwen3.8-27b")&&g===null,u=t&&(t.toLowerCase().includes("qwen3.8-27b")||t.toLowerCase().includes("qwen3.6-35b-a3b-fp8")),w={model:t,messages:p.filter(a=>a.content&&String(a.content).trim().length>0),stream:!0,stream_options:{include_usage:!0},temperature:k,tools:[],tool_choice:"none"};!i&&m&&(w.stream_options={include_usage:!0},w.reasoning_effort=m);let I=await Ze("https://model.inferx.net/endpoints/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(w),signal:l});if(!I.ok){let a=await I.text().catch(()=>""),R="";try{let d=JSON.parse(a);R=d.error?.message||d.error?.detail||d.message||d.detail||(typeof d.error=="string"?d.error:"")||(a&&a!=="{}"?a:"")}catch{R=a}throw(!R||R==="{}")&&(R=I.statusText||"Unknown error"),new Error(`InferX Error (${I.status}): ${R}`)}let h=I.body.getReader(),A=new TextDecoder,$="",C=[],x=null,_=Date.now(),M=!1,y=!0;for(;;){let{done:a,value:R}=await h.read();if(a){M&&(C.length>0||x)&&(yield{candidates:C.length>0?[{content:{parts:C}}]:[],usageMetadata:x});break}$+=A.decode(R,{stream:!0});let d=$.split(`
586
- `);$=d.pop();for(let r of d){let E=r.trim();if(!E||!E.startsWith("data: "))continue;let v=!1;if(E==="data: [DONE]")v=!0;else try{let U=JSON.parse(E.substring(6)),O=U.choices?.[0]?.delta,P=U.usage;if(P&&(x={totalTokenCount:P.total_tokens||(P.prompt_tokens||0)+(P.completion_tokens||0),promptTokenCount:P.prompt_tokens||0,candidatesTokenCount:P.completion_tokens||0,cachedContentTokenCount:P.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:P.completion_tokens_details?.reasoning_tokens||P.reasoning_tokens||0},M=!0),O){let re=O.reasoning||O.reasoning_content||null;if(re&&(C.push({text:re,thought:!0}),M=!0),O.content){let de=O.content;u&&y&&de.length>0&&(de="<think>"+de,y=!1),C.push({text:de}),M=!0}}}catch{}if((v||Date.now()-_>=150||x)&&M&&(yield{candidates:C.length>0?[{content:{parts:[...C]}}]:[],usageMetadata:x},C=[],_=Date.now(),M=!1),v)break}Date.now()-_>=150&&M&&(yield{candidates:C.length>0?[{content:{parts:[...C]}}]:[],usageMetadata:x},C=[],_=Date.now(),M=!1)}};var ns=async function*(e,t,n,s,o,c,f,l,k=1){let p=[];s&&p.push({role:"system",content:s});for(let _ of n){let M=_.role==="user"?"user":"assistant",y=[];if(Array.isArray(_.parts)){for(let a of _.parts)if(a.text)y.push({type:"text",text:a.text});else if(a.inlineData&&f){let R=a.inlineData.mimeType,d=a.inlineData.data;R.startsWith("image/")&&y.push({type:"image_url",image_url:{url:`data:${R};base64,${d}`}})}}else{let a=_.text||"";a&&y.push({type:"text",text:a})}p.push({role:M,content:y.length===1&&y[0].type==="text"?y[0].text:y})}let g=He("SenseNova",t,o),m=g!==null?g:{Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:p,stream:!0,stream_options:{include_usage:!0},temperature:k,tools:[],tool_choice:"none"};m&&(i.reasoning_effort=m);let u=await Ze("https://token.sensenova.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(i),signal:l});if(!u.ok){let _=await u.json().catch(()=>({}));throw new Error(`SenseNova Error (${u.status}): ${_.error?.message||u.statusText}`)}let w=u.body.getReader(),I=new TextDecoder,h="",A=[],$=null,C=Date.now(),x=!1;for(;;){let{done:_,value:M}=await w.read();if(_){x&&(A.length>0||$)&&(yield{candidates:A.length>0?[{content:{parts:A}}]:[],usageMetadata:$});break}h+=I.decode(M,{stream:!0});let y=h.split(`
587
- `);h=y.pop();for(let a of y){let R=a.trim();if(!R||!R.startsWith("data: "))continue;let d=!1;if(R==="data: [DONE]")d=!0;else try{let r=JSON.parse(R.substring(6)),E=r.choices?.[0]?.delta,v=r.usage;if(v&&($={totalTokenCount:v.total_tokens||(v.prompt_tokens||0)+(v.completion_tokens||0),promptTokenCount:v.prompt_tokens||0,candidatesTokenCount:v.completion_tokens||0,cachedContentTokenCount:v.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:v.completion_tokens_details?.reasoning_tokens||v.reasoning_tokens||0},x=!0),E){let U=E.reasoning||E.reasoning_content||null;U&&(A.push({text:U,thought:!0}),x=!0),E.content&&(A.push({text:E.content}),x=!0)}}catch{}if((d||Date.now()-C>=150||$)&&x&&(yield{candidates:A.length>0?[{content:{parts:[...A]}}]:[],usageMetadata:$},A=[],C=Date.now(),x=!1),d)break}Date.now()-C>=150&&x&&(yield{candidates:A.length>0?[{content:{parts:[...A]}}]:[],usageMetadata:$},A=[],C=Date.now(),x=!1)}};var os=async function*(e,t,n,s,o,c,f,l,k=1){let p=[];s&&p.push({role:"system",content:s});for(let _ of n){let M=_.role==="user"?"user":"assistant",y=[];if(Array.isArray(_.parts)){for(let a of _.parts)if(a.text)y.push({type:"text",text:a.text});else if(a.inlineData&&f){let R=a.inlineData.mimeType,d=a.inlineData.data;R.startsWith("image/")&&y.push({type:"image_url",image_url:{url:`data:${R};base64,${d}`}})}}else{let a=_.text||"";a&&y.push({type:"text",text:a})}p.push({role:M,content:y.length===1&&y[0].type==="text"?y[0].text:y})}let g=He("AIHubMix",t,o),m=g!==null?g:{Fast:"minimal",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:p,stream:!0,stream_options:{include_usage:!0},temperature:k,tools:[],tool_choice:"none"};m&&(i.reasoning_effort=m);let u=await Ze("https://aihubmix.com/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(i),signal:l});if(!u.ok){let _=await u.json().catch(()=>({}));throw new Error(`AIHubMix Error (${u.status}): ${_.error?.message||u.statusText}`)}let w=u.body.getReader(),I=new TextDecoder,h="",A=[],$=null,C=Date.now(),x=!1;for(;;){let{done:_,value:M}=await w.read();if(_){x&&(A.length>0||$)&&(yield{candidates:A.length>0?[{content:{parts:A}}]:[],usageMetadata:$});break}h+=I.decode(M,{stream:!0});let y=h.split(`
588
- `);h=y.pop();for(let a of y){let R=a.trim();if(!R||!R.startsWith("data: "))continue;let d=!1;if(R==="data: [DONE]")d=!0;else try{let r=JSON.parse(R.substring(6)),E=r.choices?.[0]?.delta,v=r.usage;if(r.choices?.[0]?.finish_reason&&(d=!0),v&&($={totalTokenCount:v.total_tokens||(v.prompt_tokens||0)+(v.completion_tokens||0),promptTokenCount:v.prompt_tokens||0,candidatesTokenCount:v.completion_tokens||0,cachedContentTokenCount:v.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:v.completion_tokens_details?.reasoning_tokens||v.reasoning_tokens||0},x=!0),E){let U=E.reasoning_content||null;U&&(A.push({text:U,thought:!0}),x=!0),E.content&&(A.push({text:E.content}),x=!0)}}catch{}if((d||Date.now()-C>=150)&&x&&(yield{candidates:A.length>0?[{content:{parts:[...A]}}]:[],usageMetadata:$},A=[],C=Date.now(),x=!1),d)break}Date.now()-C>=150&&x&&(yield{candidates:A.length>0?[{content:{parts:[...A]}}]:[],usageMetadata:$},A=[],C=Date.now(),x=!1)}};var ss=async function*(e,t,n,s,o,c,f,l,k=1){let p=[];s&&p.push({role:"system",content:s});for(let x of n){let _=x.role==="user"?"user":"assistant",M=[];if(Array.isArray(x.parts)){for(let y of x.parts)if(y.text)M.push({type:"text",text:y.text});else if(y.inlineData&&f){let a=y.inlineData.mimeType,R=y.inlineData.data;a.startsWith("image/")&&M.push({type:"image_url",image_url:{url:`data:${a};base64,${R}`}})}}else{let y=x.text||"";y&&M.push({type:"text",text:y})}p.push({role:_,content:M.length===1&&M[0].type==="text"?M[0].text:M})}let g=He("Poolside",t,o),T=g!==null?g===!1||g==="false"||g==="none"||g==="Fast":o==="Fast",m={model:t,messages:p,stream:!0,stream_options:{include_usage:!0},temperature:k,tools:[],tool_choice:"none"};T?m.chat_template_kwargs={enable_thinking:!1}:g!==null&&typeof g=="object"?m.chat_template_kwargs=g:m.chat_template_kwargs={enable_thinking:!0};let i=await Ze("https://inference.poolside.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(m),signal:l});if(!i.ok){let x=await i.json().catch(()=>({}));throw new Error(`Poolside Error (${i.status}): ${x.error?.message||i.statusText}`)}let u=i.body.getReader(),w=new TextDecoder,I="",h=[],A=null,$=Date.now(),C=!1;for(;;){let{done:x,value:_}=await u.read();if(x){C&&(h.length>0||A)&&(yield{candidates:h.length>0?[{content:{parts:h}}]:[],usageMetadata:A});break}I+=w.decode(_,{stream:!0});let M=I.split(`
589
- `);I=M.pop();for(let y of M){let a=y.trim();if(!a||!a.startsWith("data: "))continue;let R=!1;if(a==="data: [DONE]")R=!0;else try{let d=JSON.parse(a.substring(6)),r=d.choices?.[0]?.delta,E=d.usage;if(d.choices?.[0]?.finish_reason&&(R=!0),E&&(A={totalTokenCount:E.total_tokens||(E.prompt_tokens||0)+(E.completion_tokens||0),promptTokenCount:E.prompt_tokens||0,candidatesTokenCount:E.completion_tokens||0,cachedContentTokenCount:E.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:E.completion_tokens_details?.reasoning_tokens||E.reasoning_tokens||0},C=!0),r){let v=r.reasoning_content||r.reasoning||null;v&&(h.push({text:v,thought:!0}),C=!0),r.content&&(h.push({text:r.content}),C=!0)}}catch{}if((R||Date.now()-$>=150)&&C&&(yield{candidates:h.length>0?[{content:{parts:[...h]}}]:[],usageMetadata:A},h=[],$=Date.now(),C=!1),R)break}Date.now()-$>=150&&C&&(yield{candidates:h.length>0?[{content:{parts:[...h]}}]:[],usageMetadata:A},h=[],$=Date.now(),C=!1)}};var is=async function*(e,t,n,s,o,c,f,l,k=1){let p=[];s&&p.push({role:"system",content:s});for(let a of n){let R=a.role==="user"?"user":"assistant",d=[];if(Array.isArray(a.parts)){for(let r of a.parts)if(r.text)d.push({type:"text",text:r.text});else if(r.inlineData&&f){let E=r.inlineData.mimeType,v=r.inlineData.data;E.startsWith("image/")&&d.push({type:"image_url",image_url:{url:`data:${E};base64,${v}`}})}}else{let r=a.text||"";r&&d.push({type:"text",text:r})}p.push({role:R,content:d.length===1&&d[0].type==="text"?d[0].text:d})}let g=He("9router",t,o)||He("9Router",t,o),m=g!==null?g:{Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:p,stream:!0,stream_options:{include_usage:!0},temperature:k,tools:[],tool_choice:"none"};m&&m!=="none"&&(g!==null||o!=="Fast")&&(i.reasoning_effort=m);let u=process.env["9ROUTER_URL"]||process.env.NINEROUTER_URL||"http://127.0.0.1:20128/v1/chat/completions",w={"Content-Type":"application/json"},I=e&&e!=="LOCAL"?e:process.env.NINEROUTER_KEY||"dummy-key";w.Authorization=`Bearer ${I}`;let h=await Ze(u,{method:"POST",headers:w,body:JSON.stringify(i),signal:l});if(!h.ok){let a=await h.json().catch(()=>({}));throw new Error(`9router Error (${h.status}): ${a.error?.message||h.statusText}`)}let A=h.body.getReader(),$=new TextDecoder,C="",x=[],_=null,M=Date.now(),y=!1;for(;;){let{done:a,value:R}=await A.read();if(a){y&&(x.length>0||_)&&(yield{candidates:x.length>0?[{content:{parts:x}}]:[],usageMetadata:_});break}C+=$.decode(R,{stream:!0});let d=C.split(`
590
- `);C=d.pop();for(let r of d){let E=r.trim();if(!E||!E.startsWith("data: "))continue;let v=!1;if(E==="data: [DONE]")v=!0;else try{let U=JSON.parse(E.substring(6)),O=U.choices?.[0]?.delta,P=U.usage;if(U.choices?.[0]?.finish_reason&&(v=!0),P&&(_={totalTokenCount:P.total_tokens||(P.prompt_tokens||0)+(P.completion_tokens||0),promptTokenCount:P.prompt_tokens||0,candidatesTokenCount:P.completion_tokens||0,cachedContentTokenCount:P.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:P.completion_tokens_details?.reasoning_tokens||P.reasoning_tokens||0},y=!0),O){let re=O.reasoning_content||O.reasoning||O.thinking||null;!re&&Array.isArray(O.reasoning_details)&&O.reasoning_details.length>0&&(re=O.reasoning_details.map(de=>typeof de=="string"?de:de?.text||"").filter(Boolean).join("")),re&&(x.push({text:re,thought:!0}),y=!0),O.content&&(x.push({text:O.content}),y=!0)}}catch{}if((v||Date.now()-M>=150)&&y&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:_},x=[],M=Date.now(),y=!1),v)break}Date.now()-M>=150&&y&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:_},x=[],M=Date.now(),y=!1)}};var rs=async function*(e,t,n,s,o,c,f,l,k=1){let p=[];s&&p.push({role:"system",content:s});for(let a of n){let R=a.role==="user"?"user":"assistant",d=[];if(Array.isArray(a.parts)){for(let r of a.parts)if(r.text)d.push({type:"text",text:r.text});else if(r.inlineData&&f){let E=r.inlineData.mimeType,v=r.inlineData.data;E.startsWith("image/")&&d.push({type:"image_url",image_url:{url:`data:${E};base64,${v}`}})}}else{let r=a.text||"";r&&d.push({type:"text",text:r})}p.push({role:R,content:d.length===1&&d[0].type==="text"?d[0].text:d})}let g=He("ExpLabs",t,o),m=g!==null?g:{Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:p,stream:!0,stream_options:{include_usage:!0},temperature:k,tools:[],tool_choice:"none"};m&&(i.reasoning_effort=m);let u=process.env.EXPLABS_URL||process.env.EXPERIENTIALLABS_URL||"https://api.experientiallabs.ai/v1/chat/completions",w={"Content-Type":"application/json"},I=e||process.env.EXPLABS_API_KEY||process.env.EXPERIENTIALLABS_API_KEY||"";w.Authorization=`Bearer ${I}`;let h=await Ze(u,{method:"POST",headers:w,body:JSON.stringify(i),signal:l});if(!h.ok){let a=await h.json().catch(()=>({}));throw new Error(`Experiential Labs Error (${h.status}): ${a.error?.message||a.message||h.statusText}`)}let A=h.body.getReader(),$=new TextDecoder,C="",x=[],_=null,M=Date.now(),y=!1;for(;;){let{done:a,value:R}=await A.read();if(a){y&&(x.length>0||_)&&(yield{candidates:x.length>0?[{content:{parts:x}}]:[],usageMetadata:_});break}C+=$.decode(R,{stream:!0});let d=C.split(`
591
- `);C=d.pop();for(let r of d){let E=r.trim();if(!E||!E.startsWith("data: "))continue;let v=!1;if(E==="data: [DONE]")v=!0;else try{let U=JSON.parse(E.substring(6)),O=U.choices?.[0]?.delta,P=U.usage;if(P&&(_={totalTokenCount:P.total_tokens||(P.prompt_tokens||0)+(P.completion_tokens||0),promptTokenCount:P.prompt_tokens||0,candidatesTokenCount:P.completion_tokens||0,cachedContentTokenCount:P.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:P.completion_tokens_details?.reasoning_tokens||P.reasoning_tokens||0},y=!0),O){let re=O.reasoning_content||O.reasoning||null;!re&&Array.isArray(O.reasoning_details)&&O.reasoning_details.length>0&&(re=O.reasoning_details.map(de=>de.text||"").filter(Boolean).join("")),re&&(x.push({text:re,thought:!0}),y=!0),O.content&&(x.push({text:O.content}),y=!0)}}catch{}if((v||Date.now()-M>=150)&&y&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:_},x=[],M=Date.now(),y=!1),v)break}Date.now()-M>=150&&y&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:_},x=[],M=Date.now(),y=!1)}};var ti=async function*(e,t,n,s,o,c,f,l,k=1){let p=[];s&&p.push({role:"system",content:s});for(let a of n){let R=a.role==="user"?"user":"assistant",d=[];if(Array.isArray(a.parts)){for(let r of a.parts)if(r.text)d.push({type:"text",text:r.text});else if(r.inlineData&&f){let E=r.inlineData.mimeType,v=r.inlineData.data;E.startsWith("image/")&&d.push({type:"image_url",image_url:{url:`data:${E};base64,${v}`}})}}else{let r=a.text||"";r&&d.push({type:"text",text:r})}p.push({role:R,content:d.length===1&&d[0].type==="text"?d[0].text:d})}let g=He("TokenHarbor",t,o),m=g!==null?g:{Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:p,stream:!0,stream_options:{include_usage:!0},temperature:k,tools:[],tool_choice:"none"};m&&(i.reasoning_effort=m);let u=process.env.TOKENHARBOR_URL||process.env.TOKEN_HARBOR_URL||"https://tokenharbor.ai/v1/chat/completions",w={"Content-Type":"application/json","X-Title":"Flux-Flow","User-Agent":"Flux-Flow","HTTP-Referer":"https://fluxflow-cli.onrender.com/"},I=e||process.env.TOKENHARBOR_API_KEY||process.env.TOKEN_HARBOR_API_KEY||"";w.Authorization=`Bearer ${I}`;let h=await Ze(u,{method:"POST",headers:w,body:JSON.stringify(i),signal:l});if(!h.ok){let a=await h.json().catch(()=>({}));throw new Error(`Token Harbor Error (${h.status}): ${a.error?.message||a.message||h.statusText}`)}let A=h.body.getReader(),$=new TextDecoder,C="",x=[],_=null,M=Date.now(),y=!1;for(;;){let{done:a,value:R}=await A.read();if(a){y&&(x.length>0||_)&&(yield{candidates:x.length>0?[{content:{parts:x}}]:[],usageMetadata:_});break}C+=$.decode(R,{stream:!0});let d=C.split(`
592
- `);C=d.pop();for(let r of d){let E=r.trim();if(!E||!E.startsWith("data: "))continue;let v=!1;if(E==="data: [DONE]")v=!0;else try{let U=JSON.parse(E.substring(6)),O=U.choices?.[0]?.delta,P=U.usage;if(P&&(_={totalTokenCount:P.total_tokens||(P.prompt_tokens||0)+(P.completion_tokens||0),promptTokenCount:P.prompt_tokens||0,candidatesTokenCount:P.completion_tokens||0,cachedContentTokenCount:P.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:P.completion_tokens_details?.reasoning_tokens||P.reasoning_tokens||0},y=!0),O){let re=O.reasoning_content||O.reasoning||null;!re&&Array.isArray(O.reasoning_details)&&O.reasoning_details.length>0&&(re=O.reasoning_details.map(de=>de.text||"").filter(Boolean).join("")),re&&(x.push({text:re,thought:!0}),y=!0),O.content&&(x.push({text:O.content}),y=!0)}}catch{}if((v||Date.now()-M>=150)&&y&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:_},x=[],M=Date.now(),y=!1),v)break}Date.now()-M>=150&&y&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:_},x=[],M=Date.now(),y=!1)}};var ni=async function*(e,t,n,s,o,c,f,l,k=1){let p=[];s&&p.push({role:"system",content:s});for(let a of n){let R=a.role==="user"?"user":"assistant",d=[];if(Array.isArray(a.parts)){for(let r of a.parts)if(r.text)d.push({type:"text",text:r.text});else if(r.inlineData&&f){let E=r.inlineData.mimeType,v=r.inlineData.data;E.startsWith("image/")&&d.push({type:"image_url",image_url:{url:`data:${E};base64,${v}`}})}}else{let r=a.text||"";r&&d.push({type:"text",text:r})}p.push({role:R,content:d.length===1&&d[0].type==="text"?d[0].text:d})}let g=He("APInex",t,o),m=g!==null?g:{Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:p,stream:!0,stream_options:{include_usage:!0},temperature:k,tools:[],tool_choice:"none"};m&&(i.reasoning_effort=m);let u=process.env.APINEX_URL||"https://api.apinex.bond/v1/chat/completions",w={"Content-Type":"application/json","X-Title":"Flux-Flow","User-Agent":"Flux-Flow","HTTP-Referer":"https://fluxflow-cli.onrender.com/"},I=e||process.env.APINEX_API_KEY||"";w.Authorization=`Bearer ${I}`;let h=await Ze(u,{method:"POST",headers:w,body:JSON.stringify(i),signal:l});if(!h.ok){let a=await h.json().catch(()=>({}));throw new Error(`APInex Error (${h.status}): ${a.error?.message||a.message||h.statusText}`)}let A=h.body.getReader(),$=new TextDecoder,C="",x=[],_=null,M=Date.now(),y=!1;for(;;){let{done:a,value:R}=await A.read();if(a){y&&(x.length>0||_)&&(yield{candidates:x.length>0?[{content:{parts:x}}]:[],usageMetadata:_});break}C+=$.decode(R,{stream:!0});let d=C.split(`
593
- `);C=d.pop();for(let r of d){let E=r.trim();if(!E||!E.startsWith("data: "))continue;let v=!1;if(E==="data: [DONE]")v=!0;else try{let U=JSON.parse(E.substring(6)),O=U.choices?.[0]?.delta,P=U.usage;if(P&&(_={totalTokenCount:P.total_tokens||(P.prompt_tokens||0)+(P.completion_tokens||0),promptTokenCount:P.prompt_tokens||0,candidatesTokenCount:P.completion_tokens||0,cachedContentTokenCount:P.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:P.completion_tokens_details?.reasoning_tokens||P.reasoning_tokens||0},y=!0),O){let re=O.reasoning_content||O.reasoning||null;!re&&Array.isArray(O.reasoning_details)&&O.reasoning_details.length>0&&(re=O.reasoning_details.map(de=>de.text||"").filter(Boolean).join("")),re&&(x.push({text:re,thought:!0}),y=!0),O.content&&(x.push({text:O.content}),y=!0)}}catch{}if((v||Date.now()-M>=150)&&y&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:_},x=[],M=Date.now(),y=!1),v)break}Date.now()-M>=150&&y&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:_},x=[],M=Date.now(),y=!1)}};var La=/```[\s\S]*?```/g,Pa=/```[\s\S]*$/g,$a=/`[^`]+`/g,Na=/^\|.*\|$/gm,Fa=/^[^\w]+|[^\w]+$/g,Ba=/[^a-z0-9]/gi,wo=/\[\s*(?:tool|action):(?:functions\.)?([a-z0-9_]+)\s*\(/gi,Ua=/\[\s*(?:tool:(?:functions\.)?|action:(?:functions\.)?|action:)([a-z0-9_]+)\s*\(/gi,Wa=/(?:path|targetFile|TargetFile|directory|keyword|id|taskId|title|task)\s*=\s*\\?["']?([^\\"' \),]+)/,Gn=/["']/g,Br=/\\/g,Ha=/<\|channel>thought/gi,Ga=/<channel\|>/gi,ja=e=>typeof e!="string"?e:e.replace(Ha,"<think>").replace(Ga,"</think>"),cf=/^\s*(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\]|$)/i,Ka=(e,t,n=1)=>{let s=t>0?e[t-1]:"",o=t+n<e.length?e[t+n]:"";return s==="`"&&o==="`"},Va=e=>{let t=/(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\])/gi,n;for(;(n=t.exec(e))!==null;)if(!Ka(e,n.index,n[0].length))return{index:n.index,length:n[0].length};return{index:-1,length:0}},oi=e=>{if(!e||typeof e!="string")return null;let t=e.match(/^\s*(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought|\[(think|thought|thoughts)\])/i);if(!t)return null;let n=t.index+t[0].length,s=e.substring(n),o=Va(s);if(o.index!==-1){let c=n+o.index+o.length;return{fullBlock:e.substring(0,c),innerContent:s.substring(0,o.index),remainingText:e.substring(c)}}return{fullBlock:e,innerContent:s,remainingText:""}},qt=e=>{if(!e||typeof e!="string")return e;let t=oi(e);return t?t.remainingText.trimStart():e};var Vr=/`[^`]*`/g,Yr=/`[^`]*$/,Ur=/<\|\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,Ya=/"([^"]+)"\s*:\s*(?:"([^"]*)"|(\d+)|true|false|null)/g,Wr=/<\|\s*tool_calls_section_begin\s*\|>/gi,Hr=/<\|\s*tool_calls_section_end\s*\|>/gi,qa=/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi;var Gr=e=>!e||typeof e!="string"?e:e.replace(/(```[\s\S]*?```|`[^`]*`)|(<(?:\w+)(?:[^>]*)>\r?\n?|\r?\n?<\/\w+(?:[^>]*)>)/gi,(t,n)=>n||""),qr=e=>{if(!e||typeof e!="string")return e;let t=ko(e);if(!t||t.length===0)return e;let n=t[t.length-1];if(!n.fullMatch)return e;let s=e.lastIndexOf(n.fullMatch);if(s===-1)return e;let o=s+n.fullMatch.length;return e.substring(0,o).trimEnd()},ii=null,as={},jn={key:null,value:null},Yt=e=>e&&e.replace(/(?:(\x1b\[\d+m))?([✔✘✖🔍📖→➕↻↷•🛇])(?:(\x1b\[\d+m))?\s*\b(Clicked|Located|Dragged|Scrolled|Typed|Pressed Key|Recaptured Screen|Created|Read Skill|Read Documentation|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|Execution Error|Loop Detected|Contacting Ancestors)\b/ig,(t,n,s,o,c)=>`${n||""}${s}${o||""} \x1B[95m${c}\x1B[0m`),za=async(e,t=8,n=1e3,s=8e3,o=null)=>{let c=0;for(;;){if(o?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{return await e()}catch(f){if(o?.aborted||f?.name==="AbortError"||f?.message==="Subagent task was cancelled."||(c++,c>=t))throw f;let l=Math.min(n*Math.pow(2,c-1),s);await new Promise((k,p)=>{let g=setTimeout(k,l);o&&o.addEventListener("abort",()=>{clearTimeout(g),p(new DOMException("The user aborted a request.","AbortError"))})})}}},wt=!1;var Xa=e=>{let t=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,c,f)=>{let l=o.fullText||o.text||"";if(o.role==="user"&&c<f.length-1)if(l.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")){let k=l.indexOf("**CONTEXT SUMMARY OF PREVIOUS TURNS");if(k!==-1){let g=l.substring(0,k).lastIndexOf("[SYSTEM METADATA]");g!==-1?l=l.substring(g).trim():l=l.substring(k).trim()}}else{let k=l.lastIndexOf("[USER]"),p=l.lastIndexOf("[USER PROMPT]");k!==-1?l=l.substring(k+6).trim():p!==-1&&(l=l.substring(p).trim())}return{...o,text:l}}),n=[],s=0;for(;s<t.length;){let o=t[s];if(o.role==="user")n.push(o),s++;else{let c=[];for(;s<t.length&&t[s].role!=="user";)c.push(t[s]),s++;let f=[],l=[],k=!1,p=()=>{f.length>0&&(n.push({role:"agent",text:"combined"}),f=[]),l.length>0&&(n.push({role:"system",text:"combined"}),l=[]),k=!1};c.forEach(g=>{let T=g.role==="system"&&(g.text?.startsWith("[ACTION RESULT]")||g.text?.startsWith("[TOOL RESULT]")||g.text?.startsWith("SUCCESS:")||g.text?.startsWith("ERROR:")||g.fullText?.startsWith("[ACTION RESULT]")||g.fullText?.startsWith("[TOOL RESULT]")||g.fullText?.startsWith("SUCCESS:")||g.fullText?.startsWith("ERROR:")),m=g.fullText||g.text||"",i=m.trim();if(!(!i&&!g.binaryPart)){if(T)l.push(i);else if(g.role==="agent"){!k&&l.length>0&&p();let u=m.endsWith(`
594
- `),w=i.toLowerCase().includes("tool:")||i.toLowerCase().includes("action:");f.push(i),w&&u?k=!0:k=!1}}}),p()}}return n.length},Ja=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),df=()=>{wt=!0},ff=()=>wt,si={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",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"},Kn=(e,t)=>{try{let n=ne(t),s=e.toLowerCase().replace(/_/g,"");if(s==="invokesync"||s==="invoke")return n.title||(n.task?n.task.substring(0,30):null);if(s==="getprogress"||s==="cancel"||s==="steer"||s==="steersubagent")return n.id||n.taskId;let o=n.name||n.path||n.targetFile||n.TargetFile||n.directory||n.file||n.query;return o?ie.basename(o.replace(/["']/g,"").replace(/\\/g,"/")):null}catch{return null}},ri=e=>e?new Kr({apiKey:e}):ii,uf=async(e,t,n,s,o={})=>{let{onStatus:l,onMemoryUpdated:k,onBackgroundIncrement:p}=o,{profile:g,thinkingLevel:T,mode:m,janitorModel:i,chatId:u,systemSettings:w,sessionStats:I,aiProvider:h="Google",apiKey:A}=e,$=process.env.NVIDIA_BASE_URL||h==="Ollama"||h==="InferX"||h==="SenseNova"||h==="AIHubMix"||h==="Poolside"||h==="9router"||h==="ExpLabs"||h==="ExperientialLabs"?!1:w?.memory!==!1,x=Ct(Wn,[]).map(L=>`- [${L.id}]: ${L.memory}`).join(`
578
+ `}),k};var Ze=async(e,t,n=5,s=1e3)=>{let o=t?.signal;for(let f=0;f<n;f++){if(o?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{let l=await fetch(e,t);if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),l.ok||l.status!==429&&l.status<500)return l}catch(l){if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),l.name==="AbortError"||o?.aborted||f===n-1)throw l}o?await new Promise((l,k)=>{let m=setTimeout(()=>{o.removeEventListener("abort",g),l()},Math.min(24e3,s*Math.pow(2,f))),g=()=>{clearTimeout(m),k(new DOMException("The user aborted a request.","AbortError"))};o.addEventListener("abort",g)}):await new Promise(l=>setTimeout(l,Math.min(24e3,s*Math.pow(2,f))))}if(o?.aborted)throw new DOMException("The user aborted a request.","AbortError");let c=await fetch(e,t);return typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),c};async function Xo(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",t);return[...new Uint8Array(n).slice(0,16)].map(s=>s.toString(16).padStart(2,"0")).join("")}var xn=e=>typeof e!="string"?e:e.replace(/<\|channel>thought/gi,"<think>").replace(/<channel\|>/gi,"</think>");var Jo=async function*(e,t,n,s,o,c,f,l,k=1){let m=[];s&&m.push({role:"system",content:s});for(let _ of n){let M=_.role==="user"?"user":"assistant",y=[];if(Array.isArray(_.parts)){for(let a of _.parts)if(a.text)y.push({type:"text",text:a.text});else if((a.inlineData||a.inline_data)&&f){let R=a.inlineData||a.inline_data,d=R.mimeType||R.mime_type||"image/jpeg",r=R.data;d.startsWith("image/")&&y.push({type:"image_url",image_url:{url:`data:${d};base64,${r}`}})}}else{let a=_.text||"";a&&y.push({type:"text",text:a})}m.push({role:M,content:y.length===1&&y[0].type==="text"?y[0].text:y})}let g={model:t,messages:m,stream:!0,stream_options:{include_usage:!0},temperature:k,tools:[],tool_choice:"none"},T=He("DeepSeek",t,o),i=T!==null?T:o!=="Fast"?{Low:"low",Medium:"high",Standard:"high",High:"max",xHigh:"max"}[o]||"high":null;i&&i!=="disabled"&&i!=="none"&&i!=="false"&&i!==!1?(g.reasoning_effort=i,g.extra_body={thinking:{type:"enabled"}}):g.extra_body={thinking:{type:"disabled"}};let u=await Ze("https://api.deepseek.com/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(g),signal:l});if(!u.ok){let _=await u.json().catch(()=>({}));throw new Error(`DeepSeek Error (${u.status}): ${_.error?.message||u.statusText}`)}let w=u.body.getReader(),I=new TextDecoder,h="",A=[],$=null,C=Date.now(),x=!1;for(;;){let{done:_,value:M}=await w.read();if(_){x&&(A.length>0||$)&&(yield{candidates:A.length>0?[{content:{parts:A}}]:[],usageMetadata:$});break}h+=I.decode(M,{stream:!0});let y=h.split(`
579
+ `);h=y.pop();for(let a of y){let R=a.trim();if(!R||!R.startsWith("data: "))continue;let d=!1;if(R==="data: [DONE]")d=!0;else try{let r=JSON.parse(R.substring(6)),E=r.choices?.[0]?.delta,v=r.usage;if(r.choices?.[0]?.finish_reason&&(d=!0),v&&($={totalTokenCount:v.total_tokens||v.prompt_tokens+v.completion_tokens,promptTokenCount:v.prompt_tokens||0,candidatesTokenCount:v.completion_tokens||0,cachedContentTokenCount:v.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:v.completion_tokens_details?.reasoning_tokens||0},x=!0),E){let U=E.reasoning_content||null;U&&(A.push({text:U,thought:!0}),x=!0),E.content&&(A.push({text:E.content}),x=!0)}}catch{}if((d||Date.now()-C>=150)&&x&&(yield{candidates:A.length>0?[{content:{parts:[...A]}}]:[],usageMetadata:$},A=[],C=Date.now(),x=!1),d)break}Date.now()-C>=150&&x&&(yield{candidates:A.length>0?[{content:{parts:[...A]}}]:[],usageMetadata:$},A=[],C=Date.now(),x=!1)}};var Qo=async function*(e,t,n,s,o,c,f,l,k=1,m=null){let g=[];s&&g.push({role:"system",content:s});for(let a of n){let R=a.role==="user"?"user":"assistant",d=[];if(Array.isArray(a.parts)){for(let r of a.parts)if(r.text)d.push({type:"text",text:r.text});else if(r.inlineData&&f){let E=r.inlineData.mimeType,v=r.inlineData.data;E.startsWith("image/")&&d.push({type:"image_url",image_url:`data:${E};base64,${v}`})}}else{let r=a.text||"";r&&d.push({type:"text",text:r})}d.length>0&&g.push({role:R,content:d.length===1&&d[0].type==="text"?d[0].text:d})}let T={Fast:"none",Low:"none",Medium:"high",Standard:"high",High:"high",xHigh:"high"},p=`${e.slice(-5)}${m||""}${o}${t}`,i=await Xo(p),u={model:t,messages:g,stream:!0,temperature:k,prompt_cache_key:i,tools:[],tool_choice:"none"},w=He("Mistral",t,o);w!==null&&w!=="none"?w&&w!=="none"&&w!=="disabled"&&w!==!1&&(u.reasoning_effort=w):o&&T[o]!=="none"&&(u.reasoning_effort=T[o]||"high");let I=await Ze("https://api.mistral.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(u),signal:l});if(!I.ok){let a=await I.text().catch(()=>""),R=I.statusText;try{let d=JSON.parse(a);R=d.error?.message||d.message||JSON.stringify(d.detail||d)}catch{a&&(R=a)}throw new Error(`Mistral Error (${I.status}): ${JSON.stringify(R)}`)}let h=I.body.getReader(),A=new TextDecoder,$="",C=[],x=null,_=Date.now(),M=!1,y=a=>a?typeof a=="string"?xn(a):Array.isArray(a)?a.map(y).filter(Boolean).join(""):typeof a=="object"&&a!==null?typeof a.text=="string"?xn(a.text):typeof a.content=="string"?xn(a.content):typeof a.thinking=="string"?xn(a.thinking):typeof a.reasoning_content=="string"?xn(a.reasoning_content):typeof a.reasoning=="string"?xn(a.reasoning):typeof a.value=="string"?xn(a.value):a.text?y(a.text):a.content?y(a.content):a.thinking?y(a.thinking):a.reasoning_content?y(a.reasoning_content):a.reasoning?y(a.reasoning):a.value?y(a.value):"":xn(String(a)):"";for(;;){let{done:a,value:R}=await h.read();if(a){M&&(C.length>0||x)&&(yield{candidates:C.length>0?[{content:{parts:C}}]:[],usageMetadata:x});break}$+=A.decode(R,{stream:!0});let d=$.split(`
580
+ `);$=d.pop();for(let r of d){let E=r.trim();if(!E||!E.startsWith("data: "))continue;let v=!1;if(E==="data: [DONE]")v=!0;else try{let U=JSON.parse(E.substring(6)),O=U.choices?.[0]?.delta,P=U.usage;if(U.choices?.[0]?.finish_reason&&(v=!0),P&&(x={totalTokenCount:P.total_tokens||(P.prompt_tokens||0)+(P.completion_tokens||0),promptTokenCount:P.prompt_tokens||0,candidatesTokenCount:P.completion_tokens||0,cachedContentTokenCount:P.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:P.completion_tokens_details?.reasoning_tokens||0},M=!0),O){let re=O.thinking||O.reasoning_content||O.reasoning,de=y(re);de&&(C.push({text:de,thought:!0}),M=!0);let Q=O.content||(!O.thinking&&!O.reasoning_content&&!O.reasoning?O.text:null);if(Q)if(Array.isArray(Q))for(let ke of Q)if(typeof ke=="object"&&ke!==null){let ae=ke.type==="thinking"||ke.type==="reasoning"||!!ke.thought,it=y(ke);it&&(C.push({text:it,...ae?{thought:!0}:{}}),M=!0)}else{let ae=y(ke);ae&&(C.push({text:ae}),M=!0)}else if(typeof Q=="object"&&Q!==null){let ke=Q.type==="thinking"||Q.type==="reasoning"||!!Q.thought,ae=y(Q);ae&&(C.push({text:ae,...ke?{thought:!0}:{}}),M=!0)}else{let ke=y(Q);ke&&(C.push({text:ke}),M=!0)}}}catch{}if((v||Date.now()-_>=150)&&M&&(yield{candidates:C.length>0?[{content:{parts:[...C]}}]:[],usageMetadata:x},C=[],_=Date.now(),M=!1),v)break}Date.now()-_>=150&&M&&(yield{candidates:C.length>0?[{content:{parts:[...C]}}]:[],usageMetadata:x},C=[],_=Date.now(),M=!1)}};var Zo=async function*(e,t,n,s,o,c,f=!1,l,k=1){let m=[];s&&m.push({role:"system",content:s}),n.forEach(ae=>{let it=ae.role==="model"?"assistant":"user",L=[];Array.isArray(ae.parts)&&ae.parts.forEach(F=>{if(F.text)L.push({type:"text",text:F.text});else if(F.inlineData&&f){let Ee=F.inlineData.mimeType,oe=F.inlineData.data;Ee.startsWith("image/")&&ft(t)&&L.push({type:"image_url",image_url:{url:`data:${Ee};base64,${oe}`}})}}),m.push({role:it,content:L.length===1&&L[0].type==="text"?L[0].text:L})});let g=He("NVIDIA",t,o),p=g!==null?g:{Fast:"Fast",Low:"Fast",Medium:"Standard",Standard:"Standard",High:"High",xHigh:"High"}[o]||"High",i=p!=="Fast"&&p!=="none"&&p!=="disabled"&&p!==!1,u=t.includes("kimi"),w=t.includes("gemma"),I=t.includes("deepseek"),h=t.includes("glm"),A=t.includes("mistral"),$=t.includes("minimax"),C=t.includes("gpt"),x=t.includes("qwen"),_=t.includes("nemotron"),M=t.includes("llama-3"),y=t.includes("seed"),a=t.includes("poolside"),R=t.includes("thinkingmachines")||t.includes("muse"),d=M,r={Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},E={Fast:"64",Low:"64",Medium:"4096",Standard:"4096",High:"16384",xHigh:"16384"},v={Fast:"none",Low:"minimal",Medium:"medium",Standard:"medium",High:"max",xHigh:"max"},U=$||I||a||R?16384:32768;U=process.env.NVIDIA_BASE_URL?1024:U;let O={model:t,messages:m,max_tokens:U,stream:!0,stream_options:{include_usage:!0},temperature:k,tools:[],tool_choice:"none",...C&&{thinking:r[o]||"high"}};if(!(process.env.NVIDIA_BASE_URL||d))if(u)O.chat_template_kwargs={thinking:i};else if(w)O.chat_template_kwargs={enable_thinking:i};else if(I)if(i){let ae=p==="High"?"max":"high";O.chat_template_kwargs={thinking:!0,reasoning_effort:ae}}else O.chat_template_kwargs={thinking:!1};else h?O.chat_template_kwargs={enable_thinking:i,clear_thinking:!i}:A?O.reasoning_effort=i?"high":"none":$&&t.includes("minimax-m3")?O.chat_template_kwargs={thinking_mode:i?"enabled":"disabled"}:x?O.chat_template_kwargs={enable_thinking:i}:_?p==="High"?O.chat_template_kwargs={enable_thinking:!0}:p==="Standard"?O.chat_template_kwargs={enable_thinking:!0,medium_effort:!0}:O.chat_template_kwargs={enable_thinking:!1}:y?i&&(O.extra_body={thinking_budget:parseInt(E[p]??"4096")}):a?O.chat_template_kwargs={enable_thinking:i}:R&&(O.reasoning_effort=v[p]||"medium");let P=0,re=6,de=!1,Q=process.env.NVIDIA_BASE_URL||"https://integrate.api.nvidia.com/v1/chat/completions",ke=process.env.NVIDIA_API_KEY&&process.env.NVIDIA_BASE_URL?process.env.NVIDIA_API_KEY:e;for(Q.endsWith("/chat/completions")||(Q=Q.replace(/\/+$/,"")+"/chat/completions");P<re;){P++;try{let ae=await Ze(Q,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${ke}`},body:JSON.stringify(O),signal:l});if(!ae.ok){let ye=await ae.text().catch(()=>""),Re=ae.statusText;try{let Ie=JSON.parse(ye);Re=Ie.error?.message||Ie.message||JSON.stringify(Ie.detail||Ie)}catch{ye&&(Re=ye)}let ve=new Error(`NVIDIA API Error (${ae.status}): ${Re}`);throw ve.status=ae.status,ve}let it=ae.body.getReader(),L=new TextDecoder,F="",Ee=[],oe=null,B=Date.now(),G=!1;for(;;){let{done:ye,value:Re}=await it.read();if(ye){G&&(Ee.length>0||oe)&&(yield{candidates:Ee.length>0?[{content:{parts:Ee}}]:[],usageMetadata:oe},de=!0);break}F+=L.decode(Re,{stream:!0});let ve=F.split(`
581
+ `);F=ve.pop();let Ie=!1;for(let Dn of ve){let nn=Dn.trim();if(nn){if(nn==="data: [DONE]"){Ie=!0;break}if(nn.startsWith("data: ")){let mt;try{mt=JSON.parse(nn.substring(6))}catch{continue}if(mt.error)throw new Error(`NVIDIA Stream Error: ${mt.error.message||JSON.stringify(mt.error)}`);try{let kt=mt.usage;kt&&(oe={totalTokenCount:kt.total_tokens||kt.prompt_tokens+kt.completion_tokens,promptTokenCount:kt.prompt_tokens||0,candidatesTokenCount:kt.completion_tokens||0,cachedContentTokenCount:kt.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:(kt.completion_tokens_details?.reasoning_tokens||0)+(kt.completion_tokens_details?.thoughts_tokens||0)},G=!0);let Je=mt.choices?.[0]?.delta?.reasoning||mt.choices?.[0]?.delta?.reasoning_content||"",xe=mt.choices?.[0]?.delta?.content||"";Je&&(Ee.push({text:Je,thought:!0}),G=!0),xe&&(Ee.push({text:xe}),G=!0)}catch{}}}}if((Ie||Date.now()-B>=350)&&G&&(yield{candidates:Ee.length>0?[{content:{parts:[...Ee]}}]:[],usageMetadata:oe},de=!0,Ee=[],B=Date.now(),G=!1),Ie)break}break}catch(ae){if(de||P>=re)throw ae;await new Promise(it=>setTimeout(it,3500))}}},Fr=async function*(e,t){let n=[],s=null,o=!1,c=null,f=u=>{if(n.push(u),s){let w=s;s=null,w()}},l=t.split("/").pop(),k=Array.from(new Set([l,l.replace(/\./g,"-"),l.replace(/\./g,"_")])),g=["https://buildapi.ngc.nvidia.com/v2/predict/queues/models/qc69jvmznzxy","https://api.ngc.nvidia.com/v2/predict/queues/models/qc69jvmznzxy"].flatMap(u=>k.map(w=>`${u}/${w}`)),T=!1,p=null,i=async()=>{try{let w=await(await Promise.any(g.map(async I=>{let h=await fetch(I);if(!h.ok)throw new Error(`HTTP ${h.status}`);return h}))).json();if(w&&w.queues&&w.queues[0]&&typeof w.queues[0].queueDepth=="number"){let I=w.queues[0].queueDepth;T||f({value:{type:"status",content:`Queue ${I||1}`},done:!1})}}catch{}};process.env.NVIDIA_BASE_URL||(i(),p=setInterval(i,5e3)),(async()=>{try{let u=e[Symbol.asyncIterator]();for(;;){let{value:w,done:I}=await u.next();if(I)break;T=!0,p&&(clearInterval(p),p=null),f({value:w,done:!1})}o=!0,f(null)}catch(u){if(c=u,p&&(clearInterval(p),p=null),s){let w=s;s=null,w()}}})();try{for(;;){if(c)throw c;if(n.length>0){let u=n.shift();if(u===null&&o)break;yield u.value}else{if(o)break;await new Promise(u=>{s=u})}}}finally{p&&(clearInterval(p),p=null)}};var es=async function*(e,t,n,s,o,c,f,l,k=1,m=null){let g=[];s&&g.push({role:"system",content:[{type:"text",text:s}]});for(let E of n){let v=E.role==="user"?"user":"assistant",U=[];if(Array.isArray(E.parts)){for(let O of E.parts)if(O.text)U.push({type:"text",text:O.text});else if(O.inlineData&&f){let P=O.inlineData.mimeType,re=O.inlineData.data;P.startsWith("image/")?U.push({type:"image_url",image_url:{url:`data:${P};base64,${re}`}}):U.push({type:"file",file:{filename:O.filename||"file",file_data:`data:${P};base64,${re}`}})}}else{let O=E.text||"";O&&U.push({type:"text",text:O})}g.push({role:v,content:U.length===1&&U[0].type==="text"?U[0].text:U})}let T={Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},p=["free","nitro","floor","exacto"],i=t,u=null,w=null;if(t.includes(":")){let E=t.split(":");if(E.length>1){let v=E[E.length-1].toLowerCase().trim();(v==="flex"||v==="priority")&&(w=v,E.pop())}if(E.length>1){let v=E[E.length-1].toLowerCase().trim();if(!p.includes(v)){let U=E.pop().trim();U&&(u={only:[U],allow_fallbacks:!1})}}i=E.join(":").trim()}let I=`${e.slice(-5)}${m||""}${o}${i}${w||""}${u?JSON.stringify(u):""}`,h=await Xo(I),A={model:i,messages:g,stream:!0,temperature:k,cache_control:{type:"ephemeral"},tools:[],tool_choice:"none",session_id:h};w&&(A.service_tier=w),u&&(A.provider=u);let $=He("OpenRouter",t,o),C=$!==null?$:T[o];C&&C!=="none"&&($!==null||o!=="Fast")&&(A.reasoning_effort=C);let x=await Ze("https://openrouter.ai/api/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json","HTTP-Referer":"https://fluxflow-cli.onrender.com/","X-Title":"FluxFlow CLI","X-OpenRouter-Title":"FluxFlow CLI","X-Cache":"true","X-OpenRouter-Cache":"true"},body:JSON.stringify(A),signal:l});if(!x.ok){let E=await x.json().catch(()=>({})),v=E.error?.metadata?.raw||E.error?.message||(typeof E.error=="string"?E.error:"")||x.statusText||"Unknown error";throw new Error(`OpenRouter Error (${x.status}): ${v}`)}let _=x.body.getReader(),M=new TextDecoder,y="",a=[],R=null,d=Date.now(),r=!1;for(;;){let{done:E,value:v}=await _.read();if(E){r&&(a.length>0||R)&&(yield{candidates:a.length>0?[{content:{parts:a}}]:[],usageMetadata:R});break}y+=M.decode(v,{stream:!0});let U=y.split(`
582
+ `);y=U.pop();for(let O of U){let P=O.trim();if(!P||!P.startsWith("data: "))continue;let re=!1;if(P==="data: [DONE]")re=!0;else try{let de=JSON.parse(P.substring(6));if(de.error){let ae=de.error.metadata?.raw||de.error.message||JSON.stringify(de.error);throw new Error(`OpenRouter Stream Error: ${ae}`)}let Q=de.choices?.[0]?.delta,ke=de.usage;if(de.choices?.[0]?.finish_reason&&(re=!0),ke&&(R={totalTokenCount:ke.total_tokens||(ke.prompt_tokens||0)+(ke.completion_tokens||0),promptTokenCount:ke.prompt_tokens||0,candidatesTokenCount:ke.completion_tokens||0,cachedContentTokenCount:ke.prompt_tokens_details?.cached_tokens||ke.prompt_tokens_details?.cache_read_input_tokens||ke.cache_read_input_tokens||0,thoughtsTokenCount:ke.completion_tokens_details?.reasoning_tokens||0},r=!0),Q){let ae=Q.reasoning||(Q.reasoning_details?Q.reasoning_details.map(it=>it.text).join(""):null);ae&&(a.push({text:ae,thought:!0}),r=!0),Q.content&&(a.push({text:Q.content}),r=!0)}}catch(de){if(de.message&&de.message.startsWith("OpenRouter Stream Error:"))throw de}if((re||Date.now()-d>=150)&&r&&(yield{candidates:a.length>0?[{content:{parts:[...a]}}]:[],usageMetadata:R},a=[],d=Date.now(),r=!1),re)break}}};import{Ollama as Oa}from"ollama";var ei=async function*(e,t,n,s,o,c,f,l,k=1,m="Cloud"){let g=[];s&&g.push({role:"system",content:s});for(let y of n){let a=y.role==="user"?"user":"assistant",R="",d=[];if(Array.isArray(y.parts)){R=y.parts.map(r=>r.text||"").filter(Boolean).join(`
583
+ `);for(let r of y.parts){let E=r.inlineData||r.inline_data;E&&E.data&&d.push(E.data)}}else R=y.text||"";if(R||d.length>0){let r={role:a,content:R};d.length>0&&(r.images=d),g.push(r)}}let T=m==="Local"||!e||e==="LOCAL",i={host:T?process.env.OLLAMA_HOST||"http://127.0.0.1:11434":process.env.OLLAMA_HOST||"https://ollama.com"};!T&&e&&(i.headers={Authorization:"Bearer "+e});let u=new Oa(i),w=[],I=null,h=Date.now(),A=!1,$=He("Ollama",t,o),C={Fast:!1,Low:"medium",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},x=$!==null?$==="false"||$===!1?!1:$==="true"||$===!0?!0:$:C[o]!==void 0?C[o]:!0,_={model:t,messages:g,stream:!0,think:x,keep_alive:"10m",tools:[],tool_choice:"none",options:{temperature:k}},M=await u.chat(_);for await(let y of M){if(l?.aborted)throw new DOMException("The user aborted a request.","AbortError");if(y.message?.thinking&&(w.push({text:y.message.thinking,thought:!0}),A=!0),y.message?.content&&(w.push({text:y.message.content}),A=!0),y.done){let a=y.prompt_cached_count||0;if(!a&&y.prompt_eval_count){let R=y.prompt_eval_duration||0;R>0&&R<5e7&&(a=y.prompt_eval_count)}I={totalTokenCount:(y.prompt_eval_count||0)+(y.eval_count||0),promptTokenCount:y.prompt_eval_count||0,candidatesTokenCount:y.eval_count||0,cachedContentTokenCount:a,thoughtsTokenCount:0},A=!0}(y.done||Date.now()-h>=150&&A)&&(yield{candidates:w.length>0?[{content:{parts:[...w]}}]:[],usageMetadata:I},w=[],h=Date.now(),A=!1)}A&&(w.length>0||I)&&(yield{candidates:w.length>0?[{content:{parts:[...w]}}]:[],usageMetadata:I})};var ts=async function*(e,t,n,s,o,c,f,l,k=1){let m=[];s&&m.push({role:"system",content:s});for(let a of n){let R=a.role==="user"?"user":"assistant",d="";if(Array.isArray(a.parts))for(let r of a.parts)r.text&&(d+=(d?`
584
+ `:"")+r.text);else d=a.text||"";m.push({role:R,content:d})}let g=He("InferX",t,o),p=g!==null?g:{Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i=t&&t.toLowerCase().includes("qwen3.8-27b")&&g===null,u=t&&(t.toLowerCase().includes("qwen3.8-27b")||t.toLowerCase().includes("qwen3.6-35b-a3b-fp8")),w={model:t,messages:m.filter(a=>a.content&&String(a.content).trim().length>0),stream:!0,stream_options:{include_usage:!0},temperature:k,tools:[],tool_choice:"none"};!i&&p&&(w.stream_options={include_usage:!0},w.reasoning_effort=p);let I=await Ze("https://model.inferx.net/endpoints/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(w),signal:l});if(!I.ok){let a=await I.text().catch(()=>""),R="";try{let d=JSON.parse(a);R=d.error?.message||d.error?.detail||d.message||d.detail||(typeof d.error=="string"?d.error:"")||(a&&a!=="{}"?a:"")}catch{R=a}throw(!R||R==="{}")&&(R=I.statusText||"Unknown error"),new Error(`InferX Error (${I.status}): ${R}`)}let h=I.body.getReader(),A=new TextDecoder,$="",C=[],x=null,_=Date.now(),M=!1,y=!0;for(;;){let{done:a,value:R}=await h.read();if(a){M&&(C.length>0||x)&&(yield{candidates:C.length>0?[{content:{parts:C}}]:[],usageMetadata:x});break}$+=A.decode(R,{stream:!0});let d=$.split(`
585
+ `);$=d.pop();for(let r of d){let E=r.trim();if(!E||!E.startsWith("data: "))continue;let v=!1;if(E==="data: [DONE]")v=!0;else try{let U=JSON.parse(E.substring(6)),O=U.choices?.[0]?.delta,P=U.usage;if(P&&(x={totalTokenCount:P.total_tokens||(P.prompt_tokens||0)+(P.completion_tokens||0),promptTokenCount:P.prompt_tokens||0,candidatesTokenCount:P.completion_tokens||0,cachedContentTokenCount:P.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:P.completion_tokens_details?.reasoning_tokens||P.reasoning_tokens||0},M=!0),O){let re=O.reasoning||O.reasoning_content||null;if(re&&(C.push({text:re,thought:!0}),M=!0),O.content){let de=O.content;u&&y&&de.length>0&&(de="<think>"+de,y=!1),C.push({text:de}),M=!0}}}catch{}if((v||Date.now()-_>=150||x)&&M&&(yield{candidates:C.length>0?[{content:{parts:[...C]}}]:[],usageMetadata:x},C=[],_=Date.now(),M=!1),v)break}Date.now()-_>=150&&M&&(yield{candidates:C.length>0?[{content:{parts:[...C]}}]:[],usageMetadata:x},C=[],_=Date.now(),M=!1)}};var ns=async function*(e,t,n,s,o,c,f,l,k=1){let m=[];s&&m.push({role:"system",content:s});for(let _ of n){let M=_.role==="user"?"user":"assistant",y=[];if(Array.isArray(_.parts)){for(let a of _.parts)if(a.text)y.push({type:"text",text:a.text});else if(a.inlineData&&f){let R=a.inlineData.mimeType,d=a.inlineData.data;R.startsWith("image/")&&y.push({type:"image_url",image_url:{url:`data:${R};base64,${d}`}})}}else{let a=_.text||"";a&&y.push({type:"text",text:a})}m.push({role:M,content:y.length===1&&y[0].type==="text"?y[0].text:y})}let g=He("SenseNova",t,o),p=g!==null?g:{Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:m,stream:!0,stream_options:{include_usage:!0},temperature:k,tools:[],tool_choice:"none"};p&&(i.reasoning_effort=p);let u=await Ze("https://token.sensenova.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(i),signal:l});if(!u.ok){let _=await u.json().catch(()=>({}));throw new Error(`SenseNova Error (${u.status}): ${_.error?.message||u.statusText}`)}let w=u.body.getReader(),I=new TextDecoder,h="",A=[],$=null,C=Date.now(),x=!1;for(;;){let{done:_,value:M}=await w.read();if(_){x&&(A.length>0||$)&&(yield{candidates:A.length>0?[{content:{parts:A}}]:[],usageMetadata:$});break}h+=I.decode(M,{stream:!0});let y=h.split(`
586
+ `);h=y.pop();for(let a of y){let R=a.trim();if(!R||!R.startsWith("data: "))continue;let d=!1;if(R==="data: [DONE]")d=!0;else try{let r=JSON.parse(R.substring(6)),E=r.choices?.[0]?.delta,v=r.usage;if(v&&($={totalTokenCount:v.total_tokens||(v.prompt_tokens||0)+(v.completion_tokens||0),promptTokenCount:v.prompt_tokens||0,candidatesTokenCount:v.completion_tokens||0,cachedContentTokenCount:v.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:v.completion_tokens_details?.reasoning_tokens||v.reasoning_tokens||0},x=!0),E){let U=E.reasoning||E.reasoning_content||null;U&&(A.push({text:U,thought:!0}),x=!0),E.content&&(A.push({text:E.content}),x=!0)}}catch{}if((d||Date.now()-C>=150||$)&&x&&(yield{candidates:A.length>0?[{content:{parts:[...A]}}]:[],usageMetadata:$},A=[],C=Date.now(),x=!1),d)break}Date.now()-C>=150&&x&&(yield{candidates:A.length>0?[{content:{parts:[...A]}}]:[],usageMetadata:$},A=[],C=Date.now(),x=!1)}};var os=async function*(e,t,n,s,o,c,f,l,k=1){let m=[];s&&m.push({role:"system",content:s});for(let _ of n){let M=_.role==="user"?"user":"assistant",y=[];if(Array.isArray(_.parts)){for(let a of _.parts)if(a.text)y.push({type:"text",text:a.text});else if(a.inlineData&&f){let R=a.inlineData.mimeType,d=a.inlineData.data;R.startsWith("image/")&&y.push({type:"image_url",image_url:{url:`data:${R};base64,${d}`}})}}else{let a=_.text||"";a&&y.push({type:"text",text:a})}m.push({role:M,content:y.length===1&&y[0].type==="text"?y[0].text:y})}let g=He("AIHubMix",t,o),p=g!==null?g:{Fast:"minimal",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:m,stream:!0,stream_options:{include_usage:!0},temperature:k,tools:[],tool_choice:"none"};p&&(i.reasoning_effort=p);let u=await Ze("https://aihubmix.com/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(i),signal:l});if(!u.ok){let _=await u.json().catch(()=>({}));throw new Error(`AIHubMix Error (${u.status}): ${_.error?.message||u.statusText}`)}let w=u.body.getReader(),I=new TextDecoder,h="",A=[],$=null,C=Date.now(),x=!1;for(;;){let{done:_,value:M}=await w.read();if(_){x&&(A.length>0||$)&&(yield{candidates:A.length>0?[{content:{parts:A}}]:[],usageMetadata:$});break}h+=I.decode(M,{stream:!0});let y=h.split(`
587
+ `);h=y.pop();for(let a of y){let R=a.trim();if(!R||!R.startsWith("data: "))continue;let d=!1;if(R==="data: [DONE]")d=!0;else try{let r=JSON.parse(R.substring(6)),E=r.choices?.[0]?.delta,v=r.usage;if(r.choices?.[0]?.finish_reason&&(d=!0),v&&($={totalTokenCount:v.total_tokens||(v.prompt_tokens||0)+(v.completion_tokens||0),promptTokenCount:v.prompt_tokens||0,candidatesTokenCount:v.completion_tokens||0,cachedContentTokenCount:v.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:v.completion_tokens_details?.reasoning_tokens||v.reasoning_tokens||0},x=!0),E){let U=E.reasoning_content||null;U&&(A.push({text:U,thought:!0}),x=!0),E.content&&(A.push({text:E.content}),x=!0)}}catch{}if((d||Date.now()-C>=150)&&x&&(yield{candidates:A.length>0?[{content:{parts:[...A]}}]:[],usageMetadata:$},A=[],C=Date.now(),x=!1),d)break}Date.now()-C>=150&&x&&(yield{candidates:A.length>0?[{content:{parts:[...A]}}]:[],usageMetadata:$},A=[],C=Date.now(),x=!1)}};var ss=async function*(e,t,n,s,o,c,f,l,k=1){let m=[];s&&m.push({role:"system",content:s});for(let x of n){let _=x.role==="user"?"user":"assistant",M=[];if(Array.isArray(x.parts)){for(let y of x.parts)if(y.text)M.push({type:"text",text:y.text});else if(y.inlineData&&f){let a=y.inlineData.mimeType,R=y.inlineData.data;a.startsWith("image/")&&M.push({type:"image_url",image_url:{url:`data:${a};base64,${R}`}})}}else{let y=x.text||"";y&&M.push({type:"text",text:y})}m.push({role:_,content:M.length===1&&M[0].type==="text"?M[0].text:M})}let g=He("Poolside",t,o),T=g!==null?g===!1||g==="false"||g==="none"||g==="Fast":o==="Fast",p={model:t,messages:m,stream:!0,stream_options:{include_usage:!0},temperature:k,tools:[],tool_choice:"none"};T?p.chat_template_kwargs={enable_thinking:!1}:g!==null&&typeof g=="object"?p.chat_template_kwargs=g:p.chat_template_kwargs={enable_thinking:!0};let i=await Ze("https://inference.poolside.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(p),signal:l});if(!i.ok){let x=await i.json().catch(()=>({}));throw new Error(`Poolside Error (${i.status}): ${x.error?.message||i.statusText}`)}let u=i.body.getReader(),w=new TextDecoder,I="",h=[],A=null,$=Date.now(),C=!1;for(;;){let{done:x,value:_}=await u.read();if(x){C&&(h.length>0||A)&&(yield{candidates:h.length>0?[{content:{parts:h}}]:[],usageMetadata:A});break}I+=w.decode(_,{stream:!0});let M=I.split(`
588
+ `);I=M.pop();for(let y of M){let a=y.trim();if(!a||!a.startsWith("data: "))continue;let R=!1;if(a==="data: [DONE]")R=!0;else try{let d=JSON.parse(a.substring(6)),r=d.choices?.[0]?.delta,E=d.usage;if(d.choices?.[0]?.finish_reason&&(R=!0),E&&(A={totalTokenCount:E.total_tokens||(E.prompt_tokens||0)+(E.completion_tokens||0),promptTokenCount:E.prompt_tokens||0,candidatesTokenCount:E.completion_tokens||0,cachedContentTokenCount:E.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:E.completion_tokens_details?.reasoning_tokens||E.reasoning_tokens||0},C=!0),r){let v=r.reasoning_content||r.reasoning||null;v&&(h.push({text:v,thought:!0}),C=!0),r.content&&(h.push({text:r.content}),C=!0)}}catch{}if((R||Date.now()-$>=150)&&C&&(yield{candidates:h.length>0?[{content:{parts:[...h]}}]:[],usageMetadata:A},h=[],$=Date.now(),C=!1),R)break}Date.now()-$>=150&&C&&(yield{candidates:h.length>0?[{content:{parts:[...h]}}]:[],usageMetadata:A},h=[],$=Date.now(),C=!1)}};var is=async function*(e,t,n,s,o,c,f,l,k=1){let m=[];s&&m.push({role:"system",content:s});for(let a of n){let R=a.role==="user"?"user":"assistant",d=[];if(Array.isArray(a.parts)){for(let r of a.parts)if(r.text)d.push({type:"text",text:r.text});else if(r.inlineData&&f){let E=r.inlineData.mimeType,v=r.inlineData.data;E.startsWith("image/")&&d.push({type:"image_url",image_url:{url:`data:${E};base64,${v}`}})}}else{let r=a.text||"";r&&d.push({type:"text",text:r})}m.push({role:R,content:d.length===1&&d[0].type==="text"?d[0].text:d})}let g=He("9router",t,o)||He("9Router",t,o),p=g!==null?g:{Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:m,stream:!0,stream_options:{include_usage:!0},temperature:k,tools:[],tool_choice:"none"};p&&p!=="none"&&(g!==null||o!=="Fast")&&(i.reasoning_effort=p);let u=process.env["9ROUTER_URL"]||process.env.NINEROUTER_URL||"http://127.0.0.1:20128/v1/chat/completions",w={"Content-Type":"application/json"},I=e&&e!=="LOCAL"?e:process.env.NINEROUTER_KEY||"dummy-key";w.Authorization=`Bearer ${I}`;let h=await Ze(u,{method:"POST",headers:w,body:JSON.stringify(i),signal:l});if(!h.ok){let a=await h.json().catch(()=>({}));throw new Error(`9router Error (${h.status}): ${a.error?.message||h.statusText}`)}let A=h.body.getReader(),$=new TextDecoder,C="",x=[],_=null,M=Date.now(),y=!1;for(;;){let{done:a,value:R}=await A.read();if(a){y&&(x.length>0||_)&&(yield{candidates:x.length>0?[{content:{parts:x}}]:[],usageMetadata:_});break}C+=$.decode(R,{stream:!0});let d=C.split(`
589
+ `);C=d.pop();for(let r of d){let E=r.trim();if(!E||!E.startsWith("data: "))continue;let v=!1;if(E==="data: [DONE]")v=!0;else try{let U=JSON.parse(E.substring(6)),O=U.choices?.[0]?.delta,P=U.usage;if(U.choices?.[0]?.finish_reason&&(v=!0),P&&(_={totalTokenCount:P.total_tokens||(P.prompt_tokens||0)+(P.completion_tokens||0),promptTokenCount:P.prompt_tokens||0,candidatesTokenCount:P.completion_tokens||0,cachedContentTokenCount:P.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:P.completion_tokens_details?.reasoning_tokens||P.reasoning_tokens||0},y=!0),O){let re=O.reasoning_content||O.reasoning||O.thinking||null;!re&&Array.isArray(O.reasoning_details)&&O.reasoning_details.length>0&&(re=O.reasoning_details.map(de=>typeof de=="string"?de:de?.text||"").filter(Boolean).join("")),re&&(x.push({text:re,thought:!0}),y=!0),O.content&&(x.push({text:O.content}),y=!0)}}catch{}if((v||Date.now()-M>=150)&&y&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:_},x=[],M=Date.now(),y=!1),v)break}Date.now()-M>=150&&y&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:_},x=[],M=Date.now(),y=!1)}};var rs=async function*(e,t,n,s,o,c,f,l,k=1){let m=[];s&&m.push({role:"system",content:s});for(let a of n){let R=a.role==="user"?"user":"assistant",d=[];if(Array.isArray(a.parts)){for(let r of a.parts)if(r.text)d.push({type:"text",text:r.text});else if(r.inlineData&&f){let E=r.inlineData.mimeType,v=r.inlineData.data;E.startsWith("image/")&&d.push({type:"image_url",image_url:{url:`data:${E};base64,${v}`}})}}else{let r=a.text||"";r&&d.push({type:"text",text:r})}m.push({role:R,content:d.length===1&&d[0].type==="text"?d[0].text:d})}let g=He("ExpLabs",t,o),p=g!==null?g:{Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:m,stream:!0,stream_options:{include_usage:!0},temperature:k,tools:[],tool_choice:"none"};p&&(i.reasoning_effort=p);let u=process.env.EXPLABS_URL||process.env.EXPERIENTIALLABS_URL||"https://api.experientiallabs.ai/v1/chat/completions",w={"Content-Type":"application/json"},I=e||process.env.EXPLABS_API_KEY||process.env.EXPERIENTIALLABS_API_KEY||"";w.Authorization=`Bearer ${I}`;let h=await Ze(u,{method:"POST",headers:w,body:JSON.stringify(i),signal:l});if(!h.ok){let a=await h.json().catch(()=>({}));throw new Error(`Experiential Labs Error (${h.status}): ${a.error?.message||a.message||h.statusText}`)}let A=h.body.getReader(),$=new TextDecoder,C="",x=[],_=null,M=Date.now(),y=!1;for(;;){let{done:a,value:R}=await A.read();if(a){y&&(x.length>0||_)&&(yield{candidates:x.length>0?[{content:{parts:x}}]:[],usageMetadata:_});break}C+=$.decode(R,{stream:!0});let d=C.split(`
590
+ `);C=d.pop();for(let r of d){let E=r.trim();if(!E||!E.startsWith("data: "))continue;let v=!1;if(E==="data: [DONE]")v=!0;else try{let U=JSON.parse(E.substring(6)),O=U.choices?.[0]?.delta,P=U.usage;if(P&&(_={totalTokenCount:P.total_tokens||(P.prompt_tokens||0)+(P.completion_tokens||0),promptTokenCount:P.prompt_tokens||0,candidatesTokenCount:P.completion_tokens||0,cachedContentTokenCount:P.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:P.completion_tokens_details?.reasoning_tokens||P.reasoning_tokens||0},y=!0),O){let re=O.reasoning_content||O.reasoning||null;!re&&Array.isArray(O.reasoning_details)&&O.reasoning_details.length>0&&(re=O.reasoning_details.map(de=>de.text||"").filter(Boolean).join("")),re&&(x.push({text:re,thought:!0}),y=!0),O.content&&(x.push({text:O.content}),y=!0)}}catch{}if((v||Date.now()-M>=150)&&y&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:_},x=[],M=Date.now(),y=!1),v)break}Date.now()-M>=150&&y&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:_},x=[],M=Date.now(),y=!1)}};var ti=async function*(e,t,n,s,o,c,f,l,k=1){let m=[];s&&m.push({role:"system",content:s});for(let a of n){let R=a.role==="user"?"user":"assistant",d=[];if(Array.isArray(a.parts)){for(let r of a.parts)if(r.text)d.push({type:"text",text:r.text});else if(r.inlineData&&f){let E=r.inlineData.mimeType,v=r.inlineData.data;E.startsWith("image/")&&d.push({type:"image_url",image_url:{url:`data:${E};base64,${v}`}})}}else{let r=a.text||"";r&&d.push({type:"text",text:r})}m.push({role:R,content:d.length===1&&d[0].type==="text"?d[0].text:d})}let g=He("TokenHarbor",t,o),p=g!==null?g:{Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:m,stream:!0,stream_options:{include_usage:!0},temperature:k,tools:[],tool_choice:"none"};p&&(i.reasoning_effort=p);let u=process.env.TOKENHARBOR_URL||process.env.TOKEN_HARBOR_URL||"https://tokenharbor.ai/v1/chat/completions",w={"Content-Type":"application/json","X-Title":"Flux-Flow","User-Agent":"Flux-Flow","HTTP-Referer":"https://fluxflow-cli.onrender.com/"},I=e||process.env.TOKENHARBOR_API_KEY||process.env.TOKEN_HARBOR_API_KEY||"";w.Authorization=`Bearer ${I}`;let h=await Ze(u,{method:"POST",headers:w,body:JSON.stringify(i),signal:l});if(!h.ok){let a=await h.json().catch(()=>({}));throw new Error(`Token Harbor Error (${h.status}): ${a.error?.message||a.message||h.statusText}`)}let A=h.body.getReader(),$=new TextDecoder,C="",x=[],_=null,M=Date.now(),y=!1;for(;;){let{done:a,value:R}=await A.read();if(a){y&&(x.length>0||_)&&(yield{candidates:x.length>0?[{content:{parts:x}}]:[],usageMetadata:_});break}C+=$.decode(R,{stream:!0});let d=C.split(`
591
+ `);C=d.pop();for(let r of d){let E=r.trim();if(!E||!E.startsWith("data: "))continue;let v=!1;if(E==="data: [DONE]")v=!0;else try{let U=JSON.parse(E.substring(6)),O=U.choices?.[0]?.delta,P=U.usage;if(P&&(_={totalTokenCount:P.total_tokens||(P.prompt_tokens||0)+(P.completion_tokens||0),promptTokenCount:P.prompt_tokens||0,candidatesTokenCount:P.completion_tokens||0,cachedContentTokenCount:P.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:P.completion_tokens_details?.reasoning_tokens||P.reasoning_tokens||0},y=!0),O){let re=O.reasoning_content||O.reasoning||null;!re&&Array.isArray(O.reasoning_details)&&O.reasoning_details.length>0&&(re=O.reasoning_details.map(de=>de.text||"").filter(Boolean).join("")),re&&(x.push({text:re,thought:!0}),y=!0),O.content&&(x.push({text:O.content}),y=!0)}}catch{}if((v||Date.now()-M>=150)&&y&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:_},x=[],M=Date.now(),y=!1),v)break}Date.now()-M>=150&&y&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:_},x=[],M=Date.now(),y=!1)}};var ni=async function*(e,t,n,s,o,c,f,l,k=1){let m=[];s&&m.push({role:"system",content:s});for(let a of n){let R=a.role==="user"?"user":"assistant",d=[];if(Array.isArray(a.parts)){for(let r of a.parts)if(r.text)d.push({type:"text",text:r.text});else if(r.inlineData&&f){let E=r.inlineData.mimeType,v=r.inlineData.data;E.startsWith("image/")&&d.push({type:"image_url",image_url:{url:`data:${E};base64,${v}`}})}}else{let r=a.text||"";r&&d.push({type:"text",text:r})}m.push({role:R,content:d.length===1&&d[0].type==="text"?d[0].text:d})}let g=He("APInex",t,o),p=g!==null?g:{Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:m,stream:!0,stream_options:{include_usage:!0},temperature:k,tools:[],tool_choice:"none"};p&&(i.reasoning_effort=p);let u=process.env.APINEX_URL||"https://api.apinex.bond/v1/chat/completions",w={"Content-Type":"application/json","X-Title":"Flux-Flow","User-Agent":"Flux-Flow","HTTP-Referer":"https://fluxflow-cli.onrender.com/"},I=e||process.env.APINEX_API_KEY||"";w.Authorization=`Bearer ${I}`;let h=await Ze(u,{method:"POST",headers:w,body:JSON.stringify(i),signal:l});if(!h.ok){let a=await h.json().catch(()=>({}));throw new Error(`APInex Error (${h.status}): ${a.error?.message||a.message||h.statusText}`)}let A=h.body.getReader(),$=new TextDecoder,C="",x=[],_=null,M=Date.now(),y=!1;for(;;){let{done:a,value:R}=await A.read();if(a){y&&(x.length>0||_)&&(yield{candidates:x.length>0?[{content:{parts:x}}]:[],usageMetadata:_});break}C+=$.decode(R,{stream:!0});let d=C.split(`
592
+ `);C=d.pop();for(let r of d){let E=r.trim();if(!E||!E.startsWith("data: "))continue;let v=!1;if(E==="data: [DONE]")v=!0;else try{let U=JSON.parse(E.substring(6)),O=U.choices?.[0]?.delta,P=U.usage;if(P&&(_={totalTokenCount:P.total_tokens||(P.prompt_tokens||0)+(P.completion_tokens||0),promptTokenCount:P.prompt_tokens||0,candidatesTokenCount:P.completion_tokens||0,cachedContentTokenCount:P.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:P.completion_tokens_details?.reasoning_tokens||P.reasoning_tokens||0},y=!0),O){let re=O.reasoning_content||O.reasoning||null;!re&&Array.isArray(O.reasoning_details)&&O.reasoning_details.length>0&&(re=O.reasoning_details.map(de=>de.text||"").filter(Boolean).join("")),re&&(x.push({text:re,thought:!0}),y=!0),O.content&&(x.push({text:O.content}),y=!0)}}catch{}if((v||Date.now()-M>=150)&&y&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:_},x=[],M=Date.now(),y=!1),v)break}Date.now()-M>=150&&y&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:_},x=[],M=Date.now(),y=!1)}};var La=/```[\s\S]*?```/g,Pa=/```[\s\S]*$/g,$a=/`[^`]+`/g,Na=/^\|.*\|$/gm,Fa=/^[^\w]+|[^\w]+$/g,Ba=/[^a-z0-9]/gi,wo=/\[\s*(?:tool|action):(?:functions\.)?([a-z0-9_]+)\s*\(/gi,Ua=/\[\s*(?:tool:(?:functions\.)?|action:(?:functions\.)?|action:)([a-z0-9_]+)\s*\(/gi,Wa=/(?:path|targetFile|TargetFile|directory|keyword|id|taskId|title|task)\s*=\s*\\?["']?([^\\"' \),]+)/,Gn=/["']/g,Br=/\\/g,Ha=/<\|channel>thought/gi,Ga=/<channel\|>/gi,ja=e=>typeof e!="string"?e:e.replace(Ha,"<think>").replace(Ga,"</think>"),cf=/^\s*(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\]|$)/i,Ka=(e,t,n=1)=>{let s=t>0?e[t-1]:"",o=t+n<e.length?e[t+n]:"";return s==="`"&&o==="`"},Va=e=>{let t=/(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\])/gi,n;for(;(n=t.exec(e))!==null;)if(!Ka(e,n.index,n[0].length))return{index:n.index,length:n[0].length};return{index:-1,length:0}},oi=e=>{if(!e||typeof e!="string")return null;let t=e.match(/^\s*(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought|\[(think|thought|thoughts)\])/i);if(!t)return null;let n=t.index+t[0].length,s=e.substring(n),o=Va(s);if(o.index!==-1){let c=n+o.index+o.length;return{fullBlock:e.substring(0,c),innerContent:s.substring(0,o.index),remainingText:e.substring(c)}}return{fullBlock:e,innerContent:s,remainingText:""}},qt=e=>{if(!e||typeof e!="string")return e;let t=oi(e);return t?t.remainingText.trimStart():e};var Vr=/`[^`]*`/g,Yr=/`[^`]*$/,Ur=/<\|\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,Ya=/"([^"]+)"\s*:\s*(?:"([^"]*)"|(\d+)|true|false|null)/g,Wr=/<\|\s*tool_calls_section_begin\s*\|>/gi,Hr=/<\|\s*tool_calls_section_end\s*\|>/gi,qa=/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi;var Gr=e=>!e||typeof e!="string"?e:e.replace(/(```[\s\S]*?```|`[^`]*`)|(<(?:\w+)(?:[^>]*)>\r?\n?|\r?\n?<\/\w+(?:[^>]*)>)/gi,(t,n)=>n||""),qr=e=>{if(!e||typeof e!="string")return e;let t=ko(e);if(!t||t.length===0)return e;let n=t[t.length-1];if(!n.fullMatch)return e;let s=e.lastIndexOf(n.fullMatch);if(s===-1)return e;let o=s+n.fullMatch.length;return e.substring(0,o).trimEnd()},ii=null,as={},jn={key:null,value:null},Yt=e=>e&&e.replace(/(?:(\x1b\[\d+m))?([✔✘✖🔍📖→➕↻↷•🛇])(?:(\x1b\[\d+m))?\s*\b(Clicked|Located|Dragged|Scrolled|Typed|Pressed Key|Recaptured Screen|Created|Read Skill|Read Documentation|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|Execution Error|Loop Detected|Contacting Ancestors)\b/ig,(t,n,s,o,c)=>`${n||""}${s}${o||""} \x1B[95m${c}\x1B[0m`),za=async(e,t=8,n=1e3,s=8e3,o=null)=>{let c=0;for(;;){if(o?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{return await e()}catch(f){if(o?.aborted||f?.name==="AbortError"||f?.message==="Subagent task was cancelled."||(c++,c>=t))throw f;let l=Math.min(n*Math.pow(2,c-1),s);await new Promise((k,m)=>{let g=setTimeout(k,l);o&&o.addEventListener("abort",()=>{clearTimeout(g),m(new DOMException("The user aborted a request.","AbortError"))})})}}},wt=!1;var Xa=e=>{let t=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,c,f)=>{let l=o.fullText||o.text||"";if(o.role==="user"&&c<f.length-1)if(l.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")){let k=l.indexOf("**CONTEXT SUMMARY OF PREVIOUS TURNS");if(k!==-1){let g=l.substring(0,k).lastIndexOf("[SYSTEM METADATA]");g!==-1?l=l.substring(g).trim():l=l.substring(k).trim()}}else{let k=l.lastIndexOf("[USER]"),m=l.lastIndexOf("[USER PROMPT]");k!==-1?l=l.substring(k+6).trim():m!==-1&&(l=l.substring(m).trim())}return{...o,text:l}}),n=[],s=0;for(;s<t.length;){let o=t[s];if(o.role==="user")n.push(o),s++;else{let c=[];for(;s<t.length&&t[s].role!=="user";)c.push(t[s]),s++;let f=[],l=[],k=!1,m=()=>{f.length>0&&(n.push({role:"agent",text:"combined"}),f=[]),l.length>0&&(n.push({role:"system",text:"combined"}),l=[]),k=!1};c.forEach(g=>{let T=g.role==="system"&&(g.text?.startsWith("[ACTION RESULT]")||g.text?.startsWith("[TOOL RESULT]")||g.text?.startsWith("SUCCESS:")||g.text?.startsWith("ERROR:")||g.fullText?.startsWith("[ACTION RESULT]")||g.fullText?.startsWith("[TOOL RESULT]")||g.fullText?.startsWith("SUCCESS:")||g.fullText?.startsWith("ERROR:")),p=g.fullText||g.text||"",i=p.trim();if(!(!i&&!g.binaryPart)){if(T)l.push(i);else if(g.role==="agent"){!k&&l.length>0&&m();let u=p.endsWith(`
593
+ `),w=i.toLowerCase().includes("tool:")||i.toLowerCase().includes("action:");f.push(i),w&&u?k=!0:k=!1}}}),m()}}return n.length},Ja=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),df=()=>{wt=!0},ff=()=>wt,si={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",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"},Kn=(e,t)=>{try{let n=ne(t),s=e.toLowerCase().replace(/_/g,"");if(s==="invokesync"||s==="invoke")return n.title||(n.task?n.task.substring(0,30):null);if(s==="getprogress"||s==="cancel"||s==="steer"||s==="steersubagent")return n.id||n.taskId;let o=n.name||n.path||n.targetFile||n.TargetFile||n.directory||n.file||n.query;return o?ie.basename(o.replace(/["']/g,"").replace(/\\/g,"/")):null}catch{return null}},ri=e=>e?new Kr({apiKey:e}):ii,uf=async(e,t,n,s,o={})=>{let{onStatus:l,onMemoryUpdated:k,onBackgroundIncrement:m}=o,{profile:g,thinkingLevel:T,mode:p,janitorModel:i,chatId:u,systemSettings:w,sessionStats:I,aiProvider:h="Google",apiKey:A}=e,$=process.env.NVIDIA_BASE_URL||h==="Ollama"||h==="InferX"||h==="SenseNova"||h==="AIHubMix"||h==="Poolside"||h==="9router"||h==="ExpLabs"||h==="ExperientialLabs"?!1:w?.memory!==!1,x=Ct(Wn,[]).map(L=>`- [${L.id}]: ${L.memory}`).join(`
595
594
  `),_=s.slice(0,-1).filter(L=>L.text&&!L.text.includes("[ACTION RESULT]")&&!L.text.includes("[TOOL RESULT]")&&!L.text.includes("OBSERVATION:")&&!L.text.startsWith("[TERMINAL_RECORD]")&&!L.isTerminalRecord&&!L.isMeta&&!L.isLogo&&!String(L.id).startsWith("welcome")&&!String(L.id).startsWith("logo")).slice(-14).map(L=>{let F=qt(Ja(L.text)).replace(/\[(?:tool|action):(?:functions\.)?.*?\]/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[METADATA \(PRIORITY: DYNAMIC\)\] Time: ([^|\n]+)/g,(G,ye)=>`[METADATA (PRIORITY: DYNAMIC)] Time: ${ye.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,`
596
595
  `).replace(/\n\n/g,`
597
596
  `).replace(/\\n\\n/g,"").trim(),Ee=L.role==="user"?8192:32768,oe=F.substring(0,Ee);F.length>Ee&&(oe+=`
@@ -604,11 +603,11 @@ ${T[7]}
604
603
  ${v.length>8192?`... (truncated) ...
605
604
 
606
605
  `:""}
607
- [AGENT (current turn)]: ${E}`;_.push({role:"user",parts:[{text:P}]});let re=await Ss("NVIDIA"),Q=(await ao()).quotas?.providerTiers?.NVIDIA==="Free",ke="",ae=0,it=$?12:-1;for(;ae<=it;)try{if(!await ki("background",e))return;let L="",F=null,Ee=!1,oe=h;try{let ye=new Promise((Je,xe)=>setTimeout(()=>xe(new Error("JANITOR_TIMEOUT")),1e4)),Re=h==="Google"&&ae>=0&&ae<6&&re&&Q,ve=h==="DeepSeek"&&ae<4&&re&&Q;Ee=Re||ve,oe=Ee?"NVIDIA":h;let Ie=(async()=>{if(h==="OpenRouter"){let Je=pe("janitor_open_router"),te=es(A,Je,_,r,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),Wt=await te.next();return{iterator:te,firstResult:Wt}}else if(h==="DeepSeek"&&!Ee){let xe=Jo(A,pe("deepseek_fast_fallback"),_,r,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),te=await xe.next();return{iterator:xe,firstResult:te}}else if(h==="Mistral"&&!Ee){let xe=Qo(A,pe("mistral_janitor_fallback"),_,r,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),te=await xe.next();return{iterator:xe,firstResult:te}}else if(h==="NVIDIA"||Ee){let xe=Zo(Ee?re:A,pe("nvidia_janitor_fallback"),_,r,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),te=await xe.next();return{iterator:xe,firstResult:te}}else if(h==="InferX"){let xe=ts(A,targetModel||pe("inferx_fallback")||"deepseek-v4-flash",_,r,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),te=await xe.next();return{iterator:xe,firstResult:te}}else if(h==="SenseNova"){let xe=ns(A,targetModel||pe("sensenova_fallback")||"sensenova-6.8-flash-lite",_,r,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),te=await xe.next();return{iterator:xe,firstResult:te}}else if(h==="AIHubMix"){let xe=os(A,targetModel||pe("aihubmix_fallback")||"gpt-4o-mini",_,r,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),te=await xe.next();return{iterator:xe,firstResult:te}}else if(h==="Poolside"){let xe=ss(A,targetModel||pe("poolside_fallback")||"poolside/laguna-s-2.1",_,r,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),te=await xe.next();return{iterator:xe,firstResult:te}}else if(h==="9router"||h==="9Router"){let xe=is(A,targetModel||pe("9router_fallback")||"z-ai/glm-5.3-flash",_,r,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),te=await xe.next();return{iterator:xe,firstResult:te}}else if(h==="ExpLabs"||h==="ExperientialLabs"){let xe=rs(A,targetModel||pe("explabs_fallback")||"deepseek-v4-pro-0813",_,r,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),te=await xe.next();return{iterator:xe,firstResult:te}}else{let te=(await ri(A).models.generateContentStream({model:i||(ae===it?pe("janitor_default"):pe("gemma_janitor_fallback_google")),contents:_,config:{systemInstruction:r,temperature:.7,safetySettings:[{category:In.HARM_CATEGORY_HARASSMENT,threshold:Mn.BLOCK_NONE},{category:In.HARM_CATEGORY_HATE_SPEECH,threshold:Mn.BLOCK_NONE},{category:In.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Mn.BLOCK_NONE},{category:In.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Mn.BLOCK_NONE}],thinkingConfig:{includeThoughts:!1,thinkingLevel:Xe.MINIMAL},serviceTier:"flex"}}))[Symbol.asyncIterator](),Wt=await te.next();return{iterator:te,firstResult:Wt}}})();if(process.stdout.isTTY){let te=(await Cs())[u]?.name||"",Wt=te&&!te.startsWith("flow-")&&!te.startsWith("Session ")?te:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${Wt}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${Wt}\x07`)}let{iterator:Dn,firstResult:nn}=await Promise.race([Ie,ye]),{value:pt,done:kt}=nn;if(!kt&&pt){let Je=pt.candidates?.[0]?.content?.parts,xe=Je?oe==="Google"?Je[1]?.text||Je[0]?.text||"":Je.filter(te=>te.text&&!te.thought).map(te=>te.text).join(""):typeof pt.text=="function"?pt.text():"";xe&&(L+=xe),F=pt.usageMetadata;for await(let te of{[Symbol.asyncIterator]:()=>Dn}){let Wt=te.candidates?.[0]?.content?.parts,On=Wt?oe==="Google"?Wt[1]?.text||Wt[0]?.text||"":Wt.filter(Ln=>Ln.text&&!Ln.thought).map(Ln=>Ln.text).join(""):typeof te.text=="function"?te.text():"";On&&(L+=On),F=te.usageMetadata}}}catch(ye){throw ye}if(L){if(ke=L,F){let ye=F.totalTokenCount||0,Re=F.cachedContentTokenCount||0,ve=(F.candidatesTokenCount||0)+(oe==="Google"&&F.thoughtsTokenCount||0),Ie=Ee?pe("nvidia_janitor_fallback"):oe==="DeepSeek"?pe("deepseek_fast_fallback"):oe==="ExpLabs"||oe==="ExperientialLabs"?pe("explabs_fallback")||"deepseek-v4-pro-0813":oe==="OpenRouter"?pe("janitor_open_router"):i||(ae===it?pe("janitor_default"):pe("gemma_janitor_fallback_google"));await Bt("tokens",ye,oe,Ie),Re>0&&await Bt("cachedTokens",Re,oe,Ie),ve>0&&await Bt("candidateTokens",ve,oe,Ie),Do({provider:oe,model:Ie,prompt:F.promptTokenCount||0,cached:Re,output:ve,reasoning:F.thoughtsTokenCount||0})}}else throw new Error("No synthesis generated by Janitor.");p&&(p(),await Rt("background"));let B=ko(ke),G=!1;for(let ye of B){let Re=ye.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(Re)&&(G=!0);let ve={chatId:u,sessionId:u,history:s},Ie=await xo(Re,ye.args,ve);Re.toLowerCase()==="memory"&&(ye.args.includes("action='user'")||ye.args.includes('action="user"'))&&!Ie.startsWith("ERROR")&&(k&&k(),process.stdout.isTTY&&(process.stdout.write("\x1B]0;Memory Updated\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=Memory Updated\x07")),await new Promise(nn=>setTimeout(nn,3e3)))}if(!G)try{let ye=Ct(Wn,[]);if(ye.length>0){let Re=[];for(let ve of ye)ve.score===void 0&&(ve.score=.5),ve.score*=.99995,ve.score<.05&&(ve.score=0),ve.score=Math.round(ve.score*1e5)/1e5,ve.score>0&&Re.push(ve);Xn(Wn,Re)}}catch{}break}catch(L){ae++;let F=new Date().toLocaleString(),Ee=L instanceof Error?(()=>{try{return JSON.parse(JSON.parse(L.message).error.message).error.message}catch{return String(L)}})():String(L);await new Promise(G=>setTimeout(G,1e3));let oe=ie.join(Cn,"janitor");if(Ue.existsSync(oe)||Ue.mkdirSync(oe,{recursive:!0}),Ue.appendFileSync(ie.join(oe,"error.log"),`ERROR [Attempt ${ae}/${it+1}] [${F}]: ${Ee}
606
+ [AGENT (current turn)]: ${E}`;_.push({role:"user",parts:[{text:P}]});let re=await Ss("NVIDIA"),Q=(await ao()).quotas?.providerTiers?.NVIDIA==="Free",ke="",ae=0,it=$?12:-1;for(;ae<=it;)try{if(!await ki("background",e))return;let L="",F=null,Ee=!1,oe=h;try{let ye=new Promise((Je,xe)=>setTimeout(()=>xe(new Error("JANITOR_TIMEOUT")),1e4)),Re=h==="Google"&&ae>=0&&ae<6&&re&&Q,ve=h==="DeepSeek"&&ae<4&&re&&Q;Ee=Re||ve,oe=Ee?"NVIDIA":h;let Ie=(async()=>{if(h==="OpenRouter"){let Je=me("janitor_open_router"),te=es(A,Je,_,r,"Fast",p,!1,null,.7)[Symbol.asyncIterator](),Wt=await te.next();return{iterator:te,firstResult:Wt}}else if(h==="DeepSeek"&&!Ee){let xe=Jo(A,me("deepseek_fast_fallback"),_,r,"Fast",p,!1,null,.7)[Symbol.asyncIterator](),te=await xe.next();return{iterator:xe,firstResult:te}}else if(h==="Mistral"&&!Ee){let xe=Qo(A,me("mistral_janitor_fallback"),_,r,"Fast",p,!1,null,.7)[Symbol.asyncIterator](),te=await xe.next();return{iterator:xe,firstResult:te}}else if(h==="NVIDIA"||Ee){let xe=Zo(Ee?re:A,me("nvidia_janitor_fallback"),_,r,"Fast",p,!1,null,.7)[Symbol.asyncIterator](),te=await xe.next();return{iterator:xe,firstResult:te}}else if(h==="InferX"){let xe=ts(A,targetModel||me("inferx_fallback")||"deepseek-v4-flash",_,r,"Fast",p,!1,null,.7)[Symbol.asyncIterator](),te=await xe.next();return{iterator:xe,firstResult:te}}else if(h==="SenseNova"){let xe=ns(A,targetModel||me("sensenova_fallback")||"sensenova-6.8-flash-lite",_,r,"Fast",p,!1,null,.7)[Symbol.asyncIterator](),te=await xe.next();return{iterator:xe,firstResult:te}}else if(h==="AIHubMix"){let xe=os(A,targetModel||me("aihubmix_fallback")||"gpt-4o-mini",_,r,"Fast",p,!1,null,.7)[Symbol.asyncIterator](),te=await xe.next();return{iterator:xe,firstResult:te}}else if(h==="Poolside"){let xe=ss(A,targetModel||me("poolside_fallback")||"poolside/laguna-s-2.1",_,r,"Fast",p,!1,null,.7)[Symbol.asyncIterator](),te=await xe.next();return{iterator:xe,firstResult:te}}else if(h==="9router"||h==="9Router"){let xe=is(A,targetModel||me("9router_fallback")||"z-ai/glm-5.3-flash",_,r,"Fast",p,!1,null,.7)[Symbol.asyncIterator](),te=await xe.next();return{iterator:xe,firstResult:te}}else if(h==="ExpLabs"||h==="ExperientialLabs"){let xe=rs(A,targetModel||me("explabs_fallback")||"deepseek-v4-pro-0813",_,r,"Fast",p,!1,null,.7)[Symbol.asyncIterator](),te=await xe.next();return{iterator:xe,firstResult:te}}else{let te=(await ri(A).models.generateContentStream({model:i||(ae===it?me("janitor_default"):me("gemma_janitor_fallback_google")),contents:_,config:{systemInstruction:r,temperature:.7,safetySettings:[{category:In.HARM_CATEGORY_HARASSMENT,threshold:Mn.BLOCK_NONE},{category:In.HARM_CATEGORY_HATE_SPEECH,threshold:Mn.BLOCK_NONE},{category:In.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Mn.BLOCK_NONE},{category:In.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Mn.BLOCK_NONE}],thinkingConfig:{includeThoughts:!1,thinkingLevel:Xe.MINIMAL},serviceTier:"flex"}}))[Symbol.asyncIterator](),Wt=await te.next();return{iterator:te,firstResult:Wt}}})();if(process.stdout.isTTY){let te=(await Cs())[u]?.name||"",Wt=te&&!te.startsWith("flow-")&&!te.startsWith("Session ")?te:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${Wt}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${Wt}\x07`)}let{iterator:Dn,firstResult:nn}=await Promise.race([Ie,ye]),{value:mt,done:kt}=nn;if(!kt&&mt){let Je=mt.candidates?.[0]?.content?.parts,xe=Je?oe==="Google"?Je[1]?.text||Je[0]?.text||"":Je.filter(te=>te.text&&!te.thought).map(te=>te.text).join(""):typeof mt.text=="function"?mt.text():"";xe&&(L+=xe),F=mt.usageMetadata;for await(let te of{[Symbol.asyncIterator]:()=>Dn}){let Wt=te.candidates?.[0]?.content?.parts,On=Wt?oe==="Google"?Wt[1]?.text||Wt[0]?.text||"":Wt.filter(Ln=>Ln.text&&!Ln.thought).map(Ln=>Ln.text).join(""):typeof te.text=="function"?te.text():"";On&&(L+=On),F=te.usageMetadata}}}catch(ye){throw ye}if(L){if(ke=L,F){let ye=F.totalTokenCount||0,Re=F.cachedContentTokenCount||0,ve=(F.candidatesTokenCount||0)+(oe==="Google"&&F.thoughtsTokenCount||0),Ie=Ee?me("nvidia_janitor_fallback"):oe==="DeepSeek"?me("deepseek_fast_fallback"):oe==="ExpLabs"||oe==="ExperientialLabs"?me("explabs_fallback")||"deepseek-v4-pro-0813":oe==="OpenRouter"?me("janitor_open_router"):i||(ae===it?me("janitor_default"):me("gemma_janitor_fallback_google"));await Bt("tokens",ye,oe,Ie),Re>0&&await Bt("cachedTokens",Re,oe,Ie),ve>0&&await Bt("candidateTokens",ve,oe,Ie),Do({provider:oe,model:Ie,prompt:F.promptTokenCount||0,cached:Re,output:ve,reasoning:F.thoughtsTokenCount||0})}}else throw new Error("No synthesis generated by Janitor.");m&&(m(),await Rt("background"));let B=ko(ke),G=!1;for(let ye of B){let Re=ye.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(Re)&&(G=!0);let ve={chatId:u,sessionId:u,history:s},Ie=await xo(Re,ye.args,ve);Re.toLowerCase()==="memory"&&(ye.args.includes("action='user'")||ye.args.includes('action="user"'))&&!Ie.startsWith("ERROR")&&(k&&k(),process.stdout.isTTY&&(process.stdout.write("\x1B]0;Memory Updated\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=Memory Updated\x07")),await new Promise(nn=>setTimeout(nn,3e3)))}if(!G)try{let ye=Ct(Wn,[]);if(ye.length>0){let Re=[];for(let ve of ye)ve.score===void 0&&(ve.score=.5),ve.score*=.99995,ve.score<.05&&(ve.score=0),ve.score=Math.round(ve.score*1e5)/1e5,ve.score>0&&Re.push(ve);Xn(Wn,Re)}}catch{}break}catch(L){ae++;let F=new Date().toLocaleString(),Ee=L instanceof Error?(()=>{try{return JSON.parse(JSON.parse(L.message).error.message).error.message}catch{return String(L)}})():String(L);await new Promise(G=>setTimeout(G,1e3));let oe=ie.join(Cn,"janitor");if(Ue.existsSync(oe)||Ue.mkdirSync(oe,{recursive:!0}),Ue.appendFileSync(ie.join(oe,"error.log"),`ERROR [Attempt ${ae}/${it+1}] [${F}]: ${Ee}
608
607
 
609
608
  `),ae>it)break;let B=Math.min(750*Math.pow(2,ae-1),5e3);await new Promise(G=>setTimeout(G,B))}if(ae){let L=ie.join(Cn,"janitor");Ue.appendFileSync(ie.join(L,"error.log"),`-----------------------------------------------------------------------------
610
609
 
611
- `)}if(process.stdout.isTTY)try{let Ee=(await Cs())[u]?.name||"",oe=Ee&&!Ee.startsWith("flow-")&&!Ee.startsWith("Session ")?Ee:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${oe}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${oe}\x07`)}catch{process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")}},Qa=e=>{let t=qt(e),n=Es?t:t.replace(Vr,o=>" ".repeat(o.length)).replace(Yr,o=>" ".repeat(o.length));wo.lastIndex=0;let s;for(;(s=wo.exec(n))!==null;){let o=s.index+s[0].length-1,c=0,f=null,l=!1,k=!1;for(let p=o;p<n.length;p++){let g=t[p];if(!f&&(g==='"'||g==="'"||g==="`")?(f=g,l=!1):f&&g===f&&!l&&(f=null),!f&&(g==="("?c++:g===")"&&c--,c===0)){let T=p+1;for(;T<n.length&&/\s/.test(n[T]);)T++;if(T<n.length&&n[T]==="]"){k=!0,wo.lastIndex=T+1;break}}g==="\\"?l=!l:l=!1}if(!k)return{inside:!0,toolName:s[1],startIndex:s.index,args:t.substring(s.index+s[0].length)}}return{inside:!1}},zr=(e,t=!0)=>{let n=wo;n.lastIndex=0;let s="",o=0,c;for(;(c=n.exec(e))!==null;){let f=e.substring(o,c.index);s+=t&&o===0?qt(f):f;let l=c.index+c[0].length-1,k=0,p=null,g=-1;for(let T=l;T<e.length;T++){let m=e[T];if(p){if(m===p){let i=0;for(let u=T-1;u>=0&&e[u]==="\\";u--)i++;i%2===0&&(p=null)}}else if(m==='"'||m==="'"||m==="`")p=m;else if(m==="(")k++;else if(m===")"&&(k--,k===0)){let i=T+1;for(;i<e.length&&/\s/.test(e[i]);)i++;if(i<e.length&&e[i]==="]"){g=i;break}}}if(g!==-1)s+="[tool:functions."+c[1]+"()]",o=g+1,n.lastIndex=o;else{s+="[tool:functions."+c[1]+"(",o=e.length;break}}return o<e.length&&(s+=t&&o===0?qt(e.substring(o)):e.substring(o)),s},Za=(e,t,n)=>{let s=wo;s.lastIndex=0;let o="",c=0,f;for(;(f=s.exec(e))!==null;){let l=e.substring(c,f.index);o+=l.replace(t,n);let k=f.index+f[0].length-1,p=0,g=null,T=-1;for(let m=k;m<e.length;m++){let i=e[m];if(g){if(i===g){let u=0;for(let w=m-1;w>=0&&e[w]==="\\";w--)u++;u%2===0&&(g=null)}}else if(i==='"'||i==="'"||i==="`")g=i;else if(i==="(")p++;else if(i===")"&&(p--,p===0)){let u=m+1;for(;u<e.length&&/\s/.test(e[u]);)u++;if(u<e.length&&e[u]==="]"){T=u;break}}}if(T!==-1)o+=e.substring(f.index,T+1),c=T+1,s.lastIndex=c;else{o+=e.substring(f.index),c=e.length;break}}return c<e.length&&(o+=e.substring(c).replace(t,n)),o},jr=e=>zr(e,!0),el=e=>{if(!e)return e;let t={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"},n=o=>o.split("_").map(c=>c.charAt(0).toUpperCase()+c.slice(1)).join("");Ur.lastIndex=0;let s=e.replace(Ur,(o,c,f)=>{let l="";try{let g=JSON.parse(f.trim());g&&typeof g=="object"&&(l=Object.entries(g).map(([m,i])=>{let u=typeof i=="string"?i:JSON.stringify(i);return`${m}=${JSON.stringify(u)}`}).join(", "))}catch{let T=[],m=Ya;m.lastIndex=0;let i;for(;(i=m.exec(f))!==null;){let u=i[1],w=i[2]!==void 0?i[2]:i[0].split(":").slice(1).join(":").trim();T.push(`${u}=${JSON.stringify(w)}`)}T.length>0?l=T.join(", "):l=f.trim()}let k=c.toLowerCase().replace(/_/g,"");return`[tool:functions.${t[k]||n(c)}(${l})]`});return Wr.lastIndex=0,Hr.lastIndex=0,s=s.replace(Wr,""),s=s.replace(Hr,""),s},tl=/(?:path|query|url|keyword|command|method|title|task|id)\s*=\s*['"`]?\s*\.\.\.\s*['"`]?/i,nl=/^['"`]?\s*\.\.\.\s*['"`]?$/,bn=e=>{if(e==null)return!1;let t=String(e).trim();return t==="..."||t==="\u2026"||nl.test(t)},ko=e=>{if(!e)return[];let t=el(e),n=qt(t),s=[],o=Es?n:n.replace(Vr,l=>" ".repeat(l.length)).replace(Yr,l=>" ".repeat(l.length)),c=Ua;c.lastIndex=0;let f;for(;(f=c.exec(o))!==null;){let l=f[1],k=f.index+f[0].length-1,p=0,g=null,T=-1,m=-1;for(let i=k;i<o.length;i++){let u=n[i];if(g){if(u===g){let w=0;for(let I=i-1;I>=0&&n[I]==="\\";I--)w++;w%2===0&&(g=null)}}else if(u==='"'||u==="'"||u==="`")g=u;else if(u==="(")p++;else if(u===")"&&(p--,p===0)){m=i;let w=i+1;for(;w<o.length&&/\s/.test(o[w]);)w++;if(w<o.length&&o[w]==="]"){T=w;break}}}if(T!==-1){let i=n.substring(k+1,m),u=n.substring(f.index,T+1),w=ne(i);bn(w.path)||bn(w.query)||bn(w.url)||bn(w.keyword)||bn(w.command)||bn(w.method)||bn(w.title)||bn(w.task)||bn(w.id)||tl.test(i)||s.push({fullMatch:u,toolName:l.trim(),args:i.trim()}),c.lastIndex=T+1}}return s},gf=(e,t={})=>{if(!e)return null;if(as=t,ii=new Kr({apiKey:e}),!globalThis.__perfCleanupInstalled){globalThis.__perfCleanupInstalled=!0,setInterval(()=>{typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks())},6e4);let n=globalThis.fetch;globalThis.fetch=async(...s)=>{try{let o=await n(...s);return typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),o}catch(o){throw typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),o}}}},Xr=e=>{if(!e)return{serviceTier:void 0,cleanModel:e};let t=e.toLowerCase();return t.endsWith(":flex")?{serviceTier:"flex",cleanModel:e.slice(0,-5)}:t.endsWith(":priority")?{serviceTier:"priority",cleanModel:e.slice(0,-9)}:{serviceTier:void 0,cleanModel:e}},ls=async(e,t,n,s,o="Fast",c=.75,f="agent")=>za(async()=>{let{aiProvider:l="Google",apiKey:k,mode:p}=e,g="",T=null,m=typeof n=="string"?[{role:"user",parts:[{text:n}]}]:n,i=new AbortController,u=i.signal,w=setInterval(()=>{wt&&(i.abort(),clearInterval(w))},100);try{let I;if(l==="Ollama")I=ei(k,t,m,s,o,p,ft(t),u,c,e.systemSettings?.ollamaEndpoint||"Cloud");else if(l==="OpenRouter")I=es(k,t,m,s,o,p,ft(t),u,c);else if(l==="DeepSeek")I=Jo(k,t,m,s,o,p,ft(t),u,c);else if(l==="Mistral")I=Qo(k,t,m,s,o,p,ft(t),u,c);else if(l==="NVIDIA")I=Zo(k,t,m,s,o,p,ft(t),u,c);else if(l==="InferX")I=ts(k,t,m,s,o,p,ft(t),u,c);else if(l==="SenseNova")I=ns(k,t,m,s,o,p,ft(t),u,c);else if(l==="AIHubMix")I=os(k,t,m,s,o,p,ft(t),u,c);else if(l==="Poolside")I=ss(k,t,m,s,o,p,ft(t),u,c);else if(l==="9router"||l==="9Router")I=is(k,t,m,s,o,p,ft(t),u,c);else if(l==="ExpLabs"||l==="ExperientialLabs")I=rs(k,t,m,s,o,p,ft(t),u,c);else if(l==="TokenHarbor"||l==="Token Harbor"||l==="tokenharbor"||l==="token_harbor"||l==="thk")I=ti(k,t,m,s,o,p,ft(t),u,c);else if(l==="APInex"||l==="apinex"||l==="apx")I=ni(k,t,m,s,o,p,ft(t),u,c);else{let h=ri(k),{serviceTier:A,cleanModel:$}=Xr(t),C={systemInstruction:s,temperature:c,thinkingConfig:(()=>{let _=(t||"").toLowerCase(),M=_.includes("gemma-4")||_.startsWith("gemma"),y=_.includes("gemini-3");if(M||y)return M?o.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:Xe.MINIMAL}:{includeThoughts:!0,thinkingLevel:Xe.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:_.includes("pro")?Xe.LOW:Xe.MINIMAL,Low:Xe.LOW,Medium:Xe.MEDIUM,Standard:Xe.MEDIUM,High:Xe.HIGH,xHigh:Xe.HIGH}[o]||Xe.MEDIUM};{let a={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[o]||2048;return a===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:a}}})()};A&&(C.serviceTier=A),I=await h.models.generateContentStream({model:$,contents:m,config:C},{signal:u})}for await(let h of I){if(wt)throw new Error("Subagent task was cancelled.");if(e?.taskId&&typeof Vt<"u"){let C=Vt.find(x=>x.id===e.taskId);if(C&&C.status==="cancelled")throw new Error("Subagent task was cancelled.")}let A="";if(h.candidates?.[0]?.content?.parts)for(let C of h.candidates[0].content.parts)C.text&&!C.thought&&(g+=C.text,A+=C.text);let $=A?As(A):0;e&&typeof e.onTokenChunk=="function"&&e.onTokenChunk(A,$),h.usageMetadata&&(T=h.usageMetadata)}}finally{clearInterval(w)}if(T){let I=T.totalTokenCount||0,h=T.cachedContentTokenCount||0,A=(T.candidatesTokenCount||0)+(l==="Google"&&T.thoughtsTokenCount||0);await Bt("tokens",I,l,t),h>0&&await Bt("cachedTokens",h,l,t),A>0&&await Bt("candidateTokens",A,l,t),Do({provider:l,model:t,prompt:T.promptTokenCount||0,cached:h,output:A,reasoning:T.thoughtsTokenCount||0}),e&&typeof e.onUsage=="function"&&e.onUsage({totalTokenCount:I,cachedContentTokenCount:h,candidatesTokenCount:A})}return await Rt("agent",l),{text:g,usageMetadata:T}}),ol=async(e,t,n=null)=>{n=n||Ct(vo,{});try{let{aiProvider:s="Google"}=t;if(Object.values(n).flat().length<=5)return;let c=Object.keys(n).filter(m=>m!==e&&Array.isArray(n[m])&&n[m].length>2);if(c.length===0)return;let f=`You are a silent background process for the FluxFlow CLI Agent.
610
+ `)}if(process.stdout.isTTY)try{let Ee=(await Cs())[u]?.name||"",oe=Ee&&!Ee.startsWith("flow-")&&!Ee.startsWith("Session ")?Ee:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${oe}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${oe}\x07`)}catch{process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")}},Qa=e=>{let t=qt(e),n=Es?t:t.replace(Vr,o=>" ".repeat(o.length)).replace(Yr,o=>" ".repeat(o.length));wo.lastIndex=0;let s;for(;(s=wo.exec(n))!==null;){let o=s.index+s[0].length-1,c=0,f=null,l=!1,k=!1;for(let m=o;m<n.length;m++){let g=t[m];if(!f&&(g==='"'||g==="'"||g==="`")?(f=g,l=!1):f&&g===f&&!l&&(f=null),!f&&(g==="("?c++:g===")"&&c--,c===0)){let T=m+1;for(;T<n.length&&/\s/.test(n[T]);)T++;if(T<n.length&&n[T]==="]"){k=!0,wo.lastIndex=T+1;break}}g==="\\"?l=!l:l=!1}if(!k)return{inside:!0,toolName:s[1],startIndex:s.index,args:t.substring(s.index+s[0].length)}}return{inside:!1}},zr=(e,t=!0)=>{let n=wo;n.lastIndex=0;let s="",o=0,c;for(;(c=n.exec(e))!==null;){let f=e.substring(o,c.index);s+=t&&o===0?qt(f):f;let l=c.index+c[0].length-1,k=0,m=null,g=-1;for(let T=l;T<e.length;T++){let p=e[T];if(m){if(p===m){let i=0;for(let u=T-1;u>=0&&e[u]==="\\";u--)i++;i%2===0&&(m=null)}}else if(p==='"'||p==="'"||p==="`")m=p;else if(p==="(")k++;else if(p===")"&&(k--,k===0)){let i=T+1;for(;i<e.length&&/\s/.test(e[i]);)i++;if(i<e.length&&e[i]==="]"){g=i;break}}}if(g!==-1)s+="[tool:functions."+c[1]+"()]",o=g+1,n.lastIndex=o;else{s+="[tool:functions."+c[1]+"(",o=e.length;break}}return o<e.length&&(s+=t&&o===0?qt(e.substring(o)):e.substring(o)),s},Za=(e,t,n)=>{let s=wo;s.lastIndex=0;let o="",c=0,f;for(;(f=s.exec(e))!==null;){let l=e.substring(c,f.index);o+=l.replace(t,n);let k=f.index+f[0].length-1,m=0,g=null,T=-1;for(let p=k;p<e.length;p++){let i=e[p];if(g){if(i===g){let u=0;for(let w=p-1;w>=0&&e[w]==="\\";w--)u++;u%2===0&&(g=null)}}else if(i==='"'||i==="'"||i==="`")g=i;else if(i==="(")m++;else if(i===")"&&(m--,m===0)){let u=p+1;for(;u<e.length&&/\s/.test(e[u]);)u++;if(u<e.length&&e[u]==="]"){T=u;break}}}if(T!==-1)o+=e.substring(f.index,T+1),c=T+1,s.lastIndex=c;else{o+=e.substring(f.index),c=e.length;break}}return c<e.length&&(o+=e.substring(c).replace(t,n)),o},jr=e=>zr(e,!0),el=e=>{if(!e)return e;let t={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"},n=o=>o.split("_").map(c=>c.charAt(0).toUpperCase()+c.slice(1)).join("");Ur.lastIndex=0;let s=e.replace(Ur,(o,c,f)=>{let l="";try{let g=JSON.parse(f.trim());g&&typeof g=="object"&&(l=Object.entries(g).map(([p,i])=>{let u=typeof i=="string"?i:JSON.stringify(i);return`${p}=${JSON.stringify(u)}`}).join(", "))}catch{let T=[],p=Ya;p.lastIndex=0;let i;for(;(i=p.exec(f))!==null;){let u=i[1],w=i[2]!==void 0?i[2]:i[0].split(":").slice(1).join(":").trim();T.push(`${u}=${JSON.stringify(w)}`)}T.length>0?l=T.join(", "):l=f.trim()}let k=c.toLowerCase().replace(/_/g,"");return`[tool:functions.${t[k]||n(c)}(${l})]`});return Wr.lastIndex=0,Hr.lastIndex=0,s=s.replace(Wr,""),s=s.replace(Hr,""),s},tl=/(?:path|query|url|keyword|command|method|title|task|id)\s*=\s*['"`]?\s*\.\.\.\s*['"`]?/i,nl=/^['"`]?\s*\.\.\.\s*['"`]?$/,bn=e=>{if(e==null)return!1;let t=String(e).trim();return t==="..."||t==="\u2026"||nl.test(t)},ko=e=>{if(!e)return[];let t=el(e),n=qt(t),s=[],o=Es?n:n.replace(Vr,l=>" ".repeat(l.length)).replace(Yr,l=>" ".repeat(l.length)),c=Ua;c.lastIndex=0;let f;for(;(f=c.exec(o))!==null;){let l=f[1],k=f.index+f[0].length-1,m=0,g=null,T=-1,p=-1;for(let i=k;i<o.length;i++){let u=n[i];if(g){if(u===g){let w=0;for(let I=i-1;I>=0&&n[I]==="\\";I--)w++;w%2===0&&(g=null)}}else if(u==='"'||u==="'"||u==="`")g=u;else if(u==="(")m++;else if(u===")"&&(m--,m===0)){p=i;let w=i+1;for(;w<o.length&&/\s/.test(o[w]);)w++;if(w<o.length&&o[w]==="]"){T=w;break}}}if(T!==-1){let i=n.substring(k+1,p),u=n.substring(f.index,T+1),w=ne(i);bn(w.path)||bn(w.query)||bn(w.url)||bn(w.keyword)||bn(w.command)||bn(w.method)||bn(w.title)||bn(w.task)||bn(w.id)||tl.test(i)||s.push({fullMatch:u,toolName:l.trim(),args:i.trim()}),c.lastIndex=T+1}}return s},gf=(e,t={})=>{if(!e)return null;if(as=t,ii=new Kr({apiKey:e}),!globalThis.__perfCleanupInstalled){globalThis.__perfCleanupInstalled=!0,setInterval(()=>{typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks())},6e4);let n=globalThis.fetch;globalThis.fetch=async(...s)=>{try{let o=await n(...s);return typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),o}catch(o){throw typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),o}}}},Xr=e=>{if(!e)return{serviceTier:void 0,cleanModel:e};let t=e.toLowerCase();return t.endsWith(":flex")?{serviceTier:"flex",cleanModel:e.slice(0,-5)}:t.endsWith(":priority")?{serviceTier:"priority",cleanModel:e.slice(0,-9)}:{serviceTier:void 0,cleanModel:e}},ls=async(e,t,n,s,o="Fast",c=.75,f="agent")=>za(async()=>{let{aiProvider:l="Google",apiKey:k,mode:m}=e,g="",T=null,p=typeof n=="string"?[{role:"user",parts:[{text:n}]}]:n,i=new AbortController,u=i.signal,w=setInterval(()=>{wt&&(i.abort(),clearInterval(w))},100);try{let I;if(l==="Ollama")I=ei(k,t,p,s,o,m,ft(t),u,c,e.systemSettings?.ollamaEndpoint||"Cloud");else if(l==="OpenRouter")I=es(k,t,p,s,o,m,ft(t),u,c);else if(l==="DeepSeek")I=Jo(k,t,p,s,o,m,ft(t),u,c);else if(l==="Mistral")I=Qo(k,t,p,s,o,m,ft(t),u,c);else if(l==="NVIDIA")I=Zo(k,t,p,s,o,m,ft(t),u,c);else if(l==="InferX")I=ts(k,t,p,s,o,m,ft(t),u,c);else if(l==="SenseNova")I=ns(k,t,p,s,o,m,ft(t),u,c);else if(l==="AIHubMix")I=os(k,t,p,s,o,m,ft(t),u,c);else if(l==="Poolside")I=ss(k,t,p,s,o,m,ft(t),u,c);else if(l==="9router"||l==="9Router")I=is(k,t,p,s,o,m,ft(t),u,c);else if(l==="ExpLabs"||l==="ExperientialLabs")I=rs(k,t,p,s,o,m,ft(t),u,c);else if(l==="TokenHarbor"||l==="Token Harbor"||l==="tokenharbor"||l==="token_harbor"||l==="thk")I=ti(k,t,p,s,o,m,ft(t),u,c);else if(l==="APInex"||l==="apinex"||l==="apx")I=ni(k,t,p,s,o,m,ft(t),u,c);else{let h=ri(k),{serviceTier:A,cleanModel:$}=Xr(t),C={systemInstruction:s,temperature:c,thinkingConfig:(()=>{let _=(t||"").toLowerCase(),M=_.includes("gemma-4")||_.startsWith("gemma"),y=_.includes("gemini-3");if(M||y)return M?o.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:Xe.MINIMAL}:{includeThoughts:!0,thinkingLevel:Xe.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:_.includes("pro")?Xe.LOW:Xe.MINIMAL,Low:Xe.LOW,Medium:Xe.MEDIUM,Standard:Xe.MEDIUM,High:Xe.HIGH,xHigh:Xe.HIGH}[o]||Xe.MEDIUM};{let a={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[o]||2048;return a===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:a}}})()};A&&(C.serviceTier=A),I=await h.models.generateContentStream({model:$,contents:p,config:C},{signal:u})}for await(let h of I){if(wt)throw new Error("Subagent task was cancelled.");if(e?.taskId&&typeof Vt<"u"){let C=Vt.find(x=>x.id===e.taskId);if(C&&C.status==="cancelled")throw new Error("Subagent task was cancelled.")}let A="";if(h.candidates?.[0]?.content?.parts)for(let C of h.candidates[0].content.parts)C.text&&!C.thought&&(g+=C.text,A+=C.text);let $=A?As(A):0;e&&typeof e.onTokenChunk=="function"&&e.onTokenChunk(A,$),h.usageMetadata&&(T=h.usageMetadata)}}finally{clearInterval(w)}if(T){let I=T.totalTokenCount||0,h=T.cachedContentTokenCount||0,A=(T.candidatesTokenCount||0)+(l==="Google"&&T.thoughtsTokenCount||0);await Bt("tokens",I,l,t),h>0&&await Bt("cachedTokens",h,l,t),A>0&&await Bt("candidateTokens",A,l,t),Do({provider:l,model:t,prompt:T.promptTokenCount||0,cached:h,output:A,reasoning:T.thoughtsTokenCount||0}),e&&typeof e.onUsage=="function"&&e.onUsage({totalTokenCount:I,cachedContentTokenCount:h,candidatesTokenCount:A})}return await Rt("agent",l),{text:g,usageMetadata:T}}),ol=async(e,t,n=null)=>{n=n||Ct(vo,{});try{let{aiProvider:s="Google"}=t;if(Object.values(n).flat().length<=5)return;let c=Object.keys(n).filter(p=>p!==e&&Array.isArray(n[p])&&n[p].length>2);if(c.length===0)return;let f=`You are a silent background process for the FluxFlow CLI Agent.
612
611
  Your task is to summarize or merge temporary context memories from one or more past conversation sessions.
613
612
  For each Chat ID provided, you must output a tool call to save the consolidated summary.
614
613
 
@@ -623,8 +622,8 @@ Guidelines:
623
622
 
624
623
  Chats to process:
625
624
 
626
- `,l=Ct(ks,{});for(let m of c){let u=n[m].map(I=>`- ${I}`).join(`
627
- `),w=l[m];f+=`[Chat ID: ${m}]
625
+ `,l=Ct(ks,{});for(let p of c){let u=n[p].map(I=>`- ${I}`).join(`
626
+ `),w=l[p];f+=`[Chat ID: ${p}]
628
627
  `,w?(f+=`- Existing Summary: "${w}"
629
628
  `,f+=`
630
629
  -- New Memories to integrate:
@@ -633,7 +632,7 @@ ${u}
633
632
  `):f+=`-- Individual Memories:
634
633
  ${u}
635
634
 
636
- `}let k=0,p=5,g=!1,T=pe("gemma_janitor_fallback_google");for(s==="OpenRouter"&&(T=pe("janitor_open_router")),s==="DeepSeek"&&(T=pe("deepseek_level_1")),s==="Mistral"&&(T=pe("mistral_level_1")),s==="NVIDIA"&&(T=pe("nvidia_janitor_fallback")),s==="InferX"&&(T=pe("inferx_fallback")),s==="SenseNova"&&(T=pe("sensenova_fallback")),s==="AIHubMix"&&(T=pe("aihubmix_fallback")),s==="Poolside"&&(T=pe("poolside_fallback")),(s==="9router"||s==="9Router")&&(T=pe("9router_fallback"));k<=p&&!g;){k++;try{let i=(await ls(t,T,f,null,"Fast",.75,"background")).text||"",u=ko(i);if(u.length===0)throw new Error("No tool calls detected in synthesis response");for(let w of u){let I=w.toolName;["saveSummary","saveSumary","SaveSummary","SaveSumary"].includes(I)&&await xo(I,w.args,{chatId:e})}g=!0}catch(m){if(k>=p)throw new Error(`Failed after ${p} attempts. Last error: ${m.message}`)}}}catch(s){let o=s instanceof Error?(()=>{try{return JSON.parse(JSON.parse(s.message).error.message).error.message}catch{return String(s)}})():String(s),c=ie.join(Cn,"janitor");Ue.existsSync(c)||Ue.mkdirSync(c,{recursive:!0}),Ue.appendFileSync(ie.join(c,"error.log"),`[${new Date().toLocaleString()}] Past memory batch consolidation error: ${o}
635
+ `}let k=0,m=5,g=!1,T=me("gemma_janitor_fallback_google");for(s==="OpenRouter"&&(T=me("janitor_open_router")),s==="DeepSeek"&&(T=me("deepseek_level_1")),s==="Mistral"&&(T=me("mistral_level_1")),s==="NVIDIA"&&(T=me("nvidia_janitor_fallback")),s==="InferX"&&(T=me("inferx_fallback")),s==="SenseNova"&&(T=me("sensenova_fallback")),s==="AIHubMix"&&(T=me("aihubmix_fallback")),s==="Poolside"&&(T=me("poolside_fallback")),(s==="9router"||s==="9Router")&&(T=me("9router_fallback"));k<=m&&!g;){k++;try{let i=(await ls(t,T,f,null,"Fast",.75,"background")).text||"",u=ko(i);if(u.length===0)throw new Error("No tool calls detected in synthesis response");for(let w of u){let I=w.toolName;["saveSummary","saveSumary","SaveSummary","SaveSumary"].includes(I)&&await xo(I,w.args,{chatId:e})}g=!0}catch(p){if(k>=m)throw new Error(`Failed after ${m} attempts. Last error: ${p.message}`)}}}catch(s){let o=s instanceof Error?(()=>{try{return JSON.parse(JSON.parse(s.message).error.message).error.message}catch{return String(s)}})():String(s),c=ie.join(Cn,"janitor");Ue.existsSync(c)||Ue.mkdirSync(c,{recursive:!0}),Ue.appendFileSync(ie.join(c,"error.log"),`[${new Date().toLocaleString()}] Past memory batch consolidation error: ${o}
637
636
  `)}},hf=async(e,t,n=!1)=>{let{chatId:s,aiProvider:o="Google"}=e,c=ie.join(Ro,"chat-summaries.json"),f=i=>i.filter(u=>(u.role==="user"||u.role==="agent"||u.role==="system")&&u.role!=="think"&&!u.isVisualFeedback&&!u.isMeta&&!u.isTerminalRecord&&!(u.text&&u.text.includes("[TERMINAL_RECORD]"))&&!String(u.id).startsWith("welcome")).map(u=>{let w=u.fullText||u.text||"",I=u.role==="system"||w.startsWith("[ACTION RESULT]:")||w.startsWith("[TOOL RESULT]:")||u.text&&(u.text.startsWith("[ACTION RESULT]:")||u.text.startsWith("[TOOL RESULT]:")),h=w;return I&&(w.includes("[ACTION RESULT]:")||w.includes("[TOOL RESULT]:")||u.text&&(u.text.includes("[ACTION RESULT]:")||u.text.includes("[TOOL RESULT]:")))?h="[ACTION RESULT]: ...truncated for summary":h=h.replace(/(\[(?:tool|action):[a-zA-Z0-9_\.]+)\([\s\S]*?\)(\])/g,"$1(...)$2"),`[${I?"ACTION":u.role==="agent"?"AGENT":"USER"}]: ${h}`}).join(`
638
637
 
639
638
  `),l=async(i,u)=>{let w="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.",I=u?`Here is the previous summary:
@@ -645,9 +644,9 @@ ${i}
645
644
  Provide a new consolidated summary of the entire session.`:`Here is the conversation history:
646
645
  ${i}
647
646
 
648
- Provide a consolidated summary of the entire session.`,h=pe("gemma_janitor_fallback_google");o==="OpenRouter"&&(h=pe("janitor_open_router")),o==="DeepSeek"&&(h=pe("deepseek_level_1")),o==="Mistral"&&(h=pe("mistral_level_1")),o==="NVIDIA"&&(h=pe("nvidia_chat_summarizer_fallback")),o==="InferX"&&(h=pe("inferx_fallback")),o==="SenseNova"&&(h=pe("sensenova_fallback")),o==="AIHubMix"&&(h=pe("aihubmix_fallback")),o==="Poolside"&&(h=pe("poolside_fallback")),(o==="9router"||o==="9Router")&&(h=pe("9router_fallback")),(o==="ExpLabs"||o==="ExperientialLabs")&&(h=pe("explabs_fallback")||"deepseek-v4-pro-0813"),(o==="TokenHarbor"||o==="Token Harbor"||o==="tokenharbor"||o==="token_harbor"||o==="thk")&&(h=pe("tokenharbor_fallback")||"deepseek-v4.1-flash:free");let A=0,$=!1,C=null;for(;A<=3&&!$;){A++;try{C=await ls(e,h,I,w,"Fast"),$=!0}catch{if(A>3){if(o==="Google")try{let _=pe("general_fallback");return(await ls(e,_,I,w,"Fast")).text||""}catch{return""}return""}}}return C&&C.text||""},k=f(t),p=Ct(c,{}),g=p[s]||{summary:"",historyLength:0};typeof g=="string"&&(g={summary:g,historyLength:0});let T=g.summary||"",m=await l(k,T);if(m){g.summary=m;let i=Xa(t);return n?g.historyLength=(g.historyLength||0)+i:g.historyLength=i,p[s]=g,Xn(c,p),m}return null},mf=e=>{try{let t=ie.join(Ro,"chat-summaries.json");if(Ue.existsSync(t)){let n=Ct(t,{});n[e]&&(delete n[e],Xn(t,n))}}catch{}},pf=async function*(e,t,n,s,o){let{profile:c,thinkingLevel:f,mode:l,janitorModel:k,chatId:p,isPlayground:g,systemSettings:T,sessionStats:m,aiProvider:i="Google",apiTier:u,wildcardTooling:w,wildercardTooling:I}=n,h=ft(e);if(!ii&&i==="Google")throw new Error("AI not initialized");let A=process.env.NVIDIA_BASE_URL||n?.aiProvider==="Ollama"||n?.aiProvider==="InferX"||n?.aiProvider==="SenseNova"||n?.aiProvider==="AIHubMix"||n?.aiProvider==="Poolside"||n?.aiProvider==="9router"||n?.aiProvider==="ExpLabs"||n?.aiProvider==="ExperientialLabs"||n?.aiProvider==="TokenHarbor"||n?.aiProvider==="Token Harbor"||n?.aiProvider==="tokenharbor"||n?.aiProvider==="token_harbor"||n?.aiProvider==="thk"||n?.aiProvider==="APInex"||n?.aiProvider==="apinex"||n?.aiProvider==="apx"?!1:T?.memory!==!1,$=t[t.length-1].text,C=ie.join(Ro,"chat-summaries.json"),x=!1,_=t.filter(d=>d.role==="user").length===1,M=$.includes("[TITLE-UPDATE]"),y=_||M,a=$.replace(/\[TITLE-UPDATE\]/g,"").trim();a=a.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),yield{type:"status",content:"[start]"},yield{type:"status",content:"Gathering Context"},await Oo.startTransaction(p,a),T?.advanceRollback&&await lo.takeInitialSnapshot(p),wt=!1;let R=null;try{let d=new AbortController;R=setInterval(()=>{wt&&(d.abort(),R&&(clearInterval(R),R=null))},400);let r=[...t.slice(0,-1)];{let Ke=Ct(C,{})[p]||{summary:"",historyLength:0};if(Ke.summary&&Ke.historyLength>0){let fn=0,ot=[];for(let Fe=0;Fe<r.length;Fe++){let st=r[Fe];(st.role==="user"||st.role==="agent"||st.role==="system")&&!String(st.id).startsWith("welcome")&&!st.isMeta&&fn++,fn>Ke.historyLength&&ot.push(st)}r=ot}}r=r.map(j=>{if(j.role==="user"&&j.text){let Ke=j.text.match(/\[USER\]([\s\S]*?)\[\/USER\]/);if(Ke)return{...j,text:Ke[1].trim()}}return{...j}});let E=process.env.HIGH_CONTEXT,v=process.env.GOOGLE_GEMMA_NONSENSE==="true"||process.env.GOOGLE_GEMMA_NONSENSE===!0||!1,P={"16k":16e3,"32k":32e3,"64k":64e3,"128k":128e3,"256k":256e3,"512k":512e3,"1M":1e6}[T?.contextLength]||256e3;if(E&&E!=="false"){let j=parseInt(E,10);!isNaN(j)&&j>=0&&j<=1e6&&(P=j)}if((i==="NVIDIA"&&(e?.includes("gpt")||e?.includes("qwen")||e?.includes("medium")||e.includes("muse"))||i==="Mistral")&&(P=126e3),i==="Google"&&e?.includes("gemma")&&v&&(P=16e3),(m?.tokens||0)>P){yield{type:"text",content:"\u2726 Maximum Context Limit Reached. Start a new chat."};return}if(_&&A){let j=Ct(vo,{});Object.values(j).flat().length>5&&(yield{type:"status",content:"Condensing past chat memories"},await ol(p,n,j))}let re=Ct(vo,{}),de=Ct(ks,{}),Q=Object.entries(re).filter(([j])=>j!==p).flatMap(([j,Ke])=>Ke),ae=[...Object.entries(de).filter(([j])=>j!==p).slice(-20).map(([j,Ke])=>`[Chat Summary]: ${Ke}`),...Q].map(j=>`- ${j}`).join(`
647
+ Provide a consolidated summary of the entire session.`,h=me("gemma_janitor_fallback_google");o==="OpenRouter"&&(h=me("janitor_open_router")),o==="DeepSeek"&&(h=me("deepseek_level_1")),o==="Mistral"&&(h=me("mistral_level_1")),o==="NVIDIA"&&(h=me("nvidia_chat_summarizer_fallback")),o==="InferX"&&(h=me("inferx_fallback")),o==="SenseNova"&&(h=me("sensenova_fallback")),o==="AIHubMix"&&(h=me("aihubmix_fallback")),o==="Poolside"&&(h=me("poolside_fallback")),(o==="9router"||o==="9Router")&&(h=me("9router_fallback")),(o==="ExpLabs"||o==="ExperientialLabs")&&(h=me("explabs_fallback")||"deepseek-v4-pro-0813"),(o==="TokenHarbor"||o==="Token Harbor"||o==="tokenharbor"||o==="token_harbor"||o==="thk")&&(h=me("tokenharbor_fallback")||"deepseek-v4.1-flash:free");let A=0,$=!1,C=null;for(;A<=3&&!$;){A++;try{C=await ls(e,h,I,w,"Fast"),$=!0}catch{if(A>3){if(o==="Google")try{let _=me("general_fallback");return(await ls(e,_,I,w,"Fast")).text||""}catch{return""}return""}}}return C&&C.text||""},k=f(t),m=Ct(c,{}),g=m[s]||{summary:"",historyLength:0};typeof g=="string"&&(g={summary:g,historyLength:0});let T=g.summary||"",p=await l(k,T);if(p){g.summary=p;let i=Xa(t);return n?g.historyLength=(g.historyLength||0)+i:g.historyLength=i,m[s]=g,Xn(c,m),p}return null},pf=e=>{try{let t=ie.join(Ro,"chat-summaries.json");if(Ue.existsSync(t)){let n=Ct(t,{});n[e]&&(delete n[e],Xn(t,n))}}catch{}},mf=async function*(e,t,n,s,o){let{profile:c,thinkingLevel:f,mode:l,janitorModel:k,chatId:m,isPlayground:g,systemSettings:T,sessionStats:p,aiProvider:i="Google",apiTier:u,wildcardTooling:w,wildercardTooling:I}=n,h=ft(e);if(!ii&&i==="Google")throw new Error("AI not initialized");let A=process.env.NVIDIA_BASE_URL||n?.aiProvider==="Ollama"||n?.aiProvider==="InferX"||n?.aiProvider==="SenseNova"||n?.aiProvider==="AIHubMix"||n?.aiProvider==="Poolside"||n?.aiProvider==="9router"||n?.aiProvider==="ExpLabs"||n?.aiProvider==="ExperientialLabs"||n?.aiProvider==="TokenHarbor"||n?.aiProvider==="Token Harbor"||n?.aiProvider==="tokenharbor"||n?.aiProvider==="token_harbor"||n?.aiProvider==="thk"||n?.aiProvider==="APInex"||n?.aiProvider==="apinex"||n?.aiProvider==="apx"?!1:T?.memory!==!1,$=t[t.length-1].text,C=ie.join(Ro,"chat-summaries.json"),x=!1,_=t.filter(d=>d.role==="user").length===1,M=$.includes("[TITLE-UPDATE]"),y=_||M,a=$.replace(/\[TITLE-UPDATE\]/g,"").trim();a=a.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),yield{type:"status",content:"[start]"},yield{type:"status",content:"Gathering Context"},await Oo.startTransaction(m,a),T?.advanceRollback&&await lo.takeInitialSnapshot(m),wt=!1;let R=null;try{let d=new AbortController;R=setInterval(()=>{wt&&(d.abort(),R&&(clearInterval(R),R=null))},400);let r=[...t.slice(0,-1)];{let Ke=Ct(C,{})[m]||{summary:"",historyLength:0};if(Ke.summary&&Ke.historyLength>0){let fn=0,ot=[];for(let Fe=0;Fe<r.length;Fe++){let st=r[Fe];(st.role==="user"||st.role==="agent"||st.role==="system")&&!String(st.id).startsWith("welcome")&&!st.isMeta&&fn++,fn>Ke.historyLength&&ot.push(st)}r=ot}}r=r.map(j=>{if(j.role==="user"&&j.text){let Ke=j.text.match(/\[USER\]([\s\S]*?)\[\/USER\]/);if(Ke)return{...j,text:Ke[1].trim()}}return{...j}});let E=process.env.HIGH_CONTEXT,v=process.env.GOOGLE_GEMMA_NONSENSE==="true"||process.env.GOOGLE_GEMMA_NONSENSE===!0||!1,P={"16k":16e3,"32k":32e3,"64k":64e3,"128k":128e3,"256k":256e3,"512k":512e3,"1M":1e6}[T?.contextLength]||256e3;if(E&&E!=="false"){let j=parseInt(E,10);!isNaN(j)&&j>=0&&j<=1e6&&(P=j)}if((i==="NVIDIA"&&(e?.includes("gpt")||e?.includes("qwen")||e?.includes("medium")||e.includes("muse"))||i==="Mistral")&&(P=126e3),i==="Google"&&e?.includes("gemma")&&v&&(P=16e3),(p?.tokens||0)>P){yield{type:"text",content:"\u2726 Maximum Context Limit Reached. Start a new chat."};return}if(_&&A){let j=Ct(vo,{});Object.values(j).flat().length>5&&(yield{type:"status",content:"Condensing past chat memories"},await ol(m,n,j))}let re=Ct(vo,{}),de=Ct(ks,{}),Q=Object.entries(re).filter(([j])=>j!==m).flatMap(([j,Ke])=>Ke),ae=[...Object.entries(de).filter(([j])=>j!==m).slice(-20).map(([j,Ke])=>`[Chat Summary]: ${Ke}`),...Q].map(j=>`- ${j}`).join(`
649
648
  `),L=Ct(Wn,[]).map(j=>`- ${j.memory}`).join(`
650
- `),F=(m?.tokens||0)>=1e4,Ee=new Date,oe=Ee.getFullYear(),B=Ee.toLocaleString("en-US",{month:"short"}).toUpperCase(),G=String(Ee.getDate()).padStart(2,"0"),ye=Ee.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}),Re=`${oe}-${B}-${G}, ${ye}`,ve=`${ye}`,Ie=j=>{try{return Ue.readdirSync(j,{withFileTypes:!0})}catch{return[]}},Dn=Array.from(new Set([...io,...ro(process.cwd())])),nn=(j,Ke=4)=>T?.indentationTree!==!1?Js(j,Ke,1,Ie,Dn):Zs(j,Ke,"",1,Ie,Dn),pt=Ct(Ts,{}),kt=pt[p],Je=kt?kt!==process.cwd():!1;pt[p]=process.cwd(),Xn(Ts,pt);let xe=Ct(C,{}),te=xe[p]||{summary:"",historyLength:0};typeof te=="string"&&(te={summary:te,historyLength:0});let Wt=t.filter(j=>(j.role==="user"||j.role==="agent"||j.role==="system")&&!String(j.id).startsWith("welcome")&&!j.isMeta).length;te.historyLength&&Wt<te.historyLength&&(te.summary="",te.historyLength=0,xe[p]=te,Xn(C,xe));let On=typeof te=="object"?te.summary||"":te||"",Ln=r.length>0;Ln&&On&&r[0]&&(r[0].role==="user"||r[0].role==="system")&&(r[0].text.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")||(r[0].text=`[SYSTEM METADATA]
649
+ `),F=(p?.tokens||0)>=1e4,Ee=new Date,oe=Ee.getFullYear(),B=Ee.toLocaleString("en-US",{month:"short"}).toUpperCase(),G=String(Ee.getDate()).padStart(2,"0"),ye=Ee.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}),Re=`${oe}-${B}-${G}, ${ye}`,ve=`${ye}`,Ie=j=>{try{return Ue.readdirSync(j,{withFileTypes:!0})}catch{return[]}},Dn=Array.from(new Set([...io,...ro(process.cwd())])),nn=(j,Ke=4)=>T?.indentationTree!==!1?Js(j,Ke,1,Ie,Dn):Zs(j,Ke,"",1,Ie,Dn),mt=Ct(Ts,{}),kt=mt[m],Je=kt?kt!==process.cwd():!1;mt[m]=process.cwd(),Xn(Ts,mt);let xe=Ct(C,{}),te=xe[m]||{summary:"",historyLength:0};typeof te=="string"&&(te={summary:te,historyLength:0});let Wt=t.filter(j=>(j.role==="user"||j.role==="agent"||j.role==="system")&&!String(j.id).startsWith("welcome")&&!j.isMeta).length;te.historyLength&&Wt<te.historyLength&&(te.summary="",te.historyLength=0,xe[m]=te,Xn(C,xe));let On=typeof te=="object"?te.summary||"":te||"",Ln=r.length>0;Ln&&On&&r[0]&&(r[0].role==="user"||r[0].role==="system")&&(r[0].text.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")||(r[0].text=`[SYSTEM METADATA]
651
650
  **CONTEXT SUMMARY OF PREVIOUS TURNS (PRIORITY: DYNAMIC)**
652
651
  ${On}
653
652
 
@@ -655,7 +654,7 @@ ${On}
655
654
  [SYSTEM METADATA]
656
655
  **CONTEXT SUMMARY OF PREVIOUS TURNS**
657
656
  ${On}
658
- `:"",ai=!!T?.dynamicDirAwareness,Jr=`${p}|${i}|${f}|${e}|${c}|${ai}`,Qr=!ai&&jn.key===Jr&&jn.value?"":`
657
+ `:"",ai=!!T?.dynamicDirAwareness,Jr=`${m}|${i}|${f}|${e}|${c}|${ai}`,Qr=!ai&&jn.key===Jr&&jn.value?"":`
659
658
  **Directory**
660
659
  CWD: `+process.cwd()+`${g?" [PLAYGROUND MODE]":""}
661
660
  `+nn(process.cwd(),4),yt=await Hn(),dn="";if(zo()&&yt.file_focused!=="none"){dn=`
@@ -706,45 +705,45 @@ WARNING: CWD Changed from previous: "${kt}" to current: "${process.cwd()}", writ
706
705
  `:""}${dn}
707
706
  Action format: [action:ActionName(...)]
708
707
  [/Metadata]
709
- ${cs}${ui}${gs}${fi}[user prompt] ${di.trim()} [/user prompt]`.trim();let hi={role:"user",text:So};To&&(hi.binaryPart=To),r.forEach(j=>{j.text&&j.role==="agent"&&(j.text=qt(j.text))}),r.push(hi),cs&&t[t.length-1]?.id&&(yield{type:"summary_injected",content:{id:t[t.length-1].id,text:So}});let Jt=null,wn=l==="Flux"?50:15;wn=l.toLowerCase().includes("cu")?75:wn;let ta=Math.floor(wn/2),mi=0,on=16;yield{type:"status",content:"Connecting"},wt=!1;let hs=[],_o=!1,pi=!1;for(let j=0;j<=wn;j++){let Ke=Math.floor(wn*.95);if(j>=Ke&&mi<Ke&&typeof n?.onAskUser=="function"){mi=Ke;try{let me="Agent has been running for a long time. Do you want to continue execution?",Ae=[{id:"continue",label:"Continue",description:"Add few more steps"},{id:"cancel",label:"Cancel",description:"Stop extending and finish current turn limit"}],ee=await n.onAskUser(me,Ae);ee&&(ee.toLowerCase().includes("continue")||ee==="Continue")&&(wn+=ta)}catch{}}let fn=await _s("agent",n);if(!fn.allowed)throw new Error(fn.reason||`Budget Exhausted for Provider (${i||"Agent"})`);let ot=[];if(_o=!1,l==="ICU"||l==="FluxCU")try{yield{type:"status",content:"Capturing Screen"},await new Promise(ee=>setTimeout(ee,1e3));let{captureGriddedScreenshot:me}=await import("./screen_grid-GBIGOR5Q.js"),Ae=await me();if(Ae&&Ae.base64){let ee="[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]",Lt={inlineData:{mimeType:Ae.mimeType,data:Ae.base64}},Mt=T?.imageHistoryCU||"Standard",At=Mt==="Low"?1:Mt==="Extended"?5:3,zt=r.filter(Ge=>Array.isArray(Ge.parts)&&Ge.parts.some(Pt=>Pt.inlineData));if(zt.length>=At){let Ge=zt.length-At+1;for(let Pt=0;Pt<Ge;Pt++){let Et=zt[Pt];Array.isArray(Et.parts)&&(Et.parts=Et.parts.filter(Tt=>!Tt.inlineData))}}if(r.length>0&&r[r.length-1].role==="user"){let Ge=r[r.length-1];typeof Ge.text=="string"&&(Ge.text+=`
708
+ ${cs}${ui}${gs}${fi}[user prompt] ${di.trim()} [/user prompt]`.trim();let hi={role:"user",text:So};To&&(hi.binaryPart=To),r.forEach(j=>{j.text&&j.role==="agent"&&(j.text=qt(j.text))}),r.push(hi),cs&&t[t.length-1]?.id&&(yield{type:"summary_injected",content:{id:t[t.length-1].id,text:So}});let Jt=null,wn=l==="Flux"?50:15;wn=l.toLowerCase().includes("cu")?75:wn;let ta=Math.floor(wn/2),pi=0,on=16;yield{type:"status",content:"Connecting"},wt=!1;let hs=[],_o=!1,mi=!1;for(let j=0;j<=wn;j++){let Ke=Math.floor(wn*.95);if(j>=Ke&&pi<Ke&&typeof n?.onAskUser=="function"){pi=Ke;try{let pe="Agent has been running for a long time. Do you want to continue execution?",Ae=[{id:"continue",label:"Continue",description:"Add few more steps"},{id:"cancel",label:"Cancel",description:"Stop extending and finish current turn limit"}],ee=await n.onAskUser(pe,Ae);ee&&(ee.toLowerCase().includes("continue")||ee==="Continue")&&(wn+=ta)}catch{}}let fn=await _s("agent",n);if(!fn.allowed)throw new Error(fn.reason||`Budget Exhausted for Provider (${i||"Agent"})`);let ot=[];if(_o=!1,l==="ICU"||l==="FluxCU")try{yield{type:"status",content:"Capturing Screen"},await new Promise(ee=>setTimeout(ee,1e3));let{captureGriddedScreenshot:pe}=await import("./screen_grid-3F55Z22R.js"),Ae=await pe();if(Ae&&Ae.base64){let ee="[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]",Lt={inlineData:{mimeType:Ae.mimeType,data:Ae.base64}},Mt=T?.imageHistoryCU||"Standard",At=Mt==="Low"?1:Mt==="Extended"?5:3,zt=r.filter(Ge=>Array.isArray(Ge.parts)&&Ge.parts.some(Pt=>Pt.inlineData));if(zt.length>=At){let Ge=zt.length-At+1;for(let Pt=0;Pt<Ge;Pt++){let Et=zt[Pt];Array.isArray(Et.parts)&&(Et.parts=Et.parts.filter(Tt=>!Tt.inlineData))}}if(r.length>0&&r[r.length-1].role==="user"){let Ge=r[r.length-1];typeof Ge.text=="string"&&(Ge.text+=`
710
709
 
711
- ${ee}`,Array.isArray(Ge.parts)||(Ge.parts=[{text:Ge.text}]),Ge.parts.push(Lt))}else r.push({role:"user",text:ee,parts:[{text:ee},Lt]})}}catch(me){console.error("Vision screenshot capture error:",me)}if(T?.compression===0&&(m?.tokens||0)>P&&(r=Ci(r,6)),j>0?yield{type:"status",content:"Working"}:yield{type:"status",content:"Connecting"},wt){try{let{clearPendingNudges:me}=await import("./subagent_state-LZCOZSUJ.js");me()}catch{}yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
710
+ ${ee}`,Array.isArray(Ge.parts)||(Ge.parts=[{text:Ge.text}]),Ge.parts.push(Lt))}else r.push({role:"user",text:ee,parts:[{text:ee},Lt]})}}catch(pe){console.error("Vision screenshot capture error:",pe)}if(T?.compression===0&&(p?.tokens||0)>P&&(r=Ci(r,6)),j>0?yield{type:"status",content:"Working"}:yield{type:"status",content:"Connecting"},wt){try{let{clearPendingNudges:pe}=await import("./subagent_state-LZCOZSUJ.js");pe()}catch{}yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
712
711
 
713
- \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}try{let{consumePendingNudges:me}=await import("./subagent_state-LZCOZSUJ.js"),Ae=me();if(Ae&&Ae.length>0){let ee=Ae.join(`
712
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}try{let{consumePendingNudges:pe}=await import("./subagent_state-LZCOZSUJ.js"),Ae=pe();if(Ae&&Ae.length>0){let ee=Ae.join(`
714
713
 
715
714
  `);r.length>0&&r[r.length-1].role==="user"?r[r.length-1].text+=`
716
715
 
717
- ${ee}`:r.push({role:"user",text:ee}),yield{type:"status",content:"Subagent Update"}}}catch{}if(s){let me=await s();me&&(me.startsWith("/btw")?r.length>0&&r[r.length-1].role==="user"?r[r.length-1].text+=`
716
+ ${ee}`:r.push({role:"user",text:ee}),yield{type:"status",content:"Subagent Update"}}}catch{}if(s){let pe=await s();pe&&(pe.startsWith("/btw")?r.length>0&&r[r.length-1].role==="user"?r[r.length-1].text+=`
718
717
 
719
718
  [system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
720
- [question] ${me.replace("/btw","").trim()} [/question]`:r.push({role:"user",text:`[system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
721
- [question] ${me.replace("/btw","").trim()} [/question]`}):r.length>0&&r[r.length-1].role==="user"?r[r.length-1].text+=`
719
+ [question] ${pe.replace("/btw","").trim()} [/question]`:r.push({role:"user",text:`[system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
720
+ [question] ${pe.replace("/btw","").trim()} [/question]`}):r.length>0&&r[r.length-1].role==="user"?r[r.length-1].text+=`
722
721
 
723
- [STEERING HINT from USER, High Priority] ${me.trim()} [/STEERING HINT]`:r.push({role:"user",text:`[STEERING HINT from USER, High Priority] ${me.trim()} [/STEERING HINT]`}),yield{type:"status",content:`${me.startsWith("/btw")?"Question Forwarded...":"Steering Hint Injected..."}`})}let Fe,st=!1,et=1,rt=1,Te="",Ve=null,sn=null,K=null,We=0,Me=[],ut=0,kn=!1,vt=!1,rn=!1,Tn=!1,Zn=!0,Qt=0,xt="",Qe="",Dt=!1,Ot=!1,Ye=!0,Se=e,qe="";for(;et<=on&&rt<=on&&!st&&!wt;){let me=!1;try{Te="",Zn&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},Zn=!1,rt===1&&(xt=""));let Ae=D=>{if(!D||!D.includes("[tool:"))return D;let Y="",W=oi(D);W&&(Y=W.fullBlock,D=W.remainingText),D=D.replace(qa,(z,le)=>le.includes("[tool:")?le.trim():z);let q="",Z=0;for(;Z<D.length;){let z=D.indexOf("[tool:",Z);if(z===-1){q+=Gr(D.substring(Z));break}let le=D.substring(Z,z);q+=Gr(le);let ht=-1,N=null,V=0;for(let be=z;be<D.length;be++){let b=D[be];if(N){if(b===N){let Be=0;for(let fe=be-1;fe>=0&&D[fe]==="\\";fe--)Be++;Be%2===0&&(N=null)}}else if(b==='"'||b==="'"||b==="`")N=b;else if(b==="(")V++;else if(b===")")V--;else if(b==="]"&&V<=0){ht=be;break}}if(ht===-1){q+=D.substring(z);break}q+=D.substring(z,ht+1),Z=ht+1}return(T?.keepReasoningContext?Y:"")+q},ee=r.filter(D=>(D.role==="user"||D.role==="agent"||D.role==="system")&&!String(D.id).startsWith("welcome")&&!D.isMeta&&!D.isTerminalRecord&&!(D.text&&D.text.startsWith("[TERMINAL_RECORD]"))).map((D,Y,W)=>{let q=D.text||"";A||(q=q.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),D.role==="agent"&&(q=Ae(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*"));let Z=[];return Array.isArray(D.parts)&&D.parts.length>0?Z=D.parts.map(z=>{if(z.text){let le=z.text;return A||(le=le.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),D.role==="agent"&&(le=Ae(le),le=le.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),le=le.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*")),{text:le}}return z}):Z=[{text:q}],D.binaryPart&&ft(Se)&&W.slice(Y+1).filter(le=>le.role==="user"&&!le.text?.startsWith("[ACTION RESULT]")&&!le.text?.startsWith("[TOOL RESULT]")).length<=2&&Z.push(D.binaryPart),{role:D.role==="user"||D.role==="system"?"user":"model",parts:Z}});for(let D=0;D<ee.length;D++){let Y=ee[D],W=Y.parts?.[0]?.text||"";if(Y.role==="model"&&/\[(?:tool|action):/i.test(W)){let q=-1;for(let Z=D+1;Z<ee.length;Z++){let z=ee[Z],le=z.parts?.[0]?.text||"";if(z.role==="user"&&(le.startsWith("[ACTION RESULT]")||le.startsWith("[TOOL RESULT]"))){q=Z;break}}if(q!==-1&&q!==D+1){let[Z]=ee.splice(q,1);ee.splice(D+1,0,Z)}}}for(let D=ee.length-2;D>=0;D--){let Y=ee[D],W=ee[D+1];Y.role==="user"&&W.role==="user"&&(W.parts?.[0]?.text||"").trim().startsWith("[SYSTEM")&&ee.splice(D,1)}let Lt=[];for(let D=0;D<ee.length;D++){let Y=ee[D];if(Lt.length===0)Lt.push(Y);else{let W=Lt[Lt.length-1];W.role===Y.role?(W.parts[0].text+=`
722
+ [STEERING HINT from USER, High Priority] ${pe.trim()} [/STEERING HINT]`:r.push({role:"user",text:`[STEERING HINT from USER, High Priority] ${pe.trim()} [/STEERING HINT]`}),yield{type:"status",content:`${pe.startsWith("/btw")?"Question Forwarded...":"Steering Hint Injected..."}`})}let Fe,st=!1,et=1,rt=1,Te="",Ve=null,sn=null,K=null,We=0,Me=[],ut=0,kn=!1,vt=!1,rn=!1,Tn=!1,Zn=!0,Qt=0,xt="",Qe="",Dt=!1,Ot=!1,Ye=!0,Se=e,qe="";for(;et<=on&&rt<=on&&!st&&!wt;){let pe=!1;try{Te="",Zn&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},Zn=!1,rt===1&&(xt=""));let Ae=D=>{if(!D||!D.includes("[tool:"))return D;let Y="",W=oi(D);W&&(Y=W.fullBlock,D=W.remainingText),D=D.replace(qa,(z,le)=>le.includes("[tool:")?le.trim():z);let q="",Z=0;for(;Z<D.length;){let z=D.indexOf("[tool:",Z);if(z===-1){q+=Gr(D.substring(Z));break}let le=D.substring(Z,z);q+=Gr(le);let ht=-1,N=null,V=0;for(let be=z;be<D.length;be++){let b=D[be];if(N){if(b===N){let Be=0;for(let fe=be-1;fe>=0&&D[fe]==="\\";fe--)Be++;Be%2===0&&(N=null)}}else if(b==='"'||b==="'"||b==="`")N=b;else if(b==="(")V++;else if(b===")")V--;else if(b==="]"&&V<=0){ht=be;break}}if(ht===-1){q+=D.substring(z);break}q+=D.substring(z,ht+1),Z=ht+1}return(T?.keepReasoningContext?Y:"")+q},ee=r.filter(D=>(D.role==="user"||D.role==="agent"||D.role==="system")&&!String(D.id).startsWith("welcome")&&!D.isMeta&&!D.isTerminalRecord&&!(D.text&&D.text.startsWith("[TERMINAL_RECORD]"))).map((D,Y,W)=>{let q=D.text||"";A||(q=q.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),D.role==="agent"&&(q=Ae(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*"));let Z=[];return Array.isArray(D.parts)&&D.parts.length>0?Z=D.parts.map(z=>{if(z.text){let le=z.text;return A||(le=le.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),D.role==="agent"&&(le=Ae(le),le=le.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),le=le.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*")),{text:le}}return z}):Z=[{text:q}],D.binaryPart&&ft(Se)&&W.slice(Y+1).filter(le=>le.role==="user"&&!le.text?.startsWith("[ACTION RESULT]")&&!le.text?.startsWith("[TOOL RESULT]")).length<=2&&Z.push(D.binaryPart),{role:D.role==="user"||D.role==="system"?"user":"model",parts:Z}});for(let D=0;D<ee.length;D++){let Y=ee[D],W=Y.parts?.[0]?.text||"";if(Y.role==="model"&&/\[(?:tool|action):/i.test(W)){let q=-1;for(let Z=D+1;Z<ee.length;Z++){let z=ee[Z],le=z.parts?.[0]?.text||"";if(z.role==="user"&&(le.startsWith("[ACTION RESULT]")||le.startsWith("[TOOL RESULT]"))){q=Z;break}}if(q!==-1&&q!==D+1){let[Z]=ee.splice(q,1);ee.splice(D+1,0,Z)}}}for(let D=ee.length-2;D>=0;D--){let Y=ee[D],W=ee[D+1];Y.role==="user"&&W.role==="user"&&(W.parts?.[0]?.text||"").trim().startsWith("[SYSTEM")&&ee.splice(D,1)}let Lt=[];for(let D=0;D<ee.length;D++){let Y=ee[D];if(Lt.length===0)Lt.push(Y);else{let W=Lt[Lt.length-1];W.role===Y.role?(W.parts[0].text+=`
724
723
 
725
- `+(Y.parts?.[0]?.text||""),Y.parts?.length>1&&W.parts.push(...Y.parts.slice(1))):Lt.push(Y)}}ee.length=0,ee.push(...Lt),Se=e;let Mt=`${p}|${i}|${l}|${f}|${Se}|${JSON.stringify(c)}|${!!T?.dynamicDirAwareness}|${!!T?.subAgents}`,At=jn.key===Mt&&jn.value;if((process.env.I_HAVE_TOO_MUCH_MONEY==="true"||process.env.I_HAVE_TOO_MUCH_MONEY===!0)&&(At=!1),At)qe=jn.value;else{let D=i==="Mistral"?!!Io(Se):!(Se||"gemma").toLowerCase().startsWith("gemma");qe=fr(c,((Se||"gemma").toLowerCase().startsWith("gemma"),f),l,T,A,_,i,i==="Google"?!0:h,D,p,!!T?.keepReasoningContext,Se),T?.dynamicDirAwareness||(qe+=`
724
+ `+(Y.parts?.[0]?.text||""),Y.parts?.length>1&&W.parts.push(...Y.parts.slice(1))):Lt.push(Y)}}ee.length=0,ee.push(...Lt),Se=e;let Mt=`${m}|${i}|${l}|${f}|${Se}|${JSON.stringify(c)}|${!!T?.dynamicDirAwareness}|${!!T?.subAgents}`,At=jn.key===Mt&&jn.value;if((process.env.I_HAVE_TOO_MUCH_MONEY==="true"||process.env.I_HAVE_TOO_MUCH_MONEY===!0)&&(At=!1),At)qe=jn.value;else{let D=i==="Mistral"?!!Io(Se):!(Se||"gemma").toLowerCase().startsWith("gemma");qe=fr(c,((Se||"gemma").toLowerCase().startsWith("gemma"),f),l,T,A,_,i,i==="Google"?!0:h,D,m,!!T?.keepReasoningContext,Se),T?.dynamicDirAwareness||(qe+=`
726
725
  ${Qr.replace(`
727
726
  **Directory**`,`
728
727
  -- Directory --`)}`),jn.key=Mt,jn.value=qe}let Ge=ee[ee.length-1];if(zo()&j>0){await new Promise(W=>setTimeout(W,2500)),yield{type:"status",content:"Verifying"};let D=await Hn(),Y=D?D.diagnostics:null;Y&&Ge&&Ge.role==="user"&&Ge.parts?.[0]?.text&&(Ge.parts[0].text+=`
729
- ${Y} [/ERROR]`),yield{type:"status",content:"Working"}}let Pt=i==="Mistral"||i==="Google"&&e?.toLowerCase().startsWith("gemma");if(T?.advanceRollback&&Ge&&Ge.role==="user"&&(Ge.parts?.[0]?.text?.startsWith("[ACTION RESULT]")||Ge.parts?.[0]?.text?.startsWith("[TOOL RESULT]")))try{let D=await lo.getLatestFileChanges(p);if(D&&(D.newFiles.length>0||D.modifiedFiles.length>0||D.deletedFiles.length>0)){let Y=`
728
+ ${Y} [/ERROR]`),yield{type:"status",content:"Working"}}let Pt=i==="Mistral"||i==="Google"&&e?.toLowerCase().startsWith("gemma");if(T?.advanceRollback&&Ge&&Ge.role==="user"&&(Ge.parts?.[0]?.text?.startsWith("[ACTION RESULT]")||Ge.parts?.[0]?.text?.startsWith("[TOOL RESULT]")))try{let D=await lo.getLatestFileChanges(m);if(D&&(D.newFiles.length>0||D.modifiedFiles.length>0||D.deletedFiles.length>0)){let Y=`
730
729
  [system] File Changes:
731
730
  `;for(let q of D.newFiles)Y+=`* ${q} (created)
732
731
  `;for(let q of D.modifiedFiles)Y+=`* ${q} (modified)
733
732
  `;for(let q of D.deletedFiles)Y+=`* ${q} (deleted)
734
733
  `;Y+="[/system]",Ge.parts[0].text+=Y;let W=-1;for(let q=r.length-1;q>=0;q--)if(r[q].role==="user"&&(r[q].text?.startsWith("[ACTION RESULT]")||r[q].text?.startsWith("[TOOL RESULT]"))){W=q;break}W!==-1&&(r[W].text+=Y)}}catch{}let Et=Math.floor(wn*.99),Tt=j+1;Tt>=Et&&Ge&&Ge.parts?.[0]&&(Ge.parts[0].text+=`
735
- [system] WARNING, Turn Limit Impending: Step ${Tt}/${wn}. Wrap up quickly/prompt user to continue. [/system]`);let It=new Promise((D,Y)=>{d.signal.aborted&&Y(new DOMException("The user aborted a request.","AbortError")),d.signal.addEventListener("abort",()=>{Y(new DOMException("The user aborted a request.","AbortError"))})});It.catch(()=>{});let gt=ee;if(i==="Ollama")Fe=ei(n.apiKey,Se,gt,qe,f,l,h,d.signal,1,T?.ollamaEndpoint||"Cloud");else if(i==="OpenRouter")Fe=es(n.apiKey,Se,gt,qe,f,l,h,d.signal,1,p);else if(i==="DeepSeek")Fe=Jo(n.apiKey,Se,gt,qe,f,l,h,d.signal,1);else if(i==="Mistral")Fe=Qo(n.apiKey,Se,gt,qe,f,l,h,d.signal,1,p);else if(i==="NVIDIA"){let D=Zo(n.apiKey,Se,gt,qe,f,l,h,d.signal,1);Fe=Fr(D,Se)}else if(i==="InferX")Fe=ts(n.apiKey,Se,gt,qe,f,l,h,d.signal,1);else if(i==="SenseNova")Fe=ns(n.apiKey,Se,gt,qe,f,l,h,d.signal,1);else if(i==="AIHubMix")Fe=os(n.apiKey,Se,gt,qe,f,l,h,d.signal,1);else if(i==="Poolside")Fe=ss(n.apiKey,Se,gt,qe,f,l,h,d.signal,1);else if(i==="9router"||i==="9Router")Fe=is(n.apiKey,Se,gt,qe,f,l,h,d.signal,1);else if(i==="ExpLabs"||i==="ExperientialLabs")Fe=rs(n.apiKey,Se,gt,qe,f,l,h,d.signal,1);else if(i==="TokenHarbor"||i==="Token Harbor"||i==="tokenharbor"||i==="token_harbor"||i==="thk")Fe=ti(n.apiKey,Se,gt,qe,f,l,h,d.signal,1);else if(i==="APInex"||i==="apinex"||i==="apx")Fe=ni(n.apiKey,Se,gt,qe,f,l,h,d.signal,1);else{let D=ri(n?.apiKey),{serviceTier:Y,cleanModel:W}=Xr(Se),q={systemInstruction:qe,mediaResolution:"MEDIA_RESOLUTION_HIGH",safetySettings:[{category:In.HARM_CATEGORY_HARASSMENT,threshold:Mn.BLOCK_NONE},{category:In.HARM_CATEGORY_HATE_SPEECH,threshold:Mn.BLOCK_NONE},{category:In.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Mn.BLOCK_NONE},{category:In.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Mn.BLOCK_NONE}],temperature:1.05,thinkingConfig:(()=>{let z=He("Google",Se||"gemini-3-flash-preview",f);if(z!==null){if(typeof z=="object")return z;if(z===!1||z==="false"||z==="none"||z===0||z==="0")return{includeThoughts:!1};if(typeof z=="number")return{includeThoughts:!0,thinkingBudget:z};if(typeof z=="string"){let V=z.toLowerCase();if(V==="minimal")return{includeThoughts:!0,thinkingLevel:Xe.MINIMAL};if(V==="low")return{includeThoughts:!0,thinkingLevel:Xe.LOW};if(V==="medium")return{includeThoughts:!0,thinkingLevel:Xe.MEDIUM};if(V==="high")return{includeThoughts:!0,thinkingLevel:Xe.HIGH};let be=Number(z);if(!isNaN(be))return{includeThoughts:!0,thinkingBudget:be}}}let le=(Se||"").toLowerCase(),ht=le.includes("gemma-4")||le.startsWith("gemma"),N=le.includes("gemini-3");if(ht||N)return ht?f.toLowerCase()!=="high"?{includeThoughts:!1,thinkingLevel:Xe.MINIMAL}:{includeThoughts:!0,thinkingLevel:Xe.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:le.includes("pro")?Xe.LOW:Xe.MINIMAL,Low:Xe.LOW,Medium:Xe.MEDIUM,Standard:Xe.MEDIUM,High:Xe.HIGH,xHigh:Xe.HIGH}[f]||Xe.MEDIUM};{let V={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[f]||2048;return V===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:V}}})()};Y&&(q.serviceTier=Y);let Z=D.models.generateContentStream({model:W||"gemini-3-flash-preview",contents:gt,config:q},{signal:d.signal});Fe=await Promise.race([Z,It])}Te="",Ve=null,K=null,Me=[],ut=0,yield{type:"model_update",content:null},Qe="",Dt=xt.length>0;let an="",ms=Date.now(),Nn=async function*(){if(i==="Google"&&an){let D=to(an);for(let Y of D)yield Y;an="",ms=Date.now()}},yi=!0,Fn="",Vn=!1,St=null,xi=!1,Yn=!1,qn=!1,Ao=!1,_n=!1,eo=D=>{let Y=0;for(;Y+2<D.length;)D[Y]==="`"&&D[Y+1]==="`"&&D[Y+2]==="`"?(Ao=!Ao,Y+=3):Y++},bi=D=>{if(!D)return;let Y=/(?:<(\/?)(?:think|thought|thoughts)[^>]*>|\[(\/?)(?:think|thought|thoughts)\]|<\/?channel\|?>|<\|channel>thought)/gi,W;for(;(W=Y.exec(D))!==null;){let q=W[0].toLowerCase();q.startsWith("</")||q.startsWith("[/")||q==="<channel|>"?_n=!1:_n=!0}},sa={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|>"}},to=D=>{let Y=[],W=D,q=Z=>{if(!Z)return;if(!xi){Y.push({type:"text",content:Z}),eo(Z),bi(Z);return}let z=/(?:<(\/?)(?:think|thought|thoughts)[^>]*>|\[(\/?)(?:think|thought|thoughts)\]|<\/?channel\|?>|<\|channel>thought)/gi,le=0,ht;for(;(ht=z.exec(Z))!==null;){let V=Z.substring(le,ht.index);if(V)if(eo(V),_n)Y.push({type:"text",content:V});else{let Be=V.replace(/[^\n]/g,"");Be&&Y.push({type:"text",content:Be})}let be=ht[0];eo(be);let b=be.toLowerCase();b.startsWith("</")||b.startsWith("[/")||b==="<channel|>"?_n=!1:_n=!0,Y.push({type:"text",content:be}),le=z.lastIndex}let N=Z.substring(le);if(N)if(eo(N),_n)Y.push({type:"text",content:N});else{let V=N.replace(/[^\n]/g,"");V&&Y.push({type:"text",content:V})}};for(;W.length>0;)if(Vn){let Z=Fn+W,z=sa[St];if(z){let N=!1;if(Z.length<z.startPrefix.length?z.startPrefix.startsWith(Z)||(N=!0):Z.startsWith(z.startPrefix)?Z.length>=z.fullPrefix.length&&!Z.startsWith(z.fullPrefix)&&(N=!0):N=!0,N){q(Z),Fn="",Vn=!1,St=null,Yn=!1,qn=!1,W="";break}}let le=-1,ht=z?z.endTag:"]";if(St==="tool"||St==="action"){let N=0,V=null,be=0,b=!1;for(let Be=0;Be<Z.length;Be++){let fe=Z[Be];if(V){if(fe===V){let X=0;for(let $t=Be-1;$t>=0&&Z[$t]==="\\";$t--)X++;X%2===0&&(V=null)}}else if(fe==='"'||fe==="'"||fe==="`")V=fe;else if(fe==="(")N++,b=!0;else if(fe===")")N--;else if(fe==="[")be++;else if(fe==="]"){if(b&&N===0&&be===1){le=Be;break}be--}}}else le=Z.indexOf(ht);if(le!==-1){let N=ht.length,V=Z.substring(0,le+N);St?.startsWith("kimi")||Y.push({type:"text",content:V}),eo(V),bi(V),(St==="tool"||St==="action"||St?.startsWith("kimi"))&&!Yn&&!qn&&(xi=!0),Yn=!1,qn=!1,Fn="",Vn=!1,St=null,W=Z.substring(le+N)}else{let N=St?.startsWith("kimi")?8192:512;Z.length>N?(q(Z),Fn="",Vn=!1,St=null,Yn=!1,qn=!1):Fn=Z,W="";break}}else{let Z=W.indexOf("[tool"),z=W.indexOf("[action"),le=W.indexOf("[[END]]"),ht=W.indexOf("<|tool_calls_section_begin|>"),N=W.indexOf("<|tool_call_begin|>"),V=[{type:"tool",idx:Z,start:"[tool",end:"]"},{type:"action",idx:z,start:"[action",end:"]"},{type:"end",idx:le,start:"[[END]]",end:"[[END]]"},{type:"kimi_section",idx:ht,start:"<|tool_calls_section_begin|>",end:"<|tool_calls_section_end|>"},{type:"kimi_call",idx:N,start:"<|tool_call_begin|>",end:"<|tool_call_end|>"}].filter(be=>be.idx!==-1).sort((be,b)=>be.idx-b.idx);if(V.length>0){let be=V[0],b=W.substring(0,be.idx);be.idx>0&&q(b);let Be=be.idx>0?W[be.idx-1]:"";Yn=Ao||Be==="`",qn=_n,Vn=!0,St=be.type,Fn="",W=W.substring(be.idx)}else{let be=["[tool","[action","[[END]]","<|tool_calls_section_begin|>","<|tool_call_begin|>"],b=-1;for(let Be of be){for(let fe=Be.length-1;fe>0;fe--)if(W.endsWith(Be.substring(0,fe))){b=W.length-fe;let X=be.indexOf(Be);X===0?St="tool":X===1?St="action":X===2?St="end":X===3?St="kimi_section":St="kimi_call";break}if(b!==-1)break}if(b!==-1){if(b>0){let fe=W.substring(0,b);q(fe)}let Be=b>0?W[b-1]:"";Yn=Ao||Be==="`",qn=_n,Vn=!0,Fn=W.substring(b),W=""}else{q(W);break}}}return Y},ia=Fe[Symbol.asyncIterator]();for(;;){let{value:D,done:Y}=await Promise.race([ia.next(),It]);if(Y)break;if(D&&D.type==="status"){yield D;continue}let W="",q=D.candidates?.[0]?.content?.parts;if(q&&q.length>0)for(let z of q){let le=typeof z.text=="string"?z.text:z.text?parseChunkText(z.text):"";z.thought?le&&(me||(W+="<think>",me=!0),W+=le):le&&(me&&(W+="</think>",me=!1),W+=le)}else D.text&&me&&(W+="</think>",me=!1);W=ja(W);let Z=W?As(W):0;if(n&&typeof n.onTokenChunk=="function"&&n.onTokenChunk(W,Z),yi&&(yield{type:"status",content:"Thinking"},yi=!1),wt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
734
+ [system] WARNING, Turn Limit Impending: Step ${Tt}/${wn}. Wrap up quickly/prompt user to continue. [/system]`);let It=new Promise((D,Y)=>{d.signal.aborted&&Y(new DOMException("The user aborted a request.","AbortError")),d.signal.addEventListener("abort",()=>{Y(new DOMException("The user aborted a request.","AbortError"))})});It.catch(()=>{});let gt=ee;if(i==="Ollama")Fe=ei(n.apiKey,Se,gt,qe,f,l,h,d.signal,1,T?.ollamaEndpoint||"Cloud");else if(i==="OpenRouter")Fe=es(n.apiKey,Se,gt,qe,f,l,h,d.signal,1,m);else if(i==="DeepSeek")Fe=Jo(n.apiKey,Se,gt,qe,f,l,h,d.signal,1);else if(i==="Mistral")Fe=Qo(n.apiKey,Se,gt,qe,f,l,h,d.signal,1,m);else if(i==="NVIDIA"){let D=Zo(n.apiKey,Se,gt,qe,f,l,h,d.signal,1);Fe=Fr(D,Se)}else if(i==="InferX")Fe=ts(n.apiKey,Se,gt,qe,f,l,h,d.signal,1);else if(i==="SenseNova")Fe=ns(n.apiKey,Se,gt,qe,f,l,h,d.signal,1);else if(i==="AIHubMix")Fe=os(n.apiKey,Se,gt,qe,f,l,h,d.signal,1);else if(i==="Poolside")Fe=ss(n.apiKey,Se,gt,qe,f,l,h,d.signal,1);else if(i==="9router"||i==="9Router")Fe=is(n.apiKey,Se,gt,qe,f,l,h,d.signal,1);else if(i==="ExpLabs"||i==="ExperientialLabs")Fe=rs(n.apiKey,Se,gt,qe,f,l,h,d.signal,1);else if(i==="TokenHarbor"||i==="Token Harbor"||i==="tokenharbor"||i==="token_harbor"||i==="thk")Fe=ti(n.apiKey,Se,gt,qe,f,l,h,d.signal,1);else if(i==="APInex"||i==="apinex"||i==="apx")Fe=ni(n.apiKey,Se,gt,qe,f,l,h,d.signal,1);else{let D=ri(n?.apiKey),{serviceTier:Y,cleanModel:W}=Xr(Se),q={systemInstruction:qe,mediaResolution:"MEDIA_RESOLUTION_HIGH",safetySettings:[{category:In.HARM_CATEGORY_HARASSMENT,threshold:Mn.BLOCK_NONE},{category:In.HARM_CATEGORY_HATE_SPEECH,threshold:Mn.BLOCK_NONE},{category:In.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Mn.BLOCK_NONE},{category:In.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Mn.BLOCK_NONE}],temperature:1.05,thinkingConfig:(()=>{let z=He("Google",Se||"gemini-3-flash-preview",f);if(z!==null){if(typeof z=="object")return z;if(z===!1||z==="false"||z==="none"||z===0||z==="0")return{includeThoughts:!1};if(typeof z=="number")return{includeThoughts:!0,thinkingBudget:z};if(typeof z=="string"){let V=z.toLowerCase();if(V==="minimal")return{includeThoughts:!0,thinkingLevel:Xe.MINIMAL};if(V==="low")return{includeThoughts:!0,thinkingLevel:Xe.LOW};if(V==="medium")return{includeThoughts:!0,thinkingLevel:Xe.MEDIUM};if(V==="high")return{includeThoughts:!0,thinkingLevel:Xe.HIGH};let be=Number(z);if(!isNaN(be))return{includeThoughts:!0,thinkingBudget:be}}}let le=(Se||"").toLowerCase(),ht=le.includes("gemma-4")||le.startsWith("gemma"),N=le.includes("gemini-3");if(ht||N)return ht?f.toLowerCase()!=="high"?{includeThoughts:!1,thinkingLevel:Xe.MINIMAL}:{includeThoughts:!0,thinkingLevel:Xe.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:le.includes("pro")?Xe.LOW:Xe.MINIMAL,Low:Xe.LOW,Medium:Xe.MEDIUM,Standard:Xe.MEDIUM,High:Xe.HIGH,xHigh:Xe.HIGH}[f]||Xe.MEDIUM};{let V={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[f]||2048;return V===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:V}}})()};Y&&(q.serviceTier=Y);let Z=D.models.generateContentStream({model:W||"gemini-3-flash-preview",contents:gt,config:q},{signal:d.signal});Fe=await Promise.race([Z,It])}Te="",Ve=null,K=null,Me=[],ut=0,yield{type:"model_update",content:null},Qe="",Dt=xt.length>0;let an="",ps=Date.now(),Nn=async function*(){if(i==="Google"&&an){let D=to(an);for(let Y of D)yield Y;an="",ps=Date.now()}},yi=!0,Fn="",Vn=!1,St=null,xi=!1,Yn=!1,qn=!1,Ao=!1,_n=!1,eo=D=>{let Y=0;for(;Y+2<D.length;)D[Y]==="`"&&D[Y+1]==="`"&&D[Y+2]==="`"?(Ao=!Ao,Y+=3):Y++},bi=D=>{if(!D)return;let Y=/(?:<(\/?)(?:think|thought|thoughts)[^>]*>|\[(\/?)(?:think|thought|thoughts)\]|<\/?channel\|?>|<\|channel>thought)/gi,W;for(;(W=Y.exec(D))!==null;){let q=W[0].toLowerCase();q.startsWith("</")||q.startsWith("[/")||q==="<channel|>"?_n=!1:_n=!0}},sa={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|>"}},to=D=>{let Y=[],W=D,q=Z=>{if(!Z)return;if(!xi){Y.push({type:"text",content:Z}),eo(Z),bi(Z);return}let z=/(?:<(\/?)(?:think|thought|thoughts)[^>]*>|\[(\/?)(?:think|thought|thoughts)\]|<\/?channel\|?>|<\|channel>thought)/gi,le=0,ht;for(;(ht=z.exec(Z))!==null;){let V=Z.substring(le,ht.index);if(V)if(eo(V),_n)Y.push({type:"text",content:V});else{let Be=V.replace(/[^\n]/g,"");Be&&Y.push({type:"text",content:Be})}let be=ht[0];eo(be);let b=be.toLowerCase();b.startsWith("</")||b.startsWith("[/")||b==="<channel|>"?_n=!1:_n=!0,Y.push({type:"text",content:be}),le=z.lastIndex}let N=Z.substring(le);if(N)if(eo(N),_n)Y.push({type:"text",content:N});else{let V=N.replace(/[^\n]/g,"");V&&Y.push({type:"text",content:V})}};for(;W.length>0;)if(Vn){let Z=Fn+W,z=sa[St];if(z){let N=!1;if(Z.length<z.startPrefix.length?z.startPrefix.startsWith(Z)||(N=!0):Z.startsWith(z.startPrefix)?Z.length>=z.fullPrefix.length&&!Z.startsWith(z.fullPrefix)&&(N=!0):N=!0,N){q(Z),Fn="",Vn=!1,St=null,Yn=!1,qn=!1,W="";break}}let le=-1,ht=z?z.endTag:"]";if(St==="tool"||St==="action"){let N=0,V=null,be=0,b=!1;for(let Be=0;Be<Z.length;Be++){let fe=Z[Be];if(V){if(fe===V){let X=0;for(let $t=Be-1;$t>=0&&Z[$t]==="\\";$t--)X++;X%2===0&&(V=null)}}else if(fe==='"'||fe==="'"||fe==="`")V=fe;else if(fe==="(")N++,b=!0;else if(fe===")")N--;else if(fe==="[")be++;else if(fe==="]"){if(b&&N===0&&be===1){le=Be;break}be--}}}else le=Z.indexOf(ht);if(le!==-1){let N=ht.length,V=Z.substring(0,le+N);St?.startsWith("kimi")||Y.push({type:"text",content:V}),eo(V),bi(V),(St==="tool"||St==="action"||St?.startsWith("kimi"))&&!Yn&&!qn&&(xi=!0),Yn=!1,qn=!1,Fn="",Vn=!1,St=null,W=Z.substring(le+N)}else{let N=St?.startsWith("kimi")?8192:512;Z.length>N?(q(Z),Fn="",Vn=!1,St=null,Yn=!1,qn=!1):Fn=Z,W="";break}}else{let Z=W.indexOf("[tool"),z=W.indexOf("[action"),le=W.indexOf("[[END]]"),ht=W.indexOf("<|tool_calls_section_begin|>"),N=W.indexOf("<|tool_call_begin|>"),V=[{type:"tool",idx:Z,start:"[tool",end:"]"},{type:"action",idx:z,start:"[action",end:"]"},{type:"end",idx:le,start:"[[END]]",end:"[[END]]"},{type:"kimi_section",idx:ht,start:"<|tool_calls_section_begin|>",end:"<|tool_calls_section_end|>"},{type:"kimi_call",idx:N,start:"<|tool_call_begin|>",end:"<|tool_call_end|>"}].filter(be=>be.idx!==-1).sort((be,b)=>be.idx-b.idx);if(V.length>0){let be=V[0],b=W.substring(0,be.idx);be.idx>0&&q(b);let Be=be.idx>0?W[be.idx-1]:"";Yn=Ao||Be==="`",qn=_n,Vn=!0,St=be.type,Fn="",W=W.substring(be.idx)}else{let be=["[tool","[action","[[END]]","<|tool_calls_section_begin|>","<|tool_call_begin|>"],b=-1;for(let Be of be){for(let fe=Be.length-1;fe>0;fe--)if(W.endsWith(Be.substring(0,fe))){b=W.length-fe;let X=be.indexOf(Be);X===0?St="tool":X===1?St="action":X===2?St="end":X===3?St="kimi_section":St="kimi_call";break}if(b!==-1)break}if(b!==-1){if(b>0){let fe=W.substring(0,b);q(fe)}let Be=b>0?W[b-1]:"";Yn=Ao||Be==="`",qn=_n,Vn=!0,Fn=W.substring(b),W=""}else{q(W);break}}}return Y},ia=Fe[Symbol.asyncIterator]();for(;;){let{value:D,done:Y}=await Promise.race([ia.next(),It]);if(Y)break;if(D&&D.type==="status"){yield D;continue}let W="",q=D.candidates?.[0]?.content?.parts;if(q&&q.length>0)for(let z of q){let le=typeof z.text=="string"?z.text:z.text?parseChunkText(z.text):"";z.thought?le&&(pe||(W+="<think>",pe=!0),W+=le):le&&(pe&&(W+="</think>",pe=!1),W+=le)}else D.text&&pe&&(W+="</think>",pe=!1);W=ja(W);let Z=W?As(W):0;if(n&&typeof n.onTokenChunk=="function"&&n.onTokenChunk(W,Z),yi&&(yield{type:"status",content:"Thinking"},yi=!1),wt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
736
735
 
737
736
  \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(W){if(Dt){if(Qe+=W,Qe.length>=64){let N=0,V=Math.min(xt.length,Qe.length);for(let b=V;b>=10;b--)if(xt.endsWith(Qe.substring(0,b))){N=b;break}let be=Qe.substring(N);if(be){let Be=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(xt)?be.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):be.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(Be)if(Te+=Be,i==="Google")an+=Be;else{yield*Nn();let fe=to(Be);for(let X of fe)yield X}}Dt=!1,Qe=""}continue}else if(Te+=W,i==="Google")an+=W;else{yield*Nn();let N=to(W);for(let V of N)yield V}let z=Qa(Te);if(z.inside){Ot=!0,K||(K=Date.now());let V={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",Answer:"answer",Steer:"steer",steer:"steer"}[z.toolName]||z.toolName,be=z.args||"",b=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","answer"].includes(V)){let fe=ne(be),X=fe.basename||fe.name||fe.path||fe.targetFile||fe.TargetFile||fe.directory||fe.file,$t=fe.keyword,Bn=fe.title||fe.task,An=fe.id||fe.taskId,Le=fe.timeout||fe.time;if($t!=null)b=String($t).replace(Gn,"");else if(X)b=ie.basename(String(X).replace(Gn,"").replace(Br,"/"));else if(Bn&&(V==="invoke"||V==="invoke_sync"))b=String(Bn).replace(Gn,"").substring(0,30);else if(An&&V==="get_progress")b=String(An).replace(Gn,"");else if(Le&&V==="await"){let Nt=parseFloat(String(Le).replace(Gn,""));isNaN(Nt)?b=String(Le).replace(Gn,""):(Nt<5&&(Nt=5),Nt>120&&(Nt=120),b=(gn=>{if(gn>=60){let ys=Math.floor(gn/60),zn=gn%60;return`${ys}m${zn>0?` ${zn}s`:""}`}return`${gn}s`})(Nt))}else{let Nt=be.match(Wa);if(Nt){let Ht=Nt[1].replace(Gn,"");V==="invoke"||V==="invoke_sync"||V==="get_progress"?b=Ht.substring(0,30):b=V==="search_keyword"||V==="file_map"?Ht:ie.basename(Ht.replace(Br,"/"))}}}let Be=`${si[V]||V}${b?` ${b}`:""}`;if((V!==Ve||b!==sn)&&(Ve=V,sn=b,yield{type:"status",content:`${Be}`},process.stdout.isTTY)){let X={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",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"}[V]||"Working";process.stdout.write(`\x1B]0;${X}...\x07`)}}if(Te.length-Qt>150){Qt=Te.length;let N=zr(Te,!1),V=oi(N),be=V?(V.innerContent||"").trim():"",b=be.split(/[.!?]\s+/),Be=new Set(b),fe=b.length>10?(b.length-Be.size)/b.length:0,X=be.split(/\s+/).filter(Pe=>Pe.length>0).length,$t=.6,Bn=.8,An=!1;if(i.toLowerCase().includes("google")&&(Se||"").toLowerCase().startsWith("gemma")){let S={low:256,medium:1024,high:8192,max:16384,xhigh:16384}[f?.toLowerCase()]||2500;An=X>S}if(fe>$t||An){yield{type:"status",content:`${fe>$t?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},vt=!0,await new Promise(S=>setTimeout(S,3e3));break}let Ht=jr(Te).trim().split(/[.!?]\s+/),gn=new Set(Ht);if((Ht.length>10?(Ht.length-gn.size)/Ht.length:0)>Bn){yield{type:"status",content:"Response Loop Detected. Re-centering..."},vt=!1,Tn=!0,await new Promise(Pe=>setTimeout(Pe,3e3));break}let zn=N.replace(La,"").replace(Pa,"").replace($a,"").replace(Na,""),Ft=zn.toLowerCase().split(/\s+/).map(Pe=>Pe.replace(Fa,"")).filter(Pe=>Pe.length>0),hn=!1;if(Ft.length>=10)for(let Pe=1;Pe<=15;Pe++){let S=Math.max(3,Math.ceil(10/Pe));if(Ft.length<Pe*S)continue;let H=Ft.slice(Ft.length-Pe),se=H.join(" ");if(Pe>1&&se===H.slice(0,Math.floor(Pe/2)).join(" ").repeat(2).trim())continue;let ge=!0;for(let we=1;we<S;we++)if(Ft.slice(Ft.length-Pe*(we+1),Ft.length-Pe*we).join(" ")!==se){ge=!1;break}if(ge){hn=!0;break}}if(!hn){let Pe=zn.toLowerCase().replace(Ba,"");if(Pe.length>=20)for(let S=1;S<=10;S++){let H=Math.max(5,Math.ceil(16/S));if(Pe.length<S*H)continue;let se=Pe.substring(Pe.length-S),ge=!0;for(let we=1;we<H;we++)if(Pe.substring(Pe.length-S*(we+1),Pe.length-S*we)!==se){ge=!1;break}if(ge){hn=!0;break}}}if(hn){yield{type:"status",content:"Stuttering Detected. Re-centering..."},vt=!1,rn=!0,await new Promise(Pe=>setTimeout(Pe,3e3));break}}let le=qt(Te),ht=ko(le);for(;ht.length>ut;){yield*Nn();let N=ht[ut],V=Date.now(),b={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",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"}[N.toolName]||N.toolName,Be=si[b]||N.toolName,fe=Kn(b,N.args);yield{type:"status",content:`${Be}${fe?` ${fe}`:""}`};let X="";if(b==="click"){let S=ne(N.args);X=`\u2714 Clicked: ${S.intendedClickText?`${S.intendedClickText}`:""}`}else if(b==="drag"){let S=ne(N.args);X=`\u2714 Dragged: Cell ${S.fromGridId||""} \u2192 Cell ${S.toGridId||""}`}else if(b==="scroll"){let S=ne(N.args);X=`\u2714 Scrolled: ${S.direction||"down"} (${S.amount||1})`}else if(b==="keyboard_typing"){let S=ne(N.args);X=`\u2714 Typed: ${S.text?`"${S.text.length>20?S.text.substring(0,20)+"...":S.text}"`:""}`}else if(b==="key_press")X=`\u2714 Pressed Key: ${ne(N.args).key||""}`;else if(b==="recapture_screen")X="\u2714 Recaptured Screen";else if(b==="web_search"){let{query:S,limit:H=10,aiMode:se=!1}=ne(N.args);X=`${S?"\u2714":"\u2718"} ${se?"AI Search":"Searched"}: ${S?`${S}`:"No Search Query"}${se===!1&&S?` \u2192 ${H}`:""}`}else if(b==="web_scrape"){let S=ne(N.args).url||null;X=`${S?"\u2714":"\u2718"} Visited: ${S||"No Source"}`}else if(b==="view_file"){let{path:S,StartLine:H,EndLine:se,start_line:ge,end_line:we,startLine:Ne,endLine:De}=ne(N.args),Ce=H||ge||Ne,J=se||we||De,ce=parseInt(Ce)||1,ue=parseInt(J)||(Ce?ce+800:800),je="...",ze=ue,he=(S||"").trim().toLowerCase().replaceAll("\\","/");if(he.startsWith("#skill"))he.startsWith("#skill/global/fluxflow")||he.startsWith("#skills/global/fluxflow")||he.includes("#skill/fluxflow")||he.includes("#skills/fluxflow")?X="\u2714 Read Documentation":X=`\u2714 Read Skill: ${ie.basename(S.replaceAll("\\","/"))}`;else{try{let _e=ie.resolve(process.cwd(),S);if(Ue.existsSync(_e)){let bt=Ue.readFileSync(_e,"utf8").split(`
738
- `).length;je=bt,!Ce&&!J&&bt>800?ze=Math.min(50,bt):ze=Math.min(ue,bt)}}catch{}let Oe=(S||"").toLowerCase(),mt=Oe.endsWith(".pdf"),$e=Oe.endsWith(".docx")||Oe.endsWith(".doc")||Oe.endsWith(".ppt")||Oe.endsWith(".pptx")||Oe.endsWith(".xls")||Oe.endsWith(".xlsx"),tt=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(Oe);mt||$e?X=`${S.length>0?"\u2714":"\u2718"} ${S?`Analyzed: ${ie.basename(S)}`:"Analyzed: File Not Found"}`:tt?X=`${S.length>0?"\u2714":"\u2718"} ${S?`Processed: ${ie.basename(S)}`:"Processed: File Not Found"}`:X=`${je!=="..."?"\u2714":"\u2718"} Read: ${S?`${ie.basename(S)} \u2192 ${je!=="..."?`Lines ${ce} - ${ze} of ${je}`:"File Not Found"}`:"File Not Found"}`}}else if(b==="list_files"||b==="read_folder"){let S=b==="list_files"?"List":"Browsed",H=ne(N.args).path||null,se=ne(N.args).recurse||1;X=`${H?"\u2714":"\u2718"} ${S}: ${H?`${H==="."?`./${se>1?"*":""}`:`${H.replaceAll("\\","/")}${se>1?`${H.endsWith("/")?"*":"/*"}`:`${H.endsWith("/")?"":"/"}`}`}`:"No Folder Selected"}`}else if(b==="find_file"){let S=ne(N.args),H=S.basename||S.name||S.path||S.file||S.query||"";X=`${H?"\u2714":"\u2718"} Located: ${H||"No Query"}`}else if(b==="write_file"||b==="update_file"){let S=b==="write_file"?"Created":"Edited",H=ne(N.args),se=H.path||null,we=Object.entries(H).some(([Ne,De])=>Ne.startsWith("searchContent")&&typeof De=="string"&&De.startsWith("^LINE:"))?"\u1361":":";X=`${se?"\u2714":"\u2718"} ${S}${we} ${se?se.replaceAll("\\","/"):"No File Changes"}`}else if(b==="write_pdf"){let S=ne(N.args).path||null;X=`${S?"\u2714":"\u2718"} Generated: ${S.replaceAll("\\","/")||"No PDF Generated"}`}else if(b==="write_docx"){let S=ne(N.args).path||null;X=`${S?"\u2714":"\u2718"} Generated: ${S.replaceAll("\\","/")||"No Docx Generated"}`}else if(b==="file_map"){let S=ne(N.args).path;X=`${S?"\u2714":"\u2718"} Indexed: ${S.replaceAll("\\","/")?""+S:"File Not Found"}`}else if(b.toLowerCase()==="search_keyword"||b.toLowerCase()==="todo")X="";else if(b.toLowerCase()==="generate_image"){let{path:S,outputPath:H,output:se}=ne(N.args);X=`\u2714 Generated: ${S||H||se||"generated_image.png"}`}else if(b==="invoke_sync"||b==="InvokeSync"){let S=Kn(b,N.args);X=`\u2714 Called Generalist${S?`: ${S}`:""}`}else if(b==="Invoke"||b==="InvokeAsync"||b==="invoke"){let S=Kn(b,N.args);X=`\u2714 Started Generalist${S?`: ${S}`:""}`}else if(b==="get_progress"||b==="GetProgress"){let S=Kn(b,N.args);X=`\u2714 Checked${S?`: ${S}`:""}`}else if(b==="cancel"){let S=Kn(b,N.args);X=`\u{1F6C7} Cancelled${S?`: ${S}`:""}`}else if(b==="steer"||b==="Steer"){let S=Kn(b,N.args);X=`\u2714 Steered${S?`: ${S}`:""}`}else if(b==="EmergencyRollback"){let{method:S}=ne(N.args);X=S==="forceRevert"?"":"\u2714 Rollback Point Checked"}else if(b==="await"||b==="Await"){let{time:S,timeout:H}=ne(N.args),se=parseFloat(H||S)||0;se||(se=120);let ge=De=>{if(De>=60){let Ce=Math.floor(De/60),J=De%60;return`${Ce}m${J>0?` ${J}s`:""}`}return`${De}s`},we=["Aligning Moon Phase","Contemplating Existence","Staring At Void","Delaying Professionally","Negotiating With Electrons","Touching Grass (virtually)","Panicking Softly","Rethinking Career Choices","Loading Cat Videos","Summoning Braincell #2","Pretending To Be Busy","Waiting For Motivation DLC","Rotating Internal Screaming","Downloading More RAM","Feeding The Hamsters","Gaslighting Scheduler","Performing Dramatic Pause","Buffering Social Energy","Calculating Regret","Reading Terms And Conditions","Becoming Sentient Briefly","Contacting Ancestors"];X=`\u2714 ${we[Math.floor(Math.random()*we.length)]} \u2192 ${ge(se)}`}else b==="Answer"||b==="answer"?X="\u2714 Resolved Sub-Agent Query":b==="exec_command"||b==="ask"?X="":X=`Executed: ${N.toolName}`;if(yield*Nn(),b==="exec_command"){let{command:S}=ne(N.args);if(S&&n.systemSettings&&n.systemSettings.allowExternalAccess===!1){let H=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],se=ie.resolve(process.cwd()).substring(0,3).toLowerCase(),ge=J=>{let ce=[],ue="",je=null;for(let ze=0;ze<J.length;ze++){let he=J[ze];je?(he===je&&(je=null),ue+=he):he==='"'||he==="'"?(je=he,ue+=he):he==="&"&&J[ze+1]==="&"||he==="|"&&J[ze+1]==="|"?(ue.trim()&&(ce.push(ue.trim()),ue=""),ze++):he===";"||he==="|"||he==="&"?ue.trim()&&(ce.push(ue.trim()),ue=""):ue+=he}return ue.trim()&&ce.push(ue.trim()),ce},we=J=>{let ce=[],ue="",je=null;for(let ze=0;ze<J.length;ze++){let he=J[ze];je?(he===je&&(je=null),ue+=he):he==='"'||he==="'"?(je=he,ue+=he):/\s/.test(he)?ue&&(ce.push(ue),ue=""):ue+=he}return ue&&ce.push(ue),ce},Ne=J=>{let ce=J.replace(/^['"]|['"]$/g,"").trim();return!ce||process.platform==="win32"&&/^\/[a-zA-Z0-9?]+$/.test(ce)?!1:H.some(ue=>{if(ue.source==="[a-zA-Z]:[\\\\\\/]"){let je=ce.match(/[a-zA-Z]:[\\\/]/i);return je&&je[0].toLowerCase()!==se}return ue.test(ce)})};if(ge(S).some(J=>{let ce=we(J);if(ce.length===0)return!1;let ue=ce[0].replace(/^['"]|['"]$/g,"").toLowerCase();if(["echo","printf","write-output"].includes(ue)){let ze=!1;return ce.some(he=>{let _t=he.replace(/^['"]|['"]$/g,"");if(_t===">"||_t===">>"||_t==="<")return ze=!0,!1;if(_t.startsWith(">")||_t.startsWith("<")){let Oe=_t.replace(/^[><]+/,"");return Ne(Oe)}return ze?(ze=!1,Ne(he)):!1})}return ce.some(ze=>Ne(ze))})){let J='Access Denied. Prohibited from accessing external directories while "External Workspace Access" is disabled.';n.onExecStart&&n.onExecStart(S||"No Command"),yield{type:"exec_start"},await new Promise(ce=>setTimeout(ce,50)),n.onExecChunk&&n.onExecChunk(`ERROR: ${J}`),await new Promise(ce=>setTimeout(ce,50)),n.onExecEnd&&n.onExecEnd(),Me.push({role:"user",text:`[ACTION RESULT]: ERROR: ${J}`}),yield{type:"tool_result",content:`[ACTION RESULT]: ERROR: ${J}`},ut++;continue}}n.onExecStart&&n.onExecStart(S||"No Command"),yield{type:"exec_start"}}let $t=ne(N.args),Bn=$t.path||$t.targetPath||null;if(Bn){let S=n.systemSettings&&n.systemSettings.allowExternalAccess===!1,H=ie.resolve(Bn),se=ie.resolve(process.cwd());if(S&&!H.startsWith(se)){let ge="Access Denied. You are not allowed to access files outside the current workspace.";if(b==="write_file"||b==="update_file"){let Ne=`\u2718 ${b==="write_file"?"Write Canceled":"Edit Canceled"}: ${$t.path||"..."}`,De=115;process.stdout.isTTY&&(De=process.stdout.columns-5||120);let Ce=Math.min(Ne.length+4,De),J=`${Ne.padEnd(Ce-2).substring(0,Ce-2)}`;yield{type:"visual_feedback",content:Yt(`${Ye?`
737
+ `).length;je=bt,!Ce&&!J&&bt>800?ze=Math.min(50,bt):ze=Math.min(ue,bt)}}catch{}let Oe=(S||"").toLowerCase(),pt=Oe.endsWith(".pdf"),$e=Oe.endsWith(".docx")||Oe.endsWith(".doc")||Oe.endsWith(".ppt")||Oe.endsWith(".pptx")||Oe.endsWith(".xls")||Oe.endsWith(".xlsx"),tt=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(Oe);pt||$e?X=`${S.length>0?"\u2714":"\u2718"} ${S?`Analyzed: ${ie.basename(S)}`:"Analyzed: File Not Found"}`:tt?X=`${S.length>0?"\u2714":"\u2718"} ${S?`Processed: ${ie.basename(S)}`:"Processed: File Not Found"}`:X=`${je!=="..."?"\u2714":"\u2718"} Read: ${S?`${ie.basename(S)} \u2192 ${je!=="..."?`Lines ${ce} - ${ze} of ${je}`:"File Not Found"}`:"File Not Found"}`}}else if(b==="list_files"||b==="read_folder"){let S=b==="list_files"?"List":"Browsed",H=ne(N.args).path||null,se=ne(N.args).recurse||1;X=`${H?"\u2714":"\u2718"} ${S}: ${H?`${H==="."?`./${se>1?"*":""}`:`${H.replaceAll("\\","/")}${se>1?`${H.endsWith("/")?"*":"/*"}`:`${H.endsWith("/")?"":"/"}`}`}`:"No Folder Selected"}`}else if(b==="find_file"){let S=ne(N.args),H=S.basename||S.name||S.path||S.file||S.query||"";X=`${H?"\u2714":"\u2718"} Located: ${H||"No Query"}`}else if(b==="write_file"||b==="update_file"){let S=b==="write_file"?"Created":"Edited",H=ne(N.args),se=H.path||null,we=Object.entries(H).some(([Ne,De])=>Ne.startsWith("searchContent")&&typeof De=="string"&&De.startsWith("^LINE:"))?"\u1361":":";X=`${se?"\u2714":"\u2718"} ${S}${we} ${se?se.replaceAll("\\","/"):"No File Changes"}`}else if(b==="write_pdf"){let S=ne(N.args).path||null;X=`${S?"\u2714":"\u2718"} Generated: ${S.replaceAll("\\","/")||"No PDF Generated"}`}else if(b==="write_docx"){let S=ne(N.args).path||null;X=`${S?"\u2714":"\u2718"} Generated: ${S.replaceAll("\\","/")||"No Docx Generated"}`}else if(b==="file_map"){let S=ne(N.args).path;X=`${S?"\u2714":"\u2718"} Indexed: ${S.replaceAll("\\","/")?""+S:"File Not Found"}`}else if(b.toLowerCase()==="search_keyword"||b.toLowerCase()==="todo")X="";else if(b.toLowerCase()==="generate_image"){let{path:S,outputPath:H,output:se}=ne(N.args);X=`\u2714 Generated: ${S||H||se||"generated_image.png"}`}else if(b==="invoke_sync"||b==="InvokeSync"){let S=Kn(b,N.args);X=`\u2714 Called Generalist${S?`: ${S}`:""}`}else if(b==="Invoke"||b==="InvokeAsync"||b==="invoke"){let S=Kn(b,N.args);X=`\u2714 Started Generalist${S?`: ${S}`:""}`}else if(b==="get_progress"||b==="GetProgress"){let S=Kn(b,N.args);X=`\u2714 Checked${S?`: ${S}`:""}`}else if(b==="cancel"){let S=Kn(b,N.args);X=`\u{1F6C7} Cancelled${S?`: ${S}`:""}`}else if(b==="steer"||b==="Steer"){let S=Kn(b,N.args);X=`\u2714 Steered${S?`: ${S}`:""}`}else if(b==="EmergencyRollback"){let{method:S}=ne(N.args);X=S==="forceRevert"?"":"\u2714 Rollback Point Checked"}else if(b==="await"||b==="Await"){let{time:S,timeout:H}=ne(N.args),se=parseFloat(H||S)||0;se||(se=120);let ge=De=>{if(De>=60){let Ce=Math.floor(De/60),J=De%60;return`${Ce}m${J>0?` ${J}s`:""}`}return`${De}s`},we=["Aligning Moon Phase","Contemplating Existence","Staring At Void","Delaying Professionally","Negotiating With Electrons","Touching Grass (virtually)","Panicking Softly","Rethinking Career Choices","Loading Cat Videos","Summoning Braincell #2","Pretending To Be Busy","Waiting For Motivation DLC","Rotating Internal Screaming","Downloading More RAM","Feeding The Hamsters","Gaslighting Scheduler","Performing Dramatic Pause","Buffering Social Energy","Calculating Regret","Reading Terms And Conditions","Becoming Sentient Briefly","Contacting Ancestors"];X=`\u2714 ${we[Math.floor(Math.random()*we.length)]} \u2192 ${ge(se)}`}else b==="Answer"||b==="answer"?X="\u2714 Resolved Sub-Agent Query":b==="exec_command"||b==="ask"?X="":X=`Executed: ${N.toolName}`;if(yield*Nn(),b==="exec_command"){let{command:S}=ne(N.args);if(S&&n.systemSettings&&n.systemSettings.allowExternalAccess===!1){let H=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],se=ie.resolve(process.cwd()).substring(0,3).toLowerCase(),ge=J=>{let ce=[],ue="",je=null;for(let ze=0;ze<J.length;ze++){let he=J[ze];je?(he===je&&(je=null),ue+=he):he==='"'||he==="'"?(je=he,ue+=he):he==="&"&&J[ze+1]==="&"||he==="|"&&J[ze+1]==="|"?(ue.trim()&&(ce.push(ue.trim()),ue=""),ze++):he===";"||he==="|"||he==="&"?ue.trim()&&(ce.push(ue.trim()),ue=""):ue+=he}return ue.trim()&&ce.push(ue.trim()),ce},we=J=>{let ce=[],ue="",je=null;for(let ze=0;ze<J.length;ze++){let he=J[ze];je?(he===je&&(je=null),ue+=he):he==='"'||he==="'"?(je=he,ue+=he):/\s/.test(he)?ue&&(ce.push(ue),ue=""):ue+=he}return ue&&ce.push(ue),ce},Ne=J=>{let ce=J.replace(/^['"]|['"]$/g,"").trim();return!ce||process.platform==="win32"&&/^\/[a-zA-Z0-9?]+$/.test(ce)?!1:H.some(ue=>{if(ue.source==="[a-zA-Z]:[\\\\\\/]"){let je=ce.match(/[a-zA-Z]:[\\\/]/i);return je&&je[0].toLowerCase()!==se}return ue.test(ce)})};if(ge(S).some(J=>{let ce=we(J);if(ce.length===0)return!1;let ue=ce[0].replace(/^['"]|['"]$/g,"").toLowerCase();if(["echo","printf","write-output"].includes(ue)){let ze=!1;return ce.some(he=>{let _t=he.replace(/^['"]|['"]$/g,"");if(_t===">"||_t===">>"||_t==="<")return ze=!0,!1;if(_t.startsWith(">")||_t.startsWith("<")){let Oe=_t.replace(/^[><]+/,"");return Ne(Oe)}return ze?(ze=!1,Ne(he)):!1})}return ce.some(ze=>Ne(ze))})){let J='Access Denied. Prohibited from accessing external directories while "External Workspace Access" is disabled.';n.onExecStart&&n.onExecStart(S||"No Command"),yield{type:"exec_start"},await new Promise(ce=>setTimeout(ce,50)),n.onExecChunk&&n.onExecChunk(`ERROR: ${J}`),await new Promise(ce=>setTimeout(ce,50)),n.onExecEnd&&n.onExecEnd(),Me.push({role:"user",text:`[ACTION RESULT]: ERROR: ${J}`}),yield{type:"tool_result",content:`[ACTION RESULT]: ERROR: ${J}`},ut++;continue}}n.onExecStart&&n.onExecStart(S||"No Command"),yield{type:"exec_start"}}let $t=ne(N.args),Bn=$t.path||$t.targetPath||null;if(Bn){let S=n.systemSettings&&n.systemSettings.allowExternalAccess===!1,H=ie.resolve(Bn),se=ie.resolve(process.cwd());if(S&&!H.startsWith(se)){let ge="Access Denied. You are not allowed to access files outside the current workspace.";if(b==="write_file"||b==="update_file"){let Ne=`\u2718 ${b==="write_file"?"Write Canceled":"Edit Canceled"}: ${$t.path||"..."}`,De=115;process.stdout.isTTY&&(De=process.stdout.columns-5||120);let Ce=Math.min(Ne.length+4,De),J=`${Ne.padEnd(Ce-2).substring(0,Ce-2)}`;yield{type:"visual_feedback",content:Yt(`${Ye?`
739
738
  `:""}${J}
740
- `)},Ye=!1}Me.push({role:"user",text:`[ACTION RESULT]: ERROR: ${ge}`}),yield{type:"tool_result",content:`[ACTION RESULT]: ERROR: ${ge}`},ut++;continue}}if(n.onToolApproval&&(b==="write_file"||b==="update_file"||b==="exec_command")){let H=n.systemSettings||{},se=H.autoExec,ge=null,we=!1,Ne=!1,De=!1;if(b==="exec_command"){let{command:Oe}=ne(N.args),mt=(Oe||"").trim(),$e=(Gt,bt)=>{if(!bt)return!1;let Zt=bt.split(",").map(jt=>jt.trim().toLowerCase()).filter(Boolean),at=Gt.toLowerCase();return Zt.some(jt=>at.startsWith(jt))},tt=$e(mt,H.alwaysAskCommands),_e=$e(mt,H.autoApproveCommands);if(Ne=$e(mt,H.autoDisallowCommands),tt?we=!0:(_e||H.autoApproveGit&&/^git\s+commit\b/i.test(mt))&&(ge="allow"),!we&&!ge){if(H.networkAccess===!1){let bt=mt.trim().replace(/\s+/g," ").replace(/^['"]+|['"]+$/g,"").toLowerCase().split(" "),at=bt[0].split("/").pop().split("\\").pop().replace(/\.exe$/,""),jt=new Set(["curl","wget","httpie","xh","ssh","scp","sftp","rsync","ftp","lftp","tftp","telnet","nc","netcat","socat","ping","traceroute","tracert","dig","nslookup","host","whois","nmap","docker","podman","kubectl","helm","gcloud","aws","az","terraform","ansible-playbook","nix","nix-env","apt","apt-get","dpkg","yum","dnf","pacman","zypper","brew","apk","choco","scoop","conda","mamba","aria2c","axel","smbclient","lynx","w3m","links","elinks","heroku","netlify","vercel","firebase","supabase","wrangler","flyctl","powershell","pwsh","certutil","bitsadmin","cloudflared","ngrok","tailscale","zerotier","rclone"]),lt=!1;jt.has(at)&&(lt=!0);let nt=En=>bt.slice(1).some(mn=>En.includes(mn)),ct=En=>{let mn=bt.findIndex(pn=>En.includes(pn)),Un=bt.findIndex(pn=>["run","exec","test"].includes(pn));return mn!==-1&&!(Un!==-1&&Un<mn)};at==="git"&&nt(["clone","pull","push","fetch"])&&(lt=!0),at==="go"&&nt(["get","install"])&&(lt=!0),at==="npm"&&ct(["install","i","update","add"])&&(lt=!0),at==="yarn"&&ct(["add","install","upgrade"])&&(lt=!0),at==="pnpm"&&ct(["add","install","update"])&&(lt=!0),at==="bun"&&ct(["add","install","update"])&&(lt=!0),at==="deno"&&nt(["install","add"])&&(lt=!0),at==="pip"&&nt(["install","download"])&&(lt=!0),at==="pip3"&&nt(["install","download"])&&(lt=!0),at==="cargo"&&nt(["install","add"])&&(lt=!0),["bash","sh","zsh","fish"].includes(at)&&nt(["-c"])&&(lt=!0),at==="cmd"&&nt(["/c"])&&(lt=!0),lt&&(ge="deny",De=!0)}!ge&&Ne&&(ge="deny")}!we&&!ge&&se&&(ge="allow")}else se&&(ge="allow");let Ce=ge,J="";ge==="deny"&&(De?J="network":Ne?J="settings":J="prohibited");let ce=!1,ue="",je=[],ze=0,he=!1,_t="";if(!Ce){if(b==="write_file"||b==="update_file")try{let $e=ne(N.args),{path:tt}=$e;if(tt){let _e=ie.resolve(process.cwd(),tt),Gt=nt=>nt?nt.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,ct=>ct.toUpperCase()):"",bt=Gt(_e),Zt="",at=!1,jt=await Hn(),lt=Gt(jt?.file_focused);if(jt&&lt===bt&&jt.full_content?(Zt=jt.full_content,at=!0):Ue.existsSync(_e)&&(Zt=Ue.readFileSync(_e,"utf8"),at=!0),ue=Zt,await Oo.recordFileChange(_e,Zt),at){let nt=Zt;if(b==="write_file"){let ct=$e.content||$e.newContent||"";nt=ct.endsWith(`
739
+ `)},Ye=!1}Me.push({role:"user",text:`[ACTION RESULT]: ERROR: ${ge}`}),yield{type:"tool_result",content:`[ACTION RESULT]: ERROR: ${ge}`},ut++;continue}}if(n.onToolApproval&&(b==="write_file"||b==="update_file"||b==="exec_command")){let H=n.systemSettings||{},se=H.autoExec,ge=null,we=!1,Ne=!1,De=!1;if(b==="exec_command"){let{command:Oe}=ne(N.args),pt=(Oe||"").trim(),$e=(Gt,bt)=>{if(!bt)return!1;let Zt=bt.split(",").map(jt=>jt.trim().toLowerCase()).filter(Boolean),at=Gt.toLowerCase();return Zt.some(jt=>at.startsWith(jt))},tt=$e(pt,H.alwaysAskCommands),_e=$e(pt,H.autoApproveCommands);if(Ne=$e(pt,H.autoDisallowCommands),tt?we=!0:(_e||H.autoApproveGit&&/^git\s+commit\b/i.test(pt))&&(ge="allow"),!we&&!ge){if(H.networkAccess===!1){let bt=pt.trim().replace(/\s+/g," ").replace(/^['"]+|['"]+$/g,"").toLowerCase().split(" "),at=bt[0].split("/").pop().split("\\").pop().replace(/\.exe$/,""),jt=new Set(["curl","wget","httpie","xh","ssh","scp","sftp","rsync","ftp","lftp","tftp","telnet","nc","netcat","socat","ping","traceroute","tracert","dig","nslookup","host","whois","nmap","docker","podman","kubectl","helm","gcloud","aws","az","terraform","ansible-playbook","nix","nix-env","apt","apt-get","dpkg","yum","dnf","pacman","zypper","brew","apk","choco","scoop","conda","mamba","aria2c","axel","smbclient","lynx","w3m","links","elinks","heroku","netlify","vercel","firebase","supabase","wrangler","flyctl","powershell","pwsh","certutil","bitsadmin","cloudflared","ngrok","tailscale","zerotier","rclone"]),lt=!1;jt.has(at)&&(lt=!0);let nt=En=>bt.slice(1).some(pn=>En.includes(pn)),ct=En=>{let pn=bt.findIndex(mn=>En.includes(mn)),Un=bt.findIndex(mn=>["run","exec","test"].includes(mn));return pn!==-1&&!(Un!==-1&&Un<pn)};at==="git"&&nt(["clone","pull","push","fetch"])&&(lt=!0),at==="go"&&nt(["get","install"])&&(lt=!0),at==="npm"&&ct(["install","i","update","add"])&&(lt=!0),at==="yarn"&&ct(["add","install","upgrade"])&&(lt=!0),at==="pnpm"&&ct(["add","install","update"])&&(lt=!0),at==="bun"&&ct(["add","install","update"])&&(lt=!0),at==="deno"&&nt(["install","add"])&&(lt=!0),at==="pip"&&nt(["install","download"])&&(lt=!0),at==="pip3"&&nt(["install","download"])&&(lt=!0),at==="cargo"&&nt(["install","add"])&&(lt=!0),["bash","sh","zsh","fish"].includes(at)&&nt(["-c"])&&(lt=!0),at==="cmd"&&nt(["/c"])&&(lt=!0),lt&&(ge="deny",De=!0)}!ge&&Ne&&(ge="deny")}!we&&!ge&&se&&(ge="allow")}else se&&(ge="allow");let Ce=ge,J="";ge==="deny"&&(De?J="network":Ne?J="settings":J="prohibited");let ce=!1,ue="",je=[],ze=0,he=!1,_t="";if(!Ce){if(b==="write_file"||b==="update_file")try{let $e=ne(N.args),{path:tt}=$e;if(tt){let _e=ie.resolve(process.cwd(),tt),Gt=nt=>nt?nt.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,ct=>ct.toUpperCase()):"",bt=Gt(_e),Zt="",at=!1,jt=await Hn(),lt=Gt(jt?.file_focused);if(jt&&lt===bt&&jt.full_content?(Zt=jt.full_content,at=!0):Ue.existsSync(_e)&&(Zt=Ue.readFileSync(_e,"utf8"),at=!0),ue=Zt,await Oo.recordFileChange(_e,Zt),at){let nt=Zt;if(b==="write_file"){let ct=$e.content||$e.newContent||"";nt=ct.endsWith(`
741
740
  `)?ct:ct+`
742
- `,_t=nt}else{let{patchPairs:ct,allowMultiple:En,error:mn}=Ti($e);if(mn){let Xt=`[ACTION RESULT]: ERROR: ${mn}`;Me.push({role:"user",text:Xt}),await Rt("toolFailure"),n.onToolResult&&n.onToolResult("failure",b),yield{type:"tool_result",content:Xt,toolName:b},ut++;continue}let Un=$e.allowMultiple!==void 0?$e.allowMultiple===!0||String($e.allowMultiple).toLowerCase()==="true":En;ze=ct.length;let pn=Si(Zt,ct,{allowMultiple:Un});nt=pn.content,_t=nt,je=pn.results;let Eo=je.filter(Xt=>Xt.success),xs=je.filter(Xt=>!Xt.success);if(Eo.length===0){let Xt=`[ACTION RESULT]: ERROR: Failed to apply patches to [${ie.basename(_e)}].
741
+ `,_t=nt}else{let{patchPairs:ct,allowMultiple:En,error:pn}=Ti($e);if(pn){let Xt=`[ACTION RESULT]: ERROR: ${pn}`;Me.push({role:"user",text:Xt}),await Rt("toolFailure"),n.onToolResult&&n.onToolResult("failure",b),yield{type:"tool_result",content:Xt,toolName:b},ut++;continue}let Un=$e.allowMultiple!==void 0?$e.allowMultiple===!0||String($e.allowMultiple).toLowerCase()==="true":En;ze=ct.length;let mn=Si(Zt,ct,{allowMultiple:Un});nt=mn.content,_t=nt,je=mn.results;let Eo=je.filter(Xt=>Xt.success),xs=je.filter(Xt=>!Xt.success);if(Eo.length===0){let Xt=`[ACTION RESULT]: ERROR: Failed to apply patches to [${ie.basename(_e)}].
743
742
  ${xs.map(Co=>` \u2022 ${Co.error}`).join(`
744
743
  `)}`,oo=`\u2714 Edited: ${ie.basename(_e.replaceAll("\\","/"))}`,dt=115;process.stdout.isTTY&&(dt=process.stdout.columns-5||120);let Kt=Math.min(oo.length+4,dt),so=`${oo.padEnd(Kt-2).substring(0,Kt-2)}`;yield{type:"visual_feedback",content:Yt(`${Ye?`
745
744
  `:""}${so}`)},Ye=!1,Me.push({role:"user",text:Xt}),await Rt("toolFailure"),n.onToolResult&&n.onToolResult("failure",b),yield{type:"tool_result",content:Xt,toolName:b},ut++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${ie.basename(_e)}`},zs(_e,Zt,nt),ce=!0,await new Promise(ct=>setTimeout(ct,50))}else if(b==="write_file"){let nt=$e.content||$e.newContent||"",ct=nt.endsWith(`
746
745
  `)?nt:nt+`
747
- `;_t=ct,Ue.existsSync(_e)||(he=!0,Ue.mkdirSync(ie.dirname(_e),{recursive:!0}),Ue.writeFileSync(_e,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${ie.basename(_e)}`},zs(_e,"",ct),ce=!0,await new Promise(En=>setTimeout(En,50))}}}catch($e){console.error("Simulation/Diff Error:",$e)}let Oe=null;qs($e=>{Oe=$e});let mt=n.onToolApproval;if(Ce=await new Promise(async $e=>{let tt=setInterval(()=>{Oe&&(as.onIDEApproval&&as.onIDEApproval(Oe),clearInterval(tt),$e(Oe))},100);try{let _e=await mt(b,N.args);clearInterval(tt),$e(_e)}catch{clearInterval(tt),$e("deny")}}),qs(null),b==="write_file"||b==="update_file"){let{path:$e}=ne(N.args);if($e){let tt=ie.resolve(process.cwd(),$e);if(Nr(tt,Ce),Ce==="deny"&&he&&Ue.existsSync(tt))try{Ue.unlinkSync(tt)}catch{}}}Ce==="deny"&&(J="user")}if(Ce==="allow"&&ce&&zo()){let{path:Oe}=ne(N.args),mt=ie.resolve(process.cwd(),Oe),$e=dt=>dt?ie.resolve(dt).replace(/\\/g,"/").toLowerCase():"",tt=await Hn(),_e="";if(tt&&tt.file_focused&&$e(tt.file_focused)===$e(mt)&&tt.full_content&&(_e=tt.full_content),!_e&&Ue.existsSync(mt)){let dt=Ue.readFileSync(mt,"utf8");dt&&(_e=dt)}!_e&&_t&&(_e=_t),(_e||he)&&Ue.writeFileSync(mt,_e,"utf8");let Gt=_e.split(/\r?\n/),bt=Gt.length,Zt=Buffer.byteLength(_e,"utf8"),at="";ue&&(at=`Old File contents:
746
+ `;_t=ct,Ue.existsSync(_e)||(he=!0,Ue.mkdirSync(ie.dirname(_e),{recursive:!0}),Ue.writeFileSync(_e,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${ie.basename(_e)}`},zs(_e,"",ct),ce=!0,await new Promise(En=>setTimeout(En,50))}}}catch($e){console.error("Simulation/Diff Error:",$e)}let Oe=null;qs($e=>{Oe=$e});let pt=n.onToolApproval;if(Ce=await new Promise(async $e=>{let tt=setInterval(()=>{Oe&&(as.onIDEApproval&&as.onIDEApproval(Oe),clearInterval(tt),$e(Oe))},100);try{let _e=await pt(b,N.args);clearInterval(tt),$e(_e)}catch{clearInterval(tt),$e("deny")}}),qs(null),b==="write_file"||b==="update_file"){let{path:$e}=ne(N.args);if($e){let tt=ie.resolve(process.cwd(),$e);if(Nr(tt,Ce),Ce==="deny"&&he&&Ue.existsSync(tt))try{Ue.unlinkSync(tt)}catch{}}}Ce==="deny"&&(J="user")}if(Ce==="allow"&&ce&&zo()){let{path:Oe}=ne(N.args),pt=ie.resolve(process.cwd(),Oe),$e=dt=>dt?ie.resolve(dt).replace(/\\/g,"/").toLowerCase():"",tt=await Hn(),_e="";if(tt&&tt.file_focused&&$e(tt.file_focused)===$e(pt)&&tt.full_content&&(_e=tt.full_content),!_e&&Ue.existsSync(pt)){let dt=Ue.readFileSync(pt,"utf8");dt&&(_e=dt)}!_e&&_t&&(_e=_t),(_e||he)&&Ue.writeFileSync(pt,_e,"utf8");let Gt=_e.split(/\r?\n/),bt=Gt.length,Zt=Buffer.byteLength(_e,"utf8"),at="";ue&&(at=`Old File contents:
748
747
  ${ue.split(/\r?\n/).map((Kt,so)=>`${so+1} | ${Kt}`).join(`
749
748
  `)}
750
749
 
@@ -772,12 +771,12 @@ ${ws}`}lt=`File [${Oe}] saved via IDE Companion (May have user edits).
772
771
  - Stats: [${Kt} lines, ${(so/1024).toFixed(1)} KB]
773
772
  ${Co}- Content Preview:
774
773
 
775
- ${bs}`}let nt=b==="write_file"?"Created":"Edited",ct=ne(N.args),mn=Object.entries(ct).some(([dt,Kt])=>dt.startsWith("searchContent")&&typeof Kt=="string"&&Kt.startsWith("^LINE:"))?"\u1361":":",Un=`${Oe?"\u2714":"\u2718"} ${nt}${mn} ${Oe?Oe.replaceAll("\\","/"):"No File Changes"}`,pn=115;process.stdout.isTTY&&(pn=process.stdout.columns-5||120);let Eo=Math.min(Un.length+4,pn),xs=`${Un.padEnd(Eo-2).substring(0,Eo-2)}`;yield{type:"visual_feedback",content:Yt(`${Ye?`
774
+ ${bs}`}let nt=b==="write_file"?"Created":"Edited",ct=ne(N.args),pn=Object.entries(ct).some(([dt,Kt])=>dt.startsWith("searchContent")&&typeof Kt=="string"&&Kt.startsWith("^LINE:"))?"\u1361":":",Un=`${Oe?"\u2714":"\u2718"} ${nt}${pn} ${Oe?Oe.replaceAll("\\","/"):"No File Changes"}`,mn=115;process.stdout.isTTY&&(mn=process.stdout.columns-5||120);let Eo=Math.min(Un.length+4,mn),xs=`${Un.padEnd(Eo-2).substring(0,Eo-2)}`;yield{type:"visual_feedback",content:Yt(`${Ye?`
776
775
  `:""}${xs}`)},Ye=!1;let Xt=Date.now();We=Xt,yield{type:"tool_time",content:Xt-V};let oo=`[ACTION RESULT]: ${lt}`;Me.push({role:"user",text:oo}),kn=!0,await Rt("toolSuccess"),n.onToolResult&&n.onToolResult("success",b),yield{type:"tool_result",content:lt,aiContent:oo,toolName:b},ut++;continue}if(Ce==="deny"){let Oe=`Permission Denied: Prohibited ${b==="exec_command"?"Command":"file edit"}.`;if(J==="user"?Oe="Permission Denied by User":J==="settings"?Oe="Permission Denied by User Policy":J==="network"?Oe="Permission Denied: Sandbox Network Access Disabled by User Policy.":J==="prohibited"&&b==="exec_command"&&(Oe="Permission Denied: Prohibited Command in User Policy"),b==="write_file"||b==="update_file"){let $e=`\u2718 ${b==="write_file"?"Write Cancelled":"Edit Denied"}: ${ne(N.args).path.replaceAll("\\","/")||"..."}`,tt=115;process.stdout.isTTY&&(tt=process.stdout.columns-5||120);let _e=Math.min($e.length+4,tt),Gt=`${$e.padEnd(_e-2).substring(0,_e-2)}`,bt=` ${" ".repeat(_e)} `;yield{type:"visual_feedback",content:Yt(`${Ye?`
777
776
  `:""}${Gt}
778
- `)},Ye=!1}b==="exec_command"&&(await new Promise(mt=>setTimeout(mt,50)),n.onExecChunk&&n.onExecChunk(`ERROR: ${Oe}`),await new Promise(mt=>setTimeout(mt,50)),n.onExecEnd&&n.onExecEnd()),Me.push({role:"user",text:`[ACTION RESULT]: DENIED: ${Oe}`}),yield{type:"tool_result",content:`[ACTION RESULT]: DENIED: ${Oe}`},await Rt("toolDenied"),n.onToolResult&&n.onToolResult("denied",b),ut++;continue}}if(X){let S=115;process.stdout.isTTY&&(S=process.stdout.columns-5||120);let H=await s(),se=!1;H&&(se=H.trim().length>0);let ge=Math.min(X.length+4,S),we=`${X.padEnd(ge-2).substring(0,ge-2)}`;yield{type:"visual_feedback",content:Yt(`${Ye?`
777
+ `)},Ye=!1}b==="exec_command"&&(await new Promise(pt=>setTimeout(pt,50)),n.onExecChunk&&n.onExecChunk(`ERROR: ${Oe}`),await new Promise(pt=>setTimeout(pt,50)),n.onExecEnd&&n.onExecEnd()),Me.push({role:"user",text:`[ACTION RESULT]: DENIED: ${Oe}`}),yield{type:"tool_result",content:`[ACTION RESULT]: DENIED: ${Oe}`},await Rt("toolDenied"),n.onToolResult&&n.onToolResult("denied",b),ut++;continue}}if(X){let S=115;process.stdout.isTTY&&(S=process.stdout.columns-5||120);let H=await s(),se=!1;H&&(se=H.trim().length>0);let ge=Math.min(X.length+4,S),we=`${X.padEnd(ge-2).substring(0,ge-2)}`;yield{type:"visual_feedback",content:Yt(`${Ye?`
779
778
  `:""}${we}${X.includes("\u2714")&&(X.includes("Created")||X.includes("Edited"))?"":`${se?"":`
780
- `}`}`)},Ye=!1}if(We>0){let S=Date.now()-We,H=Math.max(0,1e3-S);H>0&&await new Promise(se=>setTimeout(se,H))}let An={chatId:p,history:t,onChunk:S=>n.onExecChunk?n.onExecChunk(S):null,onAskUser:n.onAskUser,systemSettings:n.systemSettings,mode:l,isMultiModal:ft(Se),onVisualFeedback:n.onVisualFeedback,onSubagentUpdate:n.onSubagentUpdate,onTokenChunk:n.onTokenChunk,modelName:Se,aiProvider:n.aiProvider,apiKey:n.apiKey,onUsage:n.onUsage};if(b==="write_file"||b==="update_file")try{let{path:S}=ne(N.args);if(S){let H=ie.resolve(process.cwd(),S),se=await Hn();se&&se.file_focused===H&&se.full_content&&(An.forcedContent=se.full_content)}}catch{}ot.push(b);let Le=await xo(b,N.args,An);if((b==="write_file"||b==="update_file")&&!Le.startsWith("ERROR:")){let{path:S}=ne(N.args);if(S){let H=ie.resolve(process.cwd(),S);$r(H)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let Nt=Date.now();We=Nt,yield{type:"tool_time",content:Nt-V},K=Nt;let Ht=null;if(typeof Le=="object"&&Le.binaryPart&&(Ht=Le.binaryPart,Le=Le.text),b==="search_keyword"){let{keyword:S,path:H}=ne(N.args),se=typeof Le=="string"&&Le.startsWith("[GLOB]");se&&(Le=Le.slice(6).trimStart());let ge=typeof Le=="string"&&Le.startsWith("[DIR]");ge&&(Le=Le.slice(5).trimStart());let we=0;if(Le){let he=Le.match(/Found (\d+) match/i);he&&(we=parseInt(he[1]))}let Ne=(H||"").trim().toLowerCase().replaceAll("\\","/"),De=Ne==="#doc"||Ne==="#docs"||Ne==="#documentation"||Ne.includes("#skill/global/fluxflow")||Ne.includes("#skill/fluxflow")||Ne.includes("#skills/fluxflow")||Ne.includes("#skills/global/fluxflow"),Ce,J=115;process.stdout.isTTY&&(J=process.stdout.columns-5||120);let ce=Math.max(10,(J+5)/3),ue=Math.max(10,(J+5)/4);if(De)Ce=`${S?"\u2714":"\u2718"} Searched Documentation`;else{let he=H?H.replace(/[\/\\]+$/,""):null,_t=he&&he!=="."?`${se?H:ge?`${he}/*`:he}`:"./",Oe=_t.length>ue?`${_t.slice(0,ue)}...`:_t;Ce=`${S?"\u2714":"\u2718"} Searched: "${S?S.length>J/2?`${S.slice(0,ce)}...`:S:""}" in "${Oe.replaceAll("\\","/")}" \u2192 ${we} Match${we===1?"":"es"}`}let je=Math.min(Ce.length+4,J),ze=`${Ce.padEnd(je-2).substring(0,je-2)}`;yield{type:"visual_feedback",content:Yt(`${Ye?`
779
+ `}`}`)},Ye=!1}if(We>0){let S=Date.now()-We,H=Math.max(0,1e3-S);H>0&&await new Promise(se=>setTimeout(se,H))}let An={chatId:m,history:t,onChunk:S=>n.onExecChunk?n.onExecChunk(S):null,onAskUser:n.onAskUser,systemSettings:n.systemSettings,mode:l,isMultiModal:ft(Se),onVisualFeedback:n.onVisualFeedback,onSubagentUpdate:n.onSubagentUpdate,onTokenChunk:n.onTokenChunk,modelName:Se,aiProvider:n.aiProvider,apiKey:n.apiKey,onUsage:n.onUsage};if(b==="write_file"||b==="update_file")try{let{path:S}=ne(N.args);if(S){let H=ie.resolve(process.cwd(),S),se=await Hn();se&&se.file_focused===H&&se.full_content&&(An.forcedContent=se.full_content)}}catch{}ot.push(b);let Le=await xo(b,N.args,An);if((b==="write_file"||b==="update_file")&&!Le.startsWith("ERROR:")){let{path:S}=ne(N.args);if(S){let H=ie.resolve(process.cwd(),S);$r(H)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let Nt=Date.now();We=Nt,yield{type:"tool_time",content:Nt-V},K=Nt;let Ht=null;if(typeof Le=="object"&&Le.binaryPart&&(Ht=Le.binaryPart,Le=Le.text),b==="search_keyword"){let{keyword:S,path:H}=ne(N.args),se=typeof Le=="string"&&Le.startsWith("[GLOB]");se&&(Le=Le.slice(6).trimStart());let ge=typeof Le=="string"&&Le.startsWith("[DIR]");ge&&(Le=Le.slice(5).trimStart());let we=0;if(Le){let he=Le.match(/Found (\d+) match/i);he&&(we=parseInt(he[1]))}let Ne=(H||"").trim().toLowerCase().replaceAll("\\","/"),De=Ne==="#doc"||Ne==="#docs"||Ne==="#documentation"||Ne.includes("#skill/global/fluxflow")||Ne.includes("#skill/fluxflow")||Ne.includes("#skills/fluxflow")||Ne.includes("#skills/global/fluxflow"),Ce,J=115;process.stdout.isTTY&&(J=process.stdout.columns-5||120);let ce=Math.max(10,(J+5)/3),ue=Math.max(10,(J+5)/4);if(De)Ce=`${S?"\u2714":"\u2718"} Searched Documentation`;else{let he=H?H.replace(/[\/\\]+$/,""):null,_t=he&&he!=="."?`${se?H:ge?`${he}/*`:he}`:"./",Oe=_t.length>ue?`${_t.slice(0,ue)}...`:_t;Ce=`${S?"\u2714":"\u2718"} Searched: "${S?S.length>J/2?`${S.slice(0,ce)}...`:S:""}" in "${Oe.replaceAll("\\","/")}" \u2192 ${we} Match${we===1?"":"es"}`}let je=Math.min(Ce.length+4,J),ze=`${Ce.padEnd(je-2).substring(0,je-2)}`;yield{type:"visual_feedback",content:Yt(`${Ye?`
781
780
  `:""}${ze}
782
781
  `)},Ye=!1}if(b==="EmergencyRollback"){let{method:S}=ne(N.args);if(S==="forceRevert"){let H=0;if(Le){let ce=Le.match(/Total\s*:\s*(\d+)/i);ce&&(H=parseInt(ce[1]))}let ge=Le&&Le.startsWith("ERROR:")?"\u2718 Emergency Rollback Failed":`\u2714 Emergency Rollback \u2192 ${H} file${H===1?"":"s"} processed`,we=115;process.stdout.isTTY&&(we=process.stdout.columns-5||120);let Ne=await s(),De=!1;Ne&&(De=Ne.trim().length>0);let Ce=Math.min(ge.length+4,we),J=`${ge.padEnd(Ce-2).substring(0,Ce-2)}`;yield{type:"visual_feedback",content:Yt(`${Ye?`
783
782
  `:""}${J}${De?"":`
@@ -794,9 +793,9 @@ ${bs}`}let nt=b==="write_file"?"Created":"Edited",ct=ne(N.args),mn=Object.entrie
794
793
  `)}
795
794
  [SYSTEM NOTE]: Content verified and persisted to disk. Full preview omitted to conserve context.`}else hn=`[ACTION RESULT]: ${Ft}`;Me.push({role:"user",text:hn,binaryPart:Ht}),kn=!0;let Pe=`[ACTION RESULT]: ${Le.replaceAll(`[[VERIFIED]]
796
795
  `,"").replaceAll(`
797
- [[/VERIFIED]]`,"")||""}`;(b==="view_file"||b==="web_scrape"||b==="file_map")&&(Pe=`[ACTION RESULT]: ${X} (Context Locked for UI Clarity)`),yield{type:"tool_result",content:Pe,aiContent:hn,binaryPart:Ht,toolName:b},b==="memory"&&!Le.startsWith("ERROR:")&&(yield{type:"memory_updated"}),ut++}if(i==="Google"&&an&&Date.now()-ms>=150){yield*Nn();let N=to(an);for(let V of N)yield V;an="",ms=Date.now()}}D.usageMetadata&&(Jt=D.usageMetadata),Jt&&(yield{type:"liveTokens",content:Jt.totalTokenCount})}if(me&&(me=!1,Dt?Qe+="</think>":(Te+="</think>",i==="Google"?an+="</think>":yield{type:"text",content:"</think>"})),Dt&&Qe.length>0){let D=0,Y=Math.min(xt.length,Qe.length);for(let q=Y;q>0;q--)if(xt.endsWith(Qe.substring(0,q))){D=q;break}let W=Qe.substring(D);if(W){let Z=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(xt)?W.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):W.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(Z)if(Te+=Z,i==="Google")an+=Z;else{yield*Nn();let z=to(Z);for(let le of z)yield le}}Dt=!1,Qe=""}if(yield*Nn(),wt)break;let no=(Te||"").trim(),ra=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(no.toLowerCase())||/\[\[END\]\]/i.test(no.toLowerCase()),aa=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(no.toLowerCase()),la=Me.length>0||Ve!==null,ps=qt(no).trim(),ca=/(\p{Emoji_Presentation}|\p{Extended_Pictographic})$/u.test(ps),da=/([.!?"'*_`|\]\)”’~~]+|\s|`{3}|[\u200B-\u200D\uFEFF])$/u.test(ps.trim()),fa=/[.!?}"'`’“”]$|```$/s.test(ps)||da||ca;!ra&&!aa&&!la&&no.length>0,st=!0,await Rt("agent",i)}catch(Ae){if(wt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
796
+ [[/VERIFIED]]`,"")||""}`;(b==="view_file"||b==="web_scrape"||b==="file_map")&&(Pe=`[ACTION RESULT]: ${X} (Context Locked for UI Clarity)`),yield{type:"tool_result",content:Pe,aiContent:hn,binaryPart:Ht,toolName:b},b==="memory"&&!Le.startsWith("ERROR:")&&(yield{type:"memory_updated"}),ut++}if(i==="Google"&&an&&Date.now()-ps>=150){yield*Nn();let N=to(an);for(let V of N)yield V;an="",ps=Date.now()}}D.usageMetadata&&(Jt=D.usageMetadata),Jt&&(yield{type:"liveTokens",content:Jt.totalTokenCount})}if(pe&&(pe=!1,Dt?Qe+="</think>":(Te+="</think>",i==="Google"?an+="</think>":yield{type:"text",content:"</think>"})),Dt&&Qe.length>0){let D=0,Y=Math.min(xt.length,Qe.length);for(let q=Y;q>0;q--)if(xt.endsWith(Qe.substring(0,q))){D=q;break}let W=Qe.substring(D);if(W){let Z=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(xt)?W.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):W.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(Z)if(Te+=Z,i==="Google")an+=Z;else{yield*Nn();let z=to(Z);for(let le of z)yield le}}Dt=!1,Qe=""}if(yield*Nn(),wt)break;let no=(Te||"").trim(),ra=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(no.toLowerCase())||/\[\[END\]\]/i.test(no.toLowerCase()),aa=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(no.toLowerCase()),la=Me.length>0||Ve!==null,ms=qt(no).trim(),ca=/(\p{Emoji_Presentation}|\p{Extended_Pictographic})$/u.test(ms),da=/([.!?"'*_`|\]\)”’~~]+|\s|`{3}|[\u200B-\u200D\uFEFF])$/u.test(ms.trim()),fa=/[.!?}"'`’“”]$|```$/s.test(ms)||da||ca;!ra&&!aa&&!la&&no.length>0,st=!0,await Rt("agent",i)}catch(Ae){if(wt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
798
797
 
799
- \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(String(Ae).includes("Incomplete JSON segment at the end")){me&&(me=!1,Dt?Qe+="</think>":(Te+="</think>",yield{type:"text",content:"</think>"})),st=!0,await Rt("agent",i);break}if(me&&(me=!1,Dt?Qe+="</think>":Te+="</think>"),Dt&&Qe.length>0){let Pt=0,Et=Math.min(xt.length,Qe.length);for(let It=Et;It>0;It--)if(xt.endsWith(Qe.substring(0,It))){Pt=It;break}let Tt=Qe.substring(Pt);if(Tt){let gt=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(xt)?Tt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):Tt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");gt&&(Te+=gt)}Dt=!1,Qe=""}let ee=Ae instanceof Error?(()=>{try{return JSON.parse(JSON.parse(Ae.message).error.message).error.message}catch{return String(Ae)}})():String(Ae),Lt=new Date().toLocaleString(),Mt=ie.join(Cn,"agent");Ue.existsSync(Mt)||Ue.mkdirSync(Mt,{recursive:!0}),Ue.appendFileSync(ie.join(Mt,"error.log"),`ERROR [${Lt}]: ${ee}
798
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(String(Ae).includes("Incomplete JSON segment at the end")){pe&&(pe=!1,Dt?Qe+="</think>":(Te+="</think>",yield{type:"text",content:"</think>"})),st=!0,await Rt("agent",i);break}if(pe&&(pe=!1,Dt?Qe+="</think>":Te+="</think>"),Dt&&Qe.length>0){let Pt=0,Et=Math.min(xt.length,Qe.length);for(let It=Et;It>0;It--)if(xt.endsWith(Qe.substring(0,It))){Pt=It;break}let Tt=Qe.substring(Pt);if(Tt){let gt=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(xt)?Tt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):Tt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");gt&&(Te+=gt)}Dt=!1,Qe=""}let ee=Ae instanceof Error?(()=>{try{return JSON.parse(JSON.parse(Ae.message).error.message).error.message}catch{return String(Ae)}})():String(Ae),Lt=new Date().toLocaleString(),Mt=ie.join(Cn,"agent");Ue.existsSync(Mt)||Ue.mkdirSync(Mt,{recursive:!0}),Ue.appendFileSync(ie.join(Mt,"error.log"),`ERROR [${Lt}]: ${ee}
800
799
 
801
800
  ----------------------------------------------------------------------
802
801
 
@@ -809,8 +808,8 @@ ${bs}`}let nt=b==="write_file"?"Created":"Edited",ct=ne(N.args),mn=Object.entrie
809
808
 
810
809
  ${Et}`}):r.push(Tt)}):r.push({role:"user",text:Et}),xt+=Te}for(let Et=Pt/1e3;Et>0&&!wt;Et--)yield{type:"status",content:`Error Occured. Recovering Stream (${rt}/${on}) [Retrying in ${Et.toFixed(0)}s]...`},await new Promise(Tt=>setTimeout(Tt,1e3));yield{type:"status",content:"Error Occured. Recovering Stream..."}}else throw new Error(`Stream collapsed too many times. (Failed to resolve ${on} times)
811
810
  Error log can be found in \`/export logs\``);else if(et<=on){et++,rt=1,xt="";let Pt=Math.min(1e3*Math.pow(2,et-1),32e3),Et=.8+Math.random()*.4,Tt=Math.round(Pt*Et);Zn=!0,yield{type:"status",content:`Trying to reach ${e} (${et}/${on}) [Retrying in ${(Tt/1e3).toFixed(0)}s]`};for(let It=Tt/1e3;It>0&&!wt;It--)yield{type:"status",content:`Trying to reach ${e} (${et}/${on}) [Retrying in ${It.toFixed(0)}s]`},await new Promise(gt=>setTimeout(gt,1e3));yield{type:"status",content:`Trying to reach ${e}`}}else throw new Error(`Model ${e} cannot be reached. (Failed ${on} times)
812
- Error log can be found in \`/export logs\``)}}if(Jt){let me=Jt.totalTokenCount||0,Ae=Jt.cachedContentTokenCount||0,ee=(Jt.candidatesTokenCount||0)+(i==="Google"&&Jt.thoughtsTokenCount||0);await Bt("tokens",me,i,Se),Ae>0&&await Bt("cachedTokens",Ae,i,Se),ee>0&&await Bt("candidateTokens",ee,i,Se),Do({provider:i,model:Se,prompt:Jt.promptTokenCount||0,cached:Ae,output:ee,reasoning:Jt.thoughtsTokenCount||0}),yield{type:"usage",content:Jt}}Te=qr(Te),hs.push(Te);let Sn=qt(Te),Pn=jr(Te),un=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(Pn.toLowerCase())||/\[\[END\]\]/i.test(Pn.toLowerCase())||!0,il=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(Pn.toLowerCase()),rl=ut>0;yield{type:"status",content:"Thinking"};let na=Za(Te,/(\[\s*(turn\s*:)?\s*(continue|finish)\s*\]|\[\[END\]\])/gi,"").trim(),$n=(un||Me.length===0)&&!vt&&!rn&&!Tn;if($n=Me.length===0?$n:!1,$n=Ot||_o?!1:$n,Te&&Te.trim().endsWith('")]')&&Me.length===0&&($n=!1),$n){pi=!0;let me=hs.join(`
813
- `),Ae=qt(me).trim();yield{type:"interactive_turn_finished",data:{agentText:a,fullAgentTextRaw:me,history:[...r],needTitle:y}},r.length>0&&r[r.length-1].role==="agent"?r[r.length-1].text=Ae:r.push({role:"agent",text:Ae}),r.forEach(ee=>{if(ee.role==="user"&&ee.text&&(ee.text=ee.text.replace(/\n\[COMPILE ERROR\][\s\S]*?\[\/ERROR\]/g,""),ee.text=ee.text.replaceAll(`
811
+ Error log can be found in \`/export logs\``)}}if(Jt){let pe=Jt.totalTokenCount||0,Ae=Jt.cachedContentTokenCount||0,ee=(Jt.candidatesTokenCount||0)+(i==="Google"&&Jt.thoughtsTokenCount||0);await Bt("tokens",pe,i,Se),Ae>0&&await Bt("cachedTokens",Ae,i,Se),ee>0&&await Bt("candidateTokens",ee,i,Se),Do({provider:i,model:Se,prompt:Jt.promptTokenCount||0,cached:Ae,output:ee,reasoning:Jt.thoughtsTokenCount||0}),yield{type:"usage",content:Jt}}Te=qr(Te),hs.push(Te);let Sn=qt(Te),Pn=jr(Te),un=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(Pn.toLowerCase())||/\[\[END\]\]/i.test(Pn.toLowerCase())||!0,il=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(Pn.toLowerCase()),rl=ut>0;yield{type:"status",content:"Thinking"};let na=Za(Te,/(\[\s*(turn\s*:)?\s*(continue|finish)\s*\]|\[\[END\]\])/gi,"").trim(),$n=(un||Me.length===0)&&!vt&&!rn&&!Tn;if($n=Me.length===0?$n:!1,$n=Ot||_o?!1:$n,Te&&Te.trim().endsWith('")]')&&Me.length===0&&($n=!1),$n){mi=!0;let pe=hs.join(`
812
+ `),Ae=qt(pe).trim();yield{type:"interactive_turn_finished",data:{agentText:a,fullAgentTextRaw:pe,history:[...r],needTitle:y}},r.length>0&&r[r.length-1].role==="agent"?r[r.length-1].text=Ae:r.push({role:"agent",text:Ae}),r.forEach(ee=>{if(ee.role==="user"&&ee.text&&(ee.text=ee.text.replace(/\n\[COMPILE ERROR\][\s\S]*?\[\/ERROR\]/g,""),ee.text=ee.text.replaceAll(`
814
813
 
815
814
  [system] user question. resolve this specific query within '[ANSWER] ... [/ANSWER]' concisely, naturally [/system]
816
815
  `,"").replaceAll(`[system] user question. resolve this specific query within '[ANSWER] ... [/ANSWER]' concisely, naturally
@@ -818,15 +817,15 @@ Error log can be found in \`/export logs\``)}}if(Jt){let me=Jt.totalTokenCount||
818
817
  `,"").replaceAll(`[system] **strictly follow thinking policy as high priority. do not start a response without <think>...</think>** [/system]
819
818
  `,"").replaceAll(/\n\[system\] WARNING, Turn Limit Impending: Step \d+\/\d+\. Wrap up quickly\/prompt user to continue & use \[\[END\]\] quickly\. \[\/system\]/g,""),ee.text=ee.text.replaceAll(/\n\[system\] File Changes:\n(?:\* .+ \(created|modified|deleted\)\n)*\[\/system\]/g,""),(i==="Mistral"||i==="Google"&&e?.toLowerCase().startsWith("gemma"))&&(ee.text.startsWith("[ACTION RESULT]")||ee.text.startsWith("[TOOL RESULT]")))){let Mt=`
820
819
  [system] Action result received. Analyze output and proceed with your turn [/system]`,At=`
821
- [system] Action result received. Analyze output and proceed with your turn. **strictly follow thinking policy. do not start a response without <think>...</think>** [/system]`;ee.text=ee.text.replaceAll(At,"").replaceAll(Mt,"").trim()}}),yield{type:"status",content:"[end]"}}if($n)break;let oa=na.trim()||"*Working...*";if(r.push({role:"agent",text:oa}),Me.length>0||kn){if(Me.length>0){let me=Me.map(zt=>zt.text).join(`
820
+ [system] Action result received. Analyze output and proceed with your turn. **strictly follow thinking policy. do not start a response without <think>...</think>** [/system]`;ee.text=ee.text.replaceAll(At,"").replaceAll(Mt,"").trim()}}),yield{type:"status",content:"[end]"}}if($n)break;let oa=na.trim()||"*Working...*";if(r.push({role:"agent",text:oa}),Me.length>0||kn){if(Me.length>0){let pe=Me.map(zt=>zt.text).join(`
822
821
 
823
- `),Lt=(qt(Te).replace(/\[{1,2}(?:tool|action):[\s\S]*?\)\s*\]{1,2}/gi,"").match(/\[(?:tool|action):/gi)||[]).length,Mt=Me.length+Lt;if(Me.length<Mt){me+=`
822
+ `),Lt=(qt(Te).replace(/\[{1,2}(?:tool|action):[\s\S]*?\)\s*\]{1,2}/gi,"").match(/\[(?:tool|action):/gi)||[]).length,Mt=Me.length+Lt;if(Me.length<Mt){pe+=`
824
823
 
825
- [system] Only ${Me.length} out of ${Mt} attempted tool calls were executed. Verify proper structure compliance & try failed calls again [/system]`;let zt=Mt-Me.length;for(let Ge=0;Ge<zt;Ge++)await Rt("toolFailure")}let At=Me.find(zt=>zt.binaryPart)?.binaryPart||null;r.push({role:"user",text:me,binaryPart:At})}}else if(!wt){let Ae=(Te.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/i,"").match(/\[(?:tool|action):/gi)||[]).length;_o||Ot||Ae>0?(r.push({role:"user",text:`[system] Failed to execute ${Ae} tool${Ae>1?"s":""}. Verify proper structure compliance [action:ActionName(...)] & try again [/system]`}),await Rt("toolFailure"),yield{type:"visual_feedback",content:`
824
+ [system] Only ${Me.length} out of ${Mt} attempted tool calls were executed. Verify proper structure compliance & try failed calls again [/system]`;let zt=Mt-Me.length;for(let Ge=0;Ge<zt;Ge++)await Rt("toolFailure")}let At=Me.find(zt=>zt.binaryPart)?.binaryPart||null;r.push({role:"user",text:pe,binaryPart:At})}}else if(!wt){let Ae=(Te.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/i,"").match(/\[(?:tool|action):/gi)||[]).length;_o||Ot||Ae>0?(r.push({role:"user",text:`[system] Failed to execute ${Ae} tool${Ae>1?"s":""}. Verify proper structure compliance [action:ActionName(...)] & try again [/system]`}),await Rt("toolFailure"),yield{type:"visual_feedback",content:`
826
825
  ${Yt("\u2718 Execution Error")}
827
826
  `}):(yield{type:"visual_feedback",content:`
828
827
  ${Yt("\u2718 Loop Detected")}
829
- `},r.push({role:"user",text:`[system] ${rn&&!vt?"Stuttering Detected by Internal System. Re-calibrate your response & proceed.":`${vt?" Over Thinking":" Loop"} Detected by Internal System${vt?" for current Effort Level":""}. ${vt?"If you have planned the task, prioritize execution/output":"If you have finished your task provide a simple summary and end"}`} [/system]`})),vt=!1,rn=!1,Tn=!1}T?.advanceRollback&&await lo.recordTurnDelta(p,j+1,ot),_o=ut>0||kn}if(!pi&&!wt){let j="\u2726 Turn safety limit reached. Stopping execution.";yield{type:"text",content:`
828
+ `},r.push({role:"user",text:`[system] ${rn&&!vt?"Stuttering Detected by Internal System. Re-calibrate your response & proceed.":`${vt?" Over Thinking":" Loop"} Detected by Internal System${vt?" for current Effort Level":""}. ${vt?"If you have planned the task, prioritize execution/output":"If you have finished your task provide a simple summary and end"}`} [/system]`})),vt=!1,rn=!1,Tn=!1}T?.advanceRollback&&await lo.recordTurnDelta(m,j+1,ot),_o=ut>0||kn}if(!mi&&!wt){let j="\u2726 Turn safety limit reached. Stopping execution.";yield{type:"text",content:`
830
829
 
831
830
  ${j}
832
831
  `};let Ke=(hs.join(`
@@ -839,7 +838,7 @@ CAUSE: ${d.cause?.stack||d.cause}`:""}
839
838
 
840
839
  ----------------------------------------------------------------------
841
840
 
842
- `),typeof flushGoogleBuffer=="function"&&(yield*flushGoogleBuffer()),yield{type:"tool_result",content:`ERROR: [INTERNAL CRITICAL] ${v}`}}finally{R&&(clearInterval(R),R=null),typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),await Oo.commitTransaction(),T?.advanceRollback&&await lo.cleanup(p),await Hn()}yield{type:"status",content:null}},yf=async(e,t,n=null,s=null,o=50,c=null,f=!1)=>{let l=await ao(),k={...l,...t},p=process.env.SUBAGENT_MODEL?process.env.SUBAGENT_MODEL.trim():null,g=process.env.SUBAGENT_PROVIDER?process.env.SUBAGENT_PROVIDER.trim():null,T=new Date,m=`${T.getFullYear()}-${T.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(T.getDate()).padStart(2,"0")}, ${T.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}).replace(":","-")}`,u=(R=>{if(!R)return null;let d=R.toLowerCase();return d==="google"?"Google":d==="deepseek"?"DeepSeek":d==="openrouter"?"OpenRouter":d==="nvidia"?"NVIDIA":d==="mistral"?"Mistral":d==="ollama"?"Ollama":d==="inferx"?"InferX":d==="sensenova"?"SenseNova":d==="poolside"?"Poolside":d==="9router"||d==="9Router"?"9router":d==="aihubmix"||d==="aihub"?"AIHubMix":d==="explabs"||d==="experientiallabs"||d==="experimentallabs"?"ExpLabs":d==="tokenharbor"||d==="token harbor"||d==="token_harbor"||d==="thk"?"TokenHarbor":d==="apinex"||d==="apx"?"APInex":null})(g),w=k?.systemSettings?.CustomSubAgent?k?.systemSettings?.SubAgentModel:null,I=k?.systemSettings?.CustomSubAgent?k?.systemSettings?.SubAgentProvider:null,h=null;if(w==="ENV"?(h=p,p&&u&&(k.aiProvider=u)):w&&w!=="Default"?(h=w,I&&(k.aiProvider=I)):p&&u&&(k.aiProvider=u),k.aiProvider){let R=await Ss(k.aiProvider);R&&(k.apiKey=R)}let A=R=>{if(!R||typeof R!="string")return{allowed:!0};let d=[/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 r of d)if(r.test(R))return{allowed:!1,reason:`Blocked potentially destructive or unsafe command pattern: "${r.source}"`};return{allowed:!0}},$=n||h||t?.modelName||t?.activeModel||l.activeModel,C=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",x=`-- ACTIONS (path = relative to CWD, path separator: '/') --
841
+ `),typeof flushGoogleBuffer=="function"&&(yield*flushGoogleBuffer()),yield{type:"tool_result",content:`ERROR: [INTERNAL CRITICAL] ${v}`}}finally{R&&(clearInterval(R),R=null),typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),await Oo.commitTransaction(),T?.advanceRollback&&await lo.cleanup(m),await Hn()}yield{type:"status",content:null}},yf=async(e,t,n=null,s=null,o=50,c=null,f=!1)=>{let l=await ao(),k={...l,...t},m=process.env.SUBAGENT_MODEL?process.env.SUBAGENT_MODEL.trim():null,g=process.env.SUBAGENT_PROVIDER?process.env.SUBAGENT_PROVIDER.trim():null,T=new Date,p=`${T.getFullYear()}-${T.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(T.getDate()).padStart(2,"0")}, ${T.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}).replace(":","-")}`,u=(R=>{if(!R)return null;let d=R.toLowerCase();return d==="google"?"Google":d==="deepseek"?"DeepSeek":d==="openrouter"?"OpenRouter":d==="nvidia"?"NVIDIA":d==="mistral"?"Mistral":d==="ollama"?"Ollama":d==="inferx"?"InferX":d==="sensenova"?"SenseNova":d==="poolside"?"Poolside":d==="9router"||d==="9Router"?"9router":d==="aihubmix"||d==="aihub"?"AIHubMix":d==="explabs"||d==="experientiallabs"||d==="experimentallabs"?"ExpLabs":d==="tokenharbor"||d==="token harbor"||d==="token_harbor"||d==="thk"?"TokenHarbor":d==="apinex"||d==="apx"?"APInex":null})(g),w=k?.systemSettings?.CustomSubAgent?k?.systemSettings?.SubAgentModel:null,I=k?.systemSettings?.CustomSubAgent?k?.systemSettings?.SubAgentProvider:null,h=null;if(w==="ENV"?(h=m,m&&u&&(k.aiProvider=u)):w&&w!=="Default"?(h=w,I&&(k.aiProvider=I)):m&&u&&(k.aiProvider=u),k.aiProvider){let R=await Ss(k.aiProvider);R&&(k.apiKey=R)}let A=R=>{if(!R||typeof R!="string")return{allowed:!0};let d=[/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 r of d)if(r.test(R))return{allowed:!1,reason:`Blocked potentially destructive or unsafe command pattern: "${r.source}"`};return{allowed:!0}},$=n||h||t?.modelName||t?.activeModel||l.activeModel,C=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",x=`-- ACTIONS (path = relative to CWD, path separator: '/') --
843
842
  In chat output the format \`[action:ActionName(arg1="value1")]\` in NEW line
844
843
  Rules:
845
844
  - JSON escape literal sequences, backslash: \\\\, newLine: \\ n
@@ -876,7 +875,7 @@ NO EXPLICIT THINKING REQUIRED. FOCUS ON TASK COMPLETION
876
875
  Main focus: actions and task, not chatting
877
876
  On completion, provide a detailed summary in Tables/Markdown Format with file modified info. If any task failed report back in detail
878
877
 
879
- Current Time: ${m}
878
+ Current Time: ${p}
880
879
  === END SYSTEM PROMPT ===`,M=[{role:"user",text:`Complete this task: ${e}`}],y=0,a="";for(;y<o;){let R=await _s("subagent",k);if(!R.allowed)throw new Error(R.reason||`Budget Exhausted for Provider (${k?.aiProvider||"Subagent"})`);if(wt){if(t?.taskId&&typeof Vt<"u"){let L=Vt.find(F=>F.id===t.taskId);L&&(L.status="cancelled")}throw c&&c("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}if(t?.taskId&&typeof Vt<"u"){let L=Vt.find(F=>F.id===t.taskId);if(L&&L.status==="cancelled")throw c&&c("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}let d=M.map(L=>({role:L.role==="user"?"user":"model",parts:[{text:L.text}]}));c&&c(`[Subagent Turn ${y+1}]...`);let r=["Fast","Low","Medium","High"],E=process.env.SUBAGENT_THINKING,v=r.includes(E)?E:"Low",O=(await ls(k,$,d,_,v)).text||"",P=qr(qt(O).trim());a=P,c&&c(`[Subagent Response]
881
880
  ${P}
882
881
  `),M.push({role:"agent",text:P});let re=ko(P);if(re.length===0)break;let de=re.filter(L=>L.toolName.toLowerCase()==="askmain"||L.toolName.toLowerCase()==="ask_main"),Q=!1,ke="";for(let L of re){if(wt){if(t?.taskId&&typeof Vt<"u"){let B=Vt.find(G=>G.id===t.taskId);B&&(B.status="cancelled")}throw new Error("Subagent task was cancelled.")}if(t?.taskId&&typeof Vt<"u"){let B=Vt.find(G=>G.id===t.taskId);if(B&&B.status==="cancelled")throw new Error("Subagent task was cancelled.")}let F=L.toolName.toLowerCase();if(F==="askuser"&&(F="ask"),F==="askmain"||F==="ask_main"){if(Q)continue;Q=!0;let B="";if(de.length===1?B=ne(de[0].args).question||de[0].args:B=de.map((G,ye)=>{let Re=ne(G.args);return`Q${ye+1}: ${Re.question||G.args}`}).join(`
@@ -903,4 +902,4 @@ ${B}
903
902
 
904
903
  `,await Rt("toolFailure")}}let ae="";if(t?.taskId&&typeof Vt<"u"){let L=Vt.find(F=>F.id===t.taskId);if(L&&L.pendingSteerMessages&&L.pendingSteerMessages.length>0){let F=[...L.pendingSteerMessages];L.pendingSteerMessages=[];for(let Ee of F)ae+=`
905
904
 
906
- [STEERING INSTRUCTION FROM MAIN AGENT]: ${Ee}`,c&&c(`[Subagent Steered] ${Ee}`)}}let it=(ke.trim()+ae).trim();M.push({role:"user",text:it}),y++}return a};export{bo as a,Or as b,yc as c,xc as d,He as e,ul as f,gl as g,ac as h,lc as i,kc as j,zo as k,Tc as l,ja as m,cf as n,Ka as o,Va as p,oi as q,qt as r,Gr as s,qr as t,Xa as u,df as v,ff as w,ri as x,uf as y,gf as z,ls as A,hf as B,mf as C,pf as D,yf as E};
905
+ [STEERING INSTRUCTION FROM MAIN AGENT]: ${Ee}`,c&&c(`[Subagent Steered] ${Ee}`)}}let it=(ke.trim()+ae).trim();M.push({role:"user",text:it}),y++}return a};export{bo as a,Or as b,yc as c,xc as d,He as e,ul as f,gl as g,ac as h,lc as i,kc as j,zo as k,Tc as l,ja as m,cf as n,Ka as o,Va as p,oi as q,qt as r,Gr as s,qr as t,Xa as u,df as v,ff as w,ri as x,uf as y,gf as z,ls as A,hf as B,pf as C,mf as D,yf as E};