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