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