fluxflow-cli 4.16.17 → 4.17.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.
@@ -1,5 +1,5 @@
1
- import{a as io}from"./chunk-VCF6JVQV.js";import{a as Kt}from"./chunk-56EJGQU3.js";import{a as Ss,h as Ti}from"./chunk-KRRJNFBF.js";import{a as Si}from"./chunk-UYHPCXNG.js";import{c as ws,g as yi,h as xi,i as bi,m as Ts}from"./chunk-QA3IBTCI.js";import{a as Mo}from"./chunk-KFM2OZWJ.js";import{b as bs}from"./chunk-72RYQ5W7.js";import{e as Ct,g as Bt,i as ks,j as pi}from"./chunk-WKHYRBBK.js";import{g as gt,h as Ro,k as ue,l as so}from"./chunk-AAPXJU65.js";import{c as Et,d as Jn}from"./chunk-SIINYZWE.js";import{a as ki,c as wi}from"./chunk-KBOLQV47.js";import{a as tn,d as vn,e as Eo,j as Bn,k as Co,l as ys,q as xs,u as vo}from"./chunk-FDNLMLIM.js";import{a as oe}from"./chunk-Y5JU726N.js";import{GoogleGenAI as Hr,ThinkingLevel as Ze,HarmBlockThreshold as In,HarmCategory as On}from"@google/genai";var _i=(e=!0,t=!0)=>`
2
- To use tools, must output exactly '[tool:functions.ToolName(arg1="value1")]' structured string in chat response \u2190 no exception
1
+ import{a as io}from"./chunk-VCF6JVQV.js";import{a as Kt}from"./chunk-56EJGQU3.js";import{a as Ss,h as Ti}from"./chunk-KRRJNFBF.js";import{a as Si}from"./chunk-X3ZZM2GL.js";import{c as ws,g as yi,h as xi,i as bi,m as Ts}from"./chunk-ZSVBC2ZI.js";import{a as Mo}from"./chunk-KFM2OZWJ.js";import{b as bs}from"./chunk-72RYQ5W7.js";import{e as Ct,g as Bt,i as ks,j as pi}from"./chunk-WKHYRBBK.js";import{g as gt,h as Ro,k as ue,l as so}from"./chunk-AAPXJU65.js";import{c as Et,d as Jn}from"./chunk-SIINYZWE.js";import{a as ki,c as wi}from"./chunk-HYGK7YDY.js";import{a as tn,d as vn,e as Eo,j as Bn,k as Co,l as ys,q as xs,u as vo}from"./chunk-FDNLMLIM.js";import{a as oe}from"./chunk-Y5JU726N.js";import{GoogleGenAI as Hr,ThinkingLevel as Ze,HarmBlockThreshold as In,HarmCategory as On}from"@google/genai";var _i=(e=!0,t=!0)=>`
2
+ To use tools, must output exactly '[tool:ToolName(arg1="value1")]' structured string in chat response \u2190 no exception
3
3
 
4
4
  -- Chat Management Tools --
5
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
@@ -523,7 +523,7 @@ ${Xi?"":`${n==="Flux"?"Stepwise Execution, Run Automated Tests. Task Completion"
523
523
  - Date: ${P}`:""}${o?`
524
524
  - Use relative time reference eg. few mins ago
525
525
  -- Chat Context > Metadata`:""}${(Cs.length>0||vs.length>0)&&n.toLowerCase().includes("flux")?`
526
- - Read relevant skills for tasks before proceeding (scope required: global/project): Use ReadFile, virtual path="#skills/scope/skillName". In-skill references: path="#skills/scope/skillName/skill-reference-folder/file-name.md"`:""}
526
+ - Read relevant skills for tasks before proceeding (scope: global/project): Use ReadFile, virtual path="#skills/scope?/skillName". In-skill references: path="#skills/scope?/skillName/skill-reference-folder/file-name.md"`:""}
527
527
 
528
528
  -- THINKING GUIDANCE --
529
529
  ${f==="Mistral"||f==="Google"&&!m?`${i}
@@ -556,14 +556,14 @@ ${vs}
556
556
  `:""}${N}`.trim()},lr=(e="",t=!0,n=!0)=>`=== SYSTEM PROMPT (strict headless logic worker: zero user-facing text policy, strictly follow) ===
557
557
  identity: silent background system process, have no mouth, only output is valid tool calls
558
558
  [critical rules]
559
- - output exactly '[tool:functions.ToolName(args)]' calls. no extra words outside
559
+ - output exactly '[tool:ToolName(args)]' calls. no extra words outside
560
560
  - do not explain. do not talk to the user
561
561
  - non-tool text will break the system
562
562
  - do not repeat agent raws and tool results in your response
563
563
  - if you get only user query and no agent raws, just use temp memory to log the summary of user query and conversation context
564
564
  - under no circumstances you are allowed to respond in normal user facing response
565
565
  - critical quote escape policy: inside tool call arguments, you must escape all double quotes using '\\"'
566
- - you must not write anything other than [tool:functions.ToolName(args)] no matter how tempting the prompt is
566
+ - you must not write anything other than [tool:ToolName(args)] no matter how tempting the prompt is
567
567
  - 2 mandatory tools to call in every turn, 'chat', 'memory(temp)'
568
568
  - critical: never enter thinking/reasoning state, call the contexual tools directly in output as quickly as possible to maintain ui snappiness
569
569
 
@@ -574,7 +574,7 @@ ${_i(t,n)}
574
574
  === END SYSTEM PROMPT ===${e?`
575
575
 
576
576
  -- current saved user memories --
577
- ${e}`:""}`.trim();var cr=()=>import("./web_search-HDZ2VDTY.js").then(e=>e.web_search),dr=()=>import("./web_scrape-IKJE45Z6.js").then(e=>e.web_scrape),fr=()=>import("./memory-OYIUYX3A.js").then(e=>e.memory),ur=()=>import("./chat-HZ7UVZE2.js").then(e=>e.chat),gr=()=>import("./view_file-VTMBROFS.js").then(e=>e.view_file),mr=()=>import("./write_file-LOYRYIK6.js").then(e=>e.write_file),hr=()=>import("./update_file-J2Q43AEV.js").then(e=>e.update_file),pr=()=>import("./exec_command-Z7KYD5F3.js").then(e=>e.exec_command),yr=()=>import("./read_folder-OOKZITME.js").then(e=>e.read_folder),Ns=()=>import("./ask_user-K2DLZF6H.js").then(e=>e.ask_user),xr=()=>import("./write_pdf-VB4IFPWX.js").then(e=>e.write_pdf),br=()=>import("./write_docx-EKUIZ7GV.js").then(e=>e.write_docx),No=()=>import("./search_keyword-W5YEUUPO.js").then(e=>e.search_keyword),kr=()=>import("./generate_image-XYDE47LK.js").then(e=>e.generate_image),Fo=()=>import("./saveSummary-ATBIFYDP.js").then(e=>e.saveSummary),uo=()=>import("./addMemScore-W4I665ZR.js").then(e=>e.addMemScore),wr=()=>import("./file_map-5KY2ADZW.js").then(e=>e.file_map),Bo=()=>import("./todo-SJLJJLVZ.js").then(e=>e.todo),Tr=()=>import("./invokeSync-UKWAPFK4.js").then(e=>e.invokeSync),ba=()=>import("./invoke-7UHFQOHF.js").then(e=>e.invoke),Sr=()=>import("./getProgress-LI4U6UJU.js").then(e=>e.getProgress),ka=()=>import("./cancel-7IMADALP.js").then(e=>e.cancel),_r=()=>import("./emergency_rollback-EPJPKANN.js").then(e=>e.emergency_rollback),go=()=>import("./awaitSubagent-JTUSJDKD.js").then(e=>e.awaitSubagent),mo=()=>import("./answerSubagent-JUVFNLE5.js").then(e=>e.answerSubagent),Uo=()=>import("./steerSubagent-L2JVT4QN.js").then(e=>e.steerSubagent),Wo=()=>import("./computer_action-WTHH7RBB.js").then(e=>e.computer_action),Ar=()=>import("./click-G6RRSFVC.js").then(e=>e.click),Er=()=>import("./drag-ZGH2MMP7.js").then(e=>e.drag),Cr=()=>import("./scroll-GHXES2II.js").then(e=>e.scroll),Fs=()=>import("./keyboard_typing-CK3KVAWM.js").then(e=>e.keyboard_typing),Bs=()=>import("./key_press-M5QNCIPH.js").then(e=>e.key_press),Us=()=>import("./recapture_screen-5FKLOHJL.js").then(e=>e.recapture_screen),wa={web_search:cr,web_scrape:dr,memory:fr,chat:ur,view_file:gr,write_file:mr,update_file:hr,exec_command:pr,read_folder:yr,write_pdf:xr,write_docx:br,search_keyword:No,generate_image:kr,saveSummary:Fo,addMemScore:uo,file_map:wr,todo:Bo,Todo:Bo,goal:Bo,Goal:Bo,invokeSync:Tr,invoke:ba,getProgress:Sr,cancel:ka,awaitSubagent:go,answerSubagent:mo,steerSubagent:Uo,computer_action:Wo,computer_use:Wo,ComputerAction:Wo,ComputerUse:Wo,click:Ar,Click:Ar,drag:Er,Drag:Er,scroll:Cr,Scroll:Cr,keyboard_typing:Fs,KeyboardTyping:Fs,keyboardtyping:Fs,key_press:Bs,KeyPress:Bs,keypress:Bs,recapture_screen:Us,RecaptureScreen:Us,recapturescreen:Us,invoke_sync:Tr,get_progress:Sr,await_subagent:go,answer_subagent:mo,steer_subagent:Uo,steer:Uo,Steer:Uo,ask:Ns,Ask:Ns,AskUser:Ns,WebSearch:cr,WebScrape:dr,ReadFile:gr,ReadFolder:yr,WriteFile:mr,PatchFile:hr,WritePDF:xr,WriteDoc:br,Run:pr,SearchKeyword:No,CodeSearch:No,code_search:No,Memory:fr,Chat:ur,GenerateImage:kr,saveSumary:Fo,SaveSummary:Fo,SaveSumary:Fo,add_mem_score:uo,AddMemScore:uo,addMemoryScore:uo,AddMemoryScore:uo,FileMap:wr,answer:mo,Answer:mo,AnswerSubagent:mo,await:go,Await:go,AwaitSubagent:go,EmergencyRollback:_r,emergency_rollback:_r},ho=async(e,t,n={})=>{let s=n.mode?n.mode.toLowerCase():"flux",o=e.toLowerCase(),f=["memory","chat","savesummary","addmemscore","add_mem_score","ask","web_search","web_scrape","await"].some(u=>o.includes(u))||o==="ask",m=["click","drag","scroll","keyboardtyping","keyboard_typing","keypress","key_press","recapturescreen","recapture_screen","computer"].some(u=>o.includes(u));if(!f){if(s==="flow"){if(!(o.includes("write_pdf")||o.includes("write_docx")||o.includes("generate_image")))return`ERROR: Tool [${e}] is a Workspace Tool and NOT available in Flow mode. Tell user to switch (\`/mode flux\`) to use this tool.`}else if(s==="icu"){if(!m)return`ERROR: Tool [${e}] is not available in Computer Use mode. ICU mode only supports Computer Use tools (Click, Drag, Scroll, KeyboardTyping, KeyPress, RecaptureScreen).`}else if(o.includes("write_pdf")||o.includes("write_docx")||o.includes("generate_image"))return`ERROR: Tool [${e}] is not available in ${n.mode||"Flux"} mode. Tell user to switch (\`/mode flow\`) for document generation.`}let g=wa[e];if(!g)return`ERROR: Tool [${e}] not found in registry.`;try{return await(await g())(t,n)}catch(u){let h=u instanceof Error?u.message:String(u);return`ERROR: Execution failed for [${e}]: ${h}`}};import ee from"path";import Ge from"fs";import Ta from"gradient-string";var Ws=["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 vr=[{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"]}],po={Dark:{id:"Dark",name:"Dark (Default)",text:"white",textMuted:"gray",textDim:"grey",textInverted:"black",textExclusive:"#B5B8D9",textMutedExclusive:"#D4DEE7",border:"white",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:"#1e1e1e",highlightBg:"#2a2a2a",activeBg:"#3a3a3a",inputBg:"#555555",inputBorder:"#555555",inputText:"white",inputPlaceholder:"#cccccc",inputPrompt:"white",codeBg:"#1a1a1a",codeBorder:"#444444",userMsgBg:"#444444",userMsgBorder:"#444444",userMsgText:"white",diffRemovalBg:"#250808",diffAdditionBg:"#072410",diffRemovalText:"#885555",diffAdditionText:"#558866",diffRemovalHighlightColor:"#ff3333",diffRemovalHighlightBg:"#5a1818",diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:"#185a25",diffRemovalNum:"#d96868",diffAdditionNum:"#68d98c",diffRemovalPrefix:"#ff4d4d",diffAdditionPrefix:"#4dff88",primary:"white",secondary:"cyan",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"white",statusOff:"gray",logoTextAnsi:"\x1B[1;37m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#0077ff","#ff00ff"]},Light:{id:"Light",name:"Light",text:"black",textMuted:"gray",textDim:"grey",textInverted:"white",border:"black",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:"#e5e5e5",highlightBg:"#d4d4d4",activeBg:"#c0c0c0",inputBg:"#d0d0d0",inputBorder:"#d0d0d0",inputText:"black",inputPlaceholder:"#555555",inputPrompt:"black",codeBg:"#e8e8e8",codeBorder:"#b0b0b0",userMsgBg:"#d0d0d0",userMsgBorder:"#d0d0d0",userMsgText:"black",diffRemovalBg:"#fce8e8",diffAdditionBg:"#e6f9e6",diffRemovalText:"#661111",diffAdditionText:"#115511",diffRemovalHighlightColor:"#440000",diffRemovalHighlightBg:"#f8b4b4",diffAdditionHighlightColor:"#003300",diffAdditionHighlightBg:"#a6ebad",diffRemovalNum:"#c02020",diffAdditionNum:"#188028",diffRemovalPrefix:"#d01010",diffAdditionPrefix:"#109020",primary:"black",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"black",statusOff:"gray",logoTextAnsi:"\x1B[1;30m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#0077ff","#ff00ff"]},"GitHub Dark":{id:"GitHub Dark",name:"GitHub Dark",text:"#c9d1d9",textMuted:"#8b949e",textDim:"#6e7681",textInverted:"#0d1117",border:"#30363d",borderMuted:"#30363d",borderDim:"#21262d",bg:void 0,cardBg:"#161b22",highlightBg:"#21262d",activeBg:"#30363d",inputBg:"#21262d",inputBorder:"#21262d",inputText:"#c9d1d9",inputPlaceholder:"#8b949e",inputPrompt:"#58a6ff",codeBg:"#0d1117",codeBorder:"#30363d",userMsgBg:"#21262d",userMsgBorder:"#21262d",userMsgText:"#c9d1d9",diffRemovalBg:"#3c1e1e",diffAdditionBg:"#11381e",diffRemovalText:"#f85149",diffAdditionText:"#3fb950",diffRemovalHighlightColor:"#ff7b72",diffRemovalHighlightBg:"#701c1c",diffAdditionHighlightColor:"#56d364",diffAdditionHighlightBg:"#116329",diffRemovalNum:"#f85149",diffAdditionNum:"#3fb950",diffRemovalPrefix:"#f85149",diffAdditionPrefix:"#3fb950",primary:"#c9d1d9",secondary:"#58a6ff",accent:"#bc8cff",success:"#3fb950",warning:"#d29922",danger:"#f85149",info:"#58a6ff",statusOn:"#58a6ff",statusOff:"#8b949e",logoTextAnsi:"\x1B[1;36m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#2ea043","#56d364"]},"GitHub Light":{id:"GitHub Light",name:"GitHub Light",text:"#24292f",textMuted:"#57606a",textDim:"#6e7781",textInverted:"#ffffff",border:"#d0d7de",borderMuted:"#d0d7de",borderDim:"#e1e4e8",bg:void 0,cardBg:"#f6f8fa",highlightBg:"#eaeef2",activeBg:"#d0d7de",inputBg:"#eaeef2",inputBorder:"#eaeef2",inputText:"#24292f",inputPlaceholder:"#57606a",inputPrompt:"#0969da",codeBg:"#ffffff",codeBorder:"#d0d7de",userMsgBg:"#eaeef2",userMsgBorder:"#eaeef2",userMsgText:"#24292f",diffRemovalBg:"#ffebe9",diffAdditionBg:"#e6ffec",diffRemovalText:"#cf222e",diffAdditionText:"#1a7f37",diffRemovalHighlightColor:"#82071e",diffRemovalHighlightBg:"#ffc1c0",diffAdditionHighlightColor:"#116329",diffAdditionHighlightBg:"#acf2bd",diffRemovalNum:"#cf222e",diffAdditionNum:"#1a7f37",diffRemovalPrefix:"#cf222e",diffAdditionPrefix:"#1a7f37",primary:"#24292f",secondary:"#0969da",accent:"#8250df",success:"#1a7f37",warning:"#9a6700",danger:"#cf222e",info:"#0969da",statusOn:"#0969da",statusOff:"#57606a",logoTextAnsi:"\x1B[1;34m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#1a7f37","#2da44e"]},"Transparent Dark":{id:"Transparent Dark",name:"Transparent Dark",text:"white",textMuted:"gray",textDim:"grey",textInverted:"black",border:"gray",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:void 0,highlightBg:"#2a2a2a",activeBg:"#3a3a3a",inputBg:"#555555",inputBorder:"#555555",inputText:"white",inputPlaceholder:"#cccccc",inputPrompt:"white",codeBg:void 0,codeBorder:"gray",userMsgBg:"#555555",userMsgBorder:"#555555",userMsgText:"white",diffRemovalBg:void 0,diffAdditionBg:void 0,diffRemovalText:"#ff6666",diffAdditionText:"#66ff66",diffRemovalHighlightColor:"#ff3333",diffRemovalHighlightBg:void 0,diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:void 0,diffRemovalNum:"#ff6666",diffAdditionNum:"#66ff66",diffRemovalPrefix:"#ff4d4d",diffAdditionPrefix:"#4dff88",primary:"white",secondary:"cyan",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"white",statusOff:"gray",logoTextAnsi:"\x1B[1;37m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#0077ff","#ff00ff"]},"Transparent Light":{id:"Transparent Light",name:"Transparent Light",text:"black",textMuted:"gray",textDim:"grey",textInverted:"white",border:"gray",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:void 0,highlightBg:"#d4d4d4",activeBg:"#c0c0c0",inputBg:"#d0d0d0",inputBorder:"#d0d0d0",inputText:"black",inputPlaceholder:"#555555",inputPrompt:"black",codeBg:void 0,codeBorder:"gray",userMsgBg:"#d0d0d0",userMsgBorder:"#d0d0d0",userMsgText:"black",diffRemovalBg:void 0,diffAdditionBg:void 0,diffRemovalText:"#c02020",diffAdditionText:"#188028",diffRemovalHighlightColor:"#800000",diffRemovalHighlightBg:void 0,diffAdditionHighlightColor:"#004000",diffAdditionHighlightBg:void 0,diffRemovalNum:"#c02020",diffAdditionNum:"#188028",diffRemovalPrefix:"#d01010",diffAdditionPrefix:"#109020",primary:"black",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"black",statusOff:"gray",logoTextAnsi:"\x1B[1;30m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#0077ff","#ff00ff"]},"Synthwave 84":{id:"Synthwave 84",name:"Synthwave 84",text:"#fdfdfd",textMuted:"#a08eb7",textDim:"#705c8a",textInverted:"#1a1025",textExclusive:"#e3dcf0",textMutedExclusive:"#b9abc9",border:"#fc28a8",borderMuted:"#a21568",borderDim:"#5c0a3a",bg:void 0,cardBg:"#261b38",highlightBg:"#35254d",activeBg:"#4c3570",inputBg:"#35254d",inputBorder:"#35254d",inputText:"#fdfdfd",inputPlaceholder:"#a08eb7",inputPrompt:"#03e8fc",codeBg:"#1e142b",codeBorder:"#a21568",userMsgBg:"#35254d",userMsgBorder:"#35254d",userMsgText:"#fdfdfd",diffRemovalBg:"#471434",diffAdditionBg:"#144743",diffRemovalText:"#ff4081",diffAdditionText:"#00e5ff",diffRemovalHighlightColor:"#ff79a1",diffRemovalHighlightBg:"#6b1e4e",diffAdditionHighlightColor:"#66f5ff",diffAdditionHighlightBg:"#1e6b65",diffRemovalNum:"#ff4081",diffAdditionNum:"#00e5ff",diffRemovalPrefix:"#ff79a1",diffAdditionPrefix:"#66f5ff",primary:"#fdfdfd",secondary:"#03e8fc",accent:"#fc28a8",success:"#00e5ff",warning:"#ffc107",danger:"#ff4081",info:"#b388ff",statusOn:"#03e8fc",statusOff:"#a08eb7",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#fc28a8","#03e8fc"]},"Forest Sprite":{id:"Forest Sprite",name:"Forest Sprite",text:"#d6e6d1",textMuted:"#95b38d",textDim:"#628059",textInverted:"#161c14",textExclusive:"#eaf2e8",textMutedExclusive:"#a9c7a2",border:"#74a862",borderMuted:"#477038",borderDim:"#2b4720",bg:void 0,cardBg:"#1f291c",highlightBg:"#2a3826",activeBg:"#3a4d35",inputBg:"#2a3826",inputBorder:"#2a3826",inputText:"#d6e6d1",inputPlaceholder:"#95b38d",inputPrompt:"#8feb73",codeBg:"#161e14",codeBorder:"#477038",userMsgBg:"#2a3826",userMsgBorder:"#2a3826",userMsgText:"#d6e6d1",diffRemovalBg:"#3b231c",diffAdditionBg:"#203b1c",diffRemovalText:"#db6242",diffAdditionText:"#59cc3f",diffRemovalHighlightColor:"#f0896c",diffRemovalHighlightBg:"#5c362a",diffAdditionHighlightColor:"#80e368",diffAdditionHighlightBg:"#305929",diffRemovalNum:"#db6242",diffAdditionNum:"#59cc3f",diffRemovalPrefix:"#f0896c",diffAdditionPrefix:"#80e368",primary:"#d6e6d1",secondary:"#8feb73",accent:"#e69835",success:"#59cc3f",warning:"#e69835",danger:"#db6242",info:"#73b4eb",statusOn:"#8feb73",statusOff:"#95b38d",logoTextAnsi:"\x1B[1;32m",logoBodyAnsi:"\x1B[32m",logoMutedAnsi:"\x1B[90m",logoGradient:["#8feb73","#e69835"]}};var Ho=null;var Rr=(e="Dark")=>{let t;e==="Mystery"||e==="Chaos"?(Ho||(Ho=vr[Math.floor(Math.random()*vr.length)]),t={...Ho,id:"Mystery"}):(Ho=null,po[e]?t=po[e]:e==="GitHub"?t=po["GitHub Dark"]:e==="Transparent"?t=po["Transparent Dark"]:t=po.Dark);let n=t.codeText||t.secondary||t.info||t.logoGradient&&t.logoGradient[0]||"cyan";return{...t,codeText:n}};var Sa=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",gc=(e=2)=>{let t=Sa();return t==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)},mc=(e="...",t="Loading...",n="Dark")=>{let s=Ws[Math.floor(Math.random()*Ws.length)],o=Rr(n),l=o.logoTextAnsi,f=o.logoBodyAnsi,a=o.logoMutedAnsi,m="\x1B[0m",g=[" \u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2588\u2588\u2588\u2591 "," \u2588\u2588\u2588\u2591 "," \u2588\u2588\u2588\u2591 "," \u2591\u2591\u2591 "],u=o.logoGradient||["#0077ff","#ff00ff"],h=Ta(u).multiline(g.join(`
577
+ ${e}`:""}`.trim();var cr=()=>import("./web_search-2Q2BWH6G.js").then(e=>e.web_search),dr=()=>import("./web_scrape-IKJE45Z6.js").then(e=>e.web_scrape),fr=()=>import("./memory-OYIUYX3A.js").then(e=>e.memory),ur=()=>import("./chat-HZ7UVZE2.js").then(e=>e.chat),gr=()=>import("./view_file-WUHFS5L7.js").then(e=>e.view_file),mr=()=>import("./write_file-LOYRYIK6.js").then(e=>e.write_file),hr=()=>import("./update_file-SOXC3PMR.js").then(e=>e.update_file),pr=()=>import("./exec_command-255QUWWX.js").then(e=>e.exec_command),yr=()=>import("./read_folder-OOKZITME.js").then(e=>e.read_folder),Ns=()=>import("./ask_user-K2DLZF6H.js").then(e=>e.ask_user),xr=()=>import("./write_pdf-VB4IFPWX.js").then(e=>e.write_pdf),br=()=>import("./write_docx-EKUIZ7GV.js").then(e=>e.write_docx),No=()=>import("./search_keyword-W5YEUUPO.js").then(e=>e.search_keyword),kr=()=>import("./generate_image-XYDE47LK.js").then(e=>e.generate_image),Fo=()=>import("./saveSummary-ATBIFYDP.js").then(e=>e.saveSummary),uo=()=>import("./addMemScore-W4I665ZR.js").then(e=>e.addMemScore),wr=()=>import("./file_map-5KY2ADZW.js").then(e=>e.file_map),Bo=()=>import("./todo-SJLJJLVZ.js").then(e=>e.todo),Tr=()=>import("./invokeSync-KKA5TJM6.js").then(e=>e.invokeSync),ba=()=>import("./invoke-PZPQJRG7.js").then(e=>e.invoke),Sr=()=>import("./getProgress-VG2IBPZU.js").then(e=>e.getProgress),ka=()=>import("./cancel-7IMADALP.js").then(e=>e.cancel),_r=()=>import("./emergency_rollback-EPJPKANN.js").then(e=>e.emergency_rollback),go=()=>import("./awaitSubagent-JTUSJDKD.js").then(e=>e.awaitSubagent),mo=()=>import("./answerSubagent-JUVFNLE5.js").then(e=>e.answerSubagent),Uo=()=>import("./steerSubagent-L2JVT4QN.js").then(e=>e.steerSubagent),Wo=()=>import("./computer_action-WTHH7RBB.js").then(e=>e.computer_action),Ar=()=>import("./click-G6RRSFVC.js").then(e=>e.click),Er=()=>import("./drag-ZGH2MMP7.js").then(e=>e.drag),Cr=()=>import("./scroll-GHXES2II.js").then(e=>e.scroll),Fs=()=>import("./keyboard_typing-CK3KVAWM.js").then(e=>e.keyboard_typing),Bs=()=>import("./key_press-M5QNCIPH.js").then(e=>e.key_press),Us=()=>import("./recapture_screen-5FKLOHJL.js").then(e=>e.recapture_screen),wa={web_search:cr,web_scrape:dr,memory:fr,chat:ur,view_file:gr,write_file:mr,update_file:hr,exec_command:pr,read_folder:yr,write_pdf:xr,write_docx:br,search_keyword:No,generate_image:kr,saveSummary:Fo,addMemScore:uo,file_map:wr,todo:Bo,Todo:Bo,goal:Bo,Goal:Bo,invokeSync:Tr,invoke:ba,getProgress:Sr,cancel:ka,awaitSubagent:go,answerSubagent:mo,steerSubagent:Uo,computer_action:Wo,computer_use:Wo,ComputerAction:Wo,ComputerUse:Wo,click:Ar,Click:Ar,drag:Er,Drag:Er,scroll:Cr,Scroll:Cr,keyboard_typing:Fs,KeyboardTyping:Fs,keyboardtyping:Fs,key_press:Bs,KeyPress:Bs,keypress:Bs,recapture_screen:Us,RecaptureScreen:Us,recapturescreen:Us,invoke_sync:Tr,get_progress:Sr,await_subagent:go,answer_subagent:mo,steer_subagent:Uo,steer:Uo,Steer:Uo,ask:Ns,Ask:Ns,AskUser:Ns,WebSearch:cr,WebScrape:dr,ReadFile:gr,ReadFolder:yr,WriteFile:mr,PatchFile:hr,WritePDF:xr,WriteDoc:br,Run:pr,SearchKeyword:No,CodeSearch:No,code_search:No,Memory:fr,Chat:ur,GenerateImage:kr,saveSumary:Fo,SaveSummary:Fo,SaveSumary:Fo,add_mem_score:uo,AddMemScore:uo,addMemoryScore:uo,AddMemoryScore:uo,FileMap:wr,answer:mo,Answer:mo,AnswerSubagent:mo,await:go,Await:go,AwaitSubagent:go,EmergencyRollback:_r,emergency_rollback:_r},ho=async(e,t,n={})=>{let s=n.mode?n.mode.toLowerCase():"flux",o=e.toLowerCase(),f=["memory","chat","savesummary","addmemscore","add_mem_score","ask","web_search","web_scrape","await"].some(u=>o.includes(u))||o==="ask",m=["click","drag","scroll","keyboardtyping","keyboard_typing","keypress","key_press","recapturescreen","recapture_screen","computer"].some(u=>o.includes(u));if(!f){if(s==="flow"){if(!(o.includes("write_pdf")||o.includes("write_docx")||o.includes("generate_image")))return`ERROR: Tool [${e}] is a Workspace Tool and NOT available in Flow mode. Tell user to switch (\`/mode flux\`) to use this tool.`}else if(s==="icu"){if(!m)return`ERROR: Tool [${e}] is not available in Computer Use mode. ICU mode only supports Computer Use tools (Click, Drag, Scroll, KeyboardTyping, KeyPress, RecaptureScreen).`}else if(o.includes("write_pdf")||o.includes("write_docx")||o.includes("generate_image"))return`ERROR: Tool [${e}] is not available in ${n.mode||"Flux"} mode. Tell user to switch (\`/mode flow\`) for document generation.`}let g=wa[e];if(!g)return`ERROR: Tool [${e}] not found in registry.`;try{return await(await g())(t,n)}catch(u){let h=u instanceof Error?u.message:String(u);return`ERROR: Execution failed for [${e}]: ${h}`}};import ee from"path";import je from"fs";import Ta from"gradient-string";var Ws=["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 vr=[{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"]}],po={Dark:{id:"Dark",name:"Dark (Default)",text:"white",textMuted:"gray",textDim:"grey",textInverted:"black",textExclusive:"#B5B8D9",textMutedExclusive:"#D4DEE7",border:"white",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:"#1e1e1e",highlightBg:"#2a2a2a",activeBg:"#3a3a3a",inputBg:"#555555",inputBorder:"#555555",inputText:"white",inputPlaceholder:"#cccccc",inputPrompt:"white",codeBg:"#1a1a1a",codeBorder:"#444444",userMsgBg:"#444444",userMsgBorder:"#444444",userMsgText:"white",diffRemovalBg:"#250808",diffAdditionBg:"#072410",diffRemovalText:"#885555",diffAdditionText:"#558866",diffRemovalHighlightColor:"#ff3333",diffRemovalHighlightBg:"#5a1818",diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:"#185a25",diffRemovalNum:"#d96868",diffAdditionNum:"#68d98c",diffRemovalPrefix:"#ff4d4d",diffAdditionPrefix:"#4dff88",primary:"white",secondary:"cyan",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"white",statusOff:"gray",logoTextAnsi:"\x1B[1;37m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#0077ff","#ff00ff"]},Light:{id:"Light",name:"Light",text:"black",textMuted:"gray",textDim:"grey",textInverted:"white",border:"black",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:"#e5e5e5",highlightBg:"#d4d4d4",activeBg:"#c0c0c0",inputBg:"#d0d0d0",inputBorder:"#d0d0d0",inputText:"black",inputPlaceholder:"#555555",inputPrompt:"black",codeBg:"#e8e8e8",codeBorder:"#b0b0b0",userMsgBg:"#d0d0d0",userMsgBorder:"#d0d0d0",userMsgText:"black",diffRemovalBg:"#fce8e8",diffAdditionBg:"#e6f9e6",diffRemovalText:"#661111",diffAdditionText:"#115511",diffRemovalHighlightColor:"#440000",diffRemovalHighlightBg:"#f8b4b4",diffAdditionHighlightColor:"#003300",diffAdditionHighlightBg:"#a6ebad",diffRemovalNum:"#c02020",diffAdditionNum:"#188028",diffRemovalPrefix:"#d01010",diffAdditionPrefix:"#109020",primary:"black",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"black",statusOff:"gray",logoTextAnsi:"\x1B[1;30m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#0077ff","#ff00ff"]},"GitHub Dark":{id:"GitHub Dark",name:"GitHub Dark",text:"#c9d1d9",textMuted:"#8b949e",textDim:"#6e7681",textInverted:"#0d1117",border:"#30363d",borderMuted:"#30363d",borderDim:"#21262d",bg:void 0,cardBg:"#161b22",highlightBg:"#21262d",activeBg:"#30363d",inputBg:"#21262d",inputBorder:"#21262d",inputText:"#c9d1d9",inputPlaceholder:"#8b949e",inputPrompt:"#58a6ff",codeBg:"#0d1117",codeBorder:"#30363d",userMsgBg:"#21262d",userMsgBorder:"#21262d",userMsgText:"#c9d1d9",diffRemovalBg:"#3c1e1e",diffAdditionBg:"#11381e",diffRemovalText:"#f85149",diffAdditionText:"#3fb950",diffRemovalHighlightColor:"#ff7b72",diffRemovalHighlightBg:"#701c1c",diffAdditionHighlightColor:"#56d364",diffAdditionHighlightBg:"#116329",diffRemovalNum:"#f85149",diffAdditionNum:"#3fb950",diffRemovalPrefix:"#f85149",diffAdditionPrefix:"#3fb950",primary:"#c9d1d9",secondary:"#58a6ff",accent:"#bc8cff",success:"#3fb950",warning:"#d29922",danger:"#f85149",info:"#58a6ff",statusOn:"#58a6ff",statusOff:"#8b949e",logoTextAnsi:"\x1B[1;36m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#2ea043","#56d364"]},"GitHub Light":{id:"GitHub Light",name:"GitHub Light",text:"#24292f",textMuted:"#57606a",textDim:"#6e7781",textInverted:"#ffffff",border:"#d0d7de",borderMuted:"#d0d7de",borderDim:"#e1e4e8",bg:void 0,cardBg:"#f6f8fa",highlightBg:"#eaeef2",activeBg:"#d0d7de",inputBg:"#eaeef2",inputBorder:"#eaeef2",inputText:"#24292f",inputPlaceholder:"#57606a",inputPrompt:"#0969da",codeBg:"#ffffff",codeBorder:"#d0d7de",userMsgBg:"#eaeef2",userMsgBorder:"#eaeef2",userMsgText:"#24292f",diffRemovalBg:"#ffebe9",diffAdditionBg:"#e6ffec",diffRemovalText:"#cf222e",diffAdditionText:"#1a7f37",diffRemovalHighlightColor:"#82071e",diffRemovalHighlightBg:"#ffc1c0",diffAdditionHighlightColor:"#116329",diffAdditionHighlightBg:"#acf2bd",diffRemovalNum:"#cf222e",diffAdditionNum:"#1a7f37",diffRemovalPrefix:"#cf222e",diffAdditionPrefix:"#1a7f37",primary:"#24292f",secondary:"#0969da",accent:"#8250df",success:"#1a7f37",warning:"#9a6700",danger:"#cf222e",info:"#0969da",statusOn:"#0969da",statusOff:"#57606a",logoTextAnsi:"\x1B[1;34m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#1a7f37","#2da44e"]},"Transparent Dark":{id:"Transparent Dark",name:"Transparent Dark",text:"white",textMuted:"gray",textDim:"grey",textInverted:"black",border:"gray",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:void 0,highlightBg:"#2a2a2a",activeBg:"#3a3a3a",inputBg:"#555555",inputBorder:"#555555",inputText:"white",inputPlaceholder:"#cccccc",inputPrompt:"white",codeBg:void 0,codeBorder:"gray",userMsgBg:"#555555",userMsgBorder:"#555555",userMsgText:"white",diffRemovalBg:void 0,diffAdditionBg:void 0,diffRemovalText:"#ff6666",diffAdditionText:"#66ff66",diffRemovalHighlightColor:"#ff3333",diffRemovalHighlightBg:void 0,diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:void 0,diffRemovalNum:"#ff6666",diffAdditionNum:"#66ff66",diffRemovalPrefix:"#ff4d4d",diffAdditionPrefix:"#4dff88",primary:"white",secondary:"cyan",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"white",statusOff:"gray",logoTextAnsi:"\x1B[1;37m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#0077ff","#ff00ff"]},"Transparent Light":{id:"Transparent Light",name:"Transparent Light",text:"black",textMuted:"gray",textDim:"grey",textInverted:"white",border:"gray",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:void 0,highlightBg:"#d4d4d4",activeBg:"#c0c0c0",inputBg:"#d0d0d0",inputBorder:"#d0d0d0",inputText:"black",inputPlaceholder:"#555555",inputPrompt:"black",codeBg:void 0,codeBorder:"gray",userMsgBg:"#d0d0d0",userMsgBorder:"#d0d0d0",userMsgText:"black",diffRemovalBg:void 0,diffAdditionBg:void 0,diffRemovalText:"#c02020",diffAdditionText:"#188028",diffRemovalHighlightColor:"#800000",diffRemovalHighlightBg:void 0,diffAdditionHighlightColor:"#004000",diffAdditionHighlightBg:void 0,diffRemovalNum:"#c02020",diffAdditionNum:"#188028",diffRemovalPrefix:"#d01010",diffAdditionPrefix:"#109020",primary:"black",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"black",statusOff:"gray",logoTextAnsi:"\x1B[1;30m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#0077ff","#ff00ff"]},"Synthwave 84":{id:"Synthwave 84",name:"Synthwave 84",text:"#fdfdfd",textMuted:"#a08eb7",textDim:"#705c8a",textInverted:"#1a1025",textExclusive:"#e3dcf0",textMutedExclusive:"#b9abc9",border:"#fc28a8",borderMuted:"#a21568",borderDim:"#5c0a3a",bg:void 0,cardBg:"#261b38",highlightBg:"#35254d",activeBg:"#4c3570",inputBg:"#35254d",inputBorder:"#35254d",inputText:"#fdfdfd",inputPlaceholder:"#a08eb7",inputPrompt:"#03e8fc",codeBg:"#1e142b",codeBorder:"#a21568",userMsgBg:"#35254d",userMsgBorder:"#35254d",userMsgText:"#fdfdfd",diffRemovalBg:"#471434",diffAdditionBg:"#144743",diffRemovalText:"#ff4081",diffAdditionText:"#00e5ff",diffRemovalHighlightColor:"#ff79a1",diffRemovalHighlightBg:"#6b1e4e",diffAdditionHighlightColor:"#66f5ff",diffAdditionHighlightBg:"#1e6b65",diffRemovalNum:"#ff4081",diffAdditionNum:"#00e5ff",diffRemovalPrefix:"#ff79a1",diffAdditionPrefix:"#66f5ff",primary:"#fdfdfd",secondary:"#03e8fc",accent:"#fc28a8",success:"#00e5ff",warning:"#ffc107",danger:"#ff4081",info:"#b388ff",statusOn:"#03e8fc",statusOff:"#a08eb7",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#fc28a8","#03e8fc"]},"Forest Sprite":{id:"Forest Sprite",name:"Forest Sprite",text:"#d6e6d1",textMuted:"#95b38d",textDim:"#628059",textInverted:"#161c14",textExclusive:"#eaf2e8",textMutedExclusive:"#a9c7a2",border:"#74a862",borderMuted:"#477038",borderDim:"#2b4720",bg:void 0,cardBg:"#1f291c",highlightBg:"#2a3826",activeBg:"#3a4d35",inputBg:"#2a3826",inputBorder:"#2a3826",inputText:"#d6e6d1",inputPlaceholder:"#95b38d",inputPrompt:"#8feb73",codeBg:"#161e14",codeBorder:"#477038",userMsgBg:"#2a3826",userMsgBorder:"#2a3826",userMsgText:"#d6e6d1",diffRemovalBg:"#3b231c",diffAdditionBg:"#203b1c",diffRemovalText:"#db6242",diffAdditionText:"#59cc3f",diffRemovalHighlightColor:"#f0896c",diffRemovalHighlightBg:"#5c362a",diffAdditionHighlightColor:"#80e368",diffAdditionHighlightBg:"#305929",diffRemovalNum:"#db6242",diffAdditionNum:"#59cc3f",diffRemovalPrefix:"#f0896c",diffAdditionPrefix:"#80e368",primary:"#d6e6d1",secondary:"#8feb73",accent:"#e69835",success:"#59cc3f",warning:"#e69835",danger:"#db6242",info:"#73b4eb",statusOn:"#8feb73",statusOff:"#95b38d",logoTextAnsi:"\x1B[1;32m",logoBodyAnsi:"\x1B[32m",logoMutedAnsi:"\x1B[90m",logoGradient:["#8feb73","#e69835"]}};var Ho=null;var Rr=(e="Dark")=>{let t;e==="Mystery"||e==="Chaos"?(Ho||(Ho=vr[Math.floor(Math.random()*vr.length)]),t={...Ho,id:"Mystery"}):(Ho=null,po[e]?t=po[e]:e==="GitHub"?t=po["GitHub Dark"]:e==="Transparent"?t=po["Transparent Dark"]:t=po.Dark);let n=t.codeText||t.secondary||t.info||t.logoGradient&&t.logoGradient[0]||"cyan";return{...t,codeText:n}};var Sa=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",gc=(e=2)=>{let t=Sa();return t==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)},mc=(e="...",t="Loading...",n="Dark")=>{let s=Ws[Math.floor(Math.random()*Ws.length)],o=Rr(n),l=o.logoTextAnsi,f=o.logoBodyAnsi,a=o.logoMutedAnsi,m="\x1B[0m",g=[" \u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2588\u2588\u2588\u2591 "," \u2588\u2588\u2588\u2591 "," \u2588\u2588\u2588\u2591 "," \u2591\u2591\u2591 "],u=o.logoGradient||["#0077ff","#ff00ff"],h=Ta(u).multiline(g.join(`
578
578
  `)).split(`
579
579
  `),x=i=>`${a}${i}${m}`;return`${h[0]}
580
580
  ${h[1]} ${l}Selected Provider: ${t}${m}
@@ -598,8 +598,8 @@ ${h[7]}
598
598
  `,m+=qs(E,t,C,s+1,o,l)):m+=`${n}${k}${i.name}
599
599
  `}),m};import"@google/genai";var nt=async(e,t,n=5,s=1e3)=>{let o=t?.signal;for(let f=0;f<n;f++){if(o?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{let a=await fetch(e,t);if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),a.ok||a.status!==429&&a.status<500)return a}catch(a){if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),a.name==="AbortError"||o?.aborted||f===n-1)throw a}o?await new Promise((a,m)=>{let g=setTimeout(()=>{o.removeEventListener("abort",u),a()},Math.min(24e3,s*Math.pow(2,f))),u=()=>{clearTimeout(g),m(new DOMException("The user aborted a request.","AbortError"))};o.addEventListener("abort",u)}):await new Promise(a=>setTimeout(a,Math.min(24e3,s*Math.pow(2,f))))}if(o?.aborted)throw new DOMException("The user aborted a request.","AbortError");let l=await fetch(e,t);return typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),l};async function Ko(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",t);return[...new Uint8Array(n).slice(0,16)].map(s=>s.toString(16).padStart(2,"0")).join("")}var bn=e=>typeof e!="string"?e:e.replace(/<\|channel>thought/gi,"<think>").replace(/<channel\|>/gi,"</think>");var Yo=async function*(e,t,n,s,o,l,f,a,m=1){let g=[];s&&g.push({role:"system",content:s});for(let R of n){let L=R.role==="user"?"user":"assistant",y=[];if(Array.isArray(R.parts)){for(let d of R.parts)if(d.text)y.push({type:"text",text:d.text});else if((d.inlineData||d.inline_data)&&f){let b=d.inlineData||d.inline_data,r=b.mimeType||b.mime_type||"image/jpeg",w=b.data;r.startsWith("image/")&&y.push({type:"image_url",image_url:{url:`data:${r};base64,${w}`}})}}else{let d=R.text||"";d&&y.push({type:"text",text:d})}g.push({role:L,content:y.length===1&&y[0].type==="text"?y[0].text:y})}let u={model:t,messages:g,stream:!0,stream_options:{include_usage:!0},temperature:m},h=Ke("DeepSeek",t,o),i=h!==null?h:o!=="Fast"?{Low:"low",Medium:"high",Standard:"high",High:"max",xHigh:"max"}[o]||"high":null;i&&i!=="disabled"&&i!=="none"&&i!=="false"&&i!==!1?(u.reasoning_effort=i,u.extra_body={thinking:{type:"enabled"}}):u.extra_body={thinking:{type:"disabled"}};let c=await nt("https://api.deepseek.com/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(u),signal:a});if(!c.ok){let R=await c.json().catch(()=>({}));throw new Error(`DeepSeek Error (${c.status}): ${R.error?.message||c.statusText}`)}let T=c.body.getReader(),E=new TextDecoder,k="",C=[],N=null,v=Date.now(),_=!1;for(;;){let{done:R,value:L}=await T.read();if(R){_&&(C.length>0||N)&&(yield{candidates:C.length>0?[{content:{parts:C}}]:[],usageMetadata:N});break}k+=E.decode(L,{stream:!0});let y=k.split(`
600
600
  `);k=y.pop();for(let d of y){let b=d.trim();if(!b||!b.startsWith("data: "))continue;let r=!1;if(b==="data: [DONE]")r=!0;else try{let w=JSON.parse(b.substring(6)),A=w.choices?.[0]?.delta,O=w.usage;if(w.choices?.[0]?.finish_reason&&(r=!0),O&&(N={totalTokenCount:O.total_tokens||O.prompt_tokens+O.completion_tokens,promptTokenCount:O.prompt_tokens||0,candidatesTokenCount:O.completion_tokens||0,cachedContentTokenCount:O.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:O.completion_tokens_details?.reasoning_tokens||0},_=!0),A){let H=A.reasoning_content||null;H&&(C.push({text:H,thought:!0}),_=!0),A.content&&(C.push({text:A.content}),_=!0)}}catch{}if((r||Date.now()-v>=150)&&_&&(yield{candidates:C.length>0?[{content:{parts:[...C]}}]:[],usageMetadata:N},C=[],v=Date.now(),_=!1),r)break}Date.now()-v>=150&&_&&(yield{candidates:C.length>0?[{content:{parts:[...C]}}]:[],usageMetadata:N},C=[],v=Date.now(),_=!1)}};var qo=async function*(e,t,n,s,o,l,f,a,m=1,g=null){let u=[];s&&u.push({role:"system",content:s});for(let d of n){let b=d.role==="user"?"user":"assistant",r=[];if(Array.isArray(d.parts)){for(let w of d.parts)if(w.text)r.push({type:"text",text:w.text});else if(w.inlineData&&f){let A=w.inlineData.mimeType,O=w.inlineData.data;A.startsWith("image/")&&r.push({type:"image_url",image_url:`data:${A};base64,${O}`})}}else{let w=d.text||"";w&&r.push({type:"text",text:w})}r.length>0&&u.push({role:b,content:r.length===1&&r[0].type==="text"?r[0].text:r})}let h={Fast:"none",Low:"none",Medium:"high",Standard:"high",High:"high",xHigh:"high"},x=`${e.slice(-5)}${g||""}${o}${t}`,i=await Ko(x),c={model:t,messages:u,stream:!0,temperature:m,prompt_cache_key:i},T=Ke("Mistral",t,o);T!==null&&T!=="none"?T&&T!=="none"&&T!=="disabled"&&T!==!1&&(c.reasoning_effort=T):o&&h[o]!=="none"&&(c.reasoning_effort=h[o]||"high");let E=await nt("https://api.mistral.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(c),signal:a});if(!E.ok){let d=await E.text().catch(()=>""),b=E.statusText;try{let r=JSON.parse(d);b=r.error?.message||r.message||JSON.stringify(r.detail||r)}catch{d&&(b=d)}throw new Error(`Mistral Error (${E.status}): ${JSON.stringify(b)}`)}let k=E.body.getReader(),C=new TextDecoder,N="",v=[],_=null,R=Date.now(),L=!1,y=d=>d?typeof d=="string"?bn(d):Array.isArray(d)?d.map(y).filter(Boolean).join(""):typeof d=="object"&&d!==null?typeof d.text=="string"?bn(d.text):typeof d.content=="string"?bn(d.content):typeof d.thinking=="string"?bn(d.thinking):typeof d.reasoning_content=="string"?bn(d.reasoning_content):typeof d.reasoning=="string"?bn(d.reasoning):typeof d.value=="string"?bn(d.value):d.text?y(d.text):d.content?y(d.content):d.thinking?y(d.thinking):d.reasoning_content?y(d.reasoning_content):d.reasoning?y(d.reasoning):d.value?y(d.value):"":bn(String(d)):"";for(;;){let{done:d,value:b}=await k.read();if(d){L&&(v.length>0||_)&&(yield{candidates:v.length>0?[{content:{parts:v}}]:[],usageMetadata:_});break}N+=C.decode(b,{stream:!0});let r=N.split(`
601
- `);N=r.pop();for(let w of r){let A=w.trim();if(!A||!A.startsWith("data: "))continue;let O=!1;if(A==="data: [DONE]")O=!0;else try{let H=JSON.parse(A.substring(6)),P=H.choices?.[0]?.delta,M=H.usage;if(H.choices?.[0]?.finish_reason&&(O=!0),M&&(_={totalTokenCount:M.total_tokens||(M.prompt_tokens||0)+(M.completion_tokens||0),promptTokenCount:M.prompt_tokens||0,candidatesTokenCount:M.completion_tokens||0,cachedContentTokenCount:M.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:M.completion_tokens_details?.reasoning_tokens||0},L=!0),P){let te=P.thinking||P.reasoning_content||P.reasoning,le=y(te);le&&(v.push({text:le,thought:!0}),L=!0);let J=P.content||(!P.thinking&&!P.reasoning_content&&!P.reasoning?P.text:null);if(J)if(Array.isArray(J))for(let re of J)if(typeof re=="object"&&re!==null){let De=re.type==="thinking"||re.type==="reasoning"||!!re.thought,We=y(re);We&&(v.push({text:We,...De?{thought:!0}:{}}),L=!0)}else{let De=y(re);De&&(v.push({text:De}),L=!0)}else if(typeof J=="object"&&J!==null){let re=J.type==="thinking"||J.type==="reasoning"||!!J.thought,De=y(J);De&&(v.push({text:De,...re?{thought:!0}:{}}),L=!0)}else{let re=y(J);re&&(v.push({text:re}),L=!0)}}}catch{}if((O||Date.now()-R>=150)&&L&&(yield{candidates:v.length>0?[{content:{parts:[...v]}}]:[],usageMetadata:_},v=[],R=Date.now(),L=!1),O)break}Date.now()-R>=150&&L&&(yield{candidates:v.length>0?[{content:{parts:[...v]}}]:[],usageMetadata:_},v=[],R=Date.now(),L=!1)}};var zo=async function*(e,t,n,s,o,l,f=!1,a,m=1){let g=[];s&&g.push({role:"system",content:s}),n.forEach(We=>{let D=We.role==="model"?"assistant":"user",F=[];Array.isArray(We.parts)&&We.parts.forEach(Ae=>{if(Ae.text)F.push({type:"text",text:Ae.text});else if(Ae.inlineData&&f){let z=Ae.inlineData.mimeType,B=Ae.inlineData.data;z.startsWith("image/")&&gt(t)&&F.push({type:"image_url",image_url:{url:`data:${z};base64,${B}`}})}}),g.push({role:D,content:F.length===1&&F[0].type==="text"?F[0].text:F})});let u=Ke("NVIDIA",t,o),x=u!==null?u:{Fast:"Fast",Low:"Fast",Medium:"Standard",Standard:"Standard",High:"High",xHigh:"High"}[o]||"High",i=x!=="Fast"&&x!=="none"&&x!=="disabled"&&x!==!1,c=t.includes("kimi"),T=t.includes("gemma"),E=t.includes("deepseek"),k=t.includes("glm"),C=t.includes("mistral"),N=t.includes("minimax"),v=t.includes("gpt"),_=t.includes("qwen"),R=t.includes("nemotron"),L=t.includes("llama-3"),y=t.includes("seed"),d=t.includes("poolside"),b=t.includes("thinkingmachines")||t.includes("muse"),r=L,w=null,A={Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},O={Fast:"64",Low:"64",Medium:"4096",Standard:"4096",High:"16384",xHigh:"16384"},H={Fast:"none",Low:"minimal",Medium:"medium",Standard:"medium",High:"max",xHigh:"max"},P=N||E||d||b?16384:32768;P=process.env.NVIDIA_BASE_URL?1024:P,P=w?1024:P;let M={model:t,messages:g,max_tokens:P,stream:!0,stream_options:{include_usage:!0},temperature:m,...v&&{thinking:A[o]||"high"}};if(!(process.env.NVIDIA_BASE_URL||r||w))if(c)M.chat_template_kwargs={thinking:i};else if(T)M.chat_template_kwargs={enable_thinking:i};else if(E)if(i){let We=x==="High"?"max":"high";M.chat_template_kwargs={thinking:!0,reasoning_effort:We}}else M.chat_template_kwargs={thinking:!1};else k?M.chat_template_kwargs={enable_thinking:i,clear_thinking:!i}:C?M.reasoning_effort=i?"high":"none":N&&t.includes("minimax-m3")?M.chat_template_kwargs={thinking_mode:i?"enabled":"disabled"}:_?M.chat_template_kwargs={enable_thinking:i}:R?x==="High"?M.chat_template_kwargs={enable_thinking:!0}:x==="Standard"?M.chat_template_kwargs={enable_thinking:!0,medium_effort:!0}:M.chat_template_kwargs={enable_thinking:!1}:y?i&&(M.extra_body={thinking_budget:parseInt(O[x]??"4096")}):d?M.chat_template_kwargs={enable_thinking:i}:b&&(M.reasoning_effort=H[x]||"medium");let te=0,le=6,J=!1,re=process.env.NVIDIA_BASE_URL||"https://integrate.api.nvidia.com/v1/chat/completions",De=process.env.NVIDIA_API_KEY&&process.env.NVIDIA_BASE_URL?process.env.NVIDIA_API_KEY:e;for(re.endsWith("/chat/completions")||(re=re.replace(/\/+$/,"")+"/chat/completions");te<le;){te++;try{let We=await nt(re,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${De}`},body:JSON.stringify(M),signal:a});if(!We.ok){let Ee=await We.text().catch(()=>""),Ce=We.statusText;try{let vt=JSON.parse(Ee);Ce=vt.error?.message||vt.message||JSON.stringify(vt.detail||vt)}catch{Ee&&(Ce=Ee)}let Ne=new Error(`NVIDIA API Error (${We.status}): ${Ce}`);throw Ne.status=We.status,Ne}let D=We.body.getReader(),F=new TextDecoder,Ae="",z=[],B=null,Y=Date.now(),de=!1;for(;;){let{done:Ee,value:Ce}=await D.read();if(Ee){de&&(z.length>0||B)&&(yield{candidates:z.length>0?[{content:{parts:z}}]:[],usageMetadata:B},J=!0);break}Ae+=F.decode(Ce,{stream:!0});let Ne=Ae.split(`
602
- `);Ae=Ne.pop();let vt=!1;for(let wn of Ne){let zt=wn.trim();if(zt){if(zt==="data: [DONE]"){vt=!0;break}if(zt.startsWith("data: ")){let dt;try{dt=JSON.parse(zt.substring(6))}catch{continue}if(dt.error)throw new Error(`NVIDIA Stream Error: ${dt.error.message||JSON.stringify(dt.error)}`);try{let ge=dt.usage;ge&&(B={totalTokenCount:ge.total_tokens||ge.prompt_tokens+ge.completion_tokens,promptTokenCount:ge.prompt_tokens||0,candidatesTokenCount:ge.completion_tokens||0,cachedContentTokenCount:ge.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:(ge.completion_tokens_details?.reasoning_tokens||0)+(ge.completion_tokens_details?.thoughts_tokens||0)},de=!0);let me=dt.choices?.[0]?.delta?.reasoning||dt.choices?.[0]?.delta?.reasoning_content||"",ie=dt.choices?.[0]?.delta?.content||"";me&&(z.push({text:me,thought:!0}),de=!0),ie&&(z.push({text:ie}),de=!0)}catch{}}}}if((vt||Date.now()-Y>=350)&&de&&(yield{candidates:z.length>0?[{content:{parts:[...z]}}]:[],usageMetadata:B},J=!0,z=[],Y=Date.now(),de=!1),vt)break}break}catch(We){if(J||te>=le)throw We;await new Promise(D=>setTimeout(D,3500))}}},Pr=async function*(e,t){let n=[],s=null,o=!1,l=null,f=i=>{if(n.push(i),s){let c=s;s=null,c()}},a=t.split("/").pop();a=a.replace("llama-3.3","llama-3_3");let m=`https://buildapi.ngc.nvidia.com/v2/predict/queues/models/qc69jvmznzxy/${a}`,g=`https://api.ngc.nvidia.com/v2/predict/queues/models/qc69jvmznzxy/${a}`,u=!1,h=null,x=async()=>{try{let c=await(await Promise.any([m,g].map(async T=>{let E=await fetch(T);if(!E.ok)throw new Error(`HTTP ${E.status}`);return E}))).json();if(c&&c.queues&&c.queues[0]&&typeof c.queues[0].queueDepth=="number"){let T=c.queues[0].queueDepth;u||f({value:{type:"status",content:`Queue ${T||1}`},done:!1})}}catch{}};process.env.NVIDIA_BASE_URL||(x(),h=setInterval(x,5e3)),(async()=>{try{let i=e[Symbol.asyncIterator]();for(;;){let{value:c,done:T}=await i.next();if(T)break;u=!0,h&&(clearInterval(h),h=null),f({value:c,done:!1})}o=!0,f(null)}catch(i){if(l=i,h&&(clearInterval(h),h=null),s){let c=s;s=null,c()}}})();try{for(;;){if(l)throw l;if(n.length>0){let i=n.shift();if(i===null&&o)break;yield i.value}else{if(o)break;await new Promise(i=>{s=i})}}}finally{h&&(clearInterval(h),h=null)}};var Jo=async function*(e,t,n,s,o,l,f,a,m=1,g=null){let u=[];s&&u.push({role:"system",content:[{type:"text",text:s}]});for(let A of n){let O=A.role==="user"?"user":"assistant",H=[];if(Array.isArray(A.parts)){for(let P of A.parts)if(P.text)H.push({type:"text",text:P.text});else if(P.inlineData&&f){let M=P.inlineData.mimeType,te=P.inlineData.data;M.startsWith("image/")?H.push({type:"image_url",image_url:{url:`data:${M};base64,${te}`}}):H.push({type:"file",file:{filename:P.filename||"file",file_data:`data:${M};base64,${te}`}})}}else{let P=A.text||"";P&&H.push({type:"text",text:P})}u.push({role:O,content:H.length===1&&H[0].type==="text"?H[0].text:H})}let h={Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},x=["free","nitro","floor","exacto"],i=t,c=null,T=null;if(t.includes(":")){let A=t.split(":");if(A.length>1){let O=A[A.length-1].toLowerCase().trim();(O==="flex"||O==="priority")&&(T=O,A.pop())}if(A.length>1){let O=A[A.length-1].toLowerCase().trim();if(!x.includes(O)){let H=A.pop().trim();H&&(c={only:[H],allow_fallbacks:!1})}}i=A.join(":").trim()}let E=`${e.slice(-5)}${g||""}${o}${i}${T||""}${c?JSON.stringify(c):""}`,k=await Ko(E),C={model:i,messages:u,stream:!0,temperature:m,cache_control:{type:"ephemeral"},session_id:k};T&&(C.service_tier=T),c&&(C.provider=c);let N=Ke("OpenRouter",t,o),v=N!==null?N:h[o];v&&v!=="none"&&(N!==null||o!=="Fast")&&(C.reasoning_effort=v);let _=await nt("https://openrouter.ai/api/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json","HTTP-Referer":"https://fluxflow-cli.onrender.com/","X-Title":"FluxFlow CLI","X-OpenRouter-Title":"FluxFlow CLI","X-Cache":"true","X-OpenRouter-Cache":"true"},body:JSON.stringify(C),signal:a});if(!_.ok){let A=await _.json().catch(()=>({})),O=A.error?.metadata?.raw||A.error?.message||(typeof A.error=="string"?A.error:"")||_.statusText||"Unknown error";throw new Error(`OpenRouter Error (${_.status}): ${O}`)}let R=_.body.getReader(),L=new TextDecoder,y="",d=[],b=null,r=Date.now(),w=!1;for(;;){let{done:A,value:O}=await R.read();if(A){w&&(d.length>0||b)&&(yield{candidates:d.length>0?[{content:{parts:d}}]:[],usageMetadata:b});break}y+=L.decode(O,{stream:!0});let H=y.split(`
601
+ `);N=r.pop();for(let w of r){let A=w.trim();if(!A||!A.startsWith("data: "))continue;let O=!1;if(A==="data: [DONE]")O=!0;else try{let H=JSON.parse(A.substring(6)),P=H.choices?.[0]?.delta,M=H.usage;if(H.choices?.[0]?.finish_reason&&(O=!0),M&&(_={totalTokenCount:M.total_tokens||(M.prompt_tokens||0)+(M.completion_tokens||0),promptTokenCount:M.prompt_tokens||0,candidatesTokenCount:M.completion_tokens||0,cachedContentTokenCount:M.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:M.completion_tokens_details?.reasoning_tokens||0},L=!0),P){let te=P.thinking||P.reasoning_content||P.reasoning,le=y(te);le&&(v.push({text:le,thought:!0}),L=!0);let J=P.content||(!P.thinking&&!P.reasoning_content&&!P.reasoning?P.text:null);if(J)if(Array.isArray(J))for(let re of J)if(typeof re=="object"&&re!==null){let De=re.type==="thinking"||re.type==="reasoning"||!!re.thought,We=y(re);We&&(v.push({text:We,...De?{thought:!0}:{}}),L=!0)}else{let De=y(re);De&&(v.push({text:De}),L=!0)}else if(typeof J=="object"&&J!==null){let re=J.type==="thinking"||J.type==="reasoning"||!!J.thought,De=y(J);De&&(v.push({text:De,...re?{thought:!0}:{}}),L=!0)}else{let re=y(J);re&&(v.push({text:re}),L=!0)}}}catch{}if((O||Date.now()-R>=150)&&L&&(yield{candidates:v.length>0?[{content:{parts:[...v]}}]:[],usageMetadata:_},v=[],R=Date.now(),L=!1),O)break}Date.now()-R>=150&&L&&(yield{candidates:v.length>0?[{content:{parts:[...v]}}]:[],usageMetadata:_},v=[],R=Date.now(),L=!1)}};var zo=async function*(e,t,n,s,o,l,f=!1,a,m=1){let g=[];s&&g.push({role:"system",content:s}),n.forEach(We=>{let D=We.role==="model"?"assistant":"user",F=[];Array.isArray(We.parts)&&We.parts.forEach(Ee=>{if(Ee.text)F.push({type:"text",text:Ee.text});else if(Ee.inlineData&&f){let z=Ee.inlineData.mimeType,B=Ee.inlineData.data;z.startsWith("image/")&&gt(t)&&F.push({type:"image_url",image_url:{url:`data:${z};base64,${B}`}})}}),g.push({role:D,content:F.length===1&&F[0].type==="text"?F[0].text:F})});let u=Ke("NVIDIA",t,o),x=u!==null?u:{Fast:"Fast",Low:"Fast",Medium:"Standard",Standard:"Standard",High:"High",xHigh:"High"}[o]||"High",i=x!=="Fast"&&x!=="none"&&x!=="disabled"&&x!==!1,c=t.includes("kimi"),T=t.includes("gemma"),E=t.includes("deepseek"),k=t.includes("glm"),C=t.includes("mistral"),N=t.includes("minimax"),v=t.includes("gpt"),_=t.includes("qwen"),R=t.includes("nemotron"),L=t.includes("llama-3"),y=t.includes("seed"),d=t.includes("poolside"),b=t.includes("thinkingmachines")||t.includes("muse"),r=L,w=null,A={Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},O={Fast:"64",Low:"64",Medium:"4096",Standard:"4096",High:"16384",xHigh:"16384"},H={Fast:"none",Low:"minimal",Medium:"medium",Standard:"medium",High:"max",xHigh:"max"},P=N||E||d||b?16384:32768;P=process.env.NVIDIA_BASE_URL?1024:P,P=w?1024:P;let M={model:t,messages:g,max_tokens:P,stream:!0,stream_options:{include_usage:!0},temperature:m,...v&&{thinking:A[o]||"high"}};if(!(process.env.NVIDIA_BASE_URL||r||w))if(c)M.chat_template_kwargs={thinking:i};else if(T)M.chat_template_kwargs={enable_thinking:i};else if(E)if(i){let We=x==="High"?"max":"high";M.chat_template_kwargs={thinking:!0,reasoning_effort:We}}else M.chat_template_kwargs={thinking:!1};else k?M.chat_template_kwargs={enable_thinking:i,clear_thinking:!i}:C?M.reasoning_effort=i?"high":"none":N&&t.includes("minimax-m3")?M.chat_template_kwargs={thinking_mode:i?"enabled":"disabled"}:_?M.chat_template_kwargs={enable_thinking:i}:R?x==="High"?M.chat_template_kwargs={enable_thinking:!0}:x==="Standard"?M.chat_template_kwargs={enable_thinking:!0,medium_effort:!0}:M.chat_template_kwargs={enable_thinking:!1}:y?i&&(M.extra_body={thinking_budget:parseInt(O[x]??"4096")}):d?M.chat_template_kwargs={enable_thinking:i}:b&&(M.reasoning_effort=H[x]||"medium");let te=0,le=6,J=!1,re=process.env.NVIDIA_BASE_URL||"https://integrate.api.nvidia.com/v1/chat/completions",De=process.env.NVIDIA_API_KEY&&process.env.NVIDIA_BASE_URL?process.env.NVIDIA_API_KEY:e;for(re.endsWith("/chat/completions")||(re=re.replace(/\/+$/,"")+"/chat/completions");te<le;){te++;try{let We=await nt(re,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${De}`},body:JSON.stringify(M),signal:a});if(!We.ok){let Ce=await We.text().catch(()=>""),ve=We.statusText;try{let vt=JSON.parse(Ce);ve=vt.error?.message||vt.message||JSON.stringify(vt.detail||vt)}catch{Ce&&(ve=Ce)}let Ne=new Error(`NVIDIA API Error (${We.status}): ${ve}`);throw Ne.status=We.status,Ne}let D=We.body.getReader(),F=new TextDecoder,Ee="",z=[],B=null,Y=Date.now(),de=!1;for(;;){let{done:Ce,value:ve}=await D.read();if(Ce){de&&(z.length>0||B)&&(yield{candidates:z.length>0?[{content:{parts:z}}]:[],usageMetadata:B},J=!0);break}Ee+=F.decode(ve,{stream:!0});let Ne=Ee.split(`
602
+ `);Ee=Ne.pop();let vt=!1;for(let wn of Ne){let zt=wn.trim();if(zt){if(zt==="data: [DONE]"){vt=!0;break}if(zt.startsWith("data: ")){let dt;try{dt=JSON.parse(zt.substring(6))}catch{continue}if(dt.error)throw new Error(`NVIDIA Stream Error: ${dt.error.message||JSON.stringify(dt.error)}`);try{let ge=dt.usage;ge&&(B={totalTokenCount:ge.total_tokens||ge.prompt_tokens+ge.completion_tokens,promptTokenCount:ge.prompt_tokens||0,candidatesTokenCount:ge.completion_tokens||0,cachedContentTokenCount:ge.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:(ge.completion_tokens_details?.reasoning_tokens||0)+(ge.completion_tokens_details?.thoughts_tokens||0)},de=!0);let me=dt.choices?.[0]?.delta?.reasoning||dt.choices?.[0]?.delta?.reasoning_content||"",ie=dt.choices?.[0]?.delta?.content||"";me&&(z.push({text:me,thought:!0}),de=!0),ie&&(z.push({text:ie}),de=!0)}catch{}}}}if((vt||Date.now()-Y>=350)&&de&&(yield{candidates:z.length>0?[{content:{parts:[...z]}}]:[],usageMetadata:B},J=!0,z=[],Y=Date.now(),de=!1),vt)break}break}catch(We){if(J||te>=le)throw We;await new Promise(D=>setTimeout(D,3500))}}},Pr=async function*(e,t){let n=[],s=null,o=!1,l=null,f=i=>{if(n.push(i),s){let c=s;s=null,c()}},a=t.split("/").pop();a=a.replace("llama-3.3","llama-3_3");let m=`https://buildapi.ngc.nvidia.com/v2/predict/queues/models/qc69jvmznzxy/${a}`,g=`https://api.ngc.nvidia.com/v2/predict/queues/models/qc69jvmznzxy/${a}`,u=!1,h=null,x=async()=>{try{let c=await(await Promise.any([m,g].map(async T=>{let E=await fetch(T);if(!E.ok)throw new Error(`HTTP ${E.status}`);return E}))).json();if(c&&c.queues&&c.queues[0]&&typeof c.queues[0].queueDepth=="number"){let T=c.queues[0].queueDepth;u||f({value:{type:"status",content:`Queue ${T||1}`},done:!1})}}catch{}};process.env.NVIDIA_BASE_URL||(x(),h=setInterval(x,5e3)),(async()=>{try{let i=e[Symbol.asyncIterator]();for(;;){let{value:c,done:T}=await i.next();if(T)break;u=!0,h&&(clearInterval(h),h=null),f({value:c,done:!1})}o=!0,f(null)}catch(i){if(l=i,h&&(clearInterval(h),h=null),s){let c=s;s=null,c()}}})();try{for(;;){if(l)throw l;if(n.length>0){let i=n.shift();if(i===null&&o)break;yield i.value}else{if(o)break;await new Promise(i=>{s=i})}}}finally{h&&(clearInterval(h),h=null)}};var Jo=async function*(e,t,n,s,o,l,f,a,m=1,g=null){let u=[];s&&u.push({role:"system",content:[{type:"text",text:s}]});for(let A of n){let O=A.role==="user"?"user":"assistant",H=[];if(Array.isArray(A.parts)){for(let P of A.parts)if(P.text)H.push({type:"text",text:P.text});else if(P.inlineData&&f){let M=P.inlineData.mimeType,te=P.inlineData.data;M.startsWith("image/")?H.push({type:"image_url",image_url:{url:`data:${M};base64,${te}`}}):H.push({type:"file",file:{filename:P.filename||"file",file_data:`data:${M};base64,${te}`}})}}else{let P=A.text||"";P&&H.push({type:"text",text:P})}u.push({role:O,content:H.length===1&&H[0].type==="text"?H[0].text:H})}let h={Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},x=["free","nitro","floor","exacto"],i=t,c=null,T=null;if(t.includes(":")){let A=t.split(":");if(A.length>1){let O=A[A.length-1].toLowerCase().trim();(O==="flex"||O==="priority")&&(T=O,A.pop())}if(A.length>1){let O=A[A.length-1].toLowerCase().trim();if(!x.includes(O)){let H=A.pop().trim();H&&(c={only:[H],allow_fallbacks:!1})}}i=A.join(":").trim()}let E=`${e.slice(-5)}${g||""}${o}${i}${T||""}${c?JSON.stringify(c):""}`,k=await Ko(E),C={model:i,messages:u,stream:!0,temperature:m,cache_control:{type:"ephemeral"},session_id:k};T&&(C.service_tier=T),c&&(C.provider=c);let N=Ke("OpenRouter",t,o),v=N!==null?N:h[o];v&&v!=="none"&&(N!==null||o!=="Fast")&&(C.reasoning_effort=v);let _=await nt("https://openrouter.ai/api/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json","HTTP-Referer":"https://fluxflow-cli.onrender.com/","X-Title":"FluxFlow CLI","X-OpenRouter-Title":"FluxFlow CLI","X-Cache":"true","X-OpenRouter-Cache":"true"},body:JSON.stringify(C),signal:a});if(!_.ok){let A=await _.json().catch(()=>({})),O=A.error?.metadata?.raw||A.error?.message||(typeof A.error=="string"?A.error:"")||_.statusText||"Unknown error";throw new Error(`OpenRouter Error (${_.status}): ${O}`)}let R=_.body.getReader(),L=new TextDecoder,y="",d=[],b=null,r=Date.now(),w=!1;for(;;){let{done:A,value:O}=await R.read();if(A){w&&(d.length>0||b)&&(yield{candidates:d.length>0?[{content:{parts:d}}]:[],usageMetadata:b});break}y+=L.decode(O,{stream:!0});let H=y.split(`
603
603
  `);y=H.pop();for(let P of H){let M=P.trim();if(!M||!M.startsWith("data: "))continue;let te=!1;if(M==="data: [DONE]")te=!0;else try{let le=JSON.parse(M.substring(6));if(le.error){let De=le.error.metadata?.raw||le.error.message||JSON.stringify(le.error);throw new Error(`OpenRouter Stream Error: ${De}`)}let J=le.choices?.[0]?.delta,re=le.usage;if(le.choices?.[0]?.finish_reason&&(te=!0),re&&(b={totalTokenCount:re.total_tokens||(re.prompt_tokens||0)+(re.completion_tokens||0),promptTokenCount:re.prompt_tokens||0,candidatesTokenCount:re.completion_tokens||0,cachedContentTokenCount:re.prompt_tokens_details?.cached_tokens||re.prompt_tokens_details?.cache_read_input_tokens||re.cache_read_input_tokens||0,thoughtsTokenCount:re.completion_tokens_details?.reasoning_tokens||0},w=!0),J){let De=J.reasoning||(J.reasoning_details?J.reasoning_details.map(We=>We.text).join(""):null);De&&(d.push({text:De,thought:!0}),w=!0),J.content&&(d.push({text:J.content}),w=!0)}}catch(le){if(le.message&&le.message.startsWith("OpenRouter Stream Error:"))throw le}if((te||Date.now()-r>=150)&&w&&(yield{candidates:d.length>0?[{content:{parts:[...d]}}]:[],usageMetadata:b},d=[],r=Date.now(),w=!1),te)break}}};import{Ollama as Ra}from"ollama";var zs=async function*(e,t,n,s,o,l,f,a,m=1,g="Cloud"){let u=[];s&&u.push({role:"system",content:s});for(let y of n){let d=y.role==="user"?"user":"assistant",b="",r=[];if(Array.isArray(y.parts)){b=y.parts.map(w=>w.text||"").filter(Boolean).join(`
604
604
  `);for(let w of y.parts){let A=w.inlineData||w.inline_data;A&&A.data&&r.push(A.data)}}else b=y.text||"";if(b||r.length>0){let w={role:d,content:b};r.length>0&&(w.images=r),u.push(w)}}let h=g==="Local"||!e||e==="LOCAL",i={host:h?process.env.OLLAMA_HOST||"http://127.0.0.1:11434":process.env.OLLAMA_HOST||"https://ollama.com"};!h&&e&&(i.headers={Authorization:"Bearer "+e});let c=new Ra(i),T=[],E=null,k=Date.now(),C=!1,N=Ke("Ollama",t,o),v={Fast:!1,Low:"medium",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},_=N!==null?N==="false"||N===!1?!1:N==="true"||N===!0?!0:N:v[o]!==void 0?v[o]:!0,R={model:t,messages:u,stream:!0,think:_,keep_alive:"10m",options:{temperature:m}},L=await c.chat(R);for await(let y of L){if(a?.aborted)throw new DOMException("The user aborted a request.","AbortError");if(y.message?.thinking&&(T.push({text:y.message.thinking,thought:!0}),C=!0),y.message?.content&&(T.push({text:y.message.content}),C=!0),y.done){let d=y.prompt_cached_count||0;if(!d&&y.prompt_eval_count){let b=y.prompt_eval_duration||0;b>0&&b<5e7&&(d=y.prompt_eval_count)}E={totalTokenCount:(y.prompt_eval_count||0)+(y.eval_count||0),promptTokenCount:y.prompt_eval_count||0,candidatesTokenCount:y.eval_count||0,cachedContentTokenCount:d,thoughtsTokenCount:0},C=!0}(y.done||Date.now()-k>=150&&C)&&(yield{candidates:T.length>0?[{content:{parts:[...T]}}]:[],usageMetadata:E},T=[],k=Date.now(),C=!1)}C&&(T.length>0||E)&&(yield{candidates:T.length>0?[{content:{parts:[...T]}}]:[],usageMetadata:E})};var Xo=async function*(e,t,n,s,o,l,f,a,m=1){let g=[];s&&g.push({role:"system",content:s});for(let d of n){let b=d.role==="user"?"user":"assistant",r="";if(Array.isArray(d.parts))for(let w of d.parts)w.text&&(r+=(r?`
605
605
  `:"")+w.text);else r=d.text||"";g.push({role:b,content:r})}let u=Ke("InferX",t,o),x=u!==null?u:{Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i=t&&t.toLowerCase().includes("qwen3.8-27b")&&u===null,c=t&&(t.toLowerCase().includes("qwen3.8-27b")||t.toLowerCase().includes("qwen3.6-35b-a3b-fp8")),T={model:t,messages:g.filter(d=>d.content&&String(d.content).trim().length>0),stream:!0,stream_options:{include_usage:!0},temperature:m};!i&&x&&(T.stream_options={include_usage:!0},T.reasoning_effort=x);let E=await nt("https://model.inferx.net/endpoints/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(T),signal:a});if(!E.ok){let d=await E.text().catch(()=>""),b="";try{let r=JSON.parse(d);b=r.error?.message||r.error?.detail||r.message||r.detail||(typeof r.error=="string"?r.error:"")||(d&&d!=="{}"?d:"")}catch{b=d}throw(!b||b==="{}")&&(b=E.statusText||"Unknown error"),new Error(`InferX Error (${E.status}): ${b}`)}let k=E.body.getReader(),C=new TextDecoder,N="",v=[],_=null,R=Date.now(),L=!1,y=!0;for(;;){let{done:d,value:b}=await k.read();if(d){L&&(v.length>0||_)&&(yield{candidates:v.length>0?[{content:{parts:v}}]:[],usageMetadata:_});break}N+=C.decode(b,{stream:!0});let r=N.split(`
@@ -610,12 +610,12 @@ ${h[7]}
610
610
  `);v=r.pop();for(let w of r){let A=w.trim();if(!A||!A.startsWith("data: "))continue;let O=!1;if(A==="data: [DONE]")O=!0;else try{let H=JSON.parse(A.substring(6)),P=H.choices?.[0]?.delta,M=H.usage;if(H.choices?.[0]?.finish_reason&&(O=!0),M&&(R={totalTokenCount:M.total_tokens||(M.prompt_tokens||0)+(M.completion_tokens||0),promptTokenCount:M.prompt_tokens||0,candidatesTokenCount:M.completion_tokens||0,cachedContentTokenCount:M.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:M.completion_tokens_details?.reasoning_tokens||M.reasoning_tokens||0},y=!0),P){let te=P.reasoning_content||P.reasoning||P.thinking||null;!te&&Array.isArray(P.reasoning_details)&&P.reasoning_details.length>0&&(te=P.reasoning_details.map(le=>typeof le=="string"?le:le?.text||"").filter(Boolean).join("")),te&&(_.push({text:te,thought:!0}),y=!0),P.content&&(_.push({text:P.content}),y=!0)}}catch{}if((O||Date.now()-L>=150)&&y&&(yield{candidates:_.length>0?[{content:{parts:[..._]}}]:[],usageMetadata:R},_=[],L=Date.now(),y=!1),O)break}Date.now()-L>=150&&y&&(yield{candidates:_.length>0?[{content:{parts:[..._]}}]:[],usageMetadata:R},_=[],L=Date.now(),y=!1)}};var ns=async function*(e,t,n,s,o,l,f,a,m=1){let g=[];s&&g.push({role:"system",content:s});for(let d of n){let b=d.role==="user"?"user":"assistant",r=[];if(Array.isArray(d.parts)){for(let w of d.parts)if(w.text)r.push({type:"text",text:w.text});else if(w.inlineData&&f){let A=w.inlineData.mimeType,O=w.inlineData.data;A.startsWith("image/")&&r.push({type:"image_url",image_url:{url:`data:${A};base64,${O}`}})}}else{let w=d.text||"";w&&r.push({type:"text",text:w})}g.push({role:b,content:r.length===1&&r[0].type==="text"?r[0].text:r})}let u=Ke("ExpLabs",t,o),x=u!==null?u:{Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:g,stream:!0,stream_options:{include_usage:!0},temperature:m};x&&(i.reasoning_effort=x);let c=process.env.EXPLABS_URL||process.env.EXPERIENTIALLABS_URL||"https://api.experientiallabs.ai/v1/chat/completions",T={"Content-Type":"application/json"},E=e||process.env.EXPLABS_API_KEY||process.env.EXPERIENTIALLABS_API_KEY||"";T.Authorization=`Bearer ${E}`;let k=await nt(c,{method:"POST",headers:T,body:JSON.stringify(i),signal:a});if(!k.ok){let d=await k.json().catch(()=>({}));throw new Error(`Experiential Labs Error (${k.status}): ${d.error?.message||d.message||k.statusText}`)}let C=k.body.getReader(),N=new TextDecoder,v="",_=[],R=null,L=Date.now(),y=!1;for(;;){let{done:d,value:b}=await C.read();if(d){y&&(_.length>0||R)&&(yield{candidates:_.length>0?[{content:{parts:_}}]:[],usageMetadata:R});break}v+=N.decode(b,{stream:!0});let r=v.split(`
611
611
  `);v=r.pop();for(let w of r){let A=w.trim();if(!A||!A.startsWith("data: "))continue;let O=!1;if(A==="data: [DONE]")O=!0;else try{let H=JSON.parse(A.substring(6)),P=H.choices?.[0]?.delta,M=H.usage;if(M&&(R={totalTokenCount:M.total_tokens||(M.prompt_tokens||0)+(M.completion_tokens||0),promptTokenCount:M.prompt_tokens||0,candidatesTokenCount:M.completion_tokens||0,cachedContentTokenCount:M.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:M.completion_tokens_details?.reasoning_tokens||M.reasoning_tokens||0},y=!0),P){let te=P.reasoning_content||P.reasoning||null;!te&&Array.isArray(P.reasoning_details)&&P.reasoning_details.length>0&&(te=P.reasoning_details.map(le=>le.text||"").filter(Boolean).join("")),te&&(_.push({text:te,thought:!0}),y=!0),P.content&&(_.push({text:P.content}),y=!0)}}catch{}if((O||Date.now()-L>=150)&&y&&(yield{candidates:_.length>0?[{content:{parts:[..._]}}]:[],usageMetadata:R},_=[],L=Date.now(),y=!1),O)break}Date.now()-L>=150&&y&&(yield{candidates:_.length>0?[{content:{parts:[..._]}}]:[],usageMetadata:R},_=[],L=Date.now(),y=!1)}};var Js=async function*(e,t,n,s,o,l,f,a,m=1){let g=[];s&&g.push({role:"system",content:s});for(let d of n){let b=d.role==="user"?"user":"assistant",r=[];if(Array.isArray(d.parts)){for(let w of d.parts)if(w.text)r.push({type:"text",text:w.text});else if(w.inlineData&&f){let A=w.inlineData.mimeType,O=w.inlineData.data;A.startsWith("image/")&&r.push({type:"image_url",image_url:{url:`data:${A};base64,${O}`}})}}else{let w=d.text||"";w&&r.push({type:"text",text:w})}g.push({role:b,content:r.length===1&&r[0].type==="text"?r[0].text:r})}let u=Ke("TokenHarbor",t,o),x=u!==null?u:{Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:g,stream:!0,stream_options:{include_usage:!0},temperature:m};x&&(i.reasoning_effort=x);let c=process.env.TOKENHARBOR_URL||process.env.TOKEN_HARBOR_URL||"https://tokenharbor.ai/v1/chat/completions",T={"Content-Type":"application/json","X-Title":"Flux-Flow","User-Agent":"Flux-Flow","HTTP-Referer":"https://fluxflow-cli.onrender.com/"},E=e||process.env.TOKENHARBOR_API_KEY||process.env.TOKEN_HARBOR_API_KEY||"";T.Authorization=`Bearer ${E}`;let k=await nt(c,{method:"POST",headers:T,body:JSON.stringify(i),signal:a});if(!k.ok){let d=await k.json().catch(()=>({}));throw new Error(`Token Harbor Error (${k.status}): ${d.error?.message||d.message||k.statusText}`)}let C=k.body.getReader(),N=new TextDecoder,v="",_=[],R=null,L=Date.now(),y=!1;for(;;){let{done:d,value:b}=await C.read();if(d){y&&(_.length>0||R)&&(yield{candidates:_.length>0?[{content:{parts:_}}]:[],usageMetadata:R});break}v+=N.decode(b,{stream:!0});let r=v.split(`
612
612
  `);v=r.pop();for(let w of r){let A=w.trim();if(!A||!A.startsWith("data: "))continue;let O=!1;if(A==="data: [DONE]")O=!0;else try{let H=JSON.parse(A.substring(6)),P=H.choices?.[0]?.delta,M=H.usage;if(M&&(R={totalTokenCount:M.total_tokens||(M.prompt_tokens||0)+(M.completion_tokens||0),promptTokenCount:M.prompt_tokens||0,candidatesTokenCount:M.completion_tokens||0,cachedContentTokenCount:M.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:M.completion_tokens_details?.reasoning_tokens||M.reasoning_tokens||0},y=!0),P){let te=P.reasoning_content||P.reasoning||null;!te&&Array.isArray(P.reasoning_details)&&P.reasoning_details.length>0&&(te=P.reasoning_details.map(le=>le.text||"").filter(Boolean).join("")),te&&(_.push({text:te,thought:!0}),y=!0),P.content&&(_.push({text:P.content}),y=!0)}}catch{}if((O||Date.now()-L>=150)&&y&&(yield{candidates:_.length>0?[{content:{parts:[..._]}}]:[],usageMetadata:R},_=[],L=Date.now(),y=!1),O)break}Date.now()-L>=150&&y&&(yield{candidates:_.length>0?[{content:{parts:[..._]}}]:[],usageMetadata:R},_=[],L=Date.now(),y=!1)}};var Xs=async function*(e,t,n,s,o,l,f,a,m=1){let g=[];s&&g.push({role:"system",content:s});for(let d of n){let b=d.role==="user"?"user":"assistant",r=[];if(Array.isArray(d.parts)){for(let w of d.parts)if(w.text)r.push({type:"text",text:w.text});else if(w.inlineData&&f){let A=w.inlineData.mimeType,O=w.inlineData.data;A.startsWith("image/")&&r.push({type:"image_url",image_url:{url:`data:${A};base64,${O}`}})}}else{let w=d.text||"";w&&r.push({type:"text",text:w})}g.push({role:b,content:r.length===1&&r[0].type==="text"?r[0].text:r})}let u=Ke("APInex",t,o),x=u!==null?u:{Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:g,stream:!0,stream_options:{include_usage:!0},temperature:m};x&&(i.reasoning_effort=x);let c=process.env.APINEX_URL||"https://api.apinex.bond/v1/chat/completions",T={"Content-Type":"application/json","X-Title":"Flux-Flow","User-Agent":"Flux-Flow","HTTP-Referer":"https://fluxflow-cli.onrender.com/"},E=e||process.env.APINEX_API_KEY||"";T.Authorization=`Bearer ${E}`;let k=await nt(c,{method:"POST",headers:T,body:JSON.stringify(i),signal:a});if(!k.ok){let d=await k.json().catch(()=>({}));throw new Error(`APInex Error (${k.status}): ${d.error?.message||d.message||k.statusText}`)}let C=k.body.getReader(),N=new TextDecoder,v="",_=[],R=null,L=Date.now(),y=!1;for(;;){let{done:d,value:b}=await C.read();if(d){y&&(_.length>0||R)&&(yield{candidates:_.length>0?[{content:{parts:_}}]:[],usageMetadata:R});break}v+=N.decode(b,{stream:!0});let r=v.split(`
613
- `);v=r.pop();for(let w of r){let A=w.trim();if(!A||!A.startsWith("data: "))continue;let O=!1;if(A==="data: [DONE]")O=!0;else try{let H=JSON.parse(A.substring(6)),P=H.choices?.[0]?.delta,M=H.usage;if(M&&(R={totalTokenCount:M.total_tokens||(M.prompt_tokens||0)+(M.completion_tokens||0),promptTokenCount:M.prompt_tokens||0,candidatesTokenCount:M.completion_tokens||0,cachedContentTokenCount:M.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:M.completion_tokens_details?.reasoning_tokens||M.reasoning_tokens||0},y=!0),P){let te=P.reasoning_content||P.reasoning||null;!te&&Array.isArray(P.reasoning_details)&&P.reasoning_details.length>0&&(te=P.reasoning_details.map(le=>le.text||"").filter(Boolean).join("")),te&&(_.push({text:te,thought:!0}),y=!0),P.content&&(_.push({text:P.content}),y=!0)}}catch{}if((O||Date.now()-L>=150)&&y&&(yield{candidates:_.length>0?[{content:{parts:[..._]}}]:[],usageMetadata:R},_=[],L=Date.now(),y=!1),O)break}Date.now()-L>=150&&y&&(yield{candidates:_.length>0?[{content:{parts:[..._]}}]:[],usageMetadata:R},_=[],L=Date.now(),y=!1)}};var Ma=/```[\s\S]*?```/g,Ia=/```[\s\S]*$/g,Oa=/`[^`]+`/g,Da=/^\|.*\|$/gm,La=/^[^\w]+|[^\w]+$/g,Pa=/[^a-z0-9]/gi,yo=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,$a=/\[\s*(?:tool:functions\.|agent:generalist\.)([a-z0-9_]+)\s*\(/gi,Na=/(?:path|targetFile|TargetFile|directory|keyword|id|taskId|title|task)\s*=\s*\\?["']?([^\\"' \),]+)/,Wn=/["']/g,$r=/\\/g,Fa=/<\|channel>thought/gi,Ba=/<channel\|>/gi,Ua=e=>typeof e!="string"?e:e.replace(Fa,"<think>").replace(Ba,"</think>"),sf=/^\s*(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\]|$)/i,Wa=(e,t)=>{let n=!1;for(let s=0;s<t;s++)e[s]==="`"&&(n=!n);return n},Ha=e=>{let t=/(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\])/gi,n;for(;(n=t.exec(e))!==null;)if(!Wa(e,n.index))return{index:n.index,length:n[0].length};return{index:-1,length:0}},Qs=e=>{if(!e||typeof e!="string")return null;let t=e.match(/^\s*(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought|\[(think|thought|thoughts)\])/i);if(!t)return null;let n=t.index+t[0].length,s=e.substring(n),o=Ha(s);if(o.index!==-1){let l=n+o.index+o.length;return{fullBlock:e.substring(0,l),innerContent:s.substring(0,o.index),remainingText:e.substring(l)}}return{fullBlock:e,innerContent:s,remainingText:""}},qt=e=>{if(!e||typeof e!="string")return e;let t=Qs(e);return t?t.remainingText.trimStart():e};var Gr=/`[^`]*`/g,jr=/`[^`]*$/,Nr=/<\|\s*tool_call_begin\s*\|>\s*(?:(?:tool|functions)\b[\s._]*)*([a-zA-Z0-9_]+)(?::\d+)?\s*<\|\s*tool_call_argument_begin\s*\|>([\s\S]*?)<\|\s*tool_call_end\s*\|>/gi,Ga=/"([^"]+)"\s*:\s*(?:"([^"]*)"|(\d+)|true|false|null)/g,Fr=/<\|\s*tool_calls_section_begin\s*\|>/gi,Br=/<\|\s*tool_calls_section_end\s*\|>/gi,ja=/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi;var Ur=e=>!e||typeof e!="string"?e:e.replace(/(```[\s\S]*?```|`[^`]*`)|(<(?:\w+)(?:[^>]*)>\r?\n?|\r?\n?<\/\w+(?:[^>]*)>)/gi,(t,n)=>n||""),Vr=e=>{if(!e||typeof e!="string")return e;let t=xo(e);if(!t||t.length===0)return e;let n=t[t.length-1];if(!n.fullMatch)return e;let s=e.lastIndexOf(n.fullMatch);if(s===-1)return e;let o=s+n.fullMatch.length;return e.substring(0,o).trimEnd()},ei=null,os={},Hn={key:null,value:null},Yt=e=>e&&e.replace(/(?:(\x1b\[\d+m))?([✔✘✖🔍📖→➕↻↷•🛇])(?:(\x1b\[\d+m))?\s*\b(Clicked|Dragged|Scrolled|Typed|Pressed Key|Recaptured Screen|Created|Read Skill|Read Documentation|Searched Documentation|Read|Edited|Viewed|Processed|Auto-Read|Skipped|List|Generated|Written|Searched|AI Search|Get Map|Write Canceled|Resolved Sub-Agent Query|Edit Canceled|Write Cancelled|Edit Denied|Visited|Updated|Reviewed|Delegated|Background|Checked|Indexed|Analyzed|Browsed|Elevating SubAgent|Checking SubAgent Work|Started Generalist|Called Generalist|Steered|Unsupported Modality|Awaiting|Cancelled|Aligning Moon Phase|Contemplating Existence|Staring At Void|Rollback Point Checked|Emergency Rollback Failed|Emergency Rollback|Delaying Professionally|Negotiating With Electrons|Touching Grass (virtually)|Panicking Softly|Rethinking Career Choices|Loading Cat Videos|Giving Up Entirely|Summoning Braincell #2|Pretending To Be Busy|Waiting For Motivation DLC|Rotating Internal Screaming|Downloading More RAM|Feeding The Hamsters|Gaslighting Scheduler|Performing Dramatic Pause|Buffering Social Energy|Calculating Regret|Reading Terms And Conditions|Becoming Sentient Briefly|Execution Error|Loop Detected|Contacting Ancestors)\b/ig,(t,n,s,o,l)=>`${n||""}${s}${o||""} \x1B[95m${l}\x1B[0m`),Va=async(e,t=8,n=1e3,s=8e3,o=null)=>{let l=0;for(;;){if(o?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{return await e()}catch(f){if(o?.aborted||f?.name==="AbortError"||f?.message==="Subagent task was cancelled."||(l++,l>=t))throw f;let a=Math.min(n*Math.pow(2,l-1),s);await new Promise((m,g)=>{let u=setTimeout(m,a);o&&o.addEventListener("abort",()=>{clearTimeout(u),g(new DOMException("The user aborted a request.","AbortError"))})})}}},kt=!1;var Ka=e=>{let t=e.filter(o=>(o.role==="user"||o.role==="agent"||o.role==="system")&&o.role!=="think"&&!o.isVisualFeedback&&!o.isMeta&&!o.isTerminalRecord&&!(o.text&&o.text.includes("[TERMINAL_RECORD]"))&&!String(o.id).startsWith("welcome")).map((o,l,f)=>{let a=o.fullText||o.text||"";if(o.role==="user"&&l<f.length-1)if(a.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")){let m=a.indexOf("**CONTEXT SUMMARY OF PREVIOUS TURNS");if(m!==-1){let u=a.substring(0,m).lastIndexOf("[SYSTEM METADATA]");u!==-1?a=a.substring(u).trim():a=a.substring(m).trim()}}else{let m=a.lastIndexOf("[USER]"),g=a.lastIndexOf("[USER PROMPT]");m!==-1?a=a.substring(m+6).trim():g!==-1&&(a=a.substring(g).trim())}return{...o,text:a}}),n=[],s=0;for(;s<t.length;){let o=t[s];if(o.role==="user")n.push(o),s++;else{let l=[];for(;s<t.length&&t[s].role!=="user";)l.push(t[s]),s++;let f=[],a=[],m=!1,g=()=>{f.length>0&&(n.push({role:"agent",text:"combined"}),f=[]),a.length>0&&(n.push({role:"system",text:"combined"}),a=[]),m=!1};l.forEach(u=>{let h=u.role==="system"&&(u.text?.startsWith("[TOOL RESULT]")||u.text?.startsWith("SUCCESS:")||u.text?.startsWith("ERROR:")||u.fullText?.startsWith("[TOOL RESULT]")||u.fullText?.startsWith("SUCCESS:")||u.fullText?.startsWith("ERROR:")),x=u.fullText||u.text||"",i=x.trim();if(!(!i&&!u.binaryPart)){if(h)a.push(i);else if(u.role==="agent"){!m&&a.length>0&&g();let c=x.endsWith(`
613
+ `);v=r.pop();for(let w of r){let A=w.trim();if(!A||!A.startsWith("data: "))continue;let O=!1;if(A==="data: [DONE]")O=!0;else try{let H=JSON.parse(A.substring(6)),P=H.choices?.[0]?.delta,M=H.usage;if(M&&(R={totalTokenCount:M.total_tokens||(M.prompt_tokens||0)+(M.completion_tokens||0),promptTokenCount:M.prompt_tokens||0,candidatesTokenCount:M.completion_tokens||0,cachedContentTokenCount:M.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:M.completion_tokens_details?.reasoning_tokens||M.reasoning_tokens||0},y=!0),P){let te=P.reasoning_content||P.reasoning||null;!te&&Array.isArray(P.reasoning_details)&&P.reasoning_details.length>0&&(te=P.reasoning_details.map(le=>le.text||"").filter(Boolean).join("")),te&&(_.push({text:te,thought:!0}),y=!0),P.content&&(_.push({text:P.content}),y=!0)}}catch{}if((O||Date.now()-L>=150)&&y&&(yield{candidates:_.length>0?[{content:{parts:[..._]}}]:[],usageMetadata:R},_=[],L=Date.now(),y=!1),O)break}Date.now()-L>=150&&y&&(yield{candidates:_.length>0?[{content:{parts:[..._]}}]:[],usageMetadata:R},_=[],L=Date.now(),y=!1)}};var Ma=/```[\s\S]*?```/g,Ia=/```[\s\S]*$/g,Oa=/`[^`]+`/g,Da=/^\|.*\|$/gm,La=/^[^\w]+|[^\w]+$/g,Pa=/[^a-z0-9]/gi,yo=/\[\s*tool:(?:functions\.)?([a-z0-9_]+)\s*\(/gi,$a=/\[\s*(?:tool:(?:functions\.)?|agent:generalist\.)([a-z0-9_]+)\s*\(/gi,Na=/(?:path|targetFile|TargetFile|directory|keyword|id|taskId|title|task)\s*=\s*\\?["']?([^\\"' \),]+)/,Wn=/["']/g,$r=/\\/g,Fa=/<\|channel>thought/gi,Ba=/<channel\|>/gi,Ua=e=>typeof e!="string"?e:e.replace(Fa,"<think>").replace(Ba,"</think>"),sf=/^\s*(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\]|$)/i,Wa=(e,t)=>{let n=!1;for(let s=0;s<t;s++)e[s]==="`"&&(n=!n);return n},Ha=e=>{let t=/(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\])/gi,n;for(;(n=t.exec(e))!==null;)if(!Wa(e,n.index))return{index:n.index,length:n[0].length};return{index:-1,length:0}},Qs=e=>{if(!e||typeof e!="string")return null;let t=e.match(/^\s*(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought|\[(think|thought|thoughts)\])/i);if(!t)return null;let n=t.index+t[0].length,s=e.substring(n),o=Ha(s);if(o.index!==-1){let l=n+o.index+o.length;return{fullBlock:e.substring(0,l),innerContent:s.substring(0,o.index),remainingText:e.substring(l)}}return{fullBlock:e,innerContent:s,remainingText:""}},qt=e=>{if(!e||typeof e!="string")return e;let t=Qs(e);return t?t.remainingText.trimStart():e};var Gr=/`[^`]*`/g,jr=/`[^`]*$/,Nr=/<\|\s*tool_call_begin\s*\|>\s*(?:(?:tool|functions)\b[\s._]*)*([a-zA-Z0-9_]+)(?::\d+)?\s*<\|\s*tool_call_argument_begin\s*\|>([\s\S]*?)<\|\s*tool_call_end\s*\|>/gi,Ga=/"([^"]+)"\s*:\s*(?:"([^"]*)"|(\d+)|true|false|null)/g,Fr=/<\|\s*tool_calls_section_begin\s*\|>/gi,Br=/<\|\s*tool_calls_section_end\s*\|>/gi,ja=/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi;var Ur=e=>!e||typeof e!="string"?e:e.replace(/(```[\s\S]*?```|`[^`]*`)|(<(?:\w+)(?:[^>]*)>\r?\n?|\r?\n?<\/\w+(?:[^>]*)>)/gi,(t,n)=>n||""),Vr=e=>{if(!e||typeof e!="string")return e;let t=xo(e);if(!t||t.length===0)return e;let n=t[t.length-1];if(!n.fullMatch)return e;let s=e.lastIndexOf(n.fullMatch);if(s===-1)return e;let o=s+n.fullMatch.length;return e.substring(0,o).trimEnd()},ei=null,os={},Hn={key:null,value:null},Yt=e=>e&&e.replace(/(?:(\x1b\[\d+m))?([✔✘✖🔍📖→➕↻↷•🛇])(?:(\x1b\[\d+m))?\s*\b(Clicked|Dragged|Scrolled|Typed|Pressed Key|Recaptured Screen|Created|Read Skill|Read Documentation|Searched Documentation|Read|Edited|Viewed|Processed|Auto-Read|Skipped|List|Generated|Written|Searched|AI Search|Get Map|Write Canceled|Resolved Sub-Agent Query|Edit Canceled|Write Cancelled|Edit Denied|Visited|Updated|Reviewed|Delegated|Background|Checked|Indexed|Analyzed|Browsed|Elevating SubAgent|Checking SubAgent Work|Started Generalist|Called Generalist|Steered|Unsupported Modality|Awaiting|Cancelled|Aligning Moon Phase|Contemplating Existence|Staring At Void|Rollback Point Checked|Emergency Rollback Failed|Emergency Rollback|Delaying Professionally|Negotiating With Electrons|Touching Grass (virtually)|Panicking Softly|Rethinking Career Choices|Loading Cat Videos|Giving Up Entirely|Summoning Braincell #2|Pretending To Be Busy|Waiting For Motivation DLC|Rotating Internal Screaming|Downloading More RAM|Feeding The Hamsters|Gaslighting Scheduler|Performing Dramatic Pause|Buffering Social Energy|Calculating Regret|Reading Terms And Conditions|Becoming Sentient Briefly|Execution Error|Loop Detected|Contacting Ancestors)\b/ig,(t,n,s,o,l)=>`${n||""}${s}${o||""} \x1B[95m${l}\x1B[0m`),Va=async(e,t=8,n=1e3,s=8e3,o=null)=>{let l=0;for(;;){if(o?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{return await e()}catch(f){if(o?.aborted||f?.name==="AbortError"||f?.message==="Subagent task was cancelled."||(l++,l>=t))throw f;let a=Math.min(n*Math.pow(2,l-1),s);await new Promise((m,g)=>{let u=setTimeout(m,a);o&&o.addEventListener("abort",()=>{clearTimeout(u),g(new DOMException("The user aborted a request.","AbortError"))})})}}},kt=!1;var Ka=e=>{let t=e.filter(o=>(o.role==="user"||o.role==="agent"||o.role==="system")&&o.role!=="think"&&!o.isVisualFeedback&&!o.isMeta&&!o.isTerminalRecord&&!(o.text&&o.text.includes("[TERMINAL_RECORD]"))&&!String(o.id).startsWith("welcome")).map((o,l,f)=>{let a=o.fullText||o.text||"";if(o.role==="user"&&l<f.length-1)if(a.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")){let m=a.indexOf("**CONTEXT SUMMARY OF PREVIOUS TURNS");if(m!==-1){let u=a.substring(0,m).lastIndexOf("[SYSTEM METADATA]");u!==-1?a=a.substring(u).trim():a=a.substring(m).trim()}}else{let m=a.lastIndexOf("[USER]"),g=a.lastIndexOf("[USER PROMPT]");m!==-1?a=a.substring(m+6).trim():g!==-1&&(a=a.substring(g).trim())}return{...o,text:a}}),n=[],s=0;for(;s<t.length;){let o=t[s];if(o.role==="user")n.push(o),s++;else{let l=[];for(;s<t.length&&t[s].role!=="user";)l.push(t[s]),s++;let f=[],a=[],m=!1,g=()=>{f.length>0&&(n.push({role:"agent",text:"combined"}),f=[]),a.length>0&&(n.push({role:"system",text:"combined"}),a=[]),m=!1};l.forEach(u=>{let h=u.role==="system"&&(u.text?.startsWith("[TOOL RESULT]")||u.text?.startsWith("SUCCESS:")||u.text?.startsWith("ERROR:")||u.fullText?.startsWith("[TOOL RESULT]")||u.fullText?.startsWith("SUCCESS:")||u.fullText?.startsWith("ERROR:")),x=u.fullText||u.text||"",i=x.trim();if(!(!i&&!u.binaryPart)){if(h)a.push(i);else if(u.role==="agent"){!m&&a.length>0&&g();let c=x.endsWith(`
614
614
  `),T=i.toLowerCase().includes("tool:functions.")||i.toLowerCase().includes("agent:generalist.");f.push(i),T&&c?m=!0:m=!1}}}),g()}}return n.length},Ya=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),rf=()=>{kt=!0},af=()=>kt,Zs={write_file:"Writing",update_file:"Editing",read_folder:"Reading",view_file:"Reading",exec_command:"Executing Command",web_search:"Searching",web_scrape:"Reading",memory:"Updating Memory",search_keyword:"Searching",file_map:"Generating Map",ask:"User Input",write_pdf:"Creating",write_docx:"Creating",generate_image:"Generating",todo:"Planning",Todo:"Planning",goal:"Planning",Goal:"Planning",invoke_sync:"Sub-Agent Working",invoke:"Starting Agent",get_progress:"Checking Progress",cancel:"Cancelling",await:"Waiting",EmergencyRollback:"Don't Panic. Lookin' into it",answer:"Answering Sub-Agent",Answer:"Answering Sub-Agent",steer:"Steering Sub-Agent",Steer:"Steering Sub-Agent",Click:"Clicking",click:"Clicking",Drag:"Dragging",drag:"Dragging",Scroll:"Scrolling",scroll:"Scrolling",KeyboardTyping:"Typing",keyboard_typing:"Typing",KeyPress:"Pressing Key",key_press:"Pressing Key",RecaptureScreen:"Recapturing Screen",recapture_screen:"Recapturing Screen"},Gn=(e,t)=>{try{let n=oe(t),s=e.toLowerCase().replace(/_/g,"");if(s==="invokesync"||s==="invoke")return n.title||(n.task?n.task.substring(0,30):null);if(s==="getprogress"||s==="cancel"||s==="steer"||s==="steersubagent")return n.id||n.taskId;let o=n.path||n.targetFile||n.TargetFile||n.directory;return o?ee.basename(o.replace(/["']/g,"").replace(/\\/g,"/")):null}catch{return null}},ti=e=>e?new Hr({apiKey:e}):ei,lf=async(e,t,n,s,o={})=>{let{onStatus:a,onMemoryUpdated:m,onBackgroundIncrement:g}=o,{profile:u,thinkingLevel:h,mode:x,janitorModel:i,chatId:c,systemSettings:T,sessionStats:E,aiProvider:k="Google",apiKey:C}=e,N=process.env.NVIDIA_BASE_URL||k==="Ollama"||k==="InferX"||k==="SenseNova"||k==="AIHubMix"||k==="Poolside"||k==="9router"||k==="ExpLabs"||k==="ExperientialLabs"?!1:T?.memory!==!1,_=Et(Bn,[]).map(D=>`- [${D.id}]: ${D.memory}`).join(`
615
- `),R=s.slice(0,-1).filter(D=>D.text&&!D.text.includes("[TOOL RESULT]")&&!D.text.includes("OBSERVATION:")&&!D.text.startsWith("[TERMINAL_RECORD]")&&!D.isTerminalRecord&&!D.isMeta&&!D.isLogo&&!String(D.id).startsWith("welcome")&&!String(D.id).startsWith("logo")).slice(-14).map(D=>{let F=qt(Ya(D.text)).replace(/\[tool:functions\..*?\]/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[METADATA \(PRIORITY: DYNAMIC\)\] Time: ([^|\n]+)/g,(Y,de)=>`[METADATA (PRIORITY: DYNAMIC)] Time: ${de.replace(/:\d{2}/g,"")}`).replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[TOOL RESULTS\]/g,"").replace(/\[tool results\]/g,"").replace(/\r?\n\r?\n/g,`
615
+ `),R=s.slice(0,-1).filter(D=>D.text&&!D.text.includes("[TOOL RESULT]")&&!D.text.includes("OBSERVATION:")&&!D.text.startsWith("[TERMINAL_RECORD]")&&!D.isTerminalRecord&&!D.isMeta&&!D.isLogo&&!String(D.id).startsWith("welcome")&&!String(D.id).startsWith("logo")).slice(-14).map(D=>{let F=qt(Ya(D.text)).replace(/\[tool:(?:functions\.)?.*?\]/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[METADATA \(PRIORITY: DYNAMIC\)\] Time: ([^|\n]+)/g,(Y,de)=>`[METADATA (PRIORITY: DYNAMIC)] Time: ${de.replace(/:\d{2}/g,"")}`).replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[TOOL RESULTS\]/g,"").replace(/\[tool results\]/g,"").replace(/\r?\n\r?\n/g,`
616
616
  `).replace(/\n\n/g,`
617
- `).replace(/\\n\\n/g,"").trim(),Ae=D.role==="user"?8192:32768,z=F.substring(0,Ae);F.length>Ae&&(z+=`
618
- ... (truncated) ...`);let B=D.role==="user"?z.startsWith("[USER]")?"":"[USER]: ":z.startsWith("[AGENT]")?"":"[AGENT]: ";return{role:D.role==="user"?"user":"model",parts:[{text:`${B}${z}`}]}}),L=s.filter(D=>D.role==="user").length===1,y=t.includes("[TITLE-UPDATE]"),d=Math.random()<.8,b=L||y||d,r=qt(n).trim(),w=lr(_,N,b),A=`${r.replace(/\[tool:functions\..*?\]/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[\[TOOL RESULTS\]\]/g,"").replace(/\[tool results\]/g,"").substring(0,32768)}`;A.length>32768&&(A+=`
617
+ `).replace(/\\n\\n/g,"").trim(),Ee=D.role==="user"?8192:32768,z=F.substring(0,Ee);F.length>Ee&&(z+=`
618
+ ... (truncated) ...`);let B=D.role==="user"?z.startsWith("[USER]")?"":"[USER]: ":z.startsWith("[AGENT]")?"":"[AGENT]: ";return{role:D.role==="user"?"user":"model",parts:[{text:`${B}${z}`}]}}),L=s.filter(D=>D.role==="user").length===1,y=t.includes("[TITLE-UPDATE]"),d=Math.random()<.8,b=L||y||d,r=qt(n).trim(),w=lr(_,N,b),A=`${r.replace(/\[tool:(?:functions\.)?.*?\]/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[\[TOOL RESULTS\]\]/g,"").replace(/\[tool results\]/g,"").substring(0,32768)}`;A.length>32768&&(A+=`
619
619
  ... (truncated) ...`);let O=t.replace(/\[Prompted on:.*?\]/g,"").trim();A=A.replace(/\r?\n\r?\n/g,`
620
620
  `).replace(/\n\n/g,`
621
621
  `).replace(/\\n\\n/g,"").trim();let H=new Date,M=`[METADATA] Current date and Time: ${`${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})}`}
@@ -624,11 +624,11 @@ ${h[7]}
624
624
  ${O.length>8192?`... (truncated) ...
625
625
 
626
626
  `:""}
627
- [AGENT (current turn)]: ${A}`;R.push({role:"user",parts:[{text:M}]});let te=await bs("NVIDIA"),J=(await so()).quotas?.providerTiers?.NVIDIA==="Free",re="",De=0,We=N?12:-1;for(;De<=We;)try{if(!await pi("background",e))return;let D="",F=null,Ae=!1,z=k;try{let de=new Promise((ge,me)=>setTimeout(()=>me(new Error("JANITOR_TIMEOUT")),1e4)),Ee=k==="Google"&&De>=0&&De<6&&te&&J,Ce=k==="DeepSeek"&&De<4&&te&&J;Ae=Ee||Ce,z=Ae?"NVIDIA":k;let Ne=(async()=>{if(k==="OpenRouter"){let ge=ue("janitor_open_router"),ie=Jo(C,ge,R,w,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),Ot=await ie.next();return{iterator:ie,firstResult:Ot}}else if(k==="DeepSeek"&&!Ae){let me=Yo(C,ue("deepseek_fast_fallback"),R,w,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),ie=await me.next();return{iterator:me,firstResult:ie}}else if(k==="Mistral"&&!Ae){let me=qo(C,ue("mistral_janitor_fallback"),R,w,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),ie=await me.next();return{iterator:me,firstResult:ie}}else if(k==="NVIDIA"||Ae){let me=zo(Ae?te:C,ue("nvidia_janitor_fallback"),R,w,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),ie=await me.next();return{iterator:me,firstResult:ie}}else if(k==="InferX"){let me=Xo(C,targetModel||ue("inferx_fallback")||"deepseek-v4-flash",R,w,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),ie=await me.next();return{iterator:me,firstResult:ie}}else if(k==="SenseNova"){let me=Qo(C,targetModel||ue("sensenova_fallback")||"sensenova-6.8-flash-lite",R,w,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),ie=await me.next();return{iterator:me,firstResult:ie}}else if(k==="AIHubMix"){let me=Zo(C,targetModel||ue("aihubmix_fallback")||"gpt-4o-mini",R,w,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),ie=await me.next();return{iterator:me,firstResult:ie}}else if(k==="Poolside"){let me=es(C,targetModel||ue("poolside_fallback")||"poolside/laguna-s-2.1",R,w,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),ie=await me.next();return{iterator:me,firstResult:ie}}else if(k==="9router"||k==="9Router"){let me=ts(C,targetModel||ue("9router_fallback")||"z-ai/glm-5.3-flash",R,w,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),ie=await me.next();return{iterator:me,firstResult:ie}}else if(k==="ExpLabs"||k==="ExperientialLabs"){let me=ns(C,targetModel||ue("explabs_fallback")||"deepseek-v4-pro-0813",R,w,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),ie=await me.next();return{iterator:me,firstResult:ie}}else{let ie=(await ti(C).models.generateContentStream({model:i||(De===We?ue("janitor_default"):ue("gemma_janitor_fallback_google")),contents:R,config:{systemInstruction:w,temperature:.7,safetySettings:[{category:On.HARM_CATEGORY_HARASSMENT,threshold:In.BLOCK_NONE},{category:On.HARM_CATEGORY_HATE_SPEECH,threshold:In.BLOCK_NONE},{category:On.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:In.BLOCK_NONE},{category:On.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:In.BLOCK_NONE}],thinkingConfig:{includeThoughts:!1,thinkingLevel:Ze.MINIMAL}}}))[Symbol.asyncIterator](),Ot=await ie.next();return{iterator:ie,firstResult:Ot}}})();if(process.stdout.isTTY){let ie=(await Ss())[c]?.name||"",Ot=ie&&!ie.startsWith("flow-")&&!ie.startsWith("Session ")?ie:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${Ot}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${Ot}\x07`)}let{iterator:vt,firstResult:wn}=await Promise.race([Ne,de]),{value:zt,done:dt}=wn;if(!dt&&zt){let ge=zt.candidates?.[0]?.content?.parts,me=ge?z==="Google"?ge[1]?.text||ge[0]?.text||"":ge.filter(ie=>ie.text&&!ie.thought).map(ie=>ie.text).join(""):typeof zt.text=="function"?zt.text():"";me&&(D+=me),F=zt.usageMetadata;for await(let ie of{[Symbol.asyncIterator]:()=>vt}){let Ot=ie.candidates?.[0]?.content?.parts,jn=Ot?z==="Google"?Ot[1]?.text||Ot[0]?.text||"":Ot.filter(St=>St.text&&!St.thought).map(St=>St.text).join(""):typeof ie.text=="function"?ie.text():"";jn&&(D+=jn),F=ie.usageMetadata}}}catch(de){throw de}if(D){if(re=D,F){let de=F.totalTokenCount||0,Ee=F.cachedContentTokenCount||0,Ce=(F.candidatesTokenCount||0)+(z==="Google"&&F.thoughtsTokenCount||0),Ne=Ae?ue("nvidia_janitor_fallback"):z==="DeepSeek"?ue("deepseek_fast_fallback"):z==="ExpLabs"||z==="ExperientialLabs"?ue("explabs_fallback")||"deepseek-v4-pro-0813":z==="OpenRouter"?ue("janitor_open_router"):i||(De===We?ue("janitor_default"):ue("gemma_janitor_fallback_google"));await Bt("tokens",de,z,Ne),Ee>0&&await Bt("cachedTokens",Ee,z,Ne),Ce>0&&await Bt("candidateTokens",Ce,z,Ne)}}else throw new Error("No synthesis generated by Janitor.");g&&(g(),await Ct("background"));let B=xo(re),Y=!1;for(let de of B){let Ee=de.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(Ee)&&(Y=!0);let Ce={chatId:c,sessionId:c,history:s},Ne=await ho(Ee,de.args,Ce);Ee.toLowerCase()==="memory"&&(de.args.includes("action='user'")||de.args.includes('action="user"'))&&!Ne.startsWith("ERROR")&&(m&&m(),process.stdout.isTTY&&(process.stdout.write("\x1B]0;Memory Updated\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=Memory Updated\x07")),await new Promise(wn=>setTimeout(wn,3e3)))}if(!Y)try{let de=Et(Bn,[]);if(de.length>0){let Ee=[];for(let Ce of de)Ce.score===void 0&&(Ce.score=.5),Ce.score*=.99995,Ce.score<.05&&(Ce.score=0),Ce.score=Math.round(Ce.score*1e5)/1e5,Ce.score>0&&Ee.push(Ce);Jn(Bn,Ee)}}catch{}break}catch(D){De++;let F=new Date().toLocaleString(),Ae=D instanceof Error?(()=>{try{return JSON.parse(JSON.parse(D.message).error.message).error.message}catch{return String(D)}})():String(D);await new Promise(Y=>setTimeout(Y,1e3));let z=ee.join(vn,"janitor");if(Ge.existsSync(z)||Ge.mkdirSync(z,{recursive:!0}),Ge.appendFileSync(ee.join(z,"error.log"),`ERROR [Attempt ${De}/${We+1}] [${F}]: ${Ae}
627
+ [AGENT (current turn)]: ${A}`;R.push({role:"user",parts:[{text:M}]});let te=await bs("NVIDIA"),J=(await so()).quotas?.providerTiers?.NVIDIA==="Free",re="",De=0,We=N?12:-1;for(;De<=We;)try{if(!await pi("background",e))return;let D="",F=null,Ee=!1,z=k;try{let de=new Promise((ge,me)=>setTimeout(()=>me(new Error("JANITOR_TIMEOUT")),1e4)),Ce=k==="Google"&&De>=0&&De<6&&te&&J,ve=k==="DeepSeek"&&De<4&&te&&J;Ee=Ce||ve,z=Ee?"NVIDIA":k;let Ne=(async()=>{if(k==="OpenRouter"){let ge=ue("janitor_open_router"),ie=Jo(C,ge,R,w,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),Ot=await ie.next();return{iterator:ie,firstResult:Ot}}else if(k==="DeepSeek"&&!Ee){let me=Yo(C,ue("deepseek_fast_fallback"),R,w,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),ie=await me.next();return{iterator:me,firstResult:ie}}else if(k==="Mistral"&&!Ee){let me=qo(C,ue("mistral_janitor_fallback"),R,w,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),ie=await me.next();return{iterator:me,firstResult:ie}}else if(k==="NVIDIA"||Ee){let me=zo(Ee?te:C,ue("nvidia_janitor_fallback"),R,w,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),ie=await me.next();return{iterator:me,firstResult:ie}}else if(k==="InferX"){let me=Xo(C,targetModel||ue("inferx_fallback")||"deepseek-v4-flash",R,w,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),ie=await me.next();return{iterator:me,firstResult:ie}}else if(k==="SenseNova"){let me=Qo(C,targetModel||ue("sensenova_fallback")||"sensenova-6.8-flash-lite",R,w,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),ie=await me.next();return{iterator:me,firstResult:ie}}else if(k==="AIHubMix"){let me=Zo(C,targetModel||ue("aihubmix_fallback")||"gpt-4o-mini",R,w,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),ie=await me.next();return{iterator:me,firstResult:ie}}else if(k==="Poolside"){let me=es(C,targetModel||ue("poolside_fallback")||"poolside/laguna-s-2.1",R,w,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),ie=await me.next();return{iterator:me,firstResult:ie}}else if(k==="9router"||k==="9Router"){let me=ts(C,targetModel||ue("9router_fallback")||"z-ai/glm-5.3-flash",R,w,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),ie=await me.next();return{iterator:me,firstResult:ie}}else if(k==="ExpLabs"||k==="ExperientialLabs"){let me=ns(C,targetModel||ue("explabs_fallback")||"deepseek-v4-pro-0813",R,w,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),ie=await me.next();return{iterator:me,firstResult:ie}}else{let ie=(await ti(C).models.generateContentStream({model:i||(De===We?ue("janitor_default"):ue("gemma_janitor_fallback_google")),contents:R,config:{systemInstruction:w,temperature:.7,safetySettings:[{category:On.HARM_CATEGORY_HARASSMENT,threshold:In.BLOCK_NONE},{category:On.HARM_CATEGORY_HATE_SPEECH,threshold:In.BLOCK_NONE},{category:On.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:In.BLOCK_NONE},{category:On.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:In.BLOCK_NONE}],thinkingConfig:{includeThoughts:!1,thinkingLevel:Ze.MINIMAL}}}))[Symbol.asyncIterator](),Ot=await ie.next();return{iterator:ie,firstResult:Ot}}})();if(process.stdout.isTTY){let ie=(await Ss())[c]?.name||"",Ot=ie&&!ie.startsWith("flow-")&&!ie.startsWith("Session ")?ie:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${Ot}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${Ot}\x07`)}let{iterator:vt,firstResult:wn}=await Promise.race([Ne,de]),{value:zt,done:dt}=wn;if(!dt&&zt){let ge=zt.candidates?.[0]?.content?.parts,me=ge?z==="Google"?ge[1]?.text||ge[0]?.text||"":ge.filter(ie=>ie.text&&!ie.thought).map(ie=>ie.text).join(""):typeof zt.text=="function"?zt.text():"";me&&(D+=me),F=zt.usageMetadata;for await(let ie of{[Symbol.asyncIterator]:()=>vt}){let Ot=ie.candidates?.[0]?.content?.parts,jn=Ot?z==="Google"?Ot[1]?.text||Ot[0]?.text||"":Ot.filter(St=>St.text&&!St.thought).map(St=>St.text).join(""):typeof ie.text=="function"?ie.text():"";jn&&(D+=jn),F=ie.usageMetadata}}}catch(de){throw de}if(D){if(re=D,F){let de=F.totalTokenCount||0,Ce=F.cachedContentTokenCount||0,ve=(F.candidatesTokenCount||0)+(z==="Google"&&F.thoughtsTokenCount||0),Ne=Ee?ue("nvidia_janitor_fallback"):z==="DeepSeek"?ue("deepseek_fast_fallback"):z==="ExpLabs"||z==="ExperientialLabs"?ue("explabs_fallback")||"deepseek-v4-pro-0813":z==="OpenRouter"?ue("janitor_open_router"):i||(De===We?ue("janitor_default"):ue("gemma_janitor_fallback_google"));await Bt("tokens",de,z,Ne),Ce>0&&await Bt("cachedTokens",Ce,z,Ne),ve>0&&await Bt("candidateTokens",ve,z,Ne)}}else throw new Error("No synthesis generated by Janitor.");g&&(g(),await Ct("background"));let B=xo(re),Y=!1;for(let de of B){let Ce=de.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(Ce)&&(Y=!0);let ve={chatId:c,sessionId:c,history:s},Ne=await ho(Ce,de.args,ve);Ce.toLowerCase()==="memory"&&(de.args.includes("action='user'")||de.args.includes('action="user"'))&&!Ne.startsWith("ERROR")&&(m&&m(),process.stdout.isTTY&&(process.stdout.write("\x1B]0;Memory Updated\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=Memory Updated\x07")),await new Promise(wn=>setTimeout(wn,3e3)))}if(!Y)try{let de=Et(Bn,[]);if(de.length>0){let Ce=[];for(let ve of de)ve.score===void 0&&(ve.score=.5),ve.score*=.99995,ve.score<.05&&(ve.score=0),ve.score=Math.round(ve.score*1e5)/1e5,ve.score>0&&Ce.push(ve);Jn(Bn,Ce)}}catch{}break}catch(D){De++;let F=new Date().toLocaleString(),Ee=D instanceof Error?(()=>{try{return JSON.parse(JSON.parse(D.message).error.message).error.message}catch{return String(D)}})():String(D);await new Promise(Y=>setTimeout(Y,1e3));let z=ee.join(vn,"janitor");if(je.existsSync(z)||je.mkdirSync(z,{recursive:!0}),je.appendFileSync(ee.join(z,"error.log"),`ERROR [Attempt ${De}/${We+1}] [${F}]: ${Ee}
628
628
 
629
- `),De>We)break;let B=Math.min(750*Math.pow(2,De-1),5e3);await new Promise(Y=>setTimeout(Y,B))}if(De){let D=ee.join(vn,"janitor");Ge.appendFileSync(ee.join(D,"error.log"),`-----------------------------------------------------------------------------
629
+ `),De>We)break;let B=Math.min(750*Math.pow(2,De-1),5e3);await new Promise(Y=>setTimeout(Y,B))}if(De){let D=ee.join(vn,"janitor");je.appendFileSync(ee.join(D,"error.log"),`-----------------------------------------------------------------------------
630
630
 
631
- `)}if(process.stdout.isTTY)try{let Ae=(await Ss())[c]?.name||"",z=Ae&&!Ae.startsWith("flow-")&&!Ae.startsWith("Session ")?Ae:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${z}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${z}\x07`)}catch{process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")}},qa=e=>{let t=qt(e),n=Ts?t:t.replace(Gr,o=>" ".repeat(o.length)).replace(jr,o=>" ".repeat(o.length));yo.lastIndex=0;let s;for(;(s=yo.exec(n))!==null;){let o=s.index+s[0].length-1,l=0,f=null,a=!1,m=!1;for(let g=o;g<n.length;g++){let u=t[g];if(!f&&(u==='"'||u==="'"||u==="`")?(f=u,a=!1):f&&u===f&&!a&&(f=null),!f&&(u==="("?l++:u===")"&&l--,l===0)){let h=g+1;for(;h<n.length&&/\s/.test(n[h]);)h++;if(h<n.length&&n[h]==="]"){m=!0,yo.lastIndex=h+1;break}}u==="\\"?a=!a:a=!1}if(!m)return{inside:!0,toolName:s[1],startIndex:s.index,args:t.substring(s.index+s[0].length)}}return{inside:!1}},Kr=(e,t=!0)=>{let n=yo;n.lastIndex=0;let s="",o=0,l;for(;(l=n.exec(e))!==null;){let f=e.substring(o,l.index);s+=t&&o===0?qt(f):f;let a=l.index+l[0].length-1,m=0,g=null,u=-1;for(let h=a;h<e.length;h++){let x=e[h];if(g){if(x===g){let i=0;for(let c=h-1;c>=0&&e[c]==="\\";c--)i++;i%2===0&&(g=null)}}else if(x==='"'||x==="'"||x==="`")g=x;else if(x==="(")m++;else if(x===")"&&(m--,m===0)){let i=h+1;for(;i<e.length&&/\s/.test(e[i]);)i++;if(i<e.length&&e[i]==="]"){u=i;break}}}if(u!==-1)s+="[tool:functions."+l[1]+"()]",o=u+1,n.lastIndex=o;else{s+="[tool:functions."+l[1]+"(",o=e.length;break}}return o<e.length&&(s+=t&&o===0?qt(e.substring(o)):e.substring(o)),s},za=(e,t,n)=>{let s=yo;s.lastIndex=0;let o="",l=0,f;for(;(f=s.exec(e))!==null;){let a=e.substring(l,f.index);o+=a.replace(t,n);let m=f.index+f[0].length-1,g=0,u=null,h=-1;for(let x=m;x<e.length;x++){let i=e[x];if(u){if(i===u){let c=0;for(let T=x-1;T>=0&&e[T]==="\\";T--)c++;c%2===0&&(u=null)}}else if(i==='"'||i==="'"||i==="`")u=i;else if(i==="(")g++;else if(i===")"&&(g--,g===0)){let c=x+1;for(;c<e.length&&/\s/.test(e[c]);)c++;if(c<e.length&&e[c]==="]"){h=c;break}}}if(h!==-1)o+=e.substring(f.index,h+1),l=h+1,s.lastIndex=l;else{o+=e.substring(f.index),l=e.length;break}}return l<e.length&&(o+=e.substring(l).replace(t,n)),o},Wr=e=>Kr(e,!0),Ja=e=>{if(!e)return e;let t={patchfile:"PatchFile",writefile:"WriteFile",readfile:"ReadFile",viewfile:"ReadFile",run:"Run",execcommand:"Run",searchkeyword:"SearchKeyword",codesearch:"CodeSearch",code_search:"CodeSearch",websearch:"WebSearch",webscrape:"WebScrape",readfolder:"ReadFolder",writepdf:"WritePDF",writedoc:"WriteDoc",writedocx:"WriteDoc",filemap:"FileMap",generateimage:"GenerateImage",todo:"Todo",goal:"Goal",askuser:"AskUser",ask:"AskUser"},n=o=>o.split("_").map(l=>l.charAt(0).toUpperCase()+l.slice(1)).join("");Nr.lastIndex=0;let s=e.replace(Nr,(o,l,f)=>{let a="";try{let u=JSON.parse(f.trim());u&&typeof u=="object"&&(a=Object.entries(u).map(([x,i])=>{let c=typeof i=="string"?i:JSON.stringify(i);return`${x}=${JSON.stringify(c)}`}).join(", "))}catch{let h=[],x=Ga;x.lastIndex=0;let i;for(;(i=x.exec(f))!==null;){let c=i[1],T=i[2]!==void 0?i[2]:i[0].split(":").slice(1).join(":").trim();h.push(`${c}=${JSON.stringify(T)}`)}h.length>0?a=h.join(", "):a=f.trim()}let m=l.toLowerCase().replace(/_/g,"");return`[tool:functions.${t[m]||n(l)}(${a})]`});return Fr.lastIndex=0,Br.lastIndex=0,s=s.replace(Fr,""),s=s.replace(Br,""),s},Xa=/(?:path|query|url|keyword|command|method|title|task|id)\s*=\s*['"`]?\s*\.\.\.\s*['"`]?/i,Qa=/^['"`]?\s*\.\.\.\s*['"`]?$/,kn=e=>{if(e==null)return!1;let t=String(e).trim();return t==="..."||t==="\u2026"||Qa.test(t)},xo=e=>{if(!e)return[];let t=Ja(e),n=qt(t),s=[],o=Ts?n:n.replace(Gr,a=>" ".repeat(a.length)).replace(jr,a=>" ".repeat(a.length)),l=$a;l.lastIndex=0;let f;for(;(f=l.exec(o))!==null;){let a=f[1],m=f.index+f[0].length-1,g=0,u=null,h=-1,x=-1;for(let i=m;i<o.length;i++){let c=n[i];if(u){if(c===u){let T=0;for(let E=i-1;E>=0&&n[E]==="\\";E--)T++;T%2===0&&(u=null)}}else if(c==='"'||c==="'"||c==="`")u=c;else if(c==="(")g++;else if(c===")"&&(g--,g===0)){x=i;let T=i+1;for(;T<o.length&&/\s/.test(o[T]);)T++;if(T<o.length&&o[T]==="]"){h=T;break}}}if(h!==-1){let i=n.substring(m+1,x),c=n.substring(f.index,h+1),T=oe(i);kn(T.path)||kn(T.query)||kn(T.url)||kn(T.keyword)||kn(T.command)||kn(T.method)||kn(T.title)||kn(T.task)||kn(T.id)||Xa.test(i)||s.push({fullMatch:c,toolName:a.trim(),args:i.trim()}),l.lastIndex=h+1}}return s},cf=(e,t={})=>{if(!e)return null;if(os=t,ei=new Hr({apiKey:e}),!globalThis.__perfCleanupInstalled){globalThis.__perfCleanupInstalled=!0,setInterval(()=>{typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks())},6e4);let n=globalThis.fetch;globalThis.fetch=async(...s)=>{try{let o=await n(...s);return typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),o}catch(o){throw typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),o}}}},ss=async(e,t,n,s,o="Fast",l=.75,f="agent")=>Va(async()=>{let{aiProvider:a="Google",apiKey:m,mode:g}=e,u="",h=null,x=typeof n=="string"?[{role:"user",parts:[{text:n}]}]:n,i=new AbortController,c=i.signal,T=setInterval(()=>{kt&&(i.abort(),clearInterval(T))},100);try{let E;a==="Ollama"?E=zs(m,t,x,s,o,g,gt(t),c,l,systemSettings?.ollamaEndpoint||"Cloud"):a==="OpenRouter"?E=Jo(m,t,x,s,o,g,gt(t),c,l):a==="DeepSeek"?E=Yo(m,t,x,s,o,g,gt(t),c,l):a==="Mistral"?E=qo(m,t,x,s,o,g,gt(t),c,l):a==="NVIDIA"?E=zo(m,t,x,s,o,g,gt(t),c,l):a==="InferX"?E=Xo(m,t,x,s,o,g,gt(t),c,l):a==="SenseNova"?E=Qo(m,t,x,s,o,g,gt(t),c,l):a==="AIHubMix"?E=Zo(m,t,x,s,o,g,gt(t),c,l):a==="Poolside"?E=es(m,t,x,s,o,g,gt(t),c,l):a==="9router"||a==="9Router"?E=ts(m,t,x,s,o,g,gt(t),c,l):a==="ExpLabs"||a==="ExperientialLabs"?E=ns(m,t,x,s,o,g,gt(t),c,l):a==="TokenHarbor"||a==="Token Harbor"||a==="tokenharbor"||a==="token_harbor"||a==="thk"?E=Js(m,t,x,s,o,g,gt(t),c,l):a==="APInex"||a==="apinex"||a==="apx"?E=Xs(m,t,x,s,o,g,gt(t),c,l):E=await ti(m).models.generateContentStream({model:t,contents:x,config:{systemInstruction:s,temperature:l,thinkingConfig:(()=>{let N=(t||"").toLowerCase(),v=N.includes("gemma-4")||N.startsWith("gemma"),_=N.includes("gemini-3");if(v||_)return v?o.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:Ze.MINIMAL}:{includeThoughts:!0,thinkingLevel:Ze.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:N.includes("pro")?Ze.LOW:Ze.MINIMAL,Low:Ze.LOW,Medium:Ze.MEDIUM,Standard:Ze.MEDIUM,High:Ze.HIGH,xHigh:Ze.HIGH}[o]||Ze.MEDIUM};{let R={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[o]||2048;return R===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:R}}})()}},{signal:c});for await(let k of E){if(kt)throw new Error("Subagent task was cancelled.");if(e?.taskId&&typeof Kt<"u"){let v=Kt.find(_=>_.id===e.taskId);if(v&&v.status==="cancelled")throw new Error("Subagent task was cancelled.")}let C="";if(k.candidates?.[0]?.content?.parts)for(let v of k.candidates[0].content.parts)v.text&&!v.thought&&(u+=v.text,C+=v.text);let N=C?ws(C):0;e&&typeof e.onTokenChunk=="function"&&e.onTokenChunk(C,N),k.usageMetadata&&(h=k.usageMetadata)}}finally{clearInterval(T)}if(h){let E=h.totalTokenCount||0,k=h.cachedContentTokenCount||0,C=(h.candidatesTokenCount||0)+(a==="Google"&&h.thoughtsTokenCount||0);await Bt("tokens",E,a,t),k>0&&await Bt("cachedTokens",k,a,t),C>0&&await Bt("candidateTokens",C,a,t),e&&typeof e.onUsage=="function"&&e.onUsage({totalTokenCount:E,cachedContentTokenCount:k,candidatesTokenCount:C})}return await Ct("agent",a),{text:u,usageMetadata:h}}),Za=async(e,t,n=null)=>{n=n||Et(Co,{});try{let{aiProvider:s="Google"}=t;if(Object.values(n).flat().length<=5)return;let l=Object.keys(n).filter(x=>x!==e&&Array.isArray(n[x])&&n[x].length>2);if(l.length===0)return;let f=`You are a silent background process for the FluxFlow CLI Agent.
631
+ `)}if(process.stdout.isTTY)try{let Ee=(await Ss())[c]?.name||"",z=Ee&&!Ee.startsWith("flow-")&&!Ee.startsWith("Session ")?Ee:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${z}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${z}\x07`)}catch{process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")}},qa=e=>{let t=qt(e),n=Ts?t:t.replace(Gr,o=>" ".repeat(o.length)).replace(jr,o=>" ".repeat(o.length));yo.lastIndex=0;let s;for(;(s=yo.exec(n))!==null;){let o=s.index+s[0].length-1,l=0,f=null,a=!1,m=!1;for(let g=o;g<n.length;g++){let u=t[g];if(!f&&(u==='"'||u==="'"||u==="`")?(f=u,a=!1):f&&u===f&&!a&&(f=null),!f&&(u==="("?l++:u===")"&&l--,l===0)){let h=g+1;for(;h<n.length&&/\s/.test(n[h]);)h++;if(h<n.length&&n[h]==="]"){m=!0,yo.lastIndex=h+1;break}}u==="\\"?a=!a:a=!1}if(!m)return{inside:!0,toolName:s[1],startIndex:s.index,args:t.substring(s.index+s[0].length)}}return{inside:!1}},Kr=(e,t=!0)=>{let n=yo;n.lastIndex=0;let s="",o=0,l;for(;(l=n.exec(e))!==null;){let f=e.substring(o,l.index);s+=t&&o===0?qt(f):f;let a=l.index+l[0].length-1,m=0,g=null,u=-1;for(let h=a;h<e.length;h++){let x=e[h];if(g){if(x===g){let i=0;for(let c=h-1;c>=0&&e[c]==="\\";c--)i++;i%2===0&&(g=null)}}else if(x==='"'||x==="'"||x==="`")g=x;else if(x==="(")m++;else if(x===")"&&(m--,m===0)){let i=h+1;for(;i<e.length&&/\s/.test(e[i]);)i++;if(i<e.length&&e[i]==="]"){u=i;break}}}if(u!==-1)s+="[tool:functions."+l[1]+"()]",o=u+1,n.lastIndex=o;else{s+="[tool:functions."+l[1]+"(",o=e.length;break}}return o<e.length&&(s+=t&&o===0?qt(e.substring(o)):e.substring(o)),s},za=(e,t,n)=>{let s=yo;s.lastIndex=0;let o="",l=0,f;for(;(f=s.exec(e))!==null;){let a=e.substring(l,f.index);o+=a.replace(t,n);let m=f.index+f[0].length-1,g=0,u=null,h=-1;for(let x=m;x<e.length;x++){let i=e[x];if(u){if(i===u){let c=0;for(let T=x-1;T>=0&&e[T]==="\\";T--)c++;c%2===0&&(u=null)}}else if(i==='"'||i==="'"||i==="`")u=i;else if(i==="(")g++;else if(i===")"&&(g--,g===0)){let c=x+1;for(;c<e.length&&/\s/.test(e[c]);)c++;if(c<e.length&&e[c]==="]"){h=c;break}}}if(h!==-1)o+=e.substring(f.index,h+1),l=h+1,s.lastIndex=l;else{o+=e.substring(f.index),l=e.length;break}}return l<e.length&&(o+=e.substring(l).replace(t,n)),o},Wr=e=>Kr(e,!0),Ja=e=>{if(!e)return e;let t={patchfile:"PatchFile",writefile:"WriteFile",readfile:"ReadFile",viewfile:"ReadFile",run:"Run",execcommand:"Run",searchkeyword:"SearchKeyword",codesearch:"CodeSearch",code_search:"CodeSearch",websearch:"WebSearch",webscrape:"WebScrape",readfolder:"ReadFolder",writepdf:"WritePDF",writedoc:"WriteDoc",writedocx:"WriteDoc",filemap:"FileMap",generateimage:"GenerateImage",todo:"Todo",goal:"Goal",askuser:"AskUser",ask:"AskUser"},n=o=>o.split("_").map(l=>l.charAt(0).toUpperCase()+l.slice(1)).join("");Nr.lastIndex=0;let s=e.replace(Nr,(o,l,f)=>{let a="";try{let u=JSON.parse(f.trim());u&&typeof u=="object"&&(a=Object.entries(u).map(([x,i])=>{let c=typeof i=="string"?i:JSON.stringify(i);return`${x}=${JSON.stringify(c)}`}).join(", "))}catch{let h=[],x=Ga;x.lastIndex=0;let i;for(;(i=x.exec(f))!==null;){let c=i[1],T=i[2]!==void 0?i[2]:i[0].split(":").slice(1).join(":").trim();h.push(`${c}=${JSON.stringify(T)}`)}h.length>0?a=h.join(", "):a=f.trim()}let m=l.toLowerCase().replace(/_/g,"");return`[tool:functions.${t[m]||n(l)}(${a})]`});return Fr.lastIndex=0,Br.lastIndex=0,s=s.replace(Fr,""),s=s.replace(Br,""),s},Xa=/(?:path|query|url|keyword|command|method|title|task|id)\s*=\s*['"`]?\s*\.\.\.\s*['"`]?/i,Qa=/^['"`]?\s*\.\.\.\s*['"`]?$/,kn=e=>{if(e==null)return!1;let t=String(e).trim();return t==="..."||t==="\u2026"||Qa.test(t)},xo=e=>{if(!e)return[];let t=Ja(e),n=qt(t),s=[],o=Ts?n:n.replace(Gr,a=>" ".repeat(a.length)).replace(jr,a=>" ".repeat(a.length)),l=$a;l.lastIndex=0;let f;for(;(f=l.exec(o))!==null;){let a=f[1],m=f.index+f[0].length-1,g=0,u=null,h=-1,x=-1;for(let i=m;i<o.length;i++){let c=n[i];if(u){if(c===u){let T=0;for(let E=i-1;E>=0&&n[E]==="\\";E--)T++;T%2===0&&(u=null)}}else if(c==='"'||c==="'"||c==="`")u=c;else if(c==="(")g++;else if(c===")"&&(g--,g===0)){x=i;let T=i+1;for(;T<o.length&&/\s/.test(o[T]);)T++;if(T<o.length&&o[T]==="]"){h=T;break}}}if(h!==-1){let i=n.substring(m+1,x),c=n.substring(f.index,h+1),T=oe(i);kn(T.path)||kn(T.query)||kn(T.url)||kn(T.keyword)||kn(T.command)||kn(T.method)||kn(T.title)||kn(T.task)||kn(T.id)||Xa.test(i)||s.push({fullMatch:c,toolName:a.trim(),args:i.trim()}),l.lastIndex=h+1}}return s},cf=(e,t={})=>{if(!e)return null;if(os=t,ei=new Hr({apiKey:e}),!globalThis.__perfCleanupInstalled){globalThis.__perfCleanupInstalled=!0,setInterval(()=>{typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks())},6e4);let n=globalThis.fetch;globalThis.fetch=async(...s)=>{try{let o=await n(...s);return typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),o}catch(o){throw typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),o}}}},ss=async(e,t,n,s,o="Fast",l=.75,f="agent")=>Va(async()=>{let{aiProvider:a="Google",apiKey:m,mode:g}=e,u="",h=null,x=typeof n=="string"?[{role:"user",parts:[{text:n}]}]:n,i=new AbortController,c=i.signal,T=setInterval(()=>{kt&&(i.abort(),clearInterval(T))},100);try{let E;a==="Ollama"?E=zs(m,t,x,s,o,g,gt(t),c,l,systemSettings?.ollamaEndpoint||"Cloud"):a==="OpenRouter"?E=Jo(m,t,x,s,o,g,gt(t),c,l):a==="DeepSeek"?E=Yo(m,t,x,s,o,g,gt(t),c,l):a==="Mistral"?E=qo(m,t,x,s,o,g,gt(t),c,l):a==="NVIDIA"?E=zo(m,t,x,s,o,g,gt(t),c,l):a==="InferX"?E=Xo(m,t,x,s,o,g,gt(t),c,l):a==="SenseNova"?E=Qo(m,t,x,s,o,g,gt(t),c,l):a==="AIHubMix"?E=Zo(m,t,x,s,o,g,gt(t),c,l):a==="Poolside"?E=es(m,t,x,s,o,g,gt(t),c,l):a==="9router"||a==="9Router"?E=ts(m,t,x,s,o,g,gt(t),c,l):a==="ExpLabs"||a==="ExperientialLabs"?E=ns(m,t,x,s,o,g,gt(t),c,l):a==="TokenHarbor"||a==="Token Harbor"||a==="tokenharbor"||a==="token_harbor"||a==="thk"?E=Js(m,t,x,s,o,g,gt(t),c,l):a==="APInex"||a==="apinex"||a==="apx"?E=Xs(m,t,x,s,o,g,gt(t),c,l):E=await ti(m).models.generateContentStream({model:t,contents:x,config:{systemInstruction:s,temperature:l,thinkingConfig:(()=>{let N=(t||"").toLowerCase(),v=N.includes("gemma-4")||N.startsWith("gemma"),_=N.includes("gemini-3");if(v||_)return v?o.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:Ze.MINIMAL}:{includeThoughts:!0,thinkingLevel:Ze.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:N.includes("pro")?Ze.LOW:Ze.MINIMAL,Low:Ze.LOW,Medium:Ze.MEDIUM,Standard:Ze.MEDIUM,High:Ze.HIGH,xHigh:Ze.HIGH}[o]||Ze.MEDIUM};{let R={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[o]||2048;return R===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:R}}})()}},{signal:c});for await(let k of E){if(kt)throw new Error("Subagent task was cancelled.");if(e?.taskId&&typeof Kt<"u"){let v=Kt.find(_=>_.id===e.taskId);if(v&&v.status==="cancelled")throw new Error("Subagent task was cancelled.")}let C="";if(k.candidates?.[0]?.content?.parts)for(let v of k.candidates[0].content.parts)v.text&&!v.thought&&(u+=v.text,C+=v.text);let N=C?ws(C):0;e&&typeof e.onTokenChunk=="function"&&e.onTokenChunk(C,N),k.usageMetadata&&(h=k.usageMetadata)}}finally{clearInterval(T)}if(h){let E=h.totalTokenCount||0,k=h.cachedContentTokenCount||0,C=(h.candidatesTokenCount||0)+(a==="Google"&&h.thoughtsTokenCount||0);await Bt("tokens",E,a,t),k>0&&await Bt("cachedTokens",k,a,t),C>0&&await Bt("candidateTokens",C,a,t),e&&typeof e.onUsage=="function"&&e.onUsage({totalTokenCount:E,cachedContentTokenCount:k,candidatesTokenCount:C})}return await Ct("agent",a),{text:u,usageMetadata:h}}),Za=async(e,t,n=null)=>{n=n||Et(Co,{});try{let{aiProvider:s="Google"}=t;if(Object.values(n).flat().length<=5)return;let l=Object.keys(n).filter(x=>x!==e&&Array.isArray(n[x])&&n[x].length>2);if(l.length===0)return;let f=`You are a silent background process for the FluxFlow CLI Agent.
632
632
  Your task is to summarize or merge temporary context memories from one or more past conversation sessions.
633
633
  For each Chat ID provided, you must output a tool call to save the consolidated summary.
634
634
 
@@ -653,7 +653,7 @@ ${c}
653
653
  `):f+=`-- Individual Memories:
654
654
  ${c}
655
655
 
656
- `}let m=0,g=5,u=!1,h=ue("gemma_janitor_fallback_google");for(s==="OpenRouter"&&(h=ue("janitor_open_router")),s==="DeepSeek"&&(h=ue("deepseek_level_1")),s==="Mistral"&&(h=ue("mistral_level_1")),s==="NVIDIA"&&(h=ue("nvidia_janitor_fallback")),s==="InferX"&&(h=ue("inferx_fallback")),s==="SenseNova"&&(h=ue("sensenova_fallback")),s==="AIHubMix"&&(h=ue("aihubmix_fallback")),s==="Poolside"&&(h=ue("poolside_fallback")),(s==="9router"||s==="9Router")&&(h=ue("9router_fallback"));m<=g&&!u;){m++;try{let i=(await ss(t,h,f,null,"Fast",.75,"background")).text||"",c=xo(i);if(c.length===0)throw new Error("No tool calls detected in synthesis response");for(let T of c){let E=T.toolName;["saveSummary","saveSumary","SaveSummary","SaveSumary"].includes(E)&&await ho(E,T.args,{chatId:e})}u=!0}catch(x){if(m>=g)throw new Error(`Failed after ${g} attempts. Last error: ${x.message}`)}}}catch(s){let o=s instanceof Error?(()=>{try{return JSON.parse(JSON.parse(s.message).error.message).error.message}catch{return String(s)}})():String(s),l=ee.join(vn,"janitor");Ge.existsSync(l)||Ge.mkdirSync(l,{recursive:!0}),Ge.appendFileSync(ee.join(l,"error.log"),`[${new Date().toLocaleString()}] Past memory batch consolidation error: ${o}
656
+ `}let m=0,g=5,u=!1,h=ue("gemma_janitor_fallback_google");for(s==="OpenRouter"&&(h=ue("janitor_open_router")),s==="DeepSeek"&&(h=ue("deepseek_level_1")),s==="Mistral"&&(h=ue("mistral_level_1")),s==="NVIDIA"&&(h=ue("nvidia_janitor_fallback")),s==="InferX"&&(h=ue("inferx_fallback")),s==="SenseNova"&&(h=ue("sensenova_fallback")),s==="AIHubMix"&&(h=ue("aihubmix_fallback")),s==="Poolside"&&(h=ue("poolside_fallback")),(s==="9router"||s==="9Router")&&(h=ue("9router_fallback"));m<=g&&!u;){m++;try{let i=(await ss(t,h,f,null,"Fast",.75,"background")).text||"",c=xo(i);if(c.length===0)throw new Error("No tool calls detected in synthesis response");for(let T of c){let E=T.toolName;["saveSummary","saveSumary","SaveSummary","SaveSumary"].includes(E)&&await ho(E,T.args,{chatId:e})}u=!0}catch(x){if(m>=g)throw new Error(`Failed after ${g} attempts. Last error: ${x.message}`)}}}catch(s){let o=s instanceof Error?(()=>{try{return JSON.parse(JSON.parse(s.message).error.message).error.message}catch{return String(s)}})():String(s),l=ee.join(vn,"janitor");je.existsSync(l)||je.mkdirSync(l,{recursive:!0}),je.appendFileSync(ee.join(l,"error.log"),`[${new Date().toLocaleString()}] Past memory batch consolidation error: ${o}
657
657
  `)}},df=async(e,t,n=!1)=>{let{chatId:s,aiProvider:o="Google"}=e,l=ee.join(Eo,"chat-summaries.json"),f=i=>i.filter(c=>(c.role==="user"||c.role==="agent"||c.role==="system")&&c.role!=="think"&&!c.isVisualFeedback&&!c.isMeta&&!c.isTerminalRecord&&!(c.text&&c.text.includes("[TERMINAL_RECORD]"))&&!String(c.id).startsWith("welcome")).map(c=>{let T=c.fullText||c.text||"",E=c.role==="system"||T.startsWith("[TOOL RESULT]:")||c.text&&c.text.startsWith("[TOOL RESULT]:"),k=T;return E&&(T.includes("[TOOL RESULT]:")||c.text&&c.text.includes("[TOOL RESULT]:"))?k="[TOOL RESULT]: ...truncated for summary":k=k.replace(/(\[(?:tool|agent):[a-zA-Z0-9_\.]+)\([\s\S]*?\)(\])/g,"$1(...)$2"),`[${E?"TOOL":c.role==="agent"?"AGENT":"USER"}]: ${k}`}).join(`
658
658
 
659
659
  `),a=async(i,c)=>{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.",E=c?`Here is the previous summary:
@@ -665,9 +665,9 @@ ${i}
665
665
  Provide a new consolidated summary of the entire session.`:`Here is the conversation history:
666
666
  ${i}
667
667
 
668
- Provide a consolidated summary of the entire session.`,k=ue("gemma_janitor_fallback_google");o==="OpenRouter"&&(k=ue("janitor_open_router")),o==="DeepSeek"&&(k=ue("deepseek_level_1")),o==="Mistral"&&(k=ue("mistral_level_1")),o==="NVIDIA"&&(k=ue("nvidia_chat_summarizer_fallback")),o==="InferX"&&(k=ue("inferx_fallback")),o==="SenseNova"&&(k=ue("sensenova_fallback")),o==="AIHubMix"&&(k=ue("aihubmix_fallback")),o==="Poolside"&&(k=ue("poolside_fallback")),(o==="9router"||o==="9Router")&&(k=ue("9router_fallback")),(o==="ExpLabs"||o==="ExperientialLabs")&&(k=ue("explabs_fallback")||"deepseek-v4-pro-0813"),(o==="TokenHarbor"||o==="Token Harbor"||o==="tokenharbor"||o==="token_harbor"||o==="thk")&&(k=ue("tokenharbor_fallback")||"deepseek-v4.1-flash:free");let C=0,N=!1,v=null;for(;C<=3&&!N;){C++;try{v=await ss(e,k,E,T,"Fast"),N=!0}catch{if(C>3){if(o==="Google")try{let R=ue("general_fallback");return(await ss(e,R,E,T,"Fast")).text||""}catch{return""}return""}}}return v&&v.text||""},m=f(t),g=Et(l,{}),u=g[s]||{summary:"",historyLength:0};typeof u=="string"&&(u={summary:u,historyLength:0});let h=u.summary||"",x=await a(m,h);if(x){u.summary=x;let i=Ka(t);return n?u.historyLength=(u.historyLength||0)+i:u.historyLength=i,g[s]=u,Jn(l,g),x}return null},ff=e=>{try{let t=ee.join(Eo,"chat-summaries.json");if(Ge.existsSync(t)){let n=Et(t,{});n[e]&&(delete n[e],Jn(t,n))}}catch{}},uf=async function*(e,t,n,s,o){let{profile:l,thinkingLevel:f,mode:a,janitorModel:m,chatId:g,isPlayground:u,systemSettings:h,sessionStats:x,aiProvider:i="Google",apiTier:c,wildcardTooling:T}=n,E=gt(e);if(!ei&&i==="Google")throw new Error("AI not initialized");let k=process.env.NVIDIA_BASE_URL||n?.aiProvider==="Ollama"||n?.aiProvider==="InferX"||n?.aiProvider==="SenseNova"||n?.aiProvider==="AIHubMix"||n?.aiProvider==="Poolside"||n?.aiProvider==="9router"||n?.aiProvider==="ExpLabs"||n?.aiProvider==="ExperientialLabs"||n?.aiProvider==="TokenHarbor"||n?.aiProvider==="Token Harbor"||n?.aiProvider==="tokenharbor"||n?.aiProvider==="token_harbor"||n?.aiProvider==="thk"||n?.aiProvider==="APInex"||n?.aiProvider==="apinex"||n?.aiProvider==="apx"?!1:h?.memory!==!1,C=t[t.length-1].text,N=ee.join(Eo,"chat-summaries.json"),v=!1,_=t.filter(b=>b.role==="user").length===1,R=C.includes("[TITLE-UPDATE]"),L=_||R,y=C.replace(/\[TITLE-UPDATE\]/g,"").trim();y=y.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),yield{type:"status",content:"[start]"},yield{type:"status",content:"Gathering Context"},await Mo.startTransaction(g,y),h?.advanceRollback&&await io.takeInitialSnapshot(g),kt=!1;let d=null;try{let b=new AbortController;d=setInterval(()=>{kt&&(b.abort(),d&&(clearInterval(d),d=null))},400);let r=[...t.slice(0,-1)];{let Pe=Et(N,{})[g]||{summary:"",historyLength:0};if(Pe.summary&&Pe.historyLength>0){let Jt=0,et=[];for(let ve=0;ve<r.length;ve++){let rt=r[ve];(rt.role==="user"||rt.role==="agent"||rt.role==="system")&&!String(rt.id).startsWith("welcome")&&!rt.isMeta&&Jt++,Jt>Pe.historyLength&&et.push(rt)}r=et}}r=r.map(G=>{if(G.role==="user"&&G.text){let Pe=G.text.match(/\[USER\]([\s\S]*?)\[\/USER\]/);if(Pe)return{...G,text:Pe[1].trim()}}return{...G}});let w=process.env.HIGH_CONTEXT,A=process.env.GOOGLE_GEMMA_NONSENSE==="true"||process.env.GOOGLE_GEMMA_NONSENSE===!0||!1,P={"16k":16e3,"32k":32e3,"64k":64e3,"128k":128e3,"256k":256e3,"512k":512e3,"1M":1e6}[h?.contextLength]||256e3;if(w&&w!=="false"){let G=parseInt(w,10);!isNaN(G)&&G>=0&&G<=1e6&&(P=G)}if((i==="NVIDIA"&&(e?.includes("gpt")||e?.includes("qwen")||e?.includes("medium")||e.includes("muse"))||i==="Mistral")&&(P=126e3),i==="Google"&&e?.includes("gemma")&&A&&(P=16e3),(x?.tokens||0)>P){yield{type:"text",content:"\u2726 Maximum Context Limit Reached. Start a new chat."};return}if(_&&k){let G=Et(Co,{});Object.values(G).flat().length>5&&(yield{type:"status",content:"Condensing past chat memories"},await Za(g,n,G))}let M=Et(Co,{}),te=Et(ys,{}),le=Object.entries(M).filter(([G])=>G!==g).flatMap(([G,Pe])=>Pe),re=[...Object.entries(te).filter(([G])=>G!==g).slice(-20).map(([G,Pe])=>`[Chat Summary]: ${Pe}`),...le].map(G=>`- ${G}`).join(`
668
+ Provide a consolidated summary of the entire session.`,k=ue("gemma_janitor_fallback_google");o==="OpenRouter"&&(k=ue("janitor_open_router")),o==="DeepSeek"&&(k=ue("deepseek_level_1")),o==="Mistral"&&(k=ue("mistral_level_1")),o==="NVIDIA"&&(k=ue("nvidia_chat_summarizer_fallback")),o==="InferX"&&(k=ue("inferx_fallback")),o==="SenseNova"&&(k=ue("sensenova_fallback")),o==="AIHubMix"&&(k=ue("aihubmix_fallback")),o==="Poolside"&&(k=ue("poolside_fallback")),(o==="9router"||o==="9Router")&&(k=ue("9router_fallback")),(o==="ExpLabs"||o==="ExperientialLabs")&&(k=ue("explabs_fallback")||"deepseek-v4-pro-0813"),(o==="TokenHarbor"||o==="Token Harbor"||o==="tokenharbor"||o==="token_harbor"||o==="thk")&&(k=ue("tokenharbor_fallback")||"deepseek-v4.1-flash:free");let C=0,N=!1,v=null;for(;C<=3&&!N;){C++;try{v=await ss(e,k,E,T,"Fast"),N=!0}catch{if(C>3){if(o==="Google")try{let R=ue("general_fallback");return(await ss(e,R,E,T,"Fast")).text||""}catch{return""}return""}}}return v&&v.text||""},m=f(t),g=Et(l,{}),u=g[s]||{summary:"",historyLength:0};typeof u=="string"&&(u={summary:u,historyLength:0});let h=u.summary||"",x=await a(m,h);if(x){u.summary=x;let i=Ka(t);return n?u.historyLength=(u.historyLength||0)+i:u.historyLength=i,g[s]=u,Jn(l,g),x}return null},ff=e=>{try{let t=ee.join(Eo,"chat-summaries.json");if(je.existsSync(t)){let n=Et(t,{});n[e]&&(delete n[e],Jn(t,n))}}catch{}},uf=async function*(e,t,n,s,o){let{profile:l,thinkingLevel:f,mode:a,janitorModel:m,chatId:g,isPlayground:u,systemSettings:h,sessionStats:x,aiProvider:i="Google",apiTier:c,wildcardTooling:T}=n,E=gt(e);if(!ei&&i==="Google")throw new Error("AI not initialized");let k=process.env.NVIDIA_BASE_URL||n?.aiProvider==="Ollama"||n?.aiProvider==="InferX"||n?.aiProvider==="SenseNova"||n?.aiProvider==="AIHubMix"||n?.aiProvider==="Poolside"||n?.aiProvider==="9router"||n?.aiProvider==="ExpLabs"||n?.aiProvider==="ExperientialLabs"||n?.aiProvider==="TokenHarbor"||n?.aiProvider==="Token Harbor"||n?.aiProvider==="tokenharbor"||n?.aiProvider==="token_harbor"||n?.aiProvider==="thk"||n?.aiProvider==="APInex"||n?.aiProvider==="apinex"||n?.aiProvider==="apx"?!1:h?.memory!==!1,C=t[t.length-1].text,N=ee.join(Eo,"chat-summaries.json"),v=!1,_=t.filter(b=>b.role==="user").length===1,R=C.includes("[TITLE-UPDATE]"),L=_||R,y=C.replace(/\[TITLE-UPDATE\]/g,"").trim();y=y.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),yield{type:"status",content:"[start]"},yield{type:"status",content:"Gathering Context"},await Mo.startTransaction(g,y),h?.advanceRollback&&await io.takeInitialSnapshot(g),kt=!1;let d=null;try{let b=new AbortController;d=setInterval(()=>{kt&&(b.abort(),d&&(clearInterval(d),d=null))},400);let r=[...t.slice(0,-1)];{let Pe=Et(N,{})[g]||{summary:"",historyLength:0};if(Pe.summary&&Pe.historyLength>0){let Jt=0,et=[];for(let Re=0;Re<r.length;Re++){let rt=r[Re];(rt.role==="user"||rt.role==="agent"||rt.role==="system")&&!String(rt.id).startsWith("welcome")&&!rt.isMeta&&Jt++,Jt>Pe.historyLength&&et.push(rt)}r=et}}r=r.map(G=>{if(G.role==="user"&&G.text){let Pe=G.text.match(/\[USER\]([\s\S]*?)\[\/USER\]/);if(Pe)return{...G,text:Pe[1].trim()}}return{...G}});let w=process.env.HIGH_CONTEXT,A=process.env.GOOGLE_GEMMA_NONSENSE==="true"||process.env.GOOGLE_GEMMA_NONSENSE===!0||!1,P={"16k":16e3,"32k":32e3,"64k":64e3,"128k":128e3,"256k":256e3,"512k":512e3,"1M":1e6}[h?.contextLength]||256e3;if(w&&w!=="false"){let G=parseInt(w,10);!isNaN(G)&&G>=0&&G<=1e6&&(P=G)}if((i==="NVIDIA"&&(e?.includes("gpt")||e?.includes("qwen")||e?.includes("medium")||e.includes("muse"))||i==="Mistral")&&(P=126e3),i==="Google"&&e?.includes("gemma")&&A&&(P=16e3),(x?.tokens||0)>P){yield{type:"text",content:"\u2726 Maximum Context Limit Reached. Start a new chat."};return}if(_&&k){let G=Et(Co,{});Object.values(G).flat().length>5&&(yield{type:"status",content:"Condensing past chat memories"},await Za(g,n,G))}let M=Et(Co,{}),te=Et(ys,{}),le=Object.entries(M).filter(([G])=>G!==g).flatMap(([G,Pe])=>Pe),re=[...Object.entries(te).filter(([G])=>G!==g).slice(-20).map(([G,Pe])=>`[Chat Summary]: ${Pe}`),...le].map(G=>`- ${G}`).join(`
669
669
  `),We=Et(Bn,[]).map(G=>`- ${G.memory}`).join(`
670
- `),D=(x?.tokens||0)>=1e4,F=rr(re,We,k,D),Ae=new Date,z=Ae.getFullYear(),B=Ae.toLocaleString("en-US",{month:"short"}).toUpperCase(),Y=String(Ae.getDate()).padStart(2,"0"),de=Ae.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}),Ee=`${z}-${B}-${Y}, ${de}`,Ce=`${de}`,Ne=[".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"],vt=G=>{try{return Ge.readdirSync(G,{withFileTypes:!0})}catch{return[]}},wn=(G,Pe={value:0},Jt=1)=>{if(Pe.value>6200||Jt>7)return Pe.value;let et=vt(G);for(let ve of et){if(Pe.value>6200)break;Ne.includes(ve.name)||ve.name.startsWith(".")||ve.isDirectory()&&(Pe.value++,wn(ee.join(G,ve.name),Pe,Jt+1))}return Pe.value},zt=(G,Pe)=>h?.indentationTree!==!1?Ks(G,Pe,1,vt,Ne):qs(G,Pe,"",1,vt,Ne),dt=wn(process.cwd()),ge=10;dt>3072||dt>2304?ge=1:dt>1536?ge=2:dt>768?ge=3:dt>384?ge=5:dt>192?ge=6:dt>96?ge=7:(dt>48||dt>24)&&(ge=9);let me=Et(xs,{}),ie=me[g],Ot=ie?ie!==process.cwd():!1;me[g]=process.cwd(),Jn(xs,me);let jn=Et(N,{}),St=jn[g]||{summary:"",historyLength:0};typeof St=="string"&&(St={summary:St,historyLength:0});let Yr=t.filter(G=>(G.role==="user"||G.role==="agent"||G.role==="system")&&!String(G.id).startsWith("welcome")&&!G.isMeta).length;St.historyLength&&Yr<St.historyLength&&(St.summary="",St.historyLength=0,jn[g]=St,Jn(N,jn));let bo=typeof St=="object"?St.summary||"":St||"",ni=r.length>0;ni&&bo&&r[0]&&(r[0].role==="user"||r[0].role==="system")&&(r[0].text.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")||(r[0].text=`[SYSTEM METADATA]
670
+ `),D=(x?.tokens||0)>=1e4,F=rr(re,We,k,D),Ee=new Date,z=Ee.getFullYear(),B=Ee.toLocaleString("en-US",{month:"short"}).toUpperCase(),Y=String(Ee.getDate()).padStart(2,"0"),de=Ee.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}),Ce=`${z}-${B}-${Y}, ${de}`,ve=`${de}`,Ne=[".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"],vt=G=>{try{return je.readdirSync(G,{withFileTypes:!0})}catch{return[]}},wn=(G,Pe={value:0},Jt=1)=>{if(Pe.value>6200||Jt>7)return Pe.value;let et=vt(G);for(let Re of et){if(Pe.value>6200)break;Ne.includes(Re.name)||Re.name.startsWith(".")||Re.isDirectory()&&(Pe.value++,wn(ee.join(G,Re.name),Pe,Jt+1))}return Pe.value},zt=(G,Pe)=>h?.indentationTree!==!1?Ks(G,Pe,1,vt,Ne):qs(G,Pe,"",1,vt,Ne),dt=wn(process.cwd()),ge=10;dt>3072||dt>2304?ge=1:dt>1536?ge=2:dt>768?ge=3:dt>384?ge=5:dt>192?ge=6:dt>96?ge=7:(dt>48||dt>24)&&(ge=9);let me=Et(xs,{}),ie=me[g],Ot=ie?ie!==process.cwd():!1;me[g]=process.cwd(),Jn(xs,me);let jn=Et(N,{}),St=jn[g]||{summary:"",historyLength:0};typeof St=="string"&&(St={summary:St,historyLength:0});let Yr=t.filter(G=>(G.role==="user"||G.role==="agent"||G.role==="system")&&!String(G.id).startsWith("welcome")&&!G.isMeta).length;St.historyLength&&Yr<St.historyLength&&(St.summary="",St.historyLength=0,jn[g]=St,Jn(N,jn));let bo=typeof St=="object"?St.summary||"":St||"",ni=r.length>0;ni&&bo&&r[0]&&(r[0].role==="user"||r[0].role==="system")&&(r[0].text.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")||(r[0].text=`[SYSTEM METADATA]
671
671
  **CONTEXT SUMMARY OF PREVIOUS TURNS (PRIORITY: DYNAMIC)**
672
672
  ${bo}
673
673
 
@@ -680,25 +680,25 @@ ${bo}
680
680
  CWD: `+process.cwd()+`${u?" [PLAYGROUND MODE]":""}
681
681
  `+zt(process.cwd(),ge),yt=await Un(),fn="";if(Vo()&&yt.file_focused!=="none"){fn=`
682
682
  [Additional IDE Context]
683
- `;let G=ee.relative(process.cwd(),yt.file_focused),Pe=(yt.opened_editors||[]).map(et=>{let ve=ee.relative(process.cwd(),et);return ve.startsWith("..")?`[External] ${ee.basename(et)}`:ve});if(fn+=`Focused File: ${G}
683
+ `;let G=ee.relative(process.cwd(),yt.file_focused),Pe=(yt.opened_editors||[]).map(et=>{let Re=ee.relative(process.cwd(),et);return Re.startsWith("..")?`[External] ${ee.basename(et)}`:Re});if(fn+=`Focused File: ${G}
684
684
  Cursor Line: ${yt.cursor_line}
685
- `,yt.selected){let et=yt.selected,ve=et.split(`
686
- `);ve.length>256&&(et=ve.slice(0,240).join(`
685
+ `,yt.selected){let et=yt.selected,Re=et.split(`
686
+ `);Re.length>256&&(et=Re.slice(0,240).join(`
687
687
  `)+`
688
688
  ... [truncated] ...
689
- `+ve.slice(-16).join(`
689
+ `+Re.slice(-16).join(`
690
690
  `)),et.length>2048&&(et=et.slice(0,1920)+`
691
691
  ... [truncated] ...
692
692
  `+et.slice(-128)),fn+=`Current Selection: "${et}"
693
- `}if(yt.manual_edits){let ve=yt.manual_edits.split(`
694
- `),rt=[],ot=null;for(let j of ve)j.trim()&&(j.startsWith(" Line ")?ot&&ot.edits.push(j):(ot={path:j.endsWith(":")?j.slice(0,-1):j,edits:[]},rt.push(ot)));for(let j of rt)j.edits.length>80&&(j.edits=j.edits.slice(-80)),j.originalEditsCount=j.edits.length;let at=(j,je)=>je.reduce((_e,mt)=>{let Rt=yt.file_focused&&(mt.path===yt.file_focused||ee.resolve(process.cwd(),mt.path)===ee.resolve(yt.file_focused))?Math.ceil(j*1.2):j;return _e+Math.min(mt.edits.length,Rt)},0),ye=80;if(at(80,rt)>300){let j=!1;for(let je=80;je>=10;je--)if(at(je,rt)<=300){ye=je,j=!0;break}j||(ye=10)}let ze=[...rt];if(ye===10&&at(10,ze)>500)for(;ze.length>0&&at(10,ze)>500;){let j=0,je=ze[0].originalEditsCount;for(let _e=1;_e<ze.length;_e++)ze[_e].originalEditsCount<je&&(je=ze[_e].originalEditsCount,j=_e);ze.splice(j,1)}for(let j of ze){let _e=yt.file_focused&&(j.path===yt.file_focused||ee.resolve(process.cwd(),j.path)===ee.resolve(yt.file_focused))?Math.ceil(ye*1.2):ye;j.edits.length>_e&&(j.edits=j.edits.slice(-_e))}for(let j of ze){let je=`${j.path}:
693
+ `}if(yt.manual_edits){let Re=yt.manual_edits.split(`
694
+ `),rt=[],ot=null;for(let j of Re)j.trim()&&(j.startsWith(" Line ")?ot&&ot.edits.push(j):(ot={path:j.endsWith(":")?j.slice(0,-1):j,edits:[]},rt.push(ot)));for(let j of rt)j.edits.length>80&&(j.edits=j.edits.slice(-80)),j.originalEditsCount=j.edits.length;let at=(j,Ve)=>Ve.reduce((_e,mt)=>{let Rt=yt.file_focused&&(mt.path===yt.file_focused||ee.resolve(process.cwd(),mt.path)===ee.resolve(yt.file_focused))?Math.ceil(j*1.2):j;return _e+Math.min(mt.edits.length,Rt)},0),ye=80;if(at(80,rt)>300){let j=!1;for(let Ve=80;Ve>=10;Ve--)if(at(Ve,rt)<=300){ye=Ve,j=!0;break}j||(ye=10)}let ze=[...rt];if(ye===10&&at(10,ze)>500)for(;ze.length>0&&at(10,ze)>500;){let j=0,Ve=ze[0].originalEditsCount;for(let _e=1;_e<ze.length;_e++)ze[_e].originalEditsCount<Ve&&(Ve=ze[_e].originalEditsCount,j=_e);ze.splice(j,1)}for(let j of ze){let _e=yt.file_focused&&(j.path===yt.file_focused||ee.resolve(process.cwd(),j.path)===ee.resolve(yt.file_focused))?Math.ceil(ye*1.2):ye;j.edits.length>_e&&(j.edits=j.edits.slice(-_e))}for(let j of ze){let Ve=`${j.path}:
695
695
  ${j.edits.join(`
696
- `)}`;for(;j.edits.length>0&&je.length>4*768;)j.edits.shift(),je=`${j.path}:
696
+ `)}`;for(;j.edits.length>0&&Ve.length>4*768;)j.edits.shift(),Ve=`${j.path}:
697
697
  ${j.edits.join(`
698
- `)}`;je.length>4*768?j.stringRepresentation="... "+je.slice(-(4*768-4)):j.stringRepresentation=je}let sn=ze.map(j=>j.stringRepresentation).join(`
699
- `);for(;ze.length>0&&sn.length>4*2048;){ze[0].edits.length>0?ze[0].edits.shift():ze.shift();for(let j of ze){let je=`${j.path}:
698
+ `)}`;Ve.length>4*768?j.stringRepresentation="... "+Ve.slice(-(4*768-4)):j.stringRepresentation=Ve}let sn=ze.map(j=>j.stringRepresentation).join(`
699
+ `);for(;ze.length>0&&sn.length>4*2048;){ze[0].edits.length>0?ze[0].edits.shift():ze.shift();for(let j of ze){let Ve=`${j.path}:
700
700
  ${j.edits.join(`
701
- `)}`;je.length>4*768?j.stringRepresentation="... "+je.slice(-(4*768-4)):j.stringRepresentation=je}sn=ze.map(j=>j.stringRepresentation).join(`
701
+ `)}`;Ve.length>4*768?j.stringRepresentation="... "+Ve.slice(-(4*768-4)):j.stringRepresentation=Ve}sn=ze.map(j=>j.stringRepresentation).join(`
702
702
  `)}sn.length>4*2048&&(sn="... "+sn.slice(-(4*2048-4))),fn+=`Recent Manual Edits:
703
703
  ${sn}
704
704
  `}Pe.length>0&&(fn+=`All Opened Editors: ${Pe.join(", ")}`),yt.diagnostics&&(fn+=`
@@ -707,22 +707,22 @@ ${yt.diagnostics}
707
707
  `),(y.toLowerCase().includes("lint")||y.toLowerCase().includes("warning"))&&yt.warnings&&(fn+=`
708
708
  **Lint Warnings**:
709
709
  ${yt.warnings}
710
- `)}let ii=y.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),ri=/(?:\\)?@\[([^\]]+)\]/g,rs,as=[];for(ri.lastIndex=0;(rs=ri.exec(ii))!==null;){let G=rs[0].startsWith("\\");as.push({tag:rs[1],isEscaped:G})}let ls=[],ko=null;for(let G=0;G<as.length;G++){let{tag:Pe,isEscaped:Jt}=as[G];if(!Jt)try{let et=Pe.trim().replace(/^["']|["']$/g,""),ve=/[:#]L?(\d+)(?:-L?(\d+))?$/i,rt=et.match(ve),ot=et,at=null,ye=null;rt&&(at=parseInt(rt[1],10),ye=rt[2]?parseInt(rt[2],10):at,ot=et.slice(0,rt.index));let ze=ee.resolve(process.cwd(),ot);if(Ge.existsSync(ze)&&Ge.statSync(ze).isFile()){let j=ot.toLowerCase(),je=j.endsWith(".pdf"),_e=j.endsWith(".docx")||j.endsWith(".doc")||j.endsWith(".ppt")||j.endsWith(".pptx")||j.endsWith(".xls")||j.endsWith(".xlsx"),mt=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(j),Sn=mt||je||_e,Rt=i==="Google"||gt(e);if(Sn&&!Rt){let Lt=`\u2718 Unsupported Modality: ${ee.basename(ot)}`,Je=115;process.stdout.isTTY&&(Je=process.stdout.columns-5||120);let be=[Lt],Qe=Math.max(...be.map(gn=>gn.length)),An=Math.min(Qe+4,Je),Dn=be.map(gn=>`${gn.padEnd(An-2).substring(0,An-2)}`).join(`
710
+ `)}let ii=y.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),ri=/(?:\\)?@\[([^\]]+)\]/g,rs,as=[];for(ri.lastIndex=0;(rs=ri.exec(ii))!==null;){let G=rs[0].startsWith("\\");as.push({tag:rs[1],isEscaped:G})}let ls=[],ko=null;for(let G=0;G<as.length;G++){let{tag:Pe,isEscaped:Jt}=as[G];if(!Jt)try{let et=Pe.trim().replace(/^["']|["']$/g,""),Re=/[:#]L?(\d+)(?:-L?(\d+))?$/i,rt=et.match(Re),ot=et,at=null,ye=null;rt&&(at=parseInt(rt[1],10),ye=rt[2]?parseInt(rt[2],10):at,ot=et.slice(0,rt.index));let ze=ee.resolve(process.cwd(),ot);if(je.existsSync(ze)&&je.statSync(ze).isFile()){let j=ot.toLowerCase(),Ve=j.endsWith(".pdf"),_e=j.endsWith(".docx")||j.endsWith(".doc")||j.endsWith(".ppt")||j.endsWith(".pptx")||j.endsWith(".xls")||j.endsWith(".xlsx"),mt=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(j),Sn=mt||Ve||_e,Rt=i==="Google"||gt(e);if(Sn&&!Rt){let Lt=`\u2718 Unsupported Modality: ${ee.basename(ot)}`,Je=115;process.stdout.isTTY&&(Je=process.stdout.columns-5||120);let be=[Lt],Qe=Math.max(...be.map(gn=>gn.length)),An=Math.min(Qe+4,Je),Dn=be.map(gn=>`${gn.padEnd(An-2).substring(0,An-2)}`).join(`
711
711
  `);yield{type:"visual_feedback",content:Yt(`${Dn}
712
- `)};continue}if(at===null&&!Sn){let Lt=0;try{Lt=Ge.readFileSync(ze,"utf8").split(/\r\n|\r|\n/).length}catch{}if(Lt>300){let Je=`\u21B7 Skipped (Too Large): ${ee.basename(ot)}`,be=115;process.stdout.isTTY&&(be=process.stdout.columns-5||120);let Qe=Math.min(Je.length+4,be),An=Je.padEnd(Qe-2).substring(0,Qe-2);yield{type:"visual_feedback",content:Yt(`${An}
713
- `)};continue}}let rn=at!==null?at:1,_n=ye!==null?ye:at!==null?at:rn+299;_n-rn>300&&(_n=rn+300);let Zn=`path=${JSON.stringify(ot)}, startLine=${rn}, endLine=${_n}`,Zt=await Si(Zn,{isMultiModal:Rt}),xt=!1,tt="",Dt=null;if(typeof Zt=="string"?Zt.trim().startsWith("ERROR")?xt=!0:tt=Zt:Zt&&typeof Zt=="object"&&Zt.binaryPart?(Dt=Zt.binaryPart,tt=Zt.text||""):xt=!0,!xt){let Lt="";if(mt?(Lt=`\u2714 Processed: ${ee.basename(ot)}`,ko=Dt):je||_e?(Lt=`\u2714 Auto-Analysed: ${ee.basename(ot)}`,ko=Dt):(Lt=`\u2714 Auto-Read: ${ee.basename(ot)}`,ls.push(tt)),Lt){let Je=115;process.stdout.isTTY&&(Je=process.stdout.columns-5||120);let be=[Lt],Qe=Math.max(...be.map(gn=>gn.length)),An=Math.min(Qe+4,Je),Dn=be.map(gn=>`${gn.padEnd(An-2).substring(0,An-2)}`).join(`
712
+ `)};continue}if(at===null&&!Sn){let Lt=0;try{Lt=je.readFileSync(ze,"utf8").split(/\r\n|\r|\n/).length}catch{}if(Lt>300){let Je=`\u21B7 Skipped (Too Large): ${ee.basename(ot)}`,be=115;process.stdout.isTTY&&(be=process.stdout.columns-5||120);let Qe=Math.min(Je.length+4,be),An=Je.padEnd(Qe-2).substring(0,Qe-2);yield{type:"visual_feedback",content:Yt(`${An}
713
+ `)};continue}}let rn=at!==null?at:1,_n=ye!==null?ye:at!==null?at:rn+299;_n-rn>300&&(_n=rn+300);let Zn=`path=${JSON.stringify(ot)}, startLine=${rn}, endLine=${_n}`,Zt=await Si(Zn,{isMultiModal:Rt}),xt=!1,tt="",Dt=null;if(typeof Zt=="string"?Zt.trim().startsWith("ERROR")?xt=!0:tt=Zt:Zt&&typeof Zt=="object"&&Zt.binaryPart?(Dt=Zt.binaryPart,tt=Zt.text||""):xt=!0,!xt){let Lt="";if(mt?(Lt=`\u2714 Processed: ${ee.basename(ot)}`,ko=Dt):Ve||_e?(Lt=`\u2714 Auto-Analysed: ${ee.basename(ot)}`,ko=Dt):(Lt=`\u2714 Auto-Read: ${ee.basename(ot)}`,ls.push(tt)),Lt){let Je=115;process.stdout.isTTY&&(Je=process.stdout.columns-5||120);let be=[Lt],Qe=Math.max(...be.map(gn=>gn.length)),An=Math.min(Qe+4,Je),Dn=be.map(gn=>`${gn.padEnd(An-2).substring(0,An-2)}`).join(`
714
714
  `);yield{type:"visual_feedback",content:Yt(`${Dn}
715
715
  `)}}}}}catch{}}let cs="";ls.length>0&&(cs=`[Tagged File Contents] Auto Read User Tagged files by System, No need to re-read
716
716
  `+ls.join(`
717
717
 
718
718
  `)+`
719
719
  [Tagged File Contents]
720
- `);let ai=ii.replace(/\\(@\[[^\]]+\])/g,"$1"),li=T?`[system] exact tool string format [tool:functions.ToolName(arg="value")] in chat [/system]
720
+ `);let ai=ii.replace(/\\(@\[[^\]]+\])/g,"$1"),li=T?`[system] exact tool string format [tool:ToolName(arg="value")] in chat [/system]
721
721
  You cannot execute tools
722
722
  Instead, output in chat the exact string you WOULD have produced & wait for system response
723
723
  `:"",zr=process.env.forcedReasoning||!1,ci=f!=="Fast"&&(i==="Mistral"&&!Ro(e)||f!=="High"&&i==="Google")?`${i==="Mistral"&&!Ro(e)||e.toLowerCase().startsWith("gemma")||zr?`[system] strictly follow thinking policy as high priority. do not start a response without <think>...</think> [/system]
724
724
  `:""}`:"",wo="",di=!!h?.autoExcludeMetadata,Jr=!!(fn||cs||li||is||F||ci||Ot||h?.dynamicDirAwareness||h?.autoTruncateResults||k);di&&!Jr?wo=ai.trim():wo=`[System Metadata]
725
- Time: ${di?Ce:Ee}${h?.dynamicDirAwareness?si:""}${Ot?`
725
+ Time: ${di?ve:Ce}${h?.dynamicDirAwareness?si:""}${Ot?`
726
726
  WARNING: CWD Changed from previous: "${ie}" to current: "${process.cwd()}", write change in chat to avoid future path mismatches
727
727
  `:""}${F}${fn}
728
728
  [/Metadata]
@@ -741,7 +741,7 @@ ${Q}`:r.push({role:"user",text:Q}),yield{type:"status",content:"Subagent Update"
741
741
  [question] ${fe.replace("/btw","").trim()} [/question]`:r.push({role:"user",text:`[system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
742
742
  [question] ${fe.replace("/btw","").trim()} [/question]`}):r.length>0&&r[r.length-1].role==="user"?r[r.length-1].text+=`
743
743
 
744
- [STEERING HINT from USER, High Priority] ${fe.trim()} [/STEERING HINT]`:r.push({role:"user",text:`[STEERING HINT from USER, High Priority] ${fe.trim()} [/STEERING HINT]`}),yield{type:"status",content:`${fe.startsWith("/btw")?"Question Forwarded...":"Steering Hint Injected..."}`})}let ve,rt=!1,ot=1,at=1,ye="",ze=null,sn=null,j=null,je=0,_e=[],mt=0,Sn=!1,Rt=!1,rn=!1,_n=!1,Zn=!0,Zt=0,xt="",tt="",Dt=!1,Lt=!1,Je=!0,be=e,Qe="";for(;ot<=on&&at<=on&&!rt&&!kt;){let fe=!1;try{ye="",Zn&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},Zn=!1,at===1&&(xt=""));let we=I=>{if(!I||!I.includes("[tool:"))return I;let K="",$=Qs(I);$&&(K=$.fullBlock,I=$.remainingText),I=I.replace(ja,(ke,he)=>he.includes("[tool:")?he.trim():ke);let W="",Te=0;for(;Te<I.length;){let ke=I.indexOf("[tool:",Te);if(ke===-1){W+=Ur(I.substring(Te));break}let he=I.substring(Te,ke);W+=Ur(he);let Xe=-1,U=null,Z=0;for(let Le=ke;Le<I.length;Le++){let p=I[Le];if(U){if(p===U){let Re=0;for(let Me=Le-1;Me>=0&&I[Me]==="\\";Me--)Re++;Re%2===0&&(U=null)}}else if(p==='"'||p==="'"||p==="`")U=p;else if(p==="(")Z++;else if(p===")")Z--;else if(p==="]"&&Z<=0){Xe=Le;break}}if(Xe===-1){W+=I.substring(ke);break}W+=I.substring(ke,Xe+1),Te=Xe+1}return(h?.keepReasoningContext?K:"")+W},Q=r.filter(I=>(I.role==="user"||I.role==="agent"||I.role==="system")&&!String(I.id).startsWith("welcome")&&!I.isMeta&&!I.isTerminalRecord&&!(I.text&&I.text.startsWith("[TERMINAL_RECORD]"))).map((I,K,$)=>{let W=I.text||"";k||(W=W.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),I.role==="agent"&&(W=we(W),W=W.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),W=W.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*"));let Te=[];return Array.isArray(I.parts)&&I.parts.length>0?Te=I.parts.map(ke=>{if(ke.text){let he=ke.text;return k||(he=he.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),I.role==="agent"&&(he=we(he),he=he.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),he=he.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*")),{text:he}}return ke}):Te=[{text:W}],I.binaryPart&&gt(be)&&$.slice(K+1).filter(he=>he.role==="user"&&!he.text?.startsWith("[TOOL RESULT]")).length<=2&&Te.push(I.binaryPart),{role:I.role==="user"||I.role==="system"?"user":"model",parts:Te}});for(let I=0;I<Q.length;I++){let K=Q[I],$=K.parts?.[0]?.text||"";if(K.role==="model"&&/\[tool:/i.test($)){let W=-1;for(let Te=I+1;Te<Q.length;Te++){let ke=Q[Te],he=ke.parts?.[0]?.text||"";if(ke.role==="user"&&he.startsWith("[TOOL RESULT]")){W=Te;break}}if(W!==-1&&W!==I+1){let[Te]=Q.splice(W,1);Q.splice(I+1,0,Te)}}}for(let I=Q.length-2;I>=0;I--){let K=Q[I],$=Q[I+1];K.role==="user"&&$.role==="user"&&($.parts?.[0]?.text||"").trim().startsWith("[SYSTEM")&&Q.splice(I,1)}let Pt=[];for(let I=0;I<Q.length;I++){let K=Q[I];if(Pt.length===0)Pt.push(K);else{let $=Pt[Pt.length-1];$.role===K.role?($.parts[0].text+=`
744
+ [STEERING HINT from USER, High Priority] ${fe.trim()} [/STEERING HINT]`:r.push({role:"user",text:`[STEERING HINT from USER, High Priority] ${fe.trim()} [/STEERING HINT]`}),yield{type:"status",content:`${fe.startsWith("/btw")?"Question Forwarded...":"Steering Hint Injected..."}`})}let Re,rt=!1,ot=1,at=1,ye="",ze=null,sn=null,j=null,Ve=0,_e=[],mt=0,Sn=!1,Rt=!1,rn=!1,_n=!1,Zn=!0,Zt=0,xt="",tt="",Dt=!1,Lt=!1,Je=!0,be=e,Qe="";for(;ot<=on&&at<=on&&!rt&&!kt;){let fe=!1;try{ye="",Zn&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},Zn=!1,at===1&&(xt=""));let we=I=>{if(!I||!I.includes("[tool:"))return I;let K="",$=Qs(I);$&&(K=$.fullBlock,I=$.remainingText),I=I.replace(ja,(ke,he)=>he.includes("[tool:")?he.trim():ke);let W="",Te=0;for(;Te<I.length;){let ke=I.indexOf("[tool:",Te);if(ke===-1){W+=Ur(I.substring(Te));break}let he=I.substring(Te,ke);W+=Ur(he);let Xe=-1,U=null,Z=0;for(let Le=ke;Le<I.length;Le++){let p=I[Le];if(U){if(p===U){let Me=0;for(let Ie=Le-1;Ie>=0&&I[Ie]==="\\";Ie--)Me++;Me%2===0&&(U=null)}}else if(p==='"'||p==="'"||p==="`")U=p;else if(p==="(")Z++;else if(p===")")Z--;else if(p==="]"&&Z<=0){Xe=Le;break}}if(Xe===-1){W+=I.substring(ke);break}W+=I.substring(ke,Xe+1),Te=Xe+1}return(h?.keepReasoningContext?K:"")+W},Q=r.filter(I=>(I.role==="user"||I.role==="agent"||I.role==="system")&&!String(I.id).startsWith("welcome")&&!I.isMeta&&!I.isTerminalRecord&&!(I.text&&I.text.startsWith("[TERMINAL_RECORD]"))).map((I,K,$)=>{let W=I.text||"";k||(W=W.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),I.role==="agent"&&(W=we(W),W=W.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),W=W.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*"));let Te=[];return Array.isArray(I.parts)&&I.parts.length>0?Te=I.parts.map(ke=>{if(ke.text){let he=ke.text;return k||(he=he.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),I.role==="agent"&&(he=we(he),he=he.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),he=he.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*")),{text:he}}return ke}):Te=[{text:W}],I.binaryPart&&gt(be)&&$.slice(K+1).filter(he=>he.role==="user"&&!he.text?.startsWith("[TOOL RESULT]")).length<=2&&Te.push(I.binaryPart),{role:I.role==="user"||I.role==="system"?"user":"model",parts:Te}});for(let I=0;I<Q.length;I++){let K=Q[I],$=K.parts?.[0]?.text||"";if(K.role==="model"&&/\[tool:/i.test($)){let W=-1;for(let Te=I+1;Te<Q.length;Te++){let ke=Q[Te],he=ke.parts?.[0]?.text||"";if(ke.role==="user"&&he.startsWith("[TOOL RESULT]")){W=Te;break}}if(W!==-1&&W!==I+1){let[Te]=Q.splice(W,1);Q.splice(I+1,0,Te)}}}for(let I=Q.length-2;I>=0;I--){let K=Q[I],$=Q[I+1];K.role==="user"&&$.role==="user"&&($.parts?.[0]?.text||"").trim().startsWith("[SYSTEM")&&Q.splice(I,1)}let Pt=[];for(let I=0;I<Q.length;I++){let K=Q[I];if(Pt.length===0)Pt.push(K);else{let $=Pt[Pt.length-1];$.role===K.role?($.parts[0].text+=`
745
745
 
746
746
  `+(K.parts?.[0]?.text||""),K.parts?.length>1&&$.parts.push(...K.parts.slice(1))):Pt.push(K)}}Q.length=0,Q.push(...Pt),be=e;let Mt=`${g}|${i}|${a}|${f}|${be}|${JSON.stringify(l)}|${!!h?.dynamicDirAwareness}|${!!h?.subAgents}`,_t=Hn.key===Mt&&Hn.value;if((process.env.I_HAVE_TOO_MUCH_MONEY==="true"||process.env.I_HAVE_TOO_MUCH_MONEY===!0)&&(_t=!1),_t)Qe=Hn.value;else{let I=i==="Mistral"?!!Ro(be):!(be||"gemma").toLowerCase().startsWith("gemma");Qe=ar(l,((be||"gemma").toLowerCase().startsWith("gemma"),f),a,h,k,_,i,i==="Google"?!0:E,I,g,!!h?.keepReasoningContext,be),h?.dynamicDirAwareness||(Qe+=`
747
747
  ${si.replace(`
@@ -753,19 +753,19 @@ ${K} [/ERROR]`),yield{type:"status",content:"Working"}}let $t=i==="Mistral"||i==
753
753
  `;for(let W of I.modifiedFiles)K+=`* ${W} (modified)
754
754
  `;for(let W of I.deletedFiles)K+=`* ${W} (deleted)
755
755
  `;K+="[/system]",Ye.parts[0].text+=K;let $=-1;for(let W=r.length-1;W>=0;W--)if(r[W].role==="user"&&r[W].text?.startsWith("[TOOL RESULT]")){$=W;break}$!==-1&&(r[$].text+=K)}}catch{}let At=Math.floor(Tn*.99),wt=G+1;wt>=At&&Ye&&Ye.parts?.[0]&&(Ye.parts[0].text+=`
756
- [system] WARNING, Turn Limit Impending: Step ${wt}/${Tn}. Wrap up quickly/prompt user to continue. [/system]`);let It=new Promise((I,K)=>{b.signal.aborted&&K(new DOMException("The user aborted a request.","AbortError")),b.signal.addEventListener("abort",()=>{K(new DOMException("The user aborted a request.","AbortError"))})});It.catch(()=>{});let ht=Q;if(i==="Ollama")ve=zs(n.apiKey,be,ht,Qe,f,a,E,b.signal,1,h?.ollamaEndpoint||"Cloud");else if(i==="OpenRouter")ve=Jo(n.apiKey,be,ht,Qe,f,a,E,b.signal,1,g);else if(i==="DeepSeek")ve=Yo(n.apiKey,be,ht,Qe,f,a,E,b.signal,1);else if(i==="Mistral")ve=qo(n.apiKey,be,ht,Qe,f,a,E,b.signal,1,g);else if(i==="NVIDIA"){let I=zo(n.apiKey,be,ht,Qe,f,a,E,b.signal,1);ve=Pr(I,be)}else if(i==="InferX")ve=Xo(n.apiKey,be,ht,Qe,f,a,E,b.signal,1);else if(i==="SenseNova")ve=Qo(n.apiKey,be,ht,Qe,f,a,E,b.signal,1);else if(i==="AIHubMix")ve=Zo(n.apiKey,be,ht,Qe,f,a,E,b.signal,1);else if(i==="Poolside")ve=es(n.apiKey,be,ht,Qe,f,a,E,b.signal,1);else if(i==="9router"||i==="9Router")ve=ts(n.apiKey,be,ht,Qe,f,a,E,b.signal,1);else if(i==="ExpLabs"||i==="ExperientialLabs")ve=ns(n.apiKey,be,ht,Qe,f,a,E,b.signal,1);else if(i==="TokenHarbor"||i==="Token Harbor"||i==="tokenharbor"||i==="token_harbor"||i==="thk")ve=Js(n.apiKey,be,ht,Qe,f,a,E,b.signal,1);else if(i==="APInex"||i==="apinex"||i==="apx")ve=Xs(n.apiKey,be,ht,Qe,f,a,E,b.signal,1);else{let K=ti(n?.apiKey).models.generateContentStream({model:be||"gemini-3-flash-preview",contents:ht,config:{systemInstruction:Qe,mediaResolution:"MEDIA_RESOLUTION_HIGH",safetySettings:[{category:On.HARM_CATEGORY_HARASSMENT,threshold:In.BLOCK_NONE},{category:On.HARM_CATEGORY_HATE_SPEECH,threshold:In.BLOCK_NONE},{category:On.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:In.BLOCK_NONE},{category:On.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:In.BLOCK_NONE}],temperature:1.05,thinkingConfig:(()=>{let $=Ke("Google",be||"gemini-3-flash-preview",f);if($!==null){if(typeof $=="object")return $;if($===!1||$==="false"||$==="none"||$===0||$==="0")return{includeThoughts:!1};if(typeof $=="number")return{includeThoughts:!0,thinkingBudget:$};if(typeof $=="string"){let he=$.toLowerCase();if(he==="minimal")return{includeThoughts:!0,thinkingLevel:Ze.MINIMAL};if(he==="low")return{includeThoughts:!0,thinkingLevel:Ze.LOW};if(he==="medium")return{includeThoughts:!0,thinkingLevel:Ze.MEDIUM};if(he==="high")return{includeThoughts:!0,thinkingLevel:Ze.HIGH};let Xe=Number($);if(!isNaN(Xe))return{includeThoughts:!0,thinkingBudget:Xe}}}let W=(be||"").toLowerCase(),Te=W.includes("gemma-4")||W.startsWith("gemma"),ke=W.includes("gemini-3");if(Te||ke)return Te?f.toLowerCase()!=="high"?{includeThoughts:!1,thinkingLevel:Ze.MINIMAL}:{includeThoughts:!0,thinkingLevel:Ze.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:W.includes("pro")?Ze.LOW:Ze.MINIMAL,Low:Ze.LOW,Medium:Ze.MEDIUM,Standard:Ze.MEDIUM,High:Ze.HIGH,xHigh:Ze.HIGH}[f]||Ze.MEDIUM};{let he={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[f]||2048;return he===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:he}}})()}},{signal:b.signal});ve=await Promise.race([K,It])}ye="",ze=null,j=null,_e=[],mt=0,yield{type:"model_update",content:null},tt="",Dt=xt.length>0;let an="",fs=Date.now(),Pn=async function*(){if(i==="Google"&&an){let I=eo(an);for(let K of I)yield K;an="",fs=Date.now()}},mi=!0,$n="",Vn=!1,Tt=null,Kn=!1,Yn=!1,So=!1,qn=I=>{let K=0;for(;K+2<I.length;)I[K]==="`"&&I[K+1]==="`"&&I[K+2]==="`"?(So=!So,K+=3):K++},ea={tool:{startPrefix:"[tool",fullPrefix:"[tool:functions.",endTag:"]"},agent:{startPrefix:"[agent",fullPrefix:"[agent:generalist.",endTag:"]"},end:{startPrefix:"[[END]]",fullPrefix:"[[END]]",endTag:"[[END]]"},kimi_section:{startPrefix:"<|tool_calls_section_begin|>",fullPrefix:"<|tool_calls_section_begin|>",endTag:"<|tool_calls_section_end|>"},kimi_call:{startPrefix:"<|tool_call_begin|>",fullPrefix:"<|tool_call_begin|>",endTag:"<|tool_call_end|>"}},eo=I=>{let K=[],$=I;for(;$.length>0;)if(Vn){let W=$n+$,Te=ea[Tt];if(Te){let Xe=!1;if(W.length<Te.startPrefix.length?Te.startPrefix.startsWith(W)||(Xe=!0):W.startsWith(Te.startPrefix)?W.length>=Te.fullPrefix.length&&!W.startsWith(Te.fullPrefix)&&(Xe=!0):Xe=!0,Xe){if(!Kn)K.push({type:"text",content:W});else{let U=W.replace(/[^\n]/g,"");U&&K.push({type:"text",content:U})}qn(W),$n="",Vn=!1,Tt=null,Yn=!1,$="";break}}let ke=-1,he=Te?Te.endTag:"]";if(Tt==="tool"||Tt==="agent"){let Xe=0,U=null,Z=0,Le=!1;for(let p=0;p<W.length;p++){let Re=W[p];if(U){if(Re===U){let Me=0;for(let X=p-1;X>=0&&W[X]==="\\";X--)Me++;Me%2===0&&(U=null)}}else if(Re==='"'||Re==="'"||Re==="`")U=Re;else if(Re==="(")Xe++,Le=!0;else if(Re===")")Xe--;else if(Re==="[")Z++;else if(Re==="]"){if(Le&&Xe===0&&Z===1){ke=p;break}Z--}}}else ke=W.indexOf(he);if(ke!==-1){let Xe=he.length,U=W.substring(0,ke+Xe);Tt?.startsWith("kimi")||K.push({type:"text",content:U}),qn(U),(Tt==="tool"||Tt==="agent"||Tt?.startsWith("kimi"))&&!Yn&&(Kn=!0),Yn=!1,$n="",Vn=!1,Tt=null,$=W.substring(ke+Xe)}else{let Xe=Tt?.startsWith("kimi")?8192:512;if(W.length>Xe){if(!Kn)K.push({type:"text",content:W});else{let U=W.replace(/[^\n]/g,"");U&&K.push({type:"text",content:U})}qn(W),$n="",Vn=!1,Tt=null,Yn=!1}else $n=W;$="";break}}else{let W=$.indexOf("[tool"),Te=$.indexOf("[agent"),ke=$.indexOf("[[END]]"),he=$.indexOf("<|tool_calls_section_begin|>"),Xe=$.indexOf("<|tool_call_begin|>"),U=[{type:"tool",idx:W,start:"[tool",end:"]"},{type:"agent",idx:Te,start:"[agent",end:"]"},{type:"end",idx:ke,start:"[[END]]",end:"[[END]]"},{type:"kimi_section",idx:he,start:"<|tool_calls_section_begin|>",end:"<|tool_calls_section_end|>"},{type:"kimi_call",idx:Xe,start:"<|tool_call_begin|>",end:"<|tool_call_end|>"}].filter(Z=>Z.idx!==-1).sort((Z,Le)=>Z.idx-Le.idx);if(U.length>0){let Z=U[0],Le=$.substring(0,Z.idx);qn(Le);let p=Z.idx>0?$[Z.idx-1]:"";if(Yn=So||p==="`",Z.idx>0)if(!Kn)K.push({type:"text",content:Le});else{let Re=Le.replace(/[^\n]/g,"");Re&&K.push({type:"text",content:Re})}Vn=!0,Tt=Z.type,$n="",$=$.substring(Z.idx)}else{let Z=["[tool","[agent","[[END]]","<|tool_calls_section_begin|>","<|tool_call_begin|>"],Le=-1;for(let p of Z){for(let Re=p.length-1;Re>0;Re--)if($.endsWith(p.substring(0,Re))){Le=$.length-Re;let Me=Z.indexOf(p);Me===0?Tt="tool":Me===1?Tt="agent":Me===2?Tt="end":Me===3?Tt="kimi_section":Tt="kimi_call";break}if(Le!==-1)break}if(Le!==-1){if(Le>0){let Re=$.substring(0,Le);if(qn(Re),!Kn)K.push({type:"text",content:Re});else{let Me=Re.replace(/[^\n]/g,"");Me&&K.push({type:"text",content:Me})}}let p=Le>0?$[Le-1]:"";Yn=So||p==="`",Vn=!0,$n=$.substring(Le),$=""}else{if(!Kn)K.push({type:"text",content:$});else{let p=$.replace(/[^\n]/g,"");p&&K.push({type:"text",content:p})}qn($);break}}}return K},ta=ve[Symbol.asyncIterator]();for(;;){let{value:I,done:K}=await Promise.race([ta.next(),It]);if(K)break;if(I&&I.type==="status"){yield I;continue}let $="",W=I.candidates?.[0]?.content?.parts;if(W&&W.length>0)for(let ke of W){let he=typeof ke.text=="string"?ke.text:ke.text?parseChunkText(ke.text):"";ke.thought?he&&(fe||($+="<think>",fe=!0),$+=he):he&&(fe&&($+="</think>",fe=!1),$+=he)}else I.text&&fe&&($+="</think>",fe=!1);$=Ua($);let Te=$?ws($):0;if(n&&typeof n.onTokenChunk=="function"&&n.onTokenChunk($,Te),mi&&(yield{type:"status",content:"Thinking"},mi=!1),kt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
756
+ [system] WARNING, Turn Limit Impending: Step ${wt}/${Tn}. Wrap up quickly/prompt user to continue. [/system]`);let It=new Promise((I,K)=>{b.signal.aborted&&K(new DOMException("The user aborted a request.","AbortError")),b.signal.addEventListener("abort",()=>{K(new DOMException("The user aborted a request.","AbortError"))})});It.catch(()=>{});let ht=Q;if(i==="Ollama")Re=zs(n.apiKey,be,ht,Qe,f,a,E,b.signal,1,h?.ollamaEndpoint||"Cloud");else if(i==="OpenRouter")Re=Jo(n.apiKey,be,ht,Qe,f,a,E,b.signal,1,g);else if(i==="DeepSeek")Re=Yo(n.apiKey,be,ht,Qe,f,a,E,b.signal,1);else if(i==="Mistral")Re=qo(n.apiKey,be,ht,Qe,f,a,E,b.signal,1,g);else if(i==="NVIDIA"){let I=zo(n.apiKey,be,ht,Qe,f,a,E,b.signal,1);Re=Pr(I,be)}else if(i==="InferX")Re=Xo(n.apiKey,be,ht,Qe,f,a,E,b.signal,1);else if(i==="SenseNova")Re=Qo(n.apiKey,be,ht,Qe,f,a,E,b.signal,1);else if(i==="AIHubMix")Re=Zo(n.apiKey,be,ht,Qe,f,a,E,b.signal,1);else if(i==="Poolside")Re=es(n.apiKey,be,ht,Qe,f,a,E,b.signal,1);else if(i==="9router"||i==="9Router")Re=ts(n.apiKey,be,ht,Qe,f,a,E,b.signal,1);else if(i==="ExpLabs"||i==="ExperientialLabs")Re=ns(n.apiKey,be,ht,Qe,f,a,E,b.signal,1);else if(i==="TokenHarbor"||i==="Token Harbor"||i==="tokenharbor"||i==="token_harbor"||i==="thk")Re=Js(n.apiKey,be,ht,Qe,f,a,E,b.signal,1);else if(i==="APInex"||i==="apinex"||i==="apx")Re=Xs(n.apiKey,be,ht,Qe,f,a,E,b.signal,1);else{let K=ti(n?.apiKey).models.generateContentStream({model:be||"gemini-3-flash-preview",contents:ht,config:{systemInstruction:Qe,mediaResolution:"MEDIA_RESOLUTION_HIGH",safetySettings:[{category:On.HARM_CATEGORY_HARASSMENT,threshold:In.BLOCK_NONE},{category:On.HARM_CATEGORY_HATE_SPEECH,threshold:In.BLOCK_NONE},{category:On.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:In.BLOCK_NONE},{category:On.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:In.BLOCK_NONE}],temperature:1.05,thinkingConfig:(()=>{let $=Ke("Google",be||"gemini-3-flash-preview",f);if($!==null){if(typeof $=="object")return $;if($===!1||$==="false"||$==="none"||$===0||$==="0")return{includeThoughts:!1};if(typeof $=="number")return{includeThoughts:!0,thinkingBudget:$};if(typeof $=="string"){let he=$.toLowerCase();if(he==="minimal")return{includeThoughts:!0,thinkingLevel:Ze.MINIMAL};if(he==="low")return{includeThoughts:!0,thinkingLevel:Ze.LOW};if(he==="medium")return{includeThoughts:!0,thinkingLevel:Ze.MEDIUM};if(he==="high")return{includeThoughts:!0,thinkingLevel:Ze.HIGH};let Xe=Number($);if(!isNaN(Xe))return{includeThoughts:!0,thinkingBudget:Xe}}}let W=(be||"").toLowerCase(),Te=W.includes("gemma-4")||W.startsWith("gemma"),ke=W.includes("gemini-3");if(Te||ke)return Te?f.toLowerCase()!=="high"?{includeThoughts:!1,thinkingLevel:Ze.MINIMAL}:{includeThoughts:!0,thinkingLevel:Ze.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:W.includes("pro")?Ze.LOW:Ze.MINIMAL,Low:Ze.LOW,Medium:Ze.MEDIUM,Standard:Ze.MEDIUM,High:Ze.HIGH,xHigh:Ze.HIGH}[f]||Ze.MEDIUM};{let he={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[f]||2048;return he===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:he}}})()}},{signal:b.signal});Re=await Promise.race([K,It])}ye="",ze=null,j=null,_e=[],mt=0,yield{type:"model_update",content:null},tt="",Dt=xt.length>0;let an="",fs=Date.now(),Pn=async function*(){if(i==="Google"&&an){let I=eo(an);for(let K of I)yield K;an="",fs=Date.now()}},mi=!0,$n="",Vn=!1,Tt=null,Kn=!1,Yn=!1,So=!1,qn=I=>{let K=0;for(;K+2<I.length;)I[K]==="`"&&I[K+1]==="`"&&I[K+2]==="`"?(So=!So,K+=3):K++},ea={tool:{startPrefix:"[tool",fullPrefix:"[tool:",endTag:"]"},agent:{startPrefix:"[agent",fullPrefix:"[agent:generalist.",endTag:"]"},end:{startPrefix:"[[END]]",fullPrefix:"[[END]]",endTag:"[[END]]"},kimi_section:{startPrefix:"<|tool_calls_section_begin|>",fullPrefix:"<|tool_calls_section_begin|>",endTag:"<|tool_calls_section_end|>"},kimi_call:{startPrefix:"<|tool_call_begin|>",fullPrefix:"<|tool_call_begin|>",endTag:"<|tool_call_end|>"}},eo=I=>{let K=[],$=I;for(;$.length>0;)if(Vn){let W=$n+$,Te=ea[Tt];if(Te){let Xe=!1;if(W.length<Te.startPrefix.length?Te.startPrefix.startsWith(W)||(Xe=!0):W.startsWith(Te.startPrefix)?W.length>=Te.fullPrefix.length&&!W.startsWith(Te.fullPrefix)&&(Xe=!0):Xe=!0,Xe){if(!Kn)K.push({type:"text",content:W});else{let U=W.replace(/[^\n]/g,"");U&&K.push({type:"text",content:U})}qn(W),$n="",Vn=!1,Tt=null,Yn=!1,$="";break}}let ke=-1,he=Te?Te.endTag:"]";if(Tt==="tool"||Tt==="agent"){let Xe=0,U=null,Z=0,Le=!1;for(let p=0;p<W.length;p++){let Me=W[p];if(U){if(Me===U){let Ie=0;for(let X=p-1;X>=0&&W[X]==="\\";X--)Ie++;Ie%2===0&&(U=null)}}else if(Me==='"'||Me==="'"||Me==="`")U=Me;else if(Me==="(")Xe++,Le=!0;else if(Me===")")Xe--;else if(Me==="[")Z++;else if(Me==="]"){if(Le&&Xe===0&&Z===1){ke=p;break}Z--}}}else ke=W.indexOf(he);if(ke!==-1){let Xe=he.length,U=W.substring(0,ke+Xe);Tt?.startsWith("kimi")||K.push({type:"text",content:U}),qn(U),(Tt==="tool"||Tt==="agent"||Tt?.startsWith("kimi"))&&!Yn&&(Kn=!0),Yn=!1,$n="",Vn=!1,Tt=null,$=W.substring(ke+Xe)}else{let Xe=Tt?.startsWith("kimi")?8192:512;if(W.length>Xe){if(!Kn)K.push({type:"text",content:W});else{let U=W.replace(/[^\n]/g,"");U&&K.push({type:"text",content:U})}qn(W),$n="",Vn=!1,Tt=null,Yn=!1}else $n=W;$="";break}}else{let W=$.indexOf("[tool"),Te=$.indexOf("[agent"),ke=$.indexOf("[[END]]"),he=$.indexOf("<|tool_calls_section_begin|>"),Xe=$.indexOf("<|tool_call_begin|>"),U=[{type:"tool",idx:W,start:"[tool",end:"]"},{type:"agent",idx:Te,start:"[agent",end:"]"},{type:"end",idx:ke,start:"[[END]]",end:"[[END]]"},{type:"kimi_section",idx:he,start:"<|tool_calls_section_begin|>",end:"<|tool_calls_section_end|>"},{type:"kimi_call",idx:Xe,start:"<|tool_call_begin|>",end:"<|tool_call_end|>"}].filter(Z=>Z.idx!==-1).sort((Z,Le)=>Z.idx-Le.idx);if(U.length>0){let Z=U[0],Le=$.substring(0,Z.idx);qn(Le);let p=Z.idx>0?$[Z.idx-1]:"";if(Yn=So||p==="`",Z.idx>0)if(!Kn)K.push({type:"text",content:Le});else{let Me=Le.replace(/[^\n]/g,"");Me&&K.push({type:"text",content:Me})}Vn=!0,Tt=Z.type,$n="",$=$.substring(Z.idx)}else{let Z=["[tool","[agent","[[END]]","<|tool_calls_section_begin|>","<|tool_call_begin|>"],Le=-1;for(let p of Z){for(let Me=p.length-1;Me>0;Me--)if($.endsWith(p.substring(0,Me))){Le=$.length-Me;let Ie=Z.indexOf(p);Ie===0?Tt="tool":Ie===1?Tt="agent":Ie===2?Tt="end":Ie===3?Tt="kimi_section":Tt="kimi_call";break}if(Le!==-1)break}if(Le!==-1){if(Le>0){let Me=$.substring(0,Le);if(qn(Me),!Kn)K.push({type:"text",content:Me});else{let Ie=Me.replace(/[^\n]/g,"");Ie&&K.push({type:"text",content:Ie})}}let p=Le>0?$[Le-1]:"";Yn=So||p==="`",Vn=!0,$n=$.substring(Le),$=""}else{if(!Kn)K.push({type:"text",content:$});else{let p=$.replace(/[^\n]/g,"");p&&K.push({type:"text",content:p})}qn($);break}}}return K},ta=Re[Symbol.asyncIterator]();for(;;){let{value:I,done:K}=await Promise.race([ta.next(),It]);if(K)break;if(I&&I.type==="status"){yield I;continue}let $="",W=I.candidates?.[0]?.content?.parts;if(W&&W.length>0)for(let ke of W){let he=typeof ke.text=="string"?ke.text:ke.text?parseChunkText(ke.text):"";ke.thought?he&&(fe||($+="<think>",fe=!0),$+=he):he&&(fe&&($+="</think>",fe=!1),$+=he)}else I.text&&fe&&($+="</think>",fe=!1);$=Ua($);let Te=$?ws($):0;if(n&&typeof n.onTokenChunk=="function"&&n.onTokenChunk($,Te),mi&&(yield{type:"status",content:"Thinking"},mi=!1),kt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
757
757
 
758
- \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if($){if(Dt){if(tt+=$,tt.length>=64){let U=0,Z=Math.min(xt.length,tt.length);for(let p=Z;p>=10;p--)if(xt.endsWith(tt.substring(0,p))){U=p;break}let Le=tt.substring(U);if(Le){let Re=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(xt)?Le.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):Le.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(Re)if(ye+=Re,i==="Google")an+=Re;else{yield*Pn();let Me=eo(Re);for(let X of Me)yield X}}Dt=!1,tt=""}continue}else if(ye+=$,i==="Google")an+=$;else{yield*Pn();let U=eo($);for(let Z of U)yield Z}let ke=qa(ye);if(ke.inside){Lt=!0,j||(j=Date.now());let Z={Ask:"ask",AskUser:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Cancel:"cancel",Await:"await",Answer:"answer",Steer:"steer",steer:"steer"}[ke.toolName]||ke.toolName,Le=ke.args||"",p=null;if(["write_file","update_file","view_file","read_folder","write_pdf","write_docx","search_keyword","generate_image","file_map","invoke","invoke_sync","get_progress","await","answer"].includes(Z)){let Me=oe(Le),X=Me.path||Me.targetFile||Me.TargetFile||Me.directory,ln=Me.keyword,Nn=Me.title||Me.task,En=Me.id||Me.taskId,$e=Me.timeout||Me.time;if(ln!=null)p=String(ln).replace(Wn,"");else if(X)p=ee.basename(String(X).replace(Wn,"").replace($r,"/"));else if(Nn&&(Z==="invoke"||Z==="invoke_sync"))p=String(Nn).replace(Wn,"").substring(0,30);else if(En&&Z==="get_progress")p=String(En).replace(Wn,"");else if($e&&Z==="await"){let Nt=parseFloat(String($e).replace(Wn,""));isNaN(Nt)?p=String($e).replace(Wn,""):(Nt<5&&(Nt=5),Nt>120&&(Nt=120),p=(mn=>{if(mn>=60){let gs=Math.floor(mn/60),zn=mn%60;return`${gs}m${zn>0?` ${zn}s`:""}`}return`${mn}s`})(Nt))}else{let Nt=Le.match(Na);if(Nt){let Wt=Nt[1].replace(Wn,"");Z==="invoke"||Z==="invoke_sync"||Z==="get_progress"?p=Wt.substring(0,30):p=Z==="search_keyword"||Z==="file_map"?Wt:ee.basename(Wt.replace($r,"/"))}}}let Re=`${Zs[Z]||Z}${p?` ${p}`:""}`;if((Z!==ze||p!==sn)&&(ze=Z,sn=p,yield{type:"status",content:`${Re}`},process.stdout.isTTY)){let X={WebSearch:"Searching",web_search:"Searching",WebScrape:"Reading",web_scrape:"Reading",ReadFile:"Reading",read_file:"Reading",ReadFolder:"Reading",read_folder:"Reading",WriteFile:"Writing",write_file:"Writing",UpdateFile:"Editing",update_file:"Editing",WritePdf:"Creating",write_pdf:"Creating",WriteDocx:"Creating",write_docx:"Creating",SearchKeyword:"Searching",search_keyword:"Searching",CodeSearch:"Searching",code_search:"Searching",Run:"Executing",Ask:"User Input Required",AskUser:"User Input Required",Memory:"Updating Memory",GenerateImage:"Generating",InvokeSync:"Sub-Agent Working",invoke_sync:"Sub-Agent Working",Invoke:"Working",invoke:"Working",GetProgress:"Checking Progress",get_progress:"Checking Progress",Cancel:"Stopping Generalist",cancel:"Stopping Generalist",Await:"Waiting",await:"Waiting",EmergencyRollback:"Rolling the Ball",Answer:"Answering Sub-Agent",answer:"Answering Sub-Agent",Steer:"Steering Sub-Agent",steer:"Steering Sub-Agent",Click:"Clicking",click:"Clicking",Drag:"Dragging",drag:"Dragging",Scroll:"Scrolling",scroll:"Scrolling",KeyboardTyping:"Typing",keyboard_typing:"Typing",KeyPress:"Pressing Key",key_press:"Pressing Key",RecaptureScreen:"Recapturing Screen",recapture_screen:"Recapturing Screen"}[Z]||"Working";process.stdout.write(`\x1B]0;${X}...\x07`)}}if(ye.length-Zt>150){Zt=ye.length;let U=Kr(ye,!1),Z=Qs(U),Le=Z?(Z.innerContent||"").trim():"",p=Le.split(/[.!?]\s+/),Re=new Set(p),Me=p.length>10?(p.length-Re.size)/p.length:0,X=Le.split(/\s+/).filter(Fe=>Fe.length>0).length,ln=.6,Nn=.8,En=!1;if(i.toLowerCase().includes("google")&&(be||"").toLowerCase().startsWith("gemma")){let S={low:256,medium:1024,high:8192,max:16384,xhigh:16384}[f?.toLowerCase()]||2500;En=X>S}if(Me>ln||En){yield{type:"status",content:`${Me>ln?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},Rt=!0,await new Promise(S=>setTimeout(S,3e3));break}let Wt=Wr(ye).trim().split(/[.!?]\s+/),mn=new Set(Wt);if((Wt.length>10?(Wt.length-mn.size)/Wt.length:0)>Nn){yield{type:"status",content:"Response Loop Detected. Re-centering..."},Rt=!1,_n=!0,await new Promise(Fe=>setTimeout(Fe,3e3));break}let zn=U.replace(Ma,"").replace(Ia,"").replace(Oa,"").replace(Da,""),Ft=zn.toLowerCase().split(/\s+/).map(Fe=>Fe.replace(La,"")).filter(Fe=>Fe.length>0),hn=!1;if(Ft.length>=10)for(let Fe=1;Fe<=15;Fe++){let S=Math.max(3,Math.ceil(10/Fe));if(Ft.length<Fe*S)continue;let V=Ft.slice(Ft.length-Fe),ne=V.join(" ");if(Fe>1&&ne===V.slice(0,Math.floor(Fe/2)).join(" ").repeat(2).trim())continue;let ce=!0;for(let pe=1;pe<S;pe++)if(Ft.slice(Ft.length-Fe*(pe+1),Ft.length-Fe*pe).join(" ")!==ne){ce=!1;break}if(ce){hn=!0;break}}if(!hn){let Fe=zn.toLowerCase().replace(Pa,"");if(Fe.length>=20)for(let S=1;S<=10;S++){let V=Math.max(5,Math.ceil(16/S));if(Fe.length<S*V)continue;let ne=Fe.substring(Fe.length-S),ce=!0;for(let pe=1;pe<V;pe++)if(Fe.substring(Fe.length-S*(pe+1),Fe.length-S*pe)!==ne){ce=!1;break}if(ce){hn=!0;break}}}if(hn){yield{type:"status",content:"Stuttering Detected. Re-centering..."},Rt=!1,rn=!0,await new Promise(Fe=>setTimeout(Fe,3e3));break}}let he=qt(ye),Xe=xo(he);for(;Xe.length>mt;){yield*Pn();let U=Xe[mt],Z=Date.now(),p={Ask:"ask",AskUser:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Await:"await",await:"await",AwaitSubagent:"await",awaitSubagent:"await",Answer:"answer",answer:"answer",AnswerSubagent:"answer",answerSubagent:"answer",Steer:"steer",steer:"steer",SteerSubagent:"steer",steerSubagent:"steer",Cancel:"cancel",cancel:"cancel",Click:"click",click:"click",Drag:"drag",drag:"drag",Scroll:"scroll",scroll:"scroll",KeyboardTyping:"keyboard_typing",keyboard_typing:"keyboard_typing",KeyPress:"key_press",key_press:"key_press",RecaptureScreen:"recapture_screen",recapture_screen:"recapture_screen",EmergencyRollback:"EmergencyRollback"}[U.toolName]||U.toolName,Re=Zs[p]||U.toolName,Me=Gn(p,U.args);yield{type:"status",content:`${Re}${Me?` ${Me}`:""}`};let X="";if(p==="click"){let S=oe(U.args);X=`\u2714 Clicked: ${S.intendedClickText?`${S.intendedClickText}`:""}`}else if(p==="drag"){let S=oe(U.args);X=`\u2714 Dragged: Cell ${S.fromGridId||""} \u2192 Cell ${S.toGridId||""}`}else if(p==="scroll"){let S=oe(U.args);X=`\u2714 Scrolled: ${S.direction||"down"} (${S.amount||1})`}else if(p==="keyboard_typing"){let S=oe(U.args);X=`\u2714 Typed: ${S.text?`"${S.text.length>20?S.text.substring(0,20)+"...":S.text}"`:""}`}else if(p==="key_press")X=`\u2714 Pressed Key: ${oe(U.args).key||""}`;else if(p==="recapture_screen")X="\u2714 Recaptured Screen";else if(p==="web_search"){let{query:S,limit:V=10,aiMode:ne=!1}=oe(U.args);X=`${S?"\u2714":"\u2718"} ${ne?"AI Search":"Searched"}: ${S?`${S}`:"No Search Query"}${ne===!1&&S?` \u2192 ${V}`:""}`}else if(p==="web_scrape"){let S=oe(U.args).url||null;X=`${S?"\u2714":"\u2718"} Visited: ${S||"No Source"}`}else if(p==="view_file"){let{path:S,StartLine:V,EndLine:ne,start_line:ce,end_line:pe,startLine:Ve,endLine:Ie}=oe(U.args),Se=V||ce||Ve,q=ne||pe||Ie,se=parseInt(Se)||1,ae=parseInt(q)||(Se?se+800:800),qe="...",He=ae,Oe=(S||"").trim().toLowerCase().replaceAll("\\","/");if(Oe.startsWith("#skill"))Oe.startsWith("#skill/global/fluxflow")||Oe.startsWith("#skills/global/fluxflow")?X="\u2714 Read Documentation":X=`\u2714 Read Skill: ${ee.basename(S.replaceAll("\\","/"))}`;else{try{let xe=ee.resolve(process.cwd(),S);if(Ge.existsSync(xe)){let bt=Ge.readFileSync(xe,"utf8").split(`
759
- `).length;qe=bt,!Se&&!q&&bt>800?He=Math.min(50,bt):He=Math.min(ae,bt)}}catch{}let Be=(S||"").toLowerCase(),pt=Be.endsWith(".pdf"),Ue=Be.endsWith(".docx")||Be.endsWith(".doc")||Be.endsWith(".ppt")||Be.endsWith(".pptx")||Be.endsWith(".xls")||Be.endsWith(".xlsx"),st=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(Be);pt||Ue?X=`${S.length>0?"\u2714":"\u2718"} ${S?`Analyzed: ${ee.basename(S)}`:"Analyzed: File Not Found"}`:st?X=`${S.length>0?"\u2714":"\u2718"} ${S?`Processed: ${ee.basename(S)}`:"Processed: File Not Found"}`:X=`${qe!=="..."?"\u2714":"\u2718"} Read: ${S?`${ee.basename(S)} \u2192 ${qe!=="..."?`Lines ${se} - ${He} of ${qe}`:"File Not Found"}`:"File Not Found"}`}}else if(p==="list_files"||p==="read_folder"){let S=p==="list_files"?"List":"Browsed",V=oe(U.args).path||null,ne=oe(U.args).recurse||1;X=`${V?"\u2714":"\u2718"} ${S}: ${V?`${V==="."?`./${ne>1?"*":""}`:`${V.replaceAll("\\","/")}${ne>1?`${V.endsWith("/")?"*":"/*"}`:`${V.endsWith("/")?"":"/"}`}`}`:"No Folder Selected"}`}else if(p==="write_file"||p==="update_file"){let S=p==="write_file"?"Created":"Edited",V=oe(U.args),ne=V.path||null,pe=Object.entries(V).some(([Ve,Ie])=>Ve.startsWith("searchContent")&&typeof Ie=="string"&&Ie.startsWith("^LINE:"))?"\u1361":":";X=`${ne?"\u2714":"\u2718"} ${S}${pe} ${ne?ne.replaceAll("\\","/"):"No File Changes"}`}else if(p==="write_pdf"){let S=oe(U.args).path||null;X=`${S?"\u2714":"\u2718"} Generated: ${S.replaceAll("\\","/")||"No PDF Generated"}`}else if(p==="write_docx"){let S=oe(U.args).path||null;X=`${S?"\u2714":"\u2718"} Generated: ${S.replaceAll("\\","/")||"No Docx Generated"}`}else if(p==="file_map"){let S=oe(U.args).path;X=`${S?"\u2714":"\u2718"} Indexed: ${S.replaceAll("\\","/")?""+S:"File Not Found"}`}else if(p.toLowerCase()==="search_keyword"||p.toLowerCase()==="todo")X="";else if(p.toLowerCase()==="generate_image"){let{path:S,outputPath:V,output:ne}=oe(U.args);X=`\u2714 Generated: ${S||V||ne||"generated_image.png"}`}else if(p==="invoke_sync"||p==="InvokeSync"){let S=Gn(p,U.args);X=`\u2714 Called Generalist${S?`: ${S}`:""}`}else if(p==="Invoke"||p==="InvokeAsync"||p==="invoke"){let S=Gn(p,U.args);X=`\u2714 Started Generalist${S?`: ${S}`:""}`}else if(p==="get_progress"||p==="GetProgress"){let S=Gn(p,U.args);X=`\u2714 Checked${S?`: ${S}`:""}`}else if(p==="cancel"){let S=Gn(p,U.args);X=`\u{1F6C7} Cancelled${S?`: ${S}`:""}`}else if(p==="steer"||p==="Steer"){let S=Gn(p,U.args);X=`\u2714 Steered${S?`: ${S}`:""}`}else if(p==="EmergencyRollback"){let{method:S}=oe(U.args);X=S==="forceRevert"?"":"\u2714 Rollback Point Checked"}else if(p==="await"||p==="Await"){let{time:S,timeout:V}=oe(U.args),ne=parseFloat(V||S)||0;ne||(ne=120);let ce=Ie=>{if(Ie>=60){let Se=Math.floor(Ie/60),q=Ie%60;return`${Se}m${q>0?` ${q}s`:""}`}return`${Ie}s`},pe=["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"];X=`\u2714 ${pe[Math.floor(Math.random()*pe.length)]} \u2192 ${ce(ne)}`}else p==="Answer"||p==="answer"?X="\u2714 Resolved Sub-Agent Query":p==="exec_command"||p==="ask"?X="":X=`Executed: ${U.toolName}`;if(yield*Pn(),p==="exec_command"){let{command:S}=oe(U.args);if(S&&n.systemSettings&&n.systemSettings.allowExternalAccess===!1){let V=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],ne=ee.resolve(process.cwd()).substring(0,3).toLowerCase(),ce=q=>{let se=[],ae="",qe=null;for(let He=0;He<q.length;He++){let Oe=q[He];qe?(Oe===qe&&(qe=null),ae+=Oe):Oe==='"'||Oe==="'"?(qe=Oe,ae+=Oe):Oe==="&"&&q[He+1]==="&"||Oe==="|"&&q[He+1]==="|"?(ae.trim()&&(se.push(ae.trim()),ae=""),He++):Oe===";"||Oe==="|"||Oe==="&"?ae.trim()&&(se.push(ae.trim()),ae=""):ae+=Oe}return ae.trim()&&se.push(ae.trim()),se},pe=q=>{let se=[],ae="",qe=null;for(let He=0;He<q.length;He++){let Oe=q[He];qe?(Oe===qe&&(qe=null),ae+=Oe):Oe==='"'||Oe==="'"?(qe=Oe,ae+=Oe):/\s/.test(Oe)?ae&&(se.push(ae),ae=""):ae+=Oe}return ae&&se.push(ae),se},Ve=q=>{let se=q.replace(/^['"]|['"]$/g,"").trim();return!se||process.platform==="win32"&&/^\/[a-zA-Z0-9?]+$/.test(se)?!1:V.some(ae=>{if(ae.source==="[a-zA-Z]:[\\\\\\/]"){let qe=se.match(/[a-zA-Z]:[\\\/]/i);return qe&&qe[0].toLowerCase()!==ne}return ae.test(se)})};if(ce(S).some(q=>{let se=pe(q);if(se.length===0)return!1;let ae=se[0].replace(/^['"]|['"]$/g,"").toLowerCase();if(["echo","printf","write-output"].includes(ae)){let He=!1;return se.some(Oe=>{let Ht=Oe.replace(/^['"]|['"]$/g,"");if(Ht===">"||Ht===">>"||Ht==="<")return He=!0,!1;if(Ht.startsWith(">")||Ht.startsWith("<")){let Be=Ht.replace(/^[><]+/,"");return Ve(Be)}return He?(He=!1,Ve(Oe)):!1})}return se.some(He=>Ve(He))})){let q='Access Denied. Prohibited from accessing external directories while "External Workspace Access" is disabled.';n.onExecStart&&n.onExecStart(S||"No Command"),yield{type:"exec_start"},await new Promise(se=>setTimeout(se,50)),n.onExecChunk&&n.onExecChunk(`ERROR: ${q}`),await new Promise(se=>setTimeout(se,50)),n.onExecEnd&&n.onExecEnd(),_e.push({role:"user",text:`[TOOL RESULT]: ERROR: ${q}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${q}`},mt++;continue}}n.onExecStart&&n.onExecStart(S||"No Command"),yield{type:"exec_start"}}let ln=oe(U.args),Nn=ln.path||ln.targetPath||null;if(Nn){let S=n.systemSettings&&n.systemSettings.allowExternalAccess===!1,V=ee.resolve(Nn),ne=ee.resolve(process.cwd());if(S&&!V.startsWith(ne)){let ce="Access Denied. You are not allowed to access files outside the current workspace.";if(p==="write_file"||p==="update_file"){let Ve=`\u2718 ${p==="write_file"?"Write Canceled":"Edit Canceled"}: ${ln.path||"..."}`,Ie=115;process.stdout.isTTY&&(Ie=process.stdout.columns-5||120);let Se=Math.min(Ve.length+4,Ie),q=`${Ve.padEnd(Se-2).substring(0,Se-2)}`;yield{type:"visual_feedback",content:Yt(`${Je?`
758
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if($){if(Dt){if(tt+=$,tt.length>=64){let U=0,Z=Math.min(xt.length,tt.length);for(let p=Z;p>=10;p--)if(xt.endsWith(tt.substring(0,p))){U=p;break}let Le=tt.substring(U);if(Le){let Me=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(xt)?Le.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):Le.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(ye+=Me,i==="Google")an+=Me;else{yield*Pn();let Ie=eo(Me);for(let X of Ie)yield X}}Dt=!1,tt=""}continue}else if(ye+=$,i==="Google")an+=$;else{yield*Pn();let U=eo($);for(let Z of U)yield Z}let ke=qa(ye);if(ke.inside){Lt=!0,j||(j=Date.now());let Z={Ask:"ask",AskUser:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Cancel:"cancel",Await:"await",Answer:"answer",Steer:"steer",steer:"steer"}[ke.toolName]||ke.toolName,Le=ke.args||"",p=null;if(["write_file","update_file","view_file","read_folder","write_pdf","write_docx","search_keyword","generate_image","file_map","invoke","invoke_sync","get_progress","await","answer"].includes(Z)){let Ie=oe(Le),X=Ie.path||Ie.targetFile||Ie.TargetFile||Ie.directory,ln=Ie.keyword,Nn=Ie.title||Ie.task,En=Ie.id||Ie.taskId,$e=Ie.timeout||Ie.time;if(ln!=null)p=String(ln).replace(Wn,"");else if(X)p=ee.basename(String(X).replace(Wn,"").replace($r,"/"));else if(Nn&&(Z==="invoke"||Z==="invoke_sync"))p=String(Nn).replace(Wn,"").substring(0,30);else if(En&&Z==="get_progress")p=String(En).replace(Wn,"");else if($e&&Z==="await"){let Nt=parseFloat(String($e).replace(Wn,""));isNaN(Nt)?p=String($e).replace(Wn,""):(Nt<5&&(Nt=5),Nt>120&&(Nt=120),p=(mn=>{if(mn>=60){let gs=Math.floor(mn/60),zn=mn%60;return`${gs}m${zn>0?` ${zn}s`:""}`}return`${mn}s`})(Nt))}else{let Nt=Le.match(Na);if(Nt){let Wt=Nt[1].replace(Wn,"");Z==="invoke"||Z==="invoke_sync"||Z==="get_progress"?p=Wt.substring(0,30):p=Z==="search_keyword"||Z==="file_map"?Wt:ee.basename(Wt.replace($r,"/"))}}}let Me=`${Zs[Z]||Z}${p?` ${p}`:""}`;if((Z!==ze||p!==sn)&&(ze=Z,sn=p,yield{type:"status",content:`${Me}`},process.stdout.isTTY)){let X={WebSearch:"Searching",web_search:"Searching",WebScrape:"Reading",web_scrape:"Reading",ReadFile:"Reading",read_file:"Reading",ReadFolder:"Reading",read_folder:"Reading",WriteFile:"Writing",write_file:"Writing",UpdateFile:"Editing",update_file:"Editing",WritePdf:"Creating",write_pdf:"Creating",WriteDocx:"Creating",write_docx:"Creating",SearchKeyword:"Searching",search_keyword:"Searching",CodeSearch:"Searching",code_search:"Searching",Run:"Executing",Ask:"User Input Required",AskUser:"User Input Required",Memory:"Updating Memory",GenerateImage:"Generating",InvokeSync:"Sub-Agent Working",invoke_sync:"Sub-Agent Working",Invoke:"Working",invoke:"Working",GetProgress:"Checking Progress",get_progress:"Checking Progress",Cancel:"Stopping Generalist",cancel:"Stopping Generalist",Await:"Waiting",await:"Waiting",EmergencyRollback:"Rolling the Ball",Answer:"Answering Sub-Agent",answer:"Answering Sub-Agent",Steer:"Steering Sub-Agent",steer:"Steering Sub-Agent",Click:"Clicking",click:"Clicking",Drag:"Dragging",drag:"Dragging",Scroll:"Scrolling",scroll:"Scrolling",KeyboardTyping:"Typing",keyboard_typing:"Typing",KeyPress:"Pressing Key",key_press:"Pressing Key",RecaptureScreen:"Recapturing Screen",recapture_screen:"Recapturing Screen"}[Z]||"Working";process.stdout.write(`\x1B]0;${X}...\x07`)}}if(ye.length-Zt>150){Zt=ye.length;let U=Kr(ye,!1),Z=Qs(U),Le=Z?(Z.innerContent||"").trim():"",p=Le.split(/[.!?]\s+/),Me=new Set(p),Ie=p.length>10?(p.length-Me.size)/p.length:0,X=Le.split(/\s+/).filter(Fe=>Fe.length>0).length,ln=.6,Nn=.8,En=!1;if(i.toLowerCase().includes("google")&&(be||"").toLowerCase().startsWith("gemma")){let S={low:256,medium:1024,high:8192,max:16384,xhigh:16384}[f?.toLowerCase()]||2500;En=X>S}if(Ie>ln||En){yield{type:"status",content:`${Ie>ln?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},Rt=!0,await new Promise(S=>setTimeout(S,3e3));break}let Wt=Wr(ye).trim().split(/[.!?]\s+/),mn=new Set(Wt);if((Wt.length>10?(Wt.length-mn.size)/Wt.length:0)>Nn){yield{type:"status",content:"Response Loop Detected. Re-centering..."},Rt=!1,_n=!0,await new Promise(Fe=>setTimeout(Fe,3e3));break}let zn=U.replace(Ma,"").replace(Ia,"").replace(Oa,"").replace(Da,""),Ft=zn.toLowerCase().split(/\s+/).map(Fe=>Fe.replace(La,"")).filter(Fe=>Fe.length>0),hn=!1;if(Ft.length>=10)for(let Fe=1;Fe<=15;Fe++){let S=Math.max(3,Math.ceil(10/Fe));if(Ft.length<Fe*S)continue;let V=Ft.slice(Ft.length-Fe),ne=V.join(" ");if(Fe>1&&ne===V.slice(0,Math.floor(Fe/2)).join(" ").repeat(2).trim())continue;let ce=!0;for(let pe=1;pe<S;pe++)if(Ft.slice(Ft.length-Fe*(pe+1),Ft.length-Fe*pe).join(" ")!==ne){ce=!1;break}if(ce){hn=!0;break}}if(!hn){let Fe=zn.toLowerCase().replace(Pa,"");if(Fe.length>=20)for(let S=1;S<=10;S++){let V=Math.max(5,Math.ceil(16/S));if(Fe.length<S*V)continue;let ne=Fe.substring(Fe.length-S),ce=!0;for(let pe=1;pe<V;pe++)if(Fe.substring(Fe.length-S*(pe+1),Fe.length-S*pe)!==ne){ce=!1;break}if(ce){hn=!0;break}}}if(hn){yield{type:"status",content:"Stuttering Detected. Re-centering..."},Rt=!1,rn=!0,await new Promise(Fe=>setTimeout(Fe,3e3));break}}let he=qt(ye),Xe=xo(he);for(;Xe.length>mt;){yield*Pn();let U=Xe[mt],Z=Date.now(),p={Ask:"ask",AskUser:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Await:"await",await:"await",AwaitSubagent:"await",awaitSubagent:"await",Answer:"answer",answer:"answer",AnswerSubagent:"answer",answerSubagent:"answer",Steer:"steer",steer:"steer",SteerSubagent:"steer",steerSubagent:"steer",Cancel:"cancel",cancel:"cancel",Click:"click",click:"click",Drag:"drag",drag:"drag",Scroll:"scroll",scroll:"scroll",KeyboardTyping:"keyboard_typing",keyboard_typing:"keyboard_typing",KeyPress:"key_press",key_press:"key_press",RecaptureScreen:"recapture_screen",recapture_screen:"recapture_screen",EmergencyRollback:"EmergencyRollback"}[U.toolName]||U.toolName,Me=Zs[p]||U.toolName,Ie=Gn(p,U.args);yield{type:"status",content:`${Me}${Ie?` ${Ie}`:""}`};let X="";if(p==="click"){let S=oe(U.args);X=`\u2714 Clicked: ${S.intendedClickText?`${S.intendedClickText}`:""}`}else if(p==="drag"){let S=oe(U.args);X=`\u2714 Dragged: Cell ${S.fromGridId||""} \u2192 Cell ${S.toGridId||""}`}else if(p==="scroll"){let S=oe(U.args);X=`\u2714 Scrolled: ${S.direction||"down"} (${S.amount||1})`}else if(p==="keyboard_typing"){let S=oe(U.args);X=`\u2714 Typed: ${S.text?`"${S.text.length>20?S.text.substring(0,20)+"...":S.text}"`:""}`}else if(p==="key_press")X=`\u2714 Pressed Key: ${oe(U.args).key||""}`;else if(p==="recapture_screen")X="\u2714 Recaptured Screen";else if(p==="web_search"){let{query:S,limit:V=10,aiMode:ne=!1}=oe(U.args);X=`${S?"\u2714":"\u2718"} ${ne?"AI Search":"Searched"}: ${S?`${S}`:"No Search Query"}${ne===!1&&S?` \u2192 ${V}`:""}`}else if(p==="web_scrape"){let S=oe(U.args).url||null;X=`${S?"\u2714":"\u2718"} Visited: ${S||"No Source"}`}else if(p==="view_file"){let{path:S,StartLine:V,EndLine:ne,start_line:ce,end_line:pe,startLine:He,endLine:Oe}=oe(U.args),Se=V||ce||He,q=ne||pe||Oe,se=parseInt(Se)||1,ae=parseInt(q)||(Se?se+800:800),qe="...",Ge=ae,Ae=(S||"").trim().toLowerCase().replaceAll("\\","/");if(Ae.startsWith("#skill"))Ae.startsWith("#skill/global/fluxflow")||Ae.startsWith("#skills/global/fluxflow")||Ae.includes("#skill/fluxflow")||Ae.includes("#skills/fluxflow")?X="\u2714 Read Documentation":X=`\u2714 Read Skill: ${ee.basename(S.replaceAll("\\","/"))}`;else{try{let xe=ee.resolve(process.cwd(),S);if(je.existsSync(xe)){let bt=je.readFileSync(xe,"utf8").split(`
759
+ `).length;qe=bt,!Se&&!q&&bt>800?Ge=Math.min(50,bt):Ge=Math.min(ae,bt)}}catch{}let Be=(S||"").toLowerCase(),pt=Be.endsWith(".pdf"),Ue=Be.endsWith(".docx")||Be.endsWith(".doc")||Be.endsWith(".ppt")||Be.endsWith(".pptx")||Be.endsWith(".xls")||Be.endsWith(".xlsx"),st=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(Be);pt||Ue?X=`${S.length>0?"\u2714":"\u2718"} ${S?`Analyzed: ${ee.basename(S)}`:"Analyzed: File Not Found"}`:st?X=`${S.length>0?"\u2714":"\u2718"} ${S?`Processed: ${ee.basename(S)}`:"Processed: File Not Found"}`:X=`${qe!=="..."?"\u2714":"\u2718"} Read: ${S?`${ee.basename(S)} \u2192 ${qe!=="..."?`Lines ${se} - ${Ge} of ${qe}`:"File Not Found"}`:"File Not Found"}`}}else if(p==="list_files"||p==="read_folder"){let S=p==="list_files"?"List":"Browsed",V=oe(U.args).path||null,ne=oe(U.args).recurse||1;X=`${V?"\u2714":"\u2718"} ${S}: ${V?`${V==="."?`./${ne>1?"*":""}`:`${V.replaceAll("\\","/")}${ne>1?`${V.endsWith("/")?"*":"/*"}`:`${V.endsWith("/")?"":"/"}`}`}`:"No Folder Selected"}`}else if(p==="write_file"||p==="update_file"){let S=p==="write_file"?"Created":"Edited",V=oe(U.args),ne=V.path||null,pe=Object.entries(V).some(([He,Oe])=>He.startsWith("searchContent")&&typeof Oe=="string"&&Oe.startsWith("^LINE:"))?"\u1361":":";X=`${ne?"\u2714":"\u2718"} ${S}${pe} ${ne?ne.replaceAll("\\","/"):"No File Changes"}`}else if(p==="write_pdf"){let S=oe(U.args).path||null;X=`${S?"\u2714":"\u2718"} Generated: ${S.replaceAll("\\","/")||"No PDF Generated"}`}else if(p==="write_docx"){let S=oe(U.args).path||null;X=`${S?"\u2714":"\u2718"} Generated: ${S.replaceAll("\\","/")||"No Docx Generated"}`}else if(p==="file_map"){let S=oe(U.args).path;X=`${S?"\u2714":"\u2718"} Indexed: ${S.replaceAll("\\","/")?""+S:"File Not Found"}`}else if(p.toLowerCase()==="search_keyword"||p.toLowerCase()==="todo")X="";else if(p.toLowerCase()==="generate_image"){let{path:S,outputPath:V,output:ne}=oe(U.args);X=`\u2714 Generated: ${S||V||ne||"generated_image.png"}`}else if(p==="invoke_sync"||p==="InvokeSync"){let S=Gn(p,U.args);X=`\u2714 Called Generalist${S?`: ${S}`:""}`}else if(p==="Invoke"||p==="InvokeAsync"||p==="invoke"){let S=Gn(p,U.args);X=`\u2714 Started Generalist${S?`: ${S}`:""}`}else if(p==="get_progress"||p==="GetProgress"){let S=Gn(p,U.args);X=`\u2714 Checked${S?`: ${S}`:""}`}else if(p==="cancel"){let S=Gn(p,U.args);X=`\u{1F6C7} Cancelled${S?`: ${S}`:""}`}else if(p==="steer"||p==="Steer"){let S=Gn(p,U.args);X=`\u2714 Steered${S?`: ${S}`:""}`}else if(p==="EmergencyRollback"){let{method:S}=oe(U.args);X=S==="forceRevert"?"":"\u2714 Rollback Point Checked"}else if(p==="await"||p==="Await"){let{time:S,timeout:V}=oe(U.args),ne=parseFloat(V||S)||0;ne||(ne=120);let ce=Oe=>{if(Oe>=60){let Se=Math.floor(Oe/60),q=Oe%60;return`${Se}m${q>0?` ${q}s`:""}`}return`${Oe}s`},pe=["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"];X=`\u2714 ${pe[Math.floor(Math.random()*pe.length)]} \u2192 ${ce(ne)}`}else p==="Answer"||p==="answer"?X="\u2714 Resolved Sub-Agent Query":p==="exec_command"||p==="ask"?X="":X=`Executed: ${U.toolName}`;if(yield*Pn(),p==="exec_command"){let{command:S}=oe(U.args);if(S&&n.systemSettings&&n.systemSettings.allowExternalAccess===!1){let V=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],ne=ee.resolve(process.cwd()).substring(0,3).toLowerCase(),ce=q=>{let se=[],ae="",qe=null;for(let Ge=0;Ge<q.length;Ge++){let Ae=q[Ge];qe?(Ae===qe&&(qe=null),ae+=Ae):Ae==='"'||Ae==="'"?(qe=Ae,ae+=Ae):Ae==="&"&&q[Ge+1]==="&"||Ae==="|"&&q[Ge+1]==="|"?(ae.trim()&&(se.push(ae.trim()),ae=""),Ge++):Ae===";"||Ae==="|"||Ae==="&"?ae.trim()&&(se.push(ae.trim()),ae=""):ae+=Ae}return ae.trim()&&se.push(ae.trim()),se},pe=q=>{let se=[],ae="",qe=null;for(let Ge=0;Ge<q.length;Ge++){let Ae=q[Ge];qe?(Ae===qe&&(qe=null),ae+=Ae):Ae==='"'||Ae==="'"?(qe=Ae,ae+=Ae):/\s/.test(Ae)?ae&&(se.push(ae),ae=""):ae+=Ae}return ae&&se.push(ae),se},He=q=>{let se=q.replace(/^['"]|['"]$/g,"").trim();return!se||process.platform==="win32"&&/^\/[a-zA-Z0-9?]+$/.test(se)?!1:V.some(ae=>{if(ae.source==="[a-zA-Z]:[\\\\\\/]"){let qe=se.match(/[a-zA-Z]:[\\\/]/i);return qe&&qe[0].toLowerCase()!==ne}return ae.test(se)})};if(ce(S).some(q=>{let se=pe(q);if(se.length===0)return!1;let ae=se[0].replace(/^['"]|['"]$/g,"").toLowerCase();if(["echo","printf","write-output"].includes(ae)){let Ge=!1;return se.some(Ae=>{let Ht=Ae.replace(/^['"]|['"]$/g,"");if(Ht===">"||Ht===">>"||Ht==="<")return Ge=!0,!1;if(Ht.startsWith(">")||Ht.startsWith("<")){let Be=Ht.replace(/^[><]+/,"");return He(Be)}return Ge?(Ge=!1,He(Ae)):!1})}return se.some(Ge=>He(Ge))})){let q='Access Denied. Prohibited from accessing external directories while "External Workspace Access" is disabled.';n.onExecStart&&n.onExecStart(S||"No Command"),yield{type:"exec_start"},await new Promise(se=>setTimeout(se,50)),n.onExecChunk&&n.onExecChunk(`ERROR: ${q}`),await new Promise(se=>setTimeout(se,50)),n.onExecEnd&&n.onExecEnd(),_e.push({role:"user",text:`[TOOL RESULT]: ERROR: ${q}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${q}`},mt++;continue}}n.onExecStart&&n.onExecStart(S||"No Command"),yield{type:"exec_start"}}let ln=oe(U.args),Nn=ln.path||ln.targetPath||null;if(Nn){let S=n.systemSettings&&n.systemSettings.allowExternalAccess===!1,V=ee.resolve(Nn),ne=ee.resolve(process.cwd());if(S&&!V.startsWith(ne)){let ce="Access Denied. You are not allowed to access files outside the current workspace.";if(p==="write_file"||p==="update_file"){let He=`\u2718 ${p==="write_file"?"Write Canceled":"Edit Canceled"}: ${ln.path||"..."}`,Oe=115;process.stdout.isTTY&&(Oe=process.stdout.columns-5||120);let Se=Math.min(He.length+4,Oe),q=`${He.padEnd(Se-2).substring(0,Se-2)}`;yield{type:"visual_feedback",content:Yt(`${Je?`
760
760
  `:""}${q}
761
- `)},Je=!1}_e.push({role:"user",text:`[TOOL RESULT]: ERROR: ${ce}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${ce}`},mt++;continue}}if(n.onToolApproval&&(p==="write_file"||p==="update_file"||p==="exec_command")){let V=n.systemSettings||{},ne=V.autoExec,ce=null,pe=!1,Ve=!1,Ie=!1;if(p==="exec_command"){let{command:Be}=oe(U.args),pt=(Be||"").trim(),Ue=(Gt,bt)=>{if(!bt)return!1;let en=bt.split(",").map(jt=>jt.trim().toLowerCase()).filter(Boolean),lt=Gt.toLowerCase();return en.some(jt=>lt.startsWith(jt))},st=Ue(pt,V.alwaysAskCommands),xe=Ue(pt,V.autoApproveCommands);if(Ve=Ue(pt,V.autoDisallowCommands),st?pe=!0:(xe||V.autoApproveGit&&/^git\s+commit\b/i.test(pt))&&(ce="allow"),!pe&&!ce){if(V.networkAccess===!1){let bt=pt.trim().replace(/\s+/g," ").replace(/^['"]+|['"]+$/g,"").toLowerCase().split(" "),lt=bt[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"]),ct=!1;jt.has(lt)&&(ct=!0);let it=Cn=>bt.slice(1).some(pn=>Cn.includes(pn)),ft=Cn=>{let pn=bt.findIndex(yn=>Cn.includes(yn)),Fn=bt.findIndex(yn=>["run","exec","test"].includes(yn));return pn!==-1&&!(Fn!==-1&&Fn<pn)};lt==="git"&&it(["clone","pull","push","fetch"])&&(ct=!0),lt==="go"&&it(["get","install"])&&(ct=!0),lt==="npm"&&ft(["install","i","update","add"])&&(ct=!0),lt==="yarn"&&ft(["add","install","upgrade"])&&(ct=!0),lt==="pnpm"&&ft(["add","install","update"])&&(ct=!0),lt==="bun"&&ft(["add","install","update"])&&(ct=!0),lt==="deno"&&it(["install","add"])&&(ct=!0),lt==="pip"&&it(["install","download"])&&(ct=!0),lt==="pip3"&&it(["install","download"])&&(ct=!0),lt==="cargo"&&it(["install","add"])&&(ct=!0),["bash","sh","zsh","fish"].includes(lt)&&it(["-c"])&&(ct=!0),lt==="cmd"&&it(["/c"])&&(ct=!0),ct&&(ce="deny",Ie=!0)}!ce&&Ve&&(ce="deny")}!pe&&!ce&&ne&&(ce="allow")}else ne&&(ce="allow");let Se=ce,q="";ce==="deny"&&(Ie?q="network":Ve?q="settings":q="prohibited");let se=!1,ae="",qe=[],He=0,Oe=!1,Ht="";if(!Se){if(p==="write_file"||p==="update_file")try{let Ue=oe(U.args),{path:st}=Ue;if(st){let xe=ee.resolve(process.cwd(),st),Gt=it=>it?it.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,ft=>ft.toUpperCase()):"",bt=Gt(xe),en="",lt=!1,jt=await Un(),ct=Gt(jt?.file_focused);if(jt&&ct===bt&&jt.full_content?(en=jt.full_content,lt=!0):Ge.existsSync(xe)&&(en=Ge.readFileSync(xe,"utf8"),lt=!0),ae=en,await Mo.recordFileChange(xe,en),lt){let it=en;if(p==="write_file"){let ft=Ue.content||Ue.newContent||"";it=ft.endsWith(`
761
+ `)},Je=!1}_e.push({role:"user",text:`[TOOL RESULT]: ERROR: ${ce}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${ce}`},mt++;continue}}if(n.onToolApproval&&(p==="write_file"||p==="update_file"||p==="exec_command")){let V=n.systemSettings||{},ne=V.autoExec,ce=null,pe=!1,He=!1,Oe=!1;if(p==="exec_command"){let{command:Be}=oe(U.args),pt=(Be||"").trim(),Ue=(Gt,bt)=>{if(!bt)return!1;let en=bt.split(",").map(jt=>jt.trim().toLowerCase()).filter(Boolean),lt=Gt.toLowerCase();return en.some(jt=>lt.startsWith(jt))},st=Ue(pt,V.alwaysAskCommands),xe=Ue(pt,V.autoApproveCommands);if(He=Ue(pt,V.autoDisallowCommands),st?pe=!0:(xe||V.autoApproveGit&&/^git\s+commit\b/i.test(pt))&&(ce="allow"),!pe&&!ce){if(V.networkAccess===!1){let bt=pt.trim().replace(/\s+/g," ").replace(/^['"]+|['"]+$/g,"").toLowerCase().split(" "),lt=bt[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"]),ct=!1;jt.has(lt)&&(ct=!0);let it=Cn=>bt.slice(1).some(pn=>Cn.includes(pn)),ft=Cn=>{let pn=bt.findIndex(yn=>Cn.includes(yn)),Fn=bt.findIndex(yn=>["run","exec","test"].includes(yn));return pn!==-1&&!(Fn!==-1&&Fn<pn)};lt==="git"&&it(["clone","pull","push","fetch"])&&(ct=!0),lt==="go"&&it(["get","install"])&&(ct=!0),lt==="npm"&&ft(["install","i","update","add"])&&(ct=!0),lt==="yarn"&&ft(["add","install","upgrade"])&&(ct=!0),lt==="pnpm"&&ft(["add","install","update"])&&(ct=!0),lt==="bun"&&ft(["add","install","update"])&&(ct=!0),lt==="deno"&&it(["install","add"])&&(ct=!0),lt==="pip"&&it(["install","download"])&&(ct=!0),lt==="pip3"&&it(["install","download"])&&(ct=!0),lt==="cargo"&&it(["install","add"])&&(ct=!0),["bash","sh","zsh","fish"].includes(lt)&&it(["-c"])&&(ct=!0),lt==="cmd"&&it(["/c"])&&(ct=!0),ct&&(ce="deny",Oe=!0)}!ce&&He&&(ce="deny")}!pe&&!ce&&ne&&(ce="allow")}else ne&&(ce="allow");let Se=ce,q="";ce==="deny"&&(Oe?q="network":He?q="settings":q="prohibited");let se=!1,ae="",qe=[],Ge=0,Ae=!1,Ht="";if(!Se){if(p==="write_file"||p==="update_file")try{let Ue=oe(U.args),{path:st}=Ue;if(st){let xe=ee.resolve(process.cwd(),st),Gt=it=>it?it.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,ft=>ft.toUpperCase()):"",bt=Gt(xe),en="",lt=!1,jt=await Un(),ct=Gt(jt?.file_focused);if(jt&&ct===bt&&jt.full_content?(en=jt.full_content,lt=!0):je.existsSync(xe)&&(en=je.readFileSync(xe,"utf8"),lt=!0),ae=en,await Mo.recordFileChange(xe,en),lt){let it=en;if(p==="write_file"){let ft=Ue.content||Ue.newContent||"";it=ft.endsWith(`
762
762
  `)?ft:ft+`
763
- `,Ht=it}else{let{patchPairs:ft,allowMultiple:Cn,error:pn}=yi(Ue);if(pn){let Qt=`[TOOL RESULT]: ERROR: ${pn}`;_e.push({role:"user",text:Qt}),await Ct("toolFailure"),n.onToolResult&&n.onToolResult("failure",p),yield{type:"tool_result",content:Qt,toolName:p},mt++;continue}let Fn=Ue.allowMultiple!==void 0?Ue.allowMultiple===!0||String(Ue.allowMultiple).toLowerCase()==="true":Cn;He=ft.length;let yn=xi(en,ft,{allowMultiple:Fn});it=yn.content,Ht=it,qe=yn.results;let _o=qe.filter(Qt=>Qt.success),ms=qe.filter(Qt=>!Qt.success);if(_o.length===0){let Qt=`[TOOL RESULT]: ERROR: Failed to apply patches to [${ee.basename(xe)}].
763
+ `,Ht=it}else{let{patchPairs:ft,allowMultiple:Cn,error:pn}=yi(Ue);if(pn){let Qt=`[TOOL RESULT]: ERROR: ${pn}`;_e.push({role:"user",text:Qt}),await Ct("toolFailure"),n.onToolResult&&n.onToolResult("failure",p),yield{type:"tool_result",content:Qt,toolName:p},mt++;continue}let Fn=Ue.allowMultiple!==void 0?Ue.allowMultiple===!0||String(Ue.allowMultiple).toLowerCase()==="true":Cn;Ge=ft.length;let yn=xi(en,ft,{allowMultiple:Fn});it=yn.content,Ht=it,qe=yn.results;let _o=qe.filter(Qt=>Qt.success),ms=qe.filter(Qt=>!Qt.success);if(_o.length===0){let Qt=`[TOOL RESULT]: ERROR: Failed to apply patches to [${ee.basename(xe)}].
764
764
  ${ms.map(Ao=>` \u2022 ${Ao.error}`).join(`
765
765
  `)}`,no=`\u2714 Edited: ${ee.basename(xe.replaceAll("\\","/"))}`,ut=115;process.stdout.isTTY&&(ut=process.stdout.columns-5||120);let Vt=Math.min(no.length+4,ut),oo=`${no.padEnd(Vt-2).substring(0,Vt-2)}`;yield{type:"visual_feedback",content:Yt(`${Je?`
766
766
  `:""}${oo}`)},Je=!1,_e.push({role:"user",text:Qt}),await Ct("toolFailure"),n.onToolResult&&n.onToolResult("failure",p),yield{type:"tool_result",content:Qt,toolName:p},mt++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${ee.basename(xe)}`},Vs(xe,en,it),se=!0,await new Promise(ft=>setTimeout(ft,50))}else if(p==="write_file"){let it=Ue.content||Ue.newContent||"",ft=it.endsWith(`
767
767
  `)?it:it+`
768
- `;Ht=ft,Ge.existsSync(xe)||(Oe=!0,Ge.mkdirSync(ee.dirname(xe),{recursive:!0}),Ge.writeFileSync(xe,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${ee.basename(xe)}`},Vs(xe,"",ft),se=!0,await new Promise(Cn=>setTimeout(Cn,50))}}}catch(Ue){console.error("Simulation/Diff Error:",Ue)}let Be=null;js(Ue=>{Be=Ue});let pt=n.onToolApproval;if(Se=await new Promise(async Ue=>{let st=setInterval(()=>{Be&&(os.onIDEApproval&&os.onIDEApproval(Be),clearInterval(st),Ue(Be))},100);try{let xe=await pt(p,U.args);clearInterval(st),Ue(xe)}catch{clearInterval(st),Ue("deny")}}),js(null),p==="write_file"||p==="update_file"){let{path:Ue}=oe(U.args);if(Ue){let st=ee.resolve(process.cwd(),Ue);if(Dr(st,Se),Se==="deny"&&Oe&&Ge.existsSync(st))try{Ge.unlinkSync(st)}catch{}}}Se==="deny"&&(q="user")}if(Se==="allow"&&se&&Vo()){let{path:Be}=oe(U.args),pt=ee.resolve(process.cwd(),Be),Ue=ut=>ut?ee.resolve(ut).replace(/\\/g,"/").toLowerCase():"",st=await Un(),xe="";if(st&&st.file_focused&&Ue(st.file_focused)===Ue(pt)&&st.full_content&&(xe=st.full_content),!xe&&Ge.existsSync(pt)){let ut=Ge.readFileSync(pt,"utf8");ut&&(xe=ut)}!xe&&Ht&&(xe=Ht),(xe||Oe)&&Ge.writeFileSync(pt,xe,"utf8");let Gt=xe.split(/\r?\n/),bt=Gt.length,en=Buffer.byteLength(xe,"utf8"),lt="";ae&&(lt=`Old File contents:
768
+ `;Ht=ft,je.existsSync(xe)||(Ae=!0,je.mkdirSync(ee.dirname(xe),{recursive:!0}),je.writeFileSync(xe,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${ee.basename(xe)}`},Vs(xe,"",ft),se=!0,await new Promise(Cn=>setTimeout(Cn,50))}}}catch(Ue){console.error("Simulation/Diff Error:",Ue)}let Be=null;js(Ue=>{Be=Ue});let pt=n.onToolApproval;if(Se=await new Promise(async Ue=>{let st=setInterval(()=>{Be&&(os.onIDEApproval&&os.onIDEApproval(Be),clearInterval(st),Ue(Be))},100);try{let xe=await pt(p,U.args);clearInterval(st),Ue(xe)}catch{clearInterval(st),Ue("deny")}}),js(null),p==="write_file"||p==="update_file"){let{path:Ue}=oe(U.args);if(Ue){let st=ee.resolve(process.cwd(),Ue);if(Dr(st,Se),Se==="deny"&&Ae&&je.existsSync(st))try{je.unlinkSync(st)}catch{}}}Se==="deny"&&(q="user")}if(Se==="allow"&&se&&Vo()){let{path:Be}=oe(U.args),pt=ee.resolve(process.cwd(),Be),Ue=ut=>ut?ee.resolve(ut).replace(/\\/g,"/").toLowerCase():"",st=await Un(),xe="";if(st&&st.file_focused&&Ue(st.file_focused)===Ue(pt)&&st.full_content&&(xe=st.full_content),!xe&&je.existsSync(pt)){let ut=je.readFileSync(pt,"utf8");ut&&(xe=ut)}!xe&&Ht&&(xe=Ht),(xe||Ae)&&je.writeFileSync(pt,xe,"utf8");let Gt=xe.split(/\r?\n/),bt=Gt.length,en=Buffer.byteLength(xe,"utf8"),lt="";ae&&(lt=`Old File contents:
769
769
  ${ae.split(/\r?\n/).map((Vt,oo)=>`${oo+1} | ${Vt}`).join(`
770
770
  `)}
771
771
 
@@ -776,7 +776,7 @@ ${ae.split(/\r?\n/).map((Vt,oo)=>`${oo+1} | ${Vt}`).join(`
776
776
 
777
777
  ... [${bt-100} lines truncated for history stability] ...
778
778
 
779
- ${Vt}`}let ct="";if(p==="update_file"){let ut=bi(ae,xe,qe,12,n?.compressToolResults||os?.systemSettings?.compressToolResults);ct=`SUCCESS: File [${Be}] updated via IDE Companion (May have user edits). [${qe.length}/${He}] blocks applied.
779
+ ${Vt}`}let ct="";if(p==="update_file"){let ut=bi(ae,xe,qe,12,n?.compressToolResults||os?.systemSettings?.compressToolResults);ct=`SUCCESS: File [${Be}] updated via IDE Companion (May have user edits). [${qe.length}/${Ge}] blocks applied.
780
780
 
781
781
  ${ut}`}else{let ut=xe.split(/\r?\n/),Vt=ut.length,oo=Buffer.byteLength(xe,"utf8"),Ao="";ae&&(Ao=`Old File contents:
782
782
  ${ae.split(/\r?\n/).map((ps,la)=>`${la+1} | ${ps}`).join(`
@@ -794,21 +794,21 @@ ${ps}`}ct=`SUCCESS: File [${Be}] saved via IDE Companion (May have user edits).
794
794
  ${Ao}- Content Preview:
795
795
 
796
796
  ${hs}`}let it=p==="write_file"?"Created":"Edited",ft=oe(U.args),pn=Object.entries(ft).some(([ut,Vt])=>ut.startsWith("searchContent")&&typeof Vt=="string"&&Vt.startsWith("^LINE:"))?"\u1361":":",Fn=`${Be?"\u2714":"\u2718"} ${it}${pn} ${Be?Be.replaceAll("\\","/"):"No File Changes"}`,yn=115;process.stdout.isTTY&&(yn=process.stdout.columns-5||120);let _o=Math.min(Fn.length+4,yn),ms=`${Fn.padEnd(_o-2).substring(0,_o-2)}`;yield{type:"visual_feedback",content:Yt(`${Je?`
797
- `:""}${ms}`)},Je=!1;let Qt=Date.now();je=Qt,yield{type:"tool_time",content:Qt-Z};let no=`[TOOL RESULT]: ${ct}`;_e.push({role:"user",text:no}),Sn=!0,await Ct("toolSuccess"),n.onToolResult&&n.onToolResult("success",p),yield{type:"tool_result",content:ct,aiContent:no,toolName:p},mt++;continue}if(Se==="deny"){let Be=`Permission Denied: Prohibited ${p==="exec_command"?"Command":"file edit"}.`;if(q==="user"?Be="Permission Denied by User":q==="settings"?Be="Permission Denied by User Policy":q==="network"?Be="Permission Denied: Sandbox Network Access Disabled by User Policy.":q==="prohibited"&&p==="exec_command"&&(Be="Permission Denied: Prohibited Command in User Policy"),p==="write_file"||p==="update_file"){let Ue=`\u2718 ${p==="write_file"?"Write Cancelled":"Edit Denied"}: ${oe(U.args).path.replaceAll("\\","/")||"..."}`,st=115;process.stdout.isTTY&&(st=process.stdout.columns-5||120);let xe=Math.min(Ue.length+4,st),Gt=`${Ue.padEnd(xe-2).substring(0,xe-2)}`,bt=` ${" ".repeat(xe)} `;yield{type:"visual_feedback",content:Yt(`${Je?`
797
+ `:""}${ms}`)},Je=!1;let Qt=Date.now();Ve=Qt,yield{type:"tool_time",content:Qt-Z};let no=`[TOOL RESULT]: ${ct}`;_e.push({role:"user",text:no}),Sn=!0,await Ct("toolSuccess"),n.onToolResult&&n.onToolResult("success",p),yield{type:"tool_result",content:ct,aiContent:no,toolName:p},mt++;continue}if(Se==="deny"){let Be=`Permission Denied: Prohibited ${p==="exec_command"?"Command":"file edit"}.`;if(q==="user"?Be="Permission Denied by User":q==="settings"?Be="Permission Denied by User Policy":q==="network"?Be="Permission Denied: Sandbox Network Access Disabled by User Policy.":q==="prohibited"&&p==="exec_command"&&(Be="Permission Denied: Prohibited Command in User Policy"),p==="write_file"||p==="update_file"){let Ue=`\u2718 ${p==="write_file"?"Write Cancelled":"Edit Denied"}: ${oe(U.args).path.replaceAll("\\","/")||"..."}`,st=115;process.stdout.isTTY&&(st=process.stdout.columns-5||120);let xe=Math.min(Ue.length+4,st),Gt=`${Ue.padEnd(xe-2).substring(0,xe-2)}`,bt=` ${" ".repeat(xe)} `;yield{type:"visual_feedback",content:Yt(`${Je?`
798
798
  `:""}${Gt}
799
799
  `)},Je=!1}p==="exec_command"&&(await new Promise(pt=>setTimeout(pt,50)),n.onExecChunk&&n.onExecChunk(`ERROR: ${Be}`),await new Promise(pt=>setTimeout(pt,50)),n.onExecEnd&&n.onExecEnd()),_e.push({role:"user",text:`[TOOL RESULT]: DENIED: ${Be}`}),yield{type:"tool_result",content:`[TOOL RESULT]: DENIED: ${Be}`},await Ct("toolDenied"),n.onToolResult&&n.onToolResult("denied",p),mt++;continue}}if(X){let S=115;process.stdout.isTTY&&(S=process.stdout.columns-5||120);let V=await s(),ne=!1;V&&(ne=V.trim().length>0);let ce=Math.min(X.length+4,S),pe=`${X.padEnd(ce-2).substring(0,ce-2)}`;yield{type:"visual_feedback",content:Yt(`${Je?`
800
800
  `:""}${pe}${X.includes("\u2714")&&(X.includes("Created")||X.includes("Edited"))?"":`${ne?"":`
801
- `}`}`)},Je=!1}if(je>0){let S=Date.now()-je,V=Math.max(0,1e3-S);V>0&&await new Promise(ne=>setTimeout(ne,V))}let En={chatId:g,history:t,onChunk:S=>n.onExecChunk?n.onExecChunk(S):null,onAskUser:n.onAskUser,systemSettings:n.systemSettings,mode:a,isMultiModal:gt(be),onVisualFeedback:n.onVisualFeedback,onSubagentUpdate:n.onSubagentUpdate,onTokenChunk:n.onTokenChunk,modelName:be,aiProvider:n.aiProvider,apiKey:n.apiKey,onUsage:n.onUsage};if(p==="write_file"||p==="update_file")try{let{path:S}=oe(U.args);if(S){let V=ee.resolve(process.cwd(),S),ne=await Un();ne&&ne.file_focused===V&&ne.full_content&&(En.forcedContent=ne.full_content)}}catch{}et.push(p);let $e=await ho(p,U.args,En);if((p==="write_file"||p==="update_file")&&$e.startsWith("SUCCESS")){let{path:S}=oe(U.args);if(S){let V=ee.resolve(process.cwd(),S);Or(V)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let Nt=Date.now();je=Nt,yield{type:"tool_time",content:Nt-Z},j=Nt;let Wt=null;if(typeof $e=="object"&&$e.binaryPart&&(Wt=$e.binaryPart,$e=$e.text),p==="search_keyword"){let{keyword:S,path:V}=oe(U.args),ne=typeof $e=="string"&&$e.startsWith("[GLOB]");ne&&($e=$e.slice(6).trimStart());let ce=typeof $e=="string"&&$e.startsWith("[DIR]");ce&&($e=$e.slice(5).trimStart());let pe=0;if($e){let He=$e.match(/Found (\d+) match/i);He&&(pe=parseInt(He[1]))}let Ve=(V||"").trim().toLowerCase().replaceAll("\\","/"),Ie=Ve==="#doc"||Ve==="#docs"||Ve==="#documentation"||Ve.includes("#skill/global/fluxflow")||Ve.includes("#skills/global/fluxflow"),Se,q=115;process.stdout.isTTY&&(q=process.stdout.columns-5||120);let se=Math.max(10,(q+5)/3);if(Ie)Se=`${S?"\u2714":"\u2718"} Searched Documentation`;else{let He=V?V.replace(/[\/\\]+$/,""):null,Oe=He&&He!=="."?`"${ne?V:ce?`${He}/*`:He}"`:"./";Se=`${S?"\u2714":"\u2718"} Searched: "${S?S.length>q/2?`${S.slice(se)}...`:S:""}" in ${Oe.replaceAll("\\","/")} \u2192 ${pe} Match${pe===1?"":"es"}`}let ae=Math.min(Se.length+4,q),qe=`${Se.padEnd(ae-2).substring(0,ae-2)}`;yield{type:"visual_feedback",content:Yt(`${Je?`
801
+ `}`}`)},Je=!1}if(Ve>0){let S=Date.now()-Ve,V=Math.max(0,1e3-S);V>0&&await new Promise(ne=>setTimeout(ne,V))}let En={chatId:g,history:t,onChunk:S=>n.onExecChunk?n.onExecChunk(S):null,onAskUser:n.onAskUser,systemSettings:n.systemSettings,mode:a,isMultiModal:gt(be),onVisualFeedback:n.onVisualFeedback,onSubagentUpdate:n.onSubagentUpdate,onTokenChunk:n.onTokenChunk,modelName:be,aiProvider:n.aiProvider,apiKey:n.apiKey,onUsage:n.onUsage};if(p==="write_file"||p==="update_file")try{let{path:S}=oe(U.args);if(S){let V=ee.resolve(process.cwd(),S),ne=await Un();ne&&ne.file_focused===V&&ne.full_content&&(En.forcedContent=ne.full_content)}}catch{}et.push(p);let $e=await ho(p,U.args,En);if((p==="write_file"||p==="update_file")&&$e.startsWith("SUCCESS")){let{path:S}=oe(U.args);if(S){let V=ee.resolve(process.cwd(),S);Or(V)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let Nt=Date.now();Ve=Nt,yield{type:"tool_time",content:Nt-Z},j=Nt;let Wt=null;if(typeof $e=="object"&&$e.binaryPart&&(Wt=$e.binaryPart,$e=$e.text),p==="search_keyword"){let{keyword:S,path:V}=oe(U.args),ne=typeof $e=="string"&&$e.startsWith("[GLOB]");ne&&($e=$e.slice(6).trimStart());let ce=typeof $e=="string"&&$e.startsWith("[DIR]");ce&&($e=$e.slice(5).trimStart());let pe=0;if($e){let Ge=$e.match(/Found (\d+) match/i);Ge&&(pe=parseInt(Ge[1]))}let He=(V||"").trim().toLowerCase().replaceAll("\\","/"),Oe=He==="#doc"||He==="#docs"||He==="#documentation"||He.includes("#skill/global/fluxflow")||He.includes("#skill/fluxflow")||He.includes("#skills/fluxflow")||He.includes("#skills/global/fluxflow"),Se,q=115;process.stdout.isTTY&&(q=process.stdout.columns-5||120);let se=Math.max(10,(q+5)/3);if(Oe)Se=`${S?"\u2714":"\u2718"} Searched Documentation`;else{let Ge=V?V.replace(/[\/\\]+$/,""):null,Ae=Ge&&Ge!=="."?`"${ne?V:ce?`${Ge}/*`:Ge}"`:"./";Se=`${S?"\u2714":"\u2718"} Searched: "${S?S.length>q/2?`${S.slice(se)}...`:S:""}" in ${Ae.replaceAll("\\","/")} \u2192 ${pe} Match${pe===1?"":"es"}`}let ae=Math.min(Se.length+4,q),qe=`${Se.padEnd(ae-2).substring(0,ae-2)}`;yield{type:"visual_feedback",content:Yt(`${Je?`
802
802
  `:""}${qe}
803
- `)},Je=!1}if(p==="EmergencyRollback"){let{method:S}=oe(U.args);if(S==="forceRevert"){let V=0;if($e){let se=$e.match(/Total\s*:\s*(\d+)/i);se&&(V=parseInt(se[1]))}let ce=$e&&$e.startsWith("ERROR:")?"\u2718 Emergency Rollback Failed":`\u2714 Emergency Rollback \u2192 ${V} file${V===1?"":"s"} processed`,pe=115;process.stdout.isTTY&&(pe=process.stdout.columns-5||120);let Ve=await s(),Ie=!1;Ve&&(Ie=Ve.trim().length>0);let Se=Math.min(ce.length+4,pe),q=`${ce.padEnd(Se-2).substring(0,Se-2)}`;yield{type:"visual_feedback",content:Yt(`${Je?`
804
- `:""}${q}${Ie?"":`
805
- `}`)},Je=!1}}if(p==="todo"){let{method:S,tasks:V,markDone:ne}=oe(U.args),ce="",pe=[],Ve=Ie=>{if(!Ie)return[];let Se=Array.isArray(Ie)?Ie:[];if(Se.length===0&&typeof Ie=="string"){let q=Ie.trim();if(q.startsWith("[")&&q.endsWith("]")){let se=q.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);se?Se=se.map(ae=>ae.slice(1,-1).replace(/\\(.)/g,"$1")):Se=q.slice(1,-1).split(",").map(ae=>ae.trim()).filter(Boolean)}else Se=Ie.split(`
806
- `)}return Se.filter(q=>String(q).trim()).map(q=>{let se=String(q).trim();return se.startsWith("- [")?se.substring(6).trim():se})};if(S==="create"?(ce="\x1B[32m\u2192\x1B[0m Created Goals",pe=Ve(V).map(Ie=>`\x1B[90m\u25CB\x1B[0m ${Ie}`)):S==="append"?(ce="\x1B[34m\u2795\x1B[0m Added New Goals",pe=Ve(V).map(Ie=>`\x1B[90m\u25CB\x1B[0m ${Ie}`)):S==="get"&&(ce=ne?"\x1B[36m\u21BB\x1B[0m Updated Goals":"\x1B[35m\u2022\x1B[0m Reviewed Goals",pe=($e||"").split(`
803
+ `)},Je=!1}if(p==="EmergencyRollback"){let{method:S}=oe(U.args);if(S==="forceRevert"){let V=0;if($e){let se=$e.match(/Total\s*:\s*(\d+)/i);se&&(V=parseInt(se[1]))}let ce=$e&&$e.startsWith("ERROR:")?"\u2718 Emergency Rollback Failed":`\u2714 Emergency Rollback \u2192 ${V} file${V===1?"":"s"} processed`,pe=115;process.stdout.isTTY&&(pe=process.stdout.columns-5||120);let He=await s(),Oe=!1;He&&(Oe=He.trim().length>0);let Se=Math.min(ce.length+4,pe),q=`${ce.padEnd(Se-2).substring(0,Se-2)}`;yield{type:"visual_feedback",content:Yt(`${Je?`
804
+ `:""}${q}${Oe?"":`
805
+ `}`)},Je=!1}}if(p==="todo"){let{method:S,tasks:V,markDone:ne}=oe(U.args),ce="",pe=[],He=Oe=>{if(!Oe)return[];let Se=Array.isArray(Oe)?Oe:[];if(Se.length===0&&typeof Oe=="string"){let q=Oe.trim();if(q.startsWith("[")&&q.endsWith("]")){let se=q.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);se?Se=se.map(ae=>ae.slice(1,-1).replace(/\\(.)/g,"$1")):Se=q.slice(1,-1).split(",").map(ae=>ae.trim()).filter(Boolean)}else Se=Oe.split(`
806
+ `)}return Se.filter(q=>String(q).trim()).map(q=>{let se=String(q).trim();return se.startsWith("- [")?se.substring(6).trim():se})};if(S==="create"?(ce="\x1B[32m\u2192\x1B[0m Created Goals",pe=He(V).map(Oe=>`\x1B[90m\u25CB\x1B[0m ${Oe}`)):S==="append"?(ce="\x1B[34m\u2795\x1B[0m Added New Goals",pe=He(V).map(Oe=>`\x1B[90m\u25CB\x1B[0m ${Oe}`)):S==="get"&&(ce=ne?"\x1B[36m\u21BB\x1B[0m Updated Goals":"\x1B[35m\u2022\x1B[0m Reviewed Goals",pe=($e||"").split(`
807
807
  `).slice(1).join(`
808
808
  `).split(`
809
- `).filter(Se=>Se.trim().startsWith("- [")).map(Se=>{let q=Se.trim(),se=q.startsWith("- [x]");return`${se?"\x1B[32m\u2714\x1B[0m":"\x1B[90m\u25CB\x1B[0m"} ${se?"\x1B[90m":"\x1B[37m"}${q.substring(6).trim()}\x1B[0m`})),ce&&pe.length>0){let Ie=[`${ce}`,...pe.map(se=>` ${se}`)].join(`
809
+ `).filter(Se=>Se.trim().startsWith("- [")).map(Se=>{let q=Se.trim(),se=q.startsWith("- [x]");return`${se?"\x1B[32m\u2714\x1B[0m":"\x1B[90m\u25CB\x1B[0m"} ${se?"\x1B[90m":"\x1B[37m"}${q.substring(6).trim()}\x1B[0m`})),ce&&pe.length>0){let Oe=[`${ce}`,...pe.map(se=>` ${se}`)].join(`
810
810
  `),Se=await s(),q=!1;Se&&(q=Se.trim().length>0),yield{type:"visual_feedback",content:Yt(`${Je?`
811
- `:""}${Ie}${q?"":`
811
+ `:""}${Oe}${q?"":`
812
812
  `}`)},Je=!1}}p==="exec_command"&&n.onExecEnd&&(await new Promise(S=>setTimeout(S,800)),n.onExecEnd());let mn=$e&&$e.startsWith("DENIED:");$e&&!$e.startsWith("ERROR:")&&!mn?(await Ct("toolSuccess"),n.onToolResult&&n.onToolResult("success",p)):mn||(await Ct("toolFailure"),n.onToolResult&&n.onToolResult("failure",p));let Ft=($e||"").toString().replaceAll("[UI_CONTEXT]","");Ft.includes("[[VERIFIED]]")&&(Ft=Ft.replace(/\[\[VERIFIED\]\][\s\S]*?\[\[\/VERIFIED\]\]/g,`[SYSTEM NOTE]: Patch Block matched & applied successfully. Large Block omitted to conserve context.
813
813
  `));let hn;if(Ft.startsWith("[[SAME]]")){let V=Ft.replace(/^\[\[SAME\]\]\s*\r?\n?/,"").split(/\r?\n/),ne=V.filter(pe=>pe.startsWith("SUCCESS:")||pe.trim().startsWith("- Stats:"));hn=`[TOOL RESULT]: ${ne.length>0?ne.join(`
814
814
  `):V.slice(0,2).join(`
@@ -817,7 +817,7 @@ ${hs}`}let it=p==="write_file"?"Created":"Edited",ft=oe(U.args),pn=Object.entrie
817
817
  `,"").replaceAll(`
818
818
  [[/VERIFIED]]`,"")||""}`;(p==="view_file"||p==="web_scrape"||p==="file_map")&&(Fe=`[TOOL RESULT]: ${X} (Context Locked for UI Clarity)`),yield{type:"tool_result",content:Fe,aiContent:hn,binaryPart:Wt,toolName:p},p==="memory"&&$e.includes("SUCCESS")&&(yield{type:"memory_updated"}),mt++}if(i==="Google"&&an&&Date.now()-fs>=150){yield*Pn();let U=eo(an);for(let Z of U)yield Z;an="",fs=Date.now()}}I.usageMetadata&&(un=I.usageMetadata),un&&(yield{type:"liveTokens",content:un.totalTokenCount})}if(fe&&(fe=!1,Dt?tt+="</think>":(ye+="</think>",i==="Google"?an+="</think>":yield{type:"text",content:"</think>"})),Dt&&tt.length>0){let I=0,K=Math.min(xt.length,tt.length);for(let W=K;W>0;W--)if(xt.endsWith(tt.substring(0,W))){I=W;break}let $=tt.substring(I);if($){let Te=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(xt)?$.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):$.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(Te)if(ye+=Te,i==="Google")an+=Te;else{yield*Pn();let ke=eo(Te);for(let he of ke)yield he}}Dt=!1,tt=""}if(yield*Pn(),kt)break;let to=(ye||"").trim(),na=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(to.toLowerCase())||/\[\[END\]\]/i.test(to.toLowerCase()),oa=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(to.toLowerCase()),sa=_e.length>0||ze!==null,us=qt(to).trim(),ia=/(\p{Emoji_Presentation}|\p{Extended_Pictographic})$/u.test(us),ra=/([.!?"'*_`|\]\)”’~~]+|\s|`{3}|[\u200B-\u200D\uFEFF])$/u.test(us.trim()),aa=/[.!?}"'`’“”]$|```$/s.test(us)||ra||ia;!na&&!oa&&!sa&&to.length>0,rt=!0,await Ct("agent",i)}catch(we){if(kt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
819
819
 
820
- \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(String(we).includes("Incomplete JSON segment at the end")){fe&&(fe=!1,Dt?tt+="</think>":(ye+="</think>",yield{type:"text",content:"</think>"})),rt=!0,await Ct("agent",i);break}if(fe&&(fe=!1,Dt?tt+="</think>":ye+="</think>"),Dt&&tt.length>0){let $t=0,At=Math.min(xt.length,tt.length);for(let It=At;It>0;It--)if(xt.endsWith(tt.substring(0,It))){$t=It;break}let wt=tt.substring($t);if(wt){let ht=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(xt)?wt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):wt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");ht&&(ye+=ht)}Dt=!1,tt=""}let Q=we instanceof Error?(()=>{try{return JSON.parse(JSON.parse(we.message).error.message).error.message}catch{return String(we)}})():String(we),Pt=new Date().toLocaleString(),Mt=ee.join(vn,"agent");Ge.existsSync(Mt)||Ge.mkdirSync(Mt,{recursive:!0}),Ge.appendFileSync(ee.join(Mt,"error.log"),`ERROR [${Pt}]: ${Q}
820
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(String(we).includes("Incomplete JSON segment at the end")){fe&&(fe=!1,Dt?tt+="</think>":(ye+="</think>",yield{type:"text",content:"</think>"})),rt=!0,await Ct("agent",i);break}if(fe&&(fe=!1,Dt?tt+="</think>":ye+="</think>"),Dt&&tt.length>0){let $t=0,At=Math.min(xt.length,tt.length);for(let It=At;It>0;It--)if(xt.endsWith(tt.substring(0,It))){$t=It;break}let wt=tt.substring($t);if(wt){let ht=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(xt)?wt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):wt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");ht&&(ye+=ht)}Dt=!1,tt=""}let Q=we instanceof Error?(()=>{try{return JSON.parse(JSON.parse(we.message).error.message).error.message}catch{return String(we)}})():String(we),Pt=new Date().toLocaleString(),Mt=ee.join(vn,"agent");je.existsSync(Mt)||je.mkdirSync(Mt,{recursive:!0}),je.appendFileSync(ee.join(Mt,"error.log"),`ERROR [${Pt}]: ${Q}
821
821
 
822
822
  ----------------------------------------------------------------------
823
823
 
@@ -855,13 +855,13 @@ ${G}
855
855
  ${G}`).trim();yield{type:"interactive_turn_finished",data:{agentText:y,fullAgentTextRaw:Pe,history:[...r],needTitle:L}},yield{type:"status",content:"[end]"}}}catch(b){let r=b?.cause?` (Cause: ${b.cause?.message||String(b.cause)})`:"",A=(b instanceof Error?(()=>{try{return JSON.parse(JSON.parse(b.message).error.message).error.message}catch{return(b.message?`${b.message}${r}`:"")||String(b)}})():String(b)).replace(/^(Error:\s*)+/i,""),O=new Date().toLocaleString(),H=ee.join(vn,"agent");yield{type:"text",content:`
856
856
 
857
857
  \u2726 CRITICAL ERROR: ${A.includes("fetch failed")?"Failed to Connect. Check your Internet Connection or Wait a moment":A}
858
- \u2800`},Ge.existsSync(H)||Ge.mkdirSync(H,{recursive:!0}),Ge.appendFileSync(ee.join(H,"error.log"),`CRITICAL ERROR [${O}]: ${b}${b?.cause?`
858
+ \u2800`},je.existsSync(H)||je.mkdirSync(H,{recursive:!0}),je.appendFileSync(ee.join(H,"error.log"),`CRITICAL ERROR [${O}]: ${b}${b?.cause?`
859
859
  CAUSE: ${b.cause?.stack||b.cause}`:""}
860
860
 
861
861
  ----------------------------------------------------------------------
862
862
 
863
863
  `),typeof flushGoogleBuffer=="function"&&(yield*flushGoogleBuffer()),yield{type:"tool_result",content:`ERROR: [INTERNAL CRITICAL] ${A}`}}finally{d&&(clearInterval(d),d=null),typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),await Mo.commitTransaction(),h?.advanceRollback&&await io.cleanup(g),await Un()}yield{type:"status",content:null}},gf=async(e,t,n=null,s=null,o=50,l=null,f=!1)=>{let a=await so(),m={...a,...t},g=process.env.SUBAGENT_MODEL?process.env.SUBAGENT_MODEL.trim():null,u=process.env.SUBAGENT_PROVIDER?process.env.SUBAGENT_PROVIDER.trim():null,h=new Date,x=`${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(":","-")}`,c=(b=>{if(!b)return null;let r=b.toLowerCase();return r==="google"?"Google":r==="deepseek"?"DeepSeek":r==="openrouter"?"OpenRouter":r==="nvidia"?"NVIDIA":r==="mistral"?"Mistral":r==="ollama"?"Ollama":r==="inferx"?"InferX":r==="sensenova"?"SenseNova":r==="poolside"?"Poolside":r==="9router"||r==="9Router"?"9router":r==="aihubmix"||r==="aihub"?"AIHubMix":r==="explabs"||r==="experientiallabs"||r==="experimentallabs"?"ExpLabs":r==="tokenharbor"||r==="token harbor"||r==="token_harbor"||r==="thk"?"TokenHarbor":r==="apinex"||r==="apx"?"APInex":null})(u),T=m?.systemSettings?.CustomSubAgent?m?.systemSettings?.SubAgentModel:null,E=m?.systemSettings?.CustomSubAgent?m?.systemSettings?.SubAgentProvider:null,k=null;if(T==="ENV"?(k=g,g&&c&&(m.aiProvider=c)):T&&T!=="Default"?(k=T,E&&(m.aiProvider=E)):g&&c&&(m.aiProvider=c),m.aiProvider){let b=await bs(m.aiProvider);b&&(m.apiKey=b)}let C=b=>{if(!b||typeof b!="string")return{allowed:!0};let r=[/rm\s+-[rf]{1,2}\s+[\/*.]/i,/rmdir\s+\/[sq]/i,/del\s+\/[fsq]/i,/\bformat\b\s+[a-z]:/i,/mkfs/i,/dd\s+if=/i,/\b(shutdown|reboot|poweroff|init\s+0|init\s+6)\b/i,/chmod\s+(-R\s+)?777\s+[\/*.]/i,/chown\s+(-R\s+)?root/i,/git\s+push\s+.*--force/i,/git\s+clean\s+-fdx/i,/\bsudo\s+su\b/i,/\bsu\s+-\b/i];for(let w of r)if(w.test(b))return{allowed:!1,reason:`Blocked potentially destructive or unsafe command pattern: "${w.source}"`};return{allowed:!0}},N=n||k||t?.modelName||t?.activeModel||a.activeModel,v=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",_=`-- TOOL DEFINITIONS (path = relative to CWD, path separator: '/') --
864
- You cant execute tools. Instead output in chat the exact string [tool:functions.ToolName(arg1="value1")] \u2190 mandatory, tool:functions must
864
+ You cant execute tools. Instead output in chat the exact string [tool:ToolName(arg1="value1")] \u2190 mandatory
865
865
  Tool Rules:
866
866
  - Mandatorily JSON escape literal sequences (backslash: \\\\, newLine: \\ n, quote: \\")
867
867
  - Same file, multiple edits? ONE PatchFile (\u226415 blocks)
@@ -902,7 +902,7 @@ ${_.trimEnd()}
902
902
  Current Time: ${x}
903
903
  === END SYSTEM PROMPT ===`,L=[{role:"user",text:`Complete this task: ${e}`}],y=0,d="";for(;y<o;){let b=await ks("subagent",m);if(!b.allowed)throw new Error(b.reason||`Budget Exhausted for Provider (${m?.aiProvider||"Subagent"})`);if(kt){if(t?.taskId&&typeof Kt<"u"){let D=Kt.find(F=>F.id===t.taskId);D&&(D.status="cancelled")}throw l&&l("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}if(t?.taskId&&typeof Kt<"u"){let D=Kt.find(F=>F.id===t.taskId);if(D&&D.status==="cancelled")throw l&&l("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}let r=L.map(D=>({role:D.role==="user"?"user":"model",parts:[{text:D.text}]}));l&&l(`[Subagent Turn ${y+1}]...`);let w=["Fast","Low","Medium","High"],A=process.env.SUBAGENT_THINKING,O=w.includes(A)?A:"Low",P=(await ss(m,N,r,R,O)).text||"",M=Vr(qt(P).trim());d=M,l&&l(`[Subagent Response]
904
904
  ${M}
905
- `),L.push({role:"agent",text:M});let te=xo(M);if(te.length===0)break;let le=te.filter(D=>D.toolName.toLowerCase()==="askmain"||D.toolName.toLowerCase()==="ask_main"),J=!1,re="";for(let D of te){if(kt){if(t?.taskId&&typeof Kt<"u"){let B=Kt.find(Y=>Y.id===t.taskId);B&&(B.status="cancelled")}throw new Error("Subagent task was cancelled.")}if(t?.taskId&&typeof Kt<"u"){let B=Kt.find(Y=>Y.id===t.taskId);if(B&&B.status==="cancelled")throw new Error("Subagent task was cancelled.")}let F=D.toolName.toLowerCase();if(F==="askuser"&&(F="ask"),F==="askmain"||F==="ask_main"){if(J)continue;J=!0;let B="";if(le.length===1?B=oe(le[0].args).question||le[0].args:B=le.map((Y,de)=>{let Ee=oe(Y.args);return`Q${de+1}: ${Ee.question||Y.args}`}).join(`
905
+ `),L.push({role:"agent",text:M});let te=xo(M);if(te.length===0)break;let le=te.filter(D=>D.toolName.toLowerCase()==="askmain"||D.toolName.toLowerCase()==="ask_main"),J=!1,re="";for(let D of te){if(kt){if(t?.taskId&&typeof Kt<"u"){let B=Kt.find(Y=>Y.id===t.taskId);B&&(B.status="cancelled")}throw new Error("Subagent task was cancelled.")}if(t?.taskId&&typeof Kt<"u"){let B=Kt.find(Y=>Y.id===t.taskId);if(B&&B.status==="cancelled")throw new Error("Subagent task was cancelled.")}let F=D.toolName.toLowerCase();if(F==="askuser"&&(F="ask"),F==="askmain"||F==="ask_main"){if(J)continue;J=!0;let B="";if(le.length===1?B=oe(le[0].args).question||le[0].args:B=le.map((Y,de)=>{let Ce=oe(Y.args);return`Q${de+1}: ${Ce.question||Y.args}`}).join(`
906
906
  `),t.onAskMain){l&&l(`[Executing Tool] AskMain("${B}")...`);let Y=await t.onAskMain(B);l&&l(`[Tool Result]
907
907
  Answer from Main Agent: ${Y}
908
908
  `),re+=`[TOOL RESULT for AskMain]: Answer from Main Agent: ${Y}
@@ -915,15 +915,15 @@ Answer from Main Agent: ${Y}
915
915
  `;continue}if(F==="exec_command"||F==="execcommand"||F==="run"){let B=oe(D.args).command||"",Y=C(B);if(!Y.allowed){let de=`ERROR: [SECURITY RESTRICTION] Subagent execution blocked command: ${Y.reason}`;l&&l(`[Blocked Command] ${B} - ${Y.reason}
916
916
  `),re+=`${de}
917
917
 
918
- `;continue}}let z="";if(F==="web_search"||F==="websearch")z=`\u2714 \x1B[95mSearched\x1B[0m: ${oe(D.args).query||""}`;else if(F==="web_scrape"||F==="webscrape")z=`\u2714 \x1B[95mScraped\x1B[0m: ${oe(D.args).url||""}`;else if(F==="search_keyword"||F==="searchkeyword"||F==="codesearch"||F==="code_search"){let B=oe(D.args),Y=B.keyword||"",de=B.path||"";z=`${Y?"\u2714":"\u2718"} \x1B[95mSearched\x1B[0m: ${Y||"No Query"}${de?` \u2192 ${de.replaceAll("\\","/")}`:""}`}else if(F==="view_file"||F==="viewfile"||F==="readfile")z=`\u2714 \x1B[95mRead\x1B[0m: ${(oe(D.args).path||"").replaceAll("\\","/")}`;else if(F==="list_files"||F==="read_folder"||F==="readfolder"){let B=oe(D.args).path||null,Y=oe(D.args).recurse||0;z=`${B?"\u2714":"\u2718"} \x1B[95mBrowsed\x1B[0m: ${B?`${B.replaceAll("\\","/")}${Y>0?`${B.endsWith("/")?`*${Y}`:`/*${Y}`}`:`${B.endsWith("/")?"":"/"}`}`:""}`}else if(F==="write_file"||F==="writefile"){let B=oe(D.args).path||null;z=`${B?"\u2714":"\u2718"} \x1B[95mCreated\x1B[0m: ${B?`${B.replaceAll("\\","/")}`:"No File Changes"}`}else if(F==="update_file"||F==="updatefile"||F==="patchfile"||F==="patch_file"){let B=oe(D.args),Y=B.path||null,Ee=Object.entries(B).some(([Ce,Ne])=>Ce.startsWith("searchContent")&&typeof Ne=="string"&&Ne.startsWith("^LINE:"))?"\u1361":":";z=`${Y?"\u2714":"\u2718"} \x1B[95mEdited\x1B[0m${Ee} ${Y?`${Y.replaceAll("\\","/")}`:"No File Changes"}`}else if(F==="exec_command"||F==="execcommand"||F==="run"){let B=oe(D.args).command||null;z=`${B?"\u2714":"\u2718"} \x1B[95mExecuted\x1B[0m: ${B?B.slice(0,100)+(B.length>100?"...":""):"No Command"}`}else if(F==="file_map"||F==="filemap"){let B=oe(D.args).path||"";z=`${B?"\u2714":"\u2718"} \x1B[95mIndexed\x1B[0m: ${B?`${B.replaceAll("\\","/")}`:"File Not Found"}`}else if(F==="await"){let{time:B}=oe(D.args),Y=parseFloat(B)||0;Y<10&&(Y=10),Y>180&&(Y=180),z=`\u2714 \x1B[95mAwaiting\x1B[0m \u2192 ${(Ee=>{if(Ee>=60){let Ce=Math.floor(Ee/60),Ne=Ee%60;return`${Ce}m${Ne>0?` ${Ne}s`:""}`}return`${Ee}s`})(Y)}`}else{let B=Zs[F]||D.toolName,Y=Gn(F,D.args);z=`\u2714 \x1B[95m${B}\x1B[0m${Y?`: ${Y}`:""}`}t.onVisualFeedback&&z&&t.onVisualFeedback(z),l&&l(`[Executing Tool] ${D.toolName}(${D.args})...`);try{let B=await ho(D.toolName,D.args,{...t,mode:"Flux"});if(l&&l(`[Tool Result]
918
+ `;continue}}let z="";if(F==="web_search"||F==="websearch")z=`\u2714 \x1B[95mSearched\x1B[0m: ${oe(D.args).query||""}`;else if(F==="web_scrape"||F==="webscrape")z=`\u2714 \x1B[95mScraped\x1B[0m: ${oe(D.args).url||""}`;else if(F==="search_keyword"||F==="searchkeyword"||F==="codesearch"||F==="code_search"){let B=oe(D.args),Y=B.keyword||"",de=B.path||"";z=`${Y?"\u2714":"\u2718"} \x1B[95mSearched\x1B[0m: ${Y||"No Query"}${de?` \u2192 ${de.replaceAll("\\","/")}`:""}`}else if(F==="view_file"||F==="viewfile"||F==="readfile")z=`\u2714 \x1B[95mRead\x1B[0m: ${(oe(D.args).path||"").replaceAll("\\","/")}`;else if(F==="list_files"||F==="read_folder"||F==="readfolder"){let B=oe(D.args).path||null,Y=oe(D.args).recurse||0;z=`${B?"\u2714":"\u2718"} \x1B[95mBrowsed\x1B[0m: ${B?`${B.replaceAll("\\","/")}${Y>0?`${B.endsWith("/")?`*${Y}`:`/*${Y}`}`:`${B.endsWith("/")?"":"/"}`}`:""}`}else if(F==="write_file"||F==="writefile"){let B=oe(D.args).path||null;z=`${B?"\u2714":"\u2718"} \x1B[95mCreated\x1B[0m: ${B?`${B.replaceAll("\\","/")}`:"No File Changes"}`}else if(F==="update_file"||F==="updatefile"||F==="patchfile"||F==="patch_file"){let B=oe(D.args),Y=B.path||null,Ce=Object.entries(B).some(([ve,Ne])=>ve.startsWith("searchContent")&&typeof Ne=="string"&&Ne.startsWith("^LINE:"))?"\u1361":":";z=`${Y?"\u2714":"\u2718"} \x1B[95mEdited\x1B[0m${Ce} ${Y?`${Y.replaceAll("\\","/")}`:"No File Changes"}`}else if(F==="exec_command"||F==="execcommand"||F==="run"){let B=oe(D.args).command||null;z=`${B?"\u2714":"\u2718"} \x1B[95mExecuted\x1B[0m: ${B?B.slice(0,100)+(B.length>100?"...":""):"No Command"}`}else if(F==="file_map"||F==="filemap"){let B=oe(D.args).path||"";z=`${B?"\u2714":"\u2718"} \x1B[95mIndexed\x1B[0m: ${B?`${B.replaceAll("\\","/")}`:"File Not Found"}`}else if(F==="await"){let{time:B}=oe(D.args),Y=parseFloat(B)||0;Y<10&&(Y=10),Y>180&&(Y=180),z=`\u2714 \x1B[95mAwaiting\x1B[0m \u2192 ${(Ce=>{if(Ce>=60){let ve=Math.floor(Ce/60),Ne=Ce%60;return`${ve}m${Ne>0?` ${Ne}s`:""}`}return`${Ce}s`})(Y)}`}else{let B=Zs[F]||D.toolName,Y=Gn(F,D.args);z=`\u2714 \x1B[95m${B}\x1B[0m${Y?`: ${Y}`:""}`}t.onVisualFeedback&&z&&t.onVisualFeedback(z),l&&l(`[Executing Tool] ${D.toolName}(${D.args})...`);try{let B=await ho(D.toolName,D.args,{...t,mode:"Flux"});if(l&&l(`[Tool Result]
919
919
  ${B}
920
920
  `),re+=`[TOOL RESULT for ${D.toolName}]: ${B}
921
921
 
922
922
  `,await Ct("toolSuccess"),F==="patchfile"||F==="update_file"||F==="updatefile"||F==="patch_file"){if(B){let Y=B.split(`
923
- `),de=0,Ee=0,Ce=!1;for(let Ne of Y){if(Ne.includes("[DIFF_START]")){Ce=!0;continue}if(Ne.includes("[DIFF_END]")){Ce=!1;continue}Ce&&(/^\+\d+/.test(Ne)?de++:/^\-\d+/.test(Ne)&&Ee++)}(de>0||Ee>0)&&(await Bt("linesAdded",de),await Bt("linesRemoved",Ee))}}else if((F==="writefile"||F==="write_file")&&B){let Y=B.match(/- Stats: \[(\d+) lines/),de=Y?parseInt(Y[1]):0,Ee=0;if(B.includes("Old File contents:")){let Ce=!1;for(let Ne of B.split(`
924
- `)){if(Ne.includes("Old File contents:")){Ce=!0;continue}Ce&&(Ne.trim()===""?Ce=!1:/^\d+ \|/.test(Ne)&&Ee++)}}(de>0||Ee>0)&&(await Bt("linesAdded",de),await Bt("linesRemoved",Ee))}}catch(B){let Y=`ERROR: Execution failed for [${D.toolName}]: ${B.message}`;l&&l(`[Tool Error] ${Y}
923
+ `),de=0,Ce=0,ve=!1;for(let Ne of Y){if(Ne.includes("[DIFF_START]")){ve=!0;continue}if(Ne.includes("[DIFF_END]")){ve=!1;continue}ve&&(/^\+\d+/.test(Ne)?de++:/^\-\d+/.test(Ne)&&Ce++)}(de>0||Ce>0)&&(await Bt("linesAdded",de),await Bt("linesRemoved",Ce))}}else if((F==="writefile"||F==="write_file")&&B){let Y=B.match(/- Stats: \[(\d+) lines/),de=Y?parseInt(Y[1]):0,Ce=0;if(B.includes("Old File contents:")){let ve=!1;for(let Ne of B.split(`
924
+ `)){if(Ne.includes("Old File contents:")){ve=!0;continue}ve&&(Ne.trim()===""?ve=!1:/^\d+ \|/.test(Ne)&&Ce++)}}(de>0||Ce>0)&&(await Bt("linesAdded",de),await Bt("linesRemoved",Ce))}}catch(B){let Y=`ERROR: Execution failed for [${D.toolName}]: ${B.message}`;l&&l(`[Tool Error] ${Y}
925
925
  `),re+=`${Y}
926
926
 
927
- `,await Ct("toolFailure")}}let De="";if(t?.taskId&&typeof Kt<"u"){let D=Kt.find(F=>F.id===t.taskId);if(D&&D.pendingSteerMessages&&D.pendingSteerMessages.length>0){let F=[...D.pendingSteerMessages];D.pendingSteerMessages=[];for(let Ae of F)De+=`
927
+ `,await Ct("toolFailure")}}let De="";if(t?.taskId&&typeof Kt<"u"){let D=Kt.find(F=>F.id===t.taskId);if(D&&D.pendingSteerMessages&&D.pendingSteerMessages.length>0){let F=[...D.pendingSteerMessages];D.pendingSteerMessages=[];for(let Ee of F)De+=`
928
928
 
929
- [STEERING INSTRUCTION FROM MAIN AGENT]: ${Ae}`,l&&l(`[Subagent Steered] ${Ae}`)}}let We=(re.trim()+De).trim();L.push({role:"user",text:We}),y++}return d};export{po as a,Rr as b,gc as c,mc as d,Ke as e,ll as f,cl as g,oc as h,sc as i,yc as j,Vo as k,xc as l,Ua as m,sf as n,Wa as o,Ha as p,Qs as q,qt as r,Ur as s,Vr as t,Ka as u,rf as v,af as w,ti as x,lf as y,cf as z,df as A,ff as B,uf as C,gf as D};
929
+ [STEERING INSTRUCTION FROM MAIN AGENT]: ${Ee}`,l&&l(`[Subagent Steered] ${Ee}`)}}let We=(re.trim()+De).trim();L.push({role:"user",text:We}),y++}return d};export{po as a,Rr as b,gc as c,mc as d,Ke as e,ll as f,cl as g,oc as h,sc as i,yc as j,Vo as k,xc as l,Ua as m,sf as n,Wa as o,Ha as p,Qs as q,qt as r,Ur as s,Vr as t,Ka as u,rf as v,af as w,ti as x,lf as y,cf as z,df as A,ff as B,uf as C,gf as D};