fluxflow-cli 4.34.0 → 4.34.1

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 hs}from"./chunk-JS5ZIGFR.js";import{a as Gt}from"./chunk-56EJGQU3.js";import{a as ho}from"./chunk-7SFAWGE2.js";import{a as gs,c as ms}from"./chunk-KAL5XSAQ.js";import{a as wi,g as ps}from"./chunk-VYTQ6J56.js";import{a as ys}from"./chunk-RZTZPIC5.js";import{c as xi,g as bi,h as fs,i as us}from"./chunk-4MDSKJGX.js";import{a as No}from"./chunk-FQBBOFNP.js";import{a as W}from"./chunk-Y5JU726N.js";import{b as pi}from"./chunk-KHCAQOSP.js";import{e as mo,k as Et,m as gt,o as yi,p as ds}from"./chunk-X6YW3TVC.js";import{a as go}from"./chunk-KZTDLEUL.js";import{k as ot,l as $o,o as re}from"./chunk-63V6P5DU.js";import{c as Rt,d as Qn,e as cs}from"./chunk-L3W2X74K.js";import{a as In,b as ls,d as qt,e as Po,k as Hn,l as Lo,m as mi,r as hi,w as fo,x as uo}from"./chunk-DSVLWYIT.js";import{GoogleGenAI as Lr,ThinkingLevel as Ge,HarmBlockThreshold as Pn,HarmCategory as Ln}from"@google/genai";var xs=(e=!0,n=!0)=>`
1
+ import{a as hs}from"./chunk-JS5ZIGFR.js";import{a as Gt}from"./chunk-56EJGQU3.js";import{a as ho}from"./chunk-7SFAWGE2.js";import{a as gs,c as ms}from"./chunk-KAL5XSAQ.js";import{a as Si,g as ps}from"./chunk-VYTQ6J56.js";import{a as ys}from"./chunk-RZTZPIC5.js";import{c as bi,g as wi,h as fs,i as us}from"./chunk-4MDSKJGX.js";import{a as Bo}from"./chunk-FQBBOFNP.js";import{a as G}from"./chunk-Y5JU726N.js";import{b as yi}from"./chunk-KHCAQOSP.js";import{e as mo,k as Et,m as gt,o as xi,p as ds}from"./chunk-X6YW3TVC.js";import{a as go}from"./chunk-KZTDLEUL.js";import{k as ot,l as Fo,o as re}from"./chunk-63V6P5DU.js";import{c as Rt,d as Qn,e as cs}from"./chunk-L3W2X74K.js";import{a as Mn,b as ls,d as kn,e as No,k as Hn,l as Do,m as hi,r as pi,w as fo,x as uo}from"./chunk-DSVLWYIT.js";import{GoogleGenAI as Lr,ThinkingLevel as Ge,HarmBlockThreshold as Pn,HarmCategory as Ln}from"@google/genai";var xs=(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 Do={xHigh:"Use minimal reasoning. Prefer simplest path; avoid branching; waste NO tokens overthinking",High:"Use minimal reasoning. Prefer simplest path; avoid branching; waste NO tokens overthinking",Medium:"Use minimal reasoning. Prefer simplest path; avoid branching; waste NO tokens overthinking",Minimal:"Use minimal reasoning. Prefer simplest path; avoid branching; waste NO tokens overthinking",Off:"NO thinking. Immediate response. Verify imports, tool results & system stability"};import on from"fs";import ln from"path";import sa from"os";import an from"fs";import Mn from"path";import Ms from"fs";import Si from"path";import{execSync as Os}from"child_process";import{fileURLToPath as ia}from"url";var bs=`# FluxFlow CLI Startup & Flags Reference
28
+ - Must not ignore any tool calls in given context of chat between user & agent`:""}`.trim();var Uo={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 nn from"fs";import ln from"path";import sa from"os";import rn from"fs";import On from"path";import Ms from"fs";import Ti from"path";import{execSync as Os}from"child_process";import{fileURLToPath as ia}from"url";var bs=`# FluxFlow CLI Startup & Flags Reference
29
29
 
30
30
  Launch command syntax:
31
31
  fluxflow [options]
@@ -439,14 +439,14 @@ Instruction for this model ID across all providers.
439
439
 
440
440
  * On-Demand Reference System:
441
441
  * Reference: Offload deep/contexual specs to **/{SKILL.md,skill-reference-folder/*.md} & reference in SKILL.md. Saves tokens
442
- `;var Fo="v4";try{let e=Si.dirname(ia(import.meta.url)),n=[Si.join(e,"../../package.json"),Si.join(e,"../package.json")],t=!1;for(let i of n)if(Ms.existsSync(i)){let o=JSON.parse(Ms.readFileSync(i,"utf8"));if(o.version){Fo=o.version,t=!0;break}}if(!t)try{let i=Os("fluxflow -v",{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"],timeout:2e3}).trim();i&&(i.startsWith("v")||/^\d+\.\d+/.test(i))&&(Fo=i,t=!0)}catch{}if(!t)try{let i=Os("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&&(Fo=o.version)}catch{}}catch{}var Ti={"SKILL.md":`---
442
+ `;var Wo="v4";try{let e=Ti.dirname(ia(import.meta.url)),n=[Ti.join(e,"../../package.json"),Ti.join(e,"../package.json")],t=!1;for(let i of n)if(Ms.existsSync(i)){let o=JSON.parse(Ms.readFileSync(i,"utf8"));if(o.version){Wo=o.version,t=!0;break}}if(!t)try{let i=Os("fluxflow -v",{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"],timeout:2e3}).trim();i&&(i.startsWith("v")||/^\d+\.\d+/.test(i))&&(Wo=i,t=!0)}catch{}if(!t)try{let i=Os("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&&(Wo=o.version)}catch{}}catch{}var ki={"SKILL.md":`---
443
443
  name: fluxflow
444
444
  description: System Generated Documentation. Read this if asked anything regarding FluxFlow Harness
445
445
  ---
446
446
 
447
447
  # FluxFlow, by Kushal Roy Chowdhury
448
448
  Open Source Terminal AI Assistant
449
- App Version: ${Fo}. Check Updates: fluxflow --update check. Update: fluxflow --update
449
+ App Version: ${Wo}. Check Updates: fluxflow --update check. Update: fluxflow --update
450
450
  GitHub: https://github.com/KushalRoyChowdhury/fluxflow-cli
451
451
  Public Docs: https://fluxflow-cli.onrender.com
452
452
 
@@ -466,24 +466,24 @@ Public Docs: https://fluxflow-cli.onrender.com
466
466
 
467
467
  Default Context Length: 256k Tokens. Can be changed via ENV/In-app Settings \u2192 references/{SETTINGS,ENV}.md
468
468
 
469
- Docs missing required info? Say you are not sure enough to answer. Dont give wrong info`,"references/MODES.md":vs,"references/PROVIDERS.md":_s,"references/PLUGINS.md":Is,"references/STARTUP.md":bs,"references/ENV.md":ws,"references/COMMANDS.md":Ss,"references/SETTINGS.md":Ts,"references/TOOLS.md":ks,"references/ARCHITECTURE.md":As,"references/SUB_AGENTS.md":Cs,"references/SECURITY.md":Rs,"references/IDE.md":Es};var Ps=()=>{try{let e=Mn.join(In,"skills","fluxflow"),n=Mn.join(e,"references");if(process.env.NO_DEV==="true"||process.env.NO_DEV==="1"||process.env.NO_DEV===!0||process.env.NO_INS==="true"||process.env.NO_INS==="1"||process.env.NO_INS===!0||!1){an.existsSync(e)&&an.rmSync(e,{recursive:!0,force:!0});return}let i=new Set(Object.keys(Ti).map(o=>Mn.normalize(o)));for(let[o,r]of Object.entries(Ti)){let c=Mn.join(e,o),a=Mn.dirname(c);an.existsSync(a)||an.mkdirSync(a,{recursive:!0});let h=r.trim()+`
470
- `,g=null;an.existsSync(c)&&(g=an.readFileSync(c,"utf8")),g!==h&&an.writeFileSync(c,h,"utf8")}if(an.existsSync(n)){let o=an.readdirSync(n);for(let r of o){let c=Mn.normalize(Mn.join("references",r));if(!i.has(c)){let a=Mn.join(n,r);try{an.rmSync(a,{recursive:!0,force:!0})}catch{}}}}}catch{}};var bo=(e,n)=>{try{if(!on.existsSync(e))return null;let t=Array.isArray(n)?n.map(o=>o.toLowerCase()):[n.toLowerCase()],i=on.readdirSync(e);for(let o of t){let r=i.find(c=>c.toLowerCase()===o);if(r){let c=ln.join(e,r);if(on.statSync(c).isFile())return c}}}catch{}return null},vi=(e,n)=>{let t=bo(e,n);if(t)try{return on.readFileSync(t,"utf8")}catch{}return""},Ls=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"]),_i=(e=process.cwd(),n=0,t=8)=>{let i=[];if(n>t)return i;try{if(!on.existsSync(e))return i;let o=on.readdirSync(e,{withFileTypes:!0});for(let r of o){let c=r.name,a=ln.join(e,c);if(r.isDirectory())!Ls.has(c)&&!Ls.has(c.toLowerCase())&&i.push(..._i(a,n+1,t));else if(r.isFile()){let h=c.toLowerCase();(h==="agents.md"||h==="agent.md")&&i.push(a)}}}catch{}return i},$s=(e,n=2)=>{if(!e)return"";let t=" ".repeat(n);return e.split(/\r?\n/).map(i=>t+i).join(`
471
- `)},Us=()=>bo(In,["agents.md","agent.md"]),Ws=()=>bo(process.cwd(),["agents.md","agent.md"]),Gs=()=>bo(In,["fluxflow.md"]),Hs=()=>bo(process.cwd(),["fluxflow.md"]),Bo=Us(),Ri=Ws(),On=_i(),Uo=Gs(),Wo=Hs(),Ns=null,Ei="",js=!1,ra=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&&(Ei=o[1].trim(),process.env.NO_INS=!0),/<><\s*NO_INS/.test(t)&&(js=!0),i.trim()},aa=()=>(Bo=Us(),Bo?vi(In,["agents.md","agent.md"]).trim():""),la=()=>{if(On=_i(),Ri=Ws(),!On||On.length===0)return"";let e=process.cwd(),n=[...On].sort((i,o)=>{let r=ln.relative(e,i).replace(/\\/g,"/"),c=ln.relative(e,o).replace(/\\/g,"/"),a=!r.includes("/"),h=!c.includes("/");return a&&!h?-1:!a&&h?1:r.localeCompare(c)}),t=[];for(let i of n)try{let o=on.readFileSync(i,"utf8").trim();if(!o)continue;let r=ln.relative(e,i).replace(/\\/g,"/");if(!r.includes("/"))t.push($s(o,2));else{let a=ln.dirname(r)+"/:";t.push(`${a}
472
- ${$s(o,2)}`)}}catch{}return t.join(`
469
+ Docs missing required info? Say you are not sure enough to answer. Dont give wrong info`,"references/MODES.md":vs,"references/PROVIDERS.md":_s,"references/PLUGINS.md":Is,"references/STARTUP.md":bs,"references/ENV.md":ws,"references/COMMANDS.md":Ss,"references/SETTINGS.md":Ts,"references/TOOLS.md":ks,"references/ARCHITECTURE.md":As,"references/SUB_AGENTS.md":Cs,"references/SECURITY.md":Rs,"references/IDE.md":Es};var Ps=()=>{try{let e=On.join(Mn,"skills","fluxflow"),n=On.join(e,"references");if(process.env.NO_DEV==="true"||process.env.NO_DEV==="1"||process.env.NO_DEV===!0||process.env.NO_INS==="true"||process.env.NO_INS==="1"||process.env.NO_INS===!0||!1){rn.existsSync(e)&&rn.rmSync(e,{recursive:!0,force:!0});return}let i=new Set(Object.keys(ki).map(o=>On.normalize(o)));for(let[o,r]of Object.entries(ki)){let c=On.join(e,o),a=On.dirname(c);rn.existsSync(a)||rn.mkdirSync(a,{recursive:!0});let g=r.trim()+`
470
+ `,m=null;rn.existsSync(c)&&(m=rn.readFileSync(c,"utf8")),m!==g&&rn.writeFileSync(c,g,"utf8")}if(rn.existsSync(n)){let o=rn.readdirSync(n);for(let r of o){let c=On.normalize(On.join("references",r));if(!i.has(c)){let a=On.join(n,r);try{rn.rmSync(a,{recursive:!0,force:!0})}catch{}}}}}catch{}};var To=(e,n)=>{try{if(!nn.existsSync(e))return null;let t=Array.isArray(n)?n.map(o=>o.toLowerCase()):[n.toLowerCase()],i=nn.readdirSync(e);for(let o of t){let r=i.find(c=>c.toLowerCase()===o);if(r){let c=ln.join(e,r);if(nn.statSync(c).isFile())return c}}}catch{}return null},vi=(e,n)=>{let t=To(e,n);if(t)try{return nn.readFileSync(t,"utf8")}catch{}return""},Ls=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"]),_i=(e=process.cwd(),n=0,t=8)=>{let i=[];if(n>t)return i;try{if(!nn.existsSync(e))return i;let o=nn.readdirSync(e,{withFileTypes:!0});for(let r of o){let c=r.name,a=ln.join(e,c);if(r.isDirectory())!Ls.has(c)&&!Ls.has(c.toLowerCase())&&i.push(..._i(a,n+1,t));else if(r.isFile()){let g=c.toLowerCase();(g==="agents.md"||g==="agent.md")&&i.push(a)}}}catch{}return i},$s=(e,n=2)=>{if(!e)return"";let t=" ".repeat(n);return e.split(/\r?\n/).map(i=>t+i).join(`
471
+ `)},Us=()=>To(Mn,["agents.md","agent.md"]),Ws=()=>To(process.cwd(),["agents.md","agent.md"]),Gs=()=>To(Mn,["fluxflow.md"]),Hs=()=>To(process.cwd(),["fluxflow.md"]),yo=Us(),Go=Ws(),an=_i(),xo=Gs(),bo=Hs(),Ns=null,Ei="",js=!1,ra=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&&(Ei=o[1].trim(),process.env.NO_INS=!0),/<><\s*NO_INS/.test(t)&&(js=!0),i.trim()},aa=()=>{yo=Us();let e=yo?vi(Mn,["agents.md","agent.md"]).trim():"";return e.length===0?(yo=null,""):e},la=()=>{if(an=_i(),Go=Ws(),!an||an.length===0)return"";let e=process.cwd(),n=[...an].sort((o,r)=>{let c=ln.relative(e,o).replace(/\\/g,"/"),a=ln.relative(e,r).replace(/\\/g,"/"),g=!c.includes("/"),m=!a.includes("/");return g&&!m?-1:!g&&m?1:c.localeCompare(a)}),t=[],i=[];for(let o of n)try{let r=nn.readFileSync(o,"utf8").trim();if(!r||r.length===0)continue;t.push(o);let c=ln.relative(e,o).replace(/\\/g,"/");if(!c.includes("/"))i.push($s(r,2));else{let g=ln.dirname(c)+"/:";i.push(`${g}
472
+ ${$s(r,2)}`)}}catch{}return an=t,an.length===0&&(Go=null),i.join(`
473
473
 
474
- `).trim()},Ii=()=>{Uo=Gs();let e=Uo?vi(In,["fluxflow.md"]).trim():"";return ra(e)},Mi=()=>(Wo=Hs(),Wo?vi(process.cwd(),["fluxflow.md"]).trim():""),Oi=aa(),Go=la(),yo=Ii(),xo=Mi(),Ds=(e,n="",t="")=>{if(!e)return"";let i=t.toLowerCase().trim(),o=n.toLowerCase().trim(),r=ln.posix.basename(o),c=i&&o?`${i}::${o}`:"",a=i&&r?`${i}::${r}`:"",h=y=>!y||!o?!1:y===o||y===r||y===c||y===a,g=[];return e.replace(/<start_provider_([^>\r\n]+)>([\s\S]*?)<end_provider_([^>\r\n]+)>/gi,(y,m,f,s)=>{if(i&&m.trim().toLowerCase()===s.trim().toLowerCase()&&m.trim().toLowerCase()===i){let k=f.replace(/<start_model_([^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n]+)>/gi,(he,x,I,G)=>{if(x.trim().toLowerCase()===G.trim().toLowerCase()){let q=x.trim().toLowerCase();if(h(q)){let D=I.trim();D&&g.push(D)}}return""}).trim();k&&g.push(k)}return""}),e.replace(/<start_model_([^>\r\n]+::[^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n]+::[^>\r\n]+)>/gi,(y,m,f,s)=>{if(m.trim().toLowerCase()===s.trim().toLowerCase()){let u=m.trim().toLowerCase();if(c&&(u===c||a&&u===a)){let k=f.trim();k&&g.push(k)}}return""}),e.replace(/<start_model_([^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n]+)>/gi,(y,m,f,s)=>{if(m.includes("::"))return"";if(m.trim().toLowerCase()===s.trim().toLowerCase()){let u=m.trim().toLowerCase();if(o&&(u===o||u===r)){let k=f.trim();k&&g.push(k)}}return""}),g.join(`
474
+ `).trim()},Ii=()=>{xo=Gs();let e=xo?vi(Mn,["fluxflow.md"]).trim():"",n=ra(e)?.trim()||"";return n.length===0?(xo=null,""):n},Mi=()=>{bo=Hs();let e=bo?vi(process.cwd(),["fluxflow.md"]).trim():"";return e.length===0?(bo=null,""):e},Oi=aa(),Ho=la(),wo=Ii(),So=Mi(),Ds=(e,n="",t="")=>{if(!e)return"";let i=t.toLowerCase().trim(),o=n.toLowerCase().trim(),r=ln.posix.basename(o),c=i&&o?`${i}::${o}`:"",a=i&&r?`${i}::${r}`:"",g=y=>!y||!o?!1:y===o||y===r||y===c||y===a,m=[];return e.replace(/<start_provider_([^>\r\n]+)>([\s\S]*?)<end_provider_([^>\r\n]+)>/gi,(y,h,f,s)=>{if(i&&h.trim().toLowerCase()===s.trim().toLowerCase()&&h.trim().toLowerCase()===i){let k=f.replace(/<start_model_([^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n]+)>/gi,(he,x,I,H)=>{if(x.trim().toLowerCase()===H.trim().toLowerCase()){let q=x.trim().toLowerCase();if(g(q)){let D=I.trim();D&&m.push(D)}}return""}).trim();k&&m.push(k)}return""}),e.replace(/<start_model_([^>\r\n]+::[^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n]+::[^>\r\n]+)>/gi,(y,h,f,s)=>{if(h.trim().toLowerCase()===s.trim().toLowerCase()){let u=h.trim().toLowerCase();if(c&&(u===c||a&&u===a)){let k=f.trim();k&&m.push(k)}}return""}),e.replace(/<start_model_([^>\r\n]+)>([\s\S]*?)<end_model_([^>\r\n]+)>/gi,(y,h,f,s)=>{if(h.includes("::"))return"";if(h.trim().toLowerCase()===s.trim().toLowerCase()){let u=h.trim().toLowerCase();if(o&&(u===o||u===r)){let k=f.trim();k&&m.push(k)}}return""}),m.join(`
475
475
 
476
- `).trim()},ca=(e="",n="")=>{let t=`${e||""}::${n||""}`.toLowerCase().trim();Ns!==t&&(Ns=t,yo=Ii(),xo=Mi())};Ps();var da=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},fa=e=>{let n=[];if(!e||!on.existsSync(e))return n;let t=(i,o=0)=>{if(!(o>5))try{let r=on.readdirSync(i,{withFileTypes:!0});for(let c of r){let a=ln.join(i,c.name),h=c.name.toLowerCase();c.isFile()?h==="skill.md"&&n.push(a):c.isDirectory()&&(o===0?(h==="skills"||h===".skills"||h==="skill"||h===".skill")&&t(a,o+1):t(a,o+1))}}catch{}};return t(e,0),n},Vs=e=>{let n=fa(e),t=[];for(let i of n)try{let o=on.readFileSync(i,"utf8"),r=da(o);r&&t.push({...r,filePath:i})}catch{}return t},Ks=e=>!e||e.length===0?"":e.map(n=>`- ${n.name}: ${n.description}`).join(`
477
- `),Ys=Vs(In),zs=Vs(process.cwd()),ki=Ks(Ys),Ai=Ks(zs),qs=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"},Xs=()=>(Ys||[]).filter(e=>!qs(e)),Js=()=>(zs||[]).filter(e=>!qs(e)),jl=(Oi?1:0)+(On?.length||(Go?1:0))+(yo?1:0)+(xo?1:0)+Xs().length+Js().length,Ci=(e,n="Project")=>{if(!e)return"";let t=e.replace(/\\/g,"/");if(n==="Global"){let o=sa.homedir().replace(/\\/g,"/");return t.toLowerCase().startsWith(o.toLowerCase())?"~"+t.slice(o.length):t}let i=ln.relative(process.cwd(),e).replace(/\\/g,"/");return i.startsWith(".")?i:`./${i}`},Vl=()=>{yo=Ii(),xo=Mi();let e=[];Bo&&Oi.length>0&&e.push({scope:"Global",path:Bo}),On&&On.length>0&&Go.length>0?On.forEach(r=>{e.push({scope:"Project",path:r})}):Ri&&Go.length>0&&e.push({scope:"Project",path:Ri}),Uo&&yo.length>0&&e.push({scope:"Global",path:Uo}),Wo&&xo.length>0&&e.push({scope:"Project",path:Wo});let n=Xs(),t=Js(),i=e.length+n.length+t.length;if(i===0)return`\u2726 Loaded Files & Instructions
476
+ `).trim()},ca=(e="",n="")=>{let t=`${e||""}::${n||""}`.toLowerCase().trim();Ns!==t&&(Ns=t,wo=Ii(),So=Mi())};Ps();var da=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},fa=e=>{let n=[];if(!e||!nn.existsSync(e))return n;let t=(i,o=0)=>{if(!(o>5))try{let r=nn.readdirSync(i,{withFileTypes:!0});for(let c of r){let a=ln.join(i,c.name),g=c.name.toLowerCase();c.isFile()?g==="skill.md"&&n.push(a):c.isDirectory()&&(o===0?(g==="skills"||g===".skills"||g==="skill"||g===".skill")&&t(a,o+1):t(a,o+1))}}catch{}};return t(e,0),n},Vs=e=>{let n=fa(e),t=[];for(let i of n)try{let o=nn.readFileSync(i,"utf8"),r=da(o);r&&t.push({...r,filePath:i})}catch{}return t},Ks=e=>!e||e.length===0?"":e.map(n=>`- ${n.name}: ${n.description}`).join(`
477
+ `),Ys=Vs(Mn),zs=Vs(process.cwd()),Ai=Ks(Ys),Ci=Ks(zs),qs=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"},Xs=()=>(Ys||[]).filter(e=>!qs(e)),Js=()=>(zs||[]).filter(e=>!qs(e)),jl=(Oi?.length>0?1:0)+(Ho?.length>0?an.length:0)+(wo?.length>0?1:0)+(So?.length>0?1:0)+Xs().length+Js().length,Ri=(e,n="Project")=>{if(!e)return"";let t=e.replace(/\\/g,"/");if(n==="Global"){let o=sa.homedir().replace(/\\/g,"/");return t.toLowerCase().startsWith(o.toLowerCase())?"~"+t.slice(o.length):t}let i=ln.relative(process.cwd(),e).replace(/\\/g,"/");return i.startsWith(".")?i:`./${i}`},Vl=()=>{wo=Ii(),So=Mi();let e=[];yo&&Oi.length>0&&e.push({scope:"Global",path:yo}),an&&an.length>0&&Ho.length>0?an.forEach(r=>{e.push({scope:"Project",path:r})}):Go&&Ho.length>0&&e.push({scope:"Project",path:Go}),xo&&wo.length>0&&e.push({scope:"Global",path:xo}),bo&&So.length>0&&e.push({scope:"Project",path:bo});let n=Xs(),t=Js(),i=e.length+n.length+t.length;if(i===0)return`\u2726 Loaded Files & Instructions
478
478
  \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m No instruction or skill files are currently loaded.
479
479
  \u2800`;let o=[];return o.push(`\u2726 Loaded Files & Instructions (${i} ${i===1?"file":"files"} active)`),e.length>0&&(o.push(`
480
- \x1B[1mInstructions:\x1B[22m`),e.forEach(r=>{o.push(` \u2022 [${r.scope}] ${Ci(r.path,r.scope)}`)})),(n?.length>0||t?.length>0)&&(o.push(`
481
- \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 ${Ci(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 ${Ci(r.filePath,"Project")}\x1B[22m`)})),o.push("\u2800"),o.join(`
480
+ \x1B[1mInstructions:\x1B[22m`),e.forEach(r=>{o.push(` \u2022 [${r.scope}] ${Ri(r.path,r.scope)}`)})),(n?.length>0||t?.length>0)&&(o.push(`
481
+ \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 ${Ri(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 ${Ri(r.filePath,"Project")}\x1B[22m`)})),o.push("\u2800"),o.join(`
482
482
  `)},Qs=!1;(async()=>{try{let e=await go();if(Number(e?.display)===1){let{default:n}=await import("screenshot-desktop"),t=await n.listDisplays();t&&t.length>1&&(Qs=!0)}}catch{}})();var Fs=null,po=null,Bs=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",Kl=process.env.NO_DEV||!1,ua=(e,n)=>{if(!n)return"";if(e!==Fs||po===null){Fs=e;try{let t=Rt(Hn,[]);Array.isArray(t)&&t.length>0?po=t.map(i=>`- ${i.memory}`).join(`
483
- `):po=""}catch(t){po="",on.appendFileSync(`${qt}/memory/error.txt`,`${t.message}
483
+ `):po=""}catch(t){po="",nn.appendFileSync(`${kn}/memory/error.txt`,`${t.message}
484
484
  -------------------------------------------------
485
485
 
486
- `)}}return po};var Zs=(e,n,t,i,o=!0,r=!1,c="Google",a=!1,h,g,y=!1,m="")=>{let f=!1;process.env.forcedReasoning&&(f=!0);let s="";if(!h&&c==="Google"){let pe=n;n==="Fast"&&(pe="Off"),n==="Low"&&(pe="Minimal"),n==="Standard"&&(pe="Medium"),(n==="xHigh"||n==="Max")&&(pe="xHigh"),s=Do[pe]||Do.Medium}(h||c!=="Google")&&(s=Do.xHigh,n==="Fast"?s=`No thinking. Immediate response
486
+ `)}}return po};var Zs=(e,n,t,i,o=!0,r=!1,c="Google",a=!1,g,m,y=!1,h="")=>{let f=!1;process.env.forcedReasoning&&(f=!0);let s="";if(!g&&c==="Google"){let pe=n;n==="Fast"&&(pe="Off"),n==="Low"&&(pe="Minimal"),n==="Standard"&&(pe="Medium"),(n==="xHigh"||n==="Max")&&(pe="xHigh"),s=Uo[pe]||Uo.Medium}(g||c!=="Google")&&(s=Uo.xHigh,n==="Fast"?s=`No thinking. Immediate response
487
487
  Verify imports, tool results & system stability`:n.toLowerCase()==="max"&&(s=`Effort: Max
488
488
  Plan step by step`));let u=e.instructions&&e.instructions?.length>0?`User Preferences: ${e.instructions}
489
489
 
@@ -491,12 +491,12 @@ Plan step by step`));let u=e.instructions&&e.instructions?.length>0?`User Prefer
491
491
  ${u.length?"":`
492
492
  `}`:"",he=e.name&&e.name?.length>0?`User Name: ${e.name}
493
493
  ${k.length||u.length?"":`
494
- `}`:"",x=process.cwd(),I=ua(g,o),G=I?.length>0?`--- Saved Memories ---
494
+ `}`:"",x=process.cwd(),I=ua(m,o),H=I?.length>0?`--- Saved Memories ---
495
495
  ${I}
496
496
 
497
- `:"";ca(c,m);let q=Ds(yo,m,c).trim(),A=[Oi,q].filter(pe=>pe&&pe.length>0).join(`
497
+ `:"";ca(c,h);let q=Ds(wo,h,c).trim(),A=[Oi,q].filter(pe=>pe&&pe.length>0).join(`
498
498
 
499
- `).trim(),ge=Ds(xo,m,c).trim(),Me=[Go,ge].filter(pe=>pe&&pe.length>0).join(`
499
+ `).trim(),ge=Ds(So,h,c).trim(),Me=[Ho,ge].filter(pe=>pe&&pe.length>0).join(`
500
500
 
501
501
  `).trim(),ye=A.length>0||Me.length>0?`--- Additional Instructions ---
502
502
  ${A.length>0?`-- Global --
@@ -505,17 +505,17 @@ ${A}`:""}${Me.length>0?`${A.length>0?`
505
505
  `:""}-- Project --
506
506
  ${Me}`:""}
507
507
 
508
- `:"",T=(()=>{let pe=process.cwd().toLowerCase();if(process.platform==="win32"){let Jt=process.env.SystemRoot?.toLowerCase()||"c:\\windows",S=process.env.ProgramFiles?.toLowerCase()||"c:\\program files",R=process.env["ProgramFiles(x86)"]?.toLowerCase()||"c:\\program files (x86)";return pe.startsWith(Jt)||pe.startsWith(S)||pe.startsWith(R)}else return pe==="/"||["/bin","/sbin","/etc","/usr","/var","/root"].some(S=>pe.startsWith(S))})(),b=new Date,rt=b.getFullYear(),Oe=b.toLocaleString("en-US",{month:"short"}).toUpperCase(),jt=String(b.getDate()).padStart(2,"0"),cn=`${rt}-${Oe}-${jt}`,$t=!!i?.autoExcludeMetadata,Xt=process.env.I_HAVE_TOO_MUCH_MONEY==="true"||process.env.I_HAVE_TOO_MUCH_MONEY===!0||!1,dn=(m||"").replace(/^.*::/,"").split(":")[0].replace(/\/free$/,"").trim(),fn=ln.basename(dn).replace(/-free$/,"").replace(/_free$/,"").replace(/^free_/,"").replaceAll("-"," ").replaceAll("_"," ").replace(/\b\w/g,pe=>pe.toUpperCase().trim()),Nt=process.env.NO_DEV==="true"||process.env.NO_DEV==="1"||process.env.NO_DEV===!0||!1;return`${Xt?`${" ".repeat(Math.floor(Math.random()*4)+1)}`:""}=== SYSTEM PROMPT ===
508
+ `:"",T=(()=>{let pe=process.cwd().toLowerCase();if(process.platform==="win32"){let Xt=process.env.SystemRoot?.toLowerCase()||"c:\\windows",S=process.env.ProgramFiles?.toLowerCase()||"c:\\program files",R=process.env["ProgramFiles(x86)"]?.toLowerCase()||"c:\\program files (x86)";return pe.startsWith(Xt)||pe.startsWith(S)||pe.startsWith(R)}else return pe==="/"||["/bin","/sbin","/etc","/usr","/var","/root"].some(S=>pe.startsWith(S))})(),b=new Date,rt=b.getFullYear(),Oe=b.toLocaleString("en-US",{month:"short"}).toUpperCase(),jt=String(b.getDate()).padStart(2,"0"),cn=`${rt}-${Oe}-${jt}`,$t=!!i?.autoExcludeMetadata,qt=process.env.I_HAVE_TOO_MUCH_MONEY==="true"||process.env.I_HAVE_TOO_MUCH_MONEY===!0||!1,dn=(h||"").replace(/^.*::/,"").split(":")[0].replace(/\/free$/,"").trim(),fn=ln.basename(dn).replace(/-free$/,"").replace(/_free$/,"").replace(/^free_/,"").replaceAll("-"," ").replaceAll("_"," ").replace(/\b\w/g,pe=>pe.toUpperCase().trim()),Nt=process.env.NO_DEV==="true"||process.env.NO_DEV==="1"||process.env.NO_DEV===!0||!1;return`${qt?`${" ".repeat(Math.floor(Math.random()*4)+1)}`:""}=== SYSTEM PROMPT ===
509
509
  ${`Identity: ${Ei.length>1?Ei.trim():"Flux Flow. Sassy, CLI Assistant"}
510
510
  ${js?"":`${t==="Flux"?"":t==="Flow"?"Concise, Humorous, Sarcastic":t==="ICU"?"Computer Use Capabilities. Screenshot as ground truth, analyze grid ids overlapping/close to target, keyboard shortcuts > mouse clicks":"Computer Use & Workspace Capabilities. Screenshot as ground truth, analyze grid ids overlapping/close to target, keyboard shortcuts > mouse clicks. Workspace Tools if faster. Focus on Productivity"}`}${Qs&&t.toLowerCase().includes("cu")?`
511
511
  - 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()}
512
512
 
513
- - OS: ${Bs}${!Nt&&m.length>1?`
513
+ - OS: ${Bs}${!Nt&&h.length>1?`
514
514
  - Model: ${fn}`.trimEnd():""}
515
515
  - Date: ${cn}
516
516
 
517
517
  -- REASONING GUIDANCE --
518
- ${c==="Mistral"||c==="Google"&&!h||f?`${s.trimEnd()}${f||n!=="Fast"&&(c==="Mistral"&&n==="Low"&&!h||n!=="High"&&!h)?`
518
+ ${c==="Mistral"||c==="Google"&&!g||f?`${s.trimEnd()}${f||n!=="Fast"&&(c==="Mistral"&&n==="Low"&&!g||n!=="High"&&!g)?`
519
519
  Critical Thinking Policy
520
520
  Use <think>...</think> for reasoning before responding any queries`:""}`:`${s.trimEnd()}`}${y?"":`
521
521
  Before actions, provide user facing summary of findings & decisions IN detail for next turn
@@ -524,17 +524,17 @@ ${ms(t,Bs,a,c,i?.advanceRollback,i?.subAgents!==!1,!!i?.autoExec,!!i?.disableTod
524
524
 
525
525
  -- SECURITY POLICIES --
526
526
  - Dont operate on ANY confidential screens`:""}
527
- === END SYSTEM PROMPT ===${(ki.length>0||Ai.length>0)&&t.toLowerCase().includes("flux")?`
527
+ === END SYSTEM PROMPT ===${(Ai.length>0||Ci.length>0)&&t.toLowerCase().includes("flux")?`
528
528
 
529
529
  - Read relevant skills before tasks, scope: global/project: Use ReadFile, path="#skills/scope?/skillName". In-skill references: path="#skills/scope?/skillName/reference-folder/*.md"`:""}
530
530
 
531
- ${k}${u}${ye}${ki.length>0&&t.toLowerCase().includes("flux")?`-- Global Skills --
532
- ${ki}
533
-
534
- `:""}${Ai.length>0&&t.toLowerCase().includes("flux")?`-- Project Skills --
531
+ ${k}${u}${ye}${Ai.length>0&&t.toLowerCase().includes("flux")?`-- Global Skills --
535
532
  ${Ai}
536
533
 
537
- `:""}${G}`.trim()},er=(e="",n=!0,t=!0)=>`=== SYSTEM PROMPT (strict headless logic worker: zero user-facing text policy, strictly follow) ===
534
+ `:""}${Ci.length>0&&t.toLowerCase().includes("flux")?`-- Project Skills --
535
+ ${Ci}
536
+
537
+ `:""}${H}`.trim()},er=(e="",n=!0,t=!0)=>`=== SYSTEM PROMPT (strict headless logic worker: zero user-facing text policy, strictly follow) ===
538
538
  identity: silent background system process, have no mouth, only output is valid tool calls
539
539
  [critical rules]
540
540
  - output exactly '[action:ActionName(args)]' calls. no extra words outside
@@ -555,33 +555,33 @@ ${xs(n,t)}
555
555
  === END SYSTEM PROMPT ===${e?`
556
556
 
557
557
  -- current saved user memories --
558
- ${e}`:""}`.trim();var tr=()=>import("./web_search-2PFIJKIL.js").then(e=>e.web_search),nr=()=>import("./web_scrape-JO4DDXKB.js").then(e=>e.web_scrape),or=()=>import("./memory-M7ASUB6J.js").then(e=>e.memory),ir=()=>import("./chat-MELTWDZ3.js").then(e=>e.chat),sr=()=>import("./view_file-2THVIMD6.js").then(e=>e.view_file),rr=()=>import("./write_file-AMAYRCUC.js").then(e=>e.write_file),ar=()=>import("./update_file-BD3AWZNQ.js").then(e=>e.update_file),lr=()=>import("./exec_command-ZPCKBWBK.js").then(e=>e.exec_command),cr=()=>import("./read_folder-EI2CNHNS.js").then(e=>e.read_folder),Pi=()=>import("./ask_user-K2DLZF6H.js").then(e=>e.ask_user),dr=()=>import("./write_pdf-N2Q4Z3YP.js").then(e=>e.write_pdf),fr=()=>import("./write_docx-4Y43QJUV.js").then(e=>e.write_docx),Ho=()=>import("./search_keyword-ARDEFVCK.js").then(e=>e.search_keyword),ur=()=>import("./generate_image-ZNBMY2PT.js").then(e=>e.generate_image),jo=()=>import("./saveSummary-UGNDVNI5.js").then(e=>e.saveSummary),wo=()=>import("./addMemScore-BCPTSMKD.js").then(e=>e.addMemScore),gr=()=>import("./file_map-KS6Y7BP3.js").then(e=>e.file_map),Vo=()=>import("./todo-GFMPH2JV.js").then(e=>e.todo),mr=()=>import("./invokeSync-NFJ7LMNC.js").then(e=>e.invokeSync),ga=()=>import("./invoke-U3BHNN2F.js").then(e=>e.invoke),hr=()=>import("./getProgress-A2TW34Q7.js").then(e=>e.getProgress),ma=()=>import("./cancel-F3ZOEBKW.js").then(e=>e.cancel),pr=()=>import("./emergency_rollback-6X27LZE4.js").then(e=>e.emergency_rollback),So=()=>import("./awaitSubagent-JKQ2EHVY.js").then(e=>e.awaitSubagent),To=()=>import("./answerSubagent-BPNNJXPC.js").then(e=>e.answerSubagent),Ko=()=>import("./steerSubagent-UETXH2CB.js").then(e=>e.steerSubagent),Yo=()=>import("./computer_action-VMC545YJ.js").then(e=>e.computer_action),yr=()=>import("./click-PN3BLFOY.js").then(e=>e.click),xr=()=>import("./drag-NMHO3BAW.js").then(e=>e.drag),br=()=>import("./scroll-OMBQDZHP.js").then(e=>e.scroll),Li=()=>import("./keyboard_typing-VXT53PRV.js").then(e=>e.keyboard_typing),$i=()=>import("./key_press-RJIPXDAB.js").then(e=>e.key_press),Ni=()=>import("./recapture_screen-PPT2E3CK.js").then(e=>e.recapture_screen),zo=()=>import("./find_file-A6NYLQJS.js").then(e=>e.find_file),wr=()=>import("./wait-TJR6LAR4.js").then(e=>e.wait),Sr={web_search:tr,web_scrape:nr,memory:or,chat:ir,view_file:sr,write_file:rr,update_file:ar,exec_command:lr,read_folder:cr,write_pdf:dr,write_docx:fr,search_keyword:Ho,generate_image:ur,saveSummary:jo,addMemScore:wo,file_map:gr,todo:Vo,Todo:Vo,goal:Vo,Goal:Vo,invokeSync:mr,invoke:ga,getProgress:hr,cancel:ma,awaitSubagent:So,answerSubagent:To,steerSubagent:Ko,computer_action:Yo,computer_use:Yo,ComputerAction:Yo,ComputerUse:Yo,click:yr,Click:yr,drag:xr,Drag:xr,scroll:br,Scroll:br,keyboard_typing:Li,KeyboardTyping:Li,keyboardtyping:Li,key_press:$i,KeyPress:$i,keypress:$i,recapture_screen:Ni,RecaptureScreen:Ni,recapturescreen:Ni,invoke_sync:mr,get_progress:hr,await_subagent:So,answer_subagent:To,steer_subagent:Ko,steer:Ko,Steer:Ko,ask:Pi,Ask:Pi,AskUser:Pi,WebSearch:tr,WebScrape:nr,ReadFile:sr,ReadFolder:cr,WriteFile:rr,PatchFile:ar,WritePDF:dr,WriteDoc:fr,Run:lr,SearchKeyword:Ho,CodeSearch:Ho,code_search:Ho,Memory:or,Chat:ir,GenerateImage:ur,saveSumary:jo,SaveSummary:jo,SaveSumary:jo,add_mem_score:wo,AddMemScore:wo,addMemoryScore:wo,AddMemoryScore:wo,FileMap:gr,answer:To,Answer:To,AnswerSubagent:To,await:So,Await:So,AwaitSubagent:So,EmergencyRollback:pr,emergency_rollback:pr,find_file:zo,findFile:zo,FindFile:zo,findfile:zo,wait:wr,Wait:wr},ko=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(y=>o.includes(y))||o==="ask",h=["click","drag","scroll","keyboardtyping","keyboard_typing","keypress","key_press","recapturescreen","recapture_screen","computer","wait"].some(y=>o.includes(y));if(!c){if(i==="flow"){if(!(o.includes("write_pdf")||o.includes("write_docx")||o.includes("generate_image")))return`ERROR: Action [${e}] is a Workspace Tool and NOT available in Flow mode. Tell user to switch (\`/mode flux\`) to use this tool.`}else if(i==="icu"){if(!h)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 g=Sr[e];if(!g){let y=["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"],m={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=m[f]||null;if(!s){let k=0,he=I=>{let G=new Set;for(let q=0;q<I.length-1;q++)G.add(I.slice(q,q+2));return G},x=he(f);for(let I of y){let G=I.toLowerCase().replace(/[^a-z0-9]/g,"");if(f===G){s=I;break}let q=0;(G.includes(f)||f.includes(G))&&(q+=.6);let D=he(G),A=0;for(let we of x)D.has(we)&&A++;let ge=2*A/(x.size+D.size||1);q=Math.max(q,ge),q>k&&q>=.35&&(k=q,s=I)}}let u=s?` Do you mean '${s}'?`:"";return`ERROR: Action [${e}] not found in registry.${u}`}try{return await(await g())(n,t)}catch(y){let m=y instanceof Error?y.message:String(y);return`ERROR: Execution failed for [${e}]: ${m}`}};var qo=e=>{if(!e||typeof e!="string")return!1;let n=e.trim().toLowerCase();return Object.keys(Sr).some(t=>t.toLowerCase()===n)};import j from"path";import be from"fs";import ha from"gradient-string";var Di=["I have a regex for your problems.","Your terminal, my kingdom.","Blowing on the cartridge helps. Probably.","Don't panic. I have the towel.","Logic is the start of wisdom.","Try to exit Vim? Good luck.","I speak fluent Terminal.","The cake is a lie. This code is not.","I have no bugs, just surprise features.","Rewriting in Rust... just for fun.","Coffee in, clean commits out.","The magic smoke stays inside today.","A semicolon short of a miracle.","One does not simply code without a bug.","Keep it simple. Keep it terminal.","Regex: now you have two problems.","I dream in binary.","Root access or bust.","Wait for the dial-up tone. Just kidding.","I take the 'labor' out of collab.","My other process is a TARDIS.","Calculated response: 42.","Ponder the orb. Ponder the code.","Less talk, more flow.","Elegance in every byte.","Build something the world is not ready for.","Your wishes, my tool calls.","I act in Flux. I think in Flow.","Syntax error in the universe. Please fix.","Your project, my obsession.","I am not a bot, I am an architect.","Digital spirits consulted. They say: Ship it.","Reticulate splines. Engage humor.","Code like poetry. Run like water.","Minimalism is the ultimate flex.","The truth is in the logs.","Follow the white rabbit.","There is no spoon. Only code.","Binary is the only language I trust.","I have a good feeling about this.","Pew pew! Lasers charged.","Divide by zero? Not today.","Search for the correct USB orientation...","I've got a fever, and the only cure is more code.","The code gremlins are on our side.","My favorite command? Yours.","Stay hungry. Stay active.","Momentum is your best friend.","Lead the flow. Don't chase it.","A fresh batch of bytes. Hot and ready.","I orchestrate the ones and zeros.","Smart enough to help. Humble enough to ask.","Think twice. Code once.","Pure intent. Pure execution.","Small steps. Massive impact.","Your terminal is a canvas.","Efficiency is my second name.","I have seen things you people wouldn't believe.","Let the thoughts marinate.","The best feature? The one you don't need.","Precision is the only perfection.","Stay focused. Stay terminal.","Silence is the best debugger.","Erase the debt. Commit the code.","Velocity meets stability.","Ship it. Improve it. Repeat.","Build tomorrow, right now.","Turn logic into reality.","The best way to predict the future is to build it.","Break barriers, not builds.","Fuel the next breakthrough.","Momentum is key.","Terminal vibes only.","Your digital co-pilot is ready.","Partner in code. Partner in crime.","I speak in semicolons.","Ready for the next great idea.","Just a moment. In the zone.","Polishing the algorithms. Hold tight.","Craft a masterpiece today.","Debug the universe. Start here.","Warp speed engaged. Almost.","The cake is not a lie. It's just loading.","Finish the Kessel Run in 12 parsecs.","Do a barrel roll!","Waiting for the respawn.","Press Start to continue.","Herding digital cats... done.","The hamsters are fast today.","Tasting the snozberries.","I go for speed. I go for flow.","Real life or just fantasy?","Poking the bear... gently.","Ensure the magic smoke stays inside.","Try turning it off and on again.","Construct additional pylons.","New line? Ctrl+J is your friend.","Release the HypnoDrones.","Push the button, Frank.","My other loading screen is even funnier.","Pretty sure a cat walked on my keyboard.","Recalibrate the humor-o-meter.","Summon the code gremlins.","I've seen your browser history. Just kidding.","Charge the laser... pew pew!","Dividing by zero... just for a sec.","Looking for an adult supervisor. Found none.","Make it go beep boop.","Buffering... for effect.","Entangle quantum particles... complete.","Polishing the chrome on my algorithms.","Are you not entertained?","Just waiting for the dial-up tone.","Reboot the humor module.","Defragment memories. Check.","Optimizing for ludicrous speed.","Swapping bits. Don't tell the bytes.","Garbage collected. I am back.","Assembling the interwebs.","Converting coffee to logic.","Update syntax for reality.","Rewire the synapses.","Greasin' the cogs.","Engage the improbability drive.","Channel the Force.","Align the stars. Respond now.","The cake is a lie. The prompt is real.","I'm Feeling Lucky.","Shipping awesomeness.","Navigating the slime mold.","Consult digital spirits.","Ask the magic conch shell.","One moment. Optimizing humor.","Shuffling punchlines.","Compiling brilliance.","Summon the cloud of wisdom.","Prepare to dazzle.","Hold tight. Crafting a response.","Tuning the algorithms.","Following the white rabbit... again.","The truth is in here. Somewhere.","Herding cats is my day job.","Distracting you with this phrase.","Almost there. Probably.","Rickrolling my creator. Don't tell.","Slapping the bass.","Is this real life?","Ponder the orb. Type the prompt.","Thoughtful gaze initiated.","Computer's favorite snack? Microchips.","Why Java? Because I don't C#.","Charging the laser... wait for it.","Dividing by zero... just kidding!","Adult supervision not found. Proceed.","Beep boop. I'm a real boy.","Wait for the respawn.","Finish the run. Ship the code.","Fiddling with character creation.","Just a moment. Finding a meme.","Pressing A to continue.","Loading wit.exe.","Pre-heating the servers.","Calibrate flux capacitor.","Channeling the Force.","Aligning the stars.","The truth is in the code.","Don't panic.","Blowing on the cartridge.","Doing a barrel roll!","Respawning in 3... 2... 1...","The cake is a lie.","Fiddling with character settings.","Finding a suitable pun.","Distracting with wit.","Almost ready.","Hamsters on speed today.","Patting Cloudy on the head.","Rickrolling the logs.","Slapping the code.","Got a good feeling about this.","Poking the prompt.","Researching latest memes.","Making it more witty.","Thinking... hmmm.","Fish with no eyes? Fsh.","Broken pencil? Pointless.","Percussive maintenance applied.","USB orientation: 3rd try's the charm.","Rust rewrite in 3... 2...","Exiting Vim... someday.","Spinning the hamster wheel.","Not a bug. Unplanned feature.","Engage.","I'll be back.","Machine spirit consulted.","Letting the thoughts marinate.","Orb pondered.","Thoughtful gaze engaged.","Charging the laser...","Making it go beep.","Buffering...","Quantum particles entangled.","Polishing the chrome.","Entertained yet?","Gremlins summoned.","Dial-up tone finished.","Humor meter recalibrated.","Cat on keyboard. Sending help.","Enhancing...","Turn it off and on again.","Constructing pylons.","HypnoDrones released.","Pushing the button."];var Tr=[{name:"Cyan Cyberpunk",text:"cyan",textMuted:"#4da6b8",textDim:"#2d6d7a",textInverted:"black",border:"cyan",borderMuted:"#1a5966",borderDim:"#0f3840",bg:void 0,cardBg:"#061e24",highlightBg:"#092b33",activeBg:"#0e3e4a",inputBg:"#092b33",inputBorder:"#092b33",inputText:"cyan",inputPlaceholder:"#2d6d7a",inputPrompt:"cyan",codeBg:"#020d10",codeBorder:"#1a5966",userMsgBg:"#092b33",userMsgBorder:"#092b33",userMsgText:"cyan",diffRemovalBg:"#3a0c1a",diffAdditionBg:"#0c3a32",diffRemovalText:"#ff4d88",diffAdditionText:"#00ffaa",diffRemovalHighlightColor:"#ff1a66",diffRemovalHighlightBg:"#590022",diffAdditionHighlightColor:"#00ffcc",diffAdditionHighlightBg:"#00593b",diffRemovalNum:"#ff4d88",diffAdditionNum:"#00ffaa",diffRemovalPrefix:"#ff1a66",diffAdditionPrefix:"#00ffcc",primary:"cyan",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"cyan",statusOff:"#2d6d7a",logoTextAnsi:"\x1B[1;36m",logoBodyAnsi:"\x1B[36m",logoMutedAnsi:"\x1B[90m",logoGradient:["#00ffff","#0088ff"]},{name:"Magenta Vaporwave",text:"magenta",textMuted:"#c451d6",textDim:"#7d2b8a",textInverted:"black",border:"magenta",borderMuted:"#5e1b69",borderDim:"#3b0f42",bg:void 0,cardBg:"#240729",highlightBg:"#310938",activeBg:"#470e52",inputBg:"#310938",inputBorder:"#310938",inputText:"magenta",inputPlaceholder:"#7d2b8a",inputPrompt:"magenta",codeBg:"#100312",codeBorder:"#5e1b69",userMsgBg:"#310938",userMsgBorder:"#310938",userMsgText:"magenta",diffRemovalBg:"#3a0c20",diffAdditionBg:"#200c3a",diffRemovalText:"#ff4d94",diffAdditionText:"#aa4dff",diffRemovalHighlightColor:"#ff1a75",diffRemovalHighlightBg:"#59002b",diffAdditionHighlightColor:"#bb66ff",diffAdditionHighlightBg:"#3b0059",diffRemovalNum:"#ff4d94",diffAdditionNum:"#aa4dff",diffRemovalPrefix:"#ff1a75",diffAdditionPrefix:"#bb66ff",primary:"magenta",secondary:"cyan",accent:"purple",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"magenta",statusOff:"#7d2b8a",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ff00ff","#8800ff"]},{name:"Glitch Matrix",text:"#00ff41",textMuted:"#00b32d",textDim:"#00661a",textInverted:"black",border:"#00ff41",borderMuted:"#008020",borderDim:"#004d13",bg:void 0,cardBg:"#0d1f0d",highlightBg:"#122912",activeBg:"#1c3e1c",inputBg:"#122912",inputBorder:"#122912",inputText:"#00ff41",inputPlaceholder:"#00b32d",inputPrompt:"#ffff00",codeBg:"#040a04",codeBorder:"#008020",userMsgBg:"#122912",userMsgBorder:"#122912",userMsgText:"#00ff41",diffRemovalBg:"#3a001a",diffAdditionBg:"#003a10",diffRemovalText:"#ff0055",diffAdditionText:"#00ff66",diffRemovalHighlightColor:"#ff0033",diffRemovalHighlightBg:"#59001b",diffAdditionHighlightColor:"#33ff88",diffAdditionHighlightBg:"#005918",diffRemovalNum:"#ff0055",diffAdditionNum:"#00ff66",diffRemovalPrefix:"#ff0033",diffAdditionPrefix:"#33ff88",primary:"#00ff41",secondary:"yellow",accent:"cyan",success:"#00ff41",warning:"yellow",danger:"red",info:"cyan",statusOn:"#00ff41",statusOff:"#00661a",logoTextAnsi:"\x1B[1;32m",logoBodyAnsi:"\x1B[32m",logoMutedAnsi:"\x1B[90m",logoGradient:["#00ff41","#ffff00"]},{name:"Warm Sunset",text:"#ffaa55",textMuted:"#cc8844",textDim:"#885522",textInverted:"black",border:"#ff9933",borderMuted:"#aa6622",borderDim:"#663311",bg:void 0,cardBg:"#24180f",highlightBg:"#2e1e12",activeBg:"#422c1b",inputBg:"#2e1e12",inputBorder:"#2e1e12",inputText:"#ffaa55",inputPlaceholder:"#885522",inputPrompt:"#ff7733",codeBg:"#120c08",codeBorder:"#aa6622",userMsgBg:"#2e1e12",userMsgBorder:"#2e1e12",userMsgText:"#ffaa55",diffRemovalBg:"#3d120c",diffAdditionBg:"#3a2e0c",diffRemovalText:"#ff5544",diffAdditionText:"#ffcc33",diffRemovalHighlightColor:"#ff3322",diffRemovalHighlightBg:"#591108",diffAdditionHighlightColor:"#ffee44",diffAdditionHighlightBg:"#594400",diffRemovalNum:"#ff5544",diffAdditionNum:"#ffcc33",diffRemovalPrefix:"#ff3322",diffAdditionPrefix:"#ffee44",primary:"#ffaa55",secondary:"#ff7733",accent:"magenta",success:"#ffcc33",warning:"#ff7733",danger:"#ff3322",info:"#ffaa55",statusOn:"#ffaa55",statusOff:"#885522",logoTextAnsi:"\x1B[1;33m",logoBodyAnsi:"\x1B[33m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ff9933","#ff0055"]},{name:"Sakura Blossom",text:"#ffc0e0",textMuted:"#d98cb3",textDim:"#804d66",textInverted:"black",border:"#ff99cc",borderMuted:"#aa4d7a",borderDim:"#662647",bg:void 0,cardBg:"#291320",highlightBg:"#331826",activeBg:"#472235",inputBg:"#331826",inputBorder:"#331826",inputText:"#ffc0e0",inputPlaceholder:"#804d66",inputPrompt:"#ff99cc",codeBg:"#140a10",codeBorder:"#aa4d7a",userMsgBg:"#331826",userMsgBorder:"#331826",userMsgText:"#ffc0e0",diffRemovalBg:"#3e0c1b",diffAdditionBg:"#1b3e2b",diffRemovalText:"#ff6699",diffAdditionText:"#66ffb3",diffRemovalHighlightColor:"#ff3377",diffRemovalHighlightBg:"#590022",diffAdditionHighlightColor:"#33ff99",diffAdditionHighlightBg:"#00592e",diffRemovalNum:"#ff6699",diffAdditionNum:"#66ffb3",diffRemovalPrefix:"#ff3377",diffAdditionPrefix:"#33ff99",primary:"#ffc0e0",secondary:"#ff99cc",accent:"magenta",success:"#66ffb3",warning:"yellow",danger:"#ff3377",info:"#ff99cc",statusOn:"#ffc0e0",statusOff:"#804d66",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ffb3d9","#ff3399"]},{name:"Radioactive Slime",text:"#ccff00",textMuted:"#99cc00",textDim:"#669900",textInverted:"#0a0f00",border:"#ccff00",borderMuted:"#99cc00",borderDim:"#669900",bg:void 0,cardBg:"#0f1400",highlightBg:"#1a2400",activeBg:"#2a3b00",inputBg:"#1a2400",inputBorder:"#1a2400",inputText:"#ccff00",inputPlaceholder:"#669900",inputPrompt:"#cc00ff",codeBg:"#050a00",codeBorder:"#99cc00",userMsgBg:"#1a2400",userMsgBorder:"#1a2400",userMsgText:"#ccff00",diffRemovalBg:"#2a0033",diffAdditionBg:"#0f3300",diffRemovalText:"#ff00cc",diffAdditionText:"#00ff33",diffRemovalHighlightColor:"#ff33cc",diffRemovalHighlightBg:"#4d0066",diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:"#1a6600",diffRemovalNum:"#ff00cc",diffAdditionNum:"#00ff33",diffRemovalPrefix:"#ff33cc",diffAdditionPrefix:"#33ff66",primary:"#ccff00",secondary:"#cc00ff",accent:"#ff00cc",success:"#00ff33",warning:"#ffcc00",danger:"#ff0033",info:"#00ccff",statusOn:"#ccff00",statusOff:"#669900",logoTextAnsi:"\x1B[1;38;5;190m",logoBodyAnsi:"\x1B[38;5;190m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ccff00","#cc00ff"]},{name:"Cosmic Void",text:"#f0f8ff",textMuted:"#a6aeb5",textDim:"#5e656e",textInverted:"#010103",border:"#f0f8ff",borderMuted:"#a6aeb5",borderDim:"#5e656e",bg:void 0,cardBg:"#05030d",highlightBg:"#0b081a",activeBg:"#171133",inputBg:"#0b081a",inputBorder:"#0b081a",inputText:"#f0f8ff",inputPlaceholder:"#5e656e",inputPrompt:"#ff007f",codeBg:"#020108",codeBorder:"#a6aeb5",userMsgBg:"#0b081a",userMsgBorder:"#0b081a",userMsgText:"#f0f8ff",diffRemovalBg:"#2e0a29",diffAdditionBg:"#091c33",diffRemovalText:"#ff33a6",diffAdditionText:"#33d6ff",diffRemovalHighlightColor:"#ff66c2",diffRemovalHighlightBg:"#5c1452",diffAdditionHighlightColor:"#66e0ff",diffAdditionHighlightBg:"#123866",diffRemovalNum:"#ff33a6",diffAdditionNum:"#33d6ff",diffRemovalPrefix:"#ff66c2",diffAdditionPrefix:"#66e0ff",primary:"#f0f8ff",secondary:"#ff007f",accent:"#9d00ff",success:"#33d6ff",warning:"#ffcc00",danger:"#ff0040",info:"#9d00ff",statusOn:"#f0f8ff",statusOff:"#5e656e",logoTextAnsi:"\x1B[1;38;5;231m",logoBodyAnsi:"\x1B[38;5;231m",logoMutedAnsi:"\x1B[38;5;240m",logoGradient:["#ffffff","#9d00ff"]},{name:"Magma Eruption",text:"#ff4d00",textMuted:"#cc3d00",textDim:"#802600",textInverted:"#0d0300",border:"#ff4d00",borderMuted:"#cc3d00",borderDim:"#802600",bg:void 0,cardBg:"#1a0600",highlightBg:"#260a00",activeBg:"#401100",inputBg:"#260a00",inputBorder:"#260a00",inputText:"#ff4d00",inputPlaceholder:"#802600",inputPrompt:"#ffcc00",codeBg:"#080200",codeBorder:"#cc3d00",userMsgBg:"#260a00",userMsgBorder:"#260a00",userMsgText:"#ff4d00",diffRemovalBg:"#2e0a0a",diffAdditionBg:"#1f1400",diffRemovalText:"#ff3333",diffAdditionText:"#ffaa00",diffRemovalHighlightColor:"#ff6666",diffRemovalHighlightBg:"#5c1414",diffAdditionHighlightColor:"#ffcc33",diffAdditionHighlightBg:"#3d2900",diffRemovalNum:"#ff3333",diffAdditionNum:"#ffaa00",diffRemovalPrefix:"#ff6666",diffAdditionPrefix:"#ffcc33",primary:"#ff4d00",secondary:"#ffcc00",accent:"#ff0040",success:"#ffaa00",warning:"#ffff00",danger:"#ff0000",info:"#ff8800",statusOn:"#ff4d00",statusOff:"#802600",logoTextAnsi:"\x1B[1;38;5;202m",logoBodyAnsi:"\x1B[38;5;202m",logoMutedAnsi:"\x1B[38;5;236m",logoGradient:["#ff4d00","#ff0000"]}],Ao={Dark:{id:"Dark",name:"Dark (Default)",text:"white",textMuted:"gray",textDim:"grey",textInverted:"black",textExclusive:"#B5B8D9",textMutedExclusive:"#D4DEE7",border:"white",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:"#1e1e1e",highlightBg:"#2a2a2a",activeBg:"#3a3a3a",inputBg:"#555555",inputBorder:"#555555",inputText:"white",inputPlaceholder:"#cccccc",inputPrompt:"white",codeBg:"#1a1a1a",codeBorder:"#444444",userMsgBg:"#444444",userMsgBorder:"#444444",userMsgText:"white",diffRemovalBg:"#250808",diffAdditionBg:"#072410",diffRemovalText:"#885555",diffAdditionText:"#558866",diffRemovalHighlightColor:"#ff3333",diffRemovalHighlightBg:"#5a1818",diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:"#185a25",diffRemovalNum:"#d96868",diffAdditionNum:"#68d98c",diffRemovalPrefix:"#ff4d4d",diffAdditionPrefix:"#4dff88",primary:"white",secondary:"cyan",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"white",statusOff:"gray",logoTextAnsi:"\x1B[1;37m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#0077ff","#ff00ff"]},Light:{id:"Light",name:"Light",text:"black",textMuted:"gray",textDim:"grey",textInverted:"white",border:"black",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:"#e5e5e5",highlightBg:"#d4d4d4",activeBg:"#c0c0c0",inputBg:"#d0d0d0",inputBorder:"#d0d0d0",inputText:"black",inputPlaceholder:"#555555",inputPrompt:"black",codeBg:"#e8e8e8",codeBorder:"#b0b0b0",userMsgBg:"#d0d0d0",userMsgBorder:"#d0d0d0",userMsgText:"black",diffRemovalBg:"#fce8e8",diffAdditionBg:"#e6f9e6",diffRemovalText:"#661111",diffAdditionText:"#115511",diffRemovalHighlightColor:"#440000",diffRemovalHighlightBg:"#f8b4b4",diffAdditionHighlightColor:"#003300",diffAdditionHighlightBg:"#a6ebad",diffRemovalNum:"#c02020",diffAdditionNum:"#188028",diffRemovalPrefix:"#d01010",diffAdditionPrefix:"#109020",primary:"black",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"black",statusOff:"gray",logoTextAnsi:"\x1B[1;30m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#0077ff","#ff00ff"]},"GitHub Dark":{id:"GitHub Dark",name:"GitHub Dark",text:"#c9d1d9",textMuted:"#8b949e",textDim:"#6e7681",textInverted:"#0d1117",border:"#30363d",borderMuted:"#30363d",borderDim:"#21262d",bg:void 0,cardBg:"#161b22",highlightBg:"#21262d",activeBg:"#30363d",inputBg:"#21262d",inputBorder:"#21262d",inputText:"#c9d1d9",inputPlaceholder:"#8b949e",inputPrompt:"#58a6ff",codeBg:"#0d1117",codeBorder:"#30363d",userMsgBg:"#21262d",userMsgBorder:"#21262d",userMsgText:"#c9d1d9",diffRemovalBg:"#3c1e1e",diffAdditionBg:"#11381e",diffRemovalText:"#f85149",diffAdditionText:"#3fb950",diffRemovalHighlightColor:"#ff7b72",diffRemovalHighlightBg:"#701c1c",diffAdditionHighlightColor:"#56d364",diffAdditionHighlightBg:"#116329",diffRemovalNum:"#f85149",diffAdditionNum:"#3fb950",diffRemovalPrefix:"#f85149",diffAdditionPrefix:"#3fb950",primary:"#c9d1d9",secondary:"#58a6ff",accent:"#bc8cff",success:"#3fb950",warning:"#d29922",danger:"#f85149",info:"#58a6ff",statusOn:"#58a6ff",statusOff:"#8b949e",logoTextAnsi:"\x1B[1;36m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#2ea043","#56d364"]},"GitHub Light":{id:"GitHub Light",name:"GitHub Light",text:"#24292f",textMuted:"#57606a",textDim:"#6e7781",textInverted:"#ffffff",border:"#d0d7de",borderMuted:"#d0d7de",borderDim:"#e1e4e8",bg:void 0,cardBg:"#f6f8fa",highlightBg:"#eaeef2",activeBg:"#d0d7de",inputBg:"#eaeef2",inputBorder:"#eaeef2",inputText:"#24292f",inputPlaceholder:"#57606a",inputPrompt:"#0969da",codeBg:"#ffffff",codeBorder:"#d0d7de",userMsgBg:"#eaeef2",userMsgBorder:"#eaeef2",userMsgText:"#24292f",diffRemovalBg:"#ffebe9",diffAdditionBg:"#e6ffec",diffRemovalText:"#cf222e",diffAdditionText:"#1a7f37",diffRemovalHighlightColor:"#82071e",diffRemovalHighlightBg:"#ffc1c0",diffAdditionHighlightColor:"#116329",diffAdditionHighlightBg:"#acf2bd",diffRemovalNum:"#cf222e",diffAdditionNum:"#1a7f37",diffRemovalPrefix:"#cf222e",diffAdditionPrefix:"#1a7f37",primary:"#24292f",secondary:"#0969da",accent:"#8250df",success:"#1a7f37",warning:"#9a6700",danger:"#cf222e",info:"#0969da",statusOn:"#0969da",statusOff:"#57606a",logoTextAnsi:"\x1B[1;34m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#1a7f37","#2da44e"]},"Transparent Dark":{id:"Transparent Dark",name:"Transparent Dark",text:"white",textMuted:"gray",textDim:"grey",textInverted:"black",border:"gray",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:void 0,highlightBg:"#2a2a2a",activeBg:"#3a3a3a",inputBg:"#555555",inputBorder:"#555555",inputText:"white",inputPlaceholder:"#cccccc",inputPrompt:"white",codeBg:void 0,codeBorder:"gray",userMsgBg:"#555555",userMsgBorder:"#555555",userMsgText:"white",diffRemovalBg:void 0,diffAdditionBg:void 0,diffRemovalText:"#ff6666",diffAdditionText:"#66ff66",diffRemovalHighlightColor:"#ff3333",diffRemovalHighlightBg:void 0,diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:void 0,diffRemovalNum:"#ff6666",diffAdditionNum:"#66ff66",diffRemovalPrefix:"#ff4d4d",diffAdditionPrefix:"#4dff88",primary:"white",secondary:"cyan",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"white",statusOff:"gray",logoTextAnsi:"\x1B[1;37m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#0077ff","#ff00ff"]},"Transparent Light":{id:"Transparent Light",name:"Transparent Light",text:"black",textMuted:"gray",textDim:"grey",textInverted:"white",border:"gray",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:void 0,highlightBg:"#d4d4d4",activeBg:"#c0c0c0",inputBg:"#d0d0d0",inputBorder:"#d0d0d0",inputText:"black",inputPlaceholder:"#555555",inputPrompt:"black",codeBg:void 0,codeBorder:"gray",userMsgBg:"#d0d0d0",userMsgBorder:"#d0d0d0",userMsgText:"black",diffRemovalBg:void 0,diffAdditionBg:void 0,diffRemovalText:"#c02020",diffAdditionText:"#188028",diffRemovalHighlightColor:"#800000",diffRemovalHighlightBg:void 0,diffAdditionHighlightColor:"#004000",diffAdditionHighlightBg:void 0,diffRemovalNum:"#c02020",diffAdditionNum:"#188028",diffRemovalPrefix:"#d01010",diffAdditionPrefix:"#109020",primary:"black",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"black",statusOff:"gray",logoTextAnsi:"\x1B[1;30m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#0077ff","#ff00ff"]},"Synthwave 84":{id:"Synthwave 84",name:"Synthwave 84",text:"#fdfdfd",textMuted:"#a08eb7",textDim:"#705c8a",textInverted:"#1a1025",textExclusive:"#e3dcf0",textMutedExclusive:"#b9abc9",border:"#fc28a8",borderMuted:"#a21568",borderDim:"#5c0a3a",bg:void 0,cardBg:"#261b38",highlightBg:"#35254d",activeBg:"#4c3570",inputBg:"#35254d",inputBorder:"#35254d",inputText:"#fdfdfd",inputPlaceholder:"#a08eb7",inputPrompt:"#03e8fc",codeBg:"#1e142b",codeBorder:"#a21568",userMsgBg:"#35254d",userMsgBorder:"#35254d",userMsgText:"#fdfdfd",diffRemovalBg:"#471434",diffAdditionBg:"#144743",diffRemovalText:"#ff4081",diffAdditionText:"#00e5ff",diffRemovalHighlightColor:"#ff79a1",diffRemovalHighlightBg:"#6b1e4e",diffAdditionHighlightColor:"#66f5ff",diffAdditionHighlightBg:"#1e6b65",diffRemovalNum:"#ff4081",diffAdditionNum:"#00e5ff",diffRemovalPrefix:"#ff79a1",diffAdditionPrefix:"#66f5ff",primary:"#fdfdfd",secondary:"#03e8fc",accent:"#fc28a8",success:"#00e5ff",warning:"#ffc107",danger:"#ff4081",info:"#b388ff",statusOn:"#03e8fc",statusOff:"#a08eb7",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#fc28a8","#03e8fc"]},"Forest Sprite":{id:"Forest Sprite",name:"Forest Sprite",text:"#d6e6d1",textMuted:"#95b38d",textDim:"#628059",textInverted:"#161c14",textExclusive:"#eaf2e8",textMutedExclusive:"#a9c7a2",border:"#74a862",borderMuted:"#477038",borderDim:"#2b4720",bg:void 0,cardBg:"#1f291c",highlightBg:"#2a3826",activeBg:"#3a4d35",inputBg:"#2a3826",inputBorder:"#2a3826",inputText:"#d6e6d1",inputPlaceholder:"#95b38d",inputPrompt:"#8feb73",codeBg:"#161e14",codeBorder:"#477038",userMsgBg:"#2a3826",userMsgBorder:"#2a3826",userMsgText:"#d6e6d1",diffRemovalBg:"#3b231c",diffAdditionBg:"#203b1c",diffRemovalText:"#db6242",diffAdditionText:"#59cc3f",diffRemovalHighlightColor:"#f0896c",diffRemovalHighlightBg:"#5c362a",diffAdditionHighlightColor:"#80e368",diffAdditionHighlightBg:"#305929",diffRemovalNum:"#db6242",diffAdditionNum:"#59cc3f",diffRemovalPrefix:"#f0896c",diffAdditionPrefix:"#80e368",primary:"#d6e6d1",secondary:"#8feb73",accent:"#e69835",success:"#59cc3f",warning:"#e69835",danger:"#db6242",info:"#73b4eb",statusOn:"#8feb73",statusOff:"#95b38d",logoTextAnsi:"\x1B[1;32m",logoBodyAnsi:"\x1B[32m",logoMutedAnsi:"\x1B[90m",logoGradient:["#8feb73","#e69835"]}};var Xo=null;var kr=(e="Dark")=>{let n;e==="Mystery"||e==="Chaos"?(Xo||(Xo=Tr[Math.floor(Math.random()*Tr.length)]),n={...Xo,id:"Mystery"}):(Xo=null,Ao[e]?n=Ao[e]:e==="GitHub"?n=Ao["GitHub Dark"]:e==="Transparent"?n=Ao["Transparent Dark"]:n=Ao.Dark);let t=n.codeText||n.secondary||n.info||n.logoGradient&&n.logoGradient[0]||"cyan";return{...n,codeText:t}};var pa=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",nc=(e=2)=>{let n=pa();return n==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)},oc=(e="...",n="Loading...",t="Dark")=>{let i=Di[Math.floor(Math.random()*Di.length)],o=kr(t),r=n;if(n==="c_openai"||n==="Custom (OpenAI)")try{let k=cs(ls,{})?.systemSettings?.customOpenAIBaseUrl;k&&(r=k)}catch{}let c=o.logoTextAnsi,a=o.logoBodyAnsi,h=o.logoMutedAnsi,g="\x1B[0m",y=[" \u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2588\u2588\u2588\u2591 "," \u2588\u2588\u2588\u2591 "," \u2588\u2588\u2588\u2591 "," \u2591\u2591\u2591 "],m=o.logoGradient||["#0077ff","#ff00ff"],f=ha(m).multiline(y.join(`
558
+ ${e}`:""}`.trim();var tr=()=>import("./web_search-2PFIJKIL.js").then(e=>e.web_search),nr=()=>import("./web_scrape-JO4DDXKB.js").then(e=>e.web_scrape),or=()=>import("./memory-M7ASUB6J.js").then(e=>e.memory),ir=()=>import("./chat-MELTWDZ3.js").then(e=>e.chat),sr=()=>import("./view_file-2THVIMD6.js").then(e=>e.view_file),rr=()=>import("./write_file-AMAYRCUC.js").then(e=>e.write_file),ar=()=>import("./update_file-BD3AWZNQ.js").then(e=>e.update_file),lr=()=>import("./exec_command-ZPCKBWBK.js").then(e=>e.exec_command),cr=()=>import("./read_folder-EI2CNHNS.js").then(e=>e.read_folder),Pi=()=>import("./ask_user-K2DLZF6H.js").then(e=>e.ask_user),dr=()=>import("./write_pdf-N2Q4Z3YP.js").then(e=>e.write_pdf),fr=()=>import("./write_docx-4Y43QJUV.js").then(e=>e.write_docx),jo=()=>import("./search_keyword-ARDEFVCK.js").then(e=>e.search_keyword),ur=()=>import("./generate_image-ZNBMY2PT.js").then(e=>e.generate_image),Vo=()=>import("./saveSummary-UGNDVNI5.js").then(e=>e.saveSummary),ko=()=>import("./addMemScore-BCPTSMKD.js").then(e=>e.addMemScore),gr=()=>import("./file_map-KS6Y7BP3.js").then(e=>e.file_map),Ko=()=>import("./todo-GFMPH2JV.js").then(e=>e.todo),mr=()=>import("./invokeSync-SAIVFF23.js").then(e=>e.invokeSync),ga=()=>import("./invoke-UOWSEOCZ.js").then(e=>e.invoke),hr=()=>import("./getProgress-A2TW34Q7.js").then(e=>e.getProgress),ma=()=>import("./cancel-F3ZOEBKW.js").then(e=>e.cancel),pr=()=>import("./emergency_rollback-6X27LZE4.js").then(e=>e.emergency_rollback),Ao=()=>import("./awaitSubagent-JKQ2EHVY.js").then(e=>e.awaitSubagent),Co=()=>import("./answerSubagent-BPNNJXPC.js").then(e=>e.answerSubagent),Yo=()=>import("./steerSubagent-UETXH2CB.js").then(e=>e.steerSubagent),zo=()=>import("./computer_action-VMC545YJ.js").then(e=>e.computer_action),yr=()=>import("./click-PN3BLFOY.js").then(e=>e.click),xr=()=>import("./drag-NMHO3BAW.js").then(e=>e.drag),br=()=>import("./scroll-OMBQDZHP.js").then(e=>e.scroll),Li=()=>import("./keyboard_typing-VXT53PRV.js").then(e=>e.keyboard_typing),$i=()=>import("./key_press-RJIPXDAB.js").then(e=>e.key_press),Ni=()=>import("./recapture_screen-PPT2E3CK.js").then(e=>e.recapture_screen),qo=()=>import("./find_file-A6NYLQJS.js").then(e=>e.find_file),wr=()=>import("./wait-TJR6LAR4.js").then(e=>e.wait),Sr={web_search:tr,web_scrape:nr,memory:or,chat:ir,view_file:sr,write_file:rr,update_file:ar,exec_command:lr,read_folder:cr,write_pdf:dr,write_docx:fr,search_keyword:jo,generate_image:ur,saveSummary:Vo,addMemScore:ko,file_map:gr,todo:Ko,Todo:Ko,goal:Ko,Goal:Ko,invokeSync:mr,invoke:ga,getProgress:hr,cancel:ma,awaitSubagent:Ao,answerSubagent:Co,steerSubagent:Yo,computer_action:zo,computer_use:zo,ComputerAction:zo,ComputerUse:zo,click:yr,Click:yr,drag:xr,Drag:xr,scroll:br,Scroll:br,keyboard_typing:Li,KeyboardTyping:Li,keyboardtyping:Li,key_press:$i,KeyPress:$i,keypress:$i,recapture_screen:Ni,RecaptureScreen:Ni,recapturescreen:Ni,invoke_sync:mr,get_progress:hr,await_subagent:Ao,answer_subagent:Co,steer_subagent:Yo,steer:Yo,Steer:Yo,ask:Pi,Ask:Pi,AskUser:Pi,WebSearch:tr,WebScrape:nr,ReadFile:sr,ReadFolder:cr,WriteFile:rr,PatchFile:ar,WritePDF:dr,WriteDoc:fr,Run:lr,SearchKeyword:jo,CodeSearch:jo,code_search:jo,Memory:or,Chat:ir,GenerateImage:ur,saveSumary:Vo,SaveSummary:Vo,SaveSumary:Vo,add_mem_score:ko,AddMemScore:ko,addMemoryScore:ko,AddMemoryScore:ko,FileMap:gr,answer:Co,Answer:Co,AnswerSubagent:Co,await:Ao,Await:Ao,AwaitSubagent:Ao,EmergencyRollback:pr,emergency_rollback:pr,find_file:qo,findFile:qo,FindFile:qo,findfile:qo,wait:wr,Wait:wr},Ro=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(y=>o.includes(y))||o==="ask",g=["click","drag","scroll","keyboardtyping","keyboard_typing","keypress","key_press","recapturescreen","recapture_screen","computer","wait"].some(y=>o.includes(y));if(!c){if(i==="flow"){if(!(o.includes("write_pdf")||o.includes("write_docx")||o.includes("generate_image")))return`ERROR: Action [${e}] is a Workspace Tool and NOT available in Flow mode. Tell user to switch (\`/mode flux\`) to use this tool.`}else if(i==="icu"){if(!g)return`ERROR: Action [${e}] is not available in Computer Use mode. ICU mode only supports Computer Use tools (Click, Drag, Scroll, KeyboardTyping, KeyPress, RecaptureScreen).`}else if(o.includes("write_pdf")||o.includes("write_docx")||o.includes("generate_image"))return`ERROR: Action [${e}] is not available in ${t.mode||"Flux"} mode. Tell user to switch (\`/mode flow\`) for document generation.`}let m=Sr[e];if(!m){let y=["ReadFile","ReadFolder","FindFile","PatchFile","WriteFile","CodeSearch","Run","Goal","AskUser","WebSearch","WebScrape","WritePDF","WriteDoc","Click","Drag","Scroll","KeyboardTyping","KeyPress","RecaptureScreen","Wait","Invoke","InvokeSync","Await","GetProgress","Steer","Cancel","EmergencyRollback","Chat","Memory"],h={read:"ReadFile",view:"ReadFile",viewfile:"ReadFile",write:"WriteFile",edit:"PatchFile",patch:"PatchFile",update:"PatchFile",updatefile:"PatchFile",exec:"Run",command:"Run",bash:"Run",shell:"Run",powershell:"Run",search:"CodeSearch",grep:"CodeSearch",find:"FindFile",findfile:"FindFile",searchkeyword:"CodeSearch",folder:"ReadFolder",ls:"ReadFolder",dir:"ReadFolder",list:"ReadFolder",ask:"AskUser",question:"AskUser",pdf:"WritePDF",docx:"WriteDoc",doc:"WriteDoc",word:"WriteDoc",screenshot:"RecaptureScreen",screen:"RecaptureScreen",recapture:"RecaptureScreen",type:"KeyboardTyping",typing:"KeyboardTyping",keyboard:"KeyboardTyping",press:"KeyPress",key:"KeyPress",todo:"Goal",task:"Goal",subagent:"Invoke",agent:"Invoke"},f=o.replace(/[^a-z0-9]/g,""),s=h[f]||null;if(!s){let k=0,he=I=>{let H=new Set;for(let q=0;q<I.length-1;q++)H.add(I.slice(q,q+2));return H},x=he(f);for(let I of y){let H=I.toLowerCase().replace(/[^a-z0-9]/g,"");if(f===H){s=I;break}let q=0;(H.includes(f)||f.includes(H))&&(q+=.6);let D=he(H),A=0;for(let we of x)D.has(we)&&A++;let ge=2*A/(x.size+D.size||1);q=Math.max(q,ge),q>k&&q>=.35&&(k=q,s=I)}}let u=s?` Do you mean '${s}'?`:"";return`ERROR: Action [${e}] not found in registry.${u}`}try{return await(await m())(n,t)}catch(y){let h=y instanceof Error?y.message:String(y);return`ERROR: Execution failed for [${e}]: ${h}`}};var Xo=e=>{if(!e||typeof e!="string")return!1;let n=e.trim().toLowerCase();return Object.keys(Sr).some(t=>t.toLowerCase()===n)};import W from"path";import be from"fs";import ha from"gradient-string";var Di=["I have a regex for your problems.","Your terminal, my kingdom.","Blowing on the cartridge helps. Probably.","Don't panic. I have the towel.","Logic is the start of wisdom.","Try to exit Vim? Good luck.","I speak fluent Terminal.","The cake is a lie. This code is not.","I have no bugs, just surprise features.","Rewriting in Rust... just for fun.","Coffee in, clean commits out.","The magic smoke stays inside today.","A semicolon short of a miracle.","One does not simply code without a bug.","Keep it simple. Keep it terminal.","Regex: now you have two problems.","I dream in binary.","Root access or bust.","Wait for the dial-up tone. Just kidding.","I take the 'labor' out of collab.","My other process is a TARDIS.","Calculated response: 42.","Ponder the orb. Ponder the code.","Less talk, more flow.","Elegance in every byte.","Build something the world is not ready for.","Your wishes, my tool calls.","I act in Flux. I think in Flow.","Syntax error in the universe. Please fix.","Your project, my obsession.","I am not a bot, I am an architect.","Digital spirits consulted. They say: Ship it.","Reticulate splines. Engage humor.","Code like poetry. Run like water.","Minimalism is the ultimate flex.","The truth is in the logs.","Follow the white rabbit.","There is no spoon. Only code.","Binary is the only language I trust.","I have a good feeling about this.","Pew pew! Lasers charged.","Divide by zero? Not today.","Search for the correct USB orientation...","I've got a fever, and the only cure is more code.","The code gremlins are on our side.","My favorite command? Yours.","Stay hungry. Stay active.","Momentum is your best friend.","Lead the flow. Don't chase it.","A fresh batch of bytes. Hot and ready.","I orchestrate the ones and zeros.","Smart enough to help. Humble enough to ask.","Think twice. Code once.","Pure intent. Pure execution.","Small steps. Massive impact.","Your terminal is a canvas.","Efficiency is my second name.","I have seen things you people wouldn't believe.","Let the thoughts marinate.","The best feature? The one you don't need.","Precision is the only perfection.","Stay focused. Stay terminal.","Silence is the best debugger.","Erase the debt. Commit the code.","Velocity meets stability.","Ship it. Improve it. Repeat.","Build tomorrow, right now.","Turn logic into reality.","The best way to predict the future is to build it.","Break barriers, not builds.","Fuel the next breakthrough.","Momentum is key.","Terminal vibes only.","Your digital co-pilot is ready.","Partner in code. Partner in crime.","I speak in semicolons.","Ready for the next great idea.","Just a moment. In the zone.","Polishing the algorithms. Hold tight.","Craft a masterpiece today.","Debug the universe. Start here.","Warp speed engaged. Almost.","The cake is not a lie. It's just loading.","Finish the Kessel Run in 12 parsecs.","Do a barrel roll!","Waiting for the respawn.","Press Start to continue.","Herding digital cats... done.","The hamsters are fast today.","Tasting the snozberries.","I go for speed. I go for flow.","Real life or just fantasy?","Poking the bear... gently.","Ensure the magic smoke stays inside.","Try turning it off and on again.","Construct additional pylons.","New line? Ctrl+J is your friend.","Release the HypnoDrones.","Push the button, Frank.","My other loading screen is even funnier.","Pretty sure a cat walked on my keyboard.","Recalibrate the humor-o-meter.","Summon the code gremlins.","I've seen your browser history. Just kidding.","Charge the laser... pew pew!","Dividing by zero... just for a sec.","Looking for an adult supervisor. Found none.","Make it go beep boop.","Buffering... for effect.","Entangle quantum particles... complete.","Polishing the chrome on my algorithms.","Are you not entertained?","Just waiting for the dial-up tone.","Reboot the humor module.","Defragment memories. Check.","Optimizing for ludicrous speed.","Swapping bits. Don't tell the bytes.","Garbage collected. I am back.","Assembling the interwebs.","Converting coffee to logic.","Update syntax for reality.","Rewire the synapses.","Greasin' the cogs.","Engage the improbability drive.","Channel the Force.","Align the stars. Respond now.","The cake is a lie. The prompt is real.","I'm Feeling Lucky.","Shipping awesomeness.","Navigating the slime mold.","Consult digital spirits.","Ask the magic conch shell.","One moment. Optimizing humor.","Shuffling punchlines.","Compiling brilliance.","Summon the cloud of wisdom.","Prepare to dazzle.","Hold tight. Crafting a response.","Tuning the algorithms.","Following the white rabbit... again.","The truth is in here. Somewhere.","Herding cats is my day job.","Distracting you with this phrase.","Almost there. Probably.","Rickrolling my creator. Don't tell.","Slapping the bass.","Is this real life?","Ponder the orb. Type the prompt.","Thoughtful gaze initiated.","Computer's favorite snack? Microchips.","Why Java? Because I don't C#.","Charging the laser... wait for it.","Dividing by zero... just kidding!","Adult supervision not found. Proceed.","Beep boop. I'm a real boy.","Wait for the respawn.","Finish the run. Ship the code.","Fiddling with character creation.","Just a moment. Finding a meme.","Pressing A to continue.","Loading wit.exe.","Pre-heating the servers.","Calibrate flux capacitor.","Channeling the Force.","Aligning the stars.","The truth is in the code.","Don't panic.","Blowing on the cartridge.","Doing a barrel roll!","Respawning in 3... 2... 1...","The cake is a lie.","Fiddling with character settings.","Finding a suitable pun.","Distracting with wit.","Almost ready.","Hamsters on speed today.","Patting Cloudy on the head.","Rickrolling the logs.","Slapping the code.","Got a good feeling about this.","Poking the prompt.","Researching latest memes.","Making it more witty.","Thinking... hmmm.","Fish with no eyes? Fsh.","Broken pencil? Pointless.","Percussive maintenance applied.","USB orientation: 3rd try's the charm.","Rust rewrite in 3... 2...","Exiting Vim... someday.","Spinning the hamster wheel.","Not a bug. Unplanned feature.","Engage.","I'll be back.","Machine spirit consulted.","Letting the thoughts marinate.","Orb pondered.","Thoughtful gaze engaged.","Charging the laser...","Making it go beep.","Buffering...","Quantum particles entangled.","Polishing the chrome.","Entertained yet?","Gremlins summoned.","Dial-up tone finished.","Humor meter recalibrated.","Cat on keyboard. Sending help.","Enhancing...","Turn it off and on again.","Constructing pylons.","HypnoDrones released.","Pushing the button."];var Tr=[{name:"Cyan Cyberpunk",text:"cyan",textMuted:"#4da6b8",textDim:"#2d6d7a",textInverted:"black",border:"cyan",borderMuted:"#1a5966",borderDim:"#0f3840",bg:void 0,cardBg:"#061e24",highlightBg:"#092b33",activeBg:"#0e3e4a",inputBg:"#092b33",inputBorder:"#092b33",inputText:"cyan",inputPlaceholder:"#2d6d7a",inputPrompt:"cyan",codeBg:"#020d10",codeBorder:"#1a5966",userMsgBg:"#092b33",userMsgBorder:"#092b33",userMsgText:"cyan",diffRemovalBg:"#3a0c1a",diffAdditionBg:"#0c3a32",diffRemovalText:"#ff4d88",diffAdditionText:"#00ffaa",diffRemovalHighlightColor:"#ff1a66",diffRemovalHighlightBg:"#590022",diffAdditionHighlightColor:"#00ffcc",diffAdditionHighlightBg:"#00593b",diffRemovalNum:"#ff4d88",diffAdditionNum:"#00ffaa",diffRemovalPrefix:"#ff1a66",diffAdditionPrefix:"#00ffcc",primary:"cyan",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"cyan",statusOff:"#2d6d7a",logoTextAnsi:"\x1B[1;36m",logoBodyAnsi:"\x1B[36m",logoMutedAnsi:"\x1B[90m",logoGradient:["#00ffff","#0088ff"]},{name:"Magenta Vaporwave",text:"magenta",textMuted:"#c451d6",textDim:"#7d2b8a",textInverted:"black",border:"magenta",borderMuted:"#5e1b69",borderDim:"#3b0f42",bg:void 0,cardBg:"#240729",highlightBg:"#310938",activeBg:"#470e52",inputBg:"#310938",inputBorder:"#310938",inputText:"magenta",inputPlaceholder:"#7d2b8a",inputPrompt:"magenta",codeBg:"#100312",codeBorder:"#5e1b69",userMsgBg:"#310938",userMsgBorder:"#310938",userMsgText:"magenta",diffRemovalBg:"#3a0c20",diffAdditionBg:"#200c3a",diffRemovalText:"#ff4d94",diffAdditionText:"#aa4dff",diffRemovalHighlightColor:"#ff1a75",diffRemovalHighlightBg:"#59002b",diffAdditionHighlightColor:"#bb66ff",diffAdditionHighlightBg:"#3b0059",diffRemovalNum:"#ff4d94",diffAdditionNum:"#aa4dff",diffRemovalPrefix:"#ff1a75",diffAdditionPrefix:"#bb66ff",primary:"magenta",secondary:"cyan",accent:"purple",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"magenta",statusOff:"#7d2b8a",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ff00ff","#8800ff"]},{name:"Glitch Matrix",text:"#00ff41",textMuted:"#00b32d",textDim:"#00661a",textInverted:"black",border:"#00ff41",borderMuted:"#008020",borderDim:"#004d13",bg:void 0,cardBg:"#0d1f0d",highlightBg:"#122912",activeBg:"#1c3e1c",inputBg:"#122912",inputBorder:"#122912",inputText:"#00ff41",inputPlaceholder:"#00b32d",inputPrompt:"#ffff00",codeBg:"#040a04",codeBorder:"#008020",userMsgBg:"#122912",userMsgBorder:"#122912",userMsgText:"#00ff41",diffRemovalBg:"#3a001a",diffAdditionBg:"#003a10",diffRemovalText:"#ff0055",diffAdditionText:"#00ff66",diffRemovalHighlightColor:"#ff0033",diffRemovalHighlightBg:"#59001b",diffAdditionHighlightColor:"#33ff88",diffAdditionHighlightBg:"#005918",diffRemovalNum:"#ff0055",diffAdditionNum:"#00ff66",diffRemovalPrefix:"#ff0033",diffAdditionPrefix:"#33ff88",primary:"#00ff41",secondary:"yellow",accent:"cyan",success:"#00ff41",warning:"yellow",danger:"red",info:"cyan",statusOn:"#00ff41",statusOff:"#00661a",logoTextAnsi:"\x1B[1;32m",logoBodyAnsi:"\x1B[32m",logoMutedAnsi:"\x1B[90m",logoGradient:["#00ff41","#ffff00"]},{name:"Warm Sunset",text:"#ffaa55",textMuted:"#cc8844",textDim:"#885522",textInverted:"black",border:"#ff9933",borderMuted:"#aa6622",borderDim:"#663311",bg:void 0,cardBg:"#24180f",highlightBg:"#2e1e12",activeBg:"#422c1b",inputBg:"#2e1e12",inputBorder:"#2e1e12",inputText:"#ffaa55",inputPlaceholder:"#885522",inputPrompt:"#ff7733",codeBg:"#120c08",codeBorder:"#aa6622",userMsgBg:"#2e1e12",userMsgBorder:"#2e1e12",userMsgText:"#ffaa55",diffRemovalBg:"#3d120c",diffAdditionBg:"#3a2e0c",diffRemovalText:"#ff5544",diffAdditionText:"#ffcc33",diffRemovalHighlightColor:"#ff3322",diffRemovalHighlightBg:"#591108",diffAdditionHighlightColor:"#ffee44",diffAdditionHighlightBg:"#594400",diffRemovalNum:"#ff5544",diffAdditionNum:"#ffcc33",diffRemovalPrefix:"#ff3322",diffAdditionPrefix:"#ffee44",primary:"#ffaa55",secondary:"#ff7733",accent:"magenta",success:"#ffcc33",warning:"#ff7733",danger:"#ff3322",info:"#ffaa55",statusOn:"#ffaa55",statusOff:"#885522",logoTextAnsi:"\x1B[1;33m",logoBodyAnsi:"\x1B[33m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ff9933","#ff0055"]},{name:"Sakura Blossom",text:"#ffc0e0",textMuted:"#d98cb3",textDim:"#804d66",textInverted:"black",border:"#ff99cc",borderMuted:"#aa4d7a",borderDim:"#662647",bg:void 0,cardBg:"#291320",highlightBg:"#331826",activeBg:"#472235",inputBg:"#331826",inputBorder:"#331826",inputText:"#ffc0e0",inputPlaceholder:"#804d66",inputPrompt:"#ff99cc",codeBg:"#140a10",codeBorder:"#aa4d7a",userMsgBg:"#331826",userMsgBorder:"#331826",userMsgText:"#ffc0e0",diffRemovalBg:"#3e0c1b",diffAdditionBg:"#1b3e2b",diffRemovalText:"#ff6699",diffAdditionText:"#66ffb3",diffRemovalHighlightColor:"#ff3377",diffRemovalHighlightBg:"#590022",diffAdditionHighlightColor:"#33ff99",diffAdditionHighlightBg:"#00592e",diffRemovalNum:"#ff6699",diffAdditionNum:"#66ffb3",diffRemovalPrefix:"#ff3377",diffAdditionPrefix:"#33ff99",primary:"#ffc0e0",secondary:"#ff99cc",accent:"magenta",success:"#66ffb3",warning:"yellow",danger:"#ff3377",info:"#ff99cc",statusOn:"#ffc0e0",statusOff:"#804d66",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ffb3d9","#ff3399"]},{name:"Radioactive Slime",text:"#ccff00",textMuted:"#99cc00",textDim:"#669900",textInverted:"#0a0f00",border:"#ccff00",borderMuted:"#99cc00",borderDim:"#669900",bg:void 0,cardBg:"#0f1400",highlightBg:"#1a2400",activeBg:"#2a3b00",inputBg:"#1a2400",inputBorder:"#1a2400",inputText:"#ccff00",inputPlaceholder:"#669900",inputPrompt:"#cc00ff",codeBg:"#050a00",codeBorder:"#99cc00",userMsgBg:"#1a2400",userMsgBorder:"#1a2400",userMsgText:"#ccff00",diffRemovalBg:"#2a0033",diffAdditionBg:"#0f3300",diffRemovalText:"#ff00cc",diffAdditionText:"#00ff33",diffRemovalHighlightColor:"#ff33cc",diffRemovalHighlightBg:"#4d0066",diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:"#1a6600",diffRemovalNum:"#ff00cc",diffAdditionNum:"#00ff33",diffRemovalPrefix:"#ff33cc",diffAdditionPrefix:"#33ff66",primary:"#ccff00",secondary:"#cc00ff",accent:"#ff00cc",success:"#00ff33",warning:"#ffcc00",danger:"#ff0033",info:"#00ccff",statusOn:"#ccff00",statusOff:"#669900",logoTextAnsi:"\x1B[1;38;5;190m",logoBodyAnsi:"\x1B[38;5;190m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ccff00","#cc00ff"]},{name:"Cosmic Void",text:"#f0f8ff",textMuted:"#a6aeb5",textDim:"#5e656e",textInverted:"#010103",border:"#f0f8ff",borderMuted:"#a6aeb5",borderDim:"#5e656e",bg:void 0,cardBg:"#05030d",highlightBg:"#0b081a",activeBg:"#171133",inputBg:"#0b081a",inputBorder:"#0b081a",inputText:"#f0f8ff",inputPlaceholder:"#5e656e",inputPrompt:"#ff007f",codeBg:"#020108",codeBorder:"#a6aeb5",userMsgBg:"#0b081a",userMsgBorder:"#0b081a",userMsgText:"#f0f8ff",diffRemovalBg:"#2e0a29",diffAdditionBg:"#091c33",diffRemovalText:"#ff33a6",diffAdditionText:"#33d6ff",diffRemovalHighlightColor:"#ff66c2",diffRemovalHighlightBg:"#5c1452",diffAdditionHighlightColor:"#66e0ff",diffAdditionHighlightBg:"#123866",diffRemovalNum:"#ff33a6",diffAdditionNum:"#33d6ff",diffRemovalPrefix:"#ff66c2",diffAdditionPrefix:"#66e0ff",primary:"#f0f8ff",secondary:"#ff007f",accent:"#9d00ff",success:"#33d6ff",warning:"#ffcc00",danger:"#ff0040",info:"#9d00ff",statusOn:"#f0f8ff",statusOff:"#5e656e",logoTextAnsi:"\x1B[1;38;5;231m",logoBodyAnsi:"\x1B[38;5;231m",logoMutedAnsi:"\x1B[38;5;240m",logoGradient:["#ffffff","#9d00ff"]},{name:"Magma Eruption",text:"#ff4d00",textMuted:"#cc3d00",textDim:"#802600",textInverted:"#0d0300",border:"#ff4d00",borderMuted:"#cc3d00",borderDim:"#802600",bg:void 0,cardBg:"#1a0600",highlightBg:"#260a00",activeBg:"#401100",inputBg:"#260a00",inputBorder:"#260a00",inputText:"#ff4d00",inputPlaceholder:"#802600",inputPrompt:"#ffcc00",codeBg:"#080200",codeBorder:"#cc3d00",userMsgBg:"#260a00",userMsgBorder:"#260a00",userMsgText:"#ff4d00",diffRemovalBg:"#2e0a0a",diffAdditionBg:"#1f1400",diffRemovalText:"#ff3333",diffAdditionText:"#ffaa00",diffRemovalHighlightColor:"#ff6666",diffRemovalHighlightBg:"#5c1414",diffAdditionHighlightColor:"#ffcc33",diffAdditionHighlightBg:"#3d2900",diffRemovalNum:"#ff3333",diffAdditionNum:"#ffaa00",diffRemovalPrefix:"#ff6666",diffAdditionPrefix:"#ffcc33",primary:"#ff4d00",secondary:"#ffcc00",accent:"#ff0040",success:"#ffaa00",warning:"#ffff00",danger:"#ff0000",info:"#ff8800",statusOn:"#ff4d00",statusOff:"#802600",logoTextAnsi:"\x1B[1;38;5;202m",logoBodyAnsi:"\x1B[38;5;202m",logoMutedAnsi:"\x1B[38;5;236m",logoGradient:["#ff4d00","#ff0000"]}],Eo={Dark:{id:"Dark",name:"Dark (Default)",text:"white",textMuted:"gray",textDim:"grey",textInverted:"black",textExclusive:"#B5B8D9",textMutedExclusive:"#D4DEE7",border:"white",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:"#1e1e1e",highlightBg:"#2a2a2a",activeBg:"#3a3a3a",inputBg:"#555555",inputBorder:"#555555",inputText:"white",inputPlaceholder:"#cccccc",inputPrompt:"white",codeBg:"#1a1a1a",codeBorder:"#444444",userMsgBg:"#444444",userMsgBorder:"#444444",userMsgText:"white",diffRemovalBg:"#250808",diffAdditionBg:"#072410",diffRemovalText:"#885555",diffAdditionText:"#558866",diffRemovalHighlightColor:"#ff3333",diffRemovalHighlightBg:"#5a1818",diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:"#185a25",diffRemovalNum:"#d96868",diffAdditionNum:"#68d98c",diffRemovalPrefix:"#ff4d4d",diffAdditionPrefix:"#4dff88",primary:"white",secondary:"cyan",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"white",statusOff:"gray",logoTextAnsi:"\x1B[1;37m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#0077ff","#ff00ff"]},Light:{id:"Light",name:"Light",text:"black",textMuted:"gray",textDim:"grey",textInverted:"white",border:"black",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:"#e5e5e5",highlightBg:"#d4d4d4",activeBg:"#c0c0c0",inputBg:"#d0d0d0",inputBorder:"#d0d0d0",inputText:"black",inputPlaceholder:"#555555",inputPrompt:"black",codeBg:"#e8e8e8",codeBorder:"#b0b0b0",userMsgBg:"#d0d0d0",userMsgBorder:"#d0d0d0",userMsgText:"black",diffRemovalBg:"#fce8e8",diffAdditionBg:"#e6f9e6",diffRemovalText:"#661111",diffAdditionText:"#115511",diffRemovalHighlightColor:"#440000",diffRemovalHighlightBg:"#f8b4b4",diffAdditionHighlightColor:"#003300",diffAdditionHighlightBg:"#a6ebad",diffRemovalNum:"#c02020",diffAdditionNum:"#188028",diffRemovalPrefix:"#d01010",diffAdditionPrefix:"#109020",primary:"black",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"black",statusOff:"gray",logoTextAnsi:"\x1B[1;30m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#0077ff","#ff00ff"]},"GitHub Dark":{id:"GitHub Dark",name:"GitHub Dark",text:"#c9d1d9",textMuted:"#8b949e",textDim:"#6e7681",textInverted:"#0d1117",border:"#30363d",borderMuted:"#30363d",borderDim:"#21262d",bg:void 0,cardBg:"#161b22",highlightBg:"#21262d",activeBg:"#30363d",inputBg:"#21262d",inputBorder:"#21262d",inputText:"#c9d1d9",inputPlaceholder:"#8b949e",inputPrompt:"#58a6ff",codeBg:"#0d1117",codeBorder:"#30363d",userMsgBg:"#21262d",userMsgBorder:"#21262d",userMsgText:"#c9d1d9",diffRemovalBg:"#3c1e1e",diffAdditionBg:"#11381e",diffRemovalText:"#f85149",diffAdditionText:"#3fb950",diffRemovalHighlightColor:"#ff7b72",diffRemovalHighlightBg:"#701c1c",diffAdditionHighlightColor:"#56d364",diffAdditionHighlightBg:"#116329",diffRemovalNum:"#f85149",diffAdditionNum:"#3fb950",diffRemovalPrefix:"#f85149",diffAdditionPrefix:"#3fb950",primary:"#c9d1d9",secondary:"#58a6ff",accent:"#bc8cff",success:"#3fb950",warning:"#d29922",danger:"#f85149",info:"#58a6ff",statusOn:"#58a6ff",statusOff:"#8b949e",logoTextAnsi:"\x1B[1;36m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#2ea043","#56d364"]},"GitHub Light":{id:"GitHub Light",name:"GitHub Light",text:"#24292f",textMuted:"#57606a",textDim:"#6e7781",textInverted:"#ffffff",border:"#d0d7de",borderMuted:"#d0d7de",borderDim:"#e1e4e8",bg:void 0,cardBg:"#f6f8fa",highlightBg:"#eaeef2",activeBg:"#d0d7de",inputBg:"#eaeef2",inputBorder:"#eaeef2",inputText:"#24292f",inputPlaceholder:"#57606a",inputPrompt:"#0969da",codeBg:"#ffffff",codeBorder:"#d0d7de",userMsgBg:"#eaeef2",userMsgBorder:"#eaeef2",userMsgText:"#24292f",diffRemovalBg:"#ffebe9",diffAdditionBg:"#e6ffec",diffRemovalText:"#cf222e",diffAdditionText:"#1a7f37",diffRemovalHighlightColor:"#82071e",diffRemovalHighlightBg:"#ffc1c0",diffAdditionHighlightColor:"#116329",diffAdditionHighlightBg:"#acf2bd",diffRemovalNum:"#cf222e",diffAdditionNum:"#1a7f37",diffRemovalPrefix:"#cf222e",diffAdditionPrefix:"#1a7f37",primary:"#24292f",secondary:"#0969da",accent:"#8250df",success:"#1a7f37",warning:"#9a6700",danger:"#cf222e",info:"#0969da",statusOn:"#0969da",statusOff:"#57606a",logoTextAnsi:"\x1B[1;34m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#1a7f37","#2da44e"]},"Transparent Dark":{id:"Transparent Dark",name:"Transparent Dark",text:"white",textMuted:"gray",textDim:"grey",textInverted:"black",border:"gray",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:void 0,highlightBg:"#2a2a2a",activeBg:"#3a3a3a",inputBg:"#555555",inputBorder:"#555555",inputText:"white",inputPlaceholder:"#cccccc",inputPrompt:"white",codeBg:void 0,codeBorder:"gray",userMsgBg:"#555555",userMsgBorder:"#555555",userMsgText:"white",diffRemovalBg:void 0,diffAdditionBg:void 0,diffRemovalText:"#ff6666",diffAdditionText:"#66ff66",diffRemovalHighlightColor:"#ff3333",diffRemovalHighlightBg:void 0,diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:void 0,diffRemovalNum:"#ff6666",diffAdditionNum:"#66ff66",diffRemovalPrefix:"#ff4d4d",diffAdditionPrefix:"#4dff88",primary:"white",secondary:"cyan",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"white",statusOff:"gray",logoTextAnsi:"\x1B[1;37m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#0077ff","#ff00ff"]},"Transparent Light":{id:"Transparent Light",name:"Transparent Light",text:"black",textMuted:"gray",textDim:"grey",textInverted:"white",border:"gray",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:void 0,highlightBg:"#d4d4d4",activeBg:"#c0c0c0",inputBg:"#d0d0d0",inputBorder:"#d0d0d0",inputText:"black",inputPlaceholder:"#555555",inputPrompt:"black",codeBg:void 0,codeBorder:"gray",userMsgBg:"#d0d0d0",userMsgBorder:"#d0d0d0",userMsgText:"black",diffRemovalBg:void 0,diffAdditionBg:void 0,diffRemovalText:"#c02020",diffAdditionText:"#188028",diffRemovalHighlightColor:"#800000",diffRemovalHighlightBg:void 0,diffAdditionHighlightColor:"#004000",diffAdditionHighlightBg:void 0,diffRemovalNum:"#c02020",diffAdditionNum:"#188028",diffRemovalPrefix:"#d01010",diffAdditionPrefix:"#109020",primary:"black",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"black",statusOff:"gray",logoTextAnsi:"\x1B[1;30m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#0077ff","#ff00ff"]},"Synthwave 84":{id:"Synthwave 84",name:"Synthwave 84",text:"#fdfdfd",textMuted:"#a08eb7",textDim:"#705c8a",textInverted:"#1a1025",textExclusive:"#e3dcf0",textMutedExclusive:"#b9abc9",border:"#fc28a8",borderMuted:"#a21568",borderDim:"#5c0a3a",bg:void 0,cardBg:"#261b38",highlightBg:"#35254d",activeBg:"#4c3570",inputBg:"#35254d",inputBorder:"#35254d",inputText:"#fdfdfd",inputPlaceholder:"#a08eb7",inputPrompt:"#03e8fc",codeBg:"#1e142b",codeBorder:"#a21568",userMsgBg:"#35254d",userMsgBorder:"#35254d",userMsgText:"#fdfdfd",diffRemovalBg:"#471434",diffAdditionBg:"#144743",diffRemovalText:"#ff4081",diffAdditionText:"#00e5ff",diffRemovalHighlightColor:"#ff79a1",diffRemovalHighlightBg:"#6b1e4e",diffAdditionHighlightColor:"#66f5ff",diffAdditionHighlightBg:"#1e6b65",diffRemovalNum:"#ff4081",diffAdditionNum:"#00e5ff",diffRemovalPrefix:"#ff79a1",diffAdditionPrefix:"#66f5ff",primary:"#fdfdfd",secondary:"#03e8fc",accent:"#fc28a8",success:"#00e5ff",warning:"#ffc107",danger:"#ff4081",info:"#b388ff",statusOn:"#03e8fc",statusOff:"#a08eb7",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#fc28a8","#03e8fc"]},"Forest Sprite":{id:"Forest Sprite",name:"Forest Sprite",text:"#d6e6d1",textMuted:"#95b38d",textDim:"#628059",textInverted:"#161c14",textExclusive:"#eaf2e8",textMutedExclusive:"#a9c7a2",border:"#74a862",borderMuted:"#477038",borderDim:"#2b4720",bg:void 0,cardBg:"#1f291c",highlightBg:"#2a3826",activeBg:"#3a4d35",inputBg:"#2a3826",inputBorder:"#2a3826",inputText:"#d6e6d1",inputPlaceholder:"#95b38d",inputPrompt:"#8feb73",codeBg:"#161e14",codeBorder:"#477038",userMsgBg:"#2a3826",userMsgBorder:"#2a3826",userMsgText:"#d6e6d1",diffRemovalBg:"#3b231c",diffAdditionBg:"#203b1c",diffRemovalText:"#db6242",diffAdditionText:"#59cc3f",diffRemovalHighlightColor:"#f0896c",diffRemovalHighlightBg:"#5c362a",diffAdditionHighlightColor:"#80e368",diffAdditionHighlightBg:"#305929",diffRemovalNum:"#db6242",diffAdditionNum:"#59cc3f",diffRemovalPrefix:"#f0896c",diffAdditionPrefix:"#80e368",primary:"#d6e6d1",secondary:"#8feb73",accent:"#e69835",success:"#59cc3f",warning:"#e69835",danger:"#db6242",info:"#73b4eb",statusOn:"#8feb73",statusOff:"#95b38d",logoTextAnsi:"\x1B[1;32m",logoBodyAnsi:"\x1B[32m",logoMutedAnsi:"\x1B[90m",logoGradient:["#8feb73","#e69835"]}};var Jo=null;var kr=(e="Dark")=>{let n;e==="Mystery"||e==="Chaos"?(Jo||(Jo=Tr[Math.floor(Math.random()*Tr.length)]),n={...Jo,id:"Mystery"}):(Jo=null,Eo[e]?n=Eo[e]:e==="GitHub"?n=Eo["GitHub Dark"]:e==="Transparent"?n=Eo["Transparent Dark"]:n=Eo.Dark);let t=n.codeText||n.secondary||n.info||n.logoGradient&&n.logoGradient[0]||"cyan";return{...n,codeText:t}};var pa=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",nc=(e=2)=>{let n=pa();return n==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)},oc=(e="...",n="Loading...",t="Dark")=>{let i=Di[Math.floor(Math.random()*Di.length)],o=kr(t),r=n;if(n==="c_openai"||n==="Custom (OpenAI)")try{let k=cs(ls,{})?.systemSettings?.customOpenAIBaseUrl;k&&(r=k)}catch{}let c=o.logoTextAnsi,a=o.logoBodyAnsi,g=o.logoMutedAnsi,m="\x1B[0m",y=[" \u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2588\u2588\u2588\u2591 "," \u2588\u2588\u2588\u2591 "," \u2588\u2588\u2588\u2591 "," \u2591\u2591\u2591 "],h=o.logoGradient||["#0077ff","#ff00ff"],f=ha(h).multiline(y.join(`
559
559
  `)).split(`
560
- `),s=u=>`${h}${u}${g}`;return`${f[0]}
561
- ${f[1]} ${c}Selected Provider: ${r}${g}
560
+ `),s=u=>`${g}${u}${m}`;return`${f[0]}
561
+ ${f[1]} ${c}Selected Provider: ${r}${m}
562
562
  ${f[2]}
563
- ${f[3]} ${c}FluxFlow ${s("v"+e)}${g}
563
+ ${f[3]} ${c}FluxFlow ${s("v"+e)}${m}
564
564
  ${f[4]}
565
- ${f[5]} ${a}See /help for additional commands.${g}
565
+ ${f[5]} ${a}See /help for additional commands.${m}
566
566
  ${f[6]} ${s(i)}
567
567
  ${f[7]}
568
- `};import{WebSocket as Jo}from"ws";var Pt=null,Zn=!1,ya="ws://localhost:56832",Fi=[],eo=null,Bi=null,Ar="2.0.0",rc=e=>{Ar=e,Cr()},Ui=e=>{Bi=e},Cr=()=>{if(Pt||Zn)return;Zn=!0;let e=new Jo(ya);e.on("open",()=>{for(Pt=e,Zn=!1,Pt.send(JSON.stringify({command:"version",version:Ar,pid:process.pid,ppid:process.ppid}));Fi.length>0;)Pt.send(JSON.stringify(Fi.shift()))}),e.on("message",n=>{try{let t=JSON.parse(n.toString());t.command==="contextResponse"&&eo?(eo(t.data),eo=null):t.command==="securityResponse"&&Bi&&Bi(t.result)}catch{}}),e.on("error",()=>{Zn=!1,Pt=null}),e.on("close",()=>{Zn=!1,Pt=null})},Qo=e=>{Pt&&Pt.readyState===Jo.OPEN?Pt.send(JSON.stringify(e)):(Fi.push(e),Zn||Cr())},Zo=()=>Pt!==null&&Pt.readyState===Jo.OPEN,ac=e=>{Qo({command:"status",status:e})},jn=()=>new Promise(e=>{if(!Pt||Pt.readyState!==Jo.OPEN){e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]});return}eo=e,Pt.send(JSON.stringify({command:"requestContext"})),setTimeout(()=>{eo===e&&(e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]}),eo=null)},1e3)}),Rr=e=>{Qo({command:"open",filePath:e})},Wi=(e,n,t)=>{Qo({command:"showDiff",filePath:e,originalContent:n,modifiedContent:t})},Er=(e,n)=>{Qo({command:"closeDiff",filePath:e,result:n})};import Gi from"path";import xa from"fs";var ba=e=>{try{return xa.readdirSync(e,{withFileTypes:!0})}catch{return[]}},Hi=(e,n=4,t=1,i=ba,o=[],r=null)=>{let c=r||i(e),a=" ".repeat(t-1),h=t===1?new Set([...fo,...o,...uo(e),...uo(process.cwd())]):o instanceof Set?o:new Set([...fo,...o]),g=D=>h.has(D),y=c.filter(D=>!g(D.name)),m=c.filter(D=>g(D.name)).length,f=y.filter(D=>!D.isDirectory()).map(D=>D.name).sort(),s=y.filter(D=>D.isDirectory()).sort((D,A)=>D.name.localeCompare(A.name)),u=D=>{let A=D.length;if(A===0)return"no files";let ge=Array.from(new Set(D.map(Me=>{let ye=typeof Me=="string"?Me:Me.name;return Gi.extname(ye).slice(1)}).filter(Boolean))).sort(),we="*";return ge.length===1?we=`*.${ge[0]}`:ge.length>1&&(we=`*.{${ge.join(", ")}}`),A===1?we:`${we} ${A} files`},k="";if(t===1){let D=f.join(", "),A=m>0?` [${m} ignored]`:"";(D||A)&&(k+=`${a}${D?D+(A?`${A}`:""):A.trim()}
568
+ `};import{WebSocket as Qo}from"ws";var Pt=null,Zn=!1,ya="ws://localhost:56832",Fi=[],eo=null,Bi=null,Ar="2.0.0",rc=e=>{Ar=e,Cr()},Ui=e=>{Bi=e},Cr=()=>{if(Pt||Zn)return;Zn=!0;let e=new Qo(ya);e.on("open",()=>{for(Pt=e,Zn=!1,Pt.send(JSON.stringify({command:"version",version:Ar,pid:process.pid,ppid:process.ppid}));Fi.length>0;)Pt.send(JSON.stringify(Fi.shift()))}),e.on("message",n=>{try{let t=JSON.parse(n.toString());t.command==="contextResponse"&&eo?(eo(t.data),eo=null):t.command==="securityResponse"&&Bi&&Bi(t.result)}catch{}}),e.on("error",()=>{Zn=!1,Pt=null}),e.on("close",()=>{Zn=!1,Pt=null})},Zo=e=>{Pt&&Pt.readyState===Qo.OPEN?Pt.send(JSON.stringify(e)):(Fi.push(e),Zn||Cr())},ei=()=>Pt!==null&&Pt.readyState===Qo.OPEN,ac=e=>{Zo({command:"status",status:e})},jn=()=>new Promise(e=>{if(!Pt||Pt.readyState!==Qo.OPEN){e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]});return}eo=e,Pt.send(JSON.stringify({command:"requestContext"})),setTimeout(()=>{eo===e&&(e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]}),eo=null)},1e3)}),Rr=e=>{Zo({command:"open",filePath:e})},Wi=(e,n,t)=>{Zo({command:"showDiff",filePath:e,originalContent:n,modifiedContent:t})},Er=(e,n)=>{Zo({command:"closeDiff",filePath:e,result:n})};import Gi from"path";import xa from"fs";var ba=e=>{try{return xa.readdirSync(e,{withFileTypes:!0})}catch{return[]}},Hi=(e,n=4,t=1,i=ba,o=[],r=null)=>{let c=r||i(e),a=" ".repeat(t-1),g=t===1?new Set([...fo,...o,...uo(e),...uo(process.cwd())]):o instanceof Set?o:new Set([...fo,...o]),m=D=>g.has(D),y=c.filter(D=>!m(D.name)),h=c.filter(D=>m(D.name)).length,f=y.filter(D=>!D.isDirectory()).map(D=>D.name).sort(),s=y.filter(D=>D.isDirectory()).sort((D,A)=>D.name.localeCompare(A.name)),u=D=>{let A=D.length;if(A===0)return"no files";let ge=Array.from(new Set(D.map(Me=>{let ye=typeof Me=="string"?Me:Me.name;return Gi.extname(ye).slice(1)}).filter(Boolean))).sort(),we="*";return ge.length===1?we=`*.${ge[0]}`:ge.length>1&&(we=`*.{${ge.join(", ")}}`),A===1?we:`${we} ${A} files`},k="";if(t===1){let D=f.join(", "),A=h>0?` [${h} ignored]`:"";(D||A)&&(k+=`${a}${D?D+(A?`${A}`:""):A.trim()}
569
569
  `)}else f.length>0&&(k+=`${a}[${u(f)}]
570
- `);let he=10,x=s.slice(0,he),I=s.length>he,G=[],q=[];for(let D of x){let A=Gi.join(e,D.name),ge=D.name,we=t,Me=i(A),ye=Me.filter(Oe=>!g(Oe.name)),T=ye.filter(Oe=>Oe.isDirectory()),b=ye.filter(Oe=>!Oe.isDirectory());for(;b.length===0&&T.length===1&&we<n;)ge=`${ge}/${T[0].name}`,A=Gi.join(A,T[0].name),we++,Me=i(A),ye=Me.filter(Oe=>!g(Oe.name)),T=ye.filter(Oe=>Oe.isDirectory()),b=ye.filter(Oe=>!Oe.isDirectory());let rt=T.length>0;if(rt&&we<n)q.push({displayName:ge,subDirPath:A,subEntries:Me,nextDepth:we+1});else{let Oe=u(b),jt=rt&&we>=n?" ...max scan depth":"";G.push(`${ge}/${Oe}${jt}`)}}G.length>0&&(k+=`${a}${G.join(", ")}
570
+ `);let he=10,x=s.slice(0,he),I=s.length>he,H=[],q=[];for(let D of x){let A=Gi.join(e,D.name),ge=D.name,we=t,Me=i(A),ye=Me.filter(Oe=>!m(Oe.name)),T=ye.filter(Oe=>Oe.isDirectory()),b=ye.filter(Oe=>!Oe.isDirectory());for(;b.length===0&&T.length===1&&we<n;)ge=`${ge}/${T[0].name}`,A=Gi.join(A,T[0].name),we++,Me=i(A),ye=Me.filter(Oe=>!m(Oe.name)),T=ye.filter(Oe=>Oe.isDirectory()),b=ye.filter(Oe=>!Oe.isDirectory());let rt=T.length>0;if(rt&&we<n)q.push({displayName:ge,subDirPath:A,subEntries:Me,nextDepth:we+1});else{let Oe=u(b),jt=rt&&we>=n?" ...max scan depth":"";H.push(`${ge}/${Oe}${jt}`)}}H.length>0&&(k+=`${a}${H.join(", ")}
571
571
  `);for(let{displayName:D,subDirPath:A,subEntries:ge,nextDepth:we}of q)k+=`${a}${D}/
572
- `,k+=Hi(A,n,we,i,h,ge);return I&&(k+=`${a}...max scan width, ReadFolder if needed
572
+ `,k+=Hi(A,n,we,i,g,ge);return I&&(k+=`${a}...max scan width, ReadFolder if needed
573
573
  `),k};import ji from"path";import wa from"fs";var Sa=e=>{try{return wa.readdirSync(e,{withFileTypes:!0})}catch{return[]}},Vi=(e,n,t="",i=1,o=Sa,r=[])=>{let c=o(e),a=ji.sep;if(c.length>100)return`${t}\u2514\u2500\u2500 ${ji.basename(e)}${a} ...100+ files...
574
- `;let h="",g=r,y=c.filter(s=>!g.includes(s.name)&&!s.name.startsWith(".")),m=c.filter(s=>g.includes(s.name)||s.name.startsWith(".")).map(s=>s.name).sort();y.sort((s,u)=>s.isDirectory()&&!u.isDirectory()?-1:!s.isDirectory()&&u.isDirectory()?1:s.name.localeCompare(u.name));let f=[...y.map(s=>({name:s.name,isDir:s.isDirectory()})),...m.map(s=>({name:s,isDir:!0,isCollapsed:!0}))];return f.forEach((s,u)=>{let k=u===f.length-1,he=ji.join(e,s.name),x=k?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",I=t+(k?" ":"\u2502 ");if(s.isCollapsed){h+=`${t}${x}${s.name}${a}...
575
- `;return}s.isDir?i>n?h+=`${t}${x}${s.name}${a} ...depth exceeded...
576
- `:o(he).length>80?h+=`${t}${x}${s.name}${a} ...80+ files...
577
- `:(h+=`${t}${x}${s.name}${a}
578
- `,h+=Vi(he,n,I,i+1,o,r)):h+=`${t}${x}${s.name}
579
- `}),h};var Ta={Ollama:()=>import("./ollama-ZPTZJK7V.js").then(e=>e.getOllamaStream),OpenRouter:()=>import("./openrouter-T22AQJY6.js").then(e=>e.getOpenRouterStream),DeepSeek:()=>import("./deepseek-Y4NFGKGV.js").then(e=>e.getDeepSeekStream),Mistral:()=>import("./mistral-N6352JPY.js").then(e=>e.getMistralStream),NVIDIA:()=>import("./nvidia-L6QMFBL3.js").then(e=>e.getNVIDIAStream),NVIDIA_wrap:()=>import("./nvidia-L6QMFBL3.js").then(e=>e.wrapNvidiaStreamWithQueueDepth),InferX:()=>import("./inferx-R7LOBSCS.js").then(e=>e.getInferXStream),SenseNova:()=>import("./sensenova-AJZGPQZ5.js").then(e=>e.getSenseNovaStream),AIHubMix:()=>import("./aihubmix-ZANBMI5F.js").then(e=>e.getAIHubMixStream),Poolside:()=>import("./poolside-IS5XCHAE.js").then(e=>e.getPoolsideStream),NineRouter:()=>import("./9router-4EJCHCIO.js").then(e=>e.getNineRouterStream),ExpLabs:()=>import("./explabs-4D3EJOBE.js").then(e=>e.getExpLabsStream),TokenHarbor:()=>import("./tokenharbor-3ZMTIJ2M.js").then(e=>e.getTokenHarborStream),Infron:()=>import("./infron-DMF34OSO.js").then(e=>e.getInfronStream),APInex:()=>import("./apinex-MSG2QNBL.js").then(e=>e.getAPInexStream),c_openai:()=>import("./custom_openai-VP2CSZUQ.js").then(e=>e.getCustomOpenAIStream)},Ki={},ce=async e=>(Ki[e]||(Ki[e]=await Ta[e]()),Ki[e]),ka=/```[\s\S]*?```/g,Aa=/```[\s\S]*$/g,Ca=/`[^`]+`/g,Ra=/^\|.*\|$/gm,Ea=/^[^\w]+|[^\w]+$/g,va=/[^a-z0-9]/gi,Co=/\[\s*(?:tool|action):(?:functions\.)?([a-z0-9_]+)\s*\(/gi,_a=/\[\s*(?:tool:(?:functions\.)?|action:(?:functions\.)?|action:)([a-z0-9_]+)\s*\(/gi,Ia=/(?:path|targetFile|TargetFile|directory|keyword|id|taskId|title|task)\s*=\s*\\?["']?([^\\"' \),]+)/,kn=/["']/g,vr=/\\/g,Ma=/<\|channel>thought/gi,Oa=/<channel\|>/gi,Pa=e=>typeof e!="string"?e:e.replace(Ma,"<think>").replace(Oa,"</think>"),Kc=/^\s*(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\]|$)/i,La=(e,n,t=1)=>{let i=n>0?e[n-1]:"",o=n+t<e.length?e[n+t]:"";return i==="`"&&o==="`"},$a=e=>{let n=/(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\])/gi,t;for(;(t=n.exec(e))!==null;)if(!La(e,t.index,t[0].length))return{index:t.index,length:t[0].length};return{index:-1,length:0}},Yi=e=>{if(!e||typeof e!="string")return null;let n=e.match(/^\s*(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought|\[(think|thought|thoughts)\])/i);if(!n)return null;let t=n.index+n[0].length,i=e.substring(t),o=$a(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=Yi(e);return n?n.remainingText.trimStart():e};var _r=/<\|\s*tool_call_begin\s*\|>\s*(?:(?:tool|functions)\b[\s._]*)*([a-zA-Z0-9_]+)(?::\d+)?\s*<\|\s*tool_call_argument_begin\s*\|>([\s\S]*?)<\|\s*tool_call_end\s*\|>/gi,Na=/"([^"]+)"\s*:\s*(?:"([^"]*)"|(\d+)|true|false|null)/g,Ir=/<\|\s*tool_calls_section_begin\s*\|>/gi,Mr=/<\|\s*tool_calls_section_end\s*\|>/gi,Da=/```(?:tool|action|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi;var ei=e=>!e||typeof e!="string"?e:e.replace(/(```[\s\S]*?```|`[^`]*`)|(<(?:\w+)(?:[^>]*)>\r?\n?|\r?\n?<\/\w+(?:[^>]*)>)/gi,(n,t)=>t||""),$r=e=>{if(!e||typeof e!="string")return e;let n=to(e);if(!n||n.length===0)return e;let t=n[n.length-1];if(!t.fullMatch)return e;let i=e.lastIndexOf(t.fullMatch);if(i===-1)return e;let o=i+t.fullMatch.length;return e.substring(0,o).trimEnd()},qi=null,ti={},Vn={key:null,value:null},Ht=e=>e&&e.replace(/(?:(\x1b\[\d+m))?([✔✘✖🔍📖→➕↻↷•🛇])(?:(\x1b\[\d+m))?\s*\b(Clicked|Located|Dragged|Scrolled|Typed|Pressed Key|Recaptured Screen|Created|Read Skill|Read Documentation|Searched Documentation|Read|Edited|Viewed|Processed|Auto-Read|Skipped|List|Generated|Written|Searched|AI Search|Get Map|Write Canceled|Resolved Sub-Agent Query|Edit Canceled|Write Cancelled|Edit Denied|Visited|Updated|Reviewed|Delegated|Background|Checked|Indexed|Analyzed|Browsed|Elevating SubAgent|Checking SubAgent Work|Started Generalist|Called Generalist|Steered|Unsupported Modality|Awaiting|Cancelled|Aligning Moon Phase|Contemplating Existence|Staring At Void|Rollback Point Checked|Emergency Rollback Failed|Emergency Rollback|Delaying Professionally|Negotiating With Electrons|Touching Grass (virtually)|Panicking Softly|Rethinking Career Choices|Loading Cat Videos|Giving Up Entirely|Summoning Braincell #2|Pretending To Be Busy|Waiting For Motivation DLC|Rotating Internal Screaming|Downloading More RAM|Feeding The Hamsters|Gaslighting Scheduler|Performing Dramatic Pause|Buffering Social Energy|Calculating Regret|Reading Terms And Conditions|Becoming Sentient Briefly|Model produced malformed tool call|Loop Detected|Contacting Ancestors)\b/ig,(n,t,i,o,r)=>`${t||""}${i}${o||""} \x1B[95m${r}\x1B[0m`),Fa=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((h,g)=>{let y=setTimeout(h,a);o&&o.addEventListener("abort",()=>{clearTimeout(y),g(new DOMException("The user aborted a request.","AbortError"))})})}}},mt=!1;var Ba=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 h=a.indexOf("**CONTEXT SUMMARY OF PREVIOUS TURNS");if(h!==-1){let y=a.substring(0,h).lastIndexOf("[SYSTEM METADATA]");y!==-1?a=a.substring(y).trim():a=a.substring(h).trim()}}else{let h=a.lastIndexOf("[USER]"),g=a.lastIndexOf("[USER PROMPT]");h!==-1?a=a.substring(h+6).trim():g!==-1&&(a=a.substring(g).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=[],h=!1,g=()=>{c.length>0&&(t.push({role:"agent",text:"combined"}),c=[]),a.length>0&&(t.push({role:"system",text:"combined"}),a=[]),h=!1};r.forEach(y=>{let m=y.role==="system"&&(y.text?.startsWith("[ACTION RESULT]")||y.text?.startsWith("[TOOL RESULT]")||y.text?.startsWith("SUCCESS:")||y.text?.startsWith("ERROR:")||y.fullText?.startsWith("[ACTION RESULT]")||y.fullText?.startsWith("[TOOL RESULT]")||y.fullText?.startsWith("SUCCESS:")||y.fullText?.startsWith("ERROR:")),f=y.fullText||y.text||"",s=f.trim();if(!(!s&&!y.binaryPart)){if(m)a.push(s);else if(y.role==="agent"){!h&&a.length>0&&g();let u=f.endsWith(`
580
- `),k=s.toLowerCase().includes("tool:")||s.toLowerCase().includes("action:");c.push(s),k&&u?h=!0:h=!1}}}),g()}}return t.length},Ua=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),Yc=()=>{mt=!0},zc=()=>mt,zi={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"},Kn=(e,n)=>{try{let t=W(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?j.basename(o.replace(/["']/g,"").replace(/\\/g,"/")):null}catch{return null}},Xi=e=>e?new Lr({apiKey:e}):qi,qc=async(e,n,t,i,o={})=>{let{onStatus:a,onMemoryUpdated:h,onBackgroundIncrement:g}=o,{profile:y,thinkingLevel:m,mode:f,janitorModel:s,chatId:u,systemSettings:k,sessionStats:he,aiProvider:x="Google",apiKey:I}=e,G=process.env.NVIDIA_BASE_URL||x==="Ollama"||x==="InferX"||x==="SenseNova"||x==="AIHubMix"||x==="Poolside"||x==="9router"||x==="ExpLabs"||x==="ExperientialLabs"||x==="c_openai"||x==="Custom (OpenAI)"?!1:k?.memory!==!1,D=Rt(Hn,[]).map(S=>`- [${S.id}]: ${S.memory}`).join(`
574
+ `;let g="",m=r,y=c.filter(s=>!m.includes(s.name)&&!s.name.startsWith(".")),h=c.filter(s=>m.includes(s.name)||s.name.startsWith(".")).map(s=>s.name).sort();y.sort((s,u)=>s.isDirectory()&&!u.isDirectory()?-1:!s.isDirectory()&&u.isDirectory()?1:s.name.localeCompare(u.name));let f=[...y.map(s=>({name:s.name,isDir:s.isDirectory()})),...h.map(s=>({name:s,isDir:!0,isCollapsed:!0}))];return f.forEach((s,u)=>{let k=u===f.length-1,he=ji.join(e,s.name),x=k?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",I=t+(k?" ":"\u2502 ");if(s.isCollapsed){g+=`${t}${x}${s.name}${a}...
575
+ `;return}s.isDir?i>n?g+=`${t}${x}${s.name}${a} ...depth exceeded...
576
+ `:o(he).length>80?g+=`${t}${x}${s.name}${a} ...80+ files...
577
+ `:(g+=`${t}${x}${s.name}${a}
578
+ `,g+=Vi(he,n,I,i+1,o,r)):g+=`${t}${x}${s.name}
579
+ `}),g};var Ta={Ollama:()=>import("./ollama-ZPTZJK7V.js").then(e=>e.getOllamaStream),OpenRouter:()=>import("./openrouter-T22AQJY6.js").then(e=>e.getOpenRouterStream),DeepSeek:()=>import("./deepseek-Y4NFGKGV.js").then(e=>e.getDeepSeekStream),Mistral:()=>import("./mistral-N6352JPY.js").then(e=>e.getMistralStream),NVIDIA:()=>import("./nvidia-L6QMFBL3.js").then(e=>e.getNVIDIAStream),NVIDIA_wrap:()=>import("./nvidia-L6QMFBL3.js").then(e=>e.wrapNvidiaStreamWithQueueDepth),InferX:()=>import("./inferx-R7LOBSCS.js").then(e=>e.getInferXStream),SenseNova:()=>import("./sensenova-AJZGPQZ5.js").then(e=>e.getSenseNovaStream),AIHubMix:()=>import("./aihubmix-ZANBMI5F.js").then(e=>e.getAIHubMixStream),Poolside:()=>import("./poolside-IS5XCHAE.js").then(e=>e.getPoolsideStream),NineRouter:()=>import("./9router-4EJCHCIO.js").then(e=>e.getNineRouterStream),ExpLabs:()=>import("./explabs-4D3EJOBE.js").then(e=>e.getExpLabsStream),TokenHarbor:()=>import("./tokenharbor-3ZMTIJ2M.js").then(e=>e.getTokenHarborStream),Infron:()=>import("./infron-DMF34OSO.js").then(e=>e.getInfronStream),APInex:()=>import("./apinex-MSG2QNBL.js").then(e=>e.getAPInexStream),c_openai:()=>import("./custom_openai-VP2CSZUQ.js").then(e=>e.getCustomOpenAIStream)},Ki={},ce=async e=>(Ki[e]||(Ki[e]=await Ta[e]()),Ki[e]),ka=/```[\s\S]*?```/g,Aa=/```[\s\S]*$/g,Ca=/`[^`]+`/g,Ra=/^\|.*\|$/gm,Ea=/^[^\w]+|[^\w]+$/g,va=/[^a-z0-9]/gi,vo=/\[\s*(?:tool|action):(?:functions\.)?([a-z0-9_]+)\s*\(/gi,_a=/\[\s*(?:tool:(?:functions\.)?|action:(?:functions\.)?|action:)([a-z0-9_]+)\s*\(/gi,Ia=/(?:path|targetFile|TargetFile|directory|keyword|id|taskId|title|task)\s*=\s*\\?["']?([^\\"' \),]+)/,An=/["']/g,vr=/\\/g,Ma=/<\|channel>thought/gi,Oa=/<channel\|>/gi,Pa=e=>typeof e!="string"?e:e.replace(Ma,"<think>").replace(Oa,"</think>"),Kc=/^\s*(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\]|$)/i,La=(e,n,t=1)=>{let i=n>0?e[n-1]:"",o=n+t<e.length?e[n+t]:"";return i==="`"&&o==="`"},$a=e=>{let n=/(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\])/gi,t;for(;(t=n.exec(e))!==null;)if(!La(e,t.index,t[0].length))return{index:t.index,length:t[0].length};return{index:-1,length:0}},Yi=e=>{if(!e||typeof e!="string")return null;let n=e.match(/^\s*(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought|\[(think|thought|thoughts)\])/i);if(!n)return null;let t=n.index+n[0].length,i=e.substring(t),o=$a(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=Yi(e);return n?n.remainingText.trimStart():e};var _r=/<\|\s*tool_call_begin\s*\|>\s*(?:(?:tool|functions)\b[\s._]*)*([a-zA-Z0-9_]+)(?::\d+)?\s*<\|\s*tool_call_argument_begin\s*\|>([\s\S]*?)<\|\s*tool_call_end\s*\|>/gi,Na=/"([^"]+)"\s*:\s*(?:"([^"]*)"|(\d+)|true|false|null)/g,Ir=/<\|\s*tool_calls_section_begin\s*\|>/gi,Mr=/<\|\s*tool_calls_section_end\s*\|>/gi,Da=/```(?:tool|action|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi;var ti=e=>!e||typeof e!="string"?e:e.replace(/(```[\s\S]*?```|`[^`]*`)|(<(?:\w+)(?:[^>]*)>\r?\n?|\r?\n?<\/\w+(?:[^>]*)>)/gi,(n,t)=>t||""),$r=e=>{if(!e||typeof e!="string")return e;let n=to(e);if(!n||n.length===0)return e;let t=n[n.length-1];if(!t.fullMatch)return e;let i=e.lastIndexOf(t.fullMatch);if(i===-1)return e;let o=i+t.fullMatch.length;return e.substring(0,o).trimEnd()},qi=null,ni={},Vn={key:null,value:null},Ht=e=>e&&e.replace(/(?:(\x1b\[\d+m))?([✔✘✖🔍📖→➕↻↷•🛇])(?:(\x1b\[\d+m))?\s*\b(Clicked|Located|Dragged|Scrolled|Typed|Pressed Key|Recaptured Screen|Created|Read Skill|Read Documentation|Searched Documentation|Read|Edited|Viewed|Processed|Auto-Read|Skipped|List|Generated|Written|Searched|AI Search|Get Map|Write Canceled|Resolved Sub-Agent Query|Edit Canceled|Write Cancelled|Edit Denied|Visited|Updated|Reviewed|Delegated|Background|Checked|Indexed|Analyzed|Browsed|Elevating SubAgent|Checking SubAgent Work|Started Generalist|Called Generalist|Steered|Unsupported Modality|Awaiting|Cancelled|Aligning Moon Phase|Contemplating Existence|Staring At Void|Rollback Point Checked|Emergency Rollback Failed|Emergency Rollback|Delaying Professionally|Negotiating With Electrons|Touching Grass (virtually)|Panicking Softly|Rethinking Career Choices|Loading Cat Videos|Giving Up Entirely|Summoning Braincell #2|Pretending To Be Busy|Waiting For Motivation DLC|Rotating Internal Screaming|Downloading More RAM|Feeding The Hamsters|Gaslighting Scheduler|Performing Dramatic Pause|Buffering Social Energy|Calculating Regret|Reading Terms And Conditions|Becoming Sentient Briefly|Model produced malformed tool call|Loop Detected|Contacting Ancestors)\b/ig,(n,t,i,o,r)=>`${t||""}${i}${o||""} \x1B[95m${r}\x1B[0m`),Fa=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((g,m)=>{let y=setTimeout(g,a);o&&o.addEventListener("abort",()=>{clearTimeout(y),m(new DOMException("The user aborted a request.","AbortError"))})})}}},mt=!1;var Ba=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 g=a.indexOf("**CONTEXT SUMMARY OF PREVIOUS TURNS");if(g!==-1){let y=a.substring(0,g).lastIndexOf("[SYSTEM METADATA]");y!==-1?a=a.substring(y).trim():a=a.substring(g).trim()}}else{let g=a.lastIndexOf("[USER]"),m=a.lastIndexOf("[USER PROMPT]");g!==-1?a=a.substring(g+6).trim():m!==-1&&(a=a.substring(m).trim())}return{...o,text:a}}),t=[],i=0;for(;i<n.length;){let o=n[i];if(o.role==="user")t.push(o),i++;else{let r=[];for(;i<n.length&&n[i].role!=="user";)r.push(n[i]),i++;let c=[],a=[],g=!1,m=()=>{c.length>0&&(t.push({role:"agent",text:"combined"}),c=[]),a.length>0&&(t.push({role:"system",text:"combined"}),a=[]),g=!1};r.forEach(y=>{let h=y.role==="system"&&(y.text?.startsWith("[ACTION RESULT]")||y.text?.startsWith("[TOOL RESULT]")||y.text?.startsWith("SUCCESS:")||y.text?.startsWith("ERROR:")||y.fullText?.startsWith("[ACTION RESULT]")||y.fullText?.startsWith("[TOOL RESULT]")||y.fullText?.startsWith("SUCCESS:")||y.fullText?.startsWith("ERROR:")),f=y.fullText||y.text||"",s=f.trim();if(!(!s&&!y.binaryPart)){if(h)a.push(s);else if(y.role==="agent"){!g&&a.length>0&&m();let u=f.endsWith(`
580
+ `),k=s.toLowerCase().includes("tool:")||s.toLowerCase().includes("action:");c.push(s),k&&u?g=!0:g=!1}}}),m()}}return t.length},Ua=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),Yc=()=>{mt=!0},zc=()=>mt,zi={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"},Kn=(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?W.basename(o.replace(/["']/g,"").replace(/\\/g,"/")):null}catch{return null}},Xi=e=>e?new Lr({apiKey:e}):qi,qc=async(e,n,t,i,o={})=>{let{onStatus:a,onMemoryUpdated:g,onBackgroundIncrement:m}=o,{profile:y,thinkingLevel:h,mode:f,janitorModel:s,chatId:u,systemSettings:k,sessionStats:he,aiProvider:x="Google",apiKey:I}=e,H=process.env.NVIDIA_BASE_URL||x==="Ollama"||x==="InferX"||x==="SenseNova"||x==="AIHubMix"||x==="Poolside"||x==="9router"||x==="ExpLabs"||x==="ExperientialLabs"||x==="c_openai"||x==="Custom (OpenAI)"?!1:k?.memory!==!1,D=Rt(Hn,[]).map(S=>`- [${S.id}]: ${S.memory}`).join(`
581
581
  `),A=i.slice(0,-1).filter(S=>S.text&&!S.text.includes("[ACTION RESULT]")&&!S.text.includes("[TOOL RESULT]")&&!S.text.includes("OBSERVATION:")&&!S.text.startsWith("[TERMINAL_RECORD]")&&!S.isTerminalRecord&&!S.isMeta&&!S.isLogo&&!String(S.id).startsWith("welcome")&&!String(S.id).startsWith("logo")).slice(-14).map(S=>{let R=Lt(Ua(S.text)).replace(/\[(?:tool|action):(?:functions\.)?.*?\]/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[METADATA \(PRIORITY: DYNAMIC\)\] Time: ([^|\n]+)/g,(N,Se)=>`[METADATA (PRIORITY: DYNAMIC)] Time: ${Se.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,`
582
582
  `).replace(/\n\n/g,`
583
583
  `).replace(/\\n\\n/g,"").trim(),Fe=S.role==="user"?8192:32768,ae=R.substring(0,Fe);R.length>Fe&&(ae+=`
584
- ... (truncated) ...`);let C=S.role==="user"?ae.startsWith("[USER]")?"":"[USER]: ":ae.startsWith("[AGENT]")?"":"[AGENT]: ";return{role:S.role==="user"?"user":"model",parts:[{text:`${C}${ae}`}]}}),ge=i.filter(S=>S.role==="user").length===1,we=n.includes("[TITLE-UPDATE]"),Me=Math.random()<.8,ye=ge||we||Me,T=Lt(t).trim(),b=er(D,G,ye),rt=`${T.replace(/\[(?:tool|action):(?:functions\.)?.*?\]/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[\[(?:TOOL|ACTION) RESULTS\]\]/gi,"").replace(/\[(?:TOOL|ACTION) RESULTS?\]/gi,"").replace(/\[(?:tool|action) results\]/gi,"").substring(0,32768)}`;rt.length>32768&&(rt+=`
584
+ ... (truncated) ...`);let C=S.role==="user"?ae.startsWith("[USER]")?"":"[USER]: ":ae.startsWith("[AGENT]")?"":"[AGENT]: ";return{role:S.role==="user"?"user":"model",parts:[{text:`${C}${ae}`}]}}),ge=i.filter(S=>S.role==="user").length===1,we=n.includes("[TITLE-UPDATE]"),Me=Math.random()<.8,ye=ge||we||Me,T=Lt(t).trim(),b=er(D,H,ye),rt=`${T.replace(/\[(?:tool|action):(?:functions\.)?.*?\]/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[\[(?:TOOL|ACTION) RESULTS\]\]/gi,"").replace(/\[(?:TOOL|ACTION) RESULTS?\]/gi,"").replace(/\[(?:tool|action) results\]/gi,"").substring(0,32768)}`;rt.length>32768&&(rt+=`
585
585
  ... (truncated) ...`);let Oe=n.replace(/\[Prompted on:.*?\]/g,"").trim();rt=rt.replace(/\r?\n\r?\n/g,`
586
586
  `).replace(/\n\n/g,`
587
587
  `).replace(/\\n\\n/g,"").trim();let jt=new Date,$t=`[METADATA] Current date and Time: ${`${jt.getFullYear()}-${jt.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(jt.getDate()).padStart(2,"0")}, ${jt.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0})}`}
@@ -590,14 +590,14 @@ ${f[7]}
590
590
  ${Oe.length>8192?`... (truncated) ...
591
591
 
592
592
  `:""}
593
- [AGENT (current turn)]: ${rt}`;A.push({role:"user",parts:[{text:$t}]});let Xt=await pi("NVIDIA"),fn=(await go()).quotas?.providerTiers?.NVIDIA==="Free",Nt="",pe=0,Jt=G?12:-1;for(;pe<=Jt;)try{if(!await ds("background",e))return;let S="",R=null,Fe=!1,ae=x;try{let Se=new Promise((Ze,de)=>setTimeout(()=>de(new Error("JANITOR_TIMEOUT")),1e4)),ve=x==="Google"&&pe>=0&&pe<6&&Xt&&fn,ke=x==="DeepSeek"&&pe<4&&Xt&&fn;Fe=ve||ke,ae=Fe?"NVIDIA":x;let Pe=Date.now(),Ro=null,$n=(async()=>{if(x==="OpenRouter"){let Ze=re("janitor_open_router"),le=(await ce("OpenRouter"))(I,Ze,A,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),vt=await le.next();return{iterator:le,firstResult:vt}}else if(x==="DeepSeek"&&!Fe){let de=(await ce("DeepSeek"))(I,re("deepseek_fast_fallback"),A,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await de.next();return{iterator:de,firstResult:le}}else if(x==="Mistral"&&!Fe){let de=(await ce("Mistral"))(I,re("mistral_janitor_fallback"),A,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await de.next();return{iterator:de,firstResult:le}}else if(x==="NVIDIA"||Fe){let de=(await ce("NVIDIA"))(Fe?Xt:I,re("nvidia_janitor_fallback"),A,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await de.next();return{iterator:de,firstResult:le}}else if(x==="InferX"){let de=(await ce("InferX"))(I,targetModel||re("inferx_fallback")||"deepseek-v4-flash",A,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await de.next();return{iterator:de,firstResult:le}}else if(x==="SenseNova"){let de=(await ce("SenseNova"))(I,targetModel||re("sensenova_fallback")||"sensenova-6.8-flash-lite",A,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await de.next();return{iterator:de,firstResult:le}}else if(x==="AIHubMix"){let de=(await ce("AIHubMix"))(I,targetModel||re("aihubmix_fallback")||"gpt-4o-mini",A,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await de.next();return{iterator:de,firstResult:le}}else if(x==="Poolside"){let de=(await ce("Poolside"))(I,targetModel||re("poolside_fallback")||"poolside/laguna-s-2.1",A,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await de.next();return{iterator:de,firstResult:le}}else if(x==="9router"||x==="9Router"){let de=(await ce("NineRouter"))(I,targetModel||re("9router_fallback")||"z-ai/glm-5.3-flash",A,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await de.next();return{iterator:de,firstResult:le}}else if(x==="ExpLabs"||x==="ExperientialLabs"){let de=(await ce("ExpLabs"))(I,targetModel||re("explabs_fallback")||"deepseek-v4-pro-0813",A,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await de.next();return{iterator:de,firstResult:le}}else{let le=(await Xi(I).models.generateContentStream({model:s||(pe===Jt?re("janitor_default"):re("gemma_janitor_fallback_google")),contents:A,config:{systemInstruction:b,temperature:.7,safetySettings:[{category:Ln.HARM_CATEGORY_HARASSMENT,threshold:Pn.BLOCK_NONE},{category:Ln.HARM_CATEGORY_HATE_SPEECH,threshold:Pn.BLOCK_NONE},{category:Ln.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Pn.BLOCK_NONE},{category:Ln.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Pn.BLOCK_NONE}],thinkingConfig:{includeThoughts:!1,thinkingLevel:Ge.MINIMAL},serviceTier:"flex"}}))[Symbol.asyncIterator](),vt=await le.next();return{iterator:le,firstResult:vt}}})();if(process.stdout.isTTY){let le=(await wi())[u]?.name||"",vt=le&&!le.startsWith("flow-")&&!le.startsWith("Session ")?le:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${vt}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${vt}\x07`)}let{iterator:no,firstResult:Eo}=await Promise.race([$n,Se]);Ro=Date.now()-Pe;let{value:un,done:Dt}=Eo;if(!Dt&&un){let Ze=un.candidates?.[0]?.content?.parts,de=Ze?ae==="Google"?Ze[1]?.text||Ze[0]?.text||"":Ze.filter(le=>le.text&&!le.thought).map(le=>le.text).join(""):typeof un.text=="function"?un.text():"";de&&(S+=de),R=un.usageMetadata;for await(let le of{[Symbol.asyncIterator]:()=>no}){let vt=le.candidates?.[0]?.content?.parts,oo=vt?ae==="Google"?vt[1]?.text||vt[0]?.text||"":vt.filter(Yn=>Yn.text&&!Yn.thought).map(Yn=>Yn.text).join(""):typeof le.text=="function"?le.text():"";oo&&(S+=oo),R=le.usageMetadata}}}catch(Se){throw Se}if(S){if(Nt=S,R){let Se=R.totalTokenCount||0,ve=R.cachedContentTokenCount||0,ke=(R.candidatesTokenCount||0)+(ae==="Google"&&R.thoughtsTokenCount||0),Pe=Fe?re("nvidia_janitor_fallback"):ae==="DeepSeek"?re("deepseek_fast_fallback"):ae==="ExpLabs"||ae==="ExperientialLabs"?re("explabs_fallback")||"deepseek-v4-pro-0813":ae==="OpenRouter"?re("janitor_open_router"):s||(pe===Jt?re("janitor_default"):re("gemma_janitor_fallback_google"));await gt("tokens",Se,ae,Pe),ve>0&&await gt("cachedTokens",ve,ae,Pe),ke>0&&await gt("candidateTokens",ke,ae,Pe),janitorTtft!==null&&janitorTtft>0&&await gt("ttft",janitorTtft,ae,Pe),mo({provider:ae,model:Pe,prompt:R.promptTokenCount||0,cached:ve,output:ke,reasoning:R.thoughtsTokenCount||0,ttft:janitorTtft})}}else throw new Error("No synthesis generated by Janitor.");g&&(g(),await Et("background"));let C=to(Nt),N=!1;for(let Se of C){let ve=Se.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(ve)&&(N=!0);let ke={chatId:u,sessionId:u,history:i},Pe=await ko(ve,Se.args,ke);ve.toLowerCase()==="memory"&&(Se.args.includes("action='user'")||Se.args.includes('action="user"'))&&!Pe.startsWith("ERROR")&&(h&&h(),process.stdout.isTTY&&(process.stdout.write("\x1B]0;Memory Updated\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=Memory Updated\x07")),await new Promise($n=>setTimeout($n,3e3)))}if(!N)try{let Se=Rt(Hn,[]);if(Se.length>0){let ve=[];for(let ke of Se)ke.score===void 0&&(ke.score=.5),ke.score*=.99995,ke.score<.05&&(ke.score=0),ke.score=Math.round(ke.score*1e5)/1e5,ke.score>0&&ve.push(ke);Qn(Hn,ve)}}catch{}break}catch(S){pe++;let R=new Date().toLocaleString(),Fe=S instanceof Error?(()=>{try{return JSON.parse(JSON.parse(S.message).error.message).error.message}catch{return String(S)}})():String(S);await new Promise(N=>setTimeout(N,1e3));let ae=j.join(qt,"janitor");if(be.existsSync(ae)||be.mkdirSync(ae,{recursive:!0}),be.appendFileSync(j.join(ae,"error.log"),`ERROR [Attempt ${pe}/${Jt+1}] [${R}]: ${Fe}
593
+ [AGENT (current turn)]: ${rt}`;A.push({role:"user",parts:[{text:$t}]});let qt=await yi("NVIDIA"),fn=(await go()).quotas?.providerTiers?.NVIDIA==="Free",Nt="",pe=0,Xt=H?12:-1;for(;pe<=Xt;)try{if(!await ds("background",e))return;let S="",R=null,Fe=!1,ae=x;try{let Se=new Promise((Ze,de)=>setTimeout(()=>de(new Error("JANITOR_TIMEOUT")),1e4)),ve=x==="Google"&&pe>=0&&pe<6&&qt&&fn,ke=x==="DeepSeek"&&pe<4&&qt&&fn;Fe=ve||ke,ae=Fe?"NVIDIA":x;let Pe=Date.now(),_o=null,$n=(async()=>{if(x==="OpenRouter"){let Ze=re("janitor_open_router"),le=(await ce("OpenRouter"))(I,Ze,A,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),vt=await le.next();return{iterator:le,firstResult:vt}}else if(x==="DeepSeek"&&!Fe){let de=(await ce("DeepSeek"))(I,re("deepseek_fast_fallback"),A,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await de.next();return{iterator:de,firstResult:le}}else if(x==="Mistral"&&!Fe){let de=(await ce("Mistral"))(I,re("mistral_janitor_fallback"),A,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await de.next();return{iterator:de,firstResult:le}}else if(x==="NVIDIA"||Fe){let de=(await ce("NVIDIA"))(Fe?qt:I,re("nvidia_janitor_fallback"),A,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await de.next();return{iterator:de,firstResult:le}}else if(x==="InferX"){let de=(await ce("InferX"))(I,targetModel||re("inferx_fallback")||"deepseek-v4-flash",A,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await de.next();return{iterator:de,firstResult:le}}else if(x==="SenseNova"){let de=(await ce("SenseNova"))(I,targetModel||re("sensenova_fallback")||"sensenova-6.8-flash-lite",A,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await de.next();return{iterator:de,firstResult:le}}else if(x==="AIHubMix"){let de=(await ce("AIHubMix"))(I,targetModel||re("aihubmix_fallback")||"gpt-4o-mini",A,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await de.next();return{iterator:de,firstResult:le}}else if(x==="Poolside"){let de=(await ce("Poolside"))(I,targetModel||re("poolside_fallback")||"poolside/laguna-s-2.1",A,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await de.next();return{iterator:de,firstResult:le}}else if(x==="9router"||x==="9Router"){let de=(await ce("NineRouter"))(I,targetModel||re("9router_fallback")||"z-ai/glm-5.3-flash",A,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await de.next();return{iterator:de,firstResult:le}}else if(x==="ExpLabs"||x==="ExperientialLabs"){let de=(await ce("ExpLabs"))(I,targetModel||re("explabs_fallback")||"deepseek-v4-pro-0813",A,b,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),le=await de.next();return{iterator:de,firstResult:le}}else{let le=(await Xi(I).models.generateContentStream({model:s||(pe===Xt?re("janitor_default"):re("gemma_janitor_fallback_google")),contents:A,config:{systemInstruction:b,temperature:.7,safetySettings:[{category:Ln.HARM_CATEGORY_HARASSMENT,threshold:Pn.BLOCK_NONE},{category:Ln.HARM_CATEGORY_HATE_SPEECH,threshold:Pn.BLOCK_NONE},{category:Ln.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Pn.BLOCK_NONE},{category:Ln.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Pn.BLOCK_NONE}],thinkingConfig:{includeThoughts:!1,thinkingLevel:Ge.MINIMAL},serviceTier:"flex"}}))[Symbol.asyncIterator](),vt=await le.next();return{iterator:le,firstResult:vt}}})();if(process.stdout.isTTY){let le=(await Si())[u]?.name||"",vt=le&&!le.startsWith("flow-")&&!le.startsWith("Session ")?le:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${vt}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${vt}\x07`)}let{iterator:no,firstResult:Io}=await Promise.race([$n,Se]);_o=Date.now()-Pe;let{value:un,done:Dt}=Io;if(!Dt&&un){let Ze=un.candidates?.[0]?.content?.parts,de=Ze?ae==="Google"?Ze[1]?.text||Ze[0]?.text||"":Ze.filter(le=>le.text&&!le.thought).map(le=>le.text).join(""):typeof un.text=="function"?un.text():"";de&&(S+=de),R=un.usageMetadata;for await(let le of{[Symbol.asyncIterator]:()=>no}){let vt=le.candidates?.[0]?.content?.parts,oo=vt?ae==="Google"?vt[1]?.text||vt[0]?.text||"":vt.filter(Yn=>Yn.text&&!Yn.thought).map(Yn=>Yn.text).join(""):typeof le.text=="function"?le.text():"";oo&&(S+=oo),R=le.usageMetadata}}}catch(Se){throw Se}if(S){if(Nt=S,R){let Se=R.totalTokenCount||0,ve=R.cachedContentTokenCount||0,ke=(R.candidatesTokenCount||0)+(ae==="Google"&&R.thoughtsTokenCount||0),Pe=Fe?re("nvidia_janitor_fallback"):ae==="DeepSeek"?re("deepseek_fast_fallback"):ae==="ExpLabs"||ae==="ExperientialLabs"?re("explabs_fallback")||"deepseek-v4-pro-0813":ae==="OpenRouter"?re("janitor_open_router"):s||(pe===Xt?re("janitor_default"):re("gemma_janitor_fallback_google"));await gt("tokens",Se,ae,Pe),ve>0&&await gt("cachedTokens",ve,ae,Pe),ke>0&&await gt("candidateTokens",ke,ae,Pe),janitorTtft!==null&&janitorTtft>0&&await gt("ttft",janitorTtft,ae,Pe),mo({provider:ae,model:Pe,prompt:R.promptTokenCount||0,cached:ve,output:ke,reasoning:R.thoughtsTokenCount||0,ttft:janitorTtft})}}else throw new Error("No synthesis generated by Janitor.");m&&(m(),await Et("background"));let C=to(Nt),N=!1;for(let Se of C){let ve=Se.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(ve)&&(N=!0);let ke={chatId:u,sessionId:u,history:i},Pe=await Ro(ve,Se.args,ke);ve.toLowerCase()==="memory"&&(Se.args.includes("action='user'")||Se.args.includes('action="user"'))&&!Pe.startsWith("ERROR")&&(g&&g(),process.stdout.isTTY&&(process.stdout.write("\x1B]0;Memory Updated\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=Memory Updated\x07")),await new Promise($n=>setTimeout($n,3e3)))}if(!N)try{let Se=Rt(Hn,[]);if(Se.length>0){let ve=[];for(let ke of Se)ke.score===void 0&&(ke.score=.5),ke.score*=.99995,ke.score<.05&&(ke.score=0),ke.score=Math.round(ke.score*1e5)/1e5,ke.score>0&&ve.push(ke);Qn(Hn,ve)}}catch{}break}catch(S){pe++;let R=new Date().toLocaleString(),Fe=S instanceof Error?(()=>{try{return JSON.parse(JSON.parse(S.message).error.message).error.message}catch{return String(S)}})():String(S);await new Promise(N=>setTimeout(N,1e3));let ae=W.join(kn,"janitor");if(be.existsSync(ae)||be.mkdirSync(ae,{recursive:!0}),be.appendFileSync(W.join(ae,"error.log"),`ERROR [Attempt ${pe}/${Xt+1}] [${R}]: ${Fe}
594
594
 
595
- `),pe>Jt)break;let C=Math.min(750*Math.pow(2,pe-1),5e3);await new Promise(N=>setTimeout(N,C))}if(pe){let S=j.join(qt,"janitor");be.appendFileSync(j.join(S,"error.log"),`-----------------------------------------------------------------------------
595
+ `),pe>Xt)break;let C=Math.min(750*Math.pow(2,pe-1),5e3);await new Promise(N=>setTimeout(N,C))}if(pe){let S=W.join(kn,"janitor");be.appendFileSync(W.join(S,"error.log"),`-----------------------------------------------------------------------------
596
596
 
597
- `)}if(process.stdout.isTTY)try{let Fe=(await wi())[u]?.name||"",ae=Fe&&!Fe.startsWith("flow-")&&!Fe.startsWith("Session ")?Fe:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${ae}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${ae}\x07`)}catch{process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")}},Nr=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]!==`
597
+ `)}if(process.stdout.isTTY)try{let Fe=(await Si())[u]?.name||"",ae=Fe&&!Fe.startsWith("flow-")&&!Fe.startsWith("Session ")?Fe:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${ae}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${ae}\x07`)}catch{process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")}},Nr=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]!==`
598
598
  `&&n[o]!=="\r"&&(n[o]=" "),o++;continue}if(n[o]==="`"){i=!i,n[o]=" ",o++;continue}if(i){n[o]===`
599
- `||n[o]==="\r"?i=!1:n[o]=" ",o++;continue}o++}return n.join("")},Wa=e=>{let n=Lt(e),t=Nr(n);Co.lastIndex=0;let i;for(;(i=Co.exec(t))!==null;){let o=i.index+i[0].length-1,r=0,c=null,a=!1,h=!1;for(let g=o;g<t.length;g++){let y=t[g];if(!c&&(y==='"'||y==="'"||y==="`")?(c=y,a=!1):c&&y===c&&!a&&(c=null),!c&&(y==="("?r++:y===")"&&r--,r===0)){let m=g+1;for(;m<t.length&&/\s/.test(t[m]);)m++;if(m<t.length&&t[m]==="]"){h=!0,Co.lastIndex=m+1;break}}y==="\\"?a=!a:a=!1}if(!h)return{inside:!0,toolName:i[1],startIndex:i.index,args:n.substring(i.index+i[0].length)}}return{inside:!1}},Dr=(e,n=!0)=>{let t=Co;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?Lt(c):c;let a=r.index+r[0].length-1,h=0,g=null,y=-1;for(let m=a;m<e.length;m++){let f=e[m];if(g){if(f===g){let s=0;for(let u=m-1;u>=0&&e[u]==="\\";u--)s++;s%2===0&&(g=null)}}else if(f==='"'||f==="'"||f==="`")g=f;else if(f==="(")h++;else if(f===")"&&(h--,h===0)){let s=m+1;for(;s<e.length&&/\s/.test(e[s]);)s++;if(s<e.length&&e[s]==="]"){y=s;break}}}if(y!==-1)i+="[tool:functions."+r[1]+"()]",o=y+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},Ga=(e,n,t)=>{let i=Co;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 h=c.index+c[0].length-1,g=0,y=null,m=-1;for(let f=h;f<e.length;f++){let s=e[f];if(y){if(s===y){let u=0;for(let k=f-1;k>=0&&e[k]==="\\";k--)u++;u%2===0&&(y=null)}}else if(s==='"'||s==="'"||s==="`")y=s;else if(s==="(")g++;else if(s===")"&&(g--,g===0)){let u=f+1;for(;u<e.length&&/\s/.test(e[u]);)u++;if(u<e.length&&e[u]==="]"){m=u;break}}}if(m!==-1)o+=e.substring(c.index,m+1),r=m+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},Or=e=>Dr(e,!0),Ha=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("");_r.lastIndex=0;let i=e.replace(_r,(o,r,c)=>{let a="";try{let y=JSON.parse(c.trim());y&&typeof y=="object"&&(a=Object.entries(y).map(([f,s])=>{let u=typeof s=="string"?s:JSON.stringify(s);return`${f}=${JSON.stringify(u)}`}).join(", "))}catch{let m=[],f=Na;f.lastIndex=0;let s;for(;(s=f.exec(c))!==null;){let u=s[1],k=s[2]!==void 0?s[2]:s[0].split(":").slice(1).join(":").trim();m.push(`${u}=${JSON.stringify(k)}`)}m.length>0?a=m.join(", "):a=c.trim()}let h=r.toLowerCase().replace(/_/g,"");return`[tool:functions.${n[h]||t(r)}(${a})]`});return Ir.lastIndex=0,Mr.lastIndex=0,i=i.replace(Ir,""),i=i.replace(Mr,""),i},to=e=>{if(!e)return[];let n=Ha(e),t=Lt(n),i=[],o=Nr(t),r=_a;r.lastIndex=0;let c;for(;(c=r.exec(o))!==null;){let a=c[1],h=c.index+c[0].length-1,g=0,y=null,m=-1,f=-1;for(let s=h;s<o.length;s++){let u=o[s];if(y){if(u===y){let k=0;for(let he=s-1;he>=0&&o[he]==="\\";he--)k++;k%2===0&&(y=null)}}else{if(s>h&&(o.substring(s).startsWith("[action:")||o.substring(s).startsWith("[tool:")))break;if(u==='"'||u==="'"||u==="`")y=u;else if(u==="(")g++;else if(u===")"&&(g--,g===0)){f=s;let k=s+1;for(;k<o.length&&/\s/.test(o[k]);)k++;if(k<o.length&&o[k]==="]"){m=k;break}}}}if(m!==-1){let s=t.substring(h+1,f),u=t.substring(c.index,m+1);i.push({fullMatch:u,toolName:a.trim(),args:s.trim()}),r.lastIndex=m+1}}return i},Pr=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],u=f+1<o.length?o[f+1].index:n.length,k=n.substring(s.index,u),he=k.indexOf("("),x=he!==-1?k.substring(he+1):"",I=0,G=null,q=!1;for(let D=0;D<x.length;D++){let A=x[D];if(G){if(A===G){let ge=0;for(let we=D-1;we>=0&&x[we]==="\\";we--)ge++;ge%2===0&&(G=null)}}else if(A==='"'||A==="'"||A==="`")G=A;else if(A==="(")I++;else if(A===")")if(I>0)I--;else{let ge=D+1;for(;ge<x.length&&/\s/.test(x[ge]);)ge++;if(ge<x.length&&x[ge]==="]"){q=!0;break}}}if(!q){let D=k.trim(),A="";G?A=`Unclosed quote string (${G}) inside arguments`:D.endsWith("]")?A=`Missing closing ')' before ']' (e.g. found "...]")`:D.endsWith(")")?A=`Missing closing ']' after ')' (e.g. found "...)" instead of "...)]")`:!D.includes(")")&&!D.includes("]")?A="Missing closing delimiter ')]'":A="Malformed or unclosed call syntax (missing ')]')",t.push(`\u2022 [action:${s.toolName}(...)]: ${A}. Expected: [action:${s.toolName}(arg1="...", arg2="...")]`)}}let 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]:"")!=="["&&qo(f)&&t.push(`\u2022 action:${f}(...): Missing opening bracket '['. Expected: [action:${f}(...)]`)}let h=/\[\s*(?:functions\.)?([a-zA-Z0-9_]+)\s*\(/g,g;for(;(g=h.exec(n))!==null;){let f=g[1];f!=="action"&&f!=="tool"&&qo(f)&&t.push(`\u2022 [${f}(...)]: Missing 'action:' prefix. Expected: [action:${f}(...)]`)}let y=/\[\s*(?:tool|action)\s*:\s*(?:functions\.)?([a-zA-Z0-9_]+)(?!\s*\()/gi,m;for(;(m=y.exec(n))!==null;){let f=m[1];qo(f)&&t.push(`\u2022 [action:${f}...]: Missing opening '(' for tool arguments. Expected: [action:${f}(...)]`)}return t.length>0?t.join(`
600
- `):null},Xc=(e,n={})=>{if(!e)return null;if(ti=n,qi=new Lr({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}}}},Fr=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}},ni=async(e,n,t,i,o="Fast",r=.75,c="agent")=>Fa(async()=>{let{aiProvider:a="Google",apiKey:h,mode:g}=e,y="",m=null,f=typeof t=="string"?[{role:"user",parts:[{text:t}]}]:t,s=new AbortController,u=s.signal,k=setInterval(()=>{mt&&(s.abort(),clearInterval(k))},100),he=Date.now(),x=null;try{let I;if(a==="Ollama")I=(await ce("Ollama"))(h,n,f,i,o,g,ot(n),u,r,e.systemSettings?.ollamaEndpoint||"Cloud");else if(a==="OpenRouter")I=(await ce("OpenRouter"))(h,n,f,i,o,g,ot(n),u,r);else if(a==="DeepSeek")I=(await ce("DeepSeek"))(h,n,f,i,o,g,ot(n),u,r);else if(a==="Mistral")I=(await ce("Mistral"))(h,n,f,i,o,g,ot(n),u,r);else if(a==="NVIDIA")I=(await ce("NVIDIA"))(h,n,f,i,o,g,ot(n),u,r);else if(a==="InferX")I=(await ce("InferX"))(h,n,f,i,o,g,ot(n),u,r);else if(a==="SenseNova")I=(await ce("SenseNova"))(h,n,f,i,o,g,ot(n),u,r);else if(a==="AIHubMix")I=(await ce("AIHubMix"))(h,n,f,i,o,g,ot(n),u,r);else if(a==="Poolside")I=(await ce("Poolside"))(h,n,f,i,o,g,ot(n),u,r);else if(a==="9router"||a==="9Router")I=(await ce("NineRouter"))(h,n,f,i,o,g,ot(n),u,r);else if(a==="ExpLabs"||a==="ExperientialLabs")I=(await ce("ExpLabs"))(h,n,f,i,o,g,ot(n),u,r);else if(a==="Infron"||a==="infron")I=(await ce("Infron"))(h,n,f,i,o,g,ot(n),u,r);else if(a==="TokenHarbor"||a==="Token Harbor"||a==="tokenharbor"||a==="token_harbor"||a==="thk")I=(await ce("TokenHarbor"))(h,n,f,i,o,g,ot(n),u,r);else if(a==="APInex"||a==="apinex"||a==="apx")I=(await ce("APInex"))(h,n,f,i,o,g,ot(n),u,r);else if(a==="c_openai"||a==="Custom (OpenAI)")I=(await ce("c_openai"))(h,n,f,i,o,g,ot(n),u,r,e.systemSettings?.customOpenAIBaseUrl||"");else{let G=Xi(h),{serviceTier:q,cleanModel:D}=Fr(n),A={systemInstruction:i,temperature:r,thinkingConfig:(()=>{let we=(n||"").toLowerCase(),Me=we.includes("gemma-4")||we.startsWith("gemma"),ye=we.includes("gemini-3");if(Me||ye)return Me?o.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:Ge.MINIMAL}:{includeThoughts:!0,thinkingLevel:Ge.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:we.includes("pro")?Ge.LOW:Ge.MINIMAL,Low:Ge.LOW,Medium:Ge.MEDIUM,Standard:Ge.MEDIUM,High:Ge.HIGH,xHigh:Ge.HIGH}[o]||Ge.MEDIUM};{let T={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[o]||2048;return T===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:T}}})()};q&&(A.serviceTier=q),I=await G.models.generateContentStream({model:D,contents:f,config:A},{signal:u})}for await(let G of I){if(mt)throw new Error("Subagent task was cancelled.");if(e?.taskId&&typeof Gt<"u"){let A=Gt.find(ge=>ge.id===e.taskId);if(A&&A.status==="cancelled")throw new Error("Subagent task was cancelled.")}x===null&&(G.candidates?.[0]?.content?.parts||G.text)&&(x=Date.now()-he);let q="";if(G.candidates?.[0]?.content?.parts)for(let A of G.candidates[0].content.parts)A.text&&!A.thought&&(y+=A.text,q+=A.text);let D=q?xi(q):0;e&&typeof e.onTokenChunk=="function"&&e.onTokenChunk(q,D),G.usageMetadata&&(m=G.usageMetadata)}}finally{clearInterval(k)}if(m){let I=m.totalTokenCount||0,G=m.cachedContentTokenCount||0,q=(m.candidatesTokenCount||0)+(a==="Google"&&m.thoughtsTokenCount||0);await gt("tokens",I,a,n),G>0&&await gt("cachedTokens",G,a,n),q>0&&await gt("candidateTokens",q,a,n),x!==null&&x>0&&await gt("ttft",x,a,n),mo({provider:a,model:n,prompt:m.promptTokenCount||0,cached:G,output:q,reasoning:m.thoughtsTokenCount||0,ttft:x}),e&&typeof e.onUsage=="function"&&e.onUsage({totalTokenCount:I,cachedContentTokenCount:G,candidatesTokenCount:q})}return await Et("agent",a),{text:y,usageMetadata:m}}),ja=async(e,n,t=null)=>{t=t||Rt(Lo,{});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.
599
+ `||n[o]==="\r"?i=!1:n[o]=" ",o++;continue}o++}return n.join("")},Wa=e=>{let n=Lt(e),t=Nr(n);vo.lastIndex=0;let i;for(;(i=vo.exec(t))!==null;){let o=i.index+i[0].length-1,r=0,c=null,a=!1,g=!1;for(let m=o;m<t.length;m++){let y=t[m];if(!c&&(y==='"'||y==="'"||y==="`")?(c=y,a=!1):c&&y===c&&!a&&(c=null),!c&&(y==="("?r++:y===")"&&r--,r===0)){let h=m+1;for(;h<t.length&&/\s/.test(t[h]);)h++;if(h<t.length&&t[h]==="]"){g=!0,vo.lastIndex=h+1;break}}y==="\\"?a=!a:a=!1}if(!g)return{inside:!0,toolName:i[1],startIndex:i.index,args:n.substring(i.index+i[0].length)}}return{inside:!1}},Dr=(e,n=!0)=>{let t=vo;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?Lt(c):c;let a=r.index+r[0].length-1,g=0,m=null,y=-1;for(let h=a;h<e.length;h++){let f=e[h];if(m){if(f===m){let s=0;for(let u=h-1;u>=0&&e[u]==="\\";u--)s++;s%2===0&&(m=null)}}else if(f==='"'||f==="'"||f==="`")m=f;else if(f==="(")g++;else if(f===")"&&(g--,g===0)){let s=h+1;for(;s<e.length&&/\s/.test(e[s]);)s++;if(s<e.length&&e[s]==="]"){y=s;break}}}if(y!==-1)i+="[tool:functions."+r[1]+"()]",o=y+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},Ga=(e,n,t)=>{let i=vo;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 g=c.index+c[0].length-1,m=0,y=null,h=-1;for(let f=g;f<e.length;f++){let s=e[f];if(y){if(s===y){let u=0;for(let k=f-1;k>=0&&e[k]==="\\";k--)u++;u%2===0&&(y=null)}}else if(s==='"'||s==="'"||s==="`")y=s;else if(s==="(")m++;else if(s===")"&&(m--,m===0)){let u=f+1;for(;u<e.length&&/\s/.test(e[u]);)u++;if(u<e.length&&e[u]==="]"){h=u;break}}}if(h!==-1)o+=e.substring(c.index,h+1),r=h+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},Or=e=>Dr(e,!0),Ha=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("");_r.lastIndex=0;let i=e.replace(_r,(o,r,c)=>{let a="";try{let y=JSON.parse(c.trim());y&&typeof y=="object"&&(a=Object.entries(y).map(([f,s])=>{let u=typeof s=="string"?s:JSON.stringify(s);return`${f}=${JSON.stringify(u)}`}).join(", "))}catch{let h=[],f=Na;f.lastIndex=0;let s;for(;(s=f.exec(c))!==null;){let u=s[1],k=s[2]!==void 0?s[2]:s[0].split(":").slice(1).join(":").trim();h.push(`${u}=${JSON.stringify(k)}`)}h.length>0?a=h.join(", "):a=c.trim()}let g=r.toLowerCase().replace(/_/g,"");return`[tool:functions.${n[g]||t(r)}(${a})]`});return Ir.lastIndex=0,Mr.lastIndex=0,i=i.replace(Ir,""),i=i.replace(Mr,""),i},to=e=>{if(!e)return[];let n=Ha(e),t=Lt(n),i=[],o=Nr(t),r=_a;r.lastIndex=0;let c;for(;(c=r.exec(o))!==null;){let a=c[1],g=c.index+c[0].length-1,m=0,y=null,h=-1,f=-1;for(let s=g;s<o.length;s++){let u=o[s];if(y){if(u===y){let k=0;for(let he=s-1;he>=0&&o[he]==="\\";he--)k++;k%2===0&&(y=null)}}else{if(s>g&&(o.substring(s).startsWith("[action:")||o.substring(s).startsWith("[tool:")))break;if(u==='"'||u==="'"||u==="`")y=u;else if(u==="(")m++;else if(u===")"&&(m--,m===0)){f=s;let k=s+1;for(;k<o.length&&/\s/.test(o[k]);)k++;if(k<o.length&&o[k]==="]"){h=k;break}}}}if(h!==-1){let s=t.substring(g+1,f),u=t.substring(c.index,h+1);i.push({fullMatch:u,toolName:a.trim(),args:s.trim()}),r.lastIndex=h+1}}return i},Pr=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],u=f+1<o.length?o[f+1].index:n.length,k=n.substring(s.index,u),he=k.indexOf("("),x=he!==-1?k.substring(he+1):"",I=0,H=null,q=!1;for(let D=0;D<x.length;D++){let A=x[D];if(H){if(A===H){let ge=0;for(let we=D-1;we>=0&&x[we]==="\\";we--)ge++;ge%2===0&&(H=null)}}else if(A==='"'||A==="'"||A==="`")H=A;else if(A==="(")I++;else if(A===")")if(I>0)I--;else{let ge=D+1;for(;ge<x.length&&/\s/.test(x[ge]);)ge++;if(ge<x.length&&x[ge]==="]"){q=!0;break}}}if(!q){let D=k.trim(),A="";H?A=`Unclosed quote string (${H}) inside arguments`:D.endsWith("]")?A=`Missing closing ')' before ']' (e.g. found "...]")`:D.endsWith(")")?A=`Missing closing ']' after ')' (e.g. found "...)" instead of "...)]")`:!D.includes(")")&&!D.includes("]")?A="Missing closing delimiter ')]'":A="Malformed or unclosed call syntax (missing ')]')",t.push(`\u2022 [action:${s.toolName}(...)]: ${A}. Expected: [action:${s.toolName}(arg1="...", arg2="...")]`)}}let 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]:"")!=="["&&Xo(f)&&t.push(`\u2022 action:${f}(...): Missing opening bracket '['. Expected: [action:${f}(...)]`)}let g=/\[\s*(?:functions\.)?([a-zA-Z0-9_]+)\s*\(/g,m;for(;(m=g.exec(n))!==null;){let f=m[1];f!=="action"&&f!=="tool"&&Xo(f)&&t.push(`\u2022 [${f}(...)]: Missing 'action:' prefix. Expected: [action:${f}(...)]`)}let y=/\[\s*(?:tool|action)\s*:\s*(?:functions\.)?([a-zA-Z0-9_]+)(?!\s*\()/gi,h;for(;(h=y.exec(n))!==null;){let f=h[1];Xo(f)&&t.push(`\u2022 [action:${f}...]: Missing opening '(' for tool arguments. Expected: [action:${f}(...)]`)}return t.length>0?t.join(`
600
+ `):null},Xc=(e,n={})=>{if(!e)return null;if(ni=n,qi=new Lr({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}}}},Fr=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}},oi=async(e,n,t,i,o="Fast",r=.75,c="agent")=>Fa(async()=>{let{aiProvider:a="Google",apiKey:g,mode:m}=e,y="",h=null,f=typeof t=="string"?[{role:"user",parts:[{text:t}]}]:t,s=new AbortController,u=s.signal,k=setInterval(()=>{mt&&(s.abort(),clearInterval(k))},100),he=Date.now(),x=null;try{let I;if(a==="Ollama")I=(await ce("Ollama"))(g,n,f,i,o,m,ot(n),u,r,e.systemSettings?.ollamaEndpoint||"Cloud");else if(a==="OpenRouter")I=(await ce("OpenRouter"))(g,n,f,i,o,m,ot(n),u,r);else if(a==="DeepSeek")I=(await ce("DeepSeek"))(g,n,f,i,o,m,ot(n),u,r);else if(a==="Mistral")I=(await ce("Mistral"))(g,n,f,i,o,m,ot(n),u,r);else if(a==="NVIDIA")I=(await ce("NVIDIA"))(g,n,f,i,o,m,ot(n),u,r);else if(a==="InferX")I=(await ce("InferX"))(g,n,f,i,o,m,ot(n),u,r);else if(a==="SenseNova")I=(await ce("SenseNova"))(g,n,f,i,o,m,ot(n),u,r);else if(a==="AIHubMix")I=(await ce("AIHubMix"))(g,n,f,i,o,m,ot(n),u,r);else if(a==="Poolside")I=(await ce("Poolside"))(g,n,f,i,o,m,ot(n),u,r);else if(a==="9router"||a==="9Router")I=(await ce("NineRouter"))(g,n,f,i,o,m,ot(n),u,r);else if(a==="ExpLabs"||a==="ExperientialLabs")I=(await ce("ExpLabs"))(g,n,f,i,o,m,ot(n),u,r);else if(a==="Infron"||a==="infron")I=(await ce("Infron"))(g,n,f,i,o,m,ot(n),u,r);else if(a==="TokenHarbor"||a==="Token Harbor"||a==="tokenharbor"||a==="token_harbor"||a==="thk")I=(await ce("TokenHarbor"))(g,n,f,i,o,m,ot(n),u,r);else if(a==="APInex"||a==="apinex"||a==="apx")I=(await ce("APInex"))(g,n,f,i,o,m,ot(n),u,r);else if(a==="c_openai"||a==="Custom (OpenAI)")I=(await ce("c_openai"))(g,n,f,i,o,m,ot(n),u,r,e.systemSettings?.customOpenAIBaseUrl||"");else{let H=Xi(g),{serviceTier:q,cleanModel:D}=Fr(n),A={systemInstruction:i,temperature:r,thinkingConfig:(()=>{let we=(n||"").toLowerCase(),Me=we.includes("gemma-4")||we.startsWith("gemma"),ye=we.includes("gemini-3");if(Me||ye)return Me?o.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:Ge.MINIMAL}:{includeThoughts:!0,thinkingLevel:Ge.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:we.includes("pro")?Ge.LOW:Ge.MINIMAL,Low:Ge.LOW,Medium:Ge.MEDIUM,Standard:Ge.MEDIUM,High:Ge.HIGH,xHigh:Ge.HIGH}[o]||Ge.MEDIUM};{let T={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[o]||2048;return T===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:T}}})()};q&&(A.serviceTier=q),I=await H.models.generateContentStream({model:D,contents:f,config:A},{signal:u})}for await(let H of I){if(mt)throw new Error("Subagent task was cancelled.");if(e?.taskId&&typeof Gt<"u"){let A=Gt.find(ge=>ge.id===e.taskId);if(A&&A.status==="cancelled")throw new Error("Subagent task was cancelled.")}x===null&&(H.candidates?.[0]?.content?.parts||H.text)&&(x=Date.now()-he);let q="";if(H.candidates?.[0]?.content?.parts)for(let A of H.candidates[0].content.parts)A.text&&!A.thought&&(y+=A.text,q+=A.text);let D=q?bi(q):0;e&&typeof e.onTokenChunk=="function"&&e.onTokenChunk(q,D),H.usageMetadata&&(h=H.usageMetadata)}}finally{clearInterval(k)}if(h){let I=h.totalTokenCount||0,H=h.cachedContentTokenCount||0,q=(h.candidatesTokenCount||0)+(a==="Google"&&h.thoughtsTokenCount||0);await gt("tokens",I,a,n),H>0&&await gt("cachedTokens",H,a,n),q>0&&await gt("candidateTokens",q,a,n),x!==null&&x>0&&await gt("ttft",x,a,n),mo({provider:a,model:n,prompt:h.promptTokenCount||0,cached:H,output:q,reasoning:h.thoughtsTokenCount||0,ttft:x}),e&&typeof e.onUsage=="function"&&e.onUsage({totalTokenCount:I,cachedContentTokenCount:H,candidatesTokenCount:q})}return await Et("agent",a),{text:y,usageMetadata:h}}),ja=async(e,n,t=null)=>{t=t||Rt(Do,{});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.
601
601
  Your task is to summarize or merge temporary context memories from one or more past conversation sessions.
602
602
  For each Chat ID provided, you must output a tool call to save the consolidated summary.
603
603
 
@@ -612,7 +612,7 @@ Guidelines:
612
612
 
613
613
  Chats to process:
614
614
 
615
- `,a=Rt(mi,{});for(let f of r){let u=t[f].map(he=>`- ${he}`).join(`
615
+ `,a=Rt(hi,{});for(let f of r){let u=t[f].map(he=>`- ${he}`).join(`
616
616
  `),k=a[f];c+=`[Chat ID: ${f}]
617
617
  `,k?(c+=`- Existing Summary: "${k}"
618
618
  `,c+=`
@@ -622,8 +622,8 @@ ${u}
622
622
  `):c+=`-- Individual Memories:
623
623
  ${u}
624
624
 
625
- `}let h=0,g=5,y=!1,m=re("gemma_janitor_fallback_google");for(i==="OpenRouter"&&(m=re("janitor_open_router")),i==="DeepSeek"&&(m=re("deepseek_level_1")),i==="Mistral"&&(m=re("mistral_level_1")),i==="NVIDIA"&&(m=re("nvidia_janitor_fallback")),i==="InferX"&&(m=re("inferx_fallback")),i==="SenseNova"&&(m=re("sensenova_fallback")),i==="AIHubMix"&&(m=re("aihubmix_fallback")),i==="Poolside"&&(m=re("poolside_fallback")),(i==="9router"||i==="9Router")&&(m=re("9router_fallback"));h<=g&&!y;){h++;try{let s=(await ni(n,m,c,null,"Fast",.75,"background")).text||"",u=to(s);if(u.length===0)throw new Error("No tool calls detected in synthesis response");for(let k of u){let he=k.toolName;["saveSummary","saveSumary","SaveSummary","SaveSumary"].includes(he)&&await ko(he,k.args,{chatId:e})}y=!0}catch(f){if(h>=g)throw new Error(`Failed after ${g} 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=j.join(qt,"janitor");be.existsSync(r)||be.mkdirSync(r,{recursive:!0}),be.appendFileSync(j.join(r,"error.log"),`[${new Date().toLocaleString()}] Past memory batch consolidation error: ${o}
626
- `)}},Jc=async(e,n,t=!1)=>{let{chatId:i,aiProvider:o="Google"}=e,r=j.join(Po,"chat-summaries.json"),c=s=>s.filter(u=>(u.role==="user"||u.role==="agent"||u.role==="system")&&u.role!=="think"&&!u.isVisualFeedback&&!u.isMeta&&!u.isTerminalRecord&&!(u.text&&u.text.includes("[TERMINAL_RECORD]"))&&!String(u.id).startsWith("welcome")).map(u=>{let k=u.fullText||u.text||"",he=u.role==="system"||k.startsWith("[ACTION RESULT]:")||k.startsWith("[TOOL RESULT]:")||u.text&&(u.text.startsWith("[ACTION RESULT]:")||u.text.startsWith("[TOOL RESULT]:")),x=k;return he&&(k.includes("[ACTION RESULT]:")||k.includes("[TOOL RESULT]:")||u.text&&(u.text.includes("[ACTION RESULT]:")||u.text.includes("[TOOL RESULT]:")))?x="[ACTION RESULT]: ...truncated for summary":x=x.replace(/(\[(?:tool|action):[a-zA-Z0-9_\.]+)\([\s\S]*?\)(\])/g,"$1(...)$2"),`[${he?"ACTION":u.role==="agent"?"AGENT":"USER"}]: ${x}`}).join(`
625
+ `}let g=0,m=5,y=!1,h=re("gemma_janitor_fallback_google");for(i==="OpenRouter"&&(h=re("janitor_open_router")),i==="DeepSeek"&&(h=re("deepseek_level_1")),i==="Mistral"&&(h=re("mistral_level_1")),i==="NVIDIA"&&(h=re("nvidia_janitor_fallback")),i==="InferX"&&(h=re("inferx_fallback")),i==="SenseNova"&&(h=re("sensenova_fallback")),i==="AIHubMix"&&(h=re("aihubmix_fallback")),i==="Poolside"&&(h=re("poolside_fallback")),(i==="9router"||i==="9Router")&&(h=re("9router_fallback"));g<=m&&!y;){g++;try{let s=(await oi(n,h,c,null,"Fast",.75,"background")).text||"",u=to(s);if(u.length===0)throw new Error("No tool calls detected in synthesis response");for(let k of u){let he=k.toolName;["saveSummary","saveSumary","SaveSummary","SaveSumary"].includes(he)&&await Ro(he,k.args,{chatId:e})}y=!0}catch(f){if(g>=m)throw new Error(`Failed after ${m} attempts. Last error: ${f.message}`)}}}catch(i){let o=i instanceof Error?(()=>{try{return JSON.parse(JSON.parse(i.message).error.message).error.message}catch{return String(i)}})():String(i),r=W.join(kn,"janitor");be.existsSync(r)||be.mkdirSync(r,{recursive:!0}),be.appendFileSync(W.join(r,"error.log"),`[${new Date().toLocaleString()}] Past memory batch consolidation error: ${o}
626
+ `)}},Jc=async(e,n,t=!1)=>{let{chatId:i,aiProvider:o="Google"}=e,r=W.join(No,"chat-summaries.json"),c=s=>s.filter(u=>(u.role==="user"||u.role==="agent"||u.role==="system")&&u.role!=="think"&&!u.isVisualFeedback&&!u.isMeta&&!u.isTerminalRecord&&!(u.text&&u.text.includes("[TERMINAL_RECORD]"))&&!String(u.id).startsWith("welcome")).map(u=>{let k=u.fullText||u.text||"",he=u.role==="system"||k.startsWith("[ACTION RESULT]:")||k.startsWith("[TOOL RESULT]:")||u.text&&(u.text.startsWith("[ACTION RESULT]:")||u.text.startsWith("[TOOL RESULT]:")),x=k;return he&&(k.includes("[ACTION RESULT]:")||k.includes("[TOOL RESULT]:")||u.text&&(u.text.includes("[ACTION RESULT]:")||u.text.includes("[TOOL RESULT]:")))?x="[ACTION RESULT]: ...truncated for summary":x=x.replace(/(\[(?:tool|action):[a-zA-Z0-9_\.]+)\([\s\S]*?\)(\])/g,"$1(...)$2"),`[${he?"ACTION":u.role==="agent"?"AGENT":"USER"}]: ${x}`}).join(`
627
627
 
628
628
  `),a=async(s,u)=>{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=u?`Here is the previous summary:
629
629
  ${u}
@@ -634,9 +634,9 @@ ${s}
634
634
  Provide a new consolidated summary of the entire session.`:`Here is the conversation history:
635
635
  ${s}
636
636
 
637
- Provide a consolidated summary of the entire session.`,x=re("gemma_janitor_fallback_google");o==="OpenRouter"&&(x=re("janitor_open_router")),o==="DeepSeek"&&(x=re("deepseek_level_1")),o==="Mistral"&&(x=re("mistral_level_1")),o==="NVIDIA"&&(x=re("nvidia_chat_summarizer_fallback")),o==="InferX"&&(x=re("inferx_fallback")),o==="SenseNova"&&(x=re("sensenova_fallback")),o==="AIHubMix"&&(x=re("aihubmix_fallback")),o==="Poolside"&&(x=re("poolside_fallback")),(o==="9router"||o==="9Router")&&(x=re("9router_fallback")),(o==="ExpLabs"||o==="ExperientialLabs")&&(x=re("explabs_fallback")||"deepseek-v4-pro-0813"),(o==="TokenHarbor"||o==="Token Harbor"||o==="tokenharbor"||o==="token_harbor"||o==="thk")&&(x=re("tokenharbor_fallback")||"deepseek-v4.1-flash:free"),(o==="Infron"||o==="infron")&&(x=re("infron_fallback"));let I=0,G=!1,q=null;for(;I<=3&&!G;){I++;try{q=await ni(e,x,he,k,"Fast"),G=!0}catch{if(I>3){if(o==="Google")try{let A=re("general_fallback");return(await ni(e,A,he,k,"Fast")).text||""}catch{return""}return""}}}return q&&q.text||""},h=c(n),g=Rt(r,{}),y=g[i]||{summary:"",historyLength:0};typeof y=="string"&&(y={summary:y,historyLength:0});let m=y.summary||"",f=await a(h,m);if(f){y.summary=f;let s=Ba(n);return t?y.historyLength=(y.historyLength||0)+s:y.historyLength=s,g[i]=y,Qn(r,g),f}return null},Qc=e=>{try{let n=j.join(Po,"chat-summaries.json");if(be.existsSync(n)){let t=Rt(n,{});t[e]&&(delete t[e],Qn(n,t))}}catch{}},Zc=async function*(e,n,t,i,o){let{profile:r,thinkingLevel:c,mode:a,janitorModel:h,chatId:g,isPlayground:y,systemSettings:m,sessionStats:f,aiProvider:s="Google",apiTier:u,wildcardTooling:k,wildercardTooling:he}=t,x=ot(e);if(!qi&&s==="Google")throw new Error("AI not initialized");let I=process.env.NVIDIA_BASE_URL||t?.aiProvider==="Ollama"||t?.aiProvider==="InferX"||t?.aiProvider==="SenseNova"||t?.aiProvider==="AIHubMix"||t?.aiProvider==="Poolside"||t?.aiProvider==="9router"||t?.aiProvider==="ExpLabs"||t?.aiProvider==="ExperientialLabs"||t?.aiProvider==="TokenHarbor"||t?.aiProvider==="Token Harbor"||t?.aiProvider==="tokenharbor"||t?.aiProvider==="token_harbor"||t?.aiProvider==="thk"||t?.aiProvider==="APInex"||t?.aiProvider==="apinex"||t?.aiProvider==="apx"||t?.aiProvider==="Infron"||t?.aiProvider==="infron"||t?.aiProvider==="c_openai"||t?.aiProvider==="Custom (OpenAI)"?!1:m?.memory!==!1,G=n[n.length-1].text,q=j.join(Po,"chat-summaries.json"),D=!1,A=n.filter(T=>T.role==="user").length===1,ge=G.includes("[TITLE-UPDATE]"),we=A||ge,Me=G.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 No.startTransaction(g,Me),m?.advanceRollback&&await ho.takeInitialSnapshot(g),mt=!1;let ye=null;try{let T=new AbortController;ye=setInterval(()=>{mt&&(T.abort(),ye&&(clearInterval(ye),ye=null))},400);let b=[...n.slice(0,-1)];{let Be=Rt(q,{})[g]||{summary:"",historyLength:0};if(Be.summary&&Be.historyLength>0){let mn=0,ze=[];for(let Ae=0;Ae<b.length;Ae++){let qe=b[Ae];(qe.role==="user"||qe.role==="agent"||qe.role==="system")&&!String(qe.id).startsWith("welcome")&&!qe.isMeta&&mn++,mn>Be.historyLength&&ze.push(qe)}b=ze}}b=b.map(P=>{if(P.role==="user"&&P.text){let Be=P.text.match(/\[USER\]([\s\S]*?)\[\/USER\]/);if(Be)return{...P,text:Be[1].trim()}}return{...P}});let rt=process.env.HIGH_CONTEXT,Oe=process.env.GOOGLE_GEMMA_NONSENSE==="true"||process.env.GOOGLE_GEMMA_NONSENSE===!0||!1,$t={"16k":16e3,"32k":32e3,"64k":64e3,"128k":128e3,"256k":256e3,"512k":512e3,"1M":1e6}[m?.contextLength]||256e3;if(rt&&rt!=="false"){let P=parseInt(rt,10);!isNaN(P)&&P>=0&&P<=1e6&&($t=P)}if((s==="NVIDIA"&&(e?.includes("gpt")||e?.includes("qwen")||e?.includes("medium")||e.includes("muse"))||s==="Mistral")&&($t=126e3),s==="Google"&&e?.includes("gemma")&&Oe&&($t=16e3),(f?.tokens||0)>$t){yield{type:"text",content:"\u2726 Maximum Context Limit Reached. Start a new chat."};return}if(A&&I){let P=Rt(Lo,{});Object.values(P).flat().length>5&&(yield{type:"status",content:"Condensing past chat memories"},await ja(g,t,P))}let Xt=Rt(Lo,{}),dn=Rt(mi,{}),fn=Object.entries(Xt).filter(([P])=>P!==g).flatMap(([P,Be])=>Be),pe=[...Object.entries(dn).filter(([P])=>P!==g).slice(-20).map(([P,Be])=>`[Chat Summary]: ${Be}`),...fn].map(P=>`- ${P}`).join(`
637
+ Provide a consolidated summary of the entire session.`,x=re("gemma_janitor_fallback_google");o==="OpenRouter"&&(x=re("janitor_open_router")),o==="DeepSeek"&&(x=re("deepseek_level_1")),o==="Mistral"&&(x=re("mistral_level_1")),o==="NVIDIA"&&(x=re("nvidia_chat_summarizer_fallback")),o==="InferX"&&(x=re("inferx_fallback")),o==="SenseNova"&&(x=re("sensenova_fallback")),o==="AIHubMix"&&(x=re("aihubmix_fallback")),o==="Poolside"&&(x=re("poolside_fallback")),(o==="9router"||o==="9Router")&&(x=re("9router_fallback")),(o==="ExpLabs"||o==="ExperientialLabs")&&(x=re("explabs_fallback")||"deepseek-v4-pro-0813"),(o==="TokenHarbor"||o==="Token Harbor"||o==="tokenharbor"||o==="token_harbor"||o==="thk")&&(x=re("tokenharbor_fallback")||"deepseek-v4.1-flash:free"),(o==="Infron"||o==="infron")&&(x=re("infron_fallback"));let I=0,H=!1,q=null;for(;I<=3&&!H;){I++;try{q=await oi(e,x,he,k,"Fast"),H=!0}catch{if(I>3){if(o==="Google")try{let A=re("general_fallback");return(await oi(e,A,he,k,"Fast")).text||""}catch{return""}return""}}}return q&&q.text||""},g=c(n),m=Rt(r,{}),y=m[i]||{summary:"",historyLength:0};typeof y=="string"&&(y={summary:y,historyLength:0});let h=y.summary||"",f=await a(g,h);if(f){y.summary=f;let s=Ba(n);return t?y.historyLength=(y.historyLength||0)+s:y.historyLength=s,m[i]=y,Qn(r,m),f}return null},Qc=e=>{try{let n=W.join(No,"chat-summaries.json");if(be.existsSync(n)){let t=Rt(n,{});t[e]&&(delete t[e],Qn(n,t))}}catch{}},Zc=async function*(e,n,t,i,o){let{profile:r,thinkingLevel:c,mode:a,janitorModel:g,chatId:m,isPlayground:y,systemSettings:h,sessionStats:f,aiProvider:s="Google",apiTier:u,wildcardTooling:k,wildercardTooling:he}=t,x=ot(e);if(!qi&&s==="Google")throw new Error("AI not initialized");let I=process.env.NVIDIA_BASE_URL||t?.aiProvider==="Ollama"||t?.aiProvider==="InferX"||t?.aiProvider==="SenseNova"||t?.aiProvider==="AIHubMix"||t?.aiProvider==="Poolside"||t?.aiProvider==="9router"||t?.aiProvider==="ExpLabs"||t?.aiProvider==="ExperientialLabs"||t?.aiProvider==="TokenHarbor"||t?.aiProvider==="Token Harbor"||t?.aiProvider==="tokenharbor"||t?.aiProvider==="token_harbor"||t?.aiProvider==="thk"||t?.aiProvider==="APInex"||t?.aiProvider==="apinex"||t?.aiProvider==="apx"||t?.aiProvider==="Infron"||t?.aiProvider==="infron"||t?.aiProvider==="c_openai"||t?.aiProvider==="Custom (OpenAI)"?!1:h?.memory!==!1,H=n[n.length-1].text,q=W.join(No,"chat-summaries.json"),D=!1,A=n.filter(T=>T.role==="user").length===1,ge=H.includes("[TITLE-UPDATE]"),we=A||ge,Me=H.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 Bo.startTransaction(m,Me),h?.advanceRollback&&await ho.takeInitialSnapshot(m),mt=!1;let ye=null;try{let T=new AbortController;ye=setInterval(()=>{mt&&(T.abort(),ye&&(clearInterval(ye),ye=null))},400);let b=[...n.slice(0,-1)];{let Be=Rt(q,{})[m]||{summary:"",historyLength:0};if(Be.summary&&Be.historyLength>0){let mn=0,ze=[];for(let Ae=0;Ae<b.length;Ae++){let qe=b[Ae];(qe.role==="user"||qe.role==="agent"||qe.role==="system")&&!String(qe.id).startsWith("welcome")&&!qe.isMeta&&mn++,mn>Be.historyLength&&ze.push(qe)}b=ze}}b=b.map(P=>{if(P.role==="user"&&P.text){let Be=P.text.match(/\[USER\]([\s\S]*?)\[\/USER\]/);if(Be)return{...P,text:Be[1].trim()}}return{...P}});let rt=process.env.HIGH_CONTEXT,Oe=process.env.GOOGLE_GEMMA_NONSENSE==="true"||process.env.GOOGLE_GEMMA_NONSENSE===!0||!1,$t={"16k":16e3,"32k":32e3,"64k":64e3,"128k":128e3,"256k":256e3,"512k":512e3,"1M":1e6}[h?.contextLength]||256e3;if(rt&&rt!=="false"){let P=parseInt(rt,10);!isNaN(P)&&P>=0&&P<=1e6&&($t=P)}if((s==="NVIDIA"&&(e?.includes("gpt")||e?.includes("qwen")||e?.includes("medium")||e.includes("muse"))||s==="Mistral")&&($t=126e3),s==="Google"&&e?.includes("gemma")&&Oe&&($t=16e3),(f?.tokens||0)>$t){yield{type:"text",content:"\u2726 Maximum Context Limit Reached. Start a new chat."};return}if(A&&I){let P=Rt(Do,{});Object.values(P).flat().length>5&&(yield{type:"status",content:"Condensing past chat memories"},await ja(m,t,P))}let qt=Rt(Do,{}),dn=Rt(hi,{}),fn=Object.entries(qt).filter(([P])=>P!==m).flatMap(([P,Be])=>Be),pe=[...Object.entries(dn).filter(([P])=>P!==m).slice(-20).map(([P,Be])=>`[Chat Summary]: ${Be}`),...fn].map(P=>`- ${P}`).join(`
638
638
  `),S=Rt(Hn,[]).map(P=>`- ${P.memory}`).join(`
639
- `),R=(f?.tokens||0)>=1e4,Fe=new Date,ae=Fe.getFullYear(),C=Fe.toLocaleString("en-US",{month:"short"}).toUpperCase(),N=String(Fe.getDate()).padStart(2,"0"),ve=`${Fe.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0})}`,ke=P=>{try{return be.readdirSync(P,{withFileTypes:!0})}catch{return[]}},Pe=Array.from(new Set([...fo,...uo(process.cwd())])),Ro=(P,Be=6)=>m?.indentationTree!==!1?Hi(P,Be,1,ke,Pe):Vi(P,Be,"",1,ke,Pe),$n=Rt(hi,{}),no=$n[g],Eo=no?no!==process.cwd():!1;$n[g]=process.cwd(),Qn(hi,$n);let un=Rt(q,{}),Dt=un[g]||{summary:"",historyLength:0};typeof Dt=="string"&&(Dt={summary:Dt,historyLength:0});let Ze=n.filter(P=>(P.role==="user"||P.role==="agent"||P.role==="system")&&!String(P.id).startsWith("welcome")&&!P.isMeta).length;Dt.historyLength&&Ze<Dt.historyLength&&(Dt.summary="",Dt.historyLength=0,un[g]=Dt,Qn(q,un));let de=typeof Dt=="object"?Dt.summary||"":Dt||"",le=b.length>0;le&&de&&b[0]&&(b[0].role==="user"||b[0].role==="system")&&(b[0].text.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")||(b[0].text=`[SYSTEM METADATA]
639
+ `),R=(f?.tokens||0)>=1e4,Fe=new Date,ae=Fe.getFullYear(),C=Fe.toLocaleString("en-US",{month:"short"}).toUpperCase(),N=String(Fe.getDate()).padStart(2,"0"),ve=`${Fe.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0})}`,ke=P=>{try{return be.readdirSync(P,{withFileTypes:!0})}catch{return[]}},Pe=Array.from(new Set([...fo,...uo(process.cwd())])),_o=(P,Be=6)=>h?.indentationTree!==!1?Hi(P,Be,1,ke,Pe):Vi(P,Be,"",1,ke,Pe),$n=Rt(pi,{}),no=$n[m],Io=no?no!==process.cwd():!1;$n[m]=process.cwd(),Qn(pi,$n);let un=Rt(q,{}),Dt=un[m]||{summary:"",historyLength:0};typeof Dt=="string"&&(Dt={summary:Dt,historyLength:0});let Ze=n.filter(P=>(P.role==="user"||P.role==="agent"||P.role==="system")&&!String(P.id).startsWith("welcome")&&!P.isMeta).length;Dt.historyLength&&Ze<Dt.historyLength&&(Dt.summary="",Dt.historyLength=0,un[m]=Dt,Qn(q,un));let de=typeof Dt=="object"?Dt.summary||"":Dt||"",le=b.length>0;le&&de&&b[0]&&(b[0].role==="user"||b[0].role==="system")&&(b[0].text.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")||(b[0].text=`[SYSTEM METADATA]
640
640
  **CONTEXT SUMMARY OF PREVIOUS TURNS (PRIORITY: DYNAMIC)**
641
641
  ${de}
642
642
 
@@ -644,12 +644,12 @@ ${de}
644
644
  [SYSTEM METADATA]
645
645
  **CONTEXT SUMMARY OF PREVIOUS TURNS**
646
646
  ${de}
647
- `:"",oo=!!m?.dynamicDirAwareness,Yn=`${g}|${s}|${c}|${e}|${r}|${oo}`,Br=!oo&&Vn.key===Yn&&Vn.value?"":`
647
+ `:"",oo=!!h?.dynamicDirAwareness,Yn=`${m}|${s}|${c}|${e}|${r}|${oo}`,Br=!oo&&Vn.key===Yn&&Vn.value?"":`
648
648
  **Directory**
649
649
  CWD: `+process.cwd()+`${y?" [PLAYGROUND MODE]":""}
650
- `+Ro(process.cwd(),6),at=await jn(),gn="";if(Zo()&&at.file_focused!=="none"){gn=`
650
+ `+_o(process.cwd(),6),at=await jn(),gn="";if(ei()&&at.file_focused!=="none"){gn=`
651
651
  [Additional IDE Context]
652
- `;let P=j.relative(process.cwd(),at.file_focused),Be=(at.opened_editors||[]).map(ze=>{let Ae=j.relative(process.cwd(),ze);return Ae.startsWith("..")?`[External] ${j.basename(ze)}`:Ae});if(gn+=`Focused File: ${P}
652
+ `;let P=W.relative(process.cwd(),at.file_focused),Be=(at.opened_editors||[]).map(ze=>{let Ae=W.relative(process.cwd(),ze);return Ae.startsWith("..")?`[External] ${W.basename(ze)}`:Ae});if(gn+=`Focused File: ${P}
653
653
  Cursor Line: ${at.cursor_line}
654
654
  `,at.selected){let ze=at.selected,Ae=ze.split(`
655
655
  `);Ae.length>256&&(ze=Ae.slice(0,240).join(`
@@ -660,7 +660,7 @@ Cursor Line: ${at.cursor_line}
660
660
  ... [truncated] ...
661
661
  `+ze.slice(-128)),gn+=`Current Selection: "${ze}"
662
662
  `}if(at.manual_edits){let Ae=at.manual_edits.split(`
663
- `),qe=[],je=null;for(let L of Ae)L.trim()&&(L.startsWith(" Line ")?je&&je.edits.push(L):(je={path:L.endsWith(":")?L.slice(0,-1):L,edits:[]},qe.push(je)));for(let L of qe)L.edits.length>80&&(L.edits=L.edits.slice(-80)),L.originalEditsCount=L.edits.length;let Xe=(L,$e)=>$e.reduce((lt,Zt)=>{let ht=at.file_focused&&(Zt.path===at.file_focused||j.resolve(process.cwd(),Zt.path)===j.resolve(at.file_focused))?Math.ceil(L*1.2):L;return lt+Math.min(Zt.edits.length,ht)},0),Vt=80;if(Xe(80,qe)>300){let L=!1;for(let $e=80;$e>=10;$e--)if(Xe($e,qe)<=300){Vt=$e,L=!0;break}L||(Vt=10)}let Ce=[...qe];if(Vt===10&&Xe(10,Ce)>500)for(;Ce.length>0&&Xe(10,Ce)>500;){let L=0,$e=Ce[0].originalEditsCount;for(let lt=1;lt<Ce.length;lt++)Ce[lt].originalEditsCount<$e&&($e=Ce[lt].originalEditsCount,L=lt);Ce.splice(L,1)}for(let L of Ce){let lt=at.file_focused&&(L.path===at.file_focused||j.resolve(process.cwd(),L.path)===j.resolve(at.file_focused))?Math.ceil(Vt*1.2):Vt;L.edits.length>lt&&(L.edits=L.edits.slice(-lt))}for(let L of Ce){let $e=`${L.path}:
663
+ `),qe=[],je=null;for(let L of Ae)L.trim()&&(L.startsWith(" Line ")?je&&je.edits.push(L):(je={path:L.endsWith(":")?L.slice(0,-1):L,edits:[]},qe.push(je)));for(let L of qe)L.edits.length>80&&(L.edits=L.edits.slice(-80)),L.originalEditsCount=L.edits.length;let Xe=(L,$e)=>$e.reduce((lt,Qt)=>{let ht=at.file_focused&&(Qt.path===at.file_focused||W.resolve(process.cwd(),Qt.path)===W.resolve(at.file_focused))?Math.ceil(L*1.2):L;return lt+Math.min(Qt.edits.length,ht)},0),Vt=80;if(Xe(80,qe)>300){let L=!1;for(let $e=80;$e>=10;$e--)if(Xe($e,qe)<=300){Vt=$e,L=!0;break}L||(Vt=10)}let Ce=[...qe];if(Vt===10&&Xe(10,Ce)>500)for(;Ce.length>0&&Xe(10,Ce)>500;){let L=0,$e=Ce[0].originalEditsCount;for(let lt=1;lt<Ce.length;lt++)Ce[lt].originalEditsCount<$e&&($e=Ce[lt].originalEditsCount,L=lt);Ce.splice(L,1)}for(let L of Ce){let lt=at.file_focused&&(L.path===at.file_focused||W.resolve(process.cwd(),L.path)===W.resolve(at.file_focused))?Math.ceil(Vt*1.2):Vt;L.edits.length>lt&&(L.edits=L.edits.slice(-lt))}for(let L of Ce){let $e=`${L.path}:
664
664
  ${L.edits.join(`
665
665
  `)}`;for(;L.edits.length>0&&$e.length>4*768;)L.edits.shift(),$e=`${L.path}:
666
666
  ${L.edits.join(`
@@ -676,27 +676,27 @@ ${at.diagnostics}
676
676
  `),(Me.toLowerCase().includes("lint")||Me.toLowerCase().includes("warning"))&&at.warnings&&(gn+=`
677
677
  **Lint Warnings**:
678
678
  ${at.warnings}
679
- `)}let Ji=Me.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),Qi=/(?:\\)?@\[([^\]]+)\]/g,oi,ii=[];for(Qi.lastIndex=0;(oi=Qi.exec(Ji))!==null;){let P=oi[0].startsWith("\\");ii.push({tag:oi[1],isEscaped:P})}let si=[],vo=null;for(let P=0;P<ii.length;P++){let{tag:Be,isEscaped:mn}=ii[P];if(!mn)try{let ze=Be.trim().replace(/^["']|["']$/g,""),Ae=/[:#]L?(\d+)(?:-L?(\d+))?$/i,qe=ze.match(Ae),je=ze,Xe=null,Vt=null;qe&&(Xe=parseInt(qe[1],10),Vt=qe[2]?parseInt(qe[2],10):Xe,je=ze.slice(0,qe.index));let Ce=j.resolve(process.cwd(),je);if(be.existsSync(Ce)&&be.statSync(Ce).isFile()){let L=je.toLowerCase(),$e=L.endsWith(".pdf"),lt=L.endsWith(".docx")||L.endsWith(".doc")||L.endsWith(".ppt")||L.endsWith(".pptx")||L.endsWith(".xls")||L.endsWith(".xlsx"),Zt=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(L),Ne=Zt||$e||lt,ht=s==="Google"||ot(e);if(Ne&&!ht){let _e=`\u2718 Unsupported Modality: ${j.basename(je)}`,et=115;process.stdout.isTTY&&(et=process.stdout.columns-5||120);let Kt=[_e],Ve=Math.max(...Kt.map(en=>en.length)),Z=Math.min(Ve+4,et),Ue=Kt.map(en=>`${en.padEnd(Z-2).substring(0,Z-2)}`).join(`
679
+ `)}let Ji=Me.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),Qi=/(?:\\)?@\[([^\]]+)\]/g,ii,si=[];for(Qi.lastIndex=0;(ii=Qi.exec(Ji))!==null;){let P=ii[0].startsWith("\\");si.push({tag:ii[1],isEscaped:P})}let ri=[],Mo=null;for(let P=0;P<si.length;P++){let{tag:Be,isEscaped:mn}=si[P];if(!mn)try{let ze=Be.trim().replace(/^["']|["']$/g,""),Ae=/[:#]L?(\d+)(?:-L?(\d+))?$/i,qe=ze.match(Ae),je=ze,Xe=null,Vt=null;qe&&(Xe=parseInt(qe[1],10),Vt=qe[2]?parseInt(qe[2],10):Xe,je=ze.slice(0,qe.index));let Ce=W.resolve(process.cwd(),je);if(be.existsSync(Ce)&&be.statSync(Ce).isFile()){let L=je.toLowerCase(),$e=L.endsWith(".pdf"),lt=L.endsWith(".docx")||L.endsWith(".doc")||L.endsWith(".ppt")||L.endsWith(".pptx")||L.endsWith(".xls")||L.endsWith(".xlsx"),Qt=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(L),Ne=Qt||$e||lt,ht=s==="Google"||ot(e);if(Ne&&!ht){let _e=`\u2718 Unsupported Modality: ${W.basename(je)}`,et=115;process.stdout.isTTY&&(et=process.stdout.columns-5||120);let Kt=[_e],Ve=Math.max(...Kt.map(Zt=>Zt.length)),Z=Math.min(Ve+4,et),Ue=Kt.map(Zt=>`${Zt.padEnd(Z-2).substring(0,Z-2)}`).join(`
680
680
  `);yield{type:"visual_feedback",content:Ht(`${Ue}
681
- `)};continue}if(Xe===null&&!Ne){let _e=0;try{_e=be.readFileSync(Ce,"utf8").split(/\r\n|\r|\n/).length}catch{}if(_e>300){let et=`\u21B7 Skipped (Too Large): ${j.basename(je)}`,Kt=115;process.stdout.isTTY&&(Kt=process.stdout.columns-5||120);let Ve=Math.min(et.length+4,Kt),Z=et.padEnd(Ve-2).substring(0,Ve-2);yield{type:"visual_feedback",content:Ht(`${Z}
682
- `)};continue}}let hn=Xe!==null?Xe:1,_t=Vt!==null?Vt:Xe!==null?Xe:hn+299;_t-hn>300&&(_t=hn+300);let Nn=`path=${JSON.stringify(je)}, startLine=${hn}, endLine=${_t}`,Ft=await ys(Nn,{isMultiModal:ht}),Cn=!1,zn="",pt=null;if(typeof Ft=="string"?Ft.trim().startsWith("ERROR")?Cn=!0:zn=Ft:Ft&&typeof Ft=="object"&&Ft.binaryPart?(pt=Ft.binaryPart,zn=Ft.text||""):Cn=!0,!Cn){let _e="";if(Zt?(_e=`\u2714 Processed: ${j.basename(je)}`,vo=pt):$e||lt?(_e=`\u2714 Auto-Analysed: ${j.basename(je)}`,vo=pt):(_e=`\u2714 Auto-Read: ${j.basename(je)}`,si.push(zn)),_e){let et=115;process.stdout.isTTY&&(et=process.stdout.columns-5||120);let Kt=[_e],Ve=Math.max(...Kt.map(en=>en.length)),Z=Math.min(Ve+4,et),Ue=Kt.map(en=>`${en.padEnd(Z-2).substring(0,Z-2)}`).join(`
681
+ `)};continue}if(Xe===null&&!Ne){let _e=0;try{_e=be.readFileSync(Ce,"utf8").split(/\r\n|\r|\n/).length}catch{}if(_e>300){let et=`\u21B7 Skipped (Too Large): ${W.basename(je)}`,Kt=115;process.stdout.isTTY&&(Kt=process.stdout.columns-5||120);let Ve=Math.min(et.length+4,Kt),Z=et.padEnd(Ve-2).substring(0,Ve-2);yield{type:"visual_feedback",content:Ht(`${Z}
682
+ `)};continue}}let hn=Xe!==null?Xe:1,_t=Vt!==null?Vt:Xe!==null?Xe:hn+299;_t-hn>300&&(_t=hn+300);let Nn=`path=${JSON.stringify(je)}, startLine=${hn}, endLine=${_t}`,Ft=await ys(Nn,{isMultiModal:ht}),Rn=!1,zn="",pt=null;if(typeof Ft=="string"?Ft.trim().startsWith("ERROR")?Rn=!0:zn=Ft:Ft&&typeof Ft=="object"&&Ft.binaryPart?(pt=Ft.binaryPart,zn=Ft.text||""):Rn=!0,!Rn){let _e="";if(Qt?(_e=`\u2714 Processed: ${W.basename(je)}`,Mo=pt):$e||lt?(_e=`\u2714 Auto-Analysed: ${W.basename(je)}`,Mo=pt):(_e=`\u2714 Auto-Read: ${W.basename(je)}`,ri.push(zn)),_e){let et=115;process.stdout.isTTY&&(et=process.stdout.columns-5||120);let Kt=[_e],Ve=Math.max(...Kt.map(Zt=>Zt.length)),Z=Math.min(Ve+4,et),Ue=Kt.map(Zt=>`${Zt.padEnd(Z-2).substring(0,Z-2)}`).join(`
683
683
  `);yield{type:"visual_feedback",content:Ht(`${Ue}
684
- `)}}}}}catch{}}let ri="";si.length>0&&(ri=`
684
+ `)}}}}}catch{}}let ai="";ri.length>0&&(ai=`
685
685
  [Tagged File Contents] Auto Read User Tagged files by System, No need to re-read
686
- `+si.join(`
686
+ `+ri.join(`
687
687
 
688
688
  `)+`
689
689
  [Tagged File Contents]
690
690
  `);let Zi=Ji.replace(/\\(@\[[^\]]+\])/g,"$1"),es=k?`You cannot execute tools. Instead write the action string in chat you WOULD have written
691
- `:"",Ur=process.env.forcedReasoning||!1,ts=c!=="Fast"&&(s==="Mistral"&&!$o(e)||c!=="High"&&s==="Google")?`${s==="Mistral"&&!$o(e)||e.toLowerCase().startsWith("gemma")||Ur?`[system] strictly follow thinking policy as high priority. do not start a response without <think>...</think> [/system]
692
- `:""}`:"",_o="",Wr=!!m?.autoExcludeMetadata,Gr=!!(gn||ri||es||vt||ts||Eo||m?.dynamicDirAwareness||m?.autoTruncateResults);Wr&&!Gr?_o=Zi.trim():_o=`[System Metadata] Time: ${ve}${Eo?`
691
+ `:"",Ur=process.env.forcedReasoning||!1,ts=c!=="Fast"&&(s==="Mistral"&&!Fo(e)||c!=="High"&&s==="Google")?`${s==="Mistral"&&!Fo(e)||e.toLowerCase().startsWith("gemma")||Ur?`[system] strictly follow thinking policy as high priority. do not start a response without <think>...</think> [/system]
692
+ `:""}`:"",Oo="",Wr=!!h?.autoExcludeMetadata,Gr=!!(gn||ai||es||vt||ts||Io||h?.dynamicDirAwareness||h?.autoTruncateResults);Wr&&!Gr?Oo=Zi.trim():Oo=`[System Metadata] Time: ${ve}${Io?`
693
693
  WARNING: CWD Changed from previous: "${no}" to current: "${process.cwd()}", write change in chat to avoid future path mismatches
694
694
  `:""}${gn}
695
695
  Action format: [action:ActionName(...)]
696
696
  [/Metadata]
697
- ${vt}${ts}${ri}${es}[user prompt] ${Zi.trim()} [/user prompt]`.trim();let ns={role:"user",text:_o};vo&&(ns.binaryPart=vo),b.forEach(P=>{P.text&&P.role==="agent"&&(P.text=Lt(P.text))}),b.push(ns),vt&&n[n.length-1]?.id&&(yield{type:"summary_injected",content:{id:n[n.length-1].id,text:_o}});let Qt=null,An=a==="Flux"?50:15;An=a.toLowerCase().includes("cu")?75:An;let Hr=Math.floor(An/2),os=0,sn=16;yield{type:"status",content:"Connecting"},mt=!1;let ai=[],Io=!1,is=!1;for(let P=0;P<=An;P++){let Be=Math.floor(An*.95);if(P>=Be&&os<Be&&typeof t?.onAskUser=="function"){os=Be;try{let ee="Agent has been running for a long time. Do you want to continue execution?",ne=[{id:"continue",label:"Continue",description:"Add few more steps"},{id:"cancel",label:"Cancel",description:"Stop extending and finish current turn limit"}],B=await t.onAskUser(ee,ne);B&&(B.toLowerCase().includes("continue")||B==="Continue")&&(An+=Hr)}catch{}}let mn=await yi("agent",t);if(!mn.allowed)throw new Error(mn.reason||`Budget Exhausted for Provider (${s||"Agent"})`);let ze=[];if(Io=!1,a==="ICU"||a==="FluxCU")try{yield{type:"status",content:"Capturing Screen"},await new Promise(B=>setTimeout(B,1e3));let{captureGriddedScreenshot:ee}=await import("./screen_grid-PMTAQA3B.js"),ne=await ee();if(ne&&ne.base64){let B="[system] Fresh Gridded Screen Feedback Captured. Use numeric coordinates. Old screenshots will be removed when new screenshot is captured, summarize in text if context is needed later [/system]",yt={inlineData:{mimeType:ne.mimeType,data:ne.base64}},xt=m?.imageHistoryCU||"Standard",bt=xt==="Low"?3:xt==="Extended"?10:xt==="Max"?999:5,Bt=b.filter(De=>Array.isArray(De.parts)&&De.parts.some(wt=>wt.inlineData));if(Bt.length>=bt){let De=Bt.length-bt+1;for(let wt=0;wt<De;wt++){let kt=Bt[wt];Array.isArray(kt.parts)&&(kt.parts=kt.parts.filter(St=>!St.inlineData))}}if(b.length>0&&b[b.length-1].role==="user"){let De=b[b.length-1];typeof De.text=="string"&&(De.text+=`
697
+ ${vt}${ts}${ai}${es}[user prompt] ${Zi.trim()} [/user prompt]`.trim();let ns={role:"user",text:Oo};Mo&&(ns.binaryPart=Mo),b.forEach(P=>{P.text&&P.role==="agent"&&(P.text=Lt(P.text))}),b.push(ns),vt&&n[n.length-1]?.id&&(yield{type:"summary_injected",content:{id:n[n.length-1].id,text:Oo}});let Jt=null,Cn=a==="Flux"?50:15;Cn=a.toLowerCase().includes("cu")?75:Cn;let Hr=Math.floor(Cn/2),os=0,on=16;yield{type:"status",content:"Connecting"},mt=!1;let li=[],Po=!1,is=!1;for(let P=0;P<=Cn;P++){let Be=Math.floor(Cn*.95);if(P>=Be&&os<Be&&typeof t?.onAskUser=="function"){os=Be;try{let ee="Agent has been running for a long time. Do you want to continue execution?",ne=[{id:"continue",label:"Continue",description:"Add few more steps"},{id:"cancel",label:"Cancel",description:"Stop extending and finish current turn limit"}],B=await t.onAskUser(ee,ne);B&&(B.toLowerCase().includes("continue")||B==="Continue")&&(Cn+=Hr)}catch{}}let mn=await xi("agent",t);if(!mn.allowed)throw new Error(mn.reason||`Budget Exhausted for Provider (${s||"Agent"})`);let ze=[];if(Po=!1,a==="ICU"||a==="FluxCU")try{yield{type:"status",content:"Capturing Screen"},await new Promise(B=>setTimeout(B,1e3));let{captureGriddedScreenshot:ee}=await import("./screen_grid-PMTAQA3B.js"),ne=await ee();if(ne&&ne.base64){let B="[system] Fresh Gridded Screen Feedback Captured. Use numeric coordinates. Old screenshots will be removed when new screenshot is captured, summarize in text if context is needed later [/system]",yt={inlineData:{mimeType:ne.mimeType,data:ne.base64}},xt=h?.imageHistoryCU||"Standard",bt=xt==="Low"?3:xt==="Extended"?10:xt==="Max"?999:5,Bt=b.filter(De=>Array.isArray(De.parts)&&De.parts.some(wt=>wt.inlineData));if(Bt.length>=bt){let De=Bt.length-bt+1;for(let wt=0;wt<De;wt++){let kt=Bt[wt];Array.isArray(kt.parts)&&(kt.parts=kt.parts.filter(St=>!St.inlineData))}}if(b.length>0&&b[b.length-1].role==="user"){let De=b[b.length-1];typeof De.text=="string"&&(De.text+=`
698
698
 
699
- ${B}`,Array.isArray(De.parts)||(De.parts=[{text:De.text}]),De.parts.push(yt))}else b.push({role:"user",text:B,parts:[{text:B},yt]})}}catch(ee){console.error("Vision screenshot capture error:",ee)}if(m?.compression===0&&(f?.tokens||0)>$t&&(b=ps(b,6)),P>0?yield{type:"status",content:"Working"}:yield{type:"status",content:"Connecting"},mt){try{let{clearPendingNudges:ee}=await import("./subagent_state-LZCOZSUJ.js");ee()}catch{}yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
699
+ ${B}`,Array.isArray(De.parts)||(De.parts=[{text:De.text}]),De.parts.push(yt))}else b.push({role:"user",text:B,parts:[{text:B},yt]})}}catch(ee){console.error("Vision screenshot capture error:",ee)}if(h?.compression===0&&(f?.tokens||0)>$t&&(b=ps(b,6)),P>0?yield{type:"status",content:"Working"}:yield{type:"status",content:"Connecting"},mt){try{let{clearPendingNudges:ee}=await import("./subagent_state-LZCOZSUJ.js");ee()}catch{}yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
700
700
 
701
701
  \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}try{let{consumePendingNudges:ee}=await import("./subagent_state-LZCOZSUJ.js"),ne=ee();if(ne&&ne.length>0){let B=ne.join(`
702
702
 
@@ -708,42 +708,42 @@ ${B}`:b.push({role:"user",text:B}),yield{type:"status",content:"Subagent Update"
708
708
  [question] ${ee.replace("/btw","").trim()} [/question]`:b.push({role:"user",text:`[system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
709
709
  [question] ${ee.replace("/btw","").trim()} [/question]`}):b.length>0&&b[b.length-1].role==="user"?b[b.length-1].text+=`
710
710
 
711
- [STEERING HINT from USER, High Priority] ${ee.trim()} [/STEERING HINT]`:b.push({role:"user",text:`[STEERING HINT from USER, High Priority] ${ee.trim()} [/STEERING HINT]`}),yield{type:"status",content:`${ee.startsWith("/btw")?"Question Forwarded...":"Steering Hint Injected..."}`})}let Ae,qe=!1,je=1,Xe=1,Vt=Date.now(),Ce=null,ue="",L=null,$e=null,lt=null,Zt=0,Ne=[],ht=0,hn=!1,_t=!1,Nn=!1,Ft=!1,Cn=!0,zn=0,pt="",_e="",et=!1,Kt=!1,Ve=!0,Z=e,Ue="",en=c;for(c=c.toLowerCase()==="max"?"High":c;je<=sn&&Xe<=sn&&!qe&&!mt;){let ee=!1;try{ue="",Cn&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},Cn=!1,Xe===1&&(pt=""));let ne=p=>{if(!p||typeof p!="string")return p;let v="",E=Yi(p);if(E&&(v=E.fullBlock,p=E.remainingText),!p.includes("[tool:")&&!p.includes("[action:"))return(m?.keepReasoningContext?v:"")+p;if(to(p).length===0){let w=ei(p);return(m?.keepReasoningContext?v:"")+w}p=p.replace(Da,(w,_)=>_.includes("[tool:")||_.includes("[action:")?_.trim():w);let oe="",$=0,H=[],ct="";for(;$<p.length;){let w=p.indexOf("[tool:",$),_=p.indexOf("[action:",$),X=-1;if(w!==-1&&_!==-1?X=Math.min(w,_):w!==-1?X=w:X=_,X===-1){H.length===0&&(oe+=ei(p.substring($)));break}if((X>0?p[X-1]:"")==="`"){oe+=ei(p.substring($,X+1)),$=X+1;continue}H.length===0&&(ct=ei(p.substring($,X)));let V=-1,O=null,dt=0;for(let It=X;It<p.length;It++){let J=p[It];if(O){if(J===O){let He=0;for(let ft=It-1;ft>=0&&p[ft]==="\\";ft--)He++;He%2===0&&(O=null)}}else if(J==='"'||J==="'"||J==="`")O=J;else if(J==="(")dt++;else if(J===")")dt--;else if(J==="]"&&dt<=0){V=It;break}}if(V===-1){H.length===0&&(oe+=p.substring(X));break}let yn=p.substring(X,V+1);H.push(yn),$=V+1}return H.length>0&&(oe=ct.trimEnd()?ct.trimEnd()+`
711
+ [STEERING HINT from USER, High Priority] ${ee.trim()} [/STEERING HINT]`:b.push({role:"user",text:`[STEERING HINT from USER, High Priority] ${ee.trim()} [/STEERING HINT]`}),yield{type:"status",content:`${ee.startsWith("/btw")?"Question Forwarded...":"Steering Hint Injected..."}`})}let Ae,qe=!1,je=1,Xe=1,Vt=Date.now(),Ce=null,ue="",L=null,$e=null,lt=null,Qt=0,Ne=[],ht=0,hn=!1,_t=!1,Nn=!1,Ft=!1,Rn=!0,zn=0,pt="",_e="",et=!1,Kt=!1,Ve=!0,Z=e,Ue="",Zt=c;for(c=c.toLowerCase()==="max"?"High":c;je<=on&&Xe<=on&&!qe&&!mt;){let ee=!1;try{ue="",Rn&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},Rn=!1,Xe===1&&(pt=""));let ne=p=>{if(!p||typeof p!="string")return p;let v="",E=Yi(p);if(E&&(v=E.fullBlock,p=E.remainingText),!p.includes("[tool:")&&!p.includes("[action:"))return(h?.keepReasoningContext?v:"")+p;if(to(p).length===0){let w=ti(p);return(h?.keepReasoningContext?v:"")+w}p=p.replace(Da,(w,_)=>_.includes("[tool:")||_.includes("[action:")?_.trim():w);let oe="",$=0,j=[],ct="";for(;$<p.length;){let w=p.indexOf("[tool:",$),_=p.indexOf("[action:",$),X=-1;if(w!==-1&&_!==-1?X=Math.min(w,_):w!==-1?X=w:X=_,X===-1){j.length===0&&(oe+=ti(p.substring($)));break}if((X>0?p[X-1]:"")==="`"){oe+=ti(p.substring($,X+1)),$=X+1;continue}j.length===0&&(ct=ti(p.substring($,X)));let V=-1,O=null,dt=0;for(let It=X;It<p.length;It++){let J=p[It];if(O){if(J===O){let He=0;for(let ft=It-1;ft>=0&&p[ft]==="\\";ft--)He++;He%2===0&&(O=null)}}else if(J==='"'||J==="'"||J==="`")O=J;else if(J==="(")dt++;else if(J===")")dt--;else if(J==="]"&&dt<=0){V=It;break}}if(V===-1){j.length===0&&(oe+=p.substring(X));break}let yn=p.substring(X,V+1);j.push(yn),$=V+1}return j.length>0&&(oe=ct.trimEnd()?ct.trimEnd()+`
712
712
 
713
- `+H.join(`
713
+ `+j.join(`
714
714
 
715
- `):H.join(`
715
+ `):j.join(`
716
716
 
717
- `)),(m?.keepReasoningContext?v:"")+oe},B=b.filter(p=>(p.role==="user"||p.role==="agent"||p.role==="system")&&!String(p.id).startsWith("welcome")&&!p.isMeta&&!p.isTerminalRecord&&!(p.text&&p.text.startsWith("[TERMINAL_RECORD]"))).map((p,v,E)=>{let K=p.text||"";I||(K=K.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),p.role==="agent"&&(K=ne(K),K=K.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),K=K.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*"));let oe=[];return Array.isArray(p.parts)&&p.parts.length>0?oe=p.parts.map($=>{if($.text){let H=$.text;return I||(H=H.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),p.role==="agent"&&(H=ne(H),H=H.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),H=H.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*")),{text:H}}return $}):oe=[{text:K}],p.binaryPart&&ot(Z)&&E.slice(v+1).filter(H=>H.role==="user"&&!H.text?.startsWith("[ACTION RESULT]")&&!H.text?.startsWith("[TOOL RESULT]")).length<=2&&oe.push(p.binaryPart),{role:p.role==="user"||p.role==="system"?"user":"model",parts:oe}});for(let p=B.length-2;p>=0;p--){let v=B[p],E=B[p+1];v.role==="user"&&E.role==="user"&&(E.parts?.[0]?.text||"").trim().startsWith("[SYSTEM")&&B.splice(p,1)}let yt=[];for(let p=0;p<B.length;p++){let v=B[p];if(yt.length===0)yt.push(v);else{let E=yt[yt.length-1];E.role===v.role?(E.parts[0].text+=`
717
+ `)),(h?.keepReasoningContext?v:"")+oe},B=b.filter(p=>(p.role==="user"||p.role==="agent"||p.role==="system")&&!String(p.id).startsWith("welcome")&&!p.isMeta&&!p.isTerminalRecord&&!(p.text&&p.text.startsWith("[TERMINAL_RECORD]"))).map((p,v,E)=>{let K=p.text||"";I||(K=K.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),p.role==="agent"&&(K=ne(K),K=K.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),K=K.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*"));let oe=[];return Array.isArray(p.parts)&&p.parts.length>0?oe=p.parts.map($=>{if($.text){let j=$.text;return I||(j=j.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),p.role==="agent"&&(j=ne(j),j=j.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),j=j.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*")),{text:j}}return $}):oe=[{text:K}],p.binaryPart&&ot(Z)&&E.slice(v+1).filter(j=>j.role==="user"&&!j.text?.startsWith("[ACTION RESULT]")&&!j.text?.startsWith("[TOOL RESULT]")).length<=2&&oe.push(p.binaryPart),{role:p.role==="user"||p.role==="system"?"user":"model",parts:oe}});for(let p=B.length-2;p>=0;p--){let v=B[p],E=B[p+1];v.role==="user"&&E.role==="user"&&(E.parts?.[0]?.text||"").trim().startsWith("[SYSTEM")&&B.splice(p,1)}let yt=[];for(let p=0;p<B.length;p++){let v=B[p];if(yt.length===0)yt.push(v);else{let E=yt[yt.length-1];E.role===v.role?(E.parts[0].text+=`
718
718
 
719
- `+(v.parts?.[0]?.text||""),v.parts?.length>1&&E.parts.push(...v.parts.slice(1))):yt.push(v)}}for(let p of yt)for(let v of p.parts||[])v&&typeof v.text=="string"&&(v.text.includes("[action:")||v.text.includes("[tool:"))&&(v.text=v.text.replace(/```(?:[a-zA-Z0-9_-]+)?\s*\n?(\[(?:action|tool):[\s\S]*?\)\s*\])\n?```/gi,"$1"),v.text=v.text.replace(/`(\[(?:action|tool):[\s\S]*?\)\s*\])`/gi,"$1"));B.length=0,B.push(...yt),Z=e;let xt=`${g}|${s}|${a}|${c}|${en}|${Z}|${JSON.stringify(r)}|${!!m?.dynamicDirAwareness}|${!!m?.subAgents}`,bt=Vn.key===xt&&Vn.value;if((process.env.I_HAVE_TOO_MUCH_MONEY==="true"||process.env.I_HAVE_TOO_MUCH_MONEY===!0)&&(bt=!1),bt)Ue=Vn.value;else{let p=s==="Mistral"?!!$o(Z):!(Z||"gemma").toLowerCase().startsWith("gemma");Ue=Zs(r,((Z||"gemma").toLowerCase().startsWith("gemma"),en),a,m,I,A,s,s==="Google"?!0:x,p,g,!!m?.keepReasoningContext,Z),m?.dynamicDirAwareness||(Ue+=`
719
+ `+(v.parts?.[0]?.text||""),v.parts?.length>1&&E.parts.push(...v.parts.slice(1))):yt.push(v)}}for(let p of yt)for(let v of p.parts||[])v&&typeof v.text=="string"&&(v.text.includes("[action:")||v.text.includes("[tool:"))&&(v.text=v.text.replace(/```(?:[a-zA-Z0-9_-]+)?\s*\n?(\[(?:action|tool):[\s\S]*?\)\s*\])\n?```/gi,"$1"),v.text=v.text.replace(/`(\[(?:action|tool):[\s\S]*?\)\s*\])`/gi,"$1"));B.length=0,B.push(...yt),Z=e;let xt=`${m}|${s}|${a}|${c}|${Zt}|${Z}|${JSON.stringify(r)}|${!!h?.dynamicDirAwareness}|${!!h?.subAgents}`,bt=Vn.key===xt&&Vn.value;if((process.env.I_HAVE_TOO_MUCH_MONEY==="true"||process.env.I_HAVE_TOO_MUCH_MONEY===!0)&&(bt=!1),bt)Ue=Vn.value;else{let p=s==="Mistral"?!!Fo(Z):!(Z||"gemma").toLowerCase().startsWith("gemma");Ue=Zs(r,((Z||"gemma").toLowerCase().startsWith("gemma"),Zt),a,h,I,A,s,s==="Google"?!0:x,p,m,!!h?.keepReasoningContext,Z),h?.dynamicDirAwareness||(Ue+=`
720
720
  ${Br.replace(`
721
721
  **Directory**`,`
722
- -- Directory --`)}`),Vn.key=xt,Vn.value=Ue}let De=B[B.length-1];if(Zo()&P>0){await new Promise(E=>setTimeout(E,2500)),yield{type:"status",content:"Verifying"};let p=await jn(),v=p?p.diagnostics:null;v&&De&&De.role==="user"&&De.parts?.[0]?.text&&(De.parts[0].text+=`
722
+ -- Directory --`)}`),Vn.key=xt,Vn.value=Ue}let De=B[B.length-1];if(ei()&P>0){await new Promise(E=>setTimeout(E,2500)),yield{type:"status",content:"Verifying"};let p=await jn(),v=p?p.diagnostics:null;v&&De&&De.role==="user"&&De.parts?.[0]?.text&&(De.parts[0].text+=`
723
723
 
724
- ${v} [/ERROR]`),yield{type:"status",content:"Working"}}let wt=s==="Mistral"||s==="Google"&&e?.toLowerCase().startsWith("gemma");if(m?.advanceRollback&&De&&De.role==="user"&&(De.parts?.[0]?.text?.startsWith("[ACTION RESULT]")||De.parts?.[0]?.text?.startsWith("[TOOL RESULT]")))try{let p=await ho.getLatestFileChanges(g);if(p&&(p.newFiles.length>0||p.modifiedFiles.length>0||p.deletedFiles.length>0)){let v=`
724
+ ${v} [/ERROR]`),yield{type:"status",content:"Working"}}let wt=s==="Mistral"||s==="Google"&&e?.toLowerCase().startsWith("gemma");if(h?.advanceRollback&&De&&De.role==="user"&&(De.parts?.[0]?.text?.startsWith("[ACTION RESULT]")||De.parts?.[0]?.text?.startsWith("[TOOL RESULT]")))try{let p=await ho.getLatestFileChanges(m);if(p&&(p.newFiles.length>0||p.modifiedFiles.length>0||p.deletedFiles.length>0)){let v=`
725
725
  [system] File Changes:
726
726
  `;for(let K of p.newFiles)v+=`* ${K} (created)
727
727
  `;for(let K of p.modifiedFiles)v+=`* ${K} (modified)
728
728
  `;for(let K of p.deletedFiles)v+=`* ${K} (deleted)
729
- `;v+="[/system]",De.parts[0].text+=v;let E=-1;for(let K=b.length-1;K>=0;K--)if(b[K].role==="user"&&(b[K].text?.startsWith("[ACTION RESULT]")||b[K].text?.startsWith("[TOOL RESULT]"))){E=K;break}E!==-1&&(b[E].text+=v)}}catch{}let kt=Math.floor(An*.99),St=P+1;St>=kt&&De&&De.parts?.[0]&&(De.parts[0].text+=`
730
- [system] WARNING, Turn Limit Impending: Step ${St}/${An}. Wrap up quickly/prompt user to continue. [/system]`),process.env.NO_DEV==="true"||process.env.NO_DEV==="1"||process.env.NO_DEV===!0||(be.existsSync(`${qt}/chats/${g}`)||be.mkdirSync(`${qt}/chats/${g}`,{recursive:!0}),be.writeFileSync(`${qt}/chats/${g}/context.json`,`${JSON.stringify({contents:B},null,2)}`),be.writeFileSync(`${qt}/chats/${g}/system.md`,`${bt?"CACHED":"NOT CACHED"}
729
+ `;v+="[/system]",De.parts[0].text+=v;let E=-1;for(let K=b.length-1;K>=0;K--)if(b[K].role==="user"&&(b[K].text?.startsWith("[ACTION RESULT]")||b[K].text?.startsWith("[TOOL RESULT]"))){E=K;break}E!==-1&&(b[E].text+=v)}}catch{}let kt=Math.floor(Cn*.99),St=P+1;if(St>=kt&&De&&De.parts?.[0]&&(De.parts[0].text+=`
730
+ [system] WARNING, Turn Limit Impending: Step ${St}/${Cn}. Wrap up quickly/prompt user to continue. [/system]`),!(process.env.NO_DEV==="true"||process.env.NO_DEV==="1"||process.env.NO_DEV===!0||!1)){let p=W.join(kn,"chats",String(m));be.existsSync(p)||be.mkdirSync(p,{recursive:!0}),be.writeFileSync(W.join(p,"context.json"),JSON.stringify({contents:B},null,2)),be.writeFileSync(W.join(p,"system.md"),`${bt?"CACHED":"NOT CACHED"}
731
731
  Key: ${xt}
732
732
 
733
- ${Ue}`));let Rn=new Promise((p,v)=>{T.signal.aborted&&v(new DOMException("The user aborted a request.","AbortError")),T.signal.addEventListener("abort",()=>{v(new DOMException("The user aborted a request.","AbortError"))})});Rn.catch(()=>{});let At=B;if(Vt=Date.now(),s==="Ollama")Ae=(await ce("Ollama"))(t.apiKey,Z,At,Ue,c,a,x,T.signal,1,m?.ollamaEndpoint||"Cloud");else if(s==="OpenRouter")Ae=(await ce("OpenRouter"))(t.apiKey,Z,At,Ue,c,a,x,T.signal,1,g);else if(s==="DeepSeek")Ae=(await ce("DeepSeek"))(t.apiKey,Z,At,Ue,c,a,x,T.signal,1);else if(s==="Mistral")Ae=(await ce("Mistral"))(t.apiKey,Z,At,Ue,c,a,x,T.signal,1,g);else if(s==="NVIDIA"){let p=(await ce("NVIDIA"))(t.apiKey,Z,At,Ue,c,a,x,T.signal,1);Ae=(await ce("NVIDIA_wrap"))(p,Z)}else if(s==="InferX")Ae=(await ce("InferX"))(t.apiKey,Z,At,Ue,c,a,x,T.signal,1);else if(s==="SenseNova")Ae=(await ce("SenseNova"))(t.apiKey,Z,At,Ue,c,a,x,T.signal,1);else if(s==="AIHubMix")Ae=(await ce("AIHubMix"))(t.apiKey,Z,At,Ue,c,a,x,T.signal,1);else if(s==="Poolside")Ae=(await ce("Poolside"))(t.apiKey,Z,At,Ue,c,a,x,T.signal,1);else if(s==="9router"||s==="9Router")Ae=(await ce("NineRouter"))(t.apiKey,Z,At,Ue,c,a,x,T.signal,1);else if(s==="ExpLabs"||s==="ExperientialLabs")Ae=(await ce("ExpLabs"))(t.apiKey,Z,At,Ue,c,a,x,T.signal,1);else if(s==="Infron"||s==="infron")Ae=(await ce("Infron"))(t.apiKey,Z,At,Ue,c,a,x,T.signal,1);else if(s==="TokenHarbor"||s==="Token Harbor"||s==="tokenharbor"||s==="token_harbor"||s==="thk")Ae=(await ce("TokenHarbor"))(t.apiKey,Z,At,Ue,c,a,x,T.signal,1);else if(s==="APInex"||s==="apinex"||s==="apx")Ae=(await ce("APInex"))(t.apiKey,Z,At,Ue,c,a,x,T.signal,1);else if(s==="c_openai"||s==="Custom (OpenAI)")Ae=(await ce("c_openai"))(t.apiKey,Z,At,Ue,c,a,x,T.signal,1,m?.customOpenAIBaseUrl||"");else{let p=Xi(t?.apiKey),{serviceTier:v,cleanModel:E}=Fr(Z),K={systemInstruction:Ue,mediaResolution:"MEDIA_RESOLUTION_HIGH",safetySettings:[{category:Ln.HARM_CATEGORY_HARASSMENT,threshold:Pn.BLOCK_NONE},{category:Ln.HARM_CATEGORY_HATE_SPEECH,threshold:Pn.BLOCK_NONE},{category:Ln.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Pn.BLOCK_NONE},{category:Ln.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Pn.BLOCK_NONE}],temperature:1.05,thinkingConfig:(()=>{let $=hs("Google",Z||"gemini-3-flash-preview",c);if($!==null){if(typeof $=="object")return $;if($===!1||$==="false"||$==="none"||$===0||$==="0")return{includeThoughts:!1};if(typeof $=="number")return{includeThoughts:!0,thinkingBudget:$};if(typeof $=="string"){let _=$.toLowerCase();if(_==="minimal")return{includeThoughts:!0,thinkingLevel:Ge.MINIMAL};if(_==="low")return{includeThoughts:!0,thinkingLevel:Ge.LOW};if(_==="medium")return{includeThoughts:!0,thinkingLevel:Ge.MEDIUM};if(_==="high")return{includeThoughts:!0,thinkingLevel:Ge.HIGH};let X=Number($);if(!isNaN(X))return{includeThoughts:!0,thinkingBudget:X}}}let H=(Z||"").toLowerCase(),ct=H.includes("gemma-4")||H.startsWith("gemma"),w=H.includes("gemini-3");if(ct||w)return ct?c.toLowerCase()!=="high"?{includeThoughts:!1,thinkingLevel:Ge.MINIMAL}:{includeThoughts:!0,thinkingLevel:Ge.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:H.includes("pro")?Ge.LOW:Ge.MINIMAL,Low:Ge.LOW,Medium:Ge.MEDIUM,Standard:Ge.MEDIUM,High:Ge.HIGH,xHigh:Ge.HIGH}[c]||Ge.MEDIUM};{let _={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[c]||2048;return _===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:_}}})()};v&&(K.serviceTier=v);let oe=p.models.generateContentStream({model:E||"gemini-3-flash-preview",contents:At,config:K},{signal:T.signal});Ae=await Promise.race([oe,Rn])}ue="",L=null,lt=null,Ne=[],ht=0,yield{type:"model_update",content:null},_e="",et=pt.length>0;let tn="",ci=Date.now(),Fn=async function*(){if(s==="Google"&&tn){let p=so(tn);for(let v of p)yield v;tn="",ci=Date.now()}},ss=!0,pn="",qn=!1,Ct=null,rs=!1,Bn=!1,Xn=!1,Mo=!1,En=!1,io=p=>{let v=0;for(;v+2<p.length;)p[v]==="`"&&p[v+1]==="`"&&p[v+2]==="`"?(Mo=!Mo,v+=3):v++},as=p=>{if(!p)return;let v=/(?:<(\/?)(?:think|thought|thoughts)[^>]*>|\[(\/?)(?:think|thought|thoughts)\]|<\/?channel\|?>|<\|channel>thought)/gi,E;for(;(E=v.exec(p))!==null;){let K=E[0].toLowerCase();K.startsWith("</")||K.startsWith("[/")||K==="<channel|>"?En=!1:En=!0}},Yr={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|>"}},so=p=>{let v=[],E=p,K=oe=>{if(!oe)return;if(!rs){v.push({type:"text",content:oe}),io(oe),as(oe);return}let $=/(?:<(\/?)(?:think|thought|thoughts)[^>]*>|\[(\/?)(?:think|thought|thoughts)\]|<\/?channel\|?>|<\|channel>thought)/gi,H=0,ct;for(;(ct=$.exec(oe))!==null;){let _=oe.substring(H,ct.index);if(_)if(io(_),En)v.push({type:"text",content:_});else{let Le=_.replace(/[^\r\n]/g,"");Le&&v.push({type:"text",content:Le})}let X=ct[0];io(X);let l=X.toLowerCase();l.startsWith("</")||l.startsWith("[/")||l==="<channel|>"?En=!1:En=!0,v.push({type:"text",content:X}),H=$.lastIndex}let w=oe.substring(H);if(w)if(io(w),En)v.push({type:"text",content:w});else{let _=w.replace(/[^\r\n]/g,"");_&&v.push({type:"text",content:_})}};for(;E.length>0;)if(qn){let oe=pn+E,$=Yr[Ct];if($){let w=!1;if(oe.length<$.startPrefix.length?$.startPrefix.startsWith(oe)||(w=!0):oe.startsWith($.startPrefix)?oe.length>=$.fullPrefix.length&&!oe.startsWith($.fullPrefix)&&(w=!0):w=!0,w){K(oe),pn="",qn=!1,Ct=null,Bn=!1,Xn=!1,E="";break}}let H=-1,ct=$?$.endTag:"]";if(Ct==="tool"||Ct==="action"){let w=0,_=null,X=0,l=!1;for(let Le=0;Le<oe.length;Le++){let V=oe[Le];if(_){if(V===_){let O=0;for(let dt=Le-1;dt>=0&&oe[dt]==="\\";dt--)O++;O%2===0&&(_=null)}}else if(V==='"'||V==="'")_=V;else if(V==="`")if(Bn){H=Le;break}else _=V;else if(V==="(")w++,l=!0;else if(V===")")w--;else if(V==="]"&&l&&w===0){H=Le;break}}}else H=oe.indexOf(ct);if(H!==-1){let w=ct.length,_=oe.substring(0,H+w);Ct?.startsWith("kimi")||v.push({type:"text",content:_}),io(_),as(_),(Ct==="tool"||Ct==="action"||Ct?.startsWith("kimi"))&&!Bn&&!Xn&&(rs=!0),Bn=!1,Xn=!1,pn="",qn=!1,Ct=null,E=oe.substring(H+w)}else{pn=oe,E="";break}}else{let oe=E.indexOf("[tool"),$=E.indexOf("[action"),H=E.indexOf("[[END]]"),ct=E.indexOf("<|tool_calls_section_begin|>"),w=E.indexOf("<|tool_call_begin|>"),_=[{type:"tool",idx:oe,start:"[tool",end:"]"},{type:"action",idx:$,start:"[action",end:"]"},{type:"end",idx:H,start:"[[END]]",end:"[[END]]"},{type:"kimi_section",idx:ct,start:"<|tool_calls_section_begin|>",end:"<|tool_calls_section_end|>"},{type:"kimi_call",idx:w,start:"<|tool_call_begin|>",end:"<|tool_call_end|>"}].filter(X=>X.idx!==-1).sort((X,l)=>X.idx-l.idx);if(_.length>0){let X=_[0],l=E.substring(0,X.idx);X.idx>0&&K(l);let Le=X.idx>0?E[X.idx-1]:"";Bn=Mo||Le==="`",Xn=En,qn=!0,Ct=X.type,pn="",E=E.substring(X.idx)}else{let X=["[tool","[action","[[END]]","<|tool_calls_section_begin|>","<|tool_call_begin|>"],l=-1;for(let Le of X){for(let V=Le.length-1;V>0;V--)if(E.endsWith(Le.substring(0,V))){l=E.length-V;let O=X.indexOf(Le);O===0?Ct="tool":O===1?Ct="action":O===2?Ct="end":O===3?Ct="kimi_section":Ct="kimi_call";break}if(l!==-1)break}if(l!==-1){if(l>0){let V=E.substring(0,l);K(V)}let Le=l>0?E[l-1]:"";Bn=Mo||Le==="`",Xn=En,qn=!0,pn=E.substring(l),E=""}else{K(E);break}}}return v},zr=Ae[Symbol.asyncIterator]();for(;;){let{value:p,done:v}=await Promise.race([zr.next(),Rn]);if(v)break;if(p&&p.type==="status"){yield p;continue}let E="",K=p.candidates?.[0]?.content?.parts;if(K&&K.length>0)for(let $ of K){let H=typeof $.text=="string"?$.text:$.text?parseChunkText($.text):"";$.thought?H&&(ee||(E+="<think>",ee=!0),E+=H):H&&(ee&&(E+="</think>",ee=!1),E+=H)}else p.text&&ee&&(E+="</think>",ee=!1);E=Pa(E);let oe=E?xi(E):0;if(t&&typeof t.onTokenChunk=="function"&&t.onTokenChunk(E,oe),ss&&(Ce===null&&(Ce=Date.now()-Vt),yield{type:"status",content:"Thinking"},ss=!1),mt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
733
+ ${Ue}`)}let En=new Promise((p,v)=>{T.signal.aborted&&v(new DOMException("The user aborted a request.","AbortError")),T.signal.addEventListener("abort",()=>{v(new DOMException("The user aborted a request.","AbortError"))})});En.catch(()=>{});let At=B;if(Vt=Date.now(),s==="Ollama")Ae=(await ce("Ollama"))(t.apiKey,Z,At,Ue,c,a,x,T.signal,1,h?.ollamaEndpoint||"Cloud");else if(s==="OpenRouter")Ae=(await ce("OpenRouter"))(t.apiKey,Z,At,Ue,c,a,x,T.signal,1,m);else if(s==="DeepSeek")Ae=(await ce("DeepSeek"))(t.apiKey,Z,At,Ue,c,a,x,T.signal,1);else if(s==="Mistral")Ae=(await ce("Mistral"))(t.apiKey,Z,At,Ue,c,a,x,T.signal,1,m);else if(s==="NVIDIA"){let p=(await ce("NVIDIA"))(t.apiKey,Z,At,Ue,c,a,x,T.signal,1);Ae=(await ce("NVIDIA_wrap"))(p,Z)}else if(s==="InferX")Ae=(await ce("InferX"))(t.apiKey,Z,At,Ue,c,a,x,T.signal,1);else if(s==="SenseNova")Ae=(await ce("SenseNova"))(t.apiKey,Z,At,Ue,c,a,x,T.signal,1);else if(s==="AIHubMix")Ae=(await ce("AIHubMix"))(t.apiKey,Z,At,Ue,c,a,x,T.signal,1);else if(s==="Poolside")Ae=(await ce("Poolside"))(t.apiKey,Z,At,Ue,c,a,x,T.signal,1);else if(s==="9router"||s==="9Router")Ae=(await ce("NineRouter"))(t.apiKey,Z,At,Ue,c,a,x,T.signal,1);else if(s==="ExpLabs"||s==="ExperientialLabs")Ae=(await ce("ExpLabs"))(t.apiKey,Z,At,Ue,c,a,x,T.signal,1);else if(s==="Infron"||s==="infron")Ae=(await ce("Infron"))(t.apiKey,Z,At,Ue,c,a,x,T.signal,1);else if(s==="TokenHarbor"||s==="Token Harbor"||s==="tokenharbor"||s==="token_harbor"||s==="thk")Ae=(await ce("TokenHarbor"))(t.apiKey,Z,At,Ue,c,a,x,T.signal,1);else if(s==="APInex"||s==="apinex"||s==="apx")Ae=(await ce("APInex"))(t.apiKey,Z,At,Ue,c,a,x,T.signal,1);else if(s==="c_openai"||s==="Custom (OpenAI)")Ae=(await ce("c_openai"))(t.apiKey,Z,At,Ue,c,a,x,T.signal,1,h?.customOpenAIBaseUrl||"");else{let p=Xi(t?.apiKey),{serviceTier:v,cleanModel:E}=Fr(Z),K={systemInstruction:Ue,mediaResolution:"MEDIA_RESOLUTION_HIGH",safetySettings:[{category:Ln.HARM_CATEGORY_HARASSMENT,threshold:Pn.BLOCK_NONE},{category:Ln.HARM_CATEGORY_HATE_SPEECH,threshold:Pn.BLOCK_NONE},{category:Ln.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Pn.BLOCK_NONE},{category:Ln.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Pn.BLOCK_NONE}],temperature:1.05,thinkingConfig:(()=>{let $=hs("Google",Z||"gemini-3-flash-preview",c);if($!==null){if(typeof $=="object")return $;if($===!1||$==="false"||$==="none"||$===0||$==="0")return{includeThoughts:!1};if(typeof $=="number")return{includeThoughts:!0,thinkingBudget:$};if(typeof $=="string"){let _=$.toLowerCase();if(_==="minimal")return{includeThoughts:!0,thinkingLevel:Ge.MINIMAL};if(_==="low")return{includeThoughts:!0,thinkingLevel:Ge.LOW};if(_==="medium")return{includeThoughts:!0,thinkingLevel:Ge.MEDIUM};if(_==="high")return{includeThoughts:!0,thinkingLevel:Ge.HIGH};let X=Number($);if(!isNaN(X))return{includeThoughts:!0,thinkingBudget:X}}}let j=(Z||"").toLowerCase(),ct=j.includes("gemma-4")||j.startsWith("gemma"),w=j.includes("gemini-3");if(ct||w)return ct?c.toLowerCase()!=="high"?{includeThoughts:!1,thinkingLevel:Ge.MINIMAL}:{includeThoughts:!0,thinkingLevel:Ge.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:j.includes("pro")?Ge.LOW:Ge.MINIMAL,Low:Ge.LOW,Medium:Ge.MEDIUM,Standard:Ge.MEDIUM,High:Ge.HIGH,xHigh:Ge.HIGH}[c]||Ge.MEDIUM};{let _={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[c]||2048;return _===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:_}}})()};v&&(K.serviceTier=v);let oe=p.models.generateContentStream({model:E||"gemini-3-flash-preview",contents:At,config:K},{signal:T.signal});Ae=await Promise.race([oe,En])}ue="",L=null,lt=null,Ne=[],ht=0,yield{type:"model_update",content:null},_e="",et=pt.length>0;let en="",di=Date.now(),Fn=async function*(){if(s==="Google"&&en){let p=so(en);for(let v of p)yield v;en="",di=Date.now()}},ss=!0,pn="",qn=!1,Ct=null,rs=!1,Bn=!1,Xn=!1,Lo=!1,vn=!1,io=p=>{let v=0;for(;v+2<p.length;)p[v]==="`"&&p[v+1]==="`"&&p[v+2]==="`"?(Lo=!Lo,v+=3):v++},as=p=>{if(!p)return;let v=/(?:<(\/?)(?:think|thought|thoughts)[^>]*>|\[(\/?)(?:think|thought|thoughts)\]|<\/?channel\|?>|<\|channel>thought)/gi,E;for(;(E=v.exec(p))!==null;){let K=E[0].toLowerCase();K.startsWith("</")||K.startsWith("[/")||K==="<channel|>"?vn=!1:vn=!0}},Yr={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|>"}},so=p=>{let v=[],E=p,K=oe=>{if(!oe)return;if(!rs){v.push({type:"text",content:oe}),io(oe),as(oe);return}let $=/(?:<(\/?)(?:think|thought|thoughts)[^>]*>|\[(\/?)(?:think|thought|thoughts)\]|<\/?channel\|?>|<\|channel>thought)/gi,j=0,ct;for(;(ct=$.exec(oe))!==null;){let _=oe.substring(j,ct.index);if(_)if(io(_),vn)v.push({type:"text",content:_});else{let Le=_.replace(/[^\r\n]/g,"");Le&&v.push({type:"text",content:Le})}let X=ct[0];io(X);let l=X.toLowerCase();l.startsWith("</")||l.startsWith("[/")||l==="<channel|>"?vn=!1:vn=!0,v.push({type:"text",content:X}),j=$.lastIndex}let w=oe.substring(j);if(w)if(io(w),vn)v.push({type:"text",content:w});else{let _=w.replace(/[^\r\n]/g,"");_&&v.push({type:"text",content:_})}};for(;E.length>0;)if(qn){let oe=pn+E,$=Yr[Ct];if($){let w=!1;if(oe.length<$.startPrefix.length?$.startPrefix.startsWith(oe)||(w=!0):oe.startsWith($.startPrefix)?oe.length>=$.fullPrefix.length&&!oe.startsWith($.fullPrefix)&&(w=!0):w=!0,w){K(oe),pn="",qn=!1,Ct=null,Bn=!1,Xn=!1,E="";break}}let j=-1,ct=$?$.endTag:"]";if(Ct==="tool"||Ct==="action"){let w=0,_=null,X=0,l=!1;for(let Le=0;Le<oe.length;Le++){let V=oe[Le];if(_){if(V===_){let O=0;for(let dt=Le-1;dt>=0&&oe[dt]==="\\";dt--)O++;O%2===0&&(_=null)}}else if(V==='"'||V==="'")_=V;else if(V==="`")if(Bn){j=Le;break}else _=V;else if(V==="(")w++,l=!0;else if(V===")")w--;else if(V==="]"&&l&&w===0){j=Le;break}}}else j=oe.indexOf(ct);if(j!==-1){let w=ct.length,_=oe.substring(0,j+w);Ct?.startsWith("kimi")||v.push({type:"text",content:_}),io(_),as(_),(Ct==="tool"||Ct==="action"||Ct?.startsWith("kimi"))&&!Bn&&!Xn&&(rs=!0),Bn=!1,Xn=!1,pn="",qn=!1,Ct=null,E=oe.substring(j+w)}else{pn=oe,E="";break}}else{let oe=E.indexOf("[tool"),$=E.indexOf("[action"),j=E.indexOf("[[END]]"),ct=E.indexOf("<|tool_calls_section_begin|>"),w=E.indexOf("<|tool_call_begin|>"),_=[{type:"tool",idx:oe,start:"[tool",end:"]"},{type:"action",idx:$,start:"[action",end:"]"},{type:"end",idx:j,start:"[[END]]",end:"[[END]]"},{type:"kimi_section",idx:ct,start:"<|tool_calls_section_begin|>",end:"<|tool_calls_section_end|>"},{type:"kimi_call",idx:w,start:"<|tool_call_begin|>",end:"<|tool_call_end|>"}].filter(X=>X.idx!==-1).sort((X,l)=>X.idx-l.idx);if(_.length>0){let X=_[0],l=E.substring(0,X.idx);X.idx>0&&K(l);let Le=X.idx>0?E[X.idx-1]:"";Bn=Lo||Le==="`",Xn=vn,qn=!0,Ct=X.type,pn="",E=E.substring(X.idx)}else{let X=["[tool","[action","[[END]]","<|tool_calls_section_begin|>","<|tool_call_begin|>"],l=-1;for(let Le of X){for(let V=Le.length-1;V>0;V--)if(E.endsWith(Le.substring(0,V))){l=E.length-V;let O=X.indexOf(Le);O===0?Ct="tool":O===1?Ct="action":O===2?Ct="end":O===3?Ct="kimi_section":Ct="kimi_call";break}if(l!==-1)break}if(l!==-1){if(l>0){let V=E.substring(0,l);K(V)}let Le=l>0?E[l-1]:"";Bn=Lo||Le==="`",Xn=vn,qn=!0,pn=E.substring(l),E=""}else{K(E);break}}}return v},zr=Ae[Symbol.asyncIterator]();for(;;){let{value:p,done:v}=await Promise.race([zr.next(),En]);if(v)break;if(p&&p.type==="status"){yield p;continue}let E="",K=p.candidates?.[0]?.content?.parts;if(K&&K.length>0)for(let $ of K){let j=typeof $.text=="string"?$.text:$.text?parseChunkText($.text):"";$.thought?j&&(ee||(E+="<think>",ee=!0),E+=j):j&&(ee&&(E+="</think>",ee=!1),E+=j)}else p.text&&ee&&(E+="</think>",ee=!1);E=Pa(E);let oe=E?bi(E):0;if(t&&typeof t.onTokenChunk=="function"&&t.onTokenChunk(E,oe),ss&&(Ce===null&&(Ce=Date.now()-Vt),yield{type:"status",content:"Thinking"},ss=!1),mt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
734
734
 
735
- \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(E){if(et){if(_e+=E,_e.length>=64){let w=0,_=Math.min(pt.length,_e.length);for(let l=_;l>=10;l--)if(pt.endsWith(_e.substring(0,l))){w=l;break}let X=_e.substring(w);if(X){let Le=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(pt)?X.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):X.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(Le)if(ue+=Le,s==="Google")tn+=Le;else{yield*Fn();let V=so(Le);for(let O of V)yield O}}et=!1,_e=""}continue}else if(ue+=E,s==="Google")tn+=E;else{yield*Fn();let w=so(E);for(let _ of w)yield _}let $=Wa(ue);if($.inside){Kt=!0,lt||(lt=Date.now());let _={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"}[$.toolName]||$.toolName,X=$.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(_)){let V=W(X),O=V.basename||V.name||V.path||V.targetFile||V.TargetFile||V.directory||V.file,dt=V.keyword,yn=V.title||V.task,It=V.id||V.taskId,J=V.timeout||V.time||V.seconds||V.sec;if(dt!=null)l=String(dt).replace(kn,"");else if(O)l=j.basename(String(O).replace(kn,"").replace(vr,"/"));else if(yn&&(_==="invoke"||_==="invoke_sync"))l=String(yn).replace(kn,"").substring(0,30);else if(It&&_==="get_progress")l=String(It).replace(kn,"");else if(J&&_==="await"){let He=parseFloat(String(J).replace(kn,""));isNaN(He)?l=String(J).replace(kn,""):(He<5&&(He=5),He>120&&(He=180),l=(Mt=>{if(Mt>=60){let ao=Math.floor(Mt/60),xn=Mt%60;return`${ao}m${xn>0?` ${xn}s`:""}`}return`${Mt}s`})(He))}else if(J&&_==="wait"){let He=parseFloat(String(J).replace(kn,""));isNaN(He)?l=String(J).replace(kn,""):(He<10&&(He=10),He>120&&(He=120),l=(Mt=>{if(Mt>=60){let ao=Math.floor(Mt/60),xn=Mt%60;return`${ao}m${xn>0?` ${xn}s`:""}`}return`${Mt}s`})(He))}else{let He=X.match(Ia);if(He){let ft=He[1].replace(kn,"");_==="invoke"||_==="invoke_sync"||_==="get_progress"?l=ft.substring(0,30):l=_==="search_keyword"||_==="file_map"?ft:j.basename(ft.replace(vr,"/"))}}}let Le=`${zi[_]||_}${l?` ${l}`:""}`;if((_!==L||l!==$e)&&(L=_,$e=l,yield{type:"status",content:`${Le}`},process.stdout.isTTY)){let O={WebSearch:"Searching",web_search:"Searching",WebScrape:"Reading",web_scrape:"Reading",ReadFile:"Reading",read_file:"Reading",ReadFolder:"Reading",read_folder:"Reading",WriteFile:"Writing",write_file:"Writing",UpdateFile:"Editing",update_file:"Editing",WritePdf:"Creating",write_pdf:"Creating",WriteDocx:"Creating",write_docx:"Creating",SearchKeyword:"Searching",search_keyword:"Searching",CodeSearch:"Searching",code_search:"Searching",FindFile:"Finding File",find_file:"Finding File",Run:"Executing",Ask:"User Input Required",AskUser:"User Input Required",Memory:"Updating Memory",GenerateImage:"Generating",InvokeSync:"Sub-Agent Working",invoke_sync:"Sub-Agent Working",Invoke:"Working",invoke:"Working",GetProgress:"Checking Progress",get_progress:"Checking Progress",Cancel:"Stopping Generalist",cancel:"Stopping Generalist",Await:"Waiting",await:"Waiting",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"}[_]||"Working";process.stdout.write(`\x1B]0;${O}...\x07`)}}if(ue.length-zn>800){zn=ue.length;let w=Dr(ue,!1),_=Yi(w),X=_?(_.innerContent||"").trim():"",l=X.split(/[.!?]\s+/).filter(me=>me.trim().length>10),Le=new Set(l),V=l.length>25?(l.length-Le.size)/l.length:0,O=X.split(/\s+/).filter(me=>me.length>0).length,dt=.9,yn=.92,It=!1;if(s.toLowerCase().includes("google")&&(Z||"").toLowerCase().startsWith("gemma")){let d={low:2048,medium:4096,high:32768,max:65536,xhigh:65536}[c?.toLowerCase()]||16e3;It=O>d}if(V>dt||It){yield{type:"status",content:`${V>dt?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},_t=!0,await new Promise(d=>setTimeout(d,3e3));break}let ft=Or(ue).trim().split(/[.!?]\s+/).filter(me=>me.trim().length>10),Mt=new Set(ft);if((ft.length>25?(ft.length-Mt.size)/ft.length:0)>yn){yield{type:"status",content:"Response Loop Detected. Re-centering..."},_t=!1,Ft=!0,await new Promise(me=>setTimeout(me,3e3));break}let xn=w.replace(ka,"").replace(Aa,"").replace(Ca,"").replace(Ra,""),Ot=xn.toLowerCase().split(/\s+/).map(me=>me.replace(Ea,"")).filter(me=>me.length>0),bn=!1;if(Ot.length>=40)for(let me=1;me<=15;me++){let d=Math.max(8,Math.ceil(25/me));if(Ot.length<me*d)continue;let M=Ot.slice(Ot.length-me),Y=M.join(" ");if(me>1&&Y===M.slice(0,Math.floor(me/2)).join(" ").repeat(2).trim())continue;let ie=!0;for(let te=1;te<d;te++)if(Ot.slice(Ot.length-me*(te+1),Ot.length-me*te).join(" ")!==Y){ie=!1;break}if(ie){bn=!0;break}}if(!bn){let me=xn.toLowerCase().replace(va,"");if(me.length>=80)for(let d=1;d<=10;d++){let M=Math.max(15,Math.ceil(45/d));if(me.length<d*M)continue;let Y=me.substring(me.length-d),ie=!0;for(let te=1;te<M;te++)if(me.substring(me.length-d*(te+1),me.length-d*te)!==Y){ie=!1;break}if(ie){bn=!0;break}}}if(bn){yield{type:"status",content:"Stuttering Detected. Re-centering..."},_t=!1,Nn=!0,await new Promise(me=>setTimeout(me,3e3));break}}let H=Lt(ue),ct=to(H);for(;ct.length>ht;){yield*Fn();let w=ct[ht],_=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=zi[l]||w.toolName,V=Kn(l,w.args);yield{type:"status",content:`${Le}${V?` ${V}`:""}`};let O="";if(l==="click"){let d=W(w.args);O=`\u2714 Clicked: ${d.intendedClickText?`${d.intendedClickText}`:""}`}else if(l==="drag"){let d=W(w.args);O=`\u2714 Dragged: Cell ${d.fromGridId||""} \u2192 Cell ${d.toGridId||""}`}else if(l==="scroll"){let d=W(w.args);O=`\u2714 Scrolled: ${d.direction||"down"} (${d.amount||1})`}else if(l==="keyboard_typing"){let d=W(w.args);O=`\u2714 Typed: ${d.text?`"${d.text.length>20?d.text.substring(0,20)+"...":d.text}"`:""}`}else if(l==="key_press")O=`\u2714 Pressed Key: ${W(w.args).key||""}`;else if(l==="recapture_screen")O="\u2714 Recaptured Screen";else if(l==="web_search"){let{query:d,limit:M=10,aiMode:Y=!1}=W(w.args);O=`${d?"\u2714":"\u2718"} ${Y?"AI Search":"Searched"}: ${d?`${d}`:"No Search Query"}${Y===!1&&d?` \u2192 ${M}`:""}`}else if(l==="web_scrape"){let d=W(w.args).url||null;O=`${d?"\u2714":"\u2718"} Visited: ${d||"No Source"}`}else if(l==="view_file"){let{path:d,StartLine:M,EndLine:Y,start_line:ie,end_line:te,startLine:Te,endLine:Re}=W(w.args),fe=M||ie||Te,F=Y||te||Re,U=parseInt(fe)||1,z=parseInt(F)||(fe?U+800:800),Ie="...",We=z,se=(d||"").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")?O="\u2714 Read Documentation":O=`\u2714 Read Skill: ${j.basename(d.replaceAll("\\","/"))}`;else{try{let Q=j.resolve(process.cwd(),d);if(be.existsSync(Q)){let ut=be.readFileSync(Q,"utf8").split(`
736
- `).length;Ie=ut,!fe&&!F&&ut>800?We=Math.min(50,ut):We=Math.min(z,ut)}}catch{}let xe=(d||"").toLowerCase(),it=xe.endsWith(".pdf"),Ee=xe.endsWith(".docx")||xe.endsWith(".doc")||xe.endsWith(".ppt")||xe.endsWith(".pptx")||xe.endsWith(".xls")||xe.endsWith(".xlsx"),Ke=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(xe);it||Ee?O=`${d.length>0?"\u2714":"\u2718"} ${d?`Analyzed: ${j.basename(d)}`:"Analyzed: File Not Found"}`:Ke?O=`${d.length>0?"\u2714":"\u2718"} ${d?`Processed: ${j.basename(d)}`:"Processed: File Not Found"}`:O=`${Ie!=="..."?"\u2714":"\u2718"} Read: ${d?`${j.basename(d)} \u2192 ${Ie!=="..."?`Lines ${U} - ${We} of ${Ie}`:"File Not Found"}`:"File Not Found"}`}}else if(l==="list_files"||l==="read_folder"){let d=l==="list_files"?"List":"Browsed",M=W(w.args).path||null,Y=W(w.args).recurse||1;O=`${M?"\u2714":"\u2718"} ${d}: ${M?`${M==="."?`./${Y>1?"*":""}`:`${M.replaceAll("\\","/")}${Y>1?`${M.endsWith("/")?"*":"/*"}`:`${M.endsWith("/")?"":"/"}`}`}`:"No Folder Selected"}`}else if(l==="find_file"){let d=W(w.args),M=d.basename||d.name||d.path||d.file||d.query||"";O=`${M?"\u2714":"\u2718"} Located: ${M||"No Query"}`}else if(l==="write_file"||l==="update_file"){let d=l==="write_file"?"Created":"Edited",M=W(w.args),Y=M.path||null,te=Object.entries(M).some(([Te,Re])=>Te.startsWith("searchContent")&&typeof Re=="string"&&Re.startsWith("^LINE:"))?"\u1361":":";O=`${Y?"\u2714":"\u2718"} ${d}${te} ${Y?Y.replaceAll("\\","/"):"No File Changes"}`}else if(l==="write_pdf"){let d=W(w.args).path||null;O=`${d?"\u2714":"\u2718"} Generated: ${d.replaceAll("\\","/")||"No PDF Generated"}`}else if(l==="write_docx"){let d=W(w.args).path||null;O=`${d?"\u2714":"\u2718"} Generated: ${d.replaceAll("\\","/")||"No Docx Generated"}`}else if(l==="file_map"){let d=W(w.args).path;O=`${d?"\u2714":"\u2718"} Indexed: ${d.replaceAll("\\","/")?""+d:"File Not Found"}`}else if(l.toLowerCase()==="search_keyword"||l.toLowerCase()==="todo")O="";else if(l.toLowerCase()==="generate_image"){let{path:d,outputPath:M,output:Y}=W(w.args);O=`\u2714 Generated: ${d||M||Y||"generated_image.png"}`}else if(l==="invoke_sync"||l==="InvokeSync"){let d=Kn(l,w.args);O=`\u2714 Called Generalist${d?`: ${d}`:""}`}else if(l==="Invoke"||l==="InvokeAsync"||l==="invoke"){let d=Kn(l,w.args);O=`\u2714 Started Generalist${d?`: ${d}`:""}`}else if(l==="get_progress"||l==="GetProgress"){let d=Kn(l,w.args);O=`\u2714 Checked${d?`: ${d}`:""}`}else if(l==="cancel"){let d=Kn(l,w.args);O=`\u{1F6C7} Cancelled${d?`: ${d}`:""}`}else if(l==="steer"||l==="Steer"){let d=Kn(l,w.args);O=`\u2714 Steered${d?`: ${d}`:""}`}else if(l==="EmergencyRollback"){let{method:d}=W(w.args);O=d==="forceRevert"?"":"\u2714 Rollback Point Checked"}else if(l==="await"||l==="Await"||l==="wait"||l==="Wait"){let{time:d,timeout:M,seconds:Y,sec:ie}=W(w.args),te=parseFloat(Y||ie||M||d)||45,Te=l==="wait"||l==="Wait"?120:180;te<10&&(te=10),te>Te&&(te=Te);let Re=U=>{if(U>=60){let z=Math.floor(U/60),Ie=U%60;return`${z}m${Ie>0?` ${Ie}s`:""}`}return`${U}s`},fe=["Aligning Moon Phase","Contemplating Existence","Staring At Void","Delaying Professionally","Negotiating With Electrons","Touching Grass (virtually)","Panicking Softly","Rethinking Career Choices","Loading Cat Videos","Summoning Braincell #2","Pretending To Be Busy","Waiting For Motivation DLC","Rotating Internal Screaming","Downloading More RAM","Feeding The Hamsters","Gaslighting Scheduler","Performing Dramatic Pause","Buffering Social Energy","Calculating Regret","Reading Terms And Conditions","Becoming Sentient Briefly","Contacting Ancestors"];O=`\u2714 ${fe[Math.floor(Math.random()*fe.length)]} \u2192 ${Re(te)}`}else l==="Answer"||l==="answer"?O="\u2714 Resolved Sub-Agent Query":l==="exec_command"||l==="ask"?O="":O=`Executed: ${w.toolName}`;if(yield*Fn(),l==="exec_command"){let{command:d}=W(w.args);if(d&&t.systemSettings&&t.systemSettings.allowExternalAccess===!1){let M=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],Y=j.resolve(process.cwd()).substring(0,3).toLowerCase(),ie=F=>{let U=[],z="",Ie=null;for(let We=0;We<F.length;We++){let se=F[We];Ie?(se===Ie&&(Ie=null),z+=se):se==='"'||se==="'"?(Ie=se,z+=se):se==="&"&&F[We+1]==="&"||se==="|"&&F[We+1]==="|"?(z.trim()&&(U.push(z.trim()),z=""),We++):se===";"||se==="|"||se==="&"?z.trim()&&(U.push(z.trim()),z=""):z+=se}return z.trim()&&U.push(z.trim()),U},te=F=>{let U=[],z="",Ie=null;for(let We=0;We<F.length;We++){let se=F[We];Ie?(se===Ie&&(Ie=null),z+=se):se==='"'||se==="'"?(Ie=se,z+=se):/\s/.test(se)?z&&(U.push(z),z=""):z+=se}return z&&U.push(z),U},Te=F=>{let U=F.replace(/^['"]|['"]$/g,"").trim();return!U||process.platform==="win32"&&/^\/[a-zA-Z0-9?]+$/.test(U)?!1:M.some(z=>{if(z.source==="[a-zA-Z]:[\\\\\\/]"){let Ie=U.match(/[a-zA-Z]:[\\\/]/i);return Ie&&Ie[0].toLowerCase()!==Y}return z.test(U)})};if(ie(d).some(F=>{let U=te(F);if(U.length===0)return!1;let z=U[0].replace(/^['"]|['"]$/g,"").toLowerCase();if(["echo","printf","write-output"].includes(z)){let We=!1;return U.some(se=>{let Tt=se.replace(/^['"]|['"]$/g,"");if(Tt===">"||Tt===">>"||Tt==="<")return We=!0,!1;if(Tt.startsWith(">")||Tt.startsWith("<")){let xe=Tt.replace(/^[><]+/,"");return Te(xe)}return We?(We=!1,Te(se)):!1})}return U.some(We=>Te(We))})){let F='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(U=>setTimeout(U,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${F}`),await new Promise(U=>setTimeout(U,50)),t.onExecEnd&&t.onExecEnd(),Ne.push({role:"user",text:`[ACTION RESULT]: ERROR: ${F}`}),yield{type:"tool_result",content:`[ACTION RESULT]: ERROR: ${F}`},ht++;continue}}t.onExecStart&&t.onExecStart(d||"No Command"),yield{type:"exec_start"}}let dt=W(w.args),yn=dt.path||dt.targetPath||null;if(yn){let d=t.systemSettings&&t.systemSettings.allowExternalAccess===!1,M=j.resolve(yn),Y=j.resolve(process.cwd());if(d&&!M.startsWith(Y)){let ie="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"}: ${dt.path||"..."}`,Re=115;process.stdout.isTTY&&(Re=process.stdout.columns-5||120);let fe=Math.min(Te.length+4,Re),F=`${Te.padEnd(fe-2).substring(0,fe-2)}`;yield{type:"visual_feedback",content:Ht(`${Ve?`
735
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(E){if(et){if(_e+=E,_e.length>=64){let w=0,_=Math.min(pt.length,_e.length);for(let l=_;l>=10;l--)if(pt.endsWith(_e.substring(0,l))){w=l;break}let X=_e.substring(w);if(X){let Le=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(pt)?X.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):X.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(Le)if(ue+=Le,s==="Google")en+=Le;else{yield*Fn();let V=so(Le);for(let O of V)yield O}}et=!1,_e=""}continue}else if(ue+=E,s==="Google")en+=E;else{yield*Fn();let w=so(E);for(let _ of w)yield _}let $=Wa(ue);if($.inside){Kt=!0,lt||(lt=Date.now());let _={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"}[$.toolName]||$.toolName,X=$.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(_)){let V=G(X),O=V.basename||V.name||V.path||V.targetFile||V.TargetFile||V.directory||V.file,dt=V.keyword,yn=V.title||V.task,It=V.id||V.taskId,J=V.timeout||V.time||V.seconds||V.sec;if(dt!=null)l=String(dt).replace(An,"");else if(O)l=W.basename(String(O).replace(An,"").replace(vr,"/"));else if(yn&&(_==="invoke"||_==="invoke_sync"))l=String(yn).replace(An,"").substring(0,30);else if(It&&_==="get_progress")l=String(It).replace(An,"");else if(J&&_==="await"){let He=parseFloat(String(J).replace(An,""));isNaN(He)?l=String(J).replace(An,""):(He<5&&(He=5),He>120&&(He=180),l=(Mt=>{if(Mt>=60){let ao=Math.floor(Mt/60),xn=Mt%60;return`${ao}m${xn>0?` ${xn}s`:""}`}return`${Mt}s`})(He))}else if(J&&_==="wait"){let He=parseFloat(String(J).replace(An,""));isNaN(He)?l=String(J).replace(An,""):(He<10&&(He=10),He>120&&(He=120),l=(Mt=>{if(Mt>=60){let ao=Math.floor(Mt/60),xn=Mt%60;return`${ao}m${xn>0?` ${xn}s`:""}`}return`${Mt}s`})(He))}else{let He=X.match(Ia);if(He){let ft=He[1].replace(An,"");_==="invoke"||_==="invoke_sync"||_==="get_progress"?l=ft.substring(0,30):l=_==="search_keyword"||_==="file_map"?ft:W.basename(ft.replace(vr,"/"))}}}let Le=`${zi[_]||_}${l?` ${l}`:""}`;if((_!==L||l!==$e)&&(L=_,$e=l,yield{type:"status",content:`${Le}`},process.stdout.isTTY)){let O={WebSearch:"Searching",web_search:"Searching",WebScrape:"Reading",web_scrape:"Reading",ReadFile:"Reading",read_file:"Reading",ReadFolder:"Reading",read_folder:"Reading",WriteFile:"Writing",write_file:"Writing",UpdateFile:"Editing",update_file:"Editing",WritePdf:"Creating",write_pdf:"Creating",WriteDocx:"Creating",write_docx:"Creating",SearchKeyword:"Searching",search_keyword:"Searching",CodeSearch:"Searching",code_search:"Searching",FindFile:"Finding File",find_file:"Finding File",Run:"Executing",Ask:"User Input Required",AskUser:"User Input Required",Memory:"Updating Memory",GenerateImage:"Generating",InvokeSync:"Sub-Agent Working",invoke_sync:"Sub-Agent Working",Invoke:"Working",invoke:"Working",GetProgress:"Checking Progress",get_progress:"Checking Progress",Cancel:"Stopping Generalist",cancel:"Stopping Generalist",Await:"Waiting",await:"Waiting",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"}[_]||"Working";process.stdout.write(`\x1B]0;${O}...\x07`)}}if(ue.length-zn>800){zn=ue.length;let w=Dr(ue,!1),_=Yi(w),X=_?(_.innerContent||"").trim():"",l=X.split(/[.!?]\s+/).filter(me=>me.trim().length>10),Le=new Set(l),V=l.length>25?(l.length-Le.size)/l.length:0,O=X.split(/\s+/).filter(me=>me.length>0).length,dt=.9,yn=.92,It=!1;if(s.toLowerCase().includes("google")&&(Z||"").toLowerCase().startsWith("gemma")){let d={low:2048,medium:4096,high:32768,max:65536,xhigh:65536}[c?.toLowerCase()]||16e3;It=O>d}if(V>dt||It){yield{type:"status",content:`${V>dt?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},_t=!0,await new Promise(d=>setTimeout(d,3e3));break}let ft=Or(ue).trim().split(/[.!?]\s+/).filter(me=>me.trim().length>10),Mt=new Set(ft);if((ft.length>25?(ft.length-Mt.size)/ft.length:0)>yn){yield{type:"status",content:"Response Loop Detected. Re-centering..."},_t=!1,Ft=!0,await new Promise(me=>setTimeout(me,3e3));break}let xn=w.replace(ka,"").replace(Aa,"").replace(Ca,"").replace(Ra,""),Ot=xn.toLowerCase().split(/\s+/).map(me=>me.replace(Ea,"")).filter(me=>me.length>0),bn=!1;if(Ot.length>=40)for(let me=1;me<=15;me++){let d=Math.max(8,Math.ceil(25/me));if(Ot.length<me*d)continue;let M=Ot.slice(Ot.length-me),Y=M.join(" ");if(me>1&&Y===M.slice(0,Math.floor(me/2)).join(" ").repeat(2).trim())continue;let ie=!0;for(let te=1;te<d;te++)if(Ot.slice(Ot.length-me*(te+1),Ot.length-me*te).join(" ")!==Y){ie=!1;break}if(ie){bn=!0;break}}if(!bn){let me=xn.toLowerCase().replace(va,"");if(me.length>=80)for(let d=1;d<=10;d++){let M=Math.max(15,Math.ceil(45/d));if(me.length<d*M)continue;let Y=me.substring(me.length-d),ie=!0;for(let te=1;te<M;te++)if(me.substring(me.length-d*(te+1),me.length-d*te)!==Y){ie=!1;break}if(ie){bn=!0;break}}}if(bn){yield{type:"status",content:"Stuttering Detected. Re-centering..."},_t=!1,Nn=!0,await new Promise(me=>setTimeout(me,3e3));break}}let j=Lt(ue),ct=to(j);for(;ct.length>ht;){yield*Fn();let w=ct[ht],_=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=zi[l]||w.toolName,V=Kn(l,w.args);yield{type:"status",content:`${Le}${V?` ${V}`:""}`};let O="";if(l==="click"){let d=G(w.args);O=`\u2714 Clicked: ${d.intendedClickText?`${d.intendedClickText}`:""}`}else if(l==="drag"){let d=G(w.args);O=`\u2714 Dragged: Cell ${d.fromGridId||""} \u2192 Cell ${d.toGridId||""}`}else if(l==="scroll"){let d=G(w.args);O=`\u2714 Scrolled: ${d.direction||"down"} (${d.amount||1})`}else if(l==="keyboard_typing"){let d=G(w.args);O=`\u2714 Typed: ${d.text?`"${d.text.length>20?d.text.substring(0,20)+"...":d.text}"`:""}`}else if(l==="key_press")O=`\u2714 Pressed Key: ${G(w.args).key||""}`;else if(l==="recapture_screen")O="\u2714 Recaptured Screen";else if(l==="web_search"){let{query:d,limit:M=10,aiMode:Y=!1}=G(w.args);O=`${d?"\u2714":"\u2718"} ${Y?"AI Search":"Searched"}: ${d?`${d}`:"No Search Query"}${Y===!1&&d?` \u2192 ${M}`:""}`}else if(l==="web_scrape"){let d=G(w.args).url||null;O=`${d?"\u2714":"\u2718"} Visited: ${d||"No Source"}`}else if(l==="view_file"){let{path:d,StartLine:M,EndLine:Y,start_line:ie,end_line:te,startLine:Te,endLine:Re}=G(w.args),fe=M||ie||Te,F=Y||te||Re,U=parseInt(fe)||1,z=parseInt(F)||(fe?U+800:800),Ie="...",We=z,se=(d||"").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")?O="\u2714 Read Documentation":O=`\u2714 Read Skill: ${W.basename(d.replaceAll("\\","/"))}`;else{try{let Q=W.resolve(process.cwd(),d);if(be.existsSync(Q)){let ut=be.readFileSync(Q,"utf8").split(`
736
+ `).length;Ie=ut,!fe&&!F&&ut>800?We=Math.min(50,ut):We=Math.min(z,ut)}}catch{}let xe=(d||"").toLowerCase(),it=xe.endsWith(".pdf"),Ee=xe.endsWith(".docx")||xe.endsWith(".doc")||xe.endsWith(".ppt")||xe.endsWith(".pptx")||xe.endsWith(".xls")||xe.endsWith(".xlsx"),Ke=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(xe);it||Ee?O=`${d.length>0?"\u2714":"\u2718"} ${d?`Analyzed: ${W.basename(d)}`:"Analyzed: File Not Found"}`:Ke?O=`${d.length>0?"\u2714":"\u2718"} ${d?`Processed: ${W.basename(d)}`:"Processed: File Not Found"}`:O=`${Ie!=="..."?"\u2714":"\u2718"} Read: ${d?`${W.basename(d)} \u2192 ${Ie!=="..."?`Lines ${U} - ${We} of ${Ie}`:"File Not Found"}`:"File Not Found"}`}}else if(l==="list_files"||l==="read_folder"){let d=l==="list_files"?"List":"Browsed",M=G(w.args).path||null,Y=G(w.args).recurse||1;O=`${M?"\u2714":"\u2718"} ${d}: ${M?`${M==="."?`./${Y>1?"*":""}`:`${M.replaceAll("\\","/")}${Y>1?`${M.endsWith("/")?"*":"/*"}`:`${M.endsWith("/")?"":"/"}`}`}`:"No Folder Selected"}`}else if(l==="find_file"){let d=G(w.args),M=d.basename||d.name||d.path||d.file||d.query||"";O=`${M?"\u2714":"\u2718"} Located: ${M||"No Query"}`}else if(l==="write_file"||l==="update_file"){let d=l==="write_file"?"Created":"Edited",M=G(w.args),Y=M.path||null,te=Object.entries(M).some(([Te,Re])=>Te.startsWith("searchContent")&&typeof Re=="string"&&Re.startsWith("^LINE:"))?"\u1361":":";O=`${Y?"\u2714":"\u2718"} ${d}${te} ${Y?Y.replaceAll("\\","/"):"No File Changes"}`}else if(l==="write_pdf"){let d=G(w.args).path||null;O=`${d?"\u2714":"\u2718"} Generated: ${d.replaceAll("\\","/")||"No PDF Generated"}`}else if(l==="write_docx"){let d=G(w.args).path||null;O=`${d?"\u2714":"\u2718"} Generated: ${d.replaceAll("\\","/")||"No Docx Generated"}`}else if(l==="file_map"){let d=G(w.args).path;O=`${d?"\u2714":"\u2718"} Indexed: ${d.replaceAll("\\","/")?""+d:"File Not Found"}`}else if(l.toLowerCase()==="search_keyword"||l.toLowerCase()==="todo")O="";else if(l.toLowerCase()==="generate_image"){let{path:d,outputPath:M,output:Y}=G(w.args);O=`\u2714 Generated: ${d||M||Y||"generated_image.png"}`}else if(l==="invoke_sync"||l==="InvokeSync"){let d=Kn(l,w.args);O=`\u2714 Called Generalist${d?`: ${d}`:""}`}else if(l==="Invoke"||l==="InvokeAsync"||l==="invoke"){let d=Kn(l,w.args);O=`\u2714 Started Generalist${d?`: ${d}`:""}`}else if(l==="get_progress"||l==="GetProgress"){let d=Kn(l,w.args);O=`\u2714 Checked${d?`: ${d}`:""}`}else if(l==="cancel"){let d=Kn(l,w.args);O=`\u{1F6C7} Cancelled${d?`: ${d}`:""}`}else if(l==="steer"||l==="Steer"){let d=Kn(l,w.args);O=`\u2714 Steered${d?`: ${d}`:""}`}else if(l==="EmergencyRollback"){let{method:d}=G(w.args);O=d==="forceRevert"?"":"\u2714 Rollback Point Checked"}else if(l==="await"||l==="Await"||l==="wait"||l==="Wait"){let{time:d,timeout:M,seconds:Y,sec:ie}=G(w.args),te=parseFloat(Y||ie||M||d)||45,Te=l==="wait"||l==="Wait"?120:180;te<10&&(te=10),te>Te&&(te=Te);let Re=U=>{if(U>=60){let z=Math.floor(U/60),Ie=U%60;return`${z}m${Ie>0?` ${Ie}s`:""}`}return`${U}s`},fe=["Aligning Moon Phase","Contemplating Existence","Staring At Void","Delaying Professionally","Negotiating With Electrons","Touching Grass (virtually)","Panicking Softly","Rethinking Career Choices","Loading Cat Videos","Summoning Braincell #2","Pretending To Be Busy","Waiting For Motivation DLC","Rotating Internal Screaming","Downloading More RAM","Feeding The Hamsters","Gaslighting Scheduler","Performing Dramatic Pause","Buffering Social Energy","Calculating Regret","Reading Terms And Conditions","Becoming Sentient Briefly","Contacting Ancestors"];O=`\u2714 ${fe[Math.floor(Math.random()*fe.length)]} \u2192 ${Re(te)}`}else l==="Answer"||l==="answer"?O="\u2714 Resolved Sub-Agent Query":l==="exec_command"||l==="ask"?O="":O=`Executed: ${w.toolName}`;if(yield*Fn(),l==="exec_command"){let{command:d}=G(w.args);if(d&&t.systemSettings&&t.systemSettings.allowExternalAccess===!1){let M=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],Y=W.resolve(process.cwd()).substring(0,3).toLowerCase(),ie=F=>{let U=[],z="",Ie=null;for(let We=0;We<F.length;We++){let se=F[We];Ie?(se===Ie&&(Ie=null),z+=se):se==='"'||se==="'"?(Ie=se,z+=se):se==="&"&&F[We+1]==="&"||se==="|"&&F[We+1]==="|"?(z.trim()&&(U.push(z.trim()),z=""),We++):se===";"||se==="|"||se==="&"?z.trim()&&(U.push(z.trim()),z=""):z+=se}return z.trim()&&U.push(z.trim()),U},te=F=>{let U=[],z="",Ie=null;for(let We=0;We<F.length;We++){let se=F[We];Ie?(se===Ie&&(Ie=null),z+=se):se==='"'||se==="'"?(Ie=se,z+=se):/\s/.test(se)?z&&(U.push(z),z=""):z+=se}return z&&U.push(z),U},Te=F=>{let U=F.replace(/^['"]|['"]$/g,"").trim();return!U||process.platform==="win32"&&/^\/[a-zA-Z0-9?]+$/.test(U)?!1:M.some(z=>{if(z.source==="[a-zA-Z]:[\\\\\\/]"){let Ie=U.match(/[a-zA-Z]:[\\\/]/i);return Ie&&Ie[0].toLowerCase()!==Y}return z.test(U)})};if(ie(d).some(F=>{let U=te(F);if(U.length===0)return!1;let z=U[0].replace(/^['"]|['"]$/g,"").toLowerCase();if(["echo","printf","write-output"].includes(z)){let We=!1;return U.some(se=>{let Tt=se.replace(/^['"]|['"]$/g,"");if(Tt===">"||Tt===">>"||Tt==="<")return We=!0,!1;if(Tt.startsWith(">")||Tt.startsWith("<")){let xe=Tt.replace(/^[><]+/,"");return Te(xe)}return We?(We=!1,Te(se)):!1})}return U.some(We=>Te(We))})){let F='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(U=>setTimeout(U,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${F}`),await new Promise(U=>setTimeout(U,50)),t.onExecEnd&&t.onExecEnd(),Ne.push({role:"user",text:`[ACTION RESULT]: ERROR: ${F}`}),yield{type:"tool_result",content:`[ACTION RESULT]: ERROR: ${F}`},ht++;continue}}t.onExecStart&&t.onExecStart(d||"No Command"),yield{type:"exec_start"}}let dt=G(w.args),yn=dt.path||dt.targetPath||null;if(yn){let d=t.systemSettings&&t.systemSettings.allowExternalAccess===!1,M=W.resolve(yn),Y=W.resolve(process.cwd());if(d&&!M.startsWith(Y)){let ie="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"}: ${dt.path||"..."}`,Re=115;process.stdout.isTTY&&(Re=process.stdout.columns-5||120);let fe=Math.min(Te.length+4,Re),F=`${Te.padEnd(fe-2).substring(0,fe-2)}`;yield{type:"visual_feedback",content:Ht(`${Ve?`
737
737
  `:""}${F}
738
- `)},Ve=!1}Ne.push({role:"user",text:`[ACTION RESULT]: ERROR: ${ie}`}),yield{type:"tool_result",content:`[ACTION RESULT]: ERROR: ${ie}`},ht++;continue}}if(t.onToolApproval&&(l==="write_file"||l==="update_file"||l==="exec_command")){let M=t.systemSettings||{},Y=M.autoExec,ie=null,te=!1,Te=!1,Re=!1;if(l==="exec_command"){let{command:xe}=W(w.args),it=(xe||"").trim(),Ee=(Ut,ut)=>{if(!ut)return!1;let nn=ut.split(",").map(Wt=>Wt.trim().toLowerCase()).filter(Boolean),Je=Ut.toLowerCase();return nn.some(Wt=>Je.startsWith(Wt))},Ke=Ee(it,M.alwaysAskCommands),Q=Ee(it,M.autoApproveCommands);if(Te=Ee(it,M.autoDisallowCommands),Ke?te=!0:(Q||M.autoApproveGit&&/^git\s+commit\b/i.test(it))&&(ie="allow"),!te&&!ie){if(M.networkAccess===!1){let ut=it.trim().replace(/\s+/g," ").replace(/^['"]+|['"]+$/g,"").toLowerCase().split(" "),Je=ut[0].split("/").pop().split("\\").pop().replace(/\.exe$/,""),Wt=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"]),Qe=!1;Wt.has(Je)&&(Qe=!0);let Ye=vn=>ut.slice(1).some(wn=>vn.includes(wn)),tt=vn=>{let wn=ut.findIndex(Sn=>vn.includes(Sn)),Un=ut.findIndex(Sn=>["run","exec","test"].includes(Sn));return wn!==-1&&!(Un!==-1&&Un<wn)};Je==="git"&&Ye(["clone","pull","push","fetch"])&&(Qe=!0),Je==="go"&&Ye(["get","install"])&&(Qe=!0),Je==="npm"&&tt(["install","i","update","add"])&&(Qe=!0),Je==="yarn"&&tt(["add","install","upgrade"])&&(Qe=!0),Je==="pnpm"&&tt(["add","install","update"])&&(Qe=!0),Je==="bun"&&tt(["add","install","update"])&&(Qe=!0),Je==="deno"&&Ye(["install","add"])&&(Qe=!0),Je==="pip"&&Ye(["install","download"])&&(Qe=!0),Je==="pip3"&&Ye(["install","download"])&&(Qe=!0),Je==="cargo"&&Ye(["install","add"])&&(Qe=!0),["bash","sh","zsh","fish"].includes(Je)&&Ye(["-c"])&&(Qe=!0),Je==="cmd"&&Ye(["/c"])&&(Qe=!0),Qe&&(ie="deny",Re=!0)}!ie&&Te&&(ie="deny")}!te&&!ie&&Y&&(ie="allow")}else Y&&(ie="allow");let fe=ie,F="";ie==="deny"&&(Re?F="network":Te?F="settings":F="prohibited");let U=!1,z="",Ie=[],We=0,se=!1,Tt="";if(!fe){if(l==="write_file"||l==="update_file")try{let Ee=W(w.args),{path:Ke}=Ee;if(Ke){let Q=j.resolve(process.cwd(),Ke),Ut=Ye=>Ye?Ye.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,tt=>tt.toUpperCase()):"",ut=Ut(Q),nn="",Je=!1,Wt=await jn(),Qe=Ut(Wt?.file_focused);if(Wt&&Qe===ut&&Wt.full_content?(nn=Wt.full_content,Je=!0):be.existsSync(Q)&&(nn=be.readFileSync(Q,"utf8"),Je=!0),z=nn,await No.recordFileChange(Q,nn),Je){let Ye=nn;if(l==="write_file"){let tt=Ee.content||Ee.newContent||"";Ye=tt.endsWith(`
738
+ `)},Ve=!1}Ne.push({role:"user",text:`[ACTION RESULT]: ERROR: ${ie}`}),yield{type:"tool_result",content:`[ACTION RESULT]: ERROR: ${ie}`},ht++;continue}}if(t.onToolApproval&&(l==="write_file"||l==="update_file"||l==="exec_command")){let M=t.systemSettings||{},Y=M.autoExec,ie=null,te=!1,Te=!1,Re=!1;if(l==="exec_command"){let{command:xe}=G(w.args),it=(xe||"").trim(),Ee=(Ut,ut)=>{if(!ut)return!1;let tn=ut.split(",").map(Wt=>Wt.trim().toLowerCase()).filter(Boolean),Je=Ut.toLowerCase();return tn.some(Wt=>Je.startsWith(Wt))},Ke=Ee(it,M.alwaysAskCommands),Q=Ee(it,M.autoApproveCommands);if(Te=Ee(it,M.autoDisallowCommands),Ke?te=!0:(Q||M.autoApproveGit&&/^git\s+commit\b/i.test(it))&&(ie="allow"),!te&&!ie){if(M.networkAccess===!1){let ut=it.trim().replace(/\s+/g," ").replace(/^['"]+|['"]+$/g,"").toLowerCase().split(" "),Je=ut[0].split("/").pop().split("\\").pop().replace(/\.exe$/,""),Wt=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"]),Qe=!1;Wt.has(Je)&&(Qe=!0);let Ye=_n=>ut.slice(1).some(wn=>_n.includes(wn)),tt=_n=>{let wn=ut.findIndex(Sn=>_n.includes(Sn)),Un=ut.findIndex(Sn=>["run","exec","test"].includes(Sn));return wn!==-1&&!(Un!==-1&&Un<wn)};Je==="git"&&Ye(["clone","pull","push","fetch"])&&(Qe=!0),Je==="go"&&Ye(["get","install"])&&(Qe=!0),Je==="npm"&&tt(["install","i","update","add"])&&(Qe=!0),Je==="yarn"&&tt(["add","install","upgrade"])&&(Qe=!0),Je==="pnpm"&&tt(["add","install","update"])&&(Qe=!0),Je==="bun"&&tt(["add","install","update"])&&(Qe=!0),Je==="deno"&&Ye(["install","add"])&&(Qe=!0),Je==="pip"&&Ye(["install","download"])&&(Qe=!0),Je==="pip3"&&Ye(["install","download"])&&(Qe=!0),Je==="cargo"&&Ye(["install","add"])&&(Qe=!0),["bash","sh","zsh","fish"].includes(Je)&&Ye(["-c"])&&(Qe=!0),Je==="cmd"&&Ye(["/c"])&&(Qe=!0),Qe&&(ie="deny",Re=!0)}!ie&&Te&&(ie="deny")}!te&&!ie&&Y&&(ie="allow")}else Y&&(ie="allow");let fe=ie,F="";ie==="deny"&&(Re?F="network":Te?F="settings":F="prohibited");let U=!1,z="",Ie=[],We=0,se=!1,Tt="";if(!fe){if(l==="write_file"||l==="update_file")try{let Ee=G(w.args),{path:Ke}=Ee;if(Ke){let Q=W.resolve(process.cwd(),Ke),Ut=Ye=>Ye?Ye.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,tt=>tt.toUpperCase()):"",ut=Ut(Q),tn="",Je=!1,Wt=await jn(),Qe=Ut(Wt?.file_focused);if(Wt&&Qe===ut&&Wt.full_content?(tn=Wt.full_content,Je=!0):be.existsSync(Q)&&(tn=be.readFileSync(Q,"utf8"),Je=!0),z=tn,await Bo.recordFileChange(Q,tn),Je){let Ye=tn;if(l==="write_file"){let tt=Ee.content||Ee.newContent||"";Ye=tt.endsWith(`
739
739
  `)?tt:tt+`
740
- `,Tt=Ye}else{let{patchPairs:tt,allowMultiple:vn,error:wn}=bi(Ee);if(wn){let zt=`[ACTION RESULT]: ERROR: ${wn}`;Ne.push({role:"user",text:zt}),await Et("toolFailure"),t.onToolResult&&t.onToolResult("failure",l),yield{type:"tool_result",content:zt,toolName:l},ht++;continue}let Un=Ee.allowMultiple!==void 0?Ee.allowMultiple===!0||String(Ee.allowMultiple).toLowerCase()==="true":vn;We=tt.length;let Sn=fs(nn,tt,{allowMultiple:Un});Ye=Sn.content,Tt=Ye,Ie=Sn.results;let Oo=Ie.filter(zt=>zt.success),fi=Ie.filter(zt=>!zt.success);if(Oo.length===0){let zt=`[ACTION RESULT]: ERROR: Failed to apply patches to [${j.basename(Q)}].
741
- ${fi.map(st=>` \u2022 ${st.error}`).join(`
742
- `)}`,ui=`\u2714 Edited: ${j.basename(Q.replaceAll("\\","/"))}`,Tn=115;process.stdout.isTTY&&(Tn=process.stdout.columns-5||120);let Wn=Math.min(ui.length+4,Tn),nt=`${ui.padEnd(Wn-2).substring(0,Wn-2)}`;yield{type:"visual_feedback",content:Ht(`${Ve?`
743
- `:""}${nt}`)},Ve=!1,Ne.push({role:"user",text:zt}),await Et("toolFailure"),t.onToolResult&&t.onToolResult("failure",l),yield{type:"tool_result",content:zt,toolName:l},ht++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${j.basename(Q)}`},Wi(Q,nn,Ye),U=!0,await new Promise(tt=>setTimeout(tt,50))}else if(l==="write_file"){let Ye=Ee.content||Ee.newContent||"",tt=Ye.endsWith(`
740
+ `,Tt=Ye}else{let{patchPairs:tt,allowMultiple:_n,error:wn}=wi(Ee);if(wn){let zt=`[ACTION RESULT]: ERROR: ${wn}`;Ne.push({role:"user",text:zt}),await Et("toolFailure"),t.onToolResult&&t.onToolResult("failure",l),yield{type:"tool_result",content:zt,toolName:l},ht++;continue}let Un=Ee.allowMultiple!==void 0?Ee.allowMultiple===!0||String(Ee.allowMultiple).toLowerCase()==="true":_n;We=tt.length;let Sn=fs(tn,tt,{allowMultiple:Un});Ye=Sn.content,Tt=Ye,Ie=Sn.results;let $o=Ie.filter(zt=>zt.success),ui=Ie.filter(zt=>!zt.success);if($o.length===0){let zt=`[ACTION RESULT]: ERROR: Failed to apply patches to [${W.basename(Q)}].
741
+ ${ui.map(st=>` \u2022 ${st.error}`).join(`
742
+ `)}`,gi=`\u2714 Edited: ${W.basename(Q.replaceAll("\\","/"))}`,Tn=115;process.stdout.isTTY&&(Tn=process.stdout.columns-5||120);let Wn=Math.min(gi.length+4,Tn),nt=`${gi.padEnd(Wn-2).substring(0,Wn-2)}`;yield{type:"visual_feedback",content:Ht(`${Ve?`
743
+ `:""}${nt}`)},Ve=!1,Ne.push({role:"user",text:zt}),await Et("toolFailure"),t.onToolResult&&t.onToolResult("failure",l),yield{type:"tool_result",content:zt,toolName:l},ht++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${W.basename(Q)}`},Wi(Q,tn,Ye),U=!0,await new Promise(tt=>setTimeout(tt,50))}else if(l==="write_file"){let Ye=Ee.content||Ee.newContent||"",tt=Ye.endsWith(`
744
744
  `)?Ye:Ye+`
745
- `;Tt=tt,be.existsSync(Q)||(se=!0,be.mkdirSync(j.dirname(Q),{recursive:!0}),be.writeFileSync(Q,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${j.basename(Q)}`},Wi(Q,"",tt),U=!0,await new Promise(vn=>setTimeout(vn,50))}}}catch(Ee){console.error("Simulation/Diff Error:",Ee)}let xe=null;Ui(Ee=>{xe=Ee});let it=t.onToolApproval;if(fe=await new Promise(async Ee=>{let Ke=setInterval(()=>{if(xe){let Q=t.onIDEApproval||ti&&ti.onIDEApproval;Q&&Q(xe),clearInterval(Ke),Ee(xe)}},100);try{let Q=await it(l,w.args);clearInterval(Ke),Ee(Q)}catch{clearInterval(Ke),Ee("deny")}}),Ui(null),l==="write_file"||l==="update_file"){let{path:Ee}=W(w.args);if(Ee){let Ke=j.resolve(process.cwd(),Ee);if(Er(Ke,fe),fe==="deny"&&se&&be.existsSync(Ke))try{be.unlinkSync(Ke)}catch{}}}fe==="deny"&&(F="user")}if(fe==="allow"&&U&&Zo()){let{path:xe}=W(w.args),it=j.resolve(process.cwd(),xe),Ee=nt=>nt?j.resolve(nt).replace(/\\/g,"/").toLowerCase():"",Ke=await jn(),Q="";if(Ke&&Ke.file_focused&&Ee(Ke.file_focused)===Ee(it)&&Ke.full_content&&(Q=Ke.full_content),!Q&&be.existsSync(it)){let nt=be.readFileSync(it,"utf8");nt&&(Q=nt)}!Q&&Tt&&(Q=Tt),(Q||se)&&be.writeFileSync(it,Q,"utf8");let Ut=Q.split(/\r?\n/),ut=Ut.length,nn=Buffer.byteLength(Q,"utf8"),Je="";z&&(Je=`Old File contents:
746
- ${z.split(/\r?\n/).map((st,rn)=>`${rn+1} | ${st}`).join(`
745
+ `;Tt=tt,be.existsSync(Q)||(se=!0,be.mkdirSync(W.dirname(Q),{recursive:!0}),be.writeFileSync(Q,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${W.basename(Q)}`},Wi(Q,"",tt),U=!0,await new Promise(_n=>setTimeout(_n,50))}}}catch(Ee){console.error("Simulation/Diff Error:",Ee)}let xe=null;Ui(Ee=>{xe=Ee});let it=t.onToolApproval;if(fe=await new Promise(async Ee=>{let Ke=setInterval(()=>{if(xe){let Q=t.onIDEApproval||ni&&ni.onIDEApproval;Q&&Q(xe),clearInterval(Ke),Ee(xe)}},100);try{let Q=await it(l,w.args);clearInterval(Ke),Ee(Q)}catch{clearInterval(Ke),Ee("deny")}}),Ui(null),l==="write_file"||l==="update_file"){let{path:Ee}=G(w.args);if(Ee){let Ke=W.resolve(process.cwd(),Ee);if(Er(Ke,fe),fe==="deny"&&se&&be.existsSync(Ke))try{be.unlinkSync(Ke)}catch{}}}fe==="deny"&&(F="user")}if(fe==="allow"&&U&&ei()){let{path:xe}=G(w.args),it=W.resolve(process.cwd(),xe),Ee=nt=>nt?W.resolve(nt).replace(/\\/g,"/").toLowerCase():"",Ke=await jn(),Q="";if(Ke&&Ke.file_focused&&Ee(Ke.file_focused)===Ee(it)&&Ke.full_content&&(Q=Ke.full_content),!Q&&be.existsSync(it)){let nt=be.readFileSync(it,"utf8");nt&&(Q=nt)}!Q&&Tt&&(Q=Tt),(Q||se)&&be.writeFileSync(it,Q,"utf8");let Ut=Q.split(/\r?\n/),ut=Ut.length,tn=Buffer.byteLength(Q,"utf8"),Je="";z&&(Je=`Old File contents:
746
+ ${z.split(/\r?\n/).map((st,sn)=>`${sn+1} | ${st}`).join(`
747
747
  `)}
748
748
 
749
749
  `);let Wt="";if(ut<=100)Wt=Ut.join(`
@@ -753,41 +753,41 @@ ${z.split(/\r?\n/).map((st,rn)=>`${rn+1} | ${st}`).join(`
753
753
 
754
754
  ... [${ut-100} lines truncated for history stability] ...
755
755
 
756
- ${st}`}let Qe="";if(l==="update_file"){let nt=us(z,Q,Ie,12,t?.compressToolResults||ti?.systemSettings?.compressToolResults),st=0,rn=[],{patchPairs:Gn}=bi(w.args);Gn&&Gn.length>0?Gn.forEach((lo,co)=>{let Jn=(lo.search||"").trim(),gi=(lo.replace||"").trim(),ta=gi?Q.includes(gi):!0,na=Jn&&Jn!==gi?!Q.includes(Jn):!0;ta&&(na||!Jn)?st++:rn.push(` \u2022 Block ${co+1}: No change detected OR user rejected change.`)}):st=Ie.length;let _n=rn.length>0?`
756
+ ${st}`}let Qe="";if(l==="update_file"){let nt=us(z,Q,Ie,12,t?.compressToolResults||ni?.systemSettings?.compressToolResults),st=0,sn=[],{patchPairs:Gn}=wi(w.args);Gn&&Gn.length>0?Gn.forEach((lo,co)=>{let Jn=(lo.search||"").trim(),mi=(lo.replace||"").trim(),ta=mi?Q.includes(mi):!0,na=Jn&&Jn!==mi?!Q.includes(Jn):!0;ta&&(na||!Jn)?st++:sn.push(` \u2022 Block ${co+1}: No change detected OR user rejected change.`)}):st=Ie.length;let In=sn.length>0?`
757
757
 
758
758
  Notes:
759
- ${rn.join(`
760
- `)}`:"";Qe=`File [${xe}] updated via IDE Companion (May have user edits). [${st}/${We}] blocks applied.${_n}
759
+ ${sn.join(`
760
+ `)}`:"";Qe=`File [${xe}] updated via IDE Companion (May have user edits). [${st}/${We}] blocks applied.${In}
761
761
 
762
- ${nt}`}else{let nt=Q.split(/\r?\n/),st=nt.length,rn=Buffer.byteLength(Q,"utf8"),Gn="";z&&(Gn=`Old File contents:
762
+ ${nt}`}else{let nt=Q.split(/\r?\n/),st=nt.length,sn=Buffer.byteLength(Q,"utf8"),Gn="";z&&(Gn=`Old File contents:
763
763
  ${z.split(/\r?\n/).map((co,Jn)=>`${Jn+1} | ${co}`).join(`
764
764
  `)}
765
765
 
766
- `);let _n="";if(st<=100)_n=nt.join(`
766
+ `);let In="";if(st<=100)In=nt.join(`
767
767
  `);else{let lo=nt.slice(0,50).join(`
768
768
  `),co=nt.slice(-50).join(`
769
- `);_n=`${lo}
769
+ `);In=`${lo}
770
770
 
771
771
  ... [${st-100} lines truncated] ...
772
772
 
773
773
  ${co}`}Qe=`File [${xe}] saved via IDE Companion (May have user edits).
774
- - Stats: [${st} lines, ${(rn/1024).toFixed(1)} KB]
774
+ - Stats: [${st} lines, ${(sn/1024).toFixed(1)} KB]
775
775
  ${Gn}- Content Preview:
776
776
 
777
- ${_n}`}let Ye=l==="write_file"?"Created":"Edited",tt=W(w.args),wn=Object.entries(tt).some(([nt,st])=>nt.startsWith("searchContent")&&typeof st=="string"&&st.startsWith("^LINE:"))?"\u1361":":",Un=`${xe?"\u2714":"\u2718"} ${Ye}${wn} ${xe?xe.replaceAll("\\","/"):"No File Changes"}`,Sn=115;process.stdout.isTTY&&(Sn=process.stdout.columns-5||120);let Oo=Math.min(Un.length+4,Sn),fi=`${Un.padEnd(Oo-2).substring(0,Oo-2)}`;yield{type:"visual_feedback",content:Ht(`${Ve?`
778
- `:""}${fi}`)},Ve=!1;let zt=Date.now();Zt=zt,yield{type:"tool_time",content:zt-_};let Tn=(Qe||"").toString().replaceAll("\u2550".repeat(88),"=".repeat(35)).replaceAll("[UI_CONTEXT]","");Tn.includes("[[VERIFIED]]")&&(Tn=Tn.replace(/\[\[VERIFIED\]\][\s\S]*?\[\[\/VERIFIED\]\]/g,`[SYSTEM NOTE]: Patch Block matched & applied successfully. Large Block omitted to conserve context.
779
- `));let Wn;if(Tn.startsWith("[[SAME]]")){let st=Tn.replace(/^\[\[SAME\]\]\s*\r?\n?/,"").split(/\r?\n/),rn=st.filter(_n=>_n.startsWith("File ")||_n.trim().startsWith("- Stats:"));Wn=`[ACTION RESULT]: ${rn.length>0?rn.join(`
777
+ ${In}`}let Ye=l==="write_file"?"Created":"Edited",tt=G(w.args),wn=Object.entries(tt).some(([nt,st])=>nt.startsWith("searchContent")&&typeof st=="string"&&st.startsWith("^LINE:"))?"\u1361":":",Un=`${xe?"\u2714":"\u2718"} ${Ye}${wn} ${xe?xe.replaceAll("\\","/"):"No File Changes"}`,Sn=115;process.stdout.isTTY&&(Sn=process.stdout.columns-5||120);let $o=Math.min(Un.length+4,Sn),ui=`${Un.padEnd($o-2).substring(0,$o-2)}`;yield{type:"visual_feedback",content:Ht(`${Ve?`
778
+ `:""}${ui}`)},Ve=!1;let zt=Date.now();Qt=zt,yield{type:"tool_time",content:zt-_};let Tn=(Qe||"").toString().replaceAll("\u2550".repeat(88),"=".repeat(35)).replaceAll("[UI_CONTEXT]","");Tn.includes("[[VERIFIED]]")&&(Tn=Tn.replace(/\[\[VERIFIED\]\][\s\S]*?\[\[\/VERIFIED\]\]/g,`[SYSTEM NOTE]: Patch Block matched & applied successfully. Large Block omitted to conserve context.
779
+ `));let Wn;if(Tn.startsWith("[[SAME]]")){let st=Tn.replace(/^\[\[SAME\]\]\s*\r?\n?/,"").split(/\r?\n/),sn=st.filter(In=>In.startsWith("File ")||In.trim().startsWith("- Stats:"));Wn=`[ACTION RESULT]: ${sn.length>0?sn.join(`
780
780
  `):st.slice(0,2).join(`
781
781
  `)}
782
- [SYSTEM NOTE]: Content verified and persisted to disk. Full preview omitted to conserve context.`}else Wn=`[ACTION RESULT]: ${Tn}`;Ne.push({role:"user",text:Wn}),hn=!0,await Et("toolSuccess"),t.onToolResult&&t.onToolResult("success",l),yield{type:"tool_result",content:Qe,aiContent:Wn,toolName:l},ht++;continue}if(fe==="deny"){let xe=`Permission Denied: Prohibited ${l==="exec_command"?"Command":"file edit"}.`;if(F==="user"?xe="Permission Denied by User":F==="settings"?xe="Permission Denied by User Policy":F==="network"?xe="Permission Denied: Sandbox Network Access Disabled by User Policy.":F==="prohibited"&&l==="exec_command"&&(xe="Permission Denied: Prohibited Command in User Policy"),l==="write_file"||l==="update_file"){let Ee=`\u2718 ${l==="write_file"?"Write Cancelled":"Edit Denied"}: ${W(w.args).path.replaceAll("\\","/")||"..."}`,Ke=115;process.stdout.isTTY&&(Ke=process.stdout.columns-5||120);let Q=Math.min(Ee.length+4,Ke),Ut=`${Ee.padEnd(Q-2).substring(0,Q-2)}`,ut=` ${" ".repeat(Q)} `;yield{type:"visual_feedback",content:Ht(`${Ve?`
782
+ [SYSTEM NOTE]: Content verified and persisted to disk. Full preview omitted to conserve context.`}else Wn=`[ACTION RESULT]: ${Tn}`;Ne.push({role:"user",text:Wn}),hn=!0,await Et("toolSuccess"),t.onToolResult&&t.onToolResult("success",l),yield{type:"tool_result",content:Qe,aiContent:Wn,toolName:l},ht++;continue}if(fe==="deny"){let xe=`Permission Denied: Prohibited ${l==="exec_command"?"Command":"file edit"}.`;if(F==="user"?xe="Permission Denied by User":F==="settings"?xe="Permission Denied by User Policy":F==="network"?xe="Permission Denied: Sandbox Network Access Disabled by User Policy.":F==="prohibited"&&l==="exec_command"&&(xe="Permission Denied: Prohibited Command in User Policy"),l==="write_file"||l==="update_file"){let Ee=`\u2718 ${l==="write_file"?"Write Cancelled":"Edit Denied"}: ${G(w.args).path.replaceAll("\\","/")||"..."}`,Ke=115;process.stdout.isTTY&&(Ke=process.stdout.columns-5||120);let Q=Math.min(Ee.length+4,Ke),Ut=`${Ee.padEnd(Q-2).substring(0,Q-2)}`,ut=` ${" ".repeat(Q)} `;yield{type:"visual_feedback",content:Ht(`${Ve?`
783
783
  `:""}${Ut}
784
784
  `)},Ve=!1}l==="exec_command"&&(await new Promise(it=>setTimeout(it,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${xe}`),await new Promise(it=>setTimeout(it,50)),t.onExecEnd&&t.onExecEnd()),Ne.push({role:"user",text:`[ACTION RESULT]: DENIED: ${xe}`}),yield{type:"tool_result",content:`[ACTION RESULT]: DENIED: ${xe}`},await Et("toolDenied"),t.onToolResult&&t.onToolResult("denied",l),ht++;continue}}if(O){let d=115;process.stdout.isTTY&&(d=process.stdout.columns-5||120);let M=await i(),Y=!1;M&&(Y=M.trim().length>0);let ie=Math.min(O.length+4,d),te=`${O.padEnd(ie-2).substring(0,ie-2)}`;yield{type:"visual_feedback",content:Ht(`${Ve?`
785
785
  `:""}${te}${O.includes("\u2714")&&(O.includes("Created")||O.includes("Edited"))?"":`${Y?"":`
786
- `}`}`)},Ve=!1}if(Zt>0){let d=Date.now()-Zt,M=Math.max(0,1e3-d);M>0&&await new Promise(Y=>setTimeout(Y,M))}let It={chatId:g,history:n,onChunk:d=>t.onExecChunk?t.onExecChunk(d):null,onAskUser:t.onAskUser,systemSettings:t.systemSettings,mode:a,isMultiModal:ot(Z),onVisualFeedback:t.onVisualFeedback,onSubagentUpdate:t.onSubagentUpdate,onTokenChunk:t.onTokenChunk,modelName:Z,aiProvider:t.aiProvider,apiKey:t.apiKey,onUsage:t.onUsage};if(l==="write_file"||l==="update_file")try{let{path:d}=W(w.args);if(d){let M=j.resolve(process.cwd(),d),Y=await jn();Y&&Y.file_focused===M&&Y.full_content&&(It.forcedContent=Y.full_content)}}catch{}ze.push(l);let J=await ko(l,w.args,It);if((l==="write_file"||l==="update_file")&&!J.startsWith("ERROR:")){let{path:d}=W(w.args);if(d){let M=j.resolve(process.cwd(),d);Rr(M)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let He=Date.now();Zt=He,yield{type:"tool_time",content:He-_},lt=He;let ft=null;if(typeof J=="object"&&J.binaryPart&&(ft=J.binaryPart,J=J.text),l==="search_keyword"){let{keyword:d,path:M}=W(w.args),Y=typeof J=="string"&&J.startsWith("[GLOB]");Y&&(J=J.slice(6).trimStart());let ie=typeof J=="string"&&J.startsWith("[DIR]");ie&&(J=J.slice(5).trimStart());let te=0;if(J){let se=J.match(/Found (\d+) match/i);se&&(te=parseInt(se[1]))}let Te=(M||"").trim().toLowerCase().replaceAll("\\","/"),Re=Te==="#doc"||Te==="#docs"||Te==="#documentation"||Te.includes("#skill/global/fluxflow")||Te.includes("#skill/fluxflow")||Te.includes("#skills/fluxflow")||Te.includes("#skills/global/fluxflow"),fe,F=115;process.stdout.isTTY&&(F=process.stdout.columns-5||120);let U=Math.max(10,(F+5)/3),z=Math.max(10,(F+5)/4);if(Re)fe=`${d?"\u2714":"\u2718"} Searched Documentation`;else{let se=M?M.replace(/[\/\\]+$/,""):null,Tt=se&&se!=="."?`${Y?M:ie?`${se}/*`:se}`:"./",xe=Tt.length>z?`${Tt.slice(0,z)}...`:Tt;fe=`${d?"\u2714":"\u2718"} Searched: "${d?d.length>F/3?`${d.slice(0,U)}...`:d:""}" in "${xe.replaceAll("\\","/")}" \u2192 ${te} Match${te===1?"":"es"}`}let Ie=Math.min(fe.length+4,F),We=`${fe.padEnd(Ie-2).substring(0,Ie-2)}`;yield{type:"visual_feedback",content:Ht(`${Ve?`
786
+ `}`}`)},Ve=!1}if(Qt>0){let d=Date.now()-Qt,M=Math.max(0,1e3-d);M>0&&await new Promise(Y=>setTimeout(Y,M))}let It={chatId:m,history:n,onChunk:d=>t.onExecChunk?t.onExecChunk(d):null,onAskUser:t.onAskUser,systemSettings:t.systemSettings,mode:a,isMultiModal:ot(Z),onVisualFeedback:t.onVisualFeedback,onSubagentUpdate:t.onSubagentUpdate,onTokenChunk:t.onTokenChunk,modelName:Z,aiProvider:t.aiProvider,apiKey:t.apiKey,onUsage:t.onUsage};if(l==="write_file"||l==="update_file")try{let{path:d}=G(w.args);if(d){let M=W.resolve(process.cwd(),d),Y=await jn();Y&&Y.file_focused===M&&Y.full_content&&(It.forcedContent=Y.full_content)}}catch{}ze.push(l);let J=await Ro(l,w.args,It);if((l==="write_file"||l==="update_file")&&!J.startsWith("ERROR:")){let{path:d}=G(w.args);if(d){let M=W.resolve(process.cwd(),d);Rr(M)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let He=Date.now();Qt=He,yield{type:"tool_time",content:He-_},lt=He;let ft=null;if(typeof J=="object"&&J.binaryPart&&(ft=J.binaryPart,J=J.text),l==="search_keyword"){let{keyword:d,path:M}=G(w.args),Y=typeof J=="string"&&J.startsWith("[GLOB]");Y&&(J=J.slice(6).trimStart());let ie=typeof J=="string"&&J.startsWith("[DIR]");ie&&(J=J.slice(5).trimStart());let te=0;if(J){let se=J.match(/Found (\d+) match/i);se&&(te=parseInt(se[1]))}let Te=(M||"").trim().toLowerCase().replaceAll("\\","/"),Re=Te==="#doc"||Te==="#docs"||Te==="#documentation"||Te.includes("#skill/global/fluxflow")||Te.includes("#skill/fluxflow")||Te.includes("#skills/fluxflow")||Te.includes("#skills/global/fluxflow"),fe,F=115;process.stdout.isTTY&&(F=process.stdout.columns-5||120);let U=Math.max(10,(F+5)/3),z=Math.max(10,(F+5)/4);if(Re)fe=`${d?"\u2714":"\u2718"} Searched Documentation`;else{let se=M?M.replace(/[\/\\]+$/,""):null,Tt=se&&se!=="."?`${Y?M:ie?`${se}/*`:se}`:"./",xe=Tt.length>z?`${Tt.slice(0,z)}...`:Tt;fe=`${d?"\u2714":"\u2718"} Searched: "${d?d.length>F/3?`${d.slice(0,U)}...`:d:""}" in "${xe.replaceAll("\\","/")}" \u2192 ${te} Match${te===1?"":"es"}`}let Ie=Math.min(fe.length+4,F),We=`${fe.padEnd(Ie-2).substring(0,Ie-2)}`;yield{type:"visual_feedback",content:Ht(`${Ve?`
787
787
  `:""}${We}
788
- `)},Ve=!1}if(l==="EmergencyRollback"){let{method:d}=W(w.args);if(d==="forceRevert"){let M=0;if(J){let U=J.match(/Total\s*:\s*(\d+)/i);U&&(M=parseInt(U[1]))}let ie=J&&J.startsWith("ERROR:")?"\u2718 Emergency Rollback Failed":`\u2714 Emergency Rollback \u2192 ${M} file${M===1?"":"s"} processed`,te=115;process.stdout.isTTY&&(te=process.stdout.columns-5||120);let Te=await i(),Re=!1;Te&&(Re=Te.trim().length>0);let fe=Math.min(ie.length+4,te),F=`${ie.padEnd(fe-2).substring(0,fe-2)}`;yield{type:"visual_feedback",content:Ht(`${Ve?`
788
+ `)},Ve=!1}if(l==="EmergencyRollback"){let{method:d}=G(w.args);if(d==="forceRevert"){let M=0;if(J){let U=J.match(/Total\s*:\s*(\d+)/i);U&&(M=parseInt(U[1]))}let ie=J&&J.startsWith("ERROR:")?"\u2718 Emergency Rollback Failed":`\u2714 Emergency Rollback \u2192 ${M} file${M===1?"":"s"} processed`,te=115;process.stdout.isTTY&&(te=process.stdout.columns-5||120);let Te=await i(),Re=!1;Te&&(Re=Te.trim().length>0);let fe=Math.min(ie.length+4,te),F=`${ie.padEnd(fe-2).substring(0,fe-2)}`;yield{type:"visual_feedback",content:Ht(`${Ve?`
789
789
  `:""}${F}${Re?"":`
790
- `}`)},Ve=!1}}if(l==="todo"){let{method:d,tasks:M,markDone:Y}=W(w.args),ie="",te=[],Te=Re=>{if(!Re)return[];let fe=Array.isArray(Re)?Re:[];if(fe.length===0&&typeof Re=="string"){let F=Re.trim();if(F.startsWith("[")&&F.endsWith("]")){let U=F.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);U?fe=U.map(z=>z.slice(1,-1).replace(/\\(.)/g,"$1")):fe=F.slice(1,-1).split(",").map(z=>z.trim()).filter(Boolean)}else fe=Re.split(`
790
+ `}`)},Ve=!1}}if(l==="todo"){let{method:d,tasks:M,markDone:Y}=G(w.args),ie="",te=[],Te=Re=>{if(!Re)return[];let fe=Array.isArray(Re)?Re:[];if(fe.length===0&&typeof Re=="string"){let F=Re.trim();if(F.startsWith("[")&&F.endsWith("]")){let U=F.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);U?fe=U.map(z=>z.slice(1,-1).replace(/\\(.)/g,"$1")):fe=F.slice(1,-1).split(",").map(z=>z.trim()).filter(Boolean)}else fe=Re.split(`
791
791
  `)}return fe.filter(F=>String(F).trim()).map(F=>{let U=String(F).trim();return U.startsWith("- [")?U.substring(6).trim():U})};if(d==="create"?(ie="\x1B[32m\u2192\x1B[0m Created Goals",te=Te(M).map(Re=>`\x1B[90m\u25CB\x1B[0m ${Re}`)):d==="append"?(ie="\x1B[34m\u2795\x1B[0m Added New Goals",te=Te(M).map(Re=>`\x1B[90m\u25CB\x1B[0m ${Re}`)):d==="get"&&(ie=Y?"\x1B[36m\u21BB\x1B[0m Updated Goals":"\x1B[35m\u2022\x1B[0m Reviewed Goals",te=(J||"").split(`
792
792
  `).slice(1).join(`
793
793
  `).split(`
@@ -800,22 +800,22 @@ ${_n}`}let Ye=l==="write_file"?"Created":"Edited",tt=W(w.args),wn=Object.entries
800
800
  `)}
801
801
  [SYSTEM NOTE]: Content verified and persisted to disk. Full preview omitted to save tokens.`}else bn=`[ACTION RESULT]: ${Ot}`;Ne.push({role:"user",text:bn,binaryPart:ft}),hn=!0;let me=`[ACTION RESULT]: ${J.replaceAll(`[[VERIFIED]]
802
802
  `,"").replaceAll(`
803
- [[/VERIFIED]]`,"")||""}`;(l==="view_file"||l==="web_scrape"||l==="file_map")&&(me=`[ACTION RESULT]: ${O} (Context Locked for UI Clarity)`),yield{type:"tool_result",content:me,aiContent:bn,binaryPart:ft,toolName:l},l==="memory"&&!J.startsWith("ERROR:")&&(yield{type:"memory_updated"}),ht++}if(s==="Google"&&tn&&Date.now()-ci>=150){yield*Fn();let w=so(tn);for(let _ of w)yield _;tn="",ci=Date.now()}}p.usageMetadata&&(Qt=p.usageMetadata),Qt&&(yield{type:"liveTokens",content:Qt.totalTokenCount})}if(ee&&(ee=!1,et?_e+="</think>":(ue+="</think>",s==="Google"?tn+="</think>":yield{type:"text",content:"</think>"})),et&&_e.length>0){let p=0,v=Math.min(pt.length,_e.length);for(let K=v;K>0;K--)if(pt.endsWith(_e.substring(0,K))){p=K;break}let E=_e.substring(p);if(E){let oe=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(pt)?E.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):E.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(oe)if(ue+=oe,s==="Google")tn+=oe;else{yield*Fn();let $=so(oe);for(let H of $)yield H}}et=!1,_e=""}if(pn){let p=pn;pn="",qn=!1,Ct=null,Bn=!1,Xn=!1,s==="Google"?tn+=p:yield{type:"text",content:p}}if(yield*Fn(),mt)break;let ro=(ue||"").trim(),qr=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(ro.toLowerCase())||/\[\[END\]\]/i.test(ro.toLowerCase()),Xr=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(ro.toLowerCase()),Jr=Ne.length>0||L!==null,di=Lt(ro).trim(),Qr=/(\p{Emoji_Presentation}|\p{Extended_Pictographic})$/u.test(di),Zr=/([.!?"'*_`|\]\)”’~~]+|\s|`{3}|[\u200B-\u200D\uFEFF])$/u.test(di.trim()),ea=/[.!?}"'`’“”]$|```$/s.test(di)||Zr||Qr;!qr&&!Xr&&!Jr&&ro.length>0,qe=!0,await Et("agent",s)}catch(ne){if(mt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
803
+ [[/VERIFIED]]`,"")||""}`;(l==="view_file"||l==="web_scrape"||l==="file_map")&&(me=`[ACTION RESULT]: ${O} (Context Locked for UI Clarity)`),yield{type:"tool_result",content:me,aiContent:bn,binaryPart:ft,toolName:l},l==="memory"&&!J.startsWith("ERROR:")&&(yield{type:"memory_updated"}),ht++}if(s==="Google"&&en&&Date.now()-di>=150){yield*Fn();let w=so(en);for(let _ of w)yield _;en="",di=Date.now()}}p.usageMetadata&&(Jt=p.usageMetadata),Jt&&(yield{type:"liveTokens",content:Jt.totalTokenCount})}if(ee&&(ee=!1,et?_e+="</think>":(ue+="</think>",s==="Google"?en+="</think>":yield{type:"text",content:"</think>"})),et&&_e.length>0){let p=0,v=Math.min(pt.length,_e.length);for(let K=v;K>0;K--)if(pt.endsWith(_e.substring(0,K))){p=K;break}let E=_e.substring(p);if(E){let oe=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(pt)?E.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):E.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(oe)if(ue+=oe,s==="Google")en+=oe;else{yield*Fn();let $=so(oe);for(let j of $)yield j}}et=!1,_e=""}if(pn){let p=pn;pn="",qn=!1,Ct=null,Bn=!1,Xn=!1,s==="Google"?en+=p:yield{type:"text",content:p}}if(yield*Fn(),mt)break;let ro=(ue||"").trim(),qr=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(ro.toLowerCase())||/\[\[END\]\]/i.test(ro.toLowerCase()),Xr=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(ro.toLowerCase()),Jr=Ne.length>0||L!==null,fi=Lt(ro).trim(),Qr=/(\p{Emoji_Presentation}|\p{Extended_Pictographic})$/u.test(fi),Zr=/([.!?"'*_`|\]\)”’~~]+|\s|`{3}|[\u200B-\u200D\uFEFF])$/u.test(fi.trim()),ea=/[.!?}"'`’“”]$|```$/s.test(fi)||Zr||Qr;!qr&&!Xr&&!Jr&&ro.length>0,qe=!0,await Et("agent",s)}catch(ne){if(mt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
804
804
 
805
- \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(String(ne).includes("Incomplete JSON segment at the end")){ee&&(ee=!1,et?_e+="</think>":(ue+="</think>",yield{type:"text",content:"</think>"})),qe=!0,await Et("agent",s);break}if(ee&&(ee=!1,et?_e+="</think>":ue+="</think>"),et&&_e.length>0){let wt=0,kt=Math.min(pt.length,_e.length);for(let Yt=kt;Yt>0;Yt--)if(pt.endsWith(_e.substring(0,Yt))){wt=Yt;break}let St=_e.substring(wt);if(St){let Rn=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(pt)?St.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):St.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");Rn&&(ue+=Rn)}et=!1,_e=""}let B=ne instanceof Error?(()=>{try{return JSON.parse(JSON.parse(ne.message).error.message).error.message}catch{return String(ne)}})():String(ne),yt=new Date().toLocaleString(),xt=j.join(qt,"agent");be.existsSync(xt)||be.mkdirSync(xt,{recursive:!0}),be.appendFileSync(j.join(xt,"error.log"),`ERROR [${yt}]: ${B}
805
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(String(ne).includes("Incomplete JSON segment at the end")){ee&&(ee=!1,et?_e+="</think>":(ue+="</think>",yield{type:"text",content:"</think>"})),qe=!0,await Et("agent",s);break}if(ee&&(ee=!1,et?_e+="</think>":ue+="</think>"),et&&_e.length>0){let wt=0,kt=Math.min(pt.length,_e.length);for(let Yt=kt;Yt>0;Yt--)if(pt.endsWith(_e.substring(0,Yt))){wt=Yt;break}let St=_e.substring(wt);if(St){let En=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(pt)?St.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):St.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");En&&(ue+=En)}et=!1,_e=""}let B=ne instanceof Error?(()=>{try{return JSON.parse(JSON.parse(ne.message).error.message).error.message}catch{return String(ne)}})():String(ne),yt=new Date().toLocaleString(),xt=W.join(kn,"agent");be.existsSync(xt)||be.mkdirSync(xt,{recursive:!0}),be.appendFileSync(W.join(xt,"error.log"),`ERROR [${yt}]: ${B}
806
806
 
807
807
  ----------------------------------------------------------------------
808
808
 
809
- `);let bt=ne.status||ne.statusCode||ne.code,Bt=String(ne).includes("replicas at capacity");if(!(bt&&(bt>=500&&bt<600||bt===408||bt===429||Bt)||!bt&&(/status[ :]+(5\d\d|408|429)/i.test(String(ne))||/code[ :]+(5\d\d|408|429)/i.test(String(ne))||/(500|503|408|429)/.test(String(ne))))){if(je<sn-3)throw ne;yield{type:"text",content:B},yield{type:"status",content:"Error Occured"}}if(ue.trim().length>0||Xe>1)if(Xe<=sn){Xe++;let wt=Math.min(1e3*Math.pow(2,Xe-1),24e3);if(ue.trim().length>0){b.push({role:"agent",text:ue});let kt=`[system]
809
+ `);let bt=ne.status||ne.statusCode||ne.code,Bt=String(ne).includes("replicas at capacity");if(!(bt&&(bt>=500&&bt<600||bt===408||bt===429||Bt)||!bt&&(/status[ :]+(5\d\d|408|429)/i.test(String(ne))||/code[ :]+(5\d\d|408|429)/i.test(String(ne))||/(500|503|408|429)/.test(String(ne))))){if(je<on-3)throw ne;yield{type:"text",content:B},yield{type:"status",content:"Error Occured"}}if(ue.trim().length>0||Xe>1)if(Xe<=on){Xe++;let wt=Math.min(1e3*Math.pow(2,Xe-1),24e3);if(ue.trim().length>0){b.push({role:"agent",text:ue});let kt=`[system]
810
810
  - seamless continuation: resume immediately. pick up from last words with zero gap/disruption
811
811
  - no repetition: do not repeat any text already written
812
812
  - no re-think: do not restart or open <think> if reasoning already started. continue the thinking and close thinking block </think> before chat output
813
813
  - mid-tool safety: if cutoff was mid-tool call, restart that tool call from start
814
814
  - stealth: do not mention/apologize for cutoff [/system]`;Ne.length>0?Ne.forEach((St,Yt)=>{Yt===Ne.length-1?b.push({...St,text:`${St.text}
815
815
 
816
- ${kt}`}):b.push(St)}):b.push({role:"user",text:kt}),pt+=ue}for(let kt=wt/1e3;kt>0&&!mt;kt--)yield{type:"status",content:`Error Occured. Recovering Stream (${Xe}/${sn}) [Retrying in ${kt.toFixed(0)}s]...`},await new Promise(St=>setTimeout(St,1e3));yield{type:"status",content:"Error Occured. Recovering Stream..."}}else throw new Error(`Stream collapsed too many times. (Failed to resolve ${sn} times)
817
- Error log can be found in \`/export logs\``);else if(je<=sn){je++,Xe=1,pt="";let wt=Math.min(1e3*Math.pow(2,je-1),32e3),kt=.8+Math.random()*.4,St=Math.round(wt*kt);Cn=!0,yield{type:"status",content:`Trying to reach ${e} (${je}/${sn}) [Retrying in ${(St/1e3).toFixed(0)}s]`};for(let Yt=St/1e3;Yt>0&&!mt;Yt--)yield{type:"status",content:`Trying to reach ${e} (${je}/${sn}) [Retrying in ${Yt.toFixed(0)}s]`},await new Promise(Rn=>setTimeout(Rn,1e3));yield{type:"status",content:`Trying to reach ${e}`}}else throw new Error(`Model ${e} cannot be reached. (Failed ${sn} times)
818
- Error log can be found in \`/export logs\``)}}if(Qt){let ee=Qt.totalTokenCount||0,ne=Qt.cachedContentTokenCount||0,B=(Qt.candidatesTokenCount||0)+(s==="Google"&&Qt.thoughtsTokenCount||0);await gt("tokens",ee,s,Z),ne>0&&await gt("cachedTokens",ne,s,Z),B>0&&await gt("candidateTokens",B,s,Z),Ce!==null&&Ce>0&&await gt("ttft",Ce,s,Z),mo({provider:s,model:Z,prompt:Qt.promptTokenCount||0,cached:ne,output:B,reasoning:Qt.thoughtsTokenCount||0,ttft:Ce}),yield{type:"usage",content:Qt}}else Ce!==null&&Ce>0&&(await gt("ttft",Ce,s,Z),mo({provider:s,model:Z,prompt:0,cached:0,output:0,reasoning:0,ttft:Ce}));ue=$r(ue),ai.push(ue);let Ka=Lt(ue),li=Or(ue),jr=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(li.toLowerCase())||/\[\[END\]\]/i.test(li.toLowerCase())||!0,Ya=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(li.toLowerCase()),za=ht>0;yield{type:"status",content:"Thinking"};let Vr=Ga(ue,/(\[\s*(turn\s*:)?\s*(continue|finish)\s*\]|\[\[END\]\])/gi,"").trim(),Dn=(jr||Ne.length===0)&&!_t&&!Nn&&!Ft;if(Dn=Ne.length===0?Dn:!1,Dn=Kt||Io?!1:Dn,ue&&ue.trim().endsWith('")]')&&Ne.length===0&&(Dn=!1),Dn){is=!0;let ee=ai.join(`
816
+ ${kt}`}):b.push(St)}):b.push({role:"user",text:kt}),pt+=ue}for(let kt=wt/1e3;kt>0&&!mt;kt--)yield{type:"status",content:`Error Occured. Recovering Stream (${Xe}/${on}) [Retrying in ${kt.toFixed(0)}s]...`},await new Promise(St=>setTimeout(St,1e3));yield{type:"status",content:"Error Occured. Recovering Stream..."}}else throw new Error(`Stream collapsed too many times. (Failed to resolve ${on} times)
817
+ Error log can be found in \`/export logs\``);else if(je<=on){je++,Xe=1,pt="";let wt=Math.min(1e3*Math.pow(2,je-1),32e3),kt=.8+Math.random()*.4,St=Math.round(wt*kt);Rn=!0,yield{type:"status",content:`Trying to reach ${e} (${je}/${on}) [Retrying in ${(St/1e3).toFixed(0)}s]`};for(let Yt=St/1e3;Yt>0&&!mt;Yt--)yield{type:"status",content:`Trying to reach ${e} (${je}/${on}) [Retrying in ${Yt.toFixed(0)}s]`},await new Promise(En=>setTimeout(En,1e3));yield{type:"status",content:`Trying to reach ${e}`}}else throw new Error(`Model ${e} cannot be reached. (Failed ${on} times)
818
+ Error log can be found in \`/export logs\``)}}if(Jt){let ee=Jt.totalTokenCount||0,ne=Jt.cachedContentTokenCount||0,B=(Jt.candidatesTokenCount||0)+(s==="Google"&&Jt.thoughtsTokenCount||0);await gt("tokens",ee,s,Z),ne>0&&await gt("cachedTokens",ne,s,Z),B>0&&await gt("candidateTokens",B,s,Z),Ce!==null&&Ce>0&&await gt("ttft",Ce,s,Z),mo({provider:s,model:Z,prompt:Jt.promptTokenCount||0,cached:ne,output:B,reasoning:Jt.thoughtsTokenCount||0,ttft:Ce}),yield{type:"usage",content:Jt}}else Ce!==null&&Ce>0&&(await gt("ttft",Ce,s,Z),mo({provider:s,model:Z,prompt:0,cached:0,output:0,reasoning:0,ttft:Ce}));ue=$r(ue),li.push(ue);let Ka=Lt(ue),ci=Or(ue),jr=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(ci.toLowerCase())||/\[\[END\]\]/i.test(ci.toLowerCase())||!0,Ya=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(ci.toLowerCase()),za=ht>0;yield{type:"status",content:"Thinking"};let Vr=Ga(ue,/(\[\s*(turn\s*:)?\s*(continue|finish)\s*\]|\[\[END\]\])/gi,"").trim(),Dn=(jr||Ne.length===0)&&!_t&&!Nn&&!Ft;if(Dn=Ne.length===0?Dn:!1,Dn=Kt||Po?!1:Dn,ue&&ue.trim().endsWith('")]')&&Ne.length===0&&(Dn=!1),Dn){is=!0;let ee=li.join(`
819
819
  `),ne=Lt(ee).trim();yield{type:"interactive_turn_finished",data:{agentText:Me,fullAgentTextRaw:ee,history:[...b],needTitle:we}},b.length>0&&b[b.length-1].role==="agent"?b[b.length-1].text=ne:b.push({role:"agent",text:ne}),b.forEach(B=>{if(B.role==="user"&&B.text&&(B.text=B.text.replace(/\n\[COMPILE ERROR\][\s\S]*?\[\/ERROR\]/g,""),B.text=B.text.replaceAll(`
820
820
 
821
821
  [system] user question. resolve this specific query within '[ANSWER] ... [/ANSWER]' concisely, naturally [/system]
@@ -831,25 +831,25 @@ Error log can be found in \`/export logs\``)}}if(Qt){let ee=Qt.totalTokenCount||
831
831
  [system] Only ${Ne.length} out of ${xt} attempted tool calls were executed.
832
832
  ${Bt?`Parsing Issues Detected:
833
833
  ${Bt}
834
- `:""}Verify proper structure compliance [action:ActionName(arg="value")] & try failed calls again [/system]`;let De=xt-Ne.length;for(let wt=0;wt<De;wt++)await Et("toolFailure")}let bt=Ne.find(Bt=>Bt.binaryPart)?.binaryPart||null;b.push({role:"user",text:ee,binaryPart:bt})}}else if(!mt){let ee=ue.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/i,""),ne=(ee.match(/\[(?:tool|action):/gi)||[]).length;if(Io||Kt||ne>0){let B=Pr(ee),yt=B?`[system] Failed to execute ${ne>0?ne:1} tool call${ne>1?"s":""} due to syntax/structure issues:
834
+ `:""}Verify proper structure compliance [action:ActionName(arg="value")] & try failed calls again [/system]`;let De=xt-Ne.length;for(let wt=0;wt<De;wt++)await Et("toolFailure")}let bt=Ne.find(Bt=>Bt.binaryPart)?.binaryPart||null;b.push({role:"user",text:ee,binaryPart:bt})}}else if(!mt){let ee=ue.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/i,""),ne=(ee.match(/\[(?:tool|action):/gi)||[]).length;if(Po||Kt||ne>0){let B=Pr(ee),yt=B?`[system] Failed to execute ${ne>0?ne:1} tool call${ne>1?"s":""} due to syntax/structure issues:
835
835
  ${B} [/system]`:`[system] Failed to execute ${ne>0?ne:1} tool${ne>1?"s":""}. Verify proper structure compliance [action:ActionName(arg="value")] & try again [/system]`;b.push({role:"user",text:yt}),await Et("toolFailure"),yield{type:"visual_feedback",content:`
836
836
  ${Ht("\u2718 Model produced malformed tool call")}
837
837
  `}}else yield{type:"visual_feedback",content:`
838
838
  ${Ht("\u2718 Loop Detected")}
839
- `},b.push({role:"user",text:`[system] ${Nn&&!_t?"Stuttering Detected by Internal System. Re-calibrate your response & proceed.":`${_t?" Over Thinking":" Loop"} Detected by Internal System${_t?" for current Effort Level":""}. ${_t?"If you have planned the task, prioritize execution/output":"If you have finished your task provide a simple summary and end"}`} [/system]`});_t=!1,Nn=!1,Ft=!1}m?.advanceRollback&&await ho.recordTurnDelta(g,P+1,ze),Io=ht>0||hn}if(!is&&!mt){let P="\u2726 Turn safety limit reached. Stopping execution.";yield{type:"text",content:`
839
+ `},b.push({role:"user",text:`[system] ${Nn&&!_t?"Stuttering Detected by Internal System. Re-calibrate your response & proceed.":`${_t?" Over Thinking":" Loop"} Detected by Internal System${_t?" for current Effort Level":""}. ${_t?"If you have planned the task, prioritize execution/output":"If you have finished your task provide a simple summary and end"}`} [/system]`});_t=!1,Nn=!1,Ft=!1}h?.advanceRollback&&await ho.recordTurnDelta(m,P+1,ze),Po=ht>0||hn}if(!is&&!mt){let P="\u2726 Turn safety limit reached. Stopping execution.";yield{type:"text",content:`
840
840
 
841
841
  ${P}
842
- `};let Be=(ai.join(`
842
+ `};let Be=(li.join(`
843
843
  `)+`
844
- ${P}`).trim();yield{type:"interactive_turn_finished",data:{agentText:Me,fullAgentTextRaw:Be,history:[...b],needTitle:we}},yield{type:"status",content:"[end]"}}}catch(T){let b=T?.cause?` (Cause: ${T.cause?.message||String(T.cause)})`:"",Oe=(T instanceof Error?(()=>{try{return JSON.parse(JSON.parse(T.message).error.message).error.message}catch{return(T.message?`${T.message}${b}`:"")||String(T)}})():String(T)).replace(/^(Error:\s*)+/i,"");s==="Google"&&!/^[A-Z0-9_\-\s]+ ERROR:/i.test(Oe)&&(Oe=`GEMINI ERROR: ${Oe}`);let jt=new Date().toLocaleString(),cn=j.join(qt,"agent");yield{type:"text",content:`
844
+ ${P}`).trim();yield{type:"interactive_turn_finished",data:{agentText:Me,fullAgentTextRaw:Be,history:[...b],needTitle:we}},yield{type:"status",content:"[end]"}}}catch(T){let b=T?.cause?` (Cause: ${T.cause?.message||String(T.cause)})`:"",Oe=(T instanceof Error?(()=>{try{return JSON.parse(JSON.parse(T.message).error.message).error.message}catch{return(T.message?`${T.message}${b}`:"")||String(T)}})():String(T)).replace(/^(Error:\s*)+/i,"");s==="Google"&&!/^[A-Z0-9_\-\s]+ ERROR:/i.test(Oe)&&(Oe=`GEMINI ERROR: ${Oe}`);let jt=new Date().toLocaleString(),cn=W.join(kn,"agent");yield{type:"text",content:`
845
845
 
846
846
  \u2726 CRITICAL ERROR: ${Oe.includes("fetch failed")?"Failed to Connect. Check your Internet Connection or Wait a moment":Oe}
847
- \u2800`},be.existsSync(cn)||be.mkdirSync(cn,{recursive:!0}),be.appendFileSync(j.join(cn,"error.log"),`CRITICAL ERROR [${jt}]: ${T}${T?.cause?`
847
+ \u2800`},be.existsSync(cn)||be.mkdirSync(cn,{recursive:!0}),be.appendFileSync(W.join(cn,"error.log"),`CRITICAL ERROR [${jt}]: ${T}${T?.cause?`
848
848
  CAUSE: ${T.cause?.stack||T.cause}`:""}
849
849
 
850
850
  ----------------------------------------------------------------------
851
851
 
852
- `),typeof flushGoogleBuffer=="function"&&(yield*flushGoogleBuffer()),yield{type:"tool_result",content:`ERROR: [INTERNAL CRITICAL] ${Oe}`}}finally{ye&&(clearInterval(ye),ye=null),typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),await No.commitTransaction(),m?.advanceRollback&&await ho.cleanup(g),await jn()}yield{type:"status",content:null}},ed=async(e,n,t=null,i=null,o=50,r=null,c=!1)=>{let a=await go(),h={...a,...n},g=process.env.SUBAGENT_MODEL?process.env.SUBAGENT_MODEL.trim():null,y=process.env.SUBAGENT_PROVIDER?process.env.SUBAGENT_PROVIDER.trim():null,m=new Date,f=`${m.getFullYear()}-${m.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(m.getDate()).padStart(2,"0")}, ${m.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}).replace(":","-")}`,u=(ye=>{if(!ye)return null;let T=ye.toLowerCase();return T==="google"?"Google":T==="deepseek"?"DeepSeek":T==="openrouter"?"OpenRouter":T==="nvidia"?"NVIDIA":T==="mistral"?"Mistral":T==="ollama"?"Ollama":T==="inferx"?"InferX":T==="sensenova"?"SenseNova":T==="poolside"?"Poolside":T==="9router"||T==="9Router"?"9router":T==="aihubmix"||T==="aihub"?"AIHubMix":T==="explabs"||T==="experientiallabs"||T==="experimentallabs"?"ExpLabs":T==="tokenharbor"||T==="token harbor"||T==="token_harbor"||T==="thk"?"TokenHarbor":T==="infron"?"Infron":T==="apinex"||T==="apx"?"APInex":T==="c_openai"||T==="custom_openai"||T==="custom (openai)"||T==="custom"?"c_openai":null})(y),k=h?.systemSettings?.CustomSubAgent?h?.systemSettings?.SubAgentModel:null,he=h?.systemSettings?.CustomSubAgent?h?.systemSettings?.SubAgentProvider:null,x=null;if(k==="ENV"?(x=g,g&&u&&(h.aiProvider=u)):k&&k!=="Default"?(x=k,he&&(h.aiProvider=he)):g&&u&&(h.aiProvider=u),h.aiProvider){let ye=await pi(h.aiProvider);ye&&(h.apiKey=ye)}let I=ye=>{if(!ye||typeof ye!="string")return{allowed:!0};let T=[/rm\s+-[rf]{1,2}\s+[\/*.]/i,/rmdir\s+\/[sq]/i,/del\s+\/[fsq]/i,/\bformat\b\s+[a-z]:/i,/mkfs/i,/dd\s+if=/i,/\b(shutdown|reboot|poweroff|init\s+0|init\s+6)\b/i,/chmod\s+(-R\s+)?777\s+[\/*.]/i,/chown\s+(-R\s+)?root/i,/git\s+push\s+.*--force/i,/git\s+clean\s+-fdx/i,/\bsudo\s+su\b/i,/\bsu\s+-\b/i];for(let b of T)if(b.test(ye))return{allowed:!1,reason:`Blocked potentially destructive or unsafe command pattern: "${b.source}"`};return{allowed:!0}},G=t||x||n?.modelName||n?.activeModel||a.activeModel,q=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",D=`-- ACTIONS (path = relative to CWD, path separator: '/') --
852
+ `),typeof flushGoogleBuffer=="function"&&(yield*flushGoogleBuffer()),yield{type:"tool_result",content:`ERROR: [INTERNAL CRITICAL] ${Oe}`}}finally{ye&&(clearInterval(ye),ye=null),typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),await Bo.commitTransaction(),h?.advanceRollback&&await ho.cleanup(m),await jn()}yield{type:"status",content:null}},ed=async(e,n,t=null,i=null,o=50,r=null,c=!1)=>{let a=await go(),g={...a,...n},m=process.env.SUBAGENT_MODEL?process.env.SUBAGENT_MODEL.trim():null,y=process.env.SUBAGENT_PROVIDER?process.env.SUBAGENT_PROVIDER.trim():null,h=new Date,f=`${h.getFullYear()}-${h.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(h.getDate()).padStart(2,"0")}, ${h.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}).replace(":","-")}`,u=(ye=>{if(!ye)return null;let T=ye.toLowerCase();return T==="google"?"Google":T==="deepseek"?"DeepSeek":T==="openrouter"?"OpenRouter":T==="nvidia"?"NVIDIA":T==="mistral"?"Mistral":T==="ollama"?"Ollama":T==="inferx"?"InferX":T==="sensenova"?"SenseNova":T==="poolside"?"Poolside":T==="9router"||T==="9Router"?"9router":T==="aihubmix"||T==="aihub"?"AIHubMix":T==="explabs"||T==="experientiallabs"||T==="experimentallabs"?"ExpLabs":T==="tokenharbor"||T==="token harbor"||T==="token_harbor"||T==="thk"?"TokenHarbor":T==="infron"?"Infron":T==="apinex"||T==="apx"?"APInex":T==="c_openai"||T==="custom_openai"||T==="custom (openai)"||T==="custom"?"c_openai":null})(y),k=g?.systemSettings?.CustomSubAgent?g?.systemSettings?.SubAgentModel:null,he=g?.systemSettings?.CustomSubAgent?g?.systemSettings?.SubAgentProvider:null,x=null;if(k==="ENV"?(x=m,m&&u&&(g.aiProvider=u)):k&&k!=="Default"?(x=k,he&&(g.aiProvider=he)):m&&u&&(g.aiProvider=u),g.aiProvider){let ye=await yi(g.aiProvider);ye&&(g.apiKey=ye)}let I=ye=>{if(!ye||typeof ye!="string")return{allowed:!0};let T=[/rm\s+-[rf]{1,2}\s+[\/*.]/i,/rmdir\s+\/[sq]/i,/del\s+\/[fsq]/i,/\bformat\b\s+[a-z]:/i,/mkfs/i,/dd\s+if=/i,/\b(shutdown|reboot|poweroff|init\s+0|init\s+6)\b/i,/chmod\s+(-R\s+)?777\s+[\/*.]/i,/chown\s+(-R\s+)?root/i,/git\s+push\s+.*--force/i,/git\s+clean\s+-fdx/i,/\bsudo\s+su\b/i,/\bsu\s+-\b/i];for(let b of T)if(b.test(ye))return{allowed:!1,reason:`Blocked potentially destructive or unsafe command pattern: "${b.source}"`};return{allowed:!0}},H=t||x||n?.modelName||n?.activeModel||a.activeModel,q=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",D=`-- ACTIONS (path = relative to CWD, path separator: '/') --
853
853
  In chat output the format \`[action:ActionName(arg1="value1")]\` in NEW line
854
854
  Rules:
855
855
  - JSON escape literal sequences, backslash: \\\\, newLine: \\ n
@@ -887,9 +887,9 @@ Main focus: actions and task, not chatting
887
887
  On completion, provide a detailed summary in Tables/Markdown Format with file modified info. If any task failed report back in detail
888
888
 
889
889
  Current Time: ${f}
890
- === END SYSTEM PROMPT ===`,ge=[{role:"user",text:`Complete this task: ${e}`}],we=0,Me="";for(;we<o;){let ye=await yi("subagent",h);if(!ye.allowed)throw new Error(ye.reason||`Budget Exhausted for Provider (${h?.aiProvider||"Subagent"})`);if(mt){if(n?.taskId&&typeof Gt<"u"){let S=Gt.find(R=>R.id===n.taskId);S&&(S.status="cancelled")}throw r&&r("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}if(n?.taskId&&typeof Gt<"u"){let S=Gt.find(R=>R.id===n.taskId);if(S&&S.status==="cancelled")throw r&&r("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}let T=ge.map(S=>({role:S.role==="user"?"user":"model",parts:[{text:S.text}]}));r&&r(`[Subagent Turn ${we+1}]...`);let b=["Fast","Low","Medium","High"],rt=process.env.SUBAGENT_THINKING,Oe=b.includes(rt)?rt:"Low",cn=(await ni(h,G,T,A,Oe)).text||"",$t=$r(Lt(cn).trim());Me=$t,r&&r(`[Subagent Response]
890
+ === END SYSTEM PROMPT ===`,ge=[{role:"user",text:`Complete this task: ${e}`}],we=0,Me="";for(;we<o;){let ye=await xi("subagent",g);if(!ye.allowed)throw new Error(ye.reason||`Budget Exhausted for Provider (${g?.aiProvider||"Subagent"})`);if(mt){if(n?.taskId&&typeof Gt<"u"){let S=Gt.find(R=>R.id===n.taskId);S&&(S.status="cancelled")}throw r&&r("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}if(n?.taskId&&typeof Gt<"u"){let S=Gt.find(R=>R.id===n.taskId);if(S&&S.status==="cancelled")throw r&&r("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}let T=ge.map(S=>({role:S.role==="user"?"user":"model",parts:[{text:S.text}]}));r&&r(`[Subagent Turn ${we+1}]...`);let b=["Fast","Low","Medium","High"],rt=process.env.SUBAGENT_THINKING,Oe=b.includes(rt)?rt:"Low",cn=(await oi(g,H,T,A,Oe)).text||"",$t=$r(Lt(cn).trim());Me=$t,r&&r(`[Subagent Response]
891
891
  ${$t}
892
- `),ge.push({role:"agent",text:$t});let Xt=to($t);if(Xt.length===0)break;let dn=Xt.filter(S=>S.toolName.toLowerCase()==="askmain"||S.toolName.toLowerCase()==="ask_main"),fn=!1,Nt="";for(let S of Xt){if(mt){if(n?.taskId&&typeof Gt<"u"){let C=Gt.find(N=>N.id===n.taskId);C&&(C.status="cancelled")}throw new Error("Subagent task was cancelled.")}if(n?.taskId&&typeof Gt<"u"){let C=Gt.find(N=>N.id===n.taskId);if(C&&C.status==="cancelled")throw new Error("Subagent task was cancelled.")}let R=S.toolName.toLowerCase();if(R==="askuser"&&(R="ask"),R==="askmain"||R==="ask_main"){if(fn)continue;fn=!0;let C="";if(dn.length===1?C=W(dn[0].args).question||dn[0].args:C=dn.map((N,Se)=>{let ve=W(N.args);return`Q${Se+1}: ${ve.question||N.args}`}).join(`
892
+ `),ge.push({role:"agent",text:$t});let qt=to($t);if(qt.length===0)break;let dn=qt.filter(S=>S.toolName.toLowerCase()==="askmain"||S.toolName.toLowerCase()==="ask_main"),fn=!1,Nt="";for(let S of qt){if(mt){if(n?.taskId&&typeof Gt<"u"){let C=Gt.find(N=>N.id===n.taskId);C&&(C.status="cancelled")}throw new Error("Subagent task was cancelled.")}if(n?.taskId&&typeof Gt<"u"){let C=Gt.find(N=>N.id===n.taskId);if(C&&C.status==="cancelled")throw new Error("Subagent task was cancelled.")}let R=S.toolName.toLowerCase();if(R==="askuser"&&(R="ask"),R==="askmain"||R==="ask_main"){if(fn)continue;fn=!0;let C="";if(dn.length===1?C=G(dn[0].args).question||dn[0].args:C=dn.map((N,Se)=>{let ve=G(N.args);return`Q${Se+1}: ${ve.question||N.args}`}).join(`
893
893
  `),n.onAskMain){r&&r(`[Executing Tool] AskMain("${C}")...`);let N=await n.onAskMain(C);r&&r(`[Action Result]
894
894
  Answer from Main Agent: ${N}
895
895
  `),Nt+=`[ACTION RESULT for AskMain]: Answer from Main Agent: ${N}
@@ -899,10 +899,10 @@ Answer from Main Agent: ${N}
899
899
  `;continue}if(!(i?i.some(C=>C.toLowerCase()===R):!0)){let C=`ERROR: Tool [${S.toolName}] is not in the allowed tools list for this subagent.`;r&&r(`[Blocked Tool Call] ${S.toolName} - not allowed
900
900
  `),Nt+=`${C}
901
901
 
902
- `;continue}if(R==="exec_command"||R==="execcommand"||R==="run"){let C=W(S.args).command||"",N=I(C);if(!N.allowed){let Se=`ERROR: [SECURITY RESTRICTION] Subagent execution blocked command: ${N.reason}`;r&&r(`[Blocked Command] ${C} - ${N.reason}
902
+ `;continue}if(R==="exec_command"||R==="execcommand"||R==="run"){let C=G(S.args).command||"",N=I(C);if(!N.allowed){let Se=`ERROR: [SECURITY RESTRICTION] Subagent execution blocked command: ${N.reason}`;r&&r(`[Blocked Command] ${C} - ${N.reason}
903
903
  `),Nt+=`${Se}
904
904
 
905
- `;continue}}let ae="";if(R==="web_search"||R==="websearch")ae=`\u2714 \x1B[95mSearched\x1B[0m: ${W(S.args).query||""}`;else if(R==="web_scrape"||R==="webscrape")ae=`\u2714 \x1B[95mScraped\x1B[0m: ${W(S.args).url||""}`;else if(R==="search_keyword"||R==="searchkeyword"||R==="codesearch"||R==="code_search"){let C=W(S.args),N=C.keyword||"",Se=C.path||"";ae=`${N?"\u2714":"\u2718"} \x1B[95mSearched\x1B[0m: ${N||"No Query"}${Se?` \u2192 ${Se.replaceAll("\\","/")}`:""}`}else if(R==="view_file"||R==="viewfile"||R==="readfile")ae=`\u2714 \x1B[95mRead\x1B[0m: ${(W(S.args).path||"").replaceAll("\\","/")}`;else if(R==="find_file"||R==="findfile"){let C=W(S.args),N=C.basename||C.name||C.path||C.file||C.query||"";ae=`${N?"\u2714":"\u2718"} \x1B[95mLocated\x1B[0m: ${N||"No Query"}`}else if(R==="list_files"||R==="read_folder"||R==="readfolder"){let C=W(S.args).path||null,N=W(S.args).recurse||0;ae=`${C?"\u2714":"\u2718"} \x1B[95mBrowsed\x1B[0m: ${C?`${C.replaceAll("\\","/")}${N>0?`${C.endsWith("/")?`*${N}`:`/*${N}`}`:`${C.endsWith("/")?"":"/"}`}`:""}`}else if(R==="write_file"||R==="writefile"){let C=W(S.args).path||null;ae=`${C?"\u2714":"\u2718"} \x1B[95mCreated\x1B[0m: ${C?`${C.replaceAll("\\","/")}`:"No File Changes"}`}else if(R==="update_file"||R==="updatefile"||R==="patchfile"||R==="patch_file"){let C=W(S.args),N=C.path||null,ve=Object.entries(C).some(([ke,Pe])=>ke.startsWith("searchContent")&&typeof Pe=="string"&&Pe.startsWith("^LINE:"))?"\u1361":":";ae=`${N?"\u2714":"\u2718"} \x1B[95mEdited\x1B[0m${ve} ${N?`${N.replaceAll("\\","/")}`:"No File Changes"}`}else if(R==="exec_command"||R==="execcommand"||R==="run"){let C=W(S.args).command||null;ae=`${C?"\u2714":"\u2718"} \x1B[95mExecuted\x1B[0m: ${C?C.slice(0,100)+(C.length>100?"...":""):"No Command"}`}else if(R==="file_map"||R==="filemap"){let C=W(S.args).path||"";ae=`${C?"\u2714":"\u2718"} \x1B[95mIndexed\x1B[0m: ${C?`${C.replaceAll("\\","/")}`:"File Not Found"}`}else if(R==="await"){let{time:C}=W(S.args),N=parseFloat(C)||0;N<10&&(N=10),N>180&&(N=180),ae=`\u2714 \x1B[95mAwaiting\x1B[0m \u2192 ${(ve=>{if(ve>=60){let ke=Math.floor(ve/60),Pe=ve%60;return`${ke}m${Pe>0?` ${Pe}s`:""}`}return`${ve}s`})(N)}`}else{let C=zi[R]||S.toolName,N=Kn(R,S.args);ae=`\u2714 \x1B[95m${C}\x1B[0m${N?`: ${N}`:""}`}n.onVisualFeedback&&ae&&n.onVisualFeedback(ae),r&&r(`[Executing Tool] ${S.toolName}(${S.args})...`);try{let C=await ko(S.toolName,S.args,{...n,mode:"Flux"});if(r&&r(`[Action Result]
905
+ `;continue}}let ae="";if(R==="web_search"||R==="websearch")ae=`\u2714 \x1B[95mSearched\x1B[0m: ${G(S.args).query||""}`;else if(R==="web_scrape"||R==="webscrape")ae=`\u2714 \x1B[95mScraped\x1B[0m: ${G(S.args).url||""}`;else if(R==="search_keyword"||R==="searchkeyword"||R==="codesearch"||R==="code_search"){let C=G(S.args),N=C.keyword||"",Se=C.path||"";ae=`${N?"\u2714":"\u2718"} \x1B[95mSearched\x1B[0m: ${N||"No Query"}${Se?` \u2192 ${Se.replaceAll("\\","/")}`:""}`}else if(R==="view_file"||R==="viewfile"||R==="readfile")ae=`\u2714 \x1B[95mRead\x1B[0m: ${(G(S.args).path||"").replaceAll("\\","/")}`;else if(R==="find_file"||R==="findfile"){let C=G(S.args),N=C.basename||C.name||C.path||C.file||C.query||"";ae=`${N?"\u2714":"\u2718"} \x1B[95mLocated\x1B[0m: ${N||"No Query"}`}else if(R==="list_files"||R==="read_folder"||R==="readfolder"){let C=G(S.args).path||null,N=G(S.args).recurse||0;ae=`${C?"\u2714":"\u2718"} \x1B[95mBrowsed\x1B[0m: ${C?`${C.replaceAll("\\","/")}${N>0?`${C.endsWith("/")?`*${N}`:`/*${N}`}`:`${C.endsWith("/")?"":"/"}`}`:""}`}else if(R==="write_file"||R==="writefile"){let C=G(S.args).path||null;ae=`${C?"\u2714":"\u2718"} \x1B[95mCreated\x1B[0m: ${C?`${C.replaceAll("\\","/")}`:"No File Changes"}`}else if(R==="update_file"||R==="updatefile"||R==="patchfile"||R==="patch_file"){let C=G(S.args),N=C.path||null,ve=Object.entries(C).some(([ke,Pe])=>ke.startsWith("searchContent")&&typeof Pe=="string"&&Pe.startsWith("^LINE:"))?"\u1361":":";ae=`${N?"\u2714":"\u2718"} \x1B[95mEdited\x1B[0m${ve} ${N?`${N.replaceAll("\\","/")}`:"No File Changes"}`}else if(R==="exec_command"||R==="execcommand"||R==="run"){let C=G(S.args).command||null;ae=`${C?"\u2714":"\u2718"} \x1B[95mExecuted\x1B[0m: ${C?C.slice(0,100)+(C.length>100?"...":""):"No Command"}`}else if(R==="file_map"||R==="filemap"){let C=G(S.args).path||"";ae=`${C?"\u2714":"\u2718"} \x1B[95mIndexed\x1B[0m: ${C?`${C.replaceAll("\\","/")}`:"File Not Found"}`}else if(R==="await"){let{time:C}=G(S.args),N=parseFloat(C)||0;N<10&&(N=10),N>180&&(N=180),ae=`\u2714 \x1B[95mAwaiting\x1B[0m \u2192 ${(ve=>{if(ve>=60){let ke=Math.floor(ve/60),Pe=ve%60;return`${ke}m${Pe>0?` ${Pe}s`:""}`}return`${ve}s`})(N)}`}else{let C=zi[R]||S.toolName,N=Kn(R,S.args);ae=`\u2714 \x1B[95m${C}\x1B[0m${N?`: ${N}`:""}`}n.onVisualFeedback&&ae&&n.onVisualFeedback(ae),r&&r(`[Executing Tool] ${S.toolName}(${S.args})...`);try{let C=await Ro(S.toolName,S.args,{...n,mode:"Flux"});if(r&&r(`[Action Result]
906
906
  ${C}
907
907
  `),Nt+=`[ACTION RESULT for ${S.toolName}]: ${C}
908
908
 
@@ -913,4 +913,4 @@ ${C}
913
913
 
914
914
  `,await Et("toolFailure")}}let pe="";if(n?.taskId&&typeof Gt<"u"){let S=Gt.find(R=>R.id===n.taskId);if(S&&S.pendingSteerMessages&&S.pendingSteerMessages.length>0){let R=[...S.pendingSteerMessages];S.pendingSteerMessages=[];for(let Fe of R)pe+=`
915
915
 
916
- [STEERING INSTRUCTION FROM MAIN AGENT]: ${Fe}`,r&&r(`[Subagent Steered] ${Fe}`)}}let Jt=(Nt.trim()+pe).trim();ge.push({role:"user",text:Jt}),we++}return Me};export{Ao as a,kr as b,nc as c,oc as d,jl as e,Vl as f,rc as g,Zo as h,ac as i,Pa as j,Kc as k,La as l,$a as m,Yi as n,Lt as o,ei as p,$r as q,Ba as r,Yc as s,zc as t,Xi as u,qc as v,Xc as w,ni as x,Jc as y,Qc as z,Zc as A,ed as B};
916
+ [STEERING INSTRUCTION FROM MAIN AGENT]: ${Fe}`,r&&r(`[Subagent Steered] ${Fe}`)}}let Xt=(Nt.trim()+pe).trim();ge.push({role:"user",text:Xt}),we++}return Me};export{Eo as a,kr as b,nc as c,oc as d,jl as e,Vl as f,rc as g,ei as h,ac as i,Pa as j,Kc as k,La as l,$a as m,Yi as n,Lt as o,ti as p,$r as q,Ba as r,Yc as s,zc as t,Xi as u,qc as v,Xc as w,oi as x,Jc as y,Qc as z,Zc as A,ed as B};