fluxflow-cli 4.36.5 → 4.37.1

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