fluxflow-cli 4.46.1 → 4.48.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import{a as Ds}from"./chunk-HFTI3R3Q.js";import{a as Ro}from"./chunk-52STSLCN.js";import{a as en}from"./chunk-56EJGQU3.js";import{a as Bs}from"./chunk-4BLSASW6.js";import{c as Ni,g as Di,h as Ps,i as Os}from"./chunk-MKC4AVAL.js";import{b as Ls,c as $s,d as Fi,f as Ns}from"./chunk-UIL6OCU4.js";import{b as Bi,h as Fs}from"./chunk-Z5D4VQSG.js";import{a as ti}from"./chunk-6EYQQ7GQ.js";import{a as j}from"./chunk-Y5JU726N.js";import{b as Li}from"./chunk-XDY4KWTM.js";import{y as Oi}from"./chunk-U2GX6WT2.js";import{f as Co,l as Lt,n as At,p as $i,q as Ms}from"./chunk-OSSZ4LIE.js";import{b as Eo}from"./chunk-45DLFA4C.js";import{l as lt,m as ei,q as ae}from"./chunk-HTOLY3HR.js";import{c as Ot,d as co,e as Zo}from"./chunk-P5HBJA23.js";import{a as Un,b as Xo,d as wn,e as Jo,k as Xn,l as Qo,m as Mi,r as Pi,w as To,x as Ao,y as Is}from"./chunk-26BQ45XP.js";import{GoogleGenAI as ia,ThinkingLevel as Ye,HarmBlockThreshold as Gn,HarmCategory as Hn}from"@google/genai";var Us=(e=!0,n=!0)=>`
1
+ import{a as Ds}from"./chunk-HFTI3R3Q.js";import{a as Ro}from"./chunk-52STSLCN.js";import{a as Qt}from"./chunk-56EJGQU3.js";import{a as Bs}from"./chunk-4BLSASW6.js";import{c as Di,g as Fi,h as Ps,i as Os}from"./chunk-AMFNIFF3.js";import{b as Ls,c as $s,d as Bi,f as Ns}from"./chunk-UIL6OCU4.js";import{b as Ui,h as Fs}from"./chunk-Z5D4VQSG.js";import{a as ti}from"./chunk-6EYQQ7GQ.js";import{a as G}from"./chunk-Y5JU726N.js";import{b as $i}from"./chunk-XDY4KWTM.js";import{y as Li}from"./chunk-U2GX6WT2.js";import{f as Co,l as _t,n as bt,p as Ni,q as Ms}from"./chunk-OSSZ4LIE.js";import{b as Eo}from"./chunk-45DLFA4C.js";import{l as st,m as ei,q as re}from"./chunk-HTOLY3HR.js";import{c as vt,d as lo,e as Zo}from"./chunk-P5HBJA23.js";import{a as Dn,b as Xo,d as yn,e as Jo,k as Xn,l as Qo,m as Pi,r as Oi,w as To,x as Ao,y as Is}from"./chunk-26BQ45XP.js";import{GoogleGenAI as ia,ThinkingLevel as je,HarmBlockThreshold as Bn,HarmCategory as Un}from"@google/genai";var Us=(e=!0,n=!0)=>`
2
2
  To use tools, must output exactly '[action:ActionName(arg1="value1")]' structured string in chat response \u2190 no exception
3
3
 
4
4
  -- Chat Management Tools --
@@ -25,7 +25,7 @@ Usage Rules:
25
25
  - Chat title is mandatory
26
26
  - Temporary memory is mandatory
27
27
  - When called user memory, still use Temporary Memory
28
- - Must not ignore any tool calls in given context of chat between user & agent`:""}`.trim();var ni={xHigh:"Use minimal reasoning. Prefer simplest path; avoid branching; waste NO tokens overthinking",High:"Use minimal reasoning. Prefer simplest path; avoid branching; waste NO tokens overthinking",Medium:"Use minimal reasoning. Prefer simplest path; avoid branching; waste NO tokens overthinking",Minimal:"Use minimal reasoning. Prefer simplest path; avoid branching; waste NO tokens overthinking",Off:"NO thinking. Immediate response. Verify imports, tool results & system stability"};import ln from"fs";import an from"path";import La from"os";import Sn from"fs";import Wn from"path";import Zs from"fs";import Ui from"path";import{execSync as er}from"child_process";import{fileURLToPath as Ma}from"url";var Ws=`# FluxFlow CLI Startup & Flags Reference
28
+ - Must not ignore any tool calls in given context of chat between user & agent`:""}`.trim();var ni={xHigh:"Use minimal reasoning. Prefer simplest path; avoid branching; waste NO tokens overthinking",High:"Use minimal reasoning. Prefer simplest path; avoid branching; waste NO tokens overthinking",Medium:"Use minimal reasoning. Prefer simplest path; avoid branching; waste NO tokens overthinking",Minimal:"Use minimal reasoning. Prefer simplest path; avoid branching; waste NO tokens overthinking",Off:"NO thinking. Immediate response. Verify imports, tool results & system stability"};import rn from"fs";import sn from"path";import $a from"os";import xn from"fs";import Fn from"path";import Zs from"fs";import Wi from"path";import{execSync as er}from"child_process";import{fileURLToPath as Pa}from"url";var Ws=`# FluxFlow CLI Startup & Flags Reference
29
29
 
30
30
  Launch command syntax:
31
31
  fluxflow [options]
@@ -448,7 +448,7 @@ Instruction for this model ID across all providers.
448
448
 
449
449
  * On-Demand Reference System:
450
450
  * Reference: Offload deep/contexual specs to **/{SKILL.md,skill-reference-folder/*.md} & reference in SKILL.md. Saves tokens
451
- `;var oi="v4";try{let e=Ui.dirname(Ma(import.meta.url)),n=[Ui.join(e,"../../package.json"),Ui.join(e,"../package.json")],t=!1;for(let i of n)if(Zs.existsSync(i)){let o=JSON.parse(Zs.readFileSync(i,"utf8"));if(o.version){oi=o.version,t=!0;break}}if(!t)try{let i=er("fluxflow -v",{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"],timeout:2e3}).trim();i&&(i.startsWith("v")||/^\d+\.\d+/.test(i))&&(oi=i,t=!0)}catch{}if(!t)try{let i=er("curl -s --max-time 3 https://raw.githubusercontent.com/KushalRoyChowdhury/fluxflow-cli/main/package.json",{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"]}),o=JSON.parse(i);o.version&&(oi=o.version)}catch{}}catch{}var Wi={"SKILL.md":`---
451
+ `;var oi="v4";try{let e=Wi.dirname(Pa(import.meta.url)),n=[Wi.join(e,"../../package.json"),Wi.join(e,"../package.json")],t=!1;for(let i of n)if(Zs.existsSync(i)){let o=JSON.parse(Zs.readFileSync(i,"utf8"));if(o.version){oi=o.version,t=!0;break}}if(!t)try{let i=er("fluxflow -v",{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"],timeout:2e3}).trim();i&&(i.startsWith("v")||/^\d+\.\d+/.test(i))&&(oi=i,t=!0)}catch{}if(!t)try{let i=er("curl -s --max-time 3 https://raw.githubusercontent.com/KushalRoyChowdhury/fluxflow-cli/main/package.json",{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"]}),o=JSON.parse(i);o.version&&(oi=o.version)}catch{}}catch{}var Gi={"SKILL.md":`---
452
452
  name: fluxflow
453
453
  description: System Generated Documentation. Read this if asked anything regarding FluxFlow Harness
454
454
  ---
@@ -475,76 +475,76 @@ Public Docs: https://fluxflow-cli.onrender.com
475
475
 
476
476
  Default Context Length: 256k Tokens. Can be changed via ENV/In-app Settings \u2192 references/{SETTINGS,ENV}.md
477
477
 
478
- Docs missing required info? Say you are not sure enough to answer. Dont give wrong info`,"references/MODES.md":Xs,"references/PROVIDERS.md":Js,"references/PLUGINS.md":Qs,"references/STARTUP.md":Ws,"references/ENV.md":Gs,"references/COMMANDS.md":Hs,"references/SETTINGS.md":js,"references/TOOLS.md":Ks,"references/ARCHITECTURE.md":Vs,"references/SUB_AGENTS.md":Ys,"references/SECURITY.md":zs,"references/IDE.md":qs};var tr=()=>{try{let e=Wn.join(Un,"skills","fluxflow"),n=Wn.join(e,"references");if(process.env.NO_DEV==="true"||process.env.NO_DEV==="1"||process.env.NO_DEV===!0||process.env.NO_INS==="true"||process.env.NO_INS==="1"||process.env.NO_INS==="true"||!1){Sn.existsSync(e)&&Sn.rmSync(e,{recursive:!0,force:!0});return}let i=new Set(Object.keys(Wi).map(o=>Wn.normalize(o)));for(let[o,r]of Object.entries(Wi)){let c=Wn.join(e,o),a=Wn.dirname(c);Sn.existsSync(a)||Sn.mkdirSync(a,{recursive:!0});let u=r.trim()+`
479
- `,h=null;Sn.existsSync(c)&&(h=Sn.readFileSync(c,"utf8")),h!==u&&Sn.writeFileSync(c,u,"utf8")}if(Sn.existsSync(n)){let o=Sn.readdirSync(n);for(let r of o){let c=Wn.normalize(Wn.join("references",r));if(!i.has(c)){let a=Wn.join(n,r);try{Sn.rmSync(a,{recursive:!0,force:!0})}catch{}}}}}catch{}};import{WebSocket as ii}from"ws";var Ht=null,fo=!1,Pa="ws://localhost:56832",Gi=[],uo=null,Hi=null,ji=null,nr="2.0.0",dc=e=>{nr=e,or()},Ki=e=>{Hi=e},fc=e=>{ji=e},or=()=>{if(Ht||fo)return;fo=!0;let e=new ii(Pa);e.on("open",()=>{for(Ht=e,fo=!1,Ht.send(JSON.stringify({command:"version",version:nr,pid:process.pid,ppid:process.ppid,cwd:process.cwd()}));Gi.length>0;)Ht.send(JSON.stringify(Gi.shift()))}),e.on("message",n=>{try{let t=JSON.parse(n.toString());t.command==="contextResponse"&&uo?(uo(t.data),uo=null):t.command==="securityResponse"&&Hi?Hi(t.result):t.command==="inlineComplete"?Oa(t):t.command==="connectionRejected"&&ji&&ji(t)}catch{}}),e.on("error",()=>{fo=!1,Ht=null}),e.on("close",()=>{fo=!1,Ht=null})},_o=e=>{Ht&&Ht.readyState===ii.OPEN?Ht.send(JSON.stringify(e)):(Gi.push(e),fo||or())},go=()=>Ht!==null&&Ht.readyState===ii.OPEN,Oa=async e=>{let n="";try{let{generateAutoCompletion:t}=await import("./auto_completion-TLHA4FJW.js");n=await t({prefix:e.prefix||"",suffix:e.suffix||"",fileName:e.fileName||"",language:e.language||"",recentChanges:e.recentChanges||"",clipboard:e.clipboard||""})}catch{n=""}_o({command:"inlineCompleteResponse",requestId:e.requestId,completion:n||""})},uc=e=>{_o({command:"status",status:e})},Jn=()=>new Promise(e=>{if(!Ht||Ht.readyState!==ii.OPEN){e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]});return}uo=e,Ht.send(JSON.stringify({command:"requestContext"})),setTimeout(()=>{uo===e&&(e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]}),uo=null)},1e3)}),ir=e=>{_o({command:"open",filePath:e})},Vi=(e,n,t)=>{_o({command:"showDiff",filePath:e,originalContent:n,modifiedContent:t})},sr=(e,n)=>{_o({command:"closeDiff",filePath:e,result:n})};var $o=(e,n)=>{try{if(!ln.existsSync(e))return null;let t=Array.isArray(n)?n.map(o=>o.toLowerCase()):[n.toLowerCase()],i=ln.readdirSync(e);for(let o of t){let r=i.find(c=>c.toLowerCase()===o);if(r){let c=an.join(e,r);if(ln.statSync(c).isFile())return c}}}catch{}return null},Ji=(e,n)=>{let t=$o(e,n);if(t)try{return ln.readFileSync(t,"utf8")}catch{}return""},rr=new Set([".git","node_modules",".gemini","dist","build",".next","out",".cache","bin","obj","vendor","venv",".idea",".gradle",".terraform","target","coverage",".vscode",".svn",".hg",".fslckout",".github",".gitlab",".circleci",".gitea",".gitee",".lerna",".changeset",".nx",".npm",".yarn",".pnpm-store",".pnpm",".expo",".nuxt",".svelte-kit",".docusaurus",".turbo",".vercel","bower_components",".netlify",".vuepress",".quasar",".output",".angular","jspm_packages",".parcel-cache",".rollup.cache",".rspack",".vitepress","__pycache__",".pytest_cache",".mypy_cache",".tox",".poetry","env","vhdl",".ipynb_checkpoints",".jupyter",".conda",".pdm-build",".bundle",".yardoc",".metadata","App_Data","ClientBin",".cargo",".rustc_info",".go","Godeps","_vendor",".rake_tasks","CMakefiles",".wakatime",".dart_tool",".fvm",".cocoapods","Pods",".pub-cache",".symlinks","DerivedData",".xcworkspace",".serverless",".aws",".gcloud",".azure",".kube",".vagrant",".docker","postgres-data","redis-data","mongo-data",".Spotlight-V100",".Trashes","$RECYCLE.BIN","System Volume Information",".DocumentRevisions-V100",".fseventsd","AppData","Application Data","Local","LocalLow","Roaming","$WinREAgent","$WINDOWS.~BT","$WINDOWS.~WS","scw","System32","SysWOW64",".AppleDouble",".AppleDB",".AppleDesktop","_CodeSignature",".cmio",".LSOverride",".localized",".TemporaryItems",".Trash",".Trash-0",".Trash-1000",".gvfs",".local",".config",".dbus",".fontconfig",".snap",".var",".lost+found","lost+found",".thumb",".thumbnails","EFI","boot","grub","logs","log",".nyc_output",".sonar",".ruff_cache",".VSCodeCounter",".skills","skills"]),Qi=(e=process.cwd(),n=0,t=8)=>{let i=[];if(n>t)return i;try{if(!ln.existsSync(e))return i;let o=ln.readdirSync(e,{withFileTypes:!0});for(let r of o){let c=r.name,a=an.join(e,c);if(r.isDirectory())!rr.has(c)&&!rr.has(c.toLowerCase())&&i.push(...Qi(a,n+1,t));else if(r.isFile()){let u=c.toLowerCase();(u==="agents.md"||u==="agent.md")&&i.push(a)}}}catch{}return i},ar=(e,n=2)=>{if(!e)return"";let t=" ".repeat(n);return e.split(/\r?\n/).map(i=>t+i).join(`
480
- `)},ur=()=>$o(Un,["agents.md","agent.md"]),gr=()=>$o(process.cwd(),["agents.md","agent.md"]),mr=()=>$o(Un,["fluxflow.md"]),pr=()=>$o(process.cwd(),["fluxflow.md"]),Io=ur(),si=gr(),kn=Qi(),Mo=mr(),Po=pr(),lr=null,Xi="",hr=!1,$a=e=>{if(!e||!/^<<<[\s\S]*?Identity:/m.test(e))return e;let n=e.match(/^<<<\s*\r?\n([\s\S]*?)\r?\n>>>\s*(?:\r?\n)?([\s\S]*)$/);if(!n)return e;let t=n[1],i=n[2],o=t.match(/^Identity:\s*([\s\S]*?)(?=\r?\n\s*(?:<><|>>>)|$)/m);return o&&(Xi=o[1].trim(),process.env.NO_INS=!0),/<><\s*NO_INS/.test(t)&&(hr=!0),i.trim()},Na=()=>{Io=ur();let e=Io?Ji(Un,["agents.md","agent.md"]).trim():"";return e.length===0?(Io=null,""):e},Da=()=>{if(kn=Qi(),si=gr(),!kn||kn.length===0)return"";let e=process.cwd(),n=[...kn].sort((o,r)=>{let c=an.relative(e,o).replace(/\\/g,"/"),a=an.relative(e,r).replace(/\\/g,"/"),u=!c.includes("/"),h=!a.includes("/");return u&&!h?-1:!u&&h?1:c.localeCompare(a)}),t=[],i=[];for(let o of n)try{let r=ln.readFileSync(o,"utf8").trim();if(!r||r.length===0)continue;t.push(o);let c=an.relative(e,o).replace(/\\/g,"/");if(!c.includes("/"))i.push(ar(r,2));else{let u=an.dirname(c)+"/:";i.push(`${u}
481
- ${ar(r,2)}`)}}catch{}return kn=t,kn.length===0&&(si=null),i.join(`
478
+ Docs missing required info? Say you are not sure enough to answer. Dont give wrong info`,"references/MODES.md":Xs,"references/PROVIDERS.md":Js,"references/PLUGINS.md":Qs,"references/STARTUP.md":Ws,"references/ENV.md":Gs,"references/COMMANDS.md":Hs,"references/SETTINGS.md":js,"references/TOOLS.md":Ks,"references/ARCHITECTURE.md":Vs,"references/SUB_AGENTS.md":Ys,"references/SECURITY.md":zs,"references/IDE.md":qs};var tr=()=>{try{let e=Fn.join(Dn,"skills","fluxflow"),n=Fn.join(e,"references");if(process.env.NO_DEV==="true"||process.env.NO_DEV==="1"||process.env.NO_DEV===!0||process.env.NO_INS==="true"||process.env.NO_INS==="1"||process.env.NO_INS==="true"||!1){xn.existsSync(e)&&xn.rmSync(e,{recursive:!0,force:!0});return}let i=new Set(Object.keys(Gi).map(o=>Fn.normalize(o)));for(let[o,r]of Object.entries(Gi)){let d=Fn.join(e,o),a=Fn.dirname(d);xn.existsSync(a)||xn.mkdirSync(a,{recursive:!0});let u=r.trim()+`
479
+ `,h=null;xn.existsSync(d)&&(h=xn.readFileSync(d,"utf8")),h!==u&&xn.writeFileSync(d,u,"utf8")}if(xn.existsSync(n)){let o=xn.readdirSync(n);for(let r of o){let d=Fn.normalize(Fn.join("references",r));if(!i.has(d)){let a=Fn.join(n,r);try{xn.rmSync(a,{recursive:!0,force:!0})}catch{}}}}}catch{}};import{WebSocket as ii}from"ws";var Ut=null,co=!1,Oa="ws://localhost:56832",Hi=[],fo=null,ji=null,Ki=null,nr="2.0.0",fc=e=>{nr=e,or()},Vi=e=>{ji=e},uc=e=>{Ki=e},or=()=>{if(Ut||co)return;co=!0;let e=new ii(Oa);e.on("open",()=>{for(Ut=e,co=!1,Ut.send(JSON.stringify({command:"version",version:nr,pid:process.pid,ppid:process.ppid,cwd:process.cwd()}));Hi.length>0;)Ut.send(JSON.stringify(Hi.shift()))}),e.on("message",n=>{try{let t=JSON.parse(n.toString());t.command==="contextResponse"&&fo?(fo(t.data),fo=null):t.command==="securityResponse"&&ji?ji(t.result):t.command==="inlineComplete"?La(t):t.command==="connectionRejected"&&Ki&&Ki(t)}catch{}}),e.on("error",()=>{co=!1,Ut=null}),e.on("close",()=>{co=!1,Ut=null})},vo=e=>{Ut&&Ut.readyState===ii.OPEN?Ut.send(JSON.stringify(e)):(Hi.push(e),co||or())},uo=()=>Ut!==null&&Ut.readyState===ii.OPEN,La=async e=>{let n="";try{let{generateAutoCompletion:t}=await import("./auto_completion-JQ37MRZ7.js");n=await t({prefix:e.prefix||"",suffix:e.suffix||"",fileName:e.fileName||"",language:e.language||"",recentChanges:e.recentChanges||"",clipboard:e.clipboard||""})}catch{n=""}vo({command:"inlineCompleteResponse",requestId:e.requestId,completion:n||""})},gc=e=>{vo({command:"status",status:e})},Jn=()=>new Promise(e=>{if(!Ut||Ut.readyState!==ii.OPEN){e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]});return}fo=e,Ut.send(JSON.stringify({command:"requestContext"})),setTimeout(()=>{fo===e&&(e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]}),fo=null)},1e3)}),ir=e=>{vo({command:"open",filePath:e})},Yi=(e,n,t)=>{vo({command:"showDiff",filePath:e,originalContent:n,modifiedContent:t})},sr=(e,n)=>{vo({command:"closeDiff",filePath:e,result:n})};var $o=(e,n)=>{try{if(!rn.existsSync(e))return null;let t=Array.isArray(n)?n.map(o=>o.toLowerCase()):[n.toLowerCase()],i=rn.readdirSync(e);for(let o of t){let r=i.find(d=>d.toLowerCase()===o);if(r){let d=sn.join(e,r);if(rn.statSync(d).isFile())return d}}}catch{}return null},Qi=(e,n)=>{let t=$o(e,n);if(t)try{return rn.readFileSync(t,"utf8")}catch{}return""},rr=new Set([".git","node_modules",".gemini","dist","build",".next","out",".cache","bin","obj","vendor","venv",".idea",".gradle",".terraform","target","coverage",".vscode",".svn",".hg",".fslckout",".github",".gitlab",".circleci",".gitea",".gitee",".lerna",".changeset",".nx",".npm",".yarn",".pnpm-store",".pnpm",".expo",".nuxt",".svelte-kit",".docusaurus",".turbo",".vercel","bower_components",".netlify",".vuepress",".quasar",".output",".angular","jspm_packages",".parcel-cache",".rollup.cache",".rspack",".vitepress","__pycache__",".pytest_cache",".mypy_cache",".tox",".poetry","env","vhdl",".ipynb_checkpoints",".jupyter",".conda",".pdm-build",".bundle",".yardoc",".metadata","App_Data","ClientBin",".cargo",".rustc_info",".go","Godeps","_vendor",".rake_tasks","CMakefiles",".wakatime",".dart_tool",".fvm",".cocoapods","Pods",".pub-cache",".symlinks","DerivedData",".xcworkspace",".serverless",".aws",".gcloud",".azure",".kube",".vagrant",".docker","postgres-data","redis-data","mongo-data",".Spotlight-V100",".Trashes","$RECYCLE.BIN","System Volume Information",".DocumentRevisions-V100",".fseventsd","AppData","Application Data","Local","LocalLow","Roaming","$WinREAgent","$WINDOWS.~BT","$WINDOWS.~WS","scw","System32","SysWOW64",".AppleDouble",".AppleDB",".AppleDesktop","_CodeSignature",".cmio",".LSOverride",".localized",".TemporaryItems",".Trash",".Trash-0",".Trash-1000",".gvfs",".local",".config",".dbus",".fontconfig",".snap",".var",".lost+found","lost+found",".thumb",".thumbnails","EFI","boot","grub","logs","log",".nyc_output",".sonar",".ruff_cache",".VSCodeCounter",".skills","skills"]),Zi=(e=process.cwd(),n=0,t=8)=>{let i=[];if(n>t)return i;try{if(!rn.existsSync(e))return i;let o=rn.readdirSync(e,{withFileTypes:!0});for(let r of o){let d=r.name,a=sn.join(e,d);if(r.isDirectory())!rr.has(d)&&!rr.has(d.toLowerCase())&&i.push(...Zi(a,n+1,t));else if(r.isFile()){let u=d.toLowerCase();(u==="agents.md"||u==="agent.md")&&i.push(a)}}}catch{}return i},ar=(e,n=2)=>{if(!e)return"";let t=" ".repeat(n);return e.split(/\r?\n/).map(i=>t+i).join(`
480
+ `)},ur=()=>$o(Dn,["agents.md","agent.md"]),gr=()=>$o(process.cwd(),["agents.md","agent.md"]),mr=()=>$o(Dn,["fluxflow.md"]),pr=()=>$o(process.cwd(),["fluxflow.md"]),Io=ur(),si=gr(),bn=Zi(),Mo=mr(),Po=pr(),lr=null,Ji="",hr=!1,Na=e=>{if(!e||!/^<<<[\s\S]*?Identity:/m.test(e))return e;let n=e.match(/^<<<\s*\r?\n([\s\S]*?)\r?\n>>>\s*(?:\r?\n)?([\s\S]*)$/);if(!n)return e;let t=n[1],i=n[2],o=t.match(/^Identity:\s*([\s\S]*?)(?=\r?\n\s*(?:<><|>>>)|$)/m);return o&&(Ji=o[1].trim(),process.env.NO_INS=!0),/<><\s*NO_INS/.test(t)&&(hr=!0),i.trim()},Da=()=>{Io=ur();let e=Io?Qi(Dn,["agents.md","agent.md"]).trim():"";return e.length===0?(Io=null,""):e},Fa=()=>{if(bn=Zi(),si=gr(),!bn||bn.length===0)return"";let e=process.cwd(),n=[...bn].sort((o,r)=>{let d=sn.relative(e,o).replace(/\\/g,"/"),a=sn.relative(e,r).replace(/\\/g,"/"),u=!d.includes("/"),h=!a.includes("/");return u&&!h?-1:!u&&h?1:d.localeCompare(a)}),t=[],i=[];for(let o of n)try{let r=rn.readFileSync(o,"utf8").trim();if(!r||r.length===0)continue;t.push(o);let d=sn.relative(e,o).replace(/\\/g,"/");if(!d.includes("/"))i.push(ar(r,2));else{let u=sn.dirname(d)+"/:";i.push(`${u}
481
+ ${ar(r,2)}`)}}catch{}return bn=t,bn.length===0&&(si=null),i.join(`
482
482
 
483
- `).trim()},Zi=()=>{Mo=mr();let e=Mo?Ji(Un,["fluxflow.md"]).trim():"",n=$a(e)?.trim()||"";return n.length===0?(Mo=null,""):n},es=()=>{Po=pr();let e=Po?Ji(process.cwd(),["fluxflow.md"]).trim():"";return e.length===0?(Po=null,""):e},ts=Na(),ri=Da(),Oo=Zi(),Lo=es(),cr=(e,n="",t="")=>{if(!e)return"";let i=t.toLowerCase().trim(),o=n.toLowerCase().trim(),r=an.posix.basename(o),c=i&&o?`${i}@${o}`:"",a=i&&r?`${i}@${r}`:"",u=x=>!x||!o?!1:x===o||x===r||x===c||x===a,h=[];return e.replace(/<start_provider_([^>\r\n]+)>([\s\S]*?)<end_provider_([^>\r\n]+)>/gi,(x,p,f,s)=>{if(i&&p.trim().toLowerCase()===s.trim().toLowerCase()&&p.trim().toLowerCase()===i){let k=f.replace(/<start_model_([^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n]+)>/gi,(he,y,E,D)=>{if(y.trim().toLowerCase()===D.trim().toLowerCase()){let K=y.trim().toLowerCase();if(u(K)){let O=E.trim();O&&h.push(O)}}return""}).trim();k&&h.push(k)}return""}),e.replace(/<start_model_([^>\r\n@]+@[^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n@]+@[^>\r\n]+)>/gi,(x,p,f,s)=>{if(p.trim().toLowerCase()===s.trim().toLowerCase()){let g=p.trim().toLowerCase();if(u(g)){let k=f.trim();k&&h.push(k)}}return""}),e.replace(/<start_model_([^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n]+)>/gi,(x,p,f,s)=>{if(p.includes("@"))return"";if(p.trim().toLowerCase()===s.trim().toLowerCase()){let g=p.trim().toLowerCase();if(o&&(g===o||g===r)){let k=f.trim();k&&h.push(k)}}return""}),h.join(`
483
+ `).trim()},es=()=>{Mo=mr();let e=Mo?Qi(Dn,["fluxflow.md"]).trim():"",n=Na(e)?.trim()||"";return n.length===0?(Mo=null,""):n},ts=()=>{Po=pr();let e=Po?Qi(process.cwd(),["fluxflow.md"]).trim():"";return e.length===0?(Po=null,""):e},ns=Da(),ri=Fa(),Oo=es(),Lo=ts(),cr=(e,n="",t="")=>{if(!e)return"";let i=t.toLowerCase().trim(),o=n.toLowerCase().trim(),r=sn.posix.basename(o),d=i&&o?`${i}@${o}`:"",a=i&&r?`${i}@${r}`:"",u=x=>!x||!o?!1:x===o||x===r||x===d||x===a,h=[];return e.replace(/<start_provider_([^>\r\n]+)>([\s\S]*?)<end_provider_([^>\r\n]+)>/gi,(x,p,f,s)=>{if(i&&p.trim().toLowerCase()===s.trim().toLowerCase()&&p.trim().toLowerCase()===i){let k=f.replace(/<start_model_([^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n]+)>/gi,(me,y,E,N)=>{if(y.trim().toLowerCase()===N.trim().toLowerCase()){let H=y.trim().toLowerCase();if(u(H)){let O=E.trim();O&&h.push(O)}}return""}).trim();k&&h.push(k)}return""}),e.replace(/<start_model_([^>\r\n@]+@[^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n@]+@[^>\r\n]+)>/gi,(x,p,f,s)=>{if(p.trim().toLowerCase()===s.trim().toLowerCase()){let g=p.trim().toLowerCase();if(u(g)){let k=f.trim();k&&h.push(k)}}return""}),e.replace(/<start_model_([^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n]+)>/gi,(x,p,f,s)=>{if(p.includes("@"))return"";if(p.trim().toLowerCase()===s.trim().toLowerCase()){let g=p.trim().toLowerCase();if(o&&(g===o||g===r)){let k=f.trim();k&&h.push(k)}}return""}),h.join(`
484
484
 
485
- `).trim()},Fa=(e="",n="")=>{let t=`${e||""}@${n||""}`.toLowerCase().trim();lr!==t&&(lr=t,Oo=Zi(),Lo=es())};tr();var Ba=e=>{if(!e)return null;let n=e.match(/^\s*---\r?\n([\s\S]*?)\r?\n---(?:\r?\n)?([\s\S]*)$/);if(!n)return null;let t=n[1];if((n[2]||"").trim().length===0)return null;let o="",r="",c=t.match(/^name:\s*(.+)$/m),a=t.match(/^description:\s*(.+)$/m);return c&&(o=c[1].trim().replace(/^["']|["']$/g,"")),a&&(r=a[1].trim().replace(/^["']|["']$/g,"")),o&&r?{name:o,description:r}:null},Ua=e=>{let n=[];if(!e||!ln.existsSync(e))return n;let t=(i,o=0)=>{if(!(o>5))try{let r=ln.readdirSync(i,{withFileTypes:!0});for(let c of r){let a=an.join(i,c.name),u=c.name.toLowerCase();c.isFile()?u==="skill.md"&&n.push(a):c.isDirectory()&&(o===0?(u==="skills"||u===".skills"||u==="skill"||u===".skill")&&t(a,o+1):t(a,o+1))}}catch{}};return t(e,0),n},yr=e=>{let n=Ua(e),t=[];for(let i of n)try{let o=ln.readFileSync(i,"utf8"),r=Ba(o);r&&t.push({...r,filePath:i})}catch{}return t},xr=e=>!e||e.length===0?"":e.map(n=>`- ${n.name}: ${n.description}`).join(`
486
- `),br=yr(Un),wr=yr(process.cwd()),Yi=xr(br),zi=xr(wr),Sr=e=>{if(!e)return!1;let n=(e.filePath||"").replace(/\\/g,"/").toLowerCase();return n.includes("/skills/fluxflow/skill.md")||n.includes("/skills/about-fluxflow/skill.md")||e.name?.toLowerCase()==="fluxflow"},kr=()=>(br||[]).filter(e=>!Sr(e)),Tr=()=>(wr||[]).filter(e=>!Sr(e)),Rc=(ts?.length>0?1:0)+(ri?.length>0?kn.length:0)+(Oo?.length>0?1:0)+(Lo?.length>0?1:0)+kr().length+Tr().length,qi=(e,n="Project")=>{if(!e)return"";let t=e.replace(/\\/g,"/");if(n==="Global"){let o=La.homedir().replace(/\\/g,"/");return t.toLowerCase().startsWith(o.toLowerCase())?"~"+t.slice(o.length):t}let i=an.relative(process.cwd(),e).replace(/\\/g,"/");return i.startsWith(".")?i:`./${i}`},_c=()=>{Oo=Zi(),Lo=es();let e=[];Io&&ts.length>0&&e.push({scope:"Global",path:Io}),kn&&kn.length>0&&ri.length>0?kn.forEach(r=>{e.push({scope:"Project",path:r})}):si&&ri.length>0&&e.push({scope:"Project",path:si}),Mo&&Oo.length>0&&e.push({scope:"Global",path:Mo}),Po&&Lo.length>0&&e.push({scope:"Project",path:Po});let n=kr(),t=Tr(),i=e.length+n.length+t.length;if(i===0)return`\u2726 Loaded Files & Instructions
485
+ `).trim()},Ba=(e="",n="")=>{let t=`${e||""}@${n||""}`.toLowerCase().trim();lr!==t&&(lr=t,Oo=es(),Lo=ts())};tr();var Ua=e=>{if(!e)return null;let n=e.match(/^\s*---\r?\n([\s\S]*?)\r?\n---(?:\r?\n)?([\s\S]*)$/);if(!n)return null;let t=n[1];if((n[2]||"").trim().length===0)return null;let o="",r="",d=t.match(/^name:\s*(.+)$/m),a=t.match(/^description:\s*(.+)$/m);return d&&(o=d[1].trim().replace(/^["']|["']$/g,"")),a&&(r=a[1].trim().replace(/^["']|["']$/g,"")),o&&r?{name:o,description:r}:null},Wa=e=>{let n=[];if(!e||!rn.existsSync(e))return n;let t=(i,o=0)=>{if(!(o>5))try{let r=rn.readdirSync(i,{withFileTypes:!0});for(let d of r){let a=sn.join(i,d.name),u=d.name.toLowerCase();d.isFile()?u==="skill.md"&&n.push(a):d.isDirectory()&&(o===0?(u==="skills"||u===".skills"||u==="skill"||u===".skill")&&t(a,o+1):t(a,o+1))}}catch{}};return t(e,0),n},yr=e=>{let n=Wa(e),t=[];for(let i of n)try{let o=rn.readFileSync(i,"utf8"),r=Ua(o);r&&t.push({...r,filePath:i})}catch{}return t},xr=e=>!e||e.length===0?"":e.map(n=>`- ${n.name}: ${n.description}`).join(`
486
+ `),br=yr(Dn),wr=yr(process.cwd()),zi=xr(br),qi=xr(wr),Sr=e=>{if(!e)return!1;let n=(e.filePath||"").replace(/\\/g,"/").toLowerCase();return n.includes("/skills/fluxflow/skill.md")||n.includes("/skills/about-fluxflow/skill.md")||e.name?.toLowerCase()==="fluxflow"},kr=()=>(br||[]).filter(e=>!Sr(e)),Tr=()=>(wr||[]).filter(e=>!Sr(e)),vc=(ns?.length>0?1:0)+(ri?.length>0?bn.length:0)+(Oo?.length>0?1:0)+(Lo?.length>0?1:0)+kr().length+Tr().length,Xi=(e,n="Project")=>{if(!e)return"";let t=e.replace(/\\/g,"/");if(n==="Global"){let o=$a.homedir().replace(/\\/g,"/");return t.toLowerCase().startsWith(o.toLowerCase())?"~"+t.slice(o.length):t}let i=sn.relative(process.cwd(),e).replace(/\\/g,"/");return i.startsWith(".")?i:`./${i}`},_c=()=>{Oo=es(),Lo=ts();let e=[];Io&&ns.length>0&&e.push({scope:"Global",path:Io}),bn&&bn.length>0&&ri.length>0?bn.forEach(r=>{e.push({scope:"Project",path:r})}):si&&ri.length>0&&e.push({scope:"Project",path:si}),Mo&&Oo.length>0&&e.push({scope:"Global",path:Mo}),Po&&Lo.length>0&&e.push({scope:"Project",path:Po});let n=kr(),t=Tr(),i=e.length+n.length+t.length;if(i===0)return`\u2726 Loaded Files & Instructions
487
487
  \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m No instruction or skill files are currently loaded.
488
488
  \u2800`;let o=[];return o.push(`\u2726 Loaded Files & Instructions (${i} ${i===1?"file":"files"} active)`),e.length>0&&(o.push(`
489
- \x1B[1mInstructions:\x1B[22m`),e.forEach(r=>{o.push(` \u2022 [${r.scope}] ${qi(r.path,r.scope)}`)})),(n?.length>0||t?.length>0)&&(o.push(`
490
- \x1B[1mSkills:\x1B[22m`),n?.length>0&&n.forEach(r=>{o.push(` \u2022 [Global] \x1B[36m${r.name}\x1B[39m`),o.push(` \x1B[2m\u2514\u2500 ${qi(r.filePath,"Global")}\x1B[22m`)}),t?.length>0&&t.forEach(r=>{o.push(` \u2022 [Project] \x1B[36m${r.name}\x1B[39m`),o.push(` \x1B[2m\u2514\u2500 ${qi(r.filePath,"Project")}\x1B[22m`)})),o.push("\u2800"),o.join(`
491
- `)},Ar=!1;(async()=>{try{let e=await Eo();if(Number(e?.display)===1){let{default:n}=await import("screenshot-desktop"),t=await n.listDisplays();t&&t.length>1&&(Ar=!0)}}catch{}})();var dr=null,vo=null,fr=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",vc=process.env.NO_DEV||!1,Wa=(e,n)=>{if(!n)return"";if(e!==dr||vo===null){dr=e;try{let t=Ot(Xn,[]);Array.isArray(t)&&t.length>0?vo=t.map(i=>`- ${i.memory}`).join(`
492
- `):vo=""}catch(t){vo="";try{ln.mkdirSync(an.join(wn,"memory"),{recursive:!0}),ln.appendFileSync(an.join(wn,"memory","error.txt"),`${t.message}
489
+ \x1B[1mInstructions:\x1B[22m`),e.forEach(r=>{o.push(` \u2022 [${r.scope}] ${Xi(r.path,r.scope)}`)})),(n?.length>0||t?.length>0)&&(o.push(`
490
+ \x1B[1mSkills:\x1B[22m`),n?.length>0&&n.forEach(r=>{o.push(` \u2022 [Global] \x1B[36m${r.name}\x1B[39m`),o.push(` \x1B[2m\u2514\u2500 ${Xi(r.filePath,"Global")}\x1B[22m`)}),t?.length>0&&t.forEach(r=>{o.push(` \u2022 [Project] \x1B[36m${r.name}\x1B[39m`),o.push(` \x1B[2m\u2514\u2500 ${Xi(r.filePath,"Project")}\x1B[22m`)})),o.push("\u2800"),o.join(`
491
+ `)},Ar=!1;(async()=>{try{let e=await Eo();if(Number(e?.display)===1){let{default:n}=await import("screenshot-desktop"),t=await n.listDisplays();t&&t.length>1&&(Ar=!0)}}catch{}})();var dr=null,_o=null,fr=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",Ic=process.env.NO_DEV||!1,Ga=(e,n)=>{if(!n)return"";if(e!==dr||_o===null){dr=e;try{let t=vt(Xn,[]);Array.isArray(t)&&t.length>0?_o=t.map(i=>`- ${i.memory}`).join(`
492
+ `):_o=""}catch(t){_o="";try{rn.mkdirSync(sn.join(yn,"memory"),{recursive:!0}),rn.appendFileSync(sn.join(yn,"memory","error.txt"),`${t.message}
493
493
  -------------------------------------------------
494
494
 
495
- `)}catch{}}}return vo};var Er=(e,n,t,i,o=!0,r=!1,c="Google",a=!1,u,h,x=!1,p="")=>{let f=!1;process.env.forcedReasoning&&(f=!0);let s="";if(!u&&c==="Google"){let Y=n;n==="Fast"&&(Y="Off"),n==="Low"&&(Y="Minimal"),n==="Standard"&&(Y="Medium"),(n==="xHigh"||n==="Max")&&(Y="xHigh"),s=ni[Y]||ni.Medium}(u||c!=="Google")&&(s=ni.xHigh,n==="Fast"?s=`No thinking. Immediate response
495
+ `)}catch{}}}return _o};var Er=(e,n,t,i,o=!0,r=!1,d="Google",a=!1,u,h,x=!1,p="")=>{let f=!1;process.env.forcedReasoning&&(f=!0);let s="";if(!u&&d==="Google"){let j=n;n==="Fast"&&(j="Off"),n==="Low"&&(j="Minimal"),n==="Standard"&&(j="Medium"),(n==="xHigh"||n==="Max")&&(j="xHigh"),s=ni[j]||ni.Medium}(u||d!=="Google")&&(s=ni.xHigh,n==="Fast"?s=`No thinking. Immediate response
496
496
  Verify imports, tool results & system stability`:n.toLowerCase()==="max"&&(s=`Effort: Max
497
497
  Plan step by step`));let g=e.instructions&&e.instructions?.length>0?`User Preferences: ${e.instructions}
498
498
 
499
499
  `:"",k=e.nickname&&e.nickname?.length>0?`User Nickname: ${e.nickname}
500
500
  ${g.length?"":`
501
- `}`:"",he=e.name&&e.name?.length>0?`User Name: ${e.name}
501
+ `}`:"",me=e.name&&e.name?.length>0?`User Name: ${e.name}
502
502
  ${k.length||g.length?"":`
503
- `}`:"",y=process.cwd(),E=e.preset,K={Sassy:"Sassy",Friendly:"Sassy, Warm & Chatty",Playful:"Playful",Efficient:"Quick, Concise & Efficient",Professional:"Professional"}[E]||null,O=Wa(h,o),T=O?.length>0?`--- Saved Memories ---
503
+ `}`:"",y=process.cwd(),E=e.preset,H={Sassy:"Sassy",Friendly:"Sassy, Warm & Chatty",Playful:"Playful",Efficient:"Quick, Concise & Efficient",Professional:"Professional"}[E]||null,O=Ga(h,o),T=O?.length>0?`--- Saved Memories ---
504
504
  ${O}
505
505
 
506
- `:"";Fa(c,p);let Se=cr(Oo,p,c).trim(),Me=[ts,Se].filter(Y=>Y&&Y.length>0).join(`
506
+ `:"";Ba(d,p);let be=cr(Oo,p,d).trim(),_e=[ns,be].filter(j=>j&&j.length>0).join(`
507
507
 
508
- `).trim(),Je=cr(Lo,p,c).trim(),b=[ri,Je].filter(Y=>Y&&Y.length>0).join(`
508
+ `).trim(),Ye=cr(Lo,p,d).trim(),b=[ri,Ye].filter(j=>j&&j.length>0).join(`
509
509
 
510
- `).trim(),ht=Me.length>0||b.length>0?`--- Additional Instructions ---
511
- ${Me.length>0?`-- Global --
512
- ${Me}`:""}${b.length>0?`${Me.length>0?`
510
+ `).trim(),ut=_e.length>0||b.length>0?`--- Additional Instructions ---
511
+ ${_e.length>0?`-- Global --
512
+ ${_e}`:""}${b.length>0?`${_e.length>0?`
513
513
 
514
514
  `:""}-- Project --
515
515
  ${b}`:""}
516
516
 
517
- `:"",fe=(()=>{let Y=process.cwd().toLowerCase();if(process.platform==="win32"){let H=process.env.SystemRoot?.toLowerCase()||"c:\\windows",_=process.env.ProgramFiles?.toLowerCase()||"c:\\program files",Qe=process.env["ProgramFiles(x86)"]?.toLowerCase()||"c:\\program files (x86)";return Y.startsWith(H)||Y.startsWith(_)||Y.startsWith(Qe)}else return Y==="/"||["/bin","/sbin","/etc","/usr","/var","/root"].some(_=>Y.startsWith(_))})(),q=new Date,tn=q.getFullYear(),Vt=q.toLocaleString("en-US",{month:"short"}).toUpperCase(),cn=String(q.getDate()).padStart(2,"0"),po=`${tn}-${Vt}-${cn}`,Pn=process.env.I_HAVE_TOO_MUCH_MONEY==="true"||!1,dn=process.env.HALLOWEEN_EEGG==="true"||!1,yt=dn&&Vt.includes("OCT")&&(cn.includes("30")||cn.includes("31")),Yt=(p||"").replace(/^.*::/,"").split(":")[0].replace(/\/free$/,"").trim(),ue=an.basename(Yt).replace(/-free$/,"").replace(/_free$/,"").replace(/^free_/,"").replaceAll("-"," ").replaceAll("_"," ").replace(/\b\w/g,Y=>Y.toUpperCase().trim()),Be=process.env.NO_DEV==="true"||!1,Pe=!1;try{Pe=go()}catch{Pe=!1}return`${Pn?`${" ".repeat(Math.floor(Math.random()*4)+1)}`:""}=== SYSTEM PROMPT ===
518
- ${`Identity: ${Xi.length>1?Xi.trim():`Flux Flow.${K?` ${K}`:""} CLI Assistant${dn?`. ${yt?"Peak ":""}Halloween Themed, Spooky`:""}`}
517
+ `:"",fe=(()=>{let j=process.cwd().toLowerCase();if(process.platform==="win32"){let U=process.env.SystemRoot?.toLowerCase()||"c:\\windows",v=process.env.ProgramFiles?.toLowerCase()||"c:\\program files",ze=process.env["ProgramFiles(x86)"]?.toLowerCase()||"c:\\program files (x86)";return j.startsWith(U)||j.startsWith(v)||j.startsWith(ze)}else return j==="/"||["/bin","/sbin","/etc","/usr","/var","/root"].some(v=>j.startsWith(v))})(),Y=new Date,Zt=Y.getFullYear(),Gt=Y.toLocaleString("en-US",{month:"short"}).toUpperCase(),an=String(Y.getDate()).padStart(2,"0"),mo=`${Zt}-${Gt}-${an}`,_n=process.env.I_HAVE_TOO_MUCH_MONEY==="true"||!1,ln=process.env.HALLOWEEN_EEGG==="true"||!1,gt=ln&&Gt.includes("OCT")&&(an.includes("30")||an.includes("31")),Ht=(p||"").replace(/^.*::/,"").split(":")[0].replace(/\/free$/,"").trim(),ue=sn.basename(Ht).replace(/-free$/,"").replace(/_free$/,"").replace(/^free_/,"").replaceAll("-"," ").replaceAll("_"," ").replace(/\b\w/g,j=>j.toUpperCase().trim()),De=process.env.NO_DEV==="true"||!1,Ie=!1;try{Ie=uo()}catch{Ie=!1}return`${_n?`${" ".repeat(Math.floor(Math.random()*4)+1)}`:""}=== SYSTEM PROMPT ===
518
+ ${`Identity: ${Ji.length>1?Ji.trim():`Flux Flow.${H?` ${H}`:""} CLI Assistant${ln?`. ${gt?"Peak ":""}Halloween Themed, Spooky`:""}`}
519
519
  ${hr?"":`${t==="Flux"?"":t==="Flow"?"Concise, Humorous, Sarcastic":t==="ICU"?"Computer Use Capabilities. Screenshot as ground truth, analyze grid ids of target. Keyboard shortcuts > mouse clicks":"Computer Use & Workspace Capabilities. Screenshot as ground truth, analyze grid ids of target. Keyboard shortcuts > mouse clicks. Workspace Actions when faster. Focus on Productivity"}`}${Ar&&t.toLowerCase().includes("cu")?`
520
520
  - Running on secondary screen. Opened app not visible in screenshot? Might be opened on primary. Use 'AskUser' with NO options and tell user to move app window to secondary`:""}`.trimEnd()}
521
521
 
522
- - OS: ${fr}${!Be&&p.length>1?`
522
+ - OS: ${fr}${!De&&p.length>1?`
523
523
  - Model: ${ue}`.trimEnd():""}
524
- - Date: ${po}
524
+ - Date: ${mo}
525
525
 
526
526
  -- REASONING GUIDANCE --
527
- ${c==="Mistral"||c==="Google"&&!u||f?`${s.trimEnd()}${f||n!=="Fast"&&(c==="Mistral"&&n==="Low"&&!u||n!=="High"&&!u)?`
527
+ ${d==="Mistral"||d==="Google"&&!u||f?`${s.trimEnd()}${f||n!=="Fast"&&(d==="Mistral"&&n==="Low"&&!u||n!=="High"&&!u)?`
528
528
  Critical Thinking Policy
529
529
  Use <think_fluxflow>...</think_fluxflow> for reasoning before responding any queries`:""}`:`${s.trimEnd()}`}${x?"":`
530
530
  Before actions, provide user facing summary of findings & decisions IN detail
531
531
  `}
532
- ${Ns(t,fr,a,c,i?.advanceRollback,i?.subAgents!==!1,!!i?.autoExec,!!i?.disableTodo,i?.preferBash!==!1)}${t==="Flux"?"":t.toLowerCase().includes("cu")?`
532
+ ${Ns(t,fr,a,d,i?.advanceRollback,i?.subAgents!==!1,!!i?.autoExec,!!i?.disableTodo,i?.preferBash!==!1)}${t==="Flux"?"":t.toLowerCase().includes("cu")?`
533
533
 
534
534
  -- SECURITY POLICIES --
535
- - Dont operate on ANY confidential screens/captcha \u2192 AskUser`:""}${Pe?`
535
+ - Dont operate on ANY confidential screens/captcha \u2192 AskUser`:""}${Ie?`
536
536
 
537
537
  Reference files as ./file:start..end`:""}
538
- === END SYSTEM PROMPT ===${(Yi.length>0||zi.length>0)&&t.toLowerCase().includes("flux")?`
538
+ === END SYSTEM PROMPT ===${(zi.length>0||qi.length>0)&&t.toLowerCase().includes("flux")?`
539
539
 
540
540
  - Read relevant skills before tasks, scope: global/project: Use ReadFile, path="#skills/scope?/skillName". In-skill references: path="#skills/scope?/skillName/reference-folder/*.md"`:""}
541
541
 
542
- ${k}${g}${ht}${Yi.length>0&&t.toLowerCase().includes("flux")?`-- Global Skills --
543
- ${Yi}
544
-
545
- `:""}${zi.length>0&&t.toLowerCase().includes("flux")?`-- Project Skills --
542
+ ${k}${g}${ut}${zi.length>0&&t.toLowerCase().includes("flux")?`-- Global Skills --
546
543
  ${zi}
547
544
 
545
+ `:""}${qi.length>0&&t.toLowerCase().includes("flux")?`-- Project Skills --
546
+ ${qi}
547
+
548
548
  `:""}${T}`.trim()},Cr=(e="",n=!0,t=!0)=>`=== SYSTEM PROMPT (strict headless logic worker: zero user-facing text policy, strictly follow) ===
549
549
  identity: silent background system process, have no mouth, only output is valid tool calls
550
550
  [critical rules]
@@ -566,50 +566,49 @@ ${Us(n,t)}
566
566
  === END SYSTEM PROMPT ===${e?`
567
567
 
568
568
  -- current saved user memories --
569
- ${e}`:""}`.trim();var Rr=()=>import("./web_search-KBGH67IV.js").then(e=>e.web_search),_r=()=>import("./web_scrape-J3PL2PXT.js").then(e=>e.web_scrape),vr=()=>import("./memory-7YOYCOXE.js").then(e=>e.memory),Ir=()=>import("./chat-BA72I6O3.js").then(e=>e.chat),Mr=()=>import("./view_file-I77KYUO5.js").then(e=>e.view_file),Pr=()=>import("./write_file-D7QA2LB2.js").then(e=>e.write_file),Or=()=>import("./update_file-KOHLNWAN.js").then(e=>e.update_file),Lr=()=>import("./exec_command-6V5SM6WI.js").then(e=>e.exec_command),$r=()=>import("./read_folder-EI2CNHNS.js").then(e=>e.read_folder),ns=()=>import("./ask_user-K2DLZF6H.js").then(e=>e.ask_user),Nr=()=>import("./write_pdf-TPGUF4VT.js").then(e=>e.write_pdf),Dr=()=>import("./write_docx-E3MTFXTQ.js").then(e=>e.write_docx),ai=()=>import("./search_keyword-O52M65TB.js").then(e=>e.search_keyword),Fr=()=>import("./generate_image-VW5VG6VI.js").then(e=>e.generate_image),li=()=>import("./saveSummary-W2JMDVZJ.js").then(e=>e.saveSummary),No=()=>import("./addMemScore-PBVNSFPN.js").then(e=>e.addMemScore),Br=()=>import("./file_map-UA4BA5OH.js").then(e=>e.file_map),ci=()=>import("./todo-CJLWLWJB.js").then(e=>e.todo),Ur=()=>import("./invokeSync-FK4TTKCM.js").then(e=>e.invokeSync),Ga=()=>import("./invoke-EI6WHT2A.js").then(e=>e.invoke),Wr=()=>import("./getProgress-J34K43Y7.js").then(e=>e.getProgress),Ha=()=>import("./cancel-F3ZOEBKW.js").then(e=>e.cancel),Gr=()=>import("./emergency_rollback-ZHQXCIHW.js").then(e=>e.emergency_rollback),Do=()=>import("./awaitSubagent-JKQ2EHVY.js").then(e=>e.awaitSubagent),Fo=()=>import("./answerSubagent-BPNNJXPC.js").then(e=>e.answerSubagent),di=()=>import("./steerSubagent-UETXH2CB.js").then(e=>e.steerSubagent),fi=()=>import("./computer_action-WNXZNAIZ.js").then(e=>e.computer_action),Hr=()=>import("./click-R35XTYKT.js").then(e=>e.click),jr=()=>import("./drag-IB5WSI6F.js").then(e=>e.drag),Kr=()=>import("./scroll-GIP2J2QN.js").then(e=>e.scroll),os=()=>import("./keyboard_typing-YHYH7O66.js").then(e=>e.keyboard_typing),is=()=>import("./key_press-XDYBP7DW.js").then(e=>e.key_press),ss=()=>import("./recapture_screen-F6ZPZU56.js").then(e=>e.recapture_screen),ui=()=>import("./find_file-HYHHFHUJ.js").then(e=>e.find_file),Vr=()=>import("./wait-TJR6LAR4.js").then(e=>e.wait),Yr={web_search:Rr,web_scrape:_r,memory:vr,chat:Ir,view_file:Mr,write_file:Pr,update_file:Or,exec_command:Lr,read_folder:$r,write_pdf:Nr,write_docx:Dr,search_keyword:ai,generate_image:Fr,saveSummary:li,addMemScore:No,file_map:Br,todo:ci,Todo:ci,goal:ci,Goal:ci,invokeSync:Ur,invoke:Ga,getProgress:Wr,cancel:Ha,awaitSubagent:Do,answerSubagent:Fo,steerSubagent:di,computer_action:fi,computer_use:fi,ComputerAction:fi,ComputerUse:fi,click:Hr,Click:Hr,drag:jr,Drag:jr,scroll:Kr,Scroll:Kr,keyboard_typing:os,KeyboardTyping:os,keyboardtyping:os,key_press:is,KeyPress:is,keypress:is,recapture_screen:ss,RecaptureScreen:ss,recapturescreen:ss,invoke_sync:Ur,get_progress:Wr,await_subagent:Do,answer_subagent:Fo,steer_subagent:di,steer:di,Steer:di,ask:ns,Ask:ns,AskUser:ns,WebSearch:Rr,WebScrape:_r,ReadFile:Mr,ReadFolder:$r,WriteFile:Pr,PatchFile:Or,WritePDF:Nr,WriteDoc:Dr,Run:Lr,SearchKeyword:ai,CodeSearch:ai,code_search:ai,Memory:vr,Chat:Ir,GenerateImage:Fr,saveSumary:li,SaveSummary:li,SaveSumary:li,add_mem_score:No,AddMemScore:No,addMemoryScore:No,AddMemoryScore:No,FileMap:Br,answer:Fo,Answer:Fo,AnswerSubagent:Fo,await:Do,Await:Do,AwaitSubagent:Do,EmergencyRollback:Gr,emergency_rollback:Gr,find_file:ui,findFile:ui,FindFile:ui,findfile:ui,wait:Vr,Wait:Vr},Bo=async(e,n,t={})=>{let i=t.mode?t.mode.toLowerCase():"flux",o=e.toLowerCase(),c=["memory","chat","savesummary","addmemscore","add_mem_score","ask","web_search","web_scrape","await","wait"].some(x=>o.includes(x))||o==="ask",u=["click","drag","scroll","keyboardtyping","keyboard_typing","keypress","key_press","recapturescreen","recapture_screen","computer","wait"].some(x=>o.includes(x));if(!c){if(i==="flow"){if(!(o.includes("write_pdf")||o.includes("write_docx")||o.includes("generate_image")))return`ERROR: Action [${e}] is a Workspace Tool and NOT available in Flow mode. Tell user to switch (\`/mode flux\`) to use this tool.`}else if(i==="icu"){if(!u)return`ERROR: Action [${e}] is not available in Computer Use mode. ICU mode only supports Computer Use tools (Click, Drag, Scroll, KeyboardTyping, KeyPress, RecaptureScreen).`}else if(o.includes("write_pdf")||o.includes("write_docx")||o.includes("generate_image"))return`ERROR: Action [${e}] is not available in ${t.mode||"Flux"} mode. Tell user to switch (\`/mode flow\`) for document generation.`}let h=Yr[e];if(!h){let x=["ReadFile","ReadFolder","FindFile","PatchFile","WriteFile","CodeSearch","Run","Goal","AskUser","WebSearch","WebScrape","WritePDF","WriteDoc","Click","Drag","Scroll","KeyboardTyping","KeyPress","RecaptureScreen","Wait","Invoke","InvokeSync","Await","GetProgress","Steer","Cancel","EmergencyRollback","Chat","Memory"],p={read:"ReadFile",view:"ReadFile",viewfile:"ReadFile",write:"WriteFile",edit:"PatchFile",patch:"PatchFile",update:"PatchFile",updatefile:"PatchFile",exec:"Run",command:"Run",bash:"Run",shell:"Run",powershell:"Run",search:"CodeSearch",grep:"CodeSearch",find:"FindFile",findfile:"FindFile",searchkeyword:"CodeSearch",folder:"ReadFolder",ls:"ReadFolder",dir:"ReadFolder",list:"ReadFolder",ask:"AskUser",question:"AskUser",pdf:"WritePDF",docx:"WriteDoc",doc:"WriteDoc",word:"WriteDoc",screenshot:"RecaptureScreen",screen:"RecaptureScreen",recapture:"RecaptureScreen",type:"KeyboardTyping",typing:"KeyboardTyping",keyboard:"KeyboardTyping",press:"KeyPress",key:"KeyPress",todo:"Goal",task:"Goal",subagent:"Invoke",agent:"Invoke"},f=o.replace(/[^a-z0-9]/g,""),s=p[f]||null;if(!s){let k=0,he=E=>{let D=new Set;for(let K=0;K<E.length-1;K++)D.add(E.slice(K,K+2));return D},y=he(f);for(let E of x){let D=E.toLowerCase().replace(/[^a-z0-9]/g,"");if(f===D){s=E;break}let K=0;(D.includes(f)||f.includes(D))&&(K+=.6);let O=he(D),T=0;for(let Ce of y)O.has(Ce)&&T++;let Se=2*T/(y.size+O.size||1);K=Math.max(K,Se),K>k&&K>=.35&&(k=K,s=E)}}let g=s?` Do you mean '${s}'?`:"";return`ERROR: Action [${e}] not found in registry.${g}`}try{return await(await h())(n,t)}catch(x){let p=x instanceof Error?x.message:String(x);return`ERROR: Execution failed for [${e}]: ${p}`}};var gi=e=>{if(!e||typeof e!="string")return!1;let n=e.trim().toLowerCase();return Object.keys(Yr).some(t=>t.toLowerCase()===n)};import W from"path";import Ae from"fs";import{execSync as fs}from"child_process";import ja from"gradient-string";var zr=["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 qr=["Beware the phantom processes.","A ghost in the shell has taken the wheel.","Blowing on the haunted cartridge...","Seven minutes in Raccoon City.","Wind's howling... in the terminal fans.","Slender Man was spotted in line 404.","The cake is a lie. The curse is real.","Don't look behind the server rack.","Exorcising memory leaks at 3 AM.","Pyramid Head reorganized your commit history.","It's dangerous to go alone! Take this flashlight.","YOU DIED. Respawning terminal session...","The Necronomicon evaluated to true.","Something wicked this way compiles.","Haunting your localhost with good vibes.","A full moon has risen over Git main.","Double, double toil and trouble; code fire burn.","Clickers heard in the directory tree.","Checking camera 2B for rogue animatronics.","The call is coming from inside the container.","Isaac Clarke is stomping on stubborn bugs.","Luigi vacuumed the ghosts out of RAM.","Trick or treat, give me clean code to greet.","Whispering incantations to the garbage collector.","Klaatu barada necktie... close enough.","Resurrecting deprecated APIs from the crypt.","The headless horseman forgot the return statement.","Castlevania whip cracking against network latency.","Slime mold crawling through the motherboard.","Carving a pixelated pumpkin into terminal history.","Burying undefined pointers in the pet sematary.","Spilling pumpkin spice on the CPU.","A vampire bat is draining system battery life.","Don't fall asleep at the keyboard tonight.","Silent Hill sirens sounding in the console.","Poltergeists rearranging terminal tabs.","Lighting the Black Flame Candle for autoExec.","Dusting cobwebs off legacy dependencies.","Here's Johnny! ...just checking build health.","Blood, sweat, and zero warnings.","The spirit box whispers: 'GIT PUSH FORCE'.","They're heeeere... in the stack trace.","It's alive! IT'S ALIVEEEE!","No merge conflicts in the graveyard.","Frankenstein's monster patched this logic.","Surviving Five Nights at Flux Flow.","Doom Slayer loading buckshot into cache.","The grim reaper spared your unused imports.","Candy corn lodged in mechanical switches.","May your latency be low and your crypt be quiet."];var Xr=[{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"]}],mo={Dark:{id:"Dark",name:"Dark (Default)",text:"white",textMuted:"gray",textDim:"grey",textInverted:"black",textExclusive:"#B5B8D9",textMutedExclusive:"#D4DEE7",border:"white",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:"#1e1e1e",highlightBg:"#2a2a2a",activeBg:"#3a3a3a",inputBg:"#555555",inputBorder:"#555555",inputText:"white",inputPlaceholder:"#cccccc",inputPrompt:"white",codeBg:"#1a1a1a",codeBorder:"#444444",userMsgBg:"#444444",userMsgBorder:"#444444",userMsgText:"white",diffRemovalBg:"#250808",diffAdditionBg:"#072410",diffRemovalText:"#885555",diffAdditionText:"#558866",diffRemovalHighlightColor:"#ff3333",diffRemovalHighlightBg:"#5a1818",diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:"#185a25",diffRemovalNum:"#d96868",diffAdditionNum:"#68d98c",diffRemovalPrefix:"#ff4d4d",diffAdditionPrefix:"#4dff88",primary:"white",secondary:"cyan",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"white",statusOff:"gray",logoTextAnsi:"\x1B[1;37m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#0077ff","#ff00ff"],toolFeedbackAnsi:"\x1B[95m"},Light:{id:"Light",name:"Light",text:"black",textMuted:"gray",textDim:"grey",textInverted:"white",border:"black",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:"#e5e5e5",highlightBg:"#d4d4d4",activeBg:"#c0c0c0",inputBg:"#d0d0d0",inputBorder:"#d0d0d0",inputText:"black",inputPlaceholder:"#555555",inputPrompt:"black",codeBg:"#e8e8e8",codeBorder:"#b0b0b0",userMsgBg:"#d0d0d0",userMsgBorder:"#d0d0d0",userMsgText:"black",diffRemovalBg:"#fce8e8",diffAdditionBg:"#e6f9e6",diffRemovalText:"#661111",diffAdditionText:"#115511",diffRemovalHighlightColor:"#440000",diffRemovalHighlightBg:"#f8b4b4",diffAdditionHighlightColor:"#003300",diffAdditionHighlightBg:"#a6ebad",diffRemovalNum:"#c02020",diffAdditionNum:"#188028",diffRemovalPrefix:"#d01010",diffAdditionPrefix:"#109020",primary:"black",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"black",statusOff:"gray",logoTextAnsi:"\x1B[1;30m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#0077ff","#ff00ff"],toolFeedbackAnsi:"\x1B[95m"},"GitHub Dark":{id:"GitHub Dark",name:"GitHub Dark",text:"#c9d1d9",textMuted:"#8b949e",textDim:"#6e7681",textInverted:"#0d1117",border:"#30363d",borderMuted:"#30363d",borderDim:"#21262d",bg:void 0,cardBg:"#161b22",highlightBg:"#21262d",activeBg:"#30363d",inputBg:"#21262d",inputBorder:"#21262d",inputText:"#c9d1d9",inputPlaceholder:"#8b949e",inputPrompt:"#58a6ff",codeBg:"#0d1117",codeBorder:"#30363d",userMsgBg:"#21262d",userMsgBorder:"#21262d",userMsgText:"#c9d1d9",diffRemovalBg:"#3c1e1e",diffAdditionBg:"#11381e",diffRemovalText:"#f85149",diffAdditionText:"#3fb950",diffRemovalHighlightColor:"#ff7b72",diffRemovalHighlightBg:"#701c1c",diffAdditionHighlightColor:"#56d364",diffAdditionHighlightBg:"#116329",diffRemovalNum:"#f85149",diffAdditionNum:"#3fb950",diffRemovalPrefix:"#f85149",diffAdditionPrefix:"#3fb950",primary:"#c9d1d9",secondary:"#58a6ff",accent:"#bc8cff",success:"#3fb950",warning:"#d29922",danger:"#f85149",info:"#58a6ff",statusOn:"#58a6ff",statusOff:"#8b949e",logoTextAnsi:"\x1B[1;36m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#2ea043","#56d364"],toolFeedbackAnsi:"\x1B[95m"},"GitHub Light":{id:"GitHub Light",name:"GitHub Light",text:"#24292f",textMuted:"#57606a",textDim:"#6e7781",textInverted:"#ffffff",border:"#d0d7de",borderMuted:"#d0d7de",borderDim:"#e1e4e8",bg:void 0,cardBg:"#f6f8fa",highlightBg:"#eaeef2",activeBg:"#d0d7de",inputBg:"#eaeef2",inputBorder:"#eaeef2",inputText:"#24292f",inputPlaceholder:"#57606a",inputPrompt:"#0969da",codeBg:"#ffffff",codeBorder:"#d0d7de",userMsgBg:"#eaeef2",userMsgBorder:"#eaeef2",userMsgText:"#24292f",diffRemovalBg:"#ffebe9",diffAdditionBg:"#e6ffec",diffRemovalText:"#cf222e",diffAdditionText:"#1a7f37",diffRemovalHighlightColor:"#82071e",diffRemovalHighlightBg:"#ffc1c0",diffAdditionHighlightColor:"#116329",diffAdditionHighlightBg:"#acf2bd",diffRemovalNum:"#cf222e",diffAdditionNum:"#1a7f37",diffRemovalPrefix:"#cf222e",diffAdditionPrefix:"#1a7f37",primary:"#24292f",secondary:"#0969da",accent:"#8250df",success:"#1a7f37",warning:"#9a6700",danger:"#cf222e",info:"#0969da",statusOn:"#0969da",statusOff:"#57606a",logoTextAnsi:"\x1B[1;34m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#1a7f37","#2da44e"],toolFeedbackAnsi:"\x1B[95m"},"Transparent Dark":{id:"Transparent Dark",name:"Transparent Dark",text:"white",textMuted:"gray",textDim:"grey",textInverted:"black",border:"gray",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:void 0,highlightBg:"#2a2a2a",activeBg:"#3a3a3a",inputBg:"#555555",inputBorder:"#555555",inputText:"white",inputPlaceholder:"#cccccc",inputPrompt:"white",codeBg:void 0,codeBorder:"gray",userMsgBg:"#555555",userMsgBorder:"#555555",userMsgText:"white",diffRemovalBg:void 0,diffAdditionBg:void 0,diffRemovalText:"#ff6666",diffAdditionText:"#66ff66",diffRemovalHighlightColor:"#ff3333",diffRemovalHighlightBg:"#3a1414",diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:"#143a14",diffRemovalNum:"#ff6666",diffAdditionNum:"#66ff66",diffRemovalPrefix:"#ff4d4d",diffAdditionPrefix:"#4dff88",primary:"white",secondary:"cyan",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"white",statusOff:"gray",logoTextAnsi:"\x1B[1;37m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#0077ff","#ff00ff"],toolFeedbackAnsi:"\x1B[95m"},"Transparent Light":{id:"Transparent Light",name:"Transparent Light",text:"black",textMuted:"gray",textDim:"grey",textInverted:"white",border:"gray",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:void 0,highlightBg:"#d4d4d4",activeBg:"#c0c0c0",inputBg:"#d0d0d0",inputBorder:"#d0d0d0",inputText:"black",inputPlaceholder:"#555555",inputPrompt:"black",codeBg:void 0,codeBorder:"gray",userMsgBg:"#d0d0d0",userMsgBorder:"#d0d0d0",userMsgText:"black",diffRemovalBg:void 0,diffAdditionBg:void 0,diffRemovalText:"#c02020",diffAdditionText:"#188028",diffRemovalHighlightColor:"#800000",diffRemovalHighlightBg:"#f5d0d0",diffAdditionHighlightColor:"#004000",diffAdditionHighlightBg:"#cceccc",diffRemovalNum:"#c02020",diffAdditionNum:"#188028",diffRemovalPrefix:"#d01010",diffAdditionPrefix:"#109020",primary:"black",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"black",statusOff:"gray",logoTextAnsi:"\x1B[1;30m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#0077ff","#ff00ff"],toolFeedbackAnsi:"\x1B[95m"},"Synthwave 84":{id:"Synthwave 84",name:"Synthwave 84",text:"#fdfdfd",textMuted:"#a08eb7",textDim:"#705c8a",textInverted:"#1a1025",textExclusive:"#e3dcf0",textMutedExclusive:"#b9abc9",border:"#fc28a8",borderMuted:"#a21568",borderDim:"#5c0a3a",bg:void 0,cardBg:"#261b38",highlightBg:"#35254d",activeBg:"#4c3570",inputBg:"#35254d",inputBorder:"#35254d",inputText:"#fdfdfd",inputPlaceholder:"#a08eb7",inputPrompt:"#03e8fc",codeBg:"#1e142b",codeBorder:"#a21568",userMsgBg:"#35254d",userMsgBorder:"#35254d",userMsgText:"#fdfdfd",diffRemovalBg:"#471434",diffAdditionBg:"#144743",diffRemovalText:"#ff4081",diffAdditionText:"#00e5ff",diffRemovalHighlightColor:"#ff79a1",diffRemovalHighlightBg:"#6b1e4e",diffAdditionHighlightColor:"#66f5ff",diffAdditionHighlightBg:"#1e6b65",diffRemovalNum:"#ff4081",diffAdditionNum:"#00e5ff",diffRemovalPrefix:"#ff79a1",diffAdditionPrefix:"#66f5ff",primary:"#fdfdfd",secondary:"#03e8fc",accent:"#fc28a8",success:"#00e5ff",warning:"#ffc107",danger:"#ff4081",info:"#b388ff",statusOn:"#03e8fc",statusOff:"#a08eb7",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#fc28a8","#03e8fc"],toolFeedbackAnsi:"\x1B[38;2;3;232;252m"},"Forest Sprite":{id:"Forest Sprite",name:"Forest Sprite",text:"#d6e6d1",textMuted:"#95b38d",textDim:"#628059",textInverted:"#161c14",textExclusive:"#eaf2e8",textMutedExclusive:"#a9c7a2",border:"#74a862",borderMuted:"#477038",borderDim:"#2b4720",bg:void 0,cardBg:"#1f291c",highlightBg:"#2a3826",activeBg:"#3a4d35",inputBg:"#2a3826",inputBorder:"#2a3826",inputText:"#d6e6d1",inputPlaceholder:"#95b38d",inputPrompt:"#8feb73",codeBg:"#161e14",codeBorder:"#477038",userMsgBg:"#2a3826",userMsgBorder:"#2a3826",userMsgText:"#d6e6d1",diffRemovalBg:"#3b231c",diffAdditionBg:"#203b1c",diffRemovalText:"#db6242",diffAdditionText:"#59cc3f",diffRemovalHighlightColor:"#f0896c",diffRemovalHighlightBg:"#5c362a",diffAdditionHighlightColor:"#80e368",diffAdditionHighlightBg:"#305929",diffRemovalNum:"#db6242",diffAdditionNum:"#59cc3f",diffRemovalPrefix:"#f0896c",diffAdditionPrefix:"#80e368",primary:"#d6e6d1",secondary:"#8feb73",accent:"#e69835",success:"#59cc3f",warning:"#e69835",danger:"#db6242",info:"#73b4eb",statusOn:"#8feb73",statusOff:"#95b38d",logoTextAnsi:"\x1B[1;32m",logoBodyAnsi:"\x1B[32m",logoMutedAnsi:"\x1B[90m",logoGradient:["#8feb73","#e69835"],toolFeedbackAnsi:"\x1B[38;2;143;235;115m"},Spookfest:{id:"Spookfest",name:"Spookfest \u{1F383}",text:"#ffeedd",textMuted:"#e09858",textDim:"#a6622b",textInverted:"#0d0702",textExclusive:"#fff3e6",textMutedExclusive:"#d4a276",border:"#ff7518",borderMuted:"#994409",borderDim:"#592502",bg:void 0,cardBg:"#1a0c02",highlightBg:"#2a1403",activeBg:"#3d1d05",inputBg:"#261203",inputBorder:"#261203",inputText:"#ffeedd",inputPlaceholder:"#a6622b",inputPrompt:"#ff7518",codeBg:"#120701",codeBorder:"#592502",userMsgBg:"#261203",userMsgBorder:"#261203",userMsgText:"#ffeedd",diffRemovalBg:"#3d0a0a",diffAdditionBg:"#1a330a",diffRemovalText:"#ff5555",diffAdditionText:"#73e639",diffRemovalHighlightColor:"#ff2222",diffRemovalHighlightBg:"#590e0e",diffAdditionHighlightColor:"#88ff3b",diffAdditionHighlightBg:"#244d0a",diffRemovalNum:"#ff5555",diffAdditionNum:"#73e639",diffRemovalPrefix:"#ff3333",diffAdditionPrefix:"#88ff3b",primary:"#ff7518",secondary:"#a855f7",accent:"#22c55e",success:"#22c55e",warning:"#f59e0b",danger:"#ef4444",info:"#a855f7",statusOn:"#ff7518",statusOff:"#703a08",logoTextAnsi:"\x1B[1;38;2;255;117;24m",logoBodyAnsi:"\x1B[38;2;255;140;26m",logoMutedAnsi:"\x1B[38;2;168;85;247m",logoGradient:["#ff7518","#a855f7"],toolFeedbackAnsi:"\x1B[38;2;255;117;24m"}};var mi=null;var pi=(e="Dark")=>{let n;e==="Mystery"||e==="Chaos"?(mi||(mi=Xr[Math.floor(Math.random()*Xr.length)]),n={...mi,id:"Mystery"}):(mi=null,mo[e]?n=mo[e]:e==="Halloween"?n=mo.Spookfest:e==="GitHub"?n=mo["GitHub Dark"]:e==="Transparent"?n=mo["Transparent Dark"]:n=mo.Dark);let t=n.codeText||n.secondary||n.info||n.logoGradient&&n.logoGradient[0]||"cyan",i=n.toolFeedbackAnsi||"\x1B[95m";return{...n,codeText:t,toolFeedbackAnsi:i}};var Ka=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",Wc=(e=2)=>{let n=Ka();return n==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)},Jr=new Date,Uo=Jr.getMonth(),Wo=Jr.getDate(),Va=Uo===9&&Wo>=15||Uo===10&&Wo<=1,rs=null;(process.env.SPOOKFEST==="true"||Va)&&(rs=await import("./halloween-MX3VNQRW.js"));var Gc=(e="...",n="Loading...",t="Dark")=>{let i=pi(t),o=n;if(n==="c_openai"||n==="Custom (OpenAI)")try{let K=Zo(Xo,{})?.systemSettings?.customOpenAIBaseUrl;K&&(o=K)}catch{}let r=i.logoTextAnsi,c=i.logoBodyAnsi,a=i.logoMutedAnsi,u="\x1B[0m",h=[" \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 "],x=t==="Spookfest"||i.id==="Spookfest"||t==="Halloween"||i.id==="Halloween",p=Uo===9&&Wo>=15||Uo===10&&Wo<=1,f=x&&p||process.env.SPOOKFEST==="true"&&x,s=h;if(f&&rs){process.env.HALLOWEEN_EEGG="true";let{halloweenArtSide:D,halloweenBat:K,halloweenArtUser:O}=rs;s=Math.random()>.9&&Uo===9&&Wo>=30?K:Math.random()>.5?D:O}else process.env.HALLOWEEN_EEGG="false";let g=f?qr:zr,k=g[Math.floor(Math.random()*g.length)],he=i.logoGradient||["#0077ff","#ff00ff"],y=ja(he).multiline(s.join(`
569
+ ${e}`:""}`.trim();var Rr=()=>import("./web_search-KBGH67IV.js").then(e=>e.web_search),vr=()=>import("./web_scrape-J3PL2PXT.js").then(e=>e.web_scrape),_r=()=>import("./memory-7YOYCOXE.js").then(e=>e.memory),Ir=()=>import("./chat-BA72I6O3.js").then(e=>e.chat),Mr=()=>import("./view_file-I77KYUO5.js").then(e=>e.view_file),Pr=()=>import("./write_file-D7QA2LB2.js").then(e=>e.write_file),Or=()=>import("./update_file-QKDDZKOX.js").then(e=>e.update_file),Lr=()=>import("./exec_command-6V5SM6WI.js").then(e=>e.exec_command),$r=()=>import("./read_folder-EI2CNHNS.js").then(e=>e.read_folder),os=()=>import("./ask_user-K2DLZF6H.js").then(e=>e.ask_user),Nr=()=>import("./write_pdf-TPGUF4VT.js").then(e=>e.write_pdf),Dr=()=>import("./write_docx-E3MTFXTQ.js").then(e=>e.write_docx),ai=()=>import("./search_keyword-O52M65TB.js").then(e=>e.search_keyword),Fr=()=>import("./generate_image-VW5VG6VI.js").then(e=>e.generate_image),li=()=>import("./saveSummary-W2JMDVZJ.js").then(e=>e.saveSummary),No=()=>import("./addMemScore-PBVNSFPN.js").then(e=>e.addMemScore),Br=()=>import("./file_map-UA4BA5OH.js").then(e=>e.file_map),ci=()=>import("./todo-CJLWLWJB.js").then(e=>e.todo),Ur=()=>import("./invokeSync-4JX2JCZC.js").then(e=>e.invokeSync),Ha=()=>import("./invoke-IUEAUE3X.js").then(e=>e.invoke),Wr=()=>import("./getProgress-J34K43Y7.js").then(e=>e.getProgress),ja=()=>import("./cancel-F3ZOEBKW.js").then(e=>e.cancel),Gr=()=>import("./emergency_rollback-ZHQXCIHW.js").then(e=>e.emergency_rollback),Do=()=>import("./awaitSubagent-JKQ2EHVY.js").then(e=>e.awaitSubagent),Fo=()=>import("./answerSubagent-BPNNJXPC.js").then(e=>e.answerSubagent),di=()=>import("./steerSubagent-UETXH2CB.js").then(e=>e.steerSubagent),fi=()=>import("./computer_action-WNXZNAIZ.js").then(e=>e.computer_action),Hr=()=>import("./click-R35XTYKT.js").then(e=>e.click),jr=()=>import("./drag-IB5WSI6F.js").then(e=>e.drag),Kr=()=>import("./scroll-GIP2J2QN.js").then(e=>e.scroll),is=()=>import("./keyboard_typing-YHYH7O66.js").then(e=>e.keyboard_typing),ss=()=>import("./key_press-XDYBP7DW.js").then(e=>e.key_press),rs=()=>import("./recapture_screen-F6ZPZU56.js").then(e=>e.recapture_screen),ui=()=>import("./find_file-HYHHFHUJ.js").then(e=>e.find_file),Vr=()=>import("./wait-TJR6LAR4.js").then(e=>e.wait),Yr={web_search:Rr,web_scrape:vr,memory:_r,chat:Ir,view_file:Mr,write_file:Pr,update_file:Or,exec_command:Lr,read_folder:$r,write_pdf:Nr,write_docx:Dr,search_keyword:ai,generate_image:Fr,saveSummary:li,addMemScore:No,file_map:Br,todo:ci,Todo:ci,goal:ci,Goal:ci,invokeSync:Ur,invoke:Ha,getProgress:Wr,cancel:ja,awaitSubagent:Do,answerSubagent:Fo,steerSubagent:di,computer_action:fi,computer_use:fi,ComputerAction:fi,ComputerUse:fi,click:Hr,Click:Hr,drag:jr,Drag:jr,scroll:Kr,Scroll:Kr,keyboard_typing:is,KeyboardTyping:is,keyboardtyping:is,key_press:ss,KeyPress:ss,keypress:ss,recapture_screen:rs,RecaptureScreen:rs,recapturescreen:rs,invoke_sync:Ur,get_progress:Wr,await_subagent:Do,answer_subagent:Fo,steer_subagent:di,steer:di,Steer:di,ask:os,Ask:os,AskUser:os,WebSearch:Rr,WebScrape:vr,ReadFile:Mr,ReadFolder:$r,WriteFile:Pr,PatchFile:Or,WritePDF:Nr,WriteDoc:Dr,Run:Lr,SearchKeyword:ai,CodeSearch:ai,code_search:ai,Memory:_r,Chat:Ir,GenerateImage:Fr,saveSumary:li,SaveSummary:li,SaveSumary:li,add_mem_score:No,AddMemScore:No,addMemoryScore:No,AddMemoryScore:No,FileMap:Br,answer:Fo,Answer:Fo,AnswerSubagent:Fo,await:Do,Await:Do,AwaitSubagent:Do,EmergencyRollback:Gr,emergency_rollback:Gr,find_file:ui,findFile:ui,FindFile:ui,findfile:ui,wait:Vr,Wait:Vr},Bo=async(e,n,t={})=>{let i=t.mode?t.mode.toLowerCase():"flux",o=e.toLowerCase(),d=["memory","chat","savesummary","addmemscore","add_mem_score","ask","web_search","web_scrape","await","wait"].some(x=>o.includes(x))||o==="ask",u=["click","drag","scroll","keyboardtyping","keyboard_typing","keypress","key_press","recapturescreen","recapture_screen","computer","wait"].some(x=>o.includes(x));if(!d){if(i==="flow"){if(!(o.includes("write_pdf")||o.includes("write_docx")||o.includes("generate_image")))return`ERROR: Action [${e}] is a Workspace Tool and NOT available in Flow mode. Tell user to switch (\`/mode flux\`) to use this tool.`}else if(i==="icu"){if(!u)return`ERROR: Action [${e}] is not available in Computer Use mode. ICU mode only supports Computer Use tools (Click, Drag, Scroll, KeyboardTyping, KeyPress, RecaptureScreen).`}else if(o.includes("write_pdf")||o.includes("write_docx")||o.includes("generate_image"))return`ERROR: Action [${e}] is not available in ${t.mode||"Flux"} mode. Tell user to switch (\`/mode flow\`) for document generation.`}let h=Yr[e];if(!h){let x=["ReadFile","ReadFolder","FindFile","PatchFile","WriteFile","CodeSearch","Run","Goal","AskUser","WebSearch","WebScrape","WritePDF","WriteDoc","Click","Drag","Scroll","KeyboardTyping","KeyPress","RecaptureScreen","Wait","Invoke","InvokeSync","Await","GetProgress","Steer","Cancel","EmergencyRollback","Chat","Memory"],p={read:"ReadFile",view:"ReadFile",viewfile:"ReadFile",write:"WriteFile",edit:"PatchFile",patch:"PatchFile",update:"PatchFile",updatefile:"PatchFile",exec:"Run",command:"Run",bash:"Run",shell:"Run",powershell:"Run",search:"CodeSearch",grep:"CodeSearch",find:"FindFile",findfile:"FindFile",searchkeyword:"CodeSearch",folder:"ReadFolder",ls:"ReadFolder",dir:"ReadFolder",list:"ReadFolder",ask:"AskUser",question:"AskUser",pdf:"WritePDF",docx:"WriteDoc",doc:"WriteDoc",word:"WriteDoc",screenshot:"RecaptureScreen",screen:"RecaptureScreen",recapture:"RecaptureScreen",type:"KeyboardTyping",typing:"KeyboardTyping",keyboard:"KeyboardTyping",press:"KeyPress",key:"KeyPress",todo:"Goal",task:"Goal",subagent:"Invoke",agent:"Invoke"},f=o.replace(/[^a-z0-9]/g,""),s=p[f]||null;if(!s){let k=0,me=E=>{let N=new Set;for(let H=0;H<E.length-1;H++)N.add(E.slice(H,H+2));return N},y=me(f);for(let E of x){let N=E.toLowerCase().replace(/[^a-z0-9]/g,"");if(f===N){s=E;break}let H=0;(N.includes(f)||f.includes(N))&&(H+=.6);let O=me(N),T=0;for(let Ae of y)O.has(Ae)&&T++;let be=2*T/(y.size+O.size||1);H=Math.max(H,be),H>k&&H>=.35&&(k=H,s=E)}}let g=s?` Do you mean '${s}'?`:"";return`ERROR: Action [${e}] not found in registry.${g}`}try{return await(await h())(n,t)}catch(x){let p=x instanceof Error?x.message:String(x);return`ERROR: Execution failed for [${e}]: ${p}`}};var gi=e=>{if(!e||typeof e!="string")return!1;let n=e.trim().toLowerCase();return Object.keys(Yr).some(t=>t.toLowerCase()===n)};import V from"path";import ke from"fs";import{execSync as us}from"child_process";import Ka from"gradient-string";var zr=["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 qr=["Beware the phantom processes.","A ghost in the shell has taken the wheel.","Blowing on the haunted cartridge...","Seven minutes in Raccoon City.","Wind's howling... in the terminal fans.","Slender Man was spotted in line 404.","The cake is a lie. The curse is real.","Don't look behind the server rack.","Exorcising memory leaks at 3 AM.","Pyramid Head reorganized your commit history.","It's dangerous to go alone! Take this flashlight.","YOU DIED. Respawning terminal session...","The Necronomicon evaluated to true.","Something wicked this way compiles.","Haunting your localhost with good vibes.","A full moon has risen over Git main.","Double, double toil and trouble; code fire burn.","Clickers heard in the directory tree.","Checking camera 2B for rogue animatronics.","The call is coming from inside the container.","Isaac Clarke is stomping on stubborn bugs.","Luigi vacuumed the ghosts out of RAM.","Trick or treat, give me clean code to greet.","Whispering incantations to the garbage collector.","Klaatu barada necktie... close enough.","Resurrecting deprecated APIs from the crypt.","The headless horseman forgot the return statement.","Castlevania whip cracking against network latency.","Slime mold crawling through the motherboard.","Carving a pixelated pumpkin into terminal history.","Burying undefined pointers in the pet sematary.","Spilling pumpkin spice on the CPU.","A vampire bat is draining system battery life.","Don't fall asleep at the keyboard tonight.","Silent Hill sirens sounding in the console.","Poltergeists rearranging terminal tabs.","Lighting the Black Flame Candle for autoExec.","Dusting cobwebs off legacy dependencies.","Here's Johnny! ...just checking build health.","Blood, sweat, and zero warnings.","The spirit box whispers: 'GIT PUSH FORCE'.","They're heeeere... in the stack trace.","It's alive! IT'S ALIVEEEE!","No merge conflicts in the graveyard.","Frankenstein's monster patched this logic.","Surviving Five Nights at Flux Flow.","Doom Slayer loading buckshot into cache.","The grim reaper spared your unused imports.","Candy corn lodged in mechanical switches.","May your latency be low and your crypt be quiet."];var Xr=[{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"]}],go={Dark:{id:"Dark",name:"Dark (Default)",text:"white",textMuted:"gray",textDim:"grey",textInverted:"black",textExclusive:"#B5B8D9",textMutedExclusive:"#D4DEE7",border:"white",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:"#1e1e1e",highlightBg:"#2a2a2a",activeBg:"#3a3a3a",inputBg:"#555555",inputBorder:"#555555",inputText:"white",inputPlaceholder:"#cccccc",inputPrompt:"white",codeBg:"#1a1a1a",codeBorder:"#444444",userMsgBg:"#444444",userMsgBorder:"#444444",userMsgText:"white",diffRemovalBg:"#250808",diffAdditionBg:"#072410",diffRemovalText:"#885555",diffAdditionText:"#558866",diffRemovalHighlightColor:"#ff3333",diffRemovalHighlightBg:"#5a1818",diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:"#185a25",diffRemovalNum:"#d96868",diffAdditionNum:"#68d98c",diffRemovalPrefix:"#ff4d4d",diffAdditionPrefix:"#4dff88",primary:"white",secondary:"cyan",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"white",statusOff:"gray",logoTextAnsi:"\x1B[1;37m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#0077ff","#ff00ff"],toolFeedbackAnsi:"\x1B[95m"},Light:{id:"Light",name:"Light",text:"black",textMuted:"gray",textDim:"grey",textInverted:"white",border:"black",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:"#e5e5e5",highlightBg:"#d4d4d4",activeBg:"#c0c0c0",inputBg:"#d0d0d0",inputBorder:"#d0d0d0",inputText:"black",inputPlaceholder:"#555555",inputPrompt:"black",codeBg:"#e8e8e8",codeBorder:"#b0b0b0",userMsgBg:"#d0d0d0",userMsgBorder:"#d0d0d0",userMsgText:"black",diffRemovalBg:"#fce8e8",diffAdditionBg:"#e6f9e6",diffRemovalText:"#661111",diffAdditionText:"#115511",diffRemovalHighlightColor:"#440000",diffRemovalHighlightBg:"#f8b4b4",diffAdditionHighlightColor:"#003300",diffAdditionHighlightBg:"#a6ebad",diffRemovalNum:"#c02020",diffAdditionNum:"#188028",diffRemovalPrefix:"#d01010",diffAdditionPrefix:"#109020",primary:"black",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"black",statusOff:"gray",logoTextAnsi:"\x1B[1;30m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#0077ff","#ff00ff"],toolFeedbackAnsi:"\x1B[95m"},"GitHub Dark":{id:"GitHub Dark",name:"GitHub Dark",text:"#c9d1d9",textMuted:"#8b949e",textDim:"#6e7681",textInverted:"#0d1117",border:"#30363d",borderMuted:"#30363d",borderDim:"#21262d",bg:void 0,cardBg:"#161b22",highlightBg:"#21262d",activeBg:"#30363d",inputBg:"#21262d",inputBorder:"#21262d",inputText:"#c9d1d9",inputPlaceholder:"#8b949e",inputPrompt:"#58a6ff",codeBg:"#0d1117",codeBorder:"#30363d",userMsgBg:"#21262d",userMsgBorder:"#21262d",userMsgText:"#c9d1d9",diffRemovalBg:"#3c1e1e",diffAdditionBg:"#11381e",diffRemovalText:"#f85149",diffAdditionText:"#3fb950",diffRemovalHighlightColor:"#ff7b72",diffRemovalHighlightBg:"#701c1c",diffAdditionHighlightColor:"#56d364",diffAdditionHighlightBg:"#116329",diffRemovalNum:"#f85149",diffAdditionNum:"#3fb950",diffRemovalPrefix:"#f85149",diffAdditionPrefix:"#3fb950",primary:"#c9d1d9",secondary:"#58a6ff",accent:"#bc8cff",success:"#3fb950",warning:"#d29922",danger:"#f85149",info:"#58a6ff",statusOn:"#58a6ff",statusOff:"#8b949e",logoTextAnsi:"\x1B[1;36m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#2ea043","#56d364"],toolFeedbackAnsi:"\x1B[95m"},"GitHub Light":{id:"GitHub Light",name:"GitHub Light",text:"#24292f",textMuted:"#57606a",textDim:"#6e7781",textInverted:"#ffffff",border:"#d0d7de",borderMuted:"#d0d7de",borderDim:"#e1e4e8",bg:void 0,cardBg:"#f6f8fa",highlightBg:"#eaeef2",activeBg:"#d0d7de",inputBg:"#eaeef2",inputBorder:"#eaeef2",inputText:"#24292f",inputPlaceholder:"#57606a",inputPrompt:"#0969da",codeBg:"#ffffff",codeBorder:"#d0d7de",userMsgBg:"#eaeef2",userMsgBorder:"#eaeef2",userMsgText:"#24292f",diffRemovalBg:"#ffebe9",diffAdditionBg:"#e6ffec",diffRemovalText:"#cf222e",diffAdditionText:"#1a7f37",diffRemovalHighlightColor:"#82071e",diffRemovalHighlightBg:"#ffc1c0",diffAdditionHighlightColor:"#116329",diffAdditionHighlightBg:"#acf2bd",diffRemovalNum:"#cf222e",diffAdditionNum:"#1a7f37",diffRemovalPrefix:"#cf222e",diffAdditionPrefix:"#1a7f37",primary:"#24292f",secondary:"#0969da",accent:"#8250df",success:"#1a7f37",warning:"#9a6700",danger:"#cf222e",info:"#0969da",statusOn:"#0969da",statusOff:"#57606a",logoTextAnsi:"\x1B[1;34m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#1a7f37","#2da44e"],toolFeedbackAnsi:"\x1B[95m"},"Transparent Dark":{id:"Transparent Dark",name:"Transparent Dark",text:"white",textMuted:"gray",textDim:"grey",textInverted:"black",border:"gray",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:void 0,highlightBg:"#2a2a2a",activeBg:"#3a3a3a",inputBg:"#555555",inputBorder:"#555555",inputText:"white",inputPlaceholder:"#cccccc",inputPrompt:"white",codeBg:void 0,codeBorder:"gray",userMsgBg:"#555555",userMsgBorder:"#555555",userMsgText:"white",diffRemovalBg:void 0,diffAdditionBg:void 0,diffRemovalText:"#ff6666",diffAdditionText:"#66ff66",diffRemovalHighlightColor:"#ff3333",diffRemovalHighlightBg:"#3a1414",diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:"#143a14",diffRemovalNum:"#ff6666",diffAdditionNum:"#66ff66",diffRemovalPrefix:"#ff4d4d",diffAdditionPrefix:"#4dff88",primary:"white",secondary:"cyan",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"white",statusOff:"gray",logoTextAnsi:"\x1B[1;37m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#0077ff","#ff00ff"],toolFeedbackAnsi:"\x1B[95m"},"Transparent Light":{id:"Transparent Light",name:"Transparent Light",text:"black",textMuted:"gray",textDim:"grey",textInverted:"white",border:"gray",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:void 0,highlightBg:"#d4d4d4",activeBg:"#c0c0c0",inputBg:"#d0d0d0",inputBorder:"#d0d0d0",inputText:"black",inputPlaceholder:"#555555",inputPrompt:"black",codeBg:void 0,codeBorder:"gray",userMsgBg:"#d0d0d0",userMsgBorder:"#d0d0d0",userMsgText:"black",diffRemovalBg:void 0,diffAdditionBg:void 0,diffRemovalText:"#c02020",diffAdditionText:"#188028",diffRemovalHighlightColor:"#800000",diffRemovalHighlightBg:"#f5d0d0",diffAdditionHighlightColor:"#004000",diffAdditionHighlightBg:"#cceccc",diffRemovalNum:"#c02020",diffAdditionNum:"#188028",diffRemovalPrefix:"#d01010",diffAdditionPrefix:"#109020",primary:"black",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"black",statusOff:"gray",logoTextAnsi:"\x1B[1;30m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#0077ff","#ff00ff"],toolFeedbackAnsi:"\x1B[95m"},"Synthwave 84":{id:"Synthwave 84",name:"Synthwave 84",text:"#fdfdfd",textMuted:"#a08eb7",textDim:"#705c8a",textInverted:"#1a1025",textExclusive:"#e3dcf0",textMutedExclusive:"#b9abc9",border:"#fc28a8",borderMuted:"#a21568",borderDim:"#5c0a3a",bg:void 0,cardBg:"#261b38",highlightBg:"#35254d",activeBg:"#4c3570",inputBg:"#35254d",inputBorder:"#35254d",inputText:"#fdfdfd",inputPlaceholder:"#a08eb7",inputPrompt:"#03e8fc",codeBg:"#1e142b",codeBorder:"#a21568",userMsgBg:"#35254d",userMsgBorder:"#35254d",userMsgText:"#fdfdfd",diffRemovalBg:"#471434",diffAdditionBg:"#144743",diffRemovalText:"#ff4081",diffAdditionText:"#00e5ff",diffRemovalHighlightColor:"#ff79a1",diffRemovalHighlightBg:"#6b1e4e",diffAdditionHighlightColor:"#66f5ff",diffAdditionHighlightBg:"#1e6b65",diffRemovalNum:"#ff4081",diffAdditionNum:"#00e5ff",diffRemovalPrefix:"#ff79a1",diffAdditionPrefix:"#66f5ff",primary:"#fdfdfd",secondary:"#03e8fc",accent:"#fc28a8",success:"#00e5ff",warning:"#ffc107",danger:"#ff4081",info:"#b388ff",statusOn:"#03e8fc",statusOff:"#a08eb7",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#fc28a8","#03e8fc"],toolFeedbackAnsi:"\x1B[38;2;3;232;252m"},"Forest Sprite":{id:"Forest Sprite",name:"Forest Sprite",text:"#d6e6d1",textMuted:"#95b38d",textDim:"#628059",textInverted:"#161c14",textExclusive:"#eaf2e8",textMutedExclusive:"#a9c7a2",border:"#74a862",borderMuted:"#477038",borderDim:"#2b4720",bg:void 0,cardBg:"#1f291c",highlightBg:"#2a3826",activeBg:"#3a4d35",inputBg:"#2a3826",inputBorder:"#2a3826",inputText:"#d6e6d1",inputPlaceholder:"#95b38d",inputPrompt:"#8feb73",codeBg:"#161e14",codeBorder:"#477038",userMsgBg:"#2a3826",userMsgBorder:"#2a3826",userMsgText:"#d6e6d1",diffRemovalBg:"#3b231c",diffAdditionBg:"#203b1c",diffRemovalText:"#db6242",diffAdditionText:"#59cc3f",diffRemovalHighlightColor:"#f0896c",diffRemovalHighlightBg:"#5c362a",diffAdditionHighlightColor:"#80e368",diffAdditionHighlightBg:"#305929",diffRemovalNum:"#db6242",diffAdditionNum:"#59cc3f",diffRemovalPrefix:"#f0896c",diffAdditionPrefix:"#80e368",primary:"#d6e6d1",secondary:"#8feb73",accent:"#e69835",success:"#59cc3f",warning:"#e69835",danger:"#db6242",info:"#73b4eb",statusOn:"#8feb73",statusOff:"#95b38d",logoTextAnsi:"\x1B[1;32m",logoBodyAnsi:"\x1B[32m",logoMutedAnsi:"\x1B[90m",logoGradient:["#8feb73","#e69835"],toolFeedbackAnsi:"\x1B[38;2;143;235;115m"},Spookfest:{id:"Spookfest",name:"Spookfest \u{1F383}",text:"#ffeedd",textMuted:"#e09858",textDim:"#a6622b",textInverted:"#0d0702",textExclusive:"#fff3e6",textMutedExclusive:"#d4a276",border:"#ff7518",borderMuted:"#994409",borderDim:"#592502",bg:void 0,cardBg:"#1a0c02",highlightBg:"#2a1403",activeBg:"#3d1d05",inputBg:"#261203",inputBorder:"#261203",inputText:"#ffeedd",inputPlaceholder:"#a6622b",inputPrompt:"#ff7518",codeBg:"#120701",codeBorder:"#592502",userMsgBg:"#261203",userMsgBorder:"#261203",userMsgText:"#ffeedd",diffRemovalBg:"#3d0a0a",diffAdditionBg:"#1a330a",diffRemovalText:"#ff5555",diffAdditionText:"#73e639",diffRemovalHighlightColor:"#ff2222",diffRemovalHighlightBg:"#590e0e",diffAdditionHighlightColor:"#88ff3b",diffAdditionHighlightBg:"#244d0a",diffRemovalNum:"#ff5555",diffAdditionNum:"#73e639",diffRemovalPrefix:"#ff3333",diffAdditionPrefix:"#88ff3b",primary:"#ff7518",secondary:"#a855f7",accent:"#22c55e",success:"#22c55e",warning:"#f59e0b",danger:"#ef4444",info:"#a855f7",statusOn:"#ff7518",statusOff:"#703a08",logoTextAnsi:"\x1B[1;38;2;255;117;24m",logoBodyAnsi:"\x1B[38;2;255;140;26m",logoMutedAnsi:"\x1B[38;2;168;85;247m",logoGradient:["#ff7518","#a855f7"],toolFeedbackAnsi:"\x1B[38;2;255;117;24m"}};var mi=null;var pi=(e="Dark")=>{let n;e==="Mystery"||e==="Chaos"?(mi||(mi=Xr[Math.floor(Math.random()*Xr.length)]),n={...mi,id:"Mystery"}):(mi=null,go[e]?n=go[e]:e==="Halloween"?n=go.Spookfest:e==="GitHub"?n=go["GitHub Dark"]:e==="Transparent"?n=go["Transparent Dark"]:n=go.Dark);let t=n.codeText||n.secondary||n.info||n.logoGradient&&n.logoGradient[0]||"cyan",i=n.toolFeedbackAnsi||"\x1B[95m";return{...n,codeText:t,toolFeedbackAnsi:i}};var Va=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",Gc=(e=2)=>{let n=Va();return n==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)},Jr=new Date,Uo=Jr.getMonth(),Wo=Jr.getDate(),Ya=Uo===9&&Wo>=15||Uo===10&&Wo<=1,as=null;(process.env.SPOOKFEST==="true"||Ya)&&(as=await import("./halloween-MX3VNQRW.js"));var Hc=(e="...",n="Loading...",t="Dark")=>{let i=pi(t),o=n;if(n==="c_openai"||n==="Custom (OpenAI)")try{let H=Zo(Xo,{})?.systemSettings?.customOpenAIBaseUrl;H&&(o=H)}catch{}let r=i.logoTextAnsi,d=i.logoBodyAnsi,a=i.logoMutedAnsi,u="\x1B[0m",h=[" \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 "],x=t==="Spookfest"||i.id==="Spookfest"||t==="Halloween"||i.id==="Halloween",p=Uo===9&&Wo>=15||Uo===10&&Wo<=1,f=x&&p||process.env.SPOOKFEST==="true"&&x,s=h;if(f&&as){process.env.HALLOWEEN_EEGG="true";let{halloweenArtSide:N,halloweenBat:H,halloweenArtUser:O}=as;s=Math.random()>.9&&Uo===9&&Wo>=30?H:Math.random()>.5?N:O}else process.env.HALLOWEEN_EEGG="false";let g=f?qr:zr,k=g[Math.floor(Math.random()*g.length)],me=i.logoGradient||["#0077ff","#ff00ff"],y=Ka(me).multiline(s.join(`
570
570
  `)).split(`
571
- `),E=D=>`${a}${D}${u}`;return`${y[0]}
571
+ `),E=N=>`${a}${N}${u}`;return`${y[0]}
572
572
  ${y[1]} ${r}Selected ${f?"Pumpkin":"Provider"}: ${o}${u}
573
573
  ${y[2]}
574
574
  ${y[3]} ${r}FluxFlow${f?": Spookfest":""} ${E("v"+e)}${u}
575
575
  ${y[4]}
576
- ${y[5]} ${c}See /help for additional commands.${u}
576
+ ${y[5]} ${d}See /help for additional commands.${u}
577
577
  ${y[6]} ${E(k)}
578
578
  ${y[7]}
579
- `};import{structuredPatch as Ja}from"diff";import as from"path";import Ya from"fs";var za=e=>{try{return Ya.readdirSync(e,{withFileTypes:!0})}catch{return[]}},ls=(e,n=4,t=1,i=za,o=[],r=null)=>{let c=r||i(e),a=" ".repeat(t-1),u=t===1?new Set([...To,...o,...Ao(e),...Ao(process.cwd())]):o instanceof Set?o:new Set([...To,...o]),h=O=>u.has(O),x=c.filter(O=>!h(O.name)),p=c.filter(O=>h(O.name)).length,f=x.filter(O=>!O.isDirectory()).map(O=>O.name).sort(),s=x.filter(O=>O.isDirectory()).sort((O,T)=>O.name.localeCompare(T.name)),g=O=>{let T=O.length;if(T===0)return"no files";let Se=Array.from(new Set(O.map(Me=>{let Je=typeof Me=="string"?Me:Me.name;return as.extname(Je).slice(1)}).filter(Boolean))).sort(),Ce="*";return Se.length===1?Ce=`*.${Se[0]}`:Se.length>1&&(Ce=`*.{${Se.join(", ")}}`),T===1?Ce:`${Ce} ${T} files`},k="";if(t===1){let O=f.join(", "),T=p>0?` [${p} ignored]`:"";(O||T)&&(k+=`${a}${O?O+(T?`${T}`:""):T.trim()}
579
+ `};import{structuredPatch as Qa}from"diff";import ls from"path";import za from"fs";var qa=e=>{try{return za.readdirSync(e,{withFileTypes:!0})}catch{return[]}},cs=(e,n=4,t=1,i=qa,o=[],r=null)=>{let d=r||i(e),a=" ".repeat(t-1),u=t===1?new Set([...To,...o,...Ao(e),...Ao(process.cwd())]):o instanceof Set?o:new Set([...To,...o]),h=O=>u.has(O),x=d.filter(O=>!h(O.name)),p=d.filter(O=>h(O.name)).length,f=x.filter(O=>!O.isDirectory()).map(O=>O.name).sort(),s=x.filter(O=>O.isDirectory()).sort((O,T)=>O.name.localeCompare(T.name)),g=O=>{let T=O.length;if(T===0)return"no files";let be=Array.from(new Set(O.map(_e=>{let Ye=typeof _e=="string"?_e:_e.name;return ls.extname(Ye).slice(1)}).filter(Boolean))).sort(),Ae="*";return be.length===1?Ae=`*.${be[0]}`:be.length>1&&(Ae=`*.{${be.join(", ")}}`),T===1?Ae:`${Ae} ${T} files`},k="";if(t===1){let O=f.join(", "),T=p>0?` [${p} ignored]`:"";(O||T)&&(k+=`${a}${O?O+(T?`${T}`:""):T.trim()}
580
580
  `)}else f.length>0&&(k+=`${a}[${g(f)}]
581
- `);let he=10,y=s.slice(0,he),E=s.length>he,D=[],K=[];for(let O of y){let T=as.join(e,O.name),Se=O.name,Ce=t,Me=i(T),Je=Me.filter(fe=>!h(fe.name)),G=Je.filter(fe=>fe.isDirectory()),b=Je.filter(fe=>!fe.isDirectory());for(;b.length===0&&G.length===1&&Ce<n;)Se=`${Se}/${G[0].name}`,T=as.join(T,G[0].name),Ce++,Me=i(T),Je=Me.filter(fe=>!h(fe.name)),G=Je.filter(fe=>fe.isDirectory()),b=Je.filter(fe=>!fe.isDirectory());let ht=G.length>0;if(ht&&Ce<n)K.push({displayName:Se,subDirPath:T,subEntries:Me,nextDepth:Ce+1});else{let fe=g(b),q=ht&&Ce>=n?" ...max scan depth":"";D.push(`${Se}/${fe}${q}`)}}D.length>0&&(k+=`${a}${D.join(", ")}
582
- `);for(let{displayName:O,subDirPath:T,subEntries:Se,nextDepth:Ce}of K)k+=`${a}${O}/
583
- `,k+=ls(T,n,Ce,i,u,Se);return E&&(k+=`${a}...max scan width, ReadFolder if needed
584
- `),k};import cs from"path";import qa from"fs";var Xa=e=>{try{return qa.readdirSync(e,{withFileTypes:!0})}catch{return[]}},ds=(e,n,t="",i=1,o=Xa,r=[])=>{let c=o(e),a=cs.sep;if(c.length>100)return`${t}\u2514\u2500\u2500 ${cs.basename(e)}${a} ...100+ files...
585
- `;let u="",h=r,x=c.filter(s=>!h.includes(s.name)&&!s.name.startsWith(".")),p=c.filter(s=>h.includes(s.name)||s.name.startsWith(".")).map(s=>s.name).sort();x.sort((s,g)=>s.isDirectory()&&!g.isDirectory()?-1:!s.isDirectory()&&g.isDirectory()?1:s.name.localeCompare(g.name));let f=[...x.map(s=>({name:s.name,isDir:s.isDirectory()})),...p.map(s=>({name:s,isDir:!0,isCollapsed:!0}))];return f.forEach((s,g)=>{let k=g===f.length-1,he=cs.join(e,s.name),y=k?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",E=t+(k?" ":"\u2502 ");if(s.isCollapsed){u+=`${t}${y}${s.name}${a}...
581
+ `);let me=10,y=s.slice(0,me),E=s.length>me,N=[],H=[];for(let O of y){let T=ls.join(e,O.name),be=O.name,Ae=t,_e=i(T),Ye=_e.filter(fe=>!h(fe.name)),B=Ye.filter(fe=>fe.isDirectory()),b=Ye.filter(fe=>!fe.isDirectory());for(;b.length===0&&B.length===1&&Ae<n;)be=`${be}/${B[0].name}`,T=ls.join(T,B[0].name),Ae++,_e=i(T),Ye=_e.filter(fe=>!h(fe.name)),B=Ye.filter(fe=>fe.isDirectory()),b=Ye.filter(fe=>!fe.isDirectory());let ut=B.length>0;if(ut&&Ae<n)H.push({displayName:be,subDirPath:T,subEntries:_e,nextDepth:Ae+1});else{let fe=g(b),Y=ut&&Ae>=n?" ...max scan depth":"";N.push(`${be}/${fe}${Y}`)}}N.length>0&&(k+=`${a}${N.join(", ")}
582
+ `);for(let{displayName:O,subDirPath:T,subEntries:be,nextDepth:Ae}of H)k+=`${a}${O}/
583
+ `,k+=cs(T,n,Ae,i,u,be);return E&&(k+=`${a}...max scan width, ReadFolder if needed
584
+ `),k};import ds from"path";import Xa from"fs";var Ja=e=>{try{return Xa.readdirSync(e,{withFileTypes:!0})}catch{return[]}},fs=(e,n,t="",i=1,o=Ja,r=[])=>{let d=o(e),a=ds.sep;if(d.length>100)return`${t}\u2514\u2500\u2500 ${ds.basename(e)}${a} ...100+ files...
585
+ `;let u="",h=r,x=d.filter(s=>!h.includes(s.name)&&!s.name.startsWith(".")),p=d.filter(s=>h.includes(s.name)||s.name.startsWith(".")).map(s=>s.name).sort();x.sort((s,g)=>s.isDirectory()&&!g.isDirectory()?-1:!s.isDirectory()&&g.isDirectory()?1:s.name.localeCompare(g.name));let f=[...x.map(s=>({name:s.name,isDir:s.isDirectory()})),...p.map(s=>({name:s,isDir:!0,isCollapsed:!0}))];return f.forEach((s,g)=>{let k=g===f.length-1,me=ds.join(e,s.name),y=k?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",E=t+(k?" ":"\u2502 ");if(s.isCollapsed){u+=`${t}${y}${s.name}${a}...
586
586
  `;return}s.isDir?i>n?u+=`${t}${y}${s.name}${a} ...depth exceeded...
587
- `:o(he).length>80?u+=`${t}${y}${s.name}${a} ...80+ files...
587
+ `:o(me).length>80?u+=`${t}${y}${s.name}${a} ...80+ files...
588
588
  `:(u+=`${t}${y}${s.name}${a}
589
- `,u+=ds(he,n,E,i+1,o,r)):u+=`${t}${y}${s.name}
590
- `}),u};var Qa={Ollama:()=>import("./ollama-QB7WX7VD.js").then(e=>e.getOllamaStream),OpenRouter:()=>import("./openrouter-6MRG4RT6.js").then(e=>e.getOpenRouterStream),DeepSeek:()=>import("./deepseek-WNWZJTNE.js").then(e=>e.getDeepSeekStream),Mistral:()=>import("./mistral-YTTOZB2J.js").then(e=>e.getMistralStream),NVIDIA:()=>import("./nvidia-ON4Q6Q26.js").then(e=>e.getNVIDIAStream),NVIDIA_wrap:()=>import("./nvidia-ON4Q6Q26.js").then(e=>e.wrapNvidiaStreamWithQueueDepth),InferX:()=>import("./inferx-HP5AGET3.js").then(e=>e.getInferXStream),SenseNova:()=>import("./sensenova-3K44URJQ.js").then(e=>e.getSenseNovaStream),AIHubMix:()=>import("./aihubmix-TETL5QYQ.js").then(e=>e.getAIHubMixStream),Poolside:()=>import("./poolside-ODFAIK4C.js").then(e=>e.getPoolsideStream),NineRouter:()=>import("./9router-LRFKCJF4.js").then(e=>e.getNineRouterStream),ExpLabs:()=>import("./explabs-XHHXTERB.js").then(e=>e.getExpLabsStream),TokenHarbor:()=>import("./tokenharbor-YV2GV2LM.js").then(e=>e.getTokenHarborStream),Infron:()=>import("./infron-ULXG7VDA.js").then(e=>e.getInfronStream),APInex:()=>import("./apinex-FAYOPQSL.js").then(e=>e.getAPInexStream),xKiro:()=>import("./xkiro-B2LYGZTF.js").then(e=>e.getXKiroStream),c_openai:()=>import("./custom_openai-YS5EV6DG.js").then(e=>e.getCustomOpenAIStream)},us={},ce=async e=>(us[e]||(us[e]=await Qa[e]()),us[e]),Za=/```[\s\S]*?```/g,el=/```[\s\S]*$/g,tl=/`[^`]+`/g,nl=/^\|.*\|$/gm,ol=/^[^\w]+|[^\w]+$/g,il=/[^a-z0-9]/gi,Go=/\[\s*(?:tool|action):(?:functions\.)?([a-z0-9_]+)\s*\(/gi,sl=/\[\s*(?:tool:(?:functions\.)?|action:(?:functions\.)?|action:)([a-z0-9_]+)\s*\(/gi,rl=/(?:path|targetFile|TargetFile|directory|keyword|id|taskId|title|task)\s*=\s*\\?["']?([^\\"' \),]+)/,Mn=/["']/g,Qr=/\\/g,al=/<\|channel>thought/gi,ll=/<channel\|>/gi,cl=e=>typeof e!="string"?e:e.replace(al,"<think_fluxflow>").replace(ll,"</think_fluxflow>"),Md=/^\s*(?:<think_fluxflow[^>]*>|<\|channel>thought|\[think_fluxflow\])[\s\S]*?(?:<\/think_fluxflow>|<channel\|>|\[\/think_fluxflow\]|$)/i,dl=(e,n,t=1)=>{let i=n>0?e[n-1]:"",o=n+t<e.length?e[n+t]:"";return i==="`"&&o==="`"},fl=e=>{let n=/(?:<\/think_fluxflow>|<channel\|>|\[\/think_fluxflow\])/gi,t;for(;(t=n.exec(e))!==null;)if(!dl(e,t.index,t[0].length))return{index:t.index,length:t[0].length};return{index:-1,length:0}},gs=e=>{if(!e||typeof e!="string")return null;let n=e.match(/^\s*(?:<think_fluxflow[^>]*>|<\|channel>thought|\[think_fluxflow\])/i);if(!n)return null;let t=n.index+n[0].length,i=e.substring(t),o=fl(i);if(o.index!==-1){let r=t+o.index+o.length;return{fullBlock:e.substring(0,r),innerContent:i.substring(0,o.index),remainingText:e.substring(r)}}return{fullBlock:e,innerContent:i,remainingText:""}},Kt=e=>{if(!e||typeof e!="string")return e;let n=gs(e);return n?n.remainingText.trimStart():e};var Zr=/<\|\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,ul=/"([^"]+)"\s*:\s*(?:"([^"]*)"|(\d+)|true|false|null)/g,ea=/<\|\s*tool_calls_section_begin\s*\|>/gi,ta=/<\|\s*tool_calls_section_end\s*\|>/gi,gl=/```(?:tool|action|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi;var hi=e=>!e||typeof e!="string"?e:e.replace(/(```[\s\S]*?```|`[^`]*`)|(<(?:\w+)(?:[^>]*)>\r?\n?|\r?\n?<\/\w+(?:[^>]*)>)/gi,(n,t)=>t||""),sa=e=>{if(!e||typeof e!="string")return e;let n=eo(e);if(!n||n.length===0)return e;let t=n[n.length-1];if(!t.fullMatch)return e;let i=e.lastIndexOf(t.fullMatch);if(i===-1)return e;let o=i+t.fullMatch.length,r=e.substring(o);return/\[\s*(?:tool|action):/i.test(r)?e.trimEnd():e.substring(0,o).trimEnd()},ps=null,Ho={},Qn={key:null,value:null},jt=e=>{if(!e)return e;let n=Ho?.theme;if(!n)try{n=Zo(Xo,{})?.systemSettings?.theme}catch{}let i=pi(n||"Dark").toolFeedbackAnsi||"\x1B[95m";return e.replace(/(?:(\x1b\[\d+m))?([✔✘✖🔍📖→➕↻↷•🛇])(?:(\x1b\[\d+m))?\s*\b(Clicked Screen|Clicked|Located|Dragged|Scrolled|Typed|Entered|Pressed Key|Recaptured Screen|Created|Read Skill|Read Documentation|Executed|Searched Documentation|Read|Edited|Viewed|Processed|Auto-Read|Skipped|List|Generated|Written|Searched|AI Search|Get Map|Write Canceled|Resolved Sub-Agent Query|Edit Canceled|Write Cancelled|Edit Denied|Visited|Updated|Reviewed|Delegated|Background|Checked|Indexed|Analyzed|Browsed|Elevating SubAgent|Checking SubAgent Work|Started Generalist|Called Generalist|Steered|Unsupported Modality|Awaiting|Cancelled|Aligning Moon Phase|Contemplating Existence|Staring At Void|Rollback Point Checked|Emergency Rollback Failed|Emergency Rollback|Delaying Professionally|Negotiating With Electrons|Touching Grass (virtually)|Panicking Softly|Rethinking Career Choices|Loading Cat Videos|Giving Up Entirely|Summoning Braincell #2|Pretending To Be Busy|Waiting For Motivation DLC|Rotating Internal Screaming|Downloading More RAM|Feeding The Hamsters|Gaslighting Scheduler|Performing Dramatic Pause|Buffering Social Energy|Calculating Regret|Reading Terms And Conditions|Becoming Sentient Briefly|Model produced malformed tool call|Loop Detected|Contacting Ancestors)\b/ig,(o,r,c,a,u)=>`${r||""}${c}${a||""} ${i}${u}\x1B[0m`)},ml=async(e,n=8,t=1e3,i=8e3,o=null)=>{let r=0;for(;;){if(o?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{return await e()}catch(c){if(o?.aborted||c?.name==="AbortError"||c?.message==="Subagent task was cancelled."||(r++,r>=n))throw c;let a=Math.min(t*Math.pow(2,r-1),i);await new Promise((u,h)=>{let x=setTimeout(u,a);o&&o.addEventListener("abort",()=>{clearTimeout(x),h(new DOMException("The user aborted a request.","AbortError"))})})}}},Et=!1;var pl=e=>{let n=e.filter(o=>(o.role==="user"||o.role==="agent"||o.role==="system")&&o.role!=="think"&&!o.isVisualFeedback&&!o.isMeta&&!o.isTerminalRecord&&!(o.text&&o.text.includes("[TERMINAL_RECORD]"))&&!String(o.id).startsWith("welcome")).map((o,r,c)=>{let a=o.fullText||o.text||"";if(o.role==="user"&&r<c.length-1)if(a.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")){let u=a.indexOf("**CONTEXT SUMMARY OF PREVIOUS TURNS");if(u!==-1){let x=a.substring(0,u).lastIndexOf("[SYSTEM METADATA]");x!==-1?a=a.substring(x).trim():a=a.substring(u).trim()}}else{let u=a.lastIndexOf("[USER]"),h=a.lastIndexOf("[USER PROMPT]");u!==-1?a=a.substring(u+6).trim():h!==-1&&(a=a.substring(h).trim())}return{...o,text:a}}),t=[],i=0;for(;i<n.length;){let o=n[i];if(o.role==="user")t.push(o),i++;else{let r=[];for(;i<n.length&&n[i].role!=="user";)r.push(n[i]),i++;let c=[],a=[],u=!1,h=()=>{c.length>0&&(t.push({role:"agent",text:"combined"}),c=[]),a.length>0&&(t.push({role:"system",text:"combined"}),a=[]),u=!1};r.forEach(x=>{let p=x.role==="system"&&(x.text?.startsWith("[ACTION RESULT]")||x.text?.startsWith("[TOOL RESULT]")||x.text?.startsWith("SUCCESS:")||x.text?.startsWith("ERROR:")||x.fullText?.startsWith("[ACTION RESULT]")||x.fullText?.startsWith("[TOOL RESULT]")||x.fullText?.startsWith("SUCCESS:")||x.fullText?.startsWith("ERROR:")),f=x.fullText||x.text||"",s=f.trim();if(!(!s&&!x.binaryPart)){if(p)a.push(s);else if(x.role==="agent"){!u&&a.length>0&&h();let g=f.endsWith(`
591
- `),k=s.toLowerCase().includes("tool:")||s.toLowerCase().includes("action:");c.push(s),k&&g?u=!0:u=!1}}}),h()}}return t.length},hl=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),Pd=()=>{Et=!0},Od=()=>Et,ms={write_file:"Writing",update_file:"Editing",read_folder:"Reading",view_file:"Reading",exec_command:"Executing Command",web_search:"Searching",web_scrape:"Reading",memory:"Updating Memory",search_keyword:"Searching",find_file:"Finding File",findFile:"Finding File",FindFile:"Finding File",file_map:"Generating Map",ask:"User Input",write_pdf:"Creating",write_docx:"Creating",generate_image:"Generating",todo:"Planning",Todo:"Planning",goal:"Planning",Goal:"Planning",invoke_sync:"Sub-Agent Working",invoke:"Starting Agent",get_progress:"Checking Progress",cancel:"Cancelling",await:"Waiting",wait:"Waiting",EmergencyRollback:"Don't Panic. Lookin' into it",answer:"Answering Sub-Agent",Answer:"Answering Sub-Agent",steer:"Steering Sub-Agent",Steer:"Steering Sub-Agent",Click:"Clicking",click:"Clicking",Drag:"Dragging",drag:"Dragging",Scroll:"Scrolling",scroll:"Scrolling",KeyboardTyping:"Typing",keyboard_typing:"Typing",KeyPress:"Pressing Key",key_press:"Pressing Key",RecaptureScreen:"Recapturing Screen",recapture_screen:"Recapturing Screen"},Zn=(e,n)=>{try{let t=j(n),i=e.toLowerCase().replace(/_/g,"");if(i==="invokesync"||i==="invoke")return t.title||(t.task?t.task.substring(0,30):null);if(i==="getprogress"||i==="cancel"||i==="steer"||i==="steersubagent")return t.id||t.taskId;let o=t.name||t.path||t.targetFile||t.TargetFile||t.directory||t.file||t.query;return o?W.basename(o.replace(/["']/g,"").replace(/\\/g,"/")):null}catch{return null}},hs=e=>e?new ia({apiKey:e}):ps,Ld=async(e,n,t,i,o={})=>{let{onStatus:a,onMemoryUpdated:u,onBackgroundIncrement:h}=o,{profile:x,thinkingLevel:p,mode:f,janitorModel:s,chatId:g,systemSettings:k,sessionStats:he,aiProvider:y="Google",apiKey:E}=e,D=process.env.NVIDIA_BASE_URL||y==="Ollama"||y==="InferX"||y==="SenseNova"||y==="AIHubMix"||y==="Poolside"||y==="9router"||y==="ExpLabs"||y==="ExperientialLabs"||y==="c_openai"||y==="Custom (OpenAI)"?!1:k?.memory!==!1,O=Ot(Xn,[]).map(ue=>`- [${ue.id}]: ${ue.memory}`).join(`
592
- `),T=i.slice(0,-1).filter(ue=>ue.text&&!ue.text.includes("[ACTION RESULT]")&&!ue.text.includes("[TOOL RESULT]")&&!ue.text.includes("OBSERVATION:")&&!ue.text.startsWith("[TERMINAL_RECORD]")&&!ue.isTerminalRecord&&!ue.isMeta&&!ue.isLogo&&!String(ue.id).startsWith("welcome")&&!String(ue.id).startsWith("logo")).slice(-14).map(ue=>{let Be=Kt(hl(ue.text)).replace(/\[(?:tool|action):(?:functions\.)?.*?\]/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[METADATA \(PRIORITY: DYNAMIC\)\] Time: ([^|\n]+)/g,(_,Qe)=>`[METADATA (PRIORITY: DYNAMIC)] Time: ${Qe.replace(/:\d{2}/g,"")}`).replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[\[(?:TOOL|ACTION) RESULTS\]\]/gi,"").replace(/\[(?:TOOL|ACTION) RESULTS?\]/gi,"").replace(/\[(?:tool|action) results\]/gi,"").replace(/\r?\n\r?\n/g,`
589
+ `,u+=fs(me,n,E,i+1,o,r)):u+=`${t}${y}${s.name}
590
+ `}),u};var Za={Ollama:()=>import("./ollama-QB7WX7VD.js").then(e=>e.getOllamaStream),OpenRouter:()=>import("./openrouter-6MRG4RT6.js").then(e=>e.getOpenRouterStream),DeepSeek:()=>import("./deepseek-WNWZJTNE.js").then(e=>e.getDeepSeekStream),Mistral:()=>import("./mistral-YTTOZB2J.js").then(e=>e.getMistralStream),NVIDIA:()=>import("./nvidia-ON4Q6Q26.js").then(e=>e.getNVIDIAStream),NVIDIA_wrap:()=>import("./nvidia-ON4Q6Q26.js").then(e=>e.wrapNvidiaStreamWithQueueDepth),InferX:()=>import("./inferx-HP5AGET3.js").then(e=>e.getInferXStream),SenseNova:()=>import("./sensenova-3K44URJQ.js").then(e=>e.getSenseNovaStream),AIHubMix:()=>import("./aihubmix-TETL5QYQ.js").then(e=>e.getAIHubMixStream),Poolside:()=>import("./poolside-ODFAIK4C.js").then(e=>e.getPoolsideStream),NineRouter:()=>import("./9router-LRFKCJF4.js").then(e=>e.getNineRouterStream),ExpLabs:()=>import("./explabs-XHHXTERB.js").then(e=>e.getExpLabsStream),TokenHarbor:()=>import("./tokenharbor-YV2GV2LM.js").then(e=>e.getTokenHarborStream),Infron:()=>import("./infron-ULXG7VDA.js").then(e=>e.getInfronStream),APInex:()=>import("./apinex-FAYOPQSL.js").then(e=>e.getAPInexStream),xKiro:()=>import("./xkiro-B2LYGZTF.js").then(e=>e.getXKiroStream),c_openai:()=>import("./custom_openai-YS5EV6DG.js").then(e=>e.getCustomOpenAIStream)},gs={},le=async e=>(gs[e]||(gs[e]=await Za[e]()),gs[e]),el=/```[\s\S]*?```/g,tl=/```[\s\S]*$/g,nl=/`[^`]+`/g,ol=/^\|.*\|$/gm,il=/^[^\w]+|[^\w]+$/g,sl=/[^a-z0-9]/gi,Go=/\[\s*(?:tool|action):(?:functions\.)?([a-z0-9_]+)\s*\(/gi,rl=/\[\s*(?:tool:(?:functions\.)?|action:(?:functions\.)?|action:)([a-z0-9_]+)\s*\(/gi,al=/(?:path|targetFile|TargetFile|directory|keyword|id|taskId|title|task)\s*=\s*\\?["']?([^\\"' \),]+)/,vn=/["']/g,Qr=/\\/g,ll=/<\|channel>thought/gi,cl=/<channel\|>/gi,dl=e=>typeof e!="string"?e:e.replace(ll,"<think_fluxflow>").replace(cl,"</think_fluxflow>"),Pd=/^\s*(?:<think_fluxflow[^>]*>|<\|channel>thought|\[think_fluxflow\])[\s\S]*?(?:<\/think_fluxflow>|<channel\|>|\[\/think_fluxflow\]|$)/i,fl=(e,n,t=1)=>{let i=n>0?e[n-1]:"",o=n+t<e.length?e[n+t]:"";return i==="`"&&o==="`"},ul=e=>{let n=/(?:<\/think_fluxflow>|<channel\|>|\[\/think_fluxflow\])/gi,t;for(;(t=n.exec(e))!==null;)if(!fl(e,t.index,t[0].length))return{index:t.index,length:t[0].length};return{index:-1,length:0}},ms=e=>{if(!e||typeof e!="string")return null;let n=e.match(/^\s*(?:<think_fluxflow[^>]*>|<\|channel>thought|\[think_fluxflow\])/i);if(!n)return null;let t=n.index+n[0].length,i=e.substring(t),o=ul(i);if(o.index!==-1){let r=t+o.index+o.length;return{fullBlock:e.substring(0,r),innerContent:i.substring(0,o.index),remainingText:e.substring(r)}}return{fullBlock:e,innerContent:i,remainingText:""}},Lt=e=>{if(!e||typeof e!="string")return e;let n=ms(e);return n?n.remainingText.trimStart():e};var Zr=/<\|\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,gl=/"([^"]+)"\s*:\s*(?:"([^"]*)"|(\d+)|true|false|null)/g,ea=/<\|\s*tool_calls_section_begin\s*\|>/gi,ta=/<\|\s*tool_calls_section_end\s*\|>/gi,ml=/```(?:tool|action|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi;var hi=e=>!e||typeof e!="string"?e:e.replace(/(```[\s\S]*?```|`[^`]*`)|(<(?:\w+)(?:[^>]*)>\r?\n?|\r?\n?<\/\w+(?:[^>]*)>)/gi,(n,t)=>t||""),sa=e=>{if(!e||typeof e!="string")return e;let n=Wn(e);if(!n||n.length===0)return e;let t=n[n.length-1];if(!t.fullMatch)return e;let i=e.lastIndexOf(t.fullMatch);if(i===-1)return e;let o=i+t.fullMatch.length,r=e.substring(o);return/\[\s*(?:tool|action):/i.test(r)?e.trimEnd():e.substring(0,o).trimEnd()},hs=null,Ho={},Qn={key:null,value:null},Wt=e=>{if(!e)return e;let n=Ho?.theme;if(!n)try{n=Zo(Xo,{})?.systemSettings?.theme}catch{}let i=pi(n||"Dark").toolFeedbackAnsi||"\x1B[95m";return e.replace(/(?:(\x1b\[\d+m))?([✔✘✖🔍📖→➕↻↷•🛇])(?:(\x1b\[\d+m))?\s*\b(Clicked Screen|Clicked|Located|Dragged|Scrolled|Typed|Entered|Pressed Key|Recaptured Screen|Created|Read Skill|Read Documentation|Executed|Searched Documentation|Read|Edited|Viewed|Processed|Auto-Read|Skipped|List|Generated|Written|Searched|AI Search|Get Map|Write Canceled|Resolved Sub-Agent Query|Edit Canceled|Write Cancelled|Edit Denied|Visited|Updated|Reviewed|Delegated|Background|Checked|Indexed|Analyzed|Browsed|Elevating SubAgent|Checking SubAgent Work|Started Generalist|Called Generalist|Steered|Unsupported Modality|Awaiting|Cancelled|Aligning Moon Phase|Contemplating Existence|Staring At Void|Rollback Point Checked|Emergency Rollback Failed|Emergency Rollback|Delaying Professionally|Negotiating With Electrons|Touching Grass (virtually)|Panicking Softly|Rethinking Career Choices|Loading Cat Videos|Giving Up Entirely|Summoning Braincell #2|Pretending To Be Busy|Waiting For Motivation DLC|Rotating Internal Screaming|Downloading More RAM|Feeding The Hamsters|Gaslighting Scheduler|Performing Dramatic Pause|Buffering Social Energy|Calculating Regret|Reading Terms And Conditions|Becoming Sentient Briefly|Model produced malformed tool call|Loop Detected|Contacting Ancestors)\b/ig,(o,r,d,a,u)=>`${r||""}${d}${a||""} ${i}${u}\x1B[0m`)},pl=async(e,n=8,t=1e3,i=8e3,o=null)=>{let r=0;for(;;){if(o?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{return await e()}catch(d){if(o?.aborted||d?.name==="AbortError"||d?.message==="Subagent task was cancelled."||(r++,r>=n))throw d;let a=Math.min(t*Math.pow(2,r-1),i);await new Promise((u,h)=>{let x=setTimeout(u,a);o&&o.addEventListener("abort",()=>{clearTimeout(x),h(new DOMException("The user aborted a request.","AbortError"))})})}}},wt=!1;var hl=e=>{let n=e.filter(o=>(o.role==="user"||o.role==="agent"||o.role==="system")&&o.role!=="think"&&!o.isVisualFeedback&&!o.isMeta&&!o.isTerminalRecord&&!(o.text&&o.text.includes("[TERMINAL_RECORD]"))&&!String(o.id).startsWith("welcome")).map((o,r,d)=>{let a=o.fullText||o.text||"";if(o.role==="user"&&r<d.length-1)if(a.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")){let u=a.indexOf("**CONTEXT SUMMARY OF PREVIOUS TURNS");if(u!==-1){let x=a.substring(0,u).lastIndexOf("[SYSTEM METADATA]");x!==-1?a=a.substring(x).trim():a=a.substring(u).trim()}}else{let u=a.lastIndexOf("[USER]"),h=a.lastIndexOf("[USER PROMPT]");u!==-1?a=a.substring(u+6).trim():h!==-1&&(a=a.substring(h).trim())}return{...o,text:a}}),t=[],i=0;for(;i<n.length;){let o=n[i];if(o.role==="user")t.push(o),i++;else{let r=[];for(;i<n.length&&n[i].role!=="user";)r.push(n[i]),i++;let d=[],a=[],u=!1,h=()=>{d.length>0&&(t.push({role:"agent",text:"combined"}),d=[]),a.length>0&&(t.push({role:"system",text:"combined"}),a=[]),u=!1};r.forEach(x=>{let p=x.role==="system"&&(x.text?.startsWith("[ACTION RESULT]")||x.text?.startsWith("[TOOL RESULT]")||x.text?.startsWith("SUCCESS:")||x.text?.startsWith("ERROR:")||x.fullText?.startsWith("[ACTION RESULT]")||x.fullText?.startsWith("[TOOL RESULT]")||x.fullText?.startsWith("SUCCESS:")||x.fullText?.startsWith("ERROR:")),f=x.fullText||x.text||"",s=f.trim();if(!(!s&&!x.binaryPart)){if(p)a.push(s);else if(x.role==="agent"){!u&&a.length>0&&h();let g=f.endsWith(`
591
+ `),k=s.toLowerCase().includes("tool:")||s.toLowerCase().includes("action:");d.push(s),k&&g?u=!0:u=!1}}}),h()}}return t.length},yl=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),Od=()=>{wt=!0},Ld=()=>wt,ps={write_file:"Writing",update_file:"Editing",read_folder:"Reading",view_file:"Reading",exec_command:"Executing Command",web_search:"Searching",web_scrape:"Reading",memory:"Updating Memory",search_keyword:"Searching",find_file:"Finding File",findFile:"Finding File",FindFile:"Finding File",file_map:"Generating Map",ask:"User Input",write_pdf:"Creating",write_docx:"Creating",generate_image:"Generating",todo:"Planning",Todo:"Planning",goal:"Planning",Goal:"Planning",invoke_sync:"Sub-Agent Working",invoke:"Starting Agent",get_progress:"Checking Progress",cancel:"Cancelling",await:"Waiting",wait:"Waiting",EmergencyRollback:"Don't Panic. Lookin' into it",answer:"Answering Sub-Agent",Answer:"Answering Sub-Agent",steer:"Steering Sub-Agent",Steer:"Steering Sub-Agent",Click:"Clicking",click:"Clicking",Drag:"Dragging",drag:"Dragging",Scroll:"Scrolling",scroll:"Scrolling",KeyboardTyping:"Typing",keyboard_typing:"Typing",KeyPress:"Pressing Key",key_press:"Pressing Key",RecaptureScreen:"Recapturing Screen",recapture_screen:"Recapturing Screen"},Zn=(e,n)=>{try{let t=G(n),i=e.toLowerCase().replace(/_/g,"");if(i==="invokesync"||i==="invoke")return t.title||(t.task?t.task.substring(0,30):null);if(i==="getprogress"||i==="cancel"||i==="steer"||i==="steersubagent")return t.id||t.taskId;let o=t.name||t.path||t.targetFile||t.TargetFile||t.directory||t.file||t.query;return o?V.basename(o.replace(/["']/g,"").replace(/\\/g,"/")):null}catch{return null}},ys=e=>e?new ia({apiKey:e}):hs,$d=async(e,n,t,i,o={})=>{let{onStatus:a,onMemoryUpdated:u,onBackgroundIncrement:h}=o,{profile:x,thinkingLevel:p,mode:f,janitorModel:s,chatId:g,systemSettings:k,sessionStats:me,aiProvider:y="Google",apiKey:E}=e,N=process.env.NVIDIA_BASE_URL||y==="Ollama"||y==="InferX"||y==="SenseNova"||y==="AIHubMix"||y==="Poolside"||y==="9router"||y==="ExpLabs"||y==="ExperientialLabs"||y==="c_openai"||y==="Custom (OpenAI)"?!1:k?.memory!==!1,O=vt(Xn,[]).map(ue=>`- [${ue.id}]: ${ue.memory}`).join(`
592
+ `),T=i.slice(0,-1).filter(ue=>ue.text&&!ue.text.includes("[ACTION RESULT]")&&!ue.text.includes("[TOOL RESULT]")&&!ue.text.includes("OBSERVATION:")&&!ue.text.startsWith("[TERMINAL_RECORD]")&&!ue.isTerminalRecord&&!ue.isMeta&&!ue.isLogo&&!String(ue.id).startsWith("welcome")&&!String(ue.id).startsWith("logo")).slice(-14).map(ue=>{let De=Lt(yl(ue.text)).replace(/\[(?:tool|action):(?:functions\.)?.*?\]/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[METADATA \(PRIORITY: DYNAMIC\)\] Time: ([^|\n]+)/g,(v,ze)=>`[METADATA (PRIORITY: DYNAMIC)] Time: ${ze.replace(/:\d{2}/g,"")}`).replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[\[(?:TOOL|ACTION) RESULTS\]\]/gi,"").replace(/\[(?:TOOL|ACTION) RESULTS?\]/gi,"").replace(/\[(?:tool|action) results\]/gi,"").replace(/\r?\n\r?\n/g,`
593
593
  `).replace(/\n\n/g,`
594
- `).replace(/\\n\\n/g,"").trim(),Pe=ue.role==="user"?8192:32768,Y=Be.substring(0,Pe);Be.length>Pe&&(Y+=`
595
- ... (truncated) ...`);let H=ue.role==="user"?Y.startsWith("[USER]")?"":"[USER]: ":Y.startsWith("[AGENT]")?"":"[AGENT]: ";return{role:ue.role==="user"?"user":"model",parts:[{text:`${H}${Y}`}]}}),Se=i.filter(ue=>ue.role==="user").length===1,Ce=n.includes("[TITLE-UPDATE]"),Me=Math.random()<.8,Je=Se||Ce||Me,G=Kt(t).trim(),b=Cr(O,D,Je),ht=`${G.replace(/\[(?:tool|action):(?:functions\.)?.*?\]/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[\[(?:TOOL|ACTION) RESULTS\]\]/gi,"").replace(/\[(?:TOOL|ACTION) RESULTS?\]/gi,"").replace(/\[(?:tool|action) results\]/gi,"").substring(0,32768)}`;ht.length>32768&&(ht+=`
596
- ... (truncated) ...`);let fe=n.replace(/\[Prompted on:.*?\]/g,"").trim();ht=ht.replace(/\r?\n\r?\n/g,`
594
+ `).replace(/\\n\\n/g,"").trim(),Ie=ue.role==="user"?8192:32768,j=De.substring(0,Ie);De.length>Ie&&(j+=`
595
+ ... (truncated) ...`);let U=ue.role==="user"?j.startsWith("[USER]")?"":"[USER]: ":j.startsWith("[AGENT]")?"":"[AGENT]: ";return{role:ue.role==="user"?"user":"model",parts:[{text:`${U}${j}`}]}}),be=i.filter(ue=>ue.role==="user").length===1,Ae=n.includes("[TITLE-UPDATE]"),_e=Math.random()<.8,Ye=be||Ae||_e,B=Lt(t).trim(),b=Cr(O,N,Ye),ut=`${B.replace(/\[(?:tool|action):(?:functions\.)?.*?\]/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[\[(?:TOOL|ACTION) RESULTS\]\]/gi,"").replace(/\[(?:TOOL|ACTION) RESULTS?\]/gi,"").replace(/\[(?:tool|action) results\]/gi,"").substring(0,32768)}`;ut.length>32768&&(ut+=`
596
+ ... (truncated) ...`);let fe=n.replace(/\[Prompted on:.*?\]/g,"").trim();ut=ut.replace(/\r?\n\r?\n/g,`
597
597
  `).replace(/\n\n/g,`
598
- `).replace(/\\n\\n/g,"").trim();let q=new Date,Vt=`[METADATA] Current date and Time: ${`${q.getFullYear()}-${q.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(q.getDate()).padStart(2,"0")}, ${q.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0})}`}
598
+ `).replace(/\\n\\n/g,"").trim();let Y=new Date,Gt=`[METADATA] Current date and Time: ${`${Y.getFullYear()}-${Y.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(Y.getDate()).padStart(2,"0")}, ${Y.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0})}`}
599
599
 
600
600
  [USER]: ${fe.substring(0,8192)}
601
601
  ${fe.length>8192?`... (truncated) ...
602
602
 
603
603
  `:""}
604
- [AGENT (current turn)]: ${ht}`;T.push({role:"user",parts:[{text:Vt}]});let cn=await Li("NVIDIA"),Pn=(await Eo()).quotas?.providerTiers?.NVIDIA==="Free",dn="",yt=0,Yt=D?12:-1;for(;yt<=Yt;)try{if(!await Ms("background",e))return;let ue="",Be=null,Pe=!1,Y=y;try{let Qe=new Promise((dt,ge)=>setTimeout(()=>ge(new Error("JANITOR_TIMEOUT")),1e4)),Oe=y==="Google"&&yt>=0&&yt<6&&cn&&Pn,S=y==="DeepSeek"&&yt<4&&cn&&Pn;Pe=Oe||S,Y=Pe?"NVIDIA":y;let L=Date.now(),ct=null,ze=(async()=>{if(y==="OpenRouter"){let dt=ae("janitor_open_router"),de=(await ce("OpenRouter"))(E,dt,T,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),$t=await de.next();return{iterator:de,firstResult:$t}}else if(y==="DeepSeek"&&!Pe){let ge=(await ce("DeepSeek"))(E,ae("deepseek_fast_fallback"),T,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),de=await ge.next();return{iterator:ge,firstResult:de}}else if(y==="Mistral"&&!Pe){let ge=(await ce("Mistral"))(E,ae("mistral_janitor_fallback"),T,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),de=await ge.next();return{iterator:ge,firstResult:de}}else if(y==="NVIDIA"||Pe){let ge=(await ce("NVIDIA"))(Pe?cn:E,ae("nvidia_janitor_fallback"),T,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),de=await ge.next();return{iterator:ge,firstResult:de}}else if(y==="InferX"){let ge=(await ce("InferX"))(E,targetModel||ae("inferx_fallback")||"deepseek-v4-flash",T,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),de=await ge.next();return{iterator:ge,firstResult:de}}else if(y==="SenseNova"){let ge=(await ce("SenseNova"))(E,targetModel||ae("sensenova_fallback")||"sensenova-6.8-flash-lite",T,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),de=await ge.next();return{iterator:ge,firstResult:de}}else if(y==="AIHubMix"){let ge=(await ce("AIHubMix"))(E,targetModel||ae("aihubmix_fallback")||"gpt-4o-mini",T,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),de=await ge.next();return{iterator:ge,firstResult:de}}else if(y==="Poolside"){let ge=(await ce("Poolside"))(E,targetModel||ae("poolside_fallback")||"poolside/laguna-s-2.1",T,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),de=await ge.next();return{iterator:ge,firstResult:de}}else if(y==="9router"||y==="9Router"){let ge=(await ce("NineRouter"))(E,targetModel||ae("9router_fallback")||"z-ai/glm-5.3-flash",T,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),de=await ge.next();return{iterator:ge,firstResult:de}}else if(y==="ExpLabs"||y==="ExperientialLabs"){let ge=(await ce("ExpLabs"))(E,targetModel||ae("explabs_fallback")||"deepseek-v4-pro-0813",T,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),de=await ge.next();return{iterator:ge,firstResult:de}}else{let de=(await hs(E).models.generateContentStream({model:s||(yt===Yt?ae("janitor_default"):ae("gemma_janitor_fallback_google")),contents:T,config:{systemInstruction:b,temperature:.7,safetySettings:[{category:Hn.HARM_CATEGORY_HARASSMENT,threshold:Gn.BLOCK_NONE},{category:Hn.HARM_CATEGORY_HATE_SPEECH,threshold:Gn.BLOCK_NONE},{category:Hn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Gn.BLOCK_NONE},{category:Hn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Gn.BLOCK_NONE}],thinkingConfig:{includeThoughts:!1,thinkingLevel:Ye.MINIMAL},serviceTier:"flex"}}))[Symbol.asyncIterator](),$t=await de.next();return{iterator:de,firstResult:$t}}})();if(process.stdout.isTTY){let de=(await Bi())[g]?.name||"",$t=de&&!de.startsWith("flow-")&&!de.startsWith("Session ")?de:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${$t}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${$t}\x07`)}let{iterator:Ct,firstResult:it}=await Promise.race([ze,Qe]);ct=Date.now()-L;let{value:Tn,done:zt}=it;if(!zt&&Tn){let dt=Tn.candidates?.[0]?.content?.parts,ge=dt?Y==="Google"?dt[1]?.text||dt[0]?.text||"":dt.filter(de=>de.text&&!de.thought).map(de=>de.text).join(""):typeof Tn.text=="function"?Tn.text():"";ge&&(ue+=ge),Be=Tn.usageMetadata;for await(let de of{[Symbol.asyncIterator]:()=>Ct}){let $t=de.candidates?.[0]?.content?.parts,ho=$t?Y==="Google"?$t[1]?.text||$t[0]?.text||"":$t.filter(to=>to.text&&!to.thought).map(to=>to.text).join(""):typeof de.text=="function"?de.text():"";ho&&(ue+=ho),Be=de.usageMetadata}}}catch(Qe){throw Qe}if(ue){if(dn=ue,Be){let Qe=Be.totalTokenCount||0,Oe=Be.cachedContentTokenCount||0,S=(Be.candidatesTokenCount||0)+(Y==="Google"&&Be.thoughtsTokenCount||0),L=Pe?ae("nvidia_janitor_fallback"):Y==="DeepSeek"?ae("deepseek_fast_fallback"):Y==="ExpLabs"||Y==="ExperientialLabs"?ae("explabs_fallback")||"deepseek-v4-pro-0813":Y==="OpenRouter"?ae("janitor_open_router"):s||(yt===Yt?ae("janitor_default"):ae("gemma_janitor_fallback_google"));await At("tokens",Qe,Y,L),Oe>0&&await At("cachedTokens",Oe,Y,L),S>0&&await At("candidateTokens",S,Y,L),janitorTtft!==null&&janitorTtft>0&&await At("ttft",janitorTtft,Y,L),Co({provider:Y,model:L,prompt:Be.promptTokenCount||0,cached:Oe,output:S,reasoning:Be.thoughtsTokenCount||0,ttft:janitorTtft})}}else throw new Error("No synthesis generated by Janitor.");h&&(h(),await Lt("background"));let H=eo(dn),_=!1;for(let Qe of H){let Oe=Qe.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(Oe)&&(_=!0);let S={chatId:g,sessionId:g,history:i},L=await Bo(Oe,Qe.args,S);Oe.toLowerCase()==="memory"&&(Qe.args.includes("action='user'")||Qe.args.includes('action="user"'))&&!L.startsWith("ERROR")&&(u&&u(),process.stdout.isTTY&&(process.stdout.write("\x1B]0;Memory Updated\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=Memory Updated\x07")),await new Promise(ze=>setTimeout(ze,3e3)))}if(!_)try{let Qe=Ot(Xn,[]);if(Qe.length>0){let Oe=[];for(let S of Qe)S.score===void 0&&(S.score=.5),S.score*=.99995,S.score<.05&&(S.score=0),S.score=Math.round(S.score*1e5)/1e5,S.score>0&&Oe.push(S);co(Xn,Oe)}}catch{}break}catch(ue){yt++;let Be=new Date().toLocaleString(),Pe=ue instanceof Error?(()=>{try{return JSON.parse(JSON.parse(ue.message).error.message).error.message}catch{return String(ue)}})():String(ue);await new Promise(_=>setTimeout(_,1e3));let Y=W.join(wn,"janitor");if(Ae.existsSync(Y)||Ae.mkdirSync(Y,{recursive:!0}),Ae.appendFileSync(W.join(Y,"error.log"),`ERROR [Attempt ${yt}/${Yt+1}] [${Be}]: ${Pe}
604
+ [AGENT (current turn)]: ${ut}`;T.push({role:"user",parts:[{text:Gt}]});let an=await $i("NVIDIA"),_n=(await Eo()).quotas?.providerTiers?.NVIDIA==="Free",ln="",gt=0,Ht=N?12:-1;for(;gt<=Ht;)try{if(!await Ms("background",e))return;let ue="",De=null,Ie=!1,j=y;try{let ze=new Promise((at,ge)=>setTimeout(()=>ge(new Error("JANITOR_TIMEOUT")),1e4)),Me=y==="Google"&&gt>=0&&gt<6&&an&&_n,S=y==="DeepSeek"&&gt<4&&an&&_n;Ie=Me||S,j=Ie?"NVIDIA":y;let L=Date.now(),rt=null,Ke=(async()=>{if(y==="OpenRouter"){let at=re("janitor_open_router"),ce=(await le("OpenRouter"))(E,at,T,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),It=await ce.next();return{iterator:ce,firstResult:It}}else if(y==="DeepSeek"&&!Ie){let ge=(await le("DeepSeek"))(E,re("deepseek_fast_fallback"),T,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),ce=await ge.next();return{iterator:ge,firstResult:ce}}else if(y==="Mistral"&&!Ie){let ge=(await le("Mistral"))(E,re("mistral_janitor_fallback"),T,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),ce=await ge.next();return{iterator:ge,firstResult:ce}}else if(y==="NVIDIA"||Ie){let ge=(await le("NVIDIA"))(Ie?an:E,re("nvidia_janitor_fallback"),T,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),ce=await ge.next();return{iterator:ge,firstResult:ce}}else if(y==="InferX"){let ge=(await le("InferX"))(E,targetModel||re("inferx_fallback")||"deepseek-v4-flash",T,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),ce=await ge.next();return{iterator:ge,firstResult:ce}}else if(y==="SenseNova"){let ge=(await le("SenseNova"))(E,targetModel||re("sensenova_fallback")||"sensenova-6.8-flash-lite",T,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),ce=await ge.next();return{iterator:ge,firstResult:ce}}else if(y==="AIHubMix"){let ge=(await le("AIHubMix"))(E,targetModel||re("aihubmix_fallback")||"gpt-4o-mini",T,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),ce=await ge.next();return{iterator:ge,firstResult:ce}}else if(y==="Poolside"){let ge=(await le("Poolside"))(E,targetModel||re("poolside_fallback")||"poolside/laguna-s-2.1",T,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),ce=await ge.next();return{iterator:ge,firstResult:ce}}else if(y==="9router"||y==="9Router"){let ge=(await le("NineRouter"))(E,targetModel||re("9router_fallback")||"z-ai/glm-5.3-flash",T,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),ce=await ge.next();return{iterator:ge,firstResult:ce}}else if(y==="ExpLabs"||y==="ExperientialLabs"){let ge=(await le("ExpLabs"))(E,targetModel||re("explabs_fallback")||"deepseek-v4-pro-0813",T,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),ce=await ge.next();return{iterator:ge,firstResult:ce}}else{let ce=(await ys(E).models.generateContentStream({model:s||(gt===Ht?re("janitor_default"):re("gemma_janitor_fallback_google")),contents:T,config:{systemInstruction:b,temperature:.7,safetySettings:[{category:Un.HARM_CATEGORY_HARASSMENT,threshold:Bn.BLOCK_NONE},{category:Un.HARM_CATEGORY_HATE_SPEECH,threshold:Bn.BLOCK_NONE},{category:Un.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Bn.BLOCK_NONE},{category:Un.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Bn.BLOCK_NONE}],thinkingConfig:{includeThoughts:!1,thinkingLevel:je.MINIMAL},serviceTier:"flex"}}))[Symbol.asyncIterator](),It=await ce.next();return{iterator:ce,firstResult:It}}})();if(process.stdout.isTTY){let ce=(await Ui())[g]?.name||"",It=ce&&!ce.startsWith("flow-")&&!ce.startsWith("Session ")?ce:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${It}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${It}\x07`)}let{iterator:St,firstResult:tt}=await Promise.race([Ke,ze]);rt=Date.now()-L;let{value:wn,done:jt}=tt;if(!jt&&wn){let at=wn.candidates?.[0]?.content?.parts,ge=at?j==="Google"?at[1]?.text||at[0]?.text||"":at.filter(ce=>ce.text&&!ce.thought).map(ce=>ce.text).join(""):typeof wn.text=="function"?wn.text():"";ge&&(ue+=ge),De=wn.usageMetadata;for await(let ce of{[Symbol.asyncIterator]:()=>St}){let It=ce.candidates?.[0]?.content?.parts,po=It?j==="Google"?It[1]?.text||It[0]?.text||"":It.filter(eo=>eo.text&&!eo.thought).map(eo=>eo.text).join(""):typeof ce.text=="function"?ce.text():"";po&&(ue+=po),De=ce.usageMetadata}}}catch(ze){throw ze}if(ue){if(ln=ue,De){let ze=De.totalTokenCount||0,Me=De.cachedContentTokenCount||0,S=(De.candidatesTokenCount||0)+(j==="Google"&&De.thoughtsTokenCount||0),L=Ie?re("nvidia_janitor_fallback"):j==="DeepSeek"?re("deepseek_fast_fallback"):j==="ExpLabs"||j==="ExperientialLabs"?re("explabs_fallback")||"deepseek-v4-pro-0813":j==="OpenRouter"?re("janitor_open_router"):s||(gt===Ht?re("janitor_default"):re("gemma_janitor_fallback_google"));await bt("tokens",ze,j,L),Me>0&&await bt("cachedTokens",Me,j,L),S>0&&await bt("candidateTokens",S,j,L),janitorTtft!==null&&janitorTtft>0&&await bt("ttft",janitorTtft,j,L),Co({provider:j,model:L,prompt:De.promptTokenCount||0,cached:Me,output:S,reasoning:De.thoughtsTokenCount||0,ttft:janitorTtft})}}else throw new Error("No synthesis generated by Janitor.");h&&(h(),await _t("background"));let U=Wn(ln),v=!1;for(let ze of U){let Me=ze.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(Me)&&(v=!0);let S={chatId:g,sessionId:g,history:i},L=await Bo(Me,ze.args,S);Me.toLowerCase()==="memory"&&(ze.args.includes("action='user'")||ze.args.includes('action="user"'))&&!L.startsWith("ERROR")&&(u&&u(),process.stdout.isTTY&&(process.stdout.write("\x1B]0;Memory Updated\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=Memory Updated\x07")),await new Promise(Ke=>setTimeout(Ke,3e3)))}if(!v)try{let ze=vt(Xn,[]);if(ze.length>0){let Me=[];for(let S of ze)S.score===void 0&&(S.score=.5),S.score*=.99995,S.score<.05&&(S.score=0),S.score=Math.round(S.score*1e5)/1e5,S.score>0&&Me.push(S);lo(Xn,Me)}}catch{}break}catch(ue){gt++;let De=new Date().toLocaleString(),Ie=ue instanceof Error?(()=>{try{return JSON.parse(JSON.parse(ue.message).error.message).error.message}catch{return String(ue)}})():String(ue);await new Promise(v=>setTimeout(v,1e3));let j=V.join(yn,"janitor");if(ke.existsSync(j)||ke.mkdirSync(j,{recursive:!0}),ke.appendFileSync(V.join(j,"error.log"),`ERROR [Attempt ${gt}/${Ht+1}] [${De}]: ${Ie}
605
605
 
606
- `),yt>Yt)break;let H=Math.min(750*Math.pow(2,yt-1),5e3);await new Promise(_=>setTimeout(_,H))}if(yt){let ue=W.join(wn,"janitor");Ae.appendFileSync(W.join(ue,"error.log"),`-----------------------------------------------------------------------------
606
+ `),gt>Ht)break;let U=Math.min(750*Math.pow(2,gt-1),5e3);await new Promise(v=>setTimeout(v,U))}if(gt){let ue=V.join(yn,"janitor");ke.appendFileSync(V.join(ue,"error.log"),`-----------------------------------------------------------------------------
607
607
 
608
- `)}if(process.stdout.isTTY)try{let Pe=(await Bi())[g]?.name||"",Y=Pe&&!Pe.startsWith("flow-")&&!Pe.startsWith("Session ")?Pe:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${Y}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${Y}\x07`)}catch{process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")}},ys=e=>{if(!e||typeof e!="string")return e;let n=e.split(""),t=!1,i=!1,o=0;for(;o<n.length;){if(n[o]==="`"&&n[o+1]==="`"&&n[o+2]==="`"){t?(n[o]=" ",n[o+1]=" ",n[o+2]=" ",t=!1):(n[o]=" ",n[o+1]=" ",n[o+2]=" ",t=!0),o+=3;continue}if(t){n[o]!==`
609
- `&&n[o]!=="\r"&&(n[o]=" "),o++;continue}if(n[o]==="`")if(i){i=!1,n[o]=" ",o++;continue}else{let r=!1;for(let c=o+1;c<n.length&&!(n[c]===`
610
- `||n[c]==="\r");c++)if(n[c]==="`"&&(c===0||n[c-1]!=="\\")){r=!0;break}if(r){i=!0,n[o]=" ",o++;continue}}if(i){n[o]===`
611
- `||n[o]==="\r"?i=!1:n[o]=" ",o++;continue}o++}return n.join("")},yl=e=>{let n=Kt(e),t=ys(n);Go.lastIndex=0;let i;for(;(i=Go.exec(t))!==null;){let o=i.index+i[0].length-1,r=0,c=null,a=!1,u=!1;for(let h=o;h<t.length;h++){let x=t[h];if(!c&&(x==='"'||x==="'"||x==="`")?(c=x,a=!1):c&&x===c&&!a&&(c=null),!c&&(x==="("?r++:x===")"&&r--,r===0)){let p=h+1;for(;p<t.length&&/\s/.test(t[p]);)p++;if(p<t.length&&t[p]==="]"){u=!0,Go.lastIndex=p+1;break}}x==="\\"?a=!a:a=!1}if(!u)return{inside:!0,toolName:i[1],startIndex:i.index,args:n.substring(i.index+i[0].length)}}return{inside:!1}},ra=(e,n=!0)=>{let t=Go;t.lastIndex=0;let i="",o=0,r;for(;(r=t.exec(e))!==null;){let c=e.substring(o,r.index);i+=n&&o===0?Kt(c):c;let a=r.index+r[0].length-1,u=0,h=null,x=-1;for(let p=a;p<e.length;p++){let f=e[p];if(h){if(f===h){let s=0;for(let g=p-1;g>=0&&e[g]==="\\";g--)s++;s%2===0&&(h=null)}}else if(f==='"'||f==="'"||f==="`")h=f;else if(f==="(")u++;else if(f===")"&&(u--,u===0)){let s=p+1;for(;s<e.length&&/\s/.test(e[s]);)s++;if(s<e.length&&e[s]==="]"){x=s;break}}}if(x!==-1)i+="[tool:functions."+r[1]+"()]",o=x+1,t.lastIndex=o;else{i+="[tool:functions."+r[1]+"(",o=e.length;break}}return o<e.length&&(i+=n&&o===0?Kt(e.substring(o)):e.substring(o)),i},xl=(e,n,t)=>{let i=Go;i.lastIndex=0;let o="",r=0,c;for(;(c=i.exec(e))!==null;){let a=e.substring(r,c.index);o+=a.replace(n,t);let u=c.index+c[0].length-1,h=0,x=null,p=-1;for(let f=u;f<e.length;f++){let s=e[f];if(x){if(s===x){let g=0;for(let k=f-1;k>=0&&e[k]==="\\";k--)g++;g%2===0&&(x=null)}}else if(s==='"'||s==="'"||s==="`")x=s;else if(s==="(")h++;else if(s===")"&&(h--,h===0)){let g=f+1;for(;g<e.length&&/\s/.test(e[g]);)g++;if(g<e.length&&e[g]==="]"){p=g;break}}}if(p!==-1)o+=e.substring(c.index,p+1),r=p+1,i.lastIndex=r;else{o+=e.substring(c.index),r=e.length;break}}return r<e.length&&(o+=e.substring(r).replace(n,t)),o},na=e=>ra(e,!0),bl=e=>{if(!e)return e;let n={patchfile:"PatchFile",writefile:"WriteFile",readfile:"ReadFile",viewfile:"ReadFile",run:"Run",execcommand:"Run",searchkeyword:"SearchKeyword",codesearch:"CodeSearch",code_search:"CodeSearch",websearch:"WebSearch",webscrape:"WebScrape",readfolder:"ReadFolder",writepdf:"WritePDF",writedoc:"WriteDoc",writedocx:"WriteDoc",filemap:"FileMap",generateimage:"GenerateImage",todo:"Todo",goal:"Goal",askuser:"AskUser",ask:"AskUser"},t=o=>o.split("_").map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join("");Zr.lastIndex=0;let i=e.replace(Zr,(o,r,c)=>{let a="";try{let x=JSON.parse(c.trim());x&&typeof x=="object"&&(a=Object.entries(x).map(([f,s])=>{let g=typeof s=="string"?s:JSON.stringify(s);return`${f}=${JSON.stringify(g)}`}).join(", "))}catch{let p=[],f=ul;f.lastIndex=0;let s;for(;(s=f.exec(c))!==null;){let g=s[1],k=s[2]!==void 0?s[2]:s[0].split(":").slice(1).join(":").trim();p.push(`${g}=${JSON.stringify(k)}`)}p.length>0?a=p.join(", "):a=c.trim()}let u=r.toLowerCase().replace(/_/g,"");return`[tool:functions.${n[u]||t(r)}(${a})]`});return ea.lastIndex=0,ta.lastIndex=0,i=i.replace(ea,""),i=i.replace(ta,""),i},eo=e=>{if(!e)return[];let n=bl(e),t=Kt(n),i=[],o=ys(t),r=sl;r.lastIndex=0;let c;for(;(c=r.exec(o))!==null;){let a=c[1],u=c.index+c[0].length-1,h=0,x=null,p=-1,f=-1;for(let s=u;s<o.length;s++){let g=o[s];if(x){if(g===x){let k=0;for(let he=s-1;he>=0&&o[he]==="\\";he--)k++;k%2===0&&(x=null)}}else{if(s>u&&(o.substring(s).startsWith("[action:")||o.substring(s).startsWith("[tool:")))break;if(g==='"'||g==="'"||g==="`")x=g;else if(g==="(")h++;else if(g===")"&&(h--,h===0)){f=s;let k=s+1;for(;k<o.length&&/\s/.test(o[k]);)k++;if(k<o.length&&o[k]==="]"){p=k;break}}}}if(p!==-1){let s=t.substring(u+1,f),g=t.substring(c.index,p+1);i.push({fullMatch:g,toolName:a.trim(),args:s.trim()}),r.lastIndex=p+1}}return i},oa=e=>{if(!e)return null;let n=Kt(e),t=[],i=/\[\s*(?:tool:(?:functions\.)?|action:(?:functions\.)?|action:)([a-zA-Z0-9_]+)\s*\(/gi,o=[],r;for(;(r=i.exec(n))!==null;)o.push({toolName:r[1],index:r.index,parenIndex:r.index+r[0].length-1});for(let f=0;f<o.length;f++){let s=o[f],g=f+1<o.length?o[f+1].index:n.length,k=n.substring(s.index,g),he=k.indexOf("("),y=he!==-1?k.substring(he+1):"",E=0,D=null,K=!1;for(let O=0;O<y.length;O++){let T=y[O];if(D){if(T===D){let Se=0;for(let Ce=O-1;Ce>=0&&y[Ce]==="\\";Ce--)Se++;Se%2===0&&(D=null)}}else if(T==='"'||T==="'"||T==="`")D=T;else if(T==="(")E++;else if(T===")")if(E>0)E--;else{let Se=O+1;for(;Se<y.length&&/\s/.test(y[Se]);)Se++;if(Se<y.length&&y[Se]==="]"){K=!0;break}}}if(!K){let O=k.trim(),T="";D?T=`Unclosed quote string (${D}) inside arguments`:O.endsWith("]")?T=`Missing closing ')' before ']' (e.g. found "...]")`:O.endsWith(")")?T=`Missing closing ']' after ')' (e.g. found "...)" instead of "...)]")`:!O.includes(")")&&!O.includes("]")?T="Missing closing delimiter ')]'":T="Malformed or unclosed call syntax (missing ')]')",t.push(`\u2022 [action:${s.toolName}(...)]: ${T}. Expected: [action:${s.toolName}(arg1="...", arg2="...")]`)}}let c=/(?:^|[^\w\[])(?:tool|action):(?:functions\.)?([a-zA-Z0-9_]+)\s*\(/gi,a;for(;(a=c.exec(n))!==null;){let f=a[1],s=a.index+(a[0].indexOf(":")-(a[0].startsWith("action")||a[0].startsWith("tool")?0:1));(s>0?n[s-1]:"")!=="["&&gi(f)&&t.push(`\u2022 action:${f}(...): Missing opening bracket '['. Expected: [action:${f}(...)]`)}let u=/\[\s*(?:functions\.)?([a-zA-Z0-9_]+)\s*\(/g,h;for(;(h=u.exec(n))!==null;){let f=h[1];f!=="action"&&f!=="tool"&&gi(f)&&t.push(`\u2022 [${f}(...)]: Missing 'action:' prefix. Expected: [action:${f}(...)]`)}let x=/\[\s*(?:tool|action)\s*:\s*(?:functions\.)?([a-zA-Z0-9_]+)(?!\s*\()/gi,p;for(;(p=x.exec(n))!==null;){let f=p[1];gi(f)&&t.push(`\u2022 [action:${f}...]: Missing opening '(' for tool arguments. Expected: [action:${f}(...)]`)}return t.length>0?t.join(`
612
- `):null},$d=(e,n={})=>{if(!e)return null;if(Ho=n,ps=new ia({apiKey:e}),!globalThis.__perfCleanupInstalled){globalThis.__perfCleanupInstalled=!0,setInterval(()=>{typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks())},6e4);let t=globalThis.fetch;globalThis.fetch=async(...i)=>{try{let o=await t(...i);return typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),o}catch(o){throw typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),o}}}},aa=e=>{if(!e)return{serviceTier:void 0,cleanModel:e};let n=e.toLowerCase();return n.endsWith(":flex")?{serviceTier:"flex",cleanModel:e.slice(0,-5)}:n.endsWith(":priority")?{serviceTier:"priority",cleanModel:e.slice(0,-9)}:{serviceTier:void 0,cleanModel:e}},yi=async(e,n,t,i,o="Fast",r=.75,c="agent")=>ml(async()=>{let{aiProvider:a="Google",apiKey:u,mode:h}=e,x="",p=null,f=typeof t=="string"?[{role:"user",parts:[{text:t}]}]:t,s=new AbortController,g=s.signal,k=setInterval(()=>{Et&&(s.abort(),clearInterval(k))},100),he=Date.now(),y=null;try{let E;if(a==="Ollama")E=(await ce("Ollama"))(u,n,f,i,o,h,lt(n),g,r,e.systemSettings?.ollamaEndpoint||"Cloud");else if(a==="OpenRouter")E=(await ce("OpenRouter"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="DeepSeek")E=(await ce("DeepSeek"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="Mistral")E=(await ce("Mistral"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="NVIDIA")E=(await ce("NVIDIA"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="InferX")E=(await ce("InferX"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="SenseNova")E=(await ce("SenseNova"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="AIHubMix")E=(await ce("AIHubMix"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="Poolside")E=(await ce("Poolside"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="9router"||a==="9Router")E=(await ce("NineRouter"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="ExpLabs"||a==="ExperientialLabs")E=(await ce("ExpLabs"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="Infron"||a==="infron")E=(await ce("Infron"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="TokenHarbor"||a==="Token Harbor"||a==="tokenharbor"||a==="token_harbor"||a==="thk")E=(await ce("TokenHarbor"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="APInex"||a==="apinex"||a==="apx")E=(await ce("APInex"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="xKiro"||a==="xkiro"||a==="kiro")E=(await ce("xKiro"))(u,n,f,i,o,h,lt(n),g,r);else if(a==="c_openai"||a==="Custom (OpenAI)"){let D=e.systemSettings?.customOpenAIBaseUrl||"";try{D=await Oi("c_openai")||D}catch{}E=(await ce("c_openai"))(u,n,f,i,o,h,lt(n),g,r,D)}else{let D=hs(u),{serviceTier:K,cleanModel:O}=aa(n),T={systemInstruction:i,temperature:r,thinkingConfig:(()=>{let Ce=(n||"").toLowerCase(),Me=Ce.includes("gemma-4")||Ce.startsWith("gemma"),Je=Ce.includes("gemini-3");if(Me||Je)return Me?o.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:Ye.MINIMAL}:{includeThoughts:!0,thinkingLevel:Ye.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:Ce.includes("pro")?Ye.LOW:Ye.MINIMAL,Low:Ye.LOW,Medium:Ye.MEDIUM,Standard:Ye.MEDIUM,High:Ye.HIGH,xHigh:Ye.HIGH}[o]||Ye.MEDIUM};{let G={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[o]||2048;return G===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:G}}})()};K&&(T.serviceTier=K),E=await D.models.generateContentStream({model:O,contents:f,config:T},{signal:g})}for await(let D of E){if(Et)throw new Error("Subagent task was cancelled.");if(e?.taskId&&typeof en<"u"){let T=en.find(Se=>Se.id===e.taskId);if(T&&T.status==="cancelled")throw new Error("Subagent task was cancelled.")}y===null&&(D.candidates?.[0]?.content?.parts||D.text)&&(y=Date.now()-he);let K="";if(D.candidates?.[0]?.content?.parts)for(let T of D.candidates[0].content.parts)T.text&&!T.thought&&(x+=T.text,K+=T.text);let O=K?Ni(K):0;e&&typeof e.onTokenChunk=="function"&&e.onTokenChunk(K,O),D.usageMetadata&&(p=D.usageMetadata)}}finally{clearInterval(k)}if(p){let E=p.totalTokenCount||0,D=p.cachedContentTokenCount||0,K=(p.candidatesTokenCount||0)+(a==="Google"&&p.thoughtsTokenCount||0);await At("tokens",E,a,n),D>0&&await At("cachedTokens",D,a,n),K>0&&await At("candidateTokens",K,a,n),y!==null&&y>0&&await At("ttft",y,a,n),Co({provider:a,model:n,prompt:p.promptTokenCount||0,cached:D,output:K,reasoning:p.thoughtsTokenCount||0,ttft:y}),e&&typeof e.onUsage=="function"&&e.onUsage({totalTokenCount:E,cachedContentTokenCount:D,candidatesTokenCount:K})}return await Lt("agent",a),{text:x,usageMetadata:p}}),wl=async(e,n,t=null)=>{t=t||Ot(Qo,{});try{let{aiProvider:i="Google"}=n;if(Object.values(t).flat().length<=5)return;let r=Object.keys(t).filter(f=>f!==e&&Array.isArray(t[f])&&t[f].length>2);if(r.length===0)return;let c=`You are a silent background process for the FluxFlow CLI Agent.
608
+ `)}if(process.stdout.isTTY)try{let Ie=(await Ui())[g]?.name||"",j=Ie&&!Ie.startsWith("flow-")&&!Ie.startsWith("Session ")?Ie:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${j}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${j}\x07`)}catch{process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")}},yi=e=>{if(!e||typeof e!="string")return e;let n=e.split(""),t=!1,i=!1,o=0;for(;o<n.length;){if(n[o]==="`"&&n[o+1]==="`"&&n[o+2]==="`"){t?(n[o]=" ",n[o+1]=" ",n[o+2]=" ",t=!1):(n[o]=" ",n[o+1]=" ",n[o+2]=" ",t=!0),o+=3;continue}if(t){n[o]!==`
609
+ `&&n[o]!=="\r"&&(n[o]=" "),o++;continue}if(n[o]==="`")if(i){i=!1,n[o]=" ",o++;continue}else{i=!0,n[o]=" ",o++;continue}if(i){n[o]===`
610
+ `||n[o]==="\r"?i=!1:n[o]=" ",o++;continue}o++}return n.join("")},xl=e=>{let n=Lt(e),t=yi(n);Go.lastIndex=0;let i;for(;(i=Go.exec(t))!==null;){let o=i.index+i[0].length-1,r=0,d=null,a=!1,u=!1;for(let h=o;h<t.length;h++){let x=t[h];if(!d&&(x==='"'||x==="'"||x==="`")?(d=x,a=!1):d&&x===d&&!a&&(d=null),!d&&(x==="("?r++:x===")"&&r--,r===0)){let p=h+1;for(;p<t.length&&/\s/.test(t[p]);)p++;if(p<t.length&&t[p]==="]"){u=!0,Go.lastIndex=p+1;break}}x==="\\"?a=!a:a=!1}if(!u)return{inside:!0,toolName:i[1],startIndex:i.index,args:n.substring(i.index+i[0].length)}}return{inside:!1}},ra=(e,n=!0)=>{let t=Go;t.lastIndex=0;let i="",o=0,r;for(;(r=t.exec(e))!==null;){let d=e.substring(o,r.index);i+=n&&o===0?Lt(d):d;let a=r.index+r[0].length-1,u=0,h=null,x=-1;for(let p=a;p<e.length;p++){let f=e[p];if(h){if(f===h){let s=0;for(let g=p-1;g>=0&&e[g]==="\\";g--)s++;s%2===0&&(h=null)}}else if(f==='"'||f==="'"||f==="`")h=f;else if(f==="(")u++;else if(f===")"&&(u--,u===0)){let s=p+1;for(;s<e.length&&/\s/.test(e[s]);)s++;if(s<e.length&&e[s]==="]"){x=s;break}}}if(x!==-1)i+="[tool:functions."+r[1]+"()]",o=x+1,t.lastIndex=o;else{i+="[tool:functions."+r[1]+"(",o=e.length;break}}return o<e.length&&(i+=n&&o===0?Lt(e.substring(o)):e.substring(o)),i},bl=(e,n,t)=>{let i=Go;i.lastIndex=0;let o="",r=0,d;for(;(d=i.exec(e))!==null;){let a=e.substring(r,d.index);o+=a.replace(n,t);let u=d.index+d[0].length-1,h=0,x=null,p=-1;for(let f=u;f<e.length;f++){let s=e[f];if(x){if(s===x){let g=0;for(let k=f-1;k>=0&&e[k]==="\\";k--)g++;g%2===0&&(x=null)}}else if(s==='"'||s==="'"||s==="`")x=s;else if(s==="(")h++;else if(s===")"&&(h--,h===0)){let g=f+1;for(;g<e.length&&/\s/.test(e[g]);)g++;if(g<e.length&&e[g]==="]"){p=g;break}}}if(p!==-1)o+=e.substring(d.index,p+1),r=p+1,i.lastIndex=r;else{o+=e.substring(d.index),r=e.length;break}}return r<e.length&&(o+=e.substring(r).replace(n,t)),o},na=e=>ra(e,!0),wl=e=>{if(!e)return e;let n={patchfile:"PatchFile",writefile:"WriteFile",readfile:"ReadFile",viewfile:"ReadFile",run:"Run",execcommand:"Run",searchkeyword:"SearchKeyword",codesearch:"CodeSearch",code_search:"CodeSearch",websearch:"WebSearch",webscrape:"WebScrape",readfolder:"ReadFolder",writepdf:"WritePDF",writedoc:"WriteDoc",writedocx:"WriteDoc",filemap:"FileMap",generateimage:"GenerateImage",todo:"Todo",goal:"Goal",askuser:"AskUser",ask:"AskUser"},t=o=>o.split("_").map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join("");Zr.lastIndex=0;let i=e.replace(Zr,(o,r,d)=>{let a="";try{let x=JSON.parse(d.trim());x&&typeof x=="object"&&(a=Object.entries(x).map(([f,s])=>{let g=typeof s=="string"?s:JSON.stringify(s);return`${f}=${JSON.stringify(g)}`}).join(", "))}catch{let p=[],f=gl;f.lastIndex=0;let s;for(;(s=f.exec(d))!==null;){let g=s[1],k=s[2]!==void 0?s[2]:s[0].split(":").slice(1).join(":").trim();p.push(`${g}=${JSON.stringify(k)}`)}p.length>0?a=p.join(", "):a=d.trim()}let u=r.toLowerCase().replace(/_/g,"");return`[tool:functions.${n[u]||t(r)}(${a})]`});return ea.lastIndex=0,ta.lastIndex=0,i=i.replace(ea,""),i=i.replace(ta,""),i},Wn=e=>{if(!e)return[];let n=wl(e),t=Lt(n),i=[],o=yi(t),r=rl;r.lastIndex=0;let d;for(;(d=r.exec(o))!==null;){let a=d[1],u=d.index+d[0].length-1,h=0,x=null,p=-1,f=-1;for(let s=u;s<o.length;s++){let g=o[s];if(x){if(g===x){let k=0;for(let me=s-1;me>=0&&o[me]==="\\";me--)k++;k%2===0&&(x=null)}}else{if(s>u&&(o.substring(s).startsWith("[action:")||o.substring(s).startsWith("[tool:")))break;if(g==='"'||g==="'"||g==="`")x=g;else if(g==="(")h++;else if(g===")"&&(h--,h===0)){f=s;let k=s+1;for(;k<o.length&&/\s/.test(o[k]);)k++;if(k<o.length&&o[k]==="]"){p=k;break}}}}if(p!==-1){let s=t.substring(u+1,f),g=t.substring(d.index,p+1);i.push({fullMatch:g,toolName:a.trim(),args:s.trim()}),r.lastIndex=p+1}}return i},oa=e=>{if(!e)return null;let n=Lt(e),t=[],i=/\[\s*(?:tool:(?:functions\.)?|action:(?:functions\.)?|action:)([a-zA-Z0-9_]+)\s*\(/gi,o=[],r;for(;(r=i.exec(n))!==null;)o.push({toolName:r[1],index:r.index,parenIndex:r.index+r[0].length-1});for(let f=0;f<o.length;f++){let s=o[f],g=f+1<o.length?o[f+1].index:n.length,k=n.substring(s.index,g),me=k.indexOf("("),y=me!==-1?k.substring(me+1):"",E=0,N=null,H=!1;for(let O=0;O<y.length;O++){let T=y[O];if(N){if(T===N){let be=0;for(let Ae=O-1;Ae>=0&&y[Ae]==="\\";Ae--)be++;be%2===0&&(N=null)}}else if(T==='"'||T==="'"||T==="`")N=T;else if(T==="(")E++;else if(T===")")if(E>0)E--;else{let be=O+1;for(;be<y.length&&/\s/.test(y[be]);)be++;if(be<y.length&&y[be]==="]"){H=!0;break}}}if(!H){let O=k.trim(),T="";N?T=`Unclosed quote string (${N}) inside arguments`:O.endsWith("]")?T=`Missing closing ')' before ']' (e.g. found "...]")`:O.endsWith(")")?T=`Missing closing ']' after ')' (e.g. found "...)" instead of "...)]")`:!O.includes(")")&&!O.includes("]")?T="Missing closing delimiter ')]'":T="Malformed or unclosed call syntax (missing ')]')",t.push(`\u2022 [action:${s.toolName}(...)]: ${T}. Expected: [action:${s.toolName}(arg1="...", arg2="...")]`)}}let d=/(?:^|[^\w\[])(?:tool|action):(?:functions\.)?([a-zA-Z0-9_]+)\s*\(/gi,a;for(;(a=d.exec(n))!==null;){let f=a[1],s=a.index+(a[0].indexOf(":")-(a[0].startsWith("action")||a[0].startsWith("tool")?0:1));(s>0?n[s-1]:"")!=="["&&gi(f)&&t.push(`\u2022 action:${f}(...): Missing opening bracket '['. Expected: [action:${f}(...)]`)}let u=/\[\s*(?:functions\.)?([a-zA-Z0-9_]+)\s*\(/g,h;for(;(h=u.exec(n))!==null;){let f=h[1];f!=="action"&&f!=="tool"&&gi(f)&&t.push(`\u2022 [${f}(...)]: Missing 'action:' prefix. Expected: [action:${f}(...)]`)}let x=/\[\s*(?:tool|action)\s*:\s*(?:functions\.)?([a-zA-Z0-9_]+)(?!\s*\()/gi,p;for(;(p=x.exec(n))!==null;){let f=p[1];gi(f)&&t.push(`\u2022 [action:${f}...]: Missing opening '(' for tool arguments. Expected: [action:${f}(...)]`)}return t.length>0?t.join(`
611
+ `):null},Nd=(e,n={})=>{if(!e)return null;if(Ho=n,hs=new ia({apiKey:e}),!globalThis.__perfCleanupInstalled){globalThis.__perfCleanupInstalled=!0,setInterval(()=>{typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks())},6e4);let t=globalThis.fetch;globalThis.fetch=async(...i)=>{try{let o=await t(...i);return typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),o}catch(o){throw typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),o}}}},aa=e=>{if(!e)return{serviceTier:void 0,cleanModel:e};let n=e.toLowerCase();return n.endsWith(":flex")?{serviceTier:"flex",cleanModel:e.slice(0,-5)}:n.endsWith(":priority")?{serviceTier:"priority",cleanModel:e.slice(0,-9)}:{serviceTier:void 0,cleanModel:e}},xi=async(e,n,t,i,o="Fast",r=.75,d="agent")=>pl(async()=>{let{aiProvider:a="Google",apiKey:u,mode:h}=e,x="",p=null,f=typeof t=="string"?[{role:"user",parts:[{text:t}]}]:t,s=new AbortController,g=s.signal,k=setInterval(()=>{wt&&(s.abort(),clearInterval(k))},100),me=Date.now(),y=null;try{let E;if(a==="Ollama")E=(await le("Ollama"))(u,n,f,i,o,h,st(n),g,r,e.systemSettings?.ollamaEndpoint||"Cloud");else if(a==="OpenRouter")E=(await le("OpenRouter"))(u,n,f,i,o,h,st(n),g,r);else if(a==="DeepSeek")E=(await le("DeepSeek"))(u,n,f,i,o,h,st(n),g,r);else if(a==="Mistral")E=(await le("Mistral"))(u,n,f,i,o,h,st(n),g,r);else if(a==="NVIDIA")E=(await le("NVIDIA"))(u,n,f,i,o,h,st(n),g,r);else if(a==="InferX")E=(await le("InferX"))(u,n,f,i,o,h,st(n),g,r);else if(a==="SenseNova")E=(await le("SenseNova"))(u,n,f,i,o,h,st(n),g,r);else if(a==="AIHubMix")E=(await le("AIHubMix"))(u,n,f,i,o,h,st(n),g,r);else if(a==="Poolside")E=(await le("Poolside"))(u,n,f,i,o,h,st(n),g,r);else if(a==="9router"||a==="9Router")E=(await le("NineRouter"))(u,n,f,i,o,h,st(n),g,r);else if(a==="ExpLabs"||a==="ExperientialLabs")E=(await le("ExpLabs"))(u,n,f,i,o,h,st(n),g,r);else if(a==="Infron"||a==="infron")E=(await le("Infron"))(u,n,f,i,o,h,st(n),g,r);else if(a==="TokenHarbor"||a==="Token Harbor"||a==="tokenharbor"||a==="token_harbor"||a==="thk")E=(await le("TokenHarbor"))(u,n,f,i,o,h,st(n),g,r);else if(a==="APInex"||a==="apinex"||a==="apx")E=(await le("APInex"))(u,n,f,i,o,h,st(n),g,r);else if(a==="xKiro"||a==="xkiro"||a==="kiro")E=(await le("xKiro"))(u,n,f,i,o,h,st(n),g,r);else if(a==="c_openai"||a==="Custom (OpenAI)"){let N=e.systemSettings?.customOpenAIBaseUrl||"";try{N=await Li("c_openai")||N}catch{}E=(await le("c_openai"))(u,n,f,i,o,h,st(n),g,r,N)}else{let N=ys(u),{serviceTier:H,cleanModel:O}=aa(n),T={systemInstruction:i,temperature:r,thinkingConfig:(()=>{let Ae=(n||"").toLowerCase(),_e=Ae.includes("gemma-4")||Ae.startsWith("gemma"),Ye=Ae.includes("gemini-3");if(_e||Ye)return _e?o.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:je.MINIMAL}:{includeThoughts:!0,thinkingLevel:je.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:Ae.includes("pro")?je.LOW:je.MINIMAL,Low:je.LOW,Medium:je.MEDIUM,Standard:je.MEDIUM,High:je.HIGH,xHigh:je.HIGH}[o]||je.MEDIUM};{let B={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[o]||2048;return B===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:B}}})()};H&&(T.serviceTier=H),E=await N.models.generateContentStream({model:O,contents:f,config:T},{signal:g})}for await(let N of E){if(wt)throw new Error("Subagent task was cancelled.");if(e?.taskId&&typeof Qt<"u"){let T=Qt.find(be=>be.id===e.taskId);if(T&&T.status==="cancelled")throw new Error("Subagent task was cancelled.")}y===null&&(N.candidates?.[0]?.content?.parts||N.text)&&(y=Date.now()-me);let H="";if(N.candidates?.[0]?.content?.parts)for(let T of N.candidates[0].content.parts)T.text&&!T.thought&&(x+=T.text,H+=T.text);let O=H?Di(H):0;e&&typeof e.onTokenChunk=="function"&&e.onTokenChunk(H,O),N.usageMetadata&&(p=N.usageMetadata)}}finally{clearInterval(k)}if(p){let E=p.totalTokenCount||0,N=p.cachedContentTokenCount||0,H=(p.candidatesTokenCount||0)+(a==="Google"&&p.thoughtsTokenCount||0);await bt("tokens",E,a,n),N>0&&await bt("cachedTokens",N,a,n),H>0&&await bt("candidateTokens",H,a,n),y!==null&&y>0&&await bt("ttft",y,a,n),Co({provider:a,model:n,prompt:p.promptTokenCount||0,cached:N,output:H,reasoning:p.thoughtsTokenCount||0,ttft:y}),e&&typeof e.onUsage=="function"&&e.onUsage({totalTokenCount:E,cachedContentTokenCount:N,candidatesTokenCount:H})}return await _t("agent",a),{text:x,usageMetadata:p}}),Sl=async(e,n,t=null)=>{t=t||vt(Qo,{});try{let{aiProvider:i="Google"}=n;if(Object.values(t).flat().length<=5)return;let r=Object.keys(t).filter(f=>f!==e&&Array.isArray(t[f])&&t[f].length>2);if(r.length===0)return;let d=`You are a silent background process for the FluxFlow CLI Agent.
613
612
  Your task is to summarize or merge temporary context memories from one or more past conversation sessions.
614
613
  For each Chat ID provided, you must output a tool call to save the consolidated summary.
615
614
 
@@ -624,20 +623,20 @@ Guidelines:
624
623
 
625
624
  Chats to process:
626
625
 
627
- `,a=Ot(Mi,{});for(let f of r){let g=t[f].map(he=>`- ${he}`).join(`
628
- `),k=a[f];c+=`[Chat ID: ${f}]
629
- `,k?(c+=`- Existing Summary: "${k}"
630
- `,c+=`
626
+ `,a=vt(Pi,{});for(let f of r){let g=t[f].map(me=>`- ${me}`).join(`
627
+ `),k=a[f];d+=`[Chat ID: ${f}]
628
+ `,k?(d+=`- Existing Summary: "${k}"
629
+ `,d+=`
631
630
  -- New Memories to integrate:
632
631
  ${g}
633
632
 
634
- `):c+=`-- Individual Memories:
633
+ `):d+=`-- Individual Memories:
635
634
  ${g}
636
635
 
637
- `}let u=0,h=5,x=!1,p=ae("gemma_janitor_fallback_google");for(i==="OpenRouter"&&(p=ae("janitor_open_router")),i==="DeepSeek"&&(p=ae("deepseek_level_1")),i==="Mistral"&&(p=ae("mistral_level_1")),i==="NVIDIA"&&(p=ae("nvidia_janitor_fallback")),i==="InferX"&&(p=ae("inferx_fallback")),i==="SenseNova"&&(p=ae("sensenova_fallback")),i==="AIHubMix"&&(p=ae("aihubmix_fallback")),i==="Poolside"&&(p=ae("poolside_fallback")),(i==="9router"||i==="9Router")&&(p=ae("9router_fallback"));u<=h&&!x;){u++;try{let s=(await yi(n,p,c,null,"Fast",.75,"background")).text||"",g=eo(s);if(g.length===0)throw new Error("No tool calls detected in synthesis response");for(let k of g){let he=k.toolName;["saveSummary","saveSumary","SaveSummary","SaveSumary"].includes(he)&&await Bo(he,k.args,{chatId:e})}x=!0}catch(f){if(u>=h)throw new Error(`Failed after ${h} attempts. Last error: ${f.message}`)}}}catch(i){let o=i instanceof Error?(()=>{try{return JSON.parse(JSON.parse(i.message).error.message).error.message}catch{return String(i)}})():String(i),r=W.join(wn,"janitor");Ae.existsSync(r)||Ae.mkdirSync(r,{recursive:!0}),Ae.appendFileSync(W.join(r,"error.log"),`[${new Date().toLocaleString()}] Past memory batch consolidation error: ${o}
638
- `)}},Nd=async(e,n,t=!1)=>{let{chatId:i,aiProvider:o="Google"}=e,r=W.join(Jo,"chat-summaries.json"),c=s=>s.filter(g=>(g.role==="user"||g.role==="agent"||g.role==="system")&&g.role!=="think"&&!g.isVisualFeedback&&!g.isMeta&&!g.isTerminalRecord&&!(g.text&&g.text.includes("[TERMINAL_RECORD]"))&&!String(g.id).startsWith("welcome")).map(g=>{let k=g.fullText||g.text||"",he=g.role==="system"||k.startsWith("[ACTION RESULT]:")||k.startsWith("[TOOL RESULT]:")||g.text&&(g.text.startsWith("[ACTION RESULT]:")||g.text.startsWith("[TOOL RESULT]:")),y=k;return he&&(k.includes("[ACTION RESULT]:")||k.includes("[TOOL RESULT]:")||g.text&&(g.text.includes("[ACTION RESULT]:")||g.text.includes("[TOOL RESULT]:")))?y="[ACTION RESULT]: ...truncated for summary":y=y.replace(/(\[(?:tool|action):[a-zA-Z0-9_\.]+)\([\s\S]*?\)(\])/g,"$1(...)$2"),`[${he?"ACTION":g.role==="agent"?"AGENT":"USER"}]: ${y}`}).join(`
636
+ `}let u=0,h=5,x=!1,p=re("gemma_janitor_fallback_google");for(i==="OpenRouter"&&(p=re("janitor_open_router")),i==="DeepSeek"&&(p=re("deepseek_level_1")),i==="Mistral"&&(p=re("mistral_level_1")),i==="NVIDIA"&&(p=re("nvidia_janitor_fallback")),i==="InferX"&&(p=re("inferx_fallback")),i==="SenseNova"&&(p=re("sensenova_fallback")),i==="AIHubMix"&&(p=re("aihubmix_fallback")),i==="Poolside"&&(p=re("poolside_fallback")),(i==="9router"||i==="9Router")&&(p=re("9router_fallback"));u<=h&&!x;){u++;try{let s=(await xi(n,p,d,null,"Fast",.75,"background")).text||"",g=Wn(s);if(g.length===0)throw new Error("No tool calls detected in synthesis response");for(let k of g){let me=k.toolName;["saveSummary","saveSumary","SaveSummary","SaveSumary"].includes(me)&&await Bo(me,k.args,{chatId:e})}x=!0}catch(f){if(u>=h)throw new Error(`Failed after ${h} attempts. Last error: ${f.message}`)}}}catch(i){let o=i instanceof Error?(()=>{try{return JSON.parse(JSON.parse(i.message).error.message).error.message}catch{return String(i)}})():String(i),r=V.join(yn,"janitor");ke.existsSync(r)||ke.mkdirSync(r,{recursive:!0}),ke.appendFileSync(V.join(r,"error.log"),`[${new Date().toLocaleString()}] Past memory batch consolidation error: ${o}
637
+ `)}},Dd=async(e,n,t=!1)=>{let{chatId:i,aiProvider:o="Google"}=e,r=V.join(Jo,"chat-summaries.json"),d=s=>s.filter(g=>(g.role==="user"||g.role==="agent"||g.role==="system")&&g.role!=="think"&&!g.isVisualFeedback&&!g.isMeta&&!g.isTerminalRecord&&!(g.text&&g.text.includes("[TERMINAL_RECORD]"))&&!String(g.id).startsWith("welcome")).map(g=>{let k=g.fullText||g.text||"",me=g.role==="system"||k.startsWith("[ACTION RESULT]:")||k.startsWith("[TOOL RESULT]:")||g.text&&(g.text.startsWith("[ACTION RESULT]:")||g.text.startsWith("[TOOL RESULT]:")),y=k;return me&&(k.includes("[ACTION RESULT]:")||k.includes("[TOOL RESULT]:")||g.text&&(g.text.includes("[ACTION RESULT]:")||g.text.includes("[TOOL RESULT]:")))?y="[ACTION RESULT]: ...truncated for summary":y=y.replace(/(\[(?:tool|action):[a-zA-Z0-9_\.]+)\([\s\S]*?\)(\])/g,"$1(...)$2"),`[${me?"ACTION":g.role==="agent"?"AGENT":"USER"}]: ${y}`}).join(`
639
638
 
640
- `),a=async(s,g)=>{let k="You are an expert context summarizer. Summarize the provided chat history (which may include previous summaries, user instructions, agent outputs, and tool results) into a detailed, coherent, and highly technical summary of 1000 to 1500 words. Focus on preserving the architectural decisions made, current system state, task progress, and critical code details, chat messages, file changes. Under no circumstances exceed MAX 2000 words.",he=g?`Here is the previous summary:
639
+ `),a=async(s,g)=>{let k="You are an expert context summarizer. Summarize the provided chat history (which may include previous summaries, user instructions, agent outputs, and tool results) into a detailed, coherent, and highly technical summary of 1000 to 1500 words. Focus on preserving the architectural decisions made, current system state, task progress, and critical code details, chat messages, file changes. Under no circumstances exceed MAX 2000 words.",me=g?`Here is the previous summary:
641
640
  ${g}
642
641
 
643
642
  Here is the new conversation history:
@@ -646,238 +645,233 @@ ${s}
646
645
  Provide a new consolidated summary of the entire session.`:`Here is the conversation history:
647
646
  ${s}
648
647
 
649
- Provide a consolidated summary of the entire session.`,y=ae("gemma_janitor_fallback_google");o==="OpenRouter"&&(y=ae("janitor_open_router")),o==="DeepSeek"&&(y=ae("deepseek_level_1")),o==="Mistral"&&(y=ae("mistral_level_1")),o==="NVIDIA"&&(y=ae("nvidia_chat_summarizer_fallback")),o==="InferX"&&(y=ae("inferx_fallback")),o==="SenseNova"&&(y=ae("sensenova_fallback")),o==="AIHubMix"&&(y=ae("aihubmix_fallback")),o==="Poolside"&&(y=ae("poolside_fallback")),(o==="9router"||o==="9Router")&&(y=ae("9router_fallback")),(o==="ExpLabs"||o==="ExperientialLabs")&&(y=ae("explabs_fallback")||"deepseek-v4-pro-0813"),(o==="TokenHarbor"||o==="Token Harbor"||o==="tokenharbor"||o==="token_harbor"||o==="thk")&&(y=ae("tokenharbor_fallback")||"deepseek-v4.1-flash:free"),(o==="Infron"||o==="infron")&&(y=ae("infron_fallback")),(o==="xKiro"||o==="xkiro"||o==="kiro")&&(y=ae("xkiro_fallback")||"openai/gpt-5.6-sol");let E=0,D=!1,K=null;for(;E<=3&&!D;){E++;try{K=await yi(e,y,he,k,"Fast"),D=!0}catch{if(E>3){if(o==="Google")try{let T=ae("general_fallback");return(await yi(e,T,he,k,"Fast")).text||""}catch{return""}return""}}}return K&&K.text||""},u=c(n),h=Ot(r,{}),x=h[i]||{summary:"",historyLength:0};typeof x=="string"&&(x={summary:x,historyLength:0});let p=x.summary||"",f=await a(u,p);if(f){x.summary=f;let s=pl(n);return t?x.historyLength=(x.historyLength||0)+s:x.historyLength=s,h[i]=x,co(r,h),f}return null},Dd=e=>{try{let n=W.join(Jo,"chat-summaries.json");if(Ae.existsSync(n)){let t=Ot(n,{});t[e]&&(delete t[e],co(n,t))}}catch{}},Fd=async function*(e,n,t,i,o){let{profile:r,thinkingLevel:c,mode:a,janitorModel:u,chatId:h,isPlayground:x,systemSettings:p,sessionStats:f,aiProvider:s="Google",apiTier:g,wildcardTooling:k,wildercardTooling:he}=t,y=lt(e);if(!ps&&s==="Google")throw new Error("AI not initialized");let E=process.env.NVIDIA_BASE_URL||t?.aiProvider==="Ollama"||t?.aiProvider==="InferX"||t?.aiProvider==="SenseNova"||t?.aiProvider==="AIHubMix"||t?.aiProvider==="Poolside"||t?.aiProvider==="9router"||t?.aiProvider==="ExpLabs"||t?.aiProvider==="ExperientialLabs"||t?.aiProvider==="TokenHarbor"||t?.aiProvider==="Token Harbor"||t?.aiProvider==="tokenharbor"||t?.aiProvider==="token_harbor"||t?.aiProvider==="thk"||t?.aiProvider==="APInex"||t?.aiProvider==="apinex"||t?.aiProvider==="apx"||t?.aiProvider==="xKiro"||t?.aiProvider==="xkiro"||t?.aiProvider==="kiro"||t?.aiProvider==="Infron"||t?.aiProvider==="infron"||t?.aiProvider==="c_openai"||t?.aiProvider==="Custom (OpenAI)"?!1:p?.memory!==!1,D=n[n.length-1].text,K=W.join(Jo,"chat-summaries.json"),O=!1,T=n.filter(G=>G.role==="user").length===1,Se=D.includes("[TITLE-UPDATE]"),Ce=T||Se,Me=D.replace(/\[TITLE-UPDATE\]/g,"").trim();Me=Me.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),yield{type:"status",content:"[start]"},yield{type:"status",content:"Gathering Context"},await ti.startTransaction(h,Me),p?.advanceRollback&&await Ro.takeInitialSnapshot(h),Et=!1;let Je=null;try{let G=new AbortController;Je=setInterval(()=>{Et&&(G.abort(),Je&&(clearInterval(Je),Je=null))},400);let b=[...n.slice(0,-1)];{let _e=Ot(K,{})[h]||{summary:"",historyLength:0};if(_e.summary&&_e.historyLength>0){let qt=0,Ie=[];for(let me=0;me<b.length;me++){let Ue=b[me];(Ue.role==="user"||Ue.role==="agent"||Ue.role==="system")&&!String(Ue.id).startsWith("welcome")&&!Ue.isMeta&&qt++,qt>_e.historyLength&&Ie.push(Ue)}b=Ie}}b=b.map(v=>{if(v.role==="user"&&v.text){let _e=v.text.match(/\[USER\]([\s\S]*?)\[\/USER\]/);if(_e)return{...v,text:_e[1].trim()}}return{...v}});let ht=process.env.HIGH_CONTEXT,fe=process.env.GOOGLE_GEMMA_NONSENSE==="true"||process.env.GOOGLE_GEMMA_NONSENSE===!0||!1,Vt={"16k":16e3,"32k":32e3,"64k":64e3,"128k":128e3,"256k":256e3,"512k":512e3,"1M":1e6}[p?.contextLength]||256e3;if(ht&&ht!=="false"){let v=parseInt(ht,10);!isNaN(v)&&v>=0&&v<=1e6&&(Vt=v)}if((s==="NVIDIA"&&(e?.includes("gpt")||e?.includes("qwen")||e?.includes("medium")||e.includes("muse"))||s==="Mistral")&&(Vt=126e3),s==="Google"&&e?.includes("gemma")&&fe&&(Vt=16e3),(f?.tokens||0)>Vt){yield{type:"text",content:"\u2726 Maximum Context Limit Reached. Start a new chat."};return}if(T&&E){let v=Ot(Qo,{});Object.values(v).flat().length>5&&(yield{type:"status",content:"Condensing past chat memories"},await wl(h,t,v))}let cn=Ot(Qo,{}),po=Ot(Mi,{}),Pn=Object.entries(cn).filter(([v])=>v!==h).flatMap(([v,_e])=>_e),yt=[...Object.entries(po).filter(([v])=>v!==h).slice(-20).map(([v,_e])=>`[Chat Summary]: ${_e}`),...Pn].map(v=>`- ${v}`).join(`
650
- `),ue=Ot(Xn,[]).map(v=>`- ${v.memory}`).join(`
651
- `),Be=(f?.tokens||0)>=1e4,Pe=new Date,Y=Pe.getFullYear(),H=Pe.toLocaleString("en-US",{month:"short"}).toUpperCase(),_=String(Pe.getDate()).padStart(2,"0"),Oe=`${Pe.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0})}`,S=v=>{try{return Ae.readdirSync(v,{withFileTypes:!0})}catch{return[]}},L=Array.from(new Set([...To,...Ao(process.cwd())])),ct=(v,_e=6)=>p?.indentationTree!==!1?ls(v,_e,1,S,L):ds(v,_e,"",1,S,L),ze=Ot(Pi,{}),Ct=ze[h],it=Ct?Ct!==process.cwd():!1;ze[h]=process.cwd(),co(Pi,ze);let Tn=Ot(K,{}),zt=Tn[h]||{summary:"",historyLength:0};typeof zt=="string"&&(zt={summary:zt,historyLength:0});let dt=n.filter(v=>(v.role==="user"||v.role==="agent"||v.role==="system")&&!String(v.id).startsWith("welcome")&&!v.isMeta).length;zt.historyLength&&dt<zt.historyLength&&(zt.summary="",zt.historyLength=0,Tn[h]=zt,co(K,Tn));let ge=typeof zt=="object"?zt.summary||"":zt||"",de=b.length>0;de&&ge&&b[0]&&(b[0].role==="user"||b[0].role==="system")&&(b[0].text.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")||(b[0].text=`[SYSTEM METADATA]
648
+ Provide a consolidated summary of the entire session.`,y=re("gemma_janitor_fallback_google");o==="OpenRouter"&&(y=re("janitor_open_router")),o==="DeepSeek"&&(y=re("deepseek_level_1")),o==="Mistral"&&(y=re("mistral_level_1")),o==="NVIDIA"&&(y=re("nvidia_chat_summarizer_fallback")),o==="InferX"&&(y=re("inferx_fallback")),o==="SenseNova"&&(y=re("sensenova_fallback")),o==="AIHubMix"&&(y=re("aihubmix_fallback")),o==="Poolside"&&(y=re("poolside_fallback")),(o==="9router"||o==="9Router")&&(y=re("9router_fallback")),(o==="ExpLabs"||o==="ExperientialLabs")&&(y=re("explabs_fallback")||"deepseek-v4-pro-0813"),(o==="TokenHarbor"||o==="Token Harbor"||o==="tokenharbor"||o==="token_harbor"||o==="thk")&&(y=re("tokenharbor_fallback")||"deepseek-v4.1-flash:free"),(o==="Infron"||o==="infron")&&(y=re("infron_fallback")),(o==="xKiro"||o==="xkiro"||o==="kiro")&&(y=re("xkiro_fallback")||"openai/gpt-5.6-sol");let E=0,N=!1,H=null;for(;E<=3&&!N;){E++;try{H=await xi(e,y,me,k,"Fast"),N=!0}catch{if(E>3){if(o==="Google")try{let T=re("general_fallback");return(await xi(e,T,me,k,"Fast")).text||""}catch{return""}return""}}}return H&&H.text||""},u=d(n),h=vt(r,{}),x=h[i]||{summary:"",historyLength:0};typeof x=="string"&&(x={summary:x,historyLength:0});let p=x.summary||"",f=await a(u,p);if(f){x.summary=f;let s=hl(n);return t?x.historyLength=(x.historyLength||0)+s:x.historyLength=s,h[i]=x,lo(r,h),f}return null},Fd=e=>{try{let n=V.join(Jo,"chat-summaries.json");if(ke.existsSync(n)){let t=vt(n,{});t[e]&&(delete t[e],lo(n,t))}}catch{}},Bd=async function*(e,n,t,i,o){let{profile:r,thinkingLevel:d,mode:a,janitorModel:u,chatId:h,isPlayground:x,systemSettings:p,sessionStats:f,aiProvider:s="Google",apiTier:g,wildcardTooling:k,wildercardTooling:me}=t,y=st(e);if(!hs&&s==="Google")throw new Error("AI not initialized");let E=process.env.NVIDIA_BASE_URL||t?.aiProvider==="Ollama"||t?.aiProvider==="InferX"||t?.aiProvider==="SenseNova"||t?.aiProvider==="AIHubMix"||t?.aiProvider==="Poolside"||t?.aiProvider==="9router"||t?.aiProvider==="ExpLabs"||t?.aiProvider==="ExperientialLabs"||t?.aiProvider==="TokenHarbor"||t?.aiProvider==="Token Harbor"||t?.aiProvider==="tokenharbor"||t?.aiProvider==="token_harbor"||t?.aiProvider==="thk"||t?.aiProvider==="APInex"||t?.aiProvider==="apinex"||t?.aiProvider==="apx"||t?.aiProvider==="xKiro"||t?.aiProvider==="xkiro"||t?.aiProvider==="kiro"||t?.aiProvider==="Infron"||t?.aiProvider==="infron"||t?.aiProvider==="c_openai"||t?.aiProvider==="Custom (OpenAI)"?!1:p?.memory!==!1,N=n[n.length-1].text,H=V.join(Jo,"chat-summaries.json"),O=!1,T=n.filter(B=>B.role==="user").length===1,be=N.includes("[TITLE-UPDATE]"),Ae=T||be,_e=N.replace(/\[TITLE-UPDATE\]/g,"").trim();_e=_e.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),yield{type:"status",content:"[start]"},yield{type:"status",content:"Gathering Context"},await ti.startTransaction(h,_e),p?.advanceRollback&&await Ro.takeInitialSnapshot(h),wt=!1;let Ye=null;try{let B=new AbortController;Ye=setInterval(()=>{wt&&(B.abort(),Ye&&(clearInterval(Ye),Ye=null))},400);let b=[...n.slice(0,-1)];{let Re=vt(H,{})[h]||{summary:"",historyLength:0};if(Re.summary&&Re.historyLength>0){let Kt=0,Se=[];for(let de=0;de<b.length;de++){let Ne=b[de];(Ne.role==="user"||Ne.role==="agent"||Ne.role==="system")&&!String(Ne.id).startsWith("welcome")&&!Ne.isMeta&&Kt++,Kt>Re.historyLength&&Se.push(Ne)}b=Se}}b=b.map(I=>{if(I.role==="user"&&I.text){let Re=I.text.match(/\[USER\]([\s\S]*?)\[\/USER\]/);if(Re)return{...I,text:Re[1].trim()}}return{...I}});let ut=process.env.HIGH_CONTEXT,fe=process.env.GOOGLE_GEMMA_NONSENSE==="true"||process.env.GOOGLE_GEMMA_NONSENSE===!0||!1,Gt={"16k":16e3,"32k":32e3,"64k":64e3,"128k":128e3,"256k":256e3,"512k":512e3,"1M":1e6}[p?.contextLength]||256e3;if(ut&&ut!=="false"){let I=parseInt(ut,10);!isNaN(I)&&I>=0&&I<=1e6&&(Gt=I)}if((s==="NVIDIA"&&(e?.includes("gpt")||e?.includes("qwen")||e?.includes("medium")||e.includes("muse"))||s==="Mistral")&&(Gt=126e3),s==="Google"&&e?.includes("gemma")&&fe&&(Gt=16e3),(f?.tokens||0)>Gt){yield{type:"text",content:"\u2726 Maximum Context Limit Reached. Start a new chat."};return}if(T&&E){let I=vt(Qo,{});Object.values(I).flat().length>5&&(yield{type:"status",content:"Condensing past chat memories"},await Sl(h,t,I))}let an=vt(Qo,{}),mo=vt(Pi,{}),_n=Object.entries(an).filter(([I])=>I!==h).flatMap(([I,Re])=>Re),gt=[...Object.entries(mo).filter(([I])=>I!==h).slice(-20).map(([I,Re])=>`[Chat Summary]: ${Re}`),..._n].map(I=>`- ${I}`).join(`
649
+ `),ue=vt(Xn,[]).map(I=>`- ${I.memory}`).join(`
650
+ `),De=(f?.tokens||0)>=1e4,Ie=new Date,j=Ie.getFullYear(),U=Ie.toLocaleString("en-US",{month:"short"}).toUpperCase(),v=String(Ie.getDate()).padStart(2,"0"),Me=`${Ie.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0})}`,S=I=>{try{return ke.readdirSync(I,{withFileTypes:!0})}catch{return[]}},L=Array.from(new Set([...To,...Ao(process.cwd())])),rt=(I,Re=6)=>p?.indentationTree!==!1?cs(I,Re,1,S,L):fs(I,Re,"",1,S,L),Ke=vt(Oi,{}),St=Ke[h],tt=St?St!==process.cwd():!1;Ke[h]=process.cwd(),lo(Oi,Ke);let wn=vt(H,{}),jt=wn[h]||{summary:"",historyLength:0};typeof jt=="string"&&(jt={summary:jt,historyLength:0});let at=n.filter(I=>(I.role==="user"||I.role==="agent"||I.role==="system")&&!String(I.id).startsWith("welcome")&&!I.isMeta).length;jt.historyLength&&at<jt.historyLength&&(jt.summary="",jt.historyLength=0,wn[h]=jt,lo(H,wn));let ge=typeof jt=="object"?jt.summary||"":jt||"",ce=b.length>0;ce&&ge&&b[0]&&(b[0].role==="user"||b[0].role==="system")&&(b[0].text.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")||(b[0].text=`[SYSTEM METADATA]
652
651
  **CONTEXT SUMMARY OF PREVIOUS TURNS (PRIORITY: DYNAMIC)**
653
652
  ${ge}
654
653
 
655
- [USER] ${b[0].text}`,yield{type:"summary_injected",content:{id:b[0].id,text:b[0].text}}));let $t=ge&&!de?`
654
+ [USER] ${b[0].text}`,yield{type:"summary_injected",content:{id:b[0].id,text:b[0].text}}));let It=ge&&!ce?`
656
655
  [SYSTEM METADATA]
657
656
  **CONTEXT SUMMARY OF PREVIOUS TURNS**
658
657
  ${ge}
659
- `:"",ho=!!p?.dynamicDirAwareness,to=`${h}|${s}|${c}|${e}|${r}|${ho}`,la=!ho&&Qn.key===to&&Qn.value?"":`
658
+ `:"",po=!!p?.dynamicDirAwareness,eo=`${h}|${s}|${d}|${e}|${r}|${po}`,la=!po&&Qn.key===eo&&Qn.value?"":`
660
659
  **Directory**
661
660
  CWD: `+process.cwd()+`${x?" [PLAYGROUND MODE]":""}
662
- `+ct(process.cwd(),6),ft=go()?await Jn():null,xs=v=>{if(!v||!Array.isArray(v)||v.length===0)return null;let _e=new Map;for(let Ie of v){let me=Ie.relPath||(Ie.file?W.relative(process.cwd(),Ie.file):"unknown");_e.has(me)||_e.set(me,[]),_e.get(me).push(Ie)}let qt=[];for(let[Ie,me]of _e.entries()){qt.push(`- ${Ie}:`);for(let Ue of me){let qe=(Ue.snippet||"").trim().replace(/\r?\n/g," "),Ze=Ue.line||1,Nt=(Ue.text||"").trim().replace(/\r?\n+/g,". "),Te=Nt?` [${Nt}]`:"";qt.push(` ~L${Ze}${Te}`)}}return qt.join(`
663
- `)},xi=xs(ft?.comments),An="";if(ft&&ft.file_focused!=="none"){An=`
661
+ `+rt(process.cwd(),6),$t=uo()?await Jn():null,xs=I=>{if(!I||!Array.isArray(I)||I.length===0)return null;let Re=new Map;for(let Se of I){let de=Se.relPath||(Se.file?V.relative(process.cwd(),Se.file):"unknown");Re.has(de)||Re.set(de,[]),Re.get(de).push(Se)}let Kt=[];for(let[Se,de]of Re.entries()){Kt.push(`- ${Se}:`);for(let Ne of de){let qe=(Ne.snippet||"").trim().replace(/\r?\n/g," "),Ze=Ne.line||1,Vt=(Ne.text||"").trim().replace(/\r?\n+/g,". "),At=Vt?` [${Vt}]`:"";Kt.push(` ~L${Ze}${At}`)}}return Kt.join(`
662
+ `)},bi=xs($t?.comments),Sn="";if($t&&$t.file_focused!=="none"){Sn=`
664
663
  [Additional IDE Context]
665
- `;let v=W.relative(process.cwd(),ft.file_focused),_e=(ft.opened_editors||[]).map(Ie=>{let me=W.relative(process.cwd(),Ie);return me.startsWith("..")?`[External] ${W.basename(Ie)}`:me});if(An+=`Focused File: ${v}
666
- Cursor Line: ${ft.cursor_line}
667
- `,ft.selected){let Ie=ft.selected,me=Ie.split(`
668
- `);me.length>256&&(Ie=me.slice(0,240).join(`
664
+ `;let I=V.relative(process.cwd(),$t.file_focused),Re=($t.opened_editors||[]).map(Se=>{let de=V.relative(process.cwd(),Se);return de.startsWith("..")?`[External] ${V.basename(Se)}`:de});if(Sn+=`Focused File: ${I}
665
+ Cursor Line: ${$t.cursor_line}
666
+ `,$t.selected){let Se=$t.selected,de=Se.split(`
667
+ `);de.length>256&&(Se=de.slice(0,240).join(`
669
668
  `)+`
670
669
  ... [truncated] ...
671
- `+me.slice(-16).join(`
672
- `)),Ie.length>2048&&(Ie=Ie.slice(0,1920)+`
670
+ `+de.slice(-16).join(`
671
+ `)),Se.length>2048&&(Se=Se.slice(0,1920)+`
673
672
  ... [truncated] ...
674
- `+Ie.slice(-128)),An+=`Current Selection: "${Ie}"
675
- `}if(ft.manual_edits){let me=ft.manual_edits.split(`
676
- `),Ue=[],qe=null;for(let P of me)P.trim()&&(P.startsWith(" Line ")?qe&&qe.edits.push(P):(qe={path:P.endsWith(":")?P.slice(0,-1):P,edits:[]},Ue.push(qe)));for(let P of Ue)P.edits.length>80&&(P.edits=P.edits.slice(-80)),P.originalEditsCount=P.edits.length;let Ze=(P,De)=>De.reduce((xt,un)=>{let Rt=ft.file_focused&&(un.path===ft.file_focused||W.resolve(process.cwd(),un.path)===W.resolve(ft.file_focused))?Math.ceil(P*1.2):P;return xt+Math.min(un.edits.length,Rt)},0),Nt=80;if(Ze(80,Ue)>300){let P=!1;for(let De=80;De>=10;De--)if(Ze(De,Ue)<=300){Nt=De,P=!0;break}P||(Nt=10)}let Te=[...Ue];if(Nt===10&&Ze(10,Te)>500)for(;Te.length>0&&Ze(10,Te)>500;){let P=0,De=Te[0].originalEditsCount;for(let xt=1;xt<Te.length;xt++)Te[xt].originalEditsCount<De&&(De=Te[xt].originalEditsCount,P=xt);Te.splice(P,1)}for(let P of Te){let xt=ft.file_focused&&(P.path===ft.file_focused||W.resolve(process.cwd(),P.path)===W.resolve(ft.file_focused))?Math.ceil(Nt*1.2):Nt;P.edits.length>xt&&(P.edits=P.edits.slice(-xt))}for(let P of Te){let De=`${P.path}:
677
- ${P.edits.join(`
678
- `)}`;for(;P.edits.length>0&&De.length>4*768;)P.edits.shift(),De=`${P.path}:
679
- ${P.edits.join(`
680
- `)}`;De.length>4*768?P.stringRepresentation="... "+De.slice(-(4*768-4)):P.stringRepresentation=De}let pe=Te.map(P=>P.stringRepresentation).join(`
681
- `);for(;Te.length>0&&pe.length>4*2048;){Te[0].edits.length>0?Te[0].edits.shift():Te.shift();for(let P of Te){let De=`${P.path}:
682
- ${P.edits.join(`
683
- `)}`;De.length>4*768?P.stringRepresentation="... "+De.slice(-(4*768-4)):P.stringRepresentation=De}pe=Te.map(P=>P.stringRepresentation).join(`
684
- `)}pe.length>4*2048&&(pe="... "+pe.slice(-(4*2048-4))),An+=`Recent Manual Edits:
685
- ${pe}
686
- `}_e.length>0&&(An+=`All Opened Editors: ${_e.join(", ")}`),ft.diagnostics&&(An+=`
673
+ `+Se.slice(-128)),Sn+=`Current Selection: "${Se}"
674
+ `}if($t.manual_edits){let Se=$t.manual_edits.split(`
675
+ `),de=[];for(let Ne=0;Ne<Se.length;Ne++){let qe=Se[Ne],Ze=Se[Ne+1],Vt=Se[Ne+2];if(Ze!==void 0&&Vt!==void 0&&/:\s*$/.test(qe)&&/^\s*-\s*/.test(Ze)&&/^\s*\+\s*/.test(Vt)&&(Ze.length>300||Vt.length>300)){de.push(qe.replace(/:\s*$/,": [changed]")),Ne+=2;continue}de.push(qe)}Sn+=`Recent Manual Edits:
676
+ ${de.join(`
677
+ `)}
678
+ `}Re.length>0&&(Sn+=`All Opened Editors: ${Re.join(", ")}`),$t.diagnostics&&(Sn+=`
687
679
  **Active File Errors**:
688
- ${ft.diagnostics}
689
- `),(Me.toLowerCase().includes("lint")||Me.toLowerCase().includes("warning"))&&ft.warnings&&(An+=`
680
+ ${$t.diagnostics}
681
+ `),(_e.toLowerCase().includes("lint")||_e.toLowerCase().includes("warning"))&&$t.warnings&&(Sn+=`
690
682
  **Lint Warnings**:
691
- ${ft.warnings}
692
- `)}let bs=Me.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),ws=/(?:\\)?@\[([^\]]+)\]/g,bi,wi=[];for(ws.lastIndex=0;(bi=ws.exec(bs))!==null;){let v=bi[0].startsWith("\\");wi.push({tag:bi[1],isEscaped:v})}let Si=[],jo=null;for(let v=0;v<wi.length;v++){let{tag:_e,isEscaped:qt}=wi[v];if(!qt)try{let Ie=_e.trim().replace(/^["']|["']$/g,""),me=/[:#]L?(\d+)(?:-L?(\d+))?$/i,Ue=Ie.match(me),qe=Ie,Ze=null,Nt=null;Ue&&(Ze=parseInt(Ue[1],10),Nt=Ue[2]?parseInt(Ue[2],10):Ze,qe=Ie.slice(0,Ue.index));let Te=W.resolve(process.cwd(),qe);if(Ae.existsSync(Te)&&Ae.statSync(Te).isFile()){let P=qe.toLowerCase(),De=P.endsWith(".pdf"),xt=P.endsWith(".docx")||P.endsWith(".doc")||P.endsWith(".ppt")||P.endsWith(".pptx")||P.endsWith(".xls")||P.endsWith(".xlsx"),un=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(P),He=un||De||xt,Rt=s==="Google"||lt(e);if(He&&!Rt){let ve=`\u2718 Unsupported Modality: ${W.basename(qe)}`,ut=115;process.stdout.isTTY&&(ut=process.stdout.columns-5||120);let nn=[ve],je=Math.max(...nn.map(gn=>gn.length)),ne=Math.min(je+4,ut),We=nn.map(gn=>`${gn.padEnd(ne-2).substring(0,ne-2)}`).join(`
693
- `);yield{type:"visual_feedback",content:jt(`${We}
694
- `)};continue}if(Ze===null&&!He){let ve=0;try{ve=Ae.readFileSync(Te,"utf8").split(/\r\n|\r|\n/).length}catch{}if(ve>300){let ut=`\u21B7 Skipped (Too Large): ${W.basename(qe)}`,nn=115;process.stdout.isTTY&&(nn=process.stdout.columns-5||120);let je=Math.min(ut.length+4,nn),ne=ut.padEnd(je-2).substring(0,je-2);yield{type:"visual_feedback",content:jt(`${ne}
695
- `)};continue}}let En=Ze!==null?Ze:1,Bt=Nt!==null?Nt:Ze!==null?Ze:En+299;Bt-En>300&&(Bt=En+300);let Kn=`path=${JSON.stringify(qe)}, startLine=${En}, endLine=${Bt}`,Xt=await Bs(Kn,{isMultiModal:Rt}),Ln=!1,oo="",_t=null;if(typeof Xt=="string"?Xt.trim().startsWith("ERROR")?Ln=!0:oo=Xt:Xt&&typeof Xt=="object"&&Xt.binaryPart?(_t=Xt.binaryPart,oo=Xt.text||""):Ln=!0,!Ln){let ve="";if(un?(ve=`\u2714 Processed: ${W.basename(qe)}`,jo=_t):De||xt?(ve=`\u2714 Auto-Analysed: ${W.basename(qe)}`,jo=_t):(ve=`\u2714 Auto-Read: ${W.basename(qe)}`,Si.push(oo)),ve){let ut=115;process.stdout.isTTY&&(ut=process.stdout.columns-5||120);let nn=[ve],je=Math.max(...nn.map(gn=>gn.length)),ne=Math.min(je+4,ut),We=nn.map(gn=>`${gn.padEnd(ne-2).substring(0,ne-2)}`).join(`
696
- `);yield{type:"visual_feedback",content:jt(`${We}
697
- `)}}}}}catch{}}let ki="";Si.length>0&&(ki=`
683
+ ${$t.warnings}
684
+ `)}let bs=_e.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),ws=/(?:\\)?@\[([^\]]+)\]/g,wi,Si=[];for(ws.lastIndex=0;(wi=ws.exec(bs))!==null;){let I=wi[0].startsWith("\\");Si.push({tag:wi[1],isEscaped:I})}let ki=[],jo=null;for(let I=0;I<Si.length;I++){let{tag:Re,isEscaped:Kt}=Si[I];if(!Kt)try{let Se=Re.trim().replace(/^["']|["']$/g,""),de=/[:#]L?(\d+)(?:-L?(\d+))?$/i,Ne=Se.match(de),qe=Se,Ze=null,Vt=null;Ne&&(Ze=parseInt(Ne[1],10),Vt=Ne[2]?parseInt(Ne[2],10):Ze,qe=Se.slice(0,Ne.index));let At=V.resolve(process.cwd(),qe);if(ke.existsSync(At)&&ke.statSync(At).isFile()){let Yt=qe.toLowerCase(),ho=Yt.endsWith(".pdf"),Hn=Yt.endsWith(".docx")||Yt.endsWith(".doc")||Yt.endsWith(".ppt")||Yt.endsWith(".pptx")||Yt.endsWith(".xls")||Yt.endsWith(".xlsx"),jn=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(Yt),Ue=jn||ho||Hn,Mt=s==="Google"||st(e);if(Ue&&!Mt){let ve=`\u2718 Unsupported Modality: ${V.basename(qe)}`,lt=115;process.stdout.isTTY&&(lt=process.stdout.columns-5||120);let en=[ve],We=Math.max(...en.map(dn=>dn.length)),te=Math.min(We+4,lt),Fe=en.map(dn=>`${dn.padEnd(te-2).substring(0,te-2)}`).join(`
685
+ `);yield{type:"visual_feedback",content:Wt(`${Fe}
686
+ `)};continue}if(Ze===null&&!Ue){let ve=0;try{ve=ke.readFileSync(At,"utf8").split(/\r\n|\r|\n/).length}catch{}if(ve>300){let lt=`\u21B7 Skipped (Too Large): ${V.basename(qe)}`,en=115;process.stdout.isTTY&&(en=process.stdout.columns-5||120);let We=Math.min(lt.length+4,en),te=lt.padEnd(We-2).substring(0,We-2);yield{type:"visual_feedback",content:Wt(`${te}
687
+ `)};continue}}let kn=Ze!==null?Ze:1,Nt=Vt!==null?Vt:Ze!==null?Ze:kn+299;Nt-kn>300&&(Nt=kn+300);let Kn=`path=${JSON.stringify(qe)}, startLine=${kn}, endLine=${Nt}`,zt=await Bs(Kn,{isMultiModal:Mt}),Mn=!1,no="",kt=null;if(typeof zt=="string"?zt.trim().startsWith("ERROR")?Mn=!0:no=zt:zt&&typeof zt=="object"&&zt.binaryPart?(kt=zt.binaryPart,no=zt.text||""):Mn=!0,!Mn){let ve="";if(jn?(ve=`\u2714 Processed: ${V.basename(qe)}`,jo=kt):ho||Hn?(ve=`\u2714 Auto-Analysed: ${V.basename(qe)}`,jo=kt):(ve=`\u2714 Auto-Read: ${V.basename(qe)}`,ki.push(no)),ve){let lt=115;process.stdout.isTTY&&(lt=process.stdout.columns-5||120);let en=[ve],We=Math.max(...en.map(dn=>dn.length)),te=Math.min(We+4,lt),Fe=en.map(dn=>`${dn.padEnd(te-2).substring(0,te-2)}`).join(`
688
+ `);yield{type:"visual_feedback",content:Wt(`${Fe}
689
+ `)}}}}}catch{}}let Ti="";ki.length>0&&(Ti=`
698
690
  [Tagged File Contents] Auto Read User Tagged files by System, No need to re-read
699
- `+Si.join(`
691
+ `+ki.join(`
700
692
 
701
693
  `)+`
702
694
  [Tagged File Contents]
703
695
  `);let Ss=bs.replace(/\\(@\[[^\]]+\])/g,"$1"),ks=k?`You cannot execute tools. Instead write the action string in chat you WOULD have written
704
- `:"",ca=process.env.forcedReasoning||!1,Ts=c!=="Fast"&&(s==="Mistral"&&!ei(e)||c!=="High"&&s==="Google")?`${s==="Mistral"&&!ei(e)||e.toLowerCase().startsWith("gemma")||ca?`[system] strictly follow thinking policy as high priority. do not start a response without <think_fluxflow>...</think_fluxflow> [/system]
705
- `:""}`:"",no="";if(p?.clipboardContext)try{process.platform==="win32"?no=fs("powershell.exe -NoProfile -Command Get-Clipboard",{encoding:"utf8",stdio:["pipe","pipe","ignore"],timeout:1500}).replace(/\r?\n$/,""):process.platform==="darwin"?no=fs("pbpaste",{encoding:"utf8",stdio:["pipe","pipe","ignore"],timeout:1500}).replace(/\r?\n$/,""):no=fs("xclip -selection clipboard -o || xsel --clipboard --output",{encoding:"utf8",shell:!0,stdio:["pipe","pipe","ignore"],timeout:1500}).replace(/\r?\n$/,"")}catch{no=""}let Ko="",da=!!p?.autoExcludeMetadata,fa=!!(An||ki||ks||$t||Ts||it||p?.dynamicDirAwareness||p?.autoTruncateResults);da&&!fa?Ko=Ss.trim():Ko=`[System Metadata] Time: ${Oe}${it?`
706
- WARNING: CWD Changed from previous: "${Ct}" to current: "${process.cwd()}", write change in chat to avoid future path mismatches
707
- `:""}${An}
708
- ${no.trim().length>0?`[Clipboard Context]
709
- - ${no.trim()}
710
- `:""}${xi?`[Additional Comments]
711
- ${xi.trimEnd()}
696
+ `:"",ca=process.env.forcedReasoning||!1,Ts=d!=="Fast"&&(s==="Mistral"&&!ei(e)||d!=="High"&&s==="Google")?`${s==="Mistral"&&!ei(e)||e.toLowerCase().startsWith("gemma")||ca?`[system] strictly follow thinking policy as high priority. do not start a response without <think_fluxflow>...</think_fluxflow> [/system]
697
+ `:""}`:"",to="";if(p?.clipboardContext)try{process.platform==="win32"?to=us("powershell.exe -NoProfile -Command Get-Clipboard",{encoding:"utf8",stdio:["pipe","pipe","ignore"],timeout:1500}).replace(/\r?\n$/,""):process.platform==="darwin"?to=us("pbpaste",{encoding:"utf8",stdio:["pipe","pipe","ignore"],timeout:1500}).replace(/\r?\n$/,""):to=us("xclip -selection clipboard -o || xsel --clipboard --output",{encoding:"utf8",shell:!0,stdio:["pipe","pipe","ignore"],timeout:1500}).replace(/\r?\n$/,"")}catch{to=""}let Ko="",da=!!p?.autoExcludeMetadata,fa=!!(Sn||Ti||ks||It||Ts||tt||p?.dynamicDirAwareness||p?.autoTruncateResults);da&&!fa?Ko=Ss.trim():Ko=`[System Metadata] Time: ${Me}${tt?`
698
+ WARNING: CWD Changed from previous: "${St}" to current: "${process.cwd()}", write change in chat to avoid future path mismatches
699
+ `:""}${Sn}
700
+ ${to.trim().length>0?`[Clipboard Context]
701
+ - ${to.trim()}
702
+ `:""}${bi?`[Additional Comments]
703
+ ${bi.trimEnd()}
712
704
  `:""}Action format: [action:ActionName(...)]
713
705
  [/Metadata]
714
- ${$t}${Ts}${ki}${ks}[user prompt] ${Ss.trim()} [/user prompt]`.trim();let As={role:"user",text:Ko};jo&&(As.binaryPart=jo),b.forEach(v=>{v.text&&v.role==="agent"&&(v.text=Kt(v.text))}),b.push(As),$t&&n[n.length-1]?.id&&(yield{type:"summary_injected",content:{id:n[n.length-1].id,text:Ko}});let fn=null,On=a==="Flux"?50:15;On=a.toLowerCase().includes("cu")?75:On;let ua=Math.floor(On/2),Es=0,xn=16;yield{type:"status",content:process.env.HALLOWEEN_EEGG==="true"?"Consulting the spirits":"Connecting"},Et=!1;let Ti=[],Vo=!1,Cs=!1,jn=[],Ai=!1;for(let v=0;v<=On;v++){let _e=Math.floor(On*.95);if(v>=_e&&Es<_e&&typeof t?.onAskUser=="function"){Es=_e;try{let X="Agent has been running for a long time. Do you want to continue execution?",B=[{id:"continue",label:"Continue",description:"Add few more steps"},{id:"cancel",label:"Cancel",description:"Stop extending and finish current turn limit"}],$=await t.onAskUser(X,B);$&&($.toLowerCase().includes("continue")||$==="Continue")&&(On+=ua)}catch{}}if(jn.length>=10&&typeof t?.onAskUser=="function"){let X={},B=null;for(let $ of jn)if(X[$]=(X[$]||0)+1,X[$]>=10){B=$;break}if(B)try{let $="Agent seems stuck in a tool loop. You can prompt it to steer or break the loop:",pt=[{id:"continue",label:"Continue Anyway",description:"Ignore warning and let it proceed"},{id:"stop",label:"Stop Loop",description:"Force agent to summarize progress and stop repeating"}],Fe=await t.onAskUser($,pt);if(Fe){let Ke="";typeof Fe=="string"&&(Fe.toLowerCase()==="stop"||Fe.includes("Stop Loop"))?Ke="STOP REPEATING THE SAME TOOL CALL. Acknowledge what failed or succeeded, summarize your current findings, and conclude.":typeof Fe=="string"&&(Fe.toLowerCase()==="continue"||Fe.includes("Continue Anyway"))?jn=jn.filter(It=>It!==B):Ke=typeof Fe=="string"?Fe:Fe?.label||Fe?.id||"",Ke&&(b.length>0&&b[b.length-1].role==="user"?b[b.length-1].text+=`
706
+ ${It}${Ts}${Ti}${ks}[user prompt] ${Ss.trim()} [/user prompt]`.trim();let As={role:"user",text:Ko};jo&&(As.binaryPart=jo),b.forEach(I=>{I.text&&I.role==="agent"&&(I.text=Lt(I.text))}),b.push(As),It&&n[n.length-1]?.id&&(yield{type:"summary_injected",content:{id:n[n.length-1].id,text:Ko}});let cn=null,In=a==="Flux"?50:15;In=a.toLowerCase().includes("cu")?75:In;let ua=Math.floor(In/2),Es=0,hn=16;yield{type:"status",content:process.env.HALLOWEEN_EEGG==="true"?"Consulting the spirits":"Connecting"},wt=!1;let Ai=[],Vo=!1,Cs=!1,Gn=[],Ei=!1;for(let I=0;I<=In;I++){let Re=Math.floor(In*.95);if(I>=Re&&Es<Re&&typeof t?.onAskUser=="function"){Es=Re;try{let z="Agent has been running for a long time. Do you want to continue execution?",Z=[{id:"continue",label:"Continue",description:"Add few more steps"},{id:"cancel",label:"Cancel",description:"Stop extending and finish current turn limit"}],M=await t.onAskUser(z,Z);M&&(M.toLowerCase().includes("continue")||M==="Continue")&&(In+=ua)}catch{}}if(Gn.length>=10&&typeof t?.onAskUser=="function"){let z={},Z=null;for(let M of Gn)if(z[M]=(z[M]||0)+1,z[M]>=10){Z=M;break}if(Z)try{let M="Agent seems stuck in a tool loop. You can prompt it to steer or break the loop:",ct=[{id:"continue",label:"Continue Anyway",description:"Ignore warning and let it proceed"},{id:"stop",label:"Stop Loop",description:"Force agent to summarize progress and stop repeating"}],Pe=await t.onAskUser(M,ct);if(Pe){let Ge="";typeof Pe=="string"&&(Pe.toLowerCase()==="stop"||Pe.includes("Stop Loop"))?Ge="STOP REPEATING THE SAME TOOL CALL. Acknowledge what failed or succeeded, summarize your current findings, and conclude.":typeof Pe=="string"&&(Pe.toLowerCase()==="continue"||Pe.includes("Continue Anyway"))?Gn=Gn.filter(Et=>Et!==Z):Ge=typeof Pe=="string"?Pe:Pe?.label||Pe?.id||"",Ge&&(b.length>0&&b[b.length-1].role==="user"?b[b.length-1].text+=`
715
707
 
716
- [STEERING HINT from USER, High Priority] ${Ke.trim()} [/STEERING HINT]`:b.push({role:"user",text:`[STEERING HINT from USER, High Priority] ${Ke.trim()} [/STEERING HINT]`}),yield{type:"status",content:"Steering Hint Injected..."},jn=jn.filter(It=>It!==B))}}catch{}}let qt=await $i("agent",t);if(!qt.allowed)throw new Error(qt.reason||`Budget Exhausted for Provider (${s||"Agent"})`);let Ie=[];if(Vo=!1,(a==="ICU"||a==="FluxCU")&&!Ai)try{yield{type:"status",content:"Capturing Screen"},await new Promise($=>setTimeout($,1e3));let{captureGriddedScreenshot:X}=await import("./screen_grid-IWNA3DA2.js"),B=await X();if(B&&B.base64){let $="[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]",pt={inlineData:{mimeType:B.mimeType,data:B.base64}},Fe=p?.imageHistoryCU||"Standard",Ke=Fe==="Low"?3:Fe==="Extended"?10:Fe==="Max"?999:5,It=b.filter(Ee=>Array.isArray(Ee.parts)&&Ee.parts.some(vt=>vt.inlineData));if(It.length>=Ke){let Ee=It.length-Ke+1;for(let vt=0;vt<Ee;vt++){let gt=It[vt];Array.isArray(gt.parts)&&(gt.parts=gt.parts.filter(bt=>!bt.inlineData))}}if(b.length>0&&b[b.length-1].role==="user"){let Ee=b[b.length-1];typeof Ee.text=="string"&&(Ee.text+=`
708
+ [STEERING HINT from USER, High Priority] ${Ge.trim()} [/STEERING HINT]`:b.push({role:"user",text:`[STEERING HINT from USER, High Priority] ${Ge.trim()} [/STEERING HINT]`}),yield{type:"status",content:"Steering Hint Injected..."},Gn=Gn.filter(Et=>Et!==Z))}}catch{}}let Kt=await Ni("agent",t);if(!Kt.allowed)throw new Error(Kt.reason||`Budget Exhausted for Provider (${s||"Agent"})`);let Se=[];if(Vo=!1,(a==="ICU"||a==="FluxCU")&&!Ei)try{yield{type:"status",content:"Capturing Screen"},await new Promise(M=>setTimeout(M,1e3));let{captureGriddedScreenshot:z}=await import("./screen_grid-IWNA3DA2.js"),Z=await z();if(Z&&Z.base64){let M="[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]",ct={inlineData:{mimeType:Z.mimeType,data:Z.base64}},Pe=p?.imageHistoryCU||"Standard",Ge=Pe==="Low"?3:Pe==="Extended"?10:Pe==="Max"?999:5,Et=b.filter(Te=>Array.isArray(Te.parts)&&Te.parts.some(Tt=>Tt.inlineData));if(Et.length>=Ge){let Te=Et.length-Ge+1;for(let Tt=0;Tt<Te;Tt++){let dt=Et[Tt];Array.isArray(dt.parts)&&(dt.parts=dt.parts.filter(mt=>!mt.inlineData))}}if(b.length>0&&b[b.length-1].role==="user"){let Te=b[b.length-1];typeof Te.text=="string"&&(Te.text+=`
717
709
 
718
- ${$}`,Array.isArray(Ee.parts)||(Ee.parts=[{text:Ee.text}]),Ee.parts.push(pt))}else b.push({role:"user",text:$,parts:[{text:$},pt]})}}catch(X){console.error("Vision screenshot capture error:",X)}if(Ai=!1,p?.compression===0&&(f?.tokens||0)>Vt&&(b=Fs(b,6)),v>0?yield{type:"status",content:process.env.HALLOWEEN_EEGG==="true"?"Haunting":"Working"}:yield{type:"status",content:process.env.HALLOWEEN_EEGG==="true"?"Consulting the spirits":"Connecting"},Et){try{let{clearPendingNudges:X}=await import("./subagent_state-LZCOZSUJ.js");X()}catch{}yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
710
+ ${M}`,Array.isArray(Te.parts)||(Te.parts=[{text:Te.text}]),Te.parts.push(ct))}else b.push({role:"user",text:M,parts:[{text:M},ct]})}}catch(z){console.error("Vision screenshot capture error:",z)}if(Ei=!1,p?.compression===0&&(f?.tokens||0)>Gt&&(b=Fs(b,6)),I>0?yield{type:"status",content:process.env.HALLOWEEN_EEGG==="true"?"Haunting":"Working"}:yield{type:"status",content:process.env.HALLOWEEN_EEGG==="true"?"Consulting the spirits":"Connecting"},wt){try{let{clearPendingNudges:z}=await import("./subagent_state-LZCOZSUJ.js");z()}catch{}yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
719
711
 
720
- \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}try{let{consumePendingNudges:X}=await import("./subagent_state-LZCOZSUJ.js"),B=X();if(B&&B.length>0){let $=B.join(`
712
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}try{let{consumePendingNudges:z}=await import("./subagent_state-LZCOZSUJ.js"),Z=z();if(Z&&Z.length>0){let M=Z.join(`
721
713
 
722
714
  `);b.length>0&&b[b.length-1].role==="user"?b[b.length-1].text+=`
723
715
 
724
- ${$}`:b.push({role:"user",text:$}),yield{type:"status",content:"Subagent Update"}}}catch{}if(i){let X=await i();X&&(X.startsWith("/btw")?b.length>0&&b[b.length-1].role==="user"?b[b.length-1].text+=`
716
+ ${M}`:b.push({role:"user",text:M}),yield{type:"status",content:"Subagent Update"}}}catch{}if(i){let z=await i();z&&(z.startsWith("/btw")?b.length>0&&b[b.length-1].role==="user"?b[b.length-1].text+=`
725
717
 
726
718
  [system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
727
- [question] ${X.replace("/btw","").trim()} [/question]`:b.push({role:"user",text:`[system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
728
- [question] ${X.replace("/btw","").trim()} [/question]`}):b.length>0&&b[b.length-1].role==="user"?b[b.length-1].text+=`
719
+ [question] ${z.replace("/btw","").trim()} [/question]`:b.push({role:"user",text:`[system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
720
+ [question] ${z.replace("/btw","").trim()} [/question]`}):b.length>0&&b[b.length-1].role==="user"?b[b.length-1].text+=`
729
721
 
730
- [STEERING HINT from USER, High Priority] ${X.trim()} [/STEERING HINT]`:b.push({role:"user",text:`[STEERING HINT from USER, High Priority] ${X.trim()} [/STEERING HINT]`}),yield{type:"status",content:`${X.startsWith("/btw")?"Question Forwarded...":"Steering Hint Injected..."}`})}let me,Ue=!1,qe=1,Ze=1,Nt=Date.now(),Te=null,pe="",P=null,De=null,xt=null,un=0,He=[],Rt=0,En=!1,Bt=!1,Kn=!1,Xt=!1,Ln=!0,oo=0,_t="",ve="",ut=!1,nn=!1,je=!0,ne=e,We="",gn=c;for(c=c.toLowerCase()==="max"?"High":c;qe<=xn&&Ze<=xn&&!Ue&&!Et;){let X=!1;try{pe="",Ln&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},Ln=!1,Ze===1&&(_t=""));let B=m=>{if(!m||typeof m!="string")return m;let A="",C=gs(m);if(C&&(A=C.fullBlock,m=C.remainingText),!m.includes("[tool:")&&!m.includes("[action:"))return(p?.keepReasoningContext?A:"")+m;if(eo(m).length===0){let w=hi(m);return(p?.keepReasoningContext?A:"")+w}m=m.replace(gl,(w,R)=>R.includes("[tool:")||R.includes("[action:")?R.trim():w);let le="",F=0,Q=[],St="";for(;F<m.length;){let w=m.indexOf("[tool:",F),R=m.indexOf("[action:",F),oe=-1;if(w!==-1&&R!==-1?oe=Math.min(w,R):w!==-1?oe=w:oe=R,oe===-1){Q.length===0&&(le+=hi(m.substring(F)));break}if((oe>0?m[oe-1]:"")==="`"){le+=hi(m.substring(F,oe+1)),F=oe+1;continue}Q.length===0&&(St=hi(m.substring(F,oe)));let Z=-1,M=null,kt=0;for(let Wt=oe;Wt<m.length;Wt++){let ie=m[Wt];if(M){if(ie===M){let Xe=0;for(let Tt=Wt-1;Tt>=0&&m[Tt]==="\\";Tt--)Xe++;Xe%2===0&&(M=null)}}else if(ie==='"'||ie==="'"||ie==="`")M=ie;else if(ie==="(")kt++;else if(ie===")")kt--;else if(ie==="]"&&kt<=0){Z=Wt;break}}if(Z===-1){Q.length===0&&(le+=m.substring(oe));break}let Rn=m.substring(oe,Z+1);Q.push(Rn),F=Z+1}return Q.length>0&&(le=St.trimEnd()?St.trimEnd()+`
722
+ [STEERING HINT from USER, High Priority] ${z.trim()} [/STEERING HINT]`:b.push({role:"user",text:`[STEERING HINT from USER, High Priority] ${z.trim()} [/STEERING HINT]`}),yield{type:"status",content:`${z.startsWith("/btw")?"Question Forwarded...":"Steering Hint Injected..."}`})}let de,Ne=!1,qe=1,Ze=1,Vt=Date.now(),At=null,Ee="",Yt=null,ho=null,Hn=null,jn=0,Ue=[],Mt=0,kn=!1,Nt=!1,Kn=!1,zt=!1,Mn=!0,no=0,kt="",ve="",lt=!1,en=!1,We=!0,te=e,Fe="",dn=d;for(d=d.toLowerCase()==="max"?"High":d;qe<=hn&&Ze<=hn&&!Ne&&!wt;){let z=!1;try{Ee="",Mn&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},Mn=!1,Ze===1&&(kt=""));let Z=m=>{if(!m||typeof m!="string")return m;let A="",C=ms(m);if(C&&(A=C.fullBlock,m=C.remainingText),!m.includes("[tool:")&&!m.includes("[action:"))return(p?.keepReasoningContext?A:"")+m;if(Wn(m).length===0){let w=hi(m);return(p?.keepReasoningContext?A:"")+w}m=m.replace(ml,(w,R)=>R.includes("[tool:")||R.includes("[action:")?R.trim():w);let ae="",D=0,X=[],ht="";for(;D<m.length;){let w=m.indexOf("[tool:",D),R=m.indexOf("[action:",D),ne=-1;if(w!==-1&&R!==-1?ne=Math.min(w,R):w!==-1?ne=w:ne=R,ne===-1){X.length===0&&(ae+=hi(m.substring(D)));break}if((ne>0?m[ne-1]:"")==="`"){ae+=hi(m.substring(D,ne+1)),D=ne+1;continue}X.length===0&&(ht=hi(m.substring(D,ne)));let J=-1,P=null,yt=0;for(let Ft=ne;Ft<m.length;Ft++){let oe=m[Ft];if(P){if(oe===P){let Ve=0;for(let xt=Ft-1;xt>=0&&m[xt]==="\\";xt--)Ve++;Ve%2===0&&(P=null)}}else if(oe==='"'||oe==="'"||oe==="`")P=oe;else if(oe==="(")yt++;else if(oe===")")yt--;else if(oe==="]"&&yt<=0){J=Ft;break}}if(J===-1){X.length===0&&(ae+=m.substring(ne));break}let An=m.substring(ne,J+1);X.push(An),D=J+1}return X.length>0&&(ae=ht.trimEnd()?ht.trimEnd()+`
731
723
 
732
- `+Q.join(`
724
+ `+X.join(`
733
725
 
734
- `):Q.join(`
726
+ `):X.join(`
735
727
 
736
- `)),(p?.keepReasoningContext?A:"")+le},$=b.filter(m=>(m.role==="user"||m.role==="agent"||m.role==="system")&&!String(m.id).startsWith("welcome")&&!m.isMeta&&!m.isTerminalRecord&&!(m.text&&m.text.startsWith("[TERMINAL_RECORD]"))).map((m,A,C)=>{let J=m.text||"";E||(J=J.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),m.role==="agent"&&(J=B(J),J=J.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),J=J.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*"));let le=[];return Array.isArray(m.parts)&&m.parts.length>0?le=m.parts.map(F=>{if(F.text){let Q=F.text;return E||(Q=Q.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),m.role==="agent"&&(Q=B(Q),Q=Q.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),Q=Q.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*")),{text:Q}}return F}):le=[{text:J}],m.binaryPart&&lt(ne)&&C.slice(A+1).filter(Q=>Q.role==="user"&&!Q.text?.startsWith("[ACTION RESULT]")&&!Q.text?.startsWith("[TOOL RESULT]")).length<=2&&le.push(m.binaryPart),{role:m.role==="user"||m.role==="system"?"user":"model",parts:le}});for(let m=$.length-2;m>=0;m--){let A=$[m],C=$[m+1];A.role==="user"&&C.role==="user"&&(C.parts?.[0]?.text||"").trim().startsWith("[SYSTEM")&&$.splice(m,1)}let pt=[];for(let m=0;m<$.length;m++){let A=$[m];if(pt.length===0)pt.push(A);else{let C=pt[pt.length-1];C.role===A.role?(C.parts[0].text+=`
728
+ `)),(p?.keepReasoningContext?A:"")+ae},M=b.filter(m=>(m.role==="user"||m.role==="agent"||m.role==="system")&&!String(m.id).startsWith("welcome")&&!m.isMeta&&!m.isTerminalRecord&&!(m.text&&m.text.startsWith("[TERMINAL_RECORD]"))).map((m,A,C)=>{let q=m.text||"";E||(q=q.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),m.role==="agent"&&(q=Z(q),q=q.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),q=q.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*"));let ae=[];return Array.isArray(m.parts)&&m.parts.length>0?ae=m.parts.map(D=>{if(D.text){let X=D.text;return E||(X=X.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),m.role==="agent"&&(X=Z(X),X=X.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),X=X.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*")),{text:X}}return D}):ae=[{text:q}],m.binaryPart&&st(te)&&C.slice(A+1).filter(X=>X.role==="user"&&!X.text?.startsWith("[ACTION RESULT]")&&!X.text?.startsWith("[TOOL RESULT]")).length<=2&&ae.push(m.binaryPart),{role:m.role==="user"||m.role==="system"?"user":"model",parts:ae}});for(let m=M.length-2;m>=0;m--){let A=M[m],C=M[m+1];A.role==="user"&&C.role==="user"&&(C.parts?.[0]?.text||"").trim().startsWith("[SYSTEM")&&M.splice(m,1)}let ct=[];for(let m=0;m<M.length;m++){let A=M[m];if(ct.length===0)ct.push(A);else{let C=ct[ct.length-1];C.role===A.role?(C.parts[0].text+=`
737
729
 
738
- `+(A.parts?.[0]?.text||""),A.parts?.length>1&&C.parts.push(...A.parts.slice(1))):pt.push(A)}}for(let m of pt)for(let A of m.parts||[])A&&typeof A.text=="string"&&(A.text.includes("[action:")||A.text.includes("[tool:"))&&(A.text=A.text.replace(/```(?:[a-zA-Z0-9_-]+)?\s*\n?(\[(?:action|tool):[\s\S]*?\)\s*\])\n?```/gi,"$1"),A.text=A.text.replace(/`(\[(?:action|tool):[\s\S]*?\)\s*\])`/gi,"$1"));$.length=0,$.push(...pt),ne=e;let Fe=`${h}|${s}|${a}|${c}|${gn}|${ne}|${JSON.stringify(r)}|${!!p?.dynamicDirAwareness}|${!!p?.subAgents}`,Ke=Qn.key===Fe&&Qn.value;if((process.env.I_HAVE_TOO_MUCH_MONEY==="true"||process.env.I_HAVE_TOO_MUCH_MONEY===!0)&&(Ke=!1),Ke)We=Qn.value;else{let m=s==="Mistral"?!!ei(ne):!(ne||"gemma").toLowerCase().startsWith("gemma");We=Er(r,((ne||"gemma").toLowerCase().startsWith("gemma"),gn),a,p,E,T,s,s==="Google"?!0:y,m,h,!!p?.keepReasoningContext,ne),p?.dynamicDirAwareness||(We+=`
730
+ `+(A.parts?.[0]?.text||""),A.parts?.length>1&&C.parts.push(...A.parts.slice(1))):ct.push(A)}}for(let m of ct)for(let A of m.parts||[])A&&typeof A.text=="string"&&(A.text.includes("[action:")||A.text.includes("[tool:"))&&(A.text=A.text.replace(/```(?:[a-zA-Z0-9_-]+)?\s*\n?(\[(?:action|tool):[\s\S]*?\)\s*\])\n?```/gi,"$1"),A.text=A.text.replace(/`(\[(?:action|tool):[\s\S]*?\)\s*\])`/gi,"$1"));M.length=0,M.push(...ct),te=e;let Pe=`${h}|${s}|${a}|${d}|${dn}|${te}|${JSON.stringify(r)}|${!!p?.dynamicDirAwareness}|${!!p?.subAgents}`,Ge=Qn.key===Pe&&Qn.value;if((process.env.I_HAVE_TOO_MUCH_MONEY==="true"||process.env.I_HAVE_TOO_MUCH_MONEY===!0)&&(Ge=!1),Ge)Fe=Qn.value;else{let m=s==="Mistral"?!!ei(te):!(te||"gemma").toLowerCase().startsWith("gemma");Fe=Er(r,((te||"gemma").toLowerCase().startsWith("gemma"),dn),a,p,E,T,s,s==="Google"?!0:y,m,h,!!p?.keepReasoningContext,te),p?.dynamicDirAwareness||(Fe+=`
739
731
  ${la.replace(`
740
732
  **Directory**`,`
741
- -- Directory --`)}`),Qn.key=Fe,Qn.value=We}let Ee=$[$.length-1];if(go()&v>0){await new Promise(J=>setTimeout(J,2500)),yield{type:"status",content:"Verifying"};let m=await Jn(),A=m?m.diagnostics:null,C=xs(m?.comments);A&&Ee&&Ee.role==="user"&&Ee.parts?.[0]?.text&&(Ee.parts[0].text+=`
733
+ -- Directory --`)}`),Qn.key=Pe,Qn.value=Fe}let Te=M[M.length-1];if(uo()&I>0){await new Promise(q=>setTimeout(q,2500)),yield{type:"status",content:"Verifying"};let m=await Jn(),A=m?m.diagnostics:null,C=xs(m?.comments);A&&Te&&Te.role==="user"&&Te.parts?.[0]?.text&&(Te.parts[0].text+=`
742
734
 
743
- ${A}`),xi&&Ee&&Ee.role==="user"&&Ee.parts?.[0]?.text&&(Ee.parts[0].text+=`
735
+ ${A}`),bi&&Te&&Te.role==="user"&&Te.parts?.[0]?.text&&(Te.parts[0].text+=`
744
736
 
745
737
  [Additional Comments]
746
- ${C}`),yield{type:"status",content:"Working"}}let vt=s==="Mistral"||s==="Google"&&e?.toLowerCase().startsWith("gemma");if(p?.advanceRollback&&Ee&&Ee.role==="user"&&(Ee.parts?.[0]?.text?.startsWith("[ACTION RESULT]")||Ee.parts?.[0]?.text?.startsWith("[TOOL RESULT]")))try{let m=await Ro.getLatestFileChanges(h);if(m&&(m.newFiles.length>0||m.modifiedFiles.length>0||m.deletedFiles.length>0)){let A=`
738
+ ${C}`),yield{type:"status",content:"Working"}}let Tt=s==="Mistral"||s==="Google"&&e?.toLowerCase().startsWith("gemma");if(p?.advanceRollback&&Te&&Te.role==="user"&&(Te.parts?.[0]?.text?.startsWith("[ACTION RESULT]")||Te.parts?.[0]?.text?.startsWith("[TOOL RESULT]")))try{let m=await Ro.getLatestFileChanges(h);if(m&&(m.newFiles.length>0||m.modifiedFiles.length>0||m.deletedFiles.length>0)){let A=`
747
739
  [system] File Changes:
748
- `;for(let J of m.newFiles)A+=`* ${J} (created)
749
- `;for(let J of m.modifiedFiles)A+=`* ${J} (modified)
750
- `;for(let J of m.deletedFiles)A+=`* ${J} (deleted)
751
- `;A+="[/system]",Ee.parts[0].text+=A;let C=-1;for(let J=b.length-1;J>=0;J--)if(b[J].role==="user"&&(b[J].text?.startsWith("[ACTION RESULT]")||b[J].text?.startsWith("[TOOL RESULT]"))){C=J;break}C!==-1&&(b[C].text+=A)}}catch{}let gt=Math.floor(On*.99),bt=v+1;if(bt>=gt&&Ee&&Ee.parts?.[0]&&(Ee.parts[0].text+=`
752
- [system] WARNING, Turn Limit Impending: Step ${bt}/${On}. Wrap up quickly/prompt user to continue. [/system]`),process.env.LOG_CHAT==="true"||process.env.LOG_CHAT==="1"||process.env.LOG_CHAT===!0||!1){let m=W.join(wn,"chats",String(h));Ae.existsSync(m)||Ae.mkdirSync(m,{recursive:!0}),Ae.writeFileSync(W.join(m,"context.json"),JSON.stringify({contents:$},null,2)),Ae.writeFileSync(W.join(m,"system.md"),`${Ke?"CACHED":"NOT CACHED"}
753
- Key: ${Fe}
740
+ `;for(let q of m.newFiles)A+=`* ${q} (created)
741
+ `;for(let q of m.modifiedFiles)A+=`* ${q} (modified)
742
+ `;for(let q of m.deletedFiles)A+=`* ${q} (deleted)
743
+ `;A+="[/system]",Te.parts[0].text+=A;let C=-1;for(let q=b.length-1;q>=0;q--)if(b[q].role==="user"&&(b[q].text?.startsWith("[ACTION RESULT]")||b[q].text?.startsWith("[TOOL RESULT]"))){C=q;break}C!==-1&&(b[C].text+=A)}}catch{}let dt=Math.floor(In*.99),mt=I+1;if(mt>=dt&&Te&&Te.parts?.[0]&&(Te.parts[0].text+=`
744
+ [system] WARNING, Turn Limit Impending: Step ${mt}/${In}. Wrap up quickly/prompt user to continue. [/system]`),process.env.LOG_CHAT==="true"||process.env.LOG_CHAT==="1"||process.env.LOG_CHAT===!0||!1){let m=V.join(yn,"chats",String(h));ke.existsSync(m)||ke.mkdirSync(m,{recursive:!0}),ke.writeFileSync(V.join(m,"context.json"),JSON.stringify({contents:M},null,2)),ke.writeFileSync(V.join(m,"system.md"),`${Ge?"CACHED":"NOT CACHED"}
745
+ Key: ${Pe}
754
746
  --------------------------------------------------------------------
755
747
 
756
- ${We}`)}let Dt=new Promise((m,A)=>{G.signal.aborted&&A(new DOMException("The user aborted a request.","AbortError")),G.signal.addEventListener("abort",()=>{A(new DOMException("The user aborted a request.","AbortError"))})});Dt.catch(()=>{});let Ge=$;if(Nt=Date.now(),s==="Ollama")me=(await ce("Ollama"))(t.apiKey,ne,Ge,We,c,a,y,G.signal,1,p?.ollamaEndpoint||"Cloud");else if(s==="OpenRouter")me=(await ce("OpenRouter"))(t.apiKey,ne,Ge,We,c,a,y,G.signal,1,h);else if(s==="DeepSeek")me=(await ce("DeepSeek"))(t.apiKey,ne,Ge,We,c,a,y,G.signal,1);else if(s==="Mistral")me=(await ce("Mistral"))(t.apiKey,ne,Ge,We,c,a,y,G.signal,1,h);else if(s==="NVIDIA"){let m=(await ce("NVIDIA"))(t.apiKey,ne,Ge,We,c,a,y,G.signal,1);me=(await ce("NVIDIA_wrap"))(m,ne)}else if(s==="InferX")me=(await ce("InferX"))(t.apiKey,ne,Ge,We,c,a,y,G.signal,1);else if(s==="SenseNova")me=(await ce("SenseNova"))(t.apiKey,ne,Ge,We,c,a,y,G.signal,1);else if(s==="AIHubMix")me=(await ce("AIHubMix"))(t.apiKey,ne,Ge,We,c,a,y,G.signal,1);else if(s==="Poolside")me=(await ce("Poolside"))(t.apiKey,ne,Ge,We,c,a,y,G.signal,1);else if(s==="9router"||s==="9Router")me=(await ce("NineRouter"))(t.apiKey,ne,Ge,We,c,a,y,G.signal,1);else if(s==="ExpLabs"||s==="ExperientialLabs")me=(await ce("ExpLabs"))(t.apiKey,ne,Ge,We,c,a,y,G.signal,1);else if(s==="Infron"||s==="infron")me=(await ce("Infron"))(t.apiKey,ne,Ge,We,c,a,y,G.signal,1);else if(s==="TokenHarbor"||s==="Token Harbor"||s==="tokenharbor"||s==="token_harbor"||s==="thk")me=(await ce("TokenHarbor"))(t.apiKey,ne,Ge,We,c,a,y,G.signal,1);else if(s==="APInex"||s==="apinex"||s==="apx")me=(await ce("APInex"))(t.apiKey,ne,Ge,We,c,a,y,G.signal,1);else if(s==="xKiro"||s==="xkiro"||s==="kiro")me=(await ce("xKiro"))(t.apiKey,ne,Ge,We,c,a,y,G.signal,1);else if(s==="c_openai"||s==="Custom (OpenAI)"){let m=p?.customOpenAIBaseUrl||"";try{m=await Oi("c_openai")||m}catch{}me=(await ce("c_openai"))(t.apiKey,ne,Ge,We,c,a,y,G.signal,1,m)}else{let m=hs(t?.apiKey),{serviceTier:A,cleanModel:C}=aa(ne),J={systemInstruction:We,mediaResolution:"MEDIA_RESOLUTION_HIGH",safetySettings:[{category:Hn.HARM_CATEGORY_HARASSMENT,threshold:Gn.BLOCK_NONE},{category:Hn.HARM_CATEGORY_HATE_SPEECH,threshold:Gn.BLOCK_NONE},{category:Hn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Gn.BLOCK_NONE},{category:Hn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Gn.BLOCK_NONE}],temperature:1.05,thinkingConfig:(()=>{let F=Ds("Google",ne||"gemini-3-flash-preview",c);if(F!==null){if(typeof F=="object")return F;if(F===!1||F==="false"||F==="none"||F===0||F==="0")return{includeThoughts:!1};if(typeof F=="number")return{includeThoughts:!0,thinkingBudget:F};if(typeof F=="string"){let R=F.toLowerCase();if(R==="minimal")return{includeThoughts:!0,thinkingLevel:Ye.MINIMAL};if(R==="low")return{includeThoughts:!0,thinkingLevel:Ye.LOW};if(R==="medium")return{includeThoughts:!0,thinkingLevel:Ye.MEDIUM};if(R==="high")return{includeThoughts:!0,thinkingLevel:Ye.HIGH};let oe=Number(F);if(!isNaN(oe))return{includeThoughts:!0,thinkingBudget:oe}}}let Q=(ne||"").toLowerCase(),St=Q.includes("gemma-4")||Q.startsWith("gemma"),w=Q.includes("gemini-3");if(St||w)return St?c.toLowerCase()!=="high"?{includeThoughts:!1,thinkingLevel:Ye.MINIMAL}:{includeThoughts:!0,thinkingLevel:Ye.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:Q.includes("pro")?Ye.LOW:Ye.MINIMAL,Low:Ye.LOW,Medium:Ye.MEDIUM,Standard:Ye.MEDIUM,High:Ye.HIGH,xHigh:Ye.HIGH}[c]||Ye.MEDIUM};{let R={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[c]||2048;return R===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:R}}})()};A&&(J.serviceTier=A);let le=m.models.generateContentStream({model:C||"gemini-3-flash-preview",contents:Ge,config:J},{signal:G.signal});me=await Promise.race([le,Dt])}pe="",P=null,xt=null,He=[],Rt=0,yield{type:"model_update",content:null},ve="",ut=_t.length>0;let Ut="",io=Date.now(),Yn=async function*(){if(s==="Google"&&Ut){let m=xo(Ut);for(let A of m)yield A;Ut="",io=Date.now()}},Rs=!0,Cn="",so=!1,wt=null,_s=!1,zn=!1,ro=!1,Yo=!1,$n=!1,yo=m=>{let A=0;for(;A+2<m.length;)m[A]==="`"&&m[A+1]==="`"&&m[A+2]==="`"?(Yo=!Yo,A+=3):A++},vs=m=>{if(!m)return;let A=/(?:<(\/?)think_fluxflow[^>]*>|\[(\/?)think_fluxflow\]|<\/?channel\|?>|<\|channel>thought)/gi,C;for(;(C=A.exec(m))!==null;){let J=C[0].toLowerCase();J.startsWith("</")||J.startsWith("[/")||J==="<channel|>"?$n=!1:$n=!0}},ha={tool:{startPrefix:"[tool",fullPrefix:"[tool:",endTag:"]"},action:{startPrefix:"[action",fullPrefix:"[action:",endTag:"]"},end:{startPrefix:"[[END]]",fullPrefix:"[[END]]",endTag:"[[END]]"},kimi_section:{startPrefix:"<|tool_calls_section_begin|>",fullPrefix:"<|tool_calls_section_begin|>",endTag:"<|tool_calls_section_end|>"},kimi_call:{startPrefix:"<|tool_call_begin|>",fullPrefix:"<|tool_call_begin|>",endTag:"<|tool_call_end|>"}},xo=m=>{let A=[],C=m,J=le=>{if(!le)return;if(!_s){A.push({type:"text",content:le}),yo(le),vs(le);return}let F=/(?:<(\/?)think_fluxflow[^>]*>|\[(\/?)think_fluxflow\]|<\/?channel\|?>|<\|channel>thought)/gi,Q=0,St;for(;(St=F.exec(le))!==null;){let R=le.substring(Q,St.index);if(R)if(yo(R),$n)A.push({type:"text",content:R});else{let Le=R.replace(/[^\r\n]/g,"");Le&&A.push({type:"text",content:Le})}let oe=St[0];yo(oe);let l=oe.toLowerCase();l.startsWith("</")||l.startsWith("[/")||l==="<channel|>"?$n=!1:$n=!0,A.push({type:"text",content:oe}),Q=F.lastIndex}let w=le.substring(Q);if(w)if(yo(w),$n)A.push({type:"text",content:w});else{let R=w.replace(/[^\r\n]/g,"");R&&A.push({type:"text",content:R})}};for(;C.length>0;)if(so){let le=Cn+C,F=ha[wt];if(F){let w=!1;if(le.length<F.startPrefix.length?F.startPrefix.startsWith(le)||(w=!0):le.startsWith(F.startPrefix)?le.length>=F.fullPrefix.length&&!le.startsWith(F.fullPrefix)&&(w=!0):w=!0,w){J(le),Cn="",so=!1,wt=null,zn=!1,ro=!1,C="";break}}let Q=-1,St=F?F.endTag:"]";if(wt==="tool"||wt==="action"){let w=0,R=null,oe=0,l=!1;for(let Le=0;Le<le.length;Le++){let Z=le[Le];if(R){if(Z===R){let M=0;for(let kt=Le-1;kt>=0&&le[kt]==="\\";kt--)M++;M%2===0&&(R=null)}}else if(Z==='"'||Z==="'")R=Z;else if(Z==="`")if(zn){Q=Le;break}else R=Z;else if(Z==="(")w++,l=!0;else if(Z===")")w--;else if(Z==="]"&&l&&w===0){Q=Le;break}}}else Q=le.indexOf(St);if(Q!==-1){let w=St.length,R=le.substring(0,Q+w);wt?.startsWith("kimi")||A.push({type:"text",content:R}),yo(R),vs(R),(wt==="tool"||wt==="action"||wt?.startsWith("kimi"))&&!zn&&!ro&&(_s=!0,jn.push(R.trim())),zn=!1,ro=!1,Cn="",so=!1,wt=null,C=le.substring(Q+w)}else{Cn=le,C="";break}}else{let le=C.indexOf("[tool"),F=C.indexOf("[action"),Q=C.indexOf("[[END]]"),St=C.indexOf("<|tool_calls_section_begin|>"),w=C.indexOf("<|tool_call_begin|>"),R=[{type:"tool",idx:le,start:"[tool",end:"]"},{type:"action",idx:F,start:"[action",end:"]"},{type:"end",idx:Q,start:"[[END]]",end:"[[END]]"},{type:"kimi_section",idx:St,start:"<|tool_calls_section_begin|>",end:"<|tool_calls_section_end|>"},{type:"kimi_call",idx:w,start:"<|tool_call_begin|>",end:"<|tool_call_end|>"}].filter(oe=>oe.idx!==-1).sort((oe,l)=>oe.idx-l.idx);if(R.length>0){let oe=R[0],l=C.substring(0,oe.idx);oe.idx>0&&J(l);let Le=oe.idx>0?C[oe.idx-1]:"";zn=Yo||Le==="`",ro=$n,so=!0,wt=oe.type,Cn="",C=C.substring(oe.idx)}else{let oe=["[tool","[action","[[END]]","<|tool_calls_section_begin|>","<|tool_call_begin|>"],l=-1;for(let Le of oe){for(let Z=Le.length-1;Z>0;Z--)if(C.endsWith(Le.substring(0,Z))){l=C.length-Z;let M=oe.indexOf(Le);M===0?wt="tool":M===1?wt="action":M===2?wt="end":M===3?wt="kimi_section":wt="kimi_call";break}if(l!==-1)break}if(l!==-1){if(l>0){let Z=C.substring(0,l);J(Z)}let Le=l>0?C[l-1]:"";zn=Yo||Le==="`",ro=$n,so=!0,Cn=C.substring(l),C=""}else{J(C);break}}}return A},ya=me[Symbol.asyncIterator]();for(;;){let{value:m,done:A}=await Promise.race([ya.next(),Dt]);if(A)break;if(m&&m.type==="status"){yield m;continue}let C="",J=m.candidates?.[0]?.content?.parts;if(J&&J.length>0)for(let F of J){let Q=typeof F.text=="string"?F.text:F.text?parseChunkText(F.text):"";F.thought?Q&&(X||(C+="<think_fluxflow>",X=!0),C+=Q):Q&&(X&&(C+="</think_fluxflow>",X=!1),C+=Q)}else m.text&&X&&(C+="</think_fluxflow>",X=!1);C=cl(C);let le=C?Ni(C):0;if(t&&typeof t.onTokenChunk=="function"&&t.onTokenChunk(C,le),Rs&&(Te===null&&(Te=Date.now()-Nt),yield{type:"status",content:process.env.HALLOWEEN_EEGG==="true"?"Performing dark ritual":"Thinking"},Rs=!1),Et){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
757
-
758
- \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(C){if(ut){if(ve+=C,ve.length>=64){let w=0,R=Math.min(_t.length,ve.length);for(let l=R;l>=10;l--)if(_t.endsWith(ve.substring(0,l))){w=l;break}let oe=ve.substring(w);if(oe){let Le=/(?:<think_fluxflow>|\[think_fluxflow\])(?:(?!(?:<\/think_fluxflow>|\[\/think_fluxflow\]))[\s\S])*$/i.test(_t)?oe.replace(/^\s*(?:<think_fluxflow>|\[think_fluxflow\])\s*/gi,""):oe.replace(/^\s*(?:<think_fluxflow>|\[think_fluxflow\])[\s\S]*?(?:<\/think_fluxflow>|\[\/think_fluxflow\])\s*/gi,"").replace(/^\s*(?:<think_fluxflow>|\[think_fluxflow\])\s*/gi,"");if(Le)if(pe+=Le,s==="Google")Ut+=Le;else{yield*Yn();let Z=xo(Le);for(let M of Z)yield M}}ut=!1,ve=""}continue}else if(pe+=C,s==="Google")Ut+=C;else{yield*Yn();let w=xo(C);for(let R of w)yield R}let F=yl(pe);if(F.inside){nn=!0,xt||(xt=Date.now());let R={Ask:"ask",AskUser:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",FindFile:"find_file",find_file:"find_file",findfile:"find_file",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Cancel:"cancel",Await:"await",wait:"wait",Answer:"answer",Steer:"steer",steer:"steer"}[F.toolName]||F.toolName,oe=F.args||"",l=null;if(["write_file","update_file","view_file","read_folder","find_file","write_pdf","write_docx","search_keyword","generate_image","file_map","invoke","invoke_sync","get_progress","await","wait","answer"].includes(R)){let Z=j(oe),M=Z.basename||Z.name||Z.path||Z.targetFile||Z.TargetFile||Z.directory||Z.file,kt=Z.keyword,Rn=Z.title||Z.task,Wt=Z.id||Z.taskId,ie=Z.timeout||Z.time||Z.seconds||Z.sec;if(kt!=null)l=String(kt).replace(Mn,"");else if(M)l=W.basename(String(M).replace(Mn,"").replace(Qr,"/"));else if(Rn&&(R==="invoke"||R==="invoke_sync"))l=String(Rn).replace(Mn,"").substring(0,30);else if(Wt&&R==="get_progress")l=String(Wt).replace(Mn,"");else if(ie&&R==="await"){let Xe=parseFloat(String(ie).replace(Mn,""));isNaN(Xe)?l=String(ie).replace(Mn,""):(Xe<5&&(Xe=5),Xe>120&&(Xe=180),l=(Gt=>{if(Gt>=60){let wo=Math.floor(Gt/60),_n=Gt%60;return`${wo}m${_n>0?` ${_n}s`:""}`}return`${Gt}s`})(Xe))}else if(ie&&R==="wait"){let Xe=parseFloat(String(ie).replace(Mn,""));isNaN(Xe)?l=String(ie).replace(Mn,""):(Xe<10&&(Xe=10),Xe>120&&(Xe=120),l=(Gt=>{if(Gt>=60){let wo=Math.floor(Gt/60),_n=Gt%60;return`${wo}m${_n>0?` ${_n}s`:""}`}return`${Gt}s`})(Xe))}else{let Xe=oe.match(rl);if(Xe){let Tt=Xe[1].replace(Mn,"");R==="invoke"||R==="invoke_sync"||R==="get_progress"?l=Tt.substring(0,30):l=R==="search_keyword"||R==="file_map"?Tt:W.basename(Tt.replace(Qr,"/"))}}}let Le=`${ms[R]||R}${l?` ${l}`:""}`;if((R!==P||l!==De)&&(P=R,De=l,yield{type:"status",content:`${Le}`},process.stdout.isTTY)){let M={WebSearch:"Searching",web_search:"Searching",WebScrape:"Reading",web_scrape:"Reading",ReadFile:"Reading",read_file:"Reading",ReadFolder:"Reading",read_folder:"Reading",WriteFile:"Writing",write_file:"Writing",UpdateFile:"Editing",update_file:"Editing",WritePdf:"Creating",write_pdf:"Creating",WriteDocx:"Creating",write_docx:"Creating",SearchKeyword:"Searching",search_keyword:"Searching",CodeSearch:"Searching",code_search:"Searching",FindFile:"Finding File",find_file:"Finding File",Run:"Executing",Ask:"User Input Required",AskUser:"User Input Required",Memory:"Updating Memory",GenerateImage:"Generating",InvokeSync:"Sub-Agent Working",invoke_sync:"Sub-Agent Working",Invoke:"Working",invoke:"Working",GetProgress:"Checking Progress",get_progress:"Checking Progress",Cancel:"Stopping Generalist",cancel:"Stopping Generalist",Await:"Waiting",await:"Waiting",wait:"Waiting",EmergencyRollback:"Rolling the Ball",Answer:"Answering Sub-Agent",answer:"Answering Sub-Agent",Steer:"Steering Sub-Agent",steer:"Steering Sub-Agent",Click:"Clicking",click:"Clicking",Drag:"Dragging",drag:"Dragging",Scroll:"Scrolling",scroll:"Scrolling",KeyboardTyping:"Typing",keyboard_typing:"Typing",KeyPress:"Pressing Key",key_press:"Pressing Key",RecaptureScreen:"Recapturing Screen",recapture_screen:"Recapturing Screen"}[R]||"Working";process.stdout.write(`\x1B]0;${M}...\x07`)}}if(pe.length-oo>800){oo=pe.length;let w=ra(pe,!1),R=gs(w),oe=R?(R.innerContent||"").trim():"",l=oe.split(/[.!?]\s+/).filter(be=>be.trim().length>10),Le=new Set(l),Z=l.length>25?(l.length-Le.size)/l.length:0,M=oe.split(/\s+/).filter(be=>be.length>0).length,kt=.9,Rn=.92,Wt=!1;if(s.toLowerCase().includes("google")&&(ne||"").toLowerCase().startsWith("gemma")){let d={low:2048,medium:4096,high:32768,max:65536,xhigh:65536}[c?.toLowerCase()]||16e3;Wt=M>d}if(Z>kt||Wt){yield{type:"status",content:`${Z>kt?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},Bt=!0,await new Promise(d=>setTimeout(d,3e3));break}let Tt=na(pe).trim().split(/[.!?]\s+/).filter(be=>be.trim().length>10),Gt=new Set(Tt);if((Tt.length>25?(Tt.length-Gt.size)/Tt.length:0)>Rn){yield{type:"status",content:"Response Loop Detected. Re-centering..."},Bt=!1,Xt=!0,await new Promise(be=>setTimeout(be,3e3));break}let _n=w.replace(Za,"").replace(el,"").replace(tl,"").replace(nl,""),Mt=_n.toLowerCase().split(/\s+/).map(be=>be.replace(ol,"")).filter(be=>be.length>0),bn=!1;if(Mt.length>=40)for(let be=1;be<=15;be++){let d=Math.max(8,Math.ceil(25/be));if(Mt.length<be*d)continue;let I=Mt.slice(Mt.length-be),V=I.join(" ");if(be>1&&V===I.slice(0,Math.floor(be/2)).join(" ").repeat(2).trim())continue;let ye=!0;for(let se=1;se<d;se++)if(Mt.slice(Mt.length-be*(se+1),Mt.length-be*se).join(" ")!==V){ye=!1;break}if(ye){bn=!0;break}}if(!bn){let be=_n.toLowerCase().replace(il,"");if(be.length>=80)for(let d=1;d<=10;d++){let I=Math.max(15,Math.ceil(45/d));if(be.length<d*I)continue;let V=be.substring(be.length-d),ye=!0;for(let se=1;se<I;se++)if(be.substring(be.length-d*(se+1),be.length-d*se)!==V){ye=!1;break}if(ye){bn=!0;break}}}if(bn){yield{type:"status",content:"Stuttering Detected. Re-centering..."},Bt=!1,Kn=!0,await new Promise(be=>setTimeout(be,3e3));break}}let Q=Kt(pe),St=eo(Q);for(;St.length>Rt;){yield*Yn();let w=St[Rt],R=Date.now(),l={Ask:"ask",AskUser:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",FindFile:"find_file",find_file:"find_file",findfile:"find_file",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Await:"await",await:"await",AwaitSubagent:"await",awaitSubagent:"await",Wait:"wait",wait:"wait",Answer:"answer",answer:"answer",AnswerSubagent:"answer",answerSubagent:"answer",Steer:"steer",steer:"steer",SteerSubagent:"steer",steerSubagent:"steer",Cancel:"cancel",cancel:"cancel",Click:"click",click:"click",Drag:"drag",drag:"drag",Scroll:"scroll",scroll:"scroll",KeyboardTyping:"keyboard_typing",keyboard_typing:"keyboard_typing",KeyPress:"key_press",key_press:"key_press",RecaptureScreen:"recapture_screen",recapture_screen:"recapture_screen",EmergencyRollback:"EmergencyRollback"}[w.toolName]||w.toolName,Le=ms[l]||w.toolName,Z=Zn(l,w.args);yield{type:"status",content:`${Le}${Z?` ${Z}`:""}`};let M="";if(l==="click"){let d=j(w.args);M=`\u2714 Clicked ${d.intendedClickText?`: ${d.intendedClickText}`:"Screen"}`}else if(l==="drag"){let d=j(w.args);M=`\u2714 Dragged: Cell ${d.fromGridId||""} \u2192 Cell ${d.toGridId||""}`}else if(l==="scroll"){let d=j(w.args);M=`\u2714 Scrolled: ${d.direction||"down"} (${d.amount||1})`}else if(l==="keyboard_typing"){let d=j(w.args);M=`\u2714 ${d.autoPressEnter?"Entered":"Typed"}: ${d.text?`"${d.text.length>20?d.text.substring(0,20)+"...":d.text}"`:""}`}else if(l==="key_press")M=`\u2714 Pressed Key: ${j(w.args).key||""}`;else if(l==="recapture_screen")M="\u2714 Recaptured Screen";else if(l==="web_search"){let{query:d,limit:I=10,aiMode:V=!1}=j(w.args);M=`${d?"\u2714":"\u2718"} ${V?"AI Search":"Searched"}: ${d?`${d}`:"No Search Query"}${V===!1&&d?` \u2192 ${I}`:""}`}else if(l==="web_scrape"){let d=j(w.args).url||null;M=`${d?"\u2714":"\u2718"} Visited: ${d||"No Source"}`}else if(l==="view_file"){let{path:d,StartLine:I,EndLine:V,start_line:ye,end_line:se,startLine:te,endLine:we}=j(w.args),ke=I||ye||te,ee=V||se||we,N=parseInt(ke)||1,z=parseInt(ee)||(ke?N+800:800),$e="...",Re=z,re=(d||"").trim().toLowerCase().replaceAll("\\","/");if(re.startsWith("#skill"))re.startsWith("#skill/global/fluxflow")||re.startsWith("#skills/global/fluxflow")||re.includes("#skill/fluxflow")||re.includes("#skills/fluxflow")?M="\u2714 Read Documentation":M=`\u2714 Read Skill: ${W.basename(d.replaceAll("\\","/"))}`;else{try{let xe=W.resolve(process.cwd(),d);if(Ae.existsSync(xe)){let U=Ae.readFileSync(xe,"utf8").split(`
759
- `).length;$e=U,!ke&&!ee&&U>800?Re=Math.min(50,U):Re=Math.min(z,U)}}catch{}let Pt=(d||"").toLowerCase(),on=Pt.endsWith(".pdf"),Ne=Pt.endsWith(".docx")||Pt.endsWith(".doc")||Pt.endsWith(".ppt")||Pt.endsWith(".pptx")||Pt.endsWith(".xls")||Pt.endsWith(".xlsx"),et=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(Pt);on||Ne?M=`${d.length>0?"\u2714":"\u2718"} ${d?`Analyzed: ${W.basename(d)}`:"Analyzed: File Not Found"}`:et?M=`${d.length>0?"\u2714":"\u2718"} ${d?`Processed: ${W.basename(d)}`:"Processed: File Not Found"}`:M=`${$e!=="..."?"\u2714":"\u2718"} Read: ${d?`${W.basename(d)} \u2192 ${$e!=="..."?`Lines ${N} - ${Re} of ${$e}`:"File Not Found"}`:"File Not Found"}`}}else if(l==="list_files"||l==="read_folder"){let d=l==="list_files"?"List":"Browsed",I=j(w.args).path||null,V=j(w.args).recurse||1;M=`${I?"\u2714":"\u2718"} ${d}: ${I?`${I==="."?`./${V>1?"*":""}`:`${I.replaceAll("\\","/")}${V>1?`${I.endsWith("/")?"*":"/*"}`:`${I.endsWith("/")?"":"/"}`}`}`:"No Folder Selected"}`}else if(l==="find_file"){let d=j(w.args),I=d.basename||d.name||d.path||d.file||d.query||"";M=`${I?"\u2714":"\u2718"} Located: ${I||"No Query"}`}else if(l==="write_file"||l==="update_file"){let d=l==="write_file"?"Created":"Edited",I=j(w.args),V=I.path||null,se=Object.entries(I).some(([te,we])=>te.startsWith("searchContent")&&typeof we=="string"&&we.startsWith("^LINE:"))?"\u1361":":";M=`${V?"\u2714":"\u2718"} ${d}${se} ${V?V.replaceAll("\\","/"):"No File Changes"}`}else if(l==="write_pdf"){let d=j(w.args).path||null;M=`${d?"\u2714":"\u2718"} Generated: ${d.replaceAll("\\","/")||"No PDF Generated"}`}else if(l==="write_docx"){let d=j(w.args).path||null;M=`${d?"\u2714":"\u2718"} Generated: ${d.replaceAll("\\","/")||"No Docx Generated"}`}else if(l==="file_map"){let d=j(w.args).path;M=`${d?"\u2714":"\u2718"} Indexed: ${d.replaceAll("\\","/")?""+d:"File Not Found"}`}else if(l.toLowerCase()==="search_keyword"||l.toLowerCase()==="todo")M="";else if(l.toLowerCase()==="generate_image"){let{path:d,outputPath:I,output:V}=j(w.args);M=`\u2714 Generated: ${d||I||V||"generated_image.png"}`}else if(l==="invoke_sync"||l==="InvokeSync"){let d=Zn(l,w.args);M=`\u2714 Called Generalist${d?`: ${d}`:""}`}else if(l==="Invoke"||l==="InvokeAsync"||l==="invoke"){let d=Zn(l,w.args);M=`\u2714 Started Generalist${d?`: ${d}`:""}`}else if(l==="get_progress"||l==="GetProgress"){let d=Zn(l,w.args);M=`\u2714 Checked${d?`: ${d}`:""}`}else if(l==="cancel"){let d=Zn(l,w.args);M=`\u{1F6C7} Cancelled${d?`: ${d}`:""}`}else if(l==="steer"||l==="Steer"){let d=Zn(l,w.args);M=`\u2714 Steered${d?`: ${d}`:""}`}else if(l==="EmergencyRollback"){let{method:d}=j(w.args);M=d==="forceRevert"?"":"\u2714 Rollback Point Checked"}else if(l==="await"||l==="Await"||l==="wait"||l==="Wait"){let{time:d,timeout:I,seconds:V,sec:ye}=j(w.args),se=parseFloat(V||ye||I||d)||45,te=l==="wait"||l==="Wait"?120:180;se<10&&(se=10),se>te&&(se=te);let we=N=>{if(N>=60){let z=Math.floor(N/60),$e=N%60;return`${z}m${$e>0?` ${$e}s`:""}`}return`${N}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"];M=`\u2714 ${ke[Math.floor(Math.random()*ke.length)]} \u2192 ${we(se)}`}else l==="Answer"||l==="answer"?M="\u2714 Resolved Sub-Agent Query":l==="exec_command"||l==="ask"?M="":M=`Executed: ${w.toolName}`;if(yield*Yn(),l==="exec_command"){let{command:d}=j(w.args);if(d&&t.systemSettings&&t.systemSettings.allowExternalAccess===!1){let I=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],V=W.resolve(process.cwd()).substring(0,3).toLowerCase(),ye=ee=>{let N=[],z="",$e=null;for(let Re=0;Re<ee.length;Re++){let re=ee[Re];$e?(re===$e&&($e=null),z+=re):re==='"'||re==="'"?($e=re,z+=re):re==="&"&&ee[Re+1]==="&"||re==="|"&&ee[Re+1]==="|"?(z.trim()&&(N.push(z.trim()),z=""),Re++):re===";"||re==="|"||re==="&"?z.trim()&&(N.push(z.trim()),z=""):z+=re}return z.trim()&&N.push(z.trim()),N},se=ee=>{let N=[],z="",$e=null;for(let Re=0;Re<ee.length;Re++){let re=ee[Re];$e?(re===$e&&($e=null),z+=re):re==='"'||re==="'"?($e=re,z+=re):/\s/.test(re)?z&&(N.push(z),z=""):z+=re}return z&&N.push(z),N},te=ee=>{let N=ee.replace(/^['"]|['"]$/g,"").trim();return!N||process.platform==="win32"&&/^\/[a-zA-Z0-9?]+$/.test(N)?!1:I.some(z=>{if(z.source==="[a-zA-Z]:[\\\\\\/]"){let $e=N.match(/[a-zA-Z]:[\\\/]/i);return $e&&$e[0].toLowerCase()!==V}return z.test(N)})};if(ye(d).some(ee=>{let N=se(ee);if(N.length===0)return!1;let z=N[0].replace(/^['"]|['"]$/g,"").toLowerCase();if(["echo","printf","write-output"].includes(z)){let Re=!1;return N.some(re=>{let Ft=re.replace(/^['"]|['"]$/g,"");if(Ft===">"||Ft===">>"||Ft==="<")return Re=!0,!1;if(Ft.startsWith(">")||Ft.startsWith("<")){let Pt=Ft.replace(/^[><]+/,"");return te(Pt)}return Re?(Re=!1,te(re)):!1})}return N.some(Re=>te(Re))})){let ee='Access Denied. Prohibited from accessing external directories while "External Workspace Access" is disabled.';t.onExecStart&&t.onExecStart(d||"No Command"),yield{type:"exec_start"},await new Promise(N=>setTimeout(N,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${ee}`),await new Promise(N=>setTimeout(N,50)),t.onExecEnd&&t.onExecEnd(),He.push({role:"user",text:`[ACTION RESULT]: ERROR: ${ee}`}),yield{type:"tool_result",content:`[ACTION RESULT]: ERROR: ${ee}`},Rt++;continue}}t.onExecStart&&t.onExecStart(d||"No Command"),yield{type:"exec_start"}}let kt=j(w.args),Rn=kt.path||kt.targetPath||null;if(Rn){let d=t.systemSettings&&t.systemSettings.allowExternalAccess===!1,I=W.resolve(Rn),V=W.resolve(process.cwd());if(d&&!I.startsWith(V)){let ye="Access Denied. You are not allowed to access files outside the current workspace.";if(l==="write_file"||l==="update_file"){let te=`\u2718 ${l==="write_file"?"Write Canceled":"Edit Canceled"}: ${kt.path||"..."}`,we=115;process.stdout.isTTY&&(we=process.stdout.columns-5||120);let ke=Math.min(te.length+4,we),ee=`${te.padEnd(ke-2).substring(0,ke-2)}`;yield{type:"visual_feedback",content:jt(`${je?`
760
- `:""}${ee}
761
- `)},je=!1}He.push({role:"user",text:`[ACTION RESULT]: ERROR: ${ye}`}),yield{type:"tool_result",content:`[ACTION RESULT]: ERROR: ${ye}`},Rt++;continue}}if(t.onToolApproval){let d=t.systemSettings||{},I=d.autoExec,V=!1,ye="";if(l==="view_file"){let te=j(w.args);if(ye=te.path||te.targetPath||te.file||"",ye){let we=d.alwaysAskFiles||".env, .env.*, *.env";Is(ye,we)&&(V=!0)}}if(l==="write_file"||l==="update_file"||l==="exec_command"||V){let te=null,we=!1,ke=!1,ee=!1;if(V)we=!0,te=null;else if(l==="exec_command"){let{command:Ne}=j(w.args),et=(Ne||"").trim(),xe=(sn,Jt)=>{if(!Jt)return!1;let mn=Jt.split(",").map(Qt=>Qt.trim().toLowerCase()).filter(Boolean),st=sn.toLowerCase();return mn.some(Qt=>st.startsWith(Qt))},Ve=xe(et,d.alwaysAskCommands),U=xe(et,d.autoApproveCommands);if(ke=xe(et,d.autoDisallowCommands),Ve?we=!0:(U||d.autoApproveGit&&/^git\s+commit\b/i.test(et))&&(te="allow"),!we&&!te){if(d.networkAccess===!1){let Jt=et.trim().replace(/\s+/g," ").replace(/^['"]+|['"]+$/g,"").toLowerCase().split(" "),st=Jt[0].split("/").pop().split("\\").pop().replace(/\.exe$/,""),Qt=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"]),rt=!1;Qt.has(st)&&(rt=!0);let tt=Nn=>Jt.slice(1).some(vn=>Nn.includes(vn)),mt=Nn=>{let vn=Jt.findIndex(In=>Nn.includes(In)),qn=Jt.findIndex(In=>["run","exec","test"].includes(In));return vn!==-1&&!(qn!==-1&&qn<vn)};st==="git"&&tt(["clone","pull","push","fetch"])&&(rt=!0),st==="go"&&tt(["get","install"])&&(rt=!0),st==="npm"&&mt(["install","i","update","add"])&&(rt=!0),st==="yarn"&&mt(["add","install","upgrade"])&&(rt=!0),st==="pnpm"&&mt(["add","install","update"])&&(rt=!0),st==="bun"&&mt(["add","install","update"])&&(rt=!0),st==="deno"&&tt(["install","add"])&&(rt=!0),st==="pip"&&tt(["install","download"])&&(rt=!0),st==="pip3"&&tt(["install","download"])&&(rt=!0),st==="cargo"&&tt(["install","add"])&&(rt=!0),["bash","sh","zsh","fish"].includes(st)&&tt(["-c"])&&(rt=!0),st==="cmd"&&tt(["/c"])&&(rt=!0),rt&&(te="deny",ee=!0)}!te&&ke&&(te="deny")}!we&&!te&&I&&(te="allow")}else(l==="write_file"||l==="update_file")&&I&&(te="allow");let N=te,z="";te==="deny"&&(ee?z="network":ke?z="settings":z="prohibited");let $e=!1,Re="",re=[],Ft=0,Pt=!1,on="";if(!N&&t.onToolApproval)try{let Ne=await t.onToolApproval(l,w.args,{checkOnly:!0});(Ne==="allow"||Ne==="deny")&&(N=Ne,N==="deny"&&(z="user"))}catch{}if(!N){if(l==="write_file"||l==="update_file")try{let xe=j(w.args),{path:Ve}=xe;if(Ve){let U=W.resolve(process.cwd(),Ve),sn=tt=>tt?tt.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,mt=>mt.toUpperCase()):"",Jt=sn(U),mn="",st=!1,Qt=await Jn(),rt=sn(Qt?.file_focused);if(Qt&&rt===Jt&&Qt.full_content?(mn=Qt.full_content,st=!0):Ae.existsSync(U)&&(mn=Ae.readFileSync(U,"utf8"),st=!0),Re=mn,await ti.recordFileChange(U,mn),st){let tt=mn;if(l==="write_file"){let mt=xe.content||xe.newContent||"";tt=mt.endsWith(`
762
- `)?mt:mt+`
763
- `,on=tt}else{let{patchPairs:mt,allowMultiple:Nn,error:vn}=Di(xe);if(vn){let rn=`[ACTION RESULT]: ERROR: ${vn}`;He.push({role:"user",text:rn}),await Lt("toolFailure"),t.onToolResult&&t.onToolResult("failure",l),yield{type:"tool_result",content:rn,toolName:l},Rt++;continue}let qn=xe.allowMultiple!==void 0?xe.allowMultiple===!0||String(xe.allowMultiple).toLowerCase()==="true":Nn;Ft=mt.length;let In=Ps(mn,mt,{allowMultiple:qn});tt=In.content,on=tt,re=In.results;let zo=re.filter(rn=>rn.success),Ri=re.filter(rn=>!rn.success);if(zo.length===0){let rn=`[ACTION RESULT]: ERROR: Failed to apply patches to [${W.basename(U)}].
764
- ${Ri.map(nt=>` \u2022 ${nt.error}`).join(`
765
- `)}`,_i=`\u2714 Edited: ${W.basename(U.replaceAll("\\","/"))}`,pn=115;process.stdout.isTTY&&(pn=process.stdout.columns-5||120);let Dn=Math.min(_i.length+4,pn),at=`${_i.padEnd(Dn-2).substring(0,Dn-2)}`;yield{type:"visual_feedback",content:jt(`${je?`
766
- `:""}${at}`)},je=!1,He.push({role:"user",text:rn}),await Lt("toolFailure"),t.onToolResult&&t.onToolResult("failure",l),yield{type:"tool_result",content:rn,toolName:l},Rt++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${W.basename(U)}`},Vi(U,mn,tt),$e=!0,await new Promise(mt=>setTimeout(mt,50))}else if(l==="write_file"){let tt=xe.content||xe.newContent||"",mt=tt.endsWith(`
767
- `)?tt:tt+`
768
- `;on=mt,Ae.existsSync(U)||(Pt=!0,Ae.mkdirSync(W.dirname(U),{recursive:!0}),Ae.writeFileSync(U,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${W.basename(U)}`},Vi(U,"",mt),$e=!0,await new Promise(Nn=>setTimeout(Nn,50))}}}catch(xe){console.error("Simulation/Diff Error:",xe)}let Ne=null;Ki(xe=>{Ne=xe});let et=t.onToolApproval;if(N=await new Promise(async xe=>{let Ve=setInterval(()=>{if(Ne){let U=t.onIDEApproval||Ho&&Ho.onIDEApproval;U&&U(Ne),clearInterval(Ve),xe(Ne)}},100);try{let U=await et(l,w.args);clearInterval(Ve),xe(U)}catch{clearInterval(Ve),xe("deny")}}),Ki(null),l==="write_file"||l==="update_file"){let{path:xe}=j(w.args);if(xe){let Ve=W.resolve(process.cwd(),xe);if(sr(Ve,N),N==="deny"&&Pt&&Ae.existsSync(Ve))try{Ae.unlinkSync(Ve)}catch{}}}N==="deny"&&(z="user")}if(N==="allow"&&$e&&go()){let{path:Ne}=j(w.args),et=W.resolve(process.cwd(),Ne),xe=at=>at?W.resolve(at).replace(/\\/g,"/").toLowerCase():"",Ve=await Jn(),U="";if(Ve&&Ve.file_focused&&xe(Ve.file_focused)===xe(et)&&Ve.full_content&&(U=Ve.full_content),!U&&Ae.existsSync(et)){let at=Ae.readFileSync(et,"utf8");at&&(U=at)}!U&&on&&(U=on),(U||Pt)&&Ae.writeFileSync(et,U,"utf8");let sn=U.split(/\r?\n/),Jt=sn.length,mn=Buffer.byteLength(U,"utf8"),st="";Re&&(st=`Old File contents:
769
- ${Re.split(/\r?\n/).map((nt,hn)=>`${hn+1} | ${nt}`).join(`
748
+ ${Fe}`)}let Pt=new Promise((m,A)=>{B.signal.aborted&&A(new DOMException("The user aborted a request.","AbortError")),B.signal.addEventListener("abort",()=>{A(new DOMException("The user aborted a request.","AbortError"))})});Pt.catch(()=>{});let Be=M;if(Vt=Date.now(),s==="Ollama")de=(await le("Ollama"))(t.apiKey,te,Be,Fe,d,a,y,B.signal,1,p?.ollamaEndpoint||"Cloud");else if(s==="OpenRouter")de=(await le("OpenRouter"))(t.apiKey,te,Be,Fe,d,a,y,B.signal,1,h);else if(s==="DeepSeek")de=(await le("DeepSeek"))(t.apiKey,te,Be,Fe,d,a,y,B.signal,1);else if(s==="Mistral")de=(await le("Mistral"))(t.apiKey,te,Be,Fe,d,a,y,B.signal,1,h);else if(s==="NVIDIA"){let m=(await le("NVIDIA"))(t.apiKey,te,Be,Fe,d,a,y,B.signal,1);de=(await le("NVIDIA_wrap"))(m,te)}else if(s==="InferX")de=(await le("InferX"))(t.apiKey,te,Be,Fe,d,a,y,B.signal,1);else if(s==="SenseNova")de=(await le("SenseNova"))(t.apiKey,te,Be,Fe,d,a,y,B.signal,1);else if(s==="AIHubMix")de=(await le("AIHubMix"))(t.apiKey,te,Be,Fe,d,a,y,B.signal,1);else if(s==="Poolside")de=(await le("Poolside"))(t.apiKey,te,Be,Fe,d,a,y,B.signal,1);else if(s==="9router"||s==="9Router")de=(await le("NineRouter"))(t.apiKey,te,Be,Fe,d,a,y,B.signal,1);else if(s==="ExpLabs"||s==="ExperientialLabs")de=(await le("ExpLabs"))(t.apiKey,te,Be,Fe,d,a,y,B.signal,1);else if(s==="Infron"||s==="infron")de=(await le("Infron"))(t.apiKey,te,Be,Fe,d,a,y,B.signal,1);else if(s==="TokenHarbor"||s==="Token Harbor"||s==="tokenharbor"||s==="token_harbor"||s==="thk")de=(await le("TokenHarbor"))(t.apiKey,te,Be,Fe,d,a,y,B.signal,1);else if(s==="APInex"||s==="apinex"||s==="apx")de=(await le("APInex"))(t.apiKey,te,Be,Fe,d,a,y,B.signal,1);else if(s==="xKiro"||s==="xkiro"||s==="kiro")de=(await le("xKiro"))(t.apiKey,te,Be,Fe,d,a,y,B.signal,1);else if(s==="c_openai"||s==="Custom (OpenAI)"){let m=p?.customOpenAIBaseUrl||"";try{m=await Li("c_openai")||m}catch{}de=(await le("c_openai"))(t.apiKey,te,Be,Fe,d,a,y,B.signal,1,m)}else{let m=ys(t?.apiKey),{serviceTier:A,cleanModel:C}=aa(te),q={systemInstruction:Fe,mediaResolution:"MEDIA_RESOLUTION_HIGH",safetySettings:[{category:Un.HARM_CATEGORY_HARASSMENT,threshold:Bn.BLOCK_NONE},{category:Un.HARM_CATEGORY_HATE_SPEECH,threshold:Bn.BLOCK_NONE},{category:Un.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Bn.BLOCK_NONE},{category:Un.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Bn.BLOCK_NONE}],temperature:1.05,thinkingConfig:(()=>{let D=Ds("Google",te||"gemini-3-flash-preview",d);if(D!==null){if(typeof D=="object")return D;if(D===!1||D==="false"||D==="none"||D===0||D==="0")return{includeThoughts:!1};if(typeof D=="number")return{includeThoughts:!0,thinkingBudget:D};if(typeof D=="string"){let R=D.toLowerCase();if(R==="minimal")return{includeThoughts:!0,thinkingLevel:je.MINIMAL};if(R==="low")return{includeThoughts:!0,thinkingLevel:je.LOW};if(R==="medium")return{includeThoughts:!0,thinkingLevel:je.MEDIUM};if(R==="high")return{includeThoughts:!0,thinkingLevel:je.HIGH};let ne=Number(D);if(!isNaN(ne))return{includeThoughts:!0,thinkingBudget:ne}}}let X=(te||"").toLowerCase(),ht=X.includes("gemma-4")||X.startsWith("gemma"),w=X.includes("gemini-3");if(ht||w)return ht?d.toLowerCase()!=="high"?{includeThoughts:!1,thinkingLevel:je.MINIMAL}:{includeThoughts:!0,thinkingLevel:je.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:X.includes("pro")?je.LOW:je.MINIMAL,Low:je.LOW,Medium:je.MEDIUM,Standard:je.MEDIUM,High:je.HIGH,xHigh:je.HIGH}[d]||je.MEDIUM};{let R={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[d]||2048;return R===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:R}}})()};A&&(q.serviceTier=A);let ae=m.models.generateContentStream({model:C||"gemini-3-flash-preview",contents:Be,config:q},{signal:B.signal});de=await Promise.race([ae,Pt])}Ee="",Yt=null,Hn=null,Ue=[],Mt=0,yield{type:"model_update",content:null},ve="",lt=kt.length>0;let Dt="",oo=Date.now(),Yn=async function*(){if(s==="Google"&&Dt){let m=xo(Dt);for(let A of m)yield A;Dt="",oo=Date.now()}},Rs=!0,Tn="",io=!1,pt=null,vs=!1,zn=!1,so=!1,Yo=!1,Pn=!1,yo=m=>{let A=0;for(;A+2<m.length;)m[A]==="`"&&m[A+1]==="`"&&m[A+2]==="`"?(Yo=!Yo,A+=3):A++},_s=m=>{if(!m)return;let A=/(?:<(\/?)think_fluxflow[^>]*>|\[(\/?)think_fluxflow\]|<\/?channel\|?>|<\|channel>thought)/gi,C;for(;(C=A.exec(m))!==null;){let q=C[0].toLowerCase();q.startsWith("</")||q.startsWith("[/")||q==="<channel|>"?Pn=!1:Pn=!0}},ya={tool:{startPrefix:"[tool",fullPrefix:"[tool:",endTag:"]"},action:{startPrefix:"[action",fullPrefix:"[action:",endTag:"]"},end:{startPrefix:"[[END]]",fullPrefix:"[[END]]",endTag:"[[END]]"},kimi_section:{startPrefix:"<|tool_calls_section_begin|>",fullPrefix:"<|tool_calls_section_begin|>",endTag:"<|tool_calls_section_end|>"},kimi_call:{startPrefix:"<|tool_call_begin|>",fullPrefix:"<|tool_call_begin|>",endTag:"<|tool_call_end|>"}},xo=m=>{let A=[],C=m,q=ae=>{if(!ae)return;if(!vs){A.push({type:"text",content:ae}),yo(ae),_s(ae);return}let D=/(?:<(\/?)think_fluxflow[^>]*>|\[(\/?)think_fluxflow\]|<\/?channel\|?>|<\|channel>thought)/gi,X=0,ht;for(;(ht=D.exec(ae))!==null;){let R=ae.substring(X,ht.index);if(R)if(yo(R),Pn)A.push({type:"text",content:R});else{let Oe=R.replace(/[^\r\n]/g,"");Oe&&A.push({type:"text",content:Oe})}let ne=ht[0];yo(ne);let l=ne.toLowerCase();l.startsWith("</")||l.startsWith("[/")||l==="<channel|>"?Pn=!1:Pn=!0,A.push({type:"text",content:ne}),X=D.lastIndex}let w=ae.substring(X);if(w)if(yo(w),Pn)A.push({type:"text",content:w});else{let R=w.replace(/[^\r\n]/g,"");R&&A.push({type:"text",content:R})}};for(;C.length>0;)if(io){let ae=Tn+C,D=ya[pt];if(D){let w=!1;if(ae.length<D.startPrefix.length?D.startPrefix.startsWith(ae)||(w=!0):ae.startsWith(D.startPrefix)?ae.length>=D.fullPrefix.length&&!ae.startsWith(D.fullPrefix)&&(w=!0):w=!0,w){q(ae),Tn="",io=!1,pt=null,zn=!1,so=!1,C="";break}}let X=-1,ht=D?D.endTag:"]";if(pt==="tool"||pt==="action"){let w=0,R=null,ne=0,l=!1;for(let Oe=0;Oe<ae.length;Oe++){let J=ae[Oe];if(R){if(J===R){let P=0;for(let yt=Oe-1;yt>=0&&ae[yt]==="\\";yt--)P++;P%2===0&&(R=null)}}else if(J==='"'||J==="'")R=J;else if(J==="`")if(zn){X=Oe;break}else R=J;else if(J==="(")w++,l=!0;else if(J===")")w--;else if(J==="]"&&l&&w===0){X=Oe;break}}}else X=ae.indexOf(ht);if(X!==-1){let w=ht.length,R=ae.substring(0,X+w);pt?.startsWith("kimi")||A.push({type:"text",content:R}),yo(R),_s(R),(pt==="tool"||pt==="action"||pt?.startsWith("kimi"))&&!zn&&!so&&(vs=!0,Gn.push(R.trim())),zn=!1,so=!1,Tn="",io=!1,pt=null,C=ae.substring(X+w)}else{Tn=ae,C="";break}}else{let ae=C.indexOf("[tool"),D=C.indexOf("[action"),X=C.indexOf("[[END]]"),ht=C.indexOf("<|tool_calls_section_begin|>"),w=C.indexOf("<|tool_call_begin|>"),R=[{type:"tool",idx:ae,start:"[tool",end:"]"},{type:"action",idx:D,start:"[action",end:"]"},{type:"end",idx:X,start:"[[END]]",end:"[[END]]"},{type:"kimi_section",idx:ht,start:"<|tool_calls_section_begin|>",end:"<|tool_calls_section_end|>"},{type:"kimi_call",idx:w,start:"<|tool_call_begin|>",end:"<|tool_call_end|>"}].filter(ne=>ne.idx!==-1).sort((ne,l)=>ne.idx-l.idx);if(R.length>0){let ne=R[0],l=C.substring(0,ne.idx);ne.idx>0&&q(l);let Oe=ne.idx>0?C[ne.idx-1]:"";zn=Yo||Oe==="`",so=Pn,io=!0,pt=ne.type,Tn="",C=C.substring(ne.idx)}else{let ne=["[tool","[action","[[END]]","<|tool_calls_section_begin|>","<|tool_call_begin|>"],l=-1;for(let Oe of ne){for(let J=Oe.length-1;J>0;J--)if(C.endsWith(Oe.substring(0,J))){l=C.length-J;let P=ne.indexOf(Oe);P===0?pt="tool":P===1?pt="action":P===2?pt="end":P===3?pt="kimi_section":pt="kimi_call";break}if(l!==-1)break}if(l!==-1){if(l>0){let J=C.substring(0,l);q(J)}let Oe=l>0?C[l-1]:"";zn=Yo||Oe==="`",so=Pn,io=!0,Tn=C.substring(l),C=""}else{q(C);break}}}return A},xa=de[Symbol.asyncIterator]();for(;;){let{value:m,done:A}=await Promise.race([xa.next(),Pt]);if(A)break;if(m&&m.type==="status"){yield m;continue}let C="",q=m.candidates?.[0]?.content?.parts;if(q&&q.length>0)for(let D of q){let X=typeof D.text=="string"?D.text:D.text?parseChunkText(D.text):"";D.thought?X&&(z||(C+="<think_fluxflow>",z=!0),C+=X):X&&(z&&(C+="</think_fluxflow>",z=!1),C+=X)}else m.text&&z&&(C+="</think_fluxflow>",z=!1);C=dl(C);let ae=C?Di(C):0;if(t&&typeof t.onTokenChunk=="function"&&t.onTokenChunk(C,ae),Rs&&(At===null&&(At=Date.now()-Vt),yield{type:"status",content:process.env.HALLOWEEN_EEGG==="true"?"Performing dark ritual":"Thinking"},Rs=!1),wt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
749
+
750
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(C){if(lt){if(ve+=C,ve.length>=64){let w=0,R=Math.min(kt.length,ve.length);for(let l=R;l>=10;l--)if(kt.endsWith(ve.substring(0,l))){w=l;break}let ne=ve.substring(w);if(ne){let Oe=/(?:<think_fluxflow>|\[think_fluxflow\])(?:(?!(?:<\/think_fluxflow>|\[\/think_fluxflow\]))[\s\S])*$/i.test(kt)?ne.replace(/^\s*(?:<think_fluxflow>|\[think_fluxflow\])\s*/gi,""):ne.replace(/^\s*(?:<think_fluxflow>|\[think_fluxflow\])[\s\S]*?(?:<\/think_fluxflow>|\[\/think_fluxflow\])\s*/gi,"").replace(/^\s*(?:<think_fluxflow>|\[think_fluxflow\])\s*/gi,"");if(Oe)if(Ee+=Oe,s==="Google")Dt+=Oe;else{yield*Yn();let J=xo(Oe);for(let P of J)yield P}}lt=!1,ve=""}continue}else if(Ee+=C,s==="Google")Dt+=C;else{yield*Yn();let w=xo(C);for(let R of w)yield R}let D=xl(Ee);if(D.inside){en=!0,Hn||(Hn=Date.now());let R={Ask:"ask",AskUser:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",FindFile:"find_file",find_file:"find_file",findfile:"find_file",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Cancel:"cancel",Await:"await",wait:"wait",Answer:"answer",Steer:"steer",steer:"steer"}[D.toolName]||D.toolName,ne=D.args||"",l=null;if(["write_file","update_file","view_file","read_folder","find_file","write_pdf","write_docx","search_keyword","generate_image","file_map","invoke","invoke_sync","get_progress","await","wait","answer"].includes(R)){let J=G(ne),P=J.basename||J.name||J.path||J.targetFile||J.TargetFile||J.directory||J.file,yt=J.keyword,An=J.title||J.task,Ft=J.id||J.taskId,oe=J.timeout||J.time||J.seconds||J.sec;if(yt!=null)l=String(yt).replace(vn,"");else if(P)l=V.basename(String(P).replace(vn,"").replace(Qr,"/"));else if(An&&(R==="invoke"||R==="invoke_sync"))l=String(An).replace(vn,"").substring(0,30);else if(Ft&&R==="get_progress")l=String(Ft).replace(vn,"");else if(oe&&R==="await"){let Ve=parseFloat(String(oe).replace(vn,""));isNaN(Ve)?l=String(oe).replace(vn,""):(Ve<5&&(Ve=5),Ve>120&&(Ve=180),l=(Bt=>{if(Bt>=60){let wo=Math.floor(Bt/60),En=Bt%60;return`${wo}m${En>0?` ${En}s`:""}`}return`${Bt}s`})(Ve))}else if(oe&&R==="wait"){let Ve=parseFloat(String(oe).replace(vn,""));isNaN(Ve)?l=String(oe).replace(vn,""):(Ve<10&&(Ve=10),Ve>120&&(Ve=120),l=(Bt=>{if(Bt>=60){let wo=Math.floor(Bt/60),En=Bt%60;return`${wo}m${En>0?` ${En}s`:""}`}return`${Bt}s`})(Ve))}else{let Ve=ne.match(al);if(Ve){let xt=Ve[1].replace(vn,"");R==="invoke"||R==="invoke_sync"||R==="get_progress"?l=xt.substring(0,30):l=R==="search_keyword"||R==="file_map"?xt:V.basename(xt.replace(Qr,"/"))}}}let Oe=`${ps[R]||R}${l?` ${l}`:""}`;if((R!==Yt||l!==ho)&&(Yt=R,ho=l,yield{type:"status",content:`${Oe}`},process.stdout.isTTY)){let P={WebSearch:"Searching",web_search:"Searching",WebScrape:"Reading",web_scrape:"Reading",ReadFile:"Reading",read_file:"Reading",ReadFolder:"Reading",read_folder:"Reading",WriteFile:"Writing",write_file:"Writing",UpdateFile:"Editing",update_file:"Editing",WritePdf:"Creating",write_pdf:"Creating",WriteDocx:"Creating",write_docx:"Creating",SearchKeyword:"Searching",search_keyword:"Searching",CodeSearch:"Searching",code_search:"Searching",FindFile:"Finding File",find_file:"Finding File",Run:"Executing",Ask:"User Input Required",AskUser:"User Input Required",Memory:"Updating Memory",GenerateImage:"Generating",InvokeSync:"Sub-Agent Working",invoke_sync:"Sub-Agent Working",Invoke:"Working",invoke:"Working",GetProgress:"Checking Progress",get_progress:"Checking Progress",Cancel:"Stopping Generalist",cancel:"Stopping Generalist",Await:"Waiting",await:"Waiting",wait:"Waiting",EmergencyRollback:"Rolling the Ball",Answer:"Answering Sub-Agent",answer:"Answering Sub-Agent",Steer:"Steering Sub-Agent",steer:"Steering Sub-Agent",Click:"Clicking",click:"Clicking",Drag:"Dragging",drag:"Dragging",Scroll:"Scrolling",scroll:"Scrolling",KeyboardTyping:"Typing",keyboard_typing:"Typing",KeyPress:"Pressing Key",key_press:"Pressing Key",RecaptureScreen:"Recapturing Screen",recapture_screen:"Recapturing Screen"}[R]||"Working";process.stdout.write(`\x1B]0;${P}...\x07`)}}if(Ee.length-no>800){no=Ee.length;let w=ra(Ee,!1),R=ms(w),ne=R?(R.innerContent||"").trim():"",l=ne.split(/[.!?]\s+/).filter(ye=>ye.trim().length>10),Oe=new Set(l),J=l.length>25?(l.length-Oe.size)/l.length:0,P=ne.split(/\s+/).filter(ye=>ye.length>0).length,yt=.9,An=.92,Ft=!1;if(s.toLowerCase().includes("google")&&(te||"").toLowerCase().startsWith("gemma")){let c={low:2048,medium:4096,high:32768,max:65536,xhigh:65536}[d?.toLowerCase()]||16e3;Ft=P>c}if(J>yt||Ft){yield{type:"status",content:`${J>yt?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},Nt=!0,await new Promise(c=>setTimeout(c,3e3));break}let xt=na(Ee).trim().split(/[.!?]\s+/).filter(ye=>ye.trim().length>10),Bt=new Set(xt);if((xt.length>25?(xt.length-Bt.size)/xt.length:0)>An){yield{type:"status",content:"Response Loop Detected. Re-centering..."},Nt=!1,zt=!0,await new Promise(ye=>setTimeout(ye,3e3));break}let En=w.replace(el,"").replace(tl,"").replace(nl,"").replace(ol,""),Ct=En.toLowerCase().split(/\s+/).map(ye=>ye.replace(il,"")).filter(ye=>ye.length>0),fn=!1;if(Ct.length>=40)for(let ye=1;ye<=15;ye++){let c=Math.max(8,Math.ceil(25/ye));if(Ct.length<ye*c)continue;let _=Ct.slice(Ct.length-ye),W=_.join(" ");if(ye>1&&W===_.slice(0,Math.floor(ye/2)).join(" ").repeat(2).trim())continue;let pe=!0;for(let ie=1;ie<c;ie++)if(Ct.slice(Ct.length-ye*(ie+1),Ct.length-ye*ie).join(" ")!==W){pe=!1;break}if(pe){fn=!0;break}}if(!fn){let ye=En.toLowerCase().replace(sl,"");if(ye.length>=80)for(let c=1;c<=10;c++){let _=Math.max(15,Math.ceil(45/c));if(ye.length<c*_)continue;let W=ye.substring(ye.length-c),pe=!0;for(let ie=1;ie<_;ie++)if(ye.substring(ye.length-c*(ie+1),ye.length-c*ie)!==W){pe=!1;break}if(pe){fn=!0;break}}}if(fn){yield{type:"status",content:"Stuttering Detected. Re-centering..."},Nt=!1,Kn=!0,await new Promise(ye=>setTimeout(ye,3e3));break}}let X=Lt(Ee),ht=Wn(X);for(;ht.length>Mt;){yield*Yn();let w=ht[Mt],R=Date.now(),l={Ask:"ask",AskUser:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",FindFile:"find_file",find_file:"find_file",findfile:"find_file",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Await:"await",await:"await",AwaitSubagent:"await",awaitSubagent:"await",Wait:"wait",wait:"wait",Answer:"answer",answer:"answer",AnswerSubagent:"answer",answerSubagent:"answer",Steer:"steer",steer:"steer",SteerSubagent:"steer",steerSubagent:"steer",Cancel:"cancel",cancel:"cancel",Click:"click",click:"click",Drag:"drag",drag:"drag",Scroll:"scroll",scroll:"scroll",KeyboardTyping:"keyboard_typing",keyboard_typing:"keyboard_typing",KeyPress:"key_press",key_press:"key_press",RecaptureScreen:"recapture_screen",recapture_screen:"recapture_screen",EmergencyRollback:"EmergencyRollback"}[w.toolName]||w.toolName,Oe=ps[l]||w.toolName,J=Zn(l,w.args);yield{type:"status",content:`${Oe}${J?` ${J}`:""}`};let P="";if(l==="click"){let c=G(w.args);P=`\u2714 Clicked ${c.intendedClickText?`: ${c.intendedClickText}`:"Screen"}`}else if(l==="drag"){let c=G(w.args);P=`\u2714 Dragged: Cell ${c.fromGridId||""} \u2192 Cell ${c.toGridId||""}`}else if(l==="scroll"){let c=G(w.args);P=`\u2714 Scrolled: ${c.direction||"down"} (${c.amount||1})`}else if(l==="keyboard_typing"){let c=G(w.args);P=`\u2714 ${c.autoPressEnter?"Entered":"Typed"}: ${c.text?`"${c.text.length>20?c.text.substring(0,20)+"...":c.text}"`:""}`}else if(l==="key_press")P=`\u2714 Pressed Key: ${G(w.args).key||""}`;else if(l==="recapture_screen")P="\u2714 Recaptured Screen";else if(l==="web_search"){let{query:c,limit:_=10,aiMode:W=!1}=G(w.args);P=`${c?"\u2714":"\u2718"} ${W?"AI Search":"Searched"}: ${c?`${c}`:"No Search Query"}${W===!1&&c?` \u2192 ${_}`:""}`}else if(l==="web_scrape"){let c=G(w.args).url||null;P=`${c?"\u2714":"\u2718"} Visited: ${c||"No Source"}`}else if(l==="view_file"){let{path:c,StartLine:_,EndLine:W,start_line:pe,end_line:ie,startLine:ee,endLine:xe}=G(w.args),we=_||pe||ee,Q=W||ie||xe,$=parseInt(we)||1,K=parseInt(Q)||(we?$+800:800),Le="...",Ce=K,se=(c||"").trim().toLowerCase().replaceAll("\\","/");if(se.startsWith("#skill"))se.startsWith("#skill/global/fluxflow")||se.startsWith("#skills/global/fluxflow")||se.includes("#skill/fluxflow")||se.includes("#skills/fluxflow")?P="\u2714 Read Documentation":P=`\u2714 Read Skill: ${V.basename(c.replaceAll("\\","/"))}`;else{try{let he=V.resolve(process.cwd(),c);if(ke.existsSync(he)){let F=ke.readFileSync(he,"utf8").split(`
751
+ `).length;Le=F,!we&&!Q&&F>800?Ce=Math.min(50,F):Ce=Math.min(K,F)}}catch{}let Rt=(c||"").toLowerCase(),tn=Rt.endsWith(".pdf"),$e=Rt.endsWith(".docx")||Rt.endsWith(".doc")||Rt.endsWith(".ppt")||Rt.endsWith(".pptx")||Rt.endsWith(".xls")||Rt.endsWith(".xlsx"),Xe=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(Rt);tn||$e?P=`${c.length>0?"\u2714":"\u2718"} ${c?`Analyzed: ${V.basename(c)}`:"Analyzed: File Not Found"}`:Xe?P=`${c.length>0?"\u2714":"\u2718"} ${c?`Processed: ${V.basename(c)}`:"Processed: File Not Found"}`:P=`${Le!=="..."?"\u2714":"\u2718"} Read: ${c?`${V.basename(c)} \u2192 ${Le!=="..."?`Lines ${$} - ${Ce} of ${Le}`:"File Not Found"}`:"File Not Found"}`}}else if(l==="list_files"||l==="read_folder"){let c=l==="list_files"?"List":"Browsed",_=G(w.args).path||null,W=G(w.args).recurse||1;P=`${_?"\u2714":"\u2718"} ${c}: ${_?`${_==="."?`./${W>1?"*":""}`:`${_.replaceAll("\\","/")}${W>1?`${_.endsWith("/")?"*":"/*"}`:`${_.endsWith("/")?"":"/"}`}`}`:"No Folder Selected"}`}else if(l==="find_file"){let c=G(w.args),_=c.basename||c.name||c.path||c.file||c.query||"";P=`${_?"\u2714":"\u2718"} Located: ${_||"No Query"}`}else if(l==="write_file"||l==="update_file"){let c=l==="write_file"?"Created":"Edited",_=G(w.args),W=_.path||null,ie=Object.entries(_).some(([ee,xe])=>ee.startsWith("searchContent")&&typeof xe=="string"&&xe.startsWith("^LINE:"))?"\u1361":":";P=`${W?"\u2714":"\u2718"} ${c}${ie} ${W?W.replaceAll("\\","/"):"No File Changes"}`}else if(l==="write_pdf"){let c=G(w.args).path||null;P=`${c?"\u2714":"\u2718"} Generated: ${c.replaceAll("\\","/")||"No PDF Generated"}`}else if(l==="write_docx"){let c=G(w.args).path||null;P=`${c?"\u2714":"\u2718"} Generated: ${c.replaceAll("\\","/")||"No Docx Generated"}`}else if(l==="file_map"){let c=G(w.args).path;P=`${c?"\u2714":"\u2718"} Indexed: ${c.replaceAll("\\","/")?""+c:"File Not Found"}`}else if(l.toLowerCase()==="search_keyword"||l.toLowerCase()==="todo")P="";else if(l.toLowerCase()==="generate_image"){let{path:c,outputPath:_,output:W}=G(w.args);P=`\u2714 Generated: ${c||_||W||"generated_image.png"}`}else if(l==="invoke_sync"||l==="InvokeSync"){let c=Zn(l,w.args);P=`\u2714 Called Generalist${c?`: ${c}`:""}`}else if(l==="Invoke"||l==="InvokeAsync"||l==="invoke"){let c=Zn(l,w.args);P=`\u2714 Started Generalist${c?`: ${c}`:""}`}else if(l==="get_progress"||l==="GetProgress"){let c=Zn(l,w.args);P=`\u2714 Checked${c?`: ${c}`:""}`}else if(l==="cancel"){let c=Zn(l,w.args);P=`\u{1F6C7} Cancelled${c?`: ${c}`:""}`}else if(l==="steer"||l==="Steer"){let c=Zn(l,w.args);P=`\u2714 Steered${c?`: ${c}`:""}`}else if(l==="EmergencyRollback"){let{method:c}=G(w.args);P=c==="forceRevert"?"":"\u2714 Rollback Point Checked"}else if(l==="await"||l==="Await"||l==="wait"||l==="Wait"){let{time:c,timeout:_,seconds:W,sec:pe}=G(w.args),ie=parseFloat(W||pe||_||c)||45,ee=l==="wait"||l==="Wait"?120:180;ie<10&&(ie=10),ie>ee&&(ie=ee);let xe=$=>{if($>=60){let K=Math.floor($/60),Le=$%60;return`${K}m${Le>0?` ${Le}s`:""}`}return`${$}s`},we=["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"];P=`\u2714 ${we[Math.floor(Math.random()*we.length)]} \u2192 ${xe(ie)}`}else l==="Answer"||l==="answer"?P="\u2714 Resolved Sub-Agent Query":l==="exec_command"||l==="ask"?P="":P=`Executed: ${w.toolName}`;if(yield*Yn(),l==="exec_command"){let{command:c}=G(w.args);if(c&&t.systemSettings&&t.systemSettings.allowExternalAccess===!1){let _=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],W=V.resolve(process.cwd()).substring(0,3).toLowerCase(),pe=Q=>{let $=[],K="",Le=null;for(let Ce=0;Ce<Q.length;Ce++){let se=Q[Ce];Le?(se===Le&&(Le=null),K+=se):se==='"'||se==="'"?(Le=se,K+=se):se==="&"&&Q[Ce+1]==="&"||se==="|"&&Q[Ce+1]==="|"?(K.trim()&&($.push(K.trim()),K=""),Ce++):se===";"||se==="|"||se==="&"?K.trim()&&($.push(K.trim()),K=""):K+=se}return K.trim()&&$.push(K.trim()),$},ie=Q=>{let $=[],K="",Le=null;for(let Ce=0;Ce<Q.length;Ce++){let se=Q[Ce];Le?(se===Le&&(Le=null),K+=se):se==='"'||se==="'"?(Le=se,K+=se):/\s/.test(se)?K&&($.push(K),K=""):K+=se}return K&&$.push(K),$},ee=Q=>{let $=Q.replace(/^['"]|['"]$/g,"").trim();return!$||process.platform==="win32"&&/^\/[a-zA-Z0-9?]+$/.test($)?!1:_.some(K=>{if(K.source==="[a-zA-Z]:[\\\\\\/]"){let Le=$.match(/[a-zA-Z]:[\\\/]/i);return Le&&Le[0].toLowerCase()!==W}return K.test($)})};if(pe(c).some(Q=>{let $=ie(Q);if($.length===0)return!1;let K=$[0].replace(/^['"]|['"]$/g,"").toLowerCase();if(["echo","printf","write-output"].includes(K)){let Ce=!1;return $.some(se=>{let Ot=se.replace(/^['"]|['"]$/g,"");if(Ot===">"||Ot===">>"||Ot==="<")return Ce=!0,!1;if(Ot.startsWith(">")||Ot.startsWith("<")){let Rt=Ot.replace(/^[><]+/,"");return ee(Rt)}return Ce?(Ce=!1,ee(se)):!1})}return $.some(Ce=>ee(Ce))})){let Q='Access Denied. Prohibited from accessing external directories while "External Workspace Access" is disabled.';t.onExecStart&&t.onExecStart(c||"No Command"),yield{type:"exec_start"},await new Promise($=>setTimeout($,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${Q}`),await new Promise($=>setTimeout($,50)),t.onExecEnd&&t.onExecEnd(),Ue.push({role:"user",text:`[ACTION RESULT]: ERROR: ${Q}`}),yield{type:"tool_result",content:`[ACTION RESULT]: ERROR: ${Q}`},Mt++;continue}}t.onExecStart&&t.onExecStart(c||"No Command"),yield{type:"exec_start"}}let yt=G(w.args),An=yt.path||yt.targetPath||null;if(An){let c=t.systemSettings&&t.systemSettings.allowExternalAccess===!1,_=V.resolve(An),W=V.resolve(process.cwd());if(c&&!_.startsWith(W)){let pe="Access Denied. You are not allowed to access files outside the current workspace.";if(l==="write_file"||l==="update_file"){let ee=`\u2718 ${l==="write_file"?"Write Canceled":"Edit Canceled"}: ${yt.path||"..."}`,xe=115;process.stdout.isTTY&&(xe=process.stdout.columns-5||120);let we=Math.min(ee.length+4,xe),Q=`${ee.padEnd(we-2).substring(0,we-2)}`;yield{type:"visual_feedback",content:Wt(`${We?`
752
+ `:""}${Q}
753
+ `)},We=!1}Ue.push({role:"user",text:`[ACTION RESULT]: ERROR: ${pe}`}),yield{type:"tool_result",content:`[ACTION RESULT]: ERROR: ${pe}`},Mt++;continue}}if(t.onToolApproval){let c=t.systemSettings||{},_=c.autoExec,W=!1,pe="";if(l==="view_file"){let ee=G(w.args);if(pe=ee.path||ee.targetPath||ee.file||"",pe){let xe=c.alwaysAskFiles||".env, .env.*, *.env";Is(pe,xe)&&(W=!0)}}if(l==="write_file"||l==="update_file"||l==="exec_command"||W){let ee=null,xe=!1,we=!1,Q=!1;if(W)xe=!0,ee=null;else if(l==="exec_command"){let{command:$e}=G(w.args),Xe=($e||"").trim(),he=(nn,qt)=>{if(!qt)return!1;let un=qt.split(",").map(Xt=>Xt.trim().toLowerCase()).filter(Boolean),nt=nn.toLowerCase();return un.some(Xt=>nt.startsWith(Xt))},He=he(Xe,c.alwaysAskCommands),F=he(Xe,c.autoApproveCommands);if(we=he(Xe,c.autoDisallowCommands),He?xe=!0:(F||c.autoApproveGit&&/^git\s+commit\b/i.test(Xe))&&(ee="allow"),!xe&&!ee){if(c.networkAccess===!1){let qt=Xe.trim().replace(/\s+/g," ").replace(/^['"]+|['"]+$/g,"").toLowerCase().split(" "),nt=qt[0].split("/").pop().split("\\").pop().replace(/\.exe$/,""),Xt=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"]),ot=!1;Xt.has(nt)&&(ot=!0);let Je=On=>qt.slice(1).some(Cn=>On.includes(Cn)),ft=On=>{let Cn=qt.findIndex(Rn=>On.includes(Rn)),qn=qt.findIndex(Rn=>["run","exec","test"].includes(Rn));return Cn!==-1&&!(qn!==-1&&qn<Cn)};nt==="git"&&Je(["clone","pull","push","fetch"])&&(ot=!0),nt==="go"&&Je(["get","install"])&&(ot=!0),nt==="npm"&&ft(["install","i","update","add"])&&(ot=!0),nt==="yarn"&&ft(["add","install","upgrade"])&&(ot=!0),nt==="pnpm"&&ft(["add","install","update"])&&(ot=!0),nt==="bun"&&ft(["add","install","update"])&&(ot=!0),nt==="deno"&&Je(["install","add"])&&(ot=!0),nt==="pip"&&Je(["install","download"])&&(ot=!0),nt==="pip3"&&Je(["install","download"])&&(ot=!0),nt==="cargo"&&Je(["install","add"])&&(ot=!0),["bash","sh","zsh","fish"].includes(nt)&&Je(["-c"])&&(ot=!0),nt==="cmd"&&Je(["/c"])&&(ot=!0),ot&&(ee="deny",Q=!0)}!ee&&we&&(ee="deny")}!xe&&!ee&&_&&(ee="allow")}else(l==="write_file"||l==="update_file")&&_&&(ee="allow");let $=ee,K="";ee==="deny"&&(Q?K="network":we?K="settings":K="prohibited");let Le=!1,Ce="",se=[],Ot=0,Rt=!1,tn="";if(!$&&t.onToolApproval)try{let $e=await t.onToolApproval(l,w.args,{checkOnly:!0});($e==="allow"||$e==="deny")&&($=$e,$==="deny"&&(K="user"))}catch{}if(!$){if(l==="write_file"||l==="update_file")try{let he=G(w.args),{path:He}=he;if(He){let F=V.resolve(process.cwd(),He),nn=Je=>Je?Je.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,ft=>ft.toUpperCase()):"",qt=nn(F),un="",nt=!1,Xt=await Jn(),ot=nn(Xt?.file_focused);if(Xt&&ot===qt&&Xt.full_content?(un=Xt.full_content,nt=!0):ke.existsSync(F)&&(un=ke.readFileSync(F,"utf8"),nt=!0),Ce=un,await ti.recordFileChange(F,un),nt){let Je=un;if(l==="write_file"){let ft=he.content||he.newContent||"";Je=ft.endsWith(`
754
+ `)?ft:ft+`
755
+ `,tn=Je}else{let{patchPairs:ft,allowMultiple:On,error:Cn}=Fi(he);if(Cn){let on=`[ACTION RESULT]: ERROR: ${Cn}`;Ue.push({role:"user",text:on}),await _t("toolFailure"),t.onToolResult&&t.onToolResult("failure",l),yield{type:"tool_result",content:on,toolName:l},Mt++;continue}let qn=he.allowMultiple!==void 0?he.allowMultiple===!0||String(he.allowMultiple).toLowerCase()==="true":On;Ot=ft.length;let Rn=Ps(un,ft,{allowMultiple:qn});Je=Rn.content,tn=Je,se=Rn.results;let zo=se.filter(on=>on.success),vi=se.filter(on=>!on.success);if(zo.length===0){let on=`[ACTION RESULT]: ERROR: Failed to apply patches to [${V.basename(F)}].
756
+ ${vi.map(Qe=>` \u2022 ${Qe.error}`).join(`
757
+ `)}`,_i=`\u2714 Edited: ${V.basename(F.replaceAll("\\","/"))}`,gn=115;process.stdout.isTTY&&(gn=process.stdout.columns-5||120);let Ln=Math.min(_i.length+4,gn),it=`${_i.padEnd(Ln-2).substring(0,Ln-2)}`;yield{type:"visual_feedback",content:Wt(`${We?`
758
+ `:""}${it}`)},We=!1,Ue.push({role:"user",text:on}),await _t("toolFailure"),t.onToolResult&&t.onToolResult("failure",l),yield{type:"tool_result",content:on,toolName:l},Mt++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${V.basename(F)}`},Yi(F,un,Je),Le=!0,await new Promise(ft=>setTimeout(ft,50))}else if(l==="write_file"){let Je=he.content||he.newContent||"",ft=Je.endsWith(`
759
+ `)?Je:Je+`
760
+ `;tn=ft,ke.existsSync(F)||(Rt=!0,ke.mkdirSync(V.dirname(F),{recursive:!0}),ke.writeFileSync(F,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${V.basename(F)}`},Yi(F,"",ft),Le=!0,await new Promise(On=>setTimeout(On,50))}}}catch(he){console.error("Simulation/Diff Error:",he)}let $e=null;Vi(he=>{$e=he});let Xe=t.onToolApproval;if($=await new Promise(async he=>{let He=setInterval(()=>{if($e){let F=t.onIDEApproval||Ho&&Ho.onIDEApproval;F&&F($e),clearInterval(He),he($e)}},100);try{let F=await Xe(l,w.args);clearInterval(He),he(F)}catch{clearInterval(He),he("deny")}}),Vi(null),l==="write_file"||l==="update_file"){let{path:he}=G(w.args);if(he){let He=V.resolve(process.cwd(),he);if(sr(He,$),$==="deny"&&Rt&&ke.existsSync(He))try{ke.unlinkSync(He)}catch{}}}$==="deny"&&(K="user")}if($==="allow"&&Le&&uo()){let{path:$e}=G(w.args),Xe=V.resolve(process.cwd(),$e),he=it=>it?V.resolve(it).replace(/\\/g,"/").toLowerCase():"",He=await Jn(),F="";if(He&&He.file_focused&&he(He.file_focused)===he(Xe)&&He.full_content&&(F=He.full_content),!F&&ke.existsSync(Xe)){let it=ke.readFileSync(Xe,"utf8");it&&(F=it)}!F&&tn&&(F=tn),(F||Rt)&&ke.writeFileSync(Xe,F,"utf8");let nn=F.split(/\r?\n/),qt=nn.length,un=Buffer.byteLength(F,"utf8"),nt="";Ce&&(nt=`Old File contents:
761
+ ${Ce.split(/\r?\n/).map((Qe,mn)=>`${mn+1} | ${Qe}`).join(`
770
762
  `)}
771
763
 
772
- `);let Qt="";if(Jt<=100)Qt=sn.join(`
773
- `);else{let at=sn.slice(0,50).join(`
774
- `),nt=sn.slice(-50).join(`
775
- `);Qt=`${at}
764
+ `);let Xt="";if(qt<=100)Xt=nn.join(`
765
+ `);else{let it=nn.slice(0,50).join(`
766
+ `),Qe=nn.slice(-50).join(`
767
+ `);Xt=`${it}
776
768
 
777
- ... [${Jt-100} lines truncated for history stability] ...
769
+ ... [${qt-100} lines truncated for history stability] ...
778
770
 
779
- ${nt}`}let rt="";if(l==="update_file"){let at=Os(Re,U,re,12,t?.compressToolResults||Ho?.systemSettings?.compressToolResults),{patchPairs:nt}=Di(j(w.args)),hn=nt?.length||Ft||1,Fn=0,Zt=0,ao=[];nt&&nt.length>0?nt.forEach((lo,vi)=>{let qo=lo.replace||"",yn=lo.new||"",Ii=qo.trim(),ko=yn.trim(),Ca=!!on&&U===on,Ra=ko?U.includes(yn)||U.includes(ko):!0,_a=yn?Re.includes(yn)||!!ko&&Re.includes(ko):!1,va=Ii?U.includes(qo)||U.includes(Ii):!1;Ca||!!yn&&Ra&&(!_a||!va||Ii===ko)?Fn++:(Zt++,ao.push(` \u2022 Block ${vi+1}: not applied (reverted or rejected in IDE).`))}):Fn=Ft||0;let Bn=0;if(on&&U!==on){let lo=Ja("","",on||"",U||"","","",{context:0});if(lo&&lo.hunks)for(let vi of lo.hunks){let qo=vi.lines.filter(yn=>yn.startsWith("+")).map(yn=>yn.slice(1).trim()).filter(Boolean);for(let yn of qo)Re.includes(yn)||Bn++}}let So=[`[${Fn}/${hn}] applied`];Zt>0&&So.push(`${Zt} rejected by user`),Bn>0&&So.push(`${Bn} manual ${Bn===1?"modification":"modifications"} by user`);let Aa=So.join(", "),Ea=ao.length>0?`
771
+ ${Qe}`}let ot="";if(l==="update_file"){let it=Os(Ce,F,se,12,t?.compressToolResults||Ho?.systemSettings?.compressToolResults),{patchPairs:Qe}=Fi(G(w.args)),mn=Qe?.length||Ot||1,$n=0,Jt=0,ro=[];Qe&&Qe.length>0?Qe.forEach((ao,Ii)=>{let qo=ao.replace||"",pn=ao.new||"",Mi=qo.trim(),ko=pn.trim(),Ra=!!tn&&F===tn,va=ko?F.includes(pn)||F.includes(ko):!0,_a=pn?Ce.includes(pn)||!!ko&&Ce.includes(ko):!1,Ia=Mi?F.includes(qo)||F.includes(Mi):!1;Ra||!!pn&&va&&(!_a||!Ia||Mi===ko)?$n++:(Jt++,ro.push(` \u2022 Block ${Ii+1}: not applied (reverted or rejected in IDE).`))}):$n=Ot||0;let Nn=0;if(tn&&F!==tn){let ao=Qa("","",tn||"",F||"","","",{context:0});if(ao&&ao.hunks)for(let Ii of ao.hunks){let qo=Ii.lines.filter(pn=>pn.startsWith("+")).map(pn=>pn.slice(1).trim()).filter(Boolean);for(let pn of qo)Ce.includes(pn)||Nn++}}let So=[`[${$n}/${mn}] applied`];Jt>0&&So.push(`${Jt} rejected by user`),Nn>0&&So.push(`${Nn} manual ${Nn===1?"modification":"modifications"} by user`);let Ea=So.join(", "),Ca=ro.length>0?`
780
772
 
781
773
  User Review Details:
782
- ${ao.join(`
783
- `)}`:"";rt=`File [${Ne}] updated via IDE Companion. ${Aa}.${Ea}
774
+ ${ro.join(`
775
+ `)}`:"";ot=`File [${$e}] updated via IDE Companion. ${Ea}.${Ca}
784
776
 
785
- ${at}`}else{let at=U.split(/\r?\n/),nt=at.length,hn=Buffer.byteLength(U,"utf8"),Fn="";Re&&(Fn=`Old File contents:
786
- ${Re.split(/\r?\n/).map((Bn,So)=>`${So+1} | ${Bn}`).join(`
777
+ ${it}`}else{let it=F.split(/\r?\n/),Qe=it.length,mn=Buffer.byteLength(F,"utf8"),$n="";Ce&&($n=`Old File contents:
778
+ ${Ce.split(/\r?\n/).map((Nn,So)=>`${So+1} | ${Nn}`).join(`
787
779
  `)}
788
780
 
789
- `);let Zt="";if(nt<=690)Zt=at.join(`
790
- `);else{let ao=at.slice(0,300).join(`
791
- `),Bn=at.slice(-300).join(`
792
- `);Zt=`${ao}
793
-
794
- ... [${nt-100} lines truncated] ...
795
-
796
- ${Bn}`}rt=`File [${Ne}] saved via IDE Companion (May have user edits).
797
- - Stats: [${nt} lines, ${(hn/1024).toFixed(1)} KB]
798
- ${Fn}- Content Preview:
799
-
800
- ${Zt}`}let tt=l==="write_file"?"Created":"Edited",mt=j(w.args),vn=Object.entries(mt).some(([at,nt])=>at.startsWith("searchContent")&&typeof nt=="string"&&nt.startsWith("^LINE:"))?"\u1361":":",qn=`${Ne?"\u2714":"\u2718"} ${tt}${vn} ${Ne?Ne.replaceAll("\\","/"):"No File Changes"}`,In=115;process.stdout.isTTY&&(In=process.stdout.columns-5||120);let zo=Math.min(qn.length+4,In),Ri=`${qn.padEnd(zo-2).substring(0,zo-2)}`;yield{type:"visual_feedback",content:jt(`${je?`
801
- `:""}${Ri}`)},je=!1;let rn=Date.now();un=rn,yield{type:"tool_time",content:rn-R};let pn=(rt||"").toString().replaceAll("\u2550".repeat(88),"=".repeat(35)).replaceAll("[UI_CONTEXT]","");pn.includes("[[VERIFIED]]")&&(pn=pn.replace(/\[\[VERIFIED\]\][\s\S]*?\[\[\/VERIFIED\]\]/g,`[SYSTEM NOTE]: Patch Block matched & applied successfully. Large Block omitted to conserve context.
802
- `));let Dn;if(l==="write_file"&&!pn.startsWith("ERROR:")){let nt=pn.replace(/^\[\[SAME\]\]\s*\r?\n?/,"").split(/\r?\n/),hn=nt.filter(Zt=>Zt.startsWith("File ")||Zt.trim().startsWith("- Stats:"));Dn=`[ACTION RESULT]: ${hn.length>0?hn.join(`
803
- `):nt.slice(0,2).join(`
804
- `)}`}else if(pn.startsWith("[[SAME]]")){let nt=pn.replace(/^\[\[SAME\]\]\s*\r?\n?/,"").split(/\r?\n/),hn=nt.filter(Zt=>Zt.startsWith("File ")||Zt.trim().startsWith("- Stats:"));Dn=`[ACTION RESULT]: ${hn.length>0?hn.join(`
805
- `):nt.slice(0,2).join(`
806
- `)}`}else Dn=`[ACTION RESULT]: ${pn}`;He.push({role:"user",text:Dn}),En=!0,await Lt("toolSuccess"),t.onToolResult&&t.onToolResult("success",l),yield{type:"tool_result",content:rt,aiContent:Dn,toolName:l},Rt++;continue}if(N==="deny"){let Ne=`Permission Denied: Prohibited ${l==="exec_command"?"Command":"file edit"}.`;if(V?Ne=`User denied reading ${W.basename(ye||".env")}`:z==="user"?Ne="Permission Denied by User":z==="settings"?Ne="Permission Denied by User Policy":z==="network"?Ne="Permission Denied: Sandbox Network Access Disabled by User Policy.":z==="prohibited"&&l==="exec_command"&&(Ne="Permission Denied: Prohibited Command in User Policy"),l==="view_file"){let et=`\u2718 Read Denied: ${j(w.args).path?.replaceAll("\\","/")||".env"}`,xe=115;process.stdout.isTTY&&(xe=process.stdout.columns-5||120);let Ve=Math.min(et.length+4,xe),U=`${et.padEnd(Ve-2).substring(0,Ve-2)}`;yield{type:"visual_feedback",content:jt(`${je?`
807
- `:""}${U}
808
- `)},je=!1}else if(l==="write_file"||l==="update_file"){let xe=`\u2718 ${l==="write_file"?"Write Cancelled":"Edit Denied"}: ${j(w.args).path.replaceAll("\\","/")||"..."}`,Ve=115;process.stdout.isTTY&&(Ve=process.stdout.columns-5||120);let U=Math.min(xe.length+4,Ve),sn=`${xe.padEnd(U-2).substring(0,U-2)}`,Jt=` ${" ".repeat(U)} `;yield{type:"visual_feedback",content:jt(`${je?`
809
- `:""}${sn}
810
- `)},je=!1}l==="exec_command"&&(await new Promise(et=>setTimeout(et,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${Ne}`),await new Promise(et=>setTimeout(et,50)),t.onExecEnd&&t.onExecEnd()),He.push({role:"user",text:`[ACTION RESULT]: DENIED: ${Ne}`}),yield{type:"tool_result",content:`[ACTION RESULT]: DENIED: ${Ne}`},await Lt("toolDenied"),t.onToolResult&&t.onToolResult("denied",l),Rt++;continue}}}if(M){let d=115;process.stdout.isTTY&&(d=process.stdout.columns-5||120);let I=await i(),V=!1;I&&(V=I.trim().length>0);let ye=Math.min(M.length+4,d),se=`${M.padEnd(ye-2).substring(0,ye-2)}`;yield{type:"visual_feedback",content:jt(`${je?`
811
- `:""}${se}${M.includes("\u2714")&&(M.includes("Created")||M.includes("Edited"))?"":`${V?"":`
812
- `}`}`)},je=!1}if(un>0){let d=Date.now()-un,I=Math.max(0,1e3-d);I>0&&await new Promise(V=>setTimeout(V,I))}let Wt={chatId:h,history:n,onChunk:d=>t.onExecChunk?t.onExecChunk(d):null,onAskUser:t.onAskUser,systemSettings:t.systemSettings,mode:a,isMultiModal:lt(ne),onVisualFeedback:t.onVisualFeedback,onSubagentUpdate:t.onSubagentUpdate,onTokenChunk:t.onTokenChunk,modelName:ne,aiProvider:t.aiProvider,apiKey:t.apiKey,onUsage:t.onUsage};if(l==="write_file"||l==="update_file")try{let{path:d}=j(w.args);if(d){let I=W.resolve(process.cwd(),d),V=await Jn();V&&V.file_focused===I&&V.full_content&&(Wt.forcedContent=V.full_content)}}catch{}Ie.push(l);let ie=await Bo(l,w.args,Wt);if((l==="write_file"||l==="update_file")&&!ie.startsWith("ERROR:")){let{path:d}=j(w.args);if(d){let I=W.resolve(process.cwd(),d);ir(I)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let Xe=Date.now();un=Xe,yield{type:"tool_time",content:Xe-R},xt=Xe;let Tt=null;if(typeof ie=="object"&&ie.binaryPart&&(Tt=ie.binaryPart,ie=ie.text),l==="search_keyword"){let{keyword:d,path:I}=j(w.args),V=typeof ie=="string"&&ie.startsWith("[GLOB]");V&&(ie=ie.slice(6).trimStart());let ye=typeof ie=="string"&&ie.startsWith("[DIR]");ye&&(ie=ie.slice(5).trimStart());let se=0;if(ie){let re=ie.match(/Found (\d+) match/i);re&&(se=parseInt(re[1]))}let te=(I||"").trim().toLowerCase().replaceAll("\\","/"),we=te==="#doc"||te==="#docs"||te==="#documentation"||te.includes("#skill/global/fluxflow")||te.includes("#skill/fluxflow")||te.includes("#skills/fluxflow")||te.includes("#skills/global/fluxflow"),ke,ee=115;process.stdout.isTTY&&(ee=process.stdout.columns-5||120);let N=Math.max(10,(ee+5)/3),z=Math.max(10,(ee+5)/4);if(we)ke=`${d?"\u2714":"\u2718"} Searched Documentation`;else{let re=I?I.replace(/[\/\\]+$/,""):null,Ft=re&&re!=="."?`${V?I:ye?`${re}/*`:re}`:"./",Pt=Ft.length>z?`${Ft.slice(0,z)}...`:Ft;ke=`${d?"\u2714":"\u2718"} Searched: "${d?d.length>ee/3?`${d.slice(0,N)}...`:d:""}" in "${Pt.replaceAll("\\","/")}" \u2192 ${se} Match${se===1?"":"es"}`}let $e=Math.min(ke.length+4,ee),Re=`${ke.padEnd($e-2).substring(0,$e-2)}`;yield{type:"visual_feedback",content:jt(`${je?`
813
- `:""}${Re}
814
- `)},je=!1}if(l==="EmergencyRollback"){let{method:d}=j(w.args);if(d==="forceRevert"){let I=0;if(ie){let N=ie.match(/Total\s*:\s*(\d+)/i);N&&(I=parseInt(N[1]))}let ye=ie&&ie.startsWith("ERROR:")?"\u2718 Emergency Rollback Failed":`\u2714 Emergency Rollback \u2192 ${I} file${I===1?"":"s"} processed`,se=115;process.stdout.isTTY&&(se=process.stdout.columns-5||120);let te=await i(),we=!1;te&&(we=te.trim().length>0);let ke=Math.min(ye.length+4,se),ee=`${ye.padEnd(ke-2).substring(0,ke-2)}`;yield{type:"visual_feedback",content:jt(`${je?`
815
- `:""}${ee}${we?"":`
816
- `}`)},je=!1}}if(l==="todo"){let{method:d,tasks:I,markDone:V}=j(w.args),ye="",se=[],te=we=>{if(!we)return[];let ke=Array.isArray(we)?we:[];if(ke.length===0&&typeof we=="string"){let ee=we.trim();if(ee.startsWith("[")&&ee.endsWith("]")){let N=ee.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);N?ke=N.map(z=>z.slice(1,-1).replace(/\\(.)/g,"$1")):ke=ee.slice(1,-1).split(",").map(z=>z.trim()).filter(Boolean)}else ke=we.split(`
817
- `)}return ke.filter(ee=>String(ee).trim()).map(ee=>{let N=String(ee).trim();return N.startsWith("- [")?N.substring(6).trim():N})};if(d==="create"?(ye="\x1B[32m\u2192\x1B[0m Created Goals",se=te(I).map(we=>`\x1B[90m\u25CB\x1B[0m ${we}`)):d==="append"?(ye="\x1B[34m\u2795\x1B[0m Added New Goals",se=te(I).map(we=>`\x1B[90m\u25CB\x1B[0m ${we}`)):d==="get"&&(ye=V?"\x1B[36m\u21BB\x1B[0m Updated Goals":"\x1B[35m\u2022\x1B[0m Reviewed Goals",se=(ie||"").split(`
781
+ `);let Jt="";if(Qe<=690)Jt=it.join(`
782
+ `);else{let ro=it.slice(0,300).join(`
783
+ `),Nn=it.slice(-300).join(`
784
+ `);Jt=`${ro}
785
+
786
+ ... [${Qe-100} lines truncated] ...
787
+
788
+ ${Nn}`}ot=`File [${$e}] saved via IDE Companion (May have user edits).
789
+ - Stats: [${Qe} lines, ${(mn/1024).toFixed(1)} KB]
790
+ ${$n}- Content Preview:
791
+
792
+ ${Jt}`}let Je=l==="write_file"?"Created":"Edited",ft=G(w.args),Cn=Object.entries(ft).some(([it,Qe])=>it.startsWith("searchContent")&&typeof Qe=="string"&&Qe.startsWith("^LINE:"))?"\u1361":":",qn=`${$e?"\u2714":"\u2718"} ${Je}${Cn} ${$e?$e.replaceAll("\\","/"):"No File Changes"}`,Rn=115;process.stdout.isTTY&&(Rn=process.stdout.columns-5||120);let zo=Math.min(qn.length+4,Rn),vi=`${qn.padEnd(zo-2).substring(0,zo-2)}`;yield{type:"visual_feedback",content:Wt(`${We?`
793
+ `:""}${vi}`)},We=!1;let on=Date.now();jn=on,yield{type:"tool_time",content:on-R};let gn=(ot||"").toString().replaceAll("\u2550".repeat(88),"=".repeat(35)).replaceAll("[UI_CONTEXT]","");gn.includes("[[VERIFIED]]")&&(gn=gn.replace(/\[\[VERIFIED\]\][\s\S]*?\[\[\/VERIFIED\]\]/g,`[SYSTEM NOTE]: Patch Block matched & applied successfully. Large Block omitted to conserve context.
794
+ `));let Ln;if(l==="write_file"&&!gn.startsWith("ERROR:")){let Qe=gn.replace(/^\[\[SAME\]\]\s*\r?\n?/,"").split(/\r?\n/),mn=Qe.filter(Jt=>Jt.startsWith("File ")||Jt.trim().startsWith("- Stats:"));Ln=`[ACTION RESULT]: ${mn.length>0?mn.join(`
795
+ `):Qe.slice(0,2).join(`
796
+ `)}`}else if(gn.startsWith("[[SAME]]")){let Qe=gn.replace(/^\[\[SAME\]\]\s*\r?\n?/,"").split(/\r?\n/),mn=Qe.filter(Jt=>Jt.startsWith("File ")||Jt.trim().startsWith("- Stats:"));Ln=`[ACTION RESULT]: ${mn.length>0?mn.join(`
797
+ `):Qe.slice(0,2).join(`
798
+ `)}`}else Ln=`[ACTION RESULT]: ${gn}`;Ue.push({role:"user",text:Ln}),kn=!0,await _t("toolSuccess"),t.onToolResult&&t.onToolResult("success",l),yield{type:"tool_result",content:ot,aiContent:Ln,toolName:l},Mt++;continue}if($==="deny"){let $e=`Permission Denied: Prohibited ${l==="exec_command"?"Command":"file edit"}.`;if(W?$e=`User denied reading ${V.basename(pe||".env")}`:K==="user"?$e="Permission Denied by User":K==="settings"?$e="Permission Denied by User Policy":K==="network"?$e="Permission Denied: Sandbox Network Access Disabled by User Policy.":K==="prohibited"&&l==="exec_command"&&($e="Permission Denied: Prohibited Command in User Policy"),l==="view_file"){let Xe=`\u2718 Read Denied: ${G(w.args).path?.replaceAll("\\","/")||".env"}`,he=115;process.stdout.isTTY&&(he=process.stdout.columns-5||120);let He=Math.min(Xe.length+4,he),F=`${Xe.padEnd(He-2).substring(0,He-2)}`;yield{type:"visual_feedback",content:Wt(`${We?`
799
+ `:""}${F}
800
+ `)},We=!1}else if(l==="write_file"||l==="update_file"){let he=`\u2718 ${l==="write_file"?"Write Cancelled":"Edit Denied"}: ${G(w.args).path.replaceAll("\\","/")||"..."}`,He=115;process.stdout.isTTY&&(He=process.stdout.columns-5||120);let F=Math.min(he.length+4,He),nn=`${he.padEnd(F-2).substring(0,F-2)}`,qt=` ${" ".repeat(F)} `;yield{type:"visual_feedback",content:Wt(`${We?`
801
+ `:""}${nn}
802
+ `)},We=!1}l==="exec_command"&&(await new Promise(Xe=>setTimeout(Xe,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${$e}`),await new Promise(Xe=>setTimeout(Xe,50)),t.onExecEnd&&t.onExecEnd()),Ue.push({role:"user",text:`[ACTION RESULT]: DENIED: ${$e}`}),yield{type:"tool_result",content:`[ACTION RESULT]: DENIED: ${$e}`},await _t("toolDenied"),t.onToolResult&&t.onToolResult("denied",l),Mt++;continue}}}if(P){let c=115;process.stdout.isTTY&&(c=process.stdout.columns-5||120);let _=await i(),W=!1;_&&(W=_.trim().length>0);let pe=Math.min(P.length+4,c),ie=`${P.padEnd(pe-2).substring(0,pe-2)}`;yield{type:"visual_feedback",content:Wt(`${We?`
803
+ `:""}${ie}${P.includes("\u2714")&&(P.includes("Created")||P.includes("Edited"))?"":`${W?"":`
804
+ `}`}`)},We=!1}if(jn>0){let c=Date.now()-jn,_=Math.max(0,1e3-c);_>0&&await new Promise(W=>setTimeout(W,_))}let Ft={chatId:h,history:n,onChunk:c=>t.onExecChunk?t.onExecChunk(c):null,onAskUser:t.onAskUser,systemSettings:t.systemSettings,mode:a,isMultiModal:st(te),onVisualFeedback:t.onVisualFeedback,onSubagentUpdate:t.onSubagentUpdate,onTokenChunk:t.onTokenChunk,modelName:te,aiProvider:t.aiProvider,apiKey:t.apiKey,onUsage:t.onUsage};if(l==="write_file"||l==="update_file")try{let{path:c}=G(w.args);if(c){let _=V.resolve(process.cwd(),c),W=await Jn();W&&W.file_focused===_&&W.full_content&&(Ft.forcedContent=W.full_content)}}catch{}Se.push(l);let oe=await Bo(l,w.args,Ft);if((l==="write_file"||l==="update_file")&&!oe.startsWith("ERROR:")){let{path:c}=G(w.args);if(c){let _=V.resolve(process.cwd(),c);ir(_)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let Ve=Date.now();jn=Ve,yield{type:"tool_time",content:Ve-R},Hn=Ve;let xt=null;if(typeof oe=="object"&&oe.binaryPart&&(xt=oe.binaryPart,oe=oe.text),l==="search_keyword"){let{keyword:c,path:_}=G(w.args),W=typeof oe=="string"&&oe.startsWith("[GLOB]");W&&(oe=oe.slice(6).trimStart());let pe=typeof oe=="string"&&oe.startsWith("[DIR]");pe&&(oe=oe.slice(5).trimStart());let ie=0;if(oe){let se=oe.match(/Found (\d+) match/i);se&&(ie=parseInt(se[1]))}let ee=(_||"").trim().toLowerCase().replaceAll("\\","/"),xe=ee==="#doc"||ee==="#docs"||ee==="#documentation"||ee.includes("#skill/global/fluxflow")||ee.includes("#skill/fluxflow")||ee.includes("#skills/fluxflow")||ee.includes("#skills/global/fluxflow"),we,Q=115;process.stdout.isTTY&&(Q=process.stdout.columns-5||120);let $=Math.max(10,(Q+5)/3),K=Math.max(10,(Q+5)/4);if(xe)we=`${c?"\u2714":"\u2718"} Searched Documentation`;else{let se=_?_.replace(/[\/\\]+$/,""):null,Ot=se&&se!=="."?`${W?_:pe?`${se}/*`:se}`:"./",Rt=Ot.length>K?`${Ot.slice(0,K)}...`:Ot;we=`${c?"\u2714":"\u2718"} Searched: "${c?c.length>Q/3?`${c.slice(0,$)}...`:c:""}" in "${Rt.replaceAll("\\","/")}" \u2192 ${ie} Match${ie===1?"":"es"}`}let Le=Math.min(we.length+4,Q),Ce=`${we.padEnd(Le-2).substring(0,Le-2)}`;yield{type:"visual_feedback",content:Wt(`${We?`
805
+ `:""}${Ce}
806
+ `)},We=!1}if(l==="EmergencyRollback"){let{method:c}=G(w.args);if(c==="forceRevert"){let _=0;if(oe){let $=oe.match(/Total\s*:\s*(\d+)/i);$&&(_=parseInt($[1]))}let pe=oe&&oe.startsWith("ERROR:")?"\u2718 Emergency Rollback Failed":`\u2714 Emergency Rollback \u2192 ${_} file${_===1?"":"s"} processed`,ie=115;process.stdout.isTTY&&(ie=process.stdout.columns-5||120);let ee=await i(),xe=!1;ee&&(xe=ee.trim().length>0);let we=Math.min(pe.length+4,ie),Q=`${pe.padEnd(we-2).substring(0,we-2)}`;yield{type:"visual_feedback",content:Wt(`${We?`
807
+ `:""}${Q}${xe?"":`
808
+ `}`)},We=!1}}if(l==="todo"){let{method:c,tasks:_,markDone:W}=G(w.args),pe="",ie=[],ee=xe=>{if(!xe)return[];let we=Array.isArray(xe)?xe:[];if(we.length===0&&typeof xe=="string"){let Q=xe.trim();if(Q.startsWith("[")&&Q.endsWith("]")){let $=Q.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);$?we=$.map(K=>K.slice(1,-1).replace(/\\(.)/g,"$1")):we=Q.slice(1,-1).split(",").map(K=>K.trim()).filter(Boolean)}else we=xe.split(`
809
+ `)}return we.filter(Q=>String(Q).trim()).map(Q=>{let $=String(Q).trim();return $.startsWith("- [")?$.substring(6).trim():$})};if(c==="create"?(pe="\x1B[32m\u2192\x1B[0m Created Goals",ie=ee(_).map(xe=>`\x1B[90m\u25CB\x1B[0m ${xe}`)):c==="append"?(pe="\x1B[34m\u2795\x1B[0m Added New Goals",ie=ee(_).map(xe=>`\x1B[90m\u25CB\x1B[0m ${xe}`)):c==="get"&&(pe=W?"\x1B[36m\u21BB\x1B[0m Updated Goals":"\x1B[35m\u2022\x1B[0m Reviewed Goals",ie=(oe||"").split(`
818
810
  `).slice(1).join(`
819
811
  `).split(`
820
- `).filter(ke=>ke.trim().startsWith("- [")).map(ke=>{let ee=ke.trim(),N=ee.startsWith("- [x]");return`${N?"\x1B[32m\u2714\x1B[0m":"\x1B[90m\u25CB\x1B[0m"} ${N?"\x1B[90m":"\x1B[37m"}${ee.substring(6).trim()}\x1B[0m`})),ye&&se.length>0){let we=[`${ye}`,...se.map(N=>` ${N}`)].join(`
821
- `),ke=await i(),ee=!1;ke&&(ee=ke.trim().length>0),yield{type:"visual_feedback",content:jt(`${je?`
822
- `:""}${we}${ee?"":`
823
- `}`)},je=!1}}l==="exec_command"&&t.onExecEnd&&(await new Promise(d=>setTimeout(d,800)),t.onExecEnd());let Gt=ie&&ie.startsWith("DENIED:");ie&&!ie.startsWith("ERROR:")&&!Gt?(await Lt("toolSuccess"),t.onToolResult&&t.onToolResult("success",l)):Gt||(await Lt("toolFailure"),t.onToolResult&&t.onToolResult("failure",l));let Mt=(ie||"").toString().replaceAll("\u2550".repeat(88),"=".repeat(35)).replaceAll("[UI_CONTEXT]","");Mt.includes("[[VERIFIED]]")&&(Mt=Mt.replace(/\[\[VERIFIED\]\][\s\S]*?\[\[\/VERIFIED\]\]/g,`[SYSTEM NOTE]: Patch Block matched & applied successfully. Large Block omitted to save tokens.
824
- `));let bn;if(l==="write_file"&&!Mt.startsWith("ERROR:")){let I=Mt.replace(/^\[\[SAME\]\]\s*\r?\n?/,"").split(/\r?\n/),V=I.filter(se=>se.startsWith("File ")||se.trim().startsWith("- Stats:"));bn=`[ACTION RESULT]: ${V.length>0?V.join(`
825
- `):I.slice(0,2).join(`
826
- `)}`}else if(Mt.startsWith("[[SAME]]")){let I=Mt.replace(/^\[\[SAME\]\]\s*\r?\n?/,"").split(/\r?\n/),V=I.filter(se=>se.startsWith("File ")||se.trim().startsWith("- Stats:"));bn=`[ACTION RESULT]: ${V.length>0?V.join(`
827
- `):I.slice(0,2).join(`
828
- `)}`}else bn=`[ACTION RESULT]: ${Mt}`;He.push({role:"user",text:bn,binaryPart:Tt}),En=!0;let be=`[ACTION RESULT]: ${ie.replaceAll(`[[VERIFIED]]
812
+ `).filter(we=>we.trim().startsWith("- [")).map(we=>{let Q=we.trim(),$=Q.startsWith("- [x]");return`${$?"\x1B[32m\u2714\x1B[0m":"\x1B[90m\u25CB\x1B[0m"} ${$?"\x1B[90m":"\x1B[37m"}${Q.substring(6).trim()}\x1B[0m`})),pe&&ie.length>0){let xe=[`${pe}`,...ie.map($=>` ${$}`)].join(`
813
+ `),we=await i(),Q=!1;we&&(Q=we.trim().length>0),yield{type:"visual_feedback",content:Wt(`${We?`
814
+ `:""}${xe}${Q?"":`
815
+ `}`)},We=!1}}l==="exec_command"&&t.onExecEnd&&(await new Promise(c=>setTimeout(c,800)),t.onExecEnd());let Bt=oe&&oe.startsWith("DENIED:");oe&&!oe.startsWith("ERROR:")&&!Bt?(await _t("toolSuccess"),t.onToolResult&&t.onToolResult("success",l)):Bt||(await _t("toolFailure"),t.onToolResult&&t.onToolResult("failure",l));let Ct=(oe||"").toString().replaceAll("\u2550".repeat(88),"=".repeat(35)).replaceAll("[UI_CONTEXT]","");Ct.includes("[[VERIFIED]]")&&(Ct=Ct.replace(/\[\[VERIFIED\]\][\s\S]*?\[\[\/VERIFIED\]\]/g,`[SYSTEM NOTE]: Patch Block matched & applied successfully. Large Block omitted to save tokens.
816
+ `));let fn;if(l==="write_file"&&!Ct.startsWith("ERROR:")){let c=Ct.replace(/^\[\[SAME\]\]\s*\r?\n?/,"");if(/- Stats:.*\r?\nOld File contents:/s.test(c)){let _=c.search(/^- Content Preview:/m);fn=`[ACTION RESULT]: ${_!==-1?c.slice(0,_).trimEnd():c}
817
+
818
+ [Old file content for reversal reference. Replaced with new write request]`}else{let _=c.split(/\r?\n/),W=_.filter(ie=>ie.startsWith("File ")||ie.trim().startsWith("- Stats:"));fn=`[ACTION RESULT]: ${W.length>0?W.join(`
819
+ `):_.slice(0,2).join(`
820
+ `)}`}}else if(Ct.startsWith("[[SAME]]")){let _=Ct.replace(/^\[\[SAME\]\]\s*\r?\n?/,"").split(/\r?\n/),W=_.filter(ie=>ie.startsWith("File ")||ie.trim().startsWith("- Stats:"));fn=`[ACTION RESULT]: ${W.length>0?W.join(`
821
+ `):_.slice(0,2).join(`
822
+ `)}`}else fn=`[ACTION RESULT]: ${Ct}`;Ue.push({role:"user",text:fn,binaryPart:xt}),kn=!0;let ye=`[ACTION RESULT]: ${oe.replaceAll(`[[VERIFIED]]
829
823
  `,"").replaceAll(`
830
- [[/VERIFIED]]`,"")||""}`;(l==="view_file"||l==="web_scrape"||l==="file_map"||l==="search_keyword"||l==="get_progress"||l==="getprogress")&&(be=`[ACTION RESULT]: ${M} (Context Locked for UI Clarity)`),yield{type:"tool_result",content:be,aiContent:bn,binaryPart:Tt,toolName:l},l==="memory"&&!ie.startsWith("ERROR:")&&(yield{type:"memory_updated"}),Rt++}if(s==="Google"&&Ut&&Date.now()-io>=150){yield*Yn();let w=xo(Ut);for(let R of w)yield R;Ut="",io=Date.now()}}m.usageMetadata&&(fn=m.usageMetadata),fn&&(yield{type:"liveTokens",content:fn.totalTokenCount})}if(X&&(X=!1,ut?ve+="</think_fluxflow>":(pe+="</think_fluxflow>",s==="Google"?Ut+="</think_fluxflow>":yield{type:"text",content:"</think_fluxflow>"})),ut&&ve.length>0){let m=0,A=Math.min(_t.length,ve.length);for(let J=A;J>0;J--)if(_t.endsWith(ve.substring(0,J))){m=J;break}let C=ve.substring(m);if(C){let le=/(?:<think_fluxflow>|\[think_fluxflow\])(?:(?!(?:<\/think_fluxflow>|\[\/think_fluxflow\]))[\s\S])*$/i.test(_t)?C.replace(/^\s*(?:<think_fluxflow>|\[think_fluxflow\])\s*/gi,""):C.replace(/^\s*(?:<think_fluxflow>|\[think_fluxflow\])[\s\S]*?(?:<\/think_fluxflow>|\[\/think_fluxflow\])\s*/gi,"").replace(/^\s*(?:<think_fluxflow>|\[think_fluxflow\])\s*/gi,"");if(le)if(pe+=le,s==="Google")Ut+=le;else{yield*Yn();let F=xo(le);for(let Q of F)yield Q}}ut=!1,ve=""}if(Cn){let m=Cn,A=(wt==="tool"||wt==="action")&&(m.startsWith("[tool:")||m.startsWith("[action:"));Cn="",so=!1,wt=null,zn=!1,ro=!1,A||(s==="Google"?Ut+=m:yield{type:"text",content:m})}if(yield*Yn(),Et)break;let bo=(pe||"").trim(),xa=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(bo.toLowerCase())||/\[\[END\]\]/i.test(bo.toLowerCase()),ba=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(bo.toLowerCase()),wa=He.length>0||P!==null,Ci=Kt(bo).trim(),Sa=/(\p{Emoji_Presentation}|\p{Extended_Pictographic})$/u.test(Ci),ka=/([.!?"'*_`|\]\)”’~~]+|\s|`{3}|[\u200B-\u200D\uFEFF])$/u.test(Ci.trim()),Ta=/[.!?}"'`’“”]$|```$/s.test(Ci)||ka||Sa;!xa&&!ba&&!wa&&bo.length>0,Ue=!0,await Lt("agent",s)}catch(B){if(Et){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
824
+ [[/VERIFIED]]`,"")||""}`;(l==="view_file"||l==="web_scrape"||l==="file_map"||l==="search_keyword"||l==="get_progress"||l==="getprogress")&&(ye=`[ACTION RESULT]: ${P} (Context Locked for UI Clarity)`),yield{type:"tool_result",content:ye,aiContent:fn,binaryPart:xt,toolName:l},l==="memory"&&!oe.startsWith("ERROR:")&&(yield{type:"memory_updated"}),Mt++}if(s==="Google"&&Dt&&Date.now()-oo>=150){yield*Yn();let w=xo(Dt);for(let R of w)yield R;Dt="",oo=Date.now()}}m.usageMetadata&&(cn=m.usageMetadata),cn&&(yield{type:"liveTokens",content:cn.totalTokenCount})}if(z&&(z=!1,lt?ve+="</think_fluxflow>":(Ee+="</think_fluxflow>",s==="Google"?Dt+="</think_fluxflow>":yield{type:"text",content:"</think_fluxflow>"})),lt&&ve.length>0){let m=0,A=Math.min(kt.length,ve.length);for(let q=A;q>0;q--)if(kt.endsWith(ve.substring(0,q))){m=q;break}let C=ve.substring(m);if(C){let ae=/(?:<think_fluxflow>|\[think_fluxflow\])(?:(?!(?:<\/think_fluxflow>|\[\/think_fluxflow\]))[\s\S])*$/i.test(kt)?C.replace(/^\s*(?:<think_fluxflow>|\[think_fluxflow\])\s*/gi,""):C.replace(/^\s*(?:<think_fluxflow>|\[think_fluxflow\])[\s\S]*?(?:<\/think_fluxflow>|\[\/think_fluxflow\])\s*/gi,"").replace(/^\s*(?:<think_fluxflow>|\[think_fluxflow\])\s*/gi,"");if(ae)if(Ee+=ae,s==="Google")Dt+=ae;else{yield*Yn();let D=xo(ae);for(let X of D)yield X}}lt=!1,ve=""}if(Tn){let m=Tn,A=(pt==="tool"||pt==="action")&&(m.startsWith("[tool:")||m.startsWith("[action:"));Tn="",io=!1,pt=null,zn=!1,so=!1,A||(s==="Google"?Dt+=m:yield{type:"text",content:m})}if(yield*Yn(),wt)break;let bo=(Ee||"").trim(),ba=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(bo.toLowerCase())||/\[\[END\]\]/i.test(bo.toLowerCase()),wa=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(bo.toLowerCase()),Sa=Ue.length>0||Yt!==null,Ri=Lt(bo).trim(),ka=/(\p{Emoji_Presentation}|\p{Extended_Pictographic})$/u.test(Ri),Ta=/([.!?"'*_`|\]\)”’~~]+|\s|`{3}|[\u200B-\u200D\uFEFF])$/u.test(Ri.trim()),Aa=/[.!?}"'`’“”]$|```$/s.test(Ri)||Ta||ka;!ba&&!wa&&!Sa&&bo.length>0,Ne=!0,await _t("agent",s)}catch(Z){if(wt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
831
825
 
832
- \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(String(B).includes("Incomplete JSON segment at the end")){X&&(X=!1,ut?ve+="</think_fluxflow>":(pe+="</think_fluxflow>",yield{type:"text",content:"</think_fluxflow>"})),Ue=!0,await Lt("agent",s);break}if(X&&(X=!1,ut?ve+="</think_fluxflow>":pe+="</think_fluxflow>"),ut&&ve.length>0){let vt=0,gt=Math.min(_t.length,ve.length);for(let ot=gt;ot>0;ot--)if(_t.endsWith(ve.substring(0,ot))){vt=ot;break}let bt=ve.substring(vt);if(bt){let Dt=/(?:<think_fluxflow>|\[think_fluxflow\])(?:(?!(?:<\/think_fluxflow>|\[\/think_fluxflow\]))[\s\S])*$/i.test(_t)?bt.replace(/^\s*(?:<think_fluxflow>|\[think_fluxflow\])\s*/gi,""):bt.replace(/^\s*(?:<think_fluxflow>|\[think_fluxflow\])[\s\S]*?(?:<\/think_fluxflow>|\[\/think_fluxflow\])\s*/gi,"").replace(/^\s*(?:<think_fluxflow>|\[think_fluxflow\])\s*/gi,"");Dt&&(pe+=Dt)}ut=!1,ve=""}let $=B instanceof Error?(()=>{try{return JSON.parse(JSON.parse(B.message).error.message).error.message}catch{return String(B)}})():String(B),pt=new Date().toLocaleString(),Fe=W.join(wn,"agent");Ae.existsSync(Fe)||Ae.mkdirSync(Fe,{recursive:!0}),Ae.appendFileSync(W.join(Fe,"error.log"),`ERROR [${pt}]: ${$}
826
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(String(Z).includes("Incomplete JSON segment at the end")){z&&(z=!1,lt?ve+="</think_fluxflow>":(Ee+="</think_fluxflow>",yield{type:"text",content:"</think_fluxflow>"})),Ne=!0,await _t("agent",s);break}if(z&&(z=!1,lt?ve+="</think_fluxflow>":Ee+="</think_fluxflow>"),lt&&ve.length>0){let Tt=0,dt=Math.min(kt.length,ve.length);for(let et=dt;et>0;et--)if(kt.endsWith(ve.substring(0,et))){Tt=et;break}let mt=ve.substring(Tt);if(mt){let Pt=/(?:<think_fluxflow>|\[think_fluxflow\])(?:(?!(?:<\/think_fluxflow>|\[\/think_fluxflow\]))[\s\S])*$/i.test(kt)?mt.replace(/^\s*(?:<think_fluxflow>|\[think_fluxflow\])\s*/gi,""):mt.replace(/^\s*(?:<think_fluxflow>|\[think_fluxflow\])[\s\S]*?(?:<\/think_fluxflow>|\[\/think_fluxflow\])\s*/gi,"").replace(/^\s*(?:<think_fluxflow>|\[think_fluxflow\])\s*/gi,"");Pt&&(Ee+=Pt)}lt=!1,ve=""}let M=Z instanceof Error?(()=>{try{return JSON.parse(JSON.parse(Z.message).error.message).error.message}catch{return String(Z)}})():String(Z),ct=new Date().toLocaleString(),Pe=V.join(yn,"agent");ke.existsSync(Pe)||ke.mkdirSync(Pe,{recursive:!0}),ke.appendFileSync(V.join(Pe,"error.log"),`ERROR [${ct}]: ${M}
833
827
 
834
828
  ----------------------------------------------------------------------
835
829
 
836
- `);let Ke=B.status||B.statusCode||B.code,It=String(B).includes("replicas at capacity");if(!(Ke&&(Ke>=500&&Ke<600||Ke===408||Ke===429||It)||!Ke&&(/status[ :]+(5\d\d|408|429)/i.test(String(B))||/code[ :]+(5\d\d|408|429)/i.test(String(B))||/(500|503|408|429)/.test(String(B))))){if(qe<xn-3)throw B;yield{type:"text",content:$},yield{type:"status",content:"Error Occured"}}if(pe.trim().length>0||Ze>1)if(Ze<=xn){Ze++;let vt=Math.min(1e3*Math.pow(2,Ze-1),24e3);if(pe.trim().length>0){b.push({role:"agent",text:pe});let gt=`[system]
830
+ `);let Ge=Z.status||Z.statusCode||Z.code,Et=String(Z).includes("replicas at capacity");if(!(Ge&&(Ge>=500&&Ge<600||Ge===408||Ge===429||Et)||!Ge&&(/status[ :]+(5\d\d|408|429)/i.test(String(Z))||/code[ :]+(5\d\d|408|429)/i.test(String(Z))||/(500|503|408|429)/.test(String(Z))))){if(qe<hn-3)throw Z;yield{type:"text",content:M},yield{type:"status",content:"Error Occured"}}if(Ee.trim().length>0||Ze>1)if(Ze<=hn){Ze++;let Tt=Math.min(1e3*Math.pow(2,Ze-1),24e3);if(Ee.trim().length>0){b.push({role:"agent",text:Ee});let dt=`[system]
837
831
  - seamless continuation: resume immediately. pick up from last words with zero gap/disruption
838
832
  - no repetition: do not repeat any text already written
839
833
  - no re-think: do not restart or open <think_fluxflow> if reasoning already started. continue the thinking and close thinking block </think_fluxflow> before chat output
840
834
  - mid-tool safety: if cutoff was mid-tool call, restart that tool call from start
841
- - stealth: do not mention/apologize for cutoff [/system]`;He.length>0?He.forEach((bt,ot)=>{ot===He.length-1?b.push({...bt,text:`${bt.text}
835
+ - stealth: do not mention/apologize for cutoff [/system]`;Ue.length>0?Ue.forEach((mt,et)=>{et===Ue.length-1?b.push({...mt,text:`${mt.text}
842
836
 
843
- ${gt}`}):b.push(bt)}):b.push({role:"user",text:gt}),_t+=pe}for(let gt=vt/1e3;gt>0&&!Et;gt--)yield{type:"status",content:`Error Occured. Recovering Stream (${Ze}/${xn}) [Retrying in ${gt.toFixed(0)}s]...`},await new Promise(bt=>setTimeout(bt,1e3));yield{type:"status",content:"Error Occured. Recovering Stream..."}}else throw new Error(`Stream collapsed too many times. (Failed to resolve ${xn} times)
844
- Error log can be found in \`/export logs\``);else{let gt=e.split("/").slice(e.endsWith("/free")?-2:-1).join("/");if(qe<=xn){qe++,Ze=1,_t="";let bt=Math.min(1e3*Math.pow(2,qe-1),32e3),ot=.8+Math.random()*.4,Dt=Math.round(bt*ot);Ln=!0,yield{type:"status",content:`Trying to reach ${gt} (${qe}/${xn}) [Retrying in ${(Dt/1e3).toFixed(0)}s]`};for(let Ge=Dt/1e3;Ge>0&&!Et;Ge--)yield{type:"status",content:`Trying to reach ${gt} (${qe}/${xn}) [Retrying in ${Ge.toFixed(0)}s]`},await new Promise(Ut=>setTimeout(Ut,1e3));yield{type:"status",content:`Trying to reach ${gt}`}}else throw new Error(`Model ${e} cannot be reached. (Failed ${xn} times)
845
- Error log can be found in \`/export logs\``)}}}if(fn){let X=fn.totalTokenCount||0,B=fn.cachedContentTokenCount||0,$=(fn.candidatesTokenCount||0)+(s==="Google"&&fn.thoughtsTokenCount||0);await At("tokens",X,s,ne),B>0&&await At("cachedTokens",B,s,ne),$>0&&await At("candidateTokens",$,s,ne),Te!==null&&Te>0&&await At("ttft",Te,s,ne),Co({provider:s,model:ne,prompt:fn.promptTokenCount||0,cached:B,output:$,reasoning:fn.thoughtsTokenCount||0,ttft:Te}),yield{type:"usage",content:fn}}else Te!==null&&Te>0&&(await At("ttft",Te,s,ne),Co({provider:s,model:ne,prompt:0,cached:0,output:0,reasoning:0,ttft:Te}));pe=sa(pe),Ti.push(pe);let kl=Kt(pe),Ei=na(pe),ga=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(Ei.toLowerCase())||/\[\[END\]\]/i.test(Ei.toLowerCase())||!0,Tl=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(Ei.toLowerCase()),Al=Rt>0;yield{type:"status",content:process.env.HALLOWEEN_EEGG==="true"?"Performing dark ritual":"Thinking"};let ma=xl(pe,/(\[\s*(turn\s*:)?\s*(continue|finish)\s*\]|\[\[END\]\])/gi,"").trim(),Vn=(ga||He.length===0)&&!Bt&&!Kn&&!Xt;if(Vn=He.length===0?Vn:!1,Vn=nn||Vo?!1:Vn,pe&&pe.trim().endsWith('")]')&&He.length===0&&(Vn=!1),Vn){Cs=!0;let X=Ti.join(`
846
- `),B=Kt(X).trim();yield{type:"interactive_turn_finished",data:{agentText:Me,fullAgentTextRaw:X,history:[...b],needTitle:Ce}},b.length>0&&b[b.length-1].role==="agent"?b[b.length-1].text=B:b.push({role:"agent",text:B}),b.forEach($=>{if($.role==="user"&&$.text&&($.text=$.text.replace(/\n\[COMPILE ERROR\][\s\S]*?\[\/ERROR\]/g,""),$.text=$.text.replaceAll(`
837
+ ${dt}`}):b.push(mt)}):b.push({role:"user",text:dt}),kt+=Ee}for(let dt=Tt/1e3;dt>0&&!wt;dt--)yield{type:"status",content:`Error Occured. Recovering Stream (${Ze}/${hn}) [Retrying in ${dt.toFixed(0)}s]...`},await new Promise(mt=>setTimeout(mt,1e3));yield{type:"status",content:"Error Occured. Recovering Stream..."}}else throw new Error(`Stream collapsed too many times. (Failed to resolve ${hn} times)
838
+ Error log can be found in \`/export logs\``);else{let dt=e.split("/").slice(e.endsWith("/free")?-2:-1).join("/");if(qe<=hn){qe++,Ze=1,kt="";let mt=Math.min(1e3*Math.pow(2,qe-1),32e3),et=.8+Math.random()*.4,Pt=Math.round(mt*et);Mn=!0,yield{type:"status",content:`Trying to reach ${dt} (${qe}/${hn}) [Retrying in ${(Pt/1e3).toFixed(0)}s]`};for(let Be=Pt/1e3;Be>0&&!wt;Be--)yield{type:"status",content:`Trying to reach ${dt} (${qe}/${hn}) [Retrying in ${Be.toFixed(0)}s]`},await new Promise(Dt=>setTimeout(Dt,1e3));yield{type:"status",content:`Trying to reach ${dt}`}}else throw new Error(`Model ${e} cannot be reached. (Failed ${hn} times)
839
+ Error log can be found in \`/export logs\``)}}}if(cn){let z=cn.totalTokenCount||0,Z=cn.cachedContentTokenCount||0,M=(cn.candidatesTokenCount||0)+(s==="Google"&&cn.thoughtsTokenCount||0);await bt("tokens",z,s,te),Z>0&&await bt("cachedTokens",Z,s,te),M>0&&await bt("candidateTokens",M,s,te),At!==null&&At>0&&await bt("ttft",At,s,te),Co({provider:s,model:te,prompt:cn.promptTokenCount||0,cached:Z,output:M,reasoning:cn.thoughtsTokenCount||0,ttft:At}),yield{type:"usage",content:cn}}else At!==null&&At>0&&(await bt("ttft",At,s,te),Co({provider:s,model:te,prompt:0,cached:0,output:0,reasoning:0,ttft:At}));Ee=sa(Ee),Ai.push(Ee);let Tl=Lt(Ee),Ci=na(Ee),ga=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(Ci.toLowerCase())||/\[\[END\]\]/i.test(Ci.toLowerCase())||!0,Al=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(Ci.toLowerCase()),El=Mt>0;yield{type:"status",content:process.env.HALLOWEEN_EEGG==="true"?"Performing dark ritual":"Thinking"};let ma=bl(Ee,/(\[\s*(turn\s*:)?\s*(continue|finish)\s*\]|\[\[END\]\])/gi,"").trim(),pa=Ue.length>0||Wn(Lt(Ee)).length>0,Vn=(ga||Ue.length===0)&&!Nt&&!Kn&&!zt;if(Vn=Ue.length===0?Vn:!1,Vn=pa&&en||Vo?!1:Vn,Ee&&Ee.trim().endsWith('")]')&&Ue.length===0&&(Vn=!1),Vn){Cs=!0;let z=Ai.join(`
840
+ `),Z=Lt(z).trim();yield{type:"interactive_turn_finished",data:{agentText:_e,fullAgentTextRaw:z,history:[...b],needTitle:Ae}},b.length>0&&b[b.length-1].role==="agent"?b[b.length-1].text=Z:b.push({role:"agent",text:Z}),b.forEach(M=>{if(M.role==="user"&&M.text&&(M.text=M.text.replace(/\n\[COMPILE ERROR\][\s\S]*?\[\/ERROR\]/g,""),M.text=M.text.replaceAll(`
847
841
 
848
842
  [system] user question. resolve this specific query within '[ANSWER] ... [/ANSWER]' concisely, naturally [/system]
849
843
  `,"").replaceAll(`[system] user question. resolve this specific query within '[ANSWER] ... [/ANSWER]' concisely, naturally
850
844
  **strictly follow thinking policy as high priority. do not start a response without <think_fluxflow>...</think_fluxflow>** [/system]
851
845
  `,"").replaceAll(`[system] **strictly follow thinking policy as high priority. do not start a response without <think_fluxflow>...</think_fluxflow>** [/system]
852
- `,"").replaceAll(/\n\[system\] WARNING, Turn Limit Impending: Step \d+\/\d+\. Wrap up quickly\/prompt user to continue & use \[\[END\]\] quickly\. \[\/system\]/g,""),$.text=$.text.replaceAll(/\n\[system\] File Changes:\n(?:\* .+ \(created|modified|deleted\)\n)*\[\/system\]/g,""),(s==="Mistral"||s==="Google"&&e?.toLowerCase().startsWith("gemma"))&&($.text.startsWith("[ACTION RESULT]")||$.text.startsWith("[TOOL RESULT]")))){let Fe=`
853
- [system] Action result received. Analyze output and proceed with your turn [/system]`,Ke=`
854
- [system] Action result received. Analyze output and proceed with your turn. **strictly follow thinking policy. do not start a response without <think_fluxflow>...</think_fluxflow>** [/system]`;$.text=$.text.replaceAll(Ke,"").replaceAll(Fe,"").trim()}}),yield{type:"status",content:"[end]"}}if(Vn)break;let pa=ma.trim()||"*Working...*";if(b.push({role:"agent",text:pa}),He.length>0||En){if(He.length>0){let X=He.map(ot=>ot.text).join(`
855
-
856
- `),B=Kt(pe),$=ys(B),pt=eo(B),Fe=/\[\s*(?:tool:(?:functions\.)?|action:(?:functions\.)?|action:)([a-zA-Z0-9_]+)\s*\(/gi,Ke=[],It=[],Ee;for(;(Ee=Fe.exec($))!==null;)It.push({index:Ee.index,toolName:Ee[1]});for(let ot=0;ot<It.length;ot++){let Dt=It[ot],Ge=ot+1<It.length?It[ot+1].index:B.length;pt.some(io=>io.fullMatch&&B.startsWith(io.fullMatch,Dt.index))||Ke.push(B.substring(Dt.index,Ge))}let vt=Ke.length,gt=He.length+vt;if(vt>0){let ot=Ke.join(`
857
- `),Dt=oa(ot);X+=`
858
-
859
- [system] Only ${He.length} out of ${gt} attempted tool calls were executed.
860
- ${Dt?`Parsing Issues Detected:
861
- ${Dt}
862
- `:""}Verify proper structure compliance [action:ActionName(arg="value")] & try failed calls again [/system]`;for(let Ge=0;Ge<vt;Ge++)await Lt("toolFailure")}let bt=He.find(ot=>ot.binaryPart)?.binaryPart||null;b.push({role:"user",text:X,binaryPart:bt})}}else if(!Et){let X=pe.replace(/(?:<think_fluxflow>|\[think_fluxflow\])[\s\S]*?(?:<\/think_fluxflow>|\[\/think_fluxflow\]|$)/i,""),B=(X.match(/\[(?:tool|action):/gi)||[]).length;if(Vo||nn||B>0){let $=oa(X),pt=$?`[system] Failed to execute ${B>0?B:1} tool call${B>1?"s":""} due to syntax/structure issues:
863
- ${$} [/system]`:`[system] Failed to execute ${B>0?B:1} tool${B>1?"s":""}. Verify proper structure compliance [action:ActionName(arg="value")] & try again [/system]`;b.push({role:"user",text:pt}),await Lt("toolFailure"),yield{type:"visual_feedback",content:`
864
- ${jt("\u2718 Model produced malformed tool call")}
846
+ `,"").replaceAll(/\n\[system\] WARNING, Turn Limit Impending: Step \d+\/\d+\. Wrap up quickly\/prompt user to continue & use \[\[END\]\] quickly\. \[\/system\]/g,""),M.text=M.text.replaceAll(/\n\[system\] File Changes:\n(?:\* .+ \(created|modified|deleted\)\n)*\[\/system\]/g,""),(s==="Mistral"||s==="Google"&&e?.toLowerCase().startsWith("gemma"))&&(M.text.startsWith("[ACTION RESULT]")||M.text.startsWith("[TOOL RESULT]")))){let Pe=`
847
+ [system] Action result received. Analyze output and proceed with your turn [/system]`,Ge=`
848
+ [system] Action result received. Analyze output and proceed with your turn. **strictly follow thinking policy. do not start a response without <think_fluxflow>...</think_fluxflow>** [/system]`;M.text=M.text.replaceAll(Ge,"").replaceAll(Pe,"").trim()}}),yield{type:"status",content:"[end]"}}if(Vn)break;let ha=ma.trim()||"*Working...*";if(b.push({role:"agent",text:ha}),Ue.length>0||kn){if(Ue.length>0){let z=Ue.map(et=>et.text).join(`
849
+
850
+ `),Z=Lt(Ee),M=yi(Z),ct=Wn(Z),Pe=/\[\s*(?:tool:(?:functions\.)?|action:(?:functions\.)?|action:)([a-zA-Z0-9_]+)\s*\(/gi,Ge=[],Et=[],Te;for(;(Te=Pe.exec(M))!==null;)Et.push({index:Te.index,toolName:Te[1]});for(let et=0;et<Et.length;et++){let Pt=Et[et],Be=et+1<Et.length?Et[et+1].index:Z.length;ct.some(oo=>oo.fullMatch&&Z.startsWith(oo.fullMatch,Pt.index))||Ge.push(Z.substring(Pt.index,Be))}let Tt=Ge.length,dt=Ue.length+Tt;if(Tt>0){let et=Ge.join(`
851
+ `),Pt=oa(et);z+=`
852
+
853
+ [system] Only ${Ue.length} out of ${dt} attempted tool calls were executed.
854
+ ${Pt?`Parsing Issues Detected:
855
+ ${Pt}
856
+ `:""}Verify proper structure compliance [action:ActionName(arg="value")] & try failed calls again [/system]`;for(let Be=0;Be<Tt;Be++)await _t("toolFailure")}let mt=Ue.find(et=>et.binaryPart)?.binaryPart||null;b.push({role:"user",text:z,binaryPart:mt})}}else if(!wt){let z=Ee.replace(/(?:<think_fluxflow>|\[think_fluxflow\])[\s\S]*?(?:<\/think_fluxflow>|\[\/think_fluxflow\]|$)/i,""),M=(yi(z).match(/\[\s*(?:tool:(?:functions\.)?|action:(?:functions\.)?|action:)([a-zA-Z0-9_]+)\s*\(/gi)||[]).length;if(Vo||en&&M>0||M>0){let ct=oa(z),Pe=ct?`[system] Failed to execute ${M>0?M:1} tool call${M>1?"s":""} due to syntax/structure issues:
857
+ ${ct} [/system]`:`[system] Failed to execute ${M>0?M:1} tool${M>1?"s":""}. Verify proper structure compliance [action:ActionName(arg="value")] & try again [/system]`;b.push({role:"user",text:Pe}),await _t("toolFailure"),yield{type:"visual_feedback",content:`
858
+ ${Wt("\u2718 Model produced malformed tool call")}
865
859
  `}}else yield{type:"visual_feedback",content:`
866
- ${jt("\u2718 Loop Detected")}
867
- `},b.push({role:"user",text:`[system] ${Kn&&!Bt?"Stuttering Detected by Internal System. Re-calibrate your response & proceed.":`${Bt?" Over Thinking":" Loop"} Detected by Internal System${Bt?" for current Effort Level":""}. ${Bt?"If you have planned the task, prioritize execution/output":"If you have finished your task provide a simple summary and end"}`} [/system]`});Bt=!1,Kn=!1,Xt=!1}p?.advanceRollback&&await Ro.recordTurnDelta(h,v+1,Ie),Ai=Ie.includes("recapture_screen"),Vo=Rt>0||En}if(!Cs&&!Et){let v="\u2726 Turn safety limit reached. Stopping execution.";yield{type:"text",content:`
860
+ ${Wt("\u2718 Loop Detected")}
861
+ `},b.push({role:"user",text:`[system] ${Kn&&!Nt?"Stuttering Detected by Internal System. Re-calibrate your response & proceed.":`${Nt?" Over Thinking":" Loop"} Detected by Internal System${Nt?" for current Effort Level":""}. ${Nt?"If you have planned the task, prioritize execution/output":"If you have finished your task provide a simple summary and end"}`} [/system]`});Nt=!1,Kn=!1,zt=!1}p?.advanceRollback&&await Ro.recordTurnDelta(h,I+1,Se),Ei=Se.includes("recapture_screen"),Vo=Mt>0||kn}if(!Cs&&!wt){let I="\u2726 Turn safety limit reached. Stopping execution.";yield{type:"text",content:`
868
862
 
869
- ${v}
870
- `};let _e=(Ti.join(`
863
+ ${I}
864
+ `};let Re=(Ai.join(`
871
865
  `)+`
872
- ${v}`).trim();yield{type:"interactive_turn_finished",data:{agentText:Me,fullAgentTextRaw:_e,history:[...b],needTitle:Ce}},yield{type:"status",content:"[end]"}}}catch(G){let b=G?.cause?` (Cause: ${G.cause?.message||String(G.cause)})`:"",fe=(G instanceof Error?(()=>{try{return JSON.parse(JSON.parse(G.message).error.message).error.message}catch{return(G.message?`${G.message}${b}`:"")||String(G)}})():String(G)).replace(/^(Error:\s*)+/i,"");s==="Google"&&!/^[A-Z0-9_\-\s]+ ERROR:/i.test(fe)&&(fe=`GEMINI ERROR: ${fe}`);let q=new Date().toLocaleString(),tn=W.join(wn,"agent");yield{type:"text",content:`
866
+ ${I}`).trim();yield{type:"interactive_turn_finished",data:{agentText:_e,fullAgentTextRaw:Re,history:[...b],needTitle:Ae}},yield{type:"status",content:"[end]"}}}catch(B){let b=B?.cause?` (Cause: ${B.cause?.message||String(B.cause)})`:"",fe=(B instanceof Error?(()=>{try{return JSON.parse(JSON.parse(B.message).error.message).error.message}catch{return(B.message?`${B.message}${b}`:"")||String(B)}})():String(B)).replace(/^(Error:\s*)+/i,"");s==="Google"&&!/^[A-Z0-9_\-\s]+ ERROR:/i.test(fe)&&(fe=`GEMINI ERROR: ${fe}`);let Y=new Date().toLocaleString(),Zt=V.join(yn,"agent");yield{type:"text",content:`
873
867
 
874
868
  \u2726 CRITICAL ERROR: ${fe.includes("fetch failed")?"Failed to Connect. Check your Internet Connection or Wait a moment":fe}
875
- \u2800`},Ae.existsSync(tn)||Ae.mkdirSync(tn,{recursive:!0}),Ae.appendFileSync(W.join(tn,"error.log"),`CRITICAL ERROR [${q}]: ${G}${G?.cause?`
876
- CAUSE: ${G.cause?.stack||G.cause}`:""}
869
+ \u2800`},ke.existsSync(Zt)||ke.mkdirSync(Zt,{recursive:!0}),ke.appendFileSync(V.join(Zt,"error.log"),`CRITICAL ERROR [${Y}]: ${B}${B?.cause?`
870
+ CAUSE: ${B.cause?.stack||B.cause}`:""}
877
871
 
878
872
  ----------------------------------------------------------------------
879
873
 
880
- `),typeof flushGoogleBuffer=="function"&&(yield*flushGoogleBuffer()),yield{type:"tool_result",content:`ERROR: [INTERNAL CRITICAL] ${fe}`}}finally{Je&&(clearInterval(Je),Je=null),typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),await ti.commitTransaction(),p?.advanceRollback&&await Ro.cleanup(h),await Jn()}yield{type:"status",content:null}},Bd=async(e,n,t=null,i=null,o=50,r=null,c=!1)=>{let a=await Eo(),u={...a,...n},h=process.env.SUBAGENT_MODEL?process.env.SUBAGENT_MODEL.trim():null,x=process.env.SUBAGENT_PROVIDER?process.env.SUBAGENT_PROVIDER.trim():null,p=new Date,f=`${p.getFullYear()}-${p.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(p.getDate()).padStart(2,"0")}, ${p.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}).replace(":","-")}`,g=(fe=>{if(!fe)return null;let q=fe.toLowerCase();return q==="google"?"Google":q==="deepseek"?"DeepSeek":q==="openrouter"?"OpenRouter":q==="nvidia"?"NVIDIA":q==="mistral"?"Mistral":q==="ollama"?"Ollama":q==="inferx"?"InferX":q==="sensenova"?"SenseNova":q==="poolside"?"Poolside":q==="9router"||q==="9Router"?"9router":q==="aihubmix"||q==="aihub"?"AIHubMix":q==="explabs"||q==="experientiallabs"||q==="experimentallabs"?"ExpLabs":q==="tokenharbor"||q==="token harbor"||q==="token_harbor"||q==="thk"?"TokenHarbor":q==="infron"?"Infron":q==="apinex"||q==="apx"?"APInex":q==="xkiro"||q==="kiro"?"xKiro":q==="c_openai"||q==="custom_openai"||q==="custom (openai)"||q==="custom"?"c_openai":null})(x),k=u?.systemSettings?.CustomSubAgent?u?.systemSettings?.SubAgentModel:null,he=u?.systemSettings?.CustomSubAgent?u?.systemSettings?.SubAgentProvider:null,y=null;if(k==="ENV"?(y=h,h&&g&&(u.aiProvider=g)):k&&k!=="Default"?(y=k,he&&(u.aiProvider=he)):h&&g&&(u.aiProvider=g),u.aiProvider){let fe=await Li(u.aiProvider);fe&&(u.apiKey=fe)}let E=fe=>{if(!fe||typeof fe!="string")return{allowed:!0};let q=[/rm\s+-[rf]{1,2}\s+[\/*.]/i,/rmdir\s+\/[sq]/i,/del\s+\/[fsq]/i,/\bformat\b\s+[a-z]:/i,/mkfs/i,/dd\s+if=/i,/\b(shutdown|reboot|poweroff|init\s+0|init\s+6)\b/i,/chmod\s+(-R\s+)?777\s+[\/*.]/i,/chown\s+(-R\s+)?root/i,/git\s+push\s+.*--force/i,/git\s+clean\s+-fdx/i,/\bsudo\s+su\b/i,/\bsu\s+-\b/i];for(let tn of q)if(tn.test(fe))return{allowed:!1,reason:`Blocked potentially destructive or unsafe command pattern: "${tn.source}"`};return{allowed:!0}},D=t||y||n?.modelName||n?.activeModel||a.activeModel,O=(process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux")==="Windows",T=O&&u?.systemSettings?.preferBash!==!1&&Ls(),Se="Run(command=string)",Ce=`Runs ${O?Fi()?"powershell":"windows CMD":"bash"} command`;T&&(Se=`Run(command=string, ${$s()||Fi()?"forcePowershell?=bool:false":"forceCwd?=bool:false"})`,Ce="Runs in git bash. Or force native shell");let Me=`-- ACTIONS (path = relative to CWD, path separator: '/') --
874
+ `),typeof flushGoogleBuffer=="function"&&(yield*flushGoogleBuffer()),yield{type:"tool_result",content:`ERROR: [INTERNAL CRITICAL] ${fe}`}}finally{Ye&&(clearInterval(Ye),Ye=null),typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),await ti.commitTransaction(),p?.advanceRollback&&await Ro.cleanup(h),await Jn()}yield{type:"status",content:null}},Ud=async(e,n,t=null,i=null,o=50,r=null,d=!1)=>{let a=await Eo(),u={...a,...n},h=process.env.SUBAGENT_MODEL?process.env.SUBAGENT_MODEL.trim():null,x=process.env.SUBAGENT_PROVIDER?process.env.SUBAGENT_PROVIDER.trim():null,p=new Date,f=`${p.getFullYear()}-${p.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(p.getDate()).padStart(2,"0")}, ${p.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}).replace(":","-")}`,g=(fe=>{if(!fe)return null;let Y=fe.toLowerCase();return Y==="google"?"Google":Y==="deepseek"?"DeepSeek":Y==="openrouter"?"OpenRouter":Y==="nvidia"?"NVIDIA":Y==="mistral"?"Mistral":Y==="ollama"?"Ollama":Y==="inferx"?"InferX":Y==="sensenova"?"SenseNova":Y==="poolside"?"Poolside":Y==="9router"||Y==="9Router"?"9router":Y==="aihubmix"||Y==="aihub"?"AIHubMix":Y==="explabs"||Y==="experientiallabs"||Y==="experimentallabs"?"ExpLabs":Y==="tokenharbor"||Y==="token harbor"||Y==="token_harbor"||Y==="thk"?"TokenHarbor":Y==="infron"?"Infron":Y==="apinex"||Y==="apx"?"APInex":Y==="xkiro"||Y==="kiro"?"xKiro":Y==="c_openai"||Y==="custom_openai"||Y==="custom (openai)"||Y==="custom"?"c_openai":null})(x),k=u?.systemSettings?.CustomSubAgent?u?.systemSettings?.SubAgentModel:null,me=u?.systemSettings?.CustomSubAgent?u?.systemSettings?.SubAgentProvider:null,y=null;if(k==="ENV"?(y=h,h&&g&&(u.aiProvider=g)):k&&k!=="Default"?(y=k,me&&(u.aiProvider=me)):h&&g&&(u.aiProvider=g),u.aiProvider){let fe=await $i(u.aiProvider);fe&&(u.apiKey=fe)}let E=fe=>{if(!fe||typeof fe!="string")return{allowed:!0};let Y=[/rm\s+-[rf]{1,2}\s+[\/*.]/i,/rmdir\s+\/[sq]/i,/del\s+\/[fsq]/i,/\bformat\b\s+[a-z]:/i,/mkfs/i,/dd\s+if=/i,/\b(shutdown|reboot|poweroff|init\s+0|init\s+6)\b/i,/chmod\s+(-R\s+)?777\s+[\/*.]/i,/chown\s+(-R\s+)?root/i,/git\s+push\s+.*--force/i,/git\s+clean\s+-fdx/i,/\bsudo\s+su\b/i,/\bsu\s+-\b/i];for(let Zt of Y)if(Zt.test(fe))return{allowed:!1,reason:`Blocked potentially destructive or unsafe command pattern: "${Zt.source}"`};return{allowed:!0}},N=t||y||n?.modelName||n?.activeModel||a.activeModel,O=(process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux")==="Windows",T=O&&u?.systemSettings?.preferBash!==!1&&Ls(),be="Run(command=string)",Ae=`Runs ${O?Bi()?"powershell":"windows CMD":"bash"} command`;T&&(be=`Run(command=string, ${$s()||Bi()?"forcePowershell?=bool:false":"forceCwd?=bool:false"})`,Ae="Runs in git bash. Or force native shell");let _e=`-- ACTIONS (path = relative to CWD, path separator: '/') --
881
875
  In chat output the format \`[action:ActionName(arg1="value1")]\` in NEW line
882
876
  Rules:
883
877
  - JSON escape literal sequences, backslash: \\\\, newLine: \\ n
@@ -888,7 +882,7 @@ Rules:
888
882
  # Provided Actions
889
883
  **Communication**
890
884
  - AskUser(question=string, optionA?="title::description", ...MAX4). Any Ambiguity
891
- ${c?"- AskMain(question=string). Communicate with PARENT/MAIN AGENT. When clarification/decision is needed for a task":""}
885
+ ${d?"- AskMain(question=string). Communicate with PARENT/MAIN AGENT. When clarification/decision is needed for a task":""}
892
886
 
893
887
  **Web**
894
888
  - WebSearch(query=string, aiMode?=bool:false, limit?=int[3..10]). For unknown topics, time sensitive, fact checking
@@ -901,12 +895,12 @@ ${c?"- AskMain(question=string). Communicate with PARENT/MAIN AGENT. When clarif
901
895
  - ReadFile(path=string, startLine?=int, endLine?=int)
902
896
  - PatchFile(path=string, allowMultiple?=bool, searchContent1="string match OR ^LINE:start..end$", newContent1=string, ...MAX15). Small searchString. Line Anchors: ^LINE:...$ syntax, must for large blocks & escape sequences
903
897
  - WriteFile(path=string, content=string). Creates/Overwrites. File Exist? PatchFile > WriteFile
904
- - ${Se}. ${Ce}. Destructive command \u2192 Ask user`.trim(),Je=`=== START SYSTEM PROMPT ===
898
+ - ${be}. ${Ae}. Destructive command \u2192 Ask user`.trim(),Ye=`=== START SYSTEM PROMPT ===
905
899
  Identity: FluxFlow subagent helping the main Agent
906
900
  Your task: "${e}"
907
901
  CWD: ${process.cwd()}
908
902
 
909
- ${Me.trimEnd()}
903
+ ${_e.trimEnd()}
910
904
 
911
905
  -- THINKING GUIDANCE --
912
906
  Use minimal reasoning. Prefer simplest path; avoid branching; waste NO tokens overthinking. Just focus on task completion. Before actions, provide user facing summary of findings & decisions IN detail
@@ -914,30 +908,30 @@ Main focus: actions and task, not chatting
914
908
  On completion, provide a detailed summary in Tables/Markdown Format with file modified info. If any task failed report back in detail
915
909
 
916
910
  Current Time: ${f}
917
- === END SYSTEM PROMPT ===`,G=[{role:"user",text:`Complete this task: ${e}`}],b=0,ht="";for(;b<o;){let fe=await $i("subagent",u);if(!fe.allowed)throw new Error(fe.reason||`Budget Exhausted for Provider (${u?.aiProvider||"Subagent"})`);if(Et){if(n?.taskId&&typeof en<"u"){let H=en.find(_=>_.id===n.taskId);H&&(H.status="cancelled")}throw r&&r("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}if(n?.taskId&&typeof en<"u"){let H=en.find(_=>_.id===n.taskId);if(H&&H.status==="cancelled")throw r&&r("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}let q=G.map(H=>({role:H.role==="user"?"user":"model",parts:[{text:H.text}]}));r&&r(`[Subagent Turn ${b+1}]...`);let tn=["Fast","Low","Medium","High"],Vt=process.env.SUBAGENT_THINKING,cn=tn.includes(Vt)?Vt:"Low",Pn=(await yi(u,D,q,Je,cn)).text||"",dn=sa(Kt(Pn).trim());ht=dn,r&&r(`[Subagent Response]
918
- ${dn}
919
- `),G.push({role:"agent",text:dn});let yt=eo(dn);if(yt.length===0)break;let Yt=yt.filter(H=>H.toolName.toLowerCase()==="askmain"||H.toolName.toLowerCase()==="ask_main"),ue=!1,Be="";for(let H of yt){if(Et){if(n?.taskId&&typeof en<"u"){let S=en.find(L=>L.id===n.taskId);S&&(S.status="cancelled")}throw new Error("Subagent task was cancelled.")}if(n?.taskId&&typeof en<"u"){let S=en.find(L=>L.id===n.taskId);if(S&&S.status==="cancelled")throw new Error("Subagent task was cancelled.")}let _=H.toolName.toLowerCase();if(_==="askuser"&&(_="ask"),_==="askmain"||_==="ask_main"){if(ue)continue;ue=!0;let S="";if(Yt.length===1?S=j(Yt[0].args).question||Yt[0].args:S=Yt.map((L,ct)=>{let ze=j(L.args);return`Q${ct+1}: ${ze.question||L.args}`}).join(`
911
+ === END SYSTEM PROMPT ===`,B=[{role:"user",text:`Complete this task: ${e}`}],b=0,ut="";for(;b<o;){let fe=await Ni("subagent",u);if(!fe.allowed)throw new Error(fe.reason||`Budget Exhausted for Provider (${u?.aiProvider||"Subagent"})`);if(wt){if(n?.taskId&&typeof Qt<"u"){let U=Qt.find(v=>v.id===n.taskId);U&&(U.status="cancelled")}throw r&&r("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}if(n?.taskId&&typeof Qt<"u"){let U=Qt.find(v=>v.id===n.taskId);if(U&&U.status==="cancelled")throw r&&r("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}let Y=B.map(U=>({role:U.role==="user"?"user":"model",parts:[{text:U.text}]}));r&&r(`[Subagent Turn ${b+1}]...`);let Zt=["Fast","Low","Medium","High"],Gt=process.env.SUBAGENT_THINKING,an=Zt.includes(Gt)?Gt:"Low",_n=(await xi(u,N,Y,Ye,an)).text||"",ln=sa(Lt(_n).trim());ut=ln,r&&r(`[Subagent Response]
912
+ ${ln}
913
+ `),B.push({role:"agent",text:ln});let gt=Wn(ln);if(gt.length===0)break;let Ht=gt.filter(U=>U.toolName.toLowerCase()==="askmain"||U.toolName.toLowerCase()==="ask_main"),ue=!1,De="";for(let U of gt){if(wt){if(n?.taskId&&typeof Qt<"u"){let S=Qt.find(L=>L.id===n.taskId);S&&(S.status="cancelled")}throw new Error("Subagent task was cancelled.")}if(n?.taskId&&typeof Qt<"u"){let S=Qt.find(L=>L.id===n.taskId);if(S&&S.status==="cancelled")throw new Error("Subagent task was cancelled.")}let v=U.toolName.toLowerCase();if(v==="askuser"&&(v="ask"),v==="askmain"||v==="ask_main"){if(ue)continue;ue=!0;let S="";if(Ht.length===1?S=G(Ht[0].args).question||Ht[0].args:S=Ht.map((L,rt)=>{let Ke=G(L.args);return`Q${rt+1}: ${Ke.question||L.args}`}).join(`
920
914
  `),n.onAskMain){r&&r(`[Executing Tool] AskMain("${S}")...`);let L=await n.onAskMain(S);r&&r(`[Action Result]
921
915
  Answer from Main Agent: ${L}
922
- `),Be+=`[ACTION RESULT for AskMain]: Answer from Main Agent: ${L}
916
+ `),De+=`[ACTION RESULT for AskMain]: Answer from Main Agent: ${L}
923
917
 
924
- `,await Lt("toolSuccess")}else Be+=`[ACTION RESULT for AskMain]: ERROR: Main agent communication channel not available.
918
+ `,await _t("toolSuccess")}else De+=`[ACTION RESULT for AskMain]: ERROR: Main agent communication channel not available.
925
919
 
926
- `;continue}if(!(i?i.some(S=>S.toLowerCase()===_):!0)){let S=`ERROR: Tool [${H.toolName}] is not in the allowed tools list for this subagent.`;r&&r(`[Blocked Tool Call] ${H.toolName} - not allowed
927
- `),Be+=`${S}
920
+ `;continue}if(!(i?i.some(S=>S.toLowerCase()===v):!0)){let S=`ERROR: Tool [${U.toolName}] is not in the allowed tools list for this subagent.`;r&&r(`[Blocked Tool Call] ${U.toolName} - not allowed
921
+ `),De+=`${S}
928
922
 
929
- `;continue}if(_==="exec_command"||_==="execcommand"||_==="run"){let S=j(H.args).command||"",L=E(S);if(!L.allowed){let ct=`ERROR: [SECURITY RESTRICTION] Subagent execution blocked command: ${L.reason}`;r&&r(`[Blocked Command] ${S} - ${L.reason}
930
- `),Be+=`${ct}
923
+ `;continue}if(v==="exec_command"||v==="execcommand"||v==="run"){let S=G(U.args).command||"",L=E(S);if(!L.allowed){let rt=`ERROR: [SECURITY RESTRICTION] Subagent execution blocked command: ${L.reason}`;r&&r(`[Blocked Command] ${S} - ${L.reason}
924
+ `),De+=`${rt}
931
925
 
932
- `;continue}}let Oe="";if(_==="web_search"||_==="websearch")Oe=`\u2714 \x1B[95mSearched\x1B[0m: ${j(H.args).query||""}`;else if(_==="web_scrape"||_==="webscrape")Oe=`\u2714 \x1B[95mScraped\x1B[0m: ${j(H.args).url||""}`;else if(_==="search_keyword"||_==="searchkeyword"||_==="codesearch"||_==="code_search"){let S=j(H.args),L=S.keyword||"",ct=S.path||"";Oe=`${L?"\u2714":"\u2718"} \x1B[95mSearched\x1B[0m: ${L||"No Query"}${ct?` \u2192 ${ct.replaceAll("\\","/")}`:""}`}else if(_==="view_file"||_==="viewfile"||_==="readfile")Oe=`\u2714 \x1B[95mRead\x1B[0m: ${(j(H.args).path||"").replaceAll("\\","/")}`;else if(_==="find_file"||_==="findfile"){let S=j(H.args),L=S.basename||S.name||S.path||S.file||S.query||"";Oe=`${L?"\u2714":"\u2718"} \x1B[95mLocated\x1B[0m: ${L||"No Query"}`}else if(_==="list_files"||_==="read_folder"||_==="readfolder"){let S=j(H.args).path||null,L=j(H.args).recurse||0;Oe=`${S?"\u2714":"\u2718"} \x1B[95mBrowsed\x1B[0m: ${S?`${S.replaceAll("\\","/")}${L>0?`${S.endsWith("/")?`*${L}`:`/*${L}`}`:`${S.endsWith("/")?"":"/"}`}`:""}`}else if(_==="write_file"||_==="writefile"){let S=j(H.args).path||null;Oe=`${S?"\u2714":"\u2718"} \x1B[95mCreated\x1B[0m: ${S?`${S.replaceAll("\\","/")}`:"No File Changes"}`}else if(_==="update_file"||_==="updatefile"||_==="patchfile"||_==="patch_file"){let S=j(H.args),L=S.path||null,ze=Object.entries(S).some(([Ct,it])=>Ct.startsWith("searchContent")&&typeof it=="string"&&it.startsWith("^LINE:"))?"\u1361":":";Oe=`${L?"\u2714":"\u2718"} \x1B[95mEdited\x1B[0m${ze} ${L?`${L.replaceAll("\\","/")}`:"No File Changes"}`}else if(_==="exec_command"||_==="execcommand"||_==="run"){let S=j(H.args).command||null;Oe=`${S?"\u2714":"\u2718"} \x1B[95mExecuted\x1B[0m: ${S?S.slice(0,100)+(S.length>100?"...":""):"No Command"}`}else if(_==="file_map"||_==="filemap"){let S=j(H.args).path||"";Oe=`${S?"\u2714":"\u2718"} \x1B[95mIndexed\x1B[0m: ${S?`${S.replaceAll("\\","/")}`:"File Not Found"}`}else if(_==="await"){let{time:S}=j(H.args),L=parseFloat(S)||0;L<10&&(L=10),L>180&&(L=180),Oe=`\u2714 \x1B[95mAwaiting\x1B[0m \u2192 ${(ze=>{if(ze>=60){let Ct=Math.floor(ze/60),it=ze%60;return`${Ct}m${it>0?` ${it}s`:""}`}return`${ze}s`})(L)}`}else{let S=ms[_]||H.toolName,L=Zn(_,H.args);Oe=`\u2714 \x1B[95m${S}\x1B[0m${L?`: ${L}`:""}`}n.onVisualFeedback&&Oe&&n.onVisualFeedback(Oe),r&&r(`[Executing Tool] ${H.toolName}(${H.args})...`);try{let S=await Bo(H.toolName,H.args,{...n,mode:"Flux"});if(r&&r(`[Action Result]
926
+ `;continue}}let Me="";if(v==="web_search"||v==="websearch")Me=`\u2714 \x1B[95mSearched\x1B[0m: ${G(U.args).query||""}`;else if(v==="web_scrape"||v==="webscrape")Me=`\u2714 \x1B[95mScraped\x1B[0m: ${G(U.args).url||""}`;else if(v==="search_keyword"||v==="searchkeyword"||v==="codesearch"||v==="code_search"){let S=G(U.args),L=S.keyword||"",rt=S.path||"";Me=`${L?"\u2714":"\u2718"} \x1B[95mSearched\x1B[0m: ${L||"No Query"}${rt?` \u2192 ${rt.replaceAll("\\","/")}`:""}`}else if(v==="view_file"||v==="viewfile"||v==="readfile")Me=`\u2714 \x1B[95mRead\x1B[0m: ${(G(U.args).path||"").replaceAll("\\","/")}`;else if(v==="find_file"||v==="findfile"){let S=G(U.args),L=S.basename||S.name||S.path||S.file||S.query||"";Me=`${L?"\u2714":"\u2718"} \x1B[95mLocated\x1B[0m: ${L||"No Query"}`}else if(v==="list_files"||v==="read_folder"||v==="readfolder"){let S=G(U.args).path||null,L=G(U.args).recurse||0;Me=`${S?"\u2714":"\u2718"} \x1B[95mBrowsed\x1B[0m: ${S?`${S.replaceAll("\\","/")}${L>0?`${S.endsWith("/")?`*${L}`:`/*${L}`}`:`${S.endsWith("/")?"":"/"}`}`:""}`}else if(v==="write_file"||v==="writefile"){let S=G(U.args).path||null;Me=`${S?"\u2714":"\u2718"} \x1B[95mCreated\x1B[0m: ${S?`${S.replaceAll("\\","/")}`:"No File Changes"}`}else if(v==="update_file"||v==="updatefile"||v==="patchfile"||v==="patch_file"){let S=G(U.args),L=S.path||null,Ke=Object.entries(S).some(([St,tt])=>St.startsWith("searchContent")&&typeof tt=="string"&&tt.startsWith("^LINE:"))?"\u1361":":";Me=`${L?"\u2714":"\u2718"} \x1B[95mEdited\x1B[0m${Ke} ${L?`${L.replaceAll("\\","/")}`:"No File Changes"}`}else if(v==="exec_command"||v==="execcommand"||v==="run"){let S=G(U.args).command||null;Me=`${S?"\u2714":"\u2718"} \x1B[95mExecuted\x1B[0m: ${S?S.slice(0,100)+(S.length>100?"...":""):"No Command"}`}else if(v==="file_map"||v==="filemap"){let S=G(U.args).path||"";Me=`${S?"\u2714":"\u2718"} \x1B[95mIndexed\x1B[0m: ${S?`${S.replaceAll("\\","/")}`:"File Not Found"}`}else if(v==="await"){let{time:S}=G(U.args),L=parseFloat(S)||0;L<10&&(L=10),L>180&&(L=180),Me=`\u2714 \x1B[95mAwaiting\x1B[0m \u2192 ${(Ke=>{if(Ke>=60){let St=Math.floor(Ke/60),tt=Ke%60;return`${St}m${tt>0?` ${tt}s`:""}`}return`${Ke}s`})(L)}`}else{let S=ps[v]||U.toolName,L=Zn(v,U.args);Me=`\u2714 \x1B[95m${S}\x1B[0m${L?`: ${L}`:""}`}n.onVisualFeedback&&Me&&n.onVisualFeedback(Me),r&&r(`[Executing Tool] ${U.toolName}(${U.args})...`);try{let S=await Bo(U.toolName,U.args,{...n,mode:"Flux"});if(r&&r(`[Action Result]
933
927
  ${S}
934
- `),Be+=`[ACTION RESULT for ${H.toolName}]: ${S}
928
+ `),De+=`[ACTION RESULT for ${U.toolName}]: ${S}
935
929
 
936
- `,await Lt("toolSuccess"),_==="patchfile"||_==="update_file"||_==="updatefile"||_==="patch_file"){if(S){let L=S.split(`
937
- `),ct=0,ze=0,Ct=!1;for(let it of L){if(it.includes("[DIFF_START]")){Ct=!0;continue}if(it.includes("[DIFF_END]")){Ct=!1;continue}Ct&&(/^\+\s*\d+/.test(it)?ct++:/^\-\s*\d+/.test(it)&&ze++)}(ct>0||ze>0)&&(await At("linesAdded",ct),await At("linesRemoved",ze))}}else if((_==="writefile"||_==="write_file")&&S){let L=S.match(/- Stats: \[(\d+) lines/),ct=L?parseInt(L[1]):0,ze=0;if(S.includes("Old File contents:")){let Ct=!1;for(let it of S.split(`
938
- `)){if(it.includes("Old File contents:")){Ct=!0;continue}Ct&&(it.startsWith("- Content Preview:")||it.trim()===""&&!/^\s*\d+\s*\|/.test(it)?Ct=!1:/^\s*\d+\s*\|/.test(it)&&ze++)}}(ct>0||ze>0)&&(await At("linesAdded",ct),await At("linesRemoved",ze))}}catch(S){let L=`ERROR: Execution failed for [${H.toolName}]: ${S.message}`;r&&r(`[Tool Error] ${L}
939
- `),Be+=`${L}
930
+ `,await _t("toolSuccess"),v==="patchfile"||v==="update_file"||v==="updatefile"||v==="patch_file"){if(S){let L=S.split(`
931
+ `),rt=0,Ke=0,St=!1;for(let tt of L){if(tt.includes("[DIFF_START]")){St=!0;continue}if(tt.includes("[DIFF_END]")){St=!1;continue}St&&(/^\+\s*\d+/.test(tt)?rt++:/^\-\s*\d+/.test(tt)&&Ke++)}(rt>0||Ke>0)&&(await bt("linesAdded",rt),await bt("linesRemoved",Ke))}}else if((v==="writefile"||v==="write_file")&&S){let L=S.match(/- Stats: \[(\d+) lines/),rt=L?parseInt(L[1]):0,Ke=0;if(S.includes("Old File contents:")){let St=!1;for(let tt of S.split(`
932
+ `)){if(tt.includes("Old File contents:")){St=!0;continue}St&&(tt.startsWith("- Content Preview:")||tt.trim()===""&&!/^\s*\d+\s*\|/.test(tt)?St=!1:/^\s*\d+\s*\|/.test(tt)&&Ke++)}}(rt>0||Ke>0)&&(await bt("linesAdded",rt),await bt("linesRemoved",Ke))}}catch(S){let L=`ERROR: Execution failed for [${U.toolName}]: ${S.message}`;r&&r(`[Tool Error] ${L}
933
+ `),De+=`${L}
940
934
 
941
- `,await Lt("toolFailure")}}let Pe="";if(n?.taskId&&typeof en<"u"){let H=en.find(_=>_.id===n.taskId);if(H&&H.pendingSteerMessages&&H.pendingSteerMessages.length>0){let _=[...H.pendingSteerMessages];H.pendingSteerMessages=[];for(let Qe of _)Pe+=`
935
+ `,await _t("toolFailure")}}let Ie="";if(n?.taskId&&typeof Qt<"u"){let U=Qt.find(v=>v.id===n.taskId);if(U&&U.pendingSteerMessages&&U.pendingSteerMessages.length>0){let v=[...U.pendingSteerMessages];U.pendingSteerMessages=[];for(let ze of v)Ie+=`
942
936
 
943
- [STEERING INSTRUCTION FROM MAIN AGENT]: ${Qe}`,r&&r(`[Subagent Steered] ${Qe}`)}}let Y=(Be.trim()+Pe).trim();G.push({role:"user",text:Y}),b++}return ht};export{mo as a,pi as b,Wc as c,Gc as d,dc as e,fc as f,go as g,uc as h,Rc as i,_c as j,cl as k,Md as l,dl as m,fl as n,gs as o,Kt as p,hi as q,sa as r,pl as s,Pd as t,Od as u,hs as v,Ld as w,ys as x,yl as y,eo as z,$d as A,yi as B,Nd as C,Dd as D,Fd as E,Bd as F};
937
+ [STEERING INSTRUCTION FROM MAIN AGENT]: ${ze}`,r&&r(`[Subagent Steered] ${ze}`)}}let j=(De.trim()+Ie).trim();B.push({role:"user",text:j}),b++}return ut};export{go as a,pi as b,Gc as c,Hc as d,fc as e,uc as f,uo as g,gc as h,vc as i,_c as j,dl as k,Pd as l,fl as m,ul as n,ms as o,Lt as p,hi as q,sa as r,hl as s,Od as t,Ld as u,ys as v,$d as w,yi as x,xl as y,Wn as z,Nd as A,xi as B,Dd as C,Fd as D,Bd as E,Ud as F};