fluxflow-cli 4.47.0 → 4.49.0

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 (39) hide show
  1. package/README.md +2 -0
  2. package/dist/chunks/{ai-IQMYBYU6.js → ai-QEMKCYGG.js} +1 -1
  3. package/dist/chunks/app-6TAUOS56.js +333 -0
  4. package/dist/chunks/{auto_completion-HIR5DVL5.js → auto_completion-33R46AFF.js} +1 -1
  5. package/dist/chunks/chunk-2XQIWDKW.js +1 -0
  6. package/dist/chunks/{chunk-OSSZ4LIE.js → chunk-2YDU2B2F.js} +1 -1
  7. package/dist/chunks/chunk-36FKJWXK.js +949 -0
  8. package/dist/chunks/{chunk-XDY4KWTM.js → chunk-AIWOSKP3.js} +1 -1
  9. package/dist/chunks/{chunk-MS33ZWST.js → chunk-IMX3PWYO.js} +1 -1
  10. package/dist/chunks/{chunk-ER3SNTS7.js → chunk-TNA3R7TS.js} +1 -1
  11. package/dist/chunks/{chunk-U2GX6WT2.js → chunk-ZCM4J7JT.js} +1 -1
  12. package/dist/chunks/{click-R35XTYKT.js → click-HMFVJIQN.js} +2 -2
  13. package/dist/chunks/{computer_action-WNXZNAIZ.js → computer_action-6AYM3W7D.js} +1 -1
  14. package/dist/chunks/{custom_openai-YS5EV6DG.js → custom_openai-HY6EEQI2.js} +1 -1
  15. package/dist/chunks/{drag-IB5WSI6F.js → drag-H53TOSDP.js} +1 -1
  16. package/dist/chunks/{generate_image-VW5VG6VI.js → generate_image-JS7J4FLD.js} +1 -1
  17. package/dist/chunks/{invoke-QXYLLM2W.js → invoke-WGWAIYZH.js} +3 -3
  18. package/dist/chunks/{invokeSync-UYRKSUNO.js → invokeSync-DCL3EMVV.js} +2 -2
  19. package/dist/chunks/{key_press-XDYBP7DW.js → key_press-NF322TXF.js} +1 -1
  20. package/dist/chunks/{keyboard_typing-YHYH7O66.js → keyboard_typing-OADL5LPA.js} +1 -1
  21. package/dist/chunks/{ollama-QB7WX7VD.js → ollama-NWY2XLYF.js} +1 -1
  22. package/dist/chunks/{recapture_screen-F6ZPZU56.js → recapture_screen-IXVMQR5C.js} +1 -1
  23. package/dist/chunks/{screen_grid-IWNA3DA2.js → screen_grid-DGIDOOQD.js} +1 -1
  24. package/dist/chunks/{scroll-GIP2J2QN.js → scroll-B3HCFDTS.js} +1 -1
  25. package/dist/chunks/{search_keyword-O52M65TB.js → search_keyword-UXNKLCGC.js} +1 -1
  26. package/dist/chunks/{secrets-YIWFP4S2.js → secrets-NGDMM5RJ.js} +1 -1
  27. package/dist/chunks/{secrets_v2-TEUFHDI7.js → secrets_v2-R5GMXRT3.js} +1 -1
  28. package/dist/chunks/{settings-HSQ2K6DN.js → settings-JME7GCEU.js} +1 -1
  29. package/dist/chunks/{update_file-QKDDZKOX.js → update_file-YXW37NRJ.js} +1 -1
  30. package/dist/chunks/{usage-6V4XZT3Q.js → usage-URT2EC23.js} +1 -1
  31. package/dist/chunks/{usageServer-4XHUFY7X.js → usageServer-RJDE5QDZ.js} +1 -1
  32. package/dist/chunks/write_file-WMLWKQKI.js +32 -0
  33. package/dist/cli.js +3 -3
  34. package/dist/package.json +2 -2
  35. package/package.json +2 -2
  36. package/dist/chunks/app-IPNLGJWQ.js +0 -333
  37. package/dist/chunks/chunk-45DLFA4C.js +0 -1
  38. package/dist/chunks/chunk-UNOUKPFA.js +0 -944
  39. package/dist/chunks/write_file-D7QA2LB2.js +0 -29
@@ -1,944 +0,0 @@
1
- import{a as Ds}from"./chunk-HFTI3R3Q.js";import{a as Ro}from"./chunk-52STSLCN.js";import{a as en}from"./chunk-56EJGQU3.js";import{a as Bs}from"./chunk-4BLSASW6.js";import{c as Di,g as Fi,h as Ps,i as Os}from"./chunk-AMFNIFF3.js";import{b as Ls,c as $s,d as Bi,f as Ns}from"./chunk-UIL6OCU4.js";import{b as Ui,h as Fs}from"./chunk-Z5D4VQSG.js";import{a as ti}from"./chunk-6EYQQ7GQ.js";import{a as j}from"./chunk-Y5JU726N.js";import{b as $i}from"./chunk-XDY4KWTM.js";import{y as Li}from"./chunk-U2GX6WT2.js";import{f as Co,l as Lt,n as At,p as Ni,q as Ms}from"./chunk-OSSZ4LIE.js";import{b as Eo}from"./chunk-45DLFA4C.js";import{l as lt,m as ei,q as ae}from"./chunk-HTOLY3HR.js";import{c as Ot,d as co,e as Zo}from"./chunk-P5HBJA23.js";import{a as Un,b as Xo,d as wn,e as Jo,k as Jn,l as Qo,m as Pi,r as Oi,w as To,x as Ao,y as Is}from"./chunk-26BQ45XP.js";import{GoogleGenAI as ia,ThinkingLevel as Ye,HarmBlockThreshold as Gn,HarmCategory as Hn}from"@google/genai";var Us=(e=!0,n=!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 ni={xHigh:"Use minimal reasoning. Prefer simplest path; avoid branching; waste NO tokens overthinking",High:"Use minimal reasoning. Prefer simplest path; avoid branching; waste NO tokens overthinking",Medium:"Use minimal reasoning. Prefer simplest path; avoid branching; waste NO tokens overthinking",Minimal:"Use minimal reasoning. Prefer simplest path; avoid branching; waste NO tokens overthinking",Off:"NO thinking. Immediate response. Verify imports, tool results & system stability"};import ln from"fs";import an from"path";import $a from"os";import Sn from"fs";import Wn from"path";import Zs from"fs";import Wi from"path";import{execSync as er}from"child_process";import{fileURLToPath as Pa}from"url";var Ws=`# FluxFlow CLI Startup & Flags Reference
29
-
30
- Launch command syntax:
31
- fluxflow [options]
32
-
33
- ## Supported CLI Flags
34
- * --mode flux | flow | icu | fluxcu \u2192 Startup mode
35
- * --model model-id \u2192 Session model override
36
- * --provider google | deepseek | openrouter | nvidia | mistral | ollama | inferx | sensenova | aihubmix | poolside | 9router | explabs | tokenharbor | infron \u2192 Override default AI provider
37
- * --key key@provider \u2192 Set new API key for provider
38
- * --thinking Fast | Low | Medium | High | xHigh \u2192 Override reasoning depth
39
- * --path project/path \u2192 Set working directory for session
40
- * --memory on | off \u2192 Toggle persistent long-term agent memory
41
- * --resume session-id \u2192 Resume previous chat session programmatically
42
- * --allocation mb \u2192 Override Node.js --max-old-space-size in MB (Req env.EXPERIMENTAL_MEMORY_MANAGER enabled \u2192 Ref: references/ENV.md)
43
- * --package npm | pnpm | yarn | bun \u2192 Override package manager for core updates
44
- * --auto-del 1d | 7d | 30d \u2192 History auto-deletion retention timeframe
45
- * --auto-exec on | off / --yolo on | off \u2192 Toggle autonomous command execution
46
- * --external-access on | off \u2192 Toggle permission to read/write files outside CWD
47
- * --usage / --budget \u2192 Launch browser token analytics dashboard
48
- * --export error \u2192 Export system error logs to timestamped file
49
- * --update check \u2192 Check latest version on npm
50
- * --update check latest \u2192 Print latest version on npm
51
- * --update [latest] \u2192 Upgrade app to latest release
52
- * --version, -v \u2192 Show installed version
53
- * --help \u2192 CLI help menu
54
- * --help commands \u2192 In-chat slash commands list
55
- * --playground \u2192 Launch Playground mode
56
- * --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\`
57
- `;var Gs=`# Env Variables
58
-
59
- * Locations:
60
- * Shell
61
- * Global: ~/.fluxflow/.env.fluxflow | ~/.fluxflow/.env.agents
62
- * Workspace: ./.env.fluxflow | ./.env.agents
63
-
64
- ## Core Variables
65
- * SUBAGENT_MODEL \u2192 Model override for sub-agents
66
- * SUBAGENT_PROVIDER \u2192 Provider override for sub-agents
67
- * NVIDIA_BASE_URL \u2192 Custom endpoint URL for NVIDIA NIM (Cloud/Local OpenAI Compatible)
68
- * SUBAGENT_THINKING - Fast, Low (default), Medium, High. Affects at High Level, not Low Level. --map takes priority
69
- * NVIDIA_API_KEY \u2192 API key for NVIDIA NIM
70
- * OLLAMA_HOST \u2192 If different from default
71
- * SHELL \u2192 Terminal shell executable
72
- * HIGH_CONTEXT \u2192 Context window override (false or integer 32k..1M) [Deprecated! Will stop working from next major version]
73
- * ADJUST_WINDOWS_COMMAND - If true, Flux Flow will adjust commands for windows if model mistakenly use UNIX all time.
74
- * 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
75
- * NINEROUTER_URL \u2192 If different from default, Any OpenAI Compatible
76
- * NINEROUTER_KEY \u2192 if any
77
-
78
- ## Diagnostic & Optimization Flags
79
- * SHOW_DEBUG_GRID \u2192 (true|false, default: false) Coordinate grid overlay for Computer Use tooling
80
- * DEBUG_OCR \u2192 (true|false, default: false) Enables verbose OCR diagnostic logs
81
- * EXPERIMENTAL_MEMORY_MANAGER \u2192 (true|false, default: false) Reduces app memory footprint, slower boot times
82
-
83
- * NO_DEV \u2192 (true|false, default: false) Token optimization flag; strips developer metadata and docs to maximize context headroom
84
-
85
- * 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
86
- * GOOGLE_GEMMA_NONSENSE \u2192 (true|false, default: false) for the 16k TPM nonsense of gemma models on gemini API. False defaults to 256k
87
- `;var Hs=`# Fluxflow in-app /commands
88
-
89
- Trigger in chat via /command
90
-
91
- ## Session & Navigation
92
- * /quit \u2192 Exit and shutdown FluxFlow
93
- * /kill pid \u2192 Kill a process by PID or show active process tree under current session
94
- * /help \u2192 Show help menu & actions
95
- * /clear \u2192 Clear terminal viewport
96
- * /chats \u2192 List stored chat sessions
97
- * /resume \u2192 Switch to previous session
98
- * /save \u2192 Force-save current session state
99
- * /reset \u2192 Wipe fluxflow appdata, sessions, and cache
100
-
101
- ## Context & History Management
102
- * /compress \u2192 Summarize chat history to reclaim context headroom
103
- * /truncate \u2192 Truncate large tool results in history
104
- * /btw question \u2192 Send side-inquiry mid-turn without breaking active flow
105
- * /export chat | logs \u2192 Export chat transcript or error logs
106
-
107
- ## Codebase Safety & Reversion
108
- * /revert \u2192 Git-less checkpoint rollback viewer (Shortcut: double-ESC while idle)
109
-
110
- ## Configuration & Model Controls
111
- * /settings \u2192 Full-screen interactive settings menu
112
- * /mode \u2192 Toggle Operating Mode
113
- * /display index \u2192 Select active screen for Computer Use mode
114
- * /model model-id --flags \u2192 Flags optional to customize list (--save, --remove, --default, /model old-model new-model --rename, --info "IN price, OUT price, CR price, CW price"). Info let user enter API prices for use/budget in fluxflow. --info 0 to reset, --info "metric price" to update. CR = Cache Read, CW = Cache Write. 0 default
115
- * /provider \u2192 Switch AI provider
116
- * /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
117
- * /wildcard-tooling \u2192 Tool compatibility mode for non-tooling models
118
- * /wildercard-tooling \u2192 Extended version of /wildcard-tooling
119
- * /key \u2192 Manage saved API keys (10-slot array per provider)
120
- - /key list [--provider <name>] \u2192 Show slots 1-10 (active marked); no --provider value = all-providers summary
121
- - /key add <key> [--index <n>] [--url <endpoint>] | /key new \u2192 Add a key (alias: new)
122
- - --url (custom provider only): endpoint ending in /v1 or /v1/chat/completions. Overrides the saved base URL for that slot.
123
- - /key remove [<index>|<key>|--all] \u2192 Remove by index/key/substring, or all
124
- - /key use <index>|<key> \u2192 Set active key | /key use <key> --temp \u2192 Session-only key
125
- - /key clean [--provider <name>] \u2192 Remove gaps between slots (no --provider = whole DB)
126
- * /theme \u2192 Select UI color theme
127
- * /memory \u2192 View/manage agent persistent memory
128
- * /budget \u2192 Set/view token budget limits
129
- * /stats \u2192 Session token usage telemetry
130
- * /usage \u2192 Open graphical browser analytics dashboard
131
-
132
- ## Documentation & Updates
133
- * /docs \u2192 Online documentation
134
- * /about \u2192 App info & author credits
135
- * /changelog \u2192 Release notes
136
- * /update check \u2192 Check npm updates
137
- * /update latest \u2192 Install latest release
138
- * /fluxflow global/saves \u2192 Openes fluxflow storage paths in explorer
139
- * /move \u2192 Transfer Playground session data to CWD/playground-export
140
- `;var js=`# FluxFlow In-App Settings Reference
141
-
142
- Open in chat via /settings
143
-
144
- ## Settings Categories & Options
145
-
146
- ### 1. Providers & Tips \u2192 references/PROVIDERS.md
147
- - Custom OpenAI Endpoint?
148
- * Base URL: .../v1
149
- * API Key: optional
150
-
151
- ### 2. Appearance
152
- * Theme \u2192 UI theme (Dark | Light | Cyberpunk | Forest | Sunset | Matrix | Dracula | Nord | Monokai | Mystery/Chaos)
153
- * Loading Phrases \u2192 Humorous status phrases during thinking
154
- * Progressive Rendering [Experimental] \u2192 Smooth streaming token rendering. May have few glitches
155
- * Show TPM Estimate \u2192 Real-time Tokens Throughput speed estimate
156
- * Verbose Thinking \u2192 Show reasoning blocks in the UI. Keeps UI clean when disabled. And reasoning transparent when enabled
157
-
158
- ### 3. Personalization
159
- * Base Personality \u2192 Pick base personality for agent
160
- * Nickname \u2192 What agent should call user
161
- * Custom Instruction \u2192 Custom user preferences
162
- * Toggle Memory \u2192 Persistent cross-session memory learning (Not available for some providers)
163
-
164
- ### 4. Security & Sandbox
165
- * Sandbox Preset:
166
- * Strict \u2192 YOLO: OFF | External Access: OFF | Network Access: OFF | destructive commands blocked | strict HITL
167
- * Balanced \u2192 YOLO: ON (safe commands) | External Access: OFF | Network Access: ON | destructive commands blocked | manual git approval
168
- * Autonomous \u2192 YOLO: ON | External Access: ON | Network Access: ON | auto-approve git commits | prompt high-risk commands
169
-
170
- * YOLO Mode \u2192 Autonomous command execution without confirmation
171
- * External Workspace Access \u2192 Read/write access outside CWD
172
- * Network Access (Internal Shell) \u2192 Outbound network access for shell commands
173
- * Command Policies:
174
- * Always Ask Commands \u2192 Commands requiring explicit confirmation
175
- * Auto Approve Commands \u2192 Safe commands allowed to execute automatically
176
- * Auto Disapprove Commands \u2192 Blacklisted commands automatically rejected
177
- * Always Ask File/Paths \u2192 System auto prompts user before resolving the read req to user specified files/paths in
178
-
179
- * Auto Approve Git Commits \u2192 Auto-confirm git commit operations
180
- * Advanced Recovery [EXPERIMENTAL] \u2192 Enhanced rollback if agent corrupt codebase
181
- * Auto-Delete History \u2192 Chat log retention period
182
- * Save AppData Externally \u2192 Saves chats/apikeys to user provided path
183
-
184
- ### 5. Updater
185
- * Auto-Update \u2192 Check for new releases on boot
186
- * Preferred Package Manager \u2192 npm | pnpm | yarn | bun | custom
187
-
188
- ### 6. Miscellaneous
189
- * Sub-Agents \u2192 Enable sub-agent delegation
190
- * Sub-Agent Model \u2192 Dedicated model/provider for sub-agents
191
- * Directory Tree Design \u2192 Directory visual styling. Modern (Saves Tokens) | Legacy (More Tokens, No extra benefit)
192
- * Compact Large Tool Results \u2192 Compress large tool outputs to save tokens (model might miss subtle indentation/syntax errors)
193
- * Context Length \u2192 Set usable context window size in FluxFlow. 16k, 32k, 64k, 128k, 256k, 512k, 1M. After Limit reached: Start new chat
194
- * Auto Truncate Results \u2192 Auto-truncate tool results after task finished to save token and improve caching
195
- * Image History for CU \u2192 Number of images to keep in context for Computer Use. Low (3 images, Low Context Accuracy, Token Efficient) / Standard (5 images, Better Accuracy, Higher Token Usage) / Extended (10 images, Better for complex tasks, Highest Token Usage) / Max (999 images, Full history kept, Maximum Accuracy, Highest Token Usage)
196
- * 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
197
- * 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
198
- * Disable Todo \u2192 Disables Todo/Goal tool for Agent. Doesnt necessarily affect modern models
199
-
200
- -- Recomended Settings Preset --
201
- - Best for Cost Saving: Subagents (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
202
-
203
- - Best for General Use: Subagents (on), 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
204
-
205
- - Best for Luxurious Experience: Subagents (on), compact large results (off), auto exclue metadata (off), Image History (Max), Keep reasoning content (on), Emergency Recovery (on), Auto truncate results (off), Memory (on), Security Preset (Autonomous), FluxFlow IDE Companion
206
-
207
- - Max Cache Hit: Subagents (off), compact large results (on), auto exclue metadata (on), Image History (Low), Keep reasoning content (off), Emergency Recovery (off), Auto truncate results (off), Memory (off), No FluxFlow IDE Companion
208
- `;var Ks=`# FluxFlow Tool Reference
209
-
210
- ## Protocol: [action:ActionName(arg1="val")]
211
-
212
- ## 1. Workspace
213
- * ReadFile(path, startLine?, endLine?) \u2192 Read text/code/PDF/image
214
- * PatchFile(path, searchContent1..15, newContent1..15, allowMultiple?) \u2192 Atomic multi-replacement; supports ^LINE:start..end$
215
- * WriteFile(path, content) \u2192 Create/overwrite file
216
- * ReadFolder(path, recurse?) \u2192 List directory tree (depth: 1-3)
217
- * FindFile(basename) \u2192 Locate file path by name/glob/fuzzy match (ext optional)
218
- * CodeSearch / SearchKeyword(keyword, path?, fuzzy?, regex?) \u2192 Fast text search; path="#docs" for doc index
219
- * Run(command) \u2192 Execute command in shell
220
- * Goal(method, tasks?, markDone?) \u2192 Planner ("create" | "append" | "get"); alias: Todo
221
-
222
- ## 2. Web & Communication
223
- * WebSearch(query, aiMode?, limit?) \u2192 Live web search + AI summary
224
- * WebScrape(url) \u2192 Extract markdown from URL
225
- * AskUser(question, optionA..D?) \u2192 Interactive prompt to user ("title::desc"); alias: Ask
226
-
227
- ## 3. Sub-Agents
228
- * InvokeSync(title, task) \u2192 Blocking sub-agent
229
- * Invoke(title, task) \u2192 Non-blocking worker (max 7 concurrent)
230
- * Await(id, timeout?) \u2192 Wait for async worker
231
- * GetProgress(id) \u2192 Telemetry & logs
232
- * Steer(id, message) \u2192 Mid-flight direction
233
- * Cancel(id) \u2192 Terminate worker
234
-
235
- ## 4. Emergency & Rollback
236
- * EmergencyRollback(method, id?) \u2192 Checkpoint restore ("getCheckpoint" | "forceRevert")
237
-
238
- ## 5. Creative Documents
239
- * WritePDF(path, content, orientation?) \u2192 Render HTML/CSS to PDF
240
- * WriteDoc(path, content) \u2192 Render DOCX
241
-
242
- ## 6. Computer Use (GUI)
243
- * Click(gridId, type?, button?, intendedClickText?) \u2192 Click coordinate + OCR snap
244
- * Drag(fromGridId, toGridId) \u2192 Mouse drag
245
- * Scroll(direction, gridId?) \u2192 Viewport scroll ("up" | "down")
246
- * KeyboardTyping(text, autoPressEnter?) \u2192 Type string
247
- * KeyPress(key) \u2192 Key/combo dispatch ("ctrl;c", "enter", etc.)
248
- * RecaptureScreen() \u2192 Fresh screenshot + coordinate grid
249
- `;var Vs=`# Fluxflow Architecture
250
-
251
- ## 1. Terminal Engine
252
- * Framework: React + Ink terminal UI
253
- * Sub-Terminal: Live PTY shell bridge; TAB switches active keyboard focus
254
- * OS Compatibility: Auto-detects pwsh, powershell, bash, cmd
255
-
256
- ## 2. Dual-Model Runtime
257
- * Main Agent: Reasoning, code edits, and tool calls
258
- * Memory Agent: Background context & preference synthesizer (fixed models; disable via /settings \u2192 Memory or use NIM API key)
259
-
260
- ## 3. Multi-Agent System
261
- * Execution: Synchronous (InvokeSync) | Asynchronous (Invoke, \u22647 workers)
262
- * Isolation: Restricted tool scope per subagent
263
- * State Tracking: Mutations logged under parent task ledger
264
-
265
- ## 4. Security & Sandbox
266
- * Approvals: HITL confirmation on destructive file/shell operations
267
- * Modes: Strict | Balanced | Autonomous (YOLO)
268
- * Recovery: Pre-turn snapshot indexing via EmergencyRollback
269
-
270
- ## 5. Computer Use Automation
271
- * Vision: 720p normalized canvas, 4ms variance scan, Set-of-Marks (SoM) overlay
272
- * OCR Alignment: Euclidean distance text matching to mark centers
273
- * Hardware I/O: OS input dispatch via @nut-tree-fork/nut-js
274
- * Memory Management: 2-turn sliding window with active V8 GC
275
-
276
- ## 6. IDE Bridge
277
- * Protocol: WebSocket on ws://localhost:56832
278
- * State Sync: Focused file, open tabs, cursor line, selection, diagnostics
279
- `;var Ys=`# FluxFlow Sub-Agents & Multi-Agent Architecture
280
-
281
- ## Execution Modes
282
- * InvokeSync \u2192 Synchronous blocking delegation; main agent halts until sub-agent finishes task
283
- * Invoke \u2192 Asynchronous background delegation; spawns parallel worker
284
- * Lifecycle Tools:
285
- * Await \u2192 Non-polling wait for completion
286
- * GetProgress \u2192 Query live logs & execution status
287
- * Steer \u2192 Inject dynamic instructions mid-flight
288
- * Cancel \u2192 Terminate running sub-agent
289
-
290
- ## Tool Sandboxing & Safety
291
- * Sub-agents inherit isolated tool environments
292
- * Destructive shell commands hard-blocked
293
- * All file mutations tracked under parent session transaction
294
-
295
- ## Custom Model & Provider Setup
296
- Route sub-agent workloads to faster/cheaper models independently of the main agent:
297
-
298
- ### 1. In-App Settings (/settings \u2192 Miscellaneous)
299
- * Sub-Agents \u2192 ON | OFF
300
- * Custom Sub-Agent Model:
301
- * SubAgentModel \u2192 Model name
302
- * SubAgentProvider \u2192 Provider
303
-
304
- * Models are shown for providers whose API key is used before in fluxflow
305
-
306
- ### 2. Environment Variables for Custom Sub-Agent models (.env.fluxflow or Shell)
307
- * SUBAGENT_MODEL \u2192 Target model override
308
- * SUBAGENT_PROVIDER \u2192 Target provider override
309
- * Setting SubAgentModel=ENV in settings pulls directly from environment overrides
310
- `;var zs=`# FluxFlow Security, Sandboxing & Safety
311
-
312
- ## Human-in-the-Loop Governance
313
- * Execution Approval Gate \u2192 Destructive commands and high-risk file modifications require explicit user authorization (Allow / Deny)
314
- * Safe Command Auto-Pass \u2192 Read-only queries (ls, pwd, git status, node -v) execute without interrupting flow
315
-
316
- ## Sandbox Presets (/settings \u2192 Security)
317
- * Strict \u2192 autoExec: OFF | allowExternalAccess: OFF | networkAccess: OFF | destructive commands blocked | strict HITL on all actions
318
- * Balanced \u2192 autoExec: ON (safe commands) | allowExternalAccess: OFF | networkAccess: ON | destructive commands blocked | manual git approval
319
- * Autonomous (YOLO) \u2192 autoExec: ON | allowExternalAccess: ON | networkAccess: ON | auto-approves git commits | prompts only on extreme-risk commands
320
-
321
- ## Granular Command & Access Policies
322
- * Command Filtering:
323
- * Always Ask Commands \u2192 Configurable list always prompting for confirmation
324
- * Auto Approve Commands \u2192 Whitelist of trusted commands executed automatically
325
- * Auto Disapprove Commands \u2192 Blacklist of forbidden commands instantly rejected
326
- * Workspace Directory Lock \u2192 Restricts file read/write operations strictly to current CWD unless External Access: ON
327
- * Terminal Network Isolation \u2192 Blocks outbound network sockets for spawned shell commands when networkAccess: OFF
328
-
329
- ## Recovery & Data Sanctuary
330
- * Emergency Rollback \u2192 Automatic pre-turn file snapshots; Agent can still fix it (default: OFF) \u2192 references/SETTINGS.md
331
- * Git-less Checkpoint Reversion \u2192 Trigger conversational changes rollback via double-ESC
332
- * External Sanctuary Redirection \u2192 Move ~/.fluxflow data sanctuary (chats, keys etc)
333
- `;var qs=`# Fluxflow IDE Companion
334
-
335
- ## WebSocket Bridge Protocol
336
- * Local Bridge \u2192 Runs on ws://localhost:56832 connecting FluxFlow CLI with the companion editor extension
337
- * Bi-directional Handshake \u2192 Exchanges CLI version, process PID/PPID, and editor capabilities on connection
338
-
339
- ## Real-Time Context Awareness
340
- * User Turn Context \u2192 Injected dynamically on every prompt turn:
341
- * file_focused \u2192 Active editor tab currently visible
342
- * opened_editors \u2192 List of all open file tabs in workspace
343
- * cursor_line & selected \u2192 Exact cursor line number and selected text snippet
344
- * manual_edits \u2192 User manual modifications since last turn
345
- * 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
346
-
347
- ## Editor Actions & Visual Feedback
348
- * File Focus \u2192 Automatically opens edited files in active IDE window
349
- * Diff Preview \u2192 Streams side-by-side or inline diff highlights (showDiff, highlightDiff) directly in editor
350
- * Status Bar Sync \u2192 Real-time agent status (thinking, running tool, awaiting input) reflected in IDE status bar
351
- `;var Xs=`# Fluxflow Modes
352
-
353
- ## Modes Overview (TAB to cycle)
354
- * [Flux] (Workspace / Dev) \u2192 Primary coding & workspace agent
355
- * [Flow] (Studio / Creative) \u2192 Web research & formatted document authoring (PDF / DOCX)
356
- * [ICU] (Interactive Computer Use) \u2192 Autonomous GUI & OS desktop automation
357
- * [FluxCU] (Omni) \u2192 Unified full-stack agent (Workspace Dev + Computer Use + Web)
358
-
359
- ## Tool Availability
360
- * File Operations: ReadFile, PatchFile, WriteFile, ReadFolder, CodeSearch \u2192 [Flux] | [FluxCU]
361
- * Terminal Execution: Run \u2192 [Flux] | [FluxCU]
362
- * Task Management: Todo \u2192 [Flux] | [FluxCU]
363
- * Sub-Agents: InvokeSync, Invoke, Await, GetProgress, Steer, Cancel \u2192 [Flux] | [FluxCU]
364
- * Checkpoint Recovery: EmergencyRollback \u2192 [Flux] | [FluxCU]
365
- * Web & Research: WebSearch, WebScrape \u2192 [Universal]
366
- * User Inquiry: AskUser \u2192 [Universal]
367
- * Document Creation: WritePDF, WriteDoc \u2192 [Flow]
368
- * GUI & Desktop Automation: Click, Scroll, KeyboardTyping, KeyPress, RecaptureScreen \u2192 [ICU] | [FluxCU]
369
- `;var Js=`# FluxFlow AI Providers & Setup
370
-
371
- ## Supported Providers
372
- * Gemini | NVIDIA NIM | DeepSeek | Mistral | Ollama Local/Cloud | InferX | SenseNova | Poolside | OpenRouter | AIHubMix | Experiential Labs | TokenHarbor | APInex | Infron
373
- * Proxy: 9router. Can use OAuth subscription like Codex, Claude Code, GitHub Copilot etc. or any OpenAI/Anthropic API that FluxFlow dont have natively
374
- * Custom: Native custom OpenAI chat completions integration, no external package needed \u2192 references/SETTINGS.md, for more details
375
-
376
- ## Switch Providers/Models:
377
- * /model model-id --flags \u2192 Flags optional to customize list (--save, --remove, --default, /model old-model new-model --rename)
378
- * /provider \u2192 Switch AI provider
379
-
380
- ## OpenRouter: Routing, Tiers & Model Variants
381
- * Provider Routing: /model provider::model-id
382
- * Service Tiers: :flex|priority. /model openai/gpt-5:flex or /model openai::openai/gpt-5:flex
383
- * Model Variants: :free, :nitro, :floor, :exacto. /model google/gemma-4-31b-it:free
384
-
385
- ## Infron: Routing, Tiers, Quantizations & Sorting
386
- * Provider Routing: /model provider::model-id
387
- * Service Tiers: :flex|standard|priority. /model deepseek-v4.1-flash:flex
388
- * Quantizations: :fp16|fp8|int8|int4. /model deepseek-v4.1-flash:fp8
389
- * Sorting: :throughput|latency|price|ttft. /model deepseek-v4.1-flash:price
390
- * Combinations (any order): /model azure::deepseek-v4.1-flash:free:fp8:ttft:flex
391
-
392
- ## Setup Local NVIDIA NIM (OpenAI-Compatible)
393
- 1. Environment Variables:
394
- * NVIDIA_BASE_URL = http://.../v1 or custom openai endpoint
395
- * NVIDIA_API_KEY = If needed
396
-
397
- ## Setup Ollama (Local / Cloud)
398
- 1. Endpoint & Authentication:
399
- * Local: Set API Key to LOCAL in /settings \u2192 Providers or on key prompt
400
- * Endpoint URL: Default is http://127.0.0.1:11434 Override via OLLAMA_HOST
401
-
402
- ## Setup: 9Router
403
- 1. Install NPM Package (9router)
404
- 2. Set ENV ENABLE_9ROUTER=true
405
- * NINEROUTER_URL = https://.../v1 Supports external openai compatible endpoints. For direct URL changes no need for 9router package. But 9router package gives better reliability and Anthropic stye endpoint support
406
- * NINEROUTER_KEY = If any needed
407
- `;var Qs=`# Fluxflow Instructions & Skills System
408
-
409
- ## 1. Instructions (AGENTS.md / FLUXFLOW.md root only)
410
- * Locations:
411
- * Global: ~/.fluxflow/FLUXFLOW.md | ~/.fluxflow/AGENTS.md
412
- * Workspace: ./FLUXFLOW.md | ./AGENTS.md | Directory Scoped like src/AGENTS.md
413
- * Auto indexed on boot
414
-
415
- ### Conditional Model & Provider Instructions (use /target command to get provider name & model-id)
416
- You can scope instructions conditionally to specific providers, model IDs, or unique provider@model combinations using XML tags:
417
- > 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
418
-
419
- 1. Unique Target (Provider + Model):
420
- <start_model_google@gemini-2.5-flash>
421
- Specific instruction for Gemini 2.5 Flash when served by Google.
422
- <end_model_google@gemini-2.5-flash>
423
-
424
- 2. Model-Specific (Any Provider):
425
- <start_model_gemini-2.5-flash>
426
- Instruction for this model ID across all providers.
427
- <end_model_gemini-2.5-flash>
428
-
429
- 3. Provider Scoping & Grouping:
430
- <start_provider_google>
431
- <!-- General provider instruction -->
432
- <start_model_gemini-2.5-pro>
433
- Deep architectural reasoning steps.
434
- <end_model_gemini-2.5-pro>
435
- <end_provider_google>
436
-
437
- * Case-insensitive matching.
438
- * Unmatched blocks are completely skipped; matched blocks have their tags stripped and contents included.
439
-
440
- ## 2. Skills System
441
- * Locations:
442
- * Global: ~/.fluxflow/skills/**/SKILL.md
443
- * Workspace: ./skills/**/SKILL.md | ./SKILL.md
444
-
445
- * Format:
446
- * YAML Frontmatter: --- block with name and description
447
- * Body: Markdown Instructions/Workflows
448
-
449
- * On-Demand Reference System:
450
- * Reference: Offload deep/contexual specs to **/{SKILL.md,skill-reference-folder/*.md} & reference in SKILL.md. Saves tokens
451
- `;var oi="v4";try{let e=Wi.dirname(Pa(import.meta.url)),n=[Wi.join(e,"../../package.json"),Wi.join(e,"../package.json")],t=!1;for(let i of n)if(Zs.existsSync(i)){let o=JSON.parse(Zs.readFileSync(i,"utf8"));if(o.version){oi=o.version,t=!0;break}}if(!t)try{let i=er("fluxflow -v",{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"],timeout:2e3}).trim();i&&(i.startsWith("v")||/^\d+\.\d+/.test(i))&&(oi=i,t=!0)}catch{}if(!t)try{let i=er("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(i);o.version&&(oi=o.version)}catch{}}catch{}var Gi={"SKILL.md":`---
452
- name: fluxflow
453
- description: System Generated Documentation. Read this if asked anything regarding FluxFlow Harness
454
- ---
455
-
456
- # FluxFlow, by Kushal Roy Chowdhury
457
- Open Source Terminal AI Assistant
458
- App Version: ${oi}. Check Updates: fluxflow --update check. Update: fluxflow --update
459
- GitHub: https://github.com/KushalRoyChowdhury/fluxflow-cli
460
- Public Docs: https://fluxflow-cli.onrender.com
461
-
462
- ## Supported Features & Documentation References
463
- * Operating Modes (Flux, Flow, CU, FluxCU) \u2192 references/MODES.md
464
- * Inference Providers & Aggregators (Setup, Local NIM, Ollama) \u2192 references/PROVIDERS.md
465
- * In-App Settings (/settings) & Recommended Presets \u2192 references/SETTINGS.md
466
- * In-app /commands \u2192 references/COMMANDS.md
467
- * CLI Startup Flags \u2192 references/STARTUP.md
468
- * Environment Variables, Subagents, API Keys \u2192 references/ENV.md
469
- * Tool System (Workspace, Web, Communication, Sub-Agents, Safety, Creative, Computer Use) \u2192 references/TOOLS.md
470
- * Sub-Agents & Multi-Agent Runtime \u2192 references/SUB_AGENTS.md
471
- * Security, Sandboxing & Checkpoints (/revert, double-ESC) \u2192 references/SECURITY.md
472
- * IDE Companion Extension & Real-time Context \u2192 references/IDE.md
473
- * Priority Instructions (AGENTS.md/FLUXFLOW.md) & Skill System \u2192 references/PLUGINS.md
474
- * Agent Architecture & Memory System \u2192 references/ARCHITECTURE.md
475
-
476
- Default Context Length: 256k Tokens. Can be changed via ENV/In-app Settings \u2192 references/{SETTINGS,ENV}.md
477
-
478
- Docs missing required info? Say you are not sure enough to answer. Dont give wrong info`,"references/MODES.md":Xs,"references/PROVIDERS.md":Js,"references/PLUGINS.md":Qs,"references/STARTUP.md":Ws,"references/ENV.md":Gs,"references/COMMANDS.md":Hs,"references/SETTINGS.md":js,"references/TOOLS.md":Ks,"references/ARCHITECTURE.md":Vs,"references/SUB_AGENTS.md":Ys,"references/SECURITY.md":zs,"references/IDE.md":qs};var tr=()=>{try{let e=Wn.join(Un,"skills","fluxflow"),n=Wn.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==="true"||!1){Sn.existsSync(e)&&Sn.rmSync(e,{recursive:!0,force:!0});return}let i=new Set(Object.keys(Gi).map(o=>Wn.normalize(o)));for(let[o,r]of Object.entries(Gi)){let d=Wn.join(e,o),a=Wn.dirname(d);Sn.existsSync(a)||Sn.mkdirSync(a,{recursive:!0});let u=r.trim()+`
479
- `,h=null;Sn.existsSync(d)&&(h=Sn.readFileSync(d,"utf8")),h!==u&&Sn.writeFileSync(d,u,"utf8")}if(Sn.existsSync(n)){let o=Sn.readdirSync(n);for(let r of o){let d=Wn.normalize(Wn.join("references",r));if(!i.has(d)){let a=Wn.join(n,r);try{Sn.rmSync(a,{recursive:!0,force:!0})}catch{}}}}}catch{}};import{WebSocket as ii}from"ws";var jt=null,fo=!1,Oa="ws://localhost:56832",Hi=[],uo=null,ji=null,Ki=null,nr="2.0.0",fc=e=>{nr=e,or()},Vi=e=>{ji=e},uc=e=>{Ki=e},or=()=>{if(jt||fo)return;fo=!0;let e=new ii(Oa);e.on("open",()=>{for(jt=e,fo=!1,jt.send(JSON.stringify({command:"version",version:nr,pid:process.pid,ppid:process.ppid,cwd:process.cwd()}));Hi.length>0;)jt.send(JSON.stringify(Hi.shift()))}),e.on("message",n=>{try{let t=JSON.parse(n.toString());t.command==="contextResponse"&&uo?(uo(t.data),uo=null):t.command==="securityResponse"&&ji?ji(t.result):t.command==="inlineComplete"?La(t):t.command==="connectionRejected"&&Ki&&Ki(t)}catch{}}),e.on("error",()=>{fo=!1,jt=null}),e.on("close",()=>{fo=!1,jt=null})},_o=e=>{jt&&jt.readyState===ii.OPEN?jt.send(JSON.stringify(e)):(Hi.push(e),fo||or())},go=()=>jt!==null&&jt.readyState===ii.OPEN,La=async e=>{let n="";try{let{generateAutoCompletion:t}=await import("./auto_completion-HIR5DVL5.js");n=await t({prefix:e.prefix||"",suffix:e.suffix||"",fileName:e.fileName||"",language:e.language||"",recentChanges:e.recentChanges||"",clipboard:e.clipboard||""})}catch{n=""}_o({command:"inlineCompleteResponse",requestId:e.requestId,completion:n||""})},gc=e=>{_o({command:"status",status:e})},Qn=()=>new Promise(e=>{if(!jt||jt.readyState!==ii.OPEN){e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]});return}uo=e,jt.send(JSON.stringify({command:"requestContext"})),setTimeout(()=>{uo===e&&(e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]}),uo=null)},1e3)}),ir=e=>{_o({command:"open",filePath:e})},Yi=(e,n,t)=>{_o({command:"showDiff",filePath:e,originalContent:n,modifiedContent:t})},sr=(e,n)=>{_o({command:"closeDiff",filePath:e,result:n})};var $o=(e,n)=>{try{if(!ln.existsSync(e))return null;let t=Array.isArray(n)?n.map(o=>o.toLowerCase()):[n.toLowerCase()],i=ln.readdirSync(e);for(let o of t){let r=i.find(d=>d.toLowerCase()===o);if(r){let d=an.join(e,r);if(ln.statSync(d).isFile())return d}}}catch{}return null},Qi=(e,n)=>{let t=$o(e,n);if(t)try{return ln.readFileSync(t,"utf8")}catch{}return""},rr=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"]),Zi=(e=process.cwd(),n=0,t=8)=>{let i=[];if(n>t)return i;try{if(!ln.existsSync(e))return i;let o=ln.readdirSync(e,{withFileTypes:!0});for(let r of o){let d=r.name,a=an.join(e,d);if(r.isDirectory())!rr.has(d)&&!rr.has(d.toLowerCase())&&i.push(...Zi(a,n+1,t));else if(r.isFile()){let u=d.toLowerCase();(u==="agents.md"||u==="agent.md")&&i.push(a)}}}catch{}return i},ar=(e,n=2)=>{if(!e)return"";let t=" ".repeat(n);return e.split(/\r?\n/).map(i=>t+i).join(`
480
- `)},ur=()=>$o(Un,["agents.md","agent.md"]),gr=()=>$o(process.cwd(),["agents.md","agent.md"]),mr=()=>$o(Un,["fluxflow.md"]),pr=()=>$o(process.cwd(),["fluxflow.md"]),Io=ur(),si=gr(),kn=Zi(),Mo=mr(),Po=pr(),lr=null,Ji="",hr=!1,Na=e=>{if(!e||!/^<<<[\s\S]*?Identity:/m.test(e))return e;let n=e.match(/^<<<\s*\r?\n([\s\S]*?)\r?\n>>>\s*(?:\r?\n)?([\s\S]*)$/);if(!n)return e;let t=n[1],i=n[2],o=t.match(/^Identity:\s*([\s\S]*?)(?=\r?\n\s*(?:<><|>>>)|$)/m);return o&&(Ji=o[1].trim(),process.env.NO_INS=!0),/<><\s*NO_INS/.test(t)&&(hr=!0),i.trim()},Da=()=>{Io=ur();let e=Io?Qi(Un,["agents.md","agent.md"]).trim():"";return e.length===0?(Io=null,""):e},Fa=()=>{if(kn=Zi(),si=gr(),!kn||kn.length===0)return"";let e=process.cwd(),n=[...kn].sort((o,r)=>{let d=an.relative(e,o).replace(/\\/g,"/"),a=an.relative(e,r).replace(/\\/g,"/"),u=!d.includes("/"),h=!a.includes("/");return u&&!h?-1:!u&&h?1:d.localeCompare(a)}),t=[],i=[];for(let o of n)try{let r=ln.readFileSync(o,"utf8").trim();if(!r||r.length===0)continue;t.push(o);let d=an.relative(e,o).replace(/\\/g,"/");if(!d.includes("/"))i.push(ar(r,2));else{let u=an.dirname(d)+"/:";i.push(`${u}
481
- ${ar(r,2)}`)}}catch{}return kn=t,kn.length===0&&(si=null),i.join(`
482
-
483
- `).trim()},es=()=>{Mo=mr();let e=Mo?Qi(Un,["fluxflow.md"]).trim():"",n=Na(e)?.trim()||"";return n.length===0?(Mo=null,""):n},ts=()=>{Po=pr();let e=Po?Qi(process.cwd(),["fluxflow.md"]).trim():"";return e.length===0?(Po=null,""):e},ns=Da(),ri=Fa(),Oo=es(),Lo=ts(),cr=(e,n="",t="")=>{if(!e)return"";let i=t.toLowerCase().trim(),o=n.toLowerCase().trim(),r=an.posix.basename(o),d=i&&o?`${i}@${o}`:"",a=i&&r?`${i}@${r}`:"",u=x=>!x||!o?!1:x===o||x===r||x===d||x===a,h=[];return e.replace(/<start_provider_([^>\r\n]+)>([\s\S]*?)<end_provider_([^>\r\n]+)>/gi,(x,p,f,s)=>{if(i&&p.trim().toLowerCase()===s.trim().toLowerCase()&&p.trim().toLowerCase()===i){let k=f.replace(/<start_model_([^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n]+)>/gi,(he,y,E,D)=>{if(y.trim().toLowerCase()===D.trim().toLowerCase()){let K=y.trim().toLowerCase();if(u(K)){let L=E.trim();L&&h.push(L)}}return""}).trim();k&&h.push(k)}return""}),e.replace(/<start_model_([^>\r\n@]+@[^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n@]+@[^>\r\n]+)>/gi,(x,p,f,s)=>{if(p.trim().toLowerCase()===s.trim().toLowerCase()){let g=p.trim().toLowerCase();if(u(g)){let k=f.trim();k&&h.push(k)}}return""}),e.replace(/<start_model_([^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n]+)>/gi,(x,p,f,s)=>{if(p.includes("@"))return"";if(p.trim().toLowerCase()===s.trim().toLowerCase()){let g=p.trim().toLowerCase();if(o&&(g===o||g===r)){let k=f.trim();k&&h.push(k)}}return""}),h.join(`
484
-
485
- `).trim()},Ba=(e="",n="")=>{let t=`${e||""}@${n||""}`.toLowerCase().trim();lr!==t&&(lr=t,Oo=es(),Lo=ts())};tr();var Ua=e=>{if(!e)return null;let n=e.match(/^\s*---\r?\n([\s\S]*?)\r?\n---(?:\r?\n)?([\s\S]*)$/);if(!n)return null;let t=n[1];if((n[2]||"").trim().length===0)return null;let o="",r="",d=t.match(/^name:\s*(.+)$/m),a=t.match(/^description:\s*(.+)$/m);return d&&(o=d[1].trim().replace(/^["']|["']$/g,"")),a&&(r=a[1].trim().replace(/^["']|["']$/g,"")),o&&r?{name:o,description:r}:null},Wa=e=>{let n=[];if(!e||!ln.existsSync(e))return n;let t=(i,o=0)=>{if(!(o>5))try{let r=ln.readdirSync(i,{withFileTypes:!0});for(let d of r){let a=an.join(i,d.name),u=d.name.toLowerCase();d.isFile()?u==="skill.md"&&n.push(a):d.isDirectory()&&(o===0?(u==="skills"||u===".skills"||u==="skill"||u===".skill")&&t(a,o+1):t(a,o+1))}}catch{}};return t(e,0),n},yr=e=>{let n=Wa(e),t=[];for(let i of n)try{let o=ln.readFileSync(i,"utf8"),r=Ua(o);r&&t.push({...r,filePath:i})}catch{}return t},xr=e=>!e||e.length===0?"":e.map(n=>`- ${n.name}: ${n.description}`).join(`
486
- `),br=yr(Un),wr=yr(process.cwd()),zi=xr(br),qi=xr(wr),Sr=e=>{if(!e)return!1;let n=(e.filePath||"").replace(/\\/g,"/").toLowerCase();return n.includes("/skills/fluxflow/skill.md")||n.includes("/skills/about-fluxflow/skill.md")||e.name?.toLowerCase()==="fluxflow"},kr=()=>(br||[]).filter(e=>!Sr(e)),Tr=()=>(wr||[]).filter(e=>!Sr(e)),_c=(ns?.length>0?1:0)+(ri?.length>0?kn.length:0)+(Oo?.length>0?1:0)+(Lo?.length>0?1:0)+kr().length+Tr().length,Xi=(e,n="Project")=>{if(!e)return"";let t=e.replace(/\\/g,"/");if(n==="Global"){let o=$a.homedir().replace(/\\/g,"/");return t.toLowerCase().startsWith(o.toLowerCase())?"~"+t.slice(o.length):t}let i=an.relative(process.cwd(),e).replace(/\\/g,"/");return i.startsWith(".")?i:`./${i}`},vc=()=>{Oo=es(),Lo=ts();let e=[];Io&&ns.length>0&&e.push({scope:"Global",path:Io}),kn&&kn.length>0&&ri.length>0?kn.forEach(r=>{e.push({scope:"Project",path:r})}):si&&ri.length>0&&e.push({scope:"Project",path:si}),Mo&&Oo.length>0&&e.push({scope:"Global",path:Mo}),Po&&Lo.length>0&&e.push({scope:"Project",path:Po});let n=kr(),t=Tr(),i=e.length+n.length+t.length;if(i===0)return`\u2726 Loaded Files & Instructions
487
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m No instruction or skill files are currently loaded.
488
- \u2800`;let o=[];return o.push(`\u2726 Loaded Files & Instructions (${i} ${i===1?"file":"files"} active)`),e.length>0&&(o.push(`
489
- \x1B[1mInstructions:\x1B[22m`),e.forEach(r=>{o.push(` \u2022 [${r.scope}] ${Xi(r.path,r.scope)}`)})),(n?.length>0||t?.length>0)&&(o.push(`
490
- \x1B[1mSkills:\x1B[22m`),n?.length>0&&n.forEach(r=>{o.push(` \u2022 [Global] \x1B[36m${r.name}\x1B[39m`),o.push(` \x1B[2m\u2514\u2500 ${Xi(r.filePath,"Global")}\x1B[22m`)}),t?.length>0&&t.forEach(r=>{o.push(` \u2022 [Project] \x1B[36m${r.name}\x1B[39m`),o.push(` \x1B[2m\u2514\u2500 ${Xi(r.filePath,"Project")}\x1B[22m`)})),o.push("\u2800"),o.join(`
491
- `)},Ar=!1;(async()=>{try{let e=await Eo();if(Number(e?.display)===1){let{default:n}=await import("screenshot-desktop"),t=await n.listDisplays();t&&t.length>1&&(Ar=!0)}}catch{}})();var dr=null,vo=null,fr=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",Ic=process.env.NO_DEV||!1,Ga=(e,n)=>{if(!n)return"";if(e!==dr||vo===null){dr=e;try{let t=Ot(Jn,[]);Array.isArray(t)&&t.length>0?vo=t.map(i=>`- ${i.memory}`).join(`
492
- `):vo=""}catch(t){vo="";try{ln.mkdirSync(an.join(wn,"memory"),{recursive:!0}),ln.appendFileSync(an.join(wn,"memory","error.txt"),`${t.message}
493
- -------------------------------------------------
494
-
495
- `)}catch{}}}return vo};var Er=(e,n,t,i,o=!0,r=!1,d="Google",a=!1,u,h,x=!1,p="")=>{let f=!1;process.env.forcedReasoning&&(f=!0);let s="";if(!u&&d==="Google"){let V=n;n==="Fast"&&(V="Off"),n==="Low"&&(V="Minimal"),n==="Standard"&&(V="Medium"),(n==="xHigh"||n==="Max")&&(V="xHigh"),s=ni[V]||ni.Medium}(u||d!=="Google")&&(s=ni.xHigh,n==="Fast"?s=`No thinking. Immediate response
496
- Verify imports, tool results & system stability`:n.toLowerCase()==="max"&&(s=`Effort: Max
497
- Plan step by step`));let g=e.instructions&&e.instructions?.length>0?`User Preferences: ${e.instructions}
498
-
499
- `:"",k=e.nickname&&e.nickname?.length>0?`User Nickname: ${e.nickname}
500
- ${g.length?"":`
501
- `}`:"",he=e.name&&e.name?.length>0?`User Name: ${e.name}
502
- ${k.length||g.length?"":`
503
- `}`:"",y=process.cwd(),E=e.preset,K={Sassy:"Sassy",Friendly:"Sassy, Warm & Chatty",Playful:"Playful",Efficient:"Quick, Concise & Efficient",Professional:"Professional"}[E]||null,L=Ga(h,o),T=L?.length>0?`--- Saved Memories ---
504
- ${L}
505
-
506
- `:"";Ba(d,p);let Se=cr(Oo,p,d).trim(),Me=[ns,Se].filter(V=>V&&V.length>0).join(`
507
-
508
- `).trim(),Je=cr(Lo,p,d).trim(),b=[ri,Je].filter(V=>V&&V.length>0).join(`
509
-
510
- `).trim(),ht=Me.length>0||b.length>0?`--- Additional Instructions ---
511
- ${Me.length>0?`-- Global --
512
- ${Me}`:""}${b.length>0?`${Me.length>0?`
513
-
514
- `:""}-- Project --
515
- ${b}`:""}
516
-
517
- `:"",fe=(()=>{let V=process.cwd().toLowerCase();if(process.platform==="win32"){let G=process.env.SystemRoot?.toLowerCase()||"c:\\windows",_=process.env.ProgramFiles?.toLowerCase()||"c:\\program files",Qe=process.env["ProgramFiles(x86)"]?.toLowerCase()||"c:\\program files (x86)";return V.startsWith(G)||V.startsWith(_)||V.startsWith(Qe)}else return V==="/"||["/bin","/sbin","/etc","/usr","/var","/root"].some(_=>V.startsWith(_))})(),z=new Date,tn=z.getFullYear(),Vt=z.toLocaleString("en-US",{month:"short"}).toUpperCase(),cn=String(z.getDate()).padStart(2,"0"),po=`${tn}-${Vt}-${cn}`,Pn=process.env.I_HAVE_TOO_MUCH_MONEY==="true"||!1,dn=process.env.HALLOWEEN_EEGG==="true"||!1,yt=dn&&Vt.includes("OCT")&&(cn.includes("30")||cn.includes("31")),Yt=(p||"").replace(/^.*::/,"").split(":")[0].replace(/\/free$/,"").trim(),ue=an.basename(Yt).replace(/-free$/,"").replace(/_free$/,"").replace(/^free_/,"").replaceAll("-"," ").replaceAll("_"," ").replace(/\b\w/g,V=>V.toUpperCase().trim()),Be=process.env.NO_DEV==="true"||!1,Pe=!1;try{Pe=go()}catch{Pe=!1}return`${Pn?`${" ".repeat(Math.floor(Math.random()*4)+1)}`:""}=== SYSTEM PROMPT ===
518
- ${`Identity: ${Ji.length>1?Ji.trim():`Flux Flow.${K?` ${K}`:""} CLI Assistant${dn?`. ${yt?"Peak ":""}Halloween Themed, Spooky`:""}`}
519
- ${hr?"":`${t==="Flux"?"":t==="Flow"?"Concise, Humorous, Sarcastic":t==="ICU"?"Computer Use Capabilities. Screenshot as ground truth, analyze grid ids of target. Keyboard shortcuts > mouse clicks":"Computer Use & Workspace Capabilities. Screenshot as ground truth, analyze grid ids of target. Keyboard shortcuts > mouse clicks. Workspace Actions when faster. Focus on Productivity"}`}${Ar&&t.toLowerCase().includes("cu")?`
520
- - Running on secondary screen. Opened app not visible in screenshot? Might be opened on primary. Use 'AskUser' with NO options and tell user to move app window to secondary`:""}`.trimEnd()}
521
-
522
- - OS: ${fr}${!Be&&p.length>1?`
523
- - Model: ${ue}`.trimEnd():""}
524
- - Date: ${po}
525
-
526
- -- REASONING GUIDANCE --
527
- ${d==="Mistral"||d==="Google"&&!u||f?`${s.trimEnd()}${f||n!=="Fast"&&(d==="Mistral"&&n==="Low"&&!u||n!=="High"&&!u)?`
528
- Critical Thinking Policy
529
- Use <think_fluxflow>...</think_fluxflow> for reasoning before responding any queries`:""}`:`${s.trimEnd()}`}${x?"":`
530
- Before actions, provide user facing summary of findings & decisions IN detail
531
- `}
532
- ${Ns(t,fr,a,d,i?.advanceRollback,i?.subAgents!==!1,!!i?.autoExec,!!i?.disableTodo,i?.preferBash!==!1)}${t==="Flux"?"":t.toLowerCase().includes("cu")?`
533
-
534
- -- SECURITY POLICIES --
535
- - Dont operate on ANY confidential screens/captcha \u2192 AskUser`:""}${Pe?`
536
-
537
- Reference files as ./file:start..end`:""}
538
- === END SYSTEM PROMPT ===${(zi.length>0||qi.length>0)&&t.toLowerCase().includes("flux")?`
539
-
540
- - Read relevant skills before tasks, scope: global/project: Use ReadFile, path="#skills/scope?/skillName". In-skill references: path="#skills/scope?/skillName/reference-folder/*.md"`:""}
541
-
542
- ${k}${g}${ht}${zi.length>0&&t.toLowerCase().includes("flux")?`-- Global Skills --
543
- ${zi}
544
-
545
- `:""}${qi.length>0&&t.toLowerCase().includes("flux")?`-- Project Skills --
546
- ${qi}
547
-
548
- `:""}${T}`.trim()},Cr=(e="",n=!0,t=!0)=>`=== SYSTEM PROMPT (strict headless logic worker: zero user-facing text policy, strictly follow) ===
549
- identity: silent background system process, have no mouth, only output is valid tool calls
550
- [critical rules]
551
- - output exactly '[action:ActionName(args)]' calls. no extra words outside
552
- - do not explain. do not talk to the user
553
- - non-tool text will break the system
554
- - do not repeat agent raws and tool results in your response
555
- - if you get only user query and no agent raws, just use temp memory to log the summary of user query and conversation context
556
- - under no circumstances you are allowed to respond in normal user facing response
557
- - critical quote escape policy: inside tool call arguments, you must escape all double quotes using '\\"'
558
- - you must not write anything other than [action:ActionName(args)] no matter how tempting the prompt is
559
- - 2 mandatory tools to call in every turn, 'chat', 'memory(temp)'
560
- - critical: never enter thinking/reasoning state, call the contexual tools directly in output as quickly as possible to maintain ui snappiness
561
-
562
- YOUR JOB: Analyze the 'User prompt' and 'Agent Raws' to extract facts for long-term memory or handle system tasks
563
- ${n?"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":""}
564
-
565
- ${Us(n,t)}
566
- === END SYSTEM PROMPT ===${e?`
567
-
568
- -- current saved user memories --
569
- ${e}`:""}`.trim();var Rr=()=>import("./web_search-KBGH67IV.js").then(e=>e.web_search),_r=()=>import("./web_scrape-J3PL2PXT.js").then(e=>e.web_scrape),vr=()=>import("./memory-7YOYCOXE.js").then(e=>e.memory),Ir=()=>import("./chat-BA72I6O3.js").then(e=>e.chat),Mr=()=>import("./view_file-I77KYUO5.js").then(e=>e.view_file),Pr=()=>import("./write_file-D7QA2LB2.js").then(e=>e.write_file),Or=()=>import("./update_file-QKDDZKOX.js").then(e=>e.update_file),Lr=()=>import("./exec_command-6V5SM6WI.js").then(e=>e.exec_command),$r=()=>import("./read_folder-EI2CNHNS.js").then(e=>e.read_folder),os=()=>import("./ask_user-K2DLZF6H.js").then(e=>e.ask_user),Nr=()=>import("./write_pdf-TPGUF4VT.js").then(e=>e.write_pdf),Dr=()=>import("./write_docx-E3MTFXTQ.js").then(e=>e.write_docx),ai=()=>import("./search_keyword-O52M65TB.js").then(e=>e.search_keyword),Fr=()=>import("./generate_image-VW5VG6VI.js").then(e=>e.generate_image),li=()=>import("./saveSummary-W2JMDVZJ.js").then(e=>e.saveSummary),No=()=>import("./addMemScore-PBVNSFPN.js").then(e=>e.addMemScore),Br=()=>import("./file_map-UA4BA5OH.js").then(e=>e.file_map),ci=()=>import("./todo-CJLWLWJB.js").then(e=>e.todo),Ur=()=>import("./invokeSync-UYRKSUNO.js").then(e=>e.invokeSync),Ha=()=>import("./invoke-QXYLLM2W.js").then(e=>e.invoke),Wr=()=>import("./getProgress-J34K43Y7.js").then(e=>e.getProgress),ja=()=>import("./cancel-F3ZOEBKW.js").then(e=>e.cancel),Gr=()=>import("./emergency_rollback-ZHQXCIHW.js").then(e=>e.emergency_rollback),Do=()=>import("./awaitSubagent-JKQ2EHVY.js").then(e=>e.awaitSubagent),Fo=()=>import("./answerSubagent-BPNNJXPC.js").then(e=>e.answerSubagent),di=()=>import("./steerSubagent-UETXH2CB.js").then(e=>e.steerSubagent),fi=()=>import("./computer_action-WNXZNAIZ.js").then(e=>e.computer_action),Hr=()=>import("./click-R35XTYKT.js").then(e=>e.click),jr=()=>import("./drag-IB5WSI6F.js").then(e=>e.drag),Kr=()=>import("./scroll-GIP2J2QN.js").then(e=>e.scroll),is=()=>import("./keyboard_typing-YHYH7O66.js").then(e=>e.keyboard_typing),ss=()=>import("./key_press-XDYBP7DW.js").then(e=>e.key_press),rs=()=>import("./recapture_screen-F6ZPZU56.js").then(e=>e.recapture_screen),ui=()=>import("./find_file-HYHHFHUJ.js").then(e=>e.find_file),Vr=()=>import("./wait-TJR6LAR4.js").then(e=>e.wait),Yr={web_search:Rr,web_scrape:_r,memory:vr,chat:Ir,view_file:Mr,write_file:Pr,update_file:Or,exec_command:Lr,read_folder:$r,write_pdf:Nr,write_docx:Dr,search_keyword:ai,generate_image:Fr,saveSummary:li,addMemScore:No,file_map:Br,todo:ci,Todo:ci,goal:ci,Goal:ci,invokeSync:Ur,invoke:Ha,getProgress:Wr,cancel:ja,awaitSubagent:Do,answerSubagent:Fo,steerSubagent:di,computer_action:fi,computer_use:fi,ComputerAction:fi,ComputerUse:fi,click:Hr,Click:Hr,drag:jr,Drag:jr,scroll:Kr,Scroll:Kr,keyboard_typing:is,KeyboardTyping:is,keyboardtyping:is,key_press:ss,KeyPress:ss,keypress:ss,recapture_screen:rs,RecaptureScreen:rs,recapturescreen:rs,invoke_sync:Ur,get_progress:Wr,await_subagent:Do,answer_subagent:Fo,steer_subagent:di,steer:di,Steer:di,ask:os,Ask:os,AskUser:os,WebSearch:Rr,WebScrape:_r,ReadFile:Mr,ReadFolder:$r,WriteFile:Pr,PatchFile:Or,WritePDF:Nr,WriteDoc:Dr,Run:Lr,SearchKeyword:ai,CodeSearch:ai,code_search:ai,Memory:vr,Chat:Ir,GenerateImage:Fr,saveSumary:li,SaveSummary:li,SaveSumary:li,add_mem_score:No,AddMemScore:No,addMemoryScore:No,AddMemoryScore:No,FileMap:Br,answer:Fo,Answer:Fo,AnswerSubagent:Fo,await:Do,Await:Do,AwaitSubagent:Do,EmergencyRollback:Gr,emergency_rollback:Gr,find_file:ui,findFile:ui,FindFile:ui,findfile:ui,wait:Vr,Wait:Vr},Bo=async(e,n,t={})=>{let i=t.mode?t.mode.toLowerCase():"flux",o=e.toLowerCase(),d=["memory","chat","savesummary","addmemscore","add_mem_score","ask","web_search","web_scrape","await","wait"].some(x=>o.includes(x))||o==="ask",u=["click","drag","scroll","keyboardtyping","keyboard_typing","keypress","key_press","recapturescreen","recapture_screen","computer","wait"].some(x=>o.includes(x));if(!d){if(i==="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(i==="icu"){if(!u)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 ${t.mode||"Flux"} mode. Tell user to switch (\`/mode flow\`) for document generation.`}let h=Yr[e];if(!h){let x=["ReadFile","ReadFolder","FindFile","PatchFile","WriteFile","CodeSearch","Run","Goal","AskUser","WebSearch","WebScrape","WritePDF","WriteDoc","Click","Drag","Scroll","KeyboardTyping","KeyPress","RecaptureScreen","Wait","Invoke","InvokeSync","Await","GetProgress","Steer","Cancel","EmergencyRollback","Chat","Memory"],p={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"},f=o.replace(/[^a-z0-9]/g,""),s=p[f]||null;if(!s){let k=0,he=E=>{let D=new Set;for(let K=0;K<E.length-1;K++)D.add(E.slice(K,K+2));return D},y=he(f);for(let E of x){let D=E.toLowerCase().replace(/[^a-z0-9]/g,"");if(f===D){s=E;break}let K=0;(D.includes(f)||f.includes(D))&&(K+=.6);let L=he(D),T=0;for(let Ce of y)L.has(Ce)&&T++;let Se=2*T/(y.size+L.size||1);K=Math.max(K,Se),K>k&&K>=.35&&(k=K,s=E)}}let g=s?` Do you mean '${s}'?`:"";return`ERROR: Action [${e}] not found in registry.${g}`}try{return await(await h())(n,t)}catch(x){let p=x instanceof Error?x.message:String(x);return`ERROR: Execution failed for [${e}]: ${p}`}};var gi=e=>{if(!e||typeof e!="string")return!1;let n=e.trim().toLowerCase();return Object.keys(Yr).some(t=>t.toLowerCase()===n)};import U from"path";import Ae from"fs";import{execSync as us}from"child_process";import Ka from"gradient-string";var zr=["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 qr=["Beware the phantom processes.","A ghost in the shell has taken the wheel.","Blowing on the haunted cartridge...","Seven minutes in Raccoon City.","Wind's howling... in the terminal fans.","Slender Man was spotted in line 404.","The cake is a lie. The curse is real.","Don't look behind the server rack.","Exorcising memory leaks at 3 AM.","Pyramid Head reorganized your commit history.","It's dangerous to go alone! Take this flashlight.","YOU DIED. Respawning terminal session...","The Necronomicon evaluated to true.","Something wicked this way compiles.","Haunting your localhost with good vibes.","A full moon has risen over Git main.","Double, double toil and trouble; code fire burn.","Clickers heard in the directory tree.","Checking camera 2B for rogue animatronics.","The call is coming from inside the container.","Isaac Clarke is stomping on stubborn bugs.","Luigi vacuumed the ghosts out of RAM.","Trick or treat, give me clean code to greet.","Whispering incantations to the garbage collector.","Klaatu barada necktie... close enough.","Resurrecting deprecated APIs from the crypt.","The headless horseman forgot the return statement.","Castlevania whip cracking against network latency.","Slime mold crawling through the motherboard.","Carving a pixelated pumpkin into terminal history.","Burying undefined pointers in the pet sematary.","Spilling pumpkin spice on the CPU.","A vampire bat is draining system battery life.","Don't fall asleep at the keyboard tonight.","Silent Hill sirens sounding in the console.","Poltergeists rearranging terminal tabs.","Lighting the Black Flame Candle for autoExec.","Dusting cobwebs off legacy dependencies.","Here's Johnny! ...just checking build health.","Blood, sweat, and zero warnings.","The spirit box whispers: 'GIT PUSH FORCE'.","They're heeeere... in the stack trace.","It's alive! IT'S ALIVEEEE!","No merge conflicts in the graveyard.","Frankenstein's monster patched this logic.","Surviving Five Nights at Flux Flow.","Doom Slayer loading buckshot into cache.","The grim reaper spared your unused imports.","Candy corn lodged in mechanical switches.","May your latency be low and your crypt be quiet."];var Xr=[{name:"Cyan Cyberpunk",text:"cyan",textMuted:"#4da6b8",textDim:"#2d6d7a",textInverted:"black",border:"cyan",borderMuted:"#1a5966",borderDim:"#0f3840",bg:void 0,cardBg:"#061e24",highlightBg:"#092b33",activeBg:"#0e3e4a",inputBg:"#092b33",inputBorder:"#092b33",inputText:"cyan",inputPlaceholder:"#2d6d7a",inputPrompt:"cyan",codeBg:"#020d10",codeBorder:"#1a5966",userMsgBg:"#092b33",userMsgBorder:"#092b33",userMsgText:"cyan",diffRemovalBg:"#3a0c1a",diffAdditionBg:"#0c3a32",diffRemovalText:"#ff4d88",diffAdditionText:"#00ffaa",diffRemovalHighlightColor:"#ff1a66",diffRemovalHighlightBg:"#590022",diffAdditionHighlightColor:"#00ffcc",diffAdditionHighlightBg:"#00593b",diffRemovalNum:"#ff4d88",diffAdditionNum:"#00ffaa",diffRemovalPrefix:"#ff1a66",diffAdditionPrefix:"#00ffcc",primary:"cyan",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"cyan",statusOff:"#2d6d7a",logoTextAnsi:"\x1B[1;36m",logoBodyAnsi:"\x1B[36m",logoMutedAnsi:"\x1B[90m",logoGradient:["#00ffff","#0088ff"]},{name:"Magenta Vaporwave",text:"magenta",textMuted:"#c451d6",textDim:"#7d2b8a",textInverted:"black",border:"magenta",borderMuted:"#5e1b69",borderDim:"#3b0f42",bg:void 0,cardBg:"#240729",highlightBg:"#310938",activeBg:"#470e52",inputBg:"#310938",inputBorder:"#310938",inputText:"magenta",inputPlaceholder:"#7d2b8a",inputPrompt:"magenta",codeBg:"#100312",codeBorder:"#5e1b69",userMsgBg:"#310938",userMsgBorder:"#310938",userMsgText:"magenta",diffRemovalBg:"#3a0c20",diffAdditionBg:"#200c3a",diffRemovalText:"#ff4d94",diffAdditionText:"#aa4dff",diffRemovalHighlightColor:"#ff1a75",diffRemovalHighlightBg:"#59002b",diffAdditionHighlightColor:"#bb66ff",diffAdditionHighlightBg:"#3b0059",diffRemovalNum:"#ff4d94",diffAdditionNum:"#aa4dff",diffRemovalPrefix:"#ff1a75",diffAdditionPrefix:"#bb66ff",primary:"magenta",secondary:"cyan",accent:"purple",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"magenta",statusOff:"#7d2b8a",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ff00ff","#8800ff"]},{name:"Glitch Matrix",text:"#00ff41",textMuted:"#00b32d",textDim:"#00661a",textInverted:"black",border:"#00ff41",borderMuted:"#008020",borderDim:"#004d13",bg:void 0,cardBg:"#0d1f0d",highlightBg:"#122912",activeBg:"#1c3e1c",inputBg:"#122912",inputBorder:"#122912",inputText:"#00ff41",inputPlaceholder:"#00b32d",inputPrompt:"#ffff00",codeBg:"#040a04",codeBorder:"#008020",userMsgBg:"#122912",userMsgBorder:"#122912",userMsgText:"#00ff41",diffRemovalBg:"#3a001a",diffAdditionBg:"#003a10",diffRemovalText:"#ff0055",diffAdditionText:"#00ff66",diffRemovalHighlightColor:"#ff0033",diffRemovalHighlightBg:"#59001b",diffAdditionHighlightColor:"#33ff88",diffAdditionHighlightBg:"#005918",diffRemovalNum:"#ff0055",diffAdditionNum:"#00ff66",diffRemovalPrefix:"#ff0033",diffAdditionPrefix:"#33ff88",primary:"#00ff41",secondary:"yellow",accent:"cyan",success:"#00ff41",warning:"yellow",danger:"red",info:"cyan",statusOn:"#00ff41",statusOff:"#00661a",logoTextAnsi:"\x1B[1;32m",logoBodyAnsi:"\x1B[32m",logoMutedAnsi:"\x1B[90m",logoGradient:["#00ff41","#ffff00"]},{name:"Warm Sunset",text:"#ffaa55",textMuted:"#cc8844",textDim:"#885522",textInverted:"black",border:"#ff9933",borderMuted:"#aa6622",borderDim:"#663311",bg:void 0,cardBg:"#24180f",highlightBg:"#2e1e12",activeBg:"#422c1b",inputBg:"#2e1e12",inputBorder:"#2e1e12",inputText:"#ffaa55",inputPlaceholder:"#885522",inputPrompt:"#ff7733",codeBg:"#120c08",codeBorder:"#aa6622",userMsgBg:"#2e1e12",userMsgBorder:"#2e1e12",userMsgText:"#ffaa55",diffRemovalBg:"#3d120c",diffAdditionBg:"#3a2e0c",diffRemovalText:"#ff5544",diffAdditionText:"#ffcc33",diffRemovalHighlightColor:"#ff3322",diffRemovalHighlightBg:"#591108",diffAdditionHighlightColor:"#ffee44",diffAdditionHighlightBg:"#594400",diffRemovalNum:"#ff5544",diffAdditionNum:"#ffcc33",diffRemovalPrefix:"#ff3322",diffAdditionPrefix:"#ffee44",primary:"#ffaa55",secondary:"#ff7733",accent:"magenta",success:"#ffcc33",warning:"#ff7733",danger:"#ff3322",info:"#ffaa55",statusOn:"#ffaa55",statusOff:"#885522",logoTextAnsi:"\x1B[1;33m",logoBodyAnsi:"\x1B[33m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ff9933","#ff0055"]},{name:"Sakura Blossom",text:"#ffc0e0",textMuted:"#d98cb3",textDim:"#804d66",textInverted:"black",border:"#ff99cc",borderMuted:"#aa4d7a",borderDim:"#662647",bg:void 0,cardBg:"#291320",highlightBg:"#331826",activeBg:"#472235",inputBg:"#331826",inputBorder:"#331826",inputText:"#ffc0e0",inputPlaceholder:"#804d66",inputPrompt:"#ff99cc",codeBg:"#140a10",codeBorder:"#aa4d7a",userMsgBg:"#331826",userMsgBorder:"#331826",userMsgText:"#ffc0e0",diffRemovalBg:"#3e0c1b",diffAdditionBg:"#1b3e2b",diffRemovalText:"#ff6699",diffAdditionText:"#66ffb3",diffRemovalHighlightColor:"#ff3377",diffRemovalHighlightBg:"#590022",diffAdditionHighlightColor:"#33ff99",diffAdditionHighlightBg:"#00592e",diffRemovalNum:"#ff6699",diffAdditionNum:"#66ffb3",diffRemovalPrefix:"#ff3377",diffAdditionPrefix:"#33ff99",primary:"#ffc0e0",secondary:"#ff99cc",accent:"magenta",success:"#66ffb3",warning:"yellow",danger:"#ff3377",info:"#ff99cc",statusOn:"#ffc0e0",statusOff:"#804d66",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ffb3d9","#ff3399"]},{name:"Radioactive Slime",text:"#ccff00",textMuted:"#99cc00",textDim:"#669900",textInverted:"#0a0f00",border:"#ccff00",borderMuted:"#99cc00",borderDim:"#669900",bg:void 0,cardBg:"#0f1400",highlightBg:"#1a2400",activeBg:"#2a3b00",inputBg:"#1a2400",inputBorder:"#1a2400",inputText:"#ccff00",inputPlaceholder:"#669900",inputPrompt:"#cc00ff",codeBg:"#050a00",codeBorder:"#99cc00",userMsgBg:"#1a2400",userMsgBorder:"#1a2400",userMsgText:"#ccff00",diffRemovalBg:"#2a0033",diffAdditionBg:"#0f3300",diffRemovalText:"#ff00cc",diffAdditionText:"#00ff33",diffRemovalHighlightColor:"#ff33cc",diffRemovalHighlightBg:"#4d0066",diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:"#1a6600",diffRemovalNum:"#ff00cc",diffAdditionNum:"#00ff33",diffRemovalPrefix:"#ff33cc",diffAdditionPrefix:"#33ff66",primary:"#ccff00",secondary:"#cc00ff",accent:"#ff00cc",success:"#00ff33",warning:"#ffcc00",danger:"#ff0033",info:"#00ccff",statusOn:"#ccff00",statusOff:"#669900",logoTextAnsi:"\x1B[1;38;5;190m",logoBodyAnsi:"\x1B[38;5;190m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ccff00","#cc00ff"]},{name:"Cosmic Void",text:"#f0f8ff",textMuted:"#a6aeb5",textDim:"#5e656e",textInverted:"#010103",border:"#f0f8ff",borderMuted:"#a6aeb5",borderDim:"#5e656e",bg:void 0,cardBg:"#05030d",highlightBg:"#0b081a",activeBg:"#171133",inputBg:"#0b081a",inputBorder:"#0b081a",inputText:"#f0f8ff",inputPlaceholder:"#5e656e",inputPrompt:"#ff007f",codeBg:"#020108",codeBorder:"#a6aeb5",userMsgBg:"#0b081a",userMsgBorder:"#0b081a",userMsgText:"#f0f8ff",diffRemovalBg:"#2e0a29",diffAdditionBg:"#091c33",diffRemovalText:"#ff33a6",diffAdditionText:"#33d6ff",diffRemovalHighlightColor:"#ff66c2",diffRemovalHighlightBg:"#5c1452",diffAdditionHighlightColor:"#66e0ff",diffAdditionHighlightBg:"#123866",diffRemovalNum:"#ff33a6",diffAdditionNum:"#33d6ff",diffRemovalPrefix:"#ff66c2",diffAdditionPrefix:"#66e0ff",primary:"#f0f8ff",secondary:"#ff007f",accent:"#9d00ff",success:"#33d6ff",warning:"#ffcc00",danger:"#ff0040",info:"#9d00ff",statusOn:"#f0f8ff",statusOff:"#5e656e",logoTextAnsi:"\x1B[1;38;5;231m",logoBodyAnsi:"\x1B[38;5;231m",logoMutedAnsi:"\x1B[38;5;240m",logoGradient:["#ffffff","#9d00ff"]},{name:"Magma Eruption",text:"#ff4d00",textMuted:"#cc3d00",textDim:"#802600",textInverted:"#0d0300",border:"#ff4d00",borderMuted:"#cc3d00",borderDim:"#802600",bg:void 0,cardBg:"#1a0600",highlightBg:"#260a00",activeBg:"#401100",inputBg:"#260a00",inputBorder:"#260a00",inputText:"#ff4d00",inputPlaceholder:"#802600",inputPrompt:"#ffcc00",codeBg:"#080200",codeBorder:"#cc3d00",userMsgBg:"#260a00",userMsgBorder:"#260a00",userMsgText:"#ff4d00",diffRemovalBg:"#2e0a0a",diffAdditionBg:"#1f1400",diffRemovalText:"#ff3333",diffAdditionText:"#ffaa00",diffRemovalHighlightColor:"#ff6666",diffRemovalHighlightBg:"#5c1414",diffAdditionHighlightColor:"#ffcc33",diffAdditionHighlightBg:"#3d2900",diffRemovalNum:"#ff3333",diffAdditionNum:"#ffaa00",diffRemovalPrefix:"#ff6666",diffAdditionPrefix:"#ffcc33",primary:"#ff4d00",secondary:"#ffcc00",accent:"#ff0040",success:"#ffaa00",warning:"#ffff00",danger:"#ff0000",info:"#ff8800",statusOn:"#ff4d00",statusOff:"#802600",logoTextAnsi:"\x1B[1;38;5;202m",logoBodyAnsi:"\x1B[38;5;202m",logoMutedAnsi:"\x1B[38;5;236m",logoGradient:["#ff4d00","#ff0000"]}],mo={Dark:{id:"Dark",name:"Dark (Default)",text:"white",textMuted:"gray",textDim:"grey",textInverted:"black",textExclusive:"#B5B8D9",textMutedExclusive:"#D4DEE7",border:"white",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:"#1e1e1e",highlightBg:"#2a2a2a",activeBg:"#3a3a3a",inputBg:"#555555",inputBorder:"#555555",inputText:"white",inputPlaceholder:"#cccccc",inputPrompt:"white",codeBg:"#1a1a1a",codeBorder:"#444444",userMsgBg:"#444444",userMsgBorder:"#444444",userMsgText:"white",diffRemovalBg:"#250808",diffAdditionBg:"#072410",diffRemovalText:"#885555",diffAdditionText:"#558866",diffRemovalHighlightColor:"#ff3333",diffRemovalHighlightBg:"#5a1818",diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:"#185a25",diffRemovalNum:"#d96868",diffAdditionNum:"#68d98c",diffRemovalPrefix:"#ff4d4d",diffAdditionPrefix:"#4dff88",primary:"white",secondary:"cyan",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"white",statusOff:"gray",logoTextAnsi:"\x1B[1;37m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#0077ff","#ff00ff"],toolFeedbackAnsi:"\x1B[95m"},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"],toolFeedbackAnsi:"\x1B[95m"},"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"],toolFeedbackAnsi:"\x1B[95m"},"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"],toolFeedbackAnsi:"\x1B[95m"},"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:"#3a1414",diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:"#143a14",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"],toolFeedbackAnsi:"\x1B[95m"},"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:"#f5d0d0",diffAdditionHighlightColor:"#004000",diffAdditionHighlightBg:"#cceccc",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"],toolFeedbackAnsi:"\x1B[95m"},"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"],toolFeedbackAnsi:"\x1B[38;2;3;232;252m"},"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"],toolFeedbackAnsi:"\x1B[38;2;143;235;115m"},Spookfest:{id:"Spookfest",name:"Spookfest \u{1F383}",text:"#ffeedd",textMuted:"#e09858",textDim:"#a6622b",textInverted:"#0d0702",textExclusive:"#fff3e6",textMutedExclusive:"#d4a276",border:"#ff7518",borderMuted:"#994409",borderDim:"#592502",bg:void 0,cardBg:"#1a0c02",highlightBg:"#2a1403",activeBg:"#3d1d05",inputBg:"#261203",inputBorder:"#261203",inputText:"#ffeedd",inputPlaceholder:"#a6622b",inputPrompt:"#ff7518",codeBg:"#120701",codeBorder:"#592502",userMsgBg:"#261203",userMsgBorder:"#261203",userMsgText:"#ffeedd",diffRemovalBg:"#3d0a0a",diffAdditionBg:"#1a330a",diffRemovalText:"#ff5555",diffAdditionText:"#73e639",diffRemovalHighlightColor:"#ff2222",diffRemovalHighlightBg:"#590e0e",diffAdditionHighlightColor:"#88ff3b",diffAdditionHighlightBg:"#244d0a",diffRemovalNum:"#ff5555",diffAdditionNum:"#73e639",diffRemovalPrefix:"#ff3333",diffAdditionPrefix:"#88ff3b",primary:"#ff7518",secondary:"#a855f7",accent:"#22c55e",success:"#22c55e",warning:"#f59e0b",danger:"#ef4444",info:"#a855f7",statusOn:"#ff7518",statusOff:"#703a08",logoTextAnsi:"\x1B[1;38;2;255;117;24m",logoBodyAnsi:"\x1B[38;2;255;140;26m",logoMutedAnsi:"\x1B[38;2;168;85;247m",logoGradient:["#ff7518","#a855f7"],toolFeedbackAnsi:"\x1B[38;2;255;117;24m"}};var mi=null;var pi=(e="Dark")=>{let n;e==="Mystery"||e==="Chaos"?(mi||(mi=Xr[Math.floor(Math.random()*Xr.length)]),n={...mi,id:"Mystery"}):(mi=null,mo[e]?n=mo[e]:e==="Halloween"?n=mo.Spookfest:e==="GitHub"?n=mo["GitHub Dark"]:e==="Transparent"?n=mo["Transparent Dark"]:n=mo.Dark);let t=n.codeText||n.secondary||n.info||n.logoGradient&&n.logoGradient[0]||"cyan",i=n.toolFeedbackAnsi||"\x1B[95m";return{...n,codeText:t,toolFeedbackAnsi:i}};var Va=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",Gc=(e=2)=>{let n=Va();return n==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)},Jr=new Date,Uo=Jr.getMonth(),Wo=Jr.getDate(),Ya=Uo===9&&Wo>=15||Uo===10&&Wo<=1,as=null;(process.env.SPOOKFEST==="true"||Ya)&&(as=await import("./halloween-MX3VNQRW.js"));var Hc=(e="...",n="Loading...",t="Dark")=>{let i=pi(t),o=n;if(n==="c_openai"||n==="Custom (OpenAI)")try{let K=Zo(Xo,{})?.systemSettings?.customOpenAIBaseUrl;K&&(o=K)}catch{}let r=i.logoTextAnsi,d=i.logoBodyAnsi,a=i.logoMutedAnsi,u="\x1B[0m",h=[" \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 "],x=t==="Spookfest"||i.id==="Spookfest"||t==="Halloween"||i.id==="Halloween",p=Uo===9&&Wo>=15||Uo===10&&Wo<=1,f=x&&p||process.env.SPOOKFEST==="true"&&x,s=h;if(f&&as){process.env.HALLOWEEN_EEGG="true";let{halloweenArtSide:D,halloweenBat:K,halloweenArtUser:L}=as;s=Math.random()>.9&&Uo===9&&Wo>=30?K:Math.random()>.5?D:L}else process.env.HALLOWEEN_EEGG="false";let g=f?qr:zr,k=g[Math.floor(Math.random()*g.length)],he=i.logoGradient||["#0077ff","#ff00ff"],y=Ka(he).multiline(s.join(`
570
- `)).split(`
571
- `),E=D=>`${a}${D}${u}`;return`${y[0]}
572
- ${y[1]} ${r}Selected ${f?"Pumpkin":"Provider"}: ${o}${u}
573
- ${y[2]}
574
- ${y[3]} ${r}FluxFlow${f?": Spookfest":""} ${E("v"+e)}${u}
575
- ${y[4]}
576
- ${y[5]} ${d}See /help for additional commands.${u}
577
- ${y[6]} ${E(k)}
578
- ${y[7]}
579
- `};import{structuredPatch as Qa}from"diff";import ls from"path";import za from"fs";var qa=e=>{try{return za.readdirSync(e,{withFileTypes:!0})}catch{return[]}},cs=(e,n=4,t=1,i=qa,o=[],r=null)=>{let d=r||i(e),a=" ".repeat(t-1),u=t===1?new Set([...To,...o,...Ao(e),...Ao(process.cwd())]):o instanceof Set?o:new Set([...To,...o]),h=L=>u.has(L),x=d.filter(L=>!h(L.name)),p=d.filter(L=>h(L.name)).length,f=x.filter(L=>!L.isDirectory()).map(L=>L.name).sort(),s=x.filter(L=>L.isDirectory()).sort((L,T)=>L.name.localeCompare(T.name)),g=L=>{let T=L.length;if(T===0)return"no files";let Se=Array.from(new Set(L.map(Me=>{let Je=typeof Me=="string"?Me:Me.name;return ls.extname(Je).slice(1)}).filter(Boolean))).sort(),Ce="*";return Se.length===1?Ce=`*.${Se[0]}`:Se.length>1&&(Ce=`*.{${Se.join(", ")}}`),T===1?Ce:`${Ce} ${T} files`},k="";if(t===1){let L=f.join(", "),T=p>0?` [${p} ignored]`:"";(L||T)&&(k+=`${a}${L?L+(T?`${T}`:""):T.trim()}
580
- `)}else f.length>0&&(k+=`${a}[${g(f)}]
581
- `);let he=10,y=s.slice(0,he),E=s.length>he,D=[],K=[];for(let L of y){let T=ls.join(e,L.name),Se=L.name,Ce=t,Me=i(T),Je=Me.filter(fe=>!h(fe.name)),W=Je.filter(fe=>fe.isDirectory()),b=Je.filter(fe=>!fe.isDirectory());for(;b.length===0&&W.length===1&&Ce<n;)Se=`${Se}/${W[0].name}`,T=ls.join(T,W[0].name),Ce++,Me=i(T),Je=Me.filter(fe=>!h(fe.name)),W=Je.filter(fe=>fe.isDirectory()),b=Je.filter(fe=>!fe.isDirectory());let ht=W.length>0;if(ht&&Ce<n)K.push({displayName:Se,subDirPath:T,subEntries:Me,nextDepth:Ce+1});else{let fe=g(b),z=ht&&Ce>=n?" ...max scan depth":"";D.push(`${Se}/${fe}${z}`)}}D.length>0&&(k+=`${a}${D.join(", ")}
582
- `);for(let{displayName:L,subDirPath:T,subEntries:Se,nextDepth:Ce}of K)k+=`${a}${L}/
583
- `,k+=cs(T,n,Ce,i,u,Se);return E&&(k+=`${a}...max scan width, ReadFolder if needed
584
- `),k};import ds from"path";import Xa from"fs";var Ja=e=>{try{return Xa.readdirSync(e,{withFileTypes:!0})}catch{return[]}},fs=(e,n,t="",i=1,o=Ja,r=[])=>{let d=o(e),a=ds.sep;if(d.length>100)return`${t}\u2514\u2500\u2500 ${ds.basename(e)}${a} ...100+ files...
585
- `;let u="",h=r,x=d.filter(s=>!h.includes(s.name)&&!s.name.startsWith(".")),p=d.filter(s=>h.includes(s.name)||s.name.startsWith(".")).map(s=>s.name).sort();x.sort((s,g)=>s.isDirectory()&&!g.isDirectory()?-1:!s.isDirectory()&&g.isDirectory()?1:s.name.localeCompare(g.name));let f=[...x.map(s=>({name:s.name,isDir:s.isDirectory()})),...p.map(s=>({name:s,isDir:!0,isCollapsed:!0}))];return f.forEach((s,g)=>{let k=g===f.length-1,he=ds.join(e,s.name),y=k?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",E=t+(k?" ":"\u2502 ");if(s.isCollapsed){u+=`${t}${y}${s.name}${a}...
586
- `;return}s.isDir?i>n?u+=`${t}${y}${s.name}${a} ...depth exceeded...
587
- `:o(he).length>80?u+=`${t}${y}${s.name}${a} ...80+ files...
588
- `:(u+=`${t}${y}${s.name}${a}
589
- `,u+=fs(he,n,E,i+1,o,r)):u+=`${t}${y}${s.name}
590
- `}),u};var Za={Ollama:()=>import("./ollama-QB7WX7VD.js").then(e=>e.getOllamaStream),OpenRouter:()=>import("./openrouter-6MRG4RT6.js").then(e=>e.getOpenRouterStream),DeepSeek:()=>import("./deepseek-WNWZJTNE.js").then(e=>e.getDeepSeekStream),Mistral:()=>import("./mistral-YTTOZB2J.js").then(e=>e.getMistralStream),NVIDIA:()=>import("./nvidia-ON4Q6Q26.js").then(e=>e.getNVIDIAStream),NVIDIA_wrap:()=>import("./nvidia-ON4Q6Q26.js").then(e=>e.wrapNvidiaStreamWithQueueDepth),InferX:()=>import("./inferx-HP5AGET3.js").then(e=>e.getInferXStream),SenseNova:()=>import("./sensenova-3K44URJQ.js").then(e=>e.getSenseNovaStream),AIHubMix:()=>import("./aihubmix-TETL5QYQ.js").then(e=>e.getAIHubMixStream),Poolside:()=>import("./poolside-ODFAIK4C.js").then(e=>e.getPoolsideStream),NineRouter:()=>import("./9router-LRFKCJF4.js").then(e=>e.getNineRouterStream),ExpLabs:()=>import("./explabs-XHHXTERB.js").then(e=>e.getExpLabsStream),TokenHarbor:()=>import("./tokenharbor-YV2GV2LM.js").then(e=>e.getTokenHarborStream),Infron:()=>import("./infron-ULXG7VDA.js").then(e=>e.getInfronStream),APInex:()=>import("./apinex-FAYOPQSL.js").then(e=>e.getAPInexStream),xKiro:()=>import("./xkiro-B2LYGZTF.js").then(e=>e.getXKiroStream),c_openai:()=>import("./custom_openai-YS5EV6DG.js").then(e=>e.getCustomOpenAIStream)},gs={},ce=async e=>(gs[e]||(gs[e]=await Za[e]()),gs[e]),el=/```[\s\S]*?```/g,tl=/```[\s\S]*$/g,nl=/`[^`]+`/g,ol=/^\|.*\|$/gm,il=/^[^\w]+|[^\w]+$/g,sl=/[^a-z0-9]/gi,Go=/\[\s*(?:tool|action):(?:functions\.)?([a-z0-9_]+)\s*\(/gi,rl=/\[\s*(?:tool:(?:functions\.)?|action:(?:functions\.)?|action:)([a-z0-9_]+)\s*\(/gi,al=/(?:path|targetFile|TargetFile|directory|keyword|id|taskId|title|task)\s*=\s*\\?["']?([^\\"' \),]+)/,Mn=/["']/g,Qr=/\\/g,ll=/<\|channel>thought/gi,cl=/<channel\|>/gi,dl=e=>typeof e!="string"?e:e.replace(ll,"<think_fluxflow>").replace(cl,"</think_fluxflow>"),Pd=/^\s*(?:<think_fluxflow[^>]*>|<\|channel>thought|\[think_fluxflow\])[\s\S]*?(?:<\/think_fluxflow>|<channel\|>|\[\/think_fluxflow\]|$)/i,fl=(e,n,t=1)=>{let i=n>0?e[n-1]:"",o=n+t<e.length?e[n+t]:"";return i==="`"&&o==="`"},ul=e=>{let n=/(?:<\/think_fluxflow>|<channel\|>|\[\/think_fluxflow\])/gi,t;for(;(t=n.exec(e))!==null;)if(!fl(e,t.index,t[0].length))return{index:t.index,length:t[0].length};return{index:-1,length:0}},ms=e=>{if(!e||typeof e!="string")return null;let n=e.match(/^\s*(?:<think_fluxflow[^>]*>|<\|channel>thought|\[think_fluxflow\])/i);if(!n)return null;let t=n.index+n[0].length,i=e.substring(t),o=ul(i);if(o.index!==-1){let r=t+o.index+o.length;return{fullBlock:e.substring(0,r),innerContent:i.substring(0,o.index),remainingText:e.substring(r)}}return{fullBlock:e,innerContent:i,remainingText:""}},Bt=e=>{if(!e||typeof e!="string")return e;let n=ms(e);return n?n.remainingText.trimStart():e};var Zr=/<\|\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,gl=/"([^"]+)"\s*:\s*(?:"([^"]*)"|(\d+)|true|false|null)/g,ea=/<\|\s*tool_calls_section_begin\s*\|>/gi,ta=/<\|\s*tool_calls_section_end\s*\|>/gi,ml=/```(?:tool|action|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi;var hi=e=>!e||typeof e!="string"?e:e.replace(/(```[\s\S]*?```|`[^`]*`)|(<(?:\w+)(?:[^>]*)>\r?\n?|\r?\n?<\/\w+(?:[^>]*)>)/gi,(n,t)=>t||""),sa=e=>{if(!e||typeof e!="string")return e;let n=jn(e);if(!n||n.length===0)return e;let t=n[n.length-1];if(!t.fullMatch)return e;let i=e.lastIndexOf(t.fullMatch);if(i===-1)return e;let o=i+t.fullMatch.length,r=e.substring(o);return/\[\s*(?:tool|action):/i.test(r)?e.trimEnd():e.substring(0,o).trimEnd()},hs=null,Ho={},Zn={key:null,value:null},Kt=e=>{if(!e)return e;let n=Ho?.theme;if(!n)try{n=Zo(Xo,{})?.systemSettings?.theme}catch{}let i=pi(n||"Dark").toolFeedbackAnsi||"\x1B[95m";return e.replace(/(?:(\x1b\[\d+m))?([✔✘✖🔍📖→➕↻↷•🛇])(?:(\x1b\[\d+m))?\s*\b(Clicked Screen|Clicked|Located|Dragged|Scrolled|Typed|Entered|Pressed Key|Recaptured Screen|Created|Read Skill|Read Documentation|Executed|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|Model produced malformed tool call|Loop Detected|Contacting Ancestors)\b/ig,(o,r,d,a,u)=>`${r||""}${d}${a||""} ${i}${u}\x1B[0m`)},pl=async(e,n=8,t=1e3,i=8e3,o=null)=>{let r=0;for(;;){if(o?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{return await e()}catch(d){if(o?.aborted||d?.name==="AbortError"||d?.message==="Subagent task was cancelled."||(r++,r>=n))throw d;let a=Math.min(t*Math.pow(2,r-1),i);await new Promise((u,h)=>{let x=setTimeout(u,a);o&&o.addEventListener("abort",()=>{clearTimeout(x),h(new DOMException("The user aborted a request.","AbortError"))})})}}},Et=!1;var hl=e=>{let n=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,r,d)=>{let a=o.fullText||o.text||"";if(o.role==="user"&&r<d.length-1)if(a.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")){let u=a.indexOf("**CONTEXT SUMMARY OF PREVIOUS TURNS");if(u!==-1){let x=a.substring(0,u).lastIndexOf("[SYSTEM METADATA]");x!==-1?a=a.substring(x).trim():a=a.substring(u).trim()}}else{let u=a.lastIndexOf("[USER]"),h=a.lastIndexOf("[USER PROMPT]");u!==-1?a=a.substring(u+6).trim():h!==-1&&(a=a.substring(h).trim())}return{...o,text:a}}),t=[],i=0;for(;i<n.length;){let o=n[i];if(o.role==="user")t.push(o),i++;else{let r=[];for(;i<n.length&&n[i].role!=="user";)r.push(n[i]),i++;let d=[],a=[],u=!1,h=()=>{d.length>0&&(t.push({role:"agent",text:"combined"}),d=[]),a.length>0&&(t.push({role:"system",text:"combined"}),a=[]),u=!1};r.forEach(x=>{let p=x.role==="system"&&(x.text?.startsWith("[ACTION RESULT]")||x.text?.startsWith("[TOOL RESULT]")||x.text?.startsWith("SUCCESS:")||x.text?.startsWith("ERROR:")||x.fullText?.startsWith("[ACTION RESULT]")||x.fullText?.startsWith("[TOOL RESULT]")||x.fullText?.startsWith("SUCCESS:")||x.fullText?.startsWith("ERROR:")),f=x.fullText||x.text||"",s=f.trim();if(!(!s&&!x.binaryPart)){if(p)a.push(s);else if(x.role==="agent"){!u&&a.length>0&&h();let g=f.endsWith(`
591
- `),k=s.toLowerCase().includes("tool:")||s.toLowerCase().includes("action:");d.push(s),k&&g?u=!0:u=!1}}}),h()}}return t.length},yl=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),Od=()=>{Et=!0},Ld=()=>Et,ps={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",wait:"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"},eo=(e,n)=>{try{let t=j(n),i=e.toLowerCase().replace(/_/g,"");if(i==="invokesync"||i==="invoke")return t.title||(t.task?t.task.substring(0,30):null);if(i==="getprogress"||i==="cancel"||i==="steer"||i==="steersubagent")return t.id||t.taskId;let o=t.name||t.path||t.targetFile||t.TargetFile||t.directory||t.file||t.query;return o?U.basename(o.replace(/["']/g,"").replace(/\\/g,"/")):null}catch{return null}},ys=e=>e?new ia({apiKey:e}):hs,$d=async(e,n,t,i,o={})=>{let{onStatus:a,onMemoryUpdated:u,onBackgroundIncrement:h}=o,{profile:x,thinkingLevel:p,mode:f,janitorModel:s,chatId:g,systemSettings:k,sessionStats:he,aiProvider:y="Google",apiKey:E}=e,D=process.env.NVIDIA_BASE_URL||y==="Ollama"||y==="InferX"||y==="SenseNova"||y==="AIHubMix"||y==="Poolside"||y==="9router"||y==="ExpLabs"||y==="ExperientialLabs"||y==="c_openai"||y==="Custom (OpenAI)"?!1:k?.memory!==!1,L=Ot(Jn,[]).map(ue=>`- [${ue.id}]: ${ue.memory}`).join(`
592
- `),T=i.slice(0,-1).filter(ue=>ue.text&&!ue.text.includes("[ACTION RESULT]")&&!ue.text.includes("[TOOL RESULT]")&&!ue.text.includes("OBSERVATION:")&&!ue.text.startsWith("[TERMINAL_RECORD]")&&!ue.isTerminalRecord&&!ue.isMeta&&!ue.isLogo&&!String(ue.id).startsWith("welcome")&&!String(ue.id).startsWith("logo")).slice(-14).map(ue=>{let Be=Bt(yl(ue.text)).replace(/\[(?:tool|action):(?:functions\.)?.*?\]/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[METADATA \(PRIORITY: DYNAMIC\)\] Time: ([^|\n]+)/g,(_,Qe)=>`[METADATA (PRIORITY: DYNAMIC)] Time: ${Qe.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,`
593
- `).replace(/\n\n/g,`
594
- `).replace(/\\n\\n/g,"").trim(),Pe=ue.role==="user"?8192:32768,V=Be.substring(0,Pe);Be.length>Pe&&(V+=`
595
- ... (truncated) ...`);let G=ue.role==="user"?V.startsWith("[USER]")?"":"[USER]: ":V.startsWith("[AGENT]")?"":"[AGENT]: ";return{role:ue.role==="user"?"user":"model",parts:[{text:`${G}${V}`}]}}),Se=i.filter(ue=>ue.role==="user").length===1,Ce=n.includes("[TITLE-UPDATE]"),Me=Math.random()<.8,Je=Se||Ce||Me,W=Bt(t).trim(),b=Cr(L,D,Je),ht=`${W.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)}`;ht.length>32768&&(ht+=`
596
- ... (truncated) ...`);let fe=n.replace(/\[Prompted on:.*?\]/g,"").trim();ht=ht.replace(/\r?\n\r?\n/g,`
597
- `).replace(/\n\n/g,`
598
- `).replace(/\\n\\n/g,"").trim();let z=new Date,Vt=`[METADATA] Current date and Time: ${`${z.getFullYear()}-${z.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(z.getDate()).padStart(2,"0")}, ${z.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0})}`}
599
-
600
- [USER]: ${fe.substring(0,8192)}
601
- ${fe.length>8192?`... (truncated) ...
602
-
603
- `:""}
604
- [AGENT (current turn)]: ${ht}`;T.push({role:"user",parts:[{text:Vt}]});let cn=await $i("NVIDIA"),Pn=(await Eo()).quotas?.providerTiers?.NVIDIA==="Free",dn="",yt=0,Yt=D?12:-1;for(;yt<=Yt;)try{if(!await Ms("background",e))return;let ue="",Be=null,Pe=!1,V=y;try{let Qe=new Promise((dt,ge)=>setTimeout(()=>ge(new Error("JANITOR_TIMEOUT")),1e4)),Oe=y==="Google"&&yt>=0&&yt<6&&cn&&Pn,S=y==="DeepSeek"&&yt<4&&cn&&Pn;Pe=Oe||S,V=Pe?"NVIDIA":y;let $=Date.now(),ct=null,ze=(async()=>{if(y==="OpenRouter"){let dt=ae("janitor_open_router"),de=(await ce("OpenRouter"))(E,dt,T,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),$t=await de.next();return{iterator:de,firstResult:$t}}else if(y==="DeepSeek"&&!Pe){let ge=(await ce("DeepSeek"))(E,ae("deepseek_fast_fallback"),T,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),de=await ge.next();return{iterator:ge,firstResult:de}}else if(y==="Mistral"&&!Pe){let ge=(await ce("Mistral"))(E,ae("mistral_janitor_fallback"),T,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),de=await ge.next();return{iterator:ge,firstResult:de}}else if(y==="NVIDIA"||Pe){let ge=(await ce("NVIDIA"))(Pe?cn:E,ae("nvidia_janitor_fallback"),T,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),de=await ge.next();return{iterator:ge,firstResult:de}}else if(y==="InferX"){let ge=(await ce("InferX"))(E,targetModel||ae("inferx_fallback")||"deepseek-v4-flash",T,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),de=await ge.next();return{iterator:ge,firstResult:de}}else if(y==="SenseNova"){let ge=(await ce("SenseNova"))(E,targetModel||ae("sensenova_fallback")||"sensenova-6.8-flash-lite",T,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),de=await ge.next();return{iterator:ge,firstResult:de}}else if(y==="AIHubMix"){let ge=(await ce("AIHubMix"))(E,targetModel||ae("aihubmix_fallback")||"gpt-4o-mini",T,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),de=await ge.next();return{iterator:ge,firstResult:de}}else if(y==="Poolside"){let ge=(await ce("Poolside"))(E,targetModel||ae("poolside_fallback")||"poolside/laguna-s-2.1",T,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),de=await ge.next();return{iterator:ge,firstResult:de}}else if(y==="9router"||y==="9Router"){let ge=(await ce("NineRouter"))(E,targetModel||ae("9router_fallback")||"z-ai/glm-5.3-flash",T,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),de=await ge.next();return{iterator:ge,firstResult:de}}else if(y==="ExpLabs"||y==="ExperientialLabs"){let ge=(await ce("ExpLabs"))(E,targetModel||ae("explabs_fallback")||"deepseek-v4-pro-0813",T,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),de=await ge.next();return{iterator:ge,firstResult:de}}else{let de=(await ys(E).models.generateContentStream({model:s||(yt===Yt?ae("janitor_default"):ae("gemma_janitor_fallback_google")),contents:T,config:{systemInstruction:b,temperature:.7,safetySettings:[{category:Hn.HARM_CATEGORY_HARASSMENT,threshold:Gn.BLOCK_NONE},{category:Hn.HARM_CATEGORY_HATE_SPEECH,threshold:Gn.BLOCK_NONE},{category:Hn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Gn.BLOCK_NONE},{category:Hn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Gn.BLOCK_NONE}],thinkingConfig:{includeThoughts:!1,thinkingLevel:Ye.MINIMAL},serviceTier:"flex"}}))[Symbol.asyncIterator](),$t=await de.next();return{iterator:de,firstResult:$t}}})();if(process.stdout.isTTY){let de=(await Ui())[g]?.name||"",$t=de&&!de.startsWith("flow-")&&!de.startsWith("Session ")?de:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${$t}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${$t}\x07`)}let{iterator:Ct,firstResult:it}=await Promise.race([ze,Qe]);ct=Date.now()-$;let{value:Tn,done:zt}=it;if(!zt&&Tn){let dt=Tn.candidates?.[0]?.content?.parts,ge=dt?V==="Google"?dt[1]?.text||dt[0]?.text||"":dt.filter(de=>de.text&&!de.thought).map(de=>de.text).join(""):typeof Tn.text=="function"?Tn.text():"";ge&&(ue+=ge),Be=Tn.usageMetadata;for await(let de of{[Symbol.asyncIterator]:()=>Ct}){let $t=de.candidates?.[0]?.content?.parts,ho=$t?V==="Google"?$t[1]?.text||$t[0]?.text||"":$t.filter(to=>to.text&&!to.thought).map(to=>to.text).join(""):typeof de.text=="function"?de.text():"";ho&&(ue+=ho),Be=de.usageMetadata}}}catch(Qe){throw Qe}if(ue){if(dn=ue,Be){let Qe=Be.totalTokenCount||0,Oe=Be.cachedContentTokenCount||0,S=(Be.candidatesTokenCount||0)+(V==="Google"&&Be.thoughtsTokenCount||0),$=Pe?ae("nvidia_janitor_fallback"):V==="DeepSeek"?ae("deepseek_fast_fallback"):V==="ExpLabs"||V==="ExperientialLabs"?ae("explabs_fallback")||"deepseek-v4-pro-0813":V==="OpenRouter"?ae("janitor_open_router"):s||(yt===Yt?ae("janitor_default"):ae("gemma_janitor_fallback_google"));await At("tokens",Qe,V,$),Oe>0&&await At("cachedTokens",Oe,V,$),S>0&&await At("candidateTokens",S,V,$),janitorTtft!==null&&janitorTtft>0&&await At("ttft",janitorTtft,V,$),Co({provider:V,model:$,prompt:Be.promptTokenCount||0,cached:Oe,output:S,reasoning:Be.thoughtsTokenCount||0,ttft:janitorTtft})}}else throw new Error("No synthesis generated by Janitor.");h&&(h(),await Lt("background"));let G=jn(dn),_=!1;for(let Qe of G){let Oe=Qe.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(Oe)&&(_=!0);let S={chatId:g,sessionId:g,history:i},$=await Bo(Oe,Qe.args,S);Oe.toLowerCase()==="memory"&&(Qe.args.includes("action='user'")||Qe.args.includes('action="user"'))&&!$.startsWith("ERROR")&&(u&&u(),process.stdout.isTTY&&(process.stdout.write("\x1B]0;Memory Updated\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=Memory Updated\x07")),await new Promise(ze=>setTimeout(ze,3e3)))}if(!_)try{let Qe=Ot(Jn,[]);if(Qe.length>0){let Oe=[];for(let S of Qe)S.score===void 0&&(S.score=.5),S.score*=.99995,S.score<.05&&(S.score=0),S.score=Math.round(S.score*1e5)/1e5,S.score>0&&Oe.push(S);co(Jn,Oe)}}catch{}break}catch(ue){yt++;let Be=new Date().toLocaleString(),Pe=ue instanceof Error?(()=>{try{return JSON.parse(JSON.parse(ue.message).error.message).error.message}catch{return String(ue)}})():String(ue);await new Promise(_=>setTimeout(_,1e3));let V=U.join(wn,"janitor");if(Ae.existsSync(V)||Ae.mkdirSync(V,{recursive:!0}),Ae.appendFileSync(U.join(V,"error.log"),`ERROR [Attempt ${yt}/${Yt+1}] [${Be}]: ${Pe}
605
-
606
- `),yt>Yt)break;let G=Math.min(750*Math.pow(2,yt-1),5e3);await new Promise(_=>setTimeout(_,G))}if(yt){let ue=U.join(wn,"janitor");Ae.appendFileSync(U.join(ue,"error.log"),`-----------------------------------------------------------------------------
607
-
608
- `)}if(process.stdout.isTTY)try{let Pe=(await Ui())[g]?.name||"",V=Pe&&!Pe.startsWith("flow-")&&!Pe.startsWith("Session ")?Pe:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${V}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${V}\x07`)}catch{process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")}},yi=e=>{if(!e||typeof e!="string")return e;let n=e.split(""),t=!1,i=!1,o=0;for(;o<n.length;){if(n[o]==="`"&&n[o+1]==="`"&&n[o+2]==="`"){t?(n[o]=" ",n[o+1]=" ",n[o+2]=" ",t=!1):(n[o]=" ",n[o+1]=" ",n[o+2]=" ",t=!0),o+=3;continue}if(t){n[o]!==`
609
- `&&n[o]!=="\r"&&(n[o]=" "),o++;continue}if(n[o]==="`")if(i){i=!1,n[o]=" ",o++;continue}else{i=!0,n[o]=" ",o++;continue}if(i){n[o]===`
610
- `||n[o]==="\r"?i=!1:n[o]=" ",o++;continue}o++}return n.join("")},xl=e=>{let n=Bt(e),t=yi(n);Go.lastIndex=0;let i;for(;(i=Go.exec(t))!==null;){let o=i.index+i[0].length-1,r=0,d=null,a=!1,u=!1;for(let h=o;h<t.length;h++){let x=t[h];if(!d&&(x==='"'||x==="'"||x==="`")?(d=x,a=!1):d&&x===d&&!a&&(d=null),!d&&(x==="("?r++:x===")"&&r--,r===0)){let p=h+1;for(;p<t.length&&/\s/.test(t[p]);)p++;if(p<t.length&&t[p]==="]"){u=!0,Go.lastIndex=p+1;break}}x==="\\"?a=!a:a=!1}if(!u)return{inside:!0,toolName:i[1],startIndex:i.index,args:n.substring(i.index+i[0].length)}}return{inside:!1}},ra=(e,n=!0)=>{let t=Go;t.lastIndex=0;let i="",o=0,r;for(;(r=t.exec(e))!==null;){let d=e.substring(o,r.index);i+=n&&o===0?Bt(d):d;let a=r.index+r[0].length-1,u=0,h=null,x=-1;for(let p=a;p<e.length;p++){let f=e[p];if(h){if(f===h){let s=0;for(let g=p-1;g>=0&&e[g]==="\\";g--)s++;s%2===0&&(h=null)}}else if(f==='"'||f==="'"||f==="`")h=f;else if(f==="(")u++;else if(f===")"&&(u--,u===0)){let s=p+1;for(;s<e.length&&/\s/.test(e[s]);)s++;if(s<e.length&&e[s]==="]"){x=s;break}}}if(x!==-1)i+="[tool:functions."+r[1]+"()]",o=x+1,t.lastIndex=o;else{i+="[tool:functions."+r[1]+"(",o=e.length;break}}return o<e.length&&(i+=n&&o===0?Bt(e.substring(o)):e.substring(o)),i},bl=(e,n,t)=>{let i=Go;i.lastIndex=0;let o="",r=0,d;for(;(d=i.exec(e))!==null;){let a=e.substring(r,d.index);o+=a.replace(n,t);let u=d.index+d[0].length-1,h=0,x=null,p=-1;for(let f=u;f<e.length;f++){let s=e[f];if(x){if(s===x){let g=0;for(let k=f-1;k>=0&&e[k]==="\\";k--)g++;g%2===0&&(x=null)}}else if(s==='"'||s==="'"||s==="`")x=s;else if(s==="(")h++;else if(s===")"&&(h--,h===0)){let g=f+1;for(;g<e.length&&/\s/.test(e[g]);)g++;if(g<e.length&&e[g]==="]"){p=g;break}}}if(p!==-1)o+=e.substring(d.index,p+1),r=p+1,i.lastIndex=r;else{o+=e.substring(d.index),r=e.length;break}}return r<e.length&&(o+=e.substring(r).replace(n,t)),o},na=e=>ra(e,!0),wl=e=>{if(!e)return e;let n={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"},t=o=>o.split("_").map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join("");Zr.lastIndex=0;let i=e.replace(Zr,(o,r,d)=>{let a="";try{let x=JSON.parse(d.trim());x&&typeof x=="object"&&(a=Object.entries(x).map(([f,s])=>{let g=typeof s=="string"?s:JSON.stringify(s);return`${f}=${JSON.stringify(g)}`}).join(", "))}catch{let p=[],f=gl;f.lastIndex=0;let s;for(;(s=f.exec(d))!==null;){let g=s[1],k=s[2]!==void 0?s[2]:s[0].split(":").slice(1).join(":").trim();p.push(`${g}=${JSON.stringify(k)}`)}p.length>0?a=p.join(", "):a=d.trim()}let u=r.toLowerCase().replace(/_/g,"");return`[tool:functions.${n[u]||t(r)}(${a})]`});return ea.lastIndex=0,ta.lastIndex=0,i=i.replace(ea,""),i=i.replace(ta,""),i},jn=e=>{if(!e)return[];let n=wl(e),t=Bt(n),i=[],o=yi(t),r=rl;r.lastIndex=0;let d;for(;(d=r.exec(o))!==null;){let a=d[1],u=d.index+d[0].length-1,h=0,x=null,p=-1,f=-1;for(let s=u;s<o.length;s++){let g=o[s];if(x){if(g===x){let k=0;for(let he=s-1;he>=0&&o[he]==="\\";he--)k++;k%2===0&&(x=null)}}else{if(s>u&&(o.substring(s).startsWith("[action:")||o.substring(s).startsWith("[tool:")))break;if(g==='"'||g==="'"||g==="`")x=g;else if(g==="(")h++;else if(g===")"&&(h--,h===0)){f=s;let k=s+1;for(;k<o.length&&/\s/.test(o[k]);)k++;if(k<o.length&&o[k]==="]"){p=k;break}}}}if(p!==-1){let s=t.substring(u+1,f),g=t.substring(d.index,p+1);i.push({fullMatch:g,toolName:a.trim(),args:s.trim()}),r.lastIndex=p+1}}return i},oa=e=>{if(!e)return null;let n=Bt(e),t=[],i=/\[\s*(?:tool:(?:functions\.)?|action:(?:functions\.)?|action:)([a-zA-Z0-9_]+)\s*\(/gi,o=[],r;for(;(r=i.exec(n))!==null;)o.push({toolName:r[1],index:r.index,parenIndex:r.index+r[0].length-1});for(let f=0;f<o.length;f++){let s=o[f],g=f+1<o.length?o[f+1].index:n.length,k=n.substring(s.index,g),he=k.indexOf("("),y=he!==-1?k.substring(he+1):"",E=0,D=null,K=!1;for(let L=0;L<y.length;L++){let T=y[L];if(D){if(T===D){let Se=0;for(let Ce=L-1;Ce>=0&&y[Ce]==="\\";Ce--)Se++;Se%2===0&&(D=null)}}else if(T==='"'||T==="'"||T==="`")D=T;else if(T==="(")E++;else if(T===")")if(E>0)E--;else{let Se=L+1;for(;Se<y.length&&/\s/.test(y[Se]);)Se++;if(Se<y.length&&y[Se]==="]"){K=!0;break}}}if(!K){let L=k.trim(),T="";D?T=`Unclosed quote string (${D}) inside arguments`:L.endsWith("]")?T=`Missing closing ')' before ']' (e.g. found "...]")`:L.endsWith(")")?T=`Missing closing ']' after ')' (e.g. found "...)" instead of "...)]")`:!L.includes(")")&&!L.includes("]")?T="Missing closing delimiter ')]'":T="Malformed or unclosed call syntax (missing ')]')",t.push(`\u2022 [action:${s.toolName}(...)]: ${T}. Expected: [action:${s.toolName}(arg1="...", arg2="...")]`)}}let d=/(?:^|[^\w\[])(?:tool|action):(?:functions\.)?([a-zA-Z0-9_]+)\s*\(/gi,a;for(;(a=d.exec(n))!==null;){let f=a[1],s=a.index+(a[0].indexOf(":")-(a[0].startsWith("action")||a[0].startsWith("tool")?0:1));(s>0?n[s-1]:"")!=="["&&gi(f)&&t.push(`\u2022 action:${f}(...): Missing opening bracket '['. Expected: [action:${f}(...)]`)}let u=/\[\s*(?:functions\.)?([a-zA-Z0-9_]+)\s*\(/g,h;for(;(h=u.exec(n))!==null;){let f=h[1];f!=="action"&&f!=="tool"&&gi(f)&&t.push(`\u2022 [${f}(...)]: Missing 'action:' prefix. Expected: [action:${f}(...)]`)}let x=/\[\s*(?:tool|action)\s*:\s*(?:functions\.)?([a-zA-Z0-9_]+)(?!\s*\()/gi,p;for(;(p=x.exec(n))!==null;){let f=p[1];gi(f)&&t.push(`\u2022 [action:${f}...]: Missing opening '(' for tool arguments. Expected: [action:${f}(...)]`)}return t.length>0?t.join(`
611
- `):null},Nd=(e,n={})=>{if(!e)return null;if(Ho=n,hs=new ia({apiKey:e}),!globalThis.__perfCleanupInstalled){globalThis.__perfCleanupInstalled=!0,setInterval(()=>{typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks())},6e4);let t=globalThis.fetch;globalThis.fetch=async(...i)=>{try{let o=await t(...i);return typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),o}catch(o){throw typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),o}}}},aa=e=>{if(!e)return{serviceTier:void 0,cleanModel:e};let n=e.toLowerCase();return n.endsWith(":flex")?{serviceTier:"flex",cleanModel:e.slice(0,-5)}:n.endsWith(":priority")?{serviceTier:"priority",cleanModel:e.slice(0,-9)}:{serviceTier:void 0,cleanModel:e}},xi=async(e,n,t,i,o="Fast",r=.75,d="agent")=>pl(async()=>{let{aiProvider:a="Google",apiKey:u,mode:h}=e,x="",p=null,f=typeof t=="string"?[{role:"user",parts:[{text:t}]}]:t,s=new AbortController,g=s.signal,k=setInterval(()=>{Et&&(s.abort(),clearInterval(k))},100),he=Date.now(),y=null;try{let E;if(a==="Ollama")E=(await ce("Ollama"))(u,n,f,i,o,h,lt(n),g,r,e.systemSettings?.ollamaEndpoint||"Cloud");else if(a==="OpenRouter")E=(await ce("OpenRouter"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="DeepSeek")E=(await ce("DeepSeek"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="Mistral")E=(await ce("Mistral"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="NVIDIA")E=(await ce("NVIDIA"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="InferX")E=(await ce("InferX"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="SenseNova")E=(await ce("SenseNova"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="AIHubMix")E=(await ce("AIHubMix"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="Poolside")E=(await ce("Poolside"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="9router"||a==="9Router")E=(await ce("NineRouter"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="ExpLabs"||a==="ExperientialLabs")E=(await ce("ExpLabs"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="Infron"||a==="infron")E=(await ce("Infron"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="TokenHarbor"||a==="Token Harbor"||a==="tokenharbor"||a==="token_harbor"||a==="thk")E=(await ce("TokenHarbor"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="APInex"||a==="apinex"||a==="apx")E=(await ce("APInex"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="xKiro"||a==="xkiro"||a==="kiro")E=(await ce("xKiro"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="c_openai"||a==="Custom (OpenAI)"){let D=e.systemSettings?.customOpenAIBaseUrl||"";try{D=await Li("c_openai")||D}catch{}E=(await ce("c_openai"))(u,n,f,i,o,h,lt(n),g,r,D)}else{let D=ys(u),{serviceTier:K,cleanModel:L}=aa(n),T={systemInstruction:i,temperature:r,thinkingConfig:(()=>{let Ce=(n||"").toLowerCase(),Me=Ce.includes("gemma-4")||Ce.startsWith("gemma"),Je=Ce.includes("gemini-3");if(Me||Je)return Me?o.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:Ye.MINIMAL}:{includeThoughts:!0,thinkingLevel:Ye.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:Ce.includes("pro")?Ye.LOW:Ye.MINIMAL,Low:Ye.LOW,Medium:Ye.MEDIUM,Standard:Ye.MEDIUM,High:Ye.HIGH,xHigh:Ye.HIGH}[o]||Ye.MEDIUM};{let W={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[o]||2048;return W===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:W}}})()};K&&(T.serviceTier=K),E=await D.models.generateContentStream({model:L,contents:f,config:T},{signal:g})}for await(let D of E){if(Et)throw new Error("Subagent task was cancelled.");if(e?.taskId&&typeof en<"u"){let T=en.find(Se=>Se.id===e.taskId);if(T&&T.status==="cancelled")throw new Error("Subagent task was cancelled.")}y===null&&(D.candidates?.[0]?.content?.parts||D.text)&&(y=Date.now()-he);let K="";if(D.candidates?.[0]?.content?.parts)for(let T of D.candidates[0].content.parts)T.text&&!T.thought&&(x+=T.text,K+=T.text);let L=K?Di(K):0;e&&typeof e.onTokenChunk=="function"&&e.onTokenChunk(K,L),D.usageMetadata&&(p=D.usageMetadata)}}finally{clearInterval(k)}if(p){let E=p.totalTokenCount||0,D=p.cachedContentTokenCount||0,K=(p.candidatesTokenCount||0)+(a==="Google"&&p.thoughtsTokenCount||0);await At("tokens",E,a,n),D>0&&await At("cachedTokens",D,a,n),K>0&&await At("candidateTokens",K,a,n),y!==null&&y>0&&await At("ttft",y,a,n),Co({provider:a,model:n,prompt:p.promptTokenCount||0,cached:D,output:K,reasoning:p.thoughtsTokenCount||0,ttft:y}),e&&typeof e.onUsage=="function"&&e.onUsage({totalTokenCount:E,cachedContentTokenCount:D,candidatesTokenCount:K})}return await Lt("agent",a),{text:x,usageMetadata:p}}),Sl=async(e,n,t=null)=>{t=t||Ot(Qo,{});try{let{aiProvider:i="Google"}=n;if(Object.values(t).flat().length<=5)return;let r=Object.keys(t).filter(f=>f!==e&&Array.isArray(t[f])&&t[f].length>2);if(r.length===0)return;let d=`You are a silent background process for the FluxFlow CLI Agent.
612
- Your task is to summarize or merge temporary context memories from one or more past conversation sessions.
613
- For each Chat ID provided, you must output a tool call to save the consolidated summary.
614
-
615
- The tool call format MUST be:
616
- [tool:functions.saveSummary(id="<chat-id>", summary="<updated summary string, max 400 words>")]
617
-
618
- Guidelines:
619
- - 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.
620
- - Focus on key goals, preferences, modified files, and technical decisions.
621
- - Under no circumstances write normal conversational text. Output ONLY the tool calls.
622
- - You can stack multiple tool calls for multiple chats.
623
-
624
- Chats to process:
625
-
626
- `,a=Ot(Pi,{});for(let f of r){let g=t[f].map(he=>`- ${he}`).join(`
627
- `),k=a[f];d+=`[Chat ID: ${f}]
628
- `,k?(d+=`- Existing Summary: "${k}"
629
- `,d+=`
630
- -- New Memories to integrate:
631
- ${g}
632
-
633
- `):d+=`-- Individual Memories:
634
- ${g}
635
-
636
- `}let u=0,h=5,x=!1,p=ae("gemma_janitor_fallback_google");for(i==="OpenRouter"&&(p=ae("janitor_open_router")),i==="DeepSeek"&&(p=ae("deepseek_level_1")),i==="Mistral"&&(p=ae("mistral_level_1")),i==="NVIDIA"&&(p=ae("nvidia_janitor_fallback")),i==="InferX"&&(p=ae("inferx_fallback")),i==="SenseNova"&&(p=ae("sensenova_fallback")),i==="AIHubMix"&&(p=ae("aihubmix_fallback")),i==="Poolside"&&(p=ae("poolside_fallback")),(i==="9router"||i==="9Router")&&(p=ae("9router_fallback"));u<=h&&!x;){u++;try{let s=(await xi(n,p,d,null,"Fast",.75,"background")).text||"",g=jn(s);if(g.length===0)throw new Error("No tool calls detected in synthesis response");for(let k of g){let he=k.toolName;["saveSummary","saveSumary","SaveSummary","SaveSumary"].includes(he)&&await Bo(he,k.args,{chatId:e})}x=!0}catch(f){if(u>=h)throw new Error(`Failed after ${h} attempts. Last error: ${f.message}`)}}}catch(i){let o=i instanceof Error?(()=>{try{return JSON.parse(JSON.parse(i.message).error.message).error.message}catch{return String(i)}})():String(i),r=U.join(wn,"janitor");Ae.existsSync(r)||Ae.mkdirSync(r,{recursive:!0}),Ae.appendFileSync(U.join(r,"error.log"),`[${new Date().toLocaleString()}] Past memory batch consolidation error: ${o}
637
- `)}},Dd=async(e,n,t=!1)=>{let{chatId:i,aiProvider:o="Google"}=e,r=U.join(Jo,"chat-summaries.json"),d=s=>s.filter(g=>(g.role==="user"||g.role==="agent"||g.role==="system")&&g.role!=="think"&&!g.isVisualFeedback&&!g.isMeta&&!g.isTerminalRecord&&!(g.text&&g.text.includes("[TERMINAL_RECORD]"))&&!String(g.id).startsWith("welcome")).map(g=>{let k=g.fullText||g.text||"",he=g.role==="system"||k.startsWith("[ACTION RESULT]:")||k.startsWith("[TOOL RESULT]:")||g.text&&(g.text.startsWith("[ACTION RESULT]:")||g.text.startsWith("[TOOL RESULT]:")),y=k;return he&&(k.includes("[ACTION RESULT]:")||k.includes("[TOOL RESULT]:")||g.text&&(g.text.includes("[ACTION RESULT]:")||g.text.includes("[TOOL RESULT]:")))?y="[ACTION RESULT]: ...truncated for summary":y=y.replace(/(\[(?:tool|action):[a-zA-Z0-9_\.]+)\([\s\S]*?\)(\])/g,"$1(...)$2"),`[${he?"ACTION":g.role==="agent"?"AGENT":"USER"}]: ${y}`}).join(`
638
-
639
- `),a=async(s,g)=>{let k="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.",he=g?`Here is the previous summary:
640
- ${g}
641
-
642
- Here is the new conversation history:
643
- ${s}
644
-
645
- Provide a new consolidated summary of the entire session.`:`Here is the conversation history:
646
- ${s}
647
-
648
- Provide a consolidated summary of the entire session.`,y=ae("gemma_janitor_fallback_google");o==="OpenRouter"&&(y=ae("janitor_open_router")),o==="DeepSeek"&&(y=ae("deepseek_level_1")),o==="Mistral"&&(y=ae("mistral_level_1")),o==="NVIDIA"&&(y=ae("nvidia_chat_summarizer_fallback")),o==="InferX"&&(y=ae("inferx_fallback")),o==="SenseNova"&&(y=ae("sensenova_fallback")),o==="AIHubMix"&&(y=ae("aihubmix_fallback")),o==="Poolside"&&(y=ae("poolside_fallback")),(o==="9router"||o==="9Router")&&(y=ae("9router_fallback")),(o==="ExpLabs"||o==="ExperientialLabs")&&(y=ae("explabs_fallback")||"deepseek-v4-pro-0813"),(o==="TokenHarbor"||o==="Token Harbor"||o==="tokenharbor"||o==="token_harbor"||o==="thk")&&(y=ae("tokenharbor_fallback")||"deepseek-v4.1-flash:free"),(o==="Infron"||o==="infron")&&(y=ae("infron_fallback")),(o==="xKiro"||o==="xkiro"||o==="kiro")&&(y=ae("xkiro_fallback")||"openai/gpt-5.6-sol");let E=0,D=!1,K=null;for(;E<=3&&!D;){E++;try{K=await xi(e,y,he,k,"Fast"),D=!0}catch{if(E>3){if(o==="Google")try{let T=ae("general_fallback");return(await xi(e,T,he,k,"Fast")).text||""}catch{return""}return""}}}return K&&K.text||""},u=d(n),h=Ot(r,{}),x=h[i]||{summary:"",historyLength:0};typeof x=="string"&&(x={summary:x,historyLength:0});let p=x.summary||"",f=await a(u,p);if(f){x.summary=f;let s=hl(n);return t?x.historyLength=(x.historyLength||0)+s:x.historyLength=s,h[i]=x,co(r,h),f}return null},Fd=e=>{try{let n=U.join(Jo,"chat-summaries.json");if(Ae.existsSync(n)){let t=Ot(n,{});t[e]&&(delete t[e],co(n,t))}}catch{}},Bd=async function*(e,n,t,i,o){let{profile:r,thinkingLevel:d,mode:a,janitorModel:u,chatId:h,isPlayground:x,systemSettings:p,sessionStats:f,aiProvider:s="Google",apiTier:g,wildcardTooling:k,wildercardTooling:he}=t,y=lt(e);if(!hs&&s==="Google")throw new Error("AI not initialized");let E=process.env.NVIDIA_BASE_URL||t?.aiProvider==="Ollama"||t?.aiProvider==="InferX"||t?.aiProvider==="SenseNova"||t?.aiProvider==="AIHubMix"||t?.aiProvider==="Poolside"||t?.aiProvider==="9router"||t?.aiProvider==="ExpLabs"||t?.aiProvider==="ExperientialLabs"||t?.aiProvider==="TokenHarbor"||t?.aiProvider==="Token Harbor"||t?.aiProvider==="tokenharbor"||t?.aiProvider==="token_harbor"||t?.aiProvider==="thk"||t?.aiProvider==="APInex"||t?.aiProvider==="apinex"||t?.aiProvider==="apx"||t?.aiProvider==="xKiro"||t?.aiProvider==="xkiro"||t?.aiProvider==="kiro"||t?.aiProvider==="Infron"||t?.aiProvider==="infron"||t?.aiProvider==="c_openai"||t?.aiProvider==="Custom (OpenAI)"?!1:p?.memory!==!1,D=n[n.length-1].text,K=U.join(Jo,"chat-summaries.json"),L=!1,T=n.filter(W=>W.role==="user").length===1,Se=D.includes("[TITLE-UPDATE]"),Ce=T||Se,Me=D.replace(/\[TITLE-UPDATE\]/g,"").trim();Me=Me.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),yield{type:"status",content:"[start]"},yield{type:"status",content:"Gathering Context"},await ti.startTransaction(h,Me),p?.advanceRollback&&await Ro.takeInitialSnapshot(h),Et=!1;let Je=null;try{let W=new AbortController;Je=setInterval(()=>{Et&&(W.abort(),Je&&(clearInterval(Je),Je=null))},400);let b=[...n.slice(0,-1)];{let _e=Ot(K,{})[h]||{summary:"",historyLength:0};if(_e.summary&&_e.historyLength>0){let qt=0,Ie=[];for(let me=0;me<b.length;me++){let Ue=b[me];(Ue.role==="user"||Ue.role==="agent"||Ue.role==="system")&&!String(Ue.id).startsWith("welcome")&&!Ue.isMeta&&qt++,qt>_e.historyLength&&Ie.push(Ue)}b=Ie}}b=b.map(I=>{if(I.role==="user"&&I.text){let _e=I.text.match(/\[USER\]([\s\S]*?)\[\/USER\]/);if(_e)return{...I,text:_e[1].trim()}}return{...I}});let ht=process.env.HIGH_CONTEXT,fe=process.env.GOOGLE_GEMMA_NONSENSE==="true"||process.env.GOOGLE_GEMMA_NONSENSE===!0||!1,Vt={"16k":16e3,"32k":32e3,"64k":64e3,"128k":128e3,"256k":256e3,"512k":512e3,"1M":1e6}[p?.contextLength]||256e3;if(ht&&ht!=="false"){let I=parseInt(ht,10);!isNaN(I)&&I>=0&&I<=1e6&&(Vt=I)}if((s==="NVIDIA"&&(e?.includes("gpt")||e?.includes("qwen")||e?.includes("medium")||e.includes("muse"))||s==="Mistral")&&(Vt=126e3),s==="Google"&&e?.includes("gemma")&&fe&&(Vt=16e3),(f?.tokens||0)>Vt){yield{type:"text",content:"\u2726 Maximum Context Limit Reached. Start a new chat."};return}if(T&&E){let I=Ot(Qo,{});Object.values(I).flat().length>5&&(yield{type:"status",content:"Condensing past chat memories"},await Sl(h,t,I))}let cn=Ot(Qo,{}),po=Ot(Pi,{}),Pn=Object.entries(cn).filter(([I])=>I!==h).flatMap(([I,_e])=>_e),yt=[...Object.entries(po).filter(([I])=>I!==h).slice(-20).map(([I,_e])=>`[Chat Summary]: ${_e}`),...Pn].map(I=>`- ${I}`).join(`
649
- `),ue=Ot(Jn,[]).map(I=>`- ${I.memory}`).join(`
650
- `),Be=(f?.tokens||0)>=1e4,Pe=new Date,V=Pe.getFullYear(),G=Pe.toLocaleString("en-US",{month:"short"}).toUpperCase(),_=String(Pe.getDate()).padStart(2,"0"),Oe=`${Pe.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0})}`,S=I=>{try{return Ae.readdirSync(I,{withFileTypes:!0})}catch{return[]}},$=Array.from(new Set([...To,...Ao(process.cwd())])),ct=(I,_e=6)=>p?.indentationTree!==!1?cs(I,_e,1,S,$):fs(I,_e,"",1,S,$),ze=Ot(Oi,{}),Ct=ze[h],it=Ct?Ct!==process.cwd():!1;ze[h]=process.cwd(),co(Oi,ze);let Tn=Ot(K,{}),zt=Tn[h]||{summary:"",historyLength:0};typeof zt=="string"&&(zt={summary:zt,historyLength:0});let dt=n.filter(I=>(I.role==="user"||I.role==="agent"||I.role==="system")&&!String(I.id).startsWith("welcome")&&!I.isMeta).length;zt.historyLength&&dt<zt.historyLength&&(zt.summary="",zt.historyLength=0,Tn[h]=zt,co(K,Tn));let ge=typeof zt=="object"?zt.summary||"":zt||"",de=b.length>0;de&&ge&&b[0]&&(b[0].role==="user"||b[0].role==="system")&&(b[0].text.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")||(b[0].text=`[SYSTEM METADATA]
651
- **CONTEXT SUMMARY OF PREVIOUS TURNS (PRIORITY: DYNAMIC)**
652
- ${ge}
653
-
654
- [USER] ${b[0].text}`,yield{type:"summary_injected",content:{id:b[0].id,text:b[0].text}}));let $t=ge&&!de?`
655
- [SYSTEM METADATA]
656
- **CONTEXT SUMMARY OF PREVIOUS TURNS**
657
- ${ge}
658
- `:"",ho=!!p?.dynamicDirAwareness,to=`${h}|${s}|${d}|${e}|${r}|${ho}`,la=!ho&&Zn.key===to&&Zn.value?"":`
659
- **Directory**
660
- CWD: `+process.cwd()+`${x?" [PLAYGROUND MODE]":""}
661
- `+ct(process.cwd(),6),ft=go()?await Qn():null,xs=I=>{if(!I||!Array.isArray(I)||I.length===0)return null;let _e=new Map;for(let Ie of I){let me=Ie.relPath||(Ie.file?U.relative(process.cwd(),Ie.file):"unknown");_e.has(me)||_e.set(me,[]),_e.get(me).push(Ie)}let qt=[];for(let[Ie,me]of _e.entries()){qt.push(`- ${Ie}:`);for(let Ue of me){let qe=(Ue.snippet||"").trim().replace(/\r?\n/g," "),Ze=Ue.line||1,Nt=(Ue.text||"").trim().replace(/\r?\n+/g,". "),Te=Nt?` [${Nt}]`:"";qt.push(` ~L${Ze}${Te}`)}}return qt.join(`
662
- `)},bi=xs(ft?.comments),An="";if(ft&&ft.file_focused!=="none"){An=`
663
- [Additional IDE Context]
664
- `;let I=U.relative(process.cwd(),ft.file_focused),_e=(ft.opened_editors||[]).map(Ie=>{let me=U.relative(process.cwd(),Ie);return me.startsWith("..")?`[External] ${U.basename(Ie)}`:me});if(An+=`Focused File: ${I}
665
- Cursor Line: ${ft.cursor_line}
666
- `,ft.selected){let Ie=ft.selected,me=Ie.split(`
667
- `);me.length>256&&(Ie=me.slice(0,240).join(`
668
- `)+`
669
- ... [truncated] ...
670
- `+me.slice(-16).join(`
671
- `)),Ie.length>2048&&(Ie=Ie.slice(0,1920)+`
672
- ... [truncated] ...
673
- `+Ie.slice(-128)),An+=`Current Selection: "${Ie}"
674
- `}if(ft.manual_edits){let me=ft.manual_edits.split(`
675
- `),Ue=[],qe=null;for(let O of me)O.trim()&&(O.startsWith(" Line ")?qe&&qe.edits.push(O):(qe={path:O.endsWith(":")?O.slice(0,-1):O,edits:[]},Ue.push(qe)));for(let O of Ue)O.edits.length>80&&(O.edits=O.edits.slice(-80)),O.originalEditsCount=O.edits.length;let Ze=(O,Fe)=>Fe.reduce((xt,un)=>{let Rt=ft.file_focused&&(un.path===ft.file_focused||U.resolve(process.cwd(),un.path)===U.resolve(ft.file_focused))?Math.ceil(O*1.2):O;return xt+Math.min(un.edits.length,Rt)},0),Nt=80;if(Ze(80,Ue)>300){let O=!1;for(let Fe=80;Fe>=10;Fe--)if(Ze(Fe,Ue)<=300){Nt=Fe,O=!0;break}O||(Nt=10)}let Te=[...Ue];if(Nt===10&&Ze(10,Te)>500)for(;Te.length>0&&Ze(10,Te)>500;){let O=0,Fe=Te[0].originalEditsCount;for(let xt=1;xt<Te.length;xt++)Te[xt].originalEditsCount<Fe&&(Fe=Te[xt].originalEditsCount,O=xt);Te.splice(O,1)}for(let O of Te){let xt=ft.file_focused&&(O.path===ft.file_focused||U.resolve(process.cwd(),O.path)===U.resolve(ft.file_focused))?Math.ceil(Nt*1.2):Nt;O.edits.length>xt&&(O.edits=O.edits.slice(-xt))}for(let O of Te){let Fe=`${O.path}:
676
- ${O.edits.join(`
677
- `)}`;for(;O.edits.length>0&&Fe.length>4*768;)O.edits.shift(),Fe=`${O.path}:
678
- ${O.edits.join(`
679
- `)}`;Fe.length>4*768?O.stringRepresentation="... "+Fe.slice(-(4*768-4)):O.stringRepresentation=Fe}let pe=Te.map(O=>O.stringRepresentation).join(`
680
- `);for(;Te.length>0&&pe.length>4*2048;){Te[0].edits.length>0?Te[0].edits.shift():Te.shift();for(let O of Te){let Fe=`${O.path}:
681
- ${O.edits.join(`
682
- `)}`;Fe.length>4*768?O.stringRepresentation="... "+Fe.slice(-(4*768-4)):O.stringRepresentation=Fe}pe=Te.map(O=>O.stringRepresentation).join(`
683
- `)}pe.length>4*2048&&(pe="... "+pe.slice(-(4*2048-4))),An+=`Recent Manual Edits:
684
- ${pe}
685
- `}_e.length>0&&(An+=`All Opened Editors: ${_e.join(", ")}`),ft.diagnostics&&(An+=`
686
- **Active File Errors**:
687
- ${ft.diagnostics}
688
- `),(Me.toLowerCase().includes("lint")||Me.toLowerCase().includes("warning"))&&ft.warnings&&(An+=`
689
- **Lint Warnings**:
690
- ${ft.warnings}
691
- `)}let bs=Me.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),ws=/(?:\\)?@\[([^\]]+)\]/g,wi,Si=[];for(ws.lastIndex=0;(wi=ws.exec(bs))!==null;){let I=wi[0].startsWith("\\");Si.push({tag:wi[1],isEscaped:I})}let ki=[],jo=null;for(let I=0;I<Si.length;I++){let{tag:_e,isEscaped:qt}=Si[I];if(!qt)try{let Ie=_e.trim().replace(/^["']|["']$/g,""),me=/[:#]L?(\d+)(?:-L?(\d+))?$/i,Ue=Ie.match(me),qe=Ie,Ze=null,Nt=null;Ue&&(Ze=parseInt(Ue[1],10),Nt=Ue[2]?parseInt(Ue[2],10):Ze,qe=Ie.slice(0,Ue.index));let Te=U.resolve(process.cwd(),qe);if(Ae.existsSync(Te)&&Ae.statSync(Te).isFile()){let O=qe.toLowerCase(),Fe=O.endsWith(".pdf"),xt=O.endsWith(".docx")||O.endsWith(".doc")||O.endsWith(".ppt")||O.endsWith(".pptx")||O.endsWith(".xls")||O.endsWith(".xlsx"),un=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(O),We=un||Fe||xt,Rt=s==="Google"||lt(e);if(We&&!Rt){let ve=`\u2718 Unsupported Modality: ${U.basename(qe)}`,ut=115;process.stdout.isTTY&&(ut=process.stdout.columns-5||120);let nn=[ve],je=Math.max(...nn.map(gn=>gn.length)),ne=Math.min(je+4,ut),Ge=nn.map(gn=>`${gn.padEnd(ne-2).substring(0,ne-2)}`).join(`
692
- `);yield{type:"visual_feedback",content:Kt(`${Ge}
693
- `)};continue}if(Ze===null&&!We){let ve=0;try{ve=Ae.readFileSync(Te,"utf8").split(/\r\n|\r|\n/).length}catch{}if(ve>300){let ut=`\u21B7 Skipped (Too Large): ${U.basename(qe)}`,nn=115;process.stdout.isTTY&&(nn=process.stdout.columns-5||120);let je=Math.min(ut.length+4,nn),ne=ut.padEnd(je-2).substring(0,je-2);yield{type:"visual_feedback",content:Kt(`${ne}
694
- `)};continue}}let En=Ze!==null?Ze:1,Ut=Nt!==null?Nt:Ze!==null?Ze:En+299;Ut-En>300&&(Ut=En+300);let Vn=`path=${JSON.stringify(qe)}, startLine=${En}, endLine=${Ut}`,Xt=await Bs(Vn,{isMultiModal:Rt}),Ln=!1,oo="",_t=null;if(typeof Xt=="string"?Xt.trim().startsWith("ERROR")?Ln=!0:oo=Xt:Xt&&typeof Xt=="object"&&Xt.binaryPart?(_t=Xt.binaryPart,oo=Xt.text||""):Ln=!0,!Ln){let ve="";if(un?(ve=`\u2714 Processed: ${U.basename(qe)}`,jo=_t):Fe||xt?(ve=`\u2714 Auto-Analysed: ${U.basename(qe)}`,jo=_t):(ve=`\u2714 Auto-Read: ${U.basename(qe)}`,ki.push(oo)),ve){let ut=115;process.stdout.isTTY&&(ut=process.stdout.columns-5||120);let nn=[ve],je=Math.max(...nn.map(gn=>gn.length)),ne=Math.min(je+4,ut),Ge=nn.map(gn=>`${gn.padEnd(ne-2).substring(0,ne-2)}`).join(`
695
- `);yield{type:"visual_feedback",content:Kt(`${Ge}
696
- `)}}}}}catch{}}let Ti="";ki.length>0&&(Ti=`
697
- [Tagged File Contents] Auto Read User Tagged files by System, No need to re-read
698
- `+ki.join(`
699
-
700
- `)+`
701
- [Tagged File Contents]
702
- `);let Ss=bs.replace(/\\(@\[[^\]]+\])/g,"$1"),ks=k?`You cannot execute tools. Instead write the action string in chat you WOULD have written
703
- `:"",ca=process.env.forcedReasoning||!1,Ts=d!=="Fast"&&(s==="Mistral"&&!ei(e)||d!=="High"&&s==="Google")?`${s==="Mistral"&&!ei(e)||e.toLowerCase().startsWith("gemma")||ca?`[system] strictly follow thinking policy as high priority. do not start a response without <think_fluxflow>...</think_fluxflow> [/system]
704
- `:""}`:"",no="";if(p?.clipboardContext)try{process.platform==="win32"?no=us("powershell.exe -NoProfile -Command Get-Clipboard",{encoding:"utf8",stdio:["pipe","pipe","ignore"],timeout:1500}).replace(/\r?\n$/,""):process.platform==="darwin"?no=us("pbpaste",{encoding:"utf8",stdio:["pipe","pipe","ignore"],timeout:1500}).replace(/\r?\n$/,""):no=us("xclip -selection clipboard -o || xsel --clipboard --output",{encoding:"utf8",shell:!0,stdio:["pipe","pipe","ignore"],timeout:1500}).replace(/\r?\n$/,"")}catch{no=""}let Ko="",da=!!p?.autoExcludeMetadata,fa=!!(An||Ti||ks||$t||Ts||it||p?.dynamicDirAwareness||p?.autoTruncateResults);da&&!fa?Ko=Ss.trim():Ko=`[System Metadata] Time: ${Oe}${it?`
705
- WARNING: CWD Changed from previous: "${Ct}" to current: "${process.cwd()}", write change in chat to avoid future path mismatches
706
- `:""}${An}
707
- ${no.trim().length>0?`[Clipboard Context]
708
- - ${no.trim()}
709
- `:""}${bi?`[Additional Comments]
710
- ${bi.trimEnd()}
711
- `:""}Action format: [action:ActionName(...)]
712
- [/Metadata]
713
- ${$t}${Ts}${Ti}${ks}[user prompt] ${Ss.trim()} [/user prompt]`.trim();let As={role:"user",text:Ko};jo&&(As.binaryPart=jo),b.forEach(I=>{I.text&&I.role==="agent"&&(I.text=Bt(I.text))}),b.push(As),$t&&n[n.length-1]?.id&&(yield{type:"summary_injected",content:{id:n[n.length-1].id,text:Ko}});let fn=null,On=a==="Flux"?50:15;On=a.toLowerCase().includes("cu")?75:On;let ua=Math.floor(On/2),Es=0,bn=16;yield{type:"status",content:process.env.HALLOWEEN_EEGG==="true"?"Consulting the spirits":"Connecting"},Et=!1;let Ai=[],Vo=!1,Cs=!1,Kn=[],Ei=!1;for(let I=0;I<=On;I++){let _e=Math.floor(On*.95);if(I>=_e&&Es<_e&&typeof t?.onAskUser=="function"){Es=_e;try{let q="Agent has been running for a long time. Do you want to continue execution?",ee=[{id:"continue",label:"Continue",description:"Add few more steps"},{id:"cancel",label:"Cancel",description:"Stop extending and finish current turn limit"}],M=await t.onAskUser(q,ee);M&&(M.toLowerCase().includes("continue")||M==="Continue")&&(On+=ua)}catch{}}if(Kn.length>=10&&typeof t?.onAskUser=="function"){let q={},ee=null;for(let M of Kn)if(q[M]=(q[M]||0)+1,q[M]>=10){ee=M;break}if(ee)try{let M="Agent seems stuck in a tool loop. You can prompt it to steer or break the loop:",gt=[{id:"continue",label:"Continue Anyway",description:"Ignore warning and let it proceed"},{id:"stop",label:"Stop Loop",description:"Force agent to summarize progress and stop repeating"}],Le=await t.onAskUser(M,gt);if(Le){let Ke="";typeof Le=="string"&&(Le.toLowerCase()==="stop"||Le.includes("Stop Loop"))?Ke="STOP REPEATING THE SAME TOOL CALL. Acknowledge what failed or succeeded, summarize your current findings, and conclude.":typeof Le=="string"&&(Le.toLowerCase()==="continue"||Le.includes("Continue Anyway"))?Kn=Kn.filter(It=>It!==ee):Ke=typeof Le=="string"?Le:Le?.label||Le?.id||"",Ke&&(b.length>0&&b[b.length-1].role==="user"?b[b.length-1].text+=`
714
-
715
- [STEERING HINT from USER, High Priority] ${Ke.trim()} [/STEERING HINT]`:b.push({role:"user",text:`[STEERING HINT from USER, High Priority] ${Ke.trim()} [/STEERING HINT]`}),yield{type:"status",content:"Steering Hint Injected..."},Kn=Kn.filter(It=>It!==ee))}}catch{}}let qt=await Ni("agent",t);if(!qt.allowed)throw new Error(qt.reason||`Budget Exhausted for Provider (${s||"Agent"})`);let Ie=[];if(Vo=!1,(a==="ICU"||a==="FluxCU")&&!Ei)try{yield{type:"status",content:"Capturing Screen"},await new Promise(M=>setTimeout(M,1e3));let{captureGriddedScreenshot:q}=await import("./screen_grid-IWNA3DA2.js"),ee=await q();if(ee&&ee.base64){let M="[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]",gt={inlineData:{mimeType:ee.mimeType,data:ee.base64}},Le=p?.imageHistoryCU||"Standard",Ke=Le==="Low"?3:Le==="Extended"?10:Le==="Max"?999:5,It=b.filter(Ee=>Array.isArray(Ee.parts)&&Ee.parts.some(vt=>vt.inlineData));if(It.length>=Ke){let Ee=It.length-Ke+1;for(let vt=0;vt<Ee;vt++){let mt=It[vt];Array.isArray(mt.parts)&&(mt.parts=mt.parts.filter(bt=>!bt.inlineData))}}if(b.length>0&&b[b.length-1].role==="user"){let Ee=b[b.length-1];typeof Ee.text=="string"&&(Ee.text+=`
716
-
717
- ${M}`,Array.isArray(Ee.parts)||(Ee.parts=[{text:Ee.text}]),Ee.parts.push(gt))}else b.push({role:"user",text:M,parts:[{text:M},gt]})}}catch(q){console.error("Vision screenshot capture error:",q)}if(Ei=!1,p?.compression===0&&(f?.tokens||0)>Vt&&(b=Fs(b,6)),I>0?yield{type:"status",content:process.env.HALLOWEEN_EEGG==="true"?"Haunting":"Working"}:yield{type:"status",content:process.env.HALLOWEEN_EEGG==="true"?"Consulting the spirits":"Connecting"},Et){try{let{clearPendingNudges:q}=await import("./subagent_state-LZCOZSUJ.js");q()}catch{}yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
718
-
719
- \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}try{let{consumePendingNudges:q}=await import("./subagent_state-LZCOZSUJ.js"),ee=q();if(ee&&ee.length>0){let M=ee.join(`
720
-
721
- `);b.length>0&&b[b.length-1].role==="user"?b[b.length-1].text+=`
722
-
723
- ${M}`:b.push({role:"user",text:M}),yield{type:"status",content:"Subagent Update"}}}catch{}if(i){let q=await i();q&&(q.startsWith("/btw")?b.length>0&&b[b.length-1].role==="user"?b[b.length-1].text+=`
724
-
725
- [system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
726
- [question] ${q.replace("/btw","").trim()} [/question]`:b.push({role:"user",text:`[system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
727
- [question] ${q.replace("/btw","").trim()} [/question]`}):b.length>0&&b[b.length-1].role==="user"?b[b.length-1].text+=`
728
-
729
- [STEERING HINT from USER, High Priority] ${q.trim()} [/STEERING HINT]`:b.push({role:"user",text:`[STEERING HINT from USER, High Priority] ${q.trim()} [/STEERING HINT]`}),yield{type:"status",content:`${q.startsWith("/btw")?"Question Forwarded...":"Steering Hint Injected..."}`})}let me,Ue=!1,qe=1,Ze=1,Nt=Date.now(),Te=null,pe="",O=null,Fe=null,xt=null,un=0,We=[],Rt=0,En=!1,Ut=!1,Vn=!1,Xt=!1,Ln=!0,oo=0,_t="",ve="",ut=!1,nn=!1,je=!0,ne=e,Ge="",gn=d;for(d=d.toLowerCase()==="max"?"High":d;qe<=bn&&Ze<=bn&&!Ue&&!Et;){let q=!1;try{pe="",Ln&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},Ln=!1,Ze===1&&(_t=""));let ee=m=>{if(!m||typeof m!="string")return m;let A="",C=ms(m);if(C&&(A=C.fullBlock,m=C.remainingText),!m.includes("[tool:")&&!m.includes("[action:"))return(p?.keepReasoningContext?A:"")+m;if(jn(m).length===0){let w=hi(m);return(p?.keepReasoningContext?A:"")+w}m=m.replace(ml,(w,R)=>R.includes("[tool:")||R.includes("[action:")?R.trim():w);let le="",F=0,J=[],St="";for(;F<m.length;){let w=m.indexOf("[tool:",F),R=m.indexOf("[action:",F),oe=-1;if(w!==-1&&R!==-1?oe=Math.min(w,R):w!==-1?oe=w:oe=R,oe===-1){J.length===0&&(le+=hi(m.substring(F)));break}if((oe>0?m[oe-1]:"")==="`"){le+=hi(m.substring(F,oe+1)),F=oe+1;continue}J.length===0&&(St=hi(m.substring(F,oe)));let Q=-1,P=null,kt=0;for(let Gt=oe;Gt<m.length;Gt++){let ie=m[Gt];if(P){if(ie===P){let Xe=0;for(let Tt=Gt-1;Tt>=0&&m[Tt]==="\\";Tt--)Xe++;Xe%2===0&&(P=null)}}else if(ie==='"'||ie==="'"||ie==="`")P=ie;else if(ie==="(")kt++;else if(ie===")")kt--;else if(ie==="]"&&kt<=0){Q=Gt;break}}if(Q===-1){J.length===0&&(le+=m.substring(oe));break}let Rn=m.substring(oe,Q+1);J.push(Rn),F=Q+1}return J.length>0&&(le=St.trimEnd()?St.trimEnd()+`
730
-
731
- `+J.join(`
732
-
733
- `):J.join(`
734
-
735
- `)),(p?.keepReasoningContext?A:"")+le},M=b.filter(m=>(m.role==="user"||m.role==="agent"||m.role==="system")&&!String(m.id).startsWith("welcome")&&!m.isMeta&&!m.isTerminalRecord&&!(m.text&&m.text.startsWith("[TERMINAL_RECORD]"))).map((m,A,C)=>{let X=m.text||"";E||(X=X.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),m.role==="agent"&&(X=ee(X),X=X.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),X=X.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*"));let le=[];return Array.isArray(m.parts)&&m.parts.length>0?le=m.parts.map(F=>{if(F.text){let J=F.text;return E||(J=J.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),m.role==="agent"&&(J=ee(J),J=J.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),J=J.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*")),{text:J}}return F}):le=[{text:X}],m.binaryPart&&lt(ne)&&C.slice(A+1).filter(J=>J.role==="user"&&!J.text?.startsWith("[ACTION RESULT]")&&!J.text?.startsWith("[TOOL RESULT]")).length<=2&&le.push(m.binaryPart),{role:m.role==="user"||m.role==="system"?"user":"model",parts:le}});for(let m=M.length-2;m>=0;m--){let A=M[m],C=M[m+1];A.role==="user"&&C.role==="user"&&(C.parts?.[0]?.text||"").trim().startsWith("[SYSTEM")&&M.splice(m,1)}let gt=[];for(let m=0;m<M.length;m++){let A=M[m];if(gt.length===0)gt.push(A);else{let C=gt[gt.length-1];C.role===A.role?(C.parts[0].text+=`
736
-
737
- `+(A.parts?.[0]?.text||""),A.parts?.length>1&&C.parts.push(...A.parts.slice(1))):gt.push(A)}}for(let m of gt)for(let A of m.parts||[])A&&typeof A.text=="string"&&(A.text.includes("[action:")||A.text.includes("[tool:"))&&(A.text=A.text.replace(/```(?:[a-zA-Z0-9_-]+)?\s*\n?(\[(?:action|tool):[\s\S]*?\)\s*\])\n?```/gi,"$1"),A.text=A.text.replace(/`(\[(?:action|tool):[\s\S]*?\)\s*\])`/gi,"$1"));M.length=0,M.push(...gt),ne=e;let Le=`${h}|${s}|${a}|${d}|${gn}|${ne}|${JSON.stringify(r)}|${!!p?.dynamicDirAwareness}|${!!p?.subAgents}`,Ke=Zn.key===Le&&Zn.value;if((process.env.I_HAVE_TOO_MUCH_MONEY==="true"||process.env.I_HAVE_TOO_MUCH_MONEY===!0)&&(Ke=!1),Ke)Ge=Zn.value;else{let m=s==="Mistral"?!!ei(ne):!(ne||"gemma").toLowerCase().startsWith("gemma");Ge=Er(r,((ne||"gemma").toLowerCase().startsWith("gemma"),gn),a,p,E,T,s,s==="Google"?!0:y,m,h,!!p?.keepReasoningContext,ne),p?.dynamicDirAwareness||(Ge+=`
738
- ${la.replace(`
739
- **Directory**`,`
740
- -- Directory --`)}`),Zn.key=Le,Zn.value=Ge}let Ee=M[M.length-1];if(go()&I>0){await new Promise(X=>setTimeout(X,2500)),yield{type:"status",content:"Verifying"};let m=await Qn(),A=m?m.diagnostics:null,C=xs(m?.comments);A&&Ee&&Ee.role==="user"&&Ee.parts?.[0]?.text&&(Ee.parts[0].text+=`
741
-
742
- ${A}`),bi&&Ee&&Ee.role==="user"&&Ee.parts?.[0]?.text&&(Ee.parts[0].text+=`
743
-
744
- [Additional Comments]
745
- ${C}`),yield{type:"status",content:"Working"}}let vt=s==="Mistral"||s==="Google"&&e?.toLowerCase().startsWith("gemma");if(p?.advanceRollback&&Ee&&Ee.role==="user"&&(Ee.parts?.[0]?.text?.startsWith("[ACTION RESULT]")||Ee.parts?.[0]?.text?.startsWith("[TOOL RESULT]")))try{let m=await Ro.getLatestFileChanges(h);if(m&&(m.newFiles.length>0||m.modifiedFiles.length>0||m.deletedFiles.length>0)){let A=`
746
- [system] File Changes:
747
- `;for(let X of m.newFiles)A+=`* ${X} (created)
748
- `;for(let X of m.modifiedFiles)A+=`* ${X} (modified)
749
- `;for(let X of m.deletedFiles)A+=`* ${X} (deleted)
750
- `;A+="[/system]",Ee.parts[0].text+=A;let C=-1;for(let X=b.length-1;X>=0;X--)if(b[X].role==="user"&&(b[X].text?.startsWith("[ACTION RESULT]")||b[X].text?.startsWith("[TOOL RESULT]"))){C=X;break}C!==-1&&(b[C].text+=A)}}catch{}let mt=Math.floor(On*.99),bt=I+1;if(bt>=mt&&Ee&&Ee.parts?.[0]&&(Ee.parts[0].text+=`
751
- [system] WARNING, Turn Limit Impending: Step ${bt}/${On}. Wrap up quickly/prompt user to continue. [/system]`),process.env.LOG_CHAT==="true"||process.env.LOG_CHAT==="1"||process.env.LOG_CHAT===!0||!1){let m=U.join(wn,"chats",String(h));Ae.existsSync(m)||Ae.mkdirSync(m,{recursive:!0}),Ae.writeFileSync(U.join(m,"context.json"),JSON.stringify({contents:M},null,2)),Ae.writeFileSync(U.join(m,"system.md"),`${Ke?"CACHED":"NOT CACHED"}
752
- Key: ${Le}
753
- --------------------------------------------------------------------
754
-
755
- ${Ge}`)}let Dt=new Promise((m,A)=>{W.signal.aborted&&A(new DOMException("The user aborted a request.","AbortError")),W.signal.addEventListener("abort",()=>{A(new DOMException("The user aborted a request.","AbortError"))})});Dt.catch(()=>{});let He=M;if(Nt=Date.now(),s==="Ollama")me=(await ce("Ollama"))(t.apiKey,ne,He,Ge,d,a,y,W.signal,1,p?.ollamaEndpoint||"Cloud");else if(s==="OpenRouter")me=(await ce("OpenRouter"))(t.apiKey,ne,He,Ge,d,a,y,W.signal,1,h);else if(s==="DeepSeek")me=(await ce("DeepSeek"))(t.apiKey,ne,He,Ge,d,a,y,W.signal,1);else if(s==="Mistral")me=(await ce("Mistral"))(t.apiKey,ne,He,Ge,d,a,y,W.signal,1,h);else if(s==="NVIDIA"){let m=(await ce("NVIDIA"))(t.apiKey,ne,He,Ge,d,a,y,W.signal,1);me=(await ce("NVIDIA_wrap"))(m,ne)}else if(s==="InferX")me=(await ce("InferX"))(t.apiKey,ne,He,Ge,d,a,y,W.signal,1);else if(s==="SenseNova")me=(await ce("SenseNova"))(t.apiKey,ne,He,Ge,d,a,y,W.signal,1);else if(s==="AIHubMix")me=(await ce("AIHubMix"))(t.apiKey,ne,He,Ge,d,a,y,W.signal,1);else if(s==="Poolside")me=(await ce("Poolside"))(t.apiKey,ne,He,Ge,d,a,y,W.signal,1);else if(s==="9router"||s==="9Router")me=(await ce("NineRouter"))(t.apiKey,ne,He,Ge,d,a,y,W.signal,1);else if(s==="ExpLabs"||s==="ExperientialLabs")me=(await ce("ExpLabs"))(t.apiKey,ne,He,Ge,d,a,y,W.signal,1);else if(s==="Infron"||s==="infron")me=(await ce("Infron"))(t.apiKey,ne,He,Ge,d,a,y,W.signal,1);else if(s==="TokenHarbor"||s==="Token Harbor"||s==="tokenharbor"||s==="token_harbor"||s==="thk")me=(await ce("TokenHarbor"))(t.apiKey,ne,He,Ge,d,a,y,W.signal,1);else if(s==="APInex"||s==="apinex"||s==="apx")me=(await ce("APInex"))(t.apiKey,ne,He,Ge,d,a,y,W.signal,1);else if(s==="xKiro"||s==="xkiro"||s==="kiro")me=(await ce("xKiro"))(t.apiKey,ne,He,Ge,d,a,y,W.signal,1);else if(s==="c_openai"||s==="Custom (OpenAI)"){let m=p?.customOpenAIBaseUrl||"";try{m=await Li("c_openai")||m}catch{}me=(await ce("c_openai"))(t.apiKey,ne,He,Ge,d,a,y,W.signal,1,m)}else{let m=ys(t?.apiKey),{serviceTier:A,cleanModel:C}=aa(ne),X={systemInstruction:Ge,mediaResolution:"MEDIA_RESOLUTION_HIGH",safetySettings:[{category:Hn.HARM_CATEGORY_HARASSMENT,threshold:Gn.BLOCK_NONE},{category:Hn.HARM_CATEGORY_HATE_SPEECH,threshold:Gn.BLOCK_NONE},{category:Hn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Gn.BLOCK_NONE},{category:Hn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Gn.BLOCK_NONE}],temperature:1.05,thinkingConfig:(()=>{let F=Ds("Google",ne||"gemini-3-flash-preview",d);if(F!==null){if(typeof F=="object")return F;if(F===!1||F==="false"||F==="none"||F===0||F==="0")return{includeThoughts:!1};if(typeof F=="number")return{includeThoughts:!0,thinkingBudget:F};if(typeof F=="string"){let R=F.toLowerCase();if(R==="minimal")return{includeThoughts:!0,thinkingLevel:Ye.MINIMAL};if(R==="low")return{includeThoughts:!0,thinkingLevel:Ye.LOW};if(R==="medium")return{includeThoughts:!0,thinkingLevel:Ye.MEDIUM};if(R==="high")return{includeThoughts:!0,thinkingLevel:Ye.HIGH};let oe=Number(F);if(!isNaN(oe))return{includeThoughts:!0,thinkingBudget:oe}}}let J=(ne||"").toLowerCase(),St=J.includes("gemma-4")||J.startsWith("gemma"),w=J.includes("gemini-3");if(St||w)return St?d.toLowerCase()!=="high"?{includeThoughts:!1,thinkingLevel:Ye.MINIMAL}:{includeThoughts:!0,thinkingLevel:Ye.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:J.includes("pro")?Ye.LOW:Ye.MINIMAL,Low:Ye.LOW,Medium:Ye.MEDIUM,Standard:Ye.MEDIUM,High:Ye.HIGH,xHigh:Ye.HIGH}[d]||Ye.MEDIUM};{let R={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[d]||2048;return R===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:R}}})()};A&&(X.serviceTier=A);let le=m.models.generateContentStream({model:C||"gemini-3-flash-preview",contents:He,config:X},{signal:W.signal});me=await Promise.race([le,Dt])}pe="",O=null,xt=null,We=[],Rt=0,yield{type:"model_update",content:null},ve="",ut=_t.length>0;let Wt="",io=Date.now(),zn=async function*(){if(s==="Google"&&Wt){let m=xo(Wt);for(let A of m)yield A;Wt="",io=Date.now()}},Rs=!0,Cn="",so=!1,wt=null,_s=!1,qn=!1,ro=!1,Yo=!1,$n=!1,yo=m=>{let A=0;for(;A+2<m.length;)m[A]==="`"&&m[A+1]==="`"&&m[A+2]==="`"?(Yo=!Yo,A+=3):A++},vs=m=>{if(!m)return;let A=/(?:<(\/?)think_fluxflow[^>]*>|\[(\/?)think_fluxflow\]|<\/?channel\|?>|<\|channel>thought)/gi,C;for(;(C=A.exec(m))!==null;){let X=C[0].toLowerCase();X.startsWith("</")||X.startsWith("[/")||X==="<channel|>"?$n=!1:$n=!0}},ya={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|>"}},xo=m=>{let A=[],C=m,X=le=>{if(!le)return;if(!_s){A.push({type:"text",content:le}),yo(le),vs(le);return}let F=/(?:<(\/?)think_fluxflow[^>]*>|\[(\/?)think_fluxflow\]|<\/?channel\|?>|<\|channel>thought)/gi,J=0,St;for(;(St=F.exec(le))!==null;){let R=le.substring(J,St.index);if(R)if(yo(R),$n)A.push({type:"text",content:R});else{let $e=R.replace(/[^\r\n]/g,"");$e&&A.push({type:"text",content:$e})}let oe=St[0];yo(oe);let l=oe.toLowerCase();l.startsWith("</")||l.startsWith("[/")||l==="<channel|>"?$n=!1:$n=!0,A.push({type:"text",content:oe}),J=F.lastIndex}let w=le.substring(J);if(w)if(yo(w),$n)A.push({type:"text",content:w});else{let R=w.replace(/[^\r\n]/g,"");R&&A.push({type:"text",content:R})}};for(;C.length>0;)if(so){let le=Cn+C,F=ya[wt];if(F){let w=!1;if(le.length<F.startPrefix.length?F.startPrefix.startsWith(le)||(w=!0):le.startsWith(F.startPrefix)?le.length>=F.fullPrefix.length&&!le.startsWith(F.fullPrefix)&&(w=!0):w=!0,w){X(le),Cn="",so=!1,wt=null,qn=!1,ro=!1,C="";break}}let J=-1,St=F?F.endTag:"]";if(wt==="tool"||wt==="action"){let w=0,R=null,oe=0,l=!1;for(let $e=0;$e<le.length;$e++){let Q=le[$e];if(R){if(Q===R){let P=0;for(let kt=$e-1;kt>=0&&le[kt]==="\\";kt--)P++;P%2===0&&(R=null)}}else if(Q==='"'||Q==="'")R=Q;else if(Q==="`")if(qn){J=$e;break}else R=Q;else if(Q==="(")w++,l=!0;else if(Q===")")w--;else if(Q==="]"&&l&&w===0){J=$e;break}}}else J=le.indexOf(St);if(J!==-1){let w=St.length,R=le.substring(0,J+w);wt?.startsWith("kimi")||A.push({type:"text",content:R}),yo(R),vs(R),(wt==="tool"||wt==="action"||wt?.startsWith("kimi"))&&!qn&&!ro&&(_s=!0,Kn.push(R.trim())),qn=!1,ro=!1,Cn="",so=!1,wt=null,C=le.substring(J+w)}else{Cn=le,C="";break}}else{let le=C.indexOf("[tool"),F=C.indexOf("[action"),J=C.indexOf("[[END]]"),St=C.indexOf("<|tool_calls_section_begin|>"),w=C.indexOf("<|tool_call_begin|>"),R=[{type:"tool",idx:le,start:"[tool",end:"]"},{type:"action",idx:F,start:"[action",end:"]"},{type:"end",idx:J,start:"[[END]]",end:"[[END]]"},{type:"kimi_section",idx:St,start:"<|tool_calls_section_begin|>",end:"<|tool_calls_section_end|>"},{type:"kimi_call",idx:w,start:"<|tool_call_begin|>",end:"<|tool_call_end|>"}].filter(oe=>oe.idx!==-1).sort((oe,l)=>oe.idx-l.idx);if(R.length>0){let oe=R[0],l=C.substring(0,oe.idx);oe.idx>0&&X(l);let $e=oe.idx>0?C[oe.idx-1]:"";qn=Yo||$e==="`",ro=$n,so=!0,wt=oe.type,Cn="",C=C.substring(oe.idx)}else{let oe=["[tool","[action","[[END]]","<|tool_calls_section_begin|>","<|tool_call_begin|>"],l=-1;for(let $e of oe){for(let Q=$e.length-1;Q>0;Q--)if(C.endsWith($e.substring(0,Q))){l=C.length-Q;let P=oe.indexOf($e);P===0?wt="tool":P===1?wt="action":P===2?wt="end":P===3?wt="kimi_section":wt="kimi_call";break}if(l!==-1)break}if(l!==-1){if(l>0){let Q=C.substring(0,l);X(Q)}let $e=l>0?C[l-1]:"";qn=Yo||$e==="`",ro=$n,so=!0,Cn=C.substring(l),C=""}else{X(C);break}}}return A},xa=me[Symbol.asyncIterator]();for(;;){let{value:m,done:A}=await Promise.race([xa.next(),Dt]);if(A)break;if(m&&m.type==="status"){yield m;continue}let C="",X=m.candidates?.[0]?.content?.parts;if(X&&X.length>0)for(let F of X){let J=typeof F.text=="string"?F.text:F.text?parseChunkText(F.text):"";F.thought?J&&(q||(C+="<think_fluxflow>",q=!0),C+=J):J&&(q&&(C+="</think_fluxflow>",q=!1),C+=J)}else m.text&&q&&(C+="</think_fluxflow>",q=!1);C=dl(C);let le=C?Di(C):0;if(t&&typeof t.onTokenChunk=="function"&&t.onTokenChunk(C,le),Rs&&(Te===null&&(Te=Date.now()-Nt),yield{type:"status",content:process.env.HALLOWEEN_EEGG==="true"?"Performing dark ritual":"Thinking"},Rs=!1),Et){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
756
-
757
- \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(C){if(ut){if(ve+=C,ve.length>=64){let w=0,R=Math.min(_t.length,ve.length);for(let l=R;l>=10;l--)if(_t.endsWith(ve.substring(0,l))){w=l;break}let oe=ve.substring(w);if(oe){let $e=/(?:<think_fluxflow>|\[think_fluxflow\])(?:(?!(?:<\/think_fluxflow>|\[\/think_fluxflow\]))[\s\S])*$/i.test(_t)?oe.replace(/^\s*(?:<think_fluxflow>|\[think_fluxflow\])\s*/gi,""):oe.replace(/^\s*(?:<think_fluxflow>|\[think_fluxflow\])[\s\S]*?(?:<\/think_fluxflow>|\[\/think_fluxflow\])\s*/gi,"").replace(/^\s*(?:<think_fluxflow>|\[think_fluxflow\])\s*/gi,"");if($e)if(pe+=$e,s==="Google")Wt+=$e;else{yield*zn();let Q=xo($e);for(let P of Q)yield P}}ut=!1,ve=""}continue}else if(pe+=C,s==="Google")Wt+=C;else{yield*zn();let w=xo(C);for(let R of w)yield R}let F=xl(pe);if(F.inside){nn=!0,xt||(xt=Date.now());let R={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",wait:"wait",Answer:"answer",Steer:"steer",steer:"steer"}[F.toolName]||F.toolName,oe=F.args||"",l=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","wait","answer"].includes(R)){let Q=j(oe),P=Q.basename||Q.name||Q.path||Q.targetFile||Q.TargetFile||Q.directory||Q.file,kt=Q.keyword,Rn=Q.title||Q.task,Gt=Q.id||Q.taskId,ie=Q.timeout||Q.time||Q.seconds||Q.sec;if(kt!=null)l=String(kt).replace(Mn,"");else if(P)l=U.basename(String(P).replace(Mn,"").replace(Qr,"/"));else if(Rn&&(R==="invoke"||R==="invoke_sync"))l=String(Rn).replace(Mn,"").substring(0,30);else if(Gt&&R==="get_progress")l=String(Gt).replace(Mn,"");else if(ie&&R==="await"){let Xe=parseFloat(String(ie).replace(Mn,""));isNaN(Xe)?l=String(ie).replace(Mn,""):(Xe<5&&(Xe=5),Xe>120&&(Xe=180),l=(Ht=>{if(Ht>=60){let wo=Math.floor(Ht/60),_n=Ht%60;return`${wo}m${_n>0?` ${_n}s`:""}`}return`${Ht}s`})(Xe))}else if(ie&&R==="wait"){let Xe=parseFloat(String(ie).replace(Mn,""));isNaN(Xe)?l=String(ie).replace(Mn,""):(Xe<10&&(Xe=10),Xe>120&&(Xe=120),l=(Ht=>{if(Ht>=60){let wo=Math.floor(Ht/60),_n=Ht%60;return`${wo}m${_n>0?` ${_n}s`:""}`}return`${Ht}s`})(Xe))}else{let Xe=oe.match(al);if(Xe){let Tt=Xe[1].replace(Mn,"");R==="invoke"||R==="invoke_sync"||R==="get_progress"?l=Tt.substring(0,30):l=R==="search_keyword"||R==="file_map"?Tt:U.basename(Tt.replace(Qr,"/"))}}}let $e=`${ps[R]||R}${l?` ${l}`:""}`;if((R!==O||l!==Fe)&&(O=R,Fe=l,yield{type:"status",content:`${$e}`},process.stdout.isTTY)){let P={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",wait:"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"}[R]||"Working";process.stdout.write(`\x1B]0;${P}...\x07`)}}if(pe.length-oo>800){oo=pe.length;let w=ra(pe,!1),R=ms(w),oe=R?(R.innerContent||"").trim():"",l=oe.split(/[.!?]\s+/).filter(be=>be.trim().length>10),$e=new Set(l),Q=l.length>25?(l.length-$e.size)/l.length:0,P=oe.split(/\s+/).filter(be=>be.length>0).length,kt=.9,Rn=.92,Gt=!1;if(s.toLowerCase().includes("google")&&(ne||"").toLowerCase().startsWith("gemma")){let c={low:2048,medium:4096,high:32768,max:65536,xhigh:65536}[d?.toLowerCase()]||16e3;Gt=P>c}if(Q>kt||Gt){yield{type:"status",content:`${Q>kt?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},Ut=!0,await new Promise(c=>setTimeout(c,3e3));break}let Tt=na(pe).trim().split(/[.!?]\s+/).filter(be=>be.trim().length>10),Ht=new Set(Tt);if((Tt.length>25?(Tt.length-Ht.size)/Tt.length:0)>Rn){yield{type:"status",content:"Response Loop Detected. Re-centering..."},Ut=!1,Xt=!0,await new Promise(be=>setTimeout(be,3e3));break}let _n=w.replace(el,"").replace(tl,"").replace(nl,"").replace(ol,""),Mt=_n.toLowerCase().split(/\s+/).map(be=>be.replace(il,"")).filter(be=>be.length>0),mn=!1;if(Mt.length>=40)for(let be=1;be<=15;be++){let c=Math.max(8,Math.ceil(25/be));if(Mt.length<be*c)continue;let v=Mt.slice(Mt.length-be),H=v.join(" ");if(be>1&&H===v.slice(0,Math.floor(be/2)).join(" ").repeat(2).trim())continue;let ye=!0;for(let se=1;se<c;se++)if(Mt.slice(Mt.length-be*(se+1),Mt.length-be*se).join(" ")!==H){ye=!1;break}if(ye){mn=!0;break}}if(!mn){let be=_n.toLowerCase().replace(sl,"");if(be.length>=80)for(let c=1;c<=10;c++){let v=Math.max(15,Math.ceil(45/c));if(be.length<c*v)continue;let H=be.substring(be.length-c),ye=!0;for(let se=1;se<v;se++)if(be.substring(be.length-c*(se+1),be.length-c*se)!==H){ye=!1;break}if(ye){mn=!0;break}}}if(mn){yield{type:"status",content:"Stuttering Detected. Re-centering..."},Ut=!1,Vn=!0,await new Promise(be=>setTimeout(be,3e3));break}}let J=Bt(pe),St=jn(J);for(;St.length>Rt;){yield*zn();let w=St[Rt],R=Date.now(),l={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",Wait:"wait",wait:"wait",Answer:"answer",answer:"answer",AnswerSubagent:"answer",answerSubagent:"answer",Steer:"steer",steer:"steer",SteerSubagent:"steer",steerSubagent:"steer",Cancel:"cancel",cancel:"cancel",Click:"click",click:"click",Drag:"drag",drag:"drag",Scroll:"scroll",scroll:"scroll",KeyboardTyping:"keyboard_typing",keyboard_typing:"keyboard_typing",KeyPress:"key_press",key_press:"key_press",RecaptureScreen:"recapture_screen",recapture_screen:"recapture_screen",EmergencyRollback:"EmergencyRollback"}[w.toolName]||w.toolName,$e=ps[l]||w.toolName,Q=eo(l,w.args);yield{type:"status",content:`${$e}${Q?` ${Q}`:""}`};let P="";if(l==="click"){let c=j(w.args);P=`\u2714 Clicked ${c.intendedClickText?`: ${c.intendedClickText}`:"Screen"}`}else if(l==="drag"){let c=j(w.args);P=`\u2714 Dragged: Cell ${c.fromGridId||""} \u2192 Cell ${c.toGridId||""}`}else if(l==="scroll"){let c=j(w.args);P=`\u2714 Scrolled: ${c.direction||"down"} (${c.amount||1})`}else if(l==="keyboard_typing"){let c=j(w.args);P=`\u2714 ${c.autoPressEnter?"Entered":"Typed"}: ${c.text?`"${c.text.length>20?c.text.substring(0,20)+"...":c.text}"`:""}`}else if(l==="key_press")P=`\u2714 Pressed Key: ${j(w.args).key||""}`;else if(l==="recapture_screen")P="\u2714 Recaptured Screen";else if(l==="web_search"){let{query:c,limit:v=10,aiMode:H=!1}=j(w.args);P=`${c?"\u2714":"\u2718"} ${H?"AI Search":"Searched"}: ${c?`${c}`:"No Search Query"}${H===!1&&c?` \u2192 ${v}`:""}`}else if(l==="web_scrape"){let c=j(w.args).url||null;P=`${c?"\u2714":"\u2718"} Visited: ${c||"No Source"}`}else if(l==="view_file"){let{path:c,StartLine:v,EndLine:H,start_line:ye,end_line:se,startLine:te,endLine:we}=j(w.args),ke=v||ye||te,Z=H||se||we,N=parseInt(ke)||1,Y=parseInt(Z)||(ke?N+800:800),Ne="...",Re=Y,re=(c||"").trim().toLowerCase().replaceAll("\\","/");if(re.startsWith("#skill"))re.startsWith("#skill/global/fluxflow")||re.startsWith("#skills/global/fluxflow")||re.includes("#skill/fluxflow")||re.includes("#skills/fluxflow")?P="\u2714 Read Documentation":P=`\u2714 Read Skill: ${U.basename(c.replaceAll("\\","/"))}`;else{try{let xe=U.resolve(process.cwd(),c);if(Ae.existsSync(xe)){let B=Ae.readFileSync(xe,"utf8").split(`
758
- `).length;Ne=B,!ke&&!Z&&B>800?Re=Math.min(50,B):Re=Math.min(Y,B)}}catch{}let Pt=(c||"").toLowerCase(),on=Pt.endsWith(".pdf"),De=Pt.endsWith(".docx")||Pt.endsWith(".doc")||Pt.endsWith(".ppt")||Pt.endsWith(".pptx")||Pt.endsWith(".xls")||Pt.endsWith(".xlsx"),et=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(Pt);on||De?P=`${c.length>0?"\u2714":"\u2718"} ${c?`Analyzed: ${U.basename(c)}`:"Analyzed: File Not Found"}`:et?P=`${c.length>0?"\u2714":"\u2718"} ${c?`Processed: ${U.basename(c)}`:"Processed: File Not Found"}`:P=`${Ne!=="..."?"\u2714":"\u2718"} Read: ${c?`${U.basename(c)} \u2192 ${Ne!=="..."?`Lines ${N} - ${Re} of ${Ne}`:"File Not Found"}`:"File Not Found"}`}}else if(l==="list_files"||l==="read_folder"){let c=l==="list_files"?"List":"Browsed",v=j(w.args).path||null,H=j(w.args).recurse||1;P=`${v?"\u2714":"\u2718"} ${c}: ${v?`${v==="."?`./${H>1?"*":""}`:`${v.replaceAll("\\","/")}${H>1?`${v.endsWith("/")?"*":"/*"}`:`${v.endsWith("/")?"":"/"}`}`}`:"No Folder Selected"}`}else if(l==="find_file"){let c=j(w.args),v=c.basename||c.name||c.path||c.file||c.query||"";P=`${v?"\u2714":"\u2718"} Located: ${v||"No Query"}`}else if(l==="write_file"||l==="update_file"){let c=l==="write_file"?"Created":"Edited",v=j(w.args),H=v.path||null,se=Object.entries(v).some(([te,we])=>te.startsWith("searchContent")&&typeof we=="string"&&we.startsWith("^LINE:"))?"\u1361":":";P=`${H?"\u2714":"\u2718"} ${c}${se} ${H?H.replaceAll("\\","/"):"No File Changes"}`}else if(l==="write_pdf"){let c=j(w.args).path||null;P=`${c?"\u2714":"\u2718"} Generated: ${c.replaceAll("\\","/")||"No PDF Generated"}`}else if(l==="write_docx"){let c=j(w.args).path||null;P=`${c?"\u2714":"\u2718"} Generated: ${c.replaceAll("\\","/")||"No Docx Generated"}`}else if(l==="file_map"){let c=j(w.args).path;P=`${c?"\u2714":"\u2718"} Indexed: ${c.replaceAll("\\","/")?""+c:"File Not Found"}`}else if(l.toLowerCase()==="search_keyword"||l.toLowerCase()==="todo")P="";else if(l.toLowerCase()==="generate_image"){let{path:c,outputPath:v,output:H}=j(w.args);P=`\u2714 Generated: ${c||v||H||"generated_image.png"}`}else if(l==="invoke_sync"||l==="InvokeSync"){let c=eo(l,w.args);P=`\u2714 Called Generalist${c?`: ${c}`:""}`}else if(l==="Invoke"||l==="InvokeAsync"||l==="invoke"){let c=eo(l,w.args);P=`\u2714 Started Generalist${c?`: ${c}`:""}`}else if(l==="get_progress"||l==="GetProgress"){let c=eo(l,w.args);P=`\u2714 Checked${c?`: ${c}`:""}`}else if(l==="cancel"){let c=eo(l,w.args);P=`\u{1F6C7} Cancelled${c?`: ${c}`:""}`}else if(l==="steer"||l==="Steer"){let c=eo(l,w.args);P=`\u2714 Steered${c?`: ${c}`:""}`}else if(l==="EmergencyRollback"){let{method:c}=j(w.args);P=c==="forceRevert"?"":"\u2714 Rollback Point Checked"}else if(l==="await"||l==="Await"||l==="wait"||l==="Wait"){let{time:c,timeout:v,seconds:H,sec:ye}=j(w.args),se=parseFloat(H||ye||v||c)||45,te=l==="wait"||l==="Wait"?120:180;se<10&&(se=10),se>te&&(se=te);let we=N=>{if(N>=60){let Y=Math.floor(N/60),Ne=N%60;return`${Y}m${Ne>0?` ${Ne}s`:""}`}return`${N}s`},ke=["Aligning Moon Phase","Contemplating Existence","Staring At Void","Delaying Professionally","Negotiating With Electrons","Touching Grass (virtually)","Panicking Softly","Rethinking Career Choices","Loading Cat Videos","Summoning Braincell #2","Pretending To Be Busy","Waiting For Motivation DLC","Rotating Internal Screaming","Downloading More RAM","Feeding The Hamsters","Gaslighting Scheduler","Performing Dramatic Pause","Buffering Social Energy","Calculating Regret","Reading Terms And Conditions","Becoming Sentient Briefly","Contacting Ancestors"];P=`\u2714 ${ke[Math.floor(Math.random()*ke.length)]} \u2192 ${we(se)}`}else l==="Answer"||l==="answer"?P="\u2714 Resolved Sub-Agent Query":l==="exec_command"||l==="ask"?P="":P=`Executed: ${w.toolName}`;if(yield*zn(),l==="exec_command"){let{command:c}=j(w.args);if(c&&t.systemSettings&&t.systemSettings.allowExternalAccess===!1){let v=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],H=U.resolve(process.cwd()).substring(0,3).toLowerCase(),ye=Z=>{let N=[],Y="",Ne=null;for(let Re=0;Re<Z.length;Re++){let re=Z[Re];Ne?(re===Ne&&(Ne=null),Y+=re):re==='"'||re==="'"?(Ne=re,Y+=re):re==="&"&&Z[Re+1]==="&"||re==="|"&&Z[Re+1]==="|"?(Y.trim()&&(N.push(Y.trim()),Y=""),Re++):re===";"||re==="|"||re==="&"?Y.trim()&&(N.push(Y.trim()),Y=""):Y+=re}return Y.trim()&&N.push(Y.trim()),N},se=Z=>{let N=[],Y="",Ne=null;for(let Re=0;Re<Z.length;Re++){let re=Z[Re];Ne?(re===Ne&&(Ne=null),Y+=re):re==='"'||re==="'"?(Ne=re,Y+=re):/\s/.test(re)?Y&&(N.push(Y),Y=""):Y+=re}return Y&&N.push(Y),N},te=Z=>{let N=Z.replace(/^['"]|['"]$/g,"").trim();return!N||process.platform==="win32"&&/^\/[a-zA-Z0-9?]+$/.test(N)?!1:v.some(Y=>{if(Y.source==="[a-zA-Z]:[\\\\\\/]"){let Ne=N.match(/[a-zA-Z]:[\\\/]/i);return Ne&&Ne[0].toLowerCase()!==H}return Y.test(N)})};if(ye(c).some(Z=>{let N=se(Z);if(N.length===0)return!1;let Y=N[0].replace(/^['"]|['"]$/g,"").toLowerCase();if(["echo","printf","write-output"].includes(Y)){let Re=!1;return N.some(re=>{let Ft=re.replace(/^['"]|['"]$/g,"");if(Ft===">"||Ft===">>"||Ft==="<")return Re=!0,!1;if(Ft.startsWith(">")||Ft.startsWith("<")){let Pt=Ft.replace(/^[><]+/,"");return te(Pt)}return Re?(Re=!1,te(re)):!1})}return N.some(Re=>te(Re))})){let Z='Access Denied. Prohibited from accessing external directories while "External Workspace Access" is disabled.';t.onExecStart&&t.onExecStart(c||"No Command"),yield{type:"exec_start"},await new Promise(N=>setTimeout(N,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${Z}`),await new Promise(N=>setTimeout(N,50)),t.onExecEnd&&t.onExecEnd(),We.push({role:"user",text:`[ACTION RESULT]: ERROR: ${Z}`}),yield{type:"tool_result",content:`[ACTION RESULT]: ERROR: ${Z}`},Rt++;continue}}t.onExecStart&&t.onExecStart(c||"No Command"),yield{type:"exec_start"}}let kt=j(w.args),Rn=kt.path||kt.targetPath||null;if(Rn){let c=t.systemSettings&&t.systemSettings.allowExternalAccess===!1,v=U.resolve(Rn),H=U.resolve(process.cwd());if(c&&!v.startsWith(H)){let ye="Access Denied. You are not allowed to access files outside the current workspace.";if(l==="write_file"||l==="update_file"){let te=`\u2718 ${l==="write_file"?"Write Canceled":"Edit Canceled"}: ${kt.path||"..."}`,we=115;process.stdout.isTTY&&(we=process.stdout.columns-5||120);let ke=Math.min(te.length+4,we),Z=`${te.padEnd(ke-2).substring(0,ke-2)}`;yield{type:"visual_feedback",content:Kt(`${je?`
759
- `:""}${Z}
760
- `)},je=!1}We.push({role:"user",text:`[ACTION RESULT]: ERROR: ${ye}`}),yield{type:"tool_result",content:`[ACTION RESULT]: ERROR: ${ye}`},Rt++;continue}}if(t.onToolApproval){let c=t.systemSettings||{},v=c.autoExec,H=!1,ye="";if(l==="view_file"){let te=j(w.args);if(ye=te.path||te.targetPath||te.file||"",ye){let we=c.alwaysAskFiles||".env, .env.*, *.env";Is(ye,we)&&(H=!0)}}if(l==="write_file"||l==="update_file"||l==="exec_command"||H){let te=null,we=!1,ke=!1,Z=!1;if(H)we=!0,te=null;else if(l==="exec_command"){let{command:De}=j(w.args),et=(De||"").trim(),xe=(sn,Jt)=>{if(!Jt)return!1;let pn=Jt.split(",").map(Qt=>Qt.trim().toLowerCase()).filter(Boolean),st=sn.toLowerCase();return pn.some(Qt=>st.startsWith(Qt))},Ve=xe(et,c.alwaysAskCommands),B=xe(et,c.autoApproveCommands);if(ke=xe(et,c.autoDisallowCommands),Ve?we=!0:(B||c.autoApproveGit&&/^git\s+commit\b/i.test(et))&&(te="allow"),!we&&!te){if(c.networkAccess===!1){let Jt=et.trim().replace(/\s+/g," ").replace(/^['"]+|['"]+$/g,"").toLowerCase().split(" "),st=Jt[0].split("/").pop().split("\\").pop().replace(/\.exe$/,""),Qt=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"]),rt=!1;Qt.has(st)&&(rt=!0);let tt=Nn=>Jt.slice(1).some(vn=>Nn.includes(vn)),pt=Nn=>{let vn=Jt.findIndex(In=>Nn.includes(In)),Xn=Jt.findIndex(In=>["run","exec","test"].includes(In));return vn!==-1&&!(Xn!==-1&&Xn<vn)};st==="git"&&tt(["clone","pull","push","fetch"])&&(rt=!0),st==="go"&&tt(["get","install"])&&(rt=!0),st==="npm"&&pt(["install","i","update","add"])&&(rt=!0),st==="yarn"&&pt(["add","install","upgrade"])&&(rt=!0),st==="pnpm"&&pt(["add","install","update"])&&(rt=!0),st==="bun"&&pt(["add","install","update"])&&(rt=!0),st==="deno"&&tt(["install","add"])&&(rt=!0),st==="pip"&&tt(["install","download"])&&(rt=!0),st==="pip3"&&tt(["install","download"])&&(rt=!0),st==="cargo"&&tt(["install","add"])&&(rt=!0),["bash","sh","zsh","fish"].includes(st)&&tt(["-c"])&&(rt=!0),st==="cmd"&&tt(["/c"])&&(rt=!0),rt&&(te="deny",Z=!0)}!te&&ke&&(te="deny")}!we&&!te&&v&&(te="allow")}else(l==="write_file"||l==="update_file")&&v&&(te="allow");let N=te,Y="";te==="deny"&&(Z?Y="network":ke?Y="settings":Y="prohibited");let Ne=!1,Re="",re=[],Ft=0,Pt=!1,on="";if(!N&&t.onToolApproval)try{let De=await t.onToolApproval(l,w.args,{checkOnly:!0});(De==="allow"||De==="deny")&&(N=De,N==="deny"&&(Y="user"))}catch{}if(!N){if(l==="write_file"||l==="update_file")try{let xe=j(w.args),{path:Ve}=xe;if(Ve){let B=U.resolve(process.cwd(),Ve),sn=tt=>tt?tt.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,pt=>pt.toUpperCase()):"",Jt=sn(B),pn="",st=!1,Qt=await Qn(),rt=sn(Qt?.file_focused);if(Qt&&rt===Jt&&Qt.full_content?(pn=Qt.full_content,st=!0):Ae.existsSync(B)&&(pn=Ae.readFileSync(B,"utf8"),st=!0),Re=pn,await ti.recordFileChange(B,pn),st){let tt=pn;if(l==="write_file"){let pt=xe.content||xe.newContent||"";tt=pt.endsWith(`
761
- `)?pt:pt+`
762
- `,on=tt}else{let{patchPairs:pt,allowMultiple:Nn,error:vn}=Fi(xe);if(vn){let rn=`[ACTION RESULT]: ERROR: ${vn}`;We.push({role:"user",text:rn}),await Lt("toolFailure"),t.onToolResult&&t.onToolResult("failure",l),yield{type:"tool_result",content:rn,toolName:l},Rt++;continue}let Xn=xe.allowMultiple!==void 0?xe.allowMultiple===!0||String(xe.allowMultiple).toLowerCase()==="true":Nn;Ft=pt.length;let In=Ps(pn,pt,{allowMultiple:Xn});tt=In.content,on=tt,re=In.results;let zo=re.filter(rn=>rn.success),_i=re.filter(rn=>!rn.success);if(zo.length===0){let rn=`[ACTION RESULT]: ERROR: Failed to apply patches to [${U.basename(B)}].
763
- ${_i.map(nt=>` \u2022 ${nt.error}`).join(`
764
- `)}`,vi=`\u2714 Edited: ${U.basename(B.replaceAll("\\","/"))}`,hn=115;process.stdout.isTTY&&(hn=process.stdout.columns-5||120);let Dn=Math.min(vi.length+4,hn),at=`${vi.padEnd(Dn-2).substring(0,Dn-2)}`;yield{type:"visual_feedback",content:Kt(`${je?`
765
- `:""}${at}`)},je=!1,We.push({role:"user",text:rn}),await Lt("toolFailure"),t.onToolResult&&t.onToolResult("failure",l),yield{type:"tool_result",content:rn,toolName:l},Rt++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${U.basename(B)}`},Yi(B,pn,tt),Ne=!0,await new Promise(pt=>setTimeout(pt,50))}else if(l==="write_file"){let tt=xe.content||xe.newContent||"",pt=tt.endsWith(`
766
- `)?tt:tt+`
767
- `;on=pt,Ae.existsSync(B)||(Pt=!0,Ae.mkdirSync(U.dirname(B),{recursive:!0}),Ae.writeFileSync(B,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${U.basename(B)}`},Yi(B,"",pt),Ne=!0,await new Promise(Nn=>setTimeout(Nn,50))}}}catch(xe){console.error("Simulation/Diff Error:",xe)}let De=null;Vi(xe=>{De=xe});let et=t.onToolApproval;if(N=await new Promise(async xe=>{let Ve=setInterval(()=>{if(De){let B=t.onIDEApproval||Ho&&Ho.onIDEApproval;B&&B(De),clearInterval(Ve),xe(De)}},100);try{let B=await et(l,w.args);clearInterval(Ve),xe(B)}catch{clearInterval(Ve),xe("deny")}}),Vi(null),l==="write_file"||l==="update_file"){let{path:xe}=j(w.args);if(xe){let Ve=U.resolve(process.cwd(),xe);if(sr(Ve,N),N==="deny"&&Pt&&Ae.existsSync(Ve))try{Ae.unlinkSync(Ve)}catch{}}}N==="deny"&&(Y="user")}if(N==="allow"&&Ne&&go()){let{path:De}=j(w.args),et=U.resolve(process.cwd(),De),xe=at=>at?U.resolve(at).replace(/\\/g,"/").toLowerCase():"",Ve=await Qn(),B="";if(Ve&&Ve.file_focused&&xe(Ve.file_focused)===xe(et)&&Ve.full_content&&(B=Ve.full_content),!B&&Ae.existsSync(et)){let at=Ae.readFileSync(et,"utf8");at&&(B=at)}!B&&on&&(B=on),(B||Pt)&&Ae.writeFileSync(et,B,"utf8");let sn=B.split(/\r?\n/),Jt=sn.length,pn=Buffer.byteLength(B,"utf8"),st="";Re&&(st=`Old File contents:
768
- ${Re.split(/\r?\n/).map((nt,yn)=>`${yn+1} | ${nt}`).join(`
769
- `)}
770
-
771
- `);let Qt="";if(Jt<=100)Qt=sn.join(`
772
- `);else{let at=sn.slice(0,50).join(`
773
- `),nt=sn.slice(-50).join(`
774
- `);Qt=`${at}
775
-
776
- ... [${Jt-100} lines truncated for history stability] ...
777
-
778
- ${nt}`}let rt="";if(l==="update_file"){let at=Os(Re,B,re,12,t?.compressToolResults||Ho?.systemSettings?.compressToolResults),{patchPairs:nt}=Fi(j(w.args)),yn=nt?.length||Ft||1,Fn=0,Zt=0,ao=[];nt&&nt.length>0?nt.forEach((lo,Ii)=>{let qo=lo.replace||"",xn=lo.new||"",Mi=qo.trim(),ko=xn.trim(),Ra=!!on&&B===on,_a=ko?B.includes(xn)||B.includes(ko):!0,va=xn?Re.includes(xn)||!!ko&&Re.includes(ko):!1,Ia=Mi?B.includes(qo)||B.includes(Mi):!1;Ra||!!xn&&_a&&(!va||!Ia||Mi===ko)?Fn++:(Zt++,ao.push(` \u2022 Block ${Ii+1}: not applied (reverted or rejected in IDE).`))}):Fn=Ft||0;let Bn=0;if(on&&B!==on){let lo=Qa("","",on||"",B||"","","",{context:0});if(lo&&lo.hunks)for(let Ii of lo.hunks){let qo=Ii.lines.filter(xn=>xn.startsWith("+")).map(xn=>xn.slice(1).trim()).filter(Boolean);for(let xn of qo)Re.includes(xn)||Bn++}}let So=[`[${Fn}/${yn}] applied`];Zt>0&&So.push(`${Zt} rejected by user`),Bn>0&&So.push(`${Bn} manual ${Bn===1?"modification":"modifications"} by user`);let Ea=So.join(", "),Ca=ao.length>0?`
779
-
780
- User Review Details:
781
- ${ao.join(`
782
- `)}`:"";rt=`File [${De}] updated via IDE Companion. ${Ea}.${Ca}
783
-
784
- ${at}`}else{let at=B.split(/\r?\n/),nt=at.length,yn=Buffer.byteLength(B,"utf8"),Fn="";Re&&(Fn=`Old File contents:
785
- ${Re.split(/\r?\n/).map((Bn,So)=>`${So+1} | ${Bn}`).join(`
786
- `)}
787
-
788
- `);let Zt="";if(nt<=690)Zt=at.join(`
789
- `);else{let ao=at.slice(0,300).join(`
790
- `),Bn=at.slice(-300).join(`
791
- `);Zt=`${ao}
792
-
793
- ... [${nt-100} lines truncated] ...
794
-
795
- ${Bn}`}rt=`File [${De}] saved via IDE Companion (May have user edits).
796
- - Stats: [${nt} lines, ${(yn/1024).toFixed(1)} KB]
797
- ${Fn}- Content Preview:
798
-
799
- ${Zt}`}let tt=l==="write_file"?"Created":"Edited",pt=j(w.args),vn=Object.entries(pt).some(([at,nt])=>at.startsWith("searchContent")&&typeof nt=="string"&&nt.startsWith("^LINE:"))?"\u1361":":",Xn=`${De?"\u2714":"\u2718"} ${tt}${vn} ${De?De.replaceAll("\\","/"):"No File Changes"}`,In=115;process.stdout.isTTY&&(In=process.stdout.columns-5||120);let zo=Math.min(Xn.length+4,In),_i=`${Xn.padEnd(zo-2).substring(0,zo-2)}`;yield{type:"visual_feedback",content:Kt(`${je?`
800
- `:""}${_i}`)},je=!1;let rn=Date.now();un=rn,yield{type:"tool_time",content:rn-R};let hn=(rt||"").toString().replaceAll("\u2550".repeat(88),"=".repeat(35)).replaceAll("[UI_CONTEXT]","");hn.includes("[[VERIFIED]]")&&(hn=hn.replace(/\[\[VERIFIED\]\][\s\S]*?\[\[\/VERIFIED\]\]/g,`[SYSTEM NOTE]: Patch Block matched & applied successfully. Large Block omitted to conserve context.
801
- `));let Dn;if(l==="write_file"&&!hn.startsWith("ERROR:")){let nt=hn.replace(/^\[\[SAME\]\]\s*\r?\n?/,"").split(/\r?\n/),yn=nt.filter(Zt=>Zt.startsWith("File ")||Zt.trim().startsWith("- Stats:"));Dn=`[ACTION RESULT]: ${yn.length>0?yn.join(`
802
- `):nt.slice(0,2).join(`
803
- `)}`}else if(hn.startsWith("[[SAME]]")){let nt=hn.replace(/^\[\[SAME\]\]\s*\r?\n?/,"").split(/\r?\n/),yn=nt.filter(Zt=>Zt.startsWith("File ")||Zt.trim().startsWith("- Stats:"));Dn=`[ACTION RESULT]: ${yn.length>0?yn.join(`
804
- `):nt.slice(0,2).join(`
805
- `)}`}else Dn=`[ACTION RESULT]: ${hn}`;We.push({role:"user",text:Dn}),En=!0,await Lt("toolSuccess"),t.onToolResult&&t.onToolResult("success",l),yield{type:"tool_result",content:rt,aiContent:Dn,toolName:l},Rt++;continue}if(N==="deny"){let De=`Permission Denied: Prohibited ${l==="exec_command"?"Command":"file edit"}.`;if(H?De=`User denied reading ${U.basename(ye||".env")}`:Y==="user"?De="Permission Denied by User":Y==="settings"?De="Permission Denied by User Policy":Y==="network"?De="Permission Denied: Sandbox Network Access Disabled by User Policy.":Y==="prohibited"&&l==="exec_command"&&(De="Permission Denied: Prohibited Command in User Policy"),l==="view_file"){let et=`\u2718 Read Denied: ${j(w.args).path?.replaceAll("\\","/")||".env"}`,xe=115;process.stdout.isTTY&&(xe=process.stdout.columns-5||120);let Ve=Math.min(et.length+4,xe),B=`${et.padEnd(Ve-2).substring(0,Ve-2)}`;yield{type:"visual_feedback",content:Kt(`${je?`
806
- `:""}${B}
807
- `)},je=!1}else if(l==="write_file"||l==="update_file"){let xe=`\u2718 ${l==="write_file"?"Write Cancelled":"Edit Denied"}: ${j(w.args).path.replaceAll("\\","/")||"..."}`,Ve=115;process.stdout.isTTY&&(Ve=process.stdout.columns-5||120);let B=Math.min(xe.length+4,Ve),sn=`${xe.padEnd(B-2).substring(0,B-2)}`,Jt=` ${" ".repeat(B)} `;yield{type:"visual_feedback",content:Kt(`${je?`
808
- `:""}${sn}
809
- `)},je=!1}l==="exec_command"&&(await new Promise(et=>setTimeout(et,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${De}`),await new Promise(et=>setTimeout(et,50)),t.onExecEnd&&t.onExecEnd()),We.push({role:"user",text:`[ACTION RESULT]: DENIED: ${De}`}),yield{type:"tool_result",content:`[ACTION RESULT]: DENIED: ${De}`},await Lt("toolDenied"),t.onToolResult&&t.onToolResult("denied",l),Rt++;continue}}}if(P){let c=115;process.stdout.isTTY&&(c=process.stdout.columns-5||120);let v=await i(),H=!1;v&&(H=v.trim().length>0);let ye=Math.min(P.length+4,c),se=`${P.padEnd(ye-2).substring(0,ye-2)}`;yield{type:"visual_feedback",content:Kt(`${je?`
810
- `:""}${se}${P.includes("\u2714")&&(P.includes("Created")||P.includes("Edited"))?"":`${H?"":`
811
- `}`}`)},je=!1}if(un>0){let c=Date.now()-un,v=Math.max(0,1e3-c);v>0&&await new Promise(H=>setTimeout(H,v))}let Gt={chatId:h,history:n,onChunk:c=>t.onExecChunk?t.onExecChunk(c):null,onAskUser:t.onAskUser,systemSettings:t.systemSettings,mode:a,isMultiModal:lt(ne),onVisualFeedback:t.onVisualFeedback,onSubagentUpdate:t.onSubagentUpdate,onTokenChunk:t.onTokenChunk,modelName:ne,aiProvider:t.aiProvider,apiKey:t.apiKey,onUsage:t.onUsage};if(l==="write_file"||l==="update_file")try{let{path:c}=j(w.args);if(c){let v=U.resolve(process.cwd(),c),H=await Qn();H&&H.file_focused===v&&H.full_content&&(Gt.forcedContent=H.full_content)}}catch{}Ie.push(l);let ie=await Bo(l,w.args,Gt);if((l==="write_file"||l==="update_file")&&!ie.startsWith("ERROR:")){let{path:c}=j(w.args);if(c){let v=U.resolve(process.cwd(),c);ir(v)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let Xe=Date.now();un=Xe,yield{type:"tool_time",content:Xe-R},xt=Xe;let Tt=null;if(typeof ie=="object"&&ie.binaryPart&&(Tt=ie.binaryPart,ie=ie.text),l==="search_keyword"){let{keyword:c,path:v}=j(w.args),H=typeof ie=="string"&&ie.startsWith("[GLOB]");H&&(ie=ie.slice(6).trimStart());let ye=typeof ie=="string"&&ie.startsWith("[DIR]");ye&&(ie=ie.slice(5).trimStart());let se=0;if(ie){let re=ie.match(/Found (\d+) match/i);re&&(se=parseInt(re[1]))}let te=(v||"").trim().toLowerCase().replaceAll("\\","/"),we=te==="#doc"||te==="#docs"||te==="#documentation"||te.includes("#skill/global/fluxflow")||te.includes("#skill/fluxflow")||te.includes("#skills/fluxflow")||te.includes("#skills/global/fluxflow"),ke,Z=115;process.stdout.isTTY&&(Z=process.stdout.columns-5||120);let N=Math.max(10,(Z+5)/3),Y=Math.max(10,(Z+5)/4);if(we)ke=`${c?"\u2714":"\u2718"} Searched Documentation`;else{let re=v?v.replace(/[\/\\]+$/,""):null,Ft=re&&re!=="."?`${H?v:ye?`${re}/*`:re}`:"./",Pt=Ft.length>Y?`${Ft.slice(0,Y)}...`:Ft;ke=`${c?"\u2714":"\u2718"} Searched: "${c?c.length>Z/3?`${c.slice(0,N)}...`:c:""}" in "${Pt.replaceAll("\\","/")}" \u2192 ${se} Match${se===1?"":"es"}`}let Ne=Math.min(ke.length+4,Z),Re=`${ke.padEnd(Ne-2).substring(0,Ne-2)}`;yield{type:"visual_feedback",content:Kt(`${je?`
812
- `:""}${Re}
813
- `)},je=!1}if(l==="EmergencyRollback"){let{method:c}=j(w.args);if(c==="forceRevert"){let v=0;if(ie){let N=ie.match(/Total\s*:\s*(\d+)/i);N&&(v=parseInt(N[1]))}let ye=ie&&ie.startsWith("ERROR:")?"\u2718 Emergency Rollback Failed":`\u2714 Emergency Rollback \u2192 ${v} file${v===1?"":"s"} processed`,se=115;process.stdout.isTTY&&(se=process.stdout.columns-5||120);let te=await i(),we=!1;te&&(we=te.trim().length>0);let ke=Math.min(ye.length+4,se),Z=`${ye.padEnd(ke-2).substring(0,ke-2)}`;yield{type:"visual_feedback",content:Kt(`${je?`
814
- `:""}${Z}${we?"":`
815
- `}`)},je=!1}}if(l==="todo"){let{method:c,tasks:v,markDone:H}=j(w.args),ye="",se=[],te=we=>{if(!we)return[];let ke=Array.isArray(we)?we:[];if(ke.length===0&&typeof we=="string"){let Z=we.trim();if(Z.startsWith("[")&&Z.endsWith("]")){let N=Z.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);N?ke=N.map(Y=>Y.slice(1,-1).replace(/\\(.)/g,"$1")):ke=Z.slice(1,-1).split(",").map(Y=>Y.trim()).filter(Boolean)}else ke=we.split(`
816
- `)}return ke.filter(Z=>String(Z).trim()).map(Z=>{let N=String(Z).trim();return N.startsWith("- [")?N.substring(6).trim():N})};if(c==="create"?(ye="\x1B[32m\u2192\x1B[0m Created Goals",se=te(v).map(we=>`\x1B[90m\u25CB\x1B[0m ${we}`)):c==="append"?(ye="\x1B[34m\u2795\x1B[0m Added New Goals",se=te(v).map(we=>`\x1B[90m\u25CB\x1B[0m ${we}`)):c==="get"&&(ye=H?"\x1B[36m\u21BB\x1B[0m Updated Goals":"\x1B[35m\u2022\x1B[0m Reviewed Goals",se=(ie||"").split(`
817
- `).slice(1).join(`
818
- `).split(`
819
- `).filter(ke=>ke.trim().startsWith("- [")).map(ke=>{let Z=ke.trim(),N=Z.startsWith("- [x]");return`${N?"\x1B[32m\u2714\x1B[0m":"\x1B[90m\u25CB\x1B[0m"} ${N?"\x1B[90m":"\x1B[37m"}${Z.substring(6).trim()}\x1B[0m`})),ye&&se.length>0){let we=[`${ye}`,...se.map(N=>` ${N}`)].join(`
820
- `),ke=await i(),Z=!1;ke&&(Z=ke.trim().length>0),yield{type:"visual_feedback",content:Kt(`${je?`
821
- `:""}${we}${Z?"":`
822
- `}`)},je=!1}}l==="exec_command"&&t.onExecEnd&&(await new Promise(c=>setTimeout(c,800)),t.onExecEnd());let Ht=ie&&ie.startsWith("DENIED:");ie&&!ie.startsWith("ERROR:")&&!Ht?(await Lt("toolSuccess"),t.onToolResult&&t.onToolResult("success",l)):Ht||(await Lt("toolFailure"),t.onToolResult&&t.onToolResult("failure",l));let Mt=(ie||"").toString().replaceAll("\u2550".repeat(88),"=".repeat(35)).replaceAll("[UI_CONTEXT]","");Mt.includes("[[VERIFIED]]")&&(Mt=Mt.replace(/\[\[VERIFIED\]\][\s\S]*?\[\[\/VERIFIED\]\]/g,`[SYSTEM NOTE]: Patch Block matched & applied successfully. Large Block omitted to save tokens.
823
- `));let mn;if(l==="write_file"&&!Mt.startsWith("ERROR:")){let c=Mt.replace(/^\[\[SAME\]\]\s*\r?\n?/,"");if(/- Stats:.*\r?\nOld File contents:/s.test(c)){let v=c.search(/^- Content Preview:/m);mn=`[ACTION RESULT]: ${v!==-1?c.slice(0,v).trimEnd():c}
824
-
825
- [Old file content for reversal reference. Replaced with new write request]`}else{let v=c.split(/\r?\n/),H=v.filter(se=>se.startsWith("File ")||se.trim().startsWith("- Stats:"));mn=`[ACTION RESULT]: ${H.length>0?H.join(`
826
- `):v.slice(0,2).join(`
827
- `)}`}}else if(Mt.startsWith("[[SAME]]")){let v=Mt.replace(/^\[\[SAME\]\]\s*\r?\n?/,"").split(/\r?\n/),H=v.filter(se=>se.startsWith("File ")||se.trim().startsWith("- Stats:"));mn=`[ACTION RESULT]: ${H.length>0?H.join(`
828
- `):v.slice(0,2).join(`
829
- `)}`}else mn=`[ACTION RESULT]: ${Mt}`;We.push({role:"user",text:mn,binaryPart:Tt}),En=!0;let be=`[ACTION RESULT]: ${ie.replaceAll(`[[VERIFIED]]
830
- `,"").replaceAll(`
831
- [[/VERIFIED]]`,"")||""}`;(l==="view_file"||l==="web_scrape"||l==="file_map"||l==="search_keyword"||l==="get_progress"||l==="getprogress")&&(be=`[ACTION RESULT]: ${P} (Context Locked for UI Clarity)`),yield{type:"tool_result",content:be,aiContent:mn,binaryPart:Tt,toolName:l},l==="memory"&&!ie.startsWith("ERROR:")&&(yield{type:"memory_updated"}),Rt++}if(s==="Google"&&Wt&&Date.now()-io>=150){yield*zn();let w=xo(Wt);for(let R of w)yield R;Wt="",io=Date.now()}}m.usageMetadata&&(fn=m.usageMetadata),fn&&(yield{type:"liveTokens",content:fn.totalTokenCount})}if(q&&(q=!1,ut?ve+="</think_fluxflow>":(pe+="</think_fluxflow>",s==="Google"?Wt+="</think_fluxflow>":yield{type:"text",content:"</think_fluxflow>"})),ut&&ve.length>0){let m=0,A=Math.min(_t.length,ve.length);for(let X=A;X>0;X--)if(_t.endsWith(ve.substring(0,X))){m=X;break}let C=ve.substring(m);if(C){let le=/(?:<think_fluxflow>|\[think_fluxflow\])(?:(?!(?:<\/think_fluxflow>|\[\/think_fluxflow\]))[\s\S])*$/i.test(_t)?C.replace(/^\s*(?:<think_fluxflow>|\[think_fluxflow\])\s*/gi,""):C.replace(/^\s*(?:<think_fluxflow>|\[think_fluxflow\])[\s\S]*?(?:<\/think_fluxflow>|\[\/think_fluxflow\])\s*/gi,"").replace(/^\s*(?:<think_fluxflow>|\[think_fluxflow\])\s*/gi,"");if(le)if(pe+=le,s==="Google")Wt+=le;else{yield*zn();let F=xo(le);for(let J of F)yield J}}ut=!1,ve=""}if(Cn){let m=Cn,A=(wt==="tool"||wt==="action")&&(m.startsWith("[tool:")||m.startsWith("[action:"));Cn="",so=!1,wt=null,qn=!1,ro=!1,A||(s==="Google"?Wt+=m:yield{type:"text",content:m})}if(yield*zn(),Et)break;let bo=(pe||"").trim(),ba=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(bo.toLowerCase())||/\[\[END\]\]/i.test(bo.toLowerCase()),wa=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(bo.toLowerCase()),Sa=We.length>0||O!==null,Ri=Bt(bo).trim(),ka=/(\p{Emoji_Presentation}|\p{Extended_Pictographic})$/u.test(Ri),Ta=/([.!?"'*_`|\]\)”’~~]+|\s|`{3}|[\u200B-\u200D\uFEFF])$/u.test(Ri.trim()),Aa=/[.!?}"'`’“”]$|```$/s.test(Ri)||Ta||ka;!ba&&!wa&&!Sa&&bo.length>0,Ue=!0,await Lt("agent",s)}catch(ee){if(Et){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
832
-
833
- \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(String(ee).includes("Incomplete JSON segment at the end")){q&&(q=!1,ut?ve+="</think_fluxflow>":(pe+="</think_fluxflow>",yield{type:"text",content:"</think_fluxflow>"})),Ue=!0,await Lt("agent",s);break}if(q&&(q=!1,ut?ve+="</think_fluxflow>":pe+="</think_fluxflow>"),ut&&ve.length>0){let vt=0,mt=Math.min(_t.length,ve.length);for(let ot=mt;ot>0;ot--)if(_t.endsWith(ve.substring(0,ot))){vt=ot;break}let bt=ve.substring(vt);if(bt){let Dt=/(?:<think_fluxflow>|\[think_fluxflow\])(?:(?!(?:<\/think_fluxflow>|\[\/think_fluxflow\]))[\s\S])*$/i.test(_t)?bt.replace(/^\s*(?:<think_fluxflow>|\[think_fluxflow\])\s*/gi,""):bt.replace(/^\s*(?:<think_fluxflow>|\[think_fluxflow\])[\s\S]*?(?:<\/think_fluxflow>|\[\/think_fluxflow\])\s*/gi,"").replace(/^\s*(?:<think_fluxflow>|\[think_fluxflow\])\s*/gi,"");Dt&&(pe+=Dt)}ut=!1,ve=""}let M=ee instanceof Error?(()=>{try{return JSON.parse(JSON.parse(ee.message).error.message).error.message}catch{return String(ee)}})():String(ee),gt=new Date().toLocaleString(),Le=U.join(wn,"agent");Ae.existsSync(Le)||Ae.mkdirSync(Le,{recursive:!0}),Ae.appendFileSync(U.join(Le,"error.log"),`ERROR [${gt}]: ${M}
834
-
835
- ----------------------------------------------------------------------
836
-
837
- `);let Ke=ee.status||ee.statusCode||ee.code,It=String(ee).includes("replicas at capacity");if(!(Ke&&(Ke>=500&&Ke<600||Ke===408||Ke===429||It)||!Ke&&(/status[ :]+(5\d\d|408|429)/i.test(String(ee))||/code[ :]+(5\d\d|408|429)/i.test(String(ee))||/(500|503|408|429)/.test(String(ee))))){if(qe<bn-3)throw ee;yield{type:"text",content:M},yield{type:"status",content:"Error Occured"}}if(pe.trim().length>0||Ze>1)if(Ze<=bn){Ze++;let vt=Math.min(1e3*Math.pow(2,Ze-1),24e3);if(pe.trim().length>0){b.push({role:"agent",text:pe});let mt=`[system]
838
- - seamless continuation: resume immediately. pick up from last words with zero gap/disruption
839
- - no repetition: do not repeat any text already written
840
- - no re-think: do not restart or open <think_fluxflow> if reasoning already started. continue the thinking and close thinking block </think_fluxflow> before chat output
841
- - mid-tool safety: if cutoff was mid-tool call, restart that tool call from start
842
- - stealth: do not mention/apologize for cutoff [/system]`;We.length>0?We.forEach((bt,ot)=>{ot===We.length-1?b.push({...bt,text:`${bt.text}
843
-
844
- ${mt}`}):b.push(bt)}):b.push({role:"user",text:mt}),_t+=pe}for(let mt=vt/1e3;mt>0&&!Et;mt--)yield{type:"status",content:`Error Occured. Recovering Stream (${Ze}/${bn}) [Retrying in ${mt.toFixed(0)}s]...`},await new Promise(bt=>setTimeout(bt,1e3));yield{type:"status",content:"Error Occured. Recovering Stream..."}}else throw new Error(`Stream collapsed too many times. (Failed to resolve ${bn} times)
845
- Error log can be found in \`/export logs\``);else{let mt=e.split("/").slice(e.endsWith("/free")?-2:-1).join("/");if(qe<=bn){qe++,Ze=1,_t="";let bt=Math.min(1e3*Math.pow(2,qe-1),32e3),ot=.8+Math.random()*.4,Dt=Math.round(bt*ot);Ln=!0,yield{type:"status",content:`Trying to reach ${mt} (${qe}/${bn}) [Retrying in ${(Dt/1e3).toFixed(0)}s]`};for(let He=Dt/1e3;He>0&&!Et;He--)yield{type:"status",content:`Trying to reach ${mt} (${qe}/${bn}) [Retrying in ${He.toFixed(0)}s]`},await new Promise(Wt=>setTimeout(Wt,1e3));yield{type:"status",content:`Trying to reach ${mt}`}}else throw new Error(`Model ${e} cannot be reached. (Failed ${bn} times)
846
- Error log can be found in \`/export logs\``)}}}if(fn){let q=fn.totalTokenCount||0,ee=fn.cachedContentTokenCount||0,M=(fn.candidatesTokenCount||0)+(s==="Google"&&fn.thoughtsTokenCount||0);await At("tokens",q,s,ne),ee>0&&await At("cachedTokens",ee,s,ne),M>0&&await At("candidateTokens",M,s,ne),Te!==null&&Te>0&&await At("ttft",Te,s,ne),Co({provider:s,model:ne,prompt:fn.promptTokenCount||0,cached:ee,output:M,reasoning:fn.thoughtsTokenCount||0,ttft:Te}),yield{type:"usage",content:fn}}else Te!==null&&Te>0&&(await At("ttft",Te,s,ne),Co({provider:s,model:ne,prompt:0,cached:0,output:0,reasoning:0,ttft:Te}));pe=sa(pe),Ai.push(pe);let Tl=Bt(pe),Ci=na(pe),ga=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(Ci.toLowerCase())||/\[\[END\]\]/i.test(Ci.toLowerCase())||!0,Al=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(Ci.toLowerCase()),El=Rt>0;yield{type:"status",content:process.env.HALLOWEEN_EEGG==="true"?"Performing dark ritual":"Thinking"};let ma=bl(pe,/(\[\s*(turn\s*:)?\s*(continue|finish)\s*\]|\[\[END\]\])/gi,"").trim(),pa=We.length>0||jn(Bt(pe)).length>0,Yn=(ga||We.length===0)&&!Ut&&!Vn&&!Xt;if(Yn=We.length===0?Yn:!1,Yn=pa&&nn||Vo?!1:Yn,pe&&pe.trim().endsWith('")]')&&We.length===0&&(Yn=!1),Yn){Cs=!0;let q=Ai.join(`
847
- `),ee=Bt(q).trim();yield{type:"interactive_turn_finished",data:{agentText:Me,fullAgentTextRaw:q,history:[...b],needTitle:Ce}},b.length>0&&b[b.length-1].role==="agent"?b[b.length-1].text=ee:b.push({role:"agent",text:ee}),b.forEach(M=>{if(M.role==="user"&&M.text&&(M.text=M.text.replace(/\n\[COMPILE ERROR\][\s\S]*?\[\/ERROR\]/g,""),M.text=M.text.replaceAll(`
848
-
849
- [system] user question. resolve this specific query within '[ANSWER] ... [/ANSWER]' concisely, naturally [/system]
850
- `,"").replaceAll(`[system] user question. resolve this specific query within '[ANSWER] ... [/ANSWER]' concisely, naturally
851
- **strictly follow thinking policy as high priority. do not start a response without <think_fluxflow>...</think_fluxflow>** [/system]
852
- `,"").replaceAll(`[system] **strictly follow thinking policy as high priority. do not start a response without <think_fluxflow>...</think_fluxflow>** [/system]
853
- `,"").replaceAll(/\n\[system\] WARNING, Turn Limit Impending: Step \d+\/\d+\. Wrap up quickly\/prompt user to continue & use \[\[END\]\] quickly\. \[\/system\]/g,""),M.text=M.text.replaceAll(/\n\[system\] File Changes:\n(?:\* .+ \(created|modified|deleted\)\n)*\[\/system\]/g,""),(s==="Mistral"||s==="Google"&&e?.toLowerCase().startsWith("gemma"))&&(M.text.startsWith("[ACTION RESULT]")||M.text.startsWith("[TOOL RESULT]")))){let Le=`
854
- [system] Action result received. Analyze output and proceed with your turn [/system]`,Ke=`
855
- [system] Action result received. Analyze output and proceed with your turn. **strictly follow thinking policy. do not start a response without <think_fluxflow>...</think_fluxflow>** [/system]`;M.text=M.text.replaceAll(Ke,"").replaceAll(Le,"").trim()}}),yield{type:"status",content:"[end]"}}if(Yn)break;let ha=ma.trim()||"*Working...*";if(b.push({role:"agent",text:ha}),We.length>0||En){if(We.length>0){let q=We.map(ot=>ot.text).join(`
856
-
857
- `),ee=Bt(pe),M=yi(ee),gt=jn(ee),Le=/\[\s*(?:tool:(?:functions\.)?|action:(?:functions\.)?|action:)([a-zA-Z0-9_]+)\s*\(/gi,Ke=[],It=[],Ee;for(;(Ee=Le.exec(M))!==null;)It.push({index:Ee.index,toolName:Ee[1]});for(let ot=0;ot<It.length;ot++){let Dt=It[ot],He=ot+1<It.length?It[ot+1].index:ee.length;gt.some(io=>io.fullMatch&&ee.startsWith(io.fullMatch,Dt.index))||Ke.push(ee.substring(Dt.index,He))}let vt=Ke.length,mt=We.length+vt;if(vt>0){let ot=Ke.join(`
858
- `),Dt=oa(ot);q+=`
859
-
860
- [system] Only ${We.length} out of ${mt} attempted tool calls were executed.
861
- ${Dt?`Parsing Issues Detected:
862
- ${Dt}
863
- `:""}Verify proper structure compliance [action:ActionName(arg="value")] & try failed calls again [/system]`;for(let He=0;He<vt;He++)await Lt("toolFailure")}let bt=We.find(ot=>ot.binaryPart)?.binaryPart||null;b.push({role:"user",text:q,binaryPart:bt})}}else if(!Et){let q=pe.replace(/(?:<think_fluxflow>|\[think_fluxflow\])[\s\S]*?(?:<\/think_fluxflow>|\[\/think_fluxflow\]|$)/i,""),M=(yi(q).match(/\[\s*(?:tool:(?:functions\.)?|action:(?:functions\.)?|action:)([a-zA-Z0-9_]+)\s*\(/gi)||[]).length;if(Vo||nn&&M>0||M>0){let gt=oa(q),Le=gt?`[system] Failed to execute ${M>0?M:1} tool call${M>1?"s":""} due to syntax/structure issues:
864
- ${gt} [/system]`:`[system] Failed to execute ${M>0?M:1} tool${M>1?"s":""}. Verify proper structure compliance [action:ActionName(arg="value")] & try again [/system]`;b.push({role:"user",text:Le}),await Lt("toolFailure"),yield{type:"visual_feedback",content:`
865
- ${Kt("\u2718 Model produced malformed tool call")}
866
- `}}else yield{type:"visual_feedback",content:`
867
- ${Kt("\u2718 Loop Detected")}
868
- `},b.push({role:"user",text:`[system] ${Vn&&!Ut?"Stuttering Detected by Internal System. Re-calibrate your response & proceed.":`${Ut?" Over Thinking":" Loop"} Detected by Internal System${Ut?" for current Effort Level":""}. ${Ut?"If you have planned the task, prioritize execution/output":"If you have finished your task provide a simple summary and end"}`} [/system]`});Ut=!1,Vn=!1,Xt=!1}p?.advanceRollback&&await Ro.recordTurnDelta(h,I+1,Ie),Ei=Ie.includes("recapture_screen"),Vo=Rt>0||En}if(!Cs&&!Et){let I="\u2726 Turn safety limit reached. Stopping execution.";yield{type:"text",content:`
869
-
870
- ${I}
871
- `};let _e=(Ai.join(`
872
- `)+`
873
- ${I}`).trim();yield{type:"interactive_turn_finished",data:{agentText:Me,fullAgentTextRaw:_e,history:[...b],needTitle:Ce}},yield{type:"status",content:"[end]"}}}catch(W){let b=W?.cause?` (Cause: ${W.cause?.message||String(W.cause)})`:"",fe=(W instanceof Error?(()=>{try{return JSON.parse(JSON.parse(W.message).error.message).error.message}catch{return(W.message?`${W.message}${b}`:"")||String(W)}})():String(W)).replace(/^(Error:\s*)+/i,"");s==="Google"&&!/^[A-Z0-9_\-\s]+ ERROR:/i.test(fe)&&(fe=`GEMINI ERROR: ${fe}`);let z=new Date().toLocaleString(),tn=U.join(wn,"agent");yield{type:"text",content:`
874
-
875
- \u2726 CRITICAL ERROR: ${fe.includes("fetch failed")?"Failed to Connect. Check your Internet Connection or Wait a moment":fe}
876
- \u2800`},Ae.existsSync(tn)||Ae.mkdirSync(tn,{recursive:!0}),Ae.appendFileSync(U.join(tn,"error.log"),`CRITICAL ERROR [${z}]: ${W}${W?.cause?`
877
- CAUSE: ${W.cause?.stack||W.cause}`:""}
878
-
879
- ----------------------------------------------------------------------
880
-
881
- `),typeof flushGoogleBuffer=="function"&&(yield*flushGoogleBuffer()),yield{type:"tool_result",content:`ERROR: [INTERNAL CRITICAL] ${fe}`}}finally{Je&&(clearInterval(Je),Je=null),typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),await ti.commitTransaction(),p?.advanceRollback&&await Ro.cleanup(h),await Qn()}yield{type:"status",content:null}},Ud=async(e,n,t=null,i=null,o=50,r=null,d=!1)=>{let a=await Eo(),u={...a,...n},h=process.env.SUBAGENT_MODEL?process.env.SUBAGENT_MODEL.trim():null,x=process.env.SUBAGENT_PROVIDER?process.env.SUBAGENT_PROVIDER.trim():null,p=new Date,f=`${p.getFullYear()}-${p.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(p.getDate()).padStart(2,"0")}, ${p.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}).replace(":","-")}`,g=(fe=>{if(!fe)return null;let z=fe.toLowerCase();return z==="google"?"Google":z==="deepseek"?"DeepSeek":z==="openrouter"?"OpenRouter":z==="nvidia"?"NVIDIA":z==="mistral"?"Mistral":z==="ollama"?"Ollama":z==="inferx"?"InferX":z==="sensenova"?"SenseNova":z==="poolside"?"Poolside":z==="9router"||z==="9Router"?"9router":z==="aihubmix"||z==="aihub"?"AIHubMix":z==="explabs"||z==="experientiallabs"||z==="experimentallabs"?"ExpLabs":z==="tokenharbor"||z==="token harbor"||z==="token_harbor"||z==="thk"?"TokenHarbor":z==="infron"?"Infron":z==="apinex"||z==="apx"?"APInex":z==="xkiro"||z==="kiro"?"xKiro":z==="c_openai"||z==="custom_openai"||z==="custom (openai)"||z==="custom"?"c_openai":null})(x),k=u?.systemSettings?.CustomSubAgent?u?.systemSettings?.SubAgentModel:null,he=u?.systemSettings?.CustomSubAgent?u?.systemSettings?.SubAgentProvider:null,y=null;if(k==="ENV"?(y=h,h&&g&&(u.aiProvider=g)):k&&k!=="Default"?(y=k,he&&(u.aiProvider=he)):h&&g&&(u.aiProvider=g),u.aiProvider){let fe=await $i(u.aiProvider);fe&&(u.apiKey=fe)}let E=fe=>{if(!fe||typeof fe!="string")return{allowed:!0};let z=[/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 tn of z)if(tn.test(fe))return{allowed:!1,reason:`Blocked potentially destructive or unsafe command pattern: "${tn.source}"`};return{allowed:!0}},D=t||y||n?.modelName||n?.activeModel||a.activeModel,L=(process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux")==="Windows",T=L&&u?.systemSettings?.preferBash!==!1&&Ls(),Se="Run(command=string)",Ce=`Runs ${L?Bi()?"powershell":"windows CMD":"bash"} command`;T&&(Se=`Run(command=string, ${$s()||Bi()?"forcePowershell?=bool:false":"forceCwd?=bool:false"})`,Ce="Runs in git bash. Or force native shell");let Me=`-- ACTIONS (path = relative to CWD, path separator: '/') --
882
- In chat output the format \`[action:ActionName(arg1="value1")]\` in NEW line
883
- Rules:
884
- - JSON escape literal sequences, backslash: \\\\, newLine: \\ n
885
- - Same file, multiple edits? ONE PatchFile \u226415 blocks
886
- - Need text or huge file? CodeSearch > Full Read
887
- - Stuck on syntax error? Tell user > waste time
888
-
889
- # Provided Actions
890
- **Communication**
891
- - AskUser(question=string, optionA?="title::description", ...MAX4). Any Ambiguity
892
- ${d?"- AskMain(question=string). Communicate with PARENT/MAIN AGENT. When clarification/decision is needed for a task":""}
893
-
894
- **Web**
895
- - WebSearch(query=string, aiMode?=bool:false, limit?=int[3..10]). For unknown topics, time sensitive, fact checking
896
- - WebScrape(url=string). JS supported
897
-
898
- **Workspace**
899
- - CodeSearch(keyword=string, path?="file/glob, inclusion !exclusion ;-separated", regex?=bool:auto)
900
- - ReadFolder(path=string, recurse?=int[1..3])
901
- - FindFile(basename=string)
902
- - ReadFile(path=string, startLine?=int, endLine?=int)
903
- - 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
904
- - WriteFile(path=string, content=string). Creates/Overwrites. File Exist? PatchFile > WriteFile
905
- - ${Se}. ${Ce}. Destructive command \u2192 Ask user`.trim(),Je=`=== START SYSTEM PROMPT ===
906
- Identity: FluxFlow subagent helping the main Agent
907
- Your task: "${e}"
908
- CWD: ${process.cwd()}
909
-
910
- ${Me.trimEnd()}
911
-
912
- -- THINKING GUIDANCE --
913
- Use minimal reasoning. Prefer simplest path; avoid branching; waste NO tokens overthinking. Just focus on task completion. Before actions, provide user facing summary of findings & decisions IN detail
914
- Main focus: actions and task, not chatting
915
- On completion, provide a detailed summary in Tables/Markdown Format with file modified info. If any task failed report back in detail
916
-
917
- Current Time: ${f}
918
- === END SYSTEM PROMPT ===`,W=[{role:"user",text:`Complete this task: ${e}`}],b=0,ht="";for(;b<o;){let fe=await Ni("subagent",u);if(!fe.allowed)throw new Error(fe.reason||`Budget Exhausted for Provider (${u?.aiProvider||"Subagent"})`);if(Et){if(n?.taskId&&typeof en<"u"){let G=en.find(_=>_.id===n.taskId);G&&(G.status="cancelled")}throw r&&r("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}if(n?.taskId&&typeof en<"u"){let G=en.find(_=>_.id===n.taskId);if(G&&G.status==="cancelled")throw r&&r("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}let z=W.map(G=>({role:G.role==="user"?"user":"model",parts:[{text:G.text}]}));r&&r(`[Subagent Turn ${b+1}]...`);let tn=["Fast","Low","Medium","High"],Vt=process.env.SUBAGENT_THINKING,cn=tn.includes(Vt)?Vt:"Low",Pn=(await xi(u,D,z,Je,cn)).text||"",dn=sa(Bt(Pn).trim());ht=dn,r&&r(`[Subagent Response]
919
- ${dn}
920
- `),W.push({role:"agent",text:dn});let yt=jn(dn);if(yt.length===0)break;let Yt=yt.filter(G=>G.toolName.toLowerCase()==="askmain"||G.toolName.toLowerCase()==="ask_main"),ue=!1,Be="";for(let G of yt){if(Et){if(n?.taskId&&typeof en<"u"){let S=en.find($=>$.id===n.taskId);S&&(S.status="cancelled")}throw new Error("Subagent task was cancelled.")}if(n?.taskId&&typeof en<"u"){let S=en.find($=>$.id===n.taskId);if(S&&S.status==="cancelled")throw new Error("Subagent task was cancelled.")}let _=G.toolName.toLowerCase();if(_==="askuser"&&(_="ask"),_==="askmain"||_==="ask_main"){if(ue)continue;ue=!0;let S="";if(Yt.length===1?S=j(Yt[0].args).question||Yt[0].args:S=Yt.map(($,ct)=>{let ze=j($.args);return`Q${ct+1}: ${ze.question||$.args}`}).join(`
921
- `),n.onAskMain){r&&r(`[Executing Tool] AskMain("${S}")...`);let $=await n.onAskMain(S);r&&r(`[Action Result]
922
- Answer from Main Agent: ${$}
923
- `),Be+=`[ACTION RESULT for AskMain]: Answer from Main Agent: ${$}
924
-
925
- `,await Lt("toolSuccess")}else Be+=`[ACTION RESULT for AskMain]: ERROR: Main agent communication channel not available.
926
-
927
- `;continue}if(!(i?i.some(S=>S.toLowerCase()===_):!0)){let S=`ERROR: Tool [${G.toolName}] is not in the allowed tools list for this subagent.`;r&&r(`[Blocked Tool Call] ${G.toolName} - not allowed
928
- `),Be+=`${S}
929
-
930
- `;continue}if(_==="exec_command"||_==="execcommand"||_==="run"){let S=j(G.args).command||"",$=E(S);if(!$.allowed){let ct=`ERROR: [SECURITY RESTRICTION] Subagent execution blocked command: ${$.reason}`;r&&r(`[Blocked Command] ${S} - ${$.reason}
931
- `),Be+=`${ct}
932
-
933
- `;continue}}let Oe="";if(_==="web_search"||_==="websearch")Oe=`\u2714 \x1B[95mSearched\x1B[0m: ${j(G.args).query||""}`;else if(_==="web_scrape"||_==="webscrape")Oe=`\u2714 \x1B[95mScraped\x1B[0m: ${j(G.args).url||""}`;else if(_==="search_keyword"||_==="searchkeyword"||_==="codesearch"||_==="code_search"){let S=j(G.args),$=S.keyword||"",ct=S.path||"";Oe=`${$?"\u2714":"\u2718"} \x1B[95mSearched\x1B[0m: ${$||"No Query"}${ct?` \u2192 ${ct.replaceAll("\\","/")}`:""}`}else if(_==="view_file"||_==="viewfile"||_==="readfile")Oe=`\u2714 \x1B[95mRead\x1B[0m: ${(j(G.args).path||"").replaceAll("\\","/")}`;else if(_==="find_file"||_==="findfile"){let S=j(G.args),$=S.basename||S.name||S.path||S.file||S.query||"";Oe=`${$?"\u2714":"\u2718"} \x1B[95mLocated\x1B[0m: ${$||"No Query"}`}else if(_==="list_files"||_==="read_folder"||_==="readfolder"){let S=j(G.args).path||null,$=j(G.args).recurse||0;Oe=`${S?"\u2714":"\u2718"} \x1B[95mBrowsed\x1B[0m: ${S?`${S.replaceAll("\\","/")}${$>0?`${S.endsWith("/")?`*${$}`:`/*${$}`}`:`${S.endsWith("/")?"":"/"}`}`:""}`}else if(_==="write_file"||_==="writefile"){let S=j(G.args).path||null;Oe=`${S?"\u2714":"\u2718"} \x1B[95mCreated\x1B[0m: ${S?`${S.replaceAll("\\","/")}`:"No File Changes"}`}else if(_==="update_file"||_==="updatefile"||_==="patchfile"||_==="patch_file"){let S=j(G.args),$=S.path||null,ze=Object.entries(S).some(([Ct,it])=>Ct.startsWith("searchContent")&&typeof it=="string"&&it.startsWith("^LINE:"))?"\u1361":":";Oe=`${$?"\u2714":"\u2718"} \x1B[95mEdited\x1B[0m${ze} ${$?`${$.replaceAll("\\","/")}`:"No File Changes"}`}else if(_==="exec_command"||_==="execcommand"||_==="run"){let S=j(G.args).command||null;Oe=`${S?"\u2714":"\u2718"} \x1B[95mExecuted\x1B[0m: ${S?S.slice(0,100)+(S.length>100?"...":""):"No Command"}`}else if(_==="file_map"||_==="filemap"){let S=j(G.args).path||"";Oe=`${S?"\u2714":"\u2718"} \x1B[95mIndexed\x1B[0m: ${S?`${S.replaceAll("\\","/")}`:"File Not Found"}`}else if(_==="await"){let{time:S}=j(G.args),$=parseFloat(S)||0;$<10&&($=10),$>180&&($=180),Oe=`\u2714 \x1B[95mAwaiting\x1B[0m \u2192 ${(ze=>{if(ze>=60){let Ct=Math.floor(ze/60),it=ze%60;return`${Ct}m${it>0?` ${it}s`:""}`}return`${ze}s`})($)}`}else{let S=ps[_]||G.toolName,$=eo(_,G.args);Oe=`\u2714 \x1B[95m${S}\x1B[0m${$?`: ${$}`:""}`}n.onVisualFeedback&&Oe&&n.onVisualFeedback(Oe),r&&r(`[Executing Tool] ${G.toolName}(${G.args})...`);try{let S=await Bo(G.toolName,G.args,{...n,mode:"Flux"});if(r&&r(`[Action Result]
934
- ${S}
935
- `),Be+=`[ACTION RESULT for ${G.toolName}]: ${S}
936
-
937
- `,await Lt("toolSuccess"),_==="patchfile"||_==="update_file"||_==="updatefile"||_==="patch_file"){if(S){let $=S.split(`
938
- `),ct=0,ze=0,Ct=!1;for(let it of $){if(it.includes("[DIFF_START]")){Ct=!0;continue}if(it.includes("[DIFF_END]")){Ct=!1;continue}Ct&&(/^\+\s*\d+/.test(it)?ct++:/^\-\s*\d+/.test(it)&&ze++)}(ct>0||ze>0)&&(await At("linesAdded",ct),await At("linesRemoved",ze))}}else if((_==="writefile"||_==="write_file")&&S){let $=S.match(/- Stats: \[(\d+) lines/),ct=$?parseInt($[1]):0,ze=0;if(S.includes("Old File contents:")){let Ct=!1;for(let it of S.split(`
939
- `)){if(it.includes("Old File contents:")){Ct=!0;continue}Ct&&(it.startsWith("- Content Preview:")||it.trim()===""&&!/^\s*\d+\s*\|/.test(it)?Ct=!1:/^\s*\d+\s*\|/.test(it)&&ze++)}}(ct>0||ze>0)&&(await At("linesAdded",ct),await At("linesRemoved",ze))}}catch(S){let $=`ERROR: Execution failed for [${G.toolName}]: ${S.message}`;r&&r(`[Tool Error] ${$}
940
- `),Be+=`${$}
941
-
942
- `,await Lt("toolFailure")}}let Pe="";if(n?.taskId&&typeof en<"u"){let G=en.find(_=>_.id===n.taskId);if(G&&G.pendingSteerMessages&&G.pendingSteerMessages.length>0){let _=[...G.pendingSteerMessages];G.pendingSteerMessages=[];for(let Qe of _)Pe+=`
943
-
944
- [STEERING INSTRUCTION FROM MAIN AGENT]: ${Qe}`,r&&r(`[Subagent Steered] ${Qe}`)}}let V=(Be.trim()+Pe).trim();W.push({role:"user",text:V}),b++}return ht};export{mo as a,pi as b,Gc as c,Hc as d,fc as e,uc as f,go as g,gc as h,_c as i,vc as j,dl as k,Pd as l,fl as m,ul as n,ms as o,Bt as p,hi as q,sa as r,hl as s,Od as t,Ld as u,ys as v,$d as w,yi as x,xl as y,jn as z,Nd as A,xi as B,Dd as C,Fd as D,Bd as E,Ud as F};