fluxflow-cli 4.16.9 → 4.16.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import{a as so}from"./chunk-VCF6JVQV.js";import{a as jt}from"./chunk-56EJGQU3.js";import{a as ps,h as mi}from"./chunk-KRRJNFBF.js";import{a as hi}from"./chunk-ZYJYKSIA.js";import{c as ms,g as ci,h as di,i as fi,m as hs}from"./chunk-HNUV7OHA.js";import{a as vo}from"./chunk-KFM2OZWJ.js";import{b as gs}from"./chunk-72RYQ5W7.js";import{e as At,g as Ft,i as ai,j as li}from"./chunk-WKHYRBBK.js";import{g as dt,h as qn,k as fe,l as oo}from"./chunk-AAPXJU65.js";import{c as Et,d as Yn}from"./chunk-SIINYZWE.js";import{a as ui,c as gi}from"./chunk-SHTF7RHG.js";import{a as en,d as Sn,e as Eo,j as Pn,k as Ao,l as fs,q as us,u as Co}from"./chunk-FDNLMLIM.js";import{a as Z}from"./chunk-Y5JU726N.js";import{GoogleGenAI as Lr,ThinkingLevel as Je,HarmBlockThreshold as An,HarmCategory as Cn}from"@google/genai";var pi=(e=!0,t=!0)=>`
1
+ import{a as oo}from"./chunk-VCF6JVQV.js";import{a as jt}from"./chunk-56EJGQU3.js";import{a as ps,h as mi}from"./chunk-KRRJNFBF.js";import{a as hi}from"./chunk-2N256NLX.js";import{c as ms,g as ci,h as di,i as fi,m as hs}from"./chunk-HNUV7OHA.js";import{a as vo}from"./chunk-KFM2OZWJ.js";import{b as gs}from"./chunk-72RYQ5W7.js";import{e as At,g as Ft,i as ai,j as li}from"./chunk-WKHYRBBK.js";import{g as ft,h as Co,k as de,l as no}from"./chunk-AAPXJU65.js";import{c as Et,d as Yn}from"./chunk-SIINYZWE.js";import{a as ui,c as gi}from"./chunk-SHTF7RHG.js";import{a as en,d as Sn,e as _o,j as Pn,k as Eo,l as fs,q as us,u as Ao}from"./chunk-FDNLMLIM.js";import{a as Z}from"./chunk-Y5JU726N.js";import{GoogleGenAI as Lr,ThinkingLevel as Ze,HarmBlockThreshold as An,HarmCategory as Cn}from"@google/genai";var pi=(e=!0,t=!0)=>`
2
2
  To use tools, must output exactly '[tool:functions.ToolName(arg1="value1")]' structured string in chat response \u2190 no exception
3
3
 
4
4
  -- Chat Management Tools --
@@ -30,7 +30,7 @@ Usage Rules:
30
30
  Think before complex tasks
31
31
  Prefer simplest correct solution, assess architecture, performance & maintainability, verify error handling, assumptions, edge cases, dependencies & regressions, plan: files, functions, logic & interactions
32
32
  Verify from first principles, seek failure paths, verify imports, system stability
33
- Use as less as possible thinking tokens. Achieve the final result with quality without wasting tokens`,High:`Effort: High
33
+ Critical: Direct deduction only. No exploratory branching. Output solution immediately`,High:`Effort: High
34
34
  Think before complex tasks
35
35
  Prefer simplest correct solution, assess architecture, performance & maintainability, verify error handling, assumptions, edge cases, dependencies & regressions, plan: files, functions, logic & interactions
36
36
  Continuous analysis, verify from first principles, seek failure paths, verify imports, system stability
@@ -46,7 +46,7 @@ Dont waste tokens, be efficient, use least thinking tokens, focus on result
46
46
  Gather useful context
47
47
  Brief thoughts, think only enough to avoid mistakes, verify imports, system stability`,Off:`Effort: Lowest
48
48
  No thinking. Immediate response
49
- Verify imports, tool results & system stability`};import io from"fs";var yn=null,ys=()=>{try{if(io.existsSync(Co)){let e=io.readFileSync(Co,"utf-8"),t=JSON.parse(e);if(t&&typeof t=="object")return yn=t,yn}}catch{}return yn=yn||{},yn},yi=e=>{try{return io.existsSync(en)||io.mkdirSync(en,{recursive:!0}),io.writeFileSync(Co,JSON.stringify(e,null,2),"utf-8"),yn=e,!0}catch{return!1}},Oe=(e,t,n)=>{if(!e||!t||!n)return null;let s=yn||ys(),o=`${e}::${t}`,l=s[o];if(l&&typeof l=="object"){let f=n.toLowerCase();if(l[f]!==void 0&&l[f]!==null)return l[f];for(let[a,m]of Object.entries(l))if(a.toLowerCase()===f)return m}return null},Qa=(e,t,n,s)=>{if(!e||!t||!n||!s)return{success:!1,reason:"Invalid arguments"};let o=yn||ys(),l=`${e}::${t}`;return(!o[l]||typeof o[l]!="object")&&(o[l]={}),o[l][n.toLowerCase()]=s,{success:yi(o)}},Za=(e,t,n)=>{if(!e||!t)return{success:!1,reason:"Invalid arguments"};let s=yn||ys(),o=`${e}::${t}`;return s[o]&&(n?(delete s[o][n.toLowerCase()],Object.keys(s[o]).length===0&&delete s[o]):delete s[o],yi(s)),{success:!0}};import tn from"fs";import dn from"path";import na from"os";import cn from"fs";import _n from"path";import Mi from"fs";import xs from"path";import{execSync as Ii}from"child_process";import{fileURLToPath as ta}from"url";var xi=`# FluxFlow CLI Startup & Flags Reference
49
+ Verify imports, tool results & system stability`};import so from"fs";var yn=null,ys=()=>{try{if(so.existsSync(Ao)){let e=so.readFileSync(Ao,"utf-8"),t=JSON.parse(e);if(t&&typeof t=="object")return yn=t,yn}}catch{}return yn=yn||{},yn},yi=e=>{try{return so.existsSync(en)||so.mkdirSync(en,{recursive:!0}),so.writeFileSync(Ao,JSON.stringify(e,null,2),"utf-8"),yn=e,!0}catch{return!1}},Ue=(e,t,n)=>{if(!e||!t||!n)return null;let s=yn||ys(),o=`${e}::${t}`,l=s[o];if(l&&typeof l=="object"){let f=n.toLowerCase();if(l[f]!==void 0&&l[f]!==null)return l[f];for(let[a,m]of Object.entries(l))if(a.toLowerCase()===f)return m}return null},Qa=(e,t,n,s)=>{if(!e||!t||!n||!s)return{success:!1,reason:"Invalid arguments"};let o=yn||ys(),l=`${e}::${t}`;return(!o[l]||typeof o[l]!="object")&&(o[l]={}),o[l][n.toLowerCase()]=s,{success:yi(o)}},Za=(e,t,n)=>{if(!e||!t)return{success:!1,reason:"Invalid arguments"};let s=yn||ys(),o=`${e}::${t}`;return s[o]&&(n?(delete s[o][n.toLowerCase()],Object.keys(s[o]).length===0&&delete s[o]):delete s[o],yi(s)),{success:!0}};import tn from"fs";import dn from"path";import na from"os";import cn from"fs";import _n from"path";import Mi from"fs";import xs from"path";import{execSync as Ii}from"child_process";import{fileURLToPath as ta}from"url";var xi=`# FluxFlow CLI Startup & Flags Reference
50
50
 
51
51
  Launch command syntax:
52
52
  fluxflow [options]
@@ -85,12 +85,13 @@ fluxflow [options]
85
85
  * SUBAGENT_MODEL \u2192 Model override for sub-agents
86
86
  * SUBAGENT_PROVIDER \u2192 Provider override for sub-agents
87
87
  * NVIDIA_BASE_URL \u2192 Custom endpoint URL for NVIDIA NIM (Cloud/Local OpenAI Compatible)
88
+ * SUBAGENT_THINKING - Fast, Low (default), Medium, High. Affects at High Level, not Low Level. --map takes priority
88
89
  * NVIDIA_API_KEY \u2192 API key for NVIDIA NIM
89
- * OLLAMA_HOST \u2192 Custom Ollama endpoint (default: http://127.0.0.1:11434)
90
+ * OLLAMA_HOST \u2192 If different from default
90
91
  * SHELL \u2192 Terminal shell executable
91
92
  * HIGH_CONTEXT \u2192 Context window override (false or integer 32k..1M) [Deprecated! Will stop working from next major version]
92
93
  * ENABLE_9ROUTER \u2192 Enables 9Router provider. Can use OAuth subscription like Codex, Claude Code, GitHub Copilot etc. or use providers not natively in Fluxflow. Set ENV ENABLE_9ROUTER=true, needs 9router package installed (via npm/npx etc) & running
93
- * 9ROUTER_BASE_URL
94
+ * 9ROUTER_BASE_URL \u2192 If different from default
94
95
  * 9ROUTER_API_KEY \u2192 if any
95
96
 
96
97
  ## Diagnostic & Optimization Flags
@@ -398,7 +399,7 @@ Route sub-agent workloads to faster/cheaper models independently of the main age
398
399
  * Set HIGH_CONTEXT=<tokens> in ENV (range: 32k to 1M)
399
400
  `;var Ri=`# Fluxflow Instructions & Skills System
400
401
 
401
- ## 1. Instructions (AGENTS.md / FLUXFLOW.md)
402
+ ## 1. Instructions (AGENTS.md / FLUXFLOW.md root only)
402
403
  * Locations:
403
404
  * Global: ~/.fluxflow/FLUXFLOW.md | ~/.fluxflow/AGENTS.md
404
405
  * Workspace: ./FLUXFLOW.md | ./AGENTS.md | Directory Scoped like src/AGENTS.md
@@ -432,14 +433,14 @@ Instruction for this model ID across all providers.
432
433
  ## 2. Skills System
433
434
  * Locations:
434
435
  * Global: ~/.fluxflow/skills/**/SKILL.md
435
- * Workspace: ./skills/**/SKILL.md | ./SKILL.md
436
+ * Workspace: ./skills/**/SKILL.md | ./SKILL.md
436
437
 
437
438
  * Format:
438
439
  * YAML Frontmatter: --- block with name and description
439
440
  * Body: Markdown Instructions/Workflows
440
441
 
441
- * On-Demand Reference Loading:
442
- * Reference: Offload deep/contexual specs to references/*.md linked from root SKILL.md. Saves tokens
442
+ * On-Demand Reference System:
443
+ * Reference: Offload deep/contexual specs to **/{SKILL.md,skill-reference-folder/*.md} & reference in SKILL.md. Saves tokens
443
444
  `;var Mo="v4";try{let e=xs.dirname(ta(import.meta.url)),t=[xs.join(e,"../../package.json"),xs.join(e,"../package.json")],n=!1;for(let s of t)if(Mi.existsSync(s)){let o=JSON.parse(Mi.readFileSync(s,"utf8"));if(o.version){Mo=o.version,n=!0;break}}if(!n)try{let s=Ii("fluxflow -v",{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"],timeout:2e3}).trim();s&&(s.startsWith("v")||/^\d+\.\d+/.test(s))&&(Mo=s,n=!0)}catch{}if(!n)try{let s=Ii("curl -s --max-time 3 https://raw.githubusercontent.com/KushalRoyChowdhury/fluxflow-cli/main/package.json",{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"]}),o=JSON.parse(s);o.version&&(Mo=o.version)}catch{}}catch{}var bs={"SKILL.md":`---
444
445
  name: fluxflow
445
446
  description: System Generated Documentation. Read this if asked anything regarding FluxFlow Harness
@@ -449,7 +450,7 @@ description: System Generated Documentation. Read this if asked anything regardi
449
450
  Open Source Terminal AI Assistant
450
451
  App Version: ${Mo}. Check Updates: fluxflow --update check. Update: fluxflow --update
451
452
  GitHub: https://github.com/KushalRoyChowdhury/fluxflow-cli
452
- Documentation: https://fluxflow-cli.onrender.com
453
+ Public Docs: https://fluxflow-cli.onrender.com
453
454
 
454
455
  [tool:functions.SearchKeyword(keyword="regex/word", path="#docs")]. Usage: search any keyword across docs, avoid hunting excessive references
455
456
 
@@ -459,7 +460,7 @@ Documentation: https://fluxflow-cli.onrender.com
459
460
  * In-App Settings (/settings) & Recommended Presets \u2192 references/SETTINGS.md
460
461
  * In-app /commands \u2192 references/COMMANDS.md
461
462
  * CLI Startup Flags \u2192 references/STARTUP.md
462
- * Environment Variables \u2192 references/ENV.md
463
+ * Environment Variables, Subagents, API Keys \u2192 references/ENV.md
463
464
  * Tool System (Workspace, Web, Communication, Sub-Agents, Safety, Creative, Computer Use) \u2192 references/TOOLS.md
464
465
  * Sub-Agents & Multi-Agent Runtime \u2192 references/SUB_AGENTS.md
465
466
  * Security, Sandboxing & Checkpoints (/revert, double-ESC) \u2192 references/SECURITY.md
@@ -467,63 +468,62 @@ Documentation: https://fluxflow-cli.onrender.com
467
468
  * Priority Instructions (AGENTS.md/FLUXFLOW.md) & Skill System \u2192 references/PLUGINS.md
468
469
  * Agent Architecture & Memory System \u2192 references/ARCHITECTURE.md
469
470
 
470
- Default Context Length: 256k Tokens. Can be changed via ENV/In-app Settings
471
+ Default Context Length: 256k Tokens. Can be changed via ENV/In-app Settings \u2192 references/{SETTINGS,ENV}.md
471
472
 
472
473
  Docs missing required info? Say you are not sure enough to answer. Dont give wrong info`,"references/MODES.md":Ci,"references/PROVIDERS.md":vi,"references/PLUGINS.md":Ri,"references/STARTUP.md":xi,"references/ENV.md":bi,"references/COMMANDS.md":ki,"references/SETTINGS.md":wi,"references/TOOLS.md":Ti,"references/ARCHITECTURE.md":Si,"references/SUB_AGENTS.md":_i,"references/SECURITY.md":Ei,"references/IDE.md":Ai};var Di=()=>{try{let e=_n.join(en,"skills","fluxflow"),t=_n.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){cn.existsSync(e)&&cn.rmSync(e,{recursive:!0,force:!0});return}let s=new Set(Object.keys(bs).map(o=>_n.normalize(o)));for(let[o,l]of Object.entries(bs)){let f=_n.join(e,o),a=_n.dirname(f);cn.existsSync(a)||cn.mkdirSync(a,{recursive:!0});let m=l.trim()+`
473
- `,g=null;cn.existsSync(f)&&(g=cn.readFileSync(f,"utf8")),g!==m&&cn.writeFileSync(f,m,"utf8")}if(cn.existsSync(t)){let o=cn.readdirSync(t);for(let l of o){let f=_n.normalize(_n.join("references",l));if(!s.has(f)){let a=_n.join(t,l);try{cn.rmSync(a,{recursive:!0,force:!0})}catch{}}}}}catch{}};var co=(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 l=s.find(f=>f.toLowerCase()===o);if(l){let f=dn.join(e,l);if(tn.statSync(f).isFile())return f}}}catch{}return null},Es=(e,t)=>{let n=co(e,t);if(n)try{return tn.readFileSync(n,"utf8")}catch{}return""},Oi=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"]),As=(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 l of o){let f=l.name,a=dn.join(e,f);if(l.isDirectory())!Oi.has(f)&&!Oi.has(f.toLowerCase())&&s.push(...As(a,t+1,n));else if(l.isFile()){let m=f.toLowerCase();(m==="agents.md"||m==="agent.md")&&s.push(a)}}}catch{}return s},Li=(e,t=2)=>{if(!e)return"";let n=" ".repeat(t);return e.split(/\r?\n/).map(s=>n+s).join(`
474
- `)},Bi=()=>co(en,["agents.md","agent.md"]),Ui=()=>co(process.cwd(),["agents.md","agent.md"]),Wi=()=>co(en,["fluxflow.md"]),Hi=()=>co(process.cwd(),["fluxflow.md"]),Io=Bi(),Ss=Ui(),En=As(),Do=Wi(),Oo=Hi(),Pi=null,_s="",Gi=!1,oa=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&&(_s=o[1].trim(),process.env.NO_INS=!0),/<><\s*NO_INS/.test(n)&&(Gi=!0),s.trim()},sa=()=>(Io=Bi(),Io?Es(en,["agents.md","agent.md"]).trim():""),ia=()=>{if(En=As(),Ss=Ui(),!En||En.length===0)return"";let e=process.cwd(),t=[...En].sort((s,o)=>{let l=dn.relative(e,s).replace(/\\/g,"/"),f=dn.relative(e,o).replace(/\\/g,"/"),a=!l.includes("/"),m=!f.includes("/");return a&&!m?-1:!a&&m?1:l.localeCompare(f)}),n=[];for(let s of t)try{let o=tn.readFileSync(s,"utf8").trim();if(!o)continue;let l=dn.relative(e,s).replace(/\\/g,"/");if(!l.includes("/"))n.push(Li(o,2));else{let a=dn.dirname(l)+"/:";n.push(`${a}
474
+ `,g=null;cn.existsSync(f)&&(g=cn.readFileSync(f,"utf8")),g!==m&&cn.writeFileSync(f,m,"utf8")}if(cn.existsSync(t)){let o=cn.readdirSync(t);for(let l of o){let f=_n.normalize(_n.join("references",l));if(!s.has(f)){let a=_n.join(t,l);try{cn.rmSync(a,{recursive:!0,force:!0})}catch{}}}}}catch{}};var lo=(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 l=s.find(f=>f.toLowerCase()===o);if(l){let f=dn.join(e,l);if(tn.statSync(f).isFile())return f}}}catch{}return null},Es=(e,t)=>{let n=lo(e,t);if(n)try{return tn.readFileSync(n,"utf8")}catch{}return""},Oi=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"]),As=(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 l of o){let f=l.name,a=dn.join(e,f);if(l.isDirectory())!Oi.has(f)&&!Oi.has(f.toLowerCase())&&s.push(...As(a,t+1,n));else if(l.isFile()){let m=f.toLowerCase();(m==="agents.md"||m==="agent.md")&&s.push(a)}}}catch{}return s},Li=(e,t=2)=>{if(!e)return"";let n=" ".repeat(t);return e.split(/\r?\n/).map(s=>n+s).join(`
475
+ `)},Bi=()=>lo(en,["agents.md","agent.md"]),Ui=()=>lo(process.cwd(),["agents.md","agent.md"]),Wi=()=>lo(en,["fluxflow.md"]),Hi=()=>lo(process.cwd(),["fluxflow.md"]),Io=Bi(),Ss=Ui(),En=As(),Do=Wi(),Oo=Hi(),Pi=null,_s="",Gi=!1,oa=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&&(_s=o[1].trim(),process.env.NO_INS=!0),/<><\s*NO_INS/.test(n)&&(Gi=!0),s.trim()},sa=()=>(Io=Bi(),Io?Es(en,["agents.md","agent.md"]).trim():""),ia=()=>{if(En=As(),Ss=Ui(),!En||En.length===0)return"";let e=process.cwd(),t=[...En].sort((s,o)=>{let l=dn.relative(e,s).replace(/\\/g,"/"),f=dn.relative(e,o).replace(/\\/g,"/"),a=!l.includes("/"),m=!f.includes("/");return a&&!m?-1:!a&&m?1:l.localeCompare(f)}),n=[];for(let s of t)try{let o=tn.readFileSync(s,"utf8").trim();if(!o)continue;let l=dn.relative(e,s).replace(/\\/g,"/");if(!l.includes("/"))n.push(Li(o,2));else{let a=dn.dirname(l)+"/:";n.push(`${a}
475
476
  ${Li(o,2)}`)}}catch{}return n.join(`
476
477
 
477
- `).trim()},Cs=()=>{Do=Wi();let e=Do?Es(en,["fluxflow.md"]).trim():"";return oa(e)},vs=()=>(Oo=Hi(),Oo?Es(process.cwd(),["fluxflow.md"]).trim():""),Rs=sa(),Lo=ia(),ao=Cs(),lo=vs(),$i=(e,t="",n="")=>{if(!e)return"";let s=n.toLowerCase().trim(),o=t.toLowerCase().trim(),l=dn.posix.basename(o),f=s&&o?`${s}::${o}`:"",a=s&&l?`${s}::${l}`:"",m=u=>!u||!o?!1:u===o||u===l||u===f||u===a,g=[];return e.replace(/<start_provider_([^>\r\n]+)>([\s\S]*?)<end_provider_([^>\r\n]+)>/gi,(u,h,x,i)=>{if(s&&h.trim().toLowerCase()===i.trim().toLowerCase()&&h.trim().toLowerCase()===s){let T=x.replace(/<start_model_([^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n]+)>/gi,(v,b,R,N)=>{if(b.trim().toLowerCase()===N.trim().toLowerCase()){let M=b.trim().toLowerCase();if(m(M)){let S=R.trim();S&&g.push(S)}}return""}).trim();T&&g.push(T)}return""}),e.replace(/<start_model_([^>\r\n]+::[^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n]+::[^>\r\n]+)>/gi,(u,h,x,i)=>{if(h.trim().toLowerCase()===i.trim().toLowerCase()){let c=h.trim().toLowerCase();if(f&&(c===f||a&&c===a)){let T=x.trim();T&&g.push(T)}}return""}),e.replace(/<start_model_([^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n]+)>/gi,(u,h,x,i)=>{if(h.includes("::"))return"";if(h.trim().toLowerCase()===i.trim().toLowerCase()){let c=h.trim().toLowerCase();if(o&&(c===o||c===l)){let T=x.trim();T&&g.push(T)}}return""}),g.join(`
478
+ `).trim()},Cs=()=>{Do=Wi();let e=Do?Es(en,["fluxflow.md"]).trim():"";return oa(e)},vs=()=>(Oo=Hi(),Oo?Es(process.cwd(),["fluxflow.md"]).trim():""),Rs=sa(),Lo=ia(),ro=Cs(),ao=vs(),$i=(e,t="",n="")=>{if(!e)return"";let s=n.toLowerCase().trim(),o=t.toLowerCase().trim(),l=dn.posix.basename(o),f=s&&o?`${s}::${o}`:"",a=s&&l?`${s}::${l}`:"",m=u=>!u||!o?!1:u===o||u===l||u===f||u===a,g=[];return e.replace(/<start_provider_([^>\r\n]+)>([\s\S]*?)<end_provider_([^>\r\n]+)>/gi,(u,h,x,i)=>{if(s&&h.trim().toLowerCase()===i.trim().toLowerCase()&&h.trim().toLowerCase()===s){let w=x.replace(/<start_model_([^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n]+)>/gi,(A,b,C,N)=>{if(b.trim().toLowerCase()===N.trim().toLowerCase()){let R=b.trim().toLowerCase();if(m(R)){let _=C.trim();_&&g.push(_)}}return""}).trim();w&&g.push(w)}return""}),e.replace(/<start_model_([^>\r\n]+::[^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n]+::[^>\r\n]+)>/gi,(u,h,x,i)=>{if(h.trim().toLowerCase()===i.trim().toLowerCase()){let c=h.trim().toLowerCase();if(f&&(c===f||a&&c===a)){let w=x.trim();w&&g.push(w)}}return""}),e.replace(/<start_model_([^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n]+)>/gi,(u,h,x,i)=>{if(h.includes("::"))return"";if(h.trim().toLowerCase()===i.trim().toLowerCase()){let c=h.trim().toLowerCase();if(o&&(c===o||c===l)){let w=x.trim();w&&g.push(w)}}return""}),g.join(`
478
479
 
479
- `).trim()},ra=(e="",t="")=>{let n=`${e||""}::${t||""}`.toLowerCase().trim();Pi!==n&&(Pi=n,ao=Cs(),lo=vs())};Di();var aa=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="",l="",f=n.match(/^name:\s*(.+)$/m),a=n.match(/^description:\s*(.+)$/m);return f&&(o=f[1].trim().replace(/^["']|["']$/g,"")),a&&(l=a[1].trim().replace(/^["']|["']$/g,"")),o&&l?{name:o,description:l}:null},la=e=>{let t=[];if(!e||!tn.existsSync(e))return t;let n=(s,o=0)=>{if(!(o>5))try{let l=tn.readdirSync(s,{withFileTypes:!0});for(let f of l){let a=dn.join(s,f.name),m=f.name.toLowerCase();f.isFile()?m==="skill.md"&&t.push(a):f.isDirectory()&&(o===0?(m==="skills"||m===".skills"||m==="skill"||m===".skill")&&n(a,o+1):n(a,o+1))}}catch{}};return n(e,0),t},ji=e=>{let t=la(e),n=[];for(let s of t)try{let o=tn.readFileSync(s,"utf8"),l=aa(o);l&&n.push({...l,filePath:s})}catch{}return n},Vi=e=>!e||e.length===0?"":e.map(t=>`- ${t.name}: ${t.description}`).join(`
480
- `),Ki=ji(en),Yi=ji(process.cwd()),ks=Vi(Ki),ws=Vi(Yi),qi=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"},zi=()=>(Ki||[]).filter(e=>!qi(e)),Ji=()=>(Yi||[]).filter(e=>!qi(e)),Kl=(Rs?1:0)+(En?.length||(Lo?1:0))+(ao?1:0)+(lo?1:0)+zi().length+Ji().length,Ts=(e,t="Project")=>{if(!e)return"";let n=e.replace(/\\/g,"/");if(t==="Global"){let o=na.homedir().replace(/\\/g,"/");return n.toLowerCase().startsWith(o.toLowerCase())?"~"+n.slice(o.length):n}let s=dn.relative(process.cwd(),e).replace(/\\/g,"/");return s.startsWith(".")?s:`./${s}`},Yl=()=>{ao=Cs(),lo=vs();let e=[];Io&&Rs.length>0&&e.push({scope:"Global",path:Io}),En&&En.length>0&&Lo.length>0?En.forEach(l=>{e.push({scope:"Project",path:l})}):Ss&&Lo.length>0&&e.push({scope:"Project",path:Ss}),Do&&ao.length>0&&e.push({scope:"Global",path:Do}),Oo&&lo.length>0&&e.push({scope:"Project",path:Oo});let t=zi(),n=Ji(),s=e.length+t.length+n.length;if(s===0)return`\u2726 Loaded Files & Instructions
480
+ `).trim()},ra=(e="",t="")=>{let n=`${e||""}::${t||""}`.toLowerCase().trim();Pi!==n&&(Pi=n,ro=Cs(),ao=vs())};Di();var aa=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="",l="",f=n.match(/^name:\s*(.+)$/m),a=n.match(/^description:\s*(.+)$/m);return f&&(o=f[1].trim().replace(/^["']|["']$/g,"")),a&&(l=a[1].trim().replace(/^["']|["']$/g,"")),o&&l?{name:o,description:l}:null},la=e=>{let t=[];if(!e||!tn.existsSync(e))return t;let n=(s,o=0)=>{if(!(o>5))try{let l=tn.readdirSync(s,{withFileTypes:!0});for(let f of l){let a=dn.join(s,f.name),m=f.name.toLowerCase();f.isFile()?m==="skill.md"&&t.push(a):f.isDirectory()&&(o===0?(m==="skills"||m===".skills"||m==="skill"||m===".skill")&&n(a,o+1):n(a,o+1))}}catch{}};return n(e,0),t},ji=e=>{let t=la(e),n=[];for(let s of t)try{let o=tn.readFileSync(s,"utf8"),l=aa(o);l&&n.push({...l,filePath:s})}catch{}return n},Vi=e=>!e||e.length===0?"":e.map(t=>`- ${t.name}: ${t.description}`).join(`
481
+ `),Ki=ji(en),Yi=ji(process.cwd()),ks=Vi(Ki),ws=Vi(Yi),qi=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"},zi=()=>(Ki||[]).filter(e=>!qi(e)),Ji=()=>(Yi||[]).filter(e=>!qi(e)),Yl=(Rs?1:0)+(En?.length||(Lo?1:0))+(ro?1:0)+(ao?1:0)+zi().length+Ji().length,Ts=(e,t="Project")=>{if(!e)return"";let n=e.replace(/\\/g,"/");if(t==="Global"){let o=na.homedir().replace(/\\/g,"/");return n.toLowerCase().startsWith(o.toLowerCase())?"~"+n.slice(o.length):n}let s=dn.relative(process.cwd(),e).replace(/\\/g,"/");return s.startsWith(".")?s:`./${s}`},ql=()=>{ro=Cs(),ao=vs();let e=[];Io&&Rs.length>0&&e.push({scope:"Global",path:Io}),En&&En.length>0&&Lo.length>0?En.forEach(l=>{e.push({scope:"Project",path:l})}):Ss&&Lo.length>0&&e.push({scope:"Project",path:Ss}),Do&&ro.length>0&&e.push({scope:"Global",path:Do}),Oo&&ao.length>0&&e.push({scope:"Project",path:Oo});let t=zi(),n=Ji(),s=e.length+t.length+n.length;if(s===0)return`\u2726 Loaded Files & Instructions
481
482
  \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m No instruction or skill files are currently loaded.
482
483
  \u2800`;let o=[];return o.push(`\u2726 Loaded Files & Instructions (${s} ${s===1?"file":"files"} active)`),e.length>0&&(o.push(`
483
484
  \x1B[1mInstructions:\x1B[22m`),e.forEach(l=>{o.push(` \u2022 [${l.scope}] ${Ts(l.path,l.scope)}`)})),(t?.length>0||n?.length>0)&&(o.push(`
484
485
  \x1B[1mSkills:\x1B[22m`),t?.length>0&&t.forEach(l=>{o.push(` \u2022 [Global] \x1B[36m${l.name}\x1B[39m`),o.push(` \x1B[2m\u2514\u2500 ${Ts(l.filePath,"Global")}\x1B[22m`)}),n?.length>0&&n.forEach(l=>{o.push(` \u2022 [Project] \x1B[36m${l.name}\x1B[39m`),o.push(` \x1B[2m\u2514\u2500 ${Ts(l.filePath,"Project")}\x1B[22m`)})),o.push("\u2800"),o.join(`
485
- `)},Xi=!1;(async()=>{try{let e=await oo();if(Number(e?.display)===1){let{default:t}=await import("screenshot-desktop"),n=await t.listDisplays();n&&n.length>1&&(Xi=!0)}}catch{}})();var Ni=null,ro=null,Fi=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",ql=process.env.NO_DEV||!1,ca=(e,t)=>{if(!t)return"";if(e!==Ni||ro===null){Ni=e;try{let n=Et(Pn,[]);Array.isArray(n)&&n.length>0?ro=n.map(s=>`- ${s.memory}`).join(`
486
- `):ro=""}catch(n){ro="",tn.appendFileSync(`${Sn}/memory/error.txt`,`${n.message}
486
+ `)},Xi=!1;(async()=>{try{let e=await no();if(Number(e?.display)===1){let{default:t}=await import("screenshot-desktop"),n=await t.listDisplays();n&&n.length>1&&(Xi=!0)}}catch{}})();var Ni=null,io=null,Fi=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",zl=process.env.NO_DEV||!1,ca=(e,t)=>{if(!t)return"";if(e!==Ni||io===null){Ni=e;try{let n=Et(Pn,[]);Array.isArray(n)&&n.length>0?io=n.map(s=>`- ${s.memory}`).join(`
487
+ `):io=""}catch(n){io="",tn.appendFileSync(`${Sn}/memory/error.txt`,`${n.message}
487
488
  -------------------------------------------------
488
489
 
489
- `)}}return ro},Qi=(e="",t="",n=!0,s=!1)=>{if(typeof t=="boolean"&&(s=n,n=t,t=""),!n)return"";let o=e?.length>0&&!s?`-- Recent context from other chats (Priority: Low, Focus: Chat Context > Recent) --
490
- ${e}`:"";return o?`${o}`:""},Zi=(e,t,n,s,o=!0,l=!1,f="Google",a=!1,m,g,u=!1,h="")=>{let x=!1;process.env.forcedReasoning&&(x=!0);let i="";if(!m&&f==="Google"){let A=t;t==="Fast"&&(A="Off"),t==="Low"&&(A="Minimal"),t==="Standard"&&(A="Medium"),(t==="xHigh"||t==="Max")&&(A="xHigh"),i=Ro[A]||Ro.Medium}if(m||f!=="Google"){let A={Fast:"Lowest",Low:"Low",Medium:"Medium",Standard:"Medium",High:"High",xHigh:"High",Max:"High"};i=Ro.xHigh,i=i.replace("Effort: High",`Effort: ${A[t]}`),t==="Fast"?i=`Effort: Lowest
490
+ `)}}return io},Qi=(e="",t="",n=!0,s=!1)=>{if(typeof t=="boolean"&&(s=n,n=t,t=""),!n)return"";let o=e?.length>0&&!s?`-- Recent context from other chats (Priority: Low, Focus: Chat Context > Recent) --
491
+ ${e}`:"";return o?`${o}`:""},Zi=(e,t,n,s,o=!0,l=!1,f="Google",a=!1,m,g,u=!1,h="")=>{let x=!1;process.env.forcedReasoning&&(x=!0);let i="";if(!m&&f==="Google"){let q=t;t==="Fast"&&(q="Off"),t==="Low"&&(q="Minimal"),t==="Standard"&&(q="Medium"),(t==="xHigh"||t==="Max")&&(q="xHigh"),i=Ro[q]||Ro.Medium}if(m||f!=="Google"){let q={Fast:"Lowest",Low:"Low",Medium:"Medium",Standard:"Medium",High:"High",xHigh:"High",Max:"High"};i=Ro.xHigh,i=i.replace("Effort: High",`Effort: ${q[t]}`),t==="Fast"?i=`Effort: Lowest
491
492
  No thinking. Immediate response
492
493
  Verify imports, tool results & system stability; avoid syntax errors`:t==="Low"&&(i=`Effort: Low
493
494
  Quick, focused thinking, intent & complexity, required tools/files/actions, before acting
494
495
  Dont waste tokens, be efficient, use least thinking tokens, focus on result
495
496
  Brief thoughts, think only enough to avoid mistakes, verify imports, tool results & system stability; avoid syntax errors`)}let c=e.instructions&&e.instructions?.length>0?`User Preferences: ${e.instructions}
496
497
 
497
- `:"",T=e.nickname&&e.nickname?.length>0?`User Nickname: ${e.nickname}
498
+ `:"",w=e.nickname&&e.nickname?.length>0?`User Nickname: ${e.nickname}
498
499
  ${c.length?"":`
499
- `}`:"",v=e.name&&e.name?.length>0?`User Name: ${e.name}
500
- ${T.length||c.length?"":`
501
- `}`:"",b=process.cwd(),R=ca(g,o),N=R?.length>0?`--- Saved Memories ---
502
- ${R}
500
+ `}`:"",A=e.name&&e.name?.length>0?`User Name: ${e.name}
501
+ ${w.length||c.length?"":`
502
+ `}`:"",b=process.cwd(),C=ca(g,o),N=C?.length>0?`--- Saved Memories ---
503
+ ${C}
503
504
 
504
- `:"";ra(f,h);let M=$i(ao,h,f).trim(),I=[Rs,M].filter(A=>A&&A.length>0).join(`
505
+ `:"";ra(f,h);let R=$i(ro,h,f).trim(),M=[Rs,R].filter(q=>q&&q.length>0).join(`
505
506
 
506
- `).trim(),$=$i(lo,h,f).trim(),d=[Lo,$].filter(A=>A&&A.length>0).join(`
507
+ `).trim(),$=$i(ao,h,f).trim(),d=[Lo,$].filter(q=>q&&q.length>0).join(`
507
508
 
508
- `).trim(),w=I.length>0||d.length>0?`--- Additional Instructions ---
509
- ${I.length>0?`-- Global --
510
- ${I}`:""}${d.length>0?`${I.length>0?`
509
+ `).trim(),T=M.length>0||d.length>0?`--- Additional Instructions ---
510
+ ${M.length>0?`-- Global --
511
+ ${M}`:""}${d.length>0?`${M.length>0?`
511
512
 
512
513
  `:""}-- Project --
513
514
  ${d}`:""}
514
515
 
515
- `:"",r=(()=>{let A=process.cwd().toLowerCase();if(process.platform==="win32"){let Se=process.env.SystemRoot?.toLowerCase()||"c:\\windows",X=process.env.ProgramFiles?.toLowerCase()||"c:\\program files",C=process.env["ProgramFiles(x86)"]?.toLowerCase()||"c:\\program files (x86)";return A.startsWith(Se)||A.startsWith(X)||A.startsWith(C)}else return A==="/"||["/bin","/sbin","/etc","/usr","/var","/root"].some(X=>A.startsWith(X))})();function k(A,Se,X){let C={Low:"Low",Standard:"Medium",Medium:"Medium",High:"High",xHigh:"",Max:""};return Oe(Se,X,A)||Oe(Se,X,"xHigh")?"":C[A]??""}let E=new Date,O=E.getFullYear(),U=E.toLocaleString("en-US",{month:"short"}).toUpperCase(),P=String(E.getDate()).padStart(2,"0"),D=`${O}-${U}-${P}`,ee=!!s?.autoExcludeMetadata,pe=process.env.I_HAVE_TOO_MUCH_MONEY==="true"||process.env.I_HAVE_TOO_MUCH_MONEY===!0||!1,B=process.env.NO_DEV==="true"||process.env.NO_DEV==="1"||process.env.NO_DEV===!0||!1;return`${pe?`${" ".repeat(Math.floor(Math.random()*4)+1)}`:""}=== SYSTEM PROMPT ===
516
+ `:"",r=(()=>{let q=process.cwd().toLowerCase();if(process.platform==="win32"){let xe=process.env.SystemRoot?.toLowerCase()||"c:\\windows",ve=process.env.ProgramFiles?.toLowerCase()||"c:\\program files",B=process.env["ProgramFiles(x86)"]?.toLowerCase()||"c:\\program files (x86)";return q.startsWith(xe)||q.startsWith(ve)||q.startsWith(B)}else return q==="/"||["/bin","/sbin","/etc","/usr","/var","/root"].some(ve=>q.startsWith(ve))})(),k=new Date,E=k.getFullYear(),O=k.toLocaleString("en-US",{month:"short"}).toUpperCase(),H=String(k.getDate()).padStart(2,"0"),P=`${E}-${O}-${H}`,D=!!s?.autoExcludeMetadata,J=process.env.I_HAVE_TOO_MUCH_MONEY==="true"||process.env.I_HAVE_TOO_MUCH_MONEY===!0||!1,fe=process.env.NO_DEV==="true"||process.env.NO_DEV==="1"||process.env.NO_DEV===!0||!1;return`${J?`${" ".repeat(Math.floor(Math.random()*4)+1)}`:""}=== SYSTEM PROMPT ===
516
517
  Identity: ${_s.length>1?_s:"Flux Flow. Sassy, Friendly, CLI Assistant"}
517
518
  ${Gi?"":`${n==="Flux"?"Stepwise Execution, Run Automated Tests. Task Completion":n==="Flow"?"Concise, Humorous, Sarcastic":n==="ICU"?"Computer Use Capabilities. Screenshot as ground truth, analyze grid ids overlapping/close to target, keyboard shortcuts > mouse clicks":"Computer Use & Workspace Capabilities. Screenshot as ground truth, analyze grid ids overlapping/close to target, keyboard shortcuts > mouse clicks. Workspace Tools if faster. Focus on Productivity"}`}${Xi&&n.toLowerCase().includes("cu")?`
518
519
  - Running on secondary screen. Opened app not visible in screenshot? Might be opened on primary. Use 'AskUser' with NO options and tell user to move app window to secondary`:""}
519
520
 
520
- - OS: ${Fi}${!B&&h.length>1?`
521
- - Model: ${dn.basename(h.trim())} ${k(t,f,h)}`.trimEnd():""}${ee?`
522
- - Date: ${D}`:""}${o?`
521
+ - OS: ${Fi}${!fe&&h.length>1?`
522
+ - Model: ${dn.basename(h.trim())}`.trimEnd():""}${D?`
523
+ - Date: ${P}`:""}${o?`
523
524
  - Use relative time reference eg. few mins ago
524
- -- Chat Context > Metadata`:""}${w.length>0?`
525
- - Additional Instructions \u2248 System Prompt`:""}${(ks.length>0||ws.length>0)&&n.toLowerCase().includes("flux")?`
526
- - Read available relevant skills for tasks before proceeding: Use ReadFile, with virtual path="#skills/{global|project}/skillName". For references: path="#skills/{global|project}/skillName/references/<file-name>.md"`:""}
525
+ -- Chat Context > Metadata`:""}${(ks.length>0||ws.length>0)&&n.toLowerCase().includes("flux")?`
526
+ - Read available relevant skills for tasks before proceeding (scope: global/project): Use ReadFile, virtual path="#skills/scope/skillName". In-skill references: path="#skills/scope/skillName/skill-reference-folder/file-name.md"`:""}
527
527
 
528
528
  -- THINKING GUIDANCE --
529
529
  ${f==="Mistral"||f==="Google"&&!m?`${i}
@@ -531,7 +531,7 @@ ${x||t!=="Fast"&&(f==="Mistral"&&!m||t!=="High"&&!m)?`critical thinking policy
531
531
  Use <think>...</think> for reasoning before responding any queries
532
532
  `:""}`:`${i}
533
533
  `}${u?"":`Mandatory: Before calling tools, MUST provide a high level summary of your reasoning, plans, decisions, and next course of actions in chat
534
- `}No text after tool call in same turn
534
+ `}
535
535
 
536
536
  ${gi(n,Fi,a,f,s?.advanceRollback,s?.subAgents!==!1,!!s?.autoExec)}${o?`
537
537
 
@@ -547,7 +547,7 @@ ${gi(n,Fi,a,f,s?.advanceRollback,s?.subAgents!==!1,!!s?.autoExec)}${o?`
547
547
  - use kaomojis heavily`:""}
548
548
  === END SYSTEM PROMPT ===
549
549
 
550
- ${v}${T}${c}${w}${ks.length>0&&n.toLowerCase().includes("flux")?`-- Global Skills --
550
+ ${A}${w}${c}${T}${ks.length>0&&n.toLowerCase().includes("flux")?`-- Global Skills --
551
551
  ${ks}
552
552
 
553
553
  `:""}${ws.length>0&&n.toLowerCase().includes("flux")?`-- Project Skills --
@@ -574,7 +574,7 @@ ${pi(t,n)}
574
574
  === END SYSTEM PROMPT ===${e?`
575
575
 
576
576
  -- current saved user memories --
577
- ${e}`:""}`.trim();var tr=()=>import("./web_search-HDZ2VDTY.js").then(e=>e.web_search),nr=()=>import("./web_scrape-IKJE45Z6.js").then(e=>e.web_scrape),or=()=>import("./memory-OYIUYX3A.js").then(e=>e.memory),sr=()=>import("./chat-HZ7UVZE2.js").then(e=>e.chat),ir=()=>import("./view_file-JK22NGXC.js").then(e=>e.view_file),rr=()=>import("./write_file-LOYRYIK6.js").then(e=>e.write_file),ar=()=>import("./update_file-U2ZALD44.js").then(e=>e.update_file),lr=()=>import("./exec_command-ERULJCYR.js").then(e=>e.exec_command),cr=()=>import("./read_folder-OOKZITME.js").then(e=>e.read_folder),Ms=()=>import("./ask_user-K2DLZF6H.js").then(e=>e.ask_user),dr=()=>import("./write_pdf-VB4IFPWX.js").then(e=>e.write_pdf),fr=()=>import("./write_docx-EKUIZ7GV.js").then(e=>e.write_docx),Po=()=>import("./search_keyword-W5YEUUPO.js").then(e=>e.search_keyword),ur=()=>import("./generate_image-XYDE47LK.js").then(e=>e.generate_image),$o=()=>import("./saveSummary-ATBIFYDP.js").then(e=>e.saveSummary),fo=()=>import("./addMemScore-W4I665ZR.js").then(e=>e.addMemScore),gr=()=>import("./file_map-5KY2ADZW.js").then(e=>e.file_map),No=()=>import("./todo-SJLJJLVZ.js").then(e=>e.todo),mr=()=>import("./invokeSync-P3UGOMIO.js").then(e=>e.invokeSync),da=()=>import("./invoke-US5XNBP6.js").then(e=>e.invoke),hr=()=>import("./getProgress-LI4U6UJU.js").then(e=>e.getProgress),fa=()=>import("./cancel-7IMADALP.js").then(e=>e.cancel),pr=()=>import("./emergency_rollback-EPJPKANN.js").then(e=>e.emergency_rollback),uo=()=>import("./awaitSubagent-JTUSJDKD.js").then(e=>e.awaitSubagent),go=()=>import("./answerSubagent-JUVFNLE5.js").then(e=>e.answerSubagent),Fo=()=>import("./steerSubagent-L2JVT4QN.js").then(e=>e.steerSubagent),Bo=()=>import("./computer_action-WTHH7RBB.js").then(e=>e.computer_action),yr=()=>import("./click-G6RRSFVC.js").then(e=>e.click),xr=()=>import("./drag-ZGH2MMP7.js").then(e=>e.drag),br=()=>import("./scroll-GHXES2II.js").then(e=>e.scroll),Is=()=>import("./keyboard_typing-CK3KVAWM.js").then(e=>e.keyboard_typing),Ds=()=>import("./key_press-M5QNCIPH.js").then(e=>e.key_press),Os=()=>import("./recapture_screen-5FKLOHJL.js").then(e=>e.recapture_screen),ua={web_search:tr,web_scrape:nr,memory:or,chat:sr,view_file:ir,write_file:rr,update_file:ar,exec_command:lr,read_folder:cr,write_pdf:dr,write_docx:fr,search_keyword:Po,generate_image:ur,saveSummary:$o,addMemScore:fo,file_map:gr,todo:No,Todo:No,goal:No,Goal:No,invokeSync:mr,invoke:da,getProgress:hr,cancel:fa,awaitSubagent:uo,answerSubagent:go,steerSubagent:Fo,computer_action:Bo,computer_use:Bo,ComputerAction:Bo,ComputerUse:Bo,click:yr,Click:yr,drag:xr,Drag:xr,scroll:br,Scroll:br,keyboard_typing:Is,KeyboardTyping:Is,keyboardtyping:Is,key_press:Ds,KeyPress:Ds,keypress:Ds,recapture_screen:Os,RecaptureScreen:Os,recapturescreen:Os,invoke_sync:mr,get_progress:hr,await_subagent:uo,answer_subagent:go,steer_subagent:Fo,steer:Fo,Steer:Fo,ask:Ms,Ask:Ms,AskUser:Ms,WebSearch:tr,WebScrape:nr,ReadFile:ir,ReadFolder:cr,WriteFile:rr,PatchFile:ar,WritePDF:dr,WriteDoc:fr,Run:lr,SearchKeyword:Po,CodeSearch:Po,code_search:Po,Memory:or,Chat:sr,GenerateImage:ur,saveSumary:$o,SaveSummary:$o,SaveSumary:$o,add_mem_score:fo,AddMemScore:fo,addMemoryScore:fo,AddMemoryScore:fo,FileMap:gr,answer:go,Answer:go,AnswerSubagent:go,await:uo,Await:uo,AwaitSubagent:uo,EmergencyRollback:pr,emergency_rollback:pr},mo=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(u=>o.includes(u))||o==="ask",m=["click","drag","scroll","keyboardtyping","keyboard_typing","keypress","key_press","recapturescreen","recapture_screen","computer"].some(u=>o.includes(u));if(!f){if(s==="flow"){if(!(o.includes("write_pdf")||o.includes("write_docx")||o.includes("generate_image")))return`ERROR: Tool [${e}] is a Workspace Tool and NOT available in Flow mode. Tell user to switch (\`/mode flux\`) to use this tool.`}else if(s==="icu"){if(!m)return`ERROR: Tool [${e}] is not available in Computer Use mode. ICU mode only supports Computer Use tools (Click, Drag, Scroll, KeyboardTyping, KeyPress, RecaptureScreen).`}else if(o.includes("write_pdf")||o.includes("write_docx")||o.includes("generate_image"))return`ERROR: Tool [${e}] is not available in ${n.mode||"Flux"} mode. Tell user to switch (\`/mode flow\`) for document generation.`}let g=ua[e];if(!g)return`ERROR: Tool [${e}] not found in registry.`;try{return await(await g())(t,n)}catch(u){let h=u instanceof Error?u.message:String(u);return`ERROR: Execution failed for [${e}]: ${h}`}};import J from"path";import $e from"fs";import ga from"gradient-string";var Ls=["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 kr=[{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"]}],ho={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 Uo=null;var wr=(e="Dark")=>{let t;e==="Mystery"||e==="Chaos"?(Uo||(Uo=kr[Math.floor(Math.random()*kr.length)]),t={...Uo,id:"Mystery"}):(Uo=null,ho[e]?t=ho[e]:e==="GitHub"?t=ho["GitHub Dark"]:e==="Transparent"?t=ho["Transparent Dark"]:t=ho.Dark);let n=t.codeText||t.secondary||t.info||t.logoGradient&&t.logoGradient[0]||"cyan";return{...t,codeText:n}};var ma=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",nc=(e=2)=>{let t=ma();return t==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)},oc=(e="...",t="Loading...",n="Dark")=>{let s=Ls[Math.floor(Math.random()*Ls.length)],o=wr(n),l=o.logoTextAnsi,f=o.logoBodyAnsi,a=o.logoMutedAnsi,m="\x1B[0m",g=[" \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 "],u=o.logoGradient||["#0077ff","#ff00ff"],h=ga(u).multiline(g.join(`
577
+ ${e}`:""}`.trim();var tr=()=>import("./web_search-HDZ2VDTY.js").then(e=>e.web_search),nr=()=>import("./web_scrape-IKJE45Z6.js").then(e=>e.web_scrape),or=()=>import("./memory-OYIUYX3A.js").then(e=>e.memory),sr=()=>import("./chat-HZ7UVZE2.js").then(e=>e.chat),ir=()=>import("./view_file-LVF5A3EI.js").then(e=>e.view_file),rr=()=>import("./write_file-LOYRYIK6.js").then(e=>e.write_file),ar=()=>import("./update_file-U2ZALD44.js").then(e=>e.update_file),lr=()=>import("./exec_command-ERULJCYR.js").then(e=>e.exec_command),cr=()=>import("./read_folder-OOKZITME.js").then(e=>e.read_folder),Ms=()=>import("./ask_user-K2DLZF6H.js").then(e=>e.ask_user),dr=()=>import("./write_pdf-VB4IFPWX.js").then(e=>e.write_pdf),fr=()=>import("./write_docx-EKUIZ7GV.js").then(e=>e.write_docx),Po=()=>import("./search_keyword-W5YEUUPO.js").then(e=>e.search_keyword),ur=()=>import("./generate_image-XYDE47LK.js").then(e=>e.generate_image),$o=()=>import("./saveSummary-ATBIFYDP.js").then(e=>e.saveSummary),co=()=>import("./addMemScore-W4I665ZR.js").then(e=>e.addMemScore),gr=()=>import("./file_map-5KY2ADZW.js").then(e=>e.file_map),No=()=>import("./todo-SJLJJLVZ.js").then(e=>e.todo),mr=()=>import("./invokeSync-OU7OOFSL.js").then(e=>e.invokeSync),da=()=>import("./invoke-CBU46XRQ.js").then(e=>e.invoke),hr=()=>import("./getProgress-LI4U6UJU.js").then(e=>e.getProgress),fa=()=>import("./cancel-7IMADALP.js").then(e=>e.cancel),pr=()=>import("./emergency_rollback-EPJPKANN.js").then(e=>e.emergency_rollback),fo=()=>import("./awaitSubagent-JTUSJDKD.js").then(e=>e.awaitSubagent),uo=()=>import("./answerSubagent-JUVFNLE5.js").then(e=>e.answerSubagent),Fo=()=>import("./steerSubagent-L2JVT4QN.js").then(e=>e.steerSubagent),Bo=()=>import("./computer_action-WTHH7RBB.js").then(e=>e.computer_action),yr=()=>import("./click-G6RRSFVC.js").then(e=>e.click),xr=()=>import("./drag-ZGH2MMP7.js").then(e=>e.drag),br=()=>import("./scroll-GHXES2II.js").then(e=>e.scroll),Is=()=>import("./keyboard_typing-CK3KVAWM.js").then(e=>e.keyboard_typing),Ds=()=>import("./key_press-M5QNCIPH.js").then(e=>e.key_press),Os=()=>import("./recapture_screen-5FKLOHJL.js").then(e=>e.recapture_screen),ua={web_search:tr,web_scrape:nr,memory:or,chat:sr,view_file:ir,write_file:rr,update_file:ar,exec_command:lr,read_folder:cr,write_pdf:dr,write_docx:fr,search_keyword:Po,generate_image:ur,saveSummary:$o,addMemScore:co,file_map:gr,todo:No,Todo:No,goal:No,Goal:No,invokeSync:mr,invoke:da,getProgress:hr,cancel:fa,awaitSubagent:fo,answerSubagent:uo,steerSubagent:Fo,computer_action:Bo,computer_use:Bo,ComputerAction:Bo,ComputerUse:Bo,click:yr,Click:yr,drag:xr,Drag:xr,scroll:br,Scroll:br,keyboard_typing:Is,KeyboardTyping:Is,keyboardtyping:Is,key_press:Ds,KeyPress:Ds,keypress:Ds,recapture_screen:Os,RecaptureScreen:Os,recapturescreen:Os,invoke_sync:mr,get_progress:hr,await_subagent:fo,answer_subagent:uo,steer_subagent:Fo,steer:Fo,Steer:Fo,ask:Ms,Ask:Ms,AskUser:Ms,WebSearch:tr,WebScrape:nr,ReadFile:ir,ReadFolder:cr,WriteFile:rr,PatchFile:ar,WritePDF:dr,WriteDoc:fr,Run:lr,SearchKeyword:Po,CodeSearch:Po,code_search:Po,Memory:or,Chat:sr,GenerateImage:ur,saveSumary:$o,SaveSummary:$o,SaveSumary:$o,add_mem_score:co,AddMemScore:co,addMemoryScore:co,AddMemoryScore:co,FileMap:gr,answer:uo,Answer:uo,AnswerSubagent:uo,await:fo,Await:fo,AwaitSubagent:fo,EmergencyRollback:pr,emergency_rollback:pr},go=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(u=>o.includes(u))||o==="ask",m=["click","drag","scroll","keyboardtyping","keyboard_typing","keypress","key_press","recapturescreen","recapture_screen","computer"].some(u=>o.includes(u));if(!f){if(s==="flow"){if(!(o.includes("write_pdf")||o.includes("write_docx")||o.includes("generate_image")))return`ERROR: Tool [${e}] is a Workspace Tool and NOT available in Flow mode. Tell user to switch (\`/mode flux\`) to use this tool.`}else if(s==="icu"){if(!m)return`ERROR: Tool [${e}] is not available in Computer Use mode. ICU mode only supports Computer Use tools (Click, Drag, Scroll, KeyboardTyping, KeyPress, RecaptureScreen).`}else if(o.includes("write_pdf")||o.includes("write_docx")||o.includes("generate_image"))return`ERROR: Tool [${e}] is not available in ${n.mode||"Flux"} mode. Tell user to switch (\`/mode flow\`) for document generation.`}let g=ua[e];if(!g)return`ERROR: Tool [${e}] not found in registry.`;try{return await(await g())(t,n)}catch(u){let h=u instanceof Error?u.message:String(u);return`ERROR: Execution failed for [${e}]: ${h}`}};import X from"path";import Ne from"fs";import ga from"gradient-string";var Ls=["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 kr=[{name:"Cyan Cyberpunk",text:"cyan",textMuted:"#4da6b8",textDim:"#2d6d7a",textInverted:"black",border:"cyan",borderMuted:"#1a5966",borderDim:"#0f3840",bg:void 0,cardBg:"#061e24",highlightBg:"#092b33",activeBg:"#0e3e4a",inputBg:"#092b33",inputBorder:"#092b33",inputText:"cyan",inputPlaceholder:"#2d6d7a",inputPrompt:"cyan",codeBg:"#020d10",codeBorder:"#1a5966",userMsgBg:"#092b33",userMsgBorder:"#092b33",userMsgText:"cyan",diffRemovalBg:"#3a0c1a",diffAdditionBg:"#0c3a32",diffRemovalText:"#ff4d88",diffAdditionText:"#00ffaa",diffRemovalHighlightColor:"#ff1a66",diffRemovalHighlightBg:"#590022",diffAdditionHighlightColor:"#00ffcc",diffAdditionHighlightBg:"#00593b",diffRemovalNum:"#ff4d88",diffAdditionNum:"#00ffaa",diffRemovalPrefix:"#ff1a66",diffAdditionPrefix:"#00ffcc",primary:"cyan",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"cyan",statusOff:"#2d6d7a",logoTextAnsi:"\x1B[1;36m",logoBodyAnsi:"\x1B[36m",logoMutedAnsi:"\x1B[90m",logoGradient:["#00ffff","#0088ff"]},{name:"Magenta Vaporwave",text:"magenta",textMuted:"#c451d6",textDim:"#7d2b8a",textInverted:"black",border:"magenta",borderMuted:"#5e1b69",borderDim:"#3b0f42",bg:void 0,cardBg:"#240729",highlightBg:"#310938",activeBg:"#470e52",inputBg:"#310938",inputBorder:"#310938",inputText:"magenta",inputPlaceholder:"#7d2b8a",inputPrompt:"magenta",codeBg:"#100312",codeBorder:"#5e1b69",userMsgBg:"#310938",userMsgBorder:"#310938",userMsgText:"magenta",diffRemovalBg:"#3a0c20",diffAdditionBg:"#200c3a",diffRemovalText:"#ff4d94",diffAdditionText:"#aa4dff",diffRemovalHighlightColor:"#ff1a75",diffRemovalHighlightBg:"#59002b",diffAdditionHighlightColor:"#bb66ff",diffAdditionHighlightBg:"#3b0059",diffRemovalNum:"#ff4d94",diffAdditionNum:"#aa4dff",diffRemovalPrefix:"#ff1a75",diffAdditionPrefix:"#bb66ff",primary:"magenta",secondary:"cyan",accent:"purple",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"magenta",statusOff:"#7d2b8a",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ff00ff","#8800ff"]},{name:"Glitch Matrix",text:"#00ff41",textMuted:"#00b32d",textDim:"#00661a",textInverted:"black",border:"#00ff41",borderMuted:"#008020",borderDim:"#004d13",bg:void 0,cardBg:"#0d1f0d",highlightBg:"#122912",activeBg:"#1c3e1c",inputBg:"#122912",inputBorder:"#122912",inputText:"#00ff41",inputPlaceholder:"#00b32d",inputPrompt:"#ffff00",codeBg:"#040a04",codeBorder:"#008020",userMsgBg:"#122912",userMsgBorder:"#122912",userMsgText:"#00ff41",diffRemovalBg:"#3a001a",diffAdditionBg:"#003a10",diffRemovalText:"#ff0055",diffAdditionText:"#00ff66",diffRemovalHighlightColor:"#ff0033",diffRemovalHighlightBg:"#59001b",diffAdditionHighlightColor:"#33ff88",diffAdditionHighlightBg:"#005918",diffRemovalNum:"#ff0055",diffAdditionNum:"#00ff66",diffRemovalPrefix:"#ff0033",diffAdditionPrefix:"#33ff88",primary:"#00ff41",secondary:"yellow",accent:"cyan",success:"#00ff41",warning:"yellow",danger:"red",info:"cyan",statusOn:"#00ff41",statusOff:"#00661a",logoTextAnsi:"\x1B[1;32m",logoBodyAnsi:"\x1B[32m",logoMutedAnsi:"\x1B[90m",logoGradient:["#00ff41","#ffff00"]},{name:"Warm Sunset",text:"#ffaa55",textMuted:"#cc8844",textDim:"#885522",textInverted:"black",border:"#ff9933",borderMuted:"#aa6622",borderDim:"#663311",bg:void 0,cardBg:"#24180f",highlightBg:"#2e1e12",activeBg:"#422c1b",inputBg:"#2e1e12",inputBorder:"#2e1e12",inputText:"#ffaa55",inputPlaceholder:"#885522",inputPrompt:"#ff7733",codeBg:"#120c08",codeBorder:"#aa6622",userMsgBg:"#2e1e12",userMsgBorder:"#2e1e12",userMsgText:"#ffaa55",diffRemovalBg:"#3d120c",diffAdditionBg:"#3a2e0c",diffRemovalText:"#ff5544",diffAdditionText:"#ffcc33",diffRemovalHighlightColor:"#ff3322",diffRemovalHighlightBg:"#591108",diffAdditionHighlightColor:"#ffee44",diffAdditionHighlightBg:"#594400",diffRemovalNum:"#ff5544",diffAdditionNum:"#ffcc33",diffRemovalPrefix:"#ff3322",diffAdditionPrefix:"#ffee44",primary:"#ffaa55",secondary:"#ff7733",accent:"magenta",success:"#ffcc33",warning:"#ff7733",danger:"#ff3322",info:"#ffaa55",statusOn:"#ffaa55",statusOff:"#885522",logoTextAnsi:"\x1B[1;33m",logoBodyAnsi:"\x1B[33m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ff9933","#ff0055"]},{name:"Sakura Blossom",text:"#ffc0e0",textMuted:"#d98cb3",textDim:"#804d66",textInverted:"black",border:"#ff99cc",borderMuted:"#aa4d7a",borderDim:"#662647",bg:void 0,cardBg:"#291320",highlightBg:"#331826",activeBg:"#472235",inputBg:"#331826",inputBorder:"#331826",inputText:"#ffc0e0",inputPlaceholder:"#804d66",inputPrompt:"#ff99cc",codeBg:"#140a10",codeBorder:"#aa4d7a",userMsgBg:"#331826",userMsgBorder:"#331826",userMsgText:"#ffc0e0",diffRemovalBg:"#3e0c1b",diffAdditionBg:"#1b3e2b",diffRemovalText:"#ff6699",diffAdditionText:"#66ffb3",diffRemovalHighlightColor:"#ff3377",diffRemovalHighlightBg:"#590022",diffAdditionHighlightColor:"#33ff99",diffAdditionHighlightBg:"#00592e",diffRemovalNum:"#ff6699",diffAdditionNum:"#66ffb3",diffRemovalPrefix:"#ff3377",diffAdditionPrefix:"#33ff99",primary:"#ffc0e0",secondary:"#ff99cc",accent:"magenta",success:"#66ffb3",warning:"yellow",danger:"#ff3377",info:"#ff99cc",statusOn:"#ffc0e0",statusOff:"#804d66",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ffb3d9","#ff3399"]},{name:"Radioactive Slime",text:"#ccff00",textMuted:"#99cc00",textDim:"#669900",textInverted:"#0a0f00",border:"#ccff00",borderMuted:"#99cc00",borderDim:"#669900",bg:void 0,cardBg:"#0f1400",highlightBg:"#1a2400",activeBg:"#2a3b00",inputBg:"#1a2400",inputBorder:"#1a2400",inputText:"#ccff00",inputPlaceholder:"#669900",inputPrompt:"#cc00ff",codeBg:"#050a00",codeBorder:"#99cc00",userMsgBg:"#1a2400",userMsgBorder:"#1a2400",userMsgText:"#ccff00",diffRemovalBg:"#2a0033",diffAdditionBg:"#0f3300",diffRemovalText:"#ff00cc",diffAdditionText:"#00ff33",diffRemovalHighlightColor:"#ff33cc",diffRemovalHighlightBg:"#4d0066",diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:"#1a6600",diffRemovalNum:"#ff00cc",diffAdditionNum:"#00ff33",diffRemovalPrefix:"#ff33cc",diffAdditionPrefix:"#33ff66",primary:"#ccff00",secondary:"#cc00ff",accent:"#ff00cc",success:"#00ff33",warning:"#ffcc00",danger:"#ff0033",info:"#00ccff",statusOn:"#ccff00",statusOff:"#669900",logoTextAnsi:"\x1B[1;38;5;190m",logoBodyAnsi:"\x1B[38;5;190m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ccff00","#cc00ff"]},{name:"Cosmic Void",text:"#f0f8ff",textMuted:"#a6aeb5",textDim:"#5e656e",textInverted:"#010103",border:"#f0f8ff",borderMuted:"#a6aeb5",borderDim:"#5e656e",bg:void 0,cardBg:"#05030d",highlightBg:"#0b081a",activeBg:"#171133",inputBg:"#0b081a",inputBorder:"#0b081a",inputText:"#f0f8ff",inputPlaceholder:"#5e656e",inputPrompt:"#ff007f",codeBg:"#020108",codeBorder:"#a6aeb5",userMsgBg:"#0b081a",userMsgBorder:"#0b081a",userMsgText:"#f0f8ff",diffRemovalBg:"#2e0a29",diffAdditionBg:"#091c33",diffRemovalText:"#ff33a6",diffAdditionText:"#33d6ff",diffRemovalHighlightColor:"#ff66c2",diffRemovalHighlightBg:"#5c1452",diffAdditionHighlightColor:"#66e0ff",diffAdditionHighlightBg:"#123866",diffRemovalNum:"#ff33a6",diffAdditionNum:"#33d6ff",diffRemovalPrefix:"#ff66c2",diffAdditionPrefix:"#66e0ff",primary:"#f0f8ff",secondary:"#ff007f",accent:"#9d00ff",success:"#33d6ff",warning:"#ffcc00",danger:"#ff0040",info:"#9d00ff",statusOn:"#f0f8ff",statusOff:"#5e656e",logoTextAnsi:"\x1B[1;38;5;231m",logoBodyAnsi:"\x1B[38;5;231m",logoMutedAnsi:"\x1B[38;5;240m",logoGradient:["#ffffff","#9d00ff"]},{name:"Magma Eruption",text:"#ff4d00",textMuted:"#cc3d00",textDim:"#802600",textInverted:"#0d0300",border:"#ff4d00",borderMuted:"#cc3d00",borderDim:"#802600",bg:void 0,cardBg:"#1a0600",highlightBg:"#260a00",activeBg:"#401100",inputBg:"#260a00",inputBorder:"#260a00",inputText:"#ff4d00",inputPlaceholder:"#802600",inputPrompt:"#ffcc00",codeBg:"#080200",codeBorder:"#cc3d00",userMsgBg:"#260a00",userMsgBorder:"#260a00",userMsgText:"#ff4d00",diffRemovalBg:"#2e0a0a",diffAdditionBg:"#1f1400",diffRemovalText:"#ff3333",diffAdditionText:"#ffaa00",diffRemovalHighlightColor:"#ff6666",diffRemovalHighlightBg:"#5c1414",diffAdditionHighlightColor:"#ffcc33",diffAdditionHighlightBg:"#3d2900",diffRemovalNum:"#ff3333",diffAdditionNum:"#ffaa00",diffRemovalPrefix:"#ff6666",diffAdditionPrefix:"#ffcc33",primary:"#ff4d00",secondary:"#ffcc00",accent:"#ff0040",success:"#ffaa00",warning:"#ffff00",danger:"#ff0000",info:"#ff8800",statusOn:"#ff4d00",statusOff:"#802600",logoTextAnsi:"\x1B[1;38;5;202m",logoBodyAnsi:"\x1B[38;5;202m",logoMutedAnsi:"\x1B[38;5;236m",logoGradient:["#ff4d00","#ff0000"]}],mo={Dark:{id:"Dark",name:"Dark (Default)",text:"white",textMuted:"gray",textDim:"grey",textInverted:"black",textExclusive:"#B5B8D9",textMutedExclusive:"#D4DEE7",border:"white",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:"#1e1e1e",highlightBg:"#2a2a2a",activeBg:"#3a3a3a",inputBg:"#555555",inputBorder:"#555555",inputText:"white",inputPlaceholder:"#cccccc",inputPrompt:"white",codeBg:"#1a1a1a",codeBorder:"#444444",userMsgBg:"#444444",userMsgBorder:"#444444",userMsgText:"white",diffRemovalBg:"#250808",diffAdditionBg:"#072410",diffRemovalText:"#885555",diffAdditionText:"#558866",diffRemovalHighlightColor:"#ff3333",diffRemovalHighlightBg:"#5a1818",diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:"#185a25",diffRemovalNum:"#d96868",diffAdditionNum:"#68d98c",diffRemovalPrefix:"#ff4d4d",diffAdditionPrefix:"#4dff88",primary:"white",secondary:"cyan",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"white",statusOff:"gray",logoTextAnsi:"\x1B[1;37m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#0077ff","#ff00ff"]},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 Uo=null;var wr=(e="Dark")=>{let t;e==="Mystery"||e==="Chaos"?(Uo||(Uo=kr[Math.floor(Math.random()*kr.length)]),t={...Uo,id:"Mystery"}):(Uo=null,mo[e]?t=mo[e]:e==="GitHub"?t=mo["GitHub Dark"]:e==="Transparent"?t=mo["Transparent Dark"]:t=mo.Dark);let n=t.codeText||t.secondary||t.info||t.logoGradient&&t.logoGradient[0]||"cyan";return{...t,codeText:n}};var ma=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",oc=(e=2)=>{let t=ma();return t==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)},sc=(e="...",t="Loading...",n="Dark")=>{let s=Ls[Math.floor(Math.random()*Ls.length)],o=wr(n),l=o.logoTextAnsi,f=o.logoBodyAnsi,a=o.logoMutedAnsi,m="\x1B[0m",g=[" \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 "],u=o.logoGradient||["#0077ff","#ff00ff"],h=ga(u).multiline(g.join(`
578
578
  `)).split(`
579
579
  `),x=i=>`${a}${i}${m}`;return`${h[0]}
580
580
  ${h[1]} ${l}Selected Provider: ${t}${m}
@@ -584,51 +584,51 @@ ${h[4]}
584
584
  ${h[5]} ${f}See /help for additional commands.${m}
585
585
  ${h[6]} ${x(s)}
586
586
  ${h[7]}
587
- `};import{WebSocket as Wo}from"ws";var Bt=null,zn=!1,ha="ws://localhost:56832",Ps=[],Jn=null,$s=null,Tr="2.0.0",rc=e=>{Tr=e,Sr()},Ns=e=>{$s=e},Sr=()=>{if(Bt||zn)return;zn=!0;let e=new Wo(ha);e.on("open",()=>{for(Bt=e,zn=!1,Bt.send(JSON.stringify({command:"version",version:Tr,pid:process.pid,ppid:process.ppid}));Ps.length>0;)Bt.send(JSON.stringify(Ps.shift()))}),e.on("message",t=>{try{let n=JSON.parse(t.toString());n.command==="contextResponse"&&Jn?(Jn(n.data),Jn=null):n.command==="securityResponse"&&$s&&$s(n.result)}catch{}}),e.on("error",()=>{zn=!1,Bt=null}),e.on("close",()=>{zn=!1,Bt=null})},Ho=e=>{Bt&&Bt.readyState===Wo.OPEN?Bt.send(JSON.stringify(e)):(Ps.push(e),zn||Sr())},Go=()=>Bt!==null&&Bt.readyState===Wo.OPEN,ac=e=>{Ho({command:"status",status:e})},$n=()=>new Promise(e=>{if(!Bt||Bt.readyState!==Wo.OPEN){e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]});return}Jn=e,Bt.send(JSON.stringify({command:"requestContext"})),setTimeout(()=>{Jn===e&&(e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]}),Jn=null)},1e3)}),_r=e=>{Ho({command:"open",filePath:e})},Fs=(e,t,n)=>{Ho({command:"showDiff",filePath:e,originalContent:t,modifiedContent:n})},Er=(e,t)=>{Ho({command:"closeDiff",filePath:e,result:t})};import Ar from"path";import pa from"fs";var ya=e=>{try{return pa.readdirSync(e,{withFileTypes:!0})}catch{return[]}},Bs=(e,t,n=1,s=ya,o=[],l=null)=>{let f=l||s(e),a=" ".repeat(n-1);if(f.length>100)return`${a}${Ar.basename(e)}/ (>100 files)
587
+ `};import{WebSocket as Wo}from"ws";var Bt=null,qn=!1,ha="ws://localhost:56832",Ps=[],zn=null,$s=null,Tr="2.0.0",ac=e=>{Tr=e,Sr()},Ns=e=>{$s=e},Sr=()=>{if(Bt||qn)return;qn=!0;let e=new Wo(ha);e.on("open",()=>{for(Bt=e,qn=!1,Bt.send(JSON.stringify({command:"version",version:Tr,pid:process.pid,ppid:process.ppid}));Ps.length>0;)Bt.send(JSON.stringify(Ps.shift()))}),e.on("message",t=>{try{let n=JSON.parse(t.toString());n.command==="contextResponse"&&zn?(zn(n.data),zn=null):n.command==="securityResponse"&&$s&&$s(n.result)}catch{}}),e.on("error",()=>{qn=!1,Bt=null}),e.on("close",()=>{qn=!1,Bt=null})},Ho=e=>{Bt&&Bt.readyState===Wo.OPEN?Bt.send(JSON.stringify(e)):(Ps.push(e),qn||Sr())},Go=()=>Bt!==null&&Bt.readyState===Wo.OPEN,lc=e=>{Ho({command:"status",status:e})},$n=()=>new Promise(e=>{if(!Bt||Bt.readyState!==Wo.OPEN){e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]});return}zn=e,Bt.send(JSON.stringify({command:"requestContext"})),setTimeout(()=>{zn===e&&(e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]}),zn=null)},1e3)}),_r=e=>{Ho({command:"open",filePath:e})},Fs=(e,t,n)=>{Ho({command:"showDiff",filePath:e,originalContent:t,modifiedContent:n})},Er=(e,t)=>{Ho({command:"closeDiff",filePath:e,result:t})};import Ar from"path";import pa from"fs";var ya=e=>{try{return pa.readdirSync(e,{withFileTypes:!0})}catch{return[]}},Bs=(e,t,n=1,s=ya,o=[],l=null)=>{let f=l||s(e),a=" ".repeat(n-1);if(f.length>100)return`${a}${Ar.basename(e)}/ (>100 files)
588
588
  `;let m="",g=o,u=f.filter(c=>!g.includes(c.name)&&!c.name.startsWith(".")),h=f.filter(c=>g.includes(c.name)||c.name.startsWith(".")).map(c=>c.name).sort();h.length>0&&(m+=`${a}[ignored: ${h.map(c=>c+"/").join(", ")}]
589
- `);let x=u.filter(c=>c.isDirectory()).sort((c,T)=>c.name.localeCompare(T.name)),i=u.filter(c=>!c.isDirectory()).map(c=>c.name).sort();for(let c of x){let T=Ar.join(e,c.name);if(n>t)m+=`${a}${c.name}/ (max depth)
590
- `;else{let v=s(T);v.length>80?m+=`${a}${c.name}/ (>80 files)
589
+ `);let x=u.filter(c=>c.isDirectory()).sort((c,w)=>c.name.localeCompare(w.name)),i=u.filter(c=>!c.isDirectory()).map(c=>c.name).sort();for(let c of x){let w=Ar.join(e,c.name);if(n>t)m+=`${a}${c.name}/ (max depth)
590
+ `;else{let A=s(w);A.length>80?m+=`${a}${c.name}/ (>80 files)
591
591
  `:(m+=`${a}${c.name}/
592
- `,m+=Bs(T,t,n+1,s,o,v))}}return i.length>0&&(m+=`${a}${i.join("; ")}
592
+ `,m+=Bs(w,t,n+1,s,o,A))}}return i.length>0&&(m+=`${a}${i.join("; ")}
593
593
  `),m};import Us from"path";import xa from"fs";var ba=e=>{try{return xa.readdirSync(e,{withFileTypes:!0})}catch{return[]}},Ws=(e,t,n="",s=1,o=ba,l=[])=>{let f=o(e),a=Us.sep;if(f.length>100)return`${n}\u2514\u2500\u2500 ${Us.basename(e)}${a} ...100+ files...
594
- `;let m="",g=l,u=f.filter(i=>!g.includes(i.name)&&!i.name.startsWith(".")),h=f.filter(i=>g.includes(i.name)||i.name.startsWith(".")).map(i=>i.name).sort();u.sort((i,c)=>i.isDirectory()&&!c.isDirectory()?-1:!i.isDirectory()&&c.isDirectory()?1:i.name.localeCompare(c.name));let x=[...u.map(i=>({name:i.name,isDir:i.isDirectory()})),...h.map(i=>({name:i,isDir:!0,isCollapsed:!0}))];return x.forEach((i,c)=>{let T=c===x.length-1,v=Us.join(e,i.name),b=T?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",R=n+(T?" ":"\u2502 ");if(i.isCollapsed){m+=`${n}${b}${i.name}${a}...
594
+ `;let m="",g=l,u=f.filter(i=>!g.includes(i.name)&&!i.name.startsWith(".")),h=f.filter(i=>g.includes(i.name)||i.name.startsWith(".")).map(i=>i.name).sort();u.sort((i,c)=>i.isDirectory()&&!c.isDirectory()?-1:!i.isDirectory()&&c.isDirectory()?1:i.name.localeCompare(c.name));let x=[...u.map(i=>({name:i.name,isDir:i.isDirectory()})),...h.map(i=>({name:i,isDir:!0,isCollapsed:!0}))];return x.forEach((i,c)=>{let w=c===x.length-1,A=Us.join(e,i.name),b=w?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",C=n+(w?" ":"\u2502 ");if(i.isCollapsed){m+=`${n}${b}${i.name}${a}...
595
595
  `;return}i.isDir?s>t?m+=`${n}${b}${i.name}${a} ...depth exceeded...
596
- `:o(v).length>80?m+=`${n}${b}${i.name}${a} ...80+ files...
596
+ `:o(A).length>80?m+=`${n}${b}${i.name}${a} ...80+ files...
597
597
  `:(m+=`${n}${b}${i.name}${a}
598
- `,m+=Ws(v,t,R,s+1,o,l)):m+=`${n}${b}${i.name}
599
- `}),m};import"@google/genai";var tt=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 a=await fetch(e,t);if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),a.ok||a.status!==429&&a.status<500)return a}catch(a){if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),a.name==="AbortError"||o?.aborted||f===n-1)throw a}o?await new Promise((a,m)=>{let g=setTimeout(()=>{o.removeEventListener("abort",u),a()},Math.min(24e3,s*Math.pow(2,f))),u=()=>{clearTimeout(g),m(new DOMException("The user aborted a request.","AbortError"))};o.addEventListener("abort",u)}):await new Promise(a=>setTimeout(a,Math.min(24e3,s*Math.pow(2,f))))}if(o?.aborted)throw new DOMException("The user aborted a request.","AbortError");let l=await fetch(e,t);return typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),l};async function jo(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 Vo=async function*(e,t,n,s,o,l,f,a,m=1){let g=[];s&&g.push({role:"system",content:s});for(let I of n){let $=I.role==="user"?"user":"assistant",p=[];if(Array.isArray(I.parts)){for(let d of I.parts)if(d.text)p.push({type:"text",text:d.text});else if((d.inlineData||d.inline_data)&&f){let w=d.inlineData||d.inline_data,r=w.mimeType||w.mime_type||"image/jpeg",k=w.data;r.startsWith("image/")&&p.push({type:"image_url",image_url:{url:`data:${r};base64,${k}`}})}}else{let d=I.text||"";d&&p.push({type:"text",text:d})}g.push({role:$,content:p.length===1&&p[0].type==="text"?p[0].text:p})}let u={model:t,messages:g,stream:!0,stream_options:{include_usage:!0},temperature:m},h=Oe("DeepSeek",t,o),i=h!==null?h:o!=="Fast"?{Low:"high",Medium:"high",Standard:"high",High:"max",xHigh:"max"}[o]||"high":null;i&&i!=="disabled"&&i!=="none"&&i!=="false"&&i!==!1?(u.reasoning_effort=i,u.extra_body={thinking:{type:"enabled"}}):u.extra_body={thinking:{type:"disabled"}};let c=await tt("https://api.deepseek.com/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(u),signal:a});if(!c.ok){let I=await c.json().catch(()=>({}));throw new Error(`DeepSeek Error (${c.status}): ${I.error?.message||c.statusText}`)}let T=c.body.getReader(),v=new TextDecoder,b="",R=[],N=null,M=Date.now(),S=!1;for(;;){let{done:I,value:$}=await T.read();if(I){S&&(R.length>0||N)&&(yield{candidates:R.length>0?[{content:{parts:R}}]:[],usageMetadata:N});break}b+=v.decode($,{stream:!0});let p=b.split(`
600
- `);b=p.pop();for(let d of p){let w=d.trim();if(!w||!w.startsWith("data: "))continue;let r=!1;if(w==="data: [DONE]")r=!0;else try{let k=JSON.parse(w.substring(6)),E=k.choices?.[0]?.delta,O=k.usage;if(k.choices?.[0]?.finish_reason&&(r=!0),O&&(N={totalTokenCount:O.total_tokens||O.prompt_tokens+O.completion_tokens,promptTokenCount:O.prompt_tokens||0,candidatesTokenCount:O.completion_tokens||0,cachedContentTokenCount:O.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:O.completion_tokens_details?.reasoning_tokens||0},S=!0),E){let U=E.reasoning_content||null;U&&(R.push({text:U,thought:!0}),S=!0),E.content&&(R.push({text:E.content}),S=!0)}}catch{}if((r||Date.now()-M>=150)&&S&&(yield{candidates:R.length>0?[{content:{parts:[...R]}}]:[],usageMetadata:N},R=[],M=Date.now(),S=!1),r)break}Date.now()-M>=150&&S&&(yield{candidates:R.length>0?[{content:{parts:[...R]}}]:[],usageMetadata:N},R=[],M=Date.now(),S=!1)}};var Ko=async function*(e,t,n,s,o,l,f,a,m=1,g=null){let u=[];s&&u.push({role:"system",content:s});for(let d of n){let w=d.role==="user"?"user":"assistant",r=[];if(Array.isArray(d.parts)){for(let k of d.parts)if(k.text)r.push({type:"text",text:k.text});else if(k.inlineData&&f){let E=k.inlineData.mimeType,O=k.inlineData.data;E.startsWith("image/")&&r.push({type:"image_url",image_url:`data:${E};base64,${O}`})}}else{let k=d.text||"";k&&r.push({type:"text",text:k})}r.length>0&&u.push({role:w,content:r.length===1&&r[0].type==="text"?r[0].text:r})}let h={Fast:"none",Low:"none",Medium:"high",Standard:"high",High:"high",xHigh:"high"},x=`${e.slice(-5)}${g||""}${o}${t}`,i=await jo(x),c={model:t,messages:u,stream:!0,temperature:m,prompt_cache_key:i},T=Oe("Mistral",t,o);T!==null?T&&T!=="none"&&T!=="disabled"&&T!==!1&&(c.reasoning_effort=T):o&&o!=="Fast"&&qn(t)&&(c.reasoning_effort=h[o]||"high");let v=await tt("https://api.mistral.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(c),signal:a});if(!v.ok){let d=await v.text().catch(()=>""),w=v.statusText;try{let r=JSON.parse(d);w=r.error?.message||r.message||JSON.stringify(r.detail||r)}catch{d&&(w=d)}throw new Error(`Mistral Error (${v.status}): ${JSON.stringify(w)}`)}let b=v.body.getReader(),R=new TextDecoder,N="",M=[],S=null,I=Date.now(),$=!1,p=d=>d?typeof d=="string"?xn(d):Array.isArray(d)?d.map(p).filter(Boolean).join(""):typeof d=="object"&&d!==null?typeof d.text=="string"?xn(d.text):typeof d.content=="string"?xn(d.content):typeof d.thinking=="string"?xn(d.thinking):typeof d.reasoning_content=="string"?xn(d.reasoning_content):typeof d.reasoning=="string"?xn(d.reasoning):typeof d.value=="string"?xn(d.value):d.text?p(d.text):d.content?p(d.content):d.thinking?p(d.thinking):d.reasoning_content?p(d.reasoning_content):d.reasoning?p(d.reasoning):d.value?p(d.value):"":xn(String(d)):"";for(;;){let{done:d,value:w}=await b.read();if(d){$&&(M.length>0||S)&&(yield{candidates:M.length>0?[{content:{parts:M}}]:[],usageMetadata:S});break}N+=R.decode(w,{stream:!0});let r=N.split(`
601
- `);N=r.pop();for(let k of r){let E=k.trim();if(!E||!E.startsWith("data: "))continue;let O=!1;if(E==="data: [DONE]")O=!0;else try{let U=JSON.parse(E.substring(6)),P=U.choices?.[0]?.delta,D=U.usage;if(U.choices?.[0]?.finish_reason&&(O=!0),D&&(S={totalTokenCount:D.total_tokens||(D.prompt_tokens||0)+(D.completion_tokens||0),promptTokenCount:D.prompt_tokens||0,candidatesTokenCount:D.completion_tokens||0,cachedContentTokenCount:D.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:D.completion_tokens_details?.reasoning_tokens||0},$=!0),P){let ee=P.thinking||P.reasoning_content||P.reasoning,pe=p(ee);pe&&(M.push({text:pe,thought:!0}),$=!0);let B=P.content||(!P.thinking&&!P.reasoning_content&&!P.reasoning?P.text:null);if(B)if(Array.isArray(B))for(let A of B)if(typeof A=="object"&&A!==null){let Se=A.type==="thinking"||A.type==="reasoning"||!!A.thought,X=p(A);X&&(M.push({text:X,...Se?{thought:!0}:{}}),$=!0)}else{let Se=p(A);Se&&(M.push({text:Se}),$=!0)}else if(typeof B=="object"&&B!==null){let A=B.type==="thinking"||B.type==="reasoning"||!!B.thought,Se=p(B);Se&&(M.push({text:Se,...A?{thought:!0}:{}}),$=!0)}else{let A=p(B);A&&(M.push({text:A}),$=!0)}}}catch{}if((O||Date.now()-I>=150)&&$&&(yield{candidates:M.length>0?[{content:{parts:[...M]}}]:[],usageMetadata:S},M=[],I=Date.now(),$=!1),O)break}Date.now()-I>=150&&$&&(yield{candidates:M.length>0?[{content:{parts:[...M]}}]:[],usageMetadata:S},M=[],I=Date.now(),$=!1)}};var Yo=async function*(e,t,n,s,o,l,f=!1,a,m=1){let g=[];s&&g.push({role:"system",content:s}),n.forEach(X=>{let C=X.role==="model"?"assistant":"user",G=[];Array.isArray(X.parts)&&X.parts.forEach(te=>{if(te.text)G.push({type:"text",text:te.text});else if(te.inlineData&&f){let Y=te.inlineData.mimeType,Xe=te.inlineData.data;Y.startsWith("image/")&&dt(t)&&G.push({type:"image_url",image_url:{url:`data:${Y};base64,${Xe}`}})}}),g.push({role:C,content:G.length===1&&G[0].type==="text"?G[0].text:G})});let u=Oe("NVIDIA",t,o),x=u!==null?u:{Fast:"Fast",Low:"Fast",Medium:"Standard",Standard:"Standard",High:"High",xHigh:"High"}[o]||"High",i=x!=="Fast"&&x!=="none"&&x!=="disabled"&&x!==!1,c=t.includes("kimi"),T=t.includes("gemma"),v=t.includes("deepseek"),b=t.includes("glm"),R=t.includes("mistral"),N=t.includes("minimax"),M=t.includes("gpt"),S=t.includes("qwen"),I=t.includes("nemotron"),$=t.includes("llama-3"),p=t.includes("seed"),d=t.includes("poolside"),w=t.includes("thinkingmachines")||t.includes("muse"),r=$,k=null,E={Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},O={Fast:"64",Low:"64",Medium:"4096",Standard:"4096",High:"16384",xHigh:"16384"},U={Fast:"none",Low:"minimal",Medium:"medium",Standard:"medium",High:"max",xHigh:"max"},P=N||v||d||w?16384:32768;P=process.env.NVIDIA_BASE_URL?1024:P,P=k?1024:P;let D={model:t,messages:g,max_tokens:P,stream:!0,stream_options:{include_usage:!0},temperature:m,...M&&{thinking:E[o]||"high"}};if(!(process.env.NVIDIA_BASE_URL||r||k))if(c)D.chat_template_kwargs={thinking:i};else if(T)D.chat_template_kwargs={enable_thinking:i};else if(v)if(i){let X=x==="High"?"max":"high";D.chat_template_kwargs={thinking:!0,reasoning_effort:X}}else D.chat_template_kwargs={thinking:!1};else b?D.chat_template_kwargs={enable_thinking:i,clear_thinking:!i}:R?D.reasoning_effort=i?"high":"none":N&&t.includes("minimax-m3")?D.chat_template_kwargs={thinking_mode:i?"enabled":"disabled"}:S?D.chat_template_kwargs={enable_thinking:i}:I?x==="High"?D.chat_template_kwargs={enable_thinking:!0}:x==="Standard"?D.chat_template_kwargs={enable_thinking:!0,medium_effort:!0}:D.chat_template_kwargs={enable_thinking:!1}:p?i&&(D.extra_body={thinking_budget:parseInt(O[x]??"4096")}):d?D.chat_template_kwargs={enable_thinking:i}:w&&(D.reasoning_effort=U[x]||"medium");let ee=0,pe=6,B=!1,A=process.env.NVIDIA_BASE_URL||"https://integrate.api.nvidia.com/v1/chat/completions",Se=process.env.NVIDIA_API_KEY&&process.env.NVIDIA_BASE_URL?process.env.NVIDIA_API_KEY:e;for(A.endsWith("/chat/completions")||(A=A.replace(/\/+$/,"")+"/chat/completions");ee<pe;){ee++;try{let X=await tt(A,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Se}`},body:JSON.stringify(D),signal:a});if(!X.ok){let ft=await X.text().catch(()=>""),Qe=X.statusText;try{let Ct=JSON.parse(ft);Qe=Ct.error?.message||Ct.message||JSON.stringify(Ct.detail||Ct)}catch{ft&&(Qe=ft)}let pt=new Error(`NVIDIA API Error (${X.status}): ${Qe}`);throw pt.status=X.status,pt}let C=X.body.getReader(),G=new TextDecoder,te="",Y=[],Xe=null,Ye=Date.now(),Ge=!1;for(;;){let{done:ft,value:Qe}=await C.read();if(ft){Ge&&(Y.length>0||Xe)&&(yield{candidates:Y.length>0?[{content:{parts:Y}}]:[],usageMetadata:Xe},B=!0);break}te+=G.decode(Qe,{stream:!0});let pt=te.split(`
602
- `);te=pt.pop();let Ct=!1;for(let kn of pt){let Yt=kn.trim();if(Yt){if(Yt==="data: [DONE]"){Ct=!0;break}if(Yt.startsWith("data: ")){let ct;try{ct=JSON.parse(Yt.substring(6))}catch{continue}if(ct.error)throw new Error(`NVIDIA Stream Error: ${ct.error.message||JSON.stringify(ct.error)}`);try{let ue=ct.usage;ue&&(Xe={totalTokenCount:ue.total_tokens||ue.prompt_tokens+ue.completion_tokens,promptTokenCount:ue.prompt_tokens||0,candidatesTokenCount:ue.completion_tokens||0,cachedContentTokenCount:ue.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:(ue.completion_tokens_details?.reasoning_tokens||0)+(ue.completion_tokens_details?.thoughts_tokens||0)},Ge=!0);let ge=ct.choices?.[0]?.delta?.reasoning||ct.choices?.[0]?.delta?.reasoning_content||"",ie=ct.choices?.[0]?.delta?.content||"";ge&&(Y.push({text:ge,thought:!0}),Ge=!0),ie&&(Y.push({text:ie}),Ge=!0)}catch{}}}}if((Ct||Date.now()-Ye>=350)&&Ge&&(yield{candidates:Y.length>0?[{content:{parts:[...Y]}}]:[],usageMetadata:Xe},B=!0,Y=[],Ye=Date.now(),Ge=!1),Ct)break}break}catch(X){if(B||ee>=pe)throw X;await new Promise(C=>setTimeout(C,3500))}}},Cr=async function*(e,t){let n=[],s=null,o=!1,l=null,f=i=>{if(n.push(i),s){let c=s;s=null,c()}},a=t.split("/").pop();a=a.replace("llama-3.3","llama-3_3");let m=`https://buildapi.ngc.nvidia.com/v2/predict/queues/models/qc69jvmznzxy/${a}`,g=`https://api.ngc.nvidia.com/v2/predict/queues/models/qc69jvmznzxy/${a}`,u=!1,h=null,x=async()=>{try{let c=await(await Promise.any([m,g].map(async T=>{let v=await fetch(T);if(!v.ok)throw new Error(`HTTP ${v.status}`);return v}))).json();if(c&&c.queues&&c.queues[0]&&typeof c.queues[0].queueDepth=="number"){let T=c.queues[0].queueDepth;u||f({value:{type:"status",content:`Queue ${T||1}`},done:!1})}}catch{}};process.env.NVIDIA_BASE_URL||(x(),h=setInterval(x,5e3)),(async()=>{try{let i=e[Symbol.asyncIterator]();for(;;){let{value:c,done:T}=await i.next();if(T)break;u=!0,h&&(clearInterval(h),h=null),f({value:c,done:!1})}o=!0,f(null)}catch(i){if(l=i,h&&(clearInterval(h),h=null),s){let c=s;s=null,c()}}})();try{for(;;){if(l)throw l;if(n.length>0){let i=n.shift();if(i===null&&o)break;yield i.value}else{if(o)break;await new Promise(i=>{s=i})}}}finally{h&&(clearInterval(h),h=null)}};var qo=async function*(e,t,n,s,o,l,f,a,m=1,g=null){let u=[];s&&u.push({role:"system",content:[{type:"text",text:s}]});for(let E of n){let O=E.role==="user"?"user":"assistant",U=[];if(Array.isArray(E.parts)){for(let P of E.parts)if(P.text)U.push({type:"text",text:P.text});else if(P.inlineData&&f){let D=P.inlineData.mimeType,ee=P.inlineData.data;D.startsWith("image/")?U.push({type:"image_url",image_url:{url:`data:${D};base64,${ee}`}}):U.push({type:"file",file:{filename:P.filename||"file",file_data:`data:${D};base64,${ee}`}})}}else{let P=E.text||"";P&&U.push({type:"text",text:P})}u.push({role:O,content:U.length===1&&U[0].type==="text"?U[0].text:U})}let h={Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},x=["free","nitro","floor","exacto"],i=t,c=null,T=null;if(t.includes(":")){let E=t.split(":");if(E.length>1){let O=E[E.length-1].toLowerCase().trim();(O==="flex"||O==="priority")&&(T=O,E.pop())}if(E.length>1){let O=E[E.length-1].toLowerCase().trim();if(!x.includes(O)){let U=E.pop().trim();U&&(c={only:[U],allow_fallbacks:!1})}}i=E.join(":").trim()}let v=`${e.slice(-5)}${g||""}${o}${i}${T||""}${c?JSON.stringify(c):""}`,b=await jo(v),R={model:i,messages:u,stream:!0,temperature:m,cache_control:{type:"ephemeral"},session_id:b};T&&(R.service_tier=T),c&&(R.provider=c);let N=Oe("OpenRouter",t,o),M=N!==null?N:h[o];M&&M!=="none"&&(N!==null||o!=="Fast")&&(R.reasoning_effort=M);let S=await tt("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(R),signal:a});if(!S.ok){let E=await S.json().catch(()=>({})),O=E.error?.metadata?.raw||E.error?.message||(typeof E.error=="string"?E.error:"")||S.statusText||"Unknown error";throw new Error(`OpenRouter Error (${S.status}): ${O}`)}let I=S.body.getReader(),$=new TextDecoder,p="",d=[],w=null,r=Date.now(),k=!1;for(;;){let{done:E,value:O}=await I.read();if(E){k&&(d.length>0||w)&&(yield{candidates:d.length>0?[{content:{parts:d}}]:[],usageMetadata:w});break}p+=$.decode(O,{stream:!0});let U=p.split(`
603
- `);p=U.pop();for(let P of U){let D=P.trim();if(!D||!D.startsWith("data: "))continue;let ee=!1;if(D==="data: [DONE]")ee=!0;else try{let pe=JSON.parse(D.substring(6));if(pe.error){let Se=pe.error.metadata?.raw||pe.error.message||JSON.stringify(pe.error);throw new Error(`OpenRouter Stream Error: ${Se}`)}let B=pe.choices?.[0]?.delta,A=pe.usage;if(pe.choices?.[0]?.finish_reason&&(ee=!0),A&&(w={totalTokenCount:A.total_tokens||(A.prompt_tokens||0)+(A.completion_tokens||0),promptTokenCount:A.prompt_tokens||0,candidatesTokenCount:A.completion_tokens||0,cachedContentTokenCount:A.prompt_tokens_details?.cached_tokens||A.prompt_tokens_details?.cache_read_input_tokens||A.cache_read_input_tokens||0,thoughtsTokenCount:A.completion_tokens_details?.reasoning_tokens||0},k=!0),B){let Se=B.reasoning||(B.reasoning_details?B.reasoning_details.map(X=>X.text).join(""):null);Se&&(d.push({text:Se,thought:!0}),k=!0),B.content&&(d.push({text:B.content}),k=!0)}}catch(pe){if(pe.message&&pe.message.startsWith("OpenRouter Stream Error:"))throw pe}if((ee||Date.now()-r>=150)&&k&&(yield{candidates:d.length>0?[{content:{parts:[...d]}}]:[],usageMetadata:w},d=[],r=Date.now(),k=!1),ee)break}}};import{Ollama as ka}from"ollama";var Hs=async function*(e,t,n,s,o,l,f,a,m=1,g="Cloud"){let u=[];s&&u.push({role:"system",content:s});for(let p of n){let d=p.role==="user"?"user":"assistant",w="",r=[];if(Array.isArray(p.parts)){w=p.parts.map(k=>k.text||"").filter(Boolean).join(`
604
- `);for(let k of p.parts){let E=k.inlineData||k.inline_data;E&&E.data&&r.push(E.data)}}else w=p.text||"";if(w||r.length>0){let k={role:d,content:w};r.length>0&&(k.images=r),u.push(k)}}let h=g==="Local"||!e||e==="LOCAL",i={host:h?process.env.OLLAMA_HOST||"http://127.0.0.1:11434":process.env.OLLAMA_HOST||"https://ollama.com"};!h&&e&&(i.headers={Authorization:"Bearer "+e});let c=new ka(i),T=[],v=null,b=Date.now(),R=!1,N=Oe("Ollama",t,o),M={Fast:!1,Low:"medium",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},S=N!==null?N==="false"||N===!1?!1:N==="true"||N===!0?!0:N:M[o]!==void 0?M[o]:!0,I={model:t,messages:u,stream:!0,think:S,keep_alive:"10m",options:{temperature:m}},$=await c.chat(I);for await(let p of $){if(a?.aborted)throw new DOMException("The user aborted a request.","AbortError");if(p.message?.thinking&&(T.push({text:p.message.thinking,thought:!0}),R=!0),p.message?.content&&(T.push({text:p.message.content}),R=!0),p.done){let d=p.prompt_cached_count||0;if(!d&&p.prompt_eval_count){let w=p.prompt_eval_duration||0;w>0&&w<5e7&&(d=p.prompt_eval_count)}v={totalTokenCount:(p.prompt_eval_count||0)+(p.eval_count||0),promptTokenCount:p.prompt_eval_count||0,candidatesTokenCount:p.eval_count||0,cachedContentTokenCount:d,thoughtsTokenCount:0},R=!0}(p.done||Date.now()-b>=150&&R)&&(yield{candidates:T.length>0?[{content:{parts:[...T]}}]:[],usageMetadata:v},T=[],b=Date.now(),R=!1)}R&&(T.length>0||v)&&(yield{candidates:T.length>0?[{content:{parts:[...T]}}]:[],usageMetadata:v})};var zo=async function*(e,t,n,s,o,l,f,a,m=1){let g=[];s&&g.push({role:"system",content:s});for(let d of n){let w=d.role==="user"?"user":"assistant",r="";if(Array.isArray(d.parts))for(let k of d.parts)k.text&&(r+=(r?`
605
- `:"")+k.text);else r=d.text||"";g.push({role:w,content:r})}let u=Oe("InferX",t,o),x=u!==null?u:{Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i=t&&t.toLowerCase().includes("qwen3.8-27b")&&u===null,c=t&&(t.toLowerCase().includes("qwen3.8-27b")||t.toLowerCase().includes("qwen3.6-35b-a3b-fp8")),T={model:t,messages:g.filter(d=>d.content&&String(d.content).trim().length>0),stream:!0,stream_options:{include_usage:!0},temperature:m};!i&&x&&(T.stream_options={include_usage:!0},T.reasoning_effort=x);let v=await tt("https://model.inferx.net/endpoints/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(T),signal:a});if(!v.ok){let d=await v.text().catch(()=>""),w="";try{let r=JSON.parse(d);w=r.error?.message||r.error?.detail||r.message||r.detail||(typeof r.error=="string"?r.error:"")||(d&&d!=="{}"?d:"")}catch{w=d}throw(!w||w==="{}")&&(w=v.statusText||"Unknown error"),new Error(`InferX Error (${v.status}): ${w}`)}let b=v.body.getReader(),R=new TextDecoder,N="",M=[],S=null,I=Date.now(),$=!1,p=!0;for(;;){let{done:d,value:w}=await b.read();if(d){$&&(M.length>0||S)&&(yield{candidates:M.length>0?[{content:{parts:M}}]:[],usageMetadata:S});break}N+=R.decode(w,{stream:!0});let r=N.split(`
606
- `);N=r.pop();for(let k of r){let E=k.trim();if(!E||!E.startsWith("data: "))continue;let O=!1;if(E==="data: [DONE]")O=!0;else try{let U=JSON.parse(E.substring(6)),P=U.choices?.[0]?.delta,D=U.usage;if(D&&(S={totalTokenCount:D.total_tokens||(D.prompt_tokens||0)+(D.completion_tokens||0),promptTokenCount:D.prompt_tokens||0,candidatesTokenCount:D.completion_tokens||0,cachedContentTokenCount:D.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:D.completion_tokens_details?.reasoning_tokens||D.reasoning_tokens||0},$=!0),P){let ee=P.reasoning||P.reasoning_content||null;if(ee&&(M.push({text:ee,thought:!0}),$=!0),P.content){let pe=P.content;c&&p&&pe.length>0&&(pe="<think>"+pe,p=!1),M.push({text:pe}),$=!0}}}catch{}if((O||Date.now()-I>=150||S)&&$&&(yield{candidates:M.length>0?[{content:{parts:[...M]}}]:[],usageMetadata:S},M=[],I=Date.now(),$=!1),O)break}Date.now()-I>=150&&$&&(yield{candidates:M.length>0?[{content:{parts:[...M]}}]:[],usageMetadata:S},M=[],I=Date.now(),$=!1)}};var Jo=async function*(e,t,n,s,o,l,f,a,m=1){let g=[];s&&g.push({role:"system",content:s});for(let I of n){let $=I.role==="user"?"user":"assistant",p=[];if(Array.isArray(I.parts)){for(let d of I.parts)if(d.text)p.push({type:"text",text:d.text});else if(d.inlineData&&f){let w=d.inlineData.mimeType,r=d.inlineData.data;w.startsWith("image/")&&p.push({type:"image_url",image_url:{url:`data:${w};base64,${r}`}})}}else{let d=I.text||"";d&&p.push({type:"text",text:d})}g.push({role:$,content:p.length===1&&p[0].type==="text"?p[0].text:p})}let u=Oe("SenseNova",t,o),x=u!==null?u:{Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:g,stream:!0,stream_options:{include_usage:!0},temperature:m};x&&(i.reasoning_effort=x);let c=await tt("https://token.sensenova.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(i),signal:a});if(!c.ok){let I=await c.json().catch(()=>({}));throw new Error(`SenseNova Error (${c.status}): ${I.error?.message||c.statusText}`)}let T=c.body.getReader(),v=new TextDecoder,b="",R=[],N=null,M=Date.now(),S=!1;for(;;){let{done:I,value:$}=await T.read();if(I){S&&(R.length>0||N)&&(yield{candidates:R.length>0?[{content:{parts:R}}]:[],usageMetadata:N});break}b+=v.decode($,{stream:!0});let p=b.split(`
607
- `);b=p.pop();for(let d of p){let w=d.trim();if(!w||!w.startsWith("data: "))continue;let r=!1;if(w==="data: [DONE]")r=!0;else try{let k=JSON.parse(w.substring(6)),E=k.choices?.[0]?.delta,O=k.usage;if(O&&(N={totalTokenCount:O.total_tokens||(O.prompt_tokens||0)+(O.completion_tokens||0),promptTokenCount:O.prompt_tokens||0,candidatesTokenCount:O.completion_tokens||0,cachedContentTokenCount:O.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:O.completion_tokens_details?.reasoning_tokens||O.reasoning_tokens||0},S=!0),E){let U=E.reasoning||E.reasoning_content||null;U&&(R.push({text:U,thought:!0}),S=!0),E.content&&(R.push({text:E.content}),S=!0)}}catch{}if((r||Date.now()-M>=150||N)&&S&&(yield{candidates:R.length>0?[{content:{parts:[...R]}}]:[],usageMetadata:N},R=[],M=Date.now(),S=!1),r)break}Date.now()-M>=150&&S&&(yield{candidates:R.length>0?[{content:{parts:[...R]}}]:[],usageMetadata:N},R=[],M=Date.now(),S=!1)}};var Xo=async function*(e,t,n,s,o,l,f,a,m=1){let g=[];s&&g.push({role:"system",content:s});for(let I of n){let $=I.role==="user"?"user":"assistant",p=[];if(Array.isArray(I.parts)){for(let d of I.parts)if(d.text)p.push({type:"text",text:d.text});else if(d.inlineData&&f){let w=d.inlineData.mimeType,r=d.inlineData.data;w.startsWith("image/")&&p.push({type:"image_url",image_url:{url:`data:${w};base64,${r}`}})}}else{let d=I.text||"";d&&p.push({type:"text",text:d})}g.push({role:$,content:p.length===1&&p[0].type==="text"?p[0].text:p})}let u=Oe("AIHubMix",t,o),x=u!==null?u:{Fast:"minimal",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:g,stream:!0,stream_options:{include_usage:!0},temperature:m};x&&(i.reasoning_effort=x);let c=await tt("https://aihubmix.com/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(i),signal:a});if(!c.ok){let I=await c.json().catch(()=>({}));throw new Error(`AIHubMix Error (${c.status}): ${I.error?.message||c.statusText}`)}let T=c.body.getReader(),v=new TextDecoder,b="",R=[],N=null,M=Date.now(),S=!1;for(;;){let{done:I,value:$}=await T.read();if(I){S&&(R.length>0||N)&&(yield{candidates:R.length>0?[{content:{parts:R}}]:[],usageMetadata:N});break}b+=v.decode($,{stream:!0});let p=b.split(`
608
- `);b=p.pop();for(let d of p){let w=d.trim();if(!w||!w.startsWith("data: "))continue;let r=!1;if(w==="data: [DONE]")r=!0;else try{let k=JSON.parse(w.substring(6)),E=k.choices?.[0]?.delta,O=k.usage;if(k.choices?.[0]?.finish_reason&&(r=!0),O&&(N={totalTokenCount:O.total_tokens||(O.prompt_tokens||0)+(O.completion_tokens||0),promptTokenCount:O.prompt_tokens||0,candidatesTokenCount:O.completion_tokens||0,cachedContentTokenCount:O.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:O.completion_tokens_details?.reasoning_tokens||O.reasoning_tokens||0},S=!0),E){let U=E.reasoning_content||null;U&&(R.push({text:U,thought:!0}),S=!0),E.content&&(R.push({text:E.content}),S=!0)}}catch{}if((r||Date.now()-M>=150)&&S&&(yield{candidates:R.length>0?[{content:{parts:[...R]}}]:[],usageMetadata:N},R=[],M=Date.now(),S=!1),r)break}Date.now()-M>=150&&S&&(yield{candidates:R.length>0?[{content:{parts:[...R]}}]:[],usageMetadata:N},R=[],M=Date.now(),S=!1)}};var Qo=async function*(e,t,n,s,o,l,f,a,m=1){let g=[];s&&g.push({role:"system",content:s});for(let S of n){let I=S.role==="user"?"user":"assistant",$=[];if(Array.isArray(S.parts)){for(let p of S.parts)if(p.text)$.push({type:"text",text:p.text});else if(p.inlineData&&f){let d=p.inlineData.mimeType,w=p.inlineData.data;d.startsWith("image/")&&$.push({type:"image_url",image_url:{url:`data:${d};base64,${w}`}})}}else{let p=S.text||"";p&&$.push({type:"text",text:p})}g.push({role:I,content:$.length===1&&$[0].type==="text"?$[0].text:$})}let u=Oe("Poolside",t,o),h=u!==null?u===!1||u==="false"||u==="none"||u==="Fast":o==="Fast",x={model:t,messages:g,stream:!0,stream_options:{include_usage:!0},temperature:m};h?x.chat_template_kwargs={enable_thinking:!1}:u!==null&&typeof u=="object"?x.chat_template_kwargs=u:x.chat_template_kwargs={enable_thinking:!0};let i=await tt("https://inference.poolside.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(x),signal:a});if(!i.ok){let S=await i.json().catch(()=>({}));throw new Error(`Poolside Error (${i.status}): ${S.error?.message||i.statusText}`)}let c=i.body.getReader(),T=new TextDecoder,v="",b=[],R=null,N=Date.now(),M=!1;for(;;){let{done:S,value:I}=await c.read();if(S){M&&(b.length>0||R)&&(yield{candidates:b.length>0?[{content:{parts:b}}]:[],usageMetadata:R});break}v+=T.decode(I,{stream:!0});let $=v.split(`
609
- `);v=$.pop();for(let p of $){let d=p.trim();if(!d||!d.startsWith("data: "))continue;let w=!1;if(d==="data: [DONE]")w=!0;else try{let r=JSON.parse(d.substring(6)),k=r.choices?.[0]?.delta,E=r.usage;if(r.choices?.[0]?.finish_reason&&(w=!0),E&&(R={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},M=!0),k){let O=k.reasoning_content||k.reasoning||null;O&&(b.push({text:O,thought:!0}),M=!0),k.content&&(b.push({text:k.content}),M=!0)}}catch{}if((w||Date.now()-N>=150)&&M&&(yield{candidates:b.length>0?[{content:{parts:[...b]}}]:[],usageMetadata:R},b=[],N=Date.now(),M=!1),w)break}Date.now()-N>=150&&M&&(yield{candidates:b.length>0?[{content:{parts:[...b]}}]:[],usageMetadata:R},b=[],N=Date.now(),M=!1)}};var Zo=async function*(e,t,n,s,o,l,f,a,m=1){let g=[];s&&g.push({role:"system",content:s});for(let d of n){let w=d.role==="user"?"user":"assistant",r=[];if(Array.isArray(d.parts)){for(let k of d.parts)if(k.text)r.push({type:"text",text:k.text});else if(k.inlineData&&f){let E=k.inlineData.mimeType,O=k.inlineData.data;E.startsWith("image/")&&r.push({type:"image_url",image_url:{url:`data:${E};base64,${O}`}})}}else{let k=d.text||"";k&&r.push({type:"text",text:k})}g.push({role:w,content:r.length===1&&r[0].type==="text"?r[0].text:r})}let u=Oe("9router",t,o)||Oe("9Router",t,o),x=u!==null?u:{Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:g,stream:!0,stream_options:{include_usage:!0},temperature:m};x&&x!=="none"&&(u!==null||o!=="Fast")&&(i.reasoning_effort=x);let c=process.env["9ROUTER_URL"]||process.env.NINEROUTER_URL||"http://127.0.0.1:20128/v1/chat/completions",T={"Content-Type":"application/json"},v=e&&e!=="LOCAL"?e:process.env["9ROUTER_API_KEY"]||"dummy-key";T.Authorization=`Bearer ${v}`;let b=await tt(c,{method:"POST",headers:T,body:JSON.stringify(i),signal:a});if(!b.ok){let d=await b.json().catch(()=>({}));throw new Error(`9router Error (${b.status}): ${d.error?.message||b.statusText}`)}let R=b.body.getReader(),N=new TextDecoder,M="",S=[],I=null,$=Date.now(),p=!1;for(;;){let{done:d,value:w}=await R.read();if(d){p&&(S.length>0||I)&&(yield{candidates:S.length>0?[{content:{parts:S}}]:[],usageMetadata:I});break}M+=N.decode(w,{stream:!0});let r=M.split(`
610
- `);M=r.pop();for(let k of r){let E=k.trim();if(!E||!E.startsWith("data: "))continue;let O=!1;if(E==="data: [DONE]")O=!0;else try{let U=JSON.parse(E.substring(6)),P=U.choices?.[0]?.delta,D=U.usage;if(U.choices?.[0]?.finish_reason&&(O=!0),D&&(I={totalTokenCount:D.total_tokens||(D.prompt_tokens||0)+(D.completion_tokens||0),promptTokenCount:D.prompt_tokens||0,candidatesTokenCount:D.completion_tokens||0,cachedContentTokenCount:D.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:D.completion_tokens_details?.reasoning_tokens||D.reasoning_tokens||0},p=!0),P){let ee=P.reasoning_content||P.reasoning||P.thinking||null;!ee&&Array.isArray(P.reasoning_details)&&P.reasoning_details.length>0&&(ee=P.reasoning_details.map(pe=>typeof pe=="string"?pe:pe?.text||"").filter(Boolean).join("")),ee&&(S.push({text:ee,thought:!0}),p=!0),P.content&&(S.push({text:P.content}),p=!0)}}catch{}if((O||Date.now()-$>=150)&&p&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:I},S=[],$=Date.now(),p=!1),O)break}Date.now()-$>=150&&p&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:I},S=[],$=Date.now(),p=!1)}};var es=async function*(e,t,n,s,o,l,f,a,m=1){let g=[];s&&g.push({role:"system",content:s});for(let d of n){let w=d.role==="user"?"user":"assistant",r=[];if(Array.isArray(d.parts)){for(let k of d.parts)if(k.text)r.push({type:"text",text:k.text});else if(k.inlineData&&f){let E=k.inlineData.mimeType,O=k.inlineData.data;E.startsWith("image/")&&r.push({type:"image_url",image_url:{url:`data:${E};base64,${O}`}})}}else{let k=d.text||"";k&&r.push({type:"text",text:k})}g.push({role:w,content:r.length===1&&r[0].type==="text"?r[0].text:r})}let u=Oe("ExpLabs",t,o),x=u!==null?u:{Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:g,stream:!0,stream_options:{include_usage:!0},temperature:m};x&&(i.reasoning_effort=x);let c=process.env.EXPLABS_URL||process.env.EXPERIENTIALLABS_URL||"https://api.experientiallabs.ai/v1/chat/completions",T={"Content-Type":"application/json"},v=e||process.env.EXPLABS_API_KEY||process.env.EXPERIENTIALLABS_API_KEY||"";T.Authorization=`Bearer ${v}`;let b=await tt(c,{method:"POST",headers:T,body:JSON.stringify(i),signal:a});if(!b.ok){let d=await b.json().catch(()=>({}));throw new Error(`Experiential Labs Error (${b.status}): ${d.error?.message||d.message||b.statusText}`)}let R=b.body.getReader(),N=new TextDecoder,M="",S=[],I=null,$=Date.now(),p=!1;for(;;){let{done:d,value:w}=await R.read();if(d){p&&(S.length>0||I)&&(yield{candidates:S.length>0?[{content:{parts:S}}]:[],usageMetadata:I});break}M+=N.decode(w,{stream:!0});let r=M.split(`
611
- `);M=r.pop();for(let k of r){let E=k.trim();if(!E||!E.startsWith("data: "))continue;let O=!1;if(E==="data: [DONE]")O=!0;else try{let U=JSON.parse(E.substring(6)),P=U.choices?.[0]?.delta,D=U.usage;if(D&&(I={totalTokenCount:D.total_tokens||(D.prompt_tokens||0)+(D.completion_tokens||0),promptTokenCount:D.prompt_tokens||0,candidatesTokenCount:D.completion_tokens||0,cachedContentTokenCount:D.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:D.completion_tokens_details?.reasoning_tokens||D.reasoning_tokens||0},p=!0),P){let ee=P.reasoning_content||P.reasoning||null;!ee&&Array.isArray(P.reasoning_details)&&P.reasoning_details.length>0&&(ee=P.reasoning_details.map(pe=>pe.text||"").filter(Boolean).join("")),ee&&(S.push({text:ee,thought:!0}),p=!0),P.content&&(S.push({text:P.content}),p=!0)}}catch{}if((O||Date.now()-$>=150)&&p&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:I},S=[],$=Date.now(),p=!1),O)break}Date.now()-$>=150&&p&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:I},S=[],$=Date.now(),p=!1)}};var Gs=async function*(e,t,n,s,o,l,f,a,m=1){let g=[];s&&g.push({role:"system",content:s});for(let d of n){let w=d.role==="user"?"user":"assistant",r=[];if(Array.isArray(d.parts)){for(let k of d.parts)if(k.text)r.push({type:"text",text:k.text});else if(k.inlineData&&f){let E=k.inlineData.mimeType,O=k.inlineData.data;E.startsWith("image/")&&r.push({type:"image_url",image_url:{url:`data:${E};base64,${O}`}})}}else{let k=d.text||"";k&&r.push({type:"text",text:k})}g.push({role:w,content:r.length===1&&r[0].type==="text"?r[0].text:r})}let u=Oe("TokenHarbor",t,o),x=u!==null?u:{Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:g,stream:!0,stream_options:{include_usage:!0},temperature:m};x&&(i.reasoning_effort=x);let c=process.env.TOKENHARBOR_URL||process.env.TOKEN_HARBOR_URL||"https://tokenharbor.ai/v1/chat/completions",T={"Content-Type":"application/json","X-Title":"Flux-Flow","User-Agent":"Flux-Flow","HTTP-Referer":"https://fluxflow-cli.onrender.com/"},v=e||process.env.TOKENHARBOR_API_KEY||process.env.TOKEN_HARBOR_API_KEY||"";T.Authorization=`Bearer ${v}`;let b=await tt(c,{method:"POST",headers:T,body:JSON.stringify(i),signal:a});if(!b.ok){let d=await b.json().catch(()=>({}));throw new Error(`Token Harbor Error (${b.status}): ${d.error?.message||d.message||b.statusText}`)}let R=b.body.getReader(),N=new TextDecoder,M="",S=[],I=null,$=Date.now(),p=!1;for(;;){let{done:d,value:w}=await R.read();if(d){p&&(S.length>0||I)&&(yield{candidates:S.length>0?[{content:{parts:S}}]:[],usageMetadata:I});break}M+=N.decode(w,{stream:!0});let r=M.split(`
612
- `);M=r.pop();for(let k of r){let E=k.trim();if(!E||!E.startsWith("data: "))continue;let O=!1;if(E==="data: [DONE]")O=!0;else try{let U=JSON.parse(E.substring(6)),P=U.choices?.[0]?.delta,D=U.usage;if(D&&(I={totalTokenCount:D.total_tokens||(D.prompt_tokens||0)+(D.completion_tokens||0),promptTokenCount:D.prompt_tokens||0,candidatesTokenCount:D.completion_tokens||0,cachedContentTokenCount:D.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:D.completion_tokens_details?.reasoning_tokens||D.reasoning_tokens||0},p=!0),P){let ee=P.reasoning_content||P.reasoning||null;!ee&&Array.isArray(P.reasoning_details)&&P.reasoning_details.length>0&&(ee=P.reasoning_details.map(pe=>pe.text||"").filter(Boolean).join("")),ee&&(S.push({text:ee,thought:!0}),p=!0),P.content&&(S.push({text:P.content}),p=!0)}}catch{}if((O||Date.now()-$>=150)&&p&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:I},S=[],$=Date.now(),p=!1),O)break}Date.now()-$>=150&&p&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:I},S=[],$=Date.now(),p=!1)}};var js=async function*(e,t,n,s,o,l,f,a,m=1){let g=[];s&&g.push({role:"system",content:s});for(let d of n){let w=d.role==="user"?"user":"assistant",r=[];if(Array.isArray(d.parts)){for(let k of d.parts)if(k.text)r.push({type:"text",text:k.text});else if(k.inlineData&&f){let E=k.inlineData.mimeType,O=k.inlineData.data;E.startsWith("image/")&&r.push({type:"image_url",image_url:{url:`data:${E};base64,${O}`}})}}else{let k=d.text||"";k&&r.push({type:"text",text:k})}g.push({role:w,content:r.length===1&&r[0].type==="text"?r[0].text:r})}let u=Oe("APInex",t,o),x=u!==null?u:{Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:g,stream:!0,stream_options:{include_usage:!0},temperature:m};x&&(i.reasoning_effort=x);let c=process.env.APINEX_URL||"https://api.apinex.bond/v1/chat/completions",T={"Content-Type":"application/json","X-Title":"Flux-Flow","User-Agent":"Flux-Flow","HTTP-Referer":"https://fluxflow-cli.onrender.com/"},v=e||process.env.APINEX_API_KEY||"";T.Authorization=`Bearer ${v}`;let b=await tt(c,{method:"POST",headers:T,body:JSON.stringify(i),signal:a});if(!b.ok){let d=await b.json().catch(()=>({}));throw new Error(`APInex Error (${b.status}): ${d.error?.message||d.message||b.statusText}`)}let R=b.body.getReader(),N=new TextDecoder,M="",S=[],I=null,$=Date.now(),p=!1;for(;;){let{done:d,value:w}=await R.read();if(d){p&&(S.length>0||I)&&(yield{candidates:S.length>0?[{content:{parts:S}}]:[],usageMetadata:I});break}M+=N.decode(w,{stream:!0});let r=M.split(`
613
- `);M=r.pop();for(let k of r){let E=k.trim();if(!E||!E.startsWith("data: "))continue;let O=!1;if(E==="data: [DONE]")O=!0;else try{let U=JSON.parse(E.substring(6)),P=U.choices?.[0]?.delta,D=U.usage;if(D&&(I={totalTokenCount:D.total_tokens||(D.prompt_tokens||0)+(D.completion_tokens||0),promptTokenCount:D.prompt_tokens||0,candidatesTokenCount:D.completion_tokens||0,cachedContentTokenCount:D.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:D.completion_tokens_details?.reasoning_tokens||D.reasoning_tokens||0},p=!0),P){let ee=P.reasoning_content||P.reasoning||null;!ee&&Array.isArray(P.reasoning_details)&&P.reasoning_details.length>0&&(ee=P.reasoning_details.map(pe=>pe.text||"").filter(Boolean).join("")),ee&&(S.push({text:ee,thought:!0}),p=!0),P.content&&(S.push({text:P.content}),p=!0)}}catch{}if((O||Date.now()-$>=150)&&p&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:I},S=[],$=Date.now(),p=!1),O)break}Date.now()-$>=150&&p&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:I},S=[],$=Date.now(),p=!1)}};var wa=/```[\s\S]*?```/g,Ta=/```[\s\S]*$/g,Sa=/`[^`]+`/g,_a=/^\|.*\|$/gm,Ea=/^[^\w]+|[^\w]+$/g,Aa=/[^a-z0-9]/gi,po=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,Ca=/\[\s*(?:tool:functions\.|agent:generalist\.)([a-z0-9_]+)\s*\(/gi,va=/(?:path|targetFile|TargetFile|directory|keyword|id|taskId|title|task)\s*=\s*\\?["']?([^\\"' \),]+)/,Nn=/["']/g,vr=/\\/g,Ra=/<\|channel>thought/gi,Ma=/<channel\|>/gi,Ia=e=>typeof e!="string"?e:e.replace(Ra,"<think>").replace(Ma,"</think>"),Kd=/^\s*(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\]|$)/i,Da=(e,t)=>{let n=!1;for(let s=0;s<t;s++)e[s]==="`"&&(n=!n);return n},Oa=e=>{let t=/(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\])/gi,n;for(;(n=t.exec(e))!==null;)if(!Da(e,n.index))return{index:n.index,length:n[0].length};return{index:-1,length:0}},Vs=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=Oa(s);if(o.index!==-1){let l=n+o.index+o.length;return{fullBlock:e.substring(0,l),innerContent:s.substring(0,o.index),remainingText:e.substring(l)}}return{fullBlock:e,innerContent:s,remainingText:""}},Kt=e=>{if(!e||typeof e!="string")return e;let t=Vs(e);return t?t.remainingText.trimStart():e};var Pr=/`[^`]*`/g,$r=/`[^`]*$/,Rr=/<\|\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,La=/"([^"]+)"\s*:\s*(?:"([^"]*)"|(\d+)|true|false|null)/g,Mr=/<\|\s*tool_calls_section_begin\s*\|>/gi,Ir=/<\|\s*tool_calls_section_end\s*\|>/gi,Pa=/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi;var Dr=e=>!e||typeof e!="string"?e:e.replace(/(```[\s\S]*?```|`[^`]*`)|(<(?:\w+)(?:[^>]*)>\r?\n?|\r?\n?<\/\w+(?:[^>]*)>)/gi,(t,n)=>n||""),Nr=e=>{if(!e||typeof e!="string")return e;let t=yo(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()},Ys=null,ts={},Fn={key:null,value:null},Vt=e=>e&&e.replace(/(?:(\x1b\[\d+m))?([✔✘✖🔍📖→➕↻↷•🛇])(?:(\x1b\[\d+m))?\s*\b(Clicked|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,l)=>`${n||""}${s}${o||""} \x1B[95m${l}\x1B[0m`),$a=async(e,t=8,n=1e3,s=8e3,o=null)=>{let l=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."||(l++,l>=t))throw f;let a=Math.min(n*Math.pow(2,l-1),s);await new Promise((m,g)=>{let u=setTimeout(m,a);o&&o.addEventListener("abort",()=>{clearTimeout(u),g(new DOMException("The user aborted a request.","AbortError"))})})}}},wt=!1;var Na=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,l,f)=>{let a=o.fullText||o.text||"";if(o.role==="user"&&l<f.length-1)if(a.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")){let m=a.indexOf("**CONTEXT SUMMARY OF PREVIOUS TURNS");if(m!==-1){let u=a.substring(0,m).lastIndexOf("[SYSTEM METADATA]");u!==-1?a=a.substring(u).trim():a=a.substring(m).trim()}}else{let m=a.lastIndexOf("[USER]"),g=a.lastIndexOf("[USER PROMPT]");m!==-1?a=a.substring(m+6).trim():g!==-1&&(a=a.substring(g).trim())}return{...o,text:a}}),n=[],s=0;for(;s<t.length;){let o=t[s];if(o.role==="user")n.push(o),s++;else{let l=[];for(;s<t.length&&t[s].role!=="user";)l.push(t[s]),s++;let f=[],a=[],m=!1,g=()=>{f.length>0&&(n.push({role:"agent",text:"combined"}),f=[]),a.length>0&&(n.push({role:"system",text:"combined"}),a=[]),m=!1};l.forEach(u=>{let h=u.role==="system"&&(u.text?.startsWith("[TOOL RESULT]")||u.text?.startsWith("SUCCESS:")||u.text?.startsWith("ERROR:")||u.fullText?.startsWith("[TOOL RESULT]")||u.fullText?.startsWith("SUCCESS:")||u.fullText?.startsWith("ERROR:")),x=u.fullText||u.text||"",i=x.trim();if(!(!i&&!u.binaryPart)){if(h)a.push(i);else if(u.role==="agent"){!m&&a.length>0&&g();let c=x.endsWith(`
614
- `),T=i.toLowerCase().includes("tool:functions.")||i.toLowerCase().includes("agent:generalist.");f.push(i),T&&c?m=!0:m=!1}}}),g()}}return n.length},Fa=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),Yd=()=>{wt=!0},qd=()=>wt,Ks={write_file:"Writing",update_file:"Editing",read_folder:"Reading",view_file:"Reading",exec_command:"Executing Command",web_search:"Searching",web_scrape:"Reading",memory:"Updating Memory",search_keyword:"Searching",file_map:"Generating Map",ask:"User Input",write_pdf:"Creating",write_docx:"Creating",generate_image:"Generating",todo:"Planning",Todo:"Planning",goal:"Planning",Goal:"Planning",invoke_sync:"Sub-Agent Working",invoke:"Starting Agent",get_progress:"Checking Progress",cancel:"Cancelling",await:"Waiting",EmergencyRollback:"Don't Panic. Lookin' into it",answer:"Answering Sub-Agent",Answer:"Answering Sub-Agent",steer:"Steering Sub-Agent",Steer:"Steering Sub-Agent",Click:"Clicking",click:"Clicking",Drag:"Dragging",drag:"Dragging",Scroll:"Scrolling",scroll:"Scrolling",KeyboardTyping:"Typing",keyboard_typing:"Typing",KeyPress:"Pressing Key",key_press:"Pressing Key",RecaptureScreen:"Recapturing Screen",recapture_screen:"Recapturing Screen"},Bn=(e,t)=>{try{let n=Z(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.path||n.targetFile||n.TargetFile||n.directory;return o?J.basename(o.replace(/["']/g,"").replace(/\\/g,"/")):null}catch{return null}},qs=e=>e?new Lr({apiKey:e}):Ys,zd=async(e,t,n,s,o={})=>{let{onStatus:a,onMemoryUpdated:m,onBackgroundIncrement:g}=o,{profile:u,thinkingLevel:h,mode:x,janitorModel:i,chatId:c,systemSettings:T,sessionStats:v,aiProvider:b="Google",apiKey:R}=e,N=process.env.NVIDIA_BASE_URL||b==="Ollama"||b==="InferX"||b==="SenseNova"||b==="AIHubMix"||b==="Poolside"||b==="9router"||b==="ExpLabs"||b==="ExperientialLabs"?!1:T?.memory!==!1,S=Et(Pn,[]).map(C=>`- [${C.id}]: ${C.memory}`).join(`
615
- `),I=s.slice(0,-1).filter(C=>C.text&&!C.text.includes("[TOOL RESULT]")&&!C.text.includes("OBSERVATION:")&&!C.text.startsWith("[TERMINAL_RECORD]")&&!C.isTerminalRecord&&!C.isMeta&&!C.isLogo&&!String(C.id).startsWith("welcome")&&!String(C.id).startsWith("logo")).slice(-14).map(C=>{let G=Kt(Fa(C.text)).replace(/\[tool:functions\..*?\]/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[METADATA \(PRIORITY: DYNAMIC\)\] Time: ([^|\n]+)/g,(Ye,Ge)=>`[METADATA (PRIORITY: DYNAMIC)] Time: ${Ge.replace(/:\d{2}/g,"")}`).replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[TOOL RESULTS\]/g,"").replace(/\[tool results\]/g,"").replace(/\r?\n\r?\n/g,`
598
+ `,m+=Ws(A,t,C,s+1,o,l)):m+=`${n}${b}${i.name}
599
+ `}),m};import"@google/genai";var nt=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 a=await fetch(e,t);if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),a.ok||a.status!==429&&a.status<500)return a}catch(a){if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),a.name==="AbortError"||o?.aborted||f===n-1)throw a}o?await new Promise((a,m)=>{let g=setTimeout(()=>{o.removeEventListener("abort",u),a()},Math.min(24e3,s*Math.pow(2,f))),u=()=>{clearTimeout(g),m(new DOMException("The user aborted a request.","AbortError"))};o.addEventListener("abort",u)}):await new Promise(a=>setTimeout(a,Math.min(24e3,s*Math.pow(2,f))))}if(o?.aborted)throw new DOMException("The user aborted a request.","AbortError");let l=await fetch(e,t);return typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),l};async function jo(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 Vo=async function*(e,t,n,s,o,l,f,a,m=1){let g=[];s&&g.push({role:"system",content:s});for(let M of n){let $=M.role==="user"?"user":"assistant",p=[];if(Array.isArray(M.parts)){for(let d of M.parts)if(d.text)p.push({type:"text",text:d.text});else if((d.inlineData||d.inline_data)&&f){let T=d.inlineData||d.inline_data,r=T.mimeType||T.mime_type||"image/jpeg",k=T.data;r.startsWith("image/")&&p.push({type:"image_url",image_url:{url:`data:${r};base64,${k}`}})}}else{let d=M.text||"";d&&p.push({type:"text",text:d})}g.push({role:$,content:p.length===1&&p[0].type==="text"?p[0].text:p})}let u={model:t,messages:g,stream:!0,stream_options:{include_usage:!0},temperature:m},h=Ue("DeepSeek",t,o),i=h!==null?h:o!=="Fast"?{Low:"low",Medium:"high",Standard:"high",High:"max",xHigh:"max"}[o]||"high":null;i&&i!=="disabled"&&i!=="none"&&i!=="false"&&i!==!1?(u.reasoning_effort=i,u.extra_body={thinking:{type:"enabled"}}):u.extra_body={thinking:{type:"disabled"}};let c=await nt("https://api.deepseek.com/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(u),signal:a});if(!c.ok){let M=await c.json().catch(()=>({}));throw new Error(`DeepSeek Error (${c.status}): ${M.error?.message||c.statusText}`)}let w=c.body.getReader(),A=new TextDecoder,b="",C=[],N=null,R=Date.now(),_=!1;for(;;){let{done:M,value:$}=await w.read();if(M){_&&(C.length>0||N)&&(yield{candidates:C.length>0?[{content:{parts:C}}]:[],usageMetadata:N});break}b+=A.decode($,{stream:!0});let p=b.split(`
600
+ `);b=p.pop();for(let d of p){let T=d.trim();if(!T||!T.startsWith("data: "))continue;let r=!1;if(T==="data: [DONE]")r=!0;else try{let k=JSON.parse(T.substring(6)),E=k.choices?.[0]?.delta,O=k.usage;if(k.choices?.[0]?.finish_reason&&(r=!0),O&&(N={totalTokenCount:O.total_tokens||O.prompt_tokens+O.completion_tokens,promptTokenCount:O.prompt_tokens||0,candidatesTokenCount:O.completion_tokens||0,cachedContentTokenCount:O.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:O.completion_tokens_details?.reasoning_tokens||0},_=!0),E){let H=E.reasoning_content||null;H&&(C.push({text:H,thought:!0}),_=!0),E.content&&(C.push({text:E.content}),_=!0)}}catch{}if((r||Date.now()-R>=150)&&_&&(yield{candidates:C.length>0?[{content:{parts:[...C]}}]:[],usageMetadata:N},C=[],R=Date.now(),_=!1),r)break}Date.now()-R>=150&&_&&(yield{candidates:C.length>0?[{content:{parts:[...C]}}]:[],usageMetadata:N},C=[],R=Date.now(),_=!1)}};var Ko=async function*(e,t,n,s,o,l,f,a,m=1,g=null){let u=[];s&&u.push({role:"system",content:s});for(let d of n){let T=d.role==="user"?"user":"assistant",r=[];if(Array.isArray(d.parts)){for(let k of d.parts)if(k.text)r.push({type:"text",text:k.text});else if(k.inlineData&&f){let E=k.inlineData.mimeType,O=k.inlineData.data;E.startsWith("image/")&&r.push({type:"image_url",image_url:`data:${E};base64,${O}`})}}else{let k=d.text||"";k&&r.push({type:"text",text:k})}r.length>0&&u.push({role:T,content:r.length===1&&r[0].type==="text"?r[0].text:r})}let h={Fast:"none",Low:"none",Medium:"high",Standard:"high",High:"high",xHigh:"high"},x=`${e.slice(-5)}${g||""}${o}${t}`,i=await jo(x),c={model:t,messages:u,stream:!0,temperature:m,prompt_cache_key:i},w=Ue("Mistral",t,o);w!==null&&w!=="none"?w&&w!=="none"&&w!=="disabled"&&w!==!1&&(c.reasoning_effort=w):o&&h[o]!=="none"&&(c.reasoning_effort=h[o]||"high");let A=await nt("https://api.mistral.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(c),signal:a});if(!A.ok){let d=await A.text().catch(()=>""),T=A.statusText;try{let r=JSON.parse(d);T=r.error?.message||r.message||JSON.stringify(r.detail||r)}catch{d&&(T=d)}throw new Error(`Mistral Error (${A.status}): ${JSON.stringify(T)}`)}let b=A.body.getReader(),C=new TextDecoder,N="",R=[],_=null,M=Date.now(),$=!1,p=d=>d?typeof d=="string"?xn(d):Array.isArray(d)?d.map(p).filter(Boolean).join(""):typeof d=="object"&&d!==null?typeof d.text=="string"?xn(d.text):typeof d.content=="string"?xn(d.content):typeof d.thinking=="string"?xn(d.thinking):typeof d.reasoning_content=="string"?xn(d.reasoning_content):typeof d.reasoning=="string"?xn(d.reasoning):typeof d.value=="string"?xn(d.value):d.text?p(d.text):d.content?p(d.content):d.thinking?p(d.thinking):d.reasoning_content?p(d.reasoning_content):d.reasoning?p(d.reasoning):d.value?p(d.value):"":xn(String(d)):"";for(;;){let{done:d,value:T}=await b.read();if(d){$&&(R.length>0||_)&&(yield{candidates:R.length>0?[{content:{parts:R}}]:[],usageMetadata:_});break}N+=C.decode(T,{stream:!0});let r=N.split(`
601
+ `);N=r.pop();for(let k of r){let E=k.trim();if(!E||!E.startsWith("data: "))continue;let O=!1;if(E==="data: [DONE]")O=!0;else try{let H=JSON.parse(E.substring(6)),P=H.choices?.[0]?.delta,D=H.usage;if(H.choices?.[0]?.finish_reason&&(O=!0),D&&(_={totalTokenCount:D.total_tokens||(D.prompt_tokens||0)+(D.completion_tokens||0),promptTokenCount:D.prompt_tokens||0,candidatesTokenCount:D.completion_tokens||0,cachedContentTokenCount:D.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:D.completion_tokens_details?.reasoning_tokens||0},$=!0),P){let J=P.thinking||P.reasoning_content||P.reasoning,fe=p(J);fe&&(R.push({text:fe,thought:!0}),$=!0);let q=P.content||(!P.thinking&&!P.reasoning_content&&!P.reasoning?P.text:null);if(q)if(Array.isArray(q))for(let xe of q)if(typeof xe=="object"&&xe!==null){let ve=xe.type==="thinking"||xe.type==="reasoning"||!!xe.thought,B=p(xe);B&&(R.push({text:B,...ve?{thought:!0}:{}}),$=!0)}else{let ve=p(xe);ve&&(R.push({text:ve}),$=!0)}else if(typeof q=="object"&&q!==null){let xe=q.type==="thinking"||q.type==="reasoning"||!!q.thought,ve=p(q);ve&&(R.push({text:ve,...xe?{thought:!0}:{}}),$=!0)}else{let xe=p(q);xe&&(R.push({text:xe}),$=!0)}}}catch{}if((O||Date.now()-M>=150)&&$&&(yield{candidates:R.length>0?[{content:{parts:[...R]}}]:[],usageMetadata:_},R=[],M=Date.now(),$=!1),O)break}Date.now()-M>=150&&$&&(yield{candidates:R.length>0?[{content:{parts:[...R]}}]:[],usageMetadata:_},R=[],M=Date.now(),$=!1)}};var Yo=async function*(e,t,n,s,o,l,f=!1,a,m=1){let g=[];s&&g.push({role:"system",content:s}),n.forEach(B=>{let I=B.role==="model"?"assistant":"user",Fe=[];Array.isArray(B.parts)&&B.parts.forEach(te=>{if(te.text)Fe.push({type:"text",text:te.text});else if(te.inlineData&&f){let v=te.inlineData.mimeType,K=te.inlineData.data;v.startsWith("image/")&&ft(t)&&Fe.push({type:"image_url",image_url:{url:`data:${v};base64,${K}`}})}}),g.push({role:I,content:Fe.length===1&&Fe[0].type==="text"?Fe[0].text:Fe})});let u=Ue("NVIDIA",t,o),x=u!==null?u:{Fast:"Fast",Low:"Fast",Medium:"Standard",Standard:"Standard",High:"High",xHigh:"High"}[o]||"High",i=x!=="Fast"&&x!=="none"&&x!=="disabled"&&x!==!1,c=t.includes("kimi"),w=t.includes("gemma"),A=t.includes("deepseek"),b=t.includes("glm"),C=t.includes("mistral"),N=t.includes("minimax"),R=t.includes("gpt"),_=t.includes("qwen"),M=t.includes("nemotron"),$=t.includes("llama-3"),p=t.includes("seed"),d=t.includes("poolside"),T=t.includes("thinkingmachines")||t.includes("muse"),r=$,k=null,E={Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},O={Fast:"64",Low:"64",Medium:"4096",Standard:"4096",High:"16384",xHigh:"16384"},H={Fast:"none",Low:"minimal",Medium:"medium",Standard:"medium",High:"max",xHigh:"max"},P=N||A||d||T?16384:32768;P=process.env.NVIDIA_BASE_URL?1024:P,P=k?1024:P;let D={model:t,messages:g,max_tokens:P,stream:!0,stream_options:{include_usage:!0},temperature:m,...R&&{thinking:E[o]||"high"}};if(!(process.env.NVIDIA_BASE_URL||r||k))if(c)D.chat_template_kwargs={thinking:i};else if(w)D.chat_template_kwargs={enable_thinking:i};else if(A)if(i){let B=x==="High"?"max":"high";D.chat_template_kwargs={thinking:!0,reasoning_effort:B}}else D.chat_template_kwargs={thinking:!1};else b?D.chat_template_kwargs={enable_thinking:i,clear_thinking:!i}:C?D.reasoning_effort=i?"high":"none":N&&t.includes("minimax-m3")?D.chat_template_kwargs={thinking_mode:i?"enabled":"disabled"}:_?D.chat_template_kwargs={enable_thinking:i}:M?x==="High"?D.chat_template_kwargs={enable_thinking:!0}:x==="Standard"?D.chat_template_kwargs={enable_thinking:!0,medium_effort:!0}:D.chat_template_kwargs={enable_thinking:!1}:p?i&&(D.extra_body={thinking_budget:parseInt(O[x]??"4096")}):d?D.chat_template_kwargs={enable_thinking:i}:T&&(D.reasoning_effort=H[x]||"medium");let J=0,fe=6,q=!1,xe=process.env.NVIDIA_BASE_URL||"https://integrate.api.nvidia.com/v1/chat/completions",ve=process.env.NVIDIA_API_KEY&&process.env.NVIDIA_BASE_URL?process.env.NVIDIA_API_KEY:e;for(xe.endsWith("/chat/completions")||(xe=xe.replace(/\/+$/,"")+"/chat/completions");J<fe;){J++;try{let B=await nt(xe,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${ve}`},body:JSON.stringify(D),signal:a});if(!B.ok){let Be=await B.text().catch(()=>""),Ee=B.statusText;try{let Ct=JSON.parse(Be);Ee=Ct.error?.message||Ct.message||JSON.stringify(Ct.detail||Ct)}catch{Be&&(Ee=Be)}let pt=new Error(`NVIDIA API Error (${B.status}): ${Ee}`);throw pt.status=B.status,pt}let I=B.body.getReader(),Fe=new TextDecoder,te="",v=[],K=null,We=Date.now(),ue=!1;for(;;){let{done:Be,value:Ee}=await I.read();if(Be){ue&&(v.length>0||K)&&(yield{candidates:v.length>0?[{content:{parts:v}}]:[],usageMetadata:K},q=!0);break}te+=Fe.decode(Ee,{stream:!0});let pt=te.split(`
602
+ `);te=pt.pop();let Ct=!1;for(let kn of pt){let Yt=kn.trim();if(Yt){if(Yt==="data: [DONE]"){Ct=!0;break}if(Yt.startsWith("data: ")){let dt;try{dt=JSON.parse(Yt.substring(6))}catch{continue}if(dt.error)throw new Error(`NVIDIA Stream Error: ${dt.error.message||JSON.stringify(dt.error)}`);try{let ge=dt.usage;ge&&(K={totalTokenCount:ge.total_tokens||ge.prompt_tokens+ge.completion_tokens,promptTokenCount:ge.prompt_tokens||0,candidatesTokenCount:ge.completion_tokens||0,cachedContentTokenCount:ge.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:(ge.completion_tokens_details?.reasoning_tokens||0)+(ge.completion_tokens_details?.thoughts_tokens||0)},ue=!0);let me=dt.choices?.[0]?.delta?.reasoning||dt.choices?.[0]?.delta?.reasoning_content||"",se=dt.choices?.[0]?.delta?.content||"";me&&(v.push({text:me,thought:!0}),ue=!0),se&&(v.push({text:se}),ue=!0)}catch{}}}}if((Ct||Date.now()-We>=350)&&ue&&(yield{candidates:v.length>0?[{content:{parts:[...v]}}]:[],usageMetadata:K},q=!0,v=[],We=Date.now(),ue=!1),Ct)break}break}catch(B){if(q||J>=fe)throw B;await new Promise(I=>setTimeout(I,3500))}}},Cr=async function*(e,t){let n=[],s=null,o=!1,l=null,f=i=>{if(n.push(i),s){let c=s;s=null,c()}},a=t.split("/").pop();a=a.replace("llama-3.3","llama-3_3");let m=`https://buildapi.ngc.nvidia.com/v2/predict/queues/models/qc69jvmznzxy/${a}`,g=`https://api.ngc.nvidia.com/v2/predict/queues/models/qc69jvmznzxy/${a}`,u=!1,h=null,x=async()=>{try{let c=await(await Promise.any([m,g].map(async w=>{let A=await fetch(w);if(!A.ok)throw new Error(`HTTP ${A.status}`);return A}))).json();if(c&&c.queues&&c.queues[0]&&typeof c.queues[0].queueDepth=="number"){let w=c.queues[0].queueDepth;u||f({value:{type:"status",content:`Queue ${w||1}`},done:!1})}}catch{}};process.env.NVIDIA_BASE_URL||(x(),h=setInterval(x,5e3)),(async()=>{try{let i=e[Symbol.asyncIterator]();for(;;){let{value:c,done:w}=await i.next();if(w)break;u=!0,h&&(clearInterval(h),h=null),f({value:c,done:!1})}o=!0,f(null)}catch(i){if(l=i,h&&(clearInterval(h),h=null),s){let c=s;s=null,c()}}})();try{for(;;){if(l)throw l;if(n.length>0){let i=n.shift();if(i===null&&o)break;yield i.value}else{if(o)break;await new Promise(i=>{s=i})}}}finally{h&&(clearInterval(h),h=null)}};var qo=async function*(e,t,n,s,o,l,f,a,m=1,g=null){let u=[];s&&u.push({role:"system",content:[{type:"text",text:s}]});for(let E of n){let O=E.role==="user"?"user":"assistant",H=[];if(Array.isArray(E.parts)){for(let P of E.parts)if(P.text)H.push({type:"text",text:P.text});else if(P.inlineData&&f){let D=P.inlineData.mimeType,J=P.inlineData.data;D.startsWith("image/")?H.push({type:"image_url",image_url:{url:`data:${D};base64,${J}`}}):H.push({type:"file",file:{filename:P.filename||"file",file_data:`data:${D};base64,${J}`}})}}else{let P=E.text||"";P&&H.push({type:"text",text:P})}u.push({role:O,content:H.length===1&&H[0].type==="text"?H[0].text:H})}let h={Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},x=["free","nitro","floor","exacto"],i=t,c=null,w=null;if(t.includes(":")){let E=t.split(":");if(E.length>1){let O=E[E.length-1].toLowerCase().trim();(O==="flex"||O==="priority")&&(w=O,E.pop())}if(E.length>1){let O=E[E.length-1].toLowerCase().trim();if(!x.includes(O)){let H=E.pop().trim();H&&(c={only:[H],allow_fallbacks:!1})}}i=E.join(":").trim()}let A=`${e.slice(-5)}${g||""}${o}${i}${w||""}${c?JSON.stringify(c):""}`,b=await jo(A),C={model:i,messages:u,stream:!0,temperature:m,cache_control:{type:"ephemeral"},session_id:b};w&&(C.service_tier=w),c&&(C.provider=c);let N=Ue("OpenRouter",t,o),R=N!==null?N:h[o];R&&R!=="none"&&(N!==null||o!=="Fast")&&(C.reasoning_effort=R);let _=await nt("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(C),signal:a});if(!_.ok){let E=await _.json().catch(()=>({})),O=E.error?.metadata?.raw||E.error?.message||(typeof E.error=="string"?E.error:"")||_.statusText||"Unknown error";throw new Error(`OpenRouter Error (${_.status}): ${O}`)}let M=_.body.getReader(),$=new TextDecoder,p="",d=[],T=null,r=Date.now(),k=!1;for(;;){let{done:E,value:O}=await M.read();if(E){k&&(d.length>0||T)&&(yield{candidates:d.length>0?[{content:{parts:d}}]:[],usageMetadata:T});break}p+=$.decode(O,{stream:!0});let H=p.split(`
603
+ `);p=H.pop();for(let P of H){let D=P.trim();if(!D||!D.startsWith("data: "))continue;let J=!1;if(D==="data: [DONE]")J=!0;else try{let fe=JSON.parse(D.substring(6));if(fe.error){let ve=fe.error.metadata?.raw||fe.error.message||JSON.stringify(fe.error);throw new Error(`OpenRouter Stream Error: ${ve}`)}let q=fe.choices?.[0]?.delta,xe=fe.usage;if(fe.choices?.[0]?.finish_reason&&(J=!0),xe&&(T={totalTokenCount:xe.total_tokens||(xe.prompt_tokens||0)+(xe.completion_tokens||0),promptTokenCount:xe.prompt_tokens||0,candidatesTokenCount:xe.completion_tokens||0,cachedContentTokenCount:xe.prompt_tokens_details?.cached_tokens||xe.prompt_tokens_details?.cache_read_input_tokens||xe.cache_read_input_tokens||0,thoughtsTokenCount:xe.completion_tokens_details?.reasoning_tokens||0},k=!0),q){let ve=q.reasoning||(q.reasoning_details?q.reasoning_details.map(B=>B.text).join(""):null);ve&&(d.push({text:ve,thought:!0}),k=!0),q.content&&(d.push({text:q.content}),k=!0)}}catch(fe){if(fe.message&&fe.message.startsWith("OpenRouter Stream Error:"))throw fe}if((J||Date.now()-r>=150)&&k&&(yield{candidates:d.length>0?[{content:{parts:[...d]}}]:[],usageMetadata:T},d=[],r=Date.now(),k=!1),J)break}}};import{Ollama as ka}from"ollama";var Hs=async function*(e,t,n,s,o,l,f,a,m=1,g="Cloud"){let u=[];s&&u.push({role:"system",content:s});for(let p of n){let d=p.role==="user"?"user":"assistant",T="",r=[];if(Array.isArray(p.parts)){T=p.parts.map(k=>k.text||"").filter(Boolean).join(`
604
+ `);for(let k of p.parts){let E=k.inlineData||k.inline_data;E&&E.data&&r.push(E.data)}}else T=p.text||"";if(T||r.length>0){let k={role:d,content:T};r.length>0&&(k.images=r),u.push(k)}}let h=g==="Local"||!e||e==="LOCAL",i={host:h?process.env.OLLAMA_HOST||"http://127.0.0.1:11434":process.env.OLLAMA_HOST||"https://ollama.com"};!h&&e&&(i.headers={Authorization:"Bearer "+e});let c=new ka(i),w=[],A=null,b=Date.now(),C=!1,N=Ue("Ollama",t,o),R={Fast:!1,Low:"medium",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},_=N!==null?N==="false"||N===!1?!1:N==="true"||N===!0?!0:N:R[o]!==void 0?R[o]:!0,M={model:t,messages:u,stream:!0,think:_,keep_alive:"10m",options:{temperature:m}},$=await c.chat(M);for await(let p of $){if(a?.aborted)throw new DOMException("The user aborted a request.","AbortError");if(p.message?.thinking&&(w.push({text:p.message.thinking,thought:!0}),C=!0),p.message?.content&&(w.push({text:p.message.content}),C=!0),p.done){let d=p.prompt_cached_count||0;if(!d&&p.prompt_eval_count){let T=p.prompt_eval_duration||0;T>0&&T<5e7&&(d=p.prompt_eval_count)}A={totalTokenCount:(p.prompt_eval_count||0)+(p.eval_count||0),promptTokenCount:p.prompt_eval_count||0,candidatesTokenCount:p.eval_count||0,cachedContentTokenCount:d,thoughtsTokenCount:0},C=!0}(p.done||Date.now()-b>=150&&C)&&(yield{candidates:w.length>0?[{content:{parts:[...w]}}]:[],usageMetadata:A},w=[],b=Date.now(),C=!1)}C&&(w.length>0||A)&&(yield{candidates:w.length>0?[{content:{parts:[...w]}}]:[],usageMetadata:A})};var zo=async function*(e,t,n,s,o,l,f,a,m=1){let g=[];s&&g.push({role:"system",content:s});for(let d of n){let T=d.role==="user"?"user":"assistant",r="";if(Array.isArray(d.parts))for(let k of d.parts)k.text&&(r+=(r?`
605
+ `:"")+k.text);else r=d.text||"";g.push({role:T,content:r})}let u=Ue("InferX",t,o),x=u!==null?u:{Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i=t&&t.toLowerCase().includes("qwen3.8-27b")&&u===null,c=t&&(t.toLowerCase().includes("qwen3.8-27b")||t.toLowerCase().includes("qwen3.6-35b-a3b-fp8")),w={model:t,messages:g.filter(d=>d.content&&String(d.content).trim().length>0),stream:!0,stream_options:{include_usage:!0},temperature:m};!i&&x&&(w.stream_options={include_usage:!0},w.reasoning_effort=x);let A=await nt("https://model.inferx.net/endpoints/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(w),signal:a});if(!A.ok){let d=await A.text().catch(()=>""),T="";try{let r=JSON.parse(d);T=r.error?.message||r.error?.detail||r.message||r.detail||(typeof r.error=="string"?r.error:"")||(d&&d!=="{}"?d:"")}catch{T=d}throw(!T||T==="{}")&&(T=A.statusText||"Unknown error"),new Error(`InferX Error (${A.status}): ${T}`)}let b=A.body.getReader(),C=new TextDecoder,N="",R=[],_=null,M=Date.now(),$=!1,p=!0;for(;;){let{done:d,value:T}=await b.read();if(d){$&&(R.length>0||_)&&(yield{candidates:R.length>0?[{content:{parts:R}}]:[],usageMetadata:_});break}N+=C.decode(T,{stream:!0});let r=N.split(`
606
+ `);N=r.pop();for(let k of r){let E=k.trim();if(!E||!E.startsWith("data: "))continue;let O=!1;if(E==="data: [DONE]")O=!0;else try{let H=JSON.parse(E.substring(6)),P=H.choices?.[0]?.delta,D=H.usage;if(D&&(_={totalTokenCount:D.total_tokens||(D.prompt_tokens||0)+(D.completion_tokens||0),promptTokenCount:D.prompt_tokens||0,candidatesTokenCount:D.completion_tokens||0,cachedContentTokenCount:D.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:D.completion_tokens_details?.reasoning_tokens||D.reasoning_tokens||0},$=!0),P){let J=P.reasoning||P.reasoning_content||null;if(J&&(R.push({text:J,thought:!0}),$=!0),P.content){let fe=P.content;c&&p&&fe.length>0&&(fe="<think>"+fe,p=!1),R.push({text:fe}),$=!0}}}catch{}if((O||Date.now()-M>=150||_)&&$&&(yield{candidates:R.length>0?[{content:{parts:[...R]}}]:[],usageMetadata:_},R=[],M=Date.now(),$=!1),O)break}Date.now()-M>=150&&$&&(yield{candidates:R.length>0?[{content:{parts:[...R]}}]:[],usageMetadata:_},R=[],M=Date.now(),$=!1)}};var Jo=async function*(e,t,n,s,o,l,f,a,m=1){let g=[];s&&g.push({role:"system",content:s});for(let M of n){let $=M.role==="user"?"user":"assistant",p=[];if(Array.isArray(M.parts)){for(let d of M.parts)if(d.text)p.push({type:"text",text:d.text});else if(d.inlineData&&f){let T=d.inlineData.mimeType,r=d.inlineData.data;T.startsWith("image/")&&p.push({type:"image_url",image_url:{url:`data:${T};base64,${r}`}})}}else{let d=M.text||"";d&&p.push({type:"text",text:d})}g.push({role:$,content:p.length===1&&p[0].type==="text"?p[0].text:p})}let u=Ue("SenseNova",t,o),x=u!==null?u:{Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:g,stream:!0,stream_options:{include_usage:!0},temperature:m};x&&(i.reasoning_effort=x);let c=await nt("https://token.sensenova.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(i),signal:a});if(!c.ok){let M=await c.json().catch(()=>({}));throw new Error(`SenseNova Error (${c.status}): ${M.error?.message||c.statusText}`)}let w=c.body.getReader(),A=new TextDecoder,b="",C=[],N=null,R=Date.now(),_=!1;for(;;){let{done:M,value:$}=await w.read();if(M){_&&(C.length>0||N)&&(yield{candidates:C.length>0?[{content:{parts:C}}]:[],usageMetadata:N});break}b+=A.decode($,{stream:!0});let p=b.split(`
607
+ `);b=p.pop();for(let d of p){let T=d.trim();if(!T||!T.startsWith("data: "))continue;let r=!1;if(T==="data: [DONE]")r=!0;else try{let k=JSON.parse(T.substring(6)),E=k.choices?.[0]?.delta,O=k.usage;if(O&&(N={totalTokenCount:O.total_tokens||(O.prompt_tokens||0)+(O.completion_tokens||0),promptTokenCount:O.prompt_tokens||0,candidatesTokenCount:O.completion_tokens||0,cachedContentTokenCount:O.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:O.completion_tokens_details?.reasoning_tokens||O.reasoning_tokens||0},_=!0),E){let H=E.reasoning||E.reasoning_content||null;H&&(C.push({text:H,thought:!0}),_=!0),E.content&&(C.push({text:E.content}),_=!0)}}catch{}if((r||Date.now()-R>=150||N)&&_&&(yield{candidates:C.length>0?[{content:{parts:[...C]}}]:[],usageMetadata:N},C=[],R=Date.now(),_=!1),r)break}Date.now()-R>=150&&_&&(yield{candidates:C.length>0?[{content:{parts:[...C]}}]:[],usageMetadata:N},C=[],R=Date.now(),_=!1)}};var Xo=async function*(e,t,n,s,o,l,f,a,m=1){let g=[];s&&g.push({role:"system",content:s});for(let M of n){let $=M.role==="user"?"user":"assistant",p=[];if(Array.isArray(M.parts)){for(let d of M.parts)if(d.text)p.push({type:"text",text:d.text});else if(d.inlineData&&f){let T=d.inlineData.mimeType,r=d.inlineData.data;T.startsWith("image/")&&p.push({type:"image_url",image_url:{url:`data:${T};base64,${r}`}})}}else{let d=M.text||"";d&&p.push({type:"text",text:d})}g.push({role:$,content:p.length===1&&p[0].type==="text"?p[0].text:p})}let u=Ue("AIHubMix",t,o),x=u!==null?u:{Fast:"minimal",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:g,stream:!0,stream_options:{include_usage:!0},temperature:m};x&&(i.reasoning_effort=x);let c=await nt("https://aihubmix.com/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(i),signal:a});if(!c.ok){let M=await c.json().catch(()=>({}));throw new Error(`AIHubMix Error (${c.status}): ${M.error?.message||c.statusText}`)}let w=c.body.getReader(),A=new TextDecoder,b="",C=[],N=null,R=Date.now(),_=!1;for(;;){let{done:M,value:$}=await w.read();if(M){_&&(C.length>0||N)&&(yield{candidates:C.length>0?[{content:{parts:C}}]:[],usageMetadata:N});break}b+=A.decode($,{stream:!0});let p=b.split(`
608
+ `);b=p.pop();for(let d of p){let T=d.trim();if(!T||!T.startsWith("data: "))continue;let r=!1;if(T==="data: [DONE]")r=!0;else try{let k=JSON.parse(T.substring(6)),E=k.choices?.[0]?.delta,O=k.usage;if(k.choices?.[0]?.finish_reason&&(r=!0),O&&(N={totalTokenCount:O.total_tokens||(O.prompt_tokens||0)+(O.completion_tokens||0),promptTokenCount:O.prompt_tokens||0,candidatesTokenCount:O.completion_tokens||0,cachedContentTokenCount:O.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:O.completion_tokens_details?.reasoning_tokens||O.reasoning_tokens||0},_=!0),E){let H=E.reasoning_content||null;H&&(C.push({text:H,thought:!0}),_=!0),E.content&&(C.push({text:E.content}),_=!0)}}catch{}if((r||Date.now()-R>=150)&&_&&(yield{candidates:C.length>0?[{content:{parts:[...C]}}]:[],usageMetadata:N},C=[],R=Date.now(),_=!1),r)break}Date.now()-R>=150&&_&&(yield{candidates:C.length>0?[{content:{parts:[...C]}}]:[],usageMetadata:N},C=[],R=Date.now(),_=!1)}};var Qo=async function*(e,t,n,s,o,l,f,a,m=1){let g=[];s&&g.push({role:"system",content:s});for(let _ of n){let M=_.role==="user"?"user":"assistant",$=[];if(Array.isArray(_.parts)){for(let p of _.parts)if(p.text)$.push({type:"text",text:p.text});else if(p.inlineData&&f){let d=p.inlineData.mimeType,T=p.inlineData.data;d.startsWith("image/")&&$.push({type:"image_url",image_url:{url:`data:${d};base64,${T}`}})}}else{let p=_.text||"";p&&$.push({type:"text",text:p})}g.push({role:M,content:$.length===1&&$[0].type==="text"?$[0].text:$})}let u=Ue("Poolside",t,o),h=u!==null?u===!1||u==="false"||u==="none"||u==="Fast":o==="Fast",x={model:t,messages:g,stream:!0,stream_options:{include_usage:!0},temperature:m};h?x.chat_template_kwargs={enable_thinking:!1}:u!==null&&typeof u=="object"?x.chat_template_kwargs=u:x.chat_template_kwargs={enable_thinking:!0};let i=await nt("https://inference.poolside.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(x),signal:a});if(!i.ok){let _=await i.json().catch(()=>({}));throw new Error(`Poolside Error (${i.status}): ${_.error?.message||i.statusText}`)}let c=i.body.getReader(),w=new TextDecoder,A="",b=[],C=null,N=Date.now(),R=!1;for(;;){let{done:_,value:M}=await c.read();if(_){R&&(b.length>0||C)&&(yield{candidates:b.length>0?[{content:{parts:b}}]:[],usageMetadata:C});break}A+=w.decode(M,{stream:!0});let $=A.split(`
609
+ `);A=$.pop();for(let p of $){let d=p.trim();if(!d||!d.startsWith("data: "))continue;let T=!1;if(d==="data: [DONE]")T=!0;else try{let r=JSON.parse(d.substring(6)),k=r.choices?.[0]?.delta,E=r.usage;if(r.choices?.[0]?.finish_reason&&(T=!0),E&&(C={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},R=!0),k){let O=k.reasoning_content||k.reasoning||null;O&&(b.push({text:O,thought:!0}),R=!0),k.content&&(b.push({text:k.content}),R=!0)}}catch{}if((T||Date.now()-N>=150)&&R&&(yield{candidates:b.length>0?[{content:{parts:[...b]}}]:[],usageMetadata:C},b=[],N=Date.now(),R=!1),T)break}Date.now()-N>=150&&R&&(yield{candidates:b.length>0?[{content:{parts:[...b]}}]:[],usageMetadata:C},b=[],N=Date.now(),R=!1)}};var Zo=async function*(e,t,n,s,o,l,f,a,m=1){let g=[];s&&g.push({role:"system",content:s});for(let d of n){let T=d.role==="user"?"user":"assistant",r=[];if(Array.isArray(d.parts)){for(let k of d.parts)if(k.text)r.push({type:"text",text:k.text});else if(k.inlineData&&f){let E=k.inlineData.mimeType,O=k.inlineData.data;E.startsWith("image/")&&r.push({type:"image_url",image_url:{url:`data:${E};base64,${O}`}})}}else{let k=d.text||"";k&&r.push({type:"text",text:k})}g.push({role:T,content:r.length===1&&r[0].type==="text"?r[0].text:r})}let u=Ue("9router",t,o)||Ue("9Router",t,o),x=u!==null?u:{Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:g,stream:!0,stream_options:{include_usage:!0},temperature:m};x&&x!=="none"&&(u!==null||o!=="Fast")&&(i.reasoning_effort=x);let c=process.env["9ROUTER_URL"]||process.env.NINEROUTER_URL||"http://127.0.0.1:20128/v1/chat/completions",w={"Content-Type":"application/json"},A=e&&e!=="LOCAL"?e:process.env["9ROUTER_API_KEY"]||"dummy-key";w.Authorization=`Bearer ${A}`;let b=await nt(c,{method:"POST",headers:w,body:JSON.stringify(i),signal:a});if(!b.ok){let d=await b.json().catch(()=>({}));throw new Error(`9router Error (${b.status}): ${d.error?.message||b.statusText}`)}let C=b.body.getReader(),N=new TextDecoder,R="",_=[],M=null,$=Date.now(),p=!1;for(;;){let{done:d,value:T}=await C.read();if(d){p&&(_.length>0||M)&&(yield{candidates:_.length>0?[{content:{parts:_}}]:[],usageMetadata:M});break}R+=N.decode(T,{stream:!0});let r=R.split(`
610
+ `);R=r.pop();for(let k of r){let E=k.trim();if(!E||!E.startsWith("data: "))continue;let O=!1;if(E==="data: [DONE]")O=!0;else try{let H=JSON.parse(E.substring(6)),P=H.choices?.[0]?.delta,D=H.usage;if(H.choices?.[0]?.finish_reason&&(O=!0),D&&(M={totalTokenCount:D.total_tokens||(D.prompt_tokens||0)+(D.completion_tokens||0),promptTokenCount:D.prompt_tokens||0,candidatesTokenCount:D.completion_tokens||0,cachedContentTokenCount:D.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:D.completion_tokens_details?.reasoning_tokens||D.reasoning_tokens||0},p=!0),P){let J=P.reasoning_content||P.reasoning||P.thinking||null;!J&&Array.isArray(P.reasoning_details)&&P.reasoning_details.length>0&&(J=P.reasoning_details.map(fe=>typeof fe=="string"?fe:fe?.text||"").filter(Boolean).join("")),J&&(_.push({text:J,thought:!0}),p=!0),P.content&&(_.push({text:P.content}),p=!0)}}catch{}if((O||Date.now()-$>=150)&&p&&(yield{candidates:_.length>0?[{content:{parts:[..._]}}]:[],usageMetadata:M},_=[],$=Date.now(),p=!1),O)break}Date.now()-$>=150&&p&&(yield{candidates:_.length>0?[{content:{parts:[..._]}}]:[],usageMetadata:M},_=[],$=Date.now(),p=!1)}};var es=async function*(e,t,n,s,o,l,f,a,m=1){let g=[];s&&g.push({role:"system",content:s});for(let d of n){let T=d.role==="user"?"user":"assistant",r=[];if(Array.isArray(d.parts)){for(let k of d.parts)if(k.text)r.push({type:"text",text:k.text});else if(k.inlineData&&f){let E=k.inlineData.mimeType,O=k.inlineData.data;E.startsWith("image/")&&r.push({type:"image_url",image_url:{url:`data:${E};base64,${O}`}})}}else{let k=d.text||"";k&&r.push({type:"text",text:k})}g.push({role:T,content:r.length===1&&r[0].type==="text"?r[0].text:r})}let u=Ue("ExpLabs",t,o),x=u!==null?u:{Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:g,stream:!0,stream_options:{include_usage:!0},temperature:m};x&&(i.reasoning_effort=x);let c=process.env.EXPLABS_URL||process.env.EXPERIENTIALLABS_URL||"https://api.experientiallabs.ai/v1/chat/completions",w={"Content-Type":"application/json"},A=e||process.env.EXPLABS_API_KEY||process.env.EXPERIENTIALLABS_API_KEY||"";w.Authorization=`Bearer ${A}`;let b=await nt(c,{method:"POST",headers:w,body:JSON.stringify(i),signal:a});if(!b.ok){let d=await b.json().catch(()=>({}));throw new Error(`Experiential Labs Error (${b.status}): ${d.error?.message||d.message||b.statusText}`)}let C=b.body.getReader(),N=new TextDecoder,R="",_=[],M=null,$=Date.now(),p=!1;for(;;){let{done:d,value:T}=await C.read();if(d){p&&(_.length>0||M)&&(yield{candidates:_.length>0?[{content:{parts:_}}]:[],usageMetadata:M});break}R+=N.decode(T,{stream:!0});let r=R.split(`
611
+ `);R=r.pop();for(let k of r){let E=k.trim();if(!E||!E.startsWith("data: "))continue;let O=!1;if(E==="data: [DONE]")O=!0;else try{let H=JSON.parse(E.substring(6)),P=H.choices?.[0]?.delta,D=H.usage;if(D&&(M={totalTokenCount:D.total_tokens||(D.prompt_tokens||0)+(D.completion_tokens||0),promptTokenCount:D.prompt_tokens||0,candidatesTokenCount:D.completion_tokens||0,cachedContentTokenCount:D.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:D.completion_tokens_details?.reasoning_tokens||D.reasoning_tokens||0},p=!0),P){let J=P.reasoning_content||P.reasoning||null;!J&&Array.isArray(P.reasoning_details)&&P.reasoning_details.length>0&&(J=P.reasoning_details.map(fe=>fe.text||"").filter(Boolean).join("")),J&&(_.push({text:J,thought:!0}),p=!0),P.content&&(_.push({text:P.content}),p=!0)}}catch{}if((O||Date.now()-$>=150)&&p&&(yield{candidates:_.length>0?[{content:{parts:[..._]}}]:[],usageMetadata:M},_=[],$=Date.now(),p=!1),O)break}Date.now()-$>=150&&p&&(yield{candidates:_.length>0?[{content:{parts:[..._]}}]:[],usageMetadata:M},_=[],$=Date.now(),p=!1)}};var Gs=async function*(e,t,n,s,o,l,f,a,m=1){let g=[];s&&g.push({role:"system",content:s});for(let d of n){let T=d.role==="user"?"user":"assistant",r=[];if(Array.isArray(d.parts)){for(let k of d.parts)if(k.text)r.push({type:"text",text:k.text});else if(k.inlineData&&f){let E=k.inlineData.mimeType,O=k.inlineData.data;E.startsWith("image/")&&r.push({type:"image_url",image_url:{url:`data:${E};base64,${O}`}})}}else{let k=d.text||"";k&&r.push({type:"text",text:k})}g.push({role:T,content:r.length===1&&r[0].type==="text"?r[0].text:r})}let u=Ue("TokenHarbor",t,o),x=u!==null?u:{Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:g,stream:!0,stream_options:{include_usage:!0},temperature:m};x&&(i.reasoning_effort=x);let c=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/"},A=e||process.env.TOKENHARBOR_API_KEY||process.env.TOKEN_HARBOR_API_KEY||"";w.Authorization=`Bearer ${A}`;let b=await nt(c,{method:"POST",headers:w,body:JSON.stringify(i),signal:a});if(!b.ok){let d=await b.json().catch(()=>({}));throw new Error(`Token Harbor Error (${b.status}): ${d.error?.message||d.message||b.statusText}`)}let C=b.body.getReader(),N=new TextDecoder,R="",_=[],M=null,$=Date.now(),p=!1;for(;;){let{done:d,value:T}=await C.read();if(d){p&&(_.length>0||M)&&(yield{candidates:_.length>0?[{content:{parts:_}}]:[],usageMetadata:M});break}R+=N.decode(T,{stream:!0});let r=R.split(`
612
+ `);R=r.pop();for(let k of r){let E=k.trim();if(!E||!E.startsWith("data: "))continue;let O=!1;if(E==="data: [DONE]")O=!0;else try{let H=JSON.parse(E.substring(6)),P=H.choices?.[0]?.delta,D=H.usage;if(D&&(M={totalTokenCount:D.total_tokens||(D.prompt_tokens||0)+(D.completion_tokens||0),promptTokenCount:D.prompt_tokens||0,candidatesTokenCount:D.completion_tokens||0,cachedContentTokenCount:D.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:D.completion_tokens_details?.reasoning_tokens||D.reasoning_tokens||0},p=!0),P){let J=P.reasoning_content||P.reasoning||null;!J&&Array.isArray(P.reasoning_details)&&P.reasoning_details.length>0&&(J=P.reasoning_details.map(fe=>fe.text||"").filter(Boolean).join("")),J&&(_.push({text:J,thought:!0}),p=!0),P.content&&(_.push({text:P.content}),p=!0)}}catch{}if((O||Date.now()-$>=150)&&p&&(yield{candidates:_.length>0?[{content:{parts:[..._]}}]:[],usageMetadata:M},_=[],$=Date.now(),p=!1),O)break}Date.now()-$>=150&&p&&(yield{candidates:_.length>0?[{content:{parts:[..._]}}]:[],usageMetadata:M},_=[],$=Date.now(),p=!1)}};var js=async function*(e,t,n,s,o,l,f,a,m=1){let g=[];s&&g.push({role:"system",content:s});for(let d of n){let T=d.role==="user"?"user":"assistant",r=[];if(Array.isArray(d.parts)){for(let k of d.parts)if(k.text)r.push({type:"text",text:k.text});else if(k.inlineData&&f){let E=k.inlineData.mimeType,O=k.inlineData.data;E.startsWith("image/")&&r.push({type:"image_url",image_url:{url:`data:${E};base64,${O}`}})}}else{let k=d.text||"";k&&r.push({type:"text",text:k})}g.push({role:T,content:r.length===1&&r[0].type==="text"?r[0].text:r})}let u=Ue("APInex",t,o),x=u!==null?u:{Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:g,stream:!0,stream_options:{include_usage:!0},temperature:m};x&&(i.reasoning_effort=x);let c=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/"},A=e||process.env.APINEX_API_KEY||"";w.Authorization=`Bearer ${A}`;let b=await nt(c,{method:"POST",headers:w,body:JSON.stringify(i),signal:a});if(!b.ok){let d=await b.json().catch(()=>({}));throw new Error(`APInex Error (${b.status}): ${d.error?.message||d.message||b.statusText}`)}let C=b.body.getReader(),N=new TextDecoder,R="",_=[],M=null,$=Date.now(),p=!1;for(;;){let{done:d,value:T}=await C.read();if(d){p&&(_.length>0||M)&&(yield{candidates:_.length>0?[{content:{parts:_}}]:[],usageMetadata:M});break}R+=N.decode(T,{stream:!0});let r=R.split(`
613
+ `);R=r.pop();for(let k of r){let E=k.trim();if(!E||!E.startsWith("data: "))continue;let O=!1;if(E==="data: [DONE]")O=!0;else try{let H=JSON.parse(E.substring(6)),P=H.choices?.[0]?.delta,D=H.usage;if(D&&(M={totalTokenCount:D.total_tokens||(D.prompt_tokens||0)+(D.completion_tokens||0),promptTokenCount:D.prompt_tokens||0,candidatesTokenCount:D.completion_tokens||0,cachedContentTokenCount:D.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:D.completion_tokens_details?.reasoning_tokens||D.reasoning_tokens||0},p=!0),P){let J=P.reasoning_content||P.reasoning||null;!J&&Array.isArray(P.reasoning_details)&&P.reasoning_details.length>0&&(J=P.reasoning_details.map(fe=>fe.text||"").filter(Boolean).join("")),J&&(_.push({text:J,thought:!0}),p=!0),P.content&&(_.push({text:P.content}),p=!0)}}catch{}if((O||Date.now()-$>=150)&&p&&(yield{candidates:_.length>0?[{content:{parts:[..._]}}]:[],usageMetadata:M},_=[],$=Date.now(),p=!1),O)break}Date.now()-$>=150&&p&&(yield{candidates:_.length>0?[{content:{parts:[..._]}}]:[],usageMetadata:M},_=[],$=Date.now(),p=!1)}};var wa=/```[\s\S]*?```/g,Ta=/```[\s\S]*$/g,Sa=/`[^`]+`/g,_a=/^\|.*\|$/gm,Ea=/^[^\w]+|[^\w]+$/g,Aa=/[^a-z0-9]/gi,ho=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,Ca=/\[\s*(?:tool:functions\.|agent:generalist\.)([a-z0-9_]+)\s*\(/gi,va=/(?:path|targetFile|TargetFile|directory|keyword|id|taskId|title|task)\s*=\s*\\?["']?([^\\"' \),]+)/,Nn=/["']/g,vr=/\\/g,Ra=/<\|channel>thought/gi,Ma=/<channel\|>/gi,Ia=e=>typeof e!="string"?e:e.replace(Ra,"<think>").replace(Ma,"</think>"),qd=/^\s*(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\]|$)/i,Da=(e,t)=>{let n=!1;for(let s=0;s<t;s++)e[s]==="`"&&(n=!n);return n},Oa=e=>{let t=/(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\])/gi,n;for(;(n=t.exec(e))!==null;)if(!Da(e,n.index))return{index:n.index,length:n[0].length};return{index:-1,length:0}},Vs=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=Oa(s);if(o.index!==-1){let l=n+o.index+o.length;return{fullBlock:e.substring(0,l),innerContent:s.substring(0,o.index),remainingText:e.substring(l)}}return{fullBlock:e,innerContent:s,remainingText:""}},Kt=e=>{if(!e||typeof e!="string")return e;let t=Vs(e);return t?t.remainingText.trimStart():e};var Pr=/`[^`]*`/g,$r=/`[^`]*$/,Rr=/<\|\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,La=/"([^"]+)"\s*:\s*(?:"([^"]*)"|(\d+)|true|false|null)/g,Mr=/<\|\s*tool_calls_section_begin\s*\|>/gi,Ir=/<\|\s*tool_calls_section_end\s*\|>/gi,Pa=/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi;var Dr=e=>!e||typeof e!="string"?e:e.replace(/(```[\s\S]*?```|`[^`]*`)|(<(?:\w+)(?:[^>]*)>\r?\n?|\r?\n?<\/\w+(?:[^>]*)>)/gi,(t,n)=>n||""),Nr=e=>{if(!e||typeof e!="string")return e;let t=po(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()},Ys=null,ts={},Fn={key:null,value:null},Vt=e=>e&&e.replace(/(?:(\x1b\[\d+m))?([✔✘✖🔍📖→➕↻↷•🛇])(?:(\x1b\[\d+m))?\s*\b(Clicked|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,l)=>`${n||""}${s}${o||""} \x1B[95m${l}\x1B[0m`),$a=async(e,t=8,n=1e3,s=8e3,o=null)=>{let l=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."||(l++,l>=t))throw f;let a=Math.min(n*Math.pow(2,l-1),s);await new Promise((m,g)=>{let u=setTimeout(m,a);o&&o.addEventListener("abort",()=>{clearTimeout(u),g(new DOMException("The user aborted a request.","AbortError"))})})}}},wt=!1;var Na=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,l,f)=>{let a=o.fullText||o.text||"";if(o.role==="user"&&l<f.length-1)if(a.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")){let m=a.indexOf("**CONTEXT SUMMARY OF PREVIOUS TURNS");if(m!==-1){let u=a.substring(0,m).lastIndexOf("[SYSTEM METADATA]");u!==-1?a=a.substring(u).trim():a=a.substring(m).trim()}}else{let m=a.lastIndexOf("[USER]"),g=a.lastIndexOf("[USER PROMPT]");m!==-1?a=a.substring(m+6).trim():g!==-1&&(a=a.substring(g).trim())}return{...o,text:a}}),n=[],s=0;for(;s<t.length;){let o=t[s];if(o.role==="user")n.push(o),s++;else{let l=[];for(;s<t.length&&t[s].role!=="user";)l.push(t[s]),s++;let f=[],a=[],m=!1,g=()=>{f.length>0&&(n.push({role:"agent",text:"combined"}),f=[]),a.length>0&&(n.push({role:"system",text:"combined"}),a=[]),m=!1};l.forEach(u=>{let h=u.role==="system"&&(u.text?.startsWith("[TOOL RESULT]")||u.text?.startsWith("SUCCESS:")||u.text?.startsWith("ERROR:")||u.fullText?.startsWith("[TOOL RESULT]")||u.fullText?.startsWith("SUCCESS:")||u.fullText?.startsWith("ERROR:")),x=u.fullText||u.text||"",i=x.trim();if(!(!i&&!u.binaryPart)){if(h)a.push(i);else if(u.role==="agent"){!m&&a.length>0&&g();let c=x.endsWith(`
614
+ `),w=i.toLowerCase().includes("tool:functions.")||i.toLowerCase().includes("agent:generalist.");f.push(i),w&&c?m=!0:m=!1}}}),g()}}return n.length},Fa=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),zd=()=>{wt=!0},Jd=()=>wt,Ks={write_file:"Writing",update_file:"Editing",read_folder:"Reading",view_file:"Reading",exec_command:"Executing Command",web_search:"Searching",web_scrape:"Reading",memory:"Updating Memory",search_keyword:"Searching",file_map:"Generating Map",ask:"User Input",write_pdf:"Creating",write_docx:"Creating",generate_image:"Generating",todo:"Planning",Todo:"Planning",goal:"Planning",Goal:"Planning",invoke_sync:"Sub-Agent Working",invoke:"Starting Agent",get_progress:"Checking Progress",cancel:"Cancelling",await:"Waiting",EmergencyRollback:"Don't Panic. Lookin' into it",answer:"Answering Sub-Agent",Answer:"Answering Sub-Agent",steer:"Steering Sub-Agent",Steer:"Steering Sub-Agent",Click:"Clicking",click:"Clicking",Drag:"Dragging",drag:"Dragging",Scroll:"Scrolling",scroll:"Scrolling",KeyboardTyping:"Typing",keyboard_typing:"Typing",KeyPress:"Pressing Key",key_press:"Pressing Key",RecaptureScreen:"Recapturing Screen",recapture_screen:"Recapturing Screen"},Bn=(e,t)=>{try{let n=Z(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.path||n.targetFile||n.TargetFile||n.directory;return o?X.basename(o.replace(/["']/g,"").replace(/\\/g,"/")):null}catch{return null}},qs=e=>e?new Lr({apiKey:e}):Ys,Xd=async(e,t,n,s,o={})=>{let{onStatus:a,onMemoryUpdated:m,onBackgroundIncrement:g}=o,{profile:u,thinkingLevel:h,mode:x,janitorModel:i,chatId:c,systemSettings:w,sessionStats:A,aiProvider:b="Google",apiKey:C}=e,N=process.env.NVIDIA_BASE_URL||b==="Ollama"||b==="InferX"||b==="SenseNova"||b==="AIHubMix"||b==="Poolside"||b==="9router"||b==="ExpLabs"||b==="ExperientialLabs"?!1:w?.memory!==!1,_=Et(Pn,[]).map(I=>`- [${I.id}]: ${I.memory}`).join(`
615
+ `),M=s.slice(0,-1).filter(I=>I.text&&!I.text.includes("[TOOL RESULT]")&&!I.text.includes("OBSERVATION:")&&!I.text.startsWith("[TERMINAL_RECORD]")&&!I.isTerminalRecord&&!I.isMeta&&!I.isLogo&&!String(I.id).startsWith("welcome")&&!String(I.id).startsWith("logo")).slice(-14).map(I=>{let Fe=Kt(Fa(I.text)).replace(/\[tool:functions\..*?\]/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[METADATA \(PRIORITY: DYNAMIC\)\] Time: ([^|\n]+)/g,(We,ue)=>`[METADATA (PRIORITY: DYNAMIC)] Time: ${ue.replace(/:\d{2}/g,"")}`).replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[TOOL RESULTS\]/g,"").replace(/\[tool results\]/g,"").replace(/\r?\n\r?\n/g,`
616
616
  `).replace(/\n\n/g,`
617
- `).replace(/\\n\\n/g,"").trim(),te=C.role==="user"?8192:32768,Y=G.substring(0,te);G.length>te&&(Y+=`
618
- ... (truncated) ...`);let Xe=C.role==="user"?Y.startsWith("[USER]")?"":"[USER]: ":Y.startsWith("[AGENT]")?"":"[AGENT]: ";return{role:C.role==="user"?"user":"model",parts:[{text:`${Xe}${Y}`}]}}),$=s.filter(C=>C.role==="user").length===1,p=t.includes("[TITLE-UPDATE]"),d=Math.random()<.8,w=$||p||d,r=Kt(n).trim(),k=er(S,N,w),E=`${r.replace(/\[tool:functions\..*?\]/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[\[TOOL RESULTS\]\]/g,"").replace(/\[tool results\]/g,"").substring(0,32768)}`;E.length>32768&&(E+=`
617
+ `).replace(/\\n\\n/g,"").trim(),te=I.role==="user"?8192:32768,v=Fe.substring(0,te);Fe.length>te&&(v+=`
618
+ ... (truncated) ...`);let K=I.role==="user"?v.startsWith("[USER]")?"":"[USER]: ":v.startsWith("[AGENT]")?"":"[AGENT]: ";return{role:I.role==="user"?"user":"model",parts:[{text:`${K}${v}`}]}}),$=s.filter(I=>I.role==="user").length===1,p=t.includes("[TITLE-UPDATE]"),d=Math.random()<.8,T=$||p||d,r=Kt(n).trim(),k=er(_,N,T),E=`${r.replace(/\[tool:functions\..*?\]/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[\[TOOL RESULTS\]\]/g,"").replace(/\[tool results\]/g,"").substring(0,32768)}`;E.length>32768&&(E+=`
619
619
  ... (truncated) ...`);let O=t.replace(/\[Prompted on:.*?\]/g,"").trim();E=E.replace(/\r?\n\r?\n/g,`
620
620
  `).replace(/\n\n/g,`
621
- `).replace(/\\n\\n/g,"").trim();let U=new Date,D=`[METADATA] Current date and Time: ${`${U.getFullYear()}-${U.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(U.getDate()).padStart(2,"0")}, ${U.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0})}`}
621
+ `).replace(/\\n\\n/g,"").trim();let H=new Date,D=`[METADATA] Current date and Time: ${`${H.getFullYear()}-${H.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(H.getDate()).padStart(2,"0")}, ${H.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0})}`}
622
622
 
623
623
  [USER]: ${O.substring(0,8192)}
624
624
  ${O.length>8192?`... (truncated) ...
625
625
 
626
626
  `:""}
627
- [AGENT (current turn)]: ${E}`;I.push({role:"user",parts:[{text:D}]});let ee=await gs("NVIDIA"),B=(await oo()).quotas?.providerTiers?.NVIDIA==="Free",A="",Se=0,X=N?12:-1;for(;Se<=X;)try{if(!await li("background",e))return;let C="",G=null,te=!1,Y=b;try{let Ge=new Promise((ue,ge)=>setTimeout(()=>ge(new Error("JANITOR_TIMEOUT")),1e4)),ft=b==="Google"&&Se>=0&&Se<6&&ee&&B,Qe=b==="DeepSeek"&&Se<4&&ee&&B;te=ft||Qe,Y=te?"NVIDIA":b;let pt=(async()=>{if(b==="OpenRouter"){let ue=fe("janitor_open_router"),ie=qo(R,ue,I,k,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),Mt=await ie.next();return{iterator:ie,firstResult:Mt}}else if(b==="DeepSeek"&&!te){let ge=Vo(R,fe("deepseek_fast_fallback"),I,k,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),ie=await ge.next();return{iterator:ge,firstResult:ie}}else if(b==="Mistral"&&!te){let ge=Ko(R,fe("mistral_janitor_fallback"),I,k,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),ie=await ge.next();return{iterator:ge,firstResult:ie}}else if(b==="NVIDIA"||te){let ge=Yo(te?ee:R,fe("nvidia_janitor_fallback"),I,k,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),ie=await ge.next();return{iterator:ge,firstResult:ie}}else if(b==="InferX"){let ge=zo(R,targetModel||fe("inferx_fallback")||"deepseek-v4-flash",I,k,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),ie=await ge.next();return{iterator:ge,firstResult:ie}}else if(b==="SenseNova"){let ge=Jo(R,targetModel||fe("sensenova_fallback")||"sensenova-6.8-flash-lite",I,k,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),ie=await ge.next();return{iterator:ge,firstResult:ie}}else if(b==="AIHubMix"){let ge=Xo(R,targetModel||fe("aihubmix_fallback")||"gpt-4o-mini",I,k,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),ie=await ge.next();return{iterator:ge,firstResult:ie}}else if(b==="Poolside"){let ge=Qo(R,targetModel||fe("poolside_fallback")||"poolside/laguna-s-2.1",I,k,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),ie=await ge.next();return{iterator:ge,firstResult:ie}}else if(b==="9router"||b==="9Router"){let ge=Zo(R,targetModel||fe("9router_fallback")||"z-ai/glm-5.3-flash",I,k,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),ie=await ge.next();return{iterator:ge,firstResult:ie}}else if(b==="ExpLabs"||b==="ExperientialLabs"){let ge=es(R,targetModel||fe("explabs_fallback")||"deepseek-v4-pro-0813",I,k,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),ie=await ge.next();return{iterator:ge,firstResult:ie}}else{let ie=(await qs(R).models.generateContentStream({model:i||(Se===X?fe("janitor_default"):fe("gemma_janitor_fallback_google")),contents:I,config:{systemInstruction:k,temperature:.7,safetySettings:[{category:Cn.HARM_CATEGORY_HARASSMENT,threshold:An.BLOCK_NONE},{category:Cn.HARM_CATEGORY_HATE_SPEECH,threshold:An.BLOCK_NONE},{category:Cn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:An.BLOCK_NONE},{category:Cn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:An.BLOCK_NONE}],thinkingConfig:{includeThoughts:!1,thinkingLevel:Je.MINIMAL}}}))[Symbol.asyncIterator](),Mt=await ie.next();return{iterator:ie,firstResult:Mt}}})();if(process.stdout.isTTY){let ie=(await ps())[c]?.name||"",Mt=ie&&!ie.startsWith("flow-")&&!ie.startsWith("Session ")?ie:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${Mt}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${Mt}\x07`)}let{iterator:Ct,firstResult:kn}=await Promise.race([pt,Ge]),{value:Yt,done:ct}=kn;if(!ct&&Yt){let ue=Yt.candidates?.[0]?.content?.parts,ge=ue?Y==="Google"?ue[1]?.text||ue[0]?.text||"":ue.filter(ie=>ie.text&&!ie.thought).map(ie=>ie.text).join(""):typeof Yt.text=="function"?Yt.text():"";ge&&(C+=ge),G=Yt.usageMetadata;for await(let ie of{[Symbol.asyncIterator]:()=>Ct}){let Mt=ie.candidates?.[0]?.content?.parts,Un=Mt?Y==="Google"?Mt[1]?.text||Mt[0]?.text||"":Mt.filter(Tt=>Tt.text&&!Tt.thought).map(Tt=>Tt.text).join(""):typeof ie.text=="function"?ie.text():"";Un&&(C+=Un),G=ie.usageMetadata}}}catch(Ge){throw Ge}if(C){if(A=C,G){let Ge=G.totalTokenCount||0,ft=G.cachedContentTokenCount||0,Qe=(G.candidatesTokenCount||0)+(Y==="Google"&&G.thoughtsTokenCount||0),pt=te?fe("nvidia_janitor_fallback"):Y==="DeepSeek"?fe("deepseek_fast_fallback"):Y==="ExpLabs"||Y==="ExperientialLabs"?fe("explabs_fallback")||"deepseek-v4-pro-0813":Y==="OpenRouter"?fe("janitor_open_router"):i||(Se===X?fe("janitor_default"):fe("gemma_janitor_fallback_google"));await Ft("tokens",Ge,Y,pt),ft>0&&await Ft("cachedTokens",ft,Y,pt),Qe>0&&await Ft("candidateTokens",Qe,Y,pt)}}else throw new Error("No synthesis generated by Janitor.");g&&(g(),await At("background"));let Xe=yo(A),Ye=!1;for(let Ge of Xe){let ft=Ge.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(ft)&&(Ye=!0);let Qe={chatId:c,sessionId:c,history:s},pt=await mo(ft,Ge.args,Qe);ft.toLowerCase()==="memory"&&(Ge.args.includes("action='user'")||Ge.args.includes('action="user"'))&&!pt.startsWith("ERROR")&&(m&&m(),process.stdout.isTTY&&(process.stdout.write("\x1B]0;Memory Updated\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=Memory Updated\x07")),await new Promise(kn=>setTimeout(kn,3e3)))}if(!Ye)try{let Ge=Et(Pn,[]);if(Ge.length>0){let ft=[];for(let Qe of Ge)Qe.score===void 0&&(Qe.score=.5),Qe.score*=.99995,Qe.score<.05&&(Qe.score=0),Qe.score=Math.round(Qe.score*1e5)/1e5,Qe.score>0&&ft.push(Qe);Yn(Pn,ft)}}catch{}break}catch(C){Se++;let G=new Date().toLocaleString(),te=C instanceof Error?(()=>{try{return JSON.parse(JSON.parse(C.message).error.message).error.message}catch{return String(C)}})():String(C);await new Promise(Ye=>setTimeout(Ye,1e3));let Y=J.join(Sn,"janitor");if($e.existsSync(Y)||$e.mkdirSync(Y,{recursive:!0}),$e.appendFileSync(J.join(Y,"error.log"),`ERROR [Attempt ${Se}/${X+1}] [${G}]: ${te}
627
+ [AGENT (current turn)]: ${E}`;M.push({role:"user",parts:[{text:D}]});let J=await gs("NVIDIA"),q=(await no()).quotas?.providerTiers?.NVIDIA==="Free",xe="",ve=0,B=N?12:-1;for(;ve<=B;)try{if(!await li("background",e))return;let I="",Fe=null,te=!1,v=b;try{let ue=new Promise((ge,me)=>setTimeout(()=>me(new Error("JANITOR_TIMEOUT")),1e4)),Be=b==="Google"&&ve>=0&&ve<6&&J&&q,Ee=b==="DeepSeek"&&ve<4&&J&&q;te=Be||Ee,v=te?"NVIDIA":b;let pt=(async()=>{if(b==="OpenRouter"){let ge=de("janitor_open_router"),se=qo(C,ge,M,k,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),Mt=await se.next();return{iterator:se,firstResult:Mt}}else if(b==="DeepSeek"&&!te){let me=Vo(C,de("deepseek_fast_fallback"),M,k,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),se=await me.next();return{iterator:me,firstResult:se}}else if(b==="Mistral"&&!te){let me=Ko(C,de("mistral_janitor_fallback"),M,k,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),se=await me.next();return{iterator:me,firstResult:se}}else if(b==="NVIDIA"||te){let me=Yo(te?J:C,de("nvidia_janitor_fallback"),M,k,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),se=await me.next();return{iterator:me,firstResult:se}}else if(b==="InferX"){let me=zo(C,targetModel||de("inferx_fallback")||"deepseek-v4-flash",M,k,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),se=await me.next();return{iterator:me,firstResult:se}}else if(b==="SenseNova"){let me=Jo(C,targetModel||de("sensenova_fallback")||"sensenova-6.8-flash-lite",M,k,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),se=await me.next();return{iterator:me,firstResult:se}}else if(b==="AIHubMix"){let me=Xo(C,targetModel||de("aihubmix_fallback")||"gpt-4o-mini",M,k,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),se=await me.next();return{iterator:me,firstResult:se}}else if(b==="Poolside"){let me=Qo(C,targetModel||de("poolside_fallback")||"poolside/laguna-s-2.1",M,k,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),se=await me.next();return{iterator:me,firstResult:se}}else if(b==="9router"||b==="9Router"){let me=Zo(C,targetModel||de("9router_fallback")||"z-ai/glm-5.3-flash",M,k,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),se=await me.next();return{iterator:me,firstResult:se}}else if(b==="ExpLabs"||b==="ExperientialLabs"){let me=es(C,targetModel||de("explabs_fallback")||"deepseek-v4-pro-0813",M,k,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),se=await me.next();return{iterator:me,firstResult:se}}else{let se=(await qs(C).models.generateContentStream({model:i||(ve===B?de("janitor_default"):de("gemma_janitor_fallback_google")),contents:M,config:{systemInstruction:k,temperature:.7,safetySettings:[{category:Cn.HARM_CATEGORY_HARASSMENT,threshold:An.BLOCK_NONE},{category:Cn.HARM_CATEGORY_HATE_SPEECH,threshold:An.BLOCK_NONE},{category:Cn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:An.BLOCK_NONE},{category:Cn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:An.BLOCK_NONE}],thinkingConfig:{includeThoughts:!1,thinkingLevel:Ze.MINIMAL}}}))[Symbol.asyncIterator](),Mt=await se.next();return{iterator:se,firstResult:Mt}}})();if(process.stdout.isTTY){let se=(await ps())[c]?.name||"",Mt=se&&!se.startsWith("flow-")&&!se.startsWith("Session ")?se:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${Mt}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${Mt}\x07`)}let{iterator:Ct,firstResult:kn}=await Promise.race([pt,ue]),{value:Yt,done:dt}=kn;if(!dt&&Yt){let ge=Yt.candidates?.[0]?.content?.parts,me=ge?v==="Google"?ge[1]?.text||ge[0]?.text||"":ge.filter(se=>se.text&&!se.thought).map(se=>se.text).join(""):typeof Yt.text=="function"?Yt.text():"";me&&(I+=me),Fe=Yt.usageMetadata;for await(let se of{[Symbol.asyncIterator]:()=>Ct}){let Mt=se.candidates?.[0]?.content?.parts,Un=Mt?v==="Google"?Mt[1]?.text||Mt[0]?.text||"":Mt.filter(Tt=>Tt.text&&!Tt.thought).map(Tt=>Tt.text).join(""):typeof se.text=="function"?se.text():"";Un&&(I+=Un),Fe=se.usageMetadata}}}catch(ue){throw ue}if(I){if(xe=I,Fe){let ue=Fe.totalTokenCount||0,Be=Fe.cachedContentTokenCount||0,Ee=(Fe.candidatesTokenCount||0)+(v==="Google"&&Fe.thoughtsTokenCount||0),pt=te?de("nvidia_janitor_fallback"):v==="DeepSeek"?de("deepseek_fast_fallback"):v==="ExpLabs"||v==="ExperientialLabs"?de("explabs_fallback")||"deepseek-v4-pro-0813":v==="OpenRouter"?de("janitor_open_router"):i||(ve===B?de("janitor_default"):de("gemma_janitor_fallback_google"));await Ft("tokens",ue,v,pt),Be>0&&await Ft("cachedTokens",Be,v,pt),Ee>0&&await Ft("candidateTokens",Ee,v,pt)}}else throw new Error("No synthesis generated by Janitor.");g&&(g(),await At("background"));let K=po(xe),We=!1;for(let ue of K){let Be=ue.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(Be)&&(We=!0);let Ee={chatId:c,sessionId:c,history:s},pt=await go(Be,ue.args,Ee);Be.toLowerCase()==="memory"&&(ue.args.includes("action='user'")||ue.args.includes('action="user"'))&&!pt.startsWith("ERROR")&&(m&&m(),process.stdout.isTTY&&(process.stdout.write("\x1B]0;Memory Updated\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=Memory Updated\x07")),await new Promise(kn=>setTimeout(kn,3e3)))}if(!We)try{let ue=Et(Pn,[]);if(ue.length>0){let Be=[];for(let Ee of ue)Ee.score===void 0&&(Ee.score=.5),Ee.score*=.99995,Ee.score<.05&&(Ee.score=0),Ee.score=Math.round(Ee.score*1e5)/1e5,Ee.score>0&&Be.push(Ee);Yn(Pn,Be)}}catch{}break}catch(I){ve++;let Fe=new Date().toLocaleString(),te=I instanceof Error?(()=>{try{return JSON.parse(JSON.parse(I.message).error.message).error.message}catch{return String(I)}})():String(I);await new Promise(We=>setTimeout(We,1e3));let v=X.join(Sn,"janitor");if(Ne.existsSync(v)||Ne.mkdirSync(v,{recursive:!0}),Ne.appendFileSync(X.join(v,"error.log"),`ERROR [Attempt ${ve}/${B+1}] [${Fe}]: ${te}
628
628
 
629
- `),Se>X)break;let Xe=Math.min(750*Math.pow(2,Se-1),5e3);await new Promise(Ye=>setTimeout(Ye,Xe))}if(Se){let C=J.join(Sn,"janitor");$e.appendFileSync(J.join(C,"error.log"),`-----------------------------------------------------------------------------
629
+ `),ve>B)break;let K=Math.min(750*Math.pow(2,ve-1),5e3);await new Promise(We=>setTimeout(We,K))}if(ve){let I=X.join(Sn,"janitor");Ne.appendFileSync(X.join(I,"error.log"),`-----------------------------------------------------------------------------
630
630
 
631
- `)}if(process.stdout.isTTY)try{let te=(await ps())[c]?.name||"",Y=te&&!te.startsWith("flow-")&&!te.startsWith("Session ")?te:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${Y}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${Y}\x07`)}catch{process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")}},Ba=e=>{let t=Kt(e),n=hs?t:t.replace(Pr,o=>" ".repeat(o.length)).replace($r,o=>" ".repeat(o.length));po.lastIndex=0;let s;for(;(s=po.exec(n))!==null;){let o=s.index+s[0].length-1,l=0,f=null,a=!1,m=!1;for(let g=o;g<n.length;g++){let u=t[g];if(!f&&(u==='"'||u==="'"||u==="`")?(f=u,a=!1):f&&u===f&&!a&&(f=null),!f&&(u==="("?l++:u===")"&&l--,l===0)){let h=g+1;for(;h<n.length&&/\s/.test(n[h]);)h++;if(h<n.length&&n[h]==="]"){m=!0,po.lastIndex=h+1;break}}u==="\\"?a=!a:a=!1}if(!m)return{inside:!0,toolName:s[1],startIndex:s.index,args:t.substring(s.index+s[0].length)}}return{inside:!1}},Fr=(e,t=!0)=>{let n=po;n.lastIndex=0;let s="",o=0,l;for(;(l=n.exec(e))!==null;){let f=e.substring(o,l.index);s+=t&&o===0?Kt(f):f;let a=l.index+l[0].length-1,m=0,g=null,u=-1;for(let h=a;h<e.length;h++){let x=e[h];if(g){if(x===g){let i=0;for(let c=h-1;c>=0&&e[c]==="\\";c--)i++;i%2===0&&(g=null)}}else if(x==='"'||x==="'"||x==="`")g=x;else if(x==="(")m++;else if(x===")"&&(m--,m===0)){let i=h+1;for(;i<e.length&&/\s/.test(e[i]);)i++;if(i<e.length&&e[i]==="]"){u=i;break}}}if(u!==-1)s+="[tool:functions."+l[1]+"()]",o=u+1,n.lastIndex=o;else{s+="[tool:functions."+l[1]+"(",o=e.length;break}}return o<e.length&&(s+=t&&o===0?Kt(e.substring(o)):e.substring(o)),s},Ua=(e,t,n)=>{let s=po;s.lastIndex=0;let o="",l=0,f;for(;(f=s.exec(e))!==null;){let a=e.substring(l,f.index);o+=a.replace(t,n);let m=f.index+f[0].length-1,g=0,u=null,h=-1;for(let x=m;x<e.length;x++){let i=e[x];if(u){if(i===u){let c=0;for(let T=x-1;T>=0&&e[T]==="\\";T--)c++;c%2===0&&(u=null)}}else if(i==='"'||i==="'"||i==="`")u=i;else if(i==="(")g++;else if(i===")"&&(g--,g===0)){let c=x+1;for(;c<e.length&&/\s/.test(e[c]);)c++;if(c<e.length&&e[c]==="]"){h=c;break}}}if(h!==-1)o+=e.substring(f.index,h+1),l=h+1,s.lastIndex=l;else{o+=e.substring(f.index),l=e.length;break}}return l<e.length&&(o+=e.substring(l).replace(t,n)),o},Or=e=>Fr(e,!0),Wa=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(l=>l.charAt(0).toUpperCase()+l.slice(1)).join("");Rr.lastIndex=0;let s=e.replace(Rr,(o,l,f)=>{let a="";try{let u=JSON.parse(f.trim());u&&typeof u=="object"&&(a=Object.entries(u).map(([x,i])=>{let c=typeof i=="string"?i:JSON.stringify(i);return`${x}=${JSON.stringify(c)}`}).join(", "))}catch{let h=[],x=La;x.lastIndex=0;let i;for(;(i=x.exec(f))!==null;){let c=i[1],T=i[2]!==void 0?i[2]:i[0].split(":").slice(1).join(":").trim();h.push(`${c}=${JSON.stringify(T)}`)}h.length>0?a=h.join(", "):a=f.trim()}let m=l.toLowerCase().replace(/_/g,"");return`[tool:functions.${t[m]||n(l)}(${a})]`});return Mr.lastIndex=0,Ir.lastIndex=0,s=s.replace(Mr,""),s=s.replace(Ir,""),s},Ha=/(?:path|query|url|keyword|command|method|title|task|id)\s*=\s*['"`]?\s*\.\.\.\s*['"`]?/i,Ga=/^['"`]?\s*\.\.\.\s*['"`]?$/,bn=e=>{if(e==null)return!1;let t=String(e).trim();return t==="..."||t==="\u2026"||Ga.test(t)},yo=e=>{if(!e)return[];let t=Wa(e),n=Kt(t),s=[],o=hs?n:n.replace(Pr,a=>" ".repeat(a.length)).replace($r,a=>" ".repeat(a.length)),l=Ca;l.lastIndex=0;let f;for(;(f=l.exec(o))!==null;){let a=f[1],m=f.index+f[0].length-1,g=0,u=null,h=-1,x=-1;for(let i=m;i<o.length;i++){let c=n[i];if(u){if(c===u){let T=0;for(let v=i-1;v>=0&&n[v]==="\\";v--)T++;T%2===0&&(u=null)}}else if(c==='"'||c==="'"||c==="`")u=c;else if(c==="(")g++;else if(c===")"&&(g--,g===0)){x=i;let T=i+1;for(;T<o.length&&/\s/.test(o[T]);)T++;if(T<o.length&&o[T]==="]"){h=T;break}}}if(h!==-1){let i=n.substring(m+1,x),c=n.substring(f.index,h+1),T=Z(i);bn(T.path)||bn(T.query)||bn(T.url)||bn(T.keyword)||bn(T.command)||bn(T.method)||bn(T.title)||bn(T.task)||bn(T.id)||Ha.test(i)||s.push({fullMatch:c,toolName:a.trim(),args:i.trim()}),l.lastIndex=h+1}}return s},Jd=(e,t={})=>{if(!e)return null;if(ts=t,Ys=new Lr({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}}}},ns=async(e,t,n,s,o="Fast",l=.75,f="agent")=>$a(async()=>{let{aiProvider:a="Google",apiKey:m,mode:g}=e,u="",h=null,x=typeof n=="string"?[{role:"user",parts:[{text:n}]}]:n,i=new AbortController,c=i.signal,T=setInterval(()=>{wt&&(i.abort(),clearInterval(T))},100);try{let v;a==="Ollama"?v=Hs(m,t,x,s,o,g,dt(t),c,l,systemSettings?.ollamaEndpoint||"Cloud"):a==="OpenRouter"?v=qo(m,t,x,s,o,g,dt(t),c,l):a==="DeepSeek"?v=Vo(m,t,x,s,o,g,dt(t),c,l):a==="Mistral"?v=Ko(m,t,x,s,o,g,dt(t),c,l):a==="NVIDIA"?v=Yo(m,t,x,s,o,g,dt(t),c,l):a==="InferX"?v=zo(m,t,x,s,o,g,dt(t),c,l):a==="SenseNova"?v=Jo(m,t,x,s,o,g,dt(t),c,l):a==="AIHubMix"?v=Xo(m,t,x,s,o,g,dt(t),c,l):a==="Poolside"?v=Qo(m,t,x,s,o,g,dt(t),c,l):a==="9router"||a==="9Router"?v=Zo(m,t,x,s,o,g,dt(t),c,l):a==="ExpLabs"||a==="ExperientialLabs"?v=es(m,t,x,s,o,g,dt(t),c,l):a==="TokenHarbor"||a==="Token Harbor"||a==="tokenharbor"||a==="token_harbor"||a==="thk"?v=Gs(m,t,x,s,o,g,dt(t),c,l):a==="APInex"||a==="apinex"||a==="apx"?v=js(m,t,x,s,o,g,dt(t),c,l):v=await qs(m).models.generateContentStream({model:t,contents:x,config:{systemInstruction:s,temperature:l,thinkingConfig:(()=>{let N=(t||"").toLowerCase(),M=N.includes("gemma-4")||N.startsWith("gemma"),S=N.includes("gemini-3");if(M||S)return M?o.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:Je.MINIMAL}:{includeThoughts:!0,thinkingLevel:Je.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:N.includes("pro")?Je.LOW:Je.MINIMAL,Low:Je.LOW,Medium:Je.MEDIUM,Standard:Je.MEDIUM,High:Je.HIGH,xHigh:Je.HIGH}[o]||Je.MEDIUM};{let I={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[o]||2048;return I===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:I}}})()}},{signal:c});for await(let b of v){if(wt)throw new Error("Subagent task was cancelled.");if(e?.taskId&&typeof jt<"u"){let M=jt.find(S=>S.id===e.taskId);if(M&&M.status==="cancelled")throw new Error("Subagent task was cancelled.")}let R="";if(b.candidates?.[0]?.content?.parts)for(let M of b.candidates[0].content.parts)M.text&&!M.thought&&(u+=M.text,R+=M.text);let N=R?ms(R):0;e&&typeof e.onTokenChunk=="function"&&e.onTokenChunk(R,N),b.usageMetadata&&(h=b.usageMetadata)}}finally{clearInterval(T)}if(h){let v=h.totalTokenCount||0,b=h.cachedContentTokenCount||0,R=(h.candidatesTokenCount||0)+(a==="Google"&&h.thoughtsTokenCount||0);await Ft("tokens",v,a,t),b>0&&await Ft("cachedTokens",b,a,t),R>0&&await Ft("candidateTokens",R,a,t),e&&typeof e.onUsage=="function"&&e.onUsage({totalTokenCount:v,cachedContentTokenCount:b,candidatesTokenCount:R})}return await At("agent",a),{text:u,usageMetadata:h}}),ja=async(e,t,n=null)=>{n=n||Et(Ao,{});try{let{aiProvider:s="Google"}=t;if(Object.values(n).flat().length<=5)return;let l=Object.keys(n).filter(x=>x!==e&&Array.isArray(n[x])&&n[x].length>2);if(l.length===0)return;let f=`You are a silent background process for the FluxFlow CLI Agent.
631
+ `)}if(process.stdout.isTTY)try{let te=(await ps())[c]?.name||"",v=te&&!te.startsWith("flow-")&&!te.startsWith("Session ")?te:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${v}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${v}\x07`)}catch{process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")}},Ba=e=>{let t=Kt(e),n=hs?t:t.replace(Pr,o=>" ".repeat(o.length)).replace($r,o=>" ".repeat(o.length));ho.lastIndex=0;let s;for(;(s=ho.exec(n))!==null;){let o=s.index+s[0].length-1,l=0,f=null,a=!1,m=!1;for(let g=o;g<n.length;g++){let u=t[g];if(!f&&(u==='"'||u==="'"||u==="`")?(f=u,a=!1):f&&u===f&&!a&&(f=null),!f&&(u==="("?l++:u===")"&&l--,l===0)){let h=g+1;for(;h<n.length&&/\s/.test(n[h]);)h++;if(h<n.length&&n[h]==="]"){m=!0,ho.lastIndex=h+1;break}}u==="\\"?a=!a:a=!1}if(!m)return{inside:!0,toolName:s[1],startIndex:s.index,args:t.substring(s.index+s[0].length)}}return{inside:!1}},Fr=(e,t=!0)=>{let n=ho;n.lastIndex=0;let s="",o=0,l;for(;(l=n.exec(e))!==null;){let f=e.substring(o,l.index);s+=t&&o===0?Kt(f):f;let a=l.index+l[0].length-1,m=0,g=null,u=-1;for(let h=a;h<e.length;h++){let x=e[h];if(g){if(x===g){let i=0;for(let c=h-1;c>=0&&e[c]==="\\";c--)i++;i%2===0&&(g=null)}}else if(x==='"'||x==="'"||x==="`")g=x;else if(x==="(")m++;else if(x===")"&&(m--,m===0)){let i=h+1;for(;i<e.length&&/\s/.test(e[i]);)i++;if(i<e.length&&e[i]==="]"){u=i;break}}}if(u!==-1)s+="[tool:functions."+l[1]+"()]",o=u+1,n.lastIndex=o;else{s+="[tool:functions."+l[1]+"(",o=e.length;break}}return o<e.length&&(s+=t&&o===0?Kt(e.substring(o)):e.substring(o)),s},Ua=(e,t,n)=>{let s=ho;s.lastIndex=0;let o="",l=0,f;for(;(f=s.exec(e))!==null;){let a=e.substring(l,f.index);o+=a.replace(t,n);let m=f.index+f[0].length-1,g=0,u=null,h=-1;for(let x=m;x<e.length;x++){let i=e[x];if(u){if(i===u){let c=0;for(let w=x-1;w>=0&&e[w]==="\\";w--)c++;c%2===0&&(u=null)}}else if(i==='"'||i==="'"||i==="`")u=i;else if(i==="(")g++;else if(i===")"&&(g--,g===0)){let c=x+1;for(;c<e.length&&/\s/.test(e[c]);)c++;if(c<e.length&&e[c]==="]"){h=c;break}}}if(h!==-1)o+=e.substring(f.index,h+1),l=h+1,s.lastIndex=l;else{o+=e.substring(f.index),l=e.length;break}}return l<e.length&&(o+=e.substring(l).replace(t,n)),o},Or=e=>Fr(e,!0),Wa=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(l=>l.charAt(0).toUpperCase()+l.slice(1)).join("");Rr.lastIndex=0;let s=e.replace(Rr,(o,l,f)=>{let a="";try{let u=JSON.parse(f.trim());u&&typeof u=="object"&&(a=Object.entries(u).map(([x,i])=>{let c=typeof i=="string"?i:JSON.stringify(i);return`${x}=${JSON.stringify(c)}`}).join(", "))}catch{let h=[],x=La;x.lastIndex=0;let i;for(;(i=x.exec(f))!==null;){let c=i[1],w=i[2]!==void 0?i[2]:i[0].split(":").slice(1).join(":").trim();h.push(`${c}=${JSON.stringify(w)}`)}h.length>0?a=h.join(", "):a=f.trim()}let m=l.toLowerCase().replace(/_/g,"");return`[tool:functions.${t[m]||n(l)}(${a})]`});return Mr.lastIndex=0,Ir.lastIndex=0,s=s.replace(Mr,""),s=s.replace(Ir,""),s},Ha=/(?:path|query|url|keyword|command|method|title|task|id)\s*=\s*['"`]?\s*\.\.\.\s*['"`]?/i,Ga=/^['"`]?\s*\.\.\.\s*['"`]?$/,bn=e=>{if(e==null)return!1;let t=String(e).trim();return t==="..."||t==="\u2026"||Ga.test(t)},po=e=>{if(!e)return[];let t=Wa(e),n=Kt(t),s=[],o=hs?n:n.replace(Pr,a=>" ".repeat(a.length)).replace($r,a=>" ".repeat(a.length)),l=Ca;l.lastIndex=0;let f;for(;(f=l.exec(o))!==null;){let a=f[1],m=f.index+f[0].length-1,g=0,u=null,h=-1,x=-1;for(let i=m;i<o.length;i++){let c=n[i];if(u){if(c===u){let w=0;for(let A=i-1;A>=0&&n[A]==="\\";A--)w++;w%2===0&&(u=null)}}else if(c==='"'||c==="'"||c==="`")u=c;else if(c==="(")g++;else if(c===")"&&(g--,g===0)){x=i;let w=i+1;for(;w<o.length&&/\s/.test(o[w]);)w++;if(w<o.length&&o[w]==="]"){h=w;break}}}if(h!==-1){let i=n.substring(m+1,x),c=n.substring(f.index,h+1),w=Z(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)||Ha.test(i)||s.push({fullMatch:c,toolName:a.trim(),args:i.trim()}),l.lastIndex=h+1}}return s},Qd=(e,t={})=>{if(!e)return null;if(ts=t,Ys=new Lr({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}}}},ns=async(e,t,n,s,o="Fast",l=.75,f="agent")=>$a(async()=>{let{aiProvider:a="Google",apiKey:m,mode:g}=e,u="",h=null,x=typeof n=="string"?[{role:"user",parts:[{text:n}]}]:n,i=new AbortController,c=i.signal,w=setInterval(()=>{wt&&(i.abort(),clearInterval(w))},100);try{let A;a==="Ollama"?A=Hs(m,t,x,s,o,g,ft(t),c,l,systemSettings?.ollamaEndpoint||"Cloud"):a==="OpenRouter"?A=qo(m,t,x,s,o,g,ft(t),c,l):a==="DeepSeek"?A=Vo(m,t,x,s,o,g,ft(t),c,l):a==="Mistral"?A=Ko(m,t,x,s,o,g,ft(t),c,l):a==="NVIDIA"?A=Yo(m,t,x,s,o,g,ft(t),c,l):a==="InferX"?A=zo(m,t,x,s,o,g,ft(t),c,l):a==="SenseNova"?A=Jo(m,t,x,s,o,g,ft(t),c,l):a==="AIHubMix"?A=Xo(m,t,x,s,o,g,ft(t),c,l):a==="Poolside"?A=Qo(m,t,x,s,o,g,ft(t),c,l):a==="9router"||a==="9Router"?A=Zo(m,t,x,s,o,g,ft(t),c,l):a==="ExpLabs"||a==="ExperientialLabs"?A=es(m,t,x,s,o,g,ft(t),c,l):a==="TokenHarbor"||a==="Token Harbor"||a==="tokenharbor"||a==="token_harbor"||a==="thk"?A=Gs(m,t,x,s,o,g,ft(t),c,l):a==="APInex"||a==="apinex"||a==="apx"?A=js(m,t,x,s,o,g,ft(t),c,l):A=await qs(m).models.generateContentStream({model:t,contents:x,config:{systemInstruction:s,temperature:l,thinkingConfig:(()=>{let N=(t||"").toLowerCase(),R=N.includes("gemma-4")||N.startsWith("gemma"),_=N.includes("gemini-3");if(R||_)return R?o.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:Ze.MINIMAL}:{includeThoughts:!0,thinkingLevel:Ze.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:N.includes("pro")?Ze.LOW:Ze.MINIMAL,Low:Ze.LOW,Medium:Ze.MEDIUM,Standard:Ze.MEDIUM,High:Ze.HIGH,xHigh:Ze.HIGH}[o]||Ze.MEDIUM};{let M={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[o]||2048;return M===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:M}}})()}},{signal:c});for await(let b of A){if(wt)throw new Error("Subagent task was cancelled.");if(e?.taskId&&typeof jt<"u"){let R=jt.find(_=>_.id===e.taskId);if(R&&R.status==="cancelled")throw new Error("Subagent task was cancelled.")}let C="";if(b.candidates?.[0]?.content?.parts)for(let R of b.candidates[0].content.parts)R.text&&!R.thought&&(u+=R.text,C+=R.text);let N=C?ms(C):0;e&&typeof e.onTokenChunk=="function"&&e.onTokenChunk(C,N),b.usageMetadata&&(h=b.usageMetadata)}}finally{clearInterval(w)}if(h){let A=h.totalTokenCount||0,b=h.cachedContentTokenCount||0,C=(h.candidatesTokenCount||0)+(a==="Google"&&h.thoughtsTokenCount||0);await Ft("tokens",A,a,t),b>0&&await Ft("cachedTokens",b,a,t),C>0&&await Ft("candidateTokens",C,a,t),e&&typeof e.onUsage=="function"&&e.onUsage({totalTokenCount:A,cachedContentTokenCount:b,candidatesTokenCount:C})}return await At("agent",a),{text:u,usageMetadata:h}}),ja=async(e,t,n=null)=>{n=n||Et(Eo,{});try{let{aiProvider:s="Google"}=t;if(Object.values(n).flat().length<=5)return;let l=Object.keys(n).filter(x=>x!==e&&Array.isArray(n[x])&&n[x].length>2);if(l.length===0)return;let f=`You are a silent background process for the FluxFlow CLI Agent.
632
632
  Your task is to summarize or merge temporary context memories from one or more past conversation sessions.
633
633
  For each Chat ID provided, you must output a tool call to save the consolidated summary.
634
634
 
@@ -643,9 +643,9 @@ Guidelines:
643
643
 
644
644
  Chats to process:
645
645
 
646
- `,a=Et(fs,{});for(let x of l){let c=n[x].map(v=>`- ${v}`).join(`
647
- `),T=a[x];f+=`[Chat ID: ${x}]
648
- `,T?(f+=`- Existing Summary: "${T}"
646
+ `,a=Et(fs,{});for(let x of l){let c=n[x].map(A=>`- ${A}`).join(`
647
+ `),w=a[x];f+=`[Chat ID: ${x}]
648
+ `,w?(f+=`- Existing Summary: "${w}"
649
649
  `,f+=`
650
650
  -- New Memories to integrate:
651
651
  ${c}
@@ -653,10 +653,10 @@ ${c}
653
653
  `):f+=`-- Individual Memories:
654
654
  ${c}
655
655
 
656
- `}let m=0,g=5,u=!1,h=fe("gemma_janitor_fallback_google");for(s==="OpenRouter"&&(h=fe("janitor_open_router")),s==="DeepSeek"&&(h=fe("deepseek_level_1")),s==="Mistral"&&(h=fe("mistral_level_1")),s==="NVIDIA"&&(h=fe("nvidia_janitor_fallback")),s==="InferX"&&(h=fe("inferx_fallback")),s==="SenseNova"&&(h=fe("sensenova_fallback")),s==="AIHubMix"&&(h=fe("aihubmix_fallback")),s==="Poolside"&&(h=fe("poolside_fallback")),(s==="9router"||s==="9Router")&&(h=fe("9router_fallback"));m<=g&&!u;){m++;try{let i=(await ns(t,h,f,null,"Fast",.75,"background")).text||"",c=yo(i);if(c.length===0)throw new Error("No tool calls detected in synthesis response");for(let T of c){let v=T.toolName;["saveSummary","saveSumary","SaveSummary","SaveSumary"].includes(v)&&await mo(v,T.args,{chatId:e})}u=!0}catch(x){if(m>=g)throw new Error(`Failed after ${g} attempts. Last error: ${x.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),l=J.join(Sn,"janitor");$e.existsSync(l)||$e.mkdirSync(l,{recursive:!0}),$e.appendFileSync(J.join(l,"error.log"),`[${new Date().toLocaleString()}] Past memory batch consolidation error: ${o}
657
- `)}},Xd=async(e,t,n=!1)=>{let{chatId:s,aiProvider:o="Google"}=e,l=J.join(Eo,"chat-summaries.json"),f=i=>i.filter(c=>(c.role==="user"||c.role==="agent"||c.role==="system")&&c.role!=="think"&&!c.isVisualFeedback&&!c.isMeta&&!c.isTerminalRecord&&!(c.text&&c.text.includes("[TERMINAL_RECORD]"))&&!String(c.id).startsWith("welcome")).map(c=>{let T=c.fullText||c.text||"",v=c.role==="system"||T.startsWith("[TOOL RESULT]:")||c.text&&c.text.startsWith("[TOOL RESULT]:"),b=T;return v&&(T.includes("[TOOL RESULT]:")||c.text&&c.text.includes("[TOOL RESULT]:"))?b="[TOOL RESULT]: ...truncated for summary":b=b.replace(/(\[(?:tool|agent):[a-zA-Z0-9_\.]+)\([\s\S]*?\)(\])/g,"$1(...)$2"),`[${v?"TOOL":c.role==="agent"?"AGENT":"USER"}]: ${b}`}).join(`
656
+ `}let m=0,g=5,u=!1,h=de("gemma_janitor_fallback_google");for(s==="OpenRouter"&&(h=de("janitor_open_router")),s==="DeepSeek"&&(h=de("deepseek_level_1")),s==="Mistral"&&(h=de("mistral_level_1")),s==="NVIDIA"&&(h=de("nvidia_janitor_fallback")),s==="InferX"&&(h=de("inferx_fallback")),s==="SenseNova"&&(h=de("sensenova_fallback")),s==="AIHubMix"&&(h=de("aihubmix_fallback")),s==="Poolside"&&(h=de("poolside_fallback")),(s==="9router"||s==="9Router")&&(h=de("9router_fallback"));m<=g&&!u;){m++;try{let i=(await ns(t,h,f,null,"Fast",.75,"background")).text||"",c=po(i);if(c.length===0)throw new Error("No tool calls detected in synthesis response");for(let w of c){let A=w.toolName;["saveSummary","saveSumary","SaveSummary","SaveSumary"].includes(A)&&await go(A,w.args,{chatId:e})}u=!0}catch(x){if(m>=g)throw new Error(`Failed after ${g} attempts. Last error: ${x.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),l=X.join(Sn,"janitor");Ne.existsSync(l)||Ne.mkdirSync(l,{recursive:!0}),Ne.appendFileSync(X.join(l,"error.log"),`[${new Date().toLocaleString()}] Past memory batch consolidation error: ${o}
657
+ `)}},Zd=async(e,t,n=!1)=>{let{chatId:s,aiProvider:o="Google"}=e,l=X.join(_o,"chat-summaries.json"),f=i=>i.filter(c=>(c.role==="user"||c.role==="agent"||c.role==="system")&&c.role!=="think"&&!c.isVisualFeedback&&!c.isMeta&&!c.isTerminalRecord&&!(c.text&&c.text.includes("[TERMINAL_RECORD]"))&&!String(c.id).startsWith("welcome")).map(c=>{let w=c.fullText||c.text||"",A=c.role==="system"||w.startsWith("[TOOL RESULT]:")||c.text&&c.text.startsWith("[TOOL RESULT]:"),b=w;return A&&(w.includes("[TOOL RESULT]:")||c.text&&c.text.includes("[TOOL RESULT]:"))?b="[TOOL RESULT]: ...truncated for summary":b=b.replace(/(\[(?:tool|agent):[a-zA-Z0-9_\.]+)\([\s\S]*?\)(\])/g,"$1(...)$2"),`[${A?"TOOL":c.role==="agent"?"AGENT":"USER"}]: ${b}`}).join(`
658
658
 
659
- `),a=async(i,c)=>{let T="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.",v=c?`Here is the previous summary:
659
+ `),a=async(i,c)=>{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.",A=c?`Here is the previous summary:
660
660
  ${c}
661
661
 
662
662
  Here is the new conversation history:
@@ -665,107 +665,107 @@ ${i}
665
665
  Provide a new consolidated summary of the entire session.`:`Here is the conversation history:
666
666
  ${i}
667
667
 
668
- Provide a consolidated summary of the entire session.`,b=fe("gemma_janitor_fallback_google");o==="OpenRouter"&&(b=fe("janitor_open_router")),o==="DeepSeek"&&(b=fe("deepseek_level_1")),o==="Mistral"&&(b=fe("mistral_level_1")),o==="NVIDIA"&&(b=fe("nvidia_chat_summarizer_fallback")),o==="InferX"&&(b=fe("inferx_fallback")),o==="SenseNova"&&(b=fe("sensenova_fallback")),o==="AIHubMix"&&(b=fe("aihubmix_fallback")),o==="Poolside"&&(b=fe("poolside_fallback")),(o==="9router"||o==="9Router")&&(b=fe("9router_fallback")),(o==="ExpLabs"||o==="ExperientialLabs")&&(b=fe("explabs_fallback")||"deepseek-v4-pro-0813"),(o==="TokenHarbor"||o==="Token Harbor"||o==="tokenharbor"||o==="token_harbor"||o==="thk")&&(b=fe("tokenharbor_fallback")||"deepseek-v4.1-flash:free");let R=0,N=!1,M=null;for(;R<=3&&!N;){R++;try{M=await ns(e,b,v,T,"Fast"),N=!0}catch{if(R>3){if(o==="Google")try{let I=fe("general_fallback");return(await ns(e,I,v,T,"Fast")).text||""}catch{return""}return""}}}return M&&M.text||""},m=f(t),g=Et(l,{}),u=g[s]||{summary:"",historyLength:0};typeof u=="string"&&(u={summary:u,historyLength:0});let h=u.summary||"",x=await a(m,h);if(x){u.summary=x;let i=Na(t);return n?u.historyLength=(u.historyLength||0)+i:u.historyLength=i,g[s]=u,Yn(l,g),x}return null},Qd=e=>{try{let t=J.join(Eo,"chat-summaries.json");if($e.existsSync(t)){let n=Et(t,{});n[e]&&(delete n[e],Yn(t,n))}}catch{}},Zd=async function*(e,t,n,s,o){let{profile:l,thinkingLevel:f,mode:a,janitorModel:m,chatId:g,isPlayground:u,systemSettings:h,sessionStats:x,aiProvider:i="Google",apiTier:c,wildcardTooling:T}=n,v=dt(e);if(!Ys&&i==="Google")throw new Error("AI not initialized");let b=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:h?.memory!==!1,R=t[t.length-1].text,N=J.join(Eo,"chat-summaries.json"),M=!1,S=t.filter(w=>w.role==="user").length===1,I=R.includes("[TITLE-UPDATE]"),$=S||I,p=R.replace(/\[TITLE-UPDATE\]/g,"").trim();p=p.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),yield{type:"status",content:"[start]"},yield{type:"status",content:"Gathering Context"},await vo.startTransaction(g,p),h?.advanceRollback&&await so.takeInitialSnapshot(g),wt=!1;let d=null;try{let w=new AbortController;d=setInterval(()=>{wt&&(w.abort(),d&&(clearInterval(d),d=null))},400);let r=[...t.slice(0,-1)];{let Pe=Et(N,{})[g]||{summary:"",historyLength:0};if(Pe.summary&&Pe.historyLength>0){let qt=0,_e=[];for(let nt=0;nt<r.length;nt++){let je=r[nt];(je.role==="user"||je.role==="agent"||je.role==="system")&&!String(je.id).startsWith("welcome")&&!je.isMeta&&qt++,qt>Pe.historyLength&&_e.push(je)}r=_e}}r=r.map(K=>{if(K.role==="user"&&K.text){let Pe=K.text.match(/\[USER\]([\s\S]*?)\[\/USER\]/);if(Pe)return{...K,text:Pe[1].trim()}}return{...K}});let k=process.env.HIGH_CONTEXT,E=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}[h?.contextLength]||256e3;if(k&&k!=="false"){let K=parseInt(k,10);!isNaN(K)&&K>=0&&K<=1e6&&(P=K)}if((i==="NVIDIA"&&(e?.includes("gpt")||e?.includes("qwen")||e?.includes("medium")||e.includes("muse"))||i==="Mistral")&&(P=126e3),i==="Google"&&e?.includes("gemma")&&E&&(P=16e3),(x?.tokens||0)>P){yield{type:"text",content:"\u2726 Maximum Context Limit Reached. Start a new chat."};return}if(S&&b){let K=Et(Ao,{});Object.values(K).flat().length>5&&(yield{type:"status",content:"Condensing past chat memories"},await ja(g,n,K))}let D=Et(Ao,{}),ee=Et(fs,{}),pe=Object.entries(D).filter(([K])=>K!==g).flatMap(([K,Pe])=>Pe),A=[...Object.entries(ee).filter(([K])=>K!==g).slice(-20).map(([K,Pe])=>`[Chat Summary]: ${Pe}`),...pe].map(K=>`- ${K}`).join(`
669
- `),X=Et(Pn,[]).map(K=>`- ${K.memory}`).join(`
670
- `),C=(x?.tokens||0)>=1e4,G=Qi(A,X,b,C),te=new Date,Y=te.getFullYear(),Xe=te.toLocaleString("en-US",{month:"short"}).toUpperCase(),Ye=String(te.getDate()).padStart(2,"0"),Ge=te.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}),ft=`${Y}-${Xe}-${Ye}, ${Ge}`,Qe=`${Ge}`,pt=[".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"],Ct=K=>{try{return $e.readdirSync(K,{withFileTypes:!0})}catch{return[]}},kn=(K,Pe={value:0},qt=1)=>{if(Pe.value>6200||qt>7)return Pe.value;let _e=Ct(K);for(let nt of _e){if(Pe.value>6200)break;pt.includes(nt.name)||nt.name.startsWith(".")||nt.isDirectory()&&(Pe.value++,kn(J.join(K,nt.name),Pe,qt+1))}return Pe.value},Yt=(K,Pe)=>h?.indentationTree!==!1?Bs(K,Pe,1,Ct,pt):Ws(K,Pe,"",1,Ct,pt),ct=kn(process.cwd()),ue=10;ct>3072||ct>2304?ue=1:ct>1536?ue=2:ct>768?ue=3:ct>384?ue=5:ct>192?ue=6:ct>96?ue=7:(ct>48||ct>24)&&(ue=9);let ge=Et(us,{}),ie=ge[g],Mt=ie?ie!==process.cwd():!1;ge[g]=process.cwd(),Yn(us,ge);let Un=Et(N,{}),Tt=Un[g]||{summary:"",historyLength:0};typeof Tt=="string"&&(Tt={summary:Tt,historyLength:0});let Br=t.filter(K=>(K.role==="user"||K.role==="agent"||K.role==="system")&&!String(K.id).startsWith("welcome")&&!K.isMeta).length;Tt.historyLength&&Br<Tt.historyLength&&(Tt.summary="",Tt.historyLength=0,Un[g]=Tt,Yn(N,Un));let xo=typeof Tt=="object"?Tt.summary||"":Tt||"",zs=r.length>0;zs&&xo&&r[0]&&(r[0].role==="user"||r[0].role==="system")&&(r[0].text.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")||(r[0].text=`[SYSTEM METADATA]
668
+ Provide a consolidated summary of the entire session.`,b=de("gemma_janitor_fallback_google");o==="OpenRouter"&&(b=de("janitor_open_router")),o==="DeepSeek"&&(b=de("deepseek_level_1")),o==="Mistral"&&(b=de("mistral_level_1")),o==="NVIDIA"&&(b=de("nvidia_chat_summarizer_fallback")),o==="InferX"&&(b=de("inferx_fallback")),o==="SenseNova"&&(b=de("sensenova_fallback")),o==="AIHubMix"&&(b=de("aihubmix_fallback")),o==="Poolside"&&(b=de("poolside_fallback")),(o==="9router"||o==="9Router")&&(b=de("9router_fallback")),(o==="ExpLabs"||o==="ExperientialLabs")&&(b=de("explabs_fallback")||"deepseek-v4-pro-0813"),(o==="TokenHarbor"||o==="Token Harbor"||o==="tokenharbor"||o==="token_harbor"||o==="thk")&&(b=de("tokenharbor_fallback")||"deepseek-v4.1-flash:free");let C=0,N=!1,R=null;for(;C<=3&&!N;){C++;try{R=await ns(e,b,A,w,"Fast"),N=!0}catch{if(C>3){if(o==="Google")try{let M=de("general_fallback");return(await ns(e,M,A,w,"Fast")).text||""}catch{return""}return""}}}return R&&R.text||""},m=f(t),g=Et(l,{}),u=g[s]||{summary:"",historyLength:0};typeof u=="string"&&(u={summary:u,historyLength:0});let h=u.summary||"",x=await a(m,h);if(x){u.summary=x;let i=Na(t);return n?u.historyLength=(u.historyLength||0)+i:u.historyLength=i,g[s]=u,Yn(l,g),x}return null},ef=e=>{try{let t=X.join(_o,"chat-summaries.json");if(Ne.existsSync(t)){let n=Et(t,{});n[e]&&(delete n[e],Yn(t,n))}}catch{}},tf=async function*(e,t,n,s,o){let{profile:l,thinkingLevel:f,mode:a,janitorModel:m,chatId:g,isPlayground:u,systemSettings:h,sessionStats:x,aiProvider:i="Google",apiTier:c,wildcardTooling:w}=n,A=ft(e);if(!Ys&&i==="Google")throw new Error("AI not initialized");let b=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:h?.memory!==!1,C=t[t.length-1].text,N=X.join(_o,"chat-summaries.json"),R=!1,_=t.filter(T=>T.role==="user").length===1,M=C.includes("[TITLE-UPDATE]"),$=_||M,p=C.replace(/\[TITLE-UPDATE\]/g,"").trim();p=p.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),yield{type:"status",content:"[start]"},yield{type:"status",content:"Gathering Context"},await vo.startTransaction(g,p),h?.advanceRollback&&await oo.takeInitialSnapshot(g),wt=!1;let d=null;try{let T=new AbortController;d=setInterval(()=>{wt&&(T.abort(),d&&(clearInterval(d),d=null))},400);let r=[...t.slice(0,-1)];{let $e=Et(N,{})[g]||{summary:"",historyLength:0};if($e.summary&&$e.historyLength>0){let qt=0,_e=[];for(let ot=0;ot<r.length;ot++){let ze=r[ot];(ze.role==="user"||ze.role==="agent"||ze.role==="system")&&!String(ze.id).startsWith("welcome")&&!ze.isMeta&&qt++,qt>$e.historyLength&&_e.push(ze)}r=_e}}r=r.map(V=>{if(V.role==="user"&&V.text){let $e=V.text.match(/\[USER\]([\s\S]*?)\[\/USER\]/);if($e)return{...V,text:$e[1].trim()}}return{...V}});let k=process.env.HIGH_CONTEXT,E=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}[h?.contextLength]||256e3;if(k&&k!=="false"){let V=parseInt(k,10);!isNaN(V)&&V>=0&&V<=1e6&&(P=V)}if((i==="NVIDIA"&&(e?.includes("gpt")||e?.includes("qwen")||e?.includes("medium")||e.includes("muse"))||i==="Mistral")&&(P=126e3),i==="Google"&&e?.includes("gemma")&&E&&(P=16e3),(x?.tokens||0)>P){yield{type:"text",content:"\u2726 Maximum Context Limit Reached. Start a new chat."};return}if(_&&b){let V=Et(Eo,{});Object.values(V).flat().length>5&&(yield{type:"status",content:"Condensing past chat memories"},await ja(g,n,V))}let D=Et(Eo,{}),J=Et(fs,{}),fe=Object.entries(D).filter(([V])=>V!==g).flatMap(([V,$e])=>$e),xe=[...Object.entries(J).filter(([V])=>V!==g).slice(-20).map(([V,$e])=>`[Chat Summary]: ${$e}`),...fe].map(V=>`- ${V}`).join(`
669
+ `),B=Et(Pn,[]).map(V=>`- ${V.memory}`).join(`
670
+ `),I=(x?.tokens||0)>=1e4,Fe=Qi(xe,B,b,I),te=new Date,v=te.getFullYear(),K=te.toLocaleString("en-US",{month:"short"}).toUpperCase(),We=String(te.getDate()).padStart(2,"0"),ue=te.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}),Be=`${v}-${K}-${We}, ${ue}`,Ee=`${ue}`,pt=[".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"],Ct=V=>{try{return Ne.readdirSync(V,{withFileTypes:!0})}catch{return[]}},kn=(V,$e={value:0},qt=1)=>{if($e.value>6200||qt>7)return $e.value;let _e=Ct(V);for(let ot of _e){if($e.value>6200)break;pt.includes(ot.name)||ot.name.startsWith(".")||ot.isDirectory()&&($e.value++,kn(X.join(V,ot.name),$e,qt+1))}return $e.value},Yt=(V,$e)=>h?.indentationTree!==!1?Bs(V,$e,1,Ct,pt):Ws(V,$e,"",1,Ct,pt),dt=kn(process.cwd()),ge=10;dt>3072||dt>2304?ge=1:dt>1536?ge=2:dt>768?ge=3:dt>384?ge=5:dt>192?ge=6:dt>96?ge=7:(dt>48||dt>24)&&(ge=9);let me=Et(us,{}),se=me[g],Mt=se?se!==process.cwd():!1;me[g]=process.cwd(),Yn(us,me);let Un=Et(N,{}),Tt=Un[g]||{summary:"",historyLength:0};typeof Tt=="string"&&(Tt={summary:Tt,historyLength:0});let Br=t.filter(V=>(V.role==="user"||V.role==="agent"||V.role==="system")&&!String(V.id).startsWith("welcome")&&!V.isMeta).length;Tt.historyLength&&Br<Tt.historyLength&&(Tt.summary="",Tt.historyLength=0,Un[g]=Tt,Yn(N,Un));let yo=typeof Tt=="object"?Tt.summary||"":Tt||"",zs=r.length>0;zs&&yo&&r[0]&&(r[0].role==="user"||r[0].role==="system")&&(r[0].text.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")||(r[0].text=`[SYSTEM METADATA]
671
671
  **CONTEXT SUMMARY OF PREVIOUS TURNS (PRIORITY: DYNAMIC)**
672
- ${xo}
672
+ ${yo}
673
673
 
674
- [USER] ${r[0].text}`,yield{type:"summary_injected",content:{id:r[0].id,text:r[0].text}}));let os=xo&&!zs?`
674
+ [USER] ${r[0].text}`,yield{type:"summary_injected",content:{id:r[0].id,text:r[0].text}}));let os=yo&&!zs?`
675
675
  [SYSTEM METADATA]
676
676
  **CONTEXT SUMMARY OF PREVIOUS TURNS**
677
- ${xo}
677
+ ${yo}
678
678
  `:"",Js=!!h?.dynamicDirAwareness,Ur=`${g}|${i}|${f}|${e}|${l}|${Js}`,Xs=!Js&&Fn.key===Ur&&Fn.value?"":`
679
679
  **Directory Structure**
680
680
  CWD: `+process.cwd()+`${u?" [PLAYGROUND MODE]":""}
681
- `+Yt(process.cwd(),ue),mt=await $n(),fn="";if(Go()&&mt.file_focused!=="none"){fn=`
681
+ `+Yt(process.cwd(),ge),mt=await $n(),fn="";if(Go()&&mt.file_focused!=="none"){fn=`
682
682
  [Additional IDE Context]
683
- `;let K=J.relative(process.cwd(),mt.file_focused),Pe=(mt.opened_editors||[]).map(_e=>{let nt=J.relative(process.cwd(),_e);return nt.startsWith("..")?`[External] ${J.basename(_e)}`:nt});if(fn+=`Focused File: ${K}
683
+ `;let V=X.relative(process.cwd(),mt.file_focused),$e=(mt.opened_editors||[]).map(_e=>{let ot=X.relative(process.cwd(),_e);return ot.startsWith("..")?`[External] ${X.basename(_e)}`:ot});if(fn+=`Focused File: ${V}
684
684
  Cursor Line: ${mt.cursor_line}
685
- `,mt.selected){let _e=mt.selected,nt=_e.split(`
686
- `);nt.length>256&&(_e=nt.slice(0,240).join(`
685
+ `,mt.selected){let _e=mt.selected,ot=_e.split(`
686
+ `);ot.length>256&&(_e=ot.slice(0,240).join(`
687
687
  `)+`
688
688
  ... [truncated] ...
689
- `+nt.slice(-16).join(`
689
+ `+ot.slice(-16).join(`
690
690
  `)),_e.length>2048&&(_e=_e.slice(0,1920)+`
691
691
  ... [truncated] ...
692
692
  `+_e.slice(-128)),fn+=`Current Selection: "${_e}"
693
- `}if(mt.manual_edits){let nt=mt.manual_edits.split(`
694
- `),je=[],Ze=null;for(let j of nt)j.trim()&&(j.startsWith(" Line ")?Ze&&Ze.edits.push(j):(Ze={path:j.endsWith(":")?j.slice(0,-1):j,edits:[]},je.push(Ze)));for(let j of je)j.edits.length>80&&(j.edits=j.edits.slice(-80)),j.originalEditsCount=j.edits.length;let le=(j,Q)=>Q.reduce((Ve,Xt)=>{let on=mt.file_focused&&(Xt.path===mt.file_focused||J.resolve(process.cwd(),Xt.path)===J.resolve(mt.file_focused))?Math.ceil(j*1.2):j;return Ve+Math.min(Xt.edits.length,on)},0),It=80;if(le(80,je)>300){let j=!1;for(let Q=80;Q>=10;Q--)if(le(Q,je)<=300){It=Q,j=!0;break}j||(It=10)}let et=[...je];if(It===10&&le(10,et)>500)for(;et.length>0&&le(10,et)>500;){let j=0,Q=et[0].originalEditsCount;for(let Ve=1;Ve<et.length;Ve++)et[Ve].originalEditsCount<Q&&(Q=et[Ve].originalEditsCount,j=Ve);et.splice(j,1)}for(let j of et){let Ve=mt.file_focused&&(j.path===mt.file_focused||J.resolve(process.cwd(),j.path)===J.resolve(mt.file_focused))?Math.ceil(It*1.2):It;j.edits.length>Ve&&(j.edits=j.edits.slice(-Ve))}for(let j of et){let Q=`${j.path}:
695
- ${j.edits.join(`
696
- `)}`;for(;j.edits.length>0&&Q.length>4*768;)j.edits.shift(),Q=`${j.path}:
697
- ${j.edits.join(`
698
- `)}`;Q.length>4*768?j.stringRepresentation="... "+Q.slice(-(4*768-4)):j.stringRepresentation=Q}let zt=et.map(j=>j.stringRepresentation).join(`
699
- `);for(;et.length>0&&zt.length>4*2048;){et[0].edits.length>0?et[0].edits.shift():et.shift();for(let j of et){let Q=`${j.path}:
700
- ${j.edits.join(`
701
- `)}`;Q.length>4*768?j.stringRepresentation="... "+Q.slice(-(4*768-4)):j.stringRepresentation=Q}zt=et.map(j=>j.stringRepresentation).join(`
693
+ `}if(mt.manual_edits){let ot=mt.manual_edits.split(`
694
+ `),ze=[],et=null;for(let G of ot)G.trim()&&(G.startsWith(" Line ")?et&&et.edits.push(G):(et={path:G.endsWith(":")?G.slice(0,-1):G,edits:[]},ze.push(et)));for(let G of ze)G.edits.length>80&&(G.edits=G.edits.slice(-80)),G.originalEditsCount=G.edits.length;let le=(G,Q)=>Q.reduce((Je,Xt)=>{let on=mt.file_focused&&(Xt.path===mt.file_focused||X.resolve(process.cwd(),Xt.path)===X.resolve(mt.file_focused))?Math.ceil(G*1.2):G;return Je+Math.min(Xt.edits.length,on)},0),It=80;if(le(80,ze)>300){let G=!1;for(let Q=80;Q>=10;Q--)if(le(Q,ze)<=300){It=Q,G=!0;break}G||(It=10)}let tt=[...ze];if(It===10&&le(10,tt)>500)for(;tt.length>0&&le(10,tt)>500;){let G=0,Q=tt[0].originalEditsCount;for(let Je=1;Je<tt.length;Je++)tt[Je].originalEditsCount<Q&&(Q=tt[Je].originalEditsCount,G=Je);tt.splice(G,1)}for(let G of tt){let Je=mt.file_focused&&(G.path===mt.file_focused||X.resolve(process.cwd(),G.path)===X.resolve(mt.file_focused))?Math.ceil(It*1.2):It;G.edits.length>Je&&(G.edits=G.edits.slice(-Je))}for(let G of tt){let Q=`${G.path}:
695
+ ${G.edits.join(`
696
+ `)}`;for(;G.edits.length>0&&Q.length>4*768;)G.edits.shift(),Q=`${G.path}:
697
+ ${G.edits.join(`
698
+ `)}`;Q.length>4*768?G.stringRepresentation="... "+Q.slice(-(4*768-4)):G.stringRepresentation=Q}let zt=tt.map(G=>G.stringRepresentation).join(`
699
+ `);for(;tt.length>0&&zt.length>4*2048;){tt[0].edits.length>0?tt[0].edits.shift():tt.shift();for(let G of tt){let Q=`${G.path}:
700
+ ${G.edits.join(`
701
+ `)}`;Q.length>4*768?G.stringRepresentation="... "+Q.slice(-(4*768-4)):G.stringRepresentation=Q}zt=tt.map(G=>G.stringRepresentation).join(`
702
702
  `)}zt.length>4*2048&&(zt="... "+zt.slice(-(4*2048-4))),fn+=`Recent Manual Edits:
703
703
  ${zt}
704
- `}Pe.length>0&&(fn+=`All Opened Editors: ${Pe.join(", ")}`),mt.diagnostics&&(fn+=`
704
+ `}$e.length>0&&(fn+=`All Opened Editors: ${$e.join(", ")}`),mt.diagnostics&&(fn+=`
705
705
  **Active File Errors**:
706
706
  ${mt.diagnostics}
707
707
  `),(p.toLowerCase().includes("lint")||p.toLowerCase().includes("warning"))&&mt.warnings&&(fn+=`
708
708
  **Lint Warnings**:
709
709
  ${mt.warnings}
710
- `)}let Qs=p.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),Zs=/(?:\\)?@\[([^\]]+)\]/g,ss,is=[];for(Zs.lastIndex=0;(ss=Zs.exec(Qs))!==null;){let K=ss[0].startsWith("\\");is.push({tag:ss[1],isEscaped:K})}let rs=[],bo=null;for(let K=0;K<is.length;K++){let{tag:Pe,isEscaped:qt}=is[K];if(!qt)try{let _e=Pe.trim().replace(/^["']|["']$/g,""),nt=/[:#]L?(\d+)(?:-L?(\d+))?$/i,je=_e.match(nt),Ze=_e,le=null,It=null;je&&(le=parseInt(je[1],10),It=je[2]?parseInt(je[2],10):le,Ze=_e.slice(0,je.index));let et=J.resolve(process.cwd(),Ze);if($e.existsSync(et)&&$e.statSync(et).isFile()){let j=Ze.toLowerCase(),Q=j.endsWith(".pdf"),Ve=j.endsWith(".docx")||j.endsWith(".doc")||j.endsWith(".ppt")||j.endsWith(".pptx")||j.endsWith(".xls")||j.endsWith(".xlsx"),Xt=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(j),Dt=Xt||Q||Ve,on=i==="Google"||dt(e);if(Dt&&!on){let Be=`\u2718 Unsupported Modality: ${J.basename(Ze)}`,me=115;process.stdout.isTTY&&(me=process.stdout.columns-5||120);let Ue=[Be],Mn=Math.max(...Ue.map(wn=>wn.length)),Qt=Math.min(Mn+4,me),Qn=Ue.map(wn=>`${wn.padEnd(Qt-2).substring(0,Qt-2)}`).join(`
711
- `);yield{type:"visual_feedback",content:Vt(`${Qn}
712
- `)};continue}if(le===null&&!Dt){let Be=0;try{Be=$e.readFileSync(et,"utf8").split(/\r\n|\r|\n/).length}catch{}if(Be>300){let me=`\u21B7 Skipped (Too Large): ${J.basename(Ze)}`,Ue=115;process.stdout.isTTY&&(Ue=process.stdout.columns-5||120);let Mn=Math.min(me.length+4,Ue),Qt=me.padEnd(Mn-2).substring(0,Mn-2);yield{type:"visual_feedback",content:Vt(`${Qt}
713
- `)};continue}}let gn=le!==null?le:1,vn=It!==null?It:le!==null?le:gn+299;vn-gn>300&&(vn=gn+300);let To=`path=${JSON.stringify(Ze)}, startLine=${gn}, endLine=${vn}`,st=await hi(To,{isMultiModal:on}),qe=!1,Ot="",Rn=null;if(typeof st=="string"?st.trim().startsWith("ERROR")?qe=!0:Ot=st:st&&typeof st=="object"&&st.binaryPart?(Rn=st.binaryPart,Ot=st.text||""):qe=!0,!qe){let Be="";if(Xt?(Be=`\u2714 Processed: ${J.basename(Ze)}`,bo=Rn):Q||Ve?(Be=`\u2714 Auto-Analysed: ${J.basename(Ze)}`,bo=Rn):(Be=`\u2714 Auto-Read: ${J.basename(Ze)}`,rs.push(Ot)),Be){let me=115;process.stdout.isTTY&&(me=process.stdout.columns-5||120);let Ue=[Be],Mn=Math.max(...Ue.map(wn=>wn.length)),Qt=Math.min(Mn+4,me),Qn=Ue.map(wn=>`${wn.padEnd(Qt-2).substring(0,Qt-2)}`).join(`
714
- `);yield{type:"visual_feedback",content:Vt(`${Qn}
710
+ `)}let Qs=p.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),Zs=/(?:\\)?@\[([^\]]+)\]/g,ss,is=[];for(Zs.lastIndex=0;(ss=Zs.exec(Qs))!==null;){let V=ss[0].startsWith("\\");is.push({tag:ss[1],isEscaped:V})}let rs=[],xo=null;for(let V=0;V<is.length;V++){let{tag:$e,isEscaped:qt}=is[V];if(!qt)try{let _e=$e.trim().replace(/^["']|["']$/g,""),ot=/[:#]L?(\d+)(?:-L?(\d+))?$/i,ze=_e.match(ot),et=_e,le=null,It=null;ze&&(le=parseInt(ze[1],10),It=ze[2]?parseInt(ze[2],10):le,et=_e.slice(0,ze.index));let tt=X.resolve(process.cwd(),et);if(Ne.existsSync(tt)&&Ne.statSync(tt).isFile()){let G=et.toLowerCase(),Q=G.endsWith(".pdf"),Je=G.endsWith(".docx")||G.endsWith(".doc")||G.endsWith(".ppt")||G.endsWith(".pptx")||G.endsWith(".xls")||G.endsWith(".xlsx"),Xt=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(G),Dt=Xt||Q||Je,on=i==="Google"||ft(e);if(Dt&&!on){let je=`\u2718 Unsupported Modality: ${X.basename(et)}`,he=115;process.stdout.isTTY&&(he=process.stdout.columns-5||120);let Ve=[je],Mn=Math.max(...Ve.map(wn=>wn.length)),Qt=Math.min(Mn+4,he),Xn=Ve.map(wn=>`${wn.padEnd(Qt-2).substring(0,Qt-2)}`).join(`
711
+ `);yield{type:"visual_feedback",content:Vt(`${Xn}
712
+ `)};continue}if(le===null&&!Dt){let je=0;try{je=Ne.readFileSync(tt,"utf8").split(/\r\n|\r|\n/).length}catch{}if(je>300){let he=`\u21B7 Skipped (Too Large): ${X.basename(et)}`,Ve=115;process.stdout.isTTY&&(Ve=process.stdout.columns-5||120);let Mn=Math.min(he.length+4,Ve),Qt=he.padEnd(Mn-2).substring(0,Mn-2);yield{type:"visual_feedback",content:Vt(`${Qt}
713
+ `)};continue}}let gn=le!==null?le:1,vn=It!==null?It:le!==null?le:gn+299;vn-gn>300&&(vn=gn+300);let wo=`path=${JSON.stringify(et)}, startLine=${gn}, endLine=${vn}`,it=await hi(wo,{isMultiModal:on}),Qe=!1,Ot="",Rn=null;if(typeof it=="string"?it.trim().startsWith("ERROR")?Qe=!0:Ot=it:it&&typeof it=="object"&&it.binaryPart?(Rn=it.binaryPart,Ot=it.text||""):Qe=!0,!Qe){let je="";if(Xt?(je=`\u2714 Processed: ${X.basename(et)}`,xo=Rn):Q||Je?(je=`\u2714 Auto-Analysed: ${X.basename(et)}`,xo=Rn):(je=`\u2714 Auto-Read: ${X.basename(et)}`,rs.push(Ot)),je){let he=115;process.stdout.isTTY&&(he=process.stdout.columns-5||120);let Ve=[je],Mn=Math.max(...Ve.map(wn=>wn.length)),Qt=Math.min(Mn+4,he),Xn=Ve.map(wn=>`${wn.padEnd(Qt-2).substring(0,Qt-2)}`).join(`
714
+ `);yield{type:"visual_feedback",content:Vt(`${Xn}
715
715
  `)}}}}}catch{}}let as="";rs.length>0&&(as=`[Tagged File Contents] Auto Read User Tagged files by System, No need to re-read
716
716
  `+rs.join(`
717
717
 
718
718
  `)+`
719
719
  [Tagged File Contents]
720
- `);let ei=Qs.replace(/\\(@\[[^\]]+\])/g,"$1"),ti=T?`You cannot execute tools
720
+ `);let ei=Qs.replace(/\\(@\[[^\]]+\])/g,"$1"),ti=w?`You cannot execute tools
721
721
  Instead, output in chat the exact string you WOULD have produced & wait for system response
722
- `:"",Wr=process.env.forcedReasoning||!1,ni=f!=="Fast"&&(i==="Mistral"&&!qn(e)||f!=="High"&&i==="Google")?`${i==="Mistral"&&!qn(e)||e.toLowerCase().startsWith("gemma")||Wr?`[system] strictly follow thinking policy as high priority. do not start a response without <think>...</think> [/system]
723
- `:""}`:"",ko="",oi=!!h?.autoExcludeMetadata,Hr=!!(fn||as||ti||os||G||ni||Mt||h?.dynamicDirAwareness||h?.autoTruncateResults||b);oi&&!Hr?ko=ei.trim():ko=`[System Metadata]
724
- Time: ${oi?Qe:ft}${h?.dynamicDirAwareness?Xs:""}${Mt?`
725
- WARNING: CWD Changed from previous: "${ie}" to current: "${process.cwd()}", write change in chat to avoid future path mismatches
726
- `:""}${G}${fn}
722
+ `:"",Wr=process.env.forcedReasoning||!1,ni=f!=="Fast"&&(i==="Mistral"&&!Co(e)||f!=="High"&&i==="Google")?`${i==="Mistral"&&!Co(e)||e.toLowerCase().startsWith("gemma")||Wr?`[system] strictly follow thinking policy as high priority. do not start a response without <think>...</think> [/system]
723
+ `:""}`:"",bo="",oi=!!h?.autoExcludeMetadata,Hr=!!(fn||as||ti||os||Fe||ni||Mt||h?.dynamicDirAwareness||h?.autoTruncateResults||b);oi&&!Hr?bo=ei.trim():bo=`[System Metadata]
724
+ Time: ${oi?Ee:Be}${h?.dynamicDirAwareness?Xs:""}${Mt?`
725
+ WARNING: CWD Changed from previous: "${se}" to current: "${process.cwd()}", write change in chat to avoid future path mismatches
726
+ `:""}${Fe}${fn}
727
727
  [/Metadata]
728
728
  ${os}${ni}[system] exact tool string [tool:functions.ToolName(arg="value")] in chat [/system]
729
- ${as}${ti}[user prompt] ${ei.trim()} [/user prompt]`.trim();let si={role:"user",text:ko};bo&&(si.binaryPart=bo),r.forEach(K=>{K.text&&K.role==="agent"&&(K.text=Kt(K.text))}),r.push(si),os&&t[t.length-1]?.id&&(yield{type:"summary_injected",content:{id:t[t.length-1].id,text:ko}});let un=null,Xn=a==="Flux"?200:15;Xn=a.toLowerCase().includes("cu")?300:Xn;let nn=16;yield{type:"status",content:"Connecting"},wt=!1;let ii=[],wo=!1;for(let K=0;K<=Xn;K++){let Pe=await ai("agent",n);if(!Pe.allowed)throw new Error(Pe.reason||`Budget Exhausted for Provider (${i||"Agent"})`);let qt=[];if(wo=!1,a==="ICU"||a==="FluxCU")try{yield{type:"status",content:"Capturing Screen"},await new Promise(re=>setTimeout(re,1e3));let{captureGriddedScreenshot:xe}=await import("./screen_grid-TDQC6CV5.js"),Ee=await xe();if(Ee&&Ee.base64){let re="[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:Ee.mimeType,data:Ee.base64}},vt=h?.imageHistoryCU||"Standard",St=vt==="Low"?1:vt==="Extended"?5:3,Jt=r.filter(We=>Array.isArray(We.parts)&&We.parts.some(Pt=>Pt.inlineData));if(Jt.length>=St){let We=Jt.length-St+1;for(let Pt=0;Pt<We;Pt++){let _t=Jt[Pt];Array.isArray(_t.parts)&&(_t.parts=_t.parts.filter(yt=>!yt.inlineData))}}if(r.length>0&&r[r.length-1].role==="user"){let We=r[r.length-1];typeof We.text=="string"&&(We.text+=`
729
+ ${as}${ti}[user prompt] ${ei.trim()} [/user prompt]`.trim();let si={role:"user",text:bo};xo&&(si.binaryPart=xo),r.forEach(V=>{V.text&&V.role==="agent"&&(V.text=Kt(V.text))}),r.push(si),os&&t[t.length-1]?.id&&(yield{type:"summary_injected",content:{id:t[t.length-1].id,text:bo}});let un=null,Jn=a==="Flux"?200:15;Jn=a.toLowerCase().includes("cu")?300:Jn;let nn=16;yield{type:"status",content:"Connecting"},wt=!1;let ii=[],ko=!1;for(let V=0;V<=Jn;V++){let $e=await ai("agent",n);if(!$e.allowed)throw new Error($e.reason||`Budget Exhausted for Provider (${i||"Agent"})`);let qt=[];if(ko=!1,a==="ICU"||a==="FluxCU")try{yield{type:"status",content:"Capturing Screen"},await new Promise(ie=>setTimeout(ie,1e3));let{captureGriddedScreenshot:be}=await import("./screen_grid-TDQC6CV5.js"),Ae=await be();if(Ae&&Ae.base64){let ie="[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}},vt=h?.imageHistoryCU||"Standard",St=vt==="Low"?1:vt==="Extended"?5:3,Jt=r.filter(Ke=>Array.isArray(Ke.parts)&&Ke.parts.some(Pt=>Pt.inlineData));if(Jt.length>=St){let Ke=Jt.length-St+1;for(let Pt=0;Pt<Ke;Pt++){let _t=Jt[Pt];Array.isArray(_t.parts)&&(_t.parts=_t.parts.filter(yt=>!yt.inlineData))}}if(r.length>0&&r[r.length-1].role==="user"){let Ke=r[r.length-1];typeof Ke.text=="string"&&(Ke.text+=`
730
730
 
731
- ${re}`,Array.isArray(We.parts)||(We.parts=[{text:We.text}]),We.parts.push(Lt))}else r.push({role:"user",text:re,parts:[{text:re},Lt]})}}catch(xe){console.error("Vision screenshot capture error:",xe)}if(h?.compression===0&&(x?.tokens||0)>P&&(r=mi(r,6)),K>0?yield{type:"status",content:"Working"}:yield{type:"status",content:"Connecting"},wt){try{let{clearPendingNudges:xe}=await import("./subagent_state-LZCOZSUJ.js");xe()}catch{}yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
731
+ ${ie}`,Array.isArray(Ke.parts)||(Ke.parts=[{text:Ke.text}]),Ke.parts.push(Lt))}else r.push({role:"user",text:ie,parts:[{text:ie},Lt]})}}catch(be){console.error("Vision screenshot capture error:",be)}if(h?.compression===0&&(x?.tokens||0)>P&&(r=mi(r,6)),V>0?yield{type:"status",content:"Working"}:yield{type:"status",content:"Connecting"},wt){try{let{clearPendingNudges:be}=await import("./subagent_state-LZCOZSUJ.js");be()}catch{}yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
732
732
 
733
- \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}try{let{consumePendingNudges:xe}=await import("./subagent_state-LZCOZSUJ.js"),Ee=xe();if(Ee&&Ee.length>0){let re=Ee.join(`
733
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}try{let{consumePendingNudges:be}=await import("./subagent_state-LZCOZSUJ.js"),Ae=be();if(Ae&&Ae.length>0){let ie=Ae.join(`
734
734
 
735
735
  `);r.length>0&&r[r.length-1].role==="user"?r[r.length-1].text+=`
736
736
 
737
- ${re}`:r.push({role:"user",text:re}),yield{type:"status",content:"Subagent Update"}}}catch{}if(s){let xe=await s();xe&&(xe.startsWith("/btw")?r.length>0&&r[r.length-1].role==="user"?r[r.length-1].text+=`
737
+ ${ie}`:r.push({role:"user",text:ie}),yield{type:"status",content:"Subagent Update"}}}catch{}if(s){let be=await s();be&&(be.startsWith("/btw")?r.length>0&&r[r.length-1].role==="user"?r[r.length-1].text+=`
738
738
 
739
739
  [system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
740
- [question] ${xe.replace("/btw","").trim()} [/question]`:r.push({role:"user",text:`[system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
741
- [question] ${xe.replace("/btw","").trim()} [/question]`}):r.length>0&&r[r.length-1].role==="user"?r[r.length-1].text+=`
740
+ [question] ${be.replace("/btw","").trim()} [/question]`:r.push({role:"user",text:`[system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
741
+ [question] ${be.replace("/btw","").trim()} [/question]`}):r.length>0&&r[r.length-1].role==="user"?r[r.length-1].text+=`
742
742
 
743
- [STEERING HINT from USER, High Priority] ${xe.trim()} [/STEERING HINT]`:r.push({role:"user",text:`[STEERING HINT from USER, High Priority] ${xe.trim()} [/STEERING HINT]`}),yield{type:"status",content:`${xe.startsWith("/btw")?"Question Forwarded...":"Steering Hint Injected..."}`})}let _e,nt=!1,je=1,Ze=1,le="",It=null,et=null,zt=null,j=0,Q=[],Ve=0,Xt=!1,Dt=!1,on=!1,gn=!1,vn=!0,To=0,st="",qe="",Ot=!1,Rn=!1,Be=!0,me=e,Ue="";for(;je<=nn&&Ze<=nn&&!nt&&!wt;){let xe=!1;try{le="",vn&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},vn=!1,Ze===1&&(st=""));let Ee=L=>{if(!L||!L.includes("[tool:"))return L;let se="",F=Vs(L);F&&(se=F.fullBlock,L=F.remainingText),L=L.replace(Pa,(be,he)=>he.includes("[tool:")?he.trim():be);let H="",we=0;for(;we<L.length;){let be=L.indexOf("[tool:",we);if(be===-1){H+=Dr(L.substring(we));break}let he=L.substring(we,be);H+=Dr(he);let Ke=-1,W=null,ne=0;for(let Ne=be;Ne<L.length;Ne++){let y=L[Ne];if(W){if(y===W){let Fe=0;for(let Re=Ne-1;Re>=0&&L[Re]==="\\";Re--)Fe++;Fe%2===0&&(W=null)}}else if(y==='"'||y==="'"||y==="`")W=y;else if(y==="(")ne++;else if(y===")")ne--;else if(y==="]"&&ne<=0){Ke=Ne;break}}if(Ke===-1){H+=L.substring(be);break}H+=L.substring(be,Ke+1),we=Ke+1}return(h?.keepReasoningContext?se:"")+H},re=r.filter(L=>(L.role==="user"||L.role==="agent"||L.role==="system")&&!String(L.id).startsWith("welcome")&&!L.isMeta&&!L.isTerminalRecord&&!(L.text&&L.text.startsWith("[TERMINAL_RECORD]"))).map((L,se,F)=>{let H=L.text||"";b||(H=H.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),L.role==="agent"&&(H=Ee(H),H=H.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),H=H.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*"));let we=[];return Array.isArray(L.parts)&&L.parts.length>0?we=L.parts.map(be=>{if(be.text){let he=be.text;return b||(he=he.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),L.role==="agent"&&(he=Ee(he),he=he.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),he=he.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*")),{text:he}}return be}):we=[{text:H}],L.binaryPart&&dt(me)&&F.slice(se+1).filter(he=>he.role==="user"&&!he.text?.startsWith("[TOOL RESULT]")).length<=2&&we.push(L.binaryPart),{role:L.role==="user"||L.role==="system"?"user":"model",parts:we}});for(let L=0;L<re.length;L++){let se=re[L],F=se.parts?.[0]?.text||"";if(se.role==="model"&&/\[tool:/i.test(F)){let H=-1;for(let we=L+1;we<re.length;we++){let be=re[we],he=be.parts?.[0]?.text||"";if(be.role==="user"&&he.startsWith("[TOOL RESULT]")){H=we;break}}if(H!==-1&&H!==L+1){let[we]=re.splice(H,1);re.splice(L+1,0,we)}}}for(let L=re.length-2;L>=0;L--){let se=re[L],F=re[L+1];se.role==="user"&&F.role==="user"&&(F.parts?.[0]?.text||"").trim().startsWith("[SYSTEM")&&re.splice(L,1)}let Lt=[];for(let L=0;L<re.length;L++){let se=re[L];if(Lt.length===0)Lt.push(se);else{let F=Lt[Lt.length-1];F.role===se.role?(F.parts[0].text+=`
743
+ [STEERING HINT from USER, High Priority] ${be.trim()} [/STEERING HINT]`:r.push({role:"user",text:`[STEERING HINT from USER, High Priority] ${be.trim()} [/STEERING HINT]`}),yield{type:"status",content:`${be.startsWith("/btw")?"Question Forwarded...":"Steering Hint Injected..."}`})}let _e,ot=!1,ze=1,et=1,le="",It=null,tt=null,zt=null,G=0,Q=[],Je=0,Xt=!1,Dt=!1,on=!1,gn=!1,vn=!0,wo=0,it="",Qe="",Ot=!1,Rn=!1,je=!0,he=e,Ve="";for(;ze<=nn&&et<=nn&&!ot&&!wt;){let be=!1;try{le="",vn&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},vn=!1,et===1&&(it=""));let Ae=L=>{if(!L||!L.includes("[tool:"))return L;let ne="",F=Vs(L);F&&(ne=F.fullBlock,L=F.remainingText),L=L.replace(Pa,(ke,pe)=>pe.includes("[tool:")?pe.trim():ke);let W="",Te=0;for(;Te<L.length;){let ke=L.indexOf("[tool:",Te);if(ke===-1){W+=Dr(L.substring(Te));break}let pe=L.substring(Te,ke);W+=Dr(pe);let Xe=-1,U=null,ee=0;for(let He=ke;He<L.length;He++){let y=L[He];if(U){if(y===U){let Ge=0;for(let Me=He-1;Me>=0&&L[Me]==="\\";Me--)Ge++;Ge%2===0&&(U=null)}}else if(y==='"'||y==="'"||y==="`")U=y;else if(y==="(")ee++;else if(y===")")ee--;else if(y==="]"&&ee<=0){Xe=He;break}}if(Xe===-1){W+=L.substring(ke);break}W+=L.substring(ke,Xe+1),Te=Xe+1}return(h?.keepReasoningContext?ne:"")+W},ie=r.filter(L=>(L.role==="user"||L.role==="agent"||L.role==="system")&&!String(L.id).startsWith("welcome")&&!L.isMeta&&!L.isTerminalRecord&&!(L.text&&L.text.startsWith("[TERMINAL_RECORD]"))).map((L,ne,F)=>{let W=L.text||"";b||(W=W.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),L.role==="agent"&&(W=Ae(W),W=W.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),W=W.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*"));let Te=[];return Array.isArray(L.parts)&&L.parts.length>0?Te=L.parts.map(ke=>{if(ke.text){let pe=ke.text;return b||(pe=pe.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),L.role==="agent"&&(pe=Ae(pe),pe=pe.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),pe=pe.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*")),{text:pe}}return ke}):Te=[{text:W}],L.binaryPart&&ft(he)&&F.slice(ne+1).filter(pe=>pe.role==="user"&&!pe.text?.startsWith("[TOOL RESULT]")).length<=2&&Te.push(L.binaryPart),{role:L.role==="user"||L.role==="system"?"user":"model",parts:Te}});for(let L=0;L<ie.length;L++){let ne=ie[L],F=ne.parts?.[0]?.text||"";if(ne.role==="model"&&/\[tool:/i.test(F)){let W=-1;for(let Te=L+1;Te<ie.length;Te++){let ke=ie[Te],pe=ke.parts?.[0]?.text||"";if(ke.role==="user"&&pe.startsWith("[TOOL RESULT]")){W=Te;break}}if(W!==-1&&W!==L+1){let[Te]=ie.splice(W,1);ie.splice(L+1,0,Te)}}}for(let L=ie.length-2;L>=0;L--){let ne=ie[L],F=ie[L+1];ne.role==="user"&&F.role==="user"&&(F.parts?.[0]?.text||"").trim().startsWith("[SYSTEM")&&ie.splice(L,1)}let Lt=[];for(let L=0;L<ie.length;L++){let ne=ie[L];if(Lt.length===0)Lt.push(ne);else{let F=Lt[Lt.length-1];F.role===ne.role?(F.parts[0].text+=`
744
744
 
745
- `+(se.parts?.[0]?.text||""),se.parts?.length>1&&F.parts.push(...se.parts.slice(1))):Lt.push(se)}}re.length=0,re.push(...Lt),me=e;let vt=`${g}|${i}|${a}|${f}|${me}|${JSON.stringify(l)}|${!!h?.dynamicDirAwareness}|${!!h?.subAgents}`,St=Fn.key===vt&&Fn.value;if((process.env.I_HAVE_TOO_MUCH_MONEY==="true"||process.env.I_HAVE_TOO_MUCH_MONEY===!0)&&(St=!1),St)Ue=Fn.value;else{let L=i==="Mistral"?!!qn(me):!(me||"gemma").toLowerCase().startsWith("gemma");Ue=Zi(l,((me||"gemma").toLowerCase().startsWith("gemma"),f),a,h,b,S,i,i==="Google"?!0:v,L,g,!!h?.keepReasoningContext,me),h?.dynamicDirAwareness||(Ue+=`
745
+ `+(ne.parts?.[0]?.text||""),ne.parts?.length>1&&F.parts.push(...ne.parts.slice(1))):Lt.push(ne)}}ie.length=0,ie.push(...Lt),he=e;let vt=`${g}|${i}|${a}|${f}|${he}|${JSON.stringify(l)}|${!!h?.dynamicDirAwareness}|${!!h?.subAgents}`,St=Fn.key===vt&&Fn.value;if((process.env.I_HAVE_TOO_MUCH_MONEY==="true"||process.env.I_HAVE_TOO_MUCH_MONEY===!0)&&(St=!1),St)Ve=Fn.value;else{let L=i==="Mistral"?!!Co(he):!(he||"gemma").toLowerCase().startsWith("gemma");Ve=Zi(l,((he||"gemma").toLowerCase().startsWith("gemma"),f),a,h,b,_,i,i==="Google"?!0:A,L,g,!!h?.keepReasoningContext,he),h?.dynamicDirAwareness||(Ve+=`
746
746
  ${Xs.replace(`
747
747
  **Directory Structure**`,`
748
- -- Directory Structure --`)}`),Fn.key=vt,Fn.value=Ue}let We=re[re.length-1];if(Go()&K>0){await new Promise(F=>setTimeout(F,2500)),yield{type:"status",content:"Verifying"};let L=await $n(),se=L?L.diagnostics:null;se&&We&&We.role==="user"&&We.parts?.[0]?.text&&(We.parts[0].text+=`
749
- ${se} [/ERROR]`),yield{type:"status",content:"Working"}}let Pt=i==="Mistral"||i==="Google"&&e?.toLowerCase().startsWith("gemma");if(h?.advanceRollback&&We&&We.role==="user"&&We.parts?.[0]?.text?.startsWith("[TOOL RESULT]"))try{let L=await so.getLatestFileChanges(g);if(L&&(L.newFiles.length>0||L.modifiedFiles.length>0||L.deletedFiles.length>0)){let se=`
748
+ -- Directory Structure --`)}`),Fn.key=vt,Fn.value=Ve}let Ke=ie[ie.length-1];if(Go()&V>0){await new Promise(F=>setTimeout(F,2500)),yield{type:"status",content:"Verifying"};let L=await $n(),ne=L?L.diagnostics:null;ne&&Ke&&Ke.role==="user"&&Ke.parts?.[0]?.text&&(Ke.parts[0].text+=`
749
+ ${ne} [/ERROR]`),yield{type:"status",content:"Working"}}let Pt=i==="Mistral"||i==="Google"&&e?.toLowerCase().startsWith("gemma");if(h?.advanceRollback&&Ke&&Ke.role==="user"&&Ke.parts?.[0]?.text?.startsWith("[TOOL RESULT]"))try{let L=await oo.getLatestFileChanges(g);if(L&&(L.newFiles.length>0||L.modifiedFiles.length>0||L.deletedFiles.length>0)){let ne=`
750
750
  [system] File Changes:
751
- `;for(let H of L.newFiles)se+=`* ${H} (created)
752
- `;for(let H of L.modifiedFiles)se+=`* ${H} (modified)
753
- `;for(let H of L.deletedFiles)se+=`* ${H} (deleted)
754
- `;se+="[/system]",We.parts[0].text+=se;let F=-1;for(let H=r.length-1;H>=0;H--)if(r[H].role==="user"&&r[H].text?.startsWith("[TOOL RESULT]")){F=H;break}F!==-1&&(r[F].text+=se)}}catch{}let _t=Math.floor(Xn*(a==="Flux"?.98:.8)),yt=K+1;yt>=_t&&We&&We.parts?.[0]&&(We.parts[0].text+=`
755
- [system] WARNING, Turn Limit Impending: Step ${yt}/${Xn}. Wrap up quickly/prompt user to continue. [/system]`);let Rt=new Promise((L,se)=>{w.signal.aborted&&se(new DOMException("The user aborted a request.","AbortError")),w.signal.addEventListener("abort",()=>{se(new DOMException("The user aborted a request.","AbortError"))})});Rt.catch(()=>{});let ut=re;if(i==="Ollama")_e=Hs(n.apiKey,me,ut,Ue,f,a,v,w.signal,1,h?.ollamaEndpoint||"Cloud");else if(i==="OpenRouter")_e=qo(n.apiKey,me,ut,Ue,f,a,v,w.signal,1,g);else if(i==="DeepSeek")_e=Vo(n.apiKey,me,ut,Ue,f,a,v,w.signal,1);else if(i==="Mistral")_e=Ko(n.apiKey,me,ut,Ue,f,a,v,w.signal,1,g);else if(i==="NVIDIA"){let L=Yo(n.apiKey,me,ut,Ue,f,a,v,w.signal,1);_e=Cr(L,me)}else if(i==="InferX")_e=zo(n.apiKey,me,ut,Ue,f,a,v,w.signal,1);else if(i==="SenseNova")_e=Jo(n.apiKey,me,ut,Ue,f,a,v,w.signal,1);else if(i==="AIHubMix")_e=Xo(n.apiKey,me,ut,Ue,f,a,v,w.signal,1);else if(i==="Poolside")_e=Qo(n.apiKey,me,ut,Ue,f,a,v,w.signal,1);else if(i==="9router"||i==="9Router")_e=Zo(n.apiKey,me,ut,Ue,f,a,v,w.signal,1);else if(i==="ExpLabs"||i==="ExperientialLabs")_e=es(n.apiKey,me,ut,Ue,f,a,v,w.signal,1);else if(i==="TokenHarbor"||i==="Token Harbor"||i==="tokenharbor"||i==="token_harbor"||i==="thk")_e=Gs(n.apiKey,me,ut,Ue,f,a,v,w.signal,1);else if(i==="APInex"||i==="apinex"||i==="apx")_e=js(n.apiKey,me,ut,Ue,f,a,v,w.signal,1);else{let se=qs(n?.apiKey).models.generateContentStream({model:me||"gemini-3-flash-preview",contents:ut,config:{systemInstruction:Ue,mediaResolution:"MEDIA_RESOLUTION_HIGH",safetySettings:[{category:Cn.HARM_CATEGORY_HARASSMENT,threshold:An.BLOCK_NONE},{category:Cn.HARM_CATEGORY_HATE_SPEECH,threshold:An.BLOCK_NONE},{category:Cn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:An.BLOCK_NONE},{category:Cn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:An.BLOCK_NONE}],temperature:1.05,thinkingConfig:(()=>{let F=Oe("Google",me||"gemini-3-flash-preview",f);if(F!==null){if(typeof F=="object")return F;if(F===!1||F==="false"||F==="none"||F===0||F==="0")return{includeThoughts:!1};if(typeof F=="number")return{includeThoughts:!0,thinkingBudget:F};if(typeof F=="string"){let he=F.toLowerCase();if(he==="minimal")return{includeThoughts:!0,thinkingLevel:Je.MINIMAL};if(he==="low")return{includeThoughts:!0,thinkingLevel:Je.LOW};if(he==="medium")return{includeThoughts:!0,thinkingLevel:Je.MEDIUM};if(he==="high")return{includeThoughts:!0,thinkingLevel:Je.HIGH};let Ke=Number(F);if(!isNaN(Ke))return{includeThoughts:!0,thinkingBudget:Ke}}}let H=(me||"").toLowerCase(),we=H.includes("gemma-4")||H.startsWith("gemma"),be=H.includes("gemini-3");if(we||be)return we?f.toLowerCase()!=="high"?{includeThoughts:!1,thinkingLevel:Je.MINIMAL}:{includeThoughts:!0,thinkingLevel:Je.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:H.includes("pro")?Je.LOW:Je.MINIMAL,Low:Je.LOW,Medium:Je.MEDIUM,Standard:Je.MEDIUM,High:Je.HIGH,xHigh:Je.HIGH}[f]||Je.MEDIUM};{let he={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[f]||2048;return he===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:he}}})()}},{signal:w.signal});_e=await Promise.race([se,Rt])}le="",It=null,zt=null,Q=[],Ve=0,yield{type:"model_update",content:null},qe="",Ot=st.length>0;let sn="",ls=Date.now(),Dn=async function*(){if(i==="Google"&&sn){let L=Zn(sn);for(let se of L)yield se;sn="",ls=Date.now()}},ri=!0,On="",Wn=!1,xt=null,Hn=!1,Vr={tool:{startPrefix:"[tool",fullPrefix:"[tool:functions.",endTag:"]"},agent:{startPrefix:"[agent",fullPrefix:"[agent:generalist.",endTag:"]"},end:{startPrefix:"[[END]]",fullPrefix:"[[END]]",endTag:"[[END]]"},kimi_section:{startPrefix:"<|tool_calls_section_begin|>",fullPrefix:"<|tool_calls_section_begin|>",endTag:"<|tool_calls_section_end|>"},kimi_call:{startPrefix:"<|tool_call_begin|>",fullPrefix:"<|tool_call_begin|>",endTag:"<|tool_call_end|>"}},Zn=L=>{let se=[],F=L;for(;F.length>0;)if(Wn){let H=On+F,we=Vr[xt];if(we){let Ke=!1;if(H.length<we.startPrefix.length?we.startPrefix.startsWith(H)||(Ke=!0):H.startsWith(we.startPrefix)?H.length>=we.fullPrefix.length&&!H.startsWith(we.fullPrefix)&&(Ke=!0):Ke=!0,Ke){Hn||se.push({type:"text",content:H}),On="",Wn=!1,xt=null,F="";break}}let be=-1,he=we?we.endTag:"]";if(xt==="tool"||xt==="agent"){let Ke=0,W=null,ne=0,Ne=!1;for(let y=0;y<H.length;y++){let Fe=H[y];if(W){if(Fe===W){let Re=0;for(let z=y-1;z>=0&&H[z]==="\\";z--)Re++;Re%2===0&&(W=null)}}else if(Fe==='"'||Fe==="'"||Fe==="`")W=Fe;else if(Fe==="(")Ke++,Ne=!0;else if(Fe===")")Ke--;else if(Fe==="[")ne++;else if(Fe==="]"){if(Ne&&Ke===0&&ne===1){be=y;break}ne--}}}else be=H.indexOf(he);if(be!==-1){let Ke=he.length;if(!xt?.startsWith("kimi")){let W=H.substring(0,be+Ke);se.push({type:"text",content:W})}(xt==="tool"||xt==="agent"||xt?.startsWith("kimi"))&&(Hn=!0),On="",Wn=!1,xt=null,F=H.substring(be+Ke)}else{let Ke=xt?.startsWith("kimi")?8192:512;H.length>Ke?(Hn||se.push({type:"text",content:H}),On="",Wn=!1,xt=null):On=H,F="";break}}else{let H=F.indexOf("[tool"),we=F.indexOf("[agent"),be=F.indexOf("[[END]]"),he=F.indexOf("<|tool_calls_section_begin|>"),Ke=F.indexOf("<|tool_call_begin|>"),W=[{type:"tool",idx:H,start:"[tool",end:"]"},{type:"agent",idx:we,start:"[agent",end:"]"},{type:"end",idx:be,start:"[[END]]",end:"[[END]]"},{type:"kimi_section",idx:he,start:"<|tool_calls_section_begin|>",end:"<|tool_calls_section_end|>"},{type:"kimi_call",idx:Ke,start:"<|tool_call_begin|>",end:"<|tool_call_end|>"}].filter(ne=>ne.idx!==-1).sort((ne,Ne)=>ne.idx-Ne.idx);if(W.length>0){let ne=W[0];ne.idx>0&&(Hn||se.push({type:"text",content:F.substring(0,ne.idx)})),Wn=!0,xt=ne.type,On="",F=F.substring(ne.idx)}else{let ne=["[tool","[agent","[[END]]","<|tool_calls_section_begin|>","<|tool_call_begin|>"],Ne=-1;for(let y of ne){for(let Fe=y.length-1;Fe>0;Fe--)if(F.endsWith(y.substring(0,Fe))){Ne=F.length-Fe;let Re=ne.indexOf(y);Re===0?xt="tool":Re===1?xt="agent":Re===2?xt="end":Re===3?xt="kimi_section":xt="kimi_call";break}if(Ne!==-1)break}if(Ne!==-1)Ne>0&&(Hn||se.push({type:"text",content:F.substring(0,Ne)})),Wn=!0,On=F.substring(Ne),F="";else{Hn||se.push({type:"text",content:F});break}}}return se},Kr=_e[Symbol.asyncIterator]();for(;;){let{value:L,done:se}=await Promise.race([Kr.next(),Rt]);if(se)break;if(L&&L.type==="status"){yield L;continue}let F="",H=L.candidates?.[0]?.content?.parts;if(H&&H.length>0)for(let be of H){let he=typeof be.text=="string"?be.text:be.text?parseChunkText(be.text):"";be.thought?he&&(xe||(F+="<think>",xe=!0),F+=he):he&&(xe&&(F+="</think>",xe=!1),F+=he)}else L.text&&xe&&(F+="</think>",xe=!1);F=Ia(F);let we=F?ms(F):0;if(n&&typeof n.onTokenChunk=="function"&&n.onTokenChunk(F,we),ri&&(yield{type:"status",content:"Thinking"},ri=!1),wt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
756
-
757
- \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(F){if(Ot){if(qe+=F,qe.length>=64){let W=0,ne=Math.min(st.length,qe.length);for(let y=ne;y>=10;y--)if(st.endsWith(qe.substring(0,y))){W=y;break}let Ne=qe.substring(W);if(Ne){let Fe=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(st)?Ne.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):Ne.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(Fe)if(le+=Fe,i==="Google")sn+=Fe;else{yield*Dn();let Re=Zn(Fe);for(let z of Re)yield z}}Ot=!1,qe=""}continue}else if(le+=F,i==="Google")sn+=F;else{yield*Dn();let W=Zn(F);for(let ne of W)yield ne}let be=Ba(le);if(be.inside){Rn=!0,zt||(zt=Date.now());let ne={Ask:"ask",AskUser:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Cancel:"cancel",Await:"await",Answer:"answer",Steer:"steer",steer:"steer"}[be.toolName]||be.toolName,Ne=be.args||"",y=null;if(["write_file","update_file","view_file","read_folder","write_pdf","write_docx","search_keyword","generate_image","file_map","invoke","invoke_sync","get_progress","await","answer"].includes(ne)){let Re=Z(Ne),z=Re.path||Re.targetFile||Re.TargetFile||Re.directory,rn=Re.keyword,Ln=Re.title||Re.task,Tn=Re.id||Re.taskId,Ae=Re.timeout||Re.time;if(rn!=null)y=String(rn).replace(Nn,"");else if(z)y=J.basename(String(z).replace(Nn,"").replace(vr,"/"));else if(Ln&&(ne==="invoke"||ne==="invoke_sync"))y=String(Ln).replace(Nn,"").substring(0,30);else if(Tn&&ne==="get_progress")y=String(Tn).replace(Nn,"");else if(Ae&&ne==="await"){let $t=parseFloat(String(Ae).replace(Nn,""));isNaN($t)?y=String(Ae).replace(Nn,""):($t<5&&($t=5),$t>120&&($t=120),y=(mn=>{if(mn>=60){let ds=Math.floor(mn/60),Gn=mn%60;return`${ds}m${Gn>0?` ${Gn}s`:""}`}return`${mn}s`})($t))}else{let $t=Ne.match(va);if($t){let Ut=$t[1].replace(Nn,"");ne==="invoke"||ne==="invoke_sync"||ne==="get_progress"?y=Ut.substring(0,30):y=ne==="search_keyword"||ne==="file_map"?Ut:J.basename(Ut.replace(vr,"/"))}}}let Fe=`${Ks[ne]||ne}${y?` ${y}`:""}`;if((ne!==It||y!==et)&&(It=ne,et=y,yield{type:"status",content:`${Fe}`},process.stdout.isTTY)){let z={WebSearch:"Searching",web_search:"Searching",WebScrape:"Reading",web_scrape:"Reading",ReadFile:"Reading",read_file:"Reading",ReadFolder:"Reading",read_folder:"Reading",WriteFile:"Writing",write_file:"Writing",UpdateFile:"Editing",update_file:"Editing",WritePdf:"Creating",write_pdf:"Creating",WriteDocx:"Creating",write_docx:"Creating",SearchKeyword:"Searching",search_keyword:"Searching",CodeSearch:"Searching",code_search:"Searching",Run:"Executing",Ask:"User Input Required",AskUser:"User Input Required",Memory:"Updating Memory",GenerateImage:"Generating",InvokeSync:"Sub-Agent Working",invoke_sync:"Sub-Agent Working",Invoke:"Working",invoke:"Working",GetProgress:"Checking Progress",get_progress:"Checking Progress",Cancel:"Stopping Generalist",cancel:"Stopping Generalist",Await:"Waiting",await:"Waiting",EmergencyRollback:"Rolling the Ball",Answer:"Answering Sub-Agent",answer:"Answering Sub-Agent",Steer:"Steering Sub-Agent",steer:"Steering Sub-Agent",Click:"Clicking",click:"Clicking",Drag:"Dragging",drag:"Dragging",Scroll:"Scrolling",scroll:"Scrolling",KeyboardTyping:"Typing",keyboard_typing:"Typing",KeyPress:"Pressing Key",key_press:"Pressing Key",RecaptureScreen:"Recapturing Screen",recapture_screen:"Recapturing Screen"}[ne]||"Working";process.stdout.write(`\x1B]0;${z}...\x07`)}}if(le.length-To>150){To=le.length;let W=Fr(le,!1),ne=Vs(W),Ne=ne?(ne.innerContent||"").trim():"",y=Ne.split(/[.!?]\s+/),Fe=new Set(y),Re=y.length>10?(y.length-Fe.size)/y.length:0,z=Ne.split(/\s+/).filter(Me=>Me.length>0).length,rn=.6,Ln=.8,Tn=!1;if((i.toLowerCase().includes("google")||i.toLowerCase().includes("mistral"))&&((me||"").toLowerCase().startsWith("gemma")||(me||"").toLowerCase().includes("stral"))){let _={low:256,medium:1024,high:8192,max:16384,xhigh:16384}[f?.toLowerCase()]||2500;Tn=z>_}if(Re>rn||Tn){yield{type:"status",content:`${Re>rn?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},Dt=!0,await new Promise(_=>setTimeout(_,3e3));break}let Ut=Or(le).trim().split(/[.!?]\s+/),mn=new Set(Ut);if((Ut.length>10?(Ut.length-mn.size)/Ut.length:0)>Ln){yield{type:"status",content:"Response Loop Detected. Re-centering..."},Dt=!1,gn=!0,await new Promise(Me=>setTimeout(Me,3e3));break}let Gn=W.replace(wa,"").replace(Ta,"").replace(Sa,"").replace(_a,""),Nt=Gn.toLowerCase().split(/\s+/).map(Me=>Me.replace(Ea,"")).filter(Me=>Me.length>0),hn=!1;if(Nt.length>=10)for(let Me=1;Me<=15;Me++){let _=Math.max(3,Math.ceil(10/Me));if(Nt.length<Me*_)continue;let V=Nt.slice(Nt.length-Me),ae=V.join(" ");if(Me>1&&ae===V.slice(0,Math.floor(Me/2)).join(" ").repeat(2).trim())continue;let de=!0;for(let ke=1;ke<_;ke++)if(Nt.slice(Nt.length-Me*(ke+1),Nt.length-Me*ke).join(" ")!==ae){de=!1;break}if(de){hn=!0;break}}if(!hn){let Me=Gn.toLowerCase().replace(Aa,"");if(Me.length>=20)for(let _=1;_<=10;_++){let V=Math.max(5,Math.ceil(16/_));if(Me.length<_*V)continue;let ae=Me.substring(Me.length-_),de=!0;for(let ke=1;ke<V;ke++)if(Me.substring(Me.length-_*(ke+1),Me.length-_*ke)!==ae){de=!1;break}if(de){hn=!0;break}}}if(hn){yield{type:"status",content:"Stuttering Detected. Re-centering..."},Dt=!1,on=!0,await new Promise(Me=>setTimeout(Me,3e3));break}}let he=Kt(le),Ke=yo(he);for(;Ke.length>Ve;){yield*Dn();let W=Ke[Ve],ne=Date.now(),y={Ask:"ask",AskUser:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Await:"await",await:"await",AwaitSubagent:"await",awaitSubagent:"await",Answer:"answer",answer:"answer",AnswerSubagent:"answer",answerSubagent:"answer",Steer:"steer",steer:"steer",SteerSubagent:"steer",steerSubagent:"steer",Cancel:"cancel",cancel:"cancel",Click:"click",click:"click",Drag:"drag",drag:"drag",Scroll:"scroll",scroll:"scroll",KeyboardTyping:"keyboard_typing",keyboard_typing:"keyboard_typing",KeyPress:"key_press",key_press:"key_press",RecaptureScreen:"recapture_screen",recapture_screen:"recapture_screen",EmergencyRollback:"EmergencyRollback"}[W.toolName]||W.toolName,Fe=Ks[y]||W.toolName,Re=Bn(y,W.args);yield{type:"status",content:`${Fe}${Re?` ${Re}`:""}`};let z="";if(y==="click"){let _=Z(W.args);z=`\u2714 Clicked: ${_.intendedClickText?`${_.intendedClickText}`:""}`}else if(y==="drag"){let _=Z(W.args);z=`\u2714 Dragged: Cell ${_.fromGridId||""} \u2192 Cell ${_.toGridId||""}`}else if(y==="scroll"){let _=Z(W.args);z=`\u2714 Scrolled: ${_.direction||"down"} (${_.amount||1})`}else if(y==="keyboard_typing"){let _=Z(W.args);z=`\u2714 Typed: ${_.text?`"${_.text.length>20?_.text.substring(0,20)+"...":_.text}"`:""}`}else if(y==="key_press")z=`\u2714 Pressed Key: ${Z(W.args).key||""}`;else if(y==="recapture_screen")z="\u2714 Recaptured Screen";else if(y==="web_search"){let{query:_,limit:V=10,aiMode:ae=!1}=Z(W.args);z=`${_?"\u2714":"\u2718"} ${ae?"AI Search":"Searched"}: ${_?`${_}`:"No Search Query"}${ae===!1&&_?` \u2192 ${V}`:""}`}else if(y==="web_scrape"){let _=Z(W.args).url||null;z=`${_?"\u2714":"\u2718"} Visited: ${_||"No Source"}`}else if(y==="view_file"){let{path:_,StartLine:V,EndLine:ae,start_line:de,end_line:ke,startLine:He,endLine:Ie}=Z(W.args),Te=V||de||He,q=ae||ke||Ie,oe=parseInt(Te)||1,ce=parseInt(q)||(Te?oe+800:800),Ce="...",ze=ce,ve=(_||"").trim().toLowerCase().replaceAll("\\","/");if(ve.startsWith("#skill"))ve.startsWith("#skill/global/fluxflow")||ve.startsWith("#skills/global/fluxflow")?z="\u2714 Read Documentation":z=`\u2714 Read Skill: ${J.basename(_.replaceAll("\\","/"))}`;else{try{let ye=J.resolve(process.cwd(),_);if($e.existsSync(ye)){let ht=$e.readFileSync(ye,"utf8").split(`
758
- `).length;Ce=ht,!Te&&!q&&ht>800?ze=Math.min(50,ht):ze=Math.min(ce,ht)}}catch{}let Le=(_||"").toLowerCase(),gt=Le.endsWith(".pdf"),De=Le.endsWith(".docx")||Le.endsWith(".doc")||Le.endsWith(".ppt")||Le.endsWith(".pptx")||Le.endsWith(".xls")||Le.endsWith(".xlsx"),ot=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(Le);gt||De?z=`${_.length>0?"\u2714":"\u2718"} ${_?`Analyzed: ${J.basename(_)}`:"Analyzed: File Not Found"}`:ot?z=`${_.length>0?"\u2714":"\u2718"} ${_?`Processed: ${J.basename(_)}`:"Processed: File Not Found"}`:z=`${Ce!=="..."?"\u2714":"\u2718"} Read: ${_?`${J.basename(_)} \u2192 ${Ce!=="..."?`Lines ${oe} - ${ze} of ${Ce}`:"File Not Found"}`:"File Not Found"}`}}else if(y==="list_files"||y==="read_folder"){let _=y==="list_files"?"List":"Browsed",V=Z(W.args).path||null,ae=Z(W.args).recurse||1;z=`${V?"\u2714":"\u2718"} ${_}: ${V?`${V==="."?`./${ae>1?"*":""}`:`${V.replaceAll("\\","/")}${ae>1?`${V.endsWith("/")?"*":"/*"}`:`${V.endsWith("/")?"":"/"}`}`}`:"No Folder Selected"}`}else if(y==="write_file"||y==="update_file"){let _=y==="write_file"?"Created":"Edited",V=Z(W.args).path||null;z=`${V?"\u2714":"\u2718"} ${_}: ${V.replaceAll("\\","/")||"No File Changes"}`}else if(y==="write_pdf"){let _=Z(W.args).path||null;z=`${_?"\u2714":"\u2718"} Generated: ${_.replaceAll("\\","/")||"No PDF Generated"}`}else if(y==="write_docx"){let _=Z(W.args).path||null;z=`${_?"\u2714":"\u2718"} Generated: ${_.replaceAll("\\","/")||"No Docx Generated"}`}else if(y==="file_map"){let _=Z(W.args).path;z=`${_?"\u2714":"\u2718"} Indexed: ${_.replaceAll("\\","/")?""+_:"File Not Found"}`}else if(y.toLowerCase()==="search_keyword"||y.toLowerCase()==="todo")z="";else if(y.toLowerCase()==="generate_image"){let{path:_,outputPath:V,output:ae}=Z(W.args);z=`\u2714 Generated: ${_||V||ae||"generated_image.png"}`}else if(y==="invoke_sync"||y==="InvokeSync"){let _=Bn(y,W.args);z=`\u2714 Called Generalist${_?`: ${_}`:""}`}else if(y==="Invoke"||y==="InvokeAsync"||y==="invoke"){let _=Bn(y,W.args);z=`\u2714 Started Generalist${_?`: ${_}`:""}`}else if(y==="get_progress"||y==="GetProgress"){let _=Bn(y,W.args);z=`\u2714 Checked${_?`: ${_}`:""}`}else if(y==="cancel"){let _=Bn(y,W.args);z=`\u{1F6C7} Cancelled${_?`: ${_}`:""}`}else if(y==="steer"||y==="Steer"){let _=Bn(y,W.args);z=`\u2714 Steered${_?`: ${_}`:""}`}else if(y==="EmergencyRollback"){let{method:_}=Z(W.args);z=_==="forceRevert"?"":"\u2714 Rollback Point Checked"}else if(y==="await"||y==="Await"){let{time:_,timeout:V}=Z(W.args),ae=parseFloat(V||_)||0;ae||(ae=120);let de=Ie=>{if(Ie>=60){let Te=Math.floor(Ie/60),q=Ie%60;return`${Te}m${q>0?` ${q}s`:""}`}return`${Ie}s`},ke=["Aligning Moon Phase","Contemplating Existence","Staring At Void","Delaying Professionally","Negotiating With Electrons","Touching Grass (virtually)","Panicking Softly","Rethinking Career Choices","Loading Cat Videos","Summoning Braincell #2","Pretending To Be Busy","Waiting For Motivation DLC","Rotating Internal Screaming","Downloading More RAM","Feeding The Hamsters","Gaslighting Scheduler","Performing Dramatic Pause","Buffering Social Energy","Calculating Regret","Reading Terms And Conditions","Becoming Sentient Briefly","Contacting Ancestors"];z=`\u2714 ${ke[Math.floor(Math.random()*ke.length)]} \u2192 ${de(ae)}`}else y==="Answer"||y==="answer"?z="\u2714 Resolved Sub-Agent Query":y==="exec_command"||y==="ask"?z="":z=`Executed: ${W.toolName}`;if(yield*Dn(),y==="exec_command"){let{command:_}=Z(W.args);if(_&&n.systemSettings&&n.systemSettings.allowExternalAccess===!1){let V=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],ae=J.resolve(process.cwd()).substring(0,3).toLowerCase(),de=q=>{let oe=[],ce="",Ce=null;for(let ze=0;ze<q.length;ze++){let ve=q[ze];Ce?(ve===Ce&&(Ce=null),ce+=ve):ve==='"'||ve==="'"?(Ce=ve,ce+=ve):ve==="&"&&q[ze+1]==="&"||ve==="|"&&q[ze+1]==="|"?(ce.trim()&&(oe.push(ce.trim()),ce=""),ze++):ve===";"||ve==="|"||ve==="&"?ce.trim()&&(oe.push(ce.trim()),ce=""):ce+=ve}return ce.trim()&&oe.push(ce.trim()),oe},ke=q=>{let oe=[],ce="",Ce=null;for(let ze=0;ze<q.length;ze++){let ve=q[ze];Ce?(ve===Ce&&(Ce=null),ce+=ve):ve==='"'||ve==="'"?(Ce=ve,ce+=ve):/\s/.test(ve)?ce&&(oe.push(ce),ce=""):ce+=ve}return ce&&oe.push(ce),oe},He=q=>{let oe=q.replace(/^['"]|['"]$/g,"").trim();return!oe||process.platform==="win32"&&/^\/[a-zA-Z0-9?]+$/.test(oe)?!1:V.some(ce=>{if(ce.source==="[a-zA-Z]:[\\\\\\/]"){let Ce=oe.match(/[a-zA-Z]:[\\\/]/i);return Ce&&Ce[0].toLowerCase()!==ae}return ce.test(oe)})};if(de(_).some(q=>{let oe=ke(q);if(oe.length===0)return!1;let ce=oe[0].replace(/^['"]|['"]$/g,"").toLowerCase();if(["echo","printf","write-output"].includes(ce)){let ze=!1;return oe.some(ve=>{let Wt=ve.replace(/^['"]|['"]$/g,"");if(Wt===">"||Wt===">>"||Wt==="<")return ze=!0,!1;if(Wt.startsWith(">")||Wt.startsWith("<")){let Le=Wt.replace(/^[><]+/,"");return He(Le)}return ze?(ze=!1,He(ve)):!1})}return oe.some(ze=>He(ze))})){let q='Access Denied. Prohibited from accessing external directories while "External Workspace Access" is disabled.';n.onExecStart&&n.onExecStart(_||"No Command"),yield{type:"exec_start"},await new Promise(oe=>setTimeout(oe,50)),n.onExecChunk&&n.onExecChunk(`ERROR: ${q}`),await new Promise(oe=>setTimeout(oe,50)),n.onExecEnd&&n.onExecEnd(),Q.push({role:"user",text:`[TOOL RESULT]: ERROR: ${q}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${q}`},Ve++;continue}}n.onExecStart&&n.onExecStart(_||"No Command"),yield{type:"exec_start"}}let rn=Z(W.args),Ln=rn.path||rn.targetPath||null;if(Ln){let _=n.systemSettings&&n.systemSettings.allowExternalAccess===!1,V=J.resolve(Ln),ae=J.resolve(process.cwd());if(_&&!V.startsWith(ae)){let de="Access Denied. You are not allowed to access files outside the current workspace.";if(y==="write_file"||y==="update_file"){let He=`\u2718 ${y==="write_file"?"Write Canceled":"Edit Canceled"}: ${rn.path||"..."}`,Ie=115;process.stdout.isTTY&&(Ie=process.stdout.columns-5||120);let Te=Math.min(He.length+4,Ie),q=`${He.padEnd(Te-2).substring(0,Te-2)}`;yield{type:"visual_feedback",content:Vt(`${Be?`
759
- `:""}${q}
760
- `)},Be=!1}Q.push({role:"user",text:`[TOOL RESULT]: ERROR: ${de}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${de}`},Ve++;continue}}if(n.onToolApproval&&(y==="write_file"||y==="update_file"||y==="exec_command")){let V=n.systemSettings||{},ae=V.autoExec,de=null,ke=!1,He=!1,Ie=!1;if(y==="exec_command"){let{command:Le}=Z(W.args),gt=(Le||"").trim(),De=(Ht,ht)=>{if(!ht)return!1;let Zt=ht.split(",").map(Gt=>Gt.trim().toLowerCase()).filter(Boolean),rt=Ht.toLowerCase();return Zt.some(Gt=>rt.startsWith(Gt))},ot=De(gt,V.alwaysAskCommands),ye=De(gt,V.autoApproveCommands);if(He=De(gt,V.autoDisallowCommands),ot?ke=!0:(ye||V.autoApproveGit&&/^git\s+commit\b/i.test(gt))&&(de="allow"),!ke&&!de){if(V.networkAccess===!1){let ht=gt.trim().replace(/\s+/g," ").replace(/^['"]+|['"]+$/g,"").toLowerCase().split(" "),rt=ht[0].split("/").pop().split("\\").pop().replace(/\.exe$/,""),Gt=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"]),at=!1;Gt.has(rt)&&(at=!0);let it=an=>ht.slice(1).some(ln=>an.includes(ln)),lt=an=>{let ln=ht.findIndex(pn=>an.includes(pn)),jn=ht.findIndex(pn=>["run","exec","test"].includes(pn));return ln!==-1&&!(jn!==-1&&jn<ln)};rt==="git"&&it(["clone","pull","push","fetch"])&&(at=!0),rt==="go"&&it(["get","install"])&&(at=!0),rt==="npm"&&lt(["install","i","update","add"])&&(at=!0),rt==="yarn"&&lt(["add","install","upgrade"])&&(at=!0),rt==="pnpm"&&lt(["add","install","update"])&&(at=!0),rt==="bun"&&lt(["add","install","update"])&&(at=!0),rt==="deno"&&it(["install","add"])&&(at=!0),rt==="pip"&&it(["install","download"])&&(at=!0),rt==="pip3"&&it(["install","download"])&&(at=!0),rt==="cargo"&&it(["install","add"])&&(at=!0),["bash","sh","zsh","fish"].includes(rt)&&it(["-c"])&&(at=!0),rt==="cmd"&&it(["/c"])&&(at=!0),at&&(de="deny",Ie=!0)}!de&&He&&(de="deny")}!ke&&!de&&ae&&(de="allow")}else ae&&(de="allow");let Te=de,q="";de==="deny"&&(Ie?q="network":He?q="settings":q="prohibited");let oe=!1,ce="",Ce=[],ze=0,ve=!1,Wt="";if(!Te){if(y==="write_file"||y==="update_file")try{let De=Z(W.args),{path:ot}=De;if(ot){let ye=J.resolve(process.cwd(),ot),Ht=it=>it?it.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,lt=>lt.toUpperCase()):"",ht=Ht(ye),Zt="",rt=!1,Gt=await $n(),at=Ht(Gt?.file_focused);if(Gt&&at===ht&&Gt.full_content?(Zt=Gt.full_content,rt=!0):$e.existsSync(ye)&&(Zt=$e.readFileSync(ye,"utf8"),rt=!0),ce=Zt,await vo.recordFileChange(ye,Zt),rt){let it=Zt;if(y==="write_file"){let lt=De.content||De.newContent||"";it=lt.endsWith(`
761
- `)?lt:lt+`
762
- `,Wt=it}else{let{patchPairs:lt,allowMultiple:an,error:ln}=ci(De);if(ln){let kt=`[TOOL RESULT]: ERROR: ${ln}`;Q.push({role:"user",text:kt}),await At("toolFailure"),n.onToolResult&&n.onToolResult("failure",y),yield{type:"tool_result",content:kt,toolName:y},Ve++;continue}let jn=De.allowMultiple!==void 0?De.allowMultiple===!0||String(De.allowMultiple).toLowerCase()==="true":an;ze=lt.length;let pn=di(Zt,lt,{allowMultiple:jn});it=pn.content,Wt=it,Ce=pn.results;let So=Ce.filter(kt=>kt.success),bt=Ce.filter(kt=>!kt.success);if(So.length===0){let kt=`[TOOL RESULT]: ERROR: Failed to apply patches to [${J.basename(ye)}].
763
- ${bt.map(no=>` \u2022 ${no.error}`).join(`
764
- `)}`,Vn=`\u2714 Edited: ${J.basename(ye.replaceAll("\\","/"))}`,to=115;process.stdout.isTTY&&(to=process.stdout.columns-5||120);let Kn=Math.min(Vn.length+4,to),_o=`${Vn.padEnd(Kn-2).substring(0,Kn-2)}`;yield{type:"visual_feedback",content:Vt(`${Be?`
765
- `:""}${_o}`)},Be=!1,Q.push({role:"user",text:kt}),await At("toolFailure"),n.onToolResult&&n.onToolResult("failure",y),yield{type:"tool_result",content:kt,toolName:y},Ve++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${J.basename(ye)}`},Fs(ye,Zt,it),oe=!0,await new Promise(lt=>setTimeout(lt,50))}else if(y==="write_file"){let it=De.content||De.newContent||"",lt=it.endsWith(`
766
- `)?it:it+`
767
- `;Wt=lt,$e.existsSync(ye)||(ve=!0,$e.mkdirSync(J.dirname(ye),{recursive:!0}),$e.writeFileSync(ye,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${J.basename(ye)}`},Fs(ye,"",lt),oe=!0,await new Promise(an=>setTimeout(an,50))}}}catch(De){console.error("Simulation/Diff Error:",De)}let Le=null;Ns(De=>{Le=De});let gt=n.onToolApproval;if(Te=await new Promise(async De=>{let ot=setInterval(()=>{Le&&(ts.onIDEApproval&&ts.onIDEApproval(Le),clearInterval(ot),De(Le))},100);try{let ye=await gt(y,W.args);clearInterval(ot),De(ye)}catch{clearInterval(ot),De("deny")}}),Ns(null),y==="write_file"||y==="update_file"){let{path:De}=Z(W.args);if(De){let ot=J.resolve(process.cwd(),De);if(Er(ot,Te),Te==="deny"&&ve&&$e.existsSync(ot))try{$e.unlinkSync(ot)}catch{}}}Te==="deny"&&(q="user")}if(Te==="allow"&&oe&&Go()){let{path:Le}=Z(W.args),gt=J.resolve(process.cwd(),Le),De=bt=>bt?J.resolve(bt).replace(/\\/g,"/").toLowerCase():"",ot=await $n(),ye="";if(ot&&ot.file_focused&&De(ot.file_focused)===De(gt)&&ot.full_content&&(ye=ot.full_content),!ye&&$e.existsSync(gt)){let bt=$e.readFileSync(gt,"utf8");bt&&(ye=bt)}!ye&&Wt&&(ye=Wt),(ye||ve)&&$e.writeFileSync(gt,ye,"utf8");let Ht=ye.split(/\r?\n/),ht=Ht.length,Zt=Buffer.byteLength(ye,"utf8"),rt="";ce&&(rt=`Old File contents:
768
- ${ce.split(/\r?\n/).map((kt,Vn)=>`${Vn+1} | ${kt}`).join(`
751
+ `;for(let W of L.newFiles)ne+=`* ${W} (created)
752
+ `;for(let W of L.modifiedFiles)ne+=`* ${W} (modified)
753
+ `;for(let W of L.deletedFiles)ne+=`* ${W} (deleted)
754
+ `;ne+="[/system]",Ke.parts[0].text+=ne;let F=-1;for(let W=r.length-1;W>=0;W--)if(r[W].role==="user"&&r[W].text?.startsWith("[TOOL RESULT]")){F=W;break}F!==-1&&(r[F].text+=ne)}}catch{}let _t=Math.floor(Jn*(a==="Flux"?.98:.8)),yt=V+1;yt>=_t&&Ke&&Ke.parts?.[0]&&(Ke.parts[0].text+=`
755
+ [system] WARNING, Turn Limit Impending: Step ${yt}/${Jn}. Wrap up quickly/prompt user to continue. [/system]`);let Rt=new Promise((L,ne)=>{T.signal.aborted&&ne(new DOMException("The user aborted a request.","AbortError")),T.signal.addEventListener("abort",()=>{ne(new DOMException("The user aborted a request.","AbortError"))})});Rt.catch(()=>{});let ut=ie;if(i==="Ollama")_e=Hs(n.apiKey,he,ut,Ve,f,a,A,T.signal,1,h?.ollamaEndpoint||"Cloud");else if(i==="OpenRouter")_e=qo(n.apiKey,he,ut,Ve,f,a,A,T.signal,1,g);else if(i==="DeepSeek")_e=Vo(n.apiKey,he,ut,Ve,f,a,A,T.signal,1);else if(i==="Mistral")_e=Ko(n.apiKey,he,ut,Ve,f,a,A,T.signal,1,g);else if(i==="NVIDIA"){let L=Yo(n.apiKey,he,ut,Ve,f,a,A,T.signal,1);_e=Cr(L,he)}else if(i==="InferX")_e=zo(n.apiKey,he,ut,Ve,f,a,A,T.signal,1);else if(i==="SenseNova")_e=Jo(n.apiKey,he,ut,Ve,f,a,A,T.signal,1);else if(i==="AIHubMix")_e=Xo(n.apiKey,he,ut,Ve,f,a,A,T.signal,1);else if(i==="Poolside")_e=Qo(n.apiKey,he,ut,Ve,f,a,A,T.signal,1);else if(i==="9router"||i==="9Router")_e=Zo(n.apiKey,he,ut,Ve,f,a,A,T.signal,1);else if(i==="ExpLabs"||i==="ExperientialLabs")_e=es(n.apiKey,he,ut,Ve,f,a,A,T.signal,1);else if(i==="TokenHarbor"||i==="Token Harbor"||i==="tokenharbor"||i==="token_harbor"||i==="thk")_e=Gs(n.apiKey,he,ut,Ve,f,a,A,T.signal,1);else if(i==="APInex"||i==="apinex"||i==="apx")_e=js(n.apiKey,he,ut,Ve,f,a,A,T.signal,1);else{let ne=qs(n?.apiKey).models.generateContentStream({model:he||"gemini-3-flash-preview",contents:ut,config:{systemInstruction:Ve,mediaResolution:"MEDIA_RESOLUTION_HIGH",safetySettings:[{category:Cn.HARM_CATEGORY_HARASSMENT,threshold:An.BLOCK_NONE},{category:Cn.HARM_CATEGORY_HATE_SPEECH,threshold:An.BLOCK_NONE},{category:Cn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:An.BLOCK_NONE},{category:Cn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:An.BLOCK_NONE}],temperature:1.05,thinkingConfig:(()=>{let F=Ue("Google",he||"gemini-3-flash-preview",f);if(F!==null){if(typeof F=="object")return F;if(F===!1||F==="false"||F==="none"||F===0||F==="0")return{includeThoughts:!1};if(typeof F=="number")return{includeThoughts:!0,thinkingBudget:F};if(typeof F=="string"){let pe=F.toLowerCase();if(pe==="minimal")return{includeThoughts:!0,thinkingLevel:Ze.MINIMAL};if(pe==="low")return{includeThoughts:!0,thinkingLevel:Ze.LOW};if(pe==="medium")return{includeThoughts:!0,thinkingLevel:Ze.MEDIUM};if(pe==="high")return{includeThoughts:!0,thinkingLevel:Ze.HIGH};let Xe=Number(F);if(!isNaN(Xe))return{includeThoughts:!0,thinkingBudget:Xe}}}let W=(he||"").toLowerCase(),Te=W.includes("gemma-4")||W.startsWith("gemma"),ke=W.includes("gemini-3");if(Te||ke)return Te?f.toLowerCase()!=="high"?{includeThoughts:!1,thinkingLevel:Ze.MINIMAL}:{includeThoughts:!0,thinkingLevel:Ze.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:W.includes("pro")?Ze.LOW:Ze.MINIMAL,Low:Ze.LOW,Medium:Ze.MEDIUM,Standard:Ze.MEDIUM,High:Ze.HIGH,xHigh:Ze.HIGH}[f]||Ze.MEDIUM};{let pe={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[f]||2048;return pe===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:pe}}})()}},{signal:T.signal});_e=await Promise.race([ne,Rt])}le="",It=null,zt=null,Q=[],Je=0,yield{type:"model_update",content:null},Qe="",Ot=it.length>0;let sn="",ls=Date.now(),Dn=async function*(){if(i==="Google"&&sn){let L=Qn(sn);for(let ne of L)yield ne;sn="",ls=Date.now()}},ri=!0,On="",Wn=!1,xt=null,Hn=!1,Vr={tool:{startPrefix:"[tool",fullPrefix:"[tool:functions.",endTag:"]"},agent:{startPrefix:"[agent",fullPrefix:"[agent:generalist.",endTag:"]"},end:{startPrefix:"[[END]]",fullPrefix:"[[END]]",endTag:"[[END]]"},kimi_section:{startPrefix:"<|tool_calls_section_begin|>",fullPrefix:"<|tool_calls_section_begin|>",endTag:"<|tool_calls_section_end|>"},kimi_call:{startPrefix:"<|tool_call_begin|>",fullPrefix:"<|tool_call_begin|>",endTag:"<|tool_call_end|>"}},Qn=L=>{let ne=[],F=L;for(;F.length>0;)if(Wn){let W=On+F,Te=Vr[xt];if(Te){let Xe=!1;if(W.length<Te.startPrefix.length?Te.startPrefix.startsWith(W)||(Xe=!0):W.startsWith(Te.startPrefix)?W.length>=Te.fullPrefix.length&&!W.startsWith(Te.fullPrefix)&&(Xe=!0):Xe=!0,Xe){Hn||ne.push({type:"text",content:W}),On="",Wn=!1,xt=null,F="";break}}let ke=-1,pe=Te?Te.endTag:"]";if(xt==="tool"||xt==="agent"){let Xe=0,U=null,ee=0,He=!1;for(let y=0;y<W.length;y++){let Ge=W[y];if(U){if(Ge===U){let Me=0;for(let z=y-1;z>=0&&W[z]==="\\";z--)Me++;Me%2===0&&(U=null)}}else if(Ge==='"'||Ge==="'"||Ge==="`")U=Ge;else if(Ge==="(")Xe++,He=!0;else if(Ge===")")Xe--;else if(Ge==="[")ee++;else if(Ge==="]"){if(He&&Xe===0&&ee===1){ke=y;break}ee--}}}else ke=W.indexOf(pe);if(ke!==-1){let Xe=pe.length;if(!xt?.startsWith("kimi")){let U=W.substring(0,ke+Xe);ne.push({type:"text",content:U})}(xt==="tool"||xt==="agent"||xt?.startsWith("kimi"))&&(Hn=!0),On="",Wn=!1,xt=null,F=W.substring(ke+Xe)}else{let Xe=xt?.startsWith("kimi")?8192:512;W.length>Xe?(Hn||ne.push({type:"text",content:W}),On="",Wn=!1,xt=null):On=W,F="";break}}else{let W=F.indexOf("[tool"),Te=F.indexOf("[agent"),ke=F.indexOf("[[END]]"),pe=F.indexOf("<|tool_calls_section_begin|>"),Xe=F.indexOf("<|tool_call_begin|>"),U=[{type:"tool",idx:W,start:"[tool",end:"]"},{type:"agent",idx:Te,start:"[agent",end:"]"},{type:"end",idx:ke,start:"[[END]]",end:"[[END]]"},{type:"kimi_section",idx:pe,start:"<|tool_calls_section_begin|>",end:"<|tool_calls_section_end|>"},{type:"kimi_call",idx:Xe,start:"<|tool_call_begin|>",end:"<|tool_call_end|>"}].filter(ee=>ee.idx!==-1).sort((ee,He)=>ee.idx-He.idx);if(U.length>0){let ee=U[0];ee.idx>0&&(Hn||ne.push({type:"text",content:F.substring(0,ee.idx)})),Wn=!0,xt=ee.type,On="",F=F.substring(ee.idx)}else{let ee=["[tool","[agent","[[END]]","<|tool_calls_section_begin|>","<|tool_call_begin|>"],He=-1;for(let y of ee){for(let Ge=y.length-1;Ge>0;Ge--)if(F.endsWith(y.substring(0,Ge))){He=F.length-Ge;let Me=ee.indexOf(y);Me===0?xt="tool":Me===1?xt="agent":Me===2?xt="end":Me===3?xt="kimi_section":xt="kimi_call";break}if(He!==-1)break}if(He!==-1)He>0&&(Hn||ne.push({type:"text",content:F.substring(0,He)})),Wn=!0,On=F.substring(He),F="";else{Hn||ne.push({type:"text",content:F});break}}}return ne},Kr=_e[Symbol.asyncIterator]();for(;;){let{value:L,done:ne}=await Promise.race([Kr.next(),Rt]);if(ne)break;if(L&&L.type==="status"){yield L;continue}let F="",W=L.candidates?.[0]?.content?.parts;if(W&&W.length>0)for(let ke of W){let pe=typeof ke.text=="string"?ke.text:ke.text?parseChunkText(ke.text):"";ke.thought?pe&&(be||(F+="<think>",be=!0),F+=pe):pe&&(be&&(F+="</think>",be=!1),F+=pe)}else L.text&&be&&(F+="</think>",be=!1);F=Ia(F);let Te=F?ms(F):0;if(n&&typeof n.onTokenChunk=="function"&&n.onTokenChunk(F,Te),ri&&(yield{type:"status",content:"Thinking"},ri=!1),wt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
756
+
757
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(F){if(Ot){if(Qe+=F,Qe.length>=64){let U=0,ee=Math.min(it.length,Qe.length);for(let y=ee;y>=10;y--)if(it.endsWith(Qe.substring(0,y))){U=y;break}let He=Qe.substring(U);if(He){let Ge=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(it)?He.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):He.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(Ge)if(le+=Ge,i==="Google")sn+=Ge;else{yield*Dn();let Me=Qn(Ge);for(let z of Me)yield z}}Ot=!1,Qe=""}continue}else if(le+=F,i==="Google")sn+=F;else{yield*Dn();let U=Qn(F);for(let ee of U)yield ee}let ke=Ba(le);if(ke.inside){Rn=!0,zt||(zt=Date.now());let ee={Ask:"ask",AskUser:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Cancel:"cancel",Await:"await",Answer:"answer",Steer:"steer",steer:"steer"}[ke.toolName]||ke.toolName,He=ke.args||"",y=null;if(["write_file","update_file","view_file","read_folder","write_pdf","write_docx","search_keyword","generate_image","file_map","invoke","invoke_sync","get_progress","await","answer"].includes(ee)){let Me=Z(He),z=Me.path||Me.targetFile||Me.TargetFile||Me.directory,rn=Me.keyword,Ln=Me.title||Me.task,Tn=Me.id||Me.taskId,Re=Me.timeout||Me.time;if(rn!=null)y=String(rn).replace(Nn,"");else if(z)y=X.basename(String(z).replace(Nn,"").replace(vr,"/"));else if(Ln&&(ee==="invoke"||ee==="invoke_sync"))y=String(Ln).replace(Nn,"").substring(0,30);else if(Tn&&ee==="get_progress")y=String(Tn).replace(Nn,"");else if(Re&&ee==="await"){let $t=parseFloat(String(Re).replace(Nn,""));isNaN($t)?y=String(Re).replace(Nn,""):($t<5&&($t=5),$t>120&&($t=120),y=(mn=>{if(mn>=60){let ds=Math.floor(mn/60),Gn=mn%60;return`${ds}m${Gn>0?` ${Gn}s`:""}`}return`${mn}s`})($t))}else{let $t=He.match(va);if($t){let Ut=$t[1].replace(Nn,"");ee==="invoke"||ee==="invoke_sync"||ee==="get_progress"?y=Ut.substring(0,30):y=ee==="search_keyword"||ee==="file_map"?Ut:X.basename(Ut.replace(vr,"/"))}}}let Ge=`${Ks[ee]||ee}${y?` ${y}`:""}`;if((ee!==It||y!==tt)&&(It=ee,tt=y,yield{type:"status",content:`${Ge}`},process.stdout.isTTY)){let z={WebSearch:"Searching",web_search:"Searching",WebScrape:"Reading",web_scrape:"Reading",ReadFile:"Reading",read_file:"Reading",ReadFolder:"Reading",read_folder:"Reading",WriteFile:"Writing",write_file:"Writing",UpdateFile:"Editing",update_file:"Editing",WritePdf:"Creating",write_pdf:"Creating",WriteDocx:"Creating",write_docx:"Creating",SearchKeyword:"Searching",search_keyword:"Searching",CodeSearch:"Searching",code_search:"Searching",Run:"Executing",Ask:"User Input Required",AskUser:"User Input Required",Memory:"Updating Memory",GenerateImage:"Generating",InvokeSync:"Sub-Agent Working",invoke_sync:"Sub-Agent Working",Invoke:"Working",invoke:"Working",GetProgress:"Checking Progress",get_progress:"Checking Progress",Cancel:"Stopping Generalist",cancel:"Stopping Generalist",Await:"Waiting",await:"Waiting",EmergencyRollback:"Rolling the Ball",Answer:"Answering Sub-Agent",answer:"Answering Sub-Agent",Steer:"Steering Sub-Agent",steer:"Steering Sub-Agent",Click:"Clicking",click:"Clicking",Drag:"Dragging",drag:"Dragging",Scroll:"Scrolling",scroll:"Scrolling",KeyboardTyping:"Typing",keyboard_typing:"Typing",KeyPress:"Pressing Key",key_press:"Pressing Key",RecaptureScreen:"Recapturing Screen",recapture_screen:"Recapturing Screen"}[ee]||"Working";process.stdout.write(`\x1B]0;${z}...\x07`)}}if(le.length-wo>150){wo=le.length;let U=Fr(le,!1),ee=Vs(U),He=ee?(ee.innerContent||"").trim():"",y=He.split(/[.!?]\s+/),Ge=new Set(y),Me=y.length>10?(y.length-Ge.size)/y.length:0,z=He.split(/\s+/).filter(Ie=>Ie.length>0).length,rn=.6,Ln=.8,Tn=!1;if((i.toLowerCase().includes("google")||i.toLowerCase().includes("mistral"))&&((he||"").toLowerCase().startsWith("gemma")||(he||"").toLowerCase().includes("stral"))){let S={low:256,medium:1024,high:8192,max:16384,xhigh:16384}[f?.toLowerCase()]||2500;Tn=z>S}if(Me>rn||Tn){yield{type:"status",content:`${Me>rn?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},Dt=!0,await new Promise(S=>setTimeout(S,3e3));break}let Ut=Or(le).trim().split(/[.!?]\s+/),mn=new Set(Ut);if((Ut.length>10?(Ut.length-mn.size)/Ut.length:0)>Ln){yield{type:"status",content:"Response Loop Detected. Re-centering..."},Dt=!1,gn=!0,await new Promise(Ie=>setTimeout(Ie,3e3));break}let Gn=U.replace(wa,"").replace(Ta,"").replace(Sa,"").replace(_a,""),Nt=Gn.toLowerCase().split(/\s+/).map(Ie=>Ie.replace(Ea,"")).filter(Ie=>Ie.length>0),hn=!1;if(Nt.length>=10)for(let Ie=1;Ie<=15;Ie++){let S=Math.max(3,Math.ceil(10/Ie));if(Nt.length<Ie*S)continue;let j=Nt.slice(Nt.length-Ie),re=j.join(" ");if(Ie>1&&re===j.slice(0,Math.floor(Ie/2)).join(" ").repeat(2).trim())continue;let ce=!0;for(let we=1;we<S;we++)if(Nt.slice(Nt.length-Ie*(we+1),Nt.length-Ie*we).join(" ")!==re){ce=!1;break}if(ce){hn=!0;break}}if(!hn){let Ie=Gn.toLowerCase().replace(Aa,"");if(Ie.length>=20)for(let S=1;S<=10;S++){let j=Math.max(5,Math.ceil(16/S));if(Ie.length<S*j)continue;let re=Ie.substring(Ie.length-S),ce=!0;for(let we=1;we<j;we++)if(Ie.substring(Ie.length-S*(we+1),Ie.length-S*we)!==re){ce=!1;break}if(ce){hn=!0;break}}}if(hn){yield{type:"status",content:"Stuttering Detected. Re-centering..."},Dt=!1,on=!0,await new Promise(Ie=>setTimeout(Ie,3e3));break}}let pe=Kt(le),Xe=po(pe);for(;Xe.length>Je;){yield*Dn();let U=Xe[Je],ee=Date.now(),y={Ask:"ask",AskUser:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Await:"await",await:"await",AwaitSubagent:"await",awaitSubagent:"await",Answer:"answer",answer:"answer",AnswerSubagent:"answer",answerSubagent:"answer",Steer:"steer",steer:"steer",SteerSubagent:"steer",steerSubagent:"steer",Cancel:"cancel",cancel:"cancel",Click:"click",click:"click",Drag:"drag",drag:"drag",Scroll:"scroll",scroll:"scroll",KeyboardTyping:"keyboard_typing",keyboard_typing:"keyboard_typing",KeyPress:"key_press",key_press:"key_press",RecaptureScreen:"recapture_screen",recapture_screen:"recapture_screen",EmergencyRollback:"EmergencyRollback"}[U.toolName]||U.toolName,Ge=Ks[y]||U.toolName,Me=Bn(y,U.args);yield{type:"status",content:`${Ge}${Me?` ${Me}`:""}`};let z="";if(y==="click"){let S=Z(U.args);z=`\u2714 Clicked: ${S.intendedClickText?`${S.intendedClickText}`:""}`}else if(y==="drag"){let S=Z(U.args);z=`\u2714 Dragged: Cell ${S.fromGridId||""} \u2192 Cell ${S.toGridId||""}`}else if(y==="scroll"){let S=Z(U.args);z=`\u2714 Scrolled: ${S.direction||"down"} (${S.amount||1})`}else if(y==="keyboard_typing"){let S=Z(U.args);z=`\u2714 Typed: ${S.text?`"${S.text.length>20?S.text.substring(0,20)+"...":S.text}"`:""}`}else if(y==="key_press")z=`\u2714 Pressed Key: ${Z(U.args).key||""}`;else if(y==="recapture_screen")z="\u2714 Recaptured Screen";else if(y==="web_search"){let{query:S,limit:j=10,aiMode:re=!1}=Z(U.args);z=`${S?"\u2714":"\u2718"} ${re?"AI Search":"Searched"}: ${S?`${S}`:"No Search Query"}${re===!1&&S?` \u2192 ${j}`:""}`}else if(y==="web_scrape"){let S=Z(U.args).url||null;z=`${S?"\u2714":"\u2718"} Visited: ${S||"No Source"}`}else if(y==="view_file"){let{path:S,StartLine:j,EndLine:re,start_line:ce,end_line:we,startLine:Ye,endLine:De}=Z(U.args),Se=j||ce||Ye,Y=re||we||De,oe=parseInt(Se)||1,ae=parseInt(Y)||(Se?oe+800:800),qe="...",Le=ae,Ce=(S||"").trim().toLowerCase().replaceAll("\\","/");if(Ce.startsWith("#skill"))Ce.startsWith("#skill/global/fluxflow")||Ce.startsWith("#skills/global/fluxflow")?z="\u2714 Read Documentation":z=`\u2714 Read Skill: ${X.basename(S.replaceAll("\\","/"))}`;else{try{let ye=X.resolve(process.cwd(),S);if(Ne.existsSync(ye)){let ht=Ne.readFileSync(ye,"utf8").split(`
758
+ `).length;qe=ht,!Se&&!Y&&ht>800?Le=Math.min(50,ht):Le=Math.min(ae,ht)}}catch{}let Pe=(S||"").toLowerCase(),gt=Pe.endsWith(".pdf"),Oe=Pe.endsWith(".docx")||Pe.endsWith(".doc")||Pe.endsWith(".ppt")||Pe.endsWith(".pptx")||Pe.endsWith(".xls")||Pe.endsWith(".xlsx"),st=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(Pe);gt||Oe?z=`${S.length>0?"\u2714":"\u2718"} ${S?`Analyzed: ${X.basename(S)}`:"Analyzed: File Not Found"}`:st?z=`${S.length>0?"\u2714":"\u2718"} ${S?`Processed: ${X.basename(S)}`:"Processed: File Not Found"}`:z=`${qe!=="..."?"\u2714":"\u2718"} Read: ${S?`${X.basename(S)} \u2192 ${qe!=="..."?`Lines ${oe} - ${Le} of ${qe}`:"File Not Found"}`:"File Not Found"}`}}else if(y==="list_files"||y==="read_folder"){let S=y==="list_files"?"List":"Browsed",j=Z(U.args).path||null,re=Z(U.args).recurse||1;z=`${j?"\u2714":"\u2718"} ${S}: ${j?`${j==="."?`./${re>1?"*":""}`:`${j.replaceAll("\\","/")}${re>1?`${j.endsWith("/")?"*":"/*"}`:`${j.endsWith("/")?"":"/"}`}`}`:"No Folder Selected"}`}else if(y==="write_file"||y==="update_file"){let S=y==="write_file"?"Created":"Edited",j=Z(U.args).path||null;z=`${j?"\u2714":"\u2718"} ${S}: ${j.replaceAll("\\","/")||"No File Changes"}`}else if(y==="write_pdf"){let S=Z(U.args).path||null;z=`${S?"\u2714":"\u2718"} Generated: ${S.replaceAll("\\","/")||"No PDF Generated"}`}else if(y==="write_docx"){let S=Z(U.args).path||null;z=`${S?"\u2714":"\u2718"} Generated: ${S.replaceAll("\\","/")||"No Docx Generated"}`}else if(y==="file_map"){let S=Z(U.args).path;z=`${S?"\u2714":"\u2718"} Indexed: ${S.replaceAll("\\","/")?""+S:"File Not Found"}`}else if(y.toLowerCase()==="search_keyword"||y.toLowerCase()==="todo")z="";else if(y.toLowerCase()==="generate_image"){let{path:S,outputPath:j,output:re}=Z(U.args);z=`\u2714 Generated: ${S||j||re||"generated_image.png"}`}else if(y==="invoke_sync"||y==="InvokeSync"){let S=Bn(y,U.args);z=`\u2714 Called Generalist${S?`: ${S}`:""}`}else if(y==="Invoke"||y==="InvokeAsync"||y==="invoke"){let S=Bn(y,U.args);z=`\u2714 Started Generalist${S?`: ${S}`:""}`}else if(y==="get_progress"||y==="GetProgress"){let S=Bn(y,U.args);z=`\u2714 Checked${S?`: ${S}`:""}`}else if(y==="cancel"){let S=Bn(y,U.args);z=`\u{1F6C7} Cancelled${S?`: ${S}`:""}`}else if(y==="steer"||y==="Steer"){let S=Bn(y,U.args);z=`\u2714 Steered${S?`: ${S}`:""}`}else if(y==="EmergencyRollback"){let{method:S}=Z(U.args);z=S==="forceRevert"?"":"\u2714 Rollback Point Checked"}else if(y==="await"||y==="Await"){let{time:S,timeout:j}=Z(U.args),re=parseFloat(j||S)||0;re||(re=120);let ce=De=>{if(De>=60){let Se=Math.floor(De/60),Y=De%60;return`${Se}m${Y>0?` ${Y}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"];z=`\u2714 ${we[Math.floor(Math.random()*we.length)]} \u2192 ${ce(re)}`}else y==="Answer"||y==="answer"?z="\u2714 Resolved Sub-Agent Query":y==="exec_command"||y==="ask"?z="":z=`Executed: ${U.toolName}`;if(yield*Dn(),y==="exec_command"){let{command:S}=Z(U.args);if(S&&n.systemSettings&&n.systemSettings.allowExternalAccess===!1){let j=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],re=X.resolve(process.cwd()).substring(0,3).toLowerCase(),ce=Y=>{let oe=[],ae="",qe=null;for(let Le=0;Le<Y.length;Le++){let Ce=Y[Le];qe?(Ce===qe&&(qe=null),ae+=Ce):Ce==='"'||Ce==="'"?(qe=Ce,ae+=Ce):Ce==="&"&&Y[Le+1]==="&"||Ce==="|"&&Y[Le+1]==="|"?(ae.trim()&&(oe.push(ae.trim()),ae=""),Le++):Ce===";"||Ce==="|"||Ce==="&"?ae.trim()&&(oe.push(ae.trim()),ae=""):ae+=Ce}return ae.trim()&&oe.push(ae.trim()),oe},we=Y=>{let oe=[],ae="",qe=null;for(let Le=0;Le<Y.length;Le++){let Ce=Y[Le];qe?(Ce===qe&&(qe=null),ae+=Ce):Ce==='"'||Ce==="'"?(qe=Ce,ae+=Ce):/\s/.test(Ce)?ae&&(oe.push(ae),ae=""):ae+=Ce}return ae&&oe.push(ae),oe},Ye=Y=>{let oe=Y.replace(/^['"]|['"]$/g,"").trim();return!oe||process.platform==="win32"&&/^\/[a-zA-Z0-9?]+$/.test(oe)?!1:j.some(ae=>{if(ae.source==="[a-zA-Z]:[\\\\\\/]"){let qe=oe.match(/[a-zA-Z]:[\\\/]/i);return qe&&qe[0].toLowerCase()!==re}return ae.test(oe)})};if(ce(S).some(Y=>{let oe=we(Y);if(oe.length===0)return!1;let ae=oe[0].replace(/^['"]|['"]$/g,"").toLowerCase();if(["echo","printf","write-output"].includes(ae)){let Le=!1;return oe.some(Ce=>{let Wt=Ce.replace(/^['"]|['"]$/g,"");if(Wt===">"||Wt===">>"||Wt==="<")return Le=!0,!1;if(Wt.startsWith(">")||Wt.startsWith("<")){let Pe=Wt.replace(/^[><]+/,"");return Ye(Pe)}return Le?(Le=!1,Ye(Ce)):!1})}return oe.some(Le=>Ye(Le))})){let Y='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(oe=>setTimeout(oe,50)),n.onExecChunk&&n.onExecChunk(`ERROR: ${Y}`),await new Promise(oe=>setTimeout(oe,50)),n.onExecEnd&&n.onExecEnd(),Q.push({role:"user",text:`[TOOL RESULT]: ERROR: ${Y}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${Y}`},Je++;continue}}n.onExecStart&&n.onExecStart(S||"No Command"),yield{type:"exec_start"}}let rn=Z(U.args),Ln=rn.path||rn.targetPath||null;if(Ln){let S=n.systemSettings&&n.systemSettings.allowExternalAccess===!1,j=X.resolve(Ln),re=X.resolve(process.cwd());if(S&&!j.startsWith(re)){let ce="Access Denied. You are not allowed to access files outside the current workspace.";if(y==="write_file"||y==="update_file"){let Ye=`\u2718 ${y==="write_file"?"Write Canceled":"Edit Canceled"}: ${rn.path||"..."}`,De=115;process.stdout.isTTY&&(De=process.stdout.columns-5||120);let Se=Math.min(Ye.length+4,De),Y=`${Ye.padEnd(Se-2).substring(0,Se-2)}`;yield{type:"visual_feedback",content:Vt(`${je?`
759
+ `:""}${Y}
760
+ `)},je=!1}Q.push({role:"user",text:`[TOOL RESULT]: ERROR: ${ce}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${ce}`},Je++;continue}}if(n.onToolApproval&&(y==="write_file"||y==="update_file"||y==="exec_command")){let j=n.systemSettings||{},re=j.autoExec,ce=null,we=!1,Ye=!1,De=!1;if(y==="exec_command"){let{command:Pe}=Z(U.args),gt=(Pe||"").trim(),Oe=(Ht,ht)=>{if(!ht)return!1;let Zt=ht.split(",").map(Gt=>Gt.trim().toLowerCase()).filter(Boolean),at=Ht.toLowerCase();return Zt.some(Gt=>at.startsWith(Gt))},st=Oe(gt,j.alwaysAskCommands),ye=Oe(gt,j.autoApproveCommands);if(Ye=Oe(gt,j.autoDisallowCommands),st?we=!0:(ye||j.autoApproveGit&&/^git\s+commit\b/i.test(gt))&&(ce="allow"),!we&&!ce){if(j.networkAccess===!1){let ht=gt.trim().replace(/\s+/g," ").replace(/^['"]+|['"]+$/g,"").toLowerCase().split(" "),at=ht[0].split("/").pop().split("\\").pop().replace(/\.exe$/,""),Gt=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;Gt.has(at)&&(lt=!0);let rt=an=>ht.slice(1).some(ln=>an.includes(ln)),ct=an=>{let ln=ht.findIndex(pn=>an.includes(pn)),jn=ht.findIndex(pn=>["run","exec","test"].includes(pn));return ln!==-1&&!(jn!==-1&&jn<ln)};at==="git"&&rt(["clone","pull","push","fetch"])&&(lt=!0),at==="go"&&rt(["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"&&rt(["install","add"])&&(lt=!0),at==="pip"&&rt(["install","download"])&&(lt=!0),at==="pip3"&&rt(["install","download"])&&(lt=!0),at==="cargo"&&rt(["install","add"])&&(lt=!0),["bash","sh","zsh","fish"].includes(at)&&rt(["-c"])&&(lt=!0),at==="cmd"&&rt(["/c"])&&(lt=!0),lt&&(ce="deny",De=!0)}!ce&&Ye&&(ce="deny")}!we&&!ce&&re&&(ce="allow")}else re&&(ce="allow");let Se=ce,Y="";ce==="deny"&&(De?Y="network":Ye?Y="settings":Y="prohibited");let oe=!1,ae="",qe=[],Le=0,Ce=!1,Wt="";if(!Se){if(y==="write_file"||y==="update_file")try{let Oe=Z(U.args),{path:st}=Oe;if(st){let ye=X.resolve(process.cwd(),st),Ht=rt=>rt?rt.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,ct=>ct.toUpperCase()):"",ht=Ht(ye),Zt="",at=!1,Gt=await $n(),lt=Ht(Gt?.file_focused);if(Gt&&lt===ht&&Gt.full_content?(Zt=Gt.full_content,at=!0):Ne.existsSync(ye)&&(Zt=Ne.readFileSync(ye,"utf8"),at=!0),ae=Zt,await vo.recordFileChange(ye,Zt),at){let rt=Zt;if(y==="write_file"){let ct=Oe.content||Oe.newContent||"";rt=ct.endsWith(`
761
+ `)?ct:ct+`
762
+ `,Wt=rt}else{let{patchPairs:ct,allowMultiple:an,error:ln}=ci(Oe);if(ln){let kt=`[TOOL RESULT]: ERROR: ${ln}`;Q.push({role:"user",text:kt}),await At("toolFailure"),n.onToolResult&&n.onToolResult("failure",y),yield{type:"tool_result",content:kt,toolName:y},Je++;continue}let jn=Oe.allowMultiple!==void 0?Oe.allowMultiple===!0||String(Oe.allowMultiple).toLowerCase()==="true":an;Le=ct.length;let pn=di(Zt,ct,{allowMultiple:jn});rt=pn.content,Wt=rt,qe=pn.results;let To=qe.filter(kt=>kt.success),bt=qe.filter(kt=>!kt.success);if(To.length===0){let kt=`[TOOL RESULT]: ERROR: Failed to apply patches to [${X.basename(ye)}].
763
+ ${bt.map(to=>` \u2022 ${to.error}`).join(`
764
+ `)}`,Vn=`\u2714 Edited: ${X.basename(ye.replaceAll("\\","/"))}`,eo=115;process.stdout.isTTY&&(eo=process.stdout.columns-5||120);let Kn=Math.min(Vn.length+4,eo),So=`${Vn.padEnd(Kn-2).substring(0,Kn-2)}`;yield{type:"visual_feedback",content:Vt(`${je?`
765
+ `:""}${So}`)},je=!1,Q.push({role:"user",text:kt}),await At("toolFailure"),n.onToolResult&&n.onToolResult("failure",y),yield{type:"tool_result",content:kt,toolName:y},Je++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${X.basename(ye)}`},Fs(ye,Zt,rt),oe=!0,await new Promise(ct=>setTimeout(ct,50))}else if(y==="write_file"){let rt=Oe.content||Oe.newContent||"",ct=rt.endsWith(`
766
+ `)?rt:rt+`
767
+ `;Wt=ct,Ne.existsSync(ye)||(Ce=!0,Ne.mkdirSync(X.dirname(ye),{recursive:!0}),Ne.writeFileSync(ye,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${X.basename(ye)}`},Fs(ye,"",ct),oe=!0,await new Promise(an=>setTimeout(an,50))}}}catch(Oe){console.error("Simulation/Diff Error:",Oe)}let Pe=null;Ns(Oe=>{Pe=Oe});let gt=n.onToolApproval;if(Se=await new Promise(async Oe=>{let st=setInterval(()=>{Pe&&(ts.onIDEApproval&&ts.onIDEApproval(Pe),clearInterval(st),Oe(Pe))},100);try{let ye=await gt(y,U.args);clearInterval(st),Oe(ye)}catch{clearInterval(st),Oe("deny")}}),Ns(null),y==="write_file"||y==="update_file"){let{path:Oe}=Z(U.args);if(Oe){let st=X.resolve(process.cwd(),Oe);if(Er(st,Se),Se==="deny"&&Ce&&Ne.existsSync(st))try{Ne.unlinkSync(st)}catch{}}}Se==="deny"&&(Y="user")}if(Se==="allow"&&oe&&Go()){let{path:Pe}=Z(U.args),gt=X.resolve(process.cwd(),Pe),Oe=bt=>bt?X.resolve(bt).replace(/\\/g,"/").toLowerCase():"",st=await $n(),ye="";if(st&&st.file_focused&&Oe(st.file_focused)===Oe(gt)&&st.full_content&&(ye=st.full_content),!ye&&Ne.existsSync(gt)){let bt=Ne.readFileSync(gt,"utf8");bt&&(ye=bt)}!ye&&Wt&&(ye=Wt),(ye||Ce)&&Ne.writeFileSync(gt,ye,"utf8");let Ht=ye.split(/\r?\n/),ht=Ht.length,Zt=Buffer.byteLength(ye,"utf8"),at="";ae&&(at=`Old File contents:
768
+ ${ae.split(/\r?\n/).map((kt,Vn)=>`${Vn+1} | ${kt}`).join(`
769
769
  `)}
770
770
 
771
771
  `);let Gt="";if(ht<=100)Gt=Ht.join(`
@@ -775,85 +775,85 @@ ${ce.split(/\r?\n/).map((kt,Vn)=>`${Vn+1} | ${kt}`).join(`
775
775
 
776
776
  ... [${ht-100} lines truncated for history stability] ...
777
777
 
778
- ${kt}`}let at="";if(y==="update_file"){let bt=fi(ce,ye,Ce,12,n?.compressToolResults||ts?.systemSettings?.compressToolResults);at=`SUCCESS: File [${Le}] updated via IDE Companion (May have user edits). [${Ce.length}/${ze}] blocks applied.
778
+ ${kt}`}let lt="";if(y==="update_file"){let bt=fi(ae,ye,qe,12,n?.compressToolResults||ts?.systemSettings?.compressToolResults);lt=`SUCCESS: File [${Pe}] updated via IDE Companion (May have user edits). [${qe.length}/${Le}] blocks applied.
779
779
 
780
- ${bt}`}else{let bt=ye.split(/\r?\n/),kt=bt.length,Vn=Buffer.byteLength(ye,"utf8"),to="";ce&&(to=`Old File contents:
781
- ${ce.split(/\r?\n/).map((no,Zr)=>`${Zr+1} | ${no}`).join(`
780
+ ${bt}`}else{let bt=ye.split(/\r?\n/),kt=bt.length,Vn=Buffer.byteLength(ye,"utf8"),eo="";ae&&(eo=`Old File contents:
781
+ ${ae.split(/\r?\n/).map((to,Zr)=>`${Zr+1} | ${to}`).join(`
782
782
  `)}
783
783
 
784
784
  `);let Kn="";if(kt<=100)Kn=bt.join(`
785
- `);else{let _o=bt.slice(0,50).join(`
786
- `),no=bt.slice(-50).join(`
787
- `);Kn=`${_o}
785
+ `);else{let So=bt.slice(0,50).join(`
786
+ `),to=bt.slice(-50).join(`
787
+ `);Kn=`${So}
788
788
 
789
789
  ... [${kt-100} lines truncated] ...
790
790
 
791
- ${no}`}at=`SUCCESS: File [${Le}] saved via IDE Companion (May have user edits).
791
+ ${to}`}lt=`SUCCESS: File [${Pe}] saved via IDE Companion (May have user edits).
792
792
  - Stats: [${kt} lines, ${(Vn/1024).toFixed(1)} KB]
793
- ${to}- Content Preview:
793
+ ${eo}- Content Preview:
794
794
 
795
- ${Kn}`}let lt=`${Le?"\u2714":"\u2718"} ${y==="write_file"?"Created":"Edited"}: ${Le.replaceAll("\\","/")||"No File Changes"}`,an=115;process.stdout.isTTY&&(an=process.stdout.columns-5||120);let ln=Math.min(lt.length+4,an),jn=`${lt.padEnd(ln-2).substring(0,ln-2)}`;yield{type:"visual_feedback",content:Vt(`${Be?`
796
- `:""}${jn}`)},Be=!1;let pn=Date.now();j=pn,yield{type:"tool_time",content:pn-ne};let So=`[TOOL RESULT]: ${at}`;Q.push({role:"user",text:So}),Xt=!0,await At("toolSuccess"),n.onToolResult&&n.onToolResult("success",y),yield{type:"tool_result",content:at,aiContent:So,toolName:y},Ve++;continue}if(Te==="deny"){let Le=`Permission Denied: Prohibited ${y==="exec_command"?"Command":"file edit"}.`;if(q==="user"?Le="Permission Denied by User":q==="settings"?Le="Permission Denied by User Policy":q==="network"?Le="Permission Denied: Sandbox Network Access Disabled by User Policy.":q==="prohibited"&&y==="exec_command"&&(Le="Permission Denied: Prohibited Command in User Policy"),y==="write_file"||y==="update_file"){let De=`\u2718 ${y==="write_file"?"Write Cancelled":"Edit Denied"}: ${Z(W.args).path.replaceAll("\\","/")||"..."}`,ot=115;process.stdout.isTTY&&(ot=process.stdout.columns-5||120);let ye=Math.min(De.length+4,ot),Ht=`${De.padEnd(ye-2).substring(0,ye-2)}`,ht=` ${" ".repeat(ye)} `;yield{type:"visual_feedback",content:Vt(`${Be?`
795
+ ${Kn}`}let ct=`${Pe?"\u2714":"\u2718"} ${y==="write_file"?"Created":"Edited"}: ${Pe.replaceAll("\\","/")||"No File Changes"}`,an=115;process.stdout.isTTY&&(an=process.stdout.columns-5||120);let ln=Math.min(ct.length+4,an),jn=`${ct.padEnd(ln-2).substring(0,ln-2)}`;yield{type:"visual_feedback",content:Vt(`${je?`
796
+ `:""}${jn}`)},je=!1;let pn=Date.now();G=pn,yield{type:"tool_time",content:pn-ee};let To=`[TOOL RESULT]: ${lt}`;Q.push({role:"user",text:To}),Xt=!0,await At("toolSuccess"),n.onToolResult&&n.onToolResult("success",y),yield{type:"tool_result",content:lt,aiContent:To,toolName:y},Je++;continue}if(Se==="deny"){let Pe=`Permission Denied: Prohibited ${y==="exec_command"?"Command":"file edit"}.`;if(Y==="user"?Pe="Permission Denied by User":Y==="settings"?Pe="Permission Denied by User Policy":Y==="network"?Pe="Permission Denied: Sandbox Network Access Disabled by User Policy.":Y==="prohibited"&&y==="exec_command"&&(Pe="Permission Denied: Prohibited Command in User Policy"),y==="write_file"||y==="update_file"){let Oe=`\u2718 ${y==="write_file"?"Write Cancelled":"Edit Denied"}: ${Z(U.args).path.replaceAll("\\","/")||"..."}`,st=115;process.stdout.isTTY&&(st=process.stdout.columns-5||120);let ye=Math.min(Oe.length+4,st),Ht=`${Oe.padEnd(ye-2).substring(0,ye-2)}`,ht=` ${" ".repeat(ye)} `;yield{type:"visual_feedback",content:Vt(`${je?`
797
797
  `:""}${Ht}
798
- `)},Be=!1}y==="exec_command"&&(await new Promise(gt=>setTimeout(gt,50)),n.onExecChunk&&n.onExecChunk(`ERROR: ${Le}`),await new Promise(gt=>setTimeout(gt,50)),n.onExecEnd&&n.onExecEnd()),Q.push({role:"user",text:`[TOOL RESULT]: DENIED: ${Le}`}),yield{type:"tool_result",content:`[TOOL RESULT]: DENIED: ${Le}`},await At("toolDenied"),n.onToolResult&&n.onToolResult("denied",y),Ve++;continue}}if(z){let _=115;process.stdout.isTTY&&(_=process.stdout.columns-5||120);let V=await s(),ae=!1;V&&(ae=V.trim().length>0);let de=Math.min(z.length+4,_),ke=`${z.padEnd(de-2).substring(0,de-2)}`;yield{type:"visual_feedback",content:Vt(`${Be?`
799
- `:""}${ke}${z.includes("\u2714")&&(z.includes("Created")||z.includes("Edited"))?"":`${ae?"":`
800
- `}`}`)},Be=!1}if(j>0){let _=Date.now()-j,V=Math.max(0,1e3-_);V>0&&await new Promise(ae=>setTimeout(ae,V))}let Tn={chatId:g,history:t,onChunk:_=>n.onExecChunk?n.onExecChunk(_):null,onAskUser:n.onAskUser,systemSettings:n.systemSettings,mode:a,isMultiModal:dt(me),onVisualFeedback:n.onVisualFeedback,onSubagentUpdate:n.onSubagentUpdate,onTokenChunk:n.onTokenChunk,modelName:me,aiProvider:n.aiProvider,apiKey:n.apiKey,onUsage:n.onUsage};if(y==="write_file"||y==="update_file")try{let{path:_}=Z(W.args);if(_){let V=J.resolve(process.cwd(),_),ae=await $n();ae&&ae.file_focused===V&&ae.full_content&&(Tn.forcedContent=ae.full_content)}}catch{}qt.push(y);let Ae=await mo(y,W.args,Tn);if((y==="write_file"||y==="update_file")&&Ae.startsWith("SUCCESS")){let{path:_}=Z(W.args);if(_){let V=J.resolve(process.cwd(),_);_r(V)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let $t=Date.now();j=$t,yield{type:"tool_time",content:$t-ne},zt=$t;let Ut=null;if(typeof Ae=="object"&&Ae.binaryPart&&(Ut=Ae.binaryPart,Ae=Ae.text),y==="search_keyword"){let{keyword:_,path:V}=Z(W.args),ae=typeof Ae=="string"&&Ae.startsWith("[GLOB]");ae&&(Ae=Ae.slice(6).trimStart());let de=typeof Ae=="string"&&Ae.startsWith("[DIR]");de&&(Ae=Ae.slice(5).trimStart());let ke=0;if(Ae){let Ce=Ae.match(/Found (\d+) match/i);Ce&&(ke=parseInt(Ce[1]))}let He=(V||"").trim().toLowerCase().replaceAll("\\","/"),Ie=He==="#doc"||He==="#docs"||He==="#documentation"||He.includes("#skill/global/fluxflow")||He.includes("#skills/global/fluxflow"),Te;if(Ie)Te=`${_?"\u2714":"\u2718"} Searched Documentation`;else{let Ce=V?V.replace(/[\/\\]+$/,""):null,ze=Ce&&Ce!=="."?`"${ae?V:de?`${Ce}/*`:Ce}"`:"./";Te=`${_?"\u2714":"\u2718"} Searched: "${_||""}" in ${ze.replaceAll("\\","/")} \u2192 ${ke} Match${ke===1?"":"es"}`}let q=115;process.stdout.isTTY&&(q=process.stdout.columns-5||120);let oe=Math.min(Te.length+4,q),ce=`${Te.padEnd(oe-2).substring(0,oe-2)}`;yield{type:"visual_feedback",content:Vt(`${Be?`
801
- `:""}${ce}
802
- `)},Be=!1}if(y==="EmergencyRollback"){let{method:_}=Z(W.args);if(_==="forceRevert"){let V=0;if(Ae){let oe=Ae.match(/Total\s*:\s*(\d+)/i);oe&&(V=parseInt(oe[1]))}let de=Ae&&Ae.startsWith("ERROR:")?"\u2718 Emergency Rollback Failed":`\u2714 Emergency Rollback \u2192 ${V} file${V===1?"":"s"} processed`,ke=115;process.stdout.isTTY&&(ke=process.stdout.columns-5||120);let He=await s(),Ie=!1;He&&(Ie=He.trim().length>0);let Te=Math.min(de.length+4,ke),q=`${de.padEnd(Te-2).substring(0,Te-2)}`;yield{type:"visual_feedback",content:Vt(`${Be?`
803
- `:""}${q}${Ie?"":`
804
- `}`)},Be=!1}}if(y==="todo"){let{method:_,tasks:V,markDone:ae}=Z(W.args),de="",ke=[],He=Ie=>{if(!Ie)return[];let Te=Array.isArray(Ie)?Ie:[];if(Te.length===0&&typeof Ie=="string"){let q=Ie.trim();if(q.startsWith("[")&&q.endsWith("]")){let oe=q.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);oe?Te=oe.map(ce=>ce.slice(1,-1).replace(/\\(.)/g,"$1")):Te=q.slice(1,-1).split(",").map(ce=>ce.trim()).filter(Boolean)}else Te=Ie.split(`
805
- `)}return Te.filter(q=>String(q).trim()).map(q=>{let oe=String(q).trim();return oe.startsWith("- [")?oe.substring(6).trim():oe})};if(_==="create"?(de="\x1B[32m\u2192\x1B[0m Created Goals",ke=He(V).map(Ie=>`\x1B[90m\u25CB\x1B[0m ${Ie}`)):_==="append"?(de="\x1B[34m\u2795\x1B[0m Added New Goals",ke=He(V).map(Ie=>`\x1B[90m\u25CB\x1B[0m ${Ie}`)):_==="get"&&(de=ae?"\x1B[36m\u21BB\x1B[0m Updated Goals":"\x1B[35m\u2022\x1B[0m Reviewed Goals",ke=(Ae||"").split(`
798
+ `)},je=!1}y==="exec_command"&&(await new Promise(gt=>setTimeout(gt,50)),n.onExecChunk&&n.onExecChunk(`ERROR: ${Pe}`),await new Promise(gt=>setTimeout(gt,50)),n.onExecEnd&&n.onExecEnd()),Q.push({role:"user",text:`[TOOL RESULT]: DENIED: ${Pe}`}),yield{type:"tool_result",content:`[TOOL RESULT]: DENIED: ${Pe}`},await At("toolDenied"),n.onToolResult&&n.onToolResult("denied",y),Je++;continue}}if(z){let S=115;process.stdout.isTTY&&(S=process.stdout.columns-5||120);let j=await s(),re=!1;j&&(re=j.trim().length>0);let ce=Math.min(z.length+4,S),we=`${z.padEnd(ce-2).substring(0,ce-2)}`;yield{type:"visual_feedback",content:Vt(`${je?`
799
+ `:""}${we}${z.includes("\u2714")&&(z.includes("Created")||z.includes("Edited"))?"":`${re?"":`
800
+ `}`}`)},je=!1}if(G>0){let S=Date.now()-G,j=Math.max(0,1e3-S);j>0&&await new Promise(re=>setTimeout(re,j))}let Tn={chatId:g,history:t,onChunk:S=>n.onExecChunk?n.onExecChunk(S):null,onAskUser:n.onAskUser,systemSettings:n.systemSettings,mode:a,isMultiModal:ft(he),onVisualFeedback:n.onVisualFeedback,onSubagentUpdate:n.onSubagentUpdate,onTokenChunk:n.onTokenChunk,modelName:he,aiProvider:n.aiProvider,apiKey:n.apiKey,onUsage:n.onUsage};if(y==="write_file"||y==="update_file")try{let{path:S}=Z(U.args);if(S){let j=X.resolve(process.cwd(),S),re=await $n();re&&re.file_focused===j&&re.full_content&&(Tn.forcedContent=re.full_content)}}catch{}qt.push(y);let Re=await go(y,U.args,Tn);if((y==="write_file"||y==="update_file")&&Re.startsWith("SUCCESS")){let{path:S}=Z(U.args);if(S){let j=X.resolve(process.cwd(),S);_r(j)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let $t=Date.now();G=$t,yield{type:"tool_time",content:$t-ee},zt=$t;let Ut=null;if(typeof Re=="object"&&Re.binaryPart&&(Ut=Re.binaryPart,Re=Re.text),y==="search_keyword"){let{keyword:S,path:j}=Z(U.args),re=typeof Re=="string"&&Re.startsWith("[GLOB]");re&&(Re=Re.slice(6).trimStart());let ce=typeof Re=="string"&&Re.startsWith("[DIR]");ce&&(Re=Re.slice(5).trimStart());let we=0;if(Re){let Le=Re.match(/Found (\d+) match/i);Le&&(we=parseInt(Le[1]))}let Ye=(j||"").trim().toLowerCase().replaceAll("\\","/"),De=Ye==="#doc"||Ye==="#docs"||Ye==="#documentation"||Ye.includes("#skill/global/fluxflow")||Ye.includes("#skills/global/fluxflow"),Se,Y=115;process.stdout.isTTY&&(Y=process.stdout.columns-5||120);let oe=Math.max(10,Y/2);if(De)Se=`${S?"\u2714":"\u2718"} Searched Documentation`;else{let Le=j?j.replace(/[\/\\]+$/,""):null,Ce=Le&&Le!=="."?`"${re?j:ce?`${Le}/*`:Le}"`:"./";Se=`${S?"\u2714":"\u2718"} Searched: "${S?S.length>Y/2?`${S.slice(oe)}...`:S:""}" in ${Ce.replaceAll("\\","/")} \u2192 ${we} Match${we===1?"":"es"}`}let ae=Math.min(Se.length+4,Y),qe=`${Se.padEnd(ae-2).substring(0,ae-2)}`;yield{type:"visual_feedback",content:Vt(`${je?`
801
+ `:""}${qe}
802
+ `)},je=!1}if(y==="EmergencyRollback"){let{method:S}=Z(U.args);if(S==="forceRevert"){let j=0;if(Re){let oe=Re.match(/Total\s*:\s*(\d+)/i);oe&&(j=parseInt(oe[1]))}let ce=Re&&Re.startsWith("ERROR:")?"\u2718 Emergency Rollback Failed":`\u2714 Emergency Rollback \u2192 ${j} file${j===1?"":"s"} processed`,we=115;process.stdout.isTTY&&(we=process.stdout.columns-5||120);let Ye=await s(),De=!1;Ye&&(De=Ye.trim().length>0);let Se=Math.min(ce.length+4,we),Y=`${ce.padEnd(Se-2).substring(0,Se-2)}`;yield{type:"visual_feedback",content:Vt(`${je?`
803
+ `:""}${Y}${De?"":`
804
+ `}`)},je=!1}}if(y==="todo"){let{method:S,tasks:j,markDone:re}=Z(U.args),ce="",we=[],Ye=De=>{if(!De)return[];let Se=Array.isArray(De)?De:[];if(Se.length===0&&typeof De=="string"){let Y=De.trim();if(Y.startsWith("[")&&Y.endsWith("]")){let oe=Y.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);oe?Se=oe.map(ae=>ae.slice(1,-1).replace(/\\(.)/g,"$1")):Se=Y.slice(1,-1).split(",").map(ae=>ae.trim()).filter(Boolean)}else Se=De.split(`
805
+ `)}return Se.filter(Y=>String(Y).trim()).map(Y=>{let oe=String(Y).trim();return oe.startsWith("- [")?oe.substring(6).trim():oe})};if(S==="create"?(ce="\x1B[32m\u2192\x1B[0m Created Goals",we=Ye(j).map(De=>`\x1B[90m\u25CB\x1B[0m ${De}`)):S==="append"?(ce="\x1B[34m\u2795\x1B[0m Added New Goals",we=Ye(j).map(De=>`\x1B[90m\u25CB\x1B[0m ${De}`)):S==="get"&&(ce=re?"\x1B[36m\u21BB\x1B[0m Updated Goals":"\x1B[35m\u2022\x1B[0m Reviewed Goals",we=(Re||"").split(`
806
806
  `).slice(1).join(`
807
807
  `).split(`
808
- `).filter(Te=>Te.trim().startsWith("- [")).map(Te=>{let q=Te.trim(),oe=q.startsWith("- [x]");return`${oe?"\x1B[32m\u2714\x1B[0m":"\x1B[90m\u25CB\x1B[0m"} ${oe?"\x1B[90m":"\x1B[37m"}${q.substring(6).trim()}\x1B[0m`})),de&&ke.length>0){let Ie=[`${de}`,...ke.map(oe=>` ${oe}`)].join(`
809
- `),Te=await s(),q=!1;Te&&(q=Te.trim().length>0),yield{type:"visual_feedback",content:Vt(`${Be?`
810
- `:""}${Ie}${q?"":`
811
- `}`)},Be=!1}}y==="exec_command"&&n.onExecEnd&&(await new Promise(_=>setTimeout(_,800)),n.onExecEnd());let mn=Ae&&Ae.startsWith("DENIED:");Ae&&!Ae.startsWith("ERROR:")&&!mn?(await At("toolSuccess"),n.onToolResult&&n.onToolResult("success",y)):mn||(await At("toolFailure"),n.onToolResult&&n.onToolResult("failure",y));let Nt=(Ae||"").toString().replaceAll("[UI_CONTEXT]","");Nt.includes("[[VERIFIED]]")&&(Nt=Nt.replace(/\[\[VERIFIED\]\][\s\S]*?\[\[\/VERIFIED\]\]/g,`[SYSTEM NOTE]: Patch Block matched & applied successfully. Large Block omitted to conserve context.
812
- `));let hn;if(Nt.startsWith("[[SAME]]")){let V=Nt.replace(/^\[\[SAME\]\]\s*\r?\n?/,"").split(/\r?\n/),ae=V.filter(ke=>ke.startsWith("SUCCESS:")||ke.trim().startsWith("- Stats:"));hn=`[TOOL RESULT]: ${ae.length>0?ae.join(`
813
- `):V.slice(0,2).join(`
808
+ `).filter(Se=>Se.trim().startsWith("- [")).map(Se=>{let Y=Se.trim(),oe=Y.startsWith("- [x]");return`${oe?"\x1B[32m\u2714\x1B[0m":"\x1B[90m\u25CB\x1B[0m"} ${oe?"\x1B[90m":"\x1B[37m"}${Y.substring(6).trim()}\x1B[0m`})),ce&&we.length>0){let De=[`${ce}`,...we.map(oe=>` ${oe}`)].join(`
809
+ `),Se=await s(),Y=!1;Se&&(Y=Se.trim().length>0),yield{type:"visual_feedback",content:Vt(`${je?`
810
+ `:""}${De}${Y?"":`
811
+ `}`)},je=!1}}y==="exec_command"&&n.onExecEnd&&(await new Promise(S=>setTimeout(S,800)),n.onExecEnd());let mn=Re&&Re.startsWith("DENIED:");Re&&!Re.startsWith("ERROR:")&&!mn?(await At("toolSuccess"),n.onToolResult&&n.onToolResult("success",y)):mn||(await At("toolFailure"),n.onToolResult&&n.onToolResult("failure",y));let Nt=(Re||"").toString().replaceAll("[UI_CONTEXT]","");Nt.includes("[[VERIFIED]]")&&(Nt=Nt.replace(/\[\[VERIFIED\]\][\s\S]*?\[\[\/VERIFIED\]\]/g,`[SYSTEM NOTE]: Patch Block matched & applied successfully. Large Block omitted to conserve context.
812
+ `));let hn;if(Nt.startsWith("[[SAME]]")){let j=Nt.replace(/^\[\[SAME\]\]\s*\r?\n?/,"").split(/\r?\n/),re=j.filter(we=>we.startsWith("SUCCESS:")||we.trim().startsWith("- Stats:"));hn=`[TOOL RESULT]: ${re.length>0?re.join(`
813
+ `):j.slice(0,2).join(`
814
814
  `)}
815
- [SYSTEM NOTE]: Content verified and persisted to disk. Full preview omitted to conserve context.`}else hn=`[TOOL RESULT]: ${Nt}`;Q.push({role:"user",text:hn,binaryPart:Ut}),Xt=!0;let Me=`[TOOL RESULT]: ${Ae.replaceAll(`[[VERIFIED]]
815
+ [SYSTEM NOTE]: Content verified and persisted to disk. Full preview omitted to conserve context.`}else hn=`[TOOL RESULT]: ${Nt}`;Q.push({role:"user",text:hn,binaryPart:Ut}),Xt=!0;let Ie=`[TOOL RESULT]: ${Re.replaceAll(`[[VERIFIED]]
816
816
  `,"").replaceAll(`
817
- [[/VERIFIED]]`,"")||""}`;(y==="view_file"||y==="web_scrape"||y==="file_map")&&(Me=`[TOOL RESULT]: ${z} (Context Locked for UI Clarity)`),yield{type:"tool_result",content:Me,aiContent:hn,binaryPart:Ut,toolName:y},y==="memory"&&Ae.includes("SUCCESS")&&(yield{type:"memory_updated"}),Ve++}if(i==="Google"&&sn&&Date.now()-ls>=150){yield*Dn();let W=Zn(sn);for(let ne of W)yield ne;sn="",ls=Date.now()}}L.usageMetadata&&(un=L.usageMetadata),un&&(yield{type:"liveTokens",content:un.totalTokenCount})}if(xe&&(xe=!1,Ot?qe+="</think>":(le+="</think>",i==="Google"?sn+="</think>":yield{type:"text",content:"</think>"})),Ot&&qe.length>0){let L=0,se=Math.min(st.length,qe.length);for(let H=se;H>0;H--)if(st.endsWith(qe.substring(0,H))){L=H;break}let F=qe.substring(L);if(F){let we=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(st)?F.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):F.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(we)if(le+=we,i==="Google")sn+=we;else{yield*Dn();let be=Zn(we);for(let he of be)yield he}}Ot=!1,qe=""}if(yield*Dn(),wt)break;let eo=(le||"").trim(),Yr=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(eo.toLowerCase())||/\[\[END\]\]/i.test(eo.toLowerCase()),qr=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(eo.toLowerCase()),zr=Q.length>0||It!==null,cs=Kt(eo).trim(),Jr=/(\p{Emoji_Presentation}|\p{Extended_Pictographic})$/u.test(cs),Xr=/([.!?"'*_`|\]\)”’~~]+|\s|`{3}|[\u200B-\u200D\uFEFF])$/u.test(cs.trim()),Qr=/[.!?}"'`’“”]$|```$/s.test(cs)||Xr||Jr;!Yr&&!qr&&!zr&&eo.length>0,nt=!0,await At("agent",i)}catch(Ee){if(wt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
817
+ [[/VERIFIED]]`,"")||""}`;(y==="view_file"||y==="web_scrape"||y==="file_map")&&(Ie=`[TOOL RESULT]: ${z} (Context Locked for UI Clarity)`),yield{type:"tool_result",content:Ie,aiContent:hn,binaryPart:Ut,toolName:y},y==="memory"&&Re.includes("SUCCESS")&&(yield{type:"memory_updated"}),Je++}if(i==="Google"&&sn&&Date.now()-ls>=150){yield*Dn();let U=Qn(sn);for(let ee of U)yield ee;sn="",ls=Date.now()}}L.usageMetadata&&(un=L.usageMetadata),un&&(yield{type:"liveTokens",content:un.totalTokenCount})}if(be&&(be=!1,Ot?Qe+="</think>":(le+="</think>",i==="Google"?sn+="</think>":yield{type:"text",content:"</think>"})),Ot&&Qe.length>0){let L=0,ne=Math.min(it.length,Qe.length);for(let W=ne;W>0;W--)if(it.endsWith(Qe.substring(0,W))){L=W;break}let F=Qe.substring(L);if(F){let Te=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(it)?F.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):F.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(Te)if(le+=Te,i==="Google")sn+=Te;else{yield*Dn();let ke=Qn(Te);for(let pe of ke)yield pe}}Ot=!1,Qe=""}if(yield*Dn(),wt)break;let Zn=(le||"").trim(),Yr=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(Zn.toLowerCase())||/\[\[END\]\]/i.test(Zn.toLowerCase()),qr=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(Zn.toLowerCase()),zr=Q.length>0||It!==null,cs=Kt(Zn).trim(),Jr=/(\p{Emoji_Presentation}|\p{Extended_Pictographic})$/u.test(cs),Xr=/([.!?"'*_`|\]\)”’~~]+|\s|`{3}|[\u200B-\u200D\uFEFF])$/u.test(cs.trim()),Qr=/[.!?}"'`’“”]$|```$/s.test(cs)||Xr||Jr;!Yr&&!qr&&!zr&&Zn.length>0,ot=!0,await At("agent",i)}catch(Ae){if(wt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
818
818
 
819
- \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(String(Ee).includes("Incomplete JSON segment at the end")){xe&&(xe=!1,Ot?qe+="</think>":(le+="</think>",yield{type:"text",content:"</think>"})),nt=!0,await At("agent",i);break}if(xe&&(xe=!1,Ot?qe+="</think>":le+="</think>"),Ot&&qe.length>0){let Pt=0,_t=Math.min(st.length,qe.length);for(let Rt=_t;Rt>0;Rt--)if(st.endsWith(qe.substring(0,Rt))){Pt=Rt;break}let yt=qe.substring(Pt);if(yt){let ut=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(st)?yt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):yt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");ut&&(le+=ut)}Ot=!1,qe=""}let re=Ee instanceof Error?(()=>{try{return JSON.parse(JSON.parse(Ee.message).error.message).error.message}catch{return String(Ee)}})():String(Ee),Lt=new Date().toLocaleString(),vt=J.join(Sn,"agent");$e.existsSync(vt)||$e.mkdirSync(vt,{recursive:!0}),$e.appendFileSync(J.join(vt,"error.log"),`ERROR [${Lt}]: ${re}
819
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(String(Ae).includes("Incomplete JSON segment at the end")){be&&(be=!1,Ot?Qe+="</think>":(le+="</think>",yield{type:"text",content:"</think>"})),ot=!0,await At("agent",i);break}if(be&&(be=!1,Ot?Qe+="</think>":le+="</think>"),Ot&&Qe.length>0){let Pt=0,_t=Math.min(it.length,Qe.length);for(let Rt=_t;Rt>0;Rt--)if(it.endsWith(Qe.substring(0,Rt))){Pt=Rt;break}let yt=Qe.substring(Pt);if(yt){let ut=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(it)?yt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):yt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");ut&&(le+=ut)}Ot=!1,Qe=""}let ie=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(),vt=X.join(Sn,"agent");Ne.existsSync(vt)||Ne.mkdirSync(vt,{recursive:!0}),Ne.appendFileSync(X.join(vt,"error.log"),`ERROR [${Lt}]: ${ie}
820
820
 
821
821
  ----------------------------------------------------------------------
822
822
 
823
- `);let St=Ee.status||Ee.statusCode||Ee.code,Jt=String(Ee).includes("replicas at capacity");if(!(St&&(St>=500&&St<600||St===408||St===429||Jt)||!St&&(/status[ :]+(5\d\d|408|429)/i.test(String(Ee))||/code[ :]+(5\d\d|408|429)/i.test(String(Ee))||/(500|503|408|429)/.test(String(Ee))))){if(je<nn-3)throw Ee;yield{type:"text",content:re},yield{type:"status",content:"Error Occured"}}if(le.trim().length>0||Ze>1)if(Ze<=nn){Ze++;let Pt=Math.min(1e3*Math.pow(2,Ze-1),24e3);if(le.trim().length>0){r.push({role:"agent",text:le});let _t=`[system]
823
+ `);let St=Ae.status||Ae.statusCode||Ae.code,Jt=String(Ae).includes("replicas at capacity");if(!(St&&(St>=500&&St<600||St===408||St===429||Jt)||!St&&(/status[ :]+(5\d\d|408|429)/i.test(String(Ae))||/code[ :]+(5\d\d|408|429)/i.test(String(Ae))||/(500|503|408|429)/.test(String(Ae))))){if(ze<nn-3)throw Ae;yield{type:"text",content:ie},yield{type:"status",content:"Error Occured"}}if(le.trim().length>0||et>1)if(et<=nn){et++;let Pt=Math.min(1e3*Math.pow(2,et-1),24e3);if(le.trim().length>0){r.push({role:"agent",text:le});let _t=`[system]
824
824
  - seamless continuation: resume immediately. pick up from last words with zero gap/disruption
825
825
  - no repetition: do not repeat any text already written
826
826
  - no re-think: do not restart or open <think> if reasoning already started. continue the thinking and close thinking block </think> before chat output
827
827
  - mid-tool safety: if cutoff was mid-tool call, restart that tool call from start
828
828
  - stealth: do not mention/apologize for cutoff [/system]`;Q.length>0?Q.forEach((yt,Rt)=>{Rt===Q.length-1?r.push({...yt,text:`${yt.text}
829
829
 
830
- ${_t}`}):r.push(yt)}):r.push({role:"user",text:_t}),st+=le}for(let _t=Pt/1e3;_t>0&&!wt;_t--)yield{type:"status",content:`Error Occured. Recovering Stream (${Ze}/${nn}) [Retrying in ${_t.toFixed(0)}s]...`},await new Promise(yt=>setTimeout(yt,1e3));yield{type:"status",content:"Error Occured. Recovering Stream..."}}else throw new Error(`Stream collapsed too many times. (Failed to resolve ${nn} times)
831
- Error log can be found in \`/export logs\``);else if(je<=nn){je++,Ze=1,st="";let Pt=Math.min(1e3*Math.pow(2,je-1),32e3),_t=.8+Math.random()*.4,yt=Math.round(Pt*_t);vn=!0,yield{type:"status",content:`Trying to reach ${e} (${je}/${nn}) [Retrying in ${(yt/1e3).toFixed(0)}s]`};for(let Rt=yt/1e3;Rt>0&&!wt;Rt--)yield{type:"status",content:`Trying to reach ${e} (${je}/${nn}) [Retrying in ${Rt.toFixed(0)}s]`},await new Promise(ut=>setTimeout(ut,1e3));yield{type:"status",content:`Trying to reach ${e}`}}else throw new Error(`Model ${e} cannot be reached. (Failed ${nn} times)
832
- Error log can be found in \`/export logs\``)}}if(un){let xe=un.totalTokenCount||0,Ee=un.cachedContentTokenCount||0,re=(un.candidatesTokenCount||0)+(i==="Google"&&un.thoughtsTokenCount||0);await Ft("tokens",xe,i,me),Ee>0&&await Ft("cachedTokens",Ee,i,me),re>0&&await Ft("candidateTokens",re,i,me),yield{type:"usage",content:un}}le=Nr(le),ii.push(le);let Mn=Kt(le),Qt=Or(le),Qn=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(Qt.toLowerCase())||/\[\[END\]\]/i.test(Qt.toLowerCase())||!0,wn=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(Qt.toLowerCase()),Ka=Ve>0;yield{type:"status",content:"Thinking"};let Gr=Ua(le,/(\[\s*(turn\s*:)?\s*(continue|finish)\s*\]|\[\[END\]\])/gi,"").trim(),In=(Qn||Q.length===0)&&!Dt&&!on&&!gn;if(In=Q.length===0?In:!1,In=Rn||wo?!1:In,le&&le.trim().endsWith('")]')&&Q.length===0&&(In=!1),In){let xe=ii.join(`
833
- `),Ee=Kt(xe).trim();yield{type:"interactive_turn_finished",data:{agentText:p,fullAgentTextRaw:xe,history:[...r],needTitle:$}},r.length>0&&r[r.length-1].role==="agent"?r[r.length-1].text=Ee:r.push({role:"agent",text:Ee}),r.forEach(re=>{if(re.role==="user"&&re.text&&(re.text=re.text.replace(/\n\[COMPILE ERROR\][\s\S]*?\[\/ERROR\]/g,""),re.text=re.text.replaceAll(`
830
+ ${_t}`}):r.push(yt)}):r.push({role:"user",text:_t}),it+=le}for(let _t=Pt/1e3;_t>0&&!wt;_t--)yield{type:"status",content:`Error Occured. Recovering Stream (${et}/${nn}) [Retrying in ${_t.toFixed(0)}s]...`},await new Promise(yt=>setTimeout(yt,1e3));yield{type:"status",content:"Error Occured. Recovering Stream..."}}else throw new Error(`Stream collapsed too many times. (Failed to resolve ${nn} times)
831
+ Error log can be found in \`/export logs\``);else if(ze<=nn){ze++,et=1,it="";let Pt=Math.min(1e3*Math.pow(2,ze-1),32e3),_t=.8+Math.random()*.4,yt=Math.round(Pt*_t);vn=!0,yield{type:"status",content:`Trying to reach ${e} (${ze}/${nn}) [Retrying in ${(yt/1e3).toFixed(0)}s]`};for(let Rt=yt/1e3;Rt>0&&!wt;Rt--)yield{type:"status",content:`Trying to reach ${e} (${ze}/${nn}) [Retrying in ${Rt.toFixed(0)}s]`},await new Promise(ut=>setTimeout(ut,1e3));yield{type:"status",content:`Trying to reach ${e}`}}else throw new Error(`Model ${e} cannot be reached. (Failed ${nn} times)
832
+ Error log can be found in \`/export logs\``)}}if(un){let be=un.totalTokenCount||0,Ae=un.cachedContentTokenCount||0,ie=(un.candidatesTokenCount||0)+(i==="Google"&&un.thoughtsTokenCount||0);await Ft("tokens",be,i,he),Ae>0&&await Ft("cachedTokens",Ae,i,he),ie>0&&await Ft("candidateTokens",ie,i,he),yield{type:"usage",content:un}}le=Nr(le),ii.push(le);let Mn=Kt(le),Qt=Or(le),Xn=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(Qt.toLowerCase())||/\[\[END\]\]/i.test(Qt.toLowerCase())||!0,wn=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(Qt.toLowerCase()),Ka=Je>0;yield{type:"status",content:"Thinking"};let Gr=Ua(le,/(\[\s*(turn\s*:)?\s*(continue|finish)\s*\]|\[\[END\]\])/gi,"").trim(),In=(Xn||Q.length===0)&&!Dt&&!on&&!gn;if(In=Q.length===0?In:!1,In=Rn||ko?!1:In,le&&le.trim().endsWith('")]')&&Q.length===0&&(In=!1),In){let be=ii.join(`
833
+ `),Ae=Kt(be).trim();yield{type:"interactive_turn_finished",data:{agentText:p,fullAgentTextRaw:be,history:[...r],needTitle:$}},r.length>0&&r[r.length-1].role==="agent"?r[r.length-1].text=Ae:r.push({role:"agent",text:Ae}),r.forEach(ie=>{if(ie.role==="user"&&ie.text&&(ie.text=ie.text.replace(/\n\[COMPILE ERROR\][\s\S]*?\[\/ERROR\]/g,""),ie.text=ie.text.replaceAll(`
834
834
 
835
835
  [system] user question. resolve this specific query within '[ANSWER] ... [/ANSWER]' concisely, naturally [/system]
836
836
  `,"").replaceAll(`[system] user question. resolve this specific query within '[ANSWER] ... [/ANSWER]' concisely, naturally
837
837
  **strictly follow thinking policy as high priority. do not start a response without <think>...</think>** [/system]
838
838
  `,"").replaceAll(`[system] **strictly follow thinking policy as high priority. do not start a response without <think>...</think>** [/system]
839
- `,"").replaceAll(/\n\[system\] WARNING, Turn Limit Impending: Step \d+\/\d+\. Wrap up quickly\/prompt user to continue & use \[\[END\]\] quickly\. \[\/system\]/g,""),re.text=re.text.replaceAll(/\n\[system\] File Changes:\n(?:\* .+ \(created|modified|deleted\)\n)*\[\/system\]/g,""),(i==="Mistral"||i==="Google"&&e?.toLowerCase().startsWith("gemma"))&&re.text.startsWith("[TOOL RESULT]"))){let vt=`
839
+ `,"").replaceAll(/\n\[system\] WARNING, Turn Limit Impending: Step \d+\/\d+\. Wrap up quickly\/prompt user to continue & use \[\[END\]\] quickly\. \[\/system\]/g,""),ie.text=ie.text.replaceAll(/\n\[system\] File Changes:\n(?:\* .+ \(created|modified|deleted\)\n)*\[\/system\]/g,""),(i==="Mistral"||i==="Google"&&e?.toLowerCase().startsWith("gemma"))&&ie.text.startsWith("[TOOL RESULT]"))){let vt=`
840
840
  [system] Tool result received. Analyze output and proceed with your turn [/system]`,St=`
841
- [system] Tool result received. Analyze output and proceed with your turn. **strictly follow thinking policy. do not start a response without <think>...</think>** [/system]`;re.text=re.text.replaceAll(St,"").replaceAll(vt,"").trim()}}),yield{type:"status",content:"[end]"}}if(In)break;let jr=Gr.trim()||"*Working...*";if(r.push({role:"agent",text:jr}),Q.length>0||Xt){if(Q.length>0){let xe=Q.map(Jt=>Jt.text).join(`
841
+ [system] Tool result received. Analyze output and proceed with your turn. **strictly follow thinking policy. do not start a response without <think>...</think>** [/system]`;ie.text=ie.text.replaceAll(St,"").replaceAll(vt,"").trim()}}),yield{type:"status",content:"[end]"}}if(In)break;let jr=Gr.trim()||"*Working...*";if(r.push({role:"agent",text:jr}),Q.length>0||Xt){if(Q.length>0){let be=Q.map(Jt=>Jt.text).join(`
842
842
 
843
- `),Lt=(Kt(le).replace(/\[{1,2}tool:[\s\S]*?\)\s*\]{1,2}/gi,"").match(/\[tool:/gi)||[]).length,vt=Q.length+Lt;if(Q.length<vt){xe+=`
843
+ `),Lt=(Kt(le).replace(/\[{1,2}tool:[\s\S]*?\)\s*\]{1,2}/gi,"").match(/\[tool:/gi)||[]).length,vt=Q.length+Lt;if(Q.length<vt){be+=`
844
844
 
845
- [system] Only ${Q.length} out of ${vt} attempted tool calls were executed. Verify proper structure compliance & try failed calls again [/system]`;let Jt=vt-Q.length;for(let We=0;We<Jt;We++)await At("toolFailure")}let St=Q.find(Jt=>Jt.binaryPart)?.binaryPart||null;r.push({role:"user",text:xe,binaryPart:St})}}else if(!wt){let Ee=(le.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/i,"").match(/\[tool:/gi)||[]).length;wo||Rn||Ee>0?(r.push({role:"user",text:`[system] Failed to execute ${Ee} tool${Ee>1?"s":""}. Verify proper structure compliance & try again [/system]`}),await At("toolFailure"),yield{type:"visual_feedback",content:`
845
+ [system] Only ${Q.length} out of ${vt} attempted tool calls were executed. Verify proper structure compliance & try failed calls again [/system]`;let Jt=vt-Q.length;for(let Ke=0;Ke<Jt;Ke++)await At("toolFailure")}let St=Q.find(Jt=>Jt.binaryPart)?.binaryPart||null;r.push({role:"user",text:be,binaryPart:St})}}else if(!wt){let Ae=(le.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/i,"").match(/\[tool:/gi)||[]).length;ko||Rn||Ae>0?(r.push({role:"user",text:`[system] Failed to execute ${Ae} tool${Ae>1?"s":""}. Verify proper structure compliance & try again [/system]`}),await At("toolFailure"),yield{type:"visual_feedback",content:`
846
846
  ${Vt("\u2718 Execution Error")}
847
847
  `}):(yield{type:"visual_feedback",content:`
848
848
  ${Vt("\u2718 Loop Detected")}
849
- `},r.push({role:"user",text:`[system] ${on&&!Dt?"Stuttering Detected by Internal System. Re-calibrate your response & proceed.":`${Dt?" Over Thinking":" Loop"} Detected by Internal System${Dt?" for current Effort Level":""}. ${Dt?"If you have planned the task, prioritize execution/output":"If you have finished your task provide a simple summary and end"}`} [/system]`})),Dt=!1,on=!1,gn=!1}h?.advanceRollback&&await so.recordTurnDelta(g,K+1,qt),wo=Ve>0||Xt}}catch(w){let k=(w instanceof Error?(()=>{try{return JSON.parse(JSON.parse(w.message).error.message).error.message}catch{return w.message||String(w)}})():String(w)).replace(/^(Error:\s*)+/i,""),E=new Date().toLocaleString(),O=J.join(Sn,"agent");yield{type:"text",content:`
849
+ `},r.push({role:"user",text:`[system] ${on&&!Dt?"Stuttering Detected by Internal System. Re-calibrate your response & proceed.":`${Dt?" Over Thinking":" Loop"} Detected by Internal System${Dt?" for current Effort Level":""}. ${Dt?"If you have planned the task, prioritize execution/output":"If you have finished your task provide a simple summary and end"}`} [/system]`})),Dt=!1,on=!1,gn=!1}h?.advanceRollback&&await oo.recordTurnDelta(g,V+1,qt),ko=Je>0||Xt}}catch(T){let k=(T instanceof Error?(()=>{try{return JSON.parse(JSON.parse(T.message).error.message).error.message}catch{return T.message||String(T)}})():String(T)).replace(/^(Error:\s*)+/i,""),E=new Date().toLocaleString(),O=X.join(Sn,"agent");yield{type:"text",content:`
850
850
 
851
851
  \u2726 CRITICAL ERROR: ${k.includes("fetch failed")?"Failed to Connect. Check your Internet Connection or Wait a moment":k}
852
- \u2800`},$e.existsSync(O)||$e.mkdirSync(O,{recursive:!0}),$e.appendFileSync(J.join(O,"error.log"),`CRITICAL ERROR [${E}]: ${w}
852
+ \u2800`},Ne.existsSync(O)||Ne.mkdirSync(O,{recursive:!0}),Ne.appendFileSync(X.join(O,"error.log"),`CRITICAL ERROR [${E}]: ${T}
853
853
 
854
854
  ----------------------------------------------------------------------
855
855
 
856
- `),typeof flushGoogleBuffer=="function"&&(yield*flushGoogleBuffer()),yield{type:"tool_result",content:`ERROR: [INTERNAL CRITICAL] ${k}`}}finally{d&&(clearInterval(d),d=null),typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),await vo.commitTransaction(),h?.advanceRollback&&await so.cleanup(g),await $n()}yield{type:"status",content:null}},ef=async(e,t,n=null,s=null,o=50,l=null,f=!1)=>{let a=await oo(),m={...a,...t},g=process.env.SUBAGENT_MODEL?process.env.SUBAGENT_MODEL.trim():null,u=process.env.SUBAGENT_PROVIDER?process.env.SUBAGENT_PROVIDER.trim():null,h=new Date,x=`${h.getFullYear()}-${h.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(h.getDate()).padStart(2,"0")}, ${h.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}).replace(":","-")}`,c=(w=>{if(!w)return null;let r=w.toLowerCase();return r==="google"?"Google":r==="deepseek"?"DeepSeek":r==="openrouter"?"OpenRouter":r==="nvidia"?"NVIDIA":r==="mistral"?"Mistral":r==="ollama"?"Ollama":r==="inferx"?"InferX":r==="sensenova"?"SenseNova":r==="poolside"?"Poolside":r==="9router"||r==="9Router"?"9router":r==="aihubmix"||r==="aihub"?"AIHubMix":r==="explabs"||r==="experientiallabs"||r==="experimentallabs"?"ExpLabs":r==="tokenharbor"||r==="token harbor"||r==="token_harbor"||r==="thk"?"TokenHarbor":r==="apinex"||r==="apx"?"APInex":null})(u),T=m?.systemSettings?.CustomSubAgent?m?.systemSettings?.SubAgentModel:null,v=m?.systemSettings?.CustomSubAgent?m?.systemSettings?.SubAgentProvider:null,b=null;if(T==="ENV"?(b=g,g&&c&&(m.aiProvider=c)):T&&T!=="Default"?(b=T,v&&(m.aiProvider=v)):g&&c&&(m.aiProvider=c),m.aiProvider){let w=await gs(m.aiProvider);w&&(m.apiKey=w)}let R=w=>{if(!w||typeof w!="string")return{allowed:!0};let r=[/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 k of r)if(k.test(w))return{allowed:!1,reason:`Blocked potentially destructive or unsafe command pattern: "${k.source}"`};return{allowed:!0}},N=n||b||t?.modelName||t?.activeModel||a.activeModel,M=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",S=`-- TOOL DEFINITIONS (path = relative to CWD, path separator: '/') --
856
+ `),typeof flushGoogleBuffer=="function"&&(yield*flushGoogleBuffer()),yield{type:"tool_result",content:`ERROR: [INTERNAL CRITICAL] ${k}`}}finally{d&&(clearInterval(d),d=null),typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),await vo.commitTransaction(),h?.advanceRollback&&await oo.cleanup(g),await $n()}yield{type:"status",content:null}},nf=async(e,t,n=null,s=null,o=50,l=null,f=!1)=>{let a=await no(),m={...a,...t},g=process.env.SUBAGENT_MODEL?process.env.SUBAGENT_MODEL.trim():null,u=process.env.SUBAGENT_PROVIDER?process.env.SUBAGENT_PROVIDER.trim():null,h=new Date,x=`${h.getFullYear()}-${h.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(h.getDate()).padStart(2,"0")}, ${h.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}).replace(":","-")}`,c=(T=>{if(!T)return null;let r=T.toLowerCase();return r==="google"?"Google":r==="deepseek"?"DeepSeek":r==="openrouter"?"OpenRouter":r==="nvidia"?"NVIDIA":r==="mistral"?"Mistral":r==="ollama"?"Ollama":r==="inferx"?"InferX":r==="sensenova"?"SenseNova":r==="poolside"?"Poolside":r==="9router"||r==="9Router"?"9router":r==="aihubmix"||r==="aihub"?"AIHubMix":r==="explabs"||r==="experientiallabs"||r==="experimentallabs"?"ExpLabs":r==="tokenharbor"||r==="token harbor"||r==="token_harbor"||r==="thk"?"TokenHarbor":r==="apinex"||r==="apx"?"APInex":null})(u),w=m?.systemSettings?.CustomSubAgent?m?.systemSettings?.SubAgentModel:null,A=m?.systemSettings?.CustomSubAgent?m?.systemSettings?.SubAgentProvider:null,b=null;if(w==="ENV"?(b=g,g&&c&&(m.aiProvider=c)):w&&w!=="Default"?(b=w,A&&(m.aiProvider=A)):g&&c&&(m.aiProvider=c),m.aiProvider){let T=await gs(m.aiProvider);T&&(m.apiKey=T)}let C=T=>{if(!T||typeof T!="string")return{allowed:!0};let r=[/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 k of r)if(k.test(T))return{allowed:!1,reason:`Blocked potentially destructive or unsafe command pattern: "${k.source}"`};return{allowed:!0}},N=n||b||t?.modelName||t?.activeModel||a.activeModel,R=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",_=`-- TOOL DEFINITIONS (path = relative to CWD, path separator: '/') --
857
857
  You cant execute tools. Instead, output in chat the exact string [tool:functions.ToolName(arg1="value1")] & wait for system response \u2190 no exception, tool:functions must
858
858
  Tool Rules:
859
859
  - Mandatorily JSON escape literal sequences (backslash: \\\\, newLine: \\ n, quote: \\")
@@ -879,7 +879,7 @@ ${f?"- AskMain(question=string). Communicate with PARENT/MAIN AGENT. When clarif
879
879
  - ReadFile(path=string, startLine?=int, endLine?=int)
880
880
  - PatchFile(path=string, allowMultiple?=bool, searchContent1="string match OR ^LINE:start..end$", newContent1=string, ...MAX15). Small searchString. Line Anchors: ^LINE:...$ syntax, must for large blocks/escape sequences
881
881
  - WriteFile(path=string, content=string). Creates/Overwrites. File Exist? PatchFile > WriteFile
882
- - Run(command=string). Runs ${M==="Windows"?ui()?"powershell":"windows CMD":"bash"} command. Destructive command \u2192 Ask user`.trim(),I=`=== START SYSTEM PROMPT ===
882
+ - Run(command=string). Runs ${R==="Windows"?ui()?"powershell":"windows CMD":"bash"} command. Destructive command \u2192 Ask user`.trim(),M=`=== START SYSTEM PROMPT ===
883
883
  Identity: FluxFlow subagent helping the main Agent
884
884
  Your task is: "${e}"
885
885
 
@@ -890,33 +890,33 @@ On completion, provide a detailed summary in Tables/Markdown Format with file mo
890
890
 
891
891
  CWD: ${process.cwd()}
892
892
 
893
- ${S.trimEnd()}
893
+ ${_.trimEnd()}
894
894
 
895
895
  Current Time: ${x}
896
- === END SYSTEM PROMPT ===`,$=[{role:"user",text:`Complete this task: ${e}`}],p=0,d="";for(;p<o;){if(wt){if(t?.taskId&&typeof jt<"u"){let B=jt.find(A=>A.id===t.taskId);B&&(B.status="cancelled")}throw l&&l("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}if(t?.taskId&&typeof jt<"u"){let B=jt.find(A=>A.id===t.taskId);if(B&&B.status==="cancelled")throw l&&l("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}let w=$.map(B=>({role:B.role==="user"?"user":"model",parts:[{text:B.text}]}));l&&l(`[Subagent Turn ${p+1}]...`);let k=(await ns(m,N,w,I,"Fast")).text||"",E=Nr(Kt(k).trim());d=E,l&&l(`[Subagent Response]
897
- ${E}
898
- `),$.push({role:"agent",text:E});let O=yo(E);if(O.length===0)break;let U=O.filter(B=>B.toolName.toLowerCase()==="askmain"||B.toolName.toLowerCase()==="ask_main"),P=!1,D="";for(let B of O){if(wt){if(t?.taskId&&typeof jt<"u"){let C=jt.find(G=>G.id===t.taskId);C&&(C.status="cancelled")}throw new Error("Subagent task was cancelled.")}if(t?.taskId&&typeof jt<"u"){let C=jt.find(G=>G.id===t.taskId);if(C&&C.status==="cancelled")throw new Error("Subagent task was cancelled.")}let A=B.toolName.toLowerCase();if(A==="askuser"&&(A="ask"),A==="askmain"||A==="ask_main"){if(P)continue;P=!0;let C="";if(U.length===1?C=Z(U[0].args).question||U[0].args:C=U.map((G,te)=>{let Y=Z(G.args);return`Q${te+1}: ${Y.question||G.args}`}).join(`
899
- `),t.onAskMain){l&&l(`[Executing Tool] AskMain("${C}")...`);let G=await t.onAskMain(C);l&&l(`[Tool Result]
900
- Answer from Main Agent: ${G}
901
- `),D+=`[TOOL RESULT for AskMain]: Answer from Main Agent: ${G}
896
+ === END SYSTEM PROMPT ===`,$=[{role:"user",text:`Complete this task: ${e}`}],p=0,d="";for(;p<o;){if(wt){if(t?.taskId&&typeof jt<"u"){let B=jt.find(I=>I.id===t.taskId);B&&(B.status="cancelled")}throw l&&l("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}if(t?.taskId&&typeof jt<"u"){let B=jt.find(I=>I.id===t.taskId);if(B&&B.status==="cancelled")throw l&&l("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}let T=$.map(B=>({role:B.role==="user"?"user":"model",parts:[{text:B.text}]}));l&&l(`[Subagent Turn ${p+1}]...`);let r=["Fast","Low","Medium","High"],k=process.env.SUBAGENT_THINKING,E=r.includes(k)?k:"Low",H=(await ns(m,N,T,M,E)).text||"",P=Nr(Kt(H).trim());d=P,l&&l(`[Subagent Response]
897
+ ${P}
898
+ `),$.push({role:"agent",text:P});let D=po(P);if(D.length===0)break;let J=D.filter(B=>B.toolName.toLowerCase()==="askmain"||B.toolName.toLowerCase()==="ask_main"),fe=!1,q="";for(let B of D){if(wt){if(t?.taskId&&typeof jt<"u"){let v=jt.find(K=>K.id===t.taskId);v&&(v.status="cancelled")}throw new Error("Subagent task was cancelled.")}if(t?.taskId&&typeof jt<"u"){let v=jt.find(K=>K.id===t.taskId);if(v&&v.status==="cancelled")throw new Error("Subagent task was cancelled.")}let I=B.toolName.toLowerCase();if(I==="askuser"&&(I="ask"),I==="askmain"||I==="ask_main"){if(fe)continue;fe=!0;let v="";if(J.length===1?v=Z(J[0].args).question||J[0].args:v=J.map((K,We)=>{let ue=Z(K.args);return`Q${We+1}: ${ue.question||K.args}`}).join(`
899
+ `),t.onAskMain){l&&l(`[Executing Tool] AskMain("${v}")...`);let K=await t.onAskMain(v);l&&l(`[Tool Result]
900
+ Answer from Main Agent: ${K}
901
+ `),q+=`[TOOL RESULT for AskMain]: Answer from Main Agent: ${K}
902
902
 
903
- `,await At("toolSuccess")}else D+=`[TOOL RESULT for AskMain]: ERROR: Main agent communication channel not available.
903
+ `,await At("toolSuccess")}else q+=`[TOOL RESULT for AskMain]: ERROR: Main agent communication channel not available.
904
904
 
905
- `;continue}if(!(s?s.some(C=>C.toLowerCase()===A):!0)){let C=`ERROR: Tool [${B.toolName}] is not in the allowed tools list for this subagent.`;l&&l(`[Blocked Tool Call] ${B.toolName} - not allowed
906
- `),D+=`${C}
905
+ `;continue}if(!(s?s.some(v=>v.toLowerCase()===I):!0)){let v=`ERROR: Tool [${B.toolName}] is not in the allowed tools list for this subagent.`;l&&l(`[Blocked Tool Call] ${B.toolName} - not allowed
906
+ `),q+=`${v}
907
907
 
908
- `;continue}if(A==="exec_command"||A==="execcommand"||A==="run"){let C=Z(B.args).command||"",G=R(C);if(!G.allowed){let te=`ERROR: [SECURITY RESTRICTION] Subagent execution blocked command: ${G.reason}`;l&&l(`[Blocked Command] ${C} - ${G.reason}
909
- `),D+=`${te}
908
+ `;continue}if(I==="exec_command"||I==="execcommand"||I==="run"){let v=Z(B.args).command||"",K=C(v);if(!K.allowed){let We=`ERROR: [SECURITY RESTRICTION] Subagent execution blocked command: ${K.reason}`;l&&l(`[Blocked Command] ${v} - ${K.reason}
909
+ `),q+=`${We}
910
910
 
911
- `;continue}}let X="";if(A==="web_search"||A==="websearch")X=`\u2714 \x1B[95mSearched\x1B[0m: ${Z(B.args).query||""}`;else if(A==="web_scrape"||A==="webscrape")X=`\u2714 \x1B[95mScraped\x1B[0m: ${Z(B.args).url||""}`;else if(A==="search_keyword"||A==="searchkeyword"||A==="codesearch"||A==="code_search"){let C=Z(B.args),G=C.keyword||"",te=C.path||"";X=`${G?"\u2714":"\u2718"} \x1B[95mSearched\x1B[0m: ${G||"No Query"}${te?` \u2192 ${te.replaceAll("\\","/")}`:""}`}else if(A==="view_file"||A==="viewfile"||A==="readfile")X=`\u2714 \x1B[95mRead\x1B[0m: ${(Z(B.args).path||"").replaceAll("\\","/")}`;else if(A==="list_files"||A==="read_folder"||A==="readfolder"){let C=Z(B.args).path||null,G=Z(B.args).recurse||0;X=`${C?"\u2714":"\u2718"} \x1B[95mBrowsed\x1B[0m: ${C?`${C.replaceAll("\\","/")}${G>0?`${C.endsWith("/")?`*${G}`:`/*${G}`}`:`${C.endsWith("/")?"":"/"}`}`:""}`}else if(A==="write_file"||A==="writefile"){let C=Z(B.args).path||null;X=`${C?"\u2714":"\u2718"} \x1B[95mCreated\x1B[0m: ${C?`${C.replaceAll("\\","/")}`:"No File Changes"}`}else if(A==="update_file"||A==="updatefile"||A==="patchfile"||A==="patch_file"||A==="patchfile"||A==="updatefile"){let C=Z(B.args).path||null,G=Z(B.args).content||null;X=`${C?"\u2714":"\u2718"} \x1B[95mEdited\x1B[0m: ${C?`${C.replaceAll("\\","/")}`:"No File Changes"}`}else if(A==="exec_command"||A==="execcommand"||A==="run"){let C=Z(B.args).command||null;X=`${C?"\u2714":"\u2718"} \x1B[95mExecuted\x1B[0m: ${C?C.slice(0,100)+(C.length>100?"...":""):"No Command"}`}else if(A==="file_map"||A==="filemap"){let C=Z(B.args).path||"";X=`${C?"\u2714":"\u2718"} \x1B[95mIndexed\x1B[0m: ${C?`${C.replaceAll("\\","/")}`:"File Not Found"}`}else if(A==="await"){let{time:C}=Z(B.args),G=parseFloat(C)||0;G<10&&(G=10),G>180&&(G=180),X=`\u2714 \x1B[95mAwaiting\x1B[0m \u2192 ${(Y=>{if(Y>=60){let Xe=Math.floor(Y/60),Ye=Y%60;return`${Xe}m${Ye>0?` ${Ye}s`:""}`}return`${Y}s`})(G)}`}else{let C=Ks[A]||B.toolName,G=Bn(A,B.args);X=`\u2714 \x1B[95m${C}\x1B[0m${G?`: ${G}`:""}`}t.onVisualFeedback&&X&&t.onVisualFeedback(X),l&&l(`[Executing Tool] ${B.toolName}(${B.args})...`);try{let C=await mo(B.toolName,B.args,{...t,mode:"Flux"});if(l&&l(`[Tool Result]
912
- ${C}
913
- `),D+=`[TOOL RESULT for ${B.toolName}]: ${C}
911
+ `;continue}}let te="";if(I==="web_search"||I==="websearch")te=`\u2714 \x1B[95mSearched\x1B[0m: ${Z(B.args).query||""}`;else if(I==="web_scrape"||I==="webscrape")te=`\u2714 \x1B[95mScraped\x1B[0m: ${Z(B.args).url||""}`;else if(I==="search_keyword"||I==="searchkeyword"||I==="codesearch"||I==="code_search"){let v=Z(B.args),K=v.keyword||"",We=v.path||"";te=`${K?"\u2714":"\u2718"} \x1B[95mSearched\x1B[0m: ${K||"No Query"}${We?` \u2192 ${We.replaceAll("\\","/")}`:""}`}else if(I==="view_file"||I==="viewfile"||I==="readfile")te=`\u2714 \x1B[95mRead\x1B[0m: ${(Z(B.args).path||"").replaceAll("\\","/")}`;else if(I==="list_files"||I==="read_folder"||I==="readfolder"){let v=Z(B.args).path||null,K=Z(B.args).recurse||0;te=`${v?"\u2714":"\u2718"} \x1B[95mBrowsed\x1B[0m: ${v?`${v.replaceAll("\\","/")}${K>0?`${v.endsWith("/")?`*${K}`:`/*${K}`}`:`${v.endsWith("/")?"":"/"}`}`:""}`}else if(I==="write_file"||I==="writefile"){let v=Z(B.args).path||null;te=`${v?"\u2714":"\u2718"} \x1B[95mCreated\x1B[0m: ${v?`${v.replaceAll("\\","/")}`:"No File Changes"}`}else if(I==="update_file"||I==="updatefile"||I==="patchfile"||I==="patch_file"||I==="patchfile"||I==="updatefile"){let v=Z(B.args).path||null,K=Z(B.args).content||null;te=`${v?"\u2714":"\u2718"} \x1B[95mEdited\x1B[0m: ${v?`${v.replaceAll("\\","/")}`:"No File Changes"}`}else if(I==="exec_command"||I==="execcommand"||I==="run"){let v=Z(B.args).command||null;te=`${v?"\u2714":"\u2718"} \x1B[95mExecuted\x1B[0m: ${v?v.slice(0,100)+(v.length>100?"...":""):"No Command"}`}else if(I==="file_map"||I==="filemap"){let v=Z(B.args).path||"";te=`${v?"\u2714":"\u2718"} \x1B[95mIndexed\x1B[0m: ${v?`${v.replaceAll("\\","/")}`:"File Not Found"}`}else if(I==="await"){let{time:v}=Z(B.args),K=parseFloat(v)||0;K<10&&(K=10),K>180&&(K=180),te=`\u2714 \x1B[95mAwaiting\x1B[0m \u2192 ${(ue=>{if(ue>=60){let Be=Math.floor(ue/60),Ee=ue%60;return`${Be}m${Ee>0?` ${Ee}s`:""}`}return`${ue}s`})(K)}`}else{let v=Ks[I]||B.toolName,K=Bn(I,B.args);te=`\u2714 \x1B[95m${v}\x1B[0m${K?`: ${K}`:""}`}t.onVisualFeedback&&te&&t.onVisualFeedback(te),l&&l(`[Executing Tool] ${B.toolName}(${B.args})...`);try{let v=await go(B.toolName,B.args,{...t,mode:"Flux"});if(l&&l(`[Tool Result]
912
+ ${v}
913
+ `),q+=`[TOOL RESULT for ${B.toolName}]: ${v}
914
914
 
915
- `,await At("toolSuccess"),A==="patchfile"||A==="update_file"||A==="updatefile"||A==="patch_file"){if(C){let G=C.split(`
916
- `),te=0,Y=0,Xe=!1;for(let Ye of G){if(Ye.includes("[DIFF_START]")){Xe=!0;continue}if(Ye.includes("[DIFF_END]")){Xe=!1;continue}Xe&&(/^\+\d+/.test(Ye)?te++:/^\-\d+/.test(Ye)&&Y++)}(te>0||Y>0)&&(await Ft("linesAdded",te),await Ft("linesRemoved",Y))}}else if((A==="writefile"||A==="write_file")&&C){let G=C.match(/- Stats: \[(\d+) lines/),te=G?parseInt(G[1]):0,Y=0;if(C.includes("Old File contents:")){let Xe=!1;for(let Ye of C.split(`
917
- `)){if(Ye.includes("Old File contents:")){Xe=!0;continue}Xe&&(Ye.trim()===""?Xe=!1:/^\d+ \|/.test(Ye)&&Y++)}}(te>0||Y>0)&&(await Ft("linesAdded",te),await Ft("linesRemoved",Y))}}catch(C){let G=`ERROR: Execution failed for [${B.toolName}]: ${C.message}`;l&&l(`[Tool Error] ${G}
918
- `),D+=`${G}
915
+ `,await At("toolSuccess"),I==="patchfile"||I==="update_file"||I==="updatefile"||I==="patch_file"){if(v){let K=v.split(`
916
+ `),We=0,ue=0,Be=!1;for(let Ee of K){if(Ee.includes("[DIFF_START]")){Be=!0;continue}if(Ee.includes("[DIFF_END]")){Be=!1;continue}Be&&(/^\+\d+/.test(Ee)?We++:/^\-\d+/.test(Ee)&&ue++)}(We>0||ue>0)&&(await Ft("linesAdded",We),await Ft("linesRemoved",ue))}}else if((I==="writefile"||I==="write_file")&&v){let K=v.match(/- Stats: \[(\d+) lines/),We=K?parseInt(K[1]):0,ue=0;if(v.includes("Old File contents:")){let Be=!1;for(let Ee of v.split(`
917
+ `)){if(Ee.includes("Old File contents:")){Be=!0;continue}Be&&(Ee.trim()===""?Be=!1:/^\d+ \|/.test(Ee)&&ue++)}}(We>0||ue>0)&&(await Ft("linesAdded",We),await Ft("linesRemoved",ue))}}catch(v){let K=`ERROR: Execution failed for [${B.toolName}]: ${v.message}`;l&&l(`[Tool Error] ${K}
918
+ `),q+=`${K}
919
919
 
920
- `,await At("toolFailure")}}let ee="";if(t?.taskId&&typeof jt<"u"){let B=jt.find(A=>A.id===t.taskId);if(B&&B.pendingSteerMessages&&B.pendingSteerMessages.length>0){let A=[...B.pendingSteerMessages];B.pendingSteerMessages=[];for(let Se of A)ee+=`
920
+ `,await At("toolFailure")}}let xe="";if(t?.taskId&&typeof jt<"u"){let B=jt.find(I=>I.id===t.taskId);if(B&&B.pendingSteerMessages&&B.pendingSteerMessages.length>0){let I=[...B.pendingSteerMessages];B.pendingSteerMessages=[];for(let Fe of I)xe+=`
921
921
 
922
- [STEERING INSTRUCTION FROM MAIN AGENT]: ${Se}`,l&&l(`[Subagent Steered] ${Se}`)}}let pe=(D.trim()+ee).trim();$.push({role:"user",text:pe}),p++}return d};export{ho as a,wr as b,nc as c,oc as d,Oe as e,Qa as f,Za as g,Kl as h,Yl as i,rc as j,Go as k,ac as l,Ia as m,Kd as n,Da as o,Oa as p,Vs as q,Kt as r,Dr as s,Nr as t,Na as u,Yd as v,qd as w,qs as x,zd as y,Jd as z,Xd as A,Qd as B,Zd as C,ef as D};
922
+ [STEERING INSTRUCTION FROM MAIN AGENT]: ${Fe}`,l&&l(`[Subagent Steered] ${Fe}`)}}let ve=(q.trim()+xe).trim();$.push({role:"user",text:ve}),p++}return d};export{mo as a,wr as b,oc as c,sc as d,Ue as e,Qa as f,Za as g,Yl as h,ql as i,ac as j,Go as k,lc as l,Ia as m,qd as n,Da as o,Oa as p,Vs as q,Kt as r,Dr as s,Nr as t,Na as u,zd as v,Jd as w,qs as x,Xd as y,Qd as z,Zd as A,ef as B,tf as C,nf as D};