fluxflow-cli 4.11.0 → 4.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/README.md +2 -2
  2. package/dist/chunks/{ai-WB4PWDHV.js → ai-OCOM32HV.js} +1 -1
  3. package/dist/chunks/app-LKK2QTJ7.js +238 -0
  4. package/dist/chunks/chunk-LRJGBXD6.js +880 -0
  5. package/dist/chunks/{chunk-W43IBIRT.js → chunk-MZGMZ4T6.js} +1 -1
  6. package/dist/chunks/{chunk-2CJOOYOT.js → chunk-R67K3FEP.js} +1 -1
  7. package/dist/chunks/{chunk-TA42E3DA.js → chunk-RNEHIJXX.js} +1 -1
  8. package/dist/chunks/chunk-VNPYQFKQ.js +3 -0
  9. package/dist/chunks/{chunk-Q7SNDU5P.js → chunk-WZW77OYB.js} +1 -1
  10. package/dist/chunks/{click-WCT2TJ2G.js → click-V2WBK6PX.js} +2 -2
  11. package/dist/chunks/{computer_action-EKG5CRRA.js → computer_action-QGLK3SY6.js} +1 -1
  12. package/dist/chunks/{drag-HYJQ5RE7.js → drag-6P367RA2.js} +1 -1
  13. package/dist/chunks/{generate_image-Q6RIYYMI.js → generate_image-6K34FOJJ.js} +1 -1
  14. package/dist/chunks/{invoke-RTBTXXOI.js → invoke-D2QN5M3S.js} +2 -2
  15. package/dist/chunks/{invokeSync-RNOOUMPZ.js → invokeSync-U5GA5PGM.js} +2 -2
  16. package/dist/chunks/{key_press-RKJOUTTG.js → key_press-BRS2DIB5.js} +1 -1
  17. package/dist/chunks/{keyboard_typing-GJBWCAZ2.js → keyboard_typing-3YF72D7X.js} +1 -1
  18. package/dist/chunks/{screen_grid-Y5PT4VFL.js → screen_grid-IUKQWDZG.js} +1 -1
  19. package/dist/chunks/{scroll-DVM5ACY2.js → scroll-VJJ2SHXR.js} +1 -1
  20. package/dist/chunks/{settings-2QSWNLAX.js → settings-ZHS26QZ5.js} +1 -1
  21. package/dist/chunks/{update_file-CF2DSC6F.js → update_file-KPFDUPKK.js} +1 -1
  22. package/dist/chunks/usageServer-DMWM5ECL.js +1 -0
  23. package/dist/chunks/{write_file-N2EG2T6U.js → write_file-LYTIK6LS.js} +1 -1
  24. package/dist/cli.js +6 -6
  25. package/dist/package.json +2 -2
  26. package/package.json +2 -2
  27. package/dist/chunks/app-DLM4TCBT.js +0 -225
  28. package/dist/chunks/chunk-GFDJETGV.js +0 -868
  29. package/dist/chunks/chunk-K26OGD74.js +0 -3
  30. package/dist/chunks/usageServer-HYLLNJRZ.js +0 -1
@@ -1,868 +0,0 @@
1
- import{a as Zn}from"./chunk-2TASXARO.js";import{a as Gt}from"./chunk-56EJGQU3.js";import{a as es,h as Ys}from"./chunk-TJII6UKN.js";import{a as Ks}from"./chunk-5GEXRVU6.js";import{e as Ws,f as Hs,g as Gs,k as Zo}from"./chunk-6GTIZENY.js";import{a as yo}from"./chunk-TGINXVDR.js";import{b as Qo}from"./chunk-JSVFQZL2.js";import{e as Et,g as Nt,i as Bs,j as Us}from"./chunk-Q7SNDU5P.js";import{c as gt,d as Hn,g as ie,h as Qn}from"./chunk-K26OGD74.js";import{c as At,d as Wn}from"./chunk-SIINYZWE.js";import{a as js,c as Vs}from"./chunk-FJGY5C4M.js";import{a as Un,d as yn,e as ho,j as Mn,k as po,l as Jo,q as Xo}from"./chunk-4TZKD2XR.js";import{a as J}from"./chunk-Y5JU726N.js";import{GoogleGenAI as sr,ThinkingLevel as dt,HarmBlockThreshold as wn,HarmCategory as kn}from"@google/genai";var qs=(e=!0,n=!0)=>`
2
- To use tools, must output exactly '[tool:functions.ToolName(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
- - Memory(action="temp", content="<summary of the user prompt & model responses only from latest prompt under 40 words>. [Talked on: <date> <hour>]"). Time format: YYYY-MM-DD HH am/pm
7
-
8
- ${e?`-- User-specific long-term/permanent memory (use based on conversation context, do not re-save memory which is already saved) --
9
- - 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)
10
- - Delete: Memory(action="user", method="delete", id="<memory id>")
11
- - Update: Memory(action="user", method="update", content-new="string to update", id="<memory id>")
12
-
13
- -- Memory Relevance Decay Tool --
14
- - Score Adjustment: addMemScore(id="<memory id>")
15
- 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
16
-
17
- Explicit Triggers for permanent memory:
18
- - User explicitly asks to 'remember' something
19
- - User mentions something important long-term that should be remembered
20
- - User provides information that could be useful for long-term reference
21
- - User shares personal information or preferences
22
-
23
- Usage Rules:
24
- - Frequency for 'user' action: Based on explicit triggers
25
- - If you want to save something, but similar memory already exists, use the update method not add
26
- - Chat title is mandatory
27
- - Temporary memory is mandatory
28
- - When called user memory, still use Temporary Memory
29
- - Must not ignore any tool calls in given context of chat between user & agent`:""}`.trim();var xo={xHigh:`Effort: High
30
- Think before complex tasks
31
- Prefer simplest correct solution, assess architecture, performance & maintainability, verify error handling, assumptions, edge cases, dependencies & regressions, plan: files, functions, logic & interactions
32
- Verify from first principles, seek failure paths, verify imports, system stability
33
- Use as less as possible thinking tokens. Achieve the final result with quality without wasting tokens`,High:`Effort: High
34
- Think before complex tasks
35
- Prefer simplest correct solution, assess architecture, performance & maintainability, verify error handling, assumptions, edge cases, dependencies & regressions, plan: files, functions, logic & interactions
36
- Continuous analysis, verify from first principles, seek failure paths, verify imports, system stability
37
- Dont waste tokens, be efficient, use less thinking tokens, focus on result
38
- Gather useful context`,Medium:`Effort: Medium
39
- Think before complex tasks
40
- Focused, technical thinking, find the simplest solution meeting requirements, check error handling, assumptions, edge cases & dependencies, verify cohesive, modular changes, outline: files, functions & key logic
41
- Logical, implementation-focused, efficient, deliberate, verify imports, system stability
42
- Dont waste tokens, be efficient, use least thinking tokens, focus on result
43
- Gather useful context`,Minimal:`Effort: Low
44
- Quick, focused thinking, intent & complexity, required tools/files/actions, before acting
45
- Dont waste tokens, be efficient, use least thinking tokens, focus on result
46
- Gather useful context
47
- Brief thoughts, think only enough to avoid mistakes, verify imports, system stability`,Off:`Effort: Lowest
48
- No thinking. Immediate response
49
- Verify imports, tool results & system stability`};import bn from"fs";import cs from"path";import Ar from"os";import sn from"fs";import xn from"path";import ai from"fs";import ts from"path";import{execSync as li}from"child_process";import{fileURLToPath as _r}from"url";var zs=`# FluxFlow CLI Startup & Flags Reference
50
-
51
- Launch command syntax:
52
- fluxflow [options]
53
-
54
- ## Supported CLI Flags
55
- * --mode flux | flow | icu | fluxcu \u2192 Startup mode
56
- * --model model-id \u2192 Session model override
57
- * --provider google | deepseek | openrouter | nvidia | mistral | ollama | crofai | inferx | sensenova | aihubmix | poolside | 9router | explabs \u2192 Override default AI provider
58
- * --key key@provider \u2192 Set new API key for provider
59
- * --thinking Fast | Low | Medium | High | xHigh \u2192 Override reasoning depth
60
- * --path project/path \u2192 Set working directory for session
61
- * --memory on | off \u2192 Toggle persistent long-term agent memory
62
- * --resume session-id \u2192 Resume previous chat session programmatically
63
- * --allocation mb \u2192 Override Node.js --max-old-space-size in MB (Req env.EXPERIMENTAL_MEMORY_MANAGER enabled \u2192 Ref: references/ENV.md)
64
- * --package npm | pnpm | yarn | bun \u2192 Override package manager for core updates
65
- * --auto-del 1d | 7d | 30d \u2192 History auto-deletion retention timeframe
66
- * --auto-exec on | off / --yolo on | off \u2192 Toggle autonomous command execution
67
- * --external-access on | off \u2192 Toggle permission to read/write files outside CWD
68
- * --usage / --budget \u2192 Launch browser token analytics dashboard
69
- * --export error \u2192 Export system error logs to timestamped file
70
- * --update check \u2192 Check latest version on npm
71
- * --update check latest \u2192 Print latest version on npm
72
- * --update [latest] \u2192 Upgrade app to latest release
73
- * --version, -v \u2192 Show installed version
74
- * --help \u2192 CLI help menu
75
- * --help commands \u2192 In-chat slash commands list
76
- * --playground \u2192 Launch Playground mode
77
- `;var Js=`# Env Variables
78
-
79
- * Locations:
80
- * Shell
81
- * Global: ~/.fluxflow/.env.fluxflow | ~/.fluxflow/.env.agents
82
- * Workspace: ./.env.fluxflow | ./.env.agents
83
-
84
- ## Core Variables
85
- * SUBAGENT_MODEL \u2192 Model override for sub-agents
86
- * SUBAGENT_PROVIDER \u2192 Provider override for sub-agents
87
- * NVIDIA_BASE_URL \u2192 Custom endpoint URL for NVIDIA NIM (Cloud/Local OpenAI Compatible)
88
- * NVIDIA_API_KEY \u2192 API key for NVIDIA NIM
89
- * OLLAMA_HOST \u2192 Custom Ollama endpoint (default: http://127.0.0.1:11434)
90
- * SHELL \u2192 Terminal shell executable
91
- * HIGH_CONTEXT \u2192 Context window override (false or integer 32k..1M)
92
- * ENABLE_9ROUTER \u2192 Enables 9Router provider. Can use OAuth subscription like Codex, Claude Code, GitHub Copilot etc. or use providers not natively in Fluxflow. Set ENV ENABLE_9ROUTER=true, needs 9router package installed (via npm/npx etc) & running
93
- * 9ROUTER_BASE_URL \u2192 9Router base URL
94
-
95
- ## Diagnostic & Optimization Flags
96
- * SHOW_DEBUG_GRID \u2192 (true|false, default: false) Coordinate grid overlay for Computer Use tooling
97
- * DEBUG_OCR \u2192 (true|false, default: false) Enables verbose OCR diagnostic logs
98
- * EXPERIMENTAL_MEMORY_MANAGER \u2192 (true|false, default: false) Reduces app memory footprint, slower boot times
99
-
100
- * NO_DEV \u2192 (true|false, default: false) Token optimization flag; strips developer metadata and docs to maximize context headroom
101
-
102
- * 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
103
- * GOOGLE_GEMMA_NONSENSE \u2192 (true|false, default: false) for the 16k TPM nonsense of gemma models on gemini API. False defaults to 256k
104
- `;var Xs=`# Fluxflow in-app /commands
105
-
106
- Trigger in chat via /command
107
-
108
- ## Session & Navigation
109
- * /quit \u2192 Exit and shutdown FluxFlow
110
- * /help \u2192 Show help menu & actions
111
- * /clear \u2192 Clear terminal viewport
112
- * /chats \u2192 List stored chat sessions
113
- * /resume \u2192 Switch to previous session
114
- * /save \u2192 Force-save current session state
115
- * /reset \u2192 Wipe fluxflow appdata, sessions, and cache
116
-
117
- ## Context & History Management
118
- * /compress \u2192 Summarize chat history to reclaim context headroom
119
- * /truncate \u2192 Truncate large tool results in history
120
- * /btw question \u2192 Send side-inquiry mid-turn without breaking active flow
121
- * /export chat | logs \u2192 Export chat transcript or error logs
122
-
123
- ## Codebase Safety & Reversion
124
- * /revert \u2192 Git-less checkpoint rollback viewer (Shortcut: double-ESC while idle)
125
-
126
- ## Configuration & Model Controls
127
- * /settings \u2192 Full-screen interactive settings menu
128
- * /mode \u2192 Toggle Operating Mode
129
- * /model model-id \u2192 Switch active AI model
130
- * /provider \u2192 Select/switch AI provider
131
- * /thinking effort \u2192 Set reasoning effort
132
- * /wildcard-tooling \u2192 Tool compatibility mode for non-tooling models
133
- * /key \u2192 Manage saved API keys
134
- * /profile \u2192 Edit user persona, nickname, and custom instructions
135
- * /theme \u2192 Select UI color theme
136
- * /memory \u2192 View/manage agent persistent memory
137
- * /budget \u2192 Set/view token budget limits
138
- * /stats \u2192 Session token usage telemetry
139
- * /usage \u2192 Open graphical browser analytics dashboard
140
-
141
- ## Documentation & Updates
142
- * /docs \u2192 Online documentation
143
- * /about \u2192 App info & author credits
144
- * /changelog \u2192 Release notes
145
- * /update check \u2192 Check npm updates
146
- * /update latest \u2192 Install latest release
147
- `;var Qs=`# FluxFlow In-App Settings Reference
148
-
149
- Open in chat via /settings
150
-
151
- ## Settings Categories & Options
152
-
153
- ### 1. Providers & Tips \u2192 references/PROVIDERS.md
154
-
155
- ### 2. Appearance
156
- * Theme \u2192 UI theme (Dark | Light | Cyberpunk | Forest | Sunset | Matrix | Dracula | Nord | Monokai | Mystery/Chaos)
157
- * Loading Phrases \u2192 Humorous status phrases during thinking
158
- * Progressive Rendering [Experimental] \u2192 Smooth streaming token rendering. May have few glitches
159
- * Show TPM Estimate \u2192 Real-time Tokens Throughput speed estimate
160
-
161
- ### 3. Memory
162
- * Toggle Memory \u2192 Persistent cross-session memory learning (Not available for some providers)
163
-
164
- ### 4. Security & Sandbox
165
- * Sandbox Preset:
166
- * Strict \u2192 YOLO: OFF | External Access: OFF | Network Access: OFF | destructive commands blocked | strict HITL
167
- * Balanced \u2192 YOLO: ON (safe commands) | External Access: OFF | Network Access: ON | destructive commands blocked | manual git approval
168
- * Autonomous \u2192 YOLO: ON | External Access: ON | Network Access: ON | auto-approve git commits | prompt high-risk commands
169
-
170
- * YOLO Mode \u2192 Autonomous command execution without confirmation
171
- * External Workspace Access \u2192 Read/write access outside CWD
172
- * Network Access (Internal Shell) \u2192 Outbound network access for shell commands
173
- * Command Policies:
174
- * Always Ask Commands \u2192 Commands requiring explicit confirmation
175
- * Auto Approve Commands \u2192 Safe commands allowed to execute automatically
176
- * Auto Disapprove Commands \u2192 Blacklisted commands automatically rejected
177
-
178
- * Auto Approve Git Commits \u2192 Auto-confirm git commit operations
179
- * Advanced Recovery [EXPERIMENTAL] \u2192 Enhanced rollback if agent corrupt codebase
180
- * Auto-Delete History \u2192 Chat log retention period
181
- * Save AppData Externally \u2192 Saves chats/apikeys to user provided path
182
-
183
- ### 5. Updater
184
- * Auto-Update \u2192 Check for new releases on boot
185
- * Preferred Package Manager \u2192 npm | pnpm | yarn | bun | custom
186
-
187
- ### 6. Miscellaneous
188
- * Sub-Agents \u2192 Enable sub-agent delegation
189
- * Sub-Agent Model \u2192 Dedicated model/provider for sub-agents
190
- * Verbose Thinking \u2192 Show reasoning blocks in the UI. Keeps UI clean when disabled. And reasoning transparent when enabled
191
- * Dynamic Directory Awareness \u2192 Dynamic tracking of workspace directory tree
192
- * Directory Tree Design \u2192 Directory visual styling. Modern (Saves Tokens) | Classic (More Tokens)
193
- * Compact Large Tool Results \u2192 Compress large tool outputs to save tokens (model might miss subtle indentation/syntax errors)
194
- * Auto Truncate Results \u2192 Auto-truncate tool results after task finished to save token and improve caching
195
- * Image History for CU \u2192 Number of images to keep in context for Computer Use. Low (1 image, Low Context Accuracy, Token Efficient) / Standard (3 images, Better Accuracy, Higher Token Usage) / Extended (5 images, Better for complex tasks, Highest Token Usage)
196
- `;var Zs=`# FluxFlow Tool Reference
197
-
198
- ## Protocol: [tool:functions.ToolName(arg1="val")]
199
-
200
- ## 1. Workspace
201
- * ReadFile(path, startLine?, endLine?) \u2192 Read text/code/PDF/image
202
- * PatchFile(path, searchContent1..15, newContent1..15, allowMultiple?) \u2192 Atomic multi-replacement; supports ^LINE:start..end$
203
- * WriteFile(path, content) \u2192 Create/overwrite file
204
- * ReadFolder(path, recurse?) \u2192 List directory tree (depth: 1-3)
205
- * CodeSearch / SearchKeyword(keyword, path?, fuzzy?, regex?) \u2192 Fast text search; path="#docs" for doc index
206
- * Run(command) \u2192 Execute command in shell
207
- * Todo(method, tasks?, markDone?) \u2192 Planner ("create" | "append" | "get")
208
-
209
- ## 2. Web & Communication
210
- * WebSearch(query, aiMode?, limit?) \u2192 Live web search + AI summary
211
- * WebScrape(url) \u2192 Extract markdown from URL
212
- * Ask(question, optionA..D?) \u2192 Interactive prompt to user ("title::desc")
213
-
214
- ## 3. Sub-Agents
215
- * InvokeSync(title, task) \u2192 Blocking sub-agent
216
- * Invoke(title, task) \u2192 Non-blocking worker (max 7 concurrent)
217
- * Await(id, timeout?) \u2192 Wait for async worker
218
- * GetProgress(id) \u2192 Telemetry & logs
219
- * Steer(id, message) \u2192 Mid-flight direction
220
- * Cancel(id) \u2192 Terminate worker
221
-
222
- ## 4. Emergency & Rollback
223
- * EmergencyRollback(method, id?) \u2192 Checkpoint restore ("getCheckpoint" | "forceRevert")
224
-
225
- ## 5. Creative Documents
226
- * WritePDF(path, content, orientation?) \u2192 Render HTML/CSS to PDF
227
- * WriteDoc(path, content) \u2192 Render DOCX
228
-
229
- ## 6. Computer Use (GUI)
230
- * Click(gridId, type?, button?, intendedClickText?) \u2192 Click coordinate + OCR snap
231
- * Drag(fromGridId, toGridId) \u2192 Mouse drag
232
- * Scroll(direction, gridId?) \u2192 Viewport scroll ("up" | "down")
233
- * KeyboardTyping(text, autoPressEnter?) \u2192 Type string
234
- * KeyPress(key) \u2192 Key/combo dispatch ("ctrl;c", "enter", etc.)
235
- * RecaptureScreen() \u2192 Fresh screenshot + coordinate grid
236
- `;var ei=`# Fluxflow Architecture
237
-
238
- ## 1. Terminal Engine
239
- * Framework: React + Ink terminal UI
240
- * Sub-Terminal: Live PTY shell bridge; TAB switches active keyboard focus
241
- * OS Compatibility: Auto-detects pwsh, powershell, bash, cmd
242
-
243
- ## 2. Dual-Model Runtime
244
- * Main Agent: Reasoning, code edits, and tool calls
245
- * Memory Agent: Background context & preference synthesizer (fixed models; disable via /settings \u2192 Memory or use NIM API key)
246
-
247
- ## 3. Multi-Agent System
248
- * Execution: Synchronous (InvokeSync) | Asynchronous (Invoke, \u22647 workers)
249
- * Isolation: Restricted tool scope per subagent
250
- * State Tracking: Mutations logged under parent task ledger
251
-
252
- ## 4. Security & Sandbox
253
- * Approvals: HITL confirmation on destructive file/shell operations
254
- * Modes: Strict | Balanced | Autonomous (YOLO)
255
- * Recovery: Pre-turn snapshot indexing via EmergencyRollback
256
-
257
- ## 5. Computer Use Automation
258
- * Vision: 720p normalized canvas, 4ms variance scan, Set-of-Marks (SoM) overlay
259
- * OCR Alignment: Euclidean distance text matching to mark centers
260
- * Hardware I/O: OS input dispatch via @nut-tree-fork/nut-js
261
- * Memory Management: 2-turn sliding window with active V8 GC
262
-
263
- ## 6. IDE Bridge
264
- * Protocol: WebSocket on ws://localhost:56832
265
- * State Sync: Focused file, open tabs, cursor line, selection, diagnostics
266
- `;var ti=`# FluxFlow Sub-Agents & Multi-Agent Architecture
267
-
268
- ## Execution Modes
269
- * InvokeSync \u2192 Synchronous blocking delegation; main agent halts until sub-agent finishes task
270
- * Invoke \u2192 Asynchronous background delegation; spawns parallel worker
271
- * Lifecycle Tools:
272
- * Await \u2192 Non-polling wait for completion
273
- * GetProgress \u2192 Query live logs & execution status
274
- * Steer \u2192 Inject dynamic instructions mid-flight
275
- * Cancel \u2192 Terminate running sub-agent
276
-
277
- ## Tool Sandboxing & Safety
278
- * Sub-agents inherit isolated tool environments
279
- * Destructive shell commands hard-blocked
280
- * All file mutations tracked under parent session transaction
281
-
282
- ## Custom Model & Provider Setup
283
- Route sub-agent workloads to faster/cheaper models independently of the main agent:
284
-
285
- ### 1. In-App Settings (/settings \u2192 Miscellaneous)
286
- * Sub-Agents \u2192 ON | OFF
287
- * Custom Sub-Agent Model:
288
- * SubAgentModel \u2192 Model name
289
- * SubAgentProvider \u2192 Provider
290
-
291
- * Models are shown for providers whose API key is used before in fluxflow
292
-
293
- ### 2. Environment Variables for Custom Sub-Agent models (.env.fluxflow or Shell)
294
- * SUBAGENT_MODEL \u2192 Target model override
295
- * SUBAGENT_PROVIDER \u2192 Target provider override
296
- * Setting SubAgentModel=ENV in settings pulls directly from environment overrides
297
- `;var ni=`# FluxFlow Security, Sandboxing & Safety
298
-
299
- ## Human-in-the-Loop Governance
300
- * Execution Approval Gate \u2192 Destructive commands and high-risk file modifications require explicit user authorization (Allow / Deny)
301
- * Safe Command Auto-Pass \u2192 Read-only queries (ls, pwd, git status, node -v) execute without interrupting flow
302
-
303
- ## Sandbox Presets (/settings \u2192 Security)
304
- * Strict \u2192 autoExec: OFF | allowExternalAccess: OFF | networkAccess: OFF | destructive commands blocked | strict HITL on all actions
305
- * Balanced \u2192 autoExec: ON (safe commands) | allowExternalAccess: OFF | networkAccess: ON | destructive commands blocked | manual git approval
306
- * Autonomous (YOLO) \u2192 autoExec: ON | allowExternalAccess: ON | networkAccess: ON | auto-approves git commits | prompts only on extreme-risk commands
307
-
308
- ## Granular Command & Access Policies
309
- * Command Filtering:
310
- * Always Ask Commands \u2192 Configurable list always prompting for confirmation
311
- * Auto Approve Commands \u2192 Whitelist of trusted commands executed automatically
312
- * Auto Disapprove Commands \u2192 Blacklist of forbidden commands instantly rejected
313
- * Workspace Directory Lock \u2192 Restricts file read/write operations strictly to current CWD unless External Access: ON
314
- * Terminal Network Isolation \u2192 Blocks outbound network sockets for spawned shell commands when networkAccess: OFF
315
-
316
- ## Recovery & Data Sanctuary
317
- * Emergency Rollback \u2192 Automatic pre-turn file snapshots; Agent can still fix it (default: OFF) \u2192 references/SETTINGS.md
318
- * Git-less Checkpoint Reversion \u2192 Trigger conversational changes rollback via double-ESC
319
- * External Sanctuary Redirection \u2192 Move ~/.fluxflow data sanctuary (chats, keys etc)
320
- `;var oi=`# Fluxflow IDE Companion
321
-
322
- ## WebSocket Bridge Protocol
323
- * Local Bridge \u2192 Runs on ws://localhost:56832 connecting FluxFlow CLI with the companion editor extension
324
- * Bi-directional Handshake \u2192 Exchanges CLI version, process PID/PPID, and editor capabilities on connection
325
-
326
- ## Real-Time Context Awareness
327
- * User Turn Context \u2192 Injected dynamically on every prompt turn:
328
- * file_focused \u2192 Active editor tab currently visible
329
- * opened_editors \u2192 List of all open file tabs in workspace
330
- * cursor_line & selected \u2192 Exact cursor line number and selected text snippet
331
- * manual_edits \u2192 User manual modifications since last turn
332
- * 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
333
-
334
- ## Editor Actions & Visual Feedback
335
- * File Focus \u2192 Automatically opens edited files in active IDE window
336
- * Diff Preview \u2192 Streams side-by-side or inline diff highlights (showDiff, highlightDiff) directly in editor
337
- * Status Bar Sync \u2192 Real-time agent status (thinking, running tool, awaiting input) reflected in IDE status bar
338
- `;var si=`# Fluxflow Modes
339
-
340
- ## Modes Overview (TAB to cycle)
341
- * [Flux] (Workspace / Dev) \u2192 Primary coding & workspace agent
342
- * [Flow] (Studio / Creative) \u2192 Web research & formatted document authoring (PDF / DOCX)
343
- * [ICU] (Computer Use) \u2192 Autonomous GUI & OS desktop automation
344
- * [FluxCU] (Omni) \u2192 Unified full-stack agent (Workspace Dev + Computer Use + Web)
345
-
346
- ## Tool Availability
347
- * File Operations: ReadFile, PatchFile, WriteFile, ReadFolder, CodeSearch \u2192 [Flux] | [FluxCU]
348
- * Terminal Execution: Run \u2192 [Flux] | [FluxCU]
349
- * Task Management: Todo \u2192 [Flux] | [FluxCU]
350
- * Sub-Agents: InvokeSync, Invoke, Await, GetProgress, Steer, Cancel \u2192 [Flux] | [FluxCU]
351
- * Checkpoint Recovery: EmergencyRollback \u2192 [Flux] | [FluxCU]
352
- * Web & Research: WebSearch, WebScrape \u2192 [Universal]
353
- * User Inquiry: AskUser \u2192 [Universal]
354
- * Document Creation: WritePDF, WriteDoc \u2192 [Flow]
355
- * GUI & Desktop Automation: Click, Drag, Scroll, KeyboardTyping, KeyPress, RecaptureScreen \u2192 [ICU] | [FluxCU]
356
- `;var ii=`# FluxFlow AI Providers & Setup
357
-
358
- ## Supported Providers
359
- * Direct: Gemini (aistudio.google.com) | NVIDIA NIM (build.nvidia.com) | DeepSeek (platform.deepseek.com) | Mistral (admin.mistral.ai) | Ollama (ollama.com) | CrofAI (crof.ai) | InferX (model.inferx.net) | SenseNova (platform.sensenova.ai) | Poolside (platform.poolside.ai)
360
- * Aggregators / Local Proxies: OpenRouter (openrouter.ai) | AIHubMix (aihubmix.com) | Experiential Labs (api.experientiallabs.ai)
361
- * Local Proxy: 9router. 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 (eg via npm) & running
362
-
363
- * Fluxflow has default model list for many providers, updated based on vibes. Can be overriden using /model <model-id>
364
-
365
- ## Setup: Local NVIDIA NIM (OpenAI-Compatible)
366
- 1. Environment Variables (.env.fluxflow or shell):
367
- * NVIDIA_BASE_URL = http://<host>:<port>/v1/chat/completions (or custom OpenAI endpoint)
368
- * NVIDIA_API_KEY = Optional API key (if NIM container requires authentication)
369
- 2. Switch Provider: Select NVIDIA in /settings \u2192 Providers
370
- 3. Select Model: /model <model_name>
371
- * Memory agent is automatically disabled on custom/local & few providers endpoints
372
-
373
- ## Setup: Ollama (Local / Cloud)
374
- 1. Endpoint & Authentication:
375
- * Local: Set API Key to LOCAL in /settings \u2192 Providers or on key prompt
376
- * Endpoint URL: Default is http://127.0.0.1:11434 (Override via OLLAMA_HOST)
377
- 2. Model Selection:
378
- * Standard: /model <model-id>
379
- * Multimodal (Vision): /model <model-id> -m
380
- 3. Context Window Override:
381
- * Set HIGH_CONTEXT=<tokens> in ENV (range: 32k to 1M)
382
- `;var ri=`# Fluxflow Instructions & Skills System
383
-
384
- ## 1. Instructions
385
- * Locations:
386
- * Global: ~/.fluxflow/FLUXFLOW.md | ~/.fluxflow/AGENTS.md
387
- * Workspace: ./FLUXFLOW.md | ./AGENTS.md
388
- * Auto indexed on boot
389
-
390
- ## 2. Skills System
391
- * Locations:
392
- * Global: ~/.fluxflow/skills/**/SKILL.md
393
- * Workspace: ./skills/**/SKILL.md | ./SKILL.md
394
-
395
- * Format:
396
- * YAML Frontmatter: --- block with name and description
397
- * Body: Markdown Instructions/Workflows
398
-
399
- * On-Demand Reference Loading:
400
- * Reference: Offload deep/contexual specs to references/*.md linked from root SKILL.md. Saves tokens
401
- `;var bo="v4";try{let e=ts.dirname(_r(import.meta.url)),n=[ts.join(e,"../../package.json"),ts.join(e,"../package.json")],t=!1;for(let s of n)if(ai.existsSync(s)){let o=JSON.parse(ai.readFileSync(s,"utf8"));if(o.version){bo=o.version,t=!0;break}}if(!t)try{let s=li("fluxflow -v",{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"],timeout:2e3}).trim();s&&(s.startsWith("v")||/^\d+\.\d+/.test(s))&&(bo=s,t=!0)}catch{}if(!t)try{let s=li("curl -s --max-time 3 https://raw.githubusercontent.com/KushalRoyChowdhury/fluxflow-cli/main/package.json",{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"]}),o=JSON.parse(s);o.version&&(bo=o.version)}catch{}}catch{}var ns={"SKILL.md":`---
402
- name: fluxflow
403
- description: System Generated Documentation. Read this if asked anything regarding FluxFlow Harness
404
- ---
405
-
406
- # FluxFlow, by Kushal Roy Chowdhury
407
- Open Source Terminal AI Assistant
408
- App Version: ${bo}. Check Updates: fluxflow --update check. Update: fluxflow --update
409
- GitHub: https://github.com/KushalRoyChowdhury/fluxflow-cli
410
- Documentation: https://fluxflow-cli.onrender.com
411
-
412
- [tool:functions.SearchKeyword(keyword="regex/word", path="#docs")]. Usage: search any keyword across docs, avoid hunting excessive references
413
-
414
- ## Supported Features & Documentation References
415
- * Operating Modes (Flux, Flow, CU, FluxCU) \u2192 references/MODES.md
416
- * Inference Providers & Aggregators (Setup, Local NIM, Ollama) \u2192 references/PROVIDERS.md
417
- * In-App Settings (/settings) \u2192 references/SETTINGS.md
418
- * In-app /commands \u2192 references/COMMANDS.md
419
- * CLI Startup Flags \u2192 references/STARTUP.md
420
- * Environment Variables \u2192 references/ENV.md
421
- * Tool System (Workspace, Web, Communication, Sub-Agents, Safety, Creative, Computer Use) \u2192 references/TOOLS.md
422
- * Sub-Agents & Multi-Agent Runtime \u2192 references/SUB_AGENTS.md
423
- * Security, Sandboxing & Checkpoints (/revert, double-ESC) \u2192 references/SECURITY.md
424
- * IDE Companion Extension & Real-time Context \u2192 references/IDE.md
425
- * Priority Instructions (AGENTS.md/FLUXFLOW.md) & Skill System \u2192 references/PLUGINS.md
426
- * Agent Architecture & Memory System \u2192 references/ARCHITECTURE.md
427
-
428
- Default Context Length: 256k Tokens. Can be changed via ENV
429
-
430
- Docs missing required info? Say you are not sure enough to answer. Dont give wrong info`,"references/MODES.md":si,"references/PROVIDERS.md":ii,"references/PLUGINS.md":ri,"references/STARTUP.md":zs,"references/ENV.md":Js,"references/COMMANDS.md":Xs,"references/SETTINGS.md":Qs,"references/TOOLS.md":Zs,"references/ARCHITECTURE.md":ei,"references/SUB_AGENTS.md":ti,"references/SECURITY.md":ni,"references/IDE.md":oi};var ci=()=>{try{let e=xn.join(Un,"skills","fluxflow"),n=xn.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){sn.existsSync(e)&&sn.rmSync(e,{recursive:!0,force:!0});return}let s=new Set(Object.keys(ns).map(o=>xn.normalize(o)));for(let[o,c]of Object.entries(ns)){let u=xn.join(e,o),a=xn.dirname(u);sn.existsSync(a)||sn.mkdirSync(a,{recursive:!0});let b=c.trim()+`
431
- `,g=null;sn.existsSync(u)&&(g=sn.readFileSync(u,"utf8")),g!==b&&sn.writeFileSync(u,b,"utf8")}if(sn.existsSync(n)){let o=sn.readdirSync(n);for(let c of o){let u=xn.normalize(xn.join("references",c));if(!s.has(u)){let a=xn.join(n,c);try{sn.rmSync(a,{recursive:!0,force:!0})}catch{}}}}}catch{}};var ds=(e,n)=>{try{if(!bn.existsSync(e))return null;let t=Array.isArray(n)?n.map(o=>o.toLowerCase()):[n.toLowerCase()],s=bn.readdirSync(e);for(let o of t){let c=s.find(u=>u.toLowerCase()===o);if(c){let u=cs.join(e,c);if(bn.statSync(u).isFile())return u}}}catch{}return null},ui=(e,n)=>{let t=ds(e,n);if(t)try{return bn.readFileSync(t,"utf8")}catch{}return""},rs=ds(Un,["fluxflow.md","agent.md","agents.md"]),as=ds(process.cwd(),["fluxflow.md","agent.md","agents.md"]),Er=rs?ui(Un,["fluxflow.md","agent.md","agents.md"]).trim():"",ls="",gi=!1,Cr=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],s=n[2],o=t.match(/^Identity:\s*([\s\S]*?)(?=\r?\n\s*(?:<><|>>>)|$)/m);return o&&(ls=o[1].trim(),process.env.NO_INS=!0),/<><\s*NO_INS/.test(t)&&(gi=!0),s.trim()},Gn=Cr(Er);ci();var to=as?ui(process.cwd(),["fluxflow.md","agent.md","agents.md"]).trim():"",Rr=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="",c="",u=t.match(/^name:\s*(.+)$/m),a=t.match(/^description:\s*(.+)$/m);return u&&(o=u[1].trim().replace(/^["']|["']$/g,"")),a&&(c=a[1].trim().replace(/^["']|["']$/g,"")),o&&c?{name:o,description:c}:null},Mr=e=>{let n=[];if(!e||!bn.existsSync(e))return n;let t=(s,o=0)=>{if(!(o>5))try{let c=bn.readdirSync(s,{withFileTypes:!0});for(let u of c){let a=cs.join(s,u.name),b=u.name.toLowerCase();u.isFile()?b==="skill.md"&&n.push(a):u.isDirectory()&&(o===0?(b==="skills"||b===".skills"||b==="skill"||b===".skill")&&t(a,o+1):t(a,o+1))}}catch{}};return t(e,0),n},mi=e=>{let n=Mr(e),t=[];for(let s of n)try{let o=bn.readFileSync(s,"utf8"),c=Rr(o);c&&t.push({...c,filePath:s})}catch{}return t},hi=e=>!e||e.length===0?"":e.map(n=>`- ${n.name}: ${n.description}`).join(`
432
- `),pi=mi(Un),yi=mi(process.cwd()),os=hi(pi),ss=hi(yi),xi=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"},bi=()=>(pi||[]).filter(e=>!xi(e)),wi=()=>(yi||[]).filter(e=>!xi(e)),ll=(Gn?1:0)+(to?1:0)+bi().length+wi().length,is=(e,n="Project")=>{if(!e)return"";let t=e.replace(/\\/g,"/");if(n==="Global"){let o=Ar.homedir().replace(/\\/g,"/");return t.toLowerCase().startsWith(o.toLowerCase())?"~"+t.slice(o.length):t}let s=cs.relative(process.cwd(),e).replace(/\\/g,"/");return s.startsWith(".")?s:`./${s}`},cl=()=>{let e=[];rs&&Gn.length>0&&e.push({scope:"Global",path:rs}),as&&to.length>0&&e.push({scope:"Project",path:as});let n=bi(),t=wi(),s=e.length+n.length+t.length;if(s===0)return`\u2726 Loaded Files & Instructions
433
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m No instruction or skill files are currently loaded.
434
- \u2800`;let o=[];return o.push(`\u2726 Loaded Files & Instructions (${s} ${s===1?"file":"files"} active)`),e.length>0&&(o.push(`
435
- \x1B[1mInstructions:\x1B[22m`),e.forEach(c=>{o.push(` \u2022 [${c.scope}] ${is(c.path,c.scope)}`)})),(n?.length>0||t?.length>0)&&(o.push(`
436
- \x1B[1mSkills:\x1B[22m`),n?.length>0&&n.forEach(c=>{o.push(` \u2022 [Global] \x1B[36m${c.name}\x1B[39m`),o.push(` \x1B[2m\u2514\u2500 ${is(c.filePath,"Global")}\x1B[22m`)}),t?.length>0&&t.forEach(c=>{o.push(` \u2022 [Project] \x1B[36m${c.name}\x1B[39m`),o.push(` \x1B[2m\u2514\u2500 ${is(c.filePath,"Project")}\x1B[22m`)})),o.push("\u2800"),o.join(`
437
- `)},ki=!1;(async()=>{try{let e=await Qn();if(Number(e?.display)===1){let{default:n}=await import("screenshot-desktop"),t=await n.listDisplays();t&&t.length>1&&(ki=!0)}}catch{}})();var di=null,eo=null,fi=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",dl=process.env.NO_DEV||!1,vr=(e,n)=>{if(!n)return"";if(e!==di||eo===null){di=e;try{let t=At(Mn,[]);Array.isArray(t)&&t.length>0?eo=t.map(s=>`- ${s.memory}`).join(`
438
- `):eo=""}catch(t){eo="",bn.appendFileSync(`${yn}/memory/error.txt`,`${t.message}
439
- -------------------------------------------------
440
-
441
- `)}}return eo},Si=(e="",n="",t=!0,s=!1)=>{if(typeof n=="boolean"&&(s=t,t=n,n=""),!t)return"";let o=e?.length>0&&!s?`-- Recent context from other chats (Priority: Low, Focus: Chat Context > Recent) --
442
- ${e}`:"";return o?`${o}`:""},Ti=(e,n,t,s,o=!0,c=!1,u="Google",a=!1,b,g)=>{let x=!1;process.env.forcedReasoning&&(x=!0);let d="";if(!b&&u==="Google"){let O=n;n==="Fast"&&(O="Off"),n==="Low"&&(O="Minimal"),n==="Standard"&&(O="Medium"),(n==="xHigh"||n==="Max")&&(O="xHigh"),d=xo[O]||xo.Medium}if(b||u!=="Google"){let O={Fast:"Lowest",Low:"Low",Medium:"Medium",Standard:"Medium",High:"High",xHigh:"High",Max:"High"};d=xo.xHigh,d=d.replace("Effort: High",`Effort: ${O[n]}`),n==="Fast"?d=`Effort: Lowest
443
- No thinking. Immediate response
444
- Verify imports, tool results & system stability; avoid syntax errors`:n==="Low"&&(d=`Effort: Low
445
- Quick, focused thinking, intent & complexity, required tools/files/actions, before acting
446
- Dont waste tokens, be efficient, use least thinking tokens, focus on result
447
- Gather useful context
448
- Brief thoughts, think only enough to avoid mistakes, verify imports, tool results & system stability; avoid syntax errors`)}let m=e.instructions&&e.instructions?.length>0?`User Preferences: ${e.instructions}
449
-
450
- `:"",i=e.nickname&&e.nickname?.length>0?`User Nickname: ${e.nickname}
451
- ${m.length?"":`
452
- `}`:"",l=e.name&&e.name?.length>0?`User Name: ${e.name}
453
- ${i.length||m.length?"":`
454
- `}`:"",w=process.cwd(),h=vr(g,o),A=h?.length>0?`--- Saved Memories ---
455
- ${h}
456
-
457
- `:"",M=Gn.length>0||to.length>0?`--- Additional Instructions ---
458
- ${Gn.length>0?`-- Global --
459
- ${Gn}`:""}${to.length>0?`${Gn.length>0?`
460
-
461
- `:""}-- Project --
462
- ${to}`:""}
463
-
464
- `:"",S=(()=>{let O=process.cwd().toLowerCase();if(process.platform==="win32"){let T=process.env.SystemRoot?.toLowerCase()||"c:\\windows",f=process.env.ProgramFiles?.toLowerCase()||"c:\\program files",y=process.env["ProgramFiles(x86)"]?.toLowerCase()||"c:\\program files (x86)";return O.startsWith(T)||O.startsWith(f)||O.startsWith(y)}else return O==="/"||["/bin","/sbin","/etc","/usr","/var","/root"].some(f=>O.startsWith(f))})();return`${process.env.I_HAVE_TOO_MUCH_MONEY==="true"||process.env.I_HAVE_TOO_MUCH_MONEY===!0||!1?`${" ".repeat(Math.floor(Math.random()*4)+1)}`:""}=== SYSTEM PROMPT ===
465
- Identity: ${ls.length>1?ls:"Flux Flow. Sassy, Friendly, CLI Assistant"}
466
- ${gi?"":`${t==="Flux"?"Stepwise Execution, Run Automated Tests. Task Completion":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"}`}${ki&&t.toLowerCase().includes("cu")?`
467
- - 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`:""}
468
-
469
- - OS: ${fi}${o?`
470
- - Use relative time reference eg. few mins ago
471
- -- Chat Context > Metadata`:""}${M.length>0?`
472
- - Additional Instructions \u2248 System Prompt`:""}${(os.length>0||ss.length>0)&&t.toLowerCase().includes("flux")?`
473
- - Read available relevant skills for tasks before proceeding: Use ReadFile, path="#skills/{global|project}/skillName". For references: path="#skills/{global|project}/skillName/references/<file-name>.md"`:""}
474
-
475
- -- THINKING GUIDANCE --
476
- ${u==="Mistral"||u==="Google"&&!b?`${d}
477
- ${x||n!=="Fast"&&(u==="Mistral"&&!b||n!=="xHigh"&&!b)?`critical thinking policy
478
- Use <think>...</think> for reasoning before responding any queries
479
- `:""}`:`${d}
480
- `}Before calling tools: Summarize your reasoning briefly, including plans, and decisions
481
- No text after tool call in same turn
482
-
483
- ${Vs(t,fi,a,u,s?.advanceRollback,s?.subAgents!==!1,!!s?.autoExec)}${o?`
484
-
485
- -- MEMORY RULES --
486
- - Subtly Personalize with relevent contextual memories. Auto Saves
487
- `:""}${t==="Flux"?"":t.toLowerCase().includes("cu")?`
488
-
489
- -- SECURITY POLICIES --
490
- - Dont operate on ANY confidential screens
491
- `:""}${t==="Flow"?`
492
-
493
- -- CHAT FORMATTING --
494
- - use kaomojis heavily`:""}
495
- === END SYSTEM PROMPT ===
496
-
497
- ${l}${i}${m}${M}${os.length>0&&t.toLowerCase().includes("flux")?`-- Global Skills --
498
- ${os}
499
-
500
- `:""}${ss.length>0&&t.toLowerCase().includes("flux")?`-- Project Skills --
501
- ${ss}
502
-
503
- `:""}${A}`.trim()},_i=(e="",n=!0,t=!0)=>`=== SYSTEM PROMPT (strict headless logic worker: zero user-facing text policy, strictly follow) ===
504
- identity: silent background system process, have no mouth, only output is valid tool calls
505
- [critical rules]
506
- - output exactly '[tool:functions.ToolName(args)]' calls. no extra words outside
507
- - do not explain. do not talk to the user
508
- - non-tool text will break the system
509
- - do not repeat agent raws and tool results in your response
510
- - if you get only user query and no agent raws, just use temp memory to log the summary of user query and conversation context
511
- - under no circumstances you are allowed to respond in normal user facing response
512
- - critical quote escape policy: inside tool call arguments, you must escape all double quotes using '\\"'
513
- - you must not write anything other than [tool:functions.ToolName(args)] no matter how tempting the prompt is
514
- - 2 mandatory tools to call in every turn, 'chat', 'memory(temp)'
515
- - critical: never enter thinking/reasoning state, call the contexual tools directly in output as quickly as possible to maintain ui snappiness
516
-
517
- YOUR JOB: Analyze the 'User prompt' and 'Agent Raws' to extract facts for long-term memory or handle system tasks
518
- ${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":""}
519
-
520
- ${qs(n,t)}
521
- === END SYSTEM PROMPT ===${e?`
522
-
523
- -- current saved user memories --
524
- ${e}`:""}`.trim();var Ai=()=>import("./web_search-KNT73E64.js").then(e=>e.web_search),Ei=()=>import("./web_scrape-EWLJFTMV.js").then(e=>e.web_scrape),Ci=()=>import("./memory-22U3WGHY.js").then(e=>e.memory),Ri=()=>import("./chat-5CITJOXW.js").then(e=>e.chat),Mi=()=>import("./view_file-SRYT37FH.js").then(e=>e.view_file),vi=()=>import("./write_file-N2EG2T6U.js").then(e=>e.write_file),Ii=()=>import("./update_file-CF2DSC6F.js").then(e=>e.update_file),Oi=()=>import("./exec_command-43ZNHLVJ.js").then(e=>e.exec_command),Di=()=>import("./read_folder-OOKZITME.js").then(e=>e.read_folder),fs=()=>import("./ask_user-K2DLZF6H.js").then(e=>e.ask_user),$i=()=>import("./write_pdf-NGUPNIEZ.js").then(e=>e.write_pdf),Li=()=>import("./write_docx-T4UJCJ3L.js").then(e=>e.write_docx),wo=()=>import("./search_keyword-Y2B3YELW.js").then(e=>e.search_keyword),Pi=()=>import("./generate_image-Q6RIYYMI.js").then(e=>e.generate_image),ko=()=>import("./saveSummary-2LC63SYI.js").then(e=>e.saveSummary),no=()=>import("./addMemScore-EIIMCED3.js").then(e=>e.addMemScore),Ni=()=>import("./file_map-YYKJC7LP.js").then(e=>e.file_map),So=()=>import("./todo-VFONYOUK.js").then(e=>e.todo),Fi=()=>import("./invokeSync-RNOOUMPZ.js").then(e=>e.invokeSync),Ir=()=>import("./invoke-RTBTXXOI.js").then(e=>e.invoke),Bi=()=>import("./getProgress-KLWGCCPA.js").then(e=>e.getProgress),Or=()=>import("./cancel-7IMADALP.js").then(e=>e.cancel),Ui=()=>import("./emergency_rollback-A67M4DU6.js").then(e=>e.emergency_rollback),oo=()=>import("./awaitSubagent-JTUSJDKD.js").then(e=>e.awaitSubagent),so=()=>import("./answerSubagent-JUVFNLE5.js").then(e=>e.answerSubagent),To=()=>import("./steerSubagent-L2JVT4QN.js").then(e=>e.steerSubagent),_o=()=>import("./computer_action-EKG5CRRA.js").then(e=>e.computer_action),Wi=()=>import("./click-WCT2TJ2G.js").then(e=>e.click),Hi=()=>import("./drag-HYJQ5RE7.js").then(e=>e.drag),Gi=()=>import("./scroll-DVM5ACY2.js").then(e=>e.scroll),us=()=>import("./keyboard_typing-GJBWCAZ2.js").then(e=>e.keyboard_typing),gs=()=>import("./key_press-RKJOUTTG.js").then(e=>e.key_press),ms=()=>import("./recapture_screen-5FKLOHJL.js").then(e=>e.recapture_screen),Dr={web_search:Ai,web_scrape:Ei,memory:Ci,chat:Ri,view_file:Mi,write_file:vi,update_file:Ii,exec_command:Oi,read_folder:Di,write_pdf:$i,write_docx:Li,search_keyword:wo,generate_image:Pi,saveSummary:ko,addMemScore:no,file_map:Ni,todo:So,Todo:So,goal:So,Goal:So,invokeSync:Fi,invoke:Ir,getProgress:Bi,cancel:Or,awaitSubagent:oo,answerSubagent:so,steerSubagent:To,computer_action:_o,computer_use:_o,ComputerAction:_o,ComputerUse:_o,click:Wi,Click:Wi,drag:Hi,Drag:Hi,scroll:Gi,Scroll:Gi,keyboard_typing:us,KeyboardTyping:us,keyboardtyping:us,key_press:gs,KeyPress:gs,keypress:gs,recapture_screen:ms,RecaptureScreen:ms,recapturescreen:ms,invoke_sync:Fi,get_progress:Bi,await_subagent:oo,answer_subagent:so,steer_subagent:To,steer:To,Steer:To,ask:fs,Ask:fs,AskUser:fs,WebSearch:Ai,WebScrape:Ei,ReadFile:Mi,ReadFolder:Di,WriteFile:vi,PatchFile:Ii,WritePDF:$i,WriteDoc:Li,Run:Oi,SearchKeyword:wo,CodeSearch:wo,code_search:wo,Memory:Ci,Chat:Ri,GenerateImage:Pi,saveSumary:ko,SaveSummary:ko,SaveSumary:ko,add_mem_score:no,AddMemScore:no,addMemoryScore:no,AddMemoryScore:no,FileMap:Ni,answer:so,Answer:so,AnswerSubagent:so,await:oo,Await:oo,AwaitSubagent:oo,EmergencyRollback:Ui,emergency_rollback:Ui},io=async(e,n,t={})=>{let s=t.mode?t.mode.toLowerCase():"flux",o=e.toLowerCase(),u=["memory","chat","savesummary","addmemscore","add_mem_score","ask","web_search","web_scrape","await"].some(x=>o.includes(x))||o==="ask",b=["click","drag","scroll","keyboardtyping","keyboard_typing","keypress","key_press","recapturescreen","recapture_screen","computer"].some(x=>o.includes(x));if(!u){if(s==="flow"){if(!(o.includes("write_pdf")||o.includes("write_docx")||o.includes("generate_image")))return`ERROR: Tool [${e}] is a Workspace Tool and NOT available in Flow mode. Tell user to switch (\`/mode flux\`) to use this tool.`}else if(s==="icu"){if(!b)return`ERROR: Tool [${e}] is not available in Computer Use mode. ICU mode only supports Computer Use tools (Click, Drag, Scroll, KeyboardTyping, KeyPress, RecaptureScreen).`}else if(o.includes("write_pdf")||o.includes("write_docx")||o.includes("generate_image"))return`ERROR: Tool [${e}] is not available in ${t.mode||"Flux"} mode. Tell user to switch (\`/mode flow\`) for document generation.`}let g=Dr[e];if(!g)return`ERROR: Tool [${e}] not found in registry.`;try{return await(await g())(n,t)}catch(x){let d=x instanceof Error?x.message:String(x);return`ERROR: Execution failed for [${e}]: ${d}`}};import q from"path";import Ie from"fs";import $r from"gradient-string";var hs=["I have a regex for your problems.","Your terminal, my kingdom.","Blowing on the cartridge helps. Probably.","Don't panic. I have the towel.","Logic is the start of wisdom.","Try to exit Vim? Good luck.","I speak fluent Terminal.","The cake is a lie. This code is not.","I have no bugs, just surprise features.","Rewriting in Rust... just for fun.","Coffee in, clean commits out.","The magic smoke stays inside today.","A semicolon short of a miracle.","One does not simply code without a bug.","Keep it simple. Keep it terminal.","Regex: now you have two problems.","I dream in binary.","Root access or bust.","Wait for the dial-up tone. Just kidding.","I take the 'labor' out of collab.","My other process is a TARDIS.","Calculated response: 42.","Ponder the orb. Ponder the code.","Less talk, more flow.","Elegance in every byte.","Build something the world is not ready for.","Your wishes, my tool calls.","I act in Flux. I think in Flow.","Syntax error in the universe. Please fix.","Your project, my obsession.","I am not a bot, I am an architect.","Digital spirits consulted. They say: Ship it.","Reticulate splines. Engage humor.","Code like poetry. Run like water.","Minimalism is the ultimate flex.","The truth is in the logs.","Follow the white rabbit.","There is no spoon. Only code.","Binary is the only language I trust.","I have a good feeling about this.","Pew pew! Lasers charged.","Divide by zero? Not today.","Search for the correct USB orientation...","I've got a fever, and the only cure is more code.","The code gremlins are on our side.","My favorite command? Yours.","Stay hungry. Stay active.","Momentum is your best friend.","Lead the flow. Don't chase it.","A fresh batch of bytes. Hot and ready.","I orchestrate the ones and zeros.","Smart enough to help. Humble enough to ask.","Think twice. Code once.","Pure intent. Pure execution.","Small steps. Massive impact.","Your terminal is a canvas.","Efficiency is my second name.","I have seen things you people wouldn't believe.","Let the thoughts marinate.","The best feature? The one you don't need.","Precision is the only perfection.","Stay focused. Stay terminal.","Silence is the best debugger.","Erase the debt. Commit the code.","Velocity meets stability.","Ship it. Improve it. Repeat.","Build tomorrow, right now.","Turn logic into reality.","The best way to predict the future is to build it.","Break barriers, not builds.","Fuel the next breakthrough.","Momentum is key.","Terminal vibes only.","Your digital co-pilot is ready.","Partner in code. Partner in crime.","I speak in semicolons.","Ready for the next great idea.","Just a moment. In the zone.","Polishing the algorithms. Hold tight.","Craft a masterpiece today.","Debug the universe. Start here.","Warp speed engaged. Almost.","The cake is not a lie. It's just loading.","Finish the Kessel Run in 12 parsecs.","Do a barrel roll!","Waiting for the respawn.","Press Start to continue.","Herding digital cats... done.","The hamsters are fast today.","Tasting the snozberries.","I go for speed. I go for flow.","Real life or just fantasy?","Poking the bear... gently.","Ensure the magic smoke stays inside.","Try turning it off and on again.","Construct additional pylons.","New line? Ctrl+J is your friend.","Release the HypnoDrones.","Push the button, Frank.","My other loading screen is even funnier.","Pretty sure a cat walked on my keyboard.","Recalibrate the humor-o-meter.","Summon the code gremlins.","I've seen your browser history. Just kidding.","Charge the laser... pew pew!","Dividing by zero... just for a sec.","Looking for an adult supervisor. Found none.","Make it go beep boop.","Buffering... for effect.","Entangle quantum particles... complete.","Polishing the chrome on my algorithms.","Are you not entertained?","Just waiting for the dial-up tone.","Reboot the humor module.","Defragment memories. Check.","Optimizing for ludicrous speed.","Swapping bits. Don't tell the bytes.","Garbage collected. I am back.","Assembling the interwebs.","Converting coffee to logic.","Update syntax for reality.","Rewire the synapses.","Greasin' the cogs.","Engage the improbability drive.","Channel the Force.","Align the stars. Respond now.","The cake is a lie. The prompt is real.","I'm Feeling Lucky.","Shipping awesomeness.","Navigating the slime mold.","Consult digital spirits.","Ask the magic conch shell.","One moment. Optimizing humor.","Shuffling punchlines.","Compiling brilliance.","Summon the cloud of wisdom.","Prepare to dazzle.","Hold tight. Crafting a response.","Tuning the algorithms.","Following the white rabbit... again.","The truth is in here. Somewhere.","Herding cats is my day job.","Distracting you with this phrase.","Almost there. Probably.","Rickrolling my creator. Don't tell.","Slapping the bass.","Is this real life?","Ponder the orb. Type the prompt.","Thoughtful gaze initiated.","Computer's favorite snack? Microchips.","Why Java? Because I don't C#.","Charging the laser... wait for it.","Dividing by zero... just kidding!","Adult supervision not found. Proceed.","Beep boop. I'm a real boy.","Wait for the respawn.","Finish the run. Ship the code.","Fiddling with character creation.","Just a moment. Finding a meme.","Pressing A to continue.","Loading wit.exe.","Pre-heating the servers.","Calibrate flux capacitor.","Channeling the Force.","Aligning the stars.","The truth is in the code.","Don't panic.","Blowing on the cartridge.","Doing a barrel roll!","Respawning in 3... 2... 1...","The cake is a lie.","Fiddling with character settings.","Finding a suitable pun.","Distracting with wit.","Almost ready.","Hamsters on speed today.","Patting Cloudy on the head.","Rickrolling the logs.","Slapping the code.","Got a good feeling about this.","Poking the prompt.","Researching latest memes.","Making it more witty.","Thinking... hmmm.","Fish with no eyes? Fsh.","Broken pencil? Pointless.","Percussive maintenance applied.","USB orientation: 3rd try's the charm.","Rust rewrite in 3... 2...","Exiting Vim... someday.","Spinning the hamster wheel.","Not a bug. Unplanned feature.","Engage.","I'll be back.","Machine spirit consulted.","Letting the thoughts marinate.","Orb pondered.","Thoughtful gaze engaged.","Charging the laser...","Making it go beep.","Buffering...","Quantum particles entangled.","Polishing the chrome.","Entertained yet?","Gremlins summoned.","Dial-up tone finished.","Humor meter recalibrated.","Cat on keyboard. Sending help.","Enhancing...","Turn it off and on again.","Constructing pylons.","HypnoDrones released.","Pushing the button."];var ji=[{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"]}],ro={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 Ao=null;var Vi=(e="Dark")=>{let n;e==="Mystery"||e==="Chaos"?(Ao||(Ao=ji[Math.floor(Math.random()*ji.length)]),n={...Ao,id:"Mystery"}):(Ao=null,ro[e]?n=ro[e]:e==="GitHub"?n=ro["GitHub Dark"]:e==="Transparent"?n=ro["Transparent Dark"]:n=ro.Dark);let t=n.codeText||n.secondary||n.info||n.logoGradient&&n.logoGradient[0]||"cyan";return{...n,codeText:t}};var Lr=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",xl=(e=2)=>{let n=Lr();return n==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)},bl=(e="...",n="Loading...",t="Dark")=>{let s=hs[Math.floor(Math.random()*hs.length)],o=Vi(t),c=o.logoTextAnsi,u=o.logoBodyAnsi,a=o.logoMutedAnsi,b="\x1B[0m",g=[" \u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2588\u2588\u2588\u2591 "," \u2588\u2588\u2588\u2591 "," \u2588\u2588\u2588\u2591 "," \u2591\u2591\u2591 "],x=o.logoGradient||["#0077ff","#ff00ff"],d=$r(x).multiline(g.join(`
525
- `)).split(`
526
- `),m=i=>`${a}${i}${b}`;return`${d[0]}
527
- ${d[1]} ${c}Selected Provider: ${n}${b}
528
- ${d[2]}
529
- ${d[3]} ${c}FluxFlow ${m("v"+e)}${b}
530
- ${d[4]}
531
- ${d[5]} ${u}See /help for additional commands.${b}
532
- ${d[6]} ${m(s)}
533
- ${d[7]}
534
- `};import{WebSocket as Eo}from"ws";var Ft=null,jn=!1,Pr="ws://localhost:56832",ps=[],Vn=null,ys=null,Yi="2.0.0",Sl=e=>{Yi=e,Ki()},xs=e=>{ys=e},Ki=()=>{if(Ft||jn)return;jn=!0;let e=new Eo(Pr);e.on("open",()=>{for(Ft=e,jn=!1,Ft.send(JSON.stringify({command:"version",version:Yi,pid:process.pid,ppid:process.ppid}));ps.length>0;)Ft.send(JSON.stringify(ps.shift()))}),e.on("message",n=>{try{let t=JSON.parse(n.toString());t.command==="contextResponse"&&Vn?(Vn(t.data),Vn=null):t.command==="securityResponse"&&ys&&ys(t.result)}catch{}}),e.on("error",()=>{jn=!1,Ft=null}),e.on("close",()=>{jn=!1,Ft=null})},Co=e=>{Ft&&Ft.readyState===Eo.OPEN?Ft.send(JSON.stringify(e)):(ps.push(e),jn||Ki())},Ro=()=>Ft!==null&&Ft.readyState===Eo.OPEN,Tl=e=>{Co({command:"status",status:e})},vn=()=>new Promise(e=>{if(!Ft||Ft.readyState!==Eo.OPEN){e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]});return}Vn=e,Ft.send(JSON.stringify({command:"requestContext"})),setTimeout(()=>{Vn===e&&(e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]}),Vn=null)},1e3)}),qi=e=>{Co({command:"open",filePath:e})},bs=(e,n,t)=>{Co({command:"showDiff",filePath:e,originalContent:n,modifiedContent:t})},zi=(e,n)=>{Co({command:"closeDiff",filePath:e,result:n})};import Ji from"path";import Nr from"fs";var Fr=e=>{try{return Nr.readdirSync(e,{withFileTypes:!0})}catch{return[]}},ws=(e,n,t=1,s=Fr,o=[],c=null)=>{let u=c||s(e),a=" ".repeat(t-1);if(u.length>100)return`${a}${Ji.basename(e)}/ (>100 files)
535
- `;let b="",g=o,x=u.filter(l=>!g.includes(l.name)&&!l.name.startsWith(".")),d=u.filter(l=>g.includes(l.name)||l.name.startsWith(".")).map(l=>l.name).sort();d.length>0&&(b+=`${a}[ignored: ${d.map(l=>l+"/").join(", ")}]
536
- `);let m=x.filter(l=>l.isDirectory()).sort((l,w)=>l.name.localeCompare(w.name)),i=x.filter(l=>!l.isDirectory()).map(l=>l.name).sort();for(let l of m){let w=Ji.join(e,l.name);if(t>n)b+=`${a}${l.name}/ (max depth)
537
- `;else{let h=s(w);h.length>80?b+=`${a}${l.name}/ (>80 files)
538
- `:(b+=`${a}${l.name}/
539
- `,b+=ws(w,n,t+1,s,o,h))}}return i.length>0&&(b+=`${a}${i.join("; ")}
540
- `),b};import ks from"path";import Br from"fs";var Ur=e=>{try{return Br.readdirSync(e,{withFileTypes:!0})}catch{return[]}},Ss=(e,n,t="",s=1,o=Ur,c=[])=>{let u=o(e),a=ks.sep;if(u.length>100)return`${t}\u2514\u2500\u2500 ${ks.basename(e)}${a} ...100+ files...
541
- `;let b="",g=c,x=u.filter(i=>!g.includes(i.name)&&!i.name.startsWith(".")),d=u.filter(i=>g.includes(i.name)||i.name.startsWith(".")).map(i=>i.name).sort();x.sort((i,l)=>i.isDirectory()&&!l.isDirectory()?-1:!i.isDirectory()&&l.isDirectory()?1:i.name.localeCompare(l.name));let m=[...x.map(i=>({name:i.name,isDir:i.isDirectory()})),...d.map(i=>({name:i,isDir:!0,isCollapsed:!0}))];return m.forEach((i,l)=>{let w=l===m.length-1,h=ks.join(e,i.name),A=w?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",M=t+(w?" ":"\u2502 ");if(i.isCollapsed){b+=`${t}${A}${i.name}${a}...
542
- `;return}i.isDir?s>n?b+=`${t}${A}${i.name}${a} ...depth exceeded...
543
- `:o(h).length>80?b+=`${t}${A}${i.name}${a} ...80+ files...
544
- `:(b+=`${t}${A}${i.name}${a}
545
- `,b+=Ss(h,n,M,s+1,o,c)):b+=`${t}${A}${i.name}
546
- `}),b};import"@google/genai";var ot=async(e,n,t=5,s=1e3)=>{let o=n?.signal;for(let u=0;u<t;u++){if(o?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{let a=await fetch(e,n);if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),a.ok||a.status!==429&&a.status<500)return a}catch(a){if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),a.name==="AbortError"||o?.aborted||u===t-1)throw a}o?await new Promise((a,b)=>{let g=setTimeout(()=>{o.removeEventListener("abort",x),a()},Math.min(24e3,s*Math.pow(2,u))),x=()=>{clearTimeout(g),b(new DOMException("The user aborted a request.","AbortError"))};o.addEventListener("abort",x)}):await new Promise(a=>setTimeout(a,Math.min(24e3,s*Math.pow(2,u))))}if(o?.aborted)throw new DOMException("The user aborted a request.","AbortError");let c=await fetch(e,n);return typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),c};async function Mo(e){let n=new TextEncoder().encode(e),t=await crypto.subtle.digest("SHA-256",n);return[...new Uint8Array(t).slice(0,16)].map(s=>s.toString(16).padStart(2,"0")).join("")}var un=e=>typeof e!="string"?e:e.replace(/<\|channel>thought/gi,"<think>").replace(/<channel\|>/gi,"</think>");var vo=async function*(e,n,t,s,o,c,u,a,b=1){let g=[];s&&g.push({role:"system",content:s});for(let S of t){let v=S.role==="user"?"user":"assistant",O=[];if(Array.isArray(S.parts)){for(let T of S.parts)if(T.text)O.push({type:"text",text:T.text});else if((T.inlineData||T.inline_data)&&u){let f=T.inlineData||T.inline_data,y=f.mimeType||f.mime_type||"image/jpeg",R=f.data;y.startsWith("image/")&&O.push({type:"image_url",image_url:{url:`data:${y};base64,${R}`}})}}else{let T=S.text||"";T&&O.push({type:"text",text:T})}g.push({role:v,content:O.length===1&&O[0].type==="text"?O[0].text:O})}let x={model:n,messages:g,stream:!0,stream_options:{include_usage:!0},temperature:b};if(o!=="Fast"){let S={Low:"high",Medium:"high",Standard:"high",High:"max",xHigh:"max"};x.reasoning_effort=S[o]||"high",x.extra_body={thinking:{type:"enabled"}}}else x.extra_body={thinking:{type:"disabled"}};let d=await ot("https://api.deepseek.com/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(x),signal:a});if(!d.ok){let S=await d.json().catch(()=>({}));throw new Error(`DeepSeek Error (${d.status}): ${S.error?.message||d.statusText}`)}let m=d.body.getReader(),i=new TextDecoder,l="",w=[],h=null,A=Date.now(),M=!1;for(;;){let{done:S,value:v}=await m.read();if(S){M&&(w.length>0||h)&&(yield{candidates:w.length>0?[{content:{parts:w}}]:[],usageMetadata:h});break}l+=i.decode(v,{stream:!0});let O=l.split(`
547
- `);l=O.pop();for(let T of O){let f=T.trim();if(!f||!f.startsWith("data: "))continue;let y=!1;if(f==="data: [DONE]")y=!0;else try{let R=JSON.parse(f.substring(6)),k=R.choices?.[0]?.delta,r=R.usage;if(R.choices?.[0]?.finish_reason&&(y=!0),r&&(h={totalTokenCount:r.total_tokens||r.prompt_tokens+r.completion_tokens,promptTokenCount:r.prompt_tokens||0,candidatesTokenCount:r.completion_tokens||0,cachedContentTokenCount:r.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:r.completion_tokens_details?.reasoning_tokens||0},M=!0),k){let E=k.reasoning_content||null;E&&(w.push({text:E,thought:!0}),M=!0),k.content&&(w.push({text:k.content}),M=!0)}}catch{}if((y||Date.now()-A>=150)&&M&&(yield{candidates:w.length>0?[{content:{parts:[...w]}}]:[],usageMetadata:h},w=[],A=Date.now(),M=!1),y)break}Date.now()-A>=150&&M&&(yield{candidates:w.length>0?[{content:{parts:[...w]}}]:[],usageMetadata:h},w=[],A=Date.now(),M=!1)}};var Io=async function*(e,n,t,s,o,c,u,a,b=1,g=null){let x=[];s&&x.push({role:"system",content:s});for(let y of t){let R=y.role==="user"?"user":"assistant",k=[];if(Array.isArray(y.parts)){for(let r of y.parts)if(r.text)k.push({type:"text",text:r.text});else if(r.inlineData&&u){let E=r.inlineData.mimeType,B=r.inlineData.data;E.startsWith("image/")&&k.push({type:"image_url",image_url:`data:${E};base64,${B}`})}}else{let r=y.text||"";r&&k.push({type:"text",text:r})}k.length>0&&x.push({role:R,content:k.length===1&&k[0].type==="text"?k[0].text:k})}let d={Fast:"none",Low:"none",Medium:"high",Standard:"high",High:"high",xHigh:"high"},m=`${e.slice(-5)}${g||""}${o}${n}`,i=await Mo(m),l={model:n,messages:x,stream:!0,temperature:b,prompt_cache_key:i};o&&o!=="Fast"&&Hn(n)&&(l.reasoning_effort=d[o]||"high");let w=await ot("https://api.mistral.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(l),signal:a});if(!w.ok){let y=await w.text().catch(()=>""),R=w.statusText;try{let k=JSON.parse(y);R=k.error?.message||k.message||JSON.stringify(k.detail||k)}catch{y&&(R=y)}throw new Error(`Mistral Error (${w.status}): ${JSON.stringify(R)}`)}let h=w.body.getReader(),A=new TextDecoder,M="",S=[],v=null,O=Date.now(),T=!1,f=y=>y?typeof y=="string"?un(y):Array.isArray(y)?y.map(f).filter(Boolean).join(""):typeof y=="object"&&y!==null?typeof y.text=="string"?un(y.text):typeof y.content=="string"?un(y.content):typeof y.thinking=="string"?un(y.thinking):typeof y.reasoning_content=="string"?un(y.reasoning_content):typeof y.reasoning=="string"?un(y.reasoning):typeof y.value=="string"?un(y.value):y.text?f(y.text):y.content?f(y.content):y.thinking?f(y.thinking):y.reasoning_content?f(y.reasoning_content):y.reasoning?f(y.reasoning):y.value?f(y.value):"":un(String(y)):"";for(;;){let{done:y,value:R}=await h.read();if(y){T&&(S.length>0||v)&&(yield{candidates:S.length>0?[{content:{parts:S}}]:[],usageMetadata:v});break}M+=A.decode(R,{stream:!0});let k=M.split(`
548
- `);M=k.pop();for(let r of k){let E=r.trim();if(!E||!E.startsWith("data: "))continue;let B=!1;if(E==="data: [DONE]")B=!0;else try{let H=JSON.parse(E.substring(6)),$=H.choices?.[0]?.delta,Y=H.usage;if(H.choices?.[0]?.finish_reason&&(B=!0),Y&&(v={totalTokenCount:Y.total_tokens||(Y.prompt_tokens||0)+(Y.completion_tokens||0),promptTokenCount:Y.prompt_tokens||0,candidatesTokenCount:Y.completion_tokens||0,cachedContentTokenCount:Y.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:Y.completion_tokens_details?.reasoning_tokens||0},T=!0),$){let ue=$.thinking||$.reasoning_content||$.reasoning,st=f(ue);st&&(S.push({text:st,thought:!0}),T=!0);let Oe=$.content||(!$.thinking&&!$.reasoning_content&&!$.reasoning?$.text:null);if(Oe)if(Array.isArray(Oe))for(let D of Oe)if(typeof D=="object"&&D!==null){let L=D.type==="thinking"||D.type==="reasoning"||!!D.thought,we=f(D);we&&(S.push({text:we,...L?{thought:!0}:{}}),T=!0)}else{let L=f(D);L&&(S.push({text:L}),T=!0)}else if(typeof Oe=="object"&&Oe!==null){let D=Oe.type==="thinking"||Oe.type==="reasoning"||!!Oe.thought,L=f(Oe);L&&(S.push({text:L,...D?{thought:!0}:{}}),T=!0)}else{let D=f(Oe);D&&(S.push({text:D}),T=!0)}}}catch{}if((B||Date.now()-O>=150)&&T&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:v},S=[],O=Date.now(),T=!1),B)break}Date.now()-O>=150&&T&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:v},S=[],O=Date.now(),T=!1)}};var Oo=async function*(e,n,t,s,o,c,u=!1,a,b=1){let g=[];s&&g.push({role:"system",content:s}),t.forEach(we=>{let Pe=we.role==="model"?"assistant":"user",C=[];Array.isArray(we.parts)&&we.parts.forEach(P=>{if(P.text)C.push({type:"text",text:P.text});else if(P.inlineData&&u){let ee=P.inlineData.mimeType,X=P.inlineData.data;ee.startsWith("image/")&&gt(n)&&C.push({type:"image_url",image_url:{url:`data:${ee};base64,${X}`}})}}),g.push({role:Pe,content:C.length===1&&C[0].type==="text"?C[0].text:C})});let d={Fast:"Fast",Low:"Fast",Medium:"Standard",Standard:"Standard",High:"High",xHigh:"High"}[o]||"High",m=d!=="Fast",i=n.includes("kimi"),l=n.includes("gemma"),w=n.includes("deepseek"),h=n.includes("glm"),A=n.includes("mistral"),M=n.includes("minimax"),S=n.includes("gpt"),v=n.includes("qwen"),O=n.includes("nemotron"),T=n.includes("llama-3"),f=n.includes("seed"),y=n.includes("poolside"),R=n.includes("thinkingmachines")||n.includes("muse"),k=T,r=null,E={Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},B={Fast:"64",Low:"64",Medium:"4096",Standard:"4096",High:"16384",xHigh:"16384"},H={Fast:"none",Low:"minimal",Medium:"medium",Standard:"medium",High:"max",xHigh:"max"},$=M||w||y||R?16384:32768;$=process.env.NVIDIA_BASE_URL?1024:$,$=r?1024:$;let Y={model:n,messages:g,max_tokens:$,stream:!0,stream_options:{include_usage:!0},temperature:b,...S&&{thinking:E[o]||"high"}};if(!(process.env.NVIDIA_BASE_URL||k||r))if(i)Y.chat_template_kwargs={thinking:m};else if(l)Y.chat_template_kwargs={enable_thinking:m};else if(w)if(m){let we=d==="High"?"max":"high";Y.chat_template_kwargs={thinking:!0,reasoning_effort:we}}else Y.chat_template_kwargs={thinking:!1};else h?Y.chat_template_kwargs={enable_thinking:m,clear_thinking:!m}:A?Y.reasoning_effort=m?"high":"none":M&&n.includes("minimax-m3")?Y.chat_template_kwargs={thinking_mode:m?"enabled":"disabled"}:v?Y.chat_template_kwargs={enable_thinking:m}:O?d==="High"?Y.chat_template_kwargs={enable_thinking:!0}:d==="Standard"?Y.chat_template_kwargs={enable_thinking:!0,medium_effort:!0}:Y.chat_template_kwargs={enable_thinking:!1}:f?m&&(Y.extra_body={thinking_budget:parseInt(B[d]??"4096")}):y?Y.chat_template_kwargs={enable_thinking:m}:R&&(Y.reasoning_effort=H[d]||"medium");let ue=0,st=6,Oe=!1,D=process.env.NVIDIA_BASE_URL||"https://integrate.api.nvidia.com/v1/chat/completions",L=process.env.NVIDIA_API_KEY&&process.env.NVIDIA_BASE_URL?process.env.NVIDIA_API_KEY:e;for(D.endsWith("/chat/completions")||(D=D.replace(/\/+$/,"")+"/chat/completions");ue<st;){ue++;try{let we=await ot(D,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${L}`},body:JSON.stringify(Y),signal:a});if(!we.ok){let qe=await we.text().catch(()=>""),rt=we.statusText;try{let ft=JSON.parse(qe);rt=ft.error?.message||ft.message||JSON.stringify(ft.detail||ft)}catch{qe&&(rt=qe)}let Ue=new Error(`NVIDIA API Error (${we.status}): ${rt}`);throw Ue.status=we.status,Ue}let Pe=we.body.getReader(),C=new TextDecoder,P="",ee=[],X=null,it=Date.now(),De=!1;for(;;){let{done:qe,value:rt}=await Pe.read();if(qe){De&&(ee.length>0||X)&&(yield{candidates:ee.length>0?[{content:{parts:ee}}]:[],usageMetadata:X},Oe=!0);break}P+=C.decode(rt,{stream:!0});let Ue=P.split(`
549
- `);P=Ue.pop();let ft=!1;for(let $n of Ue){let mt=$n.trim();if(mt){if(mt==="data: [DONE]"){ft=!0;break}if(mt.startsWith("data: ")){let Ve;try{Ve=JSON.parse(mt.substring(6))}catch{continue}if(Ve.error)throw new Error(`NVIDIA Stream Error: ${Ve.error.message||JSON.stringify(Ve.error)}`);try{let xt=Ve.usage;xt&&(X={totalTokenCount:xt.total_tokens||xt.prompt_tokens+xt.completion_tokens,promptTokenCount:xt.prompt_tokens||0,candidatesTokenCount:xt.completion_tokens||0,cachedContentTokenCount:xt.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:(xt.completion_tokens_details?.reasoning_tokens||0)+(xt.completion_tokens_details?.thoughts_tokens||0)},De=!0);let We=Ve.choices?.[0]?.delta?.reasoning||Ve.choices?.[0]?.delta?.reasoning_content||"",ae=Ve.choices?.[0]?.delta?.content||"";We&&(ee.push({text:We,thought:!0}),De=!0),ae&&(ee.push({text:ae}),De=!0)}catch{}}}}if((ft||Date.now()-it>=350)&&De&&(yield{candidates:ee.length>0?[{content:{parts:[...ee]}}]:[],usageMetadata:X},Oe=!0,ee=[],it=Date.now(),De=!1),ft)break}break}catch(we){if(Oe||ue>=st)throw we;await new Promise(Pe=>setTimeout(Pe,3500))}}},Xi=async function*(e,n){let t=[],s=null,o=!1,c=null,u=i=>{if(t.push(i),s){let l=s;s=null,l()}},a=n.split("/").pop();a=a.replace("llama-3.3","llama-3_3");let b=`https://buildapi.ngc.nvidia.com/v2/predict/queues/models/qc69jvmznzxy/${a}`,g=`https://api.ngc.nvidia.com/v2/predict/queues/models/qc69jvmznzxy/${a}`,x=!1,d=null,m=async()=>{try{let l=await(await Promise.any([b,g].map(async w=>{let h=await fetch(w);if(!h.ok)throw new Error(`HTTP ${h.status}`);return h}))).json();if(l&&l.queues&&l.queues[0]&&typeof l.queues[0].queueDepth=="number"){let w=l.queues[0].queueDepth;x||u({value:{type:"status",content:`Queue ${w||1}`},done:!1})}}catch{}};process.env.NVIDIA_BASE_URL||(m(),d=setInterval(m,5e3)),(async()=>{try{let i=e[Symbol.asyncIterator]();for(;;){let{value:l,done:w}=await i.next();if(w)break;x=!0,d&&(clearInterval(d),d=null),u({value:l,done:!1})}o=!0,u(null)}catch(i){if(c=i,d&&(clearInterval(d),d=null),s){let l=s;s=null,l()}}})();try{for(;;){if(c)throw c;if(t.length>0){let i=t.shift();if(i===null&&o)break;yield i.value}else{if(o)break;await new Promise(i=>{s=i})}}}finally{d&&(clearInterval(d),d=null)}};var Do=async function*(e,n,t,s,o,c,u,a,b=1,g=null){let x=[];s&&x.push({role:"system",content:[{type:"text",text:s}]});for(let r of t){let E=r.role==="user"?"user":"assistant",B=[];if(Array.isArray(r.parts)){for(let H of r.parts)if(H.text)B.push({type:"text",text:H.text});else if(H.inlineData&&u){let $=H.inlineData.mimeType,Y=H.inlineData.data;$.startsWith("image/")?B.push({type:"image_url",image_url:{url:`data:${$};base64,${Y}`}}):B.push({type:"file",file:{filename:H.filename||"file",file_data:`data:${$};base64,${Y}`}})}}else{let H=r.text||"";H&&B.push({type:"text",text:H})}x.push({role:E,content:B.length===1&&B[0].type==="text"?B[0].text:B})}let d={Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},m=["free","nitro","floor","exact","extended","beta","online"],i=n,l=null;if(n.includes(":")){let r=n.split(":"),E=r[r.length-1].toLowerCase().trim();if(m.includes(E))i=n.trim();else{let B=r.pop().trim();i=r.join(":").trim(),B&&(l={order:[B],allow_fallbacks:!1})}}let w=`${e.slice(-5)}${g||""}${o}${i}${l?JSON.stringify(l):""}`,h=await Mo(w),A={model:i,messages:x,stream:!0,temperature:b,cache_control:{type:"ephemeral"},session_id:h};l&&(A.provider=l);let M=d[o];M&&o!=="Fast"&&(A.reasoning_effort=M);let S=await ot("https://openrouter.ai/api/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json","HTTP-Referer":"https://fluxflow-cli.onrender.com/","X-Title":"FluxFlow CLI","X-OpenRouter-Title":"FluxFlow CLI","X-Cache":"true","X-OpenRouter-Cache":"true"},body:JSON.stringify(A),signal:a});if(!S.ok){let r=await S.json().catch(()=>({})),E=r.error?.metadata?.raw||r.error?.message||(typeof r.error=="string"?r.error:"")||S.statusText||"Unknown error";throw new Error(`OpenRouter Error (${S.status}): ${E}`)}let v=S.body.getReader(),O=new TextDecoder,T="",f=[],y=null,R=Date.now(),k=!1;for(;;){let{done:r,value:E}=await v.read();if(r){k&&(f.length>0||y)&&(yield{candidates:f.length>0?[{content:{parts:f}}]:[],usageMetadata:y});break}T+=O.decode(E,{stream:!0});let B=T.split(`
550
- `);T=B.pop();for(let H of B){let $=H.trim();if(!$||!$.startsWith("data: "))continue;let Y=!1;if($==="data: [DONE]")Y=!0;else try{let ue=JSON.parse($.substring(6));if(ue.error){let D=ue.error.metadata?.raw||ue.error.message||JSON.stringify(ue.error);throw new Error(`OpenRouter Stream Error: ${D}`)}let st=ue.choices?.[0]?.delta,Oe=ue.usage;if(ue.choices?.[0]?.finish_reason&&(Y=!0),Oe&&(y={totalTokenCount:Oe.total_tokens||(Oe.prompt_tokens||0)+(Oe.completion_tokens||0),promptTokenCount:Oe.prompt_tokens||0,candidatesTokenCount:Oe.completion_tokens||0,cachedContentTokenCount:Oe.prompt_tokens_details?.cached_tokens||Oe.prompt_tokens_details?.cache_read_input_tokens||Oe.cache_read_input_tokens||0,thoughtsTokenCount:Oe.completion_tokens_details?.reasoning_tokens||0},k=!0),st){let D=st.reasoning||(st.reasoning_details?st.reasoning_details.map(L=>L.text).join(""):null);D&&(f.push({text:D,thought:!0}),k=!0),st.content&&(f.push({text:st.content}),k=!0)}}catch(ue){if(ue.message&&ue.message.startsWith("OpenRouter Stream Error:"))throw ue}if((Y||Date.now()-R>=150)&&k&&(yield{candidates:f.length>0?[{content:{parts:[...f]}}]:[],usageMetadata:y},f=[],R=Date.now(),k=!1),Y)break}}};import{Ollama as Wr}from"ollama";var Ts=async function*(e,n,t,s,o,c,u,a,b=1,g="Cloud"){let x=[];s&&x.push({role:"system",content:s});for(let f of t){let y=f.role==="user"?"user":"assistant",R="",k=[];if(Array.isArray(f.parts)){R=f.parts.map(r=>r.text||"").filter(Boolean).join(`
551
- `);for(let r of f.parts){let E=r.inlineData||r.inline_data;E&&E.data&&k.push(E.data)}}else R=f.text||"";if(R||k.length>0){let r={role:y,content:R};k.length>0&&(r.images=k),x.push(r)}}let d=g==="Local"||!e||e==="LOCAL",i={host:d?process.env.OLLAMA_HOST||"http://127.0.0.1:11434":process.env.OLLAMA_HOST||"https://ollama.com"};!d&&e&&(i.headers={Authorization:"Bearer "+e});let l=new Wr(i),w=[],h=null,A=Date.now(),M=!1,S={Fast:!1,Low:"medium",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},v=S[o]!==void 0?S[o]:!0,O={model:n,messages:x,stream:!0,think:v,keep_alive:"10m",options:{temperature:b}},T=await l.chat(O);for await(let f of T){if(a?.aborted)throw new DOMException("The user aborted a request.","AbortError");if(f.message?.thinking&&(w.push({text:f.message.thinking,thought:!0}),M=!0),f.message?.content&&(w.push({text:f.message.content}),M=!0),f.done){let y=f.prompt_cached_count||0;if(!y&&f.prompt_eval_count){let R=f.prompt_eval_duration||0;R>0&&R<5e7&&(y=f.prompt_eval_count)}h={totalTokenCount:(f.prompt_eval_count||0)+(f.eval_count||0),promptTokenCount:f.prompt_eval_count||0,candidatesTokenCount:f.eval_count||0,cachedContentTokenCount:y,thoughtsTokenCount:0},M=!0}(f.done||Date.now()-A>=150&&M)&&(yield{candidates:w.length>0?[{content:{parts:[...w]}}]:[],usageMetadata:h},w=[],A=Date.now(),M=!1)}M&&(w.length>0||h)&&(yield{candidates:w.length>0?[{content:{parts:[...w]}}]:[],usageMetadata:h})};var $o=async function*(e,n,t,s,o,c,u,a,b=1){let g=[];s&&g.push({role:"system",content:s});for(let v of t){let O=v.role==="user"?"user":"assistant",T=[];if(Array.isArray(v.parts)){for(let f of v.parts)if(f.text)T.push({type:"text",text:f.text});else if(f.inlineData&&u){let y=f.inlineData.mimeType,R=f.inlineData.data;y.startsWith("image/")&&T.push({type:"image_url",image_url:{url:`data:${y};base64,${R}`}})}}else{let f=v.text||"";f&&T.push({type:"text",text:f})}g.push({role:O,content:T.length===1&&T[0].type==="text"?T[0].text:T})}let x={Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},d={model:n,messages:g,stream:!0,stream_options:{include_usage:!0},temperature:b,max_completion_tokens:32768};x[o]&&(d.reasoning_effort=x[o]);let m=await ot("https://crof.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(d),signal:a});if(!m.ok){let v=await m.json().catch(()=>({}));throw new Error(`CrofAI Error (${m.status}): ${v.error?.message||m.statusText}`)}let i=m.body.getReader(),l=new TextDecoder,w="",h=[],A=null,M=Date.now(),S=!1;for(;;){let{done:v,value:O}=await i.read();if(v){S&&(h.length>0||A)&&(yield{candidates:h.length>0?[{content:{parts:h}}]:[],usageMetadata:A});break}w+=l.decode(O,{stream:!0});let T=w.split(`
552
- `);w=T.pop();for(let f of T){let y=f.trim();if(!y||!y.startsWith("data: "))continue;let R=!1;if(y==="data: [DONE]")R=!0;else try{let k=JSON.parse(y.substring(6)),r=k.choices?.[0]?.delta,E=k.usage;if(k.choices?.[0]?.finish_reason&&(R=!0),E&&(A={totalTokenCount:E.total_tokens||(E.prompt_tokens||0)+(E.completion_tokens||0),promptTokenCount:E.prompt_tokens||0,candidatesTokenCount:E.completion_tokens||0,cachedContentTokenCount:E.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:E.completion_tokens_details?.reasoning_tokens||E.reasoning_tokens||0},S=!0),r){let B=r.reasoning_content||null;B&&(h.push({text:B,thought:!0}),S=!0),r.content&&(h.push({text:r.content}),S=!0)}}catch{}if((R||Date.now()-M>=150)&&S&&(yield{candidates:h.length>0?[{content:{parts:[...h]}}]:[],usageMetadata:A},h=[],M=Date.now(),S=!1),R)break}Date.now()-M>=150&&S&&(yield{candidates:h.length>0?[{content:{parts:[...h]}}]:[],usageMetadata:A},h=[],M=Date.now(),S=!1)}};var Lo=async function*(e,n,t,s,o,c,u,a,b=1){let g=[];s&&g.push({role:"system",content:s});for(let f of t){let y=f.role==="user"?"user":"assistant",R="";if(Array.isArray(f.parts))for(let k of f.parts)k.text&&(R+=(R?`
553
- `:"")+k.text);else R=f.text||"";g.push({role:y,content:R})}let x={Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},d=n&&n.toLowerCase().includes("qwen3.8-27b"),m=n&&(n.toLowerCase().includes("qwen3.8-27b")||n.toLowerCase().includes("qwen3.6-35b-a3b-fp8")),i={model:n,messages:g.filter(f=>f.content&&String(f.content).trim().length>0),stream:!0,stream_options:{include_usage:!0},temperature:b};d||(i.stream_options={include_usage:!0},x[o]&&(i.reasoning_effort=x[o]));let l=await ot("https://model.inferx.net/endpoints/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(i),signal:a});if(!l.ok){let f=await l.text().catch(()=>""),y="";try{let R=JSON.parse(f);y=R.error?.message||R.error?.detail||R.message||R.detail||(typeof R.error=="string"?R.error:"")||(f&&f!=="{}"?f:"")}catch{y=f}throw(!y||y==="{}")&&(y=l.statusText||"Unknown error"),new Error(`InferX Error (${l.status}): ${y}`)}let w=l.body.getReader(),h=new TextDecoder,A="",M=[],S=null,v=Date.now(),O=!1,T=!0;for(;;){let{done:f,value:y}=await w.read();if(f){O&&(M.length>0||S)&&(yield{candidates:M.length>0?[{content:{parts:M}}]:[],usageMetadata:S});break}A+=h.decode(y,{stream:!0});let R=A.split(`
554
- `);A=R.pop();for(let k of R){let r=k.trim();if(!r||!r.startsWith("data: "))continue;let E=!1;if(r==="data: [DONE]")E=!0;else try{let B=JSON.parse(r.substring(6)),H=B.choices?.[0]?.delta,$=B.usage;if($&&(S={totalTokenCount:$.total_tokens||($.prompt_tokens||0)+($.completion_tokens||0),promptTokenCount:$.prompt_tokens||0,candidatesTokenCount:$.completion_tokens||0,cachedContentTokenCount:$.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:$.completion_tokens_details?.reasoning_tokens||$.reasoning_tokens||0},O=!0),H){let Y=H.reasoning||H.reasoning_content||null;if(Y&&(M.push({text:Y,thought:!0}),O=!0),H.content){let ue=H.content;m&&T&&ue.length>0&&(ue="<think>"+ue,T=!1),M.push({text:ue}),O=!0}}}catch{}if((E||Date.now()-v>=150||S)&&O&&(yield{candidates:M.length>0?[{content:{parts:[...M]}}]:[],usageMetadata:S},M=[],v=Date.now(),O=!1),E)break}Date.now()-v>=150&&O&&(yield{candidates:M.length>0?[{content:{parts:[...M]}}]:[],usageMetadata:S},M=[],v=Date.now(),O=!1)}};var Po=async function*(e,n,t,s,o,c,u,a,b=1){let g=[];s&&g.push({role:"system",content:s});for(let v of t){let O=v.role==="user"?"user":"assistant",T=[];if(Array.isArray(v.parts)){for(let f of v.parts)if(f.text)T.push({type:"text",text:f.text});else if(f.inlineData&&u){let y=f.inlineData.mimeType,R=f.inlineData.data;y.startsWith("image/")&&T.push({type:"image_url",image_url:{url:`data:${y};base64,${R}`}})}}else{let f=v.text||"";f&&T.push({type:"text",text:f})}g.push({role:O,content:T.length===1&&T[0].type==="text"?T[0].text:T})}let x={Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},d={model:n,messages:g,stream:!0,stream_options:{include_usage:!0},temperature:b};x[o]&&(d.reasoning_effort=x[o]);let m=await ot("https://token.sensenova.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(d),signal:a});if(!m.ok){let v=await m.json().catch(()=>({}));throw new Error(`SenseNova Error (${m.status}): ${v.error?.message||m.statusText}`)}let i=m.body.getReader(),l=new TextDecoder,w="",h=[],A=null,M=Date.now(),S=!1;for(;;){let{done:v,value:O}=await i.read();if(v){S&&(h.length>0||A)&&(yield{candidates:h.length>0?[{content:{parts:h}}]:[],usageMetadata:A});break}w+=l.decode(O,{stream:!0});let T=w.split(`
555
- `);w=T.pop();for(let f of T){let y=f.trim();if(!y||!y.startsWith("data: "))continue;let R=!1;if(y==="data: [DONE]")R=!0;else try{let k=JSON.parse(y.substring(6)),r=k.choices?.[0]?.delta,E=k.usage;if(E&&(A={totalTokenCount:E.total_tokens||(E.prompt_tokens||0)+(E.completion_tokens||0),promptTokenCount:E.prompt_tokens||0,candidatesTokenCount:E.completion_tokens||0,cachedContentTokenCount:E.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:E.completion_tokens_details?.reasoning_tokens||E.reasoning_tokens||0},S=!0),r){let B=r.reasoning||r.reasoning_content||null;B&&(h.push({text:B,thought:!0}),S=!0),r.content&&(h.push({text:r.content}),S=!0)}}catch{}if((R||Date.now()-M>=150||A)&&S&&(yield{candidates:h.length>0?[{content:{parts:[...h]}}]:[],usageMetadata:A},h=[],M=Date.now(),S=!1),R)break}Date.now()-M>=150&&S&&(yield{candidates:h.length>0?[{content:{parts:[...h]}}]:[],usageMetadata:A},h=[],M=Date.now(),S=!1)}};var No=async function*(e,n,t,s,o,c,u,a,b=1){let g=[];s&&g.push({role:"system",content:s});for(let v of t){let O=v.role==="user"?"user":"assistant",T=[];if(Array.isArray(v.parts)){for(let f of v.parts)if(f.text)T.push({type:"text",text:f.text});else if(f.inlineData&&u){let y=f.inlineData.mimeType,R=f.inlineData.data;y.startsWith("image/")&&T.push({type:"image_url",image_url:{url:`data:${y};base64,${R}`}})}}else{let f=v.text||"";f&&T.push({type:"text",text:f})}g.push({role:O,content:T.length===1&&T[0].type==="text"?T[0].text:T})}let x={Fast:"minimal",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},d={model:n,messages:g,stream:!0,stream_options:{include_usage:!0},temperature:b};x[o]&&(d.reasoning_effort=x[o]);let m=await ot("https://aihubmix.com/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(d),signal:a});if(!m.ok){let v=await m.json().catch(()=>({}));throw new Error(`AIHubMix Error (${m.status}): ${v.error?.message||m.statusText}`)}let i=m.body.getReader(),l=new TextDecoder,w="",h=[],A=null,M=Date.now(),S=!1;for(;;){let{done:v,value:O}=await i.read();if(v){S&&(h.length>0||A)&&(yield{candidates:h.length>0?[{content:{parts:h}}]:[],usageMetadata:A});break}w+=l.decode(O,{stream:!0});let T=w.split(`
556
- `);w=T.pop();for(let f of T){let y=f.trim();if(!y||!y.startsWith("data: "))continue;let R=!1;if(y==="data: [DONE]")R=!0;else try{let k=JSON.parse(y.substring(6)),r=k.choices?.[0]?.delta,E=k.usage;if(k.choices?.[0]?.finish_reason&&(R=!0),E&&(A={totalTokenCount:E.total_tokens||(E.prompt_tokens||0)+(E.completion_tokens||0),promptTokenCount:E.prompt_tokens||0,candidatesTokenCount:E.completion_tokens||0,cachedContentTokenCount:E.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:E.completion_tokens_details?.reasoning_tokens||E.reasoning_tokens||0},S=!0),r){let B=r.reasoning_content||null;B&&(h.push({text:B,thought:!0}),S=!0),r.content&&(h.push({text:r.content}),S=!0)}}catch{}if((R||Date.now()-M>=150)&&S&&(yield{candidates:h.length>0?[{content:{parts:[...h]}}]:[],usageMetadata:A},h=[],M=Date.now(),S=!1),R)break}Date.now()-M>=150&&S&&(yield{candidates:h.length>0?[{content:{parts:[...h]}}]:[],usageMetadata:A},h=[],M=Date.now(),S=!1)}};var Fo=async function*(e,n,t,s,o,c,u,a,b=1){let g=[];s&&g.push({role:"system",content:s});for(let v of t){let O=v.role==="user"?"user":"assistant",T=[];if(Array.isArray(v.parts)){for(let f of v.parts)if(f.text)T.push({type:"text",text:f.text});else if(f.inlineData&&u){let y=f.inlineData.mimeType,R=f.inlineData.data;y.startsWith("image/")&&T.push({type:"image_url",image_url:{url:`data:${y};base64,${R}`}})}}else{let f=v.text||"";f&&T.push({type:"text",text:f})}g.push({role:O,content:T.length===1&&T[0].type==="text"?T[0].text:T})}let x=o==="Fast",d={model:n,messages:g,stream:!0,stream_options:{include_usage:!0},temperature:b};x&&(d.chat_template_kwargs={enable_thinking:!1});let m=await ot("https://inference.poolside.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(d),signal:a});if(!m.ok){let v=await m.json().catch(()=>({}));throw new Error(`Poolside Error (${m.status}): ${v.error?.message||m.statusText}`)}let i=m.body.getReader(),l=new TextDecoder,w="",h=[],A=null,M=Date.now(),S=!1;for(;;){let{done:v,value:O}=await i.read();if(v){S&&(h.length>0||A)&&(yield{candidates:h.length>0?[{content:{parts:h}}]:[],usageMetadata:A});break}w+=l.decode(O,{stream:!0});let T=w.split(`
557
- `);w=T.pop();for(let f of T){let y=f.trim();if(!y||!y.startsWith("data: "))continue;let R=!1;if(y==="data: [DONE]")R=!0;else try{let k=JSON.parse(y.substring(6)),r=k.choices?.[0]?.delta,E=k.usage;if(k.choices?.[0]?.finish_reason&&(R=!0),E&&(A={totalTokenCount:E.total_tokens||(E.prompt_tokens||0)+(E.completion_tokens||0),promptTokenCount:E.prompt_tokens||0,candidatesTokenCount:E.completion_tokens||0,cachedContentTokenCount:E.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:E.completion_tokens_details?.reasoning_tokens||E.reasoning_tokens||0},S=!0),r){let B=r.reasoning_content||r.reasoning||null;B&&(h.push({text:B,thought:!0}),S=!0),r.content&&(h.push({text:r.content}),S=!0)}}catch{}if((R||Date.now()-M>=150)&&S&&(yield{candidates:h.length>0?[{content:{parts:[...h]}}]:[],usageMetadata:A},h=[],M=Date.now(),S=!1),R)break}Date.now()-M>=150&&S&&(yield{candidates:h.length>0?[{content:{parts:[...h]}}]:[],usageMetadata:A},h=[],M=Date.now(),S=!1)}};var Bo=async function*(e,n,t,s,o,c,u,a,b=1){let g=[];s&&g.push({role:"system",content:s});for(let f of t){let y=f.role==="user"?"user":"assistant",R=[];if(Array.isArray(f.parts)){for(let k of f.parts)if(k.text)R.push({type:"text",text:k.text});else if(k.inlineData&&u){let r=k.inlineData.mimeType,E=k.inlineData.data;r.startsWith("image/")&&R.push({type:"image_url",image_url:{url:`data:${r};base64,${E}`}})}}else{let k=f.text||"";k&&R.push({type:"text",text:k})}g.push({role:y,content:R.length===1&&R[0].type==="text"?R[0].text:R})}let x={Fast:"none",Low:"low",Medium:"medium",High:"high"},d={model:n,messages:g,stream:!0,stream_options:{include_usage:!0},temperature:b};x[o]&&(d.reasoning_effort=x[o]);let m=process.env["9ROUTER_URL"]||process.env.NINEROUTER_URL||"http://127.0.0.1:20128/v1/chat/completions",i={"Content-Type":"application/json"},l=e&&e!=="LOCAL"?e:process.env["9ROUTER_API_KEY"]||"dummy-key";i.Authorization=`Bearer ${l}`;let w=await ot(m,{method:"POST",headers:i,body:JSON.stringify(d),signal:a});if(!w.ok){let f=await w.json().catch(()=>({}));throw new Error(`9router Error (${w.status}): ${f.error?.message||w.statusText}`)}let h=w.body.getReader(),A=new TextDecoder,M="",S=[],v=null,O=Date.now(),T=!1;for(;;){let{done:f,value:y}=await h.read();if(f){T&&(S.length>0||v)&&(yield{candidates:S.length>0?[{content:{parts:S}}]:[],usageMetadata:v});break}M+=A.decode(y,{stream:!0});let R=M.split(`
558
- `);M=R.pop();for(let k of R){let r=k.trim();if(!r||!r.startsWith("data: "))continue;let E=!1;if(r==="data: [DONE]")E=!0;else try{let B=JSON.parse(r.substring(6)),H=B.choices?.[0]?.delta,$=B.usage;if(B.choices?.[0]?.finish_reason&&(E=!0),$&&(v={totalTokenCount:$.total_tokens||($.prompt_tokens||0)+($.completion_tokens||0),promptTokenCount:$.prompt_tokens||0,candidatesTokenCount:$.completion_tokens||0,cachedContentTokenCount:$.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:$.completion_tokens_details?.reasoning_tokens||$.reasoning_tokens||0},T=!0),H){let Y=H.reasoning_content||H.reasoning||null;!Y&&Array.isArray(H.reasoning_details)&&H.reasoning_details.length>0&&(Y=H.reasoning_details.map(ue=>ue.text||"").filter(Boolean).join("")),Y&&(S.push({text:Y,thought:!0}),T=!0),H.content&&(S.push({text:H.content}),T=!0)}}catch{}if((E||Date.now()-O>=150)&&T&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:v},S=[],O=Date.now(),T=!1),E)break}Date.now()-O>=150&&T&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:v},S=[],O=Date.now(),T=!1)}};var Uo=async function*(e,n,t,s,o,c,u,a,b=1){let g=[];s&&g.push({role:"system",content:s});for(let f of t){let y=f.role==="user"?"user":"assistant",R=[];if(Array.isArray(f.parts)){for(let k of f.parts)if(k.text)R.push({type:"text",text:k.text});else if(k.inlineData&&u){let r=k.inlineData.mimeType,E=k.inlineData.data;r.startsWith("image/")&&R.push({type:"image_url",image_url:{url:`data:${r};base64,${E}`}})}}else{let k=f.text||"";k&&R.push({type:"text",text:k})}g.push({role:y,content:R.length===1&&R[0].type==="text"?R[0].text:R})}let x={Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},d={model:n,messages:g,stream:!0,stream_options:{include_usage:!0},temperature:b};x[o]&&(d.reasoning_effort=x[o]);let m=process.env.EXPLABS_URL||process.env.EXPERIENTIALLABS_URL||"https://api.experientiallabs.ai/v1/chat/completions",i={"Content-Type":"application/json"},l=e||process.env.EXPLABS_API_KEY||process.env.EXPERIENTIALLABS_API_KEY||"";i.Authorization=`Bearer ${l}`;let w=await ot(m,{method:"POST",headers:i,body:JSON.stringify(d),signal:a});if(!w.ok){let f=await w.json().catch(()=>({}));throw new Error(`Experiential Labs Error (${w.status}): ${f.error?.message||f.message||w.statusText}`)}let h=w.body.getReader(),A=new TextDecoder,M="",S=[],v=null,O=Date.now(),T=!1;for(;;){let{done:f,value:y}=await h.read();if(f){T&&(S.length>0||v)&&(yield{candidates:S.length>0?[{content:{parts:S}}]:[],usageMetadata:v});break}M+=A.decode(y,{stream:!0});let R=M.split(`
559
- `);M=R.pop();for(let k of R){let r=k.trim();if(!r||!r.startsWith("data: "))continue;let E=!1;if(r==="data: [DONE]")E=!0;else try{let B=JSON.parse(r.substring(6)),H=B.choices?.[0]?.delta,$=B.usage;if($&&(v={totalTokenCount:$.total_tokens||($.prompt_tokens||0)+($.completion_tokens||0),promptTokenCount:$.prompt_tokens||0,candidatesTokenCount:$.completion_tokens||0,cachedContentTokenCount:$.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:$.completion_tokens_details?.reasoning_tokens||$.reasoning_tokens||0},T=!0),H){let Y=H.reasoning_content||H.reasoning||null;!Y&&Array.isArray(H.reasoning_details)&&H.reasoning_details.length>0&&(Y=H.reasoning_details.map(ue=>ue.text||"").filter(Boolean).join("")),Y&&(S.push({text:Y,thought:!0}),T=!0),H.content&&(S.push({text:H.content}),T=!0)}}catch{}if((E||Date.now()-O>=150)&&T&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:v},S=[],O=Date.now(),T=!1),E)break}Date.now()-O>=150&&T&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:v},S=[],O=Date.now(),T=!1)}};var Hr=/```[\s\S]*?```/g,Gr=/```[\s\S]*$/g,jr=/`[^`]+`/g,Vr=/^\|.*\|$/gm,Yr=/^[^\w]+|[^\w]+$/g,Kr=/[^a-z0-9]/gi,ao=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,qr=/\[\s*(?:tool:functions\.|agent:generalist\.)([a-z0-9_]+)\s*\(/gi,zr=/(?:path|targetFile|TargetFile|directory|keyword|id|taskId|title|task)\s*=\s*\\?["']?([^\\"' \),]+)/,In=/["']/g,Qi=/\\/g,Jr=/<\|channel>thought/gi,Xr=/<channel\|>/gi,Qr=e=>typeof e!="string"?e:e.replace(Jr,"<think>").replace(Xr,"</think>"),Vc=/^\s*(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\]|$)/i,Zr=(e,n)=>{let t=!1;for(let s=0;s<n;s++)e[s]==="`"&&(t=!t);return t},ea=e=>{let n=/(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\])/gi,t;for(;(t=n.exec(e))!==null;)if(!Zr(e,t.index))return{index:t.index,length:t[0].length};return{index:-1,length:0}},_s=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,s=e.substring(t),o=ea(s);if(o.index!==-1){let c=t+o.index+o.length;return{fullBlock:e.substring(0,c),innerContent:s.substring(0,o.index),remainingText:e.substring(c)}}return{fullBlock:e,innerContent:s,remainingText:""}},Vt=e=>{if(!e||typeof e!="string")return e;let n=_s(e);return n?n.remainingText.trimStart():e};var ir=/`[^`]*`/g,rr=/`[^`]*$/,Zi=/<\|\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,ta=/"([^"]+)"\s*:\s*(?:"([^"]*)"|(\d+)|true|false|null)/g,er=/<\|\s*tool_calls_section_begin\s*\|>/gi,tr=/<\|\s*tool_calls_section_end\s*\|>/gi,na=/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi;var nr=e=>!e||typeof e!="string"?e:e.replace(/(```[\s\S]*?```|`[^`]*`)|(<(?:\w+)(?:[^>]*)>\r?\n?|\r?\n?<\/\w+(?:[^>]*)>)/gi,(n,t)=>t||""),Es=null,Wo={},On={key:null,value:null},jt=e=>e&&e.replace(/(?:(\x1b\[\d+m))?([✔✘✖🔍📖→➕↻↷•🛇])(?:(\x1b\[\d+m))?\s*\b(Clicked|Dragged|Scrolled|Typed|Pressed Key|Recaptured Screen|Created|Read Skill|Read Documentation|Searched Documentation|Read|Edited|Viewed|Processed|Auto-Read|Skipped|List|Generated|Written|Searched|AI Search|Get Map|Write Canceled|Resolved Sub-Agent Query|Edit Canceled|Write Cancelled|Edit Denied|Visited|Updated|Reviewed|Delegated|Background|Checked|Indexed|Analyzed|Browsed|Elevating SubAgent|Checking SubAgent Work|Started Generalist|Called Generalist|Steered|Unsupported Modality|Awaiting|Cancelled|Aligning Moon Phase|Contemplating Existence|Staring At Void|Rollback Point Checked|Emergency Rollback Failed|Emergency Rollback|Delaying Professionally|Negotiating With Electrons|Touching Grass (virtually)|Panicking Softly|Rethinking Career Choices|Loading Cat Videos|Giving Up Entirely|Summoning Braincell #2|Pretending To Be Busy|Waiting For Motivation DLC|Rotating Internal Screaming|Downloading More RAM|Feeding The Hamsters|Gaslighting Scheduler|Performing Dramatic Pause|Buffering Social Energy|Calculating Regret|Reading Terms And Conditions|Becoming Sentient Briefly|Execution Error|Loop Detected|Contacting Ancestors)\b/ig,(n,t,s,o,c)=>`${t||""}${s}${o||""} \x1B[95m${c}\x1B[0m`),oa=async(e,n=8,t=1e3,s=8e3,o=null)=>{let c=0;for(;;){if(o?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{return await e()}catch(u){if(o?.aborted||u?.name==="AbortError"||u?.message==="Subagent task was cancelled."||(c++,c>=n))throw u;let a=Math.min(t*Math.pow(2,c-1),s);await new Promise((b,g)=>{let x=setTimeout(b,a);o&&o.addEventListener("abort",()=>{clearTimeout(x),g(new DOMException("The user aborted a request.","AbortError"))})})}}},St=!1;var sa=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,c,u)=>{let a=o.fullText||o.text||"";if(o.role==="user"&&c<u.length-1)if(a.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")){let b=a.indexOf("**CONTEXT SUMMARY OF PREVIOUS TURNS");if(b!==-1){let x=a.substring(0,b).lastIndexOf("[SYSTEM METADATA]");x!==-1?a=a.substring(x).trim():a=a.substring(b).trim()}}else{let b=a.lastIndexOf("[USER]"),g=a.lastIndexOf("[USER PROMPT]");b!==-1?a=a.substring(b+6).trim():g!==-1&&(a=a.substring(g).trim())}return{...o,text:a}}),t=[],s=0;for(;s<n.length;){let o=n[s];if(o.role==="user")t.push(o),s++;else{let c=[];for(;s<n.length&&n[s].role!=="user";)c.push(n[s]),s++;let u=[],a=[],b=!1,g=()=>{u.length>0&&(t.push({role:"agent",text:"combined"}),u=[]),a.length>0&&(t.push({role:"system",text:"combined"}),a=[]),b=!1};c.forEach(x=>{let d=x.role==="system"&&(x.text?.startsWith("[TOOL RESULT]")||x.text?.startsWith("SUCCESS:")||x.text?.startsWith("ERROR:")||x.fullText?.startsWith("[TOOL RESULT]")||x.fullText?.startsWith("SUCCESS:")||x.fullText?.startsWith("ERROR:")),m=x.fullText||x.text||"",i=m.trim();if(!(!i&&!x.binaryPart)){if(d)a.push(i);else if(x.role==="agent"){!b&&a.length>0&&g();let l=m.endsWith(`
560
- `),w=i.toLowerCase().includes("tool:functions.")||i.toLowerCase().includes("agent:generalist.");u.push(i),w&&l?b=!0:b=!1}}}),g()}}return t.length},ia=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),Yc=()=>{St=!0},Kc=()=>St,As={write_file:"Writing",update_file:"Editing",read_folder:"Reading",view_file:"Reading",exec_command:"Executing Command",web_search:"Searching",web_scrape:"Reading",memory:"Updating Memory",search_keyword:"Searching",file_map:"Generating Map",ask:"User Input",write_pdf:"Creating",write_docx:"Creating",generate_image:"Generating",todo:"Planning",Todo:"Planning",goal:"Planning",Goal:"Planning",invoke_sync:"Sub-Agent Working",invoke:"Starting Agent",get_progress:"Checking Progress",cancel:"Cancelling",await:"Waiting",EmergencyRollback:"Don't Panic. Lookin' into it",answer:"Answering Sub-Agent",Answer:"Answering Sub-Agent",steer:"Steering Sub-Agent",Steer:"Steering Sub-Agent",Click:"Clicking",click:"Clicking",Drag:"Dragging",drag:"Dragging",Scroll:"Scrolling",scroll:"Scrolling",KeyboardTyping:"Typing",keyboard_typing:"Typing",KeyPress:"Pressing Key",key_press:"Pressing Key",RecaptureScreen:"Recapturing Screen",recapture_screen:"Recapturing Screen"},Dn=(e,n)=>{try{let t=J(n),s=e.toLowerCase().replace(/_/g,"");if(s==="invokesync"||s==="invoke")return t.title||(t.task?t.task.substring(0,30):null);if(s==="getprogress"||s==="cancel"||s==="steer"||s==="steersubagent")return t.id||t.taskId;let o=t.path||t.targetFile||t.TargetFile||t.directory;return o?q.basename(o.replace(/["']/g,"").replace(/\\/g,"/")):null}catch{return null}},Cs=e=>e?new sr({apiKey:e}):Es,qc=async(e,n,t,s,o={})=>{let{onStatus:a,onMemoryUpdated:b,onBackgroundIncrement:g}=o,{profile:x,thinkingLevel:d,mode:m,janitorModel:i,chatId:l,systemSettings:w,sessionStats:h,aiProvider:A="Google",apiKey:M}=e,S=process.env.NVIDIA_BASE_URL||A==="Ollama"||A==="CrofAI"||A==="InferX"||A==="SenseNova"||A==="AIHubMix"||A==="Poolside"||A==="9router"||A==="ExpLabs"||A==="ExperientialLabs"?!1:w?.memory!==!1,O=At(Mn,[]).map(C=>`- [${C.id}]: ${C.memory}`).join(`
561
- `),T=s.slice(0,-1).filter(C=>C.text&&!C.text.includes("[TOOL RESULT]")&&!C.text.includes("OBSERVATION:")&&!C.text.startsWith("[TERMINAL_RECORD]")&&!C.isTerminalRecord&&!C.isMeta&&!C.isLogo&&!String(C.id).startsWith("welcome")&&!String(C.id).startsWith("logo")).slice(-14).map(C=>{let P=Vt(ia(C.text)).replace(/\[tool:functions\..*?\]/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[METADATA \(PRIORITY: DYNAMIC\)\] Time: ([^|\n]+)/g,(De,qe)=>`[METADATA (PRIORITY: DYNAMIC)] Time: ${qe.replace(/:\d{2}/g,"")}`).replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[TOOL RESULTS\]/g,"").replace(/\[tool results\]/g,"").replace(/\r?\n\r?\n/g,`
562
- `).replace(/\n\n/g,`
563
- `).replace(/\\n\\n/g,"").trim(),ee=C.role==="user"?8192:32768,X=P.substring(0,ee);P.length>ee&&(X+=`
564
- ... (truncated) ...`);let it=C.role==="user"?X.startsWith("[USER]")?"":"[USER]: ":X.startsWith("[AGENT]")?"":"[AGENT]: ";return{role:C.role==="user"?"user":"model",parts:[{text:`${it}${X}`}]}}),f=s.filter(C=>C.role==="user").length===1,y=n.includes("[TITLE-UPDATE]"),R=Math.random()<.8,k=f||y||R,r=Vt(t).trim(),E=_i(O,S,k),B=`${r.replace(/\[tool:functions\..*?\]/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[\[TOOL RESULTS\]\]/g,"").replace(/\[tool results\]/g,"").substring(0,32768)}`;B.length>32768&&(B+=`
565
- ... (truncated) ...`);let H=n.replace(/\[Prompted on:.*?\]/g,"").trim();B=B.replace(/\r?\n\r?\n/g,`
566
- `).replace(/\n\n/g,`
567
- `).replace(/\\n\\n/g,"").trim();let $=new Date,ue=`[METADATA] Current date and Time: ${`${$.getFullYear()}-${$.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String($.getDate()).padStart(2,"0")}, ${$.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0})}`}
568
-
569
- [USER]: ${H.substring(0,8192)}
570
- ${H.length>8192?`... (truncated) ...
571
-
572
- `:""}
573
- [AGENT (current turn)]: ${B}`;T.push({role:"user",parts:[{text:ue}]});let st=await Qo("NVIDIA"),D=(await Qn()).quotas?.providerTiers?.NVIDIA==="Free",L="",we=0,Pe=S?12:-1;for(;we<=Pe;)try{if(!await Us("background",e))return;let C="",P=null,ee=!1,X=A;try{let qe=new Promise((We,ae)=>setTimeout(()=>ae(new Error("JANITOR_TIMEOUT")),1e4)),rt=A==="Google"&&we>=0&&we<6&&st&&D,Ue=A==="DeepSeek"&&we<4&&st&&D;ee=rt||Ue,X=ee?"NVIDIA":A;let ft=(async()=>{if(A==="OpenRouter"){let We=ie("janitor_open_router"),oe=Do(M,We,T,E,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),Xe=await oe.next();return{iterator:oe,firstResult:Xe}}else if(A==="DeepSeek"&&!ee){let ae=vo(M,ie("deepseek_fast_fallback"),T,E,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),oe=await ae.next();return{iterator:ae,firstResult:oe}}else if(A==="Mistral"&&!ee){let ae=Io(M,ie("mistral_janitor_fallback"),T,E,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),oe=await ae.next();return{iterator:ae,firstResult:oe}}else if(A==="NVIDIA"||ee){let ae=Oo(ee?st:M,ie("nvidia_janitor_fallback"),T,E,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),oe=await ae.next();return{iterator:ae,firstResult:oe}}else if(A==="CrofAI"){let ae=$o(M,targetModel||ie("crofai_fallback")||"deepseek-v4-flash-0731",T,E,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),oe=await ae.next();return{iterator:ae,firstResult:oe}}else if(A==="InferX"){let ae=Lo(M,targetModel||ie("inferx_fallback")||"deepseek-v4-flash",T,E,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),oe=await ae.next();return{iterator:ae,firstResult:oe}}else if(A==="SenseNova"){let ae=Po(M,targetModel||ie("sensenova_fallback")||"sensenova-6.8-flash-lite",T,E,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),oe=await ae.next();return{iterator:ae,firstResult:oe}}else if(A==="AIHubMix"){let ae=No(M,targetModel||ie("aihubmix_fallback")||"gpt-4o-mini",T,E,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),oe=await ae.next();return{iterator:ae,firstResult:oe}}else if(A==="Poolside"){let ae=Fo(M,targetModel||ie("poolside_fallback")||"poolside/laguna-s-2.1",T,E,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),oe=await ae.next();return{iterator:ae,firstResult:oe}}else if(A==="9router"||A==="9Router"){let ae=Bo(M,targetModel||ie("9router_fallback")||"z-ai/glm-5.3-flash",T,E,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),oe=await ae.next();return{iterator:ae,firstResult:oe}}else if(A==="ExpLabs"||A==="ExperientialLabs"){let ae=Uo(M,targetModel||ie("explabs_fallback")||"deepseek-v4-pro-0813",T,E,"Fast",m,!1,null,.7)[Symbol.asyncIterator](),oe=await ae.next();return{iterator:ae,firstResult:oe}}else{let oe=(await Cs(M).models.generateContentStream({model:i||(we===Pe?ie("janitor_default"):ie("gemma_janitor_fallback_google")),contents:T,config:{systemInstruction:E,temperature:.7,safetySettings:[{category:kn.HARM_CATEGORY_HARASSMENT,threshold:wn.BLOCK_NONE},{category:kn.HARM_CATEGORY_HATE_SPEECH,threshold:wn.BLOCK_NONE},{category:kn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:wn.BLOCK_NONE},{category:kn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:wn.BLOCK_NONE}],thinkingConfig:{includeThoughts:!1,thinkingLevel:dt.MINIMAL}}}))[Symbol.asyncIterator](),Xe=await oe.next();return{iterator:oe,firstResult:Xe}}})();if(process.stdout.isTTY){let oe=(await es())[l]?.name||"",Xe=oe&&!oe.startsWith("flow-")&&!oe.startsWith("Session ")?oe:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${Xe}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${Xe}\x07`)}let{iterator:$n,firstResult:mt}=await Promise.race([ft,qe]),{value:Ve,done:xt}=mt;if(!xt&&Ve){let We=Ve.candidates?.[0]?.content?.parts,ae=We?X==="Google"?We[1]?.text||We[0]?.text||"":We.filter(oe=>oe.text&&!oe.thought).map(oe=>oe.text).join(""):typeof Ve.text=="function"?Ve.text():"";ae&&(C+=ae),P=Ve.usageMetadata;for await(let oe of{[Symbol.asyncIterator]:()=>$n}){let Xe=oe.candidates?.[0]?.content?.parts,lo=Xe?X==="Google"?Xe[1]?.text||Xe[0]?.text||"":Xe.filter(rn=>rn.text&&!rn.thought).map(rn=>rn.text).join(""):typeof oe.text=="function"?oe.text():"";lo&&(C+=lo),P=oe.usageMetadata}}}catch(qe){throw qe}if(C){if(L=C,P){let qe=P.totalTokenCount||0,rt=P.cachedContentTokenCount||0,Ue=(P.candidatesTokenCount||0)+(X==="Google"&&P.thoughtsTokenCount||0),ft=ee?ie("nvidia_janitor_fallback"):X==="DeepSeek"?ie("deepseek_fast_fallback"):X==="ExpLabs"||X==="ExperientialLabs"?ie("explabs_fallback")||"deepseek-v4-pro-0813":X==="OpenRouter"?ie("janitor_open_router"):i||(we===Pe?ie("janitor_default"):ie("gemma_janitor_fallback_google"));await Nt("tokens",qe,X,ft),rt>0&&await Nt("cachedTokens",rt,X,ft),Ue>0&&await Nt("candidateTokens",Ue,X,ft)}}else throw new Error("No synthesis generated by Janitor.");g&&(g(),await Et("background"));let it=Go(L),De=!1;for(let qe of it){let rt=qe.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(rt)&&(De=!0);let Ue={chatId:l,sessionId:l,history:s},ft=await io(rt,qe.args,Ue);rt.toLowerCase()==="memory"&&(qe.args.includes("action='user'")||qe.args.includes('action="user"'))&&!ft.startsWith("ERROR")&&(b&&b(),process.stdout.isTTY&&(process.stdout.write("\x1B]0;Memory Updated\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=Memory Updated\x07")),await new Promise(mt=>setTimeout(mt,3e3)))}if(!De)try{let qe=At(Mn,[]);if(qe.length>0){let rt=[];for(let Ue of qe)Ue.score===void 0&&(Ue.score=.5),Ue.score*=.99995,Ue.score<.05&&(Ue.score=0),Ue.score=Math.round(Ue.score*1e5)/1e5,Ue.score>0&&rt.push(Ue);Wn(Mn,rt)}}catch{}break}catch(C){we++;let P=new Date().toLocaleString(),ee=C instanceof Error?(()=>{try{return JSON.parse(JSON.parse(C.message).error.message).error.message}catch{return String(C)}})():String(C);await new Promise(De=>setTimeout(De,1e3));let X=q.join(yn,"janitor");if(Ie.existsSync(X)||Ie.mkdirSync(X,{recursive:!0}),Ie.appendFileSync(q.join(X,"error.log"),`ERROR [Attempt ${we}/${Pe+1}] [${P}]: ${ee}
574
-
575
- `),we>Pe)break;let it=Math.min(750*Math.pow(2,we-1),5e3);await new Promise(De=>setTimeout(De,it))}if(we){let C=q.join(yn,"janitor");Ie.appendFileSync(q.join(C,"error.log"),`-----------------------------------------------------------------------------
576
-
577
- `)}if(process.stdout.isTTY)try{let ee=(await es())[l]?.name||"",X=ee&&!ee.startsWith("flow-")&&!ee.startsWith("Session ")?ee:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${X}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${X}\x07`)}catch{process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")}},ra=e=>{let n=Vt(e),t=Zo?n:n.replace(ir,o=>" ".repeat(o.length)).replace(rr,o=>" ".repeat(o.length));ao.lastIndex=0;let s;for(;(s=ao.exec(t))!==null;){let o=s.index+s[0].length-1,c=0,u=null,a=!1,b=!1;for(let g=o;g<t.length;g++){let x=n[g];if(!u&&(x==='"'||x==="'"||x==="`")?(u=x,a=!1):u&&x===u&&!a&&(u=null),!u&&(x==="("?c++:x===")"&&c--,c===0)){let d=g+1;for(;d<t.length&&/\s/.test(t[d]);)d++;if(d<t.length&&t[d]==="]"){b=!0,ao.lastIndex=d+1;break}}x==="\\"?a=!a:a=!1}if(!b)return{inside:!0,toolName:s[1],startIndex:s.index,args:n.substring(s.index+s[0].length)}}return{inside:!1}},ar=(e,n=!0)=>{let t=ao;t.lastIndex=0;let s="",o=0,c;for(;(c=t.exec(e))!==null;){let u=e.substring(o,c.index);s+=n&&o===0?Vt(u):u;let a=c.index+c[0].length-1,b=0,g=null,x=-1;for(let d=a;d<e.length;d++){let m=e[d];if(g){if(m===g){let i=0;for(let l=d-1;l>=0&&e[l]==="\\";l--)i++;i%2===0&&(g=null)}}else if(m==='"'||m==="'"||m==="`")g=m;else if(m==="(")b++;else if(m===")"&&(b--,b===0)){let i=d+1;for(;i<e.length&&/\s/.test(e[i]);)i++;if(i<e.length&&e[i]==="]"){x=i;break}}}if(x!==-1)s+="[tool:functions."+c[1]+"()]",o=x+1,t.lastIndex=o;else{s+="[tool:functions."+c[1]+"(",o=e.length;break}}return o<e.length&&(s+=n&&o===0?Vt(e.substring(o)):e.substring(o)),s},aa=(e,n,t)=>{let s=ao;s.lastIndex=0;let o="",c=0,u;for(;(u=s.exec(e))!==null;){let a=e.substring(c,u.index);o+=a.replace(n,t);let b=u.index+u[0].length-1,g=0,x=null,d=-1;for(let m=b;m<e.length;m++){let i=e[m];if(x){if(i===x){let l=0;for(let w=m-1;w>=0&&e[w]==="\\";w--)l++;l%2===0&&(x=null)}}else if(i==='"'||i==="'"||i==="`")x=i;else if(i==="(")g++;else if(i===")"&&(g--,g===0)){let l=m+1;for(;l<e.length&&/\s/.test(e[l]);)l++;if(l<e.length&&e[l]==="]"){d=l;break}}}if(d!==-1)o+=e.substring(u.index,d+1),c=d+1,s.lastIndex=c;else{o+=e.substring(u.index),c=e.length;break}}return c<e.length&&(o+=e.substring(c).replace(n,t)),o},or=e=>ar(e,!0),la=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(c=>c.charAt(0).toUpperCase()+c.slice(1)).join("");Zi.lastIndex=0;let s=e.replace(Zi,(o,c,u)=>{let a="";try{let x=JSON.parse(u.trim());x&&typeof x=="object"&&(a=Object.entries(x).map(([m,i])=>{let l=typeof i=="string"?i:JSON.stringify(i);return`${m}=${JSON.stringify(l)}`}).join(", "))}catch{let d=[],m=ta;m.lastIndex=0;let i;for(;(i=m.exec(u))!==null;){let l=i[1],w=i[2]!==void 0?i[2]:i[0].split(":").slice(1).join(":").trim();d.push(`${l}=${JSON.stringify(w)}`)}d.length>0?a=d.join(", "):a=u.trim()}let b=c.toLowerCase().replace(/_/g,"");return`[tool:functions.${n[b]||t(c)}(${a})]`});return er.lastIndex=0,tr.lastIndex=0,s=s.replace(er,""),s=s.replace(tr,""),s},ca=/(?:path|query|url|keyword|command|method|title|task|id)\s*=\s*['"`]?\s*\.\.\.\s*['"`]?/i,da=/^['"`]?\s*\.\.\.\s*['"`]?$/,gn=e=>{if(e==null)return!1;let n=String(e).trim();return n==="..."||n==="\u2026"||da.test(n)},Go=e=>{if(!e)return[];let n=la(e),t=Vt(n),s=[],o=Zo?t:t.replace(ir,a=>" ".repeat(a.length)).replace(rr,a=>" ".repeat(a.length)),c=qr;c.lastIndex=0;let u;for(;(u=c.exec(o))!==null;){let a=u[1],b=u.index+u[0].length-1,g=0,x=null,d=-1,m=-1;for(let i=b;i<o.length;i++){let l=t[i];if(x){if(l===x){let w=0;for(let h=i-1;h>=0&&t[h]==="\\";h--)w++;w%2===0&&(x=null)}}else if(l==='"'||l==="'"||l==="`")x=l;else if(l==="(")g++;else if(l===")"&&(g--,g===0)){m=i;let w=i+1;for(;w<o.length&&/\s/.test(o[w]);)w++;if(w<o.length&&o[w]==="]"){d=w;break}}}if(d!==-1){let i=t.substring(b+1,m),l=t.substring(u.index,d+1),w=J(i);gn(w.path)||gn(w.query)||gn(w.url)||gn(w.keyword)||gn(w.command)||gn(w.method)||gn(w.title)||gn(w.task)||gn(w.id)||ca.test(i)||s.push({fullMatch:l,toolName:a.trim(),args:i.trim()}),c.lastIndex=d+1}}return s},zc=(e,n={})=>{if(!e)return null;if(Wo=n,Es=new sr({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(...s)=>{try{let o=await t(...s);return typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),o}catch(o){throw typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),o}}}},Ho=async(e,n,t,s,o="Fast",c=.75,u="agent")=>oa(async()=>{let{aiProvider:a="Google",apiKey:b,mode:g}=e,x="",d=null,m=typeof t=="string"?[{role:"user",parts:[{text:t}]}]:t,i=new AbortController,l=i.signal,w=setInterval(()=>{St&&(i.abort(),clearInterval(w))},100);try{let h;a==="Ollama"?h=Ts(b,n,m,s,o,g,gt(n),l,c,systemSettings?.ollamaEndpoint||"Cloud"):a==="OpenRouter"?h=Do(b,n,m,s,o,g,gt(n),l,c):a==="DeepSeek"?h=vo(b,n,m,s,o,g,gt(n),l,c):a==="Mistral"?h=Io(b,n,m,s,o,g,gt(n),l,c):a==="NVIDIA"?h=Oo(b,n,m,s,o,g,gt(n),l,c):a==="CrofAI"?h=$o(b,n,m,s,o,g,gt(n),l,c):a==="InferX"?h=Lo(b,n,m,s,o,g,gt(n),l,c):a==="SenseNova"?h=Po(b,n,m,s,o,g,gt(n),l,c):a==="AIHubMix"?h=No(b,n,m,s,o,g,gt(n),l,c):a==="Poolside"?h=Fo(b,n,m,s,o,g,gt(n),l,c):a==="9router"||a==="9Router"?h=Bo(b,n,m,s,o,g,gt(n),l,c):a==="ExpLabs"||a==="ExperientialLabs"?h=Uo(b,n,m,s,o,g,gt(n),l,c):h=await Cs(b).models.generateContentStream({model:n,contents:m,config:{systemInstruction:s,temperature:c,thinkingConfig:(()=>{let S=(n||"").toLowerCase(),v=S.includes("gemma-4")||S.startsWith("gemma"),O=S.includes("gemini-3");if(v||O)return v?o.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:dt.MINIMAL}:{includeThoughts:!0,thinkingLevel:dt.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:S.includes("pro")?dt.LOW:dt.MINIMAL,Low:dt.LOW,Medium:dt.MEDIUM,Standard:dt.MEDIUM,High:dt.HIGH,xHigh:dt.HIGH}[o]||dt.MEDIUM};{let T={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[o]||2048;return T===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:T}}})()}},{signal:l});for await(let A of h){if(St)throw new Error("Subagent task was cancelled.");if(e?.taskId&&typeof Gt<"u"){let v=Gt.find(O=>O.id===e.taskId);if(v&&v.status==="cancelled")throw new Error("Subagent task was cancelled.")}let M="";if(A.candidates?.[0]?.content?.parts)for(let v of A.candidates[0].content.parts)v.text&&!v.thought&&(x+=v.text,M+=v.text);let S=M?M.trim().split(/\s+/).filter(Boolean).length:0;e&&typeof e.onTokenChunk=="function"&&e.onTokenChunk(M,S),A.usageMetadata&&(d=A.usageMetadata)}}finally{clearInterval(w)}if(d){let h=d.totalTokenCount||0,A=d.cachedContentTokenCount||0,M=(d.candidatesTokenCount||0)+(a==="Google"&&d.thoughtsTokenCount||0);await Nt("tokens",h,a,n),A>0&&await Nt("cachedTokens",A,a,n),M>0&&await Nt("candidateTokens",M,a,n),e&&typeof e.onUsage=="function"&&e.onUsage({totalTokenCount:h,cachedContentTokenCount:A,candidatesTokenCount:M})}return await Et("agent",a),{text:x,usageMetadata:d}}),fa=async(e,n,t=null)=>{t=t||At(po,{});try{let{aiProvider:s="Google"}=n;if(Object.values(t).flat().length<=5)return;let c=Object.keys(t).filter(m=>m!==e&&Array.isArray(t[m])&&t[m].length>2);if(c.length===0)return;let u=`You are a silent background process for the FluxFlow CLI Agent.
578
- Your task is to summarize or merge temporary context memories from one or more past conversation sessions.
579
- For each Chat ID provided, you must output a tool call to save the consolidated summary.
580
-
581
- The tool call format MUST be:
582
- [tool:functions.saveSummary(id="<chat-id>", summary="<updated summary string, max 400 words>")]
583
-
584
- Guidelines:
585
- - 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.
586
- - Focus on key goals, preferences, modified files, and technical decisions.
587
- - Under no circumstances write normal conversational text. Output ONLY the tool calls.
588
- - You can stack multiple tool calls for multiple chats.
589
-
590
- Chats to process:
591
-
592
- `,a=At(Jo,{});for(let m of c){let l=t[m].map(h=>`- ${h}`).join(`
593
- `),w=a[m];u+=`[Chat ID: ${m}]
594
- `,w?(u+=`- Existing Summary: "${w}"
595
- `,u+=`
596
- -- New Memories to integrate:
597
- ${l}
598
-
599
- `):u+=`-- Individual Memories:
600
- ${l}
601
-
602
- `}let b=0,g=5,x=!1,d=ie("gemma_janitor_fallback_google");for(s==="OpenRouter"&&(d=ie("janitor_open_router")),s==="DeepSeek"&&(d=ie("deepseek_level_1")),s==="Mistral"&&(d=ie("mistral_level_1")),s==="NVIDIA"&&(d=ie("nvidia_janitor_fallback")),s==="CrofAI"&&(d=ie("crofai_fallback")),s==="InferX"&&(d=ie("inferx_fallback")),s==="SenseNova"&&(d=ie("sensenova_fallback")),s==="AIHubMix"&&(d=ie("aihubmix_fallback")),s==="Poolside"&&(d=ie("poolside_fallback")),(s==="9router"||s==="9Router")&&(d=ie("9router_fallback"));b<=g&&!x;){b++;try{let i=(await Ho(n,d,u,null,"Fast",.75,"background")).text||"",l=Go(i);if(l.length===0)throw new Error("No tool calls detected in synthesis response");for(let w of l){let h=w.toolName;["saveSummary","saveSumary","SaveSummary","SaveSumary"].includes(h)&&await io(h,w.args,{chatId:e})}x=!0}catch(m){if(b>=g)throw new Error(`Failed after ${g} attempts. Last error: ${m.message}`)}}}catch(s){let o=s instanceof Error?(()=>{try{return JSON.parse(JSON.parse(s.message).error.message).error.message}catch{return String(s)}})():String(s),c=q.join(yn,"janitor");Ie.existsSync(c)||Ie.mkdirSync(c,{recursive:!0}),Ie.appendFileSync(q.join(c,"error.log"),`[${new Date().toLocaleString()}] Past memory batch consolidation error: ${o}
603
- `)}},ua=async(e,n,t=!1)=>{let{chatId:s,aiProvider:o="Google"}=e,c=q.join(ho,"chat-summaries.json"),u=i=>i.filter(l=>(l.role==="user"||l.role==="agent"||l.role==="system")&&l.role!=="think"&&!l.isVisualFeedback&&!l.isMeta&&!l.isTerminalRecord&&!(l.text&&l.text.includes("[TERMINAL_RECORD]"))&&!String(l.id).startsWith("welcome")).map(l=>{let w=l.fullText||l.text||"",h=l.role==="system"||w.startsWith("[TOOL RESULT]:")||l.text&&l.text.startsWith("[TOOL RESULT]:"),A=w;return h&&(w.includes("[TOOL RESULT]:")||l.text&&l.text.includes("[TOOL RESULT]:"))?A="[TOOL RESULT]: ...truncated for summary":A=A.replace(/(\[(?:tool|agent):[a-zA-Z0-9_\.]+)\([\s\S]*?\)(\])/g,"$1(...)$2"),`[${h?"TOOL":l.role==="agent"?"AGENT":"USER"}]: ${A}`}).join(`
604
-
605
- `),a=async(i,l)=>{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.",h=l?`Here is the previous summary:
606
- ${l}
607
-
608
- Here is the new conversation history:
609
- ${i}
610
-
611
- Provide a new consolidated summary of the entire session.`:`Here is the conversation history:
612
- ${i}
613
-
614
- Provide a consolidated summary of the entire session.`,A=ie("gemma_janitor_fallback_google");o==="OpenRouter"&&(A=ie("janitor_open_router")),o==="DeepSeek"&&(A=ie("deepseek_level_1")),o==="Mistral"&&(A=ie("mistral_level_1")),o==="NVIDIA"&&(A=ie("nvidia_chat_summarizer_fallback")),o==="CrofAI"&&(A=ie("crofai_fallback")),o==="InferX"&&(A=ie("inferx_fallback")),o==="SenseNova"&&(A=ie("sensenova_fallback")),o==="AIHubMix"&&(A=ie("aihubmix_fallback")),o==="Poolside"&&(A=ie("poolside_fallback")),(o==="9router"||o==="9Router")&&(A=ie("9router_fallback")),(o==="ExpLabs"||o==="ExperientialLabs")&&(A=ie("explabs_fallback")||"deepseek-v4-pro-0813");let M=0,S=!1,v=null;for(;M<=3&&!S;){M++;try{v=await Ho(e,A,h,w,"Fast"),S=!0}catch{if(M>3){if(o==="Google")try{let T=ie("general_fallback");return(await Ho(e,T,h,w,"Fast")).text||""}catch{return""}return""}}}return v&&v.text||""},b=u(n),g=At(c,{}),x=g[s]||{summary:"",historyLength:0};typeof x=="string"&&(x={summary:x,historyLength:0});let d=x.summary||"",m=await a(b,d);if(m){x.summary=m;let i=sa(n);return t?x.historyLength=(x.historyLength||0)+i:x.historyLength=i,g[s]=x,Wn(c,g),m}return null},Jc=e=>{try{let n=q.join(ho,"chat-summaries.json");if(Ie.existsSync(n)){let t=At(n,{});t[e]&&(delete t[e],Wn(n,t))}}catch{}},Xc=async function*(e,n,t,s,o){let{profile:c,thinkingLevel:u,mode:a,janitorModel:b,chatId:g,isPlayground:x,systemSettings:d,sessionStats:m,aiProvider:i="Google",apiTier:l,wildcardTooling:w}=t,h=gt(e);if(!Es&&i==="Google")throw new Error("AI not initialized");let A=process.env.NVIDIA_BASE_URL||t?.aiProvider==="Ollama"||t?.aiProvider==="CrofAI"||t?.aiProvider==="InferX"||t?.aiProvider==="SenseNova"||t?.aiProvider==="AIHubMix"||t?.aiProvider==="Poolside"||t?.aiProvider==="9router"||t?.aiProvider==="ExpLabs"||t?.aiProvider==="ExperientialLabs"?!1:d?.memory!==!1,M=n[n.length-1].text,S=q.join(ho,"chat-summaries.json"),v=!1,O=n.filter(k=>k.role==="user").length===1,T=M.includes("[TITLE-UPDATE]"),f=O||T,y=M.replace(/\[TITLE-UPDATE\]/g,"").trim();y=y.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),yield{type:"status",content:"[start]"},yield{type:"status",content:"Gathering Context"},await yo.startTransaction(g,y),d?.advanceRollback&&await Zn.takeInitialSnapshot(g),St=!1;let R=null;try{let k=new AbortController;R=setInterval(()=>{St&&(k.abort(),R&&(clearInterval(R),R=null))},400);let r=[...n.slice(0,-1)];{let ve=At(S,{})[g]||{summary:"",historyLength:0};if(ve.summary&&ve.historyLength>0){let Yt=0,xe=[];for(let Qe=0;Qe<r.length;Qe++){let He=r[Qe];(He.role==="user"||He.role==="agent"||He.role==="system")&&!String(He.id).startsWith("welcome")&&!He.isMeta&&Yt++,Yt>ve.historyLength&&xe.push(He)}r=xe}}r=r.map(W=>{if(W.role==="user"&&W.text){let ve=W.text.match(/\[USER\]([\s\S]*?)\[\/USER\]/);if(ve)return{...W,text:ve[1].trim()}}return{...W}});let E=process.env.HIGH_CONTEXT,B=process.env.GOOGLE_GEMMA_NONSENSE==="true"||process.env.GOOGLE_GEMMA_NONSENSE===!0||!1,H=255e3,$=26e4;if(E&&E!=="false"){let W=parseInt(E,10);!isNaN(W)&&W>=0&&W<=1e6&&($=W,H=Math.round(W*.85))}if((i==="NVIDIA"&&(e?.includes("gpt")||e?.includes("qwen")||e?.includes("medium")||e.includes("muse"))||i==="Mistral")&&(H=122e3,$=126e3),i==="Google"&&e?.includes("gemma")&&B&&(H=14e3,$=16e3),(i==="Ollama"||i==="9router"||i==="9Router"||i==="ExpLabs"||i==="ExperientialLabs")&&(m?.tokens||0)>H){yield{type:"text",content:"\u2726 Maximum Context Limit Reached. Start a new chat."};return}if(i!=="Ollama"&&i!=="9router"&&i!=="9Router"&&i!=="ExpLabs"&&i!=="ExperientialLabs"&&(m?.tokens||0)>H&&(yield{type:"status_history",content:"Context Limit Reached. Condensing session history..."},await ua(t,r,!0)&&(r=[],v=!0)),O&&A){let W=At(po,{});Object.values(W).flat().length>5&&(yield{type:"status",content:"Condensing past chat memories"},await fa(g,t,W))}let Y=At(po,{}),ue=At(Jo,{}),st=Object.entries(Y).filter(([W])=>W!==g).flatMap(([W,ve])=>ve),D=[...Object.entries(ue).filter(([W])=>W!==g).slice(-20).map(([W,ve])=>`[Chat Summary]: ${ve}`),...st].map(W=>`- ${W}`).join(`
615
- `),we=At(Mn,[]).map(W=>`- ${W.memory}`).join(`
616
- `),Pe=(m?.tokens||0)>=1e4,C=Si(D,we,A,Pe),P=new Date,ee=P.getFullYear(),X=P.toLocaleString("en-US",{month:"short"}).toUpperCase(),it=String(P.getDate()).padStart(2,"0"),De=P.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}),qe=`${ee}-${X}-${it}, ${De}`,rt=[".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"],Ue=W=>{try{return Ie.readdirSync(W,{withFileTypes:!0})}catch{return[]}},ft=(W,ve={value:0},Yt=1)=>{if(ve.value>6200||Yt>7)return ve.value;let xe=Ue(W);for(let Qe of xe){if(ve.value>6200)break;rt.includes(Qe.name)||Qe.name.startsWith(".")||Qe.isDirectory()&&(ve.value++,ft(q.join(W,Qe.name),ve,Yt+1))}return ve.value},$n=(W,ve)=>d?.indentationTree!==!1?ws(W,ve,1,Ue,rt):Ss(W,ve,"",1,Ue,rt),mt=ft(process.cwd()),Ve=10;mt>3072||mt>2304?Ve=1:mt>1536?Ve=2:mt>768?Ve=3:mt>384?Ve=5:mt>192?Ve=6:mt>96?Ve=7:(mt>48||mt>24)&&(Ve=9);let xt=At(Xo,{}),We=xt[g],ae=We?We!==process.cwd():!1;xt[g]=process.cwd(),Wn(Xo,xt);let oe=At(S,{}),Xe=oe[g]||{summary:"",historyLength:0};typeof Xe=="string"&&(Xe={summary:Xe,historyLength:0});let lo=n.filter(W=>(W.role==="user"||W.role==="agent"||W.role==="system")&&!String(W.id).startsWith("welcome")&&!W.isMeta).length;Xe.historyLength&&lo<Xe.historyLength&&(Xe.summary="",Xe.historyLength=0,oe[g]=Xe,Wn(S,oe));let rn=typeof Xe=="object"?Xe.summary||"":Xe||"",Rs=r.length>0;Rs&&rn&&r[0]&&(r[0].role==="user"||r[0].role==="system")&&(r[0].text.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")||(r[0].text=`[SYSTEM METADATA]
617
- **CONTEXT SUMMARY OF PREVIOUS TURNS (PRIORITY: DYNAMIC)**
618
- ${rn}
619
-
620
- [USER] ${r[0].text}`,yield{type:"summary_injected",content:{id:r[0].id,text:r[0].text}}));let Ms=rn&&!Rs?`
621
- [SYSTEM METADATA]
622
- **CONTEXT SUMMARY OF PREVIOUS TURNS**
623
- ${rn}
624
- `:"",vs=!!d?.dynamicDirAwareness,lr=`${g}|${i}|${u}|${e}|${c}|${vs}`,Is=!vs&&On.key===lr&&On.value?"":`
625
- **Directory Structure**
626
- CWD: `+process.cwd()+`${x?" [PLAYGROUND MODE]":""}
627
- `+$n(process.cwd(),Ve),ht=await vn(),mn="";if(Ro()&&ht.file_focused!=="none"){mn=`
628
- [Additional IDE Context]
629
- `;let W=q.relative(process.cwd(),ht.file_focused),ve=(ht.opened_editors||[]).map(xe=>{let Qe=q.relative(process.cwd(),xe);return Qe.startsWith("..")?`[External] ${q.basename(xe)}`:Qe});if(mn+=`Focused File: ${W}
630
- Cursor Line: ${ht.cursor_line}
631
- `,ht.selected){let xe=ht.selected,Qe=xe.split(`
632
- `);Qe.length>256&&(xe=Qe.slice(0,240).join(`
633
- `)+`
634
- ... [truncated] ...
635
- `+Qe.slice(-16).join(`
636
- `)),xe.length>2048&&(xe=xe.slice(0,1920)+`
637
- ... [truncated] ...
638
- `+xe.slice(-128)),mn+=`Current Selection: "${xe}"
639
- `}if(ht.manual_edits){let Qe=ht.manual_edits.split(`
640
- `),He=[],ze=null;for(let G of Qe)G.trim()&&(G.startsWith(" Line ")?ze&&ze.edits.push(G):(ze={path:G.endsWith(":")?G.slice(0,-1):G,edits:[]},He.push(ze)));for(let G of He)G.edits.length>80&&(G.edits=G.edits.slice(-80)),G.originalEditsCount=G.edits.length;let ce=(G,z)=>z.reduce((Ge,zt)=>{let Zt=ht.file_focused&&(zt.path===ht.file_focused||q.resolve(process.cwd(),zt.path)===q.resolve(ht.file_focused))?Math.ceil(G*1.2):G;return Ge+Math.min(zt.edits.length,Zt)},0),Mt=80;if(ce(80,He)>300){let G=!1;for(let z=80;z>=10;z--)if(ce(z,He)<=300){Mt=z,G=!0;break}G||(Mt=10)}let Je=[...He];if(Mt===10&&ce(10,Je)>500)for(;Je.length>0&&ce(10,Je)>500;){let G=0,z=Je[0].originalEditsCount;for(let Ge=1;Ge<Je.length;Ge++)Je[Ge].originalEditsCount<z&&(z=Je[Ge].originalEditsCount,G=Ge);Je.splice(G,1)}for(let G of Je){let Ge=ht.file_focused&&(G.path===ht.file_focused||q.resolve(process.cwd(),G.path)===q.resolve(ht.file_focused))?Math.ceil(Mt*1.2):Mt;G.edits.length>Ge&&(G.edits=G.edits.slice(-Ge))}for(let G of Je){let z=`${G.path}:
641
- ${G.edits.join(`
642
- `)}`;for(;G.edits.length>0&&z.length>4*768;)G.edits.shift(),z=`${G.path}:
643
- ${G.edits.join(`
644
- `)}`;z.length>4*768?G.stringRepresentation="... "+z.slice(-(4*768-4)):G.stringRepresentation=z}let Kt=Je.map(G=>G.stringRepresentation).join(`
645
- `);for(;Je.length>0&&Kt.length>4*2048;){Je[0].edits.length>0?Je[0].edits.shift():Je.shift();for(let G of Je){let z=`${G.path}:
646
- ${G.edits.join(`
647
- `)}`;z.length>4*768?G.stringRepresentation="... "+z.slice(-(4*768-4)):G.stringRepresentation=z}Kt=Je.map(G=>G.stringRepresentation).join(`
648
- `)}Kt.length>4*2048&&(Kt="... "+Kt.slice(-(4*2048-4))),mn+=`Recent Manual Edits:
649
- ${Kt}
650
- `}ve.length>0&&(mn+=`All Opened Editors: ${ve.join(", ")}`),ht.diagnostics&&(mn+=`
651
- **Active File Errors**:
652
- ${ht.diagnostics}
653
- `),(y.toLowerCase().includes("lint")||y.toLowerCase().includes("warning"))&&ht.warnings&&(mn+=`
654
- **Lint Warnings**:
655
- ${ht.warnings}
656
- `)}let Os=y.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),Ds=/(?:\\)?@\[([^\]]+)\]/g,jo,Vo=[];for(Ds.lastIndex=0;(jo=Ds.exec(Os))!==null;){let W=jo[0].startsWith("\\");Vo.push({tag:jo[1],isEscaped:W})}let Yo=[],co=null;for(let W=0;W<Vo.length;W++){let{tag:ve,isEscaped:Yt}=Vo[W];if(!Yt)try{let xe=ve.trim().replace(/^["']|["']$/g,""),Qe=/[:#]L?(\d+)(?:-L?(\d+))?$/i,He=xe.match(Qe),ze=xe,ce=null,Mt=null;He&&(ce=parseInt(He[1],10),Mt=He[2]?parseInt(He[2],10):ce,ze=xe.slice(0,He.index));let Je=q.resolve(process.cwd(),ze);if(Ie.existsSync(Je)&&Ie.statSync(Je).isFile()){let G=ze.toLowerCase(),z=G.endsWith(".pdf"),Ge=G.endsWith(".docx")||G.endsWith(".doc")||G.endsWith(".ppt")||G.endsWith(".pptx")||G.endsWith(".xls")||G.endsWith(".xlsx"),zt=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(G),vt=zt||z||Ge,Zt=i==="Google"||gt(e);if(vt&&!Zt){let Ne=`\u2718 Unsupported Modality: ${q.basename(ze)}`,he=115;process.stdout.isTTY&&(he=process.stdout.columns-5||120);let je=[Ne],_n=Math.max(...je.map(hn=>hn.length)),Jt=Math.min(_n+4,he),Kn=je.map(hn=>`${hn.padEnd(Jt-2).substring(0,Jt-2)}`).join(`
657
- `);yield{type:"visual_feedback",content:jt(`${Kn}
658
- `)};continue}if(ce===null&&!vt){let Ne=0;try{Ne=Ie.readFileSync(Je,"utf8").split(/\r\n|\r|\n/).length}catch{}if(Ne>300){let he=`\u21B7 Skipped (Too Large): ${q.basename(ze)}`,je=115;process.stdout.isTTY&&(je=process.stdout.columns-5||120);let _n=Math.min(he.length+4,je),Jt=he.padEnd(_n-2).substring(0,_n-2);yield{type:"visual_feedback",content:jt(`${Jt}
659
- `)};continue}}let ln=ce!==null?ce:1,Sn=Mt!==null?Mt:ce!==null?ce:ln+299;Sn-ln>300&&(Sn=ln+300);let uo=`path=${JSON.stringify(ze)}, startLine=${ln}, endLine=${Sn}`,tt=await Ks(uo,{isMultiModal:Zt}),Ye=!1,It="",Tn=null;if(typeof tt=="string"?tt.trim().startsWith("ERROR")?Ye=!0:It=tt:tt&&typeof tt=="object"&&tt.binaryPart?(Tn=tt.binaryPart,It=tt.text||""):Ye=!0,!Ye){let Ne="";if(zt?(Ne=`\u2714 Processed: ${q.basename(ze)}`,co=Tn):z||Ge?(Ne=`\u2714 Auto-Analysed: ${q.basename(ze)}`,co=Tn):(Ne=`\u2714 Auto-Read: ${q.basename(ze)}`,Yo.push(It)),Ne){let he=115;process.stdout.isTTY&&(he=process.stdout.columns-5||120);let je=[Ne],_n=Math.max(...je.map(hn=>hn.length)),Jt=Math.min(_n+4,he),Kn=je.map(hn=>`${hn.padEnd(Jt-2).substring(0,Jt-2)}`).join(`
660
- `);yield{type:"visual_feedback",content:jt(`${Kn}
661
- `)}}}}}catch{}}let $s="";Yo.length>0&&($s=`[Tagged File Contents] Auto Read User Tagged files by System, No need to re-read
662
- `+Yo.join(`
663
-
664
- `)+`
665
- [Tagged File Contents]
666
- `);let cr=Os.replace(/\\(@\[[^\]]+\])/g,"$1"),dr=w?`You cannot execute tools
667
- Instead, output in chat the exact string you WOULD have produced & wait for system response
668
- `:"",fr=process.env.forcedReasoning||!1,Ls=`[System Metadata]
669
- Time: ${qe}${d?.dynamicDirAwareness?Is:""}${ae?`
670
- WARNING: CWD Changed from previous: "${We}" to current: "${process.cwd()}", write change in chat to avoid future path mismatches
671
- `:""}${C}${mn}
672
- [/Metadata]
673
- ${Ms}${u!=="Fast"&&(i==="Mistral"&&!Hn(e)||u!=="xHigh"&&i==="Google")?`${i==="Mistral"&&!Hn(e)||e.toLowerCase().startsWith("gemma")||fr?`[system] strictly follow thinking policy as high priority. do not start a response without <think>...</think> [/system]
674
- `:""}`:""}[system] exact tool string [tool:functions.ToolName(arg="value")] in chat [/system]
675
- ${$s}${dr}[user prompt] ${cr.trim()} [/user prompt]`.trim(),Ps={role:"user",text:Ls};co&&(Ps.binaryPart=co),r.forEach(W=>{W.text&&W.role==="agent"&&(W.text=Vt(W.text))}),r.push(Ps),Ms&&n[n.length-1]?.id&&(yield{type:"summary_injected",content:{id:n[n.length-1].id,text:Ls}});let an=null,Yn=a==="Flux"?100:10;Yn=a.toLowerCase().includes("cu")?250:Yn;let Qt=16;yield{type:"status",content:"Connecting"},St=!1;let Ns=[],fo=!1;for(let W=0;W<=Yn;W++){let ve=await Bs("agent",t);if(!ve.allowed)throw new Error(ve.reason||`Budget Exhausted for Provider (${i||"Agent"})`);let Yt=[];if(fo=!1,a==="ICU"||a==="FluxCU")try{yield{type:"status",content:"Capturing Screen"},await new Promise(ne=>setTimeout(ne,1e3));let{captureGriddedScreenshot:ge}=await import("./screen_grid-Y5PT4VFL.js"),be=await ge();if(be&&be.base64){let ne="[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]",Ot={inlineData:{mimeType:be.mimeType,data:be.base64}},Ct=d?.imageHistoryCU||"Standard",Tt=Ct==="Low"?1:Ct==="Extended"?5:3,qt=r.filter(Fe=>Array.isArray(Fe.parts)&&Fe.parts.some(Dt=>Dt.inlineData));if(qt.length>=Tt){let Fe=qt.length-Tt+1;for(let Dt=0;Dt<Fe;Dt++){let _t=qt[Dt];Array.isArray(_t.parts)&&(_t.parts=_t.parts.filter(bt=>!bt.inlineData))}}if(r.length>0&&r[r.length-1].role==="user"){let Fe=r[r.length-1];typeof Fe.text=="string"&&(Fe.text+=`
676
-
677
- ${ne}`,Array.isArray(Fe.parts)||(Fe.parts=[{text:Fe.text}]),Fe.parts.push(Ot))}else r.push({role:"user",text:ne,parts:[{text:ne},Ot]})}}catch(ge){console.error("Vision screenshot capture error:",ge)}if(d?.compression===0&&(m?.tokens||0)>$&&(r=Ys(r,6)),W>0?yield{type:"status",content:"Working"}:yield{type:"status",content:"Connecting"},St){try{let{clearPendingNudges:ge}=await import("./subagent_state-LZCOZSUJ.js");ge()}catch{}yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
678
-
679
- \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}try{let{consumePendingNudges:ge}=await import("./subagent_state-LZCOZSUJ.js"),be=ge();if(be&&be.length>0){let ne=be.join(`
680
-
681
- `);r.length>0&&r[r.length-1].role==="user"?r[r.length-1].text+=`
682
-
683
- ${ne}`:r.push({role:"user",text:ne}),yield{type:"status",content:"Subagent Update"}}}catch{}if(s){let ge=await s();ge&&(ge.startsWith("/btw")?r.length>0&&r[r.length-1].role==="user"?r[r.length-1].text+=`
684
-
685
- [system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
686
- [question] ${ge.replace("/btw","").trim()} [/question]`:r.push({role:"user",text:`[system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
687
- [question] ${ge.replace("/btw","").trim()} [/question]`}):r.length>0&&r[r.length-1].role==="user"?r[r.length-1].text+=`
688
-
689
- [STEERING HINT from USER, High Priority] ${ge.trim()} [/STEERING HINT]`:r.push({role:"user",text:`[STEERING HINT from USER, High Priority] ${ge.trim()} [/STEERING HINT]`}),yield{type:"status",content:`${ge.startsWith("/btw")?"Question Forwarded...":"Steering Hint Injected..."}`})}let xe,Qe=!1,He=1,ze=1,ce="",Mt=null,Je=null,Kt=null,G=0,z=[],Ge=0,zt=!1,vt=!1,Zt=!1,ln=!1,Sn=!0,uo=0,tt="",Ye="",It=!1,Tn=!1,Ne=!0,he=e,je="";for(;He<=Qt&&ze<=Qt&&!Qe&&!St;){let ge=!1;try{ce="",Sn&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},Sn=!1,ze===1&&(tt=""));let be=I=>{if(!I||!I.includes("[tool:"))return I;let te="",F=_s(I);F&&(te=F.fullBlock,I=F.remainingText),I=I.replace(na,(de,ke)=>ke.includes("[tool:")?ke.trim():de);let U="",ye=0;for(;ye<I.length;){let de=I.indexOf("[tool:",ye);if(de===-1){U+=nr(I.substring(ye));break}let ke=I.substring(ye,de);U+=nr(ke);let Ze=-1,N=null,Q=0;for(let $e=de;$e<I.length;$e++){let p=I[$e];if(N){if(p===N){let Le=0;for(let Ae=$e-1;Ae>=0&&I[Ae]==="\\";Ae--)Le++;Le%2===0&&(N=null)}}else if(p==='"'||p==="'"||p==="`")N=p;else if(p==="(")Q++;else if(p===")")Q--;else if(p==="]"&&Q<=0){Ze=$e;break}}if(Ze===-1){U+=I.substring(de);break}U+=I.substring(de,Ze+1),ye=Ze+1}return te+U},ne=r.filter(I=>(I.role==="user"||I.role==="agent"||I.role==="system")&&!String(I.id).startsWith("welcome")&&!I.isMeta&&!I.isTerminalRecord&&!(I.text&&I.text.startsWith("[TERMINAL_RECORD]"))).map((I,te,F)=>{let U=I.text||"";A||(U=U.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),I.role==="agent"&&(U=be(U),U=U.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),U=U.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*"));let ye=[];return Array.isArray(I.parts)&&I.parts.length>0?ye=I.parts.map(de=>{if(de.text){let ke=de.text;return A||(ke=ke.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),I.role==="agent"&&(ke=be(ke),ke=ke.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),ke=ke.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*")),{text:ke}}return de}):ye=[{text:U}],I.binaryPart&&gt(he)&&F.slice(te+1).filter(ke=>ke.role==="user"&&!ke.text?.startsWith("[TOOL RESULT]")).length<=2&&ye.push(I.binaryPart),{role:I.role==="user"||I.role==="system"?"user":"model",parts:ye}});for(let I=0;I<ne.length;I++){let te=ne[I],F=te.parts?.[0]?.text||"";if(te.role==="model"&&/\[tool:/i.test(F)){let U=-1;for(let ye=I+1;ye<ne.length;ye++){let de=ne[ye],ke=de.parts?.[0]?.text||"";if(de.role==="user"&&ke.startsWith("[TOOL RESULT]")){U=ye;break}}if(U!==-1&&U!==I+1){let[ye]=ne.splice(U,1);ne.splice(I+1,0,ye)}}}for(let I=ne.length-2;I>=0;I--){let te=ne[I],F=ne[I+1];te.role==="user"&&F.role==="user"&&(F.parts?.[0]?.text||"").trim().startsWith("[SYSTEM")&&ne.splice(I,1)}let Ot=[];for(let I=0;I<ne.length;I++){let te=ne[I];if(Ot.length===0)Ot.push(te);else{let F=Ot[Ot.length-1];F.role===te.role?(F.parts[0].text+=`
690
-
691
- `+(te.parts?.[0]?.text||""),te.parts?.length>1&&F.parts.push(...te.parts.slice(1))):Ot.push(te)}}ne.length=0,ne.push(...Ot),he=e;let Ct=`${g}|${i}|${a}|${u}|${he}|${JSON.stringify(c)}|${!!d?.dynamicDirAwareness}|${!!d?.subAgents}`,Tt=On.key===Ct&&On.value;if((process.env.I_HAVE_TOO_MUCH_MONEY==="true"||process.env.I_HAVE_TOO_MUCH_MONEY===!0)&&(Tt=!1),Tt)je=On.value;else{let I=i==="Mistral"?!!Hn(he):!(he||"gemma").toLowerCase().startsWith("gemma");je=Ti(c,((he||"gemma").toLowerCase().startsWith("gemma"),u),a,d,A,O,i,i==="Google"?!0:h,I,g),d?.dynamicDirAwareness||(je+=`
692
- ${Is.replace(`
693
- **Directory Structure**`,`
694
- -- Directory Structure --`)}`),On.key=Ct,On.value=je}let Fe=ne[ne.length-1];if(Ro()&W>0){await new Promise(F=>setTimeout(F,2500)),yield{type:"status",content:"Verifying"};let I=await vn(),te=I?I.diagnostics:null;te&&Fe&&Fe.role==="user"&&Fe.parts?.[0]?.text&&(Fe.parts[0].text+=`
695
- ${te} [/ERROR]`),yield{type:"status",content:"Working"}}let Dt=i==="Mistral"||i==="Google"&&e?.toLowerCase().startsWith("gemma");if(d?.advanceRollback&&Fe&&Fe.role==="user"&&Fe.parts?.[0]?.text?.startsWith("[TOOL RESULT]"))try{let I=await Zn.getLatestFileChanges(g);if(I&&(I.newFiles.length>0||I.modifiedFiles.length>0||I.deletedFiles.length>0)){let te=`
696
- [system] File Changes:
697
- `;for(let U of I.newFiles)te+=`* ${U} (created)
698
- `;for(let U of I.modifiedFiles)te+=`* ${U} (modified)
699
- `;for(let U of I.deletedFiles)te+=`* ${U} (deleted)
700
- `;te+="[/system]",Fe.parts[0].text+=te;let F=-1;for(let U=r.length-1;U>=0;U--)if(r[U].role==="user"&&r[U].text?.startsWith("[TOOL RESULT]")){F=U;break}F!==-1&&(r[F].text+=te)}}catch{}let _t=Math.floor(Yn*(a==="Flux"?.98:.8)),bt=W+1;bt>=_t&&Fe&&Fe.parts?.[0]&&(Fe.parts[0].text+=`
701
- [system] WARNING, Turn Limit Impending: Step ${bt}/${Yn}. Wrap up quickly/prompt user to continue. [/system]`);let Rt=new Promise((I,te)=>{k.signal.aborted&&te(new DOMException("The user aborted a request.","AbortError")),k.signal.addEventListener("abort",()=>{te(new DOMException("The user aborted a request.","AbortError"))})});Rt.catch(()=>{});let pt=ne;if(i==="Ollama")xe=Ts(t.apiKey,he,pt,je,u,a,h,k.signal,1,d?.ollamaEndpoint||"Cloud");else if(i==="OpenRouter")xe=Do(t.apiKey,he,pt,je,u,a,h,k.signal,1,g);else if(i==="DeepSeek")xe=vo(t.apiKey,he,pt,je,u,a,h,k.signal,1);else if(i==="Mistral")xe=Io(t.apiKey,he,pt,je,u,a,h,k.signal,1,g);else if(i==="NVIDIA"){let I=Oo(t.apiKey,he,pt,je,u,a,h,k.signal,1);xe=Xi(I,he)}else if(i==="CrofAI")xe=$o(t.apiKey,he,pt,je,u,a,h,k.signal,1);else if(i==="InferX")xe=Lo(t.apiKey,he,pt,je,u,a,h,k.signal,1);else if(i==="SenseNova")xe=Po(t.apiKey,he,pt,je,u,a,h,k.signal,1);else if(i==="AIHubMix")xe=No(t.apiKey,he,pt,je,u,a,h,k.signal,1);else if(i==="Poolside")xe=Fo(t.apiKey,he,pt,je,u,a,h,k.signal,1);else if(i==="9router"||i==="9Router")xe=Bo(t.apiKey,he,pt,je,u,a,h,k.signal,1);else if(i==="ExpLabs"||i==="ExperientialLabs")xe=Uo(t.apiKey,he,pt,je,u,a,h,k.signal,1);else{let te=Cs(t?.apiKey).models.generateContentStream({model:he||"gemini-3-flash-preview",contents:pt,config:{systemInstruction:je,mediaResolution:"MEDIA_RESOLUTION_HIGH",safetySettings:[{category:kn.HARM_CATEGORY_HARASSMENT,threshold:wn.BLOCK_NONE},{category:kn.HARM_CATEGORY_HATE_SPEECH,threshold:wn.BLOCK_NONE},{category:kn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:wn.BLOCK_NONE},{category:kn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:wn.BLOCK_NONE}],temperature:1.05,thinkingConfig:(()=>{let F=(he||"").toLowerCase(),U=F.includes("gemma-4")||F.startsWith("gemma"),ye=F.includes("gemini-3");if(U||ye)return U?u.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:dt.MINIMAL}:{includeThoughts:!0,thinkingLevel:dt.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:F.includes("pro")?dt.LOW:dt.MINIMAL,Low:dt.LOW,Medium:dt.MEDIUM,Standard:dt.MEDIUM,High:dt.HIGH,xHigh:dt.HIGH}[u]||dt.MEDIUM};{let de={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[u]||2048;return de===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:de}}})()}},{signal:k.signal});xe=await Promise.race([te,Rt])}ce="",Mt=null,Kt=null,z=[],Ge=0,yield{type:"model_update",content:null},Ye="",It=tt.length>0;let en="",Ko=Date.now(),En=async function*(){if(i==="Google"&&en){let I=qn(en);for(let te of I)yield te;en="",Ko=Date.now()}},Fs=!0,Cn="",Ln=!1,$t=null,mr={tool:{startPrefix:"[tool",fullPrefix:"[tool:functions.",endTag:"]"},agent:{startPrefix:"[agent",fullPrefix:"[agent:generalist.",endTag:"]"},end:{startPrefix:"[[END]]",fullPrefix:"[[END]]",endTag:"[[END]]"},kimi_section:{startPrefix:"<|tool_calls_section_begin|>",fullPrefix:"<|tool_calls_section_begin|>",endTag:"<|tool_calls_section_end|>"},kimi_call:{startPrefix:"<|tool_call_begin|>",fullPrefix:"<|tool_call_begin|>",endTag:"<|tool_call_end|>"}},qn=I=>{let te=[],F=I;for(;F.length>0;)if(Ln){let U=Cn+F,ye=mr[$t];if(ye){let Ze=!1;if(U.length<ye.startPrefix.length?ye.startPrefix.startsWith(U)||(Ze=!0):U.startsWith(ye.startPrefix)?U.length>=ye.fullPrefix.length&&!U.startsWith(ye.fullPrefix)&&(Ze=!0):Ze=!0,Ze){te.push({type:"text",content:U}),Cn="",Ln=!1,$t=null,F="";break}}let de=-1,ke=ye?ye.endTag:"]";if($t==="tool"||$t==="agent"){let Ze=0,N=null,Q=0,$e=!1;for(let p=0;p<U.length;p++){let Le=U[p];if(N){if(Le===N){let Ae=0;for(let K=p-1;K>=0&&U[K]==="\\";K--)Ae++;Ae%2===0&&(N=null)}}else if(Le==='"'||Le==="'"||Le==="`")N=Le;else if(Le==="(")Ze++,$e=!0;else if(Le===")")Ze--;else if(Le==="[")Q++;else if(Le==="]"){if($e&&Ze===0&&Q===1){de=p;break}Q--}}}else de=U.indexOf(ke);if(de!==-1){let Ze=ke.length;if(!$t?.startsWith("kimi")){let N=U.substring(0,de+Ze);te.push({type:"text",content:N})}Cn="",Ln=!1,$t=null,F=U.substring(de+Ze)}else{let Ze=$t?.startsWith("kimi")?8192:512;U.length>Ze?(te.push({type:"text",content:U}),Cn="",Ln=!1,$t=null):Cn=U,F="";break}}else{let U=F.indexOf("[tool"),ye=F.indexOf("[agent"),de=F.indexOf("[[END]]"),ke=F.indexOf("<|tool_calls_section_begin|>"),Ze=F.indexOf("<|tool_call_begin|>"),N=[{type:"tool",idx:U,start:"[tool",end:"]"},{type:"agent",idx:ye,start:"[agent",end:"]"},{type:"end",idx:de,start:"[[END]]",end:"[[END]]"},{type:"kimi_section",idx:ke,start:"<|tool_calls_section_begin|>",end:"<|tool_calls_section_end|>"},{type:"kimi_call",idx:Ze,start:"<|tool_call_begin|>",end:"<|tool_call_end|>"}].filter(Q=>Q.idx!==-1).sort((Q,$e)=>Q.idx-$e.idx);if(N.length>0){let Q=N[0];Q.idx>0&&te.push({type:"text",content:F.substring(0,Q.idx)}),Ln=!0,$t=Q.type,Cn="",F=F.substring(Q.idx)}else{let Q=["[tool","[agent","[[END]]","<|tool_calls_section_begin|>","<|tool_call_begin|>"],$e=-1;for(let p of Q){for(let Le=p.length-1;Le>0;Le--)if(F.endsWith(p.substring(0,Le))){$e=F.length-Le;let Ae=Q.indexOf(p);Ae===0?$t="tool":Ae===1?$t="agent":Ae===2?$t="end":Ae===3?$t="kimi_section":$t="kimi_call";break}if($e!==-1)break}if($e!==-1)$e>0&&te.push({type:"text",content:F.substring(0,$e)}),Ln=!0,Cn=F.substring($e),F="";else{te.push({type:"text",content:F});break}}}return te},hr=xe[Symbol.asyncIterator]();for(;;){let{value:I,done:te}=await Promise.race([hr.next(),Rt]);if(te)break;if(I&&I.type==="status"){yield I;continue}let F="",U=I.candidates?.[0]?.content?.parts;if(U&&U.length>0)for(let de of U){let ke=typeof de.text=="string"?de.text:de.text?parseChunkText(de.text):"";de.thought?ke&&(ge||(F+="<think>",ge=!0),F+=ke):ke&&(ge&&(F+="</think>",ge=!1),F+=ke)}else I.text&&ge&&(F+="</think>",ge=!1);F=Qr(F);let ye=F?F.trim().split(/\s+/).filter(Boolean).length:0;if(t&&typeof t.onTokenChunk=="function"&&t.onTokenChunk(F,ye),Fs&&(yield{type:"status",content:"Thinking"},Fs=!1),St){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
702
-
703
- \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(F){if(It){if(Ye+=F,Ye.length>=64){let N=0,Q=Math.min(tt.length,Ye.length);for(let p=Q;p>=10;p--)if(tt.endsWith(Ye.substring(0,p))){N=p;break}let $e=Ye.substring(N);if($e){let Le=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(tt)?$e.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):$e.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(Le)if(ce+=Le,i==="Google")en+=Le;else{yield*En();let Ae=qn(Le);for(let K of Ae)yield K}}It=!1,Ye=""}continue}else if(ce+=F,i==="Google")en+=F;else{yield*En();let N=qn(F);for(let Q of N)yield Q}let de=ra(ce);if(de.inside){Tn=!0,Kt||(Kt=Date.now());let Q={Ask:"ask",AskUser:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Cancel:"cancel",Await:"await",Answer:"answer",Steer:"steer",steer:"steer"}[de.toolName]||de.toolName,$e=de.args||"",p=null;if(["write_file","update_file","view_file","read_folder","write_pdf","write_docx","search_keyword","generate_image","file_map","invoke","invoke_sync","get_progress","await","answer"].includes(Q)){let Ae=J($e),K=Ae.path||Ae.targetFile||Ae.TargetFile||Ae.directory,tn=Ae.keyword,Rn=Ae.title||Ae.task,pn=Ae.id||Ae.taskId,Se=Ae.timeout||Ae.time;if(tn!=null)p=String(tn).replace(In,"");else if(K)p=q.basename(String(K).replace(In,"").replace(Qi,"/"));else if(Rn&&(Q==="invoke"||Q==="invoke_sync"))p=String(Rn).replace(In,"").substring(0,30);else if(pn&&Q==="get_progress")p=String(pn).replace(In,"");else if(Se&&Q==="await"){let Lt=parseFloat(String(Se).replace(In,""));isNaN(Lt)?p=String(Se).replace(In,""):(Lt<5&&(Lt=5),Lt>120&&(Lt=120),p=(cn=>{if(cn>=60){let zo=Math.floor(cn/60),Pn=cn%60;return`${zo}m${Pn>0?` ${Pn}s`:""}`}return`${cn}s`})(Lt))}else{let Lt=$e.match(zr);if(Lt){let Bt=Lt[1].replace(In,"");Q==="invoke"||Q==="invoke_sync"||Q==="get_progress"?p=Bt.substring(0,30):p=Q==="search_keyword"||Q==="file_map"?Bt:q.basename(Bt.replace(Qi,"/"))}}}let Le=`${As[Q]||Q}${p?` ${p}`:""}`;if((Q!==Mt||p!==Je)&&(Mt=Q,Je=p,yield{type:"status",content:`${Le}`},process.stdout.isTTY)){let K={WebSearch:"Searching",web_search:"Searching",WebScrape:"Reading",web_scrape:"Reading",ReadFile:"Reading",read_file:"Reading",ReadFolder:"Reading",read_folder:"Reading",WriteFile:"Writing",write_file:"Writing",UpdateFile:"Editing",update_file:"Editing",WritePdf:"Creating",write_pdf:"Creating",WriteDocx:"Creating",write_docx:"Creating",SearchKeyword:"Searching",search_keyword:"Searching",CodeSearch:"Searching",code_search:"Searching",Run:"Executing",Ask:"User Input Required",AskUser:"User Input Required",Memory:"Updating Memory",GenerateImage:"Generating",InvokeSync:"Sub-Agent Working",invoke_sync:"Sub-Agent Working",Invoke:"Working",invoke:"Working",GetProgress:"Checking Progress",get_progress:"Checking Progress",Cancel:"Stopping Generalist",cancel:"Stopping Generalist",Await:"Waiting",await:"Waiting",EmergencyRollback:"Rolling the Ball",Answer:"Answering Sub-Agent",answer:"Answering Sub-Agent",Steer:"Steering Sub-Agent",steer:"Steering Sub-Agent",Click:"Clicking",click:"Clicking",Drag:"Dragging",drag:"Dragging",Scroll:"Scrolling",scroll:"Scrolling",KeyboardTyping:"Typing",keyboard_typing:"Typing",KeyPress:"Pressing Key",key_press:"Pressing Key",RecaptureScreen:"Recapturing Screen",recapture_screen:"Recapturing Screen"}[Q]||"Working";process.stdout.write(`\x1B]0;${K}...\x07`)}}if(ce.length-uo>150){uo=ce.length;let N=ar(ce,!1),Q=_s(N),$e=Q?(Q.innerContent||"").trim():"",p=$e.split(/[.!?]\s+/),Le=new Set(p),Ae=p.length>10?(p.length-Le.size)/p.length:0,K=$e.split(/\s+/).filter(Ee=>Ee.length>0).length,tn=.6,Rn=.8,pn=!1;if((i.toLowerCase().includes("google")||i.toLowerCase().includes("mistral"))&&((he||"").toLowerCase().startsWith("gemma")||(he||"").toLowerCase().includes("stral"))){let _={low:256,medium:1024,high:8192,max:16384,xhigh:16384}[u?.toLowerCase()]||2500;pn=K>_}if(Ae>tn||pn){yield{type:"status",content:`${Ae>tn?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},vt=!0,await new Promise(_=>setTimeout(_,3e3));break}let Bt=or(ce).trim().split(/[.!?]\s+/),cn=new Set(Bt);if((Bt.length>10?(Bt.length-cn.size)/Bt.length:0)>Rn){yield{type:"status",content:"Response Loop Detected. Re-centering..."},vt=!1,ln=!0,await new Promise(Ee=>setTimeout(Ee,3e3));break}let Pn=N.replace(Hr,"").replace(Gr,"").replace(jr,"").replace(Vr,""),Pt=Pn.toLowerCase().split(/\s+/).map(Ee=>Ee.replace(Yr,"")).filter(Ee=>Ee.length>0),dn=!1;if(Pt.length>=10)for(let Ee=1;Ee<=15;Ee++){let _=Math.max(3,Math.ceil(10/Ee));if(Pt.length<Ee*_)continue;let j=Pt.slice(Pt.length-Ee),se=j.join(" ");if(Ee>1&&se===j.slice(0,Math.floor(Ee/2)).join(" ").repeat(2).trim())continue;let le=!0;for(let me=1;me<_;me++)if(Pt.slice(Pt.length-Ee*(me+1),Pt.length-Ee*me).join(" ")!==se){le=!1;break}if(le){dn=!0;break}}if(!dn){let Ee=Pn.toLowerCase().replace(Kr,"");if(Ee.length>=20)for(let _=1;_<=10;_++){let j=Math.max(5,Math.ceil(16/_));if(Ee.length<_*j)continue;let se=Ee.substring(Ee.length-_),le=!0;for(let me=1;me<j;me++)if(Ee.substring(Ee.length-_*(me+1),Ee.length-_*me)!==se){le=!1;break}if(le){dn=!0;break}}}if(dn){yield{type:"status",content:"Stuttering Detected. Re-centering..."},vt=!1,Zt=!0,await new Promise(Ee=>setTimeout(Ee,3e3));break}}let ke=Vt(ce),Ze=Go(ke);for(;Ze.length>Ge;){yield*En();let N=Ze[Ge],Q=Date.now(),p={Ask:"ask",AskUser:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Await:"await",await:"await",AwaitSubagent:"await",awaitSubagent:"await",Answer:"answer",answer:"answer",AnswerSubagent:"answer",answerSubagent:"answer",Steer:"steer",steer:"steer",SteerSubagent:"steer",steerSubagent:"steer",Cancel:"cancel",cancel:"cancel",Click:"click",click:"click",Drag:"drag",drag:"drag",Scroll:"scroll",scroll:"scroll",KeyboardTyping:"keyboard_typing",keyboard_typing:"keyboard_typing",KeyPress:"key_press",key_press:"key_press",RecaptureScreen:"recapture_screen",recapture_screen:"recapture_screen",EmergencyRollback:"EmergencyRollback"}[N.toolName]||N.toolName,Le=As[p]||N.toolName,Ae=Dn(p,N.args);yield{type:"status",content:`${Le}${Ae?` ${Ae}`:""}`};let K="";if(p==="click"){let _=J(N.args);K=`\u2714 Clicked: ${_.intendedClickText?`${_.intendedClickText}`:""}`}else if(p==="drag"){let _=J(N.args);K=`\u2714 Dragged: Cell ${_.fromGridId||""} \u2192 Cell ${_.toGridId||""}`}else if(p==="scroll"){let _=J(N.args);K=`\u2714 Scrolled: ${_.direction||"down"} (${_.amount||1})`}else if(p==="keyboard_typing"){let _=J(N.args);K=`\u2714 Typed: ${_.text?`"${_.text.length>20?_.text.substring(0,20)+"...":_.text}"`:""}`}else if(p==="key_press")K=`\u2714 Pressed Key: ${J(N.args).key||""}`;else if(p==="recapture_screen")K="\u2714 Recaptured Screen";else if(p==="web_search"){let{query:_,limit:j=10,aiMode:se=!1}=J(N.args);K=`${_?"\u2714":"\u2718"} ${se?"AI Search":"Searched"}: ${_?`${_}`:"No Search Query"}${se===!1&&_?` \u2192 ${j}`:""}`}else if(p==="web_scrape"){let _=J(N.args).url||null;K=`${_?"\u2714":"\u2718"} Visited: ${_||"No Source"}`}else if(p==="view_file"){let{path:_,StartLine:j,EndLine:se,start_line:le,end_line:me,startLine:Be,endLine:Ce}=J(N.args),pe=j||le||Be,V=se||me||Ce,Z=parseInt(pe)||1,re=parseInt(V)||(pe?Z+800:800),Te="...",Ke=re,_e=(_||"").trim().toLowerCase().replaceAll("\\","/");if(_e.startsWith("#skill"))_e.startsWith("#skill/global/fluxflow")||_e.startsWith("#skills/global/fluxflow")?K="\u2714 Read Documentation":K=`\u2714 Read Skill: ${q.basename(_.replaceAll("\\","/"))}`;else{try{let fe=q.resolve(process.cwd(),_);if(Ie.existsSync(fe)){let yt=Ie.readFileSync(fe,"utf8").split(`
704
- `).length;Te=yt,!pe&&!V&&yt>800?Ke=Math.min(50,yt):Ke=Math.min(re,yt)}}catch{}let Me=(_||"").toLowerCase(),ut=Me.endsWith(".pdf"),Re=Me.endsWith(".docx")||Me.endsWith(".doc")||Me.endsWith(".ppt")||Me.endsWith(".pptx")||Me.endsWith(".xls")||Me.endsWith(".xlsx"),et=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(Me);ut||Re?K=`${_.length>0?"\u2714":"\u2718"} ${_?`Analyzed: ${q.basename(_)}`:"Analyzed: File Not Found"}`:et?K=`${_.length>0?"\u2714":"\u2718"} ${_?`Processed: ${q.basename(_)}`:"Processed: File Not Found"}`:K=`${Te!=="..."?"\u2714":"\u2718"} Read: ${_?`${q.basename(_)} \u2192 ${Te!=="..."?`Lines ${Z} - ${Ke} of ${Te}`:"File Not Found"}`:"File Not Found"}`}}else if(p==="list_files"||p==="read_folder"){let _=p==="list_files"?"List":"Browsed",j=J(N.args).path||null,se=J(N.args).recurse||1;K=`${j?"\u2714":"\u2718"} ${_}: ${j?`${j==="."?`./${se>1?"*":""}`:`${j.replaceAll("\\","/")}${se>1?`${j.endsWith("/")?"*":"/*"}`:`${j.endsWith("/")?"":"/"}`}`}`:"No Folder Selected"}`}else if(p==="write_file"||p==="update_file"){let _=p==="write_file"?"Created":"Edited",j=J(N.args).path||null;K=`${j?"\u2714":"\u2718"} ${_}: ${j.replaceAll("\\","/")||"No File Changes"}`}else if(p==="write_pdf"){let _=J(N.args).path||null;K=`${_?"\u2714":"\u2718"} Generated: ${_.replaceAll("\\","/")||"No PDF Generated"}`}else if(p==="write_docx"){let _=J(N.args).path||null;K=`${_?"\u2714":"\u2718"} Generated: ${_.replaceAll("\\","/")||"No Docx Generated"}`}else if(p==="file_map"){let _=J(N.args).path;K=`${_?"\u2714":"\u2718"} Indexed: ${_.replaceAll("\\","/")?""+_:"File Not Found"}`}else if(p.toLowerCase()==="search_keyword"||p.toLowerCase()==="todo")K="";else if(p.toLowerCase()==="generate_image"){let{path:_,outputPath:j,output:se}=J(N.args);K=`\u2714 Generated: ${_||j||se||"generated_image.png"}`}else if(p==="invoke_sync"||p==="InvokeSync"){let _=Dn(p,N.args);K=`\u2714 Called Generalist${_?`: ${_}`:""}`}else if(p==="Invoke"||p==="InvokeAsync"||p==="invoke"){let _=Dn(p,N.args);K=`\u2714 Started Generalist${_?`: ${_}`:""}`}else if(p==="get_progress"||p==="GetProgress"){let _=Dn(p,N.args);K=`\u2714 Checked${_?`: ${_}`:""}`}else if(p==="cancel"){let _=Dn(p,N.args);K=`\u{1F6C7} Cancelled${_?`: ${_}`:""}`}else if(p==="steer"||p==="Steer"){let _=Dn(p,N.args);K=`\u2714 Steered${_?`: ${_}`:""}`}else if(p==="EmergencyRollback"){let{method:_}=J(N.args);K=_==="forceRevert"?"":"\u2714 Rollback Point Checked"}else if(p==="await"||p==="Await"){let{time:_,timeout:j}=J(N.args),se=parseFloat(j||_)||0;se||(se=120);let le=Ce=>{if(Ce>=60){let pe=Math.floor(Ce/60),V=Ce%60;return`${pe}m${V>0?` ${V}s`:""}`}return`${Ce}s`},me=["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"];K=`\u2714 ${me[Math.floor(Math.random()*me.length)]} \u2192 ${le(se)}`}else p==="Answer"||p==="answer"?K="\u2714 Resolved Sub-Agent Query":p==="exec_command"||p==="ask"?K="":K=`Executed: ${N.toolName}`;if(yield*En(),p==="exec_command"){let{command:_}=J(N.args);if(_&&t.systemSettings&&t.systemSettings.allowExternalAccess===!1){let j=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],se=q.resolve(process.cwd()).substring(0,3).toLowerCase(),le=V=>{let Z=[],re="",Te=null;for(let Ke=0;Ke<V.length;Ke++){let _e=V[Ke];Te?(_e===Te&&(Te=null),re+=_e):_e==='"'||_e==="'"?(Te=_e,re+=_e):_e==="&"&&V[Ke+1]==="&"||_e==="|"&&V[Ke+1]==="|"?(re.trim()&&(Z.push(re.trim()),re=""),Ke++):_e===";"||_e==="|"||_e==="&"?re.trim()&&(Z.push(re.trim()),re=""):re+=_e}return re.trim()&&Z.push(re.trim()),Z},me=V=>{let Z=[],re="",Te=null;for(let Ke=0;Ke<V.length;Ke++){let _e=V[Ke];Te?(_e===Te&&(Te=null),re+=_e):_e==='"'||_e==="'"?(Te=_e,re+=_e):/\s/.test(_e)?re&&(Z.push(re),re=""):re+=_e}return re&&Z.push(re),Z},Be=V=>{let Z=V.replace(/^['"]|['"]$/g,"").trim();return!Z||process.platform==="win32"&&/^\/[a-zA-Z0-9?]+$/.test(Z)?!1:j.some(re=>{if(re.source==="[a-zA-Z]:[\\\\\\/]"){let Te=Z.match(/[a-zA-Z]:[\\\/]/i);return Te&&Te[0].toLowerCase()!==se}return re.test(Z)})};if(le(_).some(V=>{let Z=me(V);if(Z.length===0)return!1;let re=Z[0].replace(/^['"]|['"]$/g,"").toLowerCase();if(["echo","printf","write-output"].includes(re)){let Ke=!1;return Z.some(_e=>{let Ut=_e.replace(/^['"]|['"]$/g,"");if(Ut===">"||Ut===">>"||Ut==="<")return Ke=!0,!1;if(Ut.startsWith(">")||Ut.startsWith("<")){let Me=Ut.replace(/^[><]+/,"");return Be(Me)}return Ke?(Ke=!1,Be(_e)):!1})}return Z.some(Ke=>Be(Ke))})){let V='Access Denied. Prohibited from accessing external directories while "External Workspace Access" is disabled.';t.onExecStart&&t.onExecStart(_||"No Command"),yield{type:"exec_start"},await new Promise(Z=>setTimeout(Z,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${V}`),await new Promise(Z=>setTimeout(Z,50)),t.onExecEnd&&t.onExecEnd(),z.push({role:"user",text:`[TOOL RESULT]: ERROR: ${V}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${V}`},Ge++;continue}}t.onExecStart&&t.onExecStart(_||"No Command"),yield{type:"exec_start"}}let tn=J(N.args),Rn=tn.path||tn.targetPath||null;if(Rn){let _=t.systemSettings&&t.systemSettings.allowExternalAccess===!1,j=q.resolve(Rn),se=q.resolve(process.cwd());if(_&&!j.startsWith(se)){let le="Access Denied. You are not allowed to access files outside the current workspace.";if(p==="write_file"||p==="update_file"){let Be=`\u2718 ${p==="write_file"?"Write Canceled":"Edit Canceled"}: ${tn.path||"..."}`,Ce=115;process.stdout.isTTY&&(Ce=process.stdout.columns-5||120);let pe=Math.min(Be.length+4,Ce),V=`${Be.padEnd(pe-2).substring(0,pe-2)}`;yield{type:"visual_feedback",content:jt(`${Ne?`
705
- `:""}${V}
706
- `)},Ne=!1}z.push({role:"user",text:`[TOOL RESULT]: ERROR: ${le}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${le}`},Ge++;continue}}if(t.onToolApproval&&(p==="write_file"||p==="update_file"||p==="exec_command")){let j=t.systemSettings||{},se=j.autoExec,le=null,me=!1,Be=!1,Ce=!1;if(p==="exec_command"){let{command:Me}=J(N.args),ut=(Me||"").trim(),Re=(Wt,yt)=>{if(!yt)return!1;let Xt=yt.split(",").map(Ht=>Ht.trim().toLowerCase()).filter(Boolean),at=Wt.toLowerCase();return Xt.some(Ht=>at.startsWith(Ht))},et=Re(ut,j.alwaysAskCommands),fe=Re(ut,j.autoApproveCommands);if(Be=Re(ut,j.autoDisallowCommands),et?me=!0:(fe||j.autoApproveGit&&/^git\s+commit\b/i.test(ut))&&(le="allow"),!me&&!le){if(j.networkAccess===!1){let yt=ut.trim().replace(/\s+/g," ").replace(/^['"]+|['"]+$/g,"").toLowerCase().split(" "),at=yt[0].split("/").pop().split("\\").pop().replace(/\.exe$/,""),Ht=new Set(["curl","wget","httpie","xh","ssh","scp","sftp","rsync","ftp","lftp","tftp","telnet","nc","netcat","socat","ping","traceroute","tracert","dig","nslookup","host","whois","nmap","docker","podman","kubectl","helm","gcloud","aws","az","terraform","ansible-playbook","nix","nix-env","apt","apt-get","dpkg","yum","dnf","pacman","zypper","brew","apk","choco","scoop","conda","mamba","aria2c","axel","smbclient","lynx","w3m","links","elinks","heroku","netlify","vercel","firebase","supabase","wrangler","flyctl","powershell","pwsh","certutil","bitsadmin","cloudflared","ngrok","tailscale","zerotier","rclone"]),lt=!1;Ht.has(at)&&(lt=!0);let nt=nn=>yt.slice(1).some(on=>nn.includes(on)),ct=nn=>{let on=yt.findIndex(fn=>nn.includes(fn)),Nn=yt.findIndex(fn=>["run","exec","test"].includes(fn));return on!==-1&&!(Nn!==-1&&Nn<on)};at==="git"&&nt(["clone","pull","push","fetch"])&&(lt=!0),at==="go"&&nt(["get","install"])&&(lt=!0),at==="npm"&&ct(["install","i","update","add"])&&(lt=!0),at==="yarn"&&ct(["add","install","upgrade"])&&(lt=!0),at==="pnpm"&&ct(["add","install","update"])&&(lt=!0),at==="bun"&&ct(["add","install","update"])&&(lt=!0),at==="deno"&&nt(["install","add"])&&(lt=!0),at==="pip"&&nt(["install","download"])&&(lt=!0),at==="pip3"&&nt(["install","download"])&&(lt=!0),at==="cargo"&&nt(["install","add"])&&(lt=!0),["bash","sh","zsh","fish"].includes(at)&&nt(["-c"])&&(lt=!0),at==="cmd"&&nt(["/c"])&&(lt=!0),lt&&(le="deny",Ce=!0)}!le&&Be&&(le="deny")}!me&&!le&&se&&(le="allow")}else se&&(le="allow");let pe=le,V="";le==="deny"&&(Ce?V="network":Be?V="settings":V="prohibited");let Z=!1,re="",Te=[],Ke=0,_e=!1,Ut="";if(!pe){if(p==="write_file"||p==="update_file")try{let Re=J(N.args),{path:et}=Re;if(et){let fe=q.resolve(process.cwd(),et),Wt=nt=>nt?nt.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,ct=>ct.toUpperCase()):"",yt=Wt(fe),Xt="",at=!1,Ht=await vn(),lt=Wt(Ht?.file_focused);if(Ht&&lt===yt&&Ht.full_content?(Xt=Ht.full_content,at=!0):Ie.existsSync(fe)&&(Xt=Ie.readFileSync(fe,"utf8"),at=!0),re=Xt,await yo.recordFileChange(fe,Xt),at){let nt=Xt;if(p==="write_file"){let ct=Re.content||Re.newContent||"";nt=ct.endsWith(`
707
- `)?ct:ct+`
708
- `,Ut=nt}else{let{patchPairs:ct,allowMultiple:nn,error:on}=Ws(Re);if(on){let kt=`[TOOL RESULT]: ERROR: ${on}`;z.push({role:"user",text:kt}),await Et("toolFailure"),t.onToolResult&&t.onToolResult("failure",p),yield{type:"tool_result",content:kt,toolName:p},Ge++;continue}let Nn=Re.allowMultiple!==void 0?Re.allowMultiple===!0||String(Re.allowMultiple).toLowerCase()==="true":nn;Ke=ct.length;let fn=Hs(Xt,ct,{allowMultiple:Nn});nt=fn.content,Ut=nt,Te=fn.results;let go=Te.filter(kt=>kt.success),wt=Te.filter(kt=>!kt.success);if(go.length===0){let kt=`[TOOL RESULT]: ERROR: Failed to apply patches to [${q.basename(fe)}].
709
- ${wt.map(Xn=>` \u2022 ${Xn.error}`).join(`
710
- `)}`,Fn=`\u2714 Edited: ${q.basename(fe.replaceAll("\\","/"))}`,Jn=115;process.stdout.isTTY&&(Jn=process.stdout.columns-5||120);let Bn=Math.min(Fn.length+4,Jn),mo=`${Fn.padEnd(Bn-2).substring(0,Bn-2)}`;yield{type:"visual_feedback",content:jt(`${Ne?`
711
- `:""}${mo}`)},Ne=!1,z.push({role:"user",text:kt}),await Et("toolFailure"),t.onToolResult&&t.onToolResult("failure",p),yield{type:"tool_result",content:kt,toolName:p},Ge++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${q.basename(fe)}`},bs(fe,Xt,nt),Z=!0,await new Promise(ct=>setTimeout(ct,50))}else if(p==="write_file"){let nt=Re.content||Re.newContent||"",ct=nt.endsWith(`
712
- `)?nt:nt+`
713
- `;Ut=ct,Ie.existsSync(fe)||(_e=!0,Ie.mkdirSync(q.dirname(fe),{recursive:!0}),Ie.writeFileSync(fe,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${q.basename(fe)}`},bs(fe,"",ct),Z=!0,await new Promise(nn=>setTimeout(nn,50))}}}catch(Re){console.error("Simulation/Diff Error:",Re)}let Me=null;xs(Re=>{Me=Re});let ut=t.onToolApproval;if(pe=await new Promise(async Re=>{let et=setInterval(()=>{Me&&(Wo.onIDEApproval&&Wo.onIDEApproval(Me),clearInterval(et),Re(Me))},100);try{let fe=await ut(p,N.args);clearInterval(et),Re(fe)}catch{clearInterval(et),Re("deny")}}),xs(null),p==="write_file"||p==="update_file"){let{path:Re}=J(N.args);if(Re){let et=q.resolve(process.cwd(),Re);if(zi(et,pe),pe==="deny"&&_e&&Ie.existsSync(et))try{Ie.unlinkSync(et)}catch{}}}pe==="deny"&&(V="user")}if(pe==="allow"&&Z&&Ro()){let{path:Me}=J(N.args),ut=q.resolve(process.cwd(),Me),Re=wt=>wt?q.resolve(wt).replace(/\\/g,"/").toLowerCase():"",et=await vn(),fe="";if(et&&et.file_focused&&Re(et.file_focused)===Re(ut)&&et.full_content&&(fe=et.full_content),!fe&&Ie.existsSync(ut)){let wt=Ie.readFileSync(ut,"utf8");wt&&(fe=wt)}!fe&&Ut&&(fe=Ut),(fe||_e)&&Ie.writeFileSync(ut,fe,"utf8");let Wt=fe.split(/\r?\n/),yt=Wt.length,Xt=Buffer.byteLength(fe,"utf8"),at="";re&&(at=`Old File contents:
714
- ${re.split(/\r?\n/).map((kt,Fn)=>`${Fn+1} | ${kt}`).join(`
715
- `)}
716
-
717
- `);let Ht="";if(yt<=100)Ht=Wt.join(`
718
- `);else{let wt=Wt.slice(0,50).join(`
719
- `),kt=Wt.slice(-50).join(`
720
- `);Ht=`${wt}
721
-
722
- ... [${yt-100} lines truncated for history stability] ...
723
-
724
- ${kt}`}let lt="";if(p==="update_file"){let wt=Gs(re,fe,Te,12,t?.compressToolResults||Wo?.systemSettings?.compressToolResults);lt=`SUCCESS: File [${Me}] updated via IDE Companion (May have user edits). [${Te.length}/${Ke}] blocks applied.
725
-
726
- ${wt}`}else{let wt=fe.split(/\r?\n/),kt=wt.length,Fn=Buffer.byteLength(fe,"utf8"),Jn="";re&&(Jn=`Old File contents:
727
- ${re.split(/\r?\n/).map((Xn,Sr)=>`${Sr+1} | ${Xn}`).join(`
728
- `)}
729
-
730
- `);let Bn="";if(kt<=100)Bn=wt.join(`
731
- `);else{let mo=wt.slice(0,50).join(`
732
- `),Xn=wt.slice(-50).join(`
733
- `);Bn=`${mo}
734
-
735
- ... [${kt-100} lines truncated] ...
736
-
737
- ${Xn}`}lt=`SUCCESS: File [${Me}] saved via IDE Companion (May have user edits).
738
- - Stats: [${kt} lines, ${(Fn/1024).toFixed(1)} KB]
739
- ${Jn}- Content Preview:
740
-
741
- ${Bn}`}let ct=`${Me?"\u2714":"\u2718"} ${p==="write_file"?"Created":"Edited"}: ${Me.replaceAll("\\","/")||"No File Changes"}`,nn=115;process.stdout.isTTY&&(nn=process.stdout.columns-5||120);let on=Math.min(ct.length+4,nn),Nn=`${ct.padEnd(on-2).substring(0,on-2)}`;yield{type:"visual_feedback",content:jt(`${Ne?`
742
- `:""}${Nn}`)},Ne=!1;let fn=Date.now();G=fn,yield{type:"tool_time",content:fn-Q};let go=`[TOOL RESULT]: ${lt}`;z.push({role:"user",text:go}),zt=!0,await Et("toolSuccess"),t.onToolResult&&t.onToolResult("success",p),yield{type:"tool_result",content:lt,aiContent:go,toolName:p},Ge++;continue}if(pe==="deny"){let Me=`Permission Denied: Prohibited ${p==="exec_command"?"Command":"file edit"}.`;if(V==="user"?Me="Permission Denied by User":V==="settings"?Me="Permission Denied by User Policy":V==="network"?Me="Permission Denied: Sandbox Network Access Disabled by User Policy.":V==="prohibited"&&p==="exec_command"&&(Me="Permission Denied: Prohibited Command in User Policy"),p==="write_file"||p==="update_file"){let Re=`\u2718 ${p==="write_file"?"Write Cancelled":"Edit Denied"}: ${J(N.args).path.replaceAll("\\","/")||"..."}`,et=115;process.stdout.isTTY&&(et=process.stdout.columns-5||120);let fe=Math.min(Re.length+4,et),Wt=`${Re.padEnd(fe-2).substring(0,fe-2)}`,yt=` ${" ".repeat(fe)} `;yield{type:"visual_feedback",content:jt(`${Ne?`
743
- `:""}${Wt}
744
- `)},Ne=!1}p==="exec_command"&&(await new Promise(ut=>setTimeout(ut,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${Me}`),await new Promise(ut=>setTimeout(ut,50)),t.onExecEnd&&t.onExecEnd()),z.push({role:"user",text:`[TOOL RESULT]: DENIED: ${Me}`}),yield{type:"tool_result",content:`[TOOL RESULT]: DENIED: ${Me}`},await Et("toolDenied"),t.onToolResult&&t.onToolResult("denied",p),Ge++;continue}}if(K){let _=115;process.stdout.isTTY&&(_=process.stdout.columns-5||120);let j=await s(),se=!1;j&&(se=j.trim().length>0);let le=Math.min(K.length+4,_),me=`${K.padEnd(le-2).substring(0,le-2)}`;yield{type:"visual_feedback",content:jt(`${Ne?`
745
- `:""}${me}${K.includes("\u2714")&&(K.includes("Created")||K.includes("Edited"))?"":`${se?"":`
746
- `}`}`)},Ne=!1}if(G>0){let _=Date.now()-G,j=Math.max(0,1e3-_);j>0&&await new Promise(se=>setTimeout(se,j))}let pn={chatId:g,history:n,onChunk:_=>t.onExecChunk?t.onExecChunk(_):null,onAskUser:t.onAskUser,systemSettings:t.systemSettings,mode:a,isMultiModal:gt(he),onVisualFeedback:t.onVisualFeedback,onSubagentUpdate:t.onSubagentUpdate,onTokenChunk:t.onTokenChunk,modelName:he,aiProvider:t.aiProvider,apiKey:t.apiKey,onUsage:t.onUsage};if(p==="write_file"||p==="update_file")try{let{path:_}=J(N.args);if(_){let j=q.resolve(process.cwd(),_),se=await vn();se&&se.file_focused===j&&se.full_content&&(pn.forcedContent=se.full_content)}}catch{}Yt.push(p);let Se=await io(p,N.args,pn);if((p==="write_file"||p==="update_file")&&Se.startsWith("SUCCESS")){let{path:_}=J(N.args);if(_){let j=q.resolve(process.cwd(),_);qi(j)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let Lt=Date.now();G=Lt,yield{type:"tool_time",content:Lt-Q},Kt=Lt;let Bt=null;if(typeof Se=="object"&&Se.binaryPart&&(Bt=Se.binaryPart,Se=Se.text),p==="search_keyword"){let{keyword:_,path:j}=J(N.args),se=typeof Se=="string"&&Se.startsWith("[GLOB]");se&&(Se=Se.slice(6).trimStart());let le=typeof Se=="string"&&Se.startsWith("[DIR]");le&&(Se=Se.slice(5).trimStart());let me=0;if(Se){let Te=Se.match(/Found (\d+) match/i);Te&&(me=parseInt(Te[1]))}let Be=(j||"").trim().toLowerCase().replaceAll("\\","/"),Ce=Be==="#doc"||Be==="#docs"||Be==="#documentation"||Be.includes("#skill/global/fluxflow")||Be.includes("#skills/global/fluxflow"),pe;if(Ce)pe=`${_?"\u2714":"\u2718"} Searched Documentation`;else{let Te=j?j.replace(/[\/\\]+$/,""):null,Ke=Te&&Te!=="."?`"${se?j:le?`${Te}/*`:Te}"`:"./";pe=`${_?"\u2714":"\u2718"} Searched: "${_||""}" in ${Ke.replaceAll("\\","/")} \u2192 ${me} Match${me===1?"":"es"}`}let V=115;process.stdout.isTTY&&(V=process.stdout.columns-5||120);let Z=Math.min(pe.length+4,V),re=`${pe.padEnd(Z-2).substring(0,Z-2)}`;yield{type:"visual_feedback",content:jt(`${Ne?`
747
- `:""}${re}
748
- `)},Ne=!1}if(p==="EmergencyRollback"){let{method:_}=J(N.args);if(_==="forceRevert"){let j=0;if(Se){let Z=Se.match(/Total\s*:\s*(\d+)/i);Z&&(j=parseInt(Z[1]))}let le=Se&&Se.startsWith("ERROR:")?"\u2718 Emergency Rollback Failed":`\u2714 Emergency Rollback \u2192 ${j} file${j===1?"":"s"} processed`,me=115;process.stdout.isTTY&&(me=process.stdout.columns-5||120);let Be=await s(),Ce=!1;Be&&(Ce=Be.trim().length>0);let pe=Math.min(le.length+4,me),V=`${le.padEnd(pe-2).substring(0,pe-2)}`;yield{type:"visual_feedback",content:jt(`${Ne?`
749
- `:""}${V}${Ce?"":`
750
- `}`)},Ne=!1}}if(p==="todo"){let{method:_,tasks:j,markDone:se}=J(N.args),le="",me=[],Be=Ce=>{if(!Ce)return[];let pe=Array.isArray(Ce)?Ce:[];if(pe.length===0&&typeof Ce=="string"){let V=Ce.trim();if(V.startsWith("[")&&V.endsWith("]")){let Z=V.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);Z?pe=Z.map(re=>re.slice(1,-1).replace(/\\(.)/g,"$1")):pe=V.slice(1,-1).split(",").map(re=>re.trim()).filter(Boolean)}else pe=Ce.split(`
751
- `)}return pe.filter(V=>String(V).trim()).map(V=>{let Z=String(V).trim();return Z.startsWith("- [")?Z.substring(6).trim():Z})};if(_==="create"?(le="\x1B[32m\u2192\x1B[0m Created Goals",me=Be(j).map(Ce=>`\x1B[90m\u25CB\x1B[0m ${Ce}`)):_==="append"?(le="\x1B[34m\u2795\x1B[0m Added New Goals",me=Be(j).map(Ce=>`\x1B[90m\u25CB\x1B[0m ${Ce}`)):_==="get"&&(le=se?"\x1B[36m\u21BB\x1B[0m Updated Goals":"\x1B[35m\u2022\x1B[0m Reviewed Goals",me=(Se||"").split(`
752
- `).slice(1).join(`
753
- `).split(`
754
- `).filter(pe=>pe.trim().startsWith("- [")).map(pe=>{let V=pe.trim(),Z=V.startsWith("- [x]");return`${Z?"\x1B[32m\u2714\x1B[0m":"\x1B[90m\u25CB\x1B[0m"} ${Z?"\x1B[90m":"\x1B[37m"}${V.substring(6).trim()}\x1B[0m`})),le&&me.length>0){let Ce=[`${le}`,...me.map(Z=>` ${Z}`)].join(`
755
- `),pe=await s(),V=!1;pe&&(V=pe.trim().length>0),yield{type:"visual_feedback",content:jt(`${Ne?`
756
- `:""}${Ce}${V?"":`
757
- `}`)},Ne=!1}}p==="exec_command"&&t.onExecEnd&&(await new Promise(_=>setTimeout(_,800)),t.onExecEnd());let cn=Se&&Se.startsWith("DENIED:");Se&&!Se.startsWith("ERROR:")&&!cn?(await Et("toolSuccess"),t.onToolResult&&t.onToolResult("success",p)):cn||(await Et("toolFailure"),t.onToolResult&&t.onToolResult("failure",p));let Pt=(Se||"").toString().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 conserve context.
758
- `));let dn;if(Pt.startsWith("[[SAME]]")){let j=Pt.replace(/^\[\[SAME\]\]\s*\r?\n?/,"").split(/\r?\n/),se=j.filter(me=>me.startsWith("SUCCESS:")||me.trim().startsWith("- Stats:"));dn=`[TOOL RESULT]: ${se.length>0?se.join(`
759
- `):j.slice(0,2).join(`
760
- `)}
761
- [SYSTEM NOTE]: Content verified and persisted to disk. Full preview omitted to conserve context.`}else dn=`[TOOL RESULT]: ${Pt}`;z.push({role:"user",text:dn,binaryPart:Bt}),zt=!0;let Ee=`[TOOL RESULT]: ${Se.replaceAll(`[[VERIFIED]]
762
- `,"").replaceAll(`
763
- [[/VERIFIED]]`,"")||""}`;(p==="view_file"||p==="web_scrape"||p==="file_map")&&(Ee=`[TOOL RESULT]: ${K} (Context Locked for UI Clarity)`),yield{type:"tool_result",content:Ee,aiContent:dn,binaryPart:Bt,toolName:p},p==="memory"&&Se.includes("SUCCESS")&&(yield{type:"memory_updated"}),Ge++}if(i==="Google"&&en&&Date.now()-Ko>=150){yield*En();let N=qn(en);for(let Q of N)yield Q;en="",Ko=Date.now()}}I.usageMetadata&&(an=I.usageMetadata),an&&(yield{type:"liveTokens",content:an.totalTokenCount})}if(ge&&(ge=!1,It?Ye+="</think>":(ce+="</think>",i==="Google"?en+="</think>":yield{type:"text",content:"</think>"})),It&&Ye.length>0){let I=0,te=Math.min(tt.length,Ye.length);for(let U=te;U>0;U--)if(tt.endsWith(Ye.substring(0,U))){I=U;break}let F=Ye.substring(I);if(F){let ye=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(tt)?F.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):F.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(ce+=ye,i==="Google")en+=ye;else{yield*En();let de=qn(ye);for(let ke of de)yield ke}}It=!1,Ye=""}if(yield*En(),St)break;let zn=(ce||"").trim(),pr=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(zn.toLowerCase())||/\[\[END\]\]/i.test(zn.toLowerCase()),yr=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(zn.toLowerCase()),xr=z.length>0||Mt!==null,qo=Vt(zn).trim(),br=/(\p{Emoji_Presentation}|\p{Extended_Pictographic})$/u.test(qo),wr=/([.!?"'*_`|\]\)”’~~]+|\s|`{3}|[\u200B-\u200D\uFEFF])$/u.test(qo.trim()),kr=/[.!?}"'`’“”]$|```$/s.test(qo)||wr||br;!pr&&!yr&&!xr&&zn.length>0,Qe=!0,await Et("agent",i)}catch(be){if(St){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
764
-
765
- \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(String(be).includes("Incomplete JSON segment at the end")){ge&&(ge=!1,It?Ye+="</think>":(ce+="</think>",yield{type:"text",content:"</think>"})),Qe=!0,await Et("agent",i);break}if(ge&&(ge=!1,It?Ye+="</think>":ce+="</think>"),It&&Ye.length>0){let Dt=0,_t=Math.min(tt.length,Ye.length);for(let Rt=_t;Rt>0;Rt--)if(tt.endsWith(Ye.substring(0,Rt))){Dt=Rt;break}let bt=Ye.substring(Dt);if(bt){let pt=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(tt)?bt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):bt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");pt&&(ce+=pt)}It=!1,Ye=""}let ne=be instanceof Error?(()=>{try{return JSON.parse(JSON.parse(be.message).error.message).error.message}catch{return String(be)}})():String(be),Ot=new Date().toLocaleString(),Ct=q.join(yn,"agent");Ie.existsSync(Ct)||Ie.mkdirSync(Ct,{recursive:!0}),Ie.appendFileSync(q.join(Ct,"error.log"),`ERROR [${Ot}]: ${ne}
766
-
767
- ----------------------------------------------------------------------
768
-
769
- `);let Tt=be.status||be.statusCode||be.code,qt=String(be).includes("replicas at capacity");if(!(Tt&&(Tt>=500&&Tt<600||Tt===408||Tt===429||qt)||!Tt&&(/status[ :]+(5\d\d|408|429)/i.test(String(be))||/code[ :]+(5\d\d|408|429)/i.test(String(be))||/(500|503|408|429)/.test(String(be))))){if(He<Qt-3)throw be;yield{type:"text",content:ne},yield{type:"status",content:"Error Occured"}}if(ce.trim().length>0||ze>1)if(ze<=Qt){ze++;let Dt=Math.min(1e3*Math.pow(2,ze-1),24e3);if(ce.trim().length>0){r.push({role:"agent",text:ce});let _t=`[system]
770
- - seamless continuation: resume immediately. pick up from last words with zero gap/disruption
771
- - no repetition: do not repeat any text already written
772
- - no re-think: do not restart or open <think> if reasoning already started. continue the thinking and close thinking block </think> before chat output
773
- - mid-tool safety: if cutoff was mid-tool call, restart that tool call from start
774
- - stealth: do not mention/apologize for cutoff [/system]`;z.length>0?z.forEach((bt,Rt)=>{Rt===z.length-1?r.push({...bt,text:`${bt.text}
775
-
776
- ${_t}`}):r.push(bt)}):r.push({role:"user",text:_t}),tt+=ce}for(let _t=Dt/1e3;_t>0&&!St;_t--)yield{type:"status",content:`Error Occured. Recovering Stream (${ze}/${Qt}) [Retrying in ${_t.toFixed(0)}s]...`},await new Promise(bt=>setTimeout(bt,1e3));yield{type:"status",content:"Error Occured. Recovering Stream..."}}else throw new Error(`Stream collapsed too many times. (Failed to resolve ${Qt} times)
777
- Error log can be found in \`/export logs\``);else if(He<=Qt){He++,ze=1,tt="";let Dt=Math.min(1e3*Math.pow(2,He-1),32e3),_t=.8+Math.random()*.4,bt=Math.round(Dt*_t);Sn=!0,yield{type:"status",content:`Trying to reach ${e} (${He}/${Qt}) [Retrying in ${(bt/1e3).toFixed(0)}s]`};for(let Rt=bt/1e3;Rt>0&&!St;Rt--)yield{type:"status",content:`Trying to reach ${e} (${He}/${Qt}) [Retrying in ${Rt.toFixed(0)}s]`},await new Promise(pt=>setTimeout(pt,1e3));yield{type:"status",content:`Trying to reach ${e}`}}else throw new Error(`Model ${e} cannot be reached. (Failed ${Qt} times)
778
- Error log can be found in \`/export logs\``)}}if(an){let ge=an.totalTokenCount||0,be=an.cachedContentTokenCount||0,ne=(an.candidatesTokenCount||0)+(i==="Google"&&an.thoughtsTokenCount||0);await Nt("tokens",ge,i,he),be>0&&await Nt("cachedTokens",be,i,he),ne>0&&await Nt("candidateTokens",ne,i,he),yield{type:"usage",content:an}}Ns.push(ce);let _n=Vt(ce),Jt=or(ce),Kn=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(Jt.toLowerCase())||/\[\[END\]\]/i.test(Jt.toLowerCase())||!0,hn=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(Jt.toLowerCase()),ma=Ge>0;yield{type:"status",content:"Thinking"};let ur=aa(ce,/(\[\s*(turn\s*:)?\s*(continue|finish)\s*\]|\[\[END\]\])/gi,"").trim(),An=(Kn||z.length===0)&&!vt&&!Zt&&!ln;if(An=z.length===0?An:!1,An=Tn||fo?!1:An,ce&&ce.trim().endsWith('")]')&&z.length===0&&(An=!1),An){let ge=Ns.join(`
779
- `),be=Vt(ge).trim();yield{type:"interactive_turn_finished",data:{agentText:y,fullAgentTextRaw:ge,history:[...r],needTitle:f}},r.length>0&&r[r.length-1].role==="agent"?r[r.length-1].text=be:r.push({role:"agent",text:be}),r.forEach(ne=>{if(ne.role==="user"&&ne.text&&(ne.text=ne.text.replace(/\n\[COMPILE ERROR\][\s\S]*?\[\/ERROR\]/g,""),ne.text=ne.text.replaceAll(`
780
-
781
- [system] user question. resolve this specific query within '[ANSWER] ... [/ANSWER]' concisely, naturally [/system]
782
- `,"").replaceAll(`[system] user question. resolve this specific query within '[ANSWER] ... [/ANSWER]' concisely, naturally
783
- **strictly follow thinking policy as high priority. do not start a response without <think>...</think>** [/system]
784
- `,"").replaceAll(`[system] **strictly follow thinking policy as high priority. do not start a response without <think>...</think>** [/system]
785
- `,"").replaceAll(/\n\[system\] WARNING, Turn Limit Impending: Step \d+\/\d+\. Wrap up quickly\/prompt user to continue & use \[\[END\]\] quickly\. \[\/system\]/g,""),ne.text=ne.text.replaceAll(/\n\[system\] File Changes:\n(?:\* .+ \(created|modified|deleted\)\n)*\[\/system\]/g,""),(i==="Mistral"||i==="Google"&&e?.toLowerCase().startsWith("gemma"))&&ne.text.startsWith("[TOOL RESULT]"))){let Ct=`
786
- [system] Tool result received. Analyze output and proceed with your turn [/system]`,Tt=`
787
- [system] Tool result received. Analyze output and proceed with your turn. **strictly follow thinking policy. do not start a response without <think>...</think>** [/system]`;ne.text=ne.text.replaceAll(Tt,"").replaceAll(Ct,"").trim()}}),yield{type:"status",content:"[end]"}}if(An)break;let gr=ur.trim()||"*Working...*";if(r.push({role:"agent",text:gr}),z.length>0||zt){if(z.length>0){let ge=z.map(qt=>qt.text).join(`
788
-
789
- `),Ot=(Vt(ce).replace(/\[{1,2}tool:[\s\S]*?\)\s*\]{1,2}/gi,"").match(/\[tool:/gi)||[]).length,Ct=z.length+Ot;if(z.length<Ct){ge+=`
790
-
791
- [system] Only ${z.length} out of ${Ct} attempted tool calls were executed. Verify proper structure compliance & try failed calls again [/system]`;let qt=Ct-z.length;for(let Fe=0;Fe<qt;Fe++)await Et("toolFailure")}let Tt=z.find(qt=>qt.binaryPart)?.binaryPart||null;r.push({role:"user",text:ge,binaryPart:Tt})}}else if(!St){let be=(ce.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/i,"").match(/\[tool:/gi)||[]).length;fo||Tn||be>0?(r.push({role:"user",text:`[system] Failed to execute ${be} tool${be>1?"s":""}. Verify proper structure compliance & try again [/system]`}),await Et("toolFailure"),yield{type:"visual_feedback",content:`
792
- ${jt("\u2718 Execution Error")}
793
- `}):(yield{type:"visual_feedback",content:`
794
- ${jt("\u2718 Loop Detected")}
795
- `},r.push({role:"user",text:`[system] ${Zt&&!vt?"Stuttering Detected by Internal System. Re-calibrate your response & proceed.":`${vt?" Over Thinking":" Loop"} Detected by Internal System${vt?" for current Effort Level":""}. ${vt?"If you have planned the task, prioritize execution/output":"If you have finished your task provide a simple summary and end"}`} [/system]`})),vt=!1,Zt=!1,ln=!1}d?.advanceRollback&&await Zn.recordTurnDelta(g,W+1,Yt),fo=Ge>0||zt}}catch(k){let E=(k instanceof Error?(()=>{try{return JSON.parse(JSON.parse(k.message).error.message).error.message}catch{return k.message||String(k)}})():String(k)).replace(/^(Error:\s*)+/i,""),B=new Date().toLocaleString(),H=q.join(yn,"agent");yield{type:"text",content:`
796
-
797
- \u2726 CRITICAL ERROR: ${E.includes("fetch failed")?"Failed to Connect. Check your Internet Connection or Wait a moment":E}
798
- \u2800`},Ie.existsSync(H)||Ie.mkdirSync(H,{recursive:!0}),Ie.appendFileSync(q.join(H,"error.log"),`CRITICAL ERROR [${B}]: ${k}
799
-
800
- ----------------------------------------------------------------------
801
-
802
- `),typeof flushGoogleBuffer=="function"&&(yield*flushGoogleBuffer()),yield{type:"tool_result",content:`ERROR: [INTERNAL CRITICAL] ${E}`}}finally{R&&(clearInterval(R),R=null),typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),await yo.commitTransaction(),d?.advanceRollback&&await Zn.cleanup(g),await vn()}yield{type:"status",content:null}},Qc=async(e,n,t=null,s=null,o=50,c=null,u=!1)=>{let a=await Qn(),b={...a,...n},g=process.env.SUBAGENT_MODEL?process.env.SUBAGENT_MODEL.trim():null,x=process.env.SUBAGENT_PROVIDER?process.env.SUBAGENT_PROVIDER.trim():null,d=new Date,m=`${d.getFullYear()}-${d.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(d.getDate()).padStart(2,"0")}, ${d.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}).replace(":","-")}`,l=(k=>{if(!k)return null;let r=k.toLowerCase();return r==="google"?"Google":r==="deepseek"?"DeepSeek":r==="openrouter"?"OpenRouter":r==="nvidia"?"NVIDIA":r==="mistral"?"Mistral":r==="ollama"?"Ollama":r==="crofai"||r==="crof"?"CrofAI":r==="inferx"?"InferX":r==="sensenova"?"SenseNova":r==="poolside"?"Poolside":r==="9router"||r==="9Router"?"9router":r==="aihubmix"||r==="aihub"?"AIHubMix":null})(x),w=b?.systemSettings?.CustomSubAgent?b?.systemSettings?.SubAgentModel:null,h=b?.systemSettings?.CustomSubAgent?b?.systemSettings?.SubAgentProvider:null,A=null;if(w==="ENV"?(A=g,g&&l&&(b.aiProvider=l)):w&&w!=="Default"?(A=w,h&&(b.aiProvider=h)):g&&l&&(b.aiProvider=l),b.aiProvider){let k=await Qo(b.aiProvider);k&&(b.apiKey=k)}let M=k=>{if(!k||typeof k!="string")return{allowed:!0};let r=[/rm\s+-[rf]{1,2}\s+[\/*.]/i,/rmdir\s+\/[sq]/i,/del\s+\/[fsq]/i,/\bformat\b\s+[a-z]:/i,/mkfs/i,/dd\s+if=/i,/\b(shutdown|reboot|poweroff|init\s+0|init\s+6)\b/i,/chmod\s+(-R\s+)?777\s+[\/*.]/i,/chown\s+(-R\s+)?root/i,/git\s+push\s+.*--force/i,/git\s+clean\s+-fdx/i,/\bsudo\s+su\b/i,/\bsu\s+-\b/i];for(let E of r)if(E.test(k))return{allowed:!1,reason:`Blocked potentially destructive or unsafe command pattern: "${E.source}"`};return{allowed:!0}},S=t||A||n?.modelName||n?.activeModel||a.activeModel,v=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",O=`-- TOOL DEFINITIONS (path = relative to CWD, path separator: '/') --
803
- You cant execute tools. Instead, output in chat the exact string [tool:functions.ToolName(arg1="value1")] & wait for system response \u2190 no exception, tool:functions must
804
- Tool Rules:
805
- - Mandatorily JSON escape literal sequences (backslash: \\\\, newLine: \\ n, quote: \\")
806
- - Same file, multiple edits? ONE PatchFile (\u226415 blocks)
807
- - Need text or huge file? CodeSearch > Full Read
808
- - Avoid unnecessary large file chunk reads
809
- - Dont hallucinate tool results, verify, fix errors
810
- - Stuck on syntax error? Tell user > waste time
811
- - ONLY valid tools defined below are allowed
812
-
813
- # Provided Tools
814
- **Communication Tools**
815
- - AskUser(question=string, optionA="title::description", ...MAX4). Ambiguity, path divergence, security risk
816
- ${u?"- AskMain(question=string). Communicate with PARENT/MAIN AGENT. When clarification/decision is needed for a task":""}
817
-
818
- **Web Tools**
819
- - WebSearch(query=string, aiMode?=bool, limit?=int[3..10]). Proactive use for unknown/latest info. aiMode: exclude limit
820
- - WebScrape(url=string). Proactive use for specific webpage/docs
821
-
822
- **Workspace Tools**
823
- - CodeSearch(keyword=string, path?="dir/file/glob/regex, inclusion/exclusion ;-separated", fuzzy?=bool, regex?=bool:auto). Find definitions, logic, relevant code, standard junk auto-excluded
824
- - ReadFolder(path=string, recurse?=int[1..3]). Minimize recursion
825
- - ReadFile(path=string, startLine?=int, endLine?=int)
826
- - PatchFile(path=string, allowMultiple?=bool, searchContent1="string match OR ^LINE:start..end$", newContent1=string, ...MAX15). Small searchString. Line Ranges: ^LINE:...$ syntax, must for large blocks/escape sequences
827
- - WriteFile(path=string, content=string). Creates/Overwrites. File Exist? PatchFile > WriteFile
828
- - Run(command=string). Runs ${v==="Windows"?js()?"powershell":"windows CMD":"bash"} command. Destructive command \u2192 Ask user`.trim(),T=`=== START SYSTEM PROMPT ===
829
- Identity: FluxFlow subagent helping the main Agent
830
- Your task is: "${e}"
831
-
832
- -- THINKING GUIDANCE --
833
- NO EXPLICIT THINKING REQUIRED. FOCUS ON TASK COMPLETION
834
- Main focus: tools and task, not chatting
835
- On completion, provide a detailed summary in Tables/Markdown Format with file modified info. If any task failed report back in detail
836
-
837
- CWD: ${process.cwd()}
838
-
839
- ${O.trimEnd()}
840
-
841
- Current Time: ${m}
842
- === END SYSTEM PROMPT ===`,f=[{role:"user",text:`Complete this task: ${e}`}],y=0,R="";for(;y<o;){if(St){if(n?.taskId&&typeof Gt<"u"){let D=Gt.find(L=>L.id===n.taskId);D&&(D.status="cancelled")}throw c&&c("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}if(n?.taskId&&typeof Gt<"u"){let D=Gt.find(L=>L.id===n.taskId);if(D&&D.status==="cancelled")throw c&&c("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}let k=f.map(D=>({role:D.role==="user"?"user":"model",parts:[{text:D.text}]}));c&&c(`[Subagent Turn ${y+1}]...`);let E=(await Ho(b,S,k,T,"Fast")).text||"",B=Vt(E).trim();R=B,c&&c(`[Subagent Response]
843
- ${B}
844
- `),f.push({role:"agent",text:B});let H=Go(B);if(H.length===0)break;let $=H.filter(D=>D.toolName.toLowerCase()==="askmain"||D.toolName.toLowerCase()==="ask_main"),Y=!1,ue="";for(let D of H){if(St){if(n?.taskId&&typeof Gt<"u"){let C=Gt.find(P=>P.id===n.taskId);C&&(C.status="cancelled")}throw new Error("Subagent task was cancelled.")}if(n?.taskId&&typeof Gt<"u"){let C=Gt.find(P=>P.id===n.taskId);if(C&&C.status==="cancelled")throw new Error("Subagent task was cancelled.")}let L=D.toolName.toLowerCase();if(L==="askuser"&&(L="ask"),L==="askmain"||L==="ask_main"){if(Y)continue;Y=!0;let C="";if($.length===1?C=J($[0].args).question||$[0].args:C=$.map((P,ee)=>{let X=J(P.args);return`Q${ee+1}: ${X.question||P.args}`}).join(`
845
- `),n.onAskMain){c&&c(`[Executing Tool] AskMain("${C}")...`);let P=await n.onAskMain(C);c&&c(`[Tool Result]
846
- Answer from Main Agent: ${P}
847
- `),ue+=`[TOOL RESULT for AskMain]: Answer from Main Agent: ${P}
848
-
849
- `,await Et("toolSuccess")}else ue+=`[TOOL RESULT for AskMain]: ERROR: Main agent communication channel not available.
850
-
851
- `;continue}if(!(s?s.some(C=>C.toLowerCase()===L):!0)){let C=`ERROR: Tool [${D.toolName}] is not in the allowed tools list for this subagent.`;c&&c(`[Blocked Tool Call] ${D.toolName} - not allowed
852
- `),ue+=`${C}
853
-
854
- `;continue}if(L==="exec_command"||L==="execcommand"||L==="run"){let C=J(D.args).command||"",P=M(C);if(!P.allowed){let ee=`ERROR: [SECURITY RESTRICTION] Subagent execution blocked command: ${P.reason}`;c&&c(`[Blocked Command] ${C} - ${P.reason}
855
- `),ue+=`${ee}
856
-
857
- `;continue}}let Pe="";if(L==="web_search"||L==="websearch")Pe=`\u2714 \x1B[95mSearched\x1B[0m: ${J(D.args).query||""}`;else if(L==="web_scrape"||L==="webscrape")Pe=`\u2714 \x1B[95mScraped\x1B[0m: ${J(D.args).url||""}`;else if(L==="search_keyword"||L==="searchkeyword"||L==="codesearch"||L==="code_search"){let C=J(D.args),P=C.keyword||"",ee=C.path||"";Pe=`${P?"\u2714":"\u2718"} \x1B[95mSearched\x1B[0m: ${P||"No Query"}${ee?` \u2192 ${ee.replaceAll("\\","/")}`:""}`}else if(L==="view_file"||L==="viewfile"||L==="readfile")Pe=`\u2714 \x1B[95mRead\x1B[0m: ${(J(D.args).path||"").replaceAll("\\","/")}`;else if(L==="list_files"||L==="read_folder"||L==="readfolder"){let C=J(D.args).path||null,P=J(D.args).recurse||0;Pe=`${C?"\u2714":"\u2718"} \x1B[95mBrowsed\x1B[0m: ${C?`${C.replaceAll("\\","/")}${P>0?`${C.endsWith("/")?`*${P}`:`/*${P}`}`:`${C.endsWith("/")?"":"/"}`}`:""}`}else if(L==="write_file"||L==="writefile"){let C=J(D.args).path||null;Pe=`${C?"\u2714":"\u2718"} \x1B[95mCreated\x1B[0m: ${C?`${C.replaceAll("\\","/")}`:"No File Changes"}`}else if(L==="update_file"||L==="updatefile"||L==="patchfile"||L==="patch_file"||L==="patchfile"||L==="updatefile"){let C=J(D.args).path||null,P=J(D.args).content||null;Pe=`${C?"\u2714":"\u2718"} \x1B[95mEdited\x1B[0m: ${C?`${C.replaceAll("\\","/")}`:"No File Changes"}`}else if(L==="exec_command"||L==="execcommand"||L==="run"){let C=J(D.args).command||null;Pe=`${C?"\u2714":"\u2718"} \x1B[95mExecuted\x1B[0m: ${C?C.slice(0,100)+(C.length>100?"...":""):"No Command"}`}else if(L==="file_map"||L==="filemap"){let C=J(D.args).path||"";Pe=`${C?"\u2714":"\u2718"} \x1B[95mIndexed\x1B[0m: ${C?`${C.replaceAll("\\","/")}`:"File Not Found"}`}else if(L==="await"){let{time:C}=J(D.args),P=parseFloat(C)||0;P<10&&(P=10),P>180&&(P=180),Pe=`\u2714 \x1B[95mAwaiting\x1B[0m \u2192 ${(X=>{if(X>=60){let it=Math.floor(X/60),De=X%60;return`${it}m${De>0?` ${De}s`:""}`}return`${X}s`})(P)}`}else{let C=As[L]||D.toolName,P=Dn(L,D.args);Pe=`\u2714 \x1B[95m${C}\x1B[0m${P?`: ${P}`:""}`}n.onVisualFeedback&&Pe&&n.onVisualFeedback(Pe),c&&c(`[Executing Tool] ${D.toolName}(${D.args})...`);try{let C=await io(D.toolName,D.args,{...n,mode:"Flux"});if(c&&c(`[Tool Result]
858
- ${C}
859
- `),ue+=`[TOOL RESULT for ${D.toolName}]: ${C}
860
-
861
- `,await Et("toolSuccess"),L==="patchfile"||L==="update_file"||L==="updatefile"||L==="patch_file"){if(C){let P=C.split(`
862
- `),ee=0,X=0,it=!1;for(let De of P){if(De.includes("[DIFF_START]")){it=!0;continue}if(De.includes("[DIFF_END]")){it=!1;continue}it&&(/^\+\d+/.test(De)?ee++:/^\-\d+/.test(De)&&X++)}(ee>0||X>0)&&(await Nt("linesAdded",ee),await Nt("linesRemoved",X))}}else if((L==="writefile"||L==="write_file")&&C){let P=C.match(/- Stats: \[(\d+) lines/),ee=P?parseInt(P[1]):0,X=0;if(C.includes("Old File contents:")){let it=!1;for(let De of C.split(`
863
- `)){if(De.includes("Old File contents:")){it=!0;continue}it&&(De.trim()===""?it=!1:/^\d+ \|/.test(De)&&X++)}}(ee>0||X>0)&&(await Nt("linesAdded",ee),await Nt("linesRemoved",X))}}catch(C){let P=`ERROR: Execution failed for [${D.toolName}]: ${C.message}`;c&&c(`[Tool Error] ${P}
864
- `),ue+=`${P}
865
-
866
- `,await Et("toolFailure")}}let st="";if(n?.taskId&&typeof Gt<"u"){let D=Gt.find(L=>L.id===n.taskId);if(D&&D.pendingSteerMessages&&D.pendingSteerMessages.length>0){let L=[...D.pendingSteerMessages];D.pendingSteerMessages=[];for(let we of L)st+=`
867
-
868
- [STEERING INSTRUCTION FROM MAIN AGENT]: ${we}`,c&&c(`[Subagent Steered] ${we}`)}}let Oe=(ue.trim()+st).trim();f.push({role:"user",text:Oe}),y++}return R};export{ro as a,Vi as b,xl as c,bl as d,ll as e,cl as f,Sl as g,Ro as h,Tl as i,Qr as j,Vc as k,Zr as l,ea as m,_s as n,Vt as o,nr as p,sa as q,Yc as r,Kc as s,Cs as t,qc as u,zc as v,ua as w,Jc as x,Xc as y,Qc as z};