fluxflow-cli 4.16.12 → 4.16.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunks/{ai-E5DX6RYW.js → ai-CNNQXF3I.js} +1 -1
- package/dist/chunks/{app-23MVM26R.js → app-SZFXXQWI.js} +1 -1
- package/dist/chunks/chunk-UYHPCXNG.js +15 -0
- package/dist/chunks/{chunk-LU3WAJDV.js → chunk-ZGDWX7E2.js} +56 -56
- package/dist/chunks/{invoke-CBU46XRQ.js → invoke-CDCGPCCW.js} +2 -2
- package/dist/chunks/{invokeSync-OU7OOFSL.js → invokeSync-A2X2JQLH.js} +2 -2
- package/dist/chunks/view_file-VTMBROFS.js +1 -0
- package/dist/cli.js +1 -1
- package/dist/package.json +2 -2
- package/package.json +2 -2
- package/dist/chunks/ai-VQ4G26RS.js +0 -1
- package/dist/chunks/app-5KTVZSIU.js +0 -285
- package/dist/chunks/chunk-2N256NLX.js +0 -15
- package/dist/chunks/chunk-7MMKXDFE.js +0 -922
- package/dist/chunks/invoke-LGXSQLCY.js +0 -6
- package/dist/chunks/invokeSync-XD7SQTAL.js +0 -3
- package/dist/chunks/view_file-LVF5A3EI.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as so}from"./chunk-VCF6JVQV.js";import{a as Kt}from"./chunk-56EJGQU3.js";import{a as xs,h as pi}from"./chunk-KRRJNFBF.js";import{a as yi}from"./chunk-
|
|
1
|
+
import{a as so}from"./chunk-VCF6JVQV.js";import{a as Kt}from"./chunk-56EJGQU3.js";import{a as xs,h as pi}from"./chunk-KRRJNFBF.js";import{a as yi}from"./chunk-UYHPCXNG.js";import{c as ps,g as fi,h as ui,i as gi,m as ys}from"./chunk-HNUV7OHA.js";import{a as vo}from"./chunk-KFM2OZWJ.js";import{b as ms}from"./chunk-72RYQ5W7.js";import{e as vt,g as Ut,i as hs,j as di}from"./chunk-WKHYRBBK.js";import{g as ut,h as Co,k as fe,l as oo}from"./chunk-AAPXJU65.js";import{c as Ct,d as zn}from"./chunk-SIINYZWE.js";import{a as mi,c as hi}from"./chunk-SHTF7RHG.js";import{a as en,d as Cn,e as _o,j as Nn,k as Eo,l as us,q as gs,u as Ao}from"./chunk-FDNLMLIM.js";import{a as ee}from"./chunk-Y5JU726N.js";import{GoogleGenAI as $r,ThinkingLevel as Ze,HarmBlockThreshold as Mn,HarmCategory as In}from"@google/genai";var xi=(e=!0,t=!0)=>`
|
|
2
2
|
To use tools, must output exactly '[tool:functions.ToolName(arg1="value1")]' structured string in chat response \u2190 no exception
|
|
3
3
|
|
|
4
4
|
-- Chat Management Tools --
|
|
@@ -488,7 +488,7 @@ ${$i(o,2)}`)}}catch{}return n.join(`
|
|
|
488
488
|
-------------------------------------------------
|
|
489
489
|
|
|
490
490
|
`)}}return ro},er=(e="",t="",n=!0,s=!1)=>{if(typeof t=="boolean"&&(s=n,n=t,t=""),!n)return"";let o=e?.length>0&&!s?`-- Recent context from other chats (Priority: Low, Focus: Chat Context > Recent) --
|
|
491
|
-
${e}`:"";return o?`${o}`:""},tr=(e,t,n,s,o=!0,l=!1,f="Google",a=!1,m,g,u=!1,h="")=>{let x=!1;process.env.forcedReasoning&&(x=!0);let i="";if(!m&&f==="Google"){let
|
|
491
|
+
${e}`:"";return o?`${o}`:""},tr=(e,t,n,s,o=!0,l=!1,f="Google",a=!1,m,g,u=!1,h="")=>{let x=!1;process.env.forcedReasoning&&(x=!0);let i="";if(!m&&f==="Google"){let z=t;t==="Fast"&&(z="Off"),t==="Low"&&(z="Minimal"),t==="Standard"&&(z="Medium"),(t==="xHigh"||t==="Max")&&(z="xHigh"),i=Ro[z]||Ro.Medium}if(m||f!=="Google"){let z={Fast:"Lowest",Low:"Low",Medium:"Medium",Standard:"Medium",High:"High",xHigh:"High",Max:"High"};i=Ro.xHigh,i=i.replace("Effort: High",`Effort: ${z[t]}`),t==="Fast"?i=`Effort: Lowest
|
|
492
492
|
No thinking. Immediate response
|
|
493
493
|
Verify imports, tool results & system stability; avoid syntax errors`:t==="Low"&&(i=`Effort: Low
|
|
494
494
|
Quick, focused thinking, intent & complexity, required tools/files/actions, before acting
|
|
@@ -502,9 +502,9 @@ ${w.length||c.length?"":`
|
|
|
502
502
|
`}`:"",b=process.cwd(),C=ua(g,o),N=C?.length>0?`--- Saved Memories ---
|
|
503
503
|
${C}
|
|
504
504
|
|
|
505
|
-
`:"";ca(f,h);let v=Fi(ao,h,f).trim(),R=[Is,v].filter(
|
|
505
|
+
`:"";ca(f,h);let v=Fi(ao,h,f).trim(),R=[Is,v].filter(z=>z&&z.length>0).join(`
|
|
506
506
|
|
|
507
|
-
`).trim(),L=Fi(lo,h,f).trim(),d=[Lo,L].filter(
|
|
507
|
+
`).trim(),L=Fi(lo,h,f).trim(),d=[Lo,L].filter(z=>z&&z.length>0).join(`
|
|
508
508
|
|
|
509
509
|
`).trim(),T=R.length>0||d.length>0?`--- Additional Instructions ---
|
|
510
510
|
${R.length>0?`-- Global --
|
|
@@ -513,17 +513,17 @@ ${R}`:""}${d.length>0?`${R.length>0?`
|
|
|
513
513
|
`:""}-- Project --
|
|
514
514
|
${d}`:""}
|
|
515
515
|
|
|
516
|
-
`:"",r=(()=>{let
|
|
516
|
+
`:"",r=(()=>{let z=process.cwd().toLowerCase();if(process.platform==="win32"){let ie=process.env.SystemRoot?.toLowerCase()||"c:\\windows",ve=process.env.ProgramFiles?.toLowerCase()||"c:\\program files",Ne=process.env["ProgramFiles(x86)"]?.toLowerCase()||"c:\\program files (x86)";return z.startsWith(ie)||z.startsWith(ve)||z.startsWith(Ne)}else return z==="/"||["/bin","/sbin","/etc","/usr","/var","/root"].some(ve=>z.startsWith(ve))})(),k=new Date,E=k.getFullYear(),I=k.toLocaleString("en-US",{month:"short"}).toUpperCase(),H=String(k.getDate()).padStart(2,"0"),P=`${E}-${I}-${H}`,M=!!s?.autoExcludeMetadata,Z=process.env.I_HAVE_TOO_MUCH_MONEY==="true"||process.env.I_HAVE_TOO_MUCH_MONEY===!0||!1,le=process.env.NO_DEV==="true"||process.env.NO_DEV==="1"||process.env.NO_DEV===!0||!1;return`${Z?`${" ".repeat(Math.floor(Math.random()*4)+1)}`:""}=== SYSTEM PROMPT ===
|
|
517
517
|
Identity: ${As.length>1?As:"Flux Flow. Sassy, Friendly, CLI Assistant"}
|
|
518
518
|
${Vi?"":`${n==="Flux"?"Stepwise Execution, Run Automated Tests. Task Completion":n==="Flow"?"Concise, Humorous, Sarcastic":n==="ICU"?"Computer Use Capabilities. Screenshot as ground truth, analyze grid ids overlapping/close to target, keyboard shortcuts > mouse clicks":"Computer Use & Workspace Capabilities. Screenshot as ground truth, analyze grid ids overlapping/close to target, keyboard shortcuts > mouse clicks. Workspace Tools if faster. Focus on Productivity"}`}${Zi&&n.toLowerCase().includes("cu")?`
|
|
519
519
|
- Running on secondary screen. Opened app not visible in screenshot? Might be opened on primary. Use 'AskUser' with NO options and tell user to move app window to secondary`:""}
|
|
520
520
|
|
|
521
521
|
- OS: ${Ui}${!le&&h.length>1?`
|
|
522
|
-
- Model: ${fn.basename(h.trim())}`.trimEnd():""}${M?`
|
|
522
|
+
- Model: ${fn.basename(h.trim()).replaceAll("-"," ").replace(/\b\w/g,z=>z.toUpperCase())}`.trimEnd():""}${M?`
|
|
523
523
|
- Date: ${P}`:""}${o?`
|
|
524
524
|
- Use relative time reference eg. few mins ago
|
|
525
525
|
-- Chat Context > Metadata`:""}${(Ts.length>0||Ss.length>0)&&n.toLowerCase().includes("flux")?`
|
|
526
|
-
- Read
|
|
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"`:""}
|
|
527
527
|
|
|
528
528
|
-- THINKING GUIDANCE --
|
|
529
529
|
${f==="Mistral"||f==="Google"&&!m?`${i}
|
|
@@ -574,7 +574,7 @@ ${xi(t,n)}
|
|
|
574
574
|
=== END SYSTEM PROMPT ===${e?`
|
|
575
575
|
|
|
576
576
|
-- current saved user memories --
|
|
577
|
-
${e}`:""}`.trim();var or=()=>import("./web_search-HDZ2VDTY.js").then(e=>e.web_search),sr=()=>import("./web_scrape-IKJE45Z6.js").then(e=>e.web_scrape),ir=()=>import("./memory-OYIUYX3A.js").then(e=>e.memory),rr=()=>import("./chat-HZ7UVZE2.js").then(e=>e.chat),ar=()=>import("./view_file-LVF5A3EI.js").then(e=>e.view_file),lr=()=>import("./write_file-LOYRYIK6.js").then(e=>e.write_file),cr=()=>import("./update_file-U2ZALD44.js").then(e=>e.update_file),dr=()=>import("./exec_command-ERULJCYR.js").then(e=>e.exec_command),fr=()=>import("./read_folder-OOKZITME.js").then(e=>e.read_folder),Ds=()=>import("./ask_user-K2DLZF6H.js").then(e=>e.ask_user),ur=()=>import("./write_pdf-VB4IFPWX.js").then(e=>e.write_pdf),gr=()=>import("./write_docx-EKUIZ7GV.js").then(e=>e.write_docx),Po=()=>import("./search_keyword-W5YEUUPO.js").then(e=>e.search_keyword),mr=()=>import("./generate_image-XYDE47LK.js").then(e=>e.generate_image),$o=()=>import("./saveSummary-ATBIFYDP.js").then(e=>e.saveSummary),fo=()=>import("./addMemScore-W4I665ZR.js").then(e=>e.addMemScore),hr=()=>import("./file_map-5KY2ADZW.js").then(e=>e.file_map),No=()=>import("./todo-SJLJJLVZ.js").then(e=>e.todo),pr=()=>import("./invokeSync-XD7SQTAL.js").then(e=>e.invokeSync),ga=()=>import("./invoke-LGXSQLCY.js").then(e=>e.invoke),yr=()=>import("./getProgress-LI4U6UJU.js").then(e=>e.getProgress),ma=()=>import("./cancel-7IMADALP.js").then(e=>e.cancel),xr=()=>import("./emergency_rollback-EPJPKANN.js").then(e=>e.emergency_rollback),uo=()=>import("./awaitSubagent-JTUSJDKD.js").then(e=>e.awaitSubagent),go=()=>import("./answerSubagent-JUVFNLE5.js").then(e=>e.answerSubagent),Fo=()=>import("./steerSubagent-L2JVT4QN.js").then(e=>e.steerSubagent),Bo=()=>import("./computer_action-WTHH7RBB.js").then(e=>e.computer_action),br=()=>import("./click-G6RRSFVC.js").then(e=>e.click),kr=()=>import("./drag-ZGH2MMP7.js").then(e=>e.drag),wr=()=>import("./scroll-GHXES2II.js").then(e=>e.scroll),Os=()=>import("./keyboard_typing-CK3KVAWM.js").then(e=>e.keyboard_typing),Ls=()=>import("./key_press-M5QNCIPH.js").then(e=>e.key_press),Ps=()=>import("./recapture_screen-5FKLOHJL.js").then(e=>e.recapture_screen),ha={web_search:or,web_scrape:sr,memory:ir,chat:rr,view_file:ar,write_file:lr,update_file:cr,exec_command:dr,read_folder:fr,write_pdf:ur,write_docx:gr,search_keyword:Po,generate_image:mr,saveSummary:$o,addMemScore:fo,file_map:hr,todo:No,Todo:No,goal:No,Goal:No,invokeSync:pr,invoke:ga,getProgress:yr,cancel:ma,awaitSubagent:uo,answerSubagent:go,steerSubagent:Fo,computer_action:Bo,computer_use:Bo,ComputerAction:Bo,ComputerUse:Bo,click:br,Click:br,drag:kr,Drag:kr,scroll:wr,Scroll:wr,keyboard_typing:Os,KeyboardTyping:Os,keyboardtyping:Os,key_press:Ls,KeyPress:Ls,keypress:Ls,recapture_screen:Ps,RecaptureScreen:Ps,recapturescreen:Ps,invoke_sync:pr,get_progress:yr,await_subagent:uo,answer_subagent:go,steer_subagent:Fo,steer:Fo,Steer:Fo,ask:Ds,Ask:Ds,AskUser:Ds,WebSearch:or,WebScrape:sr,ReadFile:ar,ReadFolder:fr,WriteFile:lr,PatchFile:cr,WritePDF:ur,WriteDoc:gr,Run:dr,SearchKeyword:Po,CodeSearch:Po,code_search:Po,Memory:ir,Chat:rr,GenerateImage:mr,saveSumary:$o,SaveSummary:$o,SaveSumary:$o,add_mem_score:fo,AddMemScore:fo,addMemoryScore:fo,AddMemoryScore:fo,FileMap:hr,answer:go,Answer:go,AnswerSubagent:go,await:uo,Await:uo,AwaitSubagent:uo,EmergencyRollback:xr,emergency_rollback:xr},mo=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=ha[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 X from"path";import Ue from"fs";import pa from"gradient-string";var $s=["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 Tr=[{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"]}],ho={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 Uo=null;var Sr=(e="Dark")=>{let t;e==="Mystery"||e==="Chaos"?(Uo||(Uo=Tr[Math.floor(Math.random()*Tr.length)]),t={...Uo,id:"Mystery"}):(Uo=null,ho[e]?t=ho[e]:e==="GitHub"?t=ho["GitHub Dark"]:e==="Transparent"?t=ho["Transparent Dark"]:t=ho.Dark);let n=t.codeText||t.secondary||t.info||t.logoGradient&&t.logoGradient[0]||"cyan";return{...t,codeText:n}};var ya=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",ac=(e=2)=>{let t=ya();return t==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)},lc=(e="...",t="Loading...",n="Dark")=>{let s=$s[Math.floor(Math.random()*$s.length)],o=Sr(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=pa(u).multiline(g.join(`
|
|
577
|
+
${e}`:""}`.trim();var or=()=>import("./web_search-HDZ2VDTY.js").then(e=>e.web_search),sr=()=>import("./web_scrape-IKJE45Z6.js").then(e=>e.web_scrape),ir=()=>import("./memory-OYIUYX3A.js").then(e=>e.memory),rr=()=>import("./chat-HZ7UVZE2.js").then(e=>e.chat),ar=()=>import("./view_file-VTMBROFS.js").then(e=>e.view_file),lr=()=>import("./write_file-LOYRYIK6.js").then(e=>e.write_file),cr=()=>import("./update_file-U2ZALD44.js").then(e=>e.update_file),dr=()=>import("./exec_command-ERULJCYR.js").then(e=>e.exec_command),fr=()=>import("./read_folder-OOKZITME.js").then(e=>e.read_folder),Ds=()=>import("./ask_user-K2DLZF6H.js").then(e=>e.ask_user),ur=()=>import("./write_pdf-VB4IFPWX.js").then(e=>e.write_pdf),gr=()=>import("./write_docx-EKUIZ7GV.js").then(e=>e.write_docx),Po=()=>import("./search_keyword-W5YEUUPO.js").then(e=>e.search_keyword),mr=()=>import("./generate_image-XYDE47LK.js").then(e=>e.generate_image),$o=()=>import("./saveSummary-ATBIFYDP.js").then(e=>e.saveSummary),fo=()=>import("./addMemScore-W4I665ZR.js").then(e=>e.addMemScore),hr=()=>import("./file_map-5KY2ADZW.js").then(e=>e.file_map),No=()=>import("./todo-SJLJJLVZ.js").then(e=>e.todo),pr=()=>import("./invokeSync-A2X2JQLH.js").then(e=>e.invokeSync),ga=()=>import("./invoke-CDCGPCCW.js").then(e=>e.invoke),yr=()=>import("./getProgress-LI4U6UJU.js").then(e=>e.getProgress),ma=()=>import("./cancel-7IMADALP.js").then(e=>e.cancel),xr=()=>import("./emergency_rollback-EPJPKANN.js").then(e=>e.emergency_rollback),uo=()=>import("./awaitSubagent-JTUSJDKD.js").then(e=>e.awaitSubagent),go=()=>import("./answerSubagent-JUVFNLE5.js").then(e=>e.answerSubagent),Fo=()=>import("./steerSubagent-L2JVT4QN.js").then(e=>e.steerSubagent),Bo=()=>import("./computer_action-WTHH7RBB.js").then(e=>e.computer_action),br=()=>import("./click-G6RRSFVC.js").then(e=>e.click),kr=()=>import("./drag-ZGH2MMP7.js").then(e=>e.drag),wr=()=>import("./scroll-GHXES2II.js").then(e=>e.scroll),Os=()=>import("./keyboard_typing-CK3KVAWM.js").then(e=>e.keyboard_typing),Ls=()=>import("./key_press-M5QNCIPH.js").then(e=>e.key_press),Ps=()=>import("./recapture_screen-5FKLOHJL.js").then(e=>e.recapture_screen),ha={web_search:or,web_scrape:sr,memory:ir,chat:rr,view_file:ar,write_file:lr,update_file:cr,exec_command:dr,read_folder:fr,write_pdf:ur,write_docx:gr,search_keyword:Po,generate_image:mr,saveSummary:$o,addMemScore:fo,file_map:hr,todo:No,Todo:No,goal:No,Goal:No,invokeSync:pr,invoke:ga,getProgress:yr,cancel:ma,awaitSubagent:uo,answerSubagent:go,steerSubagent:Fo,computer_action:Bo,computer_use:Bo,ComputerAction:Bo,ComputerUse:Bo,click:br,Click:br,drag:kr,Drag:kr,scroll:wr,Scroll:wr,keyboard_typing:Os,KeyboardTyping:Os,keyboardtyping:Os,key_press:Ls,KeyPress:Ls,keypress:Ls,recapture_screen:Ps,RecaptureScreen:Ps,recapturescreen:Ps,invoke_sync:pr,get_progress:yr,await_subagent:uo,answer_subagent:go,steer_subagent:Fo,steer:Fo,Steer:Fo,ask:Ds,Ask:Ds,AskUser:Ds,WebSearch:or,WebScrape:sr,ReadFile:ar,ReadFolder:fr,WriteFile:lr,PatchFile:cr,WritePDF:ur,WriteDoc:gr,Run:dr,SearchKeyword:Po,CodeSearch:Po,code_search:Po,Memory:ir,Chat:rr,GenerateImage:mr,saveSumary:$o,SaveSummary:$o,SaveSumary:$o,add_mem_score:fo,AddMemScore:fo,addMemoryScore:fo,AddMemoryScore:fo,FileMap:hr,answer:go,Answer:go,AnswerSubagent:go,await:uo,Await:uo,AwaitSubagent:uo,EmergencyRollback:xr,emergency_rollback:xr},mo=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=ha[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 Q from"path";import Ue from"fs";import pa from"gradient-string";var $s=["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 Tr=[{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"]}],ho={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 Uo=null;var Sr=(e="Dark")=>{let t;e==="Mystery"||e==="Chaos"?(Uo||(Uo=Tr[Math.floor(Math.random()*Tr.length)]),t={...Uo,id:"Mystery"}):(Uo=null,ho[e]?t=ho[e]:e==="GitHub"?t=ho["GitHub Dark"]:e==="Transparent"?t=ho["Transparent Dark"]:t=ho.Dark);let n=t.codeText||t.secondary||t.info||t.logoGradient&&t.logoGradient[0]||"cyan";return{...t,codeText:n}};var ya=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",ac=(e=2)=>{let t=ya();return t==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)},lc=(e="...",t="Loading...",n="Dark")=>{let s=$s[Math.floor(Math.random()*$s.length)],o=Sr(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=pa(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,20 +598,20 @@ ${h[7]}
|
|
|
598
598
|
`,m+=Gs(A,t,C,s+1,o,l)):m+=`${n}${b}${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 jo(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 Vo=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",p=[];if(Array.isArray(R.parts)){for(let d of R.parts)if(d.text)p.push({type:"text",text:d.text});else if((d.inlineData||d.inline_data)&&f){let T=d.inlineData||d.inline_data,r=T.mimeType||T.mime_type||"image/jpeg",k=T.data;r.startsWith("image/")&&p.push({type:"image_url",image_url:{url:`data:${r};base64,${k}`}})}}else{let d=R.text||"";d&&p.push({type:"text",text:d})}g.push({role:L,content:p.length===1&&p[0].type==="text"?p[0].text:p})}let u={model:t,messages:g,stream:!0,stream_options:{include_usage:!0},temperature:m},h=Ge("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 w=c.body.getReader(),A=new TextDecoder,b="",C=[],N=null,v=Date.now(),_=!1;for(;;){let{done:R,value:L}=await w.read();if(R){_&&(C.length>0||N)&&(yield{candidates:C.length>0?[{content:{parts:C}}]:[],usageMetadata:N});break}b+=A.decode(L,{stream:!0});let p=b.split(`
|
|
600
600
|
`);b=p.pop();for(let d of p){let T=d.trim();if(!T||!T.startsWith("data: "))continue;let r=!1;if(T==="data: [DONE]")r=!0;else try{let k=JSON.parse(T.substring(6)),E=k.choices?.[0]?.delta,I=k.usage;if(k.choices?.[0]?.finish_reason&&(r=!0),I&&(N={totalTokenCount:I.total_tokens||I.prompt_tokens+I.completion_tokens,promptTokenCount:I.prompt_tokens||0,candidatesTokenCount:I.completion_tokens||0,cachedContentTokenCount:I.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:I.completion_tokens_details?.reasoning_tokens||0},_=!0),E){let H=E.reasoning_content||null;H&&(C.push({text:H,thought:!0}),_=!0),E.content&&(C.push({text:E.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 Ko=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 T=d.role==="user"?"user":"assistant",r=[];if(Array.isArray(d.parts)){for(let k of d.parts)if(k.text)r.push({type:"text",text:k.text});else if(k.inlineData&&f){let E=k.inlineData.mimeType,I=k.inlineData.data;E.startsWith("image/")&&r.push({type:"image_url",image_url:`data:${E};base64,${I}`})}}else{let k=d.text||"";k&&r.push({type:"text",text:k})}r.length>0&&u.push({role:T,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 jo(x),c={model:t,messages:u,stream:!0,temperature:m,prompt_cache_key:i},w=Ge("Mistral",t,o);w!==null&&w!=="none"?w&&w!=="none"&&w!=="disabled"&&w!==!1&&(c.reasoning_effort=w):o&&h[o]!=="none"&&(c.reasoning_effort=h[o]||"high");let A=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(!A.ok){let d=await A.text().catch(()=>""),T=A.statusText;try{let r=JSON.parse(d);T=r.error?.message||r.message||JSON.stringify(r.detail||r)}catch{d&&(T=d)}throw new Error(`Mistral Error (${A.status}): ${JSON.stringify(T)}`)}let b=A.body.getReader(),C=new TextDecoder,N="",v=[],_=null,R=Date.now(),L=!1,p=d=>d?typeof d=="string"?bn(d):Array.isArray(d)?d.map(p).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?p(d.text):d.content?p(d.content):d.thinking?p(d.thinking):d.reasoning_content?p(d.reasoning_content):d.reasoning?p(d.reasoning):d.value?p(d.value):"":bn(String(d)):"";for(;;){let{done:d,value:T}=await b.read();if(d){L&&(v.length>0||_)&&(yield{candidates:v.length>0?[{content:{parts:v}}]:[],usageMetadata:_});break}N+=C.decode(T,{stream:!0});let r=N.split(`
|
|
601
|
-
`);N=r.pop();for(let k of r){let E=k.trim();if(!E||!E.startsWith("data: "))continue;let I=!1;if(E==="data: [DONE]")I=!0;else try{let H=JSON.parse(E.substring(6)),P=H.choices?.[0]?.delta,M=H.usage;if(H.choices?.[0]?.finish_reason&&(I=!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
|
|
602
|
-
`);Ee=We.pop();let Rt=!1;for(let wn of We){let zt=wn.trim();if(zt){if(zt==="data: [DONE]"){Rt=!0;break}if(zt.startsWith("data: ")){let ft;try{ft=JSON.parse(zt.substring(6))}catch{continue}if(ft.error)throw new Error(`NVIDIA Stream Error: ${ft.error.message||JSON.stringify(ft.error)}`);try{let ge=ft.usage;ge&&(F={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)},ue=!0);let me=ft.choices?.[0]?.delta?.reasoning||ft.choices?.[0]?.delta?.reasoning_content||"",se=ft.choices?.[0]?.delta?.content||"";me&&(q.push({text:me,thought:!0}),ue=!0),se&&(q.push({text:se}),ue=!0)}catch{}}}}if((Rt||Date.now()-Y>=350)&&ue&&(yield{candidates:q.length>0?[{content:{parts:[...q]}}]:[],usageMetadata:F},
|
|
603
|
-
`);p=H.pop();for(let P of H){let M=P.trim();if(!M||!M.startsWith("data: "))continue;let
|
|
601
|
+
`);N=r.pop();for(let k of r){let E=k.trim();if(!E||!E.startsWith("data: "))continue;let I=!1;if(E==="data: [DONE]")I=!0;else try{let H=JSON.parse(E.substring(6)),P=H.choices?.[0]?.delta,M=H.usage;if(H.choices?.[0]?.finish_reason&&(I=!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 Z=P.thinking||P.reasoning_content||P.reasoning,le=p(Z);le&&(v.push({text:le,thought:!0}),L=!0);let z=P.content||(!P.thinking&&!P.reasoning_content&&!P.reasoning?P.text:null);if(z)if(Array.isArray(z))for(let ie of z)if(typeof ie=="object"&&ie!==null){let ve=ie.type==="thinking"||ie.type==="reasoning"||!!ie.thought,Ne=p(ie);Ne&&(v.push({text:Ne,...ve?{thought:!0}:{}}),L=!0)}else{let ve=p(ie);ve&&(v.push({text:ve}),L=!0)}else if(typeof z=="object"&&z!==null){let ie=z.type==="thinking"||z.type==="reasoning"||!!z.thought,ve=p(z);ve&&(v.push({text:ve,...ie?{thought:!0}:{}}),L=!0)}else{let ie=p(z);ie&&(v.push({text:ie}),L=!0)}}}catch{}if((I||Date.now()-R>=150)&&L&&(yield{candidates:v.length>0?[{content:{parts:[...v]}}]:[],usageMetadata:_},v=[],R=Date.now(),L=!1),I)break}Date.now()-R>=150&&L&&(yield{candidates:v.length>0?[{content:{parts:[...v]}}]:[],usageMetadata:_},v=[],R=Date.now(),L=!1)}};var Yo=async function*(e,t,n,s,o,l,f=!1,a,m=1){let g=[];s&&g.push({role:"system",content:s}),n.forEach(Ne=>{let O=Ne.role==="model"?"assistant":"user",$=[];Array.isArray(Ne.parts)&&Ne.parts.forEach(Ee=>{if(Ee.text)$.push({type:"text",text:Ee.text});else if(Ee.inlineData&&f){let q=Ee.inlineData.mimeType,F=Ee.inlineData.data;q.startsWith("image/")&&ut(t)&&$.push({type:"image_url",image_url:{url:`data:${q};base64,${F}`}})}}),g.push({role:O,content:$.length===1&&$[0].type==="text"?$[0].text:$})});let u=Ge("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"),w=t.includes("gemma"),A=t.includes("deepseek"),b=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"),p=t.includes("seed"),d=t.includes("poolside"),T=t.includes("thinkingmachines")||t.includes("muse"),r=L,k=null,E={Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},I={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||A||d||T?16384:32768;P=process.env.NVIDIA_BASE_URL?1024:P,P=k?1024:P;let M={model:t,messages:g,max_tokens:P,stream:!0,stream_options:{include_usage:!0},temperature:m,...v&&{thinking:E[o]||"high"}};if(!(process.env.NVIDIA_BASE_URL||r||k))if(c)M.chat_template_kwargs={thinking:i};else if(w)M.chat_template_kwargs={enable_thinking:i};else if(A)if(i){let Ne=x==="High"?"max":"high";M.chat_template_kwargs={thinking:!0,reasoning_effort:Ne}}else M.chat_template_kwargs={thinking:!1};else b?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}:p?i&&(M.extra_body={thinking_budget:parseInt(I[x]??"4096")}):d?M.chat_template_kwargs={enable_thinking:i}:T&&(M.reasoning_effort=H[x]||"medium");let Z=0,le=6,z=!1,ie=process.env.NVIDIA_BASE_URL||"https://integrate.api.nvidia.com/v1/chat/completions",ve=process.env.NVIDIA_API_KEY&&process.env.NVIDIA_BASE_URL?process.env.NVIDIA_API_KEY:e;for(ie.endsWith("/chat/completions")||(ie=ie.replace(/\/+$/,"")+"/chat/completions");Z<le;){Z++;try{let Ne=await nt(ie,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${ve}`},body:JSON.stringify(M),signal:a});if(!Ne.ok){let Re=await Ne.text().catch(()=>""),Me=Ne.statusText;try{let Rt=JSON.parse(Re);Me=Rt.error?.message||Rt.message||JSON.stringify(Rt.detail||Rt)}catch{Re&&(Me=Re)}let We=new Error(`NVIDIA API Error (${Ne.status}): ${Me}`);throw We.status=Ne.status,We}let O=Ne.body.getReader(),$=new TextDecoder,Ee="",q=[],F=null,Y=Date.now(),ue=!1;for(;;){let{done:Re,value:Me}=await O.read();if(Re){ue&&(q.length>0||F)&&(yield{candidates:q.length>0?[{content:{parts:q}}]:[],usageMetadata:F},z=!0);break}Ee+=$.decode(Me,{stream:!0});let We=Ee.split(`
|
|
602
|
+
`);Ee=We.pop();let Rt=!1;for(let wn of We){let zt=wn.trim();if(zt){if(zt==="data: [DONE]"){Rt=!0;break}if(zt.startsWith("data: ")){let ft;try{ft=JSON.parse(zt.substring(6))}catch{continue}if(ft.error)throw new Error(`NVIDIA Stream Error: ${ft.error.message||JSON.stringify(ft.error)}`);try{let ge=ft.usage;ge&&(F={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)},ue=!0);let me=ft.choices?.[0]?.delta?.reasoning||ft.choices?.[0]?.delta?.reasoning_content||"",se=ft.choices?.[0]?.delta?.content||"";me&&(q.push({text:me,thought:!0}),ue=!0),se&&(q.push({text:se}),ue=!0)}catch{}}}}if((Rt||Date.now()-Y>=350)&&ue&&(yield{candidates:q.length>0?[{content:{parts:[...q]}}]:[],usageMetadata:F},z=!0,q=[],Y=Date.now(),ue=!1),Rt)break}break}catch(Ne){if(z||Z>=le)throw Ne;await new Promise(O=>setTimeout(O,3500))}}},Rr=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 w=>{let A=await fetch(w);if(!A.ok)throw new Error(`HTTP ${A.status}`);return A}))).json();if(c&&c.queues&&c.queues[0]&&typeof c.queues[0].queueDepth=="number"){let w=c.queues[0].queueDepth;u||f({value:{type:"status",content:`Queue ${w||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:w}=await i.next();if(w)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 qo=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 E of n){let I=E.role==="user"?"user":"assistant",H=[];if(Array.isArray(E.parts)){for(let P of E.parts)if(P.text)H.push({type:"text",text:P.text});else if(P.inlineData&&f){let M=P.inlineData.mimeType,Z=P.inlineData.data;M.startsWith("image/")?H.push({type:"image_url",image_url:{url:`data:${M};base64,${Z}`}}):H.push({type:"file",file:{filename:P.filename||"file",file_data:`data:${M};base64,${Z}`}})}}else{let P=E.text||"";P&&H.push({type:"text",text:P})}u.push({role:I,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,w=null;if(t.includes(":")){let E=t.split(":");if(E.length>1){let I=E[E.length-1].toLowerCase().trim();(I==="flex"||I==="priority")&&(w=I,E.pop())}if(E.length>1){let I=E[E.length-1].toLowerCase().trim();if(!x.includes(I)){let H=E.pop().trim();H&&(c={only:[H],allow_fallbacks:!1})}}i=E.join(":").trim()}let A=`${e.slice(-5)}${g||""}${o}${i}${w||""}${c?JSON.stringify(c):""}`,b=await jo(A),C={model:i,messages:u,stream:!0,temperature:m,cache_control:{type:"ephemeral"},session_id:b};w&&(C.service_tier=w),c&&(C.provider=c);let N=Ge("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 E=await _.json().catch(()=>({})),I=E.error?.metadata?.raw||E.error?.message||(typeof E.error=="string"?E.error:"")||_.statusText||"Unknown error";throw new Error(`OpenRouter Error (${_.status}): ${I}`)}let R=_.body.getReader(),L=new TextDecoder,p="",d=[],T=null,r=Date.now(),k=!1;for(;;){let{done:E,value:I}=await R.read();if(E){k&&(d.length>0||T)&&(yield{candidates:d.length>0?[{content:{parts:d}}]:[],usageMetadata:T});break}p+=L.decode(I,{stream:!0});let H=p.split(`
|
|
603
|
+
`);p=H.pop();for(let P of H){let M=P.trim();if(!M||!M.startsWith("data: "))continue;let Z=!1;if(M==="data: [DONE]")Z=!0;else try{let le=JSON.parse(M.substring(6));if(le.error){let ve=le.error.metadata?.raw||le.error.message||JSON.stringify(le.error);throw new Error(`OpenRouter Stream Error: ${ve}`)}let z=le.choices?.[0]?.delta,ie=le.usage;if(le.choices?.[0]?.finish_reason&&(Z=!0),ie&&(T={totalTokenCount:ie.total_tokens||(ie.prompt_tokens||0)+(ie.completion_tokens||0),promptTokenCount:ie.prompt_tokens||0,candidatesTokenCount:ie.completion_tokens||0,cachedContentTokenCount:ie.prompt_tokens_details?.cached_tokens||ie.prompt_tokens_details?.cache_read_input_tokens||ie.cache_read_input_tokens||0,thoughtsTokenCount:ie.completion_tokens_details?.reasoning_tokens||0},k=!0),z){let ve=z.reasoning||(z.reasoning_details?z.reasoning_details.map(Ne=>Ne.text).join(""):null);ve&&(d.push({text:ve,thought:!0}),k=!0),z.content&&(d.push({text:z.content}),k=!0)}}catch(le){if(le.message&&le.message.startsWith("OpenRouter Stream Error:"))throw le}if((Z||Date.now()-r>=150)&&k&&(yield{candidates:d.length>0?[{content:{parts:[...d]}}]:[],usageMetadata:T},d=[],r=Date.now(),k=!1),Z)break}}};import{Ollama as Sa}from"ollama";var js=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 p of n){let d=p.role==="user"?"user":"assistant",T="",r=[];if(Array.isArray(p.parts)){T=p.parts.map(k=>k.text||"").filter(Boolean).join(`
|
|
604
604
|
`);for(let k of p.parts){let E=k.inlineData||k.inline_data;E&&E.data&&r.push(E.data)}}else T=p.text||"";if(T||r.length>0){let k={role:d,content:T};r.length>0&&(k.images=r),u.push(k)}}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 Sa(i),w=[],A=null,b=Date.now(),C=!1,N=Ge("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 p of L){if(a?.aborted)throw new DOMException("The user aborted a request.","AbortError");if(p.message?.thinking&&(w.push({text:p.message.thinking,thought:!0}),C=!0),p.message?.content&&(w.push({text:p.message.content}),C=!0),p.done){let d=p.prompt_cached_count||0;if(!d&&p.prompt_eval_count){let T=p.prompt_eval_duration||0;T>0&&T<5e7&&(d=p.prompt_eval_count)}A={totalTokenCount:(p.prompt_eval_count||0)+(p.eval_count||0),promptTokenCount:p.prompt_eval_count||0,candidatesTokenCount:p.eval_count||0,cachedContentTokenCount:d,thoughtsTokenCount:0},C=!0}(p.done||Date.now()-b>=150&&C)&&(yield{candidates:w.length>0?[{content:{parts:[...w]}}]:[],usageMetadata:A},w=[],b=Date.now(),C=!1)}C&&(w.length>0||A)&&(yield{candidates:w.length>0?[{content:{parts:[...w]}}]:[],usageMetadata:A})};var zo=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 T=d.role==="user"?"user":"assistant",r="";if(Array.isArray(d.parts))for(let k of d.parts)k.text&&(r+=(r?`
|
|
605
605
|
`:"")+k.text);else r=d.text||"";g.push({role:T,content:r})}let u=Ge("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")),w={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&&(w.stream_options={include_usage:!0},w.reasoning_effort=x);let A=await nt("https://model.inferx.net/endpoints/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(w),signal:a});if(!A.ok){let d=await A.text().catch(()=>""),T="";try{let r=JSON.parse(d);T=r.error?.message||r.error?.detail||r.message||r.detail||(typeof r.error=="string"?r.error:"")||(d&&d!=="{}"?d:"")}catch{T=d}throw(!T||T==="{}")&&(T=A.statusText||"Unknown error"),new Error(`InferX Error (${A.status}): ${T}`)}let b=A.body.getReader(),C=new TextDecoder,N="",v=[],_=null,R=Date.now(),L=!1,p=!0;for(;;){let{done:d,value:T}=await b.read();if(d){L&&(v.length>0||_)&&(yield{candidates:v.length>0?[{content:{parts:v}}]:[],usageMetadata:_});break}N+=C.decode(T,{stream:!0});let r=N.split(`
|
|
606
|
-
`);N=r.pop();for(let k of r){let E=k.trim();if(!E||!E.startsWith("data: "))continue;let I=!1;if(E==="data: [DONE]")I=!0;else try{let H=JSON.parse(E.substring(6)),P=H.choices?.[0]?.delta,M=H.usage;if(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||M.reasoning_tokens||0},L=!0),P){let
|
|
606
|
+
`);N=r.pop();for(let k of r){let E=k.trim();if(!E||!E.startsWith("data: "))continue;let I=!1;if(E==="data: [DONE]")I=!0;else try{let H=JSON.parse(E.substring(6)),P=H.choices?.[0]?.delta,M=H.usage;if(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||M.reasoning_tokens||0},L=!0),P){let Z=P.reasoning||P.reasoning_content||null;if(Z&&(v.push({text:Z,thought:!0}),L=!0),P.content){let le=P.content;c&&p&&le.length>0&&(le="<think>"+le,p=!1),v.push({text:le}),L=!0}}}catch{}if((I||Date.now()-R>=150||_)&&L&&(yield{candidates:v.length>0?[{content:{parts:[...v]}}]:[],usageMetadata:_},v=[],R=Date.now(),L=!1),I)break}Date.now()-R>=150&&L&&(yield{candidates:v.length>0?[{content:{parts:[...v]}}]:[],usageMetadata:_},v=[],R=Date.now(),L=!1)}};var Jo=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",p=[];if(Array.isArray(R.parts)){for(let d of R.parts)if(d.text)p.push({type:"text",text:d.text});else if(d.inlineData&&f){let T=d.inlineData.mimeType,r=d.inlineData.data;T.startsWith("image/")&&p.push({type:"image_url",image_url:{url:`data:${T};base64,${r}`}})}}else{let d=R.text||"";d&&p.push({type:"text",text:d})}g.push({role:L,content:p.length===1&&p[0].type==="text"?p[0].text:p})}let u=Ge("SenseNova",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=await nt("https://token.sensenova.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(i),signal:a});if(!c.ok){let R=await c.json().catch(()=>({}));throw new Error(`SenseNova Error (${c.status}): ${R.error?.message||c.statusText}`)}let w=c.body.getReader(),A=new TextDecoder,b="",C=[],N=null,v=Date.now(),_=!1;for(;;){let{done:R,value:L}=await w.read();if(R){_&&(C.length>0||N)&&(yield{candidates:C.length>0?[{content:{parts:C}}]:[],usageMetadata:N});break}b+=A.decode(L,{stream:!0});let p=b.split(`
|
|
607
607
|
`);b=p.pop();for(let d of p){let T=d.trim();if(!T||!T.startsWith("data: "))continue;let r=!1;if(T==="data: [DONE]")r=!0;else try{let k=JSON.parse(T.substring(6)),E=k.choices?.[0]?.delta,I=k.usage;if(I&&(N={totalTokenCount:I.total_tokens||(I.prompt_tokens||0)+(I.completion_tokens||0),promptTokenCount:I.prompt_tokens||0,candidatesTokenCount:I.completion_tokens||0,cachedContentTokenCount:I.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:I.completion_tokens_details?.reasoning_tokens||I.reasoning_tokens||0},_=!0),E){let H=E.reasoning||E.reasoning_content||null;H&&(C.push({text:H,thought:!0}),_=!0),E.content&&(C.push({text:E.content}),_=!0)}}catch{}if((r||Date.now()-v>=150||N)&&_&&(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 Xo=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",p=[];if(Array.isArray(R.parts)){for(let d of R.parts)if(d.text)p.push({type:"text",text:d.text});else if(d.inlineData&&f){let T=d.inlineData.mimeType,r=d.inlineData.data;T.startsWith("image/")&&p.push({type:"image_url",image_url:{url:`data:${T};base64,${r}`}})}}else{let d=R.text||"";d&&p.push({type:"text",text:d})}g.push({role:L,content:p.length===1&&p[0].type==="text"?p[0].text:p})}let u=Ge("AIHubMix",t,o),x=u!==null?u:{Fast:"minimal",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=await nt("https://aihubmix.com/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(i),signal:a});if(!c.ok){let R=await c.json().catch(()=>({}));throw new Error(`AIHubMix Error (${c.status}): ${R.error?.message||c.statusText}`)}let w=c.body.getReader(),A=new TextDecoder,b="",C=[],N=null,v=Date.now(),_=!1;for(;;){let{done:R,value:L}=await w.read();if(R){_&&(C.length>0||N)&&(yield{candidates:C.length>0?[{content:{parts:C}}]:[],usageMetadata:N});break}b+=A.decode(L,{stream:!0});let p=b.split(`
|
|
608
608
|
`);b=p.pop();for(let d of p){let T=d.trim();if(!T||!T.startsWith("data: "))continue;let r=!1;if(T==="data: [DONE]")r=!0;else try{let k=JSON.parse(T.substring(6)),E=k.choices?.[0]?.delta,I=k.usage;if(k.choices?.[0]?.finish_reason&&(r=!0),I&&(N={totalTokenCount:I.total_tokens||(I.prompt_tokens||0)+(I.completion_tokens||0),promptTokenCount:I.prompt_tokens||0,candidatesTokenCount:I.completion_tokens||0,cachedContentTokenCount:I.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:I.completion_tokens_details?.reasoning_tokens||I.reasoning_tokens||0},_=!0),E){let H=E.reasoning_content||null;H&&(C.push({text:H,thought:!0}),_=!0),E.content&&(C.push({text:E.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){let g=[];s&&g.push({role:"system",content:s});for(let _ of n){let R=_.role==="user"?"user":"assistant",L=[];if(Array.isArray(_.parts)){for(let p of _.parts)if(p.text)L.push({type:"text",text:p.text});else if(p.inlineData&&f){let d=p.inlineData.mimeType,T=p.inlineData.data;d.startsWith("image/")&&L.push({type:"image_url",image_url:{url:`data:${d};base64,${T}`}})}}else{let p=_.text||"";p&&L.push({type:"text",text:p})}g.push({role:R,content:L.length===1&&L[0].type==="text"?L[0].text:L})}let u=Ge("Poolside",t,o),h=u!==null?u===!1||u==="false"||u==="none"||u==="Fast":o==="Fast",x={model:t,messages:g,stream:!0,stream_options:{include_usage:!0},temperature:m};h?x.chat_template_kwargs={enable_thinking:!1}:u!==null&&typeof u=="object"?x.chat_template_kwargs=u:x.chat_template_kwargs={enable_thinking:!0};let i=await nt("https://inference.poolside.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(x),signal:a});if(!i.ok){let _=await i.json().catch(()=>({}));throw new Error(`Poolside Error (${i.status}): ${_.error?.message||i.statusText}`)}let c=i.body.getReader(),w=new TextDecoder,A="",b=[],C=null,N=Date.now(),v=!1;for(;;){let{done:_,value:R}=await c.read();if(_){v&&(b.length>0||C)&&(yield{candidates:b.length>0?[{content:{parts:b}}]:[],usageMetadata:C});break}A+=w.decode(R,{stream:!0});let L=A.split(`
|
|
609
609
|
`);A=L.pop();for(let p of L){let d=p.trim();if(!d||!d.startsWith("data: "))continue;let T=!1;if(d==="data: [DONE]")T=!0;else try{let r=JSON.parse(d.substring(6)),k=r.choices?.[0]?.delta,E=r.usage;if(r.choices?.[0]?.finish_reason&&(T=!0),E&&(C={totalTokenCount:E.total_tokens||(E.prompt_tokens||0)+(E.completion_tokens||0),promptTokenCount:E.prompt_tokens||0,candidatesTokenCount:E.completion_tokens||0,cachedContentTokenCount:E.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:E.completion_tokens_details?.reasoning_tokens||E.reasoning_tokens||0},v=!0),k){let I=k.reasoning_content||k.reasoning||null;I&&(b.push({text:I,thought:!0}),v=!0),k.content&&(b.push({text:k.content}),v=!0)}}catch{}if((T||Date.now()-N>=150)&&v&&(yield{candidates:b.length>0?[{content:{parts:[...b]}}]:[],usageMetadata:C},b=[],N=Date.now(),v=!1),T)break}Date.now()-N>=150&&v&&(yield{candidates:b.length>0?[{content:{parts:[...b]}}]:[],usageMetadata:C},b=[],N=Date.now(),v=!1)}};var Zo=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 T=d.role==="user"?"user":"assistant",r=[];if(Array.isArray(d.parts)){for(let k of d.parts)if(k.text)r.push({type:"text",text:k.text});else if(k.inlineData&&f){let E=k.inlineData.mimeType,I=k.inlineData.data;E.startsWith("image/")&&r.push({type:"image_url",image_url:{url:`data:${E};base64,${I}`}})}}else{let k=d.text||"";k&&r.push({type:"text",text:k})}g.push({role:T,content:r.length===1&&r[0].type==="text"?r[0].text:r})}let u=Ge("9router",t,o)||Ge("9Router",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&&x!=="none"&&(u!==null||o!=="Fast")&&(i.reasoning_effort=x);let c=process.env["9ROUTER_URL"]||process.env.NINEROUTER_URL||"http://127.0.0.1:20128/v1/chat/completions",w={"Content-Type":"application/json"},A=e&&e!=="LOCAL"?e:process.env["9ROUTER_API_KEY"]||"dummy-key";w.Authorization=`Bearer ${A}`;let b=await nt(c,{method:"POST",headers:w,body:JSON.stringify(i),signal:a});if(!b.ok){let d=await b.json().catch(()=>({}));throw new Error(`9router Error (${b.status}): ${d.error?.message||b.statusText}`)}let C=b.body.getReader(),N=new TextDecoder,v="",_=[],R=null,L=Date.now(),p=!1;for(;;){let{done:d,value:T}=await C.read();if(d){p&&(_.length>0||R)&&(yield{candidates:_.length>0?[{content:{parts:_}}]:[],usageMetadata:R});break}v+=N.decode(T,{stream:!0});let r=v.split(`
|
|
610
|
-
`);v=r.pop();for(let k of r){let E=k.trim();if(!E||!E.startsWith("data: "))continue;let I=!1;if(E==="data: [DONE]")I=!0;else try{let H=JSON.parse(E.substring(6)),P=H.choices?.[0]?.delta,M=H.usage;if(H.choices?.[0]?.finish_reason&&(I=!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},p=!0),P){let
|
|
611
|
-
`);v=r.pop();for(let k of r){let E=k.trim();if(!E||!E.startsWith("data: "))continue;let I=!1;if(E==="data: [DONE]")I=!0;else try{let H=JSON.parse(E.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},p=!0),P){let
|
|
612
|
-
`);v=r.pop();for(let k of r){let E=k.trim();if(!E||!E.startsWith("data: "))continue;let I=!1;if(E==="data: [DONE]")I=!0;else try{let H=JSON.parse(E.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},p=!0),P){let
|
|
613
|
-
`);v=r.pop();for(let k of r){let E=k.trim();if(!E||!E.startsWith("data: "))continue;let I=!1;if(E==="data: [DONE]")I=!0;else try{let H=JSON.parse(E.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},p=!0),P){let
|
|
614
|
-
`),w=i.toLowerCase().includes("tool:functions.")||i.toLowerCase().includes("agent:generalist.");f.push(i),w&&c?m=!0:m=!1}}}),g()}}return n.length},Wa=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),Zd=()=>{bt=!0},ef=()=>bt,qs={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"},Wn=(e,t)=>{try{let n=ee(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?
|
|
610
|
+
`);v=r.pop();for(let k of r){let E=k.trim();if(!E||!E.startsWith("data: "))continue;let I=!1;if(E==="data: [DONE]")I=!0;else try{let H=JSON.parse(E.substring(6)),P=H.choices?.[0]?.delta,M=H.usage;if(H.choices?.[0]?.finish_reason&&(I=!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},p=!0),P){let Z=P.reasoning_content||P.reasoning||P.thinking||null;!Z&&Array.isArray(P.reasoning_details)&&P.reasoning_details.length>0&&(Z=P.reasoning_details.map(le=>typeof le=="string"?le:le?.text||"").filter(Boolean).join("")),Z&&(_.push({text:Z,thought:!0}),p=!0),P.content&&(_.push({text:P.content}),p=!0)}}catch{}if((I||Date.now()-L>=150)&&p&&(yield{candidates:_.length>0?[{content:{parts:[..._]}}]:[],usageMetadata:R},_=[],L=Date.now(),p=!1),I)break}Date.now()-L>=150&&p&&(yield{candidates:_.length>0?[{content:{parts:[..._]}}]:[],usageMetadata:R},_=[],L=Date.now(),p=!1)}};var es=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 T=d.role==="user"?"user":"assistant",r=[];if(Array.isArray(d.parts)){for(let k of d.parts)if(k.text)r.push({type:"text",text:k.text});else if(k.inlineData&&f){let E=k.inlineData.mimeType,I=k.inlineData.data;E.startsWith("image/")&&r.push({type:"image_url",image_url:{url:`data:${E};base64,${I}`}})}}else{let k=d.text||"";k&&r.push({type:"text",text:k})}g.push({role:T,content:r.length===1&&r[0].type==="text"?r[0].text:r})}let u=Ge("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",w={"Content-Type":"application/json"},A=e||process.env.EXPLABS_API_KEY||process.env.EXPERIENTIALLABS_API_KEY||"";w.Authorization=`Bearer ${A}`;let b=await nt(c,{method:"POST",headers:w,body:JSON.stringify(i),signal:a});if(!b.ok){let d=await b.json().catch(()=>({}));throw new Error(`Experiential Labs Error (${b.status}): ${d.error?.message||d.message||b.statusText}`)}let C=b.body.getReader(),N=new TextDecoder,v="",_=[],R=null,L=Date.now(),p=!1;for(;;){let{done:d,value:T}=await C.read();if(d){p&&(_.length>0||R)&&(yield{candidates:_.length>0?[{content:{parts:_}}]:[],usageMetadata:R});break}v+=N.decode(T,{stream:!0});let r=v.split(`
|
|
611
|
+
`);v=r.pop();for(let k of r){let E=k.trim();if(!E||!E.startsWith("data: "))continue;let I=!1;if(E==="data: [DONE]")I=!0;else try{let H=JSON.parse(E.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},p=!0),P){let Z=P.reasoning_content||P.reasoning||null;!Z&&Array.isArray(P.reasoning_details)&&P.reasoning_details.length>0&&(Z=P.reasoning_details.map(le=>le.text||"").filter(Boolean).join("")),Z&&(_.push({text:Z,thought:!0}),p=!0),P.content&&(_.push({text:P.content}),p=!0)}}catch{}if((I||Date.now()-L>=150)&&p&&(yield{candidates:_.length>0?[{content:{parts:[..._]}}]:[],usageMetadata:R},_=[],L=Date.now(),p=!1),I)break}Date.now()-L>=150&&p&&(yield{candidates:_.length>0?[{content:{parts:[..._]}}]:[],usageMetadata:R},_=[],L=Date.now(),p=!1)}};var Vs=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 T=d.role==="user"?"user":"assistant",r=[];if(Array.isArray(d.parts)){for(let k of d.parts)if(k.text)r.push({type:"text",text:k.text});else if(k.inlineData&&f){let E=k.inlineData.mimeType,I=k.inlineData.data;E.startsWith("image/")&&r.push({type:"image_url",image_url:{url:`data:${E};base64,${I}`}})}}else{let k=d.text||"";k&&r.push({type:"text",text:k})}g.push({role:T,content:r.length===1&&r[0].type==="text"?r[0].text:r})}let u=Ge("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",w={"Content-Type":"application/json","X-Title":"Flux-Flow","User-Agent":"Flux-Flow","HTTP-Referer":"https://fluxflow-cli.onrender.com/"},A=e||process.env.TOKENHARBOR_API_KEY||process.env.TOKEN_HARBOR_API_KEY||"";w.Authorization=`Bearer ${A}`;let b=await nt(c,{method:"POST",headers:w,body:JSON.stringify(i),signal:a});if(!b.ok){let d=await b.json().catch(()=>({}));throw new Error(`Token Harbor Error (${b.status}): ${d.error?.message||d.message||b.statusText}`)}let C=b.body.getReader(),N=new TextDecoder,v="",_=[],R=null,L=Date.now(),p=!1;for(;;){let{done:d,value:T}=await C.read();if(d){p&&(_.length>0||R)&&(yield{candidates:_.length>0?[{content:{parts:_}}]:[],usageMetadata:R});break}v+=N.decode(T,{stream:!0});let r=v.split(`
|
|
612
|
+
`);v=r.pop();for(let k of r){let E=k.trim();if(!E||!E.startsWith("data: "))continue;let I=!1;if(E==="data: [DONE]")I=!0;else try{let H=JSON.parse(E.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},p=!0),P){let Z=P.reasoning_content||P.reasoning||null;!Z&&Array.isArray(P.reasoning_details)&&P.reasoning_details.length>0&&(Z=P.reasoning_details.map(le=>le.text||"").filter(Boolean).join("")),Z&&(_.push({text:Z,thought:!0}),p=!0),P.content&&(_.push({text:P.content}),p=!0)}}catch{}if((I||Date.now()-L>=150)&&p&&(yield{candidates:_.length>0?[{content:{parts:[..._]}}]:[],usageMetadata:R},_=[],L=Date.now(),p=!1),I)break}Date.now()-L>=150&&p&&(yield{candidates:_.length>0?[{content:{parts:[..._]}}]:[],usageMetadata:R},_=[],L=Date.now(),p=!1)}};var Ks=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 T=d.role==="user"?"user":"assistant",r=[];if(Array.isArray(d.parts)){for(let k of d.parts)if(k.text)r.push({type:"text",text:k.text});else if(k.inlineData&&f){let E=k.inlineData.mimeType,I=k.inlineData.data;E.startsWith("image/")&&r.push({type:"image_url",image_url:{url:`data:${E};base64,${I}`}})}}else{let k=d.text||"";k&&r.push({type:"text",text:k})}g.push({role:T,content:r.length===1&&r[0].type==="text"?r[0].text:r})}let u=Ge("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",w={"Content-Type":"application/json","X-Title":"Flux-Flow","User-Agent":"Flux-Flow","HTTP-Referer":"https://fluxflow-cli.onrender.com/"},A=e||process.env.APINEX_API_KEY||"";w.Authorization=`Bearer ${A}`;let b=await nt(c,{method:"POST",headers:w,body:JSON.stringify(i),signal:a});if(!b.ok){let d=await b.json().catch(()=>({}));throw new Error(`APInex Error (${b.status}): ${d.error?.message||d.message||b.statusText}`)}let C=b.body.getReader(),N=new TextDecoder,v="",_=[],R=null,L=Date.now(),p=!1;for(;;){let{done:d,value:T}=await C.read();if(d){p&&(_.length>0||R)&&(yield{candidates:_.length>0?[{content:{parts:_}}]:[],usageMetadata:R});break}v+=N.decode(T,{stream:!0});let r=v.split(`
|
|
613
|
+
`);v=r.pop();for(let k of r){let E=k.trim();if(!E||!E.startsWith("data: "))continue;let I=!1;if(E==="data: [DONE]")I=!0;else try{let H=JSON.parse(E.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},p=!0),P){let Z=P.reasoning_content||P.reasoning||null;!Z&&Array.isArray(P.reasoning_details)&&P.reasoning_details.length>0&&(Z=P.reasoning_details.map(le=>le.text||"").filter(Boolean).join("")),Z&&(_.push({text:Z,thought:!0}),p=!0),P.content&&(_.push({text:P.content}),p=!0)}}catch{}if((I||Date.now()-L>=150)&&p&&(yield{candidates:_.length>0?[{content:{parts:[..._]}}]:[],usageMetadata:R},_=[],L=Date.now(),p=!1),I)break}Date.now()-L>=150&&p&&(yield{candidates:_.length>0?[{content:{parts:[..._]}}]:[],usageMetadata:R},_=[],L=Date.now(),p=!1)}};var _a=/```[\s\S]*?```/g,Ea=/```[\s\S]*$/g,Aa=/`[^`]+`/g,Ca=/^\|.*\|$/gm,va=/^[^\w]+|[^\w]+$/g,Ra=/[^a-z0-9]/gi,po=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,Ma=/\[\s*(?:tool:functions\.|agent:generalist\.)([a-z0-9_]+)\s*\(/gi,Ia=/(?:path|targetFile|TargetFile|directory|keyword|id|taskId|title|task)\s*=\s*\\?["']?([^\\"' \),]+)/,Bn=/["']/g,Mr=/\\/g,Da=/<\|channel>thought/gi,Oa=/<channel\|>/gi,La=e=>typeof e!="string"?e:e.replace(Da,"<think>").replace(Oa,"</think>"),Qd=/^\s*(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\]|$)/i,Pa=(e,t)=>{let n=!1;for(let s=0;s<t;s++)e[s]==="`"&&(n=!n);return n},$a=e=>{let t=/(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\])/gi,n;for(;(n=t.exec(e))!==null;)if(!Pa(e,n.index))return{index:n.index,length:n[0].length};return{index:-1,length:0}},Ys=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=$a(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=Ys(e);return t?t.remainingText.trimStart():e};var Nr=/`[^`]*`/g,Fr=/`[^`]*$/,Ir=/<\|\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,Na=/"([^"]+)"\s*:\s*(?:"([^"]*)"|(\d+)|true|false|null)/g,Dr=/<\|\s*tool_calls_section_begin\s*\|>/gi,Or=/<\|\s*tool_calls_section_end\s*\|>/gi,Fa=/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi;var Lr=e=>!e||typeof e!="string"?e:e.replace(/(```[\s\S]*?```|`[^`]*`)|(<(?:\w+)(?:[^>]*)>\r?\n?|\r?\n?<\/\w+(?:[^>]*)>)/gi,(t,n)=>n||""),Br=e=>{if(!e||typeof e!="string")return e;let t=yo(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()},zs=null,ts={},Un={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`),Ba=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"))})})}}},bt=!1;var Ua=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
|
+
`),w=i.toLowerCase().includes("tool:functions.")||i.toLowerCase().includes("agent:generalist.");f.push(i),w&&c?m=!0:m=!1}}}),g()}}return n.length},Wa=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),Zd=()=>{bt=!0},ef=()=>bt,qs={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"},Wn=(e,t)=>{try{let n=ee(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?Q.basename(o.replace(/["']/g,"").replace(/\\/g,"/")):null}catch{return null}},Js=e=>e?new $r({apiKey:e}):zs,tf=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:w,sessionStats:A,aiProvider:b="Google",apiKey:C}=e,N=process.env.NVIDIA_BASE_URL||b==="Ollama"||b==="InferX"||b==="SenseNova"||b==="AIHubMix"||b==="Poolside"||b==="9router"||b==="ExpLabs"||b==="ExperientialLabs"?!1:w?.memory!==!1,_=Ct(Nn,[]).map(O=>`- [${O.id}]: ${O.memory}`).join(`
|
|
615
615
|
`),R=s.slice(0,-1).filter(O=>O.text&&!O.text.includes("[TOOL RESULT]")&&!O.text.includes("OBSERVATION:")&&!O.text.startsWith("[TERMINAL_RECORD]")&&!O.isTerminalRecord&&!O.isMeta&&!O.isLogo&&!String(O.id).startsWith("welcome")&&!String(O.id).startsWith("logo")).slice(-14).map(O=>{let $=qt(Wa(O.text)).replace(/\[tool:functions\..*?\]/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[METADATA \(PRIORITY: DYNAMIC\)\] Time: ([^|\n]+)/g,(Y,ue)=>`[METADATA (PRIORITY: DYNAMIC)] Time: ${ue.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
617
|
`).replace(/\\n\\n/g,"").trim(),Ee=O.role==="user"?8192:32768,q=$.substring(0,Ee);$.length>Ee&&(q+=`
|
|
@@ -624,9 +624,9 @@ ${h[7]}
|
|
|
624
624
|
${I.length>8192?`... (truncated) ...
|
|
625
625
|
|
|
626
626
|
`:""}
|
|
627
|
-
[AGENT (current turn)]: ${E}`;R.push({role:"user",parts:[{text:M}]});let
|
|
627
|
+
[AGENT (current turn)]: ${E}`;R.push({role:"user",parts:[{text:M}]});let Z=await ms("NVIDIA"),z=(await oo()).quotas?.providerTiers?.NVIDIA==="Free",ie="",ve=0,Ne=N?12:-1;for(;ve<=Ne;)try{if(!await di("background",e))return;let O="",$=null,Ee=!1,q=b;try{let ue=new Promise((ge,me)=>setTimeout(()=>me(new Error("JANITOR_TIMEOUT")),1e4)),Re=b==="Google"&&ve>=0&&ve<6&&Z&&z,Me=b==="DeepSeek"&&ve<4&&Z&&z;Ee=Re||Me,q=Ee?"NVIDIA":b;let We=(async()=>{if(b==="OpenRouter"){let ge=fe("janitor_open_router"),se=qo(C,ge,R,k,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),Ot=await se.next();return{iterator:se,firstResult:Ot}}else if(b==="DeepSeek"&&!Ee){let me=Vo(C,fe("deepseek_fast_fallback"),R,k,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),se=await me.next();return{iterator:me,firstResult:se}}else if(b==="Mistral"&&!Ee){let me=Ko(C,fe("mistral_janitor_fallback"),R,k,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),se=await me.next();return{iterator:me,firstResult:se}}else if(b==="NVIDIA"||Ee){let me=Yo(Ee?Z:C,fe("nvidia_janitor_fallback"),R,k,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),se=await me.next();return{iterator:me,firstResult:se}}else if(b==="InferX"){let me=zo(C,targetModel||fe("inferx_fallback")||"deepseek-v4-flash",R,k,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),se=await me.next();return{iterator:me,firstResult:se}}else if(b==="SenseNova"){let me=Jo(C,targetModel||fe("sensenova_fallback")||"sensenova-6.8-flash-lite",R,k,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),se=await me.next();return{iterator:me,firstResult:se}}else if(b==="AIHubMix"){let me=Xo(C,targetModel||fe("aihubmix_fallback")||"gpt-4o-mini",R,k,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),se=await me.next();return{iterator:me,firstResult:se}}else if(b==="Poolside"){let me=Qo(C,targetModel||fe("poolside_fallback")||"poolside/laguna-s-2.1",R,k,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),se=await me.next();return{iterator:me,firstResult:se}}else if(b==="9router"||b==="9Router"){let me=Zo(C,targetModel||fe("9router_fallback")||"z-ai/glm-5.3-flash",R,k,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),se=await me.next();return{iterator:me,firstResult:se}}else if(b==="ExpLabs"||b==="ExperientialLabs"){let me=es(C,targetModel||fe("explabs_fallback")||"deepseek-v4-pro-0813",R,k,"Fast",x,!1,null,.7)[Symbol.asyncIterator](),se=await me.next();return{iterator:me,firstResult:se}}else{let se=(await Js(C).models.generateContentStream({model:i||(ve===Ne?fe("janitor_default"):fe("gemma_janitor_fallback_google")),contents:R,config:{systemInstruction:k,temperature:.7,safetySettings:[{category:In.HARM_CATEGORY_HARASSMENT,threshold:Mn.BLOCK_NONE},{category:In.HARM_CATEGORY_HATE_SPEECH,threshold:Mn.BLOCK_NONE},{category:In.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Mn.BLOCK_NONE},{category:In.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Mn.BLOCK_NONE}],thinkingConfig:{includeThoughts:!1,thinkingLevel:Ze.MINIMAL}}}))[Symbol.asyncIterator](),Ot=await se.next();return{iterator:se,firstResult:Ot}}})();if(process.stdout.isTTY){let se=(await xs())[c]?.name||"",Ot=se&&!se.startsWith("flow-")&&!se.startsWith("Session ")?se:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${Ot}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${Ot}\x07`)}let{iterator:Rt,firstResult:wn}=await Promise.race([We,ue]),{value:zt,done:ft}=wn;if(!ft&&zt){let ge=zt.candidates?.[0]?.content?.parts,me=ge?q==="Google"?ge[1]?.text||ge[0]?.text||"":ge.filter(se=>se.text&&!se.thought).map(se=>se.text).join(""):typeof zt.text=="function"?zt.text():"";me&&(O+=me),$=zt.usageMetadata;for await(let se of{[Symbol.asyncIterator]:()=>Rt}){let Ot=se.candidates?.[0]?.content?.parts,Hn=Ot?q==="Google"?Ot[1]?.text||Ot[0]?.text||"":Ot.filter(_t=>_t.text&&!_t.thought).map(_t=>_t.text).join(""):typeof se.text=="function"?se.text():"";Hn&&(O+=Hn),$=se.usageMetadata}}}catch(ue){throw ue}if(O){if(ie=O,$){let ue=$.totalTokenCount||0,Re=$.cachedContentTokenCount||0,Me=($.candidatesTokenCount||0)+(q==="Google"&&$.thoughtsTokenCount||0),We=Ee?fe("nvidia_janitor_fallback"):q==="DeepSeek"?fe("deepseek_fast_fallback"):q==="ExpLabs"||q==="ExperientialLabs"?fe("explabs_fallback")||"deepseek-v4-pro-0813":q==="OpenRouter"?fe("janitor_open_router"):i||(ve===Ne?fe("janitor_default"):fe("gemma_janitor_fallback_google"));await Ut("tokens",ue,q,We),Re>0&&await Ut("cachedTokens",Re,q,We),Me>0&&await Ut("candidateTokens",Me,q,We)}}else throw new Error("No synthesis generated by Janitor.");g&&(g(),await vt("background"));let F=yo(ie),Y=!1;for(let ue of F){let Re=ue.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(Re)&&(Y=!0);let Me={chatId:c,sessionId:c,history:s},We=await mo(Re,ue.args,Me);Re.toLowerCase()==="memory"&&(ue.args.includes("action='user'")||ue.args.includes('action="user"'))&&!We.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 ue=Ct(Nn,[]);if(ue.length>0){let Re=[];for(let Me of ue)Me.score===void 0&&(Me.score=.5),Me.score*=.99995,Me.score<.05&&(Me.score=0),Me.score=Math.round(Me.score*1e5)/1e5,Me.score>0&&Re.push(Me);zn(Nn,Re)}}catch{}break}catch(O){ve++;let $=new Date().toLocaleString(),Ee=O instanceof Error?(()=>{try{return JSON.parse(JSON.parse(O.message).error.message).error.message}catch{return String(O)}})():String(O);await new Promise(Y=>setTimeout(Y,1e3));let q=Q.join(Cn,"janitor");if(Ue.existsSync(q)||Ue.mkdirSync(q,{recursive:!0}),Ue.appendFileSync(Q.join(q,"error.log"),`ERROR [Attempt ${ve}/${Ne+1}] [${$}]: ${Ee}
|
|
628
628
|
|
|
629
|
-
`),ve>Ne)break;let F=Math.min(750*Math.pow(2,ve-1),5e3);await new Promise(Y=>setTimeout(Y,F))}if(ve){let O=
|
|
629
|
+
`),ve>Ne)break;let F=Math.min(750*Math.pow(2,ve-1),5e3);await new Promise(Y=>setTimeout(Y,F))}if(ve){let O=Q.join(Cn,"janitor");Ue.appendFileSync(Q.join(O,"error.log"),`-----------------------------------------------------------------------------
|
|
630
630
|
|
|
631
631
|
`)}if(process.stdout.isTTY)try{let Ee=(await xs())[c]?.name||"",q=Ee&&!Ee.startsWith("flow-")&&!Ee.startsWith("Session ")?Ee:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${q}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${q}\x07`)}catch{process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")}},Ha=e=>{let t=qt(e),n=ys?t:t.replace(Nr,o=>" ".repeat(o.length)).replace(Fr,o=>" ".repeat(o.length));po.lastIndex=0;let s;for(;(s=po.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,po.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}},Ur=(e,t=!0)=>{let n=po;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},Ga=(e,t,n)=>{let s=po;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 w=x-1;w>=0&&e[w]==="\\";w--)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},Pr=e=>Ur(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("");Ir.lastIndex=0;let s=e.replace(Ir,(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=Na;x.lastIndex=0;let i;for(;(i=x.exec(f))!==null;){let c=i[1],w=i[2]!==void 0?i[2]:i[0].split(":").slice(1).join(":").trim();h.push(`${c}=${JSON.stringify(w)}`)}h.length>0?a=h.join(", "):a=f.trim()}let m=l.toLowerCase().replace(/_/g,"");return`[tool:functions.${t[m]||n(l)}(${a})]`});return Dr.lastIndex=0,Or.lastIndex=0,s=s.replace(Dr,""),s=s.replace(Or,""),s},Va=/(?:path|query|url|keyword|command|method|title|task|id)\s*=\s*['"`]?\s*\.\.\.\s*['"`]?/i,Ka=/^['"`]?\s*\.\.\.\s*['"`]?$/,kn=e=>{if(e==null)return!1;let t=String(e).trim();return t==="..."||t==="\u2026"||Ka.test(t)},yo=e=>{if(!e)return[];let t=ja(e),n=qt(t),s=[],o=ys?n:n.replace(Nr,a=>" ".repeat(a.length)).replace(Fr,a=>" ".repeat(a.length)),l=Ma;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 w=0;for(let A=i-1;A>=0&&n[A]==="\\";A--)w++;w%2===0&&(u=null)}}else if(c==='"'||c==="'"||c==="`")u=c;else if(c==="(")g++;else if(c===")"&&(g--,g===0)){x=i;let w=i+1;for(;w<o.length&&/\s/.test(o[w]);)w++;if(w<o.length&&o[w]==="]"){h=w;break}}}if(h!==-1){let i=n.substring(m+1,x),c=n.substring(f.index,h+1),w=ee(i);kn(w.path)||kn(w.query)||kn(w.url)||kn(w.keyword)||kn(w.command)||kn(w.method)||kn(w.title)||kn(w.task)||kn(w.id)||Va.test(i)||s.push({fullMatch:c,toolName:a.trim(),args:i.trim()}),l.lastIndex=h+1}}return s},nf=(e,t={})=>{if(!e)return null;if(ts=t,zs=new $r({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}}}},ns=async(e,t,n,s,o="Fast",l=.75,f="agent")=>Ba(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,w=setInterval(()=>{bt&&(i.abort(),clearInterval(w))},100);try{let A;a==="Ollama"?A=js(m,t,x,s,o,g,ut(t),c,l,systemSettings?.ollamaEndpoint||"Cloud"):a==="OpenRouter"?A=qo(m,t,x,s,o,g,ut(t),c,l):a==="DeepSeek"?A=Vo(m,t,x,s,o,g,ut(t),c,l):a==="Mistral"?A=Ko(m,t,x,s,o,g,ut(t),c,l):a==="NVIDIA"?A=Yo(m,t,x,s,o,g,ut(t),c,l):a==="InferX"?A=zo(m,t,x,s,o,g,ut(t),c,l):a==="SenseNova"?A=Jo(m,t,x,s,o,g,ut(t),c,l):a==="AIHubMix"?A=Xo(m,t,x,s,o,g,ut(t),c,l):a==="Poolside"?A=Qo(m,t,x,s,o,g,ut(t),c,l):a==="9router"||a==="9Router"?A=Zo(m,t,x,s,o,g,ut(t),c,l):a==="ExpLabs"||a==="ExperientialLabs"?A=es(m,t,x,s,o,g,ut(t),c,l):a==="TokenHarbor"||a==="Token Harbor"||a==="tokenharbor"||a==="token_harbor"||a==="thk"?A=Vs(m,t,x,s,o,g,ut(t),c,l):a==="APInex"||a==="apinex"||a==="apx"?A=Ks(m,t,x,s,o,g,ut(t),c,l):A=await Js(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 b of A){if(bt)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(b.candidates?.[0]?.content?.parts)for(let v of b.candidates[0].content.parts)v.text&&!v.thought&&(u+=v.text,C+=v.text);let N=C?ps(C):0;e&&typeof e.onTokenChunk=="function"&&e.onTokenChunk(C,N),b.usageMetadata&&(h=b.usageMetadata)}}finally{clearInterval(w)}if(h){let A=h.totalTokenCount||0,b=h.cachedContentTokenCount||0,C=(h.candidatesTokenCount||0)+(a==="Google"&&h.thoughtsTokenCount||0);await Ut("tokens",A,a,t),b>0&&await Ut("cachedTokens",b,a,t),C>0&&await Ut("candidateTokens",C,a,t),e&&typeof e.onUsage=="function"&&e.onUsage({totalTokenCount:A,cachedContentTokenCount:b,candidatesTokenCount:C})}return await vt("agent",a),{text:u,usageMetadata:h}}),Ya=async(e,t,n=null)=>{n=n||Ct(Eo,{});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.
|
|
@@ -653,8 +653,8 @@ ${c}
|
|
|
653
653
|
`):f+=`-- Individual Memories:
|
|
654
654
|
${c}
|
|
655
655
|
|
|
656
|
-
`}let m=0,g=5,u=!1,h=fe("gemma_janitor_fallback_google");for(s==="OpenRouter"&&(h=fe("janitor_open_router")),s==="DeepSeek"&&(h=fe("deepseek_level_1")),s==="Mistral"&&(h=fe("mistral_level_1")),s==="NVIDIA"&&(h=fe("nvidia_janitor_fallback")),s==="InferX"&&(h=fe("inferx_fallback")),s==="SenseNova"&&(h=fe("sensenova_fallback")),s==="AIHubMix"&&(h=fe("aihubmix_fallback")),s==="Poolside"&&(h=fe("poolside_fallback")),(s==="9router"||s==="9Router")&&(h=fe("9router_fallback"));m<=g&&!u;){m++;try{let i=(await ns(t,h,f,null,"Fast",.75,"background")).text||"",c=yo(i);if(c.length===0)throw new Error("No tool calls detected in synthesis response");for(let w of c){let A=w.toolName;["saveSummary","saveSumary","SaveSummary","SaveSumary"].includes(A)&&await mo(A,w.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=
|
|
657
|
-
`)}},of=async(e,t,n=!1)=>{let{chatId:s,aiProvider:o="Google"}=e,l=
|
|
656
|
+
`}let m=0,g=5,u=!1,h=fe("gemma_janitor_fallback_google");for(s==="OpenRouter"&&(h=fe("janitor_open_router")),s==="DeepSeek"&&(h=fe("deepseek_level_1")),s==="Mistral"&&(h=fe("mistral_level_1")),s==="NVIDIA"&&(h=fe("nvidia_janitor_fallback")),s==="InferX"&&(h=fe("inferx_fallback")),s==="SenseNova"&&(h=fe("sensenova_fallback")),s==="AIHubMix"&&(h=fe("aihubmix_fallback")),s==="Poolside"&&(h=fe("poolside_fallback")),(s==="9router"||s==="9Router")&&(h=fe("9router_fallback"));m<=g&&!u;){m++;try{let i=(await ns(t,h,f,null,"Fast",.75,"background")).text||"",c=yo(i);if(c.length===0)throw new Error("No tool calls detected in synthesis response");for(let w of c){let A=w.toolName;["saveSummary","saveSumary","SaveSummary","SaveSumary"].includes(A)&&await mo(A,w.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=Q.join(Cn,"janitor");Ue.existsSync(l)||Ue.mkdirSync(l,{recursive:!0}),Ue.appendFileSync(Q.join(l,"error.log"),`[${new Date().toLocaleString()}] Past memory batch consolidation error: ${o}
|
|
657
|
+
`)}},of=async(e,t,n=!1)=>{let{chatId:s,aiProvider:o="Google"}=e,l=Q.join(_o,"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 w=c.fullText||c.text||"",A=c.role==="system"||w.startsWith("[TOOL RESULT]:")||c.text&&c.text.startsWith("[TOOL RESULT]:"),b=w;return A&&(w.includes("[TOOL RESULT]:")||c.text&&c.text.includes("[TOOL RESULT]:"))?b="[TOOL RESULT]: ...truncated for summary":b=b.replace(/(\[(?:tool|agent):[a-zA-Z0-9_\.]+)\([\s\S]*?\)(\])/g,"$1(...)$2"),`[${A?"TOOL":c.role==="agent"?"AGENT":"USER"}]: ${b}`}).join(`
|
|
658
658
|
|
|
659
659
|
`),a=async(i,c)=>{let w="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.",A=c?`Here is the previous summary:
|
|
660
660
|
${c}
|
|
@@ -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.`,b=fe("gemma_janitor_fallback_google");o==="OpenRouter"&&(b=fe("janitor_open_router")),o==="DeepSeek"&&(b=fe("deepseek_level_1")),o==="Mistral"&&(b=fe("mistral_level_1")),o==="NVIDIA"&&(b=fe("nvidia_chat_summarizer_fallback")),o==="InferX"&&(b=fe("inferx_fallback")),o==="SenseNova"&&(b=fe("sensenova_fallback")),o==="AIHubMix"&&(b=fe("aihubmix_fallback")),o==="Poolside"&&(b=fe("poolside_fallback")),(o==="9router"||o==="9Router")&&(b=fe("9router_fallback")),(o==="ExpLabs"||o==="ExperientialLabs")&&(b=fe("explabs_fallback")||"deepseek-v4-pro-0813"),(o==="TokenHarbor"||o==="Token Harbor"||o==="tokenharbor"||o==="token_harbor"||o==="thk")&&(b=fe("tokenharbor_fallback")||"deepseek-v4.1-flash:free");let C=0,N=!1,v=null;for(;C<=3&&!N;){C++;try{v=await ns(e,b,A,w,"Fast"),N=!0}catch{if(C>3){if(o==="Google")try{let R=fe("general_fallback");return(await ns(e,R,A,w,"Fast")).text||""}catch{return""}return""}}}return v&&v.text||""},m=f(t),g=Ct(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=Ua(t);return n?u.historyLength=(u.historyLength||0)+i:u.historyLength=i,g[s]=u,zn(l,g),x}return null},sf=e=>{try{let t=
|
|
668
|
+
Provide a consolidated summary of the entire session.`,b=fe("gemma_janitor_fallback_google");o==="OpenRouter"&&(b=fe("janitor_open_router")),o==="DeepSeek"&&(b=fe("deepseek_level_1")),o==="Mistral"&&(b=fe("mistral_level_1")),o==="NVIDIA"&&(b=fe("nvidia_chat_summarizer_fallback")),o==="InferX"&&(b=fe("inferx_fallback")),o==="SenseNova"&&(b=fe("sensenova_fallback")),o==="AIHubMix"&&(b=fe("aihubmix_fallback")),o==="Poolside"&&(b=fe("poolside_fallback")),(o==="9router"||o==="9Router")&&(b=fe("9router_fallback")),(o==="ExpLabs"||o==="ExperientialLabs")&&(b=fe("explabs_fallback")||"deepseek-v4-pro-0813"),(o==="TokenHarbor"||o==="Token Harbor"||o==="tokenharbor"||o==="token_harbor"||o==="thk")&&(b=fe("tokenharbor_fallback")||"deepseek-v4.1-flash:free");let C=0,N=!1,v=null;for(;C<=3&&!N;){C++;try{v=await ns(e,b,A,w,"Fast"),N=!0}catch{if(C>3){if(o==="Google")try{let R=fe("general_fallback");return(await ns(e,R,A,w,"Fast")).text||""}catch{return""}return""}}}return v&&v.text||""},m=f(t),g=Ct(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=Ua(t);return n?u.historyLength=(u.historyLength||0)+i:u.historyLength=i,g[s]=u,zn(l,g),x}return null},sf=e=>{try{let t=Q.join(_o,"chat-summaries.json");if(Ue.existsSync(t)){let n=Ct(t,{});n[e]&&(delete n[e],zn(t,n))}}catch{}},rf=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:w}=n,A=ut(e);if(!zs&&i==="Google")throw new Error("AI not initialized");let b=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=Q.join(_o,"chat-summaries.json"),v=!1,_=t.filter(T=>T.role==="user").length===1,R=C.includes("[TITLE-UPDATE]"),L=_||R,p=C.replace(/\[TITLE-UPDATE\]/g,"").trim();p=p.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),yield{type:"status",content:"[start]"},yield{type:"status",content:"Gathering Context"},await vo.startTransaction(g,p),h?.advanceRollback&&await so.takeInitialSnapshot(g),bt=!1;let d=null;try{let T=new AbortController;d=setInterval(()=>{bt&&(T.abort(),d&&(clearInterval(d),d=null))},400);let r=[...t.slice(0,-1)];{let Ie=Ct(N,{})[g]||{summary:"",historyLength:0};if(Ie.summary&&Ie.historyLength>0){let Jt=0,et=[];for(let Ae=0;Ae<r.length;Ae++){let it=r[Ae];(it.role==="user"||it.role==="agent"||it.role==="system")&&!String(it.id).startsWith("welcome")&&!it.isMeta&&Jt++,Jt>Ie.historyLength&&et.push(it)}r=et}}r=r.map(G=>{if(G.role==="user"&&G.text){let Ie=G.text.match(/\[USER\]([\s\S]*?)\[\/USER\]/);if(Ie)return{...G,text:Ie[1].trim()}}return{...G}});let k=process.env.HIGH_CONTEXT,E=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(k&&k!=="false"){let G=parseInt(k,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")&&E&&(P=16e3),(x?.tokens||0)>P){yield{type:"text",content:"\u2726 Maximum Context Limit Reached. Start a new chat."};return}if(_&&b){let G=Ct(Eo,{});Object.values(G).flat().length>5&&(yield{type:"status",content:"Condensing past chat memories"},await Ya(g,n,G))}let M=Ct(Eo,{}),Z=Ct(us,{}),le=Object.entries(M).filter(([G])=>G!==g).flatMap(([G,Ie])=>Ie),ie=[...Object.entries(Z).filter(([G])=>G!==g).slice(-20).map(([G,Ie])=>`[Chat Summary]: ${Ie}`),...le].map(G=>`- ${G}`).join(`
|
|
669
669
|
`),Ne=Ct(Nn,[]).map(G=>`- ${G.memory}`).join(`
|
|
670
|
-
`),O=(x?.tokens||0)>=1e4,$=er(ie,Ne,b,O),Ee=new Date,q=Ee.getFullYear(),F=Ee.toLocaleString("en-US",{month:"short"}).toUpperCase(),Y=String(Ee.getDate()).padStart(2,"0"),ue=Ee.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}),Re=`${q}-${F}-${Y}, ${ue}`,Me=`${ue}`,We=[".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"],Rt=G=>{try{return Ue.readdirSync(G,{withFileTypes:!0})}catch{return[]}},wn=(G,Ie={value:0},Jt=1)=>{if(Ie.value>6200||Jt>7)return Ie.value;let et=Rt(G);for(let Ae of et){if(Ie.value>6200)break;We.includes(Ae.name)||Ae.name.startsWith(".")||Ae.isDirectory()&&(Ie.value++,wn(
|
|
670
|
+
`),O=(x?.tokens||0)>=1e4,$=er(ie,Ne,b,O),Ee=new Date,q=Ee.getFullYear(),F=Ee.toLocaleString("en-US",{month:"short"}).toUpperCase(),Y=String(Ee.getDate()).padStart(2,"0"),ue=Ee.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}),Re=`${q}-${F}-${Y}, ${ue}`,Me=`${ue}`,We=[".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"],Rt=G=>{try{return Ue.readdirSync(G,{withFileTypes:!0})}catch{return[]}},wn=(G,Ie={value:0},Jt=1)=>{if(Ie.value>6200||Jt>7)return Ie.value;let et=Rt(G);for(let Ae of et){if(Ie.value>6200)break;We.includes(Ae.name)||Ae.name.startsWith(".")||Ae.isDirectory()&&(Ie.value++,wn(Q.join(G,Ae.name),Ie,Jt+1))}return Ie.value},zt=(G,Ie)=>h?.indentationTree!==!1?Ws(G,Ie,1,Rt,We):Gs(G,Ie,"",1,Rt,We),ft=wn(process.cwd()),ge=10;ft>3072||ft>2304?ge=1:ft>1536?ge=2:ft>768?ge=3:ft>384?ge=5:ft>192?ge=6:ft>96?ge=7:(ft>48||ft>24)&&(ge=9);let me=Ct(gs,{}),se=me[g],Ot=se?se!==process.cwd():!1;me[g]=process.cwd(),zn(gs,me);let Hn=Ct(N,{}),_t=Hn[g]||{summary:"",historyLength:0};typeof _t=="string"&&(_t={summary:_t,historyLength:0});let Wr=t.filter(G=>(G.role==="user"||G.role==="agent"||G.role==="system")&&!String(G.id).startsWith("welcome")&&!G.isMeta).length;_t.historyLength&&Wr<_t.historyLength&&(_t.summary="",_t.historyLength=0,Hn[g]=_t,zn(N,Hn));let xo=typeof _t=="object"?_t.summary||"":_t||"",Xs=r.length>0;Xs&&xo&&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
|
${xo}
|
|
673
673
|
|
|
@@ -680,7 +680,7 @@ ${xo}
|
|
|
680
680
|
CWD: `+process.cwd()+`${u?" [PLAYGROUND MODE]":""}
|
|
681
681
|
`+zt(process.cwd(),ge),pt=await Fn(),un="";if(Go()&&pt.file_focused!=="none"){un=`
|
|
682
682
|
[Additional IDE Context]
|
|
683
|
-
`;let G=
|
|
683
|
+
`;let G=Q.relative(process.cwd(),pt.file_focused),Ie=(pt.opened_editors||[]).map(et=>{let Ae=Q.relative(process.cwd(),et);return Ae.startsWith("..")?`[External] ${Q.basename(et)}`:Ae});if(un+=`Focused File: ${G}
|
|
684
684
|
Cursor Line: ${pt.cursor_line}
|
|
685
685
|
`,pt.selected){let et=pt.selected,Ae=et.split(`
|
|
686
686
|
`);Ae.length>256&&(et=Ae.slice(0,240).join(`
|
|
@@ -691,7 +691,7 @@ Cursor Line: ${pt.cursor_line}
|
|
|
691
691
|
... [truncated] ...
|
|
692
692
|
`+et.slice(-128)),un+=`Current Selection: "${et}"
|
|
693
693
|
`}if(pt.manual_edits){let Ae=pt.manual_edits.split(`
|
|
694
|
-
`),it=[],ot=null;for(let j of Ae)j.trim()&&(j.startsWith(" Line ")?ot&&ot.edits.push(j):(ot={path:j.endsWith(":")?j.slice(0,-1):j,edits:[]},it.push(ot)));for(let j of it)j.edits.length>80&&(j.edits=j.edits.slice(-80)),j.originalEditsCount=j.edits.length;let at=(j,He)=>He.reduce((_e,gt)=>{let Mt=pt.file_focused&&(gt.path===pt.file_focused||
|
|
694
|
+
`),it=[],ot=null;for(let j of Ae)j.trim()&&(j.startsWith(" Line ")?ot&&ot.edits.push(j):(ot={path:j.endsWith(":")?j.slice(0,-1):j,edits:[]},it.push(ot)));for(let j of it)j.edits.length>80&&(j.edits=j.edits.slice(-80)),j.originalEditsCount=j.edits.length;let at=(j,He)=>He.reduce((_e,gt)=>{let Mt=pt.file_focused&&(gt.path===pt.file_focused||Q.resolve(process.cwd(),gt.path)===Q.resolve(pt.file_focused))?Math.ceil(j*1.2):j;return _e+Math.min(gt.edits.length,Mt)},0),pe=80;if(at(80,it)>300){let j=!1;for(let He=80;He>=10;He--)if(at(He,it)<=300){pe=He,j=!0;break}j||(pe=10)}let ze=[...it];if(pe===10&&at(10,ze)>500)for(;ze.length>0&&at(10,ze)>500;){let j=0,He=ze[0].originalEditsCount;for(let _e=1;_e<ze.length;_e++)ze[_e].originalEditsCount<He&&(He=ze[_e].originalEditsCount,j=_e);ze.splice(j,1)}for(let j of ze){let _e=pt.file_focused&&(j.path===pt.file_focused||Q.resolve(process.cwd(),j.path)===Q.resolve(pt.file_focused))?Math.ceil(pe*1.2):pe;j.edits.length>_e&&(j.edits=j.edits.slice(-_e))}for(let j of ze){let He=`${j.path}:
|
|
695
695
|
${j.edits.join(`
|
|
696
696
|
`)}`;for(;j.edits.length>0&&He.length>4*768;)j.edits.shift(),He=`${j.path}:
|
|
697
697
|
${j.edits.join(`
|
|
@@ -707,10 +707,10 @@ ${pt.diagnostics}
|
|
|
707
707
|
`),(p.toLowerCase().includes("lint")||p.toLowerCase().includes("warning"))&&pt.warnings&&(un+=`
|
|
708
708
|
**Lint Warnings**:
|
|
709
709
|
${pt.warnings}
|
|
710
|
-
`)}let ei=p.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),ti=/(?:\\)?@\[([^\]]+)\]/g,ss,is=[];for(ti.lastIndex=0;(ss=ti.exec(ei))!==null;){let G=ss[0].startsWith("\\");is.push({tag:ss[1],isEscaped:G})}let rs=[],bo=null;for(let G=0;G<is.length;G++){let{tag:Ie,isEscaped:Jt}=is[G];if(!Jt)try{let et=Ie.trim().replace(/^["']|["']$/g,""),Ae=/[:#]L?(\d+)(?:-L?(\d+))?$/i,it=et.match(Ae),ot=et,at=null,pe=null;it&&(at=parseInt(it[1],10),pe=it[2]?parseInt(it[2],10):at,ot=et.slice(0,it.index));let ze=
|
|
710
|
+
`)}let ei=p.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),ti=/(?:\\)?@\[([^\]]+)\]/g,ss,is=[];for(ti.lastIndex=0;(ss=ti.exec(ei))!==null;){let G=ss[0].startsWith("\\");is.push({tag:ss[1],isEscaped:G})}let rs=[],bo=null;for(let G=0;G<is.length;G++){let{tag:Ie,isEscaped:Jt}=is[G];if(!Jt)try{let et=Ie.trim().replace(/^["']|["']$/g,""),Ae=/[:#]L?(\d+)(?:-L?(\d+))?$/i,it=et.match(Ae),ot=et,at=null,pe=null;it&&(at=parseInt(it[1],10),pe=it[2]?parseInt(it[2],10):at,ot=et.slice(0,it.index));let ze=Q.resolve(process.cwd(),ot);if(Ue.existsSync(ze)&&Ue.statSync(ze).isFile()){let j=ot.toLowerCase(),He=j.endsWith(".pdf"),_e=j.endsWith(".docx")||j.endsWith(".doc")||j.endsWith(".ppt")||j.endsWith(".pptx")||j.endsWith(".xls")||j.endsWith(".xlsx"),gt=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(j),Sn=gt||He||_e,Mt=i==="Google"||ut(e);if(Sn&&!Mt){let Pt=`\u2718 Unsupported Modality: ${Q.basename(ot)}`,Je=115;process.stdout.isTTY&&(Je=process.stdout.columns-5||120);let ye=[Pt],Qe=Math.max(...ye.map(mn=>mn.length)),En=Math.min(Qe+4,Je),Dn=ye.map(mn=>`${mn.padEnd(En-2).substring(0,En-2)}`).join(`
|
|
711
711
|
`);yield{type:"visual_feedback",content:Yt(`${Dn}
|
|
712
|
-
`)};continue}if(at===null&&!Sn){let Pt=0;try{Pt=Ue.readFileSync(ze,"utf8").split(/\r\n|\r|\n/).length}catch{}if(Pt>300){let Je=`\u21B7 Skipped (Too Large): ${
|
|
713
|
-
`)};continue}}let sn=at!==null?at:1,_n=pe!==null?pe:at!==null?at:sn+299;_n-sn>300&&(_n=sn+300);let Qn=`path=${JSON.stringify(ot)}, startLine=${sn}, endLine=${_n}`,Qt=await yi(Qn,{isMultiModal:Mt}),yt=!1,tt="",Lt=null;if(typeof Qt=="string"?Qt.trim().startsWith("ERROR")?yt=!0:tt=Qt:Qt&&typeof Qt=="object"&&Qt.binaryPart?(Lt=Qt.binaryPart,tt=Qt.text||""):yt=!0,!yt){let Pt="";if(gt?(Pt=`\u2714 Processed: ${
|
|
712
|
+
`)};continue}if(at===null&&!Sn){let Pt=0;try{Pt=Ue.readFileSync(ze,"utf8").split(/\r\n|\r|\n/).length}catch{}if(Pt>300){let Je=`\u21B7 Skipped (Too Large): ${Q.basename(ot)}`,ye=115;process.stdout.isTTY&&(ye=process.stdout.columns-5||120);let Qe=Math.min(Je.length+4,ye),En=Je.padEnd(Qe-2).substring(0,Qe-2);yield{type:"visual_feedback",content:Yt(`${En}
|
|
713
|
+
`)};continue}}let sn=at!==null?at:1,_n=pe!==null?pe:at!==null?at:sn+299;_n-sn>300&&(_n=sn+300);let Qn=`path=${JSON.stringify(ot)}, startLine=${sn}, endLine=${_n}`,Qt=await yi(Qn,{isMultiModal:Mt}),yt=!1,tt="",Lt=null;if(typeof Qt=="string"?Qt.trim().startsWith("ERROR")?yt=!0:tt=Qt:Qt&&typeof Qt=="object"&&Qt.binaryPart?(Lt=Qt.binaryPart,tt=Qt.text||""):yt=!0,!yt){let Pt="";if(gt?(Pt=`\u2714 Processed: ${Q.basename(ot)}`,bo=Lt):He||_e?(Pt=`\u2714 Auto-Analysed: ${Q.basename(ot)}`,bo=Lt):(Pt=`\u2714 Auto-Read: ${Q.basename(ot)}`,rs.push(tt)),Pt){let Je=115;process.stdout.isTTY&&(Je=process.stdout.columns-5||120);let ye=[Pt],Qe=Math.max(...ye.map(mn=>mn.length)),En=Math.min(Qe+4,Je),Dn=ye.map(mn=>`${mn.padEnd(En-2).substring(0,En-2)}`).join(`
|
|
714
714
|
`);yield{type:"visual_feedback",content:Yt(`${Dn}
|
|
715
715
|
`)}}}}}catch{}}let as="";rs.length>0&&(as=`[Tagged File Contents] Auto Read User Tagged files by System, No need to re-read
|
|
716
716
|
`+rs.join(`
|
|
@@ -726,45 +726,45 @@ WARNING: CWD Changed from previous: "${se}" to current: "${process.cwd()}", writ
|
|
|
726
726
|
`:""}${$}${un}
|
|
727
727
|
[/Metadata]
|
|
728
728
|
${os}${si}[system] exact tool string [tool:functions.ToolName(arg="value")] in chat [/system]
|
|
729
|
-
${as}${oi}[user prompt] ${ni.trim()} [/user prompt]`.trim();let ri={role:"user",text:ko};bo&&(ri.binaryPart=bo),r.forEach(G=>{G.text&&G.role==="agent"&&(G.text=qt(G.text))}),r.push(ri),os&&t[t.length-1]?.id&&(yield{type:"summary_injected",content:{id:t[t.length-1].id,text:ko}});let gn=null,Tn=a==="Flux"?50:15;Tn=a.toLowerCase().includes("cu")?75:Tn;let Vr=Math.floor(Tn/2),ai=0,nn=16;yield{type:"status",content:"Connecting"},bt=!1;let ls=[],wo=!1,li=!1;for(let G=0;G<=Tn;G++){let Ie=Math.floor(Tn*.95);if(G>=Ie&&ai<Ie&&typeof n?.onAskUser=="function"){ai=Ie;try{let ce="Agent has been running for a long time. Do you want to continue execution?",we=[{id:"continue",label:"Continue",description:"Add few more steps"},{id:"cancel",label:"Cancel",description:"Stop extending and finish current turn limit"}],
|
|
729
|
+
${as}${oi}[user prompt] ${ni.trim()} [/user prompt]`.trim();let ri={role:"user",text:ko};bo&&(ri.binaryPart=bo),r.forEach(G=>{G.text&&G.role==="agent"&&(G.text=qt(G.text))}),r.push(ri),os&&t[t.length-1]?.id&&(yield{type:"summary_injected",content:{id:t[t.length-1].id,text:ko}});let gn=null,Tn=a==="Flux"?50:15;Tn=a.toLowerCase().includes("cu")?75:Tn;let Vr=Math.floor(Tn/2),ai=0,nn=16;yield{type:"status",content:"Connecting"},bt=!1;let ls=[],wo=!1,li=!1;for(let G=0;G<=Tn;G++){let Ie=Math.floor(Tn*.95);if(G>=Ie&&ai<Ie&&typeof n?.onAskUser=="function"){ai=Ie;try{let ce="Agent has been running for a long time. Do you want to continue execution?",we=[{id:"continue",label:"Continue",description:"Add few more steps"},{id:"cancel",label:"Cancel",description:"Stop extending and finish current turn limit"}],X=await n.onAskUser(ce,we);X&&(X.toLowerCase().includes("continue")||X==="Continue")&&(Tn+=Vr)}catch{}}let Jt=await hs("agent",n);if(!Jt.allowed)throw new Error(Jt.reason||`Budget Exhausted for Provider (${i||"Agent"})`);let et=[];if(wo=!1,a==="ICU"||a==="FluxCU")try{yield{type:"status",content:"Capturing Screen"},await new Promise(X=>setTimeout(X,1e3));let{captureGriddedScreenshot:ce}=await import("./screen_grid-TDQC6CV5.js"),we=await ce();if(we&&we.base64){let X="[system] Fresh Gridded Screen Feedback Captured. Use numeric coordinates. Old screenshots will be removed when new screenshot is captured, summarize in text if context is needed later [/system]",$t={inlineData:{mimeType:we.mimeType,data:we.base64}},It=h?.imageHistoryCU||"Standard",Et=It==="Low"?1:It==="Extended"?5:3,Xt=r.filter(Ke=>Array.isArray(Ke.parts)&&Ke.parts.some(Nt=>Nt.inlineData));if(Xt.length>=Et){let Ke=Xt.length-Et+1;for(let Nt=0;Nt<Ke;Nt++){let At=Xt[Nt];Array.isArray(At.parts)&&(At.parts=At.parts.filter(kt=>!kt.inlineData))}}if(r.length>0&&r[r.length-1].role==="user"){let Ke=r[r.length-1];typeof Ke.text=="string"&&(Ke.text+=`
|
|
730
730
|
|
|
731
|
-
${
|
|
731
|
+
${X}`,Array.isArray(Ke.parts)||(Ke.parts=[{text:Ke.text}]),Ke.parts.push($t))}else r.push({role:"user",text:X,parts:[{text:X},$t]})}}catch(ce){console.error("Vision screenshot capture error:",ce)}if(h?.compression===0&&(x?.tokens||0)>P&&(r=pi(r,6)),G>0?yield{type:"status",content:"Working"}:yield{type:"status",content:"Connecting"},bt){try{let{clearPendingNudges:ce}=await import("./subagent_state-LZCOZSUJ.js");ce()}catch{}yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
|
|
732
732
|
|
|
733
|
-
\x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}try{let{consumePendingNudges:ce}=await import("./subagent_state-LZCOZSUJ.js"),we=ce();if(we&&we.length>0){let
|
|
733
|
+
\x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}try{let{consumePendingNudges:ce}=await import("./subagent_state-LZCOZSUJ.js"),we=ce();if(we&&we.length>0){let X=we.join(`
|
|
734
734
|
|
|
735
735
|
`);r.length>0&&r[r.length-1].role==="user"?r[r.length-1].text+=`
|
|
736
736
|
|
|
737
|
-
${
|
|
737
|
+
${X}`:r.push({role:"user",text:X}),yield{type:"status",content:"Subagent Update"}}}catch{}if(s){let ce=await s();ce&&(ce.startsWith("/btw")?r.length>0&&r[r.length-1].role==="user"?r[r.length-1].text+=`
|
|
738
738
|
|
|
739
739
|
[system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
|
|
740
740
|
[question] ${ce.replace("/btw","").trim()} [/question]`:r.push({role:"user",text:`[system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
|
|
741
741
|
[question] ${ce.replace("/btw","").trim()} [/question]`}):r.length>0&&r[r.length-1].role==="user"?r[r.length-1].text+=`
|
|
742
742
|
|
|
743
|
-
[STEERING HINT from USER, High Priority] ${ce.trim()} [/STEERING HINT]`:r.push({role:"user",text:`[STEERING HINT from USER, High Priority] ${ce.trim()} [/STEERING HINT]`}),yield{type:"status",content:`${ce.startsWith("/btw")?"Question Forwarded...":"Steering Hint Injected..."}`})}let Ae,it=!1,ot=1,at=1,pe="",ze=null,on=null,j=null,He=0,_e=[],gt=0,Sn=!1,Mt=!1,sn=!1,_n=!1,Qn=!0,Qt=0,yt="",tt="",Lt=!1,Pt=!1,Je=!0,ye=e,Qe="";for(;ot<=nn&&at<=nn&&!it&&!bt;){let ce=!1;try{pe="",Qn&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},Qn=!1,at===1&&(yt=""));let we=D=>{if(!D||!D.includes("[tool:"))return D;let ne="",B=Ys(D);B&&(ne=B.fullBlock,D=B.remainingText),D=D.replace(Fa,(be,he)=>he.includes("[tool:")?he.trim():be);let W="",Te=0;for(;Te<D.length;){let be=D.indexOf("[tool:",Te);if(be===-1){W+=Lr(D.substring(Te));break}let he=D.substring(Te,be);W+=Lr(he);let Xe=-1,U=null,te=0;for(let je=be;je<D.length;je++){let y=D[je];if(U){if(y===U){let Ve=0;for(let Oe=je-1;Oe>=0&&D[Oe]==="\\";Oe--)Ve++;Ve%2===0&&(U=null)}}else if(y==='"'||y==="'"||y==="`")U=y;else if(y==="(")te++;else if(y===")")te--;else if(y==="]"&&te<=0){Xe=je;break}}if(Xe===-1){W+=D.substring(be);break}W+=D.substring(be,Xe+1),Te=Xe+1}return(h?.keepReasoningContext?ne:"")+W},
|
|
743
|
+
[STEERING HINT from USER, High Priority] ${ce.trim()} [/STEERING HINT]`:r.push({role:"user",text:`[STEERING HINT from USER, High Priority] ${ce.trim()} [/STEERING HINT]`}),yield{type:"status",content:`${ce.startsWith("/btw")?"Question Forwarded...":"Steering Hint Injected..."}`})}let Ae,it=!1,ot=1,at=1,pe="",ze=null,on=null,j=null,He=0,_e=[],gt=0,Sn=!1,Mt=!1,sn=!1,_n=!1,Qn=!0,Qt=0,yt="",tt="",Lt=!1,Pt=!1,Je=!0,ye=e,Qe="";for(;ot<=nn&&at<=nn&&!it&&!bt;){let ce=!1;try{pe="",Qn&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},Qn=!1,at===1&&(yt=""));let we=D=>{if(!D||!D.includes("[tool:"))return D;let ne="",B=Ys(D);B&&(ne=B.fullBlock,D=B.remainingText),D=D.replace(Fa,(be,he)=>he.includes("[tool:")?he.trim():be);let W="",Te=0;for(;Te<D.length;){let be=D.indexOf("[tool:",Te);if(be===-1){W+=Lr(D.substring(Te));break}let he=D.substring(Te,be);W+=Lr(he);let Xe=-1,U=null,te=0;for(let je=be;je<D.length;je++){let y=D[je];if(U){if(y===U){let Ve=0;for(let Oe=je-1;Oe>=0&&D[Oe]==="\\";Oe--)Ve++;Ve%2===0&&(U=null)}}else if(y==='"'||y==="'"||y==="`")U=y;else if(y==="(")te++;else if(y===")")te--;else if(y==="]"&&te<=0){Xe=je;break}}if(Xe===-1){W+=D.substring(be);break}W+=D.substring(be,Xe+1),Te=Xe+1}return(h?.keepReasoningContext?ne:"")+W},X=r.filter(D=>(D.role==="user"||D.role==="agent"||D.role==="system")&&!String(D.id).startsWith("welcome")&&!D.isMeta&&!D.isTerminalRecord&&!(D.text&&D.text.startsWith("[TERMINAL_RECORD]"))).map((D,ne,B)=>{let W=D.text||"";b||(W=W.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),D.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(D.parts)&&D.parts.length>0?Te=D.parts.map(be=>{if(be.text){let he=be.text;return b||(he=he.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),D.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 be}):Te=[{text:W}],D.binaryPart&&ut(ye)&&B.slice(ne+1).filter(he=>he.role==="user"&&!he.text?.startsWith("[TOOL RESULT]")).length<=2&&Te.push(D.binaryPart),{role:D.role==="user"||D.role==="system"?"user":"model",parts:Te}});for(let D=0;D<X.length;D++){let ne=X[D],B=ne.parts?.[0]?.text||"";if(ne.role==="model"&&/\[tool:/i.test(B)){let W=-1;for(let Te=D+1;Te<X.length;Te++){let be=X[Te],he=be.parts?.[0]?.text||"";if(be.role==="user"&&he.startsWith("[TOOL RESULT]")){W=Te;break}}if(W!==-1&&W!==D+1){let[Te]=X.splice(W,1);X.splice(D+1,0,Te)}}}for(let D=X.length-2;D>=0;D--){let ne=X[D],B=X[D+1];ne.role==="user"&&B.role==="user"&&(B.parts?.[0]?.text||"").trim().startsWith("[SYSTEM")&&X.splice(D,1)}let $t=[];for(let D=0;D<X.length;D++){let ne=X[D];if($t.length===0)$t.push(ne);else{let B=$t[$t.length-1];B.role===ne.role?(B.parts[0].text+=`
|
|
744
744
|
|
|
745
|
-
`+(ne.parts?.[0]?.text||""),ne.parts?.length>1&&B.parts.push(...ne.parts.slice(1))):$t.push(ne)}}
|
|
745
|
+
`+(ne.parts?.[0]?.text||""),ne.parts?.length>1&&B.parts.push(...ne.parts.slice(1))):$t.push(ne)}}X.length=0,X.push(...$t),ye=e;let It=`${g}|${i}|${a}|${f}|${ye}|${JSON.stringify(l)}|${!!h?.dynamicDirAwareness}|${!!h?.subAgents}`,Et=Un.key===It&&Un.value;if((process.env.I_HAVE_TOO_MUCH_MONEY==="true"||process.env.I_HAVE_TOO_MUCH_MONEY===!0)&&(Et=!1),Et)Qe=Un.value;else{let D=i==="Mistral"?!!Co(ye):!(ye||"gemma").toLowerCase().startsWith("gemma");Qe=tr(l,((ye||"gemma").toLowerCase().startsWith("gemma"),f),a,h,b,_,i,i==="Google"?!0:A,D,g,!!h?.keepReasoningContext,ye),h?.dynamicDirAwareness||(Qe+=`
|
|
746
746
|
${Zs.replace(`
|
|
747
747
|
**Directory Structure**`,`
|
|
748
|
-
-- Directory Structure --`)}`),Un.key=It,Un.value=Qe}let Ke=
|
|
748
|
+
-- Directory Structure --`)}`),Un.key=It,Un.value=Qe}let Ke=X[X.length-1];if(Go()&G>0){await new Promise(B=>setTimeout(B,2500)),yield{type:"status",content:"Verifying"};let D=await Fn(),ne=D?D.diagnostics:null;ne&&Ke&&Ke.role==="user"&&Ke.parts?.[0]?.text&&(Ke.parts[0].text+=`
|
|
749
749
|
${ne} [/ERROR]`),yield{type:"status",content:"Working"}}let Nt=i==="Mistral"||i==="Google"&&e?.toLowerCase().startsWith("gemma");if(h?.advanceRollback&&Ke&&Ke.role==="user"&&Ke.parts?.[0]?.text?.startsWith("[TOOL RESULT]"))try{let D=await so.getLatestFileChanges(g);if(D&&(D.newFiles.length>0||D.modifiedFiles.length>0||D.deletedFiles.length>0)){let ne=`
|
|
750
750
|
[system] File Changes:
|
|
751
751
|
`;for(let W of D.newFiles)ne+=`* ${W} (created)
|
|
752
752
|
`;for(let W of D.modifiedFiles)ne+=`* ${W} (modified)
|
|
753
753
|
`;for(let W of D.deletedFiles)ne+=`* ${W} (deleted)
|
|
754
754
|
`;ne+="[/system]",Ke.parts[0].text+=ne;let B=-1;for(let W=r.length-1;W>=0;W--)if(r[W].role==="user"&&r[W].text?.startsWith("[TOOL RESULT]")){B=W;break}B!==-1&&(r[B].text+=ne)}}catch{}let At=Math.floor(Tn*.99),kt=G+1;kt>=At&&Ke&&Ke.parts?.[0]&&(Ke.parts[0].text+=`
|
|
755
|
-
[system] WARNING, Turn Limit Impending: Step ${kt}/${Tn}. Wrap up quickly/prompt user to continue. [/system]`);let Dt=new Promise((D,ne)=>{T.signal.aborted&&ne(new DOMException("The user aborted a request.","AbortError")),T.signal.addEventListener("abort",()=>{ne(new DOMException("The user aborted a request.","AbortError"))})});Dt.catch(()=>{});let mt=
|
|
755
|
+
[system] WARNING, Turn Limit Impending: Step ${kt}/${Tn}. Wrap up quickly/prompt user to continue. [/system]`);let Dt=new Promise((D,ne)=>{T.signal.aborted&&ne(new DOMException("The user aborted a request.","AbortError")),T.signal.addEventListener("abort",()=>{ne(new DOMException("The user aborted a request.","AbortError"))})});Dt.catch(()=>{});let mt=X;if(i==="Ollama")Ae=js(n.apiKey,ye,mt,Qe,f,a,A,T.signal,1,h?.ollamaEndpoint||"Cloud");else if(i==="OpenRouter")Ae=qo(n.apiKey,ye,mt,Qe,f,a,A,T.signal,1,g);else if(i==="DeepSeek")Ae=Vo(n.apiKey,ye,mt,Qe,f,a,A,T.signal,1);else if(i==="Mistral")Ae=Ko(n.apiKey,ye,mt,Qe,f,a,A,T.signal,1,g);else if(i==="NVIDIA"){let D=Yo(n.apiKey,ye,mt,Qe,f,a,A,T.signal,1);Ae=Rr(D,ye)}else if(i==="InferX")Ae=zo(n.apiKey,ye,mt,Qe,f,a,A,T.signal,1);else if(i==="SenseNova")Ae=Jo(n.apiKey,ye,mt,Qe,f,a,A,T.signal,1);else if(i==="AIHubMix")Ae=Xo(n.apiKey,ye,mt,Qe,f,a,A,T.signal,1);else if(i==="Poolside")Ae=Qo(n.apiKey,ye,mt,Qe,f,a,A,T.signal,1);else if(i==="9router"||i==="9Router")Ae=Zo(n.apiKey,ye,mt,Qe,f,a,A,T.signal,1);else if(i==="ExpLabs"||i==="ExperientialLabs")Ae=es(n.apiKey,ye,mt,Qe,f,a,A,T.signal,1);else if(i==="TokenHarbor"||i==="Token Harbor"||i==="tokenharbor"||i==="token_harbor"||i==="thk")Ae=Vs(n.apiKey,ye,mt,Qe,f,a,A,T.signal,1);else if(i==="APInex"||i==="apinex"||i==="apx")Ae=Ks(n.apiKey,ye,mt,Qe,f,a,A,T.signal,1);else{let ne=Js(n?.apiKey).models.generateContentStream({model:ye||"gemini-3-flash-preview",contents:mt,config:{systemInstruction:Qe,mediaResolution:"MEDIA_RESOLUTION_HIGH",safetySettings:[{category:In.HARM_CATEGORY_HARASSMENT,threshold:Mn.BLOCK_NONE},{category:In.HARM_CATEGORY_HATE_SPEECH,threshold:Mn.BLOCK_NONE},{category:In.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Mn.BLOCK_NONE},{category:In.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Mn.BLOCK_NONE}],temperature:1.05,thinkingConfig:(()=>{let B=Ge("Google",ye||"gemini-3-flash-preview",f);if(B!==null){if(typeof B=="object")return B;if(B===!1||B==="false"||B==="none"||B===0||B==="0")return{includeThoughts:!1};if(typeof B=="number")return{includeThoughts:!0,thinkingBudget:B};if(typeof B=="string"){let he=B.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(B);if(!isNaN(Xe))return{includeThoughts:!0,thinkingBudget:Xe}}}let W=(ye||"").toLowerCase(),Te=W.includes("gemma-4")||W.startsWith("gemma"),be=W.includes("gemini-3");if(Te||be)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:T.signal});Ae=await Promise.race([ne,Dt])}pe="",ze=null,j=null,_e=[],gt=0,yield{type:"model_update",content:null},tt="",Lt=yt.length>0;let rn="",cs=Date.now(),Ln=async function*(){if(i==="Google"&&rn){let D=Zn(rn);for(let ne of D)yield ne;rn="",cs=Date.now()}},ci=!0,Pn="",Gn=!1,wt=null,jn=!1,qr={tool:{startPrefix:"[tool",fullPrefix:"[tool:functions.",endTag:"]"},agent:{startPrefix:"[agent",fullPrefix:"[agent:generalist.",endTag:"]"},end:{startPrefix:"[[END]]",fullPrefix:"[[END]]",endTag:"[[END]]"},kimi_section:{startPrefix:"<|tool_calls_section_begin|>",fullPrefix:"<|tool_calls_section_begin|>",endTag:"<|tool_calls_section_end|>"},kimi_call:{startPrefix:"<|tool_call_begin|>",fullPrefix:"<|tool_call_begin|>",endTag:"<|tool_call_end|>"}},Zn=D=>{let ne=[],B=D;for(;B.length>0;)if(Gn){let W=Pn+B,Te=qr[wt];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){jn||ne.push({type:"text",content:W}),Pn="",Gn=!1,wt=null,B="";break}}let be=-1,he=Te?Te.endTag:"]";if(wt==="tool"||wt==="agent"){let Xe=0,U=null,te=0,je=!1;for(let y=0;y<W.length;y++){let Ve=W[y];if(U){if(Ve===U){let Oe=0;for(let J=y-1;J>=0&&W[J]==="\\";J--)Oe++;Oe%2===0&&(U=null)}}else if(Ve==='"'||Ve==="'"||Ve==="`")U=Ve;else if(Ve==="(")Xe++,je=!0;else if(Ve===")")Xe--;else if(Ve==="[")te++;else if(Ve==="]"){if(je&&Xe===0&&te===1){be=y;break}te--}}}else be=W.indexOf(he);if(be!==-1){let Xe=he.length;if(!wt?.startsWith("kimi")){let U=W.substring(0,be+Xe);ne.push({type:"text",content:U})}(wt==="tool"||wt==="agent"||wt?.startsWith("kimi"))&&(jn=!0),Pn="",Gn=!1,wt=null,B=W.substring(be+Xe)}else{let Xe=wt?.startsWith("kimi")?8192:512;W.length>Xe?(jn||ne.push({type:"text",content:W}),Pn="",Gn=!1,wt=null):Pn=W,B="";break}}else{let W=B.indexOf("[tool"),Te=B.indexOf("[agent"),be=B.indexOf("[[END]]"),he=B.indexOf("<|tool_calls_section_begin|>"),Xe=B.indexOf("<|tool_call_begin|>"),U=[{type:"tool",idx:W,start:"[tool",end:"]"},{type:"agent",idx:Te,start:"[agent",end:"]"},{type:"end",idx:be,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(te=>te.idx!==-1).sort((te,je)=>te.idx-je.idx);if(U.length>0){let te=U[0];te.idx>0&&(jn||ne.push({type:"text",content:B.substring(0,te.idx)})),Gn=!0,wt=te.type,Pn="",B=B.substring(te.idx)}else{let te=["[tool","[agent","[[END]]","<|tool_calls_section_begin|>","<|tool_call_begin|>"],je=-1;for(let y of te){for(let Ve=y.length-1;Ve>0;Ve--)if(B.endsWith(y.substring(0,Ve))){je=B.length-Ve;let Oe=te.indexOf(y);Oe===0?wt="tool":Oe===1?wt="agent":Oe===2?wt="end":Oe===3?wt="kimi_section":wt="kimi_call";break}if(je!==-1)break}if(je!==-1)je>0&&(jn||ne.push({type:"text",content:B.substring(0,je)})),Gn=!0,Pn=B.substring(je),B="";else{jn||ne.push({type:"text",content:B});break}}}return ne},zr=Ae[Symbol.asyncIterator]();for(;;){let{value:D,done:ne}=await Promise.race([zr.next(),Dt]);if(ne)break;if(D&&D.type==="status"){yield D;continue}let B="",W=D.candidates?.[0]?.content?.parts;if(W&&W.length>0)for(let be of W){let he=typeof be.text=="string"?be.text:be.text?parseChunkText(be.text):"";be.thought?he&&(ce||(B+="<think>",ce=!0),B+=he):he&&(ce&&(B+="</think>",ce=!1),B+=he)}else D.text&&ce&&(B+="</think>",ce=!1);B=La(B);let Te=B?ps(B):0;if(n&&typeof n.onTokenChunk=="function"&&n.onTokenChunk(B,Te),ci&&(yield{type:"status",content:"Thinking"},ci=!1),bt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
|
|
756
756
|
|
|
757
|
-
\x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(B){if(Lt){if(tt+=B,tt.length>=64){let U=0,te=Math.min(yt.length,tt.length);for(let y=te;y>=10;y--)if(yt.endsWith(tt.substring(0,y))){U=y;break}let je=tt.substring(U);if(je){let Ve=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(yt)?je.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):je.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(Ve)if(pe+=Ve,i==="Google")rn+=Ve;else{yield*Ln();let Oe=Zn(Ve);for(let
|
|
758
|
-
`).length;qe=xt,!Se&&!K&&xt>800?Fe=Math.min(50,xt):Fe=Math.min(ae,xt)}}catch{}let Be=(S||"").toLowerCase(),ht=Be.endsWith(".pdf"),$e=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);ht||$e?
|
|
757
|
+
\x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(B){if(Lt){if(tt+=B,tt.length>=64){let U=0,te=Math.min(yt.length,tt.length);for(let y=te;y>=10;y--)if(yt.endsWith(tt.substring(0,y))){U=y;break}let je=tt.substring(U);if(je){let Ve=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(yt)?je.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):je.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(Ve)if(pe+=Ve,i==="Google")rn+=Ve;else{yield*Ln();let Oe=Zn(Ve);for(let J of Oe)yield J}}Lt=!1,tt=""}continue}else if(pe+=B,i==="Google")rn+=B;else{yield*Ln();let U=Zn(B);for(let te of U)yield te}let be=Ha(pe);if(be.inside){Pt=!0,j||(j=Date.now());let te={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"}[be.toolName]||be.toolName,je=be.args||"",y=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(te)){let Oe=ee(je),J=Oe.path||Oe.targetFile||Oe.TargetFile||Oe.directory,an=Oe.keyword,$n=Oe.title||Oe.task,An=Oe.id||Oe.taskId,De=Oe.timeout||Oe.time;if(an!=null)y=String(an).replace(Bn,"");else if(J)y=Q.basename(String(J).replace(Bn,"").replace(Mr,"/"));else if($n&&(te==="invoke"||te==="invoke_sync"))y=String($n).replace(Bn,"").substring(0,30);else if(An&&te==="get_progress")y=String(An).replace(Bn,"");else if(De&&te==="await"){let Ft=parseFloat(String(De).replace(Bn,""));isNaN(Ft)?y=String(De).replace(Bn,""):(Ft<5&&(Ft=5),Ft>120&&(Ft=120),y=(hn=>{if(hn>=60){let fs=Math.floor(hn/60),Vn=hn%60;return`${fs}m${Vn>0?` ${Vn}s`:""}`}return`${hn}s`})(Ft))}else{let Ft=je.match(Ia);if(Ft){let Ht=Ft[1].replace(Bn,"");te==="invoke"||te==="invoke_sync"||te==="get_progress"?y=Ht.substring(0,30):y=te==="search_keyword"||te==="file_map"?Ht:Q.basename(Ht.replace(Mr,"/"))}}}let Ve=`${qs[te]||te}${y?` ${y}`:""}`;if((te!==ze||y!==on)&&(ze=te,on=y,yield{type:"status",content:`${Ve}`},process.stdout.isTTY)){let J={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"}[te]||"Working";process.stdout.write(`\x1B]0;${J}...\x07`)}}if(pe.length-Qt>150){Qt=pe.length;let U=Ur(pe,!1),te=Ys(U),je=te?(te.innerContent||"").trim():"",y=je.split(/[.!?]\s+/),Ve=new Set(y),Oe=y.length>10?(y.length-Ve.size)/y.length:0,J=je.split(/\s+/).filter(Le=>Le.length>0).length,an=.6,$n=.8,An=!1;if((i.toLowerCase().includes("google")||i.toLowerCase().includes("mistral"))&&((ye||"").toLowerCase().startsWith("gemma")||(ye||"").toLowerCase().includes("stral"))){let S={low:256,medium:1024,high:8192,max:16384,xhigh:16384}[f?.toLowerCase()]||2500;An=J>S}if(Oe>an||An){yield{type:"status",content:`${Oe>an?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},Mt=!0,await new Promise(S=>setTimeout(S,3e3));break}let Ht=Pr(pe).trim().split(/[.!?]\s+/),hn=new Set(Ht);if((Ht.length>10?(Ht.length-hn.size)/Ht.length:0)>$n){yield{type:"status",content:"Response Loop Detected. Re-centering..."},Mt=!1,_n=!0,await new Promise(Le=>setTimeout(Le,3e3));break}let Vn=U.replace(_a,"").replace(Ea,"").replace(Aa,"").replace(Ca,""),Bt=Vn.toLowerCase().split(/\s+/).map(Le=>Le.replace(va,"")).filter(Le=>Le.length>0),pn=!1;if(Bt.length>=10)for(let Le=1;Le<=15;Le++){let S=Math.max(3,Math.ceil(10/Le));if(Bt.length<Le*S)continue;let V=Bt.slice(Bt.length-Le),re=V.join(" ");if(Le>1&&re===V.slice(0,Math.floor(Le/2)).join(" ").repeat(2).trim())continue;let de=!0;for(let ke=1;ke<S;ke++)if(Bt.slice(Bt.length-Le*(ke+1),Bt.length-Le*ke).join(" ")!==re){de=!1;break}if(de){pn=!0;break}}if(!pn){let Le=Vn.toLowerCase().replace(Ra,"");if(Le.length>=20)for(let S=1;S<=10;S++){let V=Math.max(5,Math.ceil(16/S));if(Le.length<S*V)continue;let re=Le.substring(Le.length-S),de=!0;for(let ke=1;ke<V;ke++)if(Le.substring(Le.length-S*(ke+1),Le.length-S*ke)!==re){de=!1;break}if(de){pn=!0;break}}}if(pn){yield{type:"status",content:"Stuttering Detected. Re-centering..."},Mt=!1,sn=!0,await new Promise(Le=>setTimeout(Le,3e3));break}}let he=qt(pe),Xe=yo(he);for(;Xe.length>gt;){yield*Ln();let U=Xe[gt],te=Date.now(),y={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,Ve=qs[y]||U.toolName,Oe=Wn(y,U.args);yield{type:"status",content:`${Ve}${Oe?` ${Oe}`:""}`};let J="";if(y==="click"){let S=ee(U.args);J=`\u2714 Clicked: ${S.intendedClickText?`${S.intendedClickText}`:""}`}else if(y==="drag"){let S=ee(U.args);J=`\u2714 Dragged: Cell ${S.fromGridId||""} \u2192 Cell ${S.toGridId||""}`}else if(y==="scroll"){let S=ee(U.args);J=`\u2714 Scrolled: ${S.direction||"down"} (${S.amount||1})`}else if(y==="keyboard_typing"){let S=ee(U.args);J=`\u2714 Typed: ${S.text?`"${S.text.length>20?S.text.substring(0,20)+"...":S.text}"`:""}`}else if(y==="key_press")J=`\u2714 Pressed Key: ${ee(U.args).key||""}`;else if(y==="recapture_screen")J="\u2714 Recaptured Screen";else if(y==="web_search"){let{query:S,limit:V=10,aiMode:re=!1}=ee(U.args);J=`${S?"\u2714":"\u2718"} ${re?"AI Search":"Searched"}: ${S?`${S}`:"No Search Query"}${re===!1&&S?` \u2192 ${V}`:""}`}else if(y==="web_scrape"){let S=ee(U.args).url||null;J=`${S?"\u2714":"\u2718"} Visited: ${S||"No Source"}`}else if(y==="view_file"){let{path:S,StartLine:V,EndLine:re,start_line:de,end_line:ke,startLine:Ye,endLine:Pe}=ee(U.args),Se=V||de||Ye,K=re||ke||Pe,oe=parseInt(Se)||1,ae=parseInt(K)||(Se?oe+800:800),qe="...",Fe=ae,Ce=(S||"").trim().toLowerCase().replaceAll("\\","/");if(Ce.startsWith("#skill"))Ce.startsWith("#skill/global/fluxflow")||Ce.startsWith("#skills/global/fluxflow")?J="\u2714 Read Documentation":J=`\u2714 Read Skill: ${Q.basename(S.replaceAll("\\","/"))}`;else{try{let xe=Q.resolve(process.cwd(),S);if(Ue.existsSync(xe)){let xt=Ue.readFileSync(xe,"utf8").split(`
|
|
758
|
+
`).length;qe=xt,!Se&&!K&&xt>800?Fe=Math.min(50,xt):Fe=Math.min(ae,xt)}}catch{}let Be=(S||"").toLowerCase(),ht=Be.endsWith(".pdf"),$e=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);ht||$e?J=`${S.length>0?"\u2714":"\u2718"} ${S?`Analyzed: ${Q.basename(S)}`:"Analyzed: File Not Found"}`:st?J=`${S.length>0?"\u2714":"\u2718"} ${S?`Processed: ${Q.basename(S)}`:"Processed: File Not Found"}`:J=`${qe!=="..."?"\u2714":"\u2718"} Read: ${S?`${Q.basename(S)} \u2192 ${qe!=="..."?`Lines ${oe} - ${Fe} of ${qe}`:"File Not Found"}`:"File Not Found"}`}}else if(y==="list_files"||y==="read_folder"){let S=y==="list_files"?"List":"Browsed",V=ee(U.args).path||null,re=ee(U.args).recurse||1;J=`${V?"\u2714":"\u2718"} ${S}: ${V?`${V==="."?`./${re>1?"*":""}`:`${V.replaceAll("\\","/")}${re>1?`${V.endsWith("/")?"*":"/*"}`:`${V.endsWith("/")?"":"/"}`}`}`:"No Folder Selected"}`}else if(y==="write_file"||y==="update_file"){let S=y==="write_file"?"Created":"Edited",V=ee(U.args).path||null;J=`${V?"\u2714":"\u2718"} ${S}: ${V.replaceAll("\\","/")||"No File Changes"}`}else if(y==="write_pdf"){let S=ee(U.args).path||null;J=`${S?"\u2714":"\u2718"} Generated: ${S.replaceAll("\\","/")||"No PDF Generated"}`}else if(y==="write_docx"){let S=ee(U.args).path||null;J=`${S?"\u2714":"\u2718"} Generated: ${S.replaceAll("\\","/")||"No Docx Generated"}`}else if(y==="file_map"){let S=ee(U.args).path;J=`${S?"\u2714":"\u2718"} Indexed: ${S.replaceAll("\\","/")?""+S:"File Not Found"}`}else if(y.toLowerCase()==="search_keyword"||y.toLowerCase()==="todo")J="";else if(y.toLowerCase()==="generate_image"){let{path:S,outputPath:V,output:re}=ee(U.args);J=`\u2714 Generated: ${S||V||re||"generated_image.png"}`}else if(y==="invoke_sync"||y==="InvokeSync"){let S=Wn(y,U.args);J=`\u2714 Called Generalist${S?`: ${S}`:""}`}else if(y==="Invoke"||y==="InvokeAsync"||y==="invoke"){let S=Wn(y,U.args);J=`\u2714 Started Generalist${S?`: ${S}`:""}`}else if(y==="get_progress"||y==="GetProgress"){let S=Wn(y,U.args);J=`\u2714 Checked${S?`: ${S}`:""}`}else if(y==="cancel"){let S=Wn(y,U.args);J=`\u{1F6C7} Cancelled${S?`: ${S}`:""}`}else if(y==="steer"||y==="Steer"){let S=Wn(y,U.args);J=`\u2714 Steered${S?`: ${S}`:""}`}else if(y==="EmergencyRollback"){let{method:S}=ee(U.args);J=S==="forceRevert"?"":"\u2714 Rollback Point Checked"}else if(y==="await"||y==="Await"){let{time:S,timeout:V}=ee(U.args),re=parseFloat(V||S)||0;re||(re=120);let de=Pe=>{if(Pe>=60){let Se=Math.floor(Pe/60),K=Pe%60;return`${Se}m${K>0?` ${K}s`:""}`}return`${Pe}s`},ke=["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"];J=`\u2714 ${ke[Math.floor(Math.random()*ke.length)]} \u2192 ${de(re)}`}else y==="Answer"||y==="answer"?J="\u2714 Resolved Sub-Agent Query":y==="exec_command"||y==="ask"?J="":J=`Executed: ${U.toolName}`;if(yield*Ln(),y==="exec_command"){let{command:S}=ee(U.args);if(S&&n.systemSettings&&n.systemSettings.allowExternalAccess===!1){let V=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],re=Q.resolve(process.cwd()).substring(0,3).toLowerCase(),de=K=>{let oe=[],ae="",qe=null;for(let Fe=0;Fe<K.length;Fe++){let Ce=K[Fe];qe?(Ce===qe&&(qe=null),ae+=Ce):Ce==='"'||Ce==="'"?(qe=Ce,ae+=Ce):Ce==="&"&&K[Fe+1]==="&"||Ce==="|"&&K[Fe+1]==="|"?(ae.trim()&&(oe.push(ae.trim()),ae=""),Fe++):Ce===";"||Ce==="|"||Ce==="&"?ae.trim()&&(oe.push(ae.trim()),ae=""):ae+=Ce}return ae.trim()&&oe.push(ae.trim()),oe},ke=K=>{let oe=[],ae="",qe=null;for(let Fe=0;Fe<K.length;Fe++){let Ce=K[Fe];qe?(Ce===qe&&(qe=null),ae+=Ce):Ce==='"'||Ce==="'"?(qe=Ce,ae+=Ce):/\s/.test(Ce)?ae&&(oe.push(ae),ae=""):ae+=Ce}return ae&&oe.push(ae),oe},Ye=K=>{let oe=K.replace(/^['"]|['"]$/g,"").trim();return!oe||process.platform==="win32"&&/^\/[a-zA-Z0-9?]+$/.test(oe)?!1:V.some(ae=>{if(ae.source==="[a-zA-Z]:[\\\\\\/]"){let qe=oe.match(/[a-zA-Z]:[\\\/]/i);return qe&&qe[0].toLowerCase()!==re}return ae.test(oe)})};if(de(S).some(K=>{let oe=ke(K);if(oe.length===0)return!1;let ae=oe[0].replace(/^['"]|['"]$/g,"").toLowerCase();if(["echo","printf","write-output"].includes(ae)){let Fe=!1;return oe.some(Ce=>{let Gt=Ce.replace(/^['"]|['"]$/g,"");if(Gt===">"||Gt===">>"||Gt==="<")return Fe=!0,!1;if(Gt.startsWith(">")||Gt.startsWith("<")){let Be=Gt.replace(/^[><]+/,"");return Ye(Be)}return Fe?(Fe=!1,Ye(Ce)):!1})}return oe.some(Fe=>Ye(Fe))})){let K='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(oe=>setTimeout(oe,50)),n.onExecChunk&&n.onExecChunk(`ERROR: ${K}`),await new Promise(oe=>setTimeout(oe,50)),n.onExecEnd&&n.onExecEnd(),_e.push({role:"user",text:`[TOOL RESULT]: ERROR: ${K}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${K}`},gt++;continue}}n.onExecStart&&n.onExecStart(S||"No Command"),yield{type:"exec_start"}}let an=ee(U.args),$n=an.path||an.targetPath||null;if($n){let S=n.systemSettings&&n.systemSettings.allowExternalAccess===!1,V=Q.resolve($n),re=Q.resolve(process.cwd());if(S&&!V.startsWith(re)){let de="Access Denied. You are not allowed to access files outside the current workspace.";if(y==="write_file"||y==="update_file"){let Ye=`\u2718 ${y==="write_file"?"Write Canceled":"Edit Canceled"}: ${an.path||"..."}`,Pe=115;process.stdout.isTTY&&(Pe=process.stdout.columns-5||120);let Se=Math.min(Ye.length+4,Pe),K=`${Ye.padEnd(Se-2).substring(0,Se-2)}`;yield{type:"visual_feedback",content:Yt(`${Je?`
|
|
759
759
|
`:""}${K}
|
|
760
|
-
`)},Je=!1}_e.push({role:"user",text:`[TOOL RESULT]: ERROR: ${de}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${de}`},gt++;continue}}if(n.onToolApproval&&(y==="write_file"||y==="update_file"||y==="exec_command")){let V=n.systemSettings||{},re=V.autoExec,de=null,ke=!1,Ye=!1,Pe=!1;if(y==="exec_command"){let{command:Be}=ee(U.args),ht=(Be||"").trim(),$e=(jt,xt)=>{if(!xt)return!1;let Zt=xt.split(",").map(Vt=>Vt.trim().toLowerCase()).filter(Boolean),lt=jt.toLowerCase();return Zt.some(Vt=>lt.startsWith(Vt))},st=$e(ht,V.alwaysAskCommands),xe=$e(ht,V.autoApproveCommands);if(Ye=$e(ht,V.autoDisallowCommands),st?ke=!0:(xe||V.autoApproveGit&&/^git\s+commit\b/i.test(ht))&&(de="allow"),!ke&&!de){if(V.networkAccess===!1){let xt=ht.trim().replace(/\s+/g," ").replace(/^['"]+|['"]+$/g,"").toLowerCase().split(" "),lt=xt[0].split("/").pop().split("\\").pop().replace(/\.exe$/,""),Vt=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;Vt.has(lt)&&(ct=!0);let rt=ln=>xt.slice(1).some(cn=>ln.includes(cn)),dt=ln=>{let cn=xt.findIndex(yn=>ln.includes(yn)),Kn=xt.findIndex(yn=>["run","exec","test"].includes(yn));return cn!==-1&&!(Kn!==-1&&Kn<cn)};lt==="git"&&rt(["clone","pull","push","fetch"])&&(ct=!0),lt==="go"&&rt(["get","install"])&&(ct=!0),lt==="npm"&&dt(["install","i","update","add"])&&(ct=!0),lt==="yarn"&&dt(["add","install","upgrade"])&&(ct=!0),lt==="pnpm"&&dt(["add","install","update"])&&(ct=!0),lt==="bun"&&dt(["add","install","update"])&&(ct=!0),lt==="deno"&&rt(["install","add"])&&(ct=!0),lt==="pip"&&rt(["install","download"])&&(ct=!0),lt==="pip3"&&rt(["install","download"])&&(ct=!0),lt==="cargo"&&rt(["install","add"])&&(ct=!0),["bash","sh","zsh","fish"].includes(lt)&&rt(["-c"])&&(ct=!0),lt==="cmd"&&rt(["/c"])&&(ct=!0),ct&&(de="deny",Pe=!0)}!de&&Ye&&(de="deny")}!ke&&!de&&re&&(de="allow")}else re&&(de="allow");let Se=de,K="";de==="deny"&&(Pe?K="network":Ye?K="settings":K="prohibited");let oe=!1,ae="",qe=[],Fe=0,Ce=!1,Gt="";if(!Se){if(y==="write_file"||y==="update_file")try{let $e=ee(U.args),{path:st}=$e;if(st){let xe=
|
|
760
|
+
`)},Je=!1}_e.push({role:"user",text:`[TOOL RESULT]: ERROR: ${de}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${de}`},gt++;continue}}if(n.onToolApproval&&(y==="write_file"||y==="update_file"||y==="exec_command")){let V=n.systemSettings||{},re=V.autoExec,de=null,ke=!1,Ye=!1,Pe=!1;if(y==="exec_command"){let{command:Be}=ee(U.args),ht=(Be||"").trim(),$e=(jt,xt)=>{if(!xt)return!1;let Zt=xt.split(",").map(Vt=>Vt.trim().toLowerCase()).filter(Boolean),lt=jt.toLowerCase();return Zt.some(Vt=>lt.startsWith(Vt))},st=$e(ht,V.alwaysAskCommands),xe=$e(ht,V.autoApproveCommands);if(Ye=$e(ht,V.autoDisallowCommands),st?ke=!0:(xe||V.autoApproveGit&&/^git\s+commit\b/i.test(ht))&&(de="allow"),!ke&&!de){if(V.networkAccess===!1){let xt=ht.trim().replace(/\s+/g," ").replace(/^['"]+|['"]+$/g,"").toLowerCase().split(" "),lt=xt[0].split("/").pop().split("\\").pop().replace(/\.exe$/,""),Vt=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;Vt.has(lt)&&(ct=!0);let rt=ln=>xt.slice(1).some(cn=>ln.includes(cn)),dt=ln=>{let cn=xt.findIndex(yn=>ln.includes(yn)),Kn=xt.findIndex(yn=>["run","exec","test"].includes(yn));return cn!==-1&&!(Kn!==-1&&Kn<cn)};lt==="git"&&rt(["clone","pull","push","fetch"])&&(ct=!0),lt==="go"&&rt(["get","install"])&&(ct=!0),lt==="npm"&&dt(["install","i","update","add"])&&(ct=!0),lt==="yarn"&&dt(["add","install","upgrade"])&&(ct=!0),lt==="pnpm"&&dt(["add","install","update"])&&(ct=!0),lt==="bun"&&dt(["add","install","update"])&&(ct=!0),lt==="deno"&&rt(["install","add"])&&(ct=!0),lt==="pip"&&rt(["install","download"])&&(ct=!0),lt==="pip3"&&rt(["install","download"])&&(ct=!0),lt==="cargo"&&rt(["install","add"])&&(ct=!0),["bash","sh","zsh","fish"].includes(lt)&&rt(["-c"])&&(ct=!0),lt==="cmd"&&rt(["/c"])&&(ct=!0),ct&&(de="deny",Pe=!0)}!de&&Ye&&(de="deny")}!ke&&!de&&re&&(de="allow")}else re&&(de="allow");let Se=de,K="";de==="deny"&&(Pe?K="network":Ye?K="settings":K="prohibited");let oe=!1,ae="",qe=[],Fe=0,Ce=!1,Gt="";if(!Se){if(y==="write_file"||y==="update_file")try{let $e=ee(U.args),{path:st}=$e;if(st){let xe=Q.resolve(process.cwd(),st),jt=rt=>rt?rt.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,dt=>dt.toUpperCase()):"",xt=jt(xe),Zt="",lt=!1,Vt=await Fn(),ct=jt(Vt?.file_focused);if(Vt&&ct===xt&&Vt.full_content?(Zt=Vt.full_content,lt=!0):Ue.existsSync(xe)&&(Zt=Ue.readFileSync(xe,"utf8"),lt=!0),ae=Zt,await vo.recordFileChange(xe,Zt),lt){let rt=Zt;if(y==="write_file"){let dt=$e.content||$e.newContent||"";rt=dt.endsWith(`
|
|
761
761
|
`)?dt:dt+`
|
|
762
|
-
`,Gt=rt}else{let{patchPairs:dt,allowMultiple:ln,error:cn}=fi($e);if(cn){let St=`[TOOL RESULT]: ERROR: ${cn}`;_e.push({role:"user",text:St}),await vt("toolFailure"),n.onToolResult&&n.onToolResult("failure",y),yield{type:"tool_result",content:St,toolName:y},gt++;continue}let Kn=$e.allowMultiple!==void 0?$e.allowMultiple===!0||String($e.allowMultiple).toLowerCase()==="true":ln;Fe=dt.length;let yn=ui(Zt,dt,{allowMultiple:Kn});rt=yn.content,Gt=rt,qe=yn.results;let To=qe.filter(St=>St.success),Tt=qe.filter(St=>!St.success);if(To.length===0){let St=`[TOOL RESULT]: ERROR: Failed to apply patches to [${
|
|
762
|
+
`,Gt=rt}else{let{patchPairs:dt,allowMultiple:ln,error:cn}=fi($e);if(cn){let St=`[TOOL RESULT]: ERROR: ${cn}`;_e.push({role:"user",text:St}),await vt("toolFailure"),n.onToolResult&&n.onToolResult("failure",y),yield{type:"tool_result",content:St,toolName:y},gt++;continue}let Kn=$e.allowMultiple!==void 0?$e.allowMultiple===!0||String($e.allowMultiple).toLowerCase()==="true":ln;Fe=dt.length;let yn=ui(Zt,dt,{allowMultiple:Kn});rt=yn.content,Gt=rt,qe=yn.results;let To=qe.filter(St=>St.success),Tt=qe.filter(St=>!St.success);if(To.length===0){let St=`[TOOL RESULT]: ERROR: Failed to apply patches to [${Q.basename(xe)}].
|
|
763
763
|
${Tt.map(no=>` \u2022 ${no.error}`).join(`
|
|
764
|
-
`)}`,Yn=`\u2714 Edited: ${
|
|
765
|
-
`:""}${So}`)},Je=!1,_e.push({role:"user",text:St}),await vt("toolFailure"),n.onToolResult&&n.onToolResult("failure",y),yield{type:"tool_result",content:St,toolName:y},gt++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${
|
|
764
|
+
`)}`,Yn=`\u2714 Edited: ${Q.basename(xe.replaceAll("\\","/"))}`,to=115;process.stdout.isTTY&&(to=process.stdout.columns-5||120);let qn=Math.min(Yn.length+4,to),So=`${Yn.padEnd(qn-2).substring(0,qn-2)}`;yield{type:"visual_feedback",content:Yt(`${Je?`
|
|
765
|
+
`:""}${So}`)},Je=!1,_e.push({role:"user",text:St}),await vt("toolFailure"),n.onToolResult&&n.onToolResult("failure",y),yield{type:"tool_result",content:St,toolName:y},gt++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${Q.basename(xe)}`},Us(xe,Zt,rt),oe=!0,await new Promise(dt=>setTimeout(dt,50))}else if(y==="write_file"){let rt=$e.content||$e.newContent||"",dt=rt.endsWith(`
|
|
766
766
|
`)?rt:rt+`
|
|
767
|
-
`;Gt=dt,Ue.existsSync(xe)||(Ce=!0,Ue.mkdirSync(
|
|
767
|
+
`;Gt=dt,Ue.existsSync(xe)||(Ce=!0,Ue.mkdirSync(Q.dirname(xe),{recursive:!0}),Ue.writeFileSync(xe,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${Q.basename(xe)}`},Us(xe,"",dt),oe=!0,await new Promise(ln=>setTimeout(ln,50))}}}catch($e){console.error("Simulation/Diff Error:",$e)}let Be=null;Bs($e=>{Be=$e});let ht=n.onToolApproval;if(Se=await new Promise(async $e=>{let st=setInterval(()=>{Be&&(ts.onIDEApproval&&ts.onIDEApproval(Be),clearInterval(st),$e(Be))},100);try{let xe=await ht(y,U.args);clearInterval(st),$e(xe)}catch{clearInterval(st),$e("deny")}}),Bs(null),y==="write_file"||y==="update_file"){let{path:$e}=ee(U.args);if($e){let st=Q.resolve(process.cwd(),$e);if(Cr(st,Se),Se==="deny"&&Ce&&Ue.existsSync(st))try{Ue.unlinkSync(st)}catch{}}}Se==="deny"&&(K="user")}if(Se==="allow"&&oe&&Go()){let{path:Be}=ee(U.args),ht=Q.resolve(process.cwd(),Be),$e=Tt=>Tt?Q.resolve(Tt).replace(/\\/g,"/").toLowerCase():"",st=await Fn(),xe="";if(st&&st.file_focused&&$e(st.file_focused)===$e(ht)&&st.full_content&&(xe=st.full_content),!xe&&Ue.existsSync(ht)){let Tt=Ue.readFileSync(ht,"utf8");Tt&&(xe=Tt)}!xe&&Gt&&(xe=Gt),(xe||Ce)&&Ue.writeFileSync(ht,xe,"utf8");let jt=xe.split(/\r?\n/),xt=jt.length,Zt=Buffer.byteLength(xe,"utf8"),lt="";ae&&(lt=`Old File contents:
|
|
768
768
|
${ae.split(/\r?\n/).map((St,Yn)=>`${Yn+1} | ${St}`).join(`
|
|
769
769
|
`)}
|
|
770
770
|
|
|
@@ -795,9 +795,9 @@ ${to}- Content Preview:
|
|
|
795
795
|
${qn}`}let dt=`${Be?"\u2714":"\u2718"} ${y==="write_file"?"Created":"Edited"}: ${Be.replaceAll("\\","/")||"No File Changes"}`,ln=115;process.stdout.isTTY&&(ln=process.stdout.columns-5||120);let cn=Math.min(dt.length+4,ln),Kn=`${dt.padEnd(cn-2).substring(0,cn-2)}`;yield{type:"visual_feedback",content:Yt(`${Je?`
|
|
796
796
|
`:""}${Kn}`)},Je=!1;let yn=Date.now();He=yn,yield{type:"tool_time",content:yn-te};let To=`[TOOL RESULT]: ${ct}`;_e.push({role:"user",text:To}),Sn=!0,await vt("toolSuccess"),n.onToolResult&&n.onToolResult("success",y),yield{type:"tool_result",content:ct,aiContent:To,toolName:y},gt++;continue}if(Se==="deny"){let Be=`Permission Denied: Prohibited ${y==="exec_command"?"Command":"file edit"}.`;if(K==="user"?Be="Permission Denied by User":K==="settings"?Be="Permission Denied by User Policy":K==="network"?Be="Permission Denied: Sandbox Network Access Disabled by User Policy.":K==="prohibited"&&y==="exec_command"&&(Be="Permission Denied: Prohibited Command in User Policy"),y==="write_file"||y==="update_file"){let $e=`\u2718 ${y==="write_file"?"Write Cancelled":"Edit Denied"}: ${ee(U.args).path.replaceAll("\\","/")||"..."}`,st=115;process.stdout.isTTY&&(st=process.stdout.columns-5||120);let xe=Math.min($e.length+4,st),jt=`${$e.padEnd(xe-2).substring(0,xe-2)}`,xt=` ${" ".repeat(xe)} `;yield{type:"visual_feedback",content:Yt(`${Je?`
|
|
797
797
|
`:""}${jt}
|
|
798
|
-
`)},Je=!1}y==="exec_command"&&(await new Promise(ht=>setTimeout(ht,50)),n.onExecChunk&&n.onExecChunk(`ERROR: ${Be}`),await new Promise(ht=>setTimeout(ht,50)),n.onExecEnd&&n.onExecEnd()),_e.push({role:"user",text:`[TOOL RESULT]: DENIED: ${Be}`}),yield{type:"tool_result",content:`[TOOL RESULT]: DENIED: ${Be}`},await vt("toolDenied"),n.onToolResult&&n.onToolResult("denied",y),gt++;continue}}if(
|
|
799
|
-
`:""}${ke}${
|
|
800
|
-
`}`}`)},Je=!1}if(He>0){let S=Date.now()-He,V=Math.max(0,1e3-S);V>0&&await new Promise(re=>setTimeout(re,V))}let An={chatId:g,history:t,onChunk:S=>n.onExecChunk?n.onExecChunk(S):null,onAskUser:n.onAskUser,systemSettings:n.systemSettings,mode:a,isMultiModal:ut(ye),onVisualFeedback:n.onVisualFeedback,onSubagentUpdate:n.onSubagentUpdate,onTokenChunk:n.onTokenChunk,modelName:ye,aiProvider:n.aiProvider,apiKey:n.apiKey,onUsage:n.onUsage};if(y==="write_file"||y==="update_file")try{let{path:S}=ee(U.args);if(S){let V=
|
|
798
|
+
`)},Je=!1}y==="exec_command"&&(await new Promise(ht=>setTimeout(ht,50)),n.onExecChunk&&n.onExecChunk(`ERROR: ${Be}`),await new Promise(ht=>setTimeout(ht,50)),n.onExecEnd&&n.onExecEnd()),_e.push({role:"user",text:`[TOOL RESULT]: DENIED: ${Be}`}),yield{type:"tool_result",content:`[TOOL RESULT]: DENIED: ${Be}`},await vt("toolDenied"),n.onToolResult&&n.onToolResult("denied",y),gt++;continue}}if(J){let S=115;process.stdout.isTTY&&(S=process.stdout.columns-5||120);let V=await s(),re=!1;V&&(re=V.trim().length>0);let de=Math.min(J.length+4,S),ke=`${J.padEnd(de-2).substring(0,de-2)}`;yield{type:"visual_feedback",content:Yt(`${Je?`
|
|
799
|
+
`:""}${ke}${J.includes("\u2714")&&(J.includes("Created")||J.includes("Edited"))?"":`${re?"":`
|
|
800
|
+
`}`}`)},Je=!1}if(He>0){let S=Date.now()-He,V=Math.max(0,1e3-S);V>0&&await new Promise(re=>setTimeout(re,V))}let An={chatId:g,history:t,onChunk:S=>n.onExecChunk?n.onExecChunk(S):null,onAskUser:n.onAskUser,systemSettings:n.systemSettings,mode:a,isMultiModal:ut(ye),onVisualFeedback:n.onVisualFeedback,onSubagentUpdate:n.onSubagentUpdate,onTokenChunk:n.onTokenChunk,modelName:ye,aiProvider:n.aiProvider,apiKey:n.apiKey,onUsage:n.onUsage};if(y==="write_file"||y==="update_file")try{let{path:S}=ee(U.args);if(S){let V=Q.resolve(process.cwd(),S),re=await Fn();re&&re.file_focused===V&&re.full_content&&(An.forcedContent=re.full_content)}}catch{}et.push(y);let De=await mo(y,U.args,An);if((y==="write_file"||y==="update_file")&&De.startsWith("SUCCESS")){let{path:S}=ee(U.args);if(S){let V=Q.resolve(process.cwd(),S);Ar(V)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let Ft=Date.now();He=Ft,yield{type:"tool_time",content:Ft-te},j=Ft;let Ht=null;if(typeof De=="object"&&De.binaryPart&&(Ht=De.binaryPart,De=De.text),y==="search_keyword"){let{keyword:S,path:V}=ee(U.args),re=typeof De=="string"&&De.startsWith("[GLOB]");re&&(De=De.slice(6).trimStart());let de=typeof De=="string"&&De.startsWith("[DIR]");de&&(De=De.slice(5).trimStart());let ke=0;if(De){let Fe=De.match(/Found (\d+) match/i);Fe&&(ke=parseInt(Fe[1]))}let Ye=(V||"").trim().toLowerCase().replaceAll("\\","/"),Pe=Ye==="#doc"||Ye==="#docs"||Ye==="#documentation"||Ye.includes("#skill/global/fluxflow")||Ye.includes("#skills/global/fluxflow"),Se,K=115;process.stdout.isTTY&&(K=process.stdout.columns-5||120);let oe=Math.max(10,K/2);if(Pe)Se=`${S?"\u2714":"\u2718"} Searched Documentation`;else{let Fe=V?V.replace(/[\/\\]+$/,""):null,Ce=Fe&&Fe!=="."?`"${re?V:de?`${Fe}/*`:Fe}"`:"./";Se=`${S?"\u2714":"\u2718"} Searched: "${S?S.length>K/2?`${S.slice(oe)}...`:S:""}" in ${Ce.replaceAll("\\","/")} \u2192 ${ke} Match${ke===1?"":"es"}`}let ae=Math.min(Se.length+4,K),qe=`${Se.padEnd(ae-2).substring(0,ae-2)}`;yield{type:"visual_feedback",content:Yt(`${Je?`
|
|
801
801
|
`:""}${qe}
|
|
802
802
|
`)},Je=!1}if(y==="EmergencyRollback"){let{method:S}=ee(U.args);if(S==="forceRevert"){let V=0;if(De){let oe=De.match(/Total\s*:\s*(\d+)/i);oe&&(V=parseInt(oe[1]))}let de=De&&De.startsWith("ERROR:")?"\u2718 Emergency Rollback Failed":`\u2714 Emergency Rollback \u2192 ${V} file${V===1?"":"s"} processed`,ke=115;process.stdout.isTTY&&(ke=process.stdout.columns-5||120);let Ye=await s(),Pe=!1;Ye&&(Pe=Ye.trim().length>0);let Se=Math.min(de.length+4,ke),K=`${de.padEnd(Se-2).substring(0,Se-2)}`;yield{type:"visual_feedback",content:Yt(`${Je?`
|
|
803
803
|
`:""}${K}${Pe?"":`
|
|
@@ -814,13 +814,13 @@ ${qn}`}let dt=`${Be?"\u2714":"\u2718"} ${y==="write_file"?"Created":"Edited"}: $
|
|
|
814
814
|
`)}
|
|
815
815
|
[SYSTEM NOTE]: Content verified and persisted to disk. Full preview omitted to conserve context.`}else pn=`[TOOL RESULT]: ${Bt}`;_e.push({role:"user",text:pn,binaryPart:Ht}),Sn=!0;let Le=`[TOOL RESULT]: ${De.replaceAll(`[[VERIFIED]]
|
|
816
816
|
`,"").replaceAll(`
|
|
817
|
-
[[/VERIFIED]]`,"")||""}`;(y==="view_file"||y==="web_scrape"||y==="file_map")&&(Le=`[TOOL RESULT]: ${
|
|
817
|
+
[[/VERIFIED]]`,"")||""}`;(y==="view_file"||y==="web_scrape"||y==="file_map")&&(Le=`[TOOL RESULT]: ${J} (Context Locked for UI Clarity)`),yield{type:"tool_result",content:Le,aiContent:pn,binaryPart:Ht,toolName:y},y==="memory"&&De.includes("SUCCESS")&&(yield{type:"memory_updated"}),gt++}if(i==="Google"&&rn&&Date.now()-cs>=150){yield*Ln();let U=Zn(rn);for(let te of U)yield te;rn="",cs=Date.now()}}D.usageMetadata&&(gn=D.usageMetadata),gn&&(yield{type:"liveTokens",content:gn.totalTokenCount})}if(ce&&(ce=!1,Lt?tt+="</think>":(pe+="</think>",i==="Google"?rn+="</think>":yield{type:"text",content:"</think>"})),Lt&&tt.length>0){let D=0,ne=Math.min(yt.length,tt.length);for(let W=ne;W>0;W--)if(yt.endsWith(tt.substring(0,W))){D=W;break}let B=tt.substring(D);if(B){let Te=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(yt)?B.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):B.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(pe+=Te,i==="Google")rn+=Te;else{yield*Ln();let be=Zn(Te);for(let he of be)yield he}}Lt=!1,tt=""}if(yield*Ln(),bt)break;let eo=(pe||"").trim(),Jr=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(eo.toLowerCase())||/\[\[END\]\]/i.test(eo.toLowerCase()),Xr=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(eo.toLowerCase()),Qr=_e.length>0||ze!==null,ds=qt(eo).trim(),Zr=/(\p{Emoji_Presentation}|\p{Extended_Pictographic})$/u.test(ds),ea=/([.!?"'*_`|\]\)”’~~]+|\s|`{3}|[\u200B-\u200D\uFEFF])$/u.test(ds.trim()),ta=/[.!?}"'`’“”]$|```$/s.test(ds)||ea||Zr;!Jr&&!Xr&&!Qr&&eo.length>0,it=!0,await vt("agent",i)}catch(we){if(bt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
|
|
818
818
|
|
|
819
|
-
\x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(String(we).includes("Incomplete JSON segment at the end")){ce&&(ce=!1,Lt?tt+="</think>":(pe+="</think>",yield{type:"text",content:"</think>"})),it=!0,await vt("agent",i);break}if(ce&&(ce=!1,Lt?tt+="</think>":pe+="</think>"),Lt&&tt.length>0){let Nt=0,At=Math.min(yt.length,tt.length);for(let Dt=At;Dt>0;Dt--)if(yt.endsWith(tt.substring(0,Dt))){Nt=Dt;break}let kt=tt.substring(Nt);if(kt){let mt=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(yt)?kt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):kt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");mt&&(pe+=mt)}Lt=!1,tt=""}let
|
|
819
|
+
\x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(String(we).includes("Incomplete JSON segment at the end")){ce&&(ce=!1,Lt?tt+="</think>":(pe+="</think>",yield{type:"text",content:"</think>"})),it=!0,await vt("agent",i);break}if(ce&&(ce=!1,Lt?tt+="</think>":pe+="</think>"),Lt&&tt.length>0){let Nt=0,At=Math.min(yt.length,tt.length);for(let Dt=At;Dt>0;Dt--)if(yt.endsWith(tt.substring(0,Dt))){Nt=Dt;break}let kt=tt.substring(Nt);if(kt){let mt=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(yt)?kt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):kt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");mt&&(pe+=mt)}Lt=!1,tt=""}let X=we instanceof Error?(()=>{try{return JSON.parse(JSON.parse(we.message).error.message).error.message}catch{return String(we)}})():String(we),$t=new Date().toLocaleString(),It=Q.join(Cn,"agent");Ue.existsSync(It)||Ue.mkdirSync(It,{recursive:!0}),Ue.appendFileSync(Q.join(It,"error.log"),`ERROR [${$t}]: ${X}
|
|
820
820
|
|
|
821
821
|
----------------------------------------------------------------------
|
|
822
822
|
|
|
823
|
-
`);let Et=we.status||we.statusCode||we.code,Xt=String(we).includes("replicas at capacity");if(!(Et&&(Et>=500&&Et<600||Et===408||Et===429||Xt)||!Et&&(/status[ :]+(5\d\d|408|429)/i.test(String(we))||/code[ :]+(5\d\d|408|429)/i.test(String(we))||/(500|503|408|429)/.test(String(we))))){if(ot<nn-3)throw we;yield{type:"text",content:
|
|
823
|
+
`);let Et=we.status||we.statusCode||we.code,Xt=String(we).includes("replicas at capacity");if(!(Et&&(Et>=500&&Et<600||Et===408||Et===429||Xt)||!Et&&(/status[ :]+(5\d\d|408|429)/i.test(String(we))||/code[ :]+(5\d\d|408|429)/i.test(String(we))||/(500|503|408|429)/.test(String(we))))){if(ot<nn-3)throw we;yield{type:"text",content:X},yield{type:"status",content:"Error Occured"}}if(pe.trim().length>0||at>1)if(at<=nn){at++;let Nt=Math.min(1e3*Math.pow(2,at-1),24e3);if(pe.trim().length>0){r.push({role:"agent",text:pe});let At=`[system]
|
|
824
824
|
- seamless continuation: resume immediately. pick up from last words with zero gap/disruption
|
|
825
825
|
- no repetition: do not repeat any text already written
|
|
826
826
|
- no re-think: do not restart or open <think> if reasoning already started. continue the thinking and close thinking block </think> before chat output
|
|
@@ -829,16 +829,16 @@ ${qn}`}let dt=`${Be?"\u2714":"\u2718"} ${y==="write_file"?"Created":"Edited"}: $
|
|
|
829
829
|
|
|
830
830
|
${At}`}):r.push(kt)}):r.push({role:"user",text:At}),yt+=pe}for(let At=Nt/1e3;At>0&&!bt;At--)yield{type:"status",content:`Error Occured. Recovering Stream (${at}/${nn}) [Retrying in ${At.toFixed(0)}s]...`},await new Promise(kt=>setTimeout(kt,1e3));yield{type:"status",content:"Error Occured. Recovering Stream..."}}else throw new Error(`Stream collapsed too many times. (Failed to resolve ${nn} times)
|
|
831
831
|
Error log can be found in \`/export logs\``);else if(ot<=nn){ot++,at=1,yt="";let Nt=Math.min(1e3*Math.pow(2,ot-1),32e3),At=.8+Math.random()*.4,kt=Math.round(Nt*At);Qn=!0,yield{type:"status",content:`Trying to reach ${e} (${ot}/${nn}) [Retrying in ${(kt/1e3).toFixed(0)}s]`};for(let Dt=kt/1e3;Dt>0&&!bt;Dt--)yield{type:"status",content:`Trying to reach ${e} (${ot}/${nn}) [Retrying in ${Dt.toFixed(0)}s]`},await new Promise(mt=>setTimeout(mt,1e3));yield{type:"status",content:`Trying to reach ${e}`}}else throw new Error(`Model ${e} cannot be reached. (Failed ${nn} times)
|
|
832
|
-
Error log can be found in \`/export logs\``)}}if(gn){let ce=gn.totalTokenCount||0,we=gn.cachedContentTokenCount||0,
|
|
833
|
-
`),we=qt(ce).trim();yield{type:"interactive_turn_finished",data:{agentText:p,fullAgentTextRaw:ce,history:[...r],needTitle:L}},r.length>0&&r[r.length-1].role==="agent"?r[r.length-1].text=we:r.push({role:"agent",text:we}),r.forEach(
|
|
832
|
+
Error log can be found in \`/export logs\``)}}if(gn){let ce=gn.totalTokenCount||0,we=gn.cachedContentTokenCount||0,X=(gn.candidatesTokenCount||0)+(i==="Google"&&gn.thoughtsTokenCount||0);await Ut("tokens",ce,i,ye),we>0&&await Ut("cachedTokens",we,i,ye),X>0&&await Ut("candidateTokens",X,i,ye),yield{type:"usage",content:gn}}pe=Br(pe),ls.push(pe);let En=qt(pe),Dn=Pr(pe),mn=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(Dn.toLowerCase())||/\[\[END\]\]/i.test(Dn.toLowerCase())||!0,za=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(Dn.toLowerCase()),Ja=gt>0;yield{type:"status",content:"Thinking"};let Kr=Ga(pe,/(\[\s*(turn\s*:)?\s*(continue|finish)\s*\]|\[\[END\]\])/gi,"").trim(),On=(mn||_e.length===0)&&!Mt&&!sn&&!_n;if(On=_e.length===0?On:!1,On=Pt||wo?!1:On,pe&&pe.trim().endsWith('")]')&&_e.length===0&&(On=!1),On){li=!0;let ce=ls.join(`
|
|
833
|
+
`),we=qt(ce).trim();yield{type:"interactive_turn_finished",data:{agentText:p,fullAgentTextRaw:ce,history:[...r],needTitle:L}},r.length>0&&r[r.length-1].role==="agent"?r[r.length-1].text=we:r.push({role:"agent",text:we}),r.forEach(X=>{if(X.role==="user"&&X.text&&(X.text=X.text.replace(/\n\[COMPILE ERROR\][\s\S]*?\[\/ERROR\]/g,""),X.text=X.text.replaceAll(`
|
|
834
834
|
|
|
835
835
|
[system] user question. resolve this specific query within '[ANSWER] ... [/ANSWER]' concisely, naturally [/system]
|
|
836
836
|
`,"").replaceAll(`[system] user question. resolve this specific query within '[ANSWER] ... [/ANSWER]' concisely, naturally
|
|
837
837
|
**strictly follow thinking policy as high priority. do not start a response without <think>...</think>** [/system]
|
|
838
838
|
`,"").replaceAll(`[system] **strictly follow thinking policy as high priority. do not start a response without <think>...</think>** [/system]
|
|
839
|
-
`,"").replaceAll(/\n\[system\] WARNING, Turn Limit Impending: Step \d+\/\d+\. Wrap up quickly\/prompt user to continue & use \[\[END\]\] quickly\. \[\/system\]/g,""),
|
|
839
|
+
`,"").replaceAll(/\n\[system\] WARNING, Turn Limit Impending: Step \d+\/\d+\. Wrap up quickly\/prompt user to continue & use \[\[END\]\] quickly\. \[\/system\]/g,""),X.text=X.text.replaceAll(/\n\[system\] File Changes:\n(?:\* .+ \(created|modified|deleted\)\n)*\[\/system\]/g,""),(i==="Mistral"||i==="Google"&&e?.toLowerCase().startsWith("gemma"))&&X.text.startsWith("[TOOL RESULT]"))){let It=`
|
|
840
840
|
[system] Tool result received. Analyze output and proceed with your turn [/system]`,Et=`
|
|
841
|
-
[system] Tool result received. Analyze output and proceed with your turn. **strictly follow thinking policy. do not start a response without <think>...</think>** [/system]`;
|
|
841
|
+
[system] Tool result received. Analyze output and proceed with your turn. **strictly follow thinking policy. do not start a response without <think>...</think>** [/system]`;X.text=X.text.replaceAll(Et,"").replaceAll(It,"").trim()}}),yield{type:"status",content:"[end]"}}if(On)break;let Yr=Kr.trim()||"*Working...*";if(r.push({role:"agent",text:Yr}),_e.length>0||Sn){if(_e.length>0){let ce=_e.map(Xt=>Xt.text).join(`
|
|
842
842
|
|
|
843
843
|
`),$t=(qt(pe).replace(/\[{1,2}tool:[\s\S]*?\)\s*\]{1,2}/gi,"").match(/\[tool:/gi)||[]).length,It=_e.length+$t;if(_e.length<It){ce+=`
|
|
844
844
|
|
|
@@ -851,10 +851,10 @@ Error log can be found in \`/export logs\``)}}if(gn){let ce=gn.totalTokenCount||
|
|
|
851
851
|
${G}
|
|
852
852
|
`};let Ie=(ls.join(`
|
|
853
853
|
`)+`
|
|
854
|
-
${G}`).trim();yield{type:"interactive_turn_finished",data:{agentText:p,fullAgentTextRaw:Ie,history:[...r],needTitle:L}},yield{type:"status",content:"[end]"}}}catch(T){let k=(T instanceof Error?(()=>{try{return JSON.parse(JSON.parse(T.message).error.message).error.message}catch{return T.message||String(T)}})():String(T)).replace(/^(Error:\s*)+/i,""),E=new Date().toLocaleString(),I=
|
|
854
|
+
${G}`).trim();yield{type:"interactive_turn_finished",data:{agentText:p,fullAgentTextRaw:Ie,history:[...r],needTitle:L}},yield{type:"status",content:"[end]"}}}catch(T){let k=(T instanceof Error?(()=>{try{return JSON.parse(JSON.parse(T.message).error.message).error.message}catch{return T.message||String(T)}})():String(T)).replace(/^(Error:\s*)+/i,""),E=new Date().toLocaleString(),I=Q.join(Cn,"agent");yield{type:"text",content:`
|
|
855
855
|
|
|
856
856
|
\u2726 CRITICAL ERROR: ${k.includes("fetch failed")?"Failed to Connect. Check your Internet Connection or Wait a moment":k}
|
|
857
|
-
\u2800`},Ue.existsSync(I)||Ue.mkdirSync(I,{recursive:!0}),Ue.appendFileSync(
|
|
857
|
+
\u2800`},Ue.existsSync(I)||Ue.mkdirSync(I,{recursive:!0}),Ue.appendFileSync(Q.join(I,"error.log"),`CRITICAL ERROR [${E}]: ${T}
|
|
858
858
|
|
|
859
859
|
----------------------------------------------------------------------
|
|
860
860
|
|
|
@@ -900,7 +900,7 @@ ${_.trimEnd()}
|
|
|
900
900
|
Current Time: ${x}
|
|
901
901
|
=== END SYSTEM PROMPT ===`,L=[{role:"user",text:`Complete this task: ${e}`}],p=0,d="";for(;p<o;){let T=await hs("subagent",m);if(!T.allowed)throw new Error(T.reason||`Budget Exhausted for Provider (${m?.aiProvider||"Subagent"})`);if(bt){if(t?.taskId&&typeof Kt<"u"){let O=Kt.find($=>$.id===t.taskId);O&&(O.status="cancelled")}throw l&&l("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}if(t?.taskId&&typeof Kt<"u"){let O=Kt.find($=>$.id===t.taskId);if(O&&O.status==="cancelled")throw l&&l("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}let r=L.map(O=>({role:O.role==="user"?"user":"model",parts:[{text:O.text}]}));l&&l(`[Subagent Turn ${p+1}]...`);let k=["Fast","Low","Medium","High"],E=process.env.SUBAGENT_THINKING,I=k.includes(E)?E:"Low",P=(await ns(m,N,r,R,I)).text||"",M=Br(qt(P).trim());d=M,l&&l(`[Subagent Response]
|
|
902
902
|
${M}
|
|
903
|
-
`),L.push({role:"agent",text:M});let
|
|
903
|
+
`),L.push({role:"agent",text:M});let Z=yo(M);if(Z.length===0)break;let le=Z.filter(O=>O.toolName.toLowerCase()==="askmain"||O.toolName.toLowerCase()==="ask_main"),z=!1,ie="";for(let O of Z){if(bt){if(t?.taskId&&typeof Kt<"u"){let F=Kt.find(Y=>Y.id===t.taskId);F&&(F.status="cancelled")}throw new Error("Subagent task was cancelled.")}if(t?.taskId&&typeof Kt<"u"){let F=Kt.find(Y=>Y.id===t.taskId);if(F&&F.status==="cancelled")throw new Error("Subagent task was cancelled.")}let $=O.toolName.toLowerCase();if($==="askuser"&&($="ask"),$==="askmain"||$==="ask_main"){if(z)continue;z=!0;let F="";if(le.length===1?F=ee(le[0].args).question||le[0].args:F=le.map((Y,ue)=>{let Re=ee(Y.args);return`Q${ue+1}: ${Re.question||Y.args}`}).join(`
|
|
904
904
|
`),t.onAskMain){l&&l(`[Executing Tool] AskMain("${F}")...`);let Y=await t.onAskMain(F);l&&l(`[Tool Result]
|
|
905
905
|
Answer from Main Agent: ${Y}
|
|
906
906
|
`),ie+=`[TOOL RESULT for AskMain]: Answer from Main Agent: ${Y}
|