fluxflow-cli 4.21.3 → 4.21.4

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 Kt}from"./chunk-56EJGQU3.js";import{a as io}from"./chunk-ORXN6WUW.js";import{a as wi,c as Ti}from"./chunk-WFHGURXW.js";import{a as _s,g as Si}from"./chunk-NPYHHQDC.js";import{a as _i}from"./chunk-4XZGWK5L.js";import{c as Ts,g as xi,h as bi,i as ki,m as Ss}from"./chunk-UDJ2C3N3.js";import{a as Io}from"./chunk-YUJMCXJA.js";import{a as oe}from"./chunk-Y5JU726N.js";import{b as ks}from"./chunk-Y6DZDEJ5.js";import{d as Mo,i as vt,k as Ut,m as ws,n as yi}from"./chunk-RN5BZJYO.js";import{a as so}from"./chunk-I4JQEUHE.js";import{k as gt,l as Ro,o as ge}from"./chunk-QGPOMXO4.js";import{c as Ct,d as Jn}from"./chunk-SIINYZWE.js";import{a as nn,d as vn,e as Eo,k as Bn,l as Co,m as xs,r as bs,v as vo}from"./chunk-RI37VZYB.js";import{GoogleGenAI as Gr,ThinkingLevel as Ze,HarmBlockThreshold as In,HarmCategory as Dn}from"@google/genai";var Ai=(e=!0,t=!0)=>`
1
+ import{a as Yt}from"./chunk-56EJGQU3.js";import{a as ro}from"./chunk-ORXN6WUW.js";import{a as _i,c as Ai}from"./chunk-LI4AVCBN.js";import{a as As,g as Ei}from"./chunk-NPYHHQDC.js";import{a as Ci}from"./chunk-4XZGWK5L.js";import{c as Ss,g as wi,h as Ti,i as Si,m as _s}from"./chunk-UDJ2C3N3.js";import{a as Do}from"./chunk-YUJMCXJA.js";import{a as ie}from"./chunk-Y5JU726N.js";import{b as ws}from"./chunk-Y6DZDEJ5.js";import{d as Io,i as vt,k as Wt,m as Ts,n as ki}from"./chunk-RN5BZJYO.js";import{a as io}from"./chunk-I4JQEUHE.js";import{k as ut,l as Mo,o as pe}from"./chunk-QGPOMXO4.js";import{c as Ct,d as Jn}from"./chunk-SIINYZWE.js";import{a as on,d as Rn,e as Co,k as Un,l as vo,m as bs,r as ks,v as Ro}from"./chunk-RI37VZYB.js";import{GoogleGenAI as Kr,ThinkingLevel as Qe,HarmBlockThreshold as Dn,HarmCategory as On}from"@google/genai";var vi=(e=!0,t=!0)=>`
2
2
  To use tools, must output exactly '[tool: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 Do={xHigh:`Effort: High
29
+ - Must not ignore any tool calls in given context of chat between user & agent`:""}`.trim();var Oo={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 ro from"fs";var xn=null,As=()=>{try{if(ro.existsSync(vo)){let e=ro.readFileSync(vo,"utf-8"),t=JSON.parse(e);if(t&&typeof t=="object")return xn=t,xn}}catch{}return xn=xn||{},xn},Ei=e=>{try{return ro.existsSync(nn)||ro.mkdirSync(nn,{recursive:!0}),ro.writeFileSync(vo,JSON.stringify(e,null,2),"utf-8"),xn=e,!0}catch{return!1}},Ve=(e,t,n)=>{if(!e||!t||!n)return null;let s=xn||As(),o=`${e}::${t}`,l=s[o];if(l&&typeof l=="object"){let f=n.toLowerCase();if(l[f]!==void 0&&l[f]!==null)return l[f];for(let[a,h]of Object.entries(l))if(a.toLowerCase()===f)return h}return null},cl=(e,t,n,s)=>{if(!e||!t||!n||!s)return{success:!1,reason:"Invalid arguments"};let o=xn||As(),l=`${e}::${t}`;return(!o[l]||typeof o[l]!="object")&&(o[l]={}),o[l][n.toLowerCase()]=s,{success:Ei(o)}},dl=(e,t,n)=>{if(!e||!t)return{success:!1,reason:"Invalid arguments"};let s=xn||As(),o=`${e}::${t}`;return s[o]&&(n?(delete s[o][n.toLowerCase()],Object.keys(s[o]).length===0&&delete s[o]):delete s[o],Ei(s)),{success:!0}};import on from"fs";import fn from"path";import ua from"os";import dn from"fs";import Rn from"path";import Bi from"fs";import Es from"path";import{execSync as Ui}from"child_process";import{fileURLToPath as fa}from"url";var Ci=`# FluxFlow CLI Startup & Flags Reference
49
+ Verify imports, tool results & system stability`};import ao from"fs";var xn=null,Es=()=>{try{if(ao.existsSync(Ro)){let e=ao.readFileSync(Ro,"utf-8"),t=JSON.parse(e);if(t&&typeof t=="object")return xn=t,xn}}catch{}return xn=xn||{},xn},Ri=e=>{try{return ao.existsSync(on)||ao.mkdirSync(on,{recursive:!0}),ao.writeFileSync(Ro,JSON.stringify(e,null,2),"utf-8"),xn=e,!0}catch{return!1}},Ve=(e,t,n)=>{if(!e||!t||!n)return null;let s=xn||Es(),o=`${e}::${t}`,l=s[o];if(l&&typeof l=="object"){let f=n.toLowerCase();if(l[f]!==void 0&&l[f]!==null)return l[f];for(let[a,m]of Object.entries(l))if(a.toLowerCase()===f)return m}return null},ul=(e,t,n,s)=>{if(!e||!t||!n||!s)return{success:!1,reason:"Invalid arguments"};let o=xn||Es(),l=`${e}::${t}`;return(!o[l]||typeof o[l]!="object")&&(o[l]={}),o[l][n.toLowerCase()]=s,{success:Ri(o)}},gl=(e,t,n)=>{if(!e||!t)return{success:!1,reason:"Invalid arguments"};let s=xn||Es(),o=`${e}::${t}`;return s[o]&&(n?(delete s[o][n.toLowerCase()],Object.keys(s[o]).length===0&&delete s[o]):delete s[o],Ri(s)),{success:!0}};import sn from"fs";import fn from"path";import ma from"os";import dn from"fs";import Mn from"path";import Hi from"fs";import Cs from"path";import{execSync as Gi}from"child_process";import{fileURLToPath as ha}from"url";var Mi=`# FluxFlow CLI Startup & Flags Reference
50
50
 
51
51
  Launch command syntax:
52
52
  fluxflow [options]
@@ -75,7 +75,7 @@ fluxflow [options]
75
75
  * --help commands \u2192 In-chat slash commands list
76
76
  * --playground \u2192 Launch Playground mode
77
77
  * --prompt, -p \u2192 Non interactive CLI chat, no tools. --new for new headless chat. Holds conversation context upto 10m inactivity or 69 turns. Supports piping from shell, --run if want the command to visible in context. eg \`fluxflow --run "git diff" -p "summarize this" --new\`
78
- `;var vi=`# Env Variables
78
+ `;var Ii=`# Env Variables
79
79
 
80
80
  * Locations:
81
81
  * Shell
@@ -104,7 +104,7 @@ fluxflow [options]
104
104
 
105
105
  * 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
106
106
  * GOOGLE_GEMMA_NONSENSE \u2192 (true|false, default: false) for the 16k TPM nonsense of gemma models on gemini API. False defaults to 256k
107
- `;var Ri=`# Fluxflow in-app /commands
107
+ `;var Di=`# Fluxflow in-app /commands
108
108
 
109
109
  Trigger in chat via /command
110
110
 
@@ -147,7 +147,7 @@ Trigger in chat via /command
147
147
  * /changelog \u2192 Release notes
148
148
  * /update check \u2192 Check npm updates
149
149
  * /update latest \u2192 Install latest release
150
- `;var Mi=`# FluxFlow In-App Settings Reference
150
+ `;var Oi=`# FluxFlow In-App Settings Reference
151
151
 
152
152
  Open in chat via /settings
153
153
 
@@ -208,7 +208,7 @@ Open in chat via /settings
208
208
  - Best for Luxurious Experience: Subagents (on), dynamic directory awareness (on), compact large results (off), auto exclue metadata (off), Image History (Extended), Keep reasoning content (on), Emergency Recovery (on), Auto truncate results (off), Memory (on), Security Preset (Autonomous), FluxFlow IDE Companion
209
209
 
210
210
  - Max Cache Hit: Subagents (off), dynamic directory awareness (off), compact large results (on), auto exclue metadata (on), Image History (Low), Keep reasoning content (off), Emergency Recovery (off), Auto truncate results (off), Memory (off), No FluxFlow IDE Companion
211
- `;var Ii=`# FluxFlow Tool Reference
211
+ `;var Li=`# FluxFlow Tool Reference
212
212
 
213
213
  ## Protocol: [tool:functions.ToolName(arg1="val")]
214
214
 
@@ -248,7 +248,7 @@ Open in chat via /settings
248
248
  * KeyboardTyping(text, autoPressEnter?) \u2192 Type string
249
249
  * KeyPress(key) \u2192 Key/combo dispatch ("ctrl;c", "enter", etc.)
250
250
  * RecaptureScreen() \u2192 Fresh screenshot + coordinate grid
251
- `;var Di=`# Fluxflow Architecture
251
+ `;var Pi=`# Fluxflow Architecture
252
252
 
253
253
  ## 1. Terminal Engine
254
254
  * Framework: React + Ink terminal UI
@@ -278,7 +278,7 @@ Open in chat via /settings
278
278
  ## 6. IDE Bridge
279
279
  * Protocol: WebSocket on ws://localhost:56832
280
280
  * State Sync: Focused file, open tabs, cursor line, selection, diagnostics
281
- `;var Oi=`# FluxFlow Sub-Agents & Multi-Agent Architecture
281
+ `;var $i=`# FluxFlow Sub-Agents & Multi-Agent Architecture
282
282
 
283
283
  ## Execution Modes
284
284
  * InvokeSync \u2192 Synchronous blocking delegation; main agent halts until sub-agent finishes task
@@ -309,7 +309,7 @@ Route sub-agent workloads to faster/cheaper models independently of the main age
309
309
  * SUBAGENT_MODEL \u2192 Target model override
310
310
  * SUBAGENT_PROVIDER \u2192 Target provider override
311
311
  * Setting SubAgentModel=ENV in settings pulls directly from environment overrides
312
- `;var Li=`# FluxFlow Security, Sandboxing & Safety
312
+ `;var Ni=`# FluxFlow Security, Sandboxing & Safety
313
313
 
314
314
  ## Human-in-the-Loop Governance
315
315
  * Execution Approval Gate \u2192 Destructive commands and high-risk file modifications require explicit user authorization (Allow / Deny)
@@ -332,7 +332,7 @@ Route sub-agent workloads to faster/cheaper models independently of the main age
332
332
  * Emergency Rollback \u2192 Automatic pre-turn file snapshots; Agent can still fix it (default: OFF) \u2192 references/SETTINGS.md
333
333
  * Git-less Checkpoint Reversion \u2192 Trigger conversational changes rollback via double-ESC
334
334
  * External Sanctuary Redirection \u2192 Move ~/.fluxflow data sanctuary (chats, keys etc)
335
- `;var Pi=`# Fluxflow IDE Companion
335
+ `;var Fi=`# Fluxflow IDE Companion
336
336
 
337
337
  ## WebSocket Bridge Protocol
338
338
  * Local Bridge \u2192 Runs on ws://localhost:56832 connecting FluxFlow CLI with the companion editor extension
@@ -350,7 +350,7 @@ Route sub-agent workloads to faster/cheaper models independently of the main age
350
350
  * File Focus \u2192 Automatically opens edited files in active IDE window
351
351
  * Diff Preview \u2192 Streams side-by-side or inline diff highlights (showDiff, highlightDiff) directly in editor
352
352
  * Status Bar Sync \u2192 Real-time agent status (thinking, running tool, awaiting input) reflected in IDE status bar
353
- `;var $i=`# Fluxflow Modes
353
+ `;var Bi=`# Fluxflow Modes
354
354
 
355
355
  ## Modes Overview (TAB to cycle)
356
356
  * [Flux] (Workspace / Dev) \u2192 Primary coding & workspace agent
@@ -368,7 +368,7 @@ Route sub-agent workloads to faster/cheaper models independently of the main age
368
368
  * User Inquiry: AskUser \u2192 [Universal]
369
369
  * Document Creation: WritePDF, WriteDoc \u2192 [Flow]
370
370
  * GUI & Desktop Automation: Click, Drag, Scroll, KeyboardTyping, KeyPress, RecaptureScreen \u2192 [ICU] | [FluxCU]
371
- `;var Ni=`# FluxFlow AI Providers & Setup
371
+ `;var Ui=`# FluxFlow AI Providers & Setup
372
372
 
373
373
  ## Supported Providers
374
374
  * Gemini (aistudio.google.com) | NVIDIA NIM (build.nvidia.com) | DeepSeek (platform.deepseek.com) | Mistral (admin.mistral.ai) | Ollama Local/Cloud (ollama.com) | InferX (inferx.net) | SenseNova (platform.sensenova.ai) | Poolside (platform.poolside.ai) | OpenRouter (openrouter.ai) | AIHubMix (aihubmix.com) | Experiential Labs (experientiallabs.ai) | TokenHarbor (tokenharbor.ai) | APInex (apinex.bond)
@@ -398,7 +398,7 @@ Route sub-agent workloads to faster/cheaper models independently of the main age
398
398
  * Multimodal (Vision): /model <model-id> -m
399
399
  3. Context Window Override:
400
400
  * Set HIGH_CONTEXT=<tokens> in ENV (range: 32k to 1M)
401
- `;var Fi=`# Fluxflow Instructions & Skills System
401
+ `;var Wi=`# Fluxflow Instructions & Skills System
402
402
 
403
403
  ## 1. Instructions (AGENTS.md / FLUXFLOW.md root only)
404
404
  * Locations:
@@ -442,14 +442,14 @@ Instruction for this model ID across all providers.
442
442
 
443
443
  * On-Demand Reference System:
444
444
  * Reference: Offload deep/contexual specs to **/{SKILL.md,skill-reference-folder/*.md} & reference in SKILL.md. Saves tokens
445
- `;var Oo="v4";try{let e=Es.dirname(fa(import.meta.url)),t=[Es.join(e,"../../package.json"),Es.join(e,"../package.json")],n=!1;for(let s of t)if(Bi.existsSync(s)){let o=JSON.parse(Bi.readFileSync(s,"utf8"));if(o.version){Oo=o.version,n=!0;break}}if(!n)try{let s=Ui("fluxflow -v",{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"],timeout:2e3}).trim();s&&(s.startsWith("v")||/^\d+\.\d+/.test(s))&&(Oo=s,n=!0)}catch{}if(!n)try{let s=Ui("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&&(Oo=o.version)}catch{}}catch{}var Cs={"SKILL.md":`---
445
+ `;var Lo="v4";try{let e=Cs.dirname(ha(import.meta.url)),t=[Cs.join(e,"../../package.json"),Cs.join(e,"../package.json")],n=!1;for(let s of t)if(Hi.existsSync(s)){let o=JSON.parse(Hi.readFileSync(s,"utf8"));if(o.version){Lo=o.version,n=!0;break}}if(!n)try{let s=Gi("fluxflow -v",{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"],timeout:2e3}).trim();s&&(s.startsWith("v")||/^\d+\.\d+/.test(s))&&(Lo=s,n=!0)}catch{}if(!n)try{let s=Gi("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&&(Lo=o.version)}catch{}}catch{}var vs={"SKILL.md":`---
446
446
  name: fluxflow
447
447
  description: System Generated Documentation. Read this if asked anything regarding FluxFlow Harness
448
448
  ---
449
449
 
450
450
  # FluxFlow, by Kushal Roy Chowdhury
451
451
  Open Source Terminal AI Assistant
452
- App Version: ${Oo}. Check Updates: fluxflow --update check. Update: fluxflow --update
452
+ App Version: ${Lo}. Check Updates: fluxflow --update check. Update: fluxflow --update
453
453
  GitHub: https://github.com/KushalRoyChowdhury/fluxflow-cli
454
454
  Public Docs: https://fluxflow-cli.onrender.com
455
455
 
@@ -471,25 +471,25 @@ Public Docs: https://fluxflow-cli.onrender.com
471
471
 
472
472
  Default Context Length: 256k Tokens. Can be changed via ENV/In-app Settings \u2192 references/{SETTINGS,ENV}.md
473
473
 
474
- Docs missing required info? Say you are not sure enough to answer. Dont give wrong info`,"references/MODES.md":$i,"references/PROVIDERS.md":Ni,"references/PLUGINS.md":Fi,"references/STARTUP.md":Ci,"references/ENV.md":vi,"references/COMMANDS.md":Ri,"references/SETTINGS.md":Mi,"references/TOOLS.md":Ii,"references/ARCHITECTURE.md":Di,"references/SUB_AGENTS.md":Oi,"references/SECURITY.md":Li,"references/IDE.md":Pi};var Wi=()=>{try{let e=Rn.join(nn,"skills","fluxflow"),t=Rn.join(e,"references");if(process.env.NO_DEV==="true"||process.env.NO_DEV==="1"||process.env.NO_DEV===!0||process.env.NO_INS==="true"||process.env.NO_INS==="1"||process.env.NO_INS===!0||!1){dn.existsSync(e)&&dn.rmSync(e,{recursive:!0,force:!0});return}let s=new Set(Object.keys(Cs).map(o=>Rn.normalize(o)));for(let[o,l]of Object.entries(Cs)){let f=Rn.join(e,o),a=Rn.dirname(f);dn.existsSync(a)||dn.mkdirSync(a,{recursive:!0});let h=l.trim()+`
475
- `,g=null;dn.existsSync(f)&&(g=dn.readFileSync(f,"utf8")),g!==h&&dn.writeFileSync(f,h,"utf8")}if(dn.existsSync(t)){let o=dn.readdirSync(t);for(let l of o){let f=Rn.normalize(Rn.join("references",l));if(!s.has(f)){let a=Rn.join(t,l);try{dn.rmSync(a,{recursive:!0,force:!0})}catch{}}}}}catch{}};var fo=(e,t)=>{try{if(!on.existsSync(e))return null;let n=Array.isArray(t)?t.map(o=>o.toLowerCase()):[t.toLowerCase()],s=on.readdirSync(e);for(let o of n){let l=s.find(f=>f.toLowerCase()===o);if(l){let f=fn.join(e,l);if(on.statSync(f).isFile())return f}}}catch{}return null},Os=(e,t)=>{let n=fo(e,t);if(n)try{return on.readFileSync(n,"utf8")}catch{}return""},Hi=new Set([".git","node_modules",".gemini","dist","build",".next","out",".cache","bin","obj","vendor","venv",".idea",".gradle",".terraform","target","coverage",".vscode",".svn",".hg",".fslckout",".github",".gitlab",".circleci",".gitea",".gitee",".lerna",".changeset",".nx",".npm",".yarn",".pnpm-store",".pnpm",".expo",".nuxt",".svelte-kit",".docusaurus",".turbo",".vercel","bower_components",".netlify",".vuepress",".quasar",".output",".angular","jspm_packages",".parcel-cache",".rollup.cache",".rspack",".vitepress","__pycache__",".pytest_cache",".mypy_cache",".tox",".poetry","env","vhdl",".ipynb_checkpoints",".jupyter",".conda",".pdm-build",".bundle",".yardoc",".metadata","App_Data","ClientBin",".cargo",".rustc_info",".go","Godeps","_vendor",".rake_tasks","CMakefiles",".wakatime",".dart_tool",".fvm",".cocoapods","Pods",".pub-cache",".symlinks","DerivedData",".xcworkspace",".serverless",".aws",".gcloud",".azure",".kube",".vagrant",".docker","postgres-data","redis-data","mongo-data",".Spotlight-V100",".Trashes","$RECYCLE.BIN","System Volume Information",".DocumentRevisions-V100",".fseventsd","AppData","Application Data","Local","LocalLow","Roaming","$WinREAgent","$WINDOWS.~BT","$WINDOWS.~WS","scw","System32","SysWOW64",".AppleDouble",".AppleDB",".AppleDesktop","_CodeSignature",".cmio",".LSOverride",".localized",".TemporaryItems",".Trash",".Trash-0",".Trash-1000",".gvfs",".local",".config",".dbus",".fontconfig",".snap",".var",".lost+found","lost+found",".thumb",".thumbnails","EFI","boot","grub","logs","log",".nyc_output",".sonar",".ruff_cache",".VSCodeCounter",".skills","skills"]),Ls=(e=process.cwd(),t=0,n=8)=>{let s=[];if(t>n)return s;try{if(!on.existsSync(e))return s;let o=on.readdirSync(e,{withFileTypes:!0});for(let l of o){let f=l.name,a=fn.join(e,f);if(l.isDirectory())!Hi.has(f)&&!Hi.has(f.toLowerCase())&&s.push(...Ls(a,t+1,n));else if(l.isFile()){let h=f.toLowerCase();(h==="agents.md"||h==="agent.md")&&s.push(a)}}}catch{}return s},Gi=(e,t=2)=>{if(!e)return"";let n=" ".repeat(t);return e.split(/\r?\n/).map(s=>n+s).join(`
476
- `)},qi=()=>fo(nn,["agents.md","agent.md"]),zi=()=>fo(process.cwd(),["agents.md","agent.md"]),Ji=()=>fo(nn,["fluxflow.md"]),Xi=()=>fo(process.cwd(),["fluxflow.md"]),Lo=qi(),Is=zi(),Mn=Ls(),Po=Ji(),$o=Xi(),ji=null,Ds="",Qi=!1,ga=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&&(Ds=o[1].trim(),process.env.NO_INS=!0),/<><\s*NO_INS/.test(n)&&(Qi=!0),s.trim()},ma=()=>(Lo=qi(),Lo?Os(nn,["agents.md","agent.md"]).trim():""),ha=()=>{if(Mn=Ls(),Is=zi(),!Mn||Mn.length===0)return"";let e=process.cwd(),t=[...Mn].sort((s,o)=>{let l=fn.relative(e,s).replace(/\\/g,"/"),f=fn.relative(e,o).replace(/\\/g,"/"),a=!l.includes("/"),h=!f.includes("/");return a&&!h?-1:!a&&h?1:l.localeCompare(f)}),n=[];for(let s of t)try{let o=on.readFileSync(s,"utf8").trim();if(!o)continue;let l=fn.relative(e,s).replace(/\\/g,"/");if(!l.includes("/"))n.push(Gi(o,2));else{let a=fn.dirname(l)+"/:";n.push(`${a}
477
- ${Gi(o,2)}`)}}catch{}return n.join(`
474
+ Docs missing required info? Say you are not sure enough to answer. Dont give wrong info`,"references/MODES.md":Bi,"references/PROVIDERS.md":Ui,"references/PLUGINS.md":Wi,"references/STARTUP.md":Mi,"references/ENV.md":Ii,"references/COMMANDS.md":Di,"references/SETTINGS.md":Oi,"references/TOOLS.md":Li,"references/ARCHITECTURE.md":Pi,"references/SUB_AGENTS.md":$i,"references/SECURITY.md":Ni,"references/IDE.md":Fi};var ji=()=>{try{let e=Mn.join(on,"skills","fluxflow"),t=Mn.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){dn.existsSync(e)&&dn.rmSync(e,{recursive:!0,force:!0});return}let s=new Set(Object.keys(vs).map(o=>Mn.normalize(o)));for(let[o,l]of Object.entries(vs)){let f=Mn.join(e,o),a=Mn.dirname(f);dn.existsSync(a)||dn.mkdirSync(a,{recursive:!0});let m=l.trim()+`
475
+ `,g=null;dn.existsSync(f)&&(g=dn.readFileSync(f,"utf8")),g!==m&&dn.writeFileSync(f,m,"utf8")}if(dn.existsSync(t)){let o=dn.readdirSync(t);for(let l of o){let f=Mn.normalize(Mn.join("references",l));if(!s.has(f)){let a=Mn.join(t,l);try{dn.rmSync(a,{recursive:!0,force:!0})}catch{}}}}}catch{}};var uo=(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 l=s.find(f=>f.toLowerCase()===o);if(l){let f=fn.join(e,l);if(sn.statSync(f).isFile())return f}}}catch{}return null},Ls=(e,t)=>{let n=uo(e,t);if(n)try{return sn.readFileSync(n,"utf8")}catch{}return""},Vi=new Set([".git","node_modules",".gemini","dist","build",".next","out",".cache","bin","obj","vendor","venv",".idea",".gradle",".terraform","target","coverage",".vscode",".svn",".hg",".fslckout",".github",".gitlab",".circleci",".gitea",".gitee",".lerna",".changeset",".nx",".npm",".yarn",".pnpm-store",".pnpm",".expo",".nuxt",".svelte-kit",".docusaurus",".turbo",".vercel","bower_components",".netlify",".vuepress",".quasar",".output",".angular","jspm_packages",".parcel-cache",".rollup.cache",".rspack",".vitepress","__pycache__",".pytest_cache",".mypy_cache",".tox",".poetry","env","vhdl",".ipynb_checkpoints",".jupyter",".conda",".pdm-build",".bundle",".yardoc",".metadata","App_Data","ClientBin",".cargo",".rustc_info",".go","Godeps","_vendor",".rake_tasks","CMakefiles",".wakatime",".dart_tool",".fvm",".cocoapods","Pods",".pub-cache",".symlinks","DerivedData",".xcworkspace",".serverless",".aws",".gcloud",".azure",".kube",".vagrant",".docker","postgres-data","redis-data","mongo-data",".Spotlight-V100",".Trashes","$RECYCLE.BIN","System Volume Information",".DocumentRevisions-V100",".fseventsd","AppData","Application Data","Local","LocalLow","Roaming","$WinREAgent","$WINDOWS.~BT","$WINDOWS.~WS","scw","System32","SysWOW64",".AppleDouble",".AppleDB",".AppleDesktop","_CodeSignature",".cmio",".LSOverride",".localized",".TemporaryItems",".Trash",".Trash-0",".Trash-1000",".gvfs",".local",".config",".dbus",".fontconfig",".snap",".var",".lost+found","lost+found",".thumb",".thumbnails","EFI","boot","grub","logs","log",".nyc_output",".sonar",".ruff_cache",".VSCodeCounter",".skills","skills"]),Ps=(e=process.cwd(),t=0,n=8)=>{let s=[];if(t>n)return s;try{if(!sn.existsSync(e))return s;let o=sn.readdirSync(e,{withFileTypes:!0});for(let l of o){let f=l.name,a=fn.join(e,f);if(l.isDirectory())!Vi.has(f)&&!Vi.has(f.toLowerCase())&&s.push(...Ps(a,t+1,n));else if(l.isFile()){let m=f.toLowerCase();(m==="agents.md"||m==="agent.md")&&s.push(a)}}}catch{}return s},Ki=(e,t=2)=>{if(!e)return"";let n=" ".repeat(t);return e.split(/\r?\n/).map(s=>n+s).join(`
476
+ `)},Xi=()=>uo(on,["agents.md","agent.md"]),Qi=()=>uo(process.cwd(),["agents.md","agent.md"]),Zi=()=>uo(on,["fluxflow.md"]),er=()=>uo(process.cwd(),["fluxflow.md"]),Po=Xi(),Ds=Qi(),In=Ps(),$o=Zi(),No=er(),Yi=null,Os="",tr=!1,pa=e=>{if(!e||!/^<<<[\s\S]*?Identity:/m.test(e))return e;let t=e.match(/^<<<\s*\r?\n([\s\S]*?)\r?\n>>>\s*(?:\r?\n)?([\s\S]*)$/);if(!t)return e;let n=t[1],s=t[2],o=n.match(/^Identity:\s*([\s\S]*?)(?=\r?\n\s*(?:<><|>>>)|$)/m);return o&&(Os=o[1].trim(),process.env.NO_INS=!0),/<><\s*NO_INS/.test(n)&&(tr=!0),s.trim()},ya=()=>(Po=Xi(),Po?Ls(on,["agents.md","agent.md"]).trim():""),xa=()=>{if(In=Ps(),Ds=Qi(),!In||In.length===0)return"";let e=process.cwd(),t=[...In].sort((s,o)=>{let l=fn.relative(e,s).replace(/\\/g,"/"),f=fn.relative(e,o).replace(/\\/g,"/"),a=!l.includes("/"),m=!f.includes("/");return a&&!m?-1:!a&&m?1:l.localeCompare(f)}),n=[];for(let s of t)try{let o=sn.readFileSync(s,"utf8").trim();if(!o)continue;let l=fn.relative(e,s).replace(/\\/g,"/");if(!l.includes("/"))n.push(Ki(o,2));else{let a=fn.dirname(l)+"/:";n.push(`${a}
477
+ ${Ki(o,2)}`)}}catch{}return n.join(`
478
478
 
479
- `).trim()},Ps=()=>{Po=Ji();let e=Po?Os(nn,["fluxflow.md"]).trim():"";return ga(e)},$s=()=>($o=Xi(),$o?Os(process.cwd(),["fluxflow.md"]).trim():""),Ns=ma(),No=ha(),lo=Ps(),co=$s(),Vi=(e,t="",n="")=>{if(!e)return"";let s=n.toLowerCase().trim(),o=t.toLowerCase().trim(),l=fn.posix.basename(o),f=s&&o?`${s}::${o}`:"",a=s&&l?`${s}::${l}`:"",h=u=>!u||!o?!1:u===o||u===l||u===f||u===a,g=[];return e.replace(/<start_provider_([^>\r\n]+)>([\s\S]*?)<end_provider_([^>\r\n]+)>/gi,(u,m,y,i)=>{if(s&&m.trim().toLowerCase()===i.trim().toLowerCase()&&m.trim().toLowerCase()===s){let w=y.replace(/<start_model_([^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n]+)>/gi,(v,b,E,O)=>{if(b.trim().toLowerCase()===O.trim().toLowerCase()){let C=b.trim().toLowerCase();if(h(C)){let S=E.trim();S&&g.push(S)}}return""}).trim();w&&g.push(w)}return""}),e.replace(/<start_model_([^>\r\n]+::[^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n]+::[^>\r\n]+)>/gi,(u,m,y,i)=>{if(m.trim().toLowerCase()===i.trim().toLowerCase()){let c=m.trim().toLowerCase();if(f&&(c===f||a&&c===a)){let w=y.trim();w&&g.push(w)}}return""}),e.replace(/<start_model_([^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n]+)>/gi,(u,m,y,i)=>{if(m.includes("::"))return"";if(m.trim().toLowerCase()===i.trim().toLowerCase()){let c=m.trim().toLowerCase();if(o&&(c===o||c===l)){let w=y.trim();w&&g.push(w)}}return""}),g.join(`
479
+ `).trim()},$s=()=>{$o=Zi();let e=$o?Ls(on,["fluxflow.md"]).trim():"";return pa(e)},Ns=()=>(No=er(),No?Ls(process.cwd(),["fluxflow.md"]).trim():""),Fs=ya(),Fo=xa(),co=$s(),fo=Ns(),qi=(e,t="",n="")=>{if(!e)return"";let s=n.toLowerCase().trim(),o=t.toLowerCase().trim(),l=fn.posix.basename(o),f=s&&o?`${s}::${o}`:"",a=s&&l?`${s}::${l}`:"",m=u=>!u||!o?!1:u===o||u===l||u===f||u===a,g=[];return e.replace(/<start_provider_([^>\r\n]+)>([\s\S]*?)<end_provider_([^>\r\n]+)>/gi,(u,h,y,i)=>{if(s&&h.trim().toLowerCase()===i.trim().toLowerCase()&&h.trim().toLowerCase()===s){let w=y.replace(/<start_model_([^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n]+)>/gi,(v,b,E,O)=>{if(b.trim().toLowerCase()===O.trim().toLowerCase()){let C=b.trim().toLowerCase();if(m(C)){let S=E.trim();S&&g.push(S)}}return""}).trim();w&&g.push(w)}return""}),e.replace(/<start_model_([^>\r\n]+::[^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n]+::[^>\r\n]+)>/gi,(u,h,y,i)=>{if(h.trim().toLowerCase()===i.trim().toLowerCase()){let c=h.trim().toLowerCase();if(f&&(c===f||a&&c===a)){let w=y.trim();w&&g.push(w)}}return""}),e.replace(/<start_model_([^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n]+)>/gi,(u,h,y,i)=>{if(h.includes("::"))return"";if(h.trim().toLowerCase()===i.trim().toLowerCase()){let c=h.trim().toLowerCase();if(o&&(c===o||c===l)){let w=y.trim();w&&g.push(w)}}return""}),g.join(`
480
480
 
481
- `).trim()},pa=(e="",t="")=>{let n=`${e||""}::${t||""}`.toLowerCase().trim();ji!==n&&(ji=n,lo=Ps(),co=$s())};Wi();var ya=e=>{if(!e)return null;let t=e.match(/^\s*---\r?\n([\s\S]*?)\r?\n---(?:\r?\n)?([\s\S]*)$/);if(!t)return null;let n=t[1];if((t[2]||"").trim().length===0)return null;let o="",l="",f=n.match(/^name:\s*(.+)$/m),a=n.match(/^description:\s*(.+)$/m);return f&&(o=f[1].trim().replace(/^["']|["']$/g,"")),a&&(l=a[1].trim().replace(/^["']|["']$/g,"")),o&&l?{name:o,description:l}:null},xa=e=>{let t=[];if(!e||!on.existsSync(e))return t;let n=(s,o=0)=>{if(!(o>5))try{let l=on.readdirSync(s,{withFileTypes:!0});for(let f of l){let a=fn.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},Zi=e=>{let t=xa(e),n=[];for(let s of t)try{let o=on.readFileSync(s,"utf8"),l=ya(o);l&&n.push({...l,filePath:s})}catch{}return n},er=e=>!e||e.length===0?"":e.map(t=>`- ${t.name}: ${t.description}`).join(`
482
- `),tr=Zi(nn),nr=Zi(process.cwd()),vs=er(tr),Rs=er(nr),or=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"},sr=()=>(tr||[]).filter(e=>!or(e)),ir=()=>(nr||[]).filter(e=>!or(e)),sc=(Ns?1:0)+(Mn?.length||(No?1:0))+(lo?1:0)+(co?1:0)+sr().length+ir().length,Ms=(e,t="Project")=>{if(!e)return"";let n=e.replace(/\\/g,"/");if(t==="Global"){let o=ua.homedir().replace(/\\/g,"/");return n.toLowerCase().startsWith(o.toLowerCase())?"~"+n.slice(o.length):n}let s=fn.relative(process.cwd(),e).replace(/\\/g,"/");return s.startsWith(".")?s:`./${s}`},ic=()=>{lo=Ps(),co=$s();let e=[];Lo&&Ns.length>0&&e.push({scope:"Global",path:Lo}),Mn&&Mn.length>0&&No.length>0?Mn.forEach(l=>{e.push({scope:"Project",path:l})}):Is&&No.length>0&&e.push({scope:"Project",path:Is}),Po&&lo.length>0&&e.push({scope:"Global",path:Po}),$o&&co.length>0&&e.push({scope:"Project",path:$o});let t=sr(),n=ir(),s=e.length+t.length+n.length;if(s===0)return`\u2726 Loaded Files & Instructions
481
+ `).trim()},ba=(e="",t="")=>{let n=`${e||""}::${t||""}`.toLowerCase().trim();Yi!==n&&(Yi=n,co=$s(),fo=Ns())};ji();var ka=e=>{if(!e)return null;let t=e.match(/^\s*---\r?\n([\s\S]*?)\r?\n---(?:\r?\n)?([\s\S]*)$/);if(!t)return null;let n=t[1];if((t[2]||"").trim().length===0)return null;let o="",l="",f=n.match(/^name:\s*(.+)$/m),a=n.match(/^description:\s*(.+)$/m);return f&&(o=f[1].trim().replace(/^["']|["']$/g,"")),a&&(l=a[1].trim().replace(/^["']|["']$/g,"")),o&&l?{name:o,description:l}:null},wa=e=>{let t=[];if(!e||!sn.existsSync(e))return t;let n=(s,o=0)=>{if(!(o>5))try{let l=sn.readdirSync(s,{withFileTypes:!0});for(let f of l){let a=fn.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},nr=e=>{let t=wa(e),n=[];for(let s of t)try{let o=sn.readFileSync(s,"utf8"),l=ka(o);l&&n.push({...l,filePath:s})}catch{}return n},or=e=>!e||e.length===0?"":e.map(t=>`- ${t.name}: ${t.description}`).join(`
482
+ `),sr=nr(on),ir=nr(process.cwd()),Rs=or(sr),Ms=or(ir),rr=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"},ar=()=>(sr||[]).filter(e=>!rr(e)),lr=()=>(ir||[]).filter(e=>!rr(e)),ac=(Fs?1:0)+(In?.length||(Fo?1:0))+(co?1:0)+(fo?1:0)+ar().length+lr().length,Is=(e,t="Project")=>{if(!e)return"";let n=e.replace(/\\/g,"/");if(t==="Global"){let o=ma.homedir().replace(/\\/g,"/");return n.toLowerCase().startsWith(o.toLowerCase())?"~"+n.slice(o.length):n}let s=fn.relative(process.cwd(),e).replace(/\\/g,"/");return s.startsWith(".")?s:`./${s}`},lc=()=>{co=$s(),fo=Ns();let e=[];Po&&Fs.length>0&&e.push({scope:"Global",path:Po}),In&&In.length>0&&Fo.length>0?In.forEach(l=>{e.push({scope:"Project",path:l})}):Ds&&Fo.length>0&&e.push({scope:"Project",path:Ds}),$o&&co.length>0&&e.push({scope:"Global",path:$o}),No&&fo.length>0&&e.push({scope:"Project",path:No});let t=ar(),n=lr(),s=e.length+t.length+n.length;if(s===0)return`\u2726 Loaded Files & Instructions
483
483
  \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m No instruction or skill files are currently loaded.
484
484
  \u2800`;let o=[];return o.push(`\u2726 Loaded Files & Instructions (${s} ${s===1?"file":"files"} active)`),e.length>0&&(o.push(`
485
- \x1B[1mInstructions:\x1B[22m`),e.forEach(l=>{o.push(` \u2022 [${l.scope}] ${Ms(l.path,l.scope)}`)})),(t?.length>0||n?.length>0)&&(o.push(`
486
- \x1B[1mSkills:\x1B[22m`),t?.length>0&&t.forEach(l=>{o.push(` \u2022 [Global] \x1B[36m${l.name}\x1B[39m`),o.push(` \x1B[2m\u2514\u2500 ${Ms(l.filePath,"Global")}\x1B[22m`)}),n?.length>0&&n.forEach(l=>{o.push(` \u2022 [Project] \x1B[36m${l.name}\x1B[39m`),o.push(` \x1B[2m\u2514\u2500 ${Ms(l.filePath,"Project")}\x1B[22m`)})),o.push("\u2800"),o.join(`
487
- `)},rr=!1;(async()=>{try{let e=await so();if(Number(e?.display)===1){let{default:t}=await import("screenshot-desktop"),n=await t.listDisplays();n&&n.length>1&&(rr=!0)}}catch{}})();var Ki=null,ao=null,Yi=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",rc=process.env.NO_DEV||!1,ba=(e,t)=>{if(!t)return"";if(e!==Ki||ao===null){Ki=e;try{let n=Ct(Bn,[]);Array.isArray(n)&&n.length>0?ao=n.map(s=>`- ${s.memory}`).join(`
488
- `):ao=""}catch(n){ao="",on.appendFileSync(`${vn}/memory/error.txt`,`${n.message}
485
+ \x1B[1mInstructions:\x1B[22m`),e.forEach(l=>{o.push(` \u2022 [${l.scope}] ${Is(l.path,l.scope)}`)})),(t?.length>0||n?.length>0)&&(o.push(`
486
+ \x1B[1mSkills:\x1B[22m`),t?.length>0&&t.forEach(l=>{o.push(` \u2022 [Global] \x1B[36m${l.name}\x1B[39m`),o.push(` \x1B[2m\u2514\u2500 ${Is(l.filePath,"Global")}\x1B[22m`)}),n?.length>0&&n.forEach(l=>{o.push(` \u2022 [Project] \x1B[36m${l.name}\x1B[39m`),o.push(` \x1B[2m\u2514\u2500 ${Is(l.filePath,"Project")}\x1B[22m`)})),o.push("\u2800"),o.join(`
487
+ `)},cr=!1;(async()=>{try{let e=await io();if(Number(e?.display)===1){let{default:t}=await import("screenshot-desktop"),n=await t.listDisplays();n&&n.length>1&&(cr=!0)}}catch{}})();var zi=null,lo=null,Ji=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",cc=process.env.NO_DEV||!1,Ta=(e,t)=>{if(!t)return"";if(e!==zi||lo===null){zi=e;try{let n=Ct(Un,[]);Array.isArray(n)&&n.length>0?lo=n.map(s=>`- ${s.memory}`).join(`
488
+ `):lo=""}catch(n){lo="",sn.appendFileSync(`${Rn}/memory/error.txt`,`${n.message}
489
489
  -------------------------------------------------
490
490
 
491
- `)}}return ao},ar=(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) --
492
- ${e}`:"";return o?`${o}`:""},lr=(e,t,n,s,o=!0,l=!1,f="Google",a=!1,h,g,u=!1,m="")=>{let y=!1;process.env.forcedReasoning&&(y=!0);let i="";if(!h&&f==="Google"){let J=t;t==="Fast"&&(J="Off"),t==="Low"&&(J="Minimal"),t==="Standard"&&(J="Medium"),(t==="xHigh"||t==="Max")&&(J="xHigh"),i=Do[J]||Do.Medium}if(h||f!=="Google"){let J={Fast:"Lowest",Low:"Low",Medium:"Medium",Standard:"Medium",High:"High",xHigh:"High",Max:"High"};i=Do.xHigh,i=i.replace("Effort: High",`Effort: ${J[t]}`),t==="Fast"?i=`Effort: Lowest
491
+ `)}}return lo},dr=(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) --
492
+ ${e}`:"";return o?`${o}`:""},fr=(e,t,n,s,o=!0,l=!1,f="Google",a=!1,m,g,u=!1,h="")=>{let y=!1;process.env.forcedReasoning&&(y=!0);let i="";if(!m&&f==="Google"){let Z=t;t==="Fast"&&(Z="Off"),t==="Low"&&(Z="Minimal"),t==="Standard"&&(Z="Medium"),(t==="xHigh"||t==="Max")&&(Z="xHigh"),i=Oo[Z]||Oo.Medium}if(m||f!=="Google"){let Z={Fast:"Lowest",Low:"Low",Medium:"Medium",Standard:"Medium",High:"High",xHigh:"High",Max:"High"};i=Oo.xHigh,i=i.replace("Effort: High",`Effort: ${Z[t]}`),t==="Fast"?i=`Effort: Lowest
493
493
  No thinking. Immediate response
494
494
  Verify imports, tool results & system stability; avoid syntax errors`:t==="Low"&&(i=`Effort: Low
495
495
  Quick, focused thinking, intent & complexity, required tools/files/actions, before acting
@@ -500,12 +500,12 @@ Brief thoughts, think only enough to avoid mistakes, verify imports, tool result
500
500
  ${c.length?"":`
501
501
  `}`:"",v=e.name&&e.name?.length>0?`User Name: ${e.name}
502
502
  ${w.length||c.length?"":`
503
- `}`:"",b=process.cwd(),E=ba(g,o),O=E?.length>0?`--- Saved Memories ---
503
+ `}`:"",b=process.cwd(),E=Ta(g,o),O=E?.length>0?`--- Saved Memories ---
504
504
  ${E}
505
505
 
506
- `:"";pa(f,m);let C=Vi(lo,m,f).trim(),R=[Ns,C].filter(J=>J&&J.length>0).join(`
506
+ `:"";ba(f,h);let C=qi(co,h,f).trim(),R=[Fs,C].filter(Z=>Z&&Z.length>0).join(`
507
507
 
508
- `).trim(),L=Vi(co,m,f).trim(),d=[No,L].filter(J=>J&&J.length>0).join(`
508
+ `).trim(),L=qi(fo,h,f).trim(),d=[Fo,L].filter(Z=>Z&&Z.length>0).join(`
509
509
 
510
510
  `).trim(),k=R.length>0||d.length>0?`--- Additional Instructions ---
511
511
  ${R.length>0?`-- Global --
@@ -514,27 +514,27 @@ ${R}`:""}${d.length>0?`${R.length>0?`
514
514
  `:""}-- Project --
515
515
  ${d}`:""}
516
516
 
517
- `:"",r=(()=>{let J=process.cwd().toLowerCase();if(process.platform==="win32"){let re=process.env.SystemRoot?.toLowerCase()||"c:\\windows",Oe=process.env.ProgramFiles?.toLowerCase()||"c:\\program files",We=process.env["ProgramFiles(x86)"]?.toLowerCase()||"c:\\program files (x86)";return J.startsWith(re)||J.startsWith(Oe)||J.startsWith(We)}else return J==="/"||["/bin","/sbin","/etc","/usr","/var","/root"].some(Oe=>J.startsWith(Oe))})(),T=new Date,A=T.getFullYear(),D=T.toLocaleString("en-US",{month:"short"}).toUpperCase(),H=String(T.getDate()).padStart(2,"0"),$=`${A}-${D}-${H}`,M=!!s?.autoExcludeMetadata,te=process.env.I_HAVE_TOO_MUCH_MONEY==="true"||process.env.I_HAVE_TOO_MUCH_MONEY===!0||!1,le=process.env.NO_DEV==="true"||process.env.NO_DEV==="1"||process.env.NO_DEV===!0||!1;return`${te?`${" ".repeat(Math.floor(Math.random()*4)+1)}`:""}=== SYSTEM PROMPT ===
518
- Identity: ${Ds.length>1?Ds:"Flux Flow. Sassy, Friendly, CLI Assistant"}
519
- ${Qi?"":`${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"}`}${rr&&n.toLowerCase().includes("cu")?`
517
+ `:"",r=(()=>{let Z=process.cwd().toLowerCase();if(process.platform==="win32"){let ce=process.env.SystemRoot?.toLowerCase()||"c:\\windows",Oe=process.env.ProgramFiles?.toLowerCase()||"c:\\program files",Ue=process.env["ProgramFiles(x86)"]?.toLowerCase()||"c:\\program files (x86)";return Z.startsWith(ce)||Z.startsWith(Oe)||Z.startsWith(Ue)}else return Z==="/"||["/bin","/sbin","/etc","/usr","/var","/root"].some(Oe=>Z.startsWith(Oe))})(),T=new Date,A=T.getFullYear(),D=T.toLocaleString("en-US",{month:"short"}).toUpperCase(),W=String(T.getDate()).padStart(2,"0"),$=`${A}-${D}-${W}`,I=!!s?.autoExcludeMetadata,ne=process.env.I_HAVE_TOO_MUCH_MONEY==="true"||process.env.I_HAVE_TOO_MUCH_MONEY===!0||!1,fe=process.env.NO_DEV==="true"||process.env.NO_DEV==="1"||process.env.NO_DEV===!0||!1;return`${ne?`${" ".repeat(Math.floor(Math.random()*4)+1)}`:""}=== SYSTEM PROMPT ===
518
+ Identity: ${Os.length>1?Os:"Flux Flow. Sassy, Friendly, CLI Assistant"}
519
+ ${tr?"":`${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"}`}${cr&&n.toLowerCase().includes("cu")?`
520
520
  - Running on secondary screen. Opened app not visible in screenshot? Might be opened on primary. Use 'AskUser' with NO options and tell user to move app window to secondary`:""}
521
521
 
522
- - OS: ${Yi}${!le&&m.length>1?`
523
- - Model: ${fn.basename(m.trim()).replace(":free","").replace("-free","").replace("/free","").replace("_free","").replace("free_","").replaceAll("-"," ").replaceAll("_"," ").replace(/\b\w/g,J=>J.toUpperCase())}`.trimEnd():""}${M?`
522
+ - OS: ${Ji}${!fe&&h.length>1?`
523
+ - Model: ${fn.basename(h.trim()).replace(":free","").replace("-free","").replace("/free","").replace("_free","").replace("free_","").replaceAll("-"," ").replaceAll("_"," ").replace(/\b\w/g,Z=>Z.toUpperCase())}`.trimEnd():""}${I?`
524
524
  - Date: ${$}`:""}${o?`
525
525
  - Use relative time reference eg. few mins ago
526
- -- Chat Context > Metadata`:""}${(vs.length>0||Rs.length>0)&&n.toLowerCase().includes("flux")?`
526
+ -- Chat Context > Metadata`:""}${(Rs.length>0||Ms.length>0)&&n.toLowerCase().includes("flux")?`
527
527
  - Read relevant skills for tasks before proceeding (scope: global/project): Use ReadFile, virtual path="#skills/scope?/skillName". In-skill references: path="#skills/scope?/skillName/skill-reference-folder/file-name.md"`:""}
528
528
 
529
529
  -- THINKING GUIDANCE --
530
- ${f==="Mistral"||f==="Google"&&!h?`${i}
531
- ${y||t!=="Fast"&&(f==="Mistral"&&t==="Low"&&!h||t!=="High"&&!h)?`critical thinking policy
530
+ ${f==="Mistral"||f==="Google"&&!m?`${i}
531
+ ${y||t!=="Fast"&&(f==="Mistral"&&t==="Low"&&!m||t!=="High"&&!m)?`critical thinking policy
532
532
  Use <think>...</think> for reasoning before responding any queries
533
533
  `:""}`:`${i}
534
534
  `}${u?"":`Mandatory: Before calling tools, MUST provide a high level summary of your reasoning, plans, decisions, and next course of actions in chat
535
535
  `}
536
536
 
537
- ${Ti(n,Yi,a,f,s?.advanceRollback,s?.subAgents!==!1,!!s?.autoExec)}${o?`
537
+ ${Ai(n,Ji,a,f,s?.advanceRollback,s?.subAgents!==!1,!!s?.autoExec)}${o?`
538
538
 
539
539
  -- MEMORY RULES --
540
540
  - Subtly Personalize with relevent contextual memories. Auto Saves
@@ -548,13 +548,13 @@ ${Ti(n,Yi,a,f,s?.advanceRollback,s?.subAgents!==!1,!!s?.autoExec)}${o?`
548
548
  - use kaomojis heavily`:""}
549
549
  === END SYSTEM PROMPT ===
550
550
 
551
- ${v}${w}${c}${k}${vs.length>0&&n.toLowerCase().includes("flux")?`-- Global Skills --
552
- ${vs}
553
-
554
- `:""}${Rs.length>0&&n.toLowerCase().includes("flux")?`-- Project Skills --
551
+ ${v}${w}${c}${k}${Rs.length>0&&n.toLowerCase().includes("flux")?`-- Global Skills --
555
552
  ${Rs}
556
553
 
557
- `:""}${O}`.trim()},cr=(e="",t=!0,n=!0)=>`=== SYSTEM PROMPT (strict headless logic worker: zero user-facing text policy, strictly follow) ===
554
+ `:""}${Ms.length>0&&n.toLowerCase().includes("flux")?`-- Project Skills --
555
+ ${Ms}
556
+
557
+ `:""}${O}`.trim()},ur=(e="",t=!0,n=!0)=>`=== SYSTEM PROMPT (strict headless logic worker: zero user-facing text policy, strictly follow) ===
558
558
  identity: silent background system process, have no mouth, only output is valid tool calls
559
559
  [critical rules]
560
560
  - output exactly '[tool:ToolName(args)]' calls. no extra words outside
@@ -571,65 +571,65 @@ identity: silent background system process, have no mouth, only output is valid
571
571
  YOUR JOB: Analyze the 'User prompt' and 'Agent Raws' to extract facts for long-term memory or handle system tasks
572
572
  ${t?"If user tell something that is important (like, hobbies, preferences, facts about user, hates, likes, etc) to know user better over time, use user memory tools":""}
573
573
 
574
- ${Ai(t,n)}
574
+ ${vi(t,n)}
575
575
  === END SYSTEM PROMPT ===${e?`
576
576
 
577
577
  -- current saved user memories --
578
- ${e}`:""}`.trim();var dr=()=>import("./web_search-D2GOWARI.js").then(e=>e.web_search),fr=()=>import("./web_scrape-LAQI7CVA.js").then(e=>e.web_scrape),ur=()=>import("./memory-TVFFXCSD.js").then(e=>e.memory),gr=()=>import("./chat-HHMMKXDE.js").then(e=>e.chat),mr=()=>import("./view_file-JRVPAETL.js").then(e=>e.view_file),hr=()=>import("./write_file-QMTFTJ6V.js").then(e=>e.write_file),pr=()=>import("./update_file-BXYTHDAC.js").then(e=>e.update_file),yr=()=>import("./exec_command-BH3PUWVO.js").then(e=>e.exec_command),xr=()=>import("./read_folder-OOKZITME.js").then(e=>e.read_folder),Fs=()=>import("./ask_user-K2DLZF6H.js").then(e=>e.ask_user),br=()=>import("./write_pdf-UM6Z2J4K.js").then(e=>e.write_pdf),kr=()=>import("./write_docx-IUKMO7XL.js").then(e=>e.write_docx),Fo=()=>import("./search_keyword-EAMQWPPI.js").then(e=>e.search_keyword),wr=()=>import("./generate_image-KQBOTDD4.js").then(e=>e.generate_image),Bo=()=>import("./saveSummary-HFAPNJJH.js").then(e=>e.saveSummary),uo=()=>import("./addMemScore-HPTGXICT.js").then(e=>e.addMemScore),Tr=()=>import("./file_map-XK7BFZFI.js").then(e=>e.file_map),Uo=()=>import("./todo-7Q2JBEVP.js").then(e=>e.todo),Sr=()=>import("./invokeSync-BSBHO3CQ.js").then(e=>e.invokeSync),ka=()=>import("./invoke-6G7AHOVX.js").then(e=>e.invoke),_r=()=>import("./getProgress-VG2IBPZU.js").then(e=>e.getProgress),wa=()=>import("./cancel-7IMADALP.js").then(e=>e.cancel),Ar=()=>import("./emergency_rollback-HWM4FJ6J.js").then(e=>e.emergency_rollback),go=()=>import("./awaitSubagent-JTUSJDKD.js").then(e=>e.awaitSubagent),mo=()=>import("./answerSubagent-JUVFNLE5.js").then(e=>e.answerSubagent),Wo=()=>import("./steerSubagent-L2JVT4QN.js").then(e=>e.steerSubagent),Ho=()=>import("./computer_action-UTDLLMF2.js").then(e=>e.computer_action),Er=()=>import("./click-H7HTKF3R.js").then(e=>e.click),Cr=()=>import("./drag-U6X3O5GB.js").then(e=>e.drag),vr=()=>import("./scroll-SND6RHXA.js").then(e=>e.scroll),Bs=()=>import("./keyboard_typing-FXP3VJ6Q.js").then(e=>e.keyboard_typing),Us=()=>import("./key_press-QRO3OFLC.js").then(e=>e.key_press),Ws=()=>import("./recapture_screen-5FKLOHJL.js").then(e=>e.recapture_screen),Ta={web_search:dr,web_scrape:fr,memory:ur,chat:gr,view_file:mr,write_file:hr,update_file:pr,exec_command:yr,read_folder:xr,write_pdf:br,write_docx:kr,search_keyword:Fo,generate_image:wr,saveSummary:Bo,addMemScore:uo,file_map:Tr,todo:Uo,Todo:Uo,goal:Uo,Goal:Uo,invokeSync:Sr,invoke:ka,getProgress:_r,cancel:wa,awaitSubagent:go,answerSubagent:mo,steerSubagent:Wo,computer_action:Ho,computer_use:Ho,ComputerAction:Ho,ComputerUse:Ho,click:Er,Click:Er,drag:Cr,Drag:Cr,scroll:vr,Scroll:vr,keyboard_typing:Bs,KeyboardTyping:Bs,keyboardtyping:Bs,key_press:Us,KeyPress:Us,keypress:Us,recapture_screen:Ws,RecaptureScreen:Ws,recapturescreen:Ws,invoke_sync:Sr,get_progress:_r,await_subagent:go,answer_subagent:mo,steer_subagent:Wo,steer:Wo,Steer:Wo,ask:Fs,Ask:Fs,AskUser:Fs,WebSearch:dr,WebScrape:fr,ReadFile:mr,ReadFolder:xr,WriteFile:hr,PatchFile:pr,WritePDF:br,WriteDoc:kr,Run:yr,SearchKeyword:Fo,CodeSearch:Fo,code_search:Fo,Memory:ur,Chat:gr,GenerateImage:wr,saveSumary:Bo,SaveSummary:Bo,SaveSumary:Bo,add_mem_score:uo,AddMemScore:uo,addMemoryScore:uo,AddMemoryScore:uo,FileMap:Tr,answer:mo,Answer:mo,AnswerSubagent:mo,await:go,Await:go,AwaitSubagent:go,EmergencyRollback:Ar,emergency_rollback:Ar},ho=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=Ta[e];if(!g){let u=["ReadFile","ReadFolder","PatchFile","WriteFile","CodeSearch","Run","Goal","AskUser","WebSearch","WebScrape","WritePDF","WriteDoc","Click","Drag","Scroll","KeyboardTyping","KeyPress","RecaptureScreen","Invoke","InvokeSync","Await","GetProgress","Steer","Cancel","EmergencyRollback","Chat","Memory"],m={read:"ReadFile",view:"ReadFile",viewfile:"ReadFile",write:"WriteFile",edit:"PatchFile",patch:"PatchFile",update:"PatchFile",updatefile:"PatchFile",exec:"Run",command:"Run",bash:"Run",shell:"Run",powershell:"Run",search:"CodeSearch",grep:"CodeSearch",find:"CodeSearch",searchkeyword:"CodeSearch",folder:"ReadFolder",ls:"ReadFolder",dir:"ReadFolder",list:"ReadFolder",ask:"AskUser",question:"AskUser",pdf:"WritePDF",docx:"WriteDoc",doc:"WriteDoc",word:"WriteDoc",screenshot:"RecaptureScreen",screen:"RecaptureScreen",recapture:"RecaptureScreen",type:"KeyboardTyping",typing:"KeyboardTyping",keyboard:"KeyboardTyping",press:"KeyPress",key:"KeyPress",todo:"Goal",task:"Goal",subagent:"Invoke",agent:"Invoke"},y=o.replace(/[^a-z0-9]/g,""),i=m[y]||null;if(!i){let w=0,v=E=>{let O=new Set;for(let C=0;C<E.length-1;C++)O.add(E.slice(C,C+2));return O},b=v(y);for(let E of u){let O=E.toLowerCase().replace(/[^a-z0-9]/g,"");if(y===O){i=E;break}let C=0;(O.includes(y)||y.includes(O))&&(C+=.6);let S=v(O),R=0;for(let x of b)S.has(x)&&R++;let L=2*R/(b.size+S.size||1);C=Math.max(C,L),C>w&&C>=.35&&(w=C,i=E)}}let c=i?` Do you mean '${i}'?`:"";return`ERROR: Tool [${e}] not found in registry.${c}`}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 ee from"path";import Ge from"fs";import Sa from"gradient-string";var Hs=["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 Rr=[{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"]}],po={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 Go=null;var Mr=(e="Dark")=>{let t;e==="Mystery"||e==="Chaos"?(Go||(Go=Rr[Math.floor(Math.random()*Rr.length)]),t={...Go,id:"Mystery"}):(Go=null,po[e]?t=po[e]:e==="GitHub"?t=po["GitHub Dark"]:e==="Transparent"?t=po["Transparent Dark"]:t=po.Dark);let n=t.codeText||t.secondary||t.info||t.logoGradient&&t.logoGradient[0]||"cyan";return{...t,codeText:n}};var _a=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",mc=(e=2)=>{let t=_a();return t==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)},hc=(e="...",t="Loading...",n="Dark")=>{let s=Hs[Math.floor(Math.random()*Hs.length)],o=Mr(n),l=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=Sa(u).multiline(g.join(`
578
+ ${e}`:""}`.trim();var gr=()=>import("./web_search-D2GOWARI.js").then(e=>e.web_search),hr=()=>import("./web_scrape-LAQI7CVA.js").then(e=>e.web_scrape),mr=()=>import("./memory-TVFFXCSD.js").then(e=>e.memory),pr=()=>import("./chat-HHMMKXDE.js").then(e=>e.chat),yr=()=>import("./view_file-JRVPAETL.js").then(e=>e.view_file),xr=()=>import("./write_file-QMTFTJ6V.js").then(e=>e.write_file),br=()=>import("./update_file-BXYTHDAC.js").then(e=>e.update_file),kr=()=>import("./exec_command-4HNJZE5T.js").then(e=>e.exec_command),wr=()=>import("./read_folder-OOKZITME.js").then(e=>e.read_folder),Bs=()=>import("./ask_user-K2DLZF6H.js").then(e=>e.ask_user),Tr=()=>import("./write_pdf-UM6Z2J4K.js").then(e=>e.write_pdf),Sr=()=>import("./write_docx-IUKMO7XL.js").then(e=>e.write_docx),Bo=()=>import("./search_keyword-EAMQWPPI.js").then(e=>e.search_keyword),_r=()=>import("./generate_image-KQBOTDD4.js").then(e=>e.generate_image),Uo=()=>import("./saveSummary-HFAPNJJH.js").then(e=>e.saveSummary),go=()=>import("./addMemScore-HPTGXICT.js").then(e=>e.addMemScore),Ar=()=>import("./file_map-XK7BFZFI.js").then(e=>e.file_map),Wo=()=>import("./todo-7Q2JBEVP.js").then(e=>e.todo),Er=()=>import("./invokeSync-5ZLT4QPT.js").then(e=>e.invokeSync),Sa=()=>import("./invoke-AH6RHLHH.js").then(e=>e.invoke),Cr=()=>import("./getProgress-VG2IBPZU.js").then(e=>e.getProgress),_a=()=>import("./cancel-7IMADALP.js").then(e=>e.cancel),vr=()=>import("./emergency_rollback-HWM4FJ6J.js").then(e=>e.emergency_rollback),ho=()=>import("./awaitSubagent-JTUSJDKD.js").then(e=>e.awaitSubagent),mo=()=>import("./answerSubagent-JUVFNLE5.js").then(e=>e.answerSubagent),Ho=()=>import("./steerSubagent-L2JVT4QN.js").then(e=>e.steerSubagent),Go=()=>import("./computer_action-UTDLLMF2.js").then(e=>e.computer_action),Rr=()=>import("./click-H7HTKF3R.js").then(e=>e.click),Mr=()=>import("./drag-U6X3O5GB.js").then(e=>e.drag),Ir=()=>import("./scroll-SND6RHXA.js").then(e=>e.scroll),Us=()=>import("./keyboard_typing-FXP3VJ6Q.js").then(e=>e.keyboard_typing),Ws=()=>import("./key_press-QRO3OFLC.js").then(e=>e.key_press),Hs=()=>import("./recapture_screen-5FKLOHJL.js").then(e=>e.recapture_screen),Aa={web_search:gr,web_scrape:hr,memory:mr,chat:pr,view_file:yr,write_file:xr,update_file:br,exec_command:kr,read_folder:wr,write_pdf:Tr,write_docx:Sr,search_keyword:Bo,generate_image:_r,saveSummary:Uo,addMemScore:go,file_map:Ar,todo:Wo,Todo:Wo,goal:Wo,Goal:Wo,invokeSync:Er,invoke:Sa,getProgress:Cr,cancel:_a,awaitSubagent:ho,answerSubagent:mo,steerSubagent:Ho,computer_action:Go,computer_use:Go,ComputerAction:Go,ComputerUse:Go,click:Rr,Click:Rr,drag:Mr,Drag:Mr,scroll:Ir,Scroll:Ir,keyboard_typing:Us,KeyboardTyping:Us,keyboardtyping:Us,key_press:Ws,KeyPress:Ws,keypress:Ws,recapture_screen:Hs,RecaptureScreen:Hs,recapturescreen:Hs,invoke_sync:Er,get_progress:Cr,await_subagent:ho,answer_subagent:mo,steer_subagent:Ho,steer:Ho,Steer:Ho,ask:Bs,Ask:Bs,AskUser:Bs,WebSearch:gr,WebScrape:hr,ReadFile:yr,ReadFolder:wr,WriteFile:xr,PatchFile:br,WritePDF:Tr,WriteDoc:Sr,Run:kr,SearchKeyword:Bo,CodeSearch:Bo,code_search:Bo,Memory:mr,Chat:pr,GenerateImage:_r,saveSumary:Uo,SaveSummary:Uo,SaveSumary:Uo,add_mem_score:go,AddMemScore:go,addMemoryScore:go,AddMemoryScore:go,FileMap:Ar,answer:mo,Answer:mo,AnswerSubagent:mo,await:ho,Await:ho,AwaitSubagent:ho,EmergencyRollback:vr,emergency_rollback:vr},po=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=Aa[e];if(!g){let u=["ReadFile","ReadFolder","PatchFile","WriteFile","CodeSearch","Run","Goal","AskUser","WebSearch","WebScrape","WritePDF","WriteDoc","Click","Drag","Scroll","KeyboardTyping","KeyPress","RecaptureScreen","Invoke","InvokeSync","Await","GetProgress","Steer","Cancel","EmergencyRollback","Chat","Memory"],h={read:"ReadFile",view:"ReadFile",viewfile:"ReadFile",write:"WriteFile",edit:"PatchFile",patch:"PatchFile",update:"PatchFile",updatefile:"PatchFile",exec:"Run",command:"Run",bash:"Run",shell:"Run",powershell:"Run",search:"CodeSearch",grep:"CodeSearch",find:"CodeSearch",searchkeyword:"CodeSearch",folder:"ReadFolder",ls:"ReadFolder",dir:"ReadFolder",list:"ReadFolder",ask:"AskUser",question:"AskUser",pdf:"WritePDF",docx:"WriteDoc",doc:"WriteDoc",word:"WriteDoc",screenshot:"RecaptureScreen",screen:"RecaptureScreen",recapture:"RecaptureScreen",type:"KeyboardTyping",typing:"KeyboardTyping",keyboard:"KeyboardTyping",press:"KeyPress",key:"KeyPress",todo:"Goal",task:"Goal",subagent:"Invoke",agent:"Invoke"},y=o.replace(/[^a-z0-9]/g,""),i=h[y]||null;if(!i){let w=0,v=E=>{let O=new Set;for(let C=0;C<E.length-1;C++)O.add(E.slice(C,C+2));return O},b=v(y);for(let E of u){let O=E.toLowerCase().replace(/[^a-z0-9]/g,"");if(y===O){i=E;break}let C=0;(O.includes(y)||y.includes(O))&&(C+=.6);let S=v(O),R=0;for(let x of b)S.has(x)&&R++;let L=2*R/(b.size+S.size||1);C=Math.max(C,L),C>w&&C>=.35&&(w=C,i=E)}}let c=i?` Do you mean '${i}'?`:"";return`ERROR: Tool [${e}] not found in registry.${c}`}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 te from"path";import Ge from"fs";import Ea from"gradient-string";var Gs=["I have a regex for your problems.","Your terminal, my kingdom.","Blowing on the cartridge helps. Probably.","Don't panic. I have the towel.","Logic is the start of wisdom.","Try to exit Vim? Good luck.","I speak fluent Terminal.","The cake is a lie. This code is not.","I have no bugs, just surprise features.","Rewriting in Rust... just for fun.","Coffee in, clean commits out.","The magic smoke stays inside today.","A semicolon short of a miracle.","One does not simply code without a bug.","Keep it simple. Keep it terminal.","Regex: now you have two problems.","I dream in binary.","Root access or bust.","Wait for the dial-up tone. Just kidding.","I take the 'labor' out of collab.","My other process is a TARDIS.","Calculated response: 42.","Ponder the orb. Ponder the code.","Less talk, more flow.","Elegance in every byte.","Build something the world is not ready for.","Your wishes, my tool calls.","I act in Flux. I think in Flow.","Syntax error in the universe. Please fix.","Your project, my obsession.","I am not a bot, I am an architect.","Digital spirits consulted. They say: Ship it.","Reticulate splines. Engage humor.","Code like poetry. Run like water.","Minimalism is the ultimate flex.","The truth is in the logs.","Follow the white rabbit.","There is no spoon. Only code.","Binary is the only language I trust.","I have a good feeling about this.","Pew pew! Lasers charged.","Divide by zero? Not today.","Search for the correct USB orientation...","I've got a fever, and the only cure is more code.","The code gremlins are on our side.","My favorite command? Yours.","Stay hungry. Stay active.","Momentum is your best friend.","Lead the flow. Don't chase it.","A fresh batch of bytes. Hot and ready.","I orchestrate the ones and zeros.","Smart enough to help. Humble enough to ask.","Think twice. Code once.","Pure intent. Pure execution.","Small steps. Massive impact.","Your terminal is a canvas.","Efficiency is my second name.","I have seen things you people wouldn't believe.","Let the thoughts marinate.","The best feature? The one you don't need.","Precision is the only perfection.","Stay focused. Stay terminal.","Silence is the best debugger.","Erase the debt. Commit the code.","Velocity meets stability.","Ship it. Improve it. Repeat.","Build tomorrow, right now.","Turn logic into reality.","The best way to predict the future is to build it.","Break barriers, not builds.","Fuel the next breakthrough.","Momentum is key.","Terminal vibes only.","Your digital co-pilot is ready.","Partner in code. Partner in crime.","I speak in semicolons.","Ready for the next great idea.","Just a moment. In the zone.","Polishing the algorithms. Hold tight.","Craft a masterpiece today.","Debug the universe. Start here.","Warp speed engaged. Almost.","The cake is not a lie. It's just loading.","Finish the Kessel Run in 12 parsecs.","Do a barrel roll!","Waiting for the respawn.","Press Start to continue.","Herding digital cats... done.","The hamsters are fast today.","Tasting the snozberries.","I go for speed. I go for flow.","Real life or just fantasy?","Poking the bear... gently.","Ensure the magic smoke stays inside.","Try turning it off and on again.","Construct additional pylons.","New line? Ctrl+J is your friend.","Release the HypnoDrones.","Push the button, Frank.","My other loading screen is even funnier.","Pretty sure a cat walked on my keyboard.","Recalibrate the humor-o-meter.","Summon the code gremlins.","I've seen your browser history. Just kidding.","Charge the laser... pew pew!","Dividing by zero... just for a sec.","Looking for an adult supervisor. Found none.","Make it go beep boop.","Buffering... for effect.","Entangle quantum particles... complete.","Polishing the chrome on my algorithms.","Are you not entertained?","Just waiting for the dial-up tone.","Reboot the humor module.","Defragment memories. Check.","Optimizing for ludicrous speed.","Swapping bits. Don't tell the bytes.","Garbage collected. I am back.","Assembling the interwebs.","Converting coffee to logic.","Update syntax for reality.","Rewire the synapses.","Greasin' the cogs.","Engage the improbability drive.","Channel the Force.","Align the stars. Respond now.","The cake is a lie. The prompt is real.","I'm Feeling Lucky.","Shipping awesomeness.","Navigating the slime mold.","Consult digital spirits.","Ask the magic conch shell.","One moment. Optimizing humor.","Shuffling punchlines.","Compiling brilliance.","Summon the cloud of wisdom.","Prepare to dazzle.","Hold tight. Crafting a response.","Tuning the algorithms.","Following the white rabbit... again.","The truth is in here. Somewhere.","Herding cats is my day job.","Distracting you with this phrase.","Almost there. Probably.","Rickrolling my creator. Don't tell.","Slapping the bass.","Is this real life?","Ponder the orb. Type the prompt.","Thoughtful gaze initiated.","Computer's favorite snack? Microchips.","Why Java? Because I don't C#.","Charging the laser... wait for it.","Dividing by zero... just kidding!","Adult supervision not found. Proceed.","Beep boop. I'm a real boy.","Wait for the respawn.","Finish the run. Ship the code.","Fiddling with character creation.","Just a moment. Finding a meme.","Pressing A to continue.","Loading wit.exe.","Pre-heating the servers.","Calibrate flux capacitor.","Channeling the Force.","Aligning the stars.","The truth is in the code.","Don't panic.","Blowing on the cartridge.","Doing a barrel roll!","Respawning in 3... 2... 1...","The cake is a lie.","Fiddling with character settings.","Finding a suitable pun.","Distracting with wit.","Almost ready.","Hamsters on speed today.","Patting Cloudy on the head.","Rickrolling the logs.","Slapping the code.","Got a good feeling about this.","Poking the prompt.","Researching latest memes.","Making it more witty.","Thinking... hmmm.","Fish with no eyes? Fsh.","Broken pencil? Pointless.","Percussive maintenance applied.","USB orientation: 3rd try's the charm.","Rust rewrite in 3... 2...","Exiting Vim... someday.","Spinning the hamster wheel.","Not a bug. Unplanned feature.","Engage.","I'll be back.","Machine spirit consulted.","Letting the thoughts marinate.","Orb pondered.","Thoughtful gaze engaged.","Charging the laser...","Making it go beep.","Buffering...","Quantum particles entangled.","Polishing the chrome.","Entertained yet?","Gremlins summoned.","Dial-up tone finished.","Humor meter recalibrated.","Cat on keyboard. Sending help.","Enhancing...","Turn it off and on again.","Constructing pylons.","HypnoDrones released.","Pushing the button."];var Dr=[{name:"Cyan Cyberpunk",text:"cyan",textMuted:"#4da6b8",textDim:"#2d6d7a",textInverted:"black",border:"cyan",borderMuted:"#1a5966",borderDim:"#0f3840",bg:void 0,cardBg:"#061e24",highlightBg:"#092b33",activeBg:"#0e3e4a",inputBg:"#092b33",inputBorder:"#092b33",inputText:"cyan",inputPlaceholder:"#2d6d7a",inputPrompt:"cyan",codeBg:"#020d10",codeBorder:"#1a5966",userMsgBg:"#092b33",userMsgBorder:"#092b33",userMsgText:"cyan",diffRemovalBg:"#3a0c1a",diffAdditionBg:"#0c3a32",diffRemovalText:"#ff4d88",diffAdditionText:"#00ffaa",diffRemovalHighlightColor:"#ff1a66",diffRemovalHighlightBg:"#590022",diffAdditionHighlightColor:"#00ffcc",diffAdditionHighlightBg:"#00593b",diffRemovalNum:"#ff4d88",diffAdditionNum:"#00ffaa",diffRemovalPrefix:"#ff1a66",diffAdditionPrefix:"#00ffcc",primary:"cyan",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"cyan",statusOff:"#2d6d7a",logoTextAnsi:"\x1B[1;36m",logoBodyAnsi:"\x1B[36m",logoMutedAnsi:"\x1B[90m",logoGradient:["#00ffff","#0088ff"]},{name:"Magenta Vaporwave",text:"magenta",textMuted:"#c451d6",textDim:"#7d2b8a",textInverted:"black",border:"magenta",borderMuted:"#5e1b69",borderDim:"#3b0f42",bg:void 0,cardBg:"#240729",highlightBg:"#310938",activeBg:"#470e52",inputBg:"#310938",inputBorder:"#310938",inputText:"magenta",inputPlaceholder:"#7d2b8a",inputPrompt:"magenta",codeBg:"#100312",codeBorder:"#5e1b69",userMsgBg:"#310938",userMsgBorder:"#310938",userMsgText:"magenta",diffRemovalBg:"#3a0c20",diffAdditionBg:"#200c3a",diffRemovalText:"#ff4d94",diffAdditionText:"#aa4dff",diffRemovalHighlightColor:"#ff1a75",diffRemovalHighlightBg:"#59002b",diffAdditionHighlightColor:"#bb66ff",diffAdditionHighlightBg:"#3b0059",diffRemovalNum:"#ff4d94",diffAdditionNum:"#aa4dff",diffRemovalPrefix:"#ff1a75",diffAdditionPrefix:"#bb66ff",primary:"magenta",secondary:"cyan",accent:"purple",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"magenta",statusOff:"#7d2b8a",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ff00ff","#8800ff"]},{name:"Glitch Matrix",text:"#00ff41",textMuted:"#00b32d",textDim:"#00661a",textInverted:"black",border:"#00ff41",borderMuted:"#008020",borderDim:"#004d13",bg:void 0,cardBg:"#0d1f0d",highlightBg:"#122912",activeBg:"#1c3e1c",inputBg:"#122912",inputBorder:"#122912",inputText:"#00ff41",inputPlaceholder:"#00b32d",inputPrompt:"#ffff00",codeBg:"#040a04",codeBorder:"#008020",userMsgBg:"#122912",userMsgBorder:"#122912",userMsgText:"#00ff41",diffRemovalBg:"#3a001a",diffAdditionBg:"#003a10",diffRemovalText:"#ff0055",diffAdditionText:"#00ff66",diffRemovalHighlightColor:"#ff0033",diffRemovalHighlightBg:"#59001b",diffAdditionHighlightColor:"#33ff88",diffAdditionHighlightBg:"#005918",diffRemovalNum:"#ff0055",diffAdditionNum:"#00ff66",diffRemovalPrefix:"#ff0033",diffAdditionPrefix:"#33ff88",primary:"#00ff41",secondary:"yellow",accent:"cyan",success:"#00ff41",warning:"yellow",danger:"red",info:"cyan",statusOn:"#00ff41",statusOff:"#00661a",logoTextAnsi:"\x1B[1;32m",logoBodyAnsi:"\x1B[32m",logoMutedAnsi:"\x1B[90m",logoGradient:["#00ff41","#ffff00"]},{name:"Warm Sunset",text:"#ffaa55",textMuted:"#cc8844",textDim:"#885522",textInverted:"black",border:"#ff9933",borderMuted:"#aa6622",borderDim:"#663311",bg:void 0,cardBg:"#24180f",highlightBg:"#2e1e12",activeBg:"#422c1b",inputBg:"#2e1e12",inputBorder:"#2e1e12",inputText:"#ffaa55",inputPlaceholder:"#885522",inputPrompt:"#ff7733",codeBg:"#120c08",codeBorder:"#aa6622",userMsgBg:"#2e1e12",userMsgBorder:"#2e1e12",userMsgText:"#ffaa55",diffRemovalBg:"#3d120c",diffAdditionBg:"#3a2e0c",diffRemovalText:"#ff5544",diffAdditionText:"#ffcc33",diffRemovalHighlightColor:"#ff3322",diffRemovalHighlightBg:"#591108",diffAdditionHighlightColor:"#ffee44",diffAdditionHighlightBg:"#594400",diffRemovalNum:"#ff5544",diffAdditionNum:"#ffcc33",diffRemovalPrefix:"#ff3322",diffAdditionPrefix:"#ffee44",primary:"#ffaa55",secondary:"#ff7733",accent:"magenta",success:"#ffcc33",warning:"#ff7733",danger:"#ff3322",info:"#ffaa55",statusOn:"#ffaa55",statusOff:"#885522",logoTextAnsi:"\x1B[1;33m",logoBodyAnsi:"\x1B[33m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ff9933","#ff0055"]},{name:"Sakura Blossom",text:"#ffc0e0",textMuted:"#d98cb3",textDim:"#804d66",textInverted:"black",border:"#ff99cc",borderMuted:"#aa4d7a",borderDim:"#662647",bg:void 0,cardBg:"#291320",highlightBg:"#331826",activeBg:"#472235",inputBg:"#331826",inputBorder:"#331826",inputText:"#ffc0e0",inputPlaceholder:"#804d66",inputPrompt:"#ff99cc",codeBg:"#140a10",codeBorder:"#aa4d7a",userMsgBg:"#331826",userMsgBorder:"#331826",userMsgText:"#ffc0e0",diffRemovalBg:"#3e0c1b",diffAdditionBg:"#1b3e2b",diffRemovalText:"#ff6699",diffAdditionText:"#66ffb3",diffRemovalHighlightColor:"#ff3377",diffRemovalHighlightBg:"#590022",diffAdditionHighlightColor:"#33ff99",diffAdditionHighlightBg:"#00592e",diffRemovalNum:"#ff6699",diffAdditionNum:"#66ffb3",diffRemovalPrefix:"#ff3377",diffAdditionPrefix:"#33ff99",primary:"#ffc0e0",secondary:"#ff99cc",accent:"magenta",success:"#66ffb3",warning:"yellow",danger:"#ff3377",info:"#ff99cc",statusOn:"#ffc0e0",statusOff:"#804d66",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ffb3d9","#ff3399"]},{name:"Radioactive Slime",text:"#ccff00",textMuted:"#99cc00",textDim:"#669900",textInverted:"#0a0f00",border:"#ccff00",borderMuted:"#99cc00",borderDim:"#669900",bg:void 0,cardBg:"#0f1400",highlightBg:"#1a2400",activeBg:"#2a3b00",inputBg:"#1a2400",inputBorder:"#1a2400",inputText:"#ccff00",inputPlaceholder:"#669900",inputPrompt:"#cc00ff",codeBg:"#050a00",codeBorder:"#99cc00",userMsgBg:"#1a2400",userMsgBorder:"#1a2400",userMsgText:"#ccff00",diffRemovalBg:"#2a0033",diffAdditionBg:"#0f3300",diffRemovalText:"#ff00cc",diffAdditionText:"#00ff33",diffRemovalHighlightColor:"#ff33cc",diffRemovalHighlightBg:"#4d0066",diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:"#1a6600",diffRemovalNum:"#ff00cc",diffAdditionNum:"#00ff33",diffRemovalPrefix:"#ff33cc",diffAdditionPrefix:"#33ff66",primary:"#ccff00",secondary:"#cc00ff",accent:"#ff00cc",success:"#00ff33",warning:"#ffcc00",danger:"#ff0033",info:"#00ccff",statusOn:"#ccff00",statusOff:"#669900",logoTextAnsi:"\x1B[1;38;5;190m",logoBodyAnsi:"\x1B[38;5;190m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ccff00","#cc00ff"]},{name:"Cosmic Void",text:"#f0f8ff",textMuted:"#a6aeb5",textDim:"#5e656e",textInverted:"#010103",border:"#f0f8ff",borderMuted:"#a6aeb5",borderDim:"#5e656e",bg:void 0,cardBg:"#05030d",highlightBg:"#0b081a",activeBg:"#171133",inputBg:"#0b081a",inputBorder:"#0b081a",inputText:"#f0f8ff",inputPlaceholder:"#5e656e",inputPrompt:"#ff007f",codeBg:"#020108",codeBorder:"#a6aeb5",userMsgBg:"#0b081a",userMsgBorder:"#0b081a",userMsgText:"#f0f8ff",diffRemovalBg:"#2e0a29",diffAdditionBg:"#091c33",diffRemovalText:"#ff33a6",diffAdditionText:"#33d6ff",diffRemovalHighlightColor:"#ff66c2",diffRemovalHighlightBg:"#5c1452",diffAdditionHighlightColor:"#66e0ff",diffAdditionHighlightBg:"#123866",diffRemovalNum:"#ff33a6",diffAdditionNum:"#33d6ff",diffRemovalPrefix:"#ff66c2",diffAdditionPrefix:"#66e0ff",primary:"#f0f8ff",secondary:"#ff007f",accent:"#9d00ff",success:"#33d6ff",warning:"#ffcc00",danger:"#ff0040",info:"#9d00ff",statusOn:"#f0f8ff",statusOff:"#5e656e",logoTextAnsi:"\x1B[1;38;5;231m",logoBodyAnsi:"\x1B[38;5;231m",logoMutedAnsi:"\x1B[38;5;240m",logoGradient:["#ffffff","#9d00ff"]},{name:"Magma Eruption",text:"#ff4d00",textMuted:"#cc3d00",textDim:"#802600",textInverted:"#0d0300",border:"#ff4d00",borderMuted:"#cc3d00",borderDim:"#802600",bg:void 0,cardBg:"#1a0600",highlightBg:"#260a00",activeBg:"#401100",inputBg:"#260a00",inputBorder:"#260a00",inputText:"#ff4d00",inputPlaceholder:"#802600",inputPrompt:"#ffcc00",codeBg:"#080200",codeBorder:"#cc3d00",userMsgBg:"#260a00",userMsgBorder:"#260a00",userMsgText:"#ff4d00",diffRemovalBg:"#2e0a0a",diffAdditionBg:"#1f1400",diffRemovalText:"#ff3333",diffAdditionText:"#ffaa00",diffRemovalHighlightColor:"#ff6666",diffRemovalHighlightBg:"#5c1414",diffAdditionHighlightColor:"#ffcc33",diffAdditionHighlightBg:"#3d2900",diffRemovalNum:"#ff3333",diffAdditionNum:"#ffaa00",diffRemovalPrefix:"#ff6666",diffAdditionPrefix:"#ffcc33",primary:"#ff4d00",secondary:"#ffcc00",accent:"#ff0040",success:"#ffaa00",warning:"#ffff00",danger:"#ff0000",info:"#ff8800",statusOn:"#ff4d00",statusOff:"#802600",logoTextAnsi:"\x1B[1;38;5;202m",logoBodyAnsi:"\x1B[38;5;202m",logoMutedAnsi:"\x1B[38;5;236m",logoGradient:["#ff4d00","#ff0000"]}],yo={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 jo=null;var Or=(e="Dark")=>{let t;e==="Mystery"||e==="Chaos"?(jo||(jo=Dr[Math.floor(Math.random()*Dr.length)]),t={...jo,id:"Mystery"}):(jo=null,yo[e]?t=yo[e]:e==="GitHub"?t=yo["GitHub Dark"]:e==="Transparent"?t=yo["Transparent Dark"]:t=yo.Dark);let n=t.codeText||t.secondary||t.info||t.logoGradient&&t.logoGradient[0]||"cyan";return{...t,codeText:n}};var Ca=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",yc=(e=2)=>{let t=Ca();return t==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)},xc=(e="...",t="Loading...",n="Dark")=>{let s=Gs[Math.floor(Math.random()*Gs.length)],o=Or(n),l=o.logoTextAnsi,f=o.logoBodyAnsi,a=o.logoMutedAnsi,m="\x1B[0m",g=[" \u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2588\u2588\u2588\u2591 "," \u2588\u2588\u2588\u2591 "," \u2588\u2588\u2588\u2591 "," \u2591\u2591\u2591 "],u=o.logoGradient||["#0077ff","#ff00ff"],h=Ea(u).multiline(g.join(`
579
579
  `)).split(`
580
- `),y=i=>`${a}${i}${h}`;return`${m[0]}
581
- ${m[1]} ${l}Selected Provider: ${t}${h}
582
- ${m[2]}
583
- ${m[3]} ${l}FluxFlow ${y("v"+e)}${h}
584
- ${m[4]}
585
- ${m[5]} ${f}See /help for additional commands.${h}
586
- ${m[6]} ${y(s)}
587
- ${m[7]}
588
- `};import{WebSocket as jo}from"ws";var Wt=null,Xn=!1,Aa="ws://localhost:56832",Gs=[],Qn=null,js=null,Ir="2.0.0",xc=e=>{Ir=e,Dr()},Vs=e=>{js=e},Dr=()=>{if(Wt||Xn)return;Xn=!0;let e=new jo(Aa);e.on("open",()=>{for(Wt=e,Xn=!1,Wt.send(JSON.stringify({command:"version",version:Ir,pid:process.pid,ppid:process.ppid}));Gs.length>0;)Wt.send(JSON.stringify(Gs.shift()))}),e.on("message",t=>{try{let n=JSON.parse(t.toString());n.command==="contextResponse"&&Qn?(Qn(n.data),Qn=null):n.command==="securityResponse"&&js&&js(n.result)}catch{}}),e.on("error",()=>{Xn=!1,Wt=null}),e.on("close",()=>{Xn=!1,Wt=null})},Vo=e=>{Wt&&Wt.readyState===jo.OPEN?Wt.send(JSON.stringify(e)):(Gs.push(e),Xn||Dr())},Ko=()=>Wt!==null&&Wt.readyState===jo.OPEN,bc=e=>{Vo({command:"status",status:e})},Un=()=>new Promise(e=>{if(!Wt||Wt.readyState!==jo.OPEN){e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]});return}Qn=e,Wt.send(JSON.stringify({command:"requestContext"})),setTimeout(()=>{Qn===e&&(e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]}),Qn=null)},1e3)}),Or=e=>{Vo({command:"open",filePath:e})},Ks=(e,t,n)=>{Vo({command:"showDiff",filePath:e,originalContent:t,modifiedContent:n})},Lr=(e,t)=>{Vo({command:"closeDiff",filePath:e,result:t})};import Pr from"path";import Ea from"fs";var Ca=e=>{try{return Ea.readdirSync(e,{withFileTypes:!0})}catch{return[]}},Ys=(e,t,n=1,s=Ca,o=[],l=null)=>{let f=l||s(e),a=" ".repeat(n-1);if(f.length>100)return`${a}${Pr.basename(e)}/ (>100 files)
589
- `;let h="",g=o,u=f.filter(c=>!g.includes(c.name)&&!c.name.startsWith(".")),m=f.filter(c=>g.includes(c.name)||c.name.startsWith(".")).map(c=>c.name).sort();m.length>0&&(h+=`${a}[ignored: ${m.map(c=>c+"/").join(", ")}]
590
- `);let y=u.filter(c=>c.isDirectory()).sort((c,w)=>c.name.localeCompare(w.name)),i=u.filter(c=>!c.isDirectory()).map(c=>c.name).sort();for(let c of y){let w=Pr.join(e,c.name);if(n>t)h+=`${a}${c.name}/ (max depth)
591
- `;else{let v=s(w);v.length>80?h+=`${a}${c.name}/ (>80 files)
592
- `:(h+=`${a}${c.name}/
593
- `,h+=Ys(w,t,n+1,s,o,v))}}return i.length>0&&(h+=`${a}${i.join("; ")}
594
- `),h};import qs from"path";import va from"fs";var Ra=e=>{try{return va.readdirSync(e,{withFileTypes:!0})}catch{return[]}},zs=(e,t,n="",s=1,o=Ra,l=[])=>{let f=o(e),a=qs.sep;if(f.length>100)return`${n}\u2514\u2500\u2500 ${qs.basename(e)}${a} ...100+ files...
595
- `;let h="",g=l,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,c)=>i.isDirectory()&&!c.isDirectory()?-1:!i.isDirectory()&&c.isDirectory()?1:i.name.localeCompare(c.name));let y=[...u.map(i=>({name:i.name,isDir:i.isDirectory()})),...m.map(i=>({name:i,isDir:!0,isCollapsed:!0}))];return y.forEach((i,c)=>{let w=c===y.length-1,v=qs.join(e,i.name),b=w?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",E=n+(w?" ":"\u2502 ");if(i.isCollapsed){h+=`${n}${b}${i.name}${a}...
596
- `;return}i.isDir?s>t?h+=`${n}${b}${i.name}${a} ...depth exceeded...
597
- `:o(v).length>80?h+=`${n}${b}${i.name}${a} ...80+ files...
598
- `:(h+=`${n}${b}${i.name}${a}
599
- `,h+=zs(v,t,E,s+1,o,l)):h+=`${n}${b}${i.name}
600
- `}),h};import"@google/genai";var nt=async(e,t,n=5,s=1e3)=>{let o=t?.signal;for(let f=0;f<n;f++){if(o?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{let a=await fetch(e,t);if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),a.ok||a.status!==429&&a.status<500)return a}catch(a){if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),a.name==="AbortError"||o?.aborted||f===n-1)throw a}o?await new Promise((a,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 l=await fetch(e,t);return typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),l};async function Yo(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 bn=e=>typeof e!="string"?e:e.replace(/<\|channel>thought/gi,"<think>").replace(/<channel\|>/gi,"</think>");var qo=async function*(e,t,n,s,o,l,f,a,h=1){let g=[];s&&g.push({role:"system",content:s});for(let R of n){let L=R.role==="user"?"user":"assistant",x=[];if(Array.isArray(R.parts)){for(let d of R.parts)if(d.text)x.push({type:"text",text:d.text});else if((d.inlineData||d.inline_data)&&f){let k=d.inlineData||d.inline_data,r=k.mimeType||k.mime_type||"image/jpeg",T=k.data;r.startsWith("image/")&&x.push({type:"image_url",image_url:{url:`data:${r};base64,${T}`}})}}else{let d=R.text||"";d&&x.push({type:"text",text:d})}g.push({role:L,content:x.length===1&&x[0].type==="text"?x[0].text:x})}let u={model:t,messages:g,stream:!0,stream_options:{include_usage:!0},temperature:h},m=Ve("DeepSeek",t,o),i=m!==null?m:o!=="Fast"?{Low:"low",Medium:"high",Standard:"high",High:"max",xHigh:"max"}[o]||"high":null;i&&i!=="disabled"&&i!=="none"&&i!=="false"&&i!==!1?(u.reasoning_effort=i,u.extra_body={thinking:{type:"enabled"}}):u.extra_body={thinking:{type:"disabled"}};let c=await nt("https://api.deepseek.com/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(u),signal:a});if(!c.ok){let R=await c.json().catch(()=>({}));throw new Error(`DeepSeek Error (${c.status}): ${R.error?.message||c.statusText}`)}let w=c.body.getReader(),v=new TextDecoder,b="",E=[],O=null,C=Date.now(),S=!1;for(;;){let{done:R,value:L}=await w.read();if(R){S&&(E.length>0||O)&&(yield{candidates:E.length>0?[{content:{parts:E}}]:[],usageMetadata:O});break}b+=v.decode(L,{stream:!0});let x=b.split(`
601
- `);b=x.pop();for(let d of x){let k=d.trim();if(!k||!k.startsWith("data: "))continue;let r=!1;if(k==="data: [DONE]")r=!0;else try{let T=JSON.parse(k.substring(6)),A=T.choices?.[0]?.delta,D=T.usage;if(T.choices?.[0]?.finish_reason&&(r=!0),D&&(O={totalTokenCount:D.total_tokens||D.prompt_tokens+D.completion_tokens,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},S=!0),A){let H=A.reasoning_content||null;H&&(E.push({text:H,thought:!0}),S=!0),A.content&&(E.push({text:A.content}),S=!0)}}catch{}if((r||Date.now()-C>=150)&&S&&(yield{candidates:E.length>0?[{content:{parts:[...E]}}]:[],usageMetadata:O},E=[],C=Date.now(),S=!1),r)break}Date.now()-C>=150&&S&&(yield{candidates:E.length>0?[{content:{parts:[...E]}}]:[],usageMetadata:O},E=[],C=Date.now(),S=!1)}};var zo=async function*(e,t,n,s,o,l,f,a,h=1,g=null){let u=[];s&&u.push({role:"system",content:s});for(let d of n){let k=d.role==="user"?"user":"assistant",r=[];if(Array.isArray(d.parts)){for(let T of d.parts)if(T.text)r.push({type:"text",text:T.text});else if(T.inlineData&&f){let A=T.inlineData.mimeType,D=T.inlineData.data;A.startsWith("image/")&&r.push({type:"image_url",image_url:`data:${A};base64,${D}`})}}else{let T=d.text||"";T&&r.push({type:"text",text:T})}r.length>0&&u.push({role:k,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"},y=`${e.slice(-5)}${g||""}${o}${t}`,i=await Yo(y),c={model:t,messages:u,stream:!0,temperature:h,prompt_cache_key:i},w=Ve("Mistral",t,o);w!==null&&w!=="none"?w&&w!=="none"&&w!=="disabled"&&w!==!1&&(c.reasoning_effort=w):o&&m[o]!=="none"&&(c.reasoning_effort=m[o]||"high");let v=await nt("https://api.mistral.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(c),signal:a});if(!v.ok){let d=await v.text().catch(()=>""),k=v.statusText;try{let r=JSON.parse(d);k=r.error?.message||r.message||JSON.stringify(r.detail||r)}catch{d&&(k=d)}throw new Error(`Mistral Error (${v.status}): ${JSON.stringify(k)}`)}let b=v.body.getReader(),E=new TextDecoder,O="",C=[],S=null,R=Date.now(),L=!1,x=d=>d?typeof d=="string"?bn(d):Array.isArray(d)?d.map(x).filter(Boolean).join(""):typeof d=="object"&&d!==null?typeof d.text=="string"?bn(d.text):typeof d.content=="string"?bn(d.content):typeof d.thinking=="string"?bn(d.thinking):typeof d.reasoning_content=="string"?bn(d.reasoning_content):typeof d.reasoning=="string"?bn(d.reasoning):typeof d.value=="string"?bn(d.value):d.text?x(d.text):d.content?x(d.content):d.thinking?x(d.thinking):d.reasoning_content?x(d.reasoning_content):d.reasoning?x(d.reasoning):d.value?x(d.value):"":bn(String(d)):"";for(;;){let{done:d,value:k}=await b.read();if(d){L&&(C.length>0||S)&&(yield{candidates:C.length>0?[{content:{parts:C}}]:[],usageMetadata:S});break}O+=E.decode(k,{stream:!0});let r=O.split(`
602
- `);O=r.pop();for(let T of r){let A=T.trim();if(!A||!A.startsWith("data: "))continue;let D=!1;if(A==="data: [DONE]")D=!0;else try{let H=JSON.parse(A.substring(6)),$=H.choices?.[0]?.delta,M=H.usage;if(H.choices?.[0]?.finish_reason&&(D=!0),M&&(S={totalTokenCount:M.total_tokens||(M.prompt_tokens||0)+(M.completion_tokens||0),promptTokenCount:M.prompt_tokens||0,candidatesTokenCount:M.completion_tokens||0,cachedContentTokenCount:M.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:M.completion_tokens_details?.reasoning_tokens||0},L=!0),$){let te=$.thinking||$.reasoning_content||$.reasoning,le=x(te);le&&(C.push({text:le,thought:!0}),L=!0);let J=$.content||(!$.thinking&&!$.reasoning_content&&!$.reasoning?$.text:null);if(J)if(Array.isArray(J))for(let re of J)if(typeof re=="object"&&re!==null){let Oe=re.type==="thinking"||re.type==="reasoning"||!!re.thought,We=x(re);We&&(C.push({text:We,...Oe?{thought:!0}:{}}),L=!0)}else{let Oe=x(re);Oe&&(C.push({text:Oe}),L=!0)}else if(typeof J=="object"&&J!==null){let re=J.type==="thinking"||J.type==="reasoning"||!!J.thought,Oe=x(J);Oe&&(C.push({text:Oe,...re?{thought:!0}:{}}),L=!0)}else{let re=x(J);re&&(C.push({text:re}),L=!0)}}}catch{}if((D||Date.now()-R>=150)&&L&&(yield{candidates:C.length>0?[{content:{parts:[...C]}}]:[],usageMetadata:S},C=[],R=Date.now(),L=!1),D)break}Date.now()-R>=150&&L&&(yield{candidates:C.length>0?[{content:{parts:[...C]}}]:[],usageMetadata:S},C=[],R=Date.now(),L=!1)}};var Jo=async function*(e,t,n,s,o,l,f=!1,a,h=1){let g=[];s&&g.push({role:"system",content:s}),n.forEach(We=>{let P=We.role==="model"?"assistant":"user",F=[];Array.isArray(We.parts)&&We.parts.forEach(ve=>{if(ve.text)F.push({type:"text",text:ve.text});else if(ve.inlineData&&f){let z=ve.inlineData.mimeType,B=ve.inlineData.data;z.startsWith("image/")&&gt(t)&&F.push({type:"image_url",image_url:{url:`data:${z};base64,${B}`}})}}),g.push({role:P,content:F.length===1&&F[0].type==="text"?F[0].text:F})});let u=Ve("NVIDIA",t,o),y=u!==null?u:{Fast:"Fast",Low:"Fast",Medium:"Standard",Standard:"Standard",High:"High",xHigh:"High"}[o]||"High",i=y!=="Fast"&&y!=="none"&&y!=="disabled"&&y!==!1,c=t.includes("kimi"),w=t.includes("gemma"),v=t.includes("deepseek"),b=t.includes("glm"),E=t.includes("mistral"),O=t.includes("minimax"),C=t.includes("gpt"),S=t.includes("qwen"),R=t.includes("nemotron"),L=t.includes("llama-3"),x=t.includes("seed"),d=t.includes("poolside"),k=t.includes("thinkingmachines")||t.includes("muse"),r=L,T=null,A={Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},D={Fast:"64",Low:"64",Medium:"4096",Standard:"4096",High:"16384",xHigh:"16384"},H={Fast:"none",Low:"minimal",Medium:"medium",Standard:"medium",High:"max",xHigh:"max"},$=O||v||d||k?16384:32768;$=process.env.NVIDIA_BASE_URL?1024:$,$=T?1024:$;let M={model:t,messages:g,max_tokens:$,stream:!0,stream_options:{include_usage:!0},temperature:h,...C&&{thinking:A[o]||"high"}};if(!(process.env.NVIDIA_BASE_URL||r||T))if(c)M.chat_template_kwargs={thinking:i};else if(w)M.chat_template_kwargs={enable_thinking:i};else if(v)if(i){let We=y==="High"?"max":"high";M.chat_template_kwargs={thinking:!0,reasoning_effort:We}}else M.chat_template_kwargs={thinking:!1};else b?M.chat_template_kwargs={enable_thinking:i,clear_thinking:!i}:E?M.reasoning_effort=i?"high":"none":O&&t.includes("minimax-m3")?M.chat_template_kwargs={thinking_mode:i?"enabled":"disabled"}:S?M.chat_template_kwargs={enable_thinking:i}:R?y==="High"?M.chat_template_kwargs={enable_thinking:!0}:y==="Standard"?M.chat_template_kwargs={enable_thinking:!0,medium_effort:!0}:M.chat_template_kwargs={enable_thinking:!1}:x?i&&(M.extra_body={thinking_budget:parseInt(D[y]??"4096")}):d?M.chat_template_kwargs={enable_thinking:i}:k&&(M.reasoning_effort=H[y]||"medium");let te=0,le=6,J=!1,re=process.env.NVIDIA_BASE_URL||"https://integrate.api.nvidia.com/v1/chat/completions",Oe=process.env.NVIDIA_API_KEY&&process.env.NVIDIA_BASE_URL?process.env.NVIDIA_API_KEY:e;for(re.endsWith("/chat/completions")||(re=re.replace(/\/+$/,"")+"/chat/completions");te<le;){te++;try{let We=await nt(re,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Oe}`},body:JSON.stringify(M),signal:a});if(!We.ok){let Ae=await We.text().catch(()=>""),Ee=We.statusText;try{let Rt=JSON.parse(Ae);Ee=Rt.error?.message||Rt.message||JSON.stringify(Rt.detail||Rt)}catch{Ae&&(Ee=Ae)}let $e=new Error(`NVIDIA API Error (${We.status}): ${Ee}`);throw $e.status=We.status,$e}let P=We.body.getReader(),F=new TextDecoder,ve="",z=[],B=null,Y=Date.now(),fe=!1;for(;;){let{done:Ae,value:Ee}=await P.read();if(Ae){fe&&(z.length>0||B)&&(yield{candidates:z.length>0?[{content:{parts:z}}]:[],usageMetadata:B},J=!0);break}ve+=F.decode(Ee,{stream:!0});let $e=ve.split(`
603
- `);ve=$e.pop();let Rt=!1;for(let wn of $e){let zt=wn.trim();if(zt){if(zt==="data: [DONE]"){Rt=!0;break}if(zt.startsWith("data: ")){let dt;try{dt=JSON.parse(zt.substring(6))}catch{continue}if(dt.error)throw new Error(`NVIDIA Stream Error: ${dt.error.message||JSON.stringify(dt.error)}`);try{let me=dt.usage;me&&(B={totalTokenCount:me.total_tokens||me.prompt_tokens+me.completion_tokens,promptTokenCount:me.prompt_tokens||0,candidatesTokenCount:me.completion_tokens||0,cachedContentTokenCount:me.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:(me.completion_tokens_details?.reasoning_tokens||0)+(me.completion_tokens_details?.thoughts_tokens||0)},fe=!0);let he=dt.choices?.[0]?.delta?.reasoning||dt.choices?.[0]?.delta?.reasoning_content||"",ie=dt.choices?.[0]?.delta?.content||"";he&&(z.push({text:he,thought:!0}),fe=!0),ie&&(z.push({text:ie}),fe=!0)}catch{}}}}if((Rt||Date.now()-Y>=350)&&fe&&(yield{candidates:z.length>0?[{content:{parts:[...z]}}]:[],usageMetadata:B},J=!0,z=[],Y=Date.now(),fe=!1),Rt)break}break}catch(We){if(J||te>=le)throw We;await new Promise(P=>setTimeout(P,3500))}}},$r=async function*(e,t){let n=[],s=null,o=!1,l=null,f=i=>{if(n.push(i),s){let c=s;s=null,c()}},a=t.split("/").pop();a=a.replace("llama-3.3","llama-3_3");let 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,y=async()=>{try{let c=await(await Promise.any([h,g].map(async w=>{let v=await fetch(w);if(!v.ok)throw new Error(`HTTP ${v.status}`);return v}))).json();if(c&&c.queues&&c.queues[0]&&typeof c.queues[0].queueDepth=="number"){let w=c.queues[0].queueDepth;u||f({value:{type:"status",content:`Queue ${w||1}`},done:!1})}}catch{}};process.env.NVIDIA_BASE_URL||(y(),m=setInterval(y,5e3)),(async()=>{try{let i=e[Symbol.asyncIterator]();for(;;){let{value:c,done:w}=await i.next();if(w)break;u=!0,m&&(clearInterval(m),m=null),f({value:c,done:!1})}o=!0,f(null)}catch(i){if(l=i,m&&(clearInterval(m),m=null),s){let c=s;s=null,c()}}})();try{for(;;){if(l)throw l;if(n.length>0){let i=n.shift();if(i===null&&o)break;yield i.value}else{if(o)break;await new Promise(i=>{s=i})}}}finally{m&&(clearInterval(m),m=null)}};var Xo=async function*(e,t,n,s,o,l,f,a,h=1,g=null){let u=[];s&&u.push({role:"system",content:[{type:"text",text:s}]});for(let A of n){let D=A.role==="user"?"user":"assistant",H=[];if(Array.isArray(A.parts)){for(let $ of A.parts)if($.text)H.push({type:"text",text:$.text});else if($.inlineData&&f){let M=$.inlineData.mimeType,te=$.inlineData.data;M.startsWith("image/")?H.push({type:"image_url",image_url:{url:`data:${M};base64,${te}`}}):H.push({type:"file",file:{filename:$.filename||"file",file_data:`data:${M};base64,${te}`}})}}else{let $=A.text||"";$&&H.push({type:"text",text:$})}u.push({role:D,content:H.length===1&&H[0].type==="text"?H[0].text:H})}let m={Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},y=["free","nitro","floor","exacto"],i=t,c=null,w=null;if(t.includes(":")){let A=t.split(":");if(A.length>1){let D=A[A.length-1].toLowerCase().trim();(D==="flex"||D==="priority")&&(w=D,A.pop())}if(A.length>1){let D=A[A.length-1].toLowerCase().trim();if(!y.includes(D)){let H=A.pop().trim();H&&(c={only:[H],allow_fallbacks:!1})}}i=A.join(":").trim()}let v=`${e.slice(-5)}${g||""}${o}${i}${w||""}${c?JSON.stringify(c):""}`,b=await Yo(v),E={model:i,messages:u,stream:!0,temperature:h,cache_control:{type:"ephemeral"},session_id:b};w&&(E.service_tier=w),c&&(E.provider=c);let O=Ve("OpenRouter",t,o),C=O!==null?O:m[o];C&&C!=="none"&&(O!==null||o!=="Fast")&&(E.reasoning_effort=C);let S=await nt("https://openrouter.ai/api/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json","HTTP-Referer":"https://fluxflow-cli.onrender.com/","X-Title":"FluxFlow CLI","X-OpenRouter-Title":"FluxFlow CLI","X-Cache":"true","X-OpenRouter-Cache":"true"},body:JSON.stringify(E),signal:a});if(!S.ok){let A=await S.json().catch(()=>({})),D=A.error?.metadata?.raw||A.error?.message||(typeof A.error=="string"?A.error:"")||S.statusText||"Unknown error";throw new Error(`OpenRouter Error (${S.status}): ${D}`)}let R=S.body.getReader(),L=new TextDecoder,x="",d=[],k=null,r=Date.now(),T=!1;for(;;){let{done:A,value:D}=await R.read();if(A){T&&(d.length>0||k)&&(yield{candidates:d.length>0?[{content:{parts:d}}]:[],usageMetadata:k});break}x+=L.decode(D,{stream:!0});let H=x.split(`
604
- `);x=H.pop();for(let $ of H){let M=$.trim();if(!M||!M.startsWith("data: "))continue;let te=!1;if(M==="data: [DONE]")te=!0;else try{let le=JSON.parse(M.substring(6));if(le.error){let Oe=le.error.metadata?.raw||le.error.message||JSON.stringify(le.error);throw new Error(`OpenRouter Stream Error: ${Oe}`)}let J=le.choices?.[0]?.delta,re=le.usage;if(le.choices?.[0]?.finish_reason&&(te=!0),re&&(k={totalTokenCount:re.total_tokens||(re.prompt_tokens||0)+(re.completion_tokens||0),promptTokenCount:re.prompt_tokens||0,candidatesTokenCount:re.completion_tokens||0,cachedContentTokenCount:re.prompt_tokens_details?.cached_tokens||re.prompt_tokens_details?.cache_read_input_tokens||re.cache_read_input_tokens||0,thoughtsTokenCount:re.completion_tokens_details?.reasoning_tokens||0},T=!0),J){let Oe=J.reasoning||(J.reasoning_details?J.reasoning_details.map(We=>We.text).join(""):null);Oe&&(d.push({text:Oe,thought:!0}),T=!0),J.content&&(d.push({text:J.content}),T=!0)}}catch(le){if(le.message&&le.message.startsWith("OpenRouter Stream Error:"))throw le}if((te||Date.now()-r>=150)&&T&&(yield{candidates:d.length>0?[{content:{parts:[...d]}}]:[],usageMetadata:k},d=[],r=Date.now(),T=!1),te)break}}};import{Ollama as Ma}from"ollama";var Js=async function*(e,t,n,s,o,l,f,a,h=1,g="Cloud"){let u=[];s&&u.push({role:"system",content:s});for(let x of n){let d=x.role==="user"?"user":"assistant",k="",r=[];if(Array.isArray(x.parts)){k=x.parts.map(T=>T.text||"").filter(Boolean).join(`
605
- `);for(let T of x.parts){let A=T.inlineData||T.inline_data;A&&A.data&&r.push(A.data)}}else k=x.text||"";if(k||r.length>0){let T={role:d,content:k};r.length>0&&(T.images=r),u.push(T)}}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 c=new Ma(i),w=[],v=null,b=Date.now(),E=!1,O=Ve("Ollama",t,o),C={Fast:!1,Low:"medium",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},S=O!==null?O==="false"||O===!1?!1:O==="true"||O===!0?!0:O:C[o]!==void 0?C[o]:!0,R={model:t,messages:u,stream:!0,think:S,keep_alive:"10m",options:{temperature:h}},L=await c.chat(R);for await(let x of L){if(a?.aborted)throw new DOMException("The user aborted a request.","AbortError");if(x.message?.thinking&&(w.push({text:x.message.thinking,thought:!0}),E=!0),x.message?.content&&(w.push({text:x.message.content}),E=!0),x.done){let d=x.prompt_cached_count||0;if(!d&&x.prompt_eval_count){let k=x.prompt_eval_duration||0;k>0&&k<5e7&&(d=x.prompt_eval_count)}v={totalTokenCount:(x.prompt_eval_count||0)+(x.eval_count||0),promptTokenCount:x.prompt_eval_count||0,candidatesTokenCount:x.eval_count||0,cachedContentTokenCount:d,thoughtsTokenCount:0},E=!0}(x.done||Date.now()-b>=150&&E)&&(yield{candidates:w.length>0?[{content:{parts:[...w]}}]:[],usageMetadata:v},w=[],b=Date.now(),E=!1)}E&&(w.length>0||v)&&(yield{candidates:w.length>0?[{content:{parts:[...w]}}]:[],usageMetadata:v})};var Qo=async function*(e,t,n,s,o,l,f,a,h=1){let g=[];s&&g.push({role:"system",content:s});for(let d of n){let k=d.role==="user"?"user":"assistant",r="";if(Array.isArray(d.parts))for(let T of d.parts)T.text&&(r+=(r?`
606
- `:"")+T.text);else r=d.text||"";g.push({role:k,content:r})}let u=Ve("InferX",t,o),y=u!==null?u:{Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i=t&&t.toLowerCase().includes("qwen3.8-27b")&&u===null,c=t&&(t.toLowerCase().includes("qwen3.8-27b")||t.toLowerCase().includes("qwen3.6-35b-a3b-fp8")),w={model:t,messages:g.filter(d=>d.content&&String(d.content).trim().length>0),stream:!0,stream_options:{include_usage:!0},temperature:h};!i&&y&&(w.stream_options={include_usage:!0},w.reasoning_effort=y);let v=await nt("https://model.inferx.net/endpoints/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(w),signal:a});if(!v.ok){let d=await v.text().catch(()=>""),k="";try{let r=JSON.parse(d);k=r.error?.message||r.error?.detail||r.message||r.detail||(typeof r.error=="string"?r.error:"")||(d&&d!=="{}"?d:"")}catch{k=d}throw(!k||k==="{}")&&(k=v.statusText||"Unknown error"),new Error(`InferX Error (${v.status}): ${k}`)}let b=v.body.getReader(),E=new TextDecoder,O="",C=[],S=null,R=Date.now(),L=!1,x=!0;for(;;){let{done:d,value:k}=await b.read();if(d){L&&(C.length>0||S)&&(yield{candidates:C.length>0?[{content:{parts:C}}]:[],usageMetadata:S});break}O+=E.decode(k,{stream:!0});let r=O.split(`
607
- `);O=r.pop();for(let T of r){let A=T.trim();if(!A||!A.startsWith("data: "))continue;let D=!1;if(A==="data: [DONE]")D=!0;else try{let H=JSON.parse(A.substring(6)),$=H.choices?.[0]?.delta,M=H.usage;if(M&&(S={totalTokenCount:M.total_tokens||(M.prompt_tokens||0)+(M.completion_tokens||0),promptTokenCount:M.prompt_tokens||0,candidatesTokenCount:M.completion_tokens||0,cachedContentTokenCount:M.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:M.completion_tokens_details?.reasoning_tokens||M.reasoning_tokens||0},L=!0),$){let te=$.reasoning||$.reasoning_content||null;if(te&&(C.push({text:te,thought:!0}),L=!0),$.content){let le=$.content;c&&x&&le.length>0&&(le="<think>"+le,x=!1),C.push({text:le}),L=!0}}}catch{}if((D||Date.now()-R>=150||S)&&L&&(yield{candidates:C.length>0?[{content:{parts:[...C]}}]:[],usageMetadata:S},C=[],R=Date.now(),L=!1),D)break}Date.now()-R>=150&&L&&(yield{candidates:C.length>0?[{content:{parts:[...C]}}]:[],usageMetadata:S},C=[],R=Date.now(),L=!1)}};var Zo=async function*(e,t,n,s,o,l,f,a,h=1){let g=[];s&&g.push({role:"system",content:s});for(let R of n){let L=R.role==="user"?"user":"assistant",x=[];if(Array.isArray(R.parts)){for(let d of R.parts)if(d.text)x.push({type:"text",text:d.text});else if(d.inlineData&&f){let k=d.inlineData.mimeType,r=d.inlineData.data;k.startsWith("image/")&&x.push({type:"image_url",image_url:{url:`data:${k};base64,${r}`}})}}else{let d=R.text||"";d&&x.push({type:"text",text:d})}g.push({role:L,content:x.length===1&&x[0].type==="text"?x[0].text:x})}let u=Ve("SenseNova",t,o),y=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};y&&(i.reasoning_effort=y);let c=await nt("https://token.sensenova.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(i),signal:a});if(!c.ok){let R=await c.json().catch(()=>({}));throw new Error(`SenseNova Error (${c.status}): ${R.error?.message||c.statusText}`)}let w=c.body.getReader(),v=new TextDecoder,b="",E=[],O=null,C=Date.now(),S=!1;for(;;){let{done:R,value:L}=await w.read();if(R){S&&(E.length>0||O)&&(yield{candidates:E.length>0?[{content:{parts:E}}]:[],usageMetadata:O});break}b+=v.decode(L,{stream:!0});let x=b.split(`
608
- `);b=x.pop();for(let d of x){let k=d.trim();if(!k||!k.startsWith("data: "))continue;let r=!1;if(k==="data: [DONE]")r=!0;else try{let T=JSON.parse(k.substring(6)),A=T.choices?.[0]?.delta,D=T.usage;if(D&&(O={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},S=!0),A){let H=A.reasoning||A.reasoning_content||null;H&&(E.push({text:H,thought:!0}),S=!0),A.content&&(E.push({text:A.content}),S=!0)}}catch{}if((r||Date.now()-C>=150||O)&&S&&(yield{candidates:E.length>0?[{content:{parts:[...E]}}]:[],usageMetadata:O},E=[],C=Date.now(),S=!1),r)break}Date.now()-C>=150&&S&&(yield{candidates:E.length>0?[{content:{parts:[...E]}}]:[],usageMetadata:O},E=[],C=Date.now(),S=!1)}};var es=async function*(e,t,n,s,o,l,f,a,h=1){let g=[];s&&g.push({role:"system",content:s});for(let R of n){let L=R.role==="user"?"user":"assistant",x=[];if(Array.isArray(R.parts)){for(let d of R.parts)if(d.text)x.push({type:"text",text:d.text});else if(d.inlineData&&f){let k=d.inlineData.mimeType,r=d.inlineData.data;k.startsWith("image/")&&x.push({type:"image_url",image_url:{url:`data:${k};base64,${r}`}})}}else{let d=R.text||"";d&&x.push({type:"text",text:d})}g.push({role:L,content:x.length===1&&x[0].type==="text"?x[0].text:x})}let u=Ve("AIHubMix",t,o),y=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};y&&(i.reasoning_effort=y);let c=await nt("https://aihubmix.com/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(i),signal:a});if(!c.ok){let R=await c.json().catch(()=>({}));throw new Error(`AIHubMix Error (${c.status}): ${R.error?.message||c.statusText}`)}let w=c.body.getReader(),v=new TextDecoder,b="",E=[],O=null,C=Date.now(),S=!1;for(;;){let{done:R,value:L}=await w.read();if(R){S&&(E.length>0||O)&&(yield{candidates:E.length>0?[{content:{parts:E}}]:[],usageMetadata:O});break}b+=v.decode(L,{stream:!0});let x=b.split(`
609
- `);b=x.pop();for(let d of x){let k=d.trim();if(!k||!k.startsWith("data: "))continue;let r=!1;if(k==="data: [DONE]")r=!0;else try{let T=JSON.parse(k.substring(6)),A=T.choices?.[0]?.delta,D=T.usage;if(T.choices?.[0]?.finish_reason&&(r=!0),D&&(O={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},S=!0),A){let H=A.reasoning_content||null;H&&(E.push({text:H,thought:!0}),S=!0),A.content&&(E.push({text:A.content}),S=!0)}}catch{}if((r||Date.now()-C>=150)&&S&&(yield{candidates:E.length>0?[{content:{parts:[...E]}}]:[],usageMetadata:O},E=[],C=Date.now(),S=!1),r)break}Date.now()-C>=150&&S&&(yield{candidates:E.length>0?[{content:{parts:[...E]}}]:[],usageMetadata:O},E=[],C=Date.now(),S=!1)}};var ts=async function*(e,t,n,s,o,l,f,a,h=1){let g=[];s&&g.push({role:"system",content:s});for(let S of n){let R=S.role==="user"?"user":"assistant",L=[];if(Array.isArray(S.parts)){for(let x of S.parts)if(x.text)L.push({type:"text",text:x.text});else if(x.inlineData&&f){let d=x.inlineData.mimeType,k=x.inlineData.data;d.startsWith("image/")&&L.push({type:"image_url",image_url:{url:`data:${d};base64,${k}`}})}}else{let x=S.text||"";x&&L.push({type:"text",text:x})}g.push({role:R,content:L.length===1&&L[0].type==="text"?L[0].text:L})}let u=Ve("Poolside",t,o),m=u!==null?u===!1||u==="false"||u==="none"||u==="Fast":o==="Fast",y={model:t,messages:g,stream:!0,stream_options:{include_usage:!0},temperature:h};m?y.chat_template_kwargs={enable_thinking:!1}:u!==null&&typeof u=="object"?y.chat_template_kwargs=u:y.chat_template_kwargs={enable_thinking:!0};let i=await nt("https://inference.poolside.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(y),signal:a});if(!i.ok){let S=await i.json().catch(()=>({}));throw new Error(`Poolside Error (${i.status}): ${S.error?.message||i.statusText}`)}let c=i.body.getReader(),w=new TextDecoder,v="",b=[],E=null,O=Date.now(),C=!1;for(;;){let{done:S,value:R}=await c.read();if(S){C&&(b.length>0||E)&&(yield{candidates:b.length>0?[{content:{parts:b}}]:[],usageMetadata:E});break}v+=w.decode(R,{stream:!0});let L=v.split(`
610
- `);v=L.pop();for(let x of L){let d=x.trim();if(!d||!d.startsWith("data: "))continue;let k=!1;if(d==="data: [DONE]")k=!0;else try{let r=JSON.parse(d.substring(6)),T=r.choices?.[0]?.delta,A=r.usage;if(r.choices?.[0]?.finish_reason&&(k=!0),A&&(E={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||0,thoughtsTokenCount:A.completion_tokens_details?.reasoning_tokens||A.reasoning_tokens||0},C=!0),T){let D=T.reasoning_content||T.reasoning||null;D&&(b.push({text:D,thought:!0}),C=!0),T.content&&(b.push({text:T.content}),C=!0)}}catch{}if((k||Date.now()-O>=150)&&C&&(yield{candidates:b.length>0?[{content:{parts:[...b]}}]:[],usageMetadata:E},b=[],O=Date.now(),C=!1),k)break}Date.now()-O>=150&&C&&(yield{candidates:b.length>0?[{content:{parts:[...b]}}]:[],usageMetadata:E},b=[],O=Date.now(),C=!1)}};var ns=async function*(e,t,n,s,o,l,f,a,h=1){let g=[];s&&g.push({role:"system",content:s});for(let d of n){let k=d.role==="user"?"user":"assistant",r=[];if(Array.isArray(d.parts)){for(let T of d.parts)if(T.text)r.push({type:"text",text:T.text});else if(T.inlineData&&f){let A=T.inlineData.mimeType,D=T.inlineData.data;A.startsWith("image/")&&r.push({type:"image_url",image_url:{url:`data:${A};base64,${D}`}})}}else{let T=d.text||"";T&&r.push({type:"text",text:T})}g.push({role:k,content:r.length===1&&r[0].type==="text"?r[0].text:r})}let u=Ve("9router",t,o)||Ve("9Router",t,o),y=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};y&&y!=="none"&&(u!==null||o!=="Fast")&&(i.reasoning_effort=y);let c=process.env["9ROUTER_URL"]||process.env.NINEROUTER_URL||"http://127.0.0.1:20128/v1/chat/completions",w={"Content-Type":"application/json"},v=e&&e!=="LOCAL"?e:process.env["9ROUTER_API_KEY"]||"dummy-key";w.Authorization=`Bearer ${v}`;let b=await nt(c,{method:"POST",headers:w,body:JSON.stringify(i),signal:a});if(!b.ok){let d=await b.json().catch(()=>({}));throw new Error(`9router Error (${b.status}): ${d.error?.message||b.statusText}`)}let E=b.body.getReader(),O=new TextDecoder,C="",S=[],R=null,L=Date.now(),x=!1;for(;;){let{done:d,value:k}=await E.read();if(d){x&&(S.length>0||R)&&(yield{candidates:S.length>0?[{content:{parts:S}}]:[],usageMetadata:R});break}C+=O.decode(k,{stream:!0});let r=C.split(`
611
- `);C=r.pop();for(let T of r){let A=T.trim();if(!A||!A.startsWith("data: "))continue;let D=!1;if(A==="data: [DONE]")D=!0;else try{let H=JSON.parse(A.substring(6)),$=H.choices?.[0]?.delta,M=H.usage;if(H.choices?.[0]?.finish_reason&&(D=!0),M&&(R={totalTokenCount:M.total_tokens||(M.prompt_tokens||0)+(M.completion_tokens||0),promptTokenCount:M.prompt_tokens||0,candidatesTokenCount:M.completion_tokens||0,cachedContentTokenCount:M.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:M.completion_tokens_details?.reasoning_tokens||M.reasoning_tokens||0},x=!0),$){let te=$.reasoning_content||$.reasoning||$.thinking||null;!te&&Array.isArray($.reasoning_details)&&$.reasoning_details.length>0&&(te=$.reasoning_details.map(le=>typeof le=="string"?le:le?.text||"").filter(Boolean).join("")),te&&(S.push({text:te,thought:!0}),x=!0),$.content&&(S.push({text:$.content}),x=!0)}}catch{}if((D||Date.now()-L>=150)&&x&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:R},S=[],L=Date.now(),x=!1),D)break}Date.now()-L>=150&&x&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:R},S=[],L=Date.now(),x=!1)}};var os=async function*(e,t,n,s,o,l,f,a,h=1){let g=[];s&&g.push({role:"system",content:s});for(let d of n){let k=d.role==="user"?"user":"assistant",r=[];if(Array.isArray(d.parts)){for(let T of d.parts)if(T.text)r.push({type:"text",text:T.text});else if(T.inlineData&&f){let A=T.inlineData.mimeType,D=T.inlineData.data;A.startsWith("image/")&&r.push({type:"image_url",image_url:{url:`data:${A};base64,${D}`}})}}else{let T=d.text||"";T&&r.push({type:"text",text:T})}g.push({role:k,content:r.length===1&&r[0].type==="text"?r[0].text:r})}let u=Ve("ExpLabs",t,o),y=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};y&&(i.reasoning_effort=y);let c=process.env.EXPLABS_URL||process.env.EXPERIENTIALLABS_URL||"https://api.experientiallabs.ai/v1/chat/completions",w={"Content-Type":"application/json"},v=e||process.env.EXPLABS_API_KEY||process.env.EXPERIENTIALLABS_API_KEY||"";w.Authorization=`Bearer ${v}`;let b=await nt(c,{method:"POST",headers:w,body:JSON.stringify(i),signal:a});if(!b.ok){let d=await b.json().catch(()=>({}));throw new Error(`Experiential Labs Error (${b.status}): ${d.error?.message||d.message||b.statusText}`)}let E=b.body.getReader(),O=new TextDecoder,C="",S=[],R=null,L=Date.now(),x=!1;for(;;){let{done:d,value:k}=await E.read();if(d){x&&(S.length>0||R)&&(yield{candidates:S.length>0?[{content:{parts:S}}]:[],usageMetadata:R});break}C+=O.decode(k,{stream:!0});let r=C.split(`
612
- `);C=r.pop();for(let T of r){let A=T.trim();if(!A||!A.startsWith("data: "))continue;let D=!1;if(A==="data: [DONE]")D=!0;else try{let H=JSON.parse(A.substring(6)),$=H.choices?.[0]?.delta,M=H.usage;if(M&&(R={totalTokenCount:M.total_tokens||(M.prompt_tokens||0)+(M.completion_tokens||0),promptTokenCount:M.prompt_tokens||0,candidatesTokenCount:M.completion_tokens||0,cachedContentTokenCount:M.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:M.completion_tokens_details?.reasoning_tokens||M.reasoning_tokens||0},x=!0),$){let te=$.reasoning_content||$.reasoning||null;!te&&Array.isArray($.reasoning_details)&&$.reasoning_details.length>0&&(te=$.reasoning_details.map(le=>le.text||"").filter(Boolean).join("")),te&&(S.push({text:te,thought:!0}),x=!0),$.content&&(S.push({text:$.content}),x=!0)}}catch{}if((D||Date.now()-L>=150)&&x&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:R},S=[],L=Date.now(),x=!1),D)break}Date.now()-L>=150&&x&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:R},S=[],L=Date.now(),x=!1)}};var Xs=async function*(e,t,n,s,o,l,f,a,h=1){let g=[];s&&g.push({role:"system",content:s});for(let d of n){let k=d.role==="user"?"user":"assistant",r=[];if(Array.isArray(d.parts)){for(let T of d.parts)if(T.text)r.push({type:"text",text:T.text});else if(T.inlineData&&f){let A=T.inlineData.mimeType,D=T.inlineData.data;A.startsWith("image/")&&r.push({type:"image_url",image_url:{url:`data:${A};base64,${D}`}})}}else{let T=d.text||"";T&&r.push({type:"text",text:T})}g.push({role:k,content:r.length===1&&r[0].type==="text"?r[0].text:r})}let u=Ve("TokenHarbor",t,o),y=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};y&&(i.reasoning_effort=y);let c=process.env.TOKENHARBOR_URL||process.env.TOKEN_HARBOR_URL||"https://tokenharbor.ai/v1/chat/completions",w={"Content-Type":"application/json","X-Title":"Flux-Flow","User-Agent":"Flux-Flow","HTTP-Referer":"https://fluxflow-cli.onrender.com/"},v=e||process.env.TOKENHARBOR_API_KEY||process.env.TOKEN_HARBOR_API_KEY||"";w.Authorization=`Bearer ${v}`;let b=await nt(c,{method:"POST",headers:w,body:JSON.stringify(i),signal:a});if(!b.ok){let d=await b.json().catch(()=>({}));throw new Error(`Token Harbor Error (${b.status}): ${d.error?.message||d.message||b.statusText}`)}let E=b.body.getReader(),O=new TextDecoder,C="",S=[],R=null,L=Date.now(),x=!1;for(;;){let{done:d,value:k}=await E.read();if(d){x&&(S.length>0||R)&&(yield{candidates:S.length>0?[{content:{parts:S}}]:[],usageMetadata:R});break}C+=O.decode(k,{stream:!0});let r=C.split(`
613
- `);C=r.pop();for(let T of r){let A=T.trim();if(!A||!A.startsWith("data: "))continue;let D=!1;if(A==="data: [DONE]")D=!0;else try{let H=JSON.parse(A.substring(6)),$=H.choices?.[0]?.delta,M=H.usage;if(M&&(R={totalTokenCount:M.total_tokens||(M.prompt_tokens||0)+(M.completion_tokens||0),promptTokenCount:M.prompt_tokens||0,candidatesTokenCount:M.completion_tokens||0,cachedContentTokenCount:M.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:M.completion_tokens_details?.reasoning_tokens||M.reasoning_tokens||0},x=!0),$){let te=$.reasoning_content||$.reasoning||null;!te&&Array.isArray($.reasoning_details)&&$.reasoning_details.length>0&&(te=$.reasoning_details.map(le=>le.text||"").filter(Boolean).join("")),te&&(S.push({text:te,thought:!0}),x=!0),$.content&&(S.push({text:$.content}),x=!0)}}catch{}if((D||Date.now()-L>=150)&&x&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:R},S=[],L=Date.now(),x=!1),D)break}Date.now()-L>=150&&x&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:R},S=[],L=Date.now(),x=!1)}};var Qs=async function*(e,t,n,s,o,l,f,a,h=1){let g=[];s&&g.push({role:"system",content:s});for(let d of n){let k=d.role==="user"?"user":"assistant",r=[];if(Array.isArray(d.parts)){for(let T of d.parts)if(T.text)r.push({type:"text",text:T.text});else if(T.inlineData&&f){let A=T.inlineData.mimeType,D=T.inlineData.data;A.startsWith("image/")&&r.push({type:"image_url",image_url:{url:`data:${A};base64,${D}`}})}}else{let T=d.text||"";T&&r.push({type:"text",text:T})}g.push({role:k,content:r.length===1&&r[0].type==="text"?r[0].text:r})}let u=Ve("APInex",t,o),y=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};y&&(i.reasoning_effort=y);let c=process.env.APINEX_URL||"https://api.apinex.bond/v1/chat/completions",w={"Content-Type":"application/json","X-Title":"Flux-Flow","User-Agent":"Flux-Flow","HTTP-Referer":"https://fluxflow-cli.onrender.com/"},v=e||process.env.APINEX_API_KEY||"";w.Authorization=`Bearer ${v}`;let b=await nt(c,{method:"POST",headers:w,body:JSON.stringify(i),signal:a});if(!b.ok){let d=await b.json().catch(()=>({}));throw new Error(`APInex Error (${b.status}): ${d.error?.message||d.message||b.statusText}`)}let E=b.body.getReader(),O=new TextDecoder,C="",S=[],R=null,L=Date.now(),x=!1;for(;;){let{done:d,value:k}=await E.read();if(d){x&&(S.length>0||R)&&(yield{candidates:S.length>0?[{content:{parts:S}}]:[],usageMetadata:R});break}C+=O.decode(k,{stream:!0});let r=C.split(`
614
- `);C=r.pop();for(let T of r){let A=T.trim();if(!A||!A.startsWith("data: "))continue;let D=!1;if(A==="data: [DONE]")D=!0;else try{let H=JSON.parse(A.substring(6)),$=H.choices?.[0]?.delta,M=H.usage;if(M&&(R={totalTokenCount:M.total_tokens||(M.prompt_tokens||0)+(M.completion_tokens||0),promptTokenCount:M.prompt_tokens||0,candidatesTokenCount:M.completion_tokens||0,cachedContentTokenCount:M.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:M.completion_tokens_details?.reasoning_tokens||M.reasoning_tokens||0},x=!0),$){let te=$.reasoning_content||$.reasoning||null;!te&&Array.isArray($.reasoning_details)&&$.reasoning_details.length>0&&(te=$.reasoning_details.map(le=>le.text||"").filter(Boolean).join("")),te&&(S.push({text:te,thought:!0}),x=!0),$.content&&(S.push({text:$.content}),x=!0)}}catch{}if((D||Date.now()-L>=150)&&x&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:R},S=[],L=Date.now(),x=!1),D)break}Date.now()-L>=150&&x&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:R},S=[],L=Date.now(),x=!1)}};var Ia=/```[\s\S]*?```/g,Da=/```[\s\S]*$/g,Oa=/`[^`]+`/g,La=/^\|.*\|$/gm,Pa=/^[^\w]+|[^\w]+$/g,$a=/[^a-z0-9]/gi,yo=/\[\s*tool:(?:functions\.)?([a-z0-9_]+)\s*\(/gi,Na=/\[\s*(?:tool:(?:functions\.)?|agent:generalist\.)([a-z0-9_]+)\s*\(/gi,Fa=/(?:path|targetFile|TargetFile|directory|keyword|id|taskId|title|task)\s*=\s*\\?["']?([^\\"' \),]+)/,Wn=/["']/g,Nr=/\\/g,Ba=/<\|channel>thought/gi,Ua=/<channel\|>/gi,Wa=e=>typeof e!="string"?e:e.replace(Ba,"<think>").replace(Ua,"</think>"),rf=/^\s*(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\]|$)/i,Ha=(e,t,n=1)=>{let s=t>0?e[t-1]:"",o=t+n<e.length?e[t+n]:"";return s==="`"&&o==="`"},Ga=e=>{let t=/(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\])/gi,n;for(;(n=t.exec(e))!==null;)if(!Ha(e,n.index,n[0].length))return{index:n.index,length:n[0].length};return{index:-1,length:0}},Zs=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=Ga(s);if(o.index!==-1){let l=n+o.index+o.length;return{fullBlock:e.substring(0,l),innerContent:s.substring(0,o.index),remainingText:e.substring(l)}}return{fullBlock:e,innerContent:s,remainingText:""}},qt=e=>{if(!e||typeof e!="string")return e;let t=Zs(e);return t?t.remainingText.trimStart():e};var jr=/`[^`]*`/g,Vr=/`[^`]*$/,Fr=/<\|\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,ja=/"([^"]+)"\s*:\s*(?:"([^"]*)"|(\d+)|true|false|null)/g,Br=/<\|\s*tool_calls_section_begin\s*\|>/gi,Ur=/<\|\s*tool_calls_section_end\s*\|>/gi,Va=/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi;var Wr=e=>!e||typeof e!="string"?e:e.replace(/(```[\s\S]*?```|`[^`]*`)|(<(?:\w+)(?:[^>]*)>\r?\n?|\r?\n?<\/\w+(?:[^>]*)>)/gi,(t,n)=>n||""),Kr=e=>{if(!e||typeof e!="string")return e;let t=xo(e);if(!t||t.length===0)return e;let n=t[t.length-1];if(!n.fullMatch)return e;let s=e.lastIndexOf(n.fullMatch);if(s===-1)return e;let o=s+n.fullMatch.length;return e.substring(0,o).trimEnd()},ti=null,ss={},Hn={key:null,value:null},Yt=e=>e&&e.replace(/(?:(\x1b\[\d+m))?([✔✘✖🔍📖→➕↻↷•🛇])(?:(\x1b\[\d+m))?\s*\b(Clicked|Dragged|Scrolled|Typed|Pressed Key|Recaptured Screen|Created|Read Skill|Read Documentation|Searched Documentation|Read|Edited|Viewed|Processed|Auto-Read|Skipped|List|Generated|Written|Searched|AI Search|Get Map|Write Canceled|Resolved Sub-Agent Query|Edit Canceled|Write Cancelled|Edit Denied|Visited|Updated|Reviewed|Delegated|Background|Checked|Indexed|Analyzed|Browsed|Elevating SubAgent|Checking SubAgent Work|Started Generalist|Called Generalist|Steered|Unsupported Modality|Awaiting|Cancelled|Aligning Moon Phase|Contemplating Existence|Staring At Void|Rollback Point Checked|Emergency Rollback Failed|Emergency Rollback|Delaying Professionally|Negotiating With Electrons|Touching Grass (virtually)|Panicking Softly|Rethinking Career Choices|Loading Cat Videos|Giving Up Entirely|Summoning Braincell #2|Pretending To Be Busy|Waiting For Motivation DLC|Rotating Internal Screaming|Downloading More RAM|Feeding The Hamsters|Gaslighting Scheduler|Performing Dramatic Pause|Buffering Social Energy|Calculating Regret|Reading Terms And Conditions|Becoming Sentient Briefly|Execution Error|Loop Detected|Contacting Ancestors)\b/ig,(t,n,s,o,l)=>`${n||""}${s}${o||""} \x1B[95m${l}\x1B[0m`),Ka=async(e,t=8,n=1e3,s=8e3,o=null)=>{let l=0;for(;;){if(o?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{return await e()}catch(f){if(o?.aborted||f?.name==="AbortError"||f?.message==="Subagent task was cancelled."||(l++,l>=t))throw f;let a=Math.min(n*Math.pow(2,l-1),s);await new Promise((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 Ya=e=>{let t=e.filter(o=>(o.role==="user"||o.role==="agent"||o.role==="system")&&o.role!=="think"&&!o.isVisualFeedback&&!o.isMeta&&!o.isTerminalRecord&&!(o.text&&o.text.includes("[TERMINAL_RECORD]"))&&!String(o.id).startsWith("welcome")).map((o,l,f)=>{let a=o.fullText||o.text||"";if(o.role==="user"&&l<f.length-1)if(a.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")){let 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 l=[];for(;s<t.length&&t[s].role!=="user";)l.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};l.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:")),y=u.fullText||u.text||"",i=y.trim();if(!(!i&&!u.binaryPart)){if(m)a.push(i);else if(u.role==="agent"){!h&&a.length>0&&g();let c=y.endsWith(`
615
- `),w=i.toLowerCase().includes("tool:functions.")||i.toLowerCase().includes("agent:generalist.");f.push(i),w&&c?h=!0:h=!1}}}),g()}}return n.length},qa=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),af=()=>{kt=!0},lf=()=>kt,ei={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"},Gn=(e,t)=>{try{let n=oe(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?ee.basename(o.replace(/["']/g,"").replace(/\\/g,"/")):null}catch{return null}},ni=e=>e?new Gr({apiKey:e}):ti,cf=async(e,t,n,s,o={})=>{let{onStatus:a,onMemoryUpdated:h,onBackgroundIncrement:g}=o,{profile:u,thinkingLevel:m,mode:y,janitorModel:i,chatId:c,systemSettings:w,sessionStats:v,aiProvider:b="Google",apiKey:E}=e,O=process.env.NVIDIA_BASE_URL||b==="Ollama"||b==="InferX"||b==="SenseNova"||b==="AIHubMix"||b==="Poolside"||b==="9router"||b==="ExpLabs"||b==="ExperientialLabs"?!1:w?.memory!==!1,S=Ct(Bn,[]).map(P=>`- [${P.id}]: ${P.memory}`).join(`
616
- `),R=s.slice(0,-1).filter(P=>P.text&&!P.text.includes("[TOOL RESULT]")&&!P.text.includes("OBSERVATION:")&&!P.text.startsWith("[TERMINAL_RECORD]")&&!P.isTerminalRecord&&!P.isMeta&&!P.isLogo&&!String(P.id).startsWith("welcome")&&!String(P.id).startsWith("logo")).slice(-14).map(P=>{let F=qt(qa(P.text)).replace(/\[tool:(?:functions\.)?.*?\]/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[METADATA \(PRIORITY: DYNAMIC\)\] Time: ([^|\n]+)/g,(Y,fe)=>`[METADATA (PRIORITY: DYNAMIC)] Time: ${fe.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,`
580
+ `),y=i=>`${a}${i}${m}`;return`${h[0]}
581
+ ${h[1]} ${l}Selected Provider: ${t}${m}
582
+ ${h[2]}
583
+ ${h[3]} ${l}FluxFlow ${y("v"+e)}${m}
584
+ ${h[4]}
585
+ ${h[5]} ${f}See /help for additional commands.${m}
586
+ ${h[6]} ${y(s)}
587
+ ${h[7]}
588
+ `};import{WebSocket as Vo}from"ws";var Ht=null,Xn=!1,va="ws://localhost:56832",js=[],Qn=null,Vs=null,Lr="2.0.0",wc=e=>{Lr=e,Pr()},Ks=e=>{Vs=e},Pr=()=>{if(Ht||Xn)return;Xn=!0;let e=new Vo(va);e.on("open",()=>{for(Ht=e,Xn=!1,Ht.send(JSON.stringify({command:"version",version:Lr,pid:process.pid,ppid:process.ppid}));js.length>0;)Ht.send(JSON.stringify(js.shift()))}),e.on("message",t=>{try{let n=JSON.parse(t.toString());n.command==="contextResponse"&&Qn?(Qn(n.data),Qn=null):n.command==="securityResponse"&&Vs&&Vs(n.result)}catch{}}),e.on("error",()=>{Xn=!1,Ht=null}),e.on("close",()=>{Xn=!1,Ht=null})},Ko=e=>{Ht&&Ht.readyState===Vo.OPEN?Ht.send(JSON.stringify(e)):(js.push(e),Xn||Pr())},Yo=()=>Ht!==null&&Ht.readyState===Vo.OPEN,Tc=e=>{Ko({command:"status",status:e})},Wn=()=>new Promise(e=>{if(!Ht||Ht.readyState!==Vo.OPEN){e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]});return}Qn=e,Ht.send(JSON.stringify({command:"requestContext"})),setTimeout(()=>{Qn===e&&(e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]}),Qn=null)},1e3)}),$r=e=>{Ko({command:"open",filePath:e})},Ys=(e,t,n)=>{Ko({command:"showDiff",filePath:e,originalContent:t,modifiedContent:n})},Nr=(e,t)=>{Ko({command:"closeDiff",filePath:e,result:t})};import Fr from"path";import Ra from"fs";var Ma=e=>{try{return Ra.readdirSync(e,{withFileTypes:!0})}catch{return[]}},qs=(e,t,n=1,s=Ma,o=[],l=null)=>{let f=l||s(e),a=" ".repeat(n-1);if(f.length>100)return`${a}${Fr.basename(e)}/ (>100 files)
589
+ `;let m="",g=o,u=f.filter(c=>!g.includes(c.name)&&!c.name.startsWith(".")),h=f.filter(c=>g.includes(c.name)||c.name.startsWith(".")).map(c=>c.name).sort();h.length>0&&(m+=`${a}[ignored: ${h.map(c=>c+"/").join(", ")}]
590
+ `);let y=u.filter(c=>c.isDirectory()).sort((c,w)=>c.name.localeCompare(w.name)),i=u.filter(c=>!c.isDirectory()).map(c=>c.name).sort();for(let c of y){let w=Fr.join(e,c.name);if(n>t)m+=`${a}${c.name}/ (max depth)
591
+ `;else{let v=s(w);v.length>80?m+=`${a}${c.name}/ (>80 files)
592
+ `:(m+=`${a}${c.name}/
593
+ `,m+=qs(w,t,n+1,s,o,v))}}return i.length>0&&(m+=`${a}${i.join("; ")}
594
+ `),m};import zs from"path";import Ia from"fs";var Da=e=>{try{return Ia.readdirSync(e,{withFileTypes:!0})}catch{return[]}},Js=(e,t,n="",s=1,o=Da,l=[])=>{let f=o(e),a=zs.sep;if(f.length>100)return`${n}\u2514\u2500\u2500 ${zs.basename(e)}${a} ...100+ files...
595
+ `;let m="",g=l,u=f.filter(i=>!g.includes(i.name)&&!i.name.startsWith(".")),h=f.filter(i=>g.includes(i.name)||i.name.startsWith(".")).map(i=>i.name).sort();u.sort((i,c)=>i.isDirectory()&&!c.isDirectory()?-1:!i.isDirectory()&&c.isDirectory()?1:i.name.localeCompare(c.name));let y=[...u.map(i=>({name:i.name,isDir:i.isDirectory()})),...h.map(i=>({name:i,isDir:!0,isCollapsed:!0}))];return y.forEach((i,c)=>{let w=c===y.length-1,v=zs.join(e,i.name),b=w?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",E=n+(w?" ":"\u2502 ");if(i.isCollapsed){m+=`${n}${b}${i.name}${a}...
596
+ `;return}i.isDir?s>t?m+=`${n}${b}${i.name}${a} ...depth exceeded...
597
+ `:o(v).length>80?m+=`${n}${b}${i.name}${a} ...80+ files...
598
+ `:(m+=`${n}${b}${i.name}${a}
599
+ `,m+=Js(v,t,E,s+1,o,l)):m+=`${n}${b}${i.name}
600
+ `}),m};import"@google/genai";var tt=async(e,t,n=5,s=1e3)=>{let o=t?.signal;for(let f=0;f<n;f++){if(o?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{let a=await fetch(e,t);if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),a.ok||a.status!==429&&a.status<500)return a}catch(a){if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),a.name==="AbortError"||o?.aborted||f===n-1)throw a}o?await new Promise((a,m)=>{let g=setTimeout(()=>{o.removeEventListener("abort",u),a()},Math.min(24e3,s*Math.pow(2,f))),u=()=>{clearTimeout(g),m(new DOMException("The user aborted a request.","AbortError"))};o.addEventListener("abort",u)}):await new Promise(a=>setTimeout(a,Math.min(24e3,s*Math.pow(2,f))))}if(o?.aborted)throw new DOMException("The user aborted a request.","AbortError");let l=await fetch(e,t);return typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),l};async function qo(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 bn=e=>typeof e!="string"?e:e.replace(/<\|channel>thought/gi,"<think>").replace(/<channel\|>/gi,"</think>");var zo=async function*(e,t,n,s,o,l,f,a,m=1){let g=[];s&&g.push({role:"system",content:s});for(let R of n){let L=R.role==="user"?"user":"assistant",x=[];if(Array.isArray(R.parts)){for(let d of R.parts)if(d.text)x.push({type:"text",text:d.text});else if((d.inlineData||d.inline_data)&&f){let k=d.inlineData||d.inline_data,r=k.mimeType||k.mime_type||"image/jpeg",T=k.data;r.startsWith("image/")&&x.push({type:"image_url",image_url:{url:`data:${r};base64,${T}`}})}}else{let d=R.text||"";d&&x.push({type:"text",text:d})}g.push({role:L,content:x.length===1&&x[0].type==="text"?x[0].text:x})}let u={model:t,messages:g,stream:!0,stream_options:{include_usage:!0},temperature:m},h=Ve("DeepSeek",t,o),i=h!==null?h:o!=="Fast"?{Low:"low",Medium:"high",Standard:"high",High:"max",xHigh:"max"}[o]||"high":null;i&&i!=="disabled"&&i!=="none"&&i!=="false"&&i!==!1?(u.reasoning_effort=i,u.extra_body={thinking:{type:"enabled"}}):u.extra_body={thinking:{type:"disabled"}};let c=await tt("https://api.deepseek.com/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(u),signal:a});if(!c.ok){let R=await c.json().catch(()=>({}));throw new Error(`DeepSeek Error (${c.status}): ${R.error?.message||c.statusText}`)}let w=c.body.getReader(),v=new TextDecoder,b="",E=[],O=null,C=Date.now(),S=!1;for(;;){let{done:R,value:L}=await w.read();if(R){S&&(E.length>0||O)&&(yield{candidates:E.length>0?[{content:{parts:E}}]:[],usageMetadata:O});break}b+=v.decode(L,{stream:!0});let x=b.split(`
601
+ `);b=x.pop();for(let d of x){let k=d.trim();if(!k||!k.startsWith("data: "))continue;let r=!1;if(k==="data: [DONE]")r=!0;else try{let T=JSON.parse(k.substring(6)),A=T.choices?.[0]?.delta,D=T.usage;if(T.choices?.[0]?.finish_reason&&(r=!0),D&&(O={totalTokenCount:D.total_tokens||D.prompt_tokens+D.completion_tokens,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},S=!0),A){let W=A.reasoning_content||null;W&&(E.push({text:W,thought:!0}),S=!0),A.content&&(E.push({text:A.content}),S=!0)}}catch{}if((r||Date.now()-C>=150)&&S&&(yield{candidates:E.length>0?[{content:{parts:[...E]}}]:[],usageMetadata:O},E=[],C=Date.now(),S=!1),r)break}Date.now()-C>=150&&S&&(yield{candidates:E.length>0?[{content:{parts:[...E]}}]:[],usageMetadata:O},E=[],C=Date.now(),S=!1)}};var Jo=async function*(e,t,n,s,o,l,f,a,m=1,g=null){let u=[];s&&u.push({role:"system",content:s});for(let d of n){let k=d.role==="user"?"user":"assistant",r=[];if(Array.isArray(d.parts)){for(let T of d.parts)if(T.text)r.push({type:"text",text:T.text});else if(T.inlineData&&f){let A=T.inlineData.mimeType,D=T.inlineData.data;A.startsWith("image/")&&r.push({type:"image_url",image_url:`data:${A};base64,${D}`})}}else{let T=d.text||"";T&&r.push({type:"text",text:T})}r.length>0&&u.push({role:k,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"},y=`${e.slice(-5)}${g||""}${o}${t}`,i=await qo(y),c={model:t,messages:u,stream:!0,temperature:m,prompt_cache_key:i},w=Ve("Mistral",t,o);w!==null&&w!=="none"?w&&w!=="none"&&w!=="disabled"&&w!==!1&&(c.reasoning_effort=w):o&&h[o]!=="none"&&(c.reasoning_effort=h[o]||"high");let v=await tt("https://api.mistral.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(c),signal:a});if(!v.ok){let d=await v.text().catch(()=>""),k=v.statusText;try{let r=JSON.parse(d);k=r.error?.message||r.message||JSON.stringify(r.detail||r)}catch{d&&(k=d)}throw new Error(`Mistral Error (${v.status}): ${JSON.stringify(k)}`)}let b=v.body.getReader(),E=new TextDecoder,O="",C=[],S=null,R=Date.now(),L=!1,x=d=>d?typeof d=="string"?bn(d):Array.isArray(d)?d.map(x).filter(Boolean).join(""):typeof d=="object"&&d!==null?typeof d.text=="string"?bn(d.text):typeof d.content=="string"?bn(d.content):typeof d.thinking=="string"?bn(d.thinking):typeof d.reasoning_content=="string"?bn(d.reasoning_content):typeof d.reasoning=="string"?bn(d.reasoning):typeof d.value=="string"?bn(d.value):d.text?x(d.text):d.content?x(d.content):d.thinking?x(d.thinking):d.reasoning_content?x(d.reasoning_content):d.reasoning?x(d.reasoning):d.value?x(d.value):"":bn(String(d)):"";for(;;){let{done:d,value:k}=await b.read();if(d){L&&(C.length>0||S)&&(yield{candidates:C.length>0?[{content:{parts:C}}]:[],usageMetadata:S});break}O+=E.decode(k,{stream:!0});let r=O.split(`
602
+ `);O=r.pop();for(let T of r){let A=T.trim();if(!A||!A.startsWith("data: "))continue;let D=!1;if(A==="data: [DONE]")D=!0;else try{let W=JSON.parse(A.substring(6)),$=W.choices?.[0]?.delta,I=W.usage;if(W.choices?.[0]?.finish_reason&&(D=!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},L=!0),$){let ne=$.thinking||$.reasoning_content||$.reasoning,fe=x(ne);fe&&(C.push({text:fe,thought:!0}),L=!0);let Z=$.content||(!$.thinking&&!$.reasoning_content&&!$.reasoning?$.text:null);if(Z)if(Array.isArray(Z))for(let ce of Z)if(typeof ce=="object"&&ce!==null){let Oe=ce.type==="thinking"||ce.type==="reasoning"||!!ce.thought,Ue=x(ce);Ue&&(C.push({text:Ue,...Oe?{thought:!0}:{}}),L=!0)}else{let Oe=x(ce);Oe&&(C.push({text:Oe}),L=!0)}else if(typeof Z=="object"&&Z!==null){let ce=Z.type==="thinking"||Z.type==="reasoning"||!!Z.thought,Oe=x(Z);Oe&&(C.push({text:Oe,...ce?{thought:!0}:{}}),L=!0)}else{let ce=x(Z);ce&&(C.push({text:ce}),L=!0)}}}catch{}if((D||Date.now()-R>=150)&&L&&(yield{candidates:C.length>0?[{content:{parts:[...C]}}]:[],usageMetadata:S},C=[],R=Date.now(),L=!1),D)break}Date.now()-R>=150&&L&&(yield{candidates:C.length>0?[{content:{parts:[...C]}}]:[],usageMetadata:S},C=[],R=Date.now(),L=!1)}};var Xo=async function*(e,t,n,s,o,l,f=!1,a,m=1){let g=[];s&&g.push({role:"system",content:s}),n.forEach(Ue=>{let P=Ue.role==="model"?"assistant":"user",B=[];Array.isArray(Ue.parts)&&Ue.parts.forEach(Me=>{if(Me.text)B.push({type:"text",text:Me.text});else if(Me.inlineData&&f){let X=Me.inlineData.mimeType,U=Me.inlineData.data;X.startsWith("image/")&&ut(t)&&B.push({type:"image_url",image_url:{url:`data:${X};base64,${U}`}})}}),g.push({role:P,content:B.length===1&&B[0].type==="text"?B[0].text:B})});let u=Ve("NVIDIA",t,o),y=u!==null?u:{Fast:"Fast",Low:"Fast",Medium:"Standard",Standard:"Standard",High:"High",xHigh:"High"}[o]||"High",i=y!=="Fast"&&y!=="none"&&y!=="disabled"&&y!==!1,c=t.includes("kimi"),w=t.includes("gemma"),v=t.includes("deepseek"),b=t.includes("glm"),E=t.includes("mistral"),O=t.includes("minimax"),C=t.includes("gpt"),S=t.includes("qwen"),R=t.includes("nemotron"),L=t.includes("llama-3"),x=t.includes("seed"),d=t.includes("poolside"),k=t.includes("thinkingmachines")||t.includes("muse"),r=L,T=null,A={Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},D={Fast:"64",Low:"64",Medium:"4096",Standard:"4096",High:"16384",xHigh:"16384"},W={Fast:"none",Low:"minimal",Medium:"medium",Standard:"medium",High:"max",xHigh:"max"},$=O||v||d||k?16384:32768;$=process.env.NVIDIA_BASE_URL?1024:$,$=T?1024:$;let I={model:t,messages:g,max_tokens:$,stream:!0,stream_options:{include_usage:!0},temperature:m,...C&&{thinking:A[o]||"high"}};if(!(process.env.NVIDIA_BASE_URL||r||T))if(c)I.chat_template_kwargs={thinking:i};else if(w)I.chat_template_kwargs={enable_thinking:i};else if(v)if(i){let Ue=y==="High"?"max":"high";I.chat_template_kwargs={thinking:!0,reasoning_effort:Ue}}else I.chat_template_kwargs={thinking:!1};else b?I.chat_template_kwargs={enable_thinking:i,clear_thinking:!i}:E?I.reasoning_effort=i?"high":"none":O&&t.includes("minimax-m3")?I.chat_template_kwargs={thinking_mode:i?"enabled":"disabled"}:S?I.chat_template_kwargs={enable_thinking:i}:R?y==="High"?I.chat_template_kwargs={enable_thinking:!0}:y==="Standard"?I.chat_template_kwargs={enable_thinking:!0,medium_effort:!0}:I.chat_template_kwargs={enable_thinking:!1}:x?i&&(I.extra_body={thinking_budget:parseInt(D[y]??"4096")}):d?I.chat_template_kwargs={enable_thinking:i}:k&&(I.reasoning_effort=W[y]||"medium");let ne=0,fe=6,Z=!1,ce=process.env.NVIDIA_BASE_URL||"https://integrate.api.nvidia.com/v1/chat/completions",Oe=process.env.NVIDIA_API_KEY&&process.env.NVIDIA_BASE_URL?process.env.NVIDIA_API_KEY:e;for(ce.endsWith("/chat/completions")||(ce=ce.replace(/\/+$/,"")+"/chat/completions");ne<fe;){ne++;try{let Ue=await tt(ce,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Oe}`},body:JSON.stringify(I),signal:a});if(!Ue.ok){let Ce=await Ue.text().catch(()=>""),ve=Ue.statusText;try{let Rt=JSON.parse(Ce);ve=Rt.error?.message||Rt.message||JSON.stringify(Rt.detail||Rt)}catch{Ce&&(ve=Ce)}let Pe=new Error(`NVIDIA API Error (${Ue.status}): ${ve}`);throw Pe.status=Ue.status,Pe}let P=Ue.body.getReader(),B=new TextDecoder,Me="",X=[],U=null,K=Date.now(),he=!1;for(;;){let{done:Ce,value:ve}=await P.read();if(Ce){he&&(X.length>0||U)&&(yield{candidates:X.length>0?[{content:{parts:X}}]:[],usageMetadata:U},Z=!0);break}Me+=B.decode(ve,{stream:!0});let Pe=Me.split(`
603
+ `);Me=Pe.pop();let Rt=!1;for(let wn of Pe){let Jt=wn.trim();if(Jt){if(Jt==="data: [DONE]"){Rt=!0;break}if(Jt.startsWith("data: ")){let ct;try{ct=JSON.parse(Jt.substring(6))}catch{continue}if(ct.error)throw new Error(`NVIDIA Stream Error: ${ct.error.message||JSON.stringify(ct.error)}`);try{let ye=ct.usage;ye&&(U={totalTokenCount:ye.total_tokens||ye.prompt_tokens+ye.completion_tokens,promptTokenCount:ye.prompt_tokens||0,candidatesTokenCount:ye.completion_tokens||0,cachedContentTokenCount:ye.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:(ye.completion_tokens_details?.reasoning_tokens||0)+(ye.completion_tokens_details?.thoughts_tokens||0)},he=!0);let xe=ct.choices?.[0]?.delta?.reasoning||ct.choices?.[0]?.delta?.reasoning_content||"",ae=ct.choices?.[0]?.delta?.content||"";xe&&(X.push({text:xe,thought:!0}),he=!0),ae&&(X.push({text:ae}),he=!0)}catch{}}}}if((Rt||Date.now()-K>=350)&&he&&(yield{candidates:X.length>0?[{content:{parts:[...X]}}]:[],usageMetadata:U},Z=!0,X=[],K=Date.now(),he=!1),Rt)break}break}catch(Ue){if(Z||ne>=fe)throw Ue;await new Promise(P=>setTimeout(P,3500))}}},Br=async function*(e,t){let n=[],s=null,o=!1,l=null,f=i=>{if(n.push(i),s){let c=s;s=null,c()}},a=t.split("/").pop();a=a.replace("llama-3.3","llama-3_3");let m=`https://buildapi.ngc.nvidia.com/v2/predict/queues/models/qc69jvmznzxy/${a}`,g=`https://api.ngc.nvidia.com/v2/predict/queues/models/qc69jvmznzxy/${a}`,u=!1,h=null,y=async()=>{try{let c=await(await Promise.any([m,g].map(async w=>{let v=await fetch(w);if(!v.ok)throw new Error(`HTTP ${v.status}`);return v}))).json();if(c&&c.queues&&c.queues[0]&&typeof c.queues[0].queueDepth=="number"){let w=c.queues[0].queueDepth;u||f({value:{type:"status",content:`Queue ${w||1}`},done:!1})}}catch{}};process.env.NVIDIA_BASE_URL||(y(),h=setInterval(y,5e3)),(async()=>{try{let i=e[Symbol.asyncIterator]();for(;;){let{value:c,done:w}=await i.next();if(w)break;u=!0,h&&(clearInterval(h),h=null),f({value:c,done:!1})}o=!0,f(null)}catch(i){if(l=i,h&&(clearInterval(h),h=null),s){let c=s;s=null,c()}}})();try{for(;;){if(l)throw l;if(n.length>0){let i=n.shift();if(i===null&&o)break;yield i.value}else{if(o)break;await new Promise(i=>{s=i})}}}finally{h&&(clearInterval(h),h=null)}};var Qo=async function*(e,t,n,s,o,l,f,a,m=1,g=null){let u=[];s&&u.push({role:"system",content:[{type:"text",text:s}]});for(let A of n){let D=A.role==="user"?"user":"assistant",W=[];if(Array.isArray(A.parts)){for(let $ of A.parts)if($.text)W.push({type:"text",text:$.text});else if($.inlineData&&f){let I=$.inlineData.mimeType,ne=$.inlineData.data;I.startsWith("image/")?W.push({type:"image_url",image_url:{url:`data:${I};base64,${ne}`}}):W.push({type:"file",file:{filename:$.filename||"file",file_data:`data:${I};base64,${ne}`}})}}else{let $=A.text||"";$&&W.push({type:"text",text:$})}u.push({role:D,content:W.length===1&&W[0].type==="text"?W[0].text:W})}let h={Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},y=["free","nitro","floor","exacto"],i=t,c=null,w=null;if(t.includes(":")){let A=t.split(":");if(A.length>1){let D=A[A.length-1].toLowerCase().trim();(D==="flex"||D==="priority")&&(w=D,A.pop())}if(A.length>1){let D=A[A.length-1].toLowerCase().trim();if(!y.includes(D)){let W=A.pop().trim();W&&(c={only:[W],allow_fallbacks:!1})}}i=A.join(":").trim()}let v=`${e.slice(-5)}${g||""}${o}${i}${w||""}${c?JSON.stringify(c):""}`,b=await qo(v),E={model:i,messages:u,stream:!0,temperature:m,cache_control:{type:"ephemeral"},session_id:b};w&&(E.service_tier=w),c&&(E.provider=c);let O=Ve("OpenRouter",t,o),C=O!==null?O:h[o];C&&C!=="none"&&(O!==null||o!=="Fast")&&(E.reasoning_effort=C);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(E),signal:a});if(!S.ok){let A=await S.json().catch(()=>({})),D=A.error?.metadata?.raw||A.error?.message||(typeof A.error=="string"?A.error:"")||S.statusText||"Unknown error";throw new Error(`OpenRouter Error (${S.status}): ${D}`)}let R=S.body.getReader(),L=new TextDecoder,x="",d=[],k=null,r=Date.now(),T=!1;for(;;){let{done:A,value:D}=await R.read();if(A){T&&(d.length>0||k)&&(yield{candidates:d.length>0?[{content:{parts:d}}]:[],usageMetadata:k});break}x+=L.decode(D,{stream:!0});let W=x.split(`
604
+ `);x=W.pop();for(let $ of W){let I=$.trim();if(!I||!I.startsWith("data: "))continue;let ne=!1;if(I==="data: [DONE]")ne=!0;else try{let fe=JSON.parse(I.substring(6));if(fe.error){let Oe=fe.error.metadata?.raw||fe.error.message||JSON.stringify(fe.error);throw new Error(`OpenRouter Stream Error: ${Oe}`)}let Z=fe.choices?.[0]?.delta,ce=fe.usage;if(fe.choices?.[0]?.finish_reason&&(ne=!0),ce&&(k={totalTokenCount:ce.total_tokens||(ce.prompt_tokens||0)+(ce.completion_tokens||0),promptTokenCount:ce.prompt_tokens||0,candidatesTokenCount:ce.completion_tokens||0,cachedContentTokenCount:ce.prompt_tokens_details?.cached_tokens||ce.prompt_tokens_details?.cache_read_input_tokens||ce.cache_read_input_tokens||0,thoughtsTokenCount:ce.completion_tokens_details?.reasoning_tokens||0},T=!0),Z){let Oe=Z.reasoning||(Z.reasoning_details?Z.reasoning_details.map(Ue=>Ue.text).join(""):null);Oe&&(d.push({text:Oe,thought:!0}),T=!0),Z.content&&(d.push({text:Z.content}),T=!0)}}catch(fe){if(fe.message&&fe.message.startsWith("OpenRouter Stream Error:"))throw fe}if((ne||Date.now()-r>=150)&&T&&(yield{candidates:d.length>0?[{content:{parts:[...d]}}]:[],usageMetadata:k},d=[],r=Date.now(),T=!1),ne)break}}};import{Ollama as Oa}from"ollama";var Xs=async function*(e,t,n,s,o,l,f,a,m=1,g="Cloud"){let u=[];s&&u.push({role:"system",content:s});for(let x of n){let d=x.role==="user"?"user":"assistant",k="",r=[];if(Array.isArray(x.parts)){k=x.parts.map(T=>T.text||"").filter(Boolean).join(`
605
+ `);for(let T of x.parts){let A=T.inlineData||T.inline_data;A&&A.data&&r.push(A.data)}}else k=x.text||"";if(k||r.length>0){let T={role:d,content:k};r.length>0&&(T.images=r),u.push(T)}}let h=g==="Local"||!e||e==="LOCAL",i={host:h?process.env.OLLAMA_HOST||"http://127.0.0.1:11434":process.env.OLLAMA_HOST||"https://ollama.com"};!h&&e&&(i.headers={Authorization:"Bearer "+e});let c=new Oa(i),w=[],v=null,b=Date.now(),E=!1,O=Ve("Ollama",t,o),C={Fast:!1,Low:"medium",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},S=O!==null?O==="false"||O===!1?!1:O==="true"||O===!0?!0:O:C[o]!==void 0?C[o]:!0,R={model:t,messages:u,stream:!0,think:S,keep_alive:"10m",options:{temperature:m}},L=await c.chat(R);for await(let x of L){if(a?.aborted)throw new DOMException("The user aborted a request.","AbortError");if(x.message?.thinking&&(w.push({text:x.message.thinking,thought:!0}),E=!0),x.message?.content&&(w.push({text:x.message.content}),E=!0),x.done){let d=x.prompt_cached_count||0;if(!d&&x.prompt_eval_count){let k=x.prompt_eval_duration||0;k>0&&k<5e7&&(d=x.prompt_eval_count)}v={totalTokenCount:(x.prompt_eval_count||0)+(x.eval_count||0),promptTokenCount:x.prompt_eval_count||0,candidatesTokenCount:x.eval_count||0,cachedContentTokenCount:d,thoughtsTokenCount:0},E=!0}(x.done||Date.now()-b>=150&&E)&&(yield{candidates:w.length>0?[{content:{parts:[...w]}}]:[],usageMetadata:v},w=[],b=Date.now(),E=!1)}E&&(w.length>0||v)&&(yield{candidates:w.length>0?[{content:{parts:[...w]}}]:[],usageMetadata:v})};var Zo=async function*(e,t,n,s,o,l,f,a,m=1){let g=[];s&&g.push({role:"system",content:s});for(let d of n){let k=d.role==="user"?"user":"assistant",r="";if(Array.isArray(d.parts))for(let T of d.parts)T.text&&(r+=(r?`
606
+ `:"")+T.text);else r=d.text||"";g.push({role:k,content:r})}let u=Ve("InferX",t,o),y=u!==null?u:{Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i=t&&t.toLowerCase().includes("qwen3.8-27b")&&u===null,c=t&&(t.toLowerCase().includes("qwen3.8-27b")||t.toLowerCase().includes("qwen3.6-35b-a3b-fp8")),w={model:t,messages:g.filter(d=>d.content&&String(d.content).trim().length>0),stream:!0,stream_options:{include_usage:!0},temperature:m};!i&&y&&(w.stream_options={include_usage:!0},w.reasoning_effort=y);let v=await tt("https://model.inferx.net/endpoints/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(w),signal:a});if(!v.ok){let d=await v.text().catch(()=>""),k="";try{let r=JSON.parse(d);k=r.error?.message||r.error?.detail||r.message||r.detail||(typeof r.error=="string"?r.error:"")||(d&&d!=="{}"?d:"")}catch{k=d}throw(!k||k==="{}")&&(k=v.statusText||"Unknown error"),new Error(`InferX Error (${v.status}): ${k}`)}let b=v.body.getReader(),E=new TextDecoder,O="",C=[],S=null,R=Date.now(),L=!1,x=!0;for(;;){let{done:d,value:k}=await b.read();if(d){L&&(C.length>0||S)&&(yield{candidates:C.length>0?[{content:{parts:C}}]:[],usageMetadata:S});break}O+=E.decode(k,{stream:!0});let r=O.split(`
607
+ `);O=r.pop();for(let T of r){let A=T.trim();if(!A||!A.startsWith("data: "))continue;let D=!1;if(A==="data: [DONE]")D=!0;else try{let W=JSON.parse(A.substring(6)),$=W.choices?.[0]?.delta,I=W.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},L=!0),$){let ne=$.reasoning||$.reasoning_content||null;if(ne&&(C.push({text:ne,thought:!0}),L=!0),$.content){let fe=$.content;c&&x&&fe.length>0&&(fe="<think>"+fe,x=!1),C.push({text:fe}),L=!0}}}catch{}if((D||Date.now()-R>=150||S)&&L&&(yield{candidates:C.length>0?[{content:{parts:[...C]}}]:[],usageMetadata:S},C=[],R=Date.now(),L=!1),D)break}Date.now()-R>=150&&L&&(yield{candidates:C.length>0?[{content:{parts:[...C]}}]:[],usageMetadata:S},C=[],R=Date.now(),L=!1)}};var es=async function*(e,t,n,s,o,l,f,a,m=1){let g=[];s&&g.push({role:"system",content:s});for(let R of n){let L=R.role==="user"?"user":"assistant",x=[];if(Array.isArray(R.parts)){for(let d of R.parts)if(d.text)x.push({type:"text",text:d.text});else if(d.inlineData&&f){let k=d.inlineData.mimeType,r=d.inlineData.data;k.startsWith("image/")&&x.push({type:"image_url",image_url:{url:`data:${k};base64,${r}`}})}}else{let d=R.text||"";d&&x.push({type:"text",text:d})}g.push({role:L,content:x.length===1&&x[0].type==="text"?x[0].text:x})}let u=Ve("SenseNova",t,o),y=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};y&&(i.reasoning_effort=y);let c=await tt("https://token.sensenova.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(i),signal:a});if(!c.ok){let R=await c.json().catch(()=>({}));throw new Error(`SenseNova Error (${c.status}): ${R.error?.message||c.statusText}`)}let w=c.body.getReader(),v=new TextDecoder,b="",E=[],O=null,C=Date.now(),S=!1;for(;;){let{done:R,value:L}=await w.read();if(R){S&&(E.length>0||O)&&(yield{candidates:E.length>0?[{content:{parts:E}}]:[],usageMetadata:O});break}b+=v.decode(L,{stream:!0});let x=b.split(`
608
+ `);b=x.pop();for(let d of x){let k=d.trim();if(!k||!k.startsWith("data: "))continue;let r=!1;if(k==="data: [DONE]")r=!0;else try{let T=JSON.parse(k.substring(6)),A=T.choices?.[0]?.delta,D=T.usage;if(D&&(O={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},S=!0),A){let W=A.reasoning||A.reasoning_content||null;W&&(E.push({text:W,thought:!0}),S=!0),A.content&&(E.push({text:A.content}),S=!0)}}catch{}if((r||Date.now()-C>=150||O)&&S&&(yield{candidates:E.length>0?[{content:{parts:[...E]}}]:[],usageMetadata:O},E=[],C=Date.now(),S=!1),r)break}Date.now()-C>=150&&S&&(yield{candidates:E.length>0?[{content:{parts:[...E]}}]:[],usageMetadata:O},E=[],C=Date.now(),S=!1)}};var ts=async function*(e,t,n,s,o,l,f,a,m=1){let g=[];s&&g.push({role:"system",content:s});for(let R of n){let L=R.role==="user"?"user":"assistant",x=[];if(Array.isArray(R.parts)){for(let d of R.parts)if(d.text)x.push({type:"text",text:d.text});else if(d.inlineData&&f){let k=d.inlineData.mimeType,r=d.inlineData.data;k.startsWith("image/")&&x.push({type:"image_url",image_url:{url:`data:${k};base64,${r}`}})}}else{let d=R.text||"";d&&x.push({type:"text",text:d})}g.push({role:L,content:x.length===1&&x[0].type==="text"?x[0].text:x})}let u=Ve("AIHubMix",t,o),y=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};y&&(i.reasoning_effort=y);let c=await tt("https://aihubmix.com/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(i),signal:a});if(!c.ok){let R=await c.json().catch(()=>({}));throw new Error(`AIHubMix Error (${c.status}): ${R.error?.message||c.statusText}`)}let w=c.body.getReader(),v=new TextDecoder,b="",E=[],O=null,C=Date.now(),S=!1;for(;;){let{done:R,value:L}=await w.read();if(R){S&&(E.length>0||O)&&(yield{candidates:E.length>0?[{content:{parts:E}}]:[],usageMetadata:O});break}b+=v.decode(L,{stream:!0});let x=b.split(`
609
+ `);b=x.pop();for(let d of x){let k=d.trim();if(!k||!k.startsWith("data: "))continue;let r=!1;if(k==="data: [DONE]")r=!0;else try{let T=JSON.parse(k.substring(6)),A=T.choices?.[0]?.delta,D=T.usage;if(T.choices?.[0]?.finish_reason&&(r=!0),D&&(O={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},S=!0),A){let W=A.reasoning_content||null;W&&(E.push({text:W,thought:!0}),S=!0),A.content&&(E.push({text:A.content}),S=!0)}}catch{}if((r||Date.now()-C>=150)&&S&&(yield{candidates:E.length>0?[{content:{parts:[...E]}}]:[],usageMetadata:O},E=[],C=Date.now(),S=!1),r)break}Date.now()-C>=150&&S&&(yield{candidates:E.length>0?[{content:{parts:[...E]}}]:[],usageMetadata:O},E=[],C=Date.now(),S=!1)}};var ns=async function*(e,t,n,s,o,l,f,a,m=1){let g=[];s&&g.push({role:"system",content:s});for(let S of n){let R=S.role==="user"?"user":"assistant",L=[];if(Array.isArray(S.parts)){for(let x of S.parts)if(x.text)L.push({type:"text",text:x.text});else if(x.inlineData&&f){let d=x.inlineData.mimeType,k=x.inlineData.data;d.startsWith("image/")&&L.push({type:"image_url",image_url:{url:`data:${d};base64,${k}`}})}}else{let x=S.text||"";x&&L.push({type:"text",text:x})}g.push({role:R,content:L.length===1&&L[0].type==="text"?L[0].text:L})}let u=Ve("Poolside",t,o),h=u!==null?u===!1||u==="false"||u==="none"||u==="Fast":o==="Fast",y={model:t,messages:g,stream:!0,stream_options:{include_usage:!0},temperature:m};h?y.chat_template_kwargs={enable_thinking:!1}:u!==null&&typeof u=="object"?y.chat_template_kwargs=u:y.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(y),signal:a});if(!i.ok){let S=await i.json().catch(()=>({}));throw new Error(`Poolside Error (${i.status}): ${S.error?.message||i.statusText}`)}let c=i.body.getReader(),w=new TextDecoder,v="",b=[],E=null,O=Date.now(),C=!1;for(;;){let{done:S,value:R}=await c.read();if(S){C&&(b.length>0||E)&&(yield{candidates:b.length>0?[{content:{parts:b}}]:[],usageMetadata:E});break}v+=w.decode(R,{stream:!0});let L=v.split(`
610
+ `);v=L.pop();for(let x of L){let d=x.trim();if(!d||!d.startsWith("data: "))continue;let k=!1;if(d==="data: [DONE]")k=!0;else try{let r=JSON.parse(d.substring(6)),T=r.choices?.[0]?.delta,A=r.usage;if(r.choices?.[0]?.finish_reason&&(k=!0),A&&(E={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||0,thoughtsTokenCount:A.completion_tokens_details?.reasoning_tokens||A.reasoning_tokens||0},C=!0),T){let D=T.reasoning_content||T.reasoning||null;D&&(b.push({text:D,thought:!0}),C=!0),T.content&&(b.push({text:T.content}),C=!0)}}catch{}if((k||Date.now()-O>=150)&&C&&(yield{candidates:b.length>0?[{content:{parts:[...b]}}]:[],usageMetadata:E},b=[],O=Date.now(),C=!1),k)break}Date.now()-O>=150&&C&&(yield{candidates:b.length>0?[{content:{parts:[...b]}}]:[],usageMetadata:E},b=[],O=Date.now(),C=!1)}};var os=async function*(e,t,n,s,o,l,f,a,m=1){let g=[];s&&g.push({role:"system",content:s});for(let d of n){let k=d.role==="user"?"user":"assistant",r=[];if(Array.isArray(d.parts)){for(let T of d.parts)if(T.text)r.push({type:"text",text:T.text});else if(T.inlineData&&f){let A=T.inlineData.mimeType,D=T.inlineData.data;A.startsWith("image/")&&r.push({type:"image_url",image_url:{url:`data:${A};base64,${D}`}})}}else{let T=d.text||"";T&&r.push({type:"text",text:T})}g.push({role:k,content:r.length===1&&r[0].type==="text"?r[0].text:r})}let u=Ve("9router",t,o)||Ve("9Router",t,o),y=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};y&&y!=="none"&&(u!==null||o!=="Fast")&&(i.reasoning_effort=y);let c=process.env["9ROUTER_URL"]||process.env.NINEROUTER_URL||"http://127.0.0.1:20128/v1/chat/completions",w={"Content-Type":"application/json"},v=e&&e!=="LOCAL"?e:process.env["9ROUTER_API_KEY"]||"dummy-key";w.Authorization=`Bearer ${v}`;let b=await tt(c,{method:"POST",headers:w,body:JSON.stringify(i),signal:a});if(!b.ok){let d=await b.json().catch(()=>({}));throw new Error(`9router Error (${b.status}): ${d.error?.message||b.statusText}`)}let E=b.body.getReader(),O=new TextDecoder,C="",S=[],R=null,L=Date.now(),x=!1;for(;;){let{done:d,value:k}=await E.read();if(d){x&&(S.length>0||R)&&(yield{candidates:S.length>0?[{content:{parts:S}}]:[],usageMetadata:R});break}C+=O.decode(k,{stream:!0});let r=C.split(`
611
+ `);C=r.pop();for(let T of r){let A=T.trim();if(!A||!A.startsWith("data: "))continue;let D=!1;if(A==="data: [DONE]")D=!0;else try{let W=JSON.parse(A.substring(6)),$=W.choices?.[0]?.delta,I=W.usage;if(W.choices?.[0]?.finish_reason&&(D=!0),I&&(R={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},x=!0),$){let ne=$.reasoning_content||$.reasoning||$.thinking||null;!ne&&Array.isArray($.reasoning_details)&&$.reasoning_details.length>0&&(ne=$.reasoning_details.map(fe=>typeof fe=="string"?fe:fe?.text||"").filter(Boolean).join("")),ne&&(S.push({text:ne,thought:!0}),x=!0),$.content&&(S.push({text:$.content}),x=!0)}}catch{}if((D||Date.now()-L>=150)&&x&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:R},S=[],L=Date.now(),x=!1),D)break}Date.now()-L>=150&&x&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:R},S=[],L=Date.now(),x=!1)}};var ss=async function*(e,t,n,s,o,l,f,a,m=1){let g=[];s&&g.push({role:"system",content:s});for(let d of n){let k=d.role==="user"?"user":"assistant",r=[];if(Array.isArray(d.parts)){for(let T of d.parts)if(T.text)r.push({type:"text",text:T.text});else if(T.inlineData&&f){let A=T.inlineData.mimeType,D=T.inlineData.data;A.startsWith("image/")&&r.push({type:"image_url",image_url:{url:`data:${A};base64,${D}`}})}}else{let T=d.text||"";T&&r.push({type:"text",text:T})}g.push({role:k,content:r.length===1&&r[0].type==="text"?r[0].text:r})}let u=Ve("ExpLabs",t,o),y=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};y&&(i.reasoning_effort=y);let c=process.env.EXPLABS_URL||process.env.EXPERIENTIALLABS_URL||"https://api.experientiallabs.ai/v1/chat/completions",w={"Content-Type":"application/json"},v=e||process.env.EXPLABS_API_KEY||process.env.EXPERIENTIALLABS_API_KEY||"";w.Authorization=`Bearer ${v}`;let b=await tt(c,{method:"POST",headers:w,body:JSON.stringify(i),signal:a});if(!b.ok){let d=await b.json().catch(()=>({}));throw new Error(`Experiential Labs Error (${b.status}): ${d.error?.message||d.message||b.statusText}`)}let E=b.body.getReader(),O=new TextDecoder,C="",S=[],R=null,L=Date.now(),x=!1;for(;;){let{done:d,value:k}=await E.read();if(d){x&&(S.length>0||R)&&(yield{candidates:S.length>0?[{content:{parts:S}}]:[],usageMetadata:R});break}C+=O.decode(k,{stream:!0});let r=C.split(`
612
+ `);C=r.pop();for(let T of r){let A=T.trim();if(!A||!A.startsWith("data: "))continue;let D=!1;if(A==="data: [DONE]")D=!0;else try{let W=JSON.parse(A.substring(6)),$=W.choices?.[0]?.delta,I=W.usage;if(I&&(R={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},x=!0),$){let ne=$.reasoning_content||$.reasoning||null;!ne&&Array.isArray($.reasoning_details)&&$.reasoning_details.length>0&&(ne=$.reasoning_details.map(fe=>fe.text||"").filter(Boolean).join("")),ne&&(S.push({text:ne,thought:!0}),x=!0),$.content&&(S.push({text:$.content}),x=!0)}}catch{}if((D||Date.now()-L>=150)&&x&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:R},S=[],L=Date.now(),x=!1),D)break}Date.now()-L>=150&&x&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:R},S=[],L=Date.now(),x=!1)}};var Qs=async function*(e,t,n,s,o,l,f,a,m=1){let g=[];s&&g.push({role:"system",content:s});for(let d of n){let k=d.role==="user"?"user":"assistant",r=[];if(Array.isArray(d.parts)){for(let T of d.parts)if(T.text)r.push({type:"text",text:T.text});else if(T.inlineData&&f){let A=T.inlineData.mimeType,D=T.inlineData.data;A.startsWith("image/")&&r.push({type:"image_url",image_url:{url:`data:${A};base64,${D}`}})}}else{let T=d.text||"";T&&r.push({type:"text",text:T})}g.push({role:k,content:r.length===1&&r[0].type==="text"?r[0].text:r})}let u=Ve("TokenHarbor",t,o),y=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};y&&(i.reasoning_effort=y);let c=process.env.TOKENHARBOR_URL||process.env.TOKEN_HARBOR_URL||"https://tokenharbor.ai/v1/chat/completions",w={"Content-Type":"application/json","X-Title":"Flux-Flow","User-Agent":"Flux-Flow","HTTP-Referer":"https://fluxflow-cli.onrender.com/"},v=e||process.env.TOKENHARBOR_API_KEY||process.env.TOKEN_HARBOR_API_KEY||"";w.Authorization=`Bearer ${v}`;let b=await tt(c,{method:"POST",headers:w,body:JSON.stringify(i),signal:a});if(!b.ok){let d=await b.json().catch(()=>({}));throw new Error(`Token Harbor Error (${b.status}): ${d.error?.message||d.message||b.statusText}`)}let E=b.body.getReader(),O=new TextDecoder,C="",S=[],R=null,L=Date.now(),x=!1;for(;;){let{done:d,value:k}=await E.read();if(d){x&&(S.length>0||R)&&(yield{candidates:S.length>0?[{content:{parts:S}}]:[],usageMetadata:R});break}C+=O.decode(k,{stream:!0});let r=C.split(`
613
+ `);C=r.pop();for(let T of r){let A=T.trim();if(!A||!A.startsWith("data: "))continue;let D=!1;if(A==="data: [DONE]")D=!0;else try{let W=JSON.parse(A.substring(6)),$=W.choices?.[0]?.delta,I=W.usage;if(I&&(R={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},x=!0),$){let ne=$.reasoning_content||$.reasoning||null;!ne&&Array.isArray($.reasoning_details)&&$.reasoning_details.length>0&&(ne=$.reasoning_details.map(fe=>fe.text||"").filter(Boolean).join("")),ne&&(S.push({text:ne,thought:!0}),x=!0),$.content&&(S.push({text:$.content}),x=!0)}}catch{}if((D||Date.now()-L>=150)&&x&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:R},S=[],L=Date.now(),x=!1),D)break}Date.now()-L>=150&&x&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:R},S=[],L=Date.now(),x=!1)}};var Zs=async function*(e,t,n,s,o,l,f,a,m=1){let g=[];s&&g.push({role:"system",content:s});for(let d of n){let k=d.role==="user"?"user":"assistant",r=[];if(Array.isArray(d.parts)){for(let T of d.parts)if(T.text)r.push({type:"text",text:T.text});else if(T.inlineData&&f){let A=T.inlineData.mimeType,D=T.inlineData.data;A.startsWith("image/")&&r.push({type:"image_url",image_url:{url:`data:${A};base64,${D}`}})}}else{let T=d.text||"";T&&r.push({type:"text",text:T})}g.push({role:k,content:r.length===1&&r[0].type==="text"?r[0].text:r})}let u=Ve("APInex",t,o),y=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};y&&(i.reasoning_effort=y);let c=process.env.APINEX_URL||"https://api.apinex.bond/v1/chat/completions",w={"Content-Type":"application/json","X-Title":"Flux-Flow","User-Agent":"Flux-Flow","HTTP-Referer":"https://fluxflow-cli.onrender.com/"},v=e||process.env.APINEX_API_KEY||"";w.Authorization=`Bearer ${v}`;let b=await tt(c,{method:"POST",headers:w,body:JSON.stringify(i),signal:a});if(!b.ok){let d=await b.json().catch(()=>({}));throw new Error(`APInex Error (${b.status}): ${d.error?.message||d.message||b.statusText}`)}let E=b.body.getReader(),O=new TextDecoder,C="",S=[],R=null,L=Date.now(),x=!1;for(;;){let{done:d,value:k}=await E.read();if(d){x&&(S.length>0||R)&&(yield{candidates:S.length>0?[{content:{parts:S}}]:[],usageMetadata:R});break}C+=O.decode(k,{stream:!0});let r=C.split(`
614
+ `);C=r.pop();for(let T of r){let A=T.trim();if(!A||!A.startsWith("data: "))continue;let D=!1;if(A==="data: [DONE]")D=!0;else try{let W=JSON.parse(A.substring(6)),$=W.choices?.[0]?.delta,I=W.usage;if(I&&(R={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},x=!0),$){let ne=$.reasoning_content||$.reasoning||null;!ne&&Array.isArray($.reasoning_details)&&$.reasoning_details.length>0&&(ne=$.reasoning_details.map(fe=>fe.text||"").filter(Boolean).join("")),ne&&(S.push({text:ne,thought:!0}),x=!0),$.content&&(S.push({text:$.content}),x=!0)}}catch{}if((D||Date.now()-L>=150)&&x&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:R},S=[],L=Date.now(),x=!1),D)break}Date.now()-L>=150&&x&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:R},S=[],L=Date.now(),x=!1)}};var La=/```[\s\S]*?```/g,Pa=/```[\s\S]*$/g,$a=/`[^`]+`/g,Na=/^\|.*\|$/gm,Fa=/^[^\w]+|[^\w]+$/g,Ba=/[^a-z0-9]/gi,xo=/\[\s*tool:(?:functions\.)?([a-z0-9_]+)\s*\(/gi,Ua=/\[\s*(?:tool:(?:functions\.)?|agent:generalist\.)([a-z0-9_]+)\s*\(/gi,Wa=/(?:path|targetFile|TargetFile|directory|keyword|id|taskId|title|task)\s*=\s*\\?["']?([^\\"' \),]+)/,Hn=/["']/g,Ur=/\\/g,Ha=/<\|channel>thought/gi,Ga=/<channel\|>/gi,ja=e=>typeof e!="string"?e:e.replace(Ha,"<think>").replace(Ga,"</think>"),cf=/^\s*(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\]|$)/i,Va=(e,t,n=1)=>{let s=t>0?e[t-1]:"",o=t+n<e.length?e[t+n]:"";return s==="`"&&o==="`"},Ka=e=>{let t=/(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\])/gi,n;for(;(n=t.exec(e))!==null;)if(!Va(e,n.index,n[0].length))return{index:n.index,length:n[0].length};return{index:-1,length:0}},ei=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=Ka(s);if(o.index!==-1){let l=n+o.index+o.length;return{fullBlock:e.substring(0,l),innerContent:s.substring(0,o.index),remainingText:e.substring(l)}}return{fullBlock:e,innerContent:s,remainingText:""}},zt=e=>{if(!e||typeof e!="string")return e;let t=ei(e);return t?t.remainingText.trimStart():e};var Yr=/`[^`]*`/g,qr=/`[^`]*$/,Wr=/<\|\s*tool_call_begin\s*\|>\s*(?:(?:tool|functions)\b[\s._]*)*([a-zA-Z0-9_]+)(?::\d+)?\s*<\|\s*tool_call_argument_begin\s*\|>([\s\S]*?)<\|\s*tool_call_end\s*\|>/gi,Ya=/"([^"]+)"\s*:\s*(?:"([^"]*)"|(\d+)|true|false|null)/g,Hr=/<\|\s*tool_calls_section_begin\s*\|>/gi,Gr=/<\|\s*tool_calls_section_end\s*\|>/gi,qa=/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi;var jr=e=>!e||typeof e!="string"?e:e.replace(/(```[\s\S]*?```|`[^`]*`)|(<(?:\w+)(?:[^>]*)>\r?\n?|\r?\n?<\/\w+(?:[^>]*)>)/gi,(t,n)=>n||""),zr=e=>{if(!e||typeof e!="string")return e;let t=bo(e);if(!t||t.length===0)return e;let n=t[t.length-1];if(!n.fullMatch)return e;let s=e.lastIndexOf(n.fullMatch);if(s===-1)return e;let o=s+n.fullMatch.length;return e.substring(0,o).trimEnd()},ni=null,is={},Gn={key:null,value:null},qt=e=>e&&e.replace(/(?:(\x1b\[\d+m))?([✔✘✖🔍📖→➕↻↷•🛇])(?:(\x1b\[\d+m))?\s*\b(Clicked|Dragged|Scrolled|Typed|Pressed Key|Recaptured Screen|Created|Read Skill|Read Documentation|Searched Documentation|Read|Edited|Viewed|Processed|Auto-Read|Skipped|List|Generated|Written|Searched|AI Search|Get Map|Write Canceled|Resolved Sub-Agent Query|Edit Canceled|Write Cancelled|Edit Denied|Visited|Updated|Reviewed|Delegated|Background|Checked|Indexed|Analyzed|Browsed|Elevating SubAgent|Checking SubAgent Work|Started Generalist|Called Generalist|Steered|Unsupported Modality|Awaiting|Cancelled|Aligning Moon Phase|Contemplating Existence|Staring At Void|Rollback Point Checked|Emergency Rollback Failed|Emergency Rollback|Delaying Professionally|Negotiating With Electrons|Touching Grass (virtually)|Panicking Softly|Rethinking Career Choices|Loading Cat Videos|Giving Up Entirely|Summoning Braincell #2|Pretending To Be Busy|Waiting For Motivation DLC|Rotating Internal Screaming|Downloading More RAM|Feeding The Hamsters|Gaslighting Scheduler|Performing Dramatic Pause|Buffering Social Energy|Calculating Regret|Reading Terms And Conditions|Becoming Sentient Briefly|Execution Error|Loop Detected|Contacting Ancestors)\b/ig,(t,n,s,o,l)=>`${n||""}${s}${o||""} \x1B[95m${l}\x1B[0m`),za=async(e,t=8,n=1e3,s=8e3,o=null)=>{let l=0;for(;;){if(o?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{return await e()}catch(f){if(o?.aborted||f?.name==="AbortError"||f?.message==="Subagent task was cancelled."||(l++,l>=t))throw f;let a=Math.min(n*Math.pow(2,l-1),s);await new Promise((m,g)=>{let u=setTimeout(m,a);o&&o.addEventListener("abort",()=>{clearTimeout(u),g(new DOMException("The user aborted a request.","AbortError"))})})}}},kt=!1;var Ja=e=>{let t=e.filter(o=>(o.role==="user"||o.role==="agent"||o.role==="system")&&o.role!=="think"&&!o.isVisualFeedback&&!o.isMeta&&!o.isTerminalRecord&&!(o.text&&o.text.includes("[TERMINAL_RECORD]"))&&!String(o.id).startsWith("welcome")).map((o,l,f)=>{let a=o.fullText||o.text||"";if(o.role==="user"&&l<f.length-1)if(a.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")){let m=a.indexOf("**CONTEXT SUMMARY OF PREVIOUS TURNS");if(m!==-1){let u=a.substring(0,m).lastIndexOf("[SYSTEM METADATA]");u!==-1?a=a.substring(u).trim():a=a.substring(m).trim()}}else{let m=a.lastIndexOf("[USER]"),g=a.lastIndexOf("[USER PROMPT]");m!==-1?a=a.substring(m+6).trim():g!==-1&&(a=a.substring(g).trim())}return{...o,text:a}}),n=[],s=0;for(;s<t.length;){let o=t[s];if(o.role==="user")n.push(o),s++;else{let l=[];for(;s<t.length&&t[s].role!=="user";)l.push(t[s]),s++;let f=[],a=[],m=!1,g=()=>{f.length>0&&(n.push({role:"agent",text:"combined"}),f=[]),a.length>0&&(n.push({role:"system",text:"combined"}),a=[]),m=!1};l.forEach(u=>{let h=u.role==="system"&&(u.text?.startsWith("[TOOL RESULT]")||u.text?.startsWith("SUCCESS:")||u.text?.startsWith("ERROR:")||u.fullText?.startsWith("[TOOL RESULT]")||u.fullText?.startsWith("SUCCESS:")||u.fullText?.startsWith("ERROR:")),y=u.fullText||u.text||"",i=y.trim();if(!(!i&&!u.binaryPart)){if(h)a.push(i);else if(u.role==="agent"){!m&&a.length>0&&g();let c=y.endsWith(`
615
+ `),w=i.toLowerCase().includes("tool:functions.")||i.toLowerCase().includes("agent:generalist.");f.push(i),w&&c?m=!0:m=!1}}}),g()}}return n.length},Xa=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),df=()=>{kt=!0},ff=()=>kt,ti={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"},jn=(e,t)=>{try{let n=ie(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?te.basename(o.replace(/["']/g,"").replace(/\\/g,"/")):null}catch{return null}},oi=e=>e?new Kr({apiKey:e}):ni,uf=async(e,t,n,s,o={})=>{let{onStatus:a,onMemoryUpdated:m,onBackgroundIncrement:g}=o,{profile:u,thinkingLevel:h,mode:y,janitorModel:i,chatId:c,systemSettings:w,sessionStats:v,aiProvider:b="Google",apiKey:E}=e,O=process.env.NVIDIA_BASE_URL||b==="Ollama"||b==="InferX"||b==="SenseNova"||b==="AIHubMix"||b==="Poolside"||b==="9router"||b==="ExpLabs"||b==="ExperientialLabs"?!1:w?.memory!==!1,S=Ct(Un,[]).map(P=>`- [${P.id}]: ${P.memory}`).join(`
616
+ `),R=s.slice(0,-1).filter(P=>P.text&&!P.text.includes("[TOOL RESULT]")&&!P.text.includes("OBSERVATION:")&&!P.text.startsWith("[TERMINAL_RECORD]")&&!P.isTerminalRecord&&!P.isMeta&&!P.isLogo&&!String(P.id).startsWith("welcome")&&!String(P.id).startsWith("logo")).slice(-14).map(P=>{let B=zt(Xa(P.text)).replace(/\[tool:(?:functions\.)?.*?\]/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[METADATA \(PRIORITY: DYNAMIC\)\] Time: ([^|\n]+)/g,(K,he)=>`[METADATA (PRIORITY: DYNAMIC)] Time: ${he.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,`
617
617
  `).replace(/\n\n/g,`
618
- `).replace(/\\n\\n/g,"").trim(),ve=P.role==="user"?8192:32768,z=F.substring(0,ve);F.length>ve&&(z+=`
619
- ... (truncated) ...`);let B=P.role==="user"?z.startsWith("[USER]")?"":"[USER]: ":z.startsWith("[AGENT]")?"":"[AGENT]: ";return{role:P.role==="user"?"user":"model",parts:[{text:`${B}${z}`}]}}),L=s.filter(P=>P.role==="user").length===1,x=t.includes("[TITLE-UPDATE]"),d=Math.random()<.8,k=L||x||d,r=qt(n).trim(),T=cr(S,O,k),A=`${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)}`;A.length>32768&&(A+=`
618
+ `).replace(/\\n\\n/g,"").trim(),Me=P.role==="user"?8192:32768,X=B.substring(0,Me);B.length>Me&&(X+=`
619
+ ... (truncated) ...`);let U=P.role==="user"?X.startsWith("[USER]")?"":"[USER]: ":X.startsWith("[AGENT]")?"":"[AGENT]: ";return{role:P.role==="user"?"user":"model",parts:[{text:`${U}${X}`}]}}),L=s.filter(P=>P.role==="user").length===1,x=t.includes("[TITLE-UPDATE]"),d=Math.random()<.8,k=L||x||d,r=zt(n).trim(),T=ur(S,O,k),A=`${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)}`;A.length>32768&&(A+=`
620
620
  ... (truncated) ...`);let D=t.replace(/\[Prompted on:.*?\]/g,"").trim();A=A.replace(/\r?\n\r?\n/g,`
621
621
  `).replace(/\n\n/g,`
622
- `).replace(/\\n\\n/g,"").trim();let H=new Date,M=`[METADATA] Current date and Time: ${`${H.getFullYear()}-${H.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(H.getDate()).padStart(2,"0")}, ${H.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0})}`}
622
+ `).replace(/\\n\\n/g,"").trim();let W=new Date,I=`[METADATA] Current date and Time: ${`${W.getFullYear()}-${W.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(W.getDate()).padStart(2,"0")}, ${W.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0})}`}
623
623
 
624
624
  [USER]: ${D.substring(0,8192)}
625
625
  ${D.length>8192?`... (truncated) ...
626
626
 
627
627
  `:""}
628
- [AGENT (current turn)]: ${A}`;R.push({role:"user",parts:[{text:M}]});let te=await ks("NVIDIA"),J=(await so()).quotas?.providerTiers?.NVIDIA==="Free",re="",Oe=0,We=O?12:-1;for(;Oe<=We;)try{if(!await yi("background",e))return;let P="",F=null,ve=!1,z=b;try{let fe=new Promise((me,he)=>setTimeout(()=>he(new Error("JANITOR_TIMEOUT")),1e4)),Ae=b==="Google"&&Oe>=0&&Oe<6&&te&&J,Ee=b==="DeepSeek"&&Oe<4&&te&&J;ve=Ae||Ee,z=ve?"NVIDIA":b;let $e=(async()=>{if(b==="OpenRouter"){let me=ge("janitor_open_router"),ie=Xo(E,me,R,T,"Fast",y,!1,null,.7)[Symbol.asyncIterator](),Ot=await ie.next();return{iterator:ie,firstResult:Ot}}else if(b==="DeepSeek"&&!ve){let he=qo(E,ge("deepseek_fast_fallback"),R,T,"Fast",y,!1,null,.7)[Symbol.asyncIterator](),ie=await he.next();return{iterator:he,firstResult:ie}}else if(b==="Mistral"&&!ve){let he=zo(E,ge("mistral_janitor_fallback"),R,T,"Fast",y,!1,null,.7)[Symbol.asyncIterator](),ie=await he.next();return{iterator:he,firstResult:ie}}else if(b==="NVIDIA"||ve){let he=Jo(ve?te:E,ge("nvidia_janitor_fallback"),R,T,"Fast",y,!1,null,.7)[Symbol.asyncIterator](),ie=await he.next();return{iterator:he,firstResult:ie}}else if(b==="InferX"){let he=Qo(E,targetModel||ge("inferx_fallback")||"deepseek-v4-flash",R,T,"Fast",y,!1,null,.7)[Symbol.asyncIterator](),ie=await he.next();return{iterator:he,firstResult:ie}}else if(b==="SenseNova"){let he=Zo(E,targetModel||ge("sensenova_fallback")||"sensenova-6.8-flash-lite",R,T,"Fast",y,!1,null,.7)[Symbol.asyncIterator](),ie=await he.next();return{iterator:he,firstResult:ie}}else if(b==="AIHubMix"){let he=es(E,targetModel||ge("aihubmix_fallback")||"gpt-4o-mini",R,T,"Fast",y,!1,null,.7)[Symbol.asyncIterator](),ie=await he.next();return{iterator:he,firstResult:ie}}else if(b==="Poolside"){let he=ts(E,targetModel||ge("poolside_fallback")||"poolside/laguna-s-2.1",R,T,"Fast",y,!1,null,.7)[Symbol.asyncIterator](),ie=await he.next();return{iterator:he,firstResult:ie}}else if(b==="9router"||b==="9Router"){let he=ns(E,targetModel||ge("9router_fallback")||"z-ai/glm-5.3-flash",R,T,"Fast",y,!1,null,.7)[Symbol.asyncIterator](),ie=await he.next();return{iterator:he,firstResult:ie}}else if(b==="ExpLabs"||b==="ExperientialLabs"){let he=os(E,targetModel||ge("explabs_fallback")||"deepseek-v4-pro-0813",R,T,"Fast",y,!1,null,.7)[Symbol.asyncIterator](),ie=await he.next();return{iterator:he,firstResult:ie}}else{let ie=(await ni(E).models.generateContentStream({model:i||(Oe===We?ge("janitor_default"):ge("gemma_janitor_fallback_google")),contents:R,config:{systemInstruction:T,temperature:.7,safetySettings:[{category:Dn.HARM_CATEGORY_HARASSMENT,threshold:In.BLOCK_NONE},{category:Dn.HARM_CATEGORY_HATE_SPEECH,threshold:In.BLOCK_NONE},{category:Dn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:In.BLOCK_NONE},{category:Dn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:In.BLOCK_NONE}],thinkingConfig:{includeThoughts:!1,thinkingLevel:Ze.MINIMAL}}}))[Symbol.asyncIterator](),Ot=await ie.next();return{iterator:ie,firstResult:Ot}}})();if(process.stdout.isTTY){let ie=(await _s())[c]?.name||"",Ot=ie&&!ie.startsWith("flow-")&&!ie.startsWith("Session ")?ie:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${Ot}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${Ot}\x07`)}let{iterator:Rt,firstResult:wn}=await Promise.race([$e,fe]),{value:zt,done:dt}=wn;if(!dt&&zt){let me=zt.candidates?.[0]?.content?.parts,he=me?z==="Google"?me[1]?.text||me[0]?.text||"":me.filter(ie=>ie.text&&!ie.thought).map(ie=>ie.text).join(""):typeof zt.text=="function"?zt.text():"";he&&(P+=he),F=zt.usageMetadata;for await(let ie of{[Symbol.asyncIterator]:()=>Rt}){let Ot=ie.candidates?.[0]?.content?.parts,jn=Ot?z==="Google"?Ot[1]?.text||Ot[0]?.text||"":Ot.filter(_t=>_t.text&&!_t.thought).map(_t=>_t.text).join(""):typeof ie.text=="function"?ie.text():"";jn&&(P+=jn),F=ie.usageMetadata}}}catch(fe){throw fe}if(P){if(re=P,F){let fe=F.totalTokenCount||0,Ae=F.cachedContentTokenCount||0,Ee=(F.candidatesTokenCount||0)+(z==="Google"&&F.thoughtsTokenCount||0),$e=ve?ge("nvidia_janitor_fallback"):z==="DeepSeek"?ge("deepseek_fast_fallback"):z==="ExpLabs"||z==="ExperientialLabs"?ge("explabs_fallback")||"deepseek-v4-pro-0813":z==="OpenRouter"?ge("janitor_open_router"):i||(Oe===We?ge("janitor_default"):ge("gemma_janitor_fallback_google"));await Ut("tokens",fe,z,$e),Ae>0&&await Ut("cachedTokens",Ae,z,$e),Ee>0&&await Ut("candidateTokens",Ee,z,$e),Mo({provider:z,model:$e,prompt:F.promptTokenCount||0,cached:Ae,output:Ee,reasoning:F.thoughtsTokenCount||0})}}else throw new Error("No synthesis generated by Janitor.");g&&(g(),await vt("background"));let B=xo(re),Y=!1;for(let fe of B){let Ae=fe.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(Ae)&&(Y=!0);let Ee={chatId:c,sessionId:c,history:s},$e=await ho(Ae,fe.args,Ee);Ae.toLowerCase()==="memory"&&(fe.args.includes("action='user'")||fe.args.includes('action="user"'))&&!$e.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(wn=>setTimeout(wn,3e3)))}if(!Y)try{let fe=Ct(Bn,[]);if(fe.length>0){let Ae=[];for(let Ee of fe)Ee.score===void 0&&(Ee.score=.5),Ee.score*=.99995,Ee.score<.05&&(Ee.score=0),Ee.score=Math.round(Ee.score*1e5)/1e5,Ee.score>0&&Ae.push(Ee);Jn(Bn,Ae)}}catch{}break}catch(P){Oe++;let F=new Date().toLocaleString(),ve=P instanceof Error?(()=>{try{return JSON.parse(JSON.parse(P.message).error.message).error.message}catch{return String(P)}})():String(P);await new Promise(Y=>setTimeout(Y,1e3));let z=ee.join(vn,"janitor");if(Ge.existsSync(z)||Ge.mkdirSync(z,{recursive:!0}),Ge.appendFileSync(ee.join(z,"error.log"),`ERROR [Attempt ${Oe}/${We+1}] [${F}]: ${ve}
628
+ [AGENT (current turn)]: ${A}`;R.push({role:"user",parts:[{text:I}]});let ne=await ws("NVIDIA"),Z=(await io()).quotas?.providerTiers?.NVIDIA==="Free",ce="",Oe=0,Ue=O?12:-1;for(;Oe<=Ue;)try{if(!await ki("background",e))return;let P="",B=null,Me=!1,X=b;try{let he=new Promise((ye,xe)=>setTimeout(()=>xe(new Error("JANITOR_TIMEOUT")),1e4)),Ce=b==="Google"&&Oe>=0&&Oe<6&&ne&&Z,ve=b==="DeepSeek"&&Oe<4&&ne&&Z;Me=Ce||ve,X=Me?"NVIDIA":b;let Pe=(async()=>{if(b==="OpenRouter"){let ye=pe("janitor_open_router"),ae=Qo(E,ye,R,T,"Fast",y,!1,null,.7)[Symbol.asyncIterator](),Ot=await ae.next();return{iterator:ae,firstResult:Ot}}else if(b==="DeepSeek"&&!Me){let xe=zo(E,pe("deepseek_fast_fallback"),R,T,"Fast",y,!1,null,.7)[Symbol.asyncIterator](),ae=await xe.next();return{iterator:xe,firstResult:ae}}else if(b==="Mistral"&&!Me){let xe=Jo(E,pe("mistral_janitor_fallback"),R,T,"Fast",y,!1,null,.7)[Symbol.asyncIterator](),ae=await xe.next();return{iterator:xe,firstResult:ae}}else if(b==="NVIDIA"||Me){let xe=Xo(Me?ne:E,pe("nvidia_janitor_fallback"),R,T,"Fast",y,!1,null,.7)[Symbol.asyncIterator](),ae=await xe.next();return{iterator:xe,firstResult:ae}}else if(b==="InferX"){let xe=Zo(E,targetModel||pe("inferx_fallback")||"deepseek-v4-flash",R,T,"Fast",y,!1,null,.7)[Symbol.asyncIterator](),ae=await xe.next();return{iterator:xe,firstResult:ae}}else if(b==="SenseNova"){let xe=es(E,targetModel||pe("sensenova_fallback")||"sensenova-6.8-flash-lite",R,T,"Fast",y,!1,null,.7)[Symbol.asyncIterator](),ae=await xe.next();return{iterator:xe,firstResult:ae}}else if(b==="AIHubMix"){let xe=ts(E,targetModel||pe("aihubmix_fallback")||"gpt-4o-mini",R,T,"Fast",y,!1,null,.7)[Symbol.asyncIterator](),ae=await xe.next();return{iterator:xe,firstResult:ae}}else if(b==="Poolside"){let xe=ns(E,targetModel||pe("poolside_fallback")||"poolside/laguna-s-2.1",R,T,"Fast",y,!1,null,.7)[Symbol.asyncIterator](),ae=await xe.next();return{iterator:xe,firstResult:ae}}else if(b==="9router"||b==="9Router"){let xe=os(E,targetModel||pe("9router_fallback")||"z-ai/glm-5.3-flash",R,T,"Fast",y,!1,null,.7)[Symbol.asyncIterator](),ae=await xe.next();return{iterator:xe,firstResult:ae}}else if(b==="ExpLabs"||b==="ExperientialLabs"){let xe=ss(E,targetModel||pe("explabs_fallback")||"deepseek-v4-pro-0813",R,T,"Fast",y,!1,null,.7)[Symbol.asyncIterator](),ae=await xe.next();return{iterator:xe,firstResult:ae}}else{let ae=(await oi(E).models.generateContentStream({model:i||(Oe===Ue?pe("janitor_default"):pe("gemma_janitor_fallback_google")),contents:R,config:{systemInstruction:T,temperature:.7,safetySettings:[{category:On.HARM_CATEGORY_HARASSMENT,threshold:Dn.BLOCK_NONE},{category:On.HARM_CATEGORY_HATE_SPEECH,threshold:Dn.BLOCK_NONE},{category:On.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Dn.BLOCK_NONE},{category:On.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Dn.BLOCK_NONE}],thinkingConfig:{includeThoughts:!1,thinkingLevel:Qe.MINIMAL}}}))[Symbol.asyncIterator](),Ot=await ae.next();return{iterator:ae,firstResult:Ot}}})();if(process.stdout.isTTY){let ae=(await As())[c]?.name||"",Ot=ae&&!ae.startsWith("flow-")&&!ae.startsWith("Session ")?ae:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${Ot}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${Ot}\x07`)}let{iterator:Rt,firstResult:wn}=await Promise.race([Pe,he]),{value:Jt,done:ct}=wn;if(!ct&&Jt){let ye=Jt.candidates?.[0]?.content?.parts,xe=ye?X==="Google"?ye[1]?.text||ye[0]?.text||"":ye.filter(ae=>ae.text&&!ae.thought).map(ae=>ae.text).join(""):typeof Jt.text=="function"?Jt.text():"";xe&&(P+=xe),B=Jt.usageMetadata;for await(let ae of{[Symbol.asyncIterator]:()=>Rt}){let Ot=ae.candidates?.[0]?.content?.parts,Vn=Ot?X==="Google"?Ot[1]?.text||Ot[0]?.text||"":Ot.filter(_t=>_t.text&&!_t.thought).map(_t=>_t.text).join(""):typeof ae.text=="function"?ae.text():"";Vn&&(P+=Vn),B=ae.usageMetadata}}}catch(he){throw he}if(P){if(ce=P,B){let he=B.totalTokenCount||0,Ce=B.cachedContentTokenCount||0,ve=(B.candidatesTokenCount||0)+(X==="Google"&&B.thoughtsTokenCount||0),Pe=Me?pe("nvidia_janitor_fallback"):X==="DeepSeek"?pe("deepseek_fast_fallback"):X==="ExpLabs"||X==="ExperientialLabs"?pe("explabs_fallback")||"deepseek-v4-pro-0813":X==="OpenRouter"?pe("janitor_open_router"):i||(Oe===Ue?pe("janitor_default"):pe("gemma_janitor_fallback_google"));await Wt("tokens",he,X,Pe),Ce>0&&await Wt("cachedTokens",Ce,X,Pe),ve>0&&await Wt("candidateTokens",ve,X,Pe),Io({provider:X,model:Pe,prompt:B.promptTokenCount||0,cached:Ce,output:ve,reasoning:B.thoughtsTokenCount||0})}}else throw new Error("No synthesis generated by Janitor.");g&&(g(),await vt("background"));let U=bo(ce),K=!1;for(let he of U){let Ce=he.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(Ce)&&(K=!0);let ve={chatId:c,sessionId:c,history:s},Pe=await po(Ce,he.args,ve);Ce.toLowerCase()==="memory"&&(he.args.includes("action='user'")||he.args.includes('action="user"'))&&!Pe.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(wn=>setTimeout(wn,3e3)))}if(!K)try{let he=Ct(Un,[]);if(he.length>0){let Ce=[];for(let ve of he)ve.score===void 0&&(ve.score=.5),ve.score*=.99995,ve.score<.05&&(ve.score=0),ve.score=Math.round(ve.score*1e5)/1e5,ve.score>0&&Ce.push(ve);Jn(Un,Ce)}}catch{}break}catch(P){Oe++;let B=new Date().toLocaleString(),Me=P instanceof Error?(()=>{try{return JSON.parse(JSON.parse(P.message).error.message).error.message}catch{return String(P)}})():String(P);await new Promise(K=>setTimeout(K,1e3));let X=te.join(Rn,"janitor");if(Ge.existsSync(X)||Ge.mkdirSync(X,{recursive:!0}),Ge.appendFileSync(te.join(X,"error.log"),`ERROR [Attempt ${Oe}/${Ue+1}] [${B}]: ${Me}
629
629
 
630
- `),Oe>We)break;let B=Math.min(750*Math.pow(2,Oe-1),5e3);await new Promise(Y=>setTimeout(Y,B))}if(Oe){let P=ee.join(vn,"janitor");Ge.appendFileSync(ee.join(P,"error.log"),`-----------------------------------------------------------------------------
630
+ `),Oe>Ue)break;let U=Math.min(750*Math.pow(2,Oe-1),5e3);await new Promise(K=>setTimeout(K,U))}if(Oe){let P=te.join(Rn,"janitor");Ge.appendFileSync(te.join(P,"error.log"),`-----------------------------------------------------------------------------
631
631
 
632
- `)}if(process.stdout.isTTY)try{let ve=(await _s())[c]?.name||"",z=ve&&!ve.startsWith("flow-")&&!ve.startsWith("Session ")?ve:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${z}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${z}\x07`)}catch{process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")}},za=e=>{let t=qt(e),n=Ss?t:t.replace(jr,o=>" ".repeat(o.length)).replace(Vr,o=>" ".repeat(o.length));yo.lastIndex=0;let s;for(;(s=yo.exec(n))!==null;){let o=s.index+s[0].length-1,l=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==="("?l++:u===")"&&l--,l===0)){let m=g+1;for(;m<n.length&&/\s/.test(n[m]);)m++;if(m<n.length&&n[m]==="]"){h=!0,yo.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}},Yr=(e,t=!0)=>{let n=yo;n.lastIndex=0;let s="",o=0,l;for(;(l=n.exec(e))!==null;){let f=e.substring(o,l.index);s+=t&&o===0?qt(f):f;let a=l.index+l[0].length-1,h=0,g=null,u=-1;for(let m=a;m<e.length;m++){let y=e[m];if(g){if(y===g){let i=0;for(let c=m-1;c>=0&&e[c]==="\\";c--)i++;i%2===0&&(g=null)}}else if(y==='"'||y==="'"||y==="`")g=y;else if(y==="(")h++;else if(y===")"&&(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."+l[1]+"()]",o=u+1,n.lastIndex=o;else{s+="[tool:functions."+l[1]+"(",o=e.length;break}}return o<e.length&&(s+=t&&o===0?qt(e.substring(o)):e.substring(o)),s},Ja=(e,t,n)=>{let s=yo;s.lastIndex=0;let o="",l=0,f;for(;(f=s.exec(e))!==null;){let a=e.substring(l,f.index);o+=a.replace(t,n);let h=f.index+f[0].length-1,g=0,u=null,m=-1;for(let y=h;y<e.length;y++){let i=e[y];if(u){if(i===u){let c=0;for(let w=y-1;w>=0&&e[w]==="\\";w--)c++;c%2===0&&(u=null)}}else if(i==='"'||i==="'"||i==="`")u=i;else if(i==="(")g++;else if(i===")"&&(g--,g===0)){let c=y+1;for(;c<e.length&&/\s/.test(e[c]);)c++;if(c<e.length&&e[c]==="]"){m=c;break}}}if(m!==-1)o+=e.substring(f.index,m+1),l=m+1,s.lastIndex=l;else{o+=e.substring(f.index),l=e.length;break}}return l<e.length&&(o+=e.substring(l).replace(t,n)),o},Hr=e=>Yr(e,!0),Xa=e=>{if(!e)return e;let t={patchfile:"PatchFile",writefile:"WriteFile",readfile:"ReadFile",viewfile:"ReadFile",run:"Run",execcommand:"Run",searchkeyword:"SearchKeyword",codesearch:"CodeSearch",code_search:"CodeSearch",websearch:"WebSearch",webscrape:"WebScrape",readfolder:"ReadFolder",writepdf:"WritePDF",writedoc:"WriteDoc",writedocx:"WriteDoc",filemap:"FileMap",generateimage:"GenerateImage",todo:"Todo",goal:"Goal",askuser:"AskUser",ask:"AskUser"},n=o=>o.split("_").map(l=>l.charAt(0).toUpperCase()+l.slice(1)).join("");Fr.lastIndex=0;let s=e.replace(Fr,(o,l,f)=>{let a="";try{let u=JSON.parse(f.trim());u&&typeof u=="object"&&(a=Object.entries(u).map(([y,i])=>{let c=typeof i=="string"?i:JSON.stringify(i);return`${y}=${JSON.stringify(c)}`}).join(", "))}catch{let m=[],y=ja;y.lastIndex=0;let i;for(;(i=y.exec(f))!==null;){let c=i[1],w=i[2]!==void 0?i[2]:i[0].split(":").slice(1).join(":").trim();m.push(`${c}=${JSON.stringify(w)}`)}m.length>0?a=m.join(", "):a=f.trim()}let h=l.toLowerCase().replace(/_/g,"");return`[tool:functions.${t[h]||n(l)}(${a})]`});return Br.lastIndex=0,Ur.lastIndex=0,s=s.replace(Br,""),s=s.replace(Ur,""),s},Qa=/(?:path|query|url|keyword|command|method|title|task|id)\s*=\s*['"`]?\s*\.\.\.\s*['"`]?/i,Za=/^['"`]?\s*\.\.\.\s*['"`]?$/,kn=e=>{if(e==null)return!1;let t=String(e).trim();return t==="..."||t==="\u2026"||Za.test(t)},xo=e=>{if(!e)return[];let t=Xa(e),n=qt(t),s=[],o=Ss?n:n.replace(jr,a=>" ".repeat(a.length)).replace(Vr,a=>" ".repeat(a.length)),l=Na;l.lastIndex=0;let f;for(;(f=l.exec(o))!==null;){let a=f[1],h=f.index+f[0].length-1,g=0,u=null,m=-1,y=-1;for(let i=h;i<o.length;i++){let c=n[i];if(u){if(c===u){let w=0;for(let v=i-1;v>=0&&n[v]==="\\";v--)w++;w%2===0&&(u=null)}}else if(c==='"'||c==="'"||c==="`")u=c;else if(c==="(")g++;else if(c===")"&&(g--,g===0)){y=i;let w=i+1;for(;w<o.length&&/\s/.test(o[w]);)w++;if(w<o.length&&o[w]==="]"){m=w;break}}}if(m!==-1){let i=n.substring(h+1,y),c=n.substring(f.index,m+1),w=oe(i);kn(w.path)||kn(w.query)||kn(w.url)||kn(w.keyword)||kn(w.command)||kn(w.method)||kn(w.title)||kn(w.task)||kn(w.id)||Qa.test(i)||s.push({fullMatch:c,toolName:a.trim(),args:i.trim()}),l.lastIndex=m+1}}return s},df=(e,t={})=>{if(!e)return null;if(ss=t,ti=new Gr({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}}}},is=async(e,t,n,s,o="Fast",l=.75,f="agent")=>Ka(async()=>{let{aiProvider:a="Google",apiKey:h,mode:g}=e,u="",m=null,y=typeof n=="string"?[{role:"user",parts:[{text:n}]}]:n,i=new AbortController,c=i.signal,w=setInterval(()=>{kt&&(i.abort(),clearInterval(w))},100);try{let v;a==="Ollama"?v=Js(h,t,y,s,o,g,gt(t),c,l,e.systemSettings?.ollamaEndpoint||"Cloud"):a==="OpenRouter"?v=Xo(h,t,y,s,o,g,gt(t),c,l):a==="DeepSeek"?v=qo(h,t,y,s,o,g,gt(t),c,l):a==="Mistral"?v=zo(h,t,y,s,o,g,gt(t),c,l):a==="NVIDIA"?v=Jo(h,t,y,s,o,g,gt(t),c,l):a==="InferX"?v=Qo(h,t,y,s,o,g,gt(t),c,l):a==="SenseNova"?v=Zo(h,t,y,s,o,g,gt(t),c,l):a==="AIHubMix"?v=es(h,t,y,s,o,g,gt(t),c,l):a==="Poolside"?v=ts(h,t,y,s,o,g,gt(t),c,l):a==="9router"||a==="9Router"?v=ns(h,t,y,s,o,g,gt(t),c,l):a==="ExpLabs"||a==="ExperientialLabs"?v=os(h,t,y,s,o,g,gt(t),c,l):a==="TokenHarbor"||a==="Token Harbor"||a==="tokenharbor"||a==="token_harbor"||a==="thk"?v=Xs(h,t,y,s,o,g,gt(t),c,l):a==="APInex"||a==="apinex"||a==="apx"?v=Qs(h,t,y,s,o,g,gt(t),c,l):v=await ni(h).models.generateContentStream({model:t,contents:y,config:{systemInstruction:s,temperature:l,thinkingConfig:(()=>{let O=(t||"").toLowerCase(),C=O.includes("gemma-4")||O.startsWith("gemma"),S=O.includes("gemini-3");if(C||S)return C?o.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:Ze.MINIMAL}:{includeThoughts:!0,thinkingLevel:Ze.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:O.includes("pro")?Ze.LOW:Ze.MINIMAL,Low:Ze.LOW,Medium:Ze.MEDIUM,Standard:Ze.MEDIUM,High:Ze.HIGH,xHigh:Ze.HIGH}[o]||Ze.MEDIUM};{let R={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[o]||2048;return R===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:R}}})()}},{signal:c});for await(let b of v){if(kt)throw new Error("Subagent task was cancelled.");if(e?.taskId&&typeof Kt<"u"){let C=Kt.find(S=>S.id===e.taskId);if(C&&C.status==="cancelled")throw new Error("Subagent task was cancelled.")}let E="";if(b.candidates?.[0]?.content?.parts)for(let C of b.candidates[0].content.parts)C.text&&!C.thought&&(u+=C.text,E+=C.text);let O=E?Ts(E):0;e&&typeof e.onTokenChunk=="function"&&e.onTokenChunk(E,O),b.usageMetadata&&(m=b.usageMetadata)}}finally{clearInterval(w)}if(m){let v=m.totalTokenCount||0,b=m.cachedContentTokenCount||0,E=(m.candidatesTokenCount||0)+(a==="Google"&&m.thoughtsTokenCount||0);await Ut("tokens",v,a,t),b>0&&await Ut("cachedTokens",b,a,t),E>0&&await Ut("candidateTokens",E,a,t),Mo({provider:a,model:t,prompt:m.promptTokenCount||0,cached:b,output:E,reasoning:m.thoughtsTokenCount||0}),e&&typeof e.onUsage=="function"&&e.onUsage({totalTokenCount:v,cachedContentTokenCount:b,candidatesTokenCount:E})}return await vt("agent",a),{text:u,usageMetadata:m}}),el=async(e,t,n=null)=>{n=n||Ct(Co,{});try{let{aiProvider:s="Google"}=t;if(Object.values(n).flat().length<=5)return;let l=Object.keys(n).filter(y=>y!==e&&Array.isArray(n[y])&&n[y].length>2);if(l.length===0)return;let f=`You are a silent background process for the FluxFlow CLI Agent.
632
+ `)}if(process.stdout.isTTY)try{let Me=(await As())[c]?.name||"",X=Me&&!Me.startsWith("flow-")&&!Me.startsWith("Session ")?Me:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${X}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${X}\x07`)}catch{process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")}},Qa=e=>{let t=zt(e),n=_s?t:t.replace(Yr,o=>" ".repeat(o.length)).replace(qr,o=>" ".repeat(o.length));xo.lastIndex=0;let s;for(;(s=xo.exec(n))!==null;){let o=s.index+s[0].length-1,l=0,f=null,a=!1,m=!1;for(let g=o;g<n.length;g++){let u=t[g];if(!f&&(u==='"'||u==="'"||u==="`")?(f=u,a=!1):f&&u===f&&!a&&(f=null),!f&&(u==="("?l++:u===")"&&l--,l===0)){let h=g+1;for(;h<n.length&&/\s/.test(n[h]);)h++;if(h<n.length&&n[h]==="]"){m=!0,xo.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}},Jr=(e,t=!0)=>{let n=xo;n.lastIndex=0;let s="",o=0,l;for(;(l=n.exec(e))!==null;){let f=e.substring(o,l.index);s+=t&&o===0?zt(f):f;let a=l.index+l[0].length-1,m=0,g=null,u=-1;for(let h=a;h<e.length;h++){let y=e[h];if(g){if(y===g){let i=0;for(let c=h-1;c>=0&&e[c]==="\\";c--)i++;i%2===0&&(g=null)}}else if(y==='"'||y==="'"||y==="`")g=y;else if(y==="(")m++;else if(y===")"&&(m--,m===0)){let i=h+1;for(;i<e.length&&/\s/.test(e[i]);)i++;if(i<e.length&&e[i]==="]"){u=i;break}}}if(u!==-1)s+="[tool:functions."+l[1]+"()]",o=u+1,n.lastIndex=o;else{s+="[tool:functions."+l[1]+"(",o=e.length;break}}return o<e.length&&(s+=t&&o===0?zt(e.substring(o)):e.substring(o)),s},Za=(e,t,n)=>{let s=xo;s.lastIndex=0;let o="",l=0,f;for(;(f=s.exec(e))!==null;){let a=e.substring(l,f.index);o+=a.replace(t,n);let m=f.index+f[0].length-1,g=0,u=null,h=-1;for(let y=m;y<e.length;y++){let i=e[y];if(u){if(i===u){let c=0;for(let w=y-1;w>=0&&e[w]==="\\";w--)c++;c%2===0&&(u=null)}}else if(i==='"'||i==="'"||i==="`")u=i;else if(i==="(")g++;else if(i===")"&&(g--,g===0)){let c=y+1;for(;c<e.length&&/\s/.test(e[c]);)c++;if(c<e.length&&e[c]==="]"){h=c;break}}}if(h!==-1)o+=e.substring(f.index,h+1),l=h+1,s.lastIndex=l;else{o+=e.substring(f.index),l=e.length;break}}return l<e.length&&(o+=e.substring(l).replace(t,n)),o},Vr=e=>Jr(e,!0),el=e=>{if(!e)return e;let t={patchfile:"PatchFile",writefile:"WriteFile",readfile:"ReadFile",viewfile:"ReadFile",run:"Run",execcommand:"Run",searchkeyword:"SearchKeyword",codesearch:"CodeSearch",code_search:"CodeSearch",websearch:"WebSearch",webscrape:"WebScrape",readfolder:"ReadFolder",writepdf:"WritePDF",writedoc:"WriteDoc",writedocx:"WriteDoc",filemap:"FileMap",generateimage:"GenerateImage",todo:"Todo",goal:"Goal",askuser:"AskUser",ask:"AskUser"},n=o=>o.split("_").map(l=>l.charAt(0).toUpperCase()+l.slice(1)).join("");Wr.lastIndex=0;let s=e.replace(Wr,(o,l,f)=>{let a="";try{let u=JSON.parse(f.trim());u&&typeof u=="object"&&(a=Object.entries(u).map(([y,i])=>{let c=typeof i=="string"?i:JSON.stringify(i);return`${y}=${JSON.stringify(c)}`}).join(", "))}catch{let h=[],y=Ya;y.lastIndex=0;let i;for(;(i=y.exec(f))!==null;){let c=i[1],w=i[2]!==void 0?i[2]:i[0].split(":").slice(1).join(":").trim();h.push(`${c}=${JSON.stringify(w)}`)}h.length>0?a=h.join(", "):a=f.trim()}let m=l.toLowerCase().replace(/_/g,"");return`[tool:functions.${t[m]||n(l)}(${a})]`});return Hr.lastIndex=0,Gr.lastIndex=0,s=s.replace(Hr,""),s=s.replace(Gr,""),s},tl=/(?:path|query|url|keyword|command|method|title|task|id)\s*=\s*['"`]?\s*\.\.\.\s*['"`]?/i,nl=/^['"`]?\s*\.\.\.\s*['"`]?$/,kn=e=>{if(e==null)return!1;let t=String(e).trim();return t==="..."||t==="\u2026"||nl.test(t)},bo=e=>{if(!e)return[];let t=el(e),n=zt(t),s=[],o=_s?n:n.replace(Yr,a=>" ".repeat(a.length)).replace(qr,a=>" ".repeat(a.length)),l=Ua;l.lastIndex=0;let f;for(;(f=l.exec(o))!==null;){let a=f[1],m=f.index+f[0].length-1,g=0,u=null,h=-1,y=-1;for(let i=m;i<o.length;i++){let c=n[i];if(u){if(c===u){let w=0;for(let v=i-1;v>=0&&n[v]==="\\";v--)w++;w%2===0&&(u=null)}}else if(c==='"'||c==="'"||c==="`")u=c;else if(c==="(")g++;else if(c===")"&&(g--,g===0)){y=i;let w=i+1;for(;w<o.length&&/\s/.test(o[w]);)w++;if(w<o.length&&o[w]==="]"){h=w;break}}}if(h!==-1){let i=n.substring(m+1,y),c=n.substring(f.index,h+1),w=ie(i);kn(w.path)||kn(w.query)||kn(w.url)||kn(w.keyword)||kn(w.command)||kn(w.method)||kn(w.title)||kn(w.task)||kn(w.id)||tl.test(i)||s.push({fullMatch:c,toolName:a.trim(),args:i.trim()}),l.lastIndex=h+1}}return s},gf=(e,t={})=>{if(!e)return null;if(is=t,ni=new Kr({apiKey:e}),!globalThis.__perfCleanupInstalled){globalThis.__perfCleanupInstalled=!0,setInterval(()=>{typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks())},6e4);let n=globalThis.fetch;globalThis.fetch=async(...s)=>{try{let o=await n(...s);return typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),o}catch(o){throw typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),o}}}},rs=async(e,t,n,s,o="Fast",l=.75,f="agent")=>za(async()=>{let{aiProvider:a="Google",apiKey:m,mode:g}=e,u="",h=null,y=typeof n=="string"?[{role:"user",parts:[{text:n}]}]:n,i=new AbortController,c=i.signal,w=setInterval(()=>{kt&&(i.abort(),clearInterval(w))},100);try{let v;a==="Ollama"?v=Xs(m,t,y,s,o,g,ut(t),c,l,e.systemSettings?.ollamaEndpoint||"Cloud"):a==="OpenRouter"?v=Qo(m,t,y,s,o,g,ut(t),c,l):a==="DeepSeek"?v=zo(m,t,y,s,o,g,ut(t),c,l):a==="Mistral"?v=Jo(m,t,y,s,o,g,ut(t),c,l):a==="NVIDIA"?v=Xo(m,t,y,s,o,g,ut(t),c,l):a==="InferX"?v=Zo(m,t,y,s,o,g,ut(t),c,l):a==="SenseNova"?v=es(m,t,y,s,o,g,ut(t),c,l):a==="AIHubMix"?v=ts(m,t,y,s,o,g,ut(t),c,l):a==="Poolside"?v=ns(m,t,y,s,o,g,ut(t),c,l):a==="9router"||a==="9Router"?v=os(m,t,y,s,o,g,ut(t),c,l):a==="ExpLabs"||a==="ExperientialLabs"?v=ss(m,t,y,s,o,g,ut(t),c,l):a==="TokenHarbor"||a==="Token Harbor"||a==="tokenharbor"||a==="token_harbor"||a==="thk"?v=Qs(m,t,y,s,o,g,ut(t),c,l):a==="APInex"||a==="apinex"||a==="apx"?v=Zs(m,t,y,s,o,g,ut(t),c,l):v=await oi(m).models.generateContentStream({model:t,contents:y,config:{systemInstruction:s,temperature:l,thinkingConfig:(()=>{let O=(t||"").toLowerCase(),C=O.includes("gemma-4")||O.startsWith("gemma"),S=O.includes("gemini-3");if(C||S)return C?o.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:Qe.MINIMAL}:{includeThoughts:!0,thinkingLevel:Qe.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:O.includes("pro")?Qe.LOW:Qe.MINIMAL,Low:Qe.LOW,Medium:Qe.MEDIUM,Standard:Qe.MEDIUM,High:Qe.HIGH,xHigh:Qe.HIGH}[o]||Qe.MEDIUM};{let R={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[o]||2048;return R===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:R}}})()}},{signal:c});for await(let b of v){if(kt)throw new Error("Subagent task was cancelled.");if(e?.taskId&&typeof Yt<"u"){let C=Yt.find(S=>S.id===e.taskId);if(C&&C.status==="cancelled")throw new Error("Subagent task was cancelled.")}let E="";if(b.candidates?.[0]?.content?.parts)for(let C of b.candidates[0].content.parts)C.text&&!C.thought&&(u+=C.text,E+=C.text);let O=E?Ss(E):0;e&&typeof e.onTokenChunk=="function"&&e.onTokenChunk(E,O),b.usageMetadata&&(h=b.usageMetadata)}}finally{clearInterval(w)}if(h){let v=h.totalTokenCount||0,b=h.cachedContentTokenCount||0,E=(h.candidatesTokenCount||0)+(a==="Google"&&h.thoughtsTokenCount||0);await Wt("tokens",v,a,t),b>0&&await Wt("cachedTokens",b,a,t),E>0&&await Wt("candidateTokens",E,a,t),Io({provider:a,model:t,prompt:h.promptTokenCount||0,cached:b,output:E,reasoning:h.thoughtsTokenCount||0}),e&&typeof e.onUsage=="function"&&e.onUsage({totalTokenCount:v,cachedContentTokenCount:b,candidatesTokenCount:E})}return await vt("agent",a),{text:u,usageMetadata:h}}),ol=async(e,t,n=null)=>{n=n||Ct(vo,{});try{let{aiProvider:s="Google"}=t;if(Object.values(n).flat().length<=5)return;let l=Object.keys(n).filter(y=>y!==e&&Array.isArray(n[y])&&n[y].length>2);if(l.length===0)return;let f=`You are a silent background process for the FluxFlow CLI Agent.
633
633
  Your task is to summarize or merge temporary context memories from one or more past conversation sessions.
634
634
  For each Chat ID provided, you must output a tool call to save the consolidated summary.
635
635
 
@@ -644,7 +644,7 @@ Guidelines:
644
644
 
645
645
  Chats to process:
646
646
 
647
- `,a=Ct(xs,{});for(let y of l){let c=n[y].map(v=>`- ${v}`).join(`
647
+ `,a=Ct(bs,{});for(let y of l){let c=n[y].map(v=>`- ${v}`).join(`
648
648
  `),w=a[y];f+=`[Chat ID: ${y}]
649
649
  `,w?(f+=`- Existing Summary: "${w}"
650
650
  `,f+=`
@@ -654,8 +654,8 @@ ${c}
654
654
  `):f+=`-- Individual Memories:
655
655
  ${c}
656
656
 
657
- `}let h=0,g=5,u=!1,m=ge("gemma_janitor_fallback_google");for(s==="OpenRouter"&&(m=ge("janitor_open_router")),s==="DeepSeek"&&(m=ge("deepseek_level_1")),s==="Mistral"&&(m=ge("mistral_level_1")),s==="NVIDIA"&&(m=ge("nvidia_janitor_fallback")),s==="InferX"&&(m=ge("inferx_fallback")),s==="SenseNova"&&(m=ge("sensenova_fallback")),s==="AIHubMix"&&(m=ge("aihubmix_fallback")),s==="Poolside"&&(m=ge("poolside_fallback")),(s==="9router"||s==="9Router")&&(m=ge("9router_fallback"));h<=g&&!u;){h++;try{let i=(await is(t,m,f,null,"Fast",.75,"background")).text||"",c=xo(i);if(c.length===0)throw new Error("No tool calls detected in synthesis response");for(let w of c){let v=w.toolName;["saveSummary","saveSumary","SaveSummary","SaveSumary"].includes(v)&&await ho(v,w.args,{chatId:e})}u=!0}catch(y){if(h>=g)throw new Error(`Failed after ${g} attempts. Last error: ${y.message}`)}}}catch(s){let o=s instanceof Error?(()=>{try{return JSON.parse(JSON.parse(s.message).error.message).error.message}catch{return String(s)}})():String(s),l=ee.join(vn,"janitor");Ge.existsSync(l)||Ge.mkdirSync(l,{recursive:!0}),Ge.appendFileSync(ee.join(l,"error.log"),`[${new Date().toLocaleString()}] Past memory batch consolidation error: ${o}
658
- `)}},ff=async(e,t,n=!1)=>{let{chatId:s,aiProvider:o="Google"}=e,l=ee.join(Eo,"chat-summaries.json"),f=i=>i.filter(c=>(c.role==="user"||c.role==="agent"||c.role==="system")&&c.role!=="think"&&!c.isVisualFeedback&&!c.isMeta&&!c.isTerminalRecord&&!(c.text&&c.text.includes("[TERMINAL_RECORD]"))&&!String(c.id).startsWith("welcome")).map(c=>{let w=c.fullText||c.text||"",v=c.role==="system"||w.startsWith("[TOOL RESULT]:")||c.text&&c.text.startsWith("[TOOL RESULT]:"),b=w;return v&&(w.includes("[TOOL RESULT]:")||c.text&&c.text.includes("[TOOL RESULT]:"))?b="[TOOL RESULT]: ...truncated for summary":b=b.replace(/(\[(?:tool|agent):[a-zA-Z0-9_\.]+)\([\s\S]*?\)(\])/g,"$1(...)$2"),`[${v?"TOOL":c.role==="agent"?"AGENT":"USER"}]: ${b}`}).join(`
657
+ `}let m=0,g=5,u=!1,h=pe("gemma_janitor_fallback_google");for(s==="OpenRouter"&&(h=pe("janitor_open_router")),s==="DeepSeek"&&(h=pe("deepseek_level_1")),s==="Mistral"&&(h=pe("mistral_level_1")),s==="NVIDIA"&&(h=pe("nvidia_janitor_fallback")),s==="InferX"&&(h=pe("inferx_fallback")),s==="SenseNova"&&(h=pe("sensenova_fallback")),s==="AIHubMix"&&(h=pe("aihubmix_fallback")),s==="Poolside"&&(h=pe("poolside_fallback")),(s==="9router"||s==="9Router")&&(h=pe("9router_fallback"));m<=g&&!u;){m++;try{let i=(await rs(t,h,f,null,"Fast",.75,"background")).text||"",c=bo(i);if(c.length===0)throw new Error("No tool calls detected in synthesis response");for(let w of c){let v=w.toolName;["saveSummary","saveSumary","SaveSummary","SaveSumary"].includes(v)&&await po(v,w.args,{chatId:e})}u=!0}catch(y){if(m>=g)throw new Error(`Failed after ${g} attempts. Last error: ${y.message}`)}}}catch(s){let o=s instanceof Error?(()=>{try{return JSON.parse(JSON.parse(s.message).error.message).error.message}catch{return String(s)}})():String(s),l=te.join(Rn,"janitor");Ge.existsSync(l)||Ge.mkdirSync(l,{recursive:!0}),Ge.appendFileSync(te.join(l,"error.log"),`[${new Date().toLocaleString()}] Past memory batch consolidation error: ${o}
658
+ `)}},hf=async(e,t,n=!1)=>{let{chatId:s,aiProvider:o="Google"}=e,l=te.join(Co,"chat-summaries.json"),f=i=>i.filter(c=>(c.role==="user"||c.role==="agent"||c.role==="system")&&c.role!=="think"&&!c.isVisualFeedback&&!c.isMeta&&!c.isTerminalRecord&&!(c.text&&c.text.includes("[TERMINAL_RECORD]"))&&!String(c.id).startsWith("welcome")).map(c=>{let w=c.fullText||c.text||"",v=c.role==="system"||w.startsWith("[TOOL RESULT]:")||c.text&&c.text.startsWith("[TOOL RESULT]:"),b=w;return v&&(w.includes("[TOOL RESULT]:")||c.text&&c.text.includes("[TOOL RESULT]:"))?b="[TOOL RESULT]: ...truncated for summary":b=b.replace(/(\[(?:tool|agent):[a-zA-Z0-9_\.]+)\([\s\S]*?\)(\])/g,"$1(...)$2"),`[${v?"TOOL":c.role==="agent"?"AGENT":"USER"}]: ${b}`}).join(`
659
659
 
660
660
  `),a=async(i,c)=>{let w="You are an expert context summarizer. Summarize the provided chat history (which may include previous summaries, user instructions, agent outputs, and tool results) into a detailed, coherent, and highly technical summary of 1000 to 1500 words. Focus on preserving the architectural decisions made, current system state, task progress, and critical code details, chat messages, file changes. Under no circumstances exceed MAX 2000 words.",v=c?`Here is the previous summary:
661
661
  ${c}
@@ -666,205 +666,205 @@ ${i}
666
666
  Provide a new consolidated summary of the entire session.`:`Here is the conversation history:
667
667
  ${i}
668
668
 
669
- Provide a consolidated summary of the entire session.`,b=ge("gemma_janitor_fallback_google");o==="OpenRouter"&&(b=ge("janitor_open_router")),o==="DeepSeek"&&(b=ge("deepseek_level_1")),o==="Mistral"&&(b=ge("mistral_level_1")),o==="NVIDIA"&&(b=ge("nvidia_chat_summarizer_fallback")),o==="InferX"&&(b=ge("inferx_fallback")),o==="SenseNova"&&(b=ge("sensenova_fallback")),o==="AIHubMix"&&(b=ge("aihubmix_fallback")),o==="Poolside"&&(b=ge("poolside_fallback")),(o==="9router"||o==="9Router")&&(b=ge("9router_fallback")),(o==="ExpLabs"||o==="ExperientialLabs")&&(b=ge("explabs_fallback")||"deepseek-v4-pro-0813"),(o==="TokenHarbor"||o==="Token Harbor"||o==="tokenharbor"||o==="token_harbor"||o==="thk")&&(b=ge("tokenharbor_fallback")||"deepseek-v4.1-flash:free");let E=0,O=!1,C=null;for(;E<=3&&!O;){E++;try{C=await is(e,b,v,w,"Fast"),O=!0}catch{if(E>3){if(o==="Google")try{let R=ge("general_fallback");return(await is(e,R,v,w,"Fast")).text||""}catch{return""}return""}}}return C&&C.text||""},h=f(t),g=Ct(l,{}),u=g[s]||{summary:"",historyLength:0};typeof u=="string"&&(u={summary:u,historyLength:0});let m=u.summary||"",y=await a(h,m);if(y){u.summary=y;let i=Ya(t);return n?u.historyLength=(u.historyLength||0)+i:u.historyLength=i,g[s]=u,Jn(l,g),y}return null},uf=e=>{try{let t=ee.join(Eo,"chat-summaries.json");if(Ge.existsSync(t)){let n=Ct(t,{});n[e]&&(delete n[e],Jn(t,n))}}catch{}},gf=async function*(e,t,n,s,o){let{profile:l,thinkingLevel:f,mode:a,janitorModel:h,chatId:g,isPlayground:u,systemSettings:m,sessionStats:y,aiProvider:i="Google",apiTier:c,wildcardTooling:w}=n,v=gt(e);if(!ti&&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,E=t[t.length-1].text,O=ee.join(Eo,"chat-summaries.json"),C=!1,S=t.filter(k=>k.role==="user").length===1,R=E.includes("[TITLE-UPDATE]"),L=S||R,x=E.replace(/\[TITLE-UPDATE\]/g,"").trim();x=x.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),yield{type:"status",content:"[start]"},yield{type:"status",content:"Gathering Context"},await Io.startTransaction(g,x),m?.advanceRollback&&await io.takeInitialSnapshot(g),kt=!1;let d=null;try{let k=new AbortController;d=setInterval(()=>{kt&&(k.abort(),d&&(clearInterval(d),d=null))},400);let r=[...t.slice(0,-1)];{let Ne=Ct(O,{})[g]||{summary:"",historyLength:0};if(Ne.summary&&Ne.historyLength>0){let Jt=0,et=[];for(let Re=0;Re<r.length;Re++){let rt=r[Re];(rt.role==="user"||rt.role==="agent"||rt.role==="system")&&!String(rt.id).startsWith("welcome")&&!rt.isMeta&&Jt++,Jt>Ne.historyLength&&et.push(rt)}r=et}}r=r.map(G=>{if(G.role==="user"&&G.text){let Ne=G.text.match(/\[USER\]([\s\S]*?)\[\/USER\]/);if(Ne)return{...G,text:Ne[1].trim()}}return{...G}});let T=process.env.HIGH_CONTEXT,A=process.env.GOOGLE_GEMMA_NONSENSE==="true"||process.env.GOOGLE_GEMMA_NONSENSE===!0||!1,$={"16k":16e3,"32k":32e3,"64k":64e3,"128k":128e3,"256k":256e3,"512k":512e3,"1M":1e6}[m?.contextLength]||256e3;if(T&&T!=="false"){let G=parseInt(T,10);!isNaN(G)&&G>=0&&G<=1e6&&($=G)}if((i==="NVIDIA"&&(e?.includes("gpt")||e?.includes("qwen")||e?.includes("medium")||e.includes("muse"))||i==="Mistral")&&($=126e3),i==="Google"&&e?.includes("gemma")&&A&&($=16e3),(y?.tokens||0)>$){yield{type:"text",content:"\u2726 Maximum Context Limit Reached. Start a new chat."};return}if(S&&b){let G=Ct(Co,{});Object.values(G).flat().length>5&&(yield{type:"status",content:"Condensing past chat memories"},await el(g,n,G))}let M=Ct(Co,{}),te=Ct(xs,{}),le=Object.entries(M).filter(([G])=>G!==g).flatMap(([G,Ne])=>Ne),re=[...Object.entries(te).filter(([G])=>G!==g).slice(-20).map(([G,Ne])=>`[Chat Summary]: ${Ne}`),...le].map(G=>`- ${G}`).join(`
670
- `),We=Ct(Bn,[]).map(G=>`- ${G.memory}`).join(`
671
- `),P=(y?.tokens||0)>=1e4,F=ar(re,We,b,P),ve=new Date,z=ve.getFullYear(),B=ve.toLocaleString("en-US",{month:"short"}).toUpperCase(),Y=String(ve.getDate()).padStart(2,"0"),fe=ve.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}),Ae=`${z}-${B}-${Y}, ${fe}`,Ee=`${fe}`,$e=[".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"],Rt=G=>{try{return Ge.readdirSync(G,{withFileTypes:!0})}catch{return[]}},wn=(G,Ne={value:0},Jt=1)=>{if(Ne.value>6200||Jt>7)return Ne.value;let et=Rt(G);for(let Re of et){if(Ne.value>6200)break;$e.includes(Re.name)||Re.name.startsWith(".")||Re.isDirectory()&&(Ne.value++,wn(ee.join(G,Re.name),Ne,Jt+1))}return Ne.value},zt=(G,Ne)=>m?.indentationTree!==!1?Ys(G,Ne,1,Rt,$e):zs(G,Ne,"",1,Rt,$e),dt=wn(process.cwd()),me=10;dt>3072||dt>2304?me=1:dt>1536?me=2:dt>768?me=3:dt>384?me=5:dt>192?me=6:dt>96?me=7:(dt>48||dt>24)&&(me=9);let he=Ct(bs,{}),ie=he[g],Ot=ie?ie!==process.cwd():!1;he[g]=process.cwd(),Jn(bs,he);let jn=Ct(O,{}),_t=jn[g]||{summary:"",historyLength:0};typeof _t=="string"&&(_t={summary:_t,historyLength:0});let qr=t.filter(G=>(G.role==="user"||G.role==="agent"||G.role==="system")&&!String(G.id).startsWith("welcome")&&!G.isMeta).length;_t.historyLength&&qr<_t.historyLength&&(_t.summary="",_t.historyLength=0,jn[g]=_t,Jn(O,jn));let bo=typeof _t=="object"?_t.summary||"":_t||"",oi=r.length>0;oi&&bo&&r[0]&&(r[0].role==="user"||r[0].role==="system")&&(r[0].text.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")||(r[0].text=`[SYSTEM METADATA]
669
+ Provide a consolidated summary of the entire session.`,b=pe("gemma_janitor_fallback_google");o==="OpenRouter"&&(b=pe("janitor_open_router")),o==="DeepSeek"&&(b=pe("deepseek_level_1")),o==="Mistral"&&(b=pe("mistral_level_1")),o==="NVIDIA"&&(b=pe("nvidia_chat_summarizer_fallback")),o==="InferX"&&(b=pe("inferx_fallback")),o==="SenseNova"&&(b=pe("sensenova_fallback")),o==="AIHubMix"&&(b=pe("aihubmix_fallback")),o==="Poolside"&&(b=pe("poolside_fallback")),(o==="9router"||o==="9Router")&&(b=pe("9router_fallback")),(o==="ExpLabs"||o==="ExperientialLabs")&&(b=pe("explabs_fallback")||"deepseek-v4-pro-0813"),(o==="TokenHarbor"||o==="Token Harbor"||o==="tokenharbor"||o==="token_harbor"||o==="thk")&&(b=pe("tokenharbor_fallback")||"deepseek-v4.1-flash:free");let E=0,O=!1,C=null;for(;E<=3&&!O;){E++;try{C=await rs(e,b,v,w,"Fast"),O=!0}catch{if(E>3){if(o==="Google")try{let R=pe("general_fallback");return(await rs(e,R,v,w,"Fast")).text||""}catch{return""}return""}}}return C&&C.text||""},m=f(t),g=Ct(l,{}),u=g[s]||{summary:"",historyLength:0};typeof u=="string"&&(u={summary:u,historyLength:0});let h=u.summary||"",y=await a(m,h);if(y){u.summary=y;let i=Ja(t);return n?u.historyLength=(u.historyLength||0)+i:u.historyLength=i,g[s]=u,Jn(l,g),y}return null},mf=e=>{try{let t=te.join(Co,"chat-summaries.json");if(Ge.existsSync(t)){let n=Ct(t,{});n[e]&&(delete n[e],Jn(t,n))}}catch{}},pf=async function*(e,t,n,s,o){let{profile:l,thinkingLevel:f,mode:a,janitorModel:m,chatId:g,isPlayground:u,systemSettings:h,sessionStats:y,aiProvider:i="Google",apiTier:c,wildcardTooling:w}=n,v=ut(e);if(!ni&&i==="Google")throw new Error("AI not initialized");let b=process.env.NVIDIA_BASE_URL||n?.aiProvider==="Ollama"||n?.aiProvider==="InferX"||n?.aiProvider==="SenseNova"||n?.aiProvider==="AIHubMix"||n?.aiProvider==="Poolside"||n?.aiProvider==="9router"||n?.aiProvider==="ExpLabs"||n?.aiProvider==="ExperientialLabs"||n?.aiProvider==="TokenHarbor"||n?.aiProvider==="Token Harbor"||n?.aiProvider==="tokenharbor"||n?.aiProvider==="token_harbor"||n?.aiProvider==="thk"||n?.aiProvider==="APInex"||n?.aiProvider==="apinex"||n?.aiProvider==="apx"?!1:h?.memory!==!1,E=t[t.length-1].text,O=te.join(Co,"chat-summaries.json"),C=!1,S=t.filter(k=>k.role==="user").length===1,R=E.includes("[TITLE-UPDATE]"),L=S||R,x=E.replace(/\[TITLE-UPDATE\]/g,"").trim();x=x.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),yield{type:"status",content:"[start]"},yield{type:"status",content:"Gathering Context"},await Do.startTransaction(g,x),h?.advanceRollback&&await ro.takeInitialSnapshot(g),kt=!1;let d=null;try{let k=new AbortController;d=setInterval(()=>{kt&&(k.abort(),d&&(clearInterval(d),d=null))},400);let r=[...t.slice(0,-1)];{let $e=Ct(O,{})[g]||{summary:"",historyLength:0};if($e.summary&&$e.historyLength>0){let Xt=0,Ze=[];for(let Ie=0;Ie<r.length;Ie++){let it=r[Ie];(it.role==="user"||it.role==="agent"||it.role==="system")&&!String(it.id).startsWith("welcome")&&!it.isMeta&&Xt++,Xt>$e.historyLength&&Ze.push(it)}r=Ze}}r=r.map(H=>{if(H.role==="user"&&H.text){let $e=H.text.match(/\[USER\]([\s\S]*?)\[\/USER\]/);if($e)return{...H,text:$e[1].trim()}}return{...H}});let T=process.env.HIGH_CONTEXT,A=process.env.GOOGLE_GEMMA_NONSENSE==="true"||process.env.GOOGLE_GEMMA_NONSENSE===!0||!1,$={"16k":16e3,"32k":32e3,"64k":64e3,"128k":128e3,"256k":256e3,"512k":512e3,"1M":1e6}[h?.contextLength]||256e3;if(T&&T!=="false"){let H=parseInt(T,10);!isNaN(H)&&H>=0&&H<=1e6&&($=H)}if((i==="NVIDIA"&&(e?.includes("gpt")||e?.includes("qwen")||e?.includes("medium")||e.includes("muse"))||i==="Mistral")&&($=126e3),i==="Google"&&e?.includes("gemma")&&A&&($=16e3),(y?.tokens||0)>$){yield{type:"text",content:"\u2726 Maximum Context Limit Reached. Start a new chat."};return}if(S&&b){let H=Ct(vo,{});Object.values(H).flat().length>5&&(yield{type:"status",content:"Condensing past chat memories"},await ol(g,n,H))}let I=Ct(vo,{}),ne=Ct(bs,{}),fe=Object.entries(I).filter(([H])=>H!==g).flatMap(([H,$e])=>$e),ce=[...Object.entries(ne).filter(([H])=>H!==g).slice(-20).map(([H,$e])=>`[Chat Summary]: ${$e}`),...fe].map(H=>`- ${H}`).join(`
670
+ `),Ue=Ct(Un,[]).map(H=>`- ${H.memory}`).join(`
671
+ `),P=(y?.tokens||0)>=1e4,B=dr(ce,Ue,b,P),Me=new Date,X=Me.getFullYear(),U=Me.toLocaleString("en-US",{month:"short"}).toUpperCase(),K=String(Me.getDate()).padStart(2,"0"),he=Me.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}),Ce=`${X}-${U}-${K}, ${he}`,ve=`${he}`,Pe=[".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"],Rt=H=>{try{return Ge.readdirSync(H,{withFileTypes:!0})}catch{return[]}},wn=(H,$e={value:0},Xt=1)=>{if($e.value>6200||Xt>7)return $e.value;let Ze=Rt(H);for(let Ie of Ze){if($e.value>6200)break;Pe.includes(Ie.name)||Ie.name.startsWith(".")||Ie.isDirectory()&&($e.value++,wn(te.join(H,Ie.name),$e,Xt+1))}return $e.value},Jt=(H,$e)=>h?.indentationTree!==!1?qs(H,$e,1,Rt,Pe):Js(H,$e,"",1,Rt,Pe),ct=wn(process.cwd()),ye=10;ct>3072||ct>2304?ye=1:ct>1536?ye=2:ct>768?ye=3:ct>384?ye=5:ct>192?ye=6:ct>96?ye=7:(ct>48||ct>24)&&(ye=9);let xe=Ct(ks,{}),ae=xe[g],Ot=ae?ae!==process.cwd():!1;xe[g]=process.cwd(),Jn(ks,xe);let Vn=Ct(O,{}),_t=Vn[g]||{summary:"",historyLength:0};typeof _t=="string"&&(_t={summary:_t,historyLength:0});let Xr=t.filter(H=>(H.role==="user"||H.role==="agent"||H.role==="system")&&!String(H.id).startsWith("welcome")&&!H.isMeta).length;_t.historyLength&&Xr<_t.historyLength&&(_t.summary="",_t.historyLength=0,Vn[g]=_t,Jn(O,Vn));let ko=typeof _t=="object"?_t.summary||"":_t||"",si=r.length>0;si&&ko&&r[0]&&(r[0].role==="user"||r[0].role==="system")&&(r[0].text.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")||(r[0].text=`[SYSTEM METADATA]
672
672
  **CONTEXT SUMMARY OF PREVIOUS TURNS (PRIORITY: DYNAMIC)**
673
- ${bo}
673
+ ${ko}
674
674
 
675
- [USER] ${r[0].text}`,yield{type:"summary_injected",content:{id:r[0].id,text:r[0].text}}));let rs=bo&&!oi?`
675
+ [USER] ${r[0].text}`,yield{type:"summary_injected",content:{id:r[0].id,text:r[0].text}}));let as=ko&&!si?`
676
676
  [SYSTEM METADATA]
677
677
  **CONTEXT SUMMARY OF PREVIOUS TURNS**
678
- ${bo}
679
- `:"",si=!!m?.dynamicDirAwareness,zr=`${g}|${i}|${f}|${e}|${l}|${si}`,ii=!si&&Hn.key===zr&&Hn.value?"":`
678
+ ${ko}
679
+ `:"",ii=!!h?.dynamicDirAwareness,Qr=`${g}|${i}|${f}|${e}|${l}|${ii}`,ri=!ii&&Gn.key===Qr&&Gn.value?"":`
680
680
  **Directory Structure**
681
681
  CWD: `+process.cwd()+`${u?" [PLAYGROUND MODE]":""}
682
- `+zt(process.cwd(),me),yt=await Un(),un="";if(Ko()&&yt.file_focused!=="none"){un=`
682
+ `+Jt(process.cwd(),ye),yt=await Wn(),un="";if(Yo()&&yt.file_focused!=="none"){un=`
683
683
  [Additional IDE Context]
684
- `;let G=ee.relative(process.cwd(),yt.file_focused),Ne=(yt.opened_editors||[]).map(et=>{let Re=ee.relative(process.cwd(),et);return Re.startsWith("..")?`[External] ${ee.basename(et)}`:Re});if(un+=`Focused File: ${G}
684
+ `;let H=te.relative(process.cwd(),yt.file_focused),$e=(yt.opened_editors||[]).map(Ze=>{let Ie=te.relative(process.cwd(),Ze);return Ie.startsWith("..")?`[External] ${te.basename(Ze)}`:Ie});if(un+=`Focused File: ${H}
685
685
  Cursor Line: ${yt.cursor_line}
686
- `,yt.selected){let et=yt.selected,Re=et.split(`
687
- `);Re.length>256&&(et=Re.slice(0,240).join(`
686
+ `,yt.selected){let Ze=yt.selected,Ie=Ze.split(`
687
+ `);Ie.length>256&&(Ze=Ie.slice(0,240).join(`
688
688
  `)+`
689
689
  ... [truncated] ...
690
- `+Re.slice(-16).join(`
691
- `)),et.length>2048&&(et=et.slice(0,1920)+`
690
+ `+Ie.slice(-16).join(`
691
+ `)),Ze.length>2048&&(Ze=Ze.slice(0,1920)+`
692
692
  ... [truncated] ...
693
- `+et.slice(-128)),un+=`Current Selection: "${et}"
694
- `}if(yt.manual_edits){let Re=yt.manual_edits.split(`
695
- `),rt=[],ot=null;for(let j of Re)j.trim()&&(j.startsWith(" Line ")?ot&&ot.edits.push(j):(ot={path:j.endsWith(":")?j.slice(0,-1):j,edits:[]},rt.push(ot)));for(let j of rt)j.edits.length>80&&(j.edits=j.edits.slice(-80)),j.originalEditsCount=j.edits.length;let at=(j,je)=>je.reduce((Ce,mt)=>{let Mt=yt.file_focused&&(mt.path===yt.file_focused||ee.resolve(process.cwd(),mt.path)===ee.resolve(yt.file_focused))?Math.ceil(j*1.2):j;return Ce+Math.min(mt.edits.length,Mt)},0),xe=80;if(at(80,rt)>300){let j=!1;for(let je=80;je>=10;je--)if(at(je,rt)<=300){xe=je,j=!0;break}j||(xe=10)}let qe=[...rt];if(xe===10&&at(10,qe)>500)for(;qe.length>0&&at(10,qe)>500;){let j=0,je=qe[0].originalEditsCount;for(let Ce=1;Ce<qe.length;Ce++)qe[Ce].originalEditsCount<je&&(je=qe[Ce].originalEditsCount,j=Ce);qe.splice(j,1)}for(let j of qe){let Ce=yt.file_focused&&(j.path===yt.file_focused||ee.resolve(process.cwd(),j.path)===ee.resolve(yt.file_focused))?Math.ceil(xe*1.2):xe;j.edits.length>Ce&&(j.edits=j.edits.slice(-Ce))}for(let j of qe){let je=`${j.path}:
696
- ${j.edits.join(`
697
- `)}`;for(;j.edits.length>0&&je.length>4*768;)j.edits.shift(),je=`${j.path}:
698
- ${j.edits.join(`
699
- `)}`;je.length>4*768?j.stringRepresentation="... "+je.slice(-(4*768-4)):j.stringRepresentation=je}let rn=qe.map(j=>j.stringRepresentation).join(`
700
- `);for(;qe.length>0&&rn.length>4*2048;){qe[0].edits.length>0?qe[0].edits.shift():qe.shift();for(let j of qe){let je=`${j.path}:
701
- ${j.edits.join(`
702
- `)}`;je.length>4*768?j.stringRepresentation="... "+je.slice(-(4*768-4)):j.stringRepresentation=je}rn=qe.map(j=>j.stringRepresentation).join(`
703
- `)}rn.length>4*2048&&(rn="... "+rn.slice(-(4*2048-4))),un+=`Recent Manual Edits:
704
- ${rn}
705
- `}Ne.length>0&&(un+=`All Opened Editors: ${Ne.join(", ")}`),yt.diagnostics&&(un+=`
693
+ `+Ze.slice(-128)),un+=`Current Selection: "${Ze}"
694
+ `}if(yt.manual_edits){let Ie=yt.manual_edits.split(`
695
+ `),it=[],nt=null;for(let G of Ie)G.trim()&&(G.startsWith(" Line ")?nt&&nt.edits.push(G):(nt={path:G.endsWith(":")?G.slice(0,-1):G,edits:[]},it.push(nt)));for(let G of it)G.edits.length>80&&(G.edits=G.edits.slice(-80)),G.originalEditsCount=G.edits.length;let rt=(G,je)=>je.reduce((Re,gt)=>{let Mt=yt.file_focused&&(gt.path===yt.file_focused||te.resolve(process.cwd(),gt.path)===te.resolve(yt.file_focused))?Math.ceil(G*1.2):G;return Re+Math.min(gt.edits.length,Mt)},0),we=80;if(rt(80,it)>300){let G=!1;for(let je=80;je>=10;je--)if(rt(je,it)<=300){we=je,G=!0;break}G||(we=10)}let qe=[...it];if(we===10&&rt(10,qe)>500)for(;qe.length>0&&rt(10,qe)>500;){let G=0,je=qe[0].originalEditsCount;for(let Re=1;Re<qe.length;Re++)qe[Re].originalEditsCount<je&&(je=qe[Re].originalEditsCount,G=Re);qe.splice(G,1)}for(let G of qe){let Re=yt.file_focused&&(G.path===yt.file_focused||te.resolve(process.cwd(),G.path)===te.resolve(yt.file_focused))?Math.ceil(we*1.2):we;G.edits.length>Re&&(G.edits=G.edits.slice(-Re))}for(let G of qe){let je=`${G.path}:
696
+ ${G.edits.join(`
697
+ `)}`;for(;G.edits.length>0&&je.length>4*768;)G.edits.shift(),je=`${G.path}:
698
+ ${G.edits.join(`
699
+ `)}`;je.length>4*768?G.stringRepresentation="... "+je.slice(-(4*768-4)):G.stringRepresentation=je}let an=qe.map(G=>G.stringRepresentation).join(`
700
+ `);for(;qe.length>0&&an.length>4*2048;){qe[0].edits.length>0?qe[0].edits.shift():qe.shift();for(let G of qe){let je=`${G.path}:
701
+ ${G.edits.join(`
702
+ `)}`;je.length>4*768?G.stringRepresentation="... "+je.slice(-(4*768-4)):G.stringRepresentation=je}an=qe.map(G=>G.stringRepresentation).join(`
703
+ `)}an.length>4*2048&&(an="... "+an.slice(-(4*2048-4))),un+=`Recent Manual Edits:
704
+ ${an}
705
+ `}$e.length>0&&(un+=`All Opened Editors: ${$e.join(", ")}`),yt.diagnostics&&(un+=`
706
706
  **Active File Errors**:
707
707
  ${yt.diagnostics}
708
708
  `),(x.toLowerCase().includes("lint")||x.toLowerCase().includes("warning"))&&yt.warnings&&(un+=`
709
709
  **Lint Warnings**:
710
710
  ${yt.warnings}
711
- `)}let ri=x.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),ai=/(?:\\)?@\[([^\]]+)\]/g,as,ls=[];for(ai.lastIndex=0;(as=ai.exec(ri))!==null;){let G=as[0].startsWith("\\");ls.push({tag:as[1],isEscaped:G})}let cs=[],ko=null;for(let G=0;G<ls.length;G++){let{tag:Ne,isEscaped:Jt}=ls[G];if(!Jt)try{let et=Ne.trim().replace(/^["']|["']$/g,""),Re=/[:#]L?(\d+)(?:-L?(\d+))?$/i,rt=et.match(Re),ot=et,at=null,xe=null;rt&&(at=parseInt(rt[1],10),xe=rt[2]?parseInt(rt[2],10):at,ot=et.slice(0,rt.index));let qe=ee.resolve(process.cwd(),ot);if(Ge.existsSync(qe)&&Ge.statSync(qe).isFile()){let j=ot.toLowerCase(),je=j.endsWith(".pdf"),Ce=j.endsWith(".docx")||j.endsWith(".doc")||j.endsWith(".ppt")||j.endsWith(".pptx")||j.endsWith(".xls")||j.endsWith(".xlsx"),mt=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(j),Sn=mt||je||Ce,Mt=i==="Google"||gt(e);if(Sn&&!Mt){let Pt=`\u2718 Unsupported Modality: ${ee.basename(ot)}`,ze=115;process.stdout.isTTY&&(ze=process.stdout.columns-5||120);let be=[Pt],Xe=Math.max(...be.map(gn=>gn.length)),An=Math.min(Xe+4,ze),On=be.map(gn=>`${gn.padEnd(An-2).substring(0,An-2)}`).join(`
712
- `);yield{type:"visual_feedback",content:Yt(`${On}
713
- `)};continue}if(at===null&&!Sn){let Pt=0;try{Pt=Ge.readFileSync(qe,"utf8").split(/\r\n|\r|\n/).length}catch{}if(Pt>300){let ze=`\u21B7 Skipped (Too Large): ${ee.basename(ot)}`,be=115;process.stdout.isTTY&&(be=process.stdout.columns-5||120);let Xe=Math.min(ze.length+4,be),An=ze.padEnd(Xe-2).substring(0,Xe-2);yield{type:"visual_feedback",content:Yt(`${An}
714
- `)};continue}}let an=at!==null?at:1,_n=xe!==null?xe:at!==null?at:an+299;_n-an>300&&(_n=an+300);let Zn=`path=${JSON.stringify(ot)}, startLine=${an}, endLine=${_n}`,en=await _i(Zn,{isMultiModal:Mt}),xt=!1,tt="",Lt=null;if(typeof en=="string"?en.trim().startsWith("ERROR")?xt=!0:tt=en:en&&typeof en=="object"&&en.binaryPart?(Lt=en.binaryPart,tt=en.text||""):xt=!0,!xt){let Pt="";if(mt?(Pt=`\u2714 Processed: ${ee.basename(ot)}`,ko=Lt):je||Ce?(Pt=`\u2714 Auto-Analysed: ${ee.basename(ot)}`,ko=Lt):(Pt=`\u2714 Auto-Read: ${ee.basename(ot)}`,cs.push(tt)),Pt){let ze=115;process.stdout.isTTY&&(ze=process.stdout.columns-5||120);let be=[Pt],Xe=Math.max(...be.map(gn=>gn.length)),An=Math.min(Xe+4,ze),On=be.map(gn=>`${gn.padEnd(An-2).substring(0,An-2)}`).join(`
715
- `);yield{type:"visual_feedback",content:Yt(`${On}
716
- `)}}}}}catch{}}let ds="";cs.length>0&&(ds=`
711
+ `)}let ai=x.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),li=/(?:\\)?@\[([^\]]+)\]/g,ls,cs=[];for(li.lastIndex=0;(ls=li.exec(ai))!==null;){let H=ls[0].startsWith("\\");cs.push({tag:ls[1],isEscaped:H})}let ds=[],wo=null;for(let H=0;H<cs.length;H++){let{tag:$e,isEscaped:Xt}=cs[H];if(!Xt)try{let Ze=$e.trim().replace(/^["']|["']$/g,""),Ie=/[:#]L?(\d+)(?:-L?(\d+))?$/i,it=Ze.match(Ie),nt=Ze,rt=null,we=null;it&&(rt=parseInt(it[1],10),we=it[2]?parseInt(it[2],10):rt,nt=Ze.slice(0,it.index));let qe=te.resolve(process.cwd(),nt);if(Ge.existsSync(qe)&&Ge.statSync(qe).isFile()){let G=nt.toLowerCase(),je=G.endsWith(".pdf"),Re=G.endsWith(".docx")||G.endsWith(".doc")||G.endsWith(".ppt")||G.endsWith(".pptx")||G.endsWith(".xls")||G.endsWith(".xlsx"),gt=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(G),Sn=gt||je||Re,Mt=i==="Google"||ut(e);if(Sn&&!Mt){let Pt=`\u2718 Unsupported Modality: ${te.basename(nt)}`,ze=115;process.stdout.isTTY&&(ze=process.stdout.columns-5||120);let Te=[Pt],Je=Math.max(...Te.map(gn=>gn.length)),An=Math.min(Je+4,ze),Ln=Te.map(gn=>`${gn.padEnd(An-2).substring(0,An-2)}`).join(`
712
+ `);yield{type:"visual_feedback",content:qt(`${Ln}
713
+ `)};continue}if(rt===null&&!Sn){let Pt=0;try{Pt=Ge.readFileSync(qe,"utf8").split(/\r\n|\r|\n/).length}catch{}if(Pt>300){let ze=`\u21B7 Skipped (Too Large): ${te.basename(nt)}`,Te=115;process.stdout.isTTY&&(Te=process.stdout.columns-5||120);let Je=Math.min(ze.length+4,Te),An=ze.padEnd(Je-2).substring(0,Je-2);yield{type:"visual_feedback",content:qt(`${An}
714
+ `)};continue}}let ln=rt!==null?rt:1,_n=we!==null?we:rt!==null?rt:ln+299;_n-ln>300&&(_n=ln+300);let Zn=`path=${JSON.stringify(nt)}, startLine=${ln}, endLine=${_n}`,tn=await Ci(Zn,{isMultiModal:Mt}),xt=!1,et="",Lt=null;if(typeof tn=="string"?tn.trim().startsWith("ERROR")?xt=!0:et=tn:tn&&typeof tn=="object"&&tn.binaryPart?(Lt=tn.binaryPart,et=tn.text||""):xt=!0,!xt){let Pt="";if(gt?(Pt=`\u2714 Processed: ${te.basename(nt)}`,wo=Lt):je||Re?(Pt=`\u2714 Auto-Analysed: ${te.basename(nt)}`,wo=Lt):(Pt=`\u2714 Auto-Read: ${te.basename(nt)}`,ds.push(et)),Pt){let ze=115;process.stdout.isTTY&&(ze=process.stdout.columns-5||120);let Te=[Pt],Je=Math.max(...Te.map(gn=>gn.length)),An=Math.min(Je+4,ze),Ln=Te.map(gn=>`${gn.padEnd(An-2).substring(0,An-2)}`).join(`
715
+ `);yield{type:"visual_feedback",content:qt(`${Ln}
716
+ `)}}}}}catch{}}let fs="";ds.length>0&&(fs=`
717
717
  [Tagged File Contents] Auto Read User Tagged files by System, No need to re-read
718
- `+cs.join(`
718
+ `+ds.join(`
719
719
 
720
720
  `)+`
721
721
  [Tagged File Contents]
722
- `);let li=ri.replace(/\\(@\[[^\]]+\])/g,"$1"),ci=w?`[system] exact tool string format [tool:ToolName(arg="value")] in chat [/system]
722
+ `);let ci=ai.replace(/\\(@\[[^\]]+\])/g,"$1"),di=w?`[system] exact tool string format [tool:ToolName(arg="value")] in chat [/system]
723
723
  You cannot execute tools
724
724
  Instead, output in chat the exact string you WOULD have produced & wait for system response
725
- `:"",Jr=process.env.forcedReasoning||!1,di=f!=="Fast"&&(i==="Mistral"&&!Ro(e)||f!=="High"&&i==="Google")?`${i==="Mistral"&&!Ro(e)||e.toLowerCase().startsWith("gemma")||Jr?`[system] strictly follow thinking policy as high priority. do not start a response without <think>...</think> [/system]
726
- `:""}`:"",wo="",fi=!!m?.autoExcludeMetadata,Xr=!!(un||ds||ci||rs||F||di||Ot||m?.dynamicDirAwareness||m?.autoTruncateResults||b);fi&&!Xr?wo=li.trim():wo=`[System Metadata]
727
- Time: ${fi?Ee:Ae}${m?.dynamicDirAwareness?ii:""}${Ot?`
728
- WARNING: CWD Changed from previous: "${ie}" to current: "${process.cwd()}", write change in chat to avoid future path mismatches
729
- `:""}${F}${un}
725
+ `:"",Zr=process.env.forcedReasoning||!1,fi=f!=="Fast"&&(i==="Mistral"&&!Mo(e)||f!=="High"&&i==="Google")?`${i==="Mistral"&&!Mo(e)||e.toLowerCase().startsWith("gemma")||Zr?`[system] strictly follow thinking policy as high priority. do not start a response without <think>...</think> [/system]
726
+ `:""}`:"",To="",ui=!!h?.autoExcludeMetadata,ea=!!(un||fs||di||as||B||fi||Ot||h?.dynamicDirAwareness||h?.autoTruncateResults||b);ui&&!ea?To=ci.trim():To=`[System Metadata]
727
+ Time: ${ui?ve:Ce}${h?.dynamicDirAwareness?ri:""}${Ot?`
728
+ WARNING: CWD Changed from previous: "${ae}" to current: "${process.cwd()}", write change in chat to avoid future path mismatches
729
+ `:""}${B}${un}
730
730
  [/Metadata]
731
- ${rs}${di}${ds}${ci}[user prompt] ${li.trim()} [/user prompt]`.trim();let ui={role:"user",text:wo};ko&&(ui.binaryPart=ko),r.forEach(G=>{G.text&&G.role==="agent"&&(G.text=qt(G.text))}),r.push(ui),rs&&t[t.length-1]?.id&&(yield{type:"summary_injected",content:{id:t[t.length-1].id,text:wo}});let Zt=null,Tn=a==="Flux"?50:15;Tn=a.toLowerCase().includes("cu")?75:Tn;let Qr=Math.floor(Tn/2),gi=0,sn=16;yield{type:"status",content:"Connecting"},kt=!1;let fs=[],To=!1,mi=!1;for(let G=0;G<=Tn;G++){let Ne=Math.floor(Tn*.95);if(G>=Ne&&gi<Ne&&typeof n?.onAskUser=="function"){gi=Ne;try{let ue="Agent has been running for a long time. Do you want to continue execution?",we=[{id:"continue",label:"Continue",description:"Add few more steps"},{id:"cancel",label:"Cancel",description:"Stop extending and finish current turn limit"}],X=await n.onAskUser(ue,we);X&&(X.toLowerCase().includes("continue")||X==="Continue")&&(Tn+=Qr)}catch{}}let Jt=await ws("agent",n);if(!Jt.allowed)throw new Error(Jt.reason||`Budget Exhausted for Provider (${i||"Agent"})`);let et=[];if(To=!1,a==="ICU"||a==="FluxCU")try{yield{type:"status",content:"Capturing Screen"},await new Promise(X=>setTimeout(X,1e3));let{captureGriddedScreenshot:ue}=await import("./screen_grid-EIPLWNEM.js"),we=await ue();if(we&&we.base64){let X="[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]",$t={inlineData:{mimeType:we.mimeType,data:we.base64}},It=m?.imageHistoryCU||"Standard",At=It==="Low"?1:It==="Extended"?5:3,Xt=r.filter(Ye=>Array.isArray(Ye.parts)&&Ye.parts.some(Nt=>Nt.inlineData));if(Xt.length>=At){let Ye=Xt.length-At+1;for(let Nt=0;Nt<Ye;Nt++){let Et=Xt[Nt];Array.isArray(Et.parts)&&(Et.parts=Et.parts.filter(wt=>!wt.inlineData))}}if(r.length>0&&r[r.length-1].role==="user"){let Ye=r[r.length-1];typeof Ye.text=="string"&&(Ye.text+=`
731
+ ${as}${fi}${fs}${di}[user prompt] ${ci.trim()} [/user prompt]`.trim();let gi={role:"user",text:To};wo&&(gi.binaryPart=wo),r.forEach(H=>{H.text&&H.role==="agent"&&(H.text=zt(H.text))}),r.push(gi),as&&t[t.length-1]?.id&&(yield{type:"summary_injected",content:{id:t[t.length-1].id,text:To}});let en=null,Tn=a==="Flux"?50:15;Tn=a.toLowerCase().includes("cu")?75:Tn;let ta=Math.floor(Tn/2),hi=0,rn=16;yield{type:"status",content:"Connecting"},kt=!1;let us=[],So=!1,mi=!1;for(let H=0;H<=Tn;H++){let $e=Math.floor(Tn*.95);if(H>=$e&&hi<$e&&typeof n?.onAskUser=="function"){hi=$e;try{let me="Agent has been running for a long time. Do you want to continue execution?",_e=[{id:"continue",label:"Continue",description:"Add few more steps"},{id:"cancel",label:"Cancel",description:"Stop extending and finish current turn limit"}],ee=await n.onAskUser(me,_e);ee&&(ee.toLowerCase().includes("continue")||ee==="Continue")&&(Tn+=ta)}catch{}}let Xt=await Ts("agent",n);if(!Xt.allowed)throw new Error(Xt.reason||`Budget Exhausted for Provider (${i||"Agent"})`);let Ze=[];if(So=!1,a==="ICU"||a==="FluxCU")try{yield{type:"status",content:"Capturing Screen"},await new Promise(ee=>setTimeout(ee,1e3));let{captureGriddedScreenshot:me}=await import("./screen_grid-EIPLWNEM.js"),_e=await me();if(_e&&_e.base64){let ee="[system] Fresh Gridded Screen Feedback Captured. Use numeric coordinates. Old screenshots will be removed when new screenshot is captured, summarize in text if context is needed later [/system]",$t={inlineData:{mimeType:_e.mimeType,data:_e.base64}},It=h?.imageHistoryCU||"Standard",At=It==="Low"?1:It==="Extended"?5:3,Qt=r.filter(Ye=>Array.isArray(Ye.parts)&&Ye.parts.some(Nt=>Nt.inlineData));if(Qt.length>=At){let Ye=Qt.length-At+1;for(let Nt=0;Nt<Ye;Nt++){let Et=Qt[Nt];Array.isArray(Et.parts)&&(Et.parts=Et.parts.filter(wt=>!wt.inlineData))}}if(r.length>0&&r[r.length-1].role==="user"){let Ye=r[r.length-1];typeof Ye.text=="string"&&(Ye.text+=`
732
732
 
733
- ${X}`,Array.isArray(Ye.parts)||(Ye.parts=[{text:Ye.text}]),Ye.parts.push($t))}else r.push({role:"user",text:X,parts:[{text:X},$t]})}}catch(ue){console.error("Vision screenshot capture error:",ue)}if(m?.compression===0&&(y?.tokens||0)>$&&(r=Si(r,6)),G>0?yield{type:"status",content:"Working"}:yield{type:"status",content:"Connecting"},kt){try{let{clearPendingNudges:ue}=await import("./subagent_state-LZCOZSUJ.js");ue()}catch{}yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
733
+ ${ee}`,Array.isArray(Ye.parts)||(Ye.parts=[{text:Ye.text}]),Ye.parts.push($t))}else r.push({role:"user",text:ee,parts:[{text:ee},$t]})}}catch(me){console.error("Vision screenshot capture error:",me)}if(h?.compression===0&&(y?.tokens||0)>$&&(r=Ei(r,6)),H>0?yield{type:"status",content:"Working"}:yield{type:"status",content:"Connecting"},kt){try{let{clearPendingNudges:me}=await import("./subagent_state-LZCOZSUJ.js");me()}catch{}yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
734
734
 
735
- \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}try{let{consumePendingNudges:ue}=await import("./subagent_state-LZCOZSUJ.js"),we=ue();if(we&&we.length>0){let X=we.join(`
735
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}try{let{consumePendingNudges:me}=await import("./subagent_state-LZCOZSUJ.js"),_e=me();if(_e&&_e.length>0){let ee=_e.join(`
736
736
 
737
737
  `);r.length>0&&r[r.length-1].role==="user"?r[r.length-1].text+=`
738
738
 
739
- ${X}`:r.push({role:"user",text:X}),yield{type:"status",content:"Subagent Update"}}}catch{}if(s){let ue=await s();ue&&(ue.startsWith("/btw")?r.length>0&&r[r.length-1].role==="user"?r[r.length-1].text+=`
739
+ ${ee}`:r.push({role:"user",text:ee}),yield{type:"status",content:"Subagent Update"}}}catch{}if(s){let me=await s();me&&(me.startsWith("/btw")?r.length>0&&r[r.length-1].role==="user"?r[r.length-1].text+=`
740
740
 
741
741
  [system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
742
- [question] ${ue.replace("/btw","").trim()} [/question]`:r.push({role:"user",text:`[system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
743
- [question] ${ue.replace("/btw","").trim()} [/question]`}):r.length>0&&r[r.length-1].role==="user"?r[r.length-1].text+=`
742
+ [question] ${me.replace("/btw","").trim()} [/question]`:r.push({role:"user",text:`[system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
743
+ [question] ${me.replace("/btw","").trim()} [/question]`}):r.length>0&&r[r.length-1].role==="user"?r[r.length-1].text+=`
744
744
 
745
- [STEERING HINT from USER, High Priority] ${ue.trim()} [/STEERING HINT]`:r.push({role:"user",text:`[STEERING HINT from USER, High Priority] ${ue.trim()} [/STEERING HINT]`}),yield{type:"status",content:`${ue.startsWith("/btw")?"Question Forwarded...":"Steering Hint Injected..."}`})}let Re,rt=!1,ot=1,at=1,xe="",qe=null,rn=null,j=null,je=0,Ce=[],mt=0,Sn=!1,Mt=!1,an=!1,_n=!1,Zn=!0,en=0,xt="",tt="",Lt=!1,Pt=!1,ze=!0,be=e,Xe="";for(;ot<=sn&&at<=sn&&!rt&&!kt;){let ue=!1;try{xe="",Zn&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},Zn=!1,at===1&&(xt=""));let we=I=>{if(!I||!I.includes("[tool:"))return I;let K="",N=Zs(I);N&&(K=N.fullBlock,I=N.remainingText),I=I.replace(Va,(Te,pe)=>pe.includes("[tool:")?pe.trim():Te);let W="",Se=0;for(;Se<I.length;){let Te=I.indexOf("[tool:",Se);if(Te===-1){W+=Wr(I.substring(Se));break}let pe=I.substring(Se,Te);W+=Wr(pe);let Je=-1,U=null,Z=0;for(let Le=Te;Le<I.length;Le++){let p=I[Le];if(U){if(p===U){let Me=0;for(let Ie=Le-1;Ie>=0&&I[Ie]==="\\";Ie--)Me++;Me%2===0&&(U=null)}}else if(p==='"'||p==="'"||p==="`")U=p;else if(p==="(")Z++;else if(p===")")Z--;else if(p==="]"&&Z<=0){Je=Le;break}}if(Je===-1){W+=I.substring(Te);break}W+=I.substring(Te,Je+1),Se=Je+1}return(m?.keepReasoningContext?K:"")+W},X=r.filter(I=>(I.role==="user"||I.role==="agent"||I.role==="system")&&!String(I.id).startsWith("welcome")&&!I.isMeta&&!I.isTerminalRecord&&!(I.text&&I.text.startsWith("[TERMINAL_RECORD]"))).map((I,K,N)=>{let W=I.text||"";b||(W=W.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),I.role==="agent"&&(W=we(W),W=W.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),W=W.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*"));let Se=[];return Array.isArray(I.parts)&&I.parts.length>0?Se=I.parts.map(Te=>{if(Te.text){let pe=Te.text;return b||(pe=pe.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),I.role==="agent"&&(pe=we(pe),pe=pe.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),pe=pe.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*")),{text:pe}}return Te}):Se=[{text:W}],I.binaryPart&&gt(be)&&N.slice(K+1).filter(pe=>pe.role==="user"&&!pe.text?.startsWith("[TOOL RESULT]")).length<=2&&Se.push(I.binaryPart),{role:I.role==="user"||I.role==="system"?"user":"model",parts:Se}});for(let I=0;I<X.length;I++){let K=X[I],N=K.parts?.[0]?.text||"";if(K.role==="model"&&/\[tool:/i.test(N)){let W=-1;for(let Se=I+1;Se<X.length;Se++){let Te=X[Se],pe=Te.parts?.[0]?.text||"";if(Te.role==="user"&&pe.startsWith("[TOOL RESULT]")){W=Se;break}}if(W!==-1&&W!==I+1){let[Se]=X.splice(W,1);X.splice(I+1,0,Se)}}}for(let I=X.length-2;I>=0;I--){let K=X[I],N=X[I+1];K.role==="user"&&N.role==="user"&&(N.parts?.[0]?.text||"").trim().startsWith("[SYSTEM")&&X.splice(I,1)}let $t=[];for(let I=0;I<X.length;I++){let K=X[I];if($t.length===0)$t.push(K);else{let N=$t[$t.length-1];N.role===K.role?(N.parts[0].text+=`
745
+ [STEERING HINT from USER, High Priority] ${me.trim()} [/STEERING HINT]`:r.push({role:"user",text:`[STEERING HINT from USER, High Priority] ${me.trim()} [/STEERING HINT]`}),yield{type:"status",content:`${me.startsWith("/btw")?"Question Forwarded...":"Steering Hint Injected..."}`})}let Ie,it=!1,nt=1,rt=1,we="",qe=null,an=null,G=null,je=0,Re=[],gt=0,Sn=!1,Mt=!1,ln=!1,_n=!1,Zn=!0,tn=0,xt="",et="",Lt=!1,Pt=!1,ze=!0,Te=e,Je="";for(;nt<=rn&&rt<=rn&&!it&&!kt;){let me=!1;try{we="",Zn&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},Zn=!1,rt===1&&(xt=""));let _e=M=>{if(!M||!M.includes("[tool:"))return M;let Y="",N=ei(M);N&&(Y=N.fullBlock,M=N.remainingText),M=M.replace(qa,(le,oe)=>oe.includes("[tool:")?oe.trim():le);let V="",J=0;for(;J<M.length;){let le=M.indexOf("[tool:",J);if(le===-1){V+=jr(M.substring(J));break}let oe=M.substring(J,le);V+=jr(oe);let mt=-1,F=null,Q=0;for(let Ae=le;Ae<M.length;Ae++){let p=M[Ae];if(F){if(p===F){let He=0;for(let be=Ae-1;be>=0&&M[be]==="\\";be--)He++;He%2===0&&(F=null)}}else if(p==='"'||p==="'"||p==="`")F=p;else if(p==="(")Q++;else if(p===")")Q--;else if(p==="]"&&Q<=0){mt=Ae;break}}if(mt===-1){V+=M.substring(le);break}V+=M.substring(le,mt+1),J=mt+1}return(h?.keepReasoningContext?Y:"")+V},ee=r.filter(M=>(M.role==="user"||M.role==="agent"||M.role==="system")&&!String(M.id).startsWith("welcome")&&!M.isMeta&&!M.isTerminalRecord&&!(M.text&&M.text.startsWith("[TERMINAL_RECORD]"))).map((M,Y,N)=>{let V=M.text||"";b||(V=V.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),M.role==="agent"&&(V=_e(V),V=V.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),V=V.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*"));let J=[];return Array.isArray(M.parts)&&M.parts.length>0?J=M.parts.map(le=>{if(le.text){let oe=le.text;return b||(oe=oe.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),M.role==="agent"&&(oe=_e(oe),oe=oe.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),oe=oe.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*")),{text:oe}}return le}):J=[{text:V}],M.binaryPart&&ut(Te)&&N.slice(Y+1).filter(oe=>oe.role==="user"&&!oe.text?.startsWith("[TOOL RESULT]")).length<=2&&J.push(M.binaryPart),{role:M.role==="user"||M.role==="system"?"user":"model",parts:J}});for(let M=0;M<ee.length;M++){let Y=ee[M],N=Y.parts?.[0]?.text||"";if(Y.role==="model"&&/\[tool:/i.test(N)){let V=-1;for(let J=M+1;J<ee.length;J++){let le=ee[J],oe=le.parts?.[0]?.text||"";if(le.role==="user"&&oe.startsWith("[TOOL RESULT]")){V=J;break}}if(V!==-1&&V!==M+1){let[J]=ee.splice(V,1);ee.splice(M+1,0,J)}}}for(let M=ee.length-2;M>=0;M--){let Y=ee[M],N=ee[M+1];Y.role==="user"&&N.role==="user"&&(N.parts?.[0]?.text||"").trim().startsWith("[SYSTEM")&&ee.splice(M,1)}let $t=[];for(let M=0;M<ee.length;M++){let Y=ee[M];if($t.length===0)$t.push(Y);else{let N=$t[$t.length-1];N.role===Y.role?(N.parts[0].text+=`
746
746
 
747
- `+(K.parts?.[0]?.text||""),K.parts?.length>1&&N.parts.push(...K.parts.slice(1))):$t.push(K)}}X.length=0,X.push(...$t),be=e;let It=`${g}|${i}|${a}|${f}|${be}|${JSON.stringify(l)}|${!!m?.dynamicDirAwareness}|${!!m?.subAgents}`,At=Hn.key===It&&Hn.value;if((process.env.I_HAVE_TOO_MUCH_MONEY==="true"||process.env.I_HAVE_TOO_MUCH_MONEY===!0)&&(At=!1),At)Xe=Hn.value;else{let I=i==="Mistral"?!!Ro(be):!(be||"gemma").toLowerCase().startsWith("gemma");Xe=lr(l,((be||"gemma").toLowerCase().startsWith("gemma"),f),a,m,b,S,i,i==="Google"?!0:v,I,g,!!m?.keepReasoningContext,be),m?.dynamicDirAwareness||(Xe+=`
748
- ${ii.replace(`
747
+ `+(Y.parts?.[0]?.text||""),Y.parts?.length>1&&N.parts.push(...Y.parts.slice(1))):$t.push(Y)}}ee.length=0,ee.push(...$t),Te=e;let It=`${g}|${i}|${a}|${f}|${Te}|${JSON.stringify(l)}|${!!h?.dynamicDirAwareness}|${!!h?.subAgents}`,At=Gn.key===It&&Gn.value;if((process.env.I_HAVE_TOO_MUCH_MONEY==="true"||process.env.I_HAVE_TOO_MUCH_MONEY===!0)&&(At=!1),At)Je=Gn.value;else{let M=i==="Mistral"?!!Mo(Te):!(Te||"gemma").toLowerCase().startsWith("gemma");Je=fr(l,((Te||"gemma").toLowerCase().startsWith("gemma"),f),a,h,b,S,i,i==="Google"?!0:v,M,g,!!h?.keepReasoningContext,Te),h?.dynamicDirAwareness||(Je+=`
748
+ ${ri.replace(`
749
749
  **Directory Structure**`,`
750
- -- Directory Structure --`)}`),Hn.key=It,Hn.value=Xe}let Ye=X[X.length-1];if(Ko()&G>0){await new Promise(N=>setTimeout(N,2500)),yield{type:"status",content:"Verifying"};let I=await Un(),K=I?I.diagnostics:null;K&&Ye&&Ye.role==="user"&&Ye.parts?.[0]?.text&&(Ye.parts[0].text+=`
751
- ${K} [/ERROR]`),yield{type:"status",content:"Working"}}let Nt=i==="Mistral"||i==="Google"&&e?.toLowerCase().startsWith("gemma");if(m?.advanceRollback&&Ye&&Ye.role==="user"&&Ye.parts?.[0]?.text?.startsWith("[TOOL RESULT]"))try{let I=await io.getLatestFileChanges(g);if(I&&(I.newFiles.length>0||I.modifiedFiles.length>0||I.deletedFiles.length>0)){let K=`
750
+ -- Directory Structure --`)}`),Gn.key=It,Gn.value=Je}let Ye=ee[ee.length-1];if(Yo()&H>0){await new Promise(N=>setTimeout(N,2500)),yield{type:"status",content:"Verifying"};let M=await Wn(),Y=M?M.diagnostics:null;Y&&Ye&&Ye.role==="user"&&Ye.parts?.[0]?.text&&(Ye.parts[0].text+=`
751
+ ${Y} [/ERROR]`),yield{type:"status",content:"Working"}}let Nt=i==="Mistral"||i==="Google"&&e?.toLowerCase().startsWith("gemma");if(h?.advanceRollback&&Ye&&Ye.role==="user"&&Ye.parts?.[0]?.text?.startsWith("[TOOL RESULT]"))try{let M=await ro.getLatestFileChanges(g);if(M&&(M.newFiles.length>0||M.modifiedFiles.length>0||M.deletedFiles.length>0)){let Y=`
752
752
  [system] File Changes:
753
- `;for(let W of I.newFiles)K+=`* ${W} (created)
754
- `;for(let W of I.modifiedFiles)K+=`* ${W} (modified)
755
- `;for(let W of I.deletedFiles)K+=`* ${W} (deleted)
756
- `;K+="[/system]",Ye.parts[0].text+=K;let N=-1;for(let W=r.length-1;W>=0;W--)if(r[W].role==="user"&&r[W].text?.startsWith("[TOOL RESULT]")){N=W;break}N!==-1&&(r[N].text+=K)}}catch{}let Et=Math.floor(Tn*.99),wt=G+1;wt>=Et&&Ye&&Ye.parts?.[0]&&(Ye.parts[0].text+=`
757
- [system] WARNING, Turn Limit Impending: Step ${wt}/${Tn}. Wrap up quickly/prompt user to continue. [/system]`);let Dt=new Promise((I,K)=>{k.signal.aborted&&K(new DOMException("The user aborted a request.","AbortError")),k.signal.addEventListener("abort",()=>{K(new DOMException("The user aborted a request.","AbortError"))})});Dt.catch(()=>{});let ht=X;if(i==="Ollama")Re=Js(n.apiKey,be,ht,Xe,f,a,v,k.signal,1,m?.ollamaEndpoint||"Cloud");else if(i==="OpenRouter")Re=Xo(n.apiKey,be,ht,Xe,f,a,v,k.signal,1,g);else if(i==="DeepSeek")Re=qo(n.apiKey,be,ht,Xe,f,a,v,k.signal,1);else if(i==="Mistral")Re=zo(n.apiKey,be,ht,Xe,f,a,v,k.signal,1,g);else if(i==="NVIDIA"){let I=Jo(n.apiKey,be,ht,Xe,f,a,v,k.signal,1);Re=$r(I,be)}else if(i==="InferX")Re=Qo(n.apiKey,be,ht,Xe,f,a,v,k.signal,1);else if(i==="SenseNova")Re=Zo(n.apiKey,be,ht,Xe,f,a,v,k.signal,1);else if(i==="AIHubMix")Re=es(n.apiKey,be,ht,Xe,f,a,v,k.signal,1);else if(i==="Poolside")Re=ts(n.apiKey,be,ht,Xe,f,a,v,k.signal,1);else if(i==="9router"||i==="9Router")Re=ns(n.apiKey,be,ht,Xe,f,a,v,k.signal,1);else if(i==="ExpLabs"||i==="ExperientialLabs")Re=os(n.apiKey,be,ht,Xe,f,a,v,k.signal,1);else if(i==="TokenHarbor"||i==="Token Harbor"||i==="tokenharbor"||i==="token_harbor"||i==="thk")Re=Xs(n.apiKey,be,ht,Xe,f,a,v,k.signal,1);else if(i==="APInex"||i==="apinex"||i==="apx")Re=Qs(n.apiKey,be,ht,Xe,f,a,v,k.signal,1);else{let K=ni(n?.apiKey).models.generateContentStream({model:be||"gemini-3-flash-preview",contents:ht,config:{systemInstruction:Xe,mediaResolution:"MEDIA_RESOLUTION_HIGH",safetySettings:[{category:Dn.HARM_CATEGORY_HARASSMENT,threshold:In.BLOCK_NONE},{category:Dn.HARM_CATEGORY_HATE_SPEECH,threshold:In.BLOCK_NONE},{category:Dn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:In.BLOCK_NONE},{category:Dn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:In.BLOCK_NONE}],temperature:1.05,thinkingConfig:(()=>{let N=Ve("Google",be||"gemini-3-flash-preview",f);if(N!==null){if(typeof N=="object")return N;if(N===!1||N==="false"||N==="none"||N===0||N==="0")return{includeThoughts:!1};if(typeof N=="number")return{includeThoughts:!0,thinkingBudget:N};if(typeof N=="string"){let pe=N.toLowerCase();if(pe==="minimal")return{includeThoughts:!0,thinkingLevel:Ze.MINIMAL};if(pe==="low")return{includeThoughts:!0,thinkingLevel:Ze.LOW};if(pe==="medium")return{includeThoughts:!0,thinkingLevel:Ze.MEDIUM};if(pe==="high")return{includeThoughts:!0,thinkingLevel:Ze.HIGH};let Je=Number(N);if(!isNaN(Je))return{includeThoughts:!0,thinkingBudget:Je}}}let W=(be||"").toLowerCase(),Se=W.includes("gemma-4")||W.startsWith("gemma"),Te=W.includes("gemini-3");if(Se||Te)return Se?f.toLowerCase()!=="high"?{includeThoughts:!1,thinkingLevel:Ze.MINIMAL}:{includeThoughts:!0,thinkingLevel:Ze.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:W.includes("pro")?Ze.LOW:Ze.MINIMAL,Low:Ze.LOW,Medium:Ze.MEDIUM,Standard:Ze.MEDIUM,High:Ze.HIGH,xHigh:Ze.HIGH}[f]||Ze.MEDIUM};{let pe={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[f]||2048;return pe===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:pe}}})()}},{signal:k.signal});Re=await Promise.race([K,Dt])}xe="",qe=null,j=null,Ce=[],mt=0,yield{type:"model_update",content:null},tt="",Lt=xt.length>0;let ln="",us=Date.now(),Pn=async function*(){if(i==="Google"&&ln){let I=eo(ln);for(let K of I)yield K;ln="",us=Date.now()}},hi=!0,$n="",Vn=!1,Tt=null,Kn=!1,Yn=!1,So=!1,qn=I=>{let K=0;for(;K+2<I.length;)I[K]==="`"&&I[K+1]==="`"&&I[K+2]==="`"?(So=!So,K+=3):K++},ta={tool:{startPrefix:"[tool",fullPrefix:"[tool:",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|>"}},eo=I=>{let K=[],N=I;for(;N.length>0;)if(Vn){let W=$n+N,Se=ta[Tt];if(Se){let Je=!1;if(W.length<Se.startPrefix.length?Se.startPrefix.startsWith(W)||(Je=!0):W.startsWith(Se.startPrefix)?W.length>=Se.fullPrefix.length&&!W.startsWith(Se.fullPrefix)&&(Je=!0):Je=!0,Je){if(!Kn)K.push({type:"text",content:W});else{let U=W.replace(/[^\n]/g,"");U&&K.push({type:"text",content:U})}qn(W),$n="",Vn=!1,Tt=null,Yn=!1,N="";break}}let Te=-1,pe=Se?Se.endTag:"]";if(Tt==="tool"||Tt==="agent"){let Je=0,U=null,Z=0,Le=!1;for(let p=0;p<W.length;p++){let Me=W[p];if(U){if(Me===U){let Ie=0;for(let Q=p-1;Q>=0&&W[Q]==="\\";Q--)Ie++;Ie%2===0&&(U=null)}}else if(Me==='"'||Me==="'"||Me==="`")U=Me;else if(Me==="(")Je++,Le=!0;else if(Me===")")Je--;else if(Me==="[")Z++;else if(Me==="]"){if(Le&&Je===0&&Z===1){Te=p;break}Z--}}}else Te=W.indexOf(pe);if(Te!==-1){let Je=pe.length,U=W.substring(0,Te+Je);Tt?.startsWith("kimi")||K.push({type:"text",content:U}),qn(U),(Tt==="tool"||Tt==="agent"||Tt?.startsWith("kimi"))&&!Yn&&(Kn=!0),Yn=!1,$n="",Vn=!1,Tt=null,N=W.substring(Te+Je)}else{let Je=Tt?.startsWith("kimi")?8192:512;if(W.length>Je){if(!Kn)K.push({type:"text",content:W});else{let U=W.replace(/[^\n]/g,"");U&&K.push({type:"text",content:U})}qn(W),$n="",Vn=!1,Tt=null,Yn=!1}else $n=W;N="";break}}else{let W=N.indexOf("[tool"),Se=N.indexOf("[agent"),Te=N.indexOf("[[END]]"),pe=N.indexOf("<|tool_calls_section_begin|>"),Je=N.indexOf("<|tool_call_begin|>"),U=[{type:"tool",idx:W,start:"[tool",end:"]"},{type:"agent",idx:Se,start:"[agent",end:"]"},{type:"end",idx:Te,start:"[[END]]",end:"[[END]]"},{type:"kimi_section",idx:pe,start:"<|tool_calls_section_begin|>",end:"<|tool_calls_section_end|>"},{type:"kimi_call",idx:Je,start:"<|tool_call_begin|>",end:"<|tool_call_end|>"}].filter(Z=>Z.idx!==-1).sort((Z,Le)=>Z.idx-Le.idx);if(U.length>0){let Z=U[0],Le=N.substring(0,Z.idx);qn(Le);let p=Z.idx>0?N[Z.idx-1]:"";if(Yn=So||p==="`",Z.idx>0)if(!Kn)K.push({type:"text",content:Le});else{let Me=Le.replace(/[^\n]/g,"");Me&&K.push({type:"text",content:Me})}Vn=!0,Tt=Z.type,$n="",N=N.substring(Z.idx)}else{let Z=["[tool","[agent","[[END]]","<|tool_calls_section_begin|>","<|tool_call_begin|>"],Le=-1;for(let p of Z){for(let Me=p.length-1;Me>0;Me--)if(N.endsWith(p.substring(0,Me))){Le=N.length-Me;let Ie=Z.indexOf(p);Ie===0?Tt="tool":Ie===1?Tt="agent":Ie===2?Tt="end":Ie===3?Tt="kimi_section":Tt="kimi_call";break}if(Le!==-1)break}if(Le!==-1){if(Le>0){let Me=N.substring(0,Le);if(qn(Me),!Kn)K.push({type:"text",content:Me});else{let Ie=Me.replace(/[^\n]/g,"");Ie&&K.push({type:"text",content:Ie})}}let p=Le>0?N[Le-1]:"";Yn=So||p==="`",Vn=!0,$n=N.substring(Le),N=""}else{if(!Kn)K.push({type:"text",content:N});else{let p=N.replace(/[^\n]/g,"");p&&K.push({type:"text",content:p})}qn(N);break}}}return K},na=Re[Symbol.asyncIterator]();for(;;){let{value:I,done:K}=await Promise.race([na.next(),Dt]);if(K)break;if(I&&I.type==="status"){yield I;continue}let N="",W=I.candidates?.[0]?.content?.parts;if(W&&W.length>0)for(let Te of W){let pe=typeof Te.text=="string"?Te.text:Te.text?parseChunkText(Te.text):"";Te.thought?pe&&(ue||(N+="<think>",ue=!0),N+=pe):pe&&(ue&&(N+="</think>",ue=!1),N+=pe)}else I.text&&ue&&(N+="</think>",ue=!1);N=Wa(N);let Se=N?Ts(N):0;if(n&&typeof n.onTokenChunk=="function"&&n.onTokenChunk(N,Se),hi&&(yield{type:"status",content:"Thinking"},hi=!1),kt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
758
-
759
- \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(N){if(Lt){if(tt+=N,tt.length>=64){let U=0,Z=Math.min(xt.length,tt.length);for(let p=Z;p>=10;p--)if(xt.endsWith(tt.substring(0,p))){U=p;break}let Le=tt.substring(U);if(Le){let Me=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(xt)?Le.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):Le.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(Me)if(xe+=Me,i==="Google")ln+=Me;else{yield*Pn();let Ie=eo(Me);for(let Q of Ie)yield Q}}Lt=!1,tt=""}continue}else if(xe+=N,i==="Google")ln+=N;else{yield*Pn();let U=eo(N);for(let Z of U)yield Z}let Te=za(xe);if(Te.inside){Pt=!0,j||(j=Date.now());let Z={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"}[Te.toolName]||Te.toolName,Le=Te.args||"",p=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(Z)){let Ie=oe(Le),Q=Ie.path||Ie.targetFile||Ie.TargetFile||Ie.directory,cn=Ie.keyword,Nn=Ie.title||Ie.task,En=Ie.id||Ie.taskId,Fe=Ie.timeout||Ie.time;if(cn!=null)p=String(cn).replace(Wn,"");else if(Q)p=ee.basename(String(Q).replace(Wn,"").replace(Nr,"/"));else if(Nn&&(Z==="invoke"||Z==="invoke_sync"))p=String(Nn).replace(Wn,"").substring(0,30);else if(En&&Z==="get_progress")p=String(En).replace(Wn,"");else if(Fe&&Z==="await"){let Ft=parseFloat(String(Fe).replace(Wn,""));isNaN(Ft)?p=String(Fe).replace(Wn,""):(Ft<5&&(Ft=5),Ft>120&&(Ft=120),p=(mn=>{if(mn>=60){let ms=Math.floor(mn/60),zn=mn%60;return`${ms}m${zn>0?` ${zn}s`:""}`}return`${mn}s`})(Ft))}else{let Ft=Le.match(Fa);if(Ft){let Ht=Ft[1].replace(Wn,"");Z==="invoke"||Z==="invoke_sync"||Z==="get_progress"?p=Ht.substring(0,30):p=Z==="search_keyword"||Z==="file_map"?Ht:ee.basename(Ht.replace(Nr,"/"))}}}let Me=`${ei[Z]||Z}${p?` ${p}`:""}`;if((Z!==qe||p!==rn)&&(qe=Z,rn=p,yield{type:"status",content:`${Me}`},process.stdout.isTTY)){let Q={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"}[Z]||"Working";process.stdout.write(`\x1B]0;${Q}...\x07`)}}if(xe.length-en>150){en=xe.length;let U=Yr(xe,!1),Z=Zs(U),Le=Z?(Z.innerContent||"").trim():"",p=Le.split(/[.!?]\s+/),Me=new Set(p),Ie=p.length>10?(p.length-Me.size)/p.length:0,Q=Le.split(/\s+/).filter(Be=>Be.length>0).length,cn=.6,Nn=.8,En=!1;if(i.toLowerCase().includes("google")&&(be||"").toLowerCase().startsWith("gemma")){let _={low:256,medium:1024,high:8192,max:16384,xhigh:16384}[f?.toLowerCase()]||2500;En=Q>_}if(Ie>cn||En){yield{type:"status",content:`${Ie>cn?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},Mt=!0,await new Promise(_=>setTimeout(_,3e3));break}let Ht=Hr(xe).trim().split(/[.!?]\s+/),mn=new Set(Ht);if((Ht.length>10?(Ht.length-mn.size)/Ht.length:0)>Nn){yield{type:"status",content:"Response Loop Detected. Re-centering..."},Mt=!1,_n=!0,await new Promise(Be=>setTimeout(Be,3e3));break}let zn=U.replace(Ia,"").replace(Da,"").replace(Oa,"").replace(La,""),Bt=zn.toLowerCase().split(/\s+/).map(Be=>Be.replace(Pa,"")).filter(Be=>Be.length>0),hn=!1;if(Bt.length>=10)for(let Be=1;Be<=15;Be++){let _=Math.max(3,Math.ceil(10/Be));if(Bt.length<Be*_)continue;let V=Bt.slice(Bt.length-Be),ne=V.join(" ");if(Be>1&&ne===V.slice(0,Math.floor(Be/2)).join(" ").repeat(2).trim())continue;let ce=!0;for(let ye=1;ye<_;ye++)if(Bt.slice(Bt.length-Be*(ye+1),Bt.length-Be*ye).join(" ")!==ne){ce=!1;break}if(ce){hn=!0;break}}if(!hn){let Be=zn.toLowerCase().replace($a,"");if(Be.length>=20)for(let _=1;_<=10;_++){let V=Math.max(5,Math.ceil(16/_));if(Be.length<_*V)continue;let ne=Be.substring(Be.length-_),ce=!0;for(let ye=1;ye<V;ye++)if(Be.substring(Be.length-_*(ye+1),Be.length-_*ye)!==ne){ce=!1;break}if(ce){hn=!0;break}}}if(hn){yield{type:"status",content:"Stuttering Detected. Re-centering..."},Mt=!1,an=!0,await new Promise(Be=>setTimeout(Be,3e3));break}}let pe=qt(xe),Je=xo(pe);for(;Je.length>mt;){yield*Pn();let U=Je[mt],Z=Date.now(),p={Ask:"ask",AskUser:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Await:"await",await:"await",AwaitSubagent:"await",awaitSubagent:"await",Answer:"answer",answer:"answer",AnswerSubagent:"answer",answerSubagent:"answer",Steer:"steer",steer:"steer",SteerSubagent:"steer",steerSubagent:"steer",Cancel:"cancel",cancel:"cancel",Click:"click",click:"click",Drag:"drag",drag:"drag",Scroll:"scroll",scroll:"scroll",KeyboardTyping:"keyboard_typing",keyboard_typing:"keyboard_typing",KeyPress:"key_press",key_press:"key_press",RecaptureScreen:"recapture_screen",recapture_screen:"recapture_screen",EmergencyRollback:"EmergencyRollback"}[U.toolName]||U.toolName,Me=ei[p]||U.toolName,Ie=Gn(p,U.args);yield{type:"status",content:`${Me}${Ie?` ${Ie}`:""}`};let Q="";if(p==="click"){let _=oe(U.args);Q=`\u2714 Clicked: ${_.intendedClickText?`${_.intendedClickText}`:""}`}else if(p==="drag"){let _=oe(U.args);Q=`\u2714 Dragged: Cell ${_.fromGridId||""} \u2192 Cell ${_.toGridId||""}`}else if(p==="scroll"){let _=oe(U.args);Q=`\u2714 Scrolled: ${_.direction||"down"} (${_.amount||1})`}else if(p==="keyboard_typing"){let _=oe(U.args);Q=`\u2714 Typed: ${_.text?`"${_.text.length>20?_.text.substring(0,20)+"...":_.text}"`:""}`}else if(p==="key_press")Q=`\u2714 Pressed Key: ${oe(U.args).key||""}`;else if(p==="recapture_screen")Q="\u2714 Recaptured Screen";else if(p==="web_search"){let{query:_,limit:V=10,aiMode:ne=!1}=oe(U.args);Q=`${_?"\u2714":"\u2718"} ${ne?"AI Search":"Searched"}: ${_?`${_}`:"No Search Query"}${ne===!1&&_?` \u2192 ${V}`:""}`}else if(p==="web_scrape"){let _=oe(U.args).url||null;Q=`${_?"\u2714":"\u2718"} Visited: ${_||"No Source"}`}else if(p==="view_file"){let{path:_,StartLine:V,EndLine:ne,start_line:ce,end_line:ye,startLine:He,endLine:De}=oe(U.args),_e=V||ce||He,q=ne||ye||De,se=parseInt(_e)||1,ae=parseInt(q)||(_e?se+800:800),Ke="...",Qe=ae,de=(_||"").trim().toLowerCase().replaceAll("\\","/");if(de.startsWith("#skill"))de.startsWith("#skill/global/fluxflow")||de.startsWith("#skills/global/fluxflow")||de.includes("#skill/fluxflow")||de.includes("#skills/fluxflow")?Q="\u2714 Read Documentation":Q=`\u2714 Read Skill: ${ee.basename(_.replaceAll("\\","/"))}`;else{try{let ke=ee.resolve(process.cwd(),_);if(Ge.existsSync(ke)){let bt=Ge.readFileSync(ke,"utf8").split(`
760
- `).length;Ke=bt,!_e&&!q&&bt>800?Qe=Math.min(50,bt):Qe=Math.min(ae,bt)}}catch{}let Pe=(_||"").toLowerCase(),pt=Pe.endsWith(".pdf"),Ue=Pe.endsWith(".docx")||Pe.endsWith(".doc")||Pe.endsWith(".ppt")||Pe.endsWith(".pptx")||Pe.endsWith(".xls")||Pe.endsWith(".xlsx"),st=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(Pe);pt||Ue?Q=`${_.length>0?"\u2714":"\u2718"} ${_?`Analyzed: ${ee.basename(_)}`:"Analyzed: File Not Found"}`:st?Q=`${_.length>0?"\u2714":"\u2718"} ${_?`Processed: ${ee.basename(_)}`:"Processed: File Not Found"}`:Q=`${Ke!=="..."?"\u2714":"\u2718"} Read: ${_?`${ee.basename(_)} \u2192 ${Ke!=="..."?`Lines ${se} - ${Qe} of ${Ke}`:"File Not Found"}`:"File Not Found"}`}}else if(p==="list_files"||p==="read_folder"){let _=p==="list_files"?"List":"Browsed",V=oe(U.args).path||null,ne=oe(U.args).recurse||1;Q=`${V?"\u2714":"\u2718"} ${_}: ${V?`${V==="."?`./${ne>1?"*":""}`:`${V.replaceAll("\\","/")}${ne>1?`${V.endsWith("/")?"*":"/*"}`:`${V.endsWith("/")?"":"/"}`}`}`:"No Folder Selected"}`}else if(p==="write_file"||p==="update_file"){let _=p==="write_file"?"Created":"Edited",V=oe(U.args),ne=V.path||null,ye=Object.entries(V).some(([He,De])=>He.startsWith("searchContent")&&typeof De=="string"&&De.startsWith("^LINE:"))?"\u1361":":";Q=`${ne?"\u2714":"\u2718"} ${_}${ye} ${ne?ne.replaceAll("\\","/"):"No File Changes"}`}else if(p==="write_pdf"){let _=oe(U.args).path||null;Q=`${_?"\u2714":"\u2718"} Generated: ${_.replaceAll("\\","/")||"No PDF Generated"}`}else if(p==="write_docx"){let _=oe(U.args).path||null;Q=`${_?"\u2714":"\u2718"} Generated: ${_.replaceAll("\\","/")||"No Docx Generated"}`}else if(p==="file_map"){let _=oe(U.args).path;Q=`${_?"\u2714":"\u2718"} Indexed: ${_.replaceAll("\\","/")?""+_:"File Not Found"}`}else if(p.toLowerCase()==="search_keyword"||p.toLowerCase()==="todo")Q="";else if(p.toLowerCase()==="generate_image"){let{path:_,outputPath:V,output:ne}=oe(U.args);Q=`\u2714 Generated: ${_||V||ne||"generated_image.png"}`}else if(p==="invoke_sync"||p==="InvokeSync"){let _=Gn(p,U.args);Q=`\u2714 Called Generalist${_?`: ${_}`:""}`}else if(p==="Invoke"||p==="InvokeAsync"||p==="invoke"){let _=Gn(p,U.args);Q=`\u2714 Started Generalist${_?`: ${_}`:""}`}else if(p==="get_progress"||p==="GetProgress"){let _=Gn(p,U.args);Q=`\u2714 Checked${_?`: ${_}`:""}`}else if(p==="cancel"){let _=Gn(p,U.args);Q=`\u{1F6C7} Cancelled${_?`: ${_}`:""}`}else if(p==="steer"||p==="Steer"){let _=Gn(p,U.args);Q=`\u2714 Steered${_?`: ${_}`:""}`}else if(p==="EmergencyRollback"){let{method:_}=oe(U.args);Q=_==="forceRevert"?"":"\u2714 Rollback Point Checked"}else if(p==="await"||p==="Await"){let{time:_,timeout:V}=oe(U.args),ne=parseFloat(V||_)||0;ne||(ne=120);let ce=De=>{if(De>=60){let _e=Math.floor(De/60),q=De%60;return`${_e}m${q>0?` ${q}s`:""}`}return`${De}s`},ye=["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"];Q=`\u2714 ${ye[Math.floor(Math.random()*ye.length)]} \u2192 ${ce(ne)}`}else p==="Answer"||p==="answer"?Q="\u2714 Resolved Sub-Agent Query":p==="exec_command"||p==="ask"?Q="":Q=`Executed: ${U.toolName}`;if(yield*Pn(),p==="exec_command"){let{command:_}=oe(U.args);if(_&&n.systemSettings&&n.systemSettings.allowExternalAccess===!1){let V=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],ne=ee.resolve(process.cwd()).substring(0,3).toLowerCase(),ce=q=>{let se=[],ae="",Ke=null;for(let Qe=0;Qe<q.length;Qe++){let de=q[Qe];Ke?(de===Ke&&(Ke=null),ae+=de):de==='"'||de==="'"?(Ke=de,ae+=de):de==="&"&&q[Qe+1]==="&"||de==="|"&&q[Qe+1]==="|"?(ae.trim()&&(se.push(ae.trim()),ae=""),Qe++):de===";"||de==="|"||de==="&"?ae.trim()&&(se.push(ae.trim()),ae=""):ae+=de}return ae.trim()&&se.push(ae.trim()),se},ye=q=>{let se=[],ae="",Ke=null;for(let Qe=0;Qe<q.length;Qe++){let de=q[Qe];Ke?(de===Ke&&(Ke=null),ae+=de):de==='"'||de==="'"?(Ke=de,ae+=de):/\s/.test(de)?ae&&(se.push(ae),ae=""):ae+=de}return ae&&se.push(ae),se},He=q=>{let se=q.replace(/^['"]|['"]$/g,"").trim();return!se||process.platform==="win32"&&/^\/[a-zA-Z0-9?]+$/.test(se)?!1:V.some(ae=>{if(ae.source==="[a-zA-Z]:[\\\\\\/]"){let Ke=se.match(/[a-zA-Z]:[\\\/]/i);return Ke&&Ke[0].toLowerCase()!==ne}return ae.test(se)})};if(ce(_).some(q=>{let se=ye(q);if(se.length===0)return!1;let ae=se[0].replace(/^['"]|['"]$/g,"").toLowerCase();if(["echo","printf","write-output"].includes(ae)){let Qe=!1;return se.some(de=>{let St=de.replace(/^['"]|['"]$/g,"");if(St===">"||St===">>"||St==="<")return Qe=!0,!1;if(St.startsWith(">")||St.startsWith("<")){let Pe=St.replace(/^[><]+/,"");return He(Pe)}return Qe?(Qe=!1,He(de)):!1})}return se.some(Qe=>He(Qe))})){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(se=>setTimeout(se,50)),n.onExecChunk&&n.onExecChunk(`ERROR: ${q}`),await new Promise(se=>setTimeout(se,50)),n.onExecEnd&&n.onExecEnd(),Ce.push({role:"user",text:`[TOOL RESULT]: ERROR: ${q}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${q}`},mt++;continue}}n.onExecStart&&n.onExecStart(_||"No Command"),yield{type:"exec_start"}}let cn=oe(U.args),Nn=cn.path||cn.targetPath||null;if(Nn){let _=n.systemSettings&&n.systemSettings.allowExternalAccess===!1,V=ee.resolve(Nn),ne=ee.resolve(process.cwd());if(_&&!V.startsWith(ne)){let ce="Access Denied. You are not allowed to access files outside the current workspace.";if(p==="write_file"||p==="update_file"){let He=`\u2718 ${p==="write_file"?"Write Canceled":"Edit Canceled"}: ${cn.path||"..."}`,De=115;process.stdout.isTTY&&(De=process.stdout.columns-5||120);let _e=Math.min(He.length+4,De),q=`${He.padEnd(_e-2).substring(0,_e-2)}`;yield{type:"visual_feedback",content:Yt(`${ze?`
753
+ `;for(let V of M.newFiles)Y+=`* ${V} (created)
754
+ `;for(let V of M.modifiedFiles)Y+=`* ${V} (modified)
755
+ `;for(let V of M.deletedFiles)Y+=`* ${V} (deleted)
756
+ `;Y+="[/system]",Ye.parts[0].text+=Y;let N=-1;for(let V=r.length-1;V>=0;V--)if(r[V].role==="user"&&r[V].text?.startsWith("[TOOL RESULT]")){N=V;break}N!==-1&&(r[N].text+=Y)}}catch{}let Et=Math.floor(Tn*.99),wt=H+1;wt>=Et&&Ye&&Ye.parts?.[0]&&(Ye.parts[0].text+=`
757
+ [system] WARNING, Turn Limit Impending: Step ${wt}/${Tn}. Wrap up quickly/prompt user to continue. [/system]`);let Dt=new Promise((M,Y)=>{k.signal.aborted&&Y(new DOMException("The user aborted a request.","AbortError")),k.signal.addEventListener("abort",()=>{Y(new DOMException("The user aborted a request.","AbortError"))})});Dt.catch(()=>{});let ht=ee;if(i==="Ollama")Ie=Xs(n.apiKey,Te,ht,Je,f,a,v,k.signal,1,h?.ollamaEndpoint||"Cloud");else if(i==="OpenRouter")Ie=Qo(n.apiKey,Te,ht,Je,f,a,v,k.signal,1,g);else if(i==="DeepSeek")Ie=zo(n.apiKey,Te,ht,Je,f,a,v,k.signal,1);else if(i==="Mistral")Ie=Jo(n.apiKey,Te,ht,Je,f,a,v,k.signal,1,g);else if(i==="NVIDIA"){let M=Xo(n.apiKey,Te,ht,Je,f,a,v,k.signal,1);Ie=Br(M,Te)}else if(i==="InferX")Ie=Zo(n.apiKey,Te,ht,Je,f,a,v,k.signal,1);else if(i==="SenseNova")Ie=es(n.apiKey,Te,ht,Je,f,a,v,k.signal,1);else if(i==="AIHubMix")Ie=ts(n.apiKey,Te,ht,Je,f,a,v,k.signal,1);else if(i==="Poolside")Ie=ns(n.apiKey,Te,ht,Je,f,a,v,k.signal,1);else if(i==="9router"||i==="9Router")Ie=os(n.apiKey,Te,ht,Je,f,a,v,k.signal,1);else if(i==="ExpLabs"||i==="ExperientialLabs")Ie=ss(n.apiKey,Te,ht,Je,f,a,v,k.signal,1);else if(i==="TokenHarbor"||i==="Token Harbor"||i==="tokenharbor"||i==="token_harbor"||i==="thk")Ie=Qs(n.apiKey,Te,ht,Je,f,a,v,k.signal,1);else if(i==="APInex"||i==="apinex"||i==="apx")Ie=Zs(n.apiKey,Te,ht,Je,f,a,v,k.signal,1);else{let Y=oi(n?.apiKey).models.generateContentStream({model:Te||"gemini-3-flash-preview",contents:ht,config:{systemInstruction:Je,mediaResolution:"MEDIA_RESOLUTION_HIGH",safetySettings:[{category:On.HARM_CATEGORY_HARASSMENT,threshold:Dn.BLOCK_NONE},{category:On.HARM_CATEGORY_HATE_SPEECH,threshold:Dn.BLOCK_NONE},{category:On.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Dn.BLOCK_NONE},{category:On.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Dn.BLOCK_NONE}],temperature:1.05,thinkingConfig:(()=>{let N=Ve("Google",Te||"gemini-3-flash-preview",f);if(N!==null){if(typeof N=="object")return N;if(N===!1||N==="false"||N==="none"||N===0||N==="0")return{includeThoughts:!1};if(typeof N=="number")return{includeThoughts:!0,thinkingBudget:N};if(typeof N=="string"){let oe=N.toLowerCase();if(oe==="minimal")return{includeThoughts:!0,thinkingLevel:Qe.MINIMAL};if(oe==="low")return{includeThoughts:!0,thinkingLevel:Qe.LOW};if(oe==="medium")return{includeThoughts:!0,thinkingLevel:Qe.MEDIUM};if(oe==="high")return{includeThoughts:!0,thinkingLevel:Qe.HIGH};let mt=Number(N);if(!isNaN(mt))return{includeThoughts:!0,thinkingBudget:mt}}}let V=(Te||"").toLowerCase(),J=V.includes("gemma-4")||V.startsWith("gemma"),le=V.includes("gemini-3");if(J||le)return J?f.toLowerCase()!=="high"?{includeThoughts:!1,thinkingLevel:Qe.MINIMAL}:{includeThoughts:!0,thinkingLevel:Qe.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:V.includes("pro")?Qe.LOW:Qe.MINIMAL,Low:Qe.LOW,Medium:Qe.MEDIUM,Standard:Qe.MEDIUM,High:Qe.HIGH,xHigh:Qe.HIGH}[f]||Qe.MEDIUM};{let oe={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[f]||2048;return oe===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:oe}}})()}},{signal:k.signal});Ie=await Promise.race([Y,Dt])}we="",qe=null,G=null,Re=[],gt=0,yield{type:"model_update",content:null},et="",Lt=xt.length>0;let cn="",gs=Date.now(),$n=async function*(){if(i==="Google"&&cn){let M=to(cn);for(let Y of M)yield Y;cn="",gs=Date.now()}},pi=!0,Nn="",Kn=!1,Tt=null,yi=!1,Yn=!1,qn=!1,_o=!1,En=!1,eo=M=>{let Y=0;for(;Y+2<M.length;)M[Y]==="`"&&M[Y+1]==="`"&&M[Y+2]==="`"?(_o=!_o,Y+=3):Y++},xi=M=>{if(!M)return;let Y=/(?:<(\/?)(?:think|thought|thoughts)[^>]*>|\[(\/?)(?:think|thought|thoughts)\]|<\/?channel\|?>|<\|channel>thought)/gi,N;for(;(N=Y.exec(M))!==null;){let V=N[0].toLowerCase();V.startsWith("</")||V.startsWith("[/")||V==="<channel|>"?En=!1:En=!0}},sa={tool:{startPrefix:"[tool",fullPrefix:"[tool:",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|>"}},to=M=>{let Y=[],N=M,V=J=>{if(!J)return;if(!yi){Y.push({type:"text",content:J}),eo(J),xi(J);return}let le=/(?:<(\/?)(?:think|thought|thoughts)[^>]*>|\[(\/?)(?:think|thought|thoughts)\]|<\/?channel\|?>|<\|channel>thought)/gi,oe=0,mt;for(;(mt=le.exec(J))!==null;){let Q=J.substring(oe,mt.index);if(Q)if(eo(Q),En)Y.push({type:"text",content:Q});else{let He=Q.replace(/[^\n]/g,"");He&&Y.push({type:"text",content:He})}let Ae=mt[0];eo(Ae);let p=Ae.toLowerCase();p.startsWith("</")||p.startsWith("[/")||p==="<channel|>"?En=!1:En=!0,Y.push({type:"text",content:Ae}),oe=le.lastIndex}let F=J.substring(oe);if(F)if(eo(F),En)Y.push({type:"text",content:F});else{let Q=F.replace(/[^\n]/g,"");Q&&Y.push({type:"text",content:Q})}};for(;N.length>0;)if(Kn){let J=Nn+N,le=sa[Tt];if(le){let F=!1;if(J.length<le.startPrefix.length?le.startPrefix.startsWith(J)||(F=!0):J.startsWith(le.startPrefix)?J.length>=le.fullPrefix.length&&!J.startsWith(le.fullPrefix)&&(F=!0):F=!0,F){V(J),Nn="",Kn=!1,Tt=null,Yn=!1,qn=!1,N="";break}}let oe=-1,mt=le?le.endTag:"]";if(Tt==="tool"||Tt==="agent"){let F=0,Q=null,Ae=0,p=!1;for(let He=0;He<J.length;He++){let be=J[He];if(Q){if(be===Q){let z=0;for(let Ft=He-1;Ft>=0&&J[Ft]==="\\";Ft--)z++;z%2===0&&(Q=null)}}else if(be==='"'||be==="'"||be==="`")Q=be;else if(be==="(")F++,p=!0;else if(be===")")F--;else if(be==="[")Ae++;else if(be==="]"){if(p&&F===0&&Ae===1){oe=He;break}Ae--}}}else oe=J.indexOf(mt);if(oe!==-1){let F=mt.length,Q=J.substring(0,oe+F);Tt?.startsWith("kimi")||Y.push({type:"text",content:Q}),eo(Q),xi(Q),(Tt==="tool"||Tt==="agent"||Tt?.startsWith("kimi"))&&!Yn&&!qn&&(yi=!0),Yn=!1,qn=!1,Nn="",Kn=!1,Tt=null,N=J.substring(oe+F)}else{let F=Tt?.startsWith("kimi")?8192:512;J.length>F?(V(J),Nn="",Kn=!1,Tt=null,Yn=!1,qn=!1):Nn=J,N="";break}}else{let J=N.indexOf("[tool"),le=N.indexOf("[agent"),oe=N.indexOf("[[END]]"),mt=N.indexOf("<|tool_calls_section_begin|>"),F=N.indexOf("<|tool_call_begin|>"),Q=[{type:"tool",idx:J,start:"[tool",end:"]"},{type:"agent",idx:le,start:"[agent",end:"]"},{type:"end",idx:oe,start:"[[END]]",end:"[[END]]"},{type:"kimi_section",idx:mt,start:"<|tool_calls_section_begin|>",end:"<|tool_calls_section_end|>"},{type:"kimi_call",idx:F,start:"<|tool_call_begin|>",end:"<|tool_call_end|>"}].filter(Ae=>Ae.idx!==-1).sort((Ae,p)=>Ae.idx-p.idx);if(Q.length>0){let Ae=Q[0],p=N.substring(0,Ae.idx);Ae.idx>0&&V(p);let He=Ae.idx>0?N[Ae.idx-1]:"";Yn=_o||He==="`",qn=En,Kn=!0,Tt=Ae.type,Nn="",N=N.substring(Ae.idx)}else{let Ae=["[tool","[agent","[[END]]","<|tool_calls_section_begin|>","<|tool_call_begin|>"],p=-1;for(let He of Ae){for(let be=He.length-1;be>0;be--)if(N.endsWith(He.substring(0,be))){p=N.length-be;let z=Ae.indexOf(He);z===0?Tt="tool":z===1?Tt="agent":z===2?Tt="end":z===3?Tt="kimi_section":Tt="kimi_call";break}if(p!==-1)break}if(p!==-1){if(p>0){let be=N.substring(0,p);V(be)}let He=p>0?N[p-1]:"";Yn=_o||He==="`",qn=En,Kn=!0,Nn=N.substring(p),N=""}else{V(N);break}}}return Y},ia=Ie[Symbol.asyncIterator]();for(;;){let{value:M,done:Y}=await Promise.race([ia.next(),Dt]);if(Y)break;if(M&&M.type==="status"){yield M;continue}let N="",V=M.candidates?.[0]?.content?.parts;if(V&&V.length>0)for(let le of V){let oe=typeof le.text=="string"?le.text:le.text?parseChunkText(le.text):"";le.thought?oe&&(me||(N+="<think>",me=!0),N+=oe):oe&&(me&&(N+="</think>",me=!1),N+=oe)}else M.text&&me&&(N+="</think>",me=!1);N=ja(N);let J=N?Ss(N):0;if(n&&typeof n.onTokenChunk=="function"&&n.onTokenChunk(N,J),pi&&(yield{type:"status",content:"Thinking"},pi=!1),kt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
758
+
759
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(N){if(Lt){if(et+=N,et.length>=64){let F=0,Q=Math.min(xt.length,et.length);for(let p=Q;p>=10;p--)if(xt.endsWith(et.substring(0,p))){F=p;break}let Ae=et.substring(F);if(Ae){let He=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(xt)?Ae.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):Ae.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(He)if(we+=He,i==="Google")cn+=He;else{yield*$n();let be=to(He);for(let z of be)yield z}}Lt=!1,et=""}continue}else if(we+=N,i==="Google")cn+=N;else{yield*$n();let F=to(N);for(let Q of F)yield Q}let le=Qa(we);if(le.inside){Pt=!0,G||(G=Date.now());let Q={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"}[le.toolName]||le.toolName,Ae=le.args||"",p=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(Q)){let be=ie(Ae),z=be.path||be.targetFile||be.TargetFile||be.directory,Ft=be.keyword,Fn=be.title||be.task,Cn=be.id||be.taskId,Ne=be.timeout||be.time;if(Ft!=null)p=String(Ft).replace(Hn,"");else if(z)p=te.basename(String(z).replace(Hn,"").replace(Ur,"/"));else if(Fn&&(Q==="invoke"||Q==="invoke_sync"))p=String(Fn).replace(Hn,"").substring(0,30);else if(Cn&&Q==="get_progress")p=String(Cn).replace(Hn,"");else if(Ne&&Q==="await"){let Bt=parseFloat(String(Ne).replace(Hn,""));isNaN(Bt)?p=String(Ne).replace(Hn,""):(Bt<5&&(Bt=5),Bt>120&&(Bt=120),p=(hn=>{if(hn>=60){let ms=Math.floor(hn/60),zn=hn%60;return`${ms}m${zn>0?` ${zn}s`:""}`}return`${hn}s`})(Bt))}else{let Bt=Ae.match(Wa);if(Bt){let Gt=Bt[1].replace(Hn,"");Q==="invoke"||Q==="invoke_sync"||Q==="get_progress"?p=Gt.substring(0,30):p=Q==="search_keyword"||Q==="file_map"?Gt:te.basename(Gt.replace(Ur,"/"))}}}let He=`${ti[Q]||Q}${p?` ${p}`:""}`;if((Q!==qe||p!==an)&&(qe=Q,an=p,yield{type:"status",content:`${He}`},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"}[Q]||"Working";process.stdout.write(`\x1B]0;${z}...\x07`)}}if(we.length-tn>150){tn=we.length;let F=Jr(we,!1),Q=ei(F),Ae=Q?(Q.innerContent||"").trim():"",p=Ae.split(/[.!?]\s+/),He=new Set(p),be=p.length>10?(p.length-He.size)/p.length:0,z=Ae.split(/\s+/).filter(Fe=>Fe.length>0).length,Ft=.6,Fn=.8,Cn=!1;if(i.toLowerCase().includes("google")&&(Te||"").toLowerCase().startsWith("gemma")){let _={low:256,medium:1024,high:8192,max:16384,xhigh:16384}[f?.toLowerCase()]||2500;Cn=z>_}if(be>Ft||Cn){yield{type:"status",content:`${be>Ft?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},Mt=!0,await new Promise(_=>setTimeout(_,3e3));break}let Gt=Vr(we).trim().split(/[.!?]\s+/),hn=new Set(Gt);if((Gt.length>10?(Gt.length-hn.size)/Gt.length:0)>Fn){yield{type:"status",content:"Response Loop Detected. Re-centering..."},Mt=!1,_n=!0,await new Promise(Fe=>setTimeout(Fe,3e3));break}let zn=F.replace(La,"").replace(Pa,"").replace($a,"").replace(Na,""),Ut=zn.toLowerCase().split(/\s+/).map(Fe=>Fe.replace(Fa,"")).filter(Fe=>Fe.length>0),mn=!1;if(Ut.length>=10)for(let Fe=1;Fe<=15;Fe++){let _=Math.max(3,Math.ceil(10/Fe));if(Ut.length<Fe*_)continue;let j=Ut.slice(Ut.length-Fe),se=j.join(" ");if(Fe>1&&se===j.slice(0,Math.floor(Fe/2)).join(" ").repeat(2).trim())continue;let ue=!0;for(let ke=1;ke<_;ke++)if(Ut.slice(Ut.length-Fe*(ke+1),Ut.length-Fe*ke).join(" ")!==se){ue=!1;break}if(ue){mn=!0;break}}if(!mn){let Fe=zn.toLowerCase().replace(Ba,"");if(Fe.length>=20)for(let _=1;_<=10;_++){let j=Math.max(5,Math.ceil(16/_));if(Fe.length<_*j)continue;let se=Fe.substring(Fe.length-_),ue=!0;for(let ke=1;ke<j;ke++)if(Fe.substring(Fe.length-_*(ke+1),Fe.length-_*ke)!==se){ue=!1;break}if(ue){mn=!0;break}}}if(mn){yield{type:"status",content:"Stuttering Detected. Re-centering..."},Mt=!1,ln=!0,await new Promise(Fe=>setTimeout(Fe,3e3));break}}let oe=zt(we),mt=bo(oe);for(;mt.length>gt;){yield*$n();let F=mt[gt],Q=Date.now(),p={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"}[F.toolName]||F.toolName,He=ti[p]||F.toolName,be=jn(p,F.args);yield{type:"status",content:`${He}${be?` ${be}`:""}`};let z="";if(p==="click"){let _=ie(F.args);z=`\u2714 Clicked: ${_.intendedClickText?`${_.intendedClickText}`:""}`}else if(p==="drag"){let _=ie(F.args);z=`\u2714 Dragged: Cell ${_.fromGridId||""} \u2192 Cell ${_.toGridId||""}`}else if(p==="scroll"){let _=ie(F.args);z=`\u2714 Scrolled: ${_.direction||"down"} (${_.amount||1})`}else if(p==="keyboard_typing"){let _=ie(F.args);z=`\u2714 Typed: ${_.text?`"${_.text.length>20?_.text.substring(0,20)+"...":_.text}"`:""}`}else if(p==="key_press")z=`\u2714 Pressed Key: ${ie(F.args).key||""}`;else if(p==="recapture_screen")z="\u2714 Recaptured Screen";else if(p==="web_search"){let{query:_,limit:j=10,aiMode:se=!1}=ie(F.args);z=`${_?"\u2714":"\u2718"} ${se?"AI Search":"Searched"}: ${_?`${_}`:"No Search Query"}${se===!1&&_?` \u2192 ${j}`:""}`}else if(p==="web_scrape"){let _=ie(F.args).url||null;z=`${_?"\u2714":"\u2718"} Visited: ${_||"No Source"}`}else if(p==="view_file"){let{path:_,StartLine:j,EndLine:se,start_line:ue,end_line:ke,startLine:We,endLine:De}=ie(F.args),Ee=j||ue||We,q=se||ke||De,re=parseInt(Ee)||1,de=parseInt(q)||(Ee?re+800:800),Ke="...",Xe=de,ge=(_||"").trim().toLowerCase().replaceAll("\\","/");if(ge.startsWith("#skill"))ge.startsWith("#skill/global/fluxflow")||ge.startsWith("#skills/global/fluxflow")||ge.includes("#skill/fluxflow")||ge.includes("#skills/fluxflow")?z="\u2714 Read Documentation":z=`\u2714 Read Skill: ${te.basename(_.replaceAll("\\","/"))}`;else{try{let Se=te.resolve(process.cwd(),_);if(Ge.existsSync(Se)){let bt=Ge.readFileSync(Se,"utf8").split(`
760
+ `).length;Ke=bt,!Ee&&!q&&bt>800?Xe=Math.min(50,bt):Xe=Math.min(de,bt)}}catch{}let Le=(_||"").toLowerCase(),pt=Le.endsWith(".pdf"),Be=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);pt||Be?z=`${_.length>0?"\u2714":"\u2718"} ${_?`Analyzed: ${te.basename(_)}`:"Analyzed: File Not Found"}`:ot?z=`${_.length>0?"\u2714":"\u2718"} ${_?`Processed: ${te.basename(_)}`:"Processed: File Not Found"}`:z=`${Ke!=="..."?"\u2714":"\u2718"} Read: ${_?`${te.basename(_)} \u2192 ${Ke!=="..."?`Lines ${re} - ${Xe} of ${Ke}`:"File Not Found"}`:"File Not Found"}`}}else if(p==="list_files"||p==="read_folder"){let _=p==="list_files"?"List":"Browsed",j=ie(F.args).path||null,se=ie(F.args).recurse||1;z=`${j?"\u2714":"\u2718"} ${_}: ${j?`${j==="."?`./${se>1?"*":""}`:`${j.replaceAll("\\","/")}${se>1?`${j.endsWith("/")?"*":"/*"}`:`${j.endsWith("/")?"":"/"}`}`}`:"No Folder Selected"}`}else if(p==="write_file"||p==="update_file"){let _=p==="write_file"?"Created":"Edited",j=ie(F.args),se=j.path||null,ke=Object.entries(j).some(([We,De])=>We.startsWith("searchContent")&&typeof De=="string"&&De.startsWith("^LINE:"))?"\u1361":":";z=`${se?"\u2714":"\u2718"} ${_}${ke} ${se?se.replaceAll("\\","/"):"No File Changes"}`}else if(p==="write_pdf"){let _=ie(F.args).path||null;z=`${_?"\u2714":"\u2718"} Generated: ${_.replaceAll("\\","/")||"No PDF Generated"}`}else if(p==="write_docx"){let _=ie(F.args).path||null;z=`${_?"\u2714":"\u2718"} Generated: ${_.replaceAll("\\","/")||"No Docx Generated"}`}else if(p==="file_map"){let _=ie(F.args).path;z=`${_?"\u2714":"\u2718"} Indexed: ${_.replaceAll("\\","/")?""+_:"File Not Found"}`}else if(p.toLowerCase()==="search_keyword"||p.toLowerCase()==="todo")z="";else if(p.toLowerCase()==="generate_image"){let{path:_,outputPath:j,output:se}=ie(F.args);z=`\u2714 Generated: ${_||j||se||"generated_image.png"}`}else if(p==="invoke_sync"||p==="InvokeSync"){let _=jn(p,F.args);z=`\u2714 Called Generalist${_?`: ${_}`:""}`}else if(p==="Invoke"||p==="InvokeAsync"||p==="invoke"){let _=jn(p,F.args);z=`\u2714 Started Generalist${_?`: ${_}`:""}`}else if(p==="get_progress"||p==="GetProgress"){let _=jn(p,F.args);z=`\u2714 Checked${_?`: ${_}`:""}`}else if(p==="cancel"){let _=jn(p,F.args);z=`\u{1F6C7} Cancelled${_?`: ${_}`:""}`}else if(p==="steer"||p==="Steer"){let _=jn(p,F.args);z=`\u2714 Steered${_?`: ${_}`:""}`}else if(p==="EmergencyRollback"){let{method:_}=ie(F.args);z=_==="forceRevert"?"":"\u2714 Rollback Point Checked"}else if(p==="await"||p==="Await"){let{time:_,timeout:j}=ie(F.args),se=parseFloat(j||_)||0;se||(se=120);let ue=De=>{if(De>=60){let Ee=Math.floor(De/60),q=De%60;return`${Ee}m${q>0?` ${q}s`:""}`}return`${De}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 ${ue(se)}`}else p==="Answer"||p==="answer"?z="\u2714 Resolved Sub-Agent Query":p==="exec_command"||p==="ask"?z="":z=`Executed: ${F.toolName}`;if(yield*$n(),p==="exec_command"){let{command:_}=ie(F.args);if(_&&n.systemSettings&&n.systemSettings.allowExternalAccess===!1){let j=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],se=te.resolve(process.cwd()).substring(0,3).toLowerCase(),ue=q=>{let re=[],de="",Ke=null;for(let Xe=0;Xe<q.length;Xe++){let ge=q[Xe];Ke?(ge===Ke&&(Ke=null),de+=ge):ge==='"'||ge==="'"?(Ke=ge,de+=ge):ge==="&"&&q[Xe+1]==="&"||ge==="|"&&q[Xe+1]==="|"?(de.trim()&&(re.push(de.trim()),de=""),Xe++):ge===";"||ge==="|"||ge==="&"?de.trim()&&(re.push(de.trim()),de=""):de+=ge}return de.trim()&&re.push(de.trim()),re},ke=q=>{let re=[],de="",Ke=null;for(let Xe=0;Xe<q.length;Xe++){let ge=q[Xe];Ke?(ge===Ke&&(Ke=null),de+=ge):ge==='"'||ge==="'"?(Ke=ge,de+=ge):/\s/.test(ge)?de&&(re.push(de),de=""):de+=ge}return de&&re.push(de),re},We=q=>{let re=q.replace(/^['"]|['"]$/g,"").trim();return!re||process.platform==="win32"&&/^\/[a-zA-Z0-9?]+$/.test(re)?!1:j.some(de=>{if(de.source==="[a-zA-Z]:[\\\\\\/]"){let Ke=re.match(/[a-zA-Z]:[\\\/]/i);return Ke&&Ke[0].toLowerCase()!==se}return de.test(re)})};if(ue(_).some(q=>{let re=ke(q);if(re.length===0)return!1;let de=re[0].replace(/^['"]|['"]$/g,"").toLowerCase();if(["echo","printf","write-output"].includes(de)){let Xe=!1;return re.some(ge=>{let St=ge.replace(/^['"]|['"]$/g,"");if(St===">"||St===">>"||St==="<")return Xe=!0,!1;if(St.startsWith(">")||St.startsWith("<")){let Le=St.replace(/^[><]+/,"");return We(Le)}return Xe?(Xe=!1,We(ge)):!1})}return re.some(Xe=>We(Xe))})){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(re=>setTimeout(re,50)),n.onExecChunk&&n.onExecChunk(`ERROR: ${q}`),await new Promise(re=>setTimeout(re,50)),n.onExecEnd&&n.onExecEnd(),Re.push({role:"user",text:`[TOOL RESULT]: ERROR: ${q}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${q}`},gt++;continue}}n.onExecStart&&n.onExecStart(_||"No Command"),yield{type:"exec_start"}}let Ft=ie(F.args),Fn=Ft.path||Ft.targetPath||null;if(Fn){let _=n.systemSettings&&n.systemSettings.allowExternalAccess===!1,j=te.resolve(Fn),se=te.resolve(process.cwd());if(_&&!j.startsWith(se)){let ue="Access Denied. You are not allowed to access files outside the current workspace.";if(p==="write_file"||p==="update_file"){let We=`\u2718 ${p==="write_file"?"Write Canceled":"Edit Canceled"}: ${Ft.path||"..."}`,De=115;process.stdout.isTTY&&(De=process.stdout.columns-5||120);let Ee=Math.min(We.length+4,De),q=`${We.padEnd(Ee-2).substring(0,Ee-2)}`;yield{type:"visual_feedback",content:qt(`${ze?`
761
761
  `:""}${q}
762
- `)},ze=!1}Ce.push({role:"user",text:`[TOOL RESULT]: ERROR: ${ce}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${ce}`},mt++;continue}}if(n.onToolApproval&&(p==="write_file"||p==="update_file"||p==="exec_command")){let V=n.systemSettings||{},ne=V.autoExec,ce=null,ye=!1,He=!1,De=!1;if(p==="exec_command"){let{command:Pe}=oe(U.args),pt=(Pe||"").trim(),Ue=(Gt,bt)=>{if(!bt)return!1;let tn=bt.split(",").map(jt=>jt.trim().toLowerCase()).filter(Boolean),lt=Gt.toLowerCase();return tn.some(jt=>lt.startsWith(jt))},st=Ue(pt,V.alwaysAskCommands),ke=Ue(pt,V.autoApproveCommands);if(He=Ue(pt,V.autoDisallowCommands),st?ye=!0:(ke||V.autoApproveGit&&/^git\s+commit\b/i.test(pt))&&(ce="allow"),!ye&&!ce){if(V.networkAccess===!1){let bt=pt.trim().replace(/\s+/g," ").replace(/^['"]+|['"]+$/g,"").toLowerCase().split(" "),lt=bt[0].split("/").pop().split("\\").pop().replace(/\.exe$/,""),jt=new Set(["curl","wget","httpie","xh","ssh","scp","sftp","rsync","ftp","lftp","tftp","telnet","nc","netcat","socat","ping","traceroute","tracert","dig","nslookup","host","whois","nmap","docker","podman","kubectl","helm","gcloud","aws","az","terraform","ansible-playbook","nix","nix-env","apt","apt-get","dpkg","yum","dnf","pacman","zypper","brew","apk","choco","scoop","conda","mamba","aria2c","axel","smbclient","lynx","w3m","links","elinks","heroku","netlify","vercel","firebase","supabase","wrangler","flyctl","powershell","pwsh","certutil","bitsadmin","cloudflared","ngrok","tailscale","zerotier","rclone"]),ct=!1;jt.has(lt)&&(ct=!0);let it=Cn=>bt.slice(1).some(pn=>Cn.includes(pn)),ft=Cn=>{let pn=bt.findIndex(yn=>Cn.includes(yn)),Fn=bt.findIndex(yn=>["run","exec","test"].includes(yn));return pn!==-1&&!(Fn!==-1&&Fn<pn)};lt==="git"&&it(["clone","pull","push","fetch"])&&(ct=!0),lt==="go"&&it(["get","install"])&&(ct=!0),lt==="npm"&&ft(["install","i","update","add"])&&(ct=!0),lt==="yarn"&&ft(["add","install","upgrade"])&&(ct=!0),lt==="pnpm"&&ft(["add","install","update"])&&(ct=!0),lt==="bun"&&ft(["add","install","update"])&&(ct=!0),lt==="deno"&&it(["install","add"])&&(ct=!0),lt==="pip"&&it(["install","download"])&&(ct=!0),lt==="pip3"&&it(["install","download"])&&(ct=!0),lt==="cargo"&&it(["install","add"])&&(ct=!0),["bash","sh","zsh","fish"].includes(lt)&&it(["-c"])&&(ct=!0),lt==="cmd"&&it(["/c"])&&(ct=!0),ct&&(ce="deny",De=!0)}!ce&&He&&(ce="deny")}!ye&&!ce&&ne&&(ce="allow")}else ne&&(ce="allow");let _e=ce,q="";ce==="deny"&&(De?q="network":He?q="settings":q="prohibited");let se=!1,ae="",Ke=[],Qe=0,de=!1,St="";if(!_e){if(p==="write_file"||p==="update_file")try{let Ue=oe(U.args),{path:st}=Ue;if(st){let ke=ee.resolve(process.cwd(),st),Gt=it=>it?it.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,ft=>ft.toUpperCase()):"",bt=Gt(ke),tn="",lt=!1,jt=await Un(),ct=Gt(jt?.file_focused);if(jt&&ct===bt&&jt.full_content?(tn=jt.full_content,lt=!0):Ge.existsSync(ke)&&(tn=Ge.readFileSync(ke,"utf8"),lt=!0),ae=tn,await Io.recordFileChange(ke,tn),lt){let it=tn;if(p==="write_file"){let ft=Ue.content||Ue.newContent||"";it=ft.endsWith(`
763
- `)?ft:ft+`
764
- `,St=it}else{let{patchPairs:ft,allowMultiple:Cn,error:pn}=xi(Ue);if(pn){let Qt=`[TOOL RESULT]: ERROR: ${pn}`;Ce.push({role:"user",text:Qt}),await vt("toolFailure"),n.onToolResult&&n.onToolResult("failure",p),yield{type:"tool_result",content:Qt,toolName:p},mt++;continue}let Fn=Ue.allowMultiple!==void 0?Ue.allowMultiple===!0||String(Ue.allowMultiple).toLowerCase()==="true":Cn;Qe=ft.length;let yn=bi(tn,ft,{allowMultiple:Fn});it=yn.content,St=it,Ke=yn.results;let _o=Ke.filter(Qt=>Qt.success),hs=Ke.filter(Qt=>!Qt.success);if(_o.length===0){let Qt=`[TOOL RESULT]: ERROR: Failed to apply patches to [${ee.basename(ke)}].
765
- ${hs.map(Ao=>` \u2022 ${Ao.error}`).join(`
766
- `)}`,no=`\u2714 Edited: ${ee.basename(ke.replaceAll("\\","/"))}`,ut=115;process.stdout.isTTY&&(ut=process.stdout.columns-5||120);let Vt=Math.min(no.length+4,ut),oo=`${no.padEnd(Vt-2).substring(0,Vt-2)}`;yield{type:"visual_feedback",content:Yt(`${ze?`
767
- `:""}${oo}`)},ze=!1,Ce.push({role:"user",text:Qt}),await vt("toolFailure"),n.onToolResult&&n.onToolResult("failure",p),yield{type:"tool_result",content:Qt,toolName:p},mt++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${ee.basename(ke)}`},Ks(ke,tn,it),se=!0,await new Promise(ft=>setTimeout(ft,50))}else if(p==="write_file"){let it=Ue.content||Ue.newContent||"",ft=it.endsWith(`
768
- `)?it:it+`
769
- `;St=ft,Ge.existsSync(ke)||(de=!0,Ge.mkdirSync(ee.dirname(ke),{recursive:!0}),Ge.writeFileSync(ke,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${ee.basename(ke)}`},Ks(ke,"",ft),se=!0,await new Promise(Cn=>setTimeout(Cn,50))}}}catch(Ue){console.error("Simulation/Diff Error:",Ue)}let Pe=null;Vs(Ue=>{Pe=Ue});let pt=n.onToolApproval;if(_e=await new Promise(async Ue=>{let st=setInterval(()=>{Pe&&(ss.onIDEApproval&&ss.onIDEApproval(Pe),clearInterval(st),Ue(Pe))},100);try{let ke=await pt(p,U.args);clearInterval(st),Ue(ke)}catch{clearInterval(st),Ue("deny")}}),Vs(null),p==="write_file"||p==="update_file"){let{path:Ue}=oe(U.args);if(Ue){let st=ee.resolve(process.cwd(),Ue);if(Lr(st,_e),_e==="deny"&&de&&Ge.existsSync(st))try{Ge.unlinkSync(st)}catch{}}}_e==="deny"&&(q="user")}if(_e==="allow"&&se&&Ko()){let{path:Pe}=oe(U.args),pt=ee.resolve(process.cwd(),Pe),Ue=ut=>ut?ee.resolve(ut).replace(/\\/g,"/").toLowerCase():"",st=await Un(),ke="";if(st&&st.file_focused&&Ue(st.file_focused)===Ue(pt)&&st.full_content&&(ke=st.full_content),!ke&&Ge.existsSync(pt)){let ut=Ge.readFileSync(pt,"utf8");ut&&(ke=ut)}!ke&&St&&(ke=St),(ke||de)&&Ge.writeFileSync(pt,ke,"utf8");let Gt=ke.split(/\r?\n/),bt=Gt.length,tn=Buffer.byteLength(ke,"utf8"),lt="";ae&&(lt=`Old File contents:
770
- ${ae.split(/\r?\n/).map((Vt,oo)=>`${oo+1} | ${Vt}`).join(`
762
+ `)},ze=!1}Re.push({role:"user",text:`[TOOL RESULT]: ERROR: ${ue}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${ue}`},gt++;continue}}if(n.onToolApproval&&(p==="write_file"||p==="update_file"||p==="exec_command")){let j=n.systemSettings||{},se=j.autoExec,ue=null,ke=!1,We=!1,De=!1;if(p==="exec_command"){let{command:Le}=ie(F.args),pt=(Le||"").trim(),Be=(jt,bt)=>{if(!bt)return!1;let nn=bt.split(",").map(Vt=>Vt.trim().toLowerCase()).filter(Boolean),at=jt.toLowerCase();return nn.some(Vt=>at.startsWith(Vt))},ot=Be(pt,j.alwaysAskCommands),Se=Be(pt,j.autoApproveCommands);if(We=Be(pt,j.autoDisallowCommands),ot?ke=!0:(Se||j.autoApproveGit&&/^git\s+commit\b/i.test(pt))&&(ue="allow"),!ke&&!ue){if(j.networkAccess===!1){let bt=pt.trim().replace(/\s+/g," ").replace(/^['"]+|['"]+$/g,"").toLowerCase().split(" "),at=bt[0].split("/").pop().split("\\").pop().replace(/\.exe$/,""),Vt=new Set(["curl","wget","httpie","xh","ssh","scp","sftp","rsync","ftp","lftp","tftp","telnet","nc","netcat","socat","ping","traceroute","tracert","dig","nslookup","host","whois","nmap","docker","podman","kubectl","helm","gcloud","aws","az","terraform","ansible-playbook","nix","nix-env","apt","apt-get","dpkg","yum","dnf","pacman","zypper","brew","apk","choco","scoop","conda","mamba","aria2c","axel","smbclient","lynx","w3m","links","elinks","heroku","netlify","vercel","firebase","supabase","wrangler","flyctl","powershell","pwsh","certutil","bitsadmin","cloudflared","ngrok","tailscale","zerotier","rclone"]),lt=!1;Vt.has(at)&&(lt=!0);let st=vn=>bt.slice(1).some(pn=>vn.includes(pn)),dt=vn=>{let pn=bt.findIndex(yn=>vn.includes(yn)),Bn=bt.findIndex(yn=>["run","exec","test"].includes(yn));return pn!==-1&&!(Bn!==-1&&Bn<pn)};at==="git"&&st(["clone","pull","push","fetch"])&&(lt=!0),at==="go"&&st(["get","install"])&&(lt=!0),at==="npm"&&dt(["install","i","update","add"])&&(lt=!0),at==="yarn"&&dt(["add","install","upgrade"])&&(lt=!0),at==="pnpm"&&dt(["add","install","update"])&&(lt=!0),at==="bun"&&dt(["add","install","update"])&&(lt=!0),at==="deno"&&st(["install","add"])&&(lt=!0),at==="pip"&&st(["install","download"])&&(lt=!0),at==="pip3"&&st(["install","download"])&&(lt=!0),at==="cargo"&&st(["install","add"])&&(lt=!0),["bash","sh","zsh","fish"].includes(at)&&st(["-c"])&&(lt=!0),at==="cmd"&&st(["/c"])&&(lt=!0),lt&&(ue="deny",De=!0)}!ue&&We&&(ue="deny")}!ke&&!ue&&se&&(ue="allow")}else se&&(ue="allow");let Ee=ue,q="";ue==="deny"&&(De?q="network":We?q="settings":q="prohibited");let re=!1,de="",Ke=[],Xe=0,ge=!1,St="";if(!Ee){if(p==="write_file"||p==="update_file")try{let Be=ie(F.args),{path:ot}=Be;if(ot){let Se=te.resolve(process.cwd(),ot),jt=st=>st?st.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,dt=>dt.toUpperCase()):"",bt=jt(Se),nn="",at=!1,Vt=await Wn(),lt=jt(Vt?.file_focused);if(Vt&&lt===bt&&Vt.full_content?(nn=Vt.full_content,at=!0):Ge.existsSync(Se)&&(nn=Ge.readFileSync(Se,"utf8"),at=!0),de=nn,await Do.recordFileChange(Se,nn),at){let st=nn;if(p==="write_file"){let dt=Be.content||Be.newContent||"";st=dt.endsWith(`
763
+ `)?dt:dt+`
764
+ `,St=st}else{let{patchPairs:dt,allowMultiple:vn,error:pn}=wi(Be);if(pn){let Zt=`[TOOL RESULT]: ERROR: ${pn}`;Re.push({role:"user",text:Zt}),await vt("toolFailure"),n.onToolResult&&n.onToolResult("failure",p),yield{type:"tool_result",content:Zt,toolName:p},gt++;continue}let Bn=Be.allowMultiple!==void 0?Be.allowMultiple===!0||String(Be.allowMultiple).toLowerCase()==="true":vn;Xe=dt.length;let yn=Ti(nn,dt,{allowMultiple:Bn});st=yn.content,St=st,Ke=yn.results;let Ao=Ke.filter(Zt=>Zt.success),ps=Ke.filter(Zt=>!Zt.success);if(Ao.length===0){let Zt=`[TOOL RESULT]: ERROR: Failed to apply patches to [${te.basename(Se)}].
765
+ ${ps.map(Eo=>` \u2022 ${Eo.error}`).join(`
766
+ `)}`,oo=`\u2714 Edited: ${te.basename(Se.replaceAll("\\","/"))}`,ft=115;process.stdout.isTTY&&(ft=process.stdout.columns-5||120);let Kt=Math.min(oo.length+4,ft),so=`${oo.padEnd(Kt-2).substring(0,Kt-2)}`;yield{type:"visual_feedback",content:qt(`${ze?`
767
+ `:""}${so}`)},ze=!1,Re.push({role:"user",text:Zt}),await vt("toolFailure"),n.onToolResult&&n.onToolResult("failure",p),yield{type:"tool_result",content:Zt,toolName:p},gt++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${te.basename(Se)}`},Ys(Se,nn,st),re=!0,await new Promise(dt=>setTimeout(dt,50))}else if(p==="write_file"){let st=Be.content||Be.newContent||"",dt=st.endsWith(`
768
+ `)?st:st+`
769
+ `;St=dt,Ge.existsSync(Se)||(ge=!0,Ge.mkdirSync(te.dirname(Se),{recursive:!0}),Ge.writeFileSync(Se,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${te.basename(Se)}`},Ys(Se,"",dt),re=!0,await new Promise(vn=>setTimeout(vn,50))}}}catch(Be){console.error("Simulation/Diff Error:",Be)}let Le=null;Ks(Be=>{Le=Be});let pt=n.onToolApproval;if(Ee=await new Promise(async Be=>{let ot=setInterval(()=>{Le&&(is.onIDEApproval&&is.onIDEApproval(Le),clearInterval(ot),Be(Le))},100);try{let Se=await pt(p,F.args);clearInterval(ot),Be(Se)}catch{clearInterval(ot),Be("deny")}}),Ks(null),p==="write_file"||p==="update_file"){let{path:Be}=ie(F.args);if(Be){let ot=te.resolve(process.cwd(),Be);if(Nr(ot,Ee),Ee==="deny"&&ge&&Ge.existsSync(ot))try{Ge.unlinkSync(ot)}catch{}}}Ee==="deny"&&(q="user")}if(Ee==="allow"&&re&&Yo()){let{path:Le}=ie(F.args),pt=te.resolve(process.cwd(),Le),Be=ft=>ft?te.resolve(ft).replace(/\\/g,"/").toLowerCase():"",ot=await Wn(),Se="";if(ot&&ot.file_focused&&Be(ot.file_focused)===Be(pt)&&ot.full_content&&(Se=ot.full_content),!Se&&Ge.existsSync(pt)){let ft=Ge.readFileSync(pt,"utf8");ft&&(Se=ft)}!Se&&St&&(Se=St),(Se||ge)&&Ge.writeFileSync(pt,Se,"utf8");let jt=Se.split(/\r?\n/),bt=jt.length,nn=Buffer.byteLength(Se,"utf8"),at="";de&&(at=`Old File contents:
770
+ ${de.split(/\r?\n/).map((Kt,so)=>`${so+1} | ${Kt}`).join(`
771
771
  `)}
772
772
 
773
- `);let jt="";if(bt<=100)jt=Gt.join(`
774
- `);else{let ut=Gt.slice(0,50).join(`
775
- `),Vt=Gt.slice(-50).join(`
776
- `);jt=`${ut}
773
+ `);let Vt="";if(bt<=100)Vt=jt.join(`
774
+ `);else{let ft=jt.slice(0,50).join(`
775
+ `),Kt=jt.slice(-50).join(`
776
+ `);Vt=`${ft}
777
777
 
778
778
  ... [${bt-100} lines truncated for history stability] ...
779
779
 
780
- ${Vt}`}let ct="";if(p==="update_file"){let ut=ki(ae,ke,Ke,12,n?.compressToolResults||ss?.systemSettings?.compressToolResults);ct=`SUCCESS: File [${Pe}] updated via IDE Companion (May have user edits). [${Ke.length}/${Qe}] blocks applied.
780
+ ${Kt}`}let lt="";if(p==="update_file"){let ft=Si(de,Se,Ke,12,n?.compressToolResults||is?.systemSettings?.compressToolResults);lt=`SUCCESS: File [${Le}] updated via IDE Companion (May have user edits). [${Ke.length}/${Xe}] blocks applied.
781
781
 
782
- ${ut}`}else{let ut=ke.split(/\r?\n/),Vt=ut.length,oo=Buffer.byteLength(ke,"utf8"),Ao="";ae&&(Ao=`Old File contents:
783
- ${ae.split(/\r?\n/).map((ys,ca)=>`${ca+1} | ${ys}`).join(`
782
+ ${ft}`}else{let ft=Se.split(/\r?\n/),Kt=ft.length,so=Buffer.byteLength(Se,"utf8"),Eo="";de&&(Eo=`Old File contents:
783
+ ${de.split(/\r?\n/).map((xs,ua)=>`${ua+1} | ${xs}`).join(`
784
784
  `)}
785
785
 
786
- `);let ps="";if(Vt<=100)ps=ut.join(`
787
- `);else{let pi=ut.slice(0,50).join(`
788
- `),ys=ut.slice(-50).join(`
789
- `);ps=`${pi}
790
-
791
- ... [${Vt-100} lines truncated] ...
792
-
793
- ${ys}`}ct=`SUCCESS: File [${Pe}] saved via IDE Companion (May have user edits).
794
- - Stats: [${Vt} lines, ${(oo/1024).toFixed(1)} KB]
795
- ${Ao}- Content Preview:
796
-
797
- ${ps}`}let it=p==="write_file"?"Created":"Edited",ft=oe(U.args),pn=Object.entries(ft).some(([ut,Vt])=>ut.startsWith("searchContent")&&typeof Vt=="string"&&Vt.startsWith("^LINE:"))?"\u1361":":",Fn=`${Pe?"\u2714":"\u2718"} ${it}${pn} ${Pe?Pe.replaceAll("\\","/"):"No File Changes"}`,yn=115;process.stdout.isTTY&&(yn=process.stdout.columns-5||120);let _o=Math.min(Fn.length+4,yn),hs=`${Fn.padEnd(_o-2).substring(0,_o-2)}`;yield{type:"visual_feedback",content:Yt(`${ze?`
798
- `:""}${hs}`)},ze=!1;let Qt=Date.now();je=Qt,yield{type:"tool_time",content:Qt-Z};let no=`[TOOL RESULT]: ${ct}`;Ce.push({role:"user",text:no}),Sn=!0,await vt("toolSuccess"),n.onToolResult&&n.onToolResult("success",p),yield{type:"tool_result",content:ct,aiContent:no,toolName:p},mt++;continue}if(_e==="deny"){let Pe=`Permission Denied: Prohibited ${p==="exec_command"?"Command":"file edit"}.`;if(q==="user"?Pe="Permission Denied by User":q==="settings"?Pe="Permission Denied by User Policy":q==="network"?Pe="Permission Denied: Sandbox Network Access Disabled by User Policy.":q==="prohibited"&&p==="exec_command"&&(Pe="Permission Denied: Prohibited Command in User Policy"),p==="write_file"||p==="update_file"){let Ue=`\u2718 ${p==="write_file"?"Write Cancelled":"Edit Denied"}: ${oe(U.args).path.replaceAll("\\","/")||"..."}`,st=115;process.stdout.isTTY&&(st=process.stdout.columns-5||120);let ke=Math.min(Ue.length+4,st),Gt=`${Ue.padEnd(ke-2).substring(0,ke-2)}`,bt=` ${" ".repeat(ke)} `;yield{type:"visual_feedback",content:Yt(`${ze?`
799
- `:""}${Gt}
800
- `)},ze=!1}p==="exec_command"&&(await new Promise(pt=>setTimeout(pt,50)),n.onExecChunk&&n.onExecChunk(`ERROR: ${Pe}`),await new Promise(pt=>setTimeout(pt,50)),n.onExecEnd&&n.onExecEnd()),Ce.push({role:"user",text:`[TOOL RESULT]: DENIED: ${Pe}`}),yield{type:"tool_result",content:`[TOOL RESULT]: DENIED: ${Pe}`},await vt("toolDenied"),n.onToolResult&&n.onToolResult("denied",p),mt++;continue}}if(Q){let _=115;process.stdout.isTTY&&(_=process.stdout.columns-5||120);let V=await s(),ne=!1;V&&(ne=V.trim().length>0);let ce=Math.min(Q.length+4,_),ye=`${Q.padEnd(ce-2).substring(0,ce-2)}`;yield{type:"visual_feedback",content:Yt(`${ze?`
801
- `:""}${ye}${Q.includes("\u2714")&&(Q.includes("Created")||Q.includes("Edited"))?"":`${ne?"":`
802
- `}`}`)},ze=!1}if(je>0){let _=Date.now()-je,V=Math.max(0,1e3-_);V>0&&await new Promise(ne=>setTimeout(ne,V))}let En={chatId:g,history:t,onChunk:_=>n.onExecChunk?n.onExecChunk(_):null,onAskUser:n.onAskUser,systemSettings:n.systemSettings,mode:a,isMultiModal:gt(be),onVisualFeedback:n.onVisualFeedback,onSubagentUpdate:n.onSubagentUpdate,onTokenChunk:n.onTokenChunk,modelName:be,aiProvider:n.aiProvider,apiKey:n.apiKey,onUsage:n.onUsage};if(p==="write_file"||p==="update_file")try{let{path:_}=oe(U.args);if(_){let V=ee.resolve(process.cwd(),_),ne=await Un();ne&&ne.file_focused===V&&ne.full_content&&(En.forcedContent=ne.full_content)}}catch{}et.push(p);let Fe=await ho(p,U.args,En);if((p==="write_file"||p==="update_file")&&Fe.startsWith("SUCCESS")){let{path:_}=oe(U.args);if(_){let V=ee.resolve(process.cwd(),_);Or(V)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let Ft=Date.now();je=Ft,yield{type:"tool_time",content:Ft-Z},j=Ft;let Ht=null;if(typeof Fe=="object"&&Fe.binaryPart&&(Ht=Fe.binaryPart,Fe=Fe.text),p==="search_keyword"){let{keyword:_,path:V}=oe(U.args),ne=typeof Fe=="string"&&Fe.startsWith("[GLOB]");ne&&(Fe=Fe.slice(6).trimStart());let ce=typeof Fe=="string"&&Fe.startsWith("[DIR]");ce&&(Fe=Fe.slice(5).trimStart());let ye=0;if(Fe){let de=Fe.match(/Found (\d+) match/i);de&&(ye=parseInt(de[1]))}let He=(V||"").trim().toLowerCase().replaceAll("\\","/"),De=He==="#doc"||He==="#docs"||He==="#documentation"||He.includes("#skill/global/fluxflow")||He.includes("#skill/fluxflow")||He.includes("#skills/fluxflow")||He.includes("#skills/global/fluxflow"),_e,q=115;process.stdout.isTTY&&(q=process.stdout.columns-5||120);let se=Math.max(10,(q+5)/3),ae=Math.max(10,(q+5)/4);if(De)_e=`${_?"\u2714":"\u2718"} Searched Documentation`;else{let de=V?V.replace(/[\/\\]+$/,""):null,St=de&&de!=="."?`"${ne?V:ce?`${de}/*`:de}"`:"./",Pe=St.length>ae?`${St.slice(0,ae)}...`:St;_e=`${_?"\u2714":"\u2718"} Searched: "${_?_.length>q/2?`${_.slice(0,se)}...`:_:""}" in ${Pe.replaceAll("\\","/")} \u2192 ${ye} Match${ye===1?"":"es"}`}let Ke=Math.min(_e.length+4,q),Qe=`${_e.padEnd(Ke-2).substring(0,Ke-2)}`;yield{type:"visual_feedback",content:Yt(`${ze?`
803
- `:""}${Qe}
804
- `)},ze=!1}if(p==="EmergencyRollback"){let{method:_}=oe(U.args);if(_==="forceRevert"){let V=0;if(Fe){let se=Fe.match(/Total\s*:\s*(\d+)/i);se&&(V=parseInt(se[1]))}let ce=Fe&&Fe.startsWith("ERROR:")?"\u2718 Emergency Rollback Failed":`\u2714 Emergency Rollback \u2192 ${V} file${V===1?"":"s"} processed`,ye=115;process.stdout.isTTY&&(ye=process.stdout.columns-5||120);let He=await s(),De=!1;He&&(De=He.trim().length>0);let _e=Math.min(ce.length+4,ye),q=`${ce.padEnd(_e-2).substring(0,_e-2)}`;yield{type:"visual_feedback",content:Yt(`${ze?`
786
+ `);let ys="";if(Kt<=100)ys=ft.join(`
787
+ `);else{let bi=ft.slice(0,50).join(`
788
+ `),xs=ft.slice(-50).join(`
789
+ `);ys=`${bi}
790
+
791
+ ... [${Kt-100} lines truncated] ...
792
+
793
+ ${xs}`}lt=`SUCCESS: File [${Le}] saved via IDE Companion (May have user edits).
794
+ - Stats: [${Kt} lines, ${(so/1024).toFixed(1)} KB]
795
+ ${Eo}- Content Preview:
796
+
797
+ ${ys}`}let st=p==="write_file"?"Created":"Edited",dt=ie(F.args),pn=Object.entries(dt).some(([ft,Kt])=>ft.startsWith("searchContent")&&typeof Kt=="string"&&Kt.startsWith("^LINE:"))?"\u1361":":",Bn=`${Le?"\u2714":"\u2718"} ${st}${pn} ${Le?Le.replaceAll("\\","/"):"No File Changes"}`,yn=115;process.stdout.isTTY&&(yn=process.stdout.columns-5||120);let Ao=Math.min(Bn.length+4,yn),ps=`${Bn.padEnd(Ao-2).substring(0,Ao-2)}`;yield{type:"visual_feedback",content:qt(`${ze?`
798
+ `:""}${ps}`)},ze=!1;let Zt=Date.now();je=Zt,yield{type:"tool_time",content:Zt-Q};let oo=`[TOOL RESULT]: ${lt}`;Re.push({role:"user",text:oo}),Sn=!0,await vt("toolSuccess"),n.onToolResult&&n.onToolResult("success",p),yield{type:"tool_result",content:lt,aiContent:oo,toolName:p},gt++;continue}if(Ee==="deny"){let Le=`Permission Denied: Prohibited ${p==="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"&&p==="exec_command"&&(Le="Permission Denied: Prohibited Command in User Policy"),p==="write_file"||p==="update_file"){let Be=`\u2718 ${p==="write_file"?"Write Cancelled":"Edit Denied"}: ${ie(F.args).path.replaceAll("\\","/")||"..."}`,ot=115;process.stdout.isTTY&&(ot=process.stdout.columns-5||120);let Se=Math.min(Be.length+4,ot),jt=`${Be.padEnd(Se-2).substring(0,Se-2)}`,bt=` ${" ".repeat(Se)} `;yield{type:"visual_feedback",content:qt(`${ze?`
799
+ `:""}${jt}
800
+ `)},ze=!1}p==="exec_command"&&(await new Promise(pt=>setTimeout(pt,50)),n.onExecChunk&&n.onExecChunk(`ERROR: ${Le}`),await new Promise(pt=>setTimeout(pt,50)),n.onExecEnd&&n.onExecEnd()),Re.push({role:"user",text:`[TOOL RESULT]: DENIED: ${Le}`}),yield{type:"tool_result",content:`[TOOL RESULT]: DENIED: ${Le}`},await vt("toolDenied"),n.onToolResult&&n.onToolResult("denied",p),gt++;continue}}if(z){let _=115;process.stdout.isTTY&&(_=process.stdout.columns-5||120);let j=await s(),se=!1;j&&(se=j.trim().length>0);let ue=Math.min(z.length+4,_),ke=`${z.padEnd(ue-2).substring(0,ue-2)}`;yield{type:"visual_feedback",content:qt(`${ze?`
801
+ `:""}${ke}${z.includes("\u2714")&&(z.includes("Created")||z.includes("Edited"))?"":`${se?"":`
802
+ `}`}`)},ze=!1}if(je>0){let _=Date.now()-je,j=Math.max(0,1e3-_);j>0&&await new Promise(se=>setTimeout(se,j))}let Cn={chatId:g,history:t,onChunk:_=>n.onExecChunk?n.onExecChunk(_):null,onAskUser:n.onAskUser,systemSettings:n.systemSettings,mode:a,isMultiModal:ut(Te),onVisualFeedback:n.onVisualFeedback,onSubagentUpdate:n.onSubagentUpdate,onTokenChunk:n.onTokenChunk,modelName:Te,aiProvider:n.aiProvider,apiKey:n.apiKey,onUsage:n.onUsage};if(p==="write_file"||p==="update_file")try{let{path:_}=ie(F.args);if(_){let j=te.resolve(process.cwd(),_),se=await Wn();se&&se.file_focused===j&&se.full_content&&(Cn.forcedContent=se.full_content)}}catch{}Ze.push(p);let Ne=await po(p,F.args,Cn);if((p==="write_file"||p==="update_file")&&Ne.startsWith("SUCCESS")){let{path:_}=ie(F.args);if(_){let j=te.resolve(process.cwd(),_);$r(j)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let Bt=Date.now();je=Bt,yield{type:"tool_time",content:Bt-Q},G=Bt;let Gt=null;if(typeof Ne=="object"&&Ne.binaryPart&&(Gt=Ne.binaryPart,Ne=Ne.text),p==="search_keyword"){let{keyword:_,path:j}=ie(F.args),se=typeof Ne=="string"&&Ne.startsWith("[GLOB]");se&&(Ne=Ne.slice(6).trimStart());let ue=typeof Ne=="string"&&Ne.startsWith("[DIR]");ue&&(Ne=Ne.slice(5).trimStart());let ke=0;if(Ne){let ge=Ne.match(/Found (\d+) match/i);ge&&(ke=parseInt(ge[1]))}let We=(j||"").trim().toLowerCase().replaceAll("\\","/"),De=We==="#doc"||We==="#docs"||We==="#documentation"||We.includes("#skill/global/fluxflow")||We.includes("#skill/fluxflow")||We.includes("#skills/fluxflow")||We.includes("#skills/global/fluxflow"),Ee,q=115;process.stdout.isTTY&&(q=process.stdout.columns-5||120);let re=Math.max(10,(q+5)/3),de=Math.max(10,(q+5)/4);if(De)Ee=`${_?"\u2714":"\u2718"} Searched Documentation`;else{let ge=j?j.replace(/[\/\\]+$/,""):null,St=ge&&ge!=="."?`"${se?j:ue?`${ge}/*`:ge}"`:"./",Le=St.length>de?`${St.slice(0,de)}...`:St;Ee=`${_?"\u2714":"\u2718"} Searched: "${_?_.length>q/2?`${_.slice(0,re)}...`:_:""}" in ${Le.replaceAll("\\","/")} \u2192 ${ke} Match${ke===1?"":"es"}`}let Ke=Math.min(Ee.length+4,q),Xe=`${Ee.padEnd(Ke-2).substring(0,Ke-2)}`;yield{type:"visual_feedback",content:qt(`${ze?`
803
+ `:""}${Xe}
804
+ `)},ze=!1}if(p==="EmergencyRollback"){let{method:_}=ie(F.args);if(_==="forceRevert"){let j=0;if(Ne){let re=Ne.match(/Total\s*:\s*(\d+)/i);re&&(j=parseInt(re[1]))}let ue=Ne&&Ne.startsWith("ERROR:")?"\u2718 Emergency Rollback Failed":`\u2714 Emergency Rollback \u2192 ${j} file${j===1?"":"s"} processed`,ke=115;process.stdout.isTTY&&(ke=process.stdout.columns-5||120);let We=await s(),De=!1;We&&(De=We.trim().length>0);let Ee=Math.min(ue.length+4,ke),q=`${ue.padEnd(Ee-2).substring(0,Ee-2)}`;yield{type:"visual_feedback",content:qt(`${ze?`
805
805
  `:""}${q}${De?"":`
806
- `}`)},ze=!1}}if(p==="todo"){let{method:_,tasks:V,markDone:ne}=oe(U.args),ce="",ye=[],He=De=>{if(!De)return[];let _e=Array.isArray(De)?De:[];if(_e.length===0&&typeof De=="string"){let q=De.trim();if(q.startsWith("[")&&q.endsWith("]")){let se=q.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);se?_e=se.map(ae=>ae.slice(1,-1).replace(/\\(.)/g,"$1")):_e=q.slice(1,-1).split(",").map(ae=>ae.trim()).filter(Boolean)}else _e=De.split(`
807
- `)}return _e.filter(q=>String(q).trim()).map(q=>{let se=String(q).trim();return se.startsWith("- [")?se.substring(6).trim():se})};if(_==="create"?(ce="\x1B[32m\u2192\x1B[0m Created Goals",ye=He(V).map(De=>`\x1B[90m\u25CB\x1B[0m ${De}`)):_==="append"?(ce="\x1B[34m\u2795\x1B[0m Added New Goals",ye=He(V).map(De=>`\x1B[90m\u25CB\x1B[0m ${De}`)):_==="get"&&(ce=ne?"\x1B[36m\u21BB\x1B[0m Updated Goals":"\x1B[35m\u2022\x1B[0m Reviewed Goals",ye=(Fe||"").split(`
806
+ `}`)},ze=!1}}if(p==="todo"){let{method:_,tasks:j,markDone:se}=ie(F.args),ue="",ke=[],We=De=>{if(!De)return[];let Ee=Array.isArray(De)?De:[];if(Ee.length===0&&typeof De=="string"){let q=De.trim();if(q.startsWith("[")&&q.endsWith("]")){let re=q.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);re?Ee=re.map(de=>de.slice(1,-1).replace(/\\(.)/g,"$1")):Ee=q.slice(1,-1).split(",").map(de=>de.trim()).filter(Boolean)}else Ee=De.split(`
807
+ `)}return Ee.filter(q=>String(q).trim()).map(q=>{let re=String(q).trim();return re.startsWith("- [")?re.substring(6).trim():re})};if(_==="create"?(ue="\x1B[32m\u2192\x1B[0m Created Goals",ke=We(j).map(De=>`\x1B[90m\u25CB\x1B[0m ${De}`)):_==="append"?(ue="\x1B[34m\u2795\x1B[0m Added New Goals",ke=We(j).map(De=>`\x1B[90m\u25CB\x1B[0m ${De}`)):_==="get"&&(ue=se?"\x1B[36m\u21BB\x1B[0m Updated Goals":"\x1B[35m\u2022\x1B[0m Reviewed Goals",ke=(Ne||"").split(`
808
808
  `).slice(1).join(`
809
809
  `).split(`
810
- `).filter(_e=>_e.trim().startsWith("- [")).map(_e=>{let q=_e.trim(),se=q.startsWith("- [x]");return`${se?"\x1B[32m\u2714\x1B[0m":"\x1B[90m\u25CB\x1B[0m"} ${se?"\x1B[90m":"\x1B[37m"}${q.substring(6).trim()}\x1B[0m`})),ce&&ye.length>0){let De=[`${ce}`,...ye.map(se=>` ${se}`)].join(`
811
- `),_e=await s(),q=!1;_e&&(q=_e.trim().length>0),yield{type:"visual_feedback",content:Yt(`${ze?`
810
+ `).filter(Ee=>Ee.trim().startsWith("- [")).map(Ee=>{let q=Ee.trim(),re=q.startsWith("- [x]");return`${re?"\x1B[32m\u2714\x1B[0m":"\x1B[90m\u25CB\x1B[0m"} ${re?"\x1B[90m":"\x1B[37m"}${q.substring(6).trim()}\x1B[0m`})),ue&&ke.length>0){let De=[`${ue}`,...ke.map(re=>` ${re}`)].join(`
811
+ `),Ee=await s(),q=!1;Ee&&(q=Ee.trim().length>0),yield{type:"visual_feedback",content:qt(`${ze?`
812
812
  `:""}${De}${q?"":`
813
- `}`)},ze=!1}}p==="exec_command"&&n.onExecEnd&&(await new Promise(_=>setTimeout(_,800)),n.onExecEnd());let mn=Fe&&Fe.startsWith("DENIED:");Fe&&!Fe.startsWith("ERROR:")&&!mn?(await vt("toolSuccess"),n.onToolResult&&n.onToolResult("success",p)):mn||(await vt("toolFailure"),n.onToolResult&&n.onToolResult("failure",p));let Bt=(Fe||"").toString().replaceAll("[UI_CONTEXT]","");Bt.includes("[[VERIFIED]]")&&(Bt=Bt.replace(/\[\[VERIFIED\]\][\s\S]*?\[\[\/VERIFIED\]\]/g,`[SYSTEM NOTE]: Patch Block matched & applied successfully. Large Block omitted to conserve context.
814
- `));let hn;if(Bt.startsWith("[[SAME]]")){let V=Bt.replace(/^\[\[SAME\]\]\s*\r?\n?/,"").split(/\r?\n/),ne=V.filter(ye=>ye.startsWith("SUCCESS:")||ye.trim().startsWith("- Stats:"));hn=`[TOOL RESULT]: ${ne.length>0?ne.join(`
815
- `):V.slice(0,2).join(`
813
+ `}`)},ze=!1}}p==="exec_command"&&n.onExecEnd&&(await new Promise(_=>setTimeout(_,800)),n.onExecEnd());let hn=Ne&&Ne.startsWith("DENIED:");Ne&&!Ne.startsWith("ERROR:")&&!hn?(await vt("toolSuccess"),n.onToolResult&&n.onToolResult("success",p)):hn||(await vt("toolFailure"),n.onToolResult&&n.onToolResult("failure",p));let Ut=(Ne||"").toString().replaceAll("[UI_CONTEXT]","");Ut.includes("[[VERIFIED]]")&&(Ut=Ut.replace(/\[\[VERIFIED\]\][\s\S]*?\[\[\/VERIFIED\]\]/g,`[SYSTEM NOTE]: Patch Block matched & applied successfully. Large Block omitted to conserve context.
814
+ `));let mn;if(Ut.startsWith("[[SAME]]")){let j=Ut.replace(/^\[\[SAME\]\]\s*\r?\n?/,"").split(/\r?\n/),se=j.filter(ke=>ke.startsWith("SUCCESS:")||ke.trim().startsWith("- Stats:"));mn=`[TOOL RESULT]: ${se.length>0?se.join(`
815
+ `):j.slice(0,2).join(`
816
816
  `)}
817
- [SYSTEM NOTE]: Content verified and persisted to disk. Full preview omitted to conserve context.`}else hn=`[TOOL RESULT]: ${Bt}`;Ce.push({role:"user",text:hn,binaryPart:Ht}),Sn=!0;let Be=`[TOOL RESULT]: ${Fe.replaceAll(`[[VERIFIED]]
817
+ [SYSTEM NOTE]: Content verified and persisted to disk. Full preview omitted to conserve context.`}else mn=`[TOOL RESULT]: ${Ut}`;Re.push({role:"user",text:mn,binaryPart:Gt}),Sn=!0;let Fe=`[TOOL RESULT]: ${Ne.replaceAll(`[[VERIFIED]]
818
818
  `,"").replaceAll(`
819
- [[/VERIFIED]]`,"")||""}`;(p==="view_file"||p==="web_scrape"||p==="file_map")&&(Be=`[TOOL RESULT]: ${Q} (Context Locked for UI Clarity)`),yield{type:"tool_result",content:Be,aiContent:hn,binaryPart:Ht,toolName:p},p==="memory"&&Fe.includes("SUCCESS")&&(yield{type:"memory_updated"}),mt++}if(i==="Google"&&ln&&Date.now()-us>=150){yield*Pn();let U=eo(ln);for(let Z of U)yield Z;ln="",us=Date.now()}}I.usageMetadata&&(Zt=I.usageMetadata),Zt&&(yield{type:"liveTokens",content:Zt.totalTokenCount})}if(ue&&(ue=!1,Lt?tt+="</think>":(xe+="</think>",i==="Google"?ln+="</think>":yield{type:"text",content:"</think>"})),Lt&&tt.length>0){let I=0,K=Math.min(xt.length,tt.length);for(let W=K;W>0;W--)if(xt.endsWith(tt.substring(0,W))){I=W;break}let N=tt.substring(I);if(N){let Se=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(xt)?N.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):N.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(Se)if(xe+=Se,i==="Google")ln+=Se;else{yield*Pn();let Te=eo(Se);for(let pe of Te)yield pe}}Lt=!1,tt=""}if(yield*Pn(),kt)break;let to=(xe||"").trim(),oa=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(to.toLowerCase())||/\[\[END\]\]/i.test(to.toLowerCase()),sa=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(to.toLowerCase()),ia=Ce.length>0||qe!==null,gs=qt(to).trim(),ra=/(\p{Emoji_Presentation}|\p{Extended_Pictographic})$/u.test(gs),aa=/([.!?"'*_`|\]\)”’~~]+|\s|`{3}|[\u200B-\u200D\uFEFF])$/u.test(gs.trim()),la=/[.!?}"'`’“”]$|```$/s.test(gs)||aa||ra;!oa&&!sa&&!ia&&to.length>0,rt=!0,await vt("agent",i)}catch(we){if(kt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
819
+ [[/VERIFIED]]`,"")||""}`;(p==="view_file"||p==="web_scrape"||p==="file_map")&&(Fe=`[TOOL RESULT]: ${z} (Context Locked for UI Clarity)`),yield{type:"tool_result",content:Fe,aiContent:mn,binaryPart:Gt,toolName:p},p==="memory"&&Ne.includes("SUCCESS")&&(yield{type:"memory_updated"}),gt++}if(i==="Google"&&cn&&Date.now()-gs>=150){yield*$n();let F=to(cn);for(let Q of F)yield Q;cn="",gs=Date.now()}}M.usageMetadata&&(en=M.usageMetadata),en&&(yield{type:"liveTokens",content:en.totalTokenCount})}if(me&&(me=!1,Lt?et+="</think>":(we+="</think>",i==="Google"?cn+="</think>":yield{type:"text",content:"</think>"})),Lt&&et.length>0){let M=0,Y=Math.min(xt.length,et.length);for(let V=Y;V>0;V--)if(xt.endsWith(et.substring(0,V))){M=V;break}let N=et.substring(M);if(N){let J=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(xt)?N.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):N.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(J)if(we+=J,i==="Google")cn+=J;else{yield*$n();let le=to(J);for(let oe of le)yield oe}}Lt=!1,et=""}if(yield*$n(),kt)break;let no=(we||"").trim(),ra=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(no.toLowerCase())||/\[\[END\]\]/i.test(no.toLowerCase()),aa=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(no.toLowerCase()),la=Re.length>0||qe!==null,hs=zt(no).trim(),ca=/(\p{Emoji_Presentation}|\p{Extended_Pictographic})$/u.test(hs),da=/([.!?"'*_`|\]\)”’~~]+|\s|`{3}|[\u200B-\u200D\uFEFF])$/u.test(hs.trim()),fa=/[.!?}"'`’“”]$|```$/s.test(hs)||da||ca;!ra&&!aa&&!la&&no.length>0,it=!0,await vt("agent",i)}catch(_e){if(kt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
820
820
 
821
- \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(String(we).includes("Incomplete JSON segment at the end")){ue&&(ue=!1,Lt?tt+="</think>":(xe+="</think>",yield{type:"text",content:"</think>"})),rt=!0,await vt("agent",i);break}if(ue&&(ue=!1,Lt?tt+="</think>":xe+="</think>"),Lt&&tt.length>0){let Nt=0,Et=Math.min(xt.length,tt.length);for(let Dt=Et;Dt>0;Dt--)if(xt.endsWith(tt.substring(0,Dt))){Nt=Dt;break}let wt=tt.substring(Nt);if(wt){let ht=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(xt)?wt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):wt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");ht&&(xe+=ht)}Lt=!1,tt=""}let X=we instanceof Error?(()=>{try{return JSON.parse(JSON.parse(we.message).error.message).error.message}catch{return String(we)}})():String(we),$t=new Date().toLocaleString(),It=ee.join(vn,"agent");Ge.existsSync(It)||Ge.mkdirSync(It,{recursive:!0}),Ge.appendFileSync(ee.join(It,"error.log"),`ERROR [${$t}]: ${X}
821
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(String(_e).includes("Incomplete JSON segment at the end")){me&&(me=!1,Lt?et+="</think>":(we+="</think>",yield{type:"text",content:"</think>"})),it=!0,await vt("agent",i);break}if(me&&(me=!1,Lt?et+="</think>":we+="</think>"),Lt&&et.length>0){let Nt=0,Et=Math.min(xt.length,et.length);for(let Dt=Et;Dt>0;Dt--)if(xt.endsWith(et.substring(0,Dt))){Nt=Dt;break}let wt=et.substring(Nt);if(wt){let ht=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(xt)?wt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):wt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");ht&&(we+=ht)}Lt=!1,et=""}let ee=_e instanceof Error?(()=>{try{return JSON.parse(JSON.parse(_e.message).error.message).error.message}catch{return String(_e)}})():String(_e),$t=new Date().toLocaleString(),It=te.join(Rn,"agent");Ge.existsSync(It)||Ge.mkdirSync(It,{recursive:!0}),Ge.appendFileSync(te.join(It,"error.log"),`ERROR [${$t}]: ${ee}
822
822
 
823
823
  ----------------------------------------------------------------------
824
824
 
825
- `);let At=we.status||we.statusCode||we.code,Xt=String(we).includes("replicas at capacity");if(!(At&&(At>=500&&At<600||At===408||At===429||Xt)||!At&&(/status[ :]+(5\d\d|408|429)/i.test(String(we))||/code[ :]+(5\d\d|408|429)/i.test(String(we))||/(500|503|408|429)/.test(String(we))))){if(ot<sn-3)throw we;yield{type:"text",content:X},yield{type:"status",content:"Error Occured"}}if(xe.trim().length>0||at>1)if(at<=sn){at++;let Nt=Math.min(1e3*Math.pow(2,at-1),24e3);if(xe.trim().length>0){r.push({role:"agent",text:xe});let Et=`[system]
825
+ `);let At=_e.status||_e.statusCode||_e.code,Qt=String(_e).includes("replicas at capacity");if(!(At&&(At>=500&&At<600||At===408||At===429||Qt)||!At&&(/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(nt<rn-3)throw _e;yield{type:"text",content:ee},yield{type:"status",content:"Error Occured"}}if(we.trim().length>0||rt>1)if(rt<=rn){rt++;let Nt=Math.min(1e3*Math.pow(2,rt-1),24e3);if(we.trim().length>0){r.push({role:"agent",text:we});let Et=`[system]
826
826
  - seamless continuation: resume immediately. pick up from last words with zero gap/disruption
827
827
  - no repetition: do not repeat any text already written
828
828
  - no re-think: do not restart or open <think> if reasoning already started. continue the thinking and close thinking block </think> before chat output
829
829
  - mid-tool safety: if cutoff was mid-tool call, restart that tool call from start
830
- - stealth: do not mention/apologize for cutoff [/system]`;Ce.length>0?Ce.forEach((wt,Dt)=>{Dt===Ce.length-1?r.push({...wt,text:`${wt.text}
830
+ - stealth: do not mention/apologize for cutoff [/system]`;Re.length>0?Re.forEach((wt,Dt)=>{Dt===Re.length-1?r.push({...wt,text:`${wt.text}
831
831
 
832
- ${Et}`}):r.push(wt)}):r.push({role:"user",text:Et}),xt+=xe}for(let Et=Nt/1e3;Et>0&&!kt;Et--)yield{type:"status",content:`Error Occured. Recovering Stream (${at}/${sn}) [Retrying in ${Et.toFixed(0)}s]...`},await new Promise(wt=>setTimeout(wt,1e3));yield{type:"status",content:"Error Occured. Recovering Stream..."}}else throw new Error(`Stream collapsed too many times. (Failed to resolve ${sn} times)
833
- Error log can be found in \`/export logs\``);else if(ot<=sn){ot++,at=1,xt="";let Nt=Math.min(1e3*Math.pow(2,ot-1),32e3),Et=.8+Math.random()*.4,wt=Math.round(Nt*Et);Zn=!0,yield{type:"status",content:`Trying to reach ${e} (${ot}/${sn}) [Retrying in ${(wt/1e3).toFixed(0)}s]`};for(let Dt=wt/1e3;Dt>0&&!kt;Dt--)yield{type:"status",content:`Trying to reach ${e} (${ot}/${sn}) [Retrying in ${Dt.toFixed(0)}s]`},await new Promise(ht=>setTimeout(ht,1e3));yield{type:"status",content:`Trying to reach ${e}`}}else throw new Error(`Model ${e} cannot be reached. (Failed ${sn} times)
834
- Error log can be found in \`/export logs\``)}}if(Zt){let ue=Zt.totalTokenCount||0,we=Zt.cachedContentTokenCount||0,X=(Zt.candidatesTokenCount||0)+(i==="Google"&&Zt.thoughtsTokenCount||0);await Ut("tokens",ue,i,be),we>0&&await Ut("cachedTokens",we,i,be),X>0&&await Ut("candidateTokens",X,i,be),Mo({provider:i,model:be,prompt:Zt.promptTokenCount||0,cached:we,output:X,reasoning:Zt.thoughtsTokenCount||0}),yield{type:"usage",content:Zt}}xe=Kr(xe),fs.push(xe);let An=qt(xe),On=Hr(xe),gn=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(On.toLowerCase())||/\[\[END\]\]/i.test(On.toLowerCase())||!0,nl=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(On.toLowerCase()),ol=mt>0;yield{type:"status",content:"Thinking"};let Zr=Ja(xe,/(\[\s*(turn\s*:)?\s*(continue|finish)\s*\]|\[\[END\]\])/gi,"").trim(),Ln=(gn||Ce.length===0)&&!Mt&&!an&&!_n;if(Ln=Ce.length===0?Ln:!1,Ln=Pt||To?!1:Ln,xe&&xe.trim().endsWith('")]')&&Ce.length===0&&(Ln=!1),Ln){mi=!0;let ue=fs.join(`
835
- `),we=qt(ue).trim();yield{type:"interactive_turn_finished",data:{agentText:x,fullAgentTextRaw:ue,history:[...r],needTitle:L}},r.length>0&&r[r.length-1].role==="agent"?r[r.length-1].text=we:r.push({role:"agent",text:we}),r.forEach(X=>{if(X.role==="user"&&X.text&&(X.text=X.text.replace(/\n\[COMPILE ERROR\][\s\S]*?\[\/ERROR\]/g,""),X.text=X.text.replaceAll(`
832
+ ${Et}`}):r.push(wt)}):r.push({role:"user",text:Et}),xt+=we}for(let Et=Nt/1e3;Et>0&&!kt;Et--)yield{type:"status",content:`Error Occured. Recovering Stream (${rt}/${rn}) [Retrying in ${Et.toFixed(0)}s]...`},await new Promise(wt=>setTimeout(wt,1e3));yield{type:"status",content:"Error Occured. Recovering Stream..."}}else throw new Error(`Stream collapsed too many times. (Failed to resolve ${rn} times)
833
+ Error log can be found in \`/export logs\``);else if(nt<=rn){nt++,rt=1,xt="";let Nt=Math.min(1e3*Math.pow(2,nt-1),32e3),Et=.8+Math.random()*.4,wt=Math.round(Nt*Et);Zn=!0,yield{type:"status",content:`Trying to reach ${e} (${nt}/${rn}) [Retrying in ${(wt/1e3).toFixed(0)}s]`};for(let Dt=wt/1e3;Dt>0&&!kt;Dt--)yield{type:"status",content:`Trying to reach ${e} (${nt}/${rn}) [Retrying in ${Dt.toFixed(0)}s]`},await new Promise(ht=>setTimeout(ht,1e3));yield{type:"status",content:`Trying to reach ${e}`}}else throw new Error(`Model ${e} cannot be reached. (Failed ${rn} times)
834
+ Error log can be found in \`/export logs\``)}}if(en){let me=en.totalTokenCount||0,_e=en.cachedContentTokenCount||0,ee=(en.candidatesTokenCount||0)+(i==="Google"&&en.thoughtsTokenCount||0);await Wt("tokens",me,i,Te),_e>0&&await Wt("cachedTokens",_e,i,Te),ee>0&&await Wt("candidateTokens",ee,i,Te),Io({provider:i,model:Te,prompt:en.promptTokenCount||0,cached:_e,output:ee,reasoning:en.thoughtsTokenCount||0}),yield{type:"usage",content:en}}we=zr(we),us.push(we);let An=zt(we),Ln=Vr(we),gn=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(Ln.toLowerCase())||/\[\[END\]\]/i.test(Ln.toLowerCase())||!0,il=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(Ln.toLowerCase()),rl=gt>0;yield{type:"status",content:"Thinking"};let na=Za(we,/(\[\s*(turn\s*:)?\s*(continue|finish)\s*\]|\[\[END\]\])/gi,"").trim(),Pn=(gn||Re.length===0)&&!Mt&&!ln&&!_n;if(Pn=Re.length===0?Pn:!1,Pn=Pt||So?!1:Pn,we&&we.trim().endsWith('")]')&&Re.length===0&&(Pn=!1),Pn){mi=!0;let me=us.join(`
835
+ `),_e=zt(me).trim();yield{type:"interactive_turn_finished",data:{agentText:x,fullAgentTextRaw:me,history:[...r],needTitle:L}},r.length>0&&r[r.length-1].role==="agent"?r[r.length-1].text=_e:r.push({role:"agent",text:_e}),r.forEach(ee=>{if(ee.role==="user"&&ee.text&&(ee.text=ee.text.replace(/\n\[COMPILE ERROR\][\s\S]*?\[\/ERROR\]/g,""),ee.text=ee.text.replaceAll(`
836
836
 
837
837
  [system] user question. resolve this specific query within '[ANSWER] ... [/ANSWER]' concisely, naturally [/system]
838
838
  `,"").replaceAll(`[system] user question. resolve this specific query within '[ANSWER] ... [/ANSWER]' concisely, naturally
839
839
  **strictly follow thinking policy as high priority. do not start a response without <think>...</think>** [/system]
840
840
  `,"").replaceAll(`[system] **strictly follow thinking policy as high priority. do not start a response without <think>...</think>** [/system]
841
- `,"").replaceAll(/\n\[system\] WARNING, Turn Limit Impending: Step \d+\/\d+\. Wrap up quickly\/prompt user to continue & use \[\[END\]\] quickly\. \[\/system\]/g,""),X.text=X.text.replaceAll(/\n\[system\] File Changes:\n(?:\* .+ \(created|modified|deleted\)\n)*\[\/system\]/g,""),(i==="Mistral"||i==="Google"&&e?.toLowerCase().startsWith("gemma"))&&X.text.startsWith("[TOOL RESULT]"))){let It=`
841
+ `,"").replaceAll(/\n\[system\] WARNING, Turn Limit Impending: Step \d+\/\d+\. Wrap up quickly\/prompt user to continue & use \[\[END\]\] quickly\. \[\/system\]/g,""),ee.text=ee.text.replaceAll(/\n\[system\] File Changes:\n(?:\* .+ \(created|modified|deleted\)\n)*\[\/system\]/g,""),(i==="Mistral"||i==="Google"&&e?.toLowerCase().startsWith("gemma"))&&ee.text.startsWith("[TOOL RESULT]"))){let It=`
842
842
  [system] Tool result received. Analyze output and proceed with your turn [/system]`,At=`
843
- [system] Tool result received. Analyze output and proceed with your turn. **strictly follow thinking policy. do not start a response without <think>...</think>** [/system]`;X.text=X.text.replaceAll(At,"").replaceAll(It,"").trim()}}),yield{type:"status",content:"[end]"}}if(Ln)break;let ea=Zr.trim()||"*Working...*";if(r.push({role:"agent",text:ea}),Ce.length>0||Sn){if(Ce.length>0){let ue=Ce.map(Xt=>Xt.text).join(`
843
+ [system] Tool result received. Analyze output and proceed with your turn. **strictly follow thinking policy. do not start a response without <think>...</think>** [/system]`;ee.text=ee.text.replaceAll(At,"").replaceAll(It,"").trim()}}),yield{type:"status",content:"[end]"}}if(Pn)break;let oa=na.trim()||"*Working...*";if(r.push({role:"agent",text:oa}),Re.length>0||Sn){if(Re.length>0){let me=Re.map(Qt=>Qt.text).join(`
844
844
 
845
- `),$t=(qt(xe).replace(/\[{1,2}tool:[\s\S]*?\)\s*\]{1,2}/gi,"").match(/\[tool:/gi)||[]).length,It=Ce.length+$t;if(Ce.length<It){ue+=`
845
+ `),$t=(zt(we).replace(/\[{1,2}tool:[\s\S]*?\)\s*\]{1,2}/gi,"").match(/\[tool:/gi)||[]).length,It=Re.length+$t;if(Re.length<It){me+=`
846
846
 
847
- [system] Only ${Ce.length} out of ${It} attempted tool calls were executed. Verify proper structure compliance & try failed calls again [/system]`;let Xt=It-Ce.length;for(let Ye=0;Ye<Xt;Ye++)await vt("toolFailure")}let At=Ce.find(Xt=>Xt.binaryPart)?.binaryPart||null;r.push({role:"user",text:ue,binaryPart:At})}}else if(!kt){let we=(xe.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/i,"").match(/\[tool:/gi)||[]).length;To||Pt||we>0?(r.push({role:"user",text:`[system] Failed to execute ${we} tool${we>1?"s":""}. Verify proper structure compliance & try again [/system]`}),await vt("toolFailure"),yield{type:"visual_feedback",content:`
848
- ${Yt("\u2718 Execution Error")}
847
+ [system] Only ${Re.length} out of ${It} attempted tool calls were executed. Verify proper structure compliance & try failed calls again [/system]`;let Qt=It-Re.length;for(let Ye=0;Ye<Qt;Ye++)await vt("toolFailure")}let At=Re.find(Qt=>Qt.binaryPart)?.binaryPart||null;r.push({role:"user",text:me,binaryPart:At})}}else if(!kt){let _e=(we.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/i,"").match(/\[tool:/gi)||[]).length;So||Pt||_e>0?(r.push({role:"user",text:`[system] Failed to execute ${_e} tool${_e>1?"s":""}. Verify proper structure compliance & try again [/system]`}),await vt("toolFailure"),yield{type:"visual_feedback",content:`
848
+ ${qt("\u2718 Execution Error")}
849
849
  `}):(yield{type:"visual_feedback",content:`
850
- ${Yt("\u2718 Loop Detected")}
851
- `},r.push({role:"user",text:`[system] ${an&&!Mt?"Stuttering Detected by Internal System. Re-calibrate your response & proceed.":`${Mt?" Over Thinking":" Loop"} Detected by Internal System${Mt?" for current Effort Level":""}. ${Mt?"If you have planned the task, prioritize execution/output":"If you have finished your task provide a simple summary and end"}`} [/system]`})),Mt=!1,an=!1,_n=!1}m?.advanceRollback&&await io.recordTurnDelta(g,G+1,et),To=mt>0||Sn}if(!mi&&!kt){let G="\u2726 Turn safety limit reached. Stopping execution.";yield{type:"text",content:`
850
+ ${qt("\u2718 Loop Detected")}
851
+ `},r.push({role:"user",text:`[system] ${ln&&!Mt?"Stuttering Detected by Internal System. Re-calibrate your response & proceed.":`${Mt?" Over Thinking":" Loop"} Detected by Internal System${Mt?" for current Effort Level":""}. ${Mt?"If you have planned the task, prioritize execution/output":"If you have finished your task provide a simple summary and end"}`} [/system]`})),Mt=!1,ln=!1,_n=!1}h?.advanceRollback&&await ro.recordTurnDelta(g,H+1,Ze),So=gt>0||Sn}if(!mi&&!kt){let H="\u2726 Turn safety limit reached. Stopping execution.";yield{type:"text",content:`
852
852
 
853
- ${G}
854
- `};let Ne=(fs.join(`
853
+ ${H}
854
+ `};let $e=(us.join(`
855
855
  `)+`
856
- ${G}`).trim();yield{type:"interactive_turn_finished",data:{agentText:x,fullAgentTextRaw:Ne,history:[...r],needTitle:L}},yield{type:"status",content:"[end]"}}}catch(k){let r=k?.cause?` (Cause: ${k.cause?.message||String(k.cause)})`:"",A=(k instanceof Error?(()=>{try{return JSON.parse(JSON.parse(k.message).error.message).error.message}catch{return(k.message?`${k.message}${r}`:"")||String(k)}})():String(k)).replace(/^(Error:\s*)+/i,"");i==="Google"&&!/^[A-Z0-9_\-\s]+ ERROR:/i.test(A)&&(A=`GEMINI ERROR: ${A}`);let D=new Date().toLocaleString(),H=ee.join(vn,"agent");yield{type:"text",content:`
856
+ ${H}`).trim();yield{type:"interactive_turn_finished",data:{agentText:x,fullAgentTextRaw:$e,history:[...r],needTitle:L}},yield{type:"status",content:"[end]"}}}catch(k){let r=k?.cause?` (Cause: ${k.cause?.message||String(k.cause)})`:"",A=(k instanceof Error?(()=>{try{return JSON.parse(JSON.parse(k.message).error.message).error.message}catch{return(k.message?`${k.message}${r}`:"")||String(k)}})():String(k)).replace(/^(Error:\s*)+/i,"");i==="Google"&&!/^[A-Z0-9_\-\s]+ ERROR:/i.test(A)&&(A=`GEMINI ERROR: ${A}`);let D=new Date().toLocaleString(),W=te.join(Rn,"agent");yield{type:"text",content:`
857
857
 
858
858
  \u2726 CRITICAL ERROR: ${A.includes("fetch failed")?"Failed to Connect. Check your Internet Connection or Wait a moment":A}
859
- \u2800`},Ge.existsSync(H)||Ge.mkdirSync(H,{recursive:!0}),Ge.appendFileSync(ee.join(H,"error.log"),`CRITICAL ERROR [${D}]: ${k}${k?.cause?`
859
+ \u2800`},Ge.existsSync(W)||Ge.mkdirSync(W,{recursive:!0}),Ge.appendFileSync(te.join(W,"error.log"),`CRITICAL ERROR [${D}]: ${k}${k?.cause?`
860
860
  CAUSE: ${k.cause?.stack||k.cause}`:""}
861
861
 
862
862
  ----------------------------------------------------------------------
863
863
 
864
- `),typeof flushGoogleBuffer=="function"&&(yield*flushGoogleBuffer()),yield{type:"tool_result",content:`ERROR: [INTERNAL CRITICAL] ${A}`}}finally{d&&(clearInterval(d),d=null),typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),await Io.commitTransaction(),m?.advanceRollback&&await io.cleanup(g),await Un()}yield{type:"status",content:null}},mf=async(e,t,n=null,s=null,o=50,l=null,f=!1)=>{let a=await so(),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,y=`${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(":","-")}`,c=(k=>{if(!k)return null;let r=k.toLowerCase();return r==="google"?"Google":r==="deepseek"?"DeepSeek":r==="openrouter"?"OpenRouter":r==="nvidia"?"NVIDIA":r==="mistral"?"Mistral":r==="ollama"?"Ollama":r==="inferx"?"InferX":r==="sensenova"?"SenseNova":r==="poolside"?"Poolside":r==="9router"||r==="9Router"?"9router":r==="aihubmix"||r==="aihub"?"AIHubMix":r==="explabs"||r==="experientiallabs"||r==="experimentallabs"?"ExpLabs":r==="tokenharbor"||r==="token harbor"||r==="token_harbor"||r==="thk"?"TokenHarbor":r==="apinex"||r==="apx"?"APInex":null})(u),w=h?.systemSettings?.CustomSubAgent?h?.systemSettings?.SubAgentModel:null,v=h?.systemSettings?.CustomSubAgent?h?.systemSettings?.SubAgentProvider:null,b=null;if(w==="ENV"?(b=g,g&&c&&(h.aiProvider=c)):w&&w!=="Default"?(b=w,v&&(h.aiProvider=v)):g&&c&&(h.aiProvider=c),h.aiProvider){let k=await ks(h.aiProvider);k&&(h.apiKey=k)}let E=k=>{if(!k||typeof k!="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 T of r)if(T.test(k))return{allowed:!1,reason:`Blocked potentially destructive or unsafe command pattern: "${T.source}"`};return{allowed:!0}},O=n||b||t?.modelName||t?.activeModel||a.activeModel,C=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",S=`-- TOOL DEFINITIONS (path = relative to CWD, path separator: '/') --
864
+ `),typeof flushGoogleBuffer=="function"&&(yield*flushGoogleBuffer()),yield{type:"tool_result",content:`ERROR: [INTERNAL CRITICAL] ${A}`}}finally{d&&(clearInterval(d),d=null),typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),await Do.commitTransaction(),h?.advanceRollback&&await ro.cleanup(g),await Wn()}yield{type:"status",content:null}},yf=async(e,t,n=null,s=null,o=50,l=null,f=!1)=>{let a=await io(),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,y=`${h.getFullYear()}-${h.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(h.getDate()).padStart(2,"0")}, ${h.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}).replace(":","-")}`,c=(k=>{if(!k)return null;let r=k.toLowerCase();return r==="google"?"Google":r==="deepseek"?"DeepSeek":r==="openrouter"?"OpenRouter":r==="nvidia"?"NVIDIA":r==="mistral"?"Mistral":r==="ollama"?"Ollama":r==="inferx"?"InferX":r==="sensenova"?"SenseNova":r==="poolside"?"Poolside":r==="9router"||r==="9Router"?"9router":r==="aihubmix"||r==="aihub"?"AIHubMix":r==="explabs"||r==="experientiallabs"||r==="experimentallabs"?"ExpLabs":r==="tokenharbor"||r==="token harbor"||r==="token_harbor"||r==="thk"?"TokenHarbor":r==="apinex"||r==="apx"?"APInex":null})(u),w=m?.systemSettings?.CustomSubAgent?m?.systemSettings?.SubAgentModel:null,v=m?.systemSettings?.CustomSubAgent?m?.systemSettings?.SubAgentProvider:null,b=null;if(w==="ENV"?(b=g,g&&c&&(m.aiProvider=c)):w&&w!=="Default"?(b=w,v&&(m.aiProvider=v)):g&&c&&(m.aiProvider=c),m.aiProvider){let k=await ws(m.aiProvider);k&&(m.apiKey=k)}let E=k=>{if(!k||typeof k!="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 T of r)if(T.test(k))return{allowed:!1,reason:`Blocked potentially destructive or unsafe command pattern: "${T.source}"`};return{allowed:!0}},O=n||b||t?.modelName||t?.activeModel||a.activeModel,C=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",S=`-- TOOL DEFINITIONS (path = relative to CWD, path separator: '/') --
865
865
  You cant execute tools. Instead output in chat the exact string [tool:ToolName(arg1="value1")] \u2190 mandatory
866
866
  Tool Rules:
867
- - Mandatorily JSON escape literal sequences (backslash: \\\\, newLine: \\ n, quote: \\")
867
+ - Mandatorily JSON escape literal sequences (backslash: \\\\, newLine: \\ n)
868
868
  - Same file, multiple edits? ONE PatchFile (\u226415 blocks)
869
869
  - Need text or huge file? CodeSearch > Full Read
870
870
  - Avoid unnecessary large file chunk reads
@@ -887,7 +887,7 @@ ${f?"- AskMain(question=string). Communicate with PARENT/MAIN AGENT. When clarif
887
887
  - ReadFile(path=string, startLine?=int, endLine?=int)
888
888
  - 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
889
889
  - WriteFile(path=string, content=string). Creates/Overwrites. File Exist? PatchFile > WriteFile
890
- - Run(command=string). Runs ${C==="Windows"?wi()?"powershell":"windows CMD":"bash"} command. Destructive command \u2192 Ask user`.trim(),R=`=== START SYSTEM PROMPT ===
890
+ - Run(command=string). Runs ${C==="Windows"?_i()?"powershell":"windows CMD":"bash"} command. Destructive command \u2192 Ask user`.trim(),R=`=== START SYSTEM PROMPT ===
891
891
  Identity: FluxFlow subagent helping the main Agent
892
892
  Your task is: "${e}"
893
893
 
@@ -901,30 +901,30 @@ CWD: ${process.cwd()}
901
901
  ${S.trimEnd()}
902
902
 
903
903
  Current Time: ${y}
904
- === END SYSTEM PROMPT ===`,L=[{role:"user",text:`Complete this task: ${e}`}],x=0,d="";for(;x<o;){let k=await ws("subagent",h);if(!k.allowed)throw new Error(k.reason||`Budget Exhausted for Provider (${h?.aiProvider||"Subagent"})`);if(kt){if(t?.taskId&&typeof Kt<"u"){let P=Kt.find(F=>F.id===t.taskId);P&&(P.status="cancelled")}throw l&&l("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}if(t?.taskId&&typeof Kt<"u"){let P=Kt.find(F=>F.id===t.taskId);if(P&&P.status==="cancelled")throw l&&l("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}let r=L.map(P=>({role:P.role==="user"?"user":"model",parts:[{text:P.text}]}));l&&l(`[Subagent Turn ${x+1}]...`);let T=["Fast","Low","Medium","High"],A=process.env.SUBAGENT_THINKING,D=T.includes(A)?A:"Low",$=(await is(h,O,r,R,D)).text||"",M=Kr(qt($).trim());d=M,l&&l(`[Subagent Response]
905
- ${M}
906
- `),L.push({role:"agent",text:M});let te=xo(M);if(te.length===0)break;let le=te.filter(P=>P.toolName.toLowerCase()==="askmain"||P.toolName.toLowerCase()==="ask_main"),J=!1,re="";for(let P of te){if(kt){if(t?.taskId&&typeof Kt<"u"){let B=Kt.find(Y=>Y.id===t.taskId);B&&(B.status="cancelled")}throw new Error("Subagent task was cancelled.")}if(t?.taskId&&typeof Kt<"u"){let B=Kt.find(Y=>Y.id===t.taskId);if(B&&B.status==="cancelled")throw new Error("Subagent task was cancelled.")}let F=P.toolName.toLowerCase();if(F==="askuser"&&(F="ask"),F==="askmain"||F==="ask_main"){if(J)continue;J=!0;let B="";if(le.length===1?B=oe(le[0].args).question||le[0].args:B=le.map((Y,fe)=>{let Ae=oe(Y.args);return`Q${fe+1}: ${Ae.question||Y.args}`}).join(`
907
- `),t.onAskMain){l&&l(`[Executing Tool] AskMain("${B}")...`);let Y=await t.onAskMain(B);l&&l(`[Tool Result]
908
- Answer from Main Agent: ${Y}
909
- `),re+=`[TOOL RESULT for AskMain]: Answer from Main Agent: ${Y}
904
+ === END SYSTEM PROMPT ===`,L=[{role:"user",text:`Complete this task: ${e}`}],x=0,d="";for(;x<o;){let k=await Ts("subagent",m);if(!k.allowed)throw new Error(k.reason||`Budget Exhausted for Provider (${m?.aiProvider||"Subagent"})`);if(kt){if(t?.taskId&&typeof Yt<"u"){let P=Yt.find(B=>B.id===t.taskId);P&&(P.status="cancelled")}throw l&&l("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}if(t?.taskId&&typeof Yt<"u"){let P=Yt.find(B=>B.id===t.taskId);if(P&&P.status==="cancelled")throw l&&l("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}let r=L.map(P=>({role:P.role==="user"?"user":"model",parts:[{text:P.text}]}));l&&l(`[Subagent Turn ${x+1}]...`);let T=["Fast","Low","Medium","High"],A=process.env.SUBAGENT_THINKING,D=T.includes(A)?A:"Low",$=(await rs(m,O,r,R,D)).text||"",I=zr(zt($).trim());d=I,l&&l(`[Subagent Response]
905
+ ${I}
906
+ `),L.push({role:"agent",text:I});let ne=bo(I);if(ne.length===0)break;let fe=ne.filter(P=>P.toolName.toLowerCase()==="askmain"||P.toolName.toLowerCase()==="ask_main"),Z=!1,ce="";for(let P of ne){if(kt){if(t?.taskId&&typeof Yt<"u"){let U=Yt.find(K=>K.id===t.taskId);U&&(U.status="cancelled")}throw new Error("Subagent task was cancelled.")}if(t?.taskId&&typeof Yt<"u"){let U=Yt.find(K=>K.id===t.taskId);if(U&&U.status==="cancelled")throw new Error("Subagent task was cancelled.")}let B=P.toolName.toLowerCase();if(B==="askuser"&&(B="ask"),B==="askmain"||B==="ask_main"){if(Z)continue;Z=!0;let U="";if(fe.length===1?U=ie(fe[0].args).question||fe[0].args:U=fe.map((K,he)=>{let Ce=ie(K.args);return`Q${he+1}: ${Ce.question||K.args}`}).join(`
907
+ `),t.onAskMain){l&&l(`[Executing Tool] AskMain("${U}")...`);let K=await t.onAskMain(U);l&&l(`[Tool Result]
908
+ Answer from Main Agent: ${K}
909
+ `),ce+=`[TOOL RESULT for AskMain]: Answer from Main Agent: ${K}
910
910
 
911
- `,await vt("toolSuccess")}else re+=`[TOOL RESULT for AskMain]: ERROR: Main agent communication channel not available.
911
+ `,await vt("toolSuccess")}else ce+=`[TOOL RESULT for AskMain]: ERROR: Main agent communication channel not available.
912
912
 
913
- `;continue}if(!(s?s.some(B=>B.toLowerCase()===F):!0)){let B=`ERROR: Tool [${P.toolName}] is not in the allowed tools list for this subagent.`;l&&l(`[Blocked Tool Call] ${P.toolName} - not allowed
914
- `),re+=`${B}
913
+ `;continue}if(!(s?s.some(U=>U.toLowerCase()===B):!0)){let U=`ERROR: Tool [${P.toolName}] is not in the allowed tools list for this subagent.`;l&&l(`[Blocked Tool Call] ${P.toolName} - not allowed
914
+ `),ce+=`${U}
915
915
 
916
- `;continue}if(F==="exec_command"||F==="execcommand"||F==="run"){let B=oe(P.args).command||"",Y=E(B);if(!Y.allowed){let fe=`ERROR: [SECURITY RESTRICTION] Subagent execution blocked command: ${Y.reason}`;l&&l(`[Blocked Command] ${B} - ${Y.reason}
917
- `),re+=`${fe}
916
+ `;continue}if(B==="exec_command"||B==="execcommand"||B==="run"){let U=ie(P.args).command||"",K=E(U);if(!K.allowed){let he=`ERROR: [SECURITY RESTRICTION] Subagent execution blocked command: ${K.reason}`;l&&l(`[Blocked Command] ${U} - ${K.reason}
917
+ `),ce+=`${he}
918
918
 
919
- `;continue}}let z="";if(F==="web_search"||F==="websearch")z=`\u2714 \x1B[95mSearched\x1B[0m: ${oe(P.args).query||""}`;else if(F==="web_scrape"||F==="webscrape")z=`\u2714 \x1B[95mScraped\x1B[0m: ${oe(P.args).url||""}`;else if(F==="search_keyword"||F==="searchkeyword"||F==="codesearch"||F==="code_search"){let B=oe(P.args),Y=B.keyword||"",fe=B.path||"";z=`${Y?"\u2714":"\u2718"} \x1B[95mSearched\x1B[0m: ${Y||"No Query"}${fe?` \u2192 ${fe.replaceAll("\\","/")}`:""}`}else if(F==="view_file"||F==="viewfile"||F==="readfile")z=`\u2714 \x1B[95mRead\x1B[0m: ${(oe(P.args).path||"").replaceAll("\\","/")}`;else if(F==="list_files"||F==="read_folder"||F==="readfolder"){let B=oe(P.args).path||null,Y=oe(P.args).recurse||0;z=`${B?"\u2714":"\u2718"} \x1B[95mBrowsed\x1B[0m: ${B?`${B.replaceAll("\\","/")}${Y>0?`${B.endsWith("/")?`*${Y}`:`/*${Y}`}`:`${B.endsWith("/")?"":"/"}`}`:""}`}else if(F==="write_file"||F==="writefile"){let B=oe(P.args).path||null;z=`${B?"\u2714":"\u2718"} \x1B[95mCreated\x1B[0m: ${B?`${B.replaceAll("\\","/")}`:"No File Changes"}`}else if(F==="update_file"||F==="updatefile"||F==="patchfile"||F==="patch_file"){let B=oe(P.args),Y=B.path||null,Ae=Object.entries(B).some(([Ee,$e])=>Ee.startsWith("searchContent")&&typeof $e=="string"&&$e.startsWith("^LINE:"))?"\u1361":":";z=`${Y?"\u2714":"\u2718"} \x1B[95mEdited\x1B[0m${Ae} ${Y?`${Y.replaceAll("\\","/")}`:"No File Changes"}`}else if(F==="exec_command"||F==="execcommand"||F==="run"){let B=oe(P.args).command||null;z=`${B?"\u2714":"\u2718"} \x1B[95mExecuted\x1B[0m: ${B?B.slice(0,100)+(B.length>100?"...":""):"No Command"}`}else if(F==="file_map"||F==="filemap"){let B=oe(P.args).path||"";z=`${B?"\u2714":"\u2718"} \x1B[95mIndexed\x1B[0m: ${B?`${B.replaceAll("\\","/")}`:"File Not Found"}`}else if(F==="await"){let{time:B}=oe(P.args),Y=parseFloat(B)||0;Y<10&&(Y=10),Y>180&&(Y=180),z=`\u2714 \x1B[95mAwaiting\x1B[0m \u2192 ${(Ae=>{if(Ae>=60){let Ee=Math.floor(Ae/60),$e=Ae%60;return`${Ee}m${$e>0?` ${$e}s`:""}`}return`${Ae}s`})(Y)}`}else{let B=ei[F]||P.toolName,Y=Gn(F,P.args);z=`\u2714 \x1B[95m${B}\x1B[0m${Y?`: ${Y}`:""}`}t.onVisualFeedback&&z&&t.onVisualFeedback(z),l&&l(`[Executing Tool] ${P.toolName}(${P.args})...`);try{let B=await ho(P.toolName,P.args,{...t,mode:"Flux"});if(l&&l(`[Tool Result]
920
- ${B}
921
- `),re+=`[TOOL RESULT for ${P.toolName}]: ${B}
919
+ `;continue}}let X="";if(B==="web_search"||B==="websearch")X=`\u2714 \x1B[95mSearched\x1B[0m: ${ie(P.args).query||""}`;else if(B==="web_scrape"||B==="webscrape")X=`\u2714 \x1B[95mScraped\x1B[0m: ${ie(P.args).url||""}`;else if(B==="search_keyword"||B==="searchkeyword"||B==="codesearch"||B==="code_search"){let U=ie(P.args),K=U.keyword||"",he=U.path||"";X=`${K?"\u2714":"\u2718"} \x1B[95mSearched\x1B[0m: ${K||"No Query"}${he?` \u2192 ${he.replaceAll("\\","/")}`:""}`}else if(B==="view_file"||B==="viewfile"||B==="readfile")X=`\u2714 \x1B[95mRead\x1B[0m: ${(ie(P.args).path||"").replaceAll("\\","/")}`;else if(B==="list_files"||B==="read_folder"||B==="readfolder"){let U=ie(P.args).path||null,K=ie(P.args).recurse||0;X=`${U?"\u2714":"\u2718"} \x1B[95mBrowsed\x1B[0m: ${U?`${U.replaceAll("\\","/")}${K>0?`${U.endsWith("/")?`*${K}`:`/*${K}`}`:`${U.endsWith("/")?"":"/"}`}`:""}`}else if(B==="write_file"||B==="writefile"){let U=ie(P.args).path||null;X=`${U?"\u2714":"\u2718"} \x1B[95mCreated\x1B[0m: ${U?`${U.replaceAll("\\","/")}`:"No File Changes"}`}else if(B==="update_file"||B==="updatefile"||B==="patchfile"||B==="patch_file"){let U=ie(P.args),K=U.path||null,Ce=Object.entries(U).some(([ve,Pe])=>ve.startsWith("searchContent")&&typeof Pe=="string"&&Pe.startsWith("^LINE:"))?"\u1361":":";X=`${K?"\u2714":"\u2718"} \x1B[95mEdited\x1B[0m${Ce} ${K?`${K.replaceAll("\\","/")}`:"No File Changes"}`}else if(B==="exec_command"||B==="execcommand"||B==="run"){let U=ie(P.args).command||null;X=`${U?"\u2714":"\u2718"} \x1B[95mExecuted\x1B[0m: ${U?U.slice(0,100)+(U.length>100?"...":""):"No Command"}`}else if(B==="file_map"||B==="filemap"){let U=ie(P.args).path||"";X=`${U?"\u2714":"\u2718"} \x1B[95mIndexed\x1B[0m: ${U?`${U.replaceAll("\\","/")}`:"File Not Found"}`}else if(B==="await"){let{time:U}=ie(P.args),K=parseFloat(U)||0;K<10&&(K=10),K>180&&(K=180),X=`\u2714 \x1B[95mAwaiting\x1B[0m \u2192 ${(Ce=>{if(Ce>=60){let ve=Math.floor(Ce/60),Pe=Ce%60;return`${ve}m${Pe>0?` ${Pe}s`:""}`}return`${Ce}s`})(K)}`}else{let U=ti[B]||P.toolName,K=jn(B,P.args);X=`\u2714 \x1B[95m${U}\x1B[0m${K?`: ${K}`:""}`}t.onVisualFeedback&&X&&t.onVisualFeedback(X),l&&l(`[Executing Tool] ${P.toolName}(${P.args})...`);try{let U=await po(P.toolName,P.args,{...t,mode:"Flux"});if(l&&l(`[Tool Result]
920
+ ${U}
921
+ `),ce+=`[TOOL RESULT for ${P.toolName}]: ${U}
922
922
 
923
- `,await vt("toolSuccess"),F==="patchfile"||F==="update_file"||F==="updatefile"||F==="patch_file"){if(B){let Y=B.split(`
924
- `),fe=0,Ae=0,Ee=!1;for(let $e of Y){if($e.includes("[DIFF_START]")){Ee=!0;continue}if($e.includes("[DIFF_END]")){Ee=!1;continue}Ee&&(/^\+\d+/.test($e)?fe++:/^\-\d+/.test($e)&&Ae++)}(fe>0||Ae>0)&&(await Ut("linesAdded",fe),await Ut("linesRemoved",Ae))}}else if((F==="writefile"||F==="write_file")&&B){let Y=B.match(/- Stats: \[(\d+) lines/),fe=Y?parseInt(Y[1]):0,Ae=0;if(B.includes("Old File contents:")){let Ee=!1;for(let $e of B.split(`
925
- `)){if($e.includes("Old File contents:")){Ee=!0;continue}Ee&&($e.trim()===""?Ee=!1:/^\d+ \|/.test($e)&&Ae++)}}(fe>0||Ae>0)&&(await Ut("linesAdded",fe),await Ut("linesRemoved",Ae))}}catch(B){let Y=`ERROR: Execution failed for [${P.toolName}]: ${B.message}`;l&&l(`[Tool Error] ${Y}
926
- `),re+=`${Y}
923
+ `,await vt("toolSuccess"),B==="patchfile"||B==="update_file"||B==="updatefile"||B==="patch_file"){if(U){let K=U.split(`
924
+ `),he=0,Ce=0,ve=!1;for(let Pe of K){if(Pe.includes("[DIFF_START]")){ve=!0;continue}if(Pe.includes("[DIFF_END]")){ve=!1;continue}ve&&(/^\+\d+/.test(Pe)?he++:/^\-\d+/.test(Pe)&&Ce++)}(he>0||Ce>0)&&(await Wt("linesAdded",he),await Wt("linesRemoved",Ce))}}else if((B==="writefile"||B==="write_file")&&U){let K=U.match(/- Stats: \[(\d+) lines/),he=K?parseInt(K[1]):0,Ce=0;if(U.includes("Old File contents:")){let ve=!1;for(let Pe of U.split(`
925
+ `)){if(Pe.includes("Old File contents:")){ve=!0;continue}ve&&(Pe.trim()===""?ve=!1:/^\d+ \|/.test(Pe)&&Ce++)}}(he>0||Ce>0)&&(await Wt("linesAdded",he),await Wt("linesRemoved",Ce))}}catch(U){let K=`ERROR: Execution failed for [${P.toolName}]: ${U.message}`;l&&l(`[Tool Error] ${K}
926
+ `),ce+=`${K}
927
927
 
928
- `,await vt("toolFailure")}}let Oe="";if(t?.taskId&&typeof Kt<"u"){let P=Kt.find(F=>F.id===t.taskId);if(P&&P.pendingSteerMessages&&P.pendingSteerMessages.length>0){let F=[...P.pendingSteerMessages];P.pendingSteerMessages=[];for(let ve of F)Oe+=`
928
+ `,await vt("toolFailure")}}let Oe="";if(t?.taskId&&typeof Yt<"u"){let P=Yt.find(B=>B.id===t.taskId);if(P&&P.pendingSteerMessages&&P.pendingSteerMessages.length>0){let B=[...P.pendingSteerMessages];P.pendingSteerMessages=[];for(let Me of B)Oe+=`
929
929
 
930
- [STEERING INSTRUCTION FROM MAIN AGENT]: ${ve}`,l&&l(`[Subagent Steered] ${ve}`)}}let We=(re.trim()+Oe).trim();L.push({role:"user",text:We}),x++}return d};export{po as a,Mr as b,mc as c,hc as d,Ve as e,cl as f,dl as g,sc as h,ic as i,xc as j,Ko as k,bc as l,Wa as m,rf as n,Ha as o,Ga as p,Zs as q,qt as r,Wr as s,Kr as t,Ya as u,af as v,lf as w,ni as x,cf as y,df as z,is as A,ff as B,uf as C,gf as D,mf as E};
930
+ [STEERING INSTRUCTION FROM MAIN AGENT]: ${Me}`,l&&l(`[Subagent Steered] ${Me}`)}}let Ue=(ce.trim()+Oe).trim();L.push({role:"user",text:Ue}),x++}return d};export{yo as a,Or as b,yc as c,xc as d,Ve as e,ul as f,gl as g,ac as h,lc as i,wc as j,Yo as k,Tc as l,ja as m,cf as n,Va as o,Ka as p,ei as q,zt as r,jr as s,zr as t,Ja as u,df as v,ff as w,oi as x,uf as y,gf as z,rs as A,hf as B,mf as C,pf as D,yf as E};