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