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