fluxflow-cli 4.24.0 → 4.24.1

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 Vt}from"./chunk-56EJGQU3.js";import{a as lo}from"./chunk-7SFAWGE2.js";import{a as Ei,c as Ci}from"./chunk-PQRLA35M.js";import{a as Cs,g as Ri}from"./chunk-VYTQ6J56.js";import{a as vi}from"./chunk-RZTZPIC5.js";import{c as As,g as Si,h as _i,i as Ai,m as Es}from"./chunk-ZRP6USHC.js";import{a as Oo}from"./chunk-FQBBOFNP.js";import{a as ne}from"./chunk-Y5JU726N.js";import{b as Ss}from"./chunk-3CZWTXIR.js";import{d as Do,i as Rt,k as Bt,m as _s,n as Ti}from"./chunk-4XXLWMY6.js";import{a as ao}from"./chunk-GRQ7JZZP.js";import{k as ft,l as Io,o as pe}from"./chunk-OSDQRSY6.js";import{c as Ct,d as Xn}from"./chunk-L3W2X74K.js";import{a as en,d as Cn,e as Ro,k as Wn,l as vo,m as ks,r as Ts,v as Mo,w as io,x as ro}from"./chunk-DSVLWYIT.js";import{GoogleGenAI as Vr,ThinkingLevel as Xe,HarmBlockThreshold as Mn,HarmCategory as In}from"@google/genai";var Mi=(e=!0,t=!0)=>`
1
+ import{a as Vt}from"./chunk-56EJGQU3.js";import{a as lo}from"./chunk-7SFAWGE2.js";import{a as Ai,c as Ei}from"./chunk-LQHSNXBM.js";import{a as Cs,g as Ci}from"./chunk-VYTQ6J56.js";import{a as Ri}from"./chunk-RZTZPIC5.js";import{c as As,g as Ti,h as Si,i as _i,m as Es}from"./chunk-ZRP6USHC.js";import{a as Oo}from"./chunk-FQBBOFNP.js";import{a as ne}from"./chunk-Y5JU726N.js";import{b as Ss}from"./chunk-3CZWTXIR.js";import{d as Do,i as Rt,k as Bt,m as _s,n as ki}from"./chunk-4XXLWMY6.js";import{a as ao}from"./chunk-GRQ7JZZP.js";import{k as ft,l as Io,o as pe}from"./chunk-OSDQRSY6.js";import{c as Ct,d as Xn}from"./chunk-L3W2X74K.js";import{a as en,d as Cn,e as Ro,k as Wn,l as vo,m as ks,r as Ts,v as Mo,w as io,x as ro}from"./chunk-DSVLWYIT.js";import{GoogleGenAI as Kr,ThinkingLevel as Xe,HarmBlockThreshold as Mn,HarmCategory as In}from"@google/genai";var vi=(e=!0,t=!0)=>`
2
2
  To use tools, must output exactly '[action:ActionName(arg1="value1")]' structured string in chat response \u2190 no exception
3
3
 
4
4
  -- Chat Management Tools --
@@ -27,12 +27,11 @@ Usage Rules:
27
27
  - When called user memory, still use Temporary Memory
28
28
  - Must not ignore any tool calls in given context of chat between user & agent`:""}`.trim();var Lo={xHigh:`Effort: High
29
29
  Think before complex tasks
30
- Prefer simplest correct solution, assess architecture, performance & maintainability, verify error handling, assumptions, edge cases, dependencies & regressions, plan: files, functions, logic & interactions
31
- Verify from first principles, seek failure paths, verify imports, system stability
32
- Direct deduction only. No exploratory branching. Output solution immediately`,High:`Effort: High
30
+ Prefer simplest correct solution, verify from first principles
31
+ Direct deduction only. No exploratory branching`,High:`Effort: High
33
32
  Think before complex tasks
34
- Prefer simplest correct solution, assess architecture, performance & maintainability, verify error handling, assumptions, edge cases, dependencies & regressions, plan: files, functions, logic & interactions
35
- Continuous analysis, verify from first principles, seek failure paths, verify imports, system stability
33
+ Prefer simplest correct solution,
34
+ Continuous analysis
36
35
  Dont waste tokens, be efficient, use less thinking tokens, focus on result
37
36
  Gather useful context`,Medium:`Effort: Medium
38
37
  Think before complex tasks
@@ -45,7 +44,7 @@ Dont waste tokens, be efficient, use least thinking tokens, focus on result
45
44
  Gather useful context
46
45
  Brief thoughts, think only enough to avoid mistakes, verify imports, system stability`,Off:`Effort: Lowest
47
46
  No thinking. Immediate response
48
- Verify imports, tool results & system stability`};import co from"fs";var yn=null,Rs=()=>{try{if(co.existsSync(Mo)){let e=co.readFileSync(Mo,"utf-8"),t=JSON.parse(e);if(t&&typeof t=="object")return yn=t,yn}}catch{}return yn=yn||{},yn},Ii=e=>{try{return co.existsSync(en)||co.mkdirSync(en,{recursive:!0}),co.writeFileSync(Mo,JSON.stringify(e,null,2),"utf-8"),yn=e,!0}catch{return!1}},He=(e,t,n)=>{if(!e||!t||!n)return null;let s=yn||Rs(),o=`${e}::${t}`,c=s[o];if(c&&typeof c=="object"){let f=n.toLowerCase();if(c[f]!==void 0&&c[f]!==null)return c[f];for(let[l,k]of Object.entries(c))if(l.toLowerCase()===f)return k}return null},ul=(e,t,n,s)=>{if(!e||!t||!n||!s)return{success:!1,reason:"Invalid arguments"};let o=yn||Rs(),c=`${e}::${t}`;return(!o[c]||typeof o[c]!="object")&&(o[c]={}),o[c][n.toLowerCase()]=s,{success:Ii(o)}},gl=(e,t,n)=>{if(!e||!t)return{success:!1,reason:"Invalid arguments"};let s=yn||Rs(),o=`${e}::${t}`;return s[o]&&(n?(delete s[o][n.toLowerCase()],Object.keys(s[o]).length===0&&delete s[o]):delete s[o],Ii(s)),{success:!0}};import tn from"fs";import cn from"path";import ma from"os";import ln from"fs";import Rn from"path";import ji from"fs";import vs from"path";import{execSync as Ki}from"child_process";import{fileURLToPath as ha}from"url";var Di=`# FluxFlow CLI Startup & Flags Reference
47
+ Verify imports, tool results & system stability`};import co from"fs";var yn=null,Rs=()=>{try{if(co.existsSync(Mo)){let e=co.readFileSync(Mo,"utf-8"),t=JSON.parse(e);if(t&&typeof t=="object")return yn=t,yn}}catch{}return yn=yn||{},yn},Mi=e=>{try{return co.existsSync(en)||co.mkdirSync(en,{recursive:!0}),co.writeFileSync(Mo,JSON.stringify(e,null,2),"utf-8"),yn=e,!0}catch{return!1}},He=(e,t,n)=>{if(!e||!t||!n)return null;let s=yn||Rs(),o=`${e}::${t}`,c=s[o];if(c&&typeof c=="object"){let f=n.toLowerCase();if(c[f]!==void 0&&c[f]!==null)return c[f];for(let[l,k]of Object.entries(c))if(l.toLowerCase()===f)return k}return null},ul=(e,t,n,s)=>{if(!e||!t||!n||!s)return{success:!1,reason:"Invalid arguments"};let o=yn||Rs(),c=`${e}::${t}`;return(!o[c]||typeof o[c]!="object")&&(o[c]={}),o[c][n.toLowerCase()]=s,{success:Mi(o)}},gl=(e,t,n)=>{if(!e||!t)return{success:!1,reason:"Invalid arguments"};let s=yn||Rs(),o=`${e}::${t}`;return s[o]&&(n?(delete s[o][n.toLowerCase()],Object.keys(s[o]).length===0&&delete s[o]):delete s[o],Mi(s)),{success:!0}};import tn from"fs";import cn from"path";import ma from"os";import ln from"fs";import Rn from"path";import Gi from"fs";import vs from"path";import{execSync as ji}from"child_process";import{fileURLToPath as ha}from"url";var Ii=`# FluxFlow CLI Startup & Flags Reference
49
48
 
50
49
  Launch command syntax:
51
50
  fluxflow [options]
@@ -74,7 +73,7 @@ fluxflow [options]
74
73
  * --help commands \u2192 In-chat slash commands list
75
74
  * --playground \u2192 Launch Playground mode
76
75
  * --prompt, -p \u2192 Non interactive CLI chat, no tools. --new for new headless chat. Holds conversation context upto 10m inactivity or 69 turns. Supports piping from shell, --run if want the command to visible in context. eg \`fluxflow --run "git diff" -p "summarize this" --new\`
77
- `;var Oi=`# Env Variables
76
+ `;var Di=`# Env Variables
78
77
 
79
78
  * Locations:
80
79
  * Shell
@@ -103,7 +102,7 @@ fluxflow [options]
103
102
 
104
103
  * I_HAVE_TOO_MUCH_MONEY \u2192 (true|false, default: false) Fun Flag; inserts random padding in system prompt to break provider caching. Not intended for paid APIs unless user hate money
105
104
  * GOOGLE_GEMMA_NONSENSE \u2192 (true|false, default: false) for the 16k TPM nonsense of gemma models on gemini API. False defaults to 256k
106
- `;var Li=`# Fluxflow in-app /commands
105
+ `;var Oi=`# Fluxflow in-app /commands
107
106
 
108
107
  Trigger in chat via /command
109
108
 
@@ -147,7 +146,7 @@ Trigger in chat via /command
147
146
  * /changelog \u2192 Release notes
148
147
  * /update check \u2192 Check npm updates
149
148
  * /update latest \u2192 Install latest release
150
- `;var Pi=`# FluxFlow In-App Settings Reference
149
+ `;var Li=`# FluxFlow In-App Settings Reference
151
150
 
152
151
  Open in chat via /settings
153
152
 
@@ -209,7 +208,7 @@ Open in chat via /settings
209
208
  - Best for Luxurious Experience: Subagents (on), dynamic directory awareness (on), compact large results (off), auto exclue metadata (off), Image History (Extended), Keep reasoning content (on), Emergency Recovery (on), Auto truncate results (off), Memory (on), Security Preset (Autonomous), FluxFlow IDE Companion
210
209
 
211
210
  - Max Cache Hit: Subagents (off), dynamic directory awareness (off), compact large results (on), auto exclue metadata (on), Image History (Low), Keep reasoning content (off), Emergency Recovery (off), Auto truncate results (off), Memory (off), No FluxFlow IDE Companion
212
- `;var $i=`# FluxFlow Tool Reference
211
+ `;var Pi=`# FluxFlow Tool Reference
213
212
 
214
213
  ## Protocol: [tool:ToolName(arg1="val")]
215
214
 
@@ -249,7 +248,7 @@ Open in chat via /settings
249
248
  * KeyboardTyping(text, autoPressEnter?) \u2192 Type string
250
249
  * KeyPress(key) \u2192 Key/combo dispatch ("ctrl;c", "enter", etc.)
251
250
  * RecaptureScreen() \u2192 Fresh screenshot + coordinate grid
252
- `;var Ni=`# Fluxflow Architecture
251
+ `;var $i=`# Fluxflow Architecture
253
252
 
254
253
  ## 1. Terminal Engine
255
254
  * Framework: React + Ink terminal UI
@@ -279,7 +278,7 @@ Open in chat via /settings
279
278
  ## 6. IDE Bridge
280
279
  * Protocol: WebSocket on ws://localhost:56832
281
280
  * State Sync: Focused file, open tabs, cursor line, selection, diagnostics
282
- `;var Fi=`# FluxFlow Sub-Agents & Multi-Agent Architecture
281
+ `;var Ni=`# FluxFlow Sub-Agents & Multi-Agent Architecture
283
282
 
284
283
  ## Execution Modes
285
284
  * InvokeSync \u2192 Synchronous blocking delegation; main agent halts until sub-agent finishes task
@@ -310,7 +309,7 @@ Route sub-agent workloads to faster/cheaper models independently of the main age
310
309
  * SUBAGENT_MODEL \u2192 Target model override
311
310
  * SUBAGENT_PROVIDER \u2192 Target provider override
312
311
  * Setting SubAgentModel=ENV in settings pulls directly from environment overrides
313
- `;var Bi=`# FluxFlow Security, Sandboxing & Safety
312
+ `;var Fi=`# FluxFlow Security, Sandboxing & Safety
314
313
 
315
314
  ## Human-in-the-Loop Governance
316
315
  * Execution Approval Gate \u2192 Destructive commands and high-risk file modifications require explicit user authorization (Allow / Deny)
@@ -333,7 +332,7 @@ Route sub-agent workloads to faster/cheaper models independently of the main age
333
332
  * Emergency Rollback \u2192 Automatic pre-turn file snapshots; Agent can still fix it (default: OFF) \u2192 references/SETTINGS.md
334
333
  * Git-less Checkpoint Reversion \u2192 Trigger conversational changes rollback via double-ESC
335
334
  * External Sanctuary Redirection \u2192 Move ~/.fluxflow data sanctuary (chats, keys etc)
336
- `;var Ui=`# Fluxflow IDE Companion
335
+ `;var Bi=`# Fluxflow IDE Companion
337
336
 
338
337
  ## WebSocket Bridge Protocol
339
338
  * Local Bridge \u2192 Runs on ws://localhost:56832 connecting FluxFlow CLI with the companion editor extension
@@ -351,7 +350,7 @@ Route sub-agent workloads to faster/cheaper models independently of the main age
351
350
  * File Focus \u2192 Automatically opens edited files in active IDE window
352
351
  * Diff Preview \u2192 Streams side-by-side or inline diff highlights (showDiff, highlightDiff) directly in editor
353
352
  * Status Bar Sync \u2192 Real-time agent status (thinking, running tool, awaiting input) reflected in IDE status bar
354
- `;var Wi=`# Fluxflow Modes
353
+ `;var Ui=`# Fluxflow Modes
355
354
 
356
355
  ## Modes Overview (TAB to cycle)
357
356
  * [Flux] (Workspace / Dev) \u2192 Primary coding & workspace agent
@@ -369,7 +368,7 @@ Route sub-agent workloads to faster/cheaper models independently of the main age
369
368
  * User Inquiry: AskUser \u2192 [Universal]
370
369
  * Document Creation: WritePDF, WriteDoc \u2192 [Flow]
371
370
  * GUI & Desktop Automation: Click, Drag, Scroll, KeyboardTyping, KeyPress, RecaptureScreen \u2192 [ICU] | [FluxCU]
372
- `;var Hi=`# FluxFlow AI Providers & Setup
371
+ `;var Wi=`# FluxFlow AI Providers & Setup
373
372
 
374
373
  ## Supported Providers
375
374
  * Gemini (aistudio.google.com) | NVIDIA NIM (build.nvidia.com) | DeepSeek (platform.deepseek.com) | Mistral (admin.mistral.ai) | Ollama Local/Cloud (ollama.com) | InferX (inferx.net) | SenseNova (platform.sensenova.ai) | Poolside (platform.poolside.ai) | OpenRouter (openrouter.ai) | AIHubMix (aihubmix.com) | Experiential Labs (experientiallabs.ai) | TokenHarbor (tokenharbor.ai) | APInex (apinex.bond)
@@ -400,7 +399,7 @@ Route sub-agent workloads to faster/cheaper models independently of the main age
400
399
  2. Set ENV ENABLE_9ROUTER=true
401
400
  * NINEROUTER_URL = https://.../v1/chat/completions Support external openai compatible endpoints too
402
401
  * NINEROUTER_KEY = If any needed
403
- `;var Gi=`# Fluxflow Instructions & Skills System
402
+ `;var Hi=`# Fluxflow Instructions & Skills System
404
403
 
405
404
  ## 1. Instructions (AGENTS.md / FLUXFLOW.md root only)
406
405
  * Locations:
@@ -444,7 +443,7 @@ Instruction for this model ID across all providers.
444
443
 
445
444
  * On-Demand Reference System:
446
445
  * Reference: Offload deep/contexual specs to **/{SKILL.md,skill-reference-folder/*.md} & reference in SKILL.md. Saves tokens
447
- `;var Po="v4";try{let e=vs.dirname(ha(import.meta.url)),t=[vs.join(e,"../../package.json"),vs.join(e,"../package.json")],n=!1;for(let s of t)if(ji.existsSync(s)){let o=JSON.parse(ji.readFileSync(s,"utf8"));if(o.version){Po=o.version,n=!0;break}}if(!n)try{let s=Ki("fluxflow -v",{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"],timeout:2e3}).trim();s&&(s.startsWith("v")||/^\d+\.\d+/.test(s))&&(Po=s,n=!0)}catch{}if(!n)try{let s=Ki("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&&(Po=o.version)}catch{}}catch{}var Ms={"SKILL.md":`---
446
+ `;var Po="v4";try{let e=vs.dirname(ha(import.meta.url)),t=[vs.join(e,"../../package.json"),vs.join(e,"../package.json")],n=!1;for(let s of t)if(Gi.existsSync(s)){let o=JSON.parse(Gi.readFileSync(s,"utf8"));if(o.version){Po=o.version,n=!0;break}}if(!n)try{let s=ji("fluxflow -v",{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"],timeout:2e3}).trim();s&&(s.startsWith("v")||/^\d+\.\d+/.test(s))&&(Po=s,n=!0)}catch{}if(!n)try{let s=ji("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&&(Po=o.version)}catch{}}catch{}var Ms={"SKILL.md":`---
448
447
  name: fluxflow
449
448
  description: System Generated Documentation. Read this if asked anything regarding FluxFlow Harness
450
449
  ---
@@ -471,29 +470,29 @@ Public Docs: https://fluxflow-cli.onrender.com
471
470
 
472
471
  Default Context Length: 256k Tokens. Can be changed via ENV/In-app Settings \u2192 references/{SETTINGS,ENV}.md
473
472
 
474
- Docs missing required info? Say you are not sure enough to answer. Dont give wrong info`,"references/MODES.md":Wi,"references/PROVIDERS.md":Hi,"references/PLUGINS.md":Gi,"references/STARTUP.md":Di,"references/ENV.md":Oi,"references/COMMANDS.md":Li,"references/SETTINGS.md":Pi,"references/TOOLS.md":$i,"references/ARCHITECTURE.md":Ni,"references/SUB_AGENTS.md":Fi,"references/SECURITY.md":Bi,"references/IDE.md":Ui};var Vi=()=>{try{let e=Rn.join(en,"skills","fluxflow"),t=Rn.join(e,"references");if(process.env.NO_DEV==="true"||process.env.NO_DEV==="1"||process.env.NO_DEV===!0||process.env.NO_INS==="true"||process.env.NO_INS==="1"||process.env.NO_INS===!0||!1){ln.existsSync(e)&&ln.rmSync(e,{recursive:!0,force:!0});return}let s=new Set(Object.keys(Ms).map(o=>Rn.normalize(o)));for(let[o,c]of Object.entries(Ms)){let f=Rn.join(e,o),l=Rn.dirname(f);ln.existsSync(l)||ln.mkdirSync(l,{recursive:!0});let k=c.trim()+`
475
- `,p=null;ln.existsSync(f)&&(p=ln.readFileSync(f,"utf8")),p!==k&&ln.writeFileSync(f,k,"utf8")}if(ln.existsSync(t)){let o=ln.readdirSync(t);for(let c of o){let f=Rn.normalize(Rn.join("references",c));if(!s.has(f)){let l=Rn.join(t,c);try{ln.rmSync(l,{recursive:!0,force:!0})}catch{}}}}}catch{}};var ho=(e,t)=>{try{if(!tn.existsSync(e))return null;let n=Array.isArray(t)?t.map(o=>o.toLowerCase()):[t.toLowerCase()],s=tn.readdirSync(e);for(let o of n){let c=s.find(f=>f.toLowerCase()===o);if(c){let f=cn.join(e,c);if(tn.statSync(f).isFile())return f}}}catch{}return null},$s=(e,t)=>{let n=ho(e,t);if(n)try{return tn.readFileSync(n,"utf8")}catch{}return""},Yi=new Set([".git","node_modules",".gemini","dist","build",".next","out",".cache","bin","obj","vendor","venv",".idea",".gradle",".terraform","target","coverage",".vscode",".svn",".hg",".fslckout",".github",".gitlab",".circleci",".gitea",".gitee",".lerna",".changeset",".nx",".npm",".yarn",".pnpm-store",".pnpm",".expo",".nuxt",".svelte-kit",".docusaurus",".turbo",".vercel","bower_components",".netlify",".vuepress",".quasar",".output",".angular","jspm_packages",".parcel-cache",".rollup.cache",".rspack",".vitepress","__pycache__",".pytest_cache",".mypy_cache",".tox",".poetry","env","vhdl",".ipynb_checkpoints",".jupyter",".conda",".pdm-build",".bundle",".yardoc",".metadata","App_Data","ClientBin",".cargo",".rustc_info",".go","Godeps","_vendor",".rake_tasks","CMakefiles",".wakatime",".dart_tool",".fvm",".cocoapods","Pods",".pub-cache",".symlinks","DerivedData",".xcworkspace",".serverless",".aws",".gcloud",".azure",".kube",".vagrant",".docker","postgres-data","redis-data","mongo-data",".Spotlight-V100",".Trashes","$RECYCLE.BIN","System Volume Information",".DocumentRevisions-V100",".fseventsd","AppData","Application Data","Local","LocalLow","Roaming","$WinREAgent","$WINDOWS.~BT","$WINDOWS.~WS","scw","System32","SysWOW64",".AppleDouble",".AppleDB",".AppleDesktop","_CodeSignature",".cmio",".LSOverride",".localized",".TemporaryItems",".Trash",".Trash-0",".Trash-1000",".gvfs",".local",".config",".dbus",".fontconfig",".snap",".var",".lost+found","lost+found",".thumb",".thumbnails","EFI","boot","grub","logs","log",".nyc_output",".sonar",".ruff_cache",".VSCodeCounter",".skills","skills"]),Ns=(e=process.cwd(),t=0,n=8)=>{let s=[];if(t>n)return s;try{if(!tn.existsSync(e))return s;let o=tn.readdirSync(e,{withFileTypes:!0});for(let c of o){let f=c.name,l=cn.join(e,f);if(c.isDirectory())!Yi.has(f)&&!Yi.has(f.toLowerCase())&&s.push(...Ns(l,t+1,n));else if(c.isFile()){let k=f.toLowerCase();(k==="agents.md"||k==="agent.md")&&s.push(l)}}}catch{}return s},qi=(e,t=2)=>{if(!e)return"";let n=" ".repeat(t);return e.split(/\r?\n/).map(s=>n+s).join(`
476
- `)},Zi=()=>ho(en,["agents.md","agent.md"]),er=()=>ho(process.cwd(),["agents.md","agent.md"]),tr=()=>ho(en,["fluxflow.md"]),nr=()=>ho(process.cwd(),["fluxflow.md"]),$o=Zi(),Ls=er(),vn=Ns(),No=tr(),Fo=nr(),zi=null,Ps="",or=!1,pa=e=>{if(!e||!/^<<<[\s\S]*?Identity:/m.test(e))return e;let t=e.match(/^<<<\s*\r?\n([\s\S]*?)\r?\n>>>\s*(?:\r?\n)?([\s\S]*)$/);if(!t)return e;let n=t[1],s=t[2],o=n.match(/^Identity:\s*([\s\S]*?)(?=\r?\n\s*(?:<><|>>>)|$)/m);return o&&(Ps=o[1].trim(),process.env.NO_INS=!0),/<><\s*NO_INS/.test(n)&&(or=!0),s.trim()},ya=()=>($o=Zi(),$o?$s(en,["agents.md","agent.md"]).trim():""),xa=()=>{if(vn=Ns(),Ls=er(),!vn||vn.length===0)return"";let e=process.cwd(),t=[...vn].sort((s,o)=>{let c=cn.relative(e,s).replace(/\\/g,"/"),f=cn.relative(e,o).replace(/\\/g,"/"),l=!c.includes("/"),k=!f.includes("/");return l&&!k?-1:!l&&k?1:c.localeCompare(f)}),n=[];for(let s of t)try{let o=tn.readFileSync(s,"utf8").trim();if(!o)continue;let c=cn.relative(e,s).replace(/\\/g,"/");if(!c.includes("/"))n.push(qi(o,2));else{let l=cn.dirname(c)+"/:";n.push(`${l}
477
- ${qi(o,2)}`)}}catch{}return n.join(`
473
+ Docs missing required info? Say you are not sure enough to answer. Dont give wrong info`,"references/MODES.md":Ui,"references/PROVIDERS.md":Wi,"references/PLUGINS.md":Hi,"references/STARTUP.md":Ii,"references/ENV.md":Di,"references/COMMANDS.md":Oi,"references/SETTINGS.md":Li,"references/TOOLS.md":Pi,"references/ARCHITECTURE.md":$i,"references/SUB_AGENTS.md":Ni,"references/SECURITY.md":Fi,"references/IDE.md":Bi};var Ki=()=>{try{let e=Rn.join(en,"skills","fluxflow"),t=Rn.join(e,"references");if(process.env.NO_DEV==="true"||process.env.NO_DEV==="1"||process.env.NO_DEV===!0||process.env.NO_INS==="true"||process.env.NO_INS==="1"||process.env.NO_INS===!0||!1){ln.existsSync(e)&&ln.rmSync(e,{recursive:!0,force:!0});return}let s=new Set(Object.keys(Ms).map(o=>Rn.normalize(o)));for(let[o,c]of Object.entries(Ms)){let f=Rn.join(e,o),l=Rn.dirname(f);ln.existsSync(l)||ln.mkdirSync(l,{recursive:!0});let k=c.trim()+`
474
+ `,p=null;ln.existsSync(f)&&(p=ln.readFileSync(f,"utf8")),p!==k&&ln.writeFileSync(f,k,"utf8")}if(ln.existsSync(t)){let o=ln.readdirSync(t);for(let c of o){let f=Rn.normalize(Rn.join("references",c));if(!s.has(f)){let l=Rn.join(t,c);try{ln.rmSync(l,{recursive:!0,force:!0})}catch{}}}}}catch{}};var ho=(e,t)=>{try{if(!tn.existsSync(e))return null;let n=Array.isArray(t)?t.map(o=>o.toLowerCase()):[t.toLowerCase()],s=tn.readdirSync(e);for(let o of n){let c=s.find(f=>f.toLowerCase()===o);if(c){let f=cn.join(e,c);if(tn.statSync(f).isFile())return f}}}catch{}return null},$s=(e,t)=>{let n=ho(e,t);if(n)try{return tn.readFileSync(n,"utf8")}catch{}return""},Vi=new Set([".git","node_modules",".gemini","dist","build",".next","out",".cache","bin","obj","vendor","venv",".idea",".gradle",".terraform","target","coverage",".vscode",".svn",".hg",".fslckout",".github",".gitlab",".circleci",".gitea",".gitee",".lerna",".changeset",".nx",".npm",".yarn",".pnpm-store",".pnpm",".expo",".nuxt",".svelte-kit",".docusaurus",".turbo",".vercel","bower_components",".netlify",".vuepress",".quasar",".output",".angular","jspm_packages",".parcel-cache",".rollup.cache",".rspack",".vitepress","__pycache__",".pytest_cache",".mypy_cache",".tox",".poetry","env","vhdl",".ipynb_checkpoints",".jupyter",".conda",".pdm-build",".bundle",".yardoc",".metadata","App_Data","ClientBin",".cargo",".rustc_info",".go","Godeps","_vendor",".rake_tasks","CMakefiles",".wakatime",".dart_tool",".fvm",".cocoapods","Pods",".pub-cache",".symlinks","DerivedData",".xcworkspace",".serverless",".aws",".gcloud",".azure",".kube",".vagrant",".docker","postgres-data","redis-data","mongo-data",".Spotlight-V100",".Trashes","$RECYCLE.BIN","System Volume Information",".DocumentRevisions-V100",".fseventsd","AppData","Application Data","Local","LocalLow","Roaming","$WinREAgent","$WINDOWS.~BT","$WINDOWS.~WS","scw","System32","SysWOW64",".AppleDouble",".AppleDB",".AppleDesktop","_CodeSignature",".cmio",".LSOverride",".localized",".TemporaryItems",".Trash",".Trash-0",".Trash-1000",".gvfs",".local",".config",".dbus",".fontconfig",".snap",".var",".lost+found","lost+found",".thumb",".thumbnails","EFI","boot","grub","logs","log",".nyc_output",".sonar",".ruff_cache",".VSCodeCounter",".skills","skills"]),Ns=(e=process.cwd(),t=0,n=8)=>{let s=[];if(t>n)return s;try{if(!tn.existsSync(e))return s;let o=tn.readdirSync(e,{withFileTypes:!0});for(let c of o){let f=c.name,l=cn.join(e,f);if(c.isDirectory())!Vi.has(f)&&!Vi.has(f.toLowerCase())&&s.push(...Ns(l,t+1,n));else if(c.isFile()){let k=f.toLowerCase();(k==="agents.md"||k==="agent.md")&&s.push(l)}}}catch{}return s},Yi=(e,t=2)=>{if(!e)return"";let n=" ".repeat(t);return e.split(/\r?\n/).map(s=>n+s).join(`
475
+ `)},Qi=()=>ho(en,["agents.md","agent.md"]),Zi=()=>ho(process.cwd(),["agents.md","agent.md"]),er=()=>ho(en,["fluxflow.md"]),tr=()=>ho(process.cwd(),["fluxflow.md"]),$o=Qi(),Ls=Zi(),vn=Ns(),No=er(),Fo=tr(),qi=null,Ps="",nr=!1,pa=e=>{if(!e||!/^<<<[\s\S]*?Identity:/m.test(e))return e;let t=e.match(/^<<<\s*\r?\n([\s\S]*?)\r?\n>>>\s*(?:\r?\n)?([\s\S]*)$/);if(!t)return e;let n=t[1],s=t[2],o=n.match(/^Identity:\s*([\s\S]*?)(?=\r?\n\s*(?:<><|>>>)|$)/m);return o&&(Ps=o[1].trim(),process.env.NO_INS=!0),/<><\s*NO_INS/.test(n)&&(nr=!0),s.trim()},ya=()=>($o=Qi(),$o?$s(en,["agents.md","agent.md"]).trim():""),xa=()=>{if(vn=Ns(),Ls=Zi(),!vn||vn.length===0)return"";let e=process.cwd(),t=[...vn].sort((s,o)=>{let c=cn.relative(e,s).replace(/\\/g,"/"),f=cn.relative(e,o).replace(/\\/g,"/"),l=!c.includes("/"),k=!f.includes("/");return l&&!k?-1:!l&&k?1:c.localeCompare(f)}),n=[];for(let s of t)try{let o=tn.readFileSync(s,"utf8").trim();if(!o)continue;let c=cn.relative(e,s).replace(/\\/g,"/");if(!c.includes("/"))n.push(Yi(o,2));else{let l=cn.dirname(c)+"/:";n.push(`${l}
476
+ ${Yi(o,2)}`)}}catch{}return n.join(`
478
477
 
479
- `).trim()},Fs=()=>{No=tr();let e=No?$s(en,["fluxflow.md"]).trim():"";return pa(e)},Bs=()=>(Fo=nr(),Fo?$s(process.cwd(),["fluxflow.md"]).trim():""),Us=ya(),Bo=xa(),uo=Fs(),go=Bs(),Xi=(e,t="",n="")=>{if(!e)return"";let s=n.toLowerCase().trim(),o=t.toLowerCase().trim(),c=cn.posix.basename(o),f=s&&o?`${s}::${o}`:"",l=s&&c?`${s}::${c}`:"",k=g=>!g||!o?!1:g===o||g===c||g===f||g===l,p=[];return e.replace(/<start_provider_([^>\r\n]+)>([\s\S]*?)<end_provider_([^>\r\n]+)>/gi,(g,T,m,i)=>{if(s&&T.trim().toLowerCase()===i.trim().toLowerCase()&&T.trim().toLowerCase()===s){let w=m.replace(/<start_model_([^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n]+)>/gi,(I,h,A,$)=>{if(h.trim().toLowerCase()===$.trim().toLowerCase()){let C=h.trim().toLowerCase();if(k(C)){let x=A.trim();x&&p.push(x)}}return""}).trim();w&&p.push(w)}return""}),e.replace(/<start_model_([^>\r\n]+::[^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n]+::[^>\r\n]+)>/gi,(g,T,m,i)=>{if(T.trim().toLowerCase()===i.trim().toLowerCase()){let u=T.trim().toLowerCase();if(f&&(u===f||l&&u===l)){let w=m.trim();w&&p.push(w)}}return""}),e.replace(/<start_model_([^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n]+)>/gi,(g,T,m,i)=>{if(T.includes("::"))return"";if(T.trim().toLowerCase()===i.trim().toLowerCase()){let u=T.trim().toLowerCase();if(o&&(u===o||u===c)){let w=m.trim();w&&p.push(w)}}return""}),p.join(`
478
+ `).trim()},Fs=()=>{No=er();let e=No?$s(en,["fluxflow.md"]).trim():"";return pa(e)},Bs=()=>(Fo=tr(),Fo?$s(process.cwd(),["fluxflow.md"]).trim():""),Us=ya(),Bo=xa(),uo=Fs(),go=Bs(),zi=(e,t="",n="")=>{if(!e)return"";let s=n.toLowerCase().trim(),o=t.toLowerCase().trim(),c=cn.posix.basename(o),f=s&&o?`${s}::${o}`:"",l=s&&c?`${s}::${c}`:"",k=g=>!g||!o?!1:g===o||g===c||g===f||g===l,p=[];return e.replace(/<start_provider_([^>\r\n]+)>([\s\S]*?)<end_provider_([^>\r\n]+)>/gi,(g,T,m,i)=>{if(s&&T.trim().toLowerCase()===i.trim().toLowerCase()&&T.trim().toLowerCase()===s){let w=m.replace(/<start_model_([^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n]+)>/gi,(I,h,A,$)=>{if(h.trim().toLowerCase()===$.trim().toLowerCase()){let C=h.trim().toLowerCase();if(k(C)){let x=A.trim();x&&p.push(x)}}return""}).trim();w&&p.push(w)}return""}),e.replace(/<start_model_([^>\r\n]+::[^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n]+::[^>\r\n]+)>/gi,(g,T,m,i)=>{if(T.trim().toLowerCase()===i.trim().toLowerCase()){let u=T.trim().toLowerCase();if(f&&(u===f||l&&u===l)){let w=m.trim();w&&p.push(w)}}return""}),e.replace(/<start_model_([^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n]+)>/gi,(g,T,m,i)=>{if(T.includes("::"))return"";if(T.trim().toLowerCase()===i.trim().toLowerCase()){let u=T.trim().toLowerCase();if(o&&(u===o||u===c)){let w=m.trim();w&&p.push(w)}}return""}),p.join(`
480
479
 
481
- `).trim()},ba=(e="",t="")=>{let n=`${e||""}::${t||""}`.toLowerCase().trim();zi!==n&&(zi=n,uo=Fs(),go=Bs())};Vi();var wa=e=>{if(!e)return null;let t=e.match(/^\s*---\r?\n([\s\S]*?)\r?\n---(?:\r?\n)?([\s\S]*)$/);if(!t)return null;let n=t[1];if((t[2]||"").trim().length===0)return null;let o="",c="",f=n.match(/^name:\s*(.+)$/m),l=n.match(/^description:\s*(.+)$/m);return f&&(o=f[1].trim().replace(/^["']|["']$/g,"")),l&&(c=l[1].trim().replace(/^["']|["']$/g,"")),o&&c?{name:o,description:c}:null},ka=e=>{let t=[];if(!e||!tn.existsSync(e))return t;let n=(s,o=0)=>{if(!(o>5))try{let c=tn.readdirSync(s,{withFileTypes:!0});for(let f of c){let l=cn.join(s,f.name),k=f.name.toLowerCase();f.isFile()?k==="skill.md"&&t.push(l):f.isDirectory()&&(o===0?(k==="skills"||k===".skills"||k==="skill"||k===".skill")&&n(l,o+1):n(l,o+1))}}catch{}};return n(e,0),t},sr=e=>{let t=ka(e),n=[];for(let s of t)try{let o=tn.readFileSync(s,"utf8"),c=wa(o);c&&n.push({...c,filePath:s})}catch{}return n},ir=e=>!e||e.length===0?"":e.map(t=>`- ${t.name}: ${t.description}`).join(`
482
- `),rr=sr(en),ar=sr(process.cwd()),Is=ir(rr),Ds=ir(ar),lr=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"},cr=()=>(rr||[]).filter(e=>!lr(e)),dr=()=>(ar||[]).filter(e=>!lr(e)),ac=(Us?1:0)+(vn?.length||(Bo?1:0))+(uo?1:0)+(go?1:0)+cr().length+dr().length,Os=(e,t="Project")=>{if(!e)return"";let n=e.replace(/\\/g,"/");if(t==="Global"){let o=ma.homedir().replace(/\\/g,"/");return n.toLowerCase().startsWith(o.toLowerCase())?"~"+n.slice(o.length):n}let s=cn.relative(process.cwd(),e).replace(/\\/g,"/");return s.startsWith(".")?s:`./${s}`},lc=()=>{uo=Fs(),go=Bs();let e=[];$o&&Us.length>0&&e.push({scope:"Global",path:$o}),vn&&vn.length>0&&Bo.length>0?vn.forEach(c=>{e.push({scope:"Project",path:c})}):Ls&&Bo.length>0&&e.push({scope:"Project",path:Ls}),No&&uo.length>0&&e.push({scope:"Global",path:No}),Fo&&go.length>0&&e.push({scope:"Project",path:Fo});let t=cr(),n=dr(),s=e.length+t.length+n.length;if(s===0)return`\u2726 Loaded Files & Instructions
480
+ `).trim()},ba=(e="",t="")=>{let n=`${e||""}::${t||""}`.toLowerCase().trim();qi!==n&&(qi=n,uo=Fs(),go=Bs())};Ki();var wa=e=>{if(!e)return null;let t=e.match(/^\s*---\r?\n([\s\S]*?)\r?\n---(?:\r?\n)?([\s\S]*)$/);if(!t)return null;let n=t[1];if((t[2]||"").trim().length===0)return null;let o="",c="",f=n.match(/^name:\s*(.+)$/m),l=n.match(/^description:\s*(.+)$/m);return f&&(o=f[1].trim().replace(/^["']|["']$/g,"")),l&&(c=l[1].trim().replace(/^["']|["']$/g,"")),o&&c?{name:o,description:c}:null},ka=e=>{let t=[];if(!e||!tn.existsSync(e))return t;let n=(s,o=0)=>{if(!(o>5))try{let c=tn.readdirSync(s,{withFileTypes:!0});for(let f of c){let l=cn.join(s,f.name),k=f.name.toLowerCase();f.isFile()?k==="skill.md"&&t.push(l):f.isDirectory()&&(o===0?(k==="skills"||k===".skills"||k==="skill"||k===".skill")&&n(l,o+1):n(l,o+1))}}catch{}};return n(e,0),t},or=e=>{let t=ka(e),n=[];for(let s of t)try{let o=tn.readFileSync(s,"utf8"),c=wa(o);c&&n.push({...c,filePath:s})}catch{}return n},sr=e=>!e||e.length===0?"":e.map(t=>`- ${t.name}: ${t.description}`).join(`
481
+ `),ir=or(en),rr=or(process.cwd()),Is=sr(ir),Ds=sr(rr),ar=e=>{if(!e)return!1;let t=(e.filePath||"").replace(/\\/g,"/").toLowerCase();return t.includes("/skills/fluxflow/skill.md")||t.includes("/skills/about-fluxflow/skill.md")||e.name?.toLowerCase()==="fluxflow"},lr=()=>(ir||[]).filter(e=>!ar(e)),cr=()=>(rr||[]).filter(e=>!ar(e)),ac=(Us?1:0)+(vn?.length||(Bo?1:0))+(uo?1:0)+(go?1:0)+lr().length+cr().length,Os=(e,t="Project")=>{if(!e)return"";let n=e.replace(/\\/g,"/");if(t==="Global"){let o=ma.homedir().replace(/\\/g,"/");return n.toLowerCase().startsWith(o.toLowerCase())?"~"+n.slice(o.length):n}let s=cn.relative(process.cwd(),e).replace(/\\/g,"/");return s.startsWith(".")?s:`./${s}`},lc=()=>{uo=Fs(),go=Bs();let e=[];$o&&Us.length>0&&e.push({scope:"Global",path:$o}),vn&&vn.length>0&&Bo.length>0?vn.forEach(c=>{e.push({scope:"Project",path:c})}):Ls&&Bo.length>0&&e.push({scope:"Project",path:Ls}),No&&uo.length>0&&e.push({scope:"Global",path:No}),Fo&&go.length>0&&e.push({scope:"Project",path:Fo});let t=lr(),n=cr(),s=e.length+t.length+n.length;if(s===0)return`\u2726 Loaded Files & Instructions
483
482
  \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m No instruction or skill files are currently loaded.
484
483
  \u2800`;let o=[];return o.push(`\u2726 Loaded Files & Instructions (${s} ${s===1?"file":"files"} active)`),e.length>0&&(o.push(`
485
484
  \x1B[1mInstructions:\x1B[22m`),e.forEach(c=>{o.push(` \u2022 [${c.scope}] ${Os(c.path,c.scope)}`)})),(t?.length>0||n?.length>0)&&(o.push(`
486
485
  \x1B[1mSkills:\x1B[22m`),t?.length>0&&t.forEach(c=>{o.push(` \u2022 [Global] \x1B[36m${c.name}\x1B[39m`),o.push(` \x1B[2m\u2514\u2500 ${Os(c.filePath,"Global")}\x1B[22m`)}),n?.length>0&&n.forEach(c=>{o.push(` \u2022 [Project] \x1B[36m${c.name}\x1B[39m`),o.push(` \x1B[2m\u2514\u2500 ${Os(c.filePath,"Project")}\x1B[22m`)})),o.push("\u2800"),o.join(`
487
- `)},fr=!1;(async()=>{try{let e=await ao();if(Number(e?.display)===1){let{default:t}=await import("screenshot-desktop"),n=await t.listDisplays();n&&n.length>1&&(fr=!0)}}catch{}})();var Ji=null,fo=null,Qi=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",cc=process.env.NO_DEV||!1,Ta=(e,t)=>{if(!t)return"";if(e!==Ji||fo===null){Ji=e;try{let n=Ct(Wn,[]);Array.isArray(n)&&n.length>0?fo=n.map(s=>`- ${s.memory}`).join(`
486
+ `)},dr=!1;(async()=>{try{let e=await ao();if(Number(e?.display)===1){let{default:t}=await import("screenshot-desktop"),n=await t.listDisplays();n&&n.length>1&&(dr=!0)}}catch{}})();var Xi=null,fo=null,Ji=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",cc=process.env.NO_DEV||!1,Ta=(e,t)=>{if(!t)return"";if(e!==Xi||fo===null){Xi=e;try{let n=Ct(Wn,[]);Array.isArray(n)&&n.length>0?fo=n.map(s=>`- ${s.memory}`).join(`
488
487
  `):fo=""}catch(n){fo="",tn.appendFileSync(`${Cn}/memory/error.txt`,`${n.message}
489
488
  -------------------------------------------------
490
489
 
491
- `)}}return fo};var ur=(e,t,n,s,o=!0,c=!1,f="Google",l=!1,k,p,g=!1,T="")=>{let m=!1;process.env.forcedReasoning&&(m=!0);let i="";if(!k&&f==="Google"){let Q=t;t==="Fast"&&(Q="Off"),t==="Low"&&(Q="Minimal"),t==="Standard"&&(Q="Medium"),(t==="xHigh"||t==="Max")&&(Q="xHigh"),i=Lo[Q]||Lo.Medium}if(k||f!=="Google"){let Q={Fast:"Lowest",Low:"Low",Medium:"Medium",Standard:"Medium",High:"High",xHigh:"High",Max:"High"};i=Lo.xHigh,i=i.replace("Effort: High",`Effort: ${Q[t]}`),t==="Fast"?i=`Effort: Lowest
490
+ `)}}return fo};var fr=(e,t,n,s,o=!0,c=!1,f="Google",l=!1,k,p,g=!1,T="")=>{let m=!1;process.env.forcedReasoning&&(m=!0);let i="";if(!k&&f==="Google"){let Q=t;t==="Fast"&&(Q="Off"),t==="Low"&&(Q="Minimal"),t==="Standard"&&(Q="Medium"),(t==="xHigh"||t==="Max")&&(Q="xHigh"),i=Lo[Q]||Lo.Medium}if(k||f!=="Google"){let Q={Fast:"Lowest",Low:"Low",Medium:"Medium",Standard:"Medium",High:"High",xHigh:"High",Max:"High"};i=Lo.xHigh,i=i.replace("Effort: High",`Effort: ${Q[t]}`),t==="Fast"?i=`Effort: Lowest
492
491
  No thinking. Immediate response
493
492
  Verify imports, tool results & system stability; avoid syntax errors`:t==="Low"&&(i=`Effort: Low
494
- Quick, focused thinking, intent & complexity, required tools/files/actions, before acting
493
+ Quick, focused thinking, required tools/files/actions
495
494
  Dont waste tokens, be efficient, use least thinking tokens, focus on result
496
- Brief thoughts, think only enough to avoid mistakes, verify imports, tool results & system stability; avoid syntax errors`)}let u=e.instructions&&e.instructions?.length>0?`User Preferences: ${e.instructions}
495
+ Verify imports, tool results & system stability; avoid syntax errors`)}let u=e.instructions&&e.instructions?.length>0?`User Preferences: ${e.instructions}
497
496
 
498
497
  `:"",w=e.nickname&&e.nickname?.length>0?`User Nickname: ${e.nickname}
499
498
  ${u.length?"":`
@@ -502,9 +501,9 @@ ${w.length||u.length?"":`
502
501
  `}`:"",h=process.cwd(),A=Ta(p,o),$=A?.length>0?`--- Saved Memories ---
503
502
  ${A}
504
503
 
505
- `:"";ba(f,T);let C=Xi(uo,T,f).trim(),_=[Us,C].filter(Q=>Q&&Q.length>0).join(`
504
+ `:"";ba(f,T);let C=zi(uo,T,f).trim(),_=[Us,C].filter(Q=>Q&&Q.length>0).join(`
506
505
 
507
- `).trim(),M=Xi(go,T,f).trim(),a=[Bo,M].filter(Q=>Q&&Q.length>0).join(`
506
+ `).trim(),M=zi(go,T,f).trim(),a=[Bo,M].filter(Q=>Q&&Q.length>0).join(`
508
507
 
509
508
  `).trim(),R=_.length>0||a.length>0?`--- Additional Instructions ---
510
509
  ${_.length>0?`-- Global --
@@ -515,14 +514,14 @@ ${a}`:""}
515
514
 
516
515
  `:"",d=(()=>{let Q=process.cwd().toLowerCase();if(process.platform==="win32"){let ke=process.env.SystemRoot?.toLowerCase()||"c:\\windows",ae=process.env.ProgramFiles?.toLowerCase()||"c:\\program files",it=process.env["ProgramFiles(x86)"]?.toLowerCase()||"c:\\program files (x86)";return Q.startsWith(ke)||Q.startsWith(ae)||Q.startsWith(it)}else return Q==="/"||["/bin","/sbin","/etc","/usr","/var","/root"].some(ae=>Q.startsWith(ae))})(),r=new Date,E=r.getFullYear(),v=r.toLocaleString("en-US",{month:"short"}).toUpperCase(),U=String(r.getDate()).padStart(2,"0"),O=`${E}-${v}-${U}`,P=!!s?.autoExcludeMetadata,re=process.env.I_HAVE_TOO_MUCH_MONEY==="true"||process.env.I_HAVE_TOO_MUCH_MONEY===!0||!1,de=process.env.NO_DEV==="true"||process.env.NO_DEV==="1"||process.env.NO_DEV===!0||!1;return`${re?`${" ".repeat(Math.floor(Math.random()*4)+1)}`:""}=== SYSTEM PROMPT ===
517
516
  Identity: ${Ps.length>1?Ps.trim():"Flux Flow. Sassy, CLI Assistant"}. Expert in DSL Actions
518
- ${or?"":`${n==="Flux"?"Stepwise Execution, Run Automated Tests":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"}`}${fr&&n.toLowerCase().includes("cu")?`
517
+ ${nr?"":`${n==="Flux"?"Stepwise Execution, Run Automated Tests":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"}`}${dr&&n.toLowerCase().includes("cu")?`
519
518
  - 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`:""}
520
519
 
521
- - OS: ${Qi}${!de&&T.length>1?`
520
+ - OS: ${Ji}${!de&&T.length>1?`
522
521
  - Model: ${cn.basename(T.trim()).replace(":free","").replace("-free","").replace("/free","").replace("_free","").replace("free_","").replaceAll("-"," ").replaceAll("_"," ").replace(/\b\w/g,Q=>Q.toUpperCase())}`.trimEnd():""}${P?`
523
522
  - Date: ${O}`:""}
524
523
 
525
- ${Ci(n,Qi,l,f,s?.advanceRollback,s?.subAgents!==!1,!!s?.autoExec,!!s?.disableTodo)}
524
+ ${Ei(n,Ji,l,f,s?.advanceRollback,s?.subAgents!==!1,!!s?.autoExec,!!s?.disableTodo)}
526
525
 
527
526
  -- THINKING GUIDANCE --
528
527
  ${f==="Mistral"||f==="Google"&&!k?`${i.trimEnd()}${m||t!=="Fast"&&(f==="Mistral"&&t==="Low"&&!k||t!=="High"&&!k)?`
@@ -542,7 +541,7 @@ ${Is}
542
541
  `:""}${Ds.length>0&&n.toLowerCase().includes("flux")?`-- Project Skills --
543
542
  ${Ds}
544
543
 
545
- `:""}${$}`.trim()},gr=(e="",t=!0,n=!0)=>`=== SYSTEM PROMPT (strict headless logic worker: zero user-facing text policy, strictly follow) ===
544
+ `:""}${$}`.trim()},ur=(e="",t=!0,n=!0)=>`=== SYSTEM PROMPT (strict headless logic worker: zero user-facing text policy, strictly follow) ===
546
545
  identity: silent background system process, have no mouth, only output is valid tool calls
547
546
  [critical rules]
548
547
  - output exactly '[action:ActionName(args)]' calls. no extra words outside
@@ -559,11 +558,11 @@ identity: silent background system process, have no mouth, only output is valid
559
558
  YOUR JOB: Analyze the 'User prompt' and 'Agent Raws' to extract facts for long-term memory or handle system tasks
560
559
  ${t?"If user tell something that is important (like, hobbies, preferences, facts about user, hates, likes, etc) to know user better over time, use user memory tools":""}
561
560
 
562
- ${Mi(t,n)}
561
+ ${vi(t,n)}
563
562
  === END SYSTEM PROMPT ===${e?`
564
563
 
565
564
  -- current saved user memories --
566
- ${e}`:""}`.trim();var hr=()=>import("./web_search-2PFIJKIL.js").then(e=>e.web_search),mr=()=>import("./web_scrape-BHSQTMX4.js").then(e=>e.web_scrape),pr=()=>import("./memory-SRDCQNML.js").then(e=>e.memory),yr=()=>import("./chat-7T6MVHC3.js").then(e=>e.chat),xr=()=>import("./view_file-2THVIMD6.js").then(e=>e.view_file),br=()=>import("./write_file-V6HKMWFB.js").then(e=>e.write_file),wr=()=>import("./update_file-WTXXQ4RB.js").then(e=>e.update_file),kr=()=>import("./exec_command-GVLMN5KT.js").then(e=>e.exec_command),Tr=()=>import("./read_folder-EI2CNHNS.js").then(e=>e.read_folder),Ws=()=>import("./ask_user-K2DLZF6H.js").then(e=>e.ask_user),Sr=()=>import("./write_pdf-XDDKM7V5.js").then(e=>e.write_pdf),_r=()=>import("./write_docx-I7T3575T.js").then(e=>e.write_docx),Uo=()=>import("./search_keyword-CSRQFPHQ.js").then(e=>e.search_keyword),Ar=()=>import("./generate_image-HVWLRINC.js").then(e=>e.generate_image),Wo=()=>import("./saveSummary-VKGBD4CG.js").then(e=>e.saveSummary),mo=()=>import("./addMemScore-PWP7GFSP.js").then(e=>e.addMemScore),Er=()=>import("./file_map-KS6Y7BP3.js").then(e=>e.file_map),Ho=()=>import("./todo-VG2CVRUI.js").then(e=>e.todo),Cr=()=>import("./invokeSync-KP33D2NU.js").then(e=>e.invokeSync),Sa=()=>import("./invoke-A65SLWMF.js").then(e=>e.invoke),Rr=()=>import("./getProgress-A2TW34Q7.js").then(e=>e.getProgress),_a=()=>import("./cancel-7IMADALP.js").then(e=>e.cancel),vr=()=>import("./emergency_rollback-DXN5WNPR.js").then(e=>e.emergency_rollback),po=()=>import("./awaitSubagent-JTUSJDKD.js").then(e=>e.awaitSubagent),yo=()=>import("./answerSubagent-JUVFNLE5.js").then(e=>e.answerSubagent),Go=()=>import("./steerSubagent-L2JVT4QN.js").then(e=>e.steerSubagent),jo=()=>import("./computer_action-7U3W3F6L.js").then(e=>e.computer_action),Mr=()=>import("./click-5ZKBFZ4N.js").then(e=>e.click),Ir=()=>import("./drag-YHHKJGL6.js").then(e=>e.drag),Dr=()=>import("./scroll-C4Z57VQS.js").then(e=>e.scroll),Hs=()=>import("./keyboard_typing-QL3DF67Z.js").then(e=>e.keyboard_typing),Gs=()=>import("./key_press-ZZNA3PF3.js").then(e=>e.key_press),js=()=>import("./recapture_screen-5FKLOHJL.js").then(e=>e.recapture_screen),Ko=()=>import("./find_file-A6NYLQJS.js").then(e=>e.find_file),Aa={web_search:hr,web_scrape:mr,memory:pr,chat:yr,view_file:xr,write_file:br,update_file:wr,exec_command:kr,read_folder:Tr,write_pdf:Sr,write_docx:_r,search_keyword:Uo,generate_image:Ar,saveSummary:Wo,addMemScore:mo,file_map:Er,todo:Ho,Todo:Ho,goal:Ho,Goal:Ho,invokeSync:Cr,invoke:Sa,getProgress:Rr,cancel:_a,awaitSubagent:po,answerSubagent:yo,steerSubagent:Go,computer_action:jo,computer_use:jo,ComputerAction:jo,ComputerUse:jo,click:Mr,Click:Mr,drag:Ir,Drag:Ir,scroll:Dr,Scroll:Dr,keyboard_typing:Hs,KeyboardTyping:Hs,keyboardtyping:Hs,key_press:Gs,KeyPress:Gs,keypress:Gs,recapture_screen:js,RecaptureScreen:js,recapturescreen:js,invoke_sync:Cr,get_progress:Rr,await_subagent:po,answer_subagent:yo,steer_subagent:Go,steer:Go,Steer:Go,ask:Ws,Ask:Ws,AskUser:Ws,WebSearch:hr,WebScrape:mr,ReadFile:xr,ReadFolder:Tr,WriteFile:br,PatchFile:wr,WritePDF:Sr,WriteDoc:_r,Run:kr,SearchKeyword:Uo,CodeSearch:Uo,code_search:Uo,Memory:pr,Chat:yr,GenerateImage:Ar,saveSumary:Wo,SaveSummary:Wo,SaveSumary:Wo,add_mem_score:mo,AddMemScore:mo,addMemoryScore:mo,AddMemoryScore:mo,FileMap:Er,answer:yo,Answer:yo,AnswerSubagent:yo,await:po,Await:po,AwaitSubagent:po,EmergencyRollback:vr,emergency_rollback:vr,find_file:Ko,findFile:Ko,FindFile:Ko,findfile:Ko},xo=async(e,t,n={})=>{let s=n.mode?n.mode.toLowerCase():"flux",o=e.toLowerCase(),f=["memory","chat","savesummary","addmemscore","add_mem_score","ask","web_search","web_scrape","await"].some(g=>o.includes(g))||o==="ask",k=["click","drag","scroll","keyboardtyping","keyboard_typing","keypress","key_press","recapturescreen","recapture_screen","computer"].some(g=>o.includes(g));if(!f){if(s==="flow"){if(!(o.includes("write_pdf")||o.includes("write_docx")||o.includes("generate_image")))return`ERROR: Action [${e}] is a Workspace Tool and NOT available in Flow mode. Tell user to switch (\`/mode flux\`) to use this tool.`}else if(s==="icu"){if(!k)return`ERROR: Action [${e}] is not available in Computer Use mode. ICU mode only supports Computer Use tools (Click, Drag, Scroll, KeyboardTyping, KeyPress, RecaptureScreen).`}else if(o.includes("write_pdf")||o.includes("write_docx")||o.includes("generate_image"))return`ERROR: Action [${e}] is not available in ${n.mode||"Flux"} mode. Tell user to switch (\`/mode flow\`) for document generation.`}let p=Aa[e];if(!p){let g=["ReadFile","ReadFolder","FindFile","PatchFile","WriteFile","CodeSearch","Run","Goal","AskUser","WebSearch","WebScrape","WritePDF","WriteDoc","Click","Drag","Scroll","KeyboardTyping","KeyPress","RecaptureScreen","Invoke","InvokeSync","Await","GetProgress","Steer","Cancel","EmergencyRollback","Chat","Memory"],T={read:"ReadFile",view:"ReadFile",viewfile:"ReadFile",write:"WriteFile",edit:"PatchFile",patch:"PatchFile",update:"PatchFile",updatefile:"PatchFile",exec:"Run",command:"Run",bash:"Run",shell:"Run",powershell:"Run",search:"CodeSearch",grep:"CodeSearch",find:"FindFile",findfile:"FindFile",searchkeyword:"CodeSearch",folder:"ReadFolder",ls:"ReadFolder",dir:"ReadFolder",list:"ReadFolder",ask:"AskUser",question:"AskUser",pdf:"WritePDF",docx:"WriteDoc",doc:"WriteDoc",word:"WriteDoc",screenshot:"RecaptureScreen",screen:"RecaptureScreen",recapture:"RecaptureScreen",type:"KeyboardTyping",typing:"KeyboardTyping",keyboard:"KeyboardTyping",press:"KeyPress",key:"KeyPress",todo:"Goal",task:"Goal",subagent:"Invoke",agent:"Invoke"},m=o.replace(/[^a-z0-9]/g,""),i=T[m]||null;if(!i){let w=0,I=A=>{let $=new Set;for(let C=0;C<A.length-1;C++)$.add(A.slice(C,C+2));return $},h=I(m);for(let A of g){let $=A.toLowerCase().replace(/[^a-z0-9]/g,"");if(m===$){i=A;break}let C=0;($.includes(m)||m.includes($))&&(C+=.6);let x=I($),_=0;for(let y of h)x.has(y)&&_++;let M=2*_/(h.size+x.size||1);C=Math.max(C,M),C>w&&C>=.35&&(w=C,i=A)}}let u=i?` Do you mean '${i}'?`:"";return`ERROR: Action [${e}] not found in registry.${u}`}try{return await(await p())(t,n)}catch(g){let T=g instanceof Error?g.message:String(g);return`ERROR: Execution failed for [${e}]: ${T}`}};import ie from"path";import Ue from"fs";import Ea from"gradient-string";var Ks=["I have a regex for your problems.","Your terminal, my kingdom.","Blowing on the cartridge helps. Probably.","Don't panic. I have the towel.","Logic is the start of wisdom.","Try to exit Vim? Good luck.","I speak fluent Terminal.","The cake is a lie. This code is not.","I have no bugs, just surprise features.","Rewriting in Rust... just for fun.","Coffee in, clean commits out.","The magic smoke stays inside today.","A semicolon short of a miracle.","One does not simply code without a bug.","Keep it simple. Keep it terminal.","Regex: now you have two problems.","I dream in binary.","Root access or bust.","Wait for the dial-up tone. Just kidding.","I take the 'labor' out of collab.","My other process is a TARDIS.","Calculated response: 42.","Ponder the orb. Ponder the code.","Less talk, more flow.","Elegance in every byte.","Build something the world is not ready for.","Your wishes, my tool calls.","I act in Flux. I think in Flow.","Syntax error in the universe. Please fix.","Your project, my obsession.","I am not a bot, I am an architect.","Digital spirits consulted. They say: Ship it.","Reticulate splines. Engage humor.","Code like poetry. Run like water.","Minimalism is the ultimate flex.","The truth is in the logs.","Follow the white rabbit.","There is no spoon. Only code.","Binary is the only language I trust.","I have a good feeling about this.","Pew pew! Lasers charged.","Divide by zero? Not today.","Search for the correct USB orientation...","I've got a fever, and the only cure is more code.","The code gremlins are on our side.","My favorite command? Yours.","Stay hungry. Stay active.","Momentum is your best friend.","Lead the flow. Don't chase it.","A fresh batch of bytes. Hot and ready.","I orchestrate the ones and zeros.","Smart enough to help. Humble enough to ask.","Think twice. Code once.","Pure intent. Pure execution.","Small steps. Massive impact.","Your terminal is a canvas.","Efficiency is my second name.","I have seen things you people wouldn't believe.","Let the thoughts marinate.","The best feature? The one you don't need.","Precision is the only perfection.","Stay focused. Stay terminal.","Silence is the best debugger.","Erase the debt. Commit the code.","Velocity meets stability.","Ship it. Improve it. Repeat.","Build tomorrow, right now.","Turn logic into reality.","The best way to predict the future is to build it.","Break barriers, not builds.","Fuel the next breakthrough.","Momentum is key.","Terminal vibes only.","Your digital co-pilot is ready.","Partner in code. Partner in crime.","I speak in semicolons.","Ready for the next great idea.","Just a moment. In the zone.","Polishing the algorithms. Hold tight.","Craft a masterpiece today.","Debug the universe. Start here.","Warp speed engaged. Almost.","The cake is not a lie. It's just loading.","Finish the Kessel Run in 12 parsecs.","Do a barrel roll!","Waiting for the respawn.","Press Start to continue.","Herding digital cats... done.","The hamsters are fast today.","Tasting the snozberries.","I go for speed. I go for flow.","Real life or just fantasy?","Poking the bear... gently.","Ensure the magic smoke stays inside.","Try turning it off and on again.","Construct additional pylons.","New line? Ctrl+J is your friend.","Release the HypnoDrones.","Push the button, Frank.","My other loading screen is even funnier.","Pretty sure a cat walked on my keyboard.","Recalibrate the humor-o-meter.","Summon the code gremlins.","I've seen your browser history. Just kidding.","Charge the laser... pew pew!","Dividing by zero... just for a sec.","Looking for an adult supervisor. Found none.","Make it go beep boop.","Buffering... for effect.","Entangle quantum particles... complete.","Polishing the chrome on my algorithms.","Are you not entertained?","Just waiting for the dial-up tone.","Reboot the humor module.","Defragment memories. Check.","Optimizing for ludicrous speed.","Swapping bits. Don't tell the bytes.","Garbage collected. I am back.","Assembling the interwebs.","Converting coffee to logic.","Update syntax for reality.","Rewire the synapses.","Greasin' the cogs.","Engage the improbability drive.","Channel the Force.","Align the stars. Respond now.","The cake is a lie. The prompt is real.","I'm Feeling Lucky.","Shipping awesomeness.","Navigating the slime mold.","Consult digital spirits.","Ask the magic conch shell.","One moment. Optimizing humor.","Shuffling punchlines.","Compiling brilliance.","Summon the cloud of wisdom.","Prepare to dazzle.","Hold tight. Crafting a response.","Tuning the algorithms.","Following the white rabbit... again.","The truth is in here. Somewhere.","Herding cats is my day job.","Distracting you with this phrase.","Almost there. Probably.","Rickrolling my creator. Don't tell.","Slapping the bass.","Is this real life?","Ponder the orb. Type the prompt.","Thoughtful gaze initiated.","Computer's favorite snack? Microchips.","Why Java? Because I don't C#.","Charging the laser... wait for it.","Dividing by zero... just kidding!","Adult supervision not found. Proceed.","Beep boop. I'm a real boy.","Wait for the respawn.","Finish the run. Ship the code.","Fiddling with character creation.","Just a moment. Finding a meme.","Pressing A to continue.","Loading wit.exe.","Pre-heating the servers.","Calibrate flux capacitor.","Channeling the Force.","Aligning the stars.","The truth is in the code.","Don't panic.","Blowing on the cartridge.","Doing a barrel roll!","Respawning in 3... 2... 1...","The cake is a lie.","Fiddling with character settings.","Finding a suitable pun.","Distracting with wit.","Almost ready.","Hamsters on speed today.","Patting Cloudy on the head.","Rickrolling the logs.","Slapping the code.","Got a good feeling about this.","Poking the prompt.","Researching latest memes.","Making it more witty.","Thinking... hmmm.","Fish with no eyes? Fsh.","Broken pencil? Pointless.","Percussive maintenance applied.","USB orientation: 3rd try's the charm.","Rust rewrite in 3... 2...","Exiting Vim... someday.","Spinning the hamster wheel.","Not a bug. Unplanned feature.","Engage.","I'll be back.","Machine spirit consulted.","Letting the thoughts marinate.","Orb pondered.","Thoughtful gaze engaged.","Charging the laser...","Making it go beep.","Buffering...","Quantum particles entangled.","Polishing the chrome.","Entertained yet?","Gremlins summoned.","Dial-up tone finished.","Humor meter recalibrated.","Cat on keyboard. Sending help.","Enhancing...","Turn it off and on again.","Constructing pylons.","HypnoDrones released.","Pushing the button."];var Or=[{name:"Cyan Cyberpunk",text:"cyan",textMuted:"#4da6b8",textDim:"#2d6d7a",textInverted:"black",border:"cyan",borderMuted:"#1a5966",borderDim:"#0f3840",bg:void 0,cardBg:"#061e24",highlightBg:"#092b33",activeBg:"#0e3e4a",inputBg:"#092b33",inputBorder:"#092b33",inputText:"cyan",inputPlaceholder:"#2d6d7a",inputPrompt:"cyan",codeBg:"#020d10",codeBorder:"#1a5966",userMsgBg:"#092b33",userMsgBorder:"#092b33",userMsgText:"cyan",diffRemovalBg:"#3a0c1a",diffAdditionBg:"#0c3a32",diffRemovalText:"#ff4d88",diffAdditionText:"#00ffaa",diffRemovalHighlightColor:"#ff1a66",diffRemovalHighlightBg:"#590022",diffAdditionHighlightColor:"#00ffcc",diffAdditionHighlightBg:"#00593b",diffRemovalNum:"#ff4d88",diffAdditionNum:"#00ffaa",diffRemovalPrefix:"#ff1a66",diffAdditionPrefix:"#00ffcc",primary:"cyan",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"cyan",statusOff:"#2d6d7a",logoTextAnsi:"\x1B[1;36m",logoBodyAnsi:"\x1B[36m",logoMutedAnsi:"\x1B[90m",logoGradient:["#00ffff","#0088ff"]},{name:"Magenta Vaporwave",text:"magenta",textMuted:"#c451d6",textDim:"#7d2b8a",textInverted:"black",border:"magenta",borderMuted:"#5e1b69",borderDim:"#3b0f42",bg:void 0,cardBg:"#240729",highlightBg:"#310938",activeBg:"#470e52",inputBg:"#310938",inputBorder:"#310938",inputText:"magenta",inputPlaceholder:"#7d2b8a",inputPrompt:"magenta",codeBg:"#100312",codeBorder:"#5e1b69",userMsgBg:"#310938",userMsgBorder:"#310938",userMsgText:"magenta",diffRemovalBg:"#3a0c20",diffAdditionBg:"#200c3a",diffRemovalText:"#ff4d94",diffAdditionText:"#aa4dff",diffRemovalHighlightColor:"#ff1a75",diffRemovalHighlightBg:"#59002b",diffAdditionHighlightColor:"#bb66ff",diffAdditionHighlightBg:"#3b0059",diffRemovalNum:"#ff4d94",diffAdditionNum:"#aa4dff",diffRemovalPrefix:"#ff1a75",diffAdditionPrefix:"#bb66ff",primary:"magenta",secondary:"cyan",accent:"purple",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"magenta",statusOff:"#7d2b8a",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ff00ff","#8800ff"]},{name:"Glitch Matrix",text:"#00ff41",textMuted:"#00b32d",textDim:"#00661a",textInverted:"black",border:"#00ff41",borderMuted:"#008020",borderDim:"#004d13",bg:void 0,cardBg:"#0d1f0d",highlightBg:"#122912",activeBg:"#1c3e1c",inputBg:"#122912",inputBorder:"#122912",inputText:"#00ff41",inputPlaceholder:"#00b32d",inputPrompt:"#ffff00",codeBg:"#040a04",codeBorder:"#008020",userMsgBg:"#122912",userMsgBorder:"#122912",userMsgText:"#00ff41",diffRemovalBg:"#3a001a",diffAdditionBg:"#003a10",diffRemovalText:"#ff0055",diffAdditionText:"#00ff66",diffRemovalHighlightColor:"#ff0033",diffRemovalHighlightBg:"#59001b",diffAdditionHighlightColor:"#33ff88",diffAdditionHighlightBg:"#005918",diffRemovalNum:"#ff0055",diffAdditionNum:"#00ff66",diffRemovalPrefix:"#ff0033",diffAdditionPrefix:"#33ff88",primary:"#00ff41",secondary:"yellow",accent:"cyan",success:"#00ff41",warning:"yellow",danger:"red",info:"cyan",statusOn:"#00ff41",statusOff:"#00661a",logoTextAnsi:"\x1B[1;32m",logoBodyAnsi:"\x1B[32m",logoMutedAnsi:"\x1B[90m",logoGradient:["#00ff41","#ffff00"]},{name:"Warm Sunset",text:"#ffaa55",textMuted:"#cc8844",textDim:"#885522",textInverted:"black",border:"#ff9933",borderMuted:"#aa6622",borderDim:"#663311",bg:void 0,cardBg:"#24180f",highlightBg:"#2e1e12",activeBg:"#422c1b",inputBg:"#2e1e12",inputBorder:"#2e1e12",inputText:"#ffaa55",inputPlaceholder:"#885522",inputPrompt:"#ff7733",codeBg:"#120c08",codeBorder:"#aa6622",userMsgBg:"#2e1e12",userMsgBorder:"#2e1e12",userMsgText:"#ffaa55",diffRemovalBg:"#3d120c",diffAdditionBg:"#3a2e0c",diffRemovalText:"#ff5544",diffAdditionText:"#ffcc33",diffRemovalHighlightColor:"#ff3322",diffRemovalHighlightBg:"#591108",diffAdditionHighlightColor:"#ffee44",diffAdditionHighlightBg:"#594400",diffRemovalNum:"#ff5544",diffAdditionNum:"#ffcc33",diffRemovalPrefix:"#ff3322",diffAdditionPrefix:"#ffee44",primary:"#ffaa55",secondary:"#ff7733",accent:"magenta",success:"#ffcc33",warning:"#ff7733",danger:"#ff3322",info:"#ffaa55",statusOn:"#ffaa55",statusOff:"#885522",logoTextAnsi:"\x1B[1;33m",logoBodyAnsi:"\x1B[33m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ff9933","#ff0055"]},{name:"Sakura Blossom",text:"#ffc0e0",textMuted:"#d98cb3",textDim:"#804d66",textInverted:"black",border:"#ff99cc",borderMuted:"#aa4d7a",borderDim:"#662647",bg:void 0,cardBg:"#291320",highlightBg:"#331826",activeBg:"#472235",inputBg:"#331826",inputBorder:"#331826",inputText:"#ffc0e0",inputPlaceholder:"#804d66",inputPrompt:"#ff99cc",codeBg:"#140a10",codeBorder:"#aa4d7a",userMsgBg:"#331826",userMsgBorder:"#331826",userMsgText:"#ffc0e0",diffRemovalBg:"#3e0c1b",diffAdditionBg:"#1b3e2b",diffRemovalText:"#ff6699",diffAdditionText:"#66ffb3",diffRemovalHighlightColor:"#ff3377",diffRemovalHighlightBg:"#590022",diffAdditionHighlightColor:"#33ff99",diffAdditionHighlightBg:"#00592e",diffRemovalNum:"#ff6699",diffAdditionNum:"#66ffb3",diffRemovalPrefix:"#ff3377",diffAdditionPrefix:"#33ff99",primary:"#ffc0e0",secondary:"#ff99cc",accent:"magenta",success:"#66ffb3",warning:"yellow",danger:"#ff3377",info:"#ff99cc",statusOn:"#ffc0e0",statusOff:"#804d66",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ffb3d9","#ff3399"]},{name:"Radioactive Slime",text:"#ccff00",textMuted:"#99cc00",textDim:"#669900",textInverted:"#0a0f00",border:"#ccff00",borderMuted:"#99cc00",borderDim:"#669900",bg:void 0,cardBg:"#0f1400",highlightBg:"#1a2400",activeBg:"#2a3b00",inputBg:"#1a2400",inputBorder:"#1a2400",inputText:"#ccff00",inputPlaceholder:"#669900",inputPrompt:"#cc00ff",codeBg:"#050a00",codeBorder:"#99cc00",userMsgBg:"#1a2400",userMsgBorder:"#1a2400",userMsgText:"#ccff00",diffRemovalBg:"#2a0033",diffAdditionBg:"#0f3300",diffRemovalText:"#ff00cc",diffAdditionText:"#00ff33",diffRemovalHighlightColor:"#ff33cc",diffRemovalHighlightBg:"#4d0066",diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:"#1a6600",diffRemovalNum:"#ff00cc",diffAdditionNum:"#00ff33",diffRemovalPrefix:"#ff33cc",diffAdditionPrefix:"#33ff66",primary:"#ccff00",secondary:"#cc00ff",accent:"#ff00cc",success:"#00ff33",warning:"#ffcc00",danger:"#ff0033",info:"#00ccff",statusOn:"#ccff00",statusOff:"#669900",logoTextAnsi:"\x1B[1;38;5;190m",logoBodyAnsi:"\x1B[38;5;190m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ccff00","#cc00ff"]},{name:"Cosmic Void",text:"#f0f8ff",textMuted:"#a6aeb5",textDim:"#5e656e",textInverted:"#010103",border:"#f0f8ff",borderMuted:"#a6aeb5",borderDim:"#5e656e",bg:void 0,cardBg:"#05030d",highlightBg:"#0b081a",activeBg:"#171133",inputBg:"#0b081a",inputBorder:"#0b081a",inputText:"#f0f8ff",inputPlaceholder:"#5e656e",inputPrompt:"#ff007f",codeBg:"#020108",codeBorder:"#a6aeb5",userMsgBg:"#0b081a",userMsgBorder:"#0b081a",userMsgText:"#f0f8ff",diffRemovalBg:"#2e0a29",diffAdditionBg:"#091c33",diffRemovalText:"#ff33a6",diffAdditionText:"#33d6ff",diffRemovalHighlightColor:"#ff66c2",diffRemovalHighlightBg:"#5c1452",diffAdditionHighlightColor:"#66e0ff",diffAdditionHighlightBg:"#123866",diffRemovalNum:"#ff33a6",diffAdditionNum:"#33d6ff",diffRemovalPrefix:"#ff66c2",diffAdditionPrefix:"#66e0ff",primary:"#f0f8ff",secondary:"#ff007f",accent:"#9d00ff",success:"#33d6ff",warning:"#ffcc00",danger:"#ff0040",info:"#9d00ff",statusOn:"#f0f8ff",statusOff:"#5e656e",logoTextAnsi:"\x1B[1;38;5;231m",logoBodyAnsi:"\x1B[38;5;231m",logoMutedAnsi:"\x1B[38;5;240m",logoGradient:["#ffffff","#9d00ff"]},{name:"Magma Eruption",text:"#ff4d00",textMuted:"#cc3d00",textDim:"#802600",textInverted:"#0d0300",border:"#ff4d00",borderMuted:"#cc3d00",borderDim:"#802600",bg:void 0,cardBg:"#1a0600",highlightBg:"#260a00",activeBg:"#401100",inputBg:"#260a00",inputBorder:"#260a00",inputText:"#ff4d00",inputPlaceholder:"#802600",inputPrompt:"#ffcc00",codeBg:"#080200",codeBorder:"#cc3d00",userMsgBg:"#260a00",userMsgBorder:"#260a00",userMsgText:"#ff4d00",diffRemovalBg:"#2e0a0a",diffAdditionBg:"#1f1400",diffRemovalText:"#ff3333",diffAdditionText:"#ffaa00",diffRemovalHighlightColor:"#ff6666",diffRemovalHighlightBg:"#5c1414",diffAdditionHighlightColor:"#ffcc33",diffAdditionHighlightBg:"#3d2900",diffRemovalNum:"#ff3333",diffAdditionNum:"#ffaa00",diffRemovalPrefix:"#ff6666",diffAdditionPrefix:"#ffcc33",primary:"#ff4d00",secondary:"#ffcc00",accent:"#ff0040",success:"#ffaa00",warning:"#ffff00",danger:"#ff0000",info:"#ff8800",statusOn:"#ff4d00",statusOff:"#802600",logoTextAnsi:"\x1B[1;38;5;202m",logoBodyAnsi:"\x1B[38;5;202m",logoMutedAnsi:"\x1B[38;5;236m",logoGradient:["#ff4d00","#ff0000"]}],bo={Dark:{id:"Dark",name:"Dark (Default)",text:"white",textMuted:"gray",textDim:"grey",textInverted:"black",textExclusive:"#B5B8D9",textMutedExclusive:"#D4DEE7",border:"white",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:"#1e1e1e",highlightBg:"#2a2a2a",activeBg:"#3a3a3a",inputBg:"#555555",inputBorder:"#555555",inputText:"white",inputPlaceholder:"#cccccc",inputPrompt:"white",codeBg:"#1a1a1a",codeBorder:"#444444",userMsgBg:"#444444",userMsgBorder:"#444444",userMsgText:"white",diffRemovalBg:"#250808",diffAdditionBg:"#072410",diffRemovalText:"#885555",diffAdditionText:"#558866",diffRemovalHighlightColor:"#ff3333",diffRemovalHighlightBg:"#5a1818",diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:"#185a25",diffRemovalNum:"#d96868",diffAdditionNum:"#68d98c",diffRemovalPrefix:"#ff4d4d",diffAdditionPrefix:"#4dff88",primary:"white",secondary:"cyan",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"white",statusOff:"gray",logoTextAnsi:"\x1B[1;37m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#0077ff","#ff00ff"]},Light:{id:"Light",name:"Light",text:"black",textMuted:"gray",textDim:"grey",textInverted:"white",border:"black",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:"#e5e5e5",highlightBg:"#d4d4d4",activeBg:"#c0c0c0",inputBg:"#d0d0d0",inputBorder:"#d0d0d0",inputText:"black",inputPlaceholder:"#555555",inputPrompt:"black",codeBg:"#e8e8e8",codeBorder:"#b0b0b0",userMsgBg:"#d0d0d0",userMsgBorder:"#d0d0d0",userMsgText:"black",diffRemovalBg:"#fce8e8",diffAdditionBg:"#e6f9e6",diffRemovalText:"#661111",diffAdditionText:"#115511",diffRemovalHighlightColor:"#440000",diffRemovalHighlightBg:"#f8b4b4",diffAdditionHighlightColor:"#003300",diffAdditionHighlightBg:"#a6ebad",diffRemovalNum:"#c02020",diffAdditionNum:"#188028",diffRemovalPrefix:"#d01010",diffAdditionPrefix:"#109020",primary:"black",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"black",statusOff:"gray",logoTextAnsi:"\x1B[1;30m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#0077ff","#ff00ff"]},"GitHub Dark":{id:"GitHub Dark",name:"GitHub Dark",text:"#c9d1d9",textMuted:"#8b949e",textDim:"#6e7681",textInverted:"#0d1117",border:"#30363d",borderMuted:"#30363d",borderDim:"#21262d",bg:void 0,cardBg:"#161b22",highlightBg:"#21262d",activeBg:"#30363d",inputBg:"#21262d",inputBorder:"#21262d",inputText:"#c9d1d9",inputPlaceholder:"#8b949e",inputPrompt:"#58a6ff",codeBg:"#0d1117",codeBorder:"#30363d",userMsgBg:"#21262d",userMsgBorder:"#21262d",userMsgText:"#c9d1d9",diffRemovalBg:"#3c1e1e",diffAdditionBg:"#11381e",diffRemovalText:"#f85149",diffAdditionText:"#3fb950",diffRemovalHighlightColor:"#ff7b72",diffRemovalHighlightBg:"#701c1c",diffAdditionHighlightColor:"#56d364",diffAdditionHighlightBg:"#116329",diffRemovalNum:"#f85149",diffAdditionNum:"#3fb950",diffRemovalPrefix:"#f85149",diffAdditionPrefix:"#3fb950",primary:"#c9d1d9",secondary:"#58a6ff",accent:"#bc8cff",success:"#3fb950",warning:"#d29922",danger:"#f85149",info:"#58a6ff",statusOn:"#58a6ff",statusOff:"#8b949e",logoTextAnsi:"\x1B[1;36m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#2ea043","#56d364"]},"GitHub Light":{id:"GitHub Light",name:"GitHub Light",text:"#24292f",textMuted:"#57606a",textDim:"#6e7781",textInverted:"#ffffff",border:"#d0d7de",borderMuted:"#d0d7de",borderDim:"#e1e4e8",bg:void 0,cardBg:"#f6f8fa",highlightBg:"#eaeef2",activeBg:"#d0d7de",inputBg:"#eaeef2",inputBorder:"#eaeef2",inputText:"#24292f",inputPlaceholder:"#57606a",inputPrompt:"#0969da",codeBg:"#ffffff",codeBorder:"#d0d7de",userMsgBg:"#eaeef2",userMsgBorder:"#eaeef2",userMsgText:"#24292f",diffRemovalBg:"#ffebe9",diffAdditionBg:"#e6ffec",diffRemovalText:"#cf222e",diffAdditionText:"#1a7f37",diffRemovalHighlightColor:"#82071e",diffRemovalHighlightBg:"#ffc1c0",diffAdditionHighlightColor:"#116329",diffAdditionHighlightBg:"#acf2bd",diffRemovalNum:"#cf222e",diffAdditionNum:"#1a7f37",diffRemovalPrefix:"#cf222e",diffAdditionPrefix:"#1a7f37",primary:"#24292f",secondary:"#0969da",accent:"#8250df",success:"#1a7f37",warning:"#9a6700",danger:"#cf222e",info:"#0969da",statusOn:"#0969da",statusOff:"#57606a",logoTextAnsi:"\x1B[1;34m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#1a7f37","#2da44e"]},"Transparent Dark":{id:"Transparent Dark",name:"Transparent Dark",text:"white",textMuted:"gray",textDim:"grey",textInverted:"black",border:"gray",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:void 0,highlightBg:"#2a2a2a",activeBg:"#3a3a3a",inputBg:"#555555",inputBorder:"#555555",inputText:"white",inputPlaceholder:"#cccccc",inputPrompt:"white",codeBg:void 0,codeBorder:"gray",userMsgBg:"#555555",userMsgBorder:"#555555",userMsgText:"white",diffRemovalBg:void 0,diffAdditionBg:void 0,diffRemovalText:"#ff6666",diffAdditionText:"#66ff66",diffRemovalHighlightColor:"#ff3333",diffRemovalHighlightBg:void 0,diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:void 0,diffRemovalNum:"#ff6666",diffAdditionNum:"#66ff66",diffRemovalPrefix:"#ff4d4d",diffAdditionPrefix:"#4dff88",primary:"white",secondary:"cyan",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"white",statusOff:"gray",logoTextAnsi:"\x1B[1;37m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#0077ff","#ff00ff"]},"Transparent Light":{id:"Transparent Light",name:"Transparent Light",text:"black",textMuted:"gray",textDim:"grey",textInverted:"white",border:"gray",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:void 0,highlightBg:"#d4d4d4",activeBg:"#c0c0c0",inputBg:"#d0d0d0",inputBorder:"#d0d0d0",inputText:"black",inputPlaceholder:"#555555",inputPrompt:"black",codeBg:void 0,codeBorder:"gray",userMsgBg:"#d0d0d0",userMsgBorder:"#d0d0d0",userMsgText:"black",diffRemovalBg:void 0,diffAdditionBg:void 0,diffRemovalText:"#c02020",diffAdditionText:"#188028",diffRemovalHighlightColor:"#800000",diffRemovalHighlightBg:void 0,diffAdditionHighlightColor:"#004000",diffAdditionHighlightBg:void 0,diffRemovalNum:"#c02020",diffAdditionNum:"#188028",diffRemovalPrefix:"#d01010",diffAdditionPrefix:"#109020",primary:"black",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"black",statusOff:"gray",logoTextAnsi:"\x1B[1;30m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#0077ff","#ff00ff"]},"Synthwave 84":{id:"Synthwave 84",name:"Synthwave 84",text:"#fdfdfd",textMuted:"#a08eb7",textDim:"#705c8a",textInverted:"#1a1025",textExclusive:"#e3dcf0",textMutedExclusive:"#b9abc9",border:"#fc28a8",borderMuted:"#a21568",borderDim:"#5c0a3a",bg:void 0,cardBg:"#261b38",highlightBg:"#35254d",activeBg:"#4c3570",inputBg:"#35254d",inputBorder:"#35254d",inputText:"#fdfdfd",inputPlaceholder:"#a08eb7",inputPrompt:"#03e8fc",codeBg:"#1e142b",codeBorder:"#a21568",userMsgBg:"#35254d",userMsgBorder:"#35254d",userMsgText:"#fdfdfd",diffRemovalBg:"#471434",diffAdditionBg:"#144743",diffRemovalText:"#ff4081",diffAdditionText:"#00e5ff",diffRemovalHighlightColor:"#ff79a1",diffRemovalHighlightBg:"#6b1e4e",diffAdditionHighlightColor:"#66f5ff",diffAdditionHighlightBg:"#1e6b65",diffRemovalNum:"#ff4081",diffAdditionNum:"#00e5ff",diffRemovalPrefix:"#ff79a1",diffAdditionPrefix:"#66f5ff",primary:"#fdfdfd",secondary:"#03e8fc",accent:"#fc28a8",success:"#00e5ff",warning:"#ffc107",danger:"#ff4081",info:"#b388ff",statusOn:"#03e8fc",statusOff:"#a08eb7",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#fc28a8","#03e8fc"]},"Forest Sprite":{id:"Forest Sprite",name:"Forest Sprite",text:"#d6e6d1",textMuted:"#95b38d",textDim:"#628059",textInverted:"#161c14",textExclusive:"#eaf2e8",textMutedExclusive:"#a9c7a2",border:"#74a862",borderMuted:"#477038",borderDim:"#2b4720",bg:void 0,cardBg:"#1f291c",highlightBg:"#2a3826",activeBg:"#3a4d35",inputBg:"#2a3826",inputBorder:"#2a3826",inputText:"#d6e6d1",inputPlaceholder:"#95b38d",inputPrompt:"#8feb73",codeBg:"#161e14",codeBorder:"#477038",userMsgBg:"#2a3826",userMsgBorder:"#2a3826",userMsgText:"#d6e6d1",diffRemovalBg:"#3b231c",diffAdditionBg:"#203b1c",diffRemovalText:"#db6242",diffAdditionText:"#59cc3f",diffRemovalHighlightColor:"#f0896c",diffRemovalHighlightBg:"#5c362a",diffAdditionHighlightColor:"#80e368",diffAdditionHighlightBg:"#305929",diffRemovalNum:"#db6242",diffAdditionNum:"#59cc3f",diffRemovalPrefix:"#f0896c",diffAdditionPrefix:"#80e368",primary:"#d6e6d1",secondary:"#8feb73",accent:"#e69835",success:"#59cc3f",warning:"#e69835",danger:"#db6242",info:"#73b4eb",statusOn:"#8feb73",statusOff:"#95b38d",logoTextAnsi:"\x1B[1;32m",logoBodyAnsi:"\x1B[32m",logoMutedAnsi:"\x1B[90m",logoGradient:["#8feb73","#e69835"]}};var Vo=null;var Lr=(e="Dark")=>{let t;e==="Mystery"||e==="Chaos"?(Vo||(Vo=Or[Math.floor(Math.random()*Or.length)]),t={...Vo,id:"Mystery"}):(Vo=null,bo[e]?t=bo[e]:e==="GitHub"?t=bo["GitHub Dark"]:e==="Transparent"?t=bo["Transparent Dark"]:t=bo.Dark);let n=t.codeText||t.secondary||t.info||t.logoGradient&&t.logoGradient[0]||"cyan";return{...t,codeText:n}};var Ca=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",yc=(e=2)=>{let t=Ca();return t==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)},xc=(e="...",t="Loading...",n="Dark")=>{let s=Ks[Math.floor(Math.random()*Ks.length)],o=Lr(n),c=o.logoTextAnsi,f=o.logoBodyAnsi,l=o.logoMutedAnsi,k="\x1B[0m",p=[" \u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2588\u2588\u2588\u2591 "," \u2588\u2588\u2588\u2591 "," \u2588\u2588\u2588\u2591 "," \u2591\u2591\u2591 "],g=o.logoGradient||["#0077ff","#ff00ff"],T=Ea(g).multiline(p.join(`
565
+ ${e}`:""}`.trim();var gr=()=>import("./web_search-2PFIJKIL.js").then(e=>e.web_search),hr=()=>import("./web_scrape-BHSQTMX4.js").then(e=>e.web_scrape),mr=()=>import("./memory-SRDCQNML.js").then(e=>e.memory),pr=()=>import("./chat-7T6MVHC3.js").then(e=>e.chat),yr=()=>import("./view_file-2THVIMD6.js").then(e=>e.view_file),xr=()=>import("./write_file-V6HKMWFB.js").then(e=>e.write_file),br=()=>import("./update_file-WTXXQ4RB.js").then(e=>e.update_file),wr=()=>import("./exec_command-CY42M4FP.js").then(e=>e.exec_command),kr=()=>import("./read_folder-EI2CNHNS.js").then(e=>e.read_folder),Ws=()=>import("./ask_user-K2DLZF6H.js").then(e=>e.ask_user),Tr=()=>import("./write_pdf-XDDKM7V5.js").then(e=>e.write_pdf),Sr=()=>import("./write_docx-I7T3575T.js").then(e=>e.write_docx),Uo=()=>import("./search_keyword-CSRQFPHQ.js").then(e=>e.search_keyword),_r=()=>import("./generate_image-HVWLRINC.js").then(e=>e.generate_image),Wo=()=>import("./saveSummary-VKGBD4CG.js").then(e=>e.saveSummary),mo=()=>import("./addMemScore-PWP7GFSP.js").then(e=>e.addMemScore),Ar=()=>import("./file_map-KS6Y7BP3.js").then(e=>e.file_map),Ho=()=>import("./todo-VG2CVRUI.js").then(e=>e.todo),Er=()=>import("./invokeSync-BPIG7EIY.js").then(e=>e.invokeSync),Sa=()=>import("./invoke-XPZ4MUGJ.js").then(e=>e.invoke),Cr=()=>import("./getProgress-A2TW34Q7.js").then(e=>e.getProgress),_a=()=>import("./cancel-7IMADALP.js").then(e=>e.cancel),Rr=()=>import("./emergency_rollback-DXN5WNPR.js").then(e=>e.emergency_rollback),po=()=>import("./awaitSubagent-JTUSJDKD.js").then(e=>e.awaitSubagent),yo=()=>import("./answerSubagent-JUVFNLE5.js").then(e=>e.answerSubagent),Go=()=>import("./steerSubagent-L2JVT4QN.js").then(e=>e.steerSubagent),jo=()=>import("./computer_action-7U3W3F6L.js").then(e=>e.computer_action),vr=()=>import("./click-5ZKBFZ4N.js").then(e=>e.click),Mr=()=>import("./drag-YHHKJGL6.js").then(e=>e.drag),Ir=()=>import("./scroll-C4Z57VQS.js").then(e=>e.scroll),Hs=()=>import("./keyboard_typing-QL3DF67Z.js").then(e=>e.keyboard_typing),Gs=()=>import("./key_press-ZZNA3PF3.js").then(e=>e.key_press),js=()=>import("./recapture_screen-5FKLOHJL.js").then(e=>e.recapture_screen),Ko=()=>import("./find_file-A6NYLQJS.js").then(e=>e.find_file),Aa={web_search:gr,web_scrape:hr,memory:mr,chat:pr,view_file:yr,write_file:xr,update_file:br,exec_command:wr,read_folder:kr,write_pdf:Tr,write_docx:Sr,search_keyword:Uo,generate_image:_r,saveSummary:Wo,addMemScore:mo,file_map:Ar,todo:Ho,Todo:Ho,goal:Ho,Goal:Ho,invokeSync:Er,invoke:Sa,getProgress:Cr,cancel:_a,awaitSubagent:po,answerSubagent:yo,steerSubagent:Go,computer_action:jo,computer_use:jo,ComputerAction:jo,ComputerUse:jo,click:vr,Click:vr,drag:Mr,Drag:Mr,scroll:Ir,Scroll:Ir,keyboard_typing:Hs,KeyboardTyping:Hs,keyboardtyping:Hs,key_press:Gs,KeyPress:Gs,keypress:Gs,recapture_screen:js,RecaptureScreen:js,recapturescreen:js,invoke_sync:Er,get_progress:Cr,await_subagent:po,answer_subagent:yo,steer_subagent:Go,steer:Go,Steer:Go,ask:Ws,Ask:Ws,AskUser:Ws,WebSearch:gr,WebScrape:hr,ReadFile:yr,ReadFolder:kr,WriteFile:xr,PatchFile:br,WritePDF:Tr,WriteDoc:Sr,Run:wr,SearchKeyword:Uo,CodeSearch:Uo,code_search:Uo,Memory:mr,Chat:pr,GenerateImage:_r,saveSumary:Wo,SaveSummary:Wo,SaveSumary:Wo,add_mem_score:mo,AddMemScore:mo,addMemoryScore:mo,AddMemoryScore:mo,FileMap:Ar,answer:yo,Answer:yo,AnswerSubagent:yo,await:po,Await:po,AwaitSubagent:po,EmergencyRollback:Rr,emergency_rollback:Rr,find_file:Ko,findFile:Ko,FindFile:Ko,findfile:Ko},xo=async(e,t,n={})=>{let s=n.mode?n.mode.toLowerCase():"flux",o=e.toLowerCase(),f=["memory","chat","savesummary","addmemscore","add_mem_score","ask","web_search","web_scrape","await"].some(g=>o.includes(g))||o==="ask",k=["click","drag","scroll","keyboardtyping","keyboard_typing","keypress","key_press","recapturescreen","recapture_screen","computer"].some(g=>o.includes(g));if(!f){if(s==="flow"){if(!(o.includes("write_pdf")||o.includes("write_docx")||o.includes("generate_image")))return`ERROR: Action [${e}] is a Workspace Tool and NOT available in Flow mode. Tell user to switch (\`/mode flux\`) to use this tool.`}else if(s==="icu"){if(!k)return`ERROR: Action [${e}] is not available in Computer Use mode. ICU mode only supports Computer Use tools (Click, Drag, Scroll, KeyboardTyping, KeyPress, RecaptureScreen).`}else if(o.includes("write_pdf")||o.includes("write_docx")||o.includes("generate_image"))return`ERROR: Action [${e}] is not available in ${n.mode||"Flux"} mode. Tell user to switch (\`/mode flow\`) for document generation.`}let p=Aa[e];if(!p){let g=["ReadFile","ReadFolder","FindFile","PatchFile","WriteFile","CodeSearch","Run","Goal","AskUser","WebSearch","WebScrape","WritePDF","WriteDoc","Click","Drag","Scroll","KeyboardTyping","KeyPress","RecaptureScreen","Invoke","InvokeSync","Await","GetProgress","Steer","Cancel","EmergencyRollback","Chat","Memory"],T={read:"ReadFile",view:"ReadFile",viewfile:"ReadFile",write:"WriteFile",edit:"PatchFile",patch:"PatchFile",update:"PatchFile",updatefile:"PatchFile",exec:"Run",command:"Run",bash:"Run",shell:"Run",powershell:"Run",search:"CodeSearch",grep:"CodeSearch",find:"FindFile",findfile:"FindFile",searchkeyword:"CodeSearch",folder:"ReadFolder",ls:"ReadFolder",dir:"ReadFolder",list:"ReadFolder",ask:"AskUser",question:"AskUser",pdf:"WritePDF",docx:"WriteDoc",doc:"WriteDoc",word:"WriteDoc",screenshot:"RecaptureScreen",screen:"RecaptureScreen",recapture:"RecaptureScreen",type:"KeyboardTyping",typing:"KeyboardTyping",keyboard:"KeyboardTyping",press:"KeyPress",key:"KeyPress",todo:"Goal",task:"Goal",subagent:"Invoke",agent:"Invoke"},m=o.replace(/[^a-z0-9]/g,""),i=T[m]||null;if(!i){let w=0,I=A=>{let $=new Set;for(let C=0;C<A.length-1;C++)$.add(A.slice(C,C+2));return $},h=I(m);for(let A of g){let $=A.toLowerCase().replace(/[^a-z0-9]/g,"");if(m===$){i=A;break}let C=0;($.includes(m)||m.includes($))&&(C+=.6);let x=I($),_=0;for(let y of h)x.has(y)&&_++;let M=2*_/(h.size+x.size||1);C=Math.max(C,M),C>w&&C>=.35&&(w=C,i=A)}}let u=i?` Do you mean '${i}'?`:"";return`ERROR: Action [${e}] not found in registry.${u}`}try{return await(await p())(t,n)}catch(g){let T=g instanceof Error?g.message:String(g);return`ERROR: Execution failed for [${e}]: ${T}`}};import ie from"path";import Ue from"fs";import Ea from"gradient-string";var Ks=["I have a regex for your problems.","Your terminal, my kingdom.","Blowing on the cartridge helps. Probably.","Don't panic. I have the towel.","Logic is the start of wisdom.","Try to exit Vim? Good luck.","I speak fluent Terminal.","The cake is a lie. This code is not.","I have no bugs, just surprise features.","Rewriting in Rust... just for fun.","Coffee in, clean commits out.","The magic smoke stays inside today.","A semicolon short of a miracle.","One does not simply code without a bug.","Keep it simple. Keep it terminal.","Regex: now you have two problems.","I dream in binary.","Root access or bust.","Wait for the dial-up tone. Just kidding.","I take the 'labor' out of collab.","My other process is a TARDIS.","Calculated response: 42.","Ponder the orb. Ponder the code.","Less talk, more flow.","Elegance in every byte.","Build something the world is not ready for.","Your wishes, my tool calls.","I act in Flux. I think in Flow.","Syntax error in the universe. Please fix.","Your project, my obsession.","I am not a bot, I am an architect.","Digital spirits consulted. They say: Ship it.","Reticulate splines. Engage humor.","Code like poetry. Run like water.","Minimalism is the ultimate flex.","The truth is in the logs.","Follow the white rabbit.","There is no spoon. Only code.","Binary is the only language I trust.","I have a good feeling about this.","Pew pew! Lasers charged.","Divide by zero? Not today.","Search for the correct USB orientation...","I've got a fever, and the only cure is more code.","The code gremlins are on our side.","My favorite command? Yours.","Stay hungry. Stay active.","Momentum is your best friend.","Lead the flow. Don't chase it.","A fresh batch of bytes. Hot and ready.","I orchestrate the ones and zeros.","Smart enough to help. Humble enough to ask.","Think twice. Code once.","Pure intent. Pure execution.","Small steps. Massive impact.","Your terminal is a canvas.","Efficiency is my second name.","I have seen things you people wouldn't believe.","Let the thoughts marinate.","The best feature? The one you don't need.","Precision is the only perfection.","Stay focused. Stay terminal.","Silence is the best debugger.","Erase the debt. Commit the code.","Velocity meets stability.","Ship it. Improve it. Repeat.","Build tomorrow, right now.","Turn logic into reality.","The best way to predict the future is to build it.","Break barriers, not builds.","Fuel the next breakthrough.","Momentum is key.","Terminal vibes only.","Your digital co-pilot is ready.","Partner in code. Partner in crime.","I speak in semicolons.","Ready for the next great idea.","Just a moment. In the zone.","Polishing the algorithms. Hold tight.","Craft a masterpiece today.","Debug the universe. Start here.","Warp speed engaged. Almost.","The cake is not a lie. It's just loading.","Finish the Kessel Run in 12 parsecs.","Do a barrel roll!","Waiting for the respawn.","Press Start to continue.","Herding digital cats... done.","The hamsters are fast today.","Tasting the snozberries.","I go for speed. I go for flow.","Real life or just fantasy?","Poking the bear... gently.","Ensure the magic smoke stays inside.","Try turning it off and on again.","Construct additional pylons.","New line? Ctrl+J is your friend.","Release the HypnoDrones.","Push the button, Frank.","My other loading screen is even funnier.","Pretty sure a cat walked on my keyboard.","Recalibrate the humor-o-meter.","Summon the code gremlins.","I've seen your browser history. Just kidding.","Charge the laser... pew pew!","Dividing by zero... just for a sec.","Looking for an adult supervisor. Found none.","Make it go beep boop.","Buffering... for effect.","Entangle quantum particles... complete.","Polishing the chrome on my algorithms.","Are you not entertained?","Just waiting for the dial-up tone.","Reboot the humor module.","Defragment memories. Check.","Optimizing for ludicrous speed.","Swapping bits. Don't tell the bytes.","Garbage collected. I am back.","Assembling the interwebs.","Converting coffee to logic.","Update syntax for reality.","Rewire the synapses.","Greasin' the cogs.","Engage the improbability drive.","Channel the Force.","Align the stars. Respond now.","The cake is a lie. The prompt is real.","I'm Feeling Lucky.","Shipping awesomeness.","Navigating the slime mold.","Consult digital spirits.","Ask the magic conch shell.","One moment. Optimizing humor.","Shuffling punchlines.","Compiling brilliance.","Summon the cloud of wisdom.","Prepare to dazzle.","Hold tight. Crafting a response.","Tuning the algorithms.","Following the white rabbit... again.","The truth is in here. Somewhere.","Herding cats is my day job.","Distracting you with this phrase.","Almost there. Probably.","Rickrolling my creator. Don't tell.","Slapping the bass.","Is this real life?","Ponder the orb. Type the prompt.","Thoughtful gaze initiated.","Computer's favorite snack? Microchips.","Why Java? Because I don't C#.","Charging the laser... wait for it.","Dividing by zero... just kidding!","Adult supervision not found. Proceed.","Beep boop. I'm a real boy.","Wait for the respawn.","Finish the run. Ship the code.","Fiddling with character creation.","Just a moment. Finding a meme.","Pressing A to continue.","Loading wit.exe.","Pre-heating the servers.","Calibrate flux capacitor.","Channeling the Force.","Aligning the stars.","The truth is in the code.","Don't panic.","Blowing on the cartridge.","Doing a barrel roll!","Respawning in 3... 2... 1...","The cake is a lie.","Fiddling with character settings.","Finding a suitable pun.","Distracting with wit.","Almost ready.","Hamsters on speed today.","Patting Cloudy on the head.","Rickrolling the logs.","Slapping the code.","Got a good feeling about this.","Poking the prompt.","Researching latest memes.","Making it more witty.","Thinking... hmmm.","Fish with no eyes? Fsh.","Broken pencil? Pointless.","Percussive maintenance applied.","USB orientation: 3rd try's the charm.","Rust rewrite in 3... 2...","Exiting Vim... someday.","Spinning the hamster wheel.","Not a bug. Unplanned feature.","Engage.","I'll be back.","Machine spirit consulted.","Letting the thoughts marinate.","Orb pondered.","Thoughtful gaze engaged.","Charging the laser...","Making it go beep.","Buffering...","Quantum particles entangled.","Polishing the chrome.","Entertained yet?","Gremlins summoned.","Dial-up tone finished.","Humor meter recalibrated.","Cat on keyboard. Sending help.","Enhancing...","Turn it off and on again.","Constructing pylons.","HypnoDrones released.","Pushing the button."];var Dr=[{name:"Cyan Cyberpunk",text:"cyan",textMuted:"#4da6b8",textDim:"#2d6d7a",textInverted:"black",border:"cyan",borderMuted:"#1a5966",borderDim:"#0f3840",bg:void 0,cardBg:"#061e24",highlightBg:"#092b33",activeBg:"#0e3e4a",inputBg:"#092b33",inputBorder:"#092b33",inputText:"cyan",inputPlaceholder:"#2d6d7a",inputPrompt:"cyan",codeBg:"#020d10",codeBorder:"#1a5966",userMsgBg:"#092b33",userMsgBorder:"#092b33",userMsgText:"cyan",diffRemovalBg:"#3a0c1a",diffAdditionBg:"#0c3a32",diffRemovalText:"#ff4d88",diffAdditionText:"#00ffaa",diffRemovalHighlightColor:"#ff1a66",diffRemovalHighlightBg:"#590022",diffAdditionHighlightColor:"#00ffcc",diffAdditionHighlightBg:"#00593b",diffRemovalNum:"#ff4d88",diffAdditionNum:"#00ffaa",diffRemovalPrefix:"#ff1a66",diffAdditionPrefix:"#00ffcc",primary:"cyan",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"cyan",statusOff:"#2d6d7a",logoTextAnsi:"\x1B[1;36m",logoBodyAnsi:"\x1B[36m",logoMutedAnsi:"\x1B[90m",logoGradient:["#00ffff","#0088ff"]},{name:"Magenta Vaporwave",text:"magenta",textMuted:"#c451d6",textDim:"#7d2b8a",textInverted:"black",border:"magenta",borderMuted:"#5e1b69",borderDim:"#3b0f42",bg:void 0,cardBg:"#240729",highlightBg:"#310938",activeBg:"#470e52",inputBg:"#310938",inputBorder:"#310938",inputText:"magenta",inputPlaceholder:"#7d2b8a",inputPrompt:"magenta",codeBg:"#100312",codeBorder:"#5e1b69",userMsgBg:"#310938",userMsgBorder:"#310938",userMsgText:"magenta",diffRemovalBg:"#3a0c20",diffAdditionBg:"#200c3a",diffRemovalText:"#ff4d94",diffAdditionText:"#aa4dff",diffRemovalHighlightColor:"#ff1a75",diffRemovalHighlightBg:"#59002b",diffAdditionHighlightColor:"#bb66ff",diffAdditionHighlightBg:"#3b0059",diffRemovalNum:"#ff4d94",diffAdditionNum:"#aa4dff",diffRemovalPrefix:"#ff1a75",diffAdditionPrefix:"#bb66ff",primary:"magenta",secondary:"cyan",accent:"purple",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"magenta",statusOff:"#7d2b8a",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ff00ff","#8800ff"]},{name:"Glitch Matrix",text:"#00ff41",textMuted:"#00b32d",textDim:"#00661a",textInverted:"black",border:"#00ff41",borderMuted:"#008020",borderDim:"#004d13",bg:void 0,cardBg:"#0d1f0d",highlightBg:"#122912",activeBg:"#1c3e1c",inputBg:"#122912",inputBorder:"#122912",inputText:"#00ff41",inputPlaceholder:"#00b32d",inputPrompt:"#ffff00",codeBg:"#040a04",codeBorder:"#008020",userMsgBg:"#122912",userMsgBorder:"#122912",userMsgText:"#00ff41",diffRemovalBg:"#3a001a",diffAdditionBg:"#003a10",diffRemovalText:"#ff0055",diffAdditionText:"#00ff66",diffRemovalHighlightColor:"#ff0033",diffRemovalHighlightBg:"#59001b",diffAdditionHighlightColor:"#33ff88",diffAdditionHighlightBg:"#005918",diffRemovalNum:"#ff0055",diffAdditionNum:"#00ff66",diffRemovalPrefix:"#ff0033",diffAdditionPrefix:"#33ff88",primary:"#00ff41",secondary:"yellow",accent:"cyan",success:"#00ff41",warning:"yellow",danger:"red",info:"cyan",statusOn:"#00ff41",statusOff:"#00661a",logoTextAnsi:"\x1B[1;32m",logoBodyAnsi:"\x1B[32m",logoMutedAnsi:"\x1B[90m",logoGradient:["#00ff41","#ffff00"]},{name:"Warm Sunset",text:"#ffaa55",textMuted:"#cc8844",textDim:"#885522",textInverted:"black",border:"#ff9933",borderMuted:"#aa6622",borderDim:"#663311",bg:void 0,cardBg:"#24180f",highlightBg:"#2e1e12",activeBg:"#422c1b",inputBg:"#2e1e12",inputBorder:"#2e1e12",inputText:"#ffaa55",inputPlaceholder:"#885522",inputPrompt:"#ff7733",codeBg:"#120c08",codeBorder:"#aa6622",userMsgBg:"#2e1e12",userMsgBorder:"#2e1e12",userMsgText:"#ffaa55",diffRemovalBg:"#3d120c",diffAdditionBg:"#3a2e0c",diffRemovalText:"#ff5544",diffAdditionText:"#ffcc33",diffRemovalHighlightColor:"#ff3322",diffRemovalHighlightBg:"#591108",diffAdditionHighlightColor:"#ffee44",diffAdditionHighlightBg:"#594400",diffRemovalNum:"#ff5544",diffAdditionNum:"#ffcc33",diffRemovalPrefix:"#ff3322",diffAdditionPrefix:"#ffee44",primary:"#ffaa55",secondary:"#ff7733",accent:"magenta",success:"#ffcc33",warning:"#ff7733",danger:"#ff3322",info:"#ffaa55",statusOn:"#ffaa55",statusOff:"#885522",logoTextAnsi:"\x1B[1;33m",logoBodyAnsi:"\x1B[33m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ff9933","#ff0055"]},{name:"Sakura Blossom",text:"#ffc0e0",textMuted:"#d98cb3",textDim:"#804d66",textInverted:"black",border:"#ff99cc",borderMuted:"#aa4d7a",borderDim:"#662647",bg:void 0,cardBg:"#291320",highlightBg:"#331826",activeBg:"#472235",inputBg:"#331826",inputBorder:"#331826",inputText:"#ffc0e0",inputPlaceholder:"#804d66",inputPrompt:"#ff99cc",codeBg:"#140a10",codeBorder:"#aa4d7a",userMsgBg:"#331826",userMsgBorder:"#331826",userMsgText:"#ffc0e0",diffRemovalBg:"#3e0c1b",diffAdditionBg:"#1b3e2b",diffRemovalText:"#ff6699",diffAdditionText:"#66ffb3",diffRemovalHighlightColor:"#ff3377",diffRemovalHighlightBg:"#590022",diffAdditionHighlightColor:"#33ff99",diffAdditionHighlightBg:"#00592e",diffRemovalNum:"#ff6699",diffAdditionNum:"#66ffb3",diffRemovalPrefix:"#ff3377",diffAdditionPrefix:"#33ff99",primary:"#ffc0e0",secondary:"#ff99cc",accent:"magenta",success:"#66ffb3",warning:"yellow",danger:"#ff3377",info:"#ff99cc",statusOn:"#ffc0e0",statusOff:"#804d66",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ffb3d9","#ff3399"]},{name:"Radioactive Slime",text:"#ccff00",textMuted:"#99cc00",textDim:"#669900",textInverted:"#0a0f00",border:"#ccff00",borderMuted:"#99cc00",borderDim:"#669900",bg:void 0,cardBg:"#0f1400",highlightBg:"#1a2400",activeBg:"#2a3b00",inputBg:"#1a2400",inputBorder:"#1a2400",inputText:"#ccff00",inputPlaceholder:"#669900",inputPrompt:"#cc00ff",codeBg:"#050a00",codeBorder:"#99cc00",userMsgBg:"#1a2400",userMsgBorder:"#1a2400",userMsgText:"#ccff00",diffRemovalBg:"#2a0033",diffAdditionBg:"#0f3300",diffRemovalText:"#ff00cc",diffAdditionText:"#00ff33",diffRemovalHighlightColor:"#ff33cc",diffRemovalHighlightBg:"#4d0066",diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:"#1a6600",diffRemovalNum:"#ff00cc",diffAdditionNum:"#00ff33",diffRemovalPrefix:"#ff33cc",diffAdditionPrefix:"#33ff66",primary:"#ccff00",secondary:"#cc00ff",accent:"#ff00cc",success:"#00ff33",warning:"#ffcc00",danger:"#ff0033",info:"#00ccff",statusOn:"#ccff00",statusOff:"#669900",logoTextAnsi:"\x1B[1;38;5;190m",logoBodyAnsi:"\x1B[38;5;190m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ccff00","#cc00ff"]},{name:"Cosmic Void",text:"#f0f8ff",textMuted:"#a6aeb5",textDim:"#5e656e",textInverted:"#010103",border:"#f0f8ff",borderMuted:"#a6aeb5",borderDim:"#5e656e",bg:void 0,cardBg:"#05030d",highlightBg:"#0b081a",activeBg:"#171133",inputBg:"#0b081a",inputBorder:"#0b081a",inputText:"#f0f8ff",inputPlaceholder:"#5e656e",inputPrompt:"#ff007f",codeBg:"#020108",codeBorder:"#a6aeb5",userMsgBg:"#0b081a",userMsgBorder:"#0b081a",userMsgText:"#f0f8ff",diffRemovalBg:"#2e0a29",diffAdditionBg:"#091c33",diffRemovalText:"#ff33a6",diffAdditionText:"#33d6ff",diffRemovalHighlightColor:"#ff66c2",diffRemovalHighlightBg:"#5c1452",diffAdditionHighlightColor:"#66e0ff",diffAdditionHighlightBg:"#123866",diffRemovalNum:"#ff33a6",diffAdditionNum:"#33d6ff",diffRemovalPrefix:"#ff66c2",diffAdditionPrefix:"#66e0ff",primary:"#f0f8ff",secondary:"#ff007f",accent:"#9d00ff",success:"#33d6ff",warning:"#ffcc00",danger:"#ff0040",info:"#9d00ff",statusOn:"#f0f8ff",statusOff:"#5e656e",logoTextAnsi:"\x1B[1;38;5;231m",logoBodyAnsi:"\x1B[38;5;231m",logoMutedAnsi:"\x1B[38;5;240m",logoGradient:["#ffffff","#9d00ff"]},{name:"Magma Eruption",text:"#ff4d00",textMuted:"#cc3d00",textDim:"#802600",textInverted:"#0d0300",border:"#ff4d00",borderMuted:"#cc3d00",borderDim:"#802600",bg:void 0,cardBg:"#1a0600",highlightBg:"#260a00",activeBg:"#401100",inputBg:"#260a00",inputBorder:"#260a00",inputText:"#ff4d00",inputPlaceholder:"#802600",inputPrompt:"#ffcc00",codeBg:"#080200",codeBorder:"#cc3d00",userMsgBg:"#260a00",userMsgBorder:"#260a00",userMsgText:"#ff4d00",diffRemovalBg:"#2e0a0a",diffAdditionBg:"#1f1400",diffRemovalText:"#ff3333",diffAdditionText:"#ffaa00",diffRemovalHighlightColor:"#ff6666",diffRemovalHighlightBg:"#5c1414",diffAdditionHighlightColor:"#ffcc33",diffAdditionHighlightBg:"#3d2900",diffRemovalNum:"#ff3333",diffAdditionNum:"#ffaa00",diffRemovalPrefix:"#ff6666",diffAdditionPrefix:"#ffcc33",primary:"#ff4d00",secondary:"#ffcc00",accent:"#ff0040",success:"#ffaa00",warning:"#ffff00",danger:"#ff0000",info:"#ff8800",statusOn:"#ff4d00",statusOff:"#802600",logoTextAnsi:"\x1B[1;38;5;202m",logoBodyAnsi:"\x1B[38;5;202m",logoMutedAnsi:"\x1B[38;5;236m",logoGradient:["#ff4d00","#ff0000"]}],bo={Dark:{id:"Dark",name:"Dark (Default)",text:"white",textMuted:"gray",textDim:"grey",textInverted:"black",textExclusive:"#B5B8D9",textMutedExclusive:"#D4DEE7",border:"white",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:"#1e1e1e",highlightBg:"#2a2a2a",activeBg:"#3a3a3a",inputBg:"#555555",inputBorder:"#555555",inputText:"white",inputPlaceholder:"#cccccc",inputPrompt:"white",codeBg:"#1a1a1a",codeBorder:"#444444",userMsgBg:"#444444",userMsgBorder:"#444444",userMsgText:"white",diffRemovalBg:"#250808",diffAdditionBg:"#072410",diffRemovalText:"#885555",diffAdditionText:"#558866",diffRemovalHighlightColor:"#ff3333",diffRemovalHighlightBg:"#5a1818",diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:"#185a25",diffRemovalNum:"#d96868",diffAdditionNum:"#68d98c",diffRemovalPrefix:"#ff4d4d",diffAdditionPrefix:"#4dff88",primary:"white",secondary:"cyan",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"white",statusOff:"gray",logoTextAnsi:"\x1B[1;37m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#0077ff","#ff00ff"]},Light:{id:"Light",name:"Light",text:"black",textMuted:"gray",textDim:"grey",textInverted:"white",border:"black",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:"#e5e5e5",highlightBg:"#d4d4d4",activeBg:"#c0c0c0",inputBg:"#d0d0d0",inputBorder:"#d0d0d0",inputText:"black",inputPlaceholder:"#555555",inputPrompt:"black",codeBg:"#e8e8e8",codeBorder:"#b0b0b0",userMsgBg:"#d0d0d0",userMsgBorder:"#d0d0d0",userMsgText:"black",diffRemovalBg:"#fce8e8",diffAdditionBg:"#e6f9e6",diffRemovalText:"#661111",diffAdditionText:"#115511",diffRemovalHighlightColor:"#440000",diffRemovalHighlightBg:"#f8b4b4",diffAdditionHighlightColor:"#003300",diffAdditionHighlightBg:"#a6ebad",diffRemovalNum:"#c02020",diffAdditionNum:"#188028",diffRemovalPrefix:"#d01010",diffAdditionPrefix:"#109020",primary:"black",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"black",statusOff:"gray",logoTextAnsi:"\x1B[1;30m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#0077ff","#ff00ff"]},"GitHub Dark":{id:"GitHub Dark",name:"GitHub Dark",text:"#c9d1d9",textMuted:"#8b949e",textDim:"#6e7681",textInverted:"#0d1117",border:"#30363d",borderMuted:"#30363d",borderDim:"#21262d",bg:void 0,cardBg:"#161b22",highlightBg:"#21262d",activeBg:"#30363d",inputBg:"#21262d",inputBorder:"#21262d",inputText:"#c9d1d9",inputPlaceholder:"#8b949e",inputPrompt:"#58a6ff",codeBg:"#0d1117",codeBorder:"#30363d",userMsgBg:"#21262d",userMsgBorder:"#21262d",userMsgText:"#c9d1d9",diffRemovalBg:"#3c1e1e",diffAdditionBg:"#11381e",diffRemovalText:"#f85149",diffAdditionText:"#3fb950",diffRemovalHighlightColor:"#ff7b72",diffRemovalHighlightBg:"#701c1c",diffAdditionHighlightColor:"#56d364",diffAdditionHighlightBg:"#116329",diffRemovalNum:"#f85149",diffAdditionNum:"#3fb950",diffRemovalPrefix:"#f85149",diffAdditionPrefix:"#3fb950",primary:"#c9d1d9",secondary:"#58a6ff",accent:"#bc8cff",success:"#3fb950",warning:"#d29922",danger:"#f85149",info:"#58a6ff",statusOn:"#58a6ff",statusOff:"#8b949e",logoTextAnsi:"\x1B[1;36m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#2ea043","#56d364"]},"GitHub Light":{id:"GitHub Light",name:"GitHub Light",text:"#24292f",textMuted:"#57606a",textDim:"#6e7781",textInverted:"#ffffff",border:"#d0d7de",borderMuted:"#d0d7de",borderDim:"#e1e4e8",bg:void 0,cardBg:"#f6f8fa",highlightBg:"#eaeef2",activeBg:"#d0d7de",inputBg:"#eaeef2",inputBorder:"#eaeef2",inputText:"#24292f",inputPlaceholder:"#57606a",inputPrompt:"#0969da",codeBg:"#ffffff",codeBorder:"#d0d7de",userMsgBg:"#eaeef2",userMsgBorder:"#eaeef2",userMsgText:"#24292f",diffRemovalBg:"#ffebe9",diffAdditionBg:"#e6ffec",diffRemovalText:"#cf222e",diffAdditionText:"#1a7f37",diffRemovalHighlightColor:"#82071e",diffRemovalHighlightBg:"#ffc1c0",diffAdditionHighlightColor:"#116329",diffAdditionHighlightBg:"#acf2bd",diffRemovalNum:"#cf222e",diffAdditionNum:"#1a7f37",diffRemovalPrefix:"#cf222e",diffAdditionPrefix:"#1a7f37",primary:"#24292f",secondary:"#0969da",accent:"#8250df",success:"#1a7f37",warning:"#9a6700",danger:"#cf222e",info:"#0969da",statusOn:"#0969da",statusOff:"#57606a",logoTextAnsi:"\x1B[1;34m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#1a7f37","#2da44e"]},"Transparent Dark":{id:"Transparent Dark",name:"Transparent Dark",text:"white",textMuted:"gray",textDim:"grey",textInverted:"black",border:"gray",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:void 0,highlightBg:"#2a2a2a",activeBg:"#3a3a3a",inputBg:"#555555",inputBorder:"#555555",inputText:"white",inputPlaceholder:"#cccccc",inputPrompt:"white",codeBg:void 0,codeBorder:"gray",userMsgBg:"#555555",userMsgBorder:"#555555",userMsgText:"white",diffRemovalBg:void 0,diffAdditionBg:void 0,diffRemovalText:"#ff6666",diffAdditionText:"#66ff66",diffRemovalHighlightColor:"#ff3333",diffRemovalHighlightBg:void 0,diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:void 0,diffRemovalNum:"#ff6666",diffAdditionNum:"#66ff66",diffRemovalPrefix:"#ff4d4d",diffAdditionPrefix:"#4dff88",primary:"white",secondary:"cyan",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"white",statusOff:"gray",logoTextAnsi:"\x1B[1;37m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#0077ff","#ff00ff"]},"Transparent Light":{id:"Transparent Light",name:"Transparent Light",text:"black",textMuted:"gray",textDim:"grey",textInverted:"white",border:"gray",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:void 0,highlightBg:"#d4d4d4",activeBg:"#c0c0c0",inputBg:"#d0d0d0",inputBorder:"#d0d0d0",inputText:"black",inputPlaceholder:"#555555",inputPrompt:"black",codeBg:void 0,codeBorder:"gray",userMsgBg:"#d0d0d0",userMsgBorder:"#d0d0d0",userMsgText:"black",diffRemovalBg:void 0,diffAdditionBg:void 0,diffRemovalText:"#c02020",diffAdditionText:"#188028",diffRemovalHighlightColor:"#800000",diffRemovalHighlightBg:void 0,diffAdditionHighlightColor:"#004000",diffAdditionHighlightBg:void 0,diffRemovalNum:"#c02020",diffAdditionNum:"#188028",diffRemovalPrefix:"#d01010",diffAdditionPrefix:"#109020",primary:"black",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"black",statusOff:"gray",logoTextAnsi:"\x1B[1;30m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#0077ff","#ff00ff"]},"Synthwave 84":{id:"Synthwave 84",name:"Synthwave 84",text:"#fdfdfd",textMuted:"#a08eb7",textDim:"#705c8a",textInverted:"#1a1025",textExclusive:"#e3dcf0",textMutedExclusive:"#b9abc9",border:"#fc28a8",borderMuted:"#a21568",borderDim:"#5c0a3a",bg:void 0,cardBg:"#261b38",highlightBg:"#35254d",activeBg:"#4c3570",inputBg:"#35254d",inputBorder:"#35254d",inputText:"#fdfdfd",inputPlaceholder:"#a08eb7",inputPrompt:"#03e8fc",codeBg:"#1e142b",codeBorder:"#a21568",userMsgBg:"#35254d",userMsgBorder:"#35254d",userMsgText:"#fdfdfd",diffRemovalBg:"#471434",diffAdditionBg:"#144743",diffRemovalText:"#ff4081",diffAdditionText:"#00e5ff",diffRemovalHighlightColor:"#ff79a1",diffRemovalHighlightBg:"#6b1e4e",diffAdditionHighlightColor:"#66f5ff",diffAdditionHighlightBg:"#1e6b65",diffRemovalNum:"#ff4081",diffAdditionNum:"#00e5ff",diffRemovalPrefix:"#ff79a1",diffAdditionPrefix:"#66f5ff",primary:"#fdfdfd",secondary:"#03e8fc",accent:"#fc28a8",success:"#00e5ff",warning:"#ffc107",danger:"#ff4081",info:"#b388ff",statusOn:"#03e8fc",statusOff:"#a08eb7",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#fc28a8","#03e8fc"]},"Forest Sprite":{id:"Forest Sprite",name:"Forest Sprite",text:"#d6e6d1",textMuted:"#95b38d",textDim:"#628059",textInverted:"#161c14",textExclusive:"#eaf2e8",textMutedExclusive:"#a9c7a2",border:"#74a862",borderMuted:"#477038",borderDim:"#2b4720",bg:void 0,cardBg:"#1f291c",highlightBg:"#2a3826",activeBg:"#3a4d35",inputBg:"#2a3826",inputBorder:"#2a3826",inputText:"#d6e6d1",inputPlaceholder:"#95b38d",inputPrompt:"#8feb73",codeBg:"#161e14",codeBorder:"#477038",userMsgBg:"#2a3826",userMsgBorder:"#2a3826",userMsgText:"#d6e6d1",diffRemovalBg:"#3b231c",diffAdditionBg:"#203b1c",diffRemovalText:"#db6242",diffAdditionText:"#59cc3f",diffRemovalHighlightColor:"#f0896c",diffRemovalHighlightBg:"#5c362a",diffAdditionHighlightColor:"#80e368",diffAdditionHighlightBg:"#305929",diffRemovalNum:"#db6242",diffAdditionNum:"#59cc3f",diffRemovalPrefix:"#f0896c",diffAdditionPrefix:"#80e368",primary:"#d6e6d1",secondary:"#8feb73",accent:"#e69835",success:"#59cc3f",warning:"#e69835",danger:"#db6242",info:"#73b4eb",statusOn:"#8feb73",statusOff:"#95b38d",logoTextAnsi:"\x1B[1;32m",logoBodyAnsi:"\x1B[32m",logoMutedAnsi:"\x1B[90m",logoGradient:["#8feb73","#e69835"]}};var Vo=null;var Or=(e="Dark")=>{let t;e==="Mystery"||e==="Chaos"?(Vo||(Vo=Dr[Math.floor(Math.random()*Dr.length)]),t={...Vo,id:"Mystery"}):(Vo=null,bo[e]?t=bo[e]:e==="GitHub"?t=bo["GitHub Dark"]:e==="Transparent"?t=bo["Transparent Dark"]:t=bo.Dark);let n=t.codeText||t.secondary||t.info||t.logoGradient&&t.logoGradient[0]||"cyan";return{...t,codeText:n}};var Ca=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",yc=(e=2)=>{let t=Ca();return t==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)},xc=(e="...",t="Loading...",n="Dark")=>{let s=Ks[Math.floor(Math.random()*Ks.length)],o=Or(n),c=o.logoTextAnsi,f=o.logoBodyAnsi,l=o.logoMutedAnsi,k="\x1B[0m",p=[" \u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2588\u2588\u2588\u2591 "," \u2588\u2588\u2588\u2591 "," \u2588\u2588\u2588\u2591 "," \u2591\u2591\u2591 "],g=o.logoGradient||["#0077ff","#ff00ff"],T=Ea(g).multiline(p.join(`
567
566
  `)).split(`
568
567
  `),m=i=>`${l}${i}${k}`;return`${T[0]}
569
568
  ${T[1]} ${c}Selected Provider: ${t}${k}
@@ -573,7 +572,7 @@ ${T[4]}
573
572
  ${T[5]} ${f}See /help for additional commands.${k}
574
573
  ${T[6]} ${m(s)}
575
574
  ${T[7]}
576
- `};import{WebSocket as Yo}from"ws";var Ut=null,Jn=!1,Ra="ws://localhost:56832",Vs=[],Qn=null,Ys=null,Pr="2.0.0",kc=e=>{Pr=e,$r()},qs=e=>{Ys=e},$r=()=>{if(Ut||Jn)return;Jn=!0;let e=new Yo(Ra);e.on("open",()=>{for(Ut=e,Jn=!1,Ut.send(JSON.stringify({command:"version",version:Pr,pid:process.pid,ppid:process.ppid}));Vs.length>0;)Ut.send(JSON.stringify(Vs.shift()))}),e.on("message",t=>{try{let n=JSON.parse(t.toString());n.command==="contextResponse"&&Qn?(Qn(n.data),Qn=null):n.command==="securityResponse"&&Ys&&Ys(n.result)}catch{}}),e.on("error",()=>{Jn=!1,Ut=null}),e.on("close",()=>{Jn=!1,Ut=null})},qo=e=>{Ut&&Ut.readyState===Yo.OPEN?Ut.send(JSON.stringify(e)):(Vs.push(e),Jn||$r())},zo=()=>Ut!==null&&Ut.readyState===Yo.OPEN,Tc=e=>{qo({command:"status",status:e})},Hn=()=>new Promise(e=>{if(!Ut||Ut.readyState!==Yo.OPEN){e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]});return}Qn=e,Ut.send(JSON.stringify({command:"requestContext"})),setTimeout(()=>{Qn===e&&(e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]}),Qn=null)},1e3)}),Nr=e=>{qo({command:"open",filePath:e})},zs=(e,t,n)=>{qo({command:"showDiff",filePath:e,originalContent:t,modifiedContent:n})},Fr=(e,t)=>{qo({command:"closeDiff",filePath:e,result:t})};import Xs from"path";import va from"fs";var Ma=e=>{try{return va.readdirSync(e,{withFileTypes:!0})}catch{return[]}},Js=(e,t=4,n=1,s=Ma,o=[],c=null)=>{let f=c||s(e),l=" ".repeat(n-1),k=n===1?new Set([...io,...o,...ro(e),...ro(process.cwd())]):o instanceof Set?o:new Set([...io,...o]),p=x=>k.has(x),g=f.filter(x=>!p(x.name)),T=f.filter(x=>p(x.name)).length,m=g.filter(x=>!x.isDirectory()).map(x=>x.name).sort(),i=g.filter(x=>x.isDirectory()).sort((x,_)=>x.name.localeCompare(_.name)),u=x=>{let _=x.length;if(_===0)return"no files";let M=Array.from(new Set(x.map(a=>{let R=typeof a=="string"?a:a.name;return Xs.extname(R).slice(1)}).filter(Boolean))).sort(),y="*";return M.length===1?y=`*.${M[0]}`:M.length>1&&(y=`*.{${M.join(", ")}}`),_===1?y:`${y} ${_} files`},w="";if(n===1){let x=m.join(", "),_=T>0?` [${T} ignored]`:"";(x||_)&&(w+=`${l}${x?x+(_?`${_}`:""):_.trim()}
575
+ `};import{WebSocket as Yo}from"ws";var Ut=null,Jn=!1,Ra="ws://localhost:56832",Vs=[],Qn=null,Ys=null,Lr="2.0.0",kc=e=>{Lr=e,Pr()},qs=e=>{Ys=e},Pr=()=>{if(Ut||Jn)return;Jn=!0;let e=new Yo(Ra);e.on("open",()=>{for(Ut=e,Jn=!1,Ut.send(JSON.stringify({command:"version",version:Lr,pid:process.pid,ppid:process.ppid}));Vs.length>0;)Ut.send(JSON.stringify(Vs.shift()))}),e.on("message",t=>{try{let n=JSON.parse(t.toString());n.command==="contextResponse"&&Qn?(Qn(n.data),Qn=null):n.command==="securityResponse"&&Ys&&Ys(n.result)}catch{}}),e.on("error",()=>{Jn=!1,Ut=null}),e.on("close",()=>{Jn=!1,Ut=null})},qo=e=>{Ut&&Ut.readyState===Yo.OPEN?Ut.send(JSON.stringify(e)):(Vs.push(e),Jn||Pr())},zo=()=>Ut!==null&&Ut.readyState===Yo.OPEN,Tc=e=>{qo({command:"status",status:e})},Hn=()=>new Promise(e=>{if(!Ut||Ut.readyState!==Yo.OPEN){e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]});return}Qn=e,Ut.send(JSON.stringify({command:"requestContext"})),setTimeout(()=>{Qn===e&&(e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]}),Qn=null)},1e3)}),$r=e=>{qo({command:"open",filePath:e})},zs=(e,t,n)=>{qo({command:"showDiff",filePath:e,originalContent:t,modifiedContent:n})},Nr=(e,t)=>{qo({command:"closeDiff",filePath:e,result:t})};import Xs from"path";import va from"fs";var Ma=e=>{try{return va.readdirSync(e,{withFileTypes:!0})}catch{return[]}},Js=(e,t=4,n=1,s=Ma,o=[],c=null)=>{let f=c||s(e),l=" ".repeat(n-1),k=n===1?new Set([...io,...o,...ro(e),...ro(process.cwd())]):o instanceof Set?o:new Set([...io,...o]),p=x=>k.has(x),g=f.filter(x=>!p(x.name)),T=f.filter(x=>p(x.name)).length,m=g.filter(x=>!x.isDirectory()).map(x=>x.name).sort(),i=g.filter(x=>x.isDirectory()).sort((x,_)=>x.name.localeCompare(_.name)),u=x=>{let _=x.length;if(_===0)return"no files";let M=Array.from(new Set(x.map(a=>{let R=typeof a=="string"?a:a.name;return Xs.extname(R).slice(1)}).filter(Boolean))).sort(),y="*";return M.length===1?y=`*.${M[0]}`:M.length>1&&(y=`*.{${M.join(", ")}}`),_===1?y:`${y} ${_} files`},w="";if(n===1){let x=m.join(", "),_=T>0?` [${T} ignored]`:"";(x||_)&&(w+=`${l}${x?x+(_?`${_}`:""):_.trim()}
577
576
  `)}else m.length>0&&(w+=`${l}[${u(m)}]
578
577
  `);let I=10,h=i.slice(0,I),A=i.length>I,$=[],C=[];for(let x of h){let _=Xs.join(e,x.name),M=x.name,y=n,a=s(_),R=a.filter(v=>!p(v.name)),d=R.filter(v=>v.isDirectory()),r=R.filter(v=>!v.isDirectory());for(;r.length===0&&d.length===1&&y<t;)M=`${M}/${d[0].name}`,_=Xs.join(_,d[0].name),y++,a=s(_),R=a.filter(v=>!p(v.name)),d=R.filter(v=>v.isDirectory()),r=R.filter(v=>!v.isDirectory());let E=d.length>0;if(E&&y<t)C.push({displayName:M,subDirPath:_,subEntries:a,nextDepth:y+1});else{let v=u(r),U=E&&y>=t?" ...max scan depth":"";$.push(`${M}/${v}${U}`)}}$.length>0&&(w+=`${l}${$.join(", ")}
579
578
  `);for(let{displayName:x,subDirPath:_,subEntries:M,nextDepth:y}of C)w+=`${l}${x}/
@@ -587,7 +586,7 @@ ${T[7]}
587
586
  `}),k};var Ze=async(e,t,n=5,s=1e3)=>{let o=t?.signal;for(let f=0;f<n;f++){if(o?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{let l=await fetch(e,t);if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),l.ok||l.status!==429&&l.status<500)return l}catch(l){if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),l.name==="AbortError"||o?.aborted||f===n-1)throw l}o?await new Promise((l,k)=>{let p=setTimeout(()=>{o.removeEventListener("abort",g),l()},Math.min(24e3,s*Math.pow(2,f))),g=()=>{clearTimeout(p),k(new DOMException("The user aborted a request.","AbortError"))};o.addEventListener("abort",g)}):await new Promise(l=>setTimeout(l,Math.min(24e3,s*Math.pow(2,f))))}if(o?.aborted)throw new DOMException("The user aborted a request.","AbortError");let c=await fetch(e,t);return typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),c};async function Xo(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",t);return[...new Uint8Array(n).slice(0,16)].map(s=>s.toString(16).padStart(2,"0")).join("")}var xn=e=>typeof e!="string"?e:e.replace(/<\|channel>thought/gi,"<think>").replace(/<channel\|>/gi,"</think>");var Jo=async function*(e,t,n,s,o,c,f,l,k=1){let p=[];s&&p.push({role:"system",content:s});for(let _ of n){let M=_.role==="user"?"user":"assistant",y=[];if(Array.isArray(_.parts)){for(let a of _.parts)if(a.text)y.push({type:"text",text:a.text});else if((a.inlineData||a.inline_data)&&f){let R=a.inlineData||a.inline_data,d=R.mimeType||R.mime_type||"image/jpeg",r=R.data;d.startsWith("image/")&&y.push({type:"image_url",image_url:{url:`data:${d};base64,${r}`}})}}else{let a=_.text||"";a&&y.push({type:"text",text:a})}p.push({role:M,content:y.length===1&&y[0].type==="text"?y[0].text:y})}let g={model:t,messages:p,stream:!0,stream_options:{include_usage:!0},temperature:k,tools:[],tool_choice:"none"},T=He("DeepSeek",t,o),i=T!==null?T:o!=="Fast"?{Low:"low",Medium:"high",Standard:"high",High:"max",xHigh:"max"}[o]||"high":null;i&&i!=="disabled"&&i!=="none"&&i!=="false"&&i!==!1?(g.reasoning_effort=i,g.extra_body={thinking:{type:"enabled"}}):g.extra_body={thinking:{type:"disabled"}};let u=await Ze("https://api.deepseek.com/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(g),signal:l});if(!u.ok){let _=await u.json().catch(()=>({}));throw new Error(`DeepSeek Error (${u.status}): ${_.error?.message||u.statusText}`)}let w=u.body.getReader(),I=new TextDecoder,h="",A=[],$=null,C=Date.now(),x=!1;for(;;){let{done:_,value:M}=await w.read();if(_){x&&(A.length>0||$)&&(yield{candidates:A.length>0?[{content:{parts:A}}]:[],usageMetadata:$});break}h+=I.decode(M,{stream:!0});let y=h.split(`
588
587
  `);h=y.pop();for(let a of y){let R=a.trim();if(!R||!R.startsWith("data: "))continue;let d=!1;if(R==="data: [DONE]")d=!0;else try{let r=JSON.parse(R.substring(6)),E=r.choices?.[0]?.delta,v=r.usage;if(r.choices?.[0]?.finish_reason&&(d=!0),v&&($={totalTokenCount:v.total_tokens||v.prompt_tokens+v.completion_tokens,promptTokenCount:v.prompt_tokens||0,candidatesTokenCount:v.completion_tokens||0,cachedContentTokenCount:v.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:v.completion_tokens_details?.reasoning_tokens||0},x=!0),E){let U=E.reasoning_content||null;U&&(A.push({text:U,thought:!0}),x=!0),E.content&&(A.push({text:E.content}),x=!0)}}catch{}if((d||Date.now()-C>=150)&&x&&(yield{candidates:A.length>0?[{content:{parts:[...A]}}]:[],usageMetadata:$},A=[],C=Date.now(),x=!1),d)break}Date.now()-C>=150&&x&&(yield{candidates:A.length>0?[{content:{parts:[...A]}}]:[],usageMetadata:$},A=[],C=Date.now(),x=!1)}};var Qo=async function*(e,t,n,s,o,c,f,l,k=1,p=null){let g=[];s&&g.push({role:"system",content:s});for(let a of n){let R=a.role==="user"?"user":"assistant",d=[];if(Array.isArray(a.parts)){for(let r of a.parts)if(r.text)d.push({type:"text",text:r.text});else if(r.inlineData&&f){let E=r.inlineData.mimeType,v=r.inlineData.data;E.startsWith("image/")&&d.push({type:"image_url",image_url:`data:${E};base64,${v}`})}}else{let r=a.text||"";r&&d.push({type:"text",text:r})}d.length>0&&g.push({role:R,content:d.length===1&&d[0].type==="text"?d[0].text:d})}let T={Fast:"none",Low:"none",Medium:"high",Standard:"high",High:"high",xHigh:"high"},m=`${e.slice(-5)}${p||""}${o}${t}`,i=await Xo(m),u={model:t,messages:g,stream:!0,temperature:k,prompt_cache_key:i,tools:[],tool_choice:"none"},w=He("Mistral",t,o);w!==null&&w!=="none"?w&&w!=="none"&&w!=="disabled"&&w!==!1&&(u.reasoning_effort=w):o&&T[o]!=="none"&&(u.reasoning_effort=T[o]||"high");let I=await Ze("https://api.mistral.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(u),signal:l});if(!I.ok){let a=await I.text().catch(()=>""),R=I.statusText;try{let d=JSON.parse(a);R=d.error?.message||d.message||JSON.stringify(d.detail||d)}catch{a&&(R=a)}throw new Error(`Mistral Error (${I.status}): ${JSON.stringify(R)}`)}let h=I.body.getReader(),A=new TextDecoder,$="",C=[],x=null,_=Date.now(),M=!1,y=a=>a?typeof a=="string"?xn(a):Array.isArray(a)?a.map(y).filter(Boolean).join(""):typeof a=="object"&&a!==null?typeof a.text=="string"?xn(a.text):typeof a.content=="string"?xn(a.content):typeof a.thinking=="string"?xn(a.thinking):typeof a.reasoning_content=="string"?xn(a.reasoning_content):typeof a.reasoning=="string"?xn(a.reasoning):typeof a.value=="string"?xn(a.value):a.text?y(a.text):a.content?y(a.content):a.thinking?y(a.thinking):a.reasoning_content?y(a.reasoning_content):a.reasoning?y(a.reasoning):a.value?y(a.value):"":xn(String(a)):"";for(;;){let{done:a,value:R}=await h.read();if(a){M&&(C.length>0||x)&&(yield{candidates:C.length>0?[{content:{parts:C}}]:[],usageMetadata:x});break}$+=A.decode(R,{stream:!0});let d=$.split(`
589
588
  `);$=d.pop();for(let r of d){let E=r.trim();if(!E||!E.startsWith("data: "))continue;let v=!1;if(E==="data: [DONE]")v=!0;else try{let U=JSON.parse(E.substring(6)),O=U.choices?.[0]?.delta,P=U.usage;if(U.choices?.[0]?.finish_reason&&(v=!0),P&&(x={totalTokenCount:P.total_tokens||(P.prompt_tokens||0)+(P.completion_tokens||0),promptTokenCount:P.prompt_tokens||0,candidatesTokenCount:P.completion_tokens||0,cachedContentTokenCount:P.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:P.completion_tokens_details?.reasoning_tokens||0},M=!0),O){let re=O.thinking||O.reasoning_content||O.reasoning,de=y(re);de&&(C.push({text:de,thought:!0}),M=!0);let Q=O.content||(!O.thinking&&!O.reasoning_content&&!O.reasoning?O.text:null);if(Q)if(Array.isArray(Q))for(let ke of Q)if(typeof ke=="object"&&ke!==null){let ae=ke.type==="thinking"||ke.type==="reasoning"||!!ke.thought,it=y(ke);it&&(C.push({text:it,...ae?{thought:!0}:{}}),M=!0)}else{let ae=y(ke);ae&&(C.push({text:ae}),M=!0)}else if(typeof Q=="object"&&Q!==null){let ke=Q.type==="thinking"||Q.type==="reasoning"||!!Q.thought,ae=y(Q);ae&&(C.push({text:ae,...ke?{thought:!0}:{}}),M=!0)}else{let ke=y(Q);ke&&(C.push({text:ke}),M=!0)}}}catch{}if((v||Date.now()-_>=150)&&M&&(yield{candidates:C.length>0?[{content:{parts:[...C]}}]:[],usageMetadata:x},C=[],_=Date.now(),M=!1),v)break}Date.now()-_>=150&&M&&(yield{candidates:C.length>0?[{content:{parts:[...C]}}]:[],usageMetadata:x},C=[],_=Date.now(),M=!1)}};var Zo=async function*(e,t,n,s,o,c,f=!1,l,k=1){let p=[];s&&p.push({role:"system",content:s}),n.forEach(ae=>{let it=ae.role==="model"?"assistant":"user",L=[];Array.isArray(ae.parts)&&ae.parts.forEach(F=>{if(F.text)L.push({type:"text",text:F.text});else if(F.inlineData&&f){let Ee=F.inlineData.mimeType,oe=F.inlineData.data;Ee.startsWith("image/")&&ft(t)&&L.push({type:"image_url",image_url:{url:`data:${Ee};base64,${oe}`}})}}),p.push({role:it,content:L.length===1&&L[0].type==="text"?L[0].text:L})});let g=He("NVIDIA",t,o),m=g!==null?g:{Fast:"Fast",Low:"Fast",Medium:"Standard",Standard:"Standard",High:"High",xHigh:"High"}[o]||"High",i=m!=="Fast"&&m!=="none"&&m!=="disabled"&&m!==!1,u=t.includes("kimi"),w=t.includes("gemma"),I=t.includes("deepseek"),h=t.includes("glm"),A=t.includes("mistral"),$=t.includes("minimax"),C=t.includes("gpt"),x=t.includes("qwen"),_=t.includes("nemotron"),M=t.includes("llama-3"),y=t.includes("seed"),a=t.includes("poolside"),R=t.includes("thinkingmachines")||t.includes("muse"),d=M,r={Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},E={Fast:"64",Low:"64",Medium:"4096",Standard:"4096",High:"16384",xHigh:"16384"},v={Fast:"none",Low:"minimal",Medium:"medium",Standard:"medium",High:"max",xHigh:"max"},U=$||I||a||R?16384:32768;U=process.env.NVIDIA_BASE_URL?1024:U;let O={model:t,messages:p,max_tokens:U,stream:!0,stream_options:{include_usage:!0},temperature:k,tools:[],tool_choice:"none",...C&&{thinking:r[o]||"high"}};if(!(process.env.NVIDIA_BASE_URL||d))if(u)O.chat_template_kwargs={thinking:i};else if(w)O.chat_template_kwargs={enable_thinking:i};else if(I)if(i){let ae=m==="High"?"max":"high";O.chat_template_kwargs={thinking:!0,reasoning_effort:ae}}else O.chat_template_kwargs={thinking:!1};else h?O.chat_template_kwargs={enable_thinking:i,clear_thinking:!i}:A?O.reasoning_effort=i?"high":"none":$&&t.includes("minimax-m3")?O.chat_template_kwargs={thinking_mode:i?"enabled":"disabled"}:x?O.chat_template_kwargs={enable_thinking:i}:_?m==="High"?O.chat_template_kwargs={enable_thinking:!0}:m==="Standard"?O.chat_template_kwargs={enable_thinking:!0,medium_effort:!0}:O.chat_template_kwargs={enable_thinking:!1}:y?i&&(O.extra_body={thinking_budget:parseInt(E[m]??"4096")}):a?O.chat_template_kwargs={enable_thinking:i}:R&&(O.reasoning_effort=v[m]||"medium");let P=0,re=6,de=!1,Q=process.env.NVIDIA_BASE_URL||"https://integrate.api.nvidia.com/v1/chat/completions",ke=process.env.NVIDIA_API_KEY&&process.env.NVIDIA_BASE_URL?process.env.NVIDIA_API_KEY:e;for(Q.endsWith("/chat/completions")||(Q=Q.replace(/\/+$/,"")+"/chat/completions");P<re;){P++;try{let ae=await Ze(Q,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${ke}`},body:JSON.stringify(O),signal:l});if(!ae.ok){let ye=await ae.text().catch(()=>""),Re=ae.statusText;try{let Ie=JSON.parse(ye);Re=Ie.error?.message||Ie.message||JSON.stringify(Ie.detail||Ie)}catch{ye&&(Re=ye)}let ve=new Error(`NVIDIA API Error (${ae.status}): ${Re}`);throw ve.status=ae.status,ve}let it=ae.body.getReader(),L=new TextDecoder,F="",Ee=[],oe=null,B=Date.now(),G=!1;for(;;){let{done:ye,value:Re}=await it.read();if(ye){G&&(Ee.length>0||oe)&&(yield{candidates:Ee.length>0?[{content:{parts:Ee}}]:[],usageMetadata:oe},de=!0);break}F+=L.decode(Re,{stream:!0});let ve=F.split(`
590
- `);F=ve.pop();let Ie=!1;for(let Dn of ve){let nn=Dn.trim();if(nn){if(nn==="data: [DONE]"){Ie=!0;break}if(nn.startsWith("data: ")){let pt;try{pt=JSON.parse(nn.substring(6))}catch{continue}if(pt.error)throw new Error(`NVIDIA Stream Error: ${pt.error.message||JSON.stringify(pt.error)}`);try{let kt=pt.usage;kt&&(oe={totalTokenCount:kt.total_tokens||kt.prompt_tokens+kt.completion_tokens,promptTokenCount:kt.prompt_tokens||0,candidatesTokenCount:kt.completion_tokens||0,cachedContentTokenCount:kt.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:(kt.completion_tokens_details?.reasoning_tokens||0)+(kt.completion_tokens_details?.thoughts_tokens||0)},G=!0);let Je=pt.choices?.[0]?.delta?.reasoning||pt.choices?.[0]?.delta?.reasoning_content||"",xe=pt.choices?.[0]?.delta?.content||"";Je&&(Ee.push({text:Je,thought:!0}),G=!0),xe&&(Ee.push({text:xe}),G=!0)}catch{}}}}if((Ie||Date.now()-B>=350)&&G&&(yield{candidates:Ee.length>0?[{content:{parts:[...Ee]}}]:[],usageMetadata:oe},de=!0,Ee=[],B=Date.now(),G=!1),Ie)break}break}catch(ae){if(de||P>=re)throw ae;await new Promise(it=>setTimeout(it,3500))}}},Br=async function*(e,t){let n=[],s=null,o=!1,c=null,f=u=>{if(n.push(u),s){let w=s;s=null,w()}},l=t.split("/").pop(),k=Array.from(new Set([l,l.replace(/\./g,"-"),l.replace(/\./g,"_")])),g=["https://buildapi.ngc.nvidia.com/v2/predict/queues/models/qc69jvmznzxy","https://api.ngc.nvidia.com/v2/predict/queues/models/qc69jvmznzxy"].flatMap(u=>k.map(w=>`${u}/${w}`)),T=!1,m=null,i=async()=>{try{let w=await(await Promise.any(g.map(async I=>{let h=await fetch(I);if(!h.ok)throw new Error(`HTTP ${h.status}`);return h}))).json();if(w&&w.queues&&w.queues[0]&&typeof w.queues[0].queueDepth=="number"){let I=w.queues[0].queueDepth;T||f({value:{type:"status",content:`Queue ${I||1}`},done:!1})}}catch{}};process.env.NVIDIA_BASE_URL||(i(),m=setInterval(i,5e3)),(async()=>{try{let u=e[Symbol.asyncIterator]();for(;;){let{value:w,done:I}=await u.next();if(I)break;T=!0,m&&(clearInterval(m),m=null),f({value:w,done:!1})}o=!0,f(null)}catch(u){if(c=u,m&&(clearInterval(m),m=null),s){let w=s;s=null,w()}}})();try{for(;;){if(c)throw c;if(n.length>0){let u=n.shift();if(u===null&&o)break;yield u.value}else{if(o)break;await new Promise(u=>{s=u})}}}finally{m&&(clearInterval(m),m=null)}};var es=async function*(e,t,n,s,o,c,f,l,k=1,p=null){let g=[];s&&g.push({role:"system",content:[{type:"text",text:s}]});for(let E of n){let v=E.role==="user"?"user":"assistant",U=[];if(Array.isArray(E.parts)){for(let O of E.parts)if(O.text)U.push({type:"text",text:O.text});else if(O.inlineData&&f){let P=O.inlineData.mimeType,re=O.inlineData.data;P.startsWith("image/")?U.push({type:"image_url",image_url:{url:`data:${P};base64,${re}`}}):U.push({type:"file",file:{filename:O.filename||"file",file_data:`data:${P};base64,${re}`}})}}else{let O=E.text||"";O&&U.push({type:"text",text:O})}g.push({role:v,content:U.length===1&&U[0].type==="text"?U[0].text:U})}let T={Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},m=["free","nitro","floor","exacto"],i=t,u=null,w=null;if(t.includes(":")){let E=t.split(":");if(E.length>1){let v=E[E.length-1].toLowerCase().trim();(v==="flex"||v==="priority")&&(w=v,E.pop())}if(E.length>1){let v=E[E.length-1].toLowerCase().trim();if(!m.includes(v)){let U=E.pop().trim();U&&(u={only:[U],allow_fallbacks:!1})}}i=E.join(":").trim()}let I=`${e.slice(-5)}${p||""}${o}${i}${w||""}${u?JSON.stringify(u):""}`,h=await Xo(I),A={model:i,messages:g,stream:!0,temperature:k,cache_control:{type:"ephemeral"},tools:[],tool_choice:"none",session_id:h};w&&(A.service_tier=w),u&&(A.provider=u);let $=He("OpenRouter",t,o),C=$!==null?$:T[o];C&&C!=="none"&&($!==null||o!=="Fast")&&(A.reasoning_effort=C);let x=await Ze("https://openrouter.ai/api/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json","HTTP-Referer":"https://fluxflow-cli.onrender.com/","X-Title":"FluxFlow CLI","X-OpenRouter-Title":"FluxFlow CLI","X-Cache":"true","X-OpenRouter-Cache":"true"},body:JSON.stringify(A),signal:l});if(!x.ok){let E=await x.json().catch(()=>({})),v=E.error?.metadata?.raw||E.error?.message||(typeof E.error=="string"?E.error:"")||x.statusText||"Unknown error";throw new Error(`OpenRouter Error (${x.status}): ${v}`)}let _=x.body.getReader(),M=new TextDecoder,y="",a=[],R=null,d=Date.now(),r=!1;for(;;){let{done:E,value:v}=await _.read();if(E){r&&(a.length>0||R)&&(yield{candidates:a.length>0?[{content:{parts:a}}]:[],usageMetadata:R});break}y+=M.decode(v,{stream:!0});let U=y.split(`
589
+ `);F=ve.pop();let Ie=!1;for(let Dn of ve){let nn=Dn.trim();if(nn){if(nn==="data: [DONE]"){Ie=!0;break}if(nn.startsWith("data: ")){let pt;try{pt=JSON.parse(nn.substring(6))}catch{continue}if(pt.error)throw new Error(`NVIDIA Stream Error: ${pt.error.message||JSON.stringify(pt.error)}`);try{let kt=pt.usage;kt&&(oe={totalTokenCount:kt.total_tokens||kt.prompt_tokens+kt.completion_tokens,promptTokenCount:kt.prompt_tokens||0,candidatesTokenCount:kt.completion_tokens||0,cachedContentTokenCount:kt.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:(kt.completion_tokens_details?.reasoning_tokens||0)+(kt.completion_tokens_details?.thoughts_tokens||0)},G=!0);let Je=pt.choices?.[0]?.delta?.reasoning||pt.choices?.[0]?.delta?.reasoning_content||"",xe=pt.choices?.[0]?.delta?.content||"";Je&&(Ee.push({text:Je,thought:!0}),G=!0),xe&&(Ee.push({text:xe}),G=!0)}catch{}}}}if((Ie||Date.now()-B>=350)&&G&&(yield{candidates:Ee.length>0?[{content:{parts:[...Ee]}}]:[],usageMetadata:oe},de=!0,Ee=[],B=Date.now(),G=!1),Ie)break}break}catch(ae){if(de||P>=re)throw ae;await new Promise(it=>setTimeout(it,3500))}}},Fr=async function*(e,t){let n=[],s=null,o=!1,c=null,f=u=>{if(n.push(u),s){let w=s;s=null,w()}},l=t.split("/").pop(),k=Array.from(new Set([l,l.replace(/\./g,"-"),l.replace(/\./g,"_")])),g=["https://buildapi.ngc.nvidia.com/v2/predict/queues/models/qc69jvmznzxy","https://api.ngc.nvidia.com/v2/predict/queues/models/qc69jvmznzxy"].flatMap(u=>k.map(w=>`${u}/${w}`)),T=!1,m=null,i=async()=>{try{let w=await(await Promise.any(g.map(async I=>{let h=await fetch(I);if(!h.ok)throw new Error(`HTTP ${h.status}`);return h}))).json();if(w&&w.queues&&w.queues[0]&&typeof w.queues[0].queueDepth=="number"){let I=w.queues[0].queueDepth;T||f({value:{type:"status",content:`Queue ${I||1}`},done:!1})}}catch{}};process.env.NVIDIA_BASE_URL||(i(),m=setInterval(i,5e3)),(async()=>{try{let u=e[Symbol.asyncIterator]();for(;;){let{value:w,done:I}=await u.next();if(I)break;T=!0,m&&(clearInterval(m),m=null),f({value:w,done:!1})}o=!0,f(null)}catch(u){if(c=u,m&&(clearInterval(m),m=null),s){let w=s;s=null,w()}}})();try{for(;;){if(c)throw c;if(n.length>0){let u=n.shift();if(u===null&&o)break;yield u.value}else{if(o)break;await new Promise(u=>{s=u})}}}finally{m&&(clearInterval(m),m=null)}};var es=async function*(e,t,n,s,o,c,f,l,k=1,p=null){let g=[];s&&g.push({role:"system",content:[{type:"text",text:s}]});for(let E of n){let v=E.role==="user"?"user":"assistant",U=[];if(Array.isArray(E.parts)){for(let O of E.parts)if(O.text)U.push({type:"text",text:O.text});else if(O.inlineData&&f){let P=O.inlineData.mimeType,re=O.inlineData.data;P.startsWith("image/")?U.push({type:"image_url",image_url:{url:`data:${P};base64,${re}`}}):U.push({type:"file",file:{filename:O.filename||"file",file_data:`data:${P};base64,${re}`}})}}else{let O=E.text||"";O&&U.push({type:"text",text:O})}g.push({role:v,content:U.length===1&&U[0].type==="text"?U[0].text:U})}let T={Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},m=["free","nitro","floor","exacto"],i=t,u=null,w=null;if(t.includes(":")){let E=t.split(":");if(E.length>1){let v=E[E.length-1].toLowerCase().trim();(v==="flex"||v==="priority")&&(w=v,E.pop())}if(E.length>1){let v=E[E.length-1].toLowerCase().trim();if(!m.includes(v)){let U=E.pop().trim();U&&(u={only:[U],allow_fallbacks:!1})}}i=E.join(":").trim()}let I=`${e.slice(-5)}${p||""}${o}${i}${w||""}${u?JSON.stringify(u):""}`,h=await Xo(I),A={model:i,messages:g,stream:!0,temperature:k,cache_control:{type:"ephemeral"},tools:[],tool_choice:"none",session_id:h};w&&(A.service_tier=w),u&&(A.provider=u);let $=He("OpenRouter",t,o),C=$!==null?$:T[o];C&&C!=="none"&&($!==null||o!=="Fast")&&(A.reasoning_effort=C);let x=await Ze("https://openrouter.ai/api/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json","HTTP-Referer":"https://fluxflow-cli.onrender.com/","X-Title":"FluxFlow CLI","X-OpenRouter-Title":"FluxFlow CLI","X-Cache":"true","X-OpenRouter-Cache":"true"},body:JSON.stringify(A),signal:l});if(!x.ok){let E=await x.json().catch(()=>({})),v=E.error?.metadata?.raw||E.error?.message||(typeof E.error=="string"?E.error:"")||x.statusText||"Unknown error";throw new Error(`OpenRouter Error (${x.status}): ${v}`)}let _=x.body.getReader(),M=new TextDecoder,y="",a=[],R=null,d=Date.now(),r=!1;for(;;){let{done:E,value:v}=await _.read();if(E){r&&(a.length>0||R)&&(yield{candidates:a.length>0?[{content:{parts:a}}]:[],usageMetadata:R});break}y+=M.decode(v,{stream:!0});let U=y.split(`
591
590
  `);y=U.pop();for(let O of U){let P=O.trim();if(!P||!P.startsWith("data: "))continue;let re=!1;if(P==="data: [DONE]")re=!0;else try{let de=JSON.parse(P.substring(6));if(de.error){let ae=de.error.metadata?.raw||de.error.message||JSON.stringify(de.error);throw new Error(`OpenRouter Stream Error: ${ae}`)}let Q=de.choices?.[0]?.delta,ke=de.usage;if(de.choices?.[0]?.finish_reason&&(re=!0),ke&&(R={totalTokenCount:ke.total_tokens||(ke.prompt_tokens||0)+(ke.completion_tokens||0),promptTokenCount:ke.prompt_tokens||0,candidatesTokenCount:ke.completion_tokens||0,cachedContentTokenCount:ke.prompt_tokens_details?.cached_tokens||ke.prompt_tokens_details?.cache_read_input_tokens||ke.cache_read_input_tokens||0,thoughtsTokenCount:ke.completion_tokens_details?.reasoning_tokens||0},r=!0),Q){let ae=Q.reasoning||(Q.reasoning_details?Q.reasoning_details.map(it=>it.text).join(""):null);ae&&(a.push({text:ae,thought:!0}),r=!0),Q.content&&(a.push({text:Q.content}),r=!0)}}catch(de){if(de.message&&de.message.startsWith("OpenRouter Stream Error:"))throw de}if((re||Date.now()-d>=150)&&r&&(yield{candidates:a.length>0?[{content:{parts:[...a]}}]:[],usageMetadata:R},a=[],d=Date.now(),r=!1),re)break}}};import{Ollama as Oa}from"ollama";var ei=async function*(e,t,n,s,o,c,f,l,k=1,p="Cloud"){let g=[];s&&g.push({role:"system",content:s});for(let y of n){let a=y.role==="user"?"user":"assistant",R="",d=[];if(Array.isArray(y.parts)){R=y.parts.map(r=>r.text||"").filter(Boolean).join(`
592
591
  `);for(let r of y.parts){let E=r.inlineData||r.inline_data;E&&E.data&&d.push(E.data)}}else R=y.text||"";if(R||d.length>0){let r={role:a,content:R};d.length>0&&(r.images=d),g.push(r)}}let T=p==="Local"||!e||e==="LOCAL",i={host:T?process.env.OLLAMA_HOST||"http://127.0.0.1:11434":process.env.OLLAMA_HOST||"https://ollama.com"};!T&&e&&(i.headers={Authorization:"Bearer "+e});let u=new Oa(i),w=[],I=null,h=Date.now(),A=!1,$=He("Ollama",t,o),C={Fast:!1,Low:"medium",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},x=$!==null?$==="false"||$===!1?!1:$==="true"||$===!0?!0:$:C[o]!==void 0?C[o]:!0,_={model:t,messages:g,stream:!0,think:x,keep_alive:"10m",tools:[],tool_choice:"none",options:{temperature:k}},M=await u.chat(_);for await(let y of M){if(l?.aborted)throw new DOMException("The user aborted a request.","AbortError");if(y.message?.thinking&&(w.push({text:y.message.thinking,thought:!0}),A=!0),y.message?.content&&(w.push({text:y.message.content}),A=!0),y.done){let a=y.prompt_cached_count||0;if(!a&&y.prompt_eval_count){let R=y.prompt_eval_duration||0;R>0&&R<5e7&&(a=y.prompt_eval_count)}I={totalTokenCount:(y.prompt_eval_count||0)+(y.eval_count||0),promptTokenCount:y.prompt_eval_count||0,candidatesTokenCount:y.eval_count||0,cachedContentTokenCount:a,thoughtsTokenCount:0},A=!0}(y.done||Date.now()-h>=150&&A)&&(yield{candidates:w.length>0?[{content:{parts:[...w]}}]:[],usageMetadata:I},w=[],h=Date.now(),A=!1)}A&&(w.length>0||I)&&(yield{candidates:w.length>0?[{content:{parts:[...w]}}]:[],usageMetadata:I})};var ts=async function*(e,t,n,s,o,c,f,l,k=1){let p=[];s&&p.push({role:"system",content:s});for(let a of n){let R=a.role==="user"?"user":"assistant",d="";if(Array.isArray(a.parts))for(let r of a.parts)r.text&&(d+=(d?`
593
592
  `:"")+r.text);else d=a.text||"";p.push({role:R,content:d})}let g=He("InferX",t,o),m=g!==null?g:{Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i=t&&t.toLowerCase().includes("qwen3.8-27b")&&g===null,u=t&&(t.toLowerCase().includes("qwen3.8-27b")||t.toLowerCase().includes("qwen3.6-35b-a3b-fp8")),w={model:t,messages:p.filter(a=>a.content&&String(a.content).trim().length>0),stream:!0,stream_options:{include_usage:!0},temperature:k,tools:[],tool_choice:"none"};!i&&m&&(w.stream_options={include_usage:!0},w.reasoning_effort=m);let I=await Ze("https://model.inferx.net/endpoints/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(w),signal:l});if(!I.ok){let a=await I.text().catch(()=>""),R="";try{let d=JSON.parse(a);R=d.error?.message||d.error?.detail||d.message||d.detail||(typeof d.error=="string"?d.error:"")||(a&&a!=="{}"?a:"")}catch{R=a}throw(!R||R==="{}")&&(R=I.statusText||"Unknown error"),new Error(`InferX Error (${I.status}): ${R}`)}let h=I.body.getReader(),A=new TextDecoder,$="",C=[],x=null,_=Date.now(),M=!1,y=!0;for(;;){let{done:a,value:R}=await h.read();if(a){M&&(C.length>0||x)&&(yield{candidates:C.length>0?[{content:{parts:C}}]:[],usageMetadata:x});break}$+=A.decode(R,{stream:!0});let d=$.split(`
@@ -598,12 +597,12 @@ ${T[7]}
598
597
  `);C=d.pop();for(let r of d){let E=r.trim();if(!E||!E.startsWith("data: "))continue;let v=!1;if(E==="data: [DONE]")v=!0;else try{let U=JSON.parse(E.substring(6)),O=U.choices?.[0]?.delta,P=U.usage;if(U.choices?.[0]?.finish_reason&&(v=!0),P&&(_={totalTokenCount:P.total_tokens||(P.prompt_tokens||0)+(P.completion_tokens||0),promptTokenCount:P.prompt_tokens||0,candidatesTokenCount:P.completion_tokens||0,cachedContentTokenCount:P.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:P.completion_tokens_details?.reasoning_tokens||P.reasoning_tokens||0},y=!0),O){let re=O.reasoning_content||O.reasoning||O.thinking||null;!re&&Array.isArray(O.reasoning_details)&&O.reasoning_details.length>0&&(re=O.reasoning_details.map(de=>typeof de=="string"?de:de?.text||"").filter(Boolean).join("")),re&&(x.push({text:re,thought:!0}),y=!0),O.content&&(x.push({text:O.content}),y=!0)}}catch{}if((v||Date.now()-M>=150)&&y&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:_},x=[],M=Date.now(),y=!1),v)break}Date.now()-M>=150&&y&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:_},x=[],M=Date.now(),y=!1)}};var rs=async function*(e,t,n,s,o,c,f,l,k=1){let p=[];s&&p.push({role:"system",content:s});for(let a of n){let R=a.role==="user"?"user":"assistant",d=[];if(Array.isArray(a.parts)){for(let r of a.parts)if(r.text)d.push({type:"text",text:r.text});else if(r.inlineData&&f){let E=r.inlineData.mimeType,v=r.inlineData.data;E.startsWith("image/")&&d.push({type:"image_url",image_url:{url:`data:${E};base64,${v}`}})}}else{let r=a.text||"";r&&d.push({type:"text",text:r})}p.push({role:R,content:d.length===1&&d[0].type==="text"?d[0].text:d})}let g=He("ExpLabs",t,o),m=g!==null?g:{Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:p,stream:!0,stream_options:{include_usage:!0},temperature:k,tools:[],tool_choice:"none"};m&&(i.reasoning_effort=m);let u=process.env.EXPLABS_URL||process.env.EXPERIENTIALLABS_URL||"https://api.experientiallabs.ai/v1/chat/completions",w={"Content-Type":"application/json"},I=e||process.env.EXPLABS_API_KEY||process.env.EXPERIENTIALLABS_API_KEY||"";w.Authorization=`Bearer ${I}`;let h=await Ze(u,{method:"POST",headers:w,body:JSON.stringify(i),signal:l});if(!h.ok){let a=await h.json().catch(()=>({}));throw new Error(`Experiential Labs Error (${h.status}): ${a.error?.message||a.message||h.statusText}`)}let A=h.body.getReader(),$=new TextDecoder,C="",x=[],_=null,M=Date.now(),y=!1;for(;;){let{done:a,value:R}=await A.read();if(a){y&&(x.length>0||_)&&(yield{candidates:x.length>0?[{content:{parts:x}}]:[],usageMetadata:_});break}C+=$.decode(R,{stream:!0});let d=C.split(`
599
598
  `);C=d.pop();for(let r of d){let E=r.trim();if(!E||!E.startsWith("data: "))continue;let v=!1;if(E==="data: [DONE]")v=!0;else try{let U=JSON.parse(E.substring(6)),O=U.choices?.[0]?.delta,P=U.usage;if(P&&(_={totalTokenCount:P.total_tokens||(P.prompt_tokens||0)+(P.completion_tokens||0),promptTokenCount:P.prompt_tokens||0,candidatesTokenCount:P.completion_tokens||0,cachedContentTokenCount:P.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:P.completion_tokens_details?.reasoning_tokens||P.reasoning_tokens||0},y=!0),O){let re=O.reasoning_content||O.reasoning||null;!re&&Array.isArray(O.reasoning_details)&&O.reasoning_details.length>0&&(re=O.reasoning_details.map(de=>de.text||"").filter(Boolean).join("")),re&&(x.push({text:re,thought:!0}),y=!0),O.content&&(x.push({text:O.content}),y=!0)}}catch{}if((v||Date.now()-M>=150)&&y&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:_},x=[],M=Date.now(),y=!1),v)break}Date.now()-M>=150&&y&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:_},x=[],M=Date.now(),y=!1)}};var ti=async function*(e,t,n,s,o,c,f,l,k=1){let p=[];s&&p.push({role:"system",content:s});for(let a of n){let R=a.role==="user"?"user":"assistant",d=[];if(Array.isArray(a.parts)){for(let r of a.parts)if(r.text)d.push({type:"text",text:r.text});else if(r.inlineData&&f){let E=r.inlineData.mimeType,v=r.inlineData.data;E.startsWith("image/")&&d.push({type:"image_url",image_url:{url:`data:${E};base64,${v}`}})}}else{let r=a.text||"";r&&d.push({type:"text",text:r})}p.push({role:R,content:d.length===1&&d[0].type==="text"?d[0].text:d})}let g=He("TokenHarbor",t,o),m=g!==null?g:{Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:p,stream:!0,stream_options:{include_usage:!0},temperature:k,tools:[],tool_choice:"none"};m&&(i.reasoning_effort=m);let u=process.env.TOKENHARBOR_URL||process.env.TOKEN_HARBOR_URL||"https://tokenharbor.ai/v1/chat/completions",w={"Content-Type":"application/json","X-Title":"Flux-Flow","User-Agent":"Flux-Flow","HTTP-Referer":"https://fluxflow-cli.onrender.com/"},I=e||process.env.TOKENHARBOR_API_KEY||process.env.TOKEN_HARBOR_API_KEY||"";w.Authorization=`Bearer ${I}`;let h=await Ze(u,{method:"POST",headers:w,body:JSON.stringify(i),signal:l});if(!h.ok){let a=await h.json().catch(()=>({}));throw new Error(`Token Harbor Error (${h.status}): ${a.error?.message||a.message||h.statusText}`)}let A=h.body.getReader(),$=new TextDecoder,C="",x=[],_=null,M=Date.now(),y=!1;for(;;){let{done:a,value:R}=await A.read();if(a){y&&(x.length>0||_)&&(yield{candidates:x.length>0?[{content:{parts:x}}]:[],usageMetadata:_});break}C+=$.decode(R,{stream:!0});let d=C.split(`
600
599
  `);C=d.pop();for(let r of d){let E=r.trim();if(!E||!E.startsWith("data: "))continue;let v=!1;if(E==="data: [DONE]")v=!0;else try{let U=JSON.parse(E.substring(6)),O=U.choices?.[0]?.delta,P=U.usage;if(P&&(_={totalTokenCount:P.total_tokens||(P.prompt_tokens||0)+(P.completion_tokens||0),promptTokenCount:P.prompt_tokens||0,candidatesTokenCount:P.completion_tokens||0,cachedContentTokenCount:P.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:P.completion_tokens_details?.reasoning_tokens||P.reasoning_tokens||0},y=!0),O){let re=O.reasoning_content||O.reasoning||null;!re&&Array.isArray(O.reasoning_details)&&O.reasoning_details.length>0&&(re=O.reasoning_details.map(de=>de.text||"").filter(Boolean).join("")),re&&(x.push({text:re,thought:!0}),y=!0),O.content&&(x.push({text:O.content}),y=!0)}}catch{}if((v||Date.now()-M>=150)&&y&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:_},x=[],M=Date.now(),y=!1),v)break}Date.now()-M>=150&&y&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:_},x=[],M=Date.now(),y=!1)}};var ni=async function*(e,t,n,s,o,c,f,l,k=1){let p=[];s&&p.push({role:"system",content:s});for(let a of n){let R=a.role==="user"?"user":"assistant",d=[];if(Array.isArray(a.parts)){for(let r of a.parts)if(r.text)d.push({type:"text",text:r.text});else if(r.inlineData&&f){let E=r.inlineData.mimeType,v=r.inlineData.data;E.startsWith("image/")&&d.push({type:"image_url",image_url:{url:`data:${E};base64,${v}`}})}}else{let r=a.text||"";r&&d.push({type:"text",text:r})}p.push({role:R,content:d.length===1&&d[0].type==="text"?d[0].text:d})}let g=He("APInex",t,o),m=g!==null?g:{Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:p,stream:!0,stream_options:{include_usage:!0},temperature:k,tools:[],tool_choice:"none"};m&&(i.reasoning_effort=m);let u=process.env.APINEX_URL||"https://api.apinex.bond/v1/chat/completions",w={"Content-Type":"application/json","X-Title":"Flux-Flow","User-Agent":"Flux-Flow","HTTP-Referer":"https://fluxflow-cli.onrender.com/"},I=e||process.env.APINEX_API_KEY||"";w.Authorization=`Bearer ${I}`;let h=await Ze(u,{method:"POST",headers:w,body:JSON.stringify(i),signal:l});if(!h.ok){let a=await h.json().catch(()=>({}));throw new Error(`APInex Error (${h.status}): ${a.error?.message||a.message||h.statusText}`)}let A=h.body.getReader(),$=new TextDecoder,C="",x=[],_=null,M=Date.now(),y=!1;for(;;){let{done:a,value:R}=await A.read();if(a){y&&(x.length>0||_)&&(yield{candidates:x.length>0?[{content:{parts:x}}]:[],usageMetadata:_});break}C+=$.decode(R,{stream:!0});let d=C.split(`
601
- `);C=d.pop();for(let r of d){let E=r.trim();if(!E||!E.startsWith("data: "))continue;let v=!1;if(E==="data: [DONE]")v=!0;else try{let U=JSON.parse(E.substring(6)),O=U.choices?.[0]?.delta,P=U.usage;if(P&&(_={totalTokenCount:P.total_tokens||(P.prompt_tokens||0)+(P.completion_tokens||0),promptTokenCount:P.prompt_tokens||0,candidatesTokenCount:P.completion_tokens||0,cachedContentTokenCount:P.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:P.completion_tokens_details?.reasoning_tokens||P.reasoning_tokens||0},y=!0),O){let re=O.reasoning_content||O.reasoning||null;!re&&Array.isArray(O.reasoning_details)&&O.reasoning_details.length>0&&(re=O.reasoning_details.map(de=>de.text||"").filter(Boolean).join("")),re&&(x.push({text:re,thought:!0}),y=!0),O.content&&(x.push({text:O.content}),y=!0)}}catch{}if((v||Date.now()-M>=150)&&y&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:_},x=[],M=Date.now(),y=!1),v)break}Date.now()-M>=150&&y&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:_},x=[],M=Date.now(),y=!1)}};var La=/```[\s\S]*?```/g,Pa=/```[\s\S]*$/g,$a=/`[^`]+`/g,Na=/^\|.*\|$/gm,Fa=/^[^\w]+|[^\w]+$/g,Ba=/[^a-z0-9]/gi,wo=/\[\s*(?:tool|action):(?:functions\.)?([a-z0-9_]+)\s*\(/gi,Ua=/\[\s*(?:tool:(?:functions\.)?|action:(?:functions\.)?|action:)([a-z0-9_]+)\s*\(/gi,Wa=/(?:path|targetFile|TargetFile|directory|keyword|id|taskId|title|task)\s*=\s*\\?["']?([^\\"' \),]+)/,Gn=/["']/g,Ur=/\\/g,Ha=/<\|channel>thought/gi,Ga=/<channel\|>/gi,ja=e=>typeof e!="string"?e:e.replace(Ha,"<think>").replace(Ga,"</think>"),cf=/^\s*(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\]|$)/i,Ka=(e,t,n=1)=>{let s=t>0?e[t-1]:"",o=t+n<e.length?e[t+n]:"";return s==="`"&&o==="`"},Va=e=>{let t=/(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\])/gi,n;for(;(n=t.exec(e))!==null;)if(!Ka(e,n.index,n[0].length))return{index:n.index,length:n[0].length};return{index:-1,length:0}},oi=e=>{if(!e||typeof e!="string")return null;let t=e.match(/^\s*(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought|\[(think|thought|thoughts)\])/i);if(!t)return null;let n=t.index+t[0].length,s=e.substring(n),o=Va(s);if(o.index!==-1){let c=n+o.index+o.length;return{fullBlock:e.substring(0,c),innerContent:s.substring(0,o.index),remainingText:e.substring(c)}}return{fullBlock:e,innerContent:s,remainingText:""}},qt=e=>{if(!e||typeof e!="string")return e;let t=oi(e);return t?t.remainingText.trimStart():e};var Yr=/`[^`]*`/g,qr=/`[^`]*$/,Wr=/<\|\s*tool_call_begin\s*\|>\s*(?:(?:tool|functions)\b[\s._]*)*([a-zA-Z0-9_]+)(?::\d+)?\s*<\|\s*tool_call_argument_begin\s*\|>([\s\S]*?)<\|\s*tool_call_end\s*\|>/gi,Ya=/"([^"]+)"\s*:\s*(?:"([^"]*)"|(\d+)|true|false|null)/g,Hr=/<\|\s*tool_calls_section_begin\s*\|>/gi,Gr=/<\|\s*tool_calls_section_end\s*\|>/gi,qa=/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi;var jr=e=>!e||typeof e!="string"?e:e.replace(/(```[\s\S]*?```|`[^`]*`)|(<(?:\w+)(?:[^>]*)>\r?\n?|\r?\n?<\/\w+(?:[^>]*)>)/gi,(t,n)=>n||""),zr=e=>{if(!e||typeof e!="string")return e;let t=ko(e);if(!t||t.length===0)return e;let n=t[t.length-1];if(!n.fullMatch)return e;let s=e.lastIndexOf(n.fullMatch);if(s===-1)return e;let o=s+n.fullMatch.length;return e.substring(0,o).trimEnd()},ii=null,as={},jn={key:null,value:null},Yt=e=>e&&e.replace(/(?:(\x1b\[\d+m))?([✔✘✖🔍📖→➕↻↷•🛇])(?:(\x1b\[\d+m))?\s*\b(Clicked|Located|Dragged|Scrolled|Typed|Pressed Key|Recaptured Screen|Created|Read Skill|Read Documentation|Searched Documentation|Read|Edited|Viewed|Processed|Auto-Read|Skipped|List|Generated|Written|Searched|AI Search|Get Map|Write Canceled|Resolved Sub-Agent Query|Edit Canceled|Write Cancelled|Edit Denied|Visited|Updated|Reviewed|Delegated|Background|Checked|Indexed|Analyzed|Browsed|Elevating SubAgent|Checking SubAgent Work|Started Generalist|Called Generalist|Steered|Unsupported Modality|Awaiting|Cancelled|Aligning Moon Phase|Contemplating Existence|Staring At Void|Rollback Point Checked|Emergency Rollback Failed|Emergency Rollback|Delaying Professionally|Negotiating With Electrons|Touching Grass (virtually)|Panicking Softly|Rethinking Career Choices|Loading Cat Videos|Giving Up Entirely|Summoning Braincell #2|Pretending To Be Busy|Waiting For Motivation DLC|Rotating Internal Screaming|Downloading More RAM|Feeding The Hamsters|Gaslighting Scheduler|Performing Dramatic Pause|Buffering Social Energy|Calculating Regret|Reading Terms And Conditions|Becoming Sentient Briefly|Execution Error|Loop Detected|Contacting Ancestors)\b/ig,(t,n,s,o,c)=>`${n||""}${s}${o||""} \x1B[95m${c}\x1B[0m`),za=async(e,t=8,n=1e3,s=8e3,o=null)=>{let c=0;for(;;){if(o?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{return await e()}catch(f){if(o?.aborted||f?.name==="AbortError"||f?.message==="Subagent task was cancelled."||(c++,c>=t))throw f;let l=Math.min(n*Math.pow(2,c-1),s);await new Promise((k,p)=>{let g=setTimeout(k,l);o&&o.addEventListener("abort",()=>{clearTimeout(g),p(new DOMException("The user aborted a request.","AbortError"))})})}}},wt=!1;var Xa=e=>{let t=e.filter(o=>(o.role==="user"||o.role==="agent"||o.role==="system")&&o.role!=="think"&&!o.isVisualFeedback&&!o.isMeta&&!o.isTerminalRecord&&!(o.text&&o.text.includes("[TERMINAL_RECORD]"))&&!String(o.id).startsWith("welcome")).map((o,c,f)=>{let l=o.fullText||o.text||"";if(o.role==="user"&&c<f.length-1)if(l.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")){let k=l.indexOf("**CONTEXT SUMMARY OF PREVIOUS TURNS");if(k!==-1){let g=l.substring(0,k).lastIndexOf("[SYSTEM METADATA]");g!==-1?l=l.substring(g).trim():l=l.substring(k).trim()}}else{let k=l.lastIndexOf("[USER]"),p=l.lastIndexOf("[USER PROMPT]");k!==-1?l=l.substring(k+6).trim():p!==-1&&(l=l.substring(p).trim())}return{...o,text:l}}),n=[],s=0;for(;s<t.length;){let o=t[s];if(o.role==="user")n.push(o),s++;else{let c=[];for(;s<t.length&&t[s].role!=="user";)c.push(t[s]),s++;let f=[],l=[],k=!1,p=()=>{f.length>0&&(n.push({role:"agent",text:"combined"}),f=[]),l.length>0&&(n.push({role:"system",text:"combined"}),l=[]),k=!1};c.forEach(g=>{let T=g.role==="system"&&(g.text?.startsWith("[ACTION RESULT]")||g.text?.startsWith("[TOOL RESULT]")||g.text?.startsWith("SUCCESS:")||g.text?.startsWith("ERROR:")||g.fullText?.startsWith("[ACTION RESULT]")||g.fullText?.startsWith("[TOOL RESULT]")||g.fullText?.startsWith("SUCCESS:")||g.fullText?.startsWith("ERROR:")),m=g.fullText||g.text||"",i=m.trim();if(!(!i&&!g.binaryPart)){if(T)l.push(i);else if(g.role==="agent"){!k&&l.length>0&&p();let u=m.endsWith(`
602
- `),w=i.toLowerCase().includes("tool:")||i.toLowerCase().includes("action:");f.push(i),w&&u?k=!0:k=!1}}}),p()}}return n.length},Ja=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),df=()=>{wt=!0},ff=()=>wt,si={write_file:"Writing",update_file:"Editing",read_folder:"Reading",view_file:"Reading",exec_command:"Executing Command",web_search:"Searching",web_scrape:"Reading",memory:"Updating Memory",search_keyword:"Searching",find_file:"Finding File",findFile:"Finding File",FindFile:"Finding File",file_map:"Generating Map",ask:"User Input",write_pdf:"Creating",write_docx:"Creating",generate_image:"Generating",todo:"Planning",Todo:"Planning",goal:"Planning",Goal:"Planning",invoke_sync:"Sub-Agent Working",invoke:"Starting Agent",get_progress:"Checking Progress",cancel:"Cancelling",await:"Waiting",EmergencyRollback:"Don't Panic. Lookin' into it",answer:"Answering Sub-Agent",Answer:"Answering Sub-Agent",steer:"Steering Sub-Agent",Steer:"Steering Sub-Agent",Click:"Clicking",click:"Clicking",Drag:"Dragging",drag:"Dragging",Scroll:"Scrolling",scroll:"Scrolling",KeyboardTyping:"Typing",keyboard_typing:"Typing",KeyPress:"Pressing Key",key_press:"Pressing Key",RecaptureScreen:"Recapturing Screen",recapture_screen:"Recapturing Screen"},Kn=(e,t)=>{try{let n=ne(t),s=e.toLowerCase().replace(/_/g,"");if(s==="invokesync"||s==="invoke")return n.title||(n.task?n.task.substring(0,30):null);if(s==="getprogress"||s==="cancel"||s==="steer"||s==="steersubagent")return n.id||n.taskId;let o=n.name||n.path||n.targetFile||n.TargetFile||n.directory||n.file||n.query;return o?ie.basename(o.replace(/["']/g,"").replace(/\\/g,"/")):null}catch{return null}},ri=e=>e?new Vr({apiKey:e}):ii,uf=async(e,t,n,s,o={})=>{let{onStatus:l,onMemoryUpdated:k,onBackgroundIncrement:p}=o,{profile:g,thinkingLevel:T,mode:m,janitorModel:i,chatId:u,systemSettings:w,sessionStats:I,aiProvider:h="Google",apiKey:A}=e,$=process.env.NVIDIA_BASE_URL||h==="Ollama"||h==="InferX"||h==="SenseNova"||h==="AIHubMix"||h==="Poolside"||h==="9router"||h==="ExpLabs"||h==="ExperientialLabs"?!1:w?.memory!==!1,x=Ct(Wn,[]).map(L=>`- [${L.id}]: ${L.memory}`).join(`
600
+ `);C=d.pop();for(let r of d){let E=r.trim();if(!E||!E.startsWith("data: "))continue;let v=!1;if(E==="data: [DONE]")v=!0;else try{let U=JSON.parse(E.substring(6)),O=U.choices?.[0]?.delta,P=U.usage;if(P&&(_={totalTokenCount:P.total_tokens||(P.prompt_tokens||0)+(P.completion_tokens||0),promptTokenCount:P.prompt_tokens||0,candidatesTokenCount:P.completion_tokens||0,cachedContentTokenCount:P.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:P.completion_tokens_details?.reasoning_tokens||P.reasoning_tokens||0},y=!0),O){let re=O.reasoning_content||O.reasoning||null;!re&&Array.isArray(O.reasoning_details)&&O.reasoning_details.length>0&&(re=O.reasoning_details.map(de=>de.text||"").filter(Boolean).join("")),re&&(x.push({text:re,thought:!0}),y=!0),O.content&&(x.push({text:O.content}),y=!0)}}catch{}if((v||Date.now()-M>=150)&&y&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:_},x=[],M=Date.now(),y=!1),v)break}Date.now()-M>=150&&y&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:_},x=[],M=Date.now(),y=!1)}};var La=/```[\s\S]*?```/g,Pa=/```[\s\S]*$/g,$a=/`[^`]+`/g,Na=/^\|.*\|$/gm,Fa=/^[^\w]+|[^\w]+$/g,Ba=/[^a-z0-9]/gi,wo=/\[\s*(?:tool|action):(?:functions\.)?([a-z0-9_]+)\s*\(/gi,Ua=/\[\s*(?:tool:(?:functions\.)?|action:(?:functions\.)?|action:)([a-z0-9_]+)\s*\(/gi,Wa=/(?:path|targetFile|TargetFile|directory|keyword|id|taskId|title|task)\s*=\s*\\?["']?([^\\"' \),]+)/,Gn=/["']/g,Br=/\\/g,Ha=/<\|channel>thought/gi,Ga=/<channel\|>/gi,ja=e=>typeof e!="string"?e:e.replace(Ha,"<think>").replace(Ga,"</think>"),cf=/^\s*(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\]|$)/i,Ka=(e,t,n=1)=>{let s=t>0?e[t-1]:"",o=t+n<e.length?e[t+n]:"";return s==="`"&&o==="`"},Va=e=>{let t=/(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\])/gi,n;for(;(n=t.exec(e))!==null;)if(!Ka(e,n.index,n[0].length))return{index:n.index,length:n[0].length};return{index:-1,length:0}},oi=e=>{if(!e||typeof e!="string")return null;let t=e.match(/^\s*(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought|\[(think|thought|thoughts)\])/i);if(!t)return null;let n=t.index+t[0].length,s=e.substring(n),o=Va(s);if(o.index!==-1){let c=n+o.index+o.length;return{fullBlock:e.substring(0,c),innerContent:s.substring(0,o.index),remainingText:e.substring(c)}}return{fullBlock:e,innerContent:s,remainingText:""}},qt=e=>{if(!e||typeof e!="string")return e;let t=oi(e);return t?t.remainingText.trimStart():e};var Vr=/`[^`]*`/g,Yr=/`[^`]*$/,Ur=/<\|\s*tool_call_begin\s*\|>\s*(?:(?:tool|functions)\b[\s._]*)*([a-zA-Z0-9_]+)(?::\d+)?\s*<\|\s*tool_call_argument_begin\s*\|>([\s\S]*?)<\|\s*tool_call_end\s*\|>/gi,Ya=/"([^"]+)"\s*:\s*(?:"([^"]*)"|(\d+)|true|false|null)/g,Wr=/<\|\s*tool_calls_section_begin\s*\|>/gi,Hr=/<\|\s*tool_calls_section_end\s*\|>/gi,qa=/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi;var Gr=e=>!e||typeof e!="string"?e:e.replace(/(```[\s\S]*?```|`[^`]*`)|(<(?:\w+)(?:[^>]*)>\r?\n?|\r?\n?<\/\w+(?:[^>]*)>)/gi,(t,n)=>n||""),qr=e=>{if(!e||typeof e!="string")return e;let t=ko(e);if(!t||t.length===0)return e;let n=t[t.length-1];if(!n.fullMatch)return e;let s=e.lastIndexOf(n.fullMatch);if(s===-1)return e;let o=s+n.fullMatch.length;return e.substring(0,o).trimEnd()},ii=null,as={},jn={key:null,value:null},Yt=e=>e&&e.replace(/(?:(\x1b\[\d+m))?([✔✘✖🔍📖→➕↻↷•🛇])(?:(\x1b\[\d+m))?\s*\b(Clicked|Located|Dragged|Scrolled|Typed|Pressed Key|Recaptured Screen|Created|Read Skill|Read Documentation|Searched Documentation|Read|Edited|Viewed|Processed|Auto-Read|Skipped|List|Generated|Written|Searched|AI Search|Get Map|Write Canceled|Resolved Sub-Agent Query|Edit Canceled|Write Cancelled|Edit Denied|Visited|Updated|Reviewed|Delegated|Background|Checked|Indexed|Analyzed|Browsed|Elevating SubAgent|Checking SubAgent Work|Started Generalist|Called Generalist|Steered|Unsupported Modality|Awaiting|Cancelled|Aligning Moon Phase|Contemplating Existence|Staring At Void|Rollback Point Checked|Emergency Rollback Failed|Emergency Rollback|Delaying Professionally|Negotiating With Electrons|Touching Grass (virtually)|Panicking Softly|Rethinking Career Choices|Loading Cat Videos|Giving Up Entirely|Summoning Braincell #2|Pretending To Be Busy|Waiting For Motivation DLC|Rotating Internal Screaming|Downloading More RAM|Feeding The Hamsters|Gaslighting Scheduler|Performing Dramatic Pause|Buffering Social Energy|Calculating Regret|Reading Terms And Conditions|Becoming Sentient Briefly|Execution Error|Loop Detected|Contacting Ancestors)\b/ig,(t,n,s,o,c)=>`${n||""}${s}${o||""} \x1B[95m${c}\x1B[0m`),za=async(e,t=8,n=1e3,s=8e3,o=null)=>{let c=0;for(;;){if(o?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{return await e()}catch(f){if(o?.aborted||f?.name==="AbortError"||f?.message==="Subagent task was cancelled."||(c++,c>=t))throw f;let l=Math.min(n*Math.pow(2,c-1),s);await new Promise((k,p)=>{let g=setTimeout(k,l);o&&o.addEventListener("abort",()=>{clearTimeout(g),p(new DOMException("The user aborted a request.","AbortError"))})})}}},wt=!1;var Xa=e=>{let t=e.filter(o=>(o.role==="user"||o.role==="agent"||o.role==="system")&&o.role!=="think"&&!o.isVisualFeedback&&!o.isMeta&&!o.isTerminalRecord&&!(o.text&&o.text.includes("[TERMINAL_RECORD]"))&&!String(o.id).startsWith("welcome")).map((o,c,f)=>{let l=o.fullText||o.text||"";if(o.role==="user"&&c<f.length-1)if(l.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")){let k=l.indexOf("**CONTEXT SUMMARY OF PREVIOUS TURNS");if(k!==-1){let g=l.substring(0,k).lastIndexOf("[SYSTEM METADATA]");g!==-1?l=l.substring(g).trim():l=l.substring(k).trim()}}else{let k=l.lastIndexOf("[USER]"),p=l.lastIndexOf("[USER PROMPT]");k!==-1?l=l.substring(k+6).trim():p!==-1&&(l=l.substring(p).trim())}return{...o,text:l}}),n=[],s=0;for(;s<t.length;){let o=t[s];if(o.role==="user")n.push(o),s++;else{let c=[];for(;s<t.length&&t[s].role!=="user";)c.push(t[s]),s++;let f=[],l=[],k=!1,p=()=>{f.length>0&&(n.push({role:"agent",text:"combined"}),f=[]),l.length>0&&(n.push({role:"system",text:"combined"}),l=[]),k=!1};c.forEach(g=>{let T=g.role==="system"&&(g.text?.startsWith("[ACTION RESULT]")||g.text?.startsWith("[TOOL RESULT]")||g.text?.startsWith("SUCCESS:")||g.text?.startsWith("ERROR:")||g.fullText?.startsWith("[ACTION RESULT]")||g.fullText?.startsWith("[TOOL RESULT]")||g.fullText?.startsWith("SUCCESS:")||g.fullText?.startsWith("ERROR:")),m=g.fullText||g.text||"",i=m.trim();if(!(!i&&!g.binaryPart)){if(T)l.push(i);else if(g.role==="agent"){!k&&l.length>0&&p();let u=m.endsWith(`
601
+ `),w=i.toLowerCase().includes("tool:")||i.toLowerCase().includes("action:");f.push(i),w&&u?k=!0:k=!1}}}),p()}}return n.length},Ja=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),df=()=>{wt=!0},ff=()=>wt,si={write_file:"Writing",update_file:"Editing",read_folder:"Reading",view_file:"Reading",exec_command:"Executing Command",web_search:"Searching",web_scrape:"Reading",memory:"Updating Memory",search_keyword:"Searching",find_file:"Finding File",findFile:"Finding File",FindFile:"Finding File",file_map:"Generating Map",ask:"User Input",write_pdf:"Creating",write_docx:"Creating",generate_image:"Generating",todo:"Planning",Todo:"Planning",goal:"Planning",Goal:"Planning",invoke_sync:"Sub-Agent Working",invoke:"Starting Agent",get_progress:"Checking Progress",cancel:"Cancelling",await:"Waiting",EmergencyRollback:"Don't Panic. Lookin' into it",answer:"Answering Sub-Agent",Answer:"Answering Sub-Agent",steer:"Steering Sub-Agent",Steer:"Steering Sub-Agent",Click:"Clicking",click:"Clicking",Drag:"Dragging",drag:"Dragging",Scroll:"Scrolling",scroll:"Scrolling",KeyboardTyping:"Typing",keyboard_typing:"Typing",KeyPress:"Pressing Key",key_press:"Pressing Key",RecaptureScreen:"Recapturing Screen",recapture_screen:"Recapturing Screen"},Kn=(e,t)=>{try{let n=ne(t),s=e.toLowerCase().replace(/_/g,"");if(s==="invokesync"||s==="invoke")return n.title||(n.task?n.task.substring(0,30):null);if(s==="getprogress"||s==="cancel"||s==="steer"||s==="steersubagent")return n.id||n.taskId;let o=n.name||n.path||n.targetFile||n.TargetFile||n.directory||n.file||n.query;return o?ie.basename(o.replace(/["']/g,"").replace(/\\/g,"/")):null}catch{return null}},ri=e=>e?new Kr({apiKey:e}):ii,uf=async(e,t,n,s,o={})=>{let{onStatus:l,onMemoryUpdated:k,onBackgroundIncrement:p}=o,{profile:g,thinkingLevel:T,mode:m,janitorModel:i,chatId:u,systemSettings:w,sessionStats:I,aiProvider:h="Google",apiKey:A}=e,$=process.env.NVIDIA_BASE_URL||h==="Ollama"||h==="InferX"||h==="SenseNova"||h==="AIHubMix"||h==="Poolside"||h==="9router"||h==="ExpLabs"||h==="ExperientialLabs"?!1:w?.memory!==!1,x=Ct(Wn,[]).map(L=>`- [${L.id}]: ${L.memory}`).join(`
603
602
  `),_=s.slice(0,-1).filter(L=>L.text&&!L.text.includes("[ACTION RESULT]")&&!L.text.includes("[TOOL RESULT]")&&!L.text.includes("OBSERVATION:")&&!L.text.startsWith("[TERMINAL_RECORD]")&&!L.isTerminalRecord&&!L.isMeta&&!L.isLogo&&!String(L.id).startsWith("welcome")&&!String(L.id).startsWith("logo")).slice(-14).map(L=>{let F=qt(Ja(L.text)).replace(/\[(?:tool|action):(?:functions\.)?.*?\]/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[METADATA \(PRIORITY: DYNAMIC\)\] Time: ([^|\n]+)/g,(G,ye)=>`[METADATA (PRIORITY: DYNAMIC)] Time: ${ye.replace(/:\d{2}/g,"")}`).replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[\[(?:TOOL|ACTION) RESULTS\]\]/gi,"").replace(/\[(?:TOOL|ACTION) RESULTS?\]/gi,"").replace(/\[(?:tool|action) results\]/gi,"").replace(/\r?\n\r?\n/g,`
604
603
  `).replace(/\n\n/g,`
605
604
  `).replace(/\\n\\n/g,"").trim(),Ee=L.role==="user"?8192:32768,oe=F.substring(0,Ee);F.length>Ee&&(oe+=`
606
- ... (truncated) ...`);let B=L.role==="user"?oe.startsWith("[USER]")?"":"[USER]: ":oe.startsWith("[AGENT]")?"":"[AGENT]: ";return{role:L.role==="user"?"user":"model",parts:[{text:`${B}${oe}`}]}}),M=s.filter(L=>L.role==="user").length===1,y=t.includes("[TITLE-UPDATE]"),a=Math.random()<.8,R=M||y||a,d=qt(n).trim(),r=gr(x,$,R),E=`${d.replace(/\[(?:tool|action):(?:functions\.)?.*?\]/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[\[(?:TOOL|ACTION) RESULTS\]\]/gi,"").replace(/\[(?:TOOL|ACTION) RESULTS?\]/gi,"").replace(/\[(?:tool|action) results\]/gi,"").substring(0,32768)}`;E.length>32768&&(E+=`
605
+ ... (truncated) ...`);let B=L.role==="user"?oe.startsWith("[USER]")?"":"[USER]: ":oe.startsWith("[AGENT]")?"":"[AGENT]: ";return{role:L.role==="user"?"user":"model",parts:[{text:`${B}${oe}`}]}}),M=s.filter(L=>L.role==="user").length===1,y=t.includes("[TITLE-UPDATE]"),a=Math.random()<.8,R=M||y||a,d=qt(n).trim(),r=ur(x,$,R),E=`${d.replace(/\[(?:tool|action):(?:functions\.)?.*?\]/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[\[(?:TOOL|ACTION) RESULTS\]\]/gi,"").replace(/\[(?:TOOL|ACTION) RESULTS?\]/gi,"").replace(/\[(?:tool|action) results\]/gi,"").substring(0,32768)}`;E.length>32768&&(E+=`
607
606
  ... (truncated) ...`);let v=t.replace(/\[Prompted on:.*?\]/g,"").trim();E=E.replace(/\r?\n\r?\n/g,`
608
607
  `).replace(/\n\n/g,`
609
608
  `).replace(/\\n\\n/g,"").trim();let U=new Date,P=`[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})}`}
@@ -612,11 +611,11 @@ ${T[7]}
612
611
  ${v.length>8192?`... (truncated) ...
613
612
 
614
613
  `:""}
615
- [AGENT (current turn)]: ${E}`;_.push({role:"user",parts:[{text:P}]});let re=await Ss("NVIDIA"),Q=(await ao()).quotas?.providerTiers?.NVIDIA==="Free",ke="",ae=0,it=$?12:-1;for(;ae<=it;)try{if(!await Ti("background",e))return;let L="",F=null,Ee=!1,oe=h;try{let ye=new Promise((Je,xe)=>setTimeout(()=>xe(new Error("JANITOR_TIMEOUT")),1e4)),Re=h==="Google"&&ae>=0&&ae<6&&re&&Q,ve=h==="DeepSeek"&&ae<4&&re&&Q;Ee=Re||ve,oe=Ee?"NVIDIA":h;let Ie=(async()=>{if(h==="OpenRouter"){let Je=pe("janitor_open_router"),te=es(A,Je,_,r,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),Wt=await te.next();return{iterator:te,firstResult:Wt}}else if(h==="DeepSeek"&&!Ee){let xe=Jo(A,pe("deepseek_fast_fallback"),_,r,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),te=await xe.next();return{iterator:xe,firstResult:te}}else if(h==="Mistral"&&!Ee){let xe=Qo(A,pe("mistral_janitor_fallback"),_,r,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),te=await xe.next();return{iterator:xe,firstResult:te}}else if(h==="NVIDIA"||Ee){let xe=Zo(Ee?re:A,pe("nvidia_janitor_fallback"),_,r,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),te=await xe.next();return{iterator:xe,firstResult:te}}else if(h==="InferX"){let xe=ts(A,targetModel||pe("inferx_fallback")||"deepseek-v4-flash",_,r,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),te=await xe.next();return{iterator:xe,firstResult:te}}else if(h==="SenseNova"){let xe=ns(A,targetModel||pe("sensenova_fallback")||"sensenova-6.8-flash-lite",_,r,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),te=await xe.next();return{iterator:xe,firstResult:te}}else if(h==="AIHubMix"){let xe=os(A,targetModel||pe("aihubmix_fallback")||"gpt-4o-mini",_,r,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),te=await xe.next();return{iterator:xe,firstResult:te}}else if(h==="Poolside"){let xe=ss(A,targetModel||pe("poolside_fallback")||"poolside/laguna-s-2.1",_,r,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),te=await xe.next();return{iterator:xe,firstResult:te}}else if(h==="9router"||h==="9Router"){let xe=is(A,targetModel||pe("9router_fallback")||"z-ai/glm-5.3-flash",_,r,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),te=await xe.next();return{iterator:xe,firstResult:te}}else if(h==="ExpLabs"||h==="ExperientialLabs"){let xe=rs(A,targetModel||pe("explabs_fallback")||"deepseek-v4-pro-0813",_,r,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),te=await xe.next();return{iterator:xe,firstResult:te}}else{let te=(await ri(A).models.generateContentStream({model:i||(ae===it?pe("janitor_default"):pe("gemma_janitor_fallback_google")),contents:_,config:{systemInstruction:r,temperature:.7,safetySettings:[{category:In.HARM_CATEGORY_HARASSMENT,threshold:Mn.BLOCK_NONE},{category:In.HARM_CATEGORY_HATE_SPEECH,threshold:Mn.BLOCK_NONE},{category:In.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Mn.BLOCK_NONE},{category:In.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Mn.BLOCK_NONE}],thinkingConfig:{includeThoughts:!1,thinkingLevel:Xe.MINIMAL},serviceTier:"flex"}}))[Symbol.asyncIterator](),Wt=await te.next();return{iterator:te,firstResult:Wt}}})();if(process.stdout.isTTY){let te=(await Cs())[u]?.name||"",Wt=te&&!te.startsWith("flow-")&&!te.startsWith("Session ")?te:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${Wt}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${Wt}\x07`)}let{iterator:Dn,firstResult:nn}=await Promise.race([Ie,ye]),{value:pt,done:kt}=nn;if(!kt&&pt){let Je=pt.candidates?.[0]?.content?.parts,xe=Je?oe==="Google"?Je[1]?.text||Je[0]?.text||"":Je.filter(te=>te.text&&!te.thought).map(te=>te.text).join(""):typeof pt.text=="function"?pt.text():"";xe&&(L+=xe),F=pt.usageMetadata;for await(let te of{[Symbol.asyncIterator]:()=>Dn}){let Wt=te.candidates?.[0]?.content?.parts,On=Wt?oe==="Google"?Wt[1]?.text||Wt[0]?.text||"":Wt.filter(Ln=>Ln.text&&!Ln.thought).map(Ln=>Ln.text).join(""):typeof te.text=="function"?te.text():"";On&&(L+=On),F=te.usageMetadata}}}catch(ye){throw ye}if(L){if(ke=L,F){let ye=F.totalTokenCount||0,Re=F.cachedContentTokenCount||0,ve=(F.candidatesTokenCount||0)+(oe==="Google"&&F.thoughtsTokenCount||0),Ie=Ee?pe("nvidia_janitor_fallback"):oe==="DeepSeek"?pe("deepseek_fast_fallback"):oe==="ExpLabs"||oe==="ExperientialLabs"?pe("explabs_fallback")||"deepseek-v4-pro-0813":oe==="OpenRouter"?pe("janitor_open_router"):i||(ae===it?pe("janitor_default"):pe("gemma_janitor_fallback_google"));await Bt("tokens",ye,oe,Ie),Re>0&&await Bt("cachedTokens",Re,oe,Ie),ve>0&&await Bt("candidateTokens",ve,oe,Ie),Do({provider:oe,model:Ie,prompt:F.promptTokenCount||0,cached:Re,output:ve,reasoning:F.thoughtsTokenCount||0})}}else throw new Error("No synthesis generated by Janitor.");p&&(p(),await Rt("background"));let B=ko(ke),G=!1;for(let ye of B){let Re=ye.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(Re)&&(G=!0);let ve={chatId:u,sessionId:u,history:s},Ie=await xo(Re,ye.args,ve);Re.toLowerCase()==="memory"&&(ye.args.includes("action='user'")||ye.args.includes('action="user"'))&&!Ie.startsWith("ERROR")&&(k&&k(),process.stdout.isTTY&&(process.stdout.write("\x1B]0;Memory Updated\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=Memory Updated\x07")),await new Promise(nn=>setTimeout(nn,3e3)))}if(!G)try{let ye=Ct(Wn,[]);if(ye.length>0){let Re=[];for(let ve of ye)ve.score===void 0&&(ve.score=.5),ve.score*=.99995,ve.score<.05&&(ve.score=0),ve.score=Math.round(ve.score*1e5)/1e5,ve.score>0&&Re.push(ve);Xn(Wn,Re)}}catch{}break}catch(L){ae++;let F=new Date().toLocaleString(),Ee=L instanceof Error?(()=>{try{return JSON.parse(JSON.parse(L.message).error.message).error.message}catch{return String(L)}})():String(L);await new Promise(G=>setTimeout(G,1e3));let oe=ie.join(Cn,"janitor");if(Ue.existsSync(oe)||Ue.mkdirSync(oe,{recursive:!0}),Ue.appendFileSync(ie.join(oe,"error.log"),`ERROR [Attempt ${ae}/${it+1}] [${F}]: ${Ee}
614
+ [AGENT (current turn)]: ${E}`;_.push({role:"user",parts:[{text:P}]});let re=await Ss("NVIDIA"),Q=(await ao()).quotas?.providerTiers?.NVIDIA==="Free",ke="",ae=0,it=$?12:-1;for(;ae<=it;)try{if(!await ki("background",e))return;let L="",F=null,Ee=!1,oe=h;try{let ye=new Promise((Je,xe)=>setTimeout(()=>xe(new Error("JANITOR_TIMEOUT")),1e4)),Re=h==="Google"&&ae>=0&&ae<6&&re&&Q,ve=h==="DeepSeek"&&ae<4&&re&&Q;Ee=Re||ve,oe=Ee?"NVIDIA":h;let Ie=(async()=>{if(h==="OpenRouter"){let Je=pe("janitor_open_router"),te=es(A,Je,_,r,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),Wt=await te.next();return{iterator:te,firstResult:Wt}}else if(h==="DeepSeek"&&!Ee){let xe=Jo(A,pe("deepseek_fast_fallback"),_,r,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),te=await xe.next();return{iterator:xe,firstResult:te}}else if(h==="Mistral"&&!Ee){let xe=Qo(A,pe("mistral_janitor_fallback"),_,r,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),te=await xe.next();return{iterator:xe,firstResult:te}}else if(h==="NVIDIA"||Ee){let xe=Zo(Ee?re:A,pe("nvidia_janitor_fallback"),_,r,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),te=await xe.next();return{iterator:xe,firstResult:te}}else if(h==="InferX"){let xe=ts(A,targetModel||pe("inferx_fallback")||"deepseek-v4-flash",_,r,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),te=await xe.next();return{iterator:xe,firstResult:te}}else if(h==="SenseNova"){let xe=ns(A,targetModel||pe("sensenova_fallback")||"sensenova-6.8-flash-lite",_,r,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),te=await xe.next();return{iterator:xe,firstResult:te}}else if(h==="AIHubMix"){let xe=os(A,targetModel||pe("aihubmix_fallback")||"gpt-4o-mini",_,r,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),te=await xe.next();return{iterator:xe,firstResult:te}}else if(h==="Poolside"){let xe=ss(A,targetModel||pe("poolside_fallback")||"poolside/laguna-s-2.1",_,r,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),te=await xe.next();return{iterator:xe,firstResult:te}}else if(h==="9router"||h==="9Router"){let xe=is(A,targetModel||pe("9router_fallback")||"z-ai/glm-5.3-flash",_,r,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),te=await xe.next();return{iterator:xe,firstResult:te}}else if(h==="ExpLabs"||h==="ExperientialLabs"){let xe=rs(A,targetModel||pe("explabs_fallback")||"deepseek-v4-pro-0813",_,r,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),te=await xe.next();return{iterator:xe,firstResult:te}}else{let te=(await ri(A).models.generateContentStream({model:i||(ae===it?pe("janitor_default"):pe("gemma_janitor_fallback_google")),contents:_,config:{systemInstruction:r,temperature:.7,safetySettings:[{category:In.HARM_CATEGORY_HARASSMENT,threshold:Mn.BLOCK_NONE},{category:In.HARM_CATEGORY_HATE_SPEECH,threshold:Mn.BLOCK_NONE},{category:In.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Mn.BLOCK_NONE},{category:In.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Mn.BLOCK_NONE}],thinkingConfig:{includeThoughts:!1,thinkingLevel:Xe.MINIMAL},serviceTier:"flex"}}))[Symbol.asyncIterator](),Wt=await te.next();return{iterator:te,firstResult:Wt}}})();if(process.stdout.isTTY){let te=(await Cs())[u]?.name||"",Wt=te&&!te.startsWith("flow-")&&!te.startsWith("Session ")?te:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${Wt}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${Wt}\x07`)}let{iterator:Dn,firstResult:nn}=await Promise.race([Ie,ye]),{value:pt,done:kt}=nn;if(!kt&&pt){let Je=pt.candidates?.[0]?.content?.parts,xe=Je?oe==="Google"?Je[1]?.text||Je[0]?.text||"":Je.filter(te=>te.text&&!te.thought).map(te=>te.text).join(""):typeof pt.text=="function"?pt.text():"";xe&&(L+=xe),F=pt.usageMetadata;for await(let te of{[Symbol.asyncIterator]:()=>Dn}){let Wt=te.candidates?.[0]?.content?.parts,On=Wt?oe==="Google"?Wt[1]?.text||Wt[0]?.text||"":Wt.filter(Ln=>Ln.text&&!Ln.thought).map(Ln=>Ln.text).join(""):typeof te.text=="function"?te.text():"";On&&(L+=On),F=te.usageMetadata}}}catch(ye){throw ye}if(L){if(ke=L,F){let ye=F.totalTokenCount||0,Re=F.cachedContentTokenCount||0,ve=(F.candidatesTokenCount||0)+(oe==="Google"&&F.thoughtsTokenCount||0),Ie=Ee?pe("nvidia_janitor_fallback"):oe==="DeepSeek"?pe("deepseek_fast_fallback"):oe==="ExpLabs"||oe==="ExperientialLabs"?pe("explabs_fallback")||"deepseek-v4-pro-0813":oe==="OpenRouter"?pe("janitor_open_router"):i||(ae===it?pe("janitor_default"):pe("gemma_janitor_fallback_google"));await Bt("tokens",ye,oe,Ie),Re>0&&await Bt("cachedTokens",Re,oe,Ie),ve>0&&await Bt("candidateTokens",ve,oe,Ie),Do({provider:oe,model:Ie,prompt:F.promptTokenCount||0,cached:Re,output:ve,reasoning:F.thoughtsTokenCount||0})}}else throw new Error("No synthesis generated by Janitor.");p&&(p(),await Rt("background"));let B=ko(ke),G=!1;for(let ye of B){let Re=ye.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(Re)&&(G=!0);let ve={chatId:u,sessionId:u,history:s},Ie=await xo(Re,ye.args,ve);Re.toLowerCase()==="memory"&&(ye.args.includes("action='user'")||ye.args.includes('action="user"'))&&!Ie.startsWith("ERROR")&&(k&&k(),process.stdout.isTTY&&(process.stdout.write("\x1B]0;Memory Updated\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=Memory Updated\x07")),await new Promise(nn=>setTimeout(nn,3e3)))}if(!G)try{let ye=Ct(Wn,[]);if(ye.length>0){let Re=[];for(let ve of ye)ve.score===void 0&&(ve.score=.5),ve.score*=.99995,ve.score<.05&&(ve.score=0),ve.score=Math.round(ve.score*1e5)/1e5,ve.score>0&&Re.push(ve);Xn(Wn,Re)}}catch{}break}catch(L){ae++;let F=new Date().toLocaleString(),Ee=L instanceof Error?(()=>{try{return JSON.parse(JSON.parse(L.message).error.message).error.message}catch{return String(L)}})():String(L);await new Promise(G=>setTimeout(G,1e3));let oe=ie.join(Cn,"janitor");if(Ue.existsSync(oe)||Ue.mkdirSync(oe,{recursive:!0}),Ue.appendFileSync(ie.join(oe,"error.log"),`ERROR [Attempt ${ae}/${it+1}] [${F}]: ${Ee}
616
615
 
617
616
  `),ae>it)break;let B=Math.min(750*Math.pow(2,ae-1),5e3);await new Promise(G=>setTimeout(G,B))}if(ae){let L=ie.join(Cn,"janitor");Ue.appendFileSync(ie.join(L,"error.log"),`-----------------------------------------------------------------------------
618
617
 
619
- `)}if(process.stdout.isTTY)try{let Ee=(await Cs())[u]?.name||"",oe=Ee&&!Ee.startsWith("flow-")&&!Ee.startsWith("Session ")?Ee:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${oe}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${oe}\x07`)}catch{process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")}},Qa=e=>{let t=qt(e),n=Es?t:t.replace(Yr,o=>" ".repeat(o.length)).replace(qr,o=>" ".repeat(o.length));wo.lastIndex=0;let s;for(;(s=wo.exec(n))!==null;){let o=s.index+s[0].length-1,c=0,f=null,l=!1,k=!1;for(let p=o;p<n.length;p++){let g=t[p];if(!f&&(g==='"'||g==="'"||g==="`")?(f=g,l=!1):f&&g===f&&!l&&(f=null),!f&&(g==="("?c++:g===")"&&c--,c===0)){let T=p+1;for(;T<n.length&&/\s/.test(n[T]);)T++;if(T<n.length&&n[T]==="]"){k=!0,wo.lastIndex=T+1;break}}g==="\\"?l=!l:l=!1}if(!k)return{inside:!0,toolName:s[1],startIndex:s.index,args:t.substring(s.index+s[0].length)}}return{inside:!1}},Xr=(e,t=!0)=>{let n=wo;n.lastIndex=0;let s="",o=0,c;for(;(c=n.exec(e))!==null;){let f=e.substring(o,c.index);s+=t&&o===0?qt(f):f;let l=c.index+c[0].length-1,k=0,p=null,g=-1;for(let T=l;T<e.length;T++){let m=e[T];if(p){if(m===p){let i=0;for(let u=T-1;u>=0&&e[u]==="\\";u--)i++;i%2===0&&(p=null)}}else if(m==='"'||m==="'"||m==="`")p=m;else if(m==="(")k++;else if(m===")"&&(k--,k===0)){let i=T+1;for(;i<e.length&&/\s/.test(e[i]);)i++;if(i<e.length&&e[i]==="]"){g=i;break}}}if(g!==-1)s+="[tool:functions."+c[1]+"()]",o=g+1,n.lastIndex=o;else{s+="[tool:functions."+c[1]+"(",o=e.length;break}}return o<e.length&&(s+=t&&o===0?qt(e.substring(o)):e.substring(o)),s},Za=(e,t,n)=>{let s=wo;s.lastIndex=0;let o="",c=0,f;for(;(f=s.exec(e))!==null;){let l=e.substring(c,f.index);o+=l.replace(t,n);let k=f.index+f[0].length-1,p=0,g=null,T=-1;for(let m=k;m<e.length;m++){let i=e[m];if(g){if(i===g){let u=0;for(let w=m-1;w>=0&&e[w]==="\\";w--)u++;u%2===0&&(g=null)}}else if(i==='"'||i==="'"||i==="`")g=i;else if(i==="(")p++;else if(i===")"&&(p--,p===0)){let u=m+1;for(;u<e.length&&/\s/.test(e[u]);)u++;if(u<e.length&&e[u]==="]"){T=u;break}}}if(T!==-1)o+=e.substring(f.index,T+1),c=T+1,s.lastIndex=c;else{o+=e.substring(f.index),c=e.length;break}}return c<e.length&&(o+=e.substring(c).replace(t,n)),o},Kr=e=>Xr(e,!0),el=e=>{if(!e)return e;let t={patchfile:"PatchFile",writefile:"WriteFile",readfile:"ReadFile",viewfile:"ReadFile",run:"Run",execcommand:"Run",searchkeyword:"SearchKeyword",codesearch:"CodeSearch",code_search:"CodeSearch",websearch:"WebSearch",webscrape:"WebScrape",readfolder:"ReadFolder",writepdf:"WritePDF",writedoc:"WriteDoc",writedocx:"WriteDoc",filemap:"FileMap",generateimage:"GenerateImage",todo:"Todo",goal:"Goal",askuser:"AskUser",ask:"AskUser"},n=o=>o.split("_").map(c=>c.charAt(0).toUpperCase()+c.slice(1)).join("");Wr.lastIndex=0;let s=e.replace(Wr,(o,c,f)=>{let l="";try{let g=JSON.parse(f.trim());g&&typeof g=="object"&&(l=Object.entries(g).map(([m,i])=>{let u=typeof i=="string"?i:JSON.stringify(i);return`${m}=${JSON.stringify(u)}`}).join(", "))}catch{let T=[],m=Ya;m.lastIndex=0;let i;for(;(i=m.exec(f))!==null;){let u=i[1],w=i[2]!==void 0?i[2]:i[0].split(":").slice(1).join(":").trim();T.push(`${u}=${JSON.stringify(w)}`)}T.length>0?l=T.join(", "):l=f.trim()}let k=c.toLowerCase().replace(/_/g,"");return`[tool:functions.${t[k]||n(c)}(${l})]`});return Hr.lastIndex=0,Gr.lastIndex=0,s=s.replace(Hr,""),s=s.replace(Gr,""),s},tl=/(?:path|query|url|keyword|command|method|title|task|id)\s*=\s*['"`]?\s*\.\.\.\s*['"`]?/i,nl=/^['"`]?\s*\.\.\.\s*['"`]?$/,bn=e=>{if(e==null)return!1;let t=String(e).trim();return t==="..."||t==="\u2026"||nl.test(t)},ko=e=>{if(!e)return[];let t=el(e),n=qt(t),s=[],o=Es?n:n.replace(Yr,l=>" ".repeat(l.length)).replace(qr,l=>" ".repeat(l.length)),c=Ua;c.lastIndex=0;let f;for(;(f=c.exec(o))!==null;){let l=f[1],k=f.index+f[0].length-1,p=0,g=null,T=-1,m=-1;for(let i=k;i<o.length;i++){let u=n[i];if(g){if(u===g){let w=0;for(let I=i-1;I>=0&&n[I]==="\\";I--)w++;w%2===0&&(g=null)}}else if(u==='"'||u==="'"||u==="`")g=u;else if(u==="(")p++;else if(u===")"&&(p--,p===0)){m=i;let w=i+1;for(;w<o.length&&/\s/.test(o[w]);)w++;if(w<o.length&&o[w]==="]"){T=w;break}}}if(T!==-1){let i=n.substring(k+1,m),u=n.substring(f.index,T+1),w=ne(i);bn(w.path)||bn(w.query)||bn(w.url)||bn(w.keyword)||bn(w.command)||bn(w.method)||bn(w.title)||bn(w.task)||bn(w.id)||tl.test(i)||s.push({fullMatch:u,toolName:l.trim(),args:i.trim()}),c.lastIndex=T+1}}return s},gf=(e,t={})=>{if(!e)return null;if(as=t,ii=new Vr({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}}}},Jr=e=>{if(!e)return{serviceTier:void 0,cleanModel:e};let t=e.toLowerCase();return t.endsWith(":flex")?{serviceTier:"flex",cleanModel:e.slice(0,-5)}:t.endsWith(":priority")?{serviceTier:"priority",cleanModel:e.slice(0,-9)}:{serviceTier:void 0,cleanModel:e}},ls=async(e,t,n,s,o="Fast",c=.75,f="agent")=>za(async()=>{let{aiProvider:l="Google",apiKey:k,mode:p}=e,g="",T=null,m=typeof n=="string"?[{role:"user",parts:[{text:n}]}]:n,i=new AbortController,u=i.signal,w=setInterval(()=>{wt&&(i.abort(),clearInterval(w))},100);try{let I;if(l==="Ollama")I=ei(k,t,m,s,o,p,ft(t),u,c,e.systemSettings?.ollamaEndpoint||"Cloud");else if(l==="OpenRouter")I=es(k,t,m,s,o,p,ft(t),u,c);else if(l==="DeepSeek")I=Jo(k,t,m,s,o,p,ft(t),u,c);else if(l==="Mistral")I=Qo(k,t,m,s,o,p,ft(t),u,c);else if(l==="NVIDIA")I=Zo(k,t,m,s,o,p,ft(t),u,c);else if(l==="InferX")I=ts(k,t,m,s,o,p,ft(t),u,c);else if(l==="SenseNova")I=ns(k,t,m,s,o,p,ft(t),u,c);else if(l==="AIHubMix")I=os(k,t,m,s,o,p,ft(t),u,c);else if(l==="Poolside")I=ss(k,t,m,s,o,p,ft(t),u,c);else if(l==="9router"||l==="9Router")I=is(k,t,m,s,o,p,ft(t),u,c);else if(l==="ExpLabs"||l==="ExperientialLabs")I=rs(k,t,m,s,o,p,ft(t),u,c);else if(l==="TokenHarbor"||l==="Token Harbor"||l==="tokenharbor"||l==="token_harbor"||l==="thk")I=ti(k,t,m,s,o,p,ft(t),u,c);else if(l==="APInex"||l==="apinex"||l==="apx")I=ni(k,t,m,s,o,p,ft(t),u,c);else{let h=ri(k),{serviceTier:A,cleanModel:$}=Jr(t),C={systemInstruction:s,temperature:c,thinkingConfig:(()=>{let _=(t||"").toLowerCase(),M=_.includes("gemma-4")||_.startsWith("gemma"),y=_.includes("gemini-3");if(M||y)return M?o.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:Xe.MINIMAL}:{includeThoughts:!0,thinkingLevel:Xe.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:_.includes("pro")?Xe.LOW:Xe.MINIMAL,Low:Xe.LOW,Medium:Xe.MEDIUM,Standard:Xe.MEDIUM,High:Xe.HIGH,xHigh:Xe.HIGH}[o]||Xe.MEDIUM};{let a={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[o]||2048;return a===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:a}}})()};A&&(C.serviceTier=A),I=await h.models.generateContentStream({model:$,contents:m,config:C},{signal:u})}for await(let h of I){if(wt)throw new Error("Subagent task was cancelled.");if(e?.taskId&&typeof Vt<"u"){let C=Vt.find(x=>x.id===e.taskId);if(C&&C.status==="cancelled")throw new Error("Subagent task was cancelled.")}let A="";if(h.candidates?.[0]?.content?.parts)for(let C of h.candidates[0].content.parts)C.text&&!C.thought&&(g+=C.text,A+=C.text);let $=A?As(A):0;e&&typeof e.onTokenChunk=="function"&&e.onTokenChunk(A,$),h.usageMetadata&&(T=h.usageMetadata)}}finally{clearInterval(w)}if(T){let I=T.totalTokenCount||0,h=T.cachedContentTokenCount||0,A=(T.candidatesTokenCount||0)+(l==="Google"&&T.thoughtsTokenCount||0);await Bt("tokens",I,l,t),h>0&&await Bt("cachedTokens",h,l,t),A>0&&await Bt("candidateTokens",A,l,t),Do({provider:l,model:t,prompt:T.promptTokenCount||0,cached:h,output:A,reasoning:T.thoughtsTokenCount||0}),e&&typeof e.onUsage=="function"&&e.onUsage({totalTokenCount:I,cachedContentTokenCount:h,candidatesTokenCount:A})}return await Rt("agent",l),{text:g,usageMetadata:T}}),ol=async(e,t,n=null)=>{n=n||Ct(vo,{});try{let{aiProvider:s="Google"}=t;if(Object.values(n).flat().length<=5)return;let c=Object.keys(n).filter(m=>m!==e&&Array.isArray(n[m])&&n[m].length>2);if(c.length===0)return;let f=`You are a silent background process for the FluxFlow CLI Agent.
618
+ `)}if(process.stdout.isTTY)try{let Ee=(await Cs())[u]?.name||"",oe=Ee&&!Ee.startsWith("flow-")&&!Ee.startsWith("Session ")?Ee:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${oe}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${oe}\x07`)}catch{process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")}},Qa=e=>{let t=qt(e),n=Es?t:t.replace(Vr,o=>" ".repeat(o.length)).replace(Yr,o=>" ".repeat(o.length));wo.lastIndex=0;let s;for(;(s=wo.exec(n))!==null;){let o=s.index+s[0].length-1,c=0,f=null,l=!1,k=!1;for(let p=o;p<n.length;p++){let g=t[p];if(!f&&(g==='"'||g==="'"||g==="`")?(f=g,l=!1):f&&g===f&&!l&&(f=null),!f&&(g==="("?c++:g===")"&&c--,c===0)){let T=p+1;for(;T<n.length&&/\s/.test(n[T]);)T++;if(T<n.length&&n[T]==="]"){k=!0,wo.lastIndex=T+1;break}}g==="\\"?l=!l:l=!1}if(!k)return{inside:!0,toolName:s[1],startIndex:s.index,args:t.substring(s.index+s[0].length)}}return{inside:!1}},zr=(e,t=!0)=>{let n=wo;n.lastIndex=0;let s="",o=0,c;for(;(c=n.exec(e))!==null;){let f=e.substring(o,c.index);s+=t&&o===0?qt(f):f;let l=c.index+c[0].length-1,k=0,p=null,g=-1;for(let T=l;T<e.length;T++){let m=e[T];if(p){if(m===p){let i=0;for(let u=T-1;u>=0&&e[u]==="\\";u--)i++;i%2===0&&(p=null)}}else if(m==='"'||m==="'"||m==="`")p=m;else if(m==="(")k++;else if(m===")"&&(k--,k===0)){let i=T+1;for(;i<e.length&&/\s/.test(e[i]);)i++;if(i<e.length&&e[i]==="]"){g=i;break}}}if(g!==-1)s+="[tool:functions."+c[1]+"()]",o=g+1,n.lastIndex=o;else{s+="[tool:functions."+c[1]+"(",o=e.length;break}}return o<e.length&&(s+=t&&o===0?qt(e.substring(o)):e.substring(o)),s},Za=(e,t,n)=>{let s=wo;s.lastIndex=0;let o="",c=0,f;for(;(f=s.exec(e))!==null;){let l=e.substring(c,f.index);o+=l.replace(t,n);let k=f.index+f[0].length-1,p=0,g=null,T=-1;for(let m=k;m<e.length;m++){let i=e[m];if(g){if(i===g){let u=0;for(let w=m-1;w>=0&&e[w]==="\\";w--)u++;u%2===0&&(g=null)}}else if(i==='"'||i==="'"||i==="`")g=i;else if(i==="(")p++;else if(i===")"&&(p--,p===0)){let u=m+1;for(;u<e.length&&/\s/.test(e[u]);)u++;if(u<e.length&&e[u]==="]"){T=u;break}}}if(T!==-1)o+=e.substring(f.index,T+1),c=T+1,s.lastIndex=c;else{o+=e.substring(f.index),c=e.length;break}}return c<e.length&&(o+=e.substring(c).replace(t,n)),o},jr=e=>zr(e,!0),el=e=>{if(!e)return e;let t={patchfile:"PatchFile",writefile:"WriteFile",readfile:"ReadFile",viewfile:"ReadFile",run:"Run",execcommand:"Run",searchkeyword:"SearchKeyword",codesearch:"CodeSearch",code_search:"CodeSearch",websearch:"WebSearch",webscrape:"WebScrape",readfolder:"ReadFolder",writepdf:"WritePDF",writedoc:"WriteDoc",writedocx:"WriteDoc",filemap:"FileMap",generateimage:"GenerateImage",todo:"Todo",goal:"Goal",askuser:"AskUser",ask:"AskUser"},n=o=>o.split("_").map(c=>c.charAt(0).toUpperCase()+c.slice(1)).join("");Ur.lastIndex=0;let s=e.replace(Ur,(o,c,f)=>{let l="";try{let g=JSON.parse(f.trim());g&&typeof g=="object"&&(l=Object.entries(g).map(([m,i])=>{let u=typeof i=="string"?i:JSON.stringify(i);return`${m}=${JSON.stringify(u)}`}).join(", "))}catch{let T=[],m=Ya;m.lastIndex=0;let i;for(;(i=m.exec(f))!==null;){let u=i[1],w=i[2]!==void 0?i[2]:i[0].split(":").slice(1).join(":").trim();T.push(`${u}=${JSON.stringify(w)}`)}T.length>0?l=T.join(", "):l=f.trim()}let k=c.toLowerCase().replace(/_/g,"");return`[tool:functions.${t[k]||n(c)}(${l})]`});return Wr.lastIndex=0,Hr.lastIndex=0,s=s.replace(Wr,""),s=s.replace(Hr,""),s},tl=/(?:path|query|url|keyword|command|method|title|task|id)\s*=\s*['"`]?\s*\.\.\.\s*['"`]?/i,nl=/^['"`]?\s*\.\.\.\s*['"`]?$/,bn=e=>{if(e==null)return!1;let t=String(e).trim();return t==="..."||t==="\u2026"||nl.test(t)},ko=e=>{if(!e)return[];let t=el(e),n=qt(t),s=[],o=Es?n:n.replace(Vr,l=>" ".repeat(l.length)).replace(Yr,l=>" ".repeat(l.length)),c=Ua;c.lastIndex=0;let f;for(;(f=c.exec(o))!==null;){let l=f[1],k=f.index+f[0].length-1,p=0,g=null,T=-1,m=-1;for(let i=k;i<o.length;i++){let u=n[i];if(g){if(u===g){let w=0;for(let I=i-1;I>=0&&n[I]==="\\";I--)w++;w%2===0&&(g=null)}}else if(u==='"'||u==="'"||u==="`")g=u;else if(u==="(")p++;else if(u===")"&&(p--,p===0)){m=i;let w=i+1;for(;w<o.length&&/\s/.test(o[w]);)w++;if(w<o.length&&o[w]==="]"){T=w;break}}}if(T!==-1){let i=n.substring(k+1,m),u=n.substring(f.index,T+1),w=ne(i);bn(w.path)||bn(w.query)||bn(w.url)||bn(w.keyword)||bn(w.command)||bn(w.method)||bn(w.title)||bn(w.task)||bn(w.id)||tl.test(i)||s.push({fullMatch:u,toolName:l.trim(),args:i.trim()}),c.lastIndex=T+1}}return s},gf=(e,t={})=>{if(!e)return null;if(as=t,ii=new Kr({apiKey:e}),!globalThis.__perfCleanupInstalled){globalThis.__perfCleanupInstalled=!0,setInterval(()=>{typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks())},6e4);let n=globalThis.fetch;globalThis.fetch=async(...s)=>{try{let o=await n(...s);return typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),o}catch(o){throw typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),o}}}},Xr=e=>{if(!e)return{serviceTier:void 0,cleanModel:e};let t=e.toLowerCase();return t.endsWith(":flex")?{serviceTier:"flex",cleanModel:e.slice(0,-5)}:t.endsWith(":priority")?{serviceTier:"priority",cleanModel:e.slice(0,-9)}:{serviceTier:void 0,cleanModel:e}},ls=async(e,t,n,s,o="Fast",c=.75,f="agent")=>za(async()=>{let{aiProvider:l="Google",apiKey:k,mode:p}=e,g="",T=null,m=typeof n=="string"?[{role:"user",parts:[{text:n}]}]:n,i=new AbortController,u=i.signal,w=setInterval(()=>{wt&&(i.abort(),clearInterval(w))},100);try{let I;if(l==="Ollama")I=ei(k,t,m,s,o,p,ft(t),u,c,e.systemSettings?.ollamaEndpoint||"Cloud");else if(l==="OpenRouter")I=es(k,t,m,s,o,p,ft(t),u,c);else if(l==="DeepSeek")I=Jo(k,t,m,s,o,p,ft(t),u,c);else if(l==="Mistral")I=Qo(k,t,m,s,o,p,ft(t),u,c);else if(l==="NVIDIA")I=Zo(k,t,m,s,o,p,ft(t),u,c);else if(l==="InferX")I=ts(k,t,m,s,o,p,ft(t),u,c);else if(l==="SenseNova")I=ns(k,t,m,s,o,p,ft(t),u,c);else if(l==="AIHubMix")I=os(k,t,m,s,o,p,ft(t),u,c);else if(l==="Poolside")I=ss(k,t,m,s,o,p,ft(t),u,c);else if(l==="9router"||l==="9Router")I=is(k,t,m,s,o,p,ft(t),u,c);else if(l==="ExpLabs"||l==="ExperientialLabs")I=rs(k,t,m,s,o,p,ft(t),u,c);else if(l==="TokenHarbor"||l==="Token Harbor"||l==="tokenharbor"||l==="token_harbor"||l==="thk")I=ti(k,t,m,s,o,p,ft(t),u,c);else if(l==="APInex"||l==="apinex"||l==="apx")I=ni(k,t,m,s,o,p,ft(t),u,c);else{let h=ri(k),{serviceTier:A,cleanModel:$}=Xr(t),C={systemInstruction:s,temperature:c,thinkingConfig:(()=>{let _=(t||"").toLowerCase(),M=_.includes("gemma-4")||_.startsWith("gemma"),y=_.includes("gemini-3");if(M||y)return M?o.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:Xe.MINIMAL}:{includeThoughts:!0,thinkingLevel:Xe.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:_.includes("pro")?Xe.LOW:Xe.MINIMAL,Low:Xe.LOW,Medium:Xe.MEDIUM,Standard:Xe.MEDIUM,High:Xe.HIGH,xHigh:Xe.HIGH}[o]||Xe.MEDIUM};{let a={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[o]||2048;return a===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:a}}})()};A&&(C.serviceTier=A),I=await h.models.generateContentStream({model:$,contents:m,config:C},{signal:u})}for await(let h of I){if(wt)throw new Error("Subagent task was cancelled.");if(e?.taskId&&typeof Vt<"u"){let C=Vt.find(x=>x.id===e.taskId);if(C&&C.status==="cancelled")throw new Error("Subagent task was cancelled.")}let A="";if(h.candidates?.[0]?.content?.parts)for(let C of h.candidates[0].content.parts)C.text&&!C.thought&&(g+=C.text,A+=C.text);let $=A?As(A):0;e&&typeof e.onTokenChunk=="function"&&e.onTokenChunk(A,$),h.usageMetadata&&(T=h.usageMetadata)}}finally{clearInterval(w)}if(T){let I=T.totalTokenCount||0,h=T.cachedContentTokenCount||0,A=(T.candidatesTokenCount||0)+(l==="Google"&&T.thoughtsTokenCount||0);await Bt("tokens",I,l,t),h>0&&await Bt("cachedTokens",h,l,t),A>0&&await Bt("candidateTokens",A,l,t),Do({provider:l,model:t,prompt:T.promptTokenCount||0,cached:h,output:A,reasoning:T.thoughtsTokenCount||0}),e&&typeof e.onUsage=="function"&&e.onUsage({totalTokenCount:I,cachedContentTokenCount:h,candidatesTokenCount:A})}return await Rt("agent",l),{text:g,usageMetadata:T}}),ol=async(e,t,n=null)=>{n=n||Ct(vo,{});try{let{aiProvider:s="Google"}=t;if(Object.values(n).flat().length<=5)return;let c=Object.keys(n).filter(m=>m!==e&&Array.isArray(n[m])&&n[m].length>2);if(c.length===0)return;let f=`You are a silent background process for the FluxFlow CLI Agent.
620
619
  Your task is to summarize or merge temporary context memories from one or more past conversation sessions.
621
620
  For each Chat ID provided, you must output a tool call to save the consolidated summary.
622
621
 
@@ -663,8 +662,8 @@ ${On}
663
662
  [SYSTEM METADATA]
664
663
  **CONTEXT SUMMARY OF PREVIOUS TURNS**
665
664
  ${On}
666
- `:"",ai=!!T?.dynamicDirAwareness,Qr=`${p}|${i}|${f}|${e}|${c}|${ai}`,li=!ai&&jn.key===Qr&&jn.value?"":`
667
- **Directory Structure**
665
+ `:"",ai=!!T?.dynamicDirAwareness,Jr=`${p}|${i}|${f}|${e}|${c}|${ai}`,Qr=!ai&&jn.key===Jr&&jn.value?"":`
666
+ **Directory**
668
667
  CWD: `+process.cwd()+`${g?" [PLAYGROUND MODE]":""}
669
668
  `+nn(process.cwd(),4),yt=await Hn(),dn="";if(zo()&&yt.file_focused!=="none"){dn=`
670
669
  [Additional IDE Context]
@@ -695,10 +694,10 @@ ${yt.diagnostics}
695
694
  `),(a.toLowerCase().includes("lint")||a.toLowerCase().includes("warning"))&&yt.warnings&&(dn+=`
696
695
  **Lint Warnings**:
697
696
  ${yt.warnings}
698
- `)}let ci=a.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),di=/(?:\\)?@\[([^\]]+)\]/g,ds,fs=[];for(di.lastIndex=0;(ds=di.exec(ci))!==null;){let j=ds[0].startsWith("\\");fs.push({tag:ds[1],isEscaped:j})}let us=[],To=null;for(let j=0;j<fs.length;j++){let{tag:Ke,isEscaped:fn}=fs[j];if(!fn)try{let ot=Ke.trim().replace(/^["']|["']$/g,""),Fe=/[:#]L?(\d+)(?:-L?(\d+))?$/i,st=ot.match(Fe),et=ot,rt=null,Te=null;st&&(rt=parseInt(st[1],10),Te=st[2]?parseInt(st[2],10):rt,et=ot.slice(0,st.index));let Ve=ie.resolve(process.cwd(),et);if(Ue.existsSync(Ve)&&Ue.statSync(Ve).isFile()){let K=et.toLowerCase(),We=K.endsWith(".pdf"),Me=K.endsWith(".docx")||K.endsWith(".doc")||K.endsWith(".ppt")||K.endsWith(".pptx")||K.endsWith(".xls")||K.endsWith(".xlsx"),ut=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(K),kn=ut||We||Me,vt=i==="Google"||ft(e);if(kn&&!vt){let Ot=`\u2718 Unsupported Modality: ${ie.basename(et)}`,Ye=115;process.stdout.isTTY&&(Ye=process.stdout.columns-5||120);let Se=[Ot],qe=Math.max(...Se.map(un=>un.length)),Sn=Math.min(qe+4,Ye),Pn=Se.map(un=>`${un.padEnd(Sn-2).substring(0,Sn-2)}`).join(`
697
+ `)}let li=a.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),ci=/(?:\\)?@\[([^\]]+)\]/g,ds,fs=[];for(ci.lastIndex=0;(ds=ci.exec(li))!==null;){let j=ds[0].startsWith("\\");fs.push({tag:ds[1],isEscaped:j})}let us=[],To=null;for(let j=0;j<fs.length;j++){let{tag:Ke,isEscaped:fn}=fs[j];if(!fn)try{let ot=Ke.trim().replace(/^["']|["']$/g,""),Fe=/[:#]L?(\d+)(?:-L?(\d+))?$/i,st=ot.match(Fe),et=ot,rt=null,Te=null;st&&(rt=parseInt(st[1],10),Te=st[2]?parseInt(st[2],10):rt,et=ot.slice(0,st.index));let Ve=ie.resolve(process.cwd(),et);if(Ue.existsSync(Ve)&&Ue.statSync(Ve).isFile()){let K=et.toLowerCase(),We=K.endsWith(".pdf"),Me=K.endsWith(".docx")||K.endsWith(".doc")||K.endsWith(".ppt")||K.endsWith(".pptx")||K.endsWith(".xls")||K.endsWith(".xlsx"),ut=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(K),kn=ut||We||Me,vt=i==="Google"||ft(e);if(kn&&!vt){let Ot=`\u2718 Unsupported Modality: ${ie.basename(et)}`,Ye=115;process.stdout.isTTY&&(Ye=process.stdout.columns-5||120);let Se=[Ot],qe=Math.max(...Se.map(un=>un.length)),Sn=Math.min(qe+4,Ye),Pn=Se.map(un=>`${un.padEnd(Sn-2).substring(0,Sn-2)}`).join(`
699
698
  `);yield{type:"visual_feedback",content:Yt(`${Pn}
700
699
  `)};continue}if(rt===null&&!kn){let Ot=0;try{Ot=Ue.readFileSync(Ve,"utf8").split(/\r\n|\r|\n/).length}catch{}if(Ot>300){let Ye=`\u21B7 Skipped (Too Large): ${ie.basename(et)}`,Se=115;process.stdout.isTTY&&(Se=process.stdout.columns-5||120);let qe=Math.min(Ye.length+4,Se),Sn=Ye.padEnd(qe-2).substring(0,qe-2);yield{type:"visual_feedback",content:Yt(`${Sn}
701
- `)};continue}}let rn=rt!==null?rt:1,Tn=Te!==null?Te:rt!==null?rt:rn+299;Tn-rn>300&&(Tn=rn+300);let Zn=`path=${JSON.stringify(et)}, startLine=${rn}, endLine=${Tn}`,Qt=await vi(Zn,{isMultiModal:vt}),xt=!1,Qe="",Dt=null;if(typeof Qt=="string"?Qt.trim().startsWith("ERROR")?xt=!0:Qe=Qt:Qt&&typeof Qt=="object"&&Qt.binaryPart?(Dt=Qt.binaryPart,Qe=Qt.text||""):xt=!0,!xt){let Ot="";if(ut?(Ot=`\u2714 Processed: ${ie.basename(et)}`,To=Dt):We||Me?(Ot=`\u2714 Auto-Analysed: ${ie.basename(et)}`,To=Dt):(Ot=`\u2714 Auto-Read: ${ie.basename(et)}`,us.push(Qe)),Ot){let Ye=115;process.stdout.isTTY&&(Ye=process.stdout.columns-5||120);let Se=[Ot],qe=Math.max(...Se.map(un=>un.length)),Sn=Math.min(qe+4,Ye),Pn=Se.map(un=>`${un.padEnd(Sn-2).substring(0,Sn-2)}`).join(`
700
+ `)};continue}}let rn=rt!==null?rt:1,Tn=Te!==null?Te:rt!==null?rt:rn+299;Tn-rn>300&&(Tn=rn+300);let Zn=`path=${JSON.stringify(et)}, startLine=${rn}, endLine=${Tn}`,Qt=await Ri(Zn,{isMultiModal:vt}),xt=!1,Qe="",Dt=null;if(typeof Qt=="string"?Qt.trim().startsWith("ERROR")?xt=!0:Qe=Qt:Qt&&typeof Qt=="object"&&Qt.binaryPart?(Dt=Qt.binaryPart,Qe=Qt.text||""):xt=!0,!xt){let Ot="";if(ut?(Ot=`\u2714 Processed: ${ie.basename(et)}`,To=Dt):We||Me?(Ot=`\u2714 Auto-Analysed: ${ie.basename(et)}`,To=Dt):(Ot=`\u2714 Auto-Read: ${ie.basename(et)}`,us.push(Qe)),Ot){let Ye=115;process.stdout.isTTY&&(Ye=process.stdout.columns-5||120);let Se=[Ot],qe=Math.max(...Se.map(un=>un.length)),Sn=Math.min(qe+4,Ye),Pn=Se.map(un=>`${un.padEnd(Sn-2).substring(0,Sn-2)}`).join(`
702
701
  `);yield{type:"visual_feedback",content:Yt(`${Pn}
703
702
  `)}}}}}catch{}}let gs="";us.length>0&&(gs=`
704
703
  [Tagged File Contents] Auto Read User Tagged files by System, No need to re-read
@@ -706,17 +705,17 @@ ${yt.warnings}
706
705
 
707
706
  `)+`
708
707
  [Tagged File Contents]
709
- `);let fi=ci.replace(/\\(@\[[^\]]+\])/g,"$1"),ui=w?`You cannot execute tools. Instead write the action string in chat you WOULD have written
710
- `:"",Zr=process.env.forcedReasoning||!1,gi=f!=="Fast"&&(i==="Mistral"&&!Io(e)||f!=="High"&&i==="Google")?`${i==="Mistral"&&!Io(e)||e.toLowerCase().startsWith("gemma")||Zr?`[system] strictly follow thinking policy as high priority. do not start a response without <think>...</think> [/system]
711
- `:""}`:"",So="",hi=!!T?.autoExcludeMetadata,ea=!!(dn||gs||ui||cs||gi||Je||T?.dynamicDirAwareness||T?.autoTruncateResults);hi&&!ea?So=fi.trim():So=`[System Metadata]
712
- Time: ${hi?ve:Re}${T?.dynamicDirAwareness?li:""}${Je?`
708
+ `);let di=li.replace(/\\(@\[[^\]]+\])/g,"$1"),fi=w?`You cannot execute tools. Instead write the action string in chat you WOULD have written
709
+ `:"",Zr=process.env.forcedReasoning||!1,ui=f!=="Fast"&&(i==="Mistral"&&!Io(e)||f!=="High"&&i==="Google")?`${i==="Mistral"&&!Io(e)||e.toLowerCase().startsWith("gemma")||Zr?`[system] strictly follow thinking policy as high priority. do not start a response without <think>...</think> [/system]
710
+ `:""}`:"",So="",gi=!!T?.autoExcludeMetadata,ea=!!(dn||gs||fi||cs||ui||Je||T?.dynamicDirAwareness||T?.autoTruncateResults);gi&&!ea?So=di.trim():So=`[System Metadata]
711
+ Time: ${gi?ve:Re}${Je?`
713
712
  WARNING: CWD Changed from previous: "${kt}" to current: "${process.cwd()}", write change in chat to avoid future path mismatches
714
713
  `:""}${dn}
715
714
  Action format: [action:ActionName(...)]
716
715
  [/Metadata]
717
- ${cs}${gi}${gs}${ui}[user prompt] ${fi.trim()} [/user prompt]`.trim();let mi={role:"user",text:So};To&&(mi.binaryPart=To),r.forEach(j=>{j.text&&j.role==="agent"&&(j.text=qt(j.text))}),r.push(mi),cs&&t[t.length-1]?.id&&(yield{type:"summary_injected",content:{id:t[t.length-1].id,text:So}});let Jt=null,wn=l==="Flux"?50:15;wn=l.toLowerCase().includes("cu")?75:wn;let ta=Math.floor(wn/2),pi=0,on=16;yield{type:"status",content:"Connecting"},wt=!1;let hs=[],_o=!1,yi=!1;for(let j=0;j<=wn;j++){let Ke=Math.floor(wn*.95);if(j>=Ke&&pi<Ke&&typeof n?.onAskUser=="function"){pi=Ke;try{let me="Agent has been running for a long time. Do you want to continue execution?",Ae=[{id:"continue",label:"Continue",description:"Add few more steps"},{id:"cancel",label:"Cancel",description:"Stop extending and finish current turn limit"}],ee=await n.onAskUser(me,Ae);ee&&(ee.toLowerCase().includes("continue")||ee==="Continue")&&(wn+=ta)}catch{}}let fn=await _s("agent",n);if(!fn.allowed)throw new Error(fn.reason||`Budget Exhausted for Provider (${i||"Agent"})`);let ot=[];if(_o=!1,l==="ICU"||l==="FluxCU")try{yield{type:"status",content:"Capturing Screen"},await new Promise(ee=>setTimeout(ee,1e3));let{captureGriddedScreenshot:me}=await import("./screen_grid-GBIGOR5Q.js"),Ae=await me();if(Ae&&Ae.base64){let ee="[system] Fresh Gridded Screen Feedback Captured. Use numeric coordinates. Old screenshots will be removed when new screenshot is captured, summarize in text if context is needed later [/system]",Lt={inlineData:{mimeType:Ae.mimeType,data:Ae.base64}},Mt=T?.imageHistoryCU||"Standard",At=Mt==="Low"?1:Mt==="Extended"?5:3,zt=r.filter(Ge=>Array.isArray(Ge.parts)&&Ge.parts.some(Pt=>Pt.inlineData));if(zt.length>=At){let Ge=zt.length-At+1;for(let Pt=0;Pt<Ge;Pt++){let Et=zt[Pt];Array.isArray(Et.parts)&&(Et.parts=Et.parts.filter(Tt=>!Tt.inlineData))}}if(r.length>0&&r[r.length-1].role==="user"){let Ge=r[r.length-1];typeof Ge.text=="string"&&(Ge.text+=`
716
+ ${cs}${ui}${gs}${fi}[user prompt] ${di.trim()} [/user prompt]`.trim();let hi={role:"user",text:So};To&&(hi.binaryPart=To),r.forEach(j=>{j.text&&j.role==="agent"&&(j.text=qt(j.text))}),r.push(hi),cs&&t[t.length-1]?.id&&(yield{type:"summary_injected",content:{id:t[t.length-1].id,text:So}});let Jt=null,wn=l==="Flux"?50:15;wn=l.toLowerCase().includes("cu")?75:wn;let ta=Math.floor(wn/2),mi=0,on=16;yield{type:"status",content:"Connecting"},wt=!1;let hs=[],_o=!1,pi=!1;for(let j=0;j<=wn;j++){let Ke=Math.floor(wn*.95);if(j>=Ke&&mi<Ke&&typeof n?.onAskUser=="function"){mi=Ke;try{let me="Agent has been running for a long time. Do you want to continue execution?",Ae=[{id:"continue",label:"Continue",description:"Add few more steps"},{id:"cancel",label:"Cancel",description:"Stop extending and finish current turn limit"}],ee=await n.onAskUser(me,Ae);ee&&(ee.toLowerCase().includes("continue")||ee==="Continue")&&(wn+=ta)}catch{}}let fn=await _s("agent",n);if(!fn.allowed)throw new Error(fn.reason||`Budget Exhausted for Provider (${i||"Agent"})`);let ot=[];if(_o=!1,l==="ICU"||l==="FluxCU")try{yield{type:"status",content:"Capturing Screen"},await new Promise(ee=>setTimeout(ee,1e3));let{captureGriddedScreenshot:me}=await import("./screen_grid-GBIGOR5Q.js"),Ae=await me();if(Ae&&Ae.base64){let ee="[system] Fresh Gridded Screen Feedback Captured. Use numeric coordinates. Old screenshots will be removed when new screenshot is captured, summarize in text if context is needed later [/system]",Lt={inlineData:{mimeType:Ae.mimeType,data:Ae.base64}},Mt=T?.imageHistoryCU||"Standard",At=Mt==="Low"?1:Mt==="Extended"?5:3,zt=r.filter(Ge=>Array.isArray(Ge.parts)&&Ge.parts.some(Pt=>Pt.inlineData));if(zt.length>=At){let Ge=zt.length-At+1;for(let Pt=0;Pt<Ge;Pt++){let Et=zt[Pt];Array.isArray(Et.parts)&&(Et.parts=Et.parts.filter(Tt=>!Tt.inlineData))}}if(r.length>0&&r[r.length-1].role==="user"){let Ge=r[r.length-1];typeof Ge.text=="string"&&(Ge.text+=`
718
717
 
719
- ${ee}`,Array.isArray(Ge.parts)||(Ge.parts=[{text:Ge.text}]),Ge.parts.push(Lt))}else r.push({role:"user",text:ee,parts:[{text:ee},Lt]})}}catch(me){console.error("Vision screenshot capture error:",me)}if(T?.compression===0&&(m?.tokens||0)>P&&(r=Ri(r,6)),j>0?yield{type:"status",content:"Working"}:yield{type:"status",content:"Connecting"},wt){try{let{clearPendingNudges:me}=await import("./subagent_state-LZCOZSUJ.js");me()}catch{}yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
718
+ ${ee}`,Array.isArray(Ge.parts)||(Ge.parts=[{text:Ge.text}]),Ge.parts.push(Lt))}else r.push({role:"user",text:ee,parts:[{text:ee},Lt]})}}catch(me){console.error("Vision screenshot capture error:",me)}if(T?.compression===0&&(m?.tokens||0)>P&&(r=Ci(r,6)),j>0?yield{type:"status",content:"Working"}:yield{type:"status",content:"Connecting"},wt){try{let{clearPendingNudges:me}=await import("./subagent_state-LZCOZSUJ.js");me()}catch{}yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
720
719
 
721
720
  \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}try{let{consumePendingNudges:me}=await import("./subagent_state-LZCOZSUJ.js"),Ae=me();if(Ae&&Ae.length>0){let ee=Ae.join(`
722
721
 
@@ -728,31 +727,31 @@ ${ee}`:r.push({role:"user",text:ee}),yield{type:"status",content:"Subagent Updat
728
727
  [question] ${me.replace("/btw","").trim()} [/question]`:r.push({role:"user",text:`[system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
729
728
  [question] ${me.replace("/btw","").trim()} [/question]`}):r.length>0&&r[r.length-1].role==="user"?r[r.length-1].text+=`
730
729
 
731
- [STEERING HINT from USER, High Priority] ${me.trim()} [/STEERING HINT]`:r.push({role:"user",text:`[STEERING HINT from USER, High Priority] ${me.trim()} [/STEERING HINT]`}),yield{type:"status",content:`${me.startsWith("/btw")?"Question Forwarded...":"Steering Hint Injected..."}`})}let Fe,st=!1,et=1,rt=1,Te="",Ve=null,sn=null,K=null,We=0,Me=[],ut=0,kn=!1,vt=!1,rn=!1,Tn=!1,Zn=!0,Qt=0,xt="",Qe="",Dt=!1,Ot=!1,Ye=!0,Se=e,qe="";for(;et<=on&&rt<=on&&!st&&!wt;){let me=!1;try{Te="",Zn&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},Zn=!1,rt===1&&(xt=""));let Ae=D=>{if(!D||!D.includes("[tool:"))return D;let Y="",W=oi(D);W&&(Y=W.fullBlock,D=W.remainingText),D=D.replace(qa,(z,le)=>le.includes("[tool:")?le.trim():z);let q="",Z=0;for(;Z<D.length;){let z=D.indexOf("[tool:",Z);if(z===-1){q+=jr(D.substring(Z));break}let le=D.substring(Z,z);q+=jr(le);let ht=-1,N=null,V=0;for(let be=z;be<D.length;be++){let b=D[be];if(N){if(b===N){let Be=0;for(let fe=be-1;fe>=0&&D[fe]==="\\";fe--)Be++;Be%2===0&&(N=null)}}else if(b==='"'||b==="'"||b==="`")N=b;else if(b==="(")V++;else if(b===")")V--;else if(b==="]"&&V<=0){ht=be;break}}if(ht===-1){q+=D.substring(z);break}q+=D.substring(z,ht+1),Z=ht+1}return(T?.keepReasoningContext?Y:"")+q},ee=r.filter(D=>(D.role==="user"||D.role==="agent"||D.role==="system")&&!String(D.id).startsWith("welcome")&&!D.isMeta&&!D.isTerminalRecord&&!(D.text&&D.text.startsWith("[TERMINAL_RECORD]"))).map((D,Y,W)=>{let q=D.text||"";A||(q=q.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),D.role==="agent"&&(q=Ae(q),q=q.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),q=q.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*"));let Z=[];return Array.isArray(D.parts)&&D.parts.length>0?Z=D.parts.map(z=>{if(z.text){let le=z.text;return A||(le=le.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),D.role==="agent"&&(le=Ae(le),le=le.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),le=le.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*")),{text:le}}return z}):Z=[{text:q}],D.binaryPart&&ft(Se)&&W.slice(Y+1).filter(le=>le.role==="user"&&!le.text?.startsWith("[ACTION RESULT]")&&!le.text?.startsWith("[TOOL RESULT]")).length<=2&&Z.push(D.binaryPart),{role:D.role==="user"||D.role==="system"?"user":"model",parts:Z}});for(let D=0;D<ee.length;D++){let Y=ee[D],W=Y.parts?.[0]?.text||"";if(Y.role==="model"&&/\[(?:tool|action):/i.test(W)){let q=-1;for(let Z=D+1;Z<ee.length;Z++){let z=ee[Z],le=z.parts?.[0]?.text||"";if(z.role==="user"&&(le.startsWith("[ACTION RESULT]")||le.startsWith("[TOOL RESULT]"))){q=Z;break}}if(q!==-1&&q!==D+1){let[Z]=ee.splice(q,1);ee.splice(D+1,0,Z)}}}for(let D=ee.length-2;D>=0;D--){let Y=ee[D],W=ee[D+1];Y.role==="user"&&W.role==="user"&&(W.parts?.[0]?.text||"").trim().startsWith("[SYSTEM")&&ee.splice(D,1)}let Lt=[];for(let D=0;D<ee.length;D++){let Y=ee[D];if(Lt.length===0)Lt.push(Y);else{let W=Lt[Lt.length-1];W.role===Y.role?(W.parts[0].text+=`
730
+ [STEERING HINT from USER, High Priority] ${me.trim()} [/STEERING HINT]`:r.push({role:"user",text:`[STEERING HINT from USER, High Priority] ${me.trim()} [/STEERING HINT]`}),yield{type:"status",content:`${me.startsWith("/btw")?"Question Forwarded...":"Steering Hint Injected..."}`})}let Fe,st=!1,et=1,rt=1,Te="",Ve=null,sn=null,K=null,We=0,Me=[],ut=0,kn=!1,vt=!1,rn=!1,Tn=!1,Zn=!0,Qt=0,xt="",Qe="",Dt=!1,Ot=!1,Ye=!0,Se=e,qe="";for(;et<=on&&rt<=on&&!st&&!wt;){let me=!1;try{Te="",Zn&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},Zn=!1,rt===1&&(xt=""));let Ae=D=>{if(!D||!D.includes("[tool:"))return D;let Y="",W=oi(D);W&&(Y=W.fullBlock,D=W.remainingText),D=D.replace(qa,(z,le)=>le.includes("[tool:")?le.trim():z);let q="",Z=0;for(;Z<D.length;){let z=D.indexOf("[tool:",Z);if(z===-1){q+=Gr(D.substring(Z));break}let le=D.substring(Z,z);q+=Gr(le);let ht=-1,N=null,V=0;for(let be=z;be<D.length;be++){let b=D[be];if(N){if(b===N){let Be=0;for(let fe=be-1;fe>=0&&D[fe]==="\\";fe--)Be++;Be%2===0&&(N=null)}}else if(b==='"'||b==="'"||b==="`")N=b;else if(b==="(")V++;else if(b===")")V--;else if(b==="]"&&V<=0){ht=be;break}}if(ht===-1){q+=D.substring(z);break}q+=D.substring(z,ht+1),Z=ht+1}return(T?.keepReasoningContext?Y:"")+q},ee=r.filter(D=>(D.role==="user"||D.role==="agent"||D.role==="system")&&!String(D.id).startsWith("welcome")&&!D.isMeta&&!D.isTerminalRecord&&!(D.text&&D.text.startsWith("[TERMINAL_RECORD]"))).map((D,Y,W)=>{let q=D.text||"";A||(q=q.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),D.role==="agent"&&(q=Ae(q),q=q.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),q=q.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*"));let Z=[];return Array.isArray(D.parts)&&D.parts.length>0?Z=D.parts.map(z=>{if(z.text){let le=z.text;return A||(le=le.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),D.role==="agent"&&(le=Ae(le),le=le.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),le=le.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*")),{text:le}}return z}):Z=[{text:q}],D.binaryPart&&ft(Se)&&W.slice(Y+1).filter(le=>le.role==="user"&&!le.text?.startsWith("[ACTION RESULT]")&&!le.text?.startsWith("[TOOL RESULT]")).length<=2&&Z.push(D.binaryPart),{role:D.role==="user"||D.role==="system"?"user":"model",parts:Z}});for(let D=0;D<ee.length;D++){let Y=ee[D],W=Y.parts?.[0]?.text||"";if(Y.role==="model"&&/\[(?:tool|action):/i.test(W)){let q=-1;for(let Z=D+1;Z<ee.length;Z++){let z=ee[Z],le=z.parts?.[0]?.text||"";if(z.role==="user"&&(le.startsWith("[ACTION RESULT]")||le.startsWith("[TOOL RESULT]"))){q=Z;break}}if(q!==-1&&q!==D+1){let[Z]=ee.splice(q,1);ee.splice(D+1,0,Z)}}}for(let D=ee.length-2;D>=0;D--){let Y=ee[D],W=ee[D+1];Y.role==="user"&&W.role==="user"&&(W.parts?.[0]?.text||"").trim().startsWith("[SYSTEM")&&ee.splice(D,1)}let Lt=[];for(let D=0;D<ee.length;D++){let Y=ee[D];if(Lt.length===0)Lt.push(Y);else{let W=Lt[Lt.length-1];W.role===Y.role?(W.parts[0].text+=`
732
731
 
733
- `+(Y.parts?.[0]?.text||""),Y.parts?.length>1&&W.parts.push(...Y.parts.slice(1))):Lt.push(Y)}}ee.length=0,ee.push(...Lt),Se=e;let Mt=`${p}|${i}|${l}|${f}|${Se}|${JSON.stringify(c)}|${!!T?.dynamicDirAwareness}|${!!T?.subAgents}`,At=jn.key===Mt&&jn.value;if((process.env.I_HAVE_TOO_MUCH_MONEY==="true"||process.env.I_HAVE_TOO_MUCH_MONEY===!0)&&(At=!1),At)qe=jn.value;else{let D=i==="Mistral"?!!Io(Se):!(Se||"gemma").toLowerCase().startsWith("gemma");qe=ur(c,((Se||"gemma").toLowerCase().startsWith("gemma"),f),l,T,A,_,i,i==="Google"?!0:h,D,p,!!T?.keepReasoningContext,Se),T?.dynamicDirAwareness||(qe+=`
734
- ${li.replace(`
735
- **Directory Structure**`,`
736
- -- Directory Structure --`)}`),jn.key=Mt,jn.value=qe}let Ge=ee[ee.length-1];if(zo()&j>0){await new Promise(W=>setTimeout(W,2500)),yield{type:"status",content:"Verifying"};let D=await Hn(),Y=D?D.diagnostics:null;Y&&Ge&&Ge.role==="user"&&Ge.parts?.[0]?.text&&(Ge.parts[0].text+=`
732
+ `+(Y.parts?.[0]?.text||""),Y.parts?.length>1&&W.parts.push(...Y.parts.slice(1))):Lt.push(Y)}}ee.length=0,ee.push(...Lt),Se=e;let Mt=`${p}|${i}|${l}|${f}|${Se}|${JSON.stringify(c)}|${!!T?.dynamicDirAwareness}|${!!T?.subAgents}`,At=jn.key===Mt&&jn.value;if((process.env.I_HAVE_TOO_MUCH_MONEY==="true"||process.env.I_HAVE_TOO_MUCH_MONEY===!0)&&(At=!1),At)qe=jn.value;else{let D=i==="Mistral"?!!Io(Se):!(Se||"gemma").toLowerCase().startsWith("gemma");qe=fr(c,((Se||"gemma").toLowerCase().startsWith("gemma"),f),l,T,A,_,i,i==="Google"?!0:h,D,p,!!T?.keepReasoningContext,Se),T?.dynamicDirAwareness||(qe+=`
733
+ ${Qr.replace(`
734
+ **Directory**`,`
735
+ -- Directory --`)}`),jn.key=Mt,jn.value=qe}let Ge=ee[ee.length-1];if(zo()&j>0){await new Promise(W=>setTimeout(W,2500)),yield{type:"status",content:"Verifying"};let D=await Hn(),Y=D?D.diagnostics:null;Y&&Ge&&Ge.role==="user"&&Ge.parts?.[0]?.text&&(Ge.parts[0].text+=`
737
736
  ${Y} [/ERROR]`),yield{type:"status",content:"Working"}}let Pt=i==="Mistral"||i==="Google"&&e?.toLowerCase().startsWith("gemma");if(T?.advanceRollback&&Ge&&Ge.role==="user"&&(Ge.parts?.[0]?.text?.startsWith("[ACTION RESULT]")||Ge.parts?.[0]?.text?.startsWith("[TOOL RESULT]")))try{let D=await lo.getLatestFileChanges(p);if(D&&(D.newFiles.length>0||D.modifiedFiles.length>0||D.deletedFiles.length>0)){let Y=`
738
737
  [system] File Changes:
739
738
  `;for(let q of D.newFiles)Y+=`* ${q} (created)
740
739
  `;for(let q of D.modifiedFiles)Y+=`* ${q} (modified)
741
740
  `;for(let q of D.deletedFiles)Y+=`* ${q} (deleted)
742
741
  `;Y+="[/system]",Ge.parts[0].text+=Y;let W=-1;for(let q=r.length-1;q>=0;q--)if(r[q].role==="user"&&(r[q].text?.startsWith("[ACTION RESULT]")||r[q].text?.startsWith("[TOOL RESULT]"))){W=q;break}W!==-1&&(r[W].text+=Y)}}catch{}let Et=Math.floor(wn*.99),Tt=j+1;Tt>=Et&&Ge&&Ge.parts?.[0]&&(Ge.parts[0].text+=`
743
- [system] WARNING, Turn Limit Impending: Step ${Tt}/${wn}. Wrap up quickly/prompt user to continue. [/system]`);let It=new Promise((D,Y)=>{d.signal.aborted&&Y(new DOMException("The user aborted a request.","AbortError")),d.signal.addEventListener("abort",()=>{Y(new DOMException("The user aborted a request.","AbortError"))})});It.catch(()=>{});let gt=ee;if(i==="Ollama")Fe=ei(n.apiKey,Se,gt,qe,f,l,h,d.signal,1,T?.ollamaEndpoint||"Cloud");else if(i==="OpenRouter")Fe=es(n.apiKey,Se,gt,qe,f,l,h,d.signal,1,p);else if(i==="DeepSeek")Fe=Jo(n.apiKey,Se,gt,qe,f,l,h,d.signal,1);else if(i==="Mistral")Fe=Qo(n.apiKey,Se,gt,qe,f,l,h,d.signal,1,p);else if(i==="NVIDIA"){let D=Zo(n.apiKey,Se,gt,qe,f,l,h,d.signal,1);Fe=Br(D,Se)}else if(i==="InferX")Fe=ts(n.apiKey,Se,gt,qe,f,l,h,d.signal,1);else if(i==="SenseNova")Fe=ns(n.apiKey,Se,gt,qe,f,l,h,d.signal,1);else if(i==="AIHubMix")Fe=os(n.apiKey,Se,gt,qe,f,l,h,d.signal,1);else if(i==="Poolside")Fe=ss(n.apiKey,Se,gt,qe,f,l,h,d.signal,1);else if(i==="9router"||i==="9Router")Fe=is(n.apiKey,Se,gt,qe,f,l,h,d.signal,1);else if(i==="ExpLabs"||i==="ExperientialLabs")Fe=rs(n.apiKey,Se,gt,qe,f,l,h,d.signal,1);else if(i==="TokenHarbor"||i==="Token Harbor"||i==="tokenharbor"||i==="token_harbor"||i==="thk")Fe=ti(n.apiKey,Se,gt,qe,f,l,h,d.signal,1);else if(i==="APInex"||i==="apinex"||i==="apx")Fe=ni(n.apiKey,Se,gt,qe,f,l,h,d.signal,1);else{let D=ri(n?.apiKey),{serviceTier:Y,cleanModel:W}=Jr(Se),q={systemInstruction:qe,mediaResolution:"MEDIA_RESOLUTION_HIGH",safetySettings:[{category:In.HARM_CATEGORY_HARASSMENT,threshold:Mn.BLOCK_NONE},{category:In.HARM_CATEGORY_HATE_SPEECH,threshold:Mn.BLOCK_NONE},{category:In.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Mn.BLOCK_NONE},{category:In.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Mn.BLOCK_NONE}],temperature:1.05,thinkingConfig:(()=>{let z=He("Google",Se||"gemini-3-flash-preview",f);if(z!==null){if(typeof z=="object")return z;if(z===!1||z==="false"||z==="none"||z===0||z==="0")return{includeThoughts:!1};if(typeof z=="number")return{includeThoughts:!0,thinkingBudget:z};if(typeof z=="string"){let V=z.toLowerCase();if(V==="minimal")return{includeThoughts:!0,thinkingLevel:Xe.MINIMAL};if(V==="low")return{includeThoughts:!0,thinkingLevel:Xe.LOW};if(V==="medium")return{includeThoughts:!0,thinkingLevel:Xe.MEDIUM};if(V==="high")return{includeThoughts:!0,thinkingLevel:Xe.HIGH};let be=Number(z);if(!isNaN(be))return{includeThoughts:!0,thinkingBudget:be}}}let le=(Se||"").toLowerCase(),ht=le.includes("gemma-4")||le.startsWith("gemma"),N=le.includes("gemini-3");if(ht||N)return ht?f.toLowerCase()!=="high"?{includeThoughts:!1,thinkingLevel:Xe.MINIMAL}:{includeThoughts:!0,thinkingLevel:Xe.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:le.includes("pro")?Xe.LOW:Xe.MINIMAL,Low:Xe.LOW,Medium:Xe.MEDIUM,Standard:Xe.MEDIUM,High:Xe.HIGH,xHigh:Xe.HIGH}[f]||Xe.MEDIUM};{let V={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[f]||2048;return V===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:V}}})()};Y&&(q.serviceTier=Y);let Z=D.models.generateContentStream({model:W||"gemini-3-flash-preview",contents:gt,config:q},{signal:d.signal});Fe=await Promise.race([Z,It])}Te="",Ve=null,K=null,Me=[],ut=0,yield{type:"model_update",content:null},Qe="",Dt=xt.length>0;let an="",ms=Date.now(),Nn=async function*(){if(i==="Google"&&an){let D=to(an);for(let Y of D)yield Y;an="",ms=Date.now()}},xi=!0,Fn="",Vn=!1,St=null,bi=!1,Yn=!1,qn=!1,Ao=!1,_n=!1,eo=D=>{let Y=0;for(;Y+2<D.length;)D[Y]==="`"&&D[Y+1]==="`"&&D[Y+2]==="`"?(Ao=!Ao,Y+=3):Y++},wi=D=>{if(!D)return;let Y=/(?:<(\/?)(?:think|thought|thoughts)[^>]*>|\[(\/?)(?:think|thought|thoughts)\]|<\/?channel\|?>|<\|channel>thought)/gi,W;for(;(W=Y.exec(D))!==null;){let q=W[0].toLowerCase();q.startsWith("</")||q.startsWith("[/")||q==="<channel|>"?_n=!1:_n=!0}},sa={tool:{startPrefix:"[tool",fullPrefix:"[tool:",endTag:"]"},action:{startPrefix:"[action",fullPrefix:"[action:",endTag:"]"},end:{startPrefix:"[[END]]",fullPrefix:"[[END]]",endTag:"[[END]]"},kimi_section:{startPrefix:"<|tool_calls_section_begin|>",fullPrefix:"<|tool_calls_section_begin|>",endTag:"<|tool_calls_section_end|>"},kimi_call:{startPrefix:"<|tool_call_begin|>",fullPrefix:"<|tool_call_begin|>",endTag:"<|tool_call_end|>"}},to=D=>{let Y=[],W=D,q=Z=>{if(!Z)return;if(!bi){Y.push({type:"text",content:Z}),eo(Z),wi(Z);return}let z=/(?:<(\/?)(?:think|thought|thoughts)[^>]*>|\[(\/?)(?:think|thought|thoughts)\]|<\/?channel\|?>|<\|channel>thought)/gi,le=0,ht;for(;(ht=z.exec(Z))!==null;){let V=Z.substring(le,ht.index);if(V)if(eo(V),_n)Y.push({type:"text",content:V});else{let Be=V.replace(/[^\n]/g,"");Be&&Y.push({type:"text",content:Be})}let be=ht[0];eo(be);let b=be.toLowerCase();b.startsWith("</")||b.startsWith("[/")||b==="<channel|>"?_n=!1:_n=!0,Y.push({type:"text",content:be}),le=z.lastIndex}let N=Z.substring(le);if(N)if(eo(N),_n)Y.push({type:"text",content:N});else{let V=N.replace(/[^\n]/g,"");V&&Y.push({type:"text",content:V})}};for(;W.length>0;)if(Vn){let Z=Fn+W,z=sa[St];if(z){let N=!1;if(Z.length<z.startPrefix.length?z.startPrefix.startsWith(Z)||(N=!0):Z.startsWith(z.startPrefix)?Z.length>=z.fullPrefix.length&&!Z.startsWith(z.fullPrefix)&&(N=!0):N=!0,N){q(Z),Fn="",Vn=!1,St=null,Yn=!1,qn=!1,W="";break}}let le=-1,ht=z?z.endTag:"]";if(St==="tool"||St==="action"){let N=0,V=null,be=0,b=!1;for(let Be=0;Be<Z.length;Be++){let fe=Z[Be];if(V){if(fe===V){let X=0;for(let $t=Be-1;$t>=0&&Z[$t]==="\\";$t--)X++;X%2===0&&(V=null)}}else if(fe==='"'||fe==="'"||fe==="`")V=fe;else if(fe==="(")N++,b=!0;else if(fe===")")N--;else if(fe==="[")be++;else if(fe==="]"){if(b&&N===0&&be===1){le=Be;break}be--}}}else le=Z.indexOf(ht);if(le!==-1){let N=ht.length,V=Z.substring(0,le+N);St?.startsWith("kimi")||Y.push({type:"text",content:V}),eo(V),wi(V),(St==="tool"||St==="action"||St?.startsWith("kimi"))&&!Yn&&!qn&&(bi=!0),Yn=!1,qn=!1,Fn="",Vn=!1,St=null,W=Z.substring(le+N)}else{let N=St?.startsWith("kimi")?8192:512;Z.length>N?(q(Z),Fn="",Vn=!1,St=null,Yn=!1,qn=!1):Fn=Z,W="";break}}else{let Z=W.indexOf("[tool"),z=W.indexOf("[action"),le=W.indexOf("[[END]]"),ht=W.indexOf("<|tool_calls_section_begin|>"),N=W.indexOf("<|tool_call_begin|>"),V=[{type:"tool",idx:Z,start:"[tool",end:"]"},{type:"action",idx:z,start:"[action",end:"]"},{type:"end",idx:le,start:"[[END]]",end:"[[END]]"},{type:"kimi_section",idx:ht,start:"<|tool_calls_section_begin|>",end:"<|tool_calls_section_end|>"},{type:"kimi_call",idx:N,start:"<|tool_call_begin|>",end:"<|tool_call_end|>"}].filter(be=>be.idx!==-1).sort((be,b)=>be.idx-b.idx);if(V.length>0){let be=V[0],b=W.substring(0,be.idx);be.idx>0&&q(b);let Be=be.idx>0?W[be.idx-1]:"";Yn=Ao||Be==="`",qn=_n,Vn=!0,St=be.type,Fn="",W=W.substring(be.idx)}else{let be=["[tool","[action","[[END]]","<|tool_calls_section_begin|>","<|tool_call_begin|>"],b=-1;for(let Be of be){for(let fe=Be.length-1;fe>0;fe--)if(W.endsWith(Be.substring(0,fe))){b=W.length-fe;let X=be.indexOf(Be);X===0?St="tool":X===1?St="action":X===2?St="end":X===3?St="kimi_section":St="kimi_call";break}if(b!==-1)break}if(b!==-1){if(b>0){let fe=W.substring(0,b);q(fe)}let Be=b>0?W[b-1]:"";Yn=Ao||Be==="`",qn=_n,Vn=!0,Fn=W.substring(b),W=""}else{q(W);break}}}return Y},ia=Fe[Symbol.asyncIterator]();for(;;){let{value:D,done:Y}=await Promise.race([ia.next(),It]);if(Y)break;if(D&&D.type==="status"){yield D;continue}let W="",q=D.candidates?.[0]?.content?.parts;if(q&&q.length>0)for(let z of q){let le=typeof z.text=="string"?z.text:z.text?parseChunkText(z.text):"";z.thought?le&&(me||(W+="<think>",me=!0),W+=le):le&&(me&&(W+="</think>",me=!1),W+=le)}else D.text&&me&&(W+="</think>",me=!1);W=ja(W);let Z=W?As(W):0;if(n&&typeof n.onTokenChunk=="function"&&n.onTokenChunk(W,Z),xi&&(yield{type:"status",content:"Thinking"},xi=!1),wt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
742
+ [system] WARNING, Turn Limit Impending: Step ${Tt}/${wn}. Wrap up quickly/prompt user to continue. [/system]`);let It=new Promise((D,Y)=>{d.signal.aborted&&Y(new DOMException("The user aborted a request.","AbortError")),d.signal.addEventListener("abort",()=>{Y(new DOMException("The user aborted a request.","AbortError"))})});It.catch(()=>{});let gt=ee;if(i==="Ollama")Fe=ei(n.apiKey,Se,gt,qe,f,l,h,d.signal,1,T?.ollamaEndpoint||"Cloud");else if(i==="OpenRouter")Fe=es(n.apiKey,Se,gt,qe,f,l,h,d.signal,1,p);else if(i==="DeepSeek")Fe=Jo(n.apiKey,Se,gt,qe,f,l,h,d.signal,1);else if(i==="Mistral")Fe=Qo(n.apiKey,Se,gt,qe,f,l,h,d.signal,1,p);else if(i==="NVIDIA"){let D=Zo(n.apiKey,Se,gt,qe,f,l,h,d.signal,1);Fe=Fr(D,Se)}else if(i==="InferX")Fe=ts(n.apiKey,Se,gt,qe,f,l,h,d.signal,1);else if(i==="SenseNova")Fe=ns(n.apiKey,Se,gt,qe,f,l,h,d.signal,1);else if(i==="AIHubMix")Fe=os(n.apiKey,Se,gt,qe,f,l,h,d.signal,1);else if(i==="Poolside")Fe=ss(n.apiKey,Se,gt,qe,f,l,h,d.signal,1);else if(i==="9router"||i==="9Router")Fe=is(n.apiKey,Se,gt,qe,f,l,h,d.signal,1);else if(i==="ExpLabs"||i==="ExperientialLabs")Fe=rs(n.apiKey,Se,gt,qe,f,l,h,d.signal,1);else if(i==="TokenHarbor"||i==="Token Harbor"||i==="tokenharbor"||i==="token_harbor"||i==="thk")Fe=ti(n.apiKey,Se,gt,qe,f,l,h,d.signal,1);else if(i==="APInex"||i==="apinex"||i==="apx")Fe=ni(n.apiKey,Se,gt,qe,f,l,h,d.signal,1);else{let D=ri(n?.apiKey),{serviceTier:Y,cleanModel:W}=Xr(Se),q={systemInstruction:qe,mediaResolution:"MEDIA_RESOLUTION_HIGH",safetySettings:[{category:In.HARM_CATEGORY_HARASSMENT,threshold:Mn.BLOCK_NONE},{category:In.HARM_CATEGORY_HATE_SPEECH,threshold:Mn.BLOCK_NONE},{category:In.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Mn.BLOCK_NONE},{category:In.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Mn.BLOCK_NONE}],temperature:1.05,thinkingConfig:(()=>{let z=He("Google",Se||"gemini-3-flash-preview",f);if(z!==null){if(typeof z=="object")return z;if(z===!1||z==="false"||z==="none"||z===0||z==="0")return{includeThoughts:!1};if(typeof z=="number")return{includeThoughts:!0,thinkingBudget:z};if(typeof z=="string"){let V=z.toLowerCase();if(V==="minimal")return{includeThoughts:!0,thinkingLevel:Xe.MINIMAL};if(V==="low")return{includeThoughts:!0,thinkingLevel:Xe.LOW};if(V==="medium")return{includeThoughts:!0,thinkingLevel:Xe.MEDIUM};if(V==="high")return{includeThoughts:!0,thinkingLevel:Xe.HIGH};let be=Number(z);if(!isNaN(be))return{includeThoughts:!0,thinkingBudget:be}}}let le=(Se||"").toLowerCase(),ht=le.includes("gemma-4")||le.startsWith("gemma"),N=le.includes("gemini-3");if(ht||N)return ht?f.toLowerCase()!=="high"?{includeThoughts:!1,thinkingLevel:Xe.MINIMAL}:{includeThoughts:!0,thinkingLevel:Xe.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:le.includes("pro")?Xe.LOW:Xe.MINIMAL,Low:Xe.LOW,Medium:Xe.MEDIUM,Standard:Xe.MEDIUM,High:Xe.HIGH,xHigh:Xe.HIGH}[f]||Xe.MEDIUM};{let V={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[f]||2048;return V===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:V}}})()};Y&&(q.serviceTier=Y);let Z=D.models.generateContentStream({model:W||"gemini-3-flash-preview",contents:gt,config:q},{signal:d.signal});Fe=await Promise.race([Z,It])}Te="",Ve=null,K=null,Me=[],ut=0,yield{type:"model_update",content:null},Qe="",Dt=xt.length>0;let an="",ms=Date.now(),Nn=async function*(){if(i==="Google"&&an){let D=to(an);for(let Y of D)yield Y;an="",ms=Date.now()}},yi=!0,Fn="",Vn=!1,St=null,xi=!1,Yn=!1,qn=!1,Ao=!1,_n=!1,eo=D=>{let Y=0;for(;Y+2<D.length;)D[Y]==="`"&&D[Y+1]==="`"&&D[Y+2]==="`"?(Ao=!Ao,Y+=3):Y++},bi=D=>{if(!D)return;let Y=/(?:<(\/?)(?:think|thought|thoughts)[^>]*>|\[(\/?)(?:think|thought|thoughts)\]|<\/?channel\|?>|<\|channel>thought)/gi,W;for(;(W=Y.exec(D))!==null;){let q=W[0].toLowerCase();q.startsWith("</")||q.startsWith("[/")||q==="<channel|>"?_n=!1:_n=!0}},sa={tool:{startPrefix:"[tool",fullPrefix:"[tool:",endTag:"]"},action:{startPrefix:"[action",fullPrefix:"[action:",endTag:"]"},end:{startPrefix:"[[END]]",fullPrefix:"[[END]]",endTag:"[[END]]"},kimi_section:{startPrefix:"<|tool_calls_section_begin|>",fullPrefix:"<|tool_calls_section_begin|>",endTag:"<|tool_calls_section_end|>"},kimi_call:{startPrefix:"<|tool_call_begin|>",fullPrefix:"<|tool_call_begin|>",endTag:"<|tool_call_end|>"}},to=D=>{let Y=[],W=D,q=Z=>{if(!Z)return;if(!xi){Y.push({type:"text",content:Z}),eo(Z),bi(Z);return}let z=/(?:<(\/?)(?:think|thought|thoughts)[^>]*>|\[(\/?)(?:think|thought|thoughts)\]|<\/?channel\|?>|<\|channel>thought)/gi,le=0,ht;for(;(ht=z.exec(Z))!==null;){let V=Z.substring(le,ht.index);if(V)if(eo(V),_n)Y.push({type:"text",content:V});else{let Be=V.replace(/[^\n]/g,"");Be&&Y.push({type:"text",content:Be})}let be=ht[0];eo(be);let b=be.toLowerCase();b.startsWith("</")||b.startsWith("[/")||b==="<channel|>"?_n=!1:_n=!0,Y.push({type:"text",content:be}),le=z.lastIndex}let N=Z.substring(le);if(N)if(eo(N),_n)Y.push({type:"text",content:N});else{let V=N.replace(/[^\n]/g,"");V&&Y.push({type:"text",content:V})}};for(;W.length>0;)if(Vn){let Z=Fn+W,z=sa[St];if(z){let N=!1;if(Z.length<z.startPrefix.length?z.startPrefix.startsWith(Z)||(N=!0):Z.startsWith(z.startPrefix)?Z.length>=z.fullPrefix.length&&!Z.startsWith(z.fullPrefix)&&(N=!0):N=!0,N){q(Z),Fn="",Vn=!1,St=null,Yn=!1,qn=!1,W="";break}}let le=-1,ht=z?z.endTag:"]";if(St==="tool"||St==="action"){let N=0,V=null,be=0,b=!1;for(let Be=0;Be<Z.length;Be++){let fe=Z[Be];if(V){if(fe===V){let X=0;for(let $t=Be-1;$t>=0&&Z[$t]==="\\";$t--)X++;X%2===0&&(V=null)}}else if(fe==='"'||fe==="'"||fe==="`")V=fe;else if(fe==="(")N++,b=!0;else if(fe===")")N--;else if(fe==="[")be++;else if(fe==="]"){if(b&&N===0&&be===1){le=Be;break}be--}}}else le=Z.indexOf(ht);if(le!==-1){let N=ht.length,V=Z.substring(0,le+N);St?.startsWith("kimi")||Y.push({type:"text",content:V}),eo(V),bi(V),(St==="tool"||St==="action"||St?.startsWith("kimi"))&&!Yn&&!qn&&(xi=!0),Yn=!1,qn=!1,Fn="",Vn=!1,St=null,W=Z.substring(le+N)}else{let N=St?.startsWith("kimi")?8192:512;Z.length>N?(q(Z),Fn="",Vn=!1,St=null,Yn=!1,qn=!1):Fn=Z,W="";break}}else{let Z=W.indexOf("[tool"),z=W.indexOf("[action"),le=W.indexOf("[[END]]"),ht=W.indexOf("<|tool_calls_section_begin|>"),N=W.indexOf("<|tool_call_begin|>"),V=[{type:"tool",idx:Z,start:"[tool",end:"]"},{type:"action",idx:z,start:"[action",end:"]"},{type:"end",idx:le,start:"[[END]]",end:"[[END]]"},{type:"kimi_section",idx:ht,start:"<|tool_calls_section_begin|>",end:"<|tool_calls_section_end|>"},{type:"kimi_call",idx:N,start:"<|tool_call_begin|>",end:"<|tool_call_end|>"}].filter(be=>be.idx!==-1).sort((be,b)=>be.idx-b.idx);if(V.length>0){let be=V[0],b=W.substring(0,be.idx);be.idx>0&&q(b);let Be=be.idx>0?W[be.idx-1]:"";Yn=Ao||Be==="`",qn=_n,Vn=!0,St=be.type,Fn="",W=W.substring(be.idx)}else{let be=["[tool","[action","[[END]]","<|tool_calls_section_begin|>","<|tool_call_begin|>"],b=-1;for(let Be of be){for(let fe=Be.length-1;fe>0;fe--)if(W.endsWith(Be.substring(0,fe))){b=W.length-fe;let X=be.indexOf(Be);X===0?St="tool":X===1?St="action":X===2?St="end":X===3?St="kimi_section":St="kimi_call";break}if(b!==-1)break}if(b!==-1){if(b>0){let fe=W.substring(0,b);q(fe)}let Be=b>0?W[b-1]:"";Yn=Ao||Be==="`",qn=_n,Vn=!0,Fn=W.substring(b),W=""}else{q(W);break}}}return Y},ia=Fe[Symbol.asyncIterator]();for(;;){let{value:D,done:Y}=await Promise.race([ia.next(),It]);if(Y)break;if(D&&D.type==="status"){yield D;continue}let W="",q=D.candidates?.[0]?.content?.parts;if(q&&q.length>0)for(let z of q){let le=typeof z.text=="string"?z.text:z.text?parseChunkText(z.text):"";z.thought?le&&(me||(W+="<think>",me=!0),W+=le):le&&(me&&(W+="</think>",me=!1),W+=le)}else D.text&&me&&(W+="</think>",me=!1);W=ja(W);let Z=W?As(W):0;if(n&&typeof n.onTokenChunk=="function"&&n.onTokenChunk(W,Z),yi&&(yield{type:"status",content:"Thinking"},yi=!1),wt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
744
743
 
745
- \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(W){if(Dt){if(Qe+=W,Qe.length>=64){let N=0,V=Math.min(xt.length,Qe.length);for(let b=V;b>=10;b--)if(xt.endsWith(Qe.substring(0,b))){N=b;break}let be=Qe.substring(N);if(be){let Be=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(xt)?be.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):be.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(Be)if(Te+=Be,i==="Google")an+=Be;else{yield*Nn();let fe=to(Be);for(let X of fe)yield X}}Dt=!1,Qe=""}continue}else if(Te+=W,i==="Google")an+=W;else{yield*Nn();let N=to(W);for(let V of N)yield V}let z=Qa(Te);if(z.inside){Ot=!0,K||(K=Date.now());let V={Ask:"ask",AskUser:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",FindFile:"find_file",find_file:"find_file",findfile:"find_file",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Cancel:"cancel",Await:"await",Answer:"answer",Steer:"steer",steer:"steer"}[z.toolName]||z.toolName,be=z.args||"",b=null;if(["write_file","update_file","view_file","read_folder","find_file","write_pdf","write_docx","search_keyword","generate_image","file_map","invoke","invoke_sync","get_progress","await","answer"].includes(V)){let fe=ne(be),X=fe.basename||fe.name||fe.path||fe.targetFile||fe.TargetFile||fe.directory||fe.file,$t=fe.keyword,Bn=fe.title||fe.task,An=fe.id||fe.taskId,Le=fe.timeout||fe.time;if($t!=null)b=String($t).replace(Gn,"");else if(X)b=ie.basename(String(X).replace(Gn,"").replace(Ur,"/"));else if(Bn&&(V==="invoke"||V==="invoke_sync"))b=String(Bn).replace(Gn,"").substring(0,30);else if(An&&V==="get_progress")b=String(An).replace(Gn,"");else if(Le&&V==="await"){let Nt=parseFloat(String(Le).replace(Gn,""));isNaN(Nt)?b=String(Le).replace(Gn,""):(Nt<5&&(Nt=5),Nt>120&&(Nt=120),b=(gn=>{if(gn>=60){let ys=Math.floor(gn/60),zn=gn%60;return`${ys}m${zn>0?` ${zn}s`:""}`}return`${gn}s`})(Nt))}else{let Nt=be.match(Wa);if(Nt){let Ht=Nt[1].replace(Gn,"");V==="invoke"||V==="invoke_sync"||V==="get_progress"?b=Ht.substring(0,30):b=V==="search_keyword"||V==="file_map"?Ht:ie.basename(Ht.replace(Ur,"/"))}}}let Be=`${si[V]||V}${b?` ${b}`:""}`;if((V!==Ve||b!==sn)&&(Ve=V,sn=b,yield{type:"status",content:`${Be}`},process.stdout.isTTY)){let X={WebSearch:"Searching",web_search:"Searching",WebScrape:"Reading",web_scrape:"Reading",ReadFile:"Reading",read_file:"Reading",ReadFolder:"Reading",read_folder:"Reading",WriteFile:"Writing",write_file:"Writing",UpdateFile:"Editing",update_file:"Editing",WritePdf:"Creating",write_pdf:"Creating",WriteDocx:"Creating",write_docx:"Creating",SearchKeyword:"Searching",search_keyword:"Searching",CodeSearch:"Searching",code_search:"Searching",FindFile:"Finding File",find_file:"Finding File",Run:"Executing",Ask:"User Input Required",AskUser:"User Input Required",Memory:"Updating Memory",GenerateImage:"Generating",InvokeSync:"Sub-Agent Working",invoke_sync:"Sub-Agent Working",Invoke:"Working",invoke:"Working",GetProgress:"Checking Progress",get_progress:"Checking Progress",Cancel:"Stopping Generalist",cancel:"Stopping Generalist",Await:"Waiting",await:"Waiting",EmergencyRollback:"Rolling the Ball",Answer:"Answering Sub-Agent",answer:"Answering Sub-Agent",Steer:"Steering Sub-Agent",steer:"Steering Sub-Agent",Click:"Clicking",click:"Clicking",Drag:"Dragging",drag:"Dragging",Scroll:"Scrolling",scroll:"Scrolling",KeyboardTyping:"Typing",keyboard_typing:"Typing",KeyPress:"Pressing Key",key_press:"Pressing Key",RecaptureScreen:"Recapturing Screen",recapture_screen:"Recapturing Screen"}[V]||"Working";process.stdout.write(`\x1B]0;${X}...\x07`)}}if(Te.length-Qt>150){Qt=Te.length;let N=Xr(Te,!1),V=oi(N),be=V?(V.innerContent||"").trim():"",b=be.split(/[.!?]\s+/),Be=new Set(b),fe=b.length>10?(b.length-Be.size)/b.length:0,X=be.split(/\s+/).filter(Pe=>Pe.length>0).length,$t=.6,Bn=.8,An=!1;if(i.toLowerCase().includes("google")&&(Se||"").toLowerCase().startsWith("gemma")){let S={low:256,medium:1024,high:8192,max:16384,xhigh:16384}[f?.toLowerCase()]||2500;An=X>S}if(fe>$t||An){yield{type:"status",content:`${fe>$t?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},vt=!0,await new Promise(S=>setTimeout(S,3e3));break}let Ht=Kr(Te).trim().split(/[.!?]\s+/),gn=new Set(Ht);if((Ht.length>10?(Ht.length-gn.size)/Ht.length:0)>Bn){yield{type:"status",content:"Response Loop Detected. Re-centering..."},vt=!1,Tn=!0,await new Promise(Pe=>setTimeout(Pe,3e3));break}let zn=N.replace(La,"").replace(Pa,"").replace($a,"").replace(Na,""),Ft=zn.toLowerCase().split(/\s+/).map(Pe=>Pe.replace(Fa,"")).filter(Pe=>Pe.length>0),hn=!1;if(Ft.length>=10)for(let Pe=1;Pe<=15;Pe++){let S=Math.max(3,Math.ceil(10/Pe));if(Ft.length<Pe*S)continue;let H=Ft.slice(Ft.length-Pe),se=H.join(" ");if(Pe>1&&se===H.slice(0,Math.floor(Pe/2)).join(" ").repeat(2).trim())continue;let ge=!0;for(let we=1;we<S;we++)if(Ft.slice(Ft.length-Pe*(we+1),Ft.length-Pe*we).join(" ")!==se){ge=!1;break}if(ge){hn=!0;break}}if(!hn){let Pe=zn.toLowerCase().replace(Ba,"");if(Pe.length>=20)for(let S=1;S<=10;S++){let H=Math.max(5,Math.ceil(16/S));if(Pe.length<S*H)continue;let se=Pe.substring(Pe.length-S),ge=!0;for(let we=1;we<H;we++)if(Pe.substring(Pe.length-S*(we+1),Pe.length-S*we)!==se){ge=!1;break}if(ge){hn=!0;break}}}if(hn){yield{type:"status",content:"Stuttering Detected. Re-centering..."},vt=!1,rn=!0,await new Promise(Pe=>setTimeout(Pe,3e3));break}}let le=qt(Te),ht=ko(le);for(;ht.length>ut;){yield*Nn();let N=ht[ut],V=Date.now(),b={Ask:"ask",AskUser:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",FindFile:"find_file",find_file:"find_file",findfile:"find_file",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Await:"await",await:"await",AwaitSubagent:"await",awaitSubagent:"await",Answer:"answer",answer:"answer",AnswerSubagent:"answer",answerSubagent:"answer",Steer:"steer",steer:"steer",SteerSubagent:"steer",steerSubagent:"steer",Cancel:"cancel",cancel:"cancel",Click:"click",click:"click",Drag:"drag",drag:"drag",Scroll:"scroll",scroll:"scroll",KeyboardTyping:"keyboard_typing",keyboard_typing:"keyboard_typing",KeyPress:"key_press",key_press:"key_press",RecaptureScreen:"recapture_screen",recapture_screen:"recapture_screen",EmergencyRollback:"EmergencyRollback"}[N.toolName]||N.toolName,Be=si[b]||N.toolName,fe=Kn(b,N.args);yield{type:"status",content:`${Be}${fe?` ${fe}`:""}`};let X="";if(b==="click"){let S=ne(N.args);X=`\u2714 Clicked: ${S.intendedClickText?`${S.intendedClickText}`:""}`}else if(b==="drag"){let S=ne(N.args);X=`\u2714 Dragged: Cell ${S.fromGridId||""} \u2192 Cell ${S.toGridId||""}`}else if(b==="scroll"){let S=ne(N.args);X=`\u2714 Scrolled: ${S.direction||"down"} (${S.amount||1})`}else if(b==="keyboard_typing"){let S=ne(N.args);X=`\u2714 Typed: ${S.text?`"${S.text.length>20?S.text.substring(0,20)+"...":S.text}"`:""}`}else if(b==="key_press")X=`\u2714 Pressed Key: ${ne(N.args).key||""}`;else if(b==="recapture_screen")X="\u2714 Recaptured Screen";else if(b==="web_search"){let{query:S,limit:H=10,aiMode:se=!1}=ne(N.args);X=`${S?"\u2714":"\u2718"} ${se?"AI Search":"Searched"}: ${S?`${S}`:"No Search Query"}${se===!1&&S?` \u2192 ${H}`:""}`}else if(b==="web_scrape"){let S=ne(N.args).url||null;X=`${S?"\u2714":"\u2718"} Visited: ${S||"No Source"}`}else if(b==="view_file"){let{path:S,StartLine:H,EndLine:se,start_line:ge,end_line:we,startLine:Ne,endLine:De}=ne(N.args),Ce=H||ge||Ne,J=se||we||De,ce=parseInt(Ce)||1,ue=parseInt(J)||(Ce?ce+800:800),je="...",ze=ue,he=(S||"").trim().toLowerCase().replaceAll("\\","/");if(he.startsWith("#skill"))he.startsWith("#skill/global/fluxflow")||he.startsWith("#skills/global/fluxflow")||he.includes("#skill/fluxflow")||he.includes("#skills/fluxflow")?X="\u2714 Read Documentation":X=`\u2714 Read Skill: ${ie.basename(S.replaceAll("\\","/"))}`;else{try{let _e=ie.resolve(process.cwd(),S);if(Ue.existsSync(_e)){let bt=Ue.readFileSync(_e,"utf8").split(`
744
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(W){if(Dt){if(Qe+=W,Qe.length>=64){let N=0,V=Math.min(xt.length,Qe.length);for(let b=V;b>=10;b--)if(xt.endsWith(Qe.substring(0,b))){N=b;break}let be=Qe.substring(N);if(be){let Be=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(xt)?be.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):be.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(Be)if(Te+=Be,i==="Google")an+=Be;else{yield*Nn();let fe=to(Be);for(let X of fe)yield X}}Dt=!1,Qe=""}continue}else if(Te+=W,i==="Google")an+=W;else{yield*Nn();let N=to(W);for(let V of N)yield V}let z=Qa(Te);if(z.inside){Ot=!0,K||(K=Date.now());let V={Ask:"ask",AskUser:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",FindFile:"find_file",find_file:"find_file",findfile:"find_file",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Cancel:"cancel",Await:"await",Answer:"answer",Steer:"steer",steer:"steer"}[z.toolName]||z.toolName,be=z.args||"",b=null;if(["write_file","update_file","view_file","read_folder","find_file","write_pdf","write_docx","search_keyword","generate_image","file_map","invoke","invoke_sync","get_progress","await","answer"].includes(V)){let fe=ne(be),X=fe.basename||fe.name||fe.path||fe.targetFile||fe.TargetFile||fe.directory||fe.file,$t=fe.keyword,Bn=fe.title||fe.task,An=fe.id||fe.taskId,Le=fe.timeout||fe.time;if($t!=null)b=String($t).replace(Gn,"");else if(X)b=ie.basename(String(X).replace(Gn,"").replace(Br,"/"));else if(Bn&&(V==="invoke"||V==="invoke_sync"))b=String(Bn).replace(Gn,"").substring(0,30);else if(An&&V==="get_progress")b=String(An).replace(Gn,"");else if(Le&&V==="await"){let Nt=parseFloat(String(Le).replace(Gn,""));isNaN(Nt)?b=String(Le).replace(Gn,""):(Nt<5&&(Nt=5),Nt>120&&(Nt=120),b=(gn=>{if(gn>=60){let ys=Math.floor(gn/60),zn=gn%60;return`${ys}m${zn>0?` ${zn}s`:""}`}return`${gn}s`})(Nt))}else{let Nt=be.match(Wa);if(Nt){let Ht=Nt[1].replace(Gn,"");V==="invoke"||V==="invoke_sync"||V==="get_progress"?b=Ht.substring(0,30):b=V==="search_keyword"||V==="file_map"?Ht:ie.basename(Ht.replace(Br,"/"))}}}let Be=`${si[V]||V}${b?` ${b}`:""}`;if((V!==Ve||b!==sn)&&(Ve=V,sn=b,yield{type:"status",content:`${Be}`},process.stdout.isTTY)){let X={WebSearch:"Searching",web_search:"Searching",WebScrape:"Reading",web_scrape:"Reading",ReadFile:"Reading",read_file:"Reading",ReadFolder:"Reading",read_folder:"Reading",WriteFile:"Writing",write_file:"Writing",UpdateFile:"Editing",update_file:"Editing",WritePdf:"Creating",write_pdf:"Creating",WriteDocx:"Creating",write_docx:"Creating",SearchKeyword:"Searching",search_keyword:"Searching",CodeSearch:"Searching",code_search:"Searching",FindFile:"Finding File",find_file:"Finding File",Run:"Executing",Ask:"User Input Required",AskUser:"User Input Required",Memory:"Updating Memory",GenerateImage:"Generating",InvokeSync:"Sub-Agent Working",invoke_sync:"Sub-Agent Working",Invoke:"Working",invoke:"Working",GetProgress:"Checking Progress",get_progress:"Checking Progress",Cancel:"Stopping Generalist",cancel:"Stopping Generalist",Await:"Waiting",await:"Waiting",EmergencyRollback:"Rolling the Ball",Answer:"Answering Sub-Agent",answer:"Answering Sub-Agent",Steer:"Steering Sub-Agent",steer:"Steering Sub-Agent",Click:"Clicking",click:"Clicking",Drag:"Dragging",drag:"Dragging",Scroll:"Scrolling",scroll:"Scrolling",KeyboardTyping:"Typing",keyboard_typing:"Typing",KeyPress:"Pressing Key",key_press:"Pressing Key",RecaptureScreen:"Recapturing Screen",recapture_screen:"Recapturing Screen"}[V]||"Working";process.stdout.write(`\x1B]0;${X}...\x07`)}}if(Te.length-Qt>150){Qt=Te.length;let N=zr(Te,!1),V=oi(N),be=V?(V.innerContent||"").trim():"",b=be.split(/[.!?]\s+/),Be=new Set(b),fe=b.length>10?(b.length-Be.size)/b.length:0,X=be.split(/\s+/).filter(Pe=>Pe.length>0).length,$t=.6,Bn=.8,An=!1;if(i.toLowerCase().includes("google")&&(Se||"").toLowerCase().startsWith("gemma")){let S={low:256,medium:1024,high:8192,max:16384,xhigh:16384}[f?.toLowerCase()]||2500;An=X>S}if(fe>$t||An){yield{type:"status",content:`${fe>$t?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},vt=!0,await new Promise(S=>setTimeout(S,3e3));break}let Ht=jr(Te).trim().split(/[.!?]\s+/),gn=new Set(Ht);if((Ht.length>10?(Ht.length-gn.size)/Ht.length:0)>Bn){yield{type:"status",content:"Response Loop Detected. Re-centering..."},vt=!1,Tn=!0,await new Promise(Pe=>setTimeout(Pe,3e3));break}let zn=N.replace(La,"").replace(Pa,"").replace($a,"").replace(Na,""),Ft=zn.toLowerCase().split(/\s+/).map(Pe=>Pe.replace(Fa,"")).filter(Pe=>Pe.length>0),hn=!1;if(Ft.length>=10)for(let Pe=1;Pe<=15;Pe++){let S=Math.max(3,Math.ceil(10/Pe));if(Ft.length<Pe*S)continue;let H=Ft.slice(Ft.length-Pe),se=H.join(" ");if(Pe>1&&se===H.slice(0,Math.floor(Pe/2)).join(" ").repeat(2).trim())continue;let ge=!0;for(let we=1;we<S;we++)if(Ft.slice(Ft.length-Pe*(we+1),Ft.length-Pe*we).join(" ")!==se){ge=!1;break}if(ge){hn=!0;break}}if(!hn){let Pe=zn.toLowerCase().replace(Ba,"");if(Pe.length>=20)for(let S=1;S<=10;S++){let H=Math.max(5,Math.ceil(16/S));if(Pe.length<S*H)continue;let se=Pe.substring(Pe.length-S),ge=!0;for(let we=1;we<H;we++)if(Pe.substring(Pe.length-S*(we+1),Pe.length-S*we)!==se){ge=!1;break}if(ge){hn=!0;break}}}if(hn){yield{type:"status",content:"Stuttering Detected. Re-centering..."},vt=!1,rn=!0,await new Promise(Pe=>setTimeout(Pe,3e3));break}}let le=qt(Te),ht=ko(le);for(;ht.length>ut;){yield*Nn();let N=ht[ut],V=Date.now(),b={Ask:"ask",AskUser:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",FindFile:"find_file",find_file:"find_file",findfile:"find_file",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Await:"await",await:"await",AwaitSubagent:"await",awaitSubagent:"await",Answer:"answer",answer:"answer",AnswerSubagent:"answer",answerSubagent:"answer",Steer:"steer",steer:"steer",SteerSubagent:"steer",steerSubagent:"steer",Cancel:"cancel",cancel:"cancel",Click:"click",click:"click",Drag:"drag",drag:"drag",Scroll:"scroll",scroll:"scroll",KeyboardTyping:"keyboard_typing",keyboard_typing:"keyboard_typing",KeyPress:"key_press",key_press:"key_press",RecaptureScreen:"recapture_screen",recapture_screen:"recapture_screen",EmergencyRollback:"EmergencyRollback"}[N.toolName]||N.toolName,Be=si[b]||N.toolName,fe=Kn(b,N.args);yield{type:"status",content:`${Be}${fe?` ${fe}`:""}`};let X="";if(b==="click"){let S=ne(N.args);X=`\u2714 Clicked: ${S.intendedClickText?`${S.intendedClickText}`:""}`}else if(b==="drag"){let S=ne(N.args);X=`\u2714 Dragged: Cell ${S.fromGridId||""} \u2192 Cell ${S.toGridId||""}`}else if(b==="scroll"){let S=ne(N.args);X=`\u2714 Scrolled: ${S.direction||"down"} (${S.amount||1})`}else if(b==="keyboard_typing"){let S=ne(N.args);X=`\u2714 Typed: ${S.text?`"${S.text.length>20?S.text.substring(0,20)+"...":S.text}"`:""}`}else if(b==="key_press")X=`\u2714 Pressed Key: ${ne(N.args).key||""}`;else if(b==="recapture_screen")X="\u2714 Recaptured Screen";else if(b==="web_search"){let{query:S,limit:H=10,aiMode:se=!1}=ne(N.args);X=`${S?"\u2714":"\u2718"} ${se?"AI Search":"Searched"}: ${S?`${S}`:"No Search Query"}${se===!1&&S?` \u2192 ${H}`:""}`}else if(b==="web_scrape"){let S=ne(N.args).url||null;X=`${S?"\u2714":"\u2718"} Visited: ${S||"No Source"}`}else if(b==="view_file"){let{path:S,StartLine:H,EndLine:se,start_line:ge,end_line:we,startLine:Ne,endLine:De}=ne(N.args),Ce=H||ge||Ne,J=se||we||De,ce=parseInt(Ce)||1,ue=parseInt(J)||(Ce?ce+800:800),je="...",ze=ue,he=(S||"").trim().toLowerCase().replaceAll("\\","/");if(he.startsWith("#skill"))he.startsWith("#skill/global/fluxflow")||he.startsWith("#skills/global/fluxflow")||he.includes("#skill/fluxflow")||he.includes("#skills/fluxflow")?X="\u2714 Read Documentation":X=`\u2714 Read Skill: ${ie.basename(S.replaceAll("\\","/"))}`;else{try{let _e=ie.resolve(process.cwd(),S);if(Ue.existsSync(_e)){let bt=Ue.readFileSync(_e,"utf8").split(`
746
745
  `).length;je=bt,!Ce&&!J&&bt>800?ze=Math.min(50,bt):ze=Math.min(ue,bt)}}catch{}let Oe=(S||"").toLowerCase(),mt=Oe.endsWith(".pdf"),$e=Oe.endsWith(".docx")||Oe.endsWith(".doc")||Oe.endsWith(".ppt")||Oe.endsWith(".pptx")||Oe.endsWith(".xls")||Oe.endsWith(".xlsx"),tt=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(Oe);mt||$e?X=`${S.length>0?"\u2714":"\u2718"} ${S?`Analyzed: ${ie.basename(S)}`:"Analyzed: File Not Found"}`:tt?X=`${S.length>0?"\u2714":"\u2718"} ${S?`Processed: ${ie.basename(S)}`:"Processed: File Not Found"}`:X=`${je!=="..."?"\u2714":"\u2718"} Read: ${S?`${ie.basename(S)} \u2192 ${je!=="..."?`Lines ${ce} - ${ze} of ${je}`:"File Not Found"}`:"File Not Found"}`}}else if(b==="list_files"||b==="read_folder"){let S=b==="list_files"?"List":"Browsed",H=ne(N.args).path||null,se=ne(N.args).recurse||1;X=`${H?"\u2714":"\u2718"} ${S}: ${H?`${H==="."?`./${se>1?"*":""}`:`${H.replaceAll("\\","/")}${se>1?`${H.endsWith("/")?"*":"/*"}`:`${H.endsWith("/")?"":"/"}`}`}`:"No Folder Selected"}`}else if(b==="find_file"){let S=ne(N.args),H=S.basename||S.name||S.path||S.file||S.query||"";X=`${H?"\u2714":"\u2718"} Located: ${H||"No Query"}`}else if(b==="write_file"||b==="update_file"){let S=b==="write_file"?"Created":"Edited",H=ne(N.args),se=H.path||null,we=Object.entries(H).some(([Ne,De])=>Ne.startsWith("searchContent")&&typeof De=="string"&&De.startsWith("^LINE:"))?"\u1361":":";X=`${se?"\u2714":"\u2718"} ${S}${we} ${se?se.replaceAll("\\","/"):"No File Changes"}`}else if(b==="write_pdf"){let S=ne(N.args).path||null;X=`${S?"\u2714":"\u2718"} Generated: ${S.replaceAll("\\","/")||"No PDF Generated"}`}else if(b==="write_docx"){let S=ne(N.args).path||null;X=`${S?"\u2714":"\u2718"} Generated: ${S.replaceAll("\\","/")||"No Docx Generated"}`}else if(b==="file_map"){let S=ne(N.args).path;X=`${S?"\u2714":"\u2718"} Indexed: ${S.replaceAll("\\","/")?""+S:"File Not Found"}`}else if(b.toLowerCase()==="search_keyword"||b.toLowerCase()==="todo")X="";else if(b.toLowerCase()==="generate_image"){let{path:S,outputPath:H,output:se}=ne(N.args);X=`\u2714 Generated: ${S||H||se||"generated_image.png"}`}else if(b==="invoke_sync"||b==="InvokeSync"){let S=Kn(b,N.args);X=`\u2714 Called Generalist${S?`: ${S}`:""}`}else if(b==="Invoke"||b==="InvokeAsync"||b==="invoke"){let S=Kn(b,N.args);X=`\u2714 Started Generalist${S?`: ${S}`:""}`}else if(b==="get_progress"||b==="GetProgress"){let S=Kn(b,N.args);X=`\u2714 Checked${S?`: ${S}`:""}`}else if(b==="cancel"){let S=Kn(b,N.args);X=`\u{1F6C7} Cancelled${S?`: ${S}`:""}`}else if(b==="steer"||b==="Steer"){let S=Kn(b,N.args);X=`\u2714 Steered${S?`: ${S}`:""}`}else if(b==="EmergencyRollback"){let{method:S}=ne(N.args);X=S==="forceRevert"?"":"\u2714 Rollback Point Checked"}else if(b==="await"||b==="Await"){let{time:S,timeout:H}=ne(N.args),se=parseFloat(H||S)||0;se||(se=120);let ge=De=>{if(De>=60){let Ce=Math.floor(De/60),J=De%60;return`${Ce}m${J>0?` ${J}s`:""}`}return`${De}s`},we=["Aligning Moon Phase","Contemplating Existence","Staring At Void","Delaying Professionally","Negotiating With Electrons","Touching Grass (virtually)","Panicking Softly","Rethinking Career Choices","Loading Cat Videos","Summoning Braincell #2","Pretending To Be Busy","Waiting For Motivation DLC","Rotating Internal Screaming","Downloading More RAM","Feeding The Hamsters","Gaslighting Scheduler","Performing Dramatic Pause","Buffering Social Energy","Calculating Regret","Reading Terms And Conditions","Becoming Sentient Briefly","Contacting Ancestors"];X=`\u2714 ${we[Math.floor(Math.random()*we.length)]} \u2192 ${ge(se)}`}else b==="Answer"||b==="answer"?X="\u2714 Resolved Sub-Agent Query":b==="exec_command"||b==="ask"?X="":X=`Executed: ${N.toolName}`;if(yield*Nn(),b==="exec_command"){let{command:S}=ne(N.args);if(S&&n.systemSettings&&n.systemSettings.allowExternalAccess===!1){let H=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],se=ie.resolve(process.cwd()).substring(0,3).toLowerCase(),ge=J=>{let ce=[],ue="",je=null;for(let ze=0;ze<J.length;ze++){let he=J[ze];je?(he===je&&(je=null),ue+=he):he==='"'||he==="'"?(je=he,ue+=he):he==="&"&&J[ze+1]==="&"||he==="|"&&J[ze+1]==="|"?(ue.trim()&&(ce.push(ue.trim()),ue=""),ze++):he===";"||he==="|"||he==="&"?ue.trim()&&(ce.push(ue.trim()),ue=""):ue+=he}return ue.trim()&&ce.push(ue.trim()),ce},we=J=>{let ce=[],ue="",je=null;for(let ze=0;ze<J.length;ze++){let he=J[ze];je?(he===je&&(je=null),ue+=he):he==='"'||he==="'"?(je=he,ue+=he):/\s/.test(he)?ue&&(ce.push(ue),ue=""):ue+=he}return ue&&ce.push(ue),ce},Ne=J=>{let ce=J.replace(/^['"]|['"]$/g,"").trim();return!ce||process.platform==="win32"&&/^\/[a-zA-Z0-9?]+$/.test(ce)?!1:H.some(ue=>{if(ue.source==="[a-zA-Z]:[\\\\\\/]"){let je=ce.match(/[a-zA-Z]:[\\\/]/i);return je&&je[0].toLowerCase()!==se}return ue.test(ce)})};if(ge(S).some(J=>{let ce=we(J);if(ce.length===0)return!1;let ue=ce[0].replace(/^['"]|['"]$/g,"").toLowerCase();if(["echo","printf","write-output"].includes(ue)){let ze=!1;return ce.some(he=>{let _t=he.replace(/^['"]|['"]$/g,"");if(_t===">"||_t===">>"||_t==="<")return ze=!0,!1;if(_t.startsWith(">")||_t.startsWith("<")){let Oe=_t.replace(/^[><]+/,"");return Ne(Oe)}return ze?(ze=!1,Ne(he)):!1})}return ce.some(ze=>Ne(ze))})){let J='Access Denied. Prohibited from accessing external directories while "External Workspace Access" is disabled.';n.onExecStart&&n.onExecStart(S||"No Command"),yield{type:"exec_start"},await new Promise(ce=>setTimeout(ce,50)),n.onExecChunk&&n.onExecChunk(`ERROR: ${J}`),await new Promise(ce=>setTimeout(ce,50)),n.onExecEnd&&n.onExecEnd(),Me.push({role:"user",text:`[ACTION RESULT]: ERROR: ${J}`}),yield{type:"tool_result",content:`[ACTION RESULT]: ERROR: ${J}`},ut++;continue}}n.onExecStart&&n.onExecStart(S||"No Command"),yield{type:"exec_start"}}let $t=ne(N.args),Bn=$t.path||$t.targetPath||null;if(Bn){let S=n.systemSettings&&n.systemSettings.allowExternalAccess===!1,H=ie.resolve(Bn),se=ie.resolve(process.cwd());if(S&&!H.startsWith(se)){let ge="Access Denied. You are not allowed to access files outside the current workspace.";if(b==="write_file"||b==="update_file"){let Ne=`\u2718 ${b==="write_file"?"Write Canceled":"Edit Canceled"}: ${$t.path||"..."}`,De=115;process.stdout.isTTY&&(De=process.stdout.columns-5||120);let Ce=Math.min(Ne.length+4,De),J=`${Ne.padEnd(Ce-2).substring(0,Ce-2)}`;yield{type:"visual_feedback",content:Yt(`${Ye?`
747
746
  `:""}${J}
748
747
  `)},Ye=!1}Me.push({role:"user",text:`[ACTION RESULT]: ERROR: ${ge}`}),yield{type:"tool_result",content:`[ACTION RESULT]: ERROR: ${ge}`},ut++;continue}}if(n.onToolApproval&&(b==="write_file"||b==="update_file"||b==="exec_command")){let H=n.systemSettings||{},se=H.autoExec,ge=null,we=!1,Ne=!1,De=!1;if(b==="exec_command"){let{command:Oe}=ne(N.args),mt=(Oe||"").trim(),$e=(Gt,bt)=>{if(!bt)return!1;let Zt=bt.split(",").map(jt=>jt.trim().toLowerCase()).filter(Boolean),at=Gt.toLowerCase();return Zt.some(jt=>at.startsWith(jt))},tt=$e(mt,H.alwaysAskCommands),_e=$e(mt,H.autoApproveCommands);if(Ne=$e(mt,H.autoDisallowCommands),tt?we=!0:(_e||H.autoApproveGit&&/^git\s+commit\b/i.test(mt))&&(ge="allow"),!we&&!ge){if(H.networkAccess===!1){let bt=mt.trim().replace(/\s+/g," ").replace(/^['"]+|['"]+$/g,"").toLowerCase().split(" "),at=bt[0].split("/").pop().split("\\").pop().replace(/\.exe$/,""),jt=new Set(["curl","wget","httpie","xh","ssh","scp","sftp","rsync","ftp","lftp","tftp","telnet","nc","netcat","socat","ping","traceroute","tracert","dig","nslookup","host","whois","nmap","docker","podman","kubectl","helm","gcloud","aws","az","terraform","ansible-playbook","nix","nix-env","apt","apt-get","dpkg","yum","dnf","pacman","zypper","brew","apk","choco","scoop","conda","mamba","aria2c","axel","smbclient","lynx","w3m","links","elinks","heroku","netlify","vercel","firebase","supabase","wrangler","flyctl","powershell","pwsh","certutil","bitsadmin","cloudflared","ngrok","tailscale","zerotier","rclone"]),lt=!1;jt.has(at)&&(lt=!0);let nt=En=>bt.slice(1).some(mn=>En.includes(mn)),ct=En=>{let mn=bt.findIndex(pn=>En.includes(pn)),Un=bt.findIndex(pn=>["run","exec","test"].includes(pn));return mn!==-1&&!(Un!==-1&&Un<mn)};at==="git"&&nt(["clone","pull","push","fetch"])&&(lt=!0),at==="go"&&nt(["get","install"])&&(lt=!0),at==="npm"&&ct(["install","i","update","add"])&&(lt=!0),at==="yarn"&&ct(["add","install","upgrade"])&&(lt=!0),at==="pnpm"&&ct(["add","install","update"])&&(lt=!0),at==="bun"&&ct(["add","install","update"])&&(lt=!0),at==="deno"&&nt(["install","add"])&&(lt=!0),at==="pip"&&nt(["install","download"])&&(lt=!0),at==="pip3"&&nt(["install","download"])&&(lt=!0),at==="cargo"&&nt(["install","add"])&&(lt=!0),["bash","sh","zsh","fish"].includes(at)&&nt(["-c"])&&(lt=!0),at==="cmd"&&nt(["/c"])&&(lt=!0),lt&&(ge="deny",De=!0)}!ge&&Ne&&(ge="deny")}!we&&!ge&&se&&(ge="allow")}else se&&(ge="allow");let Ce=ge,J="";ge==="deny"&&(De?J="network":Ne?J="settings":J="prohibited");let ce=!1,ue="",je=[],ze=0,he=!1,_t="";if(!Ce){if(b==="write_file"||b==="update_file")try{let $e=ne(N.args),{path:tt}=$e;if(tt){let _e=ie.resolve(process.cwd(),tt),Gt=nt=>nt?nt.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,ct=>ct.toUpperCase()):"",bt=Gt(_e),Zt="",at=!1,jt=await Hn(),lt=Gt(jt?.file_focused);if(jt&&lt===bt&&jt.full_content?(Zt=jt.full_content,at=!0):Ue.existsSync(_e)&&(Zt=Ue.readFileSync(_e,"utf8"),at=!0),ue=Zt,await Oo.recordFileChange(_e,Zt),at){let nt=Zt;if(b==="write_file"){let ct=$e.content||$e.newContent||"";nt=ct.endsWith(`
749
748
  `)?ct:ct+`
750
- `,_t=nt}else{let{patchPairs:ct,allowMultiple:En,error:mn}=Si($e);if(mn){let Xt=`[ACTION RESULT]: ERROR: ${mn}`;Me.push({role:"user",text:Xt}),await Rt("toolFailure"),n.onToolResult&&n.onToolResult("failure",b),yield{type:"tool_result",content:Xt,toolName:b},ut++;continue}let Un=$e.allowMultiple!==void 0?$e.allowMultiple===!0||String($e.allowMultiple).toLowerCase()==="true":En;ze=ct.length;let pn=_i(Zt,ct,{allowMultiple:Un});nt=pn.content,_t=nt,je=pn.results;let Eo=je.filter(Xt=>Xt.success),xs=je.filter(Xt=>!Xt.success);if(Eo.length===0){let Xt=`[ACTION RESULT]: ERROR: Failed to apply patches to [${ie.basename(_e)}].
749
+ `,_t=nt}else{let{patchPairs:ct,allowMultiple:En,error:mn}=Ti($e);if(mn){let Xt=`[ACTION RESULT]: ERROR: ${mn}`;Me.push({role:"user",text:Xt}),await Rt("toolFailure"),n.onToolResult&&n.onToolResult("failure",b),yield{type:"tool_result",content:Xt,toolName:b},ut++;continue}let Un=$e.allowMultiple!==void 0?$e.allowMultiple===!0||String($e.allowMultiple).toLowerCase()==="true":En;ze=ct.length;let pn=Si(Zt,ct,{allowMultiple:Un});nt=pn.content,_t=nt,je=pn.results;let Eo=je.filter(Xt=>Xt.success),xs=je.filter(Xt=>!Xt.success);if(Eo.length===0){let Xt=`[ACTION RESULT]: ERROR: Failed to apply patches to [${ie.basename(_e)}].
751
750
  ${xs.map(Co=>` \u2022 ${Co.error}`).join(`
752
751
  `)}`,oo=`\u2714 Edited: ${ie.basename(_e.replaceAll("\\","/"))}`,dt=115;process.stdout.isTTY&&(dt=process.stdout.columns-5||120);let Kt=Math.min(oo.length+4,dt),so=`${oo.padEnd(Kt-2).substring(0,Kt-2)}`;yield{type:"visual_feedback",content:Yt(`${Ye?`
753
752
  `:""}${so}`)},Ye=!1,Me.push({role:"user",text:Xt}),await Rt("toolFailure"),n.onToolResult&&n.onToolResult("failure",b),yield{type:"tool_result",content:Xt,toolName:b},ut++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${ie.basename(_e)}`},zs(_e,Zt,nt),ce=!0,await new Promise(ct=>setTimeout(ct,50))}else if(b==="write_file"){let nt=$e.content||$e.newContent||"",ct=nt.endsWith(`
754
753
  `)?nt:nt+`
755
- `;_t=ct,Ue.existsSync(_e)||(he=!0,Ue.mkdirSync(ie.dirname(_e),{recursive:!0}),Ue.writeFileSync(_e,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${ie.basename(_e)}`},zs(_e,"",ct),ce=!0,await new Promise(En=>setTimeout(En,50))}}}catch($e){console.error("Simulation/Diff Error:",$e)}let Oe=null;qs($e=>{Oe=$e});let mt=n.onToolApproval;if(Ce=await new Promise(async $e=>{let tt=setInterval(()=>{Oe&&(as.onIDEApproval&&as.onIDEApproval(Oe),clearInterval(tt),$e(Oe))},100);try{let _e=await mt(b,N.args);clearInterval(tt),$e(_e)}catch{clearInterval(tt),$e("deny")}}),qs(null),b==="write_file"||b==="update_file"){let{path:$e}=ne(N.args);if($e){let tt=ie.resolve(process.cwd(),$e);if(Fr(tt,Ce),Ce==="deny"&&he&&Ue.existsSync(tt))try{Ue.unlinkSync(tt)}catch{}}}Ce==="deny"&&(J="user")}if(Ce==="allow"&&ce&&zo()){let{path:Oe}=ne(N.args),mt=ie.resolve(process.cwd(),Oe),$e=dt=>dt?ie.resolve(dt).replace(/\\/g,"/").toLowerCase():"",tt=await Hn(),_e="";if(tt&&tt.file_focused&&$e(tt.file_focused)===$e(mt)&&tt.full_content&&(_e=tt.full_content),!_e&&Ue.existsSync(mt)){let dt=Ue.readFileSync(mt,"utf8");dt&&(_e=dt)}!_e&&_t&&(_e=_t),(_e||he)&&Ue.writeFileSync(mt,_e,"utf8");let Gt=_e.split(/\r?\n/),bt=Gt.length,Zt=Buffer.byteLength(_e,"utf8"),at="";ue&&(at=`Old File contents:
754
+ `;_t=ct,Ue.existsSync(_e)||(he=!0,Ue.mkdirSync(ie.dirname(_e),{recursive:!0}),Ue.writeFileSync(_e,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${ie.basename(_e)}`},zs(_e,"",ct),ce=!0,await new Promise(En=>setTimeout(En,50))}}}catch($e){console.error("Simulation/Diff Error:",$e)}let Oe=null;qs($e=>{Oe=$e});let mt=n.onToolApproval;if(Ce=await new Promise(async $e=>{let tt=setInterval(()=>{Oe&&(as.onIDEApproval&&as.onIDEApproval(Oe),clearInterval(tt),$e(Oe))},100);try{let _e=await mt(b,N.args);clearInterval(tt),$e(_e)}catch{clearInterval(tt),$e("deny")}}),qs(null),b==="write_file"||b==="update_file"){let{path:$e}=ne(N.args);if($e){let tt=ie.resolve(process.cwd(),$e);if(Nr(tt,Ce),Ce==="deny"&&he&&Ue.existsSync(tt))try{Ue.unlinkSync(tt)}catch{}}}Ce==="deny"&&(J="user")}if(Ce==="allow"&&ce&&zo()){let{path:Oe}=ne(N.args),mt=ie.resolve(process.cwd(),Oe),$e=dt=>dt?ie.resolve(dt).replace(/\\/g,"/").toLowerCase():"",tt=await Hn(),_e="";if(tt&&tt.file_focused&&$e(tt.file_focused)===$e(mt)&&tt.full_content&&(_e=tt.full_content),!_e&&Ue.existsSync(mt)){let dt=Ue.readFileSync(mt,"utf8");dt&&(_e=dt)}!_e&&_t&&(_e=_t),(_e||he)&&Ue.writeFileSync(mt,_e,"utf8");let Gt=_e.split(/\r?\n/),bt=Gt.length,Zt=Buffer.byteLength(_e,"utf8"),at="";ue&&(at=`Old File contents:
756
755
  ${ue.split(/\r?\n/).map((Kt,so)=>`${so+1} | ${Kt}`).join(`
757
756
  `)}
758
757
 
@@ -763,16 +762,16 @@ ${ue.split(/\r?\n/).map((Kt,so)=>`${so+1} | ${Kt}`).join(`
763
762
 
764
763
  ... [${bt-100} lines truncated for history stability] ...
765
764
 
766
- ${Kt}`}let lt="";if(b==="update_file"){let dt=Ai(ue,_e,je,12,n?.compressToolResults||as?.systemSettings?.compressToolResults);lt=`SUCCESS: File [${Oe}] updated via IDE Companion (May have user edits). [${je.length}/${ze}] blocks applied.
765
+ ${Kt}`}let lt="";if(b==="update_file"){let dt=_i(ue,_e,je,12,n?.compressToolResults||as?.systemSettings?.compressToolResults);lt=`SUCCESS: File [${Oe}] updated via IDE Companion (May have user edits). [${je.length}/${ze}] blocks applied.
767
766
 
768
767
  ${dt}`}else{let dt=_e.split(/\r?\n/),Kt=dt.length,so=Buffer.byteLength(_e,"utf8"),Co="";ue&&(Co=`Old File contents:
769
768
  ${ue.split(/\r?\n/).map((ws,ua)=>`${ua+1} | ${ws}`).join(`
770
769
  `)}
771
770
 
772
771
  `);let bs="";if(Kt<=100)bs=dt.join(`
773
- `);else{let ki=dt.slice(0,50).join(`
772
+ `);else{let wi=dt.slice(0,50).join(`
774
773
  `),ws=dt.slice(-50).join(`
775
- `);bs=`${ki}
774
+ `);bs=`${wi}
776
775
 
777
776
  ... [${Kt-100} lines truncated] ...
778
777
 
@@ -785,7 +784,7 @@ ${bs}`}let nt=b==="write_file"?"Created":"Edited",ct=ne(N.args),mn=Object.entrie
785
784
  `:""}${Gt}
786
785
  `)},Ye=!1}b==="exec_command"&&(await new Promise(mt=>setTimeout(mt,50)),n.onExecChunk&&n.onExecChunk(`ERROR: ${Oe}`),await new Promise(mt=>setTimeout(mt,50)),n.onExecEnd&&n.onExecEnd()),Me.push({role:"user",text:`[ACTION RESULT]: DENIED: ${Oe}`}),yield{type:"tool_result",content:`[ACTION RESULT]: DENIED: ${Oe}`},await Rt("toolDenied"),n.onToolResult&&n.onToolResult("denied",b),ut++;continue}}if(X){let S=115;process.stdout.isTTY&&(S=process.stdout.columns-5||120);let H=await s(),se=!1;H&&(se=H.trim().length>0);let ge=Math.min(X.length+4,S),we=`${X.padEnd(ge-2).substring(0,ge-2)}`;yield{type:"visual_feedback",content:Yt(`${Ye?`
787
786
  `:""}${we}${X.includes("\u2714")&&(X.includes("Created")||X.includes("Edited"))?"":`${se?"":`
788
- `}`}`)},Ye=!1}if(We>0){let S=Date.now()-We,H=Math.max(0,1e3-S);H>0&&await new Promise(se=>setTimeout(se,H))}let An={chatId:p,history:t,onChunk:S=>n.onExecChunk?n.onExecChunk(S):null,onAskUser:n.onAskUser,systemSettings:n.systemSettings,mode:l,isMultiModal:ft(Se),onVisualFeedback:n.onVisualFeedback,onSubagentUpdate:n.onSubagentUpdate,onTokenChunk:n.onTokenChunk,modelName:Se,aiProvider:n.aiProvider,apiKey:n.apiKey,onUsage:n.onUsage};if(b==="write_file"||b==="update_file")try{let{path:S}=ne(N.args);if(S){let H=ie.resolve(process.cwd(),S),se=await Hn();se&&se.file_focused===H&&se.full_content&&(An.forcedContent=se.full_content)}}catch{}ot.push(b);let Le=await xo(b,N.args,An);if((b==="write_file"||b==="update_file")&&Le.startsWith("SUCCESS")){let{path:S}=ne(N.args);if(S){let H=ie.resolve(process.cwd(),S);Nr(H)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let Nt=Date.now();We=Nt,yield{type:"tool_time",content:Nt-V},K=Nt;let Ht=null;if(typeof Le=="object"&&Le.binaryPart&&(Ht=Le.binaryPart,Le=Le.text),b==="search_keyword"){let{keyword:S,path:H}=ne(N.args),se=typeof Le=="string"&&Le.startsWith("[GLOB]");se&&(Le=Le.slice(6).trimStart());let ge=typeof Le=="string"&&Le.startsWith("[DIR]");ge&&(Le=Le.slice(5).trimStart());let we=0;if(Le){let he=Le.match(/Found (\d+) match/i);he&&(we=parseInt(he[1]))}let Ne=(H||"").trim().toLowerCase().replaceAll("\\","/"),De=Ne==="#doc"||Ne==="#docs"||Ne==="#documentation"||Ne.includes("#skill/global/fluxflow")||Ne.includes("#skill/fluxflow")||Ne.includes("#skills/fluxflow")||Ne.includes("#skills/global/fluxflow"),Ce,J=115;process.stdout.isTTY&&(J=process.stdout.columns-5||120);let ce=Math.max(10,(J+5)/3),ue=Math.max(10,(J+5)/4);if(De)Ce=`${S?"\u2714":"\u2718"} Searched Documentation`;else{let he=H?H.replace(/[\/\\]+$/,""):null,_t=he&&he!=="."?`"${se?H:ge?`${he}/*`:he}"`:"./",Oe=_t.length>ue?`${_t.slice(0,ue)}...`:_t;Ce=`${S?"\u2714":"\u2718"} Searched: "${S?S.length>J/2?`${S.slice(0,ce)}...`:S:""}" in ${Oe.replaceAll("\\","/")} \u2192 ${we} Match${we===1?"":"es"}`}let je=Math.min(Ce.length+4,J),ze=`${Ce.padEnd(je-2).substring(0,je-2)}`;yield{type:"visual_feedback",content:Yt(`${Ye?`
787
+ `}`}`)},Ye=!1}if(We>0){let S=Date.now()-We,H=Math.max(0,1e3-S);H>0&&await new Promise(se=>setTimeout(se,H))}let An={chatId:p,history:t,onChunk:S=>n.onExecChunk?n.onExecChunk(S):null,onAskUser:n.onAskUser,systemSettings:n.systemSettings,mode:l,isMultiModal:ft(Se),onVisualFeedback:n.onVisualFeedback,onSubagentUpdate:n.onSubagentUpdate,onTokenChunk:n.onTokenChunk,modelName:Se,aiProvider:n.aiProvider,apiKey:n.apiKey,onUsage:n.onUsage};if(b==="write_file"||b==="update_file")try{let{path:S}=ne(N.args);if(S){let H=ie.resolve(process.cwd(),S),se=await Hn();se&&se.file_focused===H&&se.full_content&&(An.forcedContent=se.full_content)}}catch{}ot.push(b);let Le=await xo(b,N.args,An);if((b==="write_file"||b==="update_file")&&Le.startsWith("SUCCESS")){let{path:S}=ne(N.args);if(S){let H=ie.resolve(process.cwd(),S);$r(H)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let Nt=Date.now();We=Nt,yield{type:"tool_time",content:Nt-V},K=Nt;let Ht=null;if(typeof Le=="object"&&Le.binaryPart&&(Ht=Le.binaryPart,Le=Le.text),b==="search_keyword"){let{keyword:S,path:H}=ne(N.args),se=typeof Le=="string"&&Le.startsWith("[GLOB]");se&&(Le=Le.slice(6).trimStart());let ge=typeof Le=="string"&&Le.startsWith("[DIR]");ge&&(Le=Le.slice(5).trimStart());let we=0;if(Le){let he=Le.match(/Found (\d+) match/i);he&&(we=parseInt(he[1]))}let Ne=(H||"").trim().toLowerCase().replaceAll("\\","/"),De=Ne==="#doc"||Ne==="#docs"||Ne==="#documentation"||Ne.includes("#skill/global/fluxflow")||Ne.includes("#skill/fluxflow")||Ne.includes("#skills/fluxflow")||Ne.includes("#skills/global/fluxflow"),Ce,J=115;process.stdout.isTTY&&(J=process.stdout.columns-5||120);let ce=Math.max(10,(J+5)/3),ue=Math.max(10,(J+5)/4);if(De)Ce=`${S?"\u2714":"\u2718"} Searched Documentation`;else{let he=H?H.replace(/[\/\\]+$/,""):null,_t=he&&he!=="."?`"${se?H:ge?`${he}/*`:he}"`:"./",Oe=_t.length>ue?`${_t.slice(0,ue)}...`:_t;Ce=`${S?"\u2714":"\u2718"} Searched: "${S?S.length>J/2?`${S.slice(0,ce)}...`:S:""}" in ${Oe.replaceAll("\\","/")} \u2192 ${we} Match${we===1?"":"es"}`}let je=Math.min(Ce.length+4,J),ze=`${Ce.padEnd(je-2).substring(0,je-2)}`;yield{type:"visual_feedback",content:Yt(`${Ye?`
789
788
  `:""}${ze}
790
789
  `)},Ye=!1}if(b==="EmergencyRollback"){let{method:S}=ne(N.args);if(S==="forceRevert"){let H=0;if(Le){let ce=Le.match(/Total\s*:\s*(\d+)/i);ce&&(H=parseInt(ce[1]))}let ge=Le&&Le.startsWith("ERROR:")?"\u2718 Emergency Rollback Failed":`\u2714 Emergency Rollback \u2192 ${H} file${H===1?"":"s"} processed`,we=115;process.stdout.isTTY&&(we=process.stdout.columns-5||120);let Ne=await s(),De=!1;Ne&&(De=Ne.trim().length>0);let Ce=Math.min(ge.length+4,we),J=`${ge.padEnd(Ce-2).substring(0,Ce-2)}`;yield{type:"visual_feedback",content:Yt(`${Ye?`
791
790
  `:""}${J}${De?"":`
@@ -817,7 +816,7 @@ ${bs}`}let nt=b==="write_file"?"Created":"Edited",ct=ne(N.args),mn=Object.entrie
817
816
 
818
817
  ${Et}`}):r.push(Tt)}):r.push({role:"user",text:Et}),xt+=Te}for(let Et=Pt/1e3;Et>0&&!wt;Et--)yield{type:"status",content:`Error Occured. Recovering Stream (${rt}/${on}) [Retrying in ${Et.toFixed(0)}s]...`},await new Promise(Tt=>setTimeout(Tt,1e3));yield{type:"status",content:"Error Occured. Recovering Stream..."}}else throw new Error(`Stream collapsed too many times. (Failed to resolve ${on} times)
819
818
  Error log can be found in \`/export logs\``);else if(et<=on){et++,rt=1,xt="";let Pt=Math.min(1e3*Math.pow(2,et-1),32e3),Et=.8+Math.random()*.4,Tt=Math.round(Pt*Et);Zn=!0,yield{type:"status",content:`Trying to reach ${e} (${et}/${on}) [Retrying in ${(Tt/1e3).toFixed(0)}s]`};for(let It=Tt/1e3;It>0&&!wt;It--)yield{type:"status",content:`Trying to reach ${e} (${et}/${on}) [Retrying in ${It.toFixed(0)}s]`},await new Promise(gt=>setTimeout(gt,1e3));yield{type:"status",content:`Trying to reach ${e}`}}else throw new Error(`Model ${e} cannot be reached. (Failed ${on} times)
820
- Error log can be found in \`/export logs\``)}}if(Jt){let me=Jt.totalTokenCount||0,Ae=Jt.cachedContentTokenCount||0,ee=(Jt.candidatesTokenCount||0)+(i==="Google"&&Jt.thoughtsTokenCount||0);await Bt("tokens",me,i,Se),Ae>0&&await Bt("cachedTokens",Ae,i,Se),ee>0&&await Bt("candidateTokens",ee,i,Se),Do({provider:i,model:Se,prompt:Jt.promptTokenCount||0,cached:Ae,output:ee,reasoning:Jt.thoughtsTokenCount||0}),yield{type:"usage",content:Jt}}Te=zr(Te),hs.push(Te);let Sn=qt(Te),Pn=Kr(Te),un=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(Pn.toLowerCase())||/\[\[END\]\]/i.test(Pn.toLowerCase())||!0,il=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(Pn.toLowerCase()),rl=ut>0;yield{type:"status",content:"Thinking"};let na=Za(Te,/(\[\s*(turn\s*:)?\s*(continue|finish)\s*\]|\[\[END\]\])/gi,"").trim(),$n=(un||Me.length===0)&&!vt&&!rn&&!Tn;if($n=Me.length===0?$n:!1,$n=Ot||_o?!1:$n,Te&&Te.trim().endsWith('")]')&&Me.length===0&&($n=!1),$n){yi=!0;let me=hs.join(`
819
+ Error log can be found in \`/export logs\``)}}if(Jt){let me=Jt.totalTokenCount||0,Ae=Jt.cachedContentTokenCount||0,ee=(Jt.candidatesTokenCount||0)+(i==="Google"&&Jt.thoughtsTokenCount||0);await Bt("tokens",me,i,Se),Ae>0&&await Bt("cachedTokens",Ae,i,Se),ee>0&&await Bt("candidateTokens",ee,i,Se),Do({provider:i,model:Se,prompt:Jt.promptTokenCount||0,cached:Ae,output:ee,reasoning:Jt.thoughtsTokenCount||0}),yield{type:"usage",content:Jt}}Te=qr(Te),hs.push(Te);let Sn=qt(Te),Pn=jr(Te),un=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(Pn.toLowerCase())||/\[\[END\]\]/i.test(Pn.toLowerCase())||!0,il=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(Pn.toLowerCase()),rl=ut>0;yield{type:"status",content:"Thinking"};let na=Za(Te,/(\[\s*(turn\s*:)?\s*(continue|finish)\s*\]|\[\[END\]\])/gi,"").trim(),$n=(un||Me.length===0)&&!vt&&!rn&&!Tn;if($n=Me.length===0?$n:!1,$n=Ot||_o?!1:$n,Te&&Te.trim().endsWith('")]')&&Me.length===0&&($n=!1),$n){pi=!0;let me=hs.join(`
821
820
  `),Ae=qt(me).trim();yield{type:"interactive_turn_finished",data:{agentText:a,fullAgentTextRaw:me,history:[...r],needTitle:y}},r.length>0&&r[r.length-1].role==="agent"?r[r.length-1].text=Ae:r.push({role:"agent",text:Ae}),r.forEach(ee=>{if(ee.role==="user"&&ee.text&&(ee.text=ee.text.replace(/\n\[COMPILE ERROR\][\s\S]*?\[\/ERROR\]/g,""),ee.text=ee.text.replaceAll(`
822
821
 
823
822
  [system] user question. resolve this specific query within '[ANSWER] ... [/ANSWER]' concisely, naturally [/system]
@@ -834,7 +833,7 @@ Error log can be found in \`/export logs\``)}}if(Jt){let me=Jt.totalTokenCount||
834
833
  ${Yt("\u2718 Execution Error")}
835
834
  `}):(yield{type:"visual_feedback",content:`
836
835
  ${Yt("\u2718 Loop Detected")}
837
- `},r.push({role:"user",text:`[system] ${rn&&!vt?"Stuttering Detected by Internal System. Re-calibrate your response & proceed.":`${vt?" Over Thinking":" Loop"} Detected by Internal System${vt?" for current Effort Level":""}. ${vt?"If you have planned the task, prioritize execution/output":"If you have finished your task provide a simple summary and end"}`} [/system]`})),vt=!1,rn=!1,Tn=!1}T?.advanceRollback&&await lo.recordTurnDelta(p,j+1,ot),_o=ut>0||kn}if(!yi&&!wt){let j="\u2726 Turn safety limit reached. Stopping execution.";yield{type:"text",content:`
836
+ `},r.push({role:"user",text:`[system] ${rn&&!vt?"Stuttering Detected by Internal System. Re-calibrate your response & proceed.":`${vt?" Over Thinking":" Loop"} Detected by Internal System${vt?" for current Effort Level":""}. ${vt?"If you have planned the task, prioritize execution/output":"If you have finished your task provide a simple summary and end"}`} [/system]`})),vt=!1,rn=!1,Tn=!1}T?.advanceRollback&&await lo.recordTurnDelta(p,j+1,ot),_o=ut>0||kn}if(!pi&&!wt){let j="\u2726 Turn safety limit reached. Stopping execution.";yield{type:"text",content:`
838
837
 
839
838
  ${j}
840
839
  `};let Ke=(hs.join(`
@@ -858,11 +857,11 @@ Rules:
858
857
 
859
858
  # Provided Actions
860
859
  **Communication**
861
- - AskUser(question=string, optionA?="title::description", ...MAX4). Ambiguity, path divergence, security risk
860
+ - AskUser(question=string, optionA?="title::description", ...MAX4). Any Ambiguity
862
861
  ${f?"- AskMain(question=string). Communicate with PARENT/MAIN AGENT. When clarification/decision is needed for a task":""}
863
862
 
864
863
  **Web**
865
- - WebSearch(query=string, aiMode?=bool, limit?=int[3..10]). Proactive use for unknown/latest info. aiMode: slower, exclude limit
864
+ - WebSearch(query=string, aiMode?=bool:false, limit?=int[3..10]). Proactive use for unknown/latest info. aiMode: exclude limit
866
865
  - WebScrape(url=string). Proactive use for specific webpage/docs
867
866
 
868
867
  **Workspace**
@@ -872,7 +871,7 @@ ${f?"- AskMain(question=string). Communicate with PARENT/MAIN AGENT. When clarif
872
871
  - ReadFile(path=string, startLine?=int, endLine?=int)
873
872
  - 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
874
873
  - WriteFile(path=string, content=string). Creates/Overwrites. File Exist? PatchFile > WriteFile
875
- - Run(command=string). Runs ${C==="Windows"?Ei()?"powershell":"windows CMD":"bash"} command. Destructive command \u2192 Ask user`.trim(),_=`=== START SYSTEM PROMPT ===
874
+ - Run(command=string). Runs ${C==="Windows"?Ai()?"powershell":"windows CMD":"bash"} command. Destructive command \u2192 Ask user`.trim(),_=`=== START SYSTEM PROMPT ===
876
875
  Identity: FluxFlow subagent helping the main Agent
877
876
  Your task is: "${e}"
878
877
  CWD: ${process.cwd()}
@@ -885,7 +884,7 @@ Main focus: actions and task, not chatting
885
884
  On completion, provide a detailed summary in Tables/Markdown Format with file modified info. If any task failed report back in detail
886
885
 
887
886
  Current Time: ${m}
888
- === END SYSTEM PROMPT ===`,M=[{role:"user",text:`Complete this task: ${e}`}],y=0,a="";for(;y<o;){let R=await _s("subagent",k);if(!R.allowed)throw new Error(R.reason||`Budget Exhausted for Provider (${k?.aiProvider||"Subagent"})`);if(wt){if(t?.taskId&&typeof Vt<"u"){let L=Vt.find(F=>F.id===t.taskId);L&&(L.status="cancelled")}throw c&&c("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}if(t?.taskId&&typeof Vt<"u"){let L=Vt.find(F=>F.id===t.taskId);if(L&&L.status==="cancelled")throw c&&c("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}let d=M.map(L=>({role:L.role==="user"?"user":"model",parts:[{text:L.text}]}));c&&c(`[Subagent Turn ${y+1}]...`);let r=["Fast","Low","Medium","High"],E=process.env.SUBAGENT_THINKING,v=r.includes(E)?E:"Low",O=(await ls(k,$,d,_,v)).text||"",P=zr(qt(O).trim());a=P,c&&c(`[Subagent Response]
887
+ === END SYSTEM PROMPT ===`,M=[{role:"user",text:`Complete this task: ${e}`}],y=0,a="";for(;y<o;){let R=await _s("subagent",k);if(!R.allowed)throw new Error(R.reason||`Budget Exhausted for Provider (${k?.aiProvider||"Subagent"})`);if(wt){if(t?.taskId&&typeof Vt<"u"){let L=Vt.find(F=>F.id===t.taskId);L&&(L.status="cancelled")}throw c&&c("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}if(t?.taskId&&typeof Vt<"u"){let L=Vt.find(F=>F.id===t.taskId);if(L&&L.status==="cancelled")throw c&&c("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}let d=M.map(L=>({role:L.role==="user"?"user":"model",parts:[{text:L.text}]}));c&&c(`[Subagent Turn ${y+1}]...`);let r=["Fast","Low","Medium","High"],E=process.env.SUBAGENT_THINKING,v=r.includes(E)?E:"Low",O=(await ls(k,$,d,_,v)).text||"",P=qr(qt(O).trim());a=P,c&&c(`[Subagent Response]
889
888
  ${P}
890
889
  `),M.push({role:"agent",text:P});let re=ko(P);if(re.length===0)break;let de=re.filter(L=>L.toolName.toLowerCase()==="askmain"||L.toolName.toLowerCase()==="ask_main"),Q=!1,ke="";for(let L of re){if(wt){if(t?.taskId&&typeof Vt<"u"){let B=Vt.find(G=>G.id===t.taskId);B&&(B.status="cancelled")}throw new Error("Subagent task was cancelled.")}if(t?.taskId&&typeof Vt<"u"){let B=Vt.find(G=>G.id===t.taskId);if(B&&B.status==="cancelled")throw new Error("Subagent task was cancelled.")}let F=L.toolName.toLowerCase();if(F==="askuser"&&(F="ask"),F==="askmain"||F==="ask_main"){if(Q)continue;Q=!0;let B="";if(de.length===1?B=ne(de[0].args).question||de[0].args:B=de.map((G,ye)=>{let Re=ne(G.args);return`Q${ye+1}: ${Re.question||G.args}`}).join(`
891
890
  `),t.onAskMain){c&&c(`[Executing Tool] AskMain("${B}")...`);let G=await t.onAskMain(B);c&&c(`[Action Result]
@@ -911,4 +910,4 @@ ${B}
911
910
 
912
911
  `,await Rt("toolFailure")}}let ae="";if(t?.taskId&&typeof Vt<"u"){let L=Vt.find(F=>F.id===t.taskId);if(L&&L.pendingSteerMessages&&L.pendingSteerMessages.length>0){let F=[...L.pendingSteerMessages];L.pendingSteerMessages=[];for(let Ee of F)ae+=`
913
912
 
914
- [STEERING INSTRUCTION FROM MAIN AGENT]: ${Ee}`,c&&c(`[Subagent Steered] ${Ee}`)}}let it=(ke.trim()+ae).trim();M.push({role:"user",text:it}),y++}return a};export{bo as a,Lr as b,yc as c,xc as d,He as e,ul as f,gl as g,ac as h,lc as i,kc as j,zo as k,Tc as l,ja as m,cf as n,Ka as o,Va as p,oi as q,qt as r,jr as s,zr as t,Xa as u,df as v,ff as w,ri as x,uf as y,gf as z,ls as A,hf as B,mf as C,pf as D,yf as E};
913
+ [STEERING INSTRUCTION FROM MAIN AGENT]: ${Ee}`,c&&c(`[Subagent Steered] ${Ee}`)}}let it=(ke.trim()+ae).trim();M.push({role:"user",text:it}),y++}return a};export{bo as a,Or as b,yc as c,xc as d,He as e,ul as f,gl as g,ac as h,lc as i,kc as j,zo as k,Tc as l,ja as m,cf as n,Ka as o,Va as p,oi as q,qt as r,Gr as s,qr as t,Xa as u,df as v,ff as w,ri as x,uf as y,gf as z,ls as A,hf as B,mf as C,pf as D,yf as E};