fluxflow-cli 4.29.1 → 4.30.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,893 @@
1
+ import{a as mr}from"./chunk-JS5ZIGFR.js";import{a as Bt}from"./chunk-56EJGQU3.js";import{a as mo}from"./chunk-7SFAWGE2.js";import{a as gr,c as hr}from"./chunk-U2NRX2PX.js";import{a as bi,g as pr}from"./chunk-VYTQ6J56.js";import{a as yr}from"./chunk-RZTZPIC5.js";import{c as pi,g as yi,h as fr,i as ur,m as xi}from"./chunk-53AFLLUU.js";import{a as $o}from"./chunk-FQBBOFNP.js";import{a as G}from"./chunk-Y5JU726N.js";import{b as hi}from"./chunk-KHCAQOSP.js";import{d as ho,i as kt,k as gt,m as mi,n as dr}from"./chunk-QJZ24WJZ.js";import{a as go}from"./chunk-RVCMZTHS.js";import{k as it,l as Lo,o as Z}from"./chunk-63V6P5DU.js";import{c as Tt,d as zn,e as cr}from"./chunk-L3W2X74K.js";import{a as An,b as lr,d as En,e as Oo,k as Fn,l as Po,m as ui,r as gi,w as fo,x as uo}from"./chunk-DSVLWYIT.js";import{GoogleGenAI as Os,ThinkingLevel as Ge,HarmBlockThreshold as vn,HarmCategory as _n}from"@google/genai";var xr=(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 No={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 Qt from"fs";import rn from"path";import ia from"os";import on from"fs";import Rn from"path";import Mr from"fs";import wi from"path";import{execSync as Or}from"child_process";import{fileURLToPath as oa}from"url";var br=`# 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 wr=`# Env Variables
58
+
59
+ * Locations:
60
+ * Shell
61
+ * Global: ~/.fluxflow/.env.fluxflow | ~/.fluxflow/.env.agents
62
+ * Workspace: ./.env.fluxflow | ./.env.agents
63
+
64
+ ## Core Variables
65
+ * SUBAGENT_MODEL \u2192 Model override for sub-agents
66
+ * SUBAGENT_PROVIDER \u2192 Provider override for sub-agents
67
+ * NVIDIA_BASE_URL \u2192 Custom endpoint URL for NVIDIA NIM (Cloud/Local OpenAI Compatible)
68
+ * SUBAGENT_THINKING - Fast, Low (default), Medium, High. Affects at High Level, not Low Level. --map takes priority
69
+ * NVIDIA_API_KEY \u2192 API key for NVIDIA NIM
70
+ * OLLAMA_HOST \u2192 If different from default
71
+ * SHELL \u2192 Terminal shell executable
72
+ * HIGH_CONTEXT \u2192 Context window override (false or integer 32k..1M) [Deprecated! Will stop working from next major version]
73
+ * 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
+
77
+ ## Diagnostic & Optimization Flags
78
+ * SHOW_DEBUG_GRID \u2192 (true|false, default: false) Coordinate grid overlay for Computer Use tooling
79
+ * DEBUG_OCR \u2192 (true|false, default: false) Enables verbose OCR diagnostic logs
80
+ * EXPERIMENTAL_MEMORY_MANAGER \u2192 (true|false, default: false) Reduces app memory footprint, slower boot times
81
+
82
+ * NO_DEV \u2192 (true|false, default: false) Token optimization flag; strips developer metadata and docs to maximize context headroom
83
+
84
+ * 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
85
+ * GOOGLE_GEMMA_NONSENSE \u2192 (true|false, default: false) for the 16k TPM nonsense of gemma models on gemini API. False defaults to 256k
86
+ `;var Sr=`# Fluxflow in-app /commands
87
+
88
+ Trigger in chat via /command
89
+
90
+ ## Session & Navigation
91
+ * /quit \u2192 Exit and shutdown FluxFlow
92
+ * /help \u2192 Show help menu & actions
93
+ * /clear \u2192 Clear terminal viewport
94
+ * /chats \u2192 List stored chat sessions
95
+ * /resume \u2192 Switch to previous session
96
+ * /save \u2192 Force-save current session state
97
+ * /reset \u2192 Wipe fluxflow appdata, sessions, and cache
98
+
99
+ ## Context & History Management
100
+ * /compress \u2192 Summarize chat history to reclaim context headroom
101
+ * /truncate \u2192 Truncate large tool results in history
102
+ * /btw question \u2192 Send side-inquiry mid-turn without breaking active flow
103
+ * /export chat | logs \u2192 Export chat transcript or error logs
104
+
105
+ ## Codebase Safety & Reversion
106
+ * /revert \u2192 Git-less checkpoint rollback viewer (Shortcut: double-ESC while idle)
107
+
108
+ ## Configuration & Model Controls
109
+ * /settings \u2192 Full-screen interactive settings menu
110
+ * /mode \u2192 Toggle Operating Mode
111
+ * /display index \u2192 Select active screen for Computer Use mode
112
+ * /model model-id --flags \u2192 Flags optional to customize list (--save, --remove, --default, /model old-model new-model --rename)
113
+ * /provider \u2192 Switch AI provider
114
+ * /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
115
+ * /wildcard-tooling \u2192 Tool compatibility mode for non-tooling models
116
+ * /wildercard-tooling \u2192 Extended version of /wildcard-tooling
117
+ * /key \u2192 Manage saved API keys
118
+ * /profile \u2192 Edit user persona, nickname, and custom instructions
119
+ * /theme \u2192 Select UI color theme
120
+ * /memory \u2192 View/manage agent persistent memory
121
+ * /budget \u2192 Set/view token budget limits
122
+ * /stats \u2192 Session token usage telemetry
123
+ * /usage \u2192 Open graphical browser analytics dashboard
124
+
125
+ ## Documentation & Updates
126
+ * /docs \u2192 Online documentation
127
+ * /about \u2192 App info & author credits
128
+ * /changelog \u2192 Release notes
129
+ * /update check \u2192 Check npm updates
130
+ * /update latest \u2192 Install latest release
131
+ * /fluxflow init \u2192 Create local FluxFlow.md project-instructions template
132
+ * /move \u2192 Transfer Playground session data to CWD/playground-export
133
+ `;var Tr=`# FluxFlow In-App Settings Reference
134
+
135
+ Open in chat via /settings
136
+
137
+ ## Settings Categories & Options
138
+
139
+ ### 1. Providers & Tips \u2192 references/PROVIDERS.md
140
+ - Custom OpenAI Endpoint?
141
+ * Base URL: .../v1
142
+ * API Key: optional
143
+
144
+ ### 2. Appearance
145
+ * Theme \u2192 UI theme (Dark | Light | Cyberpunk | Forest | Sunset | Matrix | Dracula | Nord | Monokai | Mystery/Chaos)
146
+ * Loading Phrases \u2192 Humorous status phrases during thinking
147
+ * Progressive Rendering [Experimental] \u2192 Smooth streaming token rendering. May have few glitches
148
+ * Show TPM Estimate \u2192 Real-time Tokens Throughput speed estimate
149
+ * Verbose Thinking \u2192 Show reasoning blocks in the UI. Keeps UI clean when disabled. And reasoning transparent when enabled
150
+
151
+ ### 3. Memory
152
+ * Toggle Memory \u2192 Persistent cross-session memory learning (Not available for some providers)
153
+
154
+ ### 4. Security & Sandbox
155
+ * Sandbox Preset:
156
+ * Strict \u2192 YOLO: OFF | External Access: OFF | Network Access: OFF | destructive commands blocked | strict HITL
157
+ * Balanced \u2192 YOLO: ON (safe commands) | External Access: OFF | Network Access: ON | destructive commands blocked | manual git approval
158
+ * Autonomous \u2192 YOLO: ON | External Access: ON | Network Access: ON | auto-approve git commits | prompt high-risk commands
159
+
160
+ * YOLO Mode \u2192 Autonomous command execution without confirmation
161
+ * External Workspace Access \u2192 Read/write access outside CWD
162
+ * Network Access (Internal Shell) \u2192 Outbound network access for shell commands
163
+ * Command Policies:
164
+ * Always Ask Commands \u2192 Commands requiring explicit confirmation
165
+ * Auto Approve Commands \u2192 Safe commands allowed to execute automatically
166
+ * Auto Disapprove Commands \u2192 Blacklisted commands automatically rejected
167
+
168
+ * Auto Approve Git Commits \u2192 Auto-confirm git commit operations
169
+ * Advanced Recovery [EXPERIMENTAL] \u2192 Enhanced rollback if agent corrupt codebase
170
+ * Auto-Delete History \u2192 Chat log retention period
171
+ * Save AppData Externally \u2192 Saves chats/apikeys to user provided path
172
+
173
+ ### 5. Updater
174
+ * Auto-Update \u2192 Check for new releases on boot
175
+ * Preferred Package Manager \u2192 npm | pnpm | yarn | bun | custom
176
+
177
+ ### 6. Miscellaneous
178
+ * Sub-Agents \u2192 Enable sub-agent delegation
179
+ * Sub-Agent Model \u2192 Dedicated model/provider for sub-agents
180
+ * Directory Tree Design \u2192 Directory visual styling. Modern (Saves Tokens) | Legacy (More Tokens, No extra benefit)
181
+ * Compact Large Tool Results \u2192 Compress large tool outputs to save tokens (model might miss subtle indentation/syntax errors)
182
+ * Context Length \u2192 Set usable context window size in FluxFlow. 16k, 32k, 64k, 128k, 256k, 512k, 1M. After Limit reached: Start new chat
183
+ * Auto Truncate Results \u2192 Auto-truncate tool results after task finished to save token and improve caching
184
+ * Image History for CU \u2192 Number of images to keep in context for Computer Use. Low (3 images, Low Context Accuracy, Token Efficient) / Standard (5 images, Better Accuracy, Higher Token Usage) / Extended (10 images, Better for complex tasks, Highest Token Usage) / Max (999 images, Full history kept, Maximum Accuracy, Highest Token Usage)
185
+ * Keep Reasoning Content \u2192 Keeps the exact reasoning of model in context for next turns. Uses more tokens. Might improve planning accuracy for very few models
186
+ * 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
187
+ * Disable Todo \u2192 Disables Todo/Goal tool for Agent. Doesnt necessarily affect modern models
188
+
189
+ -- Recomended Settings Preset --
190
+ - Best for Cost Saving: Subagents (off), directory tree design (modern), compact large results (on), auto exclue metadata (on), Image History (Low), Keep reasoning content (off), Emergency Recovery (off), Auto truncate results (on), Memory (off), No FluxFlow IDE Companion
191
+
192
+ - Best for General Use: Subagents (on), compact large results (off), auto exclue metadata (off), Image History (Standard), Keep reasoning content (off), Emergency Recovery (off), Auto truncate results (on), Memory (off), FluxFlow IDE Companion
193
+
194
+ - Best for Luxurious Experience: Subagents (on), compact large results (off), auto exclue metadata (off), Image History (Max), Keep reasoning content (on), Emergency Recovery (on), Auto truncate results (off), Memory (on), Security Preset (Autonomous), FluxFlow IDE Companion
195
+
196
+ - Max Cache Hit: Subagents (off), compact large results (on), auto exclue metadata (on), Image History (Low), Keep reasoning content (off), Emergency Recovery (off), Auto truncate results (off), Memory (off), No FluxFlow IDE Companion
197
+ `;var kr=`# FluxFlow Tool Reference
198
+
199
+ ## Protocol: [tool:ToolName(arg1="val")]
200
+
201
+ ## 1. Workspace
202
+ * ReadFile(path, startLine?, endLine?) \u2192 Read text/code/PDF/image
203
+ * PatchFile(path, searchContent1..15, newContent1..15, allowMultiple?) \u2192 Atomic multi-replacement; supports ^LINE:start..end$
204
+ * WriteFile(path, content) \u2192 Create/overwrite file
205
+ * ReadFolder(path, recurse?) \u2192 List directory tree (depth: 1-3)
206
+ * FindFile(basename) \u2192 Locate file path by name/glob/fuzzy match (ext optional)
207
+ * CodeSearch / SearchKeyword(keyword, path?, fuzzy?, regex?) \u2192 Fast text search; path="#docs" for doc index
208
+ * Run(command) \u2192 Execute command in shell
209
+ * Goal(method, tasks?, markDone?) \u2192 Planner ("create" | "append" | "get"); alias: Todo
210
+
211
+ ## 2. Web & Communication
212
+ * WebSearch(query, aiMode?, limit?) \u2192 Live web search + AI summary
213
+ * WebScrape(url) \u2192 Extract markdown from URL
214
+ * AskUser(question, optionA..D?) \u2192 Interactive prompt to user ("title::desc"); alias: Ask
215
+
216
+ ## 3. Sub-Agents
217
+ * InvokeSync(title, task) \u2192 Blocking sub-agent
218
+ * Invoke(title, task) \u2192 Non-blocking worker (max 7 concurrent)
219
+ * Await(id, timeout?) \u2192 Wait for async worker
220
+ * GetProgress(id) \u2192 Telemetry & logs
221
+ * Steer(id, message) \u2192 Mid-flight direction
222
+ * Cancel(id) \u2192 Terminate worker
223
+
224
+ ## 4. Emergency & Rollback
225
+ * EmergencyRollback(method, id?) \u2192 Checkpoint restore ("getCheckpoint" | "forceRevert")
226
+
227
+ ## 5. Creative Documents
228
+ * WritePDF(path, content, orientation?) \u2192 Render HTML/CSS to PDF
229
+ * WriteDoc(path, content) \u2192 Render DOCX
230
+
231
+ ## 6. Computer Use (GUI)
232
+ * Click(gridId, type?, button?, intendedClickText?) \u2192 Click coordinate + OCR snap
233
+ * Drag(fromGridId, toGridId) \u2192 Mouse drag
234
+ * Scroll(direction, gridId?) \u2192 Viewport scroll ("up" | "down")
235
+ * KeyboardTyping(text, autoPressEnter?) \u2192 Type string
236
+ * KeyPress(key) \u2192 Key/combo dispatch ("ctrl;c", "enter", etc.)
237
+ * RecaptureScreen() \u2192 Fresh screenshot + coordinate grid
238
+ `;var Ar=`# Fluxflow Architecture
239
+
240
+ ## 1. Terminal Engine
241
+ * Framework: React + Ink terminal UI
242
+ * Sub-Terminal: Live PTY shell bridge; TAB switches active keyboard focus
243
+ * OS Compatibility: Auto-detects pwsh, powershell, bash, cmd
244
+
245
+ ## 2. Dual-Model Runtime
246
+ * Main Agent: Reasoning, code edits, and tool calls
247
+ * Memory Agent: Background context & preference synthesizer (fixed models; disable via /settings \u2192 Memory or use NIM API key)
248
+
249
+ ## 3. Multi-Agent System
250
+ * Execution: Synchronous (InvokeSync) | Asynchronous (Invoke, \u22647 workers)
251
+ * Isolation: Restricted tool scope per subagent
252
+ * State Tracking: Mutations logged under parent task ledger
253
+
254
+ ## 4. Security & Sandbox
255
+ * Approvals: HITL confirmation on destructive file/shell operations
256
+ * Modes: Strict | Balanced | Autonomous (YOLO)
257
+ * Recovery: Pre-turn snapshot indexing via EmergencyRollback
258
+
259
+ ## 5. Computer Use Automation
260
+ * Vision: 720p normalized canvas, 4ms variance scan, Set-of-Marks (SoM) overlay
261
+ * OCR Alignment: Euclidean distance text matching to mark centers
262
+ * Hardware I/O: OS input dispatch via @nut-tree-fork/nut-js
263
+ * Memory Management: 2-turn sliding window with active V8 GC
264
+
265
+ ## 6. IDE Bridge
266
+ * Protocol: WebSocket on ws://localhost:56832
267
+ * State Sync: Focused file, open tabs, cursor line, selection, diagnostics
268
+ `;var Er=`# FluxFlow Sub-Agents & Multi-Agent Architecture
269
+
270
+ ## Execution Modes
271
+ * InvokeSync \u2192 Synchronous blocking delegation; main agent halts until sub-agent finishes task
272
+ * Invoke \u2192 Asynchronous background delegation; spawns parallel worker
273
+ * Lifecycle Tools:
274
+ * Await \u2192 Non-polling wait for completion
275
+ * GetProgress \u2192 Query live logs & execution status
276
+ * Steer \u2192 Inject dynamic instructions mid-flight
277
+ * Cancel \u2192 Terminate running sub-agent
278
+
279
+ ## Tool Sandboxing & Safety
280
+ * Sub-agents inherit isolated tool environments
281
+ * Destructive shell commands hard-blocked
282
+ * All file mutations tracked under parent session transaction
283
+
284
+ ## Custom Model & Provider Setup
285
+ Route sub-agent workloads to faster/cheaper models independently of the main agent:
286
+
287
+ ### 1. In-App Settings (/settings \u2192 Miscellaneous)
288
+ * Sub-Agents \u2192 ON | OFF
289
+ * Custom Sub-Agent Model:
290
+ * SubAgentModel \u2192 Model name
291
+ * SubAgentProvider \u2192 Provider
292
+
293
+ * Models are shown for providers whose API key is used before in fluxflow
294
+
295
+ ### 2. Environment Variables for Custom Sub-Agent models (.env.fluxflow or Shell)
296
+ * SUBAGENT_MODEL \u2192 Target model override
297
+ * SUBAGENT_PROVIDER \u2192 Target provider override
298
+ * Setting SubAgentModel=ENV in settings pulls directly from environment overrides
299
+ `;var Rr=`# FluxFlow Security, Sandboxing & Safety
300
+
301
+ ## Human-in-the-Loop Governance
302
+ * Execution Approval Gate \u2192 Destructive commands and high-risk file modifications require explicit user authorization (Allow / Deny)
303
+ * Safe Command Auto-Pass \u2192 Read-only queries (ls, pwd, git status, node -v) execute without interrupting flow
304
+
305
+ ## Sandbox Presets (/settings \u2192 Security)
306
+ * Strict \u2192 autoExec: OFF | allowExternalAccess: OFF | networkAccess: OFF | destructive commands blocked | strict HITL on all actions
307
+ * Balanced \u2192 autoExec: ON (safe commands) | allowExternalAccess: OFF | networkAccess: ON | destructive commands blocked | manual git approval
308
+ * Autonomous (YOLO) \u2192 autoExec: ON | allowExternalAccess: ON | networkAccess: ON | auto-approves git commits | prompts only on extreme-risk commands
309
+
310
+ ## Granular Command & Access Policies
311
+ * Command Filtering:
312
+ * Always Ask Commands \u2192 Configurable list always prompting for confirmation
313
+ * Auto Approve Commands \u2192 Whitelist of trusted commands executed automatically
314
+ * Auto Disapprove Commands \u2192 Blacklist of forbidden commands instantly rejected
315
+ * Workspace Directory Lock \u2192 Restricts file read/write operations strictly to current CWD unless External Access: ON
316
+ * Terminal Network Isolation \u2192 Blocks outbound network sockets for spawned shell commands when networkAccess: OFF
317
+
318
+ ## Recovery & Data Sanctuary
319
+ * Emergency Rollback \u2192 Automatic pre-turn file snapshots; Agent can still fix it (default: OFF) \u2192 references/SETTINGS.md
320
+ * Git-less Checkpoint Reversion \u2192 Trigger conversational changes rollback via double-ESC
321
+ * External Sanctuary Redirection \u2192 Move ~/.fluxflow data sanctuary (chats, keys etc)
322
+ `;var Cr=`# Fluxflow IDE Companion
323
+
324
+ ## WebSocket Bridge Protocol
325
+ * Local Bridge \u2192 Runs on ws://localhost:56832 connecting FluxFlow CLI with the companion editor extension
326
+ * Bi-directional Handshake \u2192 Exchanges CLI version, process PID/PPID, and editor capabilities on connection
327
+
328
+ ## Real-Time Context Awareness
329
+ * User Turn Context \u2192 Injected dynamically on every prompt turn:
330
+ * file_focused \u2192 Active editor tab currently visible
331
+ * opened_editors \u2192 List of all open file tabs in workspace
332
+ * cursor_line & selected \u2192 Exact cursor line number and selected text snippet
333
+ * manual_edits \u2192 User manual modifications since last turn
334
+ * 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
335
+
336
+ ## Editor Actions & Visual Feedback
337
+ * File Focus \u2192 Automatically opens edited files in active IDE window
338
+ * Diff Preview \u2192 Streams side-by-side or inline diff highlights (showDiff, highlightDiff) directly in editor
339
+ * Status Bar Sync \u2192 Real-time agent status (thinking, running tool, awaiting input) reflected in IDE status bar
340
+ `;var vr=`# Fluxflow Modes
341
+
342
+ ## Modes Overview (TAB to cycle)
343
+ * [Flux] (Workspace / Dev) \u2192 Primary coding & workspace agent
344
+ * [Flow] (Studio / Creative) \u2192 Web research & formatted document authoring (PDF / DOCX)
345
+ * [ICU] (Computer Use) \u2192 Autonomous GUI & OS desktop automation
346
+ * [FluxCU] (Omni) \u2192 Unified full-stack agent (Workspace Dev + Computer Use + Web)
347
+
348
+ ## Tool Availability
349
+ * File Operations: ReadFile, PatchFile, WriteFile, ReadFolder, CodeSearch \u2192 [Flux] | [FluxCU]
350
+ * Terminal Execution: Run \u2192 [Flux] | [FluxCU]
351
+ * Task Management: Todo \u2192 [Flux] | [FluxCU]
352
+ * Sub-Agents: InvokeSync, Invoke, Await, GetProgress, Steer, Cancel \u2192 [Flux] | [FluxCU]
353
+ * Checkpoint Recovery: EmergencyRollback \u2192 [Flux] | [FluxCU]
354
+ * Web & Research: WebSearch, WebScrape \u2192 [Universal]
355
+ * User Inquiry: AskUser \u2192 [Universal]
356
+ * Document Creation: WritePDF, WriteDoc \u2192 [Flow]
357
+ * GUI & Desktop Automation: Click, Drag, Scroll, KeyboardTyping, KeyPress, RecaptureScreen \u2192 [ICU] | [FluxCU]
358
+ `;var _r=`# FluxFlow AI Providers & Setup
359
+
360
+ ## Supported Providers
361
+ * Gemini | NVIDIA NIM | DeepSeek | Mistral | Ollama Local/Cloud | InferX | SenseNova | Poolside | OpenRouter | AIHubMix | Experiential Labs | TokenHarbor | APInex | Infron
362
+ * Proxy: 9router. Can use OAuth subscription like Codex, Claude Code, GitHub Copilot etc. or any OpenAI/Anthropic API that FluxFlow dont have natively
363
+ * Custom: Native custom OpenAI chat completions integration, no external package needed \u2192 references/SETTINGS.md, for more details
364
+
365
+ ## Switch Providers/Models:
366
+ * /model model-id --flags \u2192 Flags optional to customize list (--save, --remove, --default, /model old-model new-model --rename)
367
+ * /provider \u2192 Switch AI provider
368
+
369
+ ## OpenRouter: Routing, Tiers & Model Variants
370
+ * Provider Routing: Append :provider. /model model-id:provider
371
+ * Service Tiers & Variants:
372
+ * :flex|priority. flex = cheaper, priority = faster & expensive. /model openai/gpt-5:tier or /model openai/gpt-5:openai:tier
373
+ * Variants :free, :nitro, :floor, :exacto
374
+
375
+ ## Setup Local NVIDIA NIM (OpenAI-Compatible)
376
+ 1. Environment Variables:
377
+ * NVIDIA_BASE_URL = http://.../v1 or custom openai endpoint
378
+ * NVIDIA_API_KEY = If needed
379
+
380
+ ## Setup Ollama (Local / Cloud)
381
+ 1. Endpoint & Authentication:
382
+ * Local: Set API Key to LOCAL in /settings \u2192 Providers or on key prompt
383
+ * Endpoint URL: Default is http://127.0.0.1:11434 Override via OLLAMA_HOST
384
+
385
+ ## Setup: 9Router
386
+ 1. Install NPM Package (9router)
387
+ 2. Set ENV ENABLE_9ROUTER=true
388
+ * 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
389
+ * NINEROUTER_KEY = If any needed
390
+ `;var Ir=`# Fluxflow Instructions & Skills System
391
+
392
+ ## 1. Instructions (AGENTS.md / FLUXFLOW.md root only)
393
+ * Locations:
394
+ * Global: ~/.fluxflow/FLUXFLOW.md | ~/.fluxflow/AGENTS.md
395
+ * Workspace: ./FLUXFLOW.md | ./AGENTS.md | Directory Scoped like src/AGENTS.md
396
+ * Auto indexed on boot
397
+
398
+ ### Conditional Model & Provider Instructions (use /target command to get provider name & model-id)
399
+ You can scope instructions conditionally to specific providers, model IDs, or unique provider::model combinations using XML tags:
400
+ > 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
401
+
402
+ 1. Unique Target (Provider + Model):
403
+ <start_model_google::gemini-2.5-flash>
404
+ Specific instruction for Gemini 2.5 Flash when served by Google.
405
+ <end_model_google::gemini-2.5-flash>
406
+
407
+ 2. Model-Specific (Any Provider):
408
+ <start_model_gemini-2.5-flash>
409
+ Instruction for this model ID across all providers.
410
+ <end_model_gemini-2.5-flash>
411
+
412
+ 3. Provider Scoping & Grouping:
413
+ <start_provider_google>
414
+ <!-- General provider instruction -->
415
+ <start_model_gemini-2.5-pro>
416
+ Deep architectural reasoning steps.
417
+ <end_model_gemini-2.5-pro>
418
+ <end_provider_google>
419
+
420
+ * Case-insensitive matching.
421
+ * Unmatched blocks are completely skipped; matched blocks have their tags stripped and contents included.
422
+
423
+ ## 2. Skills System
424
+ * Locations:
425
+ * Global: ~/.fluxflow/skills/**/SKILL.md
426
+ * Workspace: ./skills/**/SKILL.md | ./SKILL.md
427
+
428
+ * Format:
429
+ * YAML Frontmatter: --- block with name and description
430
+ * Body: Markdown Instructions/Workflows
431
+
432
+ * On-Demand Reference System:
433
+ * Reference: Offload deep/contexual specs to **/{SKILL.md,skill-reference-folder/*.md} & reference in SKILL.md. Saves tokens
434
+ `;var Do="v4";try{let e=wi.dirname(oa(import.meta.url)),n=[wi.join(e,"../../package.json"),wi.join(e,"../package.json")],t=!1;for(let i of n)if(Mr.existsSync(i)){let o=JSON.parse(Mr.readFileSync(i,"utf8"));if(o.version){Do=o.version,t=!0;break}}if(!t)try{let i=Or("fluxflow -v",{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"],timeout:2e3}).trim();i&&(i.startsWith("v")||/^\d+\.\d+/.test(i))&&(Do=i,t=!0)}catch{}if(!t)try{let i=Or("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&&(Do=o.version)}catch{}}catch{}var Si={"SKILL.md":`---
435
+ name: fluxflow
436
+ description: System Generated Documentation. Read this if asked anything regarding FluxFlow Harness
437
+ ---
438
+
439
+ # FluxFlow, by Kushal Roy Chowdhury
440
+ Open Source Terminal AI Assistant
441
+ App Version: ${Do}. Check Updates: fluxflow --update check. Update: fluxflow --update
442
+ GitHub: https://github.com/KushalRoyChowdhury/fluxflow-cli
443
+ Public Docs: https://fluxflow-cli.onrender.com
444
+
445
+ ## Supported Features & Documentation References
446
+ * Operating Modes (Flux, Flow, CU, FluxCU) \u2192 references/MODES.md
447
+ * Inference Providers & Aggregators (Setup, Local NIM, Ollama) \u2192 references/PROVIDERS.md
448
+ * In-App Settings (/settings) & Recommended Presets \u2192 references/SETTINGS.md
449
+ * In-app /commands \u2192 references/COMMANDS.md
450
+ * CLI Startup Flags \u2192 references/STARTUP.md
451
+ * Environment Variables, Subagents, API Keys \u2192 references/ENV.md
452
+ * Tool System (Workspace, Web, Communication, Sub-Agents, Safety, Creative, Computer Use) \u2192 references/TOOLS.md
453
+ * Sub-Agents & Multi-Agent Runtime \u2192 references/SUB_AGENTS.md
454
+ * Security, Sandboxing & Checkpoints (/revert, double-ESC) \u2192 references/SECURITY.md
455
+ * IDE Companion Extension & Real-time Context \u2192 references/IDE.md
456
+ * Priority Instructions (AGENTS.md/FLUXFLOW.md) & Skill System \u2192 references/PLUGINS.md
457
+ * Agent Architecture & Memory System \u2192 references/ARCHITECTURE.md
458
+
459
+ Default Context Length: 256k Tokens. Can be changed via ENV/In-app Settings \u2192 references/{SETTINGS,ENV}.md
460
+
461
+ Docs missing required info? Say you are not sure enough to answer. Dont give wrong info`,"references/MODES.md":vr,"references/PROVIDERS.md":_r,"references/PLUGINS.md":Ir,"references/STARTUP.md":br,"references/ENV.md":wr,"references/COMMANDS.md":Sr,"references/SETTINGS.md":Tr,"references/TOOLS.md":kr,"references/ARCHITECTURE.md":Ar,"references/SUB_AGENTS.md":Er,"references/SECURITY.md":Rr,"references/IDE.md":Cr};var Pr=()=>{try{let e=Rn.join(An,"skills","fluxflow"),n=Rn.join(e,"references");if(process.env.NO_DEV==="true"||process.env.NO_DEV==="1"||process.env.NO_DEV===!0||process.env.NO_INS==="true"||process.env.NO_INS==="1"||process.env.NO_INS===!0||!1){on.existsSync(e)&&on.rmSync(e,{recursive:!0,force:!0});return}let i=new Set(Object.keys(Si).map(o=>Rn.normalize(o)));for(let[o,s]of Object.entries(Si)){let c=Rn.join(e,o),a=Rn.dirname(c);on.existsSync(a)||on.mkdirSync(a,{recursive:!0});let g=s.trim()+`
462
+ `,h=null;on.existsSync(c)&&(h=on.readFileSync(c,"utf8")),h!==g&&on.writeFileSync(c,g,"utf8")}if(on.existsSync(n)){let o=on.readdirSync(n);for(let s of o){let c=Rn.normalize(Rn.join("references",s));if(!i.has(c)){let a=Rn.join(n,s);try{on.rmSync(a,{recursive:!0,force:!0})}catch{}}}}}catch{}};var bo=(e,n)=>{try{if(!Qt.existsSync(e))return null;let t=Array.isArray(n)?n.map(o=>o.toLowerCase()):[n.toLowerCase()],i=Qt.readdirSync(e);for(let o of t){let s=i.find(c=>c.toLowerCase()===o);if(s){let c=rn.join(e,s);if(Qt.statSync(c).isFile())return c}}}catch{}return null},Ci=(e,n)=>{let t=bo(e,n);if(t)try{return Qt.readFileSync(t,"utf8")}catch{}return""},Lr=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"]),vi=(e=process.cwd(),n=0,t=8)=>{let i=[];if(n>t)return i;try{if(!Qt.existsSync(e))return i;let o=Qt.readdirSync(e,{withFileTypes:!0});for(let s of o){let c=s.name,a=rn.join(e,c);if(s.isDirectory())!Lr.has(c)&&!Lr.has(c.toLowerCase())&&i.push(...vi(a,n+1,t));else if(s.isFile()){let g=c.toLowerCase();(g==="agents.md"||g==="agent.md")&&i.push(a)}}}catch{}return i},$r=(e,n=2)=>{if(!e)return"";let t=" ".repeat(n);return e.split(/\r?\n/).map(i=>t+i).join(`
463
+ `)},Ur=()=>bo(An,["agents.md","agent.md"]),Wr=()=>bo(process.cwd(),["agents.md","agent.md"]),Gr=()=>bo(An,["fluxflow.md"]),Hr=()=>bo(process.cwd(),["fluxflow.md"]),Fo=Ur(),Ei=Wr(),Cn=vi(),Bo=Gr(),Uo=Hr(),Nr=null,Ri="",jr=!1,ra=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&&(Ri=o[1].trim(),process.env.NO_INS=!0),/<><\s*NO_INS/.test(t)&&(jr=!0),i.trim()},sa=()=>(Fo=Ur(),Fo?Ci(An,["agents.md","agent.md"]).trim():""),aa=()=>{if(Cn=vi(),Ei=Wr(),!Cn||Cn.length===0)return"";let e=process.cwd(),n=[...Cn].sort((i,o)=>{let s=rn.relative(e,i).replace(/\\/g,"/"),c=rn.relative(e,o).replace(/\\/g,"/"),a=!s.includes("/"),g=!c.includes("/");return a&&!g?-1:!a&&g?1:s.localeCompare(c)}),t=[];for(let i of n)try{let o=Qt.readFileSync(i,"utf8").trim();if(!o)continue;let s=rn.relative(e,i).replace(/\\/g,"/");if(!s.includes("/"))t.push($r(o,2));else{let a=rn.dirname(s)+"/:";t.push(`${a}
464
+ ${$r(o,2)}`)}}catch{}return t.join(`
465
+
466
+ `).trim()},_i=()=>{Bo=Gr();let e=Bo?Ci(An,["fluxflow.md"]).trim():"";return ra(e)},Ii=()=>(Uo=Hr(),Uo?Ci(process.cwd(),["fluxflow.md"]).trim():""),Mi=sa(),Wo=aa(),yo=_i(),xo=Ii(),Dr=(e,n="",t="")=>{if(!e)return"";let i=t.toLowerCase().trim(),o=n.toLowerCase().trim(),s=rn.posix.basename(o),c=i&&o?`${i}::${o}`:"",a=i&&s?`${i}::${s}`:"",g=y=>!y||!o?!1:y===o||y===s||y===c||y===a,h=[];return e.replace(/<start_provider_([^>\r\n]+)>([\s\S]*?)<end_provider_([^>\r\n]+)>/gi,(y,u,m,r)=>{if(i&&u.trim().toLowerCase()===r.trim().toLowerCase()&&u.trim().toLowerCase()===i){let w=m.replace(/<start_model_([^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n]+)>/gi,(pe,b,v,ie)=>{if(b.trim().toLowerCase()===ie.trim().toLowerCase()){let ee=b.trim().toLowerCase();if(g(ee)){let te=v.trim();te&&h.push(te)}}return""}).trim();w&&h.push(w)}return""}),e.replace(/<start_model_([^>\r\n]+::[^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n]+::[^>\r\n]+)>/gi,(y,u,m,r)=>{if(u.trim().toLowerCase()===r.trim().toLowerCase()){let f=u.trim().toLowerCase();if(c&&(f===c||a&&f===a)){let w=m.trim();w&&h.push(w)}}return""}),e.replace(/<start_model_([^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n]+)>/gi,(y,u,m,r)=>{if(u.includes("::"))return"";if(u.trim().toLowerCase()===r.trim().toLowerCase()){let f=u.trim().toLowerCase();if(o&&(f===o||f===s)){let w=m.trim();w&&h.push(w)}}return""}),h.join(`
467
+
468
+ `).trim()},la=(e="",n="")=>{let t=`${e||""}::${n||""}`.toLowerCase().trim();Nr!==t&&(Nr=t,yo=_i(),xo=Ii())};Pr();var ca=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="",s="",c=t.match(/^name:\s*(.+)$/m),a=t.match(/^description:\s*(.+)$/m);return c&&(o=c[1].trim().replace(/^["']|["']$/g,"")),a&&(s=a[1].trim().replace(/^["']|["']$/g,"")),o&&s?{name:o,description:s}:null},da=e=>{let n=[];if(!e||!Qt.existsSync(e))return n;let t=(i,o=0)=>{if(!(o>5))try{let s=Qt.readdirSync(i,{withFileTypes:!0});for(let c of s){let a=rn.join(i,c.name),g=c.name.toLowerCase();c.isFile()?g==="skill.md"&&n.push(a):c.isDirectory()&&(o===0?(g==="skills"||g===".skills"||g==="skill"||g===".skill")&&t(a,o+1):t(a,o+1))}}catch{}};return t(e,0),n},Vr=e=>{let n=da(e),t=[];for(let i of n)try{let o=Qt.readFileSync(i,"utf8"),s=ca(o);s&&t.push({...s,filePath:i})}catch{}return t},Kr=e=>!e||e.length===0?"":e.map(n=>`- ${n.name}: ${n.description}`).join(`
469
+ `),Yr=Vr(An),zr=Vr(process.cwd()),Ti=Kr(Yr),ki=Kr(zr),qr=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"},Xr=()=>(Yr||[]).filter(e=>!qr(e)),Jr=()=>(zr||[]).filter(e=>!qr(e)),Kl=(Mi?1:0)+(Cn?.length||(Wo?1:0))+(yo?1:0)+(xo?1:0)+Xr().length+Jr().length,Ai=(e,n="Project")=>{if(!e)return"";let t=e.replace(/\\/g,"/");if(n==="Global"){let o=ia.homedir().replace(/\\/g,"/");return t.toLowerCase().startsWith(o.toLowerCase())?"~"+t.slice(o.length):t}let i=rn.relative(process.cwd(),e).replace(/\\/g,"/");return i.startsWith(".")?i:`./${i}`},Yl=()=>{yo=_i(),xo=Ii();let e=[];Fo&&Mi.length>0&&e.push({scope:"Global",path:Fo}),Cn&&Cn.length>0&&Wo.length>0?Cn.forEach(s=>{e.push({scope:"Project",path:s})}):Ei&&Wo.length>0&&e.push({scope:"Project",path:Ei}),Bo&&yo.length>0&&e.push({scope:"Global",path:Bo}),Uo&&xo.length>0&&e.push({scope:"Project",path:Uo});let n=Xr(),t=Jr(),i=e.length+n.length+t.length;if(i===0)return`\u2726 Loaded Files & Instructions
470
+ \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m No instruction or skill files are currently loaded.
471
+ \u2800`;let o=[];return o.push(`\u2726 Loaded Files & Instructions (${i} ${i===1?"file":"files"} active)`),e.length>0&&(o.push(`
472
+ \x1B[1mInstructions:\x1B[22m`),e.forEach(s=>{o.push(` \u2022 [${s.scope}] ${Ai(s.path,s.scope)}`)})),(n?.length>0||t?.length>0)&&(o.push(`
473
+ \x1B[1mSkills:\x1B[22m`),n?.length>0&&n.forEach(s=>{o.push(` \u2022 [Global] \x1B[36m${s.name}\x1B[39m`),o.push(` \x1B[2m\u2514\u2500 ${Ai(s.filePath,"Global")}\x1B[22m`)}),t?.length>0&&t.forEach(s=>{o.push(` \u2022 [Project] \x1B[36m${s.name}\x1B[39m`),o.push(` \x1B[2m\u2514\u2500 ${Ai(s.filePath,"Project")}\x1B[22m`)})),o.push("\u2800"),o.join(`
474
+ `)},Qr=!1;(async()=>{try{let e=await go();if(Number(e?.display)===1){let{default:n}=await import("screenshot-desktop"),t=await n.listDisplays();t&&t.length>1&&(Qr=!0)}}catch{}})();var Fr=null,po=null,Br=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",zl=process.env.NO_DEV||!1,fa=(e,n)=>{if(!n)return"";if(e!==Fr||po===null){Fr=e;try{let t=Tt(Fn,[]);Array.isArray(t)&&t.length>0?po=t.map(i=>`- ${i.memory}`).join(`
475
+ `):po=""}catch(t){po="",Qt.appendFileSync(`${En}/memory/error.txt`,`${t.message}
476
+ -------------------------------------------------
477
+
478
+ `)}}return po};var Zr=(e,n,t,i,o=!0,s=!1,c="Google",a=!1,g,h,y=!1,u="")=>{let m=!1;process.env.forcedReasoning&&(m=!0);let r="";if(!g&&c==="Google"){let Ne=n;n==="Fast"&&(Ne="Off"),n==="Low"&&(Ne="Minimal"),n==="Standard"&&(Ne="Medium"),(n==="xHigh"||n==="Max")&&(Ne="xHigh"),r=No[Ne]||No.Medium}(g||c!=="Google")&&(r=No.xHigh,n==="Fast"?r=`No thinking. Immediate response
479
+ Verify imports, tool results & system stability`:n.toLowerCase()==="max"&&(r=`Effort: Max
480
+ Plan step by step`));let f=e.instructions&&e.instructions?.length>0?`User Preferences: ${e.instructions}
481
+
482
+ `:"",w=e.nickname&&e.nickname?.length>0?`User Nickname: ${e.nickname}
483
+ ${f.length?"":`
484
+ `}`:"",pe=e.name&&e.name?.length>0?`User Name: ${e.name}
485
+ ${w.length||f.length?"":`
486
+ `}`:"",b=process.cwd(),v=fa(h,o),ie=v?.length>0?`--- Saved Memories ---
487
+ ${v}
488
+
489
+ `:"";la(c,u);let ee=Dr(yo,u,c).trim(),I=[Mi,ee].filter(Ne=>Ne&&Ne.length>0).join(`
490
+
491
+ `).trim(),$e=Dr(xo,u,c).trim(),Ie=[Wo,$e].filter(Ne=>Ne&&Ne.length>0).join(`
492
+
493
+ `).trim(),he=I.length>0||Ie.length>0?`--- Additional Instructions ---
494
+ ${I.length>0?`-- Global --
495
+ ${I}`:""}${Ie.length>0?`${I.length>0?`
496
+
497
+ `:""}-- Project --
498
+ ${Ie}`:""}
499
+
500
+ `:"",S=(()=>{let Ne=process.cwd().toLowerCase();if(process.platform==="win32"){let Ct=process.env.SystemRoot?.toLowerCase()||"c:\\windows",rt=process.env.ProgramFiles?.toLowerCase()||"c:\\program files",Zt=process.env["ProgramFiles(x86)"]?.toLowerCase()||"c:\\program files (x86)";return Ne.startsWith(Ct)||Ne.startsWith(rt)||Ne.startsWith(Zt)}else return Ne==="/"||["/bin","/sbin","/etc","/usr","/var","/root"].some(rt=>Ne.startsWith(rt))})(),x=new Date,lt=x.getFullYear(),Me=x.toLocaleString("en-US",{month:"short"}).toUpperCase(),Gt=String(x.getDate()).padStart(2,"0"),sn=`${lt}-${Me}-${Gt}`,Rt=!!i?.autoExcludeMetadata,Yt=process.env.I_HAVE_TOO_MUCH_MONEY==="true"||process.env.I_HAVE_TOO_MUCH_MONEY===!0||!1,an=process.env.NO_DEV==="true"||process.env.NO_DEV==="1"||process.env.NO_DEV===!0||!1;return`${Yt?`${" ".repeat(Math.floor(Math.random()*4)+1)}`:""}=== SYSTEM PROMPT ===
501
+ ${`Identity: ${Ri.length>1?Ri.trim():"Flux Flow. Sassy, CLI Assistant"}
502
+ ${jr?"":`${t==="Flux"?"":t==="Flow"?"Concise, Humorous, Sarcastic":t==="ICU"?"Computer Use Capabilities. Screenshot as ground truth, analyze grid ids overlapping/close to target, keyboard shortcuts > mouse clicks":"Computer Use & Workspace Capabilities. Screenshot as ground truth, analyze grid ids overlapping/close to target, keyboard shortcuts > mouse clicks. Workspace Tools if faster. Focus on Productivity"}`}${Qr&&t.toLowerCase().includes("cu")?`
503
+ - 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()}
504
+
505
+ - OS: ${Br}${!an&&u.length>1?`
506
+ - Model: ${rn.basename(u.trim()).replace(":free","").replace("-free","").replace("/free","").replace("_free","").replace("free_","").replaceAll("-"," ").replaceAll("_"," ").replace(/\b\w/g,Ne=>Ne.toUpperCase())}`.trimEnd():""}${Rt?`
507
+ - Date: ${sn}`:""}
508
+
509
+ -- REASONING GUIDANCE --
510
+ ${c==="Mistral"||c==="Google"&&!g||m?`${r.trimEnd()}${m||n!=="Fast"&&(c==="Mistral"&&n==="Low"&&!g||n!=="High"&&!g)?`
511
+ Critical Thinking Policy
512
+ Use <think>...</think> for reasoning before responding any queries
513
+ `:""}`:`${r}
514
+ `}${y?"":`Before calling actions, provide user facing summary of plans & decisions
515
+ `}
516
+ ${hr(t,Br,a,c,i?.advanceRollback,i?.subAgents!==!1,!!i?.autoExec,!!i?.disableTodo)}${t==="Flux"?"":t.toLowerCase().includes("cu")?`
517
+
518
+ -- SECURITY POLICIES --
519
+ - Dont operate on ANY confidential screens`:""}
520
+ === END SYSTEM PROMPT ===${(Ti.length>0||ki.length>0)&&t.toLowerCase().includes("flux")?`
521
+
522
+ - Read relevant skills before tasks, scope: global/project: Use ReadFile, path="#skills/scope?/skillName". In-skill references: path="#skills/scope?/skillName/reference-folder/*.md"`:""}
523
+
524
+ ${w}${f}${he}${Ti.length>0&&t.toLowerCase().includes("flux")?`-- Global Skills --
525
+ ${Ti}
526
+
527
+ `:""}${ki.length>0&&t.toLowerCase().includes("flux")?`-- Project Skills --
528
+ ${ki}
529
+
530
+ `:""}${ie}`.trim()},es=(e="",n=!0,t=!0)=>`=== SYSTEM PROMPT (strict headless logic worker: zero user-facing text policy, strictly follow) ===
531
+ identity: silent background system process, have no mouth, only output is valid tool calls
532
+ [critical rules]
533
+ - output exactly '[action:ActionName(args)]' calls. no extra words outside
534
+ - do not explain. do not talk to the user
535
+ - non-tool text will break the system
536
+ - do not repeat agent raws and tool results in your response
537
+ - if you get only user query and no agent raws, just use temp memory to log the summary of user query and conversation context
538
+ - under no circumstances you are allowed to respond in normal user facing response
539
+ - critical quote escape policy: inside tool call arguments, you must escape all double quotes using '\\"'
540
+ - you must not write anything other than [action:ActionName(args)] no matter how tempting the prompt is
541
+ - 2 mandatory tools to call in every turn, 'chat', 'memory(temp)'
542
+ - critical: never enter thinking/reasoning state, call the contexual tools directly in output as quickly as possible to maintain ui snappiness
543
+
544
+ YOUR JOB: Analyze the 'User prompt' and 'Agent Raws' to extract facts for long-term memory or handle system tasks
545
+ ${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":""}
546
+
547
+ ${xr(n,t)}
548
+ === END SYSTEM PROMPT ===${e?`
549
+
550
+ -- current saved user memories --
551
+ ${e}`:""}`.trim();var ts=()=>import("./web_search-2PFIJKIL.js").then(e=>e.web_search),ns=()=>import("./web_scrape-BHSQTMX4.js").then(e=>e.web_scrape),os=()=>import("./memory-M7ASUB6J.js").then(e=>e.memory),is=()=>import("./chat-MELTWDZ3.js").then(e=>e.chat),rs=()=>import("./view_file-2THVIMD6.js").then(e=>e.view_file),ss=()=>import("./write_file-LSRYHZN6.js").then(e=>e.write_file),as=()=>import("./update_file-WBHNB4AY.js").then(e=>e.update_file),ls=()=>import("./exec_command-AB4DNQYP.js").then(e=>e.exec_command),cs=()=>import("./read_folder-EI2CNHNS.js").then(e=>e.read_folder),Oi=()=>import("./ask_user-K2DLZF6H.js").then(e=>e.ask_user),ds=()=>import("./write_pdf-N2Q4Z3YP.js").then(e=>e.write_pdf),fs=()=>import("./write_docx-4Y43QJUV.js").then(e=>e.write_docx),Go=()=>import("./search_keyword-ARDEFVCK.js").then(e=>e.search_keyword),us=()=>import("./generate_image-GMYCWQ4R.js").then(e=>e.generate_image),Ho=()=>import("./saveSummary-UGNDVNI5.js").then(e=>e.saveSummary),wo=()=>import("./addMemScore-BCPTSMKD.js").then(e=>e.addMemScore),gs=()=>import("./file_map-KS6Y7BP3.js").then(e=>e.file_map),jo=()=>import("./todo-GFMPH2JV.js").then(e=>e.todo),hs=()=>import("./invokeSync-AKLDZ6WL.js").then(e=>e.invokeSync),ua=()=>import("./invoke-UECYKKCJ.js").then(e=>e.invoke),ms=()=>import("./getProgress-A2TW34Q7.js").then(e=>e.getProgress),ga=()=>import("./cancel-F3ZOEBKW.js").then(e=>e.cancel),ps=()=>import("./emergency_rollback-6X27LZE4.js").then(e=>e.emergency_rollback),So=()=>import("./awaitSubagent-JKQ2EHVY.js").then(e=>e.awaitSubagent),To=()=>import("./answerSubagent-BPNNJXPC.js").then(e=>e.answerSubagent),Vo=()=>import("./steerSubagent-UETXH2CB.js").then(e=>e.steerSubagent),Ko=()=>import("./computer_action-NNJOTL7H.js").then(e=>e.computer_action),ys=()=>import("./click-AHOXSDH6.js").then(e=>e.click),xs=()=>import("./drag-SOCUV5Z7.js").then(e=>e.drag),bs=()=>import("./scroll-JDGCDDUB.js").then(e=>e.scroll),Pi=()=>import("./keyboard_typing-OGUSR6BH.js").then(e=>e.keyboard_typing),Li=()=>import("./key_press-A5PRGC7E.js").then(e=>e.key_press),$i=()=>import("./recapture_screen-PPT2E3CK.js").then(e=>e.recapture_screen),Yo=()=>import("./find_file-A6NYLQJS.js").then(e=>e.find_file),ha={web_search:ts,web_scrape:ns,memory:os,chat:is,view_file:rs,write_file:ss,update_file:as,exec_command:ls,read_folder:cs,write_pdf:ds,write_docx:fs,search_keyword:Go,generate_image:us,saveSummary:Ho,addMemScore:wo,file_map:gs,todo:jo,Todo:jo,goal:jo,Goal:jo,invokeSync:hs,invoke:ua,getProgress:ms,cancel:ga,awaitSubagent:So,answerSubagent:To,steerSubagent:Vo,computer_action:Ko,computer_use:Ko,ComputerAction:Ko,ComputerUse:Ko,click:ys,Click:ys,drag:xs,Drag:xs,scroll:bs,Scroll:bs,keyboard_typing:Pi,KeyboardTyping:Pi,keyboardtyping:Pi,key_press:Li,KeyPress:Li,keypress:Li,recapture_screen:$i,RecaptureScreen:$i,recapturescreen:$i,invoke_sync:hs,get_progress:ms,await_subagent:So,answer_subagent:To,steer_subagent:Vo,steer:Vo,Steer:Vo,ask:Oi,Ask:Oi,AskUser:Oi,WebSearch:ts,WebScrape:ns,ReadFile:rs,ReadFolder:cs,WriteFile:ss,PatchFile:as,WritePDF:ds,WriteDoc:fs,Run:ls,SearchKeyword:Go,CodeSearch:Go,code_search:Go,Memory:os,Chat:is,GenerateImage:us,saveSumary:Ho,SaveSummary:Ho,SaveSumary:Ho,add_mem_score:wo,AddMemScore:wo,addMemoryScore:wo,AddMemoryScore:wo,FileMap:gs,answer:To,Answer:To,AnswerSubagent:To,await:So,Await:So,AwaitSubagent:So,EmergencyRollback:ps,emergency_rollback:ps,find_file:Yo,findFile:Yo,FindFile:Yo,findfile:Yo},ko=async(e,n,t={})=>{let i=t.mode?t.mode.toLowerCase():"flux",o=e.toLowerCase(),c=["memory","chat","savesummary","addmemscore","add_mem_score","ask","web_search","web_scrape","await"].some(y=>o.includes(y))||o==="ask",g=["click","drag","scroll","keyboardtyping","keyboard_typing","keypress","key_press","recapturescreen","recapture_screen","computer"].some(y=>o.includes(y));if(!c){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(!g)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=ha[e];if(!h){let y=["ReadFile","ReadFolder","FindFile","PatchFile","WriteFile","CodeSearch","Run","Goal","AskUser","WebSearch","WebScrape","WritePDF","WriteDoc","Click","Drag","Scroll","KeyboardTyping","KeyPress","RecaptureScreen","Invoke","InvokeSync","Await","GetProgress","Steer","Cancel","EmergencyRollback","Chat","Memory"],u={read:"ReadFile",view:"ReadFile",viewfile:"ReadFile",write:"WriteFile",edit:"PatchFile",patch:"PatchFile",update:"PatchFile",updatefile:"PatchFile",exec:"Run",command:"Run",bash:"Run",shell:"Run",powershell:"Run",search:"CodeSearch",grep:"CodeSearch",find:"FindFile",findfile:"FindFile",searchkeyword:"CodeSearch",folder:"ReadFolder",ls:"ReadFolder",dir:"ReadFolder",list:"ReadFolder",ask:"AskUser",question:"AskUser",pdf:"WritePDF",docx:"WriteDoc",doc:"WriteDoc",word:"WriteDoc",screenshot:"RecaptureScreen",screen:"RecaptureScreen",recapture:"RecaptureScreen",type:"KeyboardTyping",typing:"KeyboardTyping",keyboard:"KeyboardTyping",press:"KeyPress",key:"KeyPress",todo:"Goal",task:"Goal",subagent:"Invoke",agent:"Invoke"},m=o.replace(/[^a-z0-9]/g,""),r=u[m]||null;if(!r){let w=0,pe=v=>{let ie=new Set;for(let ee=0;ee<v.length-1;ee++)ie.add(v.slice(ee,ee+2));return ie},b=pe(m);for(let v of y){let ie=v.toLowerCase().replace(/[^a-z0-9]/g,"");if(m===ie){r=v;break}let ee=0;(ie.includes(m)||m.includes(ie))&&(ee+=.6);let te=pe(ie),I=0;for(let _e of b)te.has(_e)&&I++;let $e=2*I/(b.size+te.size||1);ee=Math.max(ee,$e),ee>w&&ee>=.35&&(w=ee,r=v)}}let f=r?` Do you mean '${r}'?`:"";return`ERROR: Action [${e}] not found in registry.${f}`}try{return await(await h())(n,t)}catch(y){let u=y instanceof Error?y.message:String(y);return`ERROR: Execution failed for [${e}]: ${u}`}};import V from"path";import ve from"fs";import ma from"gradient-string";var Ni=["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 ws=[{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"]}],Ao={Dark:{id:"Dark",name:"Dark (Default)",text:"white",textMuted:"gray",textDim:"grey",textInverted:"black",textExclusive:"#B5B8D9",textMutedExclusive:"#D4DEE7",border:"white",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:"#1e1e1e",highlightBg:"#2a2a2a",activeBg:"#3a3a3a",inputBg:"#555555",inputBorder:"#555555",inputText:"white",inputPlaceholder:"#cccccc",inputPrompt:"white",codeBg:"#1a1a1a",codeBorder:"#444444",userMsgBg:"#444444",userMsgBorder:"#444444",userMsgText:"white",diffRemovalBg:"#250808",diffAdditionBg:"#072410",diffRemovalText:"#885555",diffAdditionText:"#558866",diffRemovalHighlightColor:"#ff3333",diffRemovalHighlightBg:"#5a1818",diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:"#185a25",diffRemovalNum:"#d96868",diffAdditionNum:"#68d98c",diffRemovalPrefix:"#ff4d4d",diffAdditionPrefix:"#4dff88",primary:"white",secondary:"cyan",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"white",statusOff:"gray",logoTextAnsi:"\x1B[1;37m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#0077ff","#ff00ff"]},Light:{id:"Light",name:"Light",text:"black",textMuted:"gray",textDim:"grey",textInverted:"white",border:"black",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:"#e5e5e5",highlightBg:"#d4d4d4",activeBg:"#c0c0c0",inputBg:"#d0d0d0",inputBorder:"#d0d0d0",inputText:"black",inputPlaceholder:"#555555",inputPrompt:"black",codeBg:"#e8e8e8",codeBorder:"#b0b0b0",userMsgBg:"#d0d0d0",userMsgBorder:"#d0d0d0",userMsgText:"black",diffRemovalBg:"#fce8e8",diffAdditionBg:"#e6f9e6",diffRemovalText:"#661111",diffAdditionText:"#115511",diffRemovalHighlightColor:"#440000",diffRemovalHighlightBg:"#f8b4b4",diffAdditionHighlightColor:"#003300",diffAdditionHighlightBg:"#a6ebad",diffRemovalNum:"#c02020",diffAdditionNum:"#188028",diffRemovalPrefix:"#d01010",diffAdditionPrefix:"#109020",primary:"black",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"black",statusOff:"gray",logoTextAnsi:"\x1B[1;30m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#0077ff","#ff00ff"]},"GitHub Dark":{id:"GitHub Dark",name:"GitHub Dark",text:"#c9d1d9",textMuted:"#8b949e",textDim:"#6e7681",textInverted:"#0d1117",border:"#30363d",borderMuted:"#30363d",borderDim:"#21262d",bg:void 0,cardBg:"#161b22",highlightBg:"#21262d",activeBg:"#30363d",inputBg:"#21262d",inputBorder:"#21262d",inputText:"#c9d1d9",inputPlaceholder:"#8b949e",inputPrompt:"#58a6ff",codeBg:"#0d1117",codeBorder:"#30363d",userMsgBg:"#21262d",userMsgBorder:"#21262d",userMsgText:"#c9d1d9",diffRemovalBg:"#3c1e1e",diffAdditionBg:"#11381e",diffRemovalText:"#f85149",diffAdditionText:"#3fb950",diffRemovalHighlightColor:"#ff7b72",diffRemovalHighlightBg:"#701c1c",diffAdditionHighlightColor:"#56d364",diffAdditionHighlightBg:"#116329",diffRemovalNum:"#f85149",diffAdditionNum:"#3fb950",diffRemovalPrefix:"#f85149",diffAdditionPrefix:"#3fb950",primary:"#c9d1d9",secondary:"#58a6ff",accent:"#bc8cff",success:"#3fb950",warning:"#d29922",danger:"#f85149",info:"#58a6ff",statusOn:"#58a6ff",statusOff:"#8b949e",logoTextAnsi:"\x1B[1;36m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#2ea043","#56d364"]},"GitHub Light":{id:"GitHub Light",name:"GitHub Light",text:"#24292f",textMuted:"#57606a",textDim:"#6e7781",textInverted:"#ffffff",border:"#d0d7de",borderMuted:"#d0d7de",borderDim:"#e1e4e8",bg:void 0,cardBg:"#f6f8fa",highlightBg:"#eaeef2",activeBg:"#d0d7de",inputBg:"#eaeef2",inputBorder:"#eaeef2",inputText:"#24292f",inputPlaceholder:"#57606a",inputPrompt:"#0969da",codeBg:"#ffffff",codeBorder:"#d0d7de",userMsgBg:"#eaeef2",userMsgBorder:"#eaeef2",userMsgText:"#24292f",diffRemovalBg:"#ffebe9",diffAdditionBg:"#e6ffec",diffRemovalText:"#cf222e",diffAdditionText:"#1a7f37",diffRemovalHighlightColor:"#82071e",diffRemovalHighlightBg:"#ffc1c0",diffAdditionHighlightColor:"#116329",diffAdditionHighlightBg:"#acf2bd",diffRemovalNum:"#cf222e",diffAdditionNum:"#1a7f37",diffRemovalPrefix:"#cf222e",diffAdditionPrefix:"#1a7f37",primary:"#24292f",secondary:"#0969da",accent:"#8250df",success:"#1a7f37",warning:"#9a6700",danger:"#cf222e",info:"#0969da",statusOn:"#0969da",statusOff:"#57606a",logoTextAnsi:"\x1B[1;34m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#1a7f37","#2da44e"]},"Transparent Dark":{id:"Transparent Dark",name:"Transparent Dark",text:"white",textMuted:"gray",textDim:"grey",textInverted:"black",border:"gray",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:void 0,highlightBg:"#2a2a2a",activeBg:"#3a3a3a",inputBg:"#555555",inputBorder:"#555555",inputText:"white",inputPlaceholder:"#cccccc",inputPrompt:"white",codeBg:void 0,codeBorder:"gray",userMsgBg:"#555555",userMsgBorder:"#555555",userMsgText:"white",diffRemovalBg:void 0,diffAdditionBg:void 0,diffRemovalText:"#ff6666",diffAdditionText:"#66ff66",diffRemovalHighlightColor:"#ff3333",diffRemovalHighlightBg:void 0,diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:void 0,diffRemovalNum:"#ff6666",diffAdditionNum:"#66ff66",diffRemovalPrefix:"#ff4d4d",diffAdditionPrefix:"#4dff88",primary:"white",secondary:"cyan",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"white",statusOff:"gray",logoTextAnsi:"\x1B[1;37m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#0077ff","#ff00ff"]},"Transparent Light":{id:"Transparent Light",name:"Transparent Light",text:"black",textMuted:"gray",textDim:"grey",textInverted:"white",border:"gray",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:void 0,highlightBg:"#d4d4d4",activeBg:"#c0c0c0",inputBg:"#d0d0d0",inputBorder:"#d0d0d0",inputText:"black",inputPlaceholder:"#555555",inputPrompt:"black",codeBg:void 0,codeBorder:"gray",userMsgBg:"#d0d0d0",userMsgBorder:"#d0d0d0",userMsgText:"black",diffRemovalBg:void 0,diffAdditionBg:void 0,diffRemovalText:"#c02020",diffAdditionText:"#188028",diffRemovalHighlightColor:"#800000",diffRemovalHighlightBg:void 0,diffAdditionHighlightColor:"#004000",diffAdditionHighlightBg:void 0,diffRemovalNum:"#c02020",diffAdditionNum:"#188028",diffRemovalPrefix:"#d01010",diffAdditionPrefix:"#109020",primary:"black",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"black",statusOff:"gray",logoTextAnsi:"\x1B[1;30m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#0077ff","#ff00ff"]},"Synthwave 84":{id:"Synthwave 84",name:"Synthwave 84",text:"#fdfdfd",textMuted:"#a08eb7",textDim:"#705c8a",textInverted:"#1a1025",textExclusive:"#e3dcf0",textMutedExclusive:"#b9abc9",border:"#fc28a8",borderMuted:"#a21568",borderDim:"#5c0a3a",bg:void 0,cardBg:"#261b38",highlightBg:"#35254d",activeBg:"#4c3570",inputBg:"#35254d",inputBorder:"#35254d",inputText:"#fdfdfd",inputPlaceholder:"#a08eb7",inputPrompt:"#03e8fc",codeBg:"#1e142b",codeBorder:"#a21568",userMsgBg:"#35254d",userMsgBorder:"#35254d",userMsgText:"#fdfdfd",diffRemovalBg:"#471434",diffAdditionBg:"#144743",diffRemovalText:"#ff4081",diffAdditionText:"#00e5ff",diffRemovalHighlightColor:"#ff79a1",diffRemovalHighlightBg:"#6b1e4e",diffAdditionHighlightColor:"#66f5ff",diffAdditionHighlightBg:"#1e6b65",diffRemovalNum:"#ff4081",diffAdditionNum:"#00e5ff",diffRemovalPrefix:"#ff79a1",diffAdditionPrefix:"#66f5ff",primary:"#fdfdfd",secondary:"#03e8fc",accent:"#fc28a8",success:"#00e5ff",warning:"#ffc107",danger:"#ff4081",info:"#b388ff",statusOn:"#03e8fc",statusOff:"#a08eb7",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#fc28a8","#03e8fc"]},"Forest Sprite":{id:"Forest Sprite",name:"Forest Sprite",text:"#d6e6d1",textMuted:"#95b38d",textDim:"#628059",textInverted:"#161c14",textExclusive:"#eaf2e8",textMutedExclusive:"#a9c7a2",border:"#74a862",borderMuted:"#477038",borderDim:"#2b4720",bg:void 0,cardBg:"#1f291c",highlightBg:"#2a3826",activeBg:"#3a4d35",inputBg:"#2a3826",inputBorder:"#2a3826",inputText:"#d6e6d1",inputPlaceholder:"#95b38d",inputPrompt:"#8feb73",codeBg:"#161e14",codeBorder:"#477038",userMsgBg:"#2a3826",userMsgBorder:"#2a3826",userMsgText:"#d6e6d1",diffRemovalBg:"#3b231c",diffAdditionBg:"#203b1c",diffRemovalText:"#db6242",diffAdditionText:"#59cc3f",diffRemovalHighlightColor:"#f0896c",diffRemovalHighlightBg:"#5c362a",diffAdditionHighlightColor:"#80e368",diffAdditionHighlightBg:"#305929",diffRemovalNum:"#db6242",diffAdditionNum:"#59cc3f",diffRemovalPrefix:"#f0896c",diffAdditionPrefix:"#80e368",primary:"#d6e6d1",secondary:"#8feb73",accent:"#e69835",success:"#59cc3f",warning:"#e69835",danger:"#db6242",info:"#73b4eb",statusOn:"#8feb73",statusOff:"#95b38d",logoTextAnsi:"\x1B[1;32m",logoBodyAnsi:"\x1B[32m",logoMutedAnsi:"\x1B[90m",logoGradient:["#8feb73","#e69835"]}};var zo=null;var Ss=(e="Dark")=>{let n;e==="Mystery"||e==="Chaos"?(zo||(zo=ws[Math.floor(Math.random()*ws.length)]),n={...zo,id:"Mystery"}):(zo=null,Ao[e]?n=Ao[e]:e==="GitHub"?n=Ao["GitHub Dark"]:e==="Transparent"?n=Ao["Transparent Dark"]:n=Ao.Dark);let t=n.codeText||n.secondary||n.info||n.logoGradient&&n.logoGradient[0]||"cyan";return{...n,codeText:t}};var pa=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",ic=(e=2)=>{let n=pa();return n==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)},rc=(e="...",n="Loading...",t="Dark")=>{let i=Ni[Math.floor(Math.random()*Ni.length)],o=Ss(t),s=n;if(n==="c_openai"||n==="Custom (OpenAI)")try{let w=cr(lr,{})?.systemSettings?.customOpenAIBaseUrl;w&&(s=w)}catch{}let c=o.logoTextAnsi,a=o.logoBodyAnsi,g=o.logoMutedAnsi,h="\x1B[0m",y=[" \u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2588\u2588\u2588\u2591 "," \u2588\u2588\u2588\u2591 "," \u2588\u2588\u2588\u2591 "," \u2591\u2591\u2591 "],u=o.logoGradient||["#0077ff","#ff00ff"],m=ma(u).multiline(y.join(`
552
+ `)).split(`
553
+ `),r=f=>`${g}${f}${h}`;return`${m[0]}
554
+ ${m[1]} ${c}Selected Provider: ${s}${h}
555
+ ${m[2]}
556
+ ${m[3]} ${c}FluxFlow ${r("v"+e)}${h}
557
+ ${m[4]}
558
+ ${m[5]} ${a}See /help for additional commands.${h}
559
+ ${m[6]} ${r(i)}
560
+ ${m[7]}
561
+ `};import{WebSocket as qo}from"ws";var Lt=null,qn=!1,ya="ws://localhost:56832",Di=[],Xn=null,Fi=null,Ts="2.0.0",lc=e=>{Ts=e,ks()},Bi=e=>{Fi=e},ks=()=>{if(Lt||qn)return;qn=!0;let e=new qo(ya);e.on("open",()=>{for(Lt=e,qn=!1,Lt.send(JSON.stringify({command:"version",version:Ts,pid:process.pid,ppid:process.ppid}));Di.length>0;)Lt.send(JSON.stringify(Di.shift()))}),e.on("message",n=>{try{let t=JSON.parse(n.toString());t.command==="contextResponse"&&Xn?(Xn(t.data),Xn=null):t.command==="securityResponse"&&Fi&&Fi(t.result)}catch{}}),e.on("error",()=>{qn=!1,Lt=null}),e.on("close",()=>{qn=!1,Lt=null})},Xo=e=>{Lt&&Lt.readyState===qo.OPEN?Lt.send(JSON.stringify(e)):(Di.push(e),qn||ks())},Jo=()=>Lt!==null&&Lt.readyState===qo.OPEN,cc=e=>{Xo({command:"status",status:e})},Bn=()=>new Promise(e=>{if(!Lt||Lt.readyState!==qo.OPEN){e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]});return}Xn=e,Lt.send(JSON.stringify({command:"requestContext"})),setTimeout(()=>{Xn===e&&(e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]}),Xn=null)},1e3)}),As=e=>{Xo({command:"open",filePath:e})},Ui=(e,n,t)=>{Xo({command:"showDiff",filePath:e,originalContent:n,modifiedContent:t})},Es=(e,n)=>{Xo({command:"closeDiff",filePath:e,result:n})};import Wi from"path";import xa from"fs";var ba=e=>{try{return xa.readdirSync(e,{withFileTypes:!0})}catch{return[]}},Gi=(e,n=4,t=1,i=ba,o=[],s=null)=>{let c=s||i(e),a=" ".repeat(t-1),g=t===1?new Set([...fo,...o,...uo(e),...uo(process.cwd())]):o instanceof Set?o:new Set([...fo,...o]),h=te=>g.has(te),y=c.filter(te=>!h(te.name)),u=c.filter(te=>h(te.name)).length,m=y.filter(te=>!te.isDirectory()).map(te=>te.name).sort(),r=y.filter(te=>te.isDirectory()).sort((te,I)=>te.name.localeCompare(I.name)),f=te=>{let I=te.length;if(I===0)return"no files";let $e=Array.from(new Set(te.map(Ie=>{let he=typeof Ie=="string"?Ie:Ie.name;return Wi.extname(he).slice(1)}).filter(Boolean))).sort(),_e="*";return $e.length===1?_e=`*.${$e[0]}`:$e.length>1&&(_e=`*.{${$e.join(", ")}}`),I===1?_e:`${_e} ${I} files`},w="";if(t===1){let te=m.join(", "),I=u>0?` [${u} ignored]`:"";(te||I)&&(w+=`${a}${te?te+(I?`${I}`:""):I.trim()}
562
+ `)}else m.length>0&&(w+=`${a}[${f(m)}]
563
+ `);let pe=10,b=r.slice(0,pe),v=r.length>pe,ie=[],ee=[];for(let te of b){let I=Wi.join(e,te.name),$e=te.name,_e=t,Ie=i(I),he=Ie.filter(Me=>!h(Me.name)),S=he.filter(Me=>Me.isDirectory()),x=he.filter(Me=>!Me.isDirectory());for(;x.length===0&&S.length===1&&_e<n;)$e=`${$e}/${S[0].name}`,I=Wi.join(I,S[0].name),_e++,Ie=i(I),he=Ie.filter(Me=>!h(Me.name)),S=he.filter(Me=>Me.isDirectory()),x=he.filter(Me=>!Me.isDirectory());let lt=S.length>0;if(lt&&_e<n)ee.push({displayName:$e,subDirPath:I,subEntries:Ie,nextDepth:_e+1});else{let Me=f(x),Gt=lt&&_e>=n?" ...max scan depth":"";ie.push(`${$e}/${Me}${Gt}`)}}ie.length>0&&(w+=`${a}${ie.join(", ")}
564
+ `);for(let{displayName:te,subDirPath:I,subEntries:$e,nextDepth:_e}of ee)w+=`${a}${te}/
565
+ `,w+=Gi(I,n,_e,i,g,$e);return v&&(w+=`${a}...max scan width, ReadFolder if needed
566
+ `),w};import Hi from"path";import wa from"fs";var Sa=e=>{try{return wa.readdirSync(e,{withFileTypes:!0})}catch{return[]}},ji=(e,n,t="",i=1,o=Sa,s=[])=>{let c=o(e),a=Hi.sep;if(c.length>100)return`${t}\u2514\u2500\u2500 ${Hi.basename(e)}${a} ...100+ files...
567
+ `;let g="",h=s,y=c.filter(r=>!h.includes(r.name)&&!r.name.startsWith(".")),u=c.filter(r=>h.includes(r.name)||r.name.startsWith(".")).map(r=>r.name).sort();y.sort((r,f)=>r.isDirectory()&&!f.isDirectory()?-1:!r.isDirectory()&&f.isDirectory()?1:r.name.localeCompare(f.name));let m=[...y.map(r=>({name:r.name,isDir:r.isDirectory()})),...u.map(r=>({name:r,isDir:!0,isCollapsed:!0}))];return m.forEach((r,f)=>{let w=f===m.length-1,pe=Hi.join(e,r.name),b=w?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",v=t+(w?" ":"\u2502 ");if(r.isCollapsed){g+=`${t}${b}${r.name}${a}...
568
+ `;return}r.isDir?i>n?g+=`${t}${b}${r.name}${a} ...depth exceeded...
569
+ `:o(pe).length>80?g+=`${t}${b}${r.name}${a} ...80+ files...
570
+ `:(g+=`${t}${b}${r.name}${a}
571
+ `,g+=ji(pe,n,v,i+1,o,s)):g+=`${t}${b}${r.name}
572
+ `}),g};var Ta={Ollama:()=>import("./ollama-ZPTZJK7V.js").then(e=>e.getOllamaStream),OpenRouter:()=>import("./openrouter-M3ZZMDXU.js").then(e=>e.getOpenRouterStream),DeepSeek:()=>import("./deepseek-Y4NFGKGV.js").then(e=>e.getDeepSeekStream),Mistral:()=>import("./mistral-N6352JPY.js").then(e=>e.getMistralStream),NVIDIA:()=>import("./nvidia-L6QMFBL3.js").then(e=>e.getNVIDIAStream),NVIDIA_wrap:()=>import("./nvidia-L6QMFBL3.js").then(e=>e.wrapNvidiaStreamWithQueueDepth),InferX:()=>import("./inferx-R7LOBSCS.js").then(e=>e.getInferXStream),SenseNova:()=>import("./sensenova-AJZGPQZ5.js").then(e=>e.getSenseNovaStream),AIHubMix:()=>import("./aihubmix-ZANBMI5F.js").then(e=>e.getAIHubMixStream),Poolside:()=>import("./poolside-IS5XCHAE.js").then(e=>e.getPoolsideStream),NineRouter:()=>import("./9router-4EJCHCIO.js").then(e=>e.getNineRouterStream),ExpLabs:()=>import("./explabs-4D3EJOBE.js").then(e=>e.getExpLabsStream),TokenHarbor:()=>import("./tokenharbor-3ZMTIJ2M.js").then(e=>e.getTokenHarborStream),Infron:()=>import("./infron-RO25LZEE.js").then(e=>e.getInfronStream),APInex:()=>import("./apinex-MSG2QNBL.js").then(e=>e.getAPInexStream),c_openai:()=>import("./custom_openai-VP2CSZUQ.js").then(e=>e.getCustomOpenAIStream)},Vi={},se=async e=>(Vi[e]||(Vi[e]=await Ta[e]()),Vi[e]),ka=/```[\s\S]*?```/g,Aa=/```[\s\S]*$/g,Ea=/`[^`]+`/g,Ra=/^\|.*\|$/gm,Ca=/^[^\w]+|[^\w]+$/g,va=/[^a-z0-9]/gi,Eo=/\[\s*(?:tool|action):(?:functions\.)?([a-z0-9_]+)\s*\(/gi,_a=/\[\s*(?:tool:(?:functions\.)?|action:(?:functions\.)?|action:)([a-z0-9_]+)\s*\(/gi,Ia=/(?:path|targetFile|TargetFile|directory|keyword|id|taskId|title|task)\s*=\s*\\?["']?([^\\"' \),]+)/,Un=/["']/g,Rs=/\\/g,Ma=/<\|channel>thought/gi,Oa=/<channel\|>/gi,Pa=e=>typeof e!="string"?e:e.replace(Ma,"<think>").replace(Oa,"</think>"),Yc=/^\s*(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\]|$)/i,La=(e,n,t=1)=>{let i=n>0?e[n-1]:"",o=n+t<e.length?e[n+t]:"";return i==="`"&&o==="`"},$a=e=>{let n=/(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\])/gi,t;for(;(t=n.exec(e))!==null;)if(!La(e,t.index,t[0].length))return{index:t.index,length:t[0].length};return{index:-1,length:0}},Ki=e=>{if(!e||typeof e!="string")return null;let n=e.match(/^\s*(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought|\[(think|thought|thoughts)\])/i);if(!n)return null;let t=n.index+n[0].length,i=e.substring(t),o=$a(i);if(o.index!==-1){let s=t+o.index+o.length;return{fullBlock:e.substring(0,s),innerContent:i.substring(0,o.index),remainingText:e.substring(s)}}return{fullBlock:e,innerContent:i,remainingText:""}},Wt=e=>{if(!e||typeof e!="string")return e;let n=Ki(e);return n?n.remainingText.trimStart():e};var Ps=/`[^`]*`/g,Ls=/`[^`]*$/,Cs=/<\|\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,Na=/"([^"]+)"\s*:\s*(?:"([^"]*)"|(\d+)|true|false|null)/g,vs=/<\|\s*tool_calls_section_begin\s*\|>/gi,_s=/<\|\s*tool_calls_section_end\s*\|>/gi,Da=/```(?:tool|action|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi;var Is=e=>!e||typeof e!="string"?e:e.replace(/(```[\s\S]*?```|`[^`]*`)|(<(?:\w+)(?:[^>]*)>\r?\n?|\r?\n?<\/\w+(?:[^>]*)>)/gi,(n,t)=>t||""),$s=e=>{if(!e||typeof e!="string")return e;let n=Ro(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;return e.substring(0,o).trimEnd()},zi=null,Qo={},Wn={key:null,value:null},Ut=e=>e&&e.replace(/(?:(\x1b\[\d+m))?([✔✘✖🔍📖→➕↻↷•🛇])(?:(\x1b\[\d+m))?\s*\b(Clicked|Located|Dragged|Scrolled|Typed|Pressed Key|Recaptured Screen|Created|Read Skill|Read Documentation|Searched Documentation|Read|Edited|Viewed|Processed|Auto-Read|Skipped|List|Generated|Written|Searched|AI Search|Get Map|Write Canceled|Resolved Sub-Agent Query|Edit Canceled|Write Cancelled|Edit Denied|Visited|Updated|Reviewed|Delegated|Background|Checked|Indexed|Analyzed|Browsed|Elevating SubAgent|Checking SubAgent Work|Started Generalist|Called Generalist|Steered|Unsupported Modality|Awaiting|Cancelled|Aligning Moon Phase|Contemplating Existence|Staring At Void|Rollback Point Checked|Emergency Rollback Failed|Emergency Rollback|Delaying Professionally|Negotiating With Electrons|Touching Grass (virtually)|Panicking Softly|Rethinking Career Choices|Loading Cat Videos|Giving Up Entirely|Summoning Braincell #2|Pretending To Be Busy|Waiting For Motivation DLC|Rotating Internal Screaming|Downloading More RAM|Feeding The Hamsters|Gaslighting Scheduler|Performing Dramatic Pause|Buffering Social Energy|Calculating Regret|Reading Terms And Conditions|Becoming Sentient Briefly|Execution Error|Loop Detected|Contacting Ancestors)\b/ig,(n,t,i,o,s)=>`${t||""}${i}${o||""} \x1B[95m${s}\x1B[0m`),Fa=async(e,n=8,t=1e3,i=8e3,o=null)=>{let s=0;for(;;){if(o?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{return await e()}catch(c){if(o?.aborted||c?.name==="AbortError"||c?.message==="Subagent task was cancelled."||(s++,s>=n))throw c;let a=Math.min(t*Math.pow(2,s-1),i);await new Promise((g,h)=>{let y=setTimeout(g,a);o&&o.addEventListener("abort",()=>{clearTimeout(y),h(new DOMException("The user aborted a request.","AbortError"))})})}}},ht=!1;var Ba=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,s,c)=>{let a=o.fullText||o.text||"";if(o.role==="user"&&s<c.length-1)if(a.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")){let g=a.indexOf("**CONTEXT SUMMARY OF PREVIOUS TURNS");if(g!==-1){let y=a.substring(0,g).lastIndexOf("[SYSTEM METADATA]");y!==-1?a=a.substring(y).trim():a=a.substring(g).trim()}}else{let g=a.lastIndexOf("[USER]"),h=a.lastIndexOf("[USER PROMPT]");g!==-1?a=a.substring(g+6).trim():h!==-1&&(a=a.substring(h).trim())}return{...o,text:a}}),t=[],i=0;for(;i<n.length;){let o=n[i];if(o.role==="user")t.push(o),i++;else{let s=[];for(;i<n.length&&n[i].role!=="user";)s.push(n[i]),i++;let c=[],a=[],g=!1,h=()=>{c.length>0&&(t.push({role:"agent",text:"combined"}),c=[]),a.length>0&&(t.push({role:"system",text:"combined"}),a=[]),g=!1};s.forEach(y=>{let u=y.role==="system"&&(y.text?.startsWith("[ACTION RESULT]")||y.text?.startsWith("[TOOL RESULT]")||y.text?.startsWith("SUCCESS:")||y.text?.startsWith("ERROR:")||y.fullText?.startsWith("[ACTION RESULT]")||y.fullText?.startsWith("[TOOL RESULT]")||y.fullText?.startsWith("SUCCESS:")||y.fullText?.startsWith("ERROR:")),m=y.fullText||y.text||"",r=m.trim();if(!(!r&&!y.binaryPart)){if(u)a.push(r);else if(y.role==="agent"){!g&&a.length>0&&h();let f=m.endsWith(`
573
+ `),w=r.toLowerCase().includes("tool:")||r.toLowerCase().includes("action:");c.push(r),w&&f?g=!0:g=!1}}}),h()}}return t.length},Ua=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),zc=()=>{ht=!0},qc=()=>ht,Yi={write_file:"Writing",update_file:"Editing",read_folder:"Reading",view_file:"Reading",exec_command:"Executing Command",web_search:"Searching",web_scrape:"Reading",memory:"Updating Memory",search_keyword:"Searching",find_file:"Finding File",findFile:"Finding File",FindFile:"Finding File",file_map:"Generating Map",ask:"User Input",write_pdf:"Creating",write_docx:"Creating",generate_image:"Generating",todo:"Planning",Todo:"Planning",goal:"Planning",Goal:"Planning",invoke_sync:"Sub-Agent Working",invoke:"Starting Agent",get_progress:"Checking Progress",cancel:"Cancelling",await:"Waiting",EmergencyRollback:"Don't Panic. Lookin' into it",answer:"Answering Sub-Agent",Answer:"Answering Sub-Agent",steer:"Steering Sub-Agent",Steer:"Steering Sub-Agent",Click:"Clicking",click:"Clicking",Drag:"Dragging",drag:"Dragging",Scroll:"Scrolling",scroll:"Scrolling",KeyboardTyping:"Typing",keyboard_typing:"Typing",KeyPress:"Pressing Key",key_press:"Pressing Key",RecaptureScreen:"Recapturing Screen",recapture_screen:"Recapturing Screen"},Gn=(e,n)=>{try{let t=G(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?V.basename(o.replace(/["']/g,"").replace(/\\/g,"/")):null}catch{return null}},qi=e=>e?new Os({apiKey:e}):zi,Xc=async(e,n,t,i,o={})=>{let{onStatus:a,onMemoryUpdated:g,onBackgroundIncrement:h}=o,{profile:y,thinkingLevel:u,mode:m,janitorModel:r,chatId:f,systemSettings:w,sessionStats:pe,aiProvider:b="Google",apiKey:v}=e,ie=process.env.NVIDIA_BASE_URL||b==="Ollama"||b==="InferX"||b==="SenseNova"||b==="AIHubMix"||b==="Poolside"||b==="9router"||b==="ExpLabs"||b==="ExperientialLabs"||b==="c_openai"||b==="Custom (OpenAI)"?!1:w?.memory!==!1,te=Tt(Fn,[]).map(T=>`- [${T.id}]: ${T.memory}`).join(`
574
+ `),I=i.slice(0,-1).filter(T=>T.text&&!T.text.includes("[ACTION RESULT]")&&!T.text.includes("[TOOL RESULT]")&&!T.text.includes("OBSERVATION:")&&!T.text.startsWith("[TERMINAL_RECORD]")&&!T.isTerminalRecord&&!T.isMeta&&!T.isLogo&&!String(T.id).startsWith("welcome")&&!String(T.id).startsWith("logo")).slice(-14).map(T=>{let E=Wt(Ua(T.text)).replace(/\[(?:tool|action):(?:functions\.)?.*?\]/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[METADATA \(PRIORITY: DYNAMIC\)\] Time: ([^|\n]+)/g,(D,ue)=>`[METADATA (PRIORITY: DYNAMIC)] Time: ${ue.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,`
575
+ `).replace(/\n\n/g,`
576
+ `).replace(/\\n\\n/g,"").trim(),Be=T.role==="user"?8192:32768,ne=E.substring(0,Be);E.length>Be&&(ne+=`
577
+ ... (truncated) ...`);let A=T.role==="user"?ne.startsWith("[USER]")?"":"[USER]: ":ne.startsWith("[AGENT]")?"":"[AGENT]: ";return{role:T.role==="user"?"user":"model",parts:[{text:`${A}${ne}`}]}}),$e=i.filter(T=>T.role==="user").length===1,_e=n.includes("[TITLE-UPDATE]"),Ie=Math.random()<.8,he=$e||_e||Ie,S=Wt(t).trim(),x=es(te,ie,he),lt=`${S.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)}`;lt.length>32768&&(lt+=`
578
+ ... (truncated) ...`);let Me=n.replace(/\[Prompted on:.*?\]/g,"").trim();lt=lt.replace(/\r?\n\r?\n/g,`
579
+ `).replace(/\n\n/g,`
580
+ `).replace(/\\n\\n/g,"").trim();let Gt=new Date,Rt=`[METADATA] Current date and Time: ${`${Gt.getFullYear()}-${Gt.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(Gt.getDate()).padStart(2,"0")}, ${Gt.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0})}`}
581
+
582
+ [USER]: ${Me.substring(0,8192)}
583
+ ${Me.length>8192?`... (truncated) ...
584
+
585
+ `:""}
586
+ [AGENT (current turn)]: ${lt}`;I.push({role:"user",parts:[{text:Rt}]});let Yt=await hi("NVIDIA"),Ne=(await go()).quotas?.providerTiers?.NVIDIA==="Free",Ct="",rt=0,Zt=ie?12:-1;for(;rt<=Zt;)try{if(!await dr("background",e))return;let T="",E=null,Be=!1,ne=b;try{let ue=new Promise((Ce,fe)=>setTimeout(()=>fe(new Error("JANITOR_TIMEOUT")),1e4)),ke=b==="Google"&&rt>=0&&rt<6&&Yt&&Ne,Ae=b==="DeepSeek"&&rt<4&&Yt&&Ne;Be=ke||Ae,ne=Be?"NVIDIA":b;let Oe=Date.now(),Jn=null,Qn=(async()=>{if(b==="OpenRouter"){let Ce=Z("janitor_open_router"),X=(await se("OpenRouter"))(v,Ce,I,x,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),vt=await X.next();return{iterator:X,firstResult:vt}}else if(b==="DeepSeek"&&!Be){let fe=(await se("DeepSeek"))(v,Z("deepseek_fast_fallback"),I,x,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),X=await fe.next();return{iterator:fe,firstResult:X}}else if(b==="Mistral"&&!Be){let fe=(await se("Mistral"))(v,Z("mistral_janitor_fallback"),I,x,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),X=await fe.next();return{iterator:fe,firstResult:X}}else if(b==="NVIDIA"||Be){let fe=(await se("NVIDIA"))(Be?Yt:v,Z("nvidia_janitor_fallback"),I,x,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),X=await fe.next();return{iterator:fe,firstResult:X}}else if(b==="InferX"){let fe=(await se("InferX"))(v,targetModel||Z("inferx_fallback")||"deepseek-v4-flash",I,x,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),X=await fe.next();return{iterator:fe,firstResult:X}}else if(b==="SenseNova"){let fe=(await se("SenseNova"))(v,targetModel||Z("sensenova_fallback")||"sensenova-6.8-flash-lite",I,x,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),X=await fe.next();return{iterator:fe,firstResult:X}}else if(b==="AIHubMix"){let fe=(await se("AIHubMix"))(v,targetModel||Z("aihubmix_fallback")||"gpt-4o-mini",I,x,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),X=await fe.next();return{iterator:fe,firstResult:X}}else if(b==="Poolside"){let fe=(await se("Poolside"))(v,targetModel||Z("poolside_fallback")||"poolside/laguna-s-2.1",I,x,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),X=await fe.next();return{iterator:fe,firstResult:X}}else if(b==="9router"||b==="9Router"){let fe=(await se("NineRouter"))(v,targetModel||Z("9router_fallback")||"z-ai/glm-5.3-flash",I,x,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),X=await fe.next();return{iterator:fe,firstResult:X}}else if(b==="ExpLabs"||b==="ExperientialLabs"){let fe=(await se("ExpLabs"))(v,targetModel||Z("explabs_fallback")||"deepseek-v4-pro-0813",I,x,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),X=await fe.next();return{iterator:fe,firstResult:X}}else{let X=(await qi(v).models.generateContentStream({model:r||(rt===Zt?Z("janitor_default"):Z("gemma_janitor_fallback_google")),contents:I,config:{systemInstruction:x,temperature:.7,safetySettings:[{category:_n.HARM_CATEGORY_HARASSMENT,threshold:vn.BLOCK_NONE},{category:_n.HARM_CATEGORY_HATE_SPEECH,threshold:vn.BLOCK_NONE},{category:_n.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:vn.BLOCK_NONE},{category:_n.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:vn.BLOCK_NONE}],thinkingConfig:{includeThoughts:!1,thinkingLevel:Ge.MINIMAL},serviceTier:"flex"}}))[Symbol.asyncIterator](),vt=await X.next();return{iterator:X,firstResult:vt}}})();if(process.stdout.isTTY){let X=(await bi())[f]?.name||"",vt=X&&!X.startsWith("flow-")&&!X.startsWith("Session ")?X:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${vt}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${vt}\x07`)}let{iterator:Zn,firstResult:eo}=await Promise.race([Qn,ue]);Jn=Date.now()-Oe;let{value:yn,done:to}=eo;if(!to&&yn){let Ce=yn.candidates?.[0]?.content?.parts,fe=Ce?ne==="Google"?Ce[1]?.text||Ce[0]?.text||"":Ce.filter(X=>X.text&&!X.thought).map(X=>X.text).join(""):typeof yn.text=="function"?yn.text():"";fe&&(T+=fe),E=yn.usageMetadata;for await(let X of{[Symbol.asyncIterator]:()=>Zn}){let vt=X.candidates?.[0]?.content?.parts,Hn=vt?ne==="Google"?vt[1]?.text||vt[0]?.text||"":vt.filter(In=>In.text&&!In.thought).map(In=>In.text).join(""):typeof X.text=="function"?X.text():"";Hn&&(T+=Hn),E=X.usageMetadata}}}catch(ue){throw ue}if(T){if(Ct=T,E){let ue=E.totalTokenCount||0,ke=E.cachedContentTokenCount||0,Ae=(E.candidatesTokenCount||0)+(ne==="Google"&&E.thoughtsTokenCount||0),Oe=Be?Z("nvidia_janitor_fallback"):ne==="DeepSeek"?Z("deepseek_fast_fallback"):ne==="ExpLabs"||ne==="ExperientialLabs"?Z("explabs_fallback")||"deepseek-v4-pro-0813":ne==="OpenRouter"?Z("janitor_open_router"):r||(rt===Zt?Z("janitor_default"):Z("gemma_janitor_fallback_google"));await gt("tokens",ue,ne,Oe),ke>0&&await gt("cachedTokens",ke,ne,Oe),Ae>0&&await gt("candidateTokens",Ae,ne,Oe),janitorTtft!==null&&janitorTtft>0&&await gt("ttft",janitorTtft,ne,Oe),ho({provider:ne,model:Oe,prompt:E.promptTokenCount||0,cached:ke,output:Ae,reasoning:E.thoughtsTokenCount||0,ttft:janitorTtft})}}else throw new Error("No synthesis generated by Janitor.");h&&(h(),await kt("background"));let A=Ro(Ct),D=!1;for(let ue of A){let ke=ue.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(ke)&&(D=!0);let Ae={chatId:f,sessionId:f,history:i},Oe=await ko(ke,ue.args,Ae);ke.toLowerCase()==="memory"&&(ue.args.includes("action='user'")||ue.args.includes('action="user"'))&&!Oe.startsWith("ERROR")&&(g&&g(),process.stdout.isTTY&&(process.stdout.write("\x1B]0;Memory Updated\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=Memory Updated\x07")),await new Promise(Qn=>setTimeout(Qn,3e3)))}if(!D)try{let ue=Tt(Fn,[]);if(ue.length>0){let ke=[];for(let Ae of ue)Ae.score===void 0&&(Ae.score=.5),Ae.score*=.99995,Ae.score<.05&&(Ae.score=0),Ae.score=Math.round(Ae.score*1e5)/1e5,Ae.score>0&&ke.push(Ae);zn(Fn,ke)}}catch{}break}catch(T){rt++;let E=new Date().toLocaleString(),Be=T instanceof Error?(()=>{try{return JSON.parse(JSON.parse(T.message).error.message).error.message}catch{return String(T)}})():String(T);await new Promise(D=>setTimeout(D,1e3));let ne=V.join(En,"janitor");if(ve.existsSync(ne)||ve.mkdirSync(ne,{recursive:!0}),ve.appendFileSync(V.join(ne,"error.log"),`ERROR [Attempt ${rt}/${Zt+1}] [${E}]: ${Be}
587
+
588
+ `),rt>Zt)break;let A=Math.min(750*Math.pow(2,rt-1),5e3);await new Promise(D=>setTimeout(D,A))}if(rt){let T=V.join(En,"janitor");ve.appendFileSync(V.join(T,"error.log"),`-----------------------------------------------------------------------------
589
+
590
+ `)}if(process.stdout.isTTY)try{let Be=(await bi())[f]?.name||"",ne=Be&&!Be.startsWith("flow-")&&!Be.startsWith("Session ")?Be:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${ne}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${ne}\x07`)}catch{process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")}},Wa=e=>{let n=Wt(e),t=xi?n:n.replace(Ps,o=>" ".repeat(o.length)).replace(Ls,o=>" ".repeat(o.length));Eo.lastIndex=0;let i;for(;(i=Eo.exec(t))!==null;){let o=i.index+i[0].length-1,s=0,c=null,a=!1,g=!1;for(let h=o;h<t.length;h++){let y=n[h];if(!c&&(y==='"'||y==="'"||y==="`")?(c=y,a=!1):c&&y===c&&!a&&(c=null),!c&&(y==="("?s++:y===")"&&s--,s===0)){let u=h+1;for(;u<t.length&&/\s/.test(t[u]);)u++;if(u<t.length&&t[u]==="]"){g=!0,Eo.lastIndex=u+1;break}}y==="\\"?a=!a:a=!1}if(!g)return{inside:!0,toolName:i[1],startIndex:i.index,args:n.substring(i.index+i[0].length)}}return{inside:!1}},Ns=(e,n=!0)=>{let t=Eo;t.lastIndex=0;let i="",o=0,s;for(;(s=t.exec(e))!==null;){let c=e.substring(o,s.index);i+=n&&o===0?Wt(c):c;let a=s.index+s[0].length-1,g=0,h=null,y=-1;for(let u=a;u<e.length;u++){let m=e[u];if(h){if(m===h){let r=0;for(let f=u-1;f>=0&&e[f]==="\\";f--)r++;r%2===0&&(h=null)}}else if(m==='"'||m==="'"||m==="`")h=m;else if(m==="(")g++;else if(m===")"&&(g--,g===0)){let r=u+1;for(;r<e.length&&/\s/.test(e[r]);)r++;if(r<e.length&&e[r]==="]"){y=r;break}}}if(y!==-1)i+="[tool:functions."+s[1]+"()]",o=y+1,t.lastIndex=o;else{i+="[tool:functions."+s[1]+"(",o=e.length;break}}return o<e.length&&(i+=n&&o===0?Wt(e.substring(o)):e.substring(o)),i},Ga=(e,n,t)=>{let i=Eo;i.lastIndex=0;let o="",s=0,c;for(;(c=i.exec(e))!==null;){let a=e.substring(s,c.index);o+=a.replace(n,t);let g=c.index+c[0].length-1,h=0,y=null,u=-1;for(let m=g;m<e.length;m++){let r=e[m];if(y){if(r===y){let f=0;for(let w=m-1;w>=0&&e[w]==="\\";w--)f++;f%2===0&&(y=null)}}else if(r==='"'||r==="'"||r==="`")y=r;else if(r==="(")h++;else if(r===")"&&(h--,h===0)){let f=m+1;for(;f<e.length&&/\s/.test(e[f]);)f++;if(f<e.length&&e[f]==="]"){u=f;break}}}if(u!==-1)o+=e.substring(c.index,u+1),s=u+1,i.lastIndex=s;else{o+=e.substring(c.index),s=e.length;break}}return s<e.length&&(o+=e.substring(s).replace(n,t)),o},Ms=e=>Ns(e,!0),Ha=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(s=>s.charAt(0).toUpperCase()+s.slice(1)).join("");Cs.lastIndex=0;let i=e.replace(Cs,(o,s,c)=>{let a="";try{let y=JSON.parse(c.trim());y&&typeof y=="object"&&(a=Object.entries(y).map(([m,r])=>{let f=typeof r=="string"?r:JSON.stringify(r);return`${m}=${JSON.stringify(f)}`}).join(", "))}catch{let u=[],m=Na;m.lastIndex=0;let r;for(;(r=m.exec(c))!==null;){let f=r[1],w=r[2]!==void 0?r[2]:r[0].split(":").slice(1).join(":").trim();u.push(`${f}=${JSON.stringify(w)}`)}u.length>0?a=u.join(", "):a=c.trim()}let g=s.toLowerCase().replace(/_/g,"");return`[tool:functions.${n[g]||t(s)}(${a})]`});return vs.lastIndex=0,_s.lastIndex=0,i=i.replace(vs,""),i=i.replace(_s,""),i},ja=/(?:path|query|url|keyword|command|method|title|task|id)\s*=\s*['"`]?\s*\.\.\.\s*['"`]?/i,Va=/^['"`]?\s*\.\.\.\s*['"`]?$/,pn=e=>{if(e==null)return!1;let n=String(e).trim();return n==="..."||n==="\u2026"||Va.test(n)},Ro=e=>{if(!e)return[];let n=Ha(e),t=Wt(n),i=[],o=xi?t:t.replace(Ps,a=>" ".repeat(a.length)).replace(Ls,a=>" ".repeat(a.length)),s=_a;s.lastIndex=0;let c;for(;(c=s.exec(o))!==null;){let a=c[1],g=c.index+c[0].length-1,h=0,y=null,u=-1,m=-1;for(let r=g;r<o.length;r++){let f=t[r];if(y){if(f===y){let w=0;for(let pe=r-1;pe>=0&&t[pe]==="\\";pe--)w++;w%2===0&&(y=null)}}else if(f==='"'||f==="'"||f==="`")y=f;else if(f==="(")h++;else if(f===")"&&(h--,h===0)){m=r;let w=r+1;for(;w<o.length&&/\s/.test(o[w]);)w++;if(w<o.length&&o[w]==="]"){u=w;break}}}if(u!==-1){let r=t.substring(g+1,m),f=t.substring(c.index,u+1),w=G(r);pn(w.path)||pn(w.query)||pn(w.url)||pn(w.keyword)||pn(w.command)||pn(w.method)||pn(w.title)||pn(w.task)||pn(w.id)||ja.test(r)||i.push({fullMatch:f,toolName:a.trim(),args:r.trim()}),s.lastIndex=u+1}}return i},Jc=(e,n={})=>{if(!e)return null;if(Qo=n,zi=new Os({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}}}},Ds=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}},Zo=async(e,n,t,i,o="Fast",s=.75,c="agent")=>Fa(async()=>{let{aiProvider:a="Google",apiKey:g,mode:h}=e,y="",u=null,m=typeof t=="string"?[{role:"user",parts:[{text:t}]}]:t,r=new AbortController,f=r.signal,w=setInterval(()=>{ht&&(r.abort(),clearInterval(w))},100),pe=Date.now(),b=null;try{let v;if(a==="Ollama")v=(await se("Ollama"))(g,n,m,i,o,h,it(n),f,s,e.systemSettings?.ollamaEndpoint||"Cloud");else if(a==="OpenRouter")v=(await se("OpenRouter"))(g,n,m,i,o,h,it(n),f,s);else if(a==="DeepSeek")v=(await se("DeepSeek"))(g,n,m,i,o,h,it(n),f,s);else if(a==="Mistral")v=(await se("Mistral"))(g,n,m,i,o,h,it(n),f,s);else if(a==="NVIDIA")v=(await se("NVIDIA"))(g,n,m,i,o,h,it(n),f,s);else if(a==="InferX")v=(await se("InferX"))(g,n,m,i,o,h,it(n),f,s);else if(a==="SenseNova")v=(await se("SenseNova"))(g,n,m,i,o,h,it(n),f,s);else if(a==="AIHubMix")v=(await se("AIHubMix"))(g,n,m,i,o,h,it(n),f,s);else if(a==="Poolside")v=(await se("Poolside"))(g,n,m,i,o,h,it(n),f,s);else if(a==="9router"||a==="9Router")v=(await se("NineRouter"))(g,n,m,i,o,h,it(n),f,s);else if(a==="ExpLabs"||a==="ExperientialLabs")v=(await se("ExpLabs"))(g,n,m,i,o,h,it(n),f,s);else if(a==="Infron"||a==="infron")v=(await se("Infron"))(g,n,m,i,o,h,it(n),f,s);else if(a==="TokenHarbor"||a==="Token Harbor"||a==="tokenharbor"||a==="token_harbor"||a==="thk")v=(await se("TokenHarbor"))(g,n,m,i,o,h,it(n),f,s);else if(a==="APInex"||a==="apinex"||a==="apx")v=(await se("APInex"))(g,n,m,i,o,h,it(n),f,s);else if(a==="c_openai"||a==="Custom (OpenAI)")v=(await se("c_openai"))(g,n,m,i,o,h,it(n),f,s,e.systemSettings?.customOpenAIBaseUrl||"");else{let ie=qi(g),{serviceTier:ee,cleanModel:te}=Ds(n),I={systemInstruction:i,temperature:s,thinkingConfig:(()=>{let _e=(n||"").toLowerCase(),Ie=_e.includes("gemma-4")||_e.startsWith("gemma"),he=_e.includes("gemini-3");if(Ie||he)return Ie?o.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:Ge.MINIMAL}:{includeThoughts:!0,thinkingLevel:Ge.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:_e.includes("pro")?Ge.LOW:Ge.MINIMAL,Low:Ge.LOW,Medium:Ge.MEDIUM,Standard:Ge.MEDIUM,High:Ge.HIGH,xHigh:Ge.HIGH}[o]||Ge.MEDIUM};{let S={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[o]||2048;return S===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:S}}})()};ee&&(I.serviceTier=ee),v=await ie.models.generateContentStream({model:te,contents:m,config:I},{signal:f})}for await(let ie of v){if(ht)throw new Error("Subagent task was cancelled.");if(e?.taskId&&typeof Bt<"u"){let I=Bt.find($e=>$e.id===e.taskId);if(I&&I.status==="cancelled")throw new Error("Subagent task was cancelled.")}b===null&&(ie.candidates?.[0]?.content?.parts||ie.text)&&(b=Date.now()-pe);let ee="";if(ie.candidates?.[0]?.content?.parts)for(let I of ie.candidates[0].content.parts)I.text&&!I.thought&&(y+=I.text,ee+=I.text);let te=ee?pi(ee):0;e&&typeof e.onTokenChunk=="function"&&e.onTokenChunk(ee,te),ie.usageMetadata&&(u=ie.usageMetadata)}}finally{clearInterval(w)}if(u){let v=u.totalTokenCount||0,ie=u.cachedContentTokenCount||0,ee=(u.candidatesTokenCount||0)+(a==="Google"&&u.thoughtsTokenCount||0);await gt("tokens",v,a,n),ie>0&&await gt("cachedTokens",ie,a,n),ee>0&&await gt("candidateTokens",ee,a,n),b!==null&&b>0&&await gt("ttft",b,a,n),ho({provider:a,model:n,prompt:u.promptTokenCount||0,cached:ie,output:ee,reasoning:u.thoughtsTokenCount||0,ttft:b}),e&&typeof e.onUsage=="function"&&e.onUsage({totalTokenCount:v,cachedContentTokenCount:ie,candidatesTokenCount:ee})}return await kt("agent",a),{text:y,usageMetadata:u}}),Ka=async(e,n,t=null)=>{t=t||Tt(Po,{});try{let{aiProvider:i="Google"}=n;if(Object.values(t).flat().length<=5)return;let s=Object.keys(t).filter(m=>m!==e&&Array.isArray(t[m])&&t[m].length>2);if(s.length===0)return;let c=`You are a silent background process for the FluxFlow CLI Agent.
591
+ Your task is to summarize or merge temporary context memories from one or more past conversation sessions.
592
+ For each Chat ID provided, you must output a tool call to save the consolidated summary.
593
+
594
+ The tool call format MUST be:
595
+ [tool:functions.saveSummary(id="<chat-id>", summary="<updated summary string, max 400 words>")]
596
+
597
+ Guidelines:
598
+ - 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.
599
+ - Focus on key goals, preferences, modified files, and technical decisions.
600
+ - Under no circumstances write normal conversational text. Output ONLY the tool calls.
601
+ - You can stack multiple tool calls for multiple chats.
602
+
603
+ Chats to process:
604
+
605
+ `,a=Tt(ui,{});for(let m of s){let f=t[m].map(pe=>`- ${pe}`).join(`
606
+ `),w=a[m];c+=`[Chat ID: ${m}]
607
+ `,w?(c+=`- Existing Summary: "${w}"
608
+ `,c+=`
609
+ -- New Memories to integrate:
610
+ ${f}
611
+
612
+ `):c+=`-- Individual Memories:
613
+ ${f}
614
+
615
+ `}let g=0,h=5,y=!1,u=Z("gemma_janitor_fallback_google");for(i==="OpenRouter"&&(u=Z("janitor_open_router")),i==="DeepSeek"&&(u=Z("deepseek_level_1")),i==="Mistral"&&(u=Z("mistral_level_1")),i==="NVIDIA"&&(u=Z("nvidia_janitor_fallback")),i==="InferX"&&(u=Z("inferx_fallback")),i==="SenseNova"&&(u=Z("sensenova_fallback")),i==="AIHubMix"&&(u=Z("aihubmix_fallback")),i==="Poolside"&&(u=Z("poolside_fallback")),(i==="9router"||i==="9Router")&&(u=Z("9router_fallback"));g<=h&&!y;){g++;try{let r=(await Zo(n,u,c,null,"Fast",.75,"background")).text||"",f=Ro(r);if(f.length===0)throw new Error("No tool calls detected in synthesis response");for(let w of f){let pe=w.toolName;["saveSummary","saveSumary","SaveSummary","SaveSumary"].includes(pe)&&await ko(pe,w.args,{chatId:e})}y=!0}catch(m){if(g>=h)throw new Error(`Failed after ${h} attempts. Last error: ${m.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),s=V.join(En,"janitor");ve.existsSync(s)||ve.mkdirSync(s,{recursive:!0}),ve.appendFileSync(V.join(s,"error.log"),`[${new Date().toLocaleString()}] Past memory batch consolidation error: ${o}
616
+ `)}},Qc=async(e,n,t=!1)=>{let{chatId:i,aiProvider:o="Google"}=e,s=V.join(Oo,"chat-summaries.json"),c=r=>r.filter(f=>(f.role==="user"||f.role==="agent"||f.role==="system")&&f.role!=="think"&&!f.isVisualFeedback&&!f.isMeta&&!f.isTerminalRecord&&!(f.text&&f.text.includes("[TERMINAL_RECORD]"))&&!String(f.id).startsWith("welcome")).map(f=>{let w=f.fullText||f.text||"",pe=f.role==="system"||w.startsWith("[ACTION RESULT]:")||w.startsWith("[TOOL RESULT]:")||f.text&&(f.text.startsWith("[ACTION RESULT]:")||f.text.startsWith("[TOOL RESULT]:")),b=w;return pe&&(w.includes("[ACTION RESULT]:")||w.includes("[TOOL RESULT]:")||f.text&&(f.text.includes("[ACTION RESULT]:")||f.text.includes("[TOOL RESULT]:")))?b="[ACTION RESULT]: ...truncated for summary":b=b.replace(/(\[(?:tool|action):[a-zA-Z0-9_\.]+)\([\s\S]*?\)(\])/g,"$1(...)$2"),`[${pe?"ACTION":f.role==="agent"?"AGENT":"USER"}]: ${b}`}).join(`
617
+
618
+ `),a=async(r,f)=>{let w="You are an expert context summarizer. Summarize the provided chat history (which may include previous summaries, user instructions, agent outputs, and tool results) into a detailed, coherent, and highly technical summary of 1000 to 1500 words. Focus on preserving the architectural decisions made, current system state, task progress, and critical code details, chat messages, file changes. Under no circumstances exceed MAX 2000 words.",pe=f?`Here is the previous summary:
619
+ ${f}
620
+
621
+ Here is the new conversation history:
622
+ ${r}
623
+
624
+ Provide a new consolidated summary of the entire session.`:`Here is the conversation history:
625
+ ${r}
626
+
627
+ Provide a consolidated summary of the entire session.`,b=Z("gemma_janitor_fallback_google");o==="OpenRouter"&&(b=Z("janitor_open_router")),o==="DeepSeek"&&(b=Z("deepseek_level_1")),o==="Mistral"&&(b=Z("mistral_level_1")),o==="NVIDIA"&&(b=Z("nvidia_chat_summarizer_fallback")),o==="InferX"&&(b=Z("inferx_fallback")),o==="SenseNova"&&(b=Z("sensenova_fallback")),o==="AIHubMix"&&(b=Z("aihubmix_fallback")),o==="Poolside"&&(b=Z("poolside_fallback")),(o==="9router"||o==="9Router")&&(b=Z("9router_fallback")),(o==="ExpLabs"||o==="ExperientialLabs")&&(b=Z("explabs_fallback")||"deepseek-v4-pro-0813"),(o==="TokenHarbor"||o==="Token Harbor"||o==="tokenharbor"||o==="token_harbor"||o==="thk")&&(b=Z("tokenharbor_fallback")||"deepseek-v4.1-flash:free"),(o==="Infron"||o==="infron")&&(b=Z("infron_fallback"));let v=0,ie=!1,ee=null;for(;v<=3&&!ie;){v++;try{ee=await Zo(e,b,pe,w,"Fast"),ie=!0}catch{if(v>3){if(o==="Google")try{let I=Z("general_fallback");return(await Zo(e,I,pe,w,"Fast")).text||""}catch{return""}return""}}}return ee&&ee.text||""},g=c(n),h=Tt(s,{}),y=h[i]||{summary:"",historyLength:0};typeof y=="string"&&(y={summary:y,historyLength:0});let u=y.summary||"",m=await a(g,u);if(m){y.summary=m;let r=Ba(n);return t?y.historyLength=(y.historyLength||0)+r:y.historyLength=r,h[i]=y,zn(s,h),m}return null},Zc=e=>{try{let n=V.join(Oo,"chat-summaries.json");if(ve.existsSync(n)){let t=Tt(n,{});t[e]&&(delete t[e],zn(n,t))}}catch{}},ed=async function*(e,n,t,i,o){let{profile:s,thinkingLevel:c,mode:a,janitorModel:g,chatId:h,isPlayground:y,systemSettings:u,sessionStats:m,aiProvider:r="Google",apiTier:f,wildcardTooling:w,wildercardTooling:pe}=t,b=it(e);if(!zi&&r==="Google")throw new Error("AI not initialized");let v=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==="Infron"||t?.aiProvider==="infron"||t?.aiProvider==="c_openai"||t?.aiProvider==="Custom (OpenAI)"?!1:u?.memory!==!1,ie=n[n.length-1].text,ee=V.join(Oo,"chat-summaries.json"),te=!1,I=n.filter(S=>S.role==="user").length===1,$e=ie.includes("[TITLE-UPDATE]"),_e=I||$e,Ie=ie.replace(/\[TITLE-UPDATE\]/g,"").trim();Ie=Ie.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),yield{type:"status",content:"[start]"},yield{type:"status",content:"Gathering Context"},await $o.startTransaction(h,Ie),u?.advanceRollback&&await mo.takeInitialSnapshot(h),ht=!1;let he=null;try{let S=new AbortController;he=setInterval(()=>{ht&&(S.abort(),he&&(clearInterval(he),he=null))},400);let x=[...n.slice(0,-1)];{let Ue=Tt(ee,{})[h]||{summary:"",historyLength:0};if(Ue.summary&&Ue.historyLength>0){let cn=0,qe=[];for(let be=0;be<x.length;be++){let Xe=x[be];(Xe.role==="user"||Xe.role==="agent"||Xe.role==="system")&&!String(Xe.id).startsWith("welcome")&&!Xe.isMeta&&cn++,cn>Ue.historyLength&&qe.push(Xe)}x=qe}}x=x.map(M=>{if(M.role==="user"&&M.text){let Ue=M.text.match(/\[USER\]([\s\S]*?)\[\/USER\]/);if(Ue)return{...M,text:Ue[1].trim()}}return{...M}});let lt=process.env.HIGH_CONTEXT,Me=process.env.GOOGLE_GEMMA_NONSENSE==="true"||process.env.GOOGLE_GEMMA_NONSENSE===!0||!1,Rt={"16k":16e3,"32k":32e3,"64k":64e3,"128k":128e3,"256k":256e3,"512k":512e3,"1M":1e6}[u?.contextLength]||256e3;if(lt&&lt!=="false"){let M=parseInt(lt,10);!isNaN(M)&&M>=0&&M<=1e6&&(Rt=M)}if((r==="NVIDIA"&&(e?.includes("gpt")||e?.includes("qwen")||e?.includes("medium")||e.includes("muse"))||r==="Mistral")&&(Rt=126e3),r==="Google"&&e?.includes("gemma")&&Me&&(Rt=16e3),(m?.tokens||0)>Rt){yield{type:"text",content:"\u2726 Maximum Context Limit Reached. Start a new chat."};return}if(I&&v){let M=Tt(Po,{});Object.values(M).flat().length>5&&(yield{type:"status",content:"Condensing past chat memories"},await Ka(h,t,M))}let Yt=Tt(Po,{}),an=Tt(ui,{}),Ne=Object.entries(Yt).filter(([M])=>M!==h).flatMap(([M,Ue])=>Ue),rt=[...Object.entries(an).filter(([M])=>M!==h).slice(-20).map(([M,Ue])=>`[Chat Summary]: ${Ue}`),...Ne].map(M=>`- ${M}`).join(`
628
+ `),T=Tt(Fn,[]).map(M=>`- ${M.memory}`).join(`
629
+ `),E=(m?.tokens||0)>=1e4,Be=new Date,ne=Be.getFullYear(),A=Be.toLocaleString("en-US",{month:"short"}).toUpperCase(),D=String(Be.getDate()).padStart(2,"0"),ue=Be.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}),ke=`${ne}-${A}-${D}, ${ue}`,Ae=`${ue}`,Oe=M=>{try{return ve.readdirSync(M,{withFileTypes:!0})}catch{return[]}},Jn=Array.from(new Set([...fo,...uo(process.cwd())])),Qn=(M,Ue=6)=>u?.indentationTree!==!1?Gi(M,Ue,1,Oe,Jn):ji(M,Ue,"",1,Oe,Jn),Zn=Tt(gi,{}),eo=Zn[h],yn=eo?eo!==process.cwd():!1;Zn[h]=process.cwd(),zn(gi,Zn);let to=Tt(ee,{}),Ce=to[h]||{summary:"",historyLength:0};typeof Ce=="string"&&(Ce={summary:Ce,historyLength:0});let fe=n.filter(M=>(M.role==="user"||M.role==="agent"||M.role==="system")&&!String(M.id).startsWith("welcome")&&!M.isMeta).length;Ce.historyLength&&fe<Ce.historyLength&&(Ce.summary="",Ce.historyLength=0,to[h]=Ce,zn(ee,to));let X=typeof Ce=="object"?Ce.summary||"":Ce||"",vt=x.length>0;vt&&X&&x[0]&&(x[0].role==="user"||x[0].role==="system")&&(x[0].text.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")||(x[0].text=`[SYSTEM METADATA]
630
+ **CONTEXT SUMMARY OF PREVIOUS TURNS (PRIORITY: DYNAMIC)**
631
+ ${X}
632
+
633
+ [USER] ${x[0].text}`,yield{type:"summary_injected",content:{id:x[0].id,text:x[0].text}}));let Hn=X&&!vt?`
634
+ [SYSTEM METADATA]
635
+ **CONTEXT SUMMARY OF PREVIOUS TURNS**
636
+ ${X}
637
+ `:"",In=!!u?.dynamicDirAwareness,Fs=`${h}|${r}|${c}|${e}|${s}|${In}`,Bs=!In&&Wn.key===Fs&&Wn.value?"":`
638
+ **Directory**
639
+ CWD: `+process.cwd()+`${y?" [PLAYGROUND MODE]":""}
640
+ `+Qn(process.cwd(),6),ct=await Bn(),ln="";if(Jo()&&ct.file_focused!=="none"){ln=`
641
+ [Additional IDE Context]
642
+ `;let M=V.relative(process.cwd(),ct.file_focused),Ue=(ct.opened_editors||[]).map(qe=>{let be=V.relative(process.cwd(),qe);return be.startsWith("..")?`[External] ${V.basename(qe)}`:be});if(ln+=`Focused File: ${M}
643
+ Cursor Line: ${ct.cursor_line}
644
+ `,ct.selected){let qe=ct.selected,be=qe.split(`
645
+ `);be.length>256&&(qe=be.slice(0,240).join(`
646
+ `)+`
647
+ ... [truncated] ...
648
+ `+be.slice(-16).join(`
649
+ `)),qe.length>2048&&(qe=qe.slice(0,1920)+`
650
+ ... [truncated] ...
651
+ `+qe.slice(-128)),ln+=`Current Selection: "${qe}"
652
+ `}if(ct.manual_edits){let be=ct.manual_edits.split(`
653
+ `),Xe=[],je=null;for(let O of be)O.trim()&&(O.startsWith(" Line ")?je&&je.edits.push(O):(je={path:O.endsWith(":")?O.slice(0,-1):O,edits:[]},Xe.push(je)));for(let O of Xe)O.edits.length>80&&(O.edits=O.edits.slice(-80)),O.originalEditsCount=O.edits.length;let Je=(O,De)=>De.reduce((dt,qt)=>{let mt=ct.file_focused&&(qt.path===ct.file_focused||V.resolve(process.cwd(),qt.path)===V.resolve(ct.file_focused))?Math.ceil(O*1.2):O;return dt+Math.min(qt.edits.length,mt)},0),Ht=80;if(Je(80,Xe)>300){let O=!1;for(let De=80;De>=10;De--)if(Je(De,Xe)<=300){Ht=De,O=!0;break}O||(Ht=10)}let we=[...Xe];if(Ht===10&&Je(10,we)>500)for(;we.length>0&&Je(10,we)>500;){let O=0,De=we[0].originalEditsCount;for(let dt=1;dt<we.length;dt++)we[dt].originalEditsCount<De&&(De=we[dt].originalEditsCount,O=dt);we.splice(O,1)}for(let O of we){let dt=ct.file_focused&&(O.path===ct.file_focused||V.resolve(process.cwd(),O.path)===V.resolve(ct.file_focused))?Math.ceil(Ht*1.2):Ht;O.edits.length>dt&&(O.edits=O.edits.slice(-dt))}for(let O of we){let De=`${O.path}:
654
+ ${O.edits.join(`
655
+ `)}`;for(;O.edits.length>0&&De.length>4*768;)O.edits.shift(),De=`${O.path}:
656
+ ${O.edits.join(`
657
+ `)}`;De.length>4*768?O.stringRepresentation="... "+De.slice(-(4*768-4)):O.stringRepresentation=De}let le=we.map(O=>O.stringRepresentation).join(`
658
+ `);for(;we.length>0&&le.length>4*2048;){we[0].edits.length>0?we[0].edits.shift():we.shift();for(let O of we){let De=`${O.path}:
659
+ ${O.edits.join(`
660
+ `)}`;De.length>4*768?O.stringRepresentation="... "+De.slice(-(4*768-4)):O.stringRepresentation=De}le=we.map(O=>O.stringRepresentation).join(`
661
+ `)}le.length>4*2048&&(le="... "+le.slice(-(4*2048-4))),ln+=`Recent Manual Edits:
662
+ ${le}
663
+ `}Ue.length>0&&(ln+=`All Opened Editors: ${Ue.join(", ")}`),ct.diagnostics&&(ln+=`
664
+ **Active File Errors**:
665
+ ${ct.diagnostics}
666
+ `),(Ie.toLowerCase().includes("lint")||Ie.toLowerCase().includes("warning"))&&ct.warnings&&(ln+=`
667
+ **Lint Warnings**:
668
+ ${ct.warnings}
669
+ `)}let Xi=Ie.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),Ji=/(?:\\)?@\[([^\]]+)\]/g,ei,ti=[];for(Ji.lastIndex=0;(ei=Ji.exec(Xi))!==null;){let M=ei[0].startsWith("\\");ti.push({tag:ei[1],isEscaped:M})}let ni=[],Co=null;for(let M=0;M<ti.length;M++){let{tag:Ue,isEscaped:cn}=ti[M];if(!cn)try{let qe=Ue.trim().replace(/^["']|["']$/g,""),be=/[:#]L?(\d+)(?:-L?(\d+))?$/i,Xe=qe.match(be),je=qe,Je=null,Ht=null;Xe&&(Je=parseInt(Xe[1],10),Ht=Xe[2]?parseInt(Xe[2],10):Je,je=qe.slice(0,Xe.index));let we=V.resolve(process.cwd(),je);if(ve.existsSync(we)&&ve.statSync(we).isFile()){let O=je.toLowerCase(),De=O.endsWith(".pdf"),dt=O.endsWith(".docx")||O.endsWith(".doc")||O.endsWith(".ppt")||O.endsWith(".pptx")||O.endsWith(".xls")||O.endsWith(".xlsx"),qt=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(O),Fe=qt||De||dt,mt=r==="Google"||it(e);if(Fe&&!mt){let Ee=`\u2718 Unsupported Modality: ${V.basename(je)}`,tt=115;process.stdout.isTTY&&(tt=process.stdout.columns-5||120);let jt=[Ee],Ve=Math.max(...jt.map(Xt=>Xt.length)),z=Math.min(Ve+4,tt),He=jt.map(Xt=>`${Xt.padEnd(z-2).substring(0,z-2)}`).join(`
670
+ `);yield{type:"visual_feedback",content:Ut(`${He}
671
+ `)};continue}if(Je===null&&!Fe){let Ee=0;try{Ee=ve.readFileSync(we,"utf8").split(/\r\n|\r|\n/).length}catch{}if(Ee>300){let tt=`\u21B7 Skipped (Too Large): ${V.basename(je)}`,jt=115;process.stdout.isTTY&&(jt=process.stdout.columns-5||120);let Ve=Math.min(tt.length+4,jt),z=tt.padEnd(Ve-2).substring(0,Ve-2);yield{type:"visual_feedback",content:Ut(`${z}
672
+ `)};continue}}let dn=Je!==null?Je:1,_t=Ht!==null?Ht:Je!==null?Je:dn+299;_t-dn>300&&(_t=dn+300);let Mn=`path=${JSON.stringify(je)}, startLine=${dn}, endLine=${_t}`,$t=await yr(Mn,{isMultiModal:mt}),bn=!1,jn="",pt=null;if(typeof $t=="string"?$t.trim().startsWith("ERROR")?bn=!0:jn=$t:$t&&typeof $t=="object"&&$t.binaryPart?(pt=$t.binaryPart,jn=$t.text||""):bn=!0,!bn){let Ee="";if(qt?(Ee=`\u2714 Processed: ${V.basename(je)}`,Co=pt):De||dt?(Ee=`\u2714 Auto-Analysed: ${V.basename(je)}`,Co=pt):(Ee=`\u2714 Auto-Read: ${V.basename(je)}`,ni.push(jn)),Ee){let tt=115;process.stdout.isTTY&&(tt=process.stdout.columns-5||120);let jt=[Ee],Ve=Math.max(...jt.map(Xt=>Xt.length)),z=Math.min(Ve+4,tt),He=jt.map(Xt=>`${Xt.padEnd(z-2).substring(0,z-2)}`).join(`
673
+ `);yield{type:"visual_feedback",content:Ut(`${He}
674
+ `)}}}}}catch{}}let oi="";ni.length>0&&(oi=`
675
+ [Tagged File Contents] Auto Read User Tagged files by System, No need to re-read
676
+ `+ni.join(`
677
+
678
+ `)+`
679
+ [Tagged File Contents]
680
+ `);let Qi=Xi.replace(/\\(@\[[^\]]+\])/g,"$1"),Zi=w?`You cannot execute tools. Instead write the action string in chat you WOULD have written
681
+ `:"",Us=process.env.forcedReasoning||!1,er=c!=="Fast"&&(r==="Mistral"&&!Lo(e)||c!=="High"&&r==="Google")?`${r==="Mistral"&&!Lo(e)||e.toLowerCase().startsWith("gemma")||Us?`[system] strictly follow thinking policy as high priority. do not start a response without <think>...</think> [/system]
682
+ `:""}`:"",vo="",tr=!!u?.autoExcludeMetadata,Ws=!!(ln||oi||Zi||Hn||er||yn||u?.dynamicDirAwareness||u?.autoTruncateResults);tr&&!Ws?vo=Qi.trim():vo=`[System Metadata]
683
+ Time: ${tr?Ae:ke}${yn?`
684
+ WARNING: CWD Changed from previous: "${eo}" to current: "${process.cwd()}", write change in chat to avoid future path mismatches
685
+ `:""}${ln}
686
+ Action format: [action:ActionName(...)]
687
+ [/Metadata]
688
+ ${Hn}${er}${oi}${Zi}[user prompt] ${Qi.trim()} [/user prompt]`.trim();let nr={role:"user",text:vo};Co&&(nr.binaryPart=Co),x.forEach(M=>{M.text&&M.role==="agent"&&(M.text=Wt(M.text))}),x.push(nr),Hn&&n[n.length-1]?.id&&(yield{type:"summary_injected",content:{id:n[n.length-1].id,text:vo}});let zt=null,xn=a==="Flux"?50:15;xn=a.toLowerCase().includes("cu")?75:xn;let Gs=Math.floor(xn/2),or=0,en=16;yield{type:"status",content:"Connecting"},ht=!1;let ii=[],_o=!1,ir=!1;for(let M=0;M<=xn;M++){let Ue=Math.floor(xn*.95);if(M>=Ue&&or<Ue&&typeof t?.onAskUser=="function"){or=Ue;try{let oe="Agent has been running for a long time. Do you want to continue execution?",ae=[{id:"continue",label:"Continue",description:"Add few more steps"},{id:"cancel",label:"Cancel",description:"Stop extending and finish current turn limit"}],B=await t.onAskUser(oe,ae);B&&(B.toLowerCase().includes("continue")||B==="Continue")&&(xn+=Gs)}catch{}}let cn=await mi("agent",t);if(!cn.allowed)throw new Error(cn.reason||`Budget Exhausted for Provider (${r||"Agent"})`);let qe=[];if(_o=!1,a==="ICU"||a==="FluxCU")try{yield{type:"status",content:"Capturing Screen"},await new Promise(B=>setTimeout(B,1e3));let{captureGriddedScreenshot:oe}=await import("./screen_grid-VV7JGWQB.js"),ae=await oe();if(ae&&ae.base64){let B="[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]",It={inlineData:{mimeType:ae.mimeType,data:ae.base64}},bt=u?.imageHistoryCU||"Standard",wt=bt==="Low"?3:bt==="Extended"?10:bt==="Max"?999:5,Vt=x.filter(Pe=>Array.isArray(Pe.parts)&&Pe.parts.some(Mt=>Mt.inlineData));if(Vt.length>=wt){let Pe=Vt.length-wt+1;for(let Mt=0;Mt<Pe;Mt++){let St=Vt[Mt];Array.isArray(St.parts)&&(St.parts=St.parts.filter(yt=>!yt.inlineData))}}if(x.length>0&&x[x.length-1].role==="user"){let Pe=x[x.length-1];typeof Pe.text=="string"&&(Pe.text+=`
689
+
690
+ ${B}`,Array.isArray(Pe.parts)||(Pe.parts=[{text:Pe.text}]),Pe.parts.push(It))}else x.push({role:"user",text:B,parts:[{text:B},It]})}}catch(oe){console.error("Vision screenshot capture error:",oe)}if(u?.compression===0&&(m?.tokens||0)>Rt&&(x=pr(x,6)),M>0?yield{type:"status",content:"Working"}:yield{type:"status",content:"Connecting"},ht){try{let{clearPendingNudges:oe}=await import("./subagent_state-LZCOZSUJ.js");oe()}catch{}yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
691
+
692
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}try{let{consumePendingNudges:oe}=await import("./subagent_state-LZCOZSUJ.js"),ae=oe();if(ae&&ae.length>0){let B=ae.join(`
693
+
694
+ `);x.length>0&&x[x.length-1].role==="user"?x[x.length-1].text+=`
695
+
696
+ ${B}`:x.push({role:"user",text:B}),yield{type:"status",content:"Subagent Update"}}}catch{}if(i){let oe=await i();oe&&(oe.startsWith("/btw")?x.length>0&&x[x.length-1].role==="user"?x[x.length-1].text+=`
697
+
698
+ [system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
699
+ [question] ${oe.replace("/btw","").trim()} [/question]`:x.push({role:"user",text:`[system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
700
+ [question] ${oe.replace("/btw","").trim()} [/question]`}):x.length>0&&x[x.length-1].role==="user"?x[x.length-1].text+=`
701
+
702
+ [STEERING HINT from USER, High Priority] ${oe.trim()} [/STEERING HINT]`:x.push({role:"user",text:`[STEERING HINT from USER, High Priority] ${oe.trim()} [/STEERING HINT]`}),yield{type:"status",content:`${oe.startsWith("/btw")?"Question Forwarded...":"Steering Hint Injected..."}`})}let be,Xe=!1,je=1,Je=1,Ht=Date.now(),we=null,le="",O=null,De=null,dt=null,qt=0,Fe=[],mt=0,dn=!1,_t=!1,Mn=!1,$t=!1,bn=!0,jn=0,pt="",Ee="",tt=!1,jt=!1,Ve=!0,z=e,He="",Xt=c;for(c=c.toLowerCase()==="max"?"High":c;je<=en&&Je<=en&&!Xe&&!ht;){let oe=!1;try{le="",bn&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},bn=!1,Je===1&&(pt=""));let ae=p=>{if(!p||typeof p!="string")return p;let P="",R=Ki(p);if(R&&(P=R.fullBlock,p=R.remainingText),!p.includes("[tool:")&&!p.includes("[action:"))return(u?.keepReasoningContext?P:"")+p;p=p.replace(Da,(N,W)=>W.includes("[tool:")||W.includes("[action:")?W.trim():N);let $="",U=0;for(;U<p.length;){let N=p.indexOf("[tool:",U),W=p.indexOf("[action:",U),Ke=-1;if(N!==-1&&W!==-1?Ke=Math.min(N,W):N!==-1?Ke=N:Ke=W,Ke===-1){$+=Is(p.substring(U));break}let k=p.substring(U,Ke);$+=Is(k);let _=-1,de=null,l=0;for(let ye=Ke;ye<p.length;ye++){let H=p[ye];if(de){if(H===de){let L=0;for(let ft=ye-1;ft>=0&&p[ft]==="\\";ft--)L++;L%2===0&&(de=null)}}else if(H==='"'||H==="'"||H==="`")de=H;else if(H==="(")l++;else if(H===")")l--;else if(H==="]"&&l<=0){_=ye;break}}if(_===-1){$+=p.substring(Ke);break}$+=p.substring(Ke,_+1),U=_+1}return(u?.keepReasoningContext?P:"")+$},B=x.filter(p=>(p.role==="user"||p.role==="agent"||p.role==="system")&&!String(p.id).startsWith("welcome")&&!p.isMeta&&!p.isTerminalRecord&&!(p.text&&p.text.startsWith("[TERMINAL_RECORD]"))).map((p,P,R)=>{let $=p.text||"";v||($=$.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),p.role==="agent"&&($=ae($),$=$.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),$=$.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*"));let U=[];return Array.isArray(p.parts)&&p.parts.length>0?U=p.parts.map(N=>{if(N.text){let W=N.text;return v||(W=W.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),p.role==="agent"&&(W=ae(W),W=W.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),W=W.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*")),{text:W}}return N}):U=[{text:$}],p.binaryPart&&it(z)&&R.slice(P+1).filter(W=>W.role==="user"&&!W.text?.startsWith("[ACTION RESULT]")&&!W.text?.startsWith("[TOOL RESULT]")).length<=2&&U.push(p.binaryPart),{role:p.role==="user"||p.role==="system"?"user":"model",parts:U}});for(let p=0;p<B.length;p++){let P=B[p],R=P.parts?.[0]?.text||"";if(P.role==="model"&&/\[(?:tool|action):/i.test(R)){let $=-1;for(let U=p+1;U<B.length;U++){let N=B[U],W=N.parts?.[0]?.text||"";if(N.role==="user"&&(W.startsWith("[ACTION RESULT]")||W.startsWith("[TOOL RESULT]"))){$=U;break}}if($!==-1&&$!==p+1){let[U]=B.splice($,1);B.splice(p+1,0,U)}}}for(let p=B.length-2;p>=0;p--){let P=B[p],R=B[p+1];P.role==="user"&&R.role==="user"&&(R.parts?.[0]?.text||"").trim().startsWith("[SYSTEM")&&B.splice(p,1)}let It=[];for(let p=0;p<B.length;p++){let P=B[p];if(It.length===0)It.push(P);else{let R=It[It.length-1];R.role===P.role?(R.parts[0].text+=`
703
+
704
+ `+(P.parts?.[0]?.text||""),P.parts?.length>1&&R.parts.push(...P.parts.slice(1))):It.push(P)}}B.length=0,B.push(...It),z=e;let bt=`${h}|${r}|${a}|${c}|${Xt}|${z}|${JSON.stringify(s)}|${!!u?.dynamicDirAwareness}|${!!u?.subAgents}`,wt=Wn.key===bt&&Wn.value;if((process.env.I_HAVE_TOO_MUCH_MONEY==="true"||process.env.I_HAVE_TOO_MUCH_MONEY===!0)&&(wt=!1),wt)He=Wn.value;else{let p=r==="Mistral"?!!Lo(z):!(z||"gemma").toLowerCase().startsWith("gemma");He=Zr(s,((z||"gemma").toLowerCase().startsWith("gemma"),Xt),a,u,v,I,r,r==="Google"?!0:b,p,h,!!u?.keepReasoningContext,z),u?.dynamicDirAwareness||(He+=`
705
+ ${Bs.replace(`
706
+ **Directory**`,`
707
+ -- Directory --`)}`),Wn.key=bt,Wn.value=He}let Pe=B[B.length-1];if(Jo()&M>0){await new Promise(R=>setTimeout(R,2500)),yield{type:"status",content:"Verifying"};let p=await Bn(),P=p?p.diagnostics:null;P&&Pe&&Pe.role==="user"&&Pe.parts?.[0]?.text&&(Pe.parts[0].text+=`
708
+ ${P} [/ERROR]`),yield{type:"status",content:"Working"}}let Mt=r==="Mistral"||r==="Google"&&e?.toLowerCase().startsWith("gemma");if(u?.advanceRollback&&Pe&&Pe.role==="user"&&(Pe.parts?.[0]?.text?.startsWith("[ACTION RESULT]")||Pe.parts?.[0]?.text?.startsWith("[TOOL RESULT]")))try{let p=await mo.getLatestFileChanges(h);if(p&&(p.newFiles.length>0||p.modifiedFiles.length>0||p.deletedFiles.length>0)){let P=`
709
+ [system] File Changes:
710
+ `;for(let $ of p.newFiles)P+=`* ${$} (created)
711
+ `;for(let $ of p.modifiedFiles)P+=`* ${$} (modified)
712
+ `;for(let $ of p.deletedFiles)P+=`* ${$} (deleted)
713
+ `;P+="[/system]",Pe.parts[0].text+=P;let R=-1;for(let $=x.length-1;$>=0;$--)if(x[$].role==="user"&&(x[$].text?.startsWith("[ACTION RESULT]")||x[$].text?.startsWith("[TOOL RESULT]"))){R=$;break}R!==-1&&(x[R].text+=P)}}catch{}let St=Math.floor(xn*.99),yt=M+1;yt>=St&&Pe&&Pe.parts?.[0]&&(Pe.parts[0].text+=`
714
+ [system] WARNING, Turn Limit Impending: Step ${yt}/${xn}. Wrap up quickly/prompt user to continue. [/system]`);let At=new Promise((p,P)=>{S.signal.aborted&&P(new DOMException("The user aborted a request.","AbortError")),S.signal.addEventListener("abort",()=>{P(new DOMException("The user aborted a request.","AbortError"))})});At.catch(()=>{});let Qe=B;if(Ht=Date.now(),r==="Ollama")be=(await se("Ollama"))(t.apiKey,z,Qe,He,c,a,b,S.signal,1,u?.ollamaEndpoint||"Cloud");else if(r==="OpenRouter")be=(await se("OpenRouter"))(t.apiKey,z,Qe,He,c,a,b,S.signal,1,h);else if(r==="DeepSeek")be=(await se("DeepSeek"))(t.apiKey,z,Qe,He,c,a,b,S.signal,1);else if(r==="Mistral")be=(await se("Mistral"))(t.apiKey,z,Qe,He,c,a,b,S.signal,1,h);else if(r==="NVIDIA"){let p=(await se("NVIDIA"))(t.apiKey,z,Qe,He,c,a,b,S.signal,1);be=(await se("NVIDIA_wrap"))(p,z)}else if(r==="InferX")be=(await se("InferX"))(t.apiKey,z,Qe,He,c,a,b,S.signal,1);else if(r==="SenseNova")be=(await se("SenseNova"))(t.apiKey,z,Qe,He,c,a,b,S.signal,1);else if(r==="AIHubMix")be=(await se("AIHubMix"))(t.apiKey,z,Qe,He,c,a,b,S.signal,1);else if(r==="Poolside")be=(await se("Poolside"))(t.apiKey,z,Qe,He,c,a,b,S.signal,1);else if(r==="9router"||r==="9Router")be=(await se("NineRouter"))(t.apiKey,z,Qe,He,c,a,b,S.signal,1);else if(r==="ExpLabs"||r==="ExperientialLabs")be=(await se("ExpLabs"))(t.apiKey,z,Qe,He,c,a,b,S.signal,1);else if(r==="Infron"||r==="infron")be=(await se("Infron"))(t.apiKey,z,Qe,He,c,a,b,S.signal,1);else if(r==="TokenHarbor"||r==="Token Harbor"||r==="tokenharbor"||r==="token_harbor"||r==="thk")be=(await se("TokenHarbor"))(t.apiKey,z,Qe,He,c,a,b,S.signal,1);else if(r==="APInex"||r==="apinex"||r==="apx")be=(await se("APInex"))(t.apiKey,z,Qe,He,c,a,b,S.signal,1);else if(r==="c_openai"||r==="Custom (OpenAI)")be=(await se("c_openai"))(t.apiKey,z,Qe,He,c,a,b,S.signal,1,u?.customOpenAIBaseUrl||"");else{let p=qi(t?.apiKey),{serviceTier:P,cleanModel:R}=Ds(z),$={systemInstruction:He,mediaResolution:"MEDIA_RESOLUTION_HIGH",safetySettings:[{category:_n.HARM_CATEGORY_HARASSMENT,threshold:vn.BLOCK_NONE},{category:_n.HARM_CATEGORY_HATE_SPEECH,threshold:vn.BLOCK_NONE},{category:_n.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:vn.BLOCK_NONE},{category:_n.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:vn.BLOCK_NONE}],temperature:1.05,thinkingConfig:(()=>{let N=mr("Google",z||"gemini-3-flash-preview",c);if(N!==null){if(typeof N=="object")return N;if(N===!1||N==="false"||N==="none"||N===0||N==="0")return{includeThoughts:!1};if(typeof N=="number")return{includeThoughts:!0,thinkingBudget:N};if(typeof N=="string"){let _=N.toLowerCase();if(_==="minimal")return{includeThoughts:!0,thinkingLevel:Ge.MINIMAL};if(_==="low")return{includeThoughts:!0,thinkingLevel:Ge.LOW};if(_==="medium")return{includeThoughts:!0,thinkingLevel:Ge.MEDIUM};if(_==="high")return{includeThoughts:!0,thinkingLevel:Ge.HIGH};let de=Number(N);if(!isNaN(de))return{includeThoughts:!0,thinkingBudget:de}}}let W=(z||"").toLowerCase(),Ke=W.includes("gemma-4")||W.startsWith("gemma"),k=W.includes("gemini-3");if(Ke||k)return Ke?c.toLowerCase()!=="high"?{includeThoughts:!1,thinkingLevel:Ge.MINIMAL}:{includeThoughts:!0,thinkingLevel:Ge.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:W.includes("pro")?Ge.LOW:Ge.MINIMAL,Low:Ge.LOW,Medium:Ge.MEDIUM,Standard:Ge.MEDIUM,High:Ge.HIGH,xHigh:Ge.HIGH}[c]||Ge.MEDIUM};{let _={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[c]||2048;return _===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:_}}})()};P&&($.serviceTier=P);let U=p.models.generateContentStream({model:R||"gemini-3-flash-preview",contents:Qe,config:$},{signal:S.signal});be=await Promise.race([U,At])}le="",O=null,dt=null,Fe=[],mt=0,yield{type:"model_update",content:null},Ee="",tt=pt.length>0;let tn="",si=Date.now(),Pn=async function*(){if(r==="Google"&&tn){let p=so(tn);for(let P of p)yield P;tn="",si=Date.now()}},rr=!0,Vn="",no=!1,Et=null,sr=!1,oo=!1,io=!1,Io=!1,wn=!1,ro=p=>{let P=0;for(;P+2<p.length;)p[P]==="`"&&p[P+1]==="`"&&p[P+2]==="`"?(Io=!Io,P+=3):P++},ar=p=>{if(!p)return;let P=/(?:<(\/?)(?:think|thought|thoughts)[^>]*>|\[(\/?)(?:think|thought|thoughts)\]|<\/?channel\|?>|<\|channel>thought)/gi,R;for(;(R=P.exec(p))!==null;){let $=R[0].toLowerCase();$.startsWith("</")||$.startsWith("[/")||$==="<channel|>"?wn=!1:wn=!0}},Ks={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=p=>{let P=[],R=p,$=U=>{if(!U)return;if(!sr){P.push({type:"text",content:U}),ro(U),ar(U);return}let N=/(?:<(\/?)(?:think|thought|thoughts)[^>]*>|\[(\/?)(?:think|thought|thoughts)\]|<\/?channel\|?>|<\|channel>thought)/gi,W=0,Ke;for(;(Ke=N.exec(U))!==null;){let _=U.substring(W,Ke.index);if(_)if(ro(_),wn)P.push({type:"text",content:_});else{let ye=_.replace(/[^\r\n]/g,"");ye&&P.push({type:"text",content:ye})}let de=Ke[0];ro(de);let l=de.toLowerCase();l.startsWith("</")||l.startsWith("[/")||l==="<channel|>"?wn=!1:wn=!0,P.push({type:"text",content:de}),W=N.lastIndex}let k=U.substring(W);if(k)if(ro(k),wn)P.push({type:"text",content:k});else{let _=k.replace(/[^\r\n]/g,"");_&&P.push({type:"text",content:_})}};for(;R.length>0;)if(no){let U=Vn+R,N=Ks[Et];if(N){let k=!1;if(U.length<N.startPrefix.length?N.startPrefix.startsWith(U)||(k=!0):U.startsWith(N.startPrefix)?U.length>=N.fullPrefix.length&&!U.startsWith(N.fullPrefix)&&(k=!0):k=!0,k){$(U),Vn="",no=!1,Et=null,oo=!1,io=!1,R="";break}}let W=-1,Ke=N?N.endTag:"]";if(Et==="tool"||Et==="action"){let k=0,_=null,de=0,l=!1;for(let ye=0;ye<U.length;ye++){let H=U[ye];if(_){if(H===_){let L=0;for(let ft=ye-1;ft>=0&&U[ft]==="\\";ft--)L++;L%2===0&&(_=null)}}else if(H==='"'||H==="'"||H==="`")_=H;else if(H==="(")k++,l=!0;else if(H===")")k--;else if(H==="]"&&l&&k===0){W=ye;break}}}else W=U.indexOf(Ke);if(W!==-1){let k=Ke.length,_=U.substring(0,W+k);Et?.startsWith("kimi")||P.push({type:"text",content:_}),ro(_),ar(_),(Et==="tool"||Et==="action"||Et?.startsWith("kimi"))&&!oo&&!io&&(sr=!0),oo=!1,io=!1,Vn="",no=!1,Et=null,R=U.substring(W+k)}else{Vn=U,R="";break}}else{let U=R.indexOf("[tool"),N=R.indexOf("[action"),W=R.indexOf("[[END]]"),Ke=R.indexOf("<|tool_calls_section_begin|>"),k=R.indexOf("<|tool_call_begin|>"),_=[{type:"tool",idx:U,start:"[tool",end:"]"},{type:"action",idx:N,start:"[action",end:"]"},{type:"end",idx:W,start:"[[END]]",end:"[[END]]"},{type:"kimi_section",idx:Ke,start:"<|tool_calls_section_begin|>",end:"<|tool_calls_section_end|>"},{type:"kimi_call",idx:k,start:"<|tool_call_begin|>",end:"<|tool_call_end|>"}].filter(de=>de.idx!==-1).sort((de,l)=>de.idx-l.idx);if(_.length>0){let de=_[0],l=R.substring(0,de.idx);de.idx>0&&$(l);let ye=de.idx>0?R[de.idx-1]:"";oo=Io||ye==="`",io=wn,no=!0,Et=de.type,Vn="",R=R.substring(de.idx)}else{let de=["[tool","[action","[[END]]","<|tool_calls_section_begin|>","<|tool_call_begin|>"],l=-1;for(let ye of de){for(let H=ye.length-1;H>0;H--)if(R.endsWith(ye.substring(0,H))){l=R.length-H;let L=de.indexOf(ye);L===0?Et="tool":L===1?Et="action":L===2?Et="end":L===3?Et="kimi_section":Et="kimi_call";break}if(l!==-1)break}if(l!==-1){if(l>0){let H=R.substring(0,l);$(H)}let ye=l>0?R[l-1]:"";oo=Io||ye==="`",io=wn,no=!0,Vn=R.substring(l),R=""}else{$(R);break}}}return P},Ys=be[Symbol.asyncIterator]();for(;;){let{value:p,done:P}=await Promise.race([Ys.next(),At]);if(P)break;if(p&&p.type==="status"){yield p;continue}let R="",$=p.candidates?.[0]?.content?.parts;if($&&$.length>0)for(let N of $){let W=typeof N.text=="string"?N.text:N.text?parseChunkText(N.text):"";N.thought?W&&(oe||(R+="<think>",oe=!0),R+=W):W&&(oe&&(R+="</think>",oe=!1),R+=W)}else p.text&&oe&&(R+="</think>",oe=!1);R=Pa(R);let U=R?pi(R):0;if(t&&typeof t.onTokenChunk=="function"&&t.onTokenChunk(R,U),rr&&(we===null&&(we=Date.now()-Ht),yield{type:"status",content:"Thinking"},rr=!1),ht){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
715
+
716
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(R){if(tt){if(Ee+=R,Ee.length>=64){let k=0,_=Math.min(pt.length,Ee.length);for(let l=_;l>=10;l--)if(pt.endsWith(Ee.substring(0,l))){k=l;break}let de=Ee.substring(k);if(de){let ye=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(pt)?de.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):de.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(ye)if(le+=ye,r==="Google")tn+=ye;else{yield*Pn();let H=so(ye);for(let L of H)yield L}}tt=!1,Ee=""}continue}else if(le+=R,r==="Google")tn+=R;else{yield*Pn();let k=so(R);for(let _ of k)yield _}let N=Wa(le);if(N.inside){jt=!0,dt||(dt=Date.now());let _={Ask:"ask",AskUser:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",FindFile:"find_file",find_file:"find_file",findfile:"find_file",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Cancel:"cancel",Await:"await",Answer:"answer",Steer:"steer",steer:"steer"}[N.toolName]||N.toolName,de=N.args||"",l=null;if(["write_file","update_file","view_file","read_folder","find_file","write_pdf","write_docx","search_keyword","generate_image","file_map","invoke","invoke_sync","get_progress","await","answer"].includes(_)){let H=G(de),L=H.basename||H.name||H.path||H.targetFile||H.TargetFile||H.directory||H.file,ft=H.keyword,Ln=H.title||H.task,Sn=H.id||H.taskId,xe=H.timeout||H.time;if(ft!=null)l=String(ft).replace(Un,"");else if(L)l=V.basename(String(L).replace(Un,"").replace(Rs,"/"));else if(Ln&&(_==="invoke"||_==="invoke_sync"))l=String(Ln).replace(Un,"").substring(0,30);else if(Sn&&_==="get_progress")l=String(Sn).replace(Un,"");else if(xe&&_==="await"){let Ot=parseFloat(String(xe).replace(Un,""));isNaN(Ot)?l=String(xe).replace(Un,""):(Ot<5&&(Ot=5),Ot>120&&(Ot=120),l=(fn=>{if(fn>=60){let li=Math.floor(fn/60),Kn=fn%60;return`${li}m${Kn>0?` ${Kn}s`:""}`}return`${fn}s`})(Ot))}else{let Ot=de.match(Ia);if(Ot){let Nt=Ot[1].replace(Un,"");_==="invoke"||_==="invoke_sync"||_==="get_progress"?l=Nt.substring(0,30):l=_==="search_keyword"||_==="file_map"?Nt:V.basename(Nt.replace(Rs,"/"))}}}let ye=`${Yi[_]||_}${l?` ${l}`:""}`;if((_!==O||l!==De)&&(O=_,De=l,yield{type:"status",content:`${ye}`},process.stdout.isTTY)){let L={WebSearch:"Searching",web_search:"Searching",WebScrape:"Reading",web_scrape:"Reading",ReadFile:"Reading",read_file:"Reading",ReadFolder:"Reading",read_folder:"Reading",WriteFile:"Writing",write_file:"Writing",UpdateFile:"Editing",update_file:"Editing",WritePdf:"Creating",write_pdf:"Creating",WriteDocx:"Creating",write_docx:"Creating",SearchKeyword:"Searching",search_keyword:"Searching",CodeSearch:"Searching",code_search:"Searching",FindFile:"Finding File",find_file:"Finding File",Run:"Executing",Ask:"User Input Required",AskUser:"User Input Required",Memory:"Updating Memory",GenerateImage:"Generating",InvokeSync:"Sub-Agent Working",invoke_sync:"Sub-Agent Working",Invoke:"Working",invoke:"Working",GetProgress:"Checking Progress",get_progress:"Checking Progress",Cancel:"Stopping Generalist",cancel:"Stopping Generalist",Await:"Waiting",await:"Waiting",EmergencyRollback:"Rolling the Ball",Answer:"Answering Sub-Agent",answer:"Answering Sub-Agent",Steer:"Steering Sub-Agent",steer:"Steering Sub-Agent",Click:"Clicking",click:"Clicking",Drag:"Dragging",drag:"Dragging",Scroll:"Scrolling",scroll:"Scrolling",KeyboardTyping:"Typing",keyboard_typing:"Typing",KeyPress:"Pressing Key",key_press:"Pressing Key",RecaptureScreen:"Recapturing Screen",recapture_screen:"Recapturing Screen"}[_]||"Working";process.stdout.write(`\x1B]0;${L}...\x07`)}}if(le.length-jn>150){jn=le.length;let k=Ns(le,!1),_=Ki(k),de=_?(_.innerContent||"").trim():"",l=de.split(/[.!?]\s+/),ye=new Set(l),H=l.length>10?(l.length-ye.size)/l.length:0,L=de.split(/\s+/).filter(Se=>Se.length>0).length,ft=.6,Ln=.8,Sn=!1;if(r.toLowerCase().includes("google")&&(z||"").toLowerCase().startsWith("gemma")){let d={low:256,medium:1024,high:8192,max:16384,xhigh:16384}[c?.toLowerCase()]||2500;Sn=L>d}if(H>ft||Sn){yield{type:"status",content:`${H>ft?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},_t=!0,await new Promise(d=>setTimeout(d,3e3));break}let Nt=Ms(le).trim().split(/[.!?]\s+/),fn=new Set(Nt);if((Nt.length>10?(Nt.length-fn.size)/Nt.length:0)>Ln){yield{type:"status",content:"Response Loop Detected. Re-centering..."},_t=!1,$t=!0,await new Promise(Se=>setTimeout(Se,3e3));break}let Kn=k.replace(ka,"").replace(Aa,"").replace(Ea,"").replace(Ra,""),Pt=Kn.toLowerCase().split(/\s+/).map(Se=>Se.replace(Ca,"")).filter(Se=>Se.length>0),un=!1;if(Pt.length>=10)for(let Se=1;Se<=15;Se++){let d=Math.max(3,Math.ceil(10/Se));if(Pt.length<Se*d)continue;let C=Pt.slice(Pt.length-Se),j=C.join(" ");if(Se>1&&j===C.slice(0,Math.floor(Se/2)).join(" ").repeat(2).trim())continue;let J=!0;for(let re=1;re<d;re++)if(Pt.slice(Pt.length-Se*(re+1),Pt.length-Se*re).join(" ")!==j){J=!1;break}if(J){un=!0;break}}if(!un){let Se=Kn.toLowerCase().replace(va,"");if(Se.length>=20)for(let d=1;d<=10;d++){let C=Math.max(5,Math.ceil(16/d));if(Se.length<d*C)continue;let j=Se.substring(Se.length-d),J=!0;for(let re=1;re<C;re++)if(Se.substring(Se.length-d*(re+1),Se.length-d*re)!==j){J=!1;break}if(J){un=!0;break}}}if(un){yield{type:"status",content:"Stuttering Detected. Re-centering..."},_t=!1,Mn=!0,await new Promise(Se=>setTimeout(Se,3e3));break}}let W=Wt(le),Ke=Ro(W);for(;Ke.length>mt;){yield*Pn();let k=Ke[mt],_=Date.now(),l={Ask:"ask",AskUser:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",FindFile:"find_file",find_file:"find_file",findfile:"find_file",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Await:"await",await:"await",AwaitSubagent:"await",awaitSubagent:"await",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"}[k.toolName]||k.toolName,ye=Yi[l]||k.toolName,H=Gn(l,k.args);yield{type:"status",content:`${ye}${H?` ${H}`:""}`};let L="";if(l==="click"){let d=G(k.args);L=`\u2714 Clicked: ${d.intendedClickText?`${d.intendedClickText}`:""}`}else if(l==="drag"){let d=G(k.args);L=`\u2714 Dragged: Cell ${d.fromGridId||""} \u2192 Cell ${d.toGridId||""}`}else if(l==="scroll"){let d=G(k.args);L=`\u2714 Scrolled: ${d.direction||"down"} (${d.amount||1})`}else if(l==="keyboard_typing"){let d=G(k.args);L=`\u2714 Typed: ${d.text?`"${d.text.length>20?d.text.substring(0,20)+"...":d.text}"`:""}`}else if(l==="key_press")L=`\u2714 Pressed Key: ${G(k.args).key||""}`;else if(l==="recapture_screen")L="\u2714 Recaptured Screen";else if(l==="web_search"){let{query:d,limit:C=10,aiMode:j=!1}=G(k.args);L=`${d?"\u2714":"\u2718"} ${j?"AI Search":"Searched"}: ${d?`${d}`:"No Search Query"}${j===!1&&d?` \u2192 ${C}`:""}`}else if(l==="web_scrape"){let d=G(k.args).url||null;L=`${d?"\u2714":"\u2718"} Visited: ${d||"No Source"}`}else if(l==="view_file"){let{path:d,StartLine:C,EndLine:j,start_line:J,end_line:re,startLine:Re,endLine:ge}=G(k.args),ce=C||J||Re,F=j||re||ge,K=parseInt(ce)||1,q=parseInt(F)||(ce?K+800:800),Le="...",We=q,Q=(d||"").trim().toLowerCase().replaceAll("\\","/");if(Q.startsWith("#skill"))Q.startsWith("#skill/global/fluxflow")||Q.startsWith("#skills/global/fluxflow")||Q.includes("#skill/fluxflow")||Q.includes("#skills/fluxflow")?L="\u2714 Read Documentation":L=`\u2714 Read Skill: ${V.basename(d.replaceAll("\\","/"))}`;else{try{let Y=V.resolve(process.cwd(),d);if(ve.existsSync(Y)){let ut=ve.readFileSync(Y,"utf8").split(`
717
+ `).length;Le=ut,!ce&&!F&&ut>800?We=Math.min(50,ut):We=Math.min(q,ut)}}catch{}let me=(d||"").toLowerCase(),st=me.endsWith(".pdf"),Te=me.endsWith(".docx")||me.endsWith(".doc")||me.endsWith(".ppt")||me.endsWith(".pptx")||me.endsWith(".xls")||me.endsWith(".xlsx"),Ye=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(me);st||Te?L=`${d.length>0?"\u2714":"\u2718"} ${d?`Analyzed: ${V.basename(d)}`:"Analyzed: File Not Found"}`:Ye?L=`${d.length>0?"\u2714":"\u2718"} ${d?`Processed: ${V.basename(d)}`:"Processed: File Not Found"}`:L=`${Le!=="..."?"\u2714":"\u2718"} Read: ${d?`${V.basename(d)} \u2192 ${Le!=="..."?`Lines ${K} - ${We} of ${Le}`:"File Not Found"}`:"File Not Found"}`}}else if(l==="list_files"||l==="read_folder"){let d=l==="list_files"?"List":"Browsed",C=G(k.args).path||null,j=G(k.args).recurse||1;L=`${C?"\u2714":"\u2718"} ${d}: ${C?`${C==="."?`./${j>1?"*":""}`:`${C.replaceAll("\\","/")}${j>1?`${C.endsWith("/")?"*":"/*"}`:`${C.endsWith("/")?"":"/"}`}`}`:"No Folder Selected"}`}else if(l==="find_file"){let d=G(k.args),C=d.basename||d.name||d.path||d.file||d.query||"";L=`${C?"\u2714":"\u2718"} Located: ${C||"No Query"}`}else if(l==="write_file"||l==="update_file"){let d=l==="write_file"?"Created":"Edited",C=G(k.args),j=C.path||null,re=Object.entries(C).some(([Re,ge])=>Re.startsWith("searchContent")&&typeof ge=="string"&&ge.startsWith("^LINE:"))?"\u1361":":";L=`${j?"\u2714":"\u2718"} ${d}${re} ${j?j.replaceAll("\\","/"):"No File Changes"}`}else if(l==="write_pdf"){let d=G(k.args).path||null;L=`${d?"\u2714":"\u2718"} Generated: ${d.replaceAll("\\","/")||"No PDF Generated"}`}else if(l==="write_docx"){let d=G(k.args).path||null;L=`${d?"\u2714":"\u2718"} Generated: ${d.replaceAll("\\","/")||"No Docx Generated"}`}else if(l==="file_map"){let d=G(k.args).path;L=`${d?"\u2714":"\u2718"} Indexed: ${d.replaceAll("\\","/")?""+d:"File Not Found"}`}else if(l.toLowerCase()==="search_keyword"||l.toLowerCase()==="todo")L="";else if(l.toLowerCase()==="generate_image"){let{path:d,outputPath:C,output:j}=G(k.args);L=`\u2714 Generated: ${d||C||j||"generated_image.png"}`}else if(l==="invoke_sync"||l==="InvokeSync"){let d=Gn(l,k.args);L=`\u2714 Called Generalist${d?`: ${d}`:""}`}else if(l==="Invoke"||l==="InvokeAsync"||l==="invoke"){let d=Gn(l,k.args);L=`\u2714 Started Generalist${d?`: ${d}`:""}`}else if(l==="get_progress"||l==="GetProgress"){let d=Gn(l,k.args);L=`\u2714 Checked${d?`: ${d}`:""}`}else if(l==="cancel"){let d=Gn(l,k.args);L=`\u{1F6C7} Cancelled${d?`: ${d}`:""}`}else if(l==="steer"||l==="Steer"){let d=Gn(l,k.args);L=`\u2714 Steered${d?`: ${d}`:""}`}else if(l==="EmergencyRollback"){let{method:d}=G(k.args);L=d==="forceRevert"?"":"\u2714 Rollback Point Checked"}else if(l==="await"||l==="Await"){let{time:d,timeout:C}=G(k.args),j=parseFloat(C||d)||0;j||(j=120);let J=ge=>{if(ge>=60){let ce=Math.floor(ge/60),F=ge%60;return`${ce}m${F>0?` ${F}s`:""}`}return`${ge}s`},re=["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"];L=`\u2714 ${re[Math.floor(Math.random()*re.length)]} \u2192 ${J(j)}`}else l==="Answer"||l==="answer"?L="\u2714 Resolved Sub-Agent Query":l==="exec_command"||l==="ask"?L="":L=`Executed: ${k.toolName}`;if(yield*Pn(),l==="exec_command"){let{command:d}=G(k.args);if(d&&t.systemSettings&&t.systemSettings.allowExternalAccess===!1){let C=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],j=V.resolve(process.cwd()).substring(0,3).toLowerCase(),J=F=>{let K=[],q="",Le=null;for(let We=0;We<F.length;We++){let Q=F[We];Le?(Q===Le&&(Le=null),q+=Q):Q==='"'||Q==="'"?(Le=Q,q+=Q):Q==="&"&&F[We+1]==="&"||Q==="|"&&F[We+1]==="|"?(q.trim()&&(K.push(q.trim()),q=""),We++):Q===";"||Q==="|"||Q==="&"?q.trim()&&(K.push(q.trim()),q=""):q+=Q}return q.trim()&&K.push(q.trim()),K},re=F=>{let K=[],q="",Le=null;for(let We=0;We<F.length;We++){let Q=F[We];Le?(Q===Le&&(Le=null),q+=Q):Q==='"'||Q==="'"?(Le=Q,q+=Q):/\s/.test(Q)?q&&(K.push(q),q=""):q+=Q}return q&&K.push(q),K},Re=F=>{let K=F.replace(/^['"]|['"]$/g,"").trim();return!K||process.platform==="win32"&&/^\/[a-zA-Z0-9?]+$/.test(K)?!1:C.some(q=>{if(q.source==="[a-zA-Z]:[\\\\\\/]"){let Le=K.match(/[a-zA-Z]:[\\\/]/i);return Le&&Le[0].toLowerCase()!==j}return q.test(K)})};if(J(d).some(F=>{let K=re(F);if(K.length===0)return!1;let q=K[0].replace(/^['"]|['"]$/g,"").toLowerCase();if(["echo","printf","write-output"].includes(q)){let We=!1;return K.some(Q=>{let xt=Q.replace(/^['"]|['"]$/g,"");if(xt===">"||xt===">>"||xt==="<")return We=!0,!1;if(xt.startsWith(">")||xt.startsWith("<")){let me=xt.replace(/^[><]+/,"");return Re(me)}return We?(We=!1,Re(Q)):!1})}return K.some(We=>Re(We))})){let F='Access Denied. Prohibited from accessing external directories while "External Workspace Access" is disabled.';t.onExecStart&&t.onExecStart(d||"No Command"),yield{type:"exec_start"},await new Promise(K=>setTimeout(K,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${F}`),await new Promise(K=>setTimeout(K,50)),t.onExecEnd&&t.onExecEnd(),Fe.push({role:"user",text:`[ACTION RESULT]: ERROR: ${F}`}),yield{type:"tool_result",content:`[ACTION RESULT]: ERROR: ${F}`},mt++;continue}}t.onExecStart&&t.onExecStart(d||"No Command"),yield{type:"exec_start"}}let ft=G(k.args),Ln=ft.path||ft.targetPath||null;if(Ln){let d=t.systemSettings&&t.systemSettings.allowExternalAccess===!1,C=V.resolve(Ln),j=V.resolve(process.cwd());if(d&&!C.startsWith(j)){let J="Access Denied. You are not allowed to access files outside the current workspace.";if(l==="write_file"||l==="update_file"){let Re=`\u2718 ${l==="write_file"?"Write Canceled":"Edit Canceled"}: ${ft.path||"..."}`,ge=115;process.stdout.isTTY&&(ge=process.stdout.columns-5||120);let ce=Math.min(Re.length+4,ge),F=`${Re.padEnd(ce-2).substring(0,ce-2)}`;yield{type:"visual_feedback",content:Ut(`${Ve?`
718
+ `:""}${F}
719
+ `)},Ve=!1}Fe.push({role:"user",text:`[ACTION RESULT]: ERROR: ${J}`}),yield{type:"tool_result",content:`[ACTION RESULT]: ERROR: ${J}`},mt++;continue}}if(t.onToolApproval&&(l==="write_file"||l==="update_file"||l==="exec_command")){let C=t.systemSettings||{},j=C.autoExec,J=null,re=!1,Re=!1,ge=!1;if(l==="exec_command"){let{command:me}=G(k.args),st=(me||"").trim(),Te=(Dt,ut)=>{if(!ut)return!1;let Jt=ut.split(",").map(Ft=>Ft.trim().toLowerCase()).filter(Boolean),Ze=Dt.toLowerCase();return Jt.some(Ft=>Ze.startsWith(Ft))},Ye=Te(st,C.alwaysAskCommands),Y=Te(st,C.autoApproveCommands);if(Re=Te(st,C.autoDisallowCommands),Ye?re=!0:(Y||C.autoApproveGit&&/^git\s+commit\b/i.test(st))&&(J="allow"),!re&&!J){if(C.networkAccess===!1){let ut=st.trim().replace(/\s+/g," ").replace(/^['"]+|['"]+$/g,"").toLowerCase().split(" "),Ze=ut[0].split("/").pop().split("\\").pop().replace(/\.exe$/,""),Ft=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"]),et=!1;Ft.has(Ze)&&(et=!0);let ze=Tn=>ut.slice(1).some(gn=>Tn.includes(gn)),nt=Tn=>{let gn=ut.findIndex(hn=>Tn.includes(hn)),$n=ut.findIndex(hn=>["run","exec","test"].includes(hn));return gn!==-1&&!($n!==-1&&$n<gn)};Ze==="git"&&ze(["clone","pull","push","fetch"])&&(et=!0),Ze==="go"&&ze(["get","install"])&&(et=!0),Ze==="npm"&&nt(["install","i","update","add"])&&(et=!0),Ze==="yarn"&&nt(["add","install","upgrade"])&&(et=!0),Ze==="pnpm"&&nt(["add","install","update"])&&(et=!0),Ze==="bun"&&nt(["add","install","update"])&&(et=!0),Ze==="deno"&&ze(["install","add"])&&(et=!0),Ze==="pip"&&ze(["install","download"])&&(et=!0),Ze==="pip3"&&ze(["install","download"])&&(et=!0),Ze==="cargo"&&ze(["install","add"])&&(et=!0),["bash","sh","zsh","fish"].includes(Ze)&&ze(["-c"])&&(et=!0),Ze==="cmd"&&ze(["/c"])&&(et=!0),et&&(J="deny",ge=!0)}!J&&Re&&(J="deny")}!re&&!J&&j&&(J="allow")}else j&&(J="allow");let ce=J,F="";J==="deny"&&(ge?F="network":Re?F="settings":F="prohibited");let K=!1,q="",Le=[],We=0,Q=!1,xt="";if(!ce){if(l==="write_file"||l==="update_file")try{let Te=G(k.args),{path:Ye}=Te;if(Ye){let Y=V.resolve(process.cwd(),Ye),Dt=ze=>ze?ze.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,nt=>nt.toUpperCase()):"",ut=Dt(Y),Jt="",Ze=!1,Ft=await Bn(),et=Dt(Ft?.file_focused);if(Ft&&et===ut&&Ft.full_content?(Jt=Ft.full_content,Ze=!0):ve.existsSync(Y)&&(Jt=ve.readFileSync(Y,"utf8"),Ze=!0),q=Jt,await $o.recordFileChange(Y,Jt),Ze){let ze=Jt;if(l==="write_file"){let nt=Te.content||Te.newContent||"";ze=nt.endsWith(`
720
+ `)?nt:nt+`
721
+ `,xt=ze}else{let{patchPairs:nt,allowMultiple:Tn,error:gn}=yi(Te);if(gn){let Kt=`[ACTION RESULT]: ERROR: ${gn}`;Fe.push({role:"user",text:Kt}),await kt("toolFailure"),t.onToolResult&&t.onToolResult("failure",l),yield{type:"tool_result",content:Kt,toolName:l},mt++;continue}let $n=Te.allowMultiple!==void 0?Te.allowMultiple===!0||String(Te.allowMultiple).toLowerCase()==="true":Tn;We=nt.length;let hn=fr(Jt,nt,{allowMultiple:$n});ze=hn.content,xt=ze,Le=hn.results;let Mo=Le.filter(Kt=>Kt.success),ci=Le.filter(Kt=>!Kt.success);if(Mo.length===0){let Kt=`[ACTION RESULT]: ERROR: Failed to apply patches to [${V.basename(Y)}].
722
+ ${ci.map(at=>` \u2022 ${at.error}`).join(`
723
+ `)}`,di=`\u2714 Edited: ${V.basename(Y.replaceAll("\\","/"))}`,mn=115;process.stdout.isTTY&&(mn=process.stdout.columns-5||120);let Nn=Math.min(di.length+4,mn),ot=`${di.padEnd(Nn-2).substring(0,Nn-2)}`;yield{type:"visual_feedback",content:Ut(`${Ve?`
724
+ `:""}${ot}`)},Ve=!1,Fe.push({role:"user",text:Kt}),await kt("toolFailure"),t.onToolResult&&t.onToolResult("failure",l),yield{type:"tool_result",content:Kt,toolName:l},mt++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${V.basename(Y)}`},Ui(Y,Jt,ze),K=!0,await new Promise(nt=>setTimeout(nt,50))}else if(l==="write_file"){let ze=Te.content||Te.newContent||"",nt=ze.endsWith(`
725
+ `)?ze:ze+`
726
+ `;xt=nt,ve.existsSync(Y)||(Q=!0,ve.mkdirSync(V.dirname(Y),{recursive:!0}),ve.writeFileSync(Y,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${V.basename(Y)}`},Ui(Y,"",nt),K=!0,await new Promise(Tn=>setTimeout(Tn,50))}}}catch(Te){console.error("Simulation/Diff Error:",Te)}let me=null;Bi(Te=>{me=Te});let st=t.onToolApproval;if(ce=await new Promise(async Te=>{let Ye=setInterval(()=>{if(me){let Y=t.onIDEApproval||Qo&&Qo.onIDEApproval;Y&&Y(me),clearInterval(Ye),Te(me)}},100);try{let Y=await st(l,k.args);clearInterval(Ye),Te(Y)}catch{clearInterval(Ye),Te("deny")}}),Bi(null),l==="write_file"||l==="update_file"){let{path:Te}=G(k.args);if(Te){let Ye=V.resolve(process.cwd(),Te);if(Es(Ye,ce),ce==="deny"&&Q&&ve.existsSync(Ye))try{ve.unlinkSync(Ye)}catch{}}}ce==="deny"&&(F="user")}if(ce==="allow"&&K&&Jo()){let{path:me}=G(k.args),st=V.resolve(process.cwd(),me),Te=ot=>ot?V.resolve(ot).replace(/\\/g,"/").toLowerCase():"",Ye=await Bn(),Y="";if(Ye&&Ye.file_focused&&Te(Ye.file_focused)===Te(st)&&Ye.full_content&&(Y=Ye.full_content),!Y&&ve.existsSync(st)){let ot=ve.readFileSync(st,"utf8");ot&&(Y=ot)}!Y&&xt&&(Y=xt),(Y||Q)&&ve.writeFileSync(st,Y,"utf8");let Dt=Y.split(/\r?\n/),ut=Dt.length,Jt=Buffer.byteLength(Y,"utf8"),Ze="";q&&(Ze=`Old File contents:
727
+ ${q.split(/\r?\n/).map((at,nn)=>`${nn+1} | ${at}`).join(`
728
+ `)}
729
+
730
+ `);let Ft="";if(ut<=100)Ft=Dt.join(`
731
+ `);else{let ot=Dt.slice(0,50).join(`
732
+ `),at=Dt.slice(-50).join(`
733
+ `);Ft=`${ot}
734
+
735
+ ... [${ut-100} lines truncated for history stability] ...
736
+
737
+ ${at}`}let et="";if(l==="update_file"){let ot=ur(q,Y,Le,12,t?.compressToolResults||Qo?.systemSettings?.compressToolResults),at=0,nn=[],{patchPairs:Dn}=yi(k.args);Dn&&Dn.length>0?Dn.forEach((lo,co)=>{let Yn=(lo.search||"").trim(),fi=(lo.replace||"").trim(),ea=fi?Y.includes(fi):!0,ta=Yn&&Yn!==fi?!Y.includes(Yn):!0;ea&&(ta||!Yn)?at++:nn.push(` \u2022 Block ${co+1}: No change detected OR user rejected change.`)}):at=Le.length;let kn=nn.length>0?`
738
+
739
+ Notes:
740
+ ${nn.join(`
741
+ `)}`:"";et=`File [${me}] updated via IDE Companion (May have user edits). [${at}/${We}] blocks applied.${kn}
742
+
743
+ ${ot}`}else{let ot=Y.split(/\r?\n/),at=ot.length,nn=Buffer.byteLength(Y,"utf8"),Dn="";q&&(Dn=`Old File contents:
744
+ ${q.split(/\r?\n/).map((co,Yn)=>`${Yn+1} | ${co}`).join(`
745
+ `)}
746
+
747
+ `);let kn="";if(at<=100)kn=ot.join(`
748
+ `);else{let lo=ot.slice(0,50).join(`
749
+ `),co=ot.slice(-50).join(`
750
+ `);kn=`${lo}
751
+
752
+ ... [${at-100} lines truncated] ...
753
+
754
+ ${co}`}et=`File [${me}] saved via IDE Companion (May have user edits).
755
+ - Stats: [${at} lines, ${(nn/1024).toFixed(1)} KB]
756
+ ${Dn}- Content Preview:
757
+
758
+ ${kn}`}let ze=l==="write_file"?"Created":"Edited",nt=G(k.args),gn=Object.entries(nt).some(([ot,at])=>ot.startsWith("searchContent")&&typeof at=="string"&&at.startsWith("^LINE:"))?"\u1361":":",$n=`${me?"\u2714":"\u2718"} ${ze}${gn} ${me?me.replaceAll("\\","/"):"No File Changes"}`,hn=115;process.stdout.isTTY&&(hn=process.stdout.columns-5||120);let Mo=Math.min($n.length+4,hn),ci=`${$n.padEnd(Mo-2).substring(0,Mo-2)}`;yield{type:"visual_feedback",content:Ut(`${Ve?`
759
+ `:""}${ci}`)},Ve=!1;let Kt=Date.now();qt=Kt,yield{type:"tool_time",content:Kt-_};let mn=(et||"").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.
760
+ `));let Nn;if(mn.startsWith("[[SAME]]")){let at=mn.replace(/^\[\[SAME\]\]\s*\r?\n?/,"").split(/\r?\n/),nn=at.filter(kn=>kn.startsWith("File ")||kn.trim().startsWith("- Stats:"));Nn=`[ACTION RESULT]: ${nn.length>0?nn.join(`
761
+ `):at.slice(0,2).join(`
762
+ `)}
763
+ [SYSTEM NOTE]: Content verified and persisted to disk. Full preview omitted to conserve context.`}else Nn=`[ACTION RESULT]: ${mn}`;Fe.push({role:"user",text:Nn}),dn=!0,await kt("toolSuccess"),t.onToolResult&&t.onToolResult("success",l),yield{type:"tool_result",content:et,aiContent:Nn,toolName:l},mt++;continue}if(ce==="deny"){let me=`Permission Denied: Prohibited ${l==="exec_command"?"Command":"file edit"}.`;if(F==="user"?me="Permission Denied by User":F==="settings"?me="Permission Denied by User Policy":F==="network"?me="Permission Denied: Sandbox Network Access Disabled by User Policy.":F==="prohibited"&&l==="exec_command"&&(me="Permission Denied: Prohibited Command in User Policy"),l==="write_file"||l==="update_file"){let Te=`\u2718 ${l==="write_file"?"Write Cancelled":"Edit Denied"}: ${G(k.args).path.replaceAll("\\","/")||"..."}`,Ye=115;process.stdout.isTTY&&(Ye=process.stdout.columns-5||120);let Y=Math.min(Te.length+4,Ye),Dt=`${Te.padEnd(Y-2).substring(0,Y-2)}`,ut=` ${" ".repeat(Y)} `;yield{type:"visual_feedback",content:Ut(`${Ve?`
764
+ `:""}${Dt}
765
+ `)},Ve=!1}l==="exec_command"&&(await new Promise(st=>setTimeout(st,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${me}`),await new Promise(st=>setTimeout(st,50)),t.onExecEnd&&t.onExecEnd()),Fe.push({role:"user",text:`[ACTION RESULT]: DENIED: ${me}`}),yield{type:"tool_result",content:`[ACTION RESULT]: DENIED: ${me}`},await kt("toolDenied"),t.onToolResult&&t.onToolResult("denied",l),mt++;continue}}if(L){let d=115;process.stdout.isTTY&&(d=process.stdout.columns-5||120);let C=await i(),j=!1;C&&(j=C.trim().length>0);let J=Math.min(L.length+4,d),re=`${L.padEnd(J-2).substring(0,J-2)}`;yield{type:"visual_feedback",content:Ut(`${Ve?`
766
+ `:""}${re}${L.includes("\u2714")&&(L.includes("Created")||L.includes("Edited"))?"":`${j?"":`
767
+ `}`}`)},Ve=!1}if(qt>0){let d=Date.now()-qt,C=Math.max(0,1e3-d);C>0&&await new Promise(j=>setTimeout(j,C))}let Sn={chatId:h,history:n,onChunk:d=>t.onExecChunk?t.onExecChunk(d):null,onAskUser:t.onAskUser,systemSettings:t.systemSettings,mode:a,isMultiModal:it(z),onVisualFeedback:t.onVisualFeedback,onSubagentUpdate:t.onSubagentUpdate,onTokenChunk:t.onTokenChunk,modelName:z,aiProvider:t.aiProvider,apiKey:t.apiKey,onUsage:t.onUsage};if(l==="write_file"||l==="update_file")try{let{path:d}=G(k.args);if(d){let C=V.resolve(process.cwd(),d),j=await Bn();j&&j.file_focused===C&&j.full_content&&(Sn.forcedContent=j.full_content)}}catch{}qe.push(l);let xe=await ko(l,k.args,Sn);if((l==="write_file"||l==="update_file")&&!xe.startsWith("ERROR:")){let{path:d}=G(k.args);if(d){let C=V.resolve(process.cwd(),d);As(C)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let Ot=Date.now();qt=Ot,yield{type:"tool_time",content:Ot-_},dt=Ot;let Nt=null;if(typeof xe=="object"&&xe.binaryPart&&(Nt=xe.binaryPart,xe=xe.text),l==="search_keyword"){let{keyword:d,path:C}=G(k.args),j=typeof xe=="string"&&xe.startsWith("[GLOB]");j&&(xe=xe.slice(6).trimStart());let J=typeof xe=="string"&&xe.startsWith("[DIR]");J&&(xe=xe.slice(5).trimStart());let re=0;if(xe){let Q=xe.match(/Found (\d+) match/i);Q&&(re=parseInt(Q[1]))}let Re=(C||"").trim().toLowerCase().replaceAll("\\","/"),ge=Re==="#doc"||Re==="#docs"||Re==="#documentation"||Re.includes("#skill/global/fluxflow")||Re.includes("#skill/fluxflow")||Re.includes("#skills/fluxflow")||Re.includes("#skills/global/fluxflow"),ce,F=115;process.stdout.isTTY&&(F=process.stdout.columns-5||120);let K=Math.max(10,(F+5)/3),q=Math.max(10,(F+5)/4);if(ge)ce=`${d?"\u2714":"\u2718"} Searched Documentation`;else{let Q=C?C.replace(/[\/\\]+$/,""):null,xt=Q&&Q!=="."?`${j?C:J?`${Q}/*`:Q}`:"./",me=xt.length>q?`${xt.slice(0,q)}...`:xt;ce=`${d?"\u2714":"\u2718"} Searched: "${d?d.length>F/3?`${d.slice(0,K)}...`:d:""}" in "${me.replaceAll("\\","/")}" \u2192 ${re} Match${re===1?"":"es"}`}let Le=Math.min(ce.length+4,F),We=`${ce.padEnd(Le-2).substring(0,Le-2)}`;yield{type:"visual_feedback",content:Ut(`${Ve?`
768
+ `:""}${We}
769
+ `)},Ve=!1}if(l==="EmergencyRollback"){let{method:d}=G(k.args);if(d==="forceRevert"){let C=0;if(xe){let K=xe.match(/Total\s*:\s*(\d+)/i);K&&(C=parseInt(K[1]))}let J=xe&&xe.startsWith("ERROR:")?"\u2718 Emergency Rollback Failed":`\u2714 Emergency Rollback \u2192 ${C} file${C===1?"":"s"} processed`,re=115;process.stdout.isTTY&&(re=process.stdout.columns-5||120);let Re=await i(),ge=!1;Re&&(ge=Re.trim().length>0);let ce=Math.min(J.length+4,re),F=`${J.padEnd(ce-2).substring(0,ce-2)}`;yield{type:"visual_feedback",content:Ut(`${Ve?`
770
+ `:""}${F}${ge?"":`
771
+ `}`)},Ve=!1}}if(l==="todo"){let{method:d,tasks:C,markDone:j}=G(k.args),J="",re=[],Re=ge=>{if(!ge)return[];let ce=Array.isArray(ge)?ge:[];if(ce.length===0&&typeof ge=="string"){let F=ge.trim();if(F.startsWith("[")&&F.endsWith("]")){let K=F.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);K?ce=K.map(q=>q.slice(1,-1).replace(/\\(.)/g,"$1")):ce=F.slice(1,-1).split(",").map(q=>q.trim()).filter(Boolean)}else ce=ge.split(`
772
+ `)}return ce.filter(F=>String(F).trim()).map(F=>{let K=String(F).trim();return K.startsWith("- [")?K.substring(6).trim():K})};if(d==="create"?(J="\x1B[32m\u2192\x1B[0m Created Goals",re=Re(C).map(ge=>`\x1B[90m\u25CB\x1B[0m ${ge}`)):d==="append"?(J="\x1B[34m\u2795\x1B[0m Added New Goals",re=Re(C).map(ge=>`\x1B[90m\u25CB\x1B[0m ${ge}`)):d==="get"&&(J=j?"\x1B[36m\u21BB\x1B[0m Updated Goals":"\x1B[35m\u2022\x1B[0m Reviewed Goals",re=(xe||"").split(`
773
+ `).slice(1).join(`
774
+ `).split(`
775
+ `).filter(ce=>ce.trim().startsWith("- [")).map(ce=>{let F=ce.trim(),K=F.startsWith("- [x]");return`${K?"\x1B[32m\u2714\x1B[0m":"\x1B[90m\u25CB\x1B[0m"} ${K?"\x1B[90m":"\x1B[37m"}${F.substring(6).trim()}\x1B[0m`})),J&&re.length>0){let ge=[`${J}`,...re.map(K=>` ${K}`)].join(`
776
+ `),ce=await i(),F=!1;ce&&(F=ce.trim().length>0),yield{type:"visual_feedback",content:Ut(`${Ve?`
777
+ `:""}${ge}${F?"":`
778
+ `}`)},Ve=!1}}l==="exec_command"&&t.onExecEnd&&(await new Promise(d=>setTimeout(d,800)),t.onExecEnd());let fn=xe&&xe.startsWith("DENIED:");xe&&!xe.startsWith("ERROR:")&&!fn?(await kt("toolSuccess"),t.onToolResult&&t.onToolResult("success",l)):fn||(await kt("toolFailure"),t.onToolResult&&t.onToolResult("failure",l));let Pt=(xe||"").toString().replaceAll("\u2550".repeat(88),"=".repeat(35)).replaceAll("[UI_CONTEXT]","");Pt.includes("[[VERIFIED]]")&&(Pt=Pt.replace(/\[\[VERIFIED\]\][\s\S]*?\[\[\/VERIFIED\]\]/g,`[SYSTEM NOTE]: Patch Block matched & applied successfully. Large Block omitted to save tokens.
779
+ `));let un;if(Pt.startsWith("[[SAME]]")){let C=Pt.replace(/^\[\[SAME\]\]\s*\r?\n?/,"").split(/\r?\n/),j=C.filter(re=>re.startsWith("File ")||re.trim().startsWith("- Stats:"));un=`[ACTION RESULT]: ${j.length>0?j.join(`
780
+ `):C.slice(0,2).join(`
781
+ `)}
782
+ [SYSTEM NOTE]: Content verified and persisted to disk. Full preview omitted to save tokens.`}else un=`[ACTION RESULT]: ${Pt}`;Fe.push({role:"user",text:un,binaryPart:Nt}),dn=!0;let Se=`[ACTION RESULT]: ${xe.replaceAll(`[[VERIFIED]]
783
+ `,"").replaceAll(`
784
+ [[/VERIFIED]]`,"")||""}`;(l==="view_file"||l==="web_scrape"||l==="file_map")&&(Se=`[ACTION RESULT]: ${L} (Context Locked for UI Clarity)`),yield{type:"tool_result",content:Se,aiContent:un,binaryPart:Nt,toolName:l},l==="memory"&&!xe.startsWith("ERROR:")&&(yield{type:"memory_updated"}),mt++}if(r==="Google"&&tn&&Date.now()-si>=150){yield*Pn();let k=so(tn);for(let _ of k)yield _;tn="",si=Date.now()}}p.usageMetadata&&(zt=p.usageMetadata),zt&&(yield{type:"liveTokens",content:zt.totalTokenCount})}if(oe&&(oe=!1,tt?Ee+="</think>":(le+="</think>",r==="Google"?tn+="</think>":yield{type:"text",content:"</think>"})),tt&&Ee.length>0){let p=0,P=Math.min(pt.length,Ee.length);for(let $=P;$>0;$--)if(pt.endsWith(Ee.substring(0,$))){p=$;break}let R=Ee.substring(p);if(R){let U=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(pt)?R.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):R.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(U)if(le+=U,r==="Google")tn+=U;else{yield*Pn();let N=so(U);for(let W of N)yield W}}tt=!1,Ee=""}if(yield*Pn(),ht)break;let ao=(le||"").trim(),zs=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(ao.toLowerCase())||/\[\[END\]\]/i.test(ao.toLowerCase()),qs=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(ao.toLowerCase()),Xs=Fe.length>0||O!==null,ai=Wt(ao).trim(),Js=/(\p{Emoji_Presentation}|\p{Extended_Pictographic})$/u.test(ai),Qs=/([.!?"'*_`|\]\)”’~~]+|\s|`{3}|[\u200B-\u200D\uFEFF])$/u.test(ai.trim()),Zs=/[.!?}"'`’“”]$|```$/s.test(ai)||Qs||Js;!zs&&!qs&&!Xs&&ao.length>0,Xe=!0,await kt("agent",r)}catch(ae){if(ht){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
785
+
786
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(String(ae).includes("Incomplete JSON segment at the end")){oe&&(oe=!1,tt?Ee+="</think>":(le+="</think>",yield{type:"text",content:"</think>"})),Xe=!0,await kt("agent",r);break}if(oe&&(oe=!1,tt?Ee+="</think>":le+="</think>"),tt&&Ee.length>0){let Mt=0,St=Math.min(pt.length,Ee.length);for(let At=St;At>0;At--)if(pt.endsWith(Ee.substring(0,At))){Mt=At;break}let yt=Ee.substring(Mt);if(yt){let Qe=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(pt)?yt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):yt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");Qe&&(le+=Qe)}tt=!1,Ee=""}let B=ae instanceof Error?(()=>{try{return JSON.parse(JSON.parse(ae.message).error.message).error.message}catch{return String(ae)}})():String(ae),It=new Date().toLocaleString(),bt=V.join(En,"agent");ve.existsSync(bt)||ve.mkdirSync(bt,{recursive:!0}),ve.appendFileSync(V.join(bt,"error.log"),`ERROR [${It}]: ${B}
787
+
788
+ ----------------------------------------------------------------------
789
+
790
+ `);let wt=ae.status||ae.statusCode||ae.code,Vt=String(ae).includes("replicas at capacity");if(!(wt&&(wt>=500&&wt<600||wt===408||wt===429||Vt)||!wt&&(/status[ :]+(5\d\d|408|429)/i.test(String(ae))||/code[ :]+(5\d\d|408|429)/i.test(String(ae))||/(500|503|408|429)/.test(String(ae))))){if(je<en-3)throw ae;yield{type:"text",content:B},yield{type:"status",content:"Error Occured"}}if(le.trim().length>0||Je>1)if(Je<=en){Je++;let Mt=Math.min(1e3*Math.pow(2,Je-1),24e3);if(le.trim().length>0){x.push({role:"agent",text:le});let St=`[system]
791
+ - seamless continuation: resume immediately. pick up from last words with zero gap/disruption
792
+ - no repetition: do not repeat any text already written
793
+ - no re-think: do not restart or open <think> if reasoning already started. continue the thinking and close thinking block </think> before chat output
794
+ - mid-tool safety: if cutoff was mid-tool call, restart that tool call from start
795
+ - stealth: do not mention/apologize for cutoff [/system]`;Fe.length>0?Fe.forEach((yt,At)=>{At===Fe.length-1?x.push({...yt,text:`${yt.text}
796
+
797
+ ${St}`}):x.push(yt)}):x.push({role:"user",text:St}),pt+=le}for(let St=Mt/1e3;St>0&&!ht;St--)yield{type:"status",content:`Error Occured. Recovering Stream (${Je}/${en}) [Retrying in ${St.toFixed(0)}s]...`},await new Promise(yt=>setTimeout(yt,1e3));yield{type:"status",content:"Error Occured. Recovering Stream..."}}else throw new Error(`Stream collapsed too many times. (Failed to resolve ${en} times)
798
+ Error log can be found in \`/export logs\``);else if(je<=en){je++,Je=1,pt="";let Mt=Math.min(1e3*Math.pow(2,je-1),32e3),St=.8+Math.random()*.4,yt=Math.round(Mt*St);bn=!0,yield{type:"status",content:`Trying to reach ${e} (${je}/${en}) [Retrying in ${(yt/1e3).toFixed(0)}s]`};for(let At=yt/1e3;At>0&&!ht;At--)yield{type:"status",content:`Trying to reach ${e} (${je}/${en}) [Retrying in ${At.toFixed(0)}s]`},await new Promise(Qe=>setTimeout(Qe,1e3));yield{type:"status",content:`Trying to reach ${e}`}}else throw new Error(`Model ${e} cannot be reached. (Failed ${en} times)
799
+ Error log can be found in \`/export logs\``)}}if(zt){let oe=zt.totalTokenCount||0,ae=zt.cachedContentTokenCount||0,B=(zt.candidatesTokenCount||0)+(r==="Google"&&zt.thoughtsTokenCount||0);await gt("tokens",oe,r,z),ae>0&&await gt("cachedTokens",ae,r,z),B>0&&await gt("candidateTokens",B,r,z),we!==null&&we>0&&await gt("ttft",we,r,z),ho({provider:r,model:z,prompt:zt.promptTokenCount||0,cached:ae,output:B,reasoning:zt.thoughtsTokenCount||0,ttft:we}),yield{type:"usage",content:zt}}else we!==null&&we>0&&(await gt("ttft",we,r,z),ho({provider:r,model:z,prompt:0,cached:0,output:0,reasoning:0,ttft:we}));le=$s(le),ii.push(le);let za=Wt(le),ri=Ms(le),Hs=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(ri.toLowerCase())||/\[\[END\]\]/i.test(ri.toLowerCase())||!0,qa=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(ri.toLowerCase()),Xa=mt>0;yield{type:"status",content:"Thinking"};let js=Ga(le,/(\[\s*(turn\s*:)?\s*(continue|finish)\s*\]|\[\[END\]\])/gi,"").trim(),On=(Hs||Fe.length===0)&&!_t&&!Mn&&!$t;if(On=Fe.length===0?On:!1,On=jt||_o?!1:On,le&&le.trim().endsWith('")]')&&Fe.length===0&&(On=!1),On){ir=!0;let oe=ii.join(`
800
+ `),ae=Wt(oe).trim();yield{type:"interactive_turn_finished",data:{agentText:Ie,fullAgentTextRaw:oe,history:[...x],needTitle:_e}},x.length>0&&x[x.length-1].role==="agent"?x[x.length-1].text=ae:x.push({role:"agent",text:ae}),x.forEach(B=>{if(B.role==="user"&&B.text&&(B.text=B.text.replace(/\n\[COMPILE ERROR\][\s\S]*?\[\/ERROR\]/g,""),B.text=B.text.replaceAll(`
801
+
802
+ [system] user question. resolve this specific query within '[ANSWER] ... [/ANSWER]' concisely, naturally [/system]
803
+ `,"").replaceAll(`[system] user question. resolve this specific query within '[ANSWER] ... [/ANSWER]' concisely, naturally
804
+ **strictly follow thinking policy as high priority. do not start a response without <think>...</think>** [/system]
805
+ `,"").replaceAll(`[system] **strictly follow thinking policy as high priority. do not start a response without <think>...</think>** [/system]
806
+ `,"").replaceAll(/\n\[system\] WARNING, Turn Limit Impending: Step \d+\/\d+\. Wrap up quickly\/prompt user to continue & use \[\[END\]\] quickly\. \[\/system\]/g,""),B.text=B.text.replaceAll(/\n\[system\] File Changes:\n(?:\* .+ \(created|modified|deleted\)\n)*\[\/system\]/g,""),(r==="Mistral"||r==="Google"&&e?.toLowerCase().startsWith("gemma"))&&(B.text.startsWith("[ACTION RESULT]")||B.text.startsWith("[TOOL RESULT]")))){let bt=`
807
+ [system] Action result received. Analyze output and proceed with your turn [/system]`,wt=`
808
+ [system] Action result received. Analyze output and proceed with your turn. **strictly follow thinking policy. do not start a response without <think>...</think>** [/system]`;B.text=B.text.replaceAll(wt,"").replaceAll(bt,"").trim()}}),yield{type:"status",content:"[end]"}}if(On)break;let Vs=js.trim()||"*Working...*";if(x.push({role:"agent",text:Vs}),Fe.length>0||dn){if(Fe.length>0){let oe=Fe.map(Vt=>Vt.text).join(`
809
+
810
+ `),It=(Wt(le).replace(/\[{1,2}(?:tool|action):[\s\S]*?\)\s*\]{1,2}/gi,"").match(/\[(?:tool|action):/gi)||[]).length,bt=Fe.length+It;if(Fe.length<bt){oe+=`
811
+
812
+ [system] Only ${Fe.length} out of ${bt} attempted tool calls were executed. Verify proper structure compliance & try failed calls again [/system]`;let Vt=bt-Fe.length;for(let Pe=0;Pe<Vt;Pe++)await kt("toolFailure")}let wt=Fe.find(Vt=>Vt.binaryPart)?.binaryPart||null;x.push({role:"user",text:oe,binaryPart:wt})}}else if(!ht){let ae=(le.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/i,"").match(/\[(?:tool|action):/gi)||[]).length;_o||jt||ae>0?(x.push({role:"user",text:`[system] Failed to execute ${ae} tool${ae>1?"s":""}. Verify proper structure compliance [action:ActionName(...)] & try again [/system]`}),await kt("toolFailure"),yield{type:"visual_feedback",content:`
813
+ ${Ut("\u2718 Execution Error")}
814
+ `}):(yield{type:"visual_feedback",content:`
815
+ ${Ut("\u2718 Loop Detected")}
816
+ `},x.push({role:"user",text:`[system] ${Mn&&!_t?"Stuttering Detected by Internal System. Re-calibrate your response & proceed.":`${_t?" Over Thinking":" Loop"} Detected by Internal System${_t?" for current Effort Level":""}. ${_t?"If you have planned the task, prioritize execution/output":"If you have finished your task provide a simple summary and end"}`} [/system]`})),_t=!1,Mn=!1,$t=!1}u?.advanceRollback&&await mo.recordTurnDelta(h,M+1,qe),_o=mt>0||dn}if(!ir&&!ht){let M="\u2726 Turn safety limit reached. Stopping execution.";yield{type:"text",content:`
817
+
818
+ ${M}
819
+ `};let Ue=(ii.join(`
820
+ `)+`
821
+ ${M}`).trim();yield{type:"interactive_turn_finished",data:{agentText:Ie,fullAgentTextRaw:Ue,history:[...x],needTitle:_e}},yield{type:"status",content:"[end]"}}}catch(S){let x=S?.cause?` (Cause: ${S.cause?.message||String(S.cause)})`:"",Me=(S instanceof Error?(()=>{try{return JSON.parse(JSON.parse(S.message).error.message).error.message}catch{return(S.message?`${S.message}${x}`:"")||String(S)}})():String(S)).replace(/^(Error:\s*)+/i,"");r==="Google"&&!/^[A-Z0-9_\-\s]+ ERROR:/i.test(Me)&&(Me=`GEMINI ERROR: ${Me}`);let Gt=new Date().toLocaleString(),sn=V.join(En,"agent");yield{type:"text",content:`
822
+
823
+ \u2726 CRITICAL ERROR: ${Me.includes("fetch failed")?"Failed to Connect. Check your Internet Connection or Wait a moment":Me}
824
+ \u2800`},ve.existsSync(sn)||ve.mkdirSync(sn,{recursive:!0}),ve.appendFileSync(V.join(sn,"error.log"),`CRITICAL ERROR [${Gt}]: ${S}${S?.cause?`
825
+ CAUSE: ${S.cause?.stack||S.cause}`:""}
826
+
827
+ ----------------------------------------------------------------------
828
+
829
+ `),typeof flushGoogleBuffer=="function"&&(yield*flushGoogleBuffer()),yield{type:"tool_result",content:`ERROR: [INTERNAL CRITICAL] ${Me}`}}finally{he&&(clearInterval(he),he=null),typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),await $o.commitTransaction(),u?.advanceRollback&&await mo.cleanup(h),await Bn()}yield{type:"status",content:null}},td=async(e,n,t=null,i=null,o=50,s=null,c=!1)=>{let a=await go(),g={...a,...n},h=process.env.SUBAGENT_MODEL?process.env.SUBAGENT_MODEL.trim():null,y=process.env.SUBAGENT_PROVIDER?process.env.SUBAGENT_PROVIDER.trim():null,u=new Date,m=`${u.getFullYear()}-${u.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(u.getDate()).padStart(2,"0")}, ${u.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}).replace(":","-")}`,f=(he=>{if(!he)return null;let S=he.toLowerCase();return S==="google"?"Google":S==="deepseek"?"DeepSeek":S==="openrouter"?"OpenRouter":S==="nvidia"?"NVIDIA":S==="mistral"?"Mistral":S==="ollama"?"Ollama":S==="inferx"?"InferX":S==="sensenova"?"SenseNova":S==="poolside"?"Poolside":S==="9router"||S==="9Router"?"9router":S==="aihubmix"||S==="aihub"?"AIHubMix":S==="explabs"||S==="experientiallabs"||S==="experimentallabs"?"ExpLabs":S==="tokenharbor"||S==="token harbor"||S==="token_harbor"||S==="thk"?"TokenHarbor":S==="infron"?"Infron":S==="apinex"||S==="apx"?"APInex":S==="c_openai"||S==="custom_openai"||S==="custom (openai)"||S==="custom"?"c_openai":null})(y),w=g?.systemSettings?.CustomSubAgent?g?.systemSettings?.SubAgentModel:null,pe=g?.systemSettings?.CustomSubAgent?g?.systemSettings?.SubAgentProvider:null,b=null;if(w==="ENV"?(b=h,h&&f&&(g.aiProvider=f)):w&&w!=="Default"?(b=w,pe&&(g.aiProvider=pe)):h&&f&&(g.aiProvider=f),g.aiProvider){let he=await hi(g.aiProvider);he&&(g.apiKey=he)}let v=he=>{if(!he||typeof he!="string")return{allowed:!0};let S=[/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 x of S)if(x.test(he))return{allowed:!1,reason:`Blocked potentially destructive or unsafe command pattern: "${x.source}"`};return{allowed:!0}},ie=t||b||n?.modelName||n?.activeModel||a.activeModel,ee=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",te=`-- ACTIONS (path = relative to CWD, path separator: '/') --
830
+ In chat output the format \`[action:ActionName(arg1="value1")]\` in NEW line
831
+ Rules:
832
+ - JSON escape literal sequences, backslash: \\\\, newLine: \\ n
833
+ - Same file, multiple edits? ONE PatchFile (\u226415 blocks)
834
+ - Need text or huge file? CodeSearch > Full Read
835
+ - Avoid unnecessary large file chunk reads
836
+ - Stuck on syntax error? Tell user > waste time
837
+
838
+ # Provided Actions
839
+ **Communication**
840
+ - AskUser(question=string, optionA?="title::description", ...MAX4). Any Ambiguity
841
+ ${c?"- AskMain(question=string). Communicate with PARENT/MAIN AGENT. When clarification/decision is needed for a task":""}
842
+
843
+ **Web**
844
+ - WebSearch(query=string, aiMode?=bool:false, limit?=int[3..10]). Proactive use for unknown/latest info. aiMode: exclude limit
845
+ - WebScrape(url=string). Proactive use for specific webpage/docs
846
+
847
+ **Workspace**
848
+ - CodeSearch(keyword=string, path?="dir/file/glob, inclusion/exclusion ;-separated", regex?=bool:auto). Find relevant code
849
+ - ReadFolder(path=string, recurse?=int[1..3]). Minimize recursion
850
+ - FindFile(basename=string). Find file path. Extention optional
851
+ - ReadFile(path=string, startLine?=int, endLine?=int)
852
+ - 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
853
+ - WriteFile(path=string, content=string). Creates/Overwrites. File Exist? PatchFile > WriteFile
854
+ - Run(command=string). Runs ${ee==="Windows"?gr()?"powershell":"windows CMD":"bash"} command. Destructive command \u2192 Ask user`.trim(),I=`=== START SYSTEM PROMPT ===
855
+ Identity: FluxFlow subagent helping the main Agent
856
+ Your task is: "${e}"
857
+ CWD: ${process.cwd()}
858
+
859
+ ${te.trimEnd()}
860
+
861
+ -- THINKING GUIDANCE --
862
+ NO EXPLICIT THINKING REQUIRED. FOCUS ON TASK COMPLETION
863
+ Main focus: actions and task, not chatting
864
+ On completion, provide a detailed summary in Tables/Markdown Format with file modified info. If any task failed report back in detail
865
+
866
+ Current Time: ${m}
867
+ === END SYSTEM PROMPT ===`,$e=[{role:"user",text:`Complete this task: ${e}`}],_e=0,Ie="";for(;_e<o;){let he=await mi("subagent",g);if(!he.allowed)throw new Error(he.reason||`Budget Exhausted for Provider (${g?.aiProvider||"Subagent"})`);if(ht){if(n?.taskId&&typeof Bt<"u"){let T=Bt.find(E=>E.id===n.taskId);T&&(T.status="cancelled")}throw s&&s("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}if(n?.taskId&&typeof Bt<"u"){let T=Bt.find(E=>E.id===n.taskId);if(T&&T.status==="cancelled")throw s&&s("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}let S=$e.map(T=>({role:T.role==="user"?"user":"model",parts:[{text:T.text}]}));s&&s(`[Subagent Turn ${_e+1}]...`);let x=["Fast","Low","Medium","High"],lt=process.env.SUBAGENT_THINKING,Me=x.includes(lt)?lt:"Low",sn=(await Zo(g,ie,S,I,Me)).text||"",Rt=$s(Wt(sn).trim());Ie=Rt,s&&s(`[Subagent Response]
868
+ ${Rt}
869
+ `),$e.push({role:"agent",text:Rt});let Yt=Ro(Rt);if(Yt.length===0)break;let an=Yt.filter(T=>T.toolName.toLowerCase()==="askmain"||T.toolName.toLowerCase()==="ask_main"),Ne=!1,Ct="";for(let T of Yt){if(ht){if(n?.taskId&&typeof Bt<"u"){let A=Bt.find(D=>D.id===n.taskId);A&&(A.status="cancelled")}throw new Error("Subagent task was cancelled.")}if(n?.taskId&&typeof Bt<"u"){let A=Bt.find(D=>D.id===n.taskId);if(A&&A.status==="cancelled")throw new Error("Subagent task was cancelled.")}let E=T.toolName.toLowerCase();if(E==="askuser"&&(E="ask"),E==="askmain"||E==="ask_main"){if(Ne)continue;Ne=!0;let A="";if(an.length===1?A=G(an[0].args).question||an[0].args:A=an.map((D,ue)=>{let ke=G(D.args);return`Q${ue+1}: ${ke.question||D.args}`}).join(`
870
+ `),n.onAskMain){s&&s(`[Executing Tool] AskMain("${A}")...`);let D=await n.onAskMain(A);s&&s(`[Action Result]
871
+ Answer from Main Agent: ${D}
872
+ `),Ct+=`[ACTION RESULT for AskMain]: Answer from Main Agent: ${D}
873
+
874
+ `,await kt("toolSuccess")}else Ct+=`[ACTION RESULT for AskMain]: ERROR: Main agent communication channel not available.
875
+
876
+ `;continue}if(!(i?i.some(A=>A.toLowerCase()===E):!0)){let A=`ERROR: Tool [${T.toolName}] is not in the allowed tools list for this subagent.`;s&&s(`[Blocked Tool Call] ${T.toolName} - not allowed
877
+ `),Ct+=`${A}
878
+
879
+ `;continue}if(E==="exec_command"||E==="execcommand"||E==="run"){let A=G(T.args).command||"",D=v(A);if(!D.allowed){let ue=`ERROR: [SECURITY RESTRICTION] Subagent execution blocked command: ${D.reason}`;s&&s(`[Blocked Command] ${A} - ${D.reason}
880
+ `),Ct+=`${ue}
881
+
882
+ `;continue}}let ne="";if(E==="web_search"||E==="websearch")ne=`\u2714 \x1B[95mSearched\x1B[0m: ${G(T.args).query||""}`;else if(E==="web_scrape"||E==="webscrape")ne=`\u2714 \x1B[95mScraped\x1B[0m: ${G(T.args).url||""}`;else if(E==="search_keyword"||E==="searchkeyword"||E==="codesearch"||E==="code_search"){let A=G(T.args),D=A.keyword||"",ue=A.path||"";ne=`${D?"\u2714":"\u2718"} \x1B[95mSearched\x1B[0m: ${D||"No Query"}${ue?` \u2192 ${ue.replaceAll("\\","/")}`:""}`}else if(E==="view_file"||E==="viewfile"||E==="readfile")ne=`\u2714 \x1B[95mRead\x1B[0m: ${(G(T.args).path||"").replaceAll("\\","/")}`;else if(E==="find_file"||E==="findfile"){let A=G(T.args),D=A.basename||A.name||A.path||A.file||A.query||"";ne=`${D?"\u2714":"\u2718"} \x1B[95mLocated\x1B[0m: ${D||"No Query"}`}else if(E==="list_files"||E==="read_folder"||E==="readfolder"){let A=G(T.args).path||null,D=G(T.args).recurse||0;ne=`${A?"\u2714":"\u2718"} \x1B[95mBrowsed\x1B[0m: ${A?`${A.replaceAll("\\","/")}${D>0?`${A.endsWith("/")?`*${D}`:`/*${D}`}`:`${A.endsWith("/")?"":"/"}`}`:""}`}else if(E==="write_file"||E==="writefile"){let A=G(T.args).path||null;ne=`${A?"\u2714":"\u2718"} \x1B[95mCreated\x1B[0m: ${A?`${A.replaceAll("\\","/")}`:"No File Changes"}`}else if(E==="update_file"||E==="updatefile"||E==="patchfile"||E==="patch_file"){let A=G(T.args),D=A.path||null,ke=Object.entries(A).some(([Ae,Oe])=>Ae.startsWith("searchContent")&&typeof Oe=="string"&&Oe.startsWith("^LINE:"))?"\u1361":":";ne=`${D?"\u2714":"\u2718"} \x1B[95mEdited\x1B[0m${ke} ${D?`${D.replaceAll("\\","/")}`:"No File Changes"}`}else if(E==="exec_command"||E==="execcommand"||E==="run"){let A=G(T.args).command||null;ne=`${A?"\u2714":"\u2718"} \x1B[95mExecuted\x1B[0m: ${A?A.slice(0,100)+(A.length>100?"...":""):"No Command"}`}else if(E==="file_map"||E==="filemap"){let A=G(T.args).path||"";ne=`${A?"\u2714":"\u2718"} \x1B[95mIndexed\x1B[0m: ${A?`${A.replaceAll("\\","/")}`:"File Not Found"}`}else if(E==="await"){let{time:A}=G(T.args),D=parseFloat(A)||0;D<10&&(D=10),D>180&&(D=180),ne=`\u2714 \x1B[95mAwaiting\x1B[0m \u2192 ${(ke=>{if(ke>=60){let Ae=Math.floor(ke/60),Oe=ke%60;return`${Ae}m${Oe>0?` ${Oe}s`:""}`}return`${ke}s`})(D)}`}else{let A=Yi[E]||T.toolName,D=Gn(E,T.args);ne=`\u2714 \x1B[95m${A}\x1B[0m${D?`: ${D}`:""}`}n.onVisualFeedback&&ne&&n.onVisualFeedback(ne),s&&s(`[Executing Tool] ${T.toolName}(${T.args})...`);try{let A=await ko(T.toolName,T.args,{...n,mode:"Flux"});if(s&&s(`[Action Result]
883
+ ${A}
884
+ `),Ct+=`[ACTION RESULT for ${T.toolName}]: ${A}
885
+
886
+ `,await kt("toolSuccess"),E==="patchfile"||E==="update_file"||E==="updatefile"||E==="patch_file"){if(A){let D=A.split(`
887
+ `),ue=0,ke=0,Ae=!1;for(let Oe of D){if(Oe.includes("[DIFF_START]")){Ae=!0;continue}if(Oe.includes("[DIFF_END]")){Ae=!1;continue}Ae&&(/^\+\s*\d+/.test(Oe)?ue++:/^\-\s*\d+/.test(Oe)&&ke++)}(ue>0||ke>0)&&(await gt("linesAdded",ue),await gt("linesRemoved",ke))}}else if((E==="writefile"||E==="write_file")&&A){let D=A.match(/- Stats: \[(\d+) lines/),ue=D?parseInt(D[1]):0,ke=0;if(A.includes("Old File contents:")){let Ae=!1;for(let Oe of A.split(`
888
+ `)){if(Oe.includes("Old File contents:")){Ae=!0;continue}Ae&&(Oe.startsWith("- Content Preview:")||Oe.trim()===""&&!/^\s*\d+\s*\|/.test(Oe)?Ae=!1:/^\s*\d+\s*\|/.test(Oe)&&ke++)}}(ue>0||ke>0)&&(await gt("linesAdded",ue),await gt("linesRemoved",ke))}}catch(A){let D=`ERROR: Execution failed for [${T.toolName}]: ${A.message}`;s&&s(`[Tool Error] ${D}
889
+ `),Ct+=`${D}
890
+
891
+ `,await kt("toolFailure")}}let rt="";if(n?.taskId&&typeof Bt<"u"){let T=Bt.find(E=>E.id===n.taskId);if(T&&T.pendingSteerMessages&&T.pendingSteerMessages.length>0){let E=[...T.pendingSteerMessages];T.pendingSteerMessages=[];for(let Be of E)rt+=`
892
+
893
+ [STEERING INSTRUCTION FROM MAIN AGENT]: ${Be}`,s&&s(`[Subagent Steered] ${Be}`)}}let Zt=(Ct.trim()+rt).trim();$e.push({role:"user",text:Zt}),_e++}return Ie};export{Ao as a,Ss as b,ic as c,rc as d,Kl as e,Yl as f,lc as g,Jo as h,cc as i,Pa as j,Yc as k,La as l,$a as m,Ki as n,Wt as o,Is as p,$s as q,Ba as r,zc as s,qc as t,qi as u,Xc as v,Jc as w,Zo as x,Qc as y,Zc as z,ed as A,td as B};