fluxflow-cli 4.16.1 → 4.16.3

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 to}from"./chunk-VCF6JVQV.js";import{a as jt}from"./chunk-56EJGQU3.js";import{a as hs,h as fi}from"./chunk-KRRJNFBF.js";import{a as ui}from"./chunk-ZYJYKSIA.js";import{c as gs,g as ri,h as ai,i as li,m as ms}from"./chunk-M3KCPUDW.js";import{a as _o}from"./chunk-KFM2OZWJ.js";import{b as us}from"./chunk-72RYQ5W7.js";import{e as Et,g as Ft,i as si,j as ii}from"./chunk-WKHYRBBK.js";import{g as dt,h as Vn,k as de,l as eo}from"./chunk-AAPXJU65.js";import{c as _t,d as jn}from"./chunk-SIINYZWE.js";import{a as ci,c as di}from"./chunk-YVFWOJHY.js";import{a as en,d as wn,e as wo,j as On,k as To,l as ds,q as fs,u as So}from"./chunk-FDNLMLIM.js";import{a as Q}from"./chunk-Y5JU726N.js";import{GoogleGenAI as vr,ThinkingLevel as Je,HarmBlockThreshold as _n,HarmCategory as En}from"@google/genai";var gi=(e=!0,t=!0)=>`
1
+ import{a as to}from"./chunk-VCF6JVQV.js";import{a as jt}from"./chunk-56EJGQU3.js";import{a as hs,h as fi}from"./chunk-KRRJNFBF.js";import{a as ui}from"./chunk-ZYJYKSIA.js";import{c as gs,g as ri,h as ai,i as li,m as ms}from"./chunk-M3KCPUDW.js";import{a as Eo}from"./chunk-KFM2OZWJ.js";import{b as us}from"./chunk-72RYQ5W7.js";import{e as Et,g as Ft,i as si,j as ii}from"./chunk-WKHYRBBK.js";import{g as dt,h as Vn,k as de,l as eo}from"./chunk-AAPXJU65.js";import{c as _t,d as jn}from"./chunk-SIINYZWE.js";import{a as ci,c as di}from"./chunk-YVFWOJHY.js";import{a as en,d as wn,e as To,j as On,k as So,l as ds,q as fs,u as _o}from"./chunk-FDNLMLIM.js";import{a as Z}from"./chunk-Y5JU726N.js";import{GoogleGenAI as vr,ThinkingLevel as Je,HarmBlockThreshold as _n,HarmCategory as En}from"@google/genai";var gi=(e=!0,t=!0)=>`
2
2
  To use tools, must output exactly '[tool:functions.ToolName(arg1="value1")]' structured string in chat response \u2190 no exception
3
3
 
4
4
  -- Chat Management Tools --
@@ -26,7 +26,7 @@ Usage Rules:
26
26
  - Chat title is mandatory
27
27
  - Temporary memory is mandatory
28
28
  - When called user memory, still use Temporary Memory
29
- - Must not ignore any tool calls in given context of chat between user & agent`:""}`.trim();var Eo={xHigh:`Effort: High
29
+ - Must not ignore any tool calls in given context of chat between user & agent`:""}`.trim();var Ao={xHigh:`Effort: High
30
30
  Think before complex tasks
31
31
  Prefer simplest correct solution, assess architecture, performance & maintainability, verify error handling, assumptions, edge cases, dependencies & regressions, plan: files, functions, logic & interactions
32
32
  Verify from first principles, seek failure paths, verify imports, system stability
@@ -46,7 +46,7 @@ Dont waste tokens, be efficient, use least thinking tokens, focus on result
46
46
  Gather useful context
47
47
  Brief thoughts, think only enough to avoid mistakes, verify imports, system stability`,Off:`Effort: Lowest
48
48
  No thinking. Immediate response
49
- Verify imports, tool results & system stability`};import Sn from"fs";import Io from"path";import Jr from"os";import ln from"fs";import Tn from"path";import Ai from"fs";import ps from"path";import{execSync as Ci}from"child_process";import{fileURLToPath as zr}from"url";var mi=`# FluxFlow CLI Startup & Flags Reference
49
+ Verify imports, tool results & system stability`};import no from"fs";var hn=null,ps=()=>{try{if(no.existsSync(_o)){let e=no.readFileSync(_o,"utf-8"),t=JSON.parse(e);if(t&&typeof t=="object")return hn=t,hn}}catch{}return hn=hn||{},hn},mi=e=>{try{return no.existsSync(en)||no.mkdirSync(en,{recursive:!0}),no.writeFileSync(_o,JSON.stringify(e,null,2),"utf-8"),hn=e,!0}catch{return!1}},Oe=(e,t,n)=>{if(!e||!t||!n)return null;let s=hn||ps(),o=`${e}::${t}`,d=s[o];if(d&&typeof d=="object"){let f=n.toLowerCase();if(d[f]!==void 0&&d[f]!==null)return d[f];for(let[a,h]of Object.entries(d))if(a.toLowerCase()===f)return h}return null},Ya=(e,t,n,s)=>{if(!e||!t||!n||!s)return{success:!1,reason:"Invalid arguments"};let o=hn||ps(),d=`${e}::${t}`;return(!o[d]||typeof o[d]!="object")&&(o[d]={}),o[d][n.toLowerCase()]=s,{success:mi(o)}},qa=(e,t,n)=>{if(!e||!t)return{success:!1,reason:"Invalid arguments"};let s=hn||ps(),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 Sn from"fs";import ro from"path";import Jr from"os";import ln from"fs";import Tn from"path";import Ci from"fs";import ys from"path";import{execSync as Ri}from"child_process";import{fileURLToPath as zr}from"url";var hi=`# FluxFlow CLI Startup & Flags Reference
50
50
 
51
51
  Launch command syntax:
52
52
  fluxflow [options]
@@ -74,7 +74,7 @@ fluxflow [options]
74
74
  * --help \u2192 CLI help menu
75
75
  * --help commands \u2192 In-chat slash commands list
76
76
  * --playground \u2192 Launch Playground mode
77
- `;var hi=`# Env Variables
77
+ `;var pi=`# Env Variables
78
78
 
79
79
  * Locations:
80
80
  * Shell
@@ -101,7 +101,7 @@ fluxflow [options]
101
101
 
102
102
  * 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
103
103
  * GOOGLE_GEMMA_NONSENSE \u2192 (true|false, default: false) for the 16k TPM nonsense of gemma models on gemini API. False defaults to 256k
104
- `;var pi=`# Fluxflow in-app /commands
104
+ `;var yi=`# Fluxflow in-app /commands
105
105
 
106
106
  Trigger in chat via /command
107
107
 
@@ -144,7 +144,7 @@ Trigger in chat via /command
144
144
  * /changelog \u2192 Release notes
145
145
  * /update check \u2192 Check npm updates
146
146
  * /update latest \u2192 Install latest release
147
- `;var yi=`# FluxFlow In-App Settings Reference
147
+ `;var xi=`# FluxFlow In-App Settings Reference
148
148
 
149
149
  Open in chat via /settings
150
150
 
@@ -205,7 +205,7 @@ Open in chat via /settings
205
205
  - 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
206
206
 
207
207
  - 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
208
- `;var xi=`# FluxFlow Tool Reference
208
+ `;var bi=`# FluxFlow Tool Reference
209
209
 
210
210
  ## Protocol: [tool:functions.ToolName(arg1="val")]
211
211
 
@@ -245,7 +245,7 @@ Open in chat via /settings
245
245
  * KeyboardTyping(text, autoPressEnter?) \u2192 Type string
246
246
  * KeyPress(key) \u2192 Key/combo dispatch ("ctrl;c", "enter", etc.)
247
247
  * RecaptureScreen() \u2192 Fresh screenshot + coordinate grid
248
- `;var bi=`# Fluxflow Architecture
248
+ `;var ki=`# Fluxflow Architecture
249
249
 
250
250
  ## 1. Terminal Engine
251
251
  * Framework: React + Ink terminal UI
@@ -275,7 +275,7 @@ Open in chat via /settings
275
275
  ## 6. IDE Bridge
276
276
  * Protocol: WebSocket on ws://localhost:56832
277
277
  * State Sync: Focused file, open tabs, cursor line, selection, diagnostics
278
- `;var ki=`# FluxFlow Sub-Agents & Multi-Agent Architecture
278
+ `;var wi=`# FluxFlow Sub-Agents & Multi-Agent Architecture
279
279
 
280
280
  ## Execution Modes
281
281
  * InvokeSync \u2192 Synchronous blocking delegation; main agent halts until sub-agent finishes task
@@ -306,7 +306,7 @@ Route sub-agent workloads to faster/cheaper models independently of the main age
306
306
  * SUBAGENT_MODEL \u2192 Target model override
307
307
  * SUBAGENT_PROVIDER \u2192 Target provider override
308
308
  * Setting SubAgentModel=ENV in settings pulls directly from environment overrides
309
- `;var wi=`# FluxFlow Security, Sandboxing & Safety
309
+ `;var Ti=`# FluxFlow Security, Sandboxing & Safety
310
310
 
311
311
  ## Human-in-the-Loop Governance
312
312
  * Execution Approval Gate \u2192 Destructive commands and high-risk file modifications require explicit user authorization (Allow / Deny)
@@ -329,7 +329,7 @@ Route sub-agent workloads to faster/cheaper models independently of the main age
329
329
  * Emergency Rollback \u2192 Automatic pre-turn file snapshots; Agent can still fix it (default: OFF) \u2192 references/SETTINGS.md
330
330
  * Git-less Checkpoint Reversion \u2192 Trigger conversational changes rollback via double-ESC
331
331
  * External Sanctuary Redirection \u2192 Move ~/.fluxflow data sanctuary (chats, keys etc)
332
- `;var Ti=`# Fluxflow IDE Companion
332
+ `;var Si=`# Fluxflow IDE Companion
333
333
 
334
334
  ## WebSocket Bridge Protocol
335
335
  * Local Bridge \u2192 Runs on ws://localhost:56832 connecting FluxFlow CLI with the companion editor extension
@@ -347,7 +347,7 @@ Route sub-agent workloads to faster/cheaper models independently of the main age
347
347
  * File Focus \u2192 Automatically opens edited files in active IDE window
348
348
  * Diff Preview \u2192 Streams side-by-side or inline diff highlights (showDiff, highlightDiff) directly in editor
349
349
  * Status Bar Sync \u2192 Real-time agent status (thinking, running tool, awaiting input) reflected in IDE status bar
350
- `;var Si=`# Fluxflow Modes
350
+ `;var _i=`# Fluxflow Modes
351
351
 
352
352
  ## Modes Overview (TAB to cycle)
353
353
  * [Flux] (Workspace / Dev) \u2192 Primary coding & workspace agent
@@ -365,7 +365,7 @@ Route sub-agent workloads to faster/cheaper models independently of the main age
365
365
  * User Inquiry: AskUser \u2192 [Universal]
366
366
  * Document Creation: WritePDF, WriteDoc \u2192 [Flow]
367
367
  * GUI & Desktop Automation: Click, Drag, Scroll, KeyboardTyping, KeyPress, RecaptureScreen \u2192 [ICU] | [FluxCU]
368
- `;var _i=`# FluxFlow AI Providers & Setup
368
+ `;var Ei=`# FluxFlow AI Providers & Setup
369
369
 
370
370
  ## Supported Providers
371
371
  * 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)
@@ -395,7 +395,7 @@ Route sub-agent workloads to faster/cheaper models independently of the main age
395
395
  * Multimodal (Vision): /model <model-id> -m
396
396
  3. Context Window Override:
397
397
  * Set HIGH_CONTEXT=<tokens> in ENV (range: 32k to 1M)
398
- `;var Ei=`# Fluxflow Instructions & Skills System
398
+ `;var Ai=`# Fluxflow Instructions & Skills System
399
399
 
400
400
  ## 1. Instructions (AGENTS.md / FLUXFLOW.md)
401
401
  * Locations:
@@ -439,14 +439,14 @@ Instruction for this model ID across all providers.
439
439
 
440
440
  * On-Demand Reference Loading:
441
441
  * Reference: Offload deep/contexual specs to references/*.md linked from root SKILL.md. Saves tokens
442
- `;var Ao="v4";try{let e=ps.dirname(zr(import.meta.url)),t=[ps.join(e,"../../package.json"),ps.join(e,"../package.json")],n=!1;for(let s of t)if(Ai.existsSync(s)){let o=JSON.parse(Ai.readFileSync(s,"utf8"));if(o.version){Ao=o.version,n=!0;break}}if(!n)try{let s=Ci("fluxflow -v",{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"],timeout:2e3}).trim();s&&(s.startsWith("v")||/^\d+\.\d+/.test(s))&&(Ao=s,n=!0)}catch{}if(!n)try{let s=Ci("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&&(Ao=o.version)}catch{}}catch{}var ys={"SKILL.md":`---
442
+ `;var Co="v4";try{let e=ys.dirname(zr(import.meta.url)),t=[ys.join(e,"../../package.json"),ys.join(e,"../package.json")],n=!1;for(let s of t)if(Ci.existsSync(s)){let o=JSON.parse(Ci.readFileSync(s,"utf8"));if(o.version){Co=o.version,n=!0;break}}if(!n)try{let s=Ri("fluxflow -v",{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"],timeout:2e3}).trim();s&&(s.startsWith("v")||/^\d+\.\d+/.test(s))&&(Co=s,n=!0)}catch{}if(!n)try{let s=Ri("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&&(Co=o.version)}catch{}}catch{}var xs={"SKILL.md":`---
443
443
  name: fluxflow
444
444
  description: System Generated Documentation. Read this if asked anything regarding FluxFlow Harness
445
445
  ---
446
446
 
447
447
  # FluxFlow, by Kushal Roy Chowdhury
448
448
  Open Source Terminal AI Assistant
449
- App Version: ${Ao}. Check Updates: fluxflow --update check. Update: fluxflow --update
449
+ App Version: ${Co}. Check Updates: fluxflow --update check. Update: fluxflow --update
450
450
  GitHub: https://github.com/KushalRoyChowdhury/fluxflow-cli
451
451
  Documentation: https://fluxflow-cli.onrender.com
452
452
 
@@ -468,68 +468,67 @@ Documentation: https://fluxflow-cli.onrender.com
468
468
 
469
469
  Default Context Length: 256k Tokens. Can be changed via ENV/In-app Settings
470
470
 
471
- Docs missing required info? Say you are not sure enough to answer. Dont give wrong info`,"references/MODES.md":Si,"references/PROVIDERS.md":_i,"references/PLUGINS.md":Ei,"references/STARTUP.md":mi,"references/ENV.md":hi,"references/COMMANDS.md":pi,"references/SETTINGS.md":yi,"references/TOOLS.md":xi,"references/ARCHITECTURE.md":bi,"references/SUB_AGENTS.md":ki,"references/SECURITY.md":wi,"references/IDE.md":Ti};var Ri=()=>{try{let e=Tn.join(en,"skills","fluxflow"),t=Tn.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(ys).map(o=>Tn.normalize(o)));for(let[o,d]of Object.entries(ys)){let f=Tn.join(e,o),a=Tn.dirname(f);ln.existsSync(a)||ln.mkdirSync(a,{recursive:!0});let m=d.trim()+`
472
- `,g=null;ln.existsSync(f)&&(g=ln.readFileSync(f,"utf8")),g!==m&&ln.writeFileSync(f,m,"utf8")}if(ln.existsSync(t)){let o=ln.readdirSync(t);for(let d of o){let f=Tn.normalize(Tn.join("references",d));if(!s.has(f)){let a=Tn.join(t,d);try{ln.rmSync(a,{recursive:!0,force:!0})}catch{}}}}}catch{}};var io=(e,t)=>{try{if(!Sn.existsSync(e))return null;let n=Array.isArray(t)?t.map(o=>o.toLowerCase()):[t.toLowerCase()],s=Sn.readdirSync(e);for(let o of n){let d=s.find(f=>f.toLowerCase()===o);if(d){let f=Io.join(e,d);if(Sn.statSync(f).isFile())return f}}}catch{}return null},Do=(e,t)=>{let n=io(e,t);if(n)try{return Sn.readFileSync(n,"utf8")}catch{}return""},Oi=()=>io(en,["agents.md","agent.md"]),Li=()=>io(process.cwd(),["agents.md","agent.md"]),Pi=()=>io(en,["fluxflow.md"]),$i=()=>io(process.cwd(),["fluxflow.md"]),Co=Oi(),Ro=Li(),vo=Pi(),Mo=$i(),vi=null,ws="",Ni=!1,Xr=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&&(ws=o[1].trim(),process.env.NO_INS=!0),/<><\s*NO_INS/.test(n)&&(Ni=!0),s.trim()},Qr=()=>(Co=Oi(),Co?Do(en,["agents.md","agent.md"]).trim():""),Zr=()=>(Ro=Li(),Ro?Do(process.cwd(),["agents.md","agent.md"]).trim():""),Ts=()=>{vo=Pi();let e=vo?Do(en,["fluxflow.md"]).trim():"";return Xr(e)},Ss=()=>(Mo=$i(),Mo?Do(process.cwd(),["fluxflow.md"]).trim():""),_s=Qr(),Es=Zr(),oo=Ts(),so=Ss(),Mi=(e,t="",n="")=>{if(!e)return"";let s=n.toLowerCase().trim(),o=t.toLowerCase().trim(),d=s&&o?`${s}::${o}`:"",f=[];return e.replace(/<start_provider_([^>\r\n]+)>([\s\S]*?)<end_provider_([^>\r\n]+)>/gi,(a,m,g,u)=>{if(s&&m.trim().toLowerCase()===u.trim().toLowerCase()&&m.trim().toLowerCase()===s){let b=g.replace(/<start_model_([^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n]+)>/gi,(i,l,_,C)=>{if(l.trim().toLowerCase()===C.trim().toLowerCase()){let x=l.trim().toLowerCase();if(o&&(x===o||x===d)){let R=_.trim();R&&f.push(R)}}return""}).trim();b&&f.push(b)}return""}),e.replace(/<start_model_([^>\r\n]+::[^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n]+::[^>\r\n]+)>/gi,(a,m,g,u)=>{if(d&&m.trim().toLowerCase()===u.trim().toLowerCase()&&m.trim().toLowerCase()===d){let h=g.trim();h&&f.push(h)}return""}),e.replace(/<start_model_([^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n]+)>/gi,(a,m,g,u)=>{if(m.includes("::"))return"";if(o&&m.trim().toLowerCase()===u.trim().toLowerCase()&&m.trim().toLowerCase()===o){let h=g.trim();h&&f.push(h)}return""}),f.join(`
471
+ Docs missing required info? Say you are not sure enough to answer. Dont give wrong info`,"references/MODES.md":_i,"references/PROVIDERS.md":Ei,"references/PLUGINS.md":Ai,"references/STARTUP.md":hi,"references/ENV.md":pi,"references/COMMANDS.md":yi,"references/SETTINGS.md":xi,"references/TOOLS.md":bi,"references/ARCHITECTURE.md":ki,"references/SUB_AGENTS.md":wi,"references/SECURITY.md":Ti,"references/IDE.md":Si};var vi=()=>{try{let e=Tn.join(en,"skills","fluxflow"),t=Tn.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(xs).map(o=>Tn.normalize(o)));for(let[o,d]of Object.entries(xs)){let f=Tn.join(e,o),a=Tn.dirname(f);ln.existsSync(a)||ln.mkdirSync(a,{recursive:!0});let h=d.trim()+`
472
+ `,g=null;ln.existsSync(f)&&(g=ln.readFileSync(f,"utf8")),g!==h&&ln.writeFileSync(f,h,"utf8")}if(ln.existsSync(t)){let o=ln.readdirSync(t);for(let d of o){let f=Tn.normalize(Tn.join("references",d));if(!s.has(f)){let a=Tn.join(t,d);try{ln.rmSync(a,{recursive:!0,force:!0})}catch{}}}}}catch{}};var ao=(e,t)=>{try{if(!Sn.existsSync(e))return null;let n=Array.isArray(t)?t.map(o=>o.toLowerCase()):[t.toLowerCase()],s=Sn.readdirSync(e);for(let o of n){let d=s.find(f=>f.toLowerCase()===o);if(d){let f=ro.join(e,d);if(Sn.statSync(f).isFile())return f}}}catch{}return null},Do=(e,t)=>{let n=ao(e,t);if(n)try{return Sn.readFileSync(n,"utf8")}catch{}return""},Li=()=>ao(en,["agents.md","agent.md"]),Pi=()=>ao(process.cwd(),["agents.md","agent.md"]),$i=()=>ao(en,["fluxflow.md"]),Ni=()=>ao(process.cwd(),["fluxflow.md"]),Ro=Li(),vo=Pi(),Mo=$i(),Io=Ni(),Mi=null,Ts="",Fi=!1,Xr=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&&(Ts=o[1].trim(),process.env.NO_INS=!0),/<><\s*NO_INS/.test(n)&&(Fi=!0),s.trim()},Qr=()=>(Ro=Li(),Ro?Do(en,["agents.md","agent.md"]).trim():""),Zr=()=>(vo=Pi(),vo?Do(process.cwd(),["agents.md","agent.md"]).trim():""),Ss=()=>{Mo=$i();let e=Mo?Do(en,["fluxflow.md"]).trim():"";return Xr(e)},_s=()=>(Io=Ni(),Io?Do(process.cwd(),["fluxflow.md"]).trim():""),Es=Qr(),As=Zr(),so=Ss(),io=_s(),Ii=(e,t="",n="")=>{if(!e)return"";let s=n.toLowerCase().trim(),o=t.toLowerCase().trim(),d=ro.posix.basename(o),f=s&&o?`${s}::${o}`:"",a=s&&d?`${s}::${d}`:"",h=u=>!u||!o?!1:u===o||u===d||u===f||u===a,g=[];return e.replace(/<start_provider_([^>\r\n]+)>([\s\S]*?)<end_provider_([^>\r\n]+)>/gi,(u,m,x,i)=>{if(s&&m.trim().toLowerCase()===i.trim().toLowerCase()&&m.trim().toLowerCase()===s){let T=x.replace(/<start_model_([^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n]+)>/gi,(R,b,v,N)=>{if(b.trim().toLowerCase()===N.trim().toLowerCase()){let M=b.trim().toLowerCase();if(h(M)){let S=v.trim();S&&g.push(S)}}return""}).trim();T&&g.push(T)}return""}),e.replace(/<start_model_([^>\r\n]+::[^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n]+::[^>\r\n]+)>/gi,(u,m,x,i)=>{if(m.trim().toLowerCase()===i.trim().toLowerCase()){let l=m.trim().toLowerCase();if(f&&(l===f||a&&l===a)){let T=x.trim();T&&g.push(T)}}return""}),e.replace(/<start_model_([^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n]+)>/gi,(u,m,x,i)=>{if(m.includes("::"))return"";if(m.trim().toLowerCase()===i.trim().toLowerCase()){let l=m.trim().toLowerCase();if(o&&(l===o||l===d)){let T=x.trim();T&&g.push(T)}}return""}),g.join(`
473
473
 
474
- `).trim()},ea=(e="",t="")=>{let n=`${e||""}::${t||""}`.toLowerCase().trim();vi!==n&&(vi=n,oo=Ts(),so=Ss())};Ri();var ta=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="",d="",f=n.match(/^name:\s*(.+)$/m),a=n.match(/^description:\s*(.+)$/m);return f&&(o=f[1].trim().replace(/^["']|["']$/g,"")),a&&(d=a[1].trim().replace(/^["']|["']$/g,"")),o&&d?{name:o,description:d}:null},na=e=>{let t=[];if(!e||!Sn.existsSync(e))return t;let n=(s,o=0)=>{if(!(o>5))try{let d=Sn.readdirSync(s,{withFileTypes:!0});for(let f of d){let a=Io.join(s,f.name),m=f.name.toLowerCase();f.isFile()?m==="skill.md"&&t.push(a):f.isDirectory()&&(o===0?(m==="skills"||m===".skills"||m==="skill"||m===".skill")&&n(a,o+1):n(a,o+1))}}catch{}};return n(e,0),t},Fi=e=>{let t=na(e),n=[];for(let s of t)try{let o=Sn.readFileSync(s,"utf8"),d=ta(o);d&&n.push({...d,filePath:s})}catch{}return n},Bi=e=>!e||e.length===0?"":e.map(t=>`- ${t.name}: ${t.description}`).join(`
475
- `),Ui=Fi(en),Wi=Fi(process.cwd()),xs=Bi(Ui),bs=Bi(Wi),Hi=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"},Gi=()=>(Ui||[]).filter(e=>!Hi(e)),ji=()=>(Wi||[]).filter(e=>!Hi(e)),Ll=(_s?1:0)+(Es?1:0)+(oo?1:0)+(so?1:0)+Gi().length+ji().length,ks=(e,t="Project")=>{if(!e)return"";let n=e.replace(/\\/g,"/");if(t==="Global"){let o=Jr.homedir().replace(/\\/g,"/");return n.toLowerCase().startsWith(o.toLowerCase())?"~"+n.slice(o.length):n}let s=Io.relative(process.cwd(),e).replace(/\\/g,"/");return s.startsWith(".")?s:`./${s}`},Pl=()=>{oo=Ts(),so=Ss();let e=[];Co&&_s.length>0&&e.push({scope:"Global",path:Co}),Ro&&Es.length>0&&e.push({scope:"Project",path:Ro}),vo&&oo.length>0&&e.push({scope:"Global",path:vo}),Mo&&so.length>0&&e.push({scope:"Project",path:Mo});let t=Gi(),n=ji(),s=e.length+t.length+n.length;if(s===0)return`\u2726 Loaded Files & Instructions
474
+ `).trim()},ea=(e="",t="")=>{let n=`${e||""}::${t||""}`.toLowerCase().trim();Mi!==n&&(Mi=n,so=Ss(),io=_s())};vi();var ta=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="",d="",f=n.match(/^name:\s*(.+)$/m),a=n.match(/^description:\s*(.+)$/m);return f&&(o=f[1].trim().replace(/^["']|["']$/g,"")),a&&(d=a[1].trim().replace(/^["']|["']$/g,"")),o&&d?{name:o,description:d}:null},na=e=>{let t=[];if(!e||!Sn.existsSync(e))return t;let n=(s,o=0)=>{if(!(o>5))try{let d=Sn.readdirSync(s,{withFileTypes:!0});for(let f of d){let a=ro.join(s,f.name),h=f.name.toLowerCase();f.isFile()?h==="skill.md"&&t.push(a):f.isDirectory()&&(o===0?(h==="skills"||h===".skills"||h==="skill"||h===".skill")&&n(a,o+1):n(a,o+1))}}catch{}};return n(e,0),t},Bi=e=>{let t=na(e),n=[];for(let s of t)try{let o=Sn.readFileSync(s,"utf8"),d=ta(o);d&&n.push({...d,filePath:s})}catch{}return n},Ui=e=>!e||e.length===0?"":e.map(t=>`- ${t.name}: ${t.description}`).join(`
475
+ `),Wi=Bi(en),Hi=Bi(process.cwd()),bs=Ui(Wi),ks=Ui(Hi),Gi=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"},ji=()=>(Wi||[]).filter(e=>!Gi(e)),Vi=()=>(Hi||[]).filter(e=>!Gi(e)),Wl=(Es?1:0)+(As?1:0)+(so?1:0)+(io?1:0)+ji().length+Vi().length,ws=(e,t="Project")=>{if(!e)return"";let n=e.replace(/\\/g,"/");if(t==="Global"){let o=Jr.homedir().replace(/\\/g,"/");return n.toLowerCase().startsWith(o.toLowerCase())?"~"+n.slice(o.length):n}let s=ro.relative(process.cwd(),e).replace(/\\/g,"/");return s.startsWith(".")?s:`./${s}`},Hl=()=>{so=Ss(),io=_s();let e=[];Ro&&Es.length>0&&e.push({scope:"Global",path:Ro}),vo&&As.length>0&&e.push({scope:"Project",path:vo}),Mo&&so.length>0&&e.push({scope:"Global",path:Mo}),Io&&io.length>0&&e.push({scope:"Project",path:Io});let t=ji(),n=Vi(),s=e.length+t.length+n.length;if(s===0)return`\u2726 Loaded Files & Instructions
476
476
  \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m No instruction or skill files are currently loaded.
477
477
  \u2800`;let o=[];return o.push(`\u2726 Loaded Files & Instructions (${s} ${s===1?"file":"files"} active)`),e.length>0&&(o.push(`
478
- \x1B[1mInstructions:\x1B[22m`),e.forEach(d=>{o.push(` \u2022 [${d.scope}] ${ks(d.path,d.scope)}`)})),(t?.length>0||n?.length>0)&&(o.push(`
479
- \x1B[1mSkills:\x1B[22m`),t?.length>0&&t.forEach(d=>{o.push(` \u2022 [Global] \x1B[36m${d.name}\x1B[39m`),o.push(` \x1B[2m\u2514\u2500 ${ks(d.filePath,"Global")}\x1B[22m`)}),n?.length>0&&n.forEach(d=>{o.push(` \u2022 [Project] \x1B[36m${d.name}\x1B[39m`),o.push(` \x1B[2m\u2514\u2500 ${ks(d.filePath,"Project")}\x1B[22m`)})),o.push("\u2800"),o.join(`
480
- `)},Vi=!1;(async()=>{try{let e=await eo();if(Number(e?.display)===1){let{default:t}=await import("screenshot-desktop"),n=await t.listDisplays();n&&n.length>1&&(Vi=!0)}}catch{}})();var Ii=null,no=null,Di=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",$l=process.env.NO_DEV||!1,oa=(e,t)=>{if(!t)return"";if(e!==Ii||no===null){Ii=e;try{let n=_t(On,[]);Array.isArray(n)&&n.length>0?no=n.map(s=>`- ${s.memory}`).join(`
481
- `):no=""}catch(n){no="",Sn.appendFileSync(`${wn}/memory/error.txt`,`${n.message}
478
+ \x1B[1mInstructions:\x1B[22m`),e.forEach(d=>{o.push(` \u2022 [${d.scope}] ${ws(d.path,d.scope)}`)})),(t?.length>0||n?.length>0)&&(o.push(`
479
+ \x1B[1mSkills:\x1B[22m`),t?.length>0&&t.forEach(d=>{o.push(` \u2022 [Global] \x1B[36m${d.name}\x1B[39m`),o.push(` \x1B[2m\u2514\u2500 ${ws(d.filePath,"Global")}\x1B[22m`)}),n?.length>0&&n.forEach(d=>{o.push(` \u2022 [Project] \x1B[36m${d.name}\x1B[39m`),o.push(` \x1B[2m\u2514\u2500 ${ws(d.filePath,"Project")}\x1B[22m`)})),o.push("\u2800"),o.join(`
480
+ `)},Ki=!1;(async()=>{try{let e=await eo();if(Number(e?.display)===1){let{default:t}=await import("screenshot-desktop"),n=await t.listDisplays();n&&n.length>1&&(Ki=!0)}}catch{}})();var Di=null,oo=null,Oi=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",Gl=process.env.NO_DEV||!1,oa=(e,t)=>{if(!t)return"";if(e!==Di||oo===null){Di=e;try{let n=_t(On,[]);Array.isArray(n)&&n.length>0?oo=n.map(s=>`- ${s.memory}`).join(`
481
+ `):oo=""}catch(n){oo="",Sn.appendFileSync(`${wn}/memory/error.txt`,`${n.message}
482
482
  -------------------------------------------------
483
483
 
484
- `)}}return no},Ki=(e="",t="",n=!0,s=!1)=>{if(typeof t=="boolean"&&(s=n,n=t,t=""),!n)return"";let o=e?.length>0&&!s?`-- Recent context from other chats (Priority: Low, Focus: Chat Context > Recent) --
485
- ${e}`:"";return o?`${o}`:""},Yi=(e,t,n,s,o=!0,d=!1,f="Google",a=!1,m,g,u=!1,h="")=>{let b=!1;process.env.forcedReasoning&&(b=!0);let i="";if(!m&&f==="Google"){let A=t;t==="Fast"&&(A="Off"),t==="Low"&&(A="Minimal"),t==="Standard"&&(A="Medium"),(t==="xHigh"||t==="Max")&&(A="xHigh"),i=Eo[A]||Eo.Medium}if(m||f!=="Google"){let A={Fast:"Lowest",Low:"Low",Medium:"Medium",Standard:"Medium",High:"High",xHigh:"High",Max:"High"};i=Eo.xHigh,i=i.replace("Effort: High",`Effort: ${A[t]}`),t==="Fast"?i=`Effort: Lowest
484
+ `)}}return oo},Yi=(e="",t="",n=!0,s=!1)=>{if(typeof t=="boolean"&&(s=n,n=t,t=""),!n)return"";let o=e?.length>0&&!s?`-- Recent context from other chats (Priority: Low, Focus: Chat Context > Recent) --
485
+ ${e}`:"";return o?`${o}`:""},qi=(e,t,n,s,o=!0,d=!1,f="Google",a=!1,h,g,u=!1,m="")=>{let x=!1;process.env.forcedReasoning&&(x=!0);let i="";if(!h&&f==="Google"){let A=t;t==="Fast"&&(A="Off"),t==="Low"&&(A="Minimal"),t==="Standard"&&(A="Medium"),(t==="xHigh"||t==="Max")&&(A="xHigh"),i=Ao[A]||Ao.Medium}if(h||f!=="Google"){let A={Fast:"Lowest",Low:"Low",Medium:"Medium",Standard:"Medium",High:"High",xHigh:"High",Max:"High"};i=Ao.xHigh,i=i.replace("Effort: High",`Effort: ${A[t]}`),t==="Fast"?i=`Effort: Lowest
486
486
  No thinking. Immediate response
487
487
  Verify imports, tool results & system stability; avoid syntax errors`:t==="Low"&&(i=`Effort: Low
488
488
  Quick, focused thinking, intent & complexity, required tools/files/actions, before acting
489
489
  Dont waste tokens, be efficient, use least thinking tokens, focus on result
490
- Gather useful context
491
490
  Brief thoughts, think only enough to avoid mistakes, verify imports, tool results & system stability; avoid syntax errors`)}let l=e.instructions&&e.instructions?.length>0?`User Preferences: ${e.instructions}
492
491
 
493
- `:"",_=e.nickname&&e.nickname?.length>0?`User Nickname: ${e.nickname}
492
+ `:"",T=e.nickname&&e.nickname?.length>0?`User Nickname: ${e.nickname}
494
493
  ${l.length?"":`
495
- `}`:"",C=e.name&&e.name?.length>0?`User Name: ${e.name}
496
- ${_.length||l.length?"":`
497
- `}`:"",x=process.cwd(),R=oa(g,o),N=R?.length>0?`--- Saved Memories ---
498
- ${R}
494
+ `}`:"",R=e.name&&e.name?.length>0?`User Name: ${e.name}
495
+ ${T.length||l.length?"":`
496
+ `}`:"",b=process.cwd(),v=oa(g,o),N=v?.length>0?`--- Saved Memories ---
497
+ ${v}
499
498
 
500
- `:"";ea(f,h);let D=Mi(oo,h,f).trim(),M=[_s,D].filter(A=>A&&A.length>0).join(`
499
+ `:"";ea(f,m);let M=Ii(so,m,f).trim(),I=[Es,M].filter(A=>A&&A.length>0).join(`
501
500
 
502
- `).trim(),$=Mi(so,h,f).trim(),c=[Es,$].filter(A=>A&&A.length>0).join(`
501
+ `).trim(),$=Ii(io,m,f).trim(),c=[As,$].filter(A=>A&&A.length>0).join(`
503
502
 
504
- `).trim(),w=M.length>0||c.length>0?`--- Additional Instructions ---
505
- ${M.length>0?`-- Global --
506
- ${M}`:""}${c.length>0?`${M.length>0?`
503
+ `).trim(),w=I.length>0||c.length>0?`--- Additional Instructions ---
504
+ ${I.length>0?`-- Global --
505
+ ${I}`:""}${c.length>0?`${I.length>0?`
507
506
 
508
507
  `:""}-- Project --
509
508
  ${c}`:""}
510
509
 
511
- `:"",r=(()=>{let A=process.cwd().toLowerCase();if(process.platform==="win32"){let Ee=process.env.SystemRoot?.toLowerCase()||"c:\\windows",se=process.env.ProgramFiles?.toLowerCase()||"c:\\program files",v=process.env["ProgramFiles(x86)"]?.toLowerCase()||"c:\\program files (x86)";return A.startsWith(Ee)||A.startsWith(se)||A.startsWith(v)}else return A==="/"||["/bin","/sbin","/etc","/usr","/var","/root"].some(se=>A.startsWith(se))})();function k(A){return{Low:"Low",Standard:"Medium",Medium:"Medium",High:"High",xHigh:"",Max:""}[A]??""}let E=new Date,O=E.getFullYear(),U=E.toLocaleString("en-US",{month:"short"}).toUpperCase(),P=String(E.getDate()).padStart(2,"0"),I=`${O}-${U}-${P}`,Z=!!s?.autoExcludeMetadata,ke=process.env.I_HAVE_TOO_MUCH_MONEY==="true"||process.env.I_HAVE_TOO_MUCH_MONEY===!0||!1,B=process.env.NO_DEV==="true"||process.env.NO_DEV==="1"||process.env.NO_DEV===!0||!1;return`${ke?`${" ".repeat(Math.floor(Math.random()*4)+1)}`:""}=== SYSTEM PROMPT ===
512
- Identity: ${ws.length>1?ws:"Flux Flow. Sassy, Friendly, CLI Assistant"}
513
- ${Ni?"":`${n==="Flux"?"Stepwise Execution, Run Automated Tests. Task Completion":n==="Flow"?"Concise, Humorous, Sarcastic":n==="ICU"?"Computer Use Capabilities. Screenshot as ground truth, analyze grid ids overlapping/close to target, keyboard shortcuts > mouse clicks":"Computer Use & Workspace Capabilities. Screenshot as ground truth, analyze grid ids overlapping/close to target, keyboard shortcuts > mouse clicks. Workspace Tools if faster. Focus on Productivity"}`}${Vi&&n.toLowerCase().includes("cu")?`
510
+ `:"",r=(()=>{let A=process.cwd().toLowerCase();if(process.platform==="win32"){let Se=process.env.SystemRoot?.toLowerCase()||"c:\\windows",X=process.env.ProgramFiles?.toLowerCase()||"c:\\program files",C=process.env["ProgramFiles(x86)"]?.toLowerCase()||"c:\\program files (x86)";return A.startsWith(Se)||A.startsWith(X)||A.startsWith(C)}else return A==="/"||["/bin","/sbin","/etc","/usr","/var","/root"].some(X=>A.startsWith(X))})();function k(A,Se,X){let C={Low:"Low",Standard:"Medium",Medium:"Medium",High:"High",xHigh:"",Max:""};return Oe(Se,X,A)||Oe(Se,X,"xHigh")?"":C[A]??""}let E=new Date,O=E.getFullYear(),U=E.toLocaleString("en-US",{month:"short"}).toUpperCase(),P=String(E.getDate()).padStart(2,"0"),D=`${O}-${U}-${P}`,ee=!!s?.autoExcludeMetadata,pe=process.env.I_HAVE_TOO_MUCH_MONEY==="true"||process.env.I_HAVE_TOO_MUCH_MONEY===!0||!1,B=process.env.NO_DEV==="true"||process.env.NO_DEV==="1"||process.env.NO_DEV===!0||!1;return`${pe?`${" ".repeat(Math.floor(Math.random()*4)+1)}`:""}=== SYSTEM PROMPT ===
511
+ Identity: ${Ts.length>1?Ts:"Flux Flow. Sassy, Friendly, CLI Assistant"}
512
+ ${Fi?"":`${n==="Flux"?"Stepwise Execution, Run Automated Tests. Task Completion":n==="Flow"?"Concise, Humorous, Sarcastic":n==="ICU"?"Computer Use Capabilities. Screenshot as ground truth, analyze grid ids overlapping/close to target, keyboard shortcuts > mouse clicks":"Computer Use & Workspace Capabilities. Screenshot as ground truth, analyze grid ids overlapping/close to target, keyboard shortcuts > mouse clicks. Workspace Tools if faster. Focus on Productivity"}`}${Ki&&n.toLowerCase().includes("cu")?`
514
513
  - 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`:""}
515
514
 
516
- - OS: ${Di}${!B&&h.length>1?`
517
- - Model: ${Io.basename(h.trim())} ${k(t)}`.trimEnd():""}${Z?`
518
- - Date: ${I}`:""}${o?`
515
+ - OS: ${Oi}${!B&&m.length>1?`
516
+ - Model: ${ro.basename(m.trim())} ${k(t,f,m)}`.trimEnd():""}${ee?`
517
+ - Date: ${D}`:""}${o?`
519
518
  - Use relative time reference eg. few mins ago
520
519
  -- Chat Context > Metadata`:""}${w.length>0?`
521
- - Additional Instructions \u2248 System Prompt`:""}${(xs.length>0||bs.length>0)&&n.toLowerCase().includes("flux")?`
520
+ - Additional Instructions \u2248 System Prompt`:""}${(bs.length>0||ks.length>0)&&n.toLowerCase().includes("flux")?`
522
521
  - Read available relevant skills for tasks before proceeding: Use ReadFile, with virtual path="#skills/{global|project}/skillName". For references: path="#skills/{global|project}/skillName/references/<file-name>.md"`:""}
523
522
 
524
523
  -- THINKING GUIDANCE --
525
- ${f==="Mistral"||f==="Google"&&!m?`${i}
526
- ${b||t!=="Fast"&&(f==="Mistral"&&!m||t!=="xHigh"&&!m)?`critical thinking policy
524
+ ${f==="Mistral"||f==="Google"&&!h?`${i}
525
+ ${x||t!=="Fast"&&(f==="Mistral"&&!h||t!=="High"&&!h)?`critical thinking policy
527
526
  Use <think>...</think> for reasoning before responding any queries
528
527
  `:""}`:`${i}
529
528
  `}${u?"":`Mandatory: Before calling tools, MUST provide a high level summary of your reasoning, plans, decisions, and next course of actions in chat
530
529
  `}No text after tool call in same turn
531
530
 
532
- ${di(n,Di,a,f,s?.advanceRollback,s?.subAgents!==!1,!!s?.autoExec)}${o?`
531
+ ${di(n,Oi,a,f,s?.advanceRollback,s?.subAgents!==!1,!!s?.autoExec)}${o?`
533
532
 
534
533
  -- MEMORY RULES --
535
534
  - Subtly Personalize with relevent contextual memories. Auto Saves
@@ -543,13 +542,13 @@ ${di(n,Di,a,f,s?.advanceRollback,s?.subAgents!==!1,!!s?.autoExec)}${o?`
543
542
  - use kaomojis heavily`:""}
544
543
  === END SYSTEM PROMPT ===
545
544
 
546
- ${C}${_}${l}${w}${xs.length>0&&n.toLowerCase().includes("flux")?`-- Global Skills --
547
- ${xs}
548
-
549
- `:""}${bs.length>0&&n.toLowerCase().includes("flux")?`-- Project Skills --
545
+ ${R}${T}${l}${w}${bs.length>0&&n.toLowerCase().includes("flux")?`-- Global Skills --
550
546
  ${bs}
551
547
 
552
- `:""}${N}`.trim()},qi=(e="",t=!0,n=!0)=>`=== SYSTEM PROMPT (strict headless logic worker: zero user-facing text policy, strictly follow) ===
548
+ `:""}${ks.length>0&&n.toLowerCase().includes("flux")?`-- Project Skills --
549
+ ${ks}
550
+
551
+ `:""}${N}`.trim()},zi=(e="",t=!0,n=!0)=>`=== SYSTEM PROMPT (strict headless logic worker: zero user-facing text policy, strictly follow) ===
553
552
  identity: silent background system process, have no mouth, only output is valid tool calls
554
553
  [critical rules]
555
554
  - output exactly '[tool:functions.ToolName(args)]' calls. no extra words outside
@@ -570,61 +569,63 @@ ${gi(t,n)}
570
569
  === END SYSTEM PROMPT ===${e?`
571
570
 
572
571
  -- current saved user memories --
573
- ${e}`:""}`.trim();var zi=()=>import("./web_search-YG5YAC5D.js").then(e=>e.web_search),Ji=()=>import("./web_scrape-5LBY4FDC.js").then(e=>e.web_scrape),Xi=()=>import("./memory-OYIUYX3A.js").then(e=>e.memory),Qi=()=>import("./chat-HZ7UVZE2.js").then(e=>e.chat),Zi=()=>import("./view_file-JK22NGXC.js").then(e=>e.view_file),er=()=>import("./write_file-LOYRYIK6.js").then(e=>e.write_file),tr=()=>import("./update_file-UFCBJOW5.js").then(e=>e.update_file),nr=()=>import("./exec_command-7MOYM7IQ.js").then(e=>e.exec_command),or=()=>import("./read_folder-OOKZITME.js").then(e=>e.read_folder),As=()=>import("./ask_user-K2DLZF6H.js").then(e=>e.ask_user),sr=()=>import("./write_pdf-VB4IFPWX.js").then(e=>e.write_pdf),ir=()=>import("./write_docx-EKUIZ7GV.js").then(e=>e.write_docx),Oo=()=>import("./search_keyword-W5YEUUPO.js").then(e=>e.search_keyword),rr=()=>import("./generate_image-XYDE47LK.js").then(e=>e.generate_image),Lo=()=>import("./saveSummary-ATBIFYDP.js").then(e=>e.saveSummary),ro=()=>import("./addMemScore-W4I665ZR.js").then(e=>e.addMemScore),ar=()=>import("./file_map-5KY2ADZW.js").then(e=>e.file_map),Po=()=>import("./todo-SJLJJLVZ.js").then(e=>e.todo),lr=()=>import("./invokeSync-COCWPF45.js").then(e=>e.invokeSync),sa=()=>import("./invoke-4TSUCBPH.js").then(e=>e.invoke),cr=()=>import("./getProgress-KLWGCCPA.js").then(e=>e.getProgress),ia=()=>import("./cancel-7IMADALP.js").then(e=>e.cancel),dr=()=>import("./emergency_rollback-EPJPKANN.js").then(e=>e.emergency_rollback),ao=()=>import("./awaitSubagent-JTUSJDKD.js").then(e=>e.awaitSubagent),lo=()=>import("./answerSubagent-JUVFNLE5.js").then(e=>e.answerSubagent),$o=()=>import("./steerSubagent-L2JVT4QN.js").then(e=>e.steerSubagent),No=()=>import("./computer_action-WTHH7RBB.js").then(e=>e.computer_action),fr=()=>import("./click-G6RRSFVC.js").then(e=>e.click),ur=()=>import("./drag-ZGH2MMP7.js").then(e=>e.drag),gr=()=>import("./scroll-GHXES2II.js").then(e=>e.scroll),Cs=()=>import("./keyboard_typing-CK3KVAWM.js").then(e=>e.keyboard_typing),Rs=()=>import("./key_press-M5QNCIPH.js").then(e=>e.key_press),vs=()=>import("./recapture_screen-5FKLOHJL.js").then(e=>e.recapture_screen),ra={web_search:zi,web_scrape:Ji,memory:Xi,chat:Qi,view_file:Zi,write_file:er,update_file:tr,exec_command:nr,read_folder:or,write_pdf:sr,write_docx:ir,search_keyword:Oo,generate_image:rr,saveSummary:Lo,addMemScore:ro,file_map:ar,todo:Po,Todo:Po,goal:Po,Goal:Po,invokeSync:lr,invoke:sa,getProgress:cr,cancel:ia,awaitSubagent:ao,answerSubagent:lo,steerSubagent:$o,computer_action:No,computer_use:No,ComputerAction:No,ComputerUse:No,click:fr,Click:fr,drag:ur,Drag:ur,scroll:gr,Scroll:gr,keyboard_typing:Cs,KeyboardTyping:Cs,keyboardtyping:Cs,key_press:Rs,KeyPress:Rs,keypress:Rs,recapture_screen:vs,RecaptureScreen:vs,recapturescreen:vs,invoke_sync:lr,get_progress:cr,await_subagent:ao,answer_subagent:lo,steer_subagent:$o,steer:$o,Steer:$o,ask:As,Ask:As,AskUser:As,WebSearch:zi,WebScrape:Ji,ReadFile:Zi,ReadFolder:or,WriteFile:er,PatchFile:tr,WritePDF:sr,WriteDoc:ir,Run:nr,SearchKeyword:Oo,CodeSearch:Oo,code_search:Oo,Memory:Xi,Chat:Qi,GenerateImage:rr,saveSumary:Lo,SaveSummary:Lo,SaveSumary:Lo,add_mem_score:ro,AddMemScore:ro,addMemoryScore:ro,AddMemoryScore:ro,FileMap:ar,answer:lo,Answer:lo,AnswerSubagent:lo,await:ao,Await:ao,AwaitSubagent:ao,EmergencyRollback:dr,emergency_rollback:dr},co=async(e,t,n={})=>{let s=n.mode?n.mode.toLowerCase():"flux",o=e.toLowerCase(),f=["memory","chat","savesummary","addmemscore","add_mem_score","ask","web_search","web_scrape","await"].some(u=>o.includes(u))||o==="ask",m=["click","drag","scroll","keyboardtyping","keyboard_typing","keypress","key_press","recapturescreen","recapture_screen","computer"].some(u=>o.includes(u));if(!f){if(s==="flow"){if(!(o.includes("write_pdf")||o.includes("write_docx")||o.includes("generate_image")))return`ERROR: Tool [${e}] is a Workspace Tool and NOT available in Flow mode. Tell user to switch (\`/mode flux\`) to use this tool.`}else if(s==="icu"){if(!m)return`ERROR: Tool [${e}] is not available in Computer Use mode. ICU mode only supports Computer Use tools (Click, Drag, Scroll, KeyboardTyping, KeyPress, RecaptureScreen).`}else if(o.includes("write_pdf")||o.includes("write_docx")||o.includes("generate_image"))return`ERROR: Tool [${e}] is not available in ${n.mode||"Flux"} mode. Tell user to switch (\`/mode flow\`) for document generation.`}let g=ra[e];if(!g)return`ERROR: Tool [${e}] not found in registry.`;try{return await(await g())(t,n)}catch(u){let h=u instanceof Error?u.message:String(u);return`ERROR: Execution failed for [${e}]: ${h}`}};import J from"path";import Pe from"fs";import aa from"gradient-string";var Ms=["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 mr=[{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"]}],fo={Dark:{id:"Dark",name:"Dark (Default)",text:"white",textMuted:"gray",textDim:"grey",textInverted:"black",textExclusive:"#B5B8D9",textMutedExclusive:"#D4DEE7",border:"white",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:"#1e1e1e",highlightBg:"#2a2a2a",activeBg:"#3a3a3a",inputBg:"#555555",inputBorder:"#555555",inputText:"white",inputPlaceholder:"#cccccc",inputPrompt:"white",codeBg:"#1a1a1a",codeBorder:"#444444",userMsgBg:"#444444",userMsgBorder:"#444444",userMsgText:"white",diffRemovalBg:"#250808",diffAdditionBg:"#072410",diffRemovalText:"#885555",diffAdditionText:"#558866",diffRemovalHighlightColor:"#ff3333",diffRemovalHighlightBg:"#5a1818",diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:"#185a25",diffRemovalNum:"#d96868",diffAdditionNum:"#68d98c",diffRemovalPrefix:"#ff4d4d",diffAdditionPrefix:"#4dff88",primary:"white",secondary:"cyan",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"white",statusOff:"gray",logoTextAnsi:"\x1B[1;37m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#0077ff","#ff00ff"]},Light:{id:"Light",name:"Light",text:"black",textMuted:"gray",textDim:"grey",textInverted:"white",border:"black",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:"#e5e5e5",highlightBg:"#d4d4d4",activeBg:"#c0c0c0",inputBg:"#d0d0d0",inputBorder:"#d0d0d0",inputText:"black",inputPlaceholder:"#555555",inputPrompt:"black",codeBg:"#e8e8e8",codeBorder:"#b0b0b0",userMsgBg:"#d0d0d0",userMsgBorder:"#d0d0d0",userMsgText:"black",diffRemovalBg:"#fce8e8",diffAdditionBg:"#e6f9e6",diffRemovalText:"#661111",diffAdditionText:"#115511",diffRemovalHighlightColor:"#440000",diffRemovalHighlightBg:"#f8b4b4",diffAdditionHighlightColor:"#003300",diffAdditionHighlightBg:"#a6ebad",diffRemovalNum:"#c02020",diffAdditionNum:"#188028",diffRemovalPrefix:"#d01010",diffAdditionPrefix:"#109020",primary:"black",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"black",statusOff:"gray",logoTextAnsi:"\x1B[1;30m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#0077ff","#ff00ff"]},"GitHub Dark":{id:"GitHub Dark",name:"GitHub Dark",text:"#c9d1d9",textMuted:"#8b949e",textDim:"#6e7681",textInverted:"#0d1117",border:"#30363d",borderMuted:"#30363d",borderDim:"#21262d",bg:void 0,cardBg:"#161b22",highlightBg:"#21262d",activeBg:"#30363d",inputBg:"#21262d",inputBorder:"#21262d",inputText:"#c9d1d9",inputPlaceholder:"#8b949e",inputPrompt:"#58a6ff",codeBg:"#0d1117",codeBorder:"#30363d",userMsgBg:"#21262d",userMsgBorder:"#21262d",userMsgText:"#c9d1d9",diffRemovalBg:"#3c1e1e",diffAdditionBg:"#11381e",diffRemovalText:"#f85149",diffAdditionText:"#3fb950",diffRemovalHighlightColor:"#ff7b72",diffRemovalHighlightBg:"#701c1c",diffAdditionHighlightColor:"#56d364",diffAdditionHighlightBg:"#116329",diffRemovalNum:"#f85149",diffAdditionNum:"#3fb950",diffRemovalPrefix:"#f85149",diffAdditionPrefix:"#3fb950",primary:"#c9d1d9",secondary:"#58a6ff",accent:"#bc8cff",success:"#3fb950",warning:"#d29922",danger:"#f85149",info:"#58a6ff",statusOn:"#58a6ff",statusOff:"#8b949e",logoTextAnsi:"\x1B[1;36m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#2ea043","#56d364"]},"GitHub Light":{id:"GitHub Light",name:"GitHub Light",text:"#24292f",textMuted:"#57606a",textDim:"#6e7781",textInverted:"#ffffff",border:"#d0d7de",borderMuted:"#d0d7de",borderDim:"#e1e4e8",bg:void 0,cardBg:"#f6f8fa",highlightBg:"#eaeef2",activeBg:"#d0d7de",inputBg:"#eaeef2",inputBorder:"#eaeef2",inputText:"#24292f",inputPlaceholder:"#57606a",inputPrompt:"#0969da",codeBg:"#ffffff",codeBorder:"#d0d7de",userMsgBg:"#eaeef2",userMsgBorder:"#eaeef2",userMsgText:"#24292f",diffRemovalBg:"#ffebe9",diffAdditionBg:"#e6ffec",diffRemovalText:"#cf222e",diffAdditionText:"#1a7f37",diffRemovalHighlightColor:"#82071e",diffRemovalHighlightBg:"#ffc1c0",diffAdditionHighlightColor:"#116329",diffAdditionHighlightBg:"#acf2bd",diffRemovalNum:"#cf222e",diffAdditionNum:"#1a7f37",diffRemovalPrefix:"#cf222e",diffAdditionPrefix:"#1a7f37",primary:"#24292f",secondary:"#0969da",accent:"#8250df",success:"#1a7f37",warning:"#9a6700",danger:"#cf222e",info:"#0969da",statusOn:"#0969da",statusOff:"#57606a",logoTextAnsi:"\x1B[1;34m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#1a7f37","#2da44e"]},"Transparent Dark":{id:"Transparent Dark",name:"Transparent Dark",text:"white",textMuted:"gray",textDim:"grey",textInverted:"black",border:"gray",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:void 0,highlightBg:"#2a2a2a",activeBg:"#3a3a3a",inputBg:"#555555",inputBorder:"#555555",inputText:"white",inputPlaceholder:"#cccccc",inputPrompt:"white",codeBg:void 0,codeBorder:"gray",userMsgBg:"#555555",userMsgBorder:"#555555",userMsgText:"white",diffRemovalBg:void 0,diffAdditionBg:void 0,diffRemovalText:"#ff6666",diffAdditionText:"#66ff66",diffRemovalHighlightColor:"#ff3333",diffRemovalHighlightBg:void 0,diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:void 0,diffRemovalNum:"#ff6666",diffAdditionNum:"#66ff66",diffRemovalPrefix:"#ff4d4d",diffAdditionPrefix:"#4dff88",primary:"white",secondary:"cyan",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"white",statusOff:"gray",logoTextAnsi:"\x1B[1;37m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#0077ff","#ff00ff"]},"Transparent Light":{id:"Transparent Light",name:"Transparent Light",text:"black",textMuted:"gray",textDim:"grey",textInverted:"white",border:"gray",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:void 0,highlightBg:"#d4d4d4",activeBg:"#c0c0c0",inputBg:"#d0d0d0",inputBorder:"#d0d0d0",inputText:"black",inputPlaceholder:"#555555",inputPrompt:"black",codeBg:void 0,codeBorder:"gray",userMsgBg:"#d0d0d0",userMsgBorder:"#d0d0d0",userMsgText:"black",diffRemovalBg:void 0,diffAdditionBg:void 0,diffRemovalText:"#c02020",diffAdditionText:"#188028",diffRemovalHighlightColor:"#800000",diffRemovalHighlightBg:void 0,diffAdditionHighlightColor:"#004000",diffAdditionHighlightBg:void 0,diffRemovalNum:"#c02020",diffAdditionNum:"#188028",diffRemovalPrefix:"#d01010",diffAdditionPrefix:"#109020",primary:"black",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"black",statusOff:"gray",logoTextAnsi:"\x1B[1;30m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#0077ff","#ff00ff"]},"Synthwave 84":{id:"Synthwave 84",name:"Synthwave 84",text:"#fdfdfd",textMuted:"#a08eb7",textDim:"#705c8a",textInverted:"#1a1025",textExclusive:"#e3dcf0",textMutedExclusive:"#b9abc9",border:"#fc28a8",borderMuted:"#a21568",borderDim:"#5c0a3a",bg:void 0,cardBg:"#261b38",highlightBg:"#35254d",activeBg:"#4c3570",inputBg:"#35254d",inputBorder:"#35254d",inputText:"#fdfdfd",inputPlaceholder:"#a08eb7",inputPrompt:"#03e8fc",codeBg:"#1e142b",codeBorder:"#a21568",userMsgBg:"#35254d",userMsgBorder:"#35254d",userMsgText:"#fdfdfd",diffRemovalBg:"#471434",diffAdditionBg:"#144743",diffRemovalText:"#ff4081",diffAdditionText:"#00e5ff",diffRemovalHighlightColor:"#ff79a1",diffRemovalHighlightBg:"#6b1e4e",diffAdditionHighlightColor:"#66f5ff",diffAdditionHighlightBg:"#1e6b65",diffRemovalNum:"#ff4081",diffAdditionNum:"#00e5ff",diffRemovalPrefix:"#ff79a1",diffAdditionPrefix:"#66f5ff",primary:"#fdfdfd",secondary:"#03e8fc",accent:"#fc28a8",success:"#00e5ff",warning:"#ffc107",danger:"#ff4081",info:"#b388ff",statusOn:"#03e8fc",statusOff:"#a08eb7",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#fc28a8","#03e8fc"]},"Forest Sprite":{id:"Forest Sprite",name:"Forest Sprite",text:"#d6e6d1",textMuted:"#95b38d",textDim:"#628059",textInverted:"#161c14",textExclusive:"#eaf2e8",textMutedExclusive:"#a9c7a2",border:"#74a862",borderMuted:"#477038",borderDim:"#2b4720",bg:void 0,cardBg:"#1f291c",highlightBg:"#2a3826",activeBg:"#3a4d35",inputBg:"#2a3826",inputBorder:"#2a3826",inputText:"#d6e6d1",inputPlaceholder:"#95b38d",inputPrompt:"#8feb73",codeBg:"#161e14",codeBorder:"#477038",userMsgBg:"#2a3826",userMsgBorder:"#2a3826",userMsgText:"#d6e6d1",diffRemovalBg:"#3b231c",diffAdditionBg:"#203b1c",diffRemovalText:"#db6242",diffAdditionText:"#59cc3f",diffRemovalHighlightColor:"#f0896c",diffRemovalHighlightBg:"#5c362a",diffAdditionHighlightColor:"#80e368",diffAdditionHighlightBg:"#305929",diffRemovalNum:"#db6242",diffAdditionNum:"#59cc3f",diffRemovalPrefix:"#f0896c",diffAdditionPrefix:"#80e368",primary:"#d6e6d1",secondary:"#8feb73",accent:"#e69835",success:"#59cc3f",warning:"#e69835",danger:"#db6242",info:"#73b4eb",statusOn:"#8feb73",statusOff:"#95b38d",logoTextAnsi:"\x1B[1;32m",logoBodyAnsi:"\x1B[32m",logoMutedAnsi:"\x1B[90m",logoGradient:["#8feb73","#e69835"]}};var Fo=null;var hr=(e="Dark")=>{let t;e==="Mystery"||e==="Chaos"?(Fo||(Fo=mr[Math.floor(Math.random()*mr.length)]),t={...Fo,id:"Mystery"}):(Fo=null,fo[e]?t=fo[e]:e==="GitHub"?t=fo["GitHub Dark"]:e==="Transparent"?t=fo["Transparent Dark"]:t=fo.Dark);let n=t.codeText||t.secondary||t.info||t.logoGradient&&t.logoGradient[0]||"cyan";return{...t,codeText:n}};var la=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",jl=(e=2)=>{let t=la();return t==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)},Vl=(e="...",t="Loading...",n="Dark")=>{let s=Ms[Math.floor(Math.random()*Ms.length)],o=hr(n),d=o.logoTextAnsi,f=o.logoBodyAnsi,a=o.logoMutedAnsi,m="\x1B[0m",g=[" \u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2588\u2588\u2588\u2591 "," \u2588\u2588\u2588\u2591 "," \u2588\u2588\u2588\u2591 "," \u2591\u2591\u2591 "],u=o.logoGradient||["#0077ff","#ff00ff"],h=aa(u).multiline(g.join(`
572
+ ${e}`:""}`.trim();var Ji=()=>import("./web_search-YG5YAC5D.js").then(e=>e.web_search),Xi=()=>import("./web_scrape-5LBY4FDC.js").then(e=>e.web_scrape),Qi=()=>import("./memory-OYIUYX3A.js").then(e=>e.memory),Zi=()=>import("./chat-HZ7UVZE2.js").then(e=>e.chat),er=()=>import("./view_file-JK22NGXC.js").then(e=>e.view_file),tr=()=>import("./write_file-LOYRYIK6.js").then(e=>e.write_file),nr=()=>import("./update_file-UFCBJOW5.js").then(e=>e.update_file),or=()=>import("./exec_command-7MOYM7IQ.js").then(e=>e.exec_command),sr=()=>import("./read_folder-OOKZITME.js").then(e=>e.read_folder),Cs=()=>import("./ask_user-K2DLZF6H.js").then(e=>e.ask_user),ir=()=>import("./write_pdf-VB4IFPWX.js").then(e=>e.write_pdf),rr=()=>import("./write_docx-EKUIZ7GV.js").then(e=>e.write_docx),Oo=()=>import("./search_keyword-W5YEUUPO.js").then(e=>e.search_keyword),ar=()=>import("./generate_image-XYDE47LK.js").then(e=>e.generate_image),Lo=()=>import("./saveSummary-ATBIFYDP.js").then(e=>e.saveSummary),lo=()=>import("./addMemScore-W4I665ZR.js").then(e=>e.addMemScore),lr=()=>import("./file_map-5KY2ADZW.js").then(e=>e.file_map),Po=()=>import("./todo-SJLJJLVZ.js").then(e=>e.todo),cr=()=>import("./invokeSync-WFDY5DZJ.js").then(e=>e.invokeSync),sa=()=>import("./invoke-7JQ57VBG.js").then(e=>e.invoke),dr=()=>import("./getProgress-LI4U6UJU.js").then(e=>e.getProgress),ia=()=>import("./cancel-7IMADALP.js").then(e=>e.cancel),fr=()=>import("./emergency_rollback-EPJPKANN.js").then(e=>e.emergency_rollback),co=()=>import("./awaitSubagent-JTUSJDKD.js").then(e=>e.awaitSubagent),fo=()=>import("./answerSubagent-JUVFNLE5.js").then(e=>e.answerSubagent),$o=()=>import("./steerSubagent-L2JVT4QN.js").then(e=>e.steerSubagent),No=()=>import("./computer_action-WTHH7RBB.js").then(e=>e.computer_action),ur=()=>import("./click-G6RRSFVC.js").then(e=>e.click),gr=()=>import("./drag-ZGH2MMP7.js").then(e=>e.drag),mr=()=>import("./scroll-GHXES2II.js").then(e=>e.scroll),Rs=()=>import("./keyboard_typing-CK3KVAWM.js").then(e=>e.keyboard_typing),vs=()=>import("./key_press-M5QNCIPH.js").then(e=>e.key_press),Ms=()=>import("./recapture_screen-5FKLOHJL.js").then(e=>e.recapture_screen),ra={web_search:Ji,web_scrape:Xi,memory:Qi,chat:Zi,view_file:er,write_file:tr,update_file:nr,exec_command:or,read_folder:sr,write_pdf:ir,write_docx:rr,search_keyword:Oo,generate_image:ar,saveSummary:Lo,addMemScore:lo,file_map:lr,todo:Po,Todo:Po,goal:Po,Goal:Po,invokeSync:cr,invoke:sa,getProgress:dr,cancel:ia,awaitSubagent:co,answerSubagent:fo,steerSubagent:$o,computer_action:No,computer_use:No,ComputerAction:No,ComputerUse:No,click:ur,Click:ur,drag:gr,Drag:gr,scroll:mr,Scroll:mr,keyboard_typing:Rs,KeyboardTyping:Rs,keyboardtyping:Rs,key_press:vs,KeyPress:vs,keypress:vs,recapture_screen:Ms,RecaptureScreen:Ms,recapturescreen:Ms,invoke_sync:cr,get_progress:dr,await_subagent:co,answer_subagent:fo,steer_subagent:$o,steer:$o,Steer:$o,ask:Cs,Ask:Cs,AskUser:Cs,WebSearch:Ji,WebScrape:Xi,ReadFile:er,ReadFolder:sr,WriteFile:tr,PatchFile:nr,WritePDF:ir,WriteDoc:rr,Run:or,SearchKeyword:Oo,CodeSearch:Oo,code_search:Oo,Memory:Qi,Chat:Zi,GenerateImage:ar,saveSumary:Lo,SaveSummary:Lo,SaveSumary:Lo,add_mem_score:lo,AddMemScore:lo,addMemoryScore:lo,AddMemoryScore:lo,FileMap:lr,answer:fo,Answer:fo,AnswerSubagent:fo,await:co,Await:co,AwaitSubagent:co,EmergencyRollback:fr,emergency_rollback:fr},uo=async(e,t,n={})=>{let s=n.mode?n.mode.toLowerCase():"flux",o=e.toLowerCase(),f=["memory","chat","savesummary","addmemscore","add_mem_score","ask","web_search","web_scrape","await"].some(u=>o.includes(u))||o==="ask",h=["click","drag","scroll","keyboardtyping","keyboard_typing","keypress","key_press","recapturescreen","recapture_screen","computer"].some(u=>o.includes(u));if(!f){if(s==="flow"){if(!(o.includes("write_pdf")||o.includes("write_docx")||o.includes("generate_image")))return`ERROR: Tool [${e}] is a Workspace Tool and NOT available in Flow mode. Tell user to switch (\`/mode flux\`) to use this tool.`}else if(s==="icu"){if(!h)return`ERROR: Tool [${e}] is not available in Computer Use mode. ICU mode only supports Computer Use tools (Click, Drag, Scroll, KeyboardTyping, KeyPress, RecaptureScreen).`}else if(o.includes("write_pdf")||o.includes("write_docx")||o.includes("generate_image"))return`ERROR: Tool [${e}] is not available in ${n.mode||"Flux"} mode. Tell user to switch (\`/mode flow\`) for document generation.`}let g=ra[e];if(!g)return`ERROR: Tool [${e}] not found in registry.`;try{return await(await g())(t,n)}catch(u){let m=u instanceof Error?u.message:String(u);return`ERROR: Execution failed for [${e}]: ${m}`}};import J from"path";import $e from"fs";import aa from"gradient-string";var Is=["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 hr=[{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"]}],go={Dark:{id:"Dark",name:"Dark (Default)",text:"white",textMuted:"gray",textDim:"grey",textInverted:"black",textExclusive:"#B5B8D9",textMutedExclusive:"#D4DEE7",border:"white",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:"#1e1e1e",highlightBg:"#2a2a2a",activeBg:"#3a3a3a",inputBg:"#555555",inputBorder:"#555555",inputText:"white",inputPlaceholder:"#cccccc",inputPrompt:"white",codeBg:"#1a1a1a",codeBorder:"#444444",userMsgBg:"#444444",userMsgBorder:"#444444",userMsgText:"white",diffRemovalBg:"#250808",diffAdditionBg:"#072410",diffRemovalText:"#885555",diffAdditionText:"#558866",diffRemovalHighlightColor:"#ff3333",diffRemovalHighlightBg:"#5a1818",diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:"#185a25",diffRemovalNum:"#d96868",diffAdditionNum:"#68d98c",diffRemovalPrefix:"#ff4d4d",diffAdditionPrefix:"#4dff88",primary:"white",secondary:"cyan",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"white",statusOff:"gray",logoTextAnsi:"\x1B[1;37m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#0077ff","#ff00ff"]},Light:{id:"Light",name:"Light",text:"black",textMuted:"gray",textDim:"grey",textInverted:"white",border:"black",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:"#e5e5e5",highlightBg:"#d4d4d4",activeBg:"#c0c0c0",inputBg:"#d0d0d0",inputBorder:"#d0d0d0",inputText:"black",inputPlaceholder:"#555555",inputPrompt:"black",codeBg:"#e8e8e8",codeBorder:"#b0b0b0",userMsgBg:"#d0d0d0",userMsgBorder:"#d0d0d0",userMsgText:"black",diffRemovalBg:"#fce8e8",diffAdditionBg:"#e6f9e6",diffRemovalText:"#661111",diffAdditionText:"#115511",diffRemovalHighlightColor:"#440000",diffRemovalHighlightBg:"#f8b4b4",diffAdditionHighlightColor:"#003300",diffAdditionHighlightBg:"#a6ebad",diffRemovalNum:"#c02020",diffAdditionNum:"#188028",diffRemovalPrefix:"#d01010",diffAdditionPrefix:"#109020",primary:"black",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"black",statusOff:"gray",logoTextAnsi:"\x1B[1;30m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#0077ff","#ff00ff"]},"GitHub Dark":{id:"GitHub Dark",name:"GitHub Dark",text:"#c9d1d9",textMuted:"#8b949e",textDim:"#6e7681",textInverted:"#0d1117",border:"#30363d",borderMuted:"#30363d",borderDim:"#21262d",bg:void 0,cardBg:"#161b22",highlightBg:"#21262d",activeBg:"#30363d",inputBg:"#21262d",inputBorder:"#21262d",inputText:"#c9d1d9",inputPlaceholder:"#8b949e",inputPrompt:"#58a6ff",codeBg:"#0d1117",codeBorder:"#30363d",userMsgBg:"#21262d",userMsgBorder:"#21262d",userMsgText:"#c9d1d9",diffRemovalBg:"#3c1e1e",diffAdditionBg:"#11381e",diffRemovalText:"#f85149",diffAdditionText:"#3fb950",diffRemovalHighlightColor:"#ff7b72",diffRemovalHighlightBg:"#701c1c",diffAdditionHighlightColor:"#56d364",diffAdditionHighlightBg:"#116329",diffRemovalNum:"#f85149",diffAdditionNum:"#3fb950",diffRemovalPrefix:"#f85149",diffAdditionPrefix:"#3fb950",primary:"#c9d1d9",secondary:"#58a6ff",accent:"#bc8cff",success:"#3fb950",warning:"#d29922",danger:"#f85149",info:"#58a6ff",statusOn:"#58a6ff",statusOff:"#8b949e",logoTextAnsi:"\x1B[1;36m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#2ea043","#56d364"]},"GitHub Light":{id:"GitHub Light",name:"GitHub Light",text:"#24292f",textMuted:"#57606a",textDim:"#6e7781",textInverted:"#ffffff",border:"#d0d7de",borderMuted:"#d0d7de",borderDim:"#e1e4e8",bg:void 0,cardBg:"#f6f8fa",highlightBg:"#eaeef2",activeBg:"#d0d7de",inputBg:"#eaeef2",inputBorder:"#eaeef2",inputText:"#24292f",inputPlaceholder:"#57606a",inputPrompt:"#0969da",codeBg:"#ffffff",codeBorder:"#d0d7de",userMsgBg:"#eaeef2",userMsgBorder:"#eaeef2",userMsgText:"#24292f",diffRemovalBg:"#ffebe9",diffAdditionBg:"#e6ffec",diffRemovalText:"#cf222e",diffAdditionText:"#1a7f37",diffRemovalHighlightColor:"#82071e",diffRemovalHighlightBg:"#ffc1c0",diffAdditionHighlightColor:"#116329",diffAdditionHighlightBg:"#acf2bd",diffRemovalNum:"#cf222e",diffAdditionNum:"#1a7f37",diffRemovalPrefix:"#cf222e",diffAdditionPrefix:"#1a7f37",primary:"#24292f",secondary:"#0969da",accent:"#8250df",success:"#1a7f37",warning:"#9a6700",danger:"#cf222e",info:"#0969da",statusOn:"#0969da",statusOff:"#57606a",logoTextAnsi:"\x1B[1;34m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#1a7f37","#2da44e"]},"Transparent Dark":{id:"Transparent Dark",name:"Transparent Dark",text:"white",textMuted:"gray",textDim:"grey",textInverted:"black",border:"gray",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:void 0,highlightBg:"#2a2a2a",activeBg:"#3a3a3a",inputBg:"#555555",inputBorder:"#555555",inputText:"white",inputPlaceholder:"#cccccc",inputPrompt:"white",codeBg:void 0,codeBorder:"gray",userMsgBg:"#555555",userMsgBorder:"#555555",userMsgText:"white",diffRemovalBg:void 0,diffAdditionBg:void 0,diffRemovalText:"#ff6666",diffAdditionText:"#66ff66",diffRemovalHighlightColor:"#ff3333",diffRemovalHighlightBg:void 0,diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:void 0,diffRemovalNum:"#ff6666",diffAdditionNum:"#66ff66",diffRemovalPrefix:"#ff4d4d",diffAdditionPrefix:"#4dff88",primary:"white",secondary:"cyan",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"white",statusOff:"gray",logoTextAnsi:"\x1B[1;37m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#0077ff","#ff00ff"]},"Transparent Light":{id:"Transparent Light",name:"Transparent Light",text:"black",textMuted:"gray",textDim:"grey",textInverted:"white",border:"gray",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:void 0,highlightBg:"#d4d4d4",activeBg:"#c0c0c0",inputBg:"#d0d0d0",inputBorder:"#d0d0d0",inputText:"black",inputPlaceholder:"#555555",inputPrompt:"black",codeBg:void 0,codeBorder:"gray",userMsgBg:"#d0d0d0",userMsgBorder:"#d0d0d0",userMsgText:"black",diffRemovalBg:void 0,diffAdditionBg:void 0,diffRemovalText:"#c02020",diffAdditionText:"#188028",diffRemovalHighlightColor:"#800000",diffRemovalHighlightBg:void 0,diffAdditionHighlightColor:"#004000",diffAdditionHighlightBg:void 0,diffRemovalNum:"#c02020",diffAdditionNum:"#188028",diffRemovalPrefix:"#d01010",diffAdditionPrefix:"#109020",primary:"black",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"black",statusOff:"gray",logoTextAnsi:"\x1B[1;30m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#0077ff","#ff00ff"]},"Synthwave 84":{id:"Synthwave 84",name:"Synthwave 84",text:"#fdfdfd",textMuted:"#a08eb7",textDim:"#705c8a",textInverted:"#1a1025",textExclusive:"#e3dcf0",textMutedExclusive:"#b9abc9",border:"#fc28a8",borderMuted:"#a21568",borderDim:"#5c0a3a",bg:void 0,cardBg:"#261b38",highlightBg:"#35254d",activeBg:"#4c3570",inputBg:"#35254d",inputBorder:"#35254d",inputText:"#fdfdfd",inputPlaceholder:"#a08eb7",inputPrompt:"#03e8fc",codeBg:"#1e142b",codeBorder:"#a21568",userMsgBg:"#35254d",userMsgBorder:"#35254d",userMsgText:"#fdfdfd",diffRemovalBg:"#471434",diffAdditionBg:"#144743",diffRemovalText:"#ff4081",diffAdditionText:"#00e5ff",diffRemovalHighlightColor:"#ff79a1",diffRemovalHighlightBg:"#6b1e4e",diffAdditionHighlightColor:"#66f5ff",diffAdditionHighlightBg:"#1e6b65",diffRemovalNum:"#ff4081",diffAdditionNum:"#00e5ff",diffRemovalPrefix:"#ff79a1",diffAdditionPrefix:"#66f5ff",primary:"#fdfdfd",secondary:"#03e8fc",accent:"#fc28a8",success:"#00e5ff",warning:"#ffc107",danger:"#ff4081",info:"#b388ff",statusOn:"#03e8fc",statusOff:"#a08eb7",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#fc28a8","#03e8fc"]},"Forest Sprite":{id:"Forest Sprite",name:"Forest Sprite",text:"#d6e6d1",textMuted:"#95b38d",textDim:"#628059",textInverted:"#161c14",textExclusive:"#eaf2e8",textMutedExclusive:"#a9c7a2",border:"#74a862",borderMuted:"#477038",borderDim:"#2b4720",bg:void 0,cardBg:"#1f291c",highlightBg:"#2a3826",activeBg:"#3a4d35",inputBg:"#2a3826",inputBorder:"#2a3826",inputText:"#d6e6d1",inputPlaceholder:"#95b38d",inputPrompt:"#8feb73",codeBg:"#161e14",codeBorder:"#477038",userMsgBg:"#2a3826",userMsgBorder:"#2a3826",userMsgText:"#d6e6d1",diffRemovalBg:"#3b231c",diffAdditionBg:"#203b1c",diffRemovalText:"#db6242",diffAdditionText:"#59cc3f",diffRemovalHighlightColor:"#f0896c",diffRemovalHighlightBg:"#5c362a",diffAdditionHighlightColor:"#80e368",diffAdditionHighlightBg:"#305929",diffRemovalNum:"#db6242",diffAdditionNum:"#59cc3f",diffRemovalPrefix:"#f0896c",diffAdditionPrefix:"#80e368",primary:"#d6e6d1",secondary:"#8feb73",accent:"#e69835",success:"#59cc3f",warning:"#e69835",danger:"#db6242",info:"#73b4eb",statusOn:"#8feb73",statusOff:"#95b38d",logoTextAnsi:"\x1B[1;32m",logoBodyAnsi:"\x1B[32m",logoMutedAnsi:"\x1B[90m",logoGradient:["#8feb73","#e69835"]}};var Fo=null;var pr=(e="Dark")=>{let t;e==="Mystery"||e==="Chaos"?(Fo||(Fo=hr[Math.floor(Math.random()*hr.length)]),t={...Fo,id:"Mystery"}):(Fo=null,go[e]?t=go[e]:e==="GitHub"?t=go["GitHub Dark"]:e==="Transparent"?t=go["Transparent Dark"]:t=go.Dark);let n=t.codeText||t.secondary||t.info||t.logoGradient&&t.logoGradient[0]||"cyan";return{...t,codeText:n}};var la=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",Xl=(e=2)=>{let t=la();return t==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)},Ql=(e="...",t="Loading...",n="Dark")=>{let s=Is[Math.floor(Math.random()*Is.length)],o=pr(n),d=o.logoTextAnsi,f=o.logoBodyAnsi,a=o.logoMutedAnsi,h="\x1B[0m",g=[" \u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2588\u2588\u2588\u2591 "," \u2588\u2588\u2588\u2591 "," \u2588\u2588\u2588\u2591 "," \u2591\u2591\u2591 "],u=o.logoGradient||["#0077ff","#ff00ff"],m=aa(u).multiline(g.join(`
574
573
  `)).split(`
575
- `),b=i=>`${a}${i}${m}`;return`${h[0]}
576
- ${h[1]} ${d}Selected Provider: ${t}${m}
577
- ${h[2]}
578
- ${h[3]} ${d}FluxFlow ${b("v"+e)}${m}
579
- ${h[4]}
580
- ${h[5]} ${f}See /help for additional commands.${m}
581
- ${h[6]} ${b(s)}
582
- ${h[7]}
583
- `};import uo from"fs";var hn=null,Is=()=>{try{if(uo.existsSync(So)){let e=uo.readFileSync(So,"utf-8"),t=JSON.parse(e);if(t&&typeof t=="object")return hn=t,hn}}catch{}return hn=hn||{},hn},pr=e=>{try{return uo.existsSync(en)||uo.mkdirSync(en,{recursive:!0}),uo.writeFileSync(So,JSON.stringify(e,null,2),"utf-8"),hn=e,!0}catch{return!1}},$e=(e,t,n)=>{if(!e||!t||!n)return null;let s=hn||Is(),o=`${e}::${t}`,d=s[o];if(d&&typeof d=="object"){let f=n.toLowerCase();if(d[f]!==void 0&&d[f]!==null)return d[f];for(let[a,m]of Object.entries(d))if(a.toLowerCase()===f)return m}return null},zl=(e,t,n,s)=>{if(!e||!t||!n||!s)return{success:!1,reason:"Invalid arguments"};let o=hn||Is(),d=`${e}::${t}`;return(!o[d]||typeof o[d]!="object")&&(o[d]={}),o[d][n.toLowerCase()]=s,{success:pr(o)}},Jl=(e,t,n)=>{if(!e||!t)return{success:!1,reason:"Invalid arguments"};let s=hn||Is(),o=`${e}::${t}`;return s[o]&&(n?(delete s[o][n.toLowerCase()],Object.keys(s[o]).length===0&&delete s[o]):delete s[o],pr(s)),{success:!0}};import{WebSocket as Bo}from"ws";var Bt=null,Kn=!1,ca="ws://localhost:56832",Ds=[],Yn=null,Os=null,yr="2.0.0",Zl=e=>{yr=e,xr()},Ls=e=>{Os=e},xr=()=>{if(Bt||Kn)return;Kn=!0;let e=new Bo(ca);e.on("open",()=>{for(Bt=e,Kn=!1,Bt.send(JSON.stringify({command:"version",version:yr,pid:process.pid,ppid:process.ppid}));Ds.length>0;)Bt.send(JSON.stringify(Ds.shift()))}),e.on("message",t=>{try{let n=JSON.parse(t.toString());n.command==="contextResponse"&&Yn?(Yn(n.data),Yn=null):n.command==="securityResponse"&&Os&&Os(n.result)}catch{}}),e.on("error",()=>{Kn=!1,Bt=null}),e.on("close",()=>{Kn=!1,Bt=null})},Uo=e=>{Bt&&Bt.readyState===Bo.OPEN?Bt.send(JSON.stringify(e)):(Ds.push(e),Kn||xr())},Wo=()=>Bt!==null&&Bt.readyState===Bo.OPEN,ec=e=>{Uo({command:"status",status:e})},Ln=()=>new Promise(e=>{if(!Bt||Bt.readyState!==Bo.OPEN){e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]});return}Yn=e,Bt.send(JSON.stringify({command:"requestContext"})),setTimeout(()=>{Yn===e&&(e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]}),Yn=null)},1e3)}),br=e=>{Uo({command:"open",filePath:e})},Ps=(e,t,n)=>{Uo({command:"showDiff",filePath:e,originalContent:t,modifiedContent:n})},kr=(e,t)=>{Uo({command:"closeDiff",filePath:e,result:t})};import wr from"path";import da from"fs";var fa=e=>{try{return da.readdirSync(e,{withFileTypes:!0})}catch{return[]}},$s=(e,t,n=1,s=fa,o=[],d=null)=>{let f=d||s(e),a=" ".repeat(n-1);if(f.length>100)return`${a}${wr.basename(e)}/ (>100 files)
584
- `;let m="",g=o,u=f.filter(l=>!g.includes(l.name)&&!l.name.startsWith(".")),h=f.filter(l=>g.includes(l.name)||l.name.startsWith(".")).map(l=>l.name).sort();h.length>0&&(m+=`${a}[ignored: ${h.map(l=>l+"/").join(", ")}]
585
- `);let b=u.filter(l=>l.isDirectory()).sort((l,_)=>l.name.localeCompare(_.name)),i=u.filter(l=>!l.isDirectory()).map(l=>l.name).sort();for(let l of b){let _=wr.join(e,l.name);if(n>t)m+=`${a}${l.name}/ (max depth)
586
- `;else{let C=s(_);C.length>80?m+=`${a}${l.name}/ (>80 files)
587
- `:(m+=`${a}${l.name}/
588
- `,m+=$s(_,t,n+1,s,o,C))}}return i.length>0&&(m+=`${a}${i.join("; ")}
589
- `),m};import Ns from"path";import ua from"fs";var ga=e=>{try{return ua.readdirSync(e,{withFileTypes:!0})}catch{return[]}},Fs=(e,t,n="",s=1,o=ga,d=[])=>{let f=o(e),a=Ns.sep;if(f.length>100)return`${n}\u2514\u2500\u2500 ${Ns.basename(e)}${a} ...100+ files...
590
- `;let m="",g=d,u=f.filter(i=>!g.includes(i.name)&&!i.name.startsWith(".")),h=f.filter(i=>g.includes(i.name)||i.name.startsWith(".")).map(i=>i.name).sort();u.sort((i,l)=>i.isDirectory()&&!l.isDirectory()?-1:!i.isDirectory()&&l.isDirectory()?1:i.name.localeCompare(l.name));let b=[...u.map(i=>({name:i.name,isDir:i.isDirectory()})),...h.map(i=>({name:i,isDir:!0,isCollapsed:!0}))];return b.forEach((i,l)=>{let _=l===b.length-1,C=Ns.join(e,i.name),x=_?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",R=n+(_?" ":"\u2502 ");if(i.isCollapsed){m+=`${n}${x}${i.name}${a}...
591
- `;return}i.isDir?s>t?m+=`${n}${x}${i.name}${a} ...depth exceeded...
592
- `:o(C).length>80?m+=`${n}${x}${i.name}${a} ...80+ files...
593
- `:(m+=`${n}${x}${i.name}${a}
594
- `,m+=Fs(C,t,R,s+1,o,d)):m+=`${n}${x}${i.name}
595
- `}),m};import"@google/genai";var tt=async(e,t,n=5,s=1e3)=>{let o=t?.signal;for(let f=0;f<n;f++){if(o?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{let a=await fetch(e,t);if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),a.ok||a.status!==429&&a.status<500)return a}catch(a){if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),a.name==="AbortError"||o?.aborted||f===n-1)throw a}o?await new Promise((a,m)=>{let g=setTimeout(()=>{o.removeEventListener("abort",u),a()},Math.min(24e3,s*Math.pow(2,f))),u=()=>{clearTimeout(g),m(new DOMException("The user aborted a request.","AbortError"))};o.addEventListener("abort",u)}):await new Promise(a=>setTimeout(a,Math.min(24e3,s*Math.pow(2,f))))}if(o?.aborted)throw new DOMException("The user aborted a request.","AbortError");let d=await fetch(e,t);return typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),d};async function Ho(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 pn=e=>typeof e!="string"?e:e.replace(/<\|channel>thought/gi,"<think>").replace(/<channel\|>/gi,"</think>");var Go=async function*(e,t,n,s,o,d,f,a,m=1){let g=[];s&&g.push({role:"system",content:s});for(let M of n){let $=M.role==="user"?"user":"assistant",p=[];if(Array.isArray(M.parts)){for(let c of M.parts)if(c.text)p.push({type:"text",text:c.text});else if((c.inlineData||c.inline_data)&&f){let w=c.inlineData||c.inline_data,r=w.mimeType||w.mime_type||"image/jpeg",k=w.data;r.startsWith("image/")&&p.push({type:"image_url",image_url:{url:`data:${r};base64,${k}`}})}}else{let c=M.text||"";c&&p.push({type:"text",text:c})}g.push({role:$,content:p.length===1&&p[0].type==="text"?p[0].text:p})}let u={model:t,messages:g,stream:!0,stream_options:{include_usage:!0},temperature:m},h=$e("DeepSeek",t,o),i=h!==null?h:o!=="Fast"?{Low:"high",Medium:"high",Standard:"high",High:"max",xHigh:"max"}[o]||"high":null;i&&i!=="disabled"&&i!=="none"&&i!=="false"&&i!==!1?(u.reasoning_effort=i,u.extra_body={thinking:{type:"enabled"}}):u.extra_body={thinking:{type:"disabled"}};let l=await tt("https://api.deepseek.com/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(u),signal:a});if(!l.ok){let M=await l.json().catch(()=>({}));throw new Error(`DeepSeek Error (${l.status}): ${M.error?.message||l.statusText}`)}let _=l.body.getReader(),C=new TextDecoder,x="",R=[],N=null,D=Date.now(),S=!1;for(;;){let{done:M,value:$}=await _.read();if(M){S&&(R.length>0||N)&&(yield{candidates:R.length>0?[{content:{parts:R}}]:[],usageMetadata:N});break}x+=C.decode($,{stream:!0});let p=x.split(`
596
- `);x=p.pop();for(let c of p){let w=c.trim();if(!w||!w.startsWith("data: "))continue;let r=!1;if(w==="data: [DONE]")r=!0;else try{let k=JSON.parse(w.substring(6)),E=k.choices?.[0]?.delta,O=k.usage;if(k.choices?.[0]?.finish_reason&&(r=!0),O&&(N={totalTokenCount:O.total_tokens||O.prompt_tokens+O.completion_tokens,promptTokenCount:O.prompt_tokens||0,candidatesTokenCount:O.completion_tokens||0,cachedContentTokenCount:O.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:O.completion_tokens_details?.reasoning_tokens||0},S=!0),E){let U=E.reasoning_content||null;U&&(R.push({text:U,thought:!0}),S=!0),E.content&&(R.push({text:E.content}),S=!0)}}catch{}if((r||Date.now()-D>=150)&&S&&(yield{candidates:R.length>0?[{content:{parts:[...R]}}]:[],usageMetadata:N},R=[],D=Date.now(),S=!1),r)break}Date.now()-D>=150&&S&&(yield{candidates:R.length>0?[{content:{parts:[...R]}}]:[],usageMetadata:N},R=[],D=Date.now(),S=!1)}};var jo=async function*(e,t,n,s,o,d,f,a,m=1,g=null){let u=[];s&&u.push({role:"system",content:s});for(let c of n){let w=c.role==="user"?"user":"assistant",r=[];if(Array.isArray(c.parts)){for(let k of c.parts)if(k.text)r.push({type:"text",text:k.text});else if(k.inlineData&&f){let E=k.inlineData.mimeType,O=k.inlineData.data;E.startsWith("image/")&&r.push({type:"image_url",image_url:`data:${E};base64,${O}`})}}else{let k=c.text||"";k&&r.push({type:"text",text:k})}r.length>0&&u.push({role:w,content:r.length===1&&r[0].type==="text"?r[0].text:r})}let h={Fast:"none",Low:"none",Medium:"high",Standard:"high",High:"high",xHigh:"high"},b=`${e.slice(-5)}${g||""}${o}${t}`,i=await Ho(b),l={model:t,messages:u,stream:!0,temperature:m,prompt_cache_key:i},_=$e("Mistral",t,o);_!==null?_&&_!=="none"&&_!=="disabled"&&_!==!1&&(l.reasoning_effort=_):o&&o!=="Fast"&&Vn(t)&&(l.reasoning_effort=h[o]||"high");let C=await tt("https://api.mistral.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(l),signal:a});if(!C.ok){let c=await C.text().catch(()=>""),w=C.statusText;try{let r=JSON.parse(c);w=r.error?.message||r.message||JSON.stringify(r.detail||r)}catch{c&&(w=c)}throw new Error(`Mistral Error (${C.status}): ${JSON.stringify(w)}`)}let x=C.body.getReader(),R=new TextDecoder,N="",D=[],S=null,M=Date.now(),$=!1,p=c=>c?typeof c=="string"?pn(c):Array.isArray(c)?c.map(p).filter(Boolean).join(""):typeof c=="object"&&c!==null?typeof c.text=="string"?pn(c.text):typeof c.content=="string"?pn(c.content):typeof c.thinking=="string"?pn(c.thinking):typeof c.reasoning_content=="string"?pn(c.reasoning_content):typeof c.reasoning=="string"?pn(c.reasoning):typeof c.value=="string"?pn(c.value):c.text?p(c.text):c.content?p(c.content):c.thinking?p(c.thinking):c.reasoning_content?p(c.reasoning_content):c.reasoning?p(c.reasoning):c.value?p(c.value):"":pn(String(c)):"";for(;;){let{done:c,value:w}=await x.read();if(c){$&&(D.length>0||S)&&(yield{candidates:D.length>0?[{content:{parts:D}}]:[],usageMetadata:S});break}N+=R.decode(w,{stream:!0});let r=N.split(`
597
- `);N=r.pop();for(let k of r){let E=k.trim();if(!E||!E.startsWith("data: "))continue;let O=!1;if(E==="data: [DONE]")O=!0;else try{let U=JSON.parse(E.substring(6)),P=U.choices?.[0]?.delta,I=U.usage;if(U.choices?.[0]?.finish_reason&&(O=!0),I&&(S={totalTokenCount:I.total_tokens||(I.prompt_tokens||0)+(I.completion_tokens||0),promptTokenCount:I.prompt_tokens||0,candidatesTokenCount:I.completion_tokens||0,cachedContentTokenCount:I.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:I.completion_tokens_details?.reasoning_tokens||0},$=!0),P){let Z=P.thinking||P.reasoning_content||P.reasoning,ke=p(Z);ke&&(D.push({text:ke,thought:!0}),$=!0);let B=P.content||(!P.thinking&&!P.reasoning_content&&!P.reasoning?P.text:null);if(B)if(Array.isArray(B))for(let A of B)if(typeof A=="object"&&A!==null){let Ee=A.type==="thinking"||A.type==="reasoning"||!!A.thought,se=p(A);se&&(D.push({text:se,...Ee?{thought:!0}:{}}),$=!0)}else{let Ee=p(A);Ee&&(D.push({text:Ee}),$=!0)}else if(typeof B=="object"&&B!==null){let A=B.type==="thinking"||B.type==="reasoning"||!!B.thought,Ee=p(B);Ee&&(D.push({text:Ee,...A?{thought:!0}:{}}),$=!0)}else{let A=p(B);A&&(D.push({text:A}),$=!0)}}}catch{}if((O||Date.now()-M>=150)&&$&&(yield{candidates:D.length>0?[{content:{parts:[...D]}}]:[],usageMetadata:S},D=[],M=Date.now(),$=!1),O)break}Date.now()-M>=150&&$&&(yield{candidates:D.length>0?[{content:{parts:[...D]}}]:[],usageMetadata:S},D=[],M=Date.now(),$=!1)}};var Vo=async function*(e,t,n,s,o,d,f=!1,a,m=1){let g=[];s&&g.push({role:"system",content:s}),n.forEach(se=>{let v=se.role==="model"?"assistant":"user",G=[];Array.isArray(se.parts)&&se.parts.forEach(ee=>{if(ee.text)G.push({type:"text",text:ee.text});else if(ee.inlineData&&f){let Y=ee.inlineData.mimeType,Xe=ee.inlineData.data;Y.startsWith("image/")&&dt(t)&&G.push({type:"image_url",image_url:{url:`data:${Y};base64,${Xe}`}})}}),g.push({role:v,content:G.length===1&&G[0].type==="text"?G[0].text:G})});let u=$e("NVIDIA",t,o),b=u!==null?u:{Fast:"Fast",Low:"Fast",Medium:"Standard",Standard:"Standard",High:"High",xHigh:"High"}[o]||"High",i=b!=="Fast"&&b!=="none"&&b!=="disabled"&&b!==!1,l=t.includes("kimi"),_=t.includes("gemma"),C=t.includes("deepseek"),x=t.includes("glm"),R=t.includes("mistral"),N=t.includes("minimax"),D=t.includes("gpt"),S=t.includes("qwen"),M=t.includes("nemotron"),$=t.includes("llama-3"),p=t.includes("seed"),c=t.includes("poolside"),w=t.includes("thinkingmachines")||t.includes("muse"),r=$,k=null,E={Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},O={Fast:"64",Low:"64",Medium:"4096",Standard:"4096",High:"16384",xHigh:"16384"},U={Fast:"none",Low:"minimal",Medium:"medium",Standard:"medium",High:"max",xHigh:"max"},P=N||C||c||w?16384:32768;P=process.env.NVIDIA_BASE_URL?1024:P,P=k?1024:P;let I={model:t,messages:g,max_tokens:P,stream:!0,stream_options:{include_usage:!0},temperature:m,...D&&{thinking:E[o]||"high"}};if(!(process.env.NVIDIA_BASE_URL||r||k))if(l)I.chat_template_kwargs={thinking:i};else if(_)I.chat_template_kwargs={enable_thinking:i};else if(C)if(i){let se=b==="High"?"max":"high";I.chat_template_kwargs={thinking:!0,reasoning_effort:se}}else I.chat_template_kwargs={thinking:!1};else x?I.chat_template_kwargs={enable_thinking:i,clear_thinking:!i}:R?I.reasoning_effort=i?"high":"none":N&&t.includes("minimax-m3")?I.chat_template_kwargs={thinking_mode:i?"enabled":"disabled"}:S?I.chat_template_kwargs={enable_thinking:i}:M?b==="High"?I.chat_template_kwargs={enable_thinking:!0}:b==="Standard"?I.chat_template_kwargs={enable_thinking:!0,medium_effort:!0}:I.chat_template_kwargs={enable_thinking:!1}:p?i&&(I.extra_body={thinking_budget:parseInt(O[b]??"4096")}):c?I.chat_template_kwargs={enable_thinking:i}:w&&(I.reasoning_effort=U[b]||"medium");let Z=0,ke=6,B=!1,A=process.env.NVIDIA_BASE_URL||"https://integrate.api.nvidia.com/v1/chat/completions",Ee=process.env.NVIDIA_API_KEY&&process.env.NVIDIA_BASE_URL?process.env.NVIDIA_API_KEY:e;for(A.endsWith("/chat/completions")||(A=A.replace(/\/+$/,"")+"/chat/completions");Z<ke;){Z++;try{let se=await tt(A,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Ee}`},body:JSON.stringify(I),signal:a});if(!se.ok){let ft=await se.text().catch(()=>""),Qe=se.statusText;try{let At=JSON.parse(ft);Qe=At.error?.message||At.message||JSON.stringify(At.detail||At)}catch{ft&&(Qe=ft)}let pt=new Error(`NVIDIA API Error (${se.status}): ${Qe}`);throw pt.status=se.status,pt}let v=se.body.getReader(),G=new TextDecoder,ee="",Y=[],Xe=null,Ye=Date.now(),Ge=!1;for(;;){let{done:ft,value:Qe}=await v.read();if(ft){Ge&&(Y.length>0||Xe)&&(yield{candidates:Y.length>0?[{content:{parts:Y}}]:[],usageMetadata:Xe},B=!0);break}ee+=G.decode(Qe,{stream:!0});let pt=ee.split(`
598
- `);ee=pt.pop();let At=!1;for(let xn of pt){let Yt=xn.trim();if(Yt){if(Yt==="data: [DONE]"){At=!0;break}if(Yt.startsWith("data: ")){let ct;try{ct=JSON.parse(Yt.substring(6))}catch{continue}if(ct.error)throw new Error(`NVIDIA Stream Error: ${ct.error.message||JSON.stringify(ct.error)}`);try{let fe=ct.usage;fe&&(Xe={totalTokenCount:fe.total_tokens||fe.prompt_tokens+fe.completion_tokens,promptTokenCount:fe.prompt_tokens||0,candidatesTokenCount:fe.completion_tokens||0,cachedContentTokenCount:fe.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:(fe.completion_tokens_details?.reasoning_tokens||0)+(fe.completion_tokens_details?.thoughts_tokens||0)},Ge=!0);let ue=ct.choices?.[0]?.delta?.reasoning||ct.choices?.[0]?.delta?.reasoning_content||"",ie=ct.choices?.[0]?.delta?.content||"";ue&&(Y.push({text:ue,thought:!0}),Ge=!0),ie&&(Y.push({text:ie}),Ge=!0)}catch{}}}}if((At||Date.now()-Ye>=350)&&Ge&&(yield{candidates:Y.length>0?[{content:{parts:[...Y]}}]:[],usageMetadata:Xe},B=!0,Y=[],Ye=Date.now(),Ge=!1),At)break}break}catch(se){if(B||Z>=ke)throw se;await new Promise(v=>setTimeout(v,3500))}}},Tr=async function*(e,t){let n=[],s=null,o=!1,d=null,f=i=>{if(n.push(i),s){let l=s;s=null,l()}},a=t.split("/").pop();a=a.replace("llama-3.3","llama-3_3");let m=`https://buildapi.ngc.nvidia.com/v2/predict/queues/models/qc69jvmznzxy/${a}`,g=`https://api.ngc.nvidia.com/v2/predict/queues/models/qc69jvmznzxy/${a}`,u=!1,h=null,b=async()=>{try{let l=await(await Promise.any([m,g].map(async _=>{let C=await fetch(_);if(!C.ok)throw new Error(`HTTP ${C.status}`);return C}))).json();if(l&&l.queues&&l.queues[0]&&typeof l.queues[0].queueDepth=="number"){let _=l.queues[0].queueDepth;u||f({value:{type:"status",content:`Queue ${_||1}`},done:!1})}}catch{}};process.env.NVIDIA_BASE_URL||(b(),h=setInterval(b,5e3)),(async()=>{try{let i=e[Symbol.asyncIterator]();for(;;){let{value:l,done:_}=await i.next();if(_)break;u=!0,h&&(clearInterval(h),h=null),f({value:l,done:!1})}o=!0,f(null)}catch(i){if(d=i,h&&(clearInterval(h),h=null),s){let l=s;s=null,l()}}})();try{for(;;){if(d)throw d;if(n.length>0){let i=n.shift();if(i===null&&o)break;yield i.value}else{if(o)break;await new Promise(i=>{s=i})}}}finally{h&&(clearInterval(h),h=null)}};var Ko=async function*(e,t,n,s,o,d,f,a,m=1,g=null){let u=[];s&&u.push({role:"system",content:[{type:"text",text:s}]});for(let E of n){let O=E.role==="user"?"user":"assistant",U=[];if(Array.isArray(E.parts)){for(let P of E.parts)if(P.text)U.push({type:"text",text:P.text});else if(P.inlineData&&f){let I=P.inlineData.mimeType,Z=P.inlineData.data;I.startsWith("image/")?U.push({type:"image_url",image_url:{url:`data:${I};base64,${Z}`}}):U.push({type:"file",file:{filename:P.filename||"file",file_data:`data:${I};base64,${Z}`}})}}else{let P=E.text||"";P&&U.push({type:"text",text:P})}u.push({role:O,content:U.length===1&&U[0].type==="text"?U[0].text:U})}let h={Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},b=["free","nitro","floor","exacto"],i=t,l=null,_=null;if(t.includes(":")){let E=t.split(":");if(E.length>1){let O=E[E.length-1].toLowerCase().trim();(O==="flex"||O==="priority")&&(_=O,E.pop())}if(E.length>1){let O=E[E.length-1].toLowerCase().trim();if(!b.includes(O)){let U=E.pop().trim();U&&(l={only:[U],allow_fallbacks:!1})}}i=E.join(":").trim()}let C=`${e.slice(-5)}${g||""}${o}${i}${_||""}${l?JSON.stringify(l):""}`,x=await Ho(C),R={model:i,messages:u,stream:!0,temperature:m,cache_control:{type:"ephemeral"},session_id:x};_&&(R.service_tier=_),l&&(R.provider=l);let N=$e("OpenRouter",t,o),D=N!==null?N:h[o];D&&D!=="none"&&(N!==null||o!=="Fast")&&(R.reasoning_effort=D);let S=await tt("https://openrouter.ai/api/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json","HTTP-Referer":"https://fluxflow-cli.onrender.com/","X-Title":"FluxFlow CLI","X-OpenRouter-Title":"FluxFlow CLI","X-Cache":"true","X-OpenRouter-Cache":"true"},body:JSON.stringify(R),signal:a});if(!S.ok){let E=await S.json().catch(()=>({})),O=E.error?.metadata?.raw||E.error?.message||(typeof E.error=="string"?E.error:"")||S.statusText||"Unknown error";throw new Error(`OpenRouter Error (${S.status}): ${O}`)}let M=S.body.getReader(),$=new TextDecoder,p="",c=[],w=null,r=Date.now(),k=!1;for(;;){let{done:E,value:O}=await M.read();if(E){k&&(c.length>0||w)&&(yield{candidates:c.length>0?[{content:{parts:c}}]:[],usageMetadata:w});break}p+=$.decode(O,{stream:!0});let U=p.split(`
599
- `);p=U.pop();for(let P of U){let I=P.trim();if(!I||!I.startsWith("data: "))continue;let Z=!1;if(I==="data: [DONE]")Z=!0;else try{let ke=JSON.parse(I.substring(6));if(ke.error){let Ee=ke.error.metadata?.raw||ke.error.message||JSON.stringify(ke.error);throw new Error(`OpenRouter Stream Error: ${Ee}`)}let B=ke.choices?.[0]?.delta,A=ke.usage;if(ke.choices?.[0]?.finish_reason&&(Z=!0),A&&(w={totalTokenCount:A.total_tokens||(A.prompt_tokens||0)+(A.completion_tokens||0),promptTokenCount:A.prompt_tokens||0,candidatesTokenCount:A.completion_tokens||0,cachedContentTokenCount:A.prompt_tokens_details?.cached_tokens||A.prompt_tokens_details?.cache_read_input_tokens||A.cache_read_input_tokens||0,thoughtsTokenCount:A.completion_tokens_details?.reasoning_tokens||0},k=!0),B){let Ee=B.reasoning||(B.reasoning_details?B.reasoning_details.map(se=>se.text).join(""):null);Ee&&(c.push({text:Ee,thought:!0}),k=!0),B.content&&(c.push({text:B.content}),k=!0)}}catch(ke){if(ke.message&&ke.message.startsWith("OpenRouter Stream Error:"))throw ke}if((Z||Date.now()-r>=150)&&k&&(yield{candidates:c.length>0?[{content:{parts:[...c]}}]:[],usageMetadata:w},c=[],r=Date.now(),k=!1),Z)break}}};import{Ollama as ma}from"ollama";var Bs=async function*(e,t,n,s,o,d,f,a,m=1,g="Cloud"){let u=[];s&&u.push({role:"system",content:s});for(let p of n){let c=p.role==="user"?"user":"assistant",w="",r=[];if(Array.isArray(p.parts)){w=p.parts.map(k=>k.text||"").filter(Boolean).join(`
600
- `);for(let k of p.parts){let E=k.inlineData||k.inline_data;E&&E.data&&r.push(E.data)}}else w=p.text||"";if(w||r.length>0){let k={role:c,content:w};r.length>0&&(k.images=r),u.push(k)}}let h=g==="Local"||!e||e==="LOCAL",i={host:h?process.env.OLLAMA_HOST||"http://127.0.0.1:11434":process.env.OLLAMA_HOST||"https://ollama.com"};!h&&e&&(i.headers={Authorization:"Bearer "+e});let l=new ma(i),_=[],C=null,x=Date.now(),R=!1,N=$e("Ollama",t,o),D={Fast:!1,Low:"medium",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},S=N!==null?N==="false"||N===!1?!1:N==="true"||N===!0?!0:N:D[o]!==void 0?D[o]:!0,M={model:t,messages:u,stream:!0,think:S,keep_alive:"10m",options:{temperature:m}},$=await l.chat(M);for await(let p of $){if(a?.aborted)throw new DOMException("The user aborted a request.","AbortError");if(p.message?.thinking&&(_.push({text:p.message.thinking,thought:!0}),R=!0),p.message?.content&&(_.push({text:p.message.content}),R=!0),p.done){let c=p.prompt_cached_count||0;if(!c&&p.prompt_eval_count){let w=p.prompt_eval_duration||0;w>0&&w<5e7&&(c=p.prompt_eval_count)}C={totalTokenCount:(p.prompt_eval_count||0)+(p.eval_count||0),promptTokenCount:p.prompt_eval_count||0,candidatesTokenCount:p.eval_count||0,cachedContentTokenCount:c,thoughtsTokenCount:0},R=!0}(p.done||Date.now()-x>=150&&R)&&(yield{candidates:_.length>0?[{content:{parts:[..._]}}]:[],usageMetadata:C},_=[],x=Date.now(),R=!1)}R&&(_.length>0||C)&&(yield{candidates:_.length>0?[{content:{parts:[..._]}}]:[],usageMetadata:C})};var Yo=async function*(e,t,n,s,o,d,f,a,m=1){let g=[];s&&g.push({role:"system",content:s});for(let c of n){let w=c.role==="user"?"user":"assistant",r="";if(Array.isArray(c.parts))for(let k of c.parts)k.text&&(r+=(r?`
601
- `:"")+k.text);else r=c.text||"";g.push({role:w,content:r})}let u=$e("InferX",t,o),b=u!==null?u:{Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i=t&&t.toLowerCase().includes("qwen3.8-27b")&&u===null,l=t&&(t.toLowerCase().includes("qwen3.8-27b")||t.toLowerCase().includes("qwen3.6-35b-a3b-fp8")),_={model:t,messages:g.filter(c=>c.content&&String(c.content).trim().length>0),stream:!0,stream_options:{include_usage:!0},temperature:m};!i&&b&&(_.stream_options={include_usage:!0},_.reasoning_effort=b);let C=await tt("https://model.inferx.net/endpoints/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(_),signal:a});if(!C.ok){let c=await C.text().catch(()=>""),w="";try{let r=JSON.parse(c);w=r.error?.message||r.error?.detail||r.message||r.detail||(typeof r.error=="string"?r.error:"")||(c&&c!=="{}"?c:"")}catch{w=c}throw(!w||w==="{}")&&(w=C.statusText||"Unknown error"),new Error(`InferX Error (${C.status}): ${w}`)}let x=C.body.getReader(),R=new TextDecoder,N="",D=[],S=null,M=Date.now(),$=!1,p=!0;for(;;){let{done:c,value:w}=await x.read();if(c){$&&(D.length>0||S)&&(yield{candidates:D.length>0?[{content:{parts:D}}]:[],usageMetadata:S});break}N+=R.decode(w,{stream:!0});let r=N.split(`
602
- `);N=r.pop();for(let k of r){let E=k.trim();if(!E||!E.startsWith("data: "))continue;let O=!1;if(E==="data: [DONE]")O=!0;else try{let U=JSON.parse(E.substring(6)),P=U.choices?.[0]?.delta,I=U.usage;if(I&&(S={totalTokenCount:I.total_tokens||(I.prompt_tokens||0)+(I.completion_tokens||0),promptTokenCount:I.prompt_tokens||0,candidatesTokenCount:I.completion_tokens||0,cachedContentTokenCount:I.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:I.completion_tokens_details?.reasoning_tokens||I.reasoning_tokens||0},$=!0),P){let Z=P.reasoning||P.reasoning_content||null;if(Z&&(D.push({text:Z,thought:!0}),$=!0),P.content){let ke=P.content;l&&p&&ke.length>0&&(ke="<think>"+ke,p=!1),D.push({text:ke}),$=!0}}}catch{}if((O||Date.now()-M>=150||S)&&$&&(yield{candidates:D.length>0?[{content:{parts:[...D]}}]:[],usageMetadata:S},D=[],M=Date.now(),$=!1),O)break}Date.now()-M>=150&&$&&(yield{candidates:D.length>0?[{content:{parts:[...D]}}]:[],usageMetadata:S},D=[],M=Date.now(),$=!1)}};var qo=async function*(e,t,n,s,o,d,f,a,m=1){let g=[];s&&g.push({role:"system",content:s});for(let M of n){let $=M.role==="user"?"user":"assistant",p=[];if(Array.isArray(M.parts)){for(let c of M.parts)if(c.text)p.push({type:"text",text:c.text});else if(c.inlineData&&f){let w=c.inlineData.mimeType,r=c.inlineData.data;w.startsWith("image/")&&p.push({type:"image_url",image_url:{url:`data:${w};base64,${r}`}})}}else{let c=M.text||"";c&&p.push({type:"text",text:c})}g.push({role:$,content:p.length===1&&p[0].type==="text"?p[0].text:p})}let u=$e("SenseNova",t,o),b=u!==null?u:{Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:g,stream:!0,stream_options:{include_usage:!0},temperature:m};b&&(i.reasoning_effort=b);let l=await tt("https://token.sensenova.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(i),signal:a});if(!l.ok){let M=await l.json().catch(()=>({}));throw new Error(`SenseNova Error (${l.status}): ${M.error?.message||l.statusText}`)}let _=l.body.getReader(),C=new TextDecoder,x="",R=[],N=null,D=Date.now(),S=!1;for(;;){let{done:M,value:$}=await _.read();if(M){S&&(R.length>0||N)&&(yield{candidates:R.length>0?[{content:{parts:R}}]:[],usageMetadata:N});break}x+=C.decode($,{stream:!0});let p=x.split(`
603
- `);x=p.pop();for(let c of p){let w=c.trim();if(!w||!w.startsWith("data: "))continue;let r=!1;if(w==="data: [DONE]")r=!0;else try{let k=JSON.parse(w.substring(6)),E=k.choices?.[0]?.delta,O=k.usage;if(O&&(N={totalTokenCount:O.total_tokens||(O.prompt_tokens||0)+(O.completion_tokens||0),promptTokenCount:O.prompt_tokens||0,candidatesTokenCount:O.completion_tokens||0,cachedContentTokenCount:O.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:O.completion_tokens_details?.reasoning_tokens||O.reasoning_tokens||0},S=!0),E){let U=E.reasoning||E.reasoning_content||null;U&&(R.push({text:U,thought:!0}),S=!0),E.content&&(R.push({text:E.content}),S=!0)}}catch{}if((r||Date.now()-D>=150||N)&&S&&(yield{candidates:R.length>0?[{content:{parts:[...R]}}]:[],usageMetadata:N},R=[],D=Date.now(),S=!1),r)break}Date.now()-D>=150&&S&&(yield{candidates:R.length>0?[{content:{parts:[...R]}}]:[],usageMetadata:N},R=[],D=Date.now(),S=!1)}};var zo=async function*(e,t,n,s,o,d,f,a,m=1){let g=[];s&&g.push({role:"system",content:s});for(let M of n){let $=M.role==="user"?"user":"assistant",p=[];if(Array.isArray(M.parts)){for(let c of M.parts)if(c.text)p.push({type:"text",text:c.text});else if(c.inlineData&&f){let w=c.inlineData.mimeType,r=c.inlineData.data;w.startsWith("image/")&&p.push({type:"image_url",image_url:{url:`data:${w};base64,${r}`}})}}else{let c=M.text||"";c&&p.push({type:"text",text:c})}g.push({role:$,content:p.length===1&&p[0].type==="text"?p[0].text:p})}let u=$e("AIHubMix",t,o),b=u!==null?u:{Fast:"minimal",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:g,stream:!0,stream_options:{include_usage:!0},temperature:m};b&&(i.reasoning_effort=b);let l=await tt("https://aihubmix.com/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(i),signal:a});if(!l.ok){let M=await l.json().catch(()=>({}));throw new Error(`AIHubMix Error (${l.status}): ${M.error?.message||l.statusText}`)}let _=l.body.getReader(),C=new TextDecoder,x="",R=[],N=null,D=Date.now(),S=!1;for(;;){let{done:M,value:$}=await _.read();if(M){S&&(R.length>0||N)&&(yield{candidates:R.length>0?[{content:{parts:R}}]:[],usageMetadata:N});break}x+=C.decode($,{stream:!0});let p=x.split(`
604
- `);x=p.pop();for(let c of p){let w=c.trim();if(!w||!w.startsWith("data: "))continue;let r=!1;if(w==="data: [DONE]")r=!0;else try{let k=JSON.parse(w.substring(6)),E=k.choices?.[0]?.delta,O=k.usage;if(k.choices?.[0]?.finish_reason&&(r=!0),O&&(N={totalTokenCount:O.total_tokens||(O.prompt_tokens||0)+(O.completion_tokens||0),promptTokenCount:O.prompt_tokens||0,candidatesTokenCount:O.completion_tokens||0,cachedContentTokenCount:O.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:O.completion_tokens_details?.reasoning_tokens||O.reasoning_tokens||0},S=!0),E){let U=E.reasoning_content||null;U&&(R.push({text:U,thought:!0}),S=!0),E.content&&(R.push({text:E.content}),S=!0)}}catch{}if((r||Date.now()-D>=150)&&S&&(yield{candidates:R.length>0?[{content:{parts:[...R]}}]:[],usageMetadata:N},R=[],D=Date.now(),S=!1),r)break}Date.now()-D>=150&&S&&(yield{candidates:R.length>0?[{content:{parts:[...R]}}]:[],usageMetadata:N},R=[],D=Date.now(),S=!1)}};var Jo=async function*(e,t,n,s,o,d,f,a,m=1){let g=[];s&&g.push({role:"system",content:s});for(let S of n){let M=S.role==="user"?"user":"assistant",$=[];if(Array.isArray(S.parts)){for(let p of S.parts)if(p.text)$.push({type:"text",text:p.text});else if(p.inlineData&&f){let c=p.inlineData.mimeType,w=p.inlineData.data;c.startsWith("image/")&&$.push({type:"image_url",image_url:{url:`data:${c};base64,${w}`}})}}else{let p=S.text||"";p&&$.push({type:"text",text:p})}g.push({role:M,content:$.length===1&&$[0].type==="text"?$[0].text:$})}let u=$e("Poolside",t,o),h=u!==null?u===!1||u==="false"||u==="none"||u==="Fast":o==="Fast",b={model:t,messages:g,stream:!0,stream_options:{include_usage:!0},temperature:m};h?b.chat_template_kwargs={enable_thinking:!1}:u!==null&&typeof u=="object"?b.chat_template_kwargs=u:b.chat_template_kwargs={enable_thinking:!0};let i=await tt("https://inference.poolside.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(b),signal:a});if(!i.ok){let S=await i.json().catch(()=>({}));throw new Error(`Poolside Error (${i.status}): ${S.error?.message||i.statusText}`)}let l=i.body.getReader(),_=new TextDecoder,C="",x=[],R=null,N=Date.now(),D=!1;for(;;){let{done:S,value:M}=await l.read();if(S){D&&(x.length>0||R)&&(yield{candidates:x.length>0?[{content:{parts:x}}]:[],usageMetadata:R});break}C+=_.decode(M,{stream:!0});let $=C.split(`
605
- `);C=$.pop();for(let p of $){let c=p.trim();if(!c||!c.startsWith("data: "))continue;let w=!1;if(c==="data: [DONE]")w=!0;else try{let r=JSON.parse(c.substring(6)),k=r.choices?.[0]?.delta,E=r.usage;if(r.choices?.[0]?.finish_reason&&(w=!0),E&&(R={totalTokenCount:E.total_tokens||(E.prompt_tokens||0)+(E.completion_tokens||0),promptTokenCount:E.prompt_tokens||0,candidatesTokenCount:E.completion_tokens||0,cachedContentTokenCount:E.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:E.completion_tokens_details?.reasoning_tokens||E.reasoning_tokens||0},D=!0),k){let O=k.reasoning_content||k.reasoning||null;O&&(x.push({text:O,thought:!0}),D=!0),k.content&&(x.push({text:k.content}),D=!0)}}catch{}if((w||Date.now()-N>=150)&&D&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:R},x=[],N=Date.now(),D=!1),w)break}Date.now()-N>=150&&D&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:R},x=[],N=Date.now(),D=!1)}};var Xo=async function*(e,t,n,s,o,d,f,a,m=1){let g=[];s&&g.push({role:"system",content:s});for(let c of n){let w=c.role==="user"?"user":"assistant",r=[];if(Array.isArray(c.parts)){for(let k of c.parts)if(k.text)r.push({type:"text",text:k.text});else if(k.inlineData&&f){let E=k.inlineData.mimeType,O=k.inlineData.data;E.startsWith("image/")&&r.push({type:"image_url",image_url:{url:`data:${E};base64,${O}`}})}}else{let k=c.text||"";k&&r.push({type:"text",text:k})}g.push({role:w,content:r.length===1&&r[0].type==="text"?r[0].text:r})}let u=$e("9router",t,o)||$e("9Router",t,o),b=u!==null?u:{Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:g,stream:!0,stream_options:{include_usage:!0},temperature:m};b&&(i.reasoning_effort=b);let l=process.env["9ROUTER_URL"]||process.env.NINEROUTER_URL||"http://127.0.0.1:20128/v1/chat/completions",_={"Content-Type":"application/json"},C=e&&e!=="LOCAL"?e:process.env["9ROUTER_API_KEY"]||"dummy-key";_.Authorization=`Bearer ${C}`;let x=await tt(l,{method:"POST",headers:_,body:JSON.stringify(i),signal:a});if(!x.ok){let c=await x.json().catch(()=>({}));throw new Error(`9router Error (${x.status}): ${c.error?.message||x.statusText}`)}let R=x.body.getReader(),N=new TextDecoder,D="",S=[],M=null,$=Date.now(),p=!1;for(;;){let{done:c,value:w}=await R.read();if(c){p&&(S.length>0||M)&&(yield{candidates:S.length>0?[{content:{parts:S}}]:[],usageMetadata:M});break}D+=N.decode(w,{stream:!0});let r=D.split(`
606
- `);D=r.pop();for(let k of r){let E=k.trim();if(!E||!E.startsWith("data: "))continue;let O=!1;if(E==="data: [DONE]")O=!0;else try{let U=JSON.parse(E.substring(6)),P=U.choices?.[0]?.delta,I=U.usage;if(U.choices?.[0]?.finish_reason&&(O=!0),I&&(M={totalTokenCount:I.total_tokens||(I.prompt_tokens||0)+(I.completion_tokens||0),promptTokenCount:I.prompt_tokens||0,candidatesTokenCount:I.completion_tokens||0,cachedContentTokenCount:I.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:I.completion_tokens_details?.reasoning_tokens||I.reasoning_tokens||0},p=!0),P){let Z=P.reasoning_content||P.reasoning||null;!Z&&Array.isArray(P.reasoning_details)&&P.reasoning_details.length>0&&(Z=P.reasoning_details.map(ke=>ke.text||"").filter(Boolean).join("")),Z&&(S.push({text:Z,thought:!0}),p=!0),P.content&&(S.push({text:P.content}),p=!0)}}catch{}if((O||Date.now()-$>=150)&&p&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:M},S=[],$=Date.now(),p=!1),O)break}Date.now()-$>=150&&p&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:M},S=[],$=Date.now(),p=!1)}};var Qo=async function*(e,t,n,s,o,d,f,a,m=1){let g=[];s&&g.push({role:"system",content:s});for(let c of n){let w=c.role==="user"?"user":"assistant",r=[];if(Array.isArray(c.parts)){for(let k of c.parts)if(k.text)r.push({type:"text",text:k.text});else if(k.inlineData&&f){let E=k.inlineData.mimeType,O=k.inlineData.data;E.startsWith("image/")&&r.push({type:"image_url",image_url:{url:`data:${E};base64,${O}`}})}}else{let k=c.text||"";k&&r.push({type:"text",text:k})}g.push({role:w,content:r.length===1&&r[0].type==="text"?r[0].text:r})}let u=$e("ExpLabs",t,o),b=u!==null?u:{Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:g,stream:!0,stream_options:{include_usage:!0},temperature:m};b&&(i.reasoning_effort=b);let l=process.env.EXPLABS_URL||process.env.EXPERIENTIALLABS_URL||"https://api.experientiallabs.ai/v1/chat/completions",_={"Content-Type":"application/json"},C=e||process.env.EXPLABS_API_KEY||process.env.EXPERIENTIALLABS_API_KEY||"";_.Authorization=`Bearer ${C}`;let x=await tt(l,{method:"POST",headers:_,body:JSON.stringify(i),signal:a});if(!x.ok){let c=await x.json().catch(()=>({}));throw new Error(`Experiential Labs Error (${x.status}): ${c.error?.message||c.message||x.statusText}`)}let R=x.body.getReader(),N=new TextDecoder,D="",S=[],M=null,$=Date.now(),p=!1;for(;;){let{done:c,value:w}=await R.read();if(c){p&&(S.length>0||M)&&(yield{candidates:S.length>0?[{content:{parts:S}}]:[],usageMetadata:M});break}D+=N.decode(w,{stream:!0});let r=D.split(`
607
- `);D=r.pop();for(let k of r){let E=k.trim();if(!E||!E.startsWith("data: "))continue;let O=!1;if(E==="data: [DONE]")O=!0;else try{let U=JSON.parse(E.substring(6)),P=U.choices?.[0]?.delta,I=U.usage;if(I&&(M={totalTokenCount:I.total_tokens||(I.prompt_tokens||0)+(I.completion_tokens||0),promptTokenCount:I.prompt_tokens||0,candidatesTokenCount:I.completion_tokens||0,cachedContentTokenCount:I.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:I.completion_tokens_details?.reasoning_tokens||I.reasoning_tokens||0},p=!0),P){let Z=P.reasoning_content||P.reasoning||null;!Z&&Array.isArray(P.reasoning_details)&&P.reasoning_details.length>0&&(Z=P.reasoning_details.map(ke=>ke.text||"").filter(Boolean).join("")),Z&&(S.push({text:Z,thought:!0}),p=!0),P.content&&(S.push({text:P.content}),p=!0)}}catch{}if((O||Date.now()-$>=150)&&p&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:M},S=[],$=Date.now(),p=!1),O)break}Date.now()-$>=150&&p&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:M},S=[],$=Date.now(),p=!1)}};var Us=async function*(e,t,n,s,o,d,f,a,m=1){let g=[];s&&g.push({role:"system",content:s});for(let c of n){let w=c.role==="user"?"user":"assistant",r=[];if(Array.isArray(c.parts)){for(let k of c.parts)if(k.text)r.push({type:"text",text:k.text});else if(k.inlineData&&f){let E=k.inlineData.mimeType,O=k.inlineData.data;E.startsWith("image/")&&r.push({type:"image_url",image_url:{url:`data:${E};base64,${O}`}})}}else{let k=c.text||"";k&&r.push({type:"text",text:k})}g.push({role:w,content:r.length===1&&r[0].type==="text"?r[0].text:r})}let u=$e("TokenHarbor",t,o),b=u!==null?u:{Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:g,stream:!0,stream_options:{include_usage:!0},temperature:m};b&&(i.reasoning_effort=b);let l=process.env.TOKENHARBOR_URL||process.env.TOKEN_HARBOR_URL||"https://tokenharbor.ai/v1/chat/completions",_={"Content-Type":"application/json","X-Title":"Flux-Flow","User-Agent":"Flux-Flow","HTTP-Referer":"https://fluxflow-cli.onrender.com/"},C=e||process.env.TOKENHARBOR_API_KEY||process.env.TOKEN_HARBOR_API_KEY||"";_.Authorization=`Bearer ${C}`;let x=await tt(l,{method:"POST",headers:_,body:JSON.stringify(i),signal:a});if(!x.ok){let c=await x.json().catch(()=>({}));throw new Error(`Token Harbor Error (${x.status}): ${c.error?.message||c.message||x.statusText}`)}let R=x.body.getReader(),N=new TextDecoder,D="",S=[],M=null,$=Date.now(),p=!1;for(;;){let{done:c,value:w}=await R.read();if(c){p&&(S.length>0||M)&&(yield{candidates:S.length>0?[{content:{parts:S}}]:[],usageMetadata:M});break}D+=N.decode(w,{stream:!0});let r=D.split(`
608
- `);D=r.pop();for(let k of r){let E=k.trim();if(!E||!E.startsWith("data: "))continue;let O=!1;if(E==="data: [DONE]")O=!0;else try{let U=JSON.parse(E.substring(6)),P=U.choices?.[0]?.delta,I=U.usage;if(I&&(M={totalTokenCount:I.total_tokens||(I.prompt_tokens||0)+(I.completion_tokens||0),promptTokenCount:I.prompt_tokens||0,candidatesTokenCount:I.completion_tokens||0,cachedContentTokenCount:I.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:I.completion_tokens_details?.reasoning_tokens||I.reasoning_tokens||0},p=!0),P){let Z=P.reasoning_content||P.reasoning||null;!Z&&Array.isArray(P.reasoning_details)&&P.reasoning_details.length>0&&(Z=P.reasoning_details.map(ke=>ke.text||"").filter(Boolean).join("")),Z&&(S.push({text:Z,thought:!0}),p=!0),P.content&&(S.push({text:P.content}),p=!0)}}catch{}if((O||Date.now()-$>=150)&&p&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:M},S=[],$=Date.now(),p=!1),O)break}Date.now()-$>=150&&p&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:M},S=[],$=Date.now(),p=!1)}};var Ws=async function*(e,t,n,s,o,d,f,a,m=1){let g=[];s&&g.push({role:"system",content:s});for(let c of n){let w=c.role==="user"?"user":"assistant",r=[];if(Array.isArray(c.parts)){for(let k of c.parts)if(k.text)r.push({type:"text",text:k.text});else if(k.inlineData&&f){let E=k.inlineData.mimeType,O=k.inlineData.data;E.startsWith("image/")&&r.push({type:"image_url",image_url:{url:`data:${E};base64,${O}`}})}}else{let k=c.text||"";k&&r.push({type:"text",text:k})}g.push({role:w,content:r.length===1&&r[0].type==="text"?r[0].text:r})}let u=$e("APInex",t,o),b=u!==null?u:{Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:g,stream:!0,stream_options:{include_usage:!0},temperature:m};b&&(i.reasoning_effort=b);let l=process.env.APINEX_URL||"https://api.apinex.bond/v1/chat/completions",_={"Content-Type":"application/json","X-Title":"Flux-Flow","User-Agent":"Flux-Flow","HTTP-Referer":"https://fluxflow-cli.onrender.com/"},C=e||process.env.APINEX_API_KEY||"";_.Authorization=`Bearer ${C}`;let x=await tt(l,{method:"POST",headers:_,body:JSON.stringify(i),signal:a});if(!x.ok){let c=await x.json().catch(()=>({}));throw new Error(`APInex Error (${x.status}): ${c.error?.message||c.message||x.statusText}`)}let R=x.body.getReader(),N=new TextDecoder,D="",S=[],M=null,$=Date.now(),p=!1;for(;;){let{done:c,value:w}=await R.read();if(c){p&&(S.length>0||M)&&(yield{candidates:S.length>0?[{content:{parts:S}}]:[],usageMetadata:M});break}D+=N.decode(w,{stream:!0});let r=D.split(`
609
- `);D=r.pop();for(let k of r){let E=k.trim();if(!E||!E.startsWith("data: "))continue;let O=!1;if(E==="data: [DONE]")O=!0;else try{let U=JSON.parse(E.substring(6)),P=U.choices?.[0]?.delta,I=U.usage;if(I&&(M={totalTokenCount:I.total_tokens||(I.prompt_tokens||0)+(I.completion_tokens||0),promptTokenCount:I.prompt_tokens||0,candidatesTokenCount:I.completion_tokens||0,cachedContentTokenCount:I.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:I.completion_tokens_details?.reasoning_tokens||I.reasoning_tokens||0},p=!0),P){let Z=P.reasoning_content||P.reasoning||null;!Z&&Array.isArray(P.reasoning_details)&&P.reasoning_details.length>0&&(Z=P.reasoning_details.map(ke=>ke.text||"").filter(Boolean).join("")),Z&&(S.push({text:Z,thought:!0}),p=!0),P.content&&(S.push({text:P.content}),p=!0)}}catch{}if((O||Date.now()-$>=150)&&p&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:M},S=[],$=Date.now(),p=!1),O)break}Date.now()-$>=150&&p&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:M},S=[],$=Date.now(),p=!1)}};var ha=/```[\s\S]*?```/g,pa=/```[\s\S]*$/g,ya=/`[^`]+`/g,xa=/^\|.*\|$/gm,ba=/^[^\w]+|[^\w]+$/g,ka=/[^a-z0-9]/gi,go=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,wa=/\[\s*(?:tool:functions\.|agent:generalist\.)([a-z0-9_]+)\s*\(/gi,Ta=/(?:path|targetFile|TargetFile|directory|keyword|id|taskId|title|task)\s*=\s*\\?["']?([^\\"' \),]+)/,Pn=/["']/g,Sr=/\\/g,Sa=/<\|channel>thought/gi,_a=/<channel\|>/gi,Ea=e=>typeof e!="string"?e:e.replace(Sa,"<think>").replace(_a,"</think>"),Bd=/^\s*(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\]|$)/i,Aa=(e,t)=>{let n=!1;for(let s=0;s<t;s++)e[s]==="`"&&(n=!n);return n},Ca=e=>{let t=/(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\])/gi,n;for(;(n=t.exec(e))!==null;)if(!Aa(e,n.index))return{index:n.index,length:n[0].length};return{index:-1,length:0}},Hs=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=Ca(s);if(o.index!==-1){let d=n+o.index+o.length;return{fullBlock:e.substring(0,d),innerContent:s.substring(0,o.index),remainingText:e.substring(d)}}return{fullBlock:e,innerContent:s,remainingText:""}},Kt=e=>{if(!e||typeof e!="string")return e;let t=Hs(e);return t?t.remainingText.trimStart():e};var Mr=/`[^`]*`/g,Ir=/`[^`]*$/,_r=/<\|\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,Ra=/"([^"]+)"\s*:\s*(?:"([^"]*)"|(\d+)|true|false|null)/g,Er=/<\|\s*tool_calls_section_begin\s*\|>/gi,Ar=/<\|\s*tool_calls_section_end\s*\|>/gi,va=/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi;var Cr=e=>!e||typeof e!="string"?e:e.replace(/(```[\s\S]*?```|`[^`]*`)|(<(?:\w+)(?:[^>]*)>\r?\n?|\r?\n?<\/\w+(?:[^>]*)>)/gi,(t,n)=>n||""),js=null,Zo={},$n={key:null,value:null},Vt=e=>e&&e.replace(/(?:(\x1b\[\d+m))?([✔✘✖🔍📖→➕↻↷•🛇])(?:(\x1b\[\d+m))?\s*\b(Clicked|Dragged|Scrolled|Typed|Pressed Key|Recaptured Screen|Created|Read Skill|Read Documentation|Searched Documentation|Read|Edited|Viewed|Processed|Auto-Read|Skipped|List|Generated|Written|Searched|AI Search|Get Map|Write Canceled|Resolved Sub-Agent Query|Edit Canceled|Write Cancelled|Edit Denied|Visited|Updated|Reviewed|Delegated|Background|Checked|Indexed|Analyzed|Browsed|Elevating SubAgent|Checking SubAgent Work|Started Generalist|Called Generalist|Steered|Unsupported Modality|Awaiting|Cancelled|Aligning Moon Phase|Contemplating Existence|Staring At Void|Rollback Point Checked|Emergency Rollback Failed|Emergency Rollback|Delaying Professionally|Negotiating With Electrons|Touching Grass (virtually)|Panicking Softly|Rethinking Career Choices|Loading Cat Videos|Giving Up Entirely|Summoning Braincell #2|Pretending To Be Busy|Waiting For Motivation DLC|Rotating Internal Screaming|Downloading More RAM|Feeding The Hamsters|Gaslighting Scheduler|Performing Dramatic Pause|Buffering Social Energy|Calculating Regret|Reading Terms And Conditions|Becoming Sentient Briefly|Execution Error|Loop Detected|Contacting Ancestors)\b/ig,(t,n,s,o,d)=>`${n||""}${s}${o||""} \x1B[95m${d}\x1B[0m`),Ma=async(e,t=8,n=1e3,s=8e3,o=null)=>{let d=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."||(d++,d>=t))throw f;let a=Math.min(n*Math.pow(2,d-1),s);await new Promise((m,g)=>{let u=setTimeout(m,a);o&&o.addEventListener("abort",()=>{clearTimeout(u),g(new DOMException("The user aborted a request.","AbortError"))})})}}},kt=!1;var Ia=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,d,f)=>{let a=o.fullText||o.text||"";if(o.role==="user"&&d<f.length-1)if(a.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")){let m=a.indexOf("**CONTEXT SUMMARY OF PREVIOUS TURNS");if(m!==-1){let u=a.substring(0,m).lastIndexOf("[SYSTEM METADATA]");u!==-1?a=a.substring(u).trim():a=a.substring(m).trim()}}else{let m=a.lastIndexOf("[USER]"),g=a.lastIndexOf("[USER PROMPT]");m!==-1?a=a.substring(m+6).trim():g!==-1&&(a=a.substring(g).trim())}return{...o,text:a}}),n=[],s=0;for(;s<t.length;){let o=t[s];if(o.role==="user")n.push(o),s++;else{let d=[];for(;s<t.length&&t[s].role!=="user";)d.push(t[s]),s++;let f=[],a=[],m=!1,g=()=>{f.length>0&&(n.push({role:"agent",text:"combined"}),f=[]),a.length>0&&(n.push({role:"system",text:"combined"}),a=[]),m=!1};d.forEach(u=>{let h=u.role==="system"&&(u.text?.startsWith("[TOOL RESULT]")||u.text?.startsWith("SUCCESS:")||u.text?.startsWith("ERROR:")||u.fullText?.startsWith("[TOOL RESULT]")||u.fullText?.startsWith("SUCCESS:")||u.fullText?.startsWith("ERROR:")),b=u.fullText||u.text||"",i=b.trim();if(!(!i&&!u.binaryPart)){if(h)a.push(i);else if(u.role==="agent"){!m&&a.length>0&&g();let l=b.endsWith(`
610
- `),_=i.toLowerCase().includes("tool:functions.")||i.toLowerCase().includes("agent:generalist.");f.push(i),_&&l?m=!0:m=!1}}}),g()}}return n.length},Da=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),Ud=()=>{kt=!0},Wd=()=>kt,Gs={write_file:"Writing",update_file:"Editing",read_folder:"Reading",view_file:"Reading",exec_command:"Executing Command",web_search:"Searching",web_scrape:"Reading",memory:"Updating Memory",search_keyword:"Searching",file_map:"Generating Map",ask:"User Input",write_pdf:"Creating",write_docx:"Creating",generate_image:"Generating",todo:"Planning",Todo:"Planning",goal:"Planning",Goal:"Planning",invoke_sync:"Sub-Agent Working",invoke:"Starting Agent",get_progress:"Checking Progress",cancel:"Cancelling",await:"Waiting",EmergencyRollback:"Don't Panic. Lookin' into it",answer:"Answering Sub-Agent",Answer:"Answering Sub-Agent",steer:"Steering Sub-Agent",Steer:"Steering Sub-Agent",Click:"Clicking",click:"Clicking",Drag:"Dragging",drag:"Dragging",Scroll:"Scrolling",scroll:"Scrolling",KeyboardTyping:"Typing",keyboard_typing:"Typing",KeyPress:"Pressing Key",key_press:"Pressing Key",RecaptureScreen:"Recapturing Screen",recapture_screen:"Recapturing Screen"},Nn=(e,t)=>{try{let n=Q(t),s=e.toLowerCase().replace(/_/g,"");if(s==="invokesync"||s==="invoke")return n.title||(n.task?n.task.substring(0,30):null);if(s==="getprogress"||s==="cancel"||s==="steer"||s==="steersubagent")return n.id||n.taskId;let o=n.path||n.targetFile||n.TargetFile||n.directory;return o?J.basename(o.replace(/["']/g,"").replace(/\\/g,"/")):null}catch{return null}},Vs=e=>e?new vr({apiKey:e}):js,Hd=async(e,t,n,s,o={})=>{let{onStatus:a,onMemoryUpdated:m,onBackgroundIncrement:g}=o,{profile:u,thinkingLevel:h,mode:b,janitorModel:i,chatId:l,systemSettings:_,sessionStats:C,aiProvider:x="Google",apiKey:R}=e,N=process.env.NVIDIA_BASE_URL||x==="Ollama"||x==="InferX"||x==="SenseNova"||x==="AIHubMix"||x==="Poolside"||x==="9router"||x==="ExpLabs"||x==="ExperientialLabs"?!1:_?.memory!==!1,S=_t(On,[]).map(v=>`- [${v.id}]: ${v.memory}`).join(`
611
- `),M=s.slice(0,-1).filter(v=>v.text&&!v.text.includes("[TOOL RESULT]")&&!v.text.includes("OBSERVATION:")&&!v.text.startsWith("[TERMINAL_RECORD]")&&!v.isTerminalRecord&&!v.isMeta&&!v.isLogo&&!String(v.id).startsWith("welcome")&&!String(v.id).startsWith("logo")).slice(-14).map(v=>{let G=Kt(Da(v.text)).replace(/\[tool:functions\..*?\]/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[METADATA \(PRIORITY: DYNAMIC\)\] Time: ([^|\n]+)/g,(Ye,Ge)=>`[METADATA (PRIORITY: DYNAMIC)] Time: ${Ge.replace(/:\d{2}/g,"")}`).replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[TOOL RESULTS\]/g,"").replace(/\[tool results\]/g,"").replace(/\r?\n\r?\n/g,`
574
+ `),x=i=>`${a}${i}${h}`;return`${m[0]}
575
+ ${m[1]} ${d}Selected Provider: ${t}${h}
576
+ ${m[2]}
577
+ ${m[3]} ${d}FluxFlow ${x("v"+e)}${h}
578
+ ${m[4]}
579
+ ${m[5]} ${f}See /help for additional commands.${h}
580
+ ${m[6]} ${x(s)}
581
+ ${m[7]}
582
+ `};import{WebSocket as Bo}from"ws";var Bt=null,Kn=!1,ca="ws://localhost:56832",Ds=[],Yn=null,Os=null,yr="2.0.0",tc=e=>{yr=e,xr()},Ls=e=>{Os=e},xr=()=>{if(Bt||Kn)return;Kn=!0;let e=new Bo(ca);e.on("open",()=>{for(Bt=e,Kn=!1,Bt.send(JSON.stringify({command:"version",version:yr,pid:process.pid,ppid:process.ppid}));Ds.length>0;)Bt.send(JSON.stringify(Ds.shift()))}),e.on("message",t=>{try{let n=JSON.parse(t.toString());n.command==="contextResponse"&&Yn?(Yn(n.data),Yn=null):n.command==="securityResponse"&&Os&&Os(n.result)}catch{}}),e.on("error",()=>{Kn=!1,Bt=null}),e.on("close",()=>{Kn=!1,Bt=null})},Uo=e=>{Bt&&Bt.readyState===Bo.OPEN?Bt.send(JSON.stringify(e)):(Ds.push(e),Kn||xr())},Wo=()=>Bt!==null&&Bt.readyState===Bo.OPEN,nc=e=>{Uo({command:"status",status:e})},Ln=()=>new Promise(e=>{if(!Bt||Bt.readyState!==Bo.OPEN){e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]});return}Yn=e,Bt.send(JSON.stringify({command:"requestContext"})),setTimeout(()=>{Yn===e&&(e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]}),Yn=null)},1e3)}),br=e=>{Uo({command:"open",filePath:e})},Ps=(e,t,n)=>{Uo({command:"showDiff",filePath:e,originalContent:t,modifiedContent:n})},kr=(e,t)=>{Uo({command:"closeDiff",filePath:e,result:t})};import wr from"path";import da from"fs";var fa=e=>{try{return da.readdirSync(e,{withFileTypes:!0})}catch{return[]}},$s=(e,t,n=1,s=fa,o=[],d=null)=>{let f=d||s(e),a=" ".repeat(n-1);if(f.length>100)return`${a}${wr.basename(e)}/ (>100 files)
583
+ `;let h="",g=o,u=f.filter(l=>!g.includes(l.name)&&!l.name.startsWith(".")),m=f.filter(l=>g.includes(l.name)||l.name.startsWith(".")).map(l=>l.name).sort();m.length>0&&(h+=`${a}[ignored: ${m.map(l=>l+"/").join(", ")}]
584
+ `);let x=u.filter(l=>l.isDirectory()).sort((l,T)=>l.name.localeCompare(T.name)),i=u.filter(l=>!l.isDirectory()).map(l=>l.name).sort();for(let l of x){let T=wr.join(e,l.name);if(n>t)h+=`${a}${l.name}/ (max depth)
585
+ `;else{let R=s(T);R.length>80?h+=`${a}${l.name}/ (>80 files)
586
+ `:(h+=`${a}${l.name}/
587
+ `,h+=$s(T,t,n+1,s,o,R))}}return i.length>0&&(h+=`${a}${i.join("; ")}
588
+ `),h};import Ns from"path";import ua from"fs";var ga=e=>{try{return ua.readdirSync(e,{withFileTypes:!0})}catch{return[]}},Fs=(e,t,n="",s=1,o=ga,d=[])=>{let f=o(e),a=Ns.sep;if(f.length>100)return`${n}\u2514\u2500\u2500 ${Ns.basename(e)}${a} ...100+ files...
589
+ `;let h="",g=d,u=f.filter(i=>!g.includes(i.name)&&!i.name.startsWith(".")),m=f.filter(i=>g.includes(i.name)||i.name.startsWith(".")).map(i=>i.name).sort();u.sort((i,l)=>i.isDirectory()&&!l.isDirectory()?-1:!i.isDirectory()&&l.isDirectory()?1:i.name.localeCompare(l.name));let x=[...u.map(i=>({name:i.name,isDir:i.isDirectory()})),...m.map(i=>({name:i,isDir:!0,isCollapsed:!0}))];return x.forEach((i,l)=>{let T=l===x.length-1,R=Ns.join(e,i.name),b=T?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",v=n+(T?" ":"\u2502 ");if(i.isCollapsed){h+=`${n}${b}${i.name}${a}...
590
+ `;return}i.isDir?s>t?h+=`${n}${b}${i.name}${a} ...depth exceeded...
591
+ `:o(R).length>80?h+=`${n}${b}${i.name}${a} ...80+ files...
592
+ `:(h+=`${n}${b}${i.name}${a}
593
+ `,h+=Fs(R,t,v,s+1,o,d)):h+=`${n}${b}${i.name}
594
+ `}),h};import"@google/genai";var tt=async(e,t,n=5,s=1e3)=>{let o=t?.signal;for(let f=0;f<n;f++){if(o?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{let a=await fetch(e,t);if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),a.ok||a.status!==429&&a.status<500)return a}catch(a){if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),a.name==="AbortError"||o?.aborted||f===n-1)throw a}o?await new Promise((a,h)=>{let g=setTimeout(()=>{o.removeEventListener("abort",u),a()},Math.min(24e3,s*Math.pow(2,f))),u=()=>{clearTimeout(g),h(new DOMException("The user aborted a request.","AbortError"))};o.addEventListener("abort",u)}):await new Promise(a=>setTimeout(a,Math.min(24e3,s*Math.pow(2,f))))}if(o?.aborted)throw new DOMException("The user aborted a request.","AbortError");let d=await fetch(e,t);return typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),d};async function Ho(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 pn=e=>typeof e!="string"?e:e.replace(/<\|channel>thought/gi,"<think>").replace(/<channel\|>/gi,"</think>");var Go=async function*(e,t,n,s,o,d,f,a,h=1){let g=[];s&&g.push({role:"system",content:s});for(let I of n){let $=I.role==="user"?"user":"assistant",p=[];if(Array.isArray(I.parts)){for(let c of I.parts)if(c.text)p.push({type:"text",text:c.text});else if((c.inlineData||c.inline_data)&&f){let w=c.inlineData||c.inline_data,r=w.mimeType||w.mime_type||"image/jpeg",k=w.data;r.startsWith("image/")&&p.push({type:"image_url",image_url:{url:`data:${r};base64,${k}`}})}}else{let c=I.text||"";c&&p.push({type:"text",text:c})}g.push({role:$,content:p.length===1&&p[0].type==="text"?p[0].text:p})}let u={model:t,messages:g,stream:!0,stream_options:{include_usage:!0},temperature:h},m=Oe("DeepSeek",t,o),i=m!==null?m:o!=="Fast"?{Low:"high",Medium:"high",Standard:"high",High:"max",xHigh:"max"}[o]||"high":null;i&&i!=="disabled"&&i!=="none"&&i!=="false"&&i!==!1?(u.reasoning_effort=i,u.extra_body={thinking:{type:"enabled"}}):u.extra_body={thinking:{type:"disabled"}};let l=await tt("https://api.deepseek.com/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(u),signal:a});if(!l.ok){let I=await l.json().catch(()=>({}));throw new Error(`DeepSeek Error (${l.status}): ${I.error?.message||l.statusText}`)}let T=l.body.getReader(),R=new TextDecoder,b="",v=[],N=null,M=Date.now(),S=!1;for(;;){let{done:I,value:$}=await T.read();if(I){S&&(v.length>0||N)&&(yield{candidates:v.length>0?[{content:{parts:v}}]:[],usageMetadata:N});break}b+=R.decode($,{stream:!0});let p=b.split(`
595
+ `);b=p.pop();for(let c of p){let w=c.trim();if(!w||!w.startsWith("data: "))continue;let r=!1;if(w==="data: [DONE]")r=!0;else try{let k=JSON.parse(w.substring(6)),E=k.choices?.[0]?.delta,O=k.usage;if(k.choices?.[0]?.finish_reason&&(r=!0),O&&(N={totalTokenCount:O.total_tokens||O.prompt_tokens+O.completion_tokens,promptTokenCount:O.prompt_tokens||0,candidatesTokenCount:O.completion_tokens||0,cachedContentTokenCount:O.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:O.completion_tokens_details?.reasoning_tokens||0},S=!0),E){let U=E.reasoning_content||null;U&&(v.push({text:U,thought:!0}),S=!0),E.content&&(v.push({text:E.content}),S=!0)}}catch{}if((r||Date.now()-M>=150)&&S&&(yield{candidates:v.length>0?[{content:{parts:[...v]}}]:[],usageMetadata:N},v=[],M=Date.now(),S=!1),r)break}Date.now()-M>=150&&S&&(yield{candidates:v.length>0?[{content:{parts:[...v]}}]:[],usageMetadata:N},v=[],M=Date.now(),S=!1)}};var jo=async function*(e,t,n,s,o,d,f,a,h=1,g=null){let u=[];s&&u.push({role:"system",content:s});for(let c of n){let w=c.role==="user"?"user":"assistant",r=[];if(Array.isArray(c.parts)){for(let k of c.parts)if(k.text)r.push({type:"text",text:k.text});else if(k.inlineData&&f){let E=k.inlineData.mimeType,O=k.inlineData.data;E.startsWith("image/")&&r.push({type:"image_url",image_url:`data:${E};base64,${O}`})}}else{let k=c.text||"";k&&r.push({type:"text",text:k})}r.length>0&&u.push({role:w,content:r.length===1&&r[0].type==="text"?r[0].text:r})}let m={Fast:"none",Low:"none",Medium:"high",Standard:"high",High:"high",xHigh:"high"},x=`${e.slice(-5)}${g||""}${o}${t}`,i=await Ho(x),l={model:t,messages:u,stream:!0,temperature:h,prompt_cache_key:i},T=Oe("Mistral",t,o);T!==null?T&&T!=="none"&&T!=="disabled"&&T!==!1&&(l.reasoning_effort=T):o&&o!=="Fast"&&Vn(t)&&(l.reasoning_effort=m[o]||"high");let R=await tt("https://api.mistral.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(l),signal:a});if(!R.ok){let c=await R.text().catch(()=>""),w=R.statusText;try{let r=JSON.parse(c);w=r.error?.message||r.message||JSON.stringify(r.detail||r)}catch{c&&(w=c)}throw new Error(`Mistral Error (${R.status}): ${JSON.stringify(w)}`)}let b=R.body.getReader(),v=new TextDecoder,N="",M=[],S=null,I=Date.now(),$=!1,p=c=>c?typeof c=="string"?pn(c):Array.isArray(c)?c.map(p).filter(Boolean).join(""):typeof c=="object"&&c!==null?typeof c.text=="string"?pn(c.text):typeof c.content=="string"?pn(c.content):typeof c.thinking=="string"?pn(c.thinking):typeof c.reasoning_content=="string"?pn(c.reasoning_content):typeof c.reasoning=="string"?pn(c.reasoning):typeof c.value=="string"?pn(c.value):c.text?p(c.text):c.content?p(c.content):c.thinking?p(c.thinking):c.reasoning_content?p(c.reasoning_content):c.reasoning?p(c.reasoning):c.value?p(c.value):"":pn(String(c)):"";for(;;){let{done:c,value:w}=await b.read();if(c){$&&(M.length>0||S)&&(yield{candidates:M.length>0?[{content:{parts:M}}]:[],usageMetadata:S});break}N+=v.decode(w,{stream:!0});let r=N.split(`
596
+ `);N=r.pop();for(let k of r){let E=k.trim();if(!E||!E.startsWith("data: "))continue;let O=!1;if(E==="data: [DONE]")O=!0;else try{let U=JSON.parse(E.substring(6)),P=U.choices?.[0]?.delta,D=U.usage;if(U.choices?.[0]?.finish_reason&&(O=!0),D&&(S={totalTokenCount:D.total_tokens||(D.prompt_tokens||0)+(D.completion_tokens||0),promptTokenCount:D.prompt_tokens||0,candidatesTokenCount:D.completion_tokens||0,cachedContentTokenCount:D.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:D.completion_tokens_details?.reasoning_tokens||0},$=!0),P){let ee=P.thinking||P.reasoning_content||P.reasoning,pe=p(ee);pe&&(M.push({text:pe,thought:!0}),$=!0);let B=P.content||(!P.thinking&&!P.reasoning_content&&!P.reasoning?P.text:null);if(B)if(Array.isArray(B))for(let A of B)if(typeof A=="object"&&A!==null){let Se=A.type==="thinking"||A.type==="reasoning"||!!A.thought,X=p(A);X&&(M.push({text:X,...Se?{thought:!0}:{}}),$=!0)}else{let Se=p(A);Se&&(M.push({text:Se}),$=!0)}else if(typeof B=="object"&&B!==null){let A=B.type==="thinking"||B.type==="reasoning"||!!B.thought,Se=p(B);Se&&(M.push({text:Se,...A?{thought:!0}:{}}),$=!0)}else{let A=p(B);A&&(M.push({text:A}),$=!0)}}}catch{}if((O||Date.now()-I>=150)&&$&&(yield{candidates:M.length>0?[{content:{parts:[...M]}}]:[],usageMetadata:S},M=[],I=Date.now(),$=!1),O)break}Date.now()-I>=150&&$&&(yield{candidates:M.length>0?[{content:{parts:[...M]}}]:[],usageMetadata:S},M=[],I=Date.now(),$=!1)}};var Vo=async function*(e,t,n,s,o,d,f=!1,a,h=1){let g=[];s&&g.push({role:"system",content:s}),n.forEach(X=>{let C=X.role==="model"?"assistant":"user",G=[];Array.isArray(X.parts)&&X.parts.forEach(te=>{if(te.text)G.push({type:"text",text:te.text});else if(te.inlineData&&f){let Y=te.inlineData.mimeType,Xe=te.inlineData.data;Y.startsWith("image/")&&dt(t)&&G.push({type:"image_url",image_url:{url:`data:${Y};base64,${Xe}`}})}}),g.push({role:C,content:G.length===1&&G[0].type==="text"?G[0].text:G})});let u=Oe("NVIDIA",t,o),x=u!==null?u:{Fast:"Fast",Low:"Fast",Medium:"Standard",Standard:"Standard",High:"High",xHigh:"High"}[o]||"High",i=x!=="Fast"&&x!=="none"&&x!=="disabled"&&x!==!1,l=t.includes("kimi"),T=t.includes("gemma"),R=t.includes("deepseek"),b=t.includes("glm"),v=t.includes("mistral"),N=t.includes("minimax"),M=t.includes("gpt"),S=t.includes("qwen"),I=t.includes("nemotron"),$=t.includes("llama-3"),p=t.includes("seed"),c=t.includes("poolside"),w=t.includes("thinkingmachines")||t.includes("muse"),r=$,k=null,E={Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},O={Fast:"64",Low:"64",Medium:"4096",Standard:"4096",High:"16384",xHigh:"16384"},U={Fast:"none",Low:"minimal",Medium:"medium",Standard:"medium",High:"max",xHigh:"max"},P=N||R||c||w?16384:32768;P=process.env.NVIDIA_BASE_URL?1024:P,P=k?1024:P;let D={model:t,messages:g,max_tokens:P,stream:!0,stream_options:{include_usage:!0},temperature:h,...M&&{thinking:E[o]||"high"}};if(!(process.env.NVIDIA_BASE_URL||r||k))if(l)D.chat_template_kwargs={thinking:i};else if(T)D.chat_template_kwargs={enable_thinking:i};else if(R)if(i){let X=x==="High"?"max":"high";D.chat_template_kwargs={thinking:!0,reasoning_effort:X}}else D.chat_template_kwargs={thinking:!1};else b?D.chat_template_kwargs={enable_thinking:i,clear_thinking:!i}:v?D.reasoning_effort=i?"high":"none":N&&t.includes("minimax-m3")?D.chat_template_kwargs={thinking_mode:i?"enabled":"disabled"}:S?D.chat_template_kwargs={enable_thinking:i}:I?x==="High"?D.chat_template_kwargs={enable_thinking:!0}:x==="Standard"?D.chat_template_kwargs={enable_thinking:!0,medium_effort:!0}:D.chat_template_kwargs={enable_thinking:!1}:p?i&&(D.extra_body={thinking_budget:parseInt(O[x]??"4096")}):c?D.chat_template_kwargs={enable_thinking:i}:w&&(D.reasoning_effort=U[x]||"medium");let ee=0,pe=6,B=!1,A=process.env.NVIDIA_BASE_URL||"https://integrate.api.nvidia.com/v1/chat/completions",Se=process.env.NVIDIA_API_KEY&&process.env.NVIDIA_BASE_URL?process.env.NVIDIA_API_KEY:e;for(A.endsWith("/chat/completions")||(A=A.replace(/\/+$/,"")+"/chat/completions");ee<pe;){ee++;try{let X=await tt(A,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Se}`},body:JSON.stringify(D),signal:a});if(!X.ok){let ft=await X.text().catch(()=>""),Qe=X.statusText;try{let At=JSON.parse(ft);Qe=At.error?.message||At.message||JSON.stringify(At.detail||At)}catch{ft&&(Qe=ft)}let pt=new Error(`NVIDIA API Error (${X.status}): ${Qe}`);throw pt.status=X.status,pt}let C=X.body.getReader(),G=new TextDecoder,te="",Y=[],Xe=null,Ye=Date.now(),Ge=!1;for(;;){let{done:ft,value:Qe}=await C.read();if(ft){Ge&&(Y.length>0||Xe)&&(yield{candidates:Y.length>0?[{content:{parts:Y}}]:[],usageMetadata:Xe},B=!0);break}te+=G.decode(Qe,{stream:!0});let pt=te.split(`
597
+ `);te=pt.pop();let At=!1;for(let xn of pt){let Yt=xn.trim();if(Yt){if(Yt==="data: [DONE]"){At=!0;break}if(Yt.startsWith("data: ")){let ct;try{ct=JSON.parse(Yt.substring(6))}catch{continue}if(ct.error)throw new Error(`NVIDIA Stream Error: ${ct.error.message||JSON.stringify(ct.error)}`);try{let fe=ct.usage;fe&&(Xe={totalTokenCount:fe.total_tokens||fe.prompt_tokens+fe.completion_tokens,promptTokenCount:fe.prompt_tokens||0,candidatesTokenCount:fe.completion_tokens||0,cachedContentTokenCount:fe.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:(fe.completion_tokens_details?.reasoning_tokens||0)+(fe.completion_tokens_details?.thoughts_tokens||0)},Ge=!0);let ue=ct.choices?.[0]?.delta?.reasoning||ct.choices?.[0]?.delta?.reasoning_content||"",ie=ct.choices?.[0]?.delta?.content||"";ue&&(Y.push({text:ue,thought:!0}),Ge=!0),ie&&(Y.push({text:ie}),Ge=!0)}catch{}}}}if((At||Date.now()-Ye>=350)&&Ge&&(yield{candidates:Y.length>0?[{content:{parts:[...Y]}}]:[],usageMetadata:Xe},B=!0,Y=[],Ye=Date.now(),Ge=!1),At)break}break}catch(X){if(B||ee>=pe)throw X;await new Promise(C=>setTimeout(C,3500))}}},Tr=async function*(e,t){let n=[],s=null,o=!1,d=null,f=i=>{if(n.push(i),s){let l=s;s=null,l()}},a=t.split("/").pop();a=a.replace("llama-3.3","llama-3_3");let h=`https://buildapi.ngc.nvidia.com/v2/predict/queues/models/qc69jvmznzxy/${a}`,g=`https://api.ngc.nvidia.com/v2/predict/queues/models/qc69jvmznzxy/${a}`,u=!1,m=null,x=async()=>{try{let l=await(await Promise.any([h,g].map(async T=>{let R=await fetch(T);if(!R.ok)throw new Error(`HTTP ${R.status}`);return R}))).json();if(l&&l.queues&&l.queues[0]&&typeof l.queues[0].queueDepth=="number"){let T=l.queues[0].queueDepth;u||f({value:{type:"status",content:`Queue ${T||1}`},done:!1})}}catch{}};process.env.NVIDIA_BASE_URL||(x(),m=setInterval(x,5e3)),(async()=>{try{let i=e[Symbol.asyncIterator]();for(;;){let{value:l,done:T}=await i.next();if(T)break;u=!0,m&&(clearInterval(m),m=null),f({value:l,done:!1})}o=!0,f(null)}catch(i){if(d=i,m&&(clearInterval(m),m=null),s){let l=s;s=null,l()}}})();try{for(;;){if(d)throw d;if(n.length>0){let i=n.shift();if(i===null&&o)break;yield i.value}else{if(o)break;await new Promise(i=>{s=i})}}}finally{m&&(clearInterval(m),m=null)}};var Ko=async function*(e,t,n,s,o,d,f,a,h=1,g=null){let u=[];s&&u.push({role:"system",content:[{type:"text",text:s}]});for(let E of n){let O=E.role==="user"?"user":"assistant",U=[];if(Array.isArray(E.parts)){for(let P of E.parts)if(P.text)U.push({type:"text",text:P.text});else if(P.inlineData&&f){let D=P.inlineData.mimeType,ee=P.inlineData.data;D.startsWith("image/")?U.push({type:"image_url",image_url:{url:`data:${D};base64,${ee}`}}):U.push({type:"file",file:{filename:P.filename||"file",file_data:`data:${D};base64,${ee}`}})}}else{let P=E.text||"";P&&U.push({type:"text",text:P})}u.push({role:O,content:U.length===1&&U[0].type==="text"?U[0].text:U})}let m={Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},x=["free","nitro","floor","exacto"],i=t,l=null,T=null;if(t.includes(":")){let E=t.split(":");if(E.length>1){let O=E[E.length-1].toLowerCase().trim();(O==="flex"||O==="priority")&&(T=O,E.pop())}if(E.length>1){let O=E[E.length-1].toLowerCase().trim();if(!x.includes(O)){let U=E.pop().trim();U&&(l={only:[U],allow_fallbacks:!1})}}i=E.join(":").trim()}let R=`${e.slice(-5)}${g||""}${o}${i}${T||""}${l?JSON.stringify(l):""}`,b=await Ho(R),v={model:i,messages:u,stream:!0,temperature:h,cache_control:{type:"ephemeral"},session_id:b};T&&(v.service_tier=T),l&&(v.provider=l);let N=Oe("OpenRouter",t,o),M=N!==null?N:m[o];M&&M!=="none"&&(N!==null||o!=="Fast")&&(v.reasoning_effort=M);let S=await tt("https://openrouter.ai/api/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json","HTTP-Referer":"https://fluxflow-cli.onrender.com/","X-Title":"FluxFlow CLI","X-OpenRouter-Title":"FluxFlow CLI","X-Cache":"true","X-OpenRouter-Cache":"true"},body:JSON.stringify(v),signal:a});if(!S.ok){let E=await S.json().catch(()=>({})),O=E.error?.metadata?.raw||E.error?.message||(typeof E.error=="string"?E.error:"")||S.statusText||"Unknown error";throw new Error(`OpenRouter Error (${S.status}): ${O}`)}let I=S.body.getReader(),$=new TextDecoder,p="",c=[],w=null,r=Date.now(),k=!1;for(;;){let{done:E,value:O}=await I.read();if(E){k&&(c.length>0||w)&&(yield{candidates:c.length>0?[{content:{parts:c}}]:[],usageMetadata:w});break}p+=$.decode(O,{stream:!0});let U=p.split(`
598
+ `);p=U.pop();for(let P of U){let D=P.trim();if(!D||!D.startsWith("data: "))continue;let ee=!1;if(D==="data: [DONE]")ee=!0;else try{let pe=JSON.parse(D.substring(6));if(pe.error){let Se=pe.error.metadata?.raw||pe.error.message||JSON.stringify(pe.error);throw new Error(`OpenRouter Stream Error: ${Se}`)}let B=pe.choices?.[0]?.delta,A=pe.usage;if(pe.choices?.[0]?.finish_reason&&(ee=!0),A&&(w={totalTokenCount:A.total_tokens||(A.prompt_tokens||0)+(A.completion_tokens||0),promptTokenCount:A.prompt_tokens||0,candidatesTokenCount:A.completion_tokens||0,cachedContentTokenCount:A.prompt_tokens_details?.cached_tokens||A.prompt_tokens_details?.cache_read_input_tokens||A.cache_read_input_tokens||0,thoughtsTokenCount:A.completion_tokens_details?.reasoning_tokens||0},k=!0),B){let Se=B.reasoning||(B.reasoning_details?B.reasoning_details.map(X=>X.text).join(""):null);Se&&(c.push({text:Se,thought:!0}),k=!0),B.content&&(c.push({text:B.content}),k=!0)}}catch(pe){if(pe.message&&pe.message.startsWith("OpenRouter Stream Error:"))throw pe}if((ee||Date.now()-r>=150)&&k&&(yield{candidates:c.length>0?[{content:{parts:[...c]}}]:[],usageMetadata:w},c=[],r=Date.now(),k=!1),ee)break}}};import{Ollama as ma}from"ollama";var Bs=async function*(e,t,n,s,o,d,f,a,h=1,g="Cloud"){let u=[];s&&u.push({role:"system",content:s});for(let p of n){let c=p.role==="user"?"user":"assistant",w="",r=[];if(Array.isArray(p.parts)){w=p.parts.map(k=>k.text||"").filter(Boolean).join(`
599
+ `);for(let k of p.parts){let E=k.inlineData||k.inline_data;E&&E.data&&r.push(E.data)}}else w=p.text||"";if(w||r.length>0){let k={role:c,content:w};r.length>0&&(k.images=r),u.push(k)}}let m=g==="Local"||!e||e==="LOCAL",i={host:m?process.env.OLLAMA_HOST||"http://127.0.0.1:11434":process.env.OLLAMA_HOST||"https://ollama.com"};!m&&e&&(i.headers={Authorization:"Bearer "+e});let l=new ma(i),T=[],R=null,b=Date.now(),v=!1,N=Oe("Ollama",t,o),M={Fast:!1,Low:"medium",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},S=N!==null?N==="false"||N===!1?!1:N==="true"||N===!0?!0:N:M[o]!==void 0?M[o]:!0,I={model:t,messages:u,stream:!0,think:S,keep_alive:"10m",options:{temperature:h}},$=await l.chat(I);for await(let p of $){if(a?.aborted)throw new DOMException("The user aborted a request.","AbortError");if(p.message?.thinking&&(T.push({text:p.message.thinking,thought:!0}),v=!0),p.message?.content&&(T.push({text:p.message.content}),v=!0),p.done){let c=p.prompt_cached_count||0;if(!c&&p.prompt_eval_count){let w=p.prompt_eval_duration||0;w>0&&w<5e7&&(c=p.prompt_eval_count)}R={totalTokenCount:(p.prompt_eval_count||0)+(p.eval_count||0),promptTokenCount:p.prompt_eval_count||0,candidatesTokenCount:p.eval_count||0,cachedContentTokenCount:c,thoughtsTokenCount:0},v=!0}(p.done||Date.now()-b>=150&&v)&&(yield{candidates:T.length>0?[{content:{parts:[...T]}}]:[],usageMetadata:R},T=[],b=Date.now(),v=!1)}v&&(T.length>0||R)&&(yield{candidates:T.length>0?[{content:{parts:[...T]}}]:[],usageMetadata:R})};var Yo=async function*(e,t,n,s,o,d,f,a,h=1){let g=[];s&&g.push({role:"system",content:s});for(let c of n){let w=c.role==="user"?"user":"assistant",r="";if(Array.isArray(c.parts))for(let k of c.parts)k.text&&(r+=(r?`
600
+ `:"")+k.text);else r=c.text||"";g.push({role:w,content:r})}let u=Oe("InferX",t,o),x=u!==null?u:{Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i=t&&t.toLowerCase().includes("qwen3.8-27b")&&u===null,l=t&&(t.toLowerCase().includes("qwen3.8-27b")||t.toLowerCase().includes("qwen3.6-35b-a3b-fp8")),T={model:t,messages:g.filter(c=>c.content&&String(c.content).trim().length>0),stream:!0,stream_options:{include_usage:!0},temperature:h};!i&&x&&(T.stream_options={include_usage:!0},T.reasoning_effort=x);let R=await tt("https://model.inferx.net/endpoints/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(T),signal:a});if(!R.ok){let c=await R.text().catch(()=>""),w="";try{let r=JSON.parse(c);w=r.error?.message||r.error?.detail||r.message||r.detail||(typeof r.error=="string"?r.error:"")||(c&&c!=="{}"?c:"")}catch{w=c}throw(!w||w==="{}")&&(w=R.statusText||"Unknown error"),new Error(`InferX Error (${R.status}): ${w}`)}let b=R.body.getReader(),v=new TextDecoder,N="",M=[],S=null,I=Date.now(),$=!1,p=!0;for(;;){let{done:c,value:w}=await b.read();if(c){$&&(M.length>0||S)&&(yield{candidates:M.length>0?[{content:{parts:M}}]:[],usageMetadata:S});break}N+=v.decode(w,{stream:!0});let r=N.split(`
601
+ `);N=r.pop();for(let k of r){let E=k.trim();if(!E||!E.startsWith("data: "))continue;let O=!1;if(E==="data: [DONE]")O=!0;else try{let U=JSON.parse(E.substring(6)),P=U.choices?.[0]?.delta,D=U.usage;if(D&&(S={totalTokenCount:D.total_tokens||(D.prompt_tokens||0)+(D.completion_tokens||0),promptTokenCount:D.prompt_tokens||0,candidatesTokenCount:D.completion_tokens||0,cachedContentTokenCount:D.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:D.completion_tokens_details?.reasoning_tokens||D.reasoning_tokens||0},$=!0),P){let ee=P.reasoning||P.reasoning_content||null;if(ee&&(M.push({text:ee,thought:!0}),$=!0),P.content){let pe=P.content;l&&p&&pe.length>0&&(pe="<think>"+pe,p=!1),M.push({text:pe}),$=!0}}}catch{}if((O||Date.now()-I>=150||S)&&$&&(yield{candidates:M.length>0?[{content:{parts:[...M]}}]:[],usageMetadata:S},M=[],I=Date.now(),$=!1),O)break}Date.now()-I>=150&&$&&(yield{candidates:M.length>0?[{content:{parts:[...M]}}]:[],usageMetadata:S},M=[],I=Date.now(),$=!1)}};var qo=async function*(e,t,n,s,o,d,f,a,h=1){let g=[];s&&g.push({role:"system",content:s});for(let I of n){let $=I.role==="user"?"user":"assistant",p=[];if(Array.isArray(I.parts)){for(let c of I.parts)if(c.text)p.push({type:"text",text:c.text});else if(c.inlineData&&f){let w=c.inlineData.mimeType,r=c.inlineData.data;w.startsWith("image/")&&p.push({type:"image_url",image_url:{url:`data:${w};base64,${r}`}})}}else{let c=I.text||"";c&&p.push({type:"text",text:c})}g.push({role:$,content:p.length===1&&p[0].type==="text"?p[0].text:p})}let u=Oe("SenseNova",t,o),x=u!==null?u:{Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:g,stream:!0,stream_options:{include_usage:!0},temperature:h};x&&(i.reasoning_effort=x);let l=await tt("https://token.sensenova.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(i),signal:a});if(!l.ok){let I=await l.json().catch(()=>({}));throw new Error(`SenseNova Error (${l.status}): ${I.error?.message||l.statusText}`)}let T=l.body.getReader(),R=new TextDecoder,b="",v=[],N=null,M=Date.now(),S=!1;for(;;){let{done:I,value:$}=await T.read();if(I){S&&(v.length>0||N)&&(yield{candidates:v.length>0?[{content:{parts:v}}]:[],usageMetadata:N});break}b+=R.decode($,{stream:!0});let p=b.split(`
602
+ `);b=p.pop();for(let c of p){let w=c.trim();if(!w||!w.startsWith("data: "))continue;let r=!1;if(w==="data: [DONE]")r=!0;else try{let k=JSON.parse(w.substring(6)),E=k.choices?.[0]?.delta,O=k.usage;if(O&&(N={totalTokenCount:O.total_tokens||(O.prompt_tokens||0)+(O.completion_tokens||0),promptTokenCount:O.prompt_tokens||0,candidatesTokenCount:O.completion_tokens||0,cachedContentTokenCount:O.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:O.completion_tokens_details?.reasoning_tokens||O.reasoning_tokens||0},S=!0),E){let U=E.reasoning||E.reasoning_content||null;U&&(v.push({text:U,thought:!0}),S=!0),E.content&&(v.push({text:E.content}),S=!0)}}catch{}if((r||Date.now()-M>=150||N)&&S&&(yield{candidates:v.length>0?[{content:{parts:[...v]}}]:[],usageMetadata:N},v=[],M=Date.now(),S=!1),r)break}Date.now()-M>=150&&S&&(yield{candidates:v.length>0?[{content:{parts:[...v]}}]:[],usageMetadata:N},v=[],M=Date.now(),S=!1)}};var zo=async function*(e,t,n,s,o,d,f,a,h=1){let g=[];s&&g.push({role:"system",content:s});for(let I of n){let $=I.role==="user"?"user":"assistant",p=[];if(Array.isArray(I.parts)){for(let c of I.parts)if(c.text)p.push({type:"text",text:c.text});else if(c.inlineData&&f){let w=c.inlineData.mimeType,r=c.inlineData.data;w.startsWith("image/")&&p.push({type:"image_url",image_url:{url:`data:${w};base64,${r}`}})}}else{let c=I.text||"";c&&p.push({type:"text",text:c})}g.push({role:$,content:p.length===1&&p[0].type==="text"?p[0].text:p})}let u=Oe("AIHubMix",t,o),x=u!==null?u:{Fast:"minimal",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:g,stream:!0,stream_options:{include_usage:!0},temperature:h};x&&(i.reasoning_effort=x);let l=await tt("https://aihubmix.com/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(i),signal:a});if(!l.ok){let I=await l.json().catch(()=>({}));throw new Error(`AIHubMix Error (${l.status}): ${I.error?.message||l.statusText}`)}let T=l.body.getReader(),R=new TextDecoder,b="",v=[],N=null,M=Date.now(),S=!1;for(;;){let{done:I,value:$}=await T.read();if(I){S&&(v.length>0||N)&&(yield{candidates:v.length>0?[{content:{parts:v}}]:[],usageMetadata:N});break}b+=R.decode($,{stream:!0});let p=b.split(`
603
+ `);b=p.pop();for(let c of p){let w=c.trim();if(!w||!w.startsWith("data: "))continue;let r=!1;if(w==="data: [DONE]")r=!0;else try{let k=JSON.parse(w.substring(6)),E=k.choices?.[0]?.delta,O=k.usage;if(k.choices?.[0]?.finish_reason&&(r=!0),O&&(N={totalTokenCount:O.total_tokens||(O.prompt_tokens||0)+(O.completion_tokens||0),promptTokenCount:O.prompt_tokens||0,candidatesTokenCount:O.completion_tokens||0,cachedContentTokenCount:O.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:O.completion_tokens_details?.reasoning_tokens||O.reasoning_tokens||0},S=!0),E){let U=E.reasoning_content||null;U&&(v.push({text:U,thought:!0}),S=!0),E.content&&(v.push({text:E.content}),S=!0)}}catch{}if((r||Date.now()-M>=150)&&S&&(yield{candidates:v.length>0?[{content:{parts:[...v]}}]:[],usageMetadata:N},v=[],M=Date.now(),S=!1),r)break}Date.now()-M>=150&&S&&(yield{candidates:v.length>0?[{content:{parts:[...v]}}]:[],usageMetadata:N},v=[],M=Date.now(),S=!1)}};var Jo=async function*(e,t,n,s,o,d,f,a,h=1){let g=[];s&&g.push({role:"system",content:s});for(let S of n){let I=S.role==="user"?"user":"assistant",$=[];if(Array.isArray(S.parts)){for(let p of S.parts)if(p.text)$.push({type:"text",text:p.text});else if(p.inlineData&&f){let c=p.inlineData.mimeType,w=p.inlineData.data;c.startsWith("image/")&&$.push({type:"image_url",image_url:{url:`data:${c};base64,${w}`}})}}else{let p=S.text||"";p&&$.push({type:"text",text:p})}g.push({role:I,content:$.length===1&&$[0].type==="text"?$[0].text:$})}let u=Oe("Poolside",t,o),m=u!==null?u===!1||u==="false"||u==="none"||u==="Fast":o==="Fast",x={model:t,messages:g,stream:!0,stream_options:{include_usage:!0},temperature:h};m?x.chat_template_kwargs={enable_thinking:!1}:u!==null&&typeof u=="object"?x.chat_template_kwargs=u:x.chat_template_kwargs={enable_thinking:!0};let i=await tt("https://inference.poolside.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(x),signal:a});if(!i.ok){let S=await i.json().catch(()=>({}));throw new Error(`Poolside Error (${i.status}): ${S.error?.message||i.statusText}`)}let l=i.body.getReader(),T=new TextDecoder,R="",b=[],v=null,N=Date.now(),M=!1;for(;;){let{done:S,value:I}=await l.read();if(S){M&&(b.length>0||v)&&(yield{candidates:b.length>0?[{content:{parts:b}}]:[],usageMetadata:v});break}R+=T.decode(I,{stream:!0});let $=R.split(`
604
+ `);R=$.pop();for(let p of $){let c=p.trim();if(!c||!c.startsWith("data: "))continue;let w=!1;if(c==="data: [DONE]")w=!0;else try{let r=JSON.parse(c.substring(6)),k=r.choices?.[0]?.delta,E=r.usage;if(r.choices?.[0]?.finish_reason&&(w=!0),E&&(v={totalTokenCount:E.total_tokens||(E.prompt_tokens||0)+(E.completion_tokens||0),promptTokenCount:E.prompt_tokens||0,candidatesTokenCount:E.completion_tokens||0,cachedContentTokenCount:E.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:E.completion_tokens_details?.reasoning_tokens||E.reasoning_tokens||0},M=!0),k){let O=k.reasoning_content||k.reasoning||null;O&&(b.push({text:O,thought:!0}),M=!0),k.content&&(b.push({text:k.content}),M=!0)}}catch{}if((w||Date.now()-N>=150)&&M&&(yield{candidates:b.length>0?[{content:{parts:[...b]}}]:[],usageMetadata:v},b=[],N=Date.now(),M=!1),w)break}Date.now()-N>=150&&M&&(yield{candidates:b.length>0?[{content:{parts:[...b]}}]:[],usageMetadata:v},b=[],N=Date.now(),M=!1)}};import ha from"fs";var Xo=async function*(e,t,n,s,o,d,f,a,h=1){let g=[];s&&g.push({role:"system",content:s});for(let c of n){let w=c.role==="user"?"user":"assistant",r=[];if(Array.isArray(c.parts)){for(let k of c.parts)if(k.text)r.push({type:"text",text:k.text});else if(k.inlineData&&f){let E=k.inlineData.mimeType,O=k.inlineData.data;E.startsWith("image/")&&r.push({type:"image_url",image_url:{url:`data:${E};base64,${O}`}})}}else{let k=c.text||"";k&&r.push({type:"text",text:k})}g.push({role:w,content:r.length===1&&r[0].type==="text"?r[0].text:r})}let u=Oe("9router",t,o)||Oe("9Router",t,o),x=u!==null?u:{Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:g,stream:!0,stream_options:{include_usage:!0},temperature:h};x&&x!=="none"&&(u!==null||o!=="Fast")&&(i.reasoning_effort=x);let l=process.env["9ROUTER_URL"]||process.env.NINEROUTER_URL||"http://127.0.0.1:20128/v1/chat/completions",T={"Content-Type":"application/json"},R=e&&e!=="LOCAL"?e:process.env["9ROUTER_API_KEY"]||"dummy-key";T.Authorization=`Bearer ${R}`;let b=await tt(l,{method:"POST",headers:T,body:JSON.stringify(i),signal:a});if(!b.ok){let c=await b.json().catch(()=>({}));throw new Error(`9router Error (${b.status}): ${c.error?.message||b.statusText}`)}let v=b.body.getReader(),N=new TextDecoder,M="",S=[],I=null,$=Date.now(),p=!1;for(;;){let{done:c,value:w}=await v.read();if(c){p&&(S.length>0||I)&&(yield{candidates:S.length>0?[{content:{parts:S}}]:[],usageMetadata:I});break}M+=N.decode(w,{stream:!0});let r=M.split(`
605
+ `);M=r.pop();for(let k of r){let E=k.trim();if(ha.appendFileSync("9router.txt",`${E}
606
+
607
+ `),!E||!E.startsWith("data: "))continue;let O=!1;if(E==="data: [DONE]")O=!0;else try{let U=JSON.parse(E.substring(6)),P=U.choices?.[0]?.delta,D=U.usage;if(U.choices?.[0]?.finish_reason&&(O=!0),D&&(I={totalTokenCount:D.total_tokens||(D.prompt_tokens||0)+(D.completion_tokens||0),promptTokenCount:D.prompt_tokens||0,candidatesTokenCount:D.completion_tokens||0,cachedContentTokenCount:D.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:D.completion_tokens_details?.reasoning_tokens||D.reasoning_tokens||0},p=!0),P){let ee=P.reasoning_content||P.reasoning||P.thinking||null;!ee&&Array.isArray(P.reasoning_details)&&P.reasoning_details.length>0&&(ee=P.reasoning_details.map(pe=>typeof pe=="string"?pe:pe?.text||"").filter(Boolean).join("")),ee&&(S.push({text:ee,thought:!0}),p=!0),P.content&&(S.push({text:P.content}),p=!0)}}catch{}if((O||Date.now()-$>=150)&&p&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:I},S=[],$=Date.now(),p=!1),O)break}Date.now()-$>=150&&p&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:I},S=[],$=Date.now(),p=!1)}};var Qo=async function*(e,t,n,s,o,d,f,a,h=1){let g=[];s&&g.push({role:"system",content:s});for(let c of n){let w=c.role==="user"?"user":"assistant",r=[];if(Array.isArray(c.parts)){for(let k of c.parts)if(k.text)r.push({type:"text",text:k.text});else if(k.inlineData&&f){let E=k.inlineData.mimeType,O=k.inlineData.data;E.startsWith("image/")&&r.push({type:"image_url",image_url:{url:`data:${E};base64,${O}`}})}}else{let k=c.text||"";k&&r.push({type:"text",text:k})}g.push({role:w,content:r.length===1&&r[0].type==="text"?r[0].text:r})}let u=Oe("ExpLabs",t,o),x=u!==null?u:{Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:g,stream:!0,stream_options:{include_usage:!0},temperature:h};x&&(i.reasoning_effort=x);let l=process.env.EXPLABS_URL||process.env.EXPERIENTIALLABS_URL||"https://api.experientiallabs.ai/v1/chat/completions",T={"Content-Type":"application/json"},R=e||process.env.EXPLABS_API_KEY||process.env.EXPERIENTIALLABS_API_KEY||"";T.Authorization=`Bearer ${R}`;let b=await tt(l,{method:"POST",headers:T,body:JSON.stringify(i),signal:a});if(!b.ok){let c=await b.json().catch(()=>({}));throw new Error(`Experiential Labs Error (${b.status}): ${c.error?.message||c.message||b.statusText}`)}let v=b.body.getReader(),N=new TextDecoder,M="",S=[],I=null,$=Date.now(),p=!1;for(;;){let{done:c,value:w}=await v.read();if(c){p&&(S.length>0||I)&&(yield{candidates:S.length>0?[{content:{parts:S}}]:[],usageMetadata:I});break}M+=N.decode(w,{stream:!0});let r=M.split(`
608
+ `);M=r.pop();for(let k of r){let E=k.trim();if(!E||!E.startsWith("data: "))continue;let O=!1;if(E==="data: [DONE]")O=!0;else try{let U=JSON.parse(E.substring(6)),P=U.choices?.[0]?.delta,D=U.usage;if(D&&(I={totalTokenCount:D.total_tokens||(D.prompt_tokens||0)+(D.completion_tokens||0),promptTokenCount:D.prompt_tokens||0,candidatesTokenCount:D.completion_tokens||0,cachedContentTokenCount:D.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:D.completion_tokens_details?.reasoning_tokens||D.reasoning_tokens||0},p=!0),P){let ee=P.reasoning_content||P.reasoning||null;!ee&&Array.isArray(P.reasoning_details)&&P.reasoning_details.length>0&&(ee=P.reasoning_details.map(pe=>pe.text||"").filter(Boolean).join("")),ee&&(S.push({text:ee,thought:!0}),p=!0),P.content&&(S.push({text:P.content}),p=!0)}}catch{}if((O||Date.now()-$>=150)&&p&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:I},S=[],$=Date.now(),p=!1),O)break}Date.now()-$>=150&&p&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:I},S=[],$=Date.now(),p=!1)}};var Us=async function*(e,t,n,s,o,d,f,a,h=1){let g=[];s&&g.push({role:"system",content:s});for(let c of n){let w=c.role==="user"?"user":"assistant",r=[];if(Array.isArray(c.parts)){for(let k of c.parts)if(k.text)r.push({type:"text",text:k.text});else if(k.inlineData&&f){let E=k.inlineData.mimeType,O=k.inlineData.data;E.startsWith("image/")&&r.push({type:"image_url",image_url:{url:`data:${E};base64,${O}`}})}}else{let k=c.text||"";k&&r.push({type:"text",text:k})}g.push({role:w,content:r.length===1&&r[0].type==="text"?r[0].text:r})}let u=Oe("TokenHarbor",t,o),x=u!==null?u:{Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:g,stream:!0,stream_options:{include_usage:!0},temperature:h};x&&(i.reasoning_effort=x);let l=process.env.TOKENHARBOR_URL||process.env.TOKEN_HARBOR_URL||"https://tokenharbor.ai/v1/chat/completions",T={"Content-Type":"application/json","X-Title":"Flux-Flow","User-Agent":"Flux-Flow","HTTP-Referer":"https://fluxflow-cli.onrender.com/"},R=e||process.env.TOKENHARBOR_API_KEY||process.env.TOKEN_HARBOR_API_KEY||"";T.Authorization=`Bearer ${R}`;let b=await tt(l,{method:"POST",headers:T,body:JSON.stringify(i),signal:a});if(!b.ok){let c=await b.json().catch(()=>({}));throw new Error(`Token Harbor Error (${b.status}): ${c.error?.message||c.message||b.statusText}`)}let v=b.body.getReader(),N=new TextDecoder,M="",S=[],I=null,$=Date.now(),p=!1;for(;;){let{done:c,value:w}=await v.read();if(c){p&&(S.length>0||I)&&(yield{candidates:S.length>0?[{content:{parts:S}}]:[],usageMetadata:I});break}M+=N.decode(w,{stream:!0});let r=M.split(`
609
+ `);M=r.pop();for(let k of r){let E=k.trim();if(!E||!E.startsWith("data: "))continue;let O=!1;if(E==="data: [DONE]")O=!0;else try{let U=JSON.parse(E.substring(6)),P=U.choices?.[0]?.delta,D=U.usage;if(D&&(I={totalTokenCount:D.total_tokens||(D.prompt_tokens||0)+(D.completion_tokens||0),promptTokenCount:D.prompt_tokens||0,candidatesTokenCount:D.completion_tokens||0,cachedContentTokenCount:D.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:D.completion_tokens_details?.reasoning_tokens||D.reasoning_tokens||0},p=!0),P){let ee=P.reasoning_content||P.reasoning||null;!ee&&Array.isArray(P.reasoning_details)&&P.reasoning_details.length>0&&(ee=P.reasoning_details.map(pe=>pe.text||"").filter(Boolean).join("")),ee&&(S.push({text:ee,thought:!0}),p=!0),P.content&&(S.push({text:P.content}),p=!0)}}catch{}if((O||Date.now()-$>=150)&&p&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:I},S=[],$=Date.now(),p=!1),O)break}Date.now()-$>=150&&p&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:I},S=[],$=Date.now(),p=!1)}};var Ws=async function*(e,t,n,s,o,d,f,a,h=1){let g=[];s&&g.push({role:"system",content:s});for(let c of n){let w=c.role==="user"?"user":"assistant",r=[];if(Array.isArray(c.parts)){for(let k of c.parts)if(k.text)r.push({type:"text",text:k.text});else if(k.inlineData&&f){let E=k.inlineData.mimeType,O=k.inlineData.data;E.startsWith("image/")&&r.push({type:"image_url",image_url:{url:`data:${E};base64,${O}`}})}}else{let k=c.text||"";k&&r.push({type:"text",text:k})}g.push({role:w,content:r.length===1&&r[0].type==="text"?r[0].text:r})}let u=Oe("APInex",t,o),x=u!==null?u:{Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:g,stream:!0,stream_options:{include_usage:!0},temperature:h};x&&(i.reasoning_effort=x);let l=process.env.APINEX_URL||"https://api.apinex.bond/v1/chat/completions",T={"Content-Type":"application/json","X-Title":"Flux-Flow","User-Agent":"Flux-Flow","HTTP-Referer":"https://fluxflow-cli.onrender.com/"},R=e||process.env.APINEX_API_KEY||"";T.Authorization=`Bearer ${R}`;let b=await tt(l,{method:"POST",headers:T,body:JSON.stringify(i),signal:a});if(!b.ok){let c=await b.json().catch(()=>({}));throw new Error(`APInex Error (${b.status}): ${c.error?.message||c.message||b.statusText}`)}let v=b.body.getReader(),N=new TextDecoder,M="",S=[],I=null,$=Date.now(),p=!1;for(;;){let{done:c,value:w}=await v.read();if(c){p&&(S.length>0||I)&&(yield{candidates:S.length>0?[{content:{parts:S}}]:[],usageMetadata:I});break}M+=N.decode(w,{stream:!0});let r=M.split(`
610
+ `);M=r.pop();for(let k of r){let E=k.trim();if(!E||!E.startsWith("data: "))continue;let O=!1;if(E==="data: [DONE]")O=!0;else try{let U=JSON.parse(E.substring(6)),P=U.choices?.[0]?.delta,D=U.usage;if(D&&(I={totalTokenCount:D.total_tokens||(D.prompt_tokens||0)+(D.completion_tokens||0),promptTokenCount:D.prompt_tokens||0,candidatesTokenCount:D.completion_tokens||0,cachedContentTokenCount:D.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:D.completion_tokens_details?.reasoning_tokens||D.reasoning_tokens||0},p=!0),P){let ee=P.reasoning_content||P.reasoning||null;!ee&&Array.isArray(P.reasoning_details)&&P.reasoning_details.length>0&&(ee=P.reasoning_details.map(pe=>pe.text||"").filter(Boolean).join("")),ee&&(S.push({text:ee,thought:!0}),p=!0),P.content&&(S.push({text:P.content}),p=!0)}}catch{}if((O||Date.now()-$>=150)&&p&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:I},S=[],$=Date.now(),p=!1),O)break}Date.now()-$>=150&&p&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:I},S=[],$=Date.now(),p=!1)}};var pa=/```[\s\S]*?```/g,ya=/```[\s\S]*$/g,xa=/`[^`]+`/g,ba=/^\|.*\|$/gm,ka=/^[^\w]+|[^\w]+$/g,wa=/[^a-z0-9]/gi,mo=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,Ta=/\[\s*(?:tool:functions\.|agent:generalist\.)([a-z0-9_]+)\s*\(/gi,Sa=/(?:path|targetFile|TargetFile|directory|keyword|id|taskId|title|task)\s*=\s*\\?["']?([^\\"' \),]+)/,Pn=/["']/g,Sr=/\\/g,_a=/<\|channel>thought/gi,Ea=/<channel\|>/gi,Aa=e=>typeof e!="string"?e:e.replace(_a,"<think>").replace(Ea,"</think>"),Hd=/^\s*(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\]|$)/i,Ca=(e,t)=>{let n=!1;for(let s=0;s<t;s++)e[s]==="`"&&(n=!n);return n},Ra=e=>{let t=/(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\])/gi,n;for(;(n=t.exec(e))!==null;)if(!Ca(e,n.index))return{index:n.index,length:n[0].length};return{index:-1,length:0}},Hs=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=Ra(s);if(o.index!==-1){let d=n+o.index+o.length;return{fullBlock:e.substring(0,d),innerContent:s.substring(0,o.index),remainingText:e.substring(d)}}return{fullBlock:e,innerContent:s,remainingText:""}},Kt=e=>{if(!e||typeof e!="string")return e;let t=Hs(e);return t?t.remainingText.trimStart():e};var Mr=/`[^`]*`/g,Ir=/`[^`]*$/,_r=/<\|\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,va=/"([^"]+)"\s*:\s*(?:"([^"]*)"|(\d+)|true|false|null)/g,Er=/<\|\s*tool_calls_section_begin\s*\|>/gi,Ar=/<\|\s*tool_calls_section_end\s*\|>/gi,Ma=/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi;var Cr=e=>!e||typeof e!="string"?e:e.replace(/(```[\s\S]*?```|`[^`]*`)|(<(?:\w+)(?:[^>]*)>\r?\n?|\r?\n?<\/\w+(?:[^>]*)>)/gi,(t,n)=>n||""),js=null,Zo={},$n={key:null,value:null},Vt=e=>e&&e.replace(/(?:(\x1b\[\d+m))?([✔✘✖🔍📖→➕↻↷•🛇])(?:(\x1b\[\d+m))?\s*\b(Clicked|Dragged|Scrolled|Typed|Pressed Key|Recaptured Screen|Created|Read Skill|Read Documentation|Searched Documentation|Read|Edited|Viewed|Processed|Auto-Read|Skipped|List|Generated|Written|Searched|AI Search|Get Map|Write Canceled|Resolved Sub-Agent Query|Edit Canceled|Write Cancelled|Edit Denied|Visited|Updated|Reviewed|Delegated|Background|Checked|Indexed|Analyzed|Browsed|Elevating SubAgent|Checking SubAgent Work|Started Generalist|Called Generalist|Steered|Unsupported Modality|Awaiting|Cancelled|Aligning Moon Phase|Contemplating Existence|Staring At Void|Rollback Point Checked|Emergency Rollback Failed|Emergency Rollback|Delaying Professionally|Negotiating With Electrons|Touching Grass (virtually)|Panicking Softly|Rethinking Career Choices|Loading Cat Videos|Giving Up Entirely|Summoning Braincell #2|Pretending To Be Busy|Waiting For Motivation DLC|Rotating Internal Screaming|Downloading More RAM|Feeding The Hamsters|Gaslighting Scheduler|Performing Dramatic Pause|Buffering Social Energy|Calculating Regret|Reading Terms And Conditions|Becoming Sentient Briefly|Execution Error|Loop Detected|Contacting Ancestors)\b/ig,(t,n,s,o,d)=>`${n||""}${s}${o||""} \x1B[95m${d}\x1B[0m`),Ia=async(e,t=8,n=1e3,s=8e3,o=null)=>{let d=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."||(d++,d>=t))throw f;let a=Math.min(n*Math.pow(2,d-1),s);await new Promise((h,g)=>{let u=setTimeout(h,a);o&&o.addEventListener("abort",()=>{clearTimeout(u),g(new DOMException("The user aborted a request.","AbortError"))})})}}},kt=!1;var Da=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,d,f)=>{let a=o.fullText||o.text||"";if(o.role==="user"&&d<f.length-1)if(a.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")){let h=a.indexOf("**CONTEXT SUMMARY OF PREVIOUS TURNS");if(h!==-1){let u=a.substring(0,h).lastIndexOf("[SYSTEM METADATA]");u!==-1?a=a.substring(u).trim():a=a.substring(h).trim()}}else{let h=a.lastIndexOf("[USER]"),g=a.lastIndexOf("[USER PROMPT]");h!==-1?a=a.substring(h+6).trim():g!==-1&&(a=a.substring(g).trim())}return{...o,text:a}}),n=[],s=0;for(;s<t.length;){let o=t[s];if(o.role==="user")n.push(o),s++;else{let d=[];for(;s<t.length&&t[s].role!=="user";)d.push(t[s]),s++;let f=[],a=[],h=!1,g=()=>{f.length>0&&(n.push({role:"agent",text:"combined"}),f=[]),a.length>0&&(n.push({role:"system",text:"combined"}),a=[]),h=!1};d.forEach(u=>{let m=u.role==="system"&&(u.text?.startsWith("[TOOL RESULT]")||u.text?.startsWith("SUCCESS:")||u.text?.startsWith("ERROR:")||u.fullText?.startsWith("[TOOL RESULT]")||u.fullText?.startsWith("SUCCESS:")||u.fullText?.startsWith("ERROR:")),x=u.fullText||u.text||"",i=x.trim();if(!(!i&&!u.binaryPart)){if(m)a.push(i);else if(u.role==="agent"){!h&&a.length>0&&g();let l=x.endsWith(`
611
+ `),T=i.toLowerCase().includes("tool:functions.")||i.toLowerCase().includes("agent:generalist.");f.push(i),T&&l?h=!0:h=!1}}}),g()}}return n.length},Oa=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),Gd=()=>{kt=!0},jd=()=>kt,Gs={write_file:"Writing",update_file:"Editing",read_folder:"Reading",view_file:"Reading",exec_command:"Executing Command",web_search:"Searching",web_scrape:"Reading",memory:"Updating Memory",search_keyword:"Searching",file_map:"Generating Map",ask:"User Input",write_pdf:"Creating",write_docx:"Creating",generate_image:"Generating",todo:"Planning",Todo:"Planning",goal:"Planning",Goal:"Planning",invoke_sync:"Sub-Agent Working",invoke:"Starting Agent",get_progress:"Checking Progress",cancel:"Cancelling",await:"Waiting",EmergencyRollback:"Don't Panic. Lookin' into it",answer:"Answering Sub-Agent",Answer:"Answering Sub-Agent",steer:"Steering Sub-Agent",Steer:"Steering Sub-Agent",Click:"Clicking",click:"Clicking",Drag:"Dragging",drag:"Dragging",Scroll:"Scrolling",scroll:"Scrolling",KeyboardTyping:"Typing",keyboard_typing:"Typing",KeyPress:"Pressing Key",key_press:"Pressing Key",RecaptureScreen:"Recapturing Screen",recapture_screen:"Recapturing Screen"},Nn=(e,t)=>{try{let n=Z(t),s=e.toLowerCase().replace(/_/g,"");if(s==="invokesync"||s==="invoke")return n.title||(n.task?n.task.substring(0,30):null);if(s==="getprogress"||s==="cancel"||s==="steer"||s==="steersubagent")return n.id||n.taskId;let o=n.path||n.targetFile||n.TargetFile||n.directory;return o?J.basename(o.replace(/["']/g,"").replace(/\\/g,"/")):null}catch{return null}},Vs=e=>e?new vr({apiKey:e}):js,Vd=async(e,t,n,s,o={})=>{let{onStatus:a,onMemoryUpdated:h,onBackgroundIncrement:g}=o,{profile:u,thinkingLevel:m,mode:x,janitorModel:i,chatId:l,systemSettings:T,sessionStats:R,aiProvider:b="Google",apiKey:v}=e,N=process.env.NVIDIA_BASE_URL||b==="Ollama"||b==="InferX"||b==="SenseNova"||b==="AIHubMix"||b==="Poolside"||b==="9router"||b==="ExpLabs"||b==="ExperientialLabs"?!1:T?.memory!==!1,S=_t(On,[]).map(C=>`- [${C.id}]: ${C.memory}`).join(`
612
+ `),I=s.slice(0,-1).filter(C=>C.text&&!C.text.includes("[TOOL RESULT]")&&!C.text.includes("OBSERVATION:")&&!C.text.startsWith("[TERMINAL_RECORD]")&&!C.isTerminalRecord&&!C.isMeta&&!C.isLogo&&!String(C.id).startsWith("welcome")&&!String(C.id).startsWith("logo")).slice(-14).map(C=>{let G=Kt(Oa(C.text)).replace(/\[tool:functions\..*?\]/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[METADATA \(PRIORITY: DYNAMIC\)\] Time: ([^|\n]+)/g,(Ye,Ge)=>`[METADATA (PRIORITY: DYNAMIC)] Time: ${Ge.replace(/:\d{2}/g,"")}`).replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[TOOL RESULTS\]/g,"").replace(/\[tool results\]/g,"").replace(/\r?\n\r?\n/g,`
612
613
  `).replace(/\n\n/g,`
613
- `).replace(/\\n\\n/g,"").trim(),ee=v.role==="user"?8192:32768,Y=G.substring(0,ee);G.length>ee&&(Y+=`
614
- ... (truncated) ...`);let Xe=v.role==="user"?Y.startsWith("[USER]")?"":"[USER]: ":Y.startsWith("[AGENT]")?"":"[AGENT]: ";return{role:v.role==="user"?"user":"model",parts:[{text:`${Xe}${Y}`}]}}),$=s.filter(v=>v.role==="user").length===1,p=t.includes("[TITLE-UPDATE]"),c=Math.random()<.8,w=$||p||c,r=Kt(n).trim(),k=qi(S,N,w),E=`${r.replace(/\[tool:functions\..*?\]/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[\[TOOL RESULTS\]\]/g,"").replace(/\[tool results\]/g,"").substring(0,32768)}`;E.length>32768&&(E+=`
614
+ `).replace(/\\n\\n/g,"").trim(),te=C.role==="user"?8192:32768,Y=G.substring(0,te);G.length>te&&(Y+=`
615
+ ... (truncated) ...`);let Xe=C.role==="user"?Y.startsWith("[USER]")?"":"[USER]: ":Y.startsWith("[AGENT]")?"":"[AGENT]: ";return{role:C.role==="user"?"user":"model",parts:[{text:`${Xe}${Y}`}]}}),$=s.filter(C=>C.role==="user").length===1,p=t.includes("[TITLE-UPDATE]"),c=Math.random()<.8,w=$||p||c,r=Kt(n).trim(),k=zi(S,N,w),E=`${r.replace(/\[tool:functions\..*?\]/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[\[TOOL RESULTS\]\]/g,"").replace(/\[tool results\]/g,"").substring(0,32768)}`;E.length>32768&&(E+=`
615
616
  ... (truncated) ...`);let O=t.replace(/\[Prompted on:.*?\]/g,"").trim();E=E.replace(/\r?\n\r?\n/g,`
616
617
  `).replace(/\n\n/g,`
617
- `).replace(/\\n\\n/g,"").trim();let U=new Date,I=`[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})}`}
618
+ `).replace(/\\n\\n/g,"").trim();let U=new Date,D=`[METADATA] Current date and Time: ${`${U.getFullYear()}-${U.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(U.getDate()).padStart(2,"0")}, ${U.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0})}`}
618
619
 
619
620
  [USER]: ${O.substring(0,8192)}
620
621
  ${O.length>8192?`... (truncated) ...
621
622
 
622
623
  `:""}
623
- [AGENT (current turn)]: ${E}`;M.push({role:"user",parts:[{text:I}]});let Z=await us("NVIDIA"),B=(await eo()).quotas?.providerTiers?.NVIDIA==="Free",A="",Ee=0,se=N?12:-1;for(;Ee<=se;)try{if(!await ii("background",e))return;let v="",G=null,ee=!1,Y=x;try{let Ge=new Promise((fe,ue)=>setTimeout(()=>ue(new Error("JANITOR_TIMEOUT")),1e4)),ft=x==="Google"&&Ee>=0&&Ee<6&&Z&&B,Qe=x==="DeepSeek"&&Ee<4&&Z&&B;ee=ft||Qe,Y=ee?"NVIDIA":x;let pt=(async()=>{if(x==="OpenRouter"){let fe=de("janitor_open_router"),ie=Ko(R,fe,M,k,"Fast",b,!1,null,.7)[Symbol.asyncIterator](),vt=await ie.next();return{iterator:ie,firstResult:vt}}else if(x==="DeepSeek"&&!ee){let ue=Go(R,de("deepseek_fast_fallback"),M,k,"Fast",b,!1,null,.7)[Symbol.asyncIterator](),ie=await ue.next();return{iterator:ue,firstResult:ie}}else if(x==="Mistral"&&!ee){let ue=jo(R,de("mistral_janitor_fallback"),M,k,"Fast",b,!1,null,.7)[Symbol.asyncIterator](),ie=await ue.next();return{iterator:ue,firstResult:ie}}else if(x==="NVIDIA"||ee){let ue=Vo(ee?Z:R,de("nvidia_janitor_fallback"),M,k,"Fast",b,!1,null,.7)[Symbol.asyncIterator](),ie=await ue.next();return{iterator:ue,firstResult:ie}}else if(x==="InferX"){let ue=Yo(R,targetModel||de("inferx_fallback")||"deepseek-v4-flash",M,k,"Fast",b,!1,null,.7)[Symbol.asyncIterator](),ie=await ue.next();return{iterator:ue,firstResult:ie}}else if(x==="SenseNova"){let ue=qo(R,targetModel||de("sensenova_fallback")||"sensenova-6.8-flash-lite",M,k,"Fast",b,!1,null,.7)[Symbol.asyncIterator](),ie=await ue.next();return{iterator:ue,firstResult:ie}}else if(x==="AIHubMix"){let ue=zo(R,targetModel||de("aihubmix_fallback")||"gpt-4o-mini",M,k,"Fast",b,!1,null,.7)[Symbol.asyncIterator](),ie=await ue.next();return{iterator:ue,firstResult:ie}}else if(x==="Poolside"){let ue=Jo(R,targetModel||de("poolside_fallback")||"poolside/laguna-s-2.1",M,k,"Fast",b,!1,null,.7)[Symbol.asyncIterator](),ie=await ue.next();return{iterator:ue,firstResult:ie}}else if(x==="9router"||x==="9Router"){let ue=Xo(R,targetModel||de("9router_fallback")||"z-ai/glm-5.3-flash",M,k,"Fast",b,!1,null,.7)[Symbol.asyncIterator](),ie=await ue.next();return{iterator:ue,firstResult:ie}}else if(x==="ExpLabs"||x==="ExperientialLabs"){let ue=Qo(R,targetModel||de("explabs_fallback")||"deepseek-v4-pro-0813",M,k,"Fast",b,!1,null,.7)[Symbol.asyncIterator](),ie=await ue.next();return{iterator:ue,firstResult:ie}}else{let ie=(await Vs(R).models.generateContentStream({model:i||(Ee===se?de("janitor_default"):de("gemma_janitor_fallback_google")),contents:M,config:{systemInstruction:k,temperature:.7,safetySettings:[{category:En.HARM_CATEGORY_HARASSMENT,threshold:_n.BLOCK_NONE},{category:En.HARM_CATEGORY_HATE_SPEECH,threshold:_n.BLOCK_NONE},{category:En.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:_n.BLOCK_NONE},{category:En.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:_n.BLOCK_NONE}],thinkingConfig:{includeThoughts:!1,thinkingLevel:Je.MINIMAL}}}))[Symbol.asyncIterator](),vt=await ie.next();return{iterator:ie,firstResult:vt}}})();if(process.stdout.isTTY){let ie=(await hs())[l]?.name||"",vt=ie&&!ie.startsWith("flow-")&&!ie.startsWith("Session ")?ie:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${vt}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${vt}\x07`)}let{iterator:At,firstResult:xn}=await Promise.race([pt,Ge]),{value:Yt,done:ct}=xn;if(!ct&&Yt){let fe=Yt.candidates?.[0]?.content?.parts,ue=fe?Y==="Google"?fe[1]?.text||fe[0]?.text||"":fe.filter(ie=>ie.text&&!ie.thought).map(ie=>ie.text).join(""):typeof Yt.text=="function"?Yt.text():"";ue&&(v+=ue),G=Yt.usageMetadata;for await(let ie of{[Symbol.asyncIterator]:()=>At}){let vt=ie.candidates?.[0]?.content?.parts,Fn=vt?Y==="Google"?vt[1]?.text||vt[0]?.text||"":vt.filter(wt=>wt.text&&!wt.thought).map(wt=>wt.text).join(""):typeof ie.text=="function"?ie.text():"";Fn&&(v+=Fn),G=ie.usageMetadata}}}catch(Ge){throw Ge}if(v){if(A=v,G){let Ge=G.totalTokenCount||0,ft=G.cachedContentTokenCount||0,Qe=(G.candidatesTokenCount||0)+(Y==="Google"&&G.thoughtsTokenCount||0),pt=ee?de("nvidia_janitor_fallback"):Y==="DeepSeek"?de("deepseek_fast_fallback"):Y==="ExpLabs"||Y==="ExperientialLabs"?de("explabs_fallback")||"deepseek-v4-pro-0813":Y==="OpenRouter"?de("janitor_open_router"):i||(Ee===se?de("janitor_default"):de("gemma_janitor_fallback_google"));await Ft("tokens",Ge,Y,pt),ft>0&&await Ft("cachedTokens",ft,Y,pt),Qe>0&&await Ft("candidateTokens",Qe,Y,pt)}}else throw new Error("No synthesis generated by Janitor.");g&&(g(),await Et("background"));let Xe=ts(A),Ye=!1;for(let Ge of Xe){let ft=Ge.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(ft)&&(Ye=!0);let Qe={chatId:l,sessionId:l,history:s},pt=await co(ft,Ge.args,Qe);ft.toLowerCase()==="memory"&&(Ge.args.includes("action='user'")||Ge.args.includes('action="user"'))&&!pt.startsWith("ERROR")&&(m&&m(),process.stdout.isTTY&&(process.stdout.write("\x1B]0;Memory Updated\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=Memory Updated\x07")),await new Promise(xn=>setTimeout(xn,3e3)))}if(!Ye)try{let Ge=_t(On,[]);if(Ge.length>0){let ft=[];for(let Qe of Ge)Qe.score===void 0&&(Qe.score=.5),Qe.score*=.99995,Qe.score<.05&&(Qe.score=0),Qe.score=Math.round(Qe.score*1e5)/1e5,Qe.score>0&&ft.push(Qe);jn(On,ft)}}catch{}break}catch(v){Ee++;let G=new Date().toLocaleString(),ee=v instanceof Error?(()=>{try{return JSON.parse(JSON.parse(v.message).error.message).error.message}catch{return String(v)}})():String(v);await new Promise(Ye=>setTimeout(Ye,1e3));let Y=J.join(wn,"janitor");if(Pe.existsSync(Y)||Pe.mkdirSync(Y,{recursive:!0}),Pe.appendFileSync(J.join(Y,"error.log"),`ERROR [Attempt ${Ee}/${se+1}] [${G}]: ${ee}
624
+ [AGENT (current turn)]: ${E}`;I.push({role:"user",parts:[{text:D}]});let ee=await us("NVIDIA"),B=(await eo()).quotas?.providerTiers?.NVIDIA==="Free",A="",Se=0,X=N?12:-1;for(;Se<=X;)try{if(!await ii("background",e))return;let C="",G=null,te=!1,Y=b;try{let Ge=new Promise((fe,ue)=>setTimeout(()=>ue(new Error("JANITOR_TIMEOUT")),1e4)),ft=b==="Google"&&Se>=0&&Se<6&&ee&&B,Qe=b==="DeepSeek"&&Se<4&&ee&&B;te=ft||Qe,Y=te?"NVIDIA":b;let pt=(async()=>{if(b==="OpenRouter"){let fe=de("janitor_open_router"),ie=Ko(v,fe,I,k,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),vt=await ie.next();return{iterator:ie,firstResult:vt}}else if(b==="DeepSeek"&&!te){let ue=Go(v,de("deepseek_fast_fallback"),I,k,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),ie=await ue.next();return{iterator:ue,firstResult:ie}}else if(b==="Mistral"&&!te){let ue=jo(v,de("mistral_janitor_fallback"),I,k,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),ie=await ue.next();return{iterator:ue,firstResult:ie}}else if(b==="NVIDIA"||te){let ue=Vo(te?ee:v,de("nvidia_janitor_fallback"),I,k,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),ie=await ue.next();return{iterator:ue,firstResult:ie}}else if(b==="InferX"){let ue=Yo(v,targetModel||de("inferx_fallback")||"deepseek-v4-flash",I,k,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),ie=await ue.next();return{iterator:ue,firstResult:ie}}else if(b==="SenseNova"){let ue=qo(v,targetModel||de("sensenova_fallback")||"sensenova-6.8-flash-lite",I,k,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),ie=await ue.next();return{iterator:ue,firstResult:ie}}else if(b==="AIHubMix"){let ue=zo(v,targetModel||de("aihubmix_fallback")||"gpt-4o-mini",I,k,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),ie=await ue.next();return{iterator:ue,firstResult:ie}}else if(b==="Poolside"){let ue=Jo(v,targetModel||de("poolside_fallback")||"poolside/laguna-s-2.1",I,k,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),ie=await ue.next();return{iterator:ue,firstResult:ie}}else if(b==="9router"||b==="9Router"){let ue=Xo(v,targetModel||de("9router_fallback")||"z-ai/glm-5.3-flash",I,k,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),ie=await ue.next();return{iterator:ue,firstResult:ie}}else if(b==="ExpLabs"||b==="ExperientialLabs"){let ue=Qo(v,targetModel||de("explabs_fallback")||"deepseek-v4-pro-0813",I,k,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),ie=await ue.next();return{iterator:ue,firstResult:ie}}else{let ie=(await Vs(v).models.generateContentStream({model:i||(Se===X?de("janitor_default"):de("gemma_janitor_fallback_google")),contents:I,config:{systemInstruction:k,temperature:.7,safetySettings:[{category:En.HARM_CATEGORY_HARASSMENT,threshold:_n.BLOCK_NONE},{category:En.HARM_CATEGORY_HATE_SPEECH,threshold:_n.BLOCK_NONE},{category:En.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:_n.BLOCK_NONE},{category:En.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:_n.BLOCK_NONE}],thinkingConfig:{includeThoughts:!1,thinkingLevel:Je.MINIMAL}}}))[Symbol.asyncIterator](),vt=await ie.next();return{iterator:ie,firstResult:vt}}})();if(process.stdout.isTTY){let ie=(await hs())[l]?.name||"",vt=ie&&!ie.startsWith("flow-")&&!ie.startsWith("Session ")?ie:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${vt}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${vt}\x07`)}let{iterator:At,firstResult:xn}=await Promise.race([pt,Ge]),{value:Yt,done:ct}=xn;if(!ct&&Yt){let fe=Yt.candidates?.[0]?.content?.parts,ue=fe?Y==="Google"?fe[1]?.text||fe[0]?.text||"":fe.filter(ie=>ie.text&&!ie.thought).map(ie=>ie.text).join(""):typeof Yt.text=="function"?Yt.text():"";ue&&(C+=ue),G=Yt.usageMetadata;for await(let ie of{[Symbol.asyncIterator]:()=>At}){let vt=ie.candidates?.[0]?.content?.parts,Fn=vt?Y==="Google"?vt[1]?.text||vt[0]?.text||"":vt.filter(wt=>wt.text&&!wt.thought).map(wt=>wt.text).join(""):typeof ie.text=="function"?ie.text():"";Fn&&(C+=Fn),G=ie.usageMetadata}}}catch(Ge){throw Ge}if(C){if(A=C,G){let Ge=G.totalTokenCount||0,ft=G.cachedContentTokenCount||0,Qe=(G.candidatesTokenCount||0)+(Y==="Google"&&G.thoughtsTokenCount||0),pt=te?de("nvidia_janitor_fallback"):Y==="DeepSeek"?de("deepseek_fast_fallback"):Y==="ExpLabs"||Y==="ExperientialLabs"?de("explabs_fallback")||"deepseek-v4-pro-0813":Y==="OpenRouter"?de("janitor_open_router"):i||(Se===X?de("janitor_default"):de("gemma_janitor_fallback_google"));await Ft("tokens",Ge,Y,pt),ft>0&&await Ft("cachedTokens",ft,Y,pt),Qe>0&&await Ft("candidateTokens",Qe,Y,pt)}}else throw new Error("No synthesis generated by Janitor.");g&&(g(),await Et("background"));let Xe=ts(A),Ye=!1;for(let Ge of Xe){let ft=Ge.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(ft)&&(Ye=!0);let Qe={chatId:l,sessionId:l,history:s},pt=await uo(ft,Ge.args,Qe);ft.toLowerCase()==="memory"&&(Ge.args.includes("action='user'")||Ge.args.includes('action="user"'))&&!pt.startsWith("ERROR")&&(h&&h(),process.stdout.isTTY&&(process.stdout.write("\x1B]0;Memory Updated\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=Memory Updated\x07")),await new Promise(xn=>setTimeout(xn,3e3)))}if(!Ye)try{let Ge=_t(On,[]);if(Ge.length>0){let ft=[];for(let Qe of Ge)Qe.score===void 0&&(Qe.score=.5),Qe.score*=.99995,Qe.score<.05&&(Qe.score=0),Qe.score=Math.round(Qe.score*1e5)/1e5,Qe.score>0&&ft.push(Qe);jn(On,ft)}}catch{}break}catch(C){Se++;let G=new Date().toLocaleString(),te=C instanceof Error?(()=>{try{return JSON.parse(JSON.parse(C.message).error.message).error.message}catch{return String(C)}})():String(C);await new Promise(Ye=>setTimeout(Ye,1e3));let Y=J.join(wn,"janitor");if($e.existsSync(Y)||$e.mkdirSync(Y,{recursive:!0}),$e.appendFileSync(J.join(Y,"error.log"),`ERROR [Attempt ${Se}/${X+1}] [${G}]: ${te}
624
625
 
625
- `),Ee>se)break;let Xe=Math.min(750*Math.pow(2,Ee-1),5e3);await new Promise(Ye=>setTimeout(Ye,Xe))}if(Ee){let v=J.join(wn,"janitor");Pe.appendFileSync(J.join(v,"error.log"),`-----------------------------------------------------------------------------
626
+ `),Se>X)break;let Xe=Math.min(750*Math.pow(2,Se-1),5e3);await new Promise(Ye=>setTimeout(Ye,Xe))}if(Se){let C=J.join(wn,"janitor");$e.appendFileSync(J.join(C,"error.log"),`-----------------------------------------------------------------------------
626
627
 
627
- `)}if(process.stdout.isTTY)try{let ee=(await hs())[l]?.name||"",Y=ee&&!ee.startsWith("flow-")&&!ee.startsWith("Session ")?ee:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${Y}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${Y}\x07`)}catch{process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")}},Oa=e=>{let t=Kt(e),n=ms?t:t.replace(Mr,o=>" ".repeat(o.length)).replace(Ir,o=>" ".repeat(o.length));go.lastIndex=0;let s;for(;(s=go.exec(n))!==null;){let o=s.index+s[0].length-1,d=0,f=null,a=!1,m=!1;for(let g=o;g<n.length;g++){let u=t[g];if(!f&&(u==='"'||u==="'"||u==="`")?(f=u,a=!1):f&&u===f&&!a&&(f=null),!f&&(u==="("?d++:u===")"&&d--,d===0)){let h=g+1;for(;h<n.length&&/\s/.test(n[h]);)h++;if(h<n.length&&n[h]==="]"){m=!0,go.lastIndex=h+1;break}}u==="\\"?a=!a:a=!1}if(!m)return{inside:!0,toolName:s[1],startIndex:s.index,args:t.substring(s.index+s[0].length)}}return{inside:!1}},Dr=(e,t=!0)=>{let n=go;n.lastIndex=0;let s="",o=0,d;for(;(d=n.exec(e))!==null;){let f=e.substring(o,d.index);s+=t&&o===0?Kt(f):f;let a=d.index+d[0].length-1,m=0,g=null,u=-1;for(let h=a;h<e.length;h++){let b=e[h];if(g){if(b===g){let i=0;for(let l=h-1;l>=0&&e[l]==="\\";l--)i++;i%2===0&&(g=null)}}else if(b==='"'||b==="'"||b==="`")g=b;else if(b==="(")m++;else if(b===")"&&(m--,m===0)){let i=h+1;for(;i<e.length&&/\s/.test(e[i]);)i++;if(i<e.length&&e[i]==="]"){u=i;break}}}if(u!==-1)s+="[tool:functions."+d[1]+"()]",o=u+1,n.lastIndex=o;else{s+="[tool:functions."+d[1]+"(",o=e.length;break}}return o<e.length&&(s+=t&&o===0?Kt(e.substring(o)):e.substring(o)),s},La=(e,t,n)=>{let s=go;s.lastIndex=0;let o="",d=0,f;for(;(f=s.exec(e))!==null;){let a=e.substring(d,f.index);o+=a.replace(t,n);let m=f.index+f[0].length-1,g=0,u=null,h=-1;for(let b=m;b<e.length;b++){let i=e[b];if(u){if(i===u){let l=0;for(let _=b-1;_>=0&&e[_]==="\\";_--)l++;l%2===0&&(u=null)}}else if(i==='"'||i==="'"||i==="`")u=i;else if(i==="(")g++;else if(i===")"&&(g--,g===0)){let l=b+1;for(;l<e.length&&/\s/.test(e[l]);)l++;if(l<e.length&&e[l]==="]"){h=l;break}}}if(h!==-1)o+=e.substring(f.index,h+1),d=h+1,s.lastIndex=d;else{o+=e.substring(f.index),d=e.length;break}}return d<e.length&&(o+=e.substring(d).replace(t,n)),o},Rr=e=>Dr(e,!0),Pa=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(d=>d.charAt(0).toUpperCase()+d.slice(1)).join("");_r.lastIndex=0;let s=e.replace(_r,(o,d,f)=>{let a="";try{let u=JSON.parse(f.trim());u&&typeof u=="object"&&(a=Object.entries(u).map(([b,i])=>{let l=typeof i=="string"?i:JSON.stringify(i);return`${b}=${JSON.stringify(l)}`}).join(", "))}catch{let h=[],b=Ra;b.lastIndex=0;let i;for(;(i=b.exec(f))!==null;){let l=i[1],_=i[2]!==void 0?i[2]:i[0].split(":").slice(1).join(":").trim();h.push(`${l}=${JSON.stringify(_)}`)}h.length>0?a=h.join(", "):a=f.trim()}let m=d.toLowerCase().replace(/_/g,"");return`[tool:functions.${t[m]||n(d)}(${a})]`});return Er.lastIndex=0,Ar.lastIndex=0,s=s.replace(Er,""),s=s.replace(Ar,""),s},$a=/(?:path|query|url|keyword|command|method|title|task|id)\s*=\s*['"`]?\s*\.\.\.\s*['"`]?/i,Na=/^['"`]?\s*\.\.\.\s*['"`]?$/,yn=e=>{if(e==null)return!1;let t=String(e).trim();return t==="..."||t==="\u2026"||Na.test(t)},ts=e=>{if(!e)return[];let t=Pa(e),n=Kt(t),s=[],o=ms?n:n.replace(Mr,a=>" ".repeat(a.length)).replace(Ir,a=>" ".repeat(a.length)),d=wa;d.lastIndex=0;let f;for(;(f=d.exec(o))!==null;){let a=f[1],m=f.index+f[0].length-1,g=0,u=null,h=-1,b=-1;for(let i=m;i<o.length;i++){let l=n[i];if(u){if(l===u){let _=0;for(let C=i-1;C>=0&&n[C]==="\\";C--)_++;_%2===0&&(u=null)}}else if(l==='"'||l==="'"||l==="`")u=l;else if(l==="(")g++;else if(l===")"&&(g--,g===0)){b=i;let _=i+1;for(;_<o.length&&/\s/.test(o[_]);)_++;if(_<o.length&&o[_]==="]"){h=_;break}}}if(h!==-1){let i=n.substring(m+1,b),l=n.substring(f.index,h+1),_=Q(i);yn(_.path)||yn(_.query)||yn(_.url)||yn(_.keyword)||yn(_.command)||yn(_.method)||yn(_.title)||yn(_.task)||yn(_.id)||$a.test(i)||s.push({fullMatch:l,toolName:a.trim(),args:i.trim()}),d.lastIndex=h+1}}return s},Gd=(e,t={})=>{if(!e)return null;if(Zo=t,js=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}}}},es=async(e,t,n,s,o="Fast",d=.75,f="agent")=>Ma(async()=>{let{aiProvider:a="Google",apiKey:m,mode:g}=e,u="",h=null,b=typeof n=="string"?[{role:"user",parts:[{text:n}]}]:n,i=new AbortController,l=i.signal,_=setInterval(()=>{kt&&(i.abort(),clearInterval(_))},100);try{let C;a==="Ollama"?C=Bs(m,t,b,s,o,g,dt(t),l,d,systemSettings?.ollamaEndpoint||"Cloud"):a==="OpenRouter"?C=Ko(m,t,b,s,o,g,dt(t),l,d):a==="DeepSeek"?C=Go(m,t,b,s,o,g,dt(t),l,d):a==="Mistral"?C=jo(m,t,b,s,o,g,dt(t),l,d):a==="NVIDIA"?C=Vo(m,t,b,s,o,g,dt(t),l,d):a==="InferX"?C=Yo(m,t,b,s,o,g,dt(t),l,d):a==="SenseNova"?C=qo(m,t,b,s,o,g,dt(t),l,d):a==="AIHubMix"?C=zo(m,t,b,s,o,g,dt(t),l,d):a==="Poolside"?C=Jo(m,t,b,s,o,g,dt(t),l,d):a==="9router"||a==="9Router"?C=Xo(m,t,b,s,o,g,dt(t),l,d):a==="ExpLabs"||a==="ExperientialLabs"?C=Qo(m,t,b,s,o,g,dt(t),l,d):a==="TokenHarbor"||a==="Token Harbor"||a==="tokenharbor"||a==="token_harbor"||a==="thk"?C=Us(m,t,b,s,o,g,dt(t),l,d):a==="APInex"||a==="apinex"||a==="apx"?C=Ws(m,t,b,s,o,g,dt(t),l,d):C=await Vs(m).models.generateContentStream({model:t,contents:b,config:{systemInstruction:s,temperature:d,thinkingConfig:(()=>{let N=(t||"").toLowerCase(),D=N.includes("gemma-4")||N.startsWith("gemma"),S=N.includes("gemini-3");if(D||S)return D?o.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:Je.MINIMAL}:{includeThoughts:!0,thinkingLevel:Je.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:N.includes("pro")?Je.LOW:Je.MINIMAL,Low:Je.LOW,Medium:Je.MEDIUM,Standard:Je.MEDIUM,High:Je.HIGH,xHigh:Je.HIGH}[o]||Je.MEDIUM};{let M={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[o]||2048;return M===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:M}}})()}},{signal:l});for await(let x of C){if(kt)throw new Error("Subagent task was cancelled.");if(e?.taskId&&typeof jt<"u"){let D=jt.find(S=>S.id===e.taskId);if(D&&D.status==="cancelled")throw new Error("Subagent task was cancelled.")}let R="";if(x.candidates?.[0]?.content?.parts)for(let D of x.candidates[0].content.parts)D.text&&!D.thought&&(u+=D.text,R+=D.text);let N=R?gs(R):0;e&&typeof e.onTokenChunk=="function"&&e.onTokenChunk(R,N),x.usageMetadata&&(h=x.usageMetadata)}}finally{clearInterval(_)}if(h){let C=h.totalTokenCount||0,x=h.cachedContentTokenCount||0,R=(h.candidatesTokenCount||0)+(a==="Google"&&h.thoughtsTokenCount||0);await Ft("tokens",C,a,t),x>0&&await Ft("cachedTokens",x,a,t),R>0&&await Ft("candidateTokens",R,a,t),e&&typeof e.onUsage=="function"&&e.onUsage({totalTokenCount:C,cachedContentTokenCount:x,candidatesTokenCount:R})}return await Et("agent",a),{text:u,usageMetadata:h}}),Fa=async(e,t,n=null)=>{n=n||_t(To,{});try{let{aiProvider:s="Google"}=t;if(Object.values(n).flat().length<=5)return;let d=Object.keys(n).filter(b=>b!==e&&Array.isArray(n[b])&&n[b].length>2);if(d.length===0)return;let f=`You are a silent background process for the FluxFlow CLI Agent.
628
+ `)}if(process.stdout.isTTY)try{let te=(await hs())[l]?.name||"",Y=te&&!te.startsWith("flow-")&&!te.startsWith("Session ")?te:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${Y}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${Y}\x07`)}catch{process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")}},La=e=>{let t=Kt(e),n=ms?t:t.replace(Mr,o=>" ".repeat(o.length)).replace(Ir,o=>" ".repeat(o.length));mo.lastIndex=0;let s;for(;(s=mo.exec(n))!==null;){let o=s.index+s[0].length-1,d=0,f=null,a=!1,h=!1;for(let g=o;g<n.length;g++){let u=t[g];if(!f&&(u==='"'||u==="'"||u==="`")?(f=u,a=!1):f&&u===f&&!a&&(f=null),!f&&(u==="("?d++:u===")"&&d--,d===0)){let m=g+1;for(;m<n.length&&/\s/.test(n[m]);)m++;if(m<n.length&&n[m]==="]"){h=!0,mo.lastIndex=m+1;break}}u==="\\"?a=!a:a=!1}if(!h)return{inside:!0,toolName:s[1],startIndex:s.index,args:t.substring(s.index+s[0].length)}}return{inside:!1}},Dr=(e,t=!0)=>{let n=mo;n.lastIndex=0;let s="",o=0,d;for(;(d=n.exec(e))!==null;){let f=e.substring(o,d.index);s+=t&&o===0?Kt(f):f;let a=d.index+d[0].length-1,h=0,g=null,u=-1;for(let m=a;m<e.length;m++){let x=e[m];if(g){if(x===g){let i=0;for(let l=m-1;l>=0&&e[l]==="\\";l--)i++;i%2===0&&(g=null)}}else if(x==='"'||x==="'"||x==="`")g=x;else if(x==="(")h++;else if(x===")"&&(h--,h===0)){let i=m+1;for(;i<e.length&&/\s/.test(e[i]);)i++;if(i<e.length&&e[i]==="]"){u=i;break}}}if(u!==-1)s+="[tool:functions."+d[1]+"()]",o=u+1,n.lastIndex=o;else{s+="[tool:functions."+d[1]+"(",o=e.length;break}}return o<e.length&&(s+=t&&o===0?Kt(e.substring(o)):e.substring(o)),s},Pa=(e,t,n)=>{let s=mo;s.lastIndex=0;let o="",d=0,f;for(;(f=s.exec(e))!==null;){let a=e.substring(d,f.index);o+=a.replace(t,n);let h=f.index+f[0].length-1,g=0,u=null,m=-1;for(let x=h;x<e.length;x++){let i=e[x];if(u){if(i===u){let l=0;for(let T=x-1;T>=0&&e[T]==="\\";T--)l++;l%2===0&&(u=null)}}else if(i==='"'||i==="'"||i==="`")u=i;else if(i==="(")g++;else if(i===")"&&(g--,g===0)){let l=x+1;for(;l<e.length&&/\s/.test(e[l]);)l++;if(l<e.length&&e[l]==="]"){m=l;break}}}if(m!==-1)o+=e.substring(f.index,m+1),d=m+1,s.lastIndex=d;else{o+=e.substring(f.index),d=e.length;break}}return d<e.length&&(o+=e.substring(d).replace(t,n)),o},Rr=e=>Dr(e,!0),$a=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(d=>d.charAt(0).toUpperCase()+d.slice(1)).join("");_r.lastIndex=0;let s=e.replace(_r,(o,d,f)=>{let a="";try{let u=JSON.parse(f.trim());u&&typeof u=="object"&&(a=Object.entries(u).map(([x,i])=>{let l=typeof i=="string"?i:JSON.stringify(i);return`${x}=${JSON.stringify(l)}`}).join(", "))}catch{let m=[],x=va;x.lastIndex=0;let i;for(;(i=x.exec(f))!==null;){let l=i[1],T=i[2]!==void 0?i[2]:i[0].split(":").slice(1).join(":").trim();m.push(`${l}=${JSON.stringify(T)}`)}m.length>0?a=m.join(", "):a=f.trim()}let h=d.toLowerCase().replace(/_/g,"");return`[tool:functions.${t[h]||n(d)}(${a})]`});return Er.lastIndex=0,Ar.lastIndex=0,s=s.replace(Er,""),s=s.replace(Ar,""),s},Na=/(?:path|query|url|keyword|command|method|title|task|id)\s*=\s*['"`]?\s*\.\.\.\s*['"`]?/i,Fa=/^['"`]?\s*\.\.\.\s*['"`]?$/,yn=e=>{if(e==null)return!1;let t=String(e).trim();return t==="..."||t==="\u2026"||Fa.test(t)},ts=e=>{if(!e)return[];let t=$a(e),n=Kt(t),s=[],o=ms?n:n.replace(Mr,a=>" ".repeat(a.length)).replace(Ir,a=>" ".repeat(a.length)),d=Ta;d.lastIndex=0;let f;for(;(f=d.exec(o))!==null;){let a=f[1],h=f.index+f[0].length-1,g=0,u=null,m=-1,x=-1;for(let i=h;i<o.length;i++){let l=n[i];if(u){if(l===u){let T=0;for(let R=i-1;R>=0&&n[R]==="\\";R--)T++;T%2===0&&(u=null)}}else if(l==='"'||l==="'"||l==="`")u=l;else if(l==="(")g++;else if(l===")"&&(g--,g===0)){x=i;let T=i+1;for(;T<o.length&&/\s/.test(o[T]);)T++;if(T<o.length&&o[T]==="]"){m=T;break}}}if(m!==-1){let i=n.substring(h+1,x),l=n.substring(f.index,m+1),T=Z(i);yn(T.path)||yn(T.query)||yn(T.url)||yn(T.keyword)||yn(T.command)||yn(T.method)||yn(T.title)||yn(T.task)||yn(T.id)||Na.test(i)||s.push({fullMatch:l,toolName:a.trim(),args:i.trim()}),d.lastIndex=m+1}}return s},Kd=(e,t={})=>{if(!e)return null;if(Zo=t,js=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}}}},es=async(e,t,n,s,o="Fast",d=.75,f="agent")=>Ia(async()=>{let{aiProvider:a="Google",apiKey:h,mode:g}=e,u="",m=null,x=typeof n=="string"?[{role:"user",parts:[{text:n}]}]:n,i=new AbortController,l=i.signal,T=setInterval(()=>{kt&&(i.abort(),clearInterval(T))},100);try{let R;a==="Ollama"?R=Bs(h,t,x,s,o,g,dt(t),l,d,systemSettings?.ollamaEndpoint||"Cloud"):a==="OpenRouter"?R=Ko(h,t,x,s,o,g,dt(t),l,d):a==="DeepSeek"?R=Go(h,t,x,s,o,g,dt(t),l,d):a==="Mistral"?R=jo(h,t,x,s,o,g,dt(t),l,d):a==="NVIDIA"?R=Vo(h,t,x,s,o,g,dt(t),l,d):a==="InferX"?R=Yo(h,t,x,s,o,g,dt(t),l,d):a==="SenseNova"?R=qo(h,t,x,s,o,g,dt(t),l,d):a==="AIHubMix"?R=zo(h,t,x,s,o,g,dt(t),l,d):a==="Poolside"?R=Jo(h,t,x,s,o,g,dt(t),l,d):a==="9router"||a==="9Router"?R=Xo(h,t,x,s,o,g,dt(t),l,d):a==="ExpLabs"||a==="ExperientialLabs"?R=Qo(h,t,x,s,o,g,dt(t),l,d):a==="TokenHarbor"||a==="Token Harbor"||a==="tokenharbor"||a==="token_harbor"||a==="thk"?R=Us(h,t,x,s,o,g,dt(t),l,d):a==="APInex"||a==="apinex"||a==="apx"?R=Ws(h,t,x,s,o,g,dt(t),l,d):R=await Vs(h).models.generateContentStream({model:t,contents:x,config:{systemInstruction:s,temperature:d,thinkingConfig:(()=>{let N=(t||"").toLowerCase(),M=N.includes("gemma-4")||N.startsWith("gemma"),S=N.includes("gemini-3");if(M||S)return M?o.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:Je.MINIMAL}:{includeThoughts:!0,thinkingLevel:Je.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:N.includes("pro")?Je.LOW:Je.MINIMAL,Low:Je.LOW,Medium:Je.MEDIUM,Standard:Je.MEDIUM,High:Je.HIGH,xHigh:Je.HIGH}[o]||Je.MEDIUM};{let I={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[o]||2048;return I===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:I}}})()}},{signal:l});for await(let b of R){if(kt)throw new Error("Subagent task was cancelled.");if(e?.taskId&&typeof jt<"u"){let M=jt.find(S=>S.id===e.taskId);if(M&&M.status==="cancelled")throw new Error("Subagent task was cancelled.")}let v="";if(b.candidates?.[0]?.content?.parts)for(let M of b.candidates[0].content.parts)M.text&&!M.thought&&(u+=M.text,v+=M.text);let N=v?gs(v):0;e&&typeof e.onTokenChunk=="function"&&e.onTokenChunk(v,N),b.usageMetadata&&(m=b.usageMetadata)}}finally{clearInterval(T)}if(m){let R=m.totalTokenCount||0,b=m.cachedContentTokenCount||0,v=(m.candidatesTokenCount||0)+(a==="Google"&&m.thoughtsTokenCount||0);await Ft("tokens",R,a,t),b>0&&await Ft("cachedTokens",b,a,t),v>0&&await Ft("candidateTokens",v,a,t),e&&typeof e.onUsage=="function"&&e.onUsage({totalTokenCount:R,cachedContentTokenCount:b,candidatesTokenCount:v})}return await Et("agent",a),{text:u,usageMetadata:m}}),Ba=async(e,t,n=null)=>{n=n||_t(So,{});try{let{aiProvider:s="Google"}=t;if(Object.values(n).flat().length<=5)return;let d=Object.keys(n).filter(x=>x!==e&&Array.isArray(n[x])&&n[x].length>2);if(d.length===0)return;let f=`You are a silent background process for the FluxFlow CLI Agent.
628
629
  Your task is to summarize or merge temporary context memories from one or more past conversation sessions.
629
630
  For each Chat ID provided, you must output a tool call to save the consolidated summary.
630
631
 
@@ -639,9 +640,9 @@ Guidelines:
639
640
 
640
641
  Chats to process:
641
642
 
642
- `,a=_t(ds,{});for(let b of d){let l=n[b].map(C=>`- ${C}`).join(`
643
- `),_=a[b];f+=`[Chat ID: ${b}]
644
- `,_?(f+=`- Existing Summary: "${_}"
643
+ `,a=_t(ds,{});for(let x of d){let l=n[x].map(R=>`- ${R}`).join(`
644
+ `),T=a[x];f+=`[Chat ID: ${x}]
645
+ `,T?(f+=`- Existing Summary: "${T}"
645
646
  `,f+=`
646
647
  -- New Memories to integrate:
647
648
  ${l}
@@ -649,10 +650,10 @@ ${l}
649
650
  `):f+=`-- Individual Memories:
650
651
  ${l}
651
652
 
652
- `}let m=0,g=5,u=!1,h=de("gemma_janitor_fallback_google");for(s==="OpenRouter"&&(h=de("janitor_open_router")),s==="DeepSeek"&&(h=de("deepseek_level_1")),s==="Mistral"&&(h=de("mistral_level_1")),s==="NVIDIA"&&(h=de("nvidia_janitor_fallback")),s==="InferX"&&(h=de("inferx_fallback")),s==="SenseNova"&&(h=de("sensenova_fallback")),s==="AIHubMix"&&(h=de("aihubmix_fallback")),s==="Poolside"&&(h=de("poolside_fallback")),(s==="9router"||s==="9Router")&&(h=de("9router_fallback"));m<=g&&!u;){m++;try{let i=(await es(t,h,f,null,"Fast",.75,"background")).text||"",l=ts(i);if(l.length===0)throw new Error("No tool calls detected in synthesis response");for(let _ of l){let C=_.toolName;["saveSummary","saveSumary","SaveSummary","SaveSumary"].includes(C)&&await co(C,_.args,{chatId:e})}u=!0}catch(b){if(m>=g)throw new Error(`Failed after ${g} attempts. Last error: ${b.message}`)}}}catch(s){let o=s instanceof Error?(()=>{try{return JSON.parse(JSON.parse(s.message).error.message).error.message}catch{return String(s)}})():String(s),d=J.join(wn,"janitor");Pe.existsSync(d)||Pe.mkdirSync(d,{recursive:!0}),Pe.appendFileSync(J.join(d,"error.log"),`[${new Date().toLocaleString()}] Past memory batch consolidation error: ${o}
653
- `)}},jd=async(e,t,n=!1)=>{let{chatId:s,aiProvider:o="Google"}=e,d=J.join(wo,"chat-summaries.json"),f=i=>i.filter(l=>(l.role==="user"||l.role==="agent"||l.role==="system")&&l.role!=="think"&&!l.isVisualFeedback&&!l.isMeta&&!l.isTerminalRecord&&!(l.text&&l.text.includes("[TERMINAL_RECORD]"))&&!String(l.id).startsWith("welcome")).map(l=>{let _=l.fullText||l.text||"",C=l.role==="system"||_.startsWith("[TOOL RESULT]:")||l.text&&l.text.startsWith("[TOOL RESULT]:"),x=_;return C&&(_.includes("[TOOL RESULT]:")||l.text&&l.text.includes("[TOOL RESULT]:"))?x="[TOOL RESULT]: ...truncated for summary":x=x.replace(/(\[(?:tool|agent):[a-zA-Z0-9_\.]+)\([\s\S]*?\)(\])/g,"$1(...)$2"),`[${C?"TOOL":l.role==="agent"?"AGENT":"USER"}]: ${x}`}).join(`
653
+ `}let h=0,g=5,u=!1,m=de("gemma_janitor_fallback_google");for(s==="OpenRouter"&&(m=de("janitor_open_router")),s==="DeepSeek"&&(m=de("deepseek_level_1")),s==="Mistral"&&(m=de("mistral_level_1")),s==="NVIDIA"&&(m=de("nvidia_janitor_fallback")),s==="InferX"&&(m=de("inferx_fallback")),s==="SenseNova"&&(m=de("sensenova_fallback")),s==="AIHubMix"&&(m=de("aihubmix_fallback")),s==="Poolside"&&(m=de("poolside_fallback")),(s==="9router"||s==="9Router")&&(m=de("9router_fallback"));h<=g&&!u;){h++;try{let i=(await es(t,m,f,null,"Fast",.75,"background")).text||"",l=ts(i);if(l.length===0)throw new Error("No tool calls detected in synthesis response");for(let T of l){let R=T.toolName;["saveSummary","saveSumary","SaveSummary","SaveSumary"].includes(R)&&await uo(R,T.args,{chatId:e})}u=!0}catch(x){if(h>=g)throw new Error(`Failed after ${g} attempts. Last error: ${x.message}`)}}}catch(s){let o=s instanceof Error?(()=>{try{return JSON.parse(JSON.parse(s.message).error.message).error.message}catch{return String(s)}})():String(s),d=J.join(wn,"janitor");$e.existsSync(d)||$e.mkdirSync(d,{recursive:!0}),$e.appendFileSync(J.join(d,"error.log"),`[${new Date().toLocaleString()}] Past memory batch consolidation error: ${o}
654
+ `)}},Yd=async(e,t,n=!1)=>{let{chatId:s,aiProvider:o="Google"}=e,d=J.join(To,"chat-summaries.json"),f=i=>i.filter(l=>(l.role==="user"||l.role==="agent"||l.role==="system")&&l.role!=="think"&&!l.isVisualFeedback&&!l.isMeta&&!l.isTerminalRecord&&!(l.text&&l.text.includes("[TERMINAL_RECORD]"))&&!String(l.id).startsWith("welcome")).map(l=>{let T=l.fullText||l.text||"",R=l.role==="system"||T.startsWith("[TOOL RESULT]:")||l.text&&l.text.startsWith("[TOOL RESULT]:"),b=T;return R&&(T.includes("[TOOL RESULT]:")||l.text&&l.text.includes("[TOOL RESULT]:"))?b="[TOOL RESULT]: ...truncated for summary":b=b.replace(/(\[(?:tool|agent):[a-zA-Z0-9_\.]+)\([\s\S]*?\)(\])/g,"$1(...)$2"),`[${R?"TOOL":l.role==="agent"?"AGENT":"USER"}]: ${b}`}).join(`
654
655
 
655
- `),a=async(i,l)=>{let _="You are an expert context summarizer. Summarize the provided chat history (which may include previous summaries, user instructions, agent outputs, and tool results) into a detailed, coherent, and highly technical summary of 1000 to 1500 words. Focus on preserving the architectural decisions made, current system state, task progress, and critical code details, chat messages, file changes. Under no circumstances exceed MAX 2000 words.",C=l?`Here is the previous summary:
656
+ `),a=async(i,l)=>{let T="You are an expert context summarizer. Summarize the provided chat history (which may include previous summaries, user instructions, agent outputs, and tool results) into a detailed, coherent, and highly technical summary of 1000 to 1500 words. Focus on preserving the architectural decisions made, current system state, task progress, and critical code details, chat messages, file changes. Under no circumstances exceed MAX 2000 words.",R=l?`Here is the previous summary:
656
657
  ${l}
657
658
 
658
659
  Here is the new conversation history:
@@ -661,106 +662,106 @@ ${i}
661
662
  Provide a new consolidated summary of the entire session.`:`Here is the conversation history:
662
663
  ${i}
663
664
 
664
- Provide a consolidated summary of the entire session.`,x=de("gemma_janitor_fallback_google");o==="OpenRouter"&&(x=de("janitor_open_router")),o==="DeepSeek"&&(x=de("deepseek_level_1")),o==="Mistral"&&(x=de("mistral_level_1")),o==="NVIDIA"&&(x=de("nvidia_chat_summarizer_fallback")),o==="InferX"&&(x=de("inferx_fallback")),o==="SenseNova"&&(x=de("sensenova_fallback")),o==="AIHubMix"&&(x=de("aihubmix_fallback")),o==="Poolside"&&(x=de("poolside_fallback")),(o==="9router"||o==="9Router")&&(x=de("9router_fallback")),(o==="ExpLabs"||o==="ExperientialLabs")&&(x=de("explabs_fallback")||"deepseek-v4-pro-0813"),(o==="TokenHarbor"||o==="Token Harbor"||o==="tokenharbor"||o==="token_harbor"||o==="thk")&&(x=de("tokenharbor_fallback")||"deepseek-v4.1-flash:free");let R=0,N=!1,D=null;for(;R<=3&&!N;){R++;try{D=await es(e,x,C,_,"Fast"),N=!0}catch{if(R>3){if(o==="Google")try{let M=de("general_fallback");return(await es(e,M,C,_,"Fast")).text||""}catch{return""}return""}}}return D&&D.text||""},m=f(t),g=_t(d,{}),u=g[s]||{summary:"",historyLength:0};typeof u=="string"&&(u={summary:u,historyLength:0});let h=u.summary||"",b=await a(m,h);if(b){u.summary=b;let i=Ia(t);return n?u.historyLength=(u.historyLength||0)+i:u.historyLength=i,g[s]=u,jn(d,g),b}return null},Vd=e=>{try{let t=J.join(wo,"chat-summaries.json");if(Pe.existsSync(t)){let n=_t(t,{});n[e]&&(delete n[e],jn(t,n))}}catch{}},Kd=async function*(e,t,n,s,o){let{profile:d,thinkingLevel:f,mode:a,janitorModel:m,chatId:g,isPlayground:u,systemSettings:h,sessionStats:b,aiProvider:i="Google",apiTier:l,wildcardTooling:_}=n,C=dt(e);if(!js&&i==="Google")throw new Error("AI not initialized");let x=process.env.NVIDIA_BASE_URL||n?.aiProvider==="Ollama"||n?.aiProvider==="InferX"||n?.aiProvider==="SenseNova"||n?.aiProvider==="AIHubMix"||n?.aiProvider==="Poolside"||n?.aiProvider==="9router"||n?.aiProvider==="ExpLabs"||n?.aiProvider==="ExperientialLabs"||n?.aiProvider==="TokenHarbor"||n?.aiProvider==="Token Harbor"||n?.aiProvider==="tokenharbor"||n?.aiProvider==="token_harbor"||n?.aiProvider==="thk"||n?.aiProvider==="APInex"||n?.aiProvider==="apinex"||n?.aiProvider==="apx"?!1:h?.memory!==!1,R=t[t.length-1].text,N=J.join(wo,"chat-summaries.json"),D=!1,S=t.filter(w=>w.role==="user").length===1,M=R.includes("[TITLE-UPDATE]"),$=S||M,p=R.replace(/\[TITLE-UPDATE\]/g,"").trim();p=p.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),yield{type:"status",content:"[start]"},yield{type:"status",content:"Gathering Context"},await _o.startTransaction(g,p),h?.advanceRollback&&await to.takeInitialSnapshot(g),kt=!1;let c=null;try{let w=new AbortController;c=setInterval(()=>{kt&&(w.abort(),c&&(clearInterval(c),c=null))},400);let r=[...t.slice(0,-1)];{let Le=_t(N,{})[g]||{summary:"",historyLength:0};if(Le.summary&&Le.historyLength>0){let qt=0,Se=[];for(let nt=0;nt<r.length;nt++){let je=r[nt];(je.role==="user"||je.role==="agent"||je.role==="system")&&!String(je.id).startsWith("welcome")&&!je.isMeta&&qt++,qt>Le.historyLength&&Se.push(je)}r=Se}}r=r.map(K=>{if(K.role==="user"&&K.text){let Le=K.text.match(/\[USER\]([\s\S]*?)\[\/USER\]/);if(Le)return{...K,text:Le[1].trim()}}return{...K}});let k=process.env.HIGH_CONTEXT,E=process.env.GOOGLE_GEMMA_NONSENSE==="true"||process.env.GOOGLE_GEMMA_NONSENSE===!0||!1,P={"16k":16e3,"32k":32e3,"64k":64e3,"128k":128e3,"256k":256e3,"512k":512e3,"1M":1e6}[h?.contextLength]||256e3;if(k&&k!=="false"){let K=parseInt(k,10);!isNaN(K)&&K>=0&&K<=1e6&&(P=K)}if((i==="NVIDIA"&&(e?.includes("gpt")||e?.includes("qwen")||e?.includes("medium")||e.includes("muse"))||i==="Mistral")&&(P=126e3),i==="Google"&&e?.includes("gemma")&&E&&(P=16e3),(b?.tokens||0)>P){yield{type:"text",content:"\u2726 Maximum Context Limit Reached. Start a new chat."};return}if(S&&x){let K=_t(To,{});Object.values(K).flat().length>5&&(yield{type:"status",content:"Condensing past chat memories"},await Fa(g,n,K))}let I=_t(To,{}),Z=_t(ds,{}),ke=Object.entries(I).filter(([K])=>K!==g).flatMap(([K,Le])=>Le),A=[...Object.entries(Z).filter(([K])=>K!==g).slice(-20).map(([K,Le])=>`[Chat Summary]: ${Le}`),...ke].map(K=>`- ${K}`).join(`
665
- `),se=_t(On,[]).map(K=>`- ${K.memory}`).join(`
666
- `),v=(b?.tokens||0)>=1e4,G=Ki(A,se,x,v),ee=new Date,Y=ee.getFullYear(),Xe=ee.toLocaleString("en-US",{month:"short"}).toUpperCase(),Ye=String(ee.getDate()).padStart(2,"0"),Ge=ee.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}),ft=`${Y}-${Xe}-${Ye}, ${Ge}`,Qe=`${Ge}`,pt=[".git","node_modules",".gemini","dist","build",".next","out",".cache","bin","obj","vendor","venv",".idea",".gradle",".terraform","target","coverage",".vscode",".svn",".hg",".fslckout",".github",".gitlab",".circleci",".gitea",".gitee",".lerna",".changeset",".nx",".npm",".yarn",".pnpm-store",".pnpm",".expo",".nuxt",".svelte-kit",".docusaurus",".turbo",".vercel","bower_components",".netlify",".vuepress",".quasar",".output",".angular","jspm_packages",".parcel-cache",".rollup.cache",".rspack",".vitepress","__pycache__",".pytest_cache",".mypy_cache",".tox",".poetry","env","vhdl",".ipynb_checkpoints",".jupyter",".conda",".pdm-build",".bundle",".yardoc",".metadata","App_Data","ClientBin",".cargo",".rustc_info",".go","Godeps","_vendor",".rake_tasks","CMakefiles",".wakatime",".dart_tool",".fvm",".cocoapods","Pods",".pub-cache",".symlinks","DerivedData",".xcworkspace",".serverless",".aws",".gcloud",".azure",".kube",".vagrant",".docker","postgres-data","redis-data","mongo-data",".Spotlight-V100",".Trashes","$RECYCLE.BIN","System Volume Information",".DocumentRevisions-V100",".fseventsd","AppData","Application Data","Local","LocalLow","Roaming","$WinREAgent","$WINDOWS.~BT","$WINDOWS.~WS","scw","System32","SysWOW64",".AppleDouble",".AppleDB",".AppleDesktop","_CodeSignature",".cmio",".LSOverride",".localized",".TemporaryItems",".Trash",".Trash-0",".Trash-1000",".gvfs",".local",".config",".dbus",".fontconfig",".snap",".var",".lost+found","lost+found",".thumb",".thumbnails","EFI","boot","grub","logs","log",".nyc_output",".sonar",".ruff_cache",".VSCodeCounter",".skills","skills"],At=K=>{try{return Pe.readdirSync(K,{withFileTypes:!0})}catch{return[]}},xn=(K,Le={value:0},qt=1)=>{if(Le.value>6200||qt>7)return Le.value;let Se=At(K);for(let nt of Se){if(Le.value>6200)break;pt.includes(nt.name)||nt.name.startsWith(".")||nt.isDirectory()&&(Le.value++,xn(J.join(K,nt.name),Le,qt+1))}return Le.value},Yt=(K,Le)=>h?.indentationTree!==!1?$s(K,Le,1,At,pt):Fs(K,Le,"",1,At,pt),ct=xn(process.cwd()),fe=10;ct>3072||ct>2304?fe=1:ct>1536?fe=2:ct>768?fe=3:ct>384?fe=5:ct>192?fe=6:ct>96?fe=7:(ct>48||ct>24)&&(fe=9);let ue=_t(fs,{}),ie=ue[g],vt=ie?ie!==process.cwd():!1;ue[g]=process.cwd(),jn(fs,ue);let Fn=_t(N,{}),wt=Fn[g]||{summary:"",historyLength:0};typeof wt=="string"&&(wt={summary:wt,historyLength:0});let Or=t.filter(K=>(K.role==="user"||K.role==="agent"||K.role==="system")&&!String(K.id).startsWith("welcome")&&!K.isMeta).length;wt.historyLength&&Or<wt.historyLength&&(wt.summary="",wt.historyLength=0,Fn[g]=wt,jn(N,Fn));let mo=typeof wt=="object"?wt.summary||"":wt||"",Ks=r.length>0;Ks&&mo&&r[0]&&(r[0].role==="user"||r[0].role==="system")&&(r[0].text.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")||(r[0].text=`[SYSTEM METADATA]
665
+ Provide a consolidated summary of the entire session.`,b=de("gemma_janitor_fallback_google");o==="OpenRouter"&&(b=de("janitor_open_router")),o==="DeepSeek"&&(b=de("deepseek_level_1")),o==="Mistral"&&(b=de("mistral_level_1")),o==="NVIDIA"&&(b=de("nvidia_chat_summarizer_fallback")),o==="InferX"&&(b=de("inferx_fallback")),o==="SenseNova"&&(b=de("sensenova_fallback")),o==="AIHubMix"&&(b=de("aihubmix_fallback")),o==="Poolside"&&(b=de("poolside_fallback")),(o==="9router"||o==="9Router")&&(b=de("9router_fallback")),(o==="ExpLabs"||o==="ExperientialLabs")&&(b=de("explabs_fallback")||"deepseek-v4-pro-0813"),(o==="TokenHarbor"||o==="Token Harbor"||o==="tokenharbor"||o==="token_harbor"||o==="thk")&&(b=de("tokenharbor_fallback")||"deepseek-v4.1-flash:free");let v=0,N=!1,M=null;for(;v<=3&&!N;){v++;try{M=await es(e,b,R,T,"Fast"),N=!0}catch{if(v>3){if(o==="Google")try{let I=de("general_fallback");return(await es(e,I,R,T,"Fast")).text||""}catch{return""}return""}}}return M&&M.text||""},h=f(t),g=_t(d,{}),u=g[s]||{summary:"",historyLength:0};typeof u=="string"&&(u={summary:u,historyLength:0});let m=u.summary||"",x=await a(h,m);if(x){u.summary=x;let i=Da(t);return n?u.historyLength=(u.historyLength||0)+i:u.historyLength=i,g[s]=u,jn(d,g),x}return null},qd=e=>{try{let t=J.join(To,"chat-summaries.json");if($e.existsSync(t)){let n=_t(t,{});n[e]&&(delete n[e],jn(t,n))}}catch{}},zd=async function*(e,t,n,s,o){let{profile:d,thinkingLevel:f,mode:a,janitorModel:h,chatId:g,isPlayground:u,systemSettings:m,sessionStats:x,aiProvider:i="Google",apiTier:l,wildcardTooling:T}=n,R=dt(e);if(!js&&i==="Google")throw new Error("AI not initialized");let b=process.env.NVIDIA_BASE_URL||n?.aiProvider==="Ollama"||n?.aiProvider==="InferX"||n?.aiProvider==="SenseNova"||n?.aiProvider==="AIHubMix"||n?.aiProvider==="Poolside"||n?.aiProvider==="9router"||n?.aiProvider==="ExpLabs"||n?.aiProvider==="ExperientialLabs"||n?.aiProvider==="TokenHarbor"||n?.aiProvider==="Token Harbor"||n?.aiProvider==="tokenharbor"||n?.aiProvider==="token_harbor"||n?.aiProvider==="thk"||n?.aiProvider==="APInex"||n?.aiProvider==="apinex"||n?.aiProvider==="apx"?!1:m?.memory!==!1,v=t[t.length-1].text,N=J.join(To,"chat-summaries.json"),M=!1,S=t.filter(w=>w.role==="user").length===1,I=v.includes("[TITLE-UPDATE]"),$=S||I,p=v.replace(/\[TITLE-UPDATE\]/g,"").trim();p=p.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),yield{type:"status",content:"[start]"},yield{type:"status",content:"Gathering Context"},await Eo.startTransaction(g,p),m?.advanceRollback&&await to.takeInitialSnapshot(g),kt=!1;let c=null;try{let w=new AbortController;c=setInterval(()=>{kt&&(w.abort(),c&&(clearInterval(c),c=null))},400);let r=[...t.slice(0,-1)];{let Pe=_t(N,{})[g]||{summary:"",historyLength:0};if(Pe.summary&&Pe.historyLength>0){let qt=0,_e=[];for(let nt=0;nt<r.length;nt++){let je=r[nt];(je.role==="user"||je.role==="agent"||je.role==="system")&&!String(je.id).startsWith("welcome")&&!je.isMeta&&qt++,qt>Pe.historyLength&&_e.push(je)}r=_e}}r=r.map(K=>{if(K.role==="user"&&K.text){let Pe=K.text.match(/\[USER\]([\s\S]*?)\[\/USER\]/);if(Pe)return{...K,text:Pe[1].trim()}}return{...K}});let k=process.env.HIGH_CONTEXT,E=process.env.GOOGLE_GEMMA_NONSENSE==="true"||process.env.GOOGLE_GEMMA_NONSENSE===!0||!1,P={"16k":16e3,"32k":32e3,"64k":64e3,"128k":128e3,"256k":256e3,"512k":512e3,"1M":1e6}[m?.contextLength]||256e3;if(k&&k!=="false"){let K=parseInt(k,10);!isNaN(K)&&K>=0&&K<=1e6&&(P=K)}if((i==="NVIDIA"&&(e?.includes("gpt")||e?.includes("qwen")||e?.includes("medium")||e.includes("muse"))||i==="Mistral")&&(P=126e3),i==="Google"&&e?.includes("gemma")&&E&&(P=16e3),(x?.tokens||0)>P){yield{type:"text",content:"\u2726 Maximum Context Limit Reached. Start a new chat."};return}if(S&&b){let K=_t(So,{});Object.values(K).flat().length>5&&(yield{type:"status",content:"Condensing past chat memories"},await Ba(g,n,K))}let D=_t(So,{}),ee=_t(ds,{}),pe=Object.entries(D).filter(([K])=>K!==g).flatMap(([K,Pe])=>Pe),A=[...Object.entries(ee).filter(([K])=>K!==g).slice(-20).map(([K,Pe])=>`[Chat Summary]: ${Pe}`),...pe].map(K=>`- ${K}`).join(`
666
+ `),X=_t(On,[]).map(K=>`- ${K.memory}`).join(`
667
+ `),C=(x?.tokens||0)>=1e4,G=Yi(A,X,b,C),te=new Date,Y=te.getFullYear(),Xe=te.toLocaleString("en-US",{month:"short"}).toUpperCase(),Ye=String(te.getDate()).padStart(2,"0"),Ge=te.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}),ft=`${Y}-${Xe}-${Ye}, ${Ge}`,Qe=`${Ge}`,pt=[".git","node_modules",".gemini","dist","build",".next","out",".cache","bin","obj","vendor","venv",".idea",".gradle",".terraform","target","coverage",".vscode",".svn",".hg",".fslckout",".github",".gitlab",".circleci",".gitea",".gitee",".lerna",".changeset",".nx",".npm",".yarn",".pnpm-store",".pnpm",".expo",".nuxt",".svelte-kit",".docusaurus",".turbo",".vercel","bower_components",".netlify",".vuepress",".quasar",".output",".angular","jspm_packages",".parcel-cache",".rollup.cache",".rspack",".vitepress","__pycache__",".pytest_cache",".mypy_cache",".tox",".poetry","env","vhdl",".ipynb_checkpoints",".jupyter",".conda",".pdm-build",".bundle",".yardoc",".metadata","App_Data","ClientBin",".cargo",".rustc_info",".go","Godeps","_vendor",".rake_tasks","CMakefiles",".wakatime",".dart_tool",".fvm",".cocoapods","Pods",".pub-cache",".symlinks","DerivedData",".xcworkspace",".serverless",".aws",".gcloud",".azure",".kube",".vagrant",".docker","postgres-data","redis-data","mongo-data",".Spotlight-V100",".Trashes","$RECYCLE.BIN","System Volume Information",".DocumentRevisions-V100",".fseventsd","AppData","Application Data","Local","LocalLow","Roaming","$WinREAgent","$WINDOWS.~BT","$WINDOWS.~WS","scw","System32","SysWOW64",".AppleDouble",".AppleDB",".AppleDesktop","_CodeSignature",".cmio",".LSOverride",".localized",".TemporaryItems",".Trash",".Trash-0",".Trash-1000",".gvfs",".local",".config",".dbus",".fontconfig",".snap",".var",".lost+found","lost+found",".thumb",".thumbnails","EFI","boot","grub","logs","log",".nyc_output",".sonar",".ruff_cache",".VSCodeCounter",".skills","skills"],At=K=>{try{return $e.readdirSync(K,{withFileTypes:!0})}catch{return[]}},xn=(K,Pe={value:0},qt=1)=>{if(Pe.value>6200||qt>7)return Pe.value;let _e=At(K);for(let nt of _e){if(Pe.value>6200)break;pt.includes(nt.name)||nt.name.startsWith(".")||nt.isDirectory()&&(Pe.value++,xn(J.join(K,nt.name),Pe,qt+1))}return Pe.value},Yt=(K,Pe)=>m?.indentationTree!==!1?$s(K,Pe,1,At,pt):Fs(K,Pe,"",1,At,pt),ct=xn(process.cwd()),fe=10;ct>3072||ct>2304?fe=1:ct>1536?fe=2:ct>768?fe=3:ct>384?fe=5:ct>192?fe=6:ct>96?fe=7:(ct>48||ct>24)&&(fe=9);let ue=_t(fs,{}),ie=ue[g],vt=ie?ie!==process.cwd():!1;ue[g]=process.cwd(),jn(fs,ue);let Fn=_t(N,{}),wt=Fn[g]||{summary:"",historyLength:0};typeof wt=="string"&&(wt={summary:wt,historyLength:0});let Or=t.filter(K=>(K.role==="user"||K.role==="agent"||K.role==="system")&&!String(K.id).startsWith("welcome")&&!K.isMeta).length;wt.historyLength&&Or<wt.historyLength&&(wt.summary="",wt.historyLength=0,Fn[g]=wt,jn(N,Fn));let ho=typeof wt=="object"?wt.summary||"":wt||"",Ks=r.length>0;Ks&&ho&&r[0]&&(r[0].role==="user"||r[0].role==="system")&&(r[0].text.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")||(r[0].text=`[SYSTEM METADATA]
667
668
  **CONTEXT SUMMARY OF PREVIOUS TURNS (PRIORITY: DYNAMIC)**
668
- ${mo}
669
+ ${ho}
669
670
 
670
- [USER] ${r[0].text}`,yield{type:"summary_injected",content:{id:r[0].id,text:r[0].text}}));let ns=mo&&!Ks?`
671
+ [USER] ${r[0].text}`,yield{type:"summary_injected",content:{id:r[0].id,text:r[0].text}}));let ns=ho&&!Ks?`
671
672
  [SYSTEM METADATA]
672
673
  **CONTEXT SUMMARY OF PREVIOUS TURNS**
673
- ${mo}
674
- `:"",Ys=!!h?.dynamicDirAwareness,Lr=`${g}|${i}|${f}|${e}|${d}|${Ys}`,qs=!Ys&&$n.key===Lr&&$n.value?"":`
674
+ ${ho}
675
+ `:"",Ys=!!m?.dynamicDirAwareness,Lr=`${g}|${i}|${f}|${e}|${d}|${Ys}`,qs=!Ys&&$n.key===Lr&&$n.value?"":`
675
676
  **Directory Structure**
676
677
  CWD: `+process.cwd()+`${u?" [PLAYGROUND MODE]":""}
677
678
  `+Yt(process.cwd(),fe),mt=await Ln(),cn="";if(Wo()&&mt.file_focused!=="none"){cn=`
678
679
  [Additional IDE Context]
679
- `;let K=J.relative(process.cwd(),mt.file_focused),Le=(mt.opened_editors||[]).map(Se=>{let nt=J.relative(process.cwd(),Se);return nt.startsWith("..")?`[External] ${J.basename(Se)}`:nt});if(cn+=`Focused File: ${K}
680
+ `;let K=J.relative(process.cwd(),mt.file_focused),Pe=(mt.opened_editors||[]).map(_e=>{let nt=J.relative(process.cwd(),_e);return nt.startsWith("..")?`[External] ${J.basename(_e)}`:nt});if(cn+=`Focused File: ${K}
680
681
  Cursor Line: ${mt.cursor_line}
681
- `,mt.selected){let Se=mt.selected,nt=Se.split(`
682
- `);nt.length>256&&(Se=nt.slice(0,240).join(`
682
+ `,mt.selected){let _e=mt.selected,nt=_e.split(`
683
+ `);nt.length>256&&(_e=nt.slice(0,240).join(`
683
684
  `)+`
684
685
  ... [truncated] ...
685
686
  `+nt.slice(-16).join(`
686
- `)),Se.length>2048&&(Se=Se.slice(0,1920)+`
687
+ `)),_e.length>2048&&(_e=_e.slice(0,1920)+`
687
688
  ... [truncated] ...
688
- `+Se.slice(-128)),cn+=`Current Selection: "${Se}"
689
+ `+_e.slice(-128)),cn+=`Current Selection: "${_e}"
689
690
  `}if(mt.manual_edits){let nt=mt.manual_edits.split(`
690
- `),je=[],Ze=null;for(let j of nt)j.trim()&&(j.startsWith(" Line ")?Ze&&Ze.edits.push(j):(Ze={path:j.endsWith(":")?j.slice(0,-1):j,edits:[]},je.push(Ze)));for(let j of je)j.edits.length>80&&(j.edits=j.edits.slice(-80)),j.originalEditsCount=j.edits.length;let ge=(j,X)=>X.reduce((Ve,Xt)=>{let nn=mt.file_focused&&(Xt.path===mt.file_focused||J.resolve(process.cwd(),Xt.path)===J.resolve(mt.file_focused))?Math.ceil(j*1.2):j;return Ve+Math.min(Xt.edits.length,nn)},0),Mt=80;if(ge(80,je)>300){let j=!1;for(let X=80;X>=10;X--)if(ge(X,je)<=300){Mt=X,j=!0;break}j||(Mt=10)}let et=[...je];if(Mt===10&&ge(10,et)>500)for(;et.length>0&&ge(10,et)>500;){let j=0,X=et[0].originalEditsCount;for(let Ve=1;Ve<et.length;Ve++)et[Ve].originalEditsCount<X&&(X=et[Ve].originalEditsCount,j=Ve);et.splice(j,1)}for(let j of et){let Ve=mt.file_focused&&(j.path===mt.file_focused||J.resolve(process.cwd(),j.path)===J.resolve(mt.file_focused))?Math.ceil(Mt*1.2):Mt;j.edits.length>Ve&&(j.edits=j.edits.slice(-Ve))}for(let j of et){let X=`${j.path}:
691
+ `),je=[],Ze=null;for(let j of nt)j.trim()&&(j.startsWith(" Line ")?Ze&&Ze.edits.push(j):(Ze={path:j.endsWith(":")?j.slice(0,-1):j,edits:[]},je.push(Ze)));for(let j of je)j.edits.length>80&&(j.edits=j.edits.slice(-80)),j.originalEditsCount=j.edits.length;let ge=(j,Q)=>Q.reduce((Ve,Xt)=>{let nn=mt.file_focused&&(Xt.path===mt.file_focused||J.resolve(process.cwd(),Xt.path)===J.resolve(mt.file_focused))?Math.ceil(j*1.2):j;return Ve+Math.min(Xt.edits.length,nn)},0),Mt=80;if(ge(80,je)>300){let j=!1;for(let Q=80;Q>=10;Q--)if(ge(Q,je)<=300){Mt=Q,j=!0;break}j||(Mt=10)}let et=[...je];if(Mt===10&&ge(10,et)>500)for(;et.length>0&&ge(10,et)>500;){let j=0,Q=et[0].originalEditsCount;for(let Ve=1;Ve<et.length;Ve++)et[Ve].originalEditsCount<Q&&(Q=et[Ve].originalEditsCount,j=Ve);et.splice(j,1)}for(let j of et){let Ve=mt.file_focused&&(j.path===mt.file_focused||J.resolve(process.cwd(),j.path)===J.resolve(mt.file_focused))?Math.ceil(Mt*1.2):Mt;j.edits.length>Ve&&(j.edits=j.edits.slice(-Ve))}for(let j of et){let Q=`${j.path}:
691
692
  ${j.edits.join(`
692
- `)}`;for(;j.edits.length>0&&X.length>4*768;)j.edits.shift(),X=`${j.path}:
693
+ `)}`;for(;j.edits.length>0&&Q.length>4*768;)j.edits.shift(),Q=`${j.path}:
693
694
  ${j.edits.join(`
694
- `)}`;X.length>4*768?j.stringRepresentation="... "+X.slice(-(4*768-4)):j.stringRepresentation=X}let zt=et.map(j=>j.stringRepresentation).join(`
695
- `);for(;et.length>0&&zt.length>4*2048;){et[0].edits.length>0?et[0].edits.shift():et.shift();for(let j of et){let X=`${j.path}:
695
+ `)}`;Q.length>4*768?j.stringRepresentation="... "+Q.slice(-(4*768-4)):j.stringRepresentation=Q}let zt=et.map(j=>j.stringRepresentation).join(`
696
+ `);for(;et.length>0&&zt.length>4*2048;){et[0].edits.length>0?et[0].edits.shift():et.shift();for(let j of et){let Q=`${j.path}:
696
697
  ${j.edits.join(`
697
- `)}`;X.length>4*768?j.stringRepresentation="... "+X.slice(-(4*768-4)):j.stringRepresentation=X}zt=et.map(j=>j.stringRepresentation).join(`
698
+ `)}`;Q.length>4*768?j.stringRepresentation="... "+Q.slice(-(4*768-4)):j.stringRepresentation=Q}zt=et.map(j=>j.stringRepresentation).join(`
698
699
  `)}zt.length>4*2048&&(zt="... "+zt.slice(-(4*2048-4))),cn+=`Recent Manual Edits:
699
700
  ${zt}
700
- `}Le.length>0&&(cn+=`All Opened Editors: ${Le.join(", ")}`),mt.diagnostics&&(cn+=`
701
+ `}Pe.length>0&&(cn+=`All Opened Editors: ${Pe.join(", ")}`),mt.diagnostics&&(cn+=`
701
702
  **Active File Errors**:
702
703
  ${mt.diagnostics}
703
704
  `),(p.toLowerCase().includes("lint")||p.toLowerCase().includes("warning"))&&mt.warnings&&(cn+=`
704
705
  **Lint Warnings**:
705
706
  ${mt.warnings}
706
- `)}let zs=p.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),Js=/(?:\\)?@\[([^\]]+)\]/g,os,ss=[];for(Js.lastIndex=0;(os=Js.exec(zs))!==null;){let K=os[0].startsWith("\\");ss.push({tag:os[1],isEscaped:K})}let is=[],ho=null;for(let K=0;K<ss.length;K++){let{tag:Le,isEscaped:qt}=ss[K];if(!qt)try{let Se=Le.trim().replace(/^["']|["']$/g,""),nt=/[:#]L?(\d+)(?:-L?(\d+))?$/i,je=Se.match(nt),Ze=Se,ge=null,Mt=null;je&&(ge=parseInt(je[1],10),Mt=je[2]?parseInt(je[2],10):ge,Ze=Se.slice(0,je.index));let et=J.resolve(process.cwd(),Ze);if(Pe.existsSync(et)&&Pe.statSync(et).isFile()){let j=Ze.toLowerCase(),X=j.endsWith(".pdf"),Ve=j.endsWith(".docx")||j.endsWith(".doc")||j.endsWith(".ppt")||j.endsWith(".pptx")||j.endsWith(".xls")||j.endsWith(".xlsx"),Xt=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(j),It=Xt||X||Ve,nn=i==="Google"||dt(e);if(It&&!nn){let Be=`\u2718 Unsupported Modality: ${J.basename(Ze)}`,me=115;process.stdout.isTTY&&(me=process.stdout.columns-5||120);let Ue=[Be],Rn=Math.max(...Ue.map(bn=>bn.length)),Qt=Math.min(Rn+4,me),zn=Ue.map(bn=>`${bn.padEnd(Qt-2).substring(0,Qt-2)}`).join(`
707
+ `)}let zs=p.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),Js=/(?:\\)?@\[([^\]]+)\]/g,os,ss=[];for(Js.lastIndex=0;(os=Js.exec(zs))!==null;){let K=os[0].startsWith("\\");ss.push({tag:os[1],isEscaped:K})}let is=[],po=null;for(let K=0;K<ss.length;K++){let{tag:Pe,isEscaped:qt}=ss[K];if(!qt)try{let _e=Pe.trim().replace(/^["']|["']$/g,""),nt=/[:#]L?(\d+)(?:-L?(\d+))?$/i,je=_e.match(nt),Ze=_e,ge=null,Mt=null;je&&(ge=parseInt(je[1],10),Mt=je[2]?parseInt(je[2],10):ge,Ze=_e.slice(0,je.index));let et=J.resolve(process.cwd(),Ze);if($e.existsSync(et)&&$e.statSync(et).isFile()){let j=Ze.toLowerCase(),Q=j.endsWith(".pdf"),Ve=j.endsWith(".docx")||j.endsWith(".doc")||j.endsWith(".ppt")||j.endsWith(".pptx")||j.endsWith(".xls")||j.endsWith(".xlsx"),Xt=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(j),It=Xt||Q||Ve,nn=i==="Google"||dt(e);if(It&&!nn){let Be=`\u2718 Unsupported Modality: ${J.basename(Ze)}`,me=115;process.stdout.isTTY&&(me=process.stdout.columns-5||120);let Ue=[Be],Rn=Math.max(...Ue.map(bn=>bn.length)),Qt=Math.min(Rn+4,me),zn=Ue.map(bn=>`${bn.padEnd(Qt-2).substring(0,Qt-2)}`).join(`
707
708
  `);yield{type:"visual_feedback",content:Vt(`${zn}
708
- `)};continue}if(ge===null&&!It){let Be=0;try{Be=Pe.readFileSync(et,"utf8").split(/\r\n|\r|\n/).length}catch{}if(Be>300){let me=`\u21B7 Skipped (Too Large): ${J.basename(Ze)}`,Ue=115;process.stdout.isTTY&&(Ue=process.stdout.columns-5||120);let Rn=Math.min(me.length+4,Ue),Qt=me.padEnd(Rn-2).substring(0,Rn-2);yield{type:"visual_feedback",content:Vt(`${Qt}
709
- `)};continue}}let fn=ge!==null?ge:1,An=Mt!==null?Mt:ge!==null?ge:fn+299;An-fn>300&&(An=fn+300);let xo=`path=${JSON.stringify(Ze)}, startLine=${fn}, endLine=${An}`,st=await ui(xo,{isMultiModal:nn}),qe=!1,Dt="",Cn=null;if(typeof st=="string"?st.trim().startsWith("ERROR")?qe=!0:Dt=st:st&&typeof st=="object"&&st.binaryPart?(Cn=st.binaryPart,Dt=st.text||""):qe=!0,!qe){let Be="";if(Xt?(Be=`\u2714 Processed: ${J.basename(Ze)}`,ho=Cn):X||Ve?(Be=`\u2714 Auto-Analysed: ${J.basename(Ze)}`,ho=Cn):(Be=`\u2714 Auto-Read: ${J.basename(Ze)}`,is.push(Dt)),Be){let me=115;process.stdout.isTTY&&(me=process.stdout.columns-5||120);let Ue=[Be],Rn=Math.max(...Ue.map(bn=>bn.length)),Qt=Math.min(Rn+4,me),zn=Ue.map(bn=>`${bn.padEnd(Qt-2).substring(0,Qt-2)}`).join(`
709
+ `)};continue}if(ge===null&&!It){let Be=0;try{Be=$e.readFileSync(et,"utf8").split(/\r\n|\r|\n/).length}catch{}if(Be>300){let me=`\u21B7 Skipped (Too Large): ${J.basename(Ze)}`,Ue=115;process.stdout.isTTY&&(Ue=process.stdout.columns-5||120);let Rn=Math.min(me.length+4,Ue),Qt=me.padEnd(Rn-2).substring(0,Rn-2);yield{type:"visual_feedback",content:Vt(`${Qt}
710
+ `)};continue}}let fn=ge!==null?ge:1,An=Mt!==null?Mt:ge!==null?ge:fn+299;An-fn>300&&(An=fn+300);let bo=`path=${JSON.stringify(Ze)}, startLine=${fn}, endLine=${An}`,st=await ui(bo,{isMultiModal:nn}),qe=!1,Dt="",Cn=null;if(typeof st=="string"?st.trim().startsWith("ERROR")?qe=!0:Dt=st:st&&typeof st=="object"&&st.binaryPart?(Cn=st.binaryPart,Dt=st.text||""):qe=!0,!qe){let Be="";if(Xt?(Be=`\u2714 Processed: ${J.basename(Ze)}`,po=Cn):Q||Ve?(Be=`\u2714 Auto-Analysed: ${J.basename(Ze)}`,po=Cn):(Be=`\u2714 Auto-Read: ${J.basename(Ze)}`,is.push(Dt)),Be){let me=115;process.stdout.isTTY&&(me=process.stdout.columns-5||120);let Ue=[Be],Rn=Math.max(...Ue.map(bn=>bn.length)),Qt=Math.min(Rn+4,me),zn=Ue.map(bn=>`${bn.padEnd(Qt-2).substring(0,Qt-2)}`).join(`
710
711
  `);yield{type:"visual_feedback",content:Vt(`${zn}
711
712
  `)}}}}}catch{}}let rs="";is.length>0&&(rs=`[Tagged File Contents] Auto Read User Tagged files by System, No need to re-read
712
713
  `+is.join(`
713
714
 
714
715
  `)+`
715
716
  [Tagged File Contents]
716
- `);let Xs=zs.replace(/\\(@\[[^\]]+\])/g,"$1"),Qs=_?`You cannot execute tools
717
+ `);let Xs=zs.replace(/\\(@\[[^\]]+\])/g,"$1"),Qs=T?`You cannot execute tools
717
718
  Instead, output in chat the exact string you WOULD have produced & wait for system response
718
- `:"",Pr=process.env.forcedReasoning||!1,Zs=f!=="Fast"&&(i==="Mistral"&&!Vn(e)||f!=="xHigh"&&i==="Google")?`${i==="Mistral"&&!Vn(e)||e.toLowerCase().startsWith("gemma")||Pr?`[system] strictly follow thinking policy as high priority. do not start a response without <think>...</think> [/system]
719
- `:""}`:"",po="",ei=!!h?.autoExcludeMetadata,$r=!!(cn||rs||Qs||ns||G||Zs||vt||h?.dynamicDirAwareness||h?.autoTruncateResults||x);ei&&!$r?po=Xs.trim():po=`[System Metadata]
720
- Time: ${ei?Qe:ft}${h?.dynamicDirAwareness?qs:""}${vt?`
719
+ `:"",Pr=process.env.forcedReasoning||!1,Zs=f!=="Fast"&&(i==="Mistral"&&!Vn(e)||f!=="High"&&i==="Google")?`${i==="Mistral"&&!Vn(e)||e.toLowerCase().startsWith("gemma")||Pr?`[system] strictly follow thinking policy as high priority. do not start a response without <think>...</think> [/system]
720
+ `:""}`:"",yo="",ei=!!m?.autoExcludeMetadata,$r=!!(cn||rs||Qs||ns||G||Zs||vt||m?.dynamicDirAwareness||m?.autoTruncateResults||b);ei&&!$r?yo=Xs.trim():yo=`[System Metadata]
721
+ Time: ${ei?Qe:ft}${m?.dynamicDirAwareness?qs:""}${vt?`
721
722
  WARNING: CWD Changed from previous: "${ie}" to current: "${process.cwd()}", write change in chat to avoid future path mismatches
722
723
  `:""}${G}${cn}
723
724
  [/Metadata]
724
725
  ${ns}${Zs}[system] exact tool string [tool:functions.ToolName(arg="value")] in chat [/system]
725
- ${rs}${Qs}[user prompt] ${Xs.trim()} [/user prompt]`.trim();let ti={role:"user",text:po};ho&&(ti.binaryPart=ho),r.forEach(K=>{K.text&&K.role==="agent"&&(K.text=Kt(K.text))}),r.push(ti),ns&&t[t.length-1]?.id&&(yield{type:"summary_injected",content:{id:t[t.length-1].id,text:po}});let dn=null,qn=a==="Flux"?200:15;qn=a.toLowerCase().includes("cu")?300:qn;let tn=16;yield{type:"status",content:"Connecting"},kt=!1;let ni=[],yo=!1;for(let K=0;K<=qn;K++){let Le=await si("agent",n);if(!Le.allowed)throw new Error(Le.reason||`Budget Exhausted for Provider (${i||"Agent"})`);let qt=[];if(yo=!1,a==="ICU"||a==="FluxCU")try{yield{type:"status",content:"Capturing Screen"},await new Promise(re=>setTimeout(re,1e3));let{captureGriddedScreenshot:ye}=await import("./screen_grid-TDQC6CV5.js"),_e=await ye();if(_e&&_e.base64){let re="[system] Fresh Gridded Screen Feedback Captured. Use numeric coordinates. Old screenshots will be removed when new screenshot is captured, summarize in text if context is needed later [/system]",Ot={inlineData:{mimeType:_e.mimeType,data:_e.base64}},Ct=h?.imageHistoryCU||"Standard",Tt=Ct==="Low"?1:Ct==="Extended"?5:3,Jt=r.filter(We=>Array.isArray(We.parts)&&We.parts.some(Lt=>Lt.inlineData));if(Jt.length>=Tt){let We=Jt.length-Tt+1;for(let Lt=0;Lt<We;Lt++){let St=Jt[Lt];Array.isArray(St.parts)&&(St.parts=St.parts.filter(yt=>!yt.inlineData))}}if(r.length>0&&r[r.length-1].role==="user"){let We=r[r.length-1];typeof We.text=="string"&&(We.text+=`
726
+ ${rs}${Qs}[user prompt] ${Xs.trim()} [/user prompt]`.trim();let ti={role:"user",text:yo};po&&(ti.binaryPart=po),r.forEach(K=>{K.text&&K.role==="agent"&&(K.text=Kt(K.text))}),r.push(ti),ns&&t[t.length-1]?.id&&(yield{type:"summary_injected",content:{id:t[t.length-1].id,text:yo}});let dn=null,qn=a==="Flux"?200:15;qn=a.toLowerCase().includes("cu")?300:qn;let tn=16;yield{type:"status",content:"Connecting"},kt=!1;let ni=[],xo=!1;for(let K=0;K<=qn;K++){let Pe=await si("agent",n);if(!Pe.allowed)throw new Error(Pe.reason||`Budget Exhausted for Provider (${i||"Agent"})`);let qt=[];if(xo=!1,a==="ICU"||a==="FluxCU")try{yield{type:"status",content:"Capturing Screen"},await new Promise(re=>setTimeout(re,1e3));let{captureGriddedScreenshot:xe}=await import("./screen_grid-TDQC6CV5.js"),Ee=await xe();if(Ee&&Ee.base64){let re="[system] Fresh Gridded Screen Feedback Captured. Use numeric coordinates. Old screenshots will be removed when new screenshot is captured, summarize in text if context is needed later [/system]",Ot={inlineData:{mimeType:Ee.mimeType,data:Ee.base64}},Ct=m?.imageHistoryCU||"Standard",Tt=Ct==="Low"?1:Ct==="Extended"?5:3,Jt=r.filter(We=>Array.isArray(We.parts)&&We.parts.some(Lt=>Lt.inlineData));if(Jt.length>=Tt){let We=Jt.length-Tt+1;for(let Lt=0;Lt<We;Lt++){let St=Jt[Lt];Array.isArray(St.parts)&&(St.parts=St.parts.filter(yt=>!yt.inlineData))}}if(r.length>0&&r[r.length-1].role==="user"){let We=r[r.length-1];typeof We.text=="string"&&(We.text+=`
726
727
 
727
- ${re}`,Array.isArray(We.parts)||(We.parts=[{text:We.text}]),We.parts.push(Ot))}else r.push({role:"user",text:re,parts:[{text:re},Ot]})}}catch(ye){console.error("Vision screenshot capture error:",ye)}if(h?.compression===0&&(b?.tokens||0)>P&&(r=fi(r,6)),K>0?yield{type:"status",content:"Working"}:yield{type:"status",content:"Connecting"},kt){try{let{clearPendingNudges:ye}=await import("./subagent_state-LZCOZSUJ.js");ye()}catch{}yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
728
+ ${re}`,Array.isArray(We.parts)||(We.parts=[{text:We.text}]),We.parts.push(Ot))}else r.push({role:"user",text:re,parts:[{text:re},Ot]})}}catch(xe){console.error("Vision screenshot capture error:",xe)}if(m?.compression===0&&(x?.tokens||0)>P&&(r=fi(r,6)),K>0?yield{type:"status",content:"Working"}:yield{type:"status",content:"Connecting"},kt){try{let{clearPendingNudges:xe}=await import("./subagent_state-LZCOZSUJ.js");xe()}catch{}yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
728
729
 
729
- \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}try{let{consumePendingNudges:ye}=await import("./subagent_state-LZCOZSUJ.js"),_e=ye();if(_e&&_e.length>0){let re=_e.join(`
730
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}try{let{consumePendingNudges:xe}=await import("./subagent_state-LZCOZSUJ.js"),Ee=xe();if(Ee&&Ee.length>0){let re=Ee.join(`
730
731
 
731
732
  `);r.length>0&&r[r.length-1].role==="user"?r[r.length-1].text+=`
732
733
 
733
- ${re}`:r.push({role:"user",text:re}),yield{type:"status",content:"Subagent Update"}}}catch{}if(s){let ye=await s();ye&&(ye.startsWith("/btw")?r.length>0&&r[r.length-1].role==="user"?r[r.length-1].text+=`
734
+ ${re}`:r.push({role:"user",text:re}),yield{type:"status",content:"Subagent Update"}}}catch{}if(s){let xe=await s();xe&&(xe.startsWith("/btw")?r.length>0&&r[r.length-1].role==="user"?r[r.length-1].text+=`
734
735
 
735
736
  [system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
736
- [question] ${ye.replace("/btw","").trim()} [/question]`:r.push({role:"user",text:`[system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
737
- [question] ${ye.replace("/btw","").trim()} [/question]`}):r.length>0&&r[r.length-1].role==="user"?r[r.length-1].text+=`
737
+ [question] ${xe.replace("/btw","").trim()} [/question]`:r.push({role:"user",text:`[system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
738
+ [question] ${xe.replace("/btw","").trim()} [/question]`}):r.length>0&&r[r.length-1].role==="user"?r[r.length-1].text+=`
738
739
 
739
- [STEERING HINT from USER, High Priority] ${ye.trim()} [/STEERING HINT]`:r.push({role:"user",text:`[STEERING HINT from USER, High Priority] ${ye.trim()} [/STEERING HINT]`}),yield{type:"status",content:`${ye.startsWith("/btw")?"Question Forwarded...":"Steering Hint Injected..."}`})}let Se,nt=!1,je=1,Ze=1,ge="",Mt=null,et=null,zt=null,j=0,X=[],Ve=0,Xt=!1,It=!1,nn=!1,fn=!1,An=!0,xo=0,st="",qe="",Dt=!1,Cn=!1,Be=!0,me=e,Ue="";for(;je<=tn&&Ze<=tn&&!nt&&!kt;){let ye=!1;try{ge="",An&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},An=!1,Ze===1&&(st=""));let _e=L=>{if(!L||!L.includes("[tool:"))return L;let oe="",F=Hs(L);F&&(oe=F.fullBlock,L=F.remainingText),L=L.replace(va,(xe,he)=>he.includes("[tool:")?he.trim():xe);let H="",we=0;for(;we<L.length;){let xe=L.indexOf("[tool:",we);if(xe===-1){H+=Cr(L.substring(we));break}let he=L.substring(we,xe);H+=Cr(he);let Ke=-1,W=null,te=0;for(let Ne=xe;Ne<L.length;Ne++){let y=L[Ne];if(W){if(y===W){let Fe=0;for(let ve=Ne-1;ve>=0&&L[ve]==="\\";ve--)Fe++;Fe%2===0&&(W=null)}}else if(y==='"'||y==="'"||y==="`")W=y;else if(y==="(")te++;else if(y===")")te--;else if(y==="]"&&te<=0){Ke=Ne;break}}if(Ke===-1){H+=L.substring(xe);break}H+=L.substring(xe,Ke+1),we=Ke+1}return(h?.keepReasoningContext?oe:"")+H},re=r.filter(L=>(L.role==="user"||L.role==="agent"||L.role==="system")&&!String(L.id).startsWith("welcome")&&!L.isMeta&&!L.isTerminalRecord&&!(L.text&&L.text.startsWith("[TERMINAL_RECORD]"))).map((L,oe,F)=>{let H=L.text||"";x||(H=H.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),L.role==="agent"&&(H=_e(H),H=H.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),H=H.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*"));let we=[];return Array.isArray(L.parts)&&L.parts.length>0?we=L.parts.map(xe=>{if(xe.text){let he=xe.text;return x||(he=he.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),L.role==="agent"&&(he=_e(he),he=he.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),he=he.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*")),{text:he}}return xe}):we=[{text:H}],L.binaryPart&&dt(me)&&F.slice(oe+1).filter(he=>he.role==="user"&&!he.text?.startsWith("[TOOL RESULT]")).length<=2&&we.push(L.binaryPart),{role:L.role==="user"||L.role==="system"?"user":"model",parts:we}});for(let L=0;L<re.length;L++){let oe=re[L],F=oe.parts?.[0]?.text||"";if(oe.role==="model"&&/\[tool:/i.test(F)){let H=-1;for(let we=L+1;we<re.length;we++){let xe=re[we],he=xe.parts?.[0]?.text||"";if(xe.role==="user"&&he.startsWith("[TOOL RESULT]")){H=we;break}}if(H!==-1&&H!==L+1){let[we]=re.splice(H,1);re.splice(L+1,0,we)}}}for(let L=re.length-2;L>=0;L--){let oe=re[L],F=re[L+1];oe.role==="user"&&F.role==="user"&&(F.parts?.[0]?.text||"").trim().startsWith("[SYSTEM")&&re.splice(L,1)}let Ot=[];for(let L=0;L<re.length;L++){let oe=re[L];if(Ot.length===0)Ot.push(oe);else{let F=Ot[Ot.length-1];F.role===oe.role?(F.parts[0].text+=`
740
+ [STEERING HINT from USER, High Priority] ${xe.trim()} [/STEERING HINT]`:r.push({role:"user",text:`[STEERING HINT from USER, High Priority] ${xe.trim()} [/STEERING HINT]`}),yield{type:"status",content:`${xe.startsWith("/btw")?"Question Forwarded...":"Steering Hint Injected..."}`})}let _e,nt=!1,je=1,Ze=1,ge="",Mt=null,et=null,zt=null,j=0,Q=[],Ve=0,Xt=!1,It=!1,nn=!1,fn=!1,An=!0,bo=0,st="",qe="",Dt=!1,Cn=!1,Be=!0,me=e,Ue="";for(;je<=tn&&Ze<=tn&&!nt&&!kt;){let xe=!1;try{ge="",An&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},An=!1,Ze===1&&(st=""));let Ee=L=>{if(!L||!L.includes("[tool:"))return L;let se="",F=Hs(L);F&&(se=F.fullBlock,L=F.remainingText),L=L.replace(Ma,(be,he)=>he.includes("[tool:")?he.trim():be);let H="",we=0;for(;we<L.length;){let be=L.indexOf("[tool:",we);if(be===-1){H+=Cr(L.substring(we));break}let he=L.substring(we,be);H+=Cr(he);let Ke=-1,W=null,ne=0;for(let Ne=be;Ne<L.length;Ne++){let y=L[Ne];if(W){if(y===W){let Fe=0;for(let ve=Ne-1;ve>=0&&L[ve]==="\\";ve--)Fe++;Fe%2===0&&(W=null)}}else if(y==='"'||y==="'"||y==="`")W=y;else if(y==="(")ne++;else if(y===")")ne--;else if(y==="]"&&ne<=0){Ke=Ne;break}}if(Ke===-1){H+=L.substring(be);break}H+=L.substring(be,Ke+1),we=Ke+1}return(m?.keepReasoningContext?se:"")+H},re=r.filter(L=>(L.role==="user"||L.role==="agent"||L.role==="system")&&!String(L.id).startsWith("welcome")&&!L.isMeta&&!L.isTerminalRecord&&!(L.text&&L.text.startsWith("[TERMINAL_RECORD]"))).map((L,se,F)=>{let H=L.text||"";b||(H=H.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),L.role==="agent"&&(H=Ee(H),H=H.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),H=H.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*"));let we=[];return Array.isArray(L.parts)&&L.parts.length>0?we=L.parts.map(be=>{if(be.text){let he=be.text;return b||(he=he.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),L.role==="agent"&&(he=Ee(he),he=he.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),he=he.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*")),{text:he}}return be}):we=[{text:H}],L.binaryPart&&dt(me)&&F.slice(se+1).filter(he=>he.role==="user"&&!he.text?.startsWith("[TOOL RESULT]")).length<=2&&we.push(L.binaryPart),{role:L.role==="user"||L.role==="system"?"user":"model",parts:we}});for(let L=0;L<re.length;L++){let se=re[L],F=se.parts?.[0]?.text||"";if(se.role==="model"&&/\[tool:/i.test(F)){let H=-1;for(let we=L+1;we<re.length;we++){let be=re[we],he=be.parts?.[0]?.text||"";if(be.role==="user"&&he.startsWith("[TOOL RESULT]")){H=we;break}}if(H!==-1&&H!==L+1){let[we]=re.splice(H,1);re.splice(L+1,0,we)}}}for(let L=re.length-2;L>=0;L--){let se=re[L],F=re[L+1];se.role==="user"&&F.role==="user"&&(F.parts?.[0]?.text||"").trim().startsWith("[SYSTEM")&&re.splice(L,1)}let Ot=[];for(let L=0;L<re.length;L++){let se=re[L];if(Ot.length===0)Ot.push(se);else{let F=Ot[Ot.length-1];F.role===se.role?(F.parts[0].text+=`
740
741
 
741
- `+(oe.parts?.[0]?.text||""),oe.parts?.length>1&&F.parts.push(...oe.parts.slice(1))):Ot.push(oe)}}re.length=0,re.push(...Ot),me=e;let Ct=`${g}|${i}|${a}|${f}|${me}|${JSON.stringify(d)}|${!!h?.dynamicDirAwareness}|${!!h?.subAgents}`,Tt=$n.key===Ct&&$n.value;if((process.env.I_HAVE_TOO_MUCH_MONEY==="true"||process.env.I_HAVE_TOO_MUCH_MONEY===!0)&&(Tt=!1),Tt)Ue=$n.value;else{let L=i==="Mistral"?!!Vn(me):!(me||"gemma").toLowerCase().startsWith("gemma");Ue=Yi(d,((me||"gemma").toLowerCase().startsWith("gemma"),f),a,h,x,S,i,i==="Google"?!0:C,L,g,!!h?.keepReasoningContext,me),h?.dynamicDirAwareness||(Ue+=`
742
+ `+(se.parts?.[0]?.text||""),se.parts?.length>1&&F.parts.push(...se.parts.slice(1))):Ot.push(se)}}re.length=0,re.push(...Ot),me=e;let Ct=`${g}|${i}|${a}|${f}|${me}|${JSON.stringify(d)}|${!!m?.dynamicDirAwareness}|${!!m?.subAgents}`,Tt=$n.key===Ct&&$n.value;if((process.env.I_HAVE_TOO_MUCH_MONEY==="true"||process.env.I_HAVE_TOO_MUCH_MONEY===!0)&&(Tt=!1),Tt)Ue=$n.value;else{let L=i==="Mistral"?!!Vn(me):!(me||"gemma").toLowerCase().startsWith("gemma");Ue=qi(d,((me||"gemma").toLowerCase().startsWith("gemma"),f),a,m,b,S,i,i==="Google"?!0:R,L,g,!!m?.keepReasoningContext,me),m?.dynamicDirAwareness||(Ue+=`
742
743
  ${qs.replace(`
743
744
  **Directory Structure**`,`
744
- -- Directory Structure --`)}`),$n.key=Ct,$n.value=Ue}let We=re[re.length-1];if(Wo()&K>0){await new Promise(F=>setTimeout(F,2500)),yield{type:"status",content:"Verifying"};let L=await Ln(),oe=L?L.diagnostics:null;oe&&We&&We.role==="user"&&We.parts?.[0]?.text&&(We.parts[0].text+=`
745
- ${oe} [/ERROR]`),yield{type:"status",content:"Working"}}let Lt=i==="Mistral"||i==="Google"&&e?.toLowerCase().startsWith("gemma");if(h?.advanceRollback&&We&&We.role==="user"&&We.parts?.[0]?.text?.startsWith("[TOOL RESULT]"))try{let L=await to.getLatestFileChanges(g);if(L&&(L.newFiles.length>0||L.modifiedFiles.length>0||L.deletedFiles.length>0)){let oe=`
745
+ -- Directory Structure --`)}`),$n.key=Ct,$n.value=Ue}let We=re[re.length-1];if(Wo()&K>0){await new Promise(F=>setTimeout(F,2500)),yield{type:"status",content:"Verifying"};let L=await Ln(),se=L?L.diagnostics:null;se&&We&&We.role==="user"&&We.parts?.[0]?.text&&(We.parts[0].text+=`
746
+ ${se} [/ERROR]`),yield{type:"status",content:"Working"}}let Lt=i==="Mistral"||i==="Google"&&e?.toLowerCase().startsWith("gemma");if(m?.advanceRollback&&We&&We.role==="user"&&We.parts?.[0]?.text?.startsWith("[TOOL RESULT]"))try{let L=await to.getLatestFileChanges(g);if(L&&(L.newFiles.length>0||L.modifiedFiles.length>0||L.deletedFiles.length>0)){let se=`
746
747
  [system] File Changes:
747
- `;for(let H of L.newFiles)oe+=`* ${H} (created)
748
- `;for(let H of L.modifiedFiles)oe+=`* ${H} (modified)
749
- `;for(let H of L.deletedFiles)oe+=`* ${H} (deleted)
750
- `;oe+="[/system]",We.parts[0].text+=oe;let F=-1;for(let H=r.length-1;H>=0;H--)if(r[H].role==="user"&&r[H].text?.startsWith("[TOOL RESULT]")){F=H;break}F!==-1&&(r[F].text+=oe)}}catch{}let St=Math.floor(qn*(a==="Flux"?.98:.8)),yt=K+1;yt>=St&&We&&We.parts?.[0]&&(We.parts[0].text+=`
751
- [system] WARNING, Turn Limit Impending: Step ${yt}/${qn}. Wrap up quickly/prompt user to continue. [/system]`);let Rt=new Promise((L,oe)=>{w.signal.aborted&&oe(new DOMException("The user aborted a request.","AbortError")),w.signal.addEventListener("abort",()=>{oe(new DOMException("The user aborted a request.","AbortError"))})});Rt.catch(()=>{});let ut=re;if(i==="Ollama")Se=Bs(n.apiKey,me,ut,Ue,f,a,C,w.signal,1,h?.ollamaEndpoint||"Cloud");else if(i==="OpenRouter")Se=Ko(n.apiKey,me,ut,Ue,f,a,C,w.signal,1,g);else if(i==="DeepSeek")Se=Go(n.apiKey,me,ut,Ue,f,a,C,w.signal,1);else if(i==="Mistral")Se=jo(n.apiKey,me,ut,Ue,f,a,C,w.signal,1,g);else if(i==="NVIDIA"){let L=Vo(n.apiKey,me,ut,Ue,f,a,C,w.signal,1);Se=Tr(L,me)}else if(i==="InferX")Se=Yo(n.apiKey,me,ut,Ue,f,a,C,w.signal,1);else if(i==="SenseNova")Se=qo(n.apiKey,me,ut,Ue,f,a,C,w.signal,1);else if(i==="AIHubMix")Se=zo(n.apiKey,me,ut,Ue,f,a,C,w.signal,1);else if(i==="Poolside")Se=Jo(n.apiKey,me,ut,Ue,f,a,C,w.signal,1);else if(i==="9router"||i==="9Router")Se=Xo(n.apiKey,me,ut,Ue,f,a,C,w.signal,1);else if(i==="ExpLabs"||i==="ExperientialLabs")Se=Qo(n.apiKey,me,ut,Ue,f,a,C,w.signal,1);else if(i==="TokenHarbor"||i==="Token Harbor"||i==="tokenharbor"||i==="token_harbor"||i==="thk")Se=Us(n.apiKey,me,ut,Ue,f,a,C,w.signal,1);else if(i==="APInex"||i==="apinex"||i==="apx")Se=Ws(n.apiKey,me,ut,Ue,f,a,C,w.signal,1);else{let oe=Vs(n?.apiKey).models.generateContentStream({model:me||"gemini-3-flash-preview",contents:ut,config:{systemInstruction:Ue,mediaResolution:"MEDIA_RESOLUTION_HIGH",safetySettings:[{category:En.HARM_CATEGORY_HARASSMENT,threshold:_n.BLOCK_NONE},{category:En.HARM_CATEGORY_HATE_SPEECH,threshold:_n.BLOCK_NONE},{category:En.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:_n.BLOCK_NONE},{category:En.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:_n.BLOCK_NONE}],temperature:1.05,thinkingConfig:(()=>{let F=$e("Google",me||"gemini-3-flash-preview",f);if(F!==null){if(typeof F=="object")return F;if(F===!1||F==="false"||F==="none"||F===0||F==="0")return{includeThoughts:!1};if(typeof F=="number")return{includeThoughts:!0,thinkingBudget:F};if(typeof F=="string"){let he=F.toLowerCase();if(he==="minimal")return{includeThoughts:!0,thinkingLevel:Je.MINIMAL};if(he==="low")return{includeThoughts:!0,thinkingLevel:Je.LOW};if(he==="medium")return{includeThoughts:!0,thinkingLevel:Je.MEDIUM};if(he==="high")return{includeThoughts:!0,thinkingLevel:Je.HIGH};let Ke=Number(F);if(!isNaN(Ke))return{includeThoughts:!0,thinkingBudget:Ke}}}let H=(me||"").toLowerCase(),we=H.includes("gemma-4")||H.startsWith("gemma"),xe=H.includes("gemini-3");if(we||xe)return we?f.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:Je.MINIMAL}:{includeThoughts:!0,thinkingLevel:Je.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:H.includes("pro")?Je.LOW:Je.MINIMAL,Low:Je.LOW,Medium:Je.MEDIUM,Standard:Je.MEDIUM,High:Je.HIGH,xHigh:Je.HIGH}[f]||Je.MEDIUM};{let he={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[f]||2048;return he===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:he}}})()}},{signal:w.signal});Se=await Promise.race([oe,Rt])}ge="",Mt=null,zt=null,X=[],Ve=0,yield{type:"model_update",content:null},qe="",Dt=st.length>0;let on="",as=Date.now(),Mn=async function*(){if(i==="Google"&&on){let L=Jn(on);for(let oe of L)yield oe;on="",as=Date.now()}},oi=!0,In="",Bn=!1,Pt=null,Br={tool:{startPrefix:"[tool",fullPrefix:"[tool:functions.",endTag:"]"},agent:{startPrefix:"[agent",fullPrefix:"[agent:generalist.",endTag:"]"},end:{startPrefix:"[[END]]",fullPrefix:"[[END]]",endTag:"[[END]]"},kimi_section:{startPrefix:"<|tool_calls_section_begin|>",fullPrefix:"<|tool_calls_section_begin|>",endTag:"<|tool_calls_section_end|>"},kimi_call:{startPrefix:"<|tool_call_begin|>",fullPrefix:"<|tool_call_begin|>",endTag:"<|tool_call_end|>"}},Jn=L=>{let oe=[],F=L;for(;F.length>0;)if(Bn){let H=In+F,we=Br[Pt];if(we){let Ke=!1;if(H.length<we.startPrefix.length?we.startPrefix.startsWith(H)||(Ke=!0):H.startsWith(we.startPrefix)?H.length>=we.fullPrefix.length&&!H.startsWith(we.fullPrefix)&&(Ke=!0):Ke=!0,Ke){oe.push({type:"text",content:H}),In="",Bn=!1,Pt=null,F="";break}}let xe=-1,he=we?we.endTag:"]";if(Pt==="tool"||Pt==="agent"){let Ke=0,W=null,te=0,Ne=!1;for(let y=0;y<H.length;y++){let Fe=H[y];if(W){if(Fe===W){let ve=0;for(let z=y-1;z>=0&&H[z]==="\\";z--)ve++;ve%2===0&&(W=null)}}else if(Fe==='"'||Fe==="'"||Fe==="`")W=Fe;else if(Fe==="(")Ke++,Ne=!0;else if(Fe===")")Ke--;else if(Fe==="[")te++;else if(Fe==="]"){if(Ne&&Ke===0&&te===1){xe=y;break}te--}}}else xe=H.indexOf(he);if(xe!==-1){let Ke=he.length;if(!Pt?.startsWith("kimi")){let W=H.substring(0,xe+Ke);oe.push({type:"text",content:W})}In="",Bn=!1,Pt=null,F=H.substring(xe+Ke)}else{let Ke=Pt?.startsWith("kimi")?8192:512;H.length>Ke?(oe.push({type:"text",content:H}),In="",Bn=!1,Pt=null):In=H,F="";break}}else{let H=F.indexOf("[tool"),we=F.indexOf("[agent"),xe=F.indexOf("[[END]]"),he=F.indexOf("<|tool_calls_section_begin|>"),Ke=F.indexOf("<|tool_call_begin|>"),W=[{type:"tool",idx:H,start:"[tool",end:"]"},{type:"agent",idx:we,start:"[agent",end:"]"},{type:"end",idx:xe,start:"[[END]]",end:"[[END]]"},{type:"kimi_section",idx:he,start:"<|tool_calls_section_begin|>",end:"<|tool_calls_section_end|>"},{type:"kimi_call",idx:Ke,start:"<|tool_call_begin|>",end:"<|tool_call_end|>"}].filter(te=>te.idx!==-1).sort((te,Ne)=>te.idx-Ne.idx);if(W.length>0){let te=W[0];te.idx>0&&oe.push({type:"text",content:F.substring(0,te.idx)}),Bn=!0,Pt=te.type,In="",F=F.substring(te.idx)}else{let te=["[tool","[agent","[[END]]","<|tool_calls_section_begin|>","<|tool_call_begin|>"],Ne=-1;for(let y of te){for(let Fe=y.length-1;Fe>0;Fe--)if(F.endsWith(y.substring(0,Fe))){Ne=F.length-Fe;let ve=te.indexOf(y);ve===0?Pt="tool":ve===1?Pt="agent":ve===2?Pt="end":ve===3?Pt="kimi_section":Pt="kimi_call";break}if(Ne!==-1)break}if(Ne!==-1)Ne>0&&oe.push({type:"text",content:F.substring(0,Ne)}),Bn=!0,In=F.substring(Ne),F="";else{oe.push({type:"text",content:F});break}}}return oe},Ur=Se[Symbol.asyncIterator]();for(;;){let{value:L,done:oe}=await Promise.race([Ur.next(),Rt]);if(oe)break;if(L&&L.type==="status"){yield L;continue}let F="",H=L.candidates?.[0]?.content?.parts;if(H&&H.length>0)for(let xe of H){let he=typeof xe.text=="string"?xe.text:xe.text?parseChunkText(xe.text):"";xe.thought?he&&(ye||(F+="<think>",ye=!0),F+=he):he&&(ye&&(F+="</think>",ye=!1),F+=he)}else L.text&&ye&&(F+="</think>",ye=!1);F=Ea(F);let we=F?gs(F):0;if(n&&typeof n.onTokenChunk=="function"&&n.onTokenChunk(F,we),oi&&(yield{type:"status",content:"Thinking"},oi=!1),kt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
752
-
753
- \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(F){if(Dt){if(qe+=F,qe.length>=64){let W=0,te=Math.min(st.length,qe.length);for(let y=te;y>=10;y--)if(st.endsWith(qe.substring(0,y))){W=y;break}let Ne=qe.substring(W);if(Ne){let Fe=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(st)?Ne.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):Ne.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(Fe)if(ge+=Fe,i==="Google")on+=Fe;else{yield*Mn();let ve=Jn(Fe);for(let z of ve)yield z}}Dt=!1,qe=""}continue}else if(ge+=F,i==="Google")on+=F;else{yield*Mn();let W=Jn(F);for(let te of W)yield te}let xe=Oa(ge);if(xe.inside){Cn=!0,zt||(zt=Date.now());let te={Ask:"ask",AskUser:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Cancel:"cancel",Await:"await",Answer:"answer",Steer:"steer",steer:"steer"}[xe.toolName]||xe.toolName,Ne=xe.args||"",y=null;if(["write_file","update_file","view_file","read_folder","write_pdf","write_docx","search_keyword","generate_image","file_map","invoke","invoke_sync","get_progress","await","answer"].includes(te)){let ve=Q(Ne),z=ve.path||ve.targetFile||ve.TargetFile||ve.directory,sn=ve.keyword,Dn=ve.title||ve.task,kn=ve.id||ve.taskId,Ae=ve.timeout||ve.time;if(sn!=null)y=String(sn).replace(Pn,"");else if(z)y=J.basename(String(z).replace(Pn,"").replace(Sr,"/"));else if(Dn&&(te==="invoke"||te==="invoke_sync"))y=String(Dn).replace(Pn,"").substring(0,30);else if(kn&&te==="get_progress")y=String(kn).replace(Pn,"");else if(Ae&&te==="await"){let $t=parseFloat(String(Ae).replace(Pn,""));isNaN($t)?y=String(Ae).replace(Pn,""):($t<5&&($t=5),$t>120&&($t=120),y=(un=>{if(un>=60){let cs=Math.floor(un/60),Un=un%60;return`${cs}m${Un>0?` ${Un}s`:""}`}return`${un}s`})($t))}else{let $t=Ne.match(Ta);if($t){let Ut=$t[1].replace(Pn,"");te==="invoke"||te==="invoke_sync"||te==="get_progress"?y=Ut.substring(0,30):y=te==="search_keyword"||te==="file_map"?Ut:J.basename(Ut.replace(Sr,"/"))}}}let Fe=`${Gs[te]||te}${y?` ${y}`:""}`;if((te!==Mt||y!==et)&&(Mt=te,et=y,yield{type:"status",content:`${Fe}`},process.stdout.isTTY)){let z={WebSearch:"Searching",web_search:"Searching",WebScrape:"Reading",web_scrape:"Reading",ReadFile:"Reading",read_file:"Reading",ReadFolder:"Reading",read_folder:"Reading",WriteFile:"Writing",write_file:"Writing",UpdateFile:"Editing",update_file:"Editing",WritePdf:"Creating",write_pdf:"Creating",WriteDocx:"Creating",write_docx:"Creating",SearchKeyword:"Searching",search_keyword:"Searching",CodeSearch:"Searching",code_search:"Searching",Run:"Executing",Ask:"User Input Required",AskUser:"User Input Required",Memory:"Updating Memory",GenerateImage:"Generating",InvokeSync:"Sub-Agent Working",invoke_sync:"Sub-Agent Working",Invoke:"Working",invoke:"Working",GetProgress:"Checking Progress",get_progress:"Checking Progress",Cancel:"Stopping Generalist",cancel:"Stopping Generalist",Await:"Waiting",await:"Waiting",EmergencyRollback:"Rolling the Ball",Answer:"Answering Sub-Agent",answer:"Answering Sub-Agent",Steer:"Steering Sub-Agent",steer:"Steering Sub-Agent",Click:"Clicking",click:"Clicking",Drag:"Dragging",drag:"Dragging",Scroll:"Scrolling",scroll:"Scrolling",KeyboardTyping:"Typing",keyboard_typing:"Typing",KeyPress:"Pressing Key",key_press:"Pressing Key",RecaptureScreen:"Recapturing Screen",recapture_screen:"Recapturing Screen"}[te]||"Working";process.stdout.write(`\x1B]0;${z}...\x07`)}}if(ge.length-xo>150){xo=ge.length;let W=Dr(ge,!1),te=Hs(W),Ne=te?(te.innerContent||"").trim():"",y=Ne.split(/[.!?]\s+/),Fe=new Set(y),ve=y.length>10?(y.length-Fe.size)/y.length:0,z=Ne.split(/\s+/).filter(Me=>Me.length>0).length,sn=.6,Dn=.8,kn=!1;if((i.toLowerCase().includes("google")||i.toLowerCase().includes("mistral"))&&((me||"").toLowerCase().startsWith("gemma")||(me||"").toLowerCase().includes("stral"))){let T={low:256,medium:1024,high:8192,max:16384,xhigh:16384}[f?.toLowerCase()]||2500;kn=z>T}if(ve>sn||kn){yield{type:"status",content:`${ve>sn?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},It=!0,await new Promise(T=>setTimeout(T,3e3));break}let Ut=Rr(ge).trim().split(/[.!?]\s+/),un=new Set(Ut);if((Ut.length>10?(Ut.length-un.size)/Ut.length:0)>Dn){yield{type:"status",content:"Response Loop Detected. Re-centering..."},It=!1,fn=!0,await new Promise(Me=>setTimeout(Me,3e3));break}let Un=W.replace(ha,"").replace(pa,"").replace(ya,"").replace(xa,""),Nt=Un.toLowerCase().split(/\s+/).map(Me=>Me.replace(ba,"")).filter(Me=>Me.length>0),gn=!1;if(Nt.length>=10)for(let Me=1;Me<=15;Me++){let T=Math.max(3,Math.ceil(10/Me));if(Nt.length<Me*T)continue;let V=Nt.slice(Nt.length-Me),ae=V.join(" ");if(Me>1&&ae===V.slice(0,Math.floor(Me/2)).join(" ").repeat(2).trim())continue;let ce=!0;for(let be=1;be<T;be++)if(Nt.slice(Nt.length-Me*(be+1),Nt.length-Me*be).join(" ")!==ae){ce=!1;break}if(ce){gn=!0;break}}if(!gn){let Me=Un.toLowerCase().replace(ka,"");if(Me.length>=20)for(let T=1;T<=10;T++){let V=Math.max(5,Math.ceil(16/T));if(Me.length<T*V)continue;let ae=Me.substring(Me.length-T),ce=!0;for(let be=1;be<V;be++)if(Me.substring(Me.length-T*(be+1),Me.length-T*be)!==ae){ce=!1;break}if(ce){gn=!0;break}}}if(gn){yield{type:"status",content:"Stuttering Detected. Re-centering..."},It=!1,nn=!0,await new Promise(Me=>setTimeout(Me,3e3));break}}let he=Kt(ge),Ke=ts(he);for(;Ke.length>Ve;){yield*Mn();let W=Ke[Ve],te=Date.now(),y={Ask:"ask",AskUser:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Await:"await",await:"await",AwaitSubagent:"await",awaitSubagent:"await",Answer:"answer",answer:"answer",AnswerSubagent:"answer",answerSubagent:"answer",Steer:"steer",steer:"steer",SteerSubagent:"steer",steerSubagent:"steer",Cancel:"cancel",cancel:"cancel",Click:"click",click:"click",Drag:"drag",drag:"drag",Scroll:"scroll",scroll:"scroll",KeyboardTyping:"keyboard_typing",keyboard_typing:"keyboard_typing",KeyPress:"key_press",key_press:"key_press",RecaptureScreen:"recapture_screen",recapture_screen:"recapture_screen",EmergencyRollback:"EmergencyRollback"}[W.toolName]||W.toolName,Fe=Gs[y]||W.toolName,ve=Nn(y,W.args);yield{type:"status",content:`${Fe}${ve?` ${ve}`:""}`};let z="";if(y==="click"){let T=Q(W.args);z=`\u2714 Clicked: ${T.intendedClickText?`${T.intendedClickText}`:""}`}else if(y==="drag"){let T=Q(W.args);z=`\u2714 Dragged: Cell ${T.fromGridId||""} \u2192 Cell ${T.toGridId||""}`}else if(y==="scroll"){let T=Q(W.args);z=`\u2714 Scrolled: ${T.direction||"down"} (${T.amount||1})`}else if(y==="keyboard_typing"){let T=Q(W.args);z=`\u2714 Typed: ${T.text?`"${T.text.length>20?T.text.substring(0,20)+"...":T.text}"`:""}`}else if(y==="key_press")z=`\u2714 Pressed Key: ${Q(W.args).key||""}`;else if(y==="recapture_screen")z="\u2714 Recaptured Screen";else if(y==="web_search"){let{query:T,limit:V=10,aiMode:ae=!1}=Q(W.args);z=`${T?"\u2714":"\u2718"} ${ae?"AI Search":"Searched"}: ${T?`${T}`:"No Search Query"}${ae===!1&&T?` \u2192 ${V}`:""}`}else if(y==="web_scrape"){let T=Q(W.args).url||null;z=`${T?"\u2714":"\u2718"} Visited: ${T||"No Source"}`}else if(y==="view_file"){let{path:T,StartLine:V,EndLine:ae,start_line:ce,end_line:be,startLine:He,endLine:Ie}=Q(W.args),Te=V||ce||He,q=ae||be||Ie,ne=parseInt(Te)||1,le=parseInt(q)||(Te?ne+800:800),Ce="...",ze=le,Re=(T||"").trim().toLowerCase().replaceAll("\\","/");if(Re.startsWith("#skill"))Re.startsWith("#skill/global/fluxflow")||Re.startsWith("#skills/global/fluxflow")?z="\u2714 Read Documentation":z=`\u2714 Read Skill: ${J.basename(T.replaceAll("\\","/"))}`;else{try{let pe=J.resolve(process.cwd(),T);if(Pe.existsSync(pe)){let ht=Pe.readFileSync(pe,"utf8").split(`
754
- `).length;Ce=ht,!Te&&!q&&ht>800?ze=Math.min(50,ht):ze=Math.min(le,ht)}}catch{}let Oe=(T||"").toLowerCase(),gt=Oe.endsWith(".pdf"),De=Oe.endsWith(".docx")||Oe.endsWith(".doc")||Oe.endsWith(".ppt")||Oe.endsWith(".pptx")||Oe.endsWith(".xls")||Oe.endsWith(".xlsx"),ot=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(Oe);gt||De?z=`${T.length>0?"\u2714":"\u2718"} ${T?`Analyzed: ${J.basename(T)}`:"Analyzed: File Not Found"}`:ot?z=`${T.length>0?"\u2714":"\u2718"} ${T?`Processed: ${J.basename(T)}`:"Processed: File Not Found"}`:z=`${Ce!=="..."?"\u2714":"\u2718"} Read: ${T?`${J.basename(T)} \u2192 ${Ce!=="..."?`Lines ${ne} - ${ze} of ${Ce}`:"File Not Found"}`:"File Not Found"}`}}else if(y==="list_files"||y==="read_folder"){let T=y==="list_files"?"List":"Browsed",V=Q(W.args).path||null,ae=Q(W.args).recurse||1;z=`${V?"\u2714":"\u2718"} ${T}: ${V?`${V==="."?`./${ae>1?"*":""}`:`${V.replaceAll("\\","/")}${ae>1?`${V.endsWith("/")?"*":"/*"}`:`${V.endsWith("/")?"":"/"}`}`}`:"No Folder Selected"}`}else if(y==="write_file"||y==="update_file"){let T=y==="write_file"?"Created":"Edited",V=Q(W.args).path||null;z=`${V?"\u2714":"\u2718"} ${T}: ${V.replaceAll("\\","/")||"No File Changes"}`}else if(y==="write_pdf"){let T=Q(W.args).path||null;z=`${T?"\u2714":"\u2718"} Generated: ${T.replaceAll("\\","/")||"No PDF Generated"}`}else if(y==="write_docx"){let T=Q(W.args).path||null;z=`${T?"\u2714":"\u2718"} Generated: ${T.replaceAll("\\","/")||"No Docx Generated"}`}else if(y==="file_map"){let T=Q(W.args).path;z=`${T?"\u2714":"\u2718"} Indexed: ${T.replaceAll("\\","/")?""+T:"File Not Found"}`}else if(y.toLowerCase()==="search_keyword"||y.toLowerCase()==="todo")z="";else if(y.toLowerCase()==="generate_image"){let{path:T,outputPath:V,output:ae}=Q(W.args);z=`\u2714 Generated: ${T||V||ae||"generated_image.png"}`}else if(y==="invoke_sync"||y==="InvokeSync"){let T=Nn(y,W.args);z=`\u2714 Called Generalist${T?`: ${T}`:""}`}else if(y==="Invoke"||y==="InvokeAsync"||y==="invoke"){let T=Nn(y,W.args);z=`\u2714 Started Generalist${T?`: ${T}`:""}`}else if(y==="get_progress"||y==="GetProgress"){let T=Nn(y,W.args);z=`\u2714 Checked${T?`: ${T}`:""}`}else if(y==="cancel"){let T=Nn(y,W.args);z=`\u{1F6C7} Cancelled${T?`: ${T}`:""}`}else if(y==="steer"||y==="Steer"){let T=Nn(y,W.args);z=`\u2714 Steered${T?`: ${T}`:""}`}else if(y==="EmergencyRollback"){let{method:T}=Q(W.args);z=T==="forceRevert"?"":"\u2714 Rollback Point Checked"}else if(y==="await"||y==="Await"){let{time:T,timeout:V}=Q(W.args),ae=parseFloat(V||T)||0;ae||(ae=120);let ce=Ie=>{if(Ie>=60){let Te=Math.floor(Ie/60),q=Ie%60;return`${Te}m${q>0?` ${q}s`:""}`}return`${Ie}s`},be=["Aligning Moon Phase","Contemplating Existence","Staring At Void","Delaying Professionally","Negotiating With Electrons","Touching Grass (virtually)","Panicking Softly","Rethinking Career Choices","Loading Cat Videos","Summoning Braincell #2","Pretending To Be Busy","Waiting For Motivation DLC","Rotating Internal Screaming","Downloading More RAM","Feeding The Hamsters","Gaslighting Scheduler","Performing Dramatic Pause","Buffering Social Energy","Calculating Regret","Reading Terms And Conditions","Becoming Sentient Briefly","Contacting Ancestors"];z=`\u2714 ${be[Math.floor(Math.random()*be.length)]} \u2192 ${ce(ae)}`}else y==="Answer"||y==="answer"?z="\u2714 Resolved Sub-Agent Query":y==="exec_command"||y==="ask"?z="":z=`Executed: ${W.toolName}`;if(yield*Mn(),y==="exec_command"){let{command:T}=Q(W.args);if(T&&n.systemSettings&&n.systemSettings.allowExternalAccess===!1){let V=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],ae=J.resolve(process.cwd()).substring(0,3).toLowerCase(),ce=q=>{let ne=[],le="",Ce=null;for(let ze=0;ze<q.length;ze++){let Re=q[ze];Ce?(Re===Ce&&(Ce=null),le+=Re):Re==='"'||Re==="'"?(Ce=Re,le+=Re):Re==="&"&&q[ze+1]==="&"||Re==="|"&&q[ze+1]==="|"?(le.trim()&&(ne.push(le.trim()),le=""),ze++):Re===";"||Re==="|"||Re==="&"?le.trim()&&(ne.push(le.trim()),le=""):le+=Re}return le.trim()&&ne.push(le.trim()),ne},be=q=>{let ne=[],le="",Ce=null;for(let ze=0;ze<q.length;ze++){let Re=q[ze];Ce?(Re===Ce&&(Ce=null),le+=Re):Re==='"'||Re==="'"?(Ce=Re,le+=Re):/\s/.test(Re)?le&&(ne.push(le),le=""):le+=Re}return le&&ne.push(le),ne},He=q=>{let ne=q.replace(/^['"]|['"]$/g,"").trim();return!ne||process.platform==="win32"&&/^\/[a-zA-Z0-9?]+$/.test(ne)?!1:V.some(le=>{if(le.source==="[a-zA-Z]:[\\\\\\/]"){let Ce=ne.match(/[a-zA-Z]:[\\\/]/i);return Ce&&Ce[0].toLowerCase()!==ae}return le.test(ne)})};if(ce(T).some(q=>{let ne=be(q);if(ne.length===0)return!1;let le=ne[0].replace(/^['"]|['"]$/g,"").toLowerCase();if(["echo","printf","write-output"].includes(le)){let ze=!1;return ne.some(Re=>{let Wt=Re.replace(/^['"]|['"]$/g,"");if(Wt===">"||Wt===">>"||Wt==="<")return ze=!0,!1;if(Wt.startsWith(">")||Wt.startsWith("<")){let Oe=Wt.replace(/^[><]+/,"");return He(Oe)}return ze?(ze=!1,He(Re)):!1})}return ne.some(ze=>He(ze))})){let q='Access Denied. Prohibited from accessing external directories while "External Workspace Access" is disabled.';n.onExecStart&&n.onExecStart(T||"No Command"),yield{type:"exec_start"},await new Promise(ne=>setTimeout(ne,50)),n.onExecChunk&&n.onExecChunk(`ERROR: ${q}`),await new Promise(ne=>setTimeout(ne,50)),n.onExecEnd&&n.onExecEnd(),X.push({role:"user",text:`[TOOL RESULT]: ERROR: ${q}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${q}`},Ve++;continue}}n.onExecStart&&n.onExecStart(T||"No Command"),yield{type:"exec_start"}}let sn=Q(W.args),Dn=sn.path||sn.targetPath||null;if(Dn){let T=n.systemSettings&&n.systemSettings.allowExternalAccess===!1,V=J.resolve(Dn),ae=J.resolve(process.cwd());if(T&&!V.startsWith(ae)){let ce="Access Denied. You are not allowed to access files outside the current workspace.";if(y==="write_file"||y==="update_file"){let He=`\u2718 ${y==="write_file"?"Write Canceled":"Edit Canceled"}: ${sn.path||"..."}`,Ie=115;process.stdout.isTTY&&(Ie=process.stdout.columns-5||120);let Te=Math.min(He.length+4,Ie),q=`${He.padEnd(Te-2).substring(0,Te-2)}`;yield{type:"visual_feedback",content:Vt(`${Be?`
748
+ `;for(let H of L.newFiles)se+=`* ${H} (created)
749
+ `;for(let H of L.modifiedFiles)se+=`* ${H} (modified)
750
+ `;for(let H of L.deletedFiles)se+=`* ${H} (deleted)
751
+ `;se+="[/system]",We.parts[0].text+=se;let F=-1;for(let H=r.length-1;H>=0;H--)if(r[H].role==="user"&&r[H].text?.startsWith("[TOOL RESULT]")){F=H;break}F!==-1&&(r[F].text+=se)}}catch{}let St=Math.floor(qn*(a==="Flux"?.98:.8)),yt=K+1;yt>=St&&We&&We.parts?.[0]&&(We.parts[0].text+=`
752
+ [system] WARNING, Turn Limit Impending: Step ${yt}/${qn}. Wrap up quickly/prompt user to continue. [/system]`);let Rt=new Promise((L,se)=>{w.signal.aborted&&se(new DOMException("The user aborted a request.","AbortError")),w.signal.addEventListener("abort",()=>{se(new DOMException("The user aborted a request.","AbortError"))})});Rt.catch(()=>{});let ut=re;if(i==="Ollama")_e=Bs(n.apiKey,me,ut,Ue,f,a,R,w.signal,1,m?.ollamaEndpoint||"Cloud");else if(i==="OpenRouter")_e=Ko(n.apiKey,me,ut,Ue,f,a,R,w.signal,1,g);else if(i==="DeepSeek")_e=Go(n.apiKey,me,ut,Ue,f,a,R,w.signal,1);else if(i==="Mistral")_e=jo(n.apiKey,me,ut,Ue,f,a,R,w.signal,1,g);else if(i==="NVIDIA"){let L=Vo(n.apiKey,me,ut,Ue,f,a,R,w.signal,1);_e=Tr(L,me)}else if(i==="InferX")_e=Yo(n.apiKey,me,ut,Ue,f,a,R,w.signal,1);else if(i==="SenseNova")_e=qo(n.apiKey,me,ut,Ue,f,a,R,w.signal,1);else if(i==="AIHubMix")_e=zo(n.apiKey,me,ut,Ue,f,a,R,w.signal,1);else if(i==="Poolside")_e=Jo(n.apiKey,me,ut,Ue,f,a,R,w.signal,1);else if(i==="9router"||i==="9Router")_e=Xo(n.apiKey,me,ut,Ue,f,a,R,w.signal,1);else if(i==="ExpLabs"||i==="ExperientialLabs")_e=Qo(n.apiKey,me,ut,Ue,f,a,R,w.signal,1);else if(i==="TokenHarbor"||i==="Token Harbor"||i==="tokenharbor"||i==="token_harbor"||i==="thk")_e=Us(n.apiKey,me,ut,Ue,f,a,R,w.signal,1);else if(i==="APInex"||i==="apinex"||i==="apx")_e=Ws(n.apiKey,me,ut,Ue,f,a,R,w.signal,1);else{let se=Vs(n?.apiKey).models.generateContentStream({model:me||"gemini-3-flash-preview",contents:ut,config:{systemInstruction:Ue,mediaResolution:"MEDIA_RESOLUTION_HIGH",safetySettings:[{category:En.HARM_CATEGORY_HARASSMENT,threshold:_n.BLOCK_NONE},{category:En.HARM_CATEGORY_HATE_SPEECH,threshold:_n.BLOCK_NONE},{category:En.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:_n.BLOCK_NONE},{category:En.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:_n.BLOCK_NONE}],temperature:1.05,thinkingConfig:(()=>{let F=Oe("Google",me||"gemini-3-flash-preview",f);if(F!==null){if(typeof F=="object")return F;if(F===!1||F==="false"||F==="none"||F===0||F==="0")return{includeThoughts:!1};if(typeof F=="number")return{includeThoughts:!0,thinkingBudget:F};if(typeof F=="string"){let he=F.toLowerCase();if(he==="minimal")return{includeThoughts:!0,thinkingLevel:Je.MINIMAL};if(he==="low")return{includeThoughts:!0,thinkingLevel:Je.LOW};if(he==="medium")return{includeThoughts:!0,thinkingLevel:Je.MEDIUM};if(he==="high")return{includeThoughts:!0,thinkingLevel:Je.HIGH};let Ke=Number(F);if(!isNaN(Ke))return{includeThoughts:!0,thinkingBudget:Ke}}}let H=(me||"").toLowerCase(),we=H.includes("gemma-4")||H.startsWith("gemma"),be=H.includes("gemini-3");if(we||be)return we?f.toLowerCase()!=="high"?{includeThoughts:!1,thinkingLevel:Je.MINIMAL}:{includeThoughts:!0,thinkingLevel:Je.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:H.includes("pro")?Je.LOW:Je.MINIMAL,Low:Je.LOW,Medium:Je.MEDIUM,Standard:Je.MEDIUM,High:Je.HIGH,xHigh:Je.HIGH}[f]||Je.MEDIUM};{let he={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[f]||2048;return he===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:he}}})()}},{signal:w.signal});_e=await Promise.race([se,Rt])}ge="",Mt=null,zt=null,Q=[],Ve=0,yield{type:"model_update",content:null},qe="",Dt=st.length>0;let on="",as=Date.now(),Mn=async function*(){if(i==="Google"&&on){let L=Jn(on);for(let se of L)yield se;on="",as=Date.now()}},oi=!0,In="",Bn=!1,Pt=null,Br={tool:{startPrefix:"[tool",fullPrefix:"[tool:functions.",endTag:"]"},agent:{startPrefix:"[agent",fullPrefix:"[agent:generalist.",endTag:"]"},end:{startPrefix:"[[END]]",fullPrefix:"[[END]]",endTag:"[[END]]"},kimi_section:{startPrefix:"<|tool_calls_section_begin|>",fullPrefix:"<|tool_calls_section_begin|>",endTag:"<|tool_calls_section_end|>"},kimi_call:{startPrefix:"<|tool_call_begin|>",fullPrefix:"<|tool_call_begin|>",endTag:"<|tool_call_end|>"}},Jn=L=>{let se=[],F=L;for(;F.length>0;)if(Bn){let H=In+F,we=Br[Pt];if(we){let Ke=!1;if(H.length<we.startPrefix.length?we.startPrefix.startsWith(H)||(Ke=!0):H.startsWith(we.startPrefix)?H.length>=we.fullPrefix.length&&!H.startsWith(we.fullPrefix)&&(Ke=!0):Ke=!0,Ke){se.push({type:"text",content:H}),In="",Bn=!1,Pt=null,F="";break}}let be=-1,he=we?we.endTag:"]";if(Pt==="tool"||Pt==="agent"){let Ke=0,W=null,ne=0,Ne=!1;for(let y=0;y<H.length;y++){let Fe=H[y];if(W){if(Fe===W){let ve=0;for(let z=y-1;z>=0&&H[z]==="\\";z--)ve++;ve%2===0&&(W=null)}}else if(Fe==='"'||Fe==="'"||Fe==="`")W=Fe;else if(Fe==="(")Ke++,Ne=!0;else if(Fe===")")Ke--;else if(Fe==="[")ne++;else if(Fe==="]"){if(Ne&&Ke===0&&ne===1){be=y;break}ne--}}}else be=H.indexOf(he);if(be!==-1){let Ke=he.length;if(!Pt?.startsWith("kimi")){let W=H.substring(0,be+Ke);se.push({type:"text",content:W})}In="",Bn=!1,Pt=null,F=H.substring(be+Ke)}else{let Ke=Pt?.startsWith("kimi")?8192:512;H.length>Ke?(se.push({type:"text",content:H}),In="",Bn=!1,Pt=null):In=H,F="";break}}else{let H=F.indexOf("[tool"),we=F.indexOf("[agent"),be=F.indexOf("[[END]]"),he=F.indexOf("<|tool_calls_section_begin|>"),Ke=F.indexOf("<|tool_call_begin|>"),W=[{type:"tool",idx:H,start:"[tool",end:"]"},{type:"agent",idx:we,start:"[agent",end:"]"},{type:"end",idx:be,start:"[[END]]",end:"[[END]]"},{type:"kimi_section",idx:he,start:"<|tool_calls_section_begin|>",end:"<|tool_calls_section_end|>"},{type:"kimi_call",idx:Ke,start:"<|tool_call_begin|>",end:"<|tool_call_end|>"}].filter(ne=>ne.idx!==-1).sort((ne,Ne)=>ne.idx-Ne.idx);if(W.length>0){let ne=W[0];ne.idx>0&&se.push({type:"text",content:F.substring(0,ne.idx)}),Bn=!0,Pt=ne.type,In="",F=F.substring(ne.idx)}else{let ne=["[tool","[agent","[[END]]","<|tool_calls_section_begin|>","<|tool_call_begin|>"],Ne=-1;for(let y of ne){for(let Fe=y.length-1;Fe>0;Fe--)if(F.endsWith(y.substring(0,Fe))){Ne=F.length-Fe;let ve=ne.indexOf(y);ve===0?Pt="tool":ve===1?Pt="agent":ve===2?Pt="end":ve===3?Pt="kimi_section":Pt="kimi_call";break}if(Ne!==-1)break}if(Ne!==-1)Ne>0&&se.push({type:"text",content:F.substring(0,Ne)}),Bn=!0,In=F.substring(Ne),F="";else{se.push({type:"text",content:F});break}}}return se},Ur=_e[Symbol.asyncIterator]();for(;;){let{value:L,done:se}=await Promise.race([Ur.next(),Rt]);if(se)break;if(L&&L.type==="status"){yield L;continue}let F="",H=L.candidates?.[0]?.content?.parts;if(H&&H.length>0)for(let be of H){let he=typeof be.text=="string"?be.text:be.text?parseChunkText(be.text):"";be.thought?he&&(xe||(F+="<think>",xe=!0),F+=he):he&&(xe&&(F+="</think>",xe=!1),F+=he)}else L.text&&xe&&(F+="</think>",xe=!1);F=Aa(F);let we=F?gs(F):0;if(n&&typeof n.onTokenChunk=="function"&&n.onTokenChunk(F,we),oi&&(yield{type:"status",content:"Thinking"},oi=!1),kt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
753
+
754
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(F){if(Dt){if(qe+=F,qe.length>=64){let W=0,ne=Math.min(st.length,qe.length);for(let y=ne;y>=10;y--)if(st.endsWith(qe.substring(0,y))){W=y;break}let Ne=qe.substring(W);if(Ne){let Fe=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(st)?Ne.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):Ne.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(Fe)if(ge+=Fe,i==="Google")on+=Fe;else{yield*Mn();let ve=Jn(Fe);for(let z of ve)yield z}}Dt=!1,qe=""}continue}else if(ge+=F,i==="Google")on+=F;else{yield*Mn();let W=Jn(F);for(let ne of W)yield ne}let be=La(ge);if(be.inside){Cn=!0,zt||(zt=Date.now());let ne={Ask:"ask",AskUser:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Cancel:"cancel",Await:"await",Answer:"answer",Steer:"steer",steer:"steer"}[be.toolName]||be.toolName,Ne=be.args||"",y=null;if(["write_file","update_file","view_file","read_folder","write_pdf","write_docx","search_keyword","generate_image","file_map","invoke","invoke_sync","get_progress","await","answer"].includes(ne)){let ve=Z(Ne),z=ve.path||ve.targetFile||ve.TargetFile||ve.directory,sn=ve.keyword,Dn=ve.title||ve.task,kn=ve.id||ve.taskId,Ae=ve.timeout||ve.time;if(sn!=null)y=String(sn).replace(Pn,"");else if(z)y=J.basename(String(z).replace(Pn,"").replace(Sr,"/"));else if(Dn&&(ne==="invoke"||ne==="invoke_sync"))y=String(Dn).replace(Pn,"").substring(0,30);else if(kn&&ne==="get_progress")y=String(kn).replace(Pn,"");else if(Ae&&ne==="await"){let $t=parseFloat(String(Ae).replace(Pn,""));isNaN($t)?y=String(Ae).replace(Pn,""):($t<5&&($t=5),$t>120&&($t=120),y=(un=>{if(un>=60){let cs=Math.floor(un/60),Un=un%60;return`${cs}m${Un>0?` ${Un}s`:""}`}return`${un}s`})($t))}else{let $t=Ne.match(Sa);if($t){let Ut=$t[1].replace(Pn,"");ne==="invoke"||ne==="invoke_sync"||ne==="get_progress"?y=Ut.substring(0,30):y=ne==="search_keyword"||ne==="file_map"?Ut:J.basename(Ut.replace(Sr,"/"))}}}let Fe=`${Gs[ne]||ne}${y?` ${y}`:""}`;if((ne!==Mt||y!==et)&&(Mt=ne,et=y,yield{type:"status",content:`${Fe}`},process.stdout.isTTY)){let z={WebSearch:"Searching",web_search:"Searching",WebScrape:"Reading",web_scrape:"Reading",ReadFile:"Reading",read_file:"Reading",ReadFolder:"Reading",read_folder:"Reading",WriteFile:"Writing",write_file:"Writing",UpdateFile:"Editing",update_file:"Editing",WritePdf:"Creating",write_pdf:"Creating",WriteDocx:"Creating",write_docx:"Creating",SearchKeyword:"Searching",search_keyword:"Searching",CodeSearch:"Searching",code_search:"Searching",Run:"Executing",Ask:"User Input Required",AskUser:"User Input Required",Memory:"Updating Memory",GenerateImage:"Generating",InvokeSync:"Sub-Agent Working",invoke_sync:"Sub-Agent Working",Invoke:"Working",invoke:"Working",GetProgress:"Checking Progress",get_progress:"Checking Progress",Cancel:"Stopping Generalist",cancel:"Stopping Generalist",Await:"Waiting",await:"Waiting",EmergencyRollback:"Rolling the Ball",Answer:"Answering Sub-Agent",answer:"Answering Sub-Agent",Steer:"Steering Sub-Agent",steer:"Steering Sub-Agent",Click:"Clicking",click:"Clicking",Drag:"Dragging",drag:"Dragging",Scroll:"Scrolling",scroll:"Scrolling",KeyboardTyping:"Typing",keyboard_typing:"Typing",KeyPress:"Pressing Key",key_press:"Pressing Key",RecaptureScreen:"Recapturing Screen",recapture_screen:"Recapturing Screen"}[ne]||"Working";process.stdout.write(`\x1B]0;${z}...\x07`)}}if(ge.length-bo>150){bo=ge.length;let W=Dr(ge,!1),ne=Hs(W),Ne=ne?(ne.innerContent||"").trim():"",y=Ne.split(/[.!?]\s+/),Fe=new Set(y),ve=y.length>10?(y.length-Fe.size)/y.length:0,z=Ne.split(/\s+/).filter(Me=>Me.length>0).length,sn=.6,Dn=.8,kn=!1;if((i.toLowerCase().includes("google")||i.toLowerCase().includes("mistral"))&&((me||"").toLowerCase().startsWith("gemma")||(me||"").toLowerCase().includes("stral"))){let _={low:256,medium:1024,high:8192,max:16384,xhigh:16384}[f?.toLowerCase()]||2500;kn=z>_}if(ve>sn||kn){yield{type:"status",content:`${ve>sn?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},It=!0,await new Promise(_=>setTimeout(_,3e3));break}let Ut=Rr(ge).trim().split(/[.!?]\s+/),un=new Set(Ut);if((Ut.length>10?(Ut.length-un.size)/Ut.length:0)>Dn){yield{type:"status",content:"Response Loop Detected. Re-centering..."},It=!1,fn=!0,await new Promise(Me=>setTimeout(Me,3e3));break}let Un=W.replace(pa,"").replace(ya,"").replace(xa,"").replace(ba,""),Nt=Un.toLowerCase().split(/\s+/).map(Me=>Me.replace(ka,"")).filter(Me=>Me.length>0),gn=!1;if(Nt.length>=10)for(let Me=1;Me<=15;Me++){let _=Math.max(3,Math.ceil(10/Me));if(Nt.length<Me*_)continue;let V=Nt.slice(Nt.length-Me),ae=V.join(" ");if(Me>1&&ae===V.slice(0,Math.floor(Me/2)).join(" ").repeat(2).trim())continue;let ce=!0;for(let ke=1;ke<_;ke++)if(Nt.slice(Nt.length-Me*(ke+1),Nt.length-Me*ke).join(" ")!==ae){ce=!1;break}if(ce){gn=!0;break}}if(!gn){let Me=Un.toLowerCase().replace(wa,"");if(Me.length>=20)for(let _=1;_<=10;_++){let V=Math.max(5,Math.ceil(16/_));if(Me.length<_*V)continue;let ae=Me.substring(Me.length-_),ce=!0;for(let ke=1;ke<V;ke++)if(Me.substring(Me.length-_*(ke+1),Me.length-_*ke)!==ae){ce=!1;break}if(ce){gn=!0;break}}}if(gn){yield{type:"status",content:"Stuttering Detected. Re-centering..."},It=!1,nn=!0,await new Promise(Me=>setTimeout(Me,3e3));break}}let he=Kt(ge),Ke=ts(he);for(;Ke.length>Ve;){yield*Mn();let W=Ke[Ve],ne=Date.now(),y={Ask:"ask",AskUser:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Await:"await",await:"await",AwaitSubagent:"await",awaitSubagent:"await",Answer:"answer",answer:"answer",AnswerSubagent:"answer",answerSubagent:"answer",Steer:"steer",steer:"steer",SteerSubagent:"steer",steerSubagent:"steer",Cancel:"cancel",cancel:"cancel",Click:"click",click:"click",Drag:"drag",drag:"drag",Scroll:"scroll",scroll:"scroll",KeyboardTyping:"keyboard_typing",keyboard_typing:"keyboard_typing",KeyPress:"key_press",key_press:"key_press",RecaptureScreen:"recapture_screen",recapture_screen:"recapture_screen",EmergencyRollback:"EmergencyRollback"}[W.toolName]||W.toolName,Fe=Gs[y]||W.toolName,ve=Nn(y,W.args);yield{type:"status",content:`${Fe}${ve?` ${ve}`:""}`};let z="";if(y==="click"){let _=Z(W.args);z=`\u2714 Clicked: ${_.intendedClickText?`${_.intendedClickText}`:""}`}else if(y==="drag"){let _=Z(W.args);z=`\u2714 Dragged: Cell ${_.fromGridId||""} \u2192 Cell ${_.toGridId||""}`}else if(y==="scroll"){let _=Z(W.args);z=`\u2714 Scrolled: ${_.direction||"down"} (${_.amount||1})`}else if(y==="keyboard_typing"){let _=Z(W.args);z=`\u2714 Typed: ${_.text?`"${_.text.length>20?_.text.substring(0,20)+"...":_.text}"`:""}`}else if(y==="key_press")z=`\u2714 Pressed Key: ${Z(W.args).key||""}`;else if(y==="recapture_screen")z="\u2714 Recaptured Screen";else if(y==="web_search"){let{query:_,limit:V=10,aiMode:ae=!1}=Z(W.args);z=`${_?"\u2714":"\u2718"} ${ae?"AI Search":"Searched"}: ${_?`${_}`:"No Search Query"}${ae===!1&&_?` \u2192 ${V}`:""}`}else if(y==="web_scrape"){let _=Z(W.args).url||null;z=`${_?"\u2714":"\u2718"} Visited: ${_||"No Source"}`}else if(y==="view_file"){let{path:_,StartLine:V,EndLine:ae,start_line:ce,end_line:ke,startLine:He,endLine:Ie}=Z(W.args),Te=V||ce||He,q=ae||ke||Ie,oe=parseInt(Te)||1,le=parseInt(q)||(Te?oe+800:800),Ce="...",ze=le,Re=(_||"").trim().toLowerCase().replaceAll("\\","/");if(Re.startsWith("#skill"))Re.startsWith("#skill/global/fluxflow")||Re.startsWith("#skills/global/fluxflow")?z="\u2714 Read Documentation":z=`\u2714 Read Skill: ${J.basename(_.replaceAll("\\","/"))}`;else{try{let ye=J.resolve(process.cwd(),_);if($e.existsSync(ye)){let ht=$e.readFileSync(ye,"utf8").split(`
755
+ `).length;Ce=ht,!Te&&!q&&ht>800?ze=Math.min(50,ht):ze=Math.min(le,ht)}}catch{}let Le=(_||"").toLowerCase(),gt=Le.endsWith(".pdf"),De=Le.endsWith(".docx")||Le.endsWith(".doc")||Le.endsWith(".ppt")||Le.endsWith(".pptx")||Le.endsWith(".xls")||Le.endsWith(".xlsx"),ot=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(Le);gt||De?z=`${_.length>0?"\u2714":"\u2718"} ${_?`Analyzed: ${J.basename(_)}`:"Analyzed: File Not Found"}`:ot?z=`${_.length>0?"\u2714":"\u2718"} ${_?`Processed: ${J.basename(_)}`:"Processed: File Not Found"}`:z=`${Ce!=="..."?"\u2714":"\u2718"} Read: ${_?`${J.basename(_)} \u2192 ${Ce!=="..."?`Lines ${oe} - ${ze} of ${Ce}`:"File Not Found"}`:"File Not Found"}`}}else if(y==="list_files"||y==="read_folder"){let _=y==="list_files"?"List":"Browsed",V=Z(W.args).path||null,ae=Z(W.args).recurse||1;z=`${V?"\u2714":"\u2718"} ${_}: ${V?`${V==="."?`./${ae>1?"*":""}`:`${V.replaceAll("\\","/")}${ae>1?`${V.endsWith("/")?"*":"/*"}`:`${V.endsWith("/")?"":"/"}`}`}`:"No Folder Selected"}`}else if(y==="write_file"||y==="update_file"){let _=y==="write_file"?"Created":"Edited",V=Z(W.args).path||null;z=`${V?"\u2714":"\u2718"} ${_}: ${V.replaceAll("\\","/")||"No File Changes"}`}else if(y==="write_pdf"){let _=Z(W.args).path||null;z=`${_?"\u2714":"\u2718"} Generated: ${_.replaceAll("\\","/")||"No PDF Generated"}`}else if(y==="write_docx"){let _=Z(W.args).path||null;z=`${_?"\u2714":"\u2718"} Generated: ${_.replaceAll("\\","/")||"No Docx Generated"}`}else if(y==="file_map"){let _=Z(W.args).path;z=`${_?"\u2714":"\u2718"} Indexed: ${_.replaceAll("\\","/")?""+_:"File Not Found"}`}else if(y.toLowerCase()==="search_keyword"||y.toLowerCase()==="todo")z="";else if(y.toLowerCase()==="generate_image"){let{path:_,outputPath:V,output:ae}=Z(W.args);z=`\u2714 Generated: ${_||V||ae||"generated_image.png"}`}else if(y==="invoke_sync"||y==="InvokeSync"){let _=Nn(y,W.args);z=`\u2714 Called Generalist${_?`: ${_}`:""}`}else if(y==="Invoke"||y==="InvokeAsync"||y==="invoke"){let _=Nn(y,W.args);z=`\u2714 Started Generalist${_?`: ${_}`:""}`}else if(y==="get_progress"||y==="GetProgress"){let _=Nn(y,W.args);z=`\u2714 Checked${_?`: ${_}`:""}`}else if(y==="cancel"){let _=Nn(y,W.args);z=`\u{1F6C7} Cancelled${_?`: ${_}`:""}`}else if(y==="steer"||y==="Steer"){let _=Nn(y,W.args);z=`\u2714 Steered${_?`: ${_}`:""}`}else if(y==="EmergencyRollback"){let{method:_}=Z(W.args);z=_==="forceRevert"?"":"\u2714 Rollback Point Checked"}else if(y==="await"||y==="Await"){let{time:_,timeout:V}=Z(W.args),ae=parseFloat(V||_)||0;ae||(ae=120);let ce=Ie=>{if(Ie>=60){let Te=Math.floor(Ie/60),q=Ie%60;return`${Te}m${q>0?` ${q}s`:""}`}return`${Ie}s`},ke=["Aligning Moon Phase","Contemplating Existence","Staring At Void","Delaying Professionally","Negotiating With Electrons","Touching Grass (virtually)","Panicking Softly","Rethinking Career Choices","Loading Cat Videos","Summoning Braincell #2","Pretending To Be Busy","Waiting For Motivation DLC","Rotating Internal Screaming","Downloading More RAM","Feeding The Hamsters","Gaslighting Scheduler","Performing Dramatic Pause","Buffering Social Energy","Calculating Regret","Reading Terms And Conditions","Becoming Sentient Briefly","Contacting Ancestors"];z=`\u2714 ${ke[Math.floor(Math.random()*ke.length)]} \u2192 ${ce(ae)}`}else y==="Answer"||y==="answer"?z="\u2714 Resolved Sub-Agent Query":y==="exec_command"||y==="ask"?z="":z=`Executed: ${W.toolName}`;if(yield*Mn(),y==="exec_command"){let{command:_}=Z(W.args);if(_&&n.systemSettings&&n.systemSettings.allowExternalAccess===!1){let V=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],ae=J.resolve(process.cwd()).substring(0,3).toLowerCase(),ce=q=>{let oe=[],le="",Ce=null;for(let ze=0;ze<q.length;ze++){let Re=q[ze];Ce?(Re===Ce&&(Ce=null),le+=Re):Re==='"'||Re==="'"?(Ce=Re,le+=Re):Re==="&"&&q[ze+1]==="&"||Re==="|"&&q[ze+1]==="|"?(le.trim()&&(oe.push(le.trim()),le=""),ze++):Re===";"||Re==="|"||Re==="&"?le.trim()&&(oe.push(le.trim()),le=""):le+=Re}return le.trim()&&oe.push(le.trim()),oe},ke=q=>{let oe=[],le="",Ce=null;for(let ze=0;ze<q.length;ze++){let Re=q[ze];Ce?(Re===Ce&&(Ce=null),le+=Re):Re==='"'||Re==="'"?(Ce=Re,le+=Re):/\s/.test(Re)?le&&(oe.push(le),le=""):le+=Re}return le&&oe.push(le),oe},He=q=>{let oe=q.replace(/^['"]|['"]$/g,"").trim();return!oe||process.platform==="win32"&&/^\/[a-zA-Z0-9?]+$/.test(oe)?!1:V.some(le=>{if(le.source==="[a-zA-Z]:[\\\\\\/]"){let Ce=oe.match(/[a-zA-Z]:[\\\/]/i);return Ce&&Ce[0].toLowerCase()!==ae}return le.test(oe)})};if(ce(_).some(q=>{let oe=ke(q);if(oe.length===0)return!1;let le=oe[0].replace(/^['"]|['"]$/g,"").toLowerCase();if(["echo","printf","write-output"].includes(le)){let ze=!1;return oe.some(Re=>{let Wt=Re.replace(/^['"]|['"]$/g,"");if(Wt===">"||Wt===">>"||Wt==="<")return ze=!0,!1;if(Wt.startsWith(">")||Wt.startsWith("<")){let Le=Wt.replace(/^[><]+/,"");return He(Le)}return ze?(ze=!1,He(Re)):!1})}return oe.some(ze=>He(ze))})){let q='Access Denied. Prohibited from accessing external directories while "External Workspace Access" is disabled.';n.onExecStart&&n.onExecStart(_||"No Command"),yield{type:"exec_start"},await new Promise(oe=>setTimeout(oe,50)),n.onExecChunk&&n.onExecChunk(`ERROR: ${q}`),await new Promise(oe=>setTimeout(oe,50)),n.onExecEnd&&n.onExecEnd(),Q.push({role:"user",text:`[TOOL RESULT]: ERROR: ${q}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${q}`},Ve++;continue}}n.onExecStart&&n.onExecStart(_||"No Command"),yield{type:"exec_start"}}let sn=Z(W.args),Dn=sn.path||sn.targetPath||null;if(Dn){let _=n.systemSettings&&n.systemSettings.allowExternalAccess===!1,V=J.resolve(Dn),ae=J.resolve(process.cwd());if(_&&!V.startsWith(ae)){let ce="Access Denied. You are not allowed to access files outside the current workspace.";if(y==="write_file"||y==="update_file"){let He=`\u2718 ${y==="write_file"?"Write Canceled":"Edit Canceled"}: ${sn.path||"..."}`,Ie=115;process.stdout.isTTY&&(Ie=process.stdout.columns-5||120);let Te=Math.min(He.length+4,Ie),q=`${He.padEnd(Te-2).substring(0,Te-2)}`;yield{type:"visual_feedback",content:Vt(`${Be?`
755
756
  `:""}${q}
756
- `)},Be=!1}X.push({role:"user",text:`[TOOL RESULT]: ERROR: ${ce}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${ce}`},Ve++;continue}}if(n.onToolApproval&&(y==="write_file"||y==="update_file"||y==="exec_command")){let V=n.systemSettings||{},ae=V.autoExec,ce=null,be=!1,He=!1,Ie=!1;if(y==="exec_command"){let{command:Oe}=Q(W.args),gt=(Oe||"").trim(),De=(Ht,ht)=>{if(!ht)return!1;let Zt=ht.split(",").map(Gt=>Gt.trim().toLowerCase()).filter(Boolean),rt=Ht.toLowerCase();return Zt.some(Gt=>rt.startsWith(Gt))},ot=De(gt,V.alwaysAskCommands),pe=De(gt,V.autoApproveCommands);if(He=De(gt,V.autoDisallowCommands),ot?be=!0:(pe||V.autoApproveGit&&/^git\s+commit\b/i.test(gt))&&(ce="allow"),!be&&!ce){if(V.networkAccess===!1){let ht=gt.trim().replace(/\s+/g," ").replace(/^['"]+|['"]+$/g,"").toLowerCase().split(" "),rt=ht[0].split("/").pop().split("\\").pop().replace(/\.exe$/,""),Gt=new Set(["curl","wget","httpie","xh","ssh","scp","sftp","rsync","ftp","lftp","tftp","telnet","nc","netcat","socat","ping","traceroute","tracert","dig","nslookup","host","whois","nmap","docker","podman","kubectl","helm","gcloud","aws","az","terraform","ansible-playbook","nix","nix-env","apt","apt-get","dpkg","yum","dnf","pacman","zypper","brew","apk","choco","scoop","conda","mamba","aria2c","axel","smbclient","lynx","w3m","links","elinks","heroku","netlify","vercel","firebase","supabase","wrangler","flyctl","powershell","pwsh","certutil","bitsadmin","cloudflared","ngrok","tailscale","zerotier","rclone"]),at=!1;Gt.has(rt)&&(at=!0);let it=rn=>ht.slice(1).some(an=>rn.includes(an)),lt=rn=>{let an=ht.findIndex(mn=>rn.includes(mn)),Wn=ht.findIndex(mn=>["run","exec","test"].includes(mn));return an!==-1&&!(Wn!==-1&&Wn<an)};rt==="git"&&it(["clone","pull","push","fetch"])&&(at=!0),rt==="go"&&it(["get","install"])&&(at=!0),rt==="npm"&&lt(["install","i","update","add"])&&(at=!0),rt==="yarn"&&lt(["add","install","upgrade"])&&(at=!0),rt==="pnpm"&&lt(["add","install","update"])&&(at=!0),rt==="bun"&&lt(["add","install","update"])&&(at=!0),rt==="deno"&&it(["install","add"])&&(at=!0),rt==="pip"&&it(["install","download"])&&(at=!0),rt==="pip3"&&it(["install","download"])&&(at=!0),rt==="cargo"&&it(["install","add"])&&(at=!0),["bash","sh","zsh","fish"].includes(rt)&&it(["-c"])&&(at=!0),rt==="cmd"&&it(["/c"])&&(at=!0),at&&(ce="deny",Ie=!0)}!ce&&He&&(ce="deny")}!be&&!ce&&ae&&(ce="allow")}else ae&&(ce="allow");let Te=ce,q="";ce==="deny"&&(Ie?q="network":He?q="settings":q="prohibited");let ne=!1,le="",Ce=[],ze=0,Re=!1,Wt="";if(!Te){if(y==="write_file"||y==="update_file")try{let De=Q(W.args),{path:ot}=De;if(ot){let pe=J.resolve(process.cwd(),ot),Ht=it=>it?it.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,lt=>lt.toUpperCase()):"",ht=Ht(pe),Zt="",rt=!1,Gt=await Ln(),at=Ht(Gt?.file_focused);if(Gt&&at===ht&&Gt.full_content?(Zt=Gt.full_content,rt=!0):Pe.existsSync(pe)&&(Zt=Pe.readFileSync(pe,"utf8"),rt=!0),le=Zt,await _o.recordFileChange(pe,Zt),rt){let it=Zt;if(y==="write_file"){let lt=De.content||De.newContent||"";it=lt.endsWith(`
757
+ `)},Be=!1}Q.push({role:"user",text:`[TOOL RESULT]: ERROR: ${ce}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${ce}`},Ve++;continue}}if(n.onToolApproval&&(y==="write_file"||y==="update_file"||y==="exec_command")){let V=n.systemSettings||{},ae=V.autoExec,ce=null,ke=!1,He=!1,Ie=!1;if(y==="exec_command"){let{command:Le}=Z(W.args),gt=(Le||"").trim(),De=(Ht,ht)=>{if(!ht)return!1;let Zt=ht.split(",").map(Gt=>Gt.trim().toLowerCase()).filter(Boolean),rt=Ht.toLowerCase();return Zt.some(Gt=>rt.startsWith(Gt))},ot=De(gt,V.alwaysAskCommands),ye=De(gt,V.autoApproveCommands);if(He=De(gt,V.autoDisallowCommands),ot?ke=!0:(ye||V.autoApproveGit&&/^git\s+commit\b/i.test(gt))&&(ce="allow"),!ke&&!ce){if(V.networkAccess===!1){let ht=gt.trim().replace(/\s+/g," ").replace(/^['"]+|['"]+$/g,"").toLowerCase().split(" "),rt=ht[0].split("/").pop().split("\\").pop().replace(/\.exe$/,""),Gt=new Set(["curl","wget","httpie","xh","ssh","scp","sftp","rsync","ftp","lftp","tftp","telnet","nc","netcat","socat","ping","traceroute","tracert","dig","nslookup","host","whois","nmap","docker","podman","kubectl","helm","gcloud","aws","az","terraform","ansible-playbook","nix","nix-env","apt","apt-get","dpkg","yum","dnf","pacman","zypper","brew","apk","choco","scoop","conda","mamba","aria2c","axel","smbclient","lynx","w3m","links","elinks","heroku","netlify","vercel","firebase","supabase","wrangler","flyctl","powershell","pwsh","certutil","bitsadmin","cloudflared","ngrok","tailscale","zerotier","rclone"]),at=!1;Gt.has(rt)&&(at=!0);let it=rn=>ht.slice(1).some(an=>rn.includes(an)),lt=rn=>{let an=ht.findIndex(mn=>rn.includes(mn)),Wn=ht.findIndex(mn=>["run","exec","test"].includes(mn));return an!==-1&&!(Wn!==-1&&Wn<an)};rt==="git"&&it(["clone","pull","push","fetch"])&&(at=!0),rt==="go"&&it(["get","install"])&&(at=!0),rt==="npm"&&lt(["install","i","update","add"])&&(at=!0),rt==="yarn"&&lt(["add","install","upgrade"])&&(at=!0),rt==="pnpm"&&lt(["add","install","update"])&&(at=!0),rt==="bun"&&lt(["add","install","update"])&&(at=!0),rt==="deno"&&it(["install","add"])&&(at=!0),rt==="pip"&&it(["install","download"])&&(at=!0),rt==="pip3"&&it(["install","download"])&&(at=!0),rt==="cargo"&&it(["install","add"])&&(at=!0),["bash","sh","zsh","fish"].includes(rt)&&it(["-c"])&&(at=!0),rt==="cmd"&&it(["/c"])&&(at=!0),at&&(ce="deny",Ie=!0)}!ce&&He&&(ce="deny")}!ke&&!ce&&ae&&(ce="allow")}else ae&&(ce="allow");let Te=ce,q="";ce==="deny"&&(Ie?q="network":He?q="settings":q="prohibited");let oe=!1,le="",Ce=[],ze=0,Re=!1,Wt="";if(!Te){if(y==="write_file"||y==="update_file")try{let De=Z(W.args),{path:ot}=De;if(ot){let ye=J.resolve(process.cwd(),ot),Ht=it=>it?it.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,lt=>lt.toUpperCase()):"",ht=Ht(ye),Zt="",rt=!1,Gt=await Ln(),at=Ht(Gt?.file_focused);if(Gt&&at===ht&&Gt.full_content?(Zt=Gt.full_content,rt=!0):$e.existsSync(ye)&&(Zt=$e.readFileSync(ye,"utf8"),rt=!0),le=Zt,await Eo.recordFileChange(ye,Zt),rt){let it=Zt;if(y==="write_file"){let lt=De.content||De.newContent||"";it=lt.endsWith(`
757
758
  `)?lt:lt+`
758
- `,Wt=it}else{let{patchPairs:lt,allowMultiple:rn,error:an}=ri(De);if(an){let bt=`[TOOL RESULT]: ERROR: ${an}`;X.push({role:"user",text:bt}),await Et("toolFailure"),n.onToolResult&&n.onToolResult("failure",y),yield{type:"tool_result",content:bt,toolName:y},Ve++;continue}let Wn=De.allowMultiple!==void 0?De.allowMultiple===!0||String(De.allowMultiple).toLowerCase()==="true":rn;ze=lt.length;let mn=ai(Zt,lt,{allowMultiple:Wn});it=mn.content,Wt=it,Ce=mn.results;let bo=Ce.filter(bt=>bt.success),xt=Ce.filter(bt=>!bt.success);if(bo.length===0){let bt=`[TOOL RESULT]: ERROR: Failed to apply patches to [${J.basename(pe)}].
759
+ `,Wt=it}else{let{patchPairs:lt,allowMultiple:rn,error:an}=ri(De);if(an){let bt=`[TOOL RESULT]: ERROR: ${an}`;Q.push({role:"user",text:bt}),await Et("toolFailure"),n.onToolResult&&n.onToolResult("failure",y),yield{type:"tool_result",content:bt,toolName:y},Ve++;continue}let Wn=De.allowMultiple!==void 0?De.allowMultiple===!0||String(De.allowMultiple).toLowerCase()==="true":rn;ze=lt.length;let mn=ai(Zt,lt,{allowMultiple:Wn});it=mn.content,Wt=it,Ce=mn.results;let ko=Ce.filter(bt=>bt.success),xt=Ce.filter(bt=>!bt.success);if(ko.length===0){let bt=`[TOOL RESULT]: ERROR: Failed to apply patches to [${J.basename(ye)}].
759
760
  ${xt.map(Zn=>` \u2022 ${Zn.error}`).join(`
760
- `)}`,Hn=`\u2714 Edited: ${J.basename(pe.replaceAll("\\","/"))}`,Qn=115;process.stdout.isTTY&&(Qn=process.stdout.columns-5||120);let Gn=Math.min(Hn.length+4,Qn),ko=`${Hn.padEnd(Gn-2).substring(0,Gn-2)}`;yield{type:"visual_feedback",content:Vt(`${Be?`
761
- `:""}${ko}`)},Be=!1,X.push({role:"user",text:bt}),await Et("toolFailure"),n.onToolResult&&n.onToolResult("failure",y),yield{type:"tool_result",content:bt,toolName:y},Ve++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${J.basename(pe)}`},Ps(pe,Zt,it),ne=!0,await new Promise(lt=>setTimeout(lt,50))}else if(y==="write_file"){let it=De.content||De.newContent||"",lt=it.endsWith(`
761
+ `)}`,Hn=`\u2714 Edited: ${J.basename(ye.replaceAll("\\","/"))}`,Qn=115;process.stdout.isTTY&&(Qn=process.stdout.columns-5||120);let Gn=Math.min(Hn.length+4,Qn),wo=`${Hn.padEnd(Gn-2).substring(0,Gn-2)}`;yield{type:"visual_feedback",content:Vt(`${Be?`
762
+ `:""}${wo}`)},Be=!1,Q.push({role:"user",text:bt}),await Et("toolFailure"),n.onToolResult&&n.onToolResult("failure",y),yield{type:"tool_result",content:bt,toolName:y},Ve++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${J.basename(ye)}`},Ps(ye,Zt,it),oe=!0,await new Promise(lt=>setTimeout(lt,50))}else if(y==="write_file"){let it=De.content||De.newContent||"",lt=it.endsWith(`
762
763
  `)?it:it+`
763
- `;Wt=lt,Pe.existsSync(pe)||(Re=!0,Pe.mkdirSync(J.dirname(pe),{recursive:!0}),Pe.writeFileSync(pe,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${J.basename(pe)}`},Ps(pe,"",lt),ne=!0,await new Promise(rn=>setTimeout(rn,50))}}}catch(De){console.error("Simulation/Diff Error:",De)}let Oe=null;Ls(De=>{Oe=De});let gt=n.onToolApproval;if(Te=await new Promise(async De=>{let ot=setInterval(()=>{Oe&&(Zo.onIDEApproval&&Zo.onIDEApproval(Oe),clearInterval(ot),De(Oe))},100);try{let pe=await gt(y,W.args);clearInterval(ot),De(pe)}catch{clearInterval(ot),De("deny")}}),Ls(null),y==="write_file"||y==="update_file"){let{path:De}=Q(W.args);if(De){let ot=J.resolve(process.cwd(),De);if(kr(ot,Te),Te==="deny"&&Re&&Pe.existsSync(ot))try{Pe.unlinkSync(ot)}catch{}}}Te==="deny"&&(q="user")}if(Te==="allow"&&ne&&Wo()){let{path:Oe}=Q(W.args),gt=J.resolve(process.cwd(),Oe),De=xt=>xt?J.resolve(xt).replace(/\\/g,"/").toLowerCase():"",ot=await Ln(),pe="";if(ot&&ot.file_focused&&De(ot.file_focused)===De(gt)&&ot.full_content&&(pe=ot.full_content),!pe&&Pe.existsSync(gt)){let xt=Pe.readFileSync(gt,"utf8");xt&&(pe=xt)}!pe&&Wt&&(pe=Wt),(pe||Re)&&Pe.writeFileSync(gt,pe,"utf8");let Ht=pe.split(/\r?\n/),ht=Ht.length,Zt=Buffer.byteLength(pe,"utf8"),rt="";le&&(rt=`Old File contents:
764
+ `;Wt=lt,$e.existsSync(ye)||(Re=!0,$e.mkdirSync(J.dirname(ye),{recursive:!0}),$e.writeFileSync(ye,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${J.basename(ye)}`},Ps(ye,"",lt),oe=!0,await new Promise(rn=>setTimeout(rn,50))}}}catch(De){console.error("Simulation/Diff Error:",De)}let Le=null;Ls(De=>{Le=De});let gt=n.onToolApproval;if(Te=await new Promise(async De=>{let ot=setInterval(()=>{Le&&(Zo.onIDEApproval&&Zo.onIDEApproval(Le),clearInterval(ot),De(Le))},100);try{let ye=await gt(y,W.args);clearInterval(ot),De(ye)}catch{clearInterval(ot),De("deny")}}),Ls(null),y==="write_file"||y==="update_file"){let{path:De}=Z(W.args);if(De){let ot=J.resolve(process.cwd(),De);if(kr(ot,Te),Te==="deny"&&Re&&$e.existsSync(ot))try{$e.unlinkSync(ot)}catch{}}}Te==="deny"&&(q="user")}if(Te==="allow"&&oe&&Wo()){let{path:Le}=Z(W.args),gt=J.resolve(process.cwd(),Le),De=xt=>xt?J.resolve(xt).replace(/\\/g,"/").toLowerCase():"",ot=await Ln(),ye="";if(ot&&ot.file_focused&&De(ot.file_focused)===De(gt)&&ot.full_content&&(ye=ot.full_content),!ye&&$e.existsSync(gt)){let xt=$e.readFileSync(gt,"utf8");xt&&(ye=xt)}!ye&&Wt&&(ye=Wt),(ye||Re)&&$e.writeFileSync(gt,ye,"utf8");let Ht=ye.split(/\r?\n/),ht=Ht.length,Zt=Buffer.byteLength(ye,"utf8"),rt="";le&&(rt=`Old File contents:
764
765
  ${le.split(/\r?\n/).map((bt,Hn)=>`${Hn+1} | ${bt}`).join(`
765
766
  `)}
766
767
 
@@ -771,62 +772,62 @@ ${le.split(/\r?\n/).map((bt,Hn)=>`${Hn+1} | ${bt}`).join(`
771
772
 
772
773
  ... [${ht-100} lines truncated for history stability] ...
773
774
 
774
- ${bt}`}let at="";if(y==="update_file"){let xt=li(le,pe,Ce,12,n?.compressToolResults||Zo?.systemSettings?.compressToolResults);at=`SUCCESS: File [${Oe}] updated via IDE Companion (May have user edits). [${Ce.length}/${ze}] blocks applied.
775
+ ${bt}`}let at="";if(y==="update_file"){let xt=li(le,ye,Ce,12,n?.compressToolResults||Zo?.systemSettings?.compressToolResults);at=`SUCCESS: File [${Le}] updated via IDE Companion (May have user edits). [${Ce.length}/${ze}] blocks applied.
775
776
 
776
- ${xt}`}else{let xt=pe.split(/\r?\n/),bt=xt.length,Hn=Buffer.byteLength(pe,"utf8"),Qn="";le&&(Qn=`Old File contents:
777
+ ${xt}`}else{let xt=ye.split(/\r?\n/),bt=xt.length,Hn=Buffer.byteLength(ye,"utf8"),Qn="";le&&(Qn=`Old File contents:
777
778
  ${le.split(/\r?\n/).map((Zn,Yr)=>`${Yr+1} | ${Zn}`).join(`
778
779
  `)}
779
780
 
780
781
  `);let Gn="";if(bt<=100)Gn=xt.join(`
781
- `);else{let ko=xt.slice(0,50).join(`
782
+ `);else{let wo=xt.slice(0,50).join(`
782
783
  `),Zn=xt.slice(-50).join(`
783
- `);Gn=`${ko}
784
+ `);Gn=`${wo}
784
785
 
785
786
  ... [${bt-100} lines truncated] ...
786
787
 
787
- ${Zn}`}at=`SUCCESS: File [${Oe}] saved via IDE Companion (May have user edits).
788
+ ${Zn}`}at=`SUCCESS: File [${Le}] saved via IDE Companion (May have user edits).
788
789
  - Stats: [${bt} lines, ${(Hn/1024).toFixed(1)} KB]
789
790
  ${Qn}- Content Preview:
790
791
 
791
- ${Gn}`}let lt=`${Oe?"\u2714":"\u2718"} ${y==="write_file"?"Created":"Edited"}: ${Oe.replaceAll("\\","/")||"No File Changes"}`,rn=115;process.stdout.isTTY&&(rn=process.stdout.columns-5||120);let an=Math.min(lt.length+4,rn),Wn=`${lt.padEnd(an-2).substring(0,an-2)}`;yield{type:"visual_feedback",content:Vt(`${Be?`
792
- `:""}${Wn}`)},Be=!1;let mn=Date.now();j=mn,yield{type:"tool_time",content:mn-te};let bo=`[TOOL RESULT]: ${at}`;X.push({role:"user",text:bo}),Xt=!0,await Et("toolSuccess"),n.onToolResult&&n.onToolResult("success",y),yield{type:"tool_result",content:at,aiContent:bo,toolName:y},Ve++;continue}if(Te==="deny"){let Oe=`Permission Denied: Prohibited ${y==="exec_command"?"Command":"file edit"}.`;if(q==="user"?Oe="Permission Denied by User":q==="settings"?Oe="Permission Denied by User Policy":q==="network"?Oe="Permission Denied: Sandbox Network Access Disabled by User Policy.":q==="prohibited"&&y==="exec_command"&&(Oe="Permission Denied: Prohibited Command in User Policy"),y==="write_file"||y==="update_file"){let De=`\u2718 ${y==="write_file"?"Write Cancelled":"Edit Denied"}: ${Q(W.args).path.replaceAll("\\","/")||"..."}`,ot=115;process.stdout.isTTY&&(ot=process.stdout.columns-5||120);let pe=Math.min(De.length+4,ot),Ht=`${De.padEnd(pe-2).substring(0,pe-2)}`,ht=` ${" ".repeat(pe)} `;yield{type:"visual_feedback",content:Vt(`${Be?`
792
+ ${Gn}`}let lt=`${Le?"\u2714":"\u2718"} ${y==="write_file"?"Created":"Edited"}: ${Le.replaceAll("\\","/")||"No File Changes"}`,rn=115;process.stdout.isTTY&&(rn=process.stdout.columns-5||120);let an=Math.min(lt.length+4,rn),Wn=`${lt.padEnd(an-2).substring(0,an-2)}`;yield{type:"visual_feedback",content:Vt(`${Be?`
793
+ `:""}${Wn}`)},Be=!1;let mn=Date.now();j=mn,yield{type:"tool_time",content:mn-ne};let ko=`[TOOL RESULT]: ${at}`;Q.push({role:"user",text:ko}),Xt=!0,await Et("toolSuccess"),n.onToolResult&&n.onToolResult("success",y),yield{type:"tool_result",content:at,aiContent:ko,toolName:y},Ve++;continue}if(Te==="deny"){let Le=`Permission Denied: Prohibited ${y==="exec_command"?"Command":"file edit"}.`;if(q==="user"?Le="Permission Denied by User":q==="settings"?Le="Permission Denied by User Policy":q==="network"?Le="Permission Denied: Sandbox Network Access Disabled by User Policy.":q==="prohibited"&&y==="exec_command"&&(Le="Permission Denied: Prohibited Command in User Policy"),y==="write_file"||y==="update_file"){let De=`\u2718 ${y==="write_file"?"Write Cancelled":"Edit Denied"}: ${Z(W.args).path.replaceAll("\\","/")||"..."}`,ot=115;process.stdout.isTTY&&(ot=process.stdout.columns-5||120);let ye=Math.min(De.length+4,ot),Ht=`${De.padEnd(ye-2).substring(0,ye-2)}`,ht=` ${" ".repeat(ye)} `;yield{type:"visual_feedback",content:Vt(`${Be?`
793
794
  `:""}${Ht}
794
- `)},Be=!1}y==="exec_command"&&(await new Promise(gt=>setTimeout(gt,50)),n.onExecChunk&&n.onExecChunk(`ERROR: ${Oe}`),await new Promise(gt=>setTimeout(gt,50)),n.onExecEnd&&n.onExecEnd()),X.push({role:"user",text:`[TOOL RESULT]: DENIED: ${Oe}`}),yield{type:"tool_result",content:`[TOOL RESULT]: DENIED: ${Oe}`},await Et("toolDenied"),n.onToolResult&&n.onToolResult("denied",y),Ve++;continue}}if(z){let T=115;process.stdout.isTTY&&(T=process.stdout.columns-5||120);let V=await s(),ae=!1;V&&(ae=V.trim().length>0);let ce=Math.min(z.length+4,T),be=`${z.padEnd(ce-2).substring(0,ce-2)}`;yield{type:"visual_feedback",content:Vt(`${Be?`
795
- `:""}${be}${z.includes("\u2714")&&(z.includes("Created")||z.includes("Edited"))?"":`${ae?"":`
796
- `}`}`)},Be=!1}if(j>0){let T=Date.now()-j,V=Math.max(0,1e3-T);V>0&&await new Promise(ae=>setTimeout(ae,V))}let kn={chatId:g,history:t,onChunk:T=>n.onExecChunk?n.onExecChunk(T):null,onAskUser:n.onAskUser,systemSettings:n.systemSettings,mode:a,isMultiModal:dt(me),onVisualFeedback:n.onVisualFeedback,onSubagentUpdate:n.onSubagentUpdate,onTokenChunk:n.onTokenChunk,modelName:me,aiProvider:n.aiProvider,apiKey:n.apiKey,onUsage:n.onUsage};if(y==="write_file"||y==="update_file")try{let{path:T}=Q(W.args);if(T){let V=J.resolve(process.cwd(),T),ae=await Ln();ae&&ae.file_focused===V&&ae.full_content&&(kn.forcedContent=ae.full_content)}}catch{}qt.push(y);let Ae=await co(y,W.args,kn);if((y==="write_file"||y==="update_file")&&Ae.startsWith("SUCCESS")){let{path:T}=Q(W.args);if(T){let V=J.resolve(process.cwd(),T);br(V)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let $t=Date.now();j=$t,yield{type:"tool_time",content:$t-te},zt=$t;let Ut=null;if(typeof Ae=="object"&&Ae.binaryPart&&(Ut=Ae.binaryPart,Ae=Ae.text),y==="search_keyword"){let{keyword:T,path:V}=Q(W.args),ae=typeof Ae=="string"&&Ae.startsWith("[GLOB]");ae&&(Ae=Ae.slice(6).trimStart());let ce=typeof Ae=="string"&&Ae.startsWith("[DIR]");ce&&(Ae=Ae.slice(5).trimStart());let be=0;if(Ae){let Ce=Ae.match(/Found (\d+) match/i);Ce&&(be=parseInt(Ce[1]))}let He=(V||"").trim().toLowerCase().replaceAll("\\","/"),Ie=He==="#doc"||He==="#docs"||He==="#documentation"||He.includes("#skill/global/fluxflow")||He.includes("#skills/global/fluxflow"),Te;if(Ie)Te=`${T?"\u2714":"\u2718"} Searched Documentation`;else{let Ce=V?V.replace(/[\/\\]+$/,""):null,ze=Ce&&Ce!=="."?`"${ae?V:ce?`${Ce}/*`:Ce}"`:"./";Te=`${T?"\u2714":"\u2718"} Searched: "${T||""}" in ${ze.replaceAll("\\","/")} \u2192 ${be} Match${be===1?"":"es"}`}let q=115;process.stdout.isTTY&&(q=process.stdout.columns-5||120);let ne=Math.min(Te.length+4,q),le=`${Te.padEnd(ne-2).substring(0,ne-2)}`;yield{type:"visual_feedback",content:Vt(`${Be?`
795
+ `)},Be=!1}y==="exec_command"&&(await new Promise(gt=>setTimeout(gt,50)),n.onExecChunk&&n.onExecChunk(`ERROR: ${Le}`),await new Promise(gt=>setTimeout(gt,50)),n.onExecEnd&&n.onExecEnd()),Q.push({role:"user",text:`[TOOL RESULT]: DENIED: ${Le}`}),yield{type:"tool_result",content:`[TOOL RESULT]: DENIED: ${Le}`},await Et("toolDenied"),n.onToolResult&&n.onToolResult("denied",y),Ve++;continue}}if(z){let _=115;process.stdout.isTTY&&(_=process.stdout.columns-5||120);let V=await s(),ae=!1;V&&(ae=V.trim().length>0);let ce=Math.min(z.length+4,_),ke=`${z.padEnd(ce-2).substring(0,ce-2)}`;yield{type:"visual_feedback",content:Vt(`${Be?`
796
+ `:""}${ke}${z.includes("\u2714")&&(z.includes("Created")||z.includes("Edited"))?"":`${ae?"":`
797
+ `}`}`)},Be=!1}if(j>0){let _=Date.now()-j,V=Math.max(0,1e3-_);V>0&&await new Promise(ae=>setTimeout(ae,V))}let kn={chatId:g,history:t,onChunk:_=>n.onExecChunk?n.onExecChunk(_):null,onAskUser:n.onAskUser,systemSettings:n.systemSettings,mode:a,isMultiModal:dt(me),onVisualFeedback:n.onVisualFeedback,onSubagentUpdate:n.onSubagentUpdate,onTokenChunk:n.onTokenChunk,modelName:me,aiProvider:n.aiProvider,apiKey:n.apiKey,onUsage:n.onUsage};if(y==="write_file"||y==="update_file")try{let{path:_}=Z(W.args);if(_){let V=J.resolve(process.cwd(),_),ae=await Ln();ae&&ae.file_focused===V&&ae.full_content&&(kn.forcedContent=ae.full_content)}}catch{}qt.push(y);let Ae=await uo(y,W.args,kn);if((y==="write_file"||y==="update_file")&&Ae.startsWith("SUCCESS")){let{path:_}=Z(W.args);if(_){let V=J.resolve(process.cwd(),_);br(V)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let $t=Date.now();j=$t,yield{type:"tool_time",content:$t-ne},zt=$t;let Ut=null;if(typeof Ae=="object"&&Ae.binaryPart&&(Ut=Ae.binaryPart,Ae=Ae.text),y==="search_keyword"){let{keyword:_,path:V}=Z(W.args),ae=typeof Ae=="string"&&Ae.startsWith("[GLOB]");ae&&(Ae=Ae.slice(6).trimStart());let ce=typeof Ae=="string"&&Ae.startsWith("[DIR]");ce&&(Ae=Ae.slice(5).trimStart());let ke=0;if(Ae){let Ce=Ae.match(/Found (\d+) match/i);Ce&&(ke=parseInt(Ce[1]))}let He=(V||"").trim().toLowerCase().replaceAll("\\","/"),Ie=He==="#doc"||He==="#docs"||He==="#documentation"||He.includes("#skill/global/fluxflow")||He.includes("#skills/global/fluxflow"),Te;if(Ie)Te=`${_?"\u2714":"\u2718"} Searched Documentation`;else{let Ce=V?V.replace(/[\/\\]+$/,""):null,ze=Ce&&Ce!=="."?`"${ae?V:ce?`${Ce}/*`:Ce}"`:"./";Te=`${_?"\u2714":"\u2718"} Searched: "${_||""}" in ${ze.replaceAll("\\","/")} \u2192 ${ke} Match${ke===1?"":"es"}`}let q=115;process.stdout.isTTY&&(q=process.stdout.columns-5||120);let oe=Math.min(Te.length+4,q),le=`${Te.padEnd(oe-2).substring(0,oe-2)}`;yield{type:"visual_feedback",content:Vt(`${Be?`
797
798
  `:""}${le}
798
- `)},Be=!1}if(y==="EmergencyRollback"){let{method:T}=Q(W.args);if(T==="forceRevert"){let V=0;if(Ae){let ne=Ae.match(/Total\s*:\s*(\d+)/i);ne&&(V=parseInt(ne[1]))}let ce=Ae&&Ae.startsWith("ERROR:")?"\u2718 Emergency Rollback Failed":`\u2714 Emergency Rollback \u2192 ${V} file${V===1?"":"s"} processed`,be=115;process.stdout.isTTY&&(be=process.stdout.columns-5||120);let He=await s(),Ie=!1;He&&(Ie=He.trim().length>0);let Te=Math.min(ce.length+4,be),q=`${ce.padEnd(Te-2).substring(0,Te-2)}`;yield{type:"visual_feedback",content:Vt(`${Be?`
799
+ `)},Be=!1}if(y==="EmergencyRollback"){let{method:_}=Z(W.args);if(_==="forceRevert"){let V=0;if(Ae){let oe=Ae.match(/Total\s*:\s*(\d+)/i);oe&&(V=parseInt(oe[1]))}let ce=Ae&&Ae.startsWith("ERROR:")?"\u2718 Emergency Rollback Failed":`\u2714 Emergency Rollback \u2192 ${V} file${V===1?"":"s"} processed`,ke=115;process.stdout.isTTY&&(ke=process.stdout.columns-5||120);let He=await s(),Ie=!1;He&&(Ie=He.trim().length>0);let Te=Math.min(ce.length+4,ke),q=`${ce.padEnd(Te-2).substring(0,Te-2)}`;yield{type:"visual_feedback",content:Vt(`${Be?`
799
800
  `:""}${q}${Ie?"":`
800
- `}`)},Be=!1}}if(y==="todo"){let{method:T,tasks:V,markDone:ae}=Q(W.args),ce="",be=[],He=Ie=>{if(!Ie)return[];let Te=Array.isArray(Ie)?Ie:[];if(Te.length===0&&typeof Ie=="string"){let q=Ie.trim();if(q.startsWith("[")&&q.endsWith("]")){let ne=q.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);ne?Te=ne.map(le=>le.slice(1,-1).replace(/\\(.)/g,"$1")):Te=q.slice(1,-1).split(",").map(le=>le.trim()).filter(Boolean)}else Te=Ie.split(`
801
- `)}return Te.filter(q=>String(q).trim()).map(q=>{let ne=String(q).trim();return ne.startsWith("- [")?ne.substring(6).trim():ne})};if(T==="create"?(ce="\x1B[32m\u2192\x1B[0m Created Goals",be=He(V).map(Ie=>`\x1B[90m\u25CB\x1B[0m ${Ie}`)):T==="append"?(ce="\x1B[34m\u2795\x1B[0m Added New Goals",be=He(V).map(Ie=>`\x1B[90m\u25CB\x1B[0m ${Ie}`)):T==="get"&&(ce=ae?"\x1B[36m\u21BB\x1B[0m Updated Goals":"\x1B[35m\u2022\x1B[0m Reviewed Goals",be=(Ae||"").split(`
801
+ `}`)},Be=!1}}if(y==="todo"){let{method:_,tasks:V,markDone:ae}=Z(W.args),ce="",ke=[],He=Ie=>{if(!Ie)return[];let Te=Array.isArray(Ie)?Ie:[];if(Te.length===0&&typeof Ie=="string"){let q=Ie.trim();if(q.startsWith("[")&&q.endsWith("]")){let oe=q.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);oe?Te=oe.map(le=>le.slice(1,-1).replace(/\\(.)/g,"$1")):Te=q.slice(1,-1).split(",").map(le=>le.trim()).filter(Boolean)}else Te=Ie.split(`
802
+ `)}return Te.filter(q=>String(q).trim()).map(q=>{let oe=String(q).trim();return oe.startsWith("- [")?oe.substring(6).trim():oe})};if(_==="create"?(ce="\x1B[32m\u2192\x1B[0m Created Goals",ke=He(V).map(Ie=>`\x1B[90m\u25CB\x1B[0m ${Ie}`)):_==="append"?(ce="\x1B[34m\u2795\x1B[0m Added New Goals",ke=He(V).map(Ie=>`\x1B[90m\u25CB\x1B[0m ${Ie}`)):_==="get"&&(ce=ae?"\x1B[36m\u21BB\x1B[0m Updated Goals":"\x1B[35m\u2022\x1B[0m Reviewed Goals",ke=(Ae||"").split(`
802
803
  `).slice(1).join(`
803
804
  `).split(`
804
- `).filter(Te=>Te.trim().startsWith("- [")).map(Te=>{let q=Te.trim(),ne=q.startsWith("- [x]");return`${ne?"\x1B[32m\u2714\x1B[0m":"\x1B[90m\u25CB\x1B[0m"} ${ne?"\x1B[90m":"\x1B[37m"}${q.substring(6).trim()}\x1B[0m`})),ce&&be.length>0){let Ie=[`${ce}`,...be.map(ne=>` ${ne}`)].join(`
805
+ `).filter(Te=>Te.trim().startsWith("- [")).map(Te=>{let q=Te.trim(),oe=q.startsWith("- [x]");return`${oe?"\x1B[32m\u2714\x1B[0m":"\x1B[90m\u25CB\x1B[0m"} ${oe?"\x1B[90m":"\x1B[37m"}${q.substring(6).trim()}\x1B[0m`})),ce&&ke.length>0){let Ie=[`${ce}`,...ke.map(oe=>` ${oe}`)].join(`
805
806
  `),Te=await s(),q=!1;Te&&(q=Te.trim().length>0),yield{type:"visual_feedback",content:Vt(`${Be?`
806
807
  `:""}${Ie}${q?"":`
807
- `}`)},Be=!1}}y==="exec_command"&&n.onExecEnd&&(await new Promise(T=>setTimeout(T,800)),n.onExecEnd());let un=Ae&&Ae.startsWith("DENIED:");Ae&&!Ae.startsWith("ERROR:")&&!un?(await Et("toolSuccess"),n.onToolResult&&n.onToolResult("success",y)):un||(await Et("toolFailure"),n.onToolResult&&n.onToolResult("failure",y));let Nt=(Ae||"").toString().replaceAll("[UI_CONTEXT]","");Nt.includes("[[VERIFIED]]")&&(Nt=Nt.replace(/\[\[VERIFIED\]\][\s\S]*?\[\[\/VERIFIED\]\]/g,`[SYSTEM NOTE]: Patch Block matched & applied successfully. Large Block omitted to conserve context.
808
- `));let gn;if(Nt.startsWith("[[SAME]]")){let V=Nt.replace(/^\[\[SAME\]\]\s*\r?\n?/,"").split(/\r?\n/),ae=V.filter(be=>be.startsWith("SUCCESS:")||be.trim().startsWith("- Stats:"));gn=`[TOOL RESULT]: ${ae.length>0?ae.join(`
808
+ `}`)},Be=!1}}y==="exec_command"&&n.onExecEnd&&(await new Promise(_=>setTimeout(_,800)),n.onExecEnd());let un=Ae&&Ae.startsWith("DENIED:");Ae&&!Ae.startsWith("ERROR:")&&!un?(await Et("toolSuccess"),n.onToolResult&&n.onToolResult("success",y)):un||(await Et("toolFailure"),n.onToolResult&&n.onToolResult("failure",y));let Nt=(Ae||"").toString().replaceAll("[UI_CONTEXT]","");Nt.includes("[[VERIFIED]]")&&(Nt=Nt.replace(/\[\[VERIFIED\]\][\s\S]*?\[\[\/VERIFIED\]\]/g,`[SYSTEM NOTE]: Patch Block matched & applied successfully. Large Block omitted to conserve context.
809
+ `));let gn;if(Nt.startsWith("[[SAME]]")){let V=Nt.replace(/^\[\[SAME\]\]\s*\r?\n?/,"").split(/\r?\n/),ae=V.filter(ke=>ke.startsWith("SUCCESS:")||ke.trim().startsWith("- Stats:"));gn=`[TOOL RESULT]: ${ae.length>0?ae.join(`
809
810
  `):V.slice(0,2).join(`
810
811
  `)}
811
- [SYSTEM NOTE]: Content verified and persisted to disk. Full preview omitted to conserve context.`}else gn=`[TOOL RESULT]: ${Nt}`;X.push({role:"user",text:gn,binaryPart:Ut}),Xt=!0;let Me=`[TOOL RESULT]: ${Ae.replaceAll(`[[VERIFIED]]
812
+ [SYSTEM NOTE]: Content verified and persisted to disk. Full preview omitted to conserve context.`}else gn=`[TOOL RESULT]: ${Nt}`;Q.push({role:"user",text:gn,binaryPart:Ut}),Xt=!0;let Me=`[TOOL RESULT]: ${Ae.replaceAll(`[[VERIFIED]]
812
813
  `,"").replaceAll(`
813
- [[/VERIFIED]]`,"")||""}`;(y==="view_file"||y==="web_scrape"||y==="file_map")&&(Me=`[TOOL RESULT]: ${z} (Context Locked for UI Clarity)`),yield{type:"tool_result",content:Me,aiContent:gn,binaryPart:Ut,toolName:y},y==="memory"&&Ae.includes("SUCCESS")&&(yield{type:"memory_updated"}),Ve++}if(i==="Google"&&on&&Date.now()-as>=150){yield*Mn();let W=Jn(on);for(let te of W)yield te;on="",as=Date.now()}}L.usageMetadata&&(dn=L.usageMetadata),dn&&(yield{type:"liveTokens",content:dn.totalTokenCount})}if(ye&&(ye=!1,Dt?qe+="</think>":(ge+="</think>",i==="Google"?on+="</think>":yield{type:"text",content:"</think>"})),Dt&&qe.length>0){let L=0,oe=Math.min(st.length,qe.length);for(let H=oe;H>0;H--)if(st.endsWith(qe.substring(0,H))){L=H;break}let F=qe.substring(L);if(F){let we=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(st)?F.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):F.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(we)if(ge+=we,i==="Google")on+=we;else{yield*Mn();let xe=Jn(we);for(let he of xe)yield he}}Dt=!1,qe=""}if(yield*Mn(),kt)break;let Xn=(ge||"").trim(),Wr=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(Xn.toLowerCase())||/\[\[END\]\]/i.test(Xn.toLowerCase()),Hr=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(Xn.toLowerCase()),Gr=X.length>0||Mt!==null,ls=Kt(Xn).trim(),jr=/(\p{Emoji_Presentation}|\p{Extended_Pictographic})$/u.test(ls),Vr=/([.!?"'*_`|\]\)”’~~]+|\s|`{3}|[\u200B-\u200D\uFEFF])$/u.test(ls.trim()),Kr=/[.!?}"'`’“”]$|```$/s.test(ls)||Vr||jr;!Wr&&!Hr&&!Gr&&Xn.length>0,nt=!0,await Et("agent",i)}catch(_e){if(kt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
814
+ [[/VERIFIED]]`,"")||""}`;(y==="view_file"||y==="web_scrape"||y==="file_map")&&(Me=`[TOOL RESULT]: ${z} (Context Locked for UI Clarity)`),yield{type:"tool_result",content:Me,aiContent:gn,binaryPart:Ut,toolName:y},y==="memory"&&Ae.includes("SUCCESS")&&(yield{type:"memory_updated"}),Ve++}if(i==="Google"&&on&&Date.now()-as>=150){yield*Mn();let W=Jn(on);for(let ne of W)yield ne;on="",as=Date.now()}}L.usageMetadata&&(dn=L.usageMetadata),dn&&(yield{type:"liveTokens",content:dn.totalTokenCount})}if(xe&&(xe=!1,Dt?qe+="</think>":(ge+="</think>",i==="Google"?on+="</think>":yield{type:"text",content:"</think>"})),Dt&&qe.length>0){let L=0,se=Math.min(st.length,qe.length);for(let H=se;H>0;H--)if(st.endsWith(qe.substring(0,H))){L=H;break}let F=qe.substring(L);if(F){let we=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(st)?F.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):F.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(we)if(ge+=we,i==="Google")on+=we;else{yield*Mn();let be=Jn(we);for(let he of be)yield he}}Dt=!1,qe=""}if(yield*Mn(),kt)break;let Xn=(ge||"").trim(),Wr=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(Xn.toLowerCase())||/\[\[END\]\]/i.test(Xn.toLowerCase()),Hr=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(Xn.toLowerCase()),Gr=Q.length>0||Mt!==null,ls=Kt(Xn).trim(),jr=/(\p{Emoji_Presentation}|\p{Extended_Pictographic})$/u.test(ls),Vr=/([.!?"'*_`|\]\)”’~~]+|\s|`{3}|[\u200B-\u200D\uFEFF])$/u.test(ls.trim()),Kr=/[.!?}"'`’“”]$|```$/s.test(ls)||Vr||jr;!Wr&&!Hr&&!Gr&&Xn.length>0,nt=!0,await Et("agent",i)}catch(Ee){if(kt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
814
815
 
815
- \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(String(_e).includes("Incomplete JSON segment at the end")){ye&&(ye=!1,Dt?qe+="</think>":(ge+="</think>",yield{type:"text",content:"</think>"})),nt=!0,await Et("agent",i);break}if(ye&&(ye=!1,Dt?qe+="</think>":ge+="</think>"),Dt&&qe.length>0){let Lt=0,St=Math.min(st.length,qe.length);for(let Rt=St;Rt>0;Rt--)if(st.endsWith(qe.substring(0,Rt))){Lt=Rt;break}let yt=qe.substring(Lt);if(yt){let ut=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(st)?yt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):yt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");ut&&(ge+=ut)}Dt=!1,qe=""}let re=_e instanceof Error?(()=>{try{return JSON.parse(JSON.parse(_e.message).error.message).error.message}catch{return String(_e)}})():String(_e),Ot=new Date().toLocaleString(),Ct=J.join(wn,"agent");Pe.existsSync(Ct)||Pe.mkdirSync(Ct,{recursive:!0}),Pe.appendFileSync(J.join(Ct,"error.log"),`ERROR [${Ot}]: ${re}
816
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(String(Ee).includes("Incomplete JSON segment at the end")){xe&&(xe=!1,Dt?qe+="</think>":(ge+="</think>",yield{type:"text",content:"</think>"})),nt=!0,await Et("agent",i);break}if(xe&&(xe=!1,Dt?qe+="</think>":ge+="</think>"),Dt&&qe.length>0){let Lt=0,St=Math.min(st.length,qe.length);for(let Rt=St;Rt>0;Rt--)if(st.endsWith(qe.substring(0,Rt))){Lt=Rt;break}let yt=qe.substring(Lt);if(yt){let ut=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(st)?yt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):yt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");ut&&(ge+=ut)}Dt=!1,qe=""}let re=Ee instanceof Error?(()=>{try{return JSON.parse(JSON.parse(Ee.message).error.message).error.message}catch{return String(Ee)}})():String(Ee),Ot=new Date().toLocaleString(),Ct=J.join(wn,"agent");$e.existsSync(Ct)||$e.mkdirSync(Ct,{recursive:!0}),$e.appendFileSync(J.join(Ct,"error.log"),`ERROR [${Ot}]: ${re}
816
817
 
817
818
  ----------------------------------------------------------------------
818
819
 
819
- `);let Tt=_e.status||_e.statusCode||_e.code,Jt=String(_e).includes("replicas at capacity");if(!(Tt&&(Tt>=500&&Tt<600||Tt===408||Tt===429||Jt)||!Tt&&(/status[ :]+(5\d\d|408|429)/i.test(String(_e))||/code[ :]+(5\d\d|408|429)/i.test(String(_e))||/(500|503|408|429)/.test(String(_e))))){if(je<tn-3)throw _e;yield{type:"text",content:re},yield{type:"status",content:"Error Occured"}}if(ge.trim().length>0||Ze>1)if(Ze<=tn){Ze++;let Lt=Math.min(1e3*Math.pow(2,Ze-1),24e3);if(ge.trim().length>0){r.push({role:"agent",text:ge});let St=`[system]
820
+ `);let Tt=Ee.status||Ee.statusCode||Ee.code,Jt=String(Ee).includes("replicas at capacity");if(!(Tt&&(Tt>=500&&Tt<600||Tt===408||Tt===429||Jt)||!Tt&&(/status[ :]+(5\d\d|408|429)/i.test(String(Ee))||/code[ :]+(5\d\d|408|429)/i.test(String(Ee))||/(500|503|408|429)/.test(String(Ee))))){if(je<tn-3)throw Ee;yield{type:"text",content:re},yield{type:"status",content:"Error Occured"}}if(ge.trim().length>0||Ze>1)if(Ze<=tn){Ze++;let Lt=Math.min(1e3*Math.pow(2,Ze-1),24e3);if(ge.trim().length>0){r.push({role:"agent",text:ge});let St=`[system]
820
821
  - seamless continuation: resume immediately. pick up from last words with zero gap/disruption
821
822
  - no repetition: do not repeat any text already written
822
823
  - no re-think: do not restart or open <think> if reasoning already started. continue the thinking and close thinking block </think> before chat output
823
824
  - mid-tool safety: if cutoff was mid-tool call, restart that tool call from start
824
- - stealth: do not mention/apologize for cutoff [/system]`;X.length>0?X.forEach((yt,Rt)=>{Rt===X.length-1?r.push({...yt,text:`${yt.text}
825
+ - stealth: do not mention/apologize for cutoff [/system]`;Q.length>0?Q.forEach((yt,Rt)=>{Rt===Q.length-1?r.push({...yt,text:`${yt.text}
825
826
 
826
827
  ${St}`}):r.push(yt)}):r.push({role:"user",text:St}),st+=ge}for(let St=Lt/1e3;St>0&&!kt;St--)yield{type:"status",content:`Error Occured. Recovering Stream (${Ze}/${tn}) [Retrying in ${St.toFixed(0)}s]...`},await new Promise(yt=>setTimeout(yt,1e3));yield{type:"status",content:"Error Occured. Recovering Stream..."}}else throw new Error(`Stream collapsed too many times. (Failed to resolve ${tn} times)
827
828
  Error log can be found in \`/export logs\``);else if(je<=tn){je++,Ze=1,st="";let Lt=Math.min(1e3*Math.pow(2,je-1),32e3),St=.8+Math.random()*.4,yt=Math.round(Lt*St);An=!0,yield{type:"status",content:`Trying to reach ${e} (${je}/${tn}) [Retrying in ${(yt/1e3).toFixed(0)}s]`};for(let Rt=yt/1e3;Rt>0&&!kt;Rt--)yield{type:"status",content:`Trying to reach ${e} (${je}/${tn}) [Retrying in ${Rt.toFixed(0)}s]`},await new Promise(ut=>setTimeout(ut,1e3));yield{type:"status",content:`Trying to reach ${e}`}}else throw new Error(`Model ${e} cannot be reached. (Failed ${tn} times)
828
- Error log can be found in \`/export logs\``)}}if(dn){let ye=dn.totalTokenCount||0,_e=dn.cachedContentTokenCount||0,re=(dn.candidatesTokenCount||0)+(i==="Google"&&dn.thoughtsTokenCount||0);await Ft("tokens",ye,i,me),_e>0&&await Ft("cachedTokens",_e,i,me),re>0&&await Ft("candidateTokens",re,i,me),yield{type:"usage",content:dn}}ni.push(ge);let Rn=Kt(ge),Qt=Rr(ge),zn=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(Qt.toLowerCase())||/\[\[END\]\]/i.test(Qt.toLowerCase())||!0,bn=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(Qt.toLowerCase()),Ua=Ve>0;yield{type:"status",content:"Thinking"};let Nr=La(ge,/(\[\s*(turn\s*:)?\s*(continue|finish)\s*\]|\[\[END\]\])/gi,"").trim(),vn=(zn||X.length===0)&&!It&&!nn&&!fn;if(vn=X.length===0?vn:!1,vn=Cn||yo?!1:vn,ge&&ge.trim().endsWith('")]')&&X.length===0&&(vn=!1),vn){let ye=ni.join(`
829
- `),_e=Kt(ye).trim();yield{type:"interactive_turn_finished",data:{agentText:p,fullAgentTextRaw:ye,history:[...r],needTitle:$}},r.length>0&&r[r.length-1].role==="agent"?r[r.length-1].text=_e:r.push({role:"agent",text:_e}),r.forEach(re=>{if(re.role==="user"&&re.text&&(re.text=re.text.replace(/\n\[COMPILE ERROR\][\s\S]*?\[\/ERROR\]/g,""),re.text=re.text.replaceAll(`
829
+ Error log can be found in \`/export logs\``)}}if(dn){let xe=dn.totalTokenCount||0,Ee=dn.cachedContentTokenCount||0,re=(dn.candidatesTokenCount||0)+(i==="Google"&&dn.thoughtsTokenCount||0);await Ft("tokens",xe,i,me),Ee>0&&await Ft("cachedTokens",Ee,i,me),re>0&&await Ft("candidateTokens",re,i,me),yield{type:"usage",content:dn}}ni.push(ge);let Rn=Kt(ge),Qt=Rr(ge),zn=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(Qt.toLowerCase())||/\[\[END\]\]/i.test(Qt.toLowerCase())||!0,bn=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(Qt.toLowerCase()),Wa=Ve>0;yield{type:"status",content:"Thinking"};let Nr=Pa(ge,/(\[\s*(turn\s*:)?\s*(continue|finish)\s*\]|\[\[END\]\])/gi,"").trim(),vn=(zn||Q.length===0)&&!It&&!nn&&!fn;if(vn=Q.length===0?vn:!1,vn=Cn||xo?!1:vn,ge&&ge.trim().endsWith('")]')&&Q.length===0&&(vn=!1),vn){let xe=ni.join(`
830
+ `),Ee=Kt(xe).trim();yield{type:"interactive_turn_finished",data:{agentText:p,fullAgentTextRaw:xe,history:[...r],needTitle:$}},r.length>0&&r[r.length-1].role==="agent"?r[r.length-1].text=Ee:r.push({role:"agent",text:Ee}),r.forEach(re=>{if(re.role==="user"&&re.text&&(re.text=re.text.replace(/\n\[COMPILE ERROR\][\s\S]*?\[\/ERROR\]/g,""),re.text=re.text.replaceAll(`
830
831
 
831
832
  [system] user question. resolve this specific query within '[ANSWER] ... [/ANSWER]' concisely, naturally [/system]
832
833
  `,"").replaceAll(`[system] user question. resolve this specific query within '[ANSWER] ... [/ANSWER]' concisely, naturally
@@ -834,22 +835,22 @@ Error log can be found in \`/export logs\``)}}if(dn){let ye=dn.totalTokenCount||
834
835
  `,"").replaceAll(`[system] **strictly follow thinking policy as high priority. do not start a response without <think>...</think>** [/system]
835
836
  `,"").replaceAll(/\n\[system\] WARNING, Turn Limit Impending: Step \d+\/\d+\. Wrap up quickly\/prompt user to continue & use \[\[END\]\] quickly\. \[\/system\]/g,""),re.text=re.text.replaceAll(/\n\[system\] File Changes:\n(?:\* .+ \(created|modified|deleted\)\n)*\[\/system\]/g,""),(i==="Mistral"||i==="Google"&&e?.toLowerCase().startsWith("gemma"))&&re.text.startsWith("[TOOL RESULT]"))){let Ct=`
836
837
  [system] Tool result received. Analyze output and proceed with your turn [/system]`,Tt=`
837
- [system] Tool result received. Analyze output and proceed with your turn. **strictly follow thinking policy. do not start a response without <think>...</think>** [/system]`;re.text=re.text.replaceAll(Tt,"").replaceAll(Ct,"").trim()}}),yield{type:"status",content:"[end]"}}if(vn)break;let Fr=Nr.trim()||"*Working...*";if(r.push({role:"agent",text:Fr}),X.length>0||Xt){if(X.length>0){let ye=X.map(Jt=>Jt.text).join(`
838
+ [system] Tool result received. Analyze output and proceed with your turn. **strictly follow thinking policy. do not start a response without <think>...</think>** [/system]`;re.text=re.text.replaceAll(Tt,"").replaceAll(Ct,"").trim()}}),yield{type:"status",content:"[end]"}}if(vn)break;let Fr=Nr.trim()||"*Working...*";if(r.push({role:"agent",text:Fr}),Q.length>0||Xt){if(Q.length>0){let xe=Q.map(Jt=>Jt.text).join(`
838
839
 
839
- `),Ot=(Kt(ge).replace(/\[{1,2}tool:[\s\S]*?\)\s*\]{1,2}/gi,"").match(/\[tool:/gi)||[]).length,Ct=X.length+Ot;if(X.length<Ct){ye+=`
840
+ `),Ot=(Kt(ge).replace(/\[{1,2}tool:[\s\S]*?\)\s*\]{1,2}/gi,"").match(/\[tool:/gi)||[]).length,Ct=Q.length+Ot;if(Q.length<Ct){xe+=`
840
841
 
841
- [system] Only ${X.length} out of ${Ct} attempted tool calls were executed. Verify proper structure compliance & try failed calls again [/system]`;let Jt=Ct-X.length;for(let We=0;We<Jt;We++)await Et("toolFailure")}let Tt=X.find(Jt=>Jt.binaryPart)?.binaryPart||null;r.push({role:"user",text:ye,binaryPart:Tt})}}else if(!kt){let _e=(ge.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/i,"").match(/\[tool:/gi)||[]).length;yo||Cn||_e>0?(r.push({role:"user",text:`[system] Failed to execute ${_e} tool${_e>1?"s":""}. Verify proper structure compliance & try again [/system]`}),await Et("toolFailure"),yield{type:"visual_feedback",content:`
842
+ [system] Only ${Q.length} out of ${Ct} attempted tool calls were executed. Verify proper structure compliance & try failed calls again [/system]`;let Jt=Ct-Q.length;for(let We=0;We<Jt;We++)await Et("toolFailure")}let Tt=Q.find(Jt=>Jt.binaryPart)?.binaryPart||null;r.push({role:"user",text:xe,binaryPart:Tt})}}else if(!kt){let Ee=(ge.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/i,"").match(/\[tool:/gi)||[]).length;xo||Cn||Ee>0?(r.push({role:"user",text:`[system] Failed to execute ${Ee} tool${Ee>1?"s":""}. Verify proper structure compliance & try again [/system]`}),await Et("toolFailure"),yield{type:"visual_feedback",content:`
842
843
  ${Vt("\u2718 Execution Error")}
843
844
  `}):(yield{type:"visual_feedback",content:`
844
845
  ${Vt("\u2718 Loop Detected")}
845
- `},r.push({role:"user",text:`[system] ${nn&&!It?"Stuttering Detected by Internal System. Re-calibrate your response & proceed.":`${It?" Over Thinking":" Loop"} Detected by Internal System${It?" for current Effort Level":""}. ${It?"If you have planned the task, prioritize execution/output":"If you have finished your task provide a simple summary and end"}`} [/system]`})),It=!1,nn=!1,fn=!1}h?.advanceRollback&&await to.recordTurnDelta(g,K+1,qt),yo=Ve>0||Xt}}catch(w){let k=(w instanceof Error?(()=>{try{return JSON.parse(JSON.parse(w.message).error.message).error.message}catch{return w.message||String(w)}})():String(w)).replace(/^(Error:\s*)+/i,""),E=new Date().toLocaleString(),O=J.join(wn,"agent");yield{type:"text",content:`
846
+ `},r.push({role:"user",text:`[system] ${nn&&!It?"Stuttering Detected by Internal System. Re-calibrate your response & proceed.":`${It?" Over Thinking":" Loop"} Detected by Internal System${It?" for current Effort Level":""}. ${It?"If you have planned the task, prioritize execution/output":"If you have finished your task provide a simple summary and end"}`} [/system]`})),It=!1,nn=!1,fn=!1}m?.advanceRollback&&await to.recordTurnDelta(g,K+1,qt),xo=Ve>0||Xt}}catch(w){let k=(w instanceof Error?(()=>{try{return JSON.parse(JSON.parse(w.message).error.message).error.message}catch{return w.message||String(w)}})():String(w)).replace(/^(Error:\s*)+/i,""),E=new Date().toLocaleString(),O=J.join(wn,"agent");yield{type:"text",content:`
846
847
 
847
848
  \u2726 CRITICAL ERROR: ${k.includes("fetch failed")?"Failed to Connect. Check your Internet Connection or Wait a moment":k}
848
- \u2800`},Pe.existsSync(O)||Pe.mkdirSync(O,{recursive:!0}),Pe.appendFileSync(J.join(O,"error.log"),`CRITICAL ERROR [${E}]: ${w}
849
+ \u2800`},$e.existsSync(O)||$e.mkdirSync(O,{recursive:!0}),$e.appendFileSync(J.join(O,"error.log"),`CRITICAL ERROR [${E}]: ${w}
849
850
 
850
851
  ----------------------------------------------------------------------
851
852
 
852
- `),typeof flushGoogleBuffer=="function"&&(yield*flushGoogleBuffer()),yield{type:"tool_result",content:`ERROR: [INTERNAL CRITICAL] ${k}`}}finally{c&&(clearInterval(c),c=null),typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),await _o.commitTransaction(),h?.advanceRollback&&await to.cleanup(g),await Ln()}yield{type:"status",content:null}},Yd=async(e,t,n=null,s=null,o=50,d=null,f=!1)=>{let a=await eo(),m={...a,...t},g=process.env.SUBAGENT_MODEL?process.env.SUBAGENT_MODEL.trim():null,u=process.env.SUBAGENT_PROVIDER?process.env.SUBAGENT_PROVIDER.trim():null,h=new Date,b=`${h.getFullYear()}-${h.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(h.getDate()).padStart(2,"0")}, ${h.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}).replace(":","-")}`,l=(w=>{if(!w)return null;let r=w.toLowerCase();return r==="google"?"Google":r==="deepseek"?"DeepSeek":r==="openrouter"?"OpenRouter":r==="nvidia"?"NVIDIA":r==="mistral"?"Mistral":r==="ollama"?"Ollama":r==="inferx"?"InferX":r==="sensenova"?"SenseNova":r==="poolside"?"Poolside":r==="9router"||r==="9Router"?"9router":r==="aihubmix"||r==="aihub"?"AIHubMix":r==="explabs"||r==="experientiallabs"||r==="experimentallabs"?"ExpLabs":r==="tokenharbor"||r==="token harbor"||r==="token_harbor"||r==="thk"?"TokenHarbor":r==="apinex"||r==="apx"?"APInex":null})(u),_=m?.systemSettings?.CustomSubAgent?m?.systemSettings?.SubAgentModel:null,C=m?.systemSettings?.CustomSubAgent?m?.systemSettings?.SubAgentProvider:null,x=null;if(_==="ENV"?(x=g,g&&l&&(m.aiProvider=l)):_&&_!=="Default"?(x=_,C&&(m.aiProvider=C)):g&&l&&(m.aiProvider=l),m.aiProvider){let w=await us(m.aiProvider);w&&(m.apiKey=w)}let R=w=>{if(!w||typeof w!="string")return{allowed:!0};let r=[/rm\s+-[rf]{1,2}\s+[\/*.]/i,/rmdir\s+\/[sq]/i,/del\s+\/[fsq]/i,/\bformat\b\s+[a-z]:/i,/mkfs/i,/dd\s+if=/i,/\b(shutdown|reboot|poweroff|init\s+0|init\s+6)\b/i,/chmod\s+(-R\s+)?777\s+[\/*.]/i,/chown\s+(-R\s+)?root/i,/git\s+push\s+.*--force/i,/git\s+clean\s+-fdx/i,/\bsudo\s+su\b/i,/\bsu\s+-\b/i];for(let k of r)if(k.test(w))return{allowed:!1,reason:`Blocked potentially destructive or unsafe command pattern: "${k.source}"`};return{allowed:!0}},N=n||x||t?.modelName||t?.activeModel||a.activeModel,D=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",S=`-- TOOL DEFINITIONS (path = relative to CWD, path separator: '/') --
853
+ `),typeof flushGoogleBuffer=="function"&&(yield*flushGoogleBuffer()),yield{type:"tool_result",content:`ERROR: [INTERNAL CRITICAL] ${k}`}}finally{c&&(clearInterval(c),c=null),typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),await Eo.commitTransaction(),m?.advanceRollback&&await to.cleanup(g),await Ln()}yield{type:"status",content:null}},Jd=async(e,t,n=null,s=null,o=50,d=null,f=!1)=>{let a=await eo(),h={...a,...t},g=process.env.SUBAGENT_MODEL?process.env.SUBAGENT_MODEL.trim():null,u=process.env.SUBAGENT_PROVIDER?process.env.SUBAGENT_PROVIDER.trim():null,m=new Date,x=`${m.getFullYear()}-${m.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(m.getDate()).padStart(2,"0")}, ${m.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}).replace(":","-")}`,l=(w=>{if(!w)return null;let r=w.toLowerCase();return r==="google"?"Google":r==="deepseek"?"DeepSeek":r==="openrouter"?"OpenRouter":r==="nvidia"?"NVIDIA":r==="mistral"?"Mistral":r==="ollama"?"Ollama":r==="inferx"?"InferX":r==="sensenova"?"SenseNova":r==="poolside"?"Poolside":r==="9router"||r==="9Router"?"9router":r==="aihubmix"||r==="aihub"?"AIHubMix":r==="explabs"||r==="experientiallabs"||r==="experimentallabs"?"ExpLabs":r==="tokenharbor"||r==="token harbor"||r==="token_harbor"||r==="thk"?"TokenHarbor":r==="apinex"||r==="apx"?"APInex":null})(u),T=h?.systemSettings?.CustomSubAgent?h?.systemSettings?.SubAgentModel:null,R=h?.systemSettings?.CustomSubAgent?h?.systemSettings?.SubAgentProvider:null,b=null;if(T==="ENV"?(b=g,g&&l&&(h.aiProvider=l)):T&&T!=="Default"?(b=T,R&&(h.aiProvider=R)):g&&l&&(h.aiProvider=l),h.aiProvider){let w=await us(h.aiProvider);w&&(h.apiKey=w)}let v=w=>{if(!w||typeof w!="string")return{allowed:!0};let r=[/rm\s+-[rf]{1,2}\s+[\/*.]/i,/rmdir\s+\/[sq]/i,/del\s+\/[fsq]/i,/\bformat\b\s+[a-z]:/i,/mkfs/i,/dd\s+if=/i,/\b(shutdown|reboot|poweroff|init\s+0|init\s+6)\b/i,/chmod\s+(-R\s+)?777\s+[\/*.]/i,/chown\s+(-R\s+)?root/i,/git\s+push\s+.*--force/i,/git\s+clean\s+-fdx/i,/\bsudo\s+su\b/i,/\bsu\s+-\b/i];for(let k of r)if(k.test(w))return{allowed:!1,reason:`Blocked potentially destructive or unsafe command pattern: "${k.source}"`};return{allowed:!0}},N=n||b||t?.modelName||t?.activeModel||a.activeModel,M=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",S=`-- TOOL DEFINITIONS (path = relative to CWD, path separator: '/') --
853
854
  You cant execute tools. Instead, output in chat the exact string [tool:functions.ToolName(arg1="value1")] & wait for system response \u2190 no exception, tool:functions must
854
855
  Tool Rules:
855
856
  - Mandatorily JSON escape literal sequences (backslash: \\\\, newLine: \\ n, quote: \\")
@@ -875,7 +876,7 @@ ${f?"- AskMain(question=string). Communicate with PARENT/MAIN AGENT. When clarif
875
876
  - ReadFile(path=string, startLine?=int, endLine?=int)
876
877
  - 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
877
878
  - WriteFile(path=string, content=string). Creates/Overwrites. File Exist? PatchFile > WriteFile
878
- - Run(command=string). Runs ${D==="Windows"?ci()?"powershell":"windows CMD":"bash"} command. Destructive command \u2192 Ask user`.trim(),M=`=== START SYSTEM PROMPT ===
879
+ - Run(command=string). Runs ${M==="Windows"?ci()?"powershell":"windows CMD":"bash"} command. Destructive command \u2192 Ask user`.trim(),I=`=== START SYSTEM PROMPT ===
879
880
  Identity: FluxFlow subagent helping the main Agent
880
881
  Your task is: "${e}"
881
882
 
@@ -888,31 +889,31 @@ CWD: ${process.cwd()}
888
889
 
889
890
  ${S.trimEnd()}
890
891
 
891
- Current Time: ${b}
892
- === END SYSTEM PROMPT ===`,$=[{role:"user",text:`Complete this task: ${e}`}],p=0,c="";for(;p<o;){if(kt){if(t?.taskId&&typeof jt<"u"){let B=jt.find(A=>A.id===t.taskId);B&&(B.status="cancelled")}throw d&&d("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}if(t?.taskId&&typeof jt<"u"){let B=jt.find(A=>A.id===t.taskId);if(B&&B.status==="cancelled")throw d&&d("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}let w=$.map(B=>({role:B.role==="user"?"user":"model",parts:[{text:B.text}]}));d&&d(`[Subagent Turn ${p+1}]...`);let k=(await es(m,N,w,M,"Fast")).text||"",E=Kt(k).trim();c=E,d&&d(`[Subagent Response]
892
+ Current Time: ${x}
893
+ === END SYSTEM PROMPT ===`,$=[{role:"user",text:`Complete this task: ${e}`}],p=0,c="";for(;p<o;){if(kt){if(t?.taskId&&typeof jt<"u"){let B=jt.find(A=>A.id===t.taskId);B&&(B.status="cancelled")}throw d&&d("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}if(t?.taskId&&typeof jt<"u"){let B=jt.find(A=>A.id===t.taskId);if(B&&B.status==="cancelled")throw d&&d("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}let w=$.map(B=>({role:B.role==="user"?"user":"model",parts:[{text:B.text}]}));d&&d(`[Subagent Turn ${p+1}]...`);let k=(await es(h,N,w,I,"Fast")).text||"",E=Kt(k).trim();c=E,d&&d(`[Subagent Response]
893
894
  ${E}
894
- `),$.push({role:"agent",text:E});let O=ts(E);if(O.length===0)break;let U=O.filter(B=>B.toolName.toLowerCase()==="askmain"||B.toolName.toLowerCase()==="ask_main"),P=!1,I="";for(let B of O){if(kt){if(t?.taskId&&typeof jt<"u"){let v=jt.find(G=>G.id===t.taskId);v&&(v.status="cancelled")}throw new Error("Subagent task was cancelled.")}if(t?.taskId&&typeof jt<"u"){let v=jt.find(G=>G.id===t.taskId);if(v&&v.status==="cancelled")throw new Error("Subagent task was cancelled.")}let A=B.toolName.toLowerCase();if(A==="askuser"&&(A="ask"),A==="askmain"||A==="ask_main"){if(P)continue;P=!0;let v="";if(U.length===1?v=Q(U[0].args).question||U[0].args:v=U.map((G,ee)=>{let Y=Q(G.args);return`Q${ee+1}: ${Y.question||G.args}`}).join(`
895
- `),t.onAskMain){d&&d(`[Executing Tool] AskMain("${v}")...`);let G=await t.onAskMain(v);d&&d(`[Tool Result]
895
+ `),$.push({role:"agent",text:E});let O=ts(E);if(O.length===0)break;let U=O.filter(B=>B.toolName.toLowerCase()==="askmain"||B.toolName.toLowerCase()==="ask_main"),P=!1,D="";for(let B of O){if(kt){if(t?.taskId&&typeof jt<"u"){let C=jt.find(G=>G.id===t.taskId);C&&(C.status="cancelled")}throw new Error("Subagent task was cancelled.")}if(t?.taskId&&typeof jt<"u"){let C=jt.find(G=>G.id===t.taskId);if(C&&C.status==="cancelled")throw new Error("Subagent task was cancelled.")}let A=B.toolName.toLowerCase();if(A==="askuser"&&(A="ask"),A==="askmain"||A==="ask_main"){if(P)continue;P=!0;let C="";if(U.length===1?C=Z(U[0].args).question||U[0].args:C=U.map((G,te)=>{let Y=Z(G.args);return`Q${te+1}: ${Y.question||G.args}`}).join(`
896
+ `),t.onAskMain){d&&d(`[Executing Tool] AskMain("${C}")...`);let G=await t.onAskMain(C);d&&d(`[Tool Result]
896
897
  Answer from Main Agent: ${G}
897
- `),I+=`[TOOL RESULT for AskMain]: Answer from Main Agent: ${G}
898
+ `),D+=`[TOOL RESULT for AskMain]: Answer from Main Agent: ${G}
898
899
 
899
- `,await Et("toolSuccess")}else I+=`[TOOL RESULT for AskMain]: ERROR: Main agent communication channel not available.
900
+ `,await Et("toolSuccess")}else D+=`[TOOL RESULT for AskMain]: ERROR: Main agent communication channel not available.
900
901
 
901
- `;continue}if(!(s?s.some(v=>v.toLowerCase()===A):!0)){let v=`ERROR: Tool [${B.toolName}] is not in the allowed tools list for this subagent.`;d&&d(`[Blocked Tool Call] ${B.toolName} - not allowed
902
- `),I+=`${v}
902
+ `;continue}if(!(s?s.some(C=>C.toLowerCase()===A):!0)){let C=`ERROR: Tool [${B.toolName}] is not in the allowed tools list for this subagent.`;d&&d(`[Blocked Tool Call] ${B.toolName} - not allowed
903
+ `),D+=`${C}
903
904
 
904
- `;continue}if(A==="exec_command"||A==="execcommand"||A==="run"){let v=Q(B.args).command||"",G=R(v);if(!G.allowed){let ee=`ERROR: [SECURITY RESTRICTION] Subagent execution blocked command: ${G.reason}`;d&&d(`[Blocked Command] ${v} - ${G.reason}
905
- `),I+=`${ee}
905
+ `;continue}if(A==="exec_command"||A==="execcommand"||A==="run"){let C=Z(B.args).command||"",G=v(C);if(!G.allowed){let te=`ERROR: [SECURITY RESTRICTION] Subagent execution blocked command: ${G.reason}`;d&&d(`[Blocked Command] ${C} - ${G.reason}
906
+ `),D+=`${te}
906
907
 
907
- `;continue}}let se="";if(A==="web_search"||A==="websearch")se=`\u2714 \x1B[95mSearched\x1B[0m: ${Q(B.args).query||""}`;else if(A==="web_scrape"||A==="webscrape")se=`\u2714 \x1B[95mScraped\x1B[0m: ${Q(B.args).url||""}`;else if(A==="search_keyword"||A==="searchkeyword"||A==="codesearch"||A==="code_search"){let v=Q(B.args),G=v.keyword||"",ee=v.path||"";se=`${G?"\u2714":"\u2718"} \x1B[95mSearched\x1B[0m: ${G||"No Query"}${ee?` \u2192 ${ee.replaceAll("\\","/")}`:""}`}else if(A==="view_file"||A==="viewfile"||A==="readfile")se=`\u2714 \x1B[95mRead\x1B[0m: ${(Q(B.args).path||"").replaceAll("\\","/")}`;else if(A==="list_files"||A==="read_folder"||A==="readfolder"){let v=Q(B.args).path||null,G=Q(B.args).recurse||0;se=`${v?"\u2714":"\u2718"} \x1B[95mBrowsed\x1B[0m: ${v?`${v.replaceAll("\\","/")}${G>0?`${v.endsWith("/")?`*${G}`:`/*${G}`}`:`${v.endsWith("/")?"":"/"}`}`:""}`}else if(A==="write_file"||A==="writefile"){let v=Q(B.args).path||null;se=`${v?"\u2714":"\u2718"} \x1B[95mCreated\x1B[0m: ${v?`${v.replaceAll("\\","/")}`:"No File Changes"}`}else if(A==="update_file"||A==="updatefile"||A==="patchfile"||A==="patch_file"||A==="patchfile"||A==="updatefile"){let v=Q(B.args).path||null,G=Q(B.args).content||null;se=`${v?"\u2714":"\u2718"} \x1B[95mEdited\x1B[0m: ${v?`${v.replaceAll("\\","/")}`:"No File Changes"}`}else if(A==="exec_command"||A==="execcommand"||A==="run"){let v=Q(B.args).command||null;se=`${v?"\u2714":"\u2718"} \x1B[95mExecuted\x1B[0m: ${v?v.slice(0,100)+(v.length>100?"...":""):"No Command"}`}else if(A==="file_map"||A==="filemap"){let v=Q(B.args).path||"";se=`${v?"\u2714":"\u2718"} \x1B[95mIndexed\x1B[0m: ${v?`${v.replaceAll("\\","/")}`:"File Not Found"}`}else if(A==="await"){let{time:v}=Q(B.args),G=parseFloat(v)||0;G<10&&(G=10),G>180&&(G=180),se=`\u2714 \x1B[95mAwaiting\x1B[0m \u2192 ${(Y=>{if(Y>=60){let Xe=Math.floor(Y/60),Ye=Y%60;return`${Xe}m${Ye>0?` ${Ye}s`:""}`}return`${Y}s`})(G)}`}else{let v=Gs[A]||B.toolName,G=Nn(A,B.args);se=`\u2714 \x1B[95m${v}\x1B[0m${G?`: ${G}`:""}`}t.onVisualFeedback&&se&&t.onVisualFeedback(se),d&&d(`[Executing Tool] ${B.toolName}(${B.args})...`);try{let v=await co(B.toolName,B.args,{...t,mode:"Flux"});if(d&&d(`[Tool Result]
908
- ${v}
909
- `),I+=`[TOOL RESULT for ${B.toolName}]: ${v}
908
+ `;continue}}let X="";if(A==="web_search"||A==="websearch")X=`\u2714 \x1B[95mSearched\x1B[0m: ${Z(B.args).query||""}`;else if(A==="web_scrape"||A==="webscrape")X=`\u2714 \x1B[95mScraped\x1B[0m: ${Z(B.args).url||""}`;else if(A==="search_keyword"||A==="searchkeyword"||A==="codesearch"||A==="code_search"){let C=Z(B.args),G=C.keyword||"",te=C.path||"";X=`${G?"\u2714":"\u2718"} \x1B[95mSearched\x1B[0m: ${G||"No Query"}${te?` \u2192 ${te.replaceAll("\\","/")}`:""}`}else if(A==="view_file"||A==="viewfile"||A==="readfile")X=`\u2714 \x1B[95mRead\x1B[0m: ${(Z(B.args).path||"").replaceAll("\\","/")}`;else if(A==="list_files"||A==="read_folder"||A==="readfolder"){let C=Z(B.args).path||null,G=Z(B.args).recurse||0;X=`${C?"\u2714":"\u2718"} \x1B[95mBrowsed\x1B[0m: ${C?`${C.replaceAll("\\","/")}${G>0?`${C.endsWith("/")?`*${G}`:`/*${G}`}`:`${C.endsWith("/")?"":"/"}`}`:""}`}else if(A==="write_file"||A==="writefile"){let C=Z(B.args).path||null;X=`${C?"\u2714":"\u2718"} \x1B[95mCreated\x1B[0m: ${C?`${C.replaceAll("\\","/")}`:"No File Changes"}`}else if(A==="update_file"||A==="updatefile"||A==="patchfile"||A==="patch_file"||A==="patchfile"||A==="updatefile"){let C=Z(B.args).path||null,G=Z(B.args).content||null;X=`${C?"\u2714":"\u2718"} \x1B[95mEdited\x1B[0m: ${C?`${C.replaceAll("\\","/")}`:"No File Changes"}`}else if(A==="exec_command"||A==="execcommand"||A==="run"){let C=Z(B.args).command||null;X=`${C?"\u2714":"\u2718"} \x1B[95mExecuted\x1B[0m: ${C?C.slice(0,100)+(C.length>100?"...":""):"No Command"}`}else if(A==="file_map"||A==="filemap"){let C=Z(B.args).path||"";X=`${C?"\u2714":"\u2718"} \x1B[95mIndexed\x1B[0m: ${C?`${C.replaceAll("\\","/")}`:"File Not Found"}`}else if(A==="await"){let{time:C}=Z(B.args),G=parseFloat(C)||0;G<10&&(G=10),G>180&&(G=180),X=`\u2714 \x1B[95mAwaiting\x1B[0m \u2192 ${(Y=>{if(Y>=60){let Xe=Math.floor(Y/60),Ye=Y%60;return`${Xe}m${Ye>0?` ${Ye}s`:""}`}return`${Y}s`})(G)}`}else{let C=Gs[A]||B.toolName,G=Nn(A,B.args);X=`\u2714 \x1B[95m${C}\x1B[0m${G?`: ${G}`:""}`}t.onVisualFeedback&&X&&t.onVisualFeedback(X),d&&d(`[Executing Tool] ${B.toolName}(${B.args})...`);try{let C=await uo(B.toolName,B.args,{...t,mode:"Flux"});if(d&&d(`[Tool Result]
909
+ ${C}
910
+ `),D+=`[TOOL RESULT for ${B.toolName}]: ${C}
910
911
 
911
- `,await Et("toolSuccess"),A==="patchfile"||A==="update_file"||A==="updatefile"||A==="patch_file"){if(v){let G=v.split(`
912
- `),ee=0,Y=0,Xe=!1;for(let Ye of G){if(Ye.includes("[DIFF_START]")){Xe=!0;continue}if(Ye.includes("[DIFF_END]")){Xe=!1;continue}Xe&&(/^\+\d+/.test(Ye)?ee++:/^\-\d+/.test(Ye)&&Y++)}(ee>0||Y>0)&&(await Ft("linesAdded",ee),await Ft("linesRemoved",Y))}}else if((A==="writefile"||A==="write_file")&&v){let G=v.match(/- Stats: \[(\d+) lines/),ee=G?parseInt(G[1]):0,Y=0;if(v.includes("Old File contents:")){let Xe=!1;for(let Ye of v.split(`
913
- `)){if(Ye.includes("Old File contents:")){Xe=!0;continue}Xe&&(Ye.trim()===""?Xe=!1:/^\d+ \|/.test(Ye)&&Y++)}}(ee>0||Y>0)&&(await Ft("linesAdded",ee),await Ft("linesRemoved",Y))}}catch(v){let G=`ERROR: Execution failed for [${B.toolName}]: ${v.message}`;d&&d(`[Tool Error] ${G}
914
- `),I+=`${G}
912
+ `,await Et("toolSuccess"),A==="patchfile"||A==="update_file"||A==="updatefile"||A==="patch_file"){if(C){let G=C.split(`
913
+ `),te=0,Y=0,Xe=!1;for(let Ye of G){if(Ye.includes("[DIFF_START]")){Xe=!0;continue}if(Ye.includes("[DIFF_END]")){Xe=!1;continue}Xe&&(/^\+\d+/.test(Ye)?te++:/^\-\d+/.test(Ye)&&Y++)}(te>0||Y>0)&&(await Ft("linesAdded",te),await Ft("linesRemoved",Y))}}else if((A==="writefile"||A==="write_file")&&C){let G=C.match(/- Stats: \[(\d+) lines/),te=G?parseInt(G[1]):0,Y=0;if(C.includes("Old File contents:")){let Xe=!1;for(let Ye of C.split(`
914
+ `)){if(Ye.includes("Old File contents:")){Xe=!0;continue}Xe&&(Ye.trim()===""?Xe=!1:/^\d+ \|/.test(Ye)&&Y++)}}(te>0||Y>0)&&(await Ft("linesAdded",te),await Ft("linesRemoved",Y))}}catch(C){let G=`ERROR: Execution failed for [${B.toolName}]: ${C.message}`;d&&d(`[Tool Error] ${G}
915
+ `),D+=`${G}
915
916
 
916
- `,await Et("toolFailure")}}let Z="";if(t?.taskId&&typeof jt<"u"){let B=jt.find(A=>A.id===t.taskId);if(B&&B.pendingSteerMessages&&B.pendingSteerMessages.length>0){let A=[...B.pendingSteerMessages];B.pendingSteerMessages=[];for(let Ee of A)Z+=`
917
+ `,await Et("toolFailure")}}let ee="";if(t?.taskId&&typeof jt<"u"){let B=jt.find(A=>A.id===t.taskId);if(B&&B.pendingSteerMessages&&B.pendingSteerMessages.length>0){let A=[...B.pendingSteerMessages];B.pendingSteerMessages=[];for(let Se of A)ee+=`
917
918
 
918
- [STEERING INSTRUCTION FROM MAIN AGENT]: ${Ee}`,d&&d(`[Subagent Steered] ${Ee}`)}}let ke=(I.trim()+Z).trim();$.push({role:"user",text:ke}),p++}return c};export{fo as a,hr as b,jl as c,Vl as d,Ll as e,Pl as f,$e as g,zl as h,Jl as i,Zl as j,Wo as k,ec as l,Ea as m,Bd as n,Aa as o,Ca as p,Hs as q,Kt as r,Cr as s,Ia as t,Ud as u,Wd as v,Vs as w,Hd as x,Gd as y,jd as z,Vd as A,Kd as B,Yd as C};
919
+ [STEERING INSTRUCTION FROM MAIN AGENT]: ${Se}`,d&&d(`[Subagent Steered] ${Se}`)}}let pe=(D.trim()+ee).trim();$.push({role:"user",text:pe}),p++}return c};export{go as a,pr as b,Xl as c,Ql as d,Oe as e,Ya as f,qa as g,Wl as h,Hl as i,tc as j,Wo as k,nc as l,Aa as m,Hd as n,Ca as o,Ra as p,Hs as q,Kt as r,Cr as s,Da as t,Gd as u,jd as v,Vs as w,Vd as x,Kd as y,Yd as z,qd as A,zd as B,Jd as C};