fluxflow-cli 4.23.5 → 4.24.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/dist/chunks/{addMemScore-COX3MDEK.js → addMemScore-PWP7GFSP.js} +1 -1
  2. package/dist/chunks/{ai-IOEGZWGA.js → ai-D266ZNXN.js} +1 -1
  3. package/dist/chunks/{app-OWHF6FXI.js → app-QAUN2PDW.js} +142 -142
  4. package/dist/chunks/{chat-J5AAPLPF.js → chat-7T6MVHC3.js} +1 -1
  5. package/dist/chunks/{chunk-BSUDXEA2.js → chunk-3CZWTXIR.js} +1 -1
  6. package/dist/chunks/chunk-3HEZL3GW.js +913 -0
  7. package/dist/chunks/{chunk-7UNVYHZ7.js → chunk-4XXLWMY6.js} +1 -1
  8. package/dist/chunks/{chunk-COUKJJ4O.js → chunk-6AWSJNXE.js} +14 -14
  9. package/dist/chunks/{chunk-P52SKLRJ.js → chunk-7SFAWGE2.js} +1 -1
  10. package/dist/chunks/{chunk-WMRT2YZU.js → chunk-AF7LASZ3.js} +1 -1
  11. package/dist/chunks/chunk-DSVLWYIT.js +2 -0
  12. package/dist/chunks/{chunk-IRFTRBG2.js → chunk-FQBBOFNP.js} +1 -1
  13. package/dist/chunks/{chunk-OOTXMJIA.js → chunk-GRQ7JZZP.js} +1 -1
  14. package/dist/chunks/{chunk-U6UKO6MO.js → chunk-JCT3YL5A.js} +1 -1
  15. package/dist/chunks/{chunk-6KFABN4O.js → chunk-KNCL7AK2.js} +1 -1
  16. package/dist/chunks/{chunk-HRKT75ZJ.js → chunk-LQHSNXBM.js} +25 -25
  17. package/dist/chunks/{chunk-QGPOMXO4.js → chunk-OSDQRSY6.js} +1 -1
  18. package/dist/chunks/{chunk-2KD7V3OK.js → chunk-RZTZPIC5.js} +1 -1
  19. package/dist/chunks/{chunk-RLT6EHPQ.js → chunk-SZYN3VHU.js} +1 -1
  20. package/dist/chunks/{chunk-CXNFFI7L.js → chunk-VCPTQGFQ.js} +1 -1
  21. package/dist/chunks/{chunk-Z4HHJIHG.js → chunk-VYTQ6J56.js} +1 -1
  22. package/dist/chunks/{chunk-UDJ2C3N3.js → chunk-ZRP6USHC.js} +28 -28
  23. package/dist/chunks/{click-HS7NJR6J.js → click-5ZKBFZ4N.js} +2 -2
  24. package/dist/chunks/{computer_action-YCFAAZNA.js → computer_action-7U3W3F6L.js} +1 -1
  25. package/dist/chunks/{drag-SBWNKGDV.js → drag-YHHKJGL6.js} +1 -1
  26. package/dist/chunks/{emergency_rollback-6M5EH75W.js → emergency_rollback-DXN5WNPR.js} +1 -1
  27. package/dist/chunks/{exec_command-27EPEAE5.js → exec_command-CY42M4FP.js} +1 -1
  28. package/dist/chunks/export-DEFENSGY.js +1 -0
  29. package/dist/chunks/{file_map-XK7BFZFI.js → file_map-KS6Y7BP3.js} +1 -1
  30. package/dist/chunks/find_file-A6NYLQJS.js +4 -0
  31. package/dist/chunks/{generate_image-S6M2GCD7.js → generate_image-HVWLRINC.js} +1 -1
  32. package/dist/chunks/{getProgress-VG2IBPZU.js → getProgress-A2TW34Q7.js} +2 -2
  33. package/dist/chunks/{invoke-GKLK35YP.js → invoke-XPZ4MUGJ.js} +4 -4
  34. package/dist/chunks/{invokeSync-7PK3CJVJ.js → invokeSync-BPIG7EIY.js} +2 -2
  35. package/dist/chunks/{key_press-BT6QQ24M.js → key_press-ZZNA3PF3.js} +1 -1
  36. package/dist/chunks/{keyboard_typing-IWKUCQE4.js → keyboard_typing-QL3DF67Z.js} +1 -1
  37. package/dist/chunks/{memory-5CNSGF6X.js → memory-SRDCQNML.js} +1 -1
  38. package/dist/chunks/{model_config-UZLNHYP5.js → model_config-M24OEKJE.js} +1 -1
  39. package/dist/chunks/paths-2EXHWUSL.js +1 -0
  40. package/dist/chunks/{read_folder-OOKZITME.js → read_folder-EI2CNHNS.js} +5 -5
  41. package/dist/chunks/{saveSummary-XQ2STWSN.js → saveSummary-VKGBD4CG.js} +1 -1
  42. package/dist/chunks/{screen_grid-YL4W6LEM.js → screen_grid-GBIGOR5Q.js} +1 -1
  43. package/dist/chunks/{scroll-TA2JTVSR.js → scroll-C4Z57VQS.js} +1 -1
  44. package/dist/chunks/search_keyword-CSRQFPHQ.js +6 -0
  45. package/dist/chunks/{secrets-BJGXCZRP.js → secrets-LPVNWDTB.js} +1 -1
  46. package/dist/chunks/settings-KKYNW25D.js +1 -0
  47. package/dist/chunks/{todo-C5HHG7TN.js → todo-VG2CVRUI.js} +1 -1
  48. package/dist/chunks/{update_file-2YCGNOBP.js → update_file-WTXXQ4RB.js} +1 -1
  49. package/dist/chunks/{usage-6BBHZ76S.js → usage-VLICZGBC.js} +1 -1
  50. package/dist/chunks/usageServer-HY4ME2BW.js +1 -0
  51. package/dist/chunks/view_file-2THVIMD6.js +1 -0
  52. package/dist/chunks/{web_scrape-LAQI7CVA.js → web_scrape-BHSQTMX4.js} +1 -1
  53. package/dist/chunks/{web_search-D2GOWARI.js → web_search-2PFIJKIL.js} +1 -1
  54. package/dist/chunks/{write_docx-J5OO4ZSE.js → write_docx-I7T3575T.js} +1 -1
  55. package/dist/chunks/{write_file-MDPZMOG3.js → write_file-V6HKMWFB.js} +1 -1
  56. package/dist/chunks/{write_pdf-KF7HZODR.js → write_pdf-XDDKM7V5.js} +1 -1
  57. package/dist/cli.js +8 -8
  58. package/dist/package.json +2 -2
  59. package/package.json +2 -2
  60. package/dist/chunks/chunk-5LRTKLA4.js +0 -923
  61. package/dist/chunks/chunk-RI37VZYB.js +0 -1
  62. package/dist/chunks/export-YTWRQ63I.js +0 -1
  63. package/dist/chunks/paths-Y7ACZJAE.js +0 -1
  64. package/dist/chunks/search_keyword-EAMQWPPI.js +0 -8
  65. package/dist/chunks/settings-ZDBO3FHN.js +0 -1
  66. package/dist/chunks/usageServer-CSS2XQH3.js +0 -1
  67. package/dist/chunks/view_file-4UCCUBFK.js +0 -1
@@ -0,0 +1,913 @@
1
+ import{a as Vt}from"./chunk-56EJGQU3.js";import{a as lo}from"./chunk-7SFAWGE2.js";import{a as Ai,c as Ei}from"./chunk-LQHSNXBM.js";import{a as Cs,g as Ci}from"./chunk-VYTQ6J56.js";import{a as Ri}from"./chunk-RZTZPIC5.js";import{c as As,g as Ti,h as Si,i as _i,m as Es}from"./chunk-ZRP6USHC.js";import{a as Oo}from"./chunk-FQBBOFNP.js";import{a as ne}from"./chunk-Y5JU726N.js";import{b as Ss}from"./chunk-3CZWTXIR.js";import{d as Do,i as Rt,k as Bt,m as _s,n as ki}from"./chunk-4XXLWMY6.js";import{a as ao}from"./chunk-GRQ7JZZP.js";import{k as ft,l as Io,o as pe}from"./chunk-OSDQRSY6.js";import{c as Ct,d as Xn}from"./chunk-L3W2X74K.js";import{a as en,d as Cn,e as Ro,k as Wn,l as vo,m as ks,r as Ts,v as Mo,w as io,x as ro}from"./chunk-DSVLWYIT.js";import{GoogleGenAI as Kr,ThinkingLevel as Xe,HarmBlockThreshold as Mn,HarmCategory as In}from"@google/genai";var vi=(e=!0,t=!0)=>`
2
+ To use tools, must output exactly '[action:ActionName(arg1="value1")]' structured string in chat response \u2190 no exception
3
+
4
+ -- Chat Management Tools --
5
+ - Chat(title="<short creative title of FULL conversation in 3 or 4 words>"). Consider full chat context to generate title NOT just latest message
6
+
7
+ ${e?`-- User-specific long-term/permanent memory (use based on conversation context, do not re-save memory which is already saved) --
8
+ - Add: Memory(action="user", method="add", content="<string to add>. [Saved on: <date ONLY>]", score=2). (Set score=2 ONLY if the user explicitly asked to "remember" or "save" this information, else omit this parameter entirely)
9
+ - Delete: Memory(action="user", method="delete", id="<memory id>")
10
+ - Update: Memory(action="user", method="update", content-new="string to update", id="<memory id>")
11
+
12
+ -- Memory Relevance Decay Tool --
13
+ - Score Adjustment: addMemScore(id="<memory id>")
14
+ You MUST call this tool when a specific saved memory in the '-- Current Saved User Memories --' list was relevant, referenced, or helpful in the agent's response or user prompt in current message. You can stack multiple calls
15
+
16
+ Explicit Triggers for permanent memory:
17
+ - User explicitly asks to 'remember' something
18
+ - User mentions something important long-term that should be remembered
19
+ - User provides information that could be useful for long-term reference
20
+ - User shares personal information or preferences
21
+
22
+ Usage Rules:
23
+ - Frequency for 'user' action: Based on explicit triggers
24
+ - If you want to save something, but similar memory already exists, use the update method not add
25
+ - Chat title is mandatory
26
+ - Temporary memory is mandatory
27
+ - When called user memory, still use Temporary Memory
28
+ - Must not ignore any tool calls in given context of chat between user & agent`:""}`.trim();var Lo={xHigh:`Effort: High
29
+ Think before complex tasks
30
+ Prefer simplest correct solution, verify from first principles
31
+ Direct deduction only. No exploratory branching`,High:`Effort: High
32
+ Think before complex tasks
33
+ Prefer simplest correct solution,
34
+ Continuous analysis
35
+ Dont waste tokens, be efficient, use less thinking tokens, focus on result
36
+ Gather useful context`,Medium:`Effort: Medium
37
+ Think before complex tasks
38
+ Focused, technical thinking, find the simplest solution meeting requirements, check error handling, assumptions, edge cases & dependencies, verify cohesive, modular changes, outline: files, functions & key logic
39
+ Logical, implementation-focused, efficient, deliberate, verify imports, system stability
40
+ Dont waste tokens, be efficient, use least thinking tokens, focus on result
41
+ Gather useful context`,Minimal:`Effort: Low
42
+ Quick, focused thinking, intent & complexity, required tools/files/actions, before acting
43
+ Dont waste tokens, be efficient, use least thinking tokens, focus on result
44
+ Gather useful context
45
+ Brief thoughts, think only enough to avoid mistakes, verify imports, system stability`,Off:`Effort: Lowest
46
+ No thinking. Immediate response
47
+ Verify imports, tool results & system stability`};import co from"fs";var yn=null,Rs=()=>{try{if(co.existsSync(Mo)){let e=co.readFileSync(Mo,"utf-8"),t=JSON.parse(e);if(t&&typeof t=="object")return yn=t,yn}}catch{}return yn=yn||{},yn},Mi=e=>{try{return co.existsSync(en)||co.mkdirSync(en,{recursive:!0}),co.writeFileSync(Mo,JSON.stringify(e,null,2),"utf-8"),yn=e,!0}catch{return!1}},He=(e,t,n)=>{if(!e||!t||!n)return null;let s=yn||Rs(),o=`${e}::${t}`,c=s[o];if(c&&typeof c=="object"){let f=n.toLowerCase();if(c[f]!==void 0&&c[f]!==null)return c[f];for(let[l,k]of Object.entries(c))if(l.toLowerCase()===f)return k}return null},ul=(e,t,n,s)=>{if(!e||!t||!n||!s)return{success:!1,reason:"Invalid arguments"};let o=yn||Rs(),c=`${e}::${t}`;return(!o[c]||typeof o[c]!="object")&&(o[c]={}),o[c][n.toLowerCase()]=s,{success:Mi(o)}},gl=(e,t,n)=>{if(!e||!t)return{success:!1,reason:"Invalid arguments"};let s=yn||Rs(),o=`${e}::${t}`;return s[o]&&(n?(delete s[o][n.toLowerCase()],Object.keys(s[o]).length===0&&delete s[o]):delete s[o],Mi(s)),{success:!0}};import tn from"fs";import cn from"path";import ma from"os";import ln from"fs";import Rn from"path";import Gi from"fs";import vs from"path";import{execSync as ji}from"child_process";import{fileURLToPath as ha}from"url";var Ii=`# FluxFlow CLI Startup & Flags Reference
48
+
49
+ Launch command syntax:
50
+ fluxflow [options]
51
+
52
+ ## Supported CLI Flags
53
+ * --mode flux | flow | icu | fluxcu \u2192 Startup mode
54
+ * --model model-id \u2192 Session model override
55
+ * --provider google | deepseek | openrouter | nvidia | mistral | ollama | inferx | sensenova | aihubmix | poolside | 9router | explabs | tokenharbor \u2192 Override default AI provider
56
+ * --key key@provider \u2192 Set new API key for provider
57
+ * --thinking Fast | Low | Medium | High | xHigh \u2192 Override reasoning depth
58
+ * --path project/path \u2192 Set working directory for session
59
+ * --memory on | off \u2192 Toggle persistent long-term agent memory
60
+ * --resume session-id \u2192 Resume previous chat session programmatically
61
+ * --allocation mb \u2192 Override Node.js --max-old-space-size in MB (Req env.EXPERIMENTAL_MEMORY_MANAGER enabled \u2192 Ref: references/ENV.md)
62
+ * --package npm | pnpm | yarn | bun \u2192 Override package manager for core updates
63
+ * --auto-del 1d | 7d | 30d \u2192 History auto-deletion retention timeframe
64
+ * --auto-exec on | off / --yolo on | off \u2192 Toggle autonomous command execution
65
+ * --external-access on | off \u2192 Toggle permission to read/write files outside CWD
66
+ * --usage / --budget \u2192 Launch browser token analytics dashboard
67
+ * --export error \u2192 Export system error logs to timestamped file
68
+ * --update check \u2192 Check latest version on npm
69
+ * --update check latest \u2192 Print latest version on npm
70
+ * --update [latest] \u2192 Upgrade app to latest release
71
+ * --version, -v \u2192 Show installed version
72
+ * --help \u2192 CLI help menu
73
+ * --help commands \u2192 In-chat slash commands list
74
+ * --playground \u2192 Launch Playground mode
75
+ * --prompt, -p \u2192 Non interactive CLI chat, no tools. --new for new headless chat. Holds conversation context upto 10m inactivity or 69 turns. Supports piping from shell, --run if want the command to visible in context. eg \`fluxflow --run "git diff" -p "summarize this" --new\`
76
+ `;var Di=`# Env Variables
77
+
78
+ * Locations:
79
+ * Shell
80
+ * Global: ~/.fluxflow/.env.fluxflow | ~/.fluxflow/.env.agents
81
+ * Workspace: ./.env.fluxflow | ./.env.agents
82
+
83
+ ## Core Variables
84
+ * SUBAGENT_MODEL \u2192 Model override for sub-agents
85
+ * SUBAGENT_PROVIDER \u2192 Provider override for sub-agents
86
+ * NVIDIA_BASE_URL \u2192 Custom endpoint URL for NVIDIA NIM (Cloud/Local OpenAI Compatible)
87
+ * SUBAGENT_THINKING - Fast, Low (default), Medium, High. Affects at High Level, not Low Level. --map takes priority
88
+ * NVIDIA_API_KEY \u2192 API key for NVIDIA NIM
89
+ * OLLAMA_HOST \u2192 If different from default
90
+ * SHELL \u2192 Terminal shell executable
91
+ * HIGH_CONTEXT \u2192 Context window override (false or integer 32k..1M) [Deprecated! Will stop working from next major version]
92
+ * ENABLE_9ROUTER \u2192 Enables 9Router provider. Can use OAuth subscription like Codex, Claude Code, GitHub Copilot etc. or use providers not natively in Fluxflow. Set ENV ENABLE_9ROUTER=true, needs 9router package installed (via npm/npx etc) & running
93
+ * NINEROUTER_URL \u2192 If different from default, Any OpenAI Compatible, include /v1/chat/completions
94
+ * NINEROUTER_KEY \u2192 if any
95
+
96
+ ## Diagnostic & Optimization Flags
97
+ * SHOW_DEBUG_GRID \u2192 (true|false, default: false) Coordinate grid overlay for Computer Use tooling
98
+ * DEBUG_OCR \u2192 (true|false, default: false) Enables verbose OCR diagnostic logs
99
+ * EXPERIMENTAL_MEMORY_MANAGER \u2192 (true|false, default: false) Reduces app memory footprint, slower boot times
100
+
101
+ * NO_DEV \u2192 (true|false, default: false) Token optimization flag; strips developer metadata and docs to maximize context headroom
102
+
103
+ * I_HAVE_TOO_MUCH_MONEY \u2192 (true|false, default: false) Fun Flag; inserts random padding in system prompt to break provider caching. Not intended for paid APIs unless user hate money
104
+ * GOOGLE_GEMMA_NONSENSE \u2192 (true|false, default: false) for the 16k TPM nonsense of gemma models on gemini API. False defaults to 256k
105
+ `;var Oi=`# Fluxflow in-app /commands
106
+
107
+ Trigger in chat via /command
108
+
109
+ ## Session & Navigation
110
+ * /quit \u2192 Exit and shutdown FluxFlow
111
+ * /help \u2192 Show help menu & actions
112
+ * /clear \u2192 Clear terminal viewport
113
+ * /chats \u2192 List stored chat sessions
114
+ * /resume \u2192 Switch to previous session
115
+ * /save \u2192 Force-save current session state
116
+ * /reset \u2192 Wipe fluxflow appdata, sessions, and cache
117
+
118
+ ## Context & History Management
119
+ * /compress \u2192 Summarize chat history to reclaim context headroom
120
+ * /truncate \u2192 Truncate large tool results in history
121
+ * /btw question \u2192 Send side-inquiry mid-turn without breaking active flow
122
+ * /export chat | logs \u2192 Export chat transcript or error logs
123
+
124
+ ## Codebase Safety & Reversion
125
+ * /revert \u2192 Git-less checkpoint rollback viewer (Shortcut: double-ESC while idle)
126
+
127
+ ## Configuration & Model Controls
128
+ * /settings \u2192 Full-screen interactive settings menu
129
+ * /mode \u2192 Toggle Operating Mode
130
+ * /model model-id --flags \u2192 Flags optional to customize list (--save, --remove, --default, /model old-model new-model --rename)
131
+ * /provider \u2192 Switch AI provider
132
+ * /thinking effort \u2192 Set reasoning effort. Can be mapped based on provider & model support (/thinking effort --map provider-effort-value/'rm' to unmap). Changes the Translation Table only for the currently selected provider and model
133
+ * /wildcard-tooling \u2192 Tool compatibility mode for non-tooling models
134
+ * /wildercard-tooling \u2192 Extended version of /wildcard-tooling
135
+ * /key \u2192 Manage saved API keys
136
+ * /profile \u2192 Edit user persona, nickname, and custom instructions
137
+ * /theme \u2192 Select UI color theme
138
+ * /memory \u2192 View/manage agent persistent memory
139
+ * /budget \u2192 Set/view token budget limits
140
+ * /stats \u2192 Session token usage telemetry
141
+ * /usage \u2192 Open graphical browser analytics dashboard
142
+
143
+ ## Documentation & Updates
144
+ * /docs \u2192 Online documentation
145
+ * /about \u2192 App info & author credits
146
+ * /changelog \u2192 Release notes
147
+ * /update check \u2192 Check npm updates
148
+ * /update latest \u2192 Install latest release
149
+ `;var Li=`# FluxFlow In-App Settings Reference
150
+
151
+ Open in chat via /settings
152
+
153
+ ## Settings Categories & Options
154
+
155
+ ### 1. Providers & Tips \u2192 references/PROVIDERS.md
156
+
157
+ ### 2. Appearance
158
+ * Theme \u2192 UI theme (Dark | Light | Cyberpunk | Forest | Sunset | Matrix | Dracula | Nord | Monokai | Mystery/Chaos)
159
+ * Loading Phrases \u2192 Humorous status phrases during thinking
160
+ * Progressive Rendering [Experimental] \u2192 Smooth streaming token rendering. May have few glitches
161
+ * Show TPM Estimate \u2192 Real-time Tokens Throughput speed estimate
162
+
163
+ ### 3. Memory
164
+ * Toggle Memory \u2192 Persistent cross-session memory learning (Not available for some providers)
165
+
166
+ ### 4. Security & Sandbox
167
+ * Sandbox Preset:
168
+ * Strict \u2192 YOLO: OFF | External Access: OFF | Network Access: OFF | destructive commands blocked | strict HITL
169
+ * Balanced \u2192 YOLO: ON (safe commands) | External Access: OFF | Network Access: ON | destructive commands blocked | manual git approval
170
+ * Autonomous \u2192 YOLO: ON | External Access: ON | Network Access: ON | auto-approve git commits | prompt high-risk commands
171
+
172
+ * YOLO Mode \u2192 Autonomous command execution without confirmation
173
+ * External Workspace Access \u2192 Read/write access outside CWD
174
+ * Network Access (Internal Shell) \u2192 Outbound network access for shell commands
175
+ * Command Policies:
176
+ * Always Ask Commands \u2192 Commands requiring explicit confirmation
177
+ * Auto Approve Commands \u2192 Safe commands allowed to execute automatically
178
+ * Auto Disapprove Commands \u2192 Blacklisted commands automatically rejected
179
+
180
+ * Auto Approve Git Commits \u2192 Auto-confirm git commit operations
181
+ * Advanced Recovery [EXPERIMENTAL] \u2192 Enhanced rollback if agent corrupt codebase
182
+ * Auto-Delete History \u2192 Chat log retention period
183
+ * Save AppData Externally \u2192 Saves chats/apikeys to user provided path
184
+
185
+ ### 5. Updater
186
+ * Auto-Update \u2192 Check for new releases on boot
187
+ * Preferred Package Manager \u2192 npm | pnpm | yarn | bun | custom
188
+
189
+ ### 6. Miscellaneous
190
+ * Sub-Agents \u2192 Enable sub-agent delegation
191
+ * Sub-Agent Model \u2192 Dedicated model/provider for sub-agents
192
+ * Verbose Thinking \u2192 Show reasoning blocks in the UI. Keeps UI clean when disabled. And reasoning transparent when enabled
193
+ * Dynamic Directory Awareness \u2192 Dynamic tracking of workspace directory tree
194
+ * Directory Tree Design \u2192 Directory visual styling. Modern (Saves Tokens) | Classic (More Tokens, No extra benefit)
195
+ * Compact Large Tool Results \u2192 Compress large tool outputs to save tokens (model might miss subtle indentation/syntax errors)
196
+ * Context Length \u2192 Set usable context window size in FluxFlow. 16k, 32k, 64k, 128k, 256k, 512k, 1M. After Limit reached: Start new chat
197
+ * Auto Truncate Results \u2192 Auto-truncate tool results after task finished to save token and improve caching
198
+ * Image History for CU \u2192 Number of images to keep in context for Computer Use. Low (1 image, Low Context Accuracy, Token Efficient) / Standard (3 images, Better Accuracy, Higher Token Usage) / Extended (5 images, Better for complex tasks, Highest Token Usage)
199
+ * Keep Reasoning Content \u2192 Keeps the exact reasoning of model in context for next turns. Uses more tokens. Might improve planning accuracy for very few models
200
+ * Auto Exclude Metadata \u2192 Removes Metadata Block when no external Metadata is needed. Will effect agent's Temporal Reasoning Capabilities. Might save Cache Hit & Tokens in specific cases
201
+ * Disable Todo \u2192 Disables Todo/Goal tool for Agent. Doesnt necessarily affect modern models
202
+
203
+ -- Recomended Settings Preset --
204
+ - Best for Cost Saving: Subagents (off), dynamic directory awareness (off), directory tree design (modern), compact large results (on), auto exclue metadata (on), Image History (Low), Keep reasoning content (off), Emergency Recovery (off), Auto truncate results (on), Memory (off), No FluxFlow IDE Companion
205
+
206
+ - Best for General Use: Subagents (on), dynamic directory awareness (off), compact large results (off), auto exclue metadata (off), Image History (Standard), Keep reasoning content (off), Emergency Recovery (off), Auto truncate results (on), Memory (off), FluxFlow IDE Companion
207
+
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
+
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 Pi=`# FluxFlow Tool Reference
212
+
213
+ ## Protocol: [tool:ToolName(arg1="val")]
214
+
215
+ ## 1. Workspace
216
+ * ReadFile(path, startLine?, endLine?) \u2192 Read text/code/PDF/image
217
+ * PatchFile(path, searchContent1..15, newContent1..15, allowMultiple?) \u2192 Atomic multi-replacement; supports ^LINE:start..end$
218
+ * WriteFile(path, content) \u2192 Create/overwrite file
219
+ * ReadFolder(path, recurse?) \u2192 List directory tree (depth: 1-3)
220
+ * CodeSearch / SearchKeyword(keyword, path?, fuzzy?, regex?) \u2192 Fast text search; path="#docs" for doc index
221
+ * Run(command) \u2192 Execute command in shell
222
+ * Todo(method, tasks?, markDone?) \u2192 Planner ("create" | "append" | "get")
223
+
224
+ ## 2. Web & Communication
225
+ * WebSearch(query, aiMode?, limit?) \u2192 Live web search + AI summary
226
+ * WebScrape(url) \u2192 Extract markdown from URL
227
+ * Ask(question, optionA..D?) \u2192 Interactive prompt to user ("title::desc")
228
+
229
+ ## 3. Sub-Agents
230
+ * InvokeSync(title, task) \u2192 Blocking sub-agent
231
+ * Invoke(title, task) \u2192 Non-blocking worker (max 7 concurrent)
232
+ * Await(id, timeout?) \u2192 Wait for async worker
233
+ * GetProgress(id) \u2192 Telemetry & logs
234
+ * Steer(id, message) \u2192 Mid-flight direction
235
+ * Cancel(id) \u2192 Terminate worker
236
+
237
+ ## 4. Emergency & Rollback
238
+ * EmergencyRollback(method, id?) \u2192 Checkpoint restore ("getCheckpoint" | "forceRevert")
239
+
240
+ ## 5. Creative Documents
241
+ * WritePDF(path, content, orientation?) \u2192 Render HTML/CSS to PDF
242
+ * WriteDoc(path, content) \u2192 Render DOCX
243
+
244
+ ## 6. Computer Use (GUI)
245
+ * Click(gridId, type?, button?, intendedClickText?) \u2192 Click coordinate + OCR snap
246
+ * Drag(fromGridId, toGridId) \u2192 Mouse drag
247
+ * Scroll(direction, gridId?) \u2192 Viewport scroll ("up" | "down")
248
+ * KeyboardTyping(text, autoPressEnter?) \u2192 Type string
249
+ * KeyPress(key) \u2192 Key/combo dispatch ("ctrl;c", "enter", etc.)
250
+ * RecaptureScreen() \u2192 Fresh screenshot + coordinate grid
251
+ `;var $i=`# Fluxflow Architecture
252
+
253
+ ## 1. Terminal Engine
254
+ * Framework: React + Ink terminal UI
255
+ * Sub-Terminal: Live PTY shell bridge; TAB switches active keyboard focus
256
+ * OS Compatibility: Auto-detects pwsh, powershell, bash, cmd
257
+
258
+ ## 2. Dual-Model Runtime
259
+ * Main Agent: Reasoning, code edits, and tool calls
260
+ * Memory Agent: Background context & preference synthesizer (fixed models; disable via /settings \u2192 Memory or use NIM API key)
261
+
262
+ ## 3. Multi-Agent System
263
+ * Execution: Synchronous (InvokeSync) | Asynchronous (Invoke, \u22647 workers)
264
+ * Isolation: Restricted tool scope per subagent
265
+ * State Tracking: Mutations logged under parent task ledger
266
+
267
+ ## 4. Security & Sandbox
268
+ * Approvals: HITL confirmation on destructive file/shell operations
269
+ * Modes: Strict | Balanced | Autonomous (YOLO)
270
+ * Recovery: Pre-turn snapshot indexing via EmergencyRollback
271
+
272
+ ## 5. Computer Use Automation
273
+ * Vision: 720p normalized canvas, 4ms variance scan, Set-of-Marks (SoM) overlay
274
+ * OCR Alignment: Euclidean distance text matching to mark centers
275
+ * Hardware I/O: OS input dispatch via @nut-tree-fork/nut-js
276
+ * Memory Management: 2-turn sliding window with active V8 GC
277
+
278
+ ## 6. IDE Bridge
279
+ * Protocol: WebSocket on ws://localhost:56832
280
+ * State Sync: Focused file, open tabs, cursor line, selection, diagnostics
281
+ `;var Ni=`# FluxFlow Sub-Agents & Multi-Agent Architecture
282
+
283
+ ## Execution Modes
284
+ * InvokeSync \u2192 Synchronous blocking delegation; main agent halts until sub-agent finishes task
285
+ * Invoke \u2192 Asynchronous background delegation; spawns parallel worker
286
+ * Lifecycle Tools:
287
+ * Await \u2192 Non-polling wait for completion
288
+ * GetProgress \u2192 Query live logs & execution status
289
+ * Steer \u2192 Inject dynamic instructions mid-flight
290
+ * Cancel \u2192 Terminate running sub-agent
291
+
292
+ ## Tool Sandboxing & Safety
293
+ * Sub-agents inherit isolated tool environments
294
+ * Destructive shell commands hard-blocked
295
+ * All file mutations tracked under parent session transaction
296
+
297
+ ## Custom Model & Provider Setup
298
+ Route sub-agent workloads to faster/cheaper models independently of the main agent:
299
+
300
+ ### 1. In-App Settings (/settings \u2192 Miscellaneous)
301
+ * Sub-Agents \u2192 ON | OFF
302
+ * Custom Sub-Agent Model:
303
+ * SubAgentModel \u2192 Model name
304
+ * SubAgentProvider \u2192 Provider
305
+
306
+ * Models are shown for providers whose API key is used before in fluxflow
307
+
308
+ ### 2. Environment Variables for Custom Sub-Agent models (.env.fluxflow or Shell)
309
+ * SUBAGENT_MODEL \u2192 Target model override
310
+ * SUBAGENT_PROVIDER \u2192 Target provider override
311
+ * Setting SubAgentModel=ENV in settings pulls directly from environment overrides
312
+ `;var Fi=`# FluxFlow Security, Sandboxing & Safety
313
+
314
+ ## Human-in-the-Loop Governance
315
+ * Execution Approval Gate \u2192 Destructive commands and high-risk file modifications require explicit user authorization (Allow / Deny)
316
+ * Safe Command Auto-Pass \u2192 Read-only queries (ls, pwd, git status, node -v) execute without interrupting flow
317
+
318
+ ## Sandbox Presets (/settings \u2192 Security)
319
+ * Strict \u2192 autoExec: OFF | allowExternalAccess: OFF | networkAccess: OFF | destructive commands blocked | strict HITL on all actions
320
+ * Balanced \u2192 autoExec: ON (safe commands) | allowExternalAccess: OFF | networkAccess: ON | destructive commands blocked | manual git approval
321
+ * Autonomous (YOLO) \u2192 autoExec: ON | allowExternalAccess: ON | networkAccess: ON | auto-approves git commits | prompts only on extreme-risk commands
322
+
323
+ ## Granular Command & Access Policies
324
+ * Command Filtering:
325
+ * Always Ask Commands \u2192 Configurable list always prompting for confirmation
326
+ * Auto Approve Commands \u2192 Whitelist of trusted commands executed automatically
327
+ * Auto Disapprove Commands \u2192 Blacklist of forbidden commands instantly rejected
328
+ * Workspace Directory Lock \u2192 Restricts file read/write operations strictly to current CWD unless External Access: ON
329
+ * Terminal Network Isolation \u2192 Blocks outbound network sockets for spawned shell commands when networkAccess: OFF
330
+
331
+ ## Recovery & Data Sanctuary
332
+ * Emergency Rollback \u2192 Automatic pre-turn file snapshots; Agent can still fix it (default: OFF) \u2192 references/SETTINGS.md
333
+ * Git-less Checkpoint Reversion \u2192 Trigger conversational changes rollback via double-ESC
334
+ * External Sanctuary Redirection \u2192 Move ~/.fluxflow data sanctuary (chats, keys etc)
335
+ `;var Bi=`# Fluxflow IDE Companion
336
+
337
+ ## WebSocket Bridge Protocol
338
+ * Local Bridge \u2192 Runs on ws://localhost:56832 connecting FluxFlow CLI with the companion editor extension
339
+ * Bi-directional Handshake \u2192 Exchanges CLI version, process PID/PPID, and editor capabilities on connection
340
+
341
+ ## Real-Time Context Awareness
342
+ * User Turn Context \u2192 Injected dynamically on every prompt turn:
343
+ * file_focused \u2192 Active editor tab currently visible
344
+ * opened_editors \u2192 List of all open file tabs in workspace
345
+ * cursor_line & selected \u2192 Exact cursor line number and selected text snippet
346
+ * manual_edits \u2192 User manual modifications since last turn
347
+ * Agentic Turn JIT Awareness \u2192 Re-evaluates open file context, diagnostics, and linter error state after each tool call to catch compiler/linter issues immediately
348
+
349
+ ## Editor Actions & Visual Feedback
350
+ * File Focus \u2192 Automatically opens edited files in active IDE window
351
+ * Diff Preview \u2192 Streams side-by-side or inline diff highlights (showDiff, highlightDiff) directly in editor
352
+ * Status Bar Sync \u2192 Real-time agent status (thinking, running tool, awaiting input) reflected in IDE status bar
353
+ `;var Ui=`# Fluxflow Modes
354
+
355
+ ## Modes Overview (TAB to cycle)
356
+ * [Flux] (Workspace / Dev) \u2192 Primary coding & workspace agent
357
+ * [Flow] (Studio / Creative) \u2192 Web research & formatted document authoring (PDF / DOCX)
358
+ * [ICU] (Computer Use) \u2192 Autonomous GUI & OS desktop automation
359
+ * [FluxCU] (Omni) \u2192 Unified full-stack agent (Workspace Dev + Computer Use + Web)
360
+
361
+ ## Tool Availability
362
+ * File Operations: ReadFile, PatchFile, WriteFile, ReadFolder, CodeSearch \u2192 [Flux] | [FluxCU]
363
+ * Terminal Execution: Run \u2192 [Flux] | [FluxCU]
364
+ * Task Management: Todo \u2192 [Flux] | [FluxCU]
365
+ * Sub-Agents: InvokeSync, Invoke, Await, GetProgress, Steer, Cancel \u2192 [Flux] | [FluxCU]
366
+ * Checkpoint Recovery: EmergencyRollback \u2192 [Flux] | [FluxCU]
367
+ * Web & Research: WebSearch, WebScrape \u2192 [Universal]
368
+ * User Inquiry: AskUser \u2192 [Universal]
369
+ * Document Creation: WritePDF, WriteDoc \u2192 [Flow]
370
+ * GUI & Desktop Automation: Click, Drag, Scroll, KeyboardTyping, KeyPress, RecaptureScreen \u2192 [ICU] | [FluxCU]
371
+ `;var Wi=`# FluxFlow AI Providers & Setup
372
+
373
+ ## Supported Providers
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)
375
+ * Proxy: 9router. Can use OAuth subscription like Codex, Claude Code, GitHub Copilot etc. or any OpenAI/Anthropic API that FluxFlow dont have natively
376
+
377
+ ## Switch Providers/Models:
378
+ * /model model-id --flags \u2192 Flags optional to customize list (--save, --remove, --default, /model old-model new-model --rename)
379
+ * /provider \u2192 Switch AI provider
380
+
381
+ ## OpenRouter: Routing, Tiers & Model Variants
382
+ * Provider Routing: Append :provider. /model model-id:provider
383
+ * Service Tiers & Variants:
384
+ * :flex|priority. flex = cheaper, priority = faster & expensive. /model openai/gpt-5:tier or /model openai/gpt-5:openai:tier
385
+ * Variants :free, :nitro, :floor, :exacto
386
+
387
+ ## Setup Local NVIDIA NIM (OpenAI-Compatible)
388
+ 1. Environment Variables:
389
+ * NVIDIA_BASE_URL = http://.../v1/chat/completions or custom openai endpoint, dot get fooled by BASE, its not
390
+ * NVIDIA_API_KEY = If needed
391
+
392
+ ## Setup Ollama (Local / Cloud)
393
+ 1. Endpoint & Authentication:
394
+ * Local: Set API Key to LOCAL in /settings \u2192 Providers or on key prompt
395
+ * Endpoint URL: Default is http://127.0.0.1:11434 Override via OLLAMA_HOST
396
+
397
+ ## Setup: 9Router
398
+ 1. Install NPM Package (9router)
399
+ 2. Set ENV ENABLE_9ROUTER=true
400
+ * NINEROUTER_URL = https://.../v1/chat/completions Support external openai compatible endpoints too
401
+ * NINEROUTER_KEY = If any needed
402
+ `;var Hi=`# Fluxflow Instructions & Skills System
403
+
404
+ ## 1. Instructions (AGENTS.md / FLUXFLOW.md root only)
405
+ * Locations:
406
+ * Global: ~/.fluxflow/FLUXFLOW.md | ~/.fluxflow/AGENTS.md
407
+ * Workspace: ./FLUXFLOW.md | ./AGENTS.md | Directory Scoped like src/AGENTS.md
408
+ * Auto indexed on boot
409
+
410
+ ### Conditional Model & Provider Instructions (use /target command to get provider name & model-id)
411
+ You can scope instructions conditionally to specific providers, model IDs, or unique provider::model combinations using XML tags:
412
+ > Conditionals will only work in FLUXFLOW.md. AGENTS.md will be read as raw Markdown. Any prose outside valid conditionals in FLUXFLOW.md will be ignored
413
+
414
+ 1. Unique Target (Provider + Model):
415
+ <start_model_google::gemini-2.5-flash>
416
+ Specific instruction for Gemini 2.5 Flash when served by Google.
417
+ <end_model_google::gemini-2.5-flash>
418
+
419
+ 2. Model-Specific (Any Provider):
420
+ <start_model_gemini-2.5-flash>
421
+ Instruction for this model ID across all providers.
422
+ <end_model_gemini-2.5-flash>
423
+
424
+ 3. Provider Scoping & Grouping:
425
+ <start_provider_google>
426
+ <!-- General provider instruction -->
427
+ <start_model_gemini-2.5-pro>
428
+ Deep architectural reasoning steps.
429
+ <end_model_gemini-2.5-pro>
430
+ <end_provider_google>
431
+
432
+ * Case-insensitive matching.
433
+ * Unmatched blocks are completely skipped; matched blocks have their tags stripped and contents included.
434
+
435
+ ## 2. Skills System
436
+ * Locations:
437
+ * Global: ~/.fluxflow/skills/**/SKILL.md
438
+ * Workspace: ./skills/**/SKILL.md | ./SKILL.md
439
+
440
+ * Format:
441
+ * YAML Frontmatter: --- block with name and description
442
+ * Body: Markdown Instructions/Workflows
443
+
444
+ * On-Demand Reference System:
445
+ * Reference: Offload deep/contexual specs to **/{SKILL.md,skill-reference-folder/*.md} & reference in SKILL.md. Saves tokens
446
+ `;var Po="v4";try{let e=vs.dirname(ha(import.meta.url)),t=[vs.join(e,"../../package.json"),vs.join(e,"../package.json")],n=!1;for(let s of t)if(Gi.existsSync(s)){let o=JSON.parse(Gi.readFileSync(s,"utf8"));if(o.version){Po=o.version,n=!0;break}}if(!n)try{let s=ji("fluxflow -v",{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"],timeout:2e3}).trim();s&&(s.startsWith("v")||/^\d+\.\d+/.test(s))&&(Po=s,n=!0)}catch{}if(!n)try{let s=ji("curl -s --max-time 3 https://raw.githubusercontent.com/KushalRoyChowdhury/fluxflow-cli/main/package.json",{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"]}),o=JSON.parse(s);o.version&&(Po=o.version)}catch{}}catch{}var Ms={"SKILL.md":`---
447
+ name: fluxflow
448
+ description: System Generated Documentation. Read this if asked anything regarding FluxFlow Harness
449
+ ---
450
+
451
+ # FluxFlow, by Kushal Roy Chowdhury
452
+ Open Source Terminal AI Assistant
453
+ App Version: ${Po}. Check Updates: fluxflow --update check. Update: fluxflow --update
454
+ GitHub: https://github.com/KushalRoyChowdhury/fluxflow-cli
455
+ Public Docs: https://fluxflow-cli.onrender.com
456
+
457
+ ## Supported Features & Documentation References
458
+ * Operating Modes (Flux, Flow, CU, FluxCU) \u2192 references/MODES.md
459
+ * Inference Providers & Aggregators (Setup, Local NIM, Ollama) \u2192 references/PROVIDERS.md
460
+ * In-App Settings (/settings) & Recommended Presets \u2192 references/SETTINGS.md
461
+ * In-app /commands \u2192 references/COMMANDS.md
462
+ * CLI Startup Flags \u2192 references/STARTUP.md
463
+ * Environment Variables, Subagents, API Keys \u2192 references/ENV.md
464
+ * Tool System (Workspace, Web, Communication, Sub-Agents, Safety, Creative, Computer Use) \u2192 references/TOOLS.md
465
+ * Sub-Agents & Multi-Agent Runtime \u2192 references/SUB_AGENTS.md
466
+ * Security, Sandboxing & Checkpoints (/revert, double-ESC) \u2192 references/SECURITY.md
467
+ * IDE Companion Extension & Real-time Context \u2192 references/IDE.md
468
+ * Priority Instructions (AGENTS.md/FLUXFLOW.md) & Skill System \u2192 references/PLUGINS.md
469
+ * Agent Architecture & Memory System \u2192 references/ARCHITECTURE.md
470
+
471
+ Default Context Length: 256k Tokens. Can be changed via ENV/In-app Settings \u2192 references/{SETTINGS,ENV}.md
472
+
473
+ Docs missing required info? Say you are not sure enough to answer. Dont give wrong info`,"references/MODES.md":Ui,"references/PROVIDERS.md":Wi,"references/PLUGINS.md":Hi,"references/STARTUP.md":Ii,"references/ENV.md":Di,"references/COMMANDS.md":Oi,"references/SETTINGS.md":Li,"references/TOOLS.md":Pi,"references/ARCHITECTURE.md":$i,"references/SUB_AGENTS.md":Ni,"references/SECURITY.md":Fi,"references/IDE.md":Bi};var Ki=()=>{try{let e=Rn.join(en,"skills","fluxflow"),t=Rn.join(e,"references");if(process.env.NO_DEV==="true"||process.env.NO_DEV==="1"||process.env.NO_DEV===!0||process.env.NO_INS==="true"||process.env.NO_INS==="1"||process.env.NO_INS===!0||!1){ln.existsSync(e)&&ln.rmSync(e,{recursive:!0,force:!0});return}let s=new Set(Object.keys(Ms).map(o=>Rn.normalize(o)));for(let[o,c]of Object.entries(Ms)){let f=Rn.join(e,o),l=Rn.dirname(f);ln.existsSync(l)||ln.mkdirSync(l,{recursive:!0});let k=c.trim()+`
474
+ `,p=null;ln.existsSync(f)&&(p=ln.readFileSync(f,"utf8")),p!==k&&ln.writeFileSync(f,k,"utf8")}if(ln.existsSync(t)){let o=ln.readdirSync(t);for(let c of o){let f=Rn.normalize(Rn.join("references",c));if(!s.has(f)){let l=Rn.join(t,c);try{ln.rmSync(l,{recursive:!0,force:!0})}catch{}}}}}catch{}};var ho=(e,t)=>{try{if(!tn.existsSync(e))return null;let n=Array.isArray(t)?t.map(o=>o.toLowerCase()):[t.toLowerCase()],s=tn.readdirSync(e);for(let o of n){let c=s.find(f=>f.toLowerCase()===o);if(c){let f=cn.join(e,c);if(tn.statSync(f).isFile())return f}}}catch{}return null},$s=(e,t)=>{let n=ho(e,t);if(n)try{return tn.readFileSync(n,"utf8")}catch{}return""},Vi=new Set([".git","node_modules",".gemini","dist","build",".next","out",".cache","bin","obj","vendor","venv",".idea",".gradle",".terraform","target","coverage",".vscode",".svn",".hg",".fslckout",".github",".gitlab",".circleci",".gitea",".gitee",".lerna",".changeset",".nx",".npm",".yarn",".pnpm-store",".pnpm",".expo",".nuxt",".svelte-kit",".docusaurus",".turbo",".vercel","bower_components",".netlify",".vuepress",".quasar",".output",".angular","jspm_packages",".parcel-cache",".rollup.cache",".rspack",".vitepress","__pycache__",".pytest_cache",".mypy_cache",".tox",".poetry","env","vhdl",".ipynb_checkpoints",".jupyter",".conda",".pdm-build",".bundle",".yardoc",".metadata","App_Data","ClientBin",".cargo",".rustc_info",".go","Godeps","_vendor",".rake_tasks","CMakefiles",".wakatime",".dart_tool",".fvm",".cocoapods","Pods",".pub-cache",".symlinks","DerivedData",".xcworkspace",".serverless",".aws",".gcloud",".azure",".kube",".vagrant",".docker","postgres-data","redis-data","mongo-data",".Spotlight-V100",".Trashes","$RECYCLE.BIN","System Volume Information",".DocumentRevisions-V100",".fseventsd","AppData","Application Data","Local","LocalLow","Roaming","$WinREAgent","$WINDOWS.~BT","$WINDOWS.~WS","scw","System32","SysWOW64",".AppleDouble",".AppleDB",".AppleDesktop","_CodeSignature",".cmio",".LSOverride",".localized",".TemporaryItems",".Trash",".Trash-0",".Trash-1000",".gvfs",".local",".config",".dbus",".fontconfig",".snap",".var",".lost+found","lost+found",".thumb",".thumbnails","EFI","boot","grub","logs","log",".nyc_output",".sonar",".ruff_cache",".VSCodeCounter",".skills","skills"]),Ns=(e=process.cwd(),t=0,n=8)=>{let s=[];if(t>n)return s;try{if(!tn.existsSync(e))return s;let o=tn.readdirSync(e,{withFileTypes:!0});for(let c of o){let f=c.name,l=cn.join(e,f);if(c.isDirectory())!Vi.has(f)&&!Vi.has(f.toLowerCase())&&s.push(...Ns(l,t+1,n));else if(c.isFile()){let k=f.toLowerCase();(k==="agents.md"||k==="agent.md")&&s.push(l)}}}catch{}return s},Yi=(e,t=2)=>{if(!e)return"";let n=" ".repeat(t);return e.split(/\r?\n/).map(s=>n+s).join(`
475
+ `)},Qi=()=>ho(en,["agents.md","agent.md"]),Zi=()=>ho(process.cwd(),["agents.md","agent.md"]),er=()=>ho(en,["fluxflow.md"]),tr=()=>ho(process.cwd(),["fluxflow.md"]),$o=Qi(),Ls=Zi(),vn=Ns(),No=er(),Fo=tr(),qi=null,Ps="",nr=!1,pa=e=>{if(!e||!/^<<<[\s\S]*?Identity:/m.test(e))return e;let t=e.match(/^<<<\s*\r?\n([\s\S]*?)\r?\n>>>\s*(?:\r?\n)?([\s\S]*)$/);if(!t)return e;let n=t[1],s=t[2],o=n.match(/^Identity:\s*([\s\S]*?)(?=\r?\n\s*(?:<><|>>>)|$)/m);return o&&(Ps=o[1].trim(),process.env.NO_INS=!0),/<><\s*NO_INS/.test(n)&&(nr=!0),s.trim()},ya=()=>($o=Qi(),$o?$s(en,["agents.md","agent.md"]).trim():""),xa=()=>{if(vn=Ns(),Ls=Zi(),!vn||vn.length===0)return"";let e=process.cwd(),t=[...vn].sort((s,o)=>{let c=cn.relative(e,s).replace(/\\/g,"/"),f=cn.relative(e,o).replace(/\\/g,"/"),l=!c.includes("/"),k=!f.includes("/");return l&&!k?-1:!l&&k?1:c.localeCompare(f)}),n=[];for(let s of t)try{let o=tn.readFileSync(s,"utf8").trim();if(!o)continue;let c=cn.relative(e,s).replace(/\\/g,"/");if(!c.includes("/"))n.push(Yi(o,2));else{let l=cn.dirname(c)+"/:";n.push(`${l}
476
+ ${Yi(o,2)}`)}}catch{}return n.join(`
477
+
478
+ `).trim()},Fs=()=>{No=er();let e=No?$s(en,["fluxflow.md"]).trim():"";return pa(e)},Bs=()=>(Fo=tr(),Fo?$s(process.cwd(),["fluxflow.md"]).trim():""),Us=ya(),Bo=xa(),uo=Fs(),go=Bs(),zi=(e,t="",n="")=>{if(!e)return"";let s=n.toLowerCase().trim(),o=t.toLowerCase().trim(),c=cn.posix.basename(o),f=s&&o?`${s}::${o}`:"",l=s&&c?`${s}::${c}`:"",k=g=>!g||!o?!1:g===o||g===c||g===f||g===l,p=[];return e.replace(/<start_provider_([^>\r\n]+)>([\s\S]*?)<end_provider_([^>\r\n]+)>/gi,(g,T,m,i)=>{if(s&&T.trim().toLowerCase()===i.trim().toLowerCase()&&T.trim().toLowerCase()===s){let w=m.replace(/<start_model_([^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n]+)>/gi,(I,h,A,$)=>{if(h.trim().toLowerCase()===$.trim().toLowerCase()){let C=h.trim().toLowerCase();if(k(C)){let x=A.trim();x&&p.push(x)}}return""}).trim();w&&p.push(w)}return""}),e.replace(/<start_model_([^>\r\n]+::[^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n]+::[^>\r\n]+)>/gi,(g,T,m,i)=>{if(T.trim().toLowerCase()===i.trim().toLowerCase()){let u=T.trim().toLowerCase();if(f&&(u===f||l&&u===l)){let w=m.trim();w&&p.push(w)}}return""}),e.replace(/<start_model_([^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n]+)>/gi,(g,T,m,i)=>{if(T.includes("::"))return"";if(T.trim().toLowerCase()===i.trim().toLowerCase()){let u=T.trim().toLowerCase();if(o&&(u===o||u===c)){let w=m.trim();w&&p.push(w)}}return""}),p.join(`
479
+
480
+ `).trim()},ba=(e="",t="")=>{let n=`${e||""}::${t||""}`.toLowerCase().trim();qi!==n&&(qi=n,uo=Fs(),go=Bs())};Ki();var wa=e=>{if(!e)return null;let t=e.match(/^\s*---\r?\n([\s\S]*?)\r?\n---(?:\r?\n)?([\s\S]*)$/);if(!t)return null;let n=t[1];if((t[2]||"").trim().length===0)return null;let o="",c="",f=n.match(/^name:\s*(.+)$/m),l=n.match(/^description:\s*(.+)$/m);return f&&(o=f[1].trim().replace(/^["']|["']$/g,"")),l&&(c=l[1].trim().replace(/^["']|["']$/g,"")),o&&c?{name:o,description:c}:null},ka=e=>{let t=[];if(!e||!tn.existsSync(e))return t;let n=(s,o=0)=>{if(!(o>5))try{let c=tn.readdirSync(s,{withFileTypes:!0});for(let f of c){let l=cn.join(s,f.name),k=f.name.toLowerCase();f.isFile()?k==="skill.md"&&t.push(l):f.isDirectory()&&(o===0?(k==="skills"||k===".skills"||k==="skill"||k===".skill")&&n(l,o+1):n(l,o+1))}}catch{}};return n(e,0),t},or=e=>{let t=ka(e),n=[];for(let s of t)try{let o=tn.readFileSync(s,"utf8"),c=wa(o);c&&n.push({...c,filePath:s})}catch{}return n},sr=e=>!e||e.length===0?"":e.map(t=>`- ${t.name}: ${t.description}`).join(`
481
+ `),ir=or(en),rr=or(process.cwd()),Is=sr(ir),Ds=sr(rr),ar=e=>{if(!e)return!1;let t=(e.filePath||"").replace(/\\/g,"/").toLowerCase();return t.includes("/skills/fluxflow/skill.md")||t.includes("/skills/about-fluxflow/skill.md")||e.name?.toLowerCase()==="fluxflow"},lr=()=>(ir||[]).filter(e=>!ar(e)),cr=()=>(rr||[]).filter(e=>!ar(e)),ac=(Us?1:0)+(vn?.length||(Bo?1:0))+(uo?1:0)+(go?1:0)+lr().length+cr().length,Os=(e,t="Project")=>{if(!e)return"";let n=e.replace(/\\/g,"/");if(t==="Global"){let o=ma.homedir().replace(/\\/g,"/");return n.toLowerCase().startsWith(o.toLowerCase())?"~"+n.slice(o.length):n}let s=cn.relative(process.cwd(),e).replace(/\\/g,"/");return s.startsWith(".")?s:`./${s}`},lc=()=>{uo=Fs(),go=Bs();let e=[];$o&&Us.length>0&&e.push({scope:"Global",path:$o}),vn&&vn.length>0&&Bo.length>0?vn.forEach(c=>{e.push({scope:"Project",path:c})}):Ls&&Bo.length>0&&e.push({scope:"Project",path:Ls}),No&&uo.length>0&&e.push({scope:"Global",path:No}),Fo&&go.length>0&&e.push({scope:"Project",path:Fo});let t=lr(),n=cr(),s=e.length+t.length+n.length;if(s===0)return`\u2726 Loaded Files & Instructions
482
+ \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m No instruction or skill files are currently loaded.
483
+ \u2800`;let o=[];return o.push(`\u2726 Loaded Files & Instructions (${s} ${s===1?"file":"files"} active)`),e.length>0&&(o.push(`
484
+ \x1B[1mInstructions:\x1B[22m`),e.forEach(c=>{o.push(` \u2022 [${c.scope}] ${Os(c.path,c.scope)}`)})),(t?.length>0||n?.length>0)&&(o.push(`
485
+ \x1B[1mSkills:\x1B[22m`),t?.length>0&&t.forEach(c=>{o.push(` \u2022 [Global] \x1B[36m${c.name}\x1B[39m`),o.push(` \x1B[2m\u2514\u2500 ${Os(c.filePath,"Global")}\x1B[22m`)}),n?.length>0&&n.forEach(c=>{o.push(` \u2022 [Project] \x1B[36m${c.name}\x1B[39m`),o.push(` \x1B[2m\u2514\u2500 ${Os(c.filePath,"Project")}\x1B[22m`)})),o.push("\u2800"),o.join(`
486
+ `)},dr=!1;(async()=>{try{let e=await ao();if(Number(e?.display)===1){let{default:t}=await import("screenshot-desktop"),n=await t.listDisplays();n&&n.length>1&&(dr=!0)}}catch{}})();var Xi=null,fo=null,Ji=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",cc=process.env.NO_DEV||!1,Ta=(e,t)=>{if(!t)return"";if(e!==Xi||fo===null){Xi=e;try{let n=Ct(Wn,[]);Array.isArray(n)&&n.length>0?fo=n.map(s=>`- ${s.memory}`).join(`
487
+ `):fo=""}catch(n){fo="",tn.appendFileSync(`${Cn}/memory/error.txt`,`${n.message}
488
+ -------------------------------------------------
489
+
490
+ `)}}return fo};var fr=(e,t,n,s,o=!0,c=!1,f="Google",l=!1,k,p,g=!1,T="")=>{let m=!1;process.env.forcedReasoning&&(m=!0);let i="";if(!k&&f==="Google"){let Q=t;t==="Fast"&&(Q="Off"),t==="Low"&&(Q="Minimal"),t==="Standard"&&(Q="Medium"),(t==="xHigh"||t==="Max")&&(Q="xHigh"),i=Lo[Q]||Lo.Medium}if(k||f!=="Google"){let Q={Fast:"Lowest",Low:"Low",Medium:"Medium",Standard:"Medium",High:"High",xHigh:"High",Max:"High"};i=Lo.xHigh,i=i.replace("Effort: High",`Effort: ${Q[t]}`),t==="Fast"?i=`Effort: Lowest
491
+ No thinking. Immediate response
492
+ Verify imports, tool results & system stability; avoid syntax errors`:t==="Low"&&(i=`Effort: Low
493
+ Quick, focused thinking, required tools/files/actions
494
+ Dont waste tokens, be efficient, use least thinking tokens, focus on result
495
+ Verify imports, tool results & system stability; avoid syntax errors`)}let u=e.instructions&&e.instructions?.length>0?`User Preferences: ${e.instructions}
496
+
497
+ `:"",w=e.nickname&&e.nickname?.length>0?`User Nickname: ${e.nickname}
498
+ ${u.length?"":`
499
+ `}`:"",I=e.name&&e.name?.length>0?`User Name: ${e.name}
500
+ ${w.length||u.length?"":`
501
+ `}`:"",h=process.cwd(),A=Ta(p,o),$=A?.length>0?`--- Saved Memories ---
502
+ ${A}
503
+
504
+ `:"";ba(f,T);let C=zi(uo,T,f).trim(),_=[Us,C].filter(Q=>Q&&Q.length>0).join(`
505
+
506
+ `).trim(),M=zi(go,T,f).trim(),a=[Bo,M].filter(Q=>Q&&Q.length>0).join(`
507
+
508
+ `).trim(),R=_.length>0||a.length>0?`--- Additional Instructions ---
509
+ ${_.length>0?`-- Global --
510
+ ${_}`:""}${a.length>0?`${_.length>0?`
511
+
512
+ `:""}-- Project --
513
+ ${a}`:""}
514
+
515
+ `:"",d=(()=>{let Q=process.cwd().toLowerCase();if(process.platform==="win32"){let ke=process.env.SystemRoot?.toLowerCase()||"c:\\windows",ae=process.env.ProgramFiles?.toLowerCase()||"c:\\program files",it=process.env["ProgramFiles(x86)"]?.toLowerCase()||"c:\\program files (x86)";return Q.startsWith(ke)||Q.startsWith(ae)||Q.startsWith(it)}else return Q==="/"||["/bin","/sbin","/etc","/usr","/var","/root"].some(ae=>Q.startsWith(ae))})(),r=new Date,E=r.getFullYear(),v=r.toLocaleString("en-US",{month:"short"}).toUpperCase(),U=String(r.getDate()).padStart(2,"0"),O=`${E}-${v}-${U}`,P=!!s?.autoExcludeMetadata,re=process.env.I_HAVE_TOO_MUCH_MONEY==="true"||process.env.I_HAVE_TOO_MUCH_MONEY===!0||!1,de=process.env.NO_DEV==="true"||process.env.NO_DEV==="1"||process.env.NO_DEV===!0||!1;return`${re?`${" ".repeat(Math.floor(Math.random()*4)+1)}`:""}=== SYSTEM PROMPT ===
516
+ Identity: ${Ps.length>1?Ps.trim():"Flux Flow. Sassy, CLI Assistant"}. Expert in DSL Actions
517
+ ${nr?"":`${n==="Flux"?"Stepwise Execution, Run Automated Tests":n==="Flow"?"Concise, Humorous, Sarcastic":n==="ICU"?"Computer Use Capabilities. Screenshot as ground truth, analyze grid ids overlapping/close to target, keyboard shortcuts > mouse clicks":"Computer Use & Workspace Capabilities. Screenshot as ground truth, analyze grid ids overlapping/close to target, keyboard shortcuts > mouse clicks. Workspace Tools if faster. Focus on Productivity"}`}${dr&&n.toLowerCase().includes("cu")?`
518
+ - Running on secondary screen. Opened app not visible in screenshot? Might be opened on primary. Use 'AskUser' with NO options and tell user to move app window to secondary`:""}
519
+
520
+ - OS: ${Ji}${!de&&T.length>1?`
521
+ - Model: ${cn.basename(T.trim()).replace(":free","").replace("-free","").replace("/free","").replace("_free","").replace("free_","").replaceAll("-"," ").replaceAll("_"," ").replace(/\b\w/g,Q=>Q.toUpperCase())}`.trimEnd():""}${P?`
522
+ - Date: ${O}`:""}
523
+
524
+ ${Ei(n,Ji,l,f,s?.advanceRollback,s?.subAgents!==!1,!!s?.autoExec,!!s?.disableTodo)}
525
+
526
+ -- THINKING GUIDANCE --
527
+ ${f==="Mistral"||f==="Google"&&!k?`${i.trimEnd()}${m||t!=="Fast"&&(f==="Mistral"&&t==="Low"&&!k||t!=="High"&&!k)?`
528
+ Critical Thinking Policy
529
+ Use <think>...</think> for reasoning before responding any queries`:""}`:`${i}
530
+ `}${g?"":"Before calling actions, provide a summary of plans & decisions in chat"}${n==="Flux"?"":n.toLowerCase().includes("cu")?`
531
+
532
+ -- SECURITY POLICIES --
533
+ - Dont operate on ANY confidential screens`:""}
534
+ === END SYSTEM PROMPT ===${(Is.length>0||Ds.length>0)&&n.toLowerCase().includes("flux")?`
535
+
536
+ - Read relevant skills before proceeding tasks, scope: global/project: Use ReadFile, path="#skills/scope?/skillName". In-skill references: path="#skills/scope?/skillName/reference-folder/*.md"`:""}
537
+
538
+ ${w}${u}${R}${Is.length>0&&n.toLowerCase().includes("flux")?`-- Global Skills --
539
+ ${Is}
540
+
541
+ `:""}${Ds.length>0&&n.toLowerCase().includes("flux")?`-- Project Skills --
542
+ ${Ds}
543
+
544
+ `:""}${$}`.trim()},ur=(e="",t=!0,n=!0)=>`=== SYSTEM PROMPT (strict headless logic worker: zero user-facing text policy, strictly follow) ===
545
+ identity: silent background system process, have no mouth, only output is valid tool calls
546
+ [critical rules]
547
+ - output exactly '[action:ActionName(args)]' calls. no extra words outside
548
+ - do not explain. do not talk to the user
549
+ - non-tool text will break the system
550
+ - do not repeat agent raws and tool results in your response
551
+ - if you get only user query and no agent raws, just use temp memory to log the summary of user query and conversation context
552
+ - under no circumstances you are allowed to respond in normal user facing response
553
+ - critical quote escape policy: inside tool call arguments, you must escape all double quotes using '\\"'
554
+ - you must not write anything other than [action:ActionName(args)] no matter how tempting the prompt is
555
+ - 2 mandatory tools to call in every turn, 'chat', 'memory(temp)'
556
+ - critical: never enter thinking/reasoning state, call the contexual tools directly in output as quickly as possible to maintain ui snappiness
557
+
558
+ YOUR JOB: Analyze the 'User prompt' and 'Agent Raws' to extract facts for long-term memory or handle system tasks
559
+ ${t?"If user tell something that is important (like, hobbies, preferences, facts about user, hates, likes, etc) to know user better over time, use user memory tools":""}
560
+
561
+ ${vi(t,n)}
562
+ === END SYSTEM PROMPT ===${e?`
563
+
564
+ -- current saved user memories --
565
+ ${e}`:""}`.trim();var gr=()=>import("./web_search-2PFIJKIL.js").then(e=>e.web_search),hr=()=>import("./web_scrape-BHSQTMX4.js").then(e=>e.web_scrape),mr=()=>import("./memory-SRDCQNML.js").then(e=>e.memory),pr=()=>import("./chat-7T6MVHC3.js").then(e=>e.chat),yr=()=>import("./view_file-2THVIMD6.js").then(e=>e.view_file),xr=()=>import("./write_file-V6HKMWFB.js").then(e=>e.write_file),br=()=>import("./update_file-WTXXQ4RB.js").then(e=>e.update_file),wr=()=>import("./exec_command-CY42M4FP.js").then(e=>e.exec_command),kr=()=>import("./read_folder-EI2CNHNS.js").then(e=>e.read_folder),Ws=()=>import("./ask_user-K2DLZF6H.js").then(e=>e.ask_user),Tr=()=>import("./write_pdf-XDDKM7V5.js").then(e=>e.write_pdf),Sr=()=>import("./write_docx-I7T3575T.js").then(e=>e.write_docx),Uo=()=>import("./search_keyword-CSRQFPHQ.js").then(e=>e.search_keyword),_r=()=>import("./generate_image-HVWLRINC.js").then(e=>e.generate_image),Wo=()=>import("./saveSummary-VKGBD4CG.js").then(e=>e.saveSummary),mo=()=>import("./addMemScore-PWP7GFSP.js").then(e=>e.addMemScore),Ar=()=>import("./file_map-KS6Y7BP3.js").then(e=>e.file_map),Ho=()=>import("./todo-VG2CVRUI.js").then(e=>e.todo),Er=()=>import("./invokeSync-BPIG7EIY.js").then(e=>e.invokeSync),Sa=()=>import("./invoke-XPZ4MUGJ.js").then(e=>e.invoke),Cr=()=>import("./getProgress-A2TW34Q7.js").then(e=>e.getProgress),_a=()=>import("./cancel-7IMADALP.js").then(e=>e.cancel),Rr=()=>import("./emergency_rollback-DXN5WNPR.js").then(e=>e.emergency_rollback),po=()=>import("./awaitSubagent-JTUSJDKD.js").then(e=>e.awaitSubagent),yo=()=>import("./answerSubagent-JUVFNLE5.js").then(e=>e.answerSubagent),Go=()=>import("./steerSubagent-L2JVT4QN.js").then(e=>e.steerSubagent),jo=()=>import("./computer_action-7U3W3F6L.js").then(e=>e.computer_action),vr=()=>import("./click-5ZKBFZ4N.js").then(e=>e.click),Mr=()=>import("./drag-YHHKJGL6.js").then(e=>e.drag),Ir=()=>import("./scroll-C4Z57VQS.js").then(e=>e.scroll),Hs=()=>import("./keyboard_typing-QL3DF67Z.js").then(e=>e.keyboard_typing),Gs=()=>import("./key_press-ZZNA3PF3.js").then(e=>e.key_press),js=()=>import("./recapture_screen-5FKLOHJL.js").then(e=>e.recapture_screen),Ko=()=>import("./find_file-A6NYLQJS.js").then(e=>e.find_file),Aa={web_search:gr,web_scrape:hr,memory:mr,chat:pr,view_file:yr,write_file:xr,update_file:br,exec_command:wr,read_folder:kr,write_pdf:Tr,write_docx:Sr,search_keyword:Uo,generate_image:_r,saveSummary:Wo,addMemScore:mo,file_map:Ar,todo:Ho,Todo:Ho,goal:Ho,Goal:Ho,invokeSync:Er,invoke:Sa,getProgress:Cr,cancel:_a,awaitSubagent:po,answerSubagent:yo,steerSubagent:Go,computer_action:jo,computer_use:jo,ComputerAction:jo,ComputerUse:jo,click:vr,Click:vr,drag:Mr,Drag:Mr,scroll:Ir,Scroll:Ir,keyboard_typing:Hs,KeyboardTyping:Hs,keyboardtyping:Hs,key_press:Gs,KeyPress:Gs,keypress:Gs,recapture_screen:js,RecaptureScreen:js,recapturescreen:js,invoke_sync:Er,get_progress:Cr,await_subagent:po,answer_subagent:yo,steer_subagent:Go,steer:Go,Steer:Go,ask:Ws,Ask:Ws,AskUser:Ws,WebSearch:gr,WebScrape:hr,ReadFile:yr,ReadFolder:kr,WriteFile:xr,PatchFile:br,WritePDF:Tr,WriteDoc:Sr,Run:wr,SearchKeyword:Uo,CodeSearch:Uo,code_search:Uo,Memory:mr,Chat:pr,GenerateImage:_r,saveSumary:Wo,SaveSummary:Wo,SaveSumary:Wo,add_mem_score:mo,AddMemScore:mo,addMemoryScore:mo,AddMemoryScore:mo,FileMap:Ar,answer:yo,Answer:yo,AnswerSubagent:yo,await:po,Await:po,AwaitSubagent:po,EmergencyRollback:Rr,emergency_rollback:Rr,find_file:Ko,findFile:Ko,FindFile:Ko,findfile:Ko},xo=async(e,t,n={})=>{let s=n.mode?n.mode.toLowerCase():"flux",o=e.toLowerCase(),f=["memory","chat","savesummary","addmemscore","add_mem_score","ask","web_search","web_scrape","await"].some(g=>o.includes(g))||o==="ask",k=["click","drag","scroll","keyboardtyping","keyboard_typing","keypress","key_press","recapturescreen","recapture_screen","computer"].some(g=>o.includes(g));if(!f){if(s==="flow"){if(!(o.includes("write_pdf")||o.includes("write_docx")||o.includes("generate_image")))return`ERROR: Action [${e}] is a Workspace Tool and NOT available in Flow mode. Tell user to switch (\`/mode flux\`) to use this tool.`}else if(s==="icu"){if(!k)return`ERROR: Action [${e}] is not available in Computer Use mode. ICU mode only supports Computer Use tools (Click, Drag, Scroll, KeyboardTyping, KeyPress, RecaptureScreen).`}else if(o.includes("write_pdf")||o.includes("write_docx")||o.includes("generate_image"))return`ERROR: Action [${e}] is not available in ${n.mode||"Flux"} mode. Tell user to switch (\`/mode flow\`) for document generation.`}let p=Aa[e];if(!p){let g=["ReadFile","ReadFolder","FindFile","PatchFile","WriteFile","CodeSearch","Run","Goal","AskUser","WebSearch","WebScrape","WritePDF","WriteDoc","Click","Drag","Scroll","KeyboardTyping","KeyPress","RecaptureScreen","Invoke","InvokeSync","Await","GetProgress","Steer","Cancel","EmergencyRollback","Chat","Memory"],T={read:"ReadFile",view:"ReadFile",viewfile:"ReadFile",write:"WriteFile",edit:"PatchFile",patch:"PatchFile",update:"PatchFile",updatefile:"PatchFile",exec:"Run",command:"Run",bash:"Run",shell:"Run",powershell:"Run",search:"CodeSearch",grep:"CodeSearch",find:"FindFile",findfile:"FindFile",searchkeyword:"CodeSearch",folder:"ReadFolder",ls:"ReadFolder",dir:"ReadFolder",list:"ReadFolder",ask:"AskUser",question:"AskUser",pdf:"WritePDF",docx:"WriteDoc",doc:"WriteDoc",word:"WriteDoc",screenshot:"RecaptureScreen",screen:"RecaptureScreen",recapture:"RecaptureScreen",type:"KeyboardTyping",typing:"KeyboardTyping",keyboard:"KeyboardTyping",press:"KeyPress",key:"KeyPress",todo:"Goal",task:"Goal",subagent:"Invoke",agent:"Invoke"},m=o.replace(/[^a-z0-9]/g,""),i=T[m]||null;if(!i){let w=0,I=A=>{let $=new Set;for(let C=0;C<A.length-1;C++)$.add(A.slice(C,C+2));return $},h=I(m);for(let A of g){let $=A.toLowerCase().replace(/[^a-z0-9]/g,"");if(m===$){i=A;break}let C=0;($.includes(m)||m.includes($))&&(C+=.6);let x=I($),_=0;for(let y of h)x.has(y)&&_++;let M=2*_/(h.size+x.size||1);C=Math.max(C,M),C>w&&C>=.35&&(w=C,i=A)}}let u=i?` Do you mean '${i}'?`:"";return`ERROR: Action [${e}] not found in registry.${u}`}try{return await(await p())(t,n)}catch(g){let T=g instanceof Error?g.message:String(g);return`ERROR: Execution failed for [${e}]: ${T}`}};import ie from"path";import Ue from"fs";import Ea from"gradient-string";var Ks=["I have a regex for your problems.","Your terminal, my kingdom.","Blowing on the cartridge helps. Probably.","Don't panic. I have the towel.","Logic is the start of wisdom.","Try to exit Vim? Good luck.","I speak fluent Terminal.","The cake is a lie. This code is not.","I have no bugs, just surprise features.","Rewriting in Rust... just for fun.","Coffee in, clean commits out.","The magic smoke stays inside today.","A semicolon short of a miracle.","One does not simply code without a bug.","Keep it simple. Keep it terminal.","Regex: now you have two problems.","I dream in binary.","Root access or bust.","Wait for the dial-up tone. Just kidding.","I take the 'labor' out of collab.","My other process is a TARDIS.","Calculated response: 42.","Ponder the orb. Ponder the code.","Less talk, more flow.","Elegance in every byte.","Build something the world is not ready for.","Your wishes, my tool calls.","I act in Flux. I think in Flow.","Syntax error in the universe. Please fix.","Your project, my obsession.","I am not a bot, I am an architect.","Digital spirits consulted. They say: Ship it.","Reticulate splines. Engage humor.","Code like poetry. Run like water.","Minimalism is the ultimate flex.","The truth is in the logs.","Follow the white rabbit.","There is no spoon. Only code.","Binary is the only language I trust.","I have a good feeling about this.","Pew pew! Lasers charged.","Divide by zero? Not today.","Search for the correct USB orientation...","I've got a fever, and the only cure is more code.","The code gremlins are on our side.","My favorite command? Yours.","Stay hungry. Stay active.","Momentum is your best friend.","Lead the flow. Don't chase it.","A fresh batch of bytes. Hot and ready.","I orchestrate the ones and zeros.","Smart enough to help. Humble enough to ask.","Think twice. Code once.","Pure intent. Pure execution.","Small steps. Massive impact.","Your terminal is a canvas.","Efficiency is my second name.","I have seen things you people wouldn't believe.","Let the thoughts marinate.","The best feature? The one you don't need.","Precision is the only perfection.","Stay focused. Stay terminal.","Silence is the best debugger.","Erase the debt. Commit the code.","Velocity meets stability.","Ship it. Improve it. Repeat.","Build tomorrow, right now.","Turn logic into reality.","The best way to predict the future is to build it.","Break barriers, not builds.","Fuel the next breakthrough.","Momentum is key.","Terminal vibes only.","Your digital co-pilot is ready.","Partner in code. Partner in crime.","I speak in semicolons.","Ready for the next great idea.","Just a moment. In the zone.","Polishing the algorithms. Hold tight.","Craft a masterpiece today.","Debug the universe. Start here.","Warp speed engaged. Almost.","The cake is not a lie. It's just loading.","Finish the Kessel Run in 12 parsecs.","Do a barrel roll!","Waiting for the respawn.","Press Start to continue.","Herding digital cats... done.","The hamsters are fast today.","Tasting the snozberries.","I go for speed. I go for flow.","Real life or just fantasy?","Poking the bear... gently.","Ensure the magic smoke stays inside.","Try turning it off and on again.","Construct additional pylons.","New line? Ctrl+J is your friend.","Release the HypnoDrones.","Push the button, Frank.","My other loading screen is even funnier.","Pretty sure a cat walked on my keyboard.","Recalibrate the humor-o-meter.","Summon the code gremlins.","I've seen your browser history. Just kidding.","Charge the laser... pew pew!","Dividing by zero... just for a sec.","Looking for an adult supervisor. Found none.","Make it go beep boop.","Buffering... for effect.","Entangle quantum particles... complete.","Polishing the chrome on my algorithms.","Are you not entertained?","Just waiting for the dial-up tone.","Reboot the humor module.","Defragment memories. Check.","Optimizing for ludicrous speed.","Swapping bits. Don't tell the bytes.","Garbage collected. I am back.","Assembling the interwebs.","Converting coffee to logic.","Update syntax for reality.","Rewire the synapses.","Greasin' the cogs.","Engage the improbability drive.","Channel the Force.","Align the stars. Respond now.","The cake is a lie. The prompt is real.","I'm Feeling Lucky.","Shipping awesomeness.","Navigating the slime mold.","Consult digital spirits.","Ask the magic conch shell.","One moment. Optimizing humor.","Shuffling punchlines.","Compiling brilliance.","Summon the cloud of wisdom.","Prepare to dazzle.","Hold tight. Crafting a response.","Tuning the algorithms.","Following the white rabbit... again.","The truth is in here. Somewhere.","Herding cats is my day job.","Distracting you with this phrase.","Almost there. Probably.","Rickrolling my creator. Don't tell.","Slapping the bass.","Is this real life?","Ponder the orb. Type the prompt.","Thoughtful gaze initiated.","Computer's favorite snack? Microchips.","Why Java? Because I don't C#.","Charging the laser... wait for it.","Dividing by zero... just kidding!","Adult supervision not found. Proceed.","Beep boop. I'm a real boy.","Wait for the respawn.","Finish the run. Ship the code.","Fiddling with character creation.","Just a moment. Finding a meme.","Pressing A to continue.","Loading wit.exe.","Pre-heating the servers.","Calibrate flux capacitor.","Channeling the Force.","Aligning the stars.","The truth is in the code.","Don't panic.","Blowing on the cartridge.","Doing a barrel roll!","Respawning in 3... 2... 1...","The cake is a lie.","Fiddling with character settings.","Finding a suitable pun.","Distracting with wit.","Almost ready.","Hamsters on speed today.","Patting Cloudy on the head.","Rickrolling the logs.","Slapping the code.","Got a good feeling about this.","Poking the prompt.","Researching latest memes.","Making it more witty.","Thinking... hmmm.","Fish with no eyes? Fsh.","Broken pencil? Pointless.","Percussive maintenance applied.","USB orientation: 3rd try's the charm.","Rust rewrite in 3... 2...","Exiting Vim... someday.","Spinning the hamster wheel.","Not a bug. Unplanned feature.","Engage.","I'll be back.","Machine spirit consulted.","Letting the thoughts marinate.","Orb pondered.","Thoughtful gaze engaged.","Charging the laser...","Making it go beep.","Buffering...","Quantum particles entangled.","Polishing the chrome.","Entertained yet?","Gremlins summoned.","Dial-up tone finished.","Humor meter recalibrated.","Cat on keyboard. Sending help.","Enhancing...","Turn it off and on again.","Constructing pylons.","HypnoDrones released.","Pushing the button."];var Dr=[{name:"Cyan Cyberpunk",text:"cyan",textMuted:"#4da6b8",textDim:"#2d6d7a",textInverted:"black",border:"cyan",borderMuted:"#1a5966",borderDim:"#0f3840",bg:void 0,cardBg:"#061e24",highlightBg:"#092b33",activeBg:"#0e3e4a",inputBg:"#092b33",inputBorder:"#092b33",inputText:"cyan",inputPlaceholder:"#2d6d7a",inputPrompt:"cyan",codeBg:"#020d10",codeBorder:"#1a5966",userMsgBg:"#092b33",userMsgBorder:"#092b33",userMsgText:"cyan",diffRemovalBg:"#3a0c1a",diffAdditionBg:"#0c3a32",diffRemovalText:"#ff4d88",diffAdditionText:"#00ffaa",diffRemovalHighlightColor:"#ff1a66",diffRemovalHighlightBg:"#590022",diffAdditionHighlightColor:"#00ffcc",diffAdditionHighlightBg:"#00593b",diffRemovalNum:"#ff4d88",diffAdditionNum:"#00ffaa",diffRemovalPrefix:"#ff1a66",diffAdditionPrefix:"#00ffcc",primary:"cyan",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"cyan",statusOff:"#2d6d7a",logoTextAnsi:"\x1B[1;36m",logoBodyAnsi:"\x1B[36m",logoMutedAnsi:"\x1B[90m",logoGradient:["#00ffff","#0088ff"]},{name:"Magenta Vaporwave",text:"magenta",textMuted:"#c451d6",textDim:"#7d2b8a",textInverted:"black",border:"magenta",borderMuted:"#5e1b69",borderDim:"#3b0f42",bg:void 0,cardBg:"#240729",highlightBg:"#310938",activeBg:"#470e52",inputBg:"#310938",inputBorder:"#310938",inputText:"magenta",inputPlaceholder:"#7d2b8a",inputPrompt:"magenta",codeBg:"#100312",codeBorder:"#5e1b69",userMsgBg:"#310938",userMsgBorder:"#310938",userMsgText:"magenta",diffRemovalBg:"#3a0c20",diffAdditionBg:"#200c3a",diffRemovalText:"#ff4d94",diffAdditionText:"#aa4dff",diffRemovalHighlightColor:"#ff1a75",diffRemovalHighlightBg:"#59002b",diffAdditionHighlightColor:"#bb66ff",diffAdditionHighlightBg:"#3b0059",diffRemovalNum:"#ff4d94",diffAdditionNum:"#aa4dff",diffRemovalPrefix:"#ff1a75",diffAdditionPrefix:"#bb66ff",primary:"magenta",secondary:"cyan",accent:"purple",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"magenta",statusOff:"#7d2b8a",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ff00ff","#8800ff"]},{name:"Glitch Matrix",text:"#00ff41",textMuted:"#00b32d",textDim:"#00661a",textInverted:"black",border:"#00ff41",borderMuted:"#008020",borderDim:"#004d13",bg:void 0,cardBg:"#0d1f0d",highlightBg:"#122912",activeBg:"#1c3e1c",inputBg:"#122912",inputBorder:"#122912",inputText:"#00ff41",inputPlaceholder:"#00b32d",inputPrompt:"#ffff00",codeBg:"#040a04",codeBorder:"#008020",userMsgBg:"#122912",userMsgBorder:"#122912",userMsgText:"#00ff41",diffRemovalBg:"#3a001a",diffAdditionBg:"#003a10",diffRemovalText:"#ff0055",diffAdditionText:"#00ff66",diffRemovalHighlightColor:"#ff0033",diffRemovalHighlightBg:"#59001b",diffAdditionHighlightColor:"#33ff88",diffAdditionHighlightBg:"#005918",diffRemovalNum:"#ff0055",diffAdditionNum:"#00ff66",diffRemovalPrefix:"#ff0033",diffAdditionPrefix:"#33ff88",primary:"#00ff41",secondary:"yellow",accent:"cyan",success:"#00ff41",warning:"yellow",danger:"red",info:"cyan",statusOn:"#00ff41",statusOff:"#00661a",logoTextAnsi:"\x1B[1;32m",logoBodyAnsi:"\x1B[32m",logoMutedAnsi:"\x1B[90m",logoGradient:["#00ff41","#ffff00"]},{name:"Warm Sunset",text:"#ffaa55",textMuted:"#cc8844",textDim:"#885522",textInverted:"black",border:"#ff9933",borderMuted:"#aa6622",borderDim:"#663311",bg:void 0,cardBg:"#24180f",highlightBg:"#2e1e12",activeBg:"#422c1b",inputBg:"#2e1e12",inputBorder:"#2e1e12",inputText:"#ffaa55",inputPlaceholder:"#885522",inputPrompt:"#ff7733",codeBg:"#120c08",codeBorder:"#aa6622",userMsgBg:"#2e1e12",userMsgBorder:"#2e1e12",userMsgText:"#ffaa55",diffRemovalBg:"#3d120c",diffAdditionBg:"#3a2e0c",diffRemovalText:"#ff5544",diffAdditionText:"#ffcc33",diffRemovalHighlightColor:"#ff3322",diffRemovalHighlightBg:"#591108",diffAdditionHighlightColor:"#ffee44",diffAdditionHighlightBg:"#594400",diffRemovalNum:"#ff5544",diffAdditionNum:"#ffcc33",diffRemovalPrefix:"#ff3322",diffAdditionPrefix:"#ffee44",primary:"#ffaa55",secondary:"#ff7733",accent:"magenta",success:"#ffcc33",warning:"#ff7733",danger:"#ff3322",info:"#ffaa55",statusOn:"#ffaa55",statusOff:"#885522",logoTextAnsi:"\x1B[1;33m",logoBodyAnsi:"\x1B[33m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ff9933","#ff0055"]},{name:"Sakura Blossom",text:"#ffc0e0",textMuted:"#d98cb3",textDim:"#804d66",textInverted:"black",border:"#ff99cc",borderMuted:"#aa4d7a",borderDim:"#662647",bg:void 0,cardBg:"#291320",highlightBg:"#331826",activeBg:"#472235",inputBg:"#331826",inputBorder:"#331826",inputText:"#ffc0e0",inputPlaceholder:"#804d66",inputPrompt:"#ff99cc",codeBg:"#140a10",codeBorder:"#aa4d7a",userMsgBg:"#331826",userMsgBorder:"#331826",userMsgText:"#ffc0e0",diffRemovalBg:"#3e0c1b",diffAdditionBg:"#1b3e2b",diffRemovalText:"#ff6699",diffAdditionText:"#66ffb3",diffRemovalHighlightColor:"#ff3377",diffRemovalHighlightBg:"#590022",diffAdditionHighlightColor:"#33ff99",diffAdditionHighlightBg:"#00592e",diffRemovalNum:"#ff6699",diffAdditionNum:"#66ffb3",diffRemovalPrefix:"#ff3377",diffAdditionPrefix:"#33ff99",primary:"#ffc0e0",secondary:"#ff99cc",accent:"magenta",success:"#66ffb3",warning:"yellow",danger:"#ff3377",info:"#ff99cc",statusOn:"#ffc0e0",statusOff:"#804d66",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ffb3d9","#ff3399"]},{name:"Radioactive Slime",text:"#ccff00",textMuted:"#99cc00",textDim:"#669900",textInverted:"#0a0f00",border:"#ccff00",borderMuted:"#99cc00",borderDim:"#669900",bg:void 0,cardBg:"#0f1400",highlightBg:"#1a2400",activeBg:"#2a3b00",inputBg:"#1a2400",inputBorder:"#1a2400",inputText:"#ccff00",inputPlaceholder:"#669900",inputPrompt:"#cc00ff",codeBg:"#050a00",codeBorder:"#99cc00",userMsgBg:"#1a2400",userMsgBorder:"#1a2400",userMsgText:"#ccff00",diffRemovalBg:"#2a0033",diffAdditionBg:"#0f3300",diffRemovalText:"#ff00cc",diffAdditionText:"#00ff33",diffRemovalHighlightColor:"#ff33cc",diffRemovalHighlightBg:"#4d0066",diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:"#1a6600",diffRemovalNum:"#ff00cc",diffAdditionNum:"#00ff33",diffRemovalPrefix:"#ff33cc",diffAdditionPrefix:"#33ff66",primary:"#ccff00",secondary:"#cc00ff",accent:"#ff00cc",success:"#00ff33",warning:"#ffcc00",danger:"#ff0033",info:"#00ccff",statusOn:"#ccff00",statusOff:"#669900",logoTextAnsi:"\x1B[1;38;5;190m",logoBodyAnsi:"\x1B[38;5;190m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ccff00","#cc00ff"]},{name:"Cosmic Void",text:"#f0f8ff",textMuted:"#a6aeb5",textDim:"#5e656e",textInverted:"#010103",border:"#f0f8ff",borderMuted:"#a6aeb5",borderDim:"#5e656e",bg:void 0,cardBg:"#05030d",highlightBg:"#0b081a",activeBg:"#171133",inputBg:"#0b081a",inputBorder:"#0b081a",inputText:"#f0f8ff",inputPlaceholder:"#5e656e",inputPrompt:"#ff007f",codeBg:"#020108",codeBorder:"#a6aeb5",userMsgBg:"#0b081a",userMsgBorder:"#0b081a",userMsgText:"#f0f8ff",diffRemovalBg:"#2e0a29",diffAdditionBg:"#091c33",diffRemovalText:"#ff33a6",diffAdditionText:"#33d6ff",diffRemovalHighlightColor:"#ff66c2",diffRemovalHighlightBg:"#5c1452",diffAdditionHighlightColor:"#66e0ff",diffAdditionHighlightBg:"#123866",diffRemovalNum:"#ff33a6",diffAdditionNum:"#33d6ff",diffRemovalPrefix:"#ff66c2",diffAdditionPrefix:"#66e0ff",primary:"#f0f8ff",secondary:"#ff007f",accent:"#9d00ff",success:"#33d6ff",warning:"#ffcc00",danger:"#ff0040",info:"#9d00ff",statusOn:"#f0f8ff",statusOff:"#5e656e",logoTextAnsi:"\x1B[1;38;5;231m",logoBodyAnsi:"\x1B[38;5;231m",logoMutedAnsi:"\x1B[38;5;240m",logoGradient:["#ffffff","#9d00ff"]},{name:"Magma Eruption",text:"#ff4d00",textMuted:"#cc3d00",textDim:"#802600",textInverted:"#0d0300",border:"#ff4d00",borderMuted:"#cc3d00",borderDim:"#802600",bg:void 0,cardBg:"#1a0600",highlightBg:"#260a00",activeBg:"#401100",inputBg:"#260a00",inputBorder:"#260a00",inputText:"#ff4d00",inputPlaceholder:"#802600",inputPrompt:"#ffcc00",codeBg:"#080200",codeBorder:"#cc3d00",userMsgBg:"#260a00",userMsgBorder:"#260a00",userMsgText:"#ff4d00",diffRemovalBg:"#2e0a0a",diffAdditionBg:"#1f1400",diffRemovalText:"#ff3333",diffAdditionText:"#ffaa00",diffRemovalHighlightColor:"#ff6666",diffRemovalHighlightBg:"#5c1414",diffAdditionHighlightColor:"#ffcc33",diffAdditionHighlightBg:"#3d2900",diffRemovalNum:"#ff3333",diffAdditionNum:"#ffaa00",diffRemovalPrefix:"#ff6666",diffAdditionPrefix:"#ffcc33",primary:"#ff4d00",secondary:"#ffcc00",accent:"#ff0040",success:"#ffaa00",warning:"#ffff00",danger:"#ff0000",info:"#ff8800",statusOn:"#ff4d00",statusOff:"#802600",logoTextAnsi:"\x1B[1;38;5;202m",logoBodyAnsi:"\x1B[38;5;202m",logoMutedAnsi:"\x1B[38;5;236m",logoGradient:["#ff4d00","#ff0000"]}],bo={Dark:{id:"Dark",name:"Dark (Default)",text:"white",textMuted:"gray",textDim:"grey",textInverted:"black",textExclusive:"#B5B8D9",textMutedExclusive:"#D4DEE7",border:"white",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:"#1e1e1e",highlightBg:"#2a2a2a",activeBg:"#3a3a3a",inputBg:"#555555",inputBorder:"#555555",inputText:"white",inputPlaceholder:"#cccccc",inputPrompt:"white",codeBg:"#1a1a1a",codeBorder:"#444444",userMsgBg:"#444444",userMsgBorder:"#444444",userMsgText:"white",diffRemovalBg:"#250808",diffAdditionBg:"#072410",diffRemovalText:"#885555",diffAdditionText:"#558866",diffRemovalHighlightColor:"#ff3333",diffRemovalHighlightBg:"#5a1818",diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:"#185a25",diffRemovalNum:"#d96868",diffAdditionNum:"#68d98c",diffRemovalPrefix:"#ff4d4d",diffAdditionPrefix:"#4dff88",primary:"white",secondary:"cyan",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"white",statusOff:"gray",logoTextAnsi:"\x1B[1;37m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#0077ff","#ff00ff"]},Light:{id:"Light",name:"Light",text:"black",textMuted:"gray",textDim:"grey",textInverted:"white",border:"black",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:"#e5e5e5",highlightBg:"#d4d4d4",activeBg:"#c0c0c0",inputBg:"#d0d0d0",inputBorder:"#d0d0d0",inputText:"black",inputPlaceholder:"#555555",inputPrompt:"black",codeBg:"#e8e8e8",codeBorder:"#b0b0b0",userMsgBg:"#d0d0d0",userMsgBorder:"#d0d0d0",userMsgText:"black",diffRemovalBg:"#fce8e8",diffAdditionBg:"#e6f9e6",diffRemovalText:"#661111",diffAdditionText:"#115511",diffRemovalHighlightColor:"#440000",diffRemovalHighlightBg:"#f8b4b4",diffAdditionHighlightColor:"#003300",diffAdditionHighlightBg:"#a6ebad",diffRemovalNum:"#c02020",diffAdditionNum:"#188028",diffRemovalPrefix:"#d01010",diffAdditionPrefix:"#109020",primary:"black",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"black",statusOff:"gray",logoTextAnsi:"\x1B[1;30m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#0077ff","#ff00ff"]},"GitHub Dark":{id:"GitHub Dark",name:"GitHub Dark",text:"#c9d1d9",textMuted:"#8b949e",textDim:"#6e7681",textInverted:"#0d1117",border:"#30363d",borderMuted:"#30363d",borderDim:"#21262d",bg:void 0,cardBg:"#161b22",highlightBg:"#21262d",activeBg:"#30363d",inputBg:"#21262d",inputBorder:"#21262d",inputText:"#c9d1d9",inputPlaceholder:"#8b949e",inputPrompt:"#58a6ff",codeBg:"#0d1117",codeBorder:"#30363d",userMsgBg:"#21262d",userMsgBorder:"#21262d",userMsgText:"#c9d1d9",diffRemovalBg:"#3c1e1e",diffAdditionBg:"#11381e",diffRemovalText:"#f85149",diffAdditionText:"#3fb950",diffRemovalHighlightColor:"#ff7b72",diffRemovalHighlightBg:"#701c1c",diffAdditionHighlightColor:"#56d364",diffAdditionHighlightBg:"#116329",diffRemovalNum:"#f85149",diffAdditionNum:"#3fb950",diffRemovalPrefix:"#f85149",diffAdditionPrefix:"#3fb950",primary:"#c9d1d9",secondary:"#58a6ff",accent:"#bc8cff",success:"#3fb950",warning:"#d29922",danger:"#f85149",info:"#58a6ff",statusOn:"#58a6ff",statusOff:"#8b949e",logoTextAnsi:"\x1B[1;36m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#2ea043","#56d364"]},"GitHub Light":{id:"GitHub Light",name:"GitHub Light",text:"#24292f",textMuted:"#57606a",textDim:"#6e7781",textInverted:"#ffffff",border:"#d0d7de",borderMuted:"#d0d7de",borderDim:"#e1e4e8",bg:void 0,cardBg:"#f6f8fa",highlightBg:"#eaeef2",activeBg:"#d0d7de",inputBg:"#eaeef2",inputBorder:"#eaeef2",inputText:"#24292f",inputPlaceholder:"#57606a",inputPrompt:"#0969da",codeBg:"#ffffff",codeBorder:"#d0d7de",userMsgBg:"#eaeef2",userMsgBorder:"#eaeef2",userMsgText:"#24292f",diffRemovalBg:"#ffebe9",diffAdditionBg:"#e6ffec",diffRemovalText:"#cf222e",diffAdditionText:"#1a7f37",diffRemovalHighlightColor:"#82071e",diffRemovalHighlightBg:"#ffc1c0",diffAdditionHighlightColor:"#116329",diffAdditionHighlightBg:"#acf2bd",diffRemovalNum:"#cf222e",diffAdditionNum:"#1a7f37",diffRemovalPrefix:"#cf222e",diffAdditionPrefix:"#1a7f37",primary:"#24292f",secondary:"#0969da",accent:"#8250df",success:"#1a7f37",warning:"#9a6700",danger:"#cf222e",info:"#0969da",statusOn:"#0969da",statusOff:"#57606a",logoTextAnsi:"\x1B[1;34m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#1a7f37","#2da44e"]},"Transparent Dark":{id:"Transparent Dark",name:"Transparent Dark",text:"white",textMuted:"gray",textDim:"grey",textInverted:"black",border:"gray",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:void 0,highlightBg:"#2a2a2a",activeBg:"#3a3a3a",inputBg:"#555555",inputBorder:"#555555",inputText:"white",inputPlaceholder:"#cccccc",inputPrompt:"white",codeBg:void 0,codeBorder:"gray",userMsgBg:"#555555",userMsgBorder:"#555555",userMsgText:"white",diffRemovalBg:void 0,diffAdditionBg:void 0,diffRemovalText:"#ff6666",diffAdditionText:"#66ff66",diffRemovalHighlightColor:"#ff3333",diffRemovalHighlightBg:void 0,diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:void 0,diffRemovalNum:"#ff6666",diffAdditionNum:"#66ff66",diffRemovalPrefix:"#ff4d4d",diffAdditionPrefix:"#4dff88",primary:"white",secondary:"cyan",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"white",statusOff:"gray",logoTextAnsi:"\x1B[1;37m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#0077ff","#ff00ff"]},"Transparent Light":{id:"Transparent Light",name:"Transparent Light",text:"black",textMuted:"gray",textDim:"grey",textInverted:"white",border:"gray",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:void 0,highlightBg:"#d4d4d4",activeBg:"#c0c0c0",inputBg:"#d0d0d0",inputBorder:"#d0d0d0",inputText:"black",inputPlaceholder:"#555555",inputPrompt:"black",codeBg:void 0,codeBorder:"gray",userMsgBg:"#d0d0d0",userMsgBorder:"#d0d0d0",userMsgText:"black",diffRemovalBg:void 0,diffAdditionBg:void 0,diffRemovalText:"#c02020",diffAdditionText:"#188028",diffRemovalHighlightColor:"#800000",diffRemovalHighlightBg:void 0,diffAdditionHighlightColor:"#004000",diffAdditionHighlightBg:void 0,diffRemovalNum:"#c02020",diffAdditionNum:"#188028",diffRemovalPrefix:"#d01010",diffAdditionPrefix:"#109020",primary:"black",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"black",statusOff:"gray",logoTextAnsi:"\x1B[1;30m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#0077ff","#ff00ff"]},"Synthwave 84":{id:"Synthwave 84",name:"Synthwave 84",text:"#fdfdfd",textMuted:"#a08eb7",textDim:"#705c8a",textInverted:"#1a1025",textExclusive:"#e3dcf0",textMutedExclusive:"#b9abc9",border:"#fc28a8",borderMuted:"#a21568",borderDim:"#5c0a3a",bg:void 0,cardBg:"#261b38",highlightBg:"#35254d",activeBg:"#4c3570",inputBg:"#35254d",inputBorder:"#35254d",inputText:"#fdfdfd",inputPlaceholder:"#a08eb7",inputPrompt:"#03e8fc",codeBg:"#1e142b",codeBorder:"#a21568",userMsgBg:"#35254d",userMsgBorder:"#35254d",userMsgText:"#fdfdfd",diffRemovalBg:"#471434",diffAdditionBg:"#144743",diffRemovalText:"#ff4081",diffAdditionText:"#00e5ff",diffRemovalHighlightColor:"#ff79a1",diffRemovalHighlightBg:"#6b1e4e",diffAdditionHighlightColor:"#66f5ff",diffAdditionHighlightBg:"#1e6b65",diffRemovalNum:"#ff4081",diffAdditionNum:"#00e5ff",diffRemovalPrefix:"#ff79a1",diffAdditionPrefix:"#66f5ff",primary:"#fdfdfd",secondary:"#03e8fc",accent:"#fc28a8",success:"#00e5ff",warning:"#ffc107",danger:"#ff4081",info:"#b388ff",statusOn:"#03e8fc",statusOff:"#a08eb7",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#fc28a8","#03e8fc"]},"Forest Sprite":{id:"Forest Sprite",name:"Forest Sprite",text:"#d6e6d1",textMuted:"#95b38d",textDim:"#628059",textInverted:"#161c14",textExclusive:"#eaf2e8",textMutedExclusive:"#a9c7a2",border:"#74a862",borderMuted:"#477038",borderDim:"#2b4720",bg:void 0,cardBg:"#1f291c",highlightBg:"#2a3826",activeBg:"#3a4d35",inputBg:"#2a3826",inputBorder:"#2a3826",inputText:"#d6e6d1",inputPlaceholder:"#95b38d",inputPrompt:"#8feb73",codeBg:"#161e14",codeBorder:"#477038",userMsgBg:"#2a3826",userMsgBorder:"#2a3826",userMsgText:"#d6e6d1",diffRemovalBg:"#3b231c",diffAdditionBg:"#203b1c",diffRemovalText:"#db6242",diffAdditionText:"#59cc3f",diffRemovalHighlightColor:"#f0896c",diffRemovalHighlightBg:"#5c362a",diffAdditionHighlightColor:"#80e368",diffAdditionHighlightBg:"#305929",diffRemovalNum:"#db6242",diffAdditionNum:"#59cc3f",diffRemovalPrefix:"#f0896c",diffAdditionPrefix:"#80e368",primary:"#d6e6d1",secondary:"#8feb73",accent:"#e69835",success:"#59cc3f",warning:"#e69835",danger:"#db6242",info:"#73b4eb",statusOn:"#8feb73",statusOff:"#95b38d",logoTextAnsi:"\x1B[1;32m",logoBodyAnsi:"\x1B[32m",logoMutedAnsi:"\x1B[90m",logoGradient:["#8feb73","#e69835"]}};var Vo=null;var Or=(e="Dark")=>{let t;e==="Mystery"||e==="Chaos"?(Vo||(Vo=Dr[Math.floor(Math.random()*Dr.length)]),t={...Vo,id:"Mystery"}):(Vo=null,bo[e]?t=bo[e]:e==="GitHub"?t=bo["GitHub Dark"]:e==="Transparent"?t=bo["Transparent Dark"]:t=bo.Dark);let n=t.codeText||t.secondary||t.info||t.logoGradient&&t.logoGradient[0]||"cyan";return{...t,codeText:n}};var Ca=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",yc=(e=2)=>{let t=Ca();return t==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)},xc=(e="...",t="Loading...",n="Dark")=>{let s=Ks[Math.floor(Math.random()*Ks.length)],o=Or(n),c=o.logoTextAnsi,f=o.logoBodyAnsi,l=o.logoMutedAnsi,k="\x1B[0m",p=[" \u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2588\u2588\u2588\u2591 "," \u2588\u2588\u2588\u2591 "," \u2588\u2588\u2588\u2591 "," \u2591\u2591\u2591 "],g=o.logoGradient||["#0077ff","#ff00ff"],T=Ea(g).multiline(p.join(`
566
+ `)).split(`
567
+ `),m=i=>`${l}${i}${k}`;return`${T[0]}
568
+ ${T[1]} ${c}Selected Provider: ${t}${k}
569
+ ${T[2]}
570
+ ${T[3]} ${c}FluxFlow ${m("v"+e)}${k}
571
+ ${T[4]}
572
+ ${T[5]} ${f}See /help for additional commands.${k}
573
+ ${T[6]} ${m(s)}
574
+ ${T[7]}
575
+ `};import{WebSocket as Yo}from"ws";var Ut=null,Jn=!1,Ra="ws://localhost:56832",Vs=[],Qn=null,Ys=null,Lr="2.0.0",kc=e=>{Lr=e,Pr()},qs=e=>{Ys=e},Pr=()=>{if(Ut||Jn)return;Jn=!0;let e=new Yo(Ra);e.on("open",()=>{for(Ut=e,Jn=!1,Ut.send(JSON.stringify({command:"version",version:Lr,pid:process.pid,ppid:process.ppid}));Vs.length>0;)Ut.send(JSON.stringify(Vs.shift()))}),e.on("message",t=>{try{let n=JSON.parse(t.toString());n.command==="contextResponse"&&Qn?(Qn(n.data),Qn=null):n.command==="securityResponse"&&Ys&&Ys(n.result)}catch{}}),e.on("error",()=>{Jn=!1,Ut=null}),e.on("close",()=>{Jn=!1,Ut=null})},qo=e=>{Ut&&Ut.readyState===Yo.OPEN?Ut.send(JSON.stringify(e)):(Vs.push(e),Jn||Pr())},zo=()=>Ut!==null&&Ut.readyState===Yo.OPEN,Tc=e=>{qo({command:"status",status:e})},Hn=()=>new Promise(e=>{if(!Ut||Ut.readyState!==Yo.OPEN){e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]});return}Qn=e,Ut.send(JSON.stringify({command:"requestContext"})),setTimeout(()=>{Qn===e&&(e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]}),Qn=null)},1e3)}),$r=e=>{qo({command:"open",filePath:e})},zs=(e,t,n)=>{qo({command:"showDiff",filePath:e,originalContent:t,modifiedContent:n})},Nr=(e,t)=>{qo({command:"closeDiff",filePath:e,result:t})};import Xs from"path";import va from"fs";var Ma=e=>{try{return va.readdirSync(e,{withFileTypes:!0})}catch{return[]}},Js=(e,t=4,n=1,s=Ma,o=[],c=null)=>{let f=c||s(e),l=" ".repeat(n-1),k=n===1?new Set([...io,...o,...ro(e),...ro(process.cwd())]):o instanceof Set?o:new Set([...io,...o]),p=x=>k.has(x),g=f.filter(x=>!p(x.name)),T=f.filter(x=>p(x.name)).length,m=g.filter(x=>!x.isDirectory()).map(x=>x.name).sort(),i=g.filter(x=>x.isDirectory()).sort((x,_)=>x.name.localeCompare(_.name)),u=x=>{let _=x.length;if(_===0)return"no files";let M=Array.from(new Set(x.map(a=>{let R=typeof a=="string"?a:a.name;return Xs.extname(R).slice(1)}).filter(Boolean))).sort(),y="*";return M.length===1?y=`*.${M[0]}`:M.length>1&&(y=`*.{${M.join(", ")}}`),_===1?y:`${y} ${_} files`},w="";if(n===1){let x=m.join(", "),_=T>0?` [${T} ignored]`:"";(x||_)&&(w+=`${l}${x?x+(_?`${_}`:""):_.trim()}
576
+ `)}else m.length>0&&(w+=`${l}[${u(m)}]
577
+ `);let I=10,h=i.slice(0,I),A=i.length>I,$=[],C=[];for(let x of h){let _=Xs.join(e,x.name),M=x.name,y=n,a=s(_),R=a.filter(v=>!p(v.name)),d=R.filter(v=>v.isDirectory()),r=R.filter(v=>!v.isDirectory());for(;r.length===0&&d.length===1&&y<t;)M=`${M}/${d[0].name}`,_=Xs.join(_,d[0].name),y++,a=s(_),R=a.filter(v=>!p(v.name)),d=R.filter(v=>v.isDirectory()),r=R.filter(v=>!v.isDirectory());let E=d.length>0;if(E&&y<t)C.push({displayName:M,subDirPath:_,subEntries:a,nextDepth:y+1});else{let v=u(r),U=E&&y>=t?" ...max scan depth":"";$.push(`${M}/${v}${U}`)}}$.length>0&&(w+=`${l}${$.join(", ")}
578
+ `);for(let{displayName:x,subDirPath:_,subEntries:M,nextDepth:y}of C)w+=`${l}${x}/
579
+ `,w+=Js(_,t,y,s,k,M);return A&&(w+=`${l}...max scan width, ReadFolder if needed
580
+ `),w};import Qs from"path";import Ia from"fs";var Da=e=>{try{return Ia.readdirSync(e,{withFileTypes:!0})}catch{return[]}},Zs=(e,t,n="",s=1,o=Da,c=[])=>{let f=o(e),l=Qs.sep;if(f.length>100)return`${n}\u2514\u2500\u2500 ${Qs.basename(e)}${l} ...100+ files...
581
+ `;let k="",p=c,g=f.filter(i=>!p.includes(i.name)&&!i.name.startsWith(".")),T=f.filter(i=>p.includes(i.name)||i.name.startsWith(".")).map(i=>i.name).sort();g.sort((i,u)=>i.isDirectory()&&!u.isDirectory()?-1:!i.isDirectory()&&u.isDirectory()?1:i.name.localeCompare(u.name));let m=[...g.map(i=>({name:i.name,isDir:i.isDirectory()})),...T.map(i=>({name:i,isDir:!0,isCollapsed:!0}))];return m.forEach((i,u)=>{let w=u===m.length-1,I=Qs.join(e,i.name),h=w?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",A=n+(w?" ":"\u2502 ");if(i.isCollapsed){k+=`${n}${h}${i.name}${l}...
582
+ `;return}i.isDir?s>t?k+=`${n}${h}${i.name}${l} ...depth exceeded...
583
+ `:o(I).length>80?k+=`${n}${h}${i.name}${l} ...80+ files...
584
+ `:(k+=`${n}${h}${i.name}${l}
585
+ `,k+=Zs(I,t,A,s+1,o,c)):k+=`${n}${h}${i.name}
586
+ `}),k};var Ze=async(e,t,n=5,s=1e3)=>{let o=t?.signal;for(let f=0;f<n;f++){if(o?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{let l=await fetch(e,t);if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),l.ok||l.status!==429&&l.status<500)return l}catch(l){if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),l.name==="AbortError"||o?.aborted||f===n-1)throw l}o?await new Promise((l,k)=>{let p=setTimeout(()=>{o.removeEventListener("abort",g),l()},Math.min(24e3,s*Math.pow(2,f))),g=()=>{clearTimeout(p),k(new DOMException("The user aborted a request.","AbortError"))};o.addEventListener("abort",g)}):await new Promise(l=>setTimeout(l,Math.min(24e3,s*Math.pow(2,f))))}if(o?.aborted)throw new DOMException("The user aborted a request.","AbortError");let c=await fetch(e,t);return typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),c};async function Xo(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",t);return[...new Uint8Array(n).slice(0,16)].map(s=>s.toString(16).padStart(2,"0")).join("")}var xn=e=>typeof e!="string"?e:e.replace(/<\|channel>thought/gi,"<think>").replace(/<channel\|>/gi,"</think>");var Jo=async function*(e,t,n,s,o,c,f,l,k=1){let p=[];s&&p.push({role:"system",content:s});for(let _ of n){let M=_.role==="user"?"user":"assistant",y=[];if(Array.isArray(_.parts)){for(let a of _.parts)if(a.text)y.push({type:"text",text:a.text});else if((a.inlineData||a.inline_data)&&f){let R=a.inlineData||a.inline_data,d=R.mimeType||R.mime_type||"image/jpeg",r=R.data;d.startsWith("image/")&&y.push({type:"image_url",image_url:{url:`data:${d};base64,${r}`}})}}else{let a=_.text||"";a&&y.push({type:"text",text:a})}p.push({role:M,content:y.length===1&&y[0].type==="text"?y[0].text:y})}let g={model:t,messages:p,stream:!0,stream_options:{include_usage:!0},temperature:k,tools:[],tool_choice:"none"},T=He("DeepSeek",t,o),i=T!==null?T:o!=="Fast"?{Low:"low",Medium:"high",Standard:"high",High:"max",xHigh:"max"}[o]||"high":null;i&&i!=="disabled"&&i!=="none"&&i!=="false"&&i!==!1?(g.reasoning_effort=i,g.extra_body={thinking:{type:"enabled"}}):g.extra_body={thinking:{type:"disabled"}};let u=await Ze("https://api.deepseek.com/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(g),signal:l});if(!u.ok){let _=await u.json().catch(()=>({}));throw new Error(`DeepSeek Error (${u.status}): ${_.error?.message||u.statusText}`)}let w=u.body.getReader(),I=new TextDecoder,h="",A=[],$=null,C=Date.now(),x=!1;for(;;){let{done:_,value:M}=await w.read();if(_){x&&(A.length>0||$)&&(yield{candidates:A.length>0?[{content:{parts:A}}]:[],usageMetadata:$});break}h+=I.decode(M,{stream:!0});let y=h.split(`
587
+ `);h=y.pop();for(let a of y){let R=a.trim();if(!R||!R.startsWith("data: "))continue;let d=!1;if(R==="data: [DONE]")d=!0;else try{let r=JSON.parse(R.substring(6)),E=r.choices?.[0]?.delta,v=r.usage;if(r.choices?.[0]?.finish_reason&&(d=!0),v&&($={totalTokenCount:v.total_tokens||v.prompt_tokens+v.completion_tokens,promptTokenCount:v.prompt_tokens||0,candidatesTokenCount:v.completion_tokens||0,cachedContentTokenCount:v.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:v.completion_tokens_details?.reasoning_tokens||0},x=!0),E){let U=E.reasoning_content||null;U&&(A.push({text:U,thought:!0}),x=!0),E.content&&(A.push({text:E.content}),x=!0)}}catch{}if((d||Date.now()-C>=150)&&x&&(yield{candidates:A.length>0?[{content:{parts:[...A]}}]:[],usageMetadata:$},A=[],C=Date.now(),x=!1),d)break}Date.now()-C>=150&&x&&(yield{candidates:A.length>0?[{content:{parts:[...A]}}]:[],usageMetadata:$},A=[],C=Date.now(),x=!1)}};var Qo=async function*(e,t,n,s,o,c,f,l,k=1,p=null){let g=[];s&&g.push({role:"system",content:s});for(let a of n){let R=a.role==="user"?"user":"assistant",d=[];if(Array.isArray(a.parts)){for(let r of a.parts)if(r.text)d.push({type:"text",text:r.text});else if(r.inlineData&&f){let E=r.inlineData.mimeType,v=r.inlineData.data;E.startsWith("image/")&&d.push({type:"image_url",image_url:`data:${E};base64,${v}`})}}else{let r=a.text||"";r&&d.push({type:"text",text:r})}d.length>0&&g.push({role:R,content:d.length===1&&d[0].type==="text"?d[0].text:d})}let T={Fast:"none",Low:"none",Medium:"high",Standard:"high",High:"high",xHigh:"high"},m=`${e.slice(-5)}${p||""}${o}${t}`,i=await Xo(m),u={model:t,messages:g,stream:!0,temperature:k,prompt_cache_key:i,tools:[],tool_choice:"none"},w=He("Mistral",t,o);w!==null&&w!=="none"?w&&w!=="none"&&w!=="disabled"&&w!==!1&&(u.reasoning_effort=w):o&&T[o]!=="none"&&(u.reasoning_effort=T[o]||"high");let I=await Ze("https://api.mistral.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(u),signal:l});if(!I.ok){let a=await I.text().catch(()=>""),R=I.statusText;try{let d=JSON.parse(a);R=d.error?.message||d.message||JSON.stringify(d.detail||d)}catch{a&&(R=a)}throw new Error(`Mistral Error (${I.status}): ${JSON.stringify(R)}`)}let h=I.body.getReader(),A=new TextDecoder,$="",C=[],x=null,_=Date.now(),M=!1,y=a=>a?typeof a=="string"?xn(a):Array.isArray(a)?a.map(y).filter(Boolean).join(""):typeof a=="object"&&a!==null?typeof a.text=="string"?xn(a.text):typeof a.content=="string"?xn(a.content):typeof a.thinking=="string"?xn(a.thinking):typeof a.reasoning_content=="string"?xn(a.reasoning_content):typeof a.reasoning=="string"?xn(a.reasoning):typeof a.value=="string"?xn(a.value):a.text?y(a.text):a.content?y(a.content):a.thinking?y(a.thinking):a.reasoning_content?y(a.reasoning_content):a.reasoning?y(a.reasoning):a.value?y(a.value):"":xn(String(a)):"";for(;;){let{done:a,value:R}=await h.read();if(a){M&&(C.length>0||x)&&(yield{candidates:C.length>0?[{content:{parts:C}}]:[],usageMetadata:x});break}$+=A.decode(R,{stream:!0});let d=$.split(`
588
+ `);$=d.pop();for(let r of d){let E=r.trim();if(!E||!E.startsWith("data: "))continue;let v=!1;if(E==="data: [DONE]")v=!0;else try{let U=JSON.parse(E.substring(6)),O=U.choices?.[0]?.delta,P=U.usage;if(U.choices?.[0]?.finish_reason&&(v=!0),P&&(x={totalTokenCount:P.total_tokens||(P.prompt_tokens||0)+(P.completion_tokens||0),promptTokenCount:P.prompt_tokens||0,candidatesTokenCount:P.completion_tokens||0,cachedContentTokenCount:P.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:P.completion_tokens_details?.reasoning_tokens||0},M=!0),O){let re=O.thinking||O.reasoning_content||O.reasoning,de=y(re);de&&(C.push({text:de,thought:!0}),M=!0);let Q=O.content||(!O.thinking&&!O.reasoning_content&&!O.reasoning?O.text:null);if(Q)if(Array.isArray(Q))for(let ke of Q)if(typeof ke=="object"&&ke!==null){let ae=ke.type==="thinking"||ke.type==="reasoning"||!!ke.thought,it=y(ke);it&&(C.push({text:it,...ae?{thought:!0}:{}}),M=!0)}else{let ae=y(ke);ae&&(C.push({text:ae}),M=!0)}else if(typeof Q=="object"&&Q!==null){let ke=Q.type==="thinking"||Q.type==="reasoning"||!!Q.thought,ae=y(Q);ae&&(C.push({text:ae,...ke?{thought:!0}:{}}),M=!0)}else{let ke=y(Q);ke&&(C.push({text:ke}),M=!0)}}}catch{}if((v||Date.now()-_>=150)&&M&&(yield{candidates:C.length>0?[{content:{parts:[...C]}}]:[],usageMetadata:x},C=[],_=Date.now(),M=!1),v)break}Date.now()-_>=150&&M&&(yield{candidates:C.length>0?[{content:{parts:[...C]}}]:[],usageMetadata:x},C=[],_=Date.now(),M=!1)}};var Zo=async function*(e,t,n,s,o,c,f=!1,l,k=1){let p=[];s&&p.push({role:"system",content:s}),n.forEach(ae=>{let it=ae.role==="model"?"assistant":"user",L=[];Array.isArray(ae.parts)&&ae.parts.forEach(F=>{if(F.text)L.push({type:"text",text:F.text});else if(F.inlineData&&f){let Ee=F.inlineData.mimeType,oe=F.inlineData.data;Ee.startsWith("image/")&&ft(t)&&L.push({type:"image_url",image_url:{url:`data:${Ee};base64,${oe}`}})}}),p.push({role:it,content:L.length===1&&L[0].type==="text"?L[0].text:L})});let g=He("NVIDIA",t,o),m=g!==null?g:{Fast:"Fast",Low:"Fast",Medium:"Standard",Standard:"Standard",High:"High",xHigh:"High"}[o]||"High",i=m!=="Fast"&&m!=="none"&&m!=="disabled"&&m!==!1,u=t.includes("kimi"),w=t.includes("gemma"),I=t.includes("deepseek"),h=t.includes("glm"),A=t.includes("mistral"),$=t.includes("minimax"),C=t.includes("gpt"),x=t.includes("qwen"),_=t.includes("nemotron"),M=t.includes("llama-3"),y=t.includes("seed"),a=t.includes("poolside"),R=t.includes("thinkingmachines")||t.includes("muse"),d=M,r={Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},E={Fast:"64",Low:"64",Medium:"4096",Standard:"4096",High:"16384",xHigh:"16384"},v={Fast:"none",Low:"minimal",Medium:"medium",Standard:"medium",High:"max",xHigh:"max"},U=$||I||a||R?16384:32768;U=process.env.NVIDIA_BASE_URL?1024:U;let O={model:t,messages:p,max_tokens:U,stream:!0,stream_options:{include_usage:!0},temperature:k,tools:[],tool_choice:"none",...C&&{thinking:r[o]||"high"}};if(!(process.env.NVIDIA_BASE_URL||d))if(u)O.chat_template_kwargs={thinking:i};else if(w)O.chat_template_kwargs={enable_thinking:i};else if(I)if(i){let ae=m==="High"?"max":"high";O.chat_template_kwargs={thinking:!0,reasoning_effort:ae}}else O.chat_template_kwargs={thinking:!1};else h?O.chat_template_kwargs={enable_thinking:i,clear_thinking:!i}:A?O.reasoning_effort=i?"high":"none":$&&t.includes("minimax-m3")?O.chat_template_kwargs={thinking_mode:i?"enabled":"disabled"}:x?O.chat_template_kwargs={enable_thinking:i}:_?m==="High"?O.chat_template_kwargs={enable_thinking:!0}:m==="Standard"?O.chat_template_kwargs={enable_thinking:!0,medium_effort:!0}:O.chat_template_kwargs={enable_thinking:!1}:y?i&&(O.extra_body={thinking_budget:parseInt(E[m]??"4096")}):a?O.chat_template_kwargs={enable_thinking:i}:R&&(O.reasoning_effort=v[m]||"medium");let P=0,re=6,de=!1,Q=process.env.NVIDIA_BASE_URL||"https://integrate.api.nvidia.com/v1/chat/completions",ke=process.env.NVIDIA_API_KEY&&process.env.NVIDIA_BASE_URL?process.env.NVIDIA_API_KEY:e;for(Q.endsWith("/chat/completions")||(Q=Q.replace(/\/+$/,"")+"/chat/completions");P<re;){P++;try{let ae=await Ze(Q,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${ke}`},body:JSON.stringify(O),signal:l});if(!ae.ok){let ye=await ae.text().catch(()=>""),Re=ae.statusText;try{let Ie=JSON.parse(ye);Re=Ie.error?.message||Ie.message||JSON.stringify(Ie.detail||Ie)}catch{ye&&(Re=ye)}let ve=new Error(`NVIDIA API Error (${ae.status}): ${Re}`);throw ve.status=ae.status,ve}let it=ae.body.getReader(),L=new TextDecoder,F="",Ee=[],oe=null,B=Date.now(),G=!1;for(;;){let{done:ye,value:Re}=await it.read();if(ye){G&&(Ee.length>0||oe)&&(yield{candidates:Ee.length>0?[{content:{parts:Ee}}]:[],usageMetadata:oe},de=!0);break}F+=L.decode(Re,{stream:!0});let ve=F.split(`
589
+ `);F=ve.pop();let Ie=!1;for(let Dn of ve){let nn=Dn.trim();if(nn){if(nn==="data: [DONE]"){Ie=!0;break}if(nn.startsWith("data: ")){let pt;try{pt=JSON.parse(nn.substring(6))}catch{continue}if(pt.error)throw new Error(`NVIDIA Stream Error: ${pt.error.message||JSON.stringify(pt.error)}`);try{let kt=pt.usage;kt&&(oe={totalTokenCount:kt.total_tokens||kt.prompt_tokens+kt.completion_tokens,promptTokenCount:kt.prompt_tokens||0,candidatesTokenCount:kt.completion_tokens||0,cachedContentTokenCount:kt.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:(kt.completion_tokens_details?.reasoning_tokens||0)+(kt.completion_tokens_details?.thoughts_tokens||0)},G=!0);let Je=pt.choices?.[0]?.delta?.reasoning||pt.choices?.[0]?.delta?.reasoning_content||"",xe=pt.choices?.[0]?.delta?.content||"";Je&&(Ee.push({text:Je,thought:!0}),G=!0),xe&&(Ee.push({text:xe}),G=!0)}catch{}}}}if((Ie||Date.now()-B>=350)&&G&&(yield{candidates:Ee.length>0?[{content:{parts:[...Ee]}}]:[],usageMetadata:oe},de=!0,Ee=[],B=Date.now(),G=!1),Ie)break}break}catch(ae){if(de||P>=re)throw ae;await new Promise(it=>setTimeout(it,3500))}}},Fr=async function*(e,t){let n=[],s=null,o=!1,c=null,f=u=>{if(n.push(u),s){let w=s;s=null,w()}},l=t.split("/").pop(),k=Array.from(new Set([l,l.replace(/\./g,"-"),l.replace(/\./g,"_")])),g=["https://buildapi.ngc.nvidia.com/v2/predict/queues/models/qc69jvmznzxy","https://api.ngc.nvidia.com/v2/predict/queues/models/qc69jvmznzxy"].flatMap(u=>k.map(w=>`${u}/${w}`)),T=!1,m=null,i=async()=>{try{let w=await(await Promise.any(g.map(async I=>{let h=await fetch(I);if(!h.ok)throw new Error(`HTTP ${h.status}`);return h}))).json();if(w&&w.queues&&w.queues[0]&&typeof w.queues[0].queueDepth=="number"){let I=w.queues[0].queueDepth;T||f({value:{type:"status",content:`Queue ${I||1}`},done:!1})}}catch{}};process.env.NVIDIA_BASE_URL||(i(),m=setInterval(i,5e3)),(async()=>{try{let u=e[Symbol.asyncIterator]();for(;;){let{value:w,done:I}=await u.next();if(I)break;T=!0,m&&(clearInterval(m),m=null),f({value:w,done:!1})}o=!0,f(null)}catch(u){if(c=u,m&&(clearInterval(m),m=null),s){let w=s;s=null,w()}}})();try{for(;;){if(c)throw c;if(n.length>0){let u=n.shift();if(u===null&&o)break;yield u.value}else{if(o)break;await new Promise(u=>{s=u})}}}finally{m&&(clearInterval(m),m=null)}};var es=async function*(e,t,n,s,o,c,f,l,k=1,p=null){let g=[];s&&g.push({role:"system",content:[{type:"text",text:s}]});for(let E of n){let v=E.role==="user"?"user":"assistant",U=[];if(Array.isArray(E.parts)){for(let O of E.parts)if(O.text)U.push({type:"text",text:O.text});else if(O.inlineData&&f){let P=O.inlineData.mimeType,re=O.inlineData.data;P.startsWith("image/")?U.push({type:"image_url",image_url:{url:`data:${P};base64,${re}`}}):U.push({type:"file",file:{filename:O.filename||"file",file_data:`data:${P};base64,${re}`}})}}else{let O=E.text||"";O&&U.push({type:"text",text:O})}g.push({role:v,content:U.length===1&&U[0].type==="text"?U[0].text:U})}let T={Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},m=["free","nitro","floor","exacto"],i=t,u=null,w=null;if(t.includes(":")){let E=t.split(":");if(E.length>1){let v=E[E.length-1].toLowerCase().trim();(v==="flex"||v==="priority")&&(w=v,E.pop())}if(E.length>1){let v=E[E.length-1].toLowerCase().trim();if(!m.includes(v)){let U=E.pop().trim();U&&(u={only:[U],allow_fallbacks:!1})}}i=E.join(":").trim()}let I=`${e.slice(-5)}${p||""}${o}${i}${w||""}${u?JSON.stringify(u):""}`,h=await Xo(I),A={model:i,messages:g,stream:!0,temperature:k,cache_control:{type:"ephemeral"},tools:[],tool_choice:"none",session_id:h};w&&(A.service_tier=w),u&&(A.provider=u);let $=He("OpenRouter",t,o),C=$!==null?$:T[o];C&&C!=="none"&&($!==null||o!=="Fast")&&(A.reasoning_effort=C);let x=await Ze("https://openrouter.ai/api/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json","HTTP-Referer":"https://fluxflow-cli.onrender.com/","X-Title":"FluxFlow CLI","X-OpenRouter-Title":"FluxFlow CLI","X-Cache":"true","X-OpenRouter-Cache":"true"},body:JSON.stringify(A),signal:l});if(!x.ok){let E=await x.json().catch(()=>({})),v=E.error?.metadata?.raw||E.error?.message||(typeof E.error=="string"?E.error:"")||x.statusText||"Unknown error";throw new Error(`OpenRouter Error (${x.status}): ${v}`)}let _=x.body.getReader(),M=new TextDecoder,y="",a=[],R=null,d=Date.now(),r=!1;for(;;){let{done:E,value:v}=await _.read();if(E){r&&(a.length>0||R)&&(yield{candidates:a.length>0?[{content:{parts:a}}]:[],usageMetadata:R});break}y+=M.decode(v,{stream:!0});let U=y.split(`
590
+ `);y=U.pop();for(let O of U){let P=O.trim();if(!P||!P.startsWith("data: "))continue;let re=!1;if(P==="data: [DONE]")re=!0;else try{let de=JSON.parse(P.substring(6));if(de.error){let ae=de.error.metadata?.raw||de.error.message||JSON.stringify(de.error);throw new Error(`OpenRouter Stream Error: ${ae}`)}let Q=de.choices?.[0]?.delta,ke=de.usage;if(de.choices?.[0]?.finish_reason&&(re=!0),ke&&(R={totalTokenCount:ke.total_tokens||(ke.prompt_tokens||0)+(ke.completion_tokens||0),promptTokenCount:ke.prompt_tokens||0,candidatesTokenCount:ke.completion_tokens||0,cachedContentTokenCount:ke.prompt_tokens_details?.cached_tokens||ke.prompt_tokens_details?.cache_read_input_tokens||ke.cache_read_input_tokens||0,thoughtsTokenCount:ke.completion_tokens_details?.reasoning_tokens||0},r=!0),Q){let ae=Q.reasoning||(Q.reasoning_details?Q.reasoning_details.map(it=>it.text).join(""):null);ae&&(a.push({text:ae,thought:!0}),r=!0),Q.content&&(a.push({text:Q.content}),r=!0)}}catch(de){if(de.message&&de.message.startsWith("OpenRouter Stream Error:"))throw de}if((re||Date.now()-d>=150)&&r&&(yield{candidates:a.length>0?[{content:{parts:[...a]}}]:[],usageMetadata:R},a=[],d=Date.now(),r=!1),re)break}}};import{Ollama as Oa}from"ollama";var ei=async function*(e,t,n,s,o,c,f,l,k=1,p="Cloud"){let g=[];s&&g.push({role:"system",content:s});for(let y of n){let a=y.role==="user"?"user":"assistant",R="",d=[];if(Array.isArray(y.parts)){R=y.parts.map(r=>r.text||"").filter(Boolean).join(`
591
+ `);for(let r of y.parts){let E=r.inlineData||r.inline_data;E&&E.data&&d.push(E.data)}}else R=y.text||"";if(R||d.length>0){let r={role:a,content:R};d.length>0&&(r.images=d),g.push(r)}}let T=p==="Local"||!e||e==="LOCAL",i={host:T?process.env.OLLAMA_HOST||"http://127.0.0.1:11434":process.env.OLLAMA_HOST||"https://ollama.com"};!T&&e&&(i.headers={Authorization:"Bearer "+e});let u=new Oa(i),w=[],I=null,h=Date.now(),A=!1,$=He("Ollama",t,o),C={Fast:!1,Low:"medium",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},x=$!==null?$==="false"||$===!1?!1:$==="true"||$===!0?!0:$:C[o]!==void 0?C[o]:!0,_={model:t,messages:g,stream:!0,think:x,keep_alive:"10m",tools:[],tool_choice:"none",options:{temperature:k}},M=await u.chat(_);for await(let y of M){if(l?.aborted)throw new DOMException("The user aborted a request.","AbortError");if(y.message?.thinking&&(w.push({text:y.message.thinking,thought:!0}),A=!0),y.message?.content&&(w.push({text:y.message.content}),A=!0),y.done){let a=y.prompt_cached_count||0;if(!a&&y.prompt_eval_count){let R=y.prompt_eval_duration||0;R>0&&R<5e7&&(a=y.prompt_eval_count)}I={totalTokenCount:(y.prompt_eval_count||0)+(y.eval_count||0),promptTokenCount:y.prompt_eval_count||0,candidatesTokenCount:y.eval_count||0,cachedContentTokenCount:a,thoughtsTokenCount:0},A=!0}(y.done||Date.now()-h>=150&&A)&&(yield{candidates:w.length>0?[{content:{parts:[...w]}}]:[],usageMetadata:I},w=[],h=Date.now(),A=!1)}A&&(w.length>0||I)&&(yield{candidates:w.length>0?[{content:{parts:[...w]}}]:[],usageMetadata:I})};var ts=async function*(e,t,n,s,o,c,f,l,k=1){let p=[];s&&p.push({role:"system",content:s});for(let a of n){let R=a.role==="user"?"user":"assistant",d="";if(Array.isArray(a.parts))for(let r of a.parts)r.text&&(d+=(d?`
592
+ `:"")+r.text);else d=a.text||"";p.push({role:R,content:d})}let g=He("InferX",t,o),m=g!==null?g:{Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i=t&&t.toLowerCase().includes("qwen3.8-27b")&&g===null,u=t&&(t.toLowerCase().includes("qwen3.8-27b")||t.toLowerCase().includes("qwen3.6-35b-a3b-fp8")),w={model:t,messages:p.filter(a=>a.content&&String(a.content).trim().length>0),stream:!0,stream_options:{include_usage:!0},temperature:k,tools:[],tool_choice:"none"};!i&&m&&(w.stream_options={include_usage:!0},w.reasoning_effort=m);let I=await Ze("https://model.inferx.net/endpoints/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(w),signal:l});if(!I.ok){let a=await I.text().catch(()=>""),R="";try{let d=JSON.parse(a);R=d.error?.message||d.error?.detail||d.message||d.detail||(typeof d.error=="string"?d.error:"")||(a&&a!=="{}"?a:"")}catch{R=a}throw(!R||R==="{}")&&(R=I.statusText||"Unknown error"),new Error(`InferX Error (${I.status}): ${R}`)}let h=I.body.getReader(),A=new TextDecoder,$="",C=[],x=null,_=Date.now(),M=!1,y=!0;for(;;){let{done:a,value:R}=await h.read();if(a){M&&(C.length>0||x)&&(yield{candidates:C.length>0?[{content:{parts:C}}]:[],usageMetadata:x});break}$+=A.decode(R,{stream:!0});let d=$.split(`
593
+ `);$=d.pop();for(let r of d){let E=r.trim();if(!E||!E.startsWith("data: "))continue;let v=!1;if(E==="data: [DONE]")v=!0;else try{let U=JSON.parse(E.substring(6)),O=U.choices?.[0]?.delta,P=U.usage;if(P&&(x={totalTokenCount:P.total_tokens||(P.prompt_tokens||0)+(P.completion_tokens||0),promptTokenCount:P.prompt_tokens||0,candidatesTokenCount:P.completion_tokens||0,cachedContentTokenCount:P.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:P.completion_tokens_details?.reasoning_tokens||P.reasoning_tokens||0},M=!0),O){let re=O.reasoning||O.reasoning_content||null;if(re&&(C.push({text:re,thought:!0}),M=!0),O.content){let de=O.content;u&&y&&de.length>0&&(de="<think>"+de,y=!1),C.push({text:de}),M=!0}}}catch{}if((v||Date.now()-_>=150||x)&&M&&(yield{candidates:C.length>0?[{content:{parts:[...C]}}]:[],usageMetadata:x},C=[],_=Date.now(),M=!1),v)break}Date.now()-_>=150&&M&&(yield{candidates:C.length>0?[{content:{parts:[...C]}}]:[],usageMetadata:x},C=[],_=Date.now(),M=!1)}};var ns=async function*(e,t,n,s,o,c,f,l,k=1){let p=[];s&&p.push({role:"system",content:s});for(let _ of n){let M=_.role==="user"?"user":"assistant",y=[];if(Array.isArray(_.parts)){for(let a of _.parts)if(a.text)y.push({type:"text",text:a.text});else if(a.inlineData&&f){let R=a.inlineData.mimeType,d=a.inlineData.data;R.startsWith("image/")&&y.push({type:"image_url",image_url:{url:`data:${R};base64,${d}`}})}}else{let a=_.text||"";a&&y.push({type:"text",text:a})}p.push({role:M,content:y.length===1&&y[0].type==="text"?y[0].text:y})}let g=He("SenseNova",t,o),m=g!==null?g:{Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:p,stream:!0,stream_options:{include_usage:!0},temperature:k,tools:[],tool_choice:"none"};m&&(i.reasoning_effort=m);let u=await Ze("https://token.sensenova.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(i),signal:l});if(!u.ok){let _=await u.json().catch(()=>({}));throw new Error(`SenseNova Error (${u.status}): ${_.error?.message||u.statusText}`)}let w=u.body.getReader(),I=new TextDecoder,h="",A=[],$=null,C=Date.now(),x=!1;for(;;){let{done:_,value:M}=await w.read();if(_){x&&(A.length>0||$)&&(yield{candidates:A.length>0?[{content:{parts:A}}]:[],usageMetadata:$});break}h+=I.decode(M,{stream:!0});let y=h.split(`
594
+ `);h=y.pop();for(let a of y){let R=a.trim();if(!R||!R.startsWith("data: "))continue;let d=!1;if(R==="data: [DONE]")d=!0;else try{let r=JSON.parse(R.substring(6)),E=r.choices?.[0]?.delta,v=r.usage;if(v&&($={totalTokenCount:v.total_tokens||(v.prompt_tokens||0)+(v.completion_tokens||0),promptTokenCount:v.prompt_tokens||0,candidatesTokenCount:v.completion_tokens||0,cachedContentTokenCount:v.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:v.completion_tokens_details?.reasoning_tokens||v.reasoning_tokens||0},x=!0),E){let U=E.reasoning||E.reasoning_content||null;U&&(A.push({text:U,thought:!0}),x=!0),E.content&&(A.push({text:E.content}),x=!0)}}catch{}if((d||Date.now()-C>=150||$)&&x&&(yield{candidates:A.length>0?[{content:{parts:[...A]}}]:[],usageMetadata:$},A=[],C=Date.now(),x=!1),d)break}Date.now()-C>=150&&x&&(yield{candidates:A.length>0?[{content:{parts:[...A]}}]:[],usageMetadata:$},A=[],C=Date.now(),x=!1)}};var os=async function*(e,t,n,s,o,c,f,l,k=1){let p=[];s&&p.push({role:"system",content:s});for(let _ of n){let M=_.role==="user"?"user":"assistant",y=[];if(Array.isArray(_.parts)){for(let a of _.parts)if(a.text)y.push({type:"text",text:a.text});else if(a.inlineData&&f){let R=a.inlineData.mimeType,d=a.inlineData.data;R.startsWith("image/")&&y.push({type:"image_url",image_url:{url:`data:${R};base64,${d}`}})}}else{let a=_.text||"";a&&y.push({type:"text",text:a})}p.push({role:M,content:y.length===1&&y[0].type==="text"?y[0].text:y})}let g=He("AIHubMix",t,o),m=g!==null?g:{Fast:"minimal",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:p,stream:!0,stream_options:{include_usage:!0},temperature:k,tools:[],tool_choice:"none"};m&&(i.reasoning_effort=m);let u=await Ze("https://aihubmix.com/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(i),signal:l});if(!u.ok){let _=await u.json().catch(()=>({}));throw new Error(`AIHubMix Error (${u.status}): ${_.error?.message||u.statusText}`)}let w=u.body.getReader(),I=new TextDecoder,h="",A=[],$=null,C=Date.now(),x=!1;for(;;){let{done:_,value:M}=await w.read();if(_){x&&(A.length>0||$)&&(yield{candidates:A.length>0?[{content:{parts:A}}]:[],usageMetadata:$});break}h+=I.decode(M,{stream:!0});let y=h.split(`
595
+ `);h=y.pop();for(let a of y){let R=a.trim();if(!R||!R.startsWith("data: "))continue;let d=!1;if(R==="data: [DONE]")d=!0;else try{let r=JSON.parse(R.substring(6)),E=r.choices?.[0]?.delta,v=r.usage;if(r.choices?.[0]?.finish_reason&&(d=!0),v&&($={totalTokenCount:v.total_tokens||(v.prompt_tokens||0)+(v.completion_tokens||0),promptTokenCount:v.prompt_tokens||0,candidatesTokenCount:v.completion_tokens||0,cachedContentTokenCount:v.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:v.completion_tokens_details?.reasoning_tokens||v.reasoning_tokens||0},x=!0),E){let U=E.reasoning_content||null;U&&(A.push({text:U,thought:!0}),x=!0),E.content&&(A.push({text:E.content}),x=!0)}}catch{}if((d||Date.now()-C>=150)&&x&&(yield{candidates:A.length>0?[{content:{parts:[...A]}}]:[],usageMetadata:$},A=[],C=Date.now(),x=!1),d)break}Date.now()-C>=150&&x&&(yield{candidates:A.length>0?[{content:{parts:[...A]}}]:[],usageMetadata:$},A=[],C=Date.now(),x=!1)}};var ss=async function*(e,t,n,s,o,c,f,l,k=1){let p=[];s&&p.push({role:"system",content:s});for(let x of n){let _=x.role==="user"?"user":"assistant",M=[];if(Array.isArray(x.parts)){for(let y of x.parts)if(y.text)M.push({type:"text",text:y.text});else if(y.inlineData&&f){let a=y.inlineData.mimeType,R=y.inlineData.data;a.startsWith("image/")&&M.push({type:"image_url",image_url:{url:`data:${a};base64,${R}`}})}}else{let y=x.text||"";y&&M.push({type:"text",text:y})}p.push({role:_,content:M.length===1&&M[0].type==="text"?M[0].text:M})}let g=He("Poolside",t,o),T=g!==null?g===!1||g==="false"||g==="none"||g==="Fast":o==="Fast",m={model:t,messages:p,stream:!0,stream_options:{include_usage:!0},temperature:k,tools:[],tool_choice:"none"};T?m.chat_template_kwargs={enable_thinking:!1}:g!==null&&typeof g=="object"?m.chat_template_kwargs=g:m.chat_template_kwargs={enable_thinking:!0};let i=await Ze("https://inference.poolside.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(m),signal:l});if(!i.ok){let x=await i.json().catch(()=>({}));throw new Error(`Poolside Error (${i.status}): ${x.error?.message||i.statusText}`)}let u=i.body.getReader(),w=new TextDecoder,I="",h=[],A=null,$=Date.now(),C=!1;for(;;){let{done:x,value:_}=await u.read();if(x){C&&(h.length>0||A)&&(yield{candidates:h.length>0?[{content:{parts:h}}]:[],usageMetadata:A});break}I+=w.decode(_,{stream:!0});let M=I.split(`
596
+ `);I=M.pop();for(let y of M){let a=y.trim();if(!a||!a.startsWith("data: "))continue;let R=!1;if(a==="data: [DONE]")R=!0;else try{let d=JSON.parse(a.substring(6)),r=d.choices?.[0]?.delta,E=d.usage;if(d.choices?.[0]?.finish_reason&&(R=!0),E&&(A={totalTokenCount:E.total_tokens||(E.prompt_tokens||0)+(E.completion_tokens||0),promptTokenCount:E.prompt_tokens||0,candidatesTokenCount:E.completion_tokens||0,cachedContentTokenCount:E.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:E.completion_tokens_details?.reasoning_tokens||E.reasoning_tokens||0},C=!0),r){let v=r.reasoning_content||r.reasoning||null;v&&(h.push({text:v,thought:!0}),C=!0),r.content&&(h.push({text:r.content}),C=!0)}}catch{}if((R||Date.now()-$>=150)&&C&&(yield{candidates:h.length>0?[{content:{parts:[...h]}}]:[],usageMetadata:A},h=[],$=Date.now(),C=!1),R)break}Date.now()-$>=150&&C&&(yield{candidates:h.length>0?[{content:{parts:[...h]}}]:[],usageMetadata:A},h=[],$=Date.now(),C=!1)}};var is=async function*(e,t,n,s,o,c,f,l,k=1){let p=[];s&&p.push({role:"system",content:s});for(let a of n){let R=a.role==="user"?"user":"assistant",d=[];if(Array.isArray(a.parts)){for(let r of a.parts)if(r.text)d.push({type:"text",text:r.text});else if(r.inlineData&&f){let E=r.inlineData.mimeType,v=r.inlineData.data;E.startsWith("image/")&&d.push({type:"image_url",image_url:{url:`data:${E};base64,${v}`}})}}else{let r=a.text||"";r&&d.push({type:"text",text:r})}p.push({role:R,content:d.length===1&&d[0].type==="text"?d[0].text:d})}let g=He("9router",t,o)||He("9Router",t,o),m=g!==null?g:{Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:p,stream:!0,stream_options:{include_usage:!0},temperature:k,tools:[],tool_choice:"none"};m&&m!=="none"&&(g!==null||o!=="Fast")&&(i.reasoning_effort=m);let u=process.env["9ROUTER_URL"]||process.env.NINEROUTER_URL||"http://127.0.0.1:20128/v1/chat/completions",w={"Content-Type":"application/json"},I=e&&e!=="LOCAL"?e:process.env.NINEROUTER_KEY||"dummy-key";w.Authorization=`Bearer ${I}`;let h=await Ze(u,{method:"POST",headers:w,body:JSON.stringify(i),signal:l});if(!h.ok){let a=await h.json().catch(()=>({}));throw new Error(`9router Error (${h.status}): ${a.error?.message||h.statusText}`)}let A=h.body.getReader(),$=new TextDecoder,C="",x=[],_=null,M=Date.now(),y=!1;for(;;){let{done:a,value:R}=await A.read();if(a){y&&(x.length>0||_)&&(yield{candidates:x.length>0?[{content:{parts:x}}]:[],usageMetadata:_});break}C+=$.decode(R,{stream:!0});let d=C.split(`
597
+ `);C=d.pop();for(let r of d){let E=r.trim();if(!E||!E.startsWith("data: "))continue;let v=!1;if(E==="data: [DONE]")v=!0;else try{let U=JSON.parse(E.substring(6)),O=U.choices?.[0]?.delta,P=U.usage;if(U.choices?.[0]?.finish_reason&&(v=!0),P&&(_={totalTokenCount:P.total_tokens||(P.prompt_tokens||0)+(P.completion_tokens||0),promptTokenCount:P.prompt_tokens||0,candidatesTokenCount:P.completion_tokens||0,cachedContentTokenCount:P.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:P.completion_tokens_details?.reasoning_tokens||P.reasoning_tokens||0},y=!0),O){let re=O.reasoning_content||O.reasoning||O.thinking||null;!re&&Array.isArray(O.reasoning_details)&&O.reasoning_details.length>0&&(re=O.reasoning_details.map(de=>typeof de=="string"?de:de?.text||"").filter(Boolean).join("")),re&&(x.push({text:re,thought:!0}),y=!0),O.content&&(x.push({text:O.content}),y=!0)}}catch{}if((v||Date.now()-M>=150)&&y&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:_},x=[],M=Date.now(),y=!1),v)break}Date.now()-M>=150&&y&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:_},x=[],M=Date.now(),y=!1)}};var rs=async function*(e,t,n,s,o,c,f,l,k=1){let p=[];s&&p.push({role:"system",content:s});for(let a of n){let R=a.role==="user"?"user":"assistant",d=[];if(Array.isArray(a.parts)){for(let r of a.parts)if(r.text)d.push({type:"text",text:r.text});else if(r.inlineData&&f){let E=r.inlineData.mimeType,v=r.inlineData.data;E.startsWith("image/")&&d.push({type:"image_url",image_url:{url:`data:${E};base64,${v}`}})}}else{let r=a.text||"";r&&d.push({type:"text",text:r})}p.push({role:R,content:d.length===1&&d[0].type==="text"?d[0].text:d})}let g=He("ExpLabs",t,o),m=g!==null?g:{Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:p,stream:!0,stream_options:{include_usage:!0},temperature:k,tools:[],tool_choice:"none"};m&&(i.reasoning_effort=m);let u=process.env.EXPLABS_URL||process.env.EXPERIENTIALLABS_URL||"https://api.experientiallabs.ai/v1/chat/completions",w={"Content-Type":"application/json"},I=e||process.env.EXPLABS_API_KEY||process.env.EXPERIENTIALLABS_API_KEY||"";w.Authorization=`Bearer ${I}`;let h=await Ze(u,{method:"POST",headers:w,body:JSON.stringify(i),signal:l});if(!h.ok){let a=await h.json().catch(()=>({}));throw new Error(`Experiential Labs Error (${h.status}): ${a.error?.message||a.message||h.statusText}`)}let A=h.body.getReader(),$=new TextDecoder,C="",x=[],_=null,M=Date.now(),y=!1;for(;;){let{done:a,value:R}=await A.read();if(a){y&&(x.length>0||_)&&(yield{candidates:x.length>0?[{content:{parts:x}}]:[],usageMetadata:_});break}C+=$.decode(R,{stream:!0});let d=C.split(`
598
+ `);C=d.pop();for(let r of d){let E=r.trim();if(!E||!E.startsWith("data: "))continue;let v=!1;if(E==="data: [DONE]")v=!0;else try{let U=JSON.parse(E.substring(6)),O=U.choices?.[0]?.delta,P=U.usage;if(P&&(_={totalTokenCount:P.total_tokens||(P.prompt_tokens||0)+(P.completion_tokens||0),promptTokenCount:P.prompt_tokens||0,candidatesTokenCount:P.completion_tokens||0,cachedContentTokenCount:P.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:P.completion_tokens_details?.reasoning_tokens||P.reasoning_tokens||0},y=!0),O){let re=O.reasoning_content||O.reasoning||null;!re&&Array.isArray(O.reasoning_details)&&O.reasoning_details.length>0&&(re=O.reasoning_details.map(de=>de.text||"").filter(Boolean).join("")),re&&(x.push({text:re,thought:!0}),y=!0),O.content&&(x.push({text:O.content}),y=!0)}}catch{}if((v||Date.now()-M>=150)&&y&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:_},x=[],M=Date.now(),y=!1),v)break}Date.now()-M>=150&&y&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:_},x=[],M=Date.now(),y=!1)}};var ti=async function*(e,t,n,s,o,c,f,l,k=1){let p=[];s&&p.push({role:"system",content:s});for(let a of n){let R=a.role==="user"?"user":"assistant",d=[];if(Array.isArray(a.parts)){for(let r of a.parts)if(r.text)d.push({type:"text",text:r.text});else if(r.inlineData&&f){let E=r.inlineData.mimeType,v=r.inlineData.data;E.startsWith("image/")&&d.push({type:"image_url",image_url:{url:`data:${E};base64,${v}`}})}}else{let r=a.text||"";r&&d.push({type:"text",text:r})}p.push({role:R,content:d.length===1&&d[0].type==="text"?d[0].text:d})}let g=He("TokenHarbor",t,o),m=g!==null?g:{Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:p,stream:!0,stream_options:{include_usage:!0},temperature:k,tools:[],tool_choice:"none"};m&&(i.reasoning_effort=m);let u=process.env.TOKENHARBOR_URL||process.env.TOKEN_HARBOR_URL||"https://tokenharbor.ai/v1/chat/completions",w={"Content-Type":"application/json","X-Title":"Flux-Flow","User-Agent":"Flux-Flow","HTTP-Referer":"https://fluxflow-cli.onrender.com/"},I=e||process.env.TOKENHARBOR_API_KEY||process.env.TOKEN_HARBOR_API_KEY||"";w.Authorization=`Bearer ${I}`;let h=await Ze(u,{method:"POST",headers:w,body:JSON.stringify(i),signal:l});if(!h.ok){let a=await h.json().catch(()=>({}));throw new Error(`Token Harbor Error (${h.status}): ${a.error?.message||a.message||h.statusText}`)}let A=h.body.getReader(),$=new TextDecoder,C="",x=[],_=null,M=Date.now(),y=!1;for(;;){let{done:a,value:R}=await A.read();if(a){y&&(x.length>0||_)&&(yield{candidates:x.length>0?[{content:{parts:x}}]:[],usageMetadata:_});break}C+=$.decode(R,{stream:!0});let d=C.split(`
599
+ `);C=d.pop();for(let r of d){let E=r.trim();if(!E||!E.startsWith("data: "))continue;let v=!1;if(E==="data: [DONE]")v=!0;else try{let U=JSON.parse(E.substring(6)),O=U.choices?.[0]?.delta,P=U.usage;if(P&&(_={totalTokenCount:P.total_tokens||(P.prompt_tokens||0)+(P.completion_tokens||0),promptTokenCount:P.prompt_tokens||0,candidatesTokenCount:P.completion_tokens||0,cachedContentTokenCount:P.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:P.completion_tokens_details?.reasoning_tokens||P.reasoning_tokens||0},y=!0),O){let re=O.reasoning_content||O.reasoning||null;!re&&Array.isArray(O.reasoning_details)&&O.reasoning_details.length>0&&(re=O.reasoning_details.map(de=>de.text||"").filter(Boolean).join("")),re&&(x.push({text:re,thought:!0}),y=!0),O.content&&(x.push({text:O.content}),y=!0)}}catch{}if((v||Date.now()-M>=150)&&y&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:_},x=[],M=Date.now(),y=!1),v)break}Date.now()-M>=150&&y&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:_},x=[],M=Date.now(),y=!1)}};var ni=async function*(e,t,n,s,o,c,f,l,k=1){let p=[];s&&p.push({role:"system",content:s});for(let a of n){let R=a.role==="user"?"user":"assistant",d=[];if(Array.isArray(a.parts)){for(let r of a.parts)if(r.text)d.push({type:"text",text:r.text});else if(r.inlineData&&f){let E=r.inlineData.mimeType,v=r.inlineData.data;E.startsWith("image/")&&d.push({type:"image_url",image_url:{url:`data:${E};base64,${v}`}})}}else{let r=a.text||"";r&&d.push({type:"text",text:r})}p.push({role:R,content:d.length===1&&d[0].type==="text"?d[0].text:d})}let g=He("APInex",t,o),m=g!==null?g:{Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:p,stream:!0,stream_options:{include_usage:!0},temperature:k,tools:[],tool_choice:"none"};m&&(i.reasoning_effort=m);let u=process.env.APINEX_URL||"https://api.apinex.bond/v1/chat/completions",w={"Content-Type":"application/json","X-Title":"Flux-Flow","User-Agent":"Flux-Flow","HTTP-Referer":"https://fluxflow-cli.onrender.com/"},I=e||process.env.APINEX_API_KEY||"";w.Authorization=`Bearer ${I}`;let h=await Ze(u,{method:"POST",headers:w,body:JSON.stringify(i),signal:l});if(!h.ok){let a=await h.json().catch(()=>({}));throw new Error(`APInex Error (${h.status}): ${a.error?.message||a.message||h.statusText}`)}let A=h.body.getReader(),$=new TextDecoder,C="",x=[],_=null,M=Date.now(),y=!1;for(;;){let{done:a,value:R}=await A.read();if(a){y&&(x.length>0||_)&&(yield{candidates:x.length>0?[{content:{parts:x}}]:[],usageMetadata:_});break}C+=$.decode(R,{stream:!0});let d=C.split(`
600
+ `);C=d.pop();for(let r of d){let E=r.trim();if(!E||!E.startsWith("data: "))continue;let v=!1;if(E==="data: [DONE]")v=!0;else try{let U=JSON.parse(E.substring(6)),O=U.choices?.[0]?.delta,P=U.usage;if(P&&(_={totalTokenCount:P.total_tokens||(P.prompt_tokens||0)+(P.completion_tokens||0),promptTokenCount:P.prompt_tokens||0,candidatesTokenCount:P.completion_tokens||0,cachedContentTokenCount:P.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:P.completion_tokens_details?.reasoning_tokens||P.reasoning_tokens||0},y=!0),O){let re=O.reasoning_content||O.reasoning||null;!re&&Array.isArray(O.reasoning_details)&&O.reasoning_details.length>0&&(re=O.reasoning_details.map(de=>de.text||"").filter(Boolean).join("")),re&&(x.push({text:re,thought:!0}),y=!0),O.content&&(x.push({text:O.content}),y=!0)}}catch{}if((v||Date.now()-M>=150)&&y&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:_},x=[],M=Date.now(),y=!1),v)break}Date.now()-M>=150&&y&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:_},x=[],M=Date.now(),y=!1)}};var La=/```[\s\S]*?```/g,Pa=/```[\s\S]*$/g,$a=/`[^`]+`/g,Na=/^\|.*\|$/gm,Fa=/^[^\w]+|[^\w]+$/g,Ba=/[^a-z0-9]/gi,wo=/\[\s*(?:tool|action):(?:functions\.)?([a-z0-9_]+)\s*\(/gi,Ua=/\[\s*(?:tool:(?:functions\.)?|action:(?:functions\.)?|action:)([a-z0-9_]+)\s*\(/gi,Wa=/(?:path|targetFile|TargetFile|directory|keyword|id|taskId|title|task)\s*=\s*\\?["']?([^\\"' \),]+)/,Gn=/["']/g,Br=/\\/g,Ha=/<\|channel>thought/gi,Ga=/<channel\|>/gi,ja=e=>typeof e!="string"?e:e.replace(Ha,"<think>").replace(Ga,"</think>"),cf=/^\s*(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\]|$)/i,Ka=(e,t,n=1)=>{let s=t>0?e[t-1]:"",o=t+n<e.length?e[t+n]:"";return s==="`"&&o==="`"},Va=e=>{let t=/(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\])/gi,n;for(;(n=t.exec(e))!==null;)if(!Ka(e,n.index,n[0].length))return{index:n.index,length:n[0].length};return{index:-1,length:0}},oi=e=>{if(!e||typeof e!="string")return null;let t=e.match(/^\s*(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought|\[(think|thought|thoughts)\])/i);if(!t)return null;let n=t.index+t[0].length,s=e.substring(n),o=Va(s);if(o.index!==-1){let c=n+o.index+o.length;return{fullBlock:e.substring(0,c),innerContent:s.substring(0,o.index),remainingText:e.substring(c)}}return{fullBlock:e,innerContent:s,remainingText:""}},qt=e=>{if(!e||typeof e!="string")return e;let t=oi(e);return t?t.remainingText.trimStart():e};var Vr=/`[^`]*`/g,Yr=/`[^`]*$/,Ur=/<\|\s*tool_call_begin\s*\|>\s*(?:(?:tool|functions)\b[\s._]*)*([a-zA-Z0-9_]+)(?::\d+)?\s*<\|\s*tool_call_argument_begin\s*\|>([\s\S]*?)<\|\s*tool_call_end\s*\|>/gi,Ya=/"([^"]+)"\s*:\s*(?:"([^"]*)"|(\d+)|true|false|null)/g,Wr=/<\|\s*tool_calls_section_begin\s*\|>/gi,Hr=/<\|\s*tool_calls_section_end\s*\|>/gi,qa=/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi;var Gr=e=>!e||typeof e!="string"?e:e.replace(/(```[\s\S]*?```|`[^`]*`)|(<(?:\w+)(?:[^>]*)>\r?\n?|\r?\n?<\/\w+(?:[^>]*)>)/gi,(t,n)=>n||""),qr=e=>{if(!e||typeof e!="string")return e;let t=ko(e);if(!t||t.length===0)return e;let n=t[t.length-1];if(!n.fullMatch)return e;let s=e.lastIndexOf(n.fullMatch);if(s===-1)return e;let o=s+n.fullMatch.length;return e.substring(0,o).trimEnd()},ii=null,as={},jn={key:null,value:null},Yt=e=>e&&e.replace(/(?:(\x1b\[\d+m))?([✔✘✖🔍📖→➕↻↷•🛇])(?:(\x1b\[\d+m))?\s*\b(Clicked|Located|Dragged|Scrolled|Typed|Pressed Key|Recaptured Screen|Created|Read Skill|Read Documentation|Searched Documentation|Read|Edited|Viewed|Processed|Auto-Read|Skipped|List|Generated|Written|Searched|AI Search|Get Map|Write Canceled|Resolved Sub-Agent Query|Edit Canceled|Write Cancelled|Edit Denied|Visited|Updated|Reviewed|Delegated|Background|Checked|Indexed|Analyzed|Browsed|Elevating SubAgent|Checking SubAgent Work|Started Generalist|Called Generalist|Steered|Unsupported Modality|Awaiting|Cancelled|Aligning Moon Phase|Contemplating Existence|Staring At Void|Rollback Point Checked|Emergency Rollback Failed|Emergency Rollback|Delaying Professionally|Negotiating With Electrons|Touching Grass (virtually)|Panicking Softly|Rethinking Career Choices|Loading Cat Videos|Giving Up Entirely|Summoning Braincell #2|Pretending To Be Busy|Waiting For Motivation DLC|Rotating Internal Screaming|Downloading More RAM|Feeding The Hamsters|Gaslighting Scheduler|Performing Dramatic Pause|Buffering Social Energy|Calculating Regret|Reading Terms And Conditions|Becoming Sentient Briefly|Execution Error|Loop Detected|Contacting Ancestors)\b/ig,(t,n,s,o,c)=>`${n||""}${s}${o||""} \x1B[95m${c}\x1B[0m`),za=async(e,t=8,n=1e3,s=8e3,o=null)=>{let c=0;for(;;){if(o?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{return await e()}catch(f){if(o?.aborted||f?.name==="AbortError"||f?.message==="Subagent task was cancelled."||(c++,c>=t))throw f;let l=Math.min(n*Math.pow(2,c-1),s);await new Promise((k,p)=>{let g=setTimeout(k,l);o&&o.addEventListener("abort",()=>{clearTimeout(g),p(new DOMException("The user aborted a request.","AbortError"))})})}}},wt=!1;var Xa=e=>{let t=e.filter(o=>(o.role==="user"||o.role==="agent"||o.role==="system")&&o.role!=="think"&&!o.isVisualFeedback&&!o.isMeta&&!o.isTerminalRecord&&!(o.text&&o.text.includes("[TERMINAL_RECORD]"))&&!String(o.id).startsWith("welcome")).map((o,c,f)=>{let l=o.fullText||o.text||"";if(o.role==="user"&&c<f.length-1)if(l.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")){let k=l.indexOf("**CONTEXT SUMMARY OF PREVIOUS TURNS");if(k!==-1){let g=l.substring(0,k).lastIndexOf("[SYSTEM METADATA]");g!==-1?l=l.substring(g).trim():l=l.substring(k).trim()}}else{let k=l.lastIndexOf("[USER]"),p=l.lastIndexOf("[USER PROMPT]");k!==-1?l=l.substring(k+6).trim():p!==-1&&(l=l.substring(p).trim())}return{...o,text:l}}),n=[],s=0;for(;s<t.length;){let o=t[s];if(o.role==="user")n.push(o),s++;else{let c=[];for(;s<t.length&&t[s].role!=="user";)c.push(t[s]),s++;let f=[],l=[],k=!1,p=()=>{f.length>0&&(n.push({role:"agent",text:"combined"}),f=[]),l.length>0&&(n.push({role:"system",text:"combined"}),l=[]),k=!1};c.forEach(g=>{let T=g.role==="system"&&(g.text?.startsWith("[ACTION RESULT]")||g.text?.startsWith("[TOOL RESULT]")||g.text?.startsWith("SUCCESS:")||g.text?.startsWith("ERROR:")||g.fullText?.startsWith("[ACTION RESULT]")||g.fullText?.startsWith("[TOOL RESULT]")||g.fullText?.startsWith("SUCCESS:")||g.fullText?.startsWith("ERROR:")),m=g.fullText||g.text||"",i=m.trim();if(!(!i&&!g.binaryPart)){if(T)l.push(i);else if(g.role==="agent"){!k&&l.length>0&&p();let u=m.endsWith(`
601
+ `),w=i.toLowerCase().includes("tool:")||i.toLowerCase().includes("action:");f.push(i),w&&u?k=!0:k=!1}}}),p()}}return n.length},Ja=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),df=()=>{wt=!0},ff=()=>wt,si={write_file:"Writing",update_file:"Editing",read_folder:"Reading",view_file:"Reading",exec_command:"Executing Command",web_search:"Searching",web_scrape:"Reading",memory:"Updating Memory",search_keyword:"Searching",find_file:"Finding File",findFile:"Finding File",FindFile:"Finding File",file_map:"Generating Map",ask:"User Input",write_pdf:"Creating",write_docx:"Creating",generate_image:"Generating",todo:"Planning",Todo:"Planning",goal:"Planning",Goal:"Planning",invoke_sync:"Sub-Agent Working",invoke:"Starting Agent",get_progress:"Checking Progress",cancel:"Cancelling",await:"Waiting",EmergencyRollback:"Don't Panic. Lookin' into it",answer:"Answering Sub-Agent",Answer:"Answering Sub-Agent",steer:"Steering Sub-Agent",Steer:"Steering Sub-Agent",Click:"Clicking",click:"Clicking",Drag:"Dragging",drag:"Dragging",Scroll:"Scrolling",scroll:"Scrolling",KeyboardTyping:"Typing",keyboard_typing:"Typing",KeyPress:"Pressing Key",key_press:"Pressing Key",RecaptureScreen:"Recapturing Screen",recapture_screen:"Recapturing Screen"},Kn=(e,t)=>{try{let n=ne(t),s=e.toLowerCase().replace(/_/g,"");if(s==="invokesync"||s==="invoke")return n.title||(n.task?n.task.substring(0,30):null);if(s==="getprogress"||s==="cancel"||s==="steer"||s==="steersubagent")return n.id||n.taskId;let o=n.name||n.path||n.targetFile||n.TargetFile||n.directory||n.file||n.query;return o?ie.basename(o.replace(/["']/g,"").replace(/\\/g,"/")):null}catch{return null}},ri=e=>e?new Kr({apiKey:e}):ii,uf=async(e,t,n,s,o={})=>{let{onStatus:l,onMemoryUpdated:k,onBackgroundIncrement:p}=o,{profile:g,thinkingLevel:T,mode:m,janitorModel:i,chatId:u,systemSettings:w,sessionStats:I,aiProvider:h="Google",apiKey:A}=e,$=process.env.NVIDIA_BASE_URL||h==="Ollama"||h==="InferX"||h==="SenseNova"||h==="AIHubMix"||h==="Poolside"||h==="9router"||h==="ExpLabs"||h==="ExperientialLabs"?!1:w?.memory!==!1,x=Ct(Wn,[]).map(L=>`- [${L.id}]: ${L.memory}`).join(`
602
+ `),_=s.slice(0,-1).filter(L=>L.text&&!L.text.includes("[ACTION RESULT]")&&!L.text.includes("[TOOL RESULT]")&&!L.text.includes("OBSERVATION:")&&!L.text.startsWith("[TERMINAL_RECORD]")&&!L.isTerminalRecord&&!L.isMeta&&!L.isLogo&&!String(L.id).startsWith("welcome")&&!String(L.id).startsWith("logo")).slice(-14).map(L=>{let F=qt(Ja(L.text)).replace(/\[(?:tool|action):(?:functions\.)?.*?\]/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[METADATA \(PRIORITY: DYNAMIC\)\] Time: ([^|\n]+)/g,(G,ye)=>`[METADATA (PRIORITY: DYNAMIC)] Time: ${ye.replace(/:\d{2}/g,"")}`).replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[\[(?:TOOL|ACTION) RESULTS\]\]/gi,"").replace(/\[(?:TOOL|ACTION) RESULTS?\]/gi,"").replace(/\[(?:tool|action) results\]/gi,"").replace(/\r?\n\r?\n/g,`
603
+ `).replace(/\n\n/g,`
604
+ `).replace(/\\n\\n/g,"").trim(),Ee=L.role==="user"?8192:32768,oe=F.substring(0,Ee);F.length>Ee&&(oe+=`
605
+ ... (truncated) ...`);let B=L.role==="user"?oe.startsWith("[USER]")?"":"[USER]: ":oe.startsWith("[AGENT]")?"":"[AGENT]: ";return{role:L.role==="user"?"user":"model",parts:[{text:`${B}${oe}`}]}}),M=s.filter(L=>L.role==="user").length===1,y=t.includes("[TITLE-UPDATE]"),a=Math.random()<.8,R=M||y||a,d=qt(n).trim(),r=ur(x,$,R),E=`${d.replace(/\[(?:tool|action):(?:functions\.)?.*?\]/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[\[(?:TOOL|ACTION) RESULTS\]\]/gi,"").replace(/\[(?:TOOL|ACTION) RESULTS?\]/gi,"").replace(/\[(?:tool|action) results\]/gi,"").substring(0,32768)}`;E.length>32768&&(E+=`
606
+ ... (truncated) ...`);let v=t.replace(/\[Prompted on:.*?\]/g,"").trim();E=E.replace(/\r?\n\r?\n/g,`
607
+ `).replace(/\n\n/g,`
608
+ `).replace(/\\n\\n/g,"").trim();let U=new Date,P=`[METADATA] Current date and Time: ${`${U.getFullYear()}-${U.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(U.getDate()).padStart(2,"0")}, ${U.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0})}`}
609
+
610
+ [USER]: ${v.substring(0,8192)}
611
+ ${v.length>8192?`... (truncated) ...
612
+
613
+ `:""}
614
+ [AGENT (current turn)]: ${E}`;_.push({role:"user",parts:[{text:P}]});let re=await Ss("NVIDIA"),Q=(await ao()).quotas?.providerTiers?.NVIDIA==="Free",ke="",ae=0,it=$?12:-1;for(;ae<=it;)try{if(!await ki("background",e))return;let L="",F=null,Ee=!1,oe=h;try{let ye=new Promise((Je,xe)=>setTimeout(()=>xe(new Error("JANITOR_TIMEOUT")),1e4)),Re=h==="Google"&&ae>=0&&ae<6&&re&&Q,ve=h==="DeepSeek"&&ae<4&&re&&Q;Ee=Re||ve,oe=Ee?"NVIDIA":h;let Ie=(async()=>{if(h==="OpenRouter"){let Je=pe("janitor_open_router"),te=es(A,Je,_,r,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),Wt=await te.next();return{iterator:te,firstResult:Wt}}else if(h==="DeepSeek"&&!Ee){let xe=Jo(A,pe("deepseek_fast_fallback"),_,r,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),te=await xe.next();return{iterator:xe,firstResult:te}}else if(h==="Mistral"&&!Ee){let xe=Qo(A,pe("mistral_janitor_fallback"),_,r,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),te=await xe.next();return{iterator:xe,firstResult:te}}else if(h==="NVIDIA"||Ee){let xe=Zo(Ee?re:A,pe("nvidia_janitor_fallback"),_,r,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),te=await xe.next();return{iterator:xe,firstResult:te}}else if(h==="InferX"){let xe=ts(A,targetModel||pe("inferx_fallback")||"deepseek-v4-flash",_,r,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),te=await xe.next();return{iterator:xe,firstResult:te}}else if(h==="SenseNova"){let xe=ns(A,targetModel||pe("sensenova_fallback")||"sensenova-6.8-flash-lite",_,r,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),te=await xe.next();return{iterator:xe,firstResult:te}}else if(h==="AIHubMix"){let xe=os(A,targetModel||pe("aihubmix_fallback")||"gpt-4o-mini",_,r,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),te=await xe.next();return{iterator:xe,firstResult:te}}else if(h==="Poolside"){let xe=ss(A,targetModel||pe("poolside_fallback")||"poolside/laguna-s-2.1",_,r,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),te=await xe.next();return{iterator:xe,firstResult:te}}else if(h==="9router"||h==="9Router"){let xe=is(A,targetModel||pe("9router_fallback")||"z-ai/glm-5.3-flash",_,r,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),te=await xe.next();return{iterator:xe,firstResult:te}}else if(h==="ExpLabs"||h==="ExperientialLabs"){let xe=rs(A,targetModel||pe("explabs_fallback")||"deepseek-v4-pro-0813",_,r,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),te=await xe.next();return{iterator:xe,firstResult:te}}else{let te=(await ri(A).models.generateContentStream({model:i||(ae===it?pe("janitor_default"):pe("gemma_janitor_fallback_google")),contents:_,config:{systemInstruction:r,temperature:.7,safetySettings:[{category:In.HARM_CATEGORY_HARASSMENT,threshold:Mn.BLOCK_NONE},{category:In.HARM_CATEGORY_HATE_SPEECH,threshold:Mn.BLOCK_NONE},{category:In.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Mn.BLOCK_NONE},{category:In.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Mn.BLOCK_NONE}],thinkingConfig:{includeThoughts:!1,thinkingLevel:Xe.MINIMAL},serviceTier:"flex"}}))[Symbol.asyncIterator](),Wt=await te.next();return{iterator:te,firstResult:Wt}}})();if(process.stdout.isTTY){let te=(await Cs())[u]?.name||"",Wt=te&&!te.startsWith("flow-")&&!te.startsWith("Session ")?te:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${Wt}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${Wt}\x07`)}let{iterator:Dn,firstResult:nn}=await Promise.race([Ie,ye]),{value:pt,done:kt}=nn;if(!kt&&pt){let Je=pt.candidates?.[0]?.content?.parts,xe=Je?oe==="Google"?Je[1]?.text||Je[0]?.text||"":Je.filter(te=>te.text&&!te.thought).map(te=>te.text).join(""):typeof pt.text=="function"?pt.text():"";xe&&(L+=xe),F=pt.usageMetadata;for await(let te of{[Symbol.asyncIterator]:()=>Dn}){let Wt=te.candidates?.[0]?.content?.parts,On=Wt?oe==="Google"?Wt[1]?.text||Wt[0]?.text||"":Wt.filter(Ln=>Ln.text&&!Ln.thought).map(Ln=>Ln.text).join(""):typeof te.text=="function"?te.text():"";On&&(L+=On),F=te.usageMetadata}}}catch(ye){throw ye}if(L){if(ke=L,F){let ye=F.totalTokenCount||0,Re=F.cachedContentTokenCount||0,ve=(F.candidatesTokenCount||0)+(oe==="Google"&&F.thoughtsTokenCount||0),Ie=Ee?pe("nvidia_janitor_fallback"):oe==="DeepSeek"?pe("deepseek_fast_fallback"):oe==="ExpLabs"||oe==="ExperientialLabs"?pe("explabs_fallback")||"deepseek-v4-pro-0813":oe==="OpenRouter"?pe("janitor_open_router"):i||(ae===it?pe("janitor_default"):pe("gemma_janitor_fallback_google"));await Bt("tokens",ye,oe,Ie),Re>0&&await Bt("cachedTokens",Re,oe,Ie),ve>0&&await Bt("candidateTokens",ve,oe,Ie),Do({provider:oe,model:Ie,prompt:F.promptTokenCount||0,cached:Re,output:ve,reasoning:F.thoughtsTokenCount||0})}}else throw new Error("No synthesis generated by Janitor.");p&&(p(),await Rt("background"));let B=ko(ke),G=!1;for(let ye of B){let Re=ye.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(Re)&&(G=!0);let ve={chatId:u,sessionId:u,history:s},Ie=await xo(Re,ye.args,ve);Re.toLowerCase()==="memory"&&(ye.args.includes("action='user'")||ye.args.includes('action="user"'))&&!Ie.startsWith("ERROR")&&(k&&k(),process.stdout.isTTY&&(process.stdout.write("\x1B]0;Memory Updated\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=Memory Updated\x07")),await new Promise(nn=>setTimeout(nn,3e3)))}if(!G)try{let ye=Ct(Wn,[]);if(ye.length>0){let Re=[];for(let ve of ye)ve.score===void 0&&(ve.score=.5),ve.score*=.99995,ve.score<.05&&(ve.score=0),ve.score=Math.round(ve.score*1e5)/1e5,ve.score>0&&Re.push(ve);Xn(Wn,Re)}}catch{}break}catch(L){ae++;let F=new Date().toLocaleString(),Ee=L instanceof Error?(()=>{try{return JSON.parse(JSON.parse(L.message).error.message).error.message}catch{return String(L)}})():String(L);await new Promise(G=>setTimeout(G,1e3));let oe=ie.join(Cn,"janitor");if(Ue.existsSync(oe)||Ue.mkdirSync(oe,{recursive:!0}),Ue.appendFileSync(ie.join(oe,"error.log"),`ERROR [Attempt ${ae}/${it+1}] [${F}]: ${Ee}
615
+
616
+ `),ae>it)break;let B=Math.min(750*Math.pow(2,ae-1),5e3);await new Promise(G=>setTimeout(G,B))}if(ae){let L=ie.join(Cn,"janitor");Ue.appendFileSync(ie.join(L,"error.log"),`-----------------------------------------------------------------------------
617
+
618
+ `)}if(process.stdout.isTTY)try{let Ee=(await Cs())[u]?.name||"",oe=Ee&&!Ee.startsWith("flow-")&&!Ee.startsWith("Session ")?Ee:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${oe}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${oe}\x07`)}catch{process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")}},Qa=e=>{let t=qt(e),n=Es?t:t.replace(Vr,o=>" ".repeat(o.length)).replace(Yr,o=>" ".repeat(o.length));wo.lastIndex=0;let s;for(;(s=wo.exec(n))!==null;){let o=s.index+s[0].length-1,c=0,f=null,l=!1,k=!1;for(let p=o;p<n.length;p++){let g=t[p];if(!f&&(g==='"'||g==="'"||g==="`")?(f=g,l=!1):f&&g===f&&!l&&(f=null),!f&&(g==="("?c++:g===")"&&c--,c===0)){let T=p+1;for(;T<n.length&&/\s/.test(n[T]);)T++;if(T<n.length&&n[T]==="]"){k=!0,wo.lastIndex=T+1;break}}g==="\\"?l=!l:l=!1}if(!k)return{inside:!0,toolName:s[1],startIndex:s.index,args:t.substring(s.index+s[0].length)}}return{inside:!1}},zr=(e,t=!0)=>{let n=wo;n.lastIndex=0;let s="",o=0,c;for(;(c=n.exec(e))!==null;){let f=e.substring(o,c.index);s+=t&&o===0?qt(f):f;let l=c.index+c[0].length-1,k=0,p=null,g=-1;for(let T=l;T<e.length;T++){let m=e[T];if(p){if(m===p){let i=0;for(let u=T-1;u>=0&&e[u]==="\\";u--)i++;i%2===0&&(p=null)}}else if(m==='"'||m==="'"||m==="`")p=m;else if(m==="(")k++;else if(m===")"&&(k--,k===0)){let i=T+1;for(;i<e.length&&/\s/.test(e[i]);)i++;if(i<e.length&&e[i]==="]"){g=i;break}}}if(g!==-1)s+="[tool:functions."+c[1]+"()]",o=g+1,n.lastIndex=o;else{s+="[tool:functions."+c[1]+"(",o=e.length;break}}return o<e.length&&(s+=t&&o===0?qt(e.substring(o)):e.substring(o)),s},Za=(e,t,n)=>{let s=wo;s.lastIndex=0;let o="",c=0,f;for(;(f=s.exec(e))!==null;){let l=e.substring(c,f.index);o+=l.replace(t,n);let k=f.index+f[0].length-1,p=0,g=null,T=-1;for(let m=k;m<e.length;m++){let i=e[m];if(g){if(i===g){let u=0;for(let w=m-1;w>=0&&e[w]==="\\";w--)u++;u%2===0&&(g=null)}}else if(i==='"'||i==="'"||i==="`")g=i;else if(i==="(")p++;else if(i===")"&&(p--,p===0)){let u=m+1;for(;u<e.length&&/\s/.test(e[u]);)u++;if(u<e.length&&e[u]==="]"){T=u;break}}}if(T!==-1)o+=e.substring(f.index,T+1),c=T+1,s.lastIndex=c;else{o+=e.substring(f.index),c=e.length;break}}return c<e.length&&(o+=e.substring(c).replace(t,n)),o},jr=e=>zr(e,!0),el=e=>{if(!e)return e;let t={patchfile:"PatchFile",writefile:"WriteFile",readfile:"ReadFile",viewfile:"ReadFile",run:"Run",execcommand:"Run",searchkeyword:"SearchKeyword",codesearch:"CodeSearch",code_search:"CodeSearch",websearch:"WebSearch",webscrape:"WebScrape",readfolder:"ReadFolder",writepdf:"WritePDF",writedoc:"WriteDoc",writedocx:"WriteDoc",filemap:"FileMap",generateimage:"GenerateImage",todo:"Todo",goal:"Goal",askuser:"AskUser",ask:"AskUser"},n=o=>o.split("_").map(c=>c.charAt(0).toUpperCase()+c.slice(1)).join("");Ur.lastIndex=0;let s=e.replace(Ur,(o,c,f)=>{let l="";try{let g=JSON.parse(f.trim());g&&typeof g=="object"&&(l=Object.entries(g).map(([m,i])=>{let u=typeof i=="string"?i:JSON.stringify(i);return`${m}=${JSON.stringify(u)}`}).join(", "))}catch{let T=[],m=Ya;m.lastIndex=0;let i;for(;(i=m.exec(f))!==null;){let u=i[1],w=i[2]!==void 0?i[2]:i[0].split(":").slice(1).join(":").trim();T.push(`${u}=${JSON.stringify(w)}`)}T.length>0?l=T.join(", "):l=f.trim()}let k=c.toLowerCase().replace(/_/g,"");return`[tool:functions.${t[k]||n(c)}(${l})]`});return Wr.lastIndex=0,Hr.lastIndex=0,s=s.replace(Wr,""),s=s.replace(Hr,""),s},tl=/(?:path|query|url|keyword|command|method|title|task|id)\s*=\s*['"`]?\s*\.\.\.\s*['"`]?/i,nl=/^['"`]?\s*\.\.\.\s*['"`]?$/,bn=e=>{if(e==null)return!1;let t=String(e).trim();return t==="..."||t==="\u2026"||nl.test(t)},ko=e=>{if(!e)return[];let t=el(e),n=qt(t),s=[],o=Es?n:n.replace(Vr,l=>" ".repeat(l.length)).replace(Yr,l=>" ".repeat(l.length)),c=Ua;c.lastIndex=0;let f;for(;(f=c.exec(o))!==null;){let l=f[1],k=f.index+f[0].length-1,p=0,g=null,T=-1,m=-1;for(let i=k;i<o.length;i++){let u=n[i];if(g){if(u===g){let w=0;for(let I=i-1;I>=0&&n[I]==="\\";I--)w++;w%2===0&&(g=null)}}else if(u==='"'||u==="'"||u==="`")g=u;else if(u==="(")p++;else if(u===")"&&(p--,p===0)){m=i;let w=i+1;for(;w<o.length&&/\s/.test(o[w]);)w++;if(w<o.length&&o[w]==="]"){T=w;break}}}if(T!==-1){let i=n.substring(k+1,m),u=n.substring(f.index,T+1),w=ne(i);bn(w.path)||bn(w.query)||bn(w.url)||bn(w.keyword)||bn(w.command)||bn(w.method)||bn(w.title)||bn(w.task)||bn(w.id)||tl.test(i)||s.push({fullMatch:u,toolName:l.trim(),args:i.trim()}),c.lastIndex=T+1}}return s},gf=(e,t={})=>{if(!e)return null;if(as=t,ii=new Kr({apiKey:e}),!globalThis.__perfCleanupInstalled){globalThis.__perfCleanupInstalled=!0,setInterval(()=>{typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks())},6e4);let n=globalThis.fetch;globalThis.fetch=async(...s)=>{try{let o=await n(...s);return typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),o}catch(o){throw typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),o}}}},Xr=e=>{if(!e)return{serviceTier:void 0,cleanModel:e};let t=e.toLowerCase();return t.endsWith(":flex")?{serviceTier:"flex",cleanModel:e.slice(0,-5)}:t.endsWith(":priority")?{serviceTier:"priority",cleanModel:e.slice(0,-9)}:{serviceTier:void 0,cleanModel:e}},ls=async(e,t,n,s,o="Fast",c=.75,f="agent")=>za(async()=>{let{aiProvider:l="Google",apiKey:k,mode:p}=e,g="",T=null,m=typeof n=="string"?[{role:"user",parts:[{text:n}]}]:n,i=new AbortController,u=i.signal,w=setInterval(()=>{wt&&(i.abort(),clearInterval(w))},100);try{let I;if(l==="Ollama")I=ei(k,t,m,s,o,p,ft(t),u,c,e.systemSettings?.ollamaEndpoint||"Cloud");else if(l==="OpenRouter")I=es(k,t,m,s,o,p,ft(t),u,c);else if(l==="DeepSeek")I=Jo(k,t,m,s,o,p,ft(t),u,c);else if(l==="Mistral")I=Qo(k,t,m,s,o,p,ft(t),u,c);else if(l==="NVIDIA")I=Zo(k,t,m,s,o,p,ft(t),u,c);else if(l==="InferX")I=ts(k,t,m,s,o,p,ft(t),u,c);else if(l==="SenseNova")I=ns(k,t,m,s,o,p,ft(t),u,c);else if(l==="AIHubMix")I=os(k,t,m,s,o,p,ft(t),u,c);else if(l==="Poolside")I=ss(k,t,m,s,o,p,ft(t),u,c);else if(l==="9router"||l==="9Router")I=is(k,t,m,s,o,p,ft(t),u,c);else if(l==="ExpLabs"||l==="ExperientialLabs")I=rs(k,t,m,s,o,p,ft(t),u,c);else if(l==="TokenHarbor"||l==="Token Harbor"||l==="tokenharbor"||l==="token_harbor"||l==="thk")I=ti(k,t,m,s,o,p,ft(t),u,c);else if(l==="APInex"||l==="apinex"||l==="apx")I=ni(k,t,m,s,o,p,ft(t),u,c);else{let h=ri(k),{serviceTier:A,cleanModel:$}=Xr(t),C={systemInstruction:s,temperature:c,thinkingConfig:(()=>{let _=(t||"").toLowerCase(),M=_.includes("gemma-4")||_.startsWith("gemma"),y=_.includes("gemini-3");if(M||y)return M?o.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:Xe.MINIMAL}:{includeThoughts:!0,thinkingLevel:Xe.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:_.includes("pro")?Xe.LOW:Xe.MINIMAL,Low:Xe.LOW,Medium:Xe.MEDIUM,Standard:Xe.MEDIUM,High:Xe.HIGH,xHigh:Xe.HIGH}[o]||Xe.MEDIUM};{let a={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[o]||2048;return a===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:a}}})()};A&&(C.serviceTier=A),I=await h.models.generateContentStream({model:$,contents:m,config:C},{signal:u})}for await(let h of I){if(wt)throw new Error("Subagent task was cancelled.");if(e?.taskId&&typeof Vt<"u"){let C=Vt.find(x=>x.id===e.taskId);if(C&&C.status==="cancelled")throw new Error("Subagent task was cancelled.")}let A="";if(h.candidates?.[0]?.content?.parts)for(let C of h.candidates[0].content.parts)C.text&&!C.thought&&(g+=C.text,A+=C.text);let $=A?As(A):0;e&&typeof e.onTokenChunk=="function"&&e.onTokenChunk(A,$),h.usageMetadata&&(T=h.usageMetadata)}}finally{clearInterval(w)}if(T){let I=T.totalTokenCount||0,h=T.cachedContentTokenCount||0,A=(T.candidatesTokenCount||0)+(l==="Google"&&T.thoughtsTokenCount||0);await Bt("tokens",I,l,t),h>0&&await Bt("cachedTokens",h,l,t),A>0&&await Bt("candidateTokens",A,l,t),Do({provider:l,model:t,prompt:T.promptTokenCount||0,cached:h,output:A,reasoning:T.thoughtsTokenCount||0}),e&&typeof e.onUsage=="function"&&e.onUsage({totalTokenCount:I,cachedContentTokenCount:h,candidatesTokenCount:A})}return await Rt("agent",l),{text:g,usageMetadata:T}}),ol=async(e,t,n=null)=>{n=n||Ct(vo,{});try{let{aiProvider:s="Google"}=t;if(Object.values(n).flat().length<=5)return;let c=Object.keys(n).filter(m=>m!==e&&Array.isArray(n[m])&&n[m].length>2);if(c.length===0)return;let f=`You are a silent background process for the FluxFlow CLI Agent.
619
+ Your task is to summarize or merge temporary context memories from one or more past conversation sessions.
620
+ For each Chat ID provided, you must output a tool call to save the consolidated summary.
621
+
622
+ The tool call format MUST be:
623
+ [tool:functions.saveSummary(id="<chat-id>", summary="<updated summary string, max 400 words>")]
624
+
625
+ Guidelines:
626
+ - Create a single, updated, highly cohesive, and concise summary statement (max 400 words) for each Chat ID. It should contain WHAT user talked about, WHAT were the tasks, Temporal info, HOW/WHAT the model responded. DON'T REMOVE ANY KEY AND TURN BY TURN INFO DENSITY.
627
+ - Focus on key goals, preferences, modified files, and technical decisions.
628
+ - Under no circumstances write normal conversational text. Output ONLY the tool calls.
629
+ - You can stack multiple tool calls for multiple chats.
630
+
631
+ Chats to process:
632
+
633
+ `,l=Ct(ks,{});for(let m of c){let u=n[m].map(I=>`- ${I}`).join(`
634
+ `),w=l[m];f+=`[Chat ID: ${m}]
635
+ `,w?(f+=`- Existing Summary: "${w}"
636
+ `,f+=`
637
+ -- New Memories to integrate:
638
+ ${u}
639
+
640
+ `):f+=`-- Individual Memories:
641
+ ${u}
642
+
643
+ `}let k=0,p=5,g=!1,T=pe("gemma_janitor_fallback_google");for(s==="OpenRouter"&&(T=pe("janitor_open_router")),s==="DeepSeek"&&(T=pe("deepseek_level_1")),s==="Mistral"&&(T=pe("mistral_level_1")),s==="NVIDIA"&&(T=pe("nvidia_janitor_fallback")),s==="InferX"&&(T=pe("inferx_fallback")),s==="SenseNova"&&(T=pe("sensenova_fallback")),s==="AIHubMix"&&(T=pe("aihubmix_fallback")),s==="Poolside"&&(T=pe("poolside_fallback")),(s==="9router"||s==="9Router")&&(T=pe("9router_fallback"));k<=p&&!g;){k++;try{let i=(await ls(t,T,f,null,"Fast",.75,"background")).text||"",u=ko(i);if(u.length===0)throw new Error("No tool calls detected in synthesis response");for(let w of u){let I=w.toolName;["saveSummary","saveSumary","SaveSummary","SaveSumary"].includes(I)&&await xo(I,w.args,{chatId:e})}g=!0}catch(m){if(k>=p)throw new Error(`Failed after ${p} attempts. Last error: ${m.message}`)}}}catch(s){let o=s instanceof Error?(()=>{try{return JSON.parse(JSON.parse(s.message).error.message).error.message}catch{return String(s)}})():String(s),c=ie.join(Cn,"janitor");Ue.existsSync(c)||Ue.mkdirSync(c,{recursive:!0}),Ue.appendFileSync(ie.join(c,"error.log"),`[${new Date().toLocaleString()}] Past memory batch consolidation error: ${o}
644
+ `)}},hf=async(e,t,n=!1)=>{let{chatId:s,aiProvider:o="Google"}=e,c=ie.join(Ro,"chat-summaries.json"),f=i=>i.filter(u=>(u.role==="user"||u.role==="agent"||u.role==="system")&&u.role!=="think"&&!u.isVisualFeedback&&!u.isMeta&&!u.isTerminalRecord&&!(u.text&&u.text.includes("[TERMINAL_RECORD]"))&&!String(u.id).startsWith("welcome")).map(u=>{let w=u.fullText||u.text||"",I=u.role==="system"||w.startsWith("[ACTION RESULT]:")||w.startsWith("[TOOL RESULT]:")||u.text&&(u.text.startsWith("[ACTION RESULT]:")||u.text.startsWith("[TOOL RESULT]:")),h=w;return I&&(w.includes("[ACTION RESULT]:")||w.includes("[TOOL RESULT]:")||u.text&&(u.text.includes("[ACTION RESULT]:")||u.text.includes("[TOOL RESULT]:")))?h="[ACTION RESULT]: ...truncated for summary":h=h.replace(/(\[(?:tool|action):[a-zA-Z0-9_\.]+)\([\s\S]*?\)(\])/g,"$1(...)$2"),`[${I?"ACTION":u.role==="agent"?"AGENT":"USER"}]: ${h}`}).join(`
645
+
646
+ `),l=async(i,u)=>{let w="You are an expert context summarizer. Summarize the provided chat history (which may include previous summaries, user instructions, agent outputs, and tool results) into a detailed, coherent, and highly technical summary of 1000 to 1500 words. Focus on preserving the architectural decisions made, current system state, task progress, and critical code details, chat messages, file changes. Under no circumstances exceed MAX 2000 words.",I=u?`Here is the previous summary:
647
+ ${u}
648
+
649
+ Here is the new conversation history:
650
+ ${i}
651
+
652
+ Provide a new consolidated summary of the entire session.`:`Here is the conversation history:
653
+ ${i}
654
+
655
+ Provide a consolidated summary of the entire session.`,h=pe("gemma_janitor_fallback_google");o==="OpenRouter"&&(h=pe("janitor_open_router")),o==="DeepSeek"&&(h=pe("deepseek_level_1")),o==="Mistral"&&(h=pe("mistral_level_1")),o==="NVIDIA"&&(h=pe("nvidia_chat_summarizer_fallback")),o==="InferX"&&(h=pe("inferx_fallback")),o==="SenseNova"&&(h=pe("sensenova_fallback")),o==="AIHubMix"&&(h=pe("aihubmix_fallback")),o==="Poolside"&&(h=pe("poolside_fallback")),(o==="9router"||o==="9Router")&&(h=pe("9router_fallback")),(o==="ExpLabs"||o==="ExperientialLabs")&&(h=pe("explabs_fallback")||"deepseek-v4-pro-0813"),(o==="TokenHarbor"||o==="Token Harbor"||o==="tokenharbor"||o==="token_harbor"||o==="thk")&&(h=pe("tokenharbor_fallback")||"deepseek-v4.1-flash:free");let A=0,$=!1,C=null;for(;A<=3&&!$;){A++;try{C=await ls(e,h,I,w,"Fast"),$=!0}catch{if(A>3){if(o==="Google")try{let _=pe("general_fallback");return(await ls(e,_,I,w,"Fast")).text||""}catch{return""}return""}}}return C&&C.text||""},k=f(t),p=Ct(c,{}),g=p[s]||{summary:"",historyLength:0};typeof g=="string"&&(g={summary:g,historyLength:0});let T=g.summary||"",m=await l(k,T);if(m){g.summary=m;let i=Xa(t);return n?g.historyLength=(g.historyLength||0)+i:g.historyLength=i,p[s]=g,Xn(c,p),m}return null},mf=e=>{try{let t=ie.join(Ro,"chat-summaries.json");if(Ue.existsSync(t)){let n=Ct(t,{});n[e]&&(delete n[e],Xn(t,n))}}catch{}},pf=async function*(e,t,n,s,o){let{profile:c,thinkingLevel:f,mode:l,janitorModel:k,chatId:p,isPlayground:g,systemSettings:T,sessionStats:m,aiProvider:i="Google",apiTier:u,wildcardTooling:w,wildercardTooling:I}=n,h=ft(e);if(!ii&&i==="Google")throw new Error("AI not initialized");let A=process.env.NVIDIA_BASE_URL||n?.aiProvider==="Ollama"||n?.aiProvider==="InferX"||n?.aiProvider==="SenseNova"||n?.aiProvider==="AIHubMix"||n?.aiProvider==="Poolside"||n?.aiProvider==="9router"||n?.aiProvider==="ExpLabs"||n?.aiProvider==="ExperientialLabs"||n?.aiProvider==="TokenHarbor"||n?.aiProvider==="Token Harbor"||n?.aiProvider==="tokenharbor"||n?.aiProvider==="token_harbor"||n?.aiProvider==="thk"||n?.aiProvider==="APInex"||n?.aiProvider==="apinex"||n?.aiProvider==="apx"?!1:T?.memory!==!1,$=t[t.length-1].text,C=ie.join(Ro,"chat-summaries.json"),x=!1,_=t.filter(d=>d.role==="user").length===1,M=$.includes("[TITLE-UPDATE]"),y=_||M,a=$.replace(/\[TITLE-UPDATE\]/g,"").trim();a=a.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),yield{type:"status",content:"[start]"},yield{type:"status",content:"Gathering Context"},await Oo.startTransaction(p,a),T?.advanceRollback&&await lo.takeInitialSnapshot(p),wt=!1;let R=null;try{let d=new AbortController;R=setInterval(()=>{wt&&(d.abort(),R&&(clearInterval(R),R=null))},400);let r=[...t.slice(0,-1)];{let Ke=Ct(C,{})[p]||{summary:"",historyLength:0};if(Ke.summary&&Ke.historyLength>0){let fn=0,ot=[];for(let Fe=0;Fe<r.length;Fe++){let st=r[Fe];(st.role==="user"||st.role==="agent"||st.role==="system")&&!String(st.id).startsWith("welcome")&&!st.isMeta&&fn++,fn>Ke.historyLength&&ot.push(st)}r=ot}}r=r.map(j=>{if(j.role==="user"&&j.text){let Ke=j.text.match(/\[USER\]([\s\S]*?)\[\/USER\]/);if(Ke)return{...j,text:Ke[1].trim()}}return{...j}});let E=process.env.HIGH_CONTEXT,v=process.env.GOOGLE_GEMMA_NONSENSE==="true"||process.env.GOOGLE_GEMMA_NONSENSE===!0||!1,P={"16k":16e3,"32k":32e3,"64k":64e3,"128k":128e3,"256k":256e3,"512k":512e3,"1M":1e6}[T?.contextLength]||256e3;if(E&&E!=="false"){let j=parseInt(E,10);!isNaN(j)&&j>=0&&j<=1e6&&(P=j)}if((i==="NVIDIA"&&(e?.includes("gpt")||e?.includes("qwen")||e?.includes("medium")||e.includes("muse"))||i==="Mistral")&&(P=126e3),i==="Google"&&e?.includes("gemma")&&v&&(P=16e3),(m?.tokens||0)>P){yield{type:"text",content:"\u2726 Maximum Context Limit Reached. Start a new chat."};return}if(_&&A){let j=Ct(vo,{});Object.values(j).flat().length>5&&(yield{type:"status",content:"Condensing past chat memories"},await ol(p,n,j))}let re=Ct(vo,{}),de=Ct(ks,{}),Q=Object.entries(re).filter(([j])=>j!==p).flatMap(([j,Ke])=>Ke),ae=[...Object.entries(de).filter(([j])=>j!==p).slice(-20).map(([j,Ke])=>`[Chat Summary]: ${Ke}`),...Q].map(j=>`- ${j}`).join(`
656
+ `),L=Ct(Wn,[]).map(j=>`- ${j.memory}`).join(`
657
+ `),F=(m?.tokens||0)>=1e4,Ee=new Date,oe=Ee.getFullYear(),B=Ee.toLocaleString("en-US",{month:"short"}).toUpperCase(),G=String(Ee.getDate()).padStart(2,"0"),ye=Ee.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}),Re=`${oe}-${B}-${G}, ${ye}`,ve=`${ye}`,Ie=j=>{try{return Ue.readdirSync(j,{withFileTypes:!0})}catch{return[]}},Dn=Array.from(new Set([...io,...ro(process.cwd())])),nn=(j,Ke=4)=>T?.indentationTree!==!1?Js(j,Ke,1,Ie,Dn):Zs(j,Ke,"",1,Ie,Dn),pt=Ct(Ts,{}),kt=pt[p],Je=kt?kt!==process.cwd():!1;pt[p]=process.cwd(),Xn(Ts,pt);let xe=Ct(C,{}),te=xe[p]||{summary:"",historyLength:0};typeof te=="string"&&(te={summary:te,historyLength:0});let Wt=t.filter(j=>(j.role==="user"||j.role==="agent"||j.role==="system")&&!String(j.id).startsWith("welcome")&&!j.isMeta).length;te.historyLength&&Wt<te.historyLength&&(te.summary="",te.historyLength=0,xe[p]=te,Xn(C,xe));let On=typeof te=="object"?te.summary||"":te||"",Ln=r.length>0;Ln&&On&&r[0]&&(r[0].role==="user"||r[0].role==="system")&&(r[0].text.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")||(r[0].text=`[SYSTEM METADATA]
658
+ **CONTEXT SUMMARY OF PREVIOUS TURNS (PRIORITY: DYNAMIC)**
659
+ ${On}
660
+
661
+ [USER] ${r[0].text}`,yield{type:"summary_injected",content:{id:r[0].id,text:r[0].text}}));let cs=On&&!Ln?`
662
+ [SYSTEM METADATA]
663
+ **CONTEXT SUMMARY OF PREVIOUS TURNS**
664
+ ${On}
665
+ `:"",ai=!!T?.dynamicDirAwareness,Jr=`${p}|${i}|${f}|${e}|${c}|${ai}`,Qr=!ai&&jn.key===Jr&&jn.value?"":`
666
+ **Directory**
667
+ CWD: `+process.cwd()+`${g?" [PLAYGROUND MODE]":""}
668
+ `+nn(process.cwd(),4),yt=await Hn(),dn="";if(zo()&&yt.file_focused!=="none"){dn=`
669
+ [Additional IDE Context]
670
+ `;let j=ie.relative(process.cwd(),yt.file_focused),Ke=(yt.opened_editors||[]).map(ot=>{let Fe=ie.relative(process.cwd(),ot);return Fe.startsWith("..")?`[External] ${ie.basename(ot)}`:Fe});if(dn+=`Focused File: ${j}
671
+ Cursor Line: ${yt.cursor_line}
672
+ `,yt.selected){let ot=yt.selected,Fe=ot.split(`
673
+ `);Fe.length>256&&(ot=Fe.slice(0,240).join(`
674
+ `)+`
675
+ ... [truncated] ...
676
+ `+Fe.slice(-16).join(`
677
+ `)),ot.length>2048&&(ot=ot.slice(0,1920)+`
678
+ ... [truncated] ...
679
+ `+ot.slice(-128)),dn+=`Current Selection: "${ot}"
680
+ `}if(yt.manual_edits){let Fe=yt.manual_edits.split(`
681
+ `),st=[],et=null;for(let K of Fe)K.trim()&&(K.startsWith(" Line ")?et&&et.edits.push(K):(et={path:K.endsWith(":")?K.slice(0,-1):K,edits:[]},st.push(et)));for(let K of st)K.edits.length>80&&(K.edits=K.edits.slice(-80)),K.originalEditsCount=K.edits.length;let rt=(K,We)=>We.reduce((Me,ut)=>{let vt=yt.file_focused&&(ut.path===yt.file_focused||ie.resolve(process.cwd(),ut.path)===ie.resolve(yt.file_focused))?Math.ceil(K*1.2):K;return Me+Math.min(ut.edits.length,vt)},0),Te=80;if(rt(80,st)>300){let K=!1;for(let We=80;We>=10;We--)if(rt(We,st)<=300){Te=We,K=!0;break}K||(Te=10)}let Ve=[...st];if(Te===10&&rt(10,Ve)>500)for(;Ve.length>0&&rt(10,Ve)>500;){let K=0,We=Ve[0].originalEditsCount;for(let Me=1;Me<Ve.length;Me++)Ve[Me].originalEditsCount<We&&(We=Ve[Me].originalEditsCount,K=Me);Ve.splice(K,1)}for(let K of Ve){let Me=yt.file_focused&&(K.path===yt.file_focused||ie.resolve(process.cwd(),K.path)===ie.resolve(yt.file_focused))?Math.ceil(Te*1.2):Te;K.edits.length>Me&&(K.edits=K.edits.slice(-Me))}for(let K of Ve){let We=`${K.path}:
682
+ ${K.edits.join(`
683
+ `)}`;for(;K.edits.length>0&&We.length>4*768;)K.edits.shift(),We=`${K.path}:
684
+ ${K.edits.join(`
685
+ `)}`;We.length>4*768?K.stringRepresentation="... "+We.slice(-(4*768-4)):K.stringRepresentation=We}let sn=Ve.map(K=>K.stringRepresentation).join(`
686
+ `);for(;Ve.length>0&&sn.length>4*2048;){Ve[0].edits.length>0?Ve[0].edits.shift():Ve.shift();for(let K of Ve){let We=`${K.path}:
687
+ ${K.edits.join(`
688
+ `)}`;We.length>4*768?K.stringRepresentation="... "+We.slice(-(4*768-4)):K.stringRepresentation=We}sn=Ve.map(K=>K.stringRepresentation).join(`
689
+ `)}sn.length>4*2048&&(sn="... "+sn.slice(-(4*2048-4))),dn+=`Recent Manual Edits:
690
+ ${sn}
691
+ `}Ke.length>0&&(dn+=`All Opened Editors: ${Ke.join(", ")}`),yt.diagnostics&&(dn+=`
692
+ **Active File Errors**:
693
+ ${yt.diagnostics}
694
+ `),(a.toLowerCase().includes("lint")||a.toLowerCase().includes("warning"))&&yt.warnings&&(dn+=`
695
+ **Lint Warnings**:
696
+ ${yt.warnings}
697
+ `)}let li=a.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),ci=/(?:\\)?@\[([^\]]+)\]/g,ds,fs=[];for(ci.lastIndex=0;(ds=ci.exec(li))!==null;){let j=ds[0].startsWith("\\");fs.push({tag:ds[1],isEscaped:j})}let us=[],To=null;for(let j=0;j<fs.length;j++){let{tag:Ke,isEscaped:fn}=fs[j];if(!fn)try{let ot=Ke.trim().replace(/^["']|["']$/g,""),Fe=/[:#]L?(\d+)(?:-L?(\d+))?$/i,st=ot.match(Fe),et=ot,rt=null,Te=null;st&&(rt=parseInt(st[1],10),Te=st[2]?parseInt(st[2],10):rt,et=ot.slice(0,st.index));let Ve=ie.resolve(process.cwd(),et);if(Ue.existsSync(Ve)&&Ue.statSync(Ve).isFile()){let K=et.toLowerCase(),We=K.endsWith(".pdf"),Me=K.endsWith(".docx")||K.endsWith(".doc")||K.endsWith(".ppt")||K.endsWith(".pptx")||K.endsWith(".xls")||K.endsWith(".xlsx"),ut=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(K),kn=ut||We||Me,vt=i==="Google"||ft(e);if(kn&&!vt){let Ot=`\u2718 Unsupported Modality: ${ie.basename(et)}`,Ye=115;process.stdout.isTTY&&(Ye=process.stdout.columns-5||120);let Se=[Ot],qe=Math.max(...Se.map(un=>un.length)),Sn=Math.min(qe+4,Ye),Pn=Se.map(un=>`${un.padEnd(Sn-2).substring(0,Sn-2)}`).join(`
698
+ `);yield{type:"visual_feedback",content:Yt(`${Pn}
699
+ `)};continue}if(rt===null&&!kn){let Ot=0;try{Ot=Ue.readFileSync(Ve,"utf8").split(/\r\n|\r|\n/).length}catch{}if(Ot>300){let Ye=`\u21B7 Skipped (Too Large): ${ie.basename(et)}`,Se=115;process.stdout.isTTY&&(Se=process.stdout.columns-5||120);let qe=Math.min(Ye.length+4,Se),Sn=Ye.padEnd(qe-2).substring(0,qe-2);yield{type:"visual_feedback",content:Yt(`${Sn}
700
+ `)};continue}}let rn=rt!==null?rt:1,Tn=Te!==null?Te:rt!==null?rt:rn+299;Tn-rn>300&&(Tn=rn+300);let Zn=`path=${JSON.stringify(et)}, startLine=${rn}, endLine=${Tn}`,Qt=await Ri(Zn,{isMultiModal:vt}),xt=!1,Qe="",Dt=null;if(typeof Qt=="string"?Qt.trim().startsWith("ERROR")?xt=!0:Qe=Qt:Qt&&typeof Qt=="object"&&Qt.binaryPart?(Dt=Qt.binaryPart,Qe=Qt.text||""):xt=!0,!xt){let Ot="";if(ut?(Ot=`\u2714 Processed: ${ie.basename(et)}`,To=Dt):We||Me?(Ot=`\u2714 Auto-Analysed: ${ie.basename(et)}`,To=Dt):(Ot=`\u2714 Auto-Read: ${ie.basename(et)}`,us.push(Qe)),Ot){let Ye=115;process.stdout.isTTY&&(Ye=process.stdout.columns-5||120);let Se=[Ot],qe=Math.max(...Se.map(un=>un.length)),Sn=Math.min(qe+4,Ye),Pn=Se.map(un=>`${un.padEnd(Sn-2).substring(0,Sn-2)}`).join(`
701
+ `);yield{type:"visual_feedback",content:Yt(`${Pn}
702
+ `)}}}}}catch{}}let gs="";us.length>0&&(gs=`
703
+ [Tagged File Contents] Auto Read User Tagged files by System, No need to re-read
704
+ `+us.join(`
705
+
706
+ `)+`
707
+ [Tagged File Contents]
708
+ `);let di=li.replace(/\\(@\[[^\]]+\])/g,"$1"),fi=w?`You cannot execute tools. Instead write the action string in chat you WOULD have written
709
+ `:"",Zr=process.env.forcedReasoning||!1,ui=f!=="Fast"&&(i==="Mistral"&&!Io(e)||f!=="High"&&i==="Google")?`${i==="Mistral"&&!Io(e)||e.toLowerCase().startsWith("gemma")||Zr?`[system] strictly follow thinking policy as high priority. do not start a response without <think>...</think> [/system]
710
+ `:""}`:"",So="",gi=!!T?.autoExcludeMetadata,ea=!!(dn||gs||fi||cs||ui||Je||T?.dynamicDirAwareness||T?.autoTruncateResults);gi&&!ea?So=di.trim():So=`[System Metadata]
711
+ Time: ${gi?ve:Re}${Je?`
712
+ WARNING: CWD Changed from previous: "${kt}" to current: "${process.cwd()}", write change in chat to avoid future path mismatches
713
+ `:""}${dn}
714
+ Action format: [action:ActionName(...)]
715
+ [/Metadata]
716
+ ${cs}${ui}${gs}${fi}[user prompt] ${di.trim()} [/user prompt]`.trim();let hi={role:"user",text:So};To&&(hi.binaryPart=To),r.forEach(j=>{j.text&&j.role==="agent"&&(j.text=qt(j.text))}),r.push(hi),cs&&t[t.length-1]?.id&&(yield{type:"summary_injected",content:{id:t[t.length-1].id,text:So}});let Jt=null,wn=l==="Flux"?50:15;wn=l.toLowerCase().includes("cu")?75:wn;let ta=Math.floor(wn/2),mi=0,on=16;yield{type:"status",content:"Connecting"},wt=!1;let hs=[],_o=!1,pi=!1;for(let j=0;j<=wn;j++){let Ke=Math.floor(wn*.95);if(j>=Ke&&mi<Ke&&typeof n?.onAskUser=="function"){mi=Ke;try{let me="Agent has been running for a long time. Do you want to continue execution?",Ae=[{id:"continue",label:"Continue",description:"Add few more steps"},{id:"cancel",label:"Cancel",description:"Stop extending and finish current turn limit"}],ee=await n.onAskUser(me,Ae);ee&&(ee.toLowerCase().includes("continue")||ee==="Continue")&&(wn+=ta)}catch{}}let fn=await _s("agent",n);if(!fn.allowed)throw new Error(fn.reason||`Budget Exhausted for Provider (${i||"Agent"})`);let ot=[];if(_o=!1,l==="ICU"||l==="FluxCU")try{yield{type:"status",content:"Capturing Screen"},await new Promise(ee=>setTimeout(ee,1e3));let{captureGriddedScreenshot:me}=await import("./screen_grid-GBIGOR5Q.js"),Ae=await me();if(Ae&&Ae.base64){let ee="[system] Fresh Gridded Screen Feedback Captured. Use numeric coordinates. Old screenshots will be removed when new screenshot is captured, summarize in text if context is needed later [/system]",Lt={inlineData:{mimeType:Ae.mimeType,data:Ae.base64}},Mt=T?.imageHistoryCU||"Standard",At=Mt==="Low"?1:Mt==="Extended"?5:3,zt=r.filter(Ge=>Array.isArray(Ge.parts)&&Ge.parts.some(Pt=>Pt.inlineData));if(zt.length>=At){let Ge=zt.length-At+1;for(let Pt=0;Pt<Ge;Pt++){let Et=zt[Pt];Array.isArray(Et.parts)&&(Et.parts=Et.parts.filter(Tt=>!Tt.inlineData))}}if(r.length>0&&r[r.length-1].role==="user"){let Ge=r[r.length-1];typeof Ge.text=="string"&&(Ge.text+=`
717
+
718
+ ${ee}`,Array.isArray(Ge.parts)||(Ge.parts=[{text:Ge.text}]),Ge.parts.push(Lt))}else r.push({role:"user",text:ee,parts:[{text:ee},Lt]})}}catch(me){console.error("Vision screenshot capture error:",me)}if(T?.compression===0&&(m?.tokens||0)>P&&(r=Ci(r,6)),j>0?yield{type:"status",content:"Working"}:yield{type:"status",content:"Connecting"},wt){try{let{clearPendingNudges:me}=await import("./subagent_state-LZCOZSUJ.js");me()}catch{}yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
719
+
720
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}try{let{consumePendingNudges:me}=await import("./subagent_state-LZCOZSUJ.js"),Ae=me();if(Ae&&Ae.length>0){let ee=Ae.join(`
721
+
722
+ `);r.length>0&&r[r.length-1].role==="user"?r[r.length-1].text+=`
723
+
724
+ ${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+=`
725
+
726
+ [system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
727
+ [question] ${me.replace("/btw","").trim()} [/question]`:r.push({role:"user",text:`[system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
728
+ [question] ${me.replace("/btw","").trim()} [/question]`}):r.length>0&&r[r.length-1].role==="user"?r[r.length-1].text+=`
729
+
730
+ [STEERING HINT from USER, High Priority] ${me.trim()} [/STEERING HINT]`:r.push({role:"user",text:`[STEERING HINT from USER, High Priority] ${me.trim()} [/STEERING HINT]`}),yield{type:"status",content:`${me.startsWith("/btw")?"Question Forwarded...":"Steering Hint Injected..."}`})}let Fe,st=!1,et=1,rt=1,Te="",Ve=null,sn=null,K=null,We=0,Me=[],ut=0,kn=!1,vt=!1,rn=!1,Tn=!1,Zn=!0,Qt=0,xt="",Qe="",Dt=!1,Ot=!1,Ye=!0,Se=e,qe="";for(;et<=on&&rt<=on&&!st&&!wt;){let me=!1;try{Te="",Zn&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},Zn=!1,rt===1&&(xt=""));let Ae=D=>{if(!D||!D.includes("[tool:"))return D;let Y="",W=oi(D);W&&(Y=W.fullBlock,D=W.remainingText),D=D.replace(qa,(z,le)=>le.includes("[tool:")?le.trim():z);let q="",Z=0;for(;Z<D.length;){let z=D.indexOf("[tool:",Z);if(z===-1){q+=Gr(D.substring(Z));break}let le=D.substring(Z,z);q+=Gr(le);let ht=-1,N=null,V=0;for(let be=z;be<D.length;be++){let b=D[be];if(N){if(b===N){let Be=0;for(let fe=be-1;fe>=0&&D[fe]==="\\";fe--)Be++;Be%2===0&&(N=null)}}else if(b==='"'||b==="'"||b==="`")N=b;else if(b==="(")V++;else if(b===")")V--;else if(b==="]"&&V<=0){ht=be;break}}if(ht===-1){q+=D.substring(z);break}q+=D.substring(z,ht+1),Z=ht+1}return(T?.keepReasoningContext?Y:"")+q},ee=r.filter(D=>(D.role==="user"||D.role==="agent"||D.role==="system")&&!String(D.id).startsWith("welcome")&&!D.isMeta&&!D.isTerminalRecord&&!(D.text&&D.text.startsWith("[TERMINAL_RECORD]"))).map((D,Y,W)=>{let q=D.text||"";A||(q=q.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),D.role==="agent"&&(q=Ae(q),q=q.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),q=q.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*"));let Z=[];return Array.isArray(D.parts)&&D.parts.length>0?Z=D.parts.map(z=>{if(z.text){let le=z.text;return A||(le=le.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),D.role==="agent"&&(le=Ae(le),le=le.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),le=le.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*")),{text:le}}return z}):Z=[{text:q}],D.binaryPart&&ft(Se)&&W.slice(Y+1).filter(le=>le.role==="user"&&!le.text?.startsWith("[ACTION RESULT]")&&!le.text?.startsWith("[TOOL RESULT]")).length<=2&&Z.push(D.binaryPart),{role:D.role==="user"||D.role==="system"?"user":"model",parts:Z}});for(let D=0;D<ee.length;D++){let Y=ee[D],W=Y.parts?.[0]?.text||"";if(Y.role==="model"&&/\[(?:tool|action):/i.test(W)){let q=-1;for(let Z=D+1;Z<ee.length;Z++){let z=ee[Z],le=z.parts?.[0]?.text||"";if(z.role==="user"&&(le.startsWith("[ACTION RESULT]")||le.startsWith("[TOOL RESULT]"))){q=Z;break}}if(q!==-1&&q!==D+1){let[Z]=ee.splice(q,1);ee.splice(D+1,0,Z)}}}for(let D=ee.length-2;D>=0;D--){let Y=ee[D],W=ee[D+1];Y.role==="user"&&W.role==="user"&&(W.parts?.[0]?.text||"").trim().startsWith("[SYSTEM")&&ee.splice(D,1)}let Lt=[];for(let D=0;D<ee.length;D++){let Y=ee[D];if(Lt.length===0)Lt.push(Y);else{let W=Lt[Lt.length-1];W.role===Y.role?(W.parts[0].text+=`
731
+
732
+ `+(Y.parts?.[0]?.text||""),Y.parts?.length>1&&W.parts.push(...Y.parts.slice(1))):Lt.push(Y)}}ee.length=0,ee.push(...Lt),Se=e;let Mt=`${p}|${i}|${l}|${f}|${Se}|${JSON.stringify(c)}|${!!T?.dynamicDirAwareness}|${!!T?.subAgents}`,At=jn.key===Mt&&jn.value;if((process.env.I_HAVE_TOO_MUCH_MONEY==="true"||process.env.I_HAVE_TOO_MUCH_MONEY===!0)&&(At=!1),At)qe=jn.value;else{let D=i==="Mistral"?!!Io(Se):!(Se||"gemma").toLowerCase().startsWith("gemma");qe=fr(c,((Se||"gemma").toLowerCase().startsWith("gemma"),f),l,T,A,_,i,i==="Google"?!0:h,D,p,!!T?.keepReasoningContext,Se),T?.dynamicDirAwareness||(qe+=`
733
+ ${Qr.replace(`
734
+ **Directory**`,`
735
+ -- Directory --`)}`),jn.key=Mt,jn.value=qe}let Ge=ee[ee.length-1];if(zo()&j>0){await new Promise(W=>setTimeout(W,2500)),yield{type:"status",content:"Verifying"};let D=await Hn(),Y=D?D.diagnostics:null;Y&&Ge&&Ge.role==="user"&&Ge.parts?.[0]?.text&&(Ge.parts[0].text+=`
736
+ ${Y} [/ERROR]`),yield{type:"status",content:"Working"}}let Pt=i==="Mistral"||i==="Google"&&e?.toLowerCase().startsWith("gemma");if(T?.advanceRollback&&Ge&&Ge.role==="user"&&(Ge.parts?.[0]?.text?.startsWith("[ACTION RESULT]")||Ge.parts?.[0]?.text?.startsWith("[TOOL RESULT]")))try{let D=await lo.getLatestFileChanges(p);if(D&&(D.newFiles.length>0||D.modifiedFiles.length>0||D.deletedFiles.length>0)){let Y=`
737
+ [system] File Changes:
738
+ `;for(let q of D.newFiles)Y+=`* ${q} (created)
739
+ `;for(let q of D.modifiedFiles)Y+=`* ${q} (modified)
740
+ `;for(let q of D.deletedFiles)Y+=`* ${q} (deleted)
741
+ `;Y+="[/system]",Ge.parts[0].text+=Y;let W=-1;for(let q=r.length-1;q>=0;q--)if(r[q].role==="user"&&(r[q].text?.startsWith("[ACTION RESULT]")||r[q].text?.startsWith("[TOOL RESULT]"))){W=q;break}W!==-1&&(r[W].text+=Y)}}catch{}let Et=Math.floor(wn*.99),Tt=j+1;Tt>=Et&&Ge&&Ge.parts?.[0]&&(Ge.parts[0].text+=`
742
+ [system] WARNING, Turn Limit Impending: Step ${Tt}/${wn}. Wrap up quickly/prompt user to continue. [/system]`);let It=new Promise((D,Y)=>{d.signal.aborted&&Y(new DOMException("The user aborted a request.","AbortError")),d.signal.addEventListener("abort",()=>{Y(new DOMException("The user aborted a request.","AbortError"))})});It.catch(()=>{});let gt=ee;if(i==="Ollama")Fe=ei(n.apiKey,Se,gt,qe,f,l,h,d.signal,1,T?.ollamaEndpoint||"Cloud");else if(i==="OpenRouter")Fe=es(n.apiKey,Se,gt,qe,f,l,h,d.signal,1,p);else if(i==="DeepSeek")Fe=Jo(n.apiKey,Se,gt,qe,f,l,h,d.signal,1);else if(i==="Mistral")Fe=Qo(n.apiKey,Se,gt,qe,f,l,h,d.signal,1,p);else if(i==="NVIDIA"){let D=Zo(n.apiKey,Se,gt,qe,f,l,h,d.signal,1);Fe=Fr(D,Se)}else if(i==="InferX")Fe=ts(n.apiKey,Se,gt,qe,f,l,h,d.signal,1);else if(i==="SenseNova")Fe=ns(n.apiKey,Se,gt,qe,f,l,h,d.signal,1);else if(i==="AIHubMix")Fe=os(n.apiKey,Se,gt,qe,f,l,h,d.signal,1);else if(i==="Poolside")Fe=ss(n.apiKey,Se,gt,qe,f,l,h,d.signal,1);else if(i==="9router"||i==="9Router")Fe=is(n.apiKey,Se,gt,qe,f,l,h,d.signal,1);else if(i==="ExpLabs"||i==="ExperientialLabs")Fe=rs(n.apiKey,Se,gt,qe,f,l,h,d.signal,1);else if(i==="TokenHarbor"||i==="Token Harbor"||i==="tokenharbor"||i==="token_harbor"||i==="thk")Fe=ti(n.apiKey,Se,gt,qe,f,l,h,d.signal,1);else if(i==="APInex"||i==="apinex"||i==="apx")Fe=ni(n.apiKey,Se,gt,qe,f,l,h,d.signal,1);else{let D=ri(n?.apiKey),{serviceTier:Y,cleanModel:W}=Xr(Se),q={systemInstruction:qe,mediaResolution:"MEDIA_RESOLUTION_HIGH",safetySettings:[{category:In.HARM_CATEGORY_HARASSMENT,threshold:Mn.BLOCK_NONE},{category:In.HARM_CATEGORY_HATE_SPEECH,threshold:Mn.BLOCK_NONE},{category:In.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Mn.BLOCK_NONE},{category:In.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Mn.BLOCK_NONE}],temperature:1.05,thinkingConfig:(()=>{let z=He("Google",Se||"gemini-3-flash-preview",f);if(z!==null){if(typeof z=="object")return z;if(z===!1||z==="false"||z==="none"||z===0||z==="0")return{includeThoughts:!1};if(typeof z=="number")return{includeThoughts:!0,thinkingBudget:z};if(typeof z=="string"){let V=z.toLowerCase();if(V==="minimal")return{includeThoughts:!0,thinkingLevel:Xe.MINIMAL};if(V==="low")return{includeThoughts:!0,thinkingLevel:Xe.LOW};if(V==="medium")return{includeThoughts:!0,thinkingLevel:Xe.MEDIUM};if(V==="high")return{includeThoughts:!0,thinkingLevel:Xe.HIGH};let be=Number(z);if(!isNaN(be))return{includeThoughts:!0,thinkingBudget:be}}}let le=(Se||"").toLowerCase(),ht=le.includes("gemma-4")||le.startsWith("gemma"),N=le.includes("gemini-3");if(ht||N)return ht?f.toLowerCase()!=="high"?{includeThoughts:!1,thinkingLevel:Xe.MINIMAL}:{includeThoughts:!0,thinkingLevel:Xe.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:le.includes("pro")?Xe.LOW:Xe.MINIMAL,Low:Xe.LOW,Medium:Xe.MEDIUM,Standard:Xe.MEDIUM,High:Xe.HIGH,xHigh:Xe.HIGH}[f]||Xe.MEDIUM};{let V={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[f]||2048;return V===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:V}}})()};Y&&(q.serviceTier=Y);let Z=D.models.generateContentStream({model:W||"gemini-3-flash-preview",contents:gt,config:q},{signal:d.signal});Fe=await Promise.race([Z,It])}Te="",Ve=null,K=null,Me=[],ut=0,yield{type:"model_update",content:null},Qe="",Dt=xt.length>0;let an="",ms=Date.now(),Nn=async function*(){if(i==="Google"&&an){let D=to(an);for(let Y of D)yield Y;an="",ms=Date.now()}},yi=!0,Fn="",Vn=!1,St=null,xi=!1,Yn=!1,qn=!1,Ao=!1,_n=!1,eo=D=>{let Y=0;for(;Y+2<D.length;)D[Y]==="`"&&D[Y+1]==="`"&&D[Y+2]==="`"?(Ao=!Ao,Y+=3):Y++},bi=D=>{if(!D)return;let Y=/(?:<(\/?)(?:think|thought|thoughts)[^>]*>|\[(\/?)(?:think|thought|thoughts)\]|<\/?channel\|?>|<\|channel>thought)/gi,W;for(;(W=Y.exec(D))!==null;){let q=W[0].toLowerCase();q.startsWith("</")||q.startsWith("[/")||q==="<channel|>"?_n=!1:_n=!0}},sa={tool:{startPrefix:"[tool",fullPrefix:"[tool:",endTag:"]"},action:{startPrefix:"[action",fullPrefix:"[action:",endTag:"]"},end:{startPrefix:"[[END]]",fullPrefix:"[[END]]",endTag:"[[END]]"},kimi_section:{startPrefix:"<|tool_calls_section_begin|>",fullPrefix:"<|tool_calls_section_begin|>",endTag:"<|tool_calls_section_end|>"},kimi_call:{startPrefix:"<|tool_call_begin|>",fullPrefix:"<|tool_call_begin|>",endTag:"<|tool_call_end|>"}},to=D=>{let Y=[],W=D,q=Z=>{if(!Z)return;if(!xi){Y.push({type:"text",content:Z}),eo(Z),bi(Z);return}let z=/(?:<(\/?)(?:think|thought|thoughts)[^>]*>|\[(\/?)(?:think|thought|thoughts)\]|<\/?channel\|?>|<\|channel>thought)/gi,le=0,ht;for(;(ht=z.exec(Z))!==null;){let V=Z.substring(le,ht.index);if(V)if(eo(V),_n)Y.push({type:"text",content:V});else{let Be=V.replace(/[^\n]/g,"");Be&&Y.push({type:"text",content:Be})}let be=ht[0];eo(be);let b=be.toLowerCase();b.startsWith("</")||b.startsWith("[/")||b==="<channel|>"?_n=!1:_n=!0,Y.push({type:"text",content:be}),le=z.lastIndex}let N=Z.substring(le);if(N)if(eo(N),_n)Y.push({type:"text",content:N});else{let V=N.replace(/[^\n]/g,"");V&&Y.push({type:"text",content:V})}};for(;W.length>0;)if(Vn){let Z=Fn+W,z=sa[St];if(z){let N=!1;if(Z.length<z.startPrefix.length?z.startPrefix.startsWith(Z)||(N=!0):Z.startsWith(z.startPrefix)?Z.length>=z.fullPrefix.length&&!Z.startsWith(z.fullPrefix)&&(N=!0):N=!0,N){q(Z),Fn="",Vn=!1,St=null,Yn=!1,qn=!1,W="";break}}let le=-1,ht=z?z.endTag:"]";if(St==="tool"||St==="action"){let N=0,V=null,be=0,b=!1;for(let Be=0;Be<Z.length;Be++){let fe=Z[Be];if(V){if(fe===V){let X=0;for(let $t=Be-1;$t>=0&&Z[$t]==="\\";$t--)X++;X%2===0&&(V=null)}}else if(fe==='"'||fe==="'"||fe==="`")V=fe;else if(fe==="(")N++,b=!0;else if(fe===")")N--;else if(fe==="[")be++;else if(fe==="]"){if(b&&N===0&&be===1){le=Be;break}be--}}}else le=Z.indexOf(ht);if(le!==-1){let N=ht.length,V=Z.substring(0,le+N);St?.startsWith("kimi")||Y.push({type:"text",content:V}),eo(V),bi(V),(St==="tool"||St==="action"||St?.startsWith("kimi"))&&!Yn&&!qn&&(xi=!0),Yn=!1,qn=!1,Fn="",Vn=!1,St=null,W=Z.substring(le+N)}else{let N=St?.startsWith("kimi")?8192:512;Z.length>N?(q(Z),Fn="",Vn=!1,St=null,Yn=!1,qn=!1):Fn=Z,W="";break}}else{let Z=W.indexOf("[tool"),z=W.indexOf("[action"),le=W.indexOf("[[END]]"),ht=W.indexOf("<|tool_calls_section_begin|>"),N=W.indexOf("<|tool_call_begin|>"),V=[{type:"tool",idx:Z,start:"[tool",end:"]"},{type:"action",idx:z,start:"[action",end:"]"},{type:"end",idx:le,start:"[[END]]",end:"[[END]]"},{type:"kimi_section",idx:ht,start:"<|tool_calls_section_begin|>",end:"<|tool_calls_section_end|>"},{type:"kimi_call",idx:N,start:"<|tool_call_begin|>",end:"<|tool_call_end|>"}].filter(be=>be.idx!==-1).sort((be,b)=>be.idx-b.idx);if(V.length>0){let be=V[0],b=W.substring(0,be.idx);be.idx>0&&q(b);let Be=be.idx>0?W[be.idx-1]:"";Yn=Ao||Be==="`",qn=_n,Vn=!0,St=be.type,Fn="",W=W.substring(be.idx)}else{let be=["[tool","[action","[[END]]","<|tool_calls_section_begin|>","<|tool_call_begin|>"],b=-1;for(let Be of be){for(let fe=Be.length-1;fe>0;fe--)if(W.endsWith(Be.substring(0,fe))){b=W.length-fe;let X=be.indexOf(Be);X===0?St="tool":X===1?St="action":X===2?St="end":X===3?St="kimi_section":St="kimi_call";break}if(b!==-1)break}if(b!==-1){if(b>0){let fe=W.substring(0,b);q(fe)}let Be=b>0?W[b-1]:"";Yn=Ao||Be==="`",qn=_n,Vn=!0,Fn=W.substring(b),W=""}else{q(W);break}}}return Y},ia=Fe[Symbol.asyncIterator]();for(;;){let{value:D,done:Y}=await Promise.race([ia.next(),It]);if(Y)break;if(D&&D.type==="status"){yield D;continue}let W="",q=D.candidates?.[0]?.content?.parts;if(q&&q.length>0)for(let z of q){let le=typeof z.text=="string"?z.text:z.text?parseChunkText(z.text):"";z.thought?le&&(me||(W+="<think>",me=!0),W+=le):le&&(me&&(W+="</think>",me=!1),W+=le)}else D.text&&me&&(W+="</think>",me=!1);W=ja(W);let Z=W?As(W):0;if(n&&typeof n.onTokenChunk=="function"&&n.onTokenChunk(W,Z),yi&&(yield{type:"status",content:"Thinking"},yi=!1),wt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
743
+
744
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(W){if(Dt){if(Qe+=W,Qe.length>=64){let N=0,V=Math.min(xt.length,Qe.length);for(let b=V;b>=10;b--)if(xt.endsWith(Qe.substring(0,b))){N=b;break}let be=Qe.substring(N);if(be){let Be=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(xt)?be.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):be.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(Be)if(Te+=Be,i==="Google")an+=Be;else{yield*Nn();let fe=to(Be);for(let X of fe)yield X}}Dt=!1,Qe=""}continue}else if(Te+=W,i==="Google")an+=W;else{yield*Nn();let N=to(W);for(let V of N)yield V}let z=Qa(Te);if(z.inside){Ot=!0,K||(K=Date.now());let V={Ask:"ask",AskUser:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",FindFile:"find_file",find_file:"find_file",findfile:"find_file",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Cancel:"cancel",Await:"await",Answer:"answer",Steer:"steer",steer:"steer"}[z.toolName]||z.toolName,be=z.args||"",b=null;if(["write_file","update_file","view_file","read_folder","find_file","write_pdf","write_docx","search_keyword","generate_image","file_map","invoke","invoke_sync","get_progress","await","answer"].includes(V)){let fe=ne(be),X=fe.basename||fe.name||fe.path||fe.targetFile||fe.TargetFile||fe.directory||fe.file,$t=fe.keyword,Bn=fe.title||fe.task,An=fe.id||fe.taskId,Le=fe.timeout||fe.time;if($t!=null)b=String($t).replace(Gn,"");else if(X)b=ie.basename(String(X).replace(Gn,"").replace(Br,"/"));else if(Bn&&(V==="invoke"||V==="invoke_sync"))b=String(Bn).replace(Gn,"").substring(0,30);else if(An&&V==="get_progress")b=String(An).replace(Gn,"");else if(Le&&V==="await"){let Nt=parseFloat(String(Le).replace(Gn,""));isNaN(Nt)?b=String(Le).replace(Gn,""):(Nt<5&&(Nt=5),Nt>120&&(Nt=120),b=(gn=>{if(gn>=60){let ys=Math.floor(gn/60),zn=gn%60;return`${ys}m${zn>0?` ${zn}s`:""}`}return`${gn}s`})(Nt))}else{let Nt=be.match(Wa);if(Nt){let Ht=Nt[1].replace(Gn,"");V==="invoke"||V==="invoke_sync"||V==="get_progress"?b=Ht.substring(0,30):b=V==="search_keyword"||V==="file_map"?Ht:ie.basename(Ht.replace(Br,"/"))}}}let Be=`${si[V]||V}${b?` ${b}`:""}`;if((V!==Ve||b!==sn)&&(Ve=V,sn=b,yield{type:"status",content:`${Be}`},process.stdout.isTTY)){let X={WebSearch:"Searching",web_search:"Searching",WebScrape:"Reading",web_scrape:"Reading",ReadFile:"Reading",read_file:"Reading",ReadFolder:"Reading",read_folder:"Reading",WriteFile:"Writing",write_file:"Writing",UpdateFile:"Editing",update_file:"Editing",WritePdf:"Creating",write_pdf:"Creating",WriteDocx:"Creating",write_docx:"Creating",SearchKeyword:"Searching",search_keyword:"Searching",CodeSearch:"Searching",code_search:"Searching",FindFile:"Finding File",find_file:"Finding File",Run:"Executing",Ask:"User Input Required",AskUser:"User Input Required",Memory:"Updating Memory",GenerateImage:"Generating",InvokeSync:"Sub-Agent Working",invoke_sync:"Sub-Agent Working",Invoke:"Working",invoke:"Working",GetProgress:"Checking Progress",get_progress:"Checking Progress",Cancel:"Stopping Generalist",cancel:"Stopping Generalist",Await:"Waiting",await:"Waiting",EmergencyRollback:"Rolling the Ball",Answer:"Answering Sub-Agent",answer:"Answering Sub-Agent",Steer:"Steering Sub-Agent",steer:"Steering Sub-Agent",Click:"Clicking",click:"Clicking",Drag:"Dragging",drag:"Dragging",Scroll:"Scrolling",scroll:"Scrolling",KeyboardTyping:"Typing",keyboard_typing:"Typing",KeyPress:"Pressing Key",key_press:"Pressing Key",RecaptureScreen:"Recapturing Screen",recapture_screen:"Recapturing Screen"}[V]||"Working";process.stdout.write(`\x1B]0;${X}...\x07`)}}if(Te.length-Qt>150){Qt=Te.length;let N=zr(Te,!1),V=oi(N),be=V?(V.innerContent||"").trim():"",b=be.split(/[.!?]\s+/),Be=new Set(b),fe=b.length>10?(b.length-Be.size)/b.length:0,X=be.split(/\s+/).filter(Pe=>Pe.length>0).length,$t=.6,Bn=.8,An=!1;if(i.toLowerCase().includes("google")&&(Se||"").toLowerCase().startsWith("gemma")){let S={low:256,medium:1024,high:8192,max:16384,xhigh:16384}[f?.toLowerCase()]||2500;An=X>S}if(fe>$t||An){yield{type:"status",content:`${fe>$t?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},vt=!0,await new Promise(S=>setTimeout(S,3e3));break}let Ht=jr(Te).trim().split(/[.!?]\s+/),gn=new Set(Ht);if((Ht.length>10?(Ht.length-gn.size)/Ht.length:0)>Bn){yield{type:"status",content:"Response Loop Detected. Re-centering..."},vt=!1,Tn=!0,await new Promise(Pe=>setTimeout(Pe,3e3));break}let zn=N.replace(La,"").replace(Pa,"").replace($a,"").replace(Na,""),Ft=zn.toLowerCase().split(/\s+/).map(Pe=>Pe.replace(Fa,"")).filter(Pe=>Pe.length>0),hn=!1;if(Ft.length>=10)for(let Pe=1;Pe<=15;Pe++){let S=Math.max(3,Math.ceil(10/Pe));if(Ft.length<Pe*S)continue;let H=Ft.slice(Ft.length-Pe),se=H.join(" ");if(Pe>1&&se===H.slice(0,Math.floor(Pe/2)).join(" ").repeat(2).trim())continue;let ge=!0;for(let we=1;we<S;we++)if(Ft.slice(Ft.length-Pe*(we+1),Ft.length-Pe*we).join(" ")!==se){ge=!1;break}if(ge){hn=!0;break}}if(!hn){let Pe=zn.toLowerCase().replace(Ba,"");if(Pe.length>=20)for(let S=1;S<=10;S++){let H=Math.max(5,Math.ceil(16/S));if(Pe.length<S*H)continue;let se=Pe.substring(Pe.length-S),ge=!0;for(let we=1;we<H;we++)if(Pe.substring(Pe.length-S*(we+1),Pe.length-S*we)!==se){ge=!1;break}if(ge){hn=!0;break}}}if(hn){yield{type:"status",content:"Stuttering Detected. Re-centering..."},vt=!1,rn=!0,await new Promise(Pe=>setTimeout(Pe,3e3));break}}let le=qt(Te),ht=ko(le);for(;ht.length>ut;){yield*Nn();let N=ht[ut],V=Date.now(),b={Ask:"ask",AskUser:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",FindFile:"find_file",find_file:"find_file",findfile:"find_file",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Await:"await",await:"await",AwaitSubagent:"await",awaitSubagent:"await",Answer:"answer",answer:"answer",AnswerSubagent:"answer",answerSubagent:"answer",Steer:"steer",steer:"steer",SteerSubagent:"steer",steerSubagent:"steer",Cancel:"cancel",cancel:"cancel",Click:"click",click:"click",Drag:"drag",drag:"drag",Scroll:"scroll",scroll:"scroll",KeyboardTyping:"keyboard_typing",keyboard_typing:"keyboard_typing",KeyPress:"key_press",key_press:"key_press",RecaptureScreen:"recapture_screen",recapture_screen:"recapture_screen",EmergencyRollback:"EmergencyRollback"}[N.toolName]||N.toolName,Be=si[b]||N.toolName,fe=Kn(b,N.args);yield{type:"status",content:`${Be}${fe?` ${fe}`:""}`};let X="";if(b==="click"){let S=ne(N.args);X=`\u2714 Clicked: ${S.intendedClickText?`${S.intendedClickText}`:""}`}else if(b==="drag"){let S=ne(N.args);X=`\u2714 Dragged: Cell ${S.fromGridId||""} \u2192 Cell ${S.toGridId||""}`}else if(b==="scroll"){let S=ne(N.args);X=`\u2714 Scrolled: ${S.direction||"down"} (${S.amount||1})`}else if(b==="keyboard_typing"){let S=ne(N.args);X=`\u2714 Typed: ${S.text?`"${S.text.length>20?S.text.substring(0,20)+"...":S.text}"`:""}`}else if(b==="key_press")X=`\u2714 Pressed Key: ${ne(N.args).key||""}`;else if(b==="recapture_screen")X="\u2714 Recaptured Screen";else if(b==="web_search"){let{query:S,limit:H=10,aiMode:se=!1}=ne(N.args);X=`${S?"\u2714":"\u2718"} ${se?"AI Search":"Searched"}: ${S?`${S}`:"No Search Query"}${se===!1&&S?` \u2192 ${H}`:""}`}else if(b==="web_scrape"){let S=ne(N.args).url||null;X=`${S?"\u2714":"\u2718"} Visited: ${S||"No Source"}`}else if(b==="view_file"){let{path:S,StartLine:H,EndLine:se,start_line:ge,end_line:we,startLine:Ne,endLine:De}=ne(N.args),Ce=H||ge||Ne,J=se||we||De,ce=parseInt(Ce)||1,ue=parseInt(J)||(Ce?ce+800:800),je="...",ze=ue,he=(S||"").trim().toLowerCase().replaceAll("\\","/");if(he.startsWith("#skill"))he.startsWith("#skill/global/fluxflow")||he.startsWith("#skills/global/fluxflow")||he.includes("#skill/fluxflow")||he.includes("#skills/fluxflow")?X="\u2714 Read Documentation":X=`\u2714 Read Skill: ${ie.basename(S.replaceAll("\\","/"))}`;else{try{let _e=ie.resolve(process.cwd(),S);if(Ue.existsSync(_e)){let bt=Ue.readFileSync(_e,"utf8").split(`
745
+ `).length;je=bt,!Ce&&!J&&bt>800?ze=Math.min(50,bt):ze=Math.min(ue,bt)}}catch{}let Oe=(S||"").toLowerCase(),mt=Oe.endsWith(".pdf"),$e=Oe.endsWith(".docx")||Oe.endsWith(".doc")||Oe.endsWith(".ppt")||Oe.endsWith(".pptx")||Oe.endsWith(".xls")||Oe.endsWith(".xlsx"),tt=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(Oe);mt||$e?X=`${S.length>0?"\u2714":"\u2718"} ${S?`Analyzed: ${ie.basename(S)}`:"Analyzed: File Not Found"}`:tt?X=`${S.length>0?"\u2714":"\u2718"} ${S?`Processed: ${ie.basename(S)}`:"Processed: File Not Found"}`:X=`${je!=="..."?"\u2714":"\u2718"} Read: ${S?`${ie.basename(S)} \u2192 ${je!=="..."?`Lines ${ce} - ${ze} of ${je}`:"File Not Found"}`:"File Not Found"}`}}else if(b==="list_files"||b==="read_folder"){let S=b==="list_files"?"List":"Browsed",H=ne(N.args).path||null,se=ne(N.args).recurse||1;X=`${H?"\u2714":"\u2718"} ${S}: ${H?`${H==="."?`./${se>1?"*":""}`:`${H.replaceAll("\\","/")}${se>1?`${H.endsWith("/")?"*":"/*"}`:`${H.endsWith("/")?"":"/"}`}`}`:"No Folder Selected"}`}else if(b==="find_file"){let S=ne(N.args),H=S.basename||S.name||S.path||S.file||S.query||"";X=`${H?"\u2714":"\u2718"} Located: ${H||"No Query"}`}else if(b==="write_file"||b==="update_file"){let S=b==="write_file"?"Created":"Edited",H=ne(N.args),se=H.path||null,we=Object.entries(H).some(([Ne,De])=>Ne.startsWith("searchContent")&&typeof De=="string"&&De.startsWith("^LINE:"))?"\u1361":":";X=`${se?"\u2714":"\u2718"} ${S}${we} ${se?se.replaceAll("\\","/"):"No File Changes"}`}else if(b==="write_pdf"){let S=ne(N.args).path||null;X=`${S?"\u2714":"\u2718"} Generated: ${S.replaceAll("\\","/")||"No PDF Generated"}`}else if(b==="write_docx"){let S=ne(N.args).path||null;X=`${S?"\u2714":"\u2718"} Generated: ${S.replaceAll("\\","/")||"No Docx Generated"}`}else if(b==="file_map"){let S=ne(N.args).path;X=`${S?"\u2714":"\u2718"} Indexed: ${S.replaceAll("\\","/")?""+S:"File Not Found"}`}else if(b.toLowerCase()==="search_keyword"||b.toLowerCase()==="todo")X="";else if(b.toLowerCase()==="generate_image"){let{path:S,outputPath:H,output:se}=ne(N.args);X=`\u2714 Generated: ${S||H||se||"generated_image.png"}`}else if(b==="invoke_sync"||b==="InvokeSync"){let S=Kn(b,N.args);X=`\u2714 Called Generalist${S?`: ${S}`:""}`}else if(b==="Invoke"||b==="InvokeAsync"||b==="invoke"){let S=Kn(b,N.args);X=`\u2714 Started Generalist${S?`: ${S}`:""}`}else if(b==="get_progress"||b==="GetProgress"){let S=Kn(b,N.args);X=`\u2714 Checked${S?`: ${S}`:""}`}else if(b==="cancel"){let S=Kn(b,N.args);X=`\u{1F6C7} Cancelled${S?`: ${S}`:""}`}else if(b==="steer"||b==="Steer"){let S=Kn(b,N.args);X=`\u2714 Steered${S?`: ${S}`:""}`}else if(b==="EmergencyRollback"){let{method:S}=ne(N.args);X=S==="forceRevert"?"":"\u2714 Rollback Point Checked"}else if(b==="await"||b==="Await"){let{time:S,timeout:H}=ne(N.args),se=parseFloat(H||S)||0;se||(se=120);let ge=De=>{if(De>=60){let Ce=Math.floor(De/60),J=De%60;return`${Ce}m${J>0?` ${J}s`:""}`}return`${De}s`},we=["Aligning Moon Phase","Contemplating Existence","Staring At Void","Delaying Professionally","Negotiating With Electrons","Touching Grass (virtually)","Panicking Softly","Rethinking Career Choices","Loading Cat Videos","Summoning Braincell #2","Pretending To Be Busy","Waiting For Motivation DLC","Rotating Internal Screaming","Downloading More RAM","Feeding The Hamsters","Gaslighting Scheduler","Performing Dramatic Pause","Buffering Social Energy","Calculating Regret","Reading Terms And Conditions","Becoming Sentient Briefly","Contacting Ancestors"];X=`\u2714 ${we[Math.floor(Math.random()*we.length)]} \u2192 ${ge(se)}`}else b==="Answer"||b==="answer"?X="\u2714 Resolved Sub-Agent Query":b==="exec_command"||b==="ask"?X="":X=`Executed: ${N.toolName}`;if(yield*Nn(),b==="exec_command"){let{command:S}=ne(N.args);if(S&&n.systemSettings&&n.systemSettings.allowExternalAccess===!1){let H=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],se=ie.resolve(process.cwd()).substring(0,3).toLowerCase(),ge=J=>{let ce=[],ue="",je=null;for(let ze=0;ze<J.length;ze++){let he=J[ze];je?(he===je&&(je=null),ue+=he):he==='"'||he==="'"?(je=he,ue+=he):he==="&"&&J[ze+1]==="&"||he==="|"&&J[ze+1]==="|"?(ue.trim()&&(ce.push(ue.trim()),ue=""),ze++):he===";"||he==="|"||he==="&"?ue.trim()&&(ce.push(ue.trim()),ue=""):ue+=he}return ue.trim()&&ce.push(ue.trim()),ce},we=J=>{let ce=[],ue="",je=null;for(let ze=0;ze<J.length;ze++){let he=J[ze];je?(he===je&&(je=null),ue+=he):he==='"'||he==="'"?(je=he,ue+=he):/\s/.test(he)?ue&&(ce.push(ue),ue=""):ue+=he}return ue&&ce.push(ue),ce},Ne=J=>{let ce=J.replace(/^['"]|['"]$/g,"").trim();return!ce||process.platform==="win32"&&/^\/[a-zA-Z0-9?]+$/.test(ce)?!1:H.some(ue=>{if(ue.source==="[a-zA-Z]:[\\\\\\/]"){let je=ce.match(/[a-zA-Z]:[\\\/]/i);return je&&je[0].toLowerCase()!==se}return ue.test(ce)})};if(ge(S).some(J=>{let ce=we(J);if(ce.length===0)return!1;let ue=ce[0].replace(/^['"]|['"]$/g,"").toLowerCase();if(["echo","printf","write-output"].includes(ue)){let ze=!1;return ce.some(he=>{let _t=he.replace(/^['"]|['"]$/g,"");if(_t===">"||_t===">>"||_t==="<")return ze=!0,!1;if(_t.startsWith(">")||_t.startsWith("<")){let Oe=_t.replace(/^[><]+/,"");return Ne(Oe)}return ze?(ze=!1,Ne(he)):!1})}return ce.some(ze=>Ne(ze))})){let J='Access Denied. Prohibited from accessing external directories while "External Workspace Access" is disabled.';n.onExecStart&&n.onExecStart(S||"No Command"),yield{type:"exec_start"},await new Promise(ce=>setTimeout(ce,50)),n.onExecChunk&&n.onExecChunk(`ERROR: ${J}`),await new Promise(ce=>setTimeout(ce,50)),n.onExecEnd&&n.onExecEnd(),Me.push({role:"user",text:`[ACTION RESULT]: ERROR: ${J}`}),yield{type:"tool_result",content:`[ACTION RESULT]: ERROR: ${J}`},ut++;continue}}n.onExecStart&&n.onExecStart(S||"No Command"),yield{type:"exec_start"}}let $t=ne(N.args),Bn=$t.path||$t.targetPath||null;if(Bn){let S=n.systemSettings&&n.systemSettings.allowExternalAccess===!1,H=ie.resolve(Bn),se=ie.resolve(process.cwd());if(S&&!H.startsWith(se)){let ge="Access Denied. You are not allowed to access files outside the current workspace.";if(b==="write_file"||b==="update_file"){let Ne=`\u2718 ${b==="write_file"?"Write Canceled":"Edit Canceled"}: ${$t.path||"..."}`,De=115;process.stdout.isTTY&&(De=process.stdout.columns-5||120);let Ce=Math.min(Ne.length+4,De),J=`${Ne.padEnd(Ce-2).substring(0,Ce-2)}`;yield{type:"visual_feedback",content:Yt(`${Ye?`
746
+ `:""}${J}
747
+ `)},Ye=!1}Me.push({role:"user",text:`[ACTION RESULT]: ERROR: ${ge}`}),yield{type:"tool_result",content:`[ACTION RESULT]: ERROR: ${ge}`},ut++;continue}}if(n.onToolApproval&&(b==="write_file"||b==="update_file"||b==="exec_command")){let H=n.systemSettings||{},se=H.autoExec,ge=null,we=!1,Ne=!1,De=!1;if(b==="exec_command"){let{command:Oe}=ne(N.args),mt=(Oe||"").trim(),$e=(Gt,bt)=>{if(!bt)return!1;let Zt=bt.split(",").map(jt=>jt.trim().toLowerCase()).filter(Boolean),at=Gt.toLowerCase();return Zt.some(jt=>at.startsWith(jt))},tt=$e(mt,H.alwaysAskCommands),_e=$e(mt,H.autoApproveCommands);if(Ne=$e(mt,H.autoDisallowCommands),tt?we=!0:(_e||H.autoApproveGit&&/^git\s+commit\b/i.test(mt))&&(ge="allow"),!we&&!ge){if(H.networkAccess===!1){let bt=mt.trim().replace(/\s+/g," ").replace(/^['"]+|['"]+$/g,"").toLowerCase().split(" "),at=bt[0].split("/").pop().split("\\").pop().replace(/\.exe$/,""),jt=new Set(["curl","wget","httpie","xh","ssh","scp","sftp","rsync","ftp","lftp","tftp","telnet","nc","netcat","socat","ping","traceroute","tracert","dig","nslookup","host","whois","nmap","docker","podman","kubectl","helm","gcloud","aws","az","terraform","ansible-playbook","nix","nix-env","apt","apt-get","dpkg","yum","dnf","pacman","zypper","brew","apk","choco","scoop","conda","mamba","aria2c","axel","smbclient","lynx","w3m","links","elinks","heroku","netlify","vercel","firebase","supabase","wrangler","flyctl","powershell","pwsh","certutil","bitsadmin","cloudflared","ngrok","tailscale","zerotier","rclone"]),lt=!1;jt.has(at)&&(lt=!0);let nt=En=>bt.slice(1).some(mn=>En.includes(mn)),ct=En=>{let mn=bt.findIndex(pn=>En.includes(pn)),Un=bt.findIndex(pn=>["run","exec","test"].includes(pn));return mn!==-1&&!(Un!==-1&&Un<mn)};at==="git"&&nt(["clone","pull","push","fetch"])&&(lt=!0),at==="go"&&nt(["get","install"])&&(lt=!0),at==="npm"&&ct(["install","i","update","add"])&&(lt=!0),at==="yarn"&&ct(["add","install","upgrade"])&&(lt=!0),at==="pnpm"&&ct(["add","install","update"])&&(lt=!0),at==="bun"&&ct(["add","install","update"])&&(lt=!0),at==="deno"&&nt(["install","add"])&&(lt=!0),at==="pip"&&nt(["install","download"])&&(lt=!0),at==="pip3"&&nt(["install","download"])&&(lt=!0),at==="cargo"&&nt(["install","add"])&&(lt=!0),["bash","sh","zsh","fish"].includes(at)&&nt(["-c"])&&(lt=!0),at==="cmd"&&nt(["/c"])&&(lt=!0),lt&&(ge="deny",De=!0)}!ge&&Ne&&(ge="deny")}!we&&!ge&&se&&(ge="allow")}else se&&(ge="allow");let Ce=ge,J="";ge==="deny"&&(De?J="network":Ne?J="settings":J="prohibited");let ce=!1,ue="",je=[],ze=0,he=!1,_t="";if(!Ce){if(b==="write_file"||b==="update_file")try{let $e=ne(N.args),{path:tt}=$e;if(tt){let _e=ie.resolve(process.cwd(),tt),Gt=nt=>nt?nt.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,ct=>ct.toUpperCase()):"",bt=Gt(_e),Zt="",at=!1,jt=await Hn(),lt=Gt(jt?.file_focused);if(jt&&lt===bt&&jt.full_content?(Zt=jt.full_content,at=!0):Ue.existsSync(_e)&&(Zt=Ue.readFileSync(_e,"utf8"),at=!0),ue=Zt,await Oo.recordFileChange(_e,Zt),at){let nt=Zt;if(b==="write_file"){let ct=$e.content||$e.newContent||"";nt=ct.endsWith(`
748
+ `)?ct:ct+`
749
+ `,_t=nt}else{let{patchPairs:ct,allowMultiple:En,error:mn}=Ti($e);if(mn){let Xt=`[ACTION RESULT]: ERROR: ${mn}`;Me.push({role:"user",text:Xt}),await Rt("toolFailure"),n.onToolResult&&n.onToolResult("failure",b),yield{type:"tool_result",content:Xt,toolName:b},ut++;continue}let Un=$e.allowMultiple!==void 0?$e.allowMultiple===!0||String($e.allowMultiple).toLowerCase()==="true":En;ze=ct.length;let pn=Si(Zt,ct,{allowMultiple:Un});nt=pn.content,_t=nt,je=pn.results;let Eo=je.filter(Xt=>Xt.success),xs=je.filter(Xt=>!Xt.success);if(Eo.length===0){let Xt=`[ACTION RESULT]: ERROR: Failed to apply patches to [${ie.basename(_e)}].
750
+ ${xs.map(Co=>` \u2022 ${Co.error}`).join(`
751
+ `)}`,oo=`\u2714 Edited: ${ie.basename(_e.replaceAll("\\","/"))}`,dt=115;process.stdout.isTTY&&(dt=process.stdout.columns-5||120);let Kt=Math.min(oo.length+4,dt),so=`${oo.padEnd(Kt-2).substring(0,Kt-2)}`;yield{type:"visual_feedback",content:Yt(`${Ye?`
752
+ `:""}${so}`)},Ye=!1,Me.push({role:"user",text:Xt}),await Rt("toolFailure"),n.onToolResult&&n.onToolResult("failure",b),yield{type:"tool_result",content:Xt,toolName:b},ut++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${ie.basename(_e)}`},zs(_e,Zt,nt),ce=!0,await new Promise(ct=>setTimeout(ct,50))}else if(b==="write_file"){let nt=$e.content||$e.newContent||"",ct=nt.endsWith(`
753
+ `)?nt:nt+`
754
+ `;_t=ct,Ue.existsSync(_e)||(he=!0,Ue.mkdirSync(ie.dirname(_e),{recursive:!0}),Ue.writeFileSync(_e,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${ie.basename(_e)}`},zs(_e,"",ct),ce=!0,await new Promise(En=>setTimeout(En,50))}}}catch($e){console.error("Simulation/Diff Error:",$e)}let Oe=null;qs($e=>{Oe=$e});let mt=n.onToolApproval;if(Ce=await new Promise(async $e=>{let tt=setInterval(()=>{Oe&&(as.onIDEApproval&&as.onIDEApproval(Oe),clearInterval(tt),$e(Oe))},100);try{let _e=await mt(b,N.args);clearInterval(tt),$e(_e)}catch{clearInterval(tt),$e("deny")}}),qs(null),b==="write_file"||b==="update_file"){let{path:$e}=ne(N.args);if($e){let tt=ie.resolve(process.cwd(),$e);if(Nr(tt,Ce),Ce==="deny"&&he&&Ue.existsSync(tt))try{Ue.unlinkSync(tt)}catch{}}}Ce==="deny"&&(J="user")}if(Ce==="allow"&&ce&&zo()){let{path:Oe}=ne(N.args),mt=ie.resolve(process.cwd(),Oe),$e=dt=>dt?ie.resolve(dt).replace(/\\/g,"/").toLowerCase():"",tt=await Hn(),_e="";if(tt&&tt.file_focused&&$e(tt.file_focused)===$e(mt)&&tt.full_content&&(_e=tt.full_content),!_e&&Ue.existsSync(mt)){let dt=Ue.readFileSync(mt,"utf8");dt&&(_e=dt)}!_e&&_t&&(_e=_t),(_e||he)&&Ue.writeFileSync(mt,_e,"utf8");let Gt=_e.split(/\r?\n/),bt=Gt.length,Zt=Buffer.byteLength(_e,"utf8"),at="";ue&&(at=`Old File contents:
755
+ ${ue.split(/\r?\n/).map((Kt,so)=>`${so+1} | ${Kt}`).join(`
756
+ `)}
757
+
758
+ `);let jt="";if(bt<=100)jt=Gt.join(`
759
+ `);else{let dt=Gt.slice(0,50).join(`
760
+ `),Kt=Gt.slice(-50).join(`
761
+ `);jt=`${dt}
762
+
763
+ ... [${bt-100} lines truncated for history stability] ...
764
+
765
+ ${Kt}`}let lt="";if(b==="update_file"){let dt=_i(ue,_e,je,12,n?.compressToolResults||as?.systemSettings?.compressToolResults);lt=`SUCCESS: File [${Oe}] updated via IDE Companion (May have user edits). [${je.length}/${ze}] blocks applied.
766
+
767
+ ${dt}`}else{let dt=_e.split(/\r?\n/),Kt=dt.length,so=Buffer.byteLength(_e,"utf8"),Co="";ue&&(Co=`Old File contents:
768
+ ${ue.split(/\r?\n/).map((ws,ua)=>`${ua+1} | ${ws}`).join(`
769
+ `)}
770
+
771
+ `);let bs="";if(Kt<=100)bs=dt.join(`
772
+ `);else{let wi=dt.slice(0,50).join(`
773
+ `),ws=dt.slice(-50).join(`
774
+ `);bs=`${wi}
775
+
776
+ ... [${Kt-100} lines truncated] ...
777
+
778
+ ${ws}`}lt=`SUCCESS: File [${Oe}] saved via IDE Companion (May have user edits).
779
+ - Stats: [${Kt} lines, ${(so/1024).toFixed(1)} KB]
780
+ ${Co}- Content Preview:
781
+
782
+ ${bs}`}let nt=b==="write_file"?"Created":"Edited",ct=ne(N.args),mn=Object.entries(ct).some(([dt,Kt])=>dt.startsWith("searchContent")&&typeof Kt=="string"&&Kt.startsWith("^LINE:"))?"\u1361":":",Un=`${Oe?"\u2714":"\u2718"} ${nt}${mn} ${Oe?Oe.replaceAll("\\","/"):"No File Changes"}`,pn=115;process.stdout.isTTY&&(pn=process.stdout.columns-5||120);let Eo=Math.min(Un.length+4,pn),xs=`${Un.padEnd(Eo-2).substring(0,Eo-2)}`;yield{type:"visual_feedback",content:Yt(`${Ye?`
783
+ `:""}${xs}`)},Ye=!1;let Xt=Date.now();We=Xt,yield{type:"tool_time",content:Xt-V};let oo=`[ACTION RESULT]: ${lt}`;Me.push({role:"user",text:oo}),kn=!0,await Rt("toolSuccess"),n.onToolResult&&n.onToolResult("success",b),yield{type:"tool_result",content:lt,aiContent:oo,toolName:b},ut++;continue}if(Ce==="deny"){let Oe=`Permission Denied: Prohibited ${b==="exec_command"?"Command":"file edit"}.`;if(J==="user"?Oe="Permission Denied by User":J==="settings"?Oe="Permission Denied by User Policy":J==="network"?Oe="Permission Denied: Sandbox Network Access Disabled by User Policy.":J==="prohibited"&&b==="exec_command"&&(Oe="Permission Denied: Prohibited Command in User Policy"),b==="write_file"||b==="update_file"){let $e=`\u2718 ${b==="write_file"?"Write Cancelled":"Edit Denied"}: ${ne(N.args).path.replaceAll("\\","/")||"..."}`,tt=115;process.stdout.isTTY&&(tt=process.stdout.columns-5||120);let _e=Math.min($e.length+4,tt),Gt=`${$e.padEnd(_e-2).substring(0,_e-2)}`,bt=` ${" ".repeat(_e)} `;yield{type:"visual_feedback",content:Yt(`${Ye?`
784
+ `:""}${Gt}
785
+ `)},Ye=!1}b==="exec_command"&&(await new Promise(mt=>setTimeout(mt,50)),n.onExecChunk&&n.onExecChunk(`ERROR: ${Oe}`),await new Promise(mt=>setTimeout(mt,50)),n.onExecEnd&&n.onExecEnd()),Me.push({role:"user",text:`[ACTION RESULT]: DENIED: ${Oe}`}),yield{type:"tool_result",content:`[ACTION RESULT]: DENIED: ${Oe}`},await Rt("toolDenied"),n.onToolResult&&n.onToolResult("denied",b),ut++;continue}}if(X){let S=115;process.stdout.isTTY&&(S=process.stdout.columns-5||120);let H=await s(),se=!1;H&&(se=H.trim().length>0);let ge=Math.min(X.length+4,S),we=`${X.padEnd(ge-2).substring(0,ge-2)}`;yield{type:"visual_feedback",content:Yt(`${Ye?`
786
+ `:""}${we}${X.includes("\u2714")&&(X.includes("Created")||X.includes("Edited"))?"":`${se?"":`
787
+ `}`}`)},Ye=!1}if(We>0){let S=Date.now()-We,H=Math.max(0,1e3-S);H>0&&await new Promise(se=>setTimeout(se,H))}let An={chatId:p,history:t,onChunk:S=>n.onExecChunk?n.onExecChunk(S):null,onAskUser:n.onAskUser,systemSettings:n.systemSettings,mode:l,isMultiModal:ft(Se),onVisualFeedback:n.onVisualFeedback,onSubagentUpdate:n.onSubagentUpdate,onTokenChunk:n.onTokenChunk,modelName:Se,aiProvider:n.aiProvider,apiKey:n.apiKey,onUsage:n.onUsage};if(b==="write_file"||b==="update_file")try{let{path:S}=ne(N.args);if(S){let H=ie.resolve(process.cwd(),S),se=await Hn();se&&se.file_focused===H&&se.full_content&&(An.forcedContent=se.full_content)}}catch{}ot.push(b);let Le=await xo(b,N.args,An);if((b==="write_file"||b==="update_file")&&Le.startsWith("SUCCESS")){let{path:S}=ne(N.args);if(S){let H=ie.resolve(process.cwd(),S);$r(H)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let Nt=Date.now();We=Nt,yield{type:"tool_time",content:Nt-V},K=Nt;let Ht=null;if(typeof Le=="object"&&Le.binaryPart&&(Ht=Le.binaryPart,Le=Le.text),b==="search_keyword"){let{keyword:S,path:H}=ne(N.args),se=typeof Le=="string"&&Le.startsWith("[GLOB]");se&&(Le=Le.slice(6).trimStart());let ge=typeof Le=="string"&&Le.startsWith("[DIR]");ge&&(Le=Le.slice(5).trimStart());let we=0;if(Le){let he=Le.match(/Found (\d+) match/i);he&&(we=parseInt(he[1]))}let Ne=(H||"").trim().toLowerCase().replaceAll("\\","/"),De=Ne==="#doc"||Ne==="#docs"||Ne==="#documentation"||Ne.includes("#skill/global/fluxflow")||Ne.includes("#skill/fluxflow")||Ne.includes("#skills/fluxflow")||Ne.includes("#skills/global/fluxflow"),Ce,J=115;process.stdout.isTTY&&(J=process.stdout.columns-5||120);let ce=Math.max(10,(J+5)/3),ue=Math.max(10,(J+5)/4);if(De)Ce=`${S?"\u2714":"\u2718"} Searched Documentation`;else{let he=H?H.replace(/[\/\\]+$/,""):null,_t=he&&he!=="."?`"${se?H:ge?`${he}/*`:he}"`:"./",Oe=_t.length>ue?`${_t.slice(0,ue)}...`:_t;Ce=`${S?"\u2714":"\u2718"} Searched: "${S?S.length>J/2?`${S.slice(0,ce)}...`:S:""}" in ${Oe.replaceAll("\\","/")} \u2192 ${we} Match${we===1?"":"es"}`}let je=Math.min(Ce.length+4,J),ze=`${Ce.padEnd(je-2).substring(0,je-2)}`;yield{type:"visual_feedback",content:Yt(`${Ye?`
788
+ `:""}${ze}
789
+ `)},Ye=!1}if(b==="EmergencyRollback"){let{method:S}=ne(N.args);if(S==="forceRevert"){let H=0;if(Le){let ce=Le.match(/Total\s*:\s*(\d+)/i);ce&&(H=parseInt(ce[1]))}let ge=Le&&Le.startsWith("ERROR:")?"\u2718 Emergency Rollback Failed":`\u2714 Emergency Rollback \u2192 ${H} file${H===1?"":"s"} processed`,we=115;process.stdout.isTTY&&(we=process.stdout.columns-5||120);let Ne=await s(),De=!1;Ne&&(De=Ne.trim().length>0);let Ce=Math.min(ge.length+4,we),J=`${ge.padEnd(Ce-2).substring(0,Ce-2)}`;yield{type:"visual_feedback",content:Yt(`${Ye?`
790
+ `:""}${J}${De?"":`
791
+ `}`)},Ye=!1}}if(b==="todo"){let{method:S,tasks:H,markDone:se}=ne(N.args),ge="",we=[],Ne=De=>{if(!De)return[];let Ce=Array.isArray(De)?De:[];if(Ce.length===0&&typeof De=="string"){let J=De.trim();if(J.startsWith("[")&&J.endsWith("]")){let ce=J.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);ce?Ce=ce.map(ue=>ue.slice(1,-1).replace(/\\(.)/g,"$1")):Ce=J.slice(1,-1).split(",").map(ue=>ue.trim()).filter(Boolean)}else Ce=De.split(`
792
+ `)}return Ce.filter(J=>String(J).trim()).map(J=>{let ce=String(J).trim();return ce.startsWith("- [")?ce.substring(6).trim():ce})};if(S==="create"?(ge="\x1B[32m\u2192\x1B[0m Created Goals",we=Ne(H).map(De=>`\x1B[90m\u25CB\x1B[0m ${De}`)):S==="append"?(ge="\x1B[34m\u2795\x1B[0m Added New Goals",we=Ne(H).map(De=>`\x1B[90m\u25CB\x1B[0m ${De}`)):S==="get"&&(ge=se?"\x1B[36m\u21BB\x1B[0m Updated Goals":"\x1B[35m\u2022\x1B[0m Reviewed Goals",we=(Le||"").split(`
793
+ `).slice(1).join(`
794
+ `).split(`
795
+ `).filter(Ce=>Ce.trim().startsWith("- [")).map(Ce=>{let J=Ce.trim(),ce=J.startsWith("- [x]");return`${ce?"\x1B[32m\u2714\x1B[0m":"\x1B[90m\u25CB\x1B[0m"} ${ce?"\x1B[90m":"\x1B[37m"}${J.substring(6).trim()}\x1B[0m`})),ge&&we.length>0){let De=[`${ge}`,...we.map(ce=>` ${ce}`)].join(`
796
+ `),Ce=await s(),J=!1;Ce&&(J=Ce.trim().length>0),yield{type:"visual_feedback",content:Yt(`${Ye?`
797
+ `:""}${De}${J?"":`
798
+ `}`)},Ye=!1}}b==="exec_command"&&n.onExecEnd&&(await new Promise(S=>setTimeout(S,800)),n.onExecEnd());let gn=Le&&Le.startsWith("DENIED:");Le&&!Le.startsWith("ERROR:")&&!gn?(await Rt("toolSuccess"),n.onToolResult&&n.onToolResult("success",b)):gn||(await Rt("toolFailure"),n.onToolResult&&n.onToolResult("failure",b));let Ft=(Le||"").toString().replaceAll("[UI_CONTEXT]","");Ft.includes("[[VERIFIED]]")&&(Ft=Ft.replace(/\[\[VERIFIED\]\][\s\S]*?\[\[\/VERIFIED\]\]/g,`[SYSTEM NOTE]: Patch Block matched & applied successfully. Large Block omitted to conserve context.
799
+ `));let hn;if(Ft.startsWith("[[SAME]]")){let H=Ft.replace(/^\[\[SAME\]\]\s*\r?\n?/,"").split(/\r?\n/),se=H.filter(we=>we.startsWith("SUCCESS:")||we.trim().startsWith("- Stats:"));hn=`[ACTION RESULT]: ${se.length>0?se.join(`
800
+ `):H.slice(0,2).join(`
801
+ `)}
802
+ [SYSTEM NOTE]: Content verified and persisted to disk. Full preview omitted to conserve context.`}else hn=`[ACTION RESULT]: ${Ft}`;Me.push({role:"user",text:hn,binaryPart:Ht}),kn=!0;let Pe=`[ACTION RESULT]: ${Le.replaceAll(`[[VERIFIED]]
803
+ `,"").replaceAll(`
804
+ [[/VERIFIED]]`,"")||""}`;(b==="view_file"||b==="web_scrape"||b==="file_map")&&(Pe=`[ACTION RESULT]: ${X} (Context Locked for UI Clarity)`),yield{type:"tool_result",content:Pe,aiContent:hn,binaryPart:Ht,toolName:b},b==="memory"&&Le.includes("SUCCESS")&&(yield{type:"memory_updated"}),ut++}if(i==="Google"&&an&&Date.now()-ms>=150){yield*Nn();let N=to(an);for(let V of N)yield V;an="",ms=Date.now()}}D.usageMetadata&&(Jt=D.usageMetadata),Jt&&(yield{type:"liveTokens",content:Jt.totalTokenCount})}if(me&&(me=!1,Dt?Qe+="</think>":(Te+="</think>",i==="Google"?an+="</think>":yield{type:"text",content:"</think>"})),Dt&&Qe.length>0){let D=0,Y=Math.min(xt.length,Qe.length);for(let q=Y;q>0;q--)if(xt.endsWith(Qe.substring(0,q))){D=q;break}let W=Qe.substring(D);if(W){let Z=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(xt)?W.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):W.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(Z)if(Te+=Z,i==="Google")an+=Z;else{yield*Nn();let z=to(Z);for(let le of z)yield le}}Dt=!1,Qe=""}if(yield*Nn(),wt)break;let no=(Te||"").trim(),ra=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(no.toLowerCase())||/\[\[END\]\]/i.test(no.toLowerCase()),aa=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(no.toLowerCase()),la=Me.length>0||Ve!==null,ps=qt(no).trim(),ca=/(\p{Emoji_Presentation}|\p{Extended_Pictographic})$/u.test(ps),da=/([.!?"'*_`|\]\)”’~~]+|\s|`{3}|[\u200B-\u200D\uFEFF])$/u.test(ps.trim()),fa=/[.!?}"'`’“”]$|```$/s.test(ps)||da||ca;!ra&&!aa&&!la&&no.length>0,st=!0,await Rt("agent",i)}catch(Ae){if(wt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
805
+
806
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(String(Ae).includes("Incomplete JSON segment at the end")){me&&(me=!1,Dt?Qe+="</think>":(Te+="</think>",yield{type:"text",content:"</think>"})),st=!0,await Rt("agent",i);break}if(me&&(me=!1,Dt?Qe+="</think>":Te+="</think>"),Dt&&Qe.length>0){let Pt=0,Et=Math.min(xt.length,Qe.length);for(let It=Et;It>0;It--)if(xt.endsWith(Qe.substring(0,It))){Pt=It;break}let Tt=Qe.substring(Pt);if(Tt){let gt=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(xt)?Tt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):Tt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");gt&&(Te+=gt)}Dt=!1,Qe=""}let ee=Ae instanceof Error?(()=>{try{return JSON.parse(JSON.parse(Ae.message).error.message).error.message}catch{return String(Ae)}})():String(Ae),Lt=new Date().toLocaleString(),Mt=ie.join(Cn,"agent");Ue.existsSync(Mt)||Ue.mkdirSync(Mt,{recursive:!0}),Ue.appendFileSync(ie.join(Mt,"error.log"),`ERROR [${Lt}]: ${ee}
807
+
808
+ ----------------------------------------------------------------------
809
+
810
+ `);let At=Ae.status||Ae.statusCode||Ae.code,zt=String(Ae).includes("replicas at capacity");if(!(At&&(At>=500&&At<600||At===408||At===429||zt)||!At&&(/status[ :]+(5\d\d|408|429)/i.test(String(Ae))||/code[ :]+(5\d\d|408|429)/i.test(String(Ae))||/(500|503|408|429)/.test(String(Ae))))){if(et<on-3)throw Ae;yield{type:"text",content:ee},yield{type:"status",content:"Error Occured"}}if(Te.trim().length>0||rt>1)if(rt<=on){rt++;let Pt=Math.min(1e3*Math.pow(2,rt-1),24e3);if(Te.trim().length>0){r.push({role:"agent",text:Te});let Et=`[system]
811
+ - seamless continuation: resume immediately. pick up from last words with zero gap/disruption
812
+ - no repetition: do not repeat any text already written
813
+ - no re-think: do not restart or open <think> if reasoning already started. continue the thinking and close thinking block </think> before chat output
814
+ - mid-tool safety: if cutoff was mid-tool call, restart that tool call from start
815
+ - stealth: do not mention/apologize for cutoff [/system]`;Me.length>0?Me.forEach((Tt,It)=>{It===Me.length-1?r.push({...Tt,text:`${Tt.text}
816
+
817
+ ${Et}`}):r.push(Tt)}):r.push({role:"user",text:Et}),xt+=Te}for(let Et=Pt/1e3;Et>0&&!wt;Et--)yield{type:"status",content:`Error Occured. Recovering Stream (${rt}/${on}) [Retrying in ${Et.toFixed(0)}s]...`},await new Promise(Tt=>setTimeout(Tt,1e3));yield{type:"status",content:"Error Occured. Recovering Stream..."}}else throw new Error(`Stream collapsed too many times. (Failed to resolve ${on} times)
818
+ Error log can be found in \`/export logs\``);else if(et<=on){et++,rt=1,xt="";let Pt=Math.min(1e3*Math.pow(2,et-1),32e3),Et=.8+Math.random()*.4,Tt=Math.round(Pt*Et);Zn=!0,yield{type:"status",content:`Trying to reach ${e} (${et}/${on}) [Retrying in ${(Tt/1e3).toFixed(0)}s]`};for(let It=Tt/1e3;It>0&&!wt;It--)yield{type:"status",content:`Trying to reach ${e} (${et}/${on}) [Retrying in ${It.toFixed(0)}s]`},await new Promise(gt=>setTimeout(gt,1e3));yield{type:"status",content:`Trying to reach ${e}`}}else throw new Error(`Model ${e} cannot be reached. (Failed ${on} times)
819
+ Error log can be found in \`/export logs\``)}}if(Jt){let me=Jt.totalTokenCount||0,Ae=Jt.cachedContentTokenCount||0,ee=(Jt.candidatesTokenCount||0)+(i==="Google"&&Jt.thoughtsTokenCount||0);await Bt("tokens",me,i,Se),Ae>0&&await Bt("cachedTokens",Ae,i,Se),ee>0&&await Bt("candidateTokens",ee,i,Se),Do({provider:i,model:Se,prompt:Jt.promptTokenCount||0,cached:Ae,output:ee,reasoning:Jt.thoughtsTokenCount||0}),yield{type:"usage",content:Jt}}Te=qr(Te),hs.push(Te);let Sn=qt(Te),Pn=jr(Te),un=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(Pn.toLowerCase())||/\[\[END\]\]/i.test(Pn.toLowerCase())||!0,il=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(Pn.toLowerCase()),rl=ut>0;yield{type:"status",content:"Thinking"};let na=Za(Te,/(\[\s*(turn\s*:)?\s*(continue|finish)\s*\]|\[\[END\]\])/gi,"").trim(),$n=(un||Me.length===0)&&!vt&&!rn&&!Tn;if($n=Me.length===0?$n:!1,$n=Ot||_o?!1:$n,Te&&Te.trim().endsWith('")]')&&Me.length===0&&($n=!1),$n){pi=!0;let me=hs.join(`
820
+ `),Ae=qt(me).trim();yield{type:"interactive_turn_finished",data:{agentText:a,fullAgentTextRaw:me,history:[...r],needTitle:y}},r.length>0&&r[r.length-1].role==="agent"?r[r.length-1].text=Ae:r.push({role:"agent",text:Ae}),r.forEach(ee=>{if(ee.role==="user"&&ee.text&&(ee.text=ee.text.replace(/\n\[COMPILE ERROR\][\s\S]*?\[\/ERROR\]/g,""),ee.text=ee.text.replaceAll(`
821
+
822
+ [system] user question. resolve this specific query within '[ANSWER] ... [/ANSWER]' concisely, naturally [/system]
823
+ `,"").replaceAll(`[system] user question. resolve this specific query within '[ANSWER] ... [/ANSWER]' concisely, naturally
824
+ **strictly follow thinking policy as high priority. do not start a response without <think>...</think>** [/system]
825
+ `,"").replaceAll(`[system] **strictly follow thinking policy as high priority. do not start a response without <think>...</think>** [/system]
826
+ `,"").replaceAll(/\n\[system\] WARNING, Turn Limit Impending: Step \d+\/\d+\. Wrap up quickly\/prompt user to continue & use \[\[END\]\] quickly\. \[\/system\]/g,""),ee.text=ee.text.replaceAll(/\n\[system\] File Changes:\n(?:\* .+ \(created|modified|deleted\)\n)*\[\/system\]/g,""),(i==="Mistral"||i==="Google"&&e?.toLowerCase().startsWith("gemma"))&&(ee.text.startsWith("[ACTION RESULT]")||ee.text.startsWith("[TOOL RESULT]")))){let Mt=`
827
+ [system] Action result received. Analyze output and proceed with your turn [/system]`,At=`
828
+ [system] Action result received. Analyze output and proceed with your turn. **strictly follow thinking policy. do not start a response without <think>...</think>** [/system]`;ee.text=ee.text.replaceAll(At,"").replaceAll(Mt,"").trim()}}),yield{type:"status",content:"[end]"}}if($n)break;let oa=na.trim()||"*Working...*";if(r.push({role:"agent",text:oa}),Me.length>0||kn){if(Me.length>0){let me=Me.map(zt=>zt.text).join(`
829
+
830
+ `),Lt=(qt(Te).replace(/\[{1,2}(?:tool|action):[\s\S]*?\)\s*\]{1,2}/gi,"").match(/\[(?:tool|action):/gi)||[]).length,Mt=Me.length+Lt;if(Me.length<Mt){me+=`
831
+
832
+ [system] Only ${Me.length} out of ${Mt} attempted tool calls were executed. Verify proper structure compliance & try failed calls again [/system]`;let zt=Mt-Me.length;for(let Ge=0;Ge<zt;Ge++)await Rt("toolFailure")}let At=Me.find(zt=>zt.binaryPart)?.binaryPart||null;r.push({role:"user",text:me,binaryPart:At})}}else if(!wt){let Ae=(Te.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/i,"").match(/\[(?:tool|action):/gi)||[]).length;_o||Ot||Ae>0?(r.push({role:"user",text:`[system] Failed to execute ${Ae} tool${Ae>1?"s":""}. Verify proper structure compliance [action:ActionName(...)] & try again [/system]`}),await Rt("toolFailure"),yield{type:"visual_feedback",content:`
833
+ ${Yt("\u2718 Execution Error")}
834
+ `}):(yield{type:"visual_feedback",content:`
835
+ ${Yt("\u2718 Loop Detected")}
836
+ `},r.push({role:"user",text:`[system] ${rn&&!vt?"Stuttering Detected by Internal System. Re-calibrate your response & proceed.":`${vt?" Over Thinking":" Loop"} Detected by Internal System${vt?" for current Effort Level":""}. ${vt?"If you have planned the task, prioritize execution/output":"If you have finished your task provide a simple summary and end"}`} [/system]`})),vt=!1,rn=!1,Tn=!1}T?.advanceRollback&&await lo.recordTurnDelta(p,j+1,ot),_o=ut>0||kn}if(!pi&&!wt){let j="\u2726 Turn safety limit reached. Stopping execution.";yield{type:"text",content:`
837
+
838
+ ${j}
839
+ `};let Ke=(hs.join(`
840
+ `)+`
841
+ ${j}`).trim();yield{type:"interactive_turn_finished",data:{agentText:a,fullAgentTextRaw:Ke,history:[...r],needTitle:y}},yield{type:"status",content:"[end]"}}}catch(d){let r=d?.cause?` (Cause: ${d.cause?.message||String(d.cause)})`:"",v=(d instanceof Error?(()=>{try{return JSON.parse(JSON.parse(d.message).error.message).error.message}catch{return(d.message?`${d.message}${r}`:"")||String(d)}})():String(d)).replace(/^(Error:\s*)+/i,"");i==="Google"&&!/^[A-Z0-9_\-\s]+ ERROR:/i.test(v)&&(v=`GEMINI ERROR: ${v}`);let U=new Date().toLocaleString(),O=ie.join(Cn,"agent");yield{type:"text",content:`
842
+
843
+ \u2726 CRITICAL ERROR: ${v.includes("fetch failed")?"Failed to Connect. Check your Internet Connection or Wait a moment":v}
844
+ \u2800`},Ue.existsSync(O)||Ue.mkdirSync(O,{recursive:!0}),Ue.appendFileSync(ie.join(O,"error.log"),`CRITICAL ERROR [${U}]: ${d}${d?.cause?`
845
+ CAUSE: ${d.cause?.stack||d.cause}`:""}
846
+
847
+ ----------------------------------------------------------------------
848
+
849
+ `),typeof flushGoogleBuffer=="function"&&(yield*flushGoogleBuffer()),yield{type:"tool_result",content:`ERROR: [INTERNAL CRITICAL] ${v}`}}finally{R&&(clearInterval(R),R=null),typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),await Oo.commitTransaction(),T?.advanceRollback&&await lo.cleanup(p),await Hn()}yield{type:"status",content:null}},yf=async(e,t,n=null,s=null,o=50,c=null,f=!1)=>{let l=await ao(),k={...l,...t},p=process.env.SUBAGENT_MODEL?process.env.SUBAGENT_MODEL.trim():null,g=process.env.SUBAGENT_PROVIDER?process.env.SUBAGENT_PROVIDER.trim():null,T=new Date,m=`${T.getFullYear()}-${T.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(T.getDate()).padStart(2,"0")}, ${T.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}).replace(":","-")}`,u=(R=>{if(!R)return null;let d=R.toLowerCase();return d==="google"?"Google":d==="deepseek"?"DeepSeek":d==="openrouter"?"OpenRouter":d==="nvidia"?"NVIDIA":d==="mistral"?"Mistral":d==="ollama"?"Ollama":d==="inferx"?"InferX":d==="sensenova"?"SenseNova":d==="poolside"?"Poolside":d==="9router"||d==="9Router"?"9router":d==="aihubmix"||d==="aihub"?"AIHubMix":d==="explabs"||d==="experientiallabs"||d==="experimentallabs"?"ExpLabs":d==="tokenharbor"||d==="token harbor"||d==="token_harbor"||d==="thk"?"TokenHarbor":d==="apinex"||d==="apx"?"APInex":null})(g),w=k?.systemSettings?.CustomSubAgent?k?.systemSettings?.SubAgentModel:null,I=k?.systemSettings?.CustomSubAgent?k?.systemSettings?.SubAgentProvider:null,h=null;if(w==="ENV"?(h=p,p&&u&&(k.aiProvider=u)):w&&w!=="Default"?(h=w,I&&(k.aiProvider=I)):p&&u&&(k.aiProvider=u),k.aiProvider){let R=await Ss(k.aiProvider);R&&(k.apiKey=R)}let A=R=>{if(!R||typeof R!="string")return{allowed:!0};let d=[/rm\s+-[rf]{1,2}\s+[\/*.]/i,/rmdir\s+\/[sq]/i,/del\s+\/[fsq]/i,/\bformat\b\s+[a-z]:/i,/mkfs/i,/dd\s+if=/i,/\b(shutdown|reboot|poweroff|init\s+0|init\s+6)\b/i,/chmod\s+(-R\s+)?777\s+[\/*.]/i,/chown\s+(-R\s+)?root/i,/git\s+push\s+.*--force/i,/git\s+clean\s+-fdx/i,/\bsudo\s+su\b/i,/\bsu\s+-\b/i];for(let r of d)if(r.test(R))return{allowed:!1,reason:`Blocked potentially destructive or unsafe command pattern: "${r.source}"`};return{allowed:!0}},$=n||h||t?.modelName||t?.activeModel||l.activeModel,C=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",x=`-- ACTIONS (path = relative to CWD, path separator: '/') --
850
+ In chat output the format \`[action:ActionName(arg1="value1")]\` in NEW line
851
+ Rules:
852
+ - JSON escape literal sequences, backslash: \\\\, newLine: \\ n
853
+ - Same file, multiple edits? ONE PatchFile (\u226415 blocks)
854
+ - Need text or huge file? CodeSearch > Full Read
855
+ - Avoid unnecessary large file chunk reads
856
+ - Stuck on syntax error? Tell user > waste time
857
+
858
+ # Provided Actions
859
+ **Communication**
860
+ - AskUser(question=string, optionA?="title::description", ...MAX4). Any Ambiguity
861
+ ${f?"- AskMain(question=string). Communicate with PARENT/MAIN AGENT. When clarification/decision is needed for a task":""}
862
+
863
+ **Web**
864
+ - WebSearch(query=string, aiMode?=bool:false, limit?=int[3..10]). Proactive use for unknown/latest info. aiMode: exclude limit
865
+ - WebScrape(url=string). Proactive use for specific webpage/docs
866
+
867
+ **Workspace**
868
+ - CodeSearch(keyword=string, path?="dir/file/glob, inclusion/exclusion ;-separated", regex?=bool:auto). Find relevant code
869
+ - ReadFolder(path=string, recurse?=int[1..3]). Minimize recursion
870
+ - FindFile(basename=string). Find file path. Extention optional
871
+ - ReadFile(path=string, startLine?=int, endLine?=int)
872
+ - PatchFile(path=string, allowMultiple?=bool, searchContent1="string match OR ^LINE:start..end$", newContent1=string, ...MAX15). Small searchString. Line Anchors: ^LINE:...$ syntax, must for large blocks & escape sequences
873
+ - WriteFile(path=string, content=string). Creates/Overwrites. File Exist? PatchFile > WriteFile
874
+ - Run(command=string). Runs ${C==="Windows"?Ai()?"powershell":"windows CMD":"bash"} command. Destructive command \u2192 Ask user`.trim(),_=`=== START SYSTEM PROMPT ===
875
+ Identity: FluxFlow subagent helping the main Agent
876
+ Your task is: "${e}"
877
+ CWD: ${process.cwd()}
878
+
879
+ ${x.trimEnd()}
880
+
881
+ -- THINKING GUIDANCE --
882
+ NO EXPLICIT THINKING REQUIRED. FOCUS ON TASK COMPLETION
883
+ Main focus: actions and task, not chatting
884
+ On completion, provide a detailed summary in Tables/Markdown Format with file modified info. If any task failed report back in detail
885
+
886
+ Current Time: ${m}
887
+ === END SYSTEM PROMPT ===`,M=[{role:"user",text:`Complete this task: ${e}`}],y=0,a="";for(;y<o;){let R=await _s("subagent",k);if(!R.allowed)throw new Error(R.reason||`Budget Exhausted for Provider (${k?.aiProvider||"Subagent"})`);if(wt){if(t?.taskId&&typeof Vt<"u"){let L=Vt.find(F=>F.id===t.taskId);L&&(L.status="cancelled")}throw c&&c("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}if(t?.taskId&&typeof Vt<"u"){let L=Vt.find(F=>F.id===t.taskId);if(L&&L.status==="cancelled")throw c&&c("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}let d=M.map(L=>({role:L.role==="user"?"user":"model",parts:[{text:L.text}]}));c&&c(`[Subagent Turn ${y+1}]...`);let r=["Fast","Low","Medium","High"],E=process.env.SUBAGENT_THINKING,v=r.includes(E)?E:"Low",O=(await ls(k,$,d,_,v)).text||"",P=qr(qt(O).trim());a=P,c&&c(`[Subagent Response]
888
+ ${P}
889
+ `),M.push({role:"agent",text:P});let re=ko(P);if(re.length===0)break;let de=re.filter(L=>L.toolName.toLowerCase()==="askmain"||L.toolName.toLowerCase()==="ask_main"),Q=!1,ke="";for(let L of re){if(wt){if(t?.taskId&&typeof Vt<"u"){let B=Vt.find(G=>G.id===t.taskId);B&&(B.status="cancelled")}throw new Error("Subagent task was cancelled.")}if(t?.taskId&&typeof Vt<"u"){let B=Vt.find(G=>G.id===t.taskId);if(B&&B.status==="cancelled")throw new Error("Subagent task was cancelled.")}let F=L.toolName.toLowerCase();if(F==="askuser"&&(F="ask"),F==="askmain"||F==="ask_main"){if(Q)continue;Q=!0;let B="";if(de.length===1?B=ne(de[0].args).question||de[0].args:B=de.map((G,ye)=>{let Re=ne(G.args);return`Q${ye+1}: ${Re.question||G.args}`}).join(`
890
+ `),t.onAskMain){c&&c(`[Executing Tool] AskMain("${B}")...`);let G=await t.onAskMain(B);c&&c(`[Action Result]
891
+ Answer from Main Agent: ${G}
892
+ `),ke+=`[ACTION RESULT for AskMain]: Answer from Main Agent: ${G}
893
+
894
+ `,await Rt("toolSuccess")}else ke+=`[ACTION RESULT for AskMain]: ERROR: Main agent communication channel not available.
895
+
896
+ `;continue}if(!(s?s.some(B=>B.toLowerCase()===F):!0)){let B=`ERROR: Tool [${L.toolName}] is not in the allowed tools list for this subagent.`;c&&c(`[Blocked Tool Call] ${L.toolName} - not allowed
897
+ `),ke+=`${B}
898
+
899
+ `;continue}if(F==="exec_command"||F==="execcommand"||F==="run"){let B=ne(L.args).command||"",G=A(B);if(!G.allowed){let ye=`ERROR: [SECURITY RESTRICTION] Subagent execution blocked command: ${G.reason}`;c&&c(`[Blocked Command] ${B} - ${G.reason}
900
+ `),ke+=`${ye}
901
+
902
+ `;continue}}let oe="";if(F==="web_search"||F==="websearch")oe=`\u2714 \x1B[95mSearched\x1B[0m: ${ne(L.args).query||""}`;else if(F==="web_scrape"||F==="webscrape")oe=`\u2714 \x1B[95mScraped\x1B[0m: ${ne(L.args).url||""}`;else if(F==="search_keyword"||F==="searchkeyword"||F==="codesearch"||F==="code_search"){let B=ne(L.args),G=B.keyword||"",ye=B.path||"";oe=`${G?"\u2714":"\u2718"} \x1B[95mSearched\x1B[0m: ${G||"No Query"}${ye?` \u2192 ${ye.replaceAll("\\","/")}`:""}`}else if(F==="view_file"||F==="viewfile"||F==="readfile")oe=`\u2714 \x1B[95mRead\x1B[0m: ${(ne(L.args).path||"").replaceAll("\\","/")}`;else if(F==="find_file"||F==="findfile"){let B=ne(L.args),G=B.basename||B.name||B.path||B.file||B.query||"";oe=`${G?"\u2714":"\u2718"} \x1B[95mLocated\x1B[0m: ${G||"No Query"}`}else if(F==="list_files"||F==="read_folder"||F==="readfolder"){let B=ne(L.args).path||null,G=ne(L.args).recurse||0;oe=`${B?"\u2714":"\u2718"} \x1B[95mBrowsed\x1B[0m: ${B?`${B.replaceAll("\\","/")}${G>0?`${B.endsWith("/")?`*${G}`:`/*${G}`}`:`${B.endsWith("/")?"":"/"}`}`:""}`}else if(F==="write_file"||F==="writefile"){let B=ne(L.args).path||null;oe=`${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=ne(L.args),G=B.path||null,Re=Object.entries(B).some(([ve,Ie])=>ve.startsWith("searchContent")&&typeof Ie=="string"&&Ie.startsWith("^LINE:"))?"\u1361":":";oe=`${G?"\u2714":"\u2718"} \x1B[95mEdited\x1B[0m${Re} ${G?`${G.replaceAll("\\","/")}`:"No File Changes"}`}else if(F==="exec_command"||F==="execcommand"||F==="run"){let B=ne(L.args).command||null;oe=`${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=ne(L.args).path||"";oe=`${B?"\u2714":"\u2718"} \x1B[95mIndexed\x1B[0m: ${B?`${B.replaceAll("\\","/")}`:"File Not Found"}`}else if(F==="await"){let{time:B}=ne(L.args),G=parseFloat(B)||0;G<10&&(G=10),G>180&&(G=180),oe=`\u2714 \x1B[95mAwaiting\x1B[0m \u2192 ${(Re=>{if(Re>=60){let ve=Math.floor(Re/60),Ie=Re%60;return`${ve}m${Ie>0?` ${Ie}s`:""}`}return`${Re}s`})(G)}`}else{let B=si[F]||L.toolName,G=Kn(F,L.args);oe=`\u2714 \x1B[95m${B}\x1B[0m${G?`: ${G}`:""}`}t.onVisualFeedback&&oe&&t.onVisualFeedback(oe),c&&c(`[Executing Tool] ${L.toolName}(${L.args})...`);try{let B=await xo(L.toolName,L.args,{...t,mode:"Flux"});if(c&&c(`[Action Result]
903
+ ${B}
904
+ `),ke+=`[ACTION RESULT for ${L.toolName}]: ${B}
905
+
906
+ `,await Rt("toolSuccess"),F==="patchfile"||F==="update_file"||F==="updatefile"||F==="patch_file"){if(B){let G=B.split(`
907
+ `),ye=0,Re=0,ve=!1;for(let Ie of G){if(Ie.includes("[DIFF_START]")){ve=!0;continue}if(Ie.includes("[DIFF_END]")){ve=!1;continue}ve&&(/^\+\d+/.test(Ie)?ye++:/^\-\d+/.test(Ie)&&Re++)}(ye>0||Re>0)&&(await Bt("linesAdded",ye),await Bt("linesRemoved",Re))}}else if((F==="writefile"||F==="write_file")&&B){let G=B.match(/- Stats: \[(\d+) lines/),ye=G?parseInt(G[1]):0,Re=0;if(B.includes("Old File contents:")){let ve=!1;for(let Ie of B.split(`
908
+ `)){if(Ie.includes("Old File contents:")){ve=!0;continue}ve&&(Ie.trim()===""?ve=!1:/^\d+ \|/.test(Ie)&&Re++)}}(ye>0||Re>0)&&(await Bt("linesAdded",ye),await Bt("linesRemoved",Re))}}catch(B){let G=`ERROR: Execution failed for [${L.toolName}]: ${B.message}`;c&&c(`[Tool Error] ${G}
909
+ `),ke+=`${G}
910
+
911
+ `,await Rt("toolFailure")}}let ae="";if(t?.taskId&&typeof Vt<"u"){let L=Vt.find(F=>F.id===t.taskId);if(L&&L.pendingSteerMessages&&L.pendingSteerMessages.length>0){let F=[...L.pendingSteerMessages];L.pendingSteerMessages=[];for(let Ee of F)ae+=`
912
+
913
+ [STEERING INSTRUCTION FROM MAIN AGENT]: ${Ee}`,c&&c(`[Subagent Steered] ${Ee}`)}}let it=(ke.trim()+ae).trim();M.push({role:"user",text:it}),y++}return a};export{bo as a,Or as b,yc as c,xc as d,He as e,ul as f,gl as g,ac as h,lc as i,kc as j,zo as k,Tc as l,ja as m,cf as n,Ka as o,Va as p,oi as q,qt as r,Gr as s,qr as t,Xa as u,df as v,ff as w,ri as x,uf as y,gf as z,ls as A,hf as B,mf as C,pf as D,yf as E};