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